"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const semver = __importStar(require("semver"));
const vscode = __importStar(require("vscode-languageserver-protocol"));
const shared_1 = require("./shared");
const _callHierarchy = __importStar(require("./services/callHierarchy"));
const codeActions = __importStar(require("./services/codeAction"));
const codeActionResolve = __importStar(require("./services/codeActionResolve"));
const completions = __importStar(require("./services/completions/basic"));
const directiveCommentCompletions = __importStar(require("./services/completions/directiveComment"));
const jsDocCompletions = __importStar(require("./services/completions/jsDoc"));
const completionResolve = __importStar(require("./services/completions/resolve"));
const definitions = __importStar(require("./services/definition"));
const diagnostics = __importStar(require("./services/diagnostics"));
const documentHighlight = __importStar(require("./services/documentHighlight"));
const documentSymbol = __importStar(require("./services/documentSymbol"));
const fileReferences = __importStar(require("./services/fileReferences"));
const fileRename = __importStar(require("./services/fileRename"));
const foldingRanges = __importStar(require("./services/foldingRanges"));
const formatting = __importStar(require("./services/formatting"));
const hover = __importStar(require("./services/hover"));
const implementation = __importStar(require("./services/implementation"));
const inlayHints = __importStar(require("./services/inlayHints"));
const prepareRename = __importStar(require("./services/prepareRename"));
const references = __importStar(require("./services/references"));
const rename = __importStar(require("./services/rename"));
const selectionRanges = __importStar(require("./services/selectionRanges"));
const semanticTokens = __importStar(require("./services/semanticTokens"));
const signatureHelp = __importStar(require("./services/signatureHelp"));
const typeDefinitions = __importStar(require("./services/typeDefinition"));
const workspaceSymbols = __importStar(require("./services/workspaceSymbol"));
const tsconfig = __importStar(require("./services/tsconfig"));
exports.default = () => (contextOrNull) => {
    const jsDocTriggerCharacter = '*';
    const directiveCommentTriggerCharacter = '@';
    const triggerCharacters = {
        triggerCharacters: [
            ...getBasicTriggerCharacters('4.3.0'),
            jsDocTriggerCharacter,
            directiveCommentTriggerCharacter,
        ],
        signatureHelpTriggerCharacters: ['(', ',', '<'],
        signatureHelpRetriggerCharacters: [')'],
        // https://github.com/microsoft/vscode/blob/ce119308e8fd4cd3f992d42b297588e7abe33a0c/extensions/typescript-language-features/src/languageFeatures/formatting.ts#L99
        autoFormatTriggerCharacters: [';', '}', '\n'],
    };
    if (!contextOrNull) {
        return triggerCharacters;
    }
    const context = contextOrNull;
    if (!context.typescript) {
        console.warn('[@volar-plugins/typescript] context.typescript not found, @volar/typescript plugin disabled. Make sure you have provide tsdk in language client.');
        return {};
    }
    const { module: ts } = context.typescript;
    const basicTriggerCharacters = getBasicTriggerCharacters(ts.version);
    const semanticCtx = {
        ...context,
        getTextDocument(uri) {
            for (const [_, map] of context.documents.getMapsByVirtualFileUri(uri)) {
                return map.virtualFileDocument;
            }
            return context.getTextDocument(uri);
        },
    };
    const findDefinition = definitions.register(semanticCtx);
    const findTypeDefinition = typeDefinitions.register(semanticCtx);
    const findReferences = references.register(semanticCtx);
    const findFileReferences = fileReferences.register(semanticCtx);
    const findImplementations = implementation.register(semanticCtx);
    const doPrepareRename = prepareRename.register(semanticCtx);
    const doRename = rename.register(semanticCtx);
    const getEditsForFileRename = fileRename.register(semanticCtx);
    const getCodeActions = codeActions.register(semanticCtx);
    const doCodeActionResolve = codeActionResolve.register(semanticCtx);
    const getInlayHints = inlayHints.register(semanticCtx);
    const findDocumentHighlights = documentHighlight.register(semanticCtx);
    const findWorkspaceSymbols = workspaceSymbols.register(semanticCtx);
    const doComplete = completions.register(semanticCtx);
    const doCompletionResolve = completionResolve.register(semanticCtx);
    const doDirectiveCommentComplete = directiveCommentCompletions.register(semanticCtx);
    const doJsDocComplete = jsDocCompletions.register(semanticCtx);
    const doHover = hover.register(semanticCtx);
    const getSignatureHelp = signatureHelp.register(semanticCtx);
    const getSelectionRanges = selectionRanges.register(semanticCtx);
    const doValidation = diagnostics.register(semanticCtx);
    const getDocumentSemanticTokens = semanticTokens.register(semanticCtx);
    const callHierarchy = _callHierarchy.register(semanticCtx);
    const tsconfigRequests = tsconfig.register(semanticCtx);
    let syntacticHostCtx = {
        fileName: '',
        fileVersion: 0,
        snapshot: ts.ScriptSnapshot.fromString(''),
    };
    const syntacticServiceHost = {
        getProjectVersion: () => syntacticHostCtx.fileName + '::' + syntacticHostCtx.fileVersion,
        getScriptFileNames: () => [syntacticHostCtx.fileName],
        getScriptVersion: fileName => fileName === syntacticHostCtx.fileName ? syntacticHostCtx.fileVersion.toString() : '',
        getScriptSnapshot: fileName => fileName === syntacticHostCtx.fileName ? syntacticHostCtx.snapshot : undefined,
        getCompilationSettings: () => context.typescript?.languageServiceHost.getCompilationSettings() ?? {},
        getCurrentDirectory: () => '',
        getDefaultLibFileName: () => '',
        readFile: () => undefined,
        fileExists: fileName => fileName === syntacticHostCtx.fileName,
    };
    const syntacticCtx = {
        ...semanticCtx,
        typescript: {
            ...semanticCtx.typescript,
            languageServiceHost: syntacticServiceHost,
            languageService: ts.createLanguageService(syntacticServiceHost),
        },
    };
    const findDocumentSymbols = documentSymbol.register(syntacticCtx);
    const doFormatting = formatting.register(syntacticCtx);
    const getFoldingRanges = foldingRanges.register(syntacticCtx);
    return {
        ...triggerCharacters,
        triggerCharacters: [
            ...basicTriggerCharacters,
            jsDocTriggerCharacter,
            directiveCommentTriggerCharacter,
        ],
        resolveRuleContext(ruleCtx, type) {
            if ((0, shared_1.isTsDocument)(ruleCtx.document)) {
                let sourceFile;
                if (type === 'format' || type === 'syntax') {
                    prepareSyntacticService(ruleCtx.document);
                    sourceFile = syntacticCtx.typescript.languageService.getProgram()?.getSourceFile(syntacticHostCtx.fileName);
                }
                else {
                    sourceFile = semanticCtx.typescript.languageService.getProgram()?.getSourceFile(context.uriToFileName(ruleCtx.document.uri));
                }
                if (sourceFile) {
                    ruleCtx.typescript = {
                        sourceFile,
                        ...syntacticCtx.typescript,
                    };
                }
                else {
                    console.warn('[@volar-plugins/typescript] sourceFile not found', ruleCtx.document.uri);
                }
            }
            return ruleCtx;
        },
        provideAutoInsertionEdit(document, position, ctx) {
            if ((document.languageId === 'javascriptreact' || document.languageId === 'typescriptreact')
                && ctx.lastChange.text.endsWith('>')) {
                const configName = document.languageId === 'javascriptreact' ? 'javascript.autoClosingTags' : 'typescript.autoClosingTags';
                const config = context.configurationHost?.getConfiguration(configName) ?? true;
                if (config) {
                    prepareSyntacticService(document);
                    const close = syntacticCtx.typescript.languageService.getJsxClosingTagAtPosition(context.uriToFileName(document.uri), document.offsetAt(position));
                    if (close) {
                        return '$0' + close.newText;
                    }
                }
            }
        },
        async provideCompletionItems(document, position, context) {
            if ((0, shared_1.isTsDocument)(document)) {
                let result = {
                    isIncomplete: false,
                    items: [],
                };
                if (!context || context.triggerKind !== vscode.CompletionTriggerKind.TriggerCharacter || (context.triggerCharacter && basicTriggerCharacters.includes(context.triggerCharacter))) {
                    const completeOptions = {
                        triggerCharacter: context?.triggerCharacter,
                        triggerKind: context?.triggerKind,
                    };
                    const basicResult = await doComplete(document.uri, position, completeOptions);
                    if (basicResult) {
                        result = basicResult;
                    }
                }
                if (!context || context.triggerKind !== vscode.CompletionTriggerKind.TriggerCharacter || context.triggerCharacter === jsDocTriggerCharacter) {
                    const jsdocResult = await doJsDocComplete(document.uri, position);
                    if (jsdocResult) {
                        result.items.push(jsdocResult);
                    }
                }
                if (!context || context.triggerKind !== vscode.CompletionTriggerKind.TriggerCharacter || context.triggerCharacter === directiveCommentTriggerCharacter) {
                    const directiveCommentResult = await doDirectiveCommentComplete(document.uri, position);
                    if (directiveCommentResult) {
                        result.items = result.items.concat(directiveCommentResult);
                    }
                }
                return result;
            }
        },
        resolveCompletionItem(item) {
            return doCompletionResolve(item);
        },
        provideRenameRange(document, position) {
            if ((0, shared_1.isTsDocument)(document)) {
                return doPrepareRename(document.uri, position);
            }
        },
        provideRenameEdits(document, position, newName) {
            if ((0, shared_1.isTsDocument)(document) || (0, shared_1.isJsonDocument)(document)) {
                return doRename(document.uri, position, newName);
            }
        },
        provideCodeActions(document, range, context) {
            if ((0, shared_1.isTsDocument)(document)) {
                return getCodeActions(document.uri, range, context);
            }
        },
        resolveCodeAction(codeAction) {
            return doCodeActionResolve(codeAction);
        },
        provideInlayHints(document, range) {
            if ((0, shared_1.isTsDocument)(document)) {
                return getInlayHints(document.uri, range);
            }
        },
        provideCallHierarchyItems(document, position) {
            if ((0, shared_1.isTsDocument)(document)) {
                return callHierarchy.doPrepare(document.uri, position);
            }
        },
        provideCallHierarchyIncomingCalls(item) {
            return callHierarchy.getIncomingCalls(item);
        },
        provideCallHierarchyOutgoingCalls(item) {
            return callHierarchy.getOutgoingCalls(item);
        },
        provideDefinition(document, position) {
            if ((0, shared_1.isTsDocument)(document)) {
                return findDefinition(document.uri, position);
            }
        },
        provideTypeDefinition(document, position) {
            if ((0, shared_1.isTsDocument)(document)) {
                return findTypeDefinition(document.uri, position);
            }
        },
        provideSyntacticDiagnostics(document) {
            if ((0, shared_1.isTsDocument)(document)) {
                return doValidation(document.uri, { syntactic: true, suggestion: true });
            }
        },
        provideSemanticDiagnostics(document) {
            if ((0, shared_1.isTsDocument)(document)) {
                return doValidation(document.uri, { semantic: true, declaration: true });
            }
        },
        provideHover(document, position) {
            if ((0, shared_1.isTsDocument)(document)) {
                return doHover(document.uri, position);
            }
        },
        provideImplementation(document, position) {
            if ((0, shared_1.isTsDocument)(document)) {
                return findImplementations(document.uri, position);
            }
        },
        provideReferences(document, position) {
            if ((0, shared_1.isTsDocument)(document) || (0, shared_1.isJsonDocument)(document)) {
                return findReferences(document.uri, position);
            }
        },
        provideFileReferences(document) {
            if ((0, shared_1.isTsDocument)(document) || (0, shared_1.isJsonDocument)(document)) {
                return findFileReferences(document.uri);
            }
        },
        provideDocumentHighlights(document, position) {
            if ((0, shared_1.isTsDocument)(document)) {
                return findDocumentHighlights(document.uri, position);
            }
        },
        provideDocumentSymbols(document) {
            if ((0, shared_1.isTsDocument)(document)) {
                prepareSyntacticService(document);
                return findDocumentSymbols(document.uri);
            }
        },
        provideDocumentSemanticTokens(document, range, legend) {
            if ((0, shared_1.isTsDocument)(document)) {
                return getDocumentSemanticTokens(document.uri, range, legend);
            }
        },
        provideWorkspaceSymbols(query) {
            return findWorkspaceSymbols(query);
        },
        provideFileRenameEdits(oldUri, newUri) {
            return getEditsForFileRename(oldUri, newUri);
        },
        provideFoldingRanges(document) {
            if ((0, shared_1.isTsDocument)(document)) {
                prepareSyntacticService(document);
                return getFoldingRanges(document.uri);
            }
        },
        provideSelectionRanges(document, positions) {
            if ((0, shared_1.isTsDocument)(document)) {
                return getSelectionRanges(document.uri, positions);
            }
        },
        provideSignatureHelp(document, position, context) {
            if ((0, shared_1.isTsDocument)(document)) {
                return getSignatureHelp(document.uri, position, context);
            }
        },
        async provideDocumentFormattingEdits(document, range, options_2) {
            if ((0, shared_1.isTsDocument)(document)) {
                const enable = await context.configurationHost?.getConfiguration((0, shared_1.getConfigTitle)(document) + '.format.enable');
                if (enable === false) {
                    return;
                }
                prepareSyntacticService(document);
                return doFormatting.onRange(document.uri, range, options_2);
            }
        },
        async provideOnTypeFormattingEdits(document, position, key, options_2) {
            if ((0, shared_1.isTsDocument)(document)) {
                const enable = await context.configurationHost?.getConfiguration((0, shared_1.getConfigTitle)(document) + '.format.enable');
                if (enable === false) {
                    return;
                }
                prepareSyntacticService(document);
                return doFormatting.onType(document.uri, options_2, position, key);
            }
        },
        provideFormattingIndentSensitiveLines(document) {
            if ((0, shared_1.isTsDocument)(document)) {
                prepareSyntacticService(document);
                const sourceFile = syntacticCtx.typescript.languageService.getProgram()?.getSourceFile(context.uriToFileName(document.uri));
                if (sourceFile) {
                    const lines = [];
                    sourceFile.forEachChild(function walk(node) {
                        if (node.kind === ts.SyntaxKind.FirstTemplateToken
                            || node.kind === ts.SyntaxKind.LastTemplateToken
                            || node.kind === ts.SyntaxKind.TemplateHead) {
                            const startLine = document.positionAt(node.getStart(sourceFile)).line;
                            const endLine = document.positionAt(node.getEnd()).line;
                            for (let i = startLine + 1; i <= endLine; i++) {
                                lines.push(i);
                            }
                        }
                        node.forEachChild(walk);
                    });
                    return lines;
                }
            }
        },
        /**
         * for tsconfig: https://github.com/microsoft/vscode/blob/main/extensions/typescript-language-features/src/languageFeatures/tsconfig.ts
         */
        provideDocumentLinks(document, token) {
            return tsconfigRequests.provideDocumentLinks(document, token);
        },
        resolveDocumentLink(link, token) {
            return tsconfigRequests.resolve(link, token);
        },
    };
    function prepareSyntacticService(document) {
        syntacticHostCtx.fileName = context.uriToFileName(document.uri);
        syntacticHostCtx.fileVersion = document.version;
        if (context.documents.isVirtualFileUri(document.uri)) {
            const snapshot = context.documents.getVirtualFileByUri(document.uri)[0]?.snapshot;
            if (snapshot) {
                syntacticHostCtx.snapshot = snapshot;
            }
            else {
                throw new Error('No snapshot found for ' + document.uri);
            }
        }
        else {
            const snapshot = context.host.getScriptSnapshot(syntacticHostCtx.fileName);
            if (snapshot) {
                syntacticHostCtx.snapshot = snapshot;
            }
            else {
                throw new Error('No snapshot found for ' + document.uri);
            }
        }
    }
};
function getBasicTriggerCharacters(tsVersion) {
    const triggerCharacters = ['.', '"', '\'', '`', '/', '<'];
    // https://github.com/microsoft/vscode/blob/8e65ae28d5fb8b3c931135da1a41edb9c80ae46f/extensions/typescript-language-features/src/languageFeatures/completions.ts#L811-L833
    if (semver.lt(tsVersion, '3.1.0') || semver.gte(tsVersion, '3.2.0')) {
        triggerCharacters.push('@');
    }
    if (semver.gte(tsVersion, '3.8.1')) {
        triggerCharacters.push('#');
    }
    if (semver.gte(tsVersion, '4.3.0')) {
        triggerCharacters.push(' ');
    }
    return triggerCharacters;
}
//# sourceMappingURL=index.js.map