Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add vue support #45

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,16 @@ module.exports = {
"**/.vscode-test/**",
"packages/typescript-explorer-vscode/src/test/**",
"scripts/**",
"packages/api/tsup.config.ts",
],
root: true,
rules: {
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-duplicate-enum-values": "off",
"@typescript-eslint/no-floating-promises": "off",
"import/no-extraneous-dependencies": [
"error",
"warn",
{
devDependencies: false,
},
Expand Down
11 changes: 10 additions & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@
"version": "0.4.0",
"type": "commonjs",
"license": "MIT",
"scripts": {
"build": "tsup"
},
"devDependencies": {
"typescript": "^4.8.4"
"@volar/language-core": "^2.4.8",
"@volar/typescript": "^2.4.8",
"@vue/language-core": "^2.1.8",
"typescript": "^5.3.0"
},
"dependencies": {
"tsup": "7.2.0"
}
}
2 changes: 1 addition & 1 deletion packages/api/src/resolveTree.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as assert from "assert"
import assert from "assert"
import {
LocalizedTypeInfo,
LocalizedTypeInfoOrError,
Expand Down
65 changes: 58 additions & 7 deletions packages/api/src/tree.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable prefer-const */
import * as assert from "assert"
import type * as ts from "typescript"
import assert from "assert"
import * as ts from "typescript"
import { configDefaults } from "./config"
import {
wrapSafe,
Expand Down Expand Up @@ -64,6 +64,7 @@ import {
getAliasedSymbol,
getDescendantAtPosition,
} from "./util"
import { getPositionOfLineAndCharacterForVue } from "./vue"

const maxDepthExceeded: TypeInfo = { kind: "max_depth", id: getEmptyTypeId() }

Expand Down Expand Up @@ -1026,12 +1027,27 @@ export function getTypeInfoAtRange(
apiConfig?: Partial<APIConfig>
) {
const sourceFile = ctx.program.getSourceFile(location.fileName)

if (!sourceFile) return undefined

const startPos = sourceFile.getPositionOfLineAndCharacter(
location.range.start.line,
location.range.start.character
)
const rawStartPos =
sourceFile.getPositionOfLineAndCharacter(
location.range.start.line,
location.range.start.character
) || -1

let startPos = rawStartPos
let fixLocation: (startPos: number) => ts.LineAndCharacter | undefined
if (location.fileName.endsWith(".vue")) {
const [_startPos, _fixLocation] = getPositionOfLineAndCharacterForVue(
{ ...ctx, sourceFile },
location,
startPos
)
startPos = _startPos
fixLocation = _fixLocation
console.log(startPos, rawStartPos)
}

// TODO: integrate this
// getDescendantAtRange will probably need to be improved...
Expand All @@ -1046,7 +1062,41 @@ export function getTypeInfoAtRange(
return undefined
}

return getTypeInfoOfNode(ctx, node, apiConfig)
const typeInfoAtRange = getTypeInfoOfNode(ctx, node, apiConfig)

function updateLocation(
typeInfoAtRange: TypeInfo,
sourceFile: ts.SourceFile
) {
const typeLocation =
typeInfoAtRange?.symbolMeta?.declarations?.[0].location
if (typeLocation && typeLocation.fileName === location.fileName) {
const newStartPos = sourceFile.getPositionOfLineAndCharacter(
typeLocation.range.start.line,
typeLocation.range.start.character
)
const newEndPos = sourceFile.getPositionOfLineAndCharacter(
typeLocation.range.end.line,
typeLocation.range.end.character
)

typeLocation.range.start =
fixLocation(newStartPos) ?? typeLocation.range.start
typeLocation.range.end =
fixLocation(newEndPos) ?? typeLocation.range.end
}
if ("properties" in typeInfoAtRange) {
typeInfoAtRange.properties?.forEach((property) => {
updateLocation(property, sourceFile)
})
}
}

if (typeInfoAtRange && location.fileName.endsWith(".vue")) {
updateLocation(typeInfoAtRange, sourceFile)
}

return typeInfoAtRange
}

export function getTypeInfoOfNode(
Expand All @@ -1059,6 +1109,7 @@ export function getTypeInfoOfNode(
}

const symbolOrType = getSymbolOrTypeOfNode(ctx, node)

if (!symbolOrType) return undefined

return generateTypeTree(symbolOrType, ctx, apiConfig)
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/typescript.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ts = require("typescript")
import type * as ts from "typescript"
import { TypescriptContext } from "./types"

/**
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ export function checkExpression(ctx: TypescriptContext, node: ts.Node) {
},
} as unknown as ts.Declaration
symbol.valueDeclaration = declaration

// @ts-expect-error ts will get `symbol.links.checkFlags` but `symbol.links` will be `undefined`
if (!symbol.links) return undefined
const type = typeChecker.getTypeOfSymbolAtLocation(symbol, {
parent: {},
} as unknown as ts.Node)
Expand Down Expand Up @@ -769,6 +770,7 @@ export function getDescendantAtRange(
node: sourceFile,
start: sourceFile.getStart(sourceFile),
}

searchDescendants(sourceFile)
return bestMatch.node

Expand Down
135 changes: 135 additions & 0 deletions packages/api/src/vue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/* eslint-disable import/no-extraneous-dependencies */
import type * as ts from "typescript/lib/tsserverlibrary"
import { type Language } from "@volar/language-core"
import {
proxyCreateProgram,
type TypeScriptServiceScript,
} from "@volar/typescript"
import {
VueCompilerOptions,
createParsedCommandLine,
resolveVueCompilerOptions,
createVueLanguagePlugin,
} from "@vue/language-core"
import { SourceFileLocation, TypescriptContext } from "./types"

const windowsPathReg = /\\/g

type VuePrograme = ts.Program & {
// https://github.com/volarjs/volar.js/blob/v2.2.0/packages/typescript/lib/node/proxyCreateProgram.ts#L209
__volar__?: { language: Language }
// https://github.com/vuejs/language-tools/blob/v2.0.16/packages/typescript-plugin/index.ts#L75
__vue__?: { language: Language }
}

let tsPrograme: VuePrograme | undefined

function getMappingOffset(
language: Language,
serviceScript: TypeScriptServiceScript
) {
if (serviceScript.preventLeadingOffset) {
return 0
}
const sourceScript = language.scripts.fromVirtualCode(serviceScript.code)
return sourceScript.snapshot.getLength()
}

export function getPositionOfLineAndCharacterForVue(
ctx: TypescriptContext & { sourceFile: ts.SourceFile },
location: SourceFileLocation,
startPos = -1
) {
const fileName = location.fileName

const compilerOptions = {
...ctx.program.getCompilerOptions(),
rootDir: ctx.program.getCurrentDirectory(),
declaration: true,
emitDeclarationOnly: true,
allowNonTsExtensions: true,
}

const options: ts.CreateProgramOptions = {
host: ctx.ts.createCompilerHost(compilerOptions),
rootNames: ctx.program.getRootFileNames(),
options: compilerOptions,
oldProgram: ctx.program,
}

let vueOptions: VueCompilerOptions
const createProgram = proxyCreateProgram(
ctx.ts,
ctx.ts.createProgram,
(ts, _options) => {
const { configFilePath } = _options.options
vueOptions =
typeof configFilePath === "string"
? createParsedCommandLine(
ts,
ts.sys,
configFilePath.replace(windowsPathReg, "/")
).vueOptions
: resolveVueCompilerOptions({
extensions: [".vue", ".cext"],
})
const vueLanguagePlugin = createVueLanguagePlugin<string>(
ts,
options.options,
vueOptions,
(id) => id
)
return [vueLanguagePlugin]
}
)

tsPrograme = ctx.program

if (!(tsPrograme?.__vue__ || tsPrograme?.__volar__)) {
console.log("create vue program")
tsPrograme = createProgram(options) as VuePrograme
}

let fixLocation = (startPos: number) =>
undefined as ts.LineAndCharacter | undefined

const language = (tsPrograme.__volar__ || tsPrograme.__vue__)?.language
if (language?.scripts) {
const vFile = language.scripts.get(fileName)
const serviceScript =
vFile?.generated?.languagePlugin.typescript?.getServiceScript(
vFile.generated.root
)
if (vFile?.generated?.root?.languageId === "vue" && serviceScript) {
const sourceMap = language.maps.get(serviceScript.code, vFile)

const snapshotLength = getMappingOffset(language, serviceScript)

for (const [generatedLocation] of sourceMap.toGeneratedLocation(
startPos
)) {
if (generatedLocation) {
startPos = generatedLocation + snapshotLength
}
}

fixLocation = (startPos: number) => {
for (const [sourceLocation] of sourceMap.toSourceLocation(
startPos - snapshotLength
)) {
if (sourceLocation) {
const restoreLocation =
ctx.sourceFile.getLineAndCharacterOfPosition(
sourceLocation
)
return restoreLocation
}
}

return undefined
}
}
}

return [startPos, fixLocation] as const
}
4 changes: 3 additions & 1 deletion packages/api/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
{
"compilerOptions": {
"target": "es2017",
"lib": ["es2021"],
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"noImplicitAny": true,
"noFallthroughCasesInSwitch": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"outDir": "./dist",
"outDir": "./out",
"stripInternal": true
},
"exclude": ["node_modules", "dist"],
Expand Down
15 changes: 15 additions & 0 deletions packages/api/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { defineConfig } from "tsup"

export default defineConfig({
entry: ["src/index.ts"],
outDir: "dist",
splitting: false,
sourcemap: true,
clean: true,
dts: true,
format: ["cjs", "esm"],
external: [
// 'assert',
"typescript",
],
})
9 changes: 8 additions & 1 deletion packages/typescript-explorer-vscode/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,14 @@ async function getQuickInfoAtPosition(
"quickinfo-full",
toFileLocationRequestArgs(fileName, position)
)
.then((r) => (r as Proto.QuickInfoResponse).body)
.then(
(r) => (r as Proto.QuickInfoResponse).body,
(e) => {
if (!fileName.endsWith(".vue")) {
throw e
}
}
)
}

async function customTypescriptRequest<Id extends CustomTypeScriptRequestId>(
Expand Down
3 changes: 2 additions & 1 deletion packages/typescript-explorer-vscode/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export function isDocumentSupported({ languageId }: vscode.TextDocument) {
languageId === "typescript" ||
languageId === "javascript" ||
languageId === "typescriptreact" ||
languageId === "javascriptreact"
languageId === "javascriptreact" ||
languageId === "vue"
)
}
Loading