This commit is contained in:
2024-11-28 23:08:17 +01:00
parent 8895fde030
commit 0dda8e760c
16116 changed files with 2866428 additions and 71 deletions

View File

@@ -0,0 +1,5 @@
import type { VirtualCode } from '@volar/language-core';
import { ISignal } from 'alien-signals';
import type { Sfc, VueLanguagePluginReturn } from '../types';
export declare function computedEmbeddedCodes(plugins: VueLanguagePluginReturn[], fileName: string, sfc: Sfc): ISignal<VirtualCode[]>;
export declare function resolveCommonLanguageId(lang: string): string;

View File

@@ -0,0 +1,244 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computedEmbeddedCodes = computedEmbeddedCodes;
exports.resolveCommonLanguageId = resolveCommonLanguageId;
const alien_signals_1 = require("alien-signals");
const muggle_string_1 = require("muggle-string");
const buildMappings_1 = require("../utils/buildMappings");
const embeddedFile_1 = require("./embeddedFile");
function computedEmbeddedCodes(plugins, fileName, sfc) {
const nameToBlock = (0, alien_signals_1.computed)(() => {
const blocks = {};
if (sfc.template) {
blocks[sfc.template.name] = sfc.template;
}
if (sfc.script) {
blocks[sfc.script.name] = sfc.script;
}
if (sfc.scriptSetup) {
blocks[sfc.scriptSetup.name] = sfc.scriptSetup;
}
for (const block of sfc.styles) {
blocks[block.name] = block;
}
for (const block of sfc.customBlocks) {
blocks[block.name] = block;
}
return blocks;
});
const pluginsResult = plugins.map(plugin => computedPluginEmbeddedCodes(plugins, plugin, fileName, sfc, nameToBlock));
const flatResult = (0, alien_signals_1.computed)(() => pluginsResult.map(r => r.get()).flat());
const structuredResult = (0, alien_signals_1.computed)(() => {
const embeddedCodes = [];
let remain = [...flatResult.get()];
while (remain.length) {
const beforeLength = remain.length;
consumeRemain();
if (beforeLength === remain.length) {
break;
}
}
for (const { code } of remain) {
console.error('Unable to resolve embedded: ' + code.parentCodeId + ' -> ' + code.id);
}
return embeddedCodes;
function consumeRemain() {
for (let i = remain.length - 1; i >= 0; i--) {
const { code, snapshot, mappings } = remain[i];
if (!code.parentCodeId) {
embeddedCodes.push({
id: code.id,
languageId: resolveCommonLanguageId(code.lang),
linkedCodeMappings: code.linkedCodeMappings,
snapshot,
mappings,
embeddedCodes: [],
});
remain.splice(i, 1);
}
else {
const parent = findParentStructure(code.parentCodeId, embeddedCodes);
if (parent) {
parent.embeddedCodes ??= [];
parent.embeddedCodes.push({
id: code.id,
languageId: resolveCommonLanguageId(code.lang),
linkedCodeMappings: code.linkedCodeMappings,
snapshot,
mappings,
embeddedCodes: [],
});
remain.splice(i, 1);
}
}
}
}
function findParentStructure(id, current) {
for (const child of current) {
if (child.id === id) {
return child;
}
let parent = findParentStructure(id, child.embeddedCodes ?? []);
if (parent) {
return parent;
}
}
}
});
return structuredResult;
}
function computedPluginEmbeddedCodes(plugins, plugin, fileName, sfc, nameToBlock) {
const computeds = new Map();
const getComputedKey = (code) => code.id + '__' + code.lang;
const codes = (0, alien_signals_1.computed)(() => {
try {
if (!plugin.getEmbeddedCodes) {
return [...computeds.values()];
}
const embeddedCodeInfos = plugin.getEmbeddedCodes(fileName, sfc);
for (const oldId of computeds.keys()) {
if (!embeddedCodeInfos.some(code => getComputedKey(code) === oldId)) {
computeds.delete(oldId);
}
}
for (const codeInfo of embeddedCodeInfos) {
if (!computeds.has(getComputedKey(codeInfo))) {
computeds.set(getComputedKey(codeInfo), (0, alien_signals_1.computed)(() => {
const content = [];
const code = new embeddedFile_1.VueEmbeddedCode(codeInfo.id, codeInfo.lang, content);
for (const plugin of plugins) {
if (!plugin.resolveEmbeddedCode) {
continue;
}
try {
plugin.resolveEmbeddedCode(fileName, sfc, code);
}
catch (e) {
console.error(e);
}
}
const newText = (0, muggle_string_1.toString)(code.content);
const changeRanges = new Map();
const snapshot = {
getText: (start, end) => newText.slice(start, end),
getLength: () => newText.length,
getChangeRange(oldSnapshot) {
if (!changeRanges.has(oldSnapshot)) {
changeRanges.set(oldSnapshot, undefined);
const oldText = oldSnapshot.getText(0, oldSnapshot.getLength());
const changeRange = fullDiffTextChangeRange(oldText, newText);
if (changeRange) {
changeRanges.set(oldSnapshot, changeRange);
}
}
return changeRanges.get(oldSnapshot);
},
};
return {
code,
snapshot,
};
}));
}
}
}
catch (e) {
console.error(e);
}
return [...computeds.values()];
});
return (0, alien_signals_1.computed)(() => {
return codes.get().map(_file => {
const { code, snapshot } = _file.get();
const mappings = (0, buildMappings_1.buildMappings)(code.content.map(segment => {
if (typeof segment === 'string') {
return segment;
}
const source = segment[1];
if (source === undefined) {
return segment;
}
const block = nameToBlock.get()[source];
if (!block) {
// console.warn('Unable to find block: ' + source);
return segment;
}
return [
segment[0],
undefined,
segment[2] + block.startTagEnd,
segment[3],
];
}));
const newMappings = [];
let lastValidMapping;
for (let i = 0; i < mappings.length; i++) {
const mapping = mappings[i];
if (mapping.data.__combineOffsetMapping !== undefined) {
const offsetMapping = mappings[i - mapping.data.__combineOffsetMapping];
if (typeof offsetMapping === 'string' || !offsetMapping) {
throw new Error('Invalid offset mapping, mappings: ' + mappings.length + ', i: ' + i + ', offset: ' + mapping.data.__combineOffsetMapping);
}
offsetMapping.sourceOffsets.push(...mapping.sourceOffsets);
offsetMapping.generatedOffsets.push(...mapping.generatedOffsets);
offsetMapping.lengths.push(...mapping.lengths);
continue;
}
else if (mapping.data.__combineLastMapping) {
lastValidMapping.sourceOffsets.push(...mapping.sourceOffsets);
lastValidMapping.generatedOffsets.push(...mapping.generatedOffsets);
lastValidMapping.lengths.push(...mapping.lengths);
continue;
}
else {
lastValidMapping = mapping;
}
newMappings.push(mapping);
}
return {
code,
snapshot,
mappings: newMappings,
};
});
});
}
function fullDiffTextChangeRange(oldText, newText) {
for (let start = 0; start < oldText.length && start < newText.length; start++) {
if (oldText[start] !== newText[start]) {
let end = oldText.length;
for (let i = 0; i < oldText.length - start && i < newText.length - start; i++) {
if (oldText[oldText.length - i - 1] !== newText[newText.length - i - 1]) {
break;
}
end--;
}
let length = end - start;
let newLength = length + (newText.length - oldText.length);
if (newLength < 0) {
length -= newLength;
newLength = 0;
}
return {
span: { start, length },
newLength,
};
}
}
}
function resolveCommonLanguageId(lang) {
switch (lang) {
case 'js': return 'javascript';
case 'cjs': return 'javascript';
case 'mjs': return 'javascript';
case 'ts': return 'typescript';
case 'cts': return 'typescript';
case 'mts': return 'typescript';
case 'jsx': return 'javascriptreact';
case 'tsx': return 'typescriptreact';
case 'pug': return 'jade';
case 'md': return 'markdown';
}
return lang;
}
//# sourceMappingURL=computedEmbeddedCodes.js.map

