Clean up dependencies
All checks were successful
Build and Push / build (push) Successful in 18s

This commit is contained in:
2026-02-16 15:12:59 -05:00
parent d181f77fb2
commit 2f15523a55
14941 changed files with 0 additions and 2078483 deletions

View File

@@ -1,59 +0,0 @@
import type { ConvertToTSXOptions, TSXExtractedScript, TSXExtractedStyle, TSXResult } from '@astrojs/compiler/types';
import type { VirtualCode } from '@volar/language-core';
import { Range } from '@volar/language-server';
export interface LSPTSXRanges {
frontmatter: Range;
body: Range;
scripts: TSXExtractedScript[];
styles: TSXExtractedStyle[];
}
export declare function safeConvertToTSX(content: string, options: ConvertToTSXOptions): TSXResult | {
code: string;
map: {
file: string;
sources: never[];
sourcesContent: never[];
names: never[];
mappings: string;
version: number;
};
diagnostics: {
code: 1000;
location: {
file: string;
line: number;
column: number;
length: number;
};
severity: 1;
text: string;
}[];
metaRanges: {
frontmatter: {
start: number;
end: number;
};
body: {
start: number;
end: number;
};
scripts: never[];
styles: never[];
};
};
export declare function getTSXRangesAsLSPRanges(tsx: TSXResult): LSPTSXRanges;
export declare function astro2tsx(input: string, fileName: string): {
virtualCode: VirtualCode;
diagnostics: import("@astrojs/compiler").DiagnosticMessage[] | {
code: 1000;
location: {
file: string;
line: number;
column: number;
length: number;
};
severity: 1;
text: string;
}[];
ranges: LSPTSXRanges;
};

View File

@@ -1,144 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeConvertToTSX = safeConvertToTSX;
exports.getTSXRangesAsLSPRanges = getTSXRangesAsLSPRanges;
exports.astro2tsx = astro2tsx;
const sync_1 = require("@astrojs/compiler/sync");
const sourcemap_codec_1 = require("@jridgewell/sourcemap-codec");
const language_server_1 = require("@volar/language-server");
const vscode_html_languageservice_1 = require("vscode-html-languageservice");
const utils_js_1 = require("./utils.js");
function safeConvertToTSX(content, options) {
try {
const tsx = (0, sync_1.convertToTSX)(content, {
filename: options.filename,
includeScripts: false,
includeStyles: false,
});
return tsx;
}
catch (e) {
console.error(`There was an error transforming ${options.filename} to TSX. An empty file will be returned instead. Please create an issue: https://github.com/withastro/language-tools/issues\nError: ${e}.`);
return {
code: '',
map: {
file: options.filename ?? '',
sources: [],
sourcesContent: [],
names: [],
mappings: '',
version: 0,
},
diagnostics: [
{
code: 1000,
location: { file: options.filename, line: 1, column: 1, length: content.length },
severity: 1,
text: `The Astro compiler encountered an unknown error while transform this file to TSX. Please create an issue with your code and the error shown in the server's logs: https://github.com/withastro/language-tools/issues`,
},
],
metaRanges: {
frontmatter: {
start: 0,
end: 0,
},
body: {
start: 0,
end: 0,
},
scripts: [],
styles: [],
},
};
}
}
function getTSXRangesAsLSPRanges(tsx) {
const textDocument = vscode_html_languageservice_1.TextDocument.create('', 'typescriptreact', 0, tsx.code);
return {
frontmatter: language_server_1.Range.create(textDocument.positionAt(tsx.metaRanges.frontmatter.start), textDocument.positionAt(tsx.metaRanges.frontmatter.end)),
body: language_server_1.Range.create(textDocument.positionAt(tsx.metaRanges.body.start), textDocument.positionAt(tsx.metaRanges.body.end)),
scripts: tsx.metaRanges.scripts ?? [],
styles: tsx.metaRanges.styles ?? [],
};
}
function astro2tsx(input, fileName) {
const tsx = safeConvertToTSX(input, { filename: fileName });
return {
virtualCode: getVirtualCodeTSX(input, tsx, fileName),
diagnostics: tsx.diagnostics,
ranges: getTSXRangesAsLSPRanges(tsx),
};
}
function getVirtualCodeTSX(input, tsx, fileName) {
tsx.code = (0, utils_js_1.patchTSX)(tsx.code, fileName);
const v3Mappings = (0, sourcemap_codec_1.decode)(tsx.map.mappings);
const sourcedDoc = vscode_html_languageservice_1.TextDocument.create('', 'astro', 0, input);
const genDoc = vscode_html_languageservice_1.TextDocument.create('', 'typescriptreact', 0, tsx.code);
const mappings = [];
let current;
for (let genLine = 0; genLine < v3Mappings.length; genLine++) {
for (const segment of v3Mappings[genLine]) {
const genCharacter = segment[0];
const genOffset = genDoc.offsetAt({ line: genLine, character: genCharacter });
if (current) {
let length = genOffset - current.genOffset;
const sourceText = input.substring(current.sourceOffset, current.sourceOffset + length);
const genText = tsx.code.substring(current.genOffset, current.genOffset + length);
if (sourceText !== genText) {
length = 0;
for (let i = 0; i < genOffset - current.genOffset; i++) {
if (sourceText[i] === genText[i]) {
length = i + 1;
}
else {
break;
}
}
}
if (length > 0) {
const lastMapping = mappings.length ? mappings[mappings.length - 1] : undefined;
if (lastMapping &&
lastMapping.generatedOffsets[0] + lastMapping.lengths[0] === current.genOffset &&
lastMapping.sourceOffsets[0] + lastMapping.lengths[0] === current.sourceOffset) {
lastMapping.lengths[0] += length;
}
else {
mappings.push({
sourceOffsets: [current.sourceOffset],
generatedOffsets: [current.genOffset],
lengths: [length],
data: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: false,
},
});
}
}
current = undefined;
}
if (segment[2] !== undefined && segment[3] !== undefined) {
const sourceOffset = sourcedDoc.offsetAt({ line: segment[2], character: segment[3] });
current = {
genOffset,
sourceOffset,
};
}
}
}
return {
id: 'tsx',
languageId: 'typescriptreact',
snapshot: {
getText: (start, end) => tsx.code.substring(start, end),
getLength: () => tsx.code.length,
getChangeRange: () => undefined,
},
mappings: mappings,
embeddedCodes: [],
};
}
//# sourceMappingURL=astro2tsx.js.map

