"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = void 0;
var _utils = require("../utils");
const TYPE_ANOTATION = ": Metadata";
const TYPE_IMPORT = `import type { Metadata } from 'next'`;
// Find the `export const metadata = ...` node.
function getMetadataExport(fileName, position) {
    const source = (0, _utils).getSource(fileName);
    let metadataExport;
    if (source) {
        const ts = (0, _utils).getTs();
        ts.forEachChild(source, function visit(node) {
            if (metadataExport) return;
            // Covered by this node
            if ((0, _utils).isPositionInsideNode(position, node)) {
                var ref;
                // Export variable
                if (ts.isVariableStatement(node) && ((ref = node.modifiers) == null ? void 0 : ref.some((m)=>m.kind === ts.SyntaxKind.ExportKeyword))) {
                    if (ts.isVariableDeclarationList(node.declarationList)) {
                        for (const declaration of node.declarationList.declarations){
                            if ((0, _utils).isPositionInsideNode(position, declaration) && declaration.name.getText() === "metadata") {
                                // `export const metadata = ...`
                                metadataExport = declaration;
                                return;
                            }
                        }
                    }
                }
            }
        });
    }
    return metadataExport;
}
let cachedProxiedLanguageService;
let cachedProxiedLanguageServiceHost;
function getProxiedLanguageService() {
    if (cachedProxiedLanguageService) return {
        languageService: cachedProxiedLanguageService,
        languageServiceHost: cachedProxiedLanguageServiceHost
    };
    const languageServiceHost = (0, _utils).getInfo().languageServiceHost;
    const ts = (0, _utils).getTs();
    class ProxiedLanguageServiceHost {
        files = {};
        log = ()=>{};
        trace = ()=>{};
        error = ()=>{};
        getCompilationSettings = ()=>languageServiceHost.getCompilationSettings();
        getScriptIsOpen = ()=>true;
        getCurrentDirectory = ()=>languageServiceHost.getCurrentDirectory();
        getDefaultLibFileName = (o)=>languageServiceHost.getDefaultLibFileName(o);
        getScriptVersion = (fileName)=>{
            const file = this.files[fileName];
            if (!file) return languageServiceHost.getScriptVersion(fileName);
            return file.ver.toString();
        };
        getScriptSnapshot = (fileName)=>{
            const file = this.files[fileName];
            if (!file) return languageServiceHost.getScriptSnapshot(fileName);
            return file.file;
        };
        getScriptFileNames() {
            const names = new Set();
            for(var name in this.files){
                if (this.files.hasOwnProperty(name)) {
                    names.add(name);
                }
            }
            const files = languageServiceHost.getScriptFileNames();
            for (const file of files){
                names.add(file);
            }
            return [
                ...names
            ];
        }
        addFile(fileName, body) {
            const snap = ts.ScriptSnapshot.fromString(body);
            snap.getChangeRange = (_)=>undefined;
            const existing = this.files[fileName];
            if (existing) {
                this.files[fileName].ver++;
                this.files[fileName].file = snap;
            } else {
                this.files[fileName] = {
                    ver: 1,
                    file: snap
                };
            }
        }
        readFile(fileName) {
            const file = this.files[fileName];
            return file ? file.file.getText(0, file.file.getLength()) : languageServiceHost.readFile(fileName);
        }
        fileExists(fileName) {
            return this.files[fileName] !== undefined || languageServiceHost.fileExists(fileName);
        }
    }
    cachedProxiedLanguageServiceHost = new ProxiedLanguageServiceHost();
    cachedProxiedLanguageService = ts.createLanguageService(cachedProxiedLanguageServiceHost, ts.createDocumentRegistry());
    return {
        languageService: cachedProxiedLanguageService,
        languageServiceHost: cachedProxiedLanguageServiceHost
    };
}
function updateVirtualFileWithType(fileName, node) {
    const source = (0, _utils).getSource(fileName);
    if (!source) return;
    // We annotate with the type in a vritual language service
    const sourceText = source.getFullText();
    const nodeEnd = node.name.getFullStart() + node.name.getFullWidth();
    const newSource = sourceText.slice(0, nodeEnd) + TYPE_ANOTATION + sourceText.slice(nodeEnd) + TYPE_IMPORT;
    const { languageServiceHost  } = getProxiedLanguageService();
    languageServiceHost.addFile(fileName, newSource);
    return nodeEnd;
}
function isTyped(node) {
    return node.type !== undefined;
}
const metadata = {
    filterCompletionsAtPosition (fileName, position, _options, prior) {
        const node = getMetadataExport(fileName, position);
        if (!node) return prior;
        if (isTyped(node)) return prior;
        const ts = (0, _utils).getTs();
        // We annotate with the type in a vritual language service
        const nodeEnd = updateVirtualFileWithType(fileName, node);
        if (nodeEnd === undefined) return prior;
        // Get completions
        const { languageService  } = getProxiedLanguageService();
        const newPos = position <= nodeEnd ? position : position + TYPE_ANOTATION.length;
        const completions = languageService.getCompletionsAtPosition(fileName, newPos, undefined);
        if (completions) {
            completions.isIncomplete = true;
            completions.entries = completions.entries.filter((e)=>{
                return [
                    ts.ScriptElementKind.memberVariableElement,
                    ts.ScriptElementKind.typeElement,
                    ts.ScriptElementKind.string, 
                ].includes(e.kind);
            }).map((e)=>{
                const insertText = e.kind === ts.ScriptElementKind.memberVariableElement && /^[a-zA-Z0-9_]+$/.test(e.name) ? e.name + ": " : e.name;
                return {
                    name: e.name,
                    insertText,
                    kind: e.kind,
                    kindModifiers: e.kindModifiers,
                    sortText: "!" + e.name,
                    labelDetails: {
                        description: `Next.js metadata`
                    },
                    data: e.data
                };
            });
            return completions;
        }
        return prior;
    },
    getSemanticDiagnosticsForExportVariableStatement (fileName, node) {
        const source = (0, _utils).getSource(fileName);
        for (const declaration of node.declarationList.declarations){
            if (declaration.name.getText() === "metadata") {
                if (isTyped(declaration)) break;
                // We annotate with the type in a vritual language service
                const nodeEnd = updateVirtualFileWithType(fileName, declaration);
                if (!nodeEnd) break;
                // Get diagnostics
                const { languageService  } = getProxiedLanguageService();
                const diagnostics = languageService.getSemanticDiagnostics(fileName);
                // Filter and map the results
                return diagnostics.filter((d)=>{
                    if (d.start === undefined || d.length === undefined) return false;
                    if (d.start < declaration.getFullStart()) return false;
                    if (d.start + d.length > declaration.getFullStart() + declaration.getFullWidth() + TYPE_ANOTATION.length) return false;
                    return true;
                }).map((d)=>{
                    return {
                        file: source,
                        category: d.category,
                        code: d.code,
                        messageText: d.messageText,
                        start: d.start <= nodeEnd ? d.start : d.start - TYPE_ANOTATION.length,
                        length: d.length
                    };
                });
            }
        }
        return [];
    },
    getCompletionEntryDetails (fileName, position, entryName, formatOptions, source, preferences, data) {
        const node = getMetadataExport(fileName, position);
        if (!node) return;
        if (isTyped(node)) return;
        // We annotate with the type in a vritual language service
        const nodeEnd = updateVirtualFileWithType(fileName, node);
        if (nodeEnd === undefined) return;
        const { languageService  } = getProxiedLanguageService();
        const newPos = position <= nodeEnd ? position : position + TYPE_ANOTATION.length;
        const details = languageService.getCompletionEntryDetails(fileName, newPos, entryName, formatOptions, source, preferences, data);
        return details;
    },
    getQuickInfoAtPosition (fileName, position) {
        const node = getMetadataExport(fileName, position);
        if (!node) return;
        if (isTyped(node)) return;
        // We annotate with the type in a vritual language service
        const nodeEnd = updateVirtualFileWithType(fileName, node);
        if (nodeEnd === undefined) return;
        const { languageService  } = getProxiedLanguageService();
        const newPos = position <= nodeEnd ? position : position + TYPE_ANOTATION.length;
        const insight = languageService.getQuickInfoAtPosition(fileName, newPos);
        return insight;
    }
};
var _default = metadata;
exports.default = _default;

//# sourceMappingURL=metadata.js.map