View File

@@ -0,0 +1,5 @@
import type { SFCParseResult } from '@vue/compiler-sfc';
import { ISignal, Signal } from 'alien-signals';
import type * as ts from 'typescript';
import type { Sfc, VueLanguagePluginReturn } from '../types';
export declare function computedSfc(ts: typeof import('typescript'), plugins: VueLanguagePluginReturn[], fileName: string, snapshot: Signal<ts.IScriptSnapshot>, parsed: ISignal<SFCParseResult | undefined>): Sfc;

View File

@@ -0,0 +1,242 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computedSfc = computedSfc;
const alien_signals_1 = require("alien-signals");
const parseCssClassNames_1 = require("../utils/parseCssClassNames");
const parseCssVars_1 = require("../utils/parseCssVars");
function computedSfc(ts, plugins, fileName, snapshot, parsed) {
const untrackedSnapshot = () => {
const prevTrackId = alien_signals_1.System.activeTrackId;
alien_signals_1.System.activeTrackId = 0;
const res = snapshot.get();
alien_signals_1.System.activeTrackId = prevTrackId;
return res;
};
const content = (0, alien_signals_1.computed)(() => {
return snapshot.get().getText(0, snapshot.get().getLength());
});
const template = computedNullableSfcBlock('template', 'html', (0, alien_signals_1.computed)(() => parsed.get()?.descriptor.template ?? undefined), (_block, base) => {
const compiledAst = computedTemplateAst(base);
return mergeObject(base, {
get ast() { return compiledAst.get()?.ast; },
get errors() { return compiledAst.get()?.errors; },
get warnings() { return compiledAst.get()?.warnings; },
});
});
const script = computedNullableSfcBlock('script', 'js', (0, alien_signals_1.computed)(() => parsed.get()?.descriptor.script ?? undefined), (block, base) => {
const src = (0, alien_signals_1.computed)(() => block.get().src);
const srcOffset = (0, alien_signals_1.computed)(() => {
const _src = src.get();
return _src ? untrackedSnapshot().getText(0, base.startTagEnd).lastIndexOf(_src) - base.startTagEnd : -1;
});
const ast = (0, alien_signals_1.computed)(() => {
for (const plugin of plugins) {
const ast = plugin.compileSFCScript?.(base.lang, base.content);
if (ast) {
return ast;
}
}
return ts.createSourceFile(fileName + '.' + base.lang, '', 99);
});
return mergeObject(base, {
get src() { return src.get(); },
get srcOffset() { return srcOffset.get(); },
get ast() { return ast.get(); },
});
});
const scriptSetupOriginal = computedNullableSfcBlock('scriptSetup', 'js', (0, alien_signals_1.computed)(() => parsed.get()?.descriptor.scriptSetup ?? undefined), (block, base) => {
const generic = (0, alien_signals_1.computed)(() => {
const _block = block.get();
return typeof _block.attrs.generic === 'string' ? _block.attrs.generic : undefined;
});
const genericOffset = (0, alien_signals_1.computed)(() => {
const _generic = generic.get();
return _generic !== undefined ? untrackedSnapshot().getText(0, base.startTagEnd).lastIndexOf(_generic) - base.startTagEnd : -1;
});
const ast = (0, alien_signals_1.computed)(() => {
for (const plugin of plugins) {
const ast = plugin.compileSFCScript?.(base.lang, base.content);
if (ast) {
return ast;
}
}
return ts.createSourceFile(fileName + '.' + base.lang, '', 99);
});
return mergeObject(base, {
get generic() { return generic.get(); },
get genericOffset() { return genericOffset.get(); },
get ast() { return ast.get(); },
});
});
const hasScript = (0, alien_signals_1.computed)(() => !!parsed.get()?.descriptor.script);
const hasScriptSetup = (0, alien_signals_1.computed)(() => !!parsed.get()?.descriptor.scriptSetup);
const scriptSetup = (0, alien_signals_1.computed)(() => {
if (!hasScript.get() && !hasScriptSetup.get()) {
//#region monkey fix: https://github.com/vuejs/language-tools/pull/2113
return {
content: '',
lang: 'ts',
name: '',
start: 0,
end: 0,
startTagEnd: 0,
endTagStart: 0,
generic: undefined,
genericOffset: 0,
attrs: {},
ast: ts.createSourceFile('', '', 99, false, ts.ScriptKind.TS),
};
}
return scriptSetupOriginal.get();
});
const styles = alien_signals_1.Unstable.computedArray((0, alien_signals_1.computed)(() => parsed.get()?.descriptor.styles ?? []), (block, i) => {
const base = computedSfcBlock('style_' + i, 'css', block);
const module = (0, alien_signals_1.computed)(() => {
const _module = block.get().module;
return _module ? {
name: _module.name,
offset: _module.offset ? base.start + _module.offset : undefined
} : undefined;
});
const scoped = (0, alien_signals_1.computed)(() => !!block.get().scoped);
const cssVars = (0, alien_signals_1.computed)(() => [...(0, parseCssVars_1.parseCssVars)(base.content)]);
const classNames = (0, alien_signals_1.computed)(() => [...(0, parseCssClassNames_1.parseCssClassNames)(base.content)]);
return () => mergeObject(base, {
get module() { return module.get(); },
get scoped() { return scoped.get(); },
get cssVars() { return cssVars.get(); },
get classNames() { return classNames.get(); },
});
});
const customBlocks = alien_signals_1.Unstable.computedArray((0, alien_signals_1.computed)(() => parsed.get()?.descriptor.customBlocks ?? []), (block, i) => {
const base = computedSfcBlock('custom_block_' + i, 'txt', block);
const type = (0, alien_signals_1.computed)(() => block.get().type);
return () => mergeObject(base, {
get type() { return type.get(); },
});
});
return {
get content() { return content.get(); },
get template() { return template.get(); },
get script() { return script.get(); },
get scriptSetup() { return scriptSetup.get(); },
get styles() { return styles; },
get customBlocks() { return customBlocks; },
};
function computedTemplateAst(base) {
let cache;
return (0, alien_signals_1.computed)(() => {
if (cache?.template === base.content) {
return {
errors: [],
warnings: [],
ast: cache?.result.ast,
};
}
// incremental update
if (cache?.plugin.updateSFCTemplate) {
const change = untrackedSnapshot().getChangeRange(cache.snapshot);
if (change) {
const prevTrackId = alien_signals_1.System.activeTrackId;
alien_signals_1.System.activeTrackId = 0;
const templateOffset = base.startTagEnd;
alien_signals_1.System.activeTrackId = prevTrackId;
const newText = untrackedSnapshot().getText(change.span.start, change.span.start + change.newLength);
const newResult = cache.plugin.updateSFCTemplate(cache.result, {
start: change.span.start - templateOffset,
end: change.span.start + change.span.length - templateOffset,
newText,
});
if (newResult) {
cache.template = base.content;
cache.snapshot = untrackedSnapshot();
cache.result = newResult;
return {
errors: [],
warnings: [],
ast: newResult.ast,
};
}
}
}
const errors = [];
const warnings = [];
let options = {
onError: (err) => errors.push(err),
onWarn: (err) => warnings.push(err),
expressionPlugins: ['typescript'],
};
for (const plugin of plugins) {
if (plugin.resolveTemplateCompilerOptions) {
options = plugin.resolveTemplateCompilerOptions(options);
}
}
for (const plugin of plugins) {
let result;
try {
result = plugin.compileSFCTemplate?.(base.lang, base.content, options);
}
catch (e) {
const err = e;
errors.push(err);
}
if (result || errors.length) {
if (result && !errors.length && !warnings.length) {
cache = {
template: base.content,
snapshot: untrackedSnapshot(),
result: result,
plugin,
};
}
else {
cache = undefined;
}
return {
errors,
warnings,
ast: result?.ast,
};
}
}
return {
errors,
warnings,
ast: undefined,
};
});
}
function computedNullableSfcBlock(name, defaultLang, block, resolve) {
const hasBlock = (0, alien_signals_1.computed)(() => !!block.get());
return (0, alien_signals_1.computed)(() => {
if (!hasBlock.get()) {
return;
}
const _block = (0, alien_signals_1.computed)(() => block.get());
return resolve(_block, computedSfcBlock(name, defaultLang, _block));
});
}
function computedSfcBlock(name, defaultLang, block) {
const lang = (0, alien_signals_1.computed)(() => block.get().lang ?? defaultLang);
const attrs = (0, alien_signals_1.computed)(() => block.get().attrs); // TODO: computed it
const content = (0, alien_signals_1.computed)(() => block.get().content);
const startTagEnd = (0, alien_signals_1.computed)(() => block.get().loc.start.offset);
const endTagStart = (0, alien_signals_1.computed)(() => block.get().loc.end.offset);
const start = (0, alien_signals_1.computed)(() => untrackedSnapshot().getText(0, startTagEnd.get()).lastIndexOf('<' + block.get().type));
const end = (0, alien_signals_1.computed)(() => endTagStart.get() + untrackedSnapshot().getText(endTagStart.get(), untrackedSnapshot().getLength()).indexOf('>') + 1);
return {
name,
get lang() { return lang.get(); },
get attrs() { return attrs.get(); },
get content() { return content.get(); },
get startTagEnd() { return startTagEnd.get(); },
get endTagStart() { return endTagStart.get(); },
get start() { return start.get(); },
get end() { return end.get(); },
};
}
}
function mergeObject(a, b) {
return Object.defineProperties(a, Object.getOwnPropertyDescriptors(b));
}
//# sourceMappingURL=computedSfc.js.map

