@tsrx/language-server 0.6.2 → 0.7.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.
|
@@ -2397,6 +2397,12 @@ var TSRXVirtualCode = class {
|
|
|
2397
2397
|
originalCode = "";
|
|
2398
2398
|
/** @type {AST.Program | null} */
|
|
2399
2399
|
sourceAst = null;
|
|
2400
|
+
/**
|
|
2401
|
+
* The `<script>` bodies of code (not data blocks) the transform appends to the
|
|
2402
|
+
* generated TSX as blocks; empty while the file has a fatal compile error.
|
|
2403
|
+
* @type {EmbeddedRegion[]}
|
|
2404
|
+
*/
|
|
2405
|
+
scriptRegions = [];
|
|
2400
2406
|
/** @type {boolean} */
|
|
2401
2407
|
isDotCompletionMode = false;
|
|
2402
2408
|
/** @type {unknown[]} */
|
|
@@ -2439,6 +2445,7 @@ var TSRXVirtualCode = class {
|
|
|
2439
2445
|
this.fatalErrors = [];
|
|
2440
2446
|
this.usageErrors = [];
|
|
2441
2447
|
this.sourceAst = null;
|
|
2448
|
+
this.scriptRegions = [];
|
|
2442
2449
|
this.isDotCompletionMode = false;
|
|
2443
2450
|
let isDotTyped = false;
|
|
2444
2451
|
let dotPosition = -1;
|
|
@@ -2497,7 +2504,7 @@ var TSRXVirtualCode = class {
|
|
|
2497
2504
|
}
|
|
2498
2505
|
if (result.fatalError) {
|
|
2499
2506
|
logError$4("TSRX compilation failed for", this.fileName, ":", result.fatalError);
|
|
2500
|
-
if (process.env.TSRX_TSC === "true") logTSRXErrors(this.fileName, [result.fatalError]);
|
|
2507
|
+
if (process.env.TSRX_TSC === "true") logTSRXErrors(this.fileName, [result.fatalError], newCode);
|
|
2501
2508
|
this.fatalErrors.push(result.fatalError);
|
|
2502
2509
|
files_with_fatal_compile_error.add(normalize_file_name_key(this.fileName));
|
|
2503
2510
|
} else {
|
|
@@ -2506,11 +2513,12 @@ var TSRXVirtualCode = class {
|
|
|
2506
2513
|
}
|
|
2507
2514
|
this.originalCode = newCode;
|
|
2508
2515
|
if (!result.fatalError && result.text) {
|
|
2509
|
-
this.generatedCode = result.text;
|
|
2516
|
+
this.generatedCode = hashbang_as_comment(result.text);
|
|
2510
2517
|
this.mappings = result.mappings;
|
|
2511
2518
|
this.usageErrors = result.errors;
|
|
2512
2519
|
this.sourceAst = result.sourceAst;
|
|
2513
|
-
|
|
2520
|
+
this.scriptRegions = result.scriptRegions;
|
|
2521
|
+
if (process.env.TSRX_TSC === "true" && result.errors.length > 0) logTSRXErrors(this.fileName, result.errors, newCode);
|
|
2514
2522
|
if (result.cssRegions.length > 0) log$9("Creating", result.cssRegions.length, "CSS embedded codes");
|
|
2515
2523
|
this.embeddedCodes = result.cssRegions.map((region) => create_embedded_code_from_region(region, "css"));
|
|
2516
2524
|
if (DEBUG) {
|
|
@@ -2529,7 +2537,7 @@ var TSRXVirtualCode = class {
|
|
|
2529
2537
|
}
|
|
2530
2538
|
} else {
|
|
2531
2539
|
log$9("Compilation failed, only display where the compilation error occurred.");
|
|
2532
|
-
this.generatedCode = newCode;
|
|
2540
|
+
this.generatedCode = hashbang_as_comment(newCode);
|
|
2533
2541
|
this.mappings = [{
|
|
2534
2542
|
sourceOffsets: [0],
|
|
2535
2543
|
generatedOffsets: [0],
|
|
@@ -2628,6 +2636,19 @@ var TSRXVirtualCode = class {
|
|
|
2628
2636
|
}
|
|
2629
2637
|
};
|
|
2630
2638
|
/**
|
|
2639
|
+
* Volar puts the generated code after blank lines as long as the source in the
|
|
2640
|
+
* file TypeScript reads (in tsserver and `tsrx-tsc`), so a `#!` line there is no
|
|
2641
|
+
* longer at the start of the file and TypeScript reads it as code: two
|
|
2642
|
+
* expression statements without `;`. They count when TypeScript infers the
|
|
2643
|
+
* semicolon style of an edit, so an import added to a file whose own statements
|
|
2644
|
+
* have no `;` lost its `;`. A line comment of the same length keeps every offset.
|
|
2645
|
+
* @param {string} code
|
|
2646
|
+
* @returns {string}
|
|
2647
|
+
*/
|
|
2648
|
+
function hashbang_as_comment(code) {
|
|
2649
|
+
return code.startsWith("#!") ? `//${code.slice(2)}` : code;
|
|
2650
|
+
}
|
|
2651
|
+
/**
|
|
2631
2652
|
* Clamp an intra-token offset into `[0, length]`.
|
|
2632
2653
|
* @param {number} offset
|
|
2633
2654
|
* @param {number} length
|
|
@@ -2637,20 +2658,70 @@ function clamp_offset(offset, length) {
|
|
|
2637
2658
|
return Math.min(Math.max(offset, 0), length);
|
|
2638
2659
|
}
|
|
2639
2660
|
/**
|
|
2661
|
+
* @typedef {{
|
|
2662
|
+
* message?: unknown,
|
|
2663
|
+
* code?: unknown,
|
|
2664
|
+
* severity?: unknown,
|
|
2665
|
+
* type?: unknown,
|
|
2666
|
+
* pos?: unknown,
|
|
2667
|
+
* loc?: { line?: unknown, column?: unknown, start?: { line?: unknown, column?: unknown } },
|
|
2668
|
+
* }} LoggedDiagnostic
|
|
2669
|
+
*/
|
|
2670
|
+
/**
|
|
2671
|
+
* Mirrors compiler diagnostics to stderr under `tsrx-tsc`. The line follows
|
|
2672
|
+
* tsc's `file(line,col): error TS2339: message` convention — position when the
|
|
2673
|
+
* diagnostic has one, then severity and the diagnostic `code` — so output is
|
|
2674
|
+
* greppable by code and actionable by position. A thrown (fatal) error stops
|
|
2675
|
+
* the compile, so it prints as an error whatever its `severity`, as the
|
|
2676
|
+
* language server shows it.
|
|
2640
2677
|
* @param {string} file_name
|
|
2641
2678
|
* @param {ReadonlyArray<unknown>} errors
|
|
2679
|
+
* @param {string} source the compiled text, which a diagnostic's `pos` indexes
|
|
2642
2680
|
*/
|
|
2643
|
-
function logTSRXErrors(file_name, errors) {
|
|
2681
|
+
function logTSRXErrors(file_name, errors, source) {
|
|
2644
2682
|
for (const error of errors) {
|
|
2645
|
-
const
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
const
|
|
2683
|
+
const details = error && typeof error === "object" ? error : void 0;
|
|
2684
|
+
const message = details && "message" in details ? String(details.message) : String(error);
|
|
2685
|
+
const severity = details?.severity === "warning" && details.type !== "fatal" ? "warning" : "error";
|
|
2686
|
+
const code = typeof details?.code === "string" && details.code.length > 0 ? details.code : void 0;
|
|
2687
|
+
const label = code === void 0 ? severity : `${severity} ${code}`;
|
|
2688
|
+
const start = diagnostic_start(details, source);
|
|
2689
|
+
const position = start ? `(${start.line},${start.column + 1})` : "";
|
|
2690
|
+
const key = `${file_name}\0${position}\0${label}\0${message}`;
|
|
2650
2691
|
if (loggedCompilationFailures.has(key)) continue;
|
|
2651
2692
|
loggedCompilationFailures.add(key);
|
|
2652
|
-
console.error(`[tsrx-tsc] ${file_name}: ${message}`);
|
|
2693
|
+
console.error(`[tsrx-tsc] ${file_name}${position}: ${label}: ${message}`);
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
const LINE_BREAK = /\r\n?|[\n\u2028\u2029]/g;
|
|
2697
|
+
/**
|
|
2698
|
+
* Where a diagnostic starts, as a 1-based line and a 0-based column. A
|
|
2699
|
+
* collected error's `loc` is a range, and a parse error acorn throws gives its
|
|
2700
|
+
* position as `loc` itself (`{ line, column }`). A diagnostic without `loc`,
|
|
2701
|
+
* such as one a consumer compiler builds with only `pos` and `end`, is placed
|
|
2702
|
+
* by `pos` in `source`, breaking lines where tsc does.
|
|
2703
|
+
* @param {LoggedDiagnostic | undefined} details
|
|
2704
|
+
* @param {string} source
|
|
2705
|
+
* @returns {{ line: number, column: number } | undefined}
|
|
2706
|
+
*/
|
|
2707
|
+
function diagnostic_start(details, source) {
|
|
2708
|
+
const start = details?.loc?.start ?? details?.loc;
|
|
2709
|
+
if (typeof start?.line === "number" && typeof start?.column === "number") return {
|
|
2710
|
+
line: start.line,
|
|
2711
|
+
column: start.column
|
|
2712
|
+
};
|
|
2713
|
+
const pos = details?.pos;
|
|
2714
|
+
if (typeof pos !== "number" || pos < 0 || pos > source.length) return void 0;
|
|
2715
|
+
let line = 1;
|
|
2716
|
+
let line_start = 0;
|
|
2717
|
+
for (const match of source.slice(0, pos).matchAll(LINE_BREAK)) {
|
|
2718
|
+
line++;
|
|
2719
|
+
line_start = match.index + match[0].length;
|
|
2653
2720
|
}
|
|
2721
|
+
return {
|
|
2722
|
+
line,
|
|
2723
|
+
column: pos - line_start
|
|
2724
|
+
};
|
|
2654
2725
|
}
|
|
2655
2726
|
/**
|
|
2656
2727
|
* Build an embedded virtual code from a `<style>` / `<script>` region produced
|
|
@@ -6418,7 +6489,7 @@ var main_exports$1 = /* @__PURE__ */ __exportAll({
|
|
|
6418
6489
|
TextDocumentIdentifier: () => TextDocumentIdentifier,
|
|
6419
6490
|
TextDocumentItem: () => TextDocumentItem,
|
|
6420
6491
|
TextEdit: () => TextEdit,
|
|
6421
|
-
URI: () => URI$
|
|
6492
|
+
URI: () => URI$5,
|
|
6422
6493
|
VersionedTextDocumentIdentifier: () => VersionedTextDocumentIdentifier,
|
|
6423
6494
|
WorkspaceChange: () => WorkspaceChange,
|
|
6424
6495
|
WorkspaceEdit: () => WorkspaceEdit,
|
|
@@ -6427,7 +6498,7 @@ var main_exports$1 = /* @__PURE__ */ __exportAll({
|
|
|
6427
6498
|
integer: () => integer,
|
|
6428
6499
|
uinteger: () => uinteger
|
|
6429
6500
|
});
|
|
6430
|
-
var DocumentUri, URI$
|
|
6501
|
+
var DocumentUri, URI$5, integer, uinteger, Position, Range, Location, LocationLink, Color, ColorInformation, ColorPresentation, FoldingRangeKind, FoldingRange, DiagnosticRelatedInformation, DiagnosticSeverity$1, DiagnosticTag, CodeDescription, Diagnostic, Command, TextEdit, ChangeAnnotation, ChangeAnnotationIdentifier, AnnotatedTextEdit, TextDocumentEdit, CreateFile, RenameFile, DeleteFile, WorkspaceEdit, TextEditChangeImpl, SnippetTextEdit, ChangeAnnotations, WorkspaceChange, TextDocumentIdentifier, VersionedTextDocumentIdentifier, OptionalVersionedTextDocumentIdentifier, LanguageKind, TextDocumentItem, MarkupKind, MarkupContent, CompletionItemKind$1, InsertTextFormat$1, CompletionItemTag, InsertReplaceEdit, InsertTextMode, ApplyKind, CompletionItemLabelDetails, CompletionItem, CompletionList, MarkedString, Hover, ParameterInformation, SignatureInformation, DocumentHighlightKind, DocumentHighlight, SymbolKind$1, SymbolTag, SymbolInformation, WorkspaceSymbol, DocumentSymbol, CodeActionKind, CodeActionTriggerKind, CodeActionContext, CodeActionTag, CodeAction, CodeLens, FormattingOptions, DocumentLink, SelectionRange, SemanticTokenTypes, SemanticTokenModifiers, SemanticTokens, InlineValueText, InlineValueVariableLookup, InlineValueEvaluatableExpression, InlineValueContext, InlayHintKind, InlayHintLabelPart, InlayHint, StringValue, InlineCompletionItem, InlineCompletionList, InlineCompletionTriggerKind, SelectedCompletionInfo, InlineCompletionContext, WorkspaceFolder, EOL, TextDocument$1, FullTextDocument$1, Is;
|
|
6431
6502
|
var init_main$1 = __esmMin((() => {
|
|
6432
6503
|
;
|
|
6433
6504
|
(function(DocumentUri) {
|
|
@@ -6442,7 +6513,7 @@ var init_main$1 = __esmMin((() => {
|
|
|
6442
6513
|
return typeof value === "string";
|
|
6443
6514
|
}
|
|
6444
6515
|
URI.is = is;
|
|
6445
|
-
})(URI$
|
|
6516
|
+
})(URI$5 || (URI$5 = {}));
|
|
6446
6517
|
;
|
|
6447
6518
|
(function(integer) {
|
|
6448
6519
|
integer.MIN_VALUE = -2147483648;
|
|
@@ -8277,7 +8348,7 @@ var init_main$1 = __esmMin((() => {
|
|
|
8277
8348
|
(function(WorkspaceFolder) {
|
|
8278
8349
|
function is(value) {
|
|
8279
8350
|
const candidate = value;
|
|
8280
|
-
return Is.objectLiteral(candidate) && URI$
|
|
8351
|
+
return Is.objectLiteral(candidate) && URI$5.is(candidate.uri) && Is.string(candidate.name);
|
|
8281
8352
|
}
|
|
8282
8353
|
WorkspaceFolder.is = is;
|
|
8283
8354
|
})(WorkspaceFolder || (WorkspaceFolder = {}));
|
|
@@ -22683,8 +22754,86 @@ function typescript_notice(found, workspace_dirs) {
|
|
|
22683
22754
|
].join(" ");
|
|
22684
22755
|
}
|
|
22685
22756
|
|
|
22757
|
+
//#endregion
|
|
22758
|
+
//#region ../typescript-plugin/src/unclosed-element.js
|
|
22759
|
+
/** @import * as AST from 'estree' */
|
|
22760
|
+
/**
|
|
22761
|
+
* Elements whose body is raw text, each with a pattern for its opening tag. The
|
|
22762
|
+
* body ends at the next `</style>` or `<\/script>`, wherever it is later in the
|
|
22763
|
+
* file, so that closing tag can belong to a later element (see `isUnclosed`).
|
|
22764
|
+
*/
|
|
22765
|
+
const RAW_TEXT_OPENING_TAGS = /* @__PURE__ */ new Map([["style", /<style[\s/>]/], ["script", /<script[\s/>]/]]);
|
|
22766
|
+
/**
|
|
22767
|
+
* An element of the parsed source and, when the element is one of its children,
|
|
22768
|
+
* the element that holds it.
|
|
22769
|
+
* @typedef {{ element: AST.TSRXJSXElement; parent: ElementPath | null }} ElementPath
|
|
22770
|
+
*/
|
|
22771
|
+
/**
|
|
22772
|
+
* Find the element whose opening tag ends at `end` in the parsed source.
|
|
22773
|
+
* @param {unknown} node
|
|
22774
|
+
* @param {number} end - The offset right after the opening tag's `>`
|
|
22775
|
+
* @param {ElementPath | null} [parent] - The element whose `children` hold `node`
|
|
22776
|
+
* @returns {ElementPath | null}
|
|
22777
|
+
*/
|
|
22778
|
+
function findElement(node, end, parent = null) {
|
|
22779
|
+
if (Array.isArray(node)) {
|
|
22780
|
+
for (const child of node) {
|
|
22781
|
+
const found = findElement(child, end, parent);
|
|
22782
|
+
if (found) return found;
|
|
22783
|
+
}
|
|
22784
|
+
return null;
|
|
22785
|
+
}
|
|
22786
|
+
if (!node || typeof node !== "object") return null;
|
|
22787
|
+
const element = node;
|
|
22788
|
+
const path = element.openingElement ? {
|
|
22789
|
+
element,
|
|
22790
|
+
parent
|
|
22791
|
+
} : null;
|
|
22792
|
+
if (path?.element.openingElement.end === end) return path;
|
|
22793
|
+
for (const [key, value] of Object.entries(node)) {
|
|
22794
|
+
if (key === "loc" || key === "metadata") continue;
|
|
22795
|
+
const found = findElement(value, end, key === "children" ? path : null);
|
|
22796
|
+
if (found) return found;
|
|
22797
|
+
}
|
|
22798
|
+
return null;
|
|
22799
|
+
}
|
|
22800
|
+
/**
|
|
22801
|
+
* Whether the element still needs its closing tag, decided like TypeScript's
|
|
22802
|
+
* `isUnclosedTag`: the element is unclosed, or it took the closing tag of a parent
|
|
22803
|
+
* with the same name (`<div>` typed as the first child of a `<div>`), which is then
|
|
22804
|
+
* the unclosed one. Loose-mode recovery marks an element without its closing tag
|
|
22805
|
+
* `unclosed`.
|
|
22806
|
+
*
|
|
22807
|
+
* A `<style>` or `<script>` body ends at the next closing tag with its name, which
|
|
22808
|
+
* can belong to a later element: a new `<style>` typed in one component takes the
|
|
22809
|
+
* `</style>` of the style block in the next component. That element's opening tag
|
|
22810
|
+
* is then in the body, so the new element still needs its own closing tag.
|
|
22811
|
+
* @param {ElementPath} path
|
|
22812
|
+
* @param {string} sourceCode
|
|
22813
|
+
* @returns {boolean}
|
|
22814
|
+
*/
|
|
22815
|
+
function isUnclosed(path, sourceCode) {
|
|
22816
|
+
/** @param {AST.TSRXJSXElement} element */
|
|
22817
|
+
const name = (element) => {
|
|
22818
|
+
const { start, end } = element.openingElement.name;
|
|
22819
|
+
return sourceCode.slice(start, end);
|
|
22820
|
+
};
|
|
22821
|
+
const { element } = path;
|
|
22822
|
+
const rawTextOpeningTag = RAW_TEXT_OPENING_TAGS.get(name(element));
|
|
22823
|
+
if (rawTextOpeningTag) {
|
|
22824
|
+
if (element.unclosed || !element.closingElement) return true;
|
|
22825
|
+
const bodyEnd = element.closingElement.start;
|
|
22826
|
+
return rawTextOpeningTag.test(sourceCode.slice(element.openingElement.end, bodyEnd));
|
|
22827
|
+
}
|
|
22828
|
+
for (let current = path;; current = current.parent) {
|
|
22829
|
+
if (current.element.unclosed) return true;
|
|
22830
|
+
if (!current.parent || name(current.parent.element) !== name(current.element)) return false;
|
|
22831
|
+
}
|
|
22832
|
+
}
|
|
22833
|
+
|
|
22686
22834
|
//#endregion
|
|
22687
22835
|
//#region src/autoInsertPlugin.js
|
|
22836
|
+
/** @import * as AST from 'estree' */
|
|
22688
22837
|
/** @import { LanguageServicePlugin } from '@volar/language-server' */
|
|
22689
22838
|
const { log: log$8 } = createLogging("[TSRX Auto-Insert Plugin]");
|
|
22690
22839
|
/**
|
|
@@ -22786,7 +22935,8 @@ async provideAutoInsertSnippet(document, position, lastChange, _token) {
|
|
|
22786
22935
|
return null;
|
|
22787
22936
|
}
|
|
22788
22937
|
const closingTag = `</${tagName}>`;
|
|
22789
|
-
|
|
22938
|
+
const element = virtualCode.isDotCompletionMode ? null : findElement(virtualCode.sourceAst, sourceOffset + 1);
|
|
22939
|
+
if (element ? !isUnclosed(element, sourceCode) : sourceCode.startsWith(closingTag, sourceOffset + 1)) {
|
|
22790
22940
|
log$8("Closing tag already exists, skipping");
|
|
22791
22941
|
return null;
|
|
22792
22942
|
}
|
|
@@ -22980,7 +23130,7 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
22980
23130
|
let start = null;
|
|
22981
23131
|
/** @type {Position | null} */
|
|
22982
23132
|
let end = null;
|
|
22983
|
-
if (error.pos) {
|
|
23133
|
+
if (error.pos !== void 0) {
|
|
22984
23134
|
const start_offset = get_start_offset_from_error(error);
|
|
22985
23135
|
const end_offset = get_end_offset_from_error(error, start_offset);
|
|
22986
23136
|
const mapping = virtualCode.findMappingBySourceRange(start_offset, end_offset);
|
|
@@ -23001,6 +23151,13 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
23001
23151
|
}
|
|
23002
23152
|
}
|
|
23003
23153
|
}
|
|
23154
|
+
if (!start || !end) {
|
|
23155
|
+
const nearest = nearest_reported_range(virtualCode, start_offset, error.raisedAt);
|
|
23156
|
+
if (nearest) {
|
|
23157
|
+
start = document.positionAt(nearest[0]);
|
|
23158
|
+
end = document.positionAt(nearest[1]);
|
|
23159
|
+
}
|
|
23160
|
+
}
|
|
23004
23161
|
}
|
|
23005
23162
|
if (!start || !end) {
|
|
23006
23163
|
start = {
|
|
@@ -23013,7 +23170,7 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
23013
23170
|
};
|
|
23014
23171
|
}
|
|
23015
23172
|
return {
|
|
23016
|
-
severity: import_language_server.DiagnosticSeverity.Error,
|
|
23173
|
+
severity: error.severity === "warning" ? import_language_server.DiagnosticSeverity.Warning : import_language_server.DiagnosticSeverity.Error,
|
|
23017
23174
|
range: {
|
|
23018
23175
|
start,
|
|
23019
23176
|
end
|
|
@@ -23024,6 +23181,56 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
23024
23181
|
};
|
|
23025
23182
|
}
|
|
23026
23183
|
/**
|
|
23184
|
+
* The generated range of the source token that reports diagnostics and starts
|
|
23185
|
+
* nearest after `offset`, when it starts before `reach`. Otherwise the one that
|
|
23186
|
+
* ends nearest before `offset`, or starts nearest after it when none ends
|
|
23187
|
+
* before it. Of tokens the same distance away, the shortest. A mapping over
|
|
23188
|
+
* whitespace only, such as the indentation before a template's output, is not
|
|
23189
|
+
* code to show the error on.
|
|
23190
|
+
* @param {TSRXVirtualCodeInstance} virtualCode
|
|
23191
|
+
* @param {number} offset
|
|
23192
|
+
* @param {number} [reach] Where the error's parser stopped, such as the token that ended a template
|
|
23193
|
+
* @returns {[number, number] | null}
|
|
23194
|
+
*/
|
|
23195
|
+
function nearest_reported_range(virtualCode, offset, reach = offset) {
|
|
23196
|
+
/** @type {{ range: [number, number], distance: number, length: number } | null} */
|
|
23197
|
+
let before = null;
|
|
23198
|
+
/** @type {{ range: [number, number], distance: number, length: number, start: number } | null} */
|
|
23199
|
+
let after = null;
|
|
23200
|
+
for (const mapping of virtualCode.mappings ?? []) {
|
|
23201
|
+
if (!mapping.data?.verification) continue;
|
|
23202
|
+
for (let i = 0; i < mapping.sourceOffsets.length; i++) {
|
|
23203
|
+
const source_start = mapping.sourceOffsets[i];
|
|
23204
|
+
const length = mapping.lengths[i];
|
|
23205
|
+
const generated_length = mapping.generatedLengths?.[i] ?? length;
|
|
23206
|
+
if (length === 0 || generated_length <= 0) continue;
|
|
23207
|
+
if (!/\S/.test(virtualCode.originalCode.slice(source_start, source_start + length))) continue;
|
|
23208
|
+
const generated_start = mapping.generatedOffsets[i];
|
|
23209
|
+
const ends_before = source_start + length <= offset;
|
|
23210
|
+
if (!ends_before && source_start < offset) continue;
|
|
23211
|
+
const candidate = {
|
|
23212
|
+
/** @type {[number, number]} */
|
|
23213
|
+
range: [generated_start, generated_start + generated_length],
|
|
23214
|
+
distance: ends_before ? offset - (source_start + length) : source_start - offset,
|
|
23215
|
+
length,
|
|
23216
|
+
start: source_start
|
|
23217
|
+
};
|
|
23218
|
+
if (ends_before) {
|
|
23219
|
+
if (is_nearer(candidate, before)) before = candidate;
|
|
23220
|
+
} else if (is_nearer(candidate, after)) after = candidate;
|
|
23221
|
+
}
|
|
23222
|
+
}
|
|
23223
|
+
if (after && after.start < reach) return after.range;
|
|
23224
|
+
return (before ?? after)?.range ?? null;
|
|
23225
|
+
}
|
|
23226
|
+
/**
|
|
23227
|
+
* @param {{ distance: number, length: number }} candidate
|
|
23228
|
+
* @param {{ distance: number, length: number } | null} best
|
|
23229
|
+
*/
|
|
23230
|
+
function is_nearer(candidate, best) {
|
|
23231
|
+
return !best || candidate.distance < best.distance || candidate.distance === best.distance && candidate.length < best.length;
|
|
23232
|
+
}
|
|
23233
|
+
/**
|
|
23027
23234
|
* @param {CompileError} error
|
|
23028
23235
|
* @param {TextDocument} document
|
|
23029
23236
|
* @returns {Range}
|
|
@@ -23924,6 +24131,14 @@ init_main();
|
|
|
23924
24131
|
* }} NodeWithId;
|
|
23925
24132
|
*/
|
|
23926
24133
|
/**
|
|
24134
|
+
* A raw-text `<script>` element, its body verbatim in `content`.
|
|
24135
|
+
* @typedef {{
|
|
24136
|
+
* openingElement: { name: { start: number, end: number }, end: number },
|
|
24137
|
+
* closingElement: { name: { end: number } } | null,
|
|
24138
|
+
* content: string,
|
|
24139
|
+
* }} ScriptElement;
|
|
24140
|
+
*/
|
|
24141
|
+
/**
|
|
23927
24142
|
* @typedef {[
|
|
23928
24143
|
* Omit<DocumentSymbol, 'children'> & { children: SymbolInfo[] }, {
|
|
23929
24144
|
* rangeNode: AST.Node;
|
|
@@ -23956,7 +24171,7 @@ function createDocumentSymbolPlugin() {
|
|
|
23956
24171
|
if (virtualCode?.fatalErrors?.length || virtualCode?.isDotCompletionMode) return collectFallbackDocumentSymbols(document, fallbackFileName) ?? cachedSymbols;
|
|
23957
24172
|
if (!sourceMap || !sourceAst) return collectFallbackDocumentSymbols(document, fallbackFileName) ?? [];
|
|
23958
24173
|
const sourceDocument = TextDocument.create(sourceUri.toString(), "tsrx", 0, originalCode);
|
|
23959
|
-
const symbols = mapDocumentSymbolsToGenerated(collectDocumentSymbols(sourceAst, sourceDocument), virtualCode, sourceDocument, document, sourceMap);
|
|
24174
|
+
const symbols = mapDocumentSymbolsToGenerated(collectDocumentSymbols(sourceAst, sourceDocument, virtualCode.scriptRegions), virtualCode, sourceDocument, document, sourceMap);
|
|
23960
24175
|
documentSymbolCache.set(cacheKey, symbols);
|
|
23961
24176
|
return symbols;
|
|
23962
24177
|
} };
|
|
@@ -24097,10 +24312,70 @@ function isSymbolMapping(data) {
|
|
|
24097
24312
|
/**
|
|
24098
24313
|
* @param {AST.Program} ast
|
|
24099
24314
|
* @param {TextDocument} document
|
|
24315
|
+
* @param {Array<{ start: number, content: string }>} [scriptRegions] The `<script>` bodies of
|
|
24316
|
+
* code, from the compiler's script mappings.
|
|
24100
24317
|
* @returns {SymbolInfo[]}
|
|
24101
24318
|
*/
|
|
24102
|
-
function collectDocumentSymbols(ast, document) {
|
|
24103
|
-
|
|
24319
|
+
function collectDocumentSymbols(ast, document, scriptRegions = []) {
|
|
24320
|
+
const symbols = collectSymbolsFromStatements(Array.isArray(ast.body) ? ast.body : [], document);
|
|
24321
|
+
if (scriptRegions.length > 0) {
|
|
24322
|
+
const elements = findScriptElements(ast);
|
|
24323
|
+
for (const region of scriptRegions) {
|
|
24324
|
+
const element = elements.get(region.start);
|
|
24325
|
+
if (element) symbols.push(createScriptSymbol(element, region, document));
|
|
24326
|
+
}
|
|
24327
|
+
}
|
|
24328
|
+
return symbols.sort(([, a], [, b]) => a.rangeNode.start - b.rangeNode.start);
|
|
24329
|
+
}
|
|
24330
|
+
/**
|
|
24331
|
+
* The `<script>` elements of a source AST, by the offset where their body starts (the end of
|
|
24332
|
+
* the opening tag), which is where the compiler's script regions start.
|
|
24333
|
+
* @param {AST.Node} ast
|
|
24334
|
+
* @returns {Map<number, ScriptElement>}
|
|
24335
|
+
*/
|
|
24336
|
+
function findScriptElements(ast) {
|
|
24337
|
+
/** @type {Map<number, ScriptElement>} */
|
|
24338
|
+
const elements = /* @__PURE__ */ new Map();
|
|
24339
|
+
/** @param {any} node */
|
|
24340
|
+
const visit = (node) => {
|
|
24341
|
+
if (node.type === "JSXElement" && node.openingElement?.name?.type === "JSXIdentifier" && node.openingElement.name.name === "script" && typeof node.content === "string") elements.set(node.openingElement.end, node);
|
|
24342
|
+
for (const key in node) {
|
|
24343
|
+
if (key === "loc" || key === "metadata" || key === "css") continue;
|
|
24344
|
+
const value = node[key];
|
|
24345
|
+
for (const child of Array.isArray(value) ? value : [value]) if (child && typeof child === "object" && typeof child.type === "string") visit(child);
|
|
24346
|
+
}
|
|
24347
|
+
};
|
|
24348
|
+
visit(ast);
|
|
24349
|
+
return elements;
|
|
24350
|
+
}
|
|
24351
|
+
/**
|
|
24352
|
+
* A `<script>` symbol spanning the element from its tag name to its closing tag name (the
|
|
24353
|
+
* parts of it that map to the generated TSX), selected by the opening tag's name, with the
|
|
24354
|
+
* top-level declarations of its body as children. The transform appends each body to the
|
|
24355
|
+
* generated TSX as a bare block, which TypeScript's navigation tree skips, so the body is
|
|
24356
|
+
* parsed here, where it stands in the source: the rest of the file is blanked, which keeps
|
|
24357
|
+
* every offset a source offset.
|
|
24358
|
+
* @param {ScriptElement} element
|
|
24359
|
+
* @param {{ start: number, content: string }} region
|
|
24360
|
+
* @param {TextDocument} document
|
|
24361
|
+
* @returns {SymbolInfo}
|
|
24362
|
+
*/
|
|
24363
|
+
function createScriptSymbol(element, region, document) {
|
|
24364
|
+
/** @type {AST.Node[]} */
|
|
24365
|
+
let statements = [];
|
|
24366
|
+
try {
|
|
24367
|
+
const blanked = document.getText().slice(0, region.start).replace(/[^\r\n]/g, " ") + region.content;
|
|
24368
|
+
statements = (0, _tsrx_core.parseModule)(blanked, document.uri, { loose: true }).body;
|
|
24369
|
+
} catch (error) {
|
|
24370
|
+
logError$3(`Unable to read a <script> body: ${/** @type {Error} */ error.message}`);
|
|
24371
|
+
}
|
|
24372
|
+
const name = element.openingElement.name;
|
|
24373
|
+
const range = {
|
|
24374
|
+
type: "JSXElement",
|
|
24375
|
+
start: name.start,
|
|
24376
|
+
end: element.closingElement?.name.end ?? region.start + region.content.length
|
|
24377
|
+
};
|
|
24378
|
+
return createNamedNodeSymbol("<script>", import_language_server.SymbolKind.Module, range, name, document, collectSymbolsFromStatements(statements, document));
|
|
24104
24379
|
}
|
|
24105
24380
|
/**
|
|
24106
24381
|
* @param {AST.Node[]} statements
|
|
@@ -24158,6 +24433,9 @@ function createSymbolForDeclaration(node, document, fallbackName) {
|
|
|
24158
24433
|
case "TSTypeAliasDeclaration":
|
|
24159
24434
|
if (!id || !name) return [];
|
|
24160
24435
|
return [createNamedNodeSymbol(name, import_language_server.SymbolKind.TypeParameter, node, id, document)];
|
|
24436
|
+
case "TSEnumDeclaration":
|
|
24437
|
+
if (!id || !name) return [];
|
|
24438
|
+
return [createNamedNodeSymbol(name, import_language_server.SymbolKind.Enum, node, id, document)];
|
|
24161
24439
|
default: return [];
|
|
24162
24440
|
}
|
|
24163
24441
|
}
|
|
@@ -24554,6 +24832,74 @@ function createTypeScriptDiagnosticFilterPlugin() {
|
|
|
24554
24832
|
};
|
|
24555
24833
|
}
|
|
24556
24834
|
|
|
24835
|
+
//#endregion
|
|
24836
|
+
//#region ../typescript-plugin/src/module-format.js
|
|
24837
|
+
/**
|
|
24838
|
+
* The module format (`impliedNodeFormat`) of `.tsrx` files. TypeScript derives a
|
|
24839
|
+
* file's format from its extension, and knows none for `.tsrx`, so under
|
|
24840
|
+
* `node16`/`nodenext` it treats every `.tsrx` file as CommonJS: `import.meta`
|
|
24841
|
+
* reports TS1470 even in a `"type": "module"` package. Volar's
|
|
24842
|
+
* `fixupImpliedNodeFormatForFile` sets the format only while it resolves the
|
|
24843
|
+
* file's imports, and resets it afterwards.
|
|
24844
|
+
*
|
|
24845
|
+
* A `.tsrx` file takes the format a `.ts` file at the same path would have:
|
|
24846
|
+
* from the `type` of the nearest `package.json` under `node16`/`nodenext` (or in
|
|
24847
|
+
* `node_modules`), and none otherwise. TSRX has no `.mtsrx`/`.ctsrx`
|
|
24848
|
+
* counterparts of `.mts`/`.cts`. The format goes into the options TypeScript
|
|
24849
|
+
* creates the source file with, so the source file's external-module status, the
|
|
24850
|
+
* document registry's key and the `package.json` TypeScript watches all match it.
|
|
24851
|
+
*/
|
|
24852
|
+
/**
|
|
24853
|
+
* Fill in the module format of a `.tsrx` file in the options TypeScript is about
|
|
24854
|
+
* to create its source file with, as TypeScript fills it in for a `.ts` file.
|
|
24855
|
+
* Options that already carry a format, and other files, are left alone.
|
|
24856
|
+
* @param {typeof import('typescript')} ts
|
|
24857
|
+
* @param {string} file_name
|
|
24858
|
+
* @param {unknown} source_file_options The `languageVersionOrOptions` of `getSourceFile`.
|
|
24859
|
+
* @param {import('typescript').PackageJsonInfoCache | undefined} package_json_info_cache
|
|
24860
|
+
* @param {import('typescript').ModuleResolutionHost} host
|
|
24861
|
+
* @param {import('typescript').CompilerOptions} compiler_options
|
|
24862
|
+
*/
|
|
24863
|
+
function fill_tsrx_module_format(ts, file_name, source_file_options, package_json_info_cache, host, compiler_options) {
|
|
24864
|
+
if (typeof source_file_options !== "object" || source_file_options === null || source_file_options.impliedNodeFormat !== void 0 || !is_tsrx_file(file_name)) return;
|
|
24865
|
+
const worker = ts.getImpliedNodeFormatForFileWorker;
|
|
24866
|
+
const format = worker ? worker(`${file_name}.ts`, package_json_info_cache, host, compiler_options) : ts.getImpliedNodeFormatForFile?.(`${file_name}.ts`, package_json_info_cache, host, compiler_options);
|
|
24867
|
+
if (typeof format === "object" && format !== null) Object.assign(source_file_options, format);
|
|
24868
|
+
else if (format !== void 0)
|
|
24869
|
+
/** @type {import('typescript').CreateSourceFileOptions} */ source_file_options.impliedNodeFormat = format;
|
|
24870
|
+
}
|
|
24871
|
+
/** @type {WeakSet<object>} */
|
|
24872
|
+
const patched = /* @__PURE__ */ new WeakSet();
|
|
24873
|
+
/**
|
|
24874
|
+
* Language services (tsserver, the language server): fill in the module format
|
|
24875
|
+
* of each `.tsrx` document the registry creates or updates. The language
|
|
24876
|
+
* service passes the options the program computed, and the registry keys its
|
|
24877
|
+
* entries by their format, so it has to be set before the registry sees them.
|
|
24878
|
+
* @param {typeof import('typescript')} ts
|
|
24879
|
+
* @param {import('typescript').DocumentRegistry} registry
|
|
24880
|
+
* @returns {import('typescript').DocumentRegistry}
|
|
24881
|
+
*/
|
|
24882
|
+
function with_tsrx_module_format_in_registry(ts, registry) {
|
|
24883
|
+
if (patched.has(registry)) return registry;
|
|
24884
|
+
patched.add(registry);
|
|
24885
|
+
for (const method of ["acquireDocumentWithKey", "updateDocumentWithKey"]) {
|
|
24886
|
+
const original = registry[method];
|
|
24887
|
+
/** @type {any} */ registry[method] = (file_name, path, host, key, snapshot, version, script_kind, source_file_options) => {
|
|
24888
|
+
fill_tsrx_module_format(
|
|
24889
|
+
ts,
|
|
24890
|
+
file_name,
|
|
24891
|
+
source_file_options,
|
|
24892
|
+
/** @type {any} */
|
|
24893
|
+
host.getModuleResolutionCache?.()?.getPackageJsonInfoCache(),
|
|
24894
|
+
host,
|
|
24895
|
+
host.getCompilationSettings()
|
|
24896
|
+
);
|
|
24897
|
+
return original.call(registry, file_name, path, host, key, snapshot, version, script_kind, source_file_options);
|
|
24898
|
+
};
|
|
24899
|
+
}
|
|
24900
|
+
return registry;
|
|
24901
|
+
}
|
|
24902
|
+
|
|
24557
24903
|
//#endregion
|
|
24558
24904
|
//#region src/typescriptService.js
|
|
24559
24905
|
/**
|
|
@@ -24595,7 +24941,19 @@ function load_typescript_service() {
|
|
|
24595
24941
|
* @returns {ReturnType<typeof import('volar-service-typescript').create>}
|
|
24596
24942
|
*/
|
|
24597
24943
|
function createTypeScriptServices(ts) {
|
|
24598
|
-
return load_typescript_service().create(ts);
|
|
24944
|
+
return load_typescript_service().create(with_tsrx_document_registries(ts));
|
|
24945
|
+
}
|
|
24946
|
+
/**
|
|
24947
|
+
* `ts` for `volar-service-typescript`, whose language services get each `.tsrx`
|
|
24948
|
+
* document's module format from their document registry
|
|
24949
|
+
* (`with_tsrx_module_format_in_registry`). The service creates the registries
|
|
24950
|
+
* itself, and the module's exports are read-only getters, so the override sits
|
|
24951
|
+
* on an object that inherits everything else from `ts`.
|
|
24952
|
+
* @param {typeof import('typescript')} ts
|
|
24953
|
+
* @returns {typeof import('typescript')}
|
|
24954
|
+
*/
|
|
24955
|
+
function with_tsrx_document_registries(ts) {
|
|
24956
|
+
return Object.create(ts, { createDocumentRegistry: { value: (...args) => with_tsrx_module_format_in_registry(ts, ts.createDocumentRegistry(...args)) } });
|
|
24599
24957
|
}
|
|
24600
24958
|
|
|
24601
24959
|
//#endregion
|
|
@@ -24633,6 +24991,26 @@ function stripFormatting(plugin) {
|
|
|
24633
24991
|
};
|
|
24634
24992
|
}
|
|
24635
24993
|
/**
|
|
24994
|
+
* Strip the folding capability from a Volar service plugin.
|
|
24995
|
+
*
|
|
24996
|
+
* Volar runs service plugins on the generated TS and CSS, and keeps the folds whose ends
|
|
24997
|
+
* map back to the `.tsrx` source: the CSS service's folds in `<style>` blocks do, but none
|
|
24998
|
+
* of TypeScript's. The server folds `.tsrx` sources itself (`foldingRangeHandler.js`) and
|
|
24999
|
+
* adds the folds Volar maps back: a plugin that offered folding ranges would make Volar
|
|
25000
|
+
* register its own `textDocument/foldingRange` handler, which would replace that one.
|
|
25001
|
+
*
|
|
25002
|
+
* @template {{ capabilities?: Record<string, unknown> }} T
|
|
25003
|
+
* @param {T} plugin
|
|
25004
|
+
* @returns {T}
|
|
25005
|
+
*/
|
|
25006
|
+
function stripFoldingRanges(plugin) {
|
|
25007
|
+
const { foldingRangeProvider: _folding, ...capabilities } = plugin.capabilities ?? {};
|
|
25008
|
+
return {
|
|
25009
|
+
...plugin,
|
|
25010
|
+
capabilities
|
|
25011
|
+
};
|
|
25012
|
+
}
|
|
25013
|
+
/**
|
|
24636
25014
|
* The Volar service plugins for a backend, in registration order.
|
|
24637
25015
|
*
|
|
24638
25016
|
* Classic: the TypeScript services run in this process and the TSRX
|
|
@@ -24658,7 +25036,7 @@ function createServicePlugins(backend, ts) {
|
|
|
24658
25036
|
const shared_last = [
|
|
24659
25037
|
createDefinitionPlugin(),
|
|
24660
25038
|
createDocumentSymbolPlugin(),
|
|
24661
|
-
stripFormatting((0, volar_service_css.create)())
|
|
25039
|
+
stripFoldingRanges(stripFormatting((0, volar_service_css.create)()))
|
|
24662
25040
|
];
|
|
24663
25041
|
if (backend === "native" || backend === "plugin") return [
|
|
24664
25042
|
...shared_first,
|
|
@@ -24672,7 +25050,7 @@ function createServicePlugins(backend, ts) {
|
|
|
24672
25050
|
...shared_first,
|
|
24673
25051
|
createCompileErrorDiagnosticPlugin(),
|
|
24674
25052
|
...shared_last,
|
|
24675
|
-
...createTypeScriptServices(ts).map(stripFormatting),
|
|
25053
|
+
...createTypeScriptServices(ts).map((plugin) => stripFoldingRanges(stripFormatting(plugin))),
|
|
24676
25054
|
createTypeScriptDiagnosticFilterPlugin(),
|
|
24677
25055
|
createHoverPlugin({ typescriptBackend: backend }),
|
|
24678
25056
|
createDocumentHighlightPlugin({ typescriptBackend: backend })
|
|
@@ -25036,8 +25414,429 @@ async function closing_tags_enabled(connection, uri) {
|
|
|
25036
25414
|
}
|
|
25037
25415
|
}
|
|
25038
25416
|
|
|
25417
|
+
//#endregion
|
|
25418
|
+
//#region src/foldingRangeHandler.js
|
|
25419
|
+
/** @import * as AST from 'estree' */
|
|
25420
|
+
/** @import { Connection, FoldingRange, LanguageServer } from '@volar/language-server' */
|
|
25421
|
+
/**
|
|
25422
|
+
* A fold that ends on one of these keeps the line holding it visible: the closing `}`,
|
|
25423
|
+
* `</div>`, `)` or `` ` ``, as VS Code's TypeScript folds TSX.
|
|
25424
|
+
*/
|
|
25425
|
+
const CLOSING_CHARACTERS = /* @__PURE__ */ new Set([
|
|
25426
|
+
"}",
|
|
25427
|
+
"]",
|
|
25428
|
+
")",
|
|
25429
|
+
"`",
|
|
25430
|
+
">"
|
|
25431
|
+
]);
|
|
25432
|
+
/** TypeScript's region markers: `// #region name` and `// #endregion`. */
|
|
25433
|
+
const REGION_MARKER = /^#(end)?region/;
|
|
25434
|
+
/** Keys that hold no child nodes, or nodes whose offsets are not source offsets. */
|
|
25435
|
+
const SKIPPED_KEYS = /* @__PURE__ */ new Set([
|
|
25436
|
+
"loc",
|
|
25437
|
+
"metadata",
|
|
25438
|
+
"css",
|
|
25439
|
+
"leadingComments",
|
|
25440
|
+
"trailingComments",
|
|
25441
|
+
"innerComments"
|
|
25442
|
+
]);
|
|
25443
|
+
/** Statements whose body block folds from the end of the line that opens it. */
|
|
25444
|
+
const ATTACHED_BLOCK_PARENTS = /* @__PURE__ */ new Set([
|
|
25445
|
+
"IfStatement",
|
|
25446
|
+
"ForStatement",
|
|
25447
|
+
"ForInStatement",
|
|
25448
|
+
"ForOfStatement",
|
|
25449
|
+
"WhileStatement",
|
|
25450
|
+
"DoWhileStatement",
|
|
25451
|
+
"WithStatement",
|
|
25452
|
+
"TryStatement",
|
|
25453
|
+
"CatchClause",
|
|
25454
|
+
"SwitchCase",
|
|
25455
|
+
"JSXIfExpression",
|
|
25456
|
+
"JSXForExpression",
|
|
25457
|
+
"JSXTryExpression"
|
|
25458
|
+
]);
|
|
25459
|
+
const FUNCTION_TYPES = /* @__PURE__ */ new Set([
|
|
25460
|
+
"FunctionDeclaration",
|
|
25461
|
+
"FunctionExpression",
|
|
25462
|
+
"ArrowFunctionExpression"
|
|
25463
|
+
]);
|
|
25464
|
+
/**
|
|
25465
|
+
* Answer `textDocument/foldingRange` for `.tsrx` files with folds computed from the TSRX
|
|
25466
|
+
* source, merged with the folds Volar's service plugins map back from embedded code (the CSS
|
|
25467
|
+
* of `<style>` blocks). Volar's own handler would only return the mapped ones: TypeScript's
|
|
25468
|
+
* folds on the generated code do not map back, and neither VS Code's TypeScript (whose
|
|
25469
|
+
* tsserver plugin answers no outlining spans for `.tsrx` files) nor TypeScript 7 folds
|
|
25470
|
+
* `.tsrx` files. No Volar service plugin offers folding ranges (`stripFoldingRanges` in
|
|
25471
|
+
* `servicePlugins.js`), so Volar registers no handler that would replace this one.
|
|
25472
|
+
* @param {Connection} connection
|
|
25473
|
+
* @param {LanguageServer} server
|
|
25474
|
+
*/
|
|
25475
|
+
function register_folding_ranges(connection, server) {
|
|
25476
|
+
connection.onFoldingRanges(async (params, token) => {
|
|
25477
|
+
const uri = vscode_uri.URI.parse(params.textDocument.uri);
|
|
25478
|
+
const embedded = await (await server.project.getLanguageService(uri)).getFoldingRanges(uri, token) ?? [];
|
|
25479
|
+
if (token.isCancellationRequested) return null;
|
|
25480
|
+
const document = server.documents.get(uri);
|
|
25481
|
+
if (!document || !is_tsrx_document(params.textDocument.uri)) return embedded;
|
|
25482
|
+
return merge_folding_ranges([...collect_folding_ranges(document.getText(), uri.fsPath), ...embedded]);
|
|
25483
|
+
});
|
|
25484
|
+
}
|
|
25485
|
+
/**
|
|
25486
|
+
* The folds of a `.tsrx` source, following the folds TypeScript gives TSX: functions and
|
|
25487
|
+
* other blocks, `@{ ... }` bodies, each directive body and clause (`@else`, `@empty`,
|
|
25488
|
+
* `@case`, `@catch`, `@pending`), multi-line elements and `<style>` blocks, objects, arrays,
|
|
25489
|
+
* multi-line calls, template strings, groups of imports, comments and `// #region` markers.
|
|
25490
|
+
* While the source does not parse, folds follow indentation and region markers.
|
|
25491
|
+
* @param {string} text
|
|
25492
|
+
* @param {string} file_name
|
|
25493
|
+
* @returns {FoldingRange[]}
|
|
25494
|
+
*/
|
|
25495
|
+
function collect_folding_ranges(text, file_name) {
|
|
25496
|
+
const line_starts = [0];
|
|
25497
|
+
for (const match of text.matchAll(/\r\n|\r|\n/g)) line_starts.push(
|
|
25498
|
+
/** @type {number} */
|
|
25499
|
+
match.index + match[0].length
|
|
25500
|
+
);
|
|
25501
|
+
/** @param {number} offset */
|
|
25502
|
+
const line_of = (offset) => {
|
|
25503
|
+
let low = 0;
|
|
25504
|
+
let high = line_starts.length - 1;
|
|
25505
|
+
while (low < high) {
|
|
25506
|
+
const middle = low + high + 1 >> 1;
|
|
25507
|
+
if (line_starts[middle] <= offset) low = middle;
|
|
25508
|
+
else high = middle - 1;
|
|
25509
|
+
}
|
|
25510
|
+
return low;
|
|
25511
|
+
};
|
|
25512
|
+
/**
|
|
25513
|
+
* The start of each comment, by the offset where it ends, and its end by its start.
|
|
25514
|
+
* @type {Map<number, number>}
|
|
25515
|
+
*/
|
|
25516
|
+
const comment_starts = /* @__PURE__ */ new Map();
|
|
25517
|
+
/** @type {Map<number, number>} */
|
|
25518
|
+
const comment_ends = /* @__PURE__ */ new Map();
|
|
25519
|
+
/**
|
|
25520
|
+
* The offset of the first `character` from `offset` on, outside comments, or -1.
|
|
25521
|
+
* @param {string} character
|
|
25522
|
+
* @param {number} offset
|
|
25523
|
+
*/
|
|
25524
|
+
const find_after = (character, offset) => {
|
|
25525
|
+
let index = offset;
|
|
25526
|
+
while (index < text.length) {
|
|
25527
|
+
const comment_end = comment_ends.get(index);
|
|
25528
|
+
if (comment_end !== void 0) index = comment_end;
|
|
25529
|
+
else if (text[index] === character) return index;
|
|
25530
|
+
else index++;
|
|
25531
|
+
}
|
|
25532
|
+
return -1;
|
|
25533
|
+
};
|
|
25534
|
+
/**
|
|
25535
|
+
* The line of the token before `offset`, past blanks and comments, where a block opened on
|
|
25536
|
+
* a line of its own still folds from the line that opens it.
|
|
25537
|
+
* @param {number} offset
|
|
25538
|
+
*/
|
|
25539
|
+
const previous_token_line = (offset) => {
|
|
25540
|
+
let index = offset - 1;
|
|
25541
|
+
while (index > 0) {
|
|
25542
|
+
const comment_start = comment_starts.get(index + 1);
|
|
25543
|
+
if (comment_start !== void 0) index = comment_start - 1;
|
|
25544
|
+
else if (/\s/.test(text[index])) index--;
|
|
25545
|
+
else break;
|
|
25546
|
+
}
|
|
25547
|
+
return line_of(Math.max(index, 0));
|
|
25548
|
+
};
|
|
25549
|
+
/** @type {FoldingRange[]} */
|
|
25550
|
+
const ranges = [];
|
|
25551
|
+
/**
|
|
25552
|
+
* @param {number} start_line
|
|
25553
|
+
* @param {number} end Offset after the last folded character.
|
|
25554
|
+
* @param {FoldingRange['kind']} [kind] Comment and region folds end where their text ends.
|
|
25555
|
+
*/
|
|
25556
|
+
const fold = (start_line, end, kind) => {
|
|
25557
|
+
let end_line = line_of(end - 1);
|
|
25558
|
+
if (!kind && CLOSING_CHARACTERS.has(text[end - 1])) end_line--;
|
|
25559
|
+
if (end_line > start_line) ranges.push(kind ? {
|
|
25560
|
+
startLine: start_line,
|
|
25561
|
+
endLine: end_line,
|
|
25562
|
+
kind
|
|
25563
|
+
} : {
|
|
25564
|
+
startLine: start_line,
|
|
25565
|
+
endLine: end_line
|
|
25566
|
+
});
|
|
25567
|
+
};
|
|
25568
|
+
/** @type {AST.CommentWithLocation[]} */
|
|
25569
|
+
const comments = [];
|
|
25570
|
+
/** @type {AST.Program} */
|
|
25571
|
+
let ast;
|
|
25572
|
+
try {
|
|
25573
|
+
ast = (0, _tsrx_core.parseModule)(text, file_name, {
|
|
25574
|
+
loose: true,
|
|
25575
|
+
preserveParens: true,
|
|
25576
|
+
comments
|
|
25577
|
+
});
|
|
25578
|
+
} catch {
|
|
25579
|
+
return merge_folding_ranges(fallback_folding_ranges(text));
|
|
25580
|
+
}
|
|
25581
|
+
for (const comment of comments) {
|
|
25582
|
+
comment_starts.set(comment.end, comment.start);
|
|
25583
|
+
comment_ends.set(comment.start, comment.end);
|
|
25584
|
+
}
|
|
25585
|
+
/**
|
|
25586
|
+
* @param {any} node
|
|
25587
|
+
* @param {any} parent
|
|
25588
|
+
*/
|
|
25589
|
+
const visit = (node, parent) => {
|
|
25590
|
+
switch (node.type) {
|
|
25591
|
+
case "Program":
|
|
25592
|
+
fold_import_groups(node.body);
|
|
25593
|
+
break;
|
|
25594
|
+
case "BlockStatement":
|
|
25595
|
+
case "JSXCodeBlock":
|
|
25596
|
+
if (FUNCTION_TYPES.has(parent?.type) && parent.body === node) fold(function_start_line(parent), node.end);
|
|
25597
|
+
else if (ATTACHED_BLOCK_PARENTS.has(parent?.type)) fold(previous_token_line(node.start), node.end);
|
|
25598
|
+
else fold(line_of(node.start), node.end);
|
|
25599
|
+
break;
|
|
25600
|
+
case "ClassBody":
|
|
25601
|
+
case "TSInterfaceBody":
|
|
25602
|
+
case "TSEnumBody":
|
|
25603
|
+
case "TSModuleBlock":
|
|
25604
|
+
fold(previous_token_line(node.start), node.end);
|
|
25605
|
+
break;
|
|
25606
|
+
case "SwitchStatement":
|
|
25607
|
+
case "JSXSwitchExpression":
|
|
25608
|
+
fold(previous_token_line(find_after("{", node.discriminant.end)), node.end);
|
|
25609
|
+
break;
|
|
25610
|
+
case "StaticBlock":
|
|
25611
|
+
fold(line_of(find_after("{", node.start)), node.end);
|
|
25612
|
+
break;
|
|
25613
|
+
case "SwitchCase":
|
|
25614
|
+
if (Array.isArray(node.consequent) && node.consequent.length > 0) fold(line_of(node.test?.end ?? node.start), node.consequent.at(-1).end);
|
|
25615
|
+
break;
|
|
25616
|
+
case "ObjectExpression":
|
|
25617
|
+
case "ArrayExpression":
|
|
25618
|
+
case "ObjectPattern":
|
|
25619
|
+
case "ArrayPattern":
|
|
25620
|
+
case "TSTypeLiteral":
|
|
25621
|
+
case "TSTupleType":
|
|
25622
|
+
fold(parent?.type === "ArrayExpression" || parent?.type === "CallExpression" ? line_of(node.start) : previous_token_line(node.start), node.end);
|
|
25623
|
+
break;
|
|
25624
|
+
case "CallExpression":
|
|
25625
|
+
if (node.arguments.length > 0) fold(previous_token_line(find_after("(", node.typeArguments?.end ?? node.callee.end)), node.end);
|
|
25626
|
+
break;
|
|
25627
|
+
case "ArrowFunctionExpression":
|
|
25628
|
+
if (node.body.type !== "BlockStatement" && node.body.type !== "JSXCodeBlock" && node.body.type !== "ParenthesizedExpression") fold(previous_token_line(node.body.start), node.body.end);
|
|
25629
|
+
break;
|
|
25630
|
+
case "ImportDeclaration":
|
|
25631
|
+
case "ExportNamedDeclaration":
|
|
25632
|
+
case "ExportAllDeclaration":
|
|
25633
|
+
fold_braces((node.specifiers ?? []).filter((specifier) => specifier.type === "ImportSpecifier" || specifier.type === "ExportSpecifier"));
|
|
25634
|
+
fold_braces(node.attributes ?? []);
|
|
25635
|
+
break;
|
|
25636
|
+
case "JSXOpeningElement":
|
|
25637
|
+
if (node.attributes.length > 0) fold(line_of(node.attributes[0].start), node.attributes.at(-1).end);
|
|
25638
|
+
break;
|
|
25639
|
+
case "JSXElement":
|
|
25640
|
+
case "JSXStyleElement":
|
|
25641
|
+
if (node.closingElement) fold(line_of(node.start), node.end);
|
|
25642
|
+
break;
|
|
25643
|
+
case "TemplateLiteral":
|
|
25644
|
+
case "ParenthesizedExpression":
|
|
25645
|
+
case "JSXFragment": fold(line_of(node.start), node.end);
|
|
25646
|
+
}
|
|
25647
|
+
for (const key in node) {
|
|
25648
|
+
if (SKIPPED_KEYS.has(key)) continue;
|
|
25649
|
+
const value = node[key];
|
|
25650
|
+
if (Array.isArray(value)) {
|
|
25651
|
+
for (const child of value) if (is_node(child)) visit(child, node);
|
|
25652
|
+
} else if (is_node(value)) visit(value, node);
|
|
25653
|
+
}
|
|
25654
|
+
};
|
|
25655
|
+
/**
|
|
25656
|
+
* A function folds from its `(` when its parameters span lines, else from its body's `{`.
|
|
25657
|
+
* @param {any} node
|
|
25658
|
+
*/
|
|
25659
|
+
const function_start_line = (node) => {
|
|
25660
|
+
if (node.params.length > 0) {
|
|
25661
|
+
const open = previous_token_line(node.params[0].start);
|
|
25662
|
+
if (open !== line_of(node.params.at(-1).end)) return open;
|
|
25663
|
+
}
|
|
25664
|
+
return previous_token_line(node.body.start);
|
|
25665
|
+
};
|
|
25666
|
+
/**
|
|
25667
|
+
* Two or more imports in a row fold together.
|
|
25668
|
+
* @param {AST.Node[]} statements
|
|
25669
|
+
*/
|
|
25670
|
+
const fold_import_groups = (statements) => {
|
|
25671
|
+
let first = 0;
|
|
25672
|
+
while (first < statements.length) {
|
|
25673
|
+
let last = first;
|
|
25674
|
+
while (last < statements.length && is_import(statements[last])) last++;
|
|
25675
|
+
if (last - first > 1) fold(
|
|
25676
|
+
line_of(
|
|
25677
|
+
/** @type {any} */
|
|
25678
|
+
statements[first].start
|
|
25679
|
+
),
|
|
25680
|
+
/** @type {any} */
|
|
25681
|
+
statements[last - 1].end,
|
|
25682
|
+
"imports"
|
|
25683
|
+
);
|
|
25684
|
+
first = last + 1;
|
|
25685
|
+
}
|
|
25686
|
+
};
|
|
25687
|
+
/**
|
|
25688
|
+
* The braces around `elements`: the names of `import { a, b } from` and `export { a, b }`,
|
|
25689
|
+
* and import attributes (`with { type: 'json' }`).
|
|
25690
|
+
* @param {any[]} elements
|
|
25691
|
+
*/
|
|
25692
|
+
const fold_braces = (elements) => {
|
|
25693
|
+
if (elements.length === 0) return;
|
|
25694
|
+
const close = find_after("}", elements.at(-1).end);
|
|
25695
|
+
if (close !== -1) fold(previous_token_line(elements[0].start), close + 1);
|
|
25696
|
+
};
|
|
25697
|
+
visit(ast, null);
|
|
25698
|
+
fold_comments(comments, text, line_of, (offset) => /^[ \t]*$/.test(text.slice(line_starts[line_of(offset)], offset)), fold);
|
|
25699
|
+
return merge_folding_ranges(ranges);
|
|
25700
|
+
}
|
|
25701
|
+
/**
|
|
25702
|
+
* Multi-line block comments, runs of two or more line comments each on a line of its own,
|
|
25703
|
+
* and `// #region` ... `// #endregion` pairs.
|
|
25704
|
+
* @param {AST.CommentWithLocation[]} comments
|
|
25705
|
+
* @param {string} text
|
|
25706
|
+
* @param {(offset: number) => number} line_of
|
|
25707
|
+
* @param {(offset: number) => boolean} first_on_line Whether only blanks precede `offset` on
|
|
25708
|
+
* its line.
|
|
25709
|
+
* @param {(start_line: number, end: number, kind: FoldingRange['kind']) => void} fold
|
|
25710
|
+
*/
|
|
25711
|
+
function fold_comments(comments, text, line_of, first_on_line, fold) {
|
|
25712
|
+
/** @type {number[]} */
|
|
25713
|
+
const regions = [];
|
|
25714
|
+
/** @type {AST.CommentWithLocation | null} */
|
|
25715
|
+
let first = null;
|
|
25716
|
+
/** @type {AST.CommentWithLocation | null} */
|
|
25717
|
+
let last = null;
|
|
25718
|
+
const end_run = () => {
|
|
25719
|
+
if (first && last && first !== last) fold(line_of(first.start), last.end, "comment");
|
|
25720
|
+
first = last = null;
|
|
25721
|
+
};
|
|
25722
|
+
for (const comment of comments) {
|
|
25723
|
+
const own_line = comment.type === "Line" && first_on_line(comment.start);
|
|
25724
|
+
const region = own_line ? REGION_MARKER.exec(comment.value.trim()) : null;
|
|
25725
|
+
if (region || !own_line || last && /\S/.test(text.slice(last.end, comment.start))) end_run();
|
|
25726
|
+
if (region) {
|
|
25727
|
+
if (!region[1]) regions.push(line_of(comment.start));
|
|
25728
|
+
else if (regions.length > 0) fold(regions.pop(), comment.end, "region");
|
|
25729
|
+
} else if (own_line) {
|
|
25730
|
+
first ??= comment;
|
|
25731
|
+
last = comment;
|
|
25732
|
+
} else if (comment.type === "Block") fold(line_of(comment.start), comment.end, "comment");
|
|
25733
|
+
}
|
|
25734
|
+
end_run();
|
|
25735
|
+
}
|
|
25736
|
+
/**
|
|
25737
|
+
* Folds by indentation, the way VS Code folds a file no provider folds, plus region markers.
|
|
25738
|
+
* @param {string} text
|
|
25739
|
+
* @returns {FoldingRange[]}
|
|
25740
|
+
*/
|
|
25741
|
+
function fallback_folding_ranges(text) {
|
|
25742
|
+
const lines = text.split(/\r\n|\r|\n/);
|
|
25743
|
+
/** @type {FoldingRange[]} */
|
|
25744
|
+
const ranges = [];
|
|
25745
|
+
/** @type {Array<{ indent: number, end_above: number }>} */
|
|
25746
|
+
const open = [{
|
|
25747
|
+
indent: -1,
|
|
25748
|
+
end_above: lines.length
|
|
25749
|
+
}];
|
|
25750
|
+
for (let line = lines.length - 1; line >= 0; line--) {
|
|
25751
|
+
const indent = indent_of(lines[line]);
|
|
25752
|
+
if (indent === -1) continue;
|
|
25753
|
+
let previous = open[open.length - 1];
|
|
25754
|
+
if (previous.indent > indent) {
|
|
25755
|
+
do {
|
|
25756
|
+
open.pop();
|
|
25757
|
+
previous = open[open.length - 1];
|
|
25758
|
+
} while (previous.indent > indent);
|
|
25759
|
+
if (previous.end_above - 1 > line) ranges.push({
|
|
25760
|
+
startLine: line,
|
|
25761
|
+
endLine: previous.end_above - 1
|
|
25762
|
+
});
|
|
25763
|
+
}
|
|
25764
|
+
if (previous.indent === indent) previous.end_above = line;
|
|
25765
|
+
else open.push({
|
|
25766
|
+
indent,
|
|
25767
|
+
end_above: line
|
|
25768
|
+
});
|
|
25769
|
+
}
|
|
25770
|
+
/** @type {number[]} */
|
|
25771
|
+
const regions = [];
|
|
25772
|
+
for (const [line, content] of lines.entries()) {
|
|
25773
|
+
const region = /^\s*\/\/(.*)$/.exec(content);
|
|
25774
|
+
const marker = region && REGION_MARKER.exec(region[1].trim());
|
|
25775
|
+
if (!marker) continue;
|
|
25776
|
+
if (!marker[1]) regions.push(line);
|
|
25777
|
+
else if (regions.length > 0) {
|
|
25778
|
+
const start = regions.pop();
|
|
25779
|
+
if (line > start) ranges.push({
|
|
25780
|
+
startLine: start,
|
|
25781
|
+
endLine: line,
|
|
25782
|
+
kind: "region"
|
|
25783
|
+
});
|
|
25784
|
+
}
|
|
25785
|
+
}
|
|
25786
|
+
return ranges;
|
|
25787
|
+
}
|
|
25788
|
+
/**
|
|
25789
|
+
* The width of a line's indentation, tabs counting to the next multiple of 4, or -1 for a
|
|
25790
|
+
* blank line.
|
|
25791
|
+
* @param {string} line
|
|
25792
|
+
*/
|
|
25793
|
+
function indent_of(line) {
|
|
25794
|
+
let width = 0;
|
|
25795
|
+
for (const character of line) if (character === " ") width++;
|
|
25796
|
+
else if (character === " ") width += 4 - width % 4;
|
|
25797
|
+
else return width;
|
|
25798
|
+
return -1;
|
|
25799
|
+
}
|
|
25800
|
+
/**
|
|
25801
|
+
* Sorted by line, one fold per first line: the one that reaches furthest, which is the one an
|
|
25802
|
+
* editor that keeps a single fold per line keeps for TSX.
|
|
25803
|
+
* @param {FoldingRange[]} ranges
|
|
25804
|
+
* @returns {FoldingRange[]}
|
|
25805
|
+
*/
|
|
25806
|
+
function merge_folding_ranges(ranges) {
|
|
25807
|
+
const sorted = [...ranges].sort((a, b) => a.startLine - b.startLine || b.endLine - a.endLine);
|
|
25808
|
+
return sorted.filter((range, index) => index === 0 || sorted[index - 1].startLine !== range.startLine);
|
|
25809
|
+
}
|
|
25810
|
+
/**
|
|
25811
|
+
* @param {unknown} value
|
|
25812
|
+
* @returns {boolean}
|
|
25813
|
+
*/
|
|
25814
|
+
function is_node(value) {
|
|
25815
|
+
return !!value && typeof value === "object" && typeof value.type === "string" && typeof value.start === "number";
|
|
25816
|
+
}
|
|
25817
|
+
/**
|
|
25818
|
+
* @param {AST.Node} statement
|
|
25819
|
+
* @returns {boolean}
|
|
25820
|
+
*/
|
|
25821
|
+
function is_import(statement) {
|
|
25822
|
+
return statement.type === "ImportDeclaration" || statement.type === "TSImportEqualsDeclaration";
|
|
25823
|
+
}
|
|
25824
|
+
|
|
25039
25825
|
//#endregion
|
|
25040
25826
|
//#region src/workspaceState.js
|
|
25827
|
+
/** Configs and package state, which every backend reacts to (`classifyWorkspaceChanges`). */
|
|
25828
|
+
const CONFIG_AND_PACKAGE_STATE_PATTERNS = [
|
|
25829
|
+
"**/*.json",
|
|
25830
|
+
"**/pnpm-lock.yaml",
|
|
25831
|
+
"**/pnpm-workspace.yaml",
|
|
25832
|
+
"**/yarn.lock",
|
|
25833
|
+
"**/bun.lock",
|
|
25834
|
+
"**/bun.lockb",
|
|
25835
|
+
"**/node_modules/.modules.yaml",
|
|
25836
|
+
"**/node_modules/.package-lock.json",
|
|
25837
|
+
"**/node_modules/.yarn-state.yml",
|
|
25838
|
+
"**/node_modules/.yarn-integrity"
|
|
25839
|
+
];
|
|
25041
25840
|
const WORKSPACE_FILE_PATTERNS = [
|
|
25042
25841
|
"**/*.tsrx",
|
|
25043
25842
|
"**/*.ts",
|
|
@@ -25048,13 +25847,44 @@ const WORKSPACE_FILE_PATTERNS = [
|
|
|
25048
25847
|
"**/*.jsx",
|
|
25049
25848
|
"**/*.cjs",
|
|
25050
25849
|
"**/*.mjs",
|
|
25051
|
-
|
|
25052
|
-
"**/pnpm-lock.yaml",
|
|
25053
|
-
"**/pnpm-workspace.yaml",
|
|
25054
|
-
"**/yarn.lock",
|
|
25055
|
-
"**/bun.lock",
|
|
25056
|
-
"**/bun.lockb"
|
|
25850
|
+
...CONFIG_AND_PACKAGE_STATE_PATTERNS
|
|
25057
25851
|
];
|
|
25852
|
+
/**
|
|
25853
|
+
* The files to watch on a backend. Only the classic backend hosts a TypeScript
|
|
25854
|
+
* project, which needs the TypeScript and JavaScript source events. On the other
|
|
25855
|
+
* backends the editor's TypeScript reads those files, and watching them in a large
|
|
25856
|
+
* workspace only floods the server with events from build output and dev servers.
|
|
25857
|
+
* @param {import('./backend.js').TypeScriptBackend} backend
|
|
25858
|
+
* @returns {string[]}
|
|
25859
|
+
*/
|
|
25860
|
+
function getWorkspaceFilePatterns(backend) {
|
|
25861
|
+
return backend === "classic" ? WORKSPACE_FILE_PATTERNS : ["**/*.tsrx", ...CONFIG_AND_PACKAGE_STATE_PATTERNS];
|
|
25862
|
+
}
|
|
25863
|
+
/**
|
|
25864
|
+
* Directories that installs, dev servers and builds write, such as Vite's
|
|
25865
|
+
* `node_modules/.vite/deps/package.json` or Next.js's `.next/package.json`. No
|
|
25866
|
+
* project the TSRX compiler resolves from lives in one. Keep in sync with
|
|
25867
|
+
* `file-events.js` in the VS Code extension, which drops the same events.
|
|
25868
|
+
*/
|
|
25869
|
+
const GENERATED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
|
|
25870
|
+
"node_modules",
|
|
25871
|
+
".next",
|
|
25872
|
+
".nuxt",
|
|
25873
|
+
".output",
|
|
25874
|
+
".svelte-kit",
|
|
25875
|
+
".turbo",
|
|
25876
|
+
".vercel"
|
|
25877
|
+
]);
|
|
25878
|
+
/**
|
|
25879
|
+
* Files that pnpm, npm, Yarn (node-modules linker) and Yarn 1 write directly in
|
|
25880
|
+
* `node_modules` at the end of every install.
|
|
25881
|
+
*/
|
|
25882
|
+
const INSTALL_MARKER_FILE_NAMES = /* @__PURE__ */ new Set([
|
|
25883
|
+
".modules.yaml",
|
|
25884
|
+
".package-lock.json",
|
|
25885
|
+
".yarn-state.yml",
|
|
25886
|
+
".yarn-integrity"
|
|
25887
|
+
]);
|
|
25058
25888
|
const PACKAGE_STATE_FILE_NAMES = /* @__PURE__ */ new Set([
|
|
25059
25889
|
"package.json",
|
|
25060
25890
|
"package-lock.json",
|
|
@@ -25084,6 +25914,39 @@ function isPackageStateFile(file_name) {
|
|
|
25084
25914
|
return PACKAGE_STATE_FILE_NAMES.has(node_path.default.basename(file_name).toLowerCase());
|
|
25085
25915
|
}
|
|
25086
25916
|
/**
|
|
25917
|
+
* The path segments of a file, relative to the workspace folder that holds it, so a
|
|
25918
|
+
* workspace opened inside a `node_modules` folder keeps its own events.
|
|
25919
|
+
* @param {string} file_name
|
|
25920
|
+
* @param {readonly string[]} workspace_folders
|
|
25921
|
+
*/
|
|
25922
|
+
function workspaceRelativeSegments(file_name, workspace_folders) {
|
|
25923
|
+
const normalized = normalizeFileName(file_name);
|
|
25924
|
+
let relative = normalized;
|
|
25925
|
+
for (const folder of workspace_folders) {
|
|
25926
|
+
const normalized_folder = normalizeFileName(folder).replace(/[\\/]+$/, "");
|
|
25927
|
+
if (normalized.startsWith(normalized_folder) && /[\\/]/.test(normalized[normalized_folder.length] ?? "") && normalized.length - normalized_folder.length - 1 < relative.length) relative = normalized.slice(normalized_folder.length + 1);
|
|
25928
|
+
}
|
|
25929
|
+
return relative.split(/[\\/]/);
|
|
25930
|
+
}
|
|
25931
|
+
/**
|
|
25932
|
+
* Whether a file under `node_modules` shows that an install finished: an install
|
|
25933
|
+
* marker, or the manifest of a package installed directly in a `node_modules`
|
|
25934
|
+
* folder (`node_modules/<name>/package.json`, `node_modules/@scope/<name>/package.json`),
|
|
25935
|
+
* which npm and Bun write for each package they install. The lockfile is not enough:
|
|
25936
|
+
* `git pull` can change it before the install that changes the TSRX compiler. A
|
|
25937
|
+
* `node_modules` inside build output (`.output/server/node_modules`,
|
|
25938
|
+
* `.next/standalone/node_modules`) is a copy a build writes, not an install.
|
|
25939
|
+
* @param {readonly string[]} segments Path segments relative to the workspace folder.
|
|
25940
|
+
*/
|
|
25941
|
+
function isInstallStateFile(segments) {
|
|
25942
|
+
const index = segments.indexOf("node_modules");
|
|
25943
|
+
if (index === -1 || segments.includes("node_modules", index + 1) || segments.slice(0, index).some((segment) => GENERATED_DIRECTORY_NAMES.has(segment))) return false;
|
|
25944
|
+
const rest = segments.slice(index + 1);
|
|
25945
|
+
if (rest.length === 1) return INSTALL_MARKER_FILE_NAMES.has(rest[0]);
|
|
25946
|
+
const name = rest.slice(0, rest[0]?.startsWith("@") ? 2 : 1);
|
|
25947
|
+
return rest.length === name.length + 1 && rest[rest.length - 1] === "package.json" && name.every((segment) => !segment.startsWith("."));
|
|
25948
|
+
}
|
|
25949
|
+
/**
|
|
25087
25950
|
* @param {string} file_name
|
|
25088
25951
|
*/
|
|
25089
25952
|
function normalizeFileName(file_name) {
|
|
@@ -25116,11 +25979,16 @@ function trackTypeScriptConfigDependencies(config_files, project) {
|
|
|
25116
25979
|
/**
|
|
25117
25980
|
* Classify watched changes before mutating project state. Package changes need
|
|
25118
25981
|
* a process restart because Node does not expose a supported way to evict a
|
|
25119
|
-
* loaded ESM compiler and its transitive module graph.
|
|
25982
|
+
* loaded ESM compiler and its transitive module graph. A file in a generated
|
|
25983
|
+
* directory restarts the server only when it shows that an install finished
|
|
25984
|
+
* (`isInstallStateFile`), and reloads projects only when a project loaded it as a
|
|
25985
|
+
* config: dev servers rewrite such files all the time, and restarting on each one
|
|
25986
|
+
* kept a large workspace restarting the server.
|
|
25120
25987
|
* @param {import('@volar/language-server').FileEvent[]} changes
|
|
25121
25988
|
* @param {ReadonlySet<string>} [tracked_config_files]
|
|
25989
|
+
* @param {readonly string[]} [workspace_folders] File system paths of the workspace folders.
|
|
25122
25990
|
*/
|
|
25123
|
-
function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ */ new Set()) {
|
|
25991
|
+
function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ */ new Set(), workspace_folders = []) {
|
|
25124
25992
|
let reloadProjects = false;
|
|
25125
25993
|
let restartLanguageServer = false;
|
|
25126
25994
|
/** @type {Set<string>} */
|
|
@@ -25128,8 +25996,10 @@ function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ *
|
|
|
25128
25996
|
for (const change of changes) {
|
|
25129
25997
|
const uri = vscode_uri.URI.parse(change.uri);
|
|
25130
25998
|
const file_name = uri.scheme === "file" ? uri.fsPath : uri.path;
|
|
25131
|
-
|
|
25132
|
-
|
|
25999
|
+
const segments = workspaceRelativeSegments(file_name, workspace_folders);
|
|
26000
|
+
const generated = segments.some((segment) => GENERATED_DIRECTORY_NAMES.has(segment));
|
|
26001
|
+
if (!generated && isTypeScriptConfigFile(file_name) || tracked_config_files.has(normalizeFileName(file_name))) reloadProjects = true;
|
|
26002
|
+
if (generated ? isInstallStateFile(segments) : isPackageStateFile(file_name)) restartLanguageServer = true;
|
|
25133
26003
|
else if (isTypeDefinitionFile(file_name)) changedTypeDefinitions.add(file_name);
|
|
25134
26004
|
}
|
|
25135
26005
|
return {
|
|
@@ -25139,6 +26009,32 @@ function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ *
|
|
|
25139
26009
|
};
|
|
25140
26010
|
}
|
|
25141
26011
|
/**
|
|
26012
|
+
* Run `restart` once, after package changes have stopped for `delay` ms, so a burst
|
|
26013
|
+
* of them, such as an install, restarts the server once; or `max_delay` ms after
|
|
26014
|
+
* the first change at the latest, so a steady stream cannot hold it off.
|
|
26015
|
+
* @param {() => void} restart
|
|
26016
|
+
* @param {number} [delay]
|
|
26017
|
+
* @param {number} [max_delay]
|
|
26018
|
+
* @returns {() => void} Call on each change that needs a restart.
|
|
26019
|
+
*/
|
|
26020
|
+
function createRestartScheduler(restart, delay = 1e3, max_delay = 1e4) {
|
|
26021
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
26022
|
+
let timer;
|
|
26023
|
+
/** @type {number | undefined} */
|
|
26024
|
+
let first_change;
|
|
26025
|
+
let restarted = false;
|
|
26026
|
+
return () => {
|
|
26027
|
+
if (restarted) return;
|
|
26028
|
+
const now = Date.now();
|
|
26029
|
+
first_change ??= now;
|
|
26030
|
+
clearTimeout(timer);
|
|
26031
|
+
timer = setTimeout(() => {
|
|
26032
|
+
restarted = true;
|
|
26033
|
+
restart();
|
|
26034
|
+
}, Math.min(delay, first_change + max_delay - now));
|
|
26035
|
+
};
|
|
26036
|
+
}
|
|
26037
|
+
/**
|
|
25142
26038
|
* @param {import('@volar/language-server').FileEvent[]} changes
|
|
25143
26039
|
* @param {{
|
|
25144
26040
|
* restartLanguageServer: () => void,
|
|
@@ -25148,9 +26044,10 @@ function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ *
|
|
|
25148
26044
|
* invalidateTypeDefinitions: (file_name?: string) => void,
|
|
25149
26045
|
* }} hooks
|
|
25150
26046
|
* @param {ReadonlySet<string>} [tracked_config_files]
|
|
26047
|
+
* @param {readonly string[]} [workspace_folders]
|
|
25151
26048
|
*/
|
|
25152
|
-
function handleWorkspaceChanges(changes, hooks, tracked_config_files) {
|
|
25153
|
-
const effects = classifyWorkspaceChanges(changes, tracked_config_files);
|
|
26049
|
+
function handleWorkspaceChanges(changes, hooks, tracked_config_files, workspace_folders) {
|
|
26050
|
+
const effects = classifyWorkspaceChanges(changes, tracked_config_files, workspace_folders);
|
|
25154
26051
|
if (effects.restartLanguageServer) {
|
|
25155
26052
|
hooks.restartLanguageServer();
|
|
25156
26053
|
return effects;
|
|
@@ -25191,6 +26088,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25191
26088
|
const server = (0, import_node.createServer)(connection);
|
|
25192
26089
|
register_formatting(connection, (uri) => server.documents.get(vscode_uri.URI.parse(uri)));
|
|
25193
26090
|
register_closing_tags(connection, server);
|
|
26091
|
+
register_folding_ranges(connection, server);
|
|
25194
26092
|
connection.listen();
|
|
25195
26093
|
/** @type {WeakSet<Function>} */
|
|
25196
26094
|
const wrappedFunctions = /* @__PURE__ */ new WeakSet();
|
|
@@ -25198,8 +26096,9 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25198
26096
|
const trackedTypeScriptConfigFiles = /* @__PURE__ */ new Set();
|
|
25199
26097
|
/** @type {Set<Set<string>>} */
|
|
25200
26098
|
const compilerResolutionDependencySets = /* @__PURE__ */ new Set();
|
|
25201
|
-
let restartScheduled = false;
|
|
25202
26099
|
let clientRestarts = false;
|
|
26100
|
+
/** @type {import('./backend.js').TypeScriptBackend} */
|
|
26101
|
+
let activeBackend = "classic";
|
|
25203
26102
|
/**
|
|
25204
26103
|
* Shown once the client is initialized, each as its own warning: the classic
|
|
25205
26104
|
* backend skipped the `typescript.tsdk` option, or did not find a `typescript`
|
|
@@ -25208,14 +26107,13 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25208
26107
|
*/
|
|
25209
26108
|
const typescriptNotices = [];
|
|
25210
26109
|
/**
|
|
25211
|
-
* Restart the process so Node drops the complete ESM compiler graph
|
|
25212
|
-
*
|
|
25213
|
-
* server
|
|
25214
|
-
* "Cannot call write after a stream
|
|
26110
|
+
* Restart the process so Node drops the complete ESM compiler graph, once
|
|
26111
|
+
* package state has settled (`createRestartScheduler`). A client that restarts
|
|
26112
|
+
* the server itself stops sending first. When the server exits by itself, the
|
|
26113
|
+
* client's next message fails (VS Code showed "Cannot call write after a stream
|
|
26114
|
+
* was destroyed").
|
|
25215
26115
|
*/
|
|
25216
|
-
|
|
25217
|
-
if (restartScheduled) return;
|
|
25218
|
-
restartScheduled = true;
|
|
26116
|
+
const restartLanguageServer = createRestartScheduler(() => {
|
|
25219
26117
|
if (clientRestarts) {
|
|
25220
26118
|
log("Asking the client to restart the server after package state changed.");
|
|
25221
26119
|
connection.sendNotification(RESTART_NOTIFICATION);
|
|
@@ -25223,7 +26121,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25223
26121
|
}
|
|
25224
26122
|
log("Restarting after package state changed.");
|
|
25225
26123
|
setTimeout(() => process.exit(0), 50);
|
|
25226
|
-
}
|
|
26124
|
+
});
|
|
25227
26125
|
/**
|
|
25228
26126
|
* Ensure TypeScript hosts always see TSRX compiler defaults.
|
|
25229
26127
|
* @param {unknown} target
|
|
@@ -25300,6 +26198,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25300
26198
|
}
|
|
25301
26199
|
for (const notice of typescriptNotices) logError(notice);
|
|
25302
26200
|
}
|
|
26201
|
+
activeBackend = backend;
|
|
25303
26202
|
if (ts === void 0) {
|
|
25304
26203
|
const compilerResolutionDependencies = /* @__PURE__ */ new Set();
|
|
25305
26204
|
compilerResolutionDependencySets.add(compilerResolutionDependencies);
|
|
@@ -25357,10 +26256,10 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25357
26256
|
server.project.reload();
|
|
25358
26257
|
},
|
|
25359
26258
|
requestRefresh: (clearDiagnostics) => server.languageFeatures.requestRefresh(clearDiagnostics)
|
|
25360
|
-
}, trackedTypeScriptConfigFiles).reloadProjects) log("Reloaded TypeScript projects after workspace configuration changed.");
|
|
26259
|
+
}, trackedTypeScriptConfigFiles, server.workspaceFolders.all.filter((folder) => folder.scheme === "file").map((folder) => folder.fsPath)).reloadProjects) log("Reloaded TypeScript projects after workspace configuration changed.");
|
|
25361
26260
|
});
|
|
25362
26261
|
try {
|
|
25363
|
-
await server.fileWatcher.watchFiles(
|
|
26262
|
+
await server.fileWatcher.watchFiles(getWorkspaceFilePatterns(activeBackend));
|
|
25364
26263
|
log("Workspace file watchers registered.");
|
|
25365
26264
|
} catch (err) {
|
|
25366
26265
|
logError("Failed to register file watchers:", err);
|
|
@@ -25379,9 +26278,10 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25379
26278
|
}
|
|
25380
26279
|
/**
|
|
25381
26280
|
* Advertise what the server's own handlers serve: the formatters `register_formatting`
|
|
25382
|
-
* serves (whole document and range),
|
|
25383
|
-
* serves on `>`, unless the client closes tags another
|
|
25384
|
-
* No Volar service plugin advertises
|
|
26281
|
+
* serves (whole document and range), the folds `register_folding_ranges` serves, and the
|
|
26282
|
+
* closing tags `register_closing_tags` serves on `>`, unless the client closes tags another
|
|
26283
|
+
* way (`closes_tags_on_type`). No Volar service plugin advertises any of them
|
|
26284
|
+
* (`stripFormatting`, `stripFoldingRanges`).
|
|
25385
26285
|
* @template {import('@volar/language-server/node').InitializeResult} T
|
|
25386
26286
|
* @param {T} initResult
|
|
25387
26287
|
* @param {import('@volar/language-server/node').InitializeParams} params
|
|
@@ -25390,6 +26290,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25390
26290
|
function with_own_handlers(initResult, params) {
|
|
25391
26291
|
initResult.capabilities.documentFormattingProvider = true;
|
|
25392
26292
|
initResult.capabilities.documentRangeFormattingProvider = true;
|
|
26293
|
+
initResult.capabilities.foldingRangeProvider = true;
|
|
25393
26294
|
if (closes_tags_on_type(params)) initResult.capabilities.documentOnTypeFormattingProvider = CLOSING_TAGS_ON_TYPE;
|
|
25394
26295
|
return initResult;
|
|
25395
26296
|
}
|
|
@@ -25427,4 +26328,4 @@ Object.defineProperty(exports, 'createTsrxLanguageServer', {
|
|
|
25427
26328
|
return createTsrxLanguageServer;
|
|
25428
26329
|
}
|
|
25429
26330
|
});
|
|
25430
|
-
//# sourceMappingURL=server-
|
|
26331
|
+
//# sourceMappingURL=server-B_LRzE1h.js.map
|