View File

@@ -1,11 +0,0 @@
import type { AttributeNode, Point } from '@astrojs/compiler';
import { Position as LSPPosition } from '@volar/language-server';
/**
* Transform a Point from the Astro compiler to an LSP Position
*/
export declare function PointToPosition(point: Point): LSPPosition;
type WithRequired<T, K extends keyof T> = T & {
[P in K]-?: T[P];
};
export type AttributeNodeWithPosition = WithRequired<AttributeNode, 'position'>;
export {};

View File

@@ -1,12 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PointToPosition = PointToPosition;
const language_server_1 = require("@volar/language-server");
/**
* Transform a Point from the Astro compiler to an LSP Position
*/
function PointToPosition(point) {
// Columns and lines are 0-based in LSP, but the compiler's Point are 1 based.
return language_server_1.Position.create(point.line - 1, point.column - 1);
}
//# sourceMappingURL=compilerUtils.js.map

View File

@@ -1,38 +0,0 @@
import { type CodeMapping, type LanguagePlugin, type VirtualCode } from '@volar/language-core';
import type ts from 'typescript';
import type { URI } from 'vscode-uri';
export declare const SUPPORTED_FRONTMATTER_EXTENSIONS: {
md: string;
mdx: string;
mdoc: string;
};
export declare const SUPPORTED_FRONTMATTER_EXTENSIONS_KEYS: string[];
export declare const frontmatterRE: RegExp;
export type CollectionConfig = {
reload: (folders: {
uri: string;
}[]) => void;
configs: {
folder: URI;
config: CollectionConfigInstance;
}[];
};
export type CollectionConfigInstance = {
collections: {
hasSchema: boolean;
name: string;
}[];
entries: Record<string, string>;
};
export declare function getFrontmatterLanguagePlugin(collectionConfig: CollectionConfig): LanguagePlugin<URI, FrontmatterHolder>;
export declare class FrontmatterHolder implements VirtualCode {
fileName: string;
languageId: string;
snapshot: ts.IScriptSnapshot;
collection: string | undefined;
id: string;
mappings: CodeMapping[];
embeddedCodes: VirtualCode[];
hasFrontmatter: boolean;
constructor(fileName: string, languageId: string, snapshot: ts.IScriptSnapshot, collection: string | undefined);
}

View File

