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(ts-type-expand-plugin): support vue language #393

Merged
merged 2 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"typecheck",
"ununsed",
"Varibale",
"vsix"
"vsix",
"cext"
],
"ignorePaths": ["pnpm-lock.yaml", ".vscode/settings.json"]
}
4 changes: 4 additions & 0 deletions packages/ts-type-expand-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
"@types/express": "^4.17.21",
"@typescript-eslint/eslint-plugin": "^7.9.0",
"@typescript-eslint/parser": "^7.9.0",
"@volar/language-core": "^2.2.4",
"@volar/source-map": "^2.2.4",
"@volar/typescript": "^2.2.4",
"@vue/language-core": "^2.0.18",
"compiler-api-helper": "workspace:*",
"eslint": "^9.2.0",
"eslint-config": "workspace:*",
Expand Down
3 changes: 2 additions & 1 deletion packages/ts-type-expand-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { server } from 'typescript/lib/tsserverlibrary.js'
import { logger } from './logger.js'
import { pluginConfigurationSchema } from './schema.js'
import { registerApp } from './server/app.js'
import { setCreateInfo } from './server/context.js'
import { setCreateInfo, setTypescript } from './server/context.js'
zcf0508 marked this conversation as resolved.
Show resolved Hide resolved

const factory: server.PluginModuleFactory = (_mod) => {
let server: Server | undefined
Expand All @@ -20,6 +20,7 @@ const factory: server.PluginModuleFactory = (_mod) => {
})

setCreateInfo(info)
setTypescript(_mod.typescript)
zcf0508 marked this conversation as resolved.
Show resolved Hide resolved

