
import { registerCss } from '../../../../../../../css.js';
import { __decorate, __param } from '../../../../../../../external/tslib/tslib.es6.js';
import * as extensionsViewlet from './media/extensionsViewlet.css';
import { localize2, localize } from '../../../../nls.js';
import { Delayer, timeout } from '../../../../base/common/async.js';
import { isCancellationError } from '../../../../base/common/errors.js';
import { createErrorWithActions } from '../../../../base/common/errorMessage.js';
import { Disposable, MutableDisposable, DisposableStore } from '../../../../base/common/lifecycle.js';
import { Event } from '../../../../base/common/event.js';
import { Action } from '../../../../base/common/actions.js';
import { append, $, hide, DragAndDropObserver, show, trackFocus, Dimension, clearNode, addDisposableListener, EventType } from '../../../../base/browser/dom.js';
import { renderAsPlaintext, renderMarkdown } from '../../../../base/browser/markdownRenderer.js';
import { isMarkdownString } from '../../../../base/common/htmlContent.js';
import { IOpenerService } from '../../../../platform/opener/common/opener.service.js';
import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.service.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { IExtensionService } from '../../../services/extensions/common/extensions.service.js';
import { VIEWLET_ID, DefaultViewsContext, CONTEXT_EXTENSIONS_GALLERY_STATUS, CONTEXT_HAS_GALLERY, OUTDATED_EXTENSIONS_VIEW_ID, WORKSPACE_RECOMMENDATIONS_VIEW_ID, SearchMcpServersContext, SearchAgentPluginsContext, extensionsSearchActionsMenu, INSTALL_EXTENSION_FROM_VSIX_COMMAND_ID, AutoCheckUpdatesConfigurationKey, CloseExtensionDetailsOnViewChangeKey, AutoRestartConfigurationKey, ExtensionRuntimeActionType } from '../common/extensions.js';
import { IExtensionsWorkbenchService } from '../common/extensions.service.js';
import { InstallLocalExtensionsInRemoteAction, InstallRemoteExtensionsInLocalAction } from './extensionsActions.js';
import { IExtensionManagementService } from '../../../../platform/extensionManagement/common/extensionManagement.service.js';
import { IExtensionManagementServerService, IWorkbenchExtensionEnablementService } from '../../../services/extensionManagement/common/extensionManagement.service.js';
import { ExtensionsInput } from '../common/extensionsInput.js';
import { ServerInstalledExtensionsView, DefaultPopularExtensionsView, DefaultRecommendedExtensionsView, EnabledExtensionsView, DisabledExtensionsView, SearchMarketplaceExtensionsView, ExtensionsListView, RecentlyUpdatedExtensionsView, OutdatedExtensionsView, WorkspaceRecommendedExtensionsView, RecommendedExtensionsView, NONE_CATEGORY, StaticQueryExtensionsView, UntrustedWorkspaceUnsupportedExtensionsView, UntrustedWorkspacePartiallySupportedExtensionsView, VirtualWorkspaceUnsupportedExtensionsView, VirtualWorkspacePartiallySupportedExtensionsView, DeprecatedExtensionsView, AbstractExtensionsListView } from './extensionsViews.js';
import { ProgressLocation } from '../../../../platform/progress/common/progress.js';
import { IProgressService } from '../../../../platform/progress/common/progress.service.js';
import { IEditorGroupsService } from '../../../services/editor/common/editorGroupsService.service.js';
import Severity$1 from '../../../../base/common/severity.js';
import { WarningBadge, NumberBadge } from '../../../services/activity/common/activity.js';
import { IActivityService } from '../../../services/activity/common/activity.service.js';
import { IThemeService } from '../../../../platform/theme/common/themeService.service.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.service.js';
import { Extensions, ViewContainerLocation } from '../../../common/views.js';
import { IViewDescriptorService } from '../../../common/views.service.js';
import { StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
import { IStorageService } from '../../../../platform/storage/common/storage.service.js';
import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.service.js';
import { RawContextKey, ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js';
import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.service.js';
import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.service.js';
import { ILogService } from '../../../../platform/log/common/log.service.js';
import { NotificationPriority } from '../../../../platform/notification/common/notification.js';
import { INotificationService } from '../../../../platform/notification/common/notification.service.js';
import { IHostService } from '../../../services/host/browser/host.service.js';
import { IWorkbenchLayoutService } from '../../../services/layout/browser/layoutService.service.js';
import { ViewPaneContainer } from '../../../browser/parts/views/viewPaneContainer.js';
import { ViewPane } from '../../../browser/parts/views/viewPane.js';
import { Query } from '../common/extensionQuery.js';
import { SuggestEnabledInput } from '../../codeEditor/browser/suggestEnabledInput/suggestEnabledInput.js';
import { alert } from '../../../../base/browser/ui/aria/aria.js';
import { EXTENSION_CATEGORIES } from '../../../../platform/extensions/common/extensions.js';
import { Registry } from '../../../../platform/registry/common/platform.js';
import { ILabelService } from '../../../../platform/label/common/label.service.js';
import { SyncDescriptor } from '../../../../platform/instantiation/common/descriptors.js';
import { IPreferencesService } from '../../../services/preferences/common/preferences.service.js';
import { SIDE_BAR_DRAG_AND_DROP_BACKGROUND } from '../../../common/theme.js';
import { WorkbenchStateContext, VirtualWorkspaceContext } from '../../../common/contextkeys.js';
import { ICommandService } from '../../../../platform/commands/common/commands.service.js';
import { installLocalInRemoteIcon } from './extensionsIcons.js';
import { registerAction2, Action2, MenuId } from '../../../../platform/actions/common/actions.js';
import { IPaneCompositePartService } from '../../../services/panecomposite/browser/panecomposite.service.js';
import { coalesce } from '../../../../base/common/arrays.js';
import { extractEditorsAndFilesDropData } from '../../../../platform/dnd/browser/dnd.js';
import { extname } from '../../../../base/common/resources.js';
import { registerNavigableContainer } from '../../../browser/actions/widgetNavigationCommands.js';
import { MenuWorkbenchToolBar } from '../../../../platform/actions/browser/toolbar.js';
import { createActionViewItem } from '../../../../platform/actions/browser/menuEntryActionViewItem.js';
import { SeverityIcon } from '../../../../base/browser/ui/severityIcon/severityIcon.js';
import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js';
import { KeyCode } from '../../../../base/common/keyCodes.js';
import { ExtensionGalleryManifestStatus } from '../../../../platform/extensionManagement/common/extensionGalleryManifest.js';
import { IExtensionGalleryManifestService } from '../../../../platform/extensionManagement/common/extensionGalleryManifest.service.js';
import { URI } from '../../../../base/common/uri.js';
import { DEFAULT_ACCOUNT_SIGN_IN_COMMAND } from '../../../services/accounts/browser/defaultAccount.js';

registerCss(extensionsViewlet);
const ExtensionsSortByContext = ( new RawContextKey("extensionsSortByValue", ""));
const SearchMarketplaceExtensionsContext = ( new RawContextKey("searchMarketplaceExtensions", false));
const SearchHasTextContext = ( new RawContextKey("extensionSearchHasText", false));
const InstalledExtensionsContext = ( new RawContextKey("installedExtensions", false));
const SearchInstalledExtensionsContext = ( new RawContextKey("searchInstalledExtensions", false));
const SearchRecentlyUpdatedExtensionsContext = ( new RawContextKey("searchRecentlyUpdatedExtensions", false));
const SearchExtensionUpdatesContext = ( new RawContextKey("searchExtensionUpdates", false));
const SearchOutdatedExtensionsContext = ( new RawContextKey("searchOutdatedExtensions", false));
const SearchEnabledExtensionsContext = ( new RawContextKey("searchEnabledExtensions", false));
const SearchDisabledExtensionsContext = ( new RawContextKey("searchDisabledExtensions", false));
const HasInstalledExtensionsContext = ( new RawContextKey("hasInstalledExtensions", true));
const BuiltInExtensionsContext = ( new RawContextKey("builtInExtensions", false));
const SearchBuiltInExtensionsContext = ( new RawContextKey("searchBuiltInExtensions", false));
const SearchUnsupportedWorkspaceExtensionsContext = ( new RawContextKey("searchUnsupportedWorkspaceExtensions", false));
const SearchDeprecatedExtensionsContext = ( new RawContextKey("searchDeprecatedExtensions", false));
const SearchRestartRequiredExtensionsContext = ( new RawContextKey("searchRestartRequiredExtensions", false));
const RecommendedExtensionsContext = ( new RawContextKey("recommendedExtensions", false));
const SortByUpdateDateContext = ( new RawContextKey("sortByUpdateDate", false));
const ExtensionsSearchValueContext = ( new RawContextKey("extensionsSearchValue", ""));
const REMOTE_CATEGORY = ( localize2(10070, "Remote"));
let ExtensionsViewletViewsContribution = class ExtensionsViewletViewsContribution extends Disposable {
    constructor(extensionManagementServerService, labelService, contextKeyService) {
        super();
        this.extensionManagementServerService = extensionManagementServerService;
        this.labelService = labelService;
        this.contextKeyService = contextKeyService;
        this.container = ( Registry.as(Extensions.ViewContainersRegistry)).get(VIEWLET_ID);
        this.registerViews();
    }
    registerViews() {
        const viewDescriptors = [];
        viewDescriptors.push(...this.createDefaultExtensionsViewDescriptors());
        viewDescriptors.push(...this.createSearchExtensionsViewDescriptors());
        viewDescriptors.push(...this.createRecommendedExtensionsViewDescriptors());
        viewDescriptors.push(...this.createBuiltinExtensionsViewDescriptors());
        viewDescriptors.push(...this.createUnsupportedWorkspaceExtensionsViewDescriptors());
        viewDescriptors.push(...this.createOtherLocalFilteredExtensionsViewDescriptors());
        viewDescriptors.push({
            id: "workbench.views.extensions.marketplaceAccess",
            name: ( localize2(10071, "Marketplace")),
            ctorDescriptor: ( new SyncDescriptor(class extends ViewPane {
                shouldShowWelcome() {
                    return true;
                }
            })),
            when: ( ContextKeyExpr.and(( ContextKeyExpr.or(( ContextKeyExpr.has("searchMarketplaceExtensions")), ( ContextKeyExpr.and(DefaultViewsContext)))), ( ContextKeyExpr.or(( CONTEXT_EXTENSIONS_GALLERY_STATUS.isEqualTo(ExtensionGalleryManifestStatus.RequiresSignIn)), ( CONTEXT_EXTENSIONS_GALLERY_STATUS.isEqualTo(ExtensionGalleryManifestStatus.AccessDenied)))))),
            order: -1
        });
        const viewRegistry = ( Registry.as(Extensions.ViewsRegistry));
        viewRegistry.registerViews(viewDescriptors, this.container);
        viewRegistry.registerViewWelcomeContent("workbench.views.extensions.marketplaceAccess", {
            content: ( localize(
                10072,
                "[Sign in to access Extensions Marketplace]({0})",
                `command:${DEFAULT_ACCOUNT_SIGN_IN_COMMAND}`
            )),
            when: ( CONTEXT_EXTENSIONS_GALLERY_STATUS.isEqualTo(ExtensionGalleryManifestStatus.RequiresSignIn))
        });
        viewRegistry.registerViewWelcomeContent("workbench.views.extensions.marketplaceAccess", {
            content: ( localize(
                10073,
                "Your account does not have access to the Extensions Marketplace. Please contact your administrator."
            )),
            when: ( CONTEXT_EXTENSIONS_GALLERY_STATUS.isEqualTo(ExtensionGalleryManifestStatus.AccessDenied))
        });
    }
    createDefaultExtensionsViewDescriptors() {
        const viewDescriptors = [];
        const servers = [];
        if (this.extensionManagementServerService.localExtensionManagementServer) {
            servers.push(this.extensionManagementServerService.localExtensionManagementServer);
        }
        if (this.extensionManagementServerService.remoteExtensionManagementServer) {
            servers.push(this.extensionManagementServerService.remoteExtensionManagementServer);
        }
        if (this.extensionManagementServerService.webExtensionManagementServer) {
            servers.push(this.extensionManagementServerService.webExtensionManagementServer);
        }
        const getViewName = (viewTitle, server) => {
            return servers.length > 1 ? `${server.label} - ${viewTitle}` : viewTitle;
        };
        let installedWebExtensionsContextChangeEvent = Event.None;
        if (this.extensionManagementServerService.webExtensionManagementServer && this.extensionManagementServerService.remoteExtensionManagementServer) {
            const interestingContextKeys = ( new Set());
            interestingContextKeys.add("hasInstalledWebExtensions");
            installedWebExtensionsContextChangeEvent = Event.filter(
                this.contextKeyService.onDidChangeContext,
                e => e.affectsSome(interestingContextKeys)
            );
        }
        const serverLabelChangeEvent = Event.any(
            this.labelService.onDidChangeFormatters,
            installedWebExtensionsContextChangeEvent
        );
        for (const server of servers) {
            const getInstalledViewName = () => getViewName(( localize(10074, "Installed")), server);
            const onDidChangeTitle = ( Event.map(serverLabelChangeEvent, () => getInstalledViewName()));
            const id = servers.length > 1 ? `workbench.views.extensions.${server.id}.installed` : `workbench.views.extensions.installed`;
            viewDescriptors.push({
                id,
                get name() {
                    return {
                        value: getInstalledViewName(),
                        original: getViewName("Installed", server)
                    };
                },
                weight: 100,
                order: 1,
                when: ( ContextKeyExpr.and(DefaultViewsContext)),
                ctorDescriptor: ( new SyncDescriptor(ServerInstalledExtensionsView, [{
                    server,
                    flexibleHeight: true,
                    onDidChangeTitle
                }])),
                canToggleVisibility: servers.length === 1
            });
            if (server === this.extensionManagementServerService.remoteExtensionManagementServer && this.extensionManagementServerService.localExtensionManagementServer) {
                this._register(
                    registerAction2(class InstallLocalExtensionsInRemoteAction2 extends Action2 {
                        constructor() {
                            super({
                                id: "workbench.extensions.installLocalExtensions",
                                get title() {
                                    return localize2(10075, "Install Local Extensions in '{0}'...", server.label);
                                },
                                category: REMOTE_CATEGORY,
                                icon: installLocalInRemoteIcon,
                                f1: true,
                                menu: {
                                    id: MenuId.ViewTitle,
                                    when: ( ContextKeyExpr.equals("view", id)),
                                    group: "navigation"
                                }
                            });
                        }
                        run(accessor) {
                            return accessor.get(IInstantiationService).createInstance(InstallLocalExtensionsInRemoteAction).run();
                        }
                    })
                );
            }
        }
        if (this.extensionManagementServerService.localExtensionManagementServer && this.extensionManagementServerService.remoteExtensionManagementServer) {
            this._register(
                registerAction2(class InstallRemoteExtensionsInLocalAction2 extends Action2 {
                    constructor() {
                        super({
                            id: "workbench.extensions.actions.installLocalExtensionsInRemote",
                            title: ( localize2(10076, "Install Remote Extensions Locally...")),
                            category: REMOTE_CATEGORY,
                            f1: true
                        });
                    }
                    run(accessor) {
                        return accessor.get(IInstantiationService).createInstance(
                            InstallRemoteExtensionsInLocalAction,
                            "workbench.extensions.actions.installLocalExtensionsInRemote"
                        ).run();
                    }
                })
            );
        }
        viewDescriptors.push({
            id: "workbench.views.extensions.popular",
            name: ( localize2(10077, "Popular")),
            ctorDescriptor: ( new SyncDescriptor(DefaultPopularExtensionsView, [{
                hideBadge: true
            }])),
            when: ( ContextKeyExpr.and(
                DefaultViewsContext,
                ContextKeyExpr.not("hasInstalledExtensions"),
                CONTEXT_HAS_GALLERY
            )),
            weight: 60,
            order: 2,
            canToggleVisibility: false
        });
        viewDescriptors.push({
            id: "extensions.recommendedList",
            name: ( localize2(10078, "Recommended")),
            ctorDescriptor: ( new SyncDescriptor(DefaultRecommendedExtensionsView, [{
                flexibleHeight: true
            }])),
            when: ( ContextKeyExpr.and(DefaultViewsContext, ( SortByUpdateDateContext.negate()), ContextKeyExpr.not("config.extensions.showRecommendationsOnlyOnDemand"), CONTEXT_HAS_GALLERY)),
            weight: 40,
            order: 3,
            canToggleVisibility: true
        });
        if (servers.length === 1) {
            viewDescriptors.push({
                id: "workbench.views.extensions.enabled",
                name: ( localize2(10079, "Enabled")),
                ctorDescriptor: ( new SyncDescriptor(EnabledExtensionsView, [{}])),
                when: ( ContextKeyExpr.and(DefaultViewsContext, ( ContextKeyExpr.has("hasInstalledExtensions")))),
                hideByDefault: true,
                weight: 40,
                order: 4,
                canToggleVisibility: true
            });
            viewDescriptors.push({
                id: "workbench.views.extensions.disabled",
                name: ( localize2(10080, "Disabled")),
                ctorDescriptor: ( new SyncDescriptor(DisabledExtensionsView, [{}])),
                when: ( ContextKeyExpr.and(DefaultViewsContext, ( ContextKeyExpr.has("hasInstalledExtensions")))),
                hideByDefault: true,
                weight: 10,
                order: 5,
                canToggleVisibility: true
            });
        }
        return viewDescriptors;
    }
    createSearchExtensionsViewDescriptors() {
        const viewDescriptors = [];
        viewDescriptors.push({
            id: "workbench.views.extensions.marketplace",
            name: ( localize2(10071, "Marketplace")),
            ctorDescriptor: ( new SyncDescriptor(SearchMarketplaceExtensionsView, [{}])),
            when: ( ContextKeyExpr.and(( ContextKeyExpr.has("searchMarketplaceExtensions")), CONTEXT_HAS_GALLERY))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.searchInstalled",
            name: ( localize2(10074, "Installed")),
            ctorDescriptor: ( new SyncDescriptor(ExtensionsListView, [{}])),
            when: ( ContextKeyExpr.or(( ContextKeyExpr.has("searchInstalledExtensions")), ( ContextKeyExpr.has("installedExtensions"))))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.searchRecentlyUpdated",
            name: ( localize2(10081, "Recently Updated")),
            ctorDescriptor: ( new SyncDescriptor(RecentlyUpdatedExtensionsView, [{}])),
            when: ( ContextKeyExpr.or(SearchExtensionUpdatesContext, ( ContextKeyExpr.has("searchRecentlyUpdatedExtensions")))),
            order: 2
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.searchEnabled",
            name: ( localize2(10082, "Enabled")),
            ctorDescriptor: ( new SyncDescriptor(ExtensionsListView, [{}])),
            when: ( ContextKeyExpr.and(( ContextKeyExpr.has("searchEnabledExtensions"))))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.searchDisabled",
            name: ( localize2(10083, "Disabled")),
            ctorDescriptor: ( new SyncDescriptor(ExtensionsListView, [{}])),
            when: ( ContextKeyExpr.and(( ContextKeyExpr.has("searchDisabledExtensions"))))
        });
        viewDescriptors.push({
            id: OUTDATED_EXTENSIONS_VIEW_ID,
            name: ( localize2(10084, "Available Updates")),
            ctorDescriptor: ( new SyncDescriptor(OutdatedExtensionsView, [{}])),
            when: ( ContextKeyExpr.or(SearchExtensionUpdatesContext, ( ContextKeyExpr.has("searchOutdatedExtensions")))),
            order: 1
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.searchBuiltin",
            name: ( localize2(10085, "Builtin")),
            ctorDescriptor: ( new SyncDescriptor(ExtensionsListView, [{}])),
            when: ( ContextKeyExpr.and(( ContextKeyExpr.has("searchBuiltInExtensions"))))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.searchWorkspaceUnsupported",
            name: ( localize2(10086, "Workspace Unsupported")),
            ctorDescriptor: ( new SyncDescriptor(ExtensionsListView, [{}])),
            when: ( ContextKeyExpr.and(( ContextKeyExpr.has("searchWorkspaceUnsupportedExtensions"))))
        });
        return viewDescriptors;
    }
    createRecommendedExtensionsViewDescriptors() {
        const viewDescriptors = [];
        viewDescriptors.push({
            id: WORKSPACE_RECOMMENDATIONS_VIEW_ID,
            name: ( localize2(10087, "Workspace Recommendations")),
            ctorDescriptor: ( new SyncDescriptor(WorkspaceRecommendedExtensionsView, [{}])),
            when: ( ContextKeyExpr.and(( ContextKeyExpr.has("recommendedExtensions")), ( WorkbenchStateContext.notEqualsTo("empty")))),
            order: 1
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.otherRecommendations",
            name: ( localize2(10088, "Other Recommendations")),
            ctorDescriptor: ( new SyncDescriptor(RecommendedExtensionsView, [{}])),
            when: ( ContextKeyExpr.has("recommendedExtensions")),
            order: 2
        });
        return viewDescriptors;
    }
    createBuiltinExtensionsViewDescriptors() {
        const viewDescriptors = [];
        const configuredCategories = ["themes", "programming languages"];
        const otherCategories = EXTENSION_CATEGORIES.filter(c => !configuredCategories.includes(c.toLowerCase()));
        otherCategories.push(NONE_CATEGORY);
        const otherCategoriesQuery = `${( otherCategories.map(c => `category:"${c}"`)).join(" ")} ${( configuredCategories.map(c => `category:"-${c}"`)).join(" ")}`;
        viewDescriptors.push({
            id: "workbench.views.extensions.builtinFeatureExtensions",
            name: ( localize2(10089, "Features")),
            ctorDescriptor: ( new SyncDescriptor(StaticQueryExtensionsView, [{
                query: `@builtin ${otherCategoriesQuery}`
            }])),
            when: ( ContextKeyExpr.has("builtInExtensions"))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.builtinThemeExtensions",
            name: ( localize2(10090, "Themes")),
            ctorDescriptor: ( new SyncDescriptor(StaticQueryExtensionsView, [{
                query: `@builtin category:themes`
            }])),
            when: ( ContextKeyExpr.has("builtInExtensions"))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.builtinProgrammingLanguageExtensions",
            name: ( localize2(10091, "Programming Languages")),
            ctorDescriptor: ( new SyncDescriptor(StaticQueryExtensionsView, [{
                query: `@builtin category:"programming languages"`
            }])),
            when: ( ContextKeyExpr.has("builtInExtensions"))
        });
        return viewDescriptors;
    }
    createUnsupportedWorkspaceExtensionsViewDescriptors() {
        const viewDescriptors = [];
        viewDescriptors.push({
            id: "workbench.views.extensions.untrustedUnsupportedExtensions",
            name: ( localize2(10092, "Disabled in Restricted Mode")),
            ctorDescriptor: ( new SyncDescriptor(UntrustedWorkspaceUnsupportedExtensionsView, [{}])),
            when: ( ContextKeyExpr.and(SearchUnsupportedWorkspaceExtensionsContext))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.untrustedPartiallySupportedExtensions",
            name: ( localize2(10093, "Limited in Restricted Mode")),
            ctorDescriptor: ( new SyncDescriptor(UntrustedWorkspacePartiallySupportedExtensionsView, [{}])),
            when: ( ContextKeyExpr.and(SearchUnsupportedWorkspaceExtensionsContext))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.virtualUnsupportedExtensions",
            name: ( localize2(10094, "Disabled in Virtual Workspaces")),
            ctorDescriptor: ( new SyncDescriptor(VirtualWorkspaceUnsupportedExtensionsView, [{}])),
            when: ( ContextKeyExpr.and(VirtualWorkspaceContext, SearchUnsupportedWorkspaceExtensionsContext))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.virtualPartiallySupportedExtensions",
            name: ( localize2(10095, "Limited in Virtual Workspaces")),
            ctorDescriptor: ( new SyncDescriptor(VirtualWorkspacePartiallySupportedExtensionsView, [{}])),
            when: ( ContextKeyExpr.and(VirtualWorkspaceContext, SearchUnsupportedWorkspaceExtensionsContext))
        });
        return viewDescriptors;
    }
    createOtherLocalFilteredExtensionsViewDescriptors() {
        const viewDescriptors = [];
        viewDescriptors.push({
            id: "workbench.views.extensions.deprecatedExtensions",
            name: ( localize2(10096, "Deprecated")),
            ctorDescriptor: ( new SyncDescriptor(DeprecatedExtensionsView, [{}])),
            when: ( ContextKeyExpr.and(SearchDeprecatedExtensionsContext))
        });
        viewDescriptors.push({
            id: "workbench.views.extensions.restartRequired",
            name: ( localize2(10097, "Restart Required")),
            ctorDescriptor: ( new SyncDescriptor(ExtensionsListView, [{}])),
            when: ( ContextKeyExpr.and(SearchRestartRequiredExtensionsContext))
        });
        return viewDescriptors;
    }
};
ExtensionsViewletViewsContribution = ( __decorate([( __param(0, IExtensionManagementServerService)), ( __param(1, ILabelService)), ( __param(2, IContextKeyService))], ExtensionsViewletViewsContribution));
let ExtensionsViewPaneContainer = class ExtensionsViewPaneContainer extends ViewPaneContainer {
    constructor(
        layoutService,
        telemetryService,
        progressService,
        instantiationService,
        editorGroupService,
        extensionGalleryManifestService,
        extensionsWorkbenchService,
        extensionManagementServerService,
        notificationService,
        paneCompositeService,
        themeService,
        configurationService,
        storageService,
        contextService,
        contextKeyService,
        contextMenuService,
        extensionService,
        viewDescriptorService,
        preferencesService,
        commandService,
        logService,
        openerService
    ) {
        super(VIEWLET_ID, {
            mergeViewWithContainerWhenSingleView: true
        }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService, logService);
        this.progressService = progressService;
        this.editorGroupService = editorGroupService;
        this.extensionsWorkbenchService = extensionsWorkbenchService;
        this.extensionManagementServerService = extensionManagementServerService;
        this.notificationService = notificationService;
        this.paneCompositeService = paneCompositeService;
        this.contextKeyService = contextKeyService;
        this.preferencesService = preferencesService;
        this.commandService = commandService;
        this.openerService = openerService;
        this.extensionGalleryManifest = null;
        this.notificationDisposables = this._register(( new MutableDisposable()));
        this.searchDelayer = this._register(( new Delayer(500)));
        this.extensionsSearchValueContextKey = ExtensionsSearchValueContext.bindTo(contextKeyService);
        this.defaultViewsContextKey = DefaultViewsContext.bindTo(contextKeyService);
        this.sortByContextKey = ExtensionsSortByContext.bindTo(contextKeyService);
        this.searchMarketplaceExtensionsContextKey = SearchMarketplaceExtensionsContext.bindTo(contextKeyService);
        this.searchMcpServersContextKey = SearchMcpServersContext.bindTo(contextKeyService);
        this.searchAgentPluginsContextKey = SearchAgentPluginsContext.bindTo(contextKeyService);
        this.searchHasTextContextKey = SearchHasTextContext.bindTo(contextKeyService);
        this.sortByUpdateDateContextKey = SortByUpdateDateContext.bindTo(contextKeyService);
        this.installedExtensionsContextKey = InstalledExtensionsContext.bindTo(contextKeyService);
        this.searchInstalledExtensionsContextKey = SearchInstalledExtensionsContext.bindTo(contextKeyService);
        this.searchRecentlyUpdatedExtensionsContextKey = SearchRecentlyUpdatedExtensionsContext.bindTo(contextKeyService);
        this.searchExtensionUpdatesContextKey = SearchExtensionUpdatesContext.bindTo(contextKeyService);
        this.searchWorkspaceUnsupportedExtensionsContextKey = SearchUnsupportedWorkspaceExtensionsContext.bindTo(contextKeyService);
        this.searchDeprecatedExtensionsContextKey = SearchDeprecatedExtensionsContext.bindTo(contextKeyService);
        this.searchRestartRequiredExtensionsContextKey = SearchRestartRequiredExtensionsContext.bindTo(contextKeyService);
        this.searchOutdatedExtensionsContextKey = SearchOutdatedExtensionsContext.bindTo(contextKeyService);
        this.searchEnabledExtensionsContextKey = SearchEnabledExtensionsContext.bindTo(contextKeyService);
        this.searchDisabledExtensionsContextKey = SearchDisabledExtensionsContext.bindTo(contextKeyService);
        this.hasInstalledExtensionsContextKey = HasInstalledExtensionsContext.bindTo(contextKeyService);
        this.builtInExtensionsContextKey = BuiltInExtensionsContext.bindTo(contextKeyService);
        this.searchBuiltInExtensionsContextKey = SearchBuiltInExtensionsContext.bindTo(contextKeyService);
        this.recommendedExtensionsContextKey = RecommendedExtensionsContext.bindTo(contextKeyService);
        this._register(this.paneCompositeService.onDidPaneCompositeOpen(e => {
            if (e.viewContainerLocation === ViewContainerLocation.Sidebar) {
                this.onViewletOpen(e.composite);
            }
        }, this));
        this._register(extensionsWorkbenchService.onReset(() => this.refresh()));
        this.searchViewletState = this.getMemento(StorageScope.WORKSPACE, StorageTarget.MACHINE);
        extensionGalleryManifestService.getExtensionGalleryManifest().then(galleryManifest => {
            this.extensionGalleryManifest = galleryManifest;
            this._register(
                extensionGalleryManifestService.onDidChangeExtensionGalleryManifest(galleryManifest => {
                    this.extensionGalleryManifest = galleryManifest;
                    this.refresh();
                })
            );
        });
    }
    get searchValue() {
        return this.searchBox?.getValue();
    }
    create(parent) {
        parent.classList.add("extensions-viewlet");
        this.root = parent;
        const overlay = append(this.root, $(".overlay"));
        const overlayBackgroundColor = this.getColor(SIDE_BAR_DRAG_AND_DROP_BACKGROUND) ?? "";
        overlay.style.backgroundColor = overlayBackgroundColor;
        hide(overlay);
        this.header = append(this.root, $(".header"));
        const placeholder = ( localize(10098, "Search Extensions in Marketplace"));
        const searchValue = this.searchViewletState["query.value"] ? this.searchViewletState["query.value"] : "";
        const searchContainer = append(this.header, $(".extensions-search-container"));
        this.searchBox = this._register(
            this.instantiationService.createInstance(SuggestEnabledInput, `${VIEWLET_ID}.searchbox`, searchContainer, {
                triggerCharacters: ["@"],
                sortKey: item => {
                    if (item.indexOf(":") === -1) {
                        return "a";
                    } else if (/ext:/.test(item) || /id:/.test(item) || /tag:/.test(item)) {
                        return "b";
                    } else if (/sort:/.test(item)) {
                        return "c";
                    } else {
                        return "d";
                    }
                },
                provideResults: query => Query.suggestions(query, this.extensionGalleryManifest)
            }, placeholder, "extensions:searchinput", {
                placeholderText: placeholder,
                value: searchValue
            })
        );
        this.notificationContainer = append(this.header, $(".notification-container.hidden", {
            "tabindex": "0"
        }));
        this.renderNotificaiton();
        this._register(
            this.extensionsWorkbenchService.onDidChangeExtensionsNotification(() => this.renderNotificaiton())
        );
        this.updateInstalledExtensionsContexts();
        if (this.searchBox.getValue()) {
            this.triggerSearch();
        }
        this._register(this.searchBox.onInputDidChange(() => {
            this.sortByContextKey.set(Query.parse(this.searchBox?.getValue() ?? "").sortBy);
            this.triggerSearch();
        }, this));
        this._register(this.searchBox.onShouldFocusResults(() => this.focusListView(), this));
        const controlElement = append(searchContainer, $(".extensions-search-actions-container"));
        this._register(
            this.instantiationService.createInstance(MenuWorkbenchToolBar, controlElement, extensionsSearchActionsMenu, {
                toolbarOptions: {
                    primaryGroup: () => true
                },
                actionViewItemProvider: (action, options) => createActionViewItem(this.instantiationService, action, options)
            })
        );
        this._register(new DragAndDropObserver(this.root, {
            onDragEnter: e => {
                if (this.isSupportedDragElement(e)) {
                    show(overlay);
                }
            },
            onDragLeave: e => {
                if (this.isSupportedDragElement(e)) {
                    hide(overlay);
                }
            },
            onDragOver: e => {
                if (this.isSupportedDragElement(e)) {
                    e.dataTransfer.dropEffect = "copy";
                }
            },
            onDrop: async e => {
                if (this.isSupportedDragElement(e)) {
                    hide(overlay);
                    const vsixs = coalesce(( (await this.instantiationService.invokeFunction(accessor => extractEditorsAndFilesDropData(accessor, e))).map(
                        editor => editor.resource && extname(editor.resource) === ".vsix" ? editor.resource : undefined
                    )));
                    if (vsixs.length > 0) {
                        try {
                            await this.commandService.executeCommand(INSTALL_EXTENSION_FROM_VSIX_COMMAND_ID, vsixs);
                        } catch (err) {
                            this.notificationService.error(err);
                        }
                    }
                }
            }
        }));
        super.create(append(this.root, $(".extensions")));
        const focusTracker = this._register(trackFocus(this.root));
        const isSearchBoxFocused = () => this.searchBox?.inputWidget.hasWidgetFocus();
        this._register(registerNavigableContainer({
            name: "extensionsView",
            focusNotifiers: [focusTracker],
            focusNextWidget: () => {
                if (isSearchBoxFocused()) {
                    this.focusListView();
                }
            },
            focusPreviousWidget: () => {
                if (!isSearchBoxFocused()) {
                    this.searchBox?.focus();
                }
            }
        }));
    }
    focus() {
        super.focus();
        this.searchBox?.focus();
    }
    layout(dimension) {
        this._dimension = dimension;
        if (this.root) {
            this.root.classList.toggle("narrow", dimension.width <= 250);
            this.root.classList.toggle("mini", dimension.width <= 200);
        }
        this.searchBox?.layout(( new Dimension(dimension.width - 34 -  8 - (24 * 2), 20)));
        const searchBoxHeight = 20 + 21 ;
        const headerHeight = this.header && !!this.notificationContainer?.childNodes.length ? this.notificationContainer.clientHeight + searchBoxHeight + 10  : searchBoxHeight;
        this.header.style.height = `${headerHeight}px`;
        super.layout(( new Dimension(dimension.width, dimension.height - headerHeight)));
    }
    getOptimalWidth() {
        return 400;
    }
    search(value) {
        if (this.searchBox && this.searchBox.getValue() !== value) {
            this.searchBox.setValue(value);
        }
    }
    async refresh() {
        await this.updateInstalledExtensionsContexts();
        this.doSearch(true);
        if (this.configurationService.getValue(AutoCheckUpdatesConfigurationKey)) {
            this.extensionsWorkbenchService.checkForUpdates();
        }
    }
    renderNotificaiton() {
        if (!this.notificationContainer) {
            return;
        }
        clearNode(this.notificationContainer);
        this.notificationDisposables.value = ( new DisposableStore());
        const status = this.extensionsWorkbenchService.getExtensionsNotification();
        const query = status?.query ?? status?.extensions.map(extension => `@id:${extension.identifier.id}`).join(" ");
        if (status && (query === this.searchBox?.getValue() || !this.searchMarketplaceExtensionsContextKey.get())) {
            const messagePlainText = isMarkdownString(status.message) ? renderAsPlaintext(status.message) : status.message;
            this.notificationContainer.setAttribute("aria-label", messagePlainText);
            this.notificationContainer.classList.remove("hidden");
            const messageContainer = append(this.notificationContainer, $(".message-container"));
            append(messageContainer, $("span")).className = SeverityIcon.className(status.severity);
            const messageText = append(messageContainer, $("span.message-text"));
            const messageElement = append(messageText, $("span.message"));
            if (isMarkdownString(status.message)) {
                const isTrusted = status.message.isTrusted;
                const allowCommands = typeof isTrusted === "object" ? isTrusted.enabledCommands : !!isTrusted;
                this.notificationDisposables.value.add(renderMarkdown(status.message, {
                    actionHandler: link => {
                        this.openerService.open(link, {
                            allowCommands
                        });
                    }
                }, messageElement));
            } else {
                messageElement.textContent = status.message;
            }
            if (status.extensions.length) {
                const showAction = append(messageText, $("span.message-text-action", {
                    "tabindex": "0",
                    "role": "button",
                    "aria-label": `${messagePlainText}. ${( localize(10099, "Click to Show"))}`
                }, ( localize(10100, "Show"))));
                this.notificationDisposables.value.add(
                    addDisposableListener(showAction, EventType.CLICK, () => this.search(query ?? ""))
                );
                this.notificationDisposables.value.add(addDisposableListener(showAction, EventType.KEY_DOWN, e => {
                    const standardKeyboardEvent = ( new StandardKeyboardEvent(e));
                    if (standardKeyboardEvent.keyCode === KeyCode.Enter || standardKeyboardEvent.keyCode === KeyCode.Space) {
                        this.search(query ?? "");
                    }
                    standardKeyboardEvent.stopPropagation();
                }));
            }
            const actionsContainer = append(this.notificationContainer, $(".notification-actions"));
            if (status.action) {
                const actionButton = append(actionsContainer, $("span.message-action-button", {
                    "tabindex": "0",
                    "role": "button",
                    "aria-label": status.action.label
                }, status.action.label));
                this.notificationDisposables.value.add(addDisposableListener(actionButton, EventType.CLICK, () => {
                    Promise.resolve(status.action.run()).catch(error => this.notificationService.error(error));
                }));
                this.notificationDisposables.value.add(addDisposableListener(actionButton, EventType.KEY_DOWN, e => {
                    const standardKeyboardEvent = ( new StandardKeyboardEvent(e));
                    if (standardKeyboardEvent.keyCode === KeyCode.Enter || standardKeyboardEvent.keyCode === KeyCode.Space) {
                        Promise.resolve(status.action.run()).catch(error => this.notificationService.error(error));
                    }
                    standardKeyboardEvent.stopPropagation();
                }));
            }
            const dismiss = status.dismiss;
            if (dismiss) {
                const dismissLabel = ( localize(10101, "Dismiss"));
                const dismissButton = append(actionsContainer, $("span.dismiss-action.codicon.codicon-close", {
                    "tabindex": "0",
                    "role": "button",
                    "aria-label": dismissLabel,
                    "title": dismissLabel
                }));
                this.notificationDisposables.value.add(addDisposableListener(dismissButton, EventType.CLICK, () => dismiss()));
                this.notificationDisposables.value.add(addDisposableListener(dismissButton, EventType.KEY_DOWN, e => {
                    const standardKeyboardEvent = ( new StandardKeyboardEvent(e));
                    if (standardKeyboardEvent.keyCode === KeyCode.Enter || standardKeyboardEvent.keyCode === KeyCode.Space) {
                        dismiss();
                    }
                    standardKeyboardEvent.stopPropagation();
                }));
            }
        } else {
            this.notificationContainer.removeAttribute("aria-label");
            this.notificationContainer.classList.add("hidden");
            if (this.searchBox && ExtensionsListView.isRestartRequiredQuery(this.searchBox.getValue())) {
                this.search("");
            }
        }
        if (this._dimension) {
            this.layout(this._dimension);
        }
    }
    async updateInstalledExtensionsContexts() {
        const result = await this.extensionsWorkbenchService.queryLocal();
        this.hasInstalledExtensionsContextKey.set(( result.some(r => !r.isBuiltin)));
    }
    triggerSearch() {
        this.searchDelayer.trigger(
            () => this.doSearch(),
            this.searchBox && this.searchBox.getValue() ? 500 : 0
        ).then(undefined, err => this.onError(err));
    }
    normalizedQuery() {
        return this.searchBox ? this.searchBox.getValue().trim().replace(/@category/g, "category").replace(/@tag:/g, "tag:").replace(/@ext:/g, "ext:").replace(/@featured/g, "featured").replace(
            /@popular/g,
            this.extensionManagementServerService.webExtensionManagementServer && !this.extensionManagementServerService.localExtensionManagementServer && !this.extensionManagementServerService.remoteExtensionManagementServer ? "@web" : "@popular"
        ) : "";
    }
    saveState() {
        const value = this.searchBox ? this.searchBox.getValue() : "";
        if (ExtensionsListView.isLocalExtensionsQuery(value)) {
            this.searchViewletState["query.value"] = value;
        } else {
            this.searchViewletState["query.value"] = "";
        }
        super.saveState();
    }
    doSearch(refresh) {
        const value = this.normalizedQuery();
        this.contextKeyService.bufferChangeEvents(() => {
            const isRecommendedExtensionsQuery = ExtensionsListView.isRecommendedExtensionsQuery(value);
            this.searchHasTextContextKey.set(value.trim() !== "");
            this.extensionsSearchValueContextKey.set(value);
            this.installedExtensionsContextKey.set(ExtensionsListView.isInstalledExtensionsQuery(value));
            this.searchInstalledExtensionsContextKey.set(ExtensionsListView.isSearchInstalledExtensionsQuery(value));
            this.searchRecentlyUpdatedExtensionsContextKey.set(
                ExtensionsListView.isSearchRecentlyUpdatedQuery(value) && !ExtensionsListView.isSearchExtensionUpdatesQuery(value)
            );
            this.searchOutdatedExtensionsContextKey.set(
                ExtensionsListView.isOutdatedExtensionsQuery(value) && !ExtensionsListView.isSearchExtensionUpdatesQuery(value)
            );
            this.searchExtensionUpdatesContextKey.set(ExtensionsListView.isSearchExtensionUpdatesQuery(value));
            this.searchEnabledExtensionsContextKey.set(ExtensionsListView.isEnabledExtensionsQuery(value));
            this.searchDisabledExtensionsContextKey.set(ExtensionsListView.isDisabledExtensionsQuery(value));
            this.searchBuiltInExtensionsContextKey.set(ExtensionsListView.isSearchBuiltInExtensionsQuery(value));
            this.searchWorkspaceUnsupportedExtensionsContextKey.set(ExtensionsListView.isSearchWorkspaceUnsupportedExtensionsQuery(value));
            this.searchDeprecatedExtensionsContextKey.set(ExtensionsListView.isSearchDeprecatedExtensionsQuery(value));
            this.searchRestartRequiredExtensionsContextKey.set(ExtensionsListView.isRestartRequiredQuery(value));
            this.builtInExtensionsContextKey.set(ExtensionsListView.isBuiltInExtensionsQuery(value));
            this.recommendedExtensionsContextKey.set(isRecommendedExtensionsQuery);
            this.searchMcpServersContextKey.set(!!value && /@mcp\s?.*/i.test(value));
            this.searchAgentPluginsContextKey.set(!!value && /@agentPlugins\s?.*/i.test(value));
            this.searchMarketplaceExtensionsContextKey.set(
                !!value && !ExtensionsListView.isLocalExtensionsQuery(value) && !isRecommendedExtensionsQuery && !this.searchMcpServersContextKey.get() && !this.searchAgentPluginsContextKey.get()
            );
            this.sortByUpdateDateContextKey.set(ExtensionsListView.isSortUpdateDateQuery(value));
            this.defaultViewsContextKey.set(!value || ExtensionsListView.isSortInstalledExtensionsQuery(value));
        });
        this.renderNotificaiton();
        return this.showExtensionsViews(this.panes);
    }
    onDidAddViewDescriptors(added) {
        const addedViews = super.onDidAddViewDescriptors(added);
        this.showExtensionsViews(addedViews);
        return addedViews;
    }
    async showExtensionsViews(views) {
        await this.progress(Promise.all(( views.map(async view => {
            if (view instanceof AbstractExtensionsListView) {
                const model = await view.show(this.normalizedQuery());
                this.alertSearchResult(model.length, view.id);
            }
        }))));
    }
    alertSearchResult(count, viewId) {
        const view = this.viewContainerModel.visibleViewDescriptors.find(view => view.id === viewId);
        switch (count) {
        case 0:
            break;
        case 1:
            if (view) {
                alert(( localize(10102, "1 extension found in the {0} section.", view.name.value)));
            } else {
                alert(( localize(10103, "1 extension found.")));
            }
            break;
        default:
            if (view) {
                alert(( localize(10104, "{0} extensions found in the {1} section.", count, view.name.value)));
            } else {
                alert(( localize(10105, "{0} extensions found.", count)));
            }
            break;
        }
    }
    getFirstExpandedPane() {
        for (const pane of this.panes) {
            if (pane.isExpanded() && pane instanceof ExtensionsListView) {
                return pane;
            }
        }
        return undefined;
    }
    focusListView() {
        const pane = this.getFirstExpandedPane();
        if (pane && pane.count() > 0) {
            pane.focus();
        }
    }
    onViewletOpen(viewlet) {
        if (!viewlet || viewlet.getId() === VIEWLET_ID) {
            return;
        }
        if (this.configurationService.getValue(CloseExtensionDetailsOnViewChangeKey)) {
            const promises = ( this.editorGroupService.groups.map(group => {
                const editors = group.editors.filter(input => input instanceof ExtensionsInput);
                return group.closeEditors(editors);
            }));
            Promise.all(promises);
        }
    }
    progress(promise) {
        return this.progressService.withProgress({
            location: ProgressLocation.Extensions
        }, () => promise);
    }
    onError(err) {
        if (isCancellationError(err)) {
            return;
        }
        const message = err && err.message || "";
        if (/ECONNREFUSED/.test(message)) {
            const error = createErrorWithActions(( localize(
                10106,
                "Marketplace returned 'ECONNREFUSED'. Please check the 'http.proxy' setting."
            )), [( new Action("open user settings", ( localize(10107, "Open User Settings")), undefined, true, () => this.preferencesService.openUserSettings()))]);
            this.notificationService.error(error);
            return;
        }
        this.notificationService.error(err);
    }
    isSupportedDragElement(e) {
        if (e.dataTransfer) {
            const typesLowerCase = ( e.dataTransfer.types.map(t => t.toLocaleLowerCase()));
            return typesLowerCase.indexOf("files") !== -1;
        }
        return false;
    }
};
ExtensionsViewPaneContainer = ( __decorate([( __param(0, IWorkbenchLayoutService)), ( __param(1, ITelemetryService)), ( __param(2, IProgressService)), ( __param(3, IInstantiationService)), ( __param(4, IEditorGroupsService)), ( __param(5, IExtensionGalleryManifestService)), ( __param(6, IExtensionsWorkbenchService)), ( __param(7, IExtensionManagementServerService)), ( __param(8, INotificationService)), ( __param(9, IPaneCompositePartService)), ( __param(10, IThemeService)), ( __param(11, IConfigurationService)), ( __param(12, IStorageService)), ( __param(13, IWorkspaceContextService)), ( __param(14, IContextKeyService)), ( __param(15, IContextMenuService)), ( __param(16, IExtensionService)), ( __param(17, IViewDescriptorService)), ( __param(18, IPreferencesService)), ( __param(19, ICommandService)), ( __param(20, ILogService)), ( __param(21, IOpenerService))], ExtensionsViewPaneContainer));
let StatusUpdater = class StatusUpdater extends Disposable {
    constructor(
        activityService,
        extensionsWorkbenchService,
        extensionEnablementService,
        configurationService
    ) {
        super();
        this.activityService = activityService;
        this.extensionsWorkbenchService = extensionsWorkbenchService;
        this.extensionEnablementService = extensionEnablementService;
        this.configurationService = configurationService;
        this.badgeHandle = this._register(( new MutableDisposable()));
        this.onServiceChange();
        this._register(Event.any(Event.debounce(
            extensionsWorkbenchService.onChange,
            () => undefined,
            100,
            undefined,
            undefined,
            undefined,
            this._store
        ), extensionsWorkbenchService.onDidChangeExtensionsNotification)(this.onServiceChange, this));
    }
    onServiceChange() {
        this.badgeHandle.clear();
        let badge;
        const extensionsNotification = this.extensionsWorkbenchService.getExtensionsNotification();
        if (extensionsNotification && extensionsNotification.severity === Severity$1.Warning) {
            badge = ( new WarningBadge(
                () => isMarkdownString(extensionsNotification.message) ? renderAsPlaintext(extensionsNotification.message) : extensionsNotification.message
            ));
        }
        if (!badge) {
            const actionRequired = this.configurationService.getValue(AutoRestartConfigurationKey) === true ? [] : this.extensionsWorkbenchService.installed.filter(e => e.runtimeState !== undefined);
            const outdated = this.extensionsWorkbenchService.outdated.reduce(
                (r, e) => r + (this.extensionEnablementService.isEnabled(e.local) && !actionRequired.includes(e) && !this.extensionsWorkbenchService.isAutoUpdateDelayed(e) ? 1 : 0),
                0
            );
            const newBadgeNumber = outdated + actionRequired.length;
            if (newBadgeNumber > 0) {
                let msg = "";
                if (outdated) {
                    msg += outdated === 1 ? ( localize(10108, "{0} requires update", outdated)) : ( localize(10109, "{0} require update", outdated));
                }
                if (outdated > 0 && actionRequired.length > 0) {
                    msg += ", ";
                }
                if (actionRequired.length) {
                    msg += actionRequired.length === 1 ? ( localize(10110, "{0} requires restart", actionRequired.length)) : ( localize(10111, "{0} require restart", actionRequired.length));
                }
                badge = ( new NumberBadge(newBadgeNumber, () => msg));
            }
        }
        if (badge) {
            this.badgeHandle.value = this.activityService.showViewContainerActivity(VIEWLET_ID, {
                badge
            });
        }
    }
};
StatusUpdater = ( __decorate([( __param(0, IActivityService)), ( __param(1, IExtensionsWorkbenchService)), ( __param(2, IWorkbenchExtensionEnablementService)), ( __param(3, IConfigurationService))], StatusUpdater));
let MaliciousExtensionChecker = class MaliciousExtensionChecker {
    constructor(
        extensionsManagementService,
        extensionsWorkbenchService,
        hostService,
        logService,
        notificationService,
        commandService
    ) {
        this.extensionsManagementService = extensionsManagementService;
        this.extensionsWorkbenchService = extensionsWorkbenchService;
        this.hostService = hostService;
        this.logService = logService;
        this.notificationService = notificationService;
        this.commandService = commandService;
        this.loopCheckForMaliciousExtensions();
    }
    loopCheckForMaliciousExtensions() {
        this.checkForMaliciousExtensions().then(() => timeout(1000 * 60 * 5)).then(() => this.loopCheckForMaliciousExtensions());
    }
    async checkForMaliciousExtensions() {
        try {
            const maliciousExtensions = [];
            let shouldRestartExtensions = false;
            let shouldReloadWindow = false;
            for (const extension of this.extensionsWorkbenchService.installed) {
                if (extension.isMalicious && extension.local) {
                    maliciousExtensions.push([extension.local, extension.maliciousInfoLink]);
                    shouldRestartExtensions = shouldRestartExtensions || extension.runtimeState?.action === ExtensionRuntimeActionType.RestartExtensions;
                    shouldReloadWindow = shouldReloadWindow || extension.runtimeState?.action === ExtensionRuntimeActionType.ReloadWindow;
                }
            }
            if (maliciousExtensions.length) {
                await this.extensionsManagementService.uninstallExtensions(( maliciousExtensions.map(e => ({
                    extension: e[0],
                    options: {
                        remove: true
                    }
                }))));
                for (const [extension, link] of maliciousExtensions) {
                    const buttons = [];
                    if (shouldRestartExtensions || shouldReloadWindow) {
                        buttons.push({
                            label: shouldRestartExtensions ? ( localize(10112, "Restart Extensions")) : ( localize(10113, "Reload Now")),
                            run: () => shouldRestartExtensions ? this.extensionsWorkbenchService.updateRunningExtensions() : this.hostService.reload()
                        });
                    }
                    if (link) {
                        buttons.push({
                            label: ( localize(10114, "Learn More")),
                            run: () => this.commandService.executeCommand("vscode.open", ( URI.parse(link)))
                        });
                    }
                    this.notificationService.prompt(Severity$1.Warning, ( localize(
                        10115,
                        "The extension '{0}' was found to be problematic and has been uninstalled",
                        extension.manifest.displayName || extension.identifier.id
                    )), buttons, {
                        sticky: true,
                        priority: NotificationPriority.URGENT
                    });
                }
            }
        } catch (err) {
            this.logService.error(err);
        }
    }
};
MaliciousExtensionChecker = ( __decorate([( __param(0, IExtensionManagementService)), ( __param(1, IExtensionsWorkbenchService)), ( __param(2, IHostService)), ( __param(3, ILogService)), ( __param(4, INotificationService)), ( __param(5, ICommandService))], MaliciousExtensionChecker));
let ExtensionMarketplaceStatusUpdater = class ExtensionMarketplaceStatusUpdater extends Disposable {
    constructor(activityService, extensionGalleryManifestService) {
        super();
        this.activityService = activityService;
        this.extensionGalleryManifestService = extensionGalleryManifestService;
        this.badgeHandle = this._register(( new MutableDisposable()));
        this.accountBadgeDisposable = this._register(( new MutableDisposable()));
        this.updateBadge();
        this._register(
            this.extensionGalleryManifestService.onDidChangeExtensionGalleryManifestStatus(() => this.updateBadge())
        );
    }
    async updateBadge() {
        this.badgeHandle.clear();
        const status = this.extensionGalleryManifestService.extensionGalleryManifestStatus;
        let badge;
        switch (status) {
        case ExtensionGalleryManifestStatus.RequiresSignIn:
            badge = ( new NumberBadge(1, () => ( localize(10116, "Sign in required to access marketplace"))));
            break;
        case ExtensionGalleryManifestStatus.AccessDenied:
            badge = ( new WarningBadge(() => ( localize(10117, "Access denied to marketplace"))));
            break;
        }
        if (badge) {
            this.badgeHandle.value = this.activityService.showViewContainerActivity(VIEWLET_ID, {
                badge
            });
        }
        this.accountBadgeDisposable.clear();
        if (status === ExtensionGalleryManifestStatus.RequiresSignIn) {
            const badge = ( new NumberBadge(1, () => ( localize(10118, "Sign in to access Marketplace"))));
            this.accountBadgeDisposable.value = this.activityService.showAccountsActivity({
                badge
            });
        }
    }
};
ExtensionMarketplaceStatusUpdater = ( __decorate([( __param(0, IActivityService)), ( __param(1, IExtensionGalleryManifestService))], ExtensionMarketplaceStatusUpdater));

export { BuiltInExtensionsContext, ExtensionMarketplaceStatusUpdater, ExtensionsSearchValueContext, ExtensionsSortByContext, ExtensionsViewPaneContainer, ExtensionsViewletViewsContribution, MaliciousExtensionChecker, RecommendedExtensionsContext, SearchHasTextContext, SearchMarketplaceExtensionsContext, StatusUpdater };