@@ -1,119 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrontmatterHolder = exports.frontmatterRE = exports.SUPPORTED_FRONTMATTER_EXTENSIONS_KEYS = exports.SUPPORTED_FRONTMATTER_EXTENSIONS = void 0;
exports.getFrontmatterLanguagePlugin = getFrontmatterLanguagePlugin;
const yaml2ts_1 = require("@astrojs/yaml2ts");
const language_core_1 = require("@volar/language-core");
exports.SUPPORTED_FRONTMATTER_EXTENSIONS = { md: 'markdown', mdx: 'mdx', mdoc: 'markdoc' };
exports.SUPPORTED_FRONTMATTER_EXTENSIONS_KEYS = Object.keys(exports.SUPPORTED_FRONTMATTER_EXTENSIONS);
const SUPPORTED_FRONTMATTER_EXTENSIONS_VALUES = Object.values(exports.SUPPORTED_FRONTMATTER_EXTENSIONS);
exports.frontmatterRE = /^---(.*?)^---/ms;
function getCollectionName(collectionConfig, fileURI) {
for (const collection of collectionConfig.configs) {
if (collection.config.entries[fileURI]) {
return collection.config.entries[fileURI];
}
}
}
function getFrontmatterLanguagePlugin(collectionConfig) {
return {
getLanguageId(scriptId) {
const fileType = exports.SUPPORTED_FRONTMATTER_EXTENSIONS_KEYS.find((ext) => scriptId.path.endsWith(`.${ext}`));
if (fileType) {
return exports.SUPPORTED_FRONTMATTER_EXTENSIONS[fileType];
}
},
createVirtualCode(scriptId, languageId, snapshot) {
if (SUPPORTED_FRONTMATTER_EXTENSIONS_VALUES.includes(languageId)) {
return new FrontmatterHolder(scriptId.fsPath.replace(/\\/g, '/'), languageId, snapshot, getCollectionName(collectionConfig,
// The scriptId here is encoded and somewhat normalized, as such we can't use it directly to compare with
// the file URLs in the collection config entries that Astro generates.
decodeURIComponent(scriptId.toString()).toLowerCase()));
}
},
typescript: {
extraFileExtensions: exports.SUPPORTED_FRONTMATTER_EXTENSIONS_KEYS.map((ext) => ({
extension: ext,
isMixedContent: true,
scriptKind: 7,
})),
getServiceScript(astroCode) {
for (const code of (0, language_core_1.forEachEmbeddedCode)(astroCode)) {
if (code.id === yaml2ts_1.VIRTUAL_CODE_ID) {
return {
code,
extension: '.ts',
scriptKind: 3,
};
}
}
return undefined;
},
},
};
}
class FrontmatterHolder {
constructor(fileName, languageId, snapshot, collection) {
this.fileName = fileName;
this.languageId = languageId;
this.snapshot = snapshot;
this.collection = collection;
this.id = 'frontmatter-holder';
this.hasFrontmatter = false;
this.mappings = [
{
sourceOffsets: [0],
generatedOffsets: [0],
lengths: [this.snapshot.getLength()],
data: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: true,
},
},
];
this.embeddedCodes = [];
this.snapshot = snapshot;
// If the file is not part of a collection, we don't need to do anything
if (!this.collection) {
return;
}
const frontmatterContent = exports.frontmatterRE
.exec(this.snapshot.getText(0, this.snapshot.getLength()))?.[0]
.replaceAll('---', ' ') ?? '';
this.hasFrontmatter = frontmatterContent.length > 0;
this.embeddedCodes.push({
id: `yaml_frontmatter_${this.collection}`,
languageId: 'yaml',
snapshot: {
getText: (start, end) => frontmatterContent.substring(start, end),
getLength: () => frontmatterContent.length,
getChangeRange: () => undefined,
},
mappings: [
{
sourceOffsets: [0],
generatedOffsets: [0],
lengths: [frontmatterContent.length],
data: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: false,
},
},
],
});
if (this.hasFrontmatter) {
const yaml2tsResult = (0, yaml2ts_1.yaml2ts)(frontmatterContent, this.collection);
this.embeddedCodes.push(yaml2tsResult.virtualCode);
}
}
}
exports.FrontmatterHolder = FrontmatterHolder;
//# sourceMappingURL=frontmatterHolders.js.map

View File

@@ -1,23 +0,0 @@
import type { DiagnosticMessage } from '@astrojs/compiler/types';
import { type CodeMapping, type LanguagePlugin, type VirtualCode } from '@volar/language-core';
import type ts from 'typescript';
import type { HTMLDocument } from 'vscode-html-languageservice';
import type { URI } from 'vscode-uri';
import type { PackageInfo } from '../importPackage.js';
import type { AstroMetadata } from './parseAstro';
export declare function addAstroTypes(astroInstall: PackageInfo | undefined, ts: typeof import('typescript'), host: ts.LanguageServiceHost): void;
export declare function getAstroLanguagePlugin(): LanguagePlugin<URI, AstroVirtualCode>;
export declare class AstroVirtualCode implements VirtualCode {
fileName: string;
snapshot: ts.IScriptSnapshot;
id: string;
languageId: string;
mappings: CodeMapping[];
embeddedCodes: VirtualCode[];
astroMeta: AstroMetadata;
compilerDiagnostics: DiagnosticMessage[];
htmlDocument: HTMLDocument;
codegenStacks: never[];
constructor(fileName: string, snapshot: ts.IScriptSnapshot);
get hasCompilationErrors(): boolean;
}

View File