if (isInitialized) {
return info.languageService
Expand Down
16 changes: 16 additions & 0 deletions packages/ts-type-expand-plugin/src/server/context.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
import type { Program } from 'typescript'
import type { server } from 'typescript/lib/tsserverlibrary.js'

export type __ts = Parameters<server.PluginModuleFactory>[0]['typescript']

export type Context = {
program: Program | undefined
createInfo: server.PluginCreateInfo | undefined
ts: __ts | undefined
}

export const { setTypescript, getTypescript } = (() => {
let ts: __ts | undefined = undefined

return {
setTypescript: (_ts: __ts) => {
ts = _ts
},
getTypescript: (): __ts | undefined => ts,
}
})()
zcf0508 marked this conversation as resolved.
Show resolved Hide resolved

export const { setCreateInfo, getCreateInfo } = (() => {
let createInfo: server.PluginCreateInfo | undefined = undefined

Expand All @@ -19,10 +33,12 @@ export const { setCreateInfo, getCreateInfo } = (() => {

export const createContext = async (): Promise<Context> => {
const createInfo = getCreateInfo()
const ts = getTypescript()
zcf0508 marked this conversation as resolved.
Show resolved Hide resolved
const program = createInfo?.languageService.getProgram()

return {
createInfo,
program,
ts,
}
}
2 changes: 1 addition & 1 deletion packages/ts-type-expand-plugin/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const requiredProgramMiddleware = t.middleware(({ ctx, next }) => {
return previousHandler
}

return new CompilerHandler(ctx.program)
return new CompilerHandler(ctx.program, ctx.ts)
})()

setCompilerHandler(compilerHandler)
Expand Down
21 changes: 19 additions & 2 deletions packages/ts-type-expand-plugin/src/service/compiler-api-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@ import {
} from 'typescript'
import type { TypeObject } from 'compiler-api-helper'
import type * as ts from 'typescript'
import type { __ts } from '../server/context.js'
import { getPositionOfLineAndCharacterForVue } from './vue.js'

export class CompilerHandler {
private checker: ts.TypeChecker
private helper: CompilerApiHelper

public constructor(private program: ts.Program) {
public constructor(
private program: ts.Program,
private ts: __ts | undefined,
) {
this.checker = this.program.getTypeChecker()
this.helper = new CompilerApiHelper(this.program)
}
Expand Down Expand Up @@ -45,7 +50,19 @@ export class CompilerHandler {
throw new Error(`File extension is not supported: ${filePath}`)
}
}
const pos = getPositionOfLineAndCharacter(sourceFile, lineNumber, character)
let pos = getPositionOfLineAndCharacter(sourceFile, lineNumber, character)

if (filePath.endsWith('.vue')) {
pos = getPositionOfLineAndCharacterForVue(
{
program: this.program,
ts: this.ts,
},
filePath,
pos,
)
}

const maybeNode = this.getNodeFromPos(sourceFile, pos)

if (!maybeNode) {
Expand Down
140 changes: 140 additions & 0 deletions packages/ts-type-expand-plugin/src/service/vue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import type * as ts from 'typescript/lib/tsserverlibrary.js'
import type {
CodeInformation,
SourceMap,
SourceScript,
} from '@volar/language-core'
import { type Language } from '@volar/language-core'
import { proxyCreateProgram } from '@volar/typescript'
import type { VueCompilerOptions } from '@vue/language-core'
import {
createParsedCommandLine,
createVueLanguagePlugin,
resolveVueCompilerOptions,
} from '@vue/language-core'
import * as SourceMaps from '@volar/source-map'
import type { __ts } from '../server/context.js'

const windowsPathReg = /\\/g

type VueProgram = 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 oldProgram: VueProgram | undefined

export function getPositionOfLineAndCharacterForVue(
ctx: {
program: ts.Program
ts: __ts | undefined
},
fileName: string,
startPos = -1,
) {
const compilerOptions = {
...ctx.program.getCompilerOptions(),
rootDir: ctx.program.getCurrentDirectory(),
declaration: true,
emitDeclarationOnly: true,
allowNonTsExtensions: true,
}

oldProgram = oldProgram ?? ctx.program

if (!oldProgram.__vue__ && !oldProgram.__volar__) {
if (!ctx.ts) {
return startPos
}

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

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'],
})
return [
createVueLanguagePlugin(
ts,
(id) => id,
_options.host?.useCaseSensitiveFileNames() ?? false,
() => '',
() =>
_options.rootNames.map((rootName) =>
rootName.replace(windowsPathReg, '/'),
),
_options.options,
vueOptions,
),
]
},
)

console.log('create vue program')
oldProgram = createProgram(options) as VueProgram
}

const language = (oldProgram.__volar__ ?? oldProgram.__vue__)?.language
if (language?.scripts) {
const vFile = language.scripts.get(fileName)
if (vFile?.generated?.root && vFile.generated.root.languageId === 'vue') {
const code = vFile.generated.root.embeddedCodes?.[0]
if (code) {
const sourceMap = new SourceMaps.SourceMap(code.mappings)

const serviceScript =
vFile.generated.languagePlugin.typescript?.getServiceScript(
vFile.generated.root,
)
if (serviceScript) {
const map = language.maps.get(serviceScript.code, vFile.id)
if (map) {
for (const [generatedOffset, mapping] of toGeneratedOffsets(
vFile,
map,
startPos,
)) {
console.log(JSON.stringify({ generatedOffset, mapping }))
zcf0508 marked this conversation as resolved.
Show resolved Hide resolved
}

startPos =
(sourceMap.getGeneratedOffset(startPos)?.[0] ?? -1) +
// https://github.com/volarjs/volar.js/blob/v2.2.0-alpha.12/packages/typescript/lib/node/proxyCreateProgram.ts#L143
(vFile.generated.root.snapshot.getLength() || 0)
}
}
}
}
}

return startPos
}

function* toGeneratedOffsets(
sourceScript: SourceScript,
map: SourceMap<CodeInformation>,
position: number,
) {
for (const [generateOffset, mapping] of map.getGeneratedOffsets(position)) {
yield [generateOffset + sourceScript.snapshot.getLength(), mapping] as const
}
}
3 changes: 2 additions & 1 deletion packages/ts-type-expand/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
"typescript",
"typescriptreact",
"javascript",
"javascriptreact"
"javascriptreact",
"vue"
]
},
"ts-type-expand.compactOptionalType": {
Expand Down
1 change: 1 addition & 0 deletions packages/ts-type-expand/src/types/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type ExtensionOption = {
| 'typescriptreact'
| 'javascript'
| 'javascriptreact'
| 'vue'
// eslint-disable-next-line @typescript-eslint/ban-types
| (string & {})
)[]
Expand Down
Loading