View File

@@ -0,0 +1,5 @@
import type { SFCParseResult } from '@vue/compiler-sfc';
import { Signal } from 'alien-signals';
import type * as ts from 'typescript';
import type { VueLanguagePluginReturn } from '../types';
export declare function computedVueSfc(plugins: VueLanguagePluginReturn[], fileName: string, languageId: string, snapshot: Signal<ts.IScriptSnapshot>): import("alien-signals").ISignal<SFCParseResult | undefined>;

View File

@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computedVueSfc = computedVueSfc;
const alien_signals_1 = require("alien-signals");
function computedVueSfc(plugins, fileName, languageId, snapshot) {
let cache;
return (0, alien_signals_1.computed)(() => {
// incremental update
if (cache?.plugin.updateSFC) {
const change = snapshot.get().getChangeRange(cache.snapshot);
if (change) {
const newSfc = cache.plugin.updateSFC(cache.sfc, {
start: change.span.start,
end: change.span.start + change.span.length,
newText: snapshot.get().getText(change.span.start, change.span.start + change.newLength),
});
if (newSfc) {
cache.snapshot = snapshot.get();
// force dirty
cache.sfc = JSON.parse(JSON.stringify(newSfc));
return cache.sfc;
}
}
}
for (const plugin of plugins) {
const sfc = plugin.parseSFC?.(fileName, snapshot.get().getText(0, snapshot.get().getLength()))
?? plugin.parseSFC2?.(fileName, languageId, snapshot.get().getText(0, snapshot.get().getLength()));
if (sfc) {
if (!sfc.errors.length) {
cache = {
snapshot: snapshot.get(),
sfc,
plugin,
};
}
return sfc;
}
}
});
}
//# sourceMappingURL=computedVueSfc.js.map