@@ -1,175 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AstroVirtualCode = void 0;
exports.addAstroTypes = addAstroTypes;
exports.getAstroLanguagePlugin = getAstroLanguagePlugin;
const path = __importStar(require("node:path"));
const language_core_1 = require("@volar/language-core");
const utils_js_1 = require("../utils.js");
const astro2tsx_1 = require("./astro2tsx");
const parseAstro_1 = require("./parseAstro");
const parseCSS_1 = require("./parseCSS");
const parseHTML_1 = require("./parseHTML");
const parseJS_js_1 = require("./parseJS.js");
const decoratedHosts = new WeakSet();
function addAstroTypes(astroInstall, ts, host) {
if (decoratedHosts.has(host)) {
return;
}
decoratedHosts.add(host);
const getScriptFileNames = host.getScriptFileNames.bind(host);
const getCompilationSettings = host.getCompilationSettings.bind(host);
host.getScriptFileNames = () => {
const languageServerTypesDirectory = (0, utils_js_1.getLanguageServerTypesDir)(ts);
const fileNames = getScriptFileNames();
const addedFileNames = [];
if (astroInstall) {
addedFileNames.push(...['./env.d.ts', './astro-jsx.d.ts'].map((filePath) => ts.sys.resolvePath(path.resolve(astroInstall.directory, filePath))));
// If Astro version is < 4.0.8, add jsx-runtime-augment.d.ts to the files to fake `JSX` being available from "astro/jsx-runtime".
// TODO: Remove this once a majority of users are on Astro 4.0.8+, erika - 2023-12-28
if (astroInstall.version.major < 4 ||
(astroInstall.version.major === 4 &&
astroInstall.version.minor === 0 &&
astroInstall.version.patch < 8)) {
addedFileNames.push(...['./jsx-runtime-augment.d.ts'].map((filePath) => ts.sys.resolvePath(path.resolve(languageServerTypesDirectory, filePath))));
}
}
else {
// If we don't have an Astro installation, add the fallback types from the language server.
// See the README in packages/language-server/types for more information.
addedFileNames.push(...['./env.d.ts', './astro-jsx.d.ts', './jsx-runtime-fallback.d.ts'].map((f) => ts.sys.resolvePath(path.resolve(languageServerTypesDirectory, f))));
}
return [...fileNames, ...addedFileNames];
};
host.getCompilationSettings = () => {
const baseCompilationSettings = getCompilationSettings();
return {
...baseCompilationSettings,
module: ts.ModuleKind.ESNext ?? 99,
target: ts.ScriptTarget.ESNext ?? 99,
jsx: ts.JsxEmit.Preserve ?? 1,
resolveJsonModule: true,
allowJs: true, // Needed for inline scripts, which are virtual .js files
isolatedModules: true,
moduleResolution: baseCompilationSettings.moduleResolution === ts.ModuleResolutionKind.Classic ||
!baseCompilationSettings.moduleResolution
? ts.ModuleResolutionKind.Node10
: baseCompilationSettings.moduleResolution,
};
};
}
function getAstroLanguagePlugin() {
return {
getLanguageId(uri) {
if (uri.path.endsWith('.astro')) {
return 'astro';
}
},
createVirtualCode(uri, languageId, snapshot) {
if (languageId === 'astro') {
const fileName = uri.fsPath.replace(/\\/g, '/');
return new AstroVirtualCode(fileName, snapshot);
}
},
typescript: {
extraFileExtensions: [{ extension: 'astro', isMixedContent: true, scriptKind: 7 }],
getServiceScript(astroCode) {
for (const code of (0, language_core_1.forEachEmbeddedCode)(astroCode)) {
if (code.id === 'tsx') {
return {
code,
extension: '.tsx',
scriptKind: 4,
};
}
}
return undefined;
},
getExtraServiceScripts(fileName, astroCode) {
const result = [];
for (const code of (0, language_core_1.forEachEmbeddedCode)(astroCode)) {
if (code.id.endsWith('.mjs') || code.id.endsWith('.mts')) {
const fileExtension = code.id.endsWith('.mjs') ? '.mjs' : '.mts';
result.push({
fileName: fileName + '.' + code.id,
code,
extension: fileExtension,
scriptKind: fileExtension === '.mjs'
? 1
: 3,
});
}
}
return result;
},
},
};
}
class AstroVirtualCode {
constructor(fileName, snapshot) {
this.fileName = fileName;
this.snapshot = snapshot;
this.id = 'root';
this.languageId = 'astro';
this.codegenStacks = [];
this.mappings = [
{
sourceOffsets: [0],
generatedOffsets: [0],
lengths: [this.snapshot.getLength()],
data: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: true,
},
},
];
const tsx = (0, astro2tsx_1.astro2tsx)(this.snapshot.getText(0, this.snapshot.getLength()), this.fileName);
const astroMetadata = (0, parseAstro_1.getAstroMetadata)(this.fileName, this.snapshot.getText(0, this.snapshot.getLength()));
const { htmlDocument, virtualCode: htmlVirtualCode } = (0, parseHTML_1.parseHTML)(this.snapshot, astroMetadata.frontmatter.status === 'closed'
? astroMetadata.frontmatter.position.end.offset
: 0);
this.htmlDocument = htmlDocument;
htmlVirtualCode.embeddedCodes = [
...(0, parseCSS_1.extractStylesheets)(tsx.ranges.styles),
...(0, parseJS_js_1.extractScriptTags)(tsx.ranges.scripts),
];
this.astroMeta = { ...astroMetadata, tsxRanges: tsx.ranges };
this.compilerDiagnostics = [...tsx.diagnostics, ...astroMetadata.diagnostics];
this.embeddedCodes = [htmlVirtualCode, tsx.virtualCode];
}
get hasCompilationErrors() {
return (
// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
this.compilerDiagnostics.filter((diag) => diag.severity === 1)
.length > 0);
}
}
exports.AstroVirtualCode = AstroVirtualCode;
//# sourceMappingURL=index.js.map

