@vue/language-core
Advanced tools
Comparing version 2.1.5 to 2.1.6
@@ -1,1 +0,1 @@ | ||
export declare function generateGlobalTypes(mode: 'global' | 'local', lib: string, target: number, strictTemplates: boolean): string; | ||
export declare function generateGlobalTypes(lib: string, target: number, strictTemplates: boolean): string; |
@@ -5,138 +5,136 @@ "use strict"; | ||
const shared_1 = require("../utils/shared"); | ||
const common_1 = require("./common"); | ||
function generateGlobalTypes(mode, lib, target, strictTemplates) { | ||
function generateGlobalTypes(lib, target, strictTemplates) { | ||
const fnPropsType = `(K extends { $props: infer Props } ? Props : any)${strictTemplates ? '' : ' & Record<string, unknown>'}`; | ||
let str = ''; | ||
let globalComponentsType; | ||
if (mode === 'global') { | ||
str += `// @ts-nocheck${common_1.newLine}`; | ||
str += `export {}${common_1.endOfLine}`; | ||
str += `declare module '${lib}' {${common_1.newLine}`; | ||
str += ` export interface GlobalComponents { }${common_1.newLine}`; | ||
str += `}${common_1.newLine}`; | ||
str += `declare global {${common_1.newLine}`; | ||
globalComponentsType = `import('${lib}').GlobalComponents`; | ||
let text = ``; | ||
if (target < 3.5) { | ||
text += ` | ||
; declare module '${lib}' { | ||
export interface GlobalComponents { } | ||
export interface GlobalDirectives { } | ||
}`; | ||
} | ||
else { | ||
str += `const __VLS_globalComponents = { ...{} as import('${lib}').GlobalComponents }${common_1.endOfLine}`; | ||
globalComponentsType = `void extends typeof __VLS_globalComponents ? {} : typeof __VLS_globalComponents`; | ||
} | ||
str += ` | ||
const __VLS_intrinsicElements: __VLS_IntrinsicElements; | ||
const __VLS_directiveBindingRestFields = { instance: null, oldValue: null, modifiers: null as any, dir: null as any }; | ||
text += ` | ||
; declare global { | ||
const __VLS_intrinsicElements: __VLS_IntrinsicElements; | ||
const __VLS_directiveBindingRestFields: { instance: null, oldValue: null, modifiers: any, dir: any }; | ||
const __VLS_unref: typeof import('${lib}').unref; | ||
type __VLS_IntrinsicElements = ${(target >= 3.3 | ||
const __VLS_nativeElements = { | ||
...{} as SVGElementTagNameMap, | ||
...{} as HTMLElementTagNameMap, | ||
}; | ||
type __VLS_IntrinsicElements = ${(target >= 3.3 | ||
? `import('${lib}/jsx-runtime').JSX.IntrinsicElements;` | ||
: `globalThis.JSX.IntrinsicElements;`)} | ||
type __VLS_Element = ${(target >= 3.3 | ||
type __VLS_Element = ${(target >= 3.3 | ||
? `import('${lib}/jsx-runtime').JSX.Element;` | ||
: `globalThis.JSX.Element;`)} | ||
type __VLS_GlobalComponents = ${(target >= 3.5 | ||
? globalComponentsType | ||
: `(${globalComponentsType}) & Pick<typeof import('${lib}'), 'Transition' | 'TransitionGroup' | 'KeepAlive' | 'Suspense' | 'Teleport'>;`)} | ||
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false; | ||
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A; | ||
type __VLS_unknownDirective = (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void; | ||
type __VLS_WithComponent<N0 extends string, LocalComponents, N1 extends string, N2 extends string, N3 extends string> = | ||
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N1] } : | ||
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N2] } : | ||
N3 extends keyof LocalComponents ? N3 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N3] } : | ||
N1 extends keyof __VLS_GlobalComponents ? N1 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N1] } : | ||
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } : | ||
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } : | ||
${strictTemplates ? '{}' : '{ [K in N0]: unknown }'} | ||
type __VLS_FunctionalComponentProps<T, K> = | ||
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never | ||
: T extends (props: infer P, ...args: any) => any ? P : | ||
{}; | ||
type __VLS_IsFunction<T, K> = K extends keyof T | ||
? __VLS_IsAny<T[K]> extends false | ||
? unknown extends T[K] | ||
? false | ||
: true | ||
: false | ||
: false; | ||
// fix https://github.com/vuejs/language-tools/issues/926 | ||
type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never; | ||
type __VLS_OverloadUnionInner<T, U = unknown> = U & T extends (...args: infer A) => infer R | ||
? U extends T | ||
? never | ||
: __VLS_OverloadUnionInner<T, Pick<T, keyof T> & U & ((...args: A) => R)> | ((...args: A) => R) | ||
: never; | ||
type __VLS_OverloadUnion<T> = Exclude< | ||
__VLS_OverloadUnionInner<(() => never) & T>, | ||
T extends () => never ? never : () => never | ||
>; | ||
type __VLS_ConstructorOverloads<T> = __VLS_OverloadUnion<T> extends infer F | ||
? F extends (event: infer E, ...args: infer A) => any | ||
? { [K in E & string]: (...args: A) => void; } | ||
: never | ||
: never; | ||
type __VLS_NormalizeEmits<T> = __VLS_PrettifyGlobal< | ||
__VLS_UnionToIntersection< | ||
__VLS_ConstructorOverloads<T> & { | ||
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never | ||
} | ||
> | ||
>; | ||
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {}; | ||
type __VLS_GlobalComponents = ${(target >= 3.5 | ||
? `import('${lib}').GlobalComponents;` | ||
: `import('${lib}').GlobalComponents & Pick<typeof import('${lib}'), 'Transition' | 'TransitionGroup' | 'KeepAlive' | 'Suspense' | 'Teleport'>;`)} | ||
type __VLS_GlobalDirectives = import('${lib}').GlobalDirectives; | ||
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false; | ||
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A; | ||
type __VLS_unknownDirective = (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void; | ||
type __VLS_WithComponent<N0 extends string, LocalComponents, N1 extends string, N2 extends string, N3 extends string> = | ||
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N1] } : | ||
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N2] } : | ||
N3 extends keyof LocalComponents ? N3 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N3] } : | ||
N1 extends keyof __VLS_GlobalComponents ? N1 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N1] } : | ||
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } : | ||
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } : | ||
${strictTemplates ? '{}' : '{ [K in N0]: unknown }'} | ||
type __VLS_FunctionalComponentProps<T, K> = | ||
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never | ||
: T extends (props: infer P, ...args: any) => any ? P : | ||
{}; | ||
type __VLS_IsFunction<T, K> = K extends keyof T | ||
? __VLS_IsAny<T[K]> extends false | ||
? unknown extends T[K] | ||
? false | ||
: true | ||
: false | ||
: false; | ||
// fix https://github.com/vuejs/language-tools/issues/926 | ||
type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never; | ||
type __VLS_OverloadUnionInner<T, U = unknown> = U & T extends (...args: infer A) => infer R | ||
? U extends T | ||
? never | ||
: __VLS_OverloadUnionInner<T, Pick<T, keyof T> & U & ((...args: A) => R)> | ((...args: A) => R) | ||
: never; | ||
type __VLS_OverloadUnion<T> = Exclude< | ||
__VLS_OverloadUnionInner<(() => never) & T>, | ||
T extends () => never ? never : () => never | ||
>; | ||
type __VLS_ConstructorOverloads<T> = __VLS_OverloadUnion<T> extends infer F | ||
? F extends (event: infer E, ...args: infer A) => any | ||
? { [K in E & string]: (...args: A) => void; } | ||
: never | ||
: never; | ||
type __VLS_NormalizeEmits<T> = __VLS_PrettifyGlobal< | ||
__VLS_UnionToIntersection< | ||
__VLS_ConstructorOverloads<T> & { | ||
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never | ||
} | ||
> | ||
>; | ||
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {}; | ||
function __VLS_getVForSourceType(source: number): [number, number, number][]; | ||
function __VLS_getVForSourceType(source: string): [string, number, number][]; | ||
function __VLS_getVForSourceType<T extends any[]>(source: T): [ | ||
item: T[number], | ||
key: number, | ||
index: number, | ||
][]; | ||
function __VLS_getVForSourceType<T extends { [Symbol.iterator](): Iterator<any> }>(source: T): [ | ||
item: T extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never, | ||
key: number, | ||
index: undefined, | ||
][]; | ||
// #3845 | ||
function __VLS_getVForSourceType<T extends number | { [Symbol.iterator](): Iterator<any> }>(source: T): [ | ||
item: number | (Exclude<T, number> extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never), | ||
key: number, | ||
index: undefined, | ||
][]; | ||
function __VLS_getVForSourceType<T>(source: T): [ | ||
item: T[keyof T], | ||
key: keyof T, | ||
index: number, | ||
][]; | ||
// @ts-ignore | ||
function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>; | ||
// @ts-ignore | ||
function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0]; | ||
function __VLS_directiveAsFunction<T extends import('${lib}').Directive>(dir: T): T extends (...args: any) => any | ||
? T | __VLS_unknownDirective | ||
: NonNullable<(T & Record<string, __VLS_unknownDirective>)['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>; | ||
function __VLS_withScope<T, K>(ctx: T, scope: K): ctx is T & K; | ||
function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] }; | ||
function __VLS_nonNullable<T>(t: T): T extends null | undefined ? never : T; | ||
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K): | ||
T extends new (...args: any) => any | ||
? (props: ${fnPropsType}, ctx?: any) => __VLS_Element & { __ctx?: { | ||
attrs?: any, | ||
slots?: K extends { ${(0, shared_1.getSlotsPropertyName)(target)}: infer Slots } ? Slots : any, | ||
emit?: K extends { $emit: infer Emit } ? Emit : any | ||
} & { props?: ${fnPropsType}; expose?(exposed: K): void; } } | ||
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T> | ||
: T extends (...args: any) => any ? T | ||
: (_: {}${strictTemplates ? '' : ' & Record<string, unknown>'}, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {}${strictTemplates ? '' : ' & Record<string, unknown>'} } }; | ||
function __VLS_elementAsFunction<T>(tag: T, endTag?: T): (_: T${strictTemplates ? '' : ' & Record<string, unknown>'}) => void; | ||
function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): 2 extends Parameters<T>['length'] ? [any] : []; | ||
function __VLS_pickFunctionalComponentCtx<T, K>(comp: T, compInstance: K): NonNullable<__VLS_PickNotAny< | ||
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any | ||
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any | ||
>>; | ||
function __VLS_normalizeSlot<S>(s: S): S extends () => infer R ? (props: {}) => R : S; | ||
function __VLS_tryAsConstant<const T>(t: T): T; | ||
function __VLS_getVForSourceType(source: number): [number, number, number][]; | ||
function __VLS_getVForSourceType(source: string): [string, number, number][]; | ||
function __VLS_getVForSourceType<T extends any[]>(source: T): [ | ||
item: T[number], | ||
key: number, | ||
index: number, | ||
][]; | ||
function __VLS_getVForSourceType<T extends { [Symbol.iterator](): Iterator<any> }>(source: T): [ | ||
item: T extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never, | ||
key: number, | ||
index: undefined, | ||
][]; | ||
// #3845 | ||
function __VLS_getVForSourceType<T extends number | { [Symbol.iterator](): Iterator<any> }>(source: T): [ | ||
item: number | (Exclude<T, number> extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never), | ||
key: number, | ||
index: undefined, | ||
][]; | ||
function __VLS_getVForSourceType<T>(source: T): [ | ||
item: T[keyof T], | ||
key: keyof T, | ||
index: number, | ||
][]; | ||
// @ts-ignore | ||
function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>; | ||
// @ts-ignore | ||
function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0]; | ||
function __VLS_directiveAsFunction<T extends import('${lib}').Directive>(dir: T): T extends (...args: any) => any | ||
? T | __VLS_unknownDirective | ||
: NonNullable<(T & Record<string, __VLS_unknownDirective>)['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>; | ||
function __VLS_withScope<T, K>(ctx: T, scope: K): ctx is T & K; | ||
function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] }; | ||
function __VLS_nonNullable<T>(t: T): T extends null | undefined ? never : T; | ||
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K): | ||
T extends new (...args: any) => any | ||
? (props: ${fnPropsType}, ctx?: any) => __VLS_Element & { __ctx?: { | ||
attrs?: any, | ||
slots?: K extends { ${(0, shared_1.getSlotsPropertyName)(target)}: infer Slots } ? Slots : any, | ||
emit?: K extends { $emit: infer Emit } ? Emit : any | ||
} & { props?: ${fnPropsType}; expose?(exposed: K): void; } } | ||
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T> | ||
: T extends (...args: any) => any ? T | ||
: (_: {}${strictTemplates ? '' : ' & Record<string, unknown>'}, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {}${strictTemplates ? '' : ' & Record<string, unknown>'} } }; | ||
function __VLS_elementAsFunction<T>(tag: T, endTag?: T): (_: T${strictTemplates ? '' : ' & Record<string, unknown>'}) => void; | ||
function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): 2 extends Parameters<T>['length'] ? [any] : []; | ||
function __VLS_pickFunctionalComponentCtx<T, K>(comp: T, compInstance: K): NonNullable<__VLS_PickNotAny< | ||
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any | ||
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any | ||
>>; | ||
function __VLS_normalizeSlot<S>(s: S): S extends () => infer R ? (props: {}) => R : S; | ||
function __VLS_tryAsConstant<const T>(t: T): T; | ||
} | ||
`; | ||
if (mode === 'global') { | ||
str += `}${common_1.newLine}`; | ||
} | ||
return str; | ||
return text; | ||
} | ||
; | ||
//# sourceMappingURL=globalTypes.js.map |
@@ -40,3 +40,3 @@ "use strict"; | ||
if (options.vueCompilerOptions.target >= 3.5 && scriptSetupRanges.templateRefs.length) { | ||
yield `__typeRefs: {} as __VLS_Refs,${common_1.newLine}`; | ||
yield `__typeRefs: {} as __VLS_TemplateResult['refs'],${common_1.newLine}`; | ||
} | ||
@@ -108,19 +108,23 @@ yield `})`; | ||
function* generatePropsOption(options, ctx, scriptSetup, scriptSetupRanges, hasEmitsOption, inheritAttrs) { | ||
const optionExpCodes = []; | ||
const typeOptionExpCodes = []; | ||
const codes = []; | ||
if (ctx.generatedPropsType) { | ||
optionExpCodes.push([ | ||
`{} as `, | ||
scriptSetupRanges.props.withDefaults?.arg ? `${ctx.localTypes.WithDefaults}<` : '', | ||
`${ctx.localTypes.TypePropsToOption}<__VLS_PublicProps>`, | ||
scriptSetupRanges.props.withDefaults?.arg ? `, typeof __VLS_withDefaultsArg>` : '', | ||
].join('')); | ||
typeOptionExpCodes.push(`{} as __VLS_PublicProps`); | ||
codes.push({ | ||
optionExp: [ | ||
`{} as `, | ||
scriptSetupRanges.props.withDefaults?.arg ? `${ctx.localTypes.WithDefaults}<` : '', | ||
`${ctx.localTypes.TypePropsToOption}<__VLS_PublicProps>`, | ||
scriptSetupRanges.props.withDefaults?.arg ? `, typeof __VLS_withDefaultsArg>` : '', | ||
].join(''), | ||
typeOptionExp: `{} as __VLS_PublicProps`, | ||
}); | ||
} | ||
if (scriptSetupRanges.props.define?.arg) { | ||
const { arg } = scriptSetupRanges.props.define; | ||
optionExpCodes.push((0, common_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, index_1.codeFeatures.navigation)); | ||
codes.push({ | ||
optionExp: (0, common_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, index_1.codeFeatures.navigation), | ||
typeOptionExp: undefined, | ||
}); | ||
} | ||
if (inheritAttrs && options.templateCodegen?.inheritedAttrVars.size) { | ||
let attrsType = `typeof __VLS_templateResult['attrs']`; | ||
let attrsType = `__VLS_TemplateResult['attrs']`; | ||
if (hasEmitsOption) { | ||
@@ -131,24 +135,23 @@ attrsType = `Omit<${attrsType}, \`on\${string}\`>`; | ||
const optionType = `${ctx.localTypes.TypePropsToOption}<${propsType}>`; | ||
if (optionExpCodes.length) { | ||
optionExpCodes.unshift(`{} as ${optionType}`); | ||
} | ||
else { | ||
// workaround for https://github.com/vuejs/core/pull/7419 | ||
optionExpCodes.unshift(`{} as keyof ${propsType} extends never ? never: ${optionType}`); | ||
} | ||
typeOptionExpCodes.unshift(`{} as ${attrsType}`); | ||
codes.unshift({ | ||
optionExp: codes.length | ||
? `{} as ${optionType}` | ||
// workaround for https://github.com/vuejs/core/pull/7419 | ||
: `{} as keyof ${propsType} extends never ? never: ${optionType}`, | ||
typeOptionExp: `{} as ${attrsType}`, | ||
}); | ||
} | ||
const useTypeOption = options.vueCompilerOptions.target >= 3.5 && typeOptionExpCodes.length; | ||
const useOption = (!useTypeOption || scriptSetupRanges.props.withDefaults) && optionExpCodes.length; | ||
const useTypeOption = options.vueCompilerOptions.target >= 3.5 && codes.every(code => code.typeOptionExp); | ||
const useOption = !useTypeOption || scriptSetupRanges.props.withDefaults; | ||
if (useTypeOption) { | ||
if (typeOptionExpCodes.length === 1) { | ||
if (codes.length === 1) { | ||
yield `__typeProps: `; | ||
yield typeOptionExpCodes[0]; | ||
yield codes[0].typeOptionExp; | ||
yield `,${common_1.newLine}`; | ||
} | ||
else if (typeOptionExpCodes.length >= 2) { | ||
else if (codes.length >= 2) { | ||
yield `__typeProps: {${common_1.newLine}`; | ||
for (const code of typeOptionExpCodes) { | ||
for (const { typeOptionExp } of codes) { | ||
yield `...`; | ||
yield code; | ||
yield typeOptionExp; | ||
yield `,${common_1.newLine}`; | ||
@@ -160,12 +163,12 @@ } | ||
if (useOption) { | ||
if (optionExpCodes.length === 1) { | ||
if (codes.length === 1) { | ||
yield `props: `; | ||
yield optionExpCodes[0]; | ||
yield codes[0].optionExp; | ||
yield `,${common_1.newLine}`; | ||
} | ||
else if (optionExpCodes.length >= 2) { | ||
else if (codes.length >= 2) { | ||
yield `props: {${common_1.newLine}`; | ||
for (const code of optionExpCodes) { | ||
for (const { optionExp } of codes) { | ||
yield `...`; | ||
yield code; | ||
yield optionExp; | ||
yield `,${common_1.newLine}`; | ||
@@ -172,0 +175,0 @@ } |
@@ -28,2 +28,3 @@ import type { Mapping } from '@volar/language-core'; | ||
edited: boolean; | ||
appendGlobalTypes: boolean; | ||
getGeneratedLength: () => number; | ||
@@ -30,0 +31,0 @@ linkedCodeMappings: Mapping[]; |
@@ -6,7 +6,9 @@ "use strict"; | ||
const common_1 = require("../common"); | ||
const globalTypes_1 = require("../globalTypes"); | ||
const context_1 = require("./context"); | ||
const componentSelf_1 = require("./componentSelf"); | ||
const scriptSetup_1 = require("./scriptSetup"); | ||
const src_1 = require("./src"); | ||
const styleModulesType_1 = require("./styleModulesType"); | ||
const template_1 = require("./template"); | ||
const globalTypes_1 = require("../globalTypes"); | ||
exports.codeFeatures = { | ||
@@ -36,3 +38,3 @@ all: { | ||
const ctx = (0, context_1.createScriptCodegenContext)(options); | ||
if (options.vueCompilerOptions.__setupedGlobalTypes?.()) { | ||
if (options.vueCompilerOptions.__setupedGlobalTypes) { | ||
yield `/// <reference types=".vue-global-types/${options.vueCompilerOptions.lib}_${options.vueCompilerOptions.target}_${options.vueCompilerOptions.strictTemplates}.d.ts" />${common_1.newLine}`; | ||
@@ -96,3 +98,4 @@ } | ||
yield `__VLS_template = () => {`; | ||
yield* (0, template_1.generateTemplate)(options, ctx, true); | ||
const templateCodegenCtx = yield* (0, template_1.generateTemplate)(options, ctx, true); | ||
yield* (0, componentSelf_1.generateComponentSelf)(options, ctx, templateCodegenCtx); | ||
yield `},${common_1.newLine}`; | ||
@@ -118,4 +121,9 @@ yield (0, common_1.generateSfcBlockSection)(options.sfc.script, classBlockEnd, options.sfc.script.content.length, exports.codeFeatures.all); | ||
if (!ctx.generatedTemplate) { | ||
yield* (0, template_1.generateTemplate)(options, ctx, false); | ||
yield `function __VLS_template() {${common_1.newLine}`; | ||
const templateCodegenCtx = yield* (0, template_1.generateTemplate)(options, ctx, false); | ||
yield `}${common_1.endOfLine}`; | ||
yield* (0, componentSelf_1.generateComponentSelf)(options, ctx, templateCodegenCtx); | ||
} | ||
// #4788 | ||
yield* (0, styleModulesType_1.generateStyleModulesType)(options, ctx); | ||
if (options.edited) { | ||
@@ -125,4 +133,4 @@ yield `type __VLS_IntrinsicElementsCompletion = __VLS_IntrinsicElements${common_1.endOfLine}`; | ||
yield* ctx.localTypes.generate([...ctx.localTypes.getUsedNames()]); | ||
if (!options.vueCompilerOptions.__setupedGlobalTypes?.()) { | ||
yield (0, globalTypes_1.generateGlobalTypes)('local', options.vueCompilerOptions.lib, options.vueCompilerOptions.target, options.vueCompilerOptions.strictTemplates); | ||
if (options.appendGlobalTypes) { | ||
yield (0, globalTypes_1.generateGlobalTypes)(options.vueCompilerOptions.lib, options.vueCompilerOptions.target, options.vueCompilerOptions.strictTemplates); | ||
} | ||
@@ -129,0 +137,0 @@ if (options.sfc.scriptSetup) { |
@@ -8,2 +8,3 @@ "use strict"; | ||
const index_1 = require("./index"); | ||
const componentSelf_1 = require("./componentSelf"); | ||
const template_1 = require("./template"); | ||
@@ -61,3 +62,3 @@ function* generateScriptSetupImports(scriptSetup, scriptSetupRanges) { | ||
+ ` attrs: any,${common_1.newLine}` | ||
+ ` slots: __VLS_Slots,${common_1.newLine}` | ||
+ ` slots: __VLS_TemplateResult['slots'],${common_1.newLine}` | ||
+ ` emit: ${emitTypes.length ? emitTypes.join(' & ') : `{}`},${common_1.newLine}` | ||
@@ -228,5 +229,5 @@ + ` }${common_1.endOfLine}`; | ||
[ | ||
`<__VLS_Refs[`, | ||
`<__VLS_TemplateResult['refs'][`, | ||
(0, common_1.generateSfcBlockSection)(scriptSetup, define.arg.start, define.arg.end, index_1.codeFeatures.navigation), | ||
`], keyof __VLS_Refs>` | ||
`], keyof __VLS_TemplateResult['refs']>` | ||
], | ||
@@ -266,6 +267,7 @@ define.arg.start - 1, | ||
yield* generateModelEmits(options, scriptSetup, scriptSetupRanges); | ||
yield* generateStyleModules(options, ctx); | ||
yield* (0, template_1.generateTemplate)(options, ctx, false); | ||
yield `type __VLS_Refs = typeof __VLS_templateResult['refs']${common_1.endOfLine}`; | ||
yield `type __VLS_Slots = typeof __VLS_templateResult['slots']${common_1.endOfLine}`; | ||
yield `function __VLS_template() {${common_1.newLine}`; | ||
const templateCodegenCtx = yield* (0, template_1.generateTemplate)(options, ctx, false); | ||
yield `}${common_1.endOfLine}`; | ||
yield* (0, componentSelf_1.generateComponentSelf)(options, ctx, templateCodegenCtx); | ||
yield `type __VLS_TemplateResult = ReturnType<typeof __VLS_template>${common_1.endOfLine}`; | ||
if (syntax) { | ||
@@ -277,3 +279,3 @@ if (!options.vueCompilerOptions.skipTemplateCodegen && (options.templateCodegen?.hasSlot || scriptSetupRanges?.slots.define)) { | ||
yield `${syntax} `; | ||
yield `{} as ${ctx.localTypes.WithTemplateSlots}<typeof __VLS_component, __VLS_Slots>${common_1.endOfLine}`; | ||
yield `{} as ${ctx.localTypes.WithTemplateSlots}<typeof __VLS_component, __VLS_TemplateResult['slots']>${common_1.endOfLine}`; | ||
} | ||
@@ -411,31 +413,2 @@ else { | ||
} | ||
function* generateStyleModules(options, ctx) { | ||
const styles = options.sfc.styles.filter(style => style.module); | ||
if (!styles.length) { | ||
return; | ||
} | ||
yield `type __VLS_StyleModules = {${common_1.newLine}`; | ||
for (let i = 0; i < styles.length; i++) { | ||
const style = styles[i]; | ||
const { name, offset } = style.module; | ||
if (offset) { | ||
yield [ | ||
name, | ||
'main', | ||
offset + 1, | ||
index_1.codeFeatures.all | ||
]; | ||
} | ||
else { | ||
yield name; | ||
} | ||
yield `: Record<string, string> & ${ctx.localTypes.PrettifyLocal}<{}`; | ||
for (const className of style.classNames) { | ||
yield* (0, template_1.generateCssClassProperty)(i, className.text, className.offset, 'string', false); | ||
} | ||
yield `>${common_1.endOfLine}`; | ||
} | ||
yield `}`; | ||
yield common_1.endOfLine; | ||
} | ||
function* generateDefinePropType(scriptSetup, propName, localName, defineProp) { | ||
@@ -442,0 +415,0 @@ if (defineProp.type) { |
import type { Code } from '../../types'; | ||
import { TemplateCodegenContext } from '../template/context'; | ||
import type { ScriptCodegenContext } from './context'; | ||
import { type ScriptCodegenOptions } from './index'; | ||
export declare function generateTemplateCtx(options: ScriptCodegenOptions, isClassComponent: boolean): Generator<Code>; | ||
export declare function generateTemplateComponents(options: ScriptCodegenOptions): Generator<Code>; | ||
export declare function generateTemplate(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, isClassComponent: boolean): Generator<Code>; | ||
export declare function generateTemplateDirectives(options: ScriptCodegenOptions): Generator<Code>; | ||
export declare function generateTemplate(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, isClassComponent: boolean): Generator<Code, TemplateCodegenContext>; | ||
export declare function generateCssClassProperty(styleIndex: number, classNameWithDot: string, offset: number, propertyType: string, optional: boolean): Generator<Code>; | ||
export declare function getTemplateUsageVars(options: ScriptCodegenOptions, ctx: ScriptCodegenContext): Set<string>; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateTemplateCtx = generateTemplateCtx; | ||
exports.generateTemplateComponents = generateTemplateComponents; | ||
exports.generateTemplateDirectives = generateTemplateDirectives; | ||
exports.generateTemplate = generateTemplate; | ||
@@ -14,50 +13,24 @@ exports.generateCssClassProperty = generateCssClassProperty; | ||
const index_1 = require("./index"); | ||
const internalComponent_1 = require("./internalComponent"); | ||
function* generateTemplateCtx(options, isClassComponent) { | ||
const baseExps = []; | ||
const extraExps = []; | ||
const exps = []; | ||
if (isClassComponent) { | ||
baseExps.push(`this`); | ||
exps.push(`this`); | ||
} | ||
else { | ||
baseExps.push(`{} as InstanceType<__VLS_PickNotAny<typeof __VLS_internalComponent, new () => {}>>`); | ||
exps.push(`{} as InstanceType<__VLS_PickNotAny<typeof __VLS_self, new () => {}>>`); | ||
} | ||
if (options.vueCompilerOptions.petiteVueExtensions.some(ext => options.fileBaseName.endsWith(ext))) { | ||
extraExps.push(`globalThis`); | ||
exps.push(`globalThis`); | ||
} | ||
if (options.sfc.styles.some(style => style.module)) { | ||
extraExps.push(`{} as __VLS_StyleModules`); | ||
exps.push(`{} as __VLS_StyleModules`); | ||
} | ||
if (options.scriptSetupRanges?.templateRefs.length) { | ||
let exp = `{} as import('${options.vueCompilerOptions.lib}').UnwrapRef<{${common_1.newLine}`; | ||
for (const { name } of options.scriptSetupRanges.templateRefs) { | ||
if (name) { | ||
exp += `${name}: typeof ${name}${common_1.newLine}`; | ||
} | ||
} | ||
exp += `}>${common_1.newLine}`; | ||
extraExps.push(exp); | ||
} | ||
yield `const __VLS_ctxBase = `; | ||
if (baseExps.length === 1) { | ||
yield baseExps[0]; | ||
yield common_1.endOfLine; | ||
} | ||
else { | ||
yield `{${common_1.newLine}`; | ||
for (const exp of baseExps) { | ||
yield `...`; | ||
yield exp; | ||
yield `,${common_1.newLine}`; | ||
} | ||
yield `}${common_1.endOfLine}`; | ||
} | ||
yield `const __VLS_ctx = `; | ||
if (extraExps.length === 0) { | ||
yield `__VLS_ctxBase${common_1.endOfLine}`; | ||
if (exps.length === 1) { | ||
yield exps[0]; | ||
yield `${common_1.endOfLine}`; | ||
} | ||
else { | ||
yield `{${common_1.newLine}`; | ||
yield `...__VLS_ctxBase,${common_1.newLine}`; | ||
for (const exp of extraExps) { | ||
for (const exp of exps) { | ||
yield `...`; | ||
@@ -87,8 +60,7 @@ yield exp; | ||
else if (options.sfc.scriptSetup) { | ||
yield `let __VLS_name!: '${options.scriptSetupRanges?.options.name ?? options.fileBaseName.substring(0, options.fileBaseName.lastIndexOf('.'))}'${common_1.endOfLine}`; | ||
nameType = 'typeof __VLS_name'; | ||
nameType = `'${options.scriptSetupRanges?.options.name ?? options.fileBaseName.substring(0, options.fileBaseName.lastIndexOf('.'))}'`; | ||
} | ||
if (nameType) { | ||
exps.push(`{} as { | ||
[K in ${nameType}]: typeof __VLS_internalComponent | ||
[K in ${nameType}]: typeof __VLS_self | ||
& (new () => { | ||
@@ -99,4 +71,4 @@ ${(0, shared_1.getSlotsPropertyName)(options.vueCompilerOptions.target)}: typeof ${options.scriptSetupRanges?.slots?.name ?? '__VLS_slots'} | ||
} | ||
exps.push(`{} as NonNullable<typeof __VLS_internalComponent extends { components: infer C } ? C : {}>`); | ||
exps.push(`__VLS_ctxBase`); | ||
exps.push(`{} as NonNullable<typeof __VLS_self extends { components: infer C } ? C : {}>`); | ||
exps.push(`__VLS_ctx`); | ||
yield `const __VLS_localComponents = {${common_1.newLine}`; | ||
@@ -109,23 +81,38 @@ for (const type of exps) { | ||
yield `}${common_1.endOfLine}`; | ||
yield `let __VLS_components: typeof __VLS_localComponents & __VLS_GlobalComponents${common_1.endOfLine}`; | ||
yield `let __VLS_components!: typeof __VLS_localComponents & __VLS_GlobalComponents${common_1.endOfLine}`; | ||
} | ||
function* generateTemplate(options, ctx, isClassComponent) { | ||
ctx.generatedTemplate = true; | ||
if (!options.vueCompilerOptions.skipTemplateCodegen) { | ||
const templateCodegenCtx = (0, context_1.createTemplateCodegenContext)({ | ||
scriptSetupBindingNames: new Set(), | ||
edited: options.edited, | ||
}); | ||
yield* generateTemplateCtx(options, isClassComponent); | ||
yield* generateTemplateComponents(options); | ||
yield* generateTemplateBody(options, templateCodegenCtx); | ||
yield* (0, internalComponent_1.generateInternalComponent)(options, ctx, templateCodegenCtx); | ||
function* generateTemplateDirectives(options) { | ||
const exps = []; | ||
if (options.sfc.script && options.scriptRanges?.exportDefault?.directivesOption) { | ||
const { directivesOption } = options.scriptRanges.exportDefault; | ||
exps.push([ | ||
options.sfc.script.content.substring(directivesOption.start, directivesOption.end), | ||
'script', | ||
directivesOption.start, | ||
index_1.codeFeatures.navigation, | ||
]); | ||
} | ||
else { | ||
const templateUsageVars = [...getTemplateUsageVars(options, ctx)]; | ||
yield `// @ts-ignore${common_1.newLine}`; | ||
yield `[${templateUsageVars.join(', ')}]${common_1.newLine}`; | ||
yield `const __VLS_templateResult { slots: {}, refs: {}, attrs: {} }${common_1.endOfLine}`; | ||
exps.push(`{} as NonNullable<typeof __VLS_self extends { directives: infer D } ? D : {}>`); | ||
exps.push(`__VLS_ctx`); | ||
yield `const __VLS_localDirectives = {${common_1.newLine}`; | ||
for (const type of exps) { | ||
yield `...`; | ||
yield type; | ||
yield `,${common_1.newLine}`; | ||
} | ||
yield `}${common_1.endOfLine}`; | ||
yield `let __VLS_directives!: typeof __VLS_localDirectives & __VLS_GlobalDirectives${common_1.endOfLine}`; | ||
} | ||
function* generateTemplate(options, ctx, isClassComponent) { | ||
ctx.generatedTemplate = true; | ||
const templateCodegenCtx = (0, context_1.createTemplateCodegenContext)({ | ||
scriptSetupBindingNames: new Set(), | ||
edited: options.edited, | ||
}); | ||
yield* generateTemplateCtx(options, isClassComponent); | ||
yield* generateTemplateComponents(options); | ||
yield* generateTemplateDirectives(options); | ||
yield* generateTemplateBody(options, templateCodegenCtx); | ||
return templateCodegenCtx; | ||
} | ||
function* generateTemplateBody(options, templateCodegenCtx) { | ||
@@ -164,10 +151,10 @@ const firstClasses = new Set(); | ||
yield `const __VLS_slots = {}${common_1.endOfLine}`; | ||
yield `const $refs = {}${common_1.endOfLine}`; | ||
yield `const __VLS_inheritedAttrs = {}${common_1.endOfLine}`; | ||
} | ||
yield `const $refs = {}${common_1.endOfLine}`; | ||
yield `const __VLS_inheritedAttrs = {}${common_1.endOfLine}`; | ||
} | ||
yield `const __VLS_templateResult = {`; | ||
yield `slots: ${options.scriptSetupRanges?.slots.name ?? '__VLS_slots'},${common_1.newLine}`; | ||
yield `refs: $refs,${common_1.newLine}`; | ||
yield `attrs: {} as Partial<typeof __VLS_inheritedAttrs>,${common_1.newLine}`; | ||
yield `return {${common_1.newLine}`; | ||
yield ` slots: ${options.scriptSetupRanges?.slots.name ?? '__VLS_slots'},${common_1.newLine}`; | ||
yield ` refs: $refs,${common_1.newLine}`; | ||
yield ` attrs: {} as Partial<typeof __VLS_inheritedAttrs>,${common_1.newLine}`; | ||
yield `}${common_1.endOfLine}`; | ||
@@ -207,3 +194,3 @@ } | ||
for (const cssBind of style.cssVars) { | ||
for (const [segment, offset, onlyError] of (0, interpolation_1.forEachInterpolationSegment)(options.ts, ctx, cssBind.text, cssBind.offset, options.ts.createSourceFile('/a.txt', cssBind.text, 99))) { | ||
for (const [segment, offset, onlyError] of (0, interpolation_1.forEachInterpolationSegment)(options.ts, undefined, ctx, cssBind.text, cssBind.offset, options.ts.createSourceFile('/a.txt', cssBind.text, 99))) { | ||
if (offset === undefined) { | ||
@@ -210,0 +197,0 @@ yield segment; |
@@ -44,2 +44,3 @@ import type * as CompilerDOM from '@vue/compiler-dom'; | ||
inheritedAttrVars: Set<unknown>; | ||
templateRefs: Map<string, [string, number]>; | ||
singleRootNode: CompilerDOM.ElementNode | undefined; | ||
@@ -46,0 +47,0 @@ accessExternalVariable(name: string, offset?: number): void; |
@@ -98,2 +98,3 @@ "use strict"; | ||
const inlayHints = []; | ||
const templateRefs = new Map(); | ||
return { | ||
@@ -112,2 +113,3 @@ slots, | ||
inheritedAttrVars: new Set(), | ||
templateRefs, | ||
singleRootNode: undefined, | ||
@@ -114,0 +116,0 @@ accessExternalVariable(name, offset) { |
@@ -156,5 +156,5 @@ "use strict"; | ||
const varName = ctx.getInternalVariable(); | ||
options.templateRefNames.set(refName, [varName, offset]); | ||
ctx.templateRefs.set(refName, [varName, offset]); | ||
ctx.usedComponentCtxVars.add(var_defineComponentCtx); | ||
yield `var ${varName} = {} as (Parameters<typeof ${var_defineComponentCtx}['expose']>[0] | null)`; | ||
yield `var ${varName} = {} as (Parameters<NonNullable<typeof ${var_defineComponentCtx}['expose']>>[0] | null)`; | ||
if (node.codegenNode?.type === CompilerDOM.NodeTypes.VNODE_CALL | ||
@@ -212,3 +212,3 @@ && node.codegenNode.props?.type === CompilerDOM.NodeTypes.JS_OBJECT_EXPRESSION | ||
if (refName) { | ||
options.templateRefNames.set(refName, [`__VLS_intrinsicElements['${node.tag}']`, offset]); | ||
ctx.templateRefs.set(refName, [`__VLS_nativeElements['${node.tag}']`, offset]); | ||
} | ||
@@ -365,3 +365,3 @@ const slotDir = node.props.find(p => p.type === CompilerDOM.NodeTypes.DIRECTIVE && p.name === 'slot'); | ||
const [content, startOffset] = normalizeAttributeValue(prop.value); | ||
yield `// @ts-ignore${common_1.newLine}`; | ||
yield `// @ts-ignore navigation for \`const ${content} = ref()\`${common_1.newLine}`; | ||
yield `__VLS_ctx`; | ||
@@ -368,0 +368,0 @@ yield* (0, propertyAccess_1.generatePropertyAccess)(options, ctx, content, startOffset, ctx.codeFeatures.navigation, prop.value.loc); |
@@ -24,3 +24,3 @@ "use strict"; | ||
} | ||
yield* (0, common_1.wrapWith)(prop.loc.start.offset, prop.loc.end.offset, ctx.codeFeatures.verification, `__VLS_directiveAsFunction(__VLS_ctx.`, ...(0, camelized_1.generateCamelized)('v-' + prop.name, prop.loc.start.offset, { | ||
yield* (0, common_1.wrapWith)(prop.loc.start.offset, prop.loc.end.offset, ctx.codeFeatures.verification, `__VLS_directiveAsFunction(__VLS_directives.`, ...(0, camelized_1.generateCamelized)('v-' + prop.name, prop.loc.start.offset, { | ||
...ctx.codeFeatures.all, | ||
@@ -27,0 +27,0 @@ verification: false, |
@@ -139,3 +139,6 @@ "use strict"; | ||
let result = true; | ||
if (ast.statements.length === 1) { | ||
if (ast.statements.length === 0) { | ||
result = false; | ||
} | ||
else if (ast.statements.length === 1) { | ||
ts.forEachChild(ast, child_1 => { | ||
@@ -142,0 +145,0 @@ if (ts.isExpressionStatement(child_1)) { |
@@ -102,3 +102,3 @@ "use strict"; | ||
}, prop.loc.name_2 ?? (prop.loc.name_2 = {}), shouldCamelize) | ||
: (0, common_1.wrapWith)(prop.loc.start.offset, prop.loc.start.offset + 'v-model'.length, ctx.codeFeatures.verification, propName)), `: (`, ...genereatePropExp(options, ctx, prop, prop.exp, ctx.codeFeatures.all, prop.arg?.loc.start.offset === prop.exp?.loc.start.offset, enableCodeFeatures), `)`); | ||
: (0, common_1.wrapWith)(prop.loc.start.offset, prop.loc.start.offset + 'v-model'.length, ctx.codeFeatures.verification, propName)), `: (`, ...generatePropExp(options, ctx, prop, prop.exp, ctx.codeFeatures.all, prop.arg?.loc.start.offset === prop.exp?.loc.start.offset, enableCodeFeatures), `)`); | ||
if (!enableCodeFeatures) { | ||
@@ -130,18 +130,5 @@ yield (0, muggle_string_1.toString)([...codes]); | ||
} | ||
const codeInfo = ctx.codeFeatures.withoutHighlightAndCompletion; | ||
const codes = (0, common_1.conditionWrapWith)(enableCodeFeatures, prop.loc.start.offset, prop.loc.end.offset, ctx.codeFeatures.verification, ...(0, objectProperty_1.generateObjectProperty)(options, ctx, prop.name, prop.loc.start.offset, shouldCamelize | ||
const codeInfo = shouldCamelize | ||
? { | ||
...codeInfo, | ||
verification: options.vueCompilerOptions.strictTemplates | ||
? codeInfo.verification | ||
: { | ||
shouldReport(_source, code) { | ||
if (String(code) === '2353' || String(code) === '2561') { | ||
return false; | ||
} | ||
return typeof codeInfo.verification === 'object' | ||
? codeInfo.verification.shouldReport?.(_source, code) ?? true | ||
: true; | ||
}, | ||
}, | ||
...ctx.codeFeatures.withoutHighlightAndCompletion, | ||
navigation: ctx.codeFeatures.withoutHighlightAndCompletion.navigation | ||
@@ -154,3 +141,19 @@ ? { | ||
} | ||
: ctx.codeFeatures.withoutHighlightAndCompletion, prop.loc.name_1 ?? (prop.loc.name_1 = {}), shouldCamelize), `: (`, ...(prop.value | ||
: { | ||
...ctx.codeFeatures.withoutHighlightAndCompletion, | ||
}; | ||
if (!options.vueCompilerOptions.strictTemplates) { | ||
const verification = codeInfo.verification; | ||
codeInfo.verification = { | ||
shouldReport(_source, code) { | ||
if (String(code) === '2353' || String(code) === '2561') { | ||
return false; | ||
} | ||
return typeof verification === 'object' | ||
? verification.shouldReport?.(_source, code) ?? true | ||
: true; | ||
}, | ||
}; | ||
} | ||
const codes = (0, common_1.conditionWrapWith)(enableCodeFeatures, prop.loc.start.offset, prop.loc.end.offset, ctx.codeFeatures.verification, ...(0, objectProperty_1.generateObjectProperty)(options, ctx, prop.name, prop.loc.start.offset, codeInfo, prop.loc.name_1 ?? (prop.loc.name_1 = {}), shouldCamelize), `: (`, ...(prop.value | ||
? generateAttrValue(prop.value, ctx.codeFeatures.all) | ||
@@ -188,3 +191,9 @@ : [`true`]), `)`); | ||
} | ||
function* genereatePropExp(options, ctx, prop, exp, features, isShorthand, enableCodeFeatures) { | ||
function* generatePropExp(options, ctx, prop, exp, features, isShorthand, enableCodeFeatures) { | ||
if (isShorthand && features.completion) { | ||
features = { | ||
...features, | ||
completion: undefined, | ||
}; | ||
} | ||
if (exp && exp.constType !== CompilerDOM.ConstantTypes.CAN_STRINGIFY) { // style='z-index: 2' will compile to {'z-index':'2'} | ||
@@ -191,0 +200,0 @@ if (!isShorthand) { // vue 3.4+ |
@@ -10,6 +10,6 @@ import * as CompilerDOM from '@vue/compiler-dom'; | ||
template: NonNullable<Sfc['template']>; | ||
edited: boolean; | ||
scriptSetupBindingNames: Set<string>; | ||
scriptSetupImportComponentNames: Set<string>; | ||
edited: boolean; | ||
templateRefNames: Map<string, [varName: string, offset: number]>; | ||
templateRefNames: Set<string>; | ||
hasDefineSlots?: boolean; | ||
@@ -16,0 +16,0 @@ slotsAssignName?: string; |
@@ -38,3 +38,3 @@ "use strict"; | ||
yield `const __VLS_refs = {${common_1.newLine}`; | ||
for (const [name, [varName, offset]] of options.templateRefNames) { | ||
for (const [name, [varName, offset]] of ctx.templateRefs) { | ||
yield* (0, stringLiteralKey_1.generateStringLiteralKey)(name, offset, ctx.codeFeatures.navigationAndCompletion); | ||
@@ -44,3 +44,3 @@ yield `: ${varName},${common_1.newLine}`; | ||
yield `}${common_1.endOfLine}`; | ||
yield `declare var $refs: typeof __VLS_refs${common_1.endOfLine}`; | ||
yield `var $refs!: typeof __VLS_refs${common_1.endOfLine}`; | ||
} | ||
@@ -47,0 +47,0 @@ function* generateSlotsType() { |
@@ -6,2 +6,2 @@ import type * as ts from 'typescript'; | ||
export declare function generateInterpolation(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, _code: string, astHolder: any, start: number | undefined, data: VueCodeInformation | ((offset: number) => VueCodeInformation) | undefined, prefix: string, suffix: string): Generator<Code>; | ||
export declare function forEachInterpolationSegment(ts: typeof import('typescript'), ctx: TemplateCodegenContext, code: string, offset: number | undefined, ast: ts.SourceFile): Generator<[fragment: string, offset: number | undefined, isJustForErrorMapping?: boolean]>; | ||
export declare function forEachInterpolationSegment(ts: typeof import('typescript'), templateRefNames: Set<string> | undefined, ctx: TemplateCodegenContext, code: string, offset: number | undefined, ast: ts.SourceFile): Generator<[fragment: string, offset: number | undefined, errorMappingOnly?: boolean]>; |
@@ -12,3 +12,3 @@ "use strict"; | ||
const vars = []; | ||
for (let [section, offset, onlyError] of forEachInterpolationSegment(options.ts, ctx, code, start !== undefined ? start - prefix.length : undefined, ast)) { | ||
for (let [section, offset, onlyError] of forEachInterpolationSegment(options.ts, options.templateRefNames, ctx, code, start !== undefined ? start - prefix.length : undefined, ast)) { | ||
if (offset === undefined) { | ||
@@ -52,3 +52,3 @@ yield section; | ||
} | ||
function* forEachInterpolationSegment(ts, ctx, code, offset, ast) { | ||
function* forEachInterpolationSegment(ts, templateRefNames, ctx, code, offset, ast) { | ||
let ctxVars = []; | ||
@@ -89,17 +89,16 @@ const varCb = (id, isShorthand) => { | ||
for (let i = 0; i < ctxVars.length - 1; i++) { | ||
// fix https://github.com/vuejs/language-tools/issues/1205 | ||
// fix https://github.com/vuejs/language-tools/issues/1264 | ||
yield ['', ctxVars[i + 1].offset, true]; | ||
yield ['__VLS_ctx.', undefined]; | ||
if (ctxVars[i + 1].isShorthand) { | ||
yield [code.substring(ctxVars[i].offset, ctxVars[i + 1].offset + ctxVars[i + 1].text.length), ctxVars[i].offset]; | ||
const curVar = ctxVars[i]; | ||
const nextVar = ctxVars[i + 1]; | ||
yield* generateVar(code, templateRefNames, curVar, nextVar); | ||
if (nextVar.isShorthand) { | ||
yield [code.substring(curVar.offset + curVar.text.length, nextVar.offset + nextVar.text.length), curVar.offset + curVar.text.length]; | ||
yield [': ', undefined]; | ||
} | ||
else { | ||
yield [code.substring(ctxVars[i].offset, ctxVars[i + 1].offset), ctxVars[i].offset]; | ||
yield [code.substring(curVar.offset + curVar.text.length, nextVar.offset), curVar.offset + curVar.text.length]; | ||
} | ||
} | ||
yield ['', ctxVars[ctxVars.length - 1].offset, true]; | ||
yield ['__VLS_ctx.', undefined]; | ||
yield [code.substring(ctxVars[ctxVars.length - 1].offset), ctxVars[ctxVars.length - 1].offset]; | ||
const lastVar = ctxVars.at(-1); | ||
yield* generateVar(code, templateRefNames, lastVar); | ||
yield [code.substring(lastVar.offset + lastVar.text.length), lastVar.offset + lastVar.text.length]; | ||
} | ||
@@ -110,2 +109,17 @@ else { | ||
} | ||
function* generateVar(code, templateRefNames, curVar, nextVar = curVar) { | ||
// fix https://github.com/vuejs/language-tools/issues/1205 | ||
// fix https://github.com/vuejs/language-tools/issues/1264 | ||
yield ['', nextVar.offset, true]; | ||
const isTemplateRef = templateRefNames?.has(curVar.text) ?? false; | ||
if (isTemplateRef) { | ||
yield [`__VLS_unref(`, undefined]; | ||
yield [code.substring(curVar.offset, curVar.offset + curVar.text.length), curVar.offset]; | ||
yield [`)`, undefined]; | ||
} | ||
else { | ||
yield [`__VLS_ctx.`, undefined]; | ||
yield [code.substring(curVar.offset, curVar.offset + curVar.text.length), curVar.offset]; | ||
} | ||
} | ||
function walkIdentifiers(ts, node, ast, cb, ctx, blockVars = [], isRoot = true) { | ||
@@ -112,0 +126,0 @@ if (ts.isIdentifier(node)) { |
@@ -12,2 +12,3 @@ import type { TextRange } from '../types'; | ||
componentsOptionNode: ts.ObjectLiteralExpression | undefined; | ||
directivesOption: TextRange | undefined; | ||
nameOption: TextRange | undefined; | ||
@@ -14,0 +15,0 @@ inheritAttrsOption: string | undefined; |
@@ -27,2 +27,3 @@ "use strict"; | ||
let componentsOptionNode; | ||
let directivesOptionNode; | ||
let nameOptionNode; | ||
@@ -36,6 +37,9 @@ let inheritAttrsOption; | ||
} | ||
if (name === 'name') { | ||
else if (name === 'directives' && ts.isObjectLiteralExpression(node.initializer)) { | ||
directivesOptionNode = node.initializer; | ||
} | ||
else if (name === 'name') { | ||
nameOptionNode = node.initializer; | ||
} | ||
if (name === 'inheritAttrs') { | ||
else if (name === 'inheritAttrs') { | ||
inheritAttrsOption = (0, scriptSetupRanges_1.getNodeText)(ts, node.initializer, ast); | ||
@@ -52,2 +56,3 @@ } | ||
componentsOptionNode: withNode ? componentsOptionNode : undefined, | ||
directivesOption: directivesOptionNode ? _getStartEnd(directivesOptionNode) : undefined, | ||
nameOption: nameOptionNode ? _getStartEnd(nameOptionNode) : undefined, | ||
@@ -54,0 +59,0 @@ inheritAttrsOption, |
@@ -299,3 +299,3 @@ "use strict"; | ||
} | ||
else if (vueCompilerOptions.macros.templateRef.includes(callText) && node.arguments.length && !node.typeArguments?.length) { | ||
else if (vueCompilerOptions.composibles.useTemplateRef.includes(callText) && node.arguments.length && !node.typeArguments?.length) { | ||
const define = parseDefineFunction(node); | ||
@@ -302,0 +302,0 @@ define.arg = _getStartEnd(node.arguments[0]); |
@@ -8,3 +8,3 @@ "use strict"; | ||
getEmbeddedCodes(_fileName, sfc) { | ||
if (sfc.template) { | ||
if (sfc.template?.lang === 'html') { | ||
return [{ | ||
@@ -18,3 +18,3 @@ id: 'template', | ||
resolveEmbeddedCode(_fileName, sfc, embeddedFile) { | ||
if (embeddedFile.id === 'template' && sfc.template) { | ||
if (embeddedFile.id === 'template' && sfc.template?.lang === 'html') { | ||
embeddedFile.content.push([ | ||
@@ -21,0 +21,0 @@ sfc.template.content, |
@@ -11,2 +11,3 @@ import type { Mapping } from '@volar/language-core'; | ||
componentsOptionNode: import("typescript").ObjectLiteralExpression | undefined; | ||
directivesOption: import("../types").TextRange | undefined; | ||
nameOption: import("../types").TextRange | undefined; | ||
@@ -147,2 +148,3 @@ inheritAttrsOption: string | undefined; | ||
inheritedAttrVars: Set<unknown>; | ||
templateRefs: Map<string, [string, number]>; | ||
singleRootNode: import("@vue/compiler-dom").ElementNode | undefined; | ||
@@ -149,0 +151,0 @@ accessExternalVariable(name: string, offset?: number): void; |
@@ -5,3 +5,3 @@ "use strict"; | ||
const computeds_1 = require("computeds"); | ||
const path = require("path-browserify"); | ||
const path_browserify_1 = require("path-browserify"); | ||
const script_1 = require("../codegen/script"); | ||
@@ -14,2 +14,3 @@ const template_1 = require("../codegen/template"); | ||
const plugin = ctx => { | ||
let appendedGlobalTypes = false; | ||
return { | ||
@@ -43,3 +44,8 @@ version: 2.1, | ||
if (!exports.tsCodegen.has(sfc)) { | ||
exports.tsCodegen.set(sfc, createTsx(fileName, sfc, ctx)); | ||
let appendGlobalTypes = false; | ||
if (!ctx.vueCompilerOptions.__setupedGlobalTypes && !appendedGlobalTypes) { | ||
appendGlobalTypes = true; | ||
appendedGlobalTypes = true; | ||
} | ||
exports.tsCodegen.set(sfc, createTsx(fileName, sfc, ctx, appendGlobalTypes)); | ||
} | ||
@@ -50,3 +56,3 @@ return exports.tsCodegen.get(sfc); | ||
exports.default = plugin; | ||
function createTsx(fileName, _sfc, ctx) { | ||
function createTsx(fileName, _sfc, ctx, appendGlobalTypes) { | ||
const ts = ctx.modules.typescript; | ||
@@ -66,3 +72,3 @@ const lang = (0, computeds_1.computed)(() => { | ||
const generatedTemplate = (0, computeds_1.computed)(() => { | ||
if (!_sfc.template) { | ||
if (ctx.vueCompilerOptions.skipTemplateCodegen || !_sfc.template) { | ||
return; | ||
@@ -79,3 +85,3 @@ } | ||
scriptSetupImportComponentNames: scriptSetupImportComponentNames(), | ||
templateRefNames: new Map(), | ||
templateRefNames: templateRefNames(), | ||
hasDefineSlots: hasDefineSlots(), | ||
@@ -97,3 +103,2 @@ slotsAssignName: slotsAssignName(), | ||
}); | ||
const hasDefineSlots = (0, computeds_1.computed)(() => !!scriptSetupRanges()?.slots.define); | ||
const scriptSetupBindingNames = (0, computeds_1.computed)(oldNames => { | ||
@@ -114,3 +119,3 @@ const newNames = new Set(); | ||
const newNames = scriptSetupRanges()?.importComponentNames ?? new Set(); | ||
if (newNames && oldNames && twoSetsEqual(newNames, oldNames)) { | ||
if (oldNames && twoSetsEqual(newNames, oldNames)) { | ||
return oldNames; | ||
@@ -120,2 +125,12 @@ } | ||
}); | ||
const templateRefNames = (0, computeds_1.computed)(oldNames => { | ||
const newNames = new Set(scriptSetupRanges()?.templateRefs | ||
.map(({ name }) => name) | ||
.filter(name => name !== undefined)); | ||
if (oldNames && twoSetsEqual(newNames, oldNames)) { | ||
return oldNames; | ||
} | ||
return newNames; | ||
}); | ||
const hasDefineSlots = (0, computeds_1.computed)(() => !!scriptSetupRanges()?.slots.define); | ||
const slotsAssignName = (0, computeds_1.computed)(() => scriptSetupRanges()?.slots.name); | ||
@@ -130,7 +145,6 @@ const propsAssignName = (0, computeds_1.computed)(() => scriptSetupRanges()?.props.name); | ||
const linkedCodeMappings = []; | ||
const _template = generatedTemplate(); | ||
let generatedLength = 0; | ||
const codegen = (0, script_1.generateScript)({ | ||
ts, | ||
fileBaseName: path.basename(fileName), | ||
fileBaseName: path_browserify_1.posix.basename(fileName), | ||
sfc: _sfc, | ||
@@ -140,3 +154,3 @@ lang: lang(), | ||
scriptSetupRanges: scriptSetupRanges(), | ||
templateCodegen: _template, | ||
templateCodegen: generatedTemplate(), | ||
compilerOptions: ctx.compilerOptions, | ||
@@ -147,2 +161,3 @@ vueCompilerOptions: ctx.vueCompilerOptions, | ||
linkedCodeMappings, | ||
appendGlobalTypes, | ||
}); | ||
@@ -149,0 +164,0 @@ fileEditTimes.set(fileName, (fileEditTimes.get(fileName) ?? 0) + 1); |
@@ -39,6 +39,6 @@ import type { CodeInformation } from '@volar/language-core'; | ||
withDefaults: string[]; | ||
templateRef: string[]; | ||
}; | ||
composibles: { | ||
useCssModule: string[]; | ||
useTemplateRef: string[]; | ||
}; | ||
@@ -49,3 +49,3 @@ plugins: VueLanguagePlugin[]; | ||
experimentalModelPropName: Record<string, Record<string, boolean | Record<string, string> | Record<string, string>[]>>; | ||
__setupedGlobalTypes?: () => boolean; | ||
__setupedGlobalTypes?: boolean; | ||
__test?: boolean; | ||
@@ -52,0 +52,0 @@ } |
@@ -6,4 +6,10 @@ import type * as ts from 'typescript'; | ||
}; | ||
export declare function createParsedCommandLineByJson(ts: typeof import('typescript'), parseConfigHost: ts.ParseConfigHost, rootDir: string, json: any, configFileName?: string): ParsedCommandLine; | ||
export declare function createParsedCommandLine(ts: typeof import('typescript'), parseConfigHost: ts.ParseConfigHost, tsConfigPath: string): ParsedCommandLine; | ||
export declare function createParsedCommandLineByJson(ts: typeof import('typescript'), parseConfigHost: ts.ParseConfigHost & { | ||
writeFile?(path: string, data: string): void; | ||
}, rootDir: string, json: any, configFileName?: string, skipGlobalTypesSetup?: boolean): ParsedCommandLine; | ||
export declare function createParsedCommandLine(ts: typeof import('typescript'), parseConfigHost: ts.ParseConfigHost, tsConfigPath: string, skipGlobalTypesSetup?: boolean): ParsedCommandLine; | ||
export declare function resolveVueCompilerOptions(vueOptions: Partial<VueCompilerOptions>): VueCompilerOptions; | ||
export declare function setupGlobalTypes(rootDir: string, vueOptions: VueCompilerOptions, host: { | ||
fileExists(path: string): boolean; | ||
writeFile?(path: string, data: string): void; | ||
}): boolean; |
@@ -6,6 +6,8 @@ "use strict"; | ||
exports.resolveVueCompilerOptions = resolveVueCompilerOptions; | ||
exports.setupGlobalTypes = setupGlobalTypes; | ||
const shared_1 = require("@vue/shared"); | ||
const path = require("path-browserify"); | ||
const path_browserify_1 = require("path-browserify"); | ||
const languagePlugin_1 = require("../languagePlugin"); | ||
function createParsedCommandLineByJson(ts, parseConfigHost, rootDir, json, configFileName = rootDir + '/jsconfig.json') { | ||
const globalTypes_1 = require("../codegen/globalTypes"); | ||
function createParsedCommandLineByJson(ts, parseConfigHost, rootDir, json, configFileName = rootDir + '/jsconfig.json', skipGlobalTypesSetup = false) { | ||
const proxyHost = proxyParseConfigHostForExtendConfigPaths(parseConfigHost); | ||
@@ -24,2 +26,8 @@ ts.parseJsonConfigFileContent(json, proxyHost.host, rootDir, {}, configFileName); | ||
const resolvedVueOptions = resolveVueCompilerOptions(vueOptions); | ||
if (skipGlobalTypesSetup) { | ||
resolvedVueOptions.__setupedGlobalTypes = true; | ||
} | ||
else { | ||
resolvedVueOptions.__setupedGlobalTypes = setupGlobalTypes(rootDir, resolvedVueOptions, parseConfigHost); | ||
} | ||
const parsed = ts.parseJsonConfigFileContent(json, proxyHost.host, rootDir, {}, configFileName, undefined, (0, languagePlugin_1.getAllExtensions)(resolvedVueOptions) | ||
@@ -40,7 +48,7 @@ .map(extension => ({ | ||
} | ||
function createParsedCommandLine(ts, parseConfigHost, tsConfigPath) { | ||
function createParsedCommandLine(ts, parseConfigHost, tsConfigPath, skipGlobalTypesSetup = false) { | ||
try { | ||
const proxyHost = proxyParseConfigHostForExtendConfigPaths(parseConfigHost); | ||
const config = ts.readJsonConfigFile(tsConfigPath, proxyHost.host.readFile); | ||
ts.parseJsonSourceFileConfigFileContent(config, proxyHost.host, path.dirname(tsConfigPath), {}, tsConfigPath); | ||
ts.parseJsonSourceFileConfigFileContent(config, proxyHost.host, path_browserify_1.posix.dirname(tsConfigPath), {}, tsConfigPath); | ||
let vueOptions = {}; | ||
@@ -57,3 +65,9 @@ for (const extendPath of proxyHost.extendConfigPaths.reverse()) { | ||
const resolvedVueOptions = resolveVueCompilerOptions(vueOptions); | ||
const parsed = ts.parseJsonSourceFileConfigFileContent(config, proxyHost.host, path.dirname(tsConfigPath), {}, tsConfigPath, undefined, (0, languagePlugin_1.getAllExtensions)(resolvedVueOptions) | ||
if (skipGlobalTypesSetup) { | ||
resolvedVueOptions.__setupedGlobalTypes = true; | ||
} | ||
else { | ||
resolvedVueOptions.__setupedGlobalTypes = setupGlobalTypes(path_browserify_1.posix.dirname(tsConfigPath), resolvedVueOptions, parseConfigHost); | ||
} | ||
const parsed = ts.parseJsonSourceFileConfigFileContent(config, proxyHost.host, path_browserify_1.posix.dirname(tsConfigPath), {}, tsConfigPath, undefined, (0, languagePlugin_1.getAllExtensions)(resolvedVueOptions) | ||
.map(extension => ({ | ||
@@ -104,3 +118,3 @@ extension: extension.slice(1), | ||
function getPartialVueCompilerOptions(ts, tsConfigSourceFile) { | ||
const folder = path.dirname(tsConfigSourceFile.fileName); | ||
const folder = path_browserify_1.posix.dirname(tsConfigSourceFile.fileName); | ||
const obj = ts.convertToObject(tsConfigSourceFile, []); | ||
@@ -189,7 +203,8 @@ const rawOptions = obj?.vueCompilerOptions ?? {}; | ||
withDefaults: ['withDefaults'], | ||
templateRef: ['templateRef', 'useTemplateRef'], | ||
...vueOptions.macros, | ||
}, | ||
composibles: { | ||
useCssModule: ['useCssModule'] | ||
useCssModule: ['useCssModule'], | ||
useTemplateRef: ['useTemplateRef', 'templateRef'], | ||
...vueOptions.composibles, | ||
}, | ||
@@ -214,2 +229,24 @@ plugins: vueOptions.plugins ?? [], | ||
} | ||
function setupGlobalTypes(rootDir, vueOptions, host) { | ||
if (!host.writeFile) { | ||
return false; | ||
} | ||
try { | ||
let dir = rootDir; | ||
while (!host.fileExists(path_browserify_1.posix.join(dir, 'node_modules', vueOptions.lib, 'package.json'))) { | ||
const parentDir = path_browserify_1.posix.dirname(dir); | ||
if (dir === parentDir) { | ||
throw 0; | ||
} | ||
dir = parentDir; | ||
} | ||
const globalTypesPath = path_browserify_1.posix.join(dir, 'node_modules', '.vue-global-types', `${vueOptions.lib}_${vueOptions.target}_${vueOptions.strictTemplates}.d.ts`); | ||
const globalTypesContents = `// @ts-nocheck\nexport {};\n` + (0, globalTypes_1.generateGlobalTypes)(vueOptions.lib, vueOptions.target, vueOptions.strictTemplates); | ||
host.writeFile(globalTypesPath, globalTypesContents); | ||
return true; | ||
} | ||
catch { | ||
return false; | ||
} | ||
} | ||
//# sourceMappingURL=ts.js.map |
{ | ||
"name": "@vue/language-core", | ||
"version": "2.1.5", | ||
"version": "2.1.6", | ||
"license": "MIT", | ||
@@ -39,3 +39,3 @@ "files": [ | ||
}, | ||
"gitHead": "a95b51ac0b0db8825f77fbba37e29932b5be61e4" | ||
"gitHead": "fd61953ce9eb924eeaf4df0bf8d2237267321194" | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
0
328447
126
7386