@astrojs/language-server 0.11.0 → 0.13.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.
Files changed (103) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/bin/browserServer.js +3 -0
  3. package/bin/nodeServer.js +3 -0
  4. package/dist/browser.d.ts +1 -0
  5. package/dist/browser.js +8 -0
  6. package/dist/check.js +2 -5
  7. package/dist/core/DiagnosticsManager.d.ts +3 -3
  8. package/dist/core/DiagnosticsManager.js +2 -2
  9. package/dist/core/config/ConfigManager.d.ts +19 -164
  10. package/dist/core/config/ConfigManager.js +62 -101
  11. package/dist/core/config/index.d.ts +1 -0
  12. package/dist/core/config/index.js +1 -0
  13. package/dist/core/config/interfaces.d.ts +123 -0
  14. package/dist/core/config/interfaces.js +2 -0
  15. package/dist/core/documents/AstroDocument.d.ts +18 -0
  16. package/dist/core/documents/AstroDocument.js +42 -0
  17. package/dist/core/documents/DocumentBase.d.ts +10 -2
  18. package/dist/core/documents/DocumentBase.js +15 -50
  19. package/dist/core/documents/DocumentManager.d.ts +12 -16
  20. package/dist/core/documents/DocumentManager.js +32 -26
  21. package/dist/core/documents/DocumentMapper.js +3 -1
  22. package/dist/core/documents/index.d.ts +1 -1
  23. package/dist/core/documents/index.js +1 -1
  24. package/dist/core/documents/parseAstro.d.ts +2 -2
  25. package/dist/core/documents/parseHtml.d.ts +2 -2
  26. package/dist/core/documents/parseHtml.js +4 -1
  27. package/dist/core/documents/utils.d.ts +22 -26
  28. package/dist/core/documents/utils.js +96 -134
  29. package/dist/index.d.ts +0 -1
  30. package/dist/index.js +1 -3
  31. package/dist/node.d.ts +1 -0
  32. package/dist/node.js +29 -0
  33. package/dist/plugins/PluginHost.d.ts +11 -9
  34. package/dist/plugins/PluginHost.js +34 -36
  35. package/dist/plugins/astro/AstroPlugin.d.ts +11 -12
  36. package/dist/plugins/astro/AstroPlugin.js +17 -42
  37. package/dist/plugins/astro/features/{CompletionProvider.d.ts → CompletionsProvider.d.ts} +5 -5
  38. package/dist/plugins/astro/features/{CompletionProvider.js → CompletionsProvider.js} +33 -58
  39. package/dist/plugins/css/CSSDocument.d.ts +3 -3
  40. package/dist/plugins/css/CSSDocument.js +7 -16
  41. package/dist/plugins/css/CSSPlugin.d.ts +31 -12
  42. package/dist/plugins/css/CSSPlugin.js +174 -41
  43. package/dist/plugins/css/StyleAttributeDocument.d.ts +2 -2
  44. package/dist/plugins/css/StyleAttributeDocument.js +2 -2
  45. package/dist/plugins/css/features/astro-selectors.d.ts +2 -0
  46. package/dist/plugins/css/features/astro-selectors.js +16 -0
  47. package/dist/plugins/css/features/{getIdClassCompletion.d.ts → getIdClassCompletions.d.ts} +3 -3
  48. package/dist/plugins/css/features/{getIdClassCompletion.js → getIdClassCompletions.js} +10 -9
  49. package/dist/plugins/css/{service.d.ts → language-service.d.ts} +0 -0
  50. package/dist/plugins/css/{service.js → language-service.js} +2 -1
  51. package/dist/plugins/html/HTMLPlugin.d.ts +18 -17
  52. package/dist/plugins/html/HTMLPlugin.js +69 -41
  53. package/dist/plugins/html/features/astro-attributes.d.ts +2 -0
  54. package/dist/plugins/html/features/astro-attributes.js +126 -0
  55. package/dist/plugins/index.d.ts +2 -2
  56. package/dist/plugins/index.js +2 -2
  57. package/dist/plugins/interfaces.d.ts +35 -48
  58. package/dist/plugins/typescript/LanguageServiceManager.d.ts +33 -14
  59. package/dist/plugins/typescript/LanguageServiceManager.js +57 -32
  60. package/dist/plugins/typescript/TypeScriptPlugin.d.ts +18 -23
  61. package/dist/plugins/typescript/TypeScriptPlugin.js +58 -55
  62. package/dist/plugins/typescript/astro-sys.d.ts +5 -3
  63. package/dist/plugins/typescript/astro-sys.js +24 -45
  64. package/dist/plugins/typescript/features/CompletionsProvider.d.ts +6 -6
  65. package/dist/plugins/typescript/features/CompletionsProvider.js +18 -38
  66. package/dist/plugins/typescript/features/DiagnosticsProvider.d.ts +4 -4
  67. package/dist/plugins/typescript/features/DiagnosticsProvider.js +27 -87
  68. package/dist/plugins/typescript/features/DocumentSymbolsProvider.d.ts +10 -0
  69. package/dist/plugins/typescript/features/DocumentSymbolsProvider.js +69 -0
  70. package/dist/plugins/typescript/features/HoverProvider.d.ts +4 -5
  71. package/dist/plugins/typescript/features/HoverProvider.js +9 -10
  72. package/dist/plugins/typescript/features/SignatureHelpProvider.d.ts +4 -5
  73. package/dist/plugins/typescript/features/SignatureHelpProvider.js +15 -11
  74. package/dist/plugins/typescript/features/utils.d.ts +1 -12
  75. package/dist/plugins/typescript/features/utils.js +2 -22
  76. package/dist/plugins/typescript/language-service.d.ts +38 -0
  77. package/dist/plugins/typescript/language-service.js +230 -0
  78. package/dist/plugins/typescript/module-loader.d.ts +5 -8
  79. package/dist/plugins/typescript/module-loader.js +43 -23
  80. package/dist/plugins/typescript/snapshots/DocumentSnapshot.d.ts +90 -0
  81. package/dist/plugins/typescript/snapshots/DocumentSnapshot.js +135 -0
  82. package/dist/plugins/typescript/snapshots/SnapshotManager.d.ts +42 -0
  83. package/dist/plugins/typescript/snapshots/SnapshotManager.js +197 -0
  84. package/dist/plugins/typescript/snapshots/utils.d.ts +28 -0
  85. package/dist/plugins/typescript/snapshots/utils.js +84 -0
  86. package/dist/plugins/typescript/utils.d.ts +10 -13
  87. package/dist/plugins/typescript/utils.js +154 -158
  88. package/dist/server.d.ts +2 -4
  89. package/dist/server.js +93 -54
  90. package/dist/utils.d.ts +20 -16
  91. package/dist/utils.js +35 -24
  92. package/package.json +18 -12
  93. package/types/astro-jsx.d.ts +1077 -0
  94. package/bin/server.js +0 -7
  95. package/dist/core/documents/Document.d.ts +0 -51
  96. package/dist/core/documents/Document.js +0 -135
  97. package/dist/plugins/typescript/DocumentSnapshot.d.ts +0 -99
  98. package/dist/plugins/typescript/DocumentSnapshot.js +0 -259
  99. package/dist/plugins/typescript/SnapshotManager.d.ts +0 -24
  100. package/dist/plugins/typescript/SnapshotManager.js +0 -103
  101. package/dist/plugins/typescript/languageService.d.ts +0 -17
  102. package/dist/plugins/typescript/languageService.js +0 -173
  103. package/types/index.d.ts +0 -4