View File

@@ -1,27 +0,0 @@
import type { ParseOptions, ParseResult, Point } from '@astrojs/compiler/types';
import type { LSPTSXRanges } from './astro2tsx.js';
export type AstroMetadata = ParseResult & {
frontmatter: FrontmatterStatus;
tsxRanges: LSPTSXRanges;
};
export declare function getAstroMetadata(fileName: string, input: string, options?: ParseOptions): Omit<AstroMetadata, 'tsxRanges'>;
interface FrontmatterOpen {
status: 'open';
position: {
start: Point;
end: undefined;
};
}
interface FrontmatterClosed {
status: 'closed';
position: {
start: Point;
end: Point;
};
}
interface FrontmatterNull {
status: 'doesnt-exist';
position: undefined;
}
export type FrontmatterStatus = FrontmatterOpen | FrontmatterClosed | FrontmatterNull;
export {};

View File

@@ -1,85 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAstroMetadata = getAstroMetadata;
const sync_1 = require("@astrojs/compiler/sync");
function getAstroMetadata(fileName, input, options = { position: true }) {
const parseResult = safeParseAst(fileName, input, options);
return {
...parseResult,
frontmatter: getFrontmatterStatus(parseResult.ast, input),
};
}
function safeParseAst(fileName, input, parseOptions) {
try {
const parseResult = (0, sync_1.parse)(input, parseOptions);
return parseResult;
}
catch (e) {
console.error(`There was an error parsing ${fileName}'s AST. An empty AST will be returned instead to avoid breaking the server. Please create an issue: https://github.com/withastro/language-tools/issues\nError: ${e}.`);
return {
ast: {
type: 'root',
children: [],
},
diagnostics: [
{
code: 1000,
location: {
file: fileName,
line: 1,
column: 1,
length: input.length,
},
severity: 1,
text: `The Astro compiler encountered an unknown error while parsing this file's AST. Please create an issue with your code and the error shown in the server's logs: https://github.com/withastro/language-tools/issues`,
},
],
};
}
}
function getFrontmatterStatus(ast, text) {
if (!ast.children || (ast.children && ast.children.length === 0)) {
return {
status: 'doesnt-exist',
position: undefined,
};
}
if (ast.children[0].type === 'frontmatter') {
const frontmatter = ast.children[0];
if (frontmatter.position) {
if (frontmatter.position.end) {
// HACK: The compiler as of 1.5.5 always return an ending position, even if there's only a frontmatter opening
// This hack checks if the frontmatter's ending is the end of the file, and if so, checks if there's a `---`.
// If there's not, it means the compiler returned the EOF with an opened frontmatter
if (frontmatter.position.end.offset === text.length && !text.endsWith('---')) {
return {
status: 'open',
position: {
start: frontmatter.position.start,
end: undefined,
},
};
}
return {
status: 'closed',
position: {
start: frontmatter.position.start,
end: frontmatter.position.end,
},
};
}
return {
status: 'open',
position: {
start: frontmatter.position.start,
end: undefined,
},
};
}
}
return {
status: 'doesnt-exist',
position: undefined,
};
}
//# sourceMappingURL=parseAstro.js.map

View File

@@ -1,3 +0,0 @@
import type { TSXExtractedStyle } from '@astrojs/compiler/types';
import type { VirtualCode } from '@volar/language-core';
export declare function extractStylesheets(styles: TSXExtractedStyle[]): VirtualCode[];

View File

@@ -1,63 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractStylesheets = extractStylesheets;
const muggle_string_1 = require("muggle-string");
const buildMappings_js_1 = require("../buildMappings.js");
const SUPPORTED_LANGUAGES = ['css', 'scss', 'less'];
function isSupportedLanguage(lang) {
return SUPPORTED_LANGUAGES.includes(lang);
}
function extractStylesheets(styles) {
return mergeCSSContextsByLanguage(styles);
}
function mergeCSSContextsByLanguage(inlineStyles) {
const codes = {
css: [],
scss: [],
less: [],
};
for (const cssContext of inlineStyles) {
const currentCode = isSupportedLanguage(cssContext.lang) ? codes[cssContext.lang] : codes.css;
const isStyleAttribute = cssContext.type === 'style-attribute';
if (isStyleAttribute)
currentCode.push('__ { ');
currentCode.push([
cssContext.content,
undefined,
cssContext.position.start,
{
verification: false,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: false,
},
]);
if (isStyleAttribute)
currentCode.push(' }\n');
}
let virtualCodes = [];
for (const lang of SUPPORTED_LANGUAGES) {
if (codes[lang].length) {
virtualCodes.push(createVirtualCodeForLanguage(codes[lang], lang));
}
}
return virtualCodes;
}
function createVirtualCodeForLanguage(code, lang) {
const mappings = (0, buildMappings_js_1.buildMappings)(code);
const text = (0, muggle_string_1.toString)(code);
return {
id: `style.${lang}`,
languageId: lang,
snapshot: {
getText: (start, end) => text.substring(start, end),
getLength: () => text.length,
getChangeRange: () => undefined,
},
embeddedCodes: [],
mappings,
};
}
//# sourceMappingURL=parseCSS.js.map

