@sparknest/ui-build-vue 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import ts from 'typescript-js'
2
+ import { API } from 'typescript/sync'
3
3
  import { downlevelVueDeclarations } from '../src/vue-declarations.mjs'
4
4
 
5
- downlevelVueDeclarations(process.cwd(), process.argv[2] ?? 'lib', ts)
5
+ const api = new API()
6
+ try {
7
+ downlevelVueDeclarations(process.cwd(), process.argv[2] ?? 'lib', api)
8
+ } finally {
9
+ await api.close()
10
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sparknest/ui-build-vue",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Shared Vue component-library build core for Cedar and Maple",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,8 +29,7 @@
29
29
  "@vitejs/plugin-vue-jsx": "^5.1.6",
30
30
  "less": "^4.9.1",
31
31
  "vite": "^8.3.8",
32
- "vue-compat-legacy": "npm:vue@3.2.0",
33
- "typescript-js": "npm:typescript@6.0.3"
32
+ "vue-compat-legacy": "npm:vue@3.2.0"
34
33
  },
35
34
  "devDependencies": {
36
35
  "typescript": "7.1.0-beta",
@@ -40,6 +39,11 @@
40
39
  "typescript": ">=7.1.0-beta",
41
40
  "vue": ">=3.2"
42
41
  },
42
+ "peerDependenciesMeta": {
43
+ "typescript": {
44
+ "optional": true
45
+ }
46
+ },
43
47
  "engines": {
44
48
  "node": "^20.19.0 || >=22.12.0"
45
49
  },
@@ -1,11 +1,16 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
2
3
  import { dirname, join, relative, resolve } from 'node:path'
3
4
 
5
+ const require = createRequire(import.meta.url)
6
+
4
7
  // Keep each module format's declaration graph in the corresponding TS module mode.