View File

@@ -0,0 +1,11 @@
import type { Mapping } from '@volar/language-core';
import type { Code } from '../types';
export declare class VueEmbeddedCode {
id: string;
lang: string;
content: Code[];
parentCodeId?: string;
linkedCodeMappings: Mapping[];
embeddedCodes: VueEmbeddedCode[];
constructor(id: string, lang: string, content: Code[]);
}

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VueEmbeddedCode = void 0;
class VueEmbeddedCode {
constructor(id, lang, content) {
this.id = id;
this.lang = lang;
this.content = content;
this.linkedCodeMappings = [];
this.embeddedCodes = [];
}
}
exports.VueEmbeddedCode = VueEmbeddedCode;
//# sourceMappingURL=embeddedFile.js.map

View File

@@ -0,0 +1,32 @@
import type { VirtualCode } from '@volar/language-core';
import type * as ts from 'typescript';
import type { VueCompilerOptions, VueLanguagePluginReturn } from '../types';
export declare class VueVirtualCode implements VirtualCode {
fileName: string;
languageId: string;
initSnapshot: ts.IScriptSnapshot;
vueCompilerOptions: VueCompilerOptions;
plugins: VueLanguagePluginReturn[];
ts: typeof import('typescript');
id: string;
_snapshot: import("alien-signals").Signal<ts.IScriptSnapshot>;
_vueSfc: import("alien-signals").ISignal<import("@vue/compiler-sfc").SFCParseResult | undefined>;
_sfc: import("../types").Sfc;
_mappings: import("alien-signals").ISignal<{
sourceOffsets: number[];
generatedOffsets: number[];
lengths: number[];
data: import("@volar/language-core").CodeInformation;
}[]>;
_embeddedCodes: import("alien-signals").ISignal<VirtualCode[]>;
get embeddedCodes(): VirtualCode[];
get snapshot(): ts.IScriptSnapshot;
get mappings(): {
sourceOffsets: number[];
generatedOffsets: number[];
lengths: number[];
data: import("@volar/language-core").CodeInformation;
}[];
constructor(fileName: string, languageId: string, initSnapshot: ts.IScriptSnapshot, vueCompilerOptions: VueCompilerOptions, plugins: VueLanguagePluginReturn[], ts: typeof import('typescript'));
update(newSnapshot: ts.IScriptSnapshot): void;
}

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VueVirtualCode = void 0;
const alien_signals_1 = require("alien-signals");
const plugins_1 = require("../plugins");
const computedEmbeddedCodes_1 = require("./computedEmbeddedCodes");
const computedSfc_1 = require("./computedSfc");
const computedVueSfc_1 = require("./computedVueSfc");
class VueVirtualCode {
// others
get embeddedCodes() {
return this._embeddedCodes.get();
}
get snapshot() {
return this._snapshot.get();
}
get mappings() {
return this._mappings.get();
}
constructor(fileName, languageId, initSnapshot, vueCompilerOptions, plugins, ts) {
this.fileName = fileName;
this.languageId = languageId;
this.initSnapshot = initSnapshot;
this.vueCompilerOptions = vueCompilerOptions;
this.plugins = plugins;
this.ts = ts;
// sources
this.id = 'main';
this._snapshot = (0, alien_signals_1.signal)(undefined);
// computeds
this._vueSfc = (0, computedVueSfc_1.computedVueSfc)(this.plugins, this.fileName, this.languageId, this._snapshot);
this._sfc = (0, computedSfc_1.computedSfc)(this.ts, this.plugins, this.fileName, this._snapshot, this._vueSfc);
this._mappings = (0, alien_signals_1.computed)(() => {
const snapshot = this._snapshot.get();
return [{
sourceOffsets: [0],
generatedOffsets: [0],
lengths: [snapshot.getLength()],
data: plugins_1.allCodeFeatures,
}];
});
this._embeddedCodes = (0, computedEmbeddedCodes_1.computedEmbeddedCodes)(this.plugins, this.fileName, this._sfc);
this._snapshot.set(initSnapshot);
}
update(newSnapshot) {
this._snapshot.set(newSnapshot);
}
}
exports.VueVirtualCode = VueVirtualCode;
//# sourceMappingURL=vueFile.js.map