View File

@@ -1,11 +0,0 @@
import type { VirtualCode } from '@volar/language-core';
import type ts from 'typescript';
import * as html from 'vscode-html-languageservice';
export declare function parseHTML(snapshot: ts.IScriptSnapshot, frontmatterEnd: number): {
virtualCode: VirtualCode;
htmlDocument: html.HTMLDocument;
};
/**
* scan the text and remove any `>` or `<` that cause the tag to end short
*/
export declare function preprocessHTML(text: string, frontmatterEnd?: number): string;

View File

@@ -1,114 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseHTML = parseHTML;
exports.preprocessHTML = preprocessHTML;
const html = __importStar(require("vscode-html-languageservice"));
const utils_1 = require("../plugins/utils");
const htmlLs = html.getLanguageService();
function parseHTML(snapshot, frontmatterEnd) {
const htmlContent = preprocessHTML(snapshot.getText(0, snapshot.getLength()), frontmatterEnd);
return {
virtualCode: getHTMLVirtualCode(htmlContent),
htmlDocument: getHTMLDocument(htmlContent),
};
}
const createScanner = htmlLs.createScanner;
/**
* scan the text and remove any `>` or `<` that cause the tag to end short
*/
function preprocessHTML(text, frontmatterEnd) {
let content = text.split('').fill(' ', 0, frontmatterEnd).join('');
let scanner = createScanner(content);
let token = scanner.scan();
let currentStartTagStart = null;
while (token !== html.TokenType.EOS) {
const offset = scanner.getTokenOffset();
if (token === html.TokenType.StartTagOpen) {
currentStartTagStart = offset;
}
if (token === html.TokenType.StartTagClose) {
if (shouldBlankStartOrEndTagLike(offset)) {
blankStartOrEndTagLike(offset);
}
else {
currentStartTagStart = null;
}
}
if (token === html.TokenType.StartTagSelfClose) {
currentStartTagStart = null;
}
// <Foo checked={a < 1}>
// https://github.com/microsoft/vscode-html-languageservice/blob/71806ef57be07e1068ee40900ef8b0899c80e68a/src/parser/htmlScanner.ts#L327
if (token === html.TokenType.Unknown &&
scanner.getScannerState() === html.ScannerState.WithinTag &&
scanner.getTokenText() === '<' &&
shouldBlankStartOrEndTagLike(offset)) {
blankStartOrEndTagLike(offset);
}
// TODO: Handle TypeScript generics inside expressions / Use the compiler to parse HTML instead?
token = scanner.scan();
}
return content;
function shouldBlankStartOrEndTagLike(offset) {
// not null rather than falsy, otherwise it won't work on first tag(0)
return (currentStartTagStart !== null && (0, utils_1.isInsideExpression)(content, currentStartTagStart, offset));
}
function blankStartOrEndTagLike(offset, state) {
content = content.substring(0, offset) + ' ' + content.substring(offset + 1);
scanner = createScanner(content, offset, state ?? html.ScannerState.WithinTag);
}
}
function getHTMLVirtualCode(preprocessedHTML) {
return {
id: `html`,
languageId: 'html',
snapshot: {
getText: (start, end) => preprocessedHTML.substring(start, end),
getLength: () => preprocessedHTML.length,
getChangeRange: () => undefined,
},
mappings: [
{
sourceOffsets: [0],
generatedOffsets: [0],
lengths: [preprocessedHTML.length],
data: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: false,
},
},
],
embeddedCodes: [],
};
}
function getHTMLDocument(preprocessedHTML) {
return htmlLs.parseHTMLDocument({ getText: () => preprocessedHTML });
}
//# sourceMappingURL=parseHTML.js.map

View File

@@ -1,3 +0,0 @@
import type { TSXExtractedScript } from '@astrojs/compiler/types';
import type { VirtualCode } from '@volar/language-core';
export declare function extractScriptTags(scripts: TSXExtractedScript[]): VirtualCode[];

View File

