first commit

This commit is contained in:
Artem Anufrij
2026-10-07 18:56:27 +02:00
commit 2a8a60b725
7768 changed files with 1550851 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-present vuejs
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.
+5
View File
@@ -0,0 +1,5 @@
# @vue/babel-helper-vue-transform-on
A package used internally by vue jsx transformer to transform events.
on: { click: xx } --> onClick: xx
+4
View File
@@ -0,0 +1,4 @@
declare function transformOn(
obj: Record<string, any>
): Record<`on${string}`, any>;
export = transformOn;
+9
View File
@@ -0,0 +1,9 @@
const transformOn = (obj) => {
const result = {};
Object.keys(obj).forEach((evt) => {
result[`on${evt[0].toUpperCase()}${evt.slice(1)}`] = obj[evt];
});
return result;
};
module.exports = transformOn;
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@vue/babel-helper-vue-transform-on",
"version": "1.5.0",
"type": "commonjs",
"description": "to help transform on",
"author": "Amour1688 <lcz_1996@foxmail.com>",
"license": "MIT",
"main": "index.js",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/babel-plugin-jsx.git"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-present vuejs
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.
+390
View File
@@ -0,0 +1,390 @@
# Babel Plugin JSX for Vue 3
[![npm package](https://img.shields.io/npm/v/@vue/babel-plugin-jsx.svg?style=flat-square)](https://www.npmjs.com/package/@vue/babel-plugin-jsx)
[![issues-helper](https://img.shields.io/badge/Issues%20Manage%20By-issues--helper-blueviolet?style=flat-square)](https://github.com/actions-cool/issues-helper)
To add Vue JSX support.
English | [简体中文](/packages/babel-plugin-jsx/README-zh_CN.md)
## Installation
Install the plugin with:
```bash
npm install @vue/babel-plugin-jsx -D
```
Then add the plugin to your babel config:
```json
{
"plugins": ["@vue/babel-plugin-jsx"]
}
```
## Usage
### options
#### transformOn
Type: `boolean`
Default: `false`
transform `on: { click: xx }` to `onClick: xxx`
#### optimize
Type: `boolean`
Default: `false`
When enabled, this plugin generates optimized runtime code using [`PatchFlags`](https://vuejs.org/guide/extras/rendering-mechanism#patch-flags) and [`SlotFlags`](https://github.com/vuejs/core/blob/v3.5.13/packages/runtime-core/src/componentSlots.ts#L69-L77) to improve rendering performance. However, due to JSX's dynamic nature, the optimizations are not as comprehensive as those in Vue's official template compiler.
Since the optimized code may skip certain re-renders to improve performance, we strongly recommend thorough testing of your application after enabling this option to ensure everything works as expected.
#### isCustomElement
Type: `(tag: string) => boolean`
Default: `undefined`
configuring custom elements
#### mergeProps
Type: `boolean`
Default: `true`
merge static and dynamic class / style attributes / onXXX handlers
#### enableObjectSlots
Type: `boolean`
Default: `true`
Whether to enable `object slots` (mentioned below the document) syntax". It might be useful in JSX, but it will add a lot of `_isSlot` condition expressions which increase your bundle size. And `v-slots` is still available even if `enableObjectSlots` is turned off.
#### pragma
Type: `string`
Default: `createVNode`
Replace the function used when compiling JSX expressions.
#### resolveType
Type: `boolean`
Default: `false`
(**Experimental**) Infer component metadata from types (e.g. `props`, `emits`, `name`). This is an experimental feature and may not work in all cases.
## Syntax
### Content
functional component
```jsx
const App = () => <div>Vue 3.0</div>;
```
with render
```jsx
const App = {
render() {
return <div>Vue 3.0</div>;
},
};
```
```jsx
import { withModifiers, defineComponent } from 'vue';
const App = defineComponent({
setup() {
const count = ref(0);
const inc = () => {
count.value++;
};
return () => (
<div onClick={withModifiers(inc, ['self'])}>{count.value}</div>
);
},
});
```
Fragment
```jsx
const App = () => (
<>
<span>I'm</span>
<span>Fragment</span>
</>
);
```
### Attributes / Props
```jsx
const App = () => <input type="email" />;
```
with a dynamic binding:
```jsx
const placeholderText = 'email';
const App = () => <input type="email" placeholder={placeholderText} />;
```
### Directives
#### v-show
```jsx
const App = {
data() {
return { visible: true };
},
render() {
return <input v-show={this.visible} />;
},
};
```
#### v-model
> Note: You should pass the second param as string for using `arg`.
```jsx
<input v-model={val} />
```
```jsx
<input v-model:argument={val} />
```
```jsx
<input v-model={[val, ['modifier']]} />
// Or
<input v-model_modifier={val} />
```
```jsx
<A v-model={[val, 'argument', ['modifier']]} />
// Or
<input v-model:argument_modifier={val} />
```
Will compile to:
```js
h(A, {
argument: val,
argumentModifiers: {
modifier: true,
},
'onUpdate:argument': ($event) => (val = $event),
});
```
#### v-models (Not recommended since v1.1.0)
> Note: You should pass a Two-dimensional Arrays to v-models.
```jsx
<A v-models={[[foo], [bar, 'bar']]} />
```
```jsx
<A
v-models={[
[foo, 'foo'],
[bar, 'bar'],
]}
/>
```
```jsx
<A
v-models={[
[foo, ['modifier']],
[bar, 'bar', ['modifier']],
]}
/>
```
Will compile to:
```js
h(A, {
modelValue: foo,
modelModifiers: {
modifier: true,
},
'onUpdate:modelValue': ($event) => (foo = $event),
bar: bar,
barModifiers: {
modifier: true,
},
'onUpdate:bar': ($event) => (bar = $event),
});
```
#### custom directive
Recommended when using string arguments
```jsx
const App = {
directives: { custom: customDirective },
setup() {
return () => <a v-custom:arg={val} />;
},
};
```
```jsx
const App = {
directives: { custom: customDirective },
setup() {
return () => <a v-custom={[val, 'arg', ['a', 'b']]} />;
},
};
```
### Slot
> Note: In `jsx`, _`v-slot`_ should be replaced with **`v-slots`**
```jsx
const A = (props, { slots }) => (
<>
<h1>{slots.default ? slots.default() : 'foo'}</h1>
<h2>{slots.bar?.()}</h2>
</>
);
const App = {
setup() {
const slots = {
bar: () => <span>B</span>,
};
return () => (
<A v-slots={slots}>
<div>A</div>
</A>
);
},
};
// or
const App = {
setup() {
const slots = {
default: () => <div>A</div>,
bar: () => <span>B</span>,
};
return () => <A v-slots={slots} />;
},
};
// or you can use object slots when `enableObjectSlots` is not false.
const App = {
setup() {
return () => (
<>
<A>
{{
default: () => <div>A</div>,
bar: () => <span>B</span>,
}}
</A>
<B>{() => 'foo'}</B>
</>
);
},
};
```
### In TypeScript
`tsconfig.json`:
```json
{
"compilerOptions": {
"jsx": "preserve"
}
}
```
## Who is using
<table>
<tbody>
<tr>
<td align="center">
<a target="_blank" href="https://www.antdv.com/">
<img
width="32"
src="https://github.com/vuejs/babel-plugin-jsx/assets/6481596/8d604d42-fe5f-4450-af87-97999537cd21"
/>
<br>
<strong>Ant Design Vue</strong>
</a>
</td>
<td align="center">
<a target="_blank" href="https://youzan.github.io/vant/#/zh-CN/">
<img
width="32"
style="vertical-align: -0.32em; margin-right: 8px;"
src="https://img.yzcdn.cn/vant/logo.png"
/>
<br>
<strong>Vant</strong>
</a>
</td>
<td align="center">
<a target="_blank" href="https://github.com/element-plus/element-plus">
<img
height="32"
style="vertical-align: -0.32em; margin-right: 8px;"
src="https://user-images.githubusercontent.com/10731096/91267529-259f3680-e7a6-11ea-9a60-3286f750de01.png"
/>
<br>
<strong>Element Plus</strong>
</a>
</td>
<td align="center">
<a target="_blank" href="https://github.com/leezng/vue-json-pretty">
<img
height="32"
style="vertical-align: -0.32em; margin-right: 8px;"
src="https://raw.githubusercontent.com/leezng/vue-json-pretty/master/static/logo.svg"
/>
<br>
<strong>Vue Json Pretty</strong>
</a>
</td>
</tr>
</tbody>
</table>
## Compatibility
This repo is only compatible with:
- **Babel 7+**
- **Vue 3+**
+35
View File
@@ -0,0 +1,35 @@
import "@babel/types";
import { Options } from "@vue/babel-plugin-resolve-type";
import * as BabelCore from "@babel/core";
//#region src/interface.d.ts
type State = {
get: (name: string) => any;
set: (name: string, value: any) => any;
opts: VueJSXPluginOptions;
file: BabelCore.BabelFile;
};
interface VueJSXPluginOptions {
/** transform `on: { click: xx }` to `onClick: xxx` */
transformOn?: boolean;
/** enable optimization or not. */
optimize?: boolean;
/** merge static and dynamic class / style attributes / onXXX handlers */
mergeProps?: boolean;
/** configuring custom elements */
isCustomElement?: (tag: string) => boolean;
/** enable object slots syntax */
enableObjectSlots?: boolean;
/** Replace the function used when compiling JSX expressions */
pragma?: string;
/**
* (**Experimental**) Infer component metadata from types (e.g. `props`, `emits`, `name`)
* @default false
*/
resolveType?: Options | boolean;
}
//#endregion
//#region src/index.d.ts
declare const plugin: (api: object, options: VueJSXPluginOptions | null | undefined, dirname: string) => BabelCore.PluginObj<State>;
//#endregion
export { VueJSXPluginOptions, plugin as default };
+34
View File
@@ -0,0 +1,34 @@
import * as BabelCore from "@babel/core";
import { Options } from "@vue/babel-plugin-resolve-type";
//#region src/interface.d.ts
type State = {
get: (name: string) => any;
set: (name: string, value: any) => any;
opts: VueJSXPluginOptions;
file: BabelCore.BabelFile;
};
interface VueJSXPluginOptions {
/** transform `on: { click: xx }` to `onClick: xxx` */
transformOn?: boolean;
/** enable optimization or not. */
optimize?: boolean;
/** merge static and dynamic class / style attributes / onXXX handlers */
mergeProps?: boolean;
/** configuring custom elements */
isCustomElement?: (tag: string) => boolean;
/** enable object slots syntax */
enableObjectSlots?: boolean;
/** Replace the function used when compiling JSX expressions */
pragma?: string;
/**
* (**Experimental**) Infer component metadata from types (e.g. `props`, `emits`, `name`)
* @default false
*/
resolveType?: Options | boolean;
}
//#endregion
//#region src/index.d.ts
declare const plugin: (api: object, options: VueJSXPluginOptions | null | undefined, dirname: string) => BabelCore.PluginObj<State>;
//#endregion
export { VueJSXPluginOptions, plugin as default };
+818
View File
@@ -0,0 +1,818 @@
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
const __babel_types = __toESM(require("@babel/types"));
const __babel_template = __toESM(require("@babel/template"));
const __babel_plugin_syntax_jsx = __toESM(require("@babel/plugin-syntax-jsx"));
const __babel_helper_module_imports = __toESM(require("@babel/helper-module-imports"));
const __vue_babel_plugin_resolve_type = __toESM(require("@vue/babel-plugin-resolve-type"));
const __babel_helper_plugin_utils = __toESM(require("@babel/helper-plugin-utils"));
const __vue_shared = __toESM(require("@vue/shared"));
//#region src/slotFlags.ts
var SlotFlags = /* @__PURE__ */ function(SlotFlags$1) {
/**
* Stable slots that only reference slot props or context state. The slot
* can fully capture its own dependencies so when passed down the parent won't
* need to force the child to update.
*/
SlotFlags$1[SlotFlags$1["STABLE"] = 1] = "STABLE";
/**
* Slots that reference scope variables (v-for or an outer slot prop), or
* has conditional structure (v-if, v-for). The parent will need to force
* the child to update because the slot does not fully capture its dependencies.
*/
SlotFlags$1[SlotFlags$1["DYNAMIC"] = 2] = "DYNAMIC";
/**
* `<slot/>` being forwarded into a child component. Whether the parent needs
* to update the child is dependent on what kind of slots the parent itself
* received. This has to be refined at runtime, when the child's vnode
* is being created (in `normalizeChildren`)
*/
SlotFlags$1[SlotFlags$1["FORWARDED"] = 3] = "FORWARDED";
return SlotFlags$1;
}(SlotFlags || {});
var slotFlags_default = SlotFlags;
//#endregion
//#region src/utils.ts
const FRAGMENT = "Fragment";
const KEEP_ALIVE = "KeepAlive";
/**
* create Identifier
* @param path NodePath
* @param state
* @param name string
* @returns MemberExpression
*/
const createIdentifier = (state, name) => state.get(name)();
/**
* Checks if string is describing a directive
* @param src string
*/
const isDirective = (src) => src.startsWith("v-") || src.startsWith("v") && src.length >= 2 && src[1] >= "A" && src[1] <= "Z";
/**
* Should transformed to slots
* @param tag string
* @returns boolean
*/
const shouldTransformedToSlots = (tag) => !(tag.match(RegExp(`^_?${FRAGMENT}\\d*$`)) || tag === KEEP_ALIVE);
/**
* Check if a Node is a component
*
* @param t
* @param path JSXOpeningElement
* @returns boolean
*/
const checkIsComponent = (path, state) => {
var _state$opts$isCustomE, _state$opts;
const namePath = path.get("name");
if (namePath.isJSXMemberExpression()) return shouldTransformedToSlots(namePath.node.property.name);
const tag = namePath.node.name;
return !((_state$opts$isCustomE = (_state$opts = state.opts).isCustomElement) === null || _state$opts$isCustomE === void 0 ? void 0 : _state$opts$isCustomE.call(_state$opts, tag)) && shouldTransformedToSlots(tag) && !(0, __vue_shared.isHTMLTag)(tag) && !(0, __vue_shared.isSVGTag)(tag);
};
/**
* Transform JSXMemberExpression to MemberExpression
* @param path JSXMemberExpression
* @returns MemberExpression
*/
const transformJSXMemberExpression = (path) => {
const objectPath = path.node.object;
const propertyPath = path.node.property;
const transformedObject = __babel_types.isJSXMemberExpression(objectPath) ? transformJSXMemberExpression(path.get("object")) : __babel_types.isJSXIdentifier(objectPath) ? __babel_types.identifier(objectPath.name) : __babel_types.nullLiteral();
const transformedProperty = __babel_types.identifier(propertyPath.name);
return __babel_types.memberExpression(transformedObject, transformedProperty);
};
/**
* Get tag (first attribute for h) from JSXOpeningElement
* @param path JSXElement
* @param state State
* @returns Identifier | StringLiteral | MemberExpression | CallExpression
*/
const getTag = (path, state) => {
const namePath = path.get("openingElement").get("name");
if (namePath.isJSXIdentifier()) {
const { name } = namePath.node;
if (!(0, __vue_shared.isHTMLTag)(name) && !(0, __vue_shared.isSVGTag)(name)) {
var _state$opts$isCustomE2, _state$opts2;
return name === FRAGMENT ? createIdentifier(state, FRAGMENT) : path.scope.hasBinding(name) ? __babel_types.identifier(name) : ((_state$opts$isCustomE2 = (_state$opts2 = state.opts).isCustomElement) === null || _state$opts$isCustomE2 === void 0 ? void 0 : _state$opts$isCustomE2.call(_state$opts2, name)) ? __babel_types.stringLiteral(name) : __babel_types.callExpression(createIdentifier(state, "resolveComponent"), [__babel_types.stringLiteral(name)]);
}
return __babel_types.stringLiteral(name);
}
if (namePath.isJSXMemberExpression()) return transformJSXMemberExpression(namePath);
throw new Error(`getTag: ${namePath.type} is not supported`);
};
const getJSXAttributeName = (path) => {
const nameNode = path.node.name;
if (__babel_types.isJSXIdentifier(nameNode)) return nameNode.name;
return `${nameNode.namespace.name}:${nameNode.name.name}`;
};
/**
* Transform JSXText to StringLiteral
* @param path JSXText
* @returns StringLiteral | null
*/
const transformJSXText = (path) => {
const str = transformText(path.node.value);
return str !== "" ? __babel_types.stringLiteral(str) : null;
};
const transformText = (text) => {
const lines = text.split(/\r\n|\n|\r/);
let lastNonEmptyLine = 0;
for (let i = 0; i < lines.length; i++) if (lines[i].match(/[^ \t]/)) lastNonEmptyLine = i;
let str = "";
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isFirstLine = i === 0;
const isLastLine = i === lines.length - 1;
const isLastNonEmptyLine = i === lastNonEmptyLine;
let trimmedLine = line.replace(/\t/g, " ");
if (!isFirstLine) trimmedLine = trimmedLine.replace(/^[ ]+/, "");
if (!isLastLine) trimmedLine = trimmedLine.replace(/[ ]+$/, "");
if (trimmedLine) {
if (!isLastNonEmptyLine) trimmedLine += " ";
str += trimmedLine;
}
}
return str;
};
/**
* Transform JSXExpressionContainer to Expression
* @param path JSXExpressionContainer
* @returns Expression
*/
const transformJSXExpressionContainer = (path) => path.get("expression").node;
/**
* Transform JSXSpreadChild
* @param path JSXSpreadChild
* @returns SpreadElement
*/
const transformJSXSpreadChild = (path) => __babel_types.spreadElement(path.get("expression").node);
const walksScope = (path, name, slotFlag) => {
if (path.scope.hasBinding(name) && path.parentPath) {
if (__babel_types.isJSXElement(path.parentPath.node)) path.parentPath.setData("slotFlag", slotFlag);
walksScope(path.parentPath, name, slotFlag);
}
};
const buildIIFE = (path, children) => {
const { parentPath } = path;
if (parentPath.isAssignmentExpression()) {
const { left } = parentPath.node;
if (__babel_types.isIdentifier(left)) return children.map((child) => {
if (__babel_types.isIdentifier(child) && child.name === left.name) {
const insertName = path.scope.generateUidIdentifier(child.name);
parentPath.insertBefore(__babel_types.variableDeclaration("const", [__babel_types.variableDeclarator(insertName, __babel_types.callExpression(__babel_types.functionExpression(null, [], __babel_types.blockStatement([__babel_types.returnStatement(child)])), []))]));
return insertName;
}
return child;
});
}
return children;
};
const onRE = /^on[^a-z]/;
const isOn = (key) => onRE.test(key);
const mergeAsArray = (existing, incoming) => {
if (__babel_types.isArrayExpression(existing.value)) existing.value.elements.push(incoming.value);
else existing.value = __babel_types.arrayExpression([existing.value, incoming.value]);
};
const dedupeProperties = (properties = [], mergeProps) => {
if (!mergeProps) return properties;
const knownProps = /* @__PURE__ */ new Map();
const deduped = [];
properties.forEach((prop) => {
if (__babel_types.isStringLiteral(prop.key)) {
const { value: name } = prop.key;
const existing = knownProps.get(name);
if (existing) {
if (name === "style" || name === "class" || name.startsWith("on")) mergeAsArray(existing, prop);
} else {
knownProps.set(name, prop);
deduped.push(prop);
}
} else deduped.push(prop);
});
return deduped;
};
/**
* Check if an attribute value is constant
* @param node
* @returns boolean
*/
const isConstant = (node) => {
if (__babel_types.isIdentifier(node)) return node.name === "undefined";
if (__babel_types.isArrayExpression(node)) {
const { elements } = node;
return elements.every((element) => element && isConstant(element));
}
if (__babel_types.isObjectExpression(node)) return node.properties.every((property) => isConstant(property.value));
if (__babel_types.isTemplateLiteral(node) ? !node.expressions.length : __babel_types.isLiteral(node)) return true;
return false;
};
const transformJSXSpreadAttribute = (nodePath, path, mergeProps, args) => {
const argument = path.get("argument");
const properties = __babel_types.isObjectExpression(argument.node) ? argument.node.properties : void 0;
if (!properties) {
if (argument.isIdentifier()) walksScope(nodePath, argument.node.name, slotFlags_default.DYNAMIC);
args.push(mergeProps ? argument.node : __babel_types.spreadElement(argument.node));
} else if (mergeProps) args.push(__babel_types.objectExpression(properties));
else args.push(...properties);
};
//#endregion
//#region src/patchFlags.ts
let PatchFlags = /* @__PURE__ */ function(PatchFlags$1) {
PatchFlags$1[PatchFlags$1["TEXT"] = 1] = "TEXT";
PatchFlags$1[PatchFlags$1["CLASS"] = 2] = "CLASS";
PatchFlags$1[PatchFlags$1["STYLE"] = 4] = "STYLE";
PatchFlags$1[PatchFlags$1["PROPS"] = 8] = "PROPS";
PatchFlags$1[PatchFlags$1["FULL_PROPS"] = 16] = "FULL_PROPS";
PatchFlags$1[PatchFlags$1["HYDRATE_EVENTS"] = 32] = "HYDRATE_EVENTS";
PatchFlags$1[PatchFlags$1["STABLE_FRAGMENT"] = 64] = "STABLE_FRAGMENT";
PatchFlags$1[PatchFlags$1["KEYED_FRAGMENT"] = 128] = "KEYED_FRAGMENT";
PatchFlags$1[PatchFlags$1["UNKEYED_FRAGMENT"] = 256] = "UNKEYED_FRAGMENT";
PatchFlags$1[PatchFlags$1["NEED_PATCH"] = 512] = "NEED_PATCH";
PatchFlags$1[PatchFlags$1["DYNAMIC_SLOTS"] = 1024] = "DYNAMIC_SLOTS";
PatchFlags$1[PatchFlags$1["HOISTED"] = -1] = "HOISTED";
PatchFlags$1[PatchFlags$1["BAIL"] = -2] = "BAIL";
return PatchFlags$1;
}({});
const PatchFlagNames = {
[PatchFlags.TEXT]: "TEXT",
[PatchFlags.CLASS]: "CLASS",
[PatchFlags.STYLE]: "STYLE",
[PatchFlags.PROPS]: "PROPS",
[PatchFlags.FULL_PROPS]: "FULL_PROPS",
[PatchFlags.HYDRATE_EVENTS]: "HYDRATE_EVENTS",
[PatchFlags.STABLE_FRAGMENT]: "STABLE_FRAGMENT",
[PatchFlags.KEYED_FRAGMENT]: "KEYED_FRAGMENT",
[PatchFlags.UNKEYED_FRAGMENT]: "UNKEYED_FRAGMENT",
[PatchFlags.DYNAMIC_SLOTS]: "DYNAMIC_SLOTS",
[PatchFlags.NEED_PATCH]: "NEED_PATCH",
[PatchFlags.HOISTED]: "HOISTED",
[PatchFlags.BAIL]: "BAIL"
};
//#endregion
//#region src/parseDirectives.ts
/**
* Get JSX element type
*
* @param path Path<JSXOpeningElement>
*/
const getType = (path) => {
const typePath = path.get("attributes").find((attribute) => {
if (!attribute.isJSXAttribute()) return false;
return attribute.get("name").isJSXIdentifier() && attribute.get("name").node.name === "type";
});
return typePath ? typePath.get("value").node : null;
};
const parseModifiers = (value) => __babel_types.isArrayExpression(value) ? value.elements.map((el) => __babel_types.isStringLiteral(el) ? el.value : "").filter(Boolean) : [];
const parseDirectives = (params) => {
var _modifiersSet$, _modifiersSet$2;
const { path, value, state, tag, isComponent } = params;
const args = [];
const vals = [];
const modifiersSet = [];
let directiveName;
let directiveArgument;
let directiveModifiers;
if ("namespace" in path.node.name) {
[directiveName, directiveArgument] = params.name.split(":");
directiveName = path.node.name.namespace.name;
directiveArgument = path.node.name.name.name;
directiveModifiers = directiveArgument.split("_").slice(1);
} else {
const underscoreModifiers = params.name.split("_");
directiveName = underscoreModifiers.shift() || "";
directiveModifiers = underscoreModifiers;
}
directiveName = directiveName.replace(/^v/, "").replace(/^-/, "").replace(/^\S/, (s) => s.toLowerCase());
if (directiveArgument) args.push(__babel_types.stringLiteral(directiveArgument.split("_")[0]));
const isVModels = directiveName === "models";
const isVModel = directiveName === "model";
if (isVModel && !path.get("value").isJSXExpressionContainer()) throw new Error("You have to use JSX Expression inside your v-model");
if (isVModels && !isComponent) throw new Error("v-models can only use in custom components");
const shouldResolve = ![
"html",
"text",
"model",
"slots",
"models"
].includes(directiveName) || isVModel && !isComponent;
let modifiers = directiveModifiers;
if (__babel_types.isArrayExpression(value)) {
const elementsList = isVModels ? value.elements : [value];
elementsList.forEach((element) => {
if (isVModels && !__babel_types.isArrayExpression(element)) throw new Error("You should pass a Two-dimensional Arrays to v-models");
const { elements } = element;
const [first, second, third] = elements;
if (second && !__babel_types.isArrayExpression(second) && !__babel_types.isSpreadElement(second)) {
args.push(second);
modifiers = parseModifiers(third);
} else if (__babel_types.isArrayExpression(second)) {
if (!shouldResolve) args.push(__babel_types.nullLiteral());
modifiers = parseModifiers(second);
} else if (!shouldResolve) args.push(__babel_types.nullLiteral());
modifiersSet.push(new Set(modifiers));
vals.push(first);
});
} else if (isVModel && !shouldResolve) {
args.push(__babel_types.nullLiteral());
modifiersSet.push(new Set(directiveModifiers));
} else modifiersSet.push(new Set(directiveModifiers));
return {
directiveName,
modifiers: modifiersSet,
values: vals.length ? vals : [value],
args,
directive: shouldResolve ? [
resolveDirective(path, state, tag, directiveName),
vals[0] || value,
((_modifiersSet$ = modifiersSet[0]) === null || _modifiersSet$ === void 0 ? void 0 : _modifiersSet$.size) ? args[0] || __babel_types.unaryExpression("void", __babel_types.numericLiteral(0), true) : args[0],
!!((_modifiersSet$2 = modifiersSet[0]) === null || _modifiersSet$2 === void 0 ? void 0 : _modifiersSet$2.size) && __babel_types.objectExpression([...modifiersSet[0]].map((modifier) => __babel_types.objectProperty(__babel_types.identifier(modifier), __babel_types.booleanLiteral(true))))
].filter(Boolean) : void 0
};
};
const resolveDirective = (path, state, tag, directiveName) => {
if (directiveName === "show") return createIdentifier(state, "vShow");
if (directiveName === "model") {
let modelToUse;
const type = getType(path.parentPath);
switch (tag.value) {
case "select":
modelToUse = createIdentifier(state, "vModelSelect");
break;
case "textarea":
modelToUse = createIdentifier(state, "vModelText");
break;
default: if (__babel_types.isStringLiteral(type) || !type) switch (type === null || type === void 0 ? void 0 : type.value) {
case "checkbox":
modelToUse = createIdentifier(state, "vModelCheckbox");
break;
case "radio":
modelToUse = createIdentifier(state, "vModelRadio");
break;
default: modelToUse = createIdentifier(state, "vModelText");
}
else modelToUse = createIdentifier(state, "vModelDynamic");
}
return modelToUse;
}
const referenceName = "v" + directiveName[0].toUpperCase() + directiveName.slice(1);
if (path.scope.references[referenceName]) return __babel_types.identifier(referenceName);
return __babel_types.callExpression(createIdentifier(state, "resolveDirective"), [__babel_types.stringLiteral(directiveName)]);
};
var parseDirectives_default = parseDirectives;
//#endregion
//#region src/transform-vue-jsx.ts
const xlinkRE = new RegExp("^xlink([A-Z])", "");
const getJSXAttributeValue = (path, state) => {
const valuePath = path.get("value");
if (valuePath.isJSXElement()) return transformJSXElement(valuePath, state);
if (valuePath.isStringLiteral()) return __babel_types.stringLiteral(transformText(valuePath.node.value));
if (valuePath.isJSXExpressionContainer()) return transformJSXExpressionContainer(valuePath);
return null;
};
const buildProps = (path, state) => {
const tag = getTag(path, state);
const isComponent = checkIsComponent(path.get("openingElement"), state);
const props = path.get("openingElement").get("attributes");
const directives = [];
const dynamicPropNames = /* @__PURE__ */ new Set();
let slots = null;
let patchFlag = 0;
if (props.length === 0) return {
tag,
isComponent,
slots,
props: __babel_types.nullLiteral(),
directives,
patchFlag,
dynamicPropNames
};
let properties = [];
let hasRef = false;
let hasClassBinding = false;
let hasStyleBinding = false;
let hasHydrationEventBinding = false;
let hasDynamicKeys = false;
const mergeArgs = [];
const { mergeProps = true } = state.opts;
props.forEach((prop) => {
if (prop.isJSXAttribute()) {
let name = getJSXAttributeName(prop);
const attributeValue = getJSXAttributeValue(prop, state);
if (!isConstant(attributeValue) || name === "ref") {
if (!isComponent && isOn(name) && name.toLowerCase() !== "onclick" && name !== "onUpdate:modelValue") hasHydrationEventBinding = true;
if (name === "ref") hasRef = true;
else if (name === "class" && !isComponent) hasClassBinding = true;
else if (name === "style" && !isComponent) hasStyleBinding = true;
else if (name !== "key" && !isDirective(name) && name !== "on") dynamicPropNames.add(name);
}
if (state.opts.transformOn && (name === "on" || name === "nativeOn")) {
if (!state.get("transformOn")) state.set("transformOn", (0, __babel_helper_module_imports.addDefault)(path, "@vue/babel-helper-vue-transform-on", { nameHint: "_transformOn" }));
mergeArgs.push(__babel_types.callExpression(state.get("transformOn"), [attributeValue || __babel_types.booleanLiteral(true)]));
return;
}
if (isDirective(name)) {
const { directive, modifiers, values, args, directiveName } = parseDirectives_default({
tag,
isComponent,
name,
path: prop,
state,
value: attributeValue
});
if (directiveName === "slots") {
slots = attributeValue;
return;
}
if (directive) directives.push(__babel_types.arrayExpression(directive));
else if (directiveName === "html") {
properties.push(__babel_types.objectProperty(__babel_types.stringLiteral("innerHTML"), values[0]));
dynamicPropNames.add("innerHTML");
} else if (directiveName === "text") {
properties.push(__babel_types.objectProperty(__babel_types.stringLiteral("textContent"), values[0]));
dynamicPropNames.add("textContent");
}
if (["models", "model"].includes(directiveName)) values.forEach((value, index) => {
const propName = args[index];
const isDynamic = propName && !__babel_types.isStringLiteral(propName) && !__babel_types.isNullLiteral(propName);
if (!directive) {
var _modifiers$index;
properties.push(__babel_types.objectProperty(__babel_types.isNullLiteral(propName) ? __babel_types.stringLiteral("modelValue") : propName, value, isDynamic));
if (!isDynamic) dynamicPropNames.add((propName === null || propName === void 0 ? void 0 : propName.value) || "modelValue");
if ((_modifiers$index = modifiers[index]) === null || _modifiers$index === void 0 ? void 0 : _modifiers$index.size) properties.push(__babel_types.objectProperty(isDynamic ? __babel_types.binaryExpression("+", propName, __babel_types.stringLiteral("Modifiers")) : __babel_types.stringLiteral(`${(propName === null || propName === void 0 ? void 0 : propName.value) || "model"}Modifiers`), __babel_types.objectExpression([...modifiers[index]].map((modifier) => __babel_types.objectProperty(__babel_types.stringLiteral(modifier), __babel_types.booleanLiteral(true)))), isDynamic));
}
const updateName = isDynamic ? __babel_types.binaryExpression("+", __babel_types.stringLiteral("onUpdate:"), propName) : __babel_types.stringLiteral(`onUpdate:${(propName === null || propName === void 0 ? void 0 : propName.value) || "modelValue"}`);
properties.push(__babel_types.objectProperty(updateName, __babel_types.arrowFunctionExpression([__babel_types.identifier("$event")], __babel_types.assignmentExpression("=", value, __babel_types.identifier("$event"))), isDynamic));
if (!isDynamic) dynamicPropNames.add(updateName.value);
else hasDynamicKeys = true;
});
} else {
if (name.match(xlinkRE)) name = name.replace(xlinkRE, (_, firstCharacter) => `xlink:${firstCharacter.toLowerCase()}`);
properties.push(__babel_types.objectProperty(__babel_types.stringLiteral(name), attributeValue || __babel_types.booleanLiteral(true)));
}
} else {
if (properties.length && mergeProps) {
mergeArgs.push(__babel_types.objectExpression(dedupeProperties(properties, mergeProps)));
properties = [];
}
hasDynamicKeys = true;
transformJSXSpreadAttribute(path, prop, mergeProps, mergeProps ? mergeArgs : properties);
}
});
if (hasDynamicKeys) patchFlag |= PatchFlags.FULL_PROPS;
else {
if (hasClassBinding) patchFlag |= PatchFlags.CLASS;
if (hasStyleBinding) patchFlag |= PatchFlags.STYLE;
if (dynamicPropNames.size) patchFlag |= PatchFlags.PROPS;
if (hasHydrationEventBinding) patchFlag |= PatchFlags.HYDRATE_EVENTS;
}
if ((patchFlag === 0 || patchFlag === PatchFlags.HYDRATE_EVENTS) && (hasRef || directives.length > 0)) patchFlag |= PatchFlags.NEED_PATCH;
let propsExpression = __babel_types.nullLiteral();
if (mergeArgs.length) {
if (properties.length) mergeArgs.push(__babel_types.objectExpression(dedupeProperties(properties, mergeProps)));
if (mergeArgs.length > 1) propsExpression = __babel_types.callExpression(createIdentifier(state, "mergeProps"), mergeArgs);
else propsExpression = mergeArgs[0];
} else if (properties.length) if (properties.length === 1 && __babel_types.isSpreadElement(properties[0])) propsExpression = properties[0].argument;
else propsExpression = __babel_types.objectExpression(dedupeProperties(properties, mergeProps));
return {
tag,
props: propsExpression,
isComponent,
slots,
directives,
patchFlag,
dynamicPropNames
};
};
/**
* Get children from Array of JSX children
* @param paths Array<JSXText | JSXExpressionContainer | JSXElement | JSXFragment>
* @returns Array<Expression | SpreadElement>
*/
const getChildren = (paths, state) => paths.map((path) => {
if (path.isJSXText()) {
const transformedText = transformJSXText(path);
if (transformedText) return __babel_types.callExpression(createIdentifier(state, "createTextVNode"), [transformedText]);
return transformedText;
}
if (path.isJSXExpressionContainer()) {
const expression = transformJSXExpressionContainer(path);
if (__babel_types.isIdentifier(expression)) {
const { name } = expression;
const { referencePaths = [] } = path.scope.getBinding(name) || {};
referencePaths.forEach((referencePath) => {
walksScope(referencePath, name, slotFlags_default.DYNAMIC);
});
}
return expression;
}
if (path.isJSXSpreadChild()) return transformJSXSpreadChild(path);
if (path.isCallExpression()) return path.node;
if (path.isJSXElement()) return transformJSXElement(path, state);
throw new Error(`getChildren: ${path.type} is not supported`);
}).filter(((value) => value != null && !__babel_types.isJSXEmptyExpression(value)));
const transformJSXElement = (path, state) => {
var _path$getData;
const children = getChildren(path.get("children"), state);
const { tag, props, isComponent, directives, patchFlag, dynamicPropNames, slots } = buildProps(path, state);
const { optimize = false } = state.opts;
if (directives.length && directives.some((d) => {
var _d$elements;
return ((_d$elements = d.elements) === null || _d$elements === void 0 || (_d$elements = _d$elements[0]) === null || _d$elements === void 0 ? void 0 : _d$elements.type) === "CallExpression" && d.elements[0].callee.type === "Identifier" && d.elements[0].callee.name === "_resolveDirective";
})) {
var _currentPath$parentPa;
let currentPath = path;
while ((_currentPath$parentPa = currentPath.parentPath) === null || _currentPath$parentPa === void 0 ? void 0 : _currentPath$parentPa.isJSXElement()) {
currentPath = currentPath.parentPath;
currentPath.setData("slotFlag", 0);
}
}
const slotFlag = (_path$getData = path.getData("slotFlag")) !== null && _path$getData !== void 0 ? _path$getData : slotFlags_default.STABLE;
const optimizeSlots = optimize && slotFlag !== 0;
let VNodeChild;
if (children.length > 1 || slots) VNodeChild = isComponent ? children.length ? __babel_types.objectExpression([
!!children.length && __babel_types.objectProperty(__babel_types.identifier("default"), __babel_types.arrowFunctionExpression([], __babel_types.arrayExpression(buildIIFE(path, children)))),
...slots ? __babel_types.isObjectExpression(slots) ? slots.properties : [__babel_types.spreadElement(slots)] : [],
optimizeSlots && __babel_types.objectProperty(__babel_types.identifier("_"), __babel_types.numericLiteral(slotFlag))
].filter(Boolean)) : slots : __babel_types.arrayExpression(children);
else if (children.length === 1) {
const { enableObjectSlots = true } = state.opts;
const child = children[0];
const objectExpression = __babel_types.objectExpression([__babel_types.objectProperty(__babel_types.identifier("default"), __babel_types.arrowFunctionExpression([], __babel_types.arrayExpression(buildIIFE(path, [child])))), optimizeSlots && __babel_types.objectProperty(__babel_types.identifier("_"), __babel_types.numericLiteral(slotFlag))].filter(Boolean));
if (__babel_types.isIdentifier(child) && isComponent) VNodeChild = enableObjectSlots ? __babel_types.conditionalExpression(__babel_types.callExpression(state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(), [child]), child, objectExpression) : objectExpression;
else if (__babel_types.isCallExpression(child) && child.loc && isComponent) if (enableObjectSlots) {
const { scope } = path;
const slotId = scope.generateUidIdentifier("slot");
if (scope) scope.push({
id: slotId,
kind: "let"
});
const alternate = __babel_types.objectExpression([__babel_types.objectProperty(__babel_types.identifier("default"), __babel_types.arrowFunctionExpression([], __babel_types.arrayExpression(buildIIFE(path, [slotId])))), optimizeSlots && __babel_types.objectProperty(__babel_types.identifier("_"), __babel_types.numericLiteral(slotFlag))].filter(Boolean));
const assignment = __babel_types.assignmentExpression("=", slotId, child);
const condition = __babel_types.callExpression(state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(), [assignment]);
VNodeChild = __babel_types.conditionalExpression(condition, slotId, alternate);
} else VNodeChild = objectExpression;
else if (__babel_types.isFunctionExpression(child) || __babel_types.isArrowFunctionExpression(child)) VNodeChild = __babel_types.objectExpression([__babel_types.objectProperty(__babel_types.identifier("default"), child)]);
else if (__babel_types.isObjectExpression(child)) VNodeChild = __babel_types.objectExpression([...child.properties, optimizeSlots && __babel_types.objectProperty(__babel_types.identifier("_"), __babel_types.numericLiteral(slotFlag))].filter(Boolean));
else VNodeChild = isComponent ? __babel_types.objectExpression([__babel_types.objectProperty(__babel_types.identifier("default"), __babel_types.arrowFunctionExpression([], __babel_types.arrayExpression([child])))]) : __babel_types.arrayExpression([child]);
}
const createVNode = __babel_types.callExpression(createIdentifier(state, "createVNode"), [
tag,
props,
VNodeChild || __babel_types.nullLiteral(),
!!patchFlag && optimize && __babel_types.numericLiteral(patchFlag),
!!dynamicPropNames.size && optimize && __babel_types.arrayExpression([...dynamicPropNames.keys()].map((name) => __babel_types.stringLiteral(name)))
].filter(Boolean));
if (!directives.length) return createVNode;
return __babel_types.callExpression(createIdentifier(state, "withDirectives"), [createVNode, __babel_types.arrayExpression(directives)]);
};
const visitor$1 = { JSXElement: { exit(path, state) {
path.replaceWith(transformJSXElement(path, state));
} } };
var transform_vue_jsx_default = visitor$1;
//#endregion
//#region src/sugar-fragment.ts
const transformFragment = (path, Fragment) => {
const children = path.get("children") || [];
return __babel_types.jsxElement(__babel_types.jsxOpeningElement(Fragment, []), __babel_types.jsxClosingElement(Fragment), children.map(({ node }) => node), false);
};
const visitor = { JSXFragment: { enter(path, state) {
const fragmentCallee = createIdentifier(state, FRAGMENT);
path.replaceWith(transformFragment(path, __babel_types.isIdentifier(fragmentCallee) ? __babel_types.jsxIdentifier(fragmentCallee.name) : __babel_types.jsxMemberExpression(__babel_types.jsxIdentifier(fragmentCallee.object.name), __babel_types.jsxIdentifier(fragmentCallee.property.name))));
} } };
var sugar_fragment_default = visitor;
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/typeof.js
var require_typeof = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/typeof.js": ((exports, module) => {
function _typeof$2(o) {
"@babel/helpers - typeof";
return module.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
return typeof o$1;
} : function(o$1) {
return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
}, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o);
}
module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
}) });
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js
var require_toPrimitive = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js": ((exports, module) => {
var _typeof$1 = require_typeof()["default"];
function toPrimitive$1(t, r) {
if ("object" != _typeof$1(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof$1(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
}) });
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js
var require_toPropertyKey = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js": ((exports, module) => {
var _typeof = require_typeof()["default"];
var toPrimitive = require_toPrimitive();
function toPropertyKey$1(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
}) });
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js
var require_defineProperty = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js": ((exports, module) => {
var toPropertyKey = require_toPropertyKey();
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
}) });
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js
var require_objectSpread2 = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js": ((exports, module) => {
var defineProperty = require_defineProperty();
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function(r$1) {
return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) {
defineProperty(e, r$1, t[r$1]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
});
}
return e;
}
module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
}) });
//#endregion
//#region src/index.ts
var import_objectSpread2 = /* @__PURE__ */ __toESM(require_objectSpread2());
const hasJSX = (parentPath) => {
let fileHasJSX = false;
parentPath.traverse({
JSXElement(path) {
fileHasJSX = true;
path.stop();
},
JSXFragment(path) {
fileHasJSX = true;
path.stop();
}
});
return fileHasJSX;
};
const JSX_ANNOTATION_REGEX = new RegExp("\\*?\\s*@jsx\\s+([^\\s]+)", "");
/* @__NO_SIDE_EFFECTS__ */
function interopDefault(m) {
return m.default || m;
}
const syntaxJsx = /* @__PURE__ */ interopDefault(__babel_plugin_syntax_jsx.default);
const template = /* @__PURE__ */ interopDefault(__babel_template.default);
const plugin = (0, __babel_helper_plugin_utils.declare)((api, opt, dirname) => {
const { types } = api;
let resolveType;
if (opt.resolveType) {
if (typeof opt.resolveType === "boolean") opt.resolveType = {};
resolveType = (0, __vue_babel_plugin_resolve_type.default)(api, opt.resolveType, dirname);
}
return (0, import_objectSpread2.default)((0, import_objectSpread2.default)({}, resolveType || {}), {}, {
name: "babel-plugin-jsx",
inherits: /* @__PURE__ */ interopDefault(syntaxJsx),
visitor: (0, import_objectSpread2.default)((0, import_objectSpread2.default)((0, import_objectSpread2.default)((0, import_objectSpread2.default)({}, resolveType === null || resolveType === void 0 ? void 0 : resolveType.visitor), transform_vue_jsx_default), sugar_fragment_default), {}, { Program: { enter(path, state) {
if (hasJSX(path)) {
const importNames = [
"createVNode",
"Fragment",
"resolveComponent",
"withDirectives",
"vShow",
"vModelSelect",
"vModelText",
"vModelCheckbox",
"vModelRadio",
"vModelText",
"vModelDynamic",
"resolveDirective",
"mergeProps",
"createTextVNode",
"isVNode"
];
if ((0, __babel_helper_module_imports.isModule)(path)) {
const importMap = {};
importNames.forEach((name) => {
state.set(name, () => {
if (importMap[name]) return types.cloneNode(importMap[name]);
const identifier = (0, __babel_helper_module_imports.addNamed)(path, name, "vue", { ensureLiveReference: true });
importMap[name] = identifier;
return identifier;
});
});
const { enableObjectSlots = true } = state.opts;
if (enableObjectSlots) state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
if (importMap.runtimeIsSlot) return importMap.runtimeIsSlot;
const { name: isVNodeName } = state.get("isVNode")();
const isSlot = path.scope.generateUidIdentifier("isSlot");
const ast = template.ast`
function ${isSlot.name}(s) {
return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${isVNodeName}(s));
}
`;
const lastImport = path.get("body").filter((p) => p.isImportDeclaration()).pop();
if (lastImport) lastImport.insertAfter(ast);
importMap.runtimeIsSlot = isSlot;
return isSlot;
});
} else {
let sourceName;
importNames.forEach((name) => {
state.set(name, () => {
if (!sourceName) sourceName = (0, __babel_helper_module_imports.addNamespace)(path, "vue", { ensureLiveReference: true });
return __babel_types.memberExpression(sourceName, __babel_types.identifier(name));
});
});
const helpers = {};
const { enableObjectSlots = true } = state.opts;
if (enableObjectSlots) state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
if (helpers.runtimeIsSlot) return helpers.runtimeIsSlot;
const isSlot = path.scope.generateUidIdentifier("isSlot");
const { object: objectName } = state.get("isVNode")();
const ast = template.ast`
function ${isSlot.name}(s) {
return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${objectName.name}.isVNode(s));
}
`;
const nodePaths = path.get("body");
const lastImport = nodePaths.filter((p) => p.isVariableDeclaration() && p.node.declarations.some((d) => {
var _d$id;
return ((_d$id = d.id) === null || _d$id === void 0 ? void 0 : _d$id.name) === sourceName.name;
})).pop();
if (lastImport) lastImport.insertAfter(ast);
return isSlot;
});
}
const { opts: { pragma = "" }, file } = state;
if (pragma) state.set("createVNode", () => __babel_types.identifier(pragma));
if (file.ast.comments) for (const comment of file.ast.comments) {
const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
if (jsxMatches) state.set("createVNode", () => __babel_types.identifier(jsxMatches[1]));
}
}
} } })
});
});
var src_default = plugin;
//#endregion
module.exports = src_default;
+771
View File
@@ -0,0 +1,771 @@
import * as t from "@babel/types";
import _template from "@babel/template";
import _syntaxJsx from "@babel/plugin-syntax-jsx";
import { addDefault, addNamed, addNamespace, isModule } from "@babel/helper-module-imports";
import ResolveType from "@vue/babel-plugin-resolve-type";
import { declare } from "@babel/helper-plugin-utils";
import { isHTMLTag, isSVGTag } from "@vue/shared";
//#region src/slotFlags.ts
var SlotFlags = /* @__PURE__ */ function(SlotFlags$1) {
/**
* Stable slots that only reference slot props or context state. The slot
* can fully capture its own dependencies so when passed down the parent won't
* need to force the child to update.
*/
SlotFlags$1[SlotFlags$1["STABLE"] = 1] = "STABLE";
/**
* Slots that reference scope variables (v-for or an outer slot prop), or
* has conditional structure (v-if, v-for). The parent will need to force
* the child to update because the slot does not fully capture its dependencies.
*/
SlotFlags$1[SlotFlags$1["DYNAMIC"] = 2] = "DYNAMIC";
/**
* `<slot/>` being forwarded into a child component. Whether the parent needs
* to update the child is dependent on what kind of slots the parent itself
* received. This has to be refined at runtime, when the child's vnode
* is being created (in `normalizeChildren`)
*/
SlotFlags$1[SlotFlags$1["FORWARDED"] = 3] = "FORWARDED";
return SlotFlags$1;
}(SlotFlags || {});
var slotFlags_default = SlotFlags;
//#endregion
//#region src/utils.ts
const FRAGMENT = "Fragment";
const KEEP_ALIVE = "KeepAlive";
/**
* create Identifier
* @param path NodePath
* @param state
* @param name string
* @returns MemberExpression
*/
const createIdentifier = (state, name) => state.get(name)();
/**
* Checks if string is describing a directive
* @param src string
*/
const isDirective = (src) => src.startsWith("v-") || src.startsWith("v") && src.length >= 2 && src[1] >= "A" && src[1] <= "Z";
/**
* Should transformed to slots
* @param tag string
* @returns boolean
*/
const shouldTransformedToSlots = (tag) => !(tag.match(RegExp(`^_?${FRAGMENT}\\d*$`)) || tag === KEEP_ALIVE);
/**
* Check if a Node is a component
*
* @param t
* @param path JSXOpeningElement
* @returns boolean
*/
const checkIsComponent = (path, state) => {
var _state$opts$isCustomE, _state$opts;
const namePath = path.get("name");
if (namePath.isJSXMemberExpression()) return shouldTransformedToSlots(namePath.node.property.name);
const tag = namePath.node.name;
return !((_state$opts$isCustomE = (_state$opts = state.opts).isCustomElement) === null || _state$opts$isCustomE === void 0 ? void 0 : _state$opts$isCustomE.call(_state$opts, tag)) && shouldTransformedToSlots(tag) && !isHTMLTag(tag) && !isSVGTag(tag);
};
/**
* Transform JSXMemberExpression to MemberExpression
* @param path JSXMemberExpression
* @returns MemberExpression
*/
const transformJSXMemberExpression = (path) => {
const objectPath = path.node.object;
const propertyPath = path.node.property;
const transformedObject = t.isJSXMemberExpression(objectPath) ? transformJSXMemberExpression(path.get("object")) : t.isJSXIdentifier(objectPath) ? t.identifier(objectPath.name) : t.nullLiteral();
const transformedProperty = t.identifier(propertyPath.name);
return t.memberExpression(transformedObject, transformedProperty);
};
/**
* Get tag (first attribute for h) from JSXOpeningElement
* @param path JSXElement
* @param state State
* @returns Identifier | StringLiteral | MemberExpression | CallExpression
*/
const getTag = (path, state) => {
const namePath = path.get("openingElement").get("name");
if (namePath.isJSXIdentifier()) {
const { name } = namePath.node;
if (!isHTMLTag(name) && !isSVGTag(name)) {
var _state$opts$isCustomE2, _state$opts2;
return name === FRAGMENT ? createIdentifier(state, FRAGMENT) : path.scope.hasBinding(name) ? t.identifier(name) : ((_state$opts$isCustomE2 = (_state$opts2 = state.opts).isCustomElement) === null || _state$opts$isCustomE2 === void 0 ? void 0 : _state$opts$isCustomE2.call(_state$opts2, name)) ? t.stringLiteral(name) : t.callExpression(createIdentifier(state, "resolveComponent"), [t.stringLiteral(name)]);
}
return t.stringLiteral(name);
}
if (namePath.isJSXMemberExpression()) return transformJSXMemberExpression(namePath);
throw new Error(`getTag: ${namePath.type} is not supported`);
};
const getJSXAttributeName = (path) => {
const nameNode = path.node.name;
if (t.isJSXIdentifier(nameNode)) return nameNode.name;
return `${nameNode.namespace.name}:${nameNode.name.name}`;
};
/**
* Transform JSXText to StringLiteral
* @param path JSXText
* @returns StringLiteral | null
*/
const transformJSXText = (path) => {
const str = transformText(path.node.value);
return str !== "" ? t.stringLiteral(str) : null;
};
const transformText = (text) => {
const lines = text.split(/\r\n|\n|\r/);
let lastNonEmptyLine = 0;
for (let i = 0; i < lines.length; i++) if (lines[i].match(/[^ \t]/)) lastNonEmptyLine = i;
let str = "";
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isFirstLine = i === 0;
const isLastLine = i === lines.length - 1;
const isLastNonEmptyLine = i === lastNonEmptyLine;
let trimmedLine = line.replace(/\t/g, " ");
if (!isFirstLine) trimmedLine = trimmedLine.replace(/^[ ]+/, "");
if (!isLastLine) trimmedLine = trimmedLine.replace(/[ ]+$/, "");
if (trimmedLine) {
if (!isLastNonEmptyLine) trimmedLine += " ";
str += trimmedLine;
}
}
return str;
};
/**
* Transform JSXExpressionContainer to Expression
* @param path JSXExpressionContainer
* @returns Expression
*/
const transformJSXExpressionContainer = (path) => path.get("expression").node;
/**
* Transform JSXSpreadChild
* @param path JSXSpreadChild
* @returns SpreadElement
*/
const transformJSXSpreadChild = (path) => t.spreadElement(path.get("expression").node);
const walksScope = (path, name, slotFlag) => {
if (path.scope.hasBinding(name) && path.parentPath) {
if (t.isJSXElement(path.parentPath.node)) path.parentPath.setData("slotFlag", slotFlag);
walksScope(path.parentPath, name, slotFlag);
}
};
const buildIIFE = (path, children) => {
const { parentPath } = path;
if (parentPath.isAssignmentExpression()) {
const { left } = parentPath.node;
if (t.isIdentifier(left)) return children.map((child) => {
if (t.isIdentifier(child) && child.name === left.name) {
const insertName = path.scope.generateUidIdentifier(child.name);
parentPath.insertBefore(t.variableDeclaration("const", [t.variableDeclarator(insertName, t.callExpression(t.functionExpression(null, [], t.blockStatement([t.returnStatement(child)])), []))]));
return insertName;
}
return child;
});
}
return children;
};
const onRE = /^on[^a-z]/;
const isOn = (key) => onRE.test(key);
const mergeAsArray = (existing, incoming) => {
if (t.isArrayExpression(existing.value)) existing.value.elements.push(incoming.value);
else existing.value = t.arrayExpression([existing.value, incoming.value]);
};
const dedupeProperties = (properties = [], mergeProps) => {
if (!mergeProps) return properties;
const knownProps = /* @__PURE__ */ new Map();
const deduped = [];
properties.forEach((prop) => {
if (t.isStringLiteral(prop.key)) {
const { value: name } = prop.key;
const existing = knownProps.get(name);
if (existing) {
if (name === "style" || name === "class" || name.startsWith("on")) mergeAsArray(existing, prop);
} else {
knownProps.set(name, prop);
deduped.push(prop);
}
} else deduped.push(prop);
});
return deduped;
};
/**
* Check if an attribute value is constant
* @param node
* @returns boolean
*/
const isConstant = (node) => {
if (t.isIdentifier(node)) return node.name === "undefined";
if (t.isArrayExpression(node)) {
const { elements } = node;
return elements.every((element) => element && isConstant(element));
}
if (t.isObjectExpression(node)) return node.properties.every((property) => isConstant(property.value));
if (t.isTemplateLiteral(node) ? !node.expressions.length : t.isLiteral(node)) return true;
return false;
};
const transformJSXSpreadAttribute = (nodePath, path, mergeProps, args) => {
const argument = path.get("argument");
const properties = t.isObjectExpression(argument.node) ? argument.node.properties : void 0;
if (!properties) {
if (argument.isIdentifier()) walksScope(nodePath, argument.node.name, slotFlags_default.DYNAMIC);
args.push(mergeProps ? argument.node : t.spreadElement(argument.node));
} else if (mergeProps) args.push(t.objectExpression(properties));
else args.push(...properties);
};
//#endregion
//#region src/patchFlags.ts
let PatchFlags = /* @__PURE__ */ function(PatchFlags$1) {
PatchFlags$1[PatchFlags$1["TEXT"] = 1] = "TEXT";
PatchFlags$1[PatchFlags$1["CLASS"] = 2] = "CLASS";
PatchFlags$1[PatchFlags$1["STYLE"] = 4] = "STYLE";
PatchFlags$1[PatchFlags$1["PROPS"] = 8] = "PROPS";
PatchFlags$1[PatchFlags$1["FULL_PROPS"] = 16] = "FULL_PROPS";
PatchFlags$1[PatchFlags$1["HYDRATE_EVENTS"] = 32] = "HYDRATE_EVENTS";
PatchFlags$1[PatchFlags$1["STABLE_FRAGMENT"] = 64] = "STABLE_FRAGMENT";
PatchFlags$1[PatchFlags$1["KEYED_FRAGMENT"] = 128] = "KEYED_FRAGMENT";
PatchFlags$1[PatchFlags$1["UNKEYED_FRAGMENT"] = 256] = "UNKEYED_FRAGMENT";
PatchFlags$1[PatchFlags$1["NEED_PATCH"] = 512] = "NEED_PATCH";
PatchFlags$1[PatchFlags$1["DYNAMIC_SLOTS"] = 1024] = "DYNAMIC_SLOTS";
PatchFlags$1[PatchFlags$1["HOISTED"] = -1] = "HOISTED";
PatchFlags$1[PatchFlags$1["BAIL"] = -2] = "BAIL";
return PatchFlags$1;
}({});
const PatchFlagNames = {
[PatchFlags.TEXT]: "TEXT",
[PatchFlags.CLASS]: "CLASS",
[PatchFlags.STYLE]: "STYLE",
[PatchFlags.PROPS]: "PROPS",
[PatchFlags.FULL_PROPS]: "FULL_PROPS",
[PatchFlags.HYDRATE_EVENTS]: "HYDRATE_EVENTS",
[PatchFlags.STABLE_FRAGMENT]: "STABLE_FRAGMENT",
[PatchFlags.KEYED_FRAGMENT]: "KEYED_FRAGMENT",
[PatchFlags.UNKEYED_FRAGMENT]: "UNKEYED_FRAGMENT",
[PatchFlags.DYNAMIC_SLOTS]: "DYNAMIC_SLOTS",
[PatchFlags.NEED_PATCH]: "NEED_PATCH",
[PatchFlags.HOISTED]: "HOISTED",
[PatchFlags.BAIL]: "BAIL"
};
//#endregion
//#region src/parseDirectives.ts
/**
* Get JSX element type
*
* @param path Path<JSXOpeningElement>
*/
const getType = (path) => {
const typePath = path.get("attributes").find((attribute) => {
if (!attribute.isJSXAttribute()) return false;
return attribute.get("name").isJSXIdentifier() && attribute.get("name").node.name === "type";
});
return typePath ? typePath.get("value").node : null;
};
const parseModifiers = (value) => t.isArrayExpression(value) ? value.elements.map((el) => t.isStringLiteral(el) ? el.value : "").filter(Boolean) : [];
const parseDirectives = (params) => {
var _modifiersSet$, _modifiersSet$2;
const { path, value, state, tag, isComponent } = params;
const args = [];
const vals = [];
const modifiersSet = [];
let directiveName;
let directiveArgument;
let directiveModifiers;
if ("namespace" in path.node.name) {
[directiveName, directiveArgument] = params.name.split(":");
directiveName = path.node.name.namespace.name;
directiveArgument = path.node.name.name.name;
directiveModifiers = directiveArgument.split("_").slice(1);
} else {
const underscoreModifiers = params.name.split("_");
directiveName = underscoreModifiers.shift() || "";
directiveModifiers = underscoreModifiers;
}
directiveName = directiveName.replace(/^v/, "").replace(/^-/, "").replace(/^\S/, (s) => s.toLowerCase());
if (directiveArgument) args.push(t.stringLiteral(directiveArgument.split("_")[0]));
const isVModels = directiveName === "models";
const isVModel = directiveName === "model";
if (isVModel && !path.get("value").isJSXExpressionContainer()) throw new Error("You have to use JSX Expression inside your v-model");
if (isVModels && !isComponent) throw new Error("v-models can only use in custom components");
const shouldResolve = ![
"html",
"text",
"model",
"slots",
"models"
].includes(directiveName) || isVModel && !isComponent;
let modifiers = directiveModifiers;
if (t.isArrayExpression(value)) {
const elementsList = isVModels ? value.elements : [value];
elementsList.forEach((element) => {
if (isVModels && !t.isArrayExpression(element)) throw new Error("You should pass a Two-dimensional Arrays to v-models");
const { elements } = element;
const [first, second, third] = elements;
if (second && !t.isArrayExpression(second) && !t.isSpreadElement(second)) {
args.push(second);
modifiers = parseModifiers(third);
} else if (t.isArrayExpression(second)) {
if (!shouldResolve) args.push(t.nullLiteral());
modifiers = parseModifiers(second);
} else if (!shouldResolve) args.push(t.nullLiteral());
modifiersSet.push(new Set(modifiers));
vals.push(first);
});
} else if (isVModel && !shouldResolve) {
args.push(t.nullLiteral());
modifiersSet.push(new Set(directiveModifiers));
} else modifiersSet.push(new Set(directiveModifiers));
return {
directiveName,
modifiers: modifiersSet,
values: vals.length ? vals : [value],
args,
directive: shouldResolve ? [
resolveDirective(path, state, tag, directiveName),
vals[0] || value,
((_modifiersSet$ = modifiersSet[0]) === null || _modifiersSet$ === void 0 ? void 0 : _modifiersSet$.size) ? args[0] || t.unaryExpression("void", t.numericLiteral(0), true) : args[0],
!!((_modifiersSet$2 = modifiersSet[0]) === null || _modifiersSet$2 === void 0 ? void 0 : _modifiersSet$2.size) && t.objectExpression([...modifiersSet[0]].map((modifier) => t.objectProperty(t.identifier(modifier), t.booleanLiteral(true))))
].filter(Boolean) : void 0
};
};
const resolveDirective = (path, state, tag, directiveName) => {
if (directiveName === "show") return createIdentifier(state, "vShow");
if (directiveName === "model") {
let modelToUse;
const type = getType(path.parentPath);
switch (tag.value) {
case "select":
modelToUse = createIdentifier(state, "vModelSelect");
break;
case "textarea":
modelToUse = createIdentifier(state, "vModelText");
break;
default: if (t.isStringLiteral(type) || !type) switch (type === null || type === void 0 ? void 0 : type.value) {
case "checkbox":
modelToUse = createIdentifier(state, "vModelCheckbox");
break;
case "radio":
modelToUse = createIdentifier(state, "vModelRadio");
break;
default: modelToUse = createIdentifier(state, "vModelText");
}
else modelToUse = createIdentifier(state, "vModelDynamic");
}
return modelToUse;
}
const referenceName = "v" + directiveName[0].toUpperCase() + directiveName.slice(1);
if (path.scope.references[referenceName]) return t.identifier(referenceName);
return t.callExpression(createIdentifier(state, "resolveDirective"), [t.stringLiteral(directiveName)]);
};
var parseDirectives_default = parseDirectives;
//#endregion
//#region src/transform-vue-jsx.ts
const xlinkRE = new RegExp("^xlink([A-Z])", "");
const getJSXAttributeValue = (path, state) => {
const valuePath = path.get("value");
if (valuePath.isJSXElement()) return transformJSXElement(valuePath, state);
if (valuePath.isStringLiteral()) return t.stringLiteral(transformText(valuePath.node.value));
if (valuePath.isJSXExpressionContainer()) return transformJSXExpressionContainer(valuePath);
return null;
};
const buildProps = (path, state) => {
const tag = getTag(path, state);
const isComponent = checkIsComponent(path.get("openingElement"), state);
const props = path.get("openingElement").get("attributes");
const directives = [];
const dynamicPropNames = /* @__PURE__ */ new Set();
let slots = null;
let patchFlag = 0;
if (props.length === 0) return {
tag,
isComponent,
slots,
props: t.nullLiteral(),
directives,
patchFlag,
dynamicPropNames
};
let properties = [];
let hasRef = false;
let hasClassBinding = false;
let hasStyleBinding = false;
let hasHydrationEventBinding = false;
let hasDynamicKeys = false;
const mergeArgs = [];
const { mergeProps = true } = state.opts;
props.forEach((prop) => {
if (prop.isJSXAttribute()) {
let name = getJSXAttributeName(prop);
const attributeValue = getJSXAttributeValue(prop, state);
if (!isConstant(attributeValue) || name === "ref") {
if (!isComponent && isOn(name) && name.toLowerCase() !== "onclick" && name !== "onUpdate:modelValue") hasHydrationEventBinding = true;
if (name === "ref") hasRef = true;
else if (name === "class" && !isComponent) hasClassBinding = true;
else if (name === "style" && !isComponent) hasStyleBinding = true;
else if (name !== "key" && !isDirective(name) && name !== "on") dynamicPropNames.add(name);
}
if (state.opts.transformOn && (name === "on" || name === "nativeOn")) {
if (!state.get("transformOn")) state.set("transformOn", addDefault(path, "@vue/babel-helper-vue-transform-on", { nameHint: "_transformOn" }));
mergeArgs.push(t.callExpression(state.get("transformOn"), [attributeValue || t.booleanLiteral(true)]));
return;
}
if (isDirective(name)) {
const { directive, modifiers, values, args, directiveName } = parseDirectives_default({
tag,
isComponent,
name,
path: prop,
state,
value: attributeValue
});
if (directiveName === "slots") {
slots = attributeValue;
return;
}
if (directive) directives.push(t.arrayExpression(directive));
else if (directiveName === "html") {
properties.push(t.objectProperty(t.stringLiteral("innerHTML"), values[0]));
dynamicPropNames.add("innerHTML");
} else if (directiveName === "text") {
properties.push(t.objectProperty(t.stringLiteral("textContent"), values[0]));
dynamicPropNames.add("textContent");
}
if (["models", "model"].includes(directiveName)) values.forEach((value, index) => {
const propName = args[index];
const isDynamic = propName && !t.isStringLiteral(propName) && !t.isNullLiteral(propName);
if (!directive) {
var _modifiers$index;
properties.push(t.objectProperty(t.isNullLiteral(propName) ? t.stringLiteral("modelValue") : propName, value, isDynamic));
if (!isDynamic) dynamicPropNames.add((propName === null || propName === void 0 ? void 0 : propName.value) || "modelValue");
if ((_modifiers$index = modifiers[index]) === null || _modifiers$index === void 0 ? void 0 : _modifiers$index.size) properties.push(t.objectProperty(isDynamic ? t.binaryExpression("+", propName, t.stringLiteral("Modifiers")) : t.stringLiteral(`${(propName === null || propName === void 0 ? void 0 : propName.value) || "model"}Modifiers`), t.objectExpression([...modifiers[index]].map((modifier) => t.objectProperty(t.stringLiteral(modifier), t.booleanLiteral(true)))), isDynamic));
}
const updateName = isDynamic ? t.binaryExpression("+", t.stringLiteral("onUpdate:"), propName) : t.stringLiteral(`onUpdate:${(propName === null || propName === void 0 ? void 0 : propName.value) || "modelValue"}`);
properties.push(t.objectProperty(updateName, t.arrowFunctionExpression([t.identifier("$event")], t.assignmentExpression("=", value, t.identifier("$event"))), isDynamic));
if (!isDynamic) dynamicPropNames.add(updateName.value);
else hasDynamicKeys = true;
});
} else {
if (name.match(xlinkRE)) name = name.replace(xlinkRE, (_, firstCharacter) => `xlink:${firstCharacter.toLowerCase()}`);
properties.push(t.objectProperty(t.stringLiteral(name), attributeValue || t.booleanLiteral(true)));
}
} else {
if (properties.length && mergeProps) {
mergeArgs.push(t.objectExpression(dedupeProperties(properties, mergeProps)));
properties = [];
}
hasDynamicKeys = true;
transformJSXSpreadAttribute(path, prop, mergeProps, mergeProps ? mergeArgs : properties);
}
});
if (hasDynamicKeys) patchFlag |= PatchFlags.FULL_PROPS;
else {
if (hasClassBinding) patchFlag |= PatchFlags.CLASS;
if (hasStyleBinding) patchFlag |= PatchFlags.STYLE;
if (dynamicPropNames.size) patchFlag |= PatchFlags.PROPS;
if (hasHydrationEventBinding) patchFlag |= PatchFlags.HYDRATE_EVENTS;
}
if ((patchFlag === 0 || patchFlag === PatchFlags.HYDRATE_EVENTS) && (hasRef || directives.length > 0)) patchFlag |= PatchFlags.NEED_PATCH;
let propsExpression = t.nullLiteral();
if (mergeArgs.length) {
if (properties.length) mergeArgs.push(t.objectExpression(dedupeProperties(properties, mergeProps)));
if (mergeArgs.length > 1) propsExpression = t.callExpression(createIdentifier(state, "mergeProps"), mergeArgs);
else propsExpression = mergeArgs[0];
} else if (properties.length) if (properties.length === 1 && t.isSpreadElement(properties[0])) propsExpression = properties[0].argument;
else propsExpression = t.objectExpression(dedupeProperties(properties, mergeProps));
return {
tag,
props: propsExpression,
isComponent,
slots,
directives,
patchFlag,
dynamicPropNames
};
};
/**
* Get children from Array of JSX children
* @param paths Array<JSXText | JSXExpressionContainer | JSXElement | JSXFragment>
* @returns Array<Expression | SpreadElement>
*/
const getChildren = (paths, state) => paths.map((path) => {
if (path.isJSXText()) {
const transformedText = transformJSXText(path);
if (transformedText) return t.callExpression(createIdentifier(state, "createTextVNode"), [transformedText]);
return transformedText;
}
if (path.isJSXExpressionContainer()) {
const expression = transformJSXExpressionContainer(path);
if (t.isIdentifier(expression)) {
const { name } = expression;
const { referencePaths = [] } = path.scope.getBinding(name) || {};
referencePaths.forEach((referencePath) => {
walksScope(referencePath, name, slotFlags_default.DYNAMIC);
});
}
return expression;
}
if (path.isJSXSpreadChild()) return transformJSXSpreadChild(path);
if (path.isCallExpression()) return path.node;
if (path.isJSXElement()) return transformJSXElement(path, state);
throw new Error(`getChildren: ${path.type} is not supported`);
}).filter(((value) => value != null && !t.isJSXEmptyExpression(value)));
const transformJSXElement = (path, state) => {
var _path$getData;
const children = getChildren(path.get("children"), state);
const { tag, props, isComponent, directives, patchFlag, dynamicPropNames, slots } = buildProps(path, state);
const { optimize = false } = state.opts;
if (directives.length && directives.some((d) => {
var _d$elements;
return ((_d$elements = d.elements) === null || _d$elements === void 0 || (_d$elements = _d$elements[0]) === null || _d$elements === void 0 ? void 0 : _d$elements.type) === "CallExpression" && d.elements[0].callee.type === "Identifier" && d.elements[0].callee.name === "_resolveDirective";
})) {
var _currentPath$parentPa;
let currentPath = path;
while ((_currentPath$parentPa = currentPath.parentPath) === null || _currentPath$parentPa === void 0 ? void 0 : _currentPath$parentPa.isJSXElement()) {
currentPath = currentPath.parentPath;
currentPath.setData("slotFlag", 0);
}
}
const slotFlag = (_path$getData = path.getData("slotFlag")) !== null && _path$getData !== void 0 ? _path$getData : slotFlags_default.STABLE;
const optimizeSlots = optimize && slotFlag !== 0;
let VNodeChild;
if (children.length > 1 || slots) VNodeChild = isComponent ? children.length ? t.objectExpression([
!!children.length && t.objectProperty(t.identifier("default"), t.arrowFunctionExpression([], t.arrayExpression(buildIIFE(path, children)))),
...slots ? t.isObjectExpression(slots) ? slots.properties : [t.spreadElement(slots)] : [],
optimizeSlots && t.objectProperty(t.identifier("_"), t.numericLiteral(slotFlag))
].filter(Boolean)) : slots : t.arrayExpression(children);
else if (children.length === 1) {
const { enableObjectSlots = true } = state.opts;
const child = children[0];
const objectExpression = t.objectExpression([t.objectProperty(t.identifier("default"), t.arrowFunctionExpression([], t.arrayExpression(buildIIFE(path, [child])))), optimizeSlots && t.objectProperty(t.identifier("_"), t.numericLiteral(slotFlag))].filter(Boolean));
if (t.isIdentifier(child) && isComponent) VNodeChild = enableObjectSlots ? t.conditionalExpression(t.callExpression(state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(), [child]), child, objectExpression) : objectExpression;
else if (t.isCallExpression(child) && child.loc && isComponent) if (enableObjectSlots) {
const { scope } = path;
const slotId = scope.generateUidIdentifier("slot");
if (scope) scope.push({
id: slotId,
kind: "let"
});
const alternate = t.objectExpression([t.objectProperty(t.identifier("default"), t.arrowFunctionExpression([], t.arrayExpression(buildIIFE(path, [slotId])))), optimizeSlots && t.objectProperty(t.identifier("_"), t.numericLiteral(slotFlag))].filter(Boolean));
const assignment = t.assignmentExpression("=", slotId, child);
const condition = t.callExpression(state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(), [assignment]);
VNodeChild = t.conditionalExpression(condition, slotId, alternate);
} else VNodeChild = objectExpression;
else if (t.isFunctionExpression(child) || t.isArrowFunctionExpression(child)) VNodeChild = t.objectExpression([t.objectProperty(t.identifier("default"), child)]);
else if (t.isObjectExpression(child)) VNodeChild = t.objectExpression([...child.properties, optimizeSlots && t.objectProperty(t.identifier("_"), t.numericLiteral(slotFlag))].filter(Boolean));
else VNodeChild = isComponent ? t.objectExpression([t.objectProperty(t.identifier("default"), t.arrowFunctionExpression([], t.arrayExpression([child])))]) : t.arrayExpression([child]);
}
const createVNode = t.callExpression(createIdentifier(state, "createVNode"), [
tag,
props,
VNodeChild || t.nullLiteral(),
!!patchFlag && optimize && t.numericLiteral(patchFlag),
!!dynamicPropNames.size && optimize && t.arrayExpression([...dynamicPropNames.keys()].map((name) => t.stringLiteral(name)))
].filter(Boolean));
if (!directives.length) return createVNode;
return t.callExpression(createIdentifier(state, "withDirectives"), [createVNode, t.arrayExpression(directives)]);
};
const visitor$1 = { JSXElement: { exit(path, state) {
path.replaceWith(transformJSXElement(path, state));
} } };
var transform_vue_jsx_default = visitor$1;
//#endregion
//#region src/sugar-fragment.ts
const transformFragment = (path, Fragment) => {
const children = path.get("children") || [];
return t.jsxElement(t.jsxOpeningElement(Fragment, []), t.jsxClosingElement(Fragment), children.map(({ node }) => node), false);
};
const visitor = { JSXFragment: { enter(path, state) {
const fragmentCallee = createIdentifier(state, FRAGMENT);
path.replaceWith(transformFragment(path, t.isIdentifier(fragmentCallee) ? t.jsxIdentifier(fragmentCallee.name) : t.jsxMemberExpression(t.jsxIdentifier(fragmentCallee.object.name), t.jsxIdentifier(fragmentCallee.property.name))));
} } };
var sugar_fragment_default = visitor;
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/esm/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
return typeof o$1;
} : function(o$1) {
return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
}, _typeof(o);
}
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/esm/toPrimitive.js
function toPrimitive(t$1, r) {
if ("object" != _typeof(t$1) || !t$1) return t$1;
var e = t$1[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t$1, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t$1);
}
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/esm/toPropertyKey.js
function toPropertyKey(t$1) {
var i = toPrimitive(t$1, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/esm/defineProperty.js
function _defineProperty(e, r, t$1) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t$1,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t$1, e;
}
//#endregion
//#region ../../node_modules/.pnpm/@oxc-project+runtime@0.80.0/node_modules/@oxc-project/runtime/src/helpers/esm/objectSpread2.js
function ownKeys(e, r) {
var t$1 = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function(r$1) {
return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
})), t$1.push.apply(t$1, o);
}
return t$1;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t$1 = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t$1), !0).forEach(function(r$1) {
_defineProperty(e, r$1, t$1[r$1]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t$1)) : ownKeys(Object(t$1)).forEach(function(r$1) {
Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t$1, r$1));
});
}
return e;
}
//#endregion
//#region src/index.ts
const hasJSX = (parentPath) => {
let fileHasJSX = false;
parentPath.traverse({
JSXElement(path) {
fileHasJSX = true;
path.stop();
},
JSXFragment(path) {
fileHasJSX = true;
path.stop();
}
});
return fileHasJSX;
};
const JSX_ANNOTATION_REGEX = new RegExp("\\*?\\s*@jsx\\s+([^\\s]+)", "");
/* @__NO_SIDE_EFFECTS__ */
function interopDefault(m) {
return m.default || m;
}
const syntaxJsx = /* @__PURE__ */ interopDefault(_syntaxJsx);
const template = /* @__PURE__ */ interopDefault(_template);
const plugin = declare((api, opt, dirname) => {
const { types } = api;
let resolveType;
if (opt.resolveType) {
if (typeof opt.resolveType === "boolean") opt.resolveType = {};
resolveType = ResolveType(api, opt.resolveType, dirname);
}
return _objectSpread2(_objectSpread2({}, resolveType || {}), {}, {
name: "babel-plugin-jsx",
inherits: /* @__PURE__ */ interopDefault(syntaxJsx),
visitor: _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, resolveType === null || resolveType === void 0 ? void 0 : resolveType.visitor), transform_vue_jsx_default), sugar_fragment_default), {}, { Program: { enter(path, state) {
if (hasJSX(path)) {
const importNames = [
"createVNode",
"Fragment",
"resolveComponent",
"withDirectives",
"vShow",
"vModelSelect",
"vModelText",
"vModelCheckbox",
"vModelRadio",
"vModelText",
"vModelDynamic",
"resolveDirective",
"mergeProps",
"createTextVNode",
"isVNode"
];
if (isModule(path)) {
const importMap = {};
importNames.forEach((name) => {
state.set(name, () => {
if (importMap[name]) return types.cloneNode(importMap[name]);
const identifier = addNamed(path, name, "vue", { ensureLiveReference: true });
importMap[name] = identifier;
return identifier;
});
});
const { enableObjectSlots = true } = state.opts;
if (enableObjectSlots) state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
if (importMap.runtimeIsSlot) return importMap.runtimeIsSlot;
const { name: isVNodeName } = state.get("isVNode")();
const isSlot = path.scope.generateUidIdentifier("isSlot");
const ast = template.ast`
function ${isSlot.name}(s) {
return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${isVNodeName}(s));
}
`;
const lastImport = path.get("body").filter((p) => p.isImportDeclaration()).pop();
if (lastImport) lastImport.insertAfter(ast);
importMap.runtimeIsSlot = isSlot;
return isSlot;
});
} else {
let sourceName;
importNames.forEach((name) => {
state.set(name, () => {
if (!sourceName) sourceName = addNamespace(path, "vue", { ensureLiveReference: true });
return t.memberExpression(sourceName, t.identifier(name));
});
});
const helpers = {};
const { enableObjectSlots = true } = state.opts;
if (enableObjectSlots) state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
if (helpers.runtimeIsSlot) return helpers.runtimeIsSlot;
const isSlot = path.scope.generateUidIdentifier("isSlot");
const { object: objectName } = state.get("isVNode")();
const ast = template.ast`
function ${isSlot.name}(s) {
return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${objectName.name}.isVNode(s));
}
`;
const nodePaths = path.get("body");
const lastImport = nodePaths.filter((p) => p.isVariableDeclaration() && p.node.declarations.some((d) => {
var _d$id;
return ((_d$id = d.id) === null || _d$id === void 0 ? void 0 : _d$id.name) === sourceName.name;
})).pop();
if (lastImport) lastImport.insertAfter(ast);
return isSlot;
});
}
const { opts: { pragma = "" }, file } = state;
if (pragma) state.set("createVNode", () => t.identifier(pragma));
if (file.ast.comments) for (const comment of file.ast.comments) {
const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
if (jsxMatches) state.set("createVNode", () => t.identifier(jsxMatches[1]));
}
}
} } })
});
});
var src_default = plugin;
//#endregion
export { src_default as default };
+57
View File
@@ -0,0 +1,57 @@
{
"name": "@vue/babel-plugin-jsx",
"version": "1.5.0",
"description": "Babel plugin for Vue 3 JSX",
"author": "Amour1688 <lcz_1996@foxmail.com>",
"homepage": "https://github.com/vuejs/babel-plugin-jsx/tree/dev/packages/babel-plugin-jsx#readme",
"license": "MIT",
"type": "commonjs",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./*": "./*"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/babel-plugin-jsx.git"
},
"bugs": {
"url": "https://github.com/vuejs/babel-plugin-jsx/issues"
},
"files": [
"dist"
],
"dependencies": {
"@babel/helper-module-imports": "^7.27.1",
"@babel/helper-plugin-utils": "^7.27.1",
"@babel/plugin-syntax-jsx": "^7.27.1",
"@babel/template": "^7.27.2",
"@babel/traverse": "^7.28.0",
"@babel/types": "^7.28.2",
"@vue/shared": "^3.5.18",
"@vue/babel-helper-vue-transform-on": "1.5.0",
"@vue/babel-plugin-resolve-type": "1.5.0"
},
"devDependencies": {
"@babel/core": "^7.28.0",
"@babel/preset-env": "^7.28.0",
"@types/babel__template": "^7.4.4",
"@types/babel__traverse": "^7.28.0",
"@vue/test-utils": "^2.4.6",
"regenerator-runtime": "^0.14.1",
"vue": "^3.5.18"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
},
"peerDependenciesMeta": {
"@babel/core": {
"optional": true
}
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-present vuejs
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.
+1
View File
@@ -0,0 +1 @@
# babel-plugin-resolve-type
+7
View File
@@ -0,0 +1,7 @@
import { SimpleTypeResolveOptions } from "@vue/compiler-sfc";
import * as BabelCore from "@babel/core";
//#region src/index.d.ts
declare const plugin: (api: object, options: SimpleTypeResolveOptions | null | undefined, dirname: string) => BabelCore.PluginObj<BabelCore.PluginPass>;
//#endregion
export { SimpleTypeResolveOptions as Options, plugin as default };
+7
View File
@@ -0,0 +1,7 @@
import * as BabelCore from "@babel/core";
import { SimpleTypeResolveOptions } from "@vue/compiler-sfc";
//#region src/index.d.ts
declare const plugin: (api: object, options: SimpleTypeResolveOptions | null | undefined, dirname: string) => BabelCore.PluginObj<BabelCore.PluginPass>;
//#endregion
export { SimpleTypeResolveOptions as Options, plugin as default };
+196
View File
@@ -0,0 +1,196 @@
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
const __babel_parser = __toESM(require("@babel/parser"));
const __vue_compiler_sfc = __toESM(require("@vue/compiler-sfc"));
const __babel_code_frame = __toESM(require("@babel/code-frame"));
const __babel_helper_module_imports = __toESM(require("@babel/helper-module-imports"));
const __babel_helper_plugin_utils = __toESM(require("@babel/helper-plugin-utils"));
//#region src/index.ts
const plugin = (0, __babel_helper_plugin_utils.declare)(({ types: t }, options) => {
let ctx;
let helpers;
return {
name: "babel-plugin-resolve-type",
pre(file) {
const filename = file.opts.filename || "unknown.js";
helpers = /* @__PURE__ */ new Set();
ctx = {
filename,
source: file.code,
options,
ast: file.ast.program.body,
isCE: false,
error(msg, node) {
throw new Error(`[@vue/babel-plugin-resolve-type] ${msg}\n\n${filename}\n${(0, __babel_code_frame.codeFrameColumns)(file.code, {
start: {
line: node.loc.start.line,
column: node.loc.start.column + 1
},
end: {
line: node.loc.end.line,
column: node.loc.end.column + 1
}
})}`);
},
helper(key) {
helpers.add(key);
return `_${key}`;
},
getString(node) {
return file.code.slice(node.start, node.end);
},
propsTypeDecl: void 0,
propsRuntimeDefaults: void 0,
propsDestructuredBindings: {},
emitsTypeDecl: void 0
};
},
visitor: {
CallExpression(path) {
if (!ctx) throw new Error("[@vue/babel-plugin-resolve-type] context is not loaded.");
const { node } = path;
if (!t.isIdentifier(node.callee, { name: "defineComponent" })) return;
if (!checkDefineComponent(path)) return;
const comp = node.arguments[0];
if (!comp || !t.isFunction(comp)) return;
let options$1 = node.arguments[1];
if (!options$1) {
options$1 = t.objectExpression([]);
node.arguments.push(options$1);
}
let propsGenerics;
let emitsGenerics;
if (node.typeParameters && node.typeParameters.params.length > 0) {
propsGenerics = node.typeParameters.params[0];
emitsGenerics = node.typeParameters.params[1];
}
node.arguments[1] = processProps(comp, propsGenerics, options$1) || options$1;
node.arguments[1] = processEmits(comp, emitsGenerics, node.arguments[1]) || options$1;
},
VariableDeclarator(path) {
inferComponentName(path);
}
},
post(file) {
for (const helper of helpers) (0, __babel_helper_module_imports.addNamed)(file.path, `_${helper}`, "vue");
}
};
function inferComponentName(path) {
var _init$get;
const id = path.get("id");
const init = path.get("init");
if (!id || !id.isIdentifier() || !init || !init.isCallExpression()) return;
if (!((_init$get = init.get("callee")) === null || _init$get === void 0 ? void 0 : _init$get.isIdentifier({ name: "defineComponent" }))) return;
if (!checkDefineComponent(init)) return;
const nameProperty = t.objectProperty(t.identifier("name"), t.stringLiteral(id.node.name));
const { arguments: args } = init.node;
if (args.length === 0) return;
if (args.length === 1) init.node.arguments.push(t.objectExpression([]));
args[1] = addProperty(t, args[1], nameProperty);
}
function processProps(comp, generics, options$1) {
const props = comp.params[0];
if (!props) return;
if (props.type === "AssignmentPattern") {
if (generics) ctx.propsTypeDecl = resolveTypeReference(generics);
else ctx.propsTypeDecl = getTypeAnnotation(props.left);
ctx.propsRuntimeDefaults = props.right;
} else if (generics) ctx.propsTypeDecl = resolveTypeReference(generics);
else ctx.propsTypeDecl = getTypeAnnotation(props);
if (!ctx.propsTypeDecl) return;
const runtimeProps = (0, __vue_compiler_sfc.extractRuntimeProps)(ctx);
if (!runtimeProps) return;
const ast = (0, __babel_parser.parseExpression)(runtimeProps);
return addProperty(t, options$1, t.objectProperty(t.identifier("props"), ast));
}
function processEmits(comp, generics, options$1) {
let emitType;
if (generics) emitType = resolveTypeReference(generics);
const setupCtx = comp.params[1] && getTypeAnnotation(comp.params[1]);
if (!emitType && setupCtx && t.isTSTypeReference(setupCtx) && t.isIdentifier(setupCtx.typeName, { name: "SetupContext" })) {
var _setupCtx$typeParamet;
emitType = (_setupCtx$typeParamet = setupCtx.typeParameters) === null || _setupCtx$typeParamet === void 0 ? void 0 : _setupCtx$typeParamet.params[0];
}
if (!emitType) return;
ctx.emitsTypeDecl = emitType;
const runtimeEmits = (0, __vue_compiler_sfc.extractRuntimeEmits)(ctx);
const ast = t.arrayExpression(Array.from(runtimeEmits).map((e) => t.stringLiteral(e)));
return addProperty(t, options$1, t.objectProperty(t.identifier("emits"), ast));
}
function resolveTypeReference(typeNode) {
if (!ctx) return;
if (t.isTSTypeReference(typeNode)) {
const typeName = getTypeReferenceName(typeNode);
if (typeName) {
const typeDeclaration = findTypeDeclaration(typeName);
if (typeDeclaration) return typeDeclaration;
}
}
}
function getTypeReferenceName(typeRef) {
if (t.isIdentifier(typeRef.typeName)) return typeRef.typeName.name;
else if (t.isTSQualifiedName(typeRef.typeName)) {
const parts = [];
let current = typeRef.typeName;
while (t.isTSQualifiedName(current)) {
if (t.isIdentifier(current.right)) parts.unshift(current.right.name);
current = current.left;
}
if (t.isIdentifier(current)) parts.unshift(current.name);
return parts.join(".");
}
return null;
}
function findTypeDeclaration(typeName) {
if (!ctx) return null;
for (const statement of ctx.ast) {
if (t.isTSInterfaceDeclaration(statement) && statement.id.name === typeName) return t.tsTypeLiteral(statement.body.body);
if (t.isTSTypeAliasDeclaration(statement) && statement.id.name === typeName) return statement.typeAnnotation;
if (t.isExportNamedDeclaration(statement) && statement.declaration) {
if (t.isTSInterfaceDeclaration(statement.declaration) && statement.declaration.id.name === typeName) return t.tsTypeLiteral(statement.declaration.body.body);
if (t.isTSTypeAliasDeclaration(statement.declaration) && statement.declaration.id.name === typeName) return statement.declaration.typeAnnotation;
}
}
return null;
}
});
var src_default = plugin;
function getTypeAnnotation(node) {
if ("typeAnnotation" in node && node.typeAnnotation && node.typeAnnotation.type === "TSTypeAnnotation") return node.typeAnnotation.typeAnnotation;
}
function checkDefineComponent(path) {
var _path$scope$getBindin;
const defineCompImport = (_path$scope$getBindin = path.scope.getBinding("defineComponent")) === null || _path$scope$getBindin === void 0 ? void 0 : _path$scope$getBindin.path.parent;
if (!defineCompImport) return true;
return defineCompImport.type === "ImportDeclaration" && new RegExp("^@?vue(\\/|$)", "").test(defineCompImport.source.value);
}
function addProperty(t, object, property) {
if (t.isObjectExpression(object)) object.properties.unshift(property);
else if (t.isExpression(object)) return t.objectExpression([property, t.spreadElement(object)]);
return object;
}
//#endregion
module.exports = src_default;
+173
View File
@@ -0,0 +1,173 @@
import { parseExpression } from "@babel/parser";
import { extractRuntimeEmits, extractRuntimeProps } from "@vue/compiler-sfc";
import { codeFrameColumns } from "@babel/code-frame";
import { addNamed } from "@babel/helper-module-imports";
import { declare } from "@babel/helper-plugin-utils";
//#region src/index.ts
const plugin = declare(({ types: t }, options) => {
let ctx;
let helpers;
return {
name: "babel-plugin-resolve-type",
pre(file) {
const filename = file.opts.filename || "unknown.js";
helpers = /* @__PURE__ */ new Set();
ctx = {
filename,
source: file.code,
options,
ast: file.ast.program.body,
isCE: false,
error(msg, node) {
throw new Error(`[@vue/babel-plugin-resolve-type] ${msg}\n\n${filename}\n${codeFrameColumns(file.code, {
start: {
line: node.loc.start.line,
column: node.loc.start.column + 1
},
end: {
line: node.loc.end.line,
column: node.loc.end.column + 1
}
})}`);
},
helper(key) {
helpers.add(key);
return `_${key}`;
},
getString(node) {
return file.code.slice(node.start, node.end);
},
propsTypeDecl: void 0,
propsRuntimeDefaults: void 0,
propsDestructuredBindings: {},
emitsTypeDecl: void 0
};
},
visitor: {
CallExpression(path) {
if (!ctx) throw new Error("[@vue/babel-plugin-resolve-type] context is not loaded.");
const { node } = path;
if (!t.isIdentifier(node.callee, { name: "defineComponent" })) return;
if (!checkDefineComponent(path)) return;
const comp = node.arguments[0];
if (!comp || !t.isFunction(comp)) return;
let options$1 = node.arguments[1];
if (!options$1) {
options$1 = t.objectExpression([]);
node.arguments.push(options$1);
}
let propsGenerics;
let emitsGenerics;
if (node.typeParameters && node.typeParameters.params.length > 0) {
propsGenerics = node.typeParameters.params[0];
emitsGenerics = node.typeParameters.params[1];
}
node.arguments[1] = processProps(comp, propsGenerics, options$1) || options$1;
node.arguments[1] = processEmits(comp, emitsGenerics, node.arguments[1]) || options$1;
},
VariableDeclarator(path) {
inferComponentName(path);
}
},
post(file) {
for (const helper of helpers) addNamed(file.path, `_${helper}`, "vue");
}
};
function inferComponentName(path) {
var _init$get;
const id = path.get("id");
const init = path.get("init");
if (!id || !id.isIdentifier() || !init || !init.isCallExpression()) return;
if (!((_init$get = init.get("callee")) === null || _init$get === void 0 ? void 0 : _init$get.isIdentifier({ name: "defineComponent" }))) return;
if (!checkDefineComponent(init)) return;
const nameProperty = t.objectProperty(t.identifier("name"), t.stringLiteral(id.node.name));
const { arguments: args } = init.node;
if (args.length === 0) return;
if (args.length === 1) init.node.arguments.push(t.objectExpression([]));
args[1] = addProperty(t, args[1], nameProperty);
}
function processProps(comp, generics, options$1) {
const props = comp.params[0];
if (!props) return;
if (props.type === "AssignmentPattern") {
if (generics) ctx.propsTypeDecl = resolveTypeReference(generics);
else ctx.propsTypeDecl = getTypeAnnotation(props.left);
ctx.propsRuntimeDefaults = props.right;
} else if (generics) ctx.propsTypeDecl = resolveTypeReference(generics);
else ctx.propsTypeDecl = getTypeAnnotation(props);
if (!ctx.propsTypeDecl) return;
const runtimeProps = extractRuntimeProps(ctx);
if (!runtimeProps) return;
const ast = parseExpression(runtimeProps);
return addProperty(t, options$1, t.objectProperty(t.identifier("props"), ast));
}
function processEmits(comp, generics, options$1) {
let emitType;
if (generics) emitType = resolveTypeReference(generics);
const setupCtx = comp.params[1] && getTypeAnnotation(comp.params[1]);
if (!emitType && setupCtx && t.isTSTypeReference(setupCtx) && t.isIdentifier(setupCtx.typeName, { name: "SetupContext" })) {
var _setupCtx$typeParamet;
emitType = (_setupCtx$typeParamet = setupCtx.typeParameters) === null || _setupCtx$typeParamet === void 0 ? void 0 : _setupCtx$typeParamet.params[0];
}
if (!emitType) return;
ctx.emitsTypeDecl = emitType;
const runtimeEmits = extractRuntimeEmits(ctx);
const ast = t.arrayExpression(Array.from(runtimeEmits).map((e) => t.stringLiteral(e)));
return addProperty(t, options$1, t.objectProperty(t.identifier("emits"), ast));
}
function resolveTypeReference(typeNode) {
if (!ctx) return;
if (t.isTSTypeReference(typeNode)) {
const typeName = getTypeReferenceName(typeNode);
if (typeName) {
const typeDeclaration = findTypeDeclaration(typeName);
if (typeDeclaration) return typeDeclaration;
}
}
}
function getTypeReferenceName(typeRef) {
if (t.isIdentifier(typeRef.typeName)) return typeRef.typeName.name;
else if (t.isTSQualifiedName(typeRef.typeName)) {
const parts = [];
let current = typeRef.typeName;
while (t.isTSQualifiedName(current)) {
if (t.isIdentifier(current.right)) parts.unshift(current.right.name);
current = current.left;
}
if (t.isIdentifier(current)) parts.unshift(current.name);
return parts.join(".");
}
return null;
}
function findTypeDeclaration(typeName) {
if (!ctx) return null;
for (const statement of ctx.ast) {
if (t.isTSInterfaceDeclaration(statement) && statement.id.name === typeName) return t.tsTypeLiteral(statement.body.body);
if (t.isTSTypeAliasDeclaration(statement) && statement.id.name === typeName) return statement.typeAnnotation;
if (t.isExportNamedDeclaration(statement) && statement.declaration) {
if (t.isTSInterfaceDeclaration(statement.declaration) && statement.declaration.id.name === typeName) return t.tsTypeLiteral(statement.declaration.body.body);
if (t.isTSTypeAliasDeclaration(statement.declaration) && statement.declaration.id.name === typeName) return statement.declaration.typeAnnotation;
}
}
return null;
}
});
var src_default = plugin;
function getTypeAnnotation(node) {
if ("typeAnnotation" in node && node.typeAnnotation && node.typeAnnotation.type === "TSTypeAnnotation") return node.typeAnnotation.typeAnnotation;
}
function checkDefineComponent(path) {
var _path$scope$getBindin;
const defineCompImport = (_path$scope$getBindin = path.scope.getBinding("defineComponent")) === null || _path$scope$getBindin === void 0 ? void 0 : _path$scope$getBindin.path.parent;
if (!defineCompImport) return true;
return defineCompImport.type === "ImportDeclaration" && new RegExp("^@?vue(\\/|$)", "").test(defineCompImport.source.value);
}
function addProperty(t, object, property) {
if (t.isObjectExpression(object)) object.properties.unshift(property);
else if (t.isExpression(object)) return t.objectExpression([property, t.spreadElement(object)]);
return object;
}
//#endregion
export { src_default as default };
+45
View File
@@ -0,0 +1,45 @@
{
"name": "@vue/babel-plugin-resolve-type",
"version": "1.5.0",
"description": "Babel plugin for resolving Vue types.",
"author": "三咲智子 Kevin Deng <sxzz@sxzz.moe>",
"funding": "https://github.com/sponsors/sxzz",
"homepage": "https://github.com/vuejs/babel-plugin-jsx/tree/dev/packages/babel-plugin-resolve-type#readme",
"license": "MIT",
"type": "commonjs",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./package.json": "./package.json"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/babel-plugin-jsx.git"
},
"bugs": {
"url": "https://github.com/vuejs/babel-plugin-jsx/issues"
},
"files": [
"dist"
],
"peerDependencies": {
"@babel/core": "^7.0.0-0"
},
"dependencies": {
"@babel/code-frame": "^7.27.1",
"@babel/helper-module-imports": "^7.27.1",
"@babel/helper-plugin-utils": "^7.27.1",
"@babel/parser": "^7.28.0",
"@vue/compiler-sfc": "^3.5.18"
},
"devDependencies": {
"@babel/core": "^7.28.0",
"@types/babel__code-frame": "^7.0.6",
"vue": "^3.5.18"
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
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.
+1
View File
@@ -0,0 +1 @@
# @vue/compiler-core
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/compiler-core.cjs.prod.js')
} else {
module.exports = require('./dist/compiler-core.cjs.js')
}
+58
View File
@@ -0,0 +1,58 @@
{
"name": "@vue/compiler-core",
"version": "3.6.0-rc.10",
"description": "@vue/compiler-core",
"main": "index.js",
"module": "dist/compiler-core.esm-bundler.js",
"types": "dist/compiler-core.d.ts",
"files": [
"index.js",
"dist"
],
"exports": {
".": {
"types": "./dist/compiler-core.d.ts",
"node": {
"production": "./dist/compiler-core.cjs.prod.js",
"development": "./dist/compiler-core.cjs.js",
"default": "./index.js"
},
"module": "./dist/compiler-core.esm-bundler.js",
"import": "./dist/compiler-core.esm-bundler.js",
"require": "./index.js"
},
"./*": "./*"
},
"buildOptions": {
"name": "VueCompilerCore",
"compat": true,
"formats": [
"esm-bundler",
"cjs"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-core"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-core#readme",
"dependencies": {
"@babel/parser": "^7.29.8",
"@vue/shared": "3.6.0-rc.10",
"entities": "^7.0.1",
"estree-walker": "^2.0.2",
"source-map-js": "^1.2.1"
},
"devDependencies": {
"@babel/types": "^7.29.8"
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
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.
+1
View File
@@ -0,0 +1 @@
# @vue/compiler-dom
+760
View File
@@ -0,0 +1,760 @@
/**
* @vue/compiler-dom v3.6.0-rc.10
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _vue_compiler_core = require("@vue/compiler-core");
let _vue_shared = require("@vue/shared");
//#region packages/compiler-dom/src/runtimeHelpers.ts
const V_MODEL_RADIO = Symbol(`vModelRadio`);
const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox`);
const V_MODEL_TEXT = Symbol(`vModelText`);
const V_MODEL_SELECT = Symbol(`vModelSelect`);
const V_MODEL_DYNAMIC = Symbol(`vModelDynamic`);
const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard`);
const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard`);
const V_SHOW = Symbol(`vShow`);
const TRANSITION = Symbol(`Transition`);
const TRANSITION_GROUP = Symbol(`TransitionGroup`);
(0, _vue_compiler_core.registerRuntimeHelpers)({
[V_MODEL_RADIO]: `vModelRadio`,
[V_MODEL_CHECKBOX]: `vModelCheckbox`,
[V_MODEL_TEXT]: `vModelText`,
[V_MODEL_SELECT]: `vModelSelect`,
[V_MODEL_DYNAMIC]: `vModelDynamic`,
[V_ON_WITH_MODIFIERS]: `withModifiers`,
[V_ON_WITH_KEYS]: `withKeys`,
[V_SHOW]: `vShow`,
[TRANSITION]: `Transition`,
[TRANSITION_GROUP]: `TransitionGroup`
});
//#endregion
//#region packages/compiler-dom/src/parserOptions.ts
const parserOptions = {
parseMode: "html",
isVoidTag: _vue_shared.isVoidTag,
isNativeTag: (tag) => (0, _vue_shared.isHTMLTag)(tag) || (0, _vue_shared.isSVGTag)(tag) || (0, _vue_shared.isMathMLTag)(tag),
isPreTag: (tag) => tag === "pre",
isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
decodeEntities: void 0,
isBuiltInComponent: (tag) => {
if (tag === "Transition" || tag === "transition") return TRANSITION;
else if (tag === "TransitionGroup" || tag === "transition-group") return TRANSITION_GROUP;
},
getNamespace(tag, parent, rootNamespace) {
let ns = parent ? parent.ns : rootNamespace;
if (parent && ns === 2) {
if (parent.tag === "annotation-xml") {
if ((0, _vue_shared.isSVGTag)(tag)) return 1;
if (parent.props.some((a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml"))) ns = 0;
} else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") ns = 0;
} else if (parent && ns === 1) {
if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") ns = 0;
}
if (ns === 0) {
if ((0, _vue_shared.isSVGTag)(tag)) return 1;
if ((0, _vue_shared.isMathMLTag)(tag)) return 2;
}
return ns;
}
};
//#endregion
//#region packages/compiler-dom/src/transforms/transformStyle.ts
const transformStyle = (node) => {
if (node.type === 1) node.props.forEach((p, i) => {
if (p.type === 6 && p.name === "style" && p.value) node.props[i] = {
type: 7,
name: `bind`,
arg: (0, _vue_compiler_core.createSimpleExpression)(`style`, true, p.loc),
exp: parseInlineCSS(p.value.content, p.loc),
modifiers: [],
loc: p.loc
};
});
};
const parseInlineCSS = (cssText, loc) => {
const normalized = (0, _vue_shared.parseStringStyle)(cssText);
return (0, _vue_compiler_core.createSimpleExpression)(JSON.stringify(normalized), false, loc, 3);
};
//#endregion
//#region packages/compiler-dom/src/errors.ts
function createDOMCompilerError(code, loc) {
return (0, _vue_compiler_core.createCompilerError)(code, loc, DOMErrorMessages);
}
const DOMErrorCodes = {
"X_V_HTML_NO_EXPRESSION": 54,
"54": "X_V_HTML_NO_EXPRESSION",
"X_V_HTML_WITH_CHILDREN": 55,
"55": "X_V_HTML_WITH_CHILDREN",
"X_V_TEXT_NO_EXPRESSION": 56,
"56": "X_V_TEXT_NO_EXPRESSION",
"X_V_TEXT_WITH_CHILDREN": 57,
"57": "X_V_TEXT_WITH_CHILDREN",
"X_V_MODEL_ON_INVALID_ELEMENT": 58,
"58": "X_V_MODEL_ON_INVALID_ELEMENT",
"X_V_MODEL_ARG_ON_ELEMENT": 59,
"59": "X_V_MODEL_ARG_ON_ELEMENT",
"X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
"60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
"X_V_MODEL_UNNECESSARY_VALUE": 61,
"61": "X_V_MODEL_UNNECESSARY_VALUE",
"X_V_SHOW_NO_EXPRESSION": 62,
"62": "X_V_SHOW_NO_EXPRESSION",
"X_TRANSITION_INVALID_CHILDREN": 63,
"63": "X_TRANSITION_INVALID_CHILDREN",
"X_IGNORED_SIDE_EFFECT_TAG": 64,
"64": "X_IGNORED_SIDE_EFFECT_TAG",
"__EXTEND_POINT__": 65,
"65": "__EXTEND_POINT__"
};
const DOMErrorMessages = {
[54]: `v-html is missing expression.`,
[55]: `v-html will override element children.`,
[56]: `v-text is missing expression.`,
[57]: `v-text will override element children.`,
[58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
[59]: `v-model argument is not supported on plain elements.`,
[60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
[61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
[62]: `v-show is missing expression.`,
[63]: `<Transition> expects exactly one child element or component.`,
[64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`,
[65]: ``
};
//#endregion
//#region packages/compiler-dom/src/transforms/vHtml.ts
const transformVHtml = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(54, loc));
if (node.children.length) {
context.onError(createDOMCompilerError(55, loc));
node.children.length = 0;
}
return { props: [(0, _vue_compiler_core.createObjectProperty)((0, _vue_compiler_core.createSimpleExpression)(`innerHTML`, true, loc), exp || (0, _vue_compiler_core.createSimpleExpression)("", true))] };
};
//#endregion
//#region packages/compiler-dom/src/transforms/vText.ts
const transformVText = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(56, loc));
if (node.children.length) {
context.onError(createDOMCompilerError(57, loc));
node.children.length = 0;
}
return { props: [(0, _vue_compiler_core.createObjectProperty)((0, _vue_compiler_core.createSimpleExpression)(`textContent`, true), exp ? (0, _vue_compiler_core.getConstantType)(exp, context) > 0 ? exp : (0, _vue_compiler_core.createCallExpression)(context.helperString(_vue_compiler_core.TO_DISPLAY_STRING), [exp], loc) : (0, _vue_compiler_core.createSimpleExpression)("", true))] };
};
//#endregion
//#region packages/compiler-dom/src/transforms/vModel.ts
const transformModel = (dir, node, context) => {
const baseResult = (0, _vue_compiler_core.transformModel)(dir, node, context);
if (!baseResult.props.length || node.tagType === 1) return baseResult;
if (dir.arg) context.onError(createDOMCompilerError(59, dir.arg.loc));
function checkDuplicatedValue() {
const value = (0, _vue_compiler_core.findDir)(node, "bind");
if (value && (0, _vue_compiler_core.isStaticArgOf)(value.arg, "value")) context.onError(createDOMCompilerError(61, value.loc));
}
const { tag } = node;
const isCustomElement = context.isCustomElement(tag);
if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
let directiveToUse = V_MODEL_TEXT;
let isInvalidType = false;
if (tag === "input" || isCustomElement) {
const type = (0, _vue_compiler_core.findProp)(node, `type`);
if (type) {
if (type.type === 7) directiveToUse = V_MODEL_DYNAMIC;
else if (type.value) switch (type.value.content) {
case "radio":
directiveToUse = V_MODEL_RADIO;
break;
case "checkbox":
directiveToUse = V_MODEL_CHECKBOX;
break;
case "file":
isInvalidType = true;
context.onError(createDOMCompilerError(60, dir.loc));
break;
default: checkDuplicatedValue();
}
} else if ((0, _vue_compiler_core.hasDynamicKeyVBind)(node)) directiveToUse = V_MODEL_DYNAMIC;
else checkDuplicatedValue();
} else if (tag === "select") directiveToUse = V_MODEL_SELECT;
else checkDuplicatedValue();
if (!isInvalidType) baseResult.needRuntime = context.helper(directiveToUse);
} else context.onError(createDOMCompilerError(58, dir.loc));
baseResult.props = baseResult.props.filter((p) => !(p.key.type === 4 && p.key.content === "modelValue"));
return baseResult;
};
//#endregion
//#region packages/compiler-dom/src/transforms/vOn.ts
const isEventOptionModifier = /*@__PURE__*/ (0, _vue_shared.makeMap)(`passive,once,capture`);
const isNonKeyModifier = /*@__PURE__*/ (0, _vue_shared.makeMap)("stop,prevent,self,ctrl,shift,alt,meta,exact,middle");
const maybeKeyModifier = /*@__PURE__*/ (0, _vue_shared.makeMap)("left,right");
const isKeyboardEvent = /*@__PURE__*/ (0, _vue_shared.makeMap)(`onkeyup,onkeydown,onkeypress`);
const resolveModifiers = (key, modifiers, context, loc) => {
const keyModifiers = [];
const nonKeyModifiers = [];
const eventOptionModifiers = [];
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i].content;
if (modifier === "delegate") {
if (context) {
const error = /* @__PURE__ */ new SyntaxError(`.delegate modifier is only supported in Vapor components.`);
error.loc = modifiers[i].loc;
context.onWarn(error);
}
continue;
}
if (modifier === "native" && context && (0, _vue_compiler_core.checkCompatEnabled)("COMPILER_V_ON_NATIVE", context, loc)) eventOptionModifiers.push(modifier);
else if (isEventOptionModifier(modifier)) eventOptionModifiers.push(modifier);
else {
const keyString = (0, _vue_shared.isString)(key) ? key : (0, _vue_compiler_core.isStaticExp)(key) ? key.content : null;
if (maybeKeyModifier(modifier)) {
if (keyString) {
if (isKeyboardEvent(keyString.toLowerCase())) keyModifiers.push(modifier);
else nonKeyModifiers.push(modifier);
} else {
keyModifiers.push(modifier);
nonKeyModifiers.push(modifier);
}
} else if (isNonKeyModifier(modifier)) nonKeyModifiers.push(modifier);
else keyModifiers.push(modifier);
}
}
return {
keyModifiers,
nonKeyModifiers,
eventOptionModifiers
};
};
const transformClick = (key, event) => {
return (0, _vue_compiler_core.isStaticExp)(key) && key.content.toLowerCase() === "onclick" ? (0, _vue_compiler_core.createSimpleExpression)(event, true) : key.type !== 4 ? (0, _vue_compiler_core.createCompoundExpression)([
`(`,
key,
`) === "onClick" ? "${event}" : (`,
key,
`)`
]) : key;
};
const transformOn = (dir, node, context) => {
return (0, _vue_compiler_core.transformOn)(dir, node, context, (baseResult) => {
const { modifiers } = dir;
if (!modifiers.length) return baseResult;
let { key, value: handlerExp } = baseResult.props[0];
const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
if (nonKeyModifiers.includes("right")) key = transformClick(key, `onContextmenu`);
if (nonKeyModifiers.includes("middle")) key = transformClick(key, `onMouseup`);
if (nonKeyModifiers.length) handlerExp = (0, _vue_compiler_core.createCallExpression)(context.helper(V_ON_WITH_MODIFIERS), [handlerExp, JSON.stringify(nonKeyModifiers)]);
if (keyModifiers.length && (!(0, _vue_compiler_core.isStaticExp)(key) || isKeyboardEvent(key.content.toLowerCase()))) handlerExp = (0, _vue_compiler_core.createCallExpression)(context.helper(V_ON_WITH_KEYS), [handlerExp, JSON.stringify(keyModifiers)]);
if (eventOptionModifiers.length) {
const modifierPostfix = eventOptionModifiers.map(_vue_shared.capitalize).join("");
key = (0, _vue_compiler_core.isStaticExp)(key) ? (0, _vue_compiler_core.createSimpleExpression)(`${key.content}${modifierPostfix}`, true) : (0, _vue_compiler_core.createCompoundExpression)([
`(`,
key,
`) + "${modifierPostfix}"`
]);
}
return { props: [(0, _vue_compiler_core.createObjectProperty)(key, handlerExp)] };
});
};
//#endregion
//#region packages/compiler-dom/src/transforms/vShow.ts
const transformShow = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(62, loc));
return {
props: [],
needRuntime: context.helper(V_SHOW)
};
};
//#endregion
//#region packages/compiler-dom/src/transforms/Transition.ts
const transformTransition = (node, context) => {
if (node.type === 1 && node.tagType === 1) {
if (context.isBuiltInComponent(node.tag) === TRANSITION) return postTransformTransition(node, context.onError);
}
};
function postTransformTransition(node, onError, hasMultipleChildren = defaultHasMultipleChildren) {
return () => {
if (!node.children.length) return;
if (hasMultipleChildren(node)) onError(createDOMCompilerError(63, {
start: node.children[0].loc.start,
end: node.children[node.children.length - 1].loc.end,
source: ""
}));
const child = node.children[0];
if (child.type === 1 && !(0, _vue_compiler_core.findDir)(child, "if")) {
for (const p of child.props) if (p.type === 7 && p.name === "show") node.props.push({
type: 6,
name: "persisted",
nameLoc: node.loc,
value: void 0,
loc: node.loc
});
}
};
}
function defaultHasMultipleChildren(node) {
const children = node.children = node.children.filter((c) => !(0, _vue_compiler_core.isCommentOrWhitespace)(c));
const child = children[0];
return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(defaultHasMultipleChildren);
}
//#endregion
//#region packages/compiler-dom/src/transforms/stringifyStatic.ts
/**
* This module is Node-only.
*/
/**
* Regex for replacing placeholders for embedded constant variables
* (e.g. import URL string constants generated by compiler-sfc)
*/
const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
/**
* Turn eligible hoisted static trees into stringified static nodes, e.g.
*
* ```js
* const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
* ```
*
* A single static vnode can contain stringified content for **multiple**
* consecutive nodes (element and plain text), called a "chunk".
* `@vue/runtime-dom` will create the content via innerHTML in a hidden
* container element and insert all the nodes in place. The call must also
* provide the number of nodes contained in the chunk so that during hydration
* we can know how many nodes the static vnode should adopt.
*
* The optimization scans a children list that contains hoisted nodes, and
* tries to find the largest chunk of consecutive hoisted nodes before running
* into a non-hoisted node or the end of the list. A chunk is then converted
* into a single static vnode and replaces the hoisted expression of the first
* node in the chunk. Other nodes in the chunk are considered "merged" and
* therefore removed from both the hoist list and the children array.
*
* This optimization is only performed in Node.js.
*/
const stringifyStatic = (children, context, parent) => {
if (context.scopes.vSlot > 0) return;
const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !(0, _vue_shared.isArray)(parent.codegenNode.children) && parent.codegenNode.children.type === 20;
let nc = 0;
let ec = 0;
const currentChunk = [];
const stringifyCurrentChunk = (currentIndex) => {
if (nc >= 20 || ec >= 5) {
const staticCall = (0, _vue_compiler_core.createCallExpression)(context.helper(_vue_compiler_core.CREATE_STATIC), [JSON.stringify(currentChunk.map((node) => stringifyNode(node, context)).join("")).replace(expReplaceRE, `" + $1 + "`), String(currentChunk.length)]);
const deleteCount = currentChunk.length - 1;
if (isParentCached) children.splice(currentIndex - currentChunk.length, currentChunk.length, staticCall);
else {
currentChunk[0].codegenNode.value = staticCall;
if (currentChunk.length > 1) {
children.splice(currentIndex - currentChunk.length + 1, deleteCount);
const cacheIndex = context.cached.indexOf(currentChunk[currentChunk.length - 1].codegenNode);
if (cacheIndex > -1) {
for (let i = cacheIndex; i < context.cached.length; i++) {
const c = context.cached[i];
if (c) c.index -= deleteCount;
}
context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);
}
}
}
return deleteCount;
}
return 0;
};
let i = 0;
for (; i < children.length; i++) {
const child = children[i];
if (isParentCached || getCachedNode(child)) {
const result = analyzeNode(child);
if (result) {
nc += result[0];
ec += result[1];
currentChunk.push(child);
continue;
}
}
i -= stringifyCurrentChunk(i);
nc = 0;
ec = 0;
currentChunk.length = 0;
}
stringifyCurrentChunk(i);
};
const getCachedNode = (node) => {
if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) return node.codegenNode;
};
const dataAriaRE = /^(?:data|aria)-/;
const isStringifiableAttr = (name, ns) => {
return (ns === 0 ? (0, _vue_shared.isKnownHtmlAttr)(name) : ns === 1 ? (0, _vue_shared.isKnownSvgAttr)(name) : ns === 2 ? (0, _vue_shared.isKnownMathMLAttr)(name) : false) || dataAriaRE.test(name);
};
const isNonStringifiable = /*@__PURE__*/ (0, _vue_shared.makeMap)(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
/**
* for a cached node, analyze it and return:
* - false: bailed (contains non-stringifiable props or runtime constant)
* - [nc, ec] where
* - nc is the number of nodes inside
* - ec is the number of element with bindings inside
*/
function analyzeNode(node) {
if (node.type === 1 && isNonStringifiable(node.tag)) return false;
if (node.type === 1 && (0, _vue_compiler_core.findDir)(node, "once", true)) return false;
if (node.type === 12) return [1, 0];
let nc = 1;
let ec = node.props.length > 0 ? 1 : 0;
let bailed = false;
const bail = () => {
bailed = true;
return false;
};
function walk(node) {
const isOptionTag = node.tag === "option" && node.ns === 0;
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i];
if (p.type === 6 && !isStringifiableAttr(p.name, node.ns)) return bail();
if (p.type === 7 && p.name === "bind") {
if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns))) return bail();
if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) return bail();
if (isOptionTag && (0, _vue_compiler_core.isStaticArgOf)(p.arg, "value") && p.exp && !p.exp.isStatic) return bail();
}
}
for (let i = 0; i < node.children.length; i++) {
nc++;
const child = node.children[i];
if (child.type === 1) {
if (child.props.length > 0) ec++;
walk(child);
if (bailed) return false;
}
}
return true;
}
return walk(node) ? [nc, ec] : false;
}
function stringifyNode(node, context) {
if ((0, _vue_shared.isString)(node)) return node;
if ((0, _vue_shared.isSymbol)(node)) return ``;
switch (node.type) {
case 1: return stringifyElement(node, context);
case 2: return (0, _vue_shared.escapeHtml)(node.content);
case 3: return `<!--${(0, _vue_shared.escapeHtml)(node.content)}-->`;
case 5: return (0, _vue_shared.escapeHtml)((0, _vue_shared.toDisplayString)(evaluateConstant(node.content)));
case 8: return (0, _vue_shared.escapeHtml)(evaluateConstant(node));
case 12: return stringifyNode(node.content, context);
default: return "";
}
}
function stringifyElement(node, context) {
let res = `<${node.tag}`;
let innerHTML = "";
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i];
if (p.type === 6) {
res += ` ${p.name}`;
if (p.value) res += `="${(0, _vue_shared.escapeHtml)(p.value.content)}"`;
} else if (p.type === 7) {
if (p.name === "bind") {
const exp = p.exp;
if (exp.content[0] === "_") {
res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
continue;
}
if (((0, _vue_shared.isBooleanAttr)(p.arg.content) || p.arg.content === "hidden") && exp.content === "false") continue;
let evaluated = evaluateConstant(exp);
if (evaluated != null) {
const arg = p.arg && p.arg.content;
if (arg === "hidden" && typeof evaluated === "number" && !(0, _vue_shared.includeBooleanAttr)(evaluated)) continue;
if (arg === "class") evaluated = (0, _vue_shared.normalizeClass)(evaluated);
else if (arg === "style") evaluated = (0, _vue_shared.stringifyStyle)((0, _vue_shared.normalizeStyle)(evaluated));
res += ` ${p.arg.content}="${(0, _vue_shared.escapeHtml)(evaluated)}"`;
}
} else if (p.name === "html") innerHTML = evaluateConstant(p.exp);
else if (p.name === "text") innerHTML = (0, _vue_shared.escapeHtml)((0, _vue_shared.toDisplayString)(evaluateConstant(p.exp)));
}
}
if (context.scopeId) res += ` ${context.scopeId}`;
res += `>`;
if (innerHTML) res += innerHTML;
else for (let i = 0; i < node.children.length; i++) res += stringifyNode(node.children[i], context);
if (!(0, _vue_shared.isVoidTag)(node.tag)) res += `</${node.tag}>`;
return res;
}
function evaluateConstant(exp) {
if (exp.type === 4) return new Function(`return (${exp.content})`)();
else {
let res = ``;
exp.children.forEach((c) => {
if ((0, _vue_shared.isString)(c) || (0, _vue_shared.isSymbol)(c)) return;
if (c.type === 2) res += c.content;
else if (c.type === 5) res += (0, _vue_shared.toDisplayString)(evaluateConstant(c.content));
else res += evaluateConstant(c);
});
return res;
}
}
//#endregion
//#region packages/compiler-dom/src/transforms/ignoreSideEffectTags.ts
const ignoreSideEffectTags = (node, context) => {
if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
context.onError(createDOMCompilerError(64, node.loc));
context.removeNode();
}
};
//#endregion
//#region packages/compiler-dom/src/htmlNesting.ts
/**
* Copied from https://github.com/MananTank/validate-html-nesting
* with ISC license
*
* To avoid runtime dependency on validate-html-nesting
* This file should not change very often in the original repo
* but we may need to keep it up-to-date from time to time.
*/
/**
* returns true if given parent-child nesting is valid HTML
*/
function isValidHTMLNesting(parent, child) {
if (parent === "template") return true;
if (parent in onlyValidChildren) return onlyValidChildren[parent].has(child);
if (child in onlyValidParents) return onlyValidParents[child].has(parent);
if (parent in knownInvalidChildren) {
if (knownInvalidChildren[parent].has(child)) return false;
}
if (child in knownInvalidParents) {
if (knownInvalidParents[child].has(parent)) return false;
}
return true;
}
const headings = /* @__PURE__ */ new Set([
"h1",
"h2",
"h3",
"h4",
"h5",
"h6"
]);
const emptySet = /* @__PURE__ */ new Set([]);
/**
* maps element to set of elements that can be it's children, no other */
const onlyValidChildren = {
head: /* @__PURE__ */ new Set([
"base",
"basefront",
"bgsound",
"link",
"meta",
"title",
"noscript",
"noframes",
"style",
"script",
"template"
]),
optgroup: /* @__PURE__ */ new Set(["option"]),
select: /* @__PURE__ */ new Set([
"optgroup",
"option",
"hr"
]),
table: /* @__PURE__ */ new Set([
"caption",
"colgroup",
"tbody",
"tfoot",
"thead"
]),
tr: /* @__PURE__ */ new Set(["td", "th"]),
colgroup: /* @__PURE__ */ new Set(["col"]),
tbody: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["tr"]),
tfoot: /* @__PURE__ */ new Set(["tr"]),
script: emptySet,
iframe: emptySet,
option: emptySet,
textarea: emptySet,
style: emptySet,
title: emptySet
};
/** maps elements to set of elements which can be it's parent, no other */
const onlyValidParents = {
html: emptySet,
body: /* @__PURE__ */ new Set(["html"]),
head: /* @__PURE__ */ new Set(["html"]),
td: /* @__PURE__ */ new Set(["tr"]),
colgroup: /* @__PURE__ */ new Set(["table"]),
caption: /* @__PURE__ */ new Set(["table"]),
tbody: /* @__PURE__ */ new Set(["table"]),
tfoot: /* @__PURE__ */ new Set(["table"]),
col: /* @__PURE__ */ new Set(["colgroup"]),
th: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["table"]),
tr: /* @__PURE__ */ new Set([
"tbody",
"thead",
"tfoot"
]),
dd: /* @__PURE__ */ new Set(["dl", "div"]),
dt: /* @__PURE__ */ new Set(["dl", "div"]),
figcaption: /* @__PURE__ */ new Set(["figure"]),
summary: /* @__PURE__ */ new Set(["details"]),
area: /* @__PURE__ */ new Set(["map"])
};
/** maps element to set of elements that can not be it's children, others can */
const knownInvalidChildren = {
p: /* @__PURE__ */ new Set([
"address",
"article",
"aside",
"blockquote",
"center",
"details",
"dialog",
"dir",
"div",
"dl",
"fieldset",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"li",
"main",
"nav",
"menu",
"ol",
"p",
"pre",
"section",
"table",
"ul"
]),
svg: /* @__PURE__ */ new Set([
"b",
"blockquote",
"br",
"code",
"dd",
"div",
"dl",
"dt",
"em",
"embed",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"img",
"li",
"menu",
"meta",
"ol",
"p",
"pre",
"ruby",
"s",
"small",
"span",
"strong",
"sub",
"sup",
"table",
"u",
"ul",
"var"
])
};
/** maps element to set of elements that can not be it's parent, others can */
const knownInvalidParents = {
a: /* @__PURE__ */ new Set(["a"]),
button: /* @__PURE__ */ new Set(["button"]),
dd: /* @__PURE__ */ new Set(["dd", "dt"]),
dt: /* @__PURE__ */ new Set(["dd", "dt"]),
form: /* @__PURE__ */ new Set(["form"]),
li: /* @__PURE__ */ new Set(["li"]),
h1: headings,
h2: headings,
h3: headings,
h4: headings,
h5: headings,
h6: headings
};
//#endregion
//#region packages/compiler-dom/src/transforms/validateHtmlNesting.ts
const validateHtmlNesting = (node, context) => {
if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) {
const error = /* @__PURE__ */ new SyntaxError(`<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.`);
error.loc = node.loc;
context.onWarn(error);
}
};
//#endregion
//#region packages/compiler-dom/src/index.ts
const DOMNodeTransforms = [transformStyle, ...[transformTransition, validateHtmlNesting]];
const DOMDirectiveTransforms = {
cloak: _vue_compiler_core.noopDirectiveTransform,
html: transformVHtml,
text: transformVText,
model: transformModel,
on: transformOn,
show: transformShow
};
function compile(src, options = {}) {
return (0, _vue_compiler_core.baseCompile)(src, (0, _vue_shared.extend)({}, parserOptions, options, {
nodeTransforms: [
ignoreSideEffectTags,
...DOMNodeTransforms,
...options.nodeTransforms || []
],
directiveTransforms: (0, _vue_shared.extend)({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
transformHoist: stringifyStatic
}));
}
function parse(template, options = {}) {
return (0, _vue_compiler_core.baseParse)(template, (0, _vue_shared.extend)({}, parserOptions, options));
}
//#endregion
exports.DOMDirectiveTransforms = DOMDirectiveTransforms;
exports.DOMErrorCodes = DOMErrorCodes;
exports.DOMErrorMessages = DOMErrorMessages;
exports.DOMNodeTransforms = DOMNodeTransforms;
exports.TRANSITION = TRANSITION;
exports.TRANSITION_GROUP = TRANSITION_GROUP;
exports.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX;
exports.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC;
exports.V_MODEL_RADIO = V_MODEL_RADIO;
exports.V_MODEL_SELECT = V_MODEL_SELECT;
exports.V_MODEL_TEXT = V_MODEL_TEXT;
exports.V_ON_WITH_KEYS = V_ON_WITH_KEYS;
exports.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS;
exports.V_SHOW = V_SHOW;
exports.compile = compile;
exports.createDOMCompilerError = createDOMCompilerError;
exports.isKeyboardEvent = isKeyboardEvent;
exports.isValidHTMLNesting = isValidHTMLNesting;
exports.parse = parse;
exports.parserOptions = parserOptions;
exports.postTransformTransition = postTransformTransition;
exports.resolveModifiers = resolveModifiers;
exports.transformStyle = transformStyle;
Object.keys(_vue_compiler_core).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function() {
return _vue_compiler_core[k];
}
});
});
+735
View File
@@ -0,0 +1,735 @@
/**
* @vue/compiler-dom v3.6.0-rc.10
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _vue_compiler_core = require("@vue/compiler-core");
let _vue_shared = require("@vue/shared");
//#region packages/compiler-dom/src/runtimeHelpers.ts
const V_MODEL_RADIO = Symbol(``);
const V_MODEL_CHECKBOX = Symbol(``);
const V_MODEL_TEXT = Symbol(``);
const V_MODEL_SELECT = Symbol(``);
const V_MODEL_DYNAMIC = Symbol(``);
const V_ON_WITH_MODIFIERS = Symbol(``);
const V_ON_WITH_KEYS = Symbol(``);
const V_SHOW = Symbol(``);
const TRANSITION = Symbol(``);
const TRANSITION_GROUP = Symbol(``);
(0, _vue_compiler_core.registerRuntimeHelpers)({
[V_MODEL_RADIO]: `vModelRadio`,
[V_MODEL_CHECKBOX]: `vModelCheckbox`,
[V_MODEL_TEXT]: `vModelText`,
[V_MODEL_SELECT]: `vModelSelect`,
[V_MODEL_DYNAMIC]: `vModelDynamic`,
[V_ON_WITH_MODIFIERS]: `withModifiers`,
[V_ON_WITH_KEYS]: `withKeys`,
[V_SHOW]: `vShow`,
[TRANSITION]: `Transition`,
[TRANSITION_GROUP]: `TransitionGroup`
});
//#endregion
//#region packages/compiler-dom/src/parserOptions.ts
const parserOptions = {
parseMode: "html",
isVoidTag: _vue_shared.isVoidTag,
isNativeTag: (tag) => (0, _vue_shared.isHTMLTag)(tag) || (0, _vue_shared.isSVGTag)(tag) || (0, _vue_shared.isMathMLTag)(tag),
isPreTag: (tag) => tag === "pre",
isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
decodeEntities: void 0,
isBuiltInComponent: (tag) => {
if (tag === "Transition" || tag === "transition") return TRANSITION;
else if (tag === "TransitionGroup" || tag === "transition-group") return TRANSITION_GROUP;
},
getNamespace(tag, parent, rootNamespace) {
let ns = parent ? parent.ns : rootNamespace;
if (parent && ns === 2) {
if (parent.tag === "annotation-xml") {
if ((0, _vue_shared.isSVGTag)(tag)) return 1;
if (parent.props.some((a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml"))) ns = 0;
} else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") ns = 0;
} else if (parent && ns === 1) {
if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") ns = 0;
}
if (ns === 0) {
if ((0, _vue_shared.isSVGTag)(tag)) return 1;
if ((0, _vue_shared.isMathMLTag)(tag)) return 2;
}
return ns;
}
};
//#endregion
//#region packages/compiler-dom/src/transforms/transformStyle.ts
const transformStyle = (node) => {
if (node.type === 1) node.props.forEach((p, i) => {
if (p.type === 6 && p.name === "style" && p.value) node.props[i] = {
type: 7,
name: `bind`,
arg: (0, _vue_compiler_core.createSimpleExpression)(`style`, true, p.loc),
exp: parseInlineCSS(p.value.content, p.loc),
modifiers: [],
loc: p.loc
};
});
};
const parseInlineCSS = (cssText, loc) => {
const normalized = (0, _vue_shared.parseStringStyle)(cssText);
return (0, _vue_compiler_core.createSimpleExpression)(JSON.stringify(normalized), false, loc, 3);
};
//#endregion
//#region packages/compiler-dom/src/errors.ts
function createDOMCompilerError(code, loc) {
return (0, _vue_compiler_core.createCompilerError)(code, loc, DOMErrorMessages);
}
const DOMErrorCodes = {
"X_V_HTML_NO_EXPRESSION": 54,
"54": "X_V_HTML_NO_EXPRESSION",
"X_V_HTML_WITH_CHILDREN": 55,
"55": "X_V_HTML_WITH_CHILDREN",
"X_V_TEXT_NO_EXPRESSION": 56,
"56": "X_V_TEXT_NO_EXPRESSION",
"X_V_TEXT_WITH_CHILDREN": 57,
"57": "X_V_TEXT_WITH_CHILDREN",
"X_V_MODEL_ON_INVALID_ELEMENT": 58,
"58": "X_V_MODEL_ON_INVALID_ELEMENT",
"X_V_MODEL_ARG_ON_ELEMENT": 59,
"59": "X_V_MODEL_ARG_ON_ELEMENT",
"X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
"60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
"X_V_MODEL_UNNECESSARY_VALUE": 61,
"61": "X_V_MODEL_UNNECESSARY_VALUE",
"X_V_SHOW_NO_EXPRESSION": 62,
"62": "X_V_SHOW_NO_EXPRESSION",
"X_TRANSITION_INVALID_CHILDREN": 63,
"63": "X_TRANSITION_INVALID_CHILDREN",
"X_IGNORED_SIDE_EFFECT_TAG": 64,
"64": "X_IGNORED_SIDE_EFFECT_TAG",
"__EXTEND_POINT__": 65,
"65": "__EXTEND_POINT__"
};
const DOMErrorMessages = {
[54]: `v-html is missing expression.`,
[55]: `v-html will override element children.`,
[56]: `v-text is missing expression.`,
[57]: `v-text will override element children.`,
[58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
[59]: `v-model argument is not supported on plain elements.`,
[60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
[61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
[62]: `v-show is missing expression.`,
[63]: `<Transition> expects exactly one child element or component.`,
[64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`,
[65]: ``
};
//#endregion
//#region packages/compiler-dom/src/transforms/vHtml.ts
const transformVHtml = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(54, loc));
if (node.children.length) {
context.onError(createDOMCompilerError(55, loc));
node.children.length = 0;
}
return { props: [(0, _vue_compiler_core.createObjectProperty)((0, _vue_compiler_core.createSimpleExpression)(`innerHTML`, true, loc), exp || (0, _vue_compiler_core.createSimpleExpression)("", true))] };
};
//#endregion
//#region packages/compiler-dom/src/transforms/vText.ts
const transformVText = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(56, loc));
if (node.children.length) {
context.onError(createDOMCompilerError(57, loc));
node.children.length = 0;
}
return { props: [(0, _vue_compiler_core.createObjectProperty)((0, _vue_compiler_core.createSimpleExpression)(`textContent`, true), exp ? (0, _vue_compiler_core.getConstantType)(exp, context) > 0 ? exp : (0, _vue_compiler_core.createCallExpression)(context.helperString(_vue_compiler_core.TO_DISPLAY_STRING), [exp], loc) : (0, _vue_compiler_core.createSimpleExpression)("", true))] };
};
//#endregion
//#region packages/compiler-dom/src/transforms/vModel.ts
const transformModel = (dir, node, context) => {
const baseResult = (0, _vue_compiler_core.transformModel)(dir, node, context);
if (!baseResult.props.length || node.tagType === 1) return baseResult;
if (dir.arg) context.onError(createDOMCompilerError(59, dir.arg.loc));
const { tag } = node;
const isCustomElement = context.isCustomElement(tag);
if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
let directiveToUse = V_MODEL_TEXT;
let isInvalidType = false;
if (tag === "input" || isCustomElement) {
const type = (0, _vue_compiler_core.findProp)(node, `type`);
if (type) {
if (type.type === 7) directiveToUse = V_MODEL_DYNAMIC;
else if (type.value) switch (type.value.content) {
case "radio":
directiveToUse = V_MODEL_RADIO;
break;
case "checkbox":
directiveToUse = V_MODEL_CHECKBOX;
break;
case "file":
isInvalidType = true;
context.onError(createDOMCompilerError(60, dir.loc));
}
} else if ((0, _vue_compiler_core.hasDynamicKeyVBind)(node)) directiveToUse = V_MODEL_DYNAMIC;
} else if (tag === "select") directiveToUse = V_MODEL_SELECT;
if (!isInvalidType) baseResult.needRuntime = context.helper(directiveToUse);
} else context.onError(createDOMCompilerError(58, dir.loc));
baseResult.props = baseResult.props.filter((p) => !(p.key.type === 4 && p.key.content === "modelValue"));
return baseResult;
};
//#endregion
//#region packages/compiler-dom/src/transforms/vOn.ts
const isEventOptionModifier = /*@__PURE__*/ (0, _vue_shared.makeMap)(`passive,once,capture`);
const isNonKeyModifier = /*@__PURE__*/ (0, _vue_shared.makeMap)("stop,prevent,self,ctrl,shift,alt,meta,exact,middle");
const maybeKeyModifier = /*@__PURE__*/ (0, _vue_shared.makeMap)("left,right");
const isKeyboardEvent = /*@__PURE__*/ (0, _vue_shared.makeMap)(`onkeyup,onkeydown,onkeypress`);
const resolveModifiers = (key, modifiers, context, loc) => {
const keyModifiers = [];
const nonKeyModifiers = [];
const eventOptionModifiers = [];
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i].content;
if (modifier === "delegate") {
if (context) {
const error = /* @__PURE__ */ new SyntaxError(`.delegate modifier is only supported in Vapor components.`);
error.loc = modifiers[i].loc;
context.onWarn(error);
}
continue;
}
if (modifier === "native" && context && (0, _vue_compiler_core.checkCompatEnabled)("COMPILER_V_ON_NATIVE", context, loc)) eventOptionModifiers.push(modifier);
else if (isEventOptionModifier(modifier)) eventOptionModifiers.push(modifier);
else {
const keyString = (0, _vue_shared.isString)(key) ? key : (0, _vue_compiler_core.isStaticExp)(key) ? key.content : null;
if (maybeKeyModifier(modifier)) {
if (keyString) {
if (isKeyboardEvent(keyString.toLowerCase())) keyModifiers.push(modifier);
else nonKeyModifiers.push(modifier);
} else {
keyModifiers.push(modifier);
nonKeyModifiers.push(modifier);
}
} else if (isNonKeyModifier(modifier)) nonKeyModifiers.push(modifier);
else keyModifiers.push(modifier);
}
}
return {
keyModifiers,
nonKeyModifiers,
eventOptionModifiers
};
};
const transformClick = (key, event) => {
return (0, _vue_compiler_core.isStaticExp)(key) && key.content.toLowerCase() === "onclick" ? (0, _vue_compiler_core.createSimpleExpression)(event, true) : key.type !== 4 ? (0, _vue_compiler_core.createCompoundExpression)([
`(`,
key,
`) === "onClick" ? "${event}" : (`,
key,
`)`
]) : key;
};
const transformOn = (dir, node, context) => {
return (0, _vue_compiler_core.transformOn)(dir, node, context, (baseResult) => {
const { modifiers } = dir;
if (!modifiers.length) return baseResult;
let { key, value: handlerExp } = baseResult.props[0];
const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
if (nonKeyModifiers.includes("right")) key = transformClick(key, `onContextmenu`);
if (nonKeyModifiers.includes("middle")) key = transformClick(key, `onMouseup`);
if (nonKeyModifiers.length) handlerExp = (0, _vue_compiler_core.createCallExpression)(context.helper(V_ON_WITH_MODIFIERS), [handlerExp, JSON.stringify(nonKeyModifiers)]);
if (keyModifiers.length && (!(0, _vue_compiler_core.isStaticExp)(key) || isKeyboardEvent(key.content.toLowerCase()))) handlerExp = (0, _vue_compiler_core.createCallExpression)(context.helper(V_ON_WITH_KEYS), [handlerExp, JSON.stringify(keyModifiers)]);
if (eventOptionModifiers.length) {
const modifierPostfix = eventOptionModifiers.map(_vue_shared.capitalize).join("");
key = (0, _vue_compiler_core.isStaticExp)(key) ? (0, _vue_compiler_core.createSimpleExpression)(`${key.content}${modifierPostfix}`, true) : (0, _vue_compiler_core.createCompoundExpression)([
`(`,
key,
`) + "${modifierPostfix}"`
]);
}
return { props: [(0, _vue_compiler_core.createObjectProperty)(key, handlerExp)] };
});
};
//#endregion
//#region packages/compiler-dom/src/transforms/vShow.ts
const transformShow = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(62, loc));
return {
props: [],
needRuntime: context.helper(V_SHOW)
};
};
//#endregion
//#region packages/compiler-dom/src/transforms/Transition.ts
function postTransformTransition(node, onError, hasMultipleChildren = defaultHasMultipleChildren) {
return () => {
if (!node.children.length) return;
if (hasMultipleChildren(node)) onError(createDOMCompilerError(63, {
start: node.children[0].loc.start,
end: node.children[node.children.length - 1].loc.end,
source: ""
}));
const child = node.children[0];
if (child.type === 1 && !(0, _vue_compiler_core.findDir)(child, "if")) {
for (const p of child.props) if (p.type === 7 && p.name === "show") node.props.push({
type: 6,
name: "persisted",
nameLoc: node.loc,
value: void 0,
loc: node.loc
});
}
};
}
function defaultHasMultipleChildren(node) {
const children = node.children = node.children.filter((c) => !(0, _vue_compiler_core.isCommentOrWhitespace)(c));
const child = children[0];
return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(defaultHasMultipleChildren);
}
//#endregion
//#region packages/compiler-dom/src/transforms/stringifyStatic.ts
/**
* This module is Node-only.
*/
/**
* Regex for replacing placeholders for embedded constant variables
* (e.g. import URL string constants generated by compiler-sfc)
*/
const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
/**
* Turn eligible hoisted static trees into stringified static nodes, e.g.
*
* ```js
* const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
* ```
*
* A single static vnode can contain stringified content for **multiple**
* consecutive nodes (element and plain text), called a "chunk".
* `@vue/runtime-dom` will create the content via innerHTML in a hidden
* container element and insert all the nodes in place. The call must also
* provide the number of nodes contained in the chunk so that during hydration
* we can know how many nodes the static vnode should adopt.
*
* The optimization scans a children list that contains hoisted nodes, and
* tries to find the largest chunk of consecutive hoisted nodes before running
* into a non-hoisted node or the end of the list. A chunk is then converted
* into a single static vnode and replaces the hoisted expression of the first
* node in the chunk. Other nodes in the chunk are considered "merged" and
* therefore removed from both the hoist list and the children array.
*
* This optimization is only performed in Node.js.
*/
const stringifyStatic = (children, context, parent) => {
if (context.scopes.vSlot > 0) return;
const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !(0, _vue_shared.isArray)(parent.codegenNode.children) && parent.codegenNode.children.type === 20;
let nc = 0;
let ec = 0;
const currentChunk = [];
const stringifyCurrentChunk = (currentIndex) => {
if (nc >= 20 || ec >= 5) {
const staticCall = (0, _vue_compiler_core.createCallExpression)(context.helper(_vue_compiler_core.CREATE_STATIC), [JSON.stringify(currentChunk.map((node) => stringifyNode(node, context)).join("")).replace(expReplaceRE, `" + $1 + "`), String(currentChunk.length)]);
const deleteCount = currentChunk.length - 1;
if (isParentCached) children.splice(currentIndex - currentChunk.length, currentChunk.length, staticCall);
else {
currentChunk[0].codegenNode.value = staticCall;
if (currentChunk.length > 1) {
children.splice(currentIndex - currentChunk.length + 1, deleteCount);
const cacheIndex = context.cached.indexOf(currentChunk[currentChunk.length - 1].codegenNode);
if (cacheIndex > -1) {
for (let i = cacheIndex; i < context.cached.length; i++) {
const c = context.cached[i];
if (c) c.index -= deleteCount;
}
context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);
}
}
}
return deleteCount;
}
return 0;
};
let i = 0;
for (; i < children.length; i++) {
const child = children[i];
if (isParentCached || getCachedNode(child)) {
const result = analyzeNode(child);
if (result) {
nc += result[0];
ec += result[1];
currentChunk.push(child);
continue;
}
}
i -= stringifyCurrentChunk(i);
nc = 0;
ec = 0;
currentChunk.length = 0;
}
stringifyCurrentChunk(i);
};
const getCachedNode = (node) => {
if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) return node.codegenNode;
};
const dataAriaRE = /^(?:data|aria)-/;
const isStringifiableAttr = (name, ns) => {
return (ns === 0 ? (0, _vue_shared.isKnownHtmlAttr)(name) : ns === 1 ? (0, _vue_shared.isKnownSvgAttr)(name) : ns === 2 ? (0, _vue_shared.isKnownMathMLAttr)(name) : false) || dataAriaRE.test(name);
};
const isNonStringifiable = /*@__PURE__*/ (0, _vue_shared.makeMap)(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
/**
* for a cached node, analyze it and return:
* - false: bailed (contains non-stringifiable props or runtime constant)
* - [nc, ec] where
* - nc is the number of nodes inside
* - ec is the number of element with bindings inside
*/
function analyzeNode(node) {
if (node.type === 1 && isNonStringifiable(node.tag)) return false;
if (node.type === 1 && (0, _vue_compiler_core.findDir)(node, "once", true)) return false;
if (node.type === 12) return [1, 0];
let nc = 1;
let ec = node.props.length > 0 ? 1 : 0;
let bailed = false;
const bail = () => {
bailed = true;
return false;
};
function walk(node) {
const isOptionTag = node.tag === "option" && node.ns === 0;
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i];
if (p.type === 6 && !isStringifiableAttr(p.name, node.ns)) return bail();
if (p.type === 7 && p.name === "bind") {
if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns))) return bail();
if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) return bail();
if (isOptionTag && (0, _vue_compiler_core.isStaticArgOf)(p.arg, "value") && p.exp && !p.exp.isStatic) return bail();
}
}
for (let i = 0; i < node.children.length; i++) {
nc++;
const child = node.children[i];
if (child.type === 1) {
if (child.props.length > 0) ec++;
walk(child);
if (bailed) return false;
}
}
return true;
}
return walk(node) ? [nc, ec] : false;
}
function stringifyNode(node, context) {
if ((0, _vue_shared.isString)(node)) return node;
if ((0, _vue_shared.isSymbol)(node)) return ``;
switch (node.type) {
case 1: return stringifyElement(node, context);
case 2: return (0, _vue_shared.escapeHtml)(node.content);
case 3: return `<!--${(0, _vue_shared.escapeHtml)(node.content)}-->`;
case 5: return (0, _vue_shared.escapeHtml)((0, _vue_shared.toDisplayString)(evaluateConstant(node.content)));
case 8: return (0, _vue_shared.escapeHtml)(evaluateConstant(node));
case 12: return stringifyNode(node.content, context);
default: return "";
}
}
function stringifyElement(node, context) {
let res = `<${node.tag}`;
let innerHTML = "";
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i];
if (p.type === 6) {
res += ` ${p.name}`;
if (p.value) res += `="${(0, _vue_shared.escapeHtml)(p.value.content)}"`;
} else if (p.type === 7) {
if (p.name === "bind") {
const exp = p.exp;
if (exp.content[0] === "_") {
res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
continue;
}
if (((0, _vue_shared.isBooleanAttr)(p.arg.content) || p.arg.content === "hidden") && exp.content === "false") continue;
let evaluated = evaluateConstant(exp);
if (evaluated != null) {
const arg = p.arg && p.arg.content;
if (arg === "hidden" && typeof evaluated === "number" && !(0, _vue_shared.includeBooleanAttr)(evaluated)) continue;
if (arg === "class") evaluated = (0, _vue_shared.normalizeClass)(evaluated);
else if (arg === "style") evaluated = (0, _vue_shared.stringifyStyle)((0, _vue_shared.normalizeStyle)(evaluated));
res += ` ${p.arg.content}="${(0, _vue_shared.escapeHtml)(evaluated)}"`;
}
} else if (p.name === "html") innerHTML = evaluateConstant(p.exp);
else if (p.name === "text") innerHTML = (0, _vue_shared.escapeHtml)((0, _vue_shared.toDisplayString)(evaluateConstant(p.exp)));
}
}
if (context.scopeId) res += ` ${context.scopeId}`;
res += `>`;
if (innerHTML) res += innerHTML;
else for (let i = 0; i < node.children.length; i++) res += stringifyNode(node.children[i], context);
if (!(0, _vue_shared.isVoidTag)(node.tag)) res += `</${node.tag}>`;
return res;
}
function evaluateConstant(exp) {
if (exp.type === 4) return new Function(`return (${exp.content})`)();
else {
let res = ``;
exp.children.forEach((c) => {
if ((0, _vue_shared.isString)(c) || (0, _vue_shared.isSymbol)(c)) return;
if (c.type === 2) res += c.content;
else if (c.type === 5) res += (0, _vue_shared.toDisplayString)(evaluateConstant(c.content));
else res += evaluateConstant(c);
});
return res;
}
}
//#endregion
//#region packages/compiler-dom/src/transforms/ignoreSideEffectTags.ts
const ignoreSideEffectTags = (node, context) => {
if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) context.removeNode();
};
//#endregion
//#region packages/compiler-dom/src/htmlNesting.ts
/**
* Copied from https://github.com/MananTank/validate-html-nesting
* with ISC license
*
* To avoid runtime dependency on validate-html-nesting
* This file should not change very often in the original repo
* but we may need to keep it up-to-date from time to time.
*/
/**
* returns true if given parent-child nesting is valid HTML
*/
function isValidHTMLNesting(parent, child) {
if (parent === "template") return true;
if (parent in onlyValidChildren) return onlyValidChildren[parent].has(child);
if (child in onlyValidParents) return onlyValidParents[child].has(parent);
if (parent in knownInvalidChildren) {
if (knownInvalidChildren[parent].has(child)) return false;
}
if (child in knownInvalidParents) {
if (knownInvalidParents[child].has(parent)) return false;
}
return true;
}
const headings = /* @__PURE__ */ new Set([
"h1",
"h2",
"h3",
"h4",
"h5",
"h6"
]);
const emptySet = /* @__PURE__ */ new Set([]);
/**
* maps element to set of elements that can be it's children, no other */
const onlyValidChildren = {
head: /* @__PURE__ */ new Set([
"base",
"basefront",
"bgsound",
"link",
"meta",
"title",
"noscript",
"noframes",
"style",
"script",
"template"
]),
optgroup: /* @__PURE__ */ new Set(["option"]),
select: /* @__PURE__ */ new Set([
"optgroup",
"option",
"hr"
]),
table: /* @__PURE__ */ new Set([
"caption",
"colgroup",
"tbody",
"tfoot",
"thead"
]),
tr: /* @__PURE__ */ new Set(["td", "th"]),
colgroup: /* @__PURE__ */ new Set(["col"]),
tbody: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["tr"]),
tfoot: /* @__PURE__ */ new Set(["tr"]),
script: emptySet,
iframe: emptySet,
option: emptySet,
textarea: emptySet,
style: emptySet,
title: emptySet
};
/** maps elements to set of elements which can be it's parent, no other */
const onlyValidParents = {
html: emptySet,
body: /* @__PURE__ */ new Set(["html"]),
head: /* @__PURE__ */ new Set(["html"]),
td: /* @__PURE__ */ new Set(["tr"]),
colgroup: /* @__PURE__ */ new Set(["table"]),
caption: /* @__PURE__ */ new Set(["table"]),
tbody: /* @__PURE__ */ new Set(["table"]),
tfoot: /* @__PURE__ */ new Set(["table"]),
col: /* @__PURE__ */ new Set(["colgroup"]),
th: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["table"]),
tr: /* @__PURE__ */ new Set([
"tbody",
"thead",
"tfoot"
]),
dd: /* @__PURE__ */ new Set(["dl", "div"]),
dt: /* @__PURE__ */ new Set(["dl", "div"]),
figcaption: /* @__PURE__ */ new Set(["figure"]),
summary: /* @__PURE__ */ new Set(["details"]),
area: /* @__PURE__ */ new Set(["map"])
};
/** maps element to set of elements that can not be it's children, others can */
const knownInvalidChildren = {
p: /* @__PURE__ */ new Set([
"address",
"article",
"aside",
"blockquote",
"center",
"details",
"dialog",
"dir",
"div",
"dl",
"fieldset",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"li",
"main",
"nav",
"menu",
"ol",
"p",
"pre",
"section",
"table",
"ul"
]),
svg: /* @__PURE__ */ new Set([
"b",
"blockquote",
"br",
"code",
"dd",
"div",
"dl",
"dt",
"em",
"embed",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"img",
"li",
"menu",
"meta",
"ol",
"p",
"pre",
"ruby",
"s",
"small",
"span",
"strong",
"sub",
"sup",
"table",
"u",
"ul",
"var"
])
};
/** maps element to set of elements that can not be it's parent, others can */
const knownInvalidParents = {
a: /* @__PURE__ */ new Set(["a"]),
button: /* @__PURE__ */ new Set(["button"]),
dd: /* @__PURE__ */ new Set(["dd", "dt"]),
dt: /* @__PURE__ */ new Set(["dd", "dt"]),
form: /* @__PURE__ */ new Set(["form"]),
li: /* @__PURE__ */ new Set(["li"]),
h1: headings,
h2: headings,
h3: headings,
h4: headings,
h5: headings,
h6: headings
};
//#endregion
//#region packages/compiler-dom/src/index.ts
const DOMNodeTransforms = [transformStyle, ...[]];
const DOMDirectiveTransforms = {
cloak: _vue_compiler_core.noopDirectiveTransform,
html: transformVHtml,
text: transformVText,
model: transformModel,
on: transformOn,
show: transformShow
};
function compile(src, options = {}) {
return (0, _vue_compiler_core.baseCompile)(src, (0, _vue_shared.extend)({}, parserOptions, options, {
nodeTransforms: [
ignoreSideEffectTags,
...DOMNodeTransforms,
...options.nodeTransforms || []
],
directiveTransforms: (0, _vue_shared.extend)({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
transformHoist: stringifyStatic
}));
}
function parse(template, options = {}) {
return (0, _vue_compiler_core.baseParse)(template, (0, _vue_shared.extend)({}, parserOptions, options));
}
//#endregion
exports.DOMDirectiveTransforms = DOMDirectiveTransforms;
exports.DOMErrorCodes = DOMErrorCodes;
exports.DOMErrorMessages = DOMErrorMessages;
exports.DOMNodeTransforms = DOMNodeTransforms;
exports.TRANSITION = TRANSITION;
exports.TRANSITION_GROUP = TRANSITION_GROUP;
exports.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX;
exports.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC;
exports.V_MODEL_RADIO = V_MODEL_RADIO;
exports.V_MODEL_SELECT = V_MODEL_SELECT;
exports.V_MODEL_TEXT = V_MODEL_TEXT;
exports.V_ON_WITH_KEYS = V_ON_WITH_KEYS;
exports.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS;
exports.V_SHOW = V_SHOW;
exports.compile = compile;
exports.createDOMCompilerError = createDOMCompilerError;
exports.isKeyboardEvent = isKeyboardEvent;
exports.isValidHTMLNesting = isValidHTMLNesting;
exports.parse = parse;
exports.parserOptions = parserOptions;
exports.postTransformTransition = postTransformTransition;
exports.resolveModifiers = resolveModifiers;
exports.transformStyle = transformStyle;
Object.keys(_vue_compiler_core).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function() {
return _vue_compiler_core[k];
}
});
});
+72
View File
@@ -0,0 +1,72 @@
import { CodegenResult, CompilerError, CompilerOptions, ComponentNode, DirectiveTransform, ExpressionNode, NodeTransform, ParserOptions, RootNode, SimpleExpressionNode, SourceLocation, TransformContext } from "@vue/compiler-core";
export * from "@vue/compiler-core";
//#region temp/packages/compiler-dom/src/parserOptions.d.ts
export declare const parserOptions: ParserOptions;
//#endregion
//#region temp/packages/compiler-dom/src/runtimeHelpers.d.ts
export declare const V_MODEL_RADIO: unique symbol;
export declare const V_MODEL_CHECKBOX: unique symbol;
export declare const V_MODEL_TEXT: unique symbol;
export declare const V_MODEL_SELECT: unique symbol;
export declare const V_MODEL_DYNAMIC: unique symbol;
export declare const V_ON_WITH_MODIFIERS: unique symbol;
export declare const V_ON_WITH_KEYS: unique symbol;
export declare const V_SHOW: unique symbol;
export declare const TRANSITION: unique symbol;
export declare const TRANSITION_GROUP: unique symbol;
//#endregion
//#region temp/packages/compiler-dom/src/transforms/transformStyle.d.ts
export declare const transformStyle: NodeTransform;
//#endregion
//#region temp/packages/compiler-dom/src/errors.d.ts
interface DOMCompilerError extends CompilerError {
code: DOMErrorCodes;
}
export declare function createDOMCompilerError(code: DOMErrorCodes, loc?: SourceLocation): DOMCompilerError;
export declare enum DOMErrorCodes {
X_V_HTML_NO_EXPRESSION = 54,
X_V_HTML_WITH_CHILDREN = 55,
X_V_TEXT_NO_EXPRESSION = 56,
X_V_TEXT_WITH_CHILDREN = 57,
X_V_MODEL_ON_INVALID_ELEMENT = 58,
X_V_MODEL_ARG_ON_ELEMENT = 59,
X_V_MODEL_ON_FILE_INPUT_ELEMENT = 60,
X_V_MODEL_UNNECESSARY_VALUE = 61,
X_V_SHOW_NO_EXPRESSION = 62,
X_TRANSITION_INVALID_CHILDREN = 63,
X_IGNORED_SIDE_EFFECT_TAG = 64,
__EXTEND_POINT__ = 65
}
export declare const DOMErrorMessages: Record<DOMErrorCodes, string>;
//#endregion
//#region temp/packages/compiler-dom/src/transforms/vOn.d.ts
export declare const isKeyboardEvent: (key: string) => boolean;
export declare const resolveModifiers: (key: ExpressionNode | string, modifiers: SimpleExpressionNode[], context: TransformContext | null, loc: SourceLocation) => {
keyModifiers: string[];
nonKeyModifiers: string[];
eventOptionModifiers: string[];
};
//#endregion
//#region temp/packages/compiler-dom/src/htmlNesting.d.ts
/**
* Copied from https://github.com/MananTank/validate-html-nesting
* with ISC license
*
* To avoid runtime dependency on validate-html-nesting
* This file should not change very often in the original repo
* but we may need to keep it up-to-date from time to time.
*/
/**
* returns true if given parent-child nesting is valid HTML
*/
export declare function isValidHTMLNesting(parent: string, child: string): boolean;
//#endregion
//#region temp/packages/compiler-dom/src/transforms/Transition.d.ts
export declare function postTransformTransition(node: ComponentNode, onError: (error: CompilerError) => void, hasMultipleChildren?: (node: ComponentNode) => boolean): () => void;
//#endregion
//#region temp/packages/compiler-dom/src/index.d.ts
export declare const DOMNodeTransforms: NodeTransform[];
export declare const DOMDirectiveTransforms: Record<string, DirectiveTransform>;
export declare function compile(src: string | RootNode, options?: CompilerOptions): CodegenResult;
export declare function parse(template: string, options?: ParserOptions): RootNode;
//#endregion
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+548
View File
@@ -0,0 +1,548 @@
/**
* @vue/compiler-dom v3.6.0-rc.10
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/
import { TO_DISPLAY_STRING, baseCompile, baseParse, checkCompatEnabled, createCallExpression, createCompilerError, createCompoundExpression, createObjectProperty, createSimpleExpression, findDir, findProp, getConstantType, hasDynamicKeyVBind, isCommentOrWhitespace, isStaticArgOf, isStaticExp, noopDirectiveTransform, registerRuntimeHelpers, transformModel, transformOn } from "@vue/compiler-core";
import { capitalize, extend, isHTMLTag, isMathMLTag, isSVGTag, isString, isVoidTag, makeMap, parseStringStyle } from "@vue/shared";
export * from "@vue/compiler-core";
//#region packages/compiler-dom/src/runtimeHelpers.ts
const V_MODEL_RADIO = Symbol(!!(process.env.NODE_ENV !== "production") ? `vModelRadio` : ``);
const V_MODEL_CHECKBOX = Symbol(!!(process.env.NODE_ENV !== "production") ? `vModelCheckbox` : ``);
const V_MODEL_TEXT = Symbol(!!(process.env.NODE_ENV !== "production") ? `vModelText` : ``);
const V_MODEL_SELECT = Symbol(!!(process.env.NODE_ENV !== "production") ? `vModelSelect` : ``);
const V_MODEL_DYNAMIC = Symbol(!!(process.env.NODE_ENV !== "production") ? `vModelDynamic` : ``);
const V_ON_WITH_MODIFIERS = Symbol(!!(process.env.NODE_ENV !== "production") ? `vOnModifiersGuard` : ``);
const V_ON_WITH_KEYS = Symbol(!!(process.env.NODE_ENV !== "production") ? `vOnKeysGuard` : ``);
const V_SHOW = Symbol(!!(process.env.NODE_ENV !== "production") ? `vShow` : ``);
const TRANSITION = Symbol(!!(process.env.NODE_ENV !== "production") ? `Transition` : ``);
const TRANSITION_GROUP = Symbol(!!(process.env.NODE_ENV !== "production") ? `TransitionGroup` : ``);
registerRuntimeHelpers({
[V_MODEL_RADIO]: `vModelRadio`,
[V_MODEL_CHECKBOX]: `vModelCheckbox`,
[V_MODEL_TEXT]: `vModelText`,
[V_MODEL_SELECT]: `vModelSelect`,
[V_MODEL_DYNAMIC]: `vModelDynamic`,
[V_ON_WITH_MODIFIERS]: `withModifiers`,
[V_ON_WITH_KEYS]: `withKeys`,
[V_SHOW]: `vShow`,
[TRANSITION]: `Transition`,
[TRANSITION_GROUP]: `TransitionGroup`
});
//#endregion
//#region packages/compiler-dom/src/decodeHtmlBrowser.ts
let decoder;
function decodeHtmlBrowser(raw, asAttr = false) {
if (!decoder) decoder = document.createElement("div");
if (asAttr) {
decoder.innerHTML = `<div foo="${raw.replace(/"/g, "&quot;")}">`;
return decoder.children[0].getAttribute("foo");
} else {
decoder.innerHTML = raw;
return decoder.textContent;
}
}
//#endregion
//#region packages/compiler-dom/src/parserOptions.ts
const parserOptions = {
parseMode: "html",
isVoidTag,
isNativeTag: (tag) => isHTMLTag(tag) || isSVGTag(tag) || isMathMLTag(tag),
isPreTag: (tag) => tag === "pre",
isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
decodeEntities: decodeHtmlBrowser,
isBuiltInComponent: (tag) => {
if (tag === "Transition" || tag === "transition") return TRANSITION;
else if (tag === "TransitionGroup" || tag === "transition-group") return TRANSITION_GROUP;
},
getNamespace(tag, parent, rootNamespace) {
let ns = parent ? parent.ns : rootNamespace;
if (parent && ns === 2) {
if (parent.tag === "annotation-xml") {
if (isSVGTag(tag)) return 1;
if (parent.props.some((a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml"))) ns = 0;
} else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") ns = 0;
} else if (parent && ns === 1) {
if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") ns = 0;
}
if (ns === 0) {
if (isSVGTag(tag)) return 1;
if (isMathMLTag(tag)) return 2;
}
return ns;
}
};
//#endregion
//#region packages/compiler-dom/src/transforms/transformStyle.ts
const transformStyle = (node) => {
if (node.type === 1) node.props.forEach((p, i) => {
if (p.type === 6 && p.name === "style" && p.value) node.props[i] = {
type: 7,
name: `bind`,
arg: createSimpleExpression(`style`, true, p.loc),
exp: parseInlineCSS(p.value.content, p.loc),
modifiers: [],
loc: p.loc
};
});
};
const parseInlineCSS = (cssText, loc) => {
const normalized = parseStringStyle(cssText);
return createSimpleExpression(JSON.stringify(normalized), false, loc, 3);
};
//#endregion
//#region packages/compiler-dom/src/errors.ts
function createDOMCompilerError(code, loc) {
return createCompilerError(code, loc, !!(process.env.NODE_ENV !== "production") || false ? DOMErrorMessages : void 0);
}
const DOMErrorCodes = {
"X_V_HTML_NO_EXPRESSION": 54,
"54": "X_V_HTML_NO_EXPRESSION",
"X_V_HTML_WITH_CHILDREN": 55,
"55": "X_V_HTML_WITH_CHILDREN",
"X_V_TEXT_NO_EXPRESSION": 56,
"56": "X_V_TEXT_NO_EXPRESSION",
"X_V_TEXT_WITH_CHILDREN": 57,
"57": "X_V_TEXT_WITH_CHILDREN",
"X_V_MODEL_ON_INVALID_ELEMENT": 58,
"58": "X_V_MODEL_ON_INVALID_ELEMENT",
"X_V_MODEL_ARG_ON_ELEMENT": 59,
"59": "X_V_MODEL_ARG_ON_ELEMENT",
"X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
"60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
"X_V_MODEL_UNNECESSARY_VALUE": 61,
"61": "X_V_MODEL_UNNECESSARY_VALUE",
"X_V_SHOW_NO_EXPRESSION": 62,
"62": "X_V_SHOW_NO_EXPRESSION",
"X_TRANSITION_INVALID_CHILDREN": 63,
"63": "X_TRANSITION_INVALID_CHILDREN",
"X_IGNORED_SIDE_EFFECT_TAG": 64,
"64": "X_IGNORED_SIDE_EFFECT_TAG",
"__EXTEND_POINT__": 65,
"65": "__EXTEND_POINT__"
};
const DOMErrorMessages = {
[54]: `v-html is missing expression.`,
[55]: `v-html will override element children.`,
[56]: `v-text is missing expression.`,
[57]: `v-text will override element children.`,
[58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
[59]: `v-model argument is not supported on plain elements.`,
[60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
[61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
[62]: `v-show is missing expression.`,
[63]: `<Transition> expects exactly one child element or component.`,
[64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`,
[65]: ``
};
//#endregion
//#region packages/compiler-dom/src/transforms/vHtml.ts
const transformVHtml = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(54, loc));
if (node.children.length) {
context.onError(createDOMCompilerError(55, loc));
node.children.length = 0;
}
return { props: [createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression("", true))] };
};
//#endregion
//#region packages/compiler-dom/src/transforms/vText.ts
const transformVText = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(56, loc));
if (node.children.length) {
context.onError(createDOMCompilerError(57, loc));
node.children.length = 0;
}
return { props: [createObjectProperty(createSimpleExpression(`textContent`, true), exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc) : createSimpleExpression("", true))] };
};
//#endregion
//#region packages/compiler-dom/src/transforms/vModel.ts
const transformModel$1 = (dir, node, context) => {
const baseResult = transformModel(dir, node, context);
if (!baseResult.props.length || node.tagType === 1) return baseResult;
if (dir.arg) context.onError(createDOMCompilerError(59, dir.arg.loc));
function checkDuplicatedValue() {
const value = findDir(node, "bind");
if (value && isStaticArgOf(value.arg, "value")) context.onError(createDOMCompilerError(61, value.loc));
}
const { tag } = node;
const isCustomElement = context.isCustomElement(tag);
if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
let directiveToUse = V_MODEL_TEXT;
let isInvalidType = false;
if (tag === "input" || isCustomElement) {
const type = findProp(node, `type`);
if (type) {
if (type.type === 7) directiveToUse = V_MODEL_DYNAMIC;
else if (type.value) switch (type.value.content) {
case "radio":
directiveToUse = V_MODEL_RADIO;
break;
case "checkbox":
directiveToUse = V_MODEL_CHECKBOX;
break;
case "file":
isInvalidType = true;
context.onError(createDOMCompilerError(60, dir.loc));
break;
default: process.env.NODE_ENV !== "production" && checkDuplicatedValue();
}
} else if (hasDynamicKeyVBind(node)) directiveToUse = V_MODEL_DYNAMIC;
else process.env.NODE_ENV !== "production" && checkDuplicatedValue();
} else if (tag === "select") directiveToUse = V_MODEL_SELECT;
else process.env.NODE_ENV !== "production" && checkDuplicatedValue();
if (!isInvalidType) baseResult.needRuntime = context.helper(directiveToUse);
} else context.onError(createDOMCompilerError(58, dir.loc));
baseResult.props = baseResult.props.filter((p) => !(p.key.type === 4 && p.key.content === "modelValue"));
return baseResult;
};
//#endregion
//#region packages/compiler-dom/src/transforms/vOn.ts
const isEventOptionModifier = /*@__PURE__*/ makeMap(`passive,once,capture`);
const isNonKeyModifier = /*@__PURE__*/ makeMap("stop,prevent,self,ctrl,shift,alt,meta,exact,middle");
const maybeKeyModifier = /*@__PURE__*/ makeMap("left,right");
const isKeyboardEvent = /*@__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`);
const resolveModifiers = (key, modifiers, context, loc) => {
const keyModifiers = [];
const nonKeyModifiers = [];
const eventOptionModifiers = [];
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i].content;
if (modifier === "delegate") {
if (context) {
const error = /* @__PURE__ */ new SyntaxError(`.delegate modifier is only supported in Vapor components.`);
error.loc = modifiers[i].loc;
context.onWarn(error);
}
continue;
}
if (modifier === "native" && context && checkCompatEnabled("COMPILER_V_ON_NATIVE", context, loc)) eventOptionModifiers.push(modifier);
else if (isEventOptionModifier(modifier)) eventOptionModifiers.push(modifier);
else {
const keyString = isString(key) ? key : isStaticExp(key) ? key.content : null;
if (maybeKeyModifier(modifier)) {
if (keyString) {
if (isKeyboardEvent(keyString.toLowerCase())) keyModifiers.push(modifier);
else nonKeyModifiers.push(modifier);
} else {
keyModifiers.push(modifier);
nonKeyModifiers.push(modifier);
}
} else if (isNonKeyModifier(modifier)) nonKeyModifiers.push(modifier);
else keyModifiers.push(modifier);
}
}
return {
keyModifiers,
nonKeyModifiers,
eventOptionModifiers
};
};
const transformClick = (key, event) => {
return isStaticExp(key) && key.content.toLowerCase() === "onclick" ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([
`(`,
key,
`) === "onClick" ? "${event}" : (`,
key,
`)`
]) : key;
};
const transformOn$1 = (dir, node, context) => {
return transformOn(dir, node, context, (baseResult) => {
const { modifiers } = dir;
if (!modifiers.length) return baseResult;
let { key, value: handlerExp } = baseResult.props[0];
const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
if (nonKeyModifiers.includes("right")) key = transformClick(key, `onContextmenu`);
if (nonKeyModifiers.includes("middle")) key = transformClick(key, `onMouseup`);
if (nonKeyModifiers.length) handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [handlerExp, JSON.stringify(nonKeyModifiers)]);
if (keyModifiers.length && (!isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [handlerExp, JSON.stringify(keyModifiers)]);
if (eventOptionModifiers.length) {
const modifierPostfix = eventOptionModifiers.map(capitalize).join("");
key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([
`(`,
key,
`) + "${modifierPostfix}"`
]);
}
return { props: [createObjectProperty(key, handlerExp)] };
});
};
//#endregion
//#region packages/compiler-dom/src/transforms/vShow.ts
const transformShow = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) context.onError(createDOMCompilerError(62, loc));
return {
props: [],
needRuntime: context.helper(V_SHOW)
};
};
//#endregion
//#region packages/compiler-dom/src/transforms/Transition.ts
const transformTransition = (node, context) => {
if (node.type === 1 && node.tagType === 1) {
if (context.isBuiltInComponent(node.tag) === TRANSITION) return postTransformTransition(node, context.onError);
}
};
function postTransformTransition(node, onError, hasMultipleChildren = defaultHasMultipleChildren) {
return () => {
if (!node.children.length) return;
if (hasMultipleChildren(node)) onError(createDOMCompilerError(63, {
start: node.children[0].loc.start,
end: node.children[node.children.length - 1].loc.end,
source: ""
}));
const child = node.children[0];
if (child.type === 1 && !findDir(child, "if")) {
for (const p of child.props) if (p.type === 7 && p.name === "show") node.props.push({
type: 6,
name: "persisted",
nameLoc: node.loc,
value: void 0,
loc: node.loc
});
}
};
}
function defaultHasMultipleChildren(node) {
const children = node.children = node.children.filter((c) => !isCommentOrWhitespace(c));
const child = children[0];
return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(defaultHasMultipleChildren);
}
//#endregion
//#region packages/compiler-dom/src/transforms/ignoreSideEffectTags.ts
const ignoreSideEffectTags = (node, context) => {
if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
process.env.NODE_ENV !== "production" && context.onError(createDOMCompilerError(64, node.loc));
context.removeNode();
}
};
//#endregion
//#region packages/compiler-dom/src/htmlNesting.ts
/**
* Copied from https://github.com/MananTank/validate-html-nesting
* with ISC license
*
* To avoid runtime dependency on validate-html-nesting
* This file should not change very often in the original repo
* but we may need to keep it up-to-date from time to time.
*/
/**
* returns true if given parent-child nesting is valid HTML
*/
function isValidHTMLNesting(parent, child) {
if (parent === "template") return true;
if (parent in onlyValidChildren) return onlyValidChildren[parent].has(child);
if (child in onlyValidParents) return onlyValidParents[child].has(parent);
if (parent in knownInvalidChildren) {
if (knownInvalidChildren[parent].has(child)) return false;
}
if (child in knownInvalidParents) {
if (knownInvalidParents[child].has(parent)) return false;
}
return true;
}
const headings = /* @__PURE__ */ new Set([
"h1",
"h2",
"h3",
"h4",
"h5",
"h6"
]);
const emptySet = /* @__PURE__ */ new Set([]);
/**
* maps element to set of elements that can be it's children, no other */
const onlyValidChildren = {
head: /* @__PURE__ */ new Set([
"base",
"basefront",
"bgsound",
"link",
"meta",
"title",
"noscript",
"noframes",
"style",
"script",
"template"
]),
optgroup: /* @__PURE__ */ new Set(["option"]),
select: /* @__PURE__ */ new Set([
"optgroup",
"option",
"hr"
]),
table: /* @__PURE__ */ new Set([
"caption",
"colgroup",
"tbody",
"tfoot",
"thead"
]),
tr: /* @__PURE__ */ new Set(["td", "th"]),
colgroup: /* @__PURE__ */ new Set(["col"]),
tbody: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["tr"]),
tfoot: /* @__PURE__ */ new Set(["tr"]),
script: emptySet,
iframe: emptySet,
option: emptySet,
textarea: emptySet,
style: emptySet,
title: emptySet
};
/** maps elements to set of elements which can be it's parent, no other */
const onlyValidParents = {
html: emptySet,
body: /* @__PURE__ */ new Set(["html"]),
head: /* @__PURE__ */ new Set(["html"]),
td: /* @__PURE__ */ new Set(["tr"]),
colgroup: /* @__PURE__ */ new Set(["table"]),
caption: /* @__PURE__ */ new Set(["table"]),
tbody: /* @__PURE__ */ new Set(["table"]),
tfoot: /* @__PURE__ */ new Set(["table"]),
col: /* @__PURE__ */ new Set(["colgroup"]),
th: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["table"]),
tr: /* @__PURE__ */ new Set([
"tbody",
"thead",
"tfoot"
]),
dd: /* @__PURE__ */ new Set(["dl", "div"]),
dt: /* @__PURE__ */ new Set(["dl", "div"]),
figcaption: /* @__PURE__ */ new Set(["figure"]),
summary: /* @__PURE__ */ new Set(["details"]),
area: /* @__PURE__ */ new Set(["map"])
};
/** maps element to set of elements that can not be it's children, others can */
const knownInvalidChildren = {
p: /* @__PURE__ */ new Set([
"address",
"article",
"aside",
"blockquote",
"center",
"details",
"dialog",
"dir",
"div",
"dl",
"fieldset",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"li",
"main",
"nav",
"menu",
"ol",
"p",
"pre",
"section",
"table",
"ul"
]),
svg: /* @__PURE__ */ new Set([
"b",
"blockquote",
"br",
"code",
"dd",
"div",
"dl",
"dt",
"em",
"embed",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"img",
"li",
"menu",
"meta",
"ol",
"p",
"pre",
"ruby",
"s",
"small",
"span",
"strong",
"sub",
"sup",
"table",
"u",
"ul",
"var"
])
};
/** maps element to set of elements that can not be it's parent, others can */
const knownInvalidParents = {
a: /* @__PURE__ */ new Set(["a"]),
button: /* @__PURE__ */ new Set(["button"]),
dd: /* @__PURE__ */ new Set(["dd", "dt"]),
dt: /* @__PURE__ */ new Set(["dd", "dt"]),
form: /* @__PURE__ */ new Set(["form"]),
li: /* @__PURE__ */ new Set(["li"]),
h1: headings,
h2: headings,
h3: headings,
h4: headings,
h5: headings,
h6: headings
};
//#endregion
//#region packages/compiler-dom/src/transforms/validateHtmlNesting.ts
const validateHtmlNesting = (node, context) => {
if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) {
const error = /* @__PURE__ */ new SyntaxError(`<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.`);
error.loc = node.loc;
context.onWarn(error);
}
};
//#endregion
//#region packages/compiler-dom/src/index.ts
const DOMNodeTransforms = [transformStyle, ...!!(process.env.NODE_ENV !== "production") ? [transformTransition, validateHtmlNesting] : []];
const DOMDirectiveTransforms = {
cloak: noopDirectiveTransform,
html: transformVHtml,
text: transformVText,
model: transformModel$1,
on: transformOn$1,
show: transformShow
};
function compile(src, options = {}) {
return baseCompile(src, extend({}, parserOptions, options, {
nodeTransforms: [
ignoreSideEffectTags,
...DOMNodeTransforms,
...options.nodeTransforms || []
],
directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
transformHoist: null
}));
}
function parse(template, options = {}) {
return baseParse(template, extend({}, parserOptions, options));
}
//#endregion
export { DOMDirectiveTransforms, DOMErrorCodes, DOMErrorMessages, DOMNodeTransforms, TRANSITION, TRANSITION_GROUP, V_MODEL_CHECKBOX, V_MODEL_DYNAMIC, V_MODEL_RADIO, V_MODEL_SELECT, V_MODEL_TEXT, V_ON_WITH_KEYS, V_ON_WITH_MODIFIERS, V_SHOW, compile, createDOMCompilerError, isKeyboardEvent, isValidHTMLNesting, parse, parserOptions, postTransformTransition, resolveModifiers, transformStyle };
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+7
View File
@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/compiler-dom.cjs.prod.js')
} else {
module.exports = require('./dist/compiler-dom.cjs.js')
}
+57
View File
@@ -0,0 +1,57 @@
{
"name": "@vue/compiler-dom",
"version": "3.6.0-rc.10",
"description": "@vue/compiler-dom",
"main": "index.js",
"module": "dist/compiler-dom.esm-bundler.js",
"types": "dist/compiler-dom.d.ts",
"unpkg": "dist/compiler-dom.global.js",
"jsdelivr": "dist/compiler-dom.global.js",
"files": [
"index.js",
"dist"
],
"exports": {
".": {
"types": "./dist/compiler-dom.d.ts",
"node": {
"production": "./dist/compiler-dom.cjs.prod.js",
"development": "./dist/compiler-dom.cjs.js",
"default": "./index.js"
},
"module": "./dist/compiler-dom.esm-bundler.js",
"import": "./dist/compiler-dom.esm-bundler.js",
"require": "./index.js"
},
"./*": "./*"
},
"sideEffects": false,
"buildOptions": {
"name": "VueCompilerDOM",
"compat": true,
"formats": [
"esm-bundler",
"esm-browser",
"cjs",
"global"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-dom"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-dom#readme",
"dependencies": {
"@vue/shared": "3.6.0-rc.10",
"@vue/compiler-core": "3.6.0-rc.10"
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
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.
+79
View File
@@ -0,0 +1,79 @@
# @vue/compiler-sfc
> Lower level utilities for compiling Vue Single File Components
**Note: as of 3.2.13+, this package is included as a dependency of the main `vue` package and can be accessed as `vue/compiler-sfc`. This means you no longer need to explicitly install this package and ensure its version matches that of `vue`'s. Just use the main `vue/compiler-sfc` deep import instead.**
This package contains lower level utilities that you can use if you are writing a plugin / transform for a bundler or module system that compiles Vue Single File Components (SFCs) into JavaScript. It is used in [vue-loader](https://github.com/vuejs/vue-loader) and [@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue).
## API
The API is intentionally low-level due to the various considerations when integrating Vue SFCs in a build system:
- Separate hot-module replacement (HMR) for script, template and styles
- template updates should not reset component state
- style updates should be performed without component re-render
- Leveraging the tool's plugin system for pre-processor handling. e.g. `<style lang="scss">` should be processed by the corresponding webpack loader.
- In some cases, transformers of each block in an SFC do not share the same execution context. For example, when used with `thread-loader` or other parallelized configurations, the template sub-loader in `vue-loader` may not have access to the full SFC and its descriptor.
The general idea is to generate a facade module that imports the individual blocks of the component. The trick is the module imports itself with different query strings so that the build system can handle each request as "virtual" modules:
```
+--------------------+
| |
| script transform |
+----->+ |
| +--------------------+
|
+--------------------+ | +--------------------+
| | | | |
| facade transform +----------->+ template transform |
| | | | |
+--------------------+ | +--------------------+
|
| +--------------------+
+----->+ |
| style transform |
| |
+--------------------+
```
Where the facade module looks like this:
```js
// main script
import script from '/project/foo.vue?vue&type=script'
// template compiled to render function
import { render } from '/project/foo.vue?vue&type=template&id=xxxxxx'
// css
import '/project/foo.vue?vue&type=style&index=0&id=xxxxxx'
// attach render function to script
script.render = render
// attach additional metadata
// some of these should be dev only
script.__file = 'example.vue'
script.__scopeId = 'xxxxxx'
// additional tooling-specific HMR handling code
// using __VUE_HMR_API__ global
export default script
```
### High Level Workflow
1. In facade transform, parse the source into descriptor with the `parse` API and generate the above facade module code based on the descriptor;
2. In script transform, use `compileScript` to process the script. This handles features like `<script setup>` and CSS variable injection. Alternatively, this can be done directly in the facade module (with the code inlined instead of imported), but it will require rewriting `export default` to a temp variable (a `rewriteDefault` convenience API is provided for this purpose) so additional options can be attached to the exported object.
3. In template transform, use `compileTemplate` to compile the raw template into render function code.
4. In style transform, use `compileStyle` to compile raw CSS to handle `<style scoped>`, `<style module>` and CSS variable injection.
Options needed for these APIs can be passed via the query string.
For detailed API references and options, check out the source type definitions. For actual usage of these APIs, check out [@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue) or [vue-loader](https://github.com/vuejs/vue-loader/tree/next).
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+68
View File
@@ -0,0 +1,68 @@
{
"name": "@vue/compiler-sfc",
"version": "3.6.0-rc.10",
"description": "@vue/compiler-sfc",
"main": "dist/compiler-sfc.cjs.js",
"module": "dist/compiler-sfc.esm-browser.js",
"types": "dist/compiler-sfc.d.ts",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/compiler-sfc.d.ts",
"node": "./dist/compiler-sfc.cjs.js",
"module": "./dist/compiler-sfc.esm-browser.js",
"import": "./dist/compiler-sfc.esm-browser.js",
"require": "./dist/compiler-sfc.cjs.js"
},
"./*": "./*"
},
"buildOptions": {
"name": "VueCompilerSFC",
"formats": [
"cjs",
"esm-browser"
],
"prod": false,
"enableNonBrowserBranches": true
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-sfc"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-sfc#readme",
"dependencies": {
"@babel/parser": "^7.29.8",
"@vue/compiler-core": "3.6.0-rc.10",
"@vue/compiler-dom": "3.6.0-rc.10",
"@vue/compiler-ssr": "3.6.0-rc.10",
"@vue/compiler-vapor": "3.6.0-rc.10",
"@vue/shared": "3.6.0-rc.10",
"estree-walker": "^2.0.2",
"magic-string": "^0.30.21",
"postcss": "^8.5.28",
"source-map-js": "^1.2.1"
},
"devDependencies": {
"@babel/types": "^7.29.8",
"@vue/consolidate": "^1.0.0",
"hash-sum": "^2.0.0",
"lru-cache": "10.1.0",
"merge-source-map": "^1.1.0",
"minimatch": "~10.2.6",
"postcss-modules": "^6.0.1",
"postcss-selector-parser": "^7.1.6",
"pug": "^3.0.4",
"sass": "^1.104.1"
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
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.
+1
View File
@@ -0,0 +1 @@
# @vue/compiler-ssr
+870
View File
@@ -0,0 +1,870 @@
/**
* @vue/compiler-ssr v3.6.0-rc.10
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _vue_compiler_dom = require("@vue/compiler-dom");
let _vue_shared = require("@vue/shared");
//#region packages/compiler-ssr/src/runtimeHelpers.ts
const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`);
const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`);
const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`);
const ssrHelpers = {
[SSR_INTERPOLATE]: `ssrInterpolate`,
[SSR_RENDER_VNODE]: `ssrRenderVNode`,
[SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
[SSR_RENDER_SLOT]: `ssrRenderSlot`,
[SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
[SSR_RENDER_CLASS]: `ssrRenderClass`,
[SSR_RENDER_STYLE]: `ssrRenderStyle`,
[SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
[SSR_RENDER_ATTR]: `ssrRenderAttr`,
[SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
[SSR_RENDER_LIST]: `ssrRenderList`,
[SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
[SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
[SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
[SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
[SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
[SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
[SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
[SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
};
(0, _vue_compiler_dom.registerRuntimeHelpers)(ssrHelpers);
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrVIf.ts
const ssrTransformIf = (0, _vue_compiler_dom.createStructuralDirectiveTransform)(/^(?:if|else|else-if)$/, _vue_compiler_dom.processIf);
function ssrProcessIf(node, context, disableNestedFragments = false, disableComment = false) {
const [rootBranch] = node.branches;
const ifStatement = (0, _vue_compiler_dom.createIfStatement)(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
context.pushStatement(ifStatement);
let currentIf = ifStatement;
for (let i = 1; i < node.branches.length; i++) {
const branch = node.branches[i];
const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
if (branch.condition) currentIf = currentIf.alternate = (0, _vue_compiler_dom.createIfStatement)(branch.condition, branchBlockStatement);
else currentIf.alternate = branchBlockStatement;
}
if (!currentIf.alternate && (!disableComment || context.options.vapor)) currentIf.alternate = (0, _vue_compiler_dom.createBlockStatement)([(0, _vue_compiler_dom.createCallExpression)(`_push`, ["`<!---->`"])]);
}
function processIfBranch(branch, context, disableNestedFragments = false) {
const { children } = branch;
return processChildrenAsStatement(branch, context, !disableNestedFragments && (children.length !== 1 || children[0].type !== 1) && !(children.length === 1 && children[0].type === 11));
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrVFor.ts
const ssrTransformFor = (0, _vue_compiler_dom.createStructuralDirectiveTransform)("for", _vue_compiler_dom.processFor);
function ssrProcessFor(node, context, disableNestedFragments = false) {
const needFragmentWrapper = !disableNestedFragments && (node.children.length !== 1 || node.children[0].type !== 1);
const renderLoop = (0, _vue_compiler_dom.createFunctionExpression)((0, _vue_compiler_dom.createForLoopParams)(node.parseResult));
renderLoop.body = processChildrenAsStatement(node, context, needFragmentWrapper);
if (!disableNestedFragments) context.pushStringPart(`<!--[-->`);
context.pushStatement((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_LIST), [node.source, renderLoop]));
if (!disableNestedFragments) context.pushStringPart(`<!--]-->`);
}
//#endregion
//#region packages/compiler-ssr/src/errors.ts
function createSSRCompilerError(code, loc) {
return (0, _vue_compiler_dom.createCompilerError)(code, loc, SSRErrorMessages);
}
const SSRErrorMessages = {
[65]: `Unsafe attribute name for SSR.`,
[66]: `Missing the 'to' prop on teleport element.`,
[67]: `Invalid AST node during SSR transform.`
};
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrTransformTeleport.ts
function ssrProcessTeleport(node, context) {
const targetProp = (0, _vue_compiler_dom.findProp)(node, "to");
if (!targetProp) {
context.onError(createSSRCompilerError(66, node.loc));
return;
}
let target;
if (targetProp.type === 6) target = targetProp.value && (0, _vue_compiler_dom.createSimpleExpression)(targetProp.value.content, true);
else target = targetProp.exp;
if (!target) {
context.onError(createSSRCompilerError(66, targetProp.loc));
return;
}
const disabledProp = (0, _vue_compiler_dom.findProp)(node, "disabled", false, true);
const disabled = disabledProp ? disabledProp.type === 6 ? `true` : disabledProp.exp || `false` : `false`;
const contentRenderFn = (0, _vue_compiler_dom.createFunctionExpression)([`_push`], void 0, true, false, node.loc);
contentRenderFn.body = processChildrenAsStatement(node, context);
context.pushStatement((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_TELEPORT), [
`_push`,
contentRenderFn,
target,
disabled,
`_parent`
]));
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrTransformSuspense.ts
const wipMap$3 = /* @__PURE__ */ new WeakMap();
function ssrTransformSuspense(node, context) {
return () => {
if (node.children.length) {
const wipEntry = {
slotsExp: null,
wipSlots: []
};
wipMap$3.set(node, wipEntry);
wipEntry.slotsExp = (0, _vue_compiler_dom.buildSlots)(node, context, (_props, _vForExp, children, loc) => {
const fn = (0, _vue_compiler_dom.createFunctionExpression)([], void 0, true, false, loc);
wipEntry.wipSlots.push({
fn,
children
});
return fn;
}).slots;
}
};
}
function ssrProcessSuspense(node, context) {
const wipEntry = wipMap$3.get(node);
if (!wipEntry) return;
const { slotsExp, wipSlots } = wipEntry;
for (let i = 0; i < wipSlots.length; i++) {
const slot = wipSlots[i];
slot.fn.body = processChildrenAsStatement(slot, context);
}
context.pushStatement((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_SUSPENSE), [`_push`, slotsExp]));
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrTransformElement.ts
const rawChildrenMap = /* @__PURE__ */ new WeakMap();
const ssrTransformElement = (node, context) => {
if (node.type !== 1 || node.tagType !== 0) return;
return function ssrPostTransformElement() {
const openTag = [`<${node.tag}`];
const needTagForRuntime = node.tag === "textarea" || node.tag.indexOf("-") > 0;
const hasDynamicVBind = (0, _vue_compiler_dom.hasDynamicKeyVBind)(node);
const hasCustomDir = node.props.some((p) => p.type === 7 && !(0, _vue_shared.isBuiltInDirective)(p.name));
const vShowPropIndex = node.props.findIndex((i) => i.type === 7 && i.name === "show");
if (vShowPropIndex !== -1) {
const vShowProp = node.props[vShowPropIndex];
node.props.splice(vShowPropIndex, 1);
node.props.push(vShowProp);
}
const needMergeProps = hasDynamicVBind || hasCustomDir;
if (needMergeProps) {
const { props, directives } = (0, _vue_compiler_dom.buildProps)(node, context, node.props, false, false, true);
if (props || directives.length) {
const mergedProps = buildSSRProps(props, directives, context);
const propsExp = (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_ATTRS), [mergedProps]);
if (node.tag === "textarea") {
const existingText = node.children[0];
if (!hasContentOverrideDirective(node) && (!existingText || existingText.type !== 5)) {
const tempId = `_temp${context.temps++}`;
propsExp.arguments = [(0, _vue_compiler_dom.createAssignmentExpression)((0, _vue_compiler_dom.createSimpleExpression)(tempId, false), mergedProps)];
rawChildrenMap.set(node, (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_INTERPOLATE), [(0, _vue_compiler_dom.createConditionalExpression)((0, _vue_compiler_dom.createSimpleExpression)(`"value" in ${tempId}`, false), (0, _vue_compiler_dom.createSimpleExpression)(`${tempId}.value`, false), (0, _vue_compiler_dom.createSimpleExpression)(existingText ? existingText.content : ``, true), false)]));
}
} else if (node.tag === "input") {
const vModel = findVModel(node);
if (vModel) {
const tempId = `_temp${context.temps++}`;
const tempExp = (0, _vue_compiler_dom.createSimpleExpression)(tempId, false);
propsExp.arguments = [(0, _vue_compiler_dom.createSequenceExpression)([(0, _vue_compiler_dom.createAssignmentExpression)(tempExp, mergedProps), (0, _vue_compiler_dom.createCallExpression)(context.helper(_vue_compiler_dom.MERGE_PROPS), [tempExp, (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [tempExp, vModel.exp])])])];
}
} else if (directives.length && !node.children.length) {
if (!hasContentOverrideDirective(node)) {
const tempId = `_temp${context.temps++}`;
propsExp.arguments = [(0, _vue_compiler_dom.createAssignmentExpression)((0, _vue_compiler_dom.createSimpleExpression)(tempId, false), mergedProps)];
rawChildrenMap.set(node, (0, _vue_compiler_dom.createConditionalExpression)((0, _vue_compiler_dom.createSimpleExpression)(`"textContent" in ${tempId}`, false), (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_INTERPOLATE), [(0, _vue_compiler_dom.createSimpleExpression)(`${tempId}.textContent`, false)]), (0, _vue_compiler_dom.createSimpleExpression)(`${tempId}.innerHTML ?? ''`, false), false));
}
}
if (needTagForRuntime) propsExp.arguments.push(`"${node.tag}"`);
openTag.push(propsExp);
}
}
let dynamicClassBinding = void 0;
let staticClassBinding = void 0;
let dynamicStyleBinding = void 0;
for (let i = 0; i < node.props.length; i++) {
const prop = node.props[i];
if (node.tag === "input" && isTrueFalseValue(prop)) continue;
if (prop.type === 7) {
if (prop.name === "html" && prop.exp) rawChildrenMap.set(node, (0, _vue_compiler_dom.createCompoundExpression)([
`(`,
prop.exp,
`) ?? ''`
]));
else if (prop.name === "text" && prop.exp) node.children = [(0, _vue_compiler_dom.createInterpolation)(prop.exp, prop.loc)];
else if (prop.name === "slot") context.onError((0, _vue_compiler_dom.createCompilerError)(40, prop.loc));
else if (isTextareaWithValue(node, prop) && prop.exp) {
if (!needMergeProps) node.children = [(0, _vue_compiler_dom.createInterpolation)(prop.exp, prop.loc)];
} else if (!needMergeProps && prop.name !== "on") {
const directiveTransform = context.directiveTransforms[prop.name];
if (directiveTransform) {
const { props, ssrTagParts } = directiveTransform(prop, node, context);
if (ssrTagParts) openTag.push(...ssrTagParts);
for (let j = 0; j < props.length; j++) {
const { key, value } = props[j];
if ((0, _vue_compiler_dom.isStaticExp)(key)) {
let attrName = key.content;
if (attrName === "key" || attrName === "ref") continue;
if (attrName === "class") openTag.push(` class="`, dynamicClassBinding = (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_CLASS), [value]), `"`);
else if (attrName === "style") {
if (dynamicStyleBinding) mergeCall(dynamicStyleBinding, value);
else openTag.push(` style="`, dynamicStyleBinding = (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_STYLE), [value]), `"`);
} else {
attrName = node.tag.indexOf("-") > 0 ? attrName : _vue_shared.propsToAttrMap[attrName] || attrName.toLowerCase();
if ((0, _vue_shared.isBooleanAttr)(attrName)) openTag.push((0, _vue_compiler_dom.createConditionalExpression)((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [value]), (0, _vue_compiler_dom.createSimpleExpression)(" " + attrName, true), (0, _vue_compiler_dom.createSimpleExpression)("", true), false));
else if (attrName === "hidden") openTag.push((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_DYNAMIC_ATTR), [key, value]));
else if ((0, _vue_shared.isSSRSafeAttrName)(attrName)) openTag.push((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_ATTR), [key, value]));
else context.onError(createSSRCompilerError(65, key.loc));
}
} else {
const args = [key, value];
if (needTagForRuntime) args.push(`"${node.tag}"`);
openTag.push((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
}
}
}
}
} else {
const name = prop.name;
if (node.tag === "textarea" && name === "value" && prop.value) rawChildrenMap.set(node, (0, _vue_shared.escapeHtml)(prop.value.content));
else if (!needMergeProps) {
if (name === "key" || name === "ref") continue;
if (name === "class" && prop.value) staticClassBinding = JSON.stringify(prop.value.content);
openTag.push(` ${prop.name}` + (prop.value ? `="${(0, _vue_shared.escapeHtml)(prop.value.content)}"` : ``));
}
}
}
if (dynamicClassBinding && staticClassBinding) {
mergeCall(dynamicClassBinding, staticClassBinding);
removeStaticBinding(openTag, "class");
}
if (context.scopeId) openTag.push(` ${context.scopeId}`);
node.ssrCodegenNode = (0, _vue_compiler_dom.createTemplateLiteral)(openTag);
};
};
function buildSSRProps(props, directives, context) {
let mergePropsArgs = [];
if (props) {
if (props.type === 14) mergePropsArgs = props.arguments;
else mergePropsArgs.push(props);
}
if (directives.length) for (const dir of directives) mergePropsArgs.push((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_GET_DIRECTIVE_PROPS), [`_ctx`, ...(0, _vue_compiler_dom.buildDirectiveArgs)(dir, context).elements]));
return mergePropsArgs.length > 1 ? (0, _vue_compiler_dom.createCallExpression)(context.helper(_vue_compiler_dom.MERGE_PROPS), mergePropsArgs) : mergePropsArgs[0];
}
function isTrueFalseValue(prop) {
if (prop.type === 7) return prop.name === "bind" && prop.arg && (0, _vue_compiler_dom.isStaticExp)(prop.arg) && (prop.arg.content === "true-value" || prop.arg.content === "false-value");
else return prop.name === "true-value" || prop.name === "false-value";
}
function isTextareaWithValue(node, prop) {
return !!(node.tag === "textarea" && prop.name === "bind" && (0, _vue_compiler_dom.isStaticArgOf)(prop.arg, "value"));
}
function mergeCall(call, arg) {
const existing = call.arguments[0];
if (existing.type === 17) existing.elements.push(arg);
else call.arguments[0] = (0, _vue_compiler_dom.createArrayExpression)([existing, arg]);
}
function removeStaticBinding(tag, binding) {
const regExp = new RegExp(`^ ${binding}=".+"$`);
const i = tag.findIndex((e) => typeof e === "string" && regExp.test(e));
if (i > -1) tag.splice(i, 1);
}
function findVModel(node) {
return node.props.find((p) => p.type === 7 && p.name === "model" && p.exp);
}
function hasContentOverrideDirective(node) {
return !!(0, _vue_compiler_dom.findDir)(node, "text") || !!(0, _vue_compiler_dom.findDir)(node, "html");
}
function ssrProcessElement(node, context) {
const isVoidTag = context.options.isVoidTag || _vue_shared.NO;
const elementsToAdd = node.ssrCodegenNode.elements;
for (let j = 0; j < elementsToAdd.length; j++) context.pushStringPart(elementsToAdd[j]);
if (context.withSlotScopeId) context.pushStringPart((0, _vue_compiler_dom.createSimpleExpression)(`_scopeId`, false));
context.pushStringPart(`>`);
const rawChildren = rawChildrenMap.get(node);
if (rawChildren) context.pushStringPart(rawChildren);
else if (node.children.length) processChildren(node, context);
if (!isVoidTag(node.tag)) context.pushStringPart(`</${node.tag}>`);
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrTransformTransitionGroup.ts
const wipMap$2 = /* @__PURE__ */ new WeakMap();
function ssrTransformTransitionGroup(node, context) {
return () => {
const tag = (0, _vue_compiler_dom.findProp)(node, "tag");
if (tag) {
const otherProps = node.props.filter((p) => p !== tag);
const { props, directives } = (0, _vue_compiler_dom.buildProps)(node, context, otherProps, true, false, true);
let propsExp = null;
if (props || directives.length) propsExp = (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_ATTRS), [buildSSRProps(props, directives, context)]);
wipMap$2.set(node, {
tag,
propsExp,
scopeId: context.scopeId || null
});
}
};
}
function ssrProcessTransitionGroup(node, context) {
const entry = wipMap$2.get(node);
const disableNestedFragments = !context.options.vapor;
if (entry) {
const { tag, propsExp, scopeId } = entry;
if (tag.type === 7) {
context.pushStringPart(`<`);
context.pushStringPart(tag.exp);
if (propsExp) context.pushStringPart(propsExp);
if (scopeId) context.pushStringPart(` ${scopeId}`);
context.pushStringPart(`>`);
processChildren(
node,
context,
false,
/**
* TransitionGroup has the special runtime behavior of flattening and
* concatenating all children into a single fragment (in order for them to
* be patched using the same key map) so we need to account for that here
* by disabling nested fragment wrappers from being generated.
*/
disableNestedFragments,
/**
* TransitionGroup filters out comment children at runtime and thus
* doesn't expect comments to be present during hydration. We need to
* account for that by disabling the empty comment that is otherwise
* rendered for a falsy v-if that has no v-else specified. (#6715)
*/
true
);
context.pushStringPart(`</`);
context.pushStringPart(tag.exp);
context.pushStringPart(`>`);
} else {
context.pushStringPart(`<${tag.value.content}`);
if (propsExp) context.pushStringPart(propsExp);
if (scopeId) context.pushStringPart(` ${scopeId}`);
context.pushStringPart(`>`);
processChildren(node, context, false, disableNestedFragments, true);
context.pushStringPart(`</${tag.value.content}>`);
}
} else processChildren(node, context, true, disableNestedFragments, true);
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrTransformTransition.ts
const wipMap$1 = /* @__PURE__ */ new WeakMap();
function ssrTransformTransition(node, context) {
return () => {
const appear = (0, _vue_compiler_dom.findProp)(node, "appear", false, true);
wipMap$1.set(node, !!appear);
};
}
function ssrProcessTransition(node, context) {
node.children = node.children.filter((c) => c.type !== 3);
if (wipMap$1.get(node)) {
context.pushStringPart(`<template>`);
processChildren(node, context, false, true);
context.pushStringPart(`</template>`);
} else processChildren(node, context, false, true);
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrTransformComponent.ts
const wipMap = /* @__PURE__ */ new WeakMap();
const WIP_SLOT = Symbol();
const componentTypeMap = /* @__PURE__ */ new WeakMap();
const ssrTransformComponent = (node, context) => {
if (node.type !== 1 || node.tagType !== 1) return;
const component = (0, _vue_compiler_dom.resolveComponentType)(node, context, true);
const isDynamicComponent = (0, _vue_shared.isObject)(component) && component.callee === _vue_compiler_dom.RESOLVE_DYNAMIC_COMPONENT;
componentTypeMap.set(node, component);
if ((0, _vue_shared.isSymbol)(component)) {
if (component === _vue_compiler_dom.SUSPENSE) return ssrTransformSuspense(node, context);
else if (component === _vue_compiler_dom.TRANSITION_GROUP) return ssrTransformTransitionGroup(node, context);
else if (component === _vue_compiler_dom.TRANSITION) return ssrTransformTransition(node, context);
return;
}
const vnodeBranches = [];
const clonedNode = clone(node);
return function ssrPostTransformComponent() {
if (clonedNode.children.length) (0, _vue_compiler_dom.buildSlots)(clonedNode, context, (props, vFor, children) => {
vnodeBranches.push(createVNodeSlotBranch(props, vFor, children, context));
return (0, _vue_compiler_dom.createFunctionExpression)(void 0);
});
let propsExp = `null`;
if (node.props.length) {
const { props, directives } = (0, _vue_compiler_dom.buildProps)(node, context, void 0, true, isDynamicComponent);
if (props || directives.length) propsExp = buildSSRProps(props, directives, context);
}
const wipEntries = [];
wipMap.set(node, wipEntries);
const buildSSRSlotFn = (props, _vForExp, children, loc) => {
const param0 = props && (0, _vue_compiler_dom.stringifyExpression)(props) || `_`;
const fn = (0, _vue_compiler_dom.createFunctionExpression)([
param0,
`_push`,
`_parent`,
`_scopeId`
], void 0, true, true, loc);
wipEntries.push({
type: WIP_SLOT,
fn,
children,
vnodeBranch: vnodeBranches[wipEntries.length]
});
return fn;
};
const slots = node.children.length ? (0, _vue_compiler_dom.buildSlots)(node, context, buildSSRSlotFn).slots : `null`;
if (typeof component !== "string") node.ssrCodegenNode = (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_VNODE), [
`_push`,
(0, _vue_compiler_dom.createCallExpression)(context.helper(_vue_compiler_dom.CREATE_VNODE), [
component,
propsExp,
slots
]),
`_parent`
]);
else node.ssrCodegenNode = (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_COMPONENT), [
component,
propsExp,
slots,
`_parent`
]);
};
};
function ssrProcessComponent(node, context, parent) {
const component = componentTypeMap.get(node);
if (!node.ssrCodegenNode) {
if (component === _vue_compiler_dom.TELEPORT) return ssrProcessTeleport(node, context);
else if (component === _vue_compiler_dom.SUSPENSE) return ssrProcessSuspense(node, context);
else if (component === _vue_compiler_dom.TRANSITION_GROUP) return ssrProcessTransitionGroup(node, context);
else {
if (parent.type === WIP_SLOT) context.pushStringPart(``);
if (component === _vue_compiler_dom.TRANSITION) return ssrProcessTransition(node, context);
processChildren(node, context);
}
} else {
const wipEntries = wipMap.get(node) || [];
for (let i = 0; i < wipEntries.length; i++) {
const { fn, vnodeBranch } = wipEntries[i];
fn.body = (0, _vue_compiler_dom.createIfStatement)((0, _vue_compiler_dom.createSimpleExpression)(`_push`, false), processChildrenAsStatement(wipEntries[i], context, false, true), vnodeBranch);
}
if (context.withSlotScopeId) node.ssrCodegenNode.arguments.push(`_scopeId`);
if (typeof component === "string") context.pushStatement((0, _vue_compiler_dom.createCallExpression)(`_push`, [node.ssrCodegenNode]));
else context.pushStatement(node.ssrCodegenNode);
}
}
const rawOptionsMap = /* @__PURE__ */ new WeakMap();
const [baseNodeTransforms, baseDirectiveTransforms] = (0, _vue_compiler_dom.getBaseTransformPreset)(true);
const vnodeNodeTransforms = [...baseNodeTransforms, ..._vue_compiler_dom.DOMNodeTransforms];
const vnodeDirectiveTransforms = {
...baseDirectiveTransforms,
..._vue_compiler_dom.DOMDirectiveTransforms
};
function createVNodeSlotBranch(slotProps, vFor, children, parentContext) {
const rawOptions = rawOptionsMap.get(parentContext.root);
const subOptions = {
...rawOptions,
nodeTransforms: [...vnodeNodeTransforms, ...rawOptions.nodeTransforms || []],
directiveTransforms: {
...vnodeDirectiveTransforms,
...rawOptions.directiveTransforms || {}
}
};
const wrapperProps = [];
if (slotProps) wrapperProps.push({
type: 7,
name: "slot",
exp: slotProps,
arg: void 0,
modifiers: [],
loc: _vue_compiler_dom.locStub
});
if (vFor) wrapperProps.push((0, _vue_shared.extend)({}, vFor));
subTransform({
type: 1,
ns: 0,
tag: "template",
tagType: 3,
props: wrapperProps,
children,
loc: _vue_compiler_dom.locStub,
codegenNode: void 0
}, subOptions, parentContext);
return (0, _vue_compiler_dom.createReturnStatement)(children);
}
function subTransform(node, options, parentContext) {
const childRoot = (0, _vue_compiler_dom.createRoot)([node]);
const childContext = (0, _vue_compiler_dom.createTransformContext)(childRoot, options);
childContext.ssr = false;
childContext.scopes = { ...parentContext.scopes };
childContext.identifiers = { ...parentContext.identifiers };
childContext.identifierScopes = Object.create(null);
for (const name in parentContext.identifierScopes) childContext.identifierScopes[name] = parentContext.identifierScopes[name].slice();
childContext.imports = parentContext.imports;
(0, _vue_compiler_dom.traverseNode)(childRoot, childContext);
[
"helpers",
"components",
"directives"
].forEach((key) => {
childContext[key].forEach((value, helperKey) => {
if (key === "helpers") {
const parentCount = parentContext.helpers.get(helperKey);
if (parentCount === void 0) parentContext.helpers.set(helperKey, value);
else parentContext.helpers.set(helperKey, value + parentCount);
} else parentContext[key].add(value);
});
});
}
function clone(v) {
if ((0, _vue_shared.isArray)(v)) return v.map(clone);
else if ((0, _vue_shared.isPlainObject)(v)) {
const res = {};
for (const key in v) res[key] = clone(v[key]);
return res;
} else return v;
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrTransformSlotOutlet.ts
const ssrTransformSlotOutlet = (node, context) => {
if ((0, _vue_compiler_dom.isSlotOutlet)(node)) {
const { slotName, slotProps } = (0, _vue_compiler_dom.processSlotOutlet)(node, context);
const args = [
`_ctx.$slots`,
slotName,
slotProps || `{}`,
`null`,
`_push`,
`_parent`
];
if (context.scopeId && context.slotted !== false) args.push(`"${context.scopeId}-s"`);
let method = SSR_RENDER_SLOT;
let parent = context.parent;
if (parent && !rawOptionsMap.get(context.root).vapor) {
const children = parent.children;
if (parent.type === 10) parent = context.grandParent;
let componentType;
if (parent.type === 1 && parent.tagType === 1 && ((componentType = (0, _vue_compiler_dom.resolveComponentType)(parent, context, true)) === _vue_compiler_dom.TRANSITION || componentType === _vue_compiler_dom.TRANSITION_GROUP) && children.filter((c) => c.type === 1).length === 1) {
method = SSR_RENDER_SLOT_INNER;
if (!(context.scopeId && context.slotted !== false)) args.push("null");
args.push("true");
}
}
node.ssrCodegenNode = (0, _vue_compiler_dom.createCallExpression)(context.helper(method), args);
}
};
function ssrProcessSlotOutlet(node, context) {
const renderCall = node.ssrCodegenNode;
if (node.children.length) {
const fallbackRenderFn = (0, _vue_compiler_dom.createFunctionExpression)([]);
fallbackRenderFn.body = processChildrenAsStatement(node, context);
renderCall.arguments[3] = fallbackRenderFn;
}
if (context.withSlotScopeId) {
const slotScopeId = renderCall.arguments[6];
renderCall.arguments[6] = slotScopeId ? `${slotScopeId} + _scopeId` : `_scopeId`;
}
context.pushStatement(node.ssrCodegenNode);
}
//#endregion
//#region packages/compiler-ssr/src/ssrCodegenTransform.ts
function ssrCodegenTransform(ast, options) {
const context = createSSRTransformContext(ast, options);
if (options.ssrCssVars) {
const cssContext = (0, _vue_compiler_dom.createTransformContext)((0, _vue_compiler_dom.createRoot)([]), options);
const varsExp = (0, _vue_compiler_dom.processExpression)((0, _vue_compiler_dom.createSimpleExpression)(options.ssrCssVars, false), cssContext);
context.body.push((0, _vue_compiler_dom.createCompoundExpression)([
`const _cssVars = { style: `,
varsExp,
`}`
]));
Array.from(cssContext.helpers.keys()).forEach((helper) => {
ast.helpers.add(helper);
});
}
processChildren(ast, context, ast.children.length > 1 && ast.children.some((c) => !(0, _vue_compiler_dom.isText)(c)));
ast.codegenNode = (0, _vue_compiler_dom.createBlockStatement)(context.body);
ast.ssrHelpers = Array.from(/* @__PURE__ */ new Set([...Array.from(ast.helpers).filter((h) => h in ssrHelpers), ...context.helpers]));
ast.helpers = new Set(Array.from(ast.helpers).filter((h) => !(h in ssrHelpers)));
}
function createSSRTransformContext(root, options, helpers = /* @__PURE__ */ new Set(), withSlotScopeId = false) {
const body = [];
let currentString = null;
return {
root,
options,
body,
helpers,
withSlotScopeId,
onError: options.onError || ((e) => {
throw e;
}),
helper(name) {
helpers.add(name);
return name;
},
pushStringPart(part) {
if (!currentString) {
const currentCall = (0, _vue_compiler_dom.createCallExpression)(`_push`);
body.push(currentCall);
currentString = (0, _vue_compiler_dom.createTemplateLiteral)([]);
currentCall.arguments.push(currentString);
}
const bufferedElements = currentString.elements;
const lastItem = bufferedElements[bufferedElements.length - 1];
if ((0, _vue_shared.isString)(part) && (0, _vue_shared.isString)(lastItem)) bufferedElements[bufferedElements.length - 1] += part;
else bufferedElements.push(part);
},
pushStatement(statement) {
currentString = null;
body.push(statement);
}
};
}
function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
}
function processChildren(parent, context, asFragment = false, disableNestedFragments = false, disableComment = false) {
if (asFragment) context.pushStringPart(`<!--[-->`);
const { children } = parent;
for (let i = 0; i < children.length; i++) {
const child = children[i];
switch (child.type) {
case 1:
switch (child.tagType) {
case 0:
ssrProcessElement(child, context);
break;
case 1:
ssrProcessComponent(child, context, parent);
break;
case 2:
ssrProcessSlotOutlet(child, context);
break;
case 3: break;
default:
context.onError(createSSRCompilerError(67, child.loc));
return child;
}
break;
case 2:
context.pushStringPart((0, _vue_shared.escapeHtml)(child.content));
break;
case 3:
if (!disableComment) context.pushStringPart(`<!--${child.content}-->`);
break;
case 5:
context.pushStringPart((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_INTERPOLATE), [child.content]));
break;
case 9:
ssrProcessIf(child, context, disableNestedFragments, disableComment);
break;
case 11:
ssrProcessFor(child, context, disableNestedFragments);
break;
case 10: break;
case 12:
case 8: break;
default:
context.onError(createSSRCompilerError(67, child.loc));
return child;
}
}
if (asFragment) context.pushStringPart(`<!--]-->`);
}
function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
const childContext = createChildContext(parentContext, withSlotScopeId);
processChildren(parent, childContext, asFragment);
return (0, _vue_compiler_dom.createBlockStatement)(childContext.body);
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrVModel.ts
const ssrTransformModel = (dir, node, context) => {
const model = dir.exp;
function checkDuplicatedValue() {
const value = (0, _vue_compiler_dom.findProp)(node, "value");
if (value) context.onError((0, _vue_compiler_dom.createDOMCompilerError)(61, value.loc));
}
const processSelectChildren = (children) => {
children.forEach((child) => {
if (child.type === 1) processOption(child);
else if (child.type === 11) processSelectChildren(child.children);
else if (child.type === 9) child.branches.forEach((b) => processSelectChildren(b.children));
});
};
function processOption(plainNode) {
if (plainNode.tag === "option") {
if (plainNode.props.findIndex((p) => p.name === "selected") === -1) {
const value = findValueBinding(plainNode);
plainNode.ssrCodegenNode.elements.push((0, _vue_compiler_dom.createConditionalExpression)((0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [(0, _vue_compiler_dom.createConditionalExpression)((0, _vue_compiler_dom.createCallExpression)(`Array.isArray`, [model]), (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_LOOSE_CONTAIN), [model, value]), (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_LOOSE_EQUAL), [model, value]))]), (0, _vue_compiler_dom.createSimpleExpression)(" selected", true), (0, _vue_compiler_dom.createSimpleExpression)("", true), false));
}
} else if (plainNode.tag === "optgroup") processSelectChildren(plainNode.children);
}
if (node.tagType === 0) {
const res = { props: [] };
if (node.tag === "input") {
const defaultProps = [(0, _vue_compiler_dom.createObjectProperty)(`value`, model)];
const type = (0, _vue_compiler_dom.findProp)(node, "type");
if (type) {
const value = findValueBinding(node);
if (type.type === 7) res.ssrTagParts = [(0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
type.exp,
model,
value
])];
else if (type.value) switch (type.value.content) {
case "radio":
res.props = [(0, _vue_compiler_dom.createObjectProperty)(`checked`, (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_LOOSE_EQUAL), [model, value]))];
break;
case "checkbox":
const trueValueBinding = (0, _vue_compiler_dom.findProp)(node, "true-value");
if (trueValueBinding) {
const trueValue = trueValueBinding.type === 6 ? JSON.stringify(trueValueBinding.value.content) : trueValueBinding.exp;
res.props = [(0, _vue_compiler_dom.createObjectProperty)(`checked`, (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_LOOSE_EQUAL), [model, trueValue]))];
} else res.props = [(0, _vue_compiler_dom.createObjectProperty)(`checked`, (0, _vue_compiler_dom.createConditionalExpression)((0, _vue_compiler_dom.createCallExpression)(`Array.isArray`, [model]), (0, _vue_compiler_dom.createCallExpression)(context.helper(SSR_LOOSE_CONTAIN), [model, value]), model))];
break;
case "file":
context.onError((0, _vue_compiler_dom.createDOMCompilerError)(60, dir.loc));
break;
default:
checkDuplicatedValue();
res.props = defaultProps;
}
} else if ((0, _vue_compiler_dom.hasDynamicKeyVBind)(node)) {} else {
checkDuplicatedValue();
res.props = defaultProps;
}
} else if (node.tag === "textarea") {
checkDuplicatedValue();
node.children = [(0, _vue_compiler_dom.createInterpolation)(model, model.loc)];
} else if (node.tag === "select") processSelectChildren(node.children);
else context.onError((0, _vue_compiler_dom.createDOMCompilerError)(58, dir.loc));
return res;
} else return (0, _vue_compiler_dom.transformModel)(dir, node, context);
};
function findValueBinding(node) {
const valueBinding = (0, _vue_compiler_dom.findProp)(node, "value");
return valueBinding ? valueBinding.type === 7 ? valueBinding.exp : (0, _vue_compiler_dom.createSimpleExpression)(valueBinding.value.content, true) : (0, _vue_compiler_dom.createSimpleExpression)(`null`, false);
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrVShow.ts
const ssrTransformShow = (dir, node, context) => {
if (!dir.exp) context.onError((0, _vue_compiler_dom.createDOMCompilerError)(62));
return { props: [(0, _vue_compiler_dom.createObjectProperty)(`style`, (0, _vue_compiler_dom.createConditionalExpression)(dir.exp, (0, _vue_compiler_dom.createSimpleExpression)(`null`, false), (0, _vue_compiler_dom.createObjectExpression)([(0, _vue_compiler_dom.createObjectProperty)(`display`, (0, _vue_compiler_dom.createSimpleExpression)(`none`, true))]), false))] };
};
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrInjectFallthroughAttrs.ts
const ssrInjectFallthroughAttrs = (node, context) => {
if (node.type === 0) context.identifiers._attrs = 1;
if (node.type === 1 && node.tagType === 1 && (node.tag === "transition" || node.tag === "Transition" || node.tag === "KeepAlive" || node.tag === "keep-alive")) {
const rootChildren = (0, _vue_compiler_dom.filterNonCommentChildren)(context.root);
if (rootChildren.length === 1 && rootChildren[0] === node) {
if ((0, _vue_compiler_dom.hasSingleChild)(node)) injectFallthroughAttrs(node.children[0]);
return;
}
}
const parent = context.parent;
if (!parent || parent.type !== 0) return;
if (node.type === 10 && (0, _vue_compiler_dom.hasSingleChild)(node)) {
if ((0, _vue_compiler_dom.isSingleIfBlock)(parent)) injectFallthroughAttrs(node.children[0]);
} else if ((0, _vue_compiler_dom.hasSingleChild)(parent)) injectFallthroughAttrs(node);
};
function injectFallthroughAttrs(node) {
if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !(0, _vue_compiler_dom.findDir)(node, "for")) node.props.push({
type: 7,
name: "bind",
arg: void 0,
exp: (0, _vue_compiler_dom.createSimpleExpression)(`_attrs`, false),
modifiers: [],
loc: _vue_compiler_dom.locStub
});
}
//#endregion
//#region packages/compiler-ssr/src/transforms/ssrInjectCssVars.ts
const ssrInjectCssVars = (node, context) => {
if (!context.ssrCssVars) return;
if (node.type === 0) context.identifiers._cssVars = 1;
const parent = context.parent;
if (!parent || parent.type !== 0) return;
if (node.type === 10) for (const child of node.children) injectCssVars(child);
else injectCssVars(node);
};
function injectCssVars(node) {
if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !(0, _vue_compiler_dom.findDir)(node, "for")) {
if (node.tag === "suspense" || node.tag === "Suspense") for (const child of node.children) if (child.type === 1 && child.tagType === 3) child.children.forEach(injectCssVars);
else injectCssVars(child);
else node.props.push({
type: 7,
name: "bind",
arg: void 0,
exp: (0, _vue_compiler_dom.createSimpleExpression)(`_cssVars`, false),
modifiers: [],
loc: _vue_compiler_dom.locStub
});
}
}
//#endregion
//#region packages/compiler-ssr/src/index.ts
function compile(source, options = {}) {
options = {
...options,
..._vue_compiler_dom.parserOptions,
ssr: true,
inSSR: true,
scopeId: options.mode === "function" ? null : options.scopeId,
prefixIdentifiers: true,
cacheHandlers: false,
hoistStatic: false
};
const ast = typeof source === "string" ? (0, _vue_compiler_dom.baseParse)(source, options) : source;
rawOptionsMap.set(ast, options);
(0, _vue_compiler_dom.transform)(ast, {
...options,
hoistStatic: false,
nodeTransforms: [
_vue_compiler_dom.transformVBindShorthand,
ssrTransformIf,
ssrTransformFor,
_vue_compiler_dom.trackVForSlotScopes,
_vue_compiler_dom.transformExpression,
ssrTransformSlotOutlet,
ssrInjectFallthroughAttrs,
ssrInjectCssVars,
ssrTransformElement,
ssrTransformComponent,
_vue_compiler_dom.trackSlotScopes,
_vue_compiler_dom.transformStyle,
...options.nodeTransforms || []
],
directiveTransforms: {
bind: _vue_compiler_dom.transformBind,
on: _vue_compiler_dom.transformOn,
model: ssrTransformModel,
show: ssrTransformShow,
cloak: _vue_compiler_dom.noopDirectiveTransform,
once: _vue_compiler_dom.noopDirectiveTransform,
memo: _vue_compiler_dom.noopDirectiveTransform,
...options.directiveTransforms || {}
}
});
ssrCodegenTransform(ast, options);
return (0, _vue_compiler_dom.generate)(ast, options);
}
//#endregion
exports.compile = compile;
+4
View File
@@ -0,0 +1,4 @@
import { CodegenResult, CompilerOptions, RootNode } from "@vue/compiler-dom";
//#region temp/packages/compiler-ssr/src/index.d.ts
export declare function compile(source: string | RootNode, options?: CompilerOptions): CodegenResult;
//#endregion
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@vue/compiler-ssr",
"version": "3.6.0-rc.10",
"description": "@vue/compiler-ssr",
"main": "dist/compiler-ssr.cjs.js",
"types": "dist/compiler-ssr.d.ts",
"files": [
"dist"
],
"buildOptions": {
"prod": false,
"formats": [
"cjs"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-ssr"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-ssr#readme",
"dependencies": {
"@vue/shared": "3.6.0-rc.10",
"@vue/compiler-dom": "3.6.0-rc.10"
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
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.
+1
View File
@@ -0,0 +1 @@
# @vue/compiler-vapor
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+51
View File
@@ -0,0 +1,51 @@
{
"name": "@vue/compiler-vapor",
"version": "3.6.0-rc.10",
"description": "@vue/compiler-vapor",
"main": "dist/compiler-vapor.cjs.js",
"module": "dist/compiler-vapor.esm-browser.js",
"types": "dist/compiler-vapor.d.ts",
"files": [
"dist"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/compiler-vapor.d.ts",
"node": "./dist/compiler-vapor.cjs.js",
"module": "./dist/compiler-vapor.esm-browser.js",
"import": "./dist/compiler-vapor.esm-browser.js",
"require": "./dist/compiler-vapor.cjs.js"
},
"./*": "./*"
},
"buildOptions": {
"formats": [
"cjs",
"esm-browser"
],
"prod": false,
"enableNonBrowserBranches": true
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-vapor"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-vapor#readme",
"dependencies": {
"@babel/parser": "^7.29.8",
"@vue/compiler-dom": "3.6.0-rc.10",
"@vue/shared": "3.6.0-rc.10",
"estree-walker": "^2.0.2",
"source-map-js": "^1.2.1"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 webfansplz
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.
+3
View File
@@ -0,0 +1,3 @@
# @vue/devtools-core
> Internal core functions shared across @vue/devtools packages.
+544
View File
@@ -0,0 +1,544 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
let _vue_devtools_shared = require("@vue/devtools-shared");
let _vue_devtools_kit = require("@vue/devtools-kit");
let vue = require("vue");
//#region src/client.ts
function setDevToolsClientUrl(url) {
_vue_devtools_shared.target.__VUE_DEVTOOLS_CLIENT_URL__ = url;
}
function getDevToolsClientUrl() {
return _vue_devtools_shared.target.__VUE_DEVTOOLS_CLIENT_URL__ ?? (() => {
if (_vue_devtools_shared.isBrowser) {
const devtoolsMeta = document.querySelector("meta[name=__VUE_DEVTOOLS_CLIENT_URL__]");
if (devtoolsMeta) return devtoolsMeta.getAttribute("content");
}
return "";
})();
}
//#endregion
//#region ../../node_modules/.pnpm/hookable@5.5.3/node_modules/hookable/dist/index.mjs
function flatHooks(configHooks, hooks = {}, parentName) {
for (const key in configHooks) {
const subHook = configHooks[key];
const name = parentName ? `${parentName}:${key}` : key;
if (typeof subHook === "object" && subHook !== null) flatHooks(subHook, hooks, name);
else if (typeof subHook === "function") hooks[name] = subHook;
}
return hooks;
}
const defaultTask = { run: (function_) => function_() };
const _createTask = () => defaultTask;
const createTask = typeof console.createTask !== "undefined" ? console.createTask : _createTask;
function serialTaskCaller(hooks, args) {
const task = createTask(args.shift());
return hooks.reduce((promise, hookFunction) => promise.then(() => task.run(() => hookFunction(...args))), Promise.resolve());
}
function parallelTaskCaller(hooks, args) {
const task = createTask(args.shift());
return Promise.all(hooks.map((hook) => task.run(() => hook(...args))));
}
function callEachWith(callbacks, arg0) {
for (const callback of [...callbacks]) callback(arg0);
}
var Hookable = class {
constructor() {
this._hooks = {};
this._before = void 0;
this._after = void 0;
this._deprecatedMessages = void 0;
this._deprecatedHooks = {};
this.hook = this.hook.bind(this);
this.callHook = this.callHook.bind(this);
this.callHookWith = this.callHookWith.bind(this);
}
hook(name, function_, options = {}) {
if (!name || typeof function_ !== "function") return () => {};
const originalName = name;
let dep;
while (this._deprecatedHooks[name]) {
dep = this._deprecatedHooks[name];
name = dep.to;
}
if (dep && !options.allowDeprecated) {
let message = dep.message;
if (!message) message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
if (!this._deprecatedMessages) this._deprecatedMessages = /* @__PURE__ */ new Set();
if (!this._deprecatedMessages.has(message)) {
console.warn(message);
this._deprecatedMessages.add(message);
}
}
if (!function_.name) try {
Object.defineProperty(function_, "name", {
get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
configurable: true
});
} catch {}
this._hooks[name] = this._hooks[name] || [];
this._hooks[name].push(function_);
return () => {
if (function_) {
this.removeHook(name, function_);
function_ = void 0;
}
};
}
hookOnce(name, function_) {
let _unreg;
let _function = (...arguments_) => {
if (typeof _unreg === "function") _unreg();
_unreg = void 0;
_function = void 0;
return function_(...arguments_);
};
_unreg = this.hook(name, _function);
return _unreg;
}
removeHook(name, function_) {
if (this._hooks[name]) {
const index = this._hooks[name].indexOf(function_);
if (index !== -1) this._hooks[name].splice(index, 1);
if (this._hooks[name].length === 0) delete this._hooks[name];
}
}
deprecateHook(name, deprecated) {
this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
const _hooks = this._hooks[name] || [];
delete this._hooks[name];
for (const hook of _hooks) this.hook(name, hook);
}
deprecateHooks(deprecatedHooks) {
Object.assign(this._deprecatedHooks, deprecatedHooks);
for (const name in deprecatedHooks) this.deprecateHook(name, deprecatedHooks[name]);
}
addHooks(configHooks) {
const hooks = flatHooks(configHooks);
const removeFns = Object.keys(hooks).map((key) => this.hook(key, hooks[key]));
return () => {
for (const unreg of removeFns.splice(0, removeFns.length)) unreg();
};
}
removeHooks(configHooks) {
const hooks = flatHooks(configHooks);
for (const key in hooks) this.removeHook(key, hooks[key]);
}
removeAllHooks() {
for (const key in this._hooks) delete this._hooks[key];
}
callHook(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(serialTaskCaller, name, ...arguments_);
}
callHookParallel(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(parallelTaskCaller, name, ...arguments_);
}
callHookWith(caller, name, ...arguments_) {
const event = this._before || this._after ? {
name,
args: arguments_,
context: {}
} : void 0;
if (this._before) callEachWith(this._before, event);
const result = caller(name in this._hooks ? [...this._hooks[name]] : [], arguments_);
if (result instanceof Promise) return result.finally(() => {
if (this._after && event) callEachWith(this._after, event);
});
if (this._after && event) callEachWith(this._after, event);
return result;
}
beforeEach(function_) {
this._before = this._before || [];
this._before.push(function_);
return () => {
if (this._before !== void 0) {
const index = this._before.indexOf(function_);
if (index !== -1) this._before.splice(index, 1);
}
};
}
afterEach(function_) {
this._after = this._after || [];
this._after.push(function_);
return () => {
if (this._after !== void 0) {
const index = this._after.indexOf(function_);
if (index !== -1) this._after.splice(index, 1);
}
};
}
};
function createHooks() {
return new Hookable();
}
//#endregion
//#region src/rpc/global.ts
const hooks$1 = createHooks();
let DevToolsMessagingEvents = /* @__PURE__ */ function(DevToolsMessagingEvents) {
DevToolsMessagingEvents["INSPECTOR_TREE_UPDATED"] = "inspector-tree-updated";
DevToolsMessagingEvents["INSPECTOR_STATE_UPDATED"] = "inspector-state-updated";
DevToolsMessagingEvents["DEVTOOLS_STATE_UPDATED"] = "devtools-state-updated";
DevToolsMessagingEvents["ROUTER_INFO_UPDATED"] = "router-info-updated";
DevToolsMessagingEvents["TIMELINE_EVENT_UPDATED"] = "timeline-event-updated";
DevToolsMessagingEvents["INSPECTOR_UPDATED"] = "inspector-updated";
DevToolsMessagingEvents["ACTIVE_APP_UNMOUNTED"] = "active-app-updated";
DevToolsMessagingEvents["DESTROY_DEVTOOLS_CLIENT"] = "destroy-devtools-client";
DevToolsMessagingEvents["RELOAD_DEVTOOLS_CLIENT"] = "reload-devtools-client";
return DevToolsMessagingEvents;
}({});
function getDevToolsState() {
const state = _vue_devtools_kit.devtools.ctx.state;
return {
connected: state.connected,
clientConnected: true,
vueVersion: state?.activeAppRecord?.version || "",
tabs: state.tabs,
commands: state.commands,
vitePluginDetected: state.vitePluginDetected,
appRecords: state.appRecords.map((item) => ({
id: item.id,
name: item.name,
version: item.version,
routerId: item.routerId,
iframe: item.iframe
})),
activeAppRecordId: state.activeAppRecordId,
timelineLayersState: state.timelineLayersState
};
}
const functions = {
on: (event, handler) => {
hooks$1.hook(event, handler);
},
off: (event, handler) => {
hooks$1.removeHook(event, handler);
},
once: (event, handler) => {
hooks$1.hookOnce(event, handler);
},
emit: (event, ...args) => {
hooks$1.callHook(event, ...args);
},
heartbeat: () => {
return true;
},
devtoolsState: () => {
return getDevToolsState();
},
async getInspectorTree(payload) {
return (0, _vue_devtools_kit.stringify)(await _vue_devtools_kit.devtools.ctx.api.getInspectorTree(payload));
},
async getInspectorState(payload) {
const inspector = (0, _vue_devtools_kit.getInspector)(payload.inspectorId);
if (inspector) inspector.selectedNodeId = payload.nodeId;
return (0, _vue_devtools_kit.stringify)(await _vue_devtools_kit.devtools.ctx.api.getInspectorState(payload));
},
async editInspectorState(payload) {
return await _vue_devtools_kit.devtools.ctx.api.editInspectorState(payload);
},
sendInspectorState(id) {
return _vue_devtools_kit.devtools.ctx.api.sendInspectorState(id);
},
inspectComponentInspector() {
return _vue_devtools_kit.devtools.ctx.api.inspectComponentInspector();
},
cancelInspectComponentInspector() {
return _vue_devtools_kit.devtools.ctx.api.cancelInspectComponentInspector();
},
getComponentRenderCode(id) {
return _vue_devtools_kit.devtools.ctx.api.getComponentRenderCode(id);
},
scrollToComponent(id) {
return _vue_devtools_kit.devtools.ctx.api.scrollToComponent(id);
},
inspectDOM(id) {
return _vue_devtools_kit.devtools.ctx.api.inspectDOM(id);
},
getInspectorNodeActions(id) {
return (0, _vue_devtools_kit.getInspectorNodeActions)(id);
},
getInspectorActions(id) {
return (0, _vue_devtools_kit.getInspectorActions)(id);
},
updateTimelineLayersState(state) {
return (0, _vue_devtools_kit.updateTimelineLayersState)(state);
},
callInspectorNodeAction(inspectorId, actionIndex, nodeId) {
const nodeActions = (0, _vue_devtools_kit.getInspectorNodeActions)(inspectorId);
if (nodeActions?.length) nodeActions[actionIndex].action?.(nodeId);
},
callInspectorAction(inspectorId, actionIndex) {
const actions = (0, _vue_devtools_kit.getInspectorActions)(inspectorId);
if (actions?.length) actions[actionIndex].action?.();
},
openInEditor(options) {
return _vue_devtools_kit.devtools.ctx.api.openInEditor(options);
},
async checkVueInspectorDetected() {
return !!await _vue_devtools_kit.devtools.ctx.api.getVueInspector();
},
async enableVueInspector() {
const inspector = await _vue_devtools_kit.devtools?.api?.getVueInspector?.();
if (inspector) await inspector.enable();
},
async toggleApp(id, options) {
return _vue_devtools_kit.devtools.ctx.api.toggleApp(id, options);
},
updatePluginSettings(pluginId, key, value) {
return _vue_devtools_kit.devtools.ctx.api.updatePluginSettings(pluginId, key, value);
},
getPluginSettings(pluginId) {
return _vue_devtools_kit.devtools.ctx.api.getPluginSettings(pluginId);
},
getRouterInfo() {
return _vue_devtools_kit.devtoolsRouterInfo;
},
navigate(path) {
return _vue_devtools_kit.devtoolsRouter.value?.push(path).catch(() => ({}));
},
getMatchedRoutes(path) {
const c = console.warn;
console.warn = () => {};
const matched = _vue_devtools_kit.devtoolsRouter.value?.resolve?.({ path: path || "/" }).matched ?? [];
console.warn = c;
return matched;
},
toggleClientConnected(state) {
(0, _vue_devtools_kit.toggleClientConnected)(state);
},
getCustomInspector() {
return (0, _vue_devtools_kit.getActiveInspectors)();
},
getInspectorInfo(id) {
return (0, _vue_devtools_kit.getInspectorInfo)(id);
},
highlighComponent(uid) {
return _vue_devtools_kit.devtools.ctx.hooks.callHook(_vue_devtools_kit.DevToolsContextHookKeys.COMPONENT_HIGHLIGHT, { uid });
},
unhighlight() {
return _vue_devtools_kit.devtools.ctx.hooks.callHook(_vue_devtools_kit.DevToolsContextHookKeys.COMPONENT_UNHIGHLIGHT);
},
updateDevToolsClientDetected(params) {
(0, _vue_devtools_kit.updateDevToolsClientDetected)(params);
},
initDevToolsServerListener() {
const broadcast = (0, _vue_devtools_kit.getRpcServer)().broadcast;
_vue_devtools_kit.devtools.ctx.hooks.hook(_vue_devtools_kit.DevToolsMessagingHookKeys.SEND_INSPECTOR_TREE_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.INSPECTOR_TREE_UPDATED, (0, _vue_devtools_kit.stringify)(payload));
});
_vue_devtools_kit.devtools.ctx.hooks.hook(_vue_devtools_kit.DevToolsMessagingHookKeys.SEND_INSPECTOR_STATE_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.INSPECTOR_STATE_UPDATED, (0, _vue_devtools_kit.stringify)(payload));
});
_vue_devtools_kit.devtools.ctx.hooks.hook(_vue_devtools_kit.DevToolsMessagingHookKeys.DEVTOOLS_STATE_UPDATED, () => {
broadcast.emit(DevToolsMessagingEvents.DEVTOOLS_STATE_UPDATED, getDevToolsState());
});
_vue_devtools_kit.devtools.ctx.hooks.hook(_vue_devtools_kit.DevToolsMessagingHookKeys.ROUTER_INFO_UPDATED, ({ state }) => {
broadcast.emit(DevToolsMessagingEvents.ROUTER_INFO_UPDATED, state);
});
_vue_devtools_kit.devtools.ctx.hooks.hook(_vue_devtools_kit.DevToolsMessagingHookKeys.SEND_TIMELINE_EVENT_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.TIMELINE_EVENT_UPDATED, (0, _vue_devtools_kit.stringify)(payload));
});
_vue_devtools_kit.devtools.ctx.hooks.hook(_vue_devtools_kit.DevToolsMessagingHookKeys.SEND_INSPECTOR_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.INSPECTOR_UPDATED, payload);
});
_vue_devtools_kit.devtools.ctx.hooks.hook(_vue_devtools_kit.DevToolsMessagingHookKeys.SEND_ACTIVE_APP_UNMOUNTED_TO_CLIENT, () => {
broadcast.emit(DevToolsMessagingEvents.ACTIVE_APP_UNMOUNTED);
});
}
};
const rpc = new Proxy({
value: {},
functions: {}
}, { get(target, property) {
const _rpc = (0, _vue_devtools_kit.getRpcClient)();
if (property === "value") return _rpc;
else if (property === "functions") return _rpc.$functions;
} });
const rpcServer = new Proxy({
value: {},
functions: {}
}, { get(target, property) {
const _rpc = (0, _vue_devtools_kit.getRpcServer)();
if (property === "value") return _rpc;
else if (property === "functions") return _rpc.functions;
} });
function onRpcConnected(callback) {
let timer = null;
let retryCount = 0;
function heartbeat() {
rpc.value?.heartbeat?.().then(() => {
callback();
clearTimeout(timer);
}).catch(() => {});
}
timer = setInterval(() => {
if (retryCount >= 30) clearTimeout(timer);
retryCount++;
heartbeat();
}, retryCount * 200 + 200);
heartbeat();
}
function onRpcSeverReady(callback) {
let timer = null;
const timeout = 120;
function heartbeat() {
if (rpcServer.value.clients.length > 0) {
callback();
clearTimeout(timer);
}
}
timer = setInterval(() => {
heartbeat();
}, timeout);
}
//#endregion
//#region src/rpc/vite.ts
const hooks = createHooks();
const viteRpcFunctions = {
on: (event, handler) => {
hooks.hook(event, handler);
},
off: (event, handler) => {
hooks.removeHook(event, handler);
},
once: (event, handler) => {
hooks.hookOnce(event, handler);
},
emit: (event, ...args) => {
hooks.callHook(event, ...args);
},
heartbeat: () => {
return true;
}
};
const viteRpc = new Proxy({
value: {},
functions: {}
}, { get(target, property) {
const _rpc = (0, _vue_devtools_kit.getViteRpcClient)();
if (property === "value") return _rpc;
else if (property === "functions") return _rpc?.$functions;
} });
function onViteRpcConnected(callback) {
let timer = null;
function heartbeat() {
viteRpc.value?.heartbeat?.().then(() => {
clearTimeout(timer);
callback();
}).catch(() => ({}));
timer = setTimeout(() => {
heartbeat();
}, 80);
}
heartbeat();
}
function createViteClientRpc() {
(0, _vue_devtools_kit.createRpcClient)(viteRpcFunctions, { preset: "vite" });
}
function createViteServerRpc(functions) {
(0, _vue_devtools_kit.createRpcServer)(functions, { preset: "vite" });
}
//#endregion
//#region src/vue-plugin/devtools-state.ts
const VueDevToolsStateSymbol = Symbol.for("__VueDevToolsStateSymbol__");
function VueDevToolsVuePlugin() {
return { install(app) {
const state = createDevToolsStateContext();
state.getDevToolsState();
app.provide(VueDevToolsStateSymbol, state);
app.config.globalProperties.$getDevToolsState = state.getDevToolsState;
app.config.globalProperties.$disconnectDevToolsClient = () => {
state.clientConnected.value = false;
state.connected.value = false;
};
} };
}
function createDevToolsStateContext() {
const connected = (0, vue.ref)(false);
const clientConnected = (0, vue.ref)(false);
const vueVersion = (0, vue.ref)("");
const tabs = (0, vue.ref)([]);
const commands = (0, vue.ref)([]);
const vitePluginDetected = (0, vue.ref)(false);
const appRecords = (0, vue.ref)([]);
const activeAppRecordId = (0, vue.ref)("");
const timelineLayersState = (0, vue.ref)({});
function updateState(data) {
connected.value = data.connected;
clientConnected.value = data.clientConnected;
vueVersion.value = data.vueVersion || "";
tabs.value = data.tabs;
commands.value = data.commands;
vitePluginDetected.value = data.vitePluginDetected;
appRecords.value = data.appRecords;
activeAppRecordId.value = data.activeAppRecordId;
timelineLayersState.value = data.timelineLayersState;
}
function getDevToolsState() {
onRpcConnected(() => {
rpc.value.devtoolsState().then((data) => {
updateState(data);
});
rpc.functions.off(DevToolsMessagingEvents.DEVTOOLS_STATE_UPDATED, updateState);
rpc.functions.on(DevToolsMessagingEvents.DEVTOOLS_STATE_UPDATED, updateState);
});
}
return {
getDevToolsState,
connected,
clientConnected,
vueVersion,
tabs,
commands,
vitePluginDetected,
appRecords,
activeAppRecordId,
timelineLayersState
};
}
function useDevToolsState() {
return (0, vue.inject)(VueDevToolsStateSymbol);
}
const fns = [];
function onDevToolsConnected(fn) {
const { connected, clientConnected } = useDevToolsState();
fns.push(fn);
(0, vue.onUnmounted)(() => {
fns.splice(fns.indexOf(fn), 1);
});
const devtoolsReady = (0, vue.computed)(() => clientConnected.value && connected.value);
if (devtoolsReady.value) fn();
else {
const stop = (0, vue.watch)(devtoolsReady, (v) => {
if (v) {
fn();
stop();
}
});
}
return () => {
fns.splice(fns.indexOf(fn), 1);
};
}
function refreshCurrentPageData() {
fns.forEach((fn) => fn());
}
//#endregion
exports.DevToolsMessagingEvents = DevToolsMessagingEvents;
exports.VueDevToolsVuePlugin = VueDevToolsVuePlugin;
exports.createDevToolsStateContext = createDevToolsStateContext;
exports.createViteClientRpc = createViteClientRpc;
exports.createViteServerRpc = createViteServerRpc;
exports.functions = functions;
exports.getDevToolsClientUrl = getDevToolsClientUrl;
exports.onDevToolsConnected = onDevToolsConnected;
exports.onRpcConnected = onRpcConnected;
exports.onRpcSeverReady = onRpcSeverReady;
exports.onViteRpcConnected = onViteRpcConnected;
exports.refreshCurrentPageData = refreshCurrentPageData;
exports.rpc = rpc;
exports.rpcServer = rpcServer;
exports.setDevToolsClientUrl = setDevToolsClientUrl;
exports.useDevToolsState = useDevToolsState;
exports.viteRpc = viteRpc;
exports.viteRpcFunctions = viteRpcFunctions;
+348
View File
@@ -0,0 +1,348 @@
import * as _vue_devtools_kit0 from "@vue/devtools-kit";
import { AppRecord, CustomCommand, CustomTab, DevToolsV6PluginAPIHookKeys, DevToolsV6PluginAPIHookPayloads, OpenInEditorOptions, Router, RouterInfo, getRpcClient, getRpcServer, getViteRpcClient } from "@vue/devtools-kit";
import * as vue from "vue";
import { App, Ref } from "vue";
//#region src/client.d.ts
declare function setDevToolsClientUrl(url: string): void;
declare function getDevToolsClientUrl(): any;
//#endregion
//#region src/rpc/global.d.ts
declare enum DevToolsMessagingEvents {
INSPECTOR_TREE_UPDATED = "inspector-tree-updated",
INSPECTOR_STATE_UPDATED = "inspector-state-updated",
DEVTOOLS_STATE_UPDATED = "devtools-state-updated",
ROUTER_INFO_UPDATED = "router-info-updated",
TIMELINE_EVENT_UPDATED = "timeline-event-updated",
INSPECTOR_UPDATED = "inspector-updated",
ACTIVE_APP_UNMOUNTED = "active-app-updated",
DESTROY_DEVTOOLS_CLIENT = "destroy-devtools-client",
RELOAD_DEVTOOLS_CLIENT = "reload-devtools-client"
}
declare const functions: {
on: (event: string, handler: Function) => void;
off: (event: string, handler: Function) => void;
once: (event: string, handler: Function) => void;
emit: (event: string, ...args: any[]) => void;
heartbeat: () => boolean;
devtoolsState: () => {
connected: boolean;
clientConnected: boolean;
vueVersion: string;
tabs: _vue_devtools_kit0.CustomTab[];
commands: _vue_devtools_kit0.CustomCommand[];
vitePluginDetected: boolean;
appRecords: {
id: string;
name: string;
version: string | undefined;
routerId: string | undefined;
iframe: string | undefined;
}[];
activeAppRecordId: string;
timelineLayersState: Record<string, boolean>;
};
getInspectorTree(payload: Pick<DevToolsV6PluginAPIHookPayloads[DevToolsV6PluginAPIHookKeys.GET_INSPECTOR_TREE], "inspectorId" | "filter">): Promise<string>;
getInspectorState(payload: Pick<DevToolsV6PluginAPIHookPayloads[DevToolsV6PluginAPIHookKeys.GET_INSPECTOR_STATE], "inspectorId" | "nodeId">): Promise<string>;
editInspectorState(payload: DevToolsV6PluginAPIHookPayloads[DevToolsV6PluginAPIHookKeys.EDIT_INSPECTOR_STATE]): Promise<void>;
sendInspectorState(id: string): void;
inspectComponentInspector(): Promise<string>;
cancelInspectComponentInspector(): void;
getComponentRenderCode(id: string): any;
scrollToComponent(id: string): void;
inspectDOM(id: string): void;
getInspectorNodeActions(id: string): {
icon: string;
tooltip?: string;
action: (nodeId: string) => void | Promise<void>;
}[] | undefined;
getInspectorActions(id: string): {
icon: string;
tooltip?: string;
action: () => void | Promise<void>;
}[] | undefined;
updateTimelineLayersState(state: Record<string, boolean>): void;
callInspectorNodeAction(inspectorId: string, actionIndex: number, nodeId: string): void;
callInspectorAction(inspectorId: string, actionIndex: number): void;
openInEditor(options: OpenInEditorOptions): void;
checkVueInspectorDetected(): Promise<boolean>;
enableVueInspector(): Promise<void>;
toggleApp(id: string, options?: {
inspectingComponent?: boolean;
}): Promise<void>;
updatePluginSettings(pluginId: string, key: string, value: string): void;
getPluginSettings(pluginId: string): {
options: Record<string, {
label: string;
description?: string;
} & ({
type: "boolean";
defaultValue: boolean;
} | {
type: "choice";
defaultValue: string | number;
options: {
value: string | number;
label: string;
}[];
component?: "select" | "button-group";
} | {
type: "text";
defaultValue: string;
})> | null;
values: any;
};
getRouterInfo(): RouterInfo;
navigate(path: string): Promise<Awaited<ReturnType<Router["push"]>> | Record<string, never>> | undefined;
getMatchedRoutes(path: string): RouterInfo["routes"];
toggleClientConnected(state: boolean): void;
getCustomInspector(): {
id: string;
label: string;
logo: string;
icon: string;
packageName: string | undefined;
homepage: string | undefined;
pluginId: string;
}[];
getInspectorInfo(id: string): {
id: string;
label: string;
logo: string | undefined;
packageName: string | undefined;
homepage: string | undefined;
timelineLayers: {
id: string;
label: string;
color: number;
}[];
treeFilterPlaceholder: string;
stateFilterPlaceholder: string;
} | undefined;
highlighComponent(uid: string): Promise<any>;
unhighlight(): Promise<any>;
updateDevToolsClientDetected(params: Record<string, boolean>): void;
initDevToolsServerListener(): void;
};
type RPCFunctions = typeof functions;
declare const rpc: {
value: ReturnType<typeof getRpcClient<RPCFunctions>>;
functions: ReturnType<typeof getRpcClient<RPCFunctions>>;
};
declare const rpcServer: {
value: ReturnType<typeof getRpcServer<RPCFunctions>>;
functions: ReturnType<typeof getRpcServer<RPCFunctions>>;
};
declare function onRpcConnected(callback: () => void): void;
declare function onRpcSeverReady(callback: () => void): void;
//#endregion
//#region src/rpc/types.d.ts
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'wasm' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
relativePath: string;
filePath: string;
size: number;
mtime: number;
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface AssetImporter {
url: string;
id: string | null;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ModuleInfo {
id: string;
plugins: {
name: string;
transform?: number;
resolveId?: number;
}[];
deps: string[];
virtual: boolean;
}
//#endregion
//#region src/rpc/vite.d.ts
declare const viteRpcFunctions: {
on: (event: string, handler: Function) => void;
off: (event: string, handler: Function) => void;
once: (event: string, handler: Function) => void;
emit: (event: string, ...args: any[]) => void;
heartbeat: () => boolean;
};
type ViteRPCFunctions = typeof viteRpcFunctions & {
getStaticAssets: () => Promise<AssetInfo[]>;
getAssetImporters: (url: string) => Promise<AssetImporter[]>;
getImageMeta: (filepath: string) => Promise<ImageMeta>;
getTextAssetContent: (filepath: string, limit?: number) => Promise<string>;
getRoot: () => Promise<string>;
getGraphModules: () => Promise<ModuleInfo[]>;
};
declare const viteRpc: {
value: ReturnType<typeof getViteRpcClient<ViteRPCFunctions>>;
functions: ReturnType<typeof getViteRpcClient<ViteRPCFunctions>>;
};
declare function onViteRpcConnected(callback: () => void): void;
declare function createViteClientRpc(): void;
declare function createViteServerRpc(functions: Record<string, any>): void;
//#endregion
//#region src/vue-plugin/devtools-state.d.ts
interface DevToolsState {
connected: boolean;
clientConnected: boolean;
vueVersion: string;
tabs: CustomTab[];
commands: CustomCommand[];
vitePluginDetected: boolean;
appRecords: AppRecord[];
activeAppRecordId: string;
timelineLayersState: Record<string, boolean>;
}
type DevToolsRefState = { [P in keyof DevToolsState]: Ref<DevToolsState[P]> };
declare function VueDevToolsVuePlugin(): {
install(app: App): void;
};
declare function createDevToolsStateContext(): {
getDevToolsState: () => void;
connected: Ref<boolean, boolean>;
clientConnected: Ref<boolean, boolean>;
vueVersion: Ref<string, string>;
tabs: Ref<{
name: string;
icon?: string | undefined;
title: string;
view: {
type: "iframe";
src: string;
persistent?: boolean | undefined;
} | {
type: "vnode";
vnode: vue.VNode;
} | {
type: "sfc";
sfc: string;
};
category?: ("app" | "pinned" | "modules" | "advanced") | undefined;
}[], CustomTab[] | {
name: string;
icon?: string | undefined;
title: string;
view: {
type: "iframe";
src: string;
persistent?: boolean | undefined;
} | {
type: "vnode";
vnode: vue.VNode;
} | {
type: "sfc";
sfc: string;
};
category?: ("app" | "pinned" | "modules" | "advanced") | undefined;
}[]>;
commands: Ref<{
id: string;
title: string;
description?: string | undefined;
order?: number | undefined;
icon?: string | undefined;
action?: {
type: "url";
src: string;
} | undefined;
children?: {
icon?: string | undefined;
title: string;
id: string;
description?: string | undefined;
order?: number | undefined;
action?: {
type: "url";
src: string;
} | undefined;
}[] | undefined;
}[], CustomCommand[] | {
id: string;
title: string;
description?: string | undefined;
order?: number | undefined;
icon?: string | undefined;
action?: {
type: "url";
src: string;
} | undefined;
children?: {
icon?: string | undefined;
title: string;
id: string;
description?: string | undefined;
order?: number | undefined;
action?: {
type: "url";
src: string;
} | undefined;
}[] | undefined;
}[]>;
vitePluginDetected: Ref<boolean, boolean>;
appRecords: Ref<{
id: string;
name: string;
app?: _vue_devtools_kit0.App;
version?: string | undefined;
types?: Record<string, string | symbol> | undefined;
instanceMap: Map<string, any> & Omit<Map<string, any>, keyof Map<any, any>>;
perfGroupIds: Map<string, {
groupId: number;
time: number;
}> & Omit<Map<string, {
groupId: number;
time: number;
}>, keyof Map<any, any>>;
rootInstance: _vue_devtools_kit0.VueAppInstance;
routerId?: string | undefined;
iframe?: string | undefined;
}[], AppRecord[] | {
id: string;
name: string;
app?: _vue_devtools_kit0.App;
version?: string | undefined;
types?: Record<string, string | symbol> | undefined;
instanceMap: Map<string, any> & Omit<Map<string, any>, keyof Map<any, any>>;
perfGroupIds: Map<string, {
groupId: number;
time: number;
}> & Omit<Map<string, {
groupId: number;
time: number;
}>, keyof Map<any, any>>;
rootInstance: _vue_devtools_kit0.VueAppInstance;
routerId?: string | undefined;
iframe?: string | undefined;
}[]>;
activeAppRecordId: Ref<string, string>;
timelineLayersState: Ref<Record<string, boolean>, Record<string, boolean>>;
};
declare function useDevToolsState(): DevToolsRefState;
declare function onDevToolsConnected(fn: () => void): () => void;
declare function refreshCurrentPageData(): void;
//#endregion
export { AssetEntry, AssetImporter, AssetInfo, AssetType, CodeSnippet, DevToolsMessagingEvents, ImageMeta, ModuleInfo, RPCFunctions, ViteRPCFunctions, VueDevToolsVuePlugin, createDevToolsStateContext, createViteClientRpc, createViteServerRpc, functions, getDevToolsClientUrl, onDevToolsConnected, onRpcConnected, onRpcSeverReady, onViteRpcConnected, refreshCurrentPageData, rpc, rpcServer, setDevToolsClientUrl, useDevToolsState, viteRpc, viteRpcFunctions };
+348
View File
@@ -0,0 +1,348 @@
import * as _vue_devtools_kit0 from "@vue/devtools-kit";
import { AppRecord, CustomCommand, CustomTab, DevToolsV6PluginAPIHookKeys, DevToolsV6PluginAPIHookPayloads, OpenInEditorOptions, Router, RouterInfo, getRpcClient, getRpcServer, getViteRpcClient } from "@vue/devtools-kit";
import * as vue from "vue";
import { App, Ref } from "vue";
//#region src/client.d.ts
declare function setDevToolsClientUrl(url: string): void;
declare function getDevToolsClientUrl(): any;
//#endregion
//#region src/rpc/global.d.ts
declare enum DevToolsMessagingEvents {
INSPECTOR_TREE_UPDATED = "inspector-tree-updated",
INSPECTOR_STATE_UPDATED = "inspector-state-updated",
DEVTOOLS_STATE_UPDATED = "devtools-state-updated",
ROUTER_INFO_UPDATED = "router-info-updated",
TIMELINE_EVENT_UPDATED = "timeline-event-updated",
INSPECTOR_UPDATED = "inspector-updated",
ACTIVE_APP_UNMOUNTED = "active-app-updated",
DESTROY_DEVTOOLS_CLIENT = "destroy-devtools-client",
RELOAD_DEVTOOLS_CLIENT = "reload-devtools-client"
}
declare const functions: {
on: (event: string, handler: Function) => void;
off: (event: string, handler: Function) => void;
once: (event: string, handler: Function) => void;
emit: (event: string, ...args: any[]) => void;
heartbeat: () => boolean;
devtoolsState: () => {
connected: boolean;
clientConnected: boolean;
vueVersion: string;
tabs: _vue_devtools_kit0.CustomTab[];
commands: _vue_devtools_kit0.CustomCommand[];
vitePluginDetected: boolean;
appRecords: {
id: string;
name: string;
version: string | undefined;
routerId: string | undefined;
iframe: string | undefined;
}[];
activeAppRecordId: string;
timelineLayersState: Record<string, boolean>;
};
getInspectorTree(payload: Pick<DevToolsV6PluginAPIHookPayloads[DevToolsV6PluginAPIHookKeys.GET_INSPECTOR_TREE], "inspectorId" | "filter">): Promise<string>;
getInspectorState(payload: Pick<DevToolsV6PluginAPIHookPayloads[DevToolsV6PluginAPIHookKeys.GET_INSPECTOR_STATE], "inspectorId" | "nodeId">): Promise<string>;
editInspectorState(payload: DevToolsV6PluginAPIHookPayloads[DevToolsV6PluginAPIHookKeys.EDIT_INSPECTOR_STATE]): Promise<void>;
sendInspectorState(id: string): void;
inspectComponentInspector(): Promise<string>;
cancelInspectComponentInspector(): void;
getComponentRenderCode(id: string): any;
scrollToComponent(id: string): void;
inspectDOM(id: string): void;
getInspectorNodeActions(id: string): {
icon: string;
tooltip?: string;
action: (nodeId: string) => void | Promise<void>;
}[] | undefined;
getInspectorActions(id: string): {
icon: string;
tooltip?: string;
action: () => void | Promise<void>;
}[] | undefined;
updateTimelineLayersState(state: Record<string, boolean>): void;
callInspectorNodeAction(inspectorId: string, actionIndex: number, nodeId: string): void;
callInspectorAction(inspectorId: string, actionIndex: number): void;
openInEditor(options: OpenInEditorOptions): void;
checkVueInspectorDetected(): Promise<boolean>;
enableVueInspector(): Promise<void>;
toggleApp(id: string, options?: {
inspectingComponent?: boolean;
}): Promise<void>;
updatePluginSettings(pluginId: string, key: string, value: string): void;
getPluginSettings(pluginId: string): {
options: Record<string, {
label: string;
description?: string;
} & ({
type: "boolean";
defaultValue: boolean;
} | {
type: "choice";
defaultValue: string | number;
options: {
value: string | number;
label: string;
}[];
component?: "select" | "button-group";
} | {
type: "text";
defaultValue: string;
})> | null;
values: any;
};
getRouterInfo(): RouterInfo;
navigate(path: string): Promise<Awaited<ReturnType<Router["push"]>> | Record<string, never>> | undefined;
getMatchedRoutes(path: string): RouterInfo["routes"];
toggleClientConnected(state: boolean): void;
getCustomInspector(): {
id: string;
label: string;
logo: string;
icon: string;
packageName: string | undefined;
homepage: string | undefined;
pluginId: string;
}[];
getInspectorInfo(id: string): {
id: string;
label: string;
logo: string | undefined;
packageName: string | undefined;
homepage: string | undefined;
timelineLayers: {
id: string;
label: string;
color: number;
}[];
treeFilterPlaceholder: string;
stateFilterPlaceholder: string;
} | undefined;
highlighComponent(uid: string): Promise<any>;
unhighlight(): Promise<any>;
updateDevToolsClientDetected(params: Record<string, boolean>): void;
initDevToolsServerListener(): void;
};
type RPCFunctions = typeof functions;
declare const rpc: {
value: ReturnType<typeof getRpcClient<RPCFunctions>>;
functions: ReturnType<typeof getRpcClient<RPCFunctions>>;
};
declare const rpcServer: {
value: ReturnType<typeof getRpcServer<RPCFunctions>>;
functions: ReturnType<typeof getRpcServer<RPCFunctions>>;
};
declare function onRpcConnected(callback: () => void): void;
declare function onRpcSeverReady(callback: () => void): void;
//#endregion
//#region src/rpc/types.d.ts
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'wasm' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
relativePath: string;
filePath: string;
size: number;
mtime: number;
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface AssetImporter {
url: string;
id: string | null;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ModuleInfo {
id: string;
plugins: {
name: string;
transform?: number;
resolveId?: number;
}[];
deps: string[];
virtual: boolean;
}
//#endregion
//#region src/rpc/vite.d.ts
declare const viteRpcFunctions: {
on: (event: string, handler: Function) => void;
off: (event: string, handler: Function) => void;
once: (event: string, handler: Function) => void;
emit: (event: string, ...args: any[]) => void;
heartbeat: () => boolean;
};
type ViteRPCFunctions = typeof viteRpcFunctions & {
getStaticAssets: () => Promise<AssetInfo[]>;
getAssetImporters: (url: string) => Promise<AssetImporter[]>;
getImageMeta: (filepath: string) => Promise<ImageMeta>;
getTextAssetContent: (filepath: string, limit?: number) => Promise<string>;
getRoot: () => Promise<string>;
getGraphModules: () => Promise<ModuleInfo[]>;
};
declare const viteRpc: {
value: ReturnType<typeof getViteRpcClient<ViteRPCFunctions>>;
functions: ReturnType<typeof getViteRpcClient<ViteRPCFunctions>>;
};
declare function onViteRpcConnected(callback: () => void): void;
declare function createViteClientRpc(): void;
declare function createViteServerRpc(functions: Record<string, any>): void;
//#endregion
//#region src/vue-plugin/devtools-state.d.ts
interface DevToolsState {
connected: boolean;
clientConnected: boolean;
vueVersion: string;
tabs: CustomTab[];
commands: CustomCommand[];
vitePluginDetected: boolean;
appRecords: AppRecord[];
activeAppRecordId: string;
timelineLayersState: Record<string, boolean>;
}
type DevToolsRefState = { [P in keyof DevToolsState]: Ref<DevToolsState[P]> };
declare function VueDevToolsVuePlugin(): {
install(app: App): void;
};
declare function createDevToolsStateContext(): {
getDevToolsState: () => void;
connected: Ref<boolean, boolean>;
clientConnected: Ref<boolean, boolean>;
vueVersion: Ref<string, string>;
tabs: Ref<{
name: string;
icon?: string | undefined;
title: string;
view: {
type: "iframe";
src: string;
persistent?: boolean | undefined;
} | {
type: "vnode";
vnode: vue.VNode;
} | {
type: "sfc";
sfc: string;
};
category?: ("app" | "pinned" | "modules" | "advanced") | undefined;
}[], CustomTab[] | {
name: string;
icon?: string | undefined;
title: string;
view: {
type: "iframe";
src: string;
persistent?: boolean | undefined;
} | {
type: "vnode";
vnode: vue.VNode;
} | {
type: "sfc";
sfc: string;
};
category?: ("app" | "pinned" | "modules" | "advanced") | undefined;
}[]>;
commands: Ref<{
id: string;
title: string;
description?: string | undefined;
order?: number | undefined;
icon?: string | undefined;
action?: {
type: "url";
src: string;
} | undefined;
children?: {
icon?: string | undefined;
title: string;
id: string;
description?: string | undefined;
order?: number | undefined;
action?: {
type: "url";
src: string;
} | undefined;
}[] | undefined;
}[], CustomCommand[] | {
id: string;
title: string;
description?: string | undefined;
order?: number | undefined;
icon?: string | undefined;
action?: {
type: "url";
src: string;
} | undefined;
children?: {
icon?: string | undefined;
title: string;
id: string;
description?: string | undefined;
order?: number | undefined;
action?: {
type: "url";
src: string;
} | undefined;
}[] | undefined;
}[]>;
vitePluginDetected: Ref<boolean, boolean>;
appRecords: Ref<{
id: string;
name: string;
app?: _vue_devtools_kit0.App;
version?: string | undefined;
types?: Record<string, string | symbol> | undefined;
instanceMap: Map<string, any> & Omit<Map<string, any>, keyof Map<any, any>>;
perfGroupIds: Map<string, {
groupId: number;
time: number;
}> & Omit<Map<string, {
groupId: number;
time: number;
}>, keyof Map<any, any>>;
rootInstance: _vue_devtools_kit0.VueAppInstance;
routerId?: string | undefined;
iframe?: string | undefined;
}[], AppRecord[] | {
id: string;
name: string;
app?: _vue_devtools_kit0.App;
version?: string | undefined;
types?: Record<string, string | symbol> | undefined;
instanceMap: Map<string, any> & Omit<Map<string, any>, keyof Map<any, any>>;
perfGroupIds: Map<string, {
groupId: number;
time: number;
}> & Omit<Map<string, {
groupId: number;
time: number;
}>, keyof Map<any, any>>;
rootInstance: _vue_devtools_kit0.VueAppInstance;
routerId?: string | undefined;
iframe?: string | undefined;
}[]>;
activeAppRecordId: Ref<string, string>;
timelineLayersState: Ref<Record<string, boolean>, Record<string, boolean>>;
};
declare function useDevToolsState(): DevToolsRefState;
declare function onDevToolsConnected(fn: () => void): () => void;
declare function refreshCurrentPageData(): void;
//#endregion
export { AssetEntry, AssetImporter, AssetInfo, AssetType, CodeSnippet, DevToolsMessagingEvents, ImageMeta, ModuleInfo, RPCFunctions, ViteRPCFunctions, VueDevToolsVuePlugin, createDevToolsStateContext, createViteClientRpc, createViteServerRpc, functions, getDevToolsClientUrl, onDevToolsConnected, onRpcConnected, onRpcSeverReady, onViteRpcConnected, refreshCurrentPageData, rpc, rpcServer, setDevToolsClientUrl, useDevToolsState, viteRpc, viteRpcFunctions };
+526
View File
@@ -0,0 +1,526 @@
import { isBrowser, target } from "@vue/devtools-shared";
import { DevToolsContextHookKeys, DevToolsMessagingHookKeys, createRpcClient, createRpcServer, devtools, devtoolsRouter, devtoolsRouterInfo, getActiveInspectors, getInspector, getInspectorActions, getInspectorInfo, getInspectorNodeActions, getRpcClient, getRpcServer, getViteRpcClient, stringify, toggleClientConnected, updateDevToolsClientDetected, updateTimelineLayersState } from "@vue/devtools-kit";
import { computed, inject, onUnmounted, ref, watch } from "vue";
//#region src/client.ts
function setDevToolsClientUrl(url) {
target.__VUE_DEVTOOLS_CLIENT_URL__ = url;
}
function getDevToolsClientUrl() {
return target.__VUE_DEVTOOLS_CLIENT_URL__ ?? (() => {
if (isBrowser) {
const devtoolsMeta = document.querySelector("meta[name=__VUE_DEVTOOLS_CLIENT_URL__]");
if (devtoolsMeta) return devtoolsMeta.getAttribute("content");
}
return "";
})();
}
//#endregion
//#region ../../node_modules/.pnpm/hookable@5.5.3/node_modules/hookable/dist/index.mjs
function flatHooks(configHooks, hooks = {}, parentName) {
for (const key in configHooks) {
const subHook = configHooks[key];
const name = parentName ? `${parentName}:${key}` : key;
if (typeof subHook === "object" && subHook !== null) flatHooks(subHook, hooks, name);
else if (typeof subHook === "function") hooks[name] = subHook;
}
return hooks;
}
const defaultTask = { run: (function_) => function_() };
const _createTask = () => defaultTask;
const createTask = typeof console.createTask !== "undefined" ? console.createTask : _createTask;
function serialTaskCaller(hooks, args) {
const task = createTask(args.shift());
return hooks.reduce((promise, hookFunction) => promise.then(() => task.run(() => hookFunction(...args))), Promise.resolve());
}
function parallelTaskCaller(hooks, args) {
const task = createTask(args.shift());
return Promise.all(hooks.map((hook) => task.run(() => hook(...args))));
}
function callEachWith(callbacks, arg0) {
for (const callback of [...callbacks]) callback(arg0);
}
var Hookable = class {
constructor() {
this._hooks = {};
this._before = void 0;
this._after = void 0;
this._deprecatedMessages = void 0;
this._deprecatedHooks = {};
this.hook = this.hook.bind(this);
this.callHook = this.callHook.bind(this);
this.callHookWith = this.callHookWith.bind(this);
}
hook(name, function_, options = {}) {
if (!name || typeof function_ !== "function") return () => {};
const originalName = name;
let dep;
while (this._deprecatedHooks[name]) {
dep = this._deprecatedHooks[name];
name = dep.to;
}
if (dep && !options.allowDeprecated) {
let message = dep.message;
if (!message) message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
if (!this._deprecatedMessages) this._deprecatedMessages = /* @__PURE__ */ new Set();
if (!this._deprecatedMessages.has(message)) {
console.warn(message);
this._deprecatedMessages.add(message);
}
}
if (!function_.name) try {
Object.defineProperty(function_, "name", {
get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
configurable: true
});
} catch {}
this._hooks[name] = this._hooks[name] || [];
this._hooks[name].push(function_);
return () => {
if (function_) {
this.removeHook(name, function_);
function_ = void 0;
}
};
}
hookOnce(name, function_) {
let _unreg;
let _function = (...arguments_) => {
if (typeof _unreg === "function") _unreg();
_unreg = void 0;
_function = void 0;
return function_(...arguments_);
};
_unreg = this.hook(name, _function);
return _unreg;
}
removeHook(name, function_) {
if (this._hooks[name]) {
const index = this._hooks[name].indexOf(function_);
if (index !== -1) this._hooks[name].splice(index, 1);
if (this._hooks[name].length === 0) delete this._hooks[name];
}
}
deprecateHook(name, deprecated) {
this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
const _hooks = this._hooks[name] || [];
delete this._hooks[name];
for (const hook of _hooks) this.hook(name, hook);
}
deprecateHooks(deprecatedHooks) {
Object.assign(this._deprecatedHooks, deprecatedHooks);
for (const name in deprecatedHooks) this.deprecateHook(name, deprecatedHooks[name]);
}
addHooks(configHooks) {
const hooks = flatHooks(configHooks);
const removeFns = Object.keys(hooks).map((key) => this.hook(key, hooks[key]));
return () => {
for (const unreg of removeFns.splice(0, removeFns.length)) unreg();
};
}
removeHooks(configHooks) {
const hooks = flatHooks(configHooks);
for (const key in hooks) this.removeHook(key, hooks[key]);
}
removeAllHooks() {
for (const key in this._hooks) delete this._hooks[key];
}
callHook(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(serialTaskCaller, name, ...arguments_);
}
callHookParallel(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(parallelTaskCaller, name, ...arguments_);
}
callHookWith(caller, name, ...arguments_) {
const event = this._before || this._after ? {
name,
args: arguments_,
context: {}
} : void 0;
if (this._before) callEachWith(this._before, event);
const result = caller(name in this._hooks ? [...this._hooks[name]] : [], arguments_);
if (result instanceof Promise) return result.finally(() => {
if (this._after && event) callEachWith(this._after, event);
});
if (this._after && event) callEachWith(this._after, event);
return result;
}
beforeEach(function_) {
this._before = this._before || [];
this._before.push(function_);
return () => {
if (this._before !== void 0) {
const index = this._before.indexOf(function_);
if (index !== -1) this._before.splice(index, 1);
}
};
}
afterEach(function_) {
this._after = this._after || [];
this._after.push(function_);
return () => {
if (this._after !== void 0) {
const index = this._after.indexOf(function_);
if (index !== -1) this._after.splice(index, 1);
}
};
}
};
function createHooks() {
return new Hookable();
}
//#endregion
//#region src/rpc/global.ts
const hooks$1 = createHooks();
let DevToolsMessagingEvents = /* @__PURE__ */ function(DevToolsMessagingEvents) {
DevToolsMessagingEvents["INSPECTOR_TREE_UPDATED"] = "inspector-tree-updated";
DevToolsMessagingEvents["INSPECTOR_STATE_UPDATED"] = "inspector-state-updated";
DevToolsMessagingEvents["DEVTOOLS_STATE_UPDATED"] = "devtools-state-updated";
DevToolsMessagingEvents["ROUTER_INFO_UPDATED"] = "router-info-updated";
DevToolsMessagingEvents["TIMELINE_EVENT_UPDATED"] = "timeline-event-updated";
DevToolsMessagingEvents["INSPECTOR_UPDATED"] = "inspector-updated";
DevToolsMessagingEvents["ACTIVE_APP_UNMOUNTED"] = "active-app-updated";
DevToolsMessagingEvents["DESTROY_DEVTOOLS_CLIENT"] = "destroy-devtools-client";
DevToolsMessagingEvents["RELOAD_DEVTOOLS_CLIENT"] = "reload-devtools-client";
return DevToolsMessagingEvents;
}({});
function getDevToolsState() {
const state = devtools.ctx.state;
return {
connected: state.connected,
clientConnected: true,
vueVersion: state?.activeAppRecord?.version || "",
tabs: state.tabs,
commands: state.commands,
vitePluginDetected: state.vitePluginDetected,
appRecords: state.appRecords.map((item) => ({
id: item.id,
name: item.name,
version: item.version,
routerId: item.routerId,
iframe: item.iframe
})),
activeAppRecordId: state.activeAppRecordId,
timelineLayersState: state.timelineLayersState
};
}
const functions = {
on: (event, handler) => {
hooks$1.hook(event, handler);
},
off: (event, handler) => {
hooks$1.removeHook(event, handler);
},
once: (event, handler) => {
hooks$1.hookOnce(event, handler);
},
emit: (event, ...args) => {
hooks$1.callHook(event, ...args);
},
heartbeat: () => {
return true;
},
devtoolsState: () => {
return getDevToolsState();
},
async getInspectorTree(payload) {
return stringify(await devtools.ctx.api.getInspectorTree(payload));
},
async getInspectorState(payload) {
const inspector = getInspector(payload.inspectorId);
if (inspector) inspector.selectedNodeId = payload.nodeId;
return stringify(await devtools.ctx.api.getInspectorState(payload));
},
async editInspectorState(payload) {
return await devtools.ctx.api.editInspectorState(payload);
},
sendInspectorState(id) {
return devtools.ctx.api.sendInspectorState(id);
},
inspectComponentInspector() {
return devtools.ctx.api.inspectComponentInspector();
},
cancelInspectComponentInspector() {
return devtools.ctx.api.cancelInspectComponentInspector();
},
getComponentRenderCode(id) {
return devtools.ctx.api.getComponentRenderCode(id);
},
scrollToComponent(id) {
return devtools.ctx.api.scrollToComponent(id);
},
inspectDOM(id) {
return devtools.ctx.api.inspectDOM(id);
},
getInspectorNodeActions(id) {
return getInspectorNodeActions(id);
},
getInspectorActions(id) {
return getInspectorActions(id);
},
updateTimelineLayersState(state) {
return updateTimelineLayersState(state);
},
callInspectorNodeAction(inspectorId, actionIndex, nodeId) {
const nodeActions = getInspectorNodeActions(inspectorId);
if (nodeActions?.length) nodeActions[actionIndex].action?.(nodeId);
},
callInspectorAction(inspectorId, actionIndex) {
const actions = getInspectorActions(inspectorId);
if (actions?.length) actions[actionIndex].action?.();
},
openInEditor(options) {
return devtools.ctx.api.openInEditor(options);
},
async checkVueInspectorDetected() {
return !!await devtools.ctx.api.getVueInspector();
},
async enableVueInspector() {
const inspector = await devtools?.api?.getVueInspector?.();
if (inspector) await inspector.enable();
},
async toggleApp(id, options) {
return devtools.ctx.api.toggleApp(id, options);
},
updatePluginSettings(pluginId, key, value) {
return devtools.ctx.api.updatePluginSettings(pluginId, key, value);
},
getPluginSettings(pluginId) {
return devtools.ctx.api.getPluginSettings(pluginId);
},
getRouterInfo() {
return devtoolsRouterInfo;
},
navigate(path) {
return devtoolsRouter.value?.push(path).catch(() => ({}));
},
getMatchedRoutes(path) {
const c = console.warn;
console.warn = () => {};
const matched = devtoolsRouter.value?.resolve?.({ path: path || "/" }).matched ?? [];
console.warn = c;
return matched;
},
toggleClientConnected(state) {
toggleClientConnected(state);
},
getCustomInspector() {
return getActiveInspectors();
},
getInspectorInfo(id) {
return getInspectorInfo(id);
},
highlighComponent(uid) {
return devtools.ctx.hooks.callHook(DevToolsContextHookKeys.COMPONENT_HIGHLIGHT, { uid });
},
unhighlight() {
return devtools.ctx.hooks.callHook(DevToolsContextHookKeys.COMPONENT_UNHIGHLIGHT);
},
updateDevToolsClientDetected(params) {
updateDevToolsClientDetected(params);
},
initDevToolsServerListener() {
const broadcast = getRpcServer().broadcast;
devtools.ctx.hooks.hook(DevToolsMessagingHookKeys.SEND_INSPECTOR_TREE_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.INSPECTOR_TREE_UPDATED, stringify(payload));
});
devtools.ctx.hooks.hook(DevToolsMessagingHookKeys.SEND_INSPECTOR_STATE_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.INSPECTOR_STATE_UPDATED, stringify(payload));
});
devtools.ctx.hooks.hook(DevToolsMessagingHookKeys.DEVTOOLS_STATE_UPDATED, () => {
broadcast.emit(DevToolsMessagingEvents.DEVTOOLS_STATE_UPDATED, getDevToolsState());
});
devtools.ctx.hooks.hook(DevToolsMessagingHookKeys.ROUTER_INFO_UPDATED, ({ state }) => {
broadcast.emit(DevToolsMessagingEvents.ROUTER_INFO_UPDATED, state);
});
devtools.ctx.hooks.hook(DevToolsMessagingHookKeys.SEND_TIMELINE_EVENT_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.TIMELINE_EVENT_UPDATED, stringify(payload));
});
devtools.ctx.hooks.hook(DevToolsMessagingHookKeys.SEND_INSPECTOR_TO_CLIENT, (payload) => {
broadcast.emit(DevToolsMessagingEvents.INSPECTOR_UPDATED, payload);
});
devtools.ctx.hooks.hook(DevToolsMessagingHookKeys.SEND_ACTIVE_APP_UNMOUNTED_TO_CLIENT, () => {
broadcast.emit(DevToolsMessagingEvents.ACTIVE_APP_UNMOUNTED);
});
}
};
const rpc = new Proxy({
value: {},
functions: {}
}, { get(target, property) {
const _rpc = getRpcClient();
if (property === "value") return _rpc;
else if (property === "functions") return _rpc.$functions;
} });
const rpcServer = new Proxy({
value: {},
functions: {}
}, { get(target, property) {
const _rpc = getRpcServer();
if (property === "value") return _rpc;
else if (property === "functions") return _rpc.functions;
} });
function onRpcConnected(callback) {
let timer = null;
let retryCount = 0;
function heartbeat() {
rpc.value?.heartbeat?.().then(() => {
callback();
clearTimeout(timer);
}).catch(() => {});
}
timer = setInterval(() => {
if (retryCount >= 30) clearTimeout(timer);
retryCount++;
heartbeat();
}, retryCount * 200 + 200);
heartbeat();
}
function onRpcSeverReady(callback) {
let timer = null;
const timeout = 120;
function heartbeat() {
if (rpcServer.value.clients.length > 0) {
callback();
clearTimeout(timer);
}
}
timer = setInterval(() => {
heartbeat();
}, timeout);
}
//#endregion
//#region src/rpc/vite.ts
const hooks = createHooks();
const viteRpcFunctions = {
on: (event, handler) => {
hooks.hook(event, handler);
},
off: (event, handler) => {
hooks.removeHook(event, handler);
},
once: (event, handler) => {
hooks.hookOnce(event, handler);
},
emit: (event, ...args) => {
hooks.callHook(event, ...args);
},
heartbeat: () => {
return true;
}
};
const viteRpc = new Proxy({
value: {},
functions: {}
}, { get(target, property) {
const _rpc = getViteRpcClient();
if (property === "value") return _rpc;
else if (property === "functions") return _rpc?.$functions;
} });
function onViteRpcConnected(callback) {
let timer = null;
function heartbeat() {
viteRpc.value?.heartbeat?.().then(() => {
clearTimeout(timer);
callback();
}).catch(() => ({}));
timer = setTimeout(() => {
heartbeat();
}, 80);
}
heartbeat();
}
function createViteClientRpc() {
createRpcClient(viteRpcFunctions, { preset: "vite" });
}
function createViteServerRpc(functions) {
createRpcServer(functions, { preset: "vite" });
}
//#endregion
//#region src/vue-plugin/devtools-state.ts
const VueDevToolsStateSymbol = Symbol.for("__VueDevToolsStateSymbol__");
function VueDevToolsVuePlugin() {
return { install(app) {
const state = createDevToolsStateContext();
state.getDevToolsState();
app.provide(VueDevToolsStateSymbol, state);
app.config.globalProperties.$getDevToolsState = state.getDevToolsState;
app.config.globalProperties.$disconnectDevToolsClient = () => {
state.clientConnected.value = false;
state.connected.value = false;
};
} };
}
function createDevToolsStateContext() {
const connected = ref(false);
const clientConnected = ref(false);
const vueVersion = ref("");
const tabs = ref([]);
const commands = ref([]);
const vitePluginDetected = ref(false);
const appRecords = ref([]);
const activeAppRecordId = ref("");
const timelineLayersState = ref({});
function updateState(data) {
connected.value = data.connected;
clientConnected.value = data.clientConnected;
vueVersion.value = data.vueVersion || "";
tabs.value = data.tabs;
commands.value = data.commands;
vitePluginDetected.value = data.vitePluginDetected;
appRecords.value = data.appRecords;
activeAppRecordId.value = data.activeAppRecordId;
timelineLayersState.value = data.timelineLayersState;
}
function getDevToolsState() {
onRpcConnected(() => {
rpc.value.devtoolsState().then((data) => {
updateState(data);
});
rpc.functions.off(DevToolsMessagingEvents.DEVTOOLS_STATE_UPDATED, updateState);
rpc.functions.on(DevToolsMessagingEvents.DEVTOOLS_STATE_UPDATED, updateState);
});
}
return {
getDevToolsState,
connected,
clientConnected,
vueVersion,
tabs,
commands,
vitePluginDetected,
appRecords,
activeAppRecordId,
timelineLayersState
};
}
function useDevToolsState() {
return inject(VueDevToolsStateSymbol);
}
const fns = [];
function onDevToolsConnected(fn) {
const { connected, clientConnected } = useDevToolsState();
fns.push(fn);
onUnmounted(() => {
fns.splice(fns.indexOf(fn), 1);
});
const devtoolsReady = computed(() => clientConnected.value && connected.value);
if (devtoolsReady.value) fn();
else {
const stop = watch(devtoolsReady, (v) => {
if (v) {
fn();
stop();
}
});
}
return () => {
fns.splice(fns.indexOf(fn), 1);
};
}
function refreshCurrentPageData() {
fns.forEach((fn) => fn());
}
//#endregion
export { DevToolsMessagingEvents, VueDevToolsVuePlugin, createDevToolsStateContext, createViteClientRpc, createViteServerRpc, functions, getDevToolsClientUrl, onDevToolsConnected, onRpcConnected, onRpcSeverReady, onViteRpcConnected, refreshCurrentPageData, rpc, rpcServer, setDevToolsClientUrl, useDevToolsState, viteRpc, viteRpcFunctions };
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@vue/devtools-core",
"type": "module",
"version": "8.2.1",
"author": "webfansplz",
"license": "MIT",
"repository": {
"directory": "packages/core",
"type": "git",
"url": "git+https://github.com/vuejs/devtools.git"
},
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"files": [
"dist",
"server.d.ts"
],
"peerDependencies": {
"vue": "^3.0.0"
},
"dependencies": {
"@vue/devtools-kit": "^8.2.1",
"@vue/devtools-shared": "^8.2.1"
},
"devDependencies": {
"vue": "^3.5.22"
},
"scripts": {
"build": "tsdown --clean",
"prepare:type": "tsdown --dts-only",
"stub": "tsdown --watch --onSuccess 'tsdown --dts-only'"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 webfansplz
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.
+3
View File
@@ -0,0 +1,3 @@
# @vue/devtools-kit
> Utility kit for DevTools.
+5750
View File
File diff suppressed because it is too large Load Diff
+1170
View File
File diff suppressed because it is too large Load Diff
+1170
View File
File diff suppressed because it is too large Load Diff
+5668
View File
File diff suppressed because it is too large Load Diff
+20
View File
@@ -0,0 +1,20 @@
import type { DevToolsHook, RouterInfo } from './src/types'
/* eslint-disable vars-on-top */
declare global {
var __VUE_DEVTOOLS_GLOBAL_HOOK__: DevToolsHook
var __VUE_DEVTOOLS_NEXT_APP_RECORD_INFO__: {
id: number
appIds: Set<string>
}
var __VUE_DEVTOOLS_ROUTER_INFO__: RouterInfo
var __VUE_DEVTOOLS_ENV__: {
vitePluginDetected: boolean
}
var __VUE_DEVTOOLS_COMPONENT_INSPECTOR_ENABLED__: boolean
var __VUE_DEVTOOLS_VITE_PLUGIN_DETECTED__: boolean
var __VUE_DEVTOOLS_VITE_PLUGIN_CLIENT_URL__: string
var __VUE_DEVTOOLS_BROWSER_EXTENSION_DETECTED__: boolean
}
export { }
+44
View File
@@ -0,0 +1,44 @@
{
"name": "@vue/devtools-kit",
"type": "module",
"version": "8.2.1",
"author": "webfansplz",
"license": "MIT",
"repository": {
"directory": "packages/devtools-kit",
"type": "git",
"url": "git+https://github.com/vuejs/devtools.git"
},
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./types.d.ts",
"files": [
"**.d.ts",
"dist"
],
"dependencies": {
"birpc": "^2.6.1",
"hookable": "^5.5.3",
"perfect-debounce": "^2.0.0",
"@vue/devtools-shared": "^8.2.1"
},
"devDependencies": {
"@types/speakingurl": "^13.0.6",
"speakingurl": "^14.0.1",
"superjson": "^2.2.2",
"vue": "^3.5.22",
"vue-router": "^4.6.0"
},
"scripts": {
"build": "tsdown --clean",
"prepare:type": "tsdown --dts-only",
"stub": "tsdown --watch --onSuccess 'tsdown --dts-only'"
}
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="./global.d.ts" />
export * from './dist/index'
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 webfansplz
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.
+3
View File
@@ -0,0 +1,3 @@
# @vue/devtools-shared
> Internal utility types shared across @vue/devtools packages.
+265
View File
@@ -0,0 +1,265 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
//#region src/constants.ts
const VIEW_MODE_STORAGE_KEY = "__vue-devtools-view-mode__";
const VITE_PLUGIN_DETECTED_STORAGE_KEY = "__vue-devtools-vite-plugin-detected__";
const VITE_PLUGIN_CLIENT_URL_STORAGE_KEY = "__vue-devtools-vite-plugin-client-url__";
const BROADCAST_CHANNEL_NAME = "__vue-devtools-broadcast-channel__";
//#endregion
//#region src/env.ts
const isBrowser = typeof navigator !== "undefined";
const target = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : {};
const isInChromePanel = typeof target.chrome !== "undefined" && !!target.chrome.devtools;
const isInIframe = isBrowser && target.self !== target.top;
const isInElectron = typeof navigator !== "undefined" && navigator.userAgent?.toLowerCase().includes("electron");
const isNuxtApp = typeof window !== "undefined" && !!window.__NUXT__;
const isInSeparateWindow = !isInIframe && !isInChromePanel && !isInElectron;
//#endregion
//#region src/general.ts
var import_rfdc = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
module.exports = rfdc;
function copyBuffer(cur) {
if (cur instanceof Buffer) return Buffer.from(cur);
return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length);
}
function rfdc(opts) {
opts = opts || {};
if (opts.circles) return rfdcCircles(opts);
const constructorHandlers = /* @__PURE__ */ new Map();
constructorHandlers.set(Date, (o) => new Date(o));
constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));
constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));
if (opts.constructorHandlers) for (const handler of opts.constructorHandlers) constructorHandlers.set(handler[0], handler[1]);
let handler = null;
return opts.proto ? cloneProto : clone;
function cloneArray(a, fn) {
const keys = Object.keys(a);
const a2 = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const cur = a[k];
if (typeof cur !== "object" || cur === null) a2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) a2[k] = handler(cur, fn);
else if (ArrayBuffer.isView(cur)) a2[k] = copyBuffer(cur);
else a2[k] = fn(cur);
}
return a2;
}
function clone(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, clone);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, clone);
const o2 = {};
for (const k in o) {
if (Object.hasOwnProperty.call(o, k) === false) continue;
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, clone);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else o2[k] = clone(cur);
}
return o2;
}
function cloneProto(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, cloneProto);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, cloneProto);
const o2 = {};
for (const k in o) {
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, cloneProto);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else o2[k] = cloneProto(cur);
}
return o2;
}
}
function rfdcCircles(opts) {
const refs = [];
const refsNew = [];
const constructorHandlers = /* @__PURE__ */ new Map();
constructorHandlers.set(Date, (o) => new Date(o));
constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));
constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));
if (opts.constructorHandlers) for (const handler of opts.constructorHandlers) constructorHandlers.set(handler[0], handler[1]);
let handler = null;
return opts.proto ? cloneProto : clone;
function cloneArray(a, fn) {
const keys = Object.keys(a);
const a2 = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const cur = a[k];
if (typeof cur !== "object" || cur === null) a2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) a2[k] = handler(cur, fn);
else if (ArrayBuffer.isView(cur)) a2[k] = copyBuffer(cur);
else {
const index = refs.indexOf(cur);
if (index !== -1) a2[k] = refsNew[index];
else a2[k] = fn(cur);
}
}
return a2;
}
function clone(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, clone);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, clone);
const o2 = {};
refs.push(o);
refsNew.push(o2);
for (const k in o) {
if (Object.hasOwnProperty.call(o, k) === false) continue;
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, clone);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else {
const i = refs.indexOf(cur);
if (i !== -1) o2[k] = refsNew[i];
else o2[k] = clone(cur);
}
}
refs.pop();
refsNew.pop();
return o2;
}
function cloneProto(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, cloneProto);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, cloneProto);
const o2 = {};
refs.push(o);
refsNew.push(o2);
for (const k in o) {
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, cloneProto);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else {
const i = refs.indexOf(cur);
if (i !== -1) o2[k] = refsNew[i];
else o2[k] = cloneProto(cur);
}
}
refs.pop();
refsNew.pop();
return o2;
}
}
})))(), 1);
function NOOP() {}
const isNumeric = (str) => `${+str}` === str;
const isMacOS = () => navigator?.platform ? navigator?.platform.toLowerCase().includes("mac") : /Macintosh/.test(navigator.userAgent);
const classifyRE = /(?:^|[-_/])(\w)/g;
const camelizeRE = /-(\w)/g;
const kebabizeRE = /([a-z0-9])([A-Z])/g;
function toUpper(_, c) {
return c ? c.toUpperCase() : "";
}
function classify(str) {
return str && `${str}`.replace(classifyRE, toUpper);
}
function camelize(str) {
return str && str.replace(camelizeRE, toUpper);
}
function kebabize(str) {
return str && str.replace(kebabizeRE, (_, lowerCaseCharacter, upperCaseLetter) => {
return `${lowerCaseCharacter}-${upperCaseLetter}`;
}).toLowerCase();
}
function basename(filename, ext) {
let normalizedFilename = filename.replace(/^[a-z]:/i, "").replace(/\\/g, "/");
if (normalizedFilename.endsWith(`index${ext}`)) normalizedFilename = normalizedFilename.replace(`/index${ext}`, ext);
const lastSlashIndex = normalizedFilename.lastIndexOf("/");
const baseNameWithExt = normalizedFilename.substring(lastSlashIndex + 1);
if (ext) {
const extIndex = baseNameWithExt.lastIndexOf(ext);
return baseNameWithExt.substring(0, extIndex);
}
return "";
}
function sortByKey(state) {
return state && state.slice().sort((a, b) => {
if (a.key < b.key) return -1;
if (a.key > b.key) return 1;
return 0;
});
}
const HTTP_URL_RE = /^https?:\/\//;
/**
* Check a string is start with `/` or a valid http url
*/
function isUrlString(str) {
return str.startsWith("/") || HTTP_URL_RE.test(str);
}
/**
* @copyright [rfdc](https://github.com/davidmarkclements/rfdc)
* @description A really fast deep clone alternative
*/
const deepClone = (0, import_rfdc.default)({ circles: true });
function randomStr() {
return Math.random().toString(36).slice(2);
}
function isObject(value) {
return typeof value === "object" && !Array.isArray(value) && value !== null;
}
function isArray(value) {
return Array.isArray(value);
}
function isSet(value) {
return value instanceof Set;
}
function isMap(value) {
return value instanceof Map;
}
//#endregion
exports.BROADCAST_CHANNEL_NAME = BROADCAST_CHANNEL_NAME;
exports.NOOP = NOOP;
exports.VIEW_MODE_STORAGE_KEY = VIEW_MODE_STORAGE_KEY;
exports.VITE_PLUGIN_CLIENT_URL_STORAGE_KEY = VITE_PLUGIN_CLIENT_URL_STORAGE_KEY;
exports.VITE_PLUGIN_DETECTED_STORAGE_KEY = VITE_PLUGIN_DETECTED_STORAGE_KEY;
exports.basename = basename;
exports.camelize = camelize;
exports.classify = classify;
exports.deepClone = deepClone;
exports.isArray = isArray;
exports.isBrowser = isBrowser;
exports.isInChromePanel = isInChromePanel;
exports.isInElectron = isInElectron;
exports.isInIframe = isInIframe;
exports.isInSeparateWindow = isInSeparateWindow;
exports.isMacOS = isMacOS;
exports.isMap = isMap;
exports.isNumeric = isNumeric;
exports.isNuxtApp = isNuxtApp;
exports.isObject = isObject;
exports.isSet = isSet;
exports.isUrlString = isUrlString;
exports.kebabize = kebabize;
exports.randomStr = randomStr;
exports.sortByKey = sortByKey;
exports.target = target;
+40
View File
@@ -0,0 +1,40 @@
//#region src/constants.d.ts
declare const VIEW_MODE_STORAGE_KEY = "__vue-devtools-view-mode__";
declare const VITE_PLUGIN_DETECTED_STORAGE_KEY = "__vue-devtools-vite-plugin-detected__";
declare const VITE_PLUGIN_CLIENT_URL_STORAGE_KEY = "__vue-devtools-vite-plugin-client-url__";
declare const BROADCAST_CHANNEL_NAME = "__vue-devtools-broadcast-channel__";
//#endregion
//#region src/env.d.ts
declare const isBrowser: boolean;
declare const target: typeof globalThis;
declare const isInChromePanel: boolean;
declare const isInIframe: boolean;
declare const isInElectron: boolean;
declare const isNuxtApp: boolean;
declare const isInSeparateWindow: boolean;
//#endregion
//#region src/general.d.ts
declare function NOOP(): void;
declare const isNumeric: (str: string | number) => boolean;
declare const isMacOS: () => boolean;
declare function classify(str: string): string;
declare function camelize(str: string): string;
declare function kebabize(str: string): string;
declare function basename(filename: string, ext: string): string;
declare function sortByKey(state: unknown[]): Record<"key", number>[];
/**
* Check a string is start with `/` or a valid http url
*/
declare function isUrlString(str: string): boolean;
/**
* @copyright [rfdc](https://github.com/davidmarkclements/rfdc)
* @description A really fast deep clone alternative
*/
declare const deepClone: <T>(input: T) => T;
declare function randomStr(): string;
declare function isObject<T extends object>(value: any): value is T;
declare function isArray<T>(value: any): value is T[];
declare function isSet<T>(value: any): value is Set<T>;
declare function isMap<K, V>(value: any): value is Map<K, V>;
//#endregion
export { BROADCAST_CHANNEL_NAME, NOOP, VIEW_MODE_STORAGE_KEY, VITE_PLUGIN_CLIENT_URL_STORAGE_KEY, VITE_PLUGIN_DETECTED_STORAGE_KEY, basename, camelize, classify, deepClone, isArray, isBrowser, isInChromePanel, isInElectron, isInIframe, isInSeparateWindow, isMacOS, isMap, isNumeric, isNuxtApp, isObject, isSet, isUrlString, kebabize, randomStr, sortByKey, target };
+40
View File
@@ -0,0 +1,40 @@
//#region src/constants.d.ts
declare const VIEW_MODE_STORAGE_KEY = "__vue-devtools-view-mode__";
declare const VITE_PLUGIN_DETECTED_STORAGE_KEY = "__vue-devtools-vite-plugin-detected__";
declare const VITE_PLUGIN_CLIENT_URL_STORAGE_KEY = "__vue-devtools-vite-plugin-client-url__";
declare const BROADCAST_CHANNEL_NAME = "__vue-devtools-broadcast-channel__";
//#endregion
//#region src/env.d.ts
declare const isBrowser: boolean;
declare const target: typeof globalThis;
declare const isInChromePanel: boolean;
declare const isInIframe: boolean;
declare const isInElectron: boolean;
declare const isNuxtApp: boolean;
declare const isInSeparateWindow: boolean;
//#endregion
//#region src/general.d.ts
declare function NOOP(): void;
declare const isNumeric: (str: string | number) => boolean;
declare const isMacOS: () => boolean;
declare function classify(str: string): string;
declare function camelize(str: string): string;
declare function kebabize(str: string): string;
declare function basename(filename: string, ext: string): string;
declare function sortByKey(state: unknown[]): Record<"key", number>[];
/**
* Check a string is start with `/` or a valid http url
*/
declare function isUrlString(str: string): boolean;
/**
* @copyright [rfdc](https://github.com/davidmarkclements/rfdc)
* @description A really fast deep clone alternative
*/
declare const deepClone: <T>(input: T) => T;
declare function randomStr(): string;
declare function isObject<T extends object>(value: any): value is T;
declare function isArray<T>(value: any): value is T[];
declare function isSet<T>(value: any): value is Set<T>;
declare function isMap<K, V>(value: any): value is Map<K, V>;
//#endregion
export { BROADCAST_CHANNEL_NAME, NOOP, VIEW_MODE_STORAGE_KEY, VITE_PLUGIN_CLIENT_URL_STORAGE_KEY, VITE_PLUGIN_DETECTED_STORAGE_KEY, basename, camelize, classify, deepClone, isArray, isBrowser, isInChromePanel, isInElectron, isInIframe, isInSeparateWindow, isMacOS, isMap, isNumeric, isNuxtApp, isObject, isSet, isUrlString, kebabize, randomStr, sortByKey, target };
+239
View File
@@ -0,0 +1,239 @@
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
//#region src/constants.ts
const VIEW_MODE_STORAGE_KEY = "__vue-devtools-view-mode__";
const VITE_PLUGIN_DETECTED_STORAGE_KEY = "__vue-devtools-vite-plugin-detected__";
const VITE_PLUGIN_CLIENT_URL_STORAGE_KEY = "__vue-devtools-vite-plugin-client-url__";
const BROADCAST_CHANNEL_NAME = "__vue-devtools-broadcast-channel__";
//#endregion
//#region src/env.ts
const isBrowser = typeof navigator !== "undefined";
const target = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : {};
const isInChromePanel = typeof target.chrome !== "undefined" && !!target.chrome.devtools;
const isInIframe = isBrowser && target.self !== target.top;
const isInElectron = typeof navigator !== "undefined" && navigator.userAgent?.toLowerCase().includes("electron");
const isNuxtApp = typeof window !== "undefined" && !!window.__NUXT__;
const isInSeparateWindow = !isInIframe && !isInChromePanel && !isInElectron;
//#endregion
//#region src/general.ts
var import_rfdc = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
module.exports = rfdc;
function copyBuffer(cur) {
if (cur instanceof Buffer) return Buffer.from(cur);
return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length);
}
function rfdc(opts) {
opts = opts || {};
if (opts.circles) return rfdcCircles(opts);
const constructorHandlers = /* @__PURE__ */ new Map();
constructorHandlers.set(Date, (o) => new Date(o));
constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));
constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));
if (opts.constructorHandlers) for (const handler of opts.constructorHandlers) constructorHandlers.set(handler[0], handler[1]);
let handler = null;
return opts.proto ? cloneProto : clone;
function cloneArray(a, fn) {
const keys = Object.keys(a);
const a2 = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const cur = a[k];
if (typeof cur !== "object" || cur === null) a2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) a2[k] = handler(cur, fn);
else if (ArrayBuffer.isView(cur)) a2[k] = copyBuffer(cur);
else a2[k] = fn(cur);
}
return a2;
}
function clone(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, clone);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, clone);
const o2 = {};
for (const k in o) {
if (Object.hasOwnProperty.call(o, k) === false) continue;
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, clone);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else o2[k] = clone(cur);
}
return o2;
}
function cloneProto(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, cloneProto);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, cloneProto);
const o2 = {};
for (const k in o) {
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, cloneProto);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else o2[k] = cloneProto(cur);
}
return o2;
}
}
function rfdcCircles(opts) {
const refs = [];
const refsNew = [];
const constructorHandlers = /* @__PURE__ */ new Map();
constructorHandlers.set(Date, (o) => new Date(o));
constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));
constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));
if (opts.constructorHandlers) for (const handler of opts.constructorHandlers) constructorHandlers.set(handler[0], handler[1]);
let handler = null;
return opts.proto ? cloneProto : clone;
function cloneArray(a, fn) {
const keys = Object.keys(a);
const a2 = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const cur = a[k];
if (typeof cur !== "object" || cur === null) a2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) a2[k] = handler(cur, fn);
else if (ArrayBuffer.isView(cur)) a2[k] = copyBuffer(cur);
else {
const index = refs.indexOf(cur);
if (index !== -1) a2[k] = refsNew[index];
else a2[k] = fn(cur);
}
}
return a2;
}
function clone(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, clone);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, clone);
const o2 = {};
refs.push(o);
refsNew.push(o2);
for (const k in o) {
if (Object.hasOwnProperty.call(o, k) === false) continue;
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, clone);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else {
const i = refs.indexOf(cur);
if (i !== -1) o2[k] = refsNew[i];
else o2[k] = clone(cur);
}
}
refs.pop();
refsNew.pop();
return o2;
}
function cloneProto(o) {
if (typeof o !== "object" || o === null) return o;
if (Array.isArray(o)) return cloneArray(o, cloneProto);
if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) return handler(o, cloneProto);
const o2 = {};
refs.push(o);
refsNew.push(o2);
for (const k in o) {
const cur = o[k];
if (typeof cur !== "object" || cur === null) o2[k] = cur;
else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) o2[k] = handler(cur, cloneProto);
else if (ArrayBuffer.isView(cur)) o2[k] = copyBuffer(cur);
else {
const i = refs.indexOf(cur);
if (i !== -1) o2[k] = refsNew[i];
else o2[k] = cloneProto(cur);
}
}
refs.pop();
refsNew.pop();
return o2;
}
}
})))(), 1);
function NOOP() {}
const isNumeric = (str) => `${+str}` === str;
const isMacOS = () => navigator?.platform ? navigator?.platform.toLowerCase().includes("mac") : /Macintosh/.test(navigator.userAgent);
const classifyRE = /(?:^|[-_/])(\w)/g;
const camelizeRE = /-(\w)/g;
const kebabizeRE = /([a-z0-9])([A-Z])/g;
function toUpper(_, c) {
return c ? c.toUpperCase() : "";
}
function classify(str) {
return str && `${str}`.replace(classifyRE, toUpper);
}
function camelize(str) {
return str && str.replace(camelizeRE, toUpper);
}
function kebabize(str) {
return str && str.replace(kebabizeRE, (_, lowerCaseCharacter, upperCaseLetter) => {
return `${lowerCaseCharacter}-${upperCaseLetter}`;
}).toLowerCase();
}
function basename(filename, ext) {
let normalizedFilename = filename.replace(/^[a-z]:/i, "").replace(/\\/g, "/");
if (normalizedFilename.endsWith(`index${ext}`)) normalizedFilename = normalizedFilename.replace(`/index${ext}`, ext);
const lastSlashIndex = normalizedFilename.lastIndexOf("/");
const baseNameWithExt = normalizedFilename.substring(lastSlashIndex + 1);
if (ext) {
const extIndex = baseNameWithExt.lastIndexOf(ext);
return baseNameWithExt.substring(0, extIndex);
}
return "";
}
function sortByKey(state) {
return state && state.slice().sort((a, b) => {
if (a.key < b.key) return -1;
if (a.key > b.key) return 1;
return 0;
});
}
const HTTP_URL_RE = /^https?:\/\//;
/**
* Check a string is start with `/` or a valid http url
*/
function isUrlString(str) {
return str.startsWith("/") || HTTP_URL_RE.test(str);
}
/**
* @copyright [rfdc](https://github.com/davidmarkclements/rfdc)
* @description A really fast deep clone alternative
*/
const deepClone = (0, import_rfdc.default)({ circles: true });
function randomStr() {
return Math.random().toString(36).slice(2);
}
function isObject(value) {
return typeof value === "object" && !Array.isArray(value) && value !== null;
}
function isArray(value) {
return Array.isArray(value);
}
function isSet(value) {
return value instanceof Set;
}
function isMap(value) {
return value instanceof Map;
}
//#endregion
export { BROADCAST_CHANNEL_NAME, NOOP, VIEW_MODE_STORAGE_KEY, VITE_PLUGIN_CLIENT_URL_STORAGE_KEY, VITE_PLUGIN_DETECTED_STORAGE_KEY, basename, camelize, classify, deepClone, isArray, isBrowser, isInChromePanel, isInElectron, isInIframe, isInSeparateWindow, isMacOS, isMap, isNumeric, isNuxtApp, isObject, isSet, isUrlString, kebabize, randomStr, sortByKey, target };
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@vue/devtools-shared",
"type": "module",
"version": "8.2.1",
"author": "webfansplz",
"license": "MIT",
"repository": {
"directory": "packages/shared",
"type": "git",
"url": "git+https://github.com/vuejs/devtools.git"
},
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"files": [
"dist"
],
"devDependencies": {
"@types/node": "^24.7.2",
"rfdc": "^1.4.1"
},
"scripts": {
"build": "tsdown",
"prepare:type": "tsdown --dts-only",
"stub": "tsdown --watch --onSuccess 'tsdown --dts-only'"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Johnson Chu
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.
+162
View File
@@ -0,0 +1,162 @@
# @vue/language-core
<p>
<a href="https://www.npmjs.com/package/@vue/language-core"><img src="https://img.shields.io/npm/v/@vue/language-core.svg?labelColor=18181B&color=1584FC" alt="NPM version"></a>
<a href="https://github.com/vuejs/language-tools/blob/master/LICENSE"><img src="https://img.shields.io/github/license/vuejs/language-tools.svg?labelColor=18181B&color=1584FC" alt="License"></a>
</p>
The core module for Vue Language Tools, responsible for parsing Vue Single File Components (SFCs) and transforming them into virtual code structures that TypeScript can understand. This package is a low-level dependency for `@vue/language-server` and `vue-tsc`.
## Installation
```bash
npm install @vue/language-core
```
## Core API
### `createVueLanguagePlugin`
Creates a Vue language plugin for integration with Volar language services.
```typescript
import { createVueLanguagePlugin } from '@vue/language-core';
import type { LanguagePlugin } from '@volar/language-core';
import ts from 'typescript';
const plugin: LanguagePlugin<string> = createVueLanguagePlugin(
ts,
compilerOptions, // ts.CompilerOptions
vueCompilerOptions, // VueCompilerOptions
(scriptId) => scriptId // asFileName: Converts scriptId to a file name
);
```
### `createParsedCommandLine`
Parses TypeScript and Vue compiler options from `tsconfig.json`.
```typescript
import { createParsedCommandLine } from '@vue/language-core';
import ts from 'typescript';
const parsed = createParsedCommandLine(ts, ts.sys, '/path/to/tsconfig.json');
// parsed.options: ts.CompilerOptions
// parsed.vueOptions: VueCompilerOptions
```
### `parse`
Parses Vue SFC source code and returns an `SFCParseResult`.
```typescript
import { parse } from '@vue/language-core';
const result = parse(`
<template>
<div>{{ msg }}</div>
</template>
<script setup lang="ts">
const msg = 'Hello'
</script>
`);
// result.descriptor.template
// result.descriptor.scriptSetup
// result.descriptor.styles
// result.errors
```
## `vueCompilerOptions`
Configure Vue compiler behavior through the `vueCompilerOptions` field in `tsconfig.json`:
```jsonc
{
"compilerOptions": { /* ... */ },
"vueCompilerOptions": {
"target": 3.5,
"strictTemplates": true,
"plugins": ["@vue/language-plugin-pug"]
}
}
```
### File Handling Options
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `target` | `number \| 'auto'` | `'auto'` | Vue version. `'auto'` reads from `node_modules/vue/package.json`. |
| `extensions` | `string[]` | `['.vue']` | File extensions to be treated as Vue SFCs. |
| `vitePressExtensions` | `string[]` | `[]` | File extensions to be treated as VitePress Markdown. |
| `petiteVueExtensions` | `string[]` | `[]` | File extensions to be treated as Petite Vue HTML. |
| `plugins` | `string[]` | `[]` | Custom language plugins, e.g., [`@vue/language-plugin-pug`](../language-plugin-pug). |
### Type Checking Options
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `strictTemplates` | `boolean` | `false` | A convenience option that enables the four `check*` options below and `strictVModel`. |
| `checkUnknownProps` | `boolean` | `false` | Check for unknown props. |
| `checkUnknownEvents` | `boolean` | `false` | Check for unknown events. |
| `checkUnknownComponents` | `boolean` | `false` | Check for unknown components. |
| `checkUnknownDirectives` | `boolean` | `false` | Check for unknown directives. |
| `strictVModel` | `boolean` | `false` | Strictly check v-model bindings. |
| `strictCssModules` | `boolean` | `false` | Strictly check CSS Modules class names (not affected by `strictTemplates`). |
### Advanced Options
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `lib` | `string` | `'vue'` | Vue package name, used for generating import statements. |
| `skipTemplateCodegen` | `boolean` | `false` | Skip virtual code generation for templates. |
| `vapor` | `boolean` | `false` | Enable Vapor mode for all Vue SFCs. |
| `fallthroughAttributes` | `boolean` | `false` | Enable type inference for fallthrough attributes. |
| `checkRequiredFallthroughAttributes` | `boolean` | `false` | Check required fallthrough attributes. |
| `jsxSlots` | `boolean` | `false` | Use JSX-style slots types. |
| `dataAttributes` | `string[]` | `[]` | Allowed data-* attribute patterns. |
| `htmlAttributes` | `string[]` | `['aria-*']` | Allowed HTML attribute patterns. |
| `resolveStyleImports` | `boolean` | `false` | Resolve import statements in styles. |
| `resolveStyleClassNames` | `boolean \| 'scoped'` | `'scoped'` | Resolve class names in styles. |
## Built-in Plugins
This package includes the following built-in plugins to handle different file types and blocks:
### File Parsing Plugins
| Plugin | Function | Controlled By |
| :--- | :--- | :--- |
| `file-vue` | Parses `.vue` files into an SFC structure. | `extensions` |
| `file-md` | Parses Markdown files into an SFC structure. | `vitePressExtensions` |
| `file-html` | Parses HTML files into an SFC structure. | `petiteVueExtensions` |
### Virtual Code Generation Plugins
| Plugin | Function |
| :--- | :--- |
| `vue-tsx` | Generates TypeScript virtual code from an SFC. |
| `vue-template-html` | Compiles HTML templates. |
| `vue-template-inline-ts` | Handles TypeScript expressions in templates. |
| `vue-template-inline-css` | Handles inline styles in templates. |
| `vue-style-css` | Compiles CSS styles. |
| `vue-script-js` | Handles JavaScript script blocks. |
### Embedded Code Extraction Plugins
| Plugin | Function |
| :--- | :--- |
| `vue-sfc-template` | Extracts the `<template>` block. |
| `vue-sfc-styles` | Extracts `<style>` blocks. |
| `vue-sfc-scripts` | Extracts `<script>` blocks (for formatting). |
| `vue-sfc-customblocks` | Extracts custom blocks. |
## Related Packages
- [`@vue/language-server`](../language-server) - Language Server
- [`@vue/language-service`](../language-service) - Language Service
- [`vue-tsc`](../tsc) - Command-line Type Checker
## License
[MIT](https://github.com/vuejs/language-tools/blob/master/LICENSE) License
+17
View File
@@ -0,0 +1,17 @@
export * from './lib/codegen/codeFeatures';
export * from './lib/codegen/template';
export * from './lib/compilerOptions';
export * from './lib/languagePlugin';
export * from './lib/parsers/scriptRanges';
export * from './lib/parsers/scriptSetupRanges';
export * from './lib/plugins';
export * from './lib/template/compile';
export * from './lib/types';
export * from './lib/utils/collectBindings';
export * from './lib/utils/forEachTemplateNode';
export * from './lib/utils/parseSfc';
export * from './lib/utils/shared';
export * from './lib/virtualCode';
export { names } from './lib/codegen/names';
export { tsCodegen } from './lib/plugins/vue-tsx';
export * from '@volar/language-core';
+37
View File
@@ -0,0 +1,37 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsCodegen = exports.names = void 0;
__exportStar(require("./lib/codegen/codeFeatures"), exports);
__exportStar(require("./lib/codegen/template"), exports);
__exportStar(require("./lib/compilerOptions"), exports);
__exportStar(require("./lib/languagePlugin"), exports);
__exportStar(require("./lib/parsers/scriptRanges"), exports);
__exportStar(require("./lib/parsers/scriptSetupRanges"), exports);
__exportStar(require("./lib/plugins"), exports);
__exportStar(require("./lib/template/compile"), exports);
__exportStar(require("./lib/types"), exports);
__exportStar(require("./lib/utils/collectBindings"), exports);
__exportStar(require("./lib/utils/forEachTemplateNode"), exports);
__exportStar(require("./lib/utils/parseSfc"), exports);
__exportStar(require("./lib/utils/shared"), exports);
__exportStar(require("./lib/virtualCode"), exports);
var names_1 = require("./lib/codegen/names");
Object.defineProperty(exports, "names", { enumerable: true, get: function () { return names_1.names; } });
var vue_tsx_1 = require("./lib/plugins/vue-tsx");
Object.defineProperty(exports, "tsCodegen", { enumerable: true, get: function () { return vue_tsx_1.tsCodegen; } });
__exportStar(require("@volar/language-core"), exports);
//# sourceMappingURL=index.js.map
+26
View File
@@ -0,0 +1,26 @@
import type { VueCodeInformation } from '../types';
export declare const codeFeatures: {
full: VueCodeInformation;
all: VueCodeInformation;
importCompletionOnly: VueCodeInformation;
verification: VueCodeInformation;
completion: VueCodeInformation;
withoutCompletion: VueCodeInformation;
navigation: VueCodeInformation;
navigationWithoutRename: VueCodeInformation;
navigationAndCompletion: VueCodeInformation;
navigationAndVerification: VueCodeInformation;
withoutNavigation: VueCodeInformation;
semanticWithoutHighlight: VueCodeInformation;
withoutHighlight: VueCodeInformation;
withoutHighlightAndCompletion: VueCodeInformation;
withoutSemantic: VueCodeInformation;
structure: VueCodeInformation;
structureAndFormat: VueCodeInformation;
format: VueCodeInformation;
doNotReportTs2339AndTs2551: VueCodeInformation;
doNotReportTs2353AndTs2561: VueCodeInformation;
doNotReportTs6133: VueCodeInformation;
};
/** @deprecated use `codeFeatures.full` instead */
export declare const allCodeFeatures: VueCodeInformation;
+127
View File
@@ -0,0 +1,127 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.allCodeFeatures = exports.codeFeatures = void 0;
exports.codeFeatures = defineCodeFeatures({
full: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: true,
},
/** @internal */
all: {
verification: true,
completion: true,
semantic: true,
navigation: true,
},
/** @internal */
importCompletionOnly: {
__importCompletion: true,
},
/** @internal */
verification: {
verification: true,
},
/** @internal */
completion: {
completion: true,
},
/** @internal */
withoutCompletion: {
verification: true,
semantic: true,
navigation: true,
},
/** @internal */
navigation: {
navigation: true,
},
/** @internal */
navigationWithoutRename: {
navigation: { shouldRename: () => false },
},
/** @internal */
navigationAndCompletion: {
navigation: true,
completion: true,
},
/** @internal */
navigationAndVerification: {
navigation: true,
verification: true,
},
/** @internal */
withoutNavigation: {
verification: true,
completion: true,
semantic: true,
},
/** @internal */
semanticWithoutHighlight: {
semantic: { shouldHighlight: () => false },
},
/** @internal */
withoutHighlight: {
semantic: { shouldHighlight: () => false },
verification: true,
navigation: true,
completion: true,
},
/** @internal */
withoutHighlightAndCompletion: {
semantic: { shouldHighlight: () => false },
verification: true,
navigation: true,
},
/** @internal */
withoutSemantic: {
verification: true,
navigation: true,
completion: true,
},
/** @internal */
structure: {
structure: true,
},
/** @internal */
structureAndFormat: {
structure: true,
format: true,
},
/** @internal */
format: {
format: true,
},
/** @internal */
doNotReportTs2339AndTs2551: {
verification: {
// https://typescript.tv/errors/#ts2339
// https://typescript.tv/errors/#ts2551
shouldReport: (_source, code) => String(code) !== '2339' && String(code) !== '2551',
},
},
/** @internal */
doNotReportTs2353AndTs2561: {
verification: {
// https://typescript.tv/errors/#ts2353
// https://typescript.tv/errors/#ts2561
shouldReport: (_source, code) => String(code) !== '2353' && String(code) !== '2561',
},
},
/** @internal */
doNotReportTs6133: {
verification: {
// https://typescript.tv/errors/#ts6133
shouldReport: (_source, code) => String(code) !== '6133',
},
},
});
/** @deprecated use `codeFeatures.full` instead */
exports.allCodeFeatures = exports.codeFeatures.full;
function defineCodeFeatures(features) {
return features;
}
//# sourceMappingURL=codeFeatures.js.map
+11
View File
@@ -0,0 +1,11 @@
import type * as CompilerDOM from '@vue/compiler-dom';
export interface InlayHintInfo {
blockName: string;
offset: number;
setting: string;
label: string;
tooltip?: string;
paddingRight?: boolean;
paddingLeft?: boolean;
}
export declare function createVBindShorthandInlayHintInfo(loc: CompilerDOM.SourceLocation, variableName: string): InlayHintInfo;
+17
View File
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createVBindShorthandInlayHintInfo = createVBindShorthandInlayHintInfo;
function createVBindShorthandInlayHintInfo(loc, variableName) {
return {
blockName: 'template',
offset: loc.end.offset,
setting: 'vue.inlayHints.vBindShorthand',
label: `="${variableName}"`,
tooltip: [
`This is a shorthand for \`${loc.source}="${variableName}"\`.`,
'To hide this hint, set `vue.inlayHints.vBindShorthand` to `false` in IDE settings.',
'[More info](https://github.com/vuejs/core/pull/9451)',
].join('\n\n'),
};
}
//# sourceMappingURL=inlayHints.js.map
+10
View File
@@ -0,0 +1,10 @@
import type { VueCompilerOptions } from '../types';
export declare function getLocalTypesGenerator(vueCompilerOptions: VueCompilerOptions, lang: string): {
generate: () => Generator<string, void, unknown>;
readonly PrettifyLocal: string;
readonly WithDefaults: string;
readonly WithSlots: string;
readonly PropsChildren: string;
readonly TypePropsToOption: string;
readonly OmitIndexSignature: string;
};
+109
View File
@@ -0,0 +1,109 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLocalTypesGenerator = getLocalTypesGenerator;
const utils_1 = require("./utils");
function getLocalTypesGenerator(vueCompilerOptions, lang) {
const used = new Set();
const isTs = (0, utils_1.isTsLang)(lang);
const WithDefaults = defineHelper(`__VLS_WithDefaults`, () => isTs
? `
type __VLS_WithDefaults<P, D> = {
[K in keyof P & string]: K extends keyof D
? ${PrettifyLocal.name}<P[K] & { default: D[K] }>
: P[K]
};
`.trimStart()
: jsTypedef(`P, D`, `__VLS_WithDefaults`, `{ [K in keyof Pick<P, keyof P>]: K extends keyof D ? ${PrettifyLocal.name}<P[K] & { default: D[K] }> : P[K] }`));
const PrettifyLocal = defineHelper(`__VLS_PrettifyLocal`, () => isTs
? `type __VLS_PrettifyLocal<T> = (T extends any ? { [K in keyof T]: T[K]; } : { [K in keyof T as K]: T[K]; }) & {}${utils_1.endOfLine}`
: jsTypedef(`T`, `__VLS_PrettifyLocal`, `(T extends any ? { [K in keyof T]: T[K]; } : { [K in keyof T as K]: T[K]; }) & {}`));
const WithSlots = defineHelper(`__VLS_WithSlots`, () => isTs
? `
type __VLS_WithSlots<T, S> = T & {
new(): {
$slots: S;
}
};
`.trimStart()
: jsTypedef(`T, S`, `__VLS_WithSlots`, `T & { new(): { $slots: S; } }`));
const PropsChildren = defineHelper(`__VLS_PropsChildren`, () => isTs
? `
type __VLS_PropsChildren<S> = {
[K in keyof (
boolean extends (
// @ts-ignore
JSX.ElementChildrenAttribute extends never
? true
: false
)
? never
// @ts-ignore
: JSX.ElementChildrenAttribute
)]?: S;
};
`.trimStart()
// The single-line form lets the preceding @ts-ignore cover the whole typedef,
// mirroring the inline @ts-ignore guards of the TS form.
: `// @ts-ignore${utils_1.newLine}/** @template S @typedef {{ [K in keyof (boolean extends (JSX.ElementChildrenAttribute extends never ? true : false) ? never : JSX.ElementChildrenAttribute)]?: S; }} __VLS_PropsChildren */${utils_1.newLine}`);
const TypePropsToOption = defineHelper(`__VLS_TypePropsToOption`, () => isTs
? `
type __VLS_TypePropsToOption<T> = {
[K in keyof T & string]-?: {} extends Pick<T, K>
? { type: import('${vueCompilerOptions.lib}').PropType<Required<T>[K]> }
: { type: import('${vueCompilerOptions.lib}').PropType<T[K]>, required: true }
};
`.trimStart()
: jsTypedef(`T`, `__VLS_TypePropsToOption`, `{ [K in keyof T]-?: {} extends Pick<T, K> ? { type: import('${vueCompilerOptions.lib}').PropType<Required<T>[K]> } : { type: import('${vueCompilerOptions.lib}').PropType<T[K]>, required: true } }`));
const OmitIndexSignature = defineHelper(`__VLS_OmitIndexSignature`, () => isTs
? `type __VLS_OmitIndexSignature<T> = { [K in keyof T as {} extends Record<K, unknown> ? never : K]: T[K]; }${utils_1.endOfLine}`
: jsTypedef(`T`, `__VLS_OmitIndexSignature`, `{ [K in keyof T as {} extends Record<K, unknown> ? never : K]: T[K] }`));
const helpers = {
[PrettifyLocal.name]: PrettifyLocal,
[WithDefaults.name]: WithDefaults,
[WithSlots.name]: WithSlots,
[PropsChildren.name]: PropsChildren,
[TypePropsToOption.name]: TypePropsToOption,
[OmitIndexSignature.name]: OmitIndexSignature,
};
used.clear();
return {
generate,
get PrettifyLocal() {
return PrettifyLocal.name;
},
get WithDefaults() {
return WithDefaults.name;
},
get WithSlots() {
return WithSlots.name;
},
get PropsChildren() {
return PropsChildren.name;
},
get TypePropsToOption() {
return TypePropsToOption.name;
},
get OmitIndexSignature() {
return OmitIndexSignature.name;
},
};
function* generate() {
for (const name of used) {
yield helpers[name].generate();
}
used.clear();
}
function jsTypedef(params, name, body) {
return `/**${utils_1.newLine} * @template ${params}${utils_1.newLine} * @typedef {${body}} ${name}${utils_1.newLine} */${utils_1.newLine}`;
}
function defineHelper(name, generate) {
return {
get name() {
used.add(name);
return name;
},
generate,
};
}
}
//# sourceMappingURL=localTypes.js.map
+75
View File
@@ -0,0 +1,75 @@
declare const raw: {
base: string;
export: string;
components: string;
componentsOption: string;
ctx: string;
defaultModels: string;
defaults: string;
directives: string;
directivesOption: string;
dollars: string;
emit: string;
exposed: string;
intrinsics: string;
modelEmit: string;
props: string;
propsOption: string;
self: string;
setup: string;
slots: string;
src: string;
Emit: string;
EmitProps: string;
GlobalComponents: string;
InheritedAttrs: string;
LocalComponents: string;
LocalDirectives: string;
ModelEmit: string;
ModelProps: string;
Props: string;
PublicProps: string;
RootEl: string;
Slots: string;
StyleModules: string;
StyleScopedClasses: string;
TemplateRefs: string;
asFunctionalComponent0: string;
asFunctionalComponent1: string;
asFunctionalDirective: string;
asFunctionalElement0: string;
asFunctionalElement1: string;
asFunctionalSlot: string;
directiveBindingRestFields: string;
functionalComponentArgsRest: string;
nonNull: string;
omit: string;
tryAsConstant: string;
unwrap: string;
vFor: string;
vSlot: string;
withDotValue: string;
ConstructorOverloads: string;
Elements: string;
EmitsToProps: string;
ExtractComponentContext: string;
ExtractComponentProps: string;
FunctionalComponent: string;
IsAny: string;
IsFunction: string;
NormalizeEmits: string;
OverloadUnion: string;
OverloadUnionInner: string;
PickNotAny: string;
PrettifyGlobal: string;
ResolveDirectives: string;
ResolveEmits: string;
ResolveEvent: string;
ShortEmits: string;
ShortEmitsToObject: string;
SpreadMerge: string;
UnionToIntersection: string;
WithComponent: string;
};
export declare const names: typeof raw;
export {};
+80
View File
@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.names = void 0;
const raw = {
base: '',
export: '',
components: '',
componentsOption: '',
ctx: '',
defaultModels: '',
defaults: '',
directives: '',
directivesOption: '',
dollars: '',
emit: '',
exposed: '',
intrinsics: '',
modelEmit: '',
props: '',
propsOption: '',
self: '',
setup: '',
slots: '',
src: '',
Emit: '',
EmitProps: '',
GlobalComponents: '',
InheritedAttrs: '',
LocalComponents: '',
LocalDirectives: '',
ModelEmit: '',
ModelProps: '',
Props: '',
PublicProps: '',
RootEl: '',
Slots: '',
StyleModules: '',
StyleScopedClasses: '',
TemplateRefs: '',
// #region template helpers
asFunctionalComponent0: '',
asFunctionalComponent1: '',
asFunctionalDirective: '',
asFunctionalElement0: '',
asFunctionalElement1: '',
asFunctionalSlot: '',
directiveBindingRestFields: '',
functionalComponentArgsRest: '',
nonNull: '',
omit: '',
tryAsConstant: '',
unwrap: '',
vFor: '',
vSlot: '',
withDotValue: '',
ConstructorOverloads: '',
Elements: '',
EmitsToProps: '',
ExtractComponentContext: '',
ExtractComponentProps: '',
FunctionalComponent: '',
IsAny: '',
IsFunction: '',
NormalizeEmits: '',
OverloadUnion: '',
OverloadUnionInner: '',
PickNotAny: '',
PrettifyGlobal: '',
ResolveDirectives: '',
ResolveEmits: '',
ResolveEvent: '',
ShortEmits: '',
ShortEmitsToObject: '',
SpreadMerge: '',
UnionToIntersection: '',
WithComponent: '',
// #endregion
};
exports.names = Object.fromEntries(Object.keys(raw).map(key => [key, `__VLS_${key}`]));
//# sourceMappingURL=names.js.map
+5
View File
@@ -0,0 +1,5 @@
import type { ScriptSetupRanges } from '../../parsers/scriptSetupRanges';
import type { Code, IRScriptSetup } from '../../types';
import type { ScriptCodegenContext } from './context';
import type { ScriptCodegenOptions } from './index';
export declare function generateComponent(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, scriptSetup: IRScriptSetup, scriptSetupRanges: ScriptSetupRanges): Generator<Code>;
+112
View File
@@ -0,0 +1,112 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateComponent = generateComponent;
const codeFeatures_1 = require("../codeFeatures");
const names_1 = require("../names");
const utils_1 = require("../utils");
const merge_1 = require("../utils/merge");
function* generateComponent(options, ctx, scriptSetup, scriptSetupRanges) {
yield `(await import('${options.vueCompilerOptions.lib}')).defineComponent({${utils_1.newLine}`;
if (scriptSetupRanges.defineExpose) {
yield `setup: () => ${names_1.names.exposed},${utils_1.newLine}`;
}
const emitOptionCodes = [...generateEmitsOption(options, scriptSetupRanges)];
yield* emitOptionCodes;
yield* generatePropsOption(options, ctx, scriptSetup, scriptSetupRanges, !!emitOptionCodes.length);
if (options.vueCompilerOptions.target >= 3.5
&& options.vueCompilerOptions.inferComponentDollarRefs
&& options.templateAndStyleTypes.has(names_1.names.TemplateRefs)) {
yield `__typeRefs: ${(0, utils_1.asType)(names_1.names.TemplateRefs, options.scriptLang)},${utils_1.newLine}`;
}
if (options.vueCompilerOptions.target >= 3.5
&& options.vueCompilerOptions.inferComponentDollarEl
&& options.templateAndStyleTypes.has(names_1.names.RootEl)) {
yield `__typeEl: ${(0, utils_1.asType)(names_1.names.RootEl, options.scriptLang)},${utils_1.newLine}`;
}
yield `})`;
}
function* generateEmitsOption(options, scriptSetupRanges) {
const typeCodes = options.vueCompilerOptions.target >= 3.5 && !scriptSetupRanges.defineEmits?.hasUnionTypeArg
? [...generateTypeEmitsOption(scriptSetupRanges)]
: [];
const runtimeCodes = !typeCodes.length
? [...generateRuntimeEmitsOption(options, scriptSetupRanges)]
: [];
if (typeCodes.length) {
yield `__typeEmits: ${(0, utils_1.asType)(typeCodes.join(` & `), options.scriptLang)},${utils_1.newLine}`;
}
else if (runtimeCodes.length) {
yield `emits: `;
yield* (0, merge_1.generateSpreadMerge)(...runtimeCodes);
yield `,${utils_1.newLine}`;
}
}
function* generateTypeEmitsOption(scriptSetupRanges) {
if (scriptSetupRanges.defineModel.length) {
yield names_1.names.ModelEmit;
}
if (scriptSetupRanges.defineEmits?.typeArg) {
yield names_1.names.Emit;
}
}
function* generateRuntimeEmitsOption(options, scriptSetupRanges) {
if (scriptSetupRanges.defineModel.length) {
yield (0, utils_1.asType)(`${names_1.names.NormalizeEmits}<typeof ${names_1.names.modelEmit}>`, options.scriptLang);
}
if (scriptSetupRanges.defineEmits) {
yield (0, utils_1.asType)(`${names_1.names.NormalizeEmits}<typeof ${scriptSetupRanges.defineEmits.name ?? names_1.names.emit}>`, options.scriptLang);
}
}
function* generatePropsOption(options, ctx, scriptSetup, scriptSetupRanges, hasEmitsOption) {
const typeCodes = options.vueCompilerOptions.target >= 3.5 && !scriptSetupRanges.defineProps?.arg
? [...generateTypePropsOption(options, ctx, hasEmitsOption)]
: [];
const runtimeCodes = scriptSetupRanges.withDefaults || !typeCodes.length
? [...generateRuntimePropsOption(options, ctx, scriptSetup, scriptSetupRanges, hasEmitsOption)]
: [];
if (typeCodes.length) {
if (options.vueCompilerOptions.target >= 3.6 && scriptSetupRanges.withDefaults?.arg) {
yield `__defaults: ${names_1.names.defaults},${utils_1.newLine}`;
}
yield `__typeProps: `;
yield* (0, merge_1.generateSpreadMerge)(...typeCodes);
yield `,${utils_1.newLine}`;
}
if (runtimeCodes.length) {
yield `props: `;
yield* (0, merge_1.generateSpreadMerge)(...runtimeCodes);
yield `,${utils_1.newLine}`;
}
}
function* generateTypePropsOption(options, ctx, hasEmitsOption) {
if (options.templateAndStyleTypes.has(names_1.names.InheritedAttrs)) {
const attrsType = hasEmitsOption
? `Omit<${names_1.names.InheritedAttrs}, keyof ${names_1.names.EmitProps}>`
: names_1.names.InheritedAttrs;
yield (0, utils_1.asType)(attrsType, options.scriptLang);
}
if (ctx.generatedTypes.has(names_1.names.PublicProps)) {
yield (0, utils_1.asType)(names_1.names.PublicProps, options.scriptLang);
}
}
function* generateRuntimePropsOption(options, ctx, scriptSetup, scriptSetupRanges, hasEmitsOption) {
if (options.templateAndStyleTypes.has(names_1.names.InheritedAttrs)) {
const attrsType = hasEmitsOption
? `Omit<${names_1.names.InheritedAttrs}, keyof ${names_1.names.EmitProps}>`
: names_1.names.InheritedAttrs;
const propsType = `${ctx.localTypes.TypePropsToOption}<${names_1.names.PickNotAny}<${ctx.localTypes.OmitIndexSignature}<${attrsType}>, {}>>`;
yield (0, utils_1.asType)(propsType, options.scriptLang);
}
if (ctx.generatedTypes.has(names_1.names.PublicProps) && options.vueCompilerOptions.target < 3.6) {
let propsType = `${ctx.localTypes.TypePropsToOption}<${names_1.names.PublicProps}>`;
if (scriptSetupRanges.withDefaults?.arg) {
propsType = `${ctx.localTypes.WithDefaults}<${propsType}, typeof ${names_1.names.defaults}>`;
}
yield (0, utils_1.asType)(propsType, options.scriptLang);
}
if (scriptSetupRanges.defineProps?.arg) {
const { arg } = scriptSetupRanges.defineProps;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.navigation);
}
}
//# sourceMappingURL=component.js.map
+16
View File
@@ -0,0 +1,16 @@
import type { InlayHintInfo } from '../inlayHints';
import type { ScriptCodegenOptions } from './index';
export type ScriptCodegenContext = ReturnType<typeof createScriptCodegenContext>;
export declare function createScriptCodegenContext(options: ScriptCodegenOptions): {
generatedTypes: Set<string>;
localTypes: {
generate: () => Generator<string, void, unknown>;
readonly PrettifyLocal: string;
readonly WithDefaults: string;
readonly WithSlots: string;
readonly PropsChildren: string;
readonly TypePropsToOption: string;
readonly OmitIndexSignature: string;
};
inlayHints: InlayHintInfo[];
};
+14
View File
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createScriptCodegenContext = createScriptCodegenContext;
const localTypes_1 = require("../localTypes");
function createScriptCodegenContext(options) {
const localTypes = (0, localTypes_1.getLocalTypesGenerator)(options.vueCompilerOptions, options.scriptLang);
const inlayHints = [];
return {
generatedTypes: new Set(),
localTypes,
inlayHints,
};
}
//# sourceMappingURL=context.js.map
+33
View File
@@ -0,0 +1,33 @@
import type { ScriptRanges } from '../../parsers/scriptRanges';
import type { ScriptSetupRanges } from '../../parsers/scriptSetupRanges';
import type { Code, IRScript, IRScriptSetup, VueCompilerOptions } from '../../types';
export interface ScriptCodegenOptions {
vueCompilerOptions: VueCompilerOptions;
script: IRScript | undefined;
scriptSetup: IRScriptSetup | undefined;
fileName: string;
scriptLang: string;
scriptRanges: ScriptRanges | undefined;
scriptSetupRanges: ScriptSetupRanges | undefined;
templateAndStyleTypes: Set<string>;
templateAndStyleCodes: Code[];
setupBindings: Set<string>;
localComponents: Set<string>;
localDirectives: Set<string>;
dotValueBindings: Set<string>;
}
export { generate as generateScript };
declare function generate(options: ScriptCodegenOptions): {
generatedTypes: Set<string>;
localTypes: {
generate: () => Generator<string, void, unknown>;
readonly PrettifyLocal: string;
readonly WithDefaults: string;
readonly WithSlots: string;
readonly PropsChildren: string;
readonly TypePropsToOption: string;
readonly OmitIndexSignature: string;
};
inlayHints: import("../inlayHints").InlayHintInfo[];
codes: Code[];
};
+207
View File
@@ -0,0 +1,207 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateScript = generate;
const path = __importStar(require("path-browserify"));
const codeFeatures_1 = require("../codeFeatures");
const names_1 = require("../names");
const utils_1 = require("../utils");
const boundary_1 = require("../utils/boundary");
const context_1 = require("./context");
const scriptSetup_1 = require("./scriptSetup");
const template_1 = require("./template");
function generate(options) {
const ctx = (0, context_1.createScriptCodegenContext)(options);
const codeGenerator = generateWorker(options, ctx);
return { ...ctx, codes: [...codeGenerator] };
}
function* generateWorker(options, ctx) {
const { script, scriptRanges, scriptSetup, scriptSetupRanges, vueCompilerOptions, fileName } = options;
const exportExpression = (0, utils_1.asType)(`typeof ${names_1.names.export}`, options.scriptLang);
yield* generateGlobalTypesReference(vueCompilerOptions, fileName);
// <script src="">
if (typeof script?.src === 'object') {
let src = script.src.text;
if (src.endsWith('.ts') && !src.endsWith('.d.ts')) {
src = src.slice(0, -'.ts'.length) + '.js';
}
else if (src.endsWith('.tsx')) {
src = src.slice(0, -'.tsx'.length) + '.jsx';
}
yield `import ${names_1.names.src} from `;
const boundary = yield* boundary_1.Boundary.start('main', script.src.offset, script.src.offset + script.src.text.length, {
...codeFeatures_1.codeFeatures.all,
...src !== script.src.text ? codeFeatures_1.codeFeatures.navigationWithoutRename : {},
});
yield `'`;
yield [src.slice(0, script.src.text.length), 'main', script.src.offset, boundary.features];
yield src.slice(script.src.text.length);
yield `'`;
yield boundary.end();
yield utils_1.endOfLine;
yield `export default ${names_1.names.src}${utils_1.endOfLine}`;
yield* (0, template_1.generateTemplate)(options, names_1.names.src);
}
// <script> + <script setup>
else if (script && scriptRanges && scriptSetup && scriptSetupRanges) {
yield* (0, scriptSetup_1.generateScriptSetupImports)(scriptSetup, scriptSetupRanges);
// <script>
let selfType;
const { exportDefault } = scriptRanges;
if (exportDefault) {
yield* generateScriptWithExportDefault(ctx, script, scriptRanges, exportDefault, vueCompilerOptions, selfType = names_1.names.self, exportExpression);
}
else {
yield* (0, utils_1.generateSfcBlockSection)(script, 0, script.content.length, codeFeatures_1.codeFeatures.all);
yield `export default ${exportExpression}${utils_1.endOfLine}`;
}
// <script setup>
yield* generateExportDeclareEqual(scriptSetup, names_1.names.export);
if (scriptSetup.generic) {
yield* (0, scriptSetup_1.generateGeneric)(options, ctx, scriptSetup, scriptSetupRanges, scriptSetup.generic, (0, scriptSetup_1.generateSetupFunction)(options, ctx, scriptSetup, scriptSetupRanges, (0, template_1.generateTemplate)(options, selfType)));
}
else {
yield `await (async () => {${utils_1.newLine}`;
yield* (0, scriptSetup_1.generateSetupFunction)(options, ctx, scriptSetup, scriptSetupRanges, (0, template_1.generateTemplate)(options, selfType), [`return `]);
yield `})()${utils_1.endOfLine}`;
}
}
// only <script setup>
else if (scriptSetup && scriptSetupRanges) {
yield* (0, scriptSetup_1.generateScriptSetupImports)(scriptSetup, scriptSetupRanges);
if (scriptSetup.generic) {
yield* generateExportDeclareEqual(scriptSetup, names_1.names.export);
yield* (0, scriptSetup_1.generateGeneric)(options, ctx, scriptSetup, scriptSetupRanges, scriptSetup.generic, (0, scriptSetup_1.generateSetupFunction)(options, ctx, scriptSetup, scriptSetupRanges, (0, template_1.generateTemplate)(options)));
}
else {
// no script block, generate script setup code at root
yield* (0, scriptSetup_1.generateSetupFunction)(options, ctx, scriptSetup, scriptSetupRanges, (0, template_1.generateTemplate)(options), generateExportDeclareEqual(scriptSetup, names_1.names.export));
}
yield `export default ${exportExpression}${utils_1.endOfLine}`;
}
// only <script>
else if (script && scriptRanges) {
const { exportDefault } = scriptRanges;
if (exportDefault) {
yield* generateScriptWithExportDefault(ctx, script, scriptRanges, exportDefault, vueCompilerOptions, names_1.names.export, exportExpression, (0, template_1.generateTemplate)(options, names_1.names.export));
}
else {
yield* (0, utils_1.generateSfcBlockSection)(script, 0, script.content.length, codeFeatures_1.codeFeatures.all);
yield* generateExportDeclareEqual(script, names_1.names.export);
yield `(await import('${vueCompilerOptions.lib}')).defineComponent({})${utils_1.endOfLine}`;
yield* (0, template_1.generateTemplate)(options, names_1.names.export);
yield `export default ${exportExpression}${utils_1.endOfLine}`;
}
}
yield* ctx.localTypes.generate();
// The <script src> branch never embeds the script setup content, so no
// macro references can appear and the import would be unused.
if (scriptSetup && scriptSetupRanges && typeof script?.src !== 'object') {
yield* (0, scriptSetup_1.generateMacros)(options);
}
}
function* generateScriptWithExportDefault(ctx, script, scriptRanges, exportDefault, vueCompilerOptions, varName, exportExpression, templateGenerator) {
const componentOptions = scriptRanges.exportDefault?.options;
const { expression, isObjectLiteral } = componentOptions ?? exportDefault;
let wrapLeft;
let wrapRight;
if (isObjectLiteral
&& vueCompilerOptions.optionsWrapper.length) {
[wrapLeft, wrapRight] = vueCompilerOptions.optionsWrapper;
ctx.inlayHints.push({
blockName: script.name,
offset: expression.start,
setting: 'vue.inlayHints.optionsWrapper',
label: wrapLeft || '[Missing optionsWrapper[0]]',
tooltip: [
'This is virtual code that is automatically wrapped for type support, it does not affect your runtime behavior, you can customize it via `vueCompilerOptions.optionsWrapper` option in tsconfig / jsconfig.',
'To hide it, you can set `"vue.inlayHints.optionsWrapper": false` in IDE settings.',
].join('\n\n'),
}, {
blockName: script.name,
offset: expression.end,
setting: 'vue.inlayHints.optionsWrapper',
label: wrapRight || '[Missing optionsWrapper[1]]',
});
}
yield* (0, utils_1.generateSfcBlockSection)(script, 0, expression.start, codeFeatures_1.codeFeatures.all);
yield exportExpression;
yield* (0, utils_1.generateSfcBlockSection)(script, expression.end, exportDefault.end, codeFeatures_1.codeFeatures.all);
yield utils_1.endOfLine;
if (templateGenerator) {
yield* templateGenerator;
}
yield* generateExportDeclareEqual(script, varName);
if (wrapLeft && wrapRight) {
yield wrapLeft;
yield* (0, utils_1.generateSfcBlockSection)(script, expression.start, expression.end, codeFeatures_1.codeFeatures.all);
yield wrapRight;
}
else {
yield* (0, utils_1.generateSfcBlockSection)(script, expression.start, expression.end, codeFeatures_1.codeFeatures.all);
}
yield utils_1.endOfLine;
yield* (0, utils_1.generateSfcBlockSection)(script, exportDefault.end, script.content.length, codeFeatures_1.codeFeatures.all);
}
function* generateGlobalTypesReference({ typesRoot, lib, target, checkUnknownProps }, fileName) {
let typesPath;
if (path.isAbsolute(typesRoot)) {
let relativePath = path.relative(path.dirname(fileName), typesRoot);
if (relativePath !== typesRoot
&& !relativePath.startsWith('./')
&& !relativePath.startsWith('../')) {
relativePath = './' + relativePath;
}
typesPath = relativePath;
}
else {
typesPath = typesRoot;
}
yield `/// <reference types=${JSON.stringify(typesPath + '/template-helpers.d.ts')} />${utils_1.newLine}`;
if (!checkUnknownProps) {
yield `/// <reference types=${JSON.stringify(typesPath + '/props-fallback.d.ts')} />${utils_1.newLine}`;
}
if (lib === 'vue' && target < 3.5) {
yield `/// <reference types=${JSON.stringify(typesPath + '/vue-3.4-shims.d.ts')} />${utils_1.newLine}`;
}
}
function* generateExportDeclareEqual(block, name) {
yield `const `;
const boundary = yield* boundary_1.Boundary.start(block.name, 0, block.content.length, codeFeatures_1.codeFeatures.doNotReportTs6133);
yield name;
yield boundary.end();
yield ` = `;
}
//# sourceMappingURL=index.js.map
+8
View File
@@ -0,0 +1,8 @@
import type { ScriptSetupRanges } from '../../parsers/scriptSetupRanges';
import type { Code, IRScriptSetup } from '../../types';
import type { ScriptCodegenContext } from './context';
import type { ScriptCodegenOptions } from './index';
export declare function generateScriptSetupImports(scriptSetup: IRScriptSetup, scriptSetupRanges: ScriptSetupRanges): Generator<Code>;
export declare function generateGeneric(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, scriptSetup: IRScriptSetup, scriptSetupRanges: ScriptSetupRanges, generic: NonNullable<IRScriptSetup['generic']>, body: Iterable<Code>): Generator<Code>;
export declare function generateSetupFunction(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, scriptSetup: IRScriptSetup, scriptSetupRanges: ScriptSetupRanges, body: Iterable<Code>, output?: Iterable<Code>): Generator<Code>;
export declare function generateMacros(options: ScriptCodegenOptions): Generator<Code>;
+498
View File
@@ -0,0 +1,498 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateScriptSetupImports = generateScriptSetupImports;
exports.generateGeneric = generateGeneric;
exports.generateSetupFunction = generateSetupFunction;
exports.generateMacros = generateMacros;
const shared_1 = require("@vue/shared");
const codeFeatures_1 = require("../codeFeatures");
const names_1 = require("../names");
const utils_1 = require("../utils");
const boundary_1 = require("../utils/boundary");
const camelized_1 = require("../utils/camelized");
const transform_1 = require("../utils/transform");
const component_1 = require("./component");
function* generateScriptSetupImports(scriptSetup, scriptSetupRanges) {
yield [
scriptSetup.content.slice(0, Math.max(scriptSetupRanges.importSectionEndOffset, scriptSetupRanges.leadingCommentEndOffset)),
'scriptSetup',
0,
codeFeatures_1.codeFeatures.all,
];
}
function* generateGeneric(options, ctx, scriptSetup, scriptSetupRanges, generic, body) {
yield `(`;
if (typeof generic === 'object') {
const boundary = yield* boundary_1.Boundary.start('main', generic.offset, generic.offset + generic.text.length, codeFeatures_1.codeFeatures.verification);
yield `<`;
yield [generic.text, 'main', generic.offset, codeFeatures_1.codeFeatures.all];
if (!generic.text.trimEnd().endsWith(`,`)) {
yield `,`;
}
yield `>`;
yield boundary.end();
}
yield `(${utils_1.newLine}`
+ ` ${names_1.names.props}: NonNullable<Awaited<typeof ${names_1.names.setup}>>['props'],${utils_1.newLine}`
+ ` ${names_1.names.ctx}?: ${ctx.localTypes.PrettifyLocal}<Pick<NonNullable<Awaited<typeof ${names_1.names.setup}>>, 'attrs' | 'emit' | 'slots'>>,${utils_1.newLine}`
+ ` ${names_1.names.exposed}?: NonNullable<Awaited<typeof ${names_1.names.setup}>>['expose'],${utils_1.newLine}`
+ ` ${names_1.names.setup} = (async () => {${utils_1.newLine}`;
yield* body;
const propTypes = [];
const emitTypes = [];
const { vueCompilerOptions } = options;
if (ctx.generatedTypes.has(names_1.names.PublicProps)) {
propTypes.push(names_1.names.PublicProps);
}
if (scriptSetupRanges.defineProps?.arg) {
yield `const ${names_1.names.propsOption} = `;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, scriptSetupRanges.defineProps.arg.start, scriptSetupRanges.defineProps.arg.end, codeFeatures_1.codeFeatures.navigation);
yield utils_1.endOfLine;
propTypes.push(`import('${vueCompilerOptions.lib}').${vueCompilerOptions.target >= 3.3 ? `ExtractPublicPropTypes` : `ExtractPropTypes`}<typeof ${names_1.names.propsOption}>`);
}
if (scriptSetupRanges.defineEmits || scriptSetupRanges.defineModel.length) {
propTypes.push(names_1.names.EmitProps);
}
if (options.templateAndStyleTypes.has(names_1.names.InheritedAttrs)) {
propTypes.push(names_1.names.InheritedAttrs);
}
if (scriptSetupRanges.defineEmits) {
emitTypes.push(`typeof ${scriptSetupRanges.defineEmits.name ?? names_1.names.emit}`);
}
if (scriptSetupRanges.defineModel.length) {
emitTypes.push(`typeof ${names_1.names.modelEmit}`);
}
yield `return {} as {${utils_1.newLine}`;
yield ` props: `;
yield vueCompilerOptions.target >= 3.4
? `import('${vueCompilerOptions.lib}').PublicProps`
: vueCompilerOptions.target >= 3
? `import('${vueCompilerOptions.lib}').VNodeProps`
+ ` & import('${vueCompilerOptions.lib}').AllowedComponentProps`
+ ` & import('${vueCompilerOptions.lib}').ComponentCustomProps`
: `globalThis.JSX.IntrinsicAttributes`;
if (propTypes.length) {
yield ` & ${ctx.localTypes.PrettifyLocal}<${propTypes.join(` & `)}>`;
}
yield ` & (typeof globalThis extends { __VLS_PROPS_FALLBACK: infer P } ? P : {})${utils_1.endOfLine}`;
yield ` expose: (exposed: `;
yield scriptSetupRanges.defineExpose
? `import('${vueCompilerOptions.lib}').ShallowUnwrapRef<typeof ${names_1.names.exposed}>`
: `{}`;
if (options.vueCompilerOptions.inferComponentDollarRefs
&& options.templateAndStyleTypes.has(names_1.names.TemplateRefs)) {
yield ` & { $refs: ${names_1.names.TemplateRefs}; }`;
}
if (options.vueCompilerOptions.inferComponentDollarEl
&& options.templateAndStyleTypes.has(names_1.names.RootEl)) {
yield ` & { $el: ${names_1.names.RootEl}; }`;
}
yield `) => void${utils_1.endOfLine}`;
yield ` attrs: any${utils_1.endOfLine}`;
yield ` slots: ${hasSlotsType(options) ? names_1.names.Slots : `{}`}${utils_1.endOfLine}`;
yield ` emit: ${emitTypes.length ? emitTypes.join(` & `) : `{}`}${utils_1.endOfLine}`;
yield `}${utils_1.endOfLine}`;
yield `})(),${utils_1.newLine}`; // __VLS_setup = (async () => {
yield `) => ({} as import('${vueCompilerOptions.lib}').VNode & { __ctx?: NonNullable<Awaited<typeof ${names_1.names.setup}>> }))${utils_1.endOfLine}`;
}
function* generateSetupFunction(options, ctx, scriptSetup, scriptSetupRanges, body, output) {
const transforms = [];
for (const { defaultPropsArg } of scriptSetupRanges.defineModel) {
if (defaultPropsArg) {
transforms.push({
range: [defaultPropsArg.end, defaultPropsArg.end],
*generate() {
yield `: `;
if (scriptSetupRanges.defineProps?.typeArg) {
yield names_1.names.Props;
}
else {
// FIXME: (props: typeof props) => ... would cause TS2502
yield `typeof `;
yield scriptSetupRanges.defineProps?.name ?? names_1.names.props;
}
},
});
}
}
if (scriptSetupRanges.defineProps) {
const { name, statement, callExp, typeArg } = scriptSetupRanges.defineProps;
const _callExp = scriptSetupRanges.withDefaults?.callExp ?? callExp;
transforms.push(...generateDefineWithTypeTransforms(scriptSetup, statement, _callExp, typeArg, name, names_1.names.props, names_1.names.Props));
}
if (scriptSetupRanges.defineEmits) {
const { name, statement, callExp, typeArg } = scriptSetupRanges.defineEmits;
transforms.push(...generateDefineWithTypeTransforms(scriptSetup, statement, callExp, typeArg, name, names_1.names.emit, names_1.names.Emit));
}
if (scriptSetupRanges.defineSlots) {
const { name, statement, callExp, typeArg } = scriptSetupRanges.defineSlots;
transforms.push(...generateDefineWithTypeTransforms(scriptSetup, statement, callExp, typeArg, name, names_1.names.slots, names_1.names.Slots));
if (!name) {
transforms.push((0, transform_1.insert)(statement.end, function* () {
yield `${utils_1.newLine}void ${names_1.names.slots}${utils_1.endOfLine}`;
}));
}
}
if (scriptSetupRanges.defineExpose) {
const { callExp, arg, typeArg } = scriptSetupRanges.defineExpose;
if (typeArg) {
transforms.push((0, transform_1.insert)(callExp.start, function* () {
yield `let ${names_1.names.exposed}!: `;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, typeArg.start, typeArg.end, codeFeatures_1.codeFeatures.all);
yield utils_1.endOfLine;
}), (0, transform_1.replace)(typeArg.start, typeArg.end, function* () {
yield `typeof ${names_1.names.exposed}`;
}));
}
else if (arg) {
transforms.push((0, transform_1.insert)(callExp.start, function* () {
yield `const ${names_1.names.exposed} = `;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.all);
yield utils_1.endOfLine;
}), (0, transform_1.replace)(arg.start, arg.end, function* () {
yield names_1.names.exposed;
}));
}
else {
transforms.push((0, transform_1.insert)(callExp.start, function* () {
yield `const ${names_1.names.exposed} = {}${utils_1.endOfLine}`;
}));
}
}
if (options.vueCompilerOptions.inferTemplateDollarAttrs) {
for (const { callExp } of scriptSetupRanges.useAttrs) {
const type = `typeof ${names_1.names.dollars}.$attrs`;
transforms.push((0, transform_1.insert)(callExp.start, function* () {
yield (0, utils_1.isTsLang)(options.scriptLang) ? `(` : `/** @type {${type}} */ (`;
}), (0, transform_1.insert)(callExp.end, function* () {
yield (0, utils_1.isTsLang)(options.scriptLang) ? ` as ${type})` : `)`;
}));
}
}
for (const { callExp, exp, arg } of scriptSetupRanges.useCssModule) {
const type = options.templateAndStyleTypes.has(names_1.names.StyleModules)
? names_1.names.StyleModules
: `{}`;
if (arg) {
transforms.push((0, transform_1.insert)(callExp.start, function* () {
if ((0, utils_1.isTsLang)(options.scriptLang)) {
yield `(`;
}
else {
yield `/** @type {Omit<${type}, '$style'>[`;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.withoutSemantic);
yield `]} */ (`;
}
}), (0, transform_1.insert)(callExp.end, function* () {
if ((0, utils_1.isTsLang)(options.scriptLang)) {
yield ` as Omit<${type}, '$style'>[`;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.withoutSemantic);
yield `])`;
}
else {
yield `)`;
}
}), (0, transform_1.replace)(arg.start, arg.end, function* () {
yield (0, utils_1.asType)('any', options.scriptLang);
}));
}
else {
transforms.push((0, transform_1.insert)(callExp.start, function* () {
yield (0, utils_1.isTsLang)(options.scriptLang) ? `(` : `/** @type {${type}['$style']} */ (`;
}), (0, transform_1.insert)(callExp.end, function* () {
if ((0, utils_1.isTsLang)(options.scriptLang)) {
yield ` as ${type}[`;
const boundary = yield* boundary_1.Boundary.start(scriptSetup.name, exp.start, exp.end, codeFeatures_1.codeFeatures.verification);
yield `'$style'`;
yield boundary.end();
yield `])`;
}
else {
yield `)`;
}
}));
}
}
if (options.vueCompilerOptions.inferTemplateDollarSlots) {
for (const { callExp } of scriptSetupRanges.useSlots) {
const type = `typeof ${names_1.names.dollars}.$slots`;
transforms.push((0, transform_1.insert)(callExp.start, function* () {
yield (0, utils_1.isTsLang)(options.scriptLang) ? `(` : `/** @type {${type}} */ (`;
}), (0, transform_1.insert)(callExp.end, function* () {
yield (0, utils_1.isTsLang)(options.scriptLang) ? ` as ${type})` : `)`;
}));
}
}
for (const { callExp, arg } of scriptSetupRanges.useTemplateRef) {
transforms.push((0, transform_1.insert)(callExp.start, function* () {
if ((0, utils_1.isTsLang)(options.scriptLang)) {
yield `(`;
return;
}
yield `/** @type {Readonly<import('${options.vueCompilerOptions.lib}').ShallowRef<`;
if (arg) {
yield names_1.names.TemplateRefs;
yield `[`;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.withoutSemantic);
yield `]`;
}
else {
yield `unknown`;
}
yield ` | null>>} */ (`;
}), (0, transform_1.insert)(callExp.end, function* () {
if ((0, utils_1.isTsLang)(options.scriptLang)) {
yield ` as Readonly<import('${options.vueCompilerOptions.lib}').ShallowRef<`;
if (arg) {
yield names_1.names.TemplateRefs;
yield `[`;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.withoutSemantic);
yield `]`;
}
else {
yield `unknown`;
}
yield ` | null>>)`;
}
else {
yield `)`;
}
}));
if (arg) {
transforms.push((0, transform_1.replace)(arg.start, arg.end, function* () {
yield (0, utils_1.asType)('any', options.scriptLang);
}));
}
}
yield* (0, transform_1.generateCodeWithTransforms)(Math.max(scriptSetupRanges.importSectionEndOffset, scriptSetupRanges.leadingCommentEndOffset), scriptSetup.content.length, transforms, (start, end) => (0, utils_1.generateSfcBlockSection)(scriptSetup, start, end, codeFeatures_1.codeFeatures.all));
yield* generateModels(options, scriptSetup, scriptSetupRanges);
yield* generatePublicProps(options, ctx, scriptSetup, scriptSetupRanges);
yield* body;
if (output) {
if (hasSlotsType(options)) {
yield `const ${names_1.names.base} = `;
yield* (0, component_1.generateComponent)(options, ctx, scriptSetup, scriptSetupRanges);
yield utils_1.endOfLine;
yield* output;
yield (0, utils_1.asType)(`${ctx.localTypes.WithSlots}<typeof ${names_1.names.base}, ${names_1.names.Slots}>`, options.scriptLang);
yield utils_1.endOfLine;
}
else {
yield* output;
yield* (0, component_1.generateComponent)(options, ctx, scriptSetup, scriptSetupRanges);
yield utils_1.endOfLine;
}
}
}
// An `import` (rather than `declare const`) keeps the macros resolvable in JS
// virtual files, where type-only declarations are syntax errors. Imports hoist,
// so this can be emitted after all user content: leading directives stay ahead
// of any statement, and the import-section/content junction stays intact.
function* generateMacros(options) {
if (options.vueCompilerOptions.target >= 3.3) {
const scriptSetup = options.scriptSetup;
const scriptSetupRanges = options.scriptSetupRanges;
if (!scriptSetup || !scriptSetupRanges) {
return;
}
const usedMacros = [];
const add = (canonical, exp) => {
if (exp) {
usedMacros.push({ canonical, alias: getRangeText(scriptSetup, exp) });
}
};
add('defineProps', scriptSetupRanges.defineProps?.exp);
add('defineEmits', scriptSetupRanges.defineEmits?.exp);
add('defineSlots', scriptSetupRanges.defineSlots?.exp);
add('defineExpose', scriptSetupRanges.defineExpose?.exp);
add('withDefaults', scriptSetupRanges.withDefaults?.exp);
if (scriptSetupRanges.defineModel.length) {
usedMacros.push({ canonical: 'defineModel', alias: 'defineModel' });
}
if (scriptSetupRanges.defineOptions) {
usedMacros.push({ canonical: 'defineOptions', alias: 'defineOptions' });
}
const toImport = usedMacros.filter(({ alias }) => !options.setupBindings.has(alias));
if (toImport.length) {
yield `import { `;
for (const { canonical, alias } of toImport) {
yield alias === canonical ? `${canonical}, ` : `${canonical} as ${alias}, `;
}
yield `} from '${options.vueCompilerOptions.lib}'${utils_1.endOfLine}`;
}
}
}
function* generateDefineWithTypeTransforms(scriptSetup, statement, callExp, typeArg, name, defaultName, typeName) {
if (typeArg) {
yield (0, transform_1.insert)(statement.start, function* () {
yield `type ${typeName} = `;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, typeArg.start, typeArg.end, codeFeatures_1.codeFeatures.all);
yield utils_1.endOfLine;
});
yield (0, transform_1.replace)(typeArg.start, typeArg.end, function* () {
yield typeName;
});
}
if (!name) {
if (statement.start === callExp.start && statement.end === callExp.end) {
yield (0, transform_1.insert)(callExp.start, function* () {
yield `const ${defaultName} = `;
});
}
else if (typeArg) {
yield (0, transform_1.replace)(statement.start, typeArg.start, function* () {
yield `const ${defaultName} = `;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, callExp.start, typeArg.start, codeFeatures_1.codeFeatures.all);
});
yield (0, transform_1.replace)(typeArg.end, callExp.end, function* () {
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, typeArg.end, callExp.end, codeFeatures_1.codeFeatures.all);
yield utils_1.endOfLine;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, statement.start, callExp.start, codeFeatures_1.codeFeatures.all);
yield defaultName;
});
}
else {
yield (0, transform_1.replace)(statement.start, callExp.end, function* () {
yield `const ${defaultName} = `;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, callExp.start, callExp.end, codeFeatures_1.codeFeatures.all);
yield utils_1.endOfLine;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, statement.start, callExp.start, codeFeatures_1.codeFeatures.all);
yield defaultName;
});
}
}
else if (!utils_1.identifierRE.test(name)) {
yield (0, transform_1.replace)(statement.start, callExp.start, function* () {
yield `const ${defaultName} = `;
});
yield (0, transform_1.insert)(statement.end, function* () {
yield utils_1.endOfLine;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, statement.start, callExp.start, codeFeatures_1.codeFeatures.all);
yield defaultName;
});
}
}
function* generatePublicProps(options, ctx, scriptSetup, scriptSetupRanges) {
if (scriptSetupRanges.defineProps?.typeArg && scriptSetupRanges.withDefaults?.arg) {
yield `const ${names_1.names.defaults} = `;
yield* (0, utils_1.generateSfcBlockSection)(scriptSetup, scriptSetupRanges.withDefaults.arg.start, scriptSetupRanges.withDefaults.arg.end, codeFeatures_1.codeFeatures.navigation);
yield utils_1.endOfLine;
yield `void ${names_1.names.defaults}${utils_1.endOfLine}`;
}
const propTypes = [];
if (options.vueCompilerOptions.jsxSlots && hasSlotsType(options)) {
propTypes.push(`${ctx.localTypes.PropsChildren}<${names_1.names.Slots}>`);
}
if (scriptSetupRanges.defineProps?.typeArg) {
propTypes.push(names_1.names.Props);
}
if (scriptSetupRanges.defineModel.length) {
propTypes.push(names_1.names.ModelProps);
}
const target = options.vueCompilerOptions.target;
const used = !!scriptSetup.generic
|| target < 3.6
|| (target >= 3.5 && !scriptSetupRanges.defineProps?.arg);
if (propTypes.length && used) {
yield* (0, utils_1.generateTypeAlias)(names_1.names.PublicProps, options.scriptLang, function* () {
yield propTypes.join(` & `);
});
ctx.generatedTypes.add(names_1.names.PublicProps);
}
}
function hasSlotsType(options) {
return !!(options.scriptSetupRanges?.defineSlots
|| options.templateAndStyleTypes.has(names_1.names.Slots));
}
function* generateModels(options, scriptSetup, scriptSetupRanges) {
if (!scriptSetupRanges.defineModel.length) {
return;
}
const defaultCodes = [];
const propCodes = [];
const emitCodes = [];
for (const defineModel of scriptSetupRanges.defineModel) {
const propName = defineModel.name
? (0, shared_1.camelize)(getRangeText(scriptSetup, defineModel.name).slice(1, -1))
: 'modelValue';
let modelType;
if (defineModel.type) {
// Infer from defineModel<T>
modelType = getRangeText(scriptSetup, defineModel.type);
}
else if (defineModel.runtimeType && defineModel.localName) {
// Infer from actual prop declaration code
modelType = `typeof ${getRangeText(scriptSetup, defineModel.localName)}['value']`;
}
else if (defineModel.defaultValue && propName) {
// Infer from defineModel({ default: T })
modelType = `typeof ${names_1.names.defaultModels}['${propName}']`;
}
else {
modelType = `any`;
}
if (defineModel.defaultValue) {
defaultCodes.push(`'${propName}': ${getRangeText(scriptSetup, defineModel.defaultValue)},${utils_1.newLine}`);
}
propCodes.push(generateModelProp(options, scriptSetup, defineModel, propName, modelType));
emitCodes.push(generateModelEmit(defineModel, propName, modelType));
}
if (defaultCodes.length) {
yield `const ${names_1.names.defaultModels} = {${utils_1.newLine}`;
yield* defaultCodes;
yield `}${utils_1.endOfLine}`;
yield `void ${names_1.names.defaultModels}${utils_1.endOfLine}`;
}
yield* (0, utils_1.generateTypeAlias)(names_1.names.ModelProps, options.scriptLang, function* () {
yield `{${utils_1.newLine}`;
for (const codes of propCodes) {
yield* codes;
}
yield `}`;
});
yield* (0, utils_1.generateTypeAlias)(names_1.names.ModelEmit, options.scriptLang, function* () {
yield `{${utils_1.newLine}`;
for (const codes of emitCodes) {
yield* codes;
}
yield `}`;
});
// avoid `defineModel<...>()` to prevent JS AST issues
yield* (0, utils_1.generateTypedVar)('let', names_1.names.modelEmit, options.scriptLang, function* () {
yield `${names_1.names.ShortEmits}<${names_1.names.ModelEmit}>`;
});
}
function* generateModelProp(options, scriptSetup, defineModel, propName, modelType) {
// In JS the alias body lives inside a JSDoc comment; user comments could
// contain `*/` and terminate it early, so they are dropped.
if (defineModel.comments && (0, utils_1.isTsLang)(options.scriptLang)) {
yield scriptSetup.content.slice(defineModel.comments.start, defineModel.comments.end);
yield utils_1.newLine;
}
if (defineModel.name) {
yield* (0, camelized_1.generateCamelized)(getRangeText(scriptSetup, defineModel.name), scriptSetup.name, defineModel.name.start, codeFeatures_1.codeFeatures.navigation);
}
else {
yield propName;
}
yield defineModel.required ? `: ` : `?: `;
yield modelType;
yield utils_1.endOfLine;
if (defineModel.modifierType) {
const modifierName = `${propName === 'modelValue' ? 'model' : propName}Modifiers`;
const modifierType = getRangeText(scriptSetup, defineModel.modifierType);
yield `'${modifierName}'?: Partial<Record<${modifierType}, true>>${utils_1.endOfLine}`;
}
}
function* generateModelEmit(defineModel, propName, modelType) {
yield `'update:${propName}': [value: `;
yield modelType;
if (!defineModel.required && !defineModel.defaultValue) {
yield ` | undefined`;
}
yield `]${utils_1.endOfLine}`;
}
function getRangeText(scriptSetup, range) {
return scriptSetup.content.slice(range.start, range.end);
}
//# sourceMappingURL=scriptSetup.js.map
+3
View File
@@ -0,0 +1,3 @@
import type { Code } from '../../types';
import type { ScriptCodegenOptions } from './index';
export declare function generateTemplate(options: ScriptCodegenOptions, selfType?: string): Generator<Code>;

Some files were not shown because too many files have changed in this diff Show More