@@ -0,0 +1,10 @@
1
+ import { SymbolInformation } from 'vscode-languageserver-types';
2
+ import { AstroDocument } from '../../../core/documents';
3
+ import { DocumentSymbolsProvider } from '../../interfaces';
4
+ import { LanguageServiceManager } from '../LanguageServiceManager';
5
+ export declare class DocumentSymbolsProviderImpl implements DocumentSymbolsProvider {
6
+ private languageServiceManager;
7
+ constructor(languageServiceManager: LanguageServiceManager);
8
+ getDocumentSymbols(document: AstroDocument): Promise<SymbolInformation[]>;
9
+ private collectSymbols;
10
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocumentSymbolsProviderImpl = void 0;
4
+ const typescript_1 = require("typescript");
5
+ const vscode_languageserver_types_1 = require("vscode-languageserver-types");
6
+ const documents_1 = require("../../../core/documents");
7
+ const utils_1 = require("../utils");
8
+ const vscode_languageserver_types_2 = require("vscode-languageserver-types");
9
+ class DocumentSymbolsProviderImpl {
10
+ constructor(languageServiceManager) {
11
+ this.languageServiceManager = languageServiceManager;
12
+ }
13
+ async getDocumentSymbols(document) {
14
+ var _a, _b, _c;
15
+ const { lang, tsDoc } = await this.languageServiceManager.getLSAndTSDoc(document);
16
+ const fragment = await tsDoc.createFragment();
17
+ const navTree = lang.getNavigationTree(tsDoc.filePath);
18
+ if (!navTree) {
19
+ return [];
20
+ }
21
+ const symbols = [];
22
+ this.collectSymbols(navTree, fragment, undefined, (symbol) => symbols.push(symbol));
23
+ const result = [];
24
+ // Add a "Frontmatter" namespace for the frontmatter if we have a closed one
25
+ if (document.astroMeta.frontmatter.state === 'closed') {
26
+ result.push(vscode_languageserver_types_1.SymbolInformation.create('Frontmatter', vscode_languageserver_types_1.SymbolKind.Namespace, vscode_languageserver_types_1.Range.create(document.positionAt(document.astroMeta.frontmatter.startOffset), document.positionAt(document.astroMeta.frontmatter.endOffset))));
27
+ }
28
+ // Add a "Template" namespace for everything under the frontmatter
29
+ result.push(vscode_languageserver_types_1.SymbolInformation.create('Template', vscode_languageserver_types_1.SymbolKind.Namespace, vscode_languageserver_types_1.Range.create(document.positionAt((_a = document.astroMeta.frontmatter.endOffset) !== null && _a !== void 0 ? _a : 0), document.positionAt(document.getTextLength()))));
30
+ for (let symbol of symbols.splice(1)) {
31
+ symbol = (0, documents_1.mapSymbolInformationToOriginal)(fragment, symbol);
32
+ if (document.offsetAt(symbol.location.range.end) >= ((_b = document.astroMeta.content.firstNonWhitespaceOffset) !== null && _b !== void 0 ? _b : 0)) {
33
+ symbol.containerName = 'Template';
34
+ // For some reason, it seems like TypeScript thinks that the "class" attribute is a real class, weird
35
+ if (symbol.kind === vscode_languageserver_types_1.SymbolKind.Class && symbol.name === '<class>') {
36
+ const node = document.html.findNodeAt(document.offsetAt(symbol.location.range.start));
37
+ if ((_c = node.attributes) === null || _c === void 0 ? void 0 : _c.class) {
38
+ continue;
39
+ }
40
+ }
41
+ }
42
+ // Remove the default function detected in our TSX output
43
+ if (symbol.kind === vscode_languageserver_types_1.SymbolKind.Function && symbol.name == 'default') {
44
+ continue;
45
+ }
46
+ result.push(symbol);
47
+ }
48
+ return result;
49
+ }
50
+ collectSymbols(item, fragment, container, cb) {
51
+ for (const span of item.spans) {
52
+ const symbol = vscode_languageserver_types_1.SymbolInformation.create(item.text, (0, utils_1.symbolKindFromString)(item.kind), vscode_languageserver_types_1.Range.create(fragment.positionAt(span.start), fragment.positionAt(span.start + span.length)), fragment.getURL(), container);
53
+ // TypeScript gives us kind modifiers as a string instead of an array
54
+ const kindModifiers = new Set(item.kindModifiers.split(/,|\s+/g));
55
+ if (kindModifiers.has(typescript_1.ScriptElementKindModifier.deprecatedModifier)) {
56
+ if (!symbol.tags)
57
+ symbol.tags = [];
58
+ symbol.tags.push(vscode_languageserver_types_2.SymbolTag.Deprecated);
59
+ }
60
+ cb(symbol);
61
+ }
62
+ if (item.childItems) {
63
+ for (const child of item.childItems) {
64
+ this.collectSymbols(child, fragment, item.text, cb);
65
+ }
66
+ }
67
+ }
68
+ }
69
+ exports.DocumentSymbolsProviderImpl = DocumentSymbolsProviderImpl;
@@ -1,10 +1,9 @@
1
1
  import type { LanguageServiceManager } from '../LanguageServiceManager';
2
2
  import { Hover, Position } from 'vscode-languageserver';
3
- import { Document } from '../../../core/documents';
3
+ import { AstroDocument } from '../../../core/documents';
4
4
  import { HoverProvider } from '../../interfaces';
5
5
  export declare class HoverProviderImpl implements HoverProvider {
6
- private readonly lang;
7
- constructor(lang: LanguageServiceManager);
8
- doHover(document: Document, position: Position): Promise<Hover | null>;
9
- private getLSAndTSDoc;
6
+ private readonly languageServiceManager;
7
+ constructor(languageServiceManager: LanguageServiceManager);
8
+ doHover(document: AstroDocument, position: Position): Promise<Hover | null>;
10
9
  }
@@ -10,12 +10,12 @@ const previewer_1 = require("../previewer");
10
10
  const utils_1 = require("../utils");
11
11
  const partsMap = new Map([['JSX attribute', 'HTML attribute']]);
12
12
  class HoverProviderImpl {
13
- constructor(lang) {
14
- this.lang = lang;
13
+ constructor(languageServiceManager) {
14
+ this.languageServiceManager = languageServiceManager;
15
15
  }
16
16
  async doHover(document, position) {
17
- const { lang, tsDoc } = await this.getLSAndTSDoc(document);
18
- const fragment = await tsDoc.getFragment();
17
+ const { lang, tsDoc } = await this.languageServiceManager.getLSAndTSDoc(document);
18
+ const fragment = await tsDoc.createFragment();
19
19
  const offset = fragment.offsetAt(fragment.getGeneratedPosition(position));
20
20
  const filePath = (0, utils_1.toVirtualAstroFilePath)(tsDoc.filePath);
21
21
  let info = lang.getQuickInfoAtPosition(filePath, offset);
@@ -23,21 +23,20 @@ class HoverProviderImpl {
23
23
  return null;
24
24
  }
25
25
  const textSpan = info.textSpan;
26
- const displayParts = (info.displayParts || []).map(value => ({
26
+ const displayParts = (info.displayParts || []).map((value) => ({
27
27
  text: partsMap.has(value.text) ? partsMap.get(value.text) : value.text,
28
- kind: value.kind
28
+ kind: value.kind,
29
29
  }));
30
30
  const declaration = typescript_1.default.displayPartsToString(displayParts);
31
31
  const documentation = (0, previewer_1.getMarkdownDocumentation)(info.documentation, info.tags);
32
32
  // https://microsoft.github.io/language-server-protocol/specification#textDocument_hover
33
- const contents = ['```typescript', declaration, '```'].concat(documentation ? ['---', documentation] : []).join('\n');
33
+ const contents = ['```typescript', declaration, '```']
34
+ .concat(documentation ? ['---', documentation] : [])
35
+ .join('\n');
34
36
  return (0, documents_1.mapObjWithRangeToOriginal)(fragment, {
35
37
  range: (0, utils_1.convertRange)(fragment, textSpan),
36
38
  contents,
37
39
  });
38
40
  }
39
- async getLSAndTSDoc(document) {
40
- return this.lang.getTypeScriptDoc(document);
41
- }
42
41
  }
43
42
  exports.HoverProviderImpl = HoverProviderImpl;
@@ -1,13 +1,13 @@
1
1
  import type { LanguageServiceManager } from '../LanguageServiceManager';
2
2
  import type { SignatureHelpProvider } from '../../interfaces';
3
3
  import { Position, SignatureHelpContext, SignatureHelp, CancellationToken } from 'vscode-languageserver';
4
- import { Document } from '../../../core/documents';
4
+ import { AstroDocument } from '../../../core/documents';
5
5
  export declare class SignatureHelpProviderImpl implements SignatureHelpProvider {
6
- private readonly lang;
7
- constructor(lang: LanguageServiceManager);
6
+ private readonly languageServiceManager;
7
+ constructor(languageServiceManager: LanguageServiceManager);
8
8
  private static readonly triggerCharacters;
9
9
  private static readonly retriggerCharacters;
10
- getSignatureHelp(document: Document, position: Position, context: SignatureHelpContext | undefined, cancellationToken?: CancellationToken): Promise<SignatureHelp | null>;
10
+ getSignatureHelp(document: AstroDocument, position: Position, context: SignatureHelpContext | undefined, cancellationToken?: CancellationToken): Promise<SignatureHelp | null>;
11
11
  private isReTrigger;
12
12
  private isTriggerCharacter;
13
13
  /**
@@ -18,5 +18,4 @@ export declare class SignatureHelpProviderImpl implements SignatureHelpProvider
18
18
  * adopted from https://github.com/microsoft/vscode/blob/265a2f6424dfbd3a9788652c7d376a7991d049a3/extensions/typescript-language-features/src/languageFeatures/signatureHelp.ts#L73
19
19
  */
20
20
  private toSignatureHelpInformation;
21
- private isInSvelte2tsxGeneratedFunction;
22
21
  }
@@ -9,19 +9,20 @@ const vscode_languageserver_1 = require("vscode-languageserver");
9
9
  const previewer_1 = require("../previewer");
10
10
  const utils_1 = require("../utils");
11
11
  class SignatureHelpProviderImpl {
12
- constructor(lang) {
13
- this.lang = lang;
12
+ constructor(languageServiceManager) {
13
+ this.languageServiceManager = languageServiceManager;
14
14
  }
15
15
  async getSignatureHelp(document, position, context, cancellationToken) {
16
- const { lang, tsDoc } = await this.lang.getTypeScriptDoc(document);
17
- const fragment = await tsDoc.getFragment();
16
+ const { lang, tsDoc } = await this.languageServiceManager.getLSAndTSDoc(document);
17
+ const fragment = await tsDoc.createFragment();
18
18
  if (cancellationToken === null || cancellationToken === void 0 ? void 0 : cancellationToken.isCancellationRequested) {
19
19
  return null;
20
20
  }
21
+ const filePath = (0, utils_1.toVirtualAstroFilePath)(tsDoc.filePath);
21
22
  const offset = fragment.offsetAt(fragment.getGeneratedPosition(position));
22
23
  const triggerReason = this.toTsTriggerReason(context);
23
- const info = lang.getSignatureHelpItems((0, utils_1.toVirtualAstroFilePath)(tsDoc.filePath), offset, triggerReason ? { triggerReason } : undefined);
24
- if (!info || info.items.some((signature) => this.isInSvelte2tsxGeneratedFunction(signature))) {
24
+ const info = lang.getSignatureHelpItems(filePath, offset, triggerReason ? { triggerReason } : undefined);
25
+ if (!info) {
25
26
  return null;
26
27
  }
27
28
  const signatures = info.items.map(this.toSignatureHelpInformation);
@@ -32,7 +33,9 @@ class SignatureHelpProviderImpl {
32
33
  };
33
34
  }
34
35
  isReTrigger(isRetrigger, triggerCharacter) {
35
- return isRetrigger && (this.isTriggerCharacter(triggerCharacter) || SignatureHelpProviderImpl.retriggerCharacters.includes(triggerCharacter));
36
+ return (isRetrigger &&
37
+ (this.isTriggerCharacter(triggerCharacter) ||
38
+ SignatureHelpProviderImpl.retriggerCharacters.includes(triggerCharacter)));
36
39
  }
37
40
  isTriggerCharacter(triggerCharacter) {
38
41
  return SignatureHelpProviderImpl.triggerCharacters.includes(triggerCharacter);
@@ -66,7 +69,11 @@ class SignatureHelpProviderImpl {
66
69
  * adopted from https://github.com/microsoft/vscode/blob/265a2f6424dfbd3a9788652c7d376a7991d049a3/extensions/typescript-language-features/src/languageFeatures/signatureHelp.ts#L73
67
70
  */
68
71
  toSignatureHelpInformation(item) {
69
- const [prefixLabel, separatorLabel, suffixLabel] = [item.prefixDisplayParts, item.separatorDisplayParts, item.suffixDisplayParts].map(typescript_1.default.displayPartsToString);
72
+ const [prefixLabel, separatorLabel, suffixLabel] = [
73
+ item.prefixDisplayParts,
74
+ item.separatorDisplayParts,
75
+ item.suffixDisplayParts,
76
+ ].map(typescript_1.default.displayPartsToString);
70
77
  let textIndex = prefixLabel.length;
71
78
  let signatureLabel = '';
72
79
  const parameters = [];
@@ -95,9 +102,6 @@ class SignatureHelpProviderImpl {
95
102
  parameters,
96
103
  };
97
104
  }
98
- isInSvelte2tsxGeneratedFunction(signatureHelpItem) {
99
- return signatureHelpItem.prefixDisplayParts.some((part) => part.text.includes('__sveltets'));
100
- }
101
105
  }
102
106
  exports.SignatureHelpProviderImpl = SignatureHelpProviderImpl;
103
107
  SignatureHelpProviderImpl.triggerCharacters = ['(', ',', '<'];
@@ -1,16 +1,5 @@
1
- import type { SnapshotFragment, DocumentSnapshot } from '../DocumentSnapshot';
1
+ import type { SnapshotFragment, DocumentSnapshot } from '../snapshots/DocumentSnapshot';
2
2
  import type { LanguageServiceManager } from '../LanguageServiceManager';
3
- import type { TextSpan } from 'typescript';
4
- /**
5
- * Checks if this a section that should be completely ignored
6
- * because it's purely generated.
7
- */
8
- export declare function isInGeneratedCode(text: string, start: number, end: number): boolean;
9
- /**
10
- * Checks that this isn't a text span that should be completely ignored
11
- * because it's purely generated.
12
- */
13
- export declare function isNoTextSpanInGeneratedCode(text: string, span: TextSpan): boolean;
14
3
  export declare class SnapshotFragmentMap {
15
4
  private languageServiceManager;
16
5
  private map;
@@ -1,26 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SnapshotFragmentMap = exports.isNoTextSpanInGeneratedCode = exports.isInGeneratedCode = void 0;
4
- /**
5
- * Checks if this a section that should be completely ignored
6
- * because it's purely generated.
7
- */
8
- function isInGeneratedCode(text, start, end) {
9
- const lineStart = text.lastIndexOf('\n', start);
10
- const lineEnd = text.indexOf('\n', end);
11
- const lastStart = text.substring(lineStart, start).lastIndexOf('/*Ωignore_startΩ*/');
12
- const lastEnd = text.substring(lineStart, start).lastIndexOf('/*Ωignore_endΩ*/');
13
- return lastStart > lastEnd && text.substring(end, lineEnd).includes('/*Ωignore_endΩ*/');
14
- }
15
- exports.isInGeneratedCode = isInGeneratedCode;
16
- /**
17
- * Checks that this isn't a text span that should be completely ignored
18
- * because it's purely generated.
19
- */
20
- function isNoTextSpanInGeneratedCode(text, span) {
21
- return !isInGeneratedCode(text, span.start, span.start + span.length);
22
- }
23
- exports.isNoTextSpanInGeneratedCode = isNoTextSpanInGeneratedCode;
3
+ exports.SnapshotFragmentMap = void 0;
24
4
  class SnapshotFragmentMap {
25
5
  constructor(languageServiceManager) {
26
6
  this.languageServiceManager = languageServiceManager;
@@ -40,7 +20,7 @@ class SnapshotFragmentMap {
40
20
  let snapshotFragment = this.get(fileName);
41
21
  if (!snapshotFragment) {
42
22
  const snapshot = await this.languageServiceManager.getSnapshot(fileName);
43
- const fragment = await snapshot.getFragment();
23
+ const fragment = await snapshot.createFragment();
44
24
  snapshotFragment = { fragment, snapshot };
45
25
  this.set(fileName, snapshotFragment);
46
26
  }
@@ -0,0 +1,38 @@
1
+ import { AstroDocument } from '../../core/documents';
2
+ import ts from 'typescript';
3
+ import { TextDocumentContentChangeEvent } from 'vscode-languageserver';
4
+ import { GlobalSnapshotManager, SnapshotManager } from './snapshots/SnapshotManager';
5
+ import { DocumentSnapshot } from './snapshots/DocumentSnapshot';
6
+ export interface LanguageServiceContainer {
7
+ readonly tsconfigPath: string;
8
+ readonly compilerOptions: ts.CompilerOptions;
9
+ /**
10
+ * @internal Public for tests only
11
+ */
12
+ readonly snapshotManager: SnapshotManager;
13
+ getService(): ts.LanguageService;
14
+ updateSnapshot(documentOrFilePath: AstroDocument | string): DocumentSnapshot;
15
+ deleteSnapshot(filePath: string): void;
16
+ updateProjectFiles(): void;
17
+ updateNonAstroFile(fileName: string, changes?: TextDocumentContentChangeEvent[]): void;
18
+ /**
19
+ * Checks if a file is present in the project.
20
+ * Unlike `fileBelongsToProject`, this doesn't run a file search on disk.
21
+ */
22
+ hasFile(filePath: string): boolean;
23
+ /**
24
+ * Careful, don't call often, or it will hurt performance.
25
+ */
26
+ fileBelongsToProject(filePath: string): boolean;
27
+ }
28
+ export interface LanguageServiceDocumentContext {
29
+ createDocument: (fileName: string, content: string) => AstroDocument;
30
+ globalSnapshotManager: GlobalSnapshotManager;
31
+ }
32
+ export declare function getLanguageService(path: string, workspaceUris: string[], docContext: LanguageServiceDocumentContext): Promise<LanguageServiceContainer>;
33
+ export declare function forAllLanguageServices(cb: (service: LanguageServiceContainer) => any): Promise<void>;
34
+ /**
35
+ * @param tsconfigPath has to be absolute
36
+ * @param docContext
37
+ */
38
+ export declare function getLanguageServiceForTsconfig(tsconfigPath: string, docContext: LanguageServiceDocumentContext): Promise<LanguageServiceContainer>;
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.getLanguageServiceForTsconfig = exports.forAllLanguageServices = exports.getLanguageService = void 0;
30
+ const path_1 = require("path");
31
+ const typescript_1 = __importDefault(require("typescript"));
32
+ const utils_1 = require("../../utils");
33
+ const module_loader_1 = require("./module-loader");
34
+ const SnapshotManager_1 = require("./snapshots/SnapshotManager");
35
+ const utils_2 = require("./utils");
36
+ const DocumentSnapshotUtils = __importStar(require("./snapshots/utils"));
37
+ const services = new Map();
38
+ async function getLanguageService(path, workspaceUris, docContext) {
39
+ const tsconfigPath = (0, utils_2.findTsConfigPath)(path, workspaceUris);
40
+ return getLanguageServiceForTsconfig(tsconfigPath, docContext);
41
+ }
42
+ exports.getLanguageService = getLanguageService;
43
+ async function forAllLanguageServices(cb) {
44
+ for (const service of services.values()) {
45
+ cb(await service);
46
+ }
47
+ }
48
+ exports.forAllLanguageServices = forAllLanguageServices;
49
+ /**
50
+ * @param tsconfigPath has to be absolute
51
+ * @param docContext
52
+ */
53
+ async function getLanguageServiceForTsconfig(tsconfigPath, docContext) {
54
+ let service;
55
+ if (services.has(tsconfigPath)) {
56
+ service = await services.get(tsconfigPath);
57
+ }
58
+ else {
59
+ const newService = createLanguageService(tsconfigPath, docContext);
60
+ services.set(tsconfigPath, newService);
61
+ service = await newService;
62
+ }
63
+ return service;
64
+ }
65
+ exports.getLanguageServiceForTsconfig = getLanguageServiceForTsconfig;
66
+ async function createLanguageService(tsconfigPath, docContext) {
67
+ const workspaceRoot = tsconfigPath ? (0, path_1.dirname)(tsconfigPath) : process.cwd();
68
+ // `raw` here represent the tsconfig merged with any extended config
69
+ const { compilerOptions, fileNames: files, raw: fullConfig } = getParsedTSConfig();
70
+ let projectVersion = 0;
71
+ const snapshotManager = new SnapshotManager_1.SnapshotManager(docContext.globalSnapshotManager, files, fullConfig, workspaceRoot || process.cwd());
72
+ const astroModuleLoader = (0, module_loader_1.createAstroModuleLoader)(getScriptSnapshot, compilerOptions);
73
+ let languageServerDirectory;
74
+ try {
75
+ languageServerDirectory = (0, path_1.dirname)(require.resolve('@astrojs/language-server'));
76
+ }
77
+ catch (e) {
78
+ languageServerDirectory = __dirname;
79
+ }
80
+ const astroTSXFile = typescript_1.default.sys.resolvePath((0, path_1.resolve)(languageServerDirectory, '../types/astro-jsx.d.ts'));
81
+ const host = {
82
+ getNewLine: () => typescript_1.default.sys.newLine,
83
+ useCaseSensitiveFileNames: () => typescript_1.default.sys.useCaseSensitiveFileNames,
84
+ getDirectories: typescript_1.default.sys.getDirectories,
85
+ resolveModuleNames: astroModuleLoader.resolveModuleNames,
86
+ readFile: astroModuleLoader.readFile,
87
+ fileExists: astroModuleLoader.fileExists,
88
+ readDirectory: astroModuleLoader.readDirectory,
89
+ getCompilationSettings: () => compilerOptions,
90
+ getCurrentDirectory: () => workspaceRoot,
91
+ getDefaultLibFileName: typescript_1.default.getDefaultLibFilePath,
92
+ getProjectVersion: () => projectVersion.toString(),
93
+ getScriptFileNames: () => Array.from(new Set([...snapshotManager.getProjectFileNames(), ...snapshotManager.getFileNames(), astroTSXFile])),
94
+ getScriptSnapshot,
95
+ getScriptVersion: (fileName) => getScriptSnapshot(fileName).version.toString(),
96
+ };
97
+ let languageService = typescript_1.default.createLanguageService(host);
98
+ docContext.globalSnapshotManager.onChange(() => {
99
+ projectVersion++;
100
+ });
101
+ return {
102
+ tsconfigPath,
103
+ compilerOptions,
104
+ getService: () => languageService,
105
+ updateSnapshot,
106
+ deleteSnapshot,
107
+ updateProjectFiles,
108
+ updateNonAstroFile,
109
+ hasFile,
110
+ fileBelongsToProject,
111
+ snapshotManager,
112
+ };
113
+ function deleteSnapshot(filePath) {
114
+ astroModuleLoader.deleteFromModuleCache(filePath);
115
+ snapshotManager.delete(filePath);
116
+ }
117
+ function updateSnapshot(documentOrFilePath) {
118
+ return typeof documentOrFilePath === 'string'
119
+ ? updateSnapshotFromFilePath(documentOrFilePath)
120
+ : updateSnapshotFromDocument(documentOrFilePath);
121
+ }
122
+ function updateSnapshotFromDocument(document) {
123
+ const filePath = document.getFilePath() || '';
124
+ const prevSnapshot = snapshotManager.get(filePath);
125
+ if ((prevSnapshot === null || prevSnapshot === void 0 ? void 0 : prevSnapshot.version) === document.version) {
126
+ return prevSnapshot;
127
+ }
128
+ if (!prevSnapshot) {
129
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(filePath);
130
+ }
131
+ const newSnapshot = DocumentSnapshotUtils.createFromDocument(document);
132
+ snapshotManager.set(filePath, newSnapshot);
133
+ if (prevSnapshot && prevSnapshot.scriptKind !== newSnapshot.scriptKind) {
134
+ // Restart language service as it doesn't handle script kind changes.
135
+ languageService.dispose();
136
+ languageService = typescript_1.default.createLanguageService(host);
137
+ }
138
+ return newSnapshot;
139
+ }
140
+ function updateSnapshotFromFilePath(filePath) {
141
+ const prevSnapshot = snapshotManager.get(filePath);
142
+ if (prevSnapshot) {
143
+ return prevSnapshot;
144
+ }
145
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(filePath);
146
+ const newSnapshot = DocumentSnapshotUtils.createFromFilePath(filePath, docContext.createDocument);
147
+ snapshotManager.set(filePath, newSnapshot);
148
+ return newSnapshot;
149
+ }
150
+ function getScriptSnapshot(fileName) {
151
+ fileName = (0, utils_2.ensureRealFilePath)(fileName);
152
+ let doc = snapshotManager.get(fileName);
153
+ if (doc) {
154
+ return doc;
155
+ }
156
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(fileName);
157
+ doc = DocumentSnapshotUtils.createFromFilePath(fileName, docContext.createDocument);
158
+ snapshotManager.set(fileName, doc);
159
+ return doc;
160
+ }
161
+ function updateProjectFiles() {
162
+ projectVersion++;
163
+ snapshotManager.updateProjectFiles();
164
+ }
165
+ function hasFile(filePath) {
166
+ return snapshotManager.has(filePath);
167
+ }
168
+ function fileBelongsToProject(filePath) {
169
+ filePath = (0, utils_1.normalizePath)(filePath);
170
+ return hasFile(filePath) || getParsedTSConfig().fileNames.includes(filePath);
171
+ }
172
+ function updateNonAstroFile(fileName, changes) {
173
+ if (!snapshotManager.has(fileName)) {
174
+ astroModuleLoader.deleteUnresolvedResolutionsFromCache(fileName);
175
+ }
176
+ snapshotManager.updateNonAstroFile(fileName, changes);
177
+ }
178
+ function getParsedTSConfig() {
179
+ var _a, _b, _c;
180
+ let configJson = (tsconfigPath && typescript_1.default.readConfigFile(tsconfigPath, typescript_1.default.sys.readFile).config) || {};
181
+ // If our user has types in their config but it doesn't include the types needed for Astro, add them to the config
182
+ if (((_a = configJson.compilerOptions) === null || _a === void 0 ? void 0 : _a.types) && !((_b = configJson.compilerOptions) === null || _b === void 0 ? void 0 : _b.types.includes('astro/env'))) {
183
+ configJson.compilerOptions.types.push('astro/env');
184
+ }
185
+ configJson.compilerOptions = Object.assign(getDefaultCompilerOptions(), configJson.compilerOptions);
186
+ // Delete include so that .astro files don't get mistakenly excluded by the user
187
+ delete configJson.include;
188
+ // If the user supplied exclude, let's use theirs otherwise, use ours
189
+ (_c = configJson.exclude) !== null && _c !== void 0 ? _c : (configJson.exclude = getDefaultExclude());
190
+ // Everything here will always, unconditionally, be in the resulting config
191
+ const forcedCompilerOptions = {
192
+ noEmit: true,
193
+ declaration: false,
194
+ allowNonTsExtensions: true,
195
+ allowJs: true,
196
+ jsx: typescript_1.default.JsxEmit.Preserve,
197
+ jsxImportSource: undefined,
198
+ jsxFactory: 'astroHTML',
199
+ module: typescript_1.default.ModuleKind.ESNext,
200
+ target: typescript_1.default.ScriptTarget.ESNext,
201
+ moduleResolution: typescript_1.default.ModuleResolutionKind.NodeJs,
202
+ };
203
+ const project = typescript_1.default.parseJsonConfigFileContent(configJson, typescript_1.default.sys, workspaceRoot, forcedCompilerOptions, tsconfigPath, undefined, [
204
+ { extension: '.vue', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
205
+ { extension: '.svelte', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
206
+ { extension: '.astro', isMixedContent: true, scriptKind: typescript_1.default.ScriptKind.Deferred },
207
+ ]);
208
+ return {
209
+ ...project,
210
+ fileNames: project.fileNames.map(utils_1.normalizePath),
211
+ compilerOptions: {
212
+ ...project.options,
213
+ ...forcedCompilerOptions,
214
+ },
215
+ };
216
+ }
217
+ }
218
+ /**
219
+ * Default configuration used as a base and when the user doesn't have any
220
+ */
221
+ function getDefaultCompilerOptions() {
222
+ return {
223
+ maxNodeModuleJsDepth: 2,
224
+ allowSyntheticDefaultImports: true,
225
+ types: ['astro/env'],
226
+ };
227
+ }
228
+ function getDefaultExclude() {
229
+ return ['dist', 'node_modules'];
230
+ }
@@ -1,11 +1,11 @@
1
1
  import ts from 'typescript';
2
- import type { DocumentSnapshot } from './DocumentSnapshot';
2
+ import type { DocumentSnapshot } from './snapshots/DocumentSnapshot';
3
3
  /**
4
- * Creates a module loader specifically for `.astro` files.
4
+ * Creates a module loader specifically for `.astro` and other frameworks files.
5
5
  *
6
6
  * The typescript language service tries to look up other files that are referenced in the currently open astro file.
7
- * For `.ts`/`.js` files this works, for `.astro` files it does not by default.
8
- * Reason: The typescript language service does not know about the `.astro` file ending,
7
+ * For `.ts`/`.js` files this works, for `.astro` and frameworks files it does not by default.
8
+ * Reason: The typescript language service does not know about those file endings,
9
9
  * so it assumes it's a normal typescript file and searches for files like `../Component.astro.ts`, which is wrong.
10
10
  * In order to fix this, we need to wrap typescript's module resolution and reroute all `.astro.ts` file lookups to .astro.
11
11
  *
@@ -15,11 +15,8 @@ import type { DocumentSnapshot } from './DocumentSnapshot';
15
15
  export declare function createAstroModuleLoader(getSnapshot: (fileName: string) => DocumentSnapshot, compilerOptions: ts.CompilerOptions): {
16
16
  fileExists: (path: string) => boolean;
17
17
  readFile: (path: string, encoding?: string | undefined) => string | undefined;
18
- writeFile: (path: string, data: string, writeByteOrderMark?: boolean | undefined) => void;
19
18
  readDirectory: (path: string, extensions?: readonly string[] | undefined, exclude?: readonly string[] | undefined, include?: readonly string[] | undefined, depth?: number | undefined) => string[];
20
- directoryExists: (path: string) => boolean;
21
- getDirectories: (path: string) => string[];
22
- realpath: ((path: string) => string) | undefined;
23
19
  deleteFromModuleCache: (path: string) => void;
20
+ deleteUnresolvedResolutionsFromCache: (path: string) => void;
24
21
  resolveModuleNames: (moduleNames: string[], containingFile: string) => Array<ts.ResolvedModule | undefined>;
25
22
  };