@@ -1,130 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractScriptTags = extractScriptTags;
const muggle_string_1 = require("muggle-string");
const buildMappings_1 = require("../buildMappings");
function extractScriptTags(scripts) {
const embeddedJSCodes = [];
const moduleScripts = scripts
.filter((script) => script.type === 'module' || script.type === 'processed-module')
.map(moduleScriptToVirtualCode);
const inlineScripts = scripts
.filter((script) =>
// TODO: Change this at some point so that unknown scripts are not included
// We can't guarantee that they are JavaScript, so we shouldn't treat them as such, even if it might work in some cases
// Perhaps we should make it so that the user has to specify the language of the script if it's not a known type (ex: lang="js"), not sure.
script.type === 'event-attribute' || script.type === 'inline' || script.type === 'unknown')
.sort((a, b) => a.position.start - b.position.start);
embeddedJSCodes.push(...moduleScripts);
const mergedJSContext = mergeJSContexts(inlineScripts);
if (mergedJSContext) {
embeddedJSCodes.push(mergedJSContext);
}
const JSONScripts = scripts
.filter((script) => script.type === 'json')
.map(jsonScriptToVirtualCode);
embeddedJSCodes.push(...JSONScripts);
return embeddedJSCodes;
}
function moduleScriptToVirtualCode(script, index) {
let extension = 'mts';
let languageId = 'typescript';
if (script.type === 'module') {
extension = 'mjs';
languageId = 'javascript';
}
return {
id: `${index}.${extension}`,
languageId,
snapshot: {
getText: (start, end) => script.content.substring(start, end),
getLength: () => script.content.length,
getChangeRange: () => undefined,
},
mappings: [
{
sourceOffsets: [script.position.start],
generatedOffsets: [0],
lengths: [script.content.length],
data: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: false,
},
},
],
embeddedCodes: [],
};
}
function jsonScriptToVirtualCode(script, index) {
return {
id: `${index}.json`,
languageId: 'json',
snapshot: {
getText: (start, end) => script.content.substring(start, end),
getLength: () => script.content.length,
getChangeRange: () => undefined,
},
mappings: [
{
sourceOffsets: [script.position.start],
generatedOffsets: [0],
lengths: [script.content.length],
// TODO: Support JSON features
data: {
verification: false,
completion: false,
semantic: false,
navigation: false,
structure: false,
format: false,
},
},
],
embeddedCodes: [],
};
}
/**
* Merge all the inline and non-hoisted scripts into a single `.mjs` file
*/
function mergeJSContexts(inlineScripts) {
if (inlineScripts.length === 0) {
return undefined;
}
const codes = [];
for (const javascriptContext of inlineScripts) {
codes.push([
// Add a semicolon to the end of the event attribute to attempt to prevent errors from spreading to the rest of the document
// This is not perfect, but it's better than nothing
// See: https://github.com/microsoft/vscode/blob/e8e04769ec817a3374c3eaa26a08d3ae491820d5/extensions/html-language-features/server/src/modes/embeddedSupport.ts#L192
javascriptContext.content + ';',
undefined,
javascriptContext.position.start,
{
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: false,
},
]);
}
const mappings = (0, buildMappings_1.buildMappings)(codes);
const text = (0, muggle_string_1.toString)(codes);
return {
id: 'inline.mjs',
languageId: 'javascript',
snapshot: {
getText: (start, end) => text.substring(start, end),
getLength: () => text.length,
getChangeRange: () => undefined,
},
embeddedCodes: [],
mappings,
};
}
//# sourceMappingURL=parseJS.js.map

View File

@@ -1,15 +0,0 @@
import { type CodeInformation, type LanguagePlugin, type Mapping, type VirtualCode } from '@volar/language-core';
import type ts from 'typescript';
import type { URI } from 'vscode-uri';
export declare function getSvelteLanguagePlugin(): LanguagePlugin<URI, SvelteVirtualCode>;
declare class SvelteVirtualCode implements VirtualCode {
fileName: string;
snapshot: ts.IScriptSnapshot;
id: string;
languageId: string;
mappings: Mapping<CodeInformation>[];
embeddedCodes: VirtualCode[];
codegenStacks: never[];
constructor(fileName: string, snapshot: ts.IScriptSnapshot);
}
export {};

View File

@@ -1,47 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSvelteLanguagePlugin = getSvelteLanguagePlugin;
const language_core_1 = require("@volar/language-core");
const utils_js_1 = require("./utils.js");
function getSvelteLanguagePlugin() {
return {
getLanguageId(uri) {
if (uri.path.endsWith('.svelte')) {
return 'svelte';
}
},
createVirtualCode(uri, languageId, snapshot) {
if (languageId === 'svelte') {
const fileName = uri.fsPath.replace(/\\/g, '/');
return new SvelteVirtualCode(fileName, snapshot);
}
},
typescript: {
extraFileExtensions: [{ extension: 'svelte', isMixedContent: true, scriptKind: 7 }],
getServiceScript(svelteCode) {
for (const code of (0, language_core_1.forEachEmbeddedCode)(svelteCode)) {
if (code.id === 'tsx') {
return {
code,
extension: '.tsx',
scriptKind: 4,
};
}
}
},
},
};
}
class SvelteVirtualCode {
constructor(fileName, snapshot) {
this.fileName = fileName;
this.snapshot = snapshot;
this.id = 'root';
this.languageId = 'svelte';
this.codegenStacks = [];
this.mappings = [];
this.embeddedCodes = [];
this.embeddedCodes.push((0, utils_js_1.framework2tsx)(this.fileName, this.snapshot.getText(0, this.snapshot.getLength()), 'svelte'));
}
}
//# sourceMappingURL=svelte.js.map

View File

@@ -1,4 +0,0 @@
import type { VirtualCode } from '@volar/language-core';
export declare function framework2tsx(filePath: string, sourceCode: string, framework: 'vue' | 'svelte'): VirtualCode;
export declare function classNameFromFilename(filename: string): string;
export declare function patchTSX(code: string, filePath: string): string;

View File

