isBlock: VNodeCall['isBlock'] = false,
disableTracking: VNodeCall['disableTracking'] = false,
isComponent: VNodeCall['isComponent'] = false,
- loc = locStub,
+ loc: SourceLocation = locStub,
): VNodeCall {
if (context) {
if (isBlock) {
}
}
-export function getVNodeHelper(ssr: boolean, isComponent: boolean) {
+export function getVNodeHelper(
+ ssr: boolean,
+ isComponent: boolean,
+): typeof CREATE_VNODE | typeof CREATE_ELEMENT_VNODE {
return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE
}
-export function getVNodeBlockHelper(ssr: boolean, isComponent: boolean) {
+export function getVNodeBlockHelper(
+ ssr: boolean,
+ isComponent: boolean,
+): typeof CREATE_BLOCK | typeof CREATE_ELEMENT_BLOCK {
return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK
}
export function convertToBlock(
node: VNodeCall,
{ helper, removeHelper, inSSR }: TransformContext,
-) {
+): void {
if (!node.isBlock) {
node.isBlock = true
removeHelper(getVNodeHelper(inSSR, node.isComponent))
includeAll = false,
parentStack: Node[] = [],
knownIds: Record<string, number> = Object.create(null),
-) {
+): void {
if (__BROWSER__) {
return
}
id: Identifier,
parent: Node | null,
parentStack: Node[],
-) {
+): boolean {
if (__BROWSER__) {
return false
}
export function walkFunctionParams(
node: Function,
onIdent: (id: Identifier) => void,
-) {
+): void {
for (const p of node.params) {
for (const id of extractIdentifiers(p)) {
onIdent(id)
export function walkBlockDeclarations(
block: BlockStatement | Program,
onIdent: (node: Identifier) => void,
-) {
+): void {
for (const stmt of block.body) {
if (stmt.type === 'VariableDeclaration') {
if (stmt.declare) continue
(node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
!node.computed
-export const isStaticPropertyKey = (node: Node, parent: Node) =>
+export const isStaticPropertyKey = (node: Node, parent: Node): boolean =>
isStaticProperty(parent) && parent.key === node
/**
return true
}
-export const TS_NODE_TYPES = [
+export const TS_NODE_TYPES: string[] = [
'TSAsExpression', // foo as number
'TSTypeAssertion', // (<number>foo)
'TSNonNullExpression', // foo!
export function isCompatEnabled(
key: CompilerDeprecationTypes,
context: MergedParserOptions | TransformContext,
-) {
+): boolean {
const mode = getCompatValue('MODE', context)
const value = getCompatValue(key, context)
// in v3 mode, only enable if explicitly set to true
context: MergedParserOptions | TransformContext,
loc: SourceLocation | null,
...args: any[]
-) {
+): void {
const val = getCompatValue(key, context)
if (val === 'suppress-warning') {
return
code: ErrorCodes
}
-export function defaultOnError(error: CompilerError) {
+export function defaultOnError(error: CompilerError): never {
throw error
}
-export function defaultOnWarn(msg: CompilerError) {
+export function defaultOnWarn(msg: CompilerError): void {
__DEV__ && console.warn(`[Vue warn] ${msg.message}`)
}
-export const FRAGMENT = Symbol(__DEV__ ? `Fragment` : ``)
-export const TELEPORT = Symbol(__DEV__ ? `Teleport` : ``)
-export const SUSPENSE = Symbol(__DEV__ ? `Suspense` : ``)
-export const KEEP_ALIVE = Symbol(__DEV__ ? `KeepAlive` : ``)
-export const BASE_TRANSITION = Symbol(__DEV__ ? `BaseTransition` : ``)
-export const OPEN_BLOCK = Symbol(__DEV__ ? `openBlock` : ``)
-export const CREATE_BLOCK = Symbol(__DEV__ ? `createBlock` : ``)
-export const CREATE_ELEMENT_BLOCK = Symbol(__DEV__ ? `createElementBlock` : ``)
-export const CREATE_VNODE = Symbol(__DEV__ ? `createVNode` : ``)
-export const CREATE_ELEMENT_VNODE = Symbol(__DEV__ ? `createElementVNode` : ``)
-export const CREATE_COMMENT = Symbol(__DEV__ ? `createCommentVNode` : ``)
-export const CREATE_TEXT = Symbol(__DEV__ ? `createTextVNode` : ``)
-export const CREATE_STATIC = Symbol(__DEV__ ? `createStaticVNode` : ``)
-export const RESOLVE_COMPONENT = Symbol(__DEV__ ? `resolveComponent` : ``)
-export const RESOLVE_DYNAMIC_COMPONENT = Symbol(
+export const FRAGMENT: unique symbol = Symbol(__DEV__ ? `Fragment` : ``)
+export const TELEPORT: unique symbol = Symbol(__DEV__ ? `Teleport` : ``)
+export const SUSPENSE: unique symbol = Symbol(__DEV__ ? `Suspense` : ``)
+export const KEEP_ALIVE: unique symbol = Symbol(__DEV__ ? `KeepAlive` : ``)
+export const BASE_TRANSITION: unique symbol = Symbol(
+ __DEV__ ? `BaseTransition` : ``,
+)
+export const OPEN_BLOCK: unique symbol = Symbol(__DEV__ ? `openBlock` : ``)
+export const CREATE_BLOCK: unique symbol = Symbol(__DEV__ ? `createBlock` : ``)
+export const CREATE_ELEMENT_BLOCK: unique symbol = Symbol(
+ __DEV__ ? `createElementBlock` : ``,
+)
+export const CREATE_VNODE: unique symbol = Symbol(__DEV__ ? `createVNode` : ``)
+export const CREATE_ELEMENT_VNODE: unique symbol = Symbol(
+ __DEV__ ? `createElementVNode` : ``,
+)
+export const CREATE_COMMENT: unique symbol = Symbol(
+ __DEV__ ? `createCommentVNode` : ``,
+)
+export const CREATE_TEXT: unique symbol = Symbol(
+ __DEV__ ? `createTextVNode` : ``,
+)
+export const CREATE_STATIC: unique symbol = Symbol(
+ __DEV__ ? `createStaticVNode` : ``,
+)
+export const RESOLVE_COMPONENT: unique symbol = Symbol(
+ __DEV__ ? `resolveComponent` : ``,
+)
+export const RESOLVE_DYNAMIC_COMPONENT: unique symbol = Symbol(
__DEV__ ? `resolveDynamicComponent` : ``,
)
-export const RESOLVE_DIRECTIVE = Symbol(__DEV__ ? `resolveDirective` : ``)
-export const RESOLVE_FILTER = Symbol(__DEV__ ? `resolveFilter` : ``)
-export const WITH_DIRECTIVES = Symbol(__DEV__ ? `withDirectives` : ``)
-export const RENDER_LIST = Symbol(__DEV__ ? `renderList` : ``)
-export const RENDER_SLOT = Symbol(__DEV__ ? `renderSlot` : ``)
-export const CREATE_SLOTS = Symbol(__DEV__ ? `createSlots` : ``)
-export const TO_DISPLAY_STRING = Symbol(__DEV__ ? `toDisplayString` : ``)
-export const MERGE_PROPS = Symbol(__DEV__ ? `mergeProps` : ``)
-export const NORMALIZE_CLASS = Symbol(__DEV__ ? `normalizeClass` : ``)
-export const NORMALIZE_STYLE = Symbol(__DEV__ ? `normalizeStyle` : ``)
-export const NORMALIZE_PROPS = Symbol(__DEV__ ? `normalizeProps` : ``)
-export const GUARD_REACTIVE_PROPS = Symbol(__DEV__ ? `guardReactiveProps` : ``)
-export const TO_HANDLERS = Symbol(__DEV__ ? `toHandlers` : ``)
-export const CAMELIZE = Symbol(__DEV__ ? `camelize` : ``)
-export const CAPITALIZE = Symbol(__DEV__ ? `capitalize` : ``)
-export const TO_HANDLER_KEY = Symbol(__DEV__ ? `toHandlerKey` : ``)
-export const SET_BLOCK_TRACKING = Symbol(__DEV__ ? `setBlockTracking` : ``)
+export const RESOLVE_DIRECTIVE: unique symbol = Symbol(
+ __DEV__ ? `resolveDirective` : ``,
+)
+export const RESOLVE_FILTER: unique symbol = Symbol(
+ __DEV__ ? `resolveFilter` : ``,
+)
+export const WITH_DIRECTIVES: unique symbol = Symbol(
+ __DEV__ ? `withDirectives` : ``,
+)
+export const RENDER_LIST: unique symbol = Symbol(__DEV__ ? `renderList` : ``)
+export const RENDER_SLOT: unique symbol = Symbol(__DEV__ ? `renderSlot` : ``)
+export const CREATE_SLOTS: unique symbol = Symbol(__DEV__ ? `createSlots` : ``)
+export const TO_DISPLAY_STRING: unique symbol = Symbol(
+ __DEV__ ? `toDisplayString` : ``,
+)
+export const MERGE_PROPS: unique symbol = Symbol(__DEV__ ? `mergeProps` : ``)
+export const NORMALIZE_CLASS: unique symbol = Symbol(
+ __DEV__ ? `normalizeClass` : ``,
+)
+export const NORMALIZE_STYLE: unique symbol = Symbol(
+ __DEV__ ? `normalizeStyle` : ``,
+)
+export const NORMALIZE_PROPS: unique symbol = Symbol(
+ __DEV__ ? `normalizeProps` : ``,
+)
+export const GUARD_REACTIVE_PROPS: unique symbol = Symbol(
+ __DEV__ ? `guardReactiveProps` : ``,
+)
+export const TO_HANDLERS: unique symbol = Symbol(__DEV__ ? `toHandlers` : ``)
+export const CAMELIZE: unique symbol = Symbol(__DEV__ ? `camelize` : ``)
+export const CAPITALIZE: unique symbol = Symbol(__DEV__ ? `capitalize` : ``)
+export const TO_HANDLER_KEY: unique symbol = Symbol(
+ __DEV__ ? `toHandlerKey` : ``,
+)
+export const SET_BLOCK_TRACKING: unique symbol = Symbol(
+ __DEV__ ? `setBlockTracking` : ``,
+)
/**
* @deprecated no longer needed in 3.5+ because we no longer hoist element nodes
* but kept for backwards compat
*/
-export const PUSH_SCOPE_ID = Symbol(__DEV__ ? `pushScopeId` : ``)
+export const PUSH_SCOPE_ID: unique symbol = Symbol(__DEV__ ? `pushScopeId` : ``)
/**
* @deprecated kept for backwards compat
*/
-export const POP_SCOPE_ID = Symbol(__DEV__ ? `popScopeId` : ``)
-export const WITH_CTX = Symbol(__DEV__ ? `withCtx` : ``)
-export const UNREF = Symbol(__DEV__ ? `unref` : ``)
-export const IS_REF = Symbol(__DEV__ ? `isRef` : ``)
-export const WITH_MEMO = Symbol(__DEV__ ? `withMemo` : ``)
-export const IS_MEMO_SAME = Symbol(__DEV__ ? `isMemoSame` : ``)
+export const POP_SCOPE_ID: unique symbol = Symbol(__DEV__ ? `popScopeId` : ``)
+export const WITH_CTX: unique symbol = Symbol(__DEV__ ? `withCtx` : ``)
+export const UNREF: unique symbol = Symbol(__DEV__ ? `unref` : ``)
+export const IS_REF: unique symbol = Symbol(__DEV__ ? `isRef` : ``)
+export const WITH_MEMO: unique symbol = Symbol(__DEV__ ? `withMemo` : ``)
+export const IS_MEMO_SAME: unique symbol = Symbol(__DEV__ ? `isMemoSame` : ``)
// Name mapping for runtime helpers that need to be imported from 'vue' in
// generated code. Make sure these are correctly exported in the runtime!
[IS_MEMO_SAME]: `isMemoSame`,
}
-export function registerRuntimeHelpers(helpers: Record<symbol, string>) {
+export function registerRuntimeHelpers(helpers: Record<symbol, string>): void {
Object.getOwnPropertySymbols(helpers).forEach(s => {
helperNameMap[s] = helpers[s]
})
* We don't have `Script`, `Style`, or `Title` here. Instead, we re-use the *End
* sequences with an increased offset.
*/
-export const Sequences = {
+export const Sequences: {
+ Cdata: Uint8Array
+ CdataEnd: Uint8Array
+ CommentEnd: Uint8Array
+ ScriptEnd: Uint8Array
+ StyleEnd: Uint8Array
+ TitleEnd: Uint8Array
+ TextareaEnd: Uint8Array
+} = {
Cdata: new Uint8Array([0x43, 0x44, 0x41, 0x54, 0x41, 0x5b]), // CDATA[
CdataEnd: new Uint8Array([0x5d, 0x5d, 0x3e]), // ]]>
CommentEnd: new Uint8Array([0x2d, 0x2d, 0x3e]), // `-->`
export default class Tokenizer {
/** The current state the tokenizer is in. */
- public state = State.Text
+ public state: State = State.Text
/** The read buffer. */
private buffer = ''
/** The beginning of the section that is currently being read. */
private readonly entityDecoder?: EntityDecoder
- public mode = ParseMode.BASE
- public get inSFCRoot() {
+ public mode: ParseMode = ParseMode.BASE
+ public get inSFCRoot(): boolean {
return this.mode === ParseMode.SFC && this.stack.length === 0
}
this.state = State.SpecialStartSequence
}
- public enterRCDATA(sequence: Uint8Array, offset: number) {
+ public enterRCDATA(sequence: Uint8Array, offset: number): void {
this.inRCDATA = true
this.currentSequence = sequence
this.sequenceIndex = offset
*
* States that are more likely to be hit are higher up, as a performance improvement.
*/
- public parse(input: string) {
+ public parse(input: string): void {
this.buffer = input
while (this.index < this.buffer.length) {
const c = this.buffer.charCodeAt(this.index)
return context
}
-export function transform(root: RootNode, options: TransformOptions) {
+export function transform(root: RootNode, options: TransformOptions): void {
const context = createTransformContext(root, options)
traverseNode(root, context)
if (options.hoistStatic) {
export function traverseChildren(
parent: ParentNode,
context: TransformContext,
-) {
+): void {
let i = 0
const nodeRemoved = () => {
i--
export function traverseNode(
node: RootNode | TemplateChildNode,
context: TransformContext,
-) {
+): void {
context.currentNode = node
// apply transform plugins
const { nodeTransforms } = context
OPEN_BLOCK,
} from '../runtimeHelpers'
-export function cacheStatic(root: RootNode, context: TransformContext) {
+export function cacheStatic(root: RootNode, context: TransformContext): void {
walk(
root,
undefined,
node: ComponentNode,
context: TransformContext,
ssr = false,
-) {
+): string | symbol | CallExpression {
let { tag } = node
// 1. dynamic component
export function buildProps(
node: ElementNode,
context: TransformContext,
- props: ElementNode['props'] = node.props,
+ props: ElementNode['props'] | undefined = node.props,
isComponent: boolean,
isDynamicComponent: boolean,
ssr = false,
export const transformBindShorthand = (
dir: DirectiveNode,
context: TransformContext,
-) => {
+): void => {
const arg = dir.arg!
const propName = camelize((arg as SimpleExpressionNode).content)
import {
+ type NodeTransform,
type TransformContext,
createStructuralDirectiveTransform,
} from '../transform'
import { PatchFlags } from '@vue/shared'
import { transformBindShorthand } from './vBind'
-export const transformFor = createStructuralDirectiveTransform(
+export const transformFor: NodeTransform = createStructuralDirectiveTransform(
'for',
(node, dir, context) => {
const { helper, removeHelper } = context
const onExit = processCodegen && processCodegen(forNode)
- return () => {
+ return (): void => {
scopes.vFor--
if (!__BROWSER__ && context.prefixIdentifiers) {
value && removeIdentifiers(value)
export function finalizeForParseResult(
result: ForParseResult,
context: TransformContext,
-) {
+): void {
if (result.finalized) return
if (!__BROWSER__ && context.prefixIdentifiers) {
import {
+ type NodeTransform,
type TransformContext,
createStructuralDirectiveTransform,
traverseNode,
import { findDir, findProp, getMemoedVNodeCall, injectProp } from '../utils'
import { PatchFlagNames, PatchFlags } from '@vue/shared'
-export const transformIf = createStructuralDirectiveTransform(
+export const transformIf: NodeTransform = createStructuralDirectiveTransform(
/^(if|else|else-if)$/,
(node, dir, context) => {
return processIf(node, dir, context, (ifNode, branch, isRoot) => {
branch: IfBranchNode,
isRoot: boolean,
) => (() => void) | undefined,
-) {
+): (() => void) | undefined {
if (
dir.name !== 'else' &&
(!dir.exp || !(dir.exp as SimpleExpressionNode).content.trim())
return !currentOpenBracketCount && !currentOpenParensCount
}
-export const isMemberExpressionNode = __BROWSER__
- ? (NOOP as any as (path: string, context: TransformContext) => boolean)
+export const isMemberExpressionNode: (
+ path: string,
+ context: TransformContext,
+) => boolean = __BROWSER__
+ ? (NOOP as any)
: (path: string, context: TransformContext): boolean => {
try {
let ret: Expression = parseExpression(path, {
}
}
-export const isMemberExpression = __BROWSER__
- ? isMemberExpressionBrowser
- : isMemberExpressionNode
+export const isMemberExpression: (
+ path: string,
+ context: TransformContext,
+) => boolean = __BROWSER__ ? isMemberExpressionBrowser : isMemberExpressionNode
export function advancePositionWithClone(
pos: Position,
return pos
}
-export function assert(condition: boolean, msg?: string) {
+export function assert(condition: boolean, msg?: string): void {
/* istanbul ignore if */
if (!condition) {
throw new Error(msg || `unexpected compiler condition`)
node: VNodeCall | RenderSlotCall,
prop: Property,
context: TransformContext,
-) {
+): void {
let propsWithInjection: ObjectExpression | CallExpression | undefined
/**
* 1. mergeProps(...)
}
}
-export function getMemoedVNodeCall(node: BlockCodegenNode | MemoExpression) {
+export function getMemoedVNodeCall(
+ node: BlockCodegenNode | MemoExpression,
+): VNodeCall | RenderSlotCall {
if (node.type === NodeTypes.JS_CALL_EXPRESSION && node.callee === WITH_MEMO) {
return node.arguments[1].returns as VNodeCall
} else {
}
}
-export const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/
+export const forAliasRE: RegExp = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/
context: TransformContext,
asParams = false,
asRawStatements = false,
-) {
+): void {
const exp = node.content
// empty expressions are validated per-directive since some directives
import { registerRuntimeHelpers } from '@vue/compiler-core'
-export const V_MODEL_RADIO = Symbol(__DEV__ ? `vModelRadio` : ``)
-export const V_MODEL_CHECKBOX = Symbol(__DEV__ ? `vModelCheckbox` : ``)
-export const V_MODEL_TEXT = Symbol(__DEV__ ? `vModelText` : ``)
-export const V_MODEL_SELECT = Symbol(__DEV__ ? `vModelSelect` : ``)
-export const V_MODEL_DYNAMIC = Symbol(__DEV__ ? `vModelDynamic` : ``)
+export const V_MODEL_RADIO: unique symbol = Symbol(__DEV__ ? `vModelRadio` : ``)
+export const V_MODEL_CHECKBOX: unique symbol = Symbol(
+ __DEV__ ? `vModelCheckbox` : ``,
+)
+export const V_MODEL_TEXT: unique symbol = Symbol(__DEV__ ? `vModelText` : ``)
+export const V_MODEL_SELECT: unique symbol = Symbol(
+ __DEV__ ? `vModelSelect` : ``,
+)
+export const V_MODEL_DYNAMIC: unique symbol = Symbol(
+ __DEV__ ? `vModelDynamic` : ``,
+)
-export const V_ON_WITH_MODIFIERS = Symbol(__DEV__ ? `vOnModifiersGuard` : ``)
-export const V_ON_WITH_KEYS = Symbol(__DEV__ ? `vOnKeysGuard` : ``)
+export const V_ON_WITH_MODIFIERS: unique symbol = Symbol(
+ __DEV__ ? `vOnModifiersGuard` : ``,
+)
+export const V_ON_WITH_KEYS: unique symbol = Symbol(
+ __DEV__ ? `vOnKeysGuard` : ``,
+)
-export const V_SHOW = Symbol(__DEV__ ? `vShow` : ``)
+export const V_SHOW: unique symbol = Symbol(__DEV__ ? `vShow` : ``)
-export const TRANSITION = Symbol(__DEV__ ? `Transition` : ``)
-export const TRANSITION_GROUP = Symbol(__DEV__ ? `TransitionGroup` : ``)
+export const TRANSITION: unique symbol = Symbol(__DEV__ ? `Transition` : ``)
+export const TRANSITION_GROUP: unique symbol = Symbol(
+ __DEV__ ? `TransitionGroup` : ``,
+)
registerRuntimeHelpers({
[V_MODEL_RADIO]: `vModelRadio`,
-export const version = __VERSION__
+export const version: string = __VERSION__
// API
export { parse } from './parse'
errorMessages as coreErrorMessages,
} from '@vue/compiler-dom'
-export const errorMessages = {
+export const errorMessages: Record<number, string> = {
...coreErrorMessages,
...DOMErrorMessages,
}
import { createCache } from './cache'
import type { ImportBinding } from './compileScript'
import { isImportUsed } from './script/importUsageCheck'
+import type { LRUCache } from 'lru-cache'
export const DEFAULT_FILENAME = 'anonymous.vue'
errors: (CompilerError | SyntaxError)[]
}
-export const parseCache = createCache<SFCParseResult>()
+export const parseCache:
+ | Map<string, SFCParseResult>
+ | LRUCache<string, SFCParseResult> = createCache<SFCParseResult>()
function genCacheKey(source: string, options: SFCParseOptions): string {
return (
scriptAst: Program | null
scriptSetupAst: Program | null
- source = this.descriptor.source
- filename = this.descriptor.filename
- s = new MagicString(this.source)
- startOffset = this.descriptor.scriptSetup?.loc.start.offset
- endOffset = this.descriptor.scriptSetup?.loc.end.offset
+ source: string = this.descriptor.source
+ filename: string = this.descriptor.filename
+ s: MagicString = new MagicString(this.source)
+ startOffset: number | undefined =
+ this.descriptor.scriptSetup?.loc.start.offset
+ endOffset: number | undefined = this.descriptor.scriptSetup?.loc.end.offset
// import / type analysis
scope?: TypeScope
lang: string,
userPlugins?: ParserPlugin[],
dts = false,
-) {
+): ParserPlugin[] {
const plugins: ParserPlugin[] = []
if (
!userPlugins ||
ctx: ScriptCompileContext,
node: Node,
declId?: LVal,
-) {
+): boolean {
if (!isCallOf(node, DEFINE_PROPS)) {
return processWithDefaults(ctx, node, declId)
}
export function processPropsDestructure(
ctx: ScriptCompileContext,
declId: ObjectPattern,
-) {
+): void {
if (ctx.options.propsDestructure === 'error') {
ctx.error(`Props destructure is explicitly prohibited via config.`, declId)
} else if (ctx.options.propsDestructure === false) {
export function transformDestructuredProps(
ctx: ScriptCompileContext,
vueImportAliases: Record<string, string>,
-) {
+): void {
if (ctx.options.propsDestructure === false) {
return
}
import MagicString from 'magic-string'
import { rewriteDefaultAST } from '../rewriteDefault'
import { genNormalScriptCssVarsCode } from '../style/cssVars'
+import type { SFCScriptBlock } from '../parse'
export const normalScriptDefaultVar = `__default__`
export function processNormalScript(
ctx: ScriptCompileContext,
scopeId: string,
-) {
+): SFCScriptBlock {
const script = ctx.descriptor.script!
if (script.lang && !ctx.isJS && !ctx.isTS) {
// do not process non js/ts script blocks
/**
* @private
*/
-export function registerTS(_loadTS: () => typeof TS) {
+export function registerTS(_loadTS: () => typeof TS): void {
loadTS = () => {
try {
return _loadTS()
/**
* @private
*/
-export function invalidateTypeCache(filename: string) {
+export function invalidateTypeCache(filename: string): void {
filename = normalizePath(filename)
fileToScopeCache.delete(filename)
tsConfigCache.delete(filename)
}
}
-export function recordImports(body: Statement[]) {
+export function recordImports(body: Statement[]): Record<string, Import> {
const imports: TypeScope['imports'] = Object.create(null)
for (const s of body) {
recordImport(s, imports)
export function inferRuntimeType(
ctx: TypeResolveContext,
node: Node & MaybeWithScope,
- scope = node._ownerScope || ctxToScope(ctx),
+ scope: TypeScope = node._ownerScope || ctxToScope(ctx),
isKeyOf = false,
): string[] {
try {
node: AwaitExpression,
needSemi: boolean,
isStatement: boolean,
-) {
+): void {
const argumentStart =
node.argument.extra && node.argument.extra.parenthesized
? (node.argument.extra.parenStart as number)
export const UNKNOWN_TYPE = 'Unknown'
-export function resolveObjectKey(node: Node, computed: boolean) {
+export function resolveObjectKey(
+ node: Node,
+ computed: boolean,
+): string | undefined {
switch (node.type) {
case 'StringLiteral':
case 'NumericLiteral':
return undefined
}
-export function concatStrings(strs: Array<string | null | undefined | false>) {
+export function concatStrings(
+ strs: Array<string | null | undefined | false>,
+): string {
return strs.filter((s): s is string => !!s).join(', ')
}
-export function isLiteralNode(node: Node) {
+export function isLiteralNode(node: Node): boolean {
return node.type.endsWith('Literal')
}
)
}
-export function toRuntimeTypeString(types: string[]) {
+export function toRuntimeTypeString(types: string[]): string {
return types.length > 1 ? `[${types.join(', ')}]` : types[0]
}
| ImportSpecifier
| ImportDefaultSpecifier
| ImportNamespaceSpecifier,
-) {
+): string {
if (specifier.type === 'ImportSpecifier')
return specifier.imported.type === 'Identifier'
? specifier.imported.name
* but TS does not expose it directly. This implementation is repllicated from
* the TS source code.
*/
-export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean) {
+export function createGetCanonicalFileName(
+ useCaseSensitiveFileNames: boolean,
+): (str: string) => string {
return useCaseSensitiveFileNames ? identity : toFileNameLowerCase
}
// posix behavior.
const normalize = (path.posix || path).normalize
const windowsSlashRE = /\\/g
-export function normalizePath(p: string) {
+export function normalizePath(p: string): string {
return normalize(p.replace(windowsSlashRE, '/'))
}
-export const joinPaths = (path.posix || path).join
+export const joinPaths: (...paths: string[]) => string = (path.posix || path)
+ .join
/**
* key may contain symbols
* e.g. onUpdate:modelValue -> "onUpdate:modelValue"
*/
-export const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/
+export const propNameEscapeSymbolsRE: RegExp =
+ /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/
-export function getEscapedPropName(key: string) {
+export function getEscapedPropName(key: string): string {
return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key
}
-export const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g
+export const cssVarNameEscapeSymbolsRE: RegExp =
+ /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g
-export function getEscapedCssVarName(key: string, doubleEscape: boolean) {
+export function getEscapedCssVarName(
+ key: string,
+ doubleEscape: boolean,
+): string {
return key.replace(cssVarNameEscapeSymbolsRE, s =>
doubleEscape ? `\\\\${s}` : `\\${s}`,
)
const hasWarned: Record<string, boolean> = {}
-export function warnOnce(msg: string) {
+export function warnOnce(msg: string): void {
const isNodeProd =
typeof process !== 'undefined' && process.env.NODE_ENV === 'production'
if (!isNodeProd && !__TEST__ && !hasWarned[msg]) {
}
}
-export function warn(msg: string) {
+export function warn(msg: string): void {
console.warn(
`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`,
)
import { registerRuntimeHelpers } from '@vue/compiler-dom'
-export const SSR_INTERPOLATE = Symbol(`ssrInterpolate`)
-export const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`)
-export const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`)
-export const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`)
-export const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`)
-export const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`)
-export const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`)
-export const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`)
-export const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`)
-export const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`)
-export const SSR_RENDER_LIST = Symbol(`ssrRenderList`)
-export const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`)
-export const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`)
-export const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`)
-export const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`)
-export const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`)
-export const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`)
-export const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`)
-export const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`)
+export const SSR_INTERPOLATE: unique symbol = Symbol(`ssrInterpolate`)
+export const SSR_RENDER_VNODE: unique symbol = Symbol(`ssrRenderVNode`)
+export const SSR_RENDER_COMPONENT: unique symbol = Symbol(`ssrRenderComponent`)
+export const SSR_RENDER_SLOT: unique symbol = Symbol(`ssrRenderSlot`)
+export const SSR_RENDER_SLOT_INNER: unique symbol = Symbol(`ssrRenderSlotInner`)
+export const SSR_RENDER_CLASS: unique symbol = Symbol(`ssrRenderClass`)
+export const SSR_RENDER_STYLE: unique symbol = Symbol(`ssrRenderStyle`)
+export const SSR_RENDER_ATTRS: unique symbol = Symbol(`ssrRenderAttrs`)
+export const SSR_RENDER_ATTR: unique symbol = Symbol(`ssrRenderAttr`)
+export const SSR_RENDER_DYNAMIC_ATTR: unique symbol =
+ Symbol(`ssrRenderDynamicAttr`)
+export const SSR_RENDER_LIST: unique symbol = Symbol(`ssrRenderList`)
+export const SSR_INCLUDE_BOOLEAN_ATTR: unique symbol = Symbol(
+ `ssrIncludeBooleanAttr`,
+)
+export const SSR_LOOSE_EQUAL: unique symbol = Symbol(`ssrLooseEqual`)
+export const SSR_LOOSE_CONTAIN: unique symbol = Symbol(`ssrLooseContain`)
+export const SSR_RENDER_DYNAMIC_MODEL: unique symbol = Symbol(
+ `ssrRenderDynamicModel`,
+)
+export const SSR_GET_DYNAMIC_MODEL_PROPS: unique symbol = Symbol(
+ `ssrGetDynamicModelProps`,
+)
+export const SSR_RENDER_TELEPORT: unique symbol = Symbol(`ssrRenderTeleport`)
+export const SSR_RENDER_SUSPENSE: unique symbol = Symbol(`ssrRenderSuspense`)
+export const SSR_GET_DIRECTIVE_PROPS: unique symbol =
+ Symbol(`ssrGetDirectiveProps`)
-export const ssrHelpers = {
+export const ssrHelpers: Record<symbol, string> = {
[SSR_INTERPOLATE]: `ssrInterpolate`,
[SSR_RENDER_VNODE]: `ssrRenderVNode`,
[SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
import {
type BlockStatement,
type CallExpression,
+ type CompilerError,
type CompilerOptions,
ElementTypes,
type IfStatement,
+ type JSChildNode,
NodeTypes,
type RootNode,
type TemplateChildNode,
// transform pass to convert the template AST into a fresh JS AST before
// passing it to codegen.
-export function ssrCodegenTransform(ast: RootNode, options: CompilerOptions) {
+export function ssrCodegenTransform(
+ ast: RootNode,
+ options: CompilerOptions,
+): void {
const context = createSSRTransformContext(ast, options)
// inject SFC <style> CSS variables
ast.helpers = new Set(Array.from(ast.helpers).filter(h => !(h in ssrHelpers)))
}
-export type SSRTransformContext = ReturnType<typeof createSSRTransformContext>
+export interface SSRTransformContext {
+ root: RootNode
+ options: CompilerOptions
+ body: (JSChildNode | IfStatement)[]
+ helpers: Set<symbol>
+ withSlotScopeId: boolean
+ onError: (error: CompilerError) => void
+ helper<T extends symbol>(name: T): T
+ pushStringPart(part: TemplateLiteral['elements'][0]): void
+ pushStatement(statement: IfStatement | CallExpression): void
+}
function createSSRTransformContext(
root: RootNode,
options: CompilerOptions,
helpers: Set<symbol> = new Set(),
withSlotScopeId = false,
-) {
+): SSRTransformContext {
const body: BlockStatement['body'] = []
let currentString: TemplateLiteral | null = null
helpers.add(name)
return name
},
- pushStringPart(part: TemplateLiteral['elements'][0]) {
+ pushStringPart(part) {
if (!currentString) {
const currentCall = createCallExpression(`_push`)
body.push(currentCall)
bufferedElements.push(part)
}
},
- pushStatement(statement: IfStatement | CallExpression) {
+ pushStatement(statement) {
// close current string
currentString = null
body.push(statement)
asFragment = false,
disableNestedFragments = false,
disableCommentAsIfAlternate = false,
-) {
+): void {
if (asFragment) {
context.pushStringPart(`<!--[-->`)
}
parent: Container,
parentContext: SSRTransformContext,
asFragment = false,
- withSlotScopeId = parentContext.withSlotScopeId,
+ withSlotScopeId: boolean = parentContext.withSlotScopeId,
): BlockStatement {
const childContext = createChildContext(parentContext, withSlotScopeId)
processChildren(parent, childContext, asFragment)
node: ComponentNode,
context: SSRTransformContext,
parent: { children: TemplateChildNode[] },
-) {
+): void {
const component = componentTypeMap.get(node)!
if (!node.ssrCodegenNode) {
// this is a built-in component that fell-through.
}
}
-export const rawOptionsMap = new WeakMap<RootNode, CompilerOptions>()
+export const rawOptionsMap: WeakMap<RootNode, CompilerOptions> = new WeakMap<
+ RootNode,
+ CompilerOptions
+>()
const [baseNodeTransforms, baseDirectiveTransforms] =
getBaseTransformPreset(true)
export function ssrProcessElement(
node: PlainElementNode,
context: SSRTransformContext,
-) {
+): void {
const isVoidTag = context.options.isVoidTag || NO
const elementsToAdd = node.ssrCodegenNode!.elements
for (let j = 0; j < elementsToAdd.length; j++) {
export function ssrProcessSlotOutlet(
node: SlotOutletNode,
context: SSRTransformContext,
-) {
+): void {
const renderCall = node.ssrCodegenNode!
// has fallback content
node: ComponentNode,
context: TransformContext,
) {
- return () => {
+ return (): void => {
if (node.children.length) {
const wipEntry: WIPEntry = {
slotsExp: null!, // to be immediately set
export function ssrProcessSuspense(
node: ComponentNode,
context: SSRTransformContext,
-) {
+): void {
// complete wip slots with ssr code
const wipEntry = wipMap.get(node)
if (!wipEntry) {
export function ssrProcessTeleport(
node: ComponentNode,
context: SSRTransformContext,
-) {
+): void {
const targetProp = findProp(node, 'to')
if (!targetProp) {
context.onError(
node: ComponentNode,
context: TransformContext,
) {
- return () => {
+ return (): void => {
const appear = findProp(node, 'appear', false, true)
wipMap.set(node, !!appear)
}
export function ssrProcessTransition(
node: ComponentNode,
context: SSRTransformContext,
-) {
+): void {
// #5351: filter out comment children inside transition
node.children = node.children.filter(c => c.type !== NodeTypes.COMMENT)
node: ComponentNode,
context: TransformContext,
) {
- return () => {
+ return (): void => {
const tag = findProp(node, 'tag')
if (tag) {
const otherProps = node.props.filter(p => p !== tag)
export function ssrProcessTransitionGroup(
node: ComponentNode,
context: SSRTransformContext,
-) {
+): void {
const entry = wipMap.get(node)
if (entry) {
const { tag, propsExp, scopeId } = entry
import {
type ForNode,
+ type NodeTransform,
NodeTypes,
createCallExpression,
createForLoopParams,
import { SSR_RENDER_LIST } from '../runtimeHelpers'
// Plugin for the first transform pass, which simply constructs the AST node
-export const ssrTransformFor = createStructuralDirectiveTransform(
- 'for',
- processFor,
-)
+export const ssrTransformFor: NodeTransform =
+ createStructuralDirectiveTransform('for', processFor)
// This is called during the 2nd transform pass to construct the SSR-specific
// codegen nodes.
node: ForNode,
context: SSRTransformContext,
disableNestedFragments = false,
-) {
+): void {
const needFragmentWrapper =
!disableNestedFragments &&
(node.children.length !== 1 || node.children[0].type !== NodeTypes.ELEMENT)
type BlockStatement,
type IfBranchNode,
type IfNode,
+ type NodeTransform,
NodeTypes,
createBlockStatement,
createCallExpression,
} from '../ssrCodegenTransform'
// Plugin for the first transform pass, which simply constructs the AST node
-export const ssrTransformIf = createStructuralDirectiveTransform(
+export const ssrTransformIf: NodeTransform = createStructuralDirectiveTransform(
/^(if|else|else-if)$/,
processIf,
)
context: SSRTransformContext,
disableNestedFragments = false,
disableCommentAsIfAlternate = false,
-) {
+): void {
const [rootBranch] = node.branches
const ifStatement = createIfStatement(
rootBranch.condition!,
protected readonly _isShallow = false,
) {}
- get(target: Target, key: string | symbol, receiver: object) {
+ get(target: Target, key: string | symbol, receiver: object): any {
const isReadonly = this._isReadonly,
isShallow = this._isShallow
if (key === ReactiveFlags.IS_REACTIVE) {
export const readonlyHandlers: ProxyHandler<object> =
/*#__PURE__*/ new ReadonlyReactiveHandler()
-export const shallowReactiveHandlers = /*#__PURE__*/ new MutableReactiveHandler(
- true,
-)
+export const shallowReactiveHandlers: MutableReactiveHandler =
+ /*#__PURE__*/ new MutableReactiveHandler(true)
// Props handlers are special in the sense that it should not unwrap top-level
// refs (in order to allow refs to be explicitly passed down), but should
// retain the reactivity of the normal readonly object.
-export const shallowReadonlyHandlers =
+export const shallowReadonlyHandlers: ReadonlyReactiveHandler =
/*#__PURE__*/ new ReadonlyReactiveHandler(true)
/**
* @internal
*/
- readonly dep = new Dep(this)
+ readonly dep: Dep = new Dep(this)
/**
* @internal
*/
- readonly [ReactiveFlags.IS_REF] = true
+ readonly __v_isRef = true
+ // TODO isolatedDeclarations ReactiveFlags.IS_REF
/**
* @internal
*/
- readonly [ReactiveFlags.IS_READONLY]: boolean
+ readonly __v_isReadonly: boolean
+ // TODO isolatedDeclarations ReactiveFlags.IS_READONLY
// A computed is also a subscriber that tracks other deps
/**
* @internal
/**
* @internal
*/
- flags = EffectFlags.DIRTY
+ flags: EffectFlags = EffectFlags.DIRTY
/**
* @internal
*/
- globalVersion = globalVersion - 1
+ globalVersion: number = globalVersion - 1
/**
* @internal
*/
isSSR: boolean
// for backwards compat
- effect = this
+ effect: this = this
// dev only
onTrack?: (event: DebuggerEvent) => void
/**
* @internal
*/
- notify() {
+ notify(): void {
// avoid infinite self recursion
if (activeSub !== this) {
this.flags |= EffectFlags.DIRTY
}
}
- get value() {
+ get value(): T {
const link = __DEV__
? this.dep.track({
target: this,
*/
subsHead?: Link
- constructor(public computed?: ComputedRefImpl) {
+ constructor(public computed?: ComputedRefImpl | undefined) {
if (__DEV__) {
this.subsHead = undefined
}
return link
}
- trigger(debugInfo?: DebuggerEventExtraInfo) {
+ trigger(debugInfo?: DebuggerEventExtraInfo): void {
this.version++
globalVersion++
this.notify(debugInfo)
}
- notify(debugInfo?: DebuggerEventExtraInfo) {
+ notify(debugInfo?: DebuggerEventExtraInfo): void {
startBatch()
try {
if (__DEV__) {
type KeyToDepMap = Map<any, Dep>
const targetMap = new WeakMap<object, KeyToDepMap>()
-export const ITERATE_KEY = Symbol(__DEV__ ? 'Object iterate' : '')
-export const MAP_KEY_ITERATE_KEY = Symbol(__DEV__ ? 'Map keys iterate' : '')
-export const ARRAY_ITERATE_KEY = Symbol(__DEV__ ? 'Array iterate' : '')
+export const ITERATE_KEY: unique symbol = Symbol(
+ __DEV__ ? 'Object iterate' : '',
+)
+export const MAP_KEY_ITERATE_KEY: unique symbol = Symbol(
+ __DEV__ ? 'Map keys iterate' : '',
+)
+export const ARRAY_ITERATE_KEY: unique symbol = Symbol(
+ __DEV__ ? 'Array iterate' : '',
+)
/**
* Tracks access to a reactive property.
* @param type - Defines the type of access to the reactive property.
* @param key - Identifier of the reactive property to track.
*/
-export function track(target: object, type: TrackOpTypes, key: unknown) {
+export function track(target: object, type: TrackOpTypes, key: unknown): void {
if (shouldTrack && activeSub) {
let depsMap = targetMap.get(target)
if (!depsMap) {
newValue?: unknown,
oldValue?: unknown,
oldTarget?: Map<unknown, unknown> | Set<unknown>,
-) {
+): void {
const depsMap = targetMap.get(target)
if (!depsMap) {
// never been tracked
/**
* Test only
*/
-export function getDepFromReactive(object: any, key: string | number | symbol) {
+export function getDepFromReactive(
+ object: any,
+ key: string | number | symbol,
+): Dep | undefined {
// eslint-disable-next-line
return targetMap.get(object)?.get(key)
}
}
}
- pause() {
+ pause(): void {
this.flags |= EffectFlags.PAUSED
}
- resume() {
+ resume(): void {
if (this.flags & EffectFlags.PAUSED) {
this.flags &= ~EffectFlags.PAUSED
if (pausedQueueEffects.has(this)) {
/**
* @internal
*/
- notify() {
+ notify(): void {
if (
this.flags & EffectFlags.RUNNING &&
!(this.flags & EffectFlags.ALLOW_RECURSE)
}
}
- run() {
+ run(): T {
// TODO cleanupEffect
if (!(this.flags & EffectFlags.ACTIVE)) {
}
}
- stop() {
+ stop(): void {
if (this.flags & EffectFlags.ACTIVE) {
for (let link = this.deps; link; link = link.nextDep) {
removeSub(link)
}
}
- trigger() {
+ trigger(): void {
if (this.flags & EffectFlags.PAUSED) {
pausedQueueEffects.add(this)
} else if (this.scheduler) {
/**
* @internal
*/
- runIfDirty() {
+ runIfDirty(): void {
if (isDirty(this)) {
this.run()
}
}
- get dirty() {
+ get dirty(): boolean {
return isDirty(this)
}
}
/**
* @internal
*/
-export function startBatch() {
+export function startBatch(): void {
batchDepth++
}
* Run batched effects when all batches have ended
* @internal
*/
-export function endBatch() {
+export function endBatch(): void {
if (batchDepth > 1) {
batchDepth--
return
* Returning false indicates the refresh failed
* @internal
*/
-export function refreshComputed(computed: ComputedRefImpl) {
+export function refreshComputed(computed: ComputedRefImpl): false | undefined {
if (computed.flags & EffectFlags.RUNNING) {
return false
}
*
* @param runner - Association with the effect to stop tracking.
*/
-export function stop(runner: ReactiveEffectRunner) {
+export function stop(runner: ReactiveEffectRunner): void {
runner.effect.stop()
}
/**
* Temporarily pauses tracking.
*/
-export function pauseTracking() {
+export function pauseTracking(): void {
trackStack.push(shouldTrack)
shouldTrack = false
}
/**
* Re-enables effect tracking (if it was paused).
*/
-export function enableTracking() {
+export function enableTracking(): void {
trackStack.push(shouldTrack)
shouldTrack = true
}
/**
* Resets the previous global effect tracking state.
*/
-export function resetTracking() {
+export function resetTracking(): void {
const last = trackStack.pop()
shouldTrack = last === undefined ? true : last
}
* @param failSilently - if `true`, will not throw warning when called without
* an active effect.
*/
-export function onEffectCleanup(fn: () => void, failSilently = false) {
+export function onEffectCleanup(fn: () => void, failSilently = false): void {
if (activeSub instanceof ReactiveEffect) {
activeSub.cleanup = fn
} else if (__DEV__ && !failSilently) {
}
}
- get active() {
+ get active(): boolean {
return this._active
}
- pause() {
+ pause(): void {
if (this._active) {
this._isPaused = true
if (this.scopes) {
/**
* Resumes the effect scope, including all child scopes and effects.
*/
- resume() {
+ resume(): void {
if (this._active) {
if (this._isPaused) {
this._isPaused = false
* This should only be called on non-detached scopes
* @internal
*/
- on() {
+ on(): void {
activeEffectScope = this
}
* This should only be called on non-detached scopes
* @internal
*/
- off() {
+ off(): void {
activeEffectScope = this.parent
}
- stop(fromParent?: boolean) {
+ stop(fromParent?: boolean): void {
if (this._active) {
let i, l
for (i = 0, l = this.effects.length; i < l; i++) {
* @param detached - Can be used to create a "detached" effect scope.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#effectscope}
*/
-export function effectScope(detached?: boolean) {
+export function effectScope(detached?: boolean): EffectScope {
return new EffectScope(detached)
}
*
* @see {@link https://vuejs.org/api/reactivity-advanced.html#getcurrentscope}
*/
-export function getCurrentScope() {
+export function getCurrentScope(): EffectScope | undefined {
return activeEffectScope
}
* @param fn - The callback function to attach to the scope's cleanup.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#onscopedispose}
*/
-export function onScopeDispose(fn: () => void, failSilently = false) {
+export function onScopeDispose(fn: () => void, failSilently = false): void {
if (activeEffectScope) {
activeEffectScope.cleanups.push(fn)
} else if (__DEV__ && !failSilently) {
[ReactiveFlags.RAW]?: any
}
-export const reactiveMap = new WeakMap<Target, any>()
-export const shallowReactiveMap = new WeakMap<Target, any>()
-export const readonlyMap = new WeakMap<Target, any>()
-export const shallowReadonlyMap = new WeakMap<Target, any>()
+export const reactiveMap: WeakMap<Target, any> = new WeakMap<Target, any>()
+export const shallowReactiveMap: WeakMap<Target, any> = new WeakMap<
+ Target,
+ any
+>()
+export const readonlyMap: WeakMap<Target, any> = new WeakMap<Target, any>()
+export const shallowReadonlyMap: WeakMap<Target, any> = new WeakMap<
+ Target,
+ any
+>()
enum TargetType {
INVALID = 0,
declare const ReactiveMarkerSymbol: unique symbol
-export declare class ReactiveMarker {
- private [ReactiveMarkerSymbol]?: void
+export interface ReactiveMarker {
+ [ReactiveMarkerSymbol]?: void
}
export type Reactive<T> = UnwrapNestedRefs<T> &
* @param ref - The ref whose tied effects shall be executed.
* @see {@link https://vuejs.org/api/reactivity-advanced.html#triggerref}
*/
-export function triggerRef(ref: Ref) {
+export function triggerRef(ref: Ref): void {
if (__DEV__) {
;(ref as unknown as RefImpl).dep.trigger({
target: ref,
-export function warn(msg: string, ...args: any[]) {
+export function warn(msg: string, ...args: any[]): void {
console.warn(`[Vue warn] ${msg}`, ...args)
}
export function provide<T, K = InjectionKey<T> | string | number>(
key: K,
value: K extends InjectionKey<infer V> ? V : T,
-) {
+): void {
if (!currentInstance) {
if (__DEV__) {
warn(`provide() can only be used inside setup().`)
}
}
-export const createHook =
+const createHook =
<T extends Function = () => any>(lifecycle: LifecycleHooks) =>
- (hook: T, target: ComponentInternalInstance | null = currentInstance) => {
+ (
+ hook: T,
+ target: ComponentInternalInstance | null = currentInstance,
+ ): void => {
// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
if (
!isInSSRComponentSetup ||
injectHook(lifecycle, (...args: unknown[]) => hook(...args), target)
}
}
+type CreateHook<T = any> = (
+ hook: T,
+ target?: ComponentInternalInstance | null,
+) => void
-export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT)
-export const onMounted = createHook(LifecycleHooks.MOUNTED)
-export const onBeforeUpdate = createHook(LifecycleHooks.BEFORE_UPDATE)
-export const onUpdated = createHook(LifecycleHooks.UPDATED)
-export const onBeforeUnmount = createHook(LifecycleHooks.BEFORE_UNMOUNT)
-export const onUnmounted = createHook(LifecycleHooks.UNMOUNTED)
-export const onServerPrefetch = createHook(LifecycleHooks.SERVER_PREFETCH)
-
-export type DebuggerHook = (e: DebuggerEvent) => void
-export const onRenderTriggered = createHook<DebuggerHook>(
- LifecycleHooks.RENDER_TRIGGERED,
+export const onBeforeMount: CreateHook = createHook(LifecycleHooks.BEFORE_MOUNT)
+export const onMounted: CreateHook = createHook(LifecycleHooks.MOUNTED)
+export const onBeforeUpdate: CreateHook = createHook(
+ LifecycleHooks.BEFORE_UPDATE,
+)
+export const onUpdated: CreateHook = createHook(LifecycleHooks.UPDATED)
+export const onBeforeUnmount: CreateHook = createHook(
+ LifecycleHooks.BEFORE_UNMOUNT,
)
-export const onRenderTracked = createHook<DebuggerHook>(
- LifecycleHooks.RENDER_TRACKED,
+export const onUnmounted: CreateHook = createHook(LifecycleHooks.UNMOUNTED)
+export const onServerPrefetch: CreateHook = createHook(
+ LifecycleHooks.SERVER_PREFETCH,
)
+export type DebuggerHook = (e: DebuggerEvent) => void
+export const onRenderTriggered: CreateHook<DebuggerHook> =
+ createHook<DebuggerHook>(LifecycleHooks.RENDER_TRIGGERED)
+export const onRenderTracked: CreateHook<DebuggerHook> =
+ createHook<DebuggerHook>(LifecycleHooks.RENDER_TRACKED)
+
export type ErrorCapturedHook<TError = unknown> = (
err: TError,
instance: ComponentPublicInstance | null,
export function onErrorCaptured<TError = Error>(
hook: ErrorCapturedHook<TError>,
target: ComponentInternalInstance | null = currentInstance,
-) {
+): void {
injectHook(LifecycleHooks.ERROR_CAPTURED, hook, target)
}
*/
export function defineExpose<
Exposed extends Record<string, any> = Record<string, any>,
->(exposed?: Exposed) {
+>(exposed?: Exposed): void {
if (__DEV__) {
warnRuntimeUsage(`defineExpose`)
}
*/
export function normalizePropsOrEmits(
props: ComponentPropsOptions | EmitsOptions,
-) {
+): ComponentObjectPropsOptions | ObjectEmitsOptions {
return isArray(props)
? props.reduce(
(normalized, p) => ((normalized[p] = null), normalized),
export function mergeModels(
a: ComponentPropsOptions | EmitsOptions,
b: ComponentPropsOptions | EmitsOptions,
-) {
+): ComponentPropsOptions | EmitsOptions {
if (!a || !b) return a || b
if (isArray(a) && isArray(b)) return a.concat(b)
return extend({}, normalizePropsOrEmits(a), normalizePropsOrEmits(b))
* ```
* @internal
*/
-export function withAsyncContext(getAwaitable: () => any) {
+export function withAsyncContext(getAwaitable: () => any): [any, () => void] {
const ctx = getCurrentInstance()!
if (__DEV__ && !ctx) {
warn(
export function watchPostEffect(
effect: WatchEffect,
options?: DebuggerOptions,
-) {
+): WatchStopHandle {
return doWatch(
effect,
null,
export function watchSyncEffect(
effect: WatchEffect,
options?: DebuggerOptions,
-) {
+): WatchStopHandle {
return doWatch(
effect,
null,
export function createPathGetter(ctx: any, path: string) {
const segments = path.split('.')
- return () => {
+ return (): any => {
let cur = ctx
for (let i = 0; i < segments.length && cur; i++) {
cur = cur[segments[i]]
export function traverse(
value: unknown,
- depth = Infinity,
+ depth: number = Infinity,
seen?: Set<unknown>,
-) {
+): unknown {
if (depth <= 0 || !isObject(value) || (value as any)[ReactiveFlags.SKIP]) {
return value
}
// test only
let warningEnabled = true
-export function toggleDeprecationWarning(flag: boolean) {
+export function toggleDeprecationWarning(flag: boolean): void {
warningEnabled = flag
}
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
-) {
+): void {
if (!__DEV__) {
return
}
MODE: 2,
}
-export function configureCompat(config: CompatConfig) {
+export function configureCompat(config: CompatConfig): void {
if (__DEV__) {
validateCompatConfig(config)
}
export function validateCompatConfig(
config: CompatConfig,
instance?: ComponentInternalInstance,
-) {
+): void {
if (seenConfigObjects.has(config)) {
return
}
export function getCompatConfigForKey(
key: DeprecationTypes | 'MODE',
instance: ComponentInternalInstance | null,
-) {
+): CompatConfig[DeprecationTypes | 'MODE'] {
const instanceConfig =
instance && (instance.type as ComponentOptions).compatConfig
if (instanceConfig && key in instanceConfig) {
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
-) {
+): void {
if (!isCompatEnabled(key, instance)) {
throw new Error(`${key} compat has been disabled.`)
} else if (__DEV__) {
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
-) {
+): boolean {
if (__DEV__) {
warnDeprecation(key, instance, ...args)
}
key: DeprecationTypes,
instance: ComponentInternalInstance | null,
...args: any[]
-) {
+): boolean {
const enabled = isCompatEnabled(key, instance)
if (__DEV__ && enabled) {
warnDeprecation(key, instance, ...args)
Component
>()
-export function convertLegacyAsyncComponent(comp: LegacyAsyncComponent) {
+export function convertLegacyAsyncComponent(
+ comp: LegacyAsyncComponent,
+): Component {
if (normalizedAsyncComponentMap.has(comp)) {
return normalizedAsyncComponentMap.get(comp)!
}
},
}
-export function convertLegacyFunctionalComponent(comp: ComponentOptions) {
+export function convertLegacyFunctionalComponent(
+ comp: ComponentOptions,
+): FunctionalComponent {
if (normalizedFunctionalComponentMap.has(comp)) {
return normalizedFunctionalComponentMap.get(comp)!
}
const warnedTypes = new WeakSet()
-export function convertLegacyVModelProps(vnode: VNode) {
+export function convertLegacyVModelProps(vnode: VNode): void {
const { type, shapeFlag, props, dynamicProps } = vnode
const comp = type as ComponentOptions
if (shapeFlag & ShapeFlags.COMPONENT && props && 'modelValue' in props) {
instance: ComponentInternalInstance,
event: string,
args: any[],
-) {
+): void {
if (!isCompatEnabled(DeprecationTypes.COMPONENT_V_MODEL, instance)) {
return
}
import { isPlainObject } from '@vue/shared'
import { DeprecationTypes, warnDeprecation } from './compatConfig'
-export function deepMergeData(to: any, from: any) {
+export function deepMergeData(to: any, from: any): any {
for (const key in from) {
const toVal = to[key]
const fromVal = from[key]
app: App,
context: AppContext,
render: RootRenderFunction<any>,
-) {
+): void {
installFilterMethod(app, context)
installLegacyOptionMergeStrats(app.config)
}
// dev only
-export function installLegacyConfigWarnings(config: AppConfig) {
+export function installLegacyConfigWarnings(config: AppConfig): void {
const legacyConfigOptions: Record<string, DeprecationTypes> = {
silent: DeprecationTypes.CONFIG_SILENT,
devtools: DeprecationTypes.CONFIG_DEVTOOLS,
})
}
-export function installLegacyOptionMergeStrats(config: AppConfig) {
+export function installLegacyOptionMergeStrats(config: AppConfig): void {
config.optionMergeStrategies = new Proxy({} as any, {
get(target, key) {
if (key in target) {
$listeners: Record<string, Function | Function[]>
}
-export function installCompatInstanceProperties(map: PublicPropertiesMap) {
+export function installCompatInstanceProperties(
+ map: PublicPropertiesMap,
+): void {
const set = (target: any, key: any, val: any) => {
target[key] = val
return target[key]
import type { ComponentInternalInstance } from '../component'
import { ErrorCodes, callWithAsyncErrorHandling } from '../errorHandling'
import { DeprecationTypes, assertCompatEnabled } from './compatConfig'
+import type { ComponentPublicInstance } from '../componentPublicInstance'
interface EventRegistry {
[event: string]: Function[] | undefined
instance: ComponentInternalInstance,
event: string | string[],
fn: Function,
-) {
+): ComponentPublicInstance | null {
if (isArray(event)) {
event.forEach(e => on(instance, e, fn))
} else {
instance: ComponentInternalInstance,
event: string,
fn: Function,
-) {
+): ComponentPublicInstance | null {
const wrapped = (...args: any[]) => {
off(instance, event, wrapped)
fn.call(instance.proxy, ...args)
instance: ComponentInternalInstance,
event?: string | string[],
fn?: Function,
-) {
+): ComponentPublicInstance | null {
assertCompatEnabled(DeprecationTypes.INSTANCE_EVENT_EMITTER, instance)
const vm = instance.proxy
// all
instance: ComponentInternalInstance,
event: string,
args: any[],
-) {
+): ComponentPublicInstance | null {
const cbs = getRegistry(instance)[event]
if (cbs) {
callWithAsyncErrorHandling(
import type { ComponentInternalInstance } from '../component'
import { DeprecationTypes, assertCompatEnabled } from './compatConfig'
-export function getCompatListeners(instance: ComponentInternalInstance) {
+export function getCompatListeners(
+ instance: ComponentInternalInstance,
+): Record<string, Function | Function[]> {
assertCompatEnabled(DeprecationTypes.INSTANCE_LISTENERS, instance)
const listeners: Record<string, Function | Function[]> = {}
instance: ComponentInternalInstance,
rawProps: Data,
propKey: string,
-) {
+): object {
return new Proxy(
{},
{
} from './compatConfig'
import { compatModelEventPrefix } from './componentVModel'
-export function convertLegacyRenderFn(instance: ComponentInternalInstance) {
+export function convertLegacyRenderFn(
+ instance: ComponentInternalInstance,
+): void {
const Component = instance.type as ComponentOptions
const render = Component.render as InternalRenderFunction | undefined
return vnode
}
-export function defineLegacyVNodeProperties(vnode: VNode) {
+export function defineLegacyVNodeProperties(vnode: VNode): void {
/* istanbul ignore if */
if (
isCompatEnabled(
isReservedProp,
normalizeClass,
} from '@vue/shared'
-import type { ComponentInternalInstance } from '../component'
+import type { ComponentInternalInstance, Data } from '../component'
import type { Slot } from '../componentSlots'
import { createSlots } from '../helpers/createSlots'
import { renderSlot } from '../helpers/renderSlot'
value: any,
_asProp: boolean,
isSync?: boolean,
-) {
+): any {
if (value && isObject(value)) {
if (isArray(value)) {
value = toObject(value)
return data
}
-export function legacyBindObjectListeners(props: any, listeners: any) {
+export function legacyBindObjectListeners(props: any, listeners: any): Data {
return mergeProps(props, toHandlers(listeners))
}
fallback?: VNode[],
props?: any,
bindObject?: any,
-) {
+): VNode {
if (bindObject) {
props = mergeProps(props, bindObject)
}
raw?: Record<string, Slot>,
// the following are added in 2.6
hasDynamicKeys?: boolean,
-) {
+): ReturnType<typeof createSlots> {
// v2 default slot doesn't have name
return createSlots(
raw || ({ $stable: !hasDynamicKeys } as any),
export function legacyRenderStatic(
instance: ComponentInternalInstance,
index: number,
-) {
+): any {
let cache = staticCacheMap.get(instance)
if (!cache) {
staticCacheMap.set(instance, (cache = []))
builtInKeyCode?: number | number[],
eventKeyName?: string,
builtInKeyName?: string | string[],
-) {
+): boolean | undefined {
const config = instance.appContext.config as any
const configKeyCodes = config.keyCodes || {}
const mappedKeyCode = configKeyCodes[key] || builtInKeyCode
}
}
-export function legacyMarkOnce(tree: VNode) {
+export function legacyMarkOnce(tree: VNode): VNode {
return tree
}
-export function legacyBindDynamicKeys(props: any, values: any[]) {
+export function legacyBindDynamicKeys(props: any, values: any[]): any {
for (let i = 0; i < values.length; i += 2) {
const key = values[i]
if (typeof key === 'string' && key) {
return props
}
-export function legacyPrependModifier(value: any, symbol: string) {
+export function legacyPrependModifier(value: any, symbol: string): any {
return typeof value === 'string' ? symbol + value : value
}
vnode: VNode,
parent: ComponentInternalInstance | null,
suspense: SuspenseBoundary | null,
-) {
+): ComponentInternalInstance {
const type = vnode.type as ConcreteComponent
// inherit parent app context - or - if root, adopt from root vnode
const appContext =
const prev = currentInstance
internalSetCurrentInstance(instance)
instance.scope.on()
- return () => {
+ return (): void => {
instance.scope.off()
internalSetCurrentInstance(prev)
}
}
-export const unsetCurrentInstance = () => {
+export const unsetCurrentInstance = (): void => {
currentInstance && currentInstance.scope.off()
internalSetCurrentInstance(null)
}
export function validateComponentName(
name: string,
{ isNativeTag }: AppConfig,
-) {
+): void {
if (isBuiltInTag(name) || isNativeTag(name)) {
warn(
'Do not use built-in or reserved HTML elements as component id: ' + name,
}
}
-export function isStatefulComponent(instance: ComponentInternalInstance) {
+export function isStatefulComponent(
+ instance: ComponentInternalInstance,
+): number {
return instance.vnode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT
}
instance: ComponentInternalInstance,
isSSR = false,
optimized = false,
-) {
+): Promise<void> | undefined {
isSSR && setInSSRSetupState(isSSR)
const { props, children } = instance.vnode
instance: ComponentInternalInstance,
setupResult: unknown,
isSSR: boolean,
-) {
+): void {
if (isFunction(setupResult)) {
// setup returned an inline render function
if (__SSR__ && (instance.type as ComponentOptions).__ssrInlineRender) {
* For runtime-dom to register the compiler.
* Note the exported method uses any to avoid d.ts relying on the compiler types.
*/
-export function registerRuntimeCompiler(_compile: any) {
+export function registerRuntimeCompiler(_compile: any): void {
compile = _compile
installWithProxy = i => {
if (i.render!._rc) {
}
// dev only
-export const isRuntimeOnly = () => !compile
+export const isRuntimeOnly = (): boolean => !compile
export function finishComponentSetup(
instance: ComponentInternalInstance,
isSSR: boolean,
skipOptions?: boolean,
-) {
+): void {
const Component = instance.type as ComponentOptions
if (__COMPAT__) {
export function getComponentPublicInstance(
instance: ComponentInternalInstance,
-) {
+): ComponentPublicInstance | ComponentInternalInstance['exposed'] | null {
if (instance.exposed) {
return (
instance.exposeProxy ||
} from './compat/componentVModel'
import type { ComponentTypeEmits } from './apiSetupHelpers'
import { getModelModifiers } from './helpers/useModel'
+import type { ComponentPublicInstance } from './componentPublicInstance'
export type ObjectEmitsOptions = Record<
string,
instance: ComponentInternalInstance,
event: string,
...rawArgs: any[]
-) {
+): ComponentPublicInstance | null | undefined {
if (instance.isUnmounted) return
const props = instance.vnode.props || EMPTY_OBJ
export let shouldCacheAccess = true
-export function applyOptions(instance: ComponentInternalInstance) {
+export function applyOptions(instance: ComponentInternalInstance): void {
const options = resolveMergedOptions(instance)
const publicThis = instance.proxy! as any
const ctx = instance.ctx
injectOptions: ComponentInjectOptions,
ctx: any,
checkDuplicateProperties = NOOP as any,
-) {
+): void {
if (isArray(injectOptions)) {
injectOptions = normalizeInject(injectOptions)!
}
ctx: Data,
publicThis: ComponentPublicInstance,
key: string,
-) {
+): void {
const getter = key.includes('.')
? createPathGetter(publicThis, key)
: () => (publicThis as any)[key]
from: any,
strats: Record<string, OptionMergeFunction>,
asMixin = false,
-) {
+): any {
if (__COMPAT__ && isFunction(from)) {
from = from.options
}
rawProps: Data | null,
isStateful: number, // result of bitwise flag comparison
isSSR = false,
-) {
+): void {
const props: Data = {}
const attrs: Data = createInternalObject()
rawProps: Data | null,
rawPrevProps: Data | null,
optimized: boolean,
-) {
+): void {
const {
props,
attrs,
_: ComponentInternalInstance
}
-export const isReservedPrefix = (key: string) => key === '_' || key === '$'
+export const isReservedPrefix = (key: string): key is '_' | '$' =>
+ key === '_' || key === '$'
const hasSetupBinding = (state: Data, key: string) =>
state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key)
}
}
-export const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend(
- {},
- PublicInstanceProxyHandlers,
- {
+export const RuntimeCompiledPublicInstanceProxyHandlers: ProxyHandler<any> =
+ /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
get(target: ComponentRenderContext, key: string) {
// fast path for unscopables when using `with` block
if ((key as any) === Symbol.unscopables) {
}
return has
},
- },
-)
+ })
// dev only
// In dev mode, the proxy target exposes the same properties as seen on `this`
// dev only
export function exposePropsOnRenderContext(
instance: ComponentInternalInstance,
-) {
+): void {
const {
ctx,
propsOptions: [propsOptions],
// dev only
export function exposeSetupStateOnRenderContext(
instance: ComponentInternalInstance,
-) {
+): void {
const { ctx, setupState } = instance
Object.keys(toRaw(setupState)).forEach(key => {
if (!setupState.__isScriptSetup) {
* Set scope id when creating hoisted vnodes.
* @private compiler helper
*/
-export function pushScopeId(id: string | null) {
+export function pushScopeId(id: string | null): void {
currentScopeId = id
}
* API for backwards compat w/ code generated by compilers.
* @private
*/
-export function popScopeId() {
+export function popScopeId(): void {
currentScopeId = null
}
* Only for backwards compat
* @private
*/
-export const withScopeId = (_id: string) => withCtx
+export const withScopeId = (_id: string): typeof withCtx => withCtx
export type ContextualRenderFn = {
(...args: any[]): any
fn: Function,
ctx: ComponentInternalInstance | null = currentRenderingInstance,
isNonScopedSlot?: boolean, // __COMPAT__ only
-) {
+): Function {
if (!ctx) return fn
// already normalized
*/
let accessedAttrs: boolean = false
-export function markAttrsAccessed() {
+export function markAttrsAccessed(): void {
accessedAttrs = true
}
export function updateHOCHostEl(
{ vnode, parent }: ComponentInternalInstance,
el: typeof vnode.el, // HostNode
-) {
+): void {
while (parent) {
const root = parent.subTree
if (root.suspense && root.suspense.activeBranch === vnode) {
instance: ComponentInternalInstance,
children: VNodeNormalizedChildren,
optimized: boolean,
-) => {
+): void => {
const slots = (instance.slots = createInternalObject())
if (instance.vnode.shapeFlag & ShapeFlags.SLOTS_CHILDREN) {
const type = (children as RawSlots)._
instance: ComponentInternalInstance,
children: VNodeNormalizedChildren,
optimized: boolean,
-) => {
+): void => {
const { vnode, slots } = instance
let needDeletionCheck = true
let deletionComparisonTarget = EMPTY_OBJ
type Hook<T = () => void> = T | T[]
-const leaveCbKey = Symbol('_leaveCb')
-const enterCbKey = Symbol('_enterCb')
+const leaveCbKey: unique symbol = Symbol('_leaveCb')
+const enterCbKey: unique symbol = Symbol('_enterCb')
export interface BaseTransitionProps<HostElement = RendererElement> {
mode?: 'in-out' | 'out-in' | 'default'
const TransitionHookValidator = [Function, Array]
-export const BaseTransitionPropsValidators = {
+export const BaseTransitionPropsValidators: Record<string, any> = {
mode: String,
appear: Boolean,
persisted: Boolean,
}
}
-export function setTransitionHooks(vnode: VNode, hooks: TransitionHooks) {
+export function setTransitionHooks(vnode: VNode, hooks: TransitionHooks): void {
if (vnode.shapeFlag & ShapeFlags.COMPONENT && vnode.component) {
setTransitionHooks(vnode.component.subTree, hooks)
} else if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) {
export function onActivated(
hook: Function,
target?: ComponentInternalInstance | null,
-) {
+): void {
registerKeepAliveHook(hook, LifecycleHooks.ACTIVATED, target)
}
export function onDeactivated(
hook: Function,
target?: ComponentInternalInstance | null,
-) {
+): void {
registerKeepAliveHook(hook, LifecycleHooks.DEACTIVATED, target)
}
/**
* For testing only
*/
-export const resetSuspenseId = () => (suspenseId = 0)
+export const resetSuspenseId = (): number => (suspenseId = 0)
// Suspense exposes a component-like API, and is treated like a component
// in the compiler, but internally it's a special built-in type that hooks
optimized: boolean,
// platform-specific impl passed from renderer
rendererInternals: RendererInternals,
- ) {
+ ): void {
if (n1 == null) {
mountSuspense(
n2,
)
}
},
- hydrate: hydrateSuspense,
- normalize: normalizeSuspenseChildren,
+ hydrate: hydrateSuspense as typeof hydrateSuspense,
+ normalize: normalizeSuspenseChildren as typeof normalizeSuspenseChildren,
}
// Force-casted public typing for h and TSX props inference
return result
}
-function normalizeSuspenseChildren(vnode: VNode) {
+function normalizeSuspenseChildren(vnode: VNode): void {
const { shapeFlag, children } = vnode
const isSlotChildren = shapeFlag & ShapeFlags.SLOTS_CHILDREN
vnode.ssContent = normalizeSuspenseSlot(
defer?: boolean
}
-export const TeleportEndKey = Symbol('_vte')
+export const TeleportEndKey: unique symbol = Symbol('_vte')
export const isTeleport = (type: any): boolean => type.__isTeleport
slotScopeIds: string[] | null,
optimized: boolean,
internals: RendererInternals,
- ) {
+ ): void {
const {
mc: mountChildren,
pc: patchChildren,
parentSuspense: SuspenseBoundary | null,
{ um: unmount, o: { remove: hostRemove } }: RendererInternals,
doRemove: boolean,
- ) {
+ ): void {
const {
shapeFlag,
children,
}
},
- move: moveTeleport,
- hydrate: hydrateTeleport,
+ move: moveTeleport as typeof moveTeleport,
+ hydrate: hydrateTeleport as typeof hydrateTeleport,
}
export enum TeleportMoveTypes {
parentAnchor: RendererNode | null,
{ o: { insert }, m: move }: RendererInternals,
moveType: TeleportMoveTypes = TeleportMoveTypes.REORDER,
-) {
+): void {
// move target anchor if this is a target change.
if (moveType === TeleportMoveTypes.TARGET_CHANGE) {
insert(vnode.targetAnchor!, container, parentAnchor)
import type { ComponentInternalInstance, ComponentOptions } from './component'
import type { ComponentPublicInstance } from './componentPublicInstance'
-export function initCustomFormatter() {
+export function initCustomFormatter(): void {
/* eslint-disable no-restricted-globals */
if (!__DEV__ || typeof window === 'undefined') {
return
}
}
-export function setDevtoolsHook(hook: DevtoolsHook, target: any) {
+export function setDevtoolsHook(hook: DevtoolsHook, target: any): void {
devtools = hook
if (devtools) {
devtools.enabled = true
}
}
-export function devtoolsInitApp(app: App, version: string) {
+export function devtoolsInitApp(app: App, version: string): void {
emit(DevtoolsHooks.APP_INIT, app, version, {
Fragment,
Text,
})
}
-export function devtoolsUnmountApp(app: App) {
+export function devtoolsUnmountApp(app: App): void {
emit(DevtoolsHooks.APP_UNMOUNT, app)
}
-export const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook(
- DevtoolsHooks.COMPONENT_ADDED,
-)
+export const devtoolsComponentAdded: DevtoolsComponentHook =
+ /*#__PURE__*/ createDevtoolsComponentHook(DevtoolsHooks.COMPONENT_ADDED)
-export const devtoolsComponentUpdated =
+export const devtoolsComponentUpdated: DevtoolsComponentHook =
/*#__PURE__*/ createDevtoolsComponentHook(DevtoolsHooks.COMPONENT_UPDATED)
const _devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook(
export const devtoolsComponentRemoved = (
component: ComponentInternalInstance,
-) => {
+): void => {
if (
devtools &&
typeof devtools.cleanupBuffer === 'function' &&
}
}
+type DevtoolsComponentHook = (component: ComponentInternalInstance) => void
+
/*! #__NO_SIDE_EFFECTS__ */
-function createDevtoolsComponentHook(hook: DevtoolsHooks) {
+function createDevtoolsComponentHook(
+ hook: DevtoolsHooks,
+): DevtoolsComponentHook {
return (component: ComponentInternalInstance) => {
emit(
hook,
}
}
-export const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook(
- DevtoolsHooks.PERFORMANCE_START,
-)
+export const devtoolsPerfStart: DevtoolsPerformanceHook =
+ /*#__PURE__*/ createDevtoolsPerformanceHook(DevtoolsHooks.PERFORMANCE_START)
-export const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook(
- DevtoolsHooks.PERFORMANCE_END,
-)
+export const devtoolsPerfEnd: DevtoolsPerformanceHook =
+ /*#__PURE__*/ createDevtoolsPerformanceHook(DevtoolsHooks.PERFORMANCE_END)
-function createDevtoolsPerformanceHook(hook: DevtoolsHooks) {
+type DevtoolsPerformanceHook = (
+ component: ComponentInternalInstance,
+ type: string,
+ time: number,
+) => void
+function createDevtoolsPerformanceHook(
+ hook: DevtoolsHooks,
+): DevtoolsPerformanceHook {
return (component: ComponentInternalInstance, type: string, time: number) => {
emit(hook, component.appContext.app, component.uid, component, type, time)
}
component: ComponentInternalInstance,
event: string,
params: any[],
-) {
+): void {
emit(
DevtoolsHooks.COMPONENT_EMIT,
component.appContext.app,
export type DirectiveModifiers<K extends string = string> = Record<K, boolean>
-export function validateDirectiveName(name: string) {
+export function validateDirectiveName(name: string): void {
if (isBuiltInDirective(name)) {
warn('Do not use built-in directive ids as custom directive id: ' + name)
}
prevVNode: VNode | null,
instance: ComponentInternalInstance | null,
name: keyof ObjectDirective,
-) {
+): void {
const bindings = vnode.dirs!
const oldBindings = prevVNode && prevVNode.dirs!
for (let i = 0; i < bindings.length; i++) {
instance: ComponentInternalInstance | null | undefined,
type: ErrorTypes,
args?: unknown[],
-) {
+): any {
try {
return args ? fn(...args) : fn()
} catch (err) {
instance: ComponentInternalInstance | null | undefined,
type: ErrorTypes,
throwInDev = true,
-) {
+): void {
const contextVNode = instance ? instance.vnode : null
const { errorHandler, throwUnhandledErrorInProduction } =
(instance && instance.appContext.config) || EMPTY_OBJ
*
* istanbul-ignore-next
*/
-export function initFeatureFlags() {
+export function initFeatureFlags(): void {
const needWarn = []
if (typeof __FEATURE_OPTIONS_API__ !== 'boolean') {
return rendered
}
-export function ensureValidVNode(vnodes: VNodeArrayChildren) {
+export function ensureValidVNode(
+ vnodes: VNodeArrayChildren,
+): VNodeArrayChildren | null {
return vnodes.some(child => {
if (!isVNode(child)) return true
if (child.type === Comment) return false
return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name
}
-export const NULL_DYNAMIC_COMPONENT = Symbol.for('v-ndc')
+export const NULL_DYNAMIC_COMPONENT: unique symbol = Symbol.for('v-ndc')
/**
* @private
} from '../component'
import { warn } from '../warning'
-export function useId() {
+export function useId(): string | undefined {
const i = getCurrentInstance()
if (i) {
return (i.appContext.config.idPrefix || 'v') + ':' + i.ids[0] + i.ids[1]++
* - components with async setup()
* - components with serverPrefetch
*/
-export function markAsyncBoundary(instance: ComponentInternalInstance) {
+export function markAsyncBoundary(instance: ComponentInternalInstance): void {
instance.ids = [instance.ids[0] + instance.ids[2]++ + '-', 0, 0]
}
import { inject } from '../apiInject'
import { warn } from '../warning'
-export const ssrContextKey = Symbol.for('v-scx')
+export const ssrContextKey: unique symbol = Symbol.for('v-scx')
-export const useSSRContext = <T = Record<string, any>>() => {
+export const useSSRContext = <T = Record<string, any>>(): T | undefined => {
if (!__GLOBAL__) {
const ctx = inject<T>(ssrContextKey)
if (!ctx) {
render: () => VNode<any, any>,
cache: any[],
index: number,
-) {
+): VNode<any, any> {
const cached = cache[index] as VNode | undefined
if (cached && isMemoSame(cached, memo)) {
return cached
return (cache[index] = ret)
}
-export function isMemoSame(cached: VNode, memo: any[]) {
+export function isMemoSame(cached: VNode, memo: any[]): boolean {
const prev: any[] = cached.memo!
if (prev.length != memo.length) {
return false
export let isHmrUpdating = false
-export const hmrDirtyComponents = new Map<
+export const hmrDirtyComponents: Map<
ConcreteComponent,
Set<ComponentInternalInstance>
->()
+> = new Map<ConcreteComponent, Set<ComponentInternalInstance>>()
export interface HMRRuntime {
createRecord: typeof createRecord
}
> = new Map()
-export function registerHMR(instance: ComponentInternalInstance) {
+export function registerHMR(instance: ComponentInternalInstance): void {
const id = instance.type.__hmrId!
let record = map.get(id)
if (!record) {
record.instances.add(instance)
}
-export function unregisterHMR(instance: ComponentInternalInstance) {
+export function unregisterHMR(instance: ComponentInternalInstance): void {
map.get(instance.type.__hmrId!)!.instances.delete(instance)
}
return isClassComponent(component) ? component.__vccOpts : component
}
-function rerender(id: string, newRender?: Function) {
+function rerender(id: string, newRender?: Function): void {
const record = map.get(id)
if (!record) {
return
})
}
-function reload(id: string, newComp: HMRComponent) {
+function reload(id: string, newComp: HMRComponent): void {
const record = map.get(id)
if (!record) return
// passed in via arguments.
export function createHydrationFunctions(
rendererInternals: RendererInternals<Node, Element>,
-) {
+): [
+ RootHydrateFunction,
+ (
+ node: Node,
+ vnode: VNode,
+ parentComponent: ComponentInternalInstance | null,
+ parentSuspense: SuspenseBoundary | null,
+ slotScopeIds: string[] | null,
+ optimized?: boolean,
+ ) => Node | null,
+] {
const {
mt: mountComponent,
p: patch,
)
}
- return [hydrate, hydrateNode] as const
+ return [hydrate, hydrateNode]
}
/**
return teardown
}
-export function forEachElement(node: Node, cb: (el: Element) => void) {
+export function forEachElement(node: Node, cb: (el: Element) => void): void {
// fragment
if (isComment(node) && node.data === '[') {
let depth = 1
// Core API ------------------------------------------------------------------
-export const version = __VERSION__
+export const version: string = __VERSION__
export {
// core
reactive,
import { isVNode, normalizeVNode } from './vnode'
import { ensureValidVNode } from './helpers/renderSlot'
-const _ssrUtils = {
+const _ssrUtils: {
+ createComponentInstance: typeof createComponentInstance
+ setupComponent: typeof setupComponent
+ renderComponentRoot: typeof renderComponentRoot
+ setCurrentRenderingInstance: typeof setCurrentRenderingInstance
+ isVNode: typeof isVNode
+ normalizeVNode: typeof normalizeVNode
+ getComponentPublicInstance: typeof getComponentPublicInstance
+ ensureValidVNode: typeof ensureValidVNode
+} = {
createComponentInstance,
setupComponent,
renderComponentRoot,
/**
* @internal only exposed in compat builds
*/
-export const resolveFilter = __COMPAT__ ? _resolveFilter : null
-
-const _compatUtils = {
+export const resolveFilter: typeof _resolveFilter | null = __COMPAT__
+ ? _resolveFilter
+ : null
+
+const _compatUtils: {
+ warnDeprecation: typeof warnDeprecation
+ createCompatVue: typeof createCompatVue
+ isCompatEnabled: typeof isCompatEnabled
+ checkCompatEnabled: typeof checkCompatEnabled
+ softAssertCompatEnabled: typeof softAssertCompatEnabled
+} = {
warnDeprecation,
createCompatVue,
isCompatEnabled,
*/
const internalObjectProto = {}
-export const createInternalObject = () => Object.create(internalObjectProto)
+export const createInternalObject = (): any =>
+ Object.create(internalObjectProto)
-export const isInternalObject = (obj: object) =>
+export const isInternalObject = (obj: object): boolean =>
Object.getPrototypeOf(obj) === internalObjectProto
export function startMeasure(
instance: ComponentInternalInstance,
type: string,
-) {
+): void {
if (instance.appContext.config.performance && isSupported()) {
perf.mark(`vue-${type}-${instance.uid}`)
}
}
}
-export function endMeasure(instance: ComponentInternalInstance, type: string) {
+export function endMeasure(
+ instance: ComponentInternalInstance,
+ type: string,
+): void {
if (instance.appContext.config.performance && isSupported()) {
const startTag = `vue-${type}-${instance.uid}`
const endTag = startTag + `:end`
import {
type SchedulerJob,
SchedulerJobFlags,
+ type SchedulerJobs,
flushPostFlushCbs,
flushPreFlushCbs,
invalidateJob,
REORDER,
}
-export const queuePostRenderEffect = __FEATURE_SUSPENSE__
+export const queuePostRenderEffect: (
+ fn: SchedulerJobs,
+ suspense: SuspenseBoundary | null,
+) => void = __FEATURE_SUSPENSE__
? __TEST__
? // vitest can't seem to handle eager circular dependency
(fn: Function | Function[], suspense: SuspenseBoundary | null) =>
export function createRenderer<
HostNode = RendererNode,
HostElement = RendererElement,
->(options: RendererOptions<HostNode, HostElement>) {
+>(options: RendererOptions<HostNode, HostElement>): Renderer<HostElement> {
return baseCreateRenderer<HostNode, HostElement>(options)
}
// tree-shakable.
export function createHydrationRenderer(
options: RendererOptions<Node, Element>,
-) {
+): HydrationRenderer {
return baseCreateRenderer(options, createHydrationFunctions)
}
export function needTransition(
parentSuspense: SuspenseBoundary | null,
transition: TransitionHooks | null,
-) {
+): boolean | null {
return (
(!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
transition &&
* the children will always be moved. Therefore, in order to ensure correct move
* position, el should be inherited from previous nodes.
*/
-export function traverseStaticChildren(n1: VNode, n2: VNode, shallow = false) {
+export function traverseStaticChildren(
+ n1: VNode,
+ n2: VNode,
+ shallow = false,
+): void {
const ch1 = n1.children
const ch2 = n2.children
if (isArray(ch1) && isArray(ch2)) {
}
}
-export function invalidateMount(hooks: LifecycleHook) {
+export function invalidateMount(hooks: LifecycleHook): void {
if (hooks) {
for (let i = 0; i < hooks.length; i++)
hooks[i].flags! |= SchedulerJobFlags.DISPOSED
parentSuspense: SuspenseBoundary | null,
vnode: VNode,
isUnmount = false,
-) {
+): void {
if (isArray(rawRef)) {
rawRef.forEach((r, i) =>
setRef(
return start
}
-export function queueJob(job: SchedulerJob) {
+export function queueJob(job: SchedulerJob): void {
if (!(job.flags! & SchedulerJobFlags.QUEUED)) {
if (job.id == null) {
queue.push(job)
}
}
-export function invalidateJob(job: SchedulerJob) {
+export function invalidateJob(job: SchedulerJob): void {
const i = queue.indexOf(job)
if (i > flushIndex) {
queue.splice(i, 1)
}
}
-export function queuePostFlushCb(cb: SchedulerJobs) {
+export function queuePostFlushCb(cb: SchedulerJobs): void {
if (!isArray(cb)) {
if (activePostFlushCbs && cb.id === -1) {
activePostFlushCbs.splice(postFlushIndex + 1, 0, cb)
instance?: ComponentInternalInstance,
seen?: CountMap,
// if currently flushing, skip the current job itself
- i = isFlushing ? flushIndex + 1 : 0,
-) {
+ i: number = isFlushing ? flushIndex + 1 : 0,
+): void {
if (__DEV__) {
seen = seen || new Map()
}
}
}
-export function flushPostFlushCbs(seen?: CountMap) {
+export function flushPostFlushCbs(seen?: CountMap): void {
if (pendingPostFlushCbs.length) {
const deduped = [...new Set(pendingPostFlushCbs)].sort(
(a, b) => getId(a) - getId(b),
$props: VNodeProps
}
}
-export const Text = Symbol.for('v-txt')
-export const Comment = Symbol.for('v-cmt')
-export const Static = Symbol.for('v-stc')
+export const Text: unique symbol = Symbol.for('v-txt')
+export const Comment: unique symbol = Symbol.for('v-cmt')
+export const Static: unique symbol = Symbol.for('v-stc')
export type VNodeTypes =
| string
*
* @private
*/
-export function openBlock(disableTracking = false) {
+export function openBlock(disableTracking = false): void {
blockStack.push((currentBlock = disableTracking ? null : []))
}
-export function closeBlock() {
+export function closeBlock(): void {
blockStack.pop()
currentBlock = blockStack[blockStack.length - 1] || null
}
*
* @private
*/
-export function setBlockTracking(value: number) {
+export function setBlockTracking(value: number): void {
isBlockTreeEnabled += value
if (value < 0 && currentBlock) {
// mark current block so it doesn't take fast path and skip possible
patchFlag?: number,
dynamicProps?: string[],
shapeFlag?: number,
-) {
+): VNode {
return setupBlock(
createBaseVNode(
type,
* It is *internal* but needs to be exposed for test-utils to pick up proper
* typings
*/
-export function transformVNodeArgs(transformer?: typeof vnodeArgsTransformer) {
+export function transformVNodeArgs(
+ transformer?: typeof vnodeArgsTransformer,
+): void {
vnodeArgsTransformer = transformer
}
children: unknown = null,
patchFlag = 0,
dynamicProps: string[] | null = null,
- shapeFlag = type === Fragment ? 0 : ShapeFlags.ELEMENT,
+ shapeFlag: number = type === Fragment ? 0 : ShapeFlags.ELEMENT,
isBlockNode = false,
needFullChildrenNormalization = false,
-) {
+): VNode {
const vnode = {
__v_isVNode: true,
__v_skip: true,
)
}
-export function guardReactiveProps(props: (Data & VNodeProps) | null) {
+export function guardReactiveProps(
+ props: (Data & VNodeProps) | null,
+): (Data & VNodeProps) | null {
if (!props) return null
return isProxy(props) || isInternalObject(props) ? extend({}, props) : props
}
: cloneVNode(child)
}
-export function normalizeChildren(vnode: VNode, children: unknown) {
+export function normalizeChildren(vnode: VNode, children: unknown): void {
let type = 0
const { shapeFlag } = vnode
if (children == null) {
vnode.shapeFlag |= type
}
-export function mergeProps(...args: (Data & VNodeProps)[]) {
+export function mergeProps(...args: (Data & VNodeProps)[]): Data {
const ret: Data = {}
for (let i = 0; i < args.length; i++) {
const toMerge = args[i]
instance: ComponentInternalInstance | null,
vnode: VNode,
prevVNode: VNode | null = null,
-) {
+): void {
callWithAsyncErrorHandling(hook, instance, ErrorCodes.VNODE_HOOK, [
vnode,
prevVNode,
type ComponentTraceStack = TraceEntry[]
-export function pushWarningContext(vnode: VNode) {
+export function pushWarningContext(vnode: VNode): void {
stack.push(vnode)
}
-export function popWarningContext() {
+export function popWarningContext(): void {
stack.pop()
}
let isWarning = false
-export function warn(msg: string, ...args: any[]) {
+export function warn(msg: string, ...args: any[]): void {
if (isWarning) return
isWarning = true
/**
* @internal
*/
-export function assertNumber(val: unknown, type: string) {
+export function assertNumber(val: unknown, type: string): void {
if (!__DEV__) return
if (val === undefined) {
return
/**
* @internal
*/
- _nonce = this._def.nonce
+ _nonce: string | undefined = this._def.nonce
private _connected = false
private _resolved = false
}
}
- connectedCallback() {
+ connectedCallback(): void {
if (!this.shadowRoot) {
this._parseSlots()
}
}
}
- disconnectedCallback() {
+ disconnectedCallback(): void {
this._connected = false
nextTick(() => {
if (!this._connected) {
}
}
- protected _setAttr(key: string) {
+ protected _setAttr(key: string): void {
if (key.startsWith('data-v-')) return
const has = this.hasAttribute(key)
let value = has ? this.getAttribute(key) : REMOVAL
/**
* @internal
*/
- protected _getProp(key: string) {
+ protected _getProp(key: string): any {
return this._props[key]
}
/**
* @internal
*/
- _setProp(key: string, val: any, shouldReflect = true, shouldUpdate = false) {
+ _setProp(
+ key: string,
+ val: any,
+ shouldReflect = true,
+ shouldUpdate = false,
+ ): void {
if (val !== this._props[key]) {
if (val === REMOVAL) {
delete this._props[key]
/**
* @internal
*/
- _injectChildStyle(comp: ConcreteComponent & CustomElementOptions) {
+ _injectChildStyle(comp: ConcreteComponent & CustomElementOptions): void {
this._applyStyles(comp.styles, comp)
}
leaveToClass?: string
}
-export const vtcKey = Symbol('_vtc')
+export const vtcKey: unique symbol = Symbol('_vtc')
export interface ElementWithTransition extends HTMLElement {
// _vtc = Vue Transition Classes.
leaveToClass: String,
}
-export const TransitionPropsValidators = (Transition.props =
+export const TransitionPropsValidators: any = (Transition.props =
/*#__PURE__*/ extend(
{},
BaseTransitionPropsValidators as any,
return res
}
-export function addTransitionClass(el: Element, cls: string) {
+export function addTransitionClass(el: Element, cls: string): void {
cls.split(/\s+/).forEach(c => c && el.classList.add(c))
;(
(el as ElementWithTransition)[vtcKey] ||
).add(cls)
}
-export function removeTransitionClass(el: Element, cls: string) {
+export function removeTransitionClass(el: Element, cls: string): void {
cls.split(/\s+/).forEach(c => c && el.classList.remove(c))
const _vtc = (el as ElementWithTransition)[vtcKey]
if (_vtc) {
}
// synchronously force layout to put elements into a certain state
-export function forceReflow() {
+export function forceReflow(): number {
return document.body.offsetHeight
}
}
}
-const assignKey = Symbol('_assign')
+const assignKey: unique symbol = Symbol('_assign')
type ModelDirective<T, Modifiers extends string = string> = ObjectDirective<
T & { [assignKey]: AssignerFn; _assigning?: boolean },
// SSR vnode transforms, only used when user includes client-oriented render
// function in SSR
-export function initVModelForSSR() {
+export function initVModelForSSR(): void {
vModelText.getSSRProps = ({ value }) => ({ value })
vModelRadio.getSSRProps = ({ value }, vnode) => {
export type VOnModifiers = SystemModifiers | ModifierGuards | CompatModifiers
type KeyedEvent = KeyboardEvent | MouseEvent | TouchEvent
-const modifierGuards = {
+type ModifierGuards =
+ | 'shift'
+ | 'ctrl'
+ | 'alt'
+ | 'meta'
+ | 'left'
+ | 'right'
+ | 'stop'
+ | 'prevent'
+ | 'self'
+ | 'middle'
+ | 'exact'
+const modifierGuards: Record<
+ ModifierGuards,
+ | ((e: Event) => void | boolean)
+ | ((e: Event, modifiers: string[]) => void | boolean)
+> = {
stop: (e: Event) => e.stopPropagation(),
prevent: (e: Event) => e.preventDefault(),
self: (e: Event) => e.target !== e.currentTarget,
right: (e: Event) => 'button' in e && (e as MouseEvent).button !== 2,
exact: (e, modifiers) =>
systemModifiers.some(m => (e as any)[`${m}Key`] && !modifiers.includes(m)),
-} satisfies Record<
- string,
- | ((e: Event) => void | boolean)
- | ((e: Event, modifiers: string[]) => void | boolean)
->
-
-type ModifierGuards = keyof typeof modifierGuards
+}
/**
* @private
>(
fn: T & { _withMods?: { [key: string]: T } },
modifiers: VOnModifiers[],
-) => {
+): T => {
const cache = fn._withMods || (fn._withMods = {})
const cacheKey = modifiers.join('.')
return (
// Kept for 2.x compat.
// Note: IE11 compat for `spacebar` and `del` is removed for now.
-const keyNames = {
+const keyNames: Record<
+ 'esc' | 'space' | 'up' | 'left' | 'right' | 'down' | 'delete',
+ string
+> = {
esc: 'escape',
space: ' ',
up: 'arrow-up',
right: 'arrow-right',
down: 'arrow-down',
delete: 'backspace',
-} satisfies Record<string, string | string[]>
+}
/**
* @private
export const withKeys = <T extends (event: KeyboardEvent) => any>(
fn: T & { _withKeys?: { [k: string]: T } },
modifiers: string[],
-) => {
+): T => {
let globalKeyCodes: LegacyConfig['keyCodes']
let instance: ComponentInternalInstance | null = null
if (__COMPAT__) {
import type { ObjectDirective } from '@vue/runtime-core'
-export const vShowOriginalDisplay = Symbol('_vod')
-export const vShowHidden = Symbol('_vsh')
+export const vShowOriginalDisplay: unique symbol = Symbol('_vod')
+export const vShowHidden: unique symbol = Symbol('_vsh')
export interface VShowElement extends HTMLElement {
// _vod = vue original display
// SSR vnode transforms, only used when user includes client-oriented render
// function in SSR
-export function initVShowForSSR() {
+export function initVShowForSSR(): void {
vShow.getSSRProps = ({ value }) => {
if (!value) {
return { style: { display: 'none' } }
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared'
-export const CSS_VAR_TEXT = Symbol(__DEV__ ? 'CSS_VAR_TEXT' : '')
+export const CSS_VAR_TEXT: unique symbol = Symbol(__DEV__ ? 'CSS_VAR_TEXT' : '')
/**
* Runtime helper for SFC's CSS variable injection feature.
* @private
*/
-export function useCssVars(getter: (ctx: any) => Record<string, string>) {
+export function useCssVars(getter: (ctx: any) => Record<string, string>): void {
if (!__BROWSER__ && !__TEST__) return
const instance = getCurrentInstance()
value: any,
isSVG: boolean,
instance?: ComponentInternalInstance | null,
- isBoolean = isSpecialBooleanAttr(key),
-) {
+ isBoolean: boolean = isSpecialBooleanAttr(key),
+): void {
if (isSVG && key.startsWith('xlink:')) {
if (value == null) {
el.removeAttributeNS(xlinkNS, key.slice(6, key.length))
// compiler should normalize class + :class bindings on the same element
// into a single binding ['staticClass', dynamic]
-export function patchClass(el: Element, value: string | null, isSVG: boolean) {
+export function patchClass(
+ el: Element,
+ value: string | null,
+ isSVG: boolean,
+): void {
// directly setting className should be faster than setAttribute in theory
// if this is an element during a transition, take the temporary transition
// classes into account.
event: string,
handler: EventListener,
options?: EventListenerOptions,
-) {
+): void {
el.addEventListener(event, handler, options)
}
event: string,
handler: EventListener,
options?: EventListenerOptions,
-) {
+): void {
el.removeEventListener(event, handler, options)
}
-const veiKey = Symbol('_vei')
+const veiKey: unique symbol = Symbol('_vei')
export function patchEvent(
el: Element & { [veiKey]?: Record<string, Invoker | undefined> },
prevValue: EventValue | null,
nextValue: EventValue | unknown,
instance: ComponentInternalInstance | null = null,
-) {
+): void {
// vei = vue event invokers
const invokers = el[veiKey] || (el[veiKey] = {})
const existingInvoker = invokers[rawName]
key: string,
value: any,
parentComponent: any,
-) {
+): void {
if (key === 'innerHTML' || key === 'textContent') {
// null value case is handled in renderer patchElement before patching
// children
const displayRE = /(^|;)\s*display\s*:/
-export function patchStyle(el: Element, prev: Style, next: Style) {
+export function patchStyle(el: Element, prev: Style, next: Style): void {
const style = (el as HTMLElement).style
const isCssString = isString(next)
let hasControlledDisplay = false
export function ssrRenderList(
source: unknown,
renderItem: (value: unknown, key: string | number, index?: number) => void,
-) {
+): void {
if (isArray(source) || isString(source)) {
for (let i = 0, l = source.length; i < l; i++) {
renderItem(source[i], i)
push: PushFn,
parentComponent: ComponentInternalInstance,
slotScopeId?: string,
-) {
+): void {
// template-compiled slots are always rendered as fragments
push(`<!--[-->`)
ssrRenderSlotInner(
parentComponent: ComponentInternalInstance,
slotScopeId?: string,
transition?: boolean,
-) {
+): void {
const slotFn = slots[slotName]
if (slotFn) {
const slotBuffer: SSRBufferItem[] = []
export async function ssrRenderSuspense(
push: PushFn,
{ default: renderContent }: Record<string, (() => void) | undefined>,
-) {
+): Promise<void> {
if (renderContent) {
renderContent()
} else {
target: string,
disabled: boolean,
parentComponent: ComponentInternalInstance,
-) {
+): void {
parentPush('<!--teleport start-->')
const context = parentComponent.appContext.provides[
type: unknown,
model: unknown,
value: unknown,
-) {
+): string {
switch (type) {
case 'radio':
return looseEqual(model, value) ? ' checked' : ''
export function ssrGetDynamicModelProps(
existingProps: any = {},
model: unknown,
-) {
+): { checked: true } | { value: any } | null {
const { type, value } = existingProps
switch (type) {
case 'radio':
// Return static buffer and await on items during unroll stage
return buffer
},
- push(item: SSRBufferItem) {
+ push(item: SSRBufferItem): void {
const isStringItem = isString(item)
if (appendable && isStringItem) {
buffer[buffer.length - 1] += item as string
vnode: VNode,
parentComponent: ComponentInternalInstance,
slotScopeId?: string,
-) {
+): void {
const { type, shapeFlag, children } = vnode
switch (type) {
case Text:
children: VNodeArrayChildren,
parentComponent: ComponentInternalInstance,
slotScopeId?: string,
-) {
+): void {
for (let i = 0; i < children.length; i++) {
renderVNode(push, normalizeVNode(children[i]), parentComponent, slotScopeId)
}
export function pipeToNodeWritable(
input: App | VNode,
- context: SSRContext = {},
+ context: SSRContext | undefined = {},
writable: Writable,
-) {
+): void {
renderToSimpleStream(input, context, {
push(content) {
if (content != null) {
export function pipeToWebWritable(
input: App | VNode,
- context: SSRContext = {},
+ context: SSRContext | undefined = {},
writable: WritableStream,
): void {
const writer = writable.getWriter()
return result
}
-export async function resolveTeleports(context: SSRContext) {
+export async function resolveTeleports(context: SSRContext): Promise<void> {
if (context.__teleportBuffers) {
context.teleports = context.teleports || {}
for (const key in context.__teleportBuffers) {
export function generateCodeFrame(
source: string,
start = 0,
- end = source.length,
+ end: number = source.length,
): string {
// Ensure start and end are within the source length
start = Math.max(0, Math.min(start, source.length))
* - readonly -> readOnly
*/
const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`
-export const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs)
+export const isSpecialBooleanAttr: (key: string) => boolean =
+ /*#__PURE__*/ makeMap(specialBooleanAttrs)
/**
* The full list is needed during SSR to produce the correct initial markup.
*/
-export const isBooleanAttr = /*#__PURE__*/ makeMap(
+export const isBooleanAttr: (key: string) => boolean = /*#__PURE__*/ makeMap(
specialBooleanAttrs +
`,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
`inert,loop,open,required,reversed,scoped,seamless,` +
* Don't also forget to allow `data-*` and `aria-*`!
* Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
*/
-export const isKnownHtmlAttr = /*#__PURE__*/ makeMap(
+export const isKnownHtmlAttr: (key: string) => boolean = /*#__PURE__*/ makeMap(
`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
`autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
`border,buffered,capture,challenge,charset,checked,cite,class,code,` +
/**
* Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
*/
-export const isKnownSvgAttr = /*#__PURE__*/ makeMap(
+export const isKnownSvgAttr: (key: string) => boolean = /*#__PURE__*/ makeMap(
`xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,` +
`arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,` +
`baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,` +
* Compiler only.
* Do NOT use in runtime code paths unless behind `__DEV__` flag.
*/
-export const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS)
+export const isHTMLTag: (key: string) => boolean =
+ /*#__PURE__*/ makeMap(HTML_TAGS)
/**
* Compiler only.
* Do NOT use in runtime code paths unless behind `__DEV__` flag.
*/
-export const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS)
+export const isSVGTag: (key: string) => boolean =
+ /*#__PURE__*/ makeMap(SVG_TAGS)
/**
* Compiler only.
* Do NOT use in runtime code paths unless behind `__DEV__` flag.
*/
-export const isMathMLTag = /*#__PURE__*/ makeMap(MATH_TAGS)
+export const isMathMLTag: (key: string) => boolean =
+ /*#__PURE__*/ makeMap(MATH_TAGS)
/**
* Compiler only.
* Do NOT use in runtime code paths unless behind `__DEV__` flag.
*/
-export const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS)
+export const isVoidTag: (key: string) => boolean =
+ /*#__PURE__*/ makeMap(VOID_TAGS)
const escapeRE = /["'&<>]/
-export function escapeHtml(string: unknown) {
+export function escapeHtml(string: unknown): string {
const str = '' + string
const match = escapeRE.exec(str)
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
? Object.freeze({})
: {}
-export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
+export const EMPTY_ARR: readonly never[] = __DEV__ ? Object.freeze([]) : []
-export const NOOP = () => {}
+export const NOOP = (): void => {}
/**
* Always return false.
*/
export const NO = () => false
-export const isOn = (key: string) =>
+export const isOn = (key: string): boolean =>
key.charCodeAt(0) === 111 /* o */ &&
key.charCodeAt(1) === 110 /* n */ &&
// uppercase letter
(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97)
-export const isModelListener = (key: string) => key.startsWith('onUpdate:')
+export const isModelListener = (key: string): key is `onUpdate:${string}` =>
+ key.startsWith('onUpdate:')
-export const extend = Object.assign
+export const extend: typeof Object.assign = Object.assign
-export const remove = <T>(arr: T[], el: T) => {
+export const remove = <T>(arr: T[], el: T): void => {
const i = arr.indexOf(el)
if (i > -1) {
arr.splice(i, 1)
key: string | symbol,
): key is keyof typeof val => hasOwnProperty.call(val, key)
-export const isArray = Array.isArray
+export const isArray: typeof Array.isArray = Array.isArray
export const isMap = (val: unknown): val is Map<any, any> =>
toTypeString(val) === '[object Map]'
export const isSet = (val: unknown): val is Set<any> =>
)
}
-export const objectToString = Object.prototype.toString
+export const objectToString: typeof Object.prototype.toString =
+ Object.prototype.toString
export const toTypeString = (value: unknown): string =>
objectToString.call(value)
export const isPlainObject = (val: unknown): val is object =>
toTypeString(val) === '[object Object]'
-export const isIntegerKey = (key: unknown) =>
+export const isIntegerKey = (key: unknown): boolean =>
isString(key) &&
key !== 'NaN' &&
key[0] !== '-' &&
'' + parseInt(key, 10) === key
-export const isReservedProp = /*#__PURE__*/ makeMap(
+export const isReservedProp: (key: string) => boolean = /*#__PURE__*/ makeMap(
// the leading comma is intentional so empty string "" is also included
',key,ref,ref_for,ref_key,' +
'onVnodeBeforeMount,onVnodeMounted,' +
'onVnodeBeforeUnmount,onVnodeUnmounted',
)
-export const isBuiltInDirective = /*#__PURE__*/ makeMap(
- 'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo',
-)
+export const isBuiltInDirective: (key: string) => boolean =
+ /*#__PURE__*/ makeMap(
+ 'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo',
+ )
const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
const cache: Record<string, string> = Object.create(null)
/**
* @private
*/
-export const camelize = cacheStringFunction((str: string): string => {
- return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
-})
+export const camelize: (str: string) => string = cacheStringFunction(
+ (str: string): string => {
+ return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
+ },
+)
const hyphenateRE = /\B([A-Z])/g
/**
* @private
*/
-export const hyphenate = cacheStringFunction((str: string) =>
- str.replace(hyphenateRE, '-$1').toLowerCase(),
+export const hyphenate: (str: string) => string = cacheStringFunction(
+ (str: string) => str.replace(hyphenateRE, '-$1').toLowerCase(),
)
/**
* @private
*/
-export const capitalize = cacheStringFunction(<T extends string>(str: T) => {
- return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>
-})
+export const capitalize: <T extends string>(str: T) => Capitalize<T> =
+ cacheStringFunction(<T extends string>(str: T) => {
+ return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>
+ })
/**
* @private
*/
-export const toHandlerKey = cacheStringFunction(<T extends string>(str: T) => {
- const s = str ? `on${capitalize(str)}` : ``
- return s as T extends '' ? '' : `on${Capitalize<T>}`
-})
+export const toHandlerKey: <T extends string>(
+ str: T,
+) => T extends '' ? '' : `on${Capitalize<T>}` = cacheStringFunction(
+ <T extends string>(str: T) => {
+ const s = str ? `on${capitalize(str)}` : ``
+ return s as T extends '' ? '' : `on${Capitalize<T>}`
+ },
+)
// compare whether a value has changed, accounting for NaN.
export const hasChanged = (value: any, oldValue: any): boolean =>
!Object.is(value, oldValue)
-export const invokeArrayFns = (fns: Function[], ...arg: any[]) => {
+export const invokeArrayFns = (fns: Function[], ...arg: any[]): void => {
for (let i = 0; i < fns.length; i++) {
fns[i](...arg)
}
key: string | symbol,
value: any,
writable = false,
-) => {
+): void => {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: false,
const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/
-export function genPropsAccessExp(name: string) {
+export function genPropsAccessExp(name: string): string {
return identRE.test(name)
? `__props.${name}`
: `__props[${JSON.stringify(name)}]`
'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol'
-export const isGloballyAllowed = /*#__PURE__*/ makeMap(GLOBALS_ALLOWED)
+export const isGloballyAllowed: (key: string) => boolean =
+ /*#__PURE__*/ makeMap(GLOBALS_ALLOWED)
/** @deprecated use `isGloballyAllowed` instead */
-export const isGloballyWhitelisted = isGloballyAllowed
+export const isGloballyWhitelisted: (key: string) => boolean = isGloballyAllowed
return res.trim()
}
-export function normalizeProps(props: Record<string, any> | null) {
+export function normalizeProps(
+ props: Record<string, any> | null,
+): Record<string, any> | null {
if (!props) return null
let { class: klass, style } = props
if (klass && !isString(klass)) {
/**
* Dev only
*/
-export const slotFlagsText = {
+export const slotFlagsText: Record<SlotFlags, string> = {
[SlotFlags.STABLE]: 'STABLE',
[SlotFlags.DYNAMIC]: 'DYNAMIC',
[SlotFlags.FORWARDED]: 'FORWARDED',
// `dist/vue.esm-bundler.js` which is used by default for bundlers.
import { initDev } from './dev'
import {
+ type CompatVue,
DeprecationTypes,
KeepAlive,
Transition,
return app
}
-export function createCompatVue() {
+export function createCompatVue(): CompatVue {
const Vue = compatUtils.createCompatVue(createApp, wrappedCreateApp)
extend(Vue, runtimeDom)
return Vue
import { initCustomFormatter } from '@vue/runtime-dom'
-export function initDev() {
+export function initDev(): void {
if (__BROWSER__) {
if (!__ESM_BUNDLER__) {
console.info(
export default Vue
export * from '@vue/runtime-dom'
-const { configureCompat } = Vue
+const configureCompat: typeof Vue.configureCompat = Vue.configureCompat
export { configureCompat }
export default Vue
export * from '@vue/runtime-dom'
-const { configureCompat } = Vue
+const configureCompat: typeof Vue.configureCompat = Vue.configureCompat
export { configureCompat }
compile,
} from '@vue/compiler-dom'
import {
+ type CompatVue,
type RenderFunction,
registerRuntimeCompiler,
warn,
registerRuntimeCompiler(compileToFunction)
-const Vue = createCompatVue()
+const Vue: CompatVue = createCompatVue()
Vue.compile = compileToFunction
export default Vue
// This entry exports the runtime only, and is built as
// `dist/vue.esm-bundler.js` which is used by default for bundlers.
import { createCompatVue } from './createCompatVue'
-import { warn } from '@vue/runtime-core'
+import { type CompatVue, warn } from '@vue/runtime-core'
-const Vue = createCompatVue()
+const Vue: CompatVue = createCompatVue()
Vue.compile = (() => {
if (__DEV__) {
import { initCustomFormatter } from '@vue/runtime-dom'
-export function initDev() {
+export function initDev(): void {
if (__BROWSER__) {
/* istanbul ignore if */
if (!__ESM_BUNDLER__) {
export * from '@vue/runtime-dom'
-export const compile = () => {
+export const compile = (): void => {
if (__DEV__) {
warn(
`Runtime compilation is not supported in this build of Vue.` +
"types": [],
"declaration": true,
"emitDeclarationOnly": true,
- "stripInternal": true
+ "stripInternal": true,
+ "composite": false
},
"include": [
"packages/global.d.ts",
"types": ["node"],
"declaration": true,
"emitDeclarationOnly": true,
- "stripInternal": true
+ "stripInternal": true,
+ "composite": false
},
"include": [
"packages/global.d.ts",
"useDefineForClassFields": false,
"module": "esnext",
"moduleResolution": "bundler",
- "allowJs": true,
+ "allowJs": false,
"strict": true,
"noUnusedLocals": true,
"experimentalDecorators": true,
"@vue/compat": ["packages/vue-compat/src"],
"@vue/*": ["packages/*/src"],
"vue": ["packages/vue/src"]
- }
+ },
+ "isolatedDeclarations": true,
+ "composite": true
},
"include": [
"packages/global.d.ts",