summaryrefslogtreecommitdiff
path: root/tools/vscode/packages/server/src/plugins/PluginHost.ts
blob: 037dd6e070642a2466fad135a0eaa85923d79911 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { CompletionContext, CompletionItem, CompletionList, Position, TextDocumentIdentifier } from 'vscode-languageserver';
import type { DocumentManager } from '../core/documents';
import type * as d from './interfaces';
import { flatten } from '../utils';
import { FoldingRange } from 'vscode-languageserver-types';

// eslint-disable-next-line no-shadow
enum ExecuteMode {
  None,
  FirstNonNull,
  Collect,
}

export class PluginHost {
  private plugins: d.Plugin[] = [];

  constructor(private documentsManager: DocumentManager) {}

  register(plugin: d.Plugin) {
    this.plugins.push(plugin);
  }

  async getCompletions(textDocument: TextDocumentIdentifier, position: Position, completionContext?: CompletionContext): Promise<CompletionList> {
    const document = this.getDocument(textDocument.uri);
    if (!document) {
      throw new Error('Cannot call methods on an unopened document');
    }

    const completions = (await this.execute<CompletionList>('getCompletions', [document, position, completionContext], ExecuteMode.Collect)).filter(
      (completion) => completion != null
    );

    let flattenedCompletions = flatten(completions.map((completion) => completion.items));
    const isIncomplete = completions.reduce((incomplete, completion) => incomplete || completion.isIncomplete, false as boolean);

    return CompletionList.create(flattenedCompletions, isIncomplete);
  }

  async resolveCompletion(textDocument: TextDocumentIdentifier, completionItem: d.AppCompletionItem): Promise<CompletionItem> {
    const document = this.getDocument(textDocument.uri);

    if (!document) {
      throw new Error('Cannot call methods on an unopened document');
    }

    const result = await this.execute<CompletionItem>('resolveCompletion', [document, completionItem], ExecuteMode.FirstNonNull);

    return result ?? completionItem;
  }

  async doTagComplete(textDocument: TextDocumentIdentifier, position: Position): Promise<string | null> {
    const document = this.getDocument(textDocument.uri);
    if (!document) {
      throw new Error('Cannot call methods on an unopened document');
    }

    return this.execute<string | null>('doTagComplete', [document, position], ExecuteMode.FirstNonNull);
  }

  async getFoldingRanges(textDocument: TextDocumentIdentifier): Promise<FoldingRange[] | null> {
    const document = this.getDocument(textDocument.uri);
    if (!document) {
      throw new Error('Cannot call methods on an unopened document');
    }

    const foldingRanges = flatten(await this.execute<FoldingRange[]>('getFoldingRanges', [document], ExecuteMode.Collect)).filter((completion) => completion != null);

    return foldingRanges;
  }

  onWatchFileChanges(onWatchFileChangesParams: any[]): void {
    for (const support of this.plugins) {
      support.onWatchFileChanges?.(onWatchFileChangesParams);
    }
  }

  private getDocument(uri: string) {
    return this.documentsManager.get(uri);
  }

  private execute<T>(name: keyof d.LSProvider, args: any[], mode: ExecuteMode.FirstNonNull): Promise<T | null>;
  private execute<T>(name: keyof d.LSProvider, args: any[], mode: ExecuteMode.Collect): Promise<T[]>;
  private execute(name: keyof d.LSProvider, args: any[], mode: ExecuteMode.None): Promise<void>;
  private async execute<T>(name: keyof d.LSProvider, args: any[], mode: ExecuteMode): Promise<(T | null) | T[] | void> {
    const plugins = this.plugins.filter((plugin) => typeof plugin[name] === 'function');

    switch (mode) {
      case ExecuteMode.FirstNonNull:
        for (const plugin of plugins) {
          const res = await this.tryExecutePlugin(plugin, name, args, null);
          if (res != null) {
            return res;
          }
        }
        return null;
      case ExecuteMode.Collect:
        return Promise.all(plugins.map((plugin) => this.tryExecutePlugin(plugin, name, args, [])));
      case ExecuteMode.None:
        await Promise.all(plugins.map((plugin) => this.tryExecutePlugin(plugin, name, args, null)));
        return;
    }
  }

  private async tryExecutePlugin(plugin: any, fnName: string, args: any[], failValue: any) {
    try {
      return await plugin[fnName](...args);
    } catch (e) {
      console.error(e);
      return failValue;
    }
  }
}