@@ -1,73 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.framework2tsx = framework2tsx;
exports.classNameFromFilename = classNameFromFilename;
exports.patchTSX = patchTSX;
const vscode_uri_1 = require("vscode-uri");
const importPackage_1 = require("../importPackage");
function framework2tsx(filePath, sourceCode, framework) {
const integrationEditorEntrypoint = framework === 'vue' ? (0, importPackage_1.importVueIntegration)(filePath) : (0, importPackage_1.importSvelteIntegration)(filePath);
if (!integrationEditorEntrypoint) {
const EMPTY_FILE = '';
return getVirtualCode(EMPTY_FILE);
}
const className = classNameFromFilename(filePath);
const tsx = patchTSX(integrationEditorEntrypoint.toTSX(sourceCode, className), filePath);
return getVirtualCode(tsx);
function getVirtualCode(content) {
return {
id: 'tsx',
languageId: 'typescript',
snapshot: {
getText: (start, end) => content.substring(start, end),
getLength: () => content.length,
getChangeRange: () => undefined,
},
mappings: [],
embeddedCodes: [],
};
}
}
/**
* Transform a string into PascalCase
*/
function toPascalCase(string) {
return `${string}`
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), '')
.replace(new RegExp(/\s+(.)(\w*)/, 'g'), ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`)
.replace(new RegExp(/\w/), (s) => s.toUpperCase());
}
function classNameFromFilename(filename) {
const url = vscode_uri_1.URI.parse(filename);
const withoutExtensions = vscode_uri_1.Utils.basename(url).slice(0, -vscode_uri_1.Utils.extname(url).length);
const withoutInvalidCharacters = withoutExtensions
.split('')
// Although "-" is invalid, we leave it in, pascal-case-handling will throw it out later
.filter((char) => /[\w$-]/.test(char))
.join('');
const firstValidCharIdx = withoutInvalidCharacters
.split('')
// Although _ and $ are valid first characters for classes, they are invalid first characters
// for tag names. For a better import autocompletion experience, we therefore throw them out.
.findIndex((char) => /[A-Za-z]/.test(char));
const withoutLeadingInvalidCharacters = withoutInvalidCharacters.substring(firstValidCharIdx);
const inPascalCase = toPascalCase(withoutLeadingInvalidCharacters);
const finalName = firstValidCharIdx === -1 ? `A${inPascalCase}` : inPascalCase;
return finalName;
}
// TODO: Patch the upstream packages with these changes
function patchTSX(code, filePath) {
const basename = filePath.split('/').pop();
const isDynamic = basename.startsWith('[') && basename.endsWith(']');
return code.replace(/\b(\S*)__AstroComponent_/g, (fullMatch, m1) => {
// If we don't have a match here, it usually means the file has a weird name that couldn't be expressed with valid identifier characters
if (!m1) {
if (basename === '404')
return 'FourOhFour';
return fullMatch;
}
return isDynamic ? `_${m1}_` : m1[0].toUpperCase() + m1.slice(1);
});
}
//# sourceMappingURL=utils.js.map

View File

@@ -1,15 +0,0 @@
import { type CodeInformation, type LanguagePlugin, type Mapping, type VirtualCode } from '@volar/language-core';
import type ts from 'typescript';
import type { URI } from 'vscode-uri';
export declare function getVueLanguagePlugin(): LanguagePlugin<URI, VueVirtualCode>;
declare class VueVirtualCode implements VirtualCode {
fileName: string;
snapshot: ts.IScriptSnapshot;
id: string;
languageId: string;
mappings: Mapping<CodeInformation>[];
embeddedCodes: VirtualCode[];
codegenStacks: never[];
constructor(fileName: string, snapshot: ts.IScriptSnapshot);
}
export {};

View File

@@ -1,47 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getVueLanguagePlugin = getVueLanguagePlugin;
const language_core_1 = require("@volar/language-core");
const utils_js_1 = require("./utils.js");
function getVueLanguagePlugin() {
return {
getLanguageId(uri) {
if (uri.path.endsWith('.vue')) {
return 'vue';
}
},
createVirtualCode(uri, languageId, snapshot) {
if (languageId === 'vue') {
const fileName = uri.fsPath.replace(/\\/g, '/');
return new VueVirtualCode(fileName, snapshot);
}
},
typescript: {
extraFileExtensions: [{ extension: 'vue', isMixedContent: true, scriptKind: 7 }],
getServiceScript(vueCode) {
for (const code of (0, language_core_1.forEachEmbeddedCode)(vueCode)) {
if (code.id === 'tsx') {
return {
code,
extension: '.tsx',
scriptKind: 4,
};
}
}
},
},
};
}
class VueVirtualCode {
constructor(fileName, snapshot) {
this.fileName = fileName;
this.snapshot = snapshot;
this.id = 'root';
this.languageId = 'vue';
this.codegenStacks = [];
this.mappings = [];
this.embeddedCodes = [];
this.embeddedCodes.push((0, utils_js_1.framework2tsx)(this.fileName, this.snapshot.getText(0, this.snapshot.getLength()), 'vue'));
}
}
//# sourceMappingURL=vue.js.map