5
- // The caller provides its TypeScript instance, for transforming the generated declarations.
6
- export function writeDualDeclarations(root, ts) {
7
- if (!ts || typeof ts.createSourceFile !== 'function') {
8
- throw new Error('TypeScript compiler API is required to generate dual declarations')
8
+ // The caller provides its TS7 API instance for parsing the generated declarations.
9
+ export function writeDualDeclarations(root, api) {
10
+ if (typeof api?.createProgram !== 'function' || typeof api.createSnapshot !== 'function') {
11
+ throw new Error(
12
+ 'TypeScript compiler API is required to generate dual declarations; pass an API from typescript/sync',
13
+ )
9
14
  }
10
15
  root = resolve(root)
11
16
  const files = []
@@ -17,14 +22,41 @@ export function writeDualDeclarations(root, ts) {
17
22
  }
18
23
  }
19
24
  collect(root)
20
- const contents = new Map(files.map((file) => [file, readFileSync(file, 'utf8')]))
25
+ if (!files.length) return
26
+ const program = api.createProgram(files, { noResolve: true, noLib: true, types: [] })
27
+ let outputs
28
+ try {
29
+ outputs = declarationOutputs(root, files, program)
30
+ } finally {
31
+ program.dispose()
32
+ }
33
+ for (const [file, text] of outputs) {
34
+ mkdirSync(dirname(file), { recursive: true })
35
+ writeFileSync(file, text)
36
+ }
37
+ }
38
+
39
+ function declarationOutputs(root, files, program) {
40
+ const {
41
+ isExportDeclaration,
42
+ isExternalModuleReference,
43
+ isImportDeclaration,
44
+ isImportEqualsDeclaration,
45
+ isImportTypeNode,
46
+ isLiteralTypeNode,
47
+ isStringLiteral,
48
+ } = require('typescript/ast')
49
+ const contents = new Set(files)
21
50
  const outputs = []
22
- for (const [file, text] of contents) {
23
- const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
24
- if (source.parseDiagnostics.length) throw new Error(`Cannot parse declaration: ${file}`)
51
+ for (const file of files) {
52
+ const source = program.getSourceFile(file)
53
+ if (!source || program.getSyntacticDiagnostics(file).length) throw new Error(`Cannot parse declaration: ${file}`)
54
+ const text = readFileSync(file, 'utf8')
55
+ // The program strips the BOM when reading from disk.
56
+ const bomLength = text.startsWith('\uFEFF') ? 1 : 0
25
57
  const edits = []
26
58
  function add(literal) {
27
- if (!literal || !ts.isStringLiteral(literal) || !literal.text.startsWith('.')) return
59
+ if (!literal || !isStringLiteral(literal) || !literal.text.startsWith('.')) return
28
60
  let specifier = literal.text
29
61
  let target = resolve(dirname(file), specifier)
30
62
  if (existsSync(target) && statSync(target).isDirectory()) {
@@ -34,15 +66,15 @@ export function writeDualDeclarations(root, ts) {
34
66
  if (!contents.has(`${target}.d.ts`)) {
35
67
  throw new Error(`Unresolved declaration ${literal.text} in ${relative(root, file)}`)
36
68
  }
37
- edits.push({ start: literal.getStart(source) + 1, end: literal.getEnd() - 1, specifier })
69
+ edits.push({ start: literal.getStart(source) + bomLength + 1, end: literal.end + bomLength - 1, specifier })
38
70
  }
39
71
  function visit(node) {
40
- if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) add(node.moduleSpecifier)
41
- else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) add(node.argument.literal)
42
- else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
72
+ if (isImportDeclaration(node) || isExportDeclaration(node)) add(node.moduleSpecifier)
73
+ else if (isImportTypeNode(node) && isLiteralTypeNode(node.argument)) add(node.argument.literal)
74
+ else if (isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference)) {
43
75
  add(node.moduleReference.expression)
44
76
  }
45
- ts.forEachChild(node, visit)
77
+ node.forEachChild(visit)
46
78
  }
47
79
  visit(source)
48
80
  edits.sort((a, b) => b.start - a.start)
@@ -57,8 +89,5 @@ export function writeDualDeclarations(root, ts) {
57
89
  outputs.push([file.slice(0, -'.d.ts'.length) + suffix, result])
58
90
  }
59
91
  }
60
- for (const [file, text] of outputs) {
61
- mkdirSync(dirname(file), { recursive: true })
62
- writeFileSync(file, text)
63
- }
92
+ return outputs
64
93
  }
package/src/index.mjs CHANGED
@@ -7,16 +7,26 @@ import { basename, dirname, relative, resolve } from 'node:path'
7
7
  import vue from '@vitejs/plugin-vue'
8
8
  import vueJsx from '@vitejs/plugin-vue-jsx'
9
9
  import less from 'less'
10
+ import * as vueCompiler from 'vue/compiler-sfc'
10
11
  import { build } from 'vite'
11
12
  import { browserTargets } from './browser-targets.mjs'
12
13
  import { libraryDefines } from './environment.mjs'
13
14
  import { collectModuleEntries } from './module-entries.mjs'
15
+ import { createTypeScript7Adapter, loadTypeScript7Sync } from './ts7-bridge.mjs'
14
16
  import { downlevelVueDeclarations } from './vue-declarations.mjs'
15
17
 
16
18
  export { writeDualDeclarations } from './dual-declarations.mjs'
17
19
  export { browserTargets } from './browser-targets.mjs'
18
20
  export { downlevelVueDeclarations } from './vue-declarations.mjs'
19
21
 
22
+ let compilerTypeScript
23
+ try {
24
+ compilerTypeScript = createTypeScript7Adapter()
25
+ } catch {
26
+ // Leave Vue's default TypeScript loading in place.
27
+ }
28
+ if (compilerTypeScript) vueCompiler.registerTS?.(() => compilerTypeScript)
29
+
20
30
  export function defineConfig(config) {
21
31
  return config
22
32
  }
@@ -326,7 +336,16 @@ async function compileStyles(config) {
326
336
  }
327
337
 
328
338
  function vitePlugins(config) {
329
- return [vue(), vueJsx(), styleImportPlugin(), ...(config.vueSfcStyles ? [ignoreVueStylePlugin()] : [])]
339
+ // Vite can resolve a separate compiler from the consuming workspace.
340
+ const require = createRequire(resolve(config.root, 'package.json'))
341
+ let compiler = vueCompiler
342
+ try {
343
+ compiler = require('vue/compiler-sfc')
344
+ } catch (error) {
345
+ if (error.code !== 'MODULE_NOT_FOUND' && error.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw error
346
+ }
347
+ if (compilerTypeScript) compiler.registerTS?.(() => compilerTypeScript)
348
+ return [vue({ compiler }), vueJsx(), styleImportPlugin(), ...(config.vueSfcStyles ? [ignoreVueStylePlugin()] : [])]
330
349
  }
331
350
 
332
351
  async function buildModules(config, entries, format, outDir, extension) {
@@ -504,7 +523,13 @@ export async function buildLibrary(userConfig) {
504
523
  await run('tsc', ['--runExternalCode', '-p', config.tsconfig], config.root)
505
524
  await normalizeVueTypeFiles(resolve(config.root, 'types'))
506
525
  if (existsSync(resolve(config.root, '../../node_modules/vue-compat-min/package.json'))) {
507
- downlevelVueDeclarations(config.root, 'types', createRequire(import.meta.url)('typescript-js'))
526
+ const { API } = loadTypeScript7Sync()
527
+ const api = new API()
528
+ try {
529
+ downlevelVueDeclarations(config.root, 'types', api)
530
+ } finally {
531
+ await api.close()
532
+ }
508
533
  }
509
534
  }
510
535
 
@@ -0,0 +1,103 @@
1
+ import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { dirname, join, resolve } from 'node:path'
4
+
5
+ export function loadTypeScript7Sync() {
6
+ const require = createRequire(import.meta.url)
7
+ try {
8
+ return require('typescript/sync')
9
+ } catch (cause) {
10
+ throw new Error('TypeScript 7 is required to load typescript/sync', { cause })
11
+ }
12
+ }
13
+
14
+ const readFile = (f) => {
15
+ try {
16
+ return readFileSync(String(f).startsWith('file:') ? new URL(f) : f, 'utf8')
17
+ } catch {
18
+ return undefined
19
+ }
20
+ }
21
+ const fileExists = (f) => {
22
+ try {
23
+ return statSync(String(f).startsWith('file:') ? new URL(f) : f).isFile()
24
+ } catch {
25
+ return false
26
+ }
27
+ }
28
+ const directoryExists = (f) => {
29
+ try {
30
+ return statSync(String(f).startsWith('file:') ? new URL(f) : f).isDirectory()
31
+ } catch {
32
+ return false
33
+ }
34
+ }
35
+
36
+ const sys = {
37
+ useCaseSensitiveFileNames: true,
38
+ newLine: '\n',
39
+ fileExists,
40
+ readFile,
41
+ directoryExists,
42
+ getCurrentDirectory: () => process.cwd(),
43
+ getDirectories: (f) => {
44
+ try {
45
+ return readdirSync(f, { withFileTypes: true })
46
+ .filter((d) => d.isDirectory())
47
+ .map((d) => d.name)
48
+ } catch {
49
+ return []
50
+ }
51
+ },
52
+ realpath: (f) => {
53
+ try {
54
+ return realpathSync(f)
55
+ } catch {
56
+ return f
57
+ }
58
+ },
59
+ }
60
+
61
+ function findConfigFile(searchPath, existsFn = fileExists) {
62
+ let dir = resolve(searchPath)
63
+ try {
64
+ if (statSync(dir).isFile()) dir = dirname(dir)
65
+ } catch {
66
+ /* noop */
67
+ }
68
+ for (;;) {
69
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
70
+ const candidate = join(dir, name)
71
+ if (existsFn(candidate)) return candidate
72
+ }
73
+ const parent = dirname(dir)
74
+ if (parent === dir || !parent) return undefined
75
+ dir = parent
76
+ }
77
+ }
78
+
79
+ // The compiler only needs these seven TypeScript capabilities.
80
+ export function createTypeScript7Adapter() {
81
+ const { API } = loadTypeScript7Sync()
82
+ const api = new API()
83
+ return {
84
+ versionMajorMinor: '7.1',
85
+ sys,
86
+ findConfigFile,
87
+ readConfigFile: (configPath) => api.readConfigFile(configPath),
88
+ parseJsonConfigFileContent: (json, _host, basePath, _existing, configPath) =>
89
+ api.parseJsonConfigFileContent(json, configPath ? { configFileName: configPath } : { configDirectory: basePath }),
90
+ createModuleResolutionCache: (_cwd, _canonicalName, compilerOptions) => ({
91
+ resolver: api.createModuleResolver(compilerOptions ?? {}),
92
+ }),
93
+ resolveModuleName: (moduleName, containingFile, compilerOptions, _fs, cache) => {
94
+ if (cache) return cache.resolver.resolveModuleName(moduleName, dirname(containingFile))
95
+ const resolver = api.createModuleResolver(compilerOptions ?? {})
96
+ try {
97
+ return resolver.resolveModuleName(moduleName, dirname(containingFile))
98
+ } finally {
99
+ resolver.dispose()
100
+ }
101
+ },
102
+ }
103
+ }
@@ -1,9 +1,12 @@
1
1
  import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
2
2
  import { createRequire } from 'node:module'
3
3
  import { dirname, join, relative, resolve } from 'node:path'
4
+ import { loadTypeScript7Sync } from './ts7-bridge.mjs'
5
+
6
+ const require = createRequire(import.meta.url)
4
7
 
5
8
  const baselines = new Map()
6
- function baseline(ts, packageDirectory) {
9
+ function baseline(api, packageDirectory) {
7
10
  let root = resolve(packageDirectory)
8
11
  while (!existsSync(join(root, 'node_modules/vue-compat-min/package.json')) && root !== dirname(root)) {
9
12
  root = dirname(root)
@@ -11,29 +14,46 @@ function baseline(ts, packageDirectory) {
11
14
  // Workspaces may explicitly select their minimum; standalone projects use
12
15
  // the tool's pinned Vue 3.2.0 baseline instead of relying on a sibling repo.
13
16
  const hasWorkspaceBaseline = existsSync(join(root, 'node_modules/vue-compat-min/package.json'))
14
- const require = hasWorkspaceBaseline ? createRequire(join(root, 'package.json')) : createRequire(import.meta.url)
15
- const entry = require.resolve(`${hasWorkspaceBaseline ? 'vue-compat-min' : 'vue-compat-legacy'}/dist/vue.d.ts`)
17
+ const baselineRequire = hasWorkspaceBaseline ? createRequire(join(root, 'package.json')) : require
18
+ const entry = baselineRequire.resolve(`${hasWorkspaceBaseline ? 'vue-compat-min' : 'vue-compat-legacy'}/dist/vue.d.ts`)
16
19
  if (baselines.has(entry)) return baselines.get(entry)
17
- const program = ts.createProgram([entry], {
18
- moduleResolution: ts.ModuleResolutionKind.Node10,
19
- target: ts.ScriptTarget.ESNext,
20
- types: [],
21
- skipLibCheck: true,
20
+ const { ScriptTarget } = require('typescript/ast')
21
+ const { ModuleResolutionKind, SymbolFlags } = loadTypeScript7Sync()
22
+ const snapshot = api.createSnapshot({
23
+ createPrograms: [
24
+ {
25
+ rootFiles: [entry],
26
+ compilerOptions: {
27
+ moduleResolution: ModuleResolutionKind.Node10,
28
+ target: ScriptTarget.ESNext,
29
+ types: [],
30
+ skipLibCheck: true,
31
+ },
32
+ },
33
+ ],
22
34
  })
23
- const checker = program.getTypeChecker()
24
- const exports = new Map(
25
- checker.getExportsOfModule(checker.getSymbolAtLocation(program.getSourceFile(entry))).map((symbol) => {
26
- const name = symbol.name
27
- if (symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol)
28
- return [name, Math.max(0, ...(symbol.declarations ?? []).map((node) => node.typeParameters?.length ?? 0))]
29
- }),
30
- )
31
- baselines.set(entry, exports)
32
- return exports
35
+ try {
36
+ const [program] = snapshot.operation.createdPrograms
37
+ const { checker } = snapshot.getProject(program.id)
38
+ const exports = new Map(
39
+ checker.getExportsOfModule(checker.getSymbolAtLocation(program.getSourceFile(entry))).map((symbol) => {
40
+ const name = symbol.name
41
+ if (symbol.flags & SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol)
42
+ return [
43
+ name,
44
+ Math.max(0, ...(symbol.declarations ?? []).map((node) => node.resolve()?.typeParameters?.length ?? 0)),
45
+ ]
46
+ }),
47
+ )
48
+ baselines.set(entry, exports)
49
+ return exports
50
+ } finally {
51
+ snapshot.dispose()
52
+ }
33
53
  }
34
54
 
35
55
  // These are type conveniences absent from 3.2.47, expressed using its public API.
36
- // Runtime helpers are never shimmed by this declaration transform.
56
+ // Runtime helpers are never shimmed by this declaration rewrite.
37
57
  const conveniences = new Set([
38
58
  'PublicProps',
39
59
  'SlotsType',
@@ -67,9 +87,9 @@ export type ComponentProvideOptions = Record<string | symbol, unknown> | (() =>
67
87
  export interface GlobalDirectives {}
68
88
  `
69
89
 
70
- export function downlevelVueDeclarations(packageDirectory, outputDirectory, ts) {
90
+ export function downlevelVueDeclarations(packageDirectory, outputDirectory, api) {
71
91
  const root = resolve(packageDirectory, outputDirectory)
72
- const exports = baseline(ts, packageDirectory)
92
+ const exports = baseline(api, packageDirectory)
73
93
  const files = []
74
94
  const collect = (dir) => {
75
95
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
@@ -79,139 +99,215 @@ export function downlevelVueDeclarations(packageDirectory, outputDirectory, ts)
79
99
  }
80
100
  }
81
101
  collect(root)
82
- const printer = ts.createPrinter()
83
102
  for (const file of files) {
84
103
  const text = readFileSync(file, 'utf8')
85
104
  if (!/['"]vue['"]/.test(text)) continue
86
- const ast = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true)
105
+ writeFileSync(file, rewriteDeclaration(api, file, text, root, exports))
106
+ }
107
+ writeFileSync(join(root, 'vue-compat.d.ts'), convenienceSource)
108
+ }
109
+
110
+ function rewriteDeclaration(api, file, text, root, exports) {
111
+ const {
112
+ isArrayTypeNode,
113
+ isExportAssignment,
114
+ isExportDeclaration,
115
+ isIdentifier,
116
+ isIndexedAccessTypeNode,
117
+ isImportDeclaration,
118
+ isImportTypeNode,
119
+ isIntersectionTypeNode,
120
+ isLiteralTypeNode,
121
+ isNamedExports,
122
+ isNamedImports,
123
+ isNamespaceImport,
124
+ isOptionalTypeNode,
125
+ isQualifiedName,
126
+ isTypeOperatorNode,
127
+ isTypeReferenceNode,
128
+ isUnionTypeNode,
129
+ isVariableStatement,
130
+ } = require('typescript/ast')
131
+ const { getTrailingCommentRanges } = require('typescript/ast/scanner')
132
+ const lease = api.createSourceFile(file, text)
133
+ try {
134
+ const ast = lease.sourceFile
135
+ const nodeText = (node) => text.slice(node.getStart(ast), node.end)
87
136
  // Vue language tools can append an empty synthetic component to a
88
137
  // script-only SFC which already forwards its implementation's default.
89
138
  // The forwarded declaration is the component's full public contract.
90
139
  if (file.endsWith('.vue.d.ts') && ast.statements.length === 4) {
91
140
  const [forward, component, alias, assignment] = ast.statements
92
141
  if (
93
- ts.isExportDeclaration(forward) && forward.moduleSpecifier && forward.exportClause &&
94
- ts.isNamedExports(forward.exportClause) && forward.exportClause.elements.some(item => item.name.text === 'default') &&
95
- ts.isVariableStatement(component) && component.declarationList.declarations[0]?.name.getText(ast) === '__VLS_export' &&
96
- ts.isVariableStatement(alias) && alias.declarationList.declarations[0]?.type?.getText(ast) === 'typeof __VLS_export' &&
97
- ts.isExportAssignment(assignment) && assignment.expression.getText(ast) === alias.declarationList.declarations[0].name.getText(ast)
142
+ isExportDeclaration(forward) &&
143
+ forward.moduleSpecifier &&
144
+ forward.exportClause &&
145
+ isNamedExports(forward.exportClause) &&
146
+ forward.exportClause.elements.some((item) => item.name.text === 'default') &&
147
+ isVariableStatement(component) &&
148
+ component.declarationList.declarations[0]?.name.text === '__VLS_export' &&
149
+ isVariableStatement(alias) &&
150
+ alias.declarationList.declarations[0]?.type?.getText(ast) === 'typeof __VLS_export' &&
151
+ isExportAssignment(assignment) &&
152
+ assignment.expression.getText(ast) === alias.declarationList.declarations[0].name.getText(ast)
98
153
  ) {
99
- writeFileSync(file, forward.getText(ast) + '\n')
100
- continue
154
+ return nodeText(forward) + '\n'
101
155
  }
102
156
  }
103
157
  const imports = new Map()
104
158
  const namespaces = new Set()
105
159
  for (const node of ast.statements)
106
- if (ts.isImportDeclaration(node) && node.moduleSpecifier.text === 'vue') {
160
+ if (isImportDeclaration(node) && node.moduleSpecifier.text === 'vue') {
107
161
  const bindings = node.importClause?.namedBindings
108
- if (bindings && ts.isNamedImports(bindings))
162
+ if (bindings && isNamedImports(bindings))
109
163
  for (const item of bindings.elements) imports.set(item.name.text, (item.propertyName ?? item.name).text)
110
- if (bindings && ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text)
164
+ if (bindings && isNamespaceImport(bindings)) namespaces.add(bindings.name.text)
111
165
  }
112
166
  let helper = relative(dirname(file), join(root, 'vue-compat')).replaceAll('\\', '/')
113
167
  if (!helper.startsWith('.')) helper = `./${helper}`
114
- const importType = (module, name, args, isTypeOf = false) =>
115
- ts.factory.createImportTypeNode(
116
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(module)),
117
- undefined,
118
- ts.factory.createIdentifier(name),
119
- args,
120
- isTypeOf,
121
- )
122
168
  const nameOf = (node) => {
123
169
  if (
124
- ts.isImportTypeNode(node) &&
125
- ts.isLiteralTypeNode(node.argument) &&
170
+ isImportTypeNode(node) &&
171
+ isLiteralTypeNode(node.argument) &&
126
172
  node.argument.literal.text === 'vue' &&
127
173
  node.qualifier &&
128
- ts.isIdentifier(node.qualifier)
174
+ isIdentifier(node.qualifier)
129
175
  )
130
176
  return node.qualifier.text
131
- if (ts.isTypeReferenceNode(node)) {
132
- if (ts.isIdentifier(node.typeName)) return imports.get(node.typeName.text)
177
+ if (isTypeReferenceNode(node)) {
178
+ if (isIdentifier(node.typeName)) return imports.get(node.typeName.text)
133
179
  if (
134
- ts.isQualifiedName(node.typeName) &&
135
- ts.isIdentifier(node.typeName.left) &&
180
+ isQualifiedName(node.typeName) &&
181
+ isIdentifier(node.typeName.left) &&
136
182
  namespaces.has(node.typeName.left.text)
137
183
  )
138
184
  return node.typeName.right.text
139
185
  }
140
186
  }
141
- const transformed = ts.transform(ast, [
142
- (context) => {
143
- const visit = (original) => {
144
- const name = nameOf(original)
145
- if (!name) return ts.visitEachChild(original, visit, context)
146
- let target = name
147
- let args = original.typeArguments ? [...original.typeArguments] : undefined
148
- let node
149
- let slots
150
- if (name === 'CreateComponentPublicInstanceWithMixins') {
151
- target = 'CreateComponentPublicInstance'
152
- slots = original.typeArguments?.[12]
153
- args = args?.slice(0, 11)
154
- } else if (name === 'DefineComponent') slots = original.typeArguments?.[12]
155
- if (exports.has(target)) {
156
- if (args) args = args.slice(0, exports.get(target))
157
- node = importType('vue', target, args?.length ? args : undefined, original.isTypeOf)
158
- } else if (conveniences.has(target)) node = importType(helper, target, args)
159
- else
160
- throw new Error(`${file}: cannot downlevel unknown Vue type ${target}; choose a 3.2-compatible public type`)
161
- node = ts.visitEachChild(node, visit, context)
162
- // Vue 3.2 has no SlotsType parameter. Preserve consumer slot inference as
163
- // an explicit instance intersection, rather than deleting the slot API.
164
- if (slots && nameOf(slots) === 'SlotsType' && slots.typeArguments?.[0]) {
165
- const slotType = ts.visitNode(slots.typeArguments[0], visit)
166
- const members = [ts.factory.createPropertySignature(undefined, '$slots', undefined, slotType)]
167
- const exposed = ts.factory.createTypeLiteralNode(members)
168
- const extra =
169
- name === 'DefineComponent'
170
- ? ts.factory.createTypeLiteralNode([ts.factory.createConstructSignature(undefined, [], exposed)])
171
- : exposed
172
- node = ts.factory.createIntersectionTypeNode([node, extra])
173
- }
174
- return node
175
- }
176
- return (source) => {
177
- const transformed = ts.visitNode(source, visit)
178
- // References to unavailable named convenience types were rewritten above;
179
- // retaining their old imports would still break strict consumer checking.
180
- return ts.factory.updateSourceFile(
181
- transformed,
182
- transformed.statements.flatMap((node) => {
183
- if (
184
- !ts.isImportDeclaration(node) ||
185
- node.moduleSpecifier.text !== 'vue' ||
186
- !node.importClause?.namedBindings ||
187
- !ts.isNamedImports(node.importClause.namedBindings)
188
- )
189
- return [node]
190
- const bindings = node.importClause.namedBindings.elements.filter((item) =>
191
- exports.has((item.propertyName ?? item.name).text),
192
- )
193
- if (!bindings.length && !node.importClause.name) return []
194
- return [
195
- ts.factory.updateImportDeclaration(
196
- node,
197
- node.modifiers,
198
- ts.factory.updateImportClause(
199
- node.importClause,
200
- node.importClause.isTypeOnly,
201
- node.importClause.name,
202
- ts.factory.updateNamedImports(node.importClause.namedBindings, bindings),
203
- ),
204
- node.moduleSpecifier,
205
- node.attributes,
206
- ),
207
- ]
208
- }),
209
- )
187
+ const edits = []
188
+ const trailingEnd = (position) => getTrailingCommentRanges(text, position)?.at(-1)?.end ?? position
189
+ function render(node) {
190
+ const nested = []
191
+ visit(node, nested)
192
+ const end = nameOf(node) ? node.end : trailingEnd(node.end)
193
+ const newline = end > node.end && /[\r\n]/.test(text[end] ?? '') ? '\n' : ''
194
+ return applyEdits(text, nested, node.pos, end) + newline
195
+ }
196
+
197
+ function visit(node, edits) {
198
+ const name = nameOf(node)
199
+ if (!name) {
200
+ node.forEachChild((child) => {
201
+ visit(child, edits)
202
+ })
203
+ return
204
+ }
205
+ const target = name === 'CreateComponentPublicInstanceWithMixins' ? 'CreateComponentPublicInstance' : name
206
+ const slots =
207
+ name === 'DefineComponent' || name === 'CreateComponentPublicInstanceWithMixins'
208
+ ? node.typeArguments?.[12]
209
+ : undefined
210
+ const args = target === name ? node.typeArguments : node.typeArguments?.slice(0, 11)
211
+ let replacement
212
+ if (exports.has(target)) {
213
+ replacement = (node.isTypeOf ? 'typeof ' : '') + `import("vue").${target}`
214
+ const retained = args?.slice(0, exports.get(target))
215
+ if (retained?.length) replacement += `<${retained.map(render).join(', ')}>`
216
+ } else if (conveniences.has(target)) {
217
+ replacement = `import(${JSON.stringify(helper)}).${target}`
218
+ if (args?.length) replacement += `<${args.map(render).join(', ')}>`
219
+ } else {
220
+ throw new Error(`${file}: cannot downlevel unknown Vue type ${target}; choose a 3.2-compatible public type`)
221
+ }
222
+
223
+ // Vue 3.2 represents consumer slot inference as an instance intersection.
224
+ if (slots && nameOf(slots) === 'SlotsType' && slots.typeArguments?.[0]) {
225
+ const exposed = `{\n$slots: ${render(slots.typeArguments[0])};\n}`
226
+ replacement += name === 'DefineComponent' ? ` & {\nnew (): ${exposed};\n}` : ` & ${exposed}`
227
+ const parent = node.parent
228
+ if (
229
+ isArrayTypeNode(parent) ||
230
+ isTypeOperatorNode(parent) ||
231
+ isOptionalTypeNode(parent) ||
232
+ isIntersectionTypeNode(parent) ||
233
+ isUnionTypeNode(parent) ||
234
+ (isIndexedAccessTypeNode(parent) && parent.objectType === node)
235
+ )
236
+ replacement = `(${replacement})`
237
+ }
238
+ const trivia = text.slice(node.pos, node.getStart(ast)).replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, '')
239
+ edits.push({ start: node.pos, end: node.end, replacement: trivia + replacement })
240
+ }
241
+
242
+ for (const node of ast.statements) {
243
+ const clause = isImportDeclaration(node) && node.moduleSpecifier.text === 'vue' && node.importClause
244
+ const bindings = clause?.namedBindings
245
+ if (bindings && isNamedImports(bindings)) {
246
+ const retained = bindings.elements.filter((item) => exports.has((item.propertyName ?? item.name).text))
247
+ if (!retained.length && !clause.name) {
248
+ const start = node.pos === 0 ? 0 : trailingEnd(node.pos)
249
+ edits.push({ start, end: trailingEnd(node.end), replacement: '' })
250
+ } else if (retained.length !== bindings.elements.length || bindings.elements.hasTrailingComma) {
251
+ const replacement = `{${retained.map((item) => text.slice(item.pos, item.end)).join(',')}}`
252
+ edits.push({ start: bindings.getStart(ast), end: bindings.end, replacement })
210
253
  }
211
- },
212
- ])
213
- writeFileSync(file, printer.printFile(transformed.transformed[0]))
214
- transformed.dispose()
254
+ } else {
255
+ visit(node, edits)
256
+ }
257
+ }
258
+
259
+ // Match the legacy output's omission of detached comments at EOF.
260
+ const end = ast.statements.length ? trailingEnd(ast.endOfFileToken.pos) : 0
261
+ return referenceDirectives(ast) + formatDeclaration(api, file, applyEdits(text, edits, 0, end))
262
+ } finally {
263
+ lease.dispose()
215
264
  }
216
- writeFileSync(join(root, 'vue-compat.d.ts'), convenienceSource)
265
+ }
266
+
267
+ function referenceDirectives(source) {
268
+ const { ModuleKind } = loadTypeScript7Sync()
269
+ let output = ''
270
+ for (const [kind, directives] of [
271
+ ['path', source.referencedFiles],
272
+ ['types', source.typeReferenceDirectives],
273
+ ['lib', source.libReferenceDirectives],
274
+ ]) {
275
+ for (const directive of directives) {
276
+ const mode = directive.resolutionMode === ModuleKind.ESNext ? 'import' : 'require'
277
+ const resolution = directive.resolutionMode ? `resolution-mode="${mode}" ` : ''
278
+ const preserve = directive.preserve ? 'preserve="true" ' : ''
279
+ output += `/// <reference ${kind}="${directive.fileName}" ${resolution}${preserve}/>\n`
280
+ }
281
+ }
282
+ return output
283
+ }
284
+
285
+ function formatDeclaration(api, file, content) {
286
+ // Preserve the declaration formatting produced by the previous printer.
287
+ // TS7's printer misplaces comments after multibyte characters. Parse an
288
+ // ASCII copy for formatting, then restore the original characters.
289
+ let marker = '__VUE_DECLARATION_CHAR_'
290
+ while (content.includes(marker)) marker += '_'
291
+ const characters = []
292
+ const ascii = content.replace(/[^\x00-\x7f\s]+/gu, (value) => {
293
+ characters.push(value)
294
+ return `${marker}${characters.length - 1}__`
295
+ })
296
+ const rewritten = api.createSourceFile(file, ascii)
297
+ try {
298
+ return api.printer
299
+ .printFile(rewritten.sourceFile)
300
+ .replace(new RegExp(`${marker}(\\d+)__`, 'g'), (_, i) => characters[i])
301
+ } finally {
302
+ rewritten.dispose()
303
+ }
304
+ }
305
+
306
+ function applyEdits(text, edits, start = 0, end = text.length) {
307
+ let result = ''
308
+ for (const edit of edits.sort((a, b) => a.start - b.start)) {
309
+ result += text.slice(start, edit.start) + edit.replacement
310
+ start = edit.end
311
+ }
312
+ return result + text.slice(start, end)
217
313
  }