"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FleetPlugin = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _public = require("@kbn/core/public");
var _i18n = require("@kbn/i18n");
var _coreHttpCommon = require("@kbn/core-http-common");
var _lodash = require("lodash");
var _public2 = require("@kbn/kibana-utils-plugin/public");
var _common = require("../common");
var _authz = require("../common/authz");
var _experimental_features = require("../common/experimental_features");
var _constants = require("../common/constants");
var _constants2 = require("./constants");
var _hooks = require("./hooks");
var _use_request = require("./hooks/use_request");
var _search_provider = require("./search_provider");
var _home_integration = require("./components/home_integration");
var _ui_extensions = require("./services/ui_extensions");
var _experimental_features2 = require("./services/experimental_features");
var _lazy_custom_logs_assets_extension = require("./lazy_custom_logs_assets_extension");
var _custom_integrations = require("./services/custom_integrations");
var _deep_links = require("./deep_links");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /*
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      * or more contributor license agreements. Licensed under the Elastic License
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      * 2.0; you may not use this file except in compliance with the Elastic License
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      * 2.0.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
// We need to provide an object instead of void so that dependent plugins know when Fleet
// is disabled.
// eslint-disable-next-line @typescript-eslint/no-empty-interface

/**
 * Describes public Fleet plugin contract returned at the `start` stage.
 */

class FleetPlugin {
  constructor(initializerContext) {
    (0, _defineProperty2.default)(this, "config", void 0);
    (0, _defineProperty2.default)(this, "kibanaVersion", void 0);
    (0, _defineProperty2.default)(this, "extensions", {});
    (0, _defineProperty2.default)(this, "experimentalFeatures", void 0);
    (0, _defineProperty2.default)(this, "storage", new _public2.Storage(localStorage));
    this.initializerContext = initializerContext;
    this.config = this.initializerContext.config.get();
    this.experimentalFeatures = (0, _experimental_features.parseExperimentalConfigValue)(this.config.enableExperimental || []);
    this.kibanaVersion = initializerContext.env.packageInfo.version;
  }
  setup(core, deps) {
    const config = this.config;
    const kibanaVersion = this.kibanaVersion;
    const extensions = this.extensions;
    (0, _custom_integrations.setCustomIntegrations)(deps.customIntegrations);

    // TODO: this is a contract leak and an issue.  We shouldn't be setting a module-level
    // variable from plugin setup.  Refactor to an abstraction, if necessary.
    // Set up http client
    (0, _use_request.setHttpClient)(core.http);

    // Register Integrations app
    core.application.register({
      id: _common.INTEGRATIONS_PLUGIN_ID,
      category: _public.DEFAULT_APP_CATEGORIES.management,
      appRoute: '/app/integrations',
      title: _i18n.i18n.translate('xpack.fleet.integrationsAppTitle', {
        defaultMessage: 'Integrations'
      }),
      order: 9019,
      euiIconType: 'logoElastic',
      mount: async params => {
        var _deps$usageCollection, _deps$usageCollection2;
        const [coreStartServices, startDepsServices, fleetStart] = await core.getStartServices();
        const cloud = deps.cloud && startDepsServices.cloud ? {
          ...deps.cloud,
          ...startDepsServices.cloud
        } : undefined;
        const startServices = {
          ...coreStartServices,
          ...startDepsServices,
          storage: this.storage,
          cloud,
          authz: await fleetStart.authz
        };
        const {
          renderApp,
          teardownIntegrations
        } = await Promise.resolve().then(() => _interopRequireWildcard(require('./applications/integrations')));
        const Tracker = (_deps$usageCollection = (_deps$usageCollection2 = deps.usageCollection) === null || _deps$usageCollection2 === void 0 ? void 0 : _deps$usageCollection2.components.ApplicationUsageTrackingProvider) !== null && _deps$usageCollection !== void 0 ? _deps$usageCollection : _react.default.Fragment;
        const unmount = renderApp(startServices, params, config, kibanaVersion, extensions, Tracker);
        return () => {
          unmount();
          teardownIntegrations(startServices);
        };
      }
    });

    // Register main Fleet app
    core.application.register({
      id: _common.PLUGIN_ID,
      category: _public.DEFAULT_APP_CATEGORIES.management,
      title: _i18n.i18n.translate('xpack.fleet.appTitle', {
        defaultMessage: 'Fleet'
      }),
      order: 9020,
      euiIconType: 'logoElastic',
      appRoute: '/app/fleet',
      deepLinks: (0, _deep_links.getFleetDeepLinks)(this.experimentalFeatures),
      mount: async params => {
        const [coreStartServices, startDepsServices, fleetStart] = await core.getStartServices();
        const cloud = deps.cloud && startDepsServices.cloud ? {
          ...deps.cloud,
          ...startDepsServices.cloud
        } : undefined;
        const startServices = {
          ...coreStartServices,
          ...startDepsServices,
          storage: this.storage,
          cloud,
          authz: await fleetStart.authz
        };
        const {
          renderApp,
          teardownFleet
        } = await Promise.resolve().then(() => _interopRequireWildcard(require('./applications/fleet')));
        const unmount = renderApp(startServices, params, config, kibanaVersion, extensions);
        return () => {
          unmount();
          teardownFleet(startServices);
        };
      }
    });

    // BWC < 7.11 redirect /app/ingestManager to /app/fleet
    core.application.register({
      id: 'ingestManager',
      category: _public.DEFAULT_APP_CATEGORIES.management,
      navLinkStatus: _public.AppNavLinkStatus.hidden,
      title: _i18n.i18n.translate('xpack.fleet.oldAppTitle', {
        defaultMessage: 'Ingest Manager'
      }),
      async mount(params) {
        const [coreStart] = await core.getStartServices();
        coreStart.application.navigateToApp('fleet', {
          path: params.history.location.hash
        });
        return () => {};
      }
    });

    // Register components for home/add data integration
    if (deps.home) {
      deps.home.tutorials.registerDirectoryHeaderLink(_common.PLUGIN_ID, _home_integration.TutorialDirectoryHeaderLink);
      deps.home.tutorials.registerModuleNotice(_common.PLUGIN_ID, _home_integration.TutorialModuleNotice);
      deps.home.featureCatalogue.register({
        id: 'fleet',
        title: _i18n.i18n.translate('xpack.fleet.featureCatalogueTitle', {
          defaultMessage: 'Add Elastic Agent integrations'
        }),
        description: _i18n.i18n.translate('xpack.fleet.featureCatalogueDescription', {
          defaultMessage: 'Add and manage integrations with Elastic Agent'
        }),
        icon: 'indexManagementApp',
        showOnHomePage: true,
        path: _constants2.INTEGRATIONS_BASE_PATH,
        category: 'data',
        order: 510
      });
    }
    if (deps.globalSearch) {
      deps.globalSearch.registerResultProvider((0, _search_provider.createPackageSearchProvider)(core));
    }
    return {};
  }
  start(core, deps) {
    _experimental_features2.ExperimentalFeaturesService.init(this.experimentalFeatures);
    const registerExtension = (0, _ui_extensions.createExtensionRegistrationCallback)(this.extensions);
    const getPermissions = (0, _lodash.once)(() => core.http.fetch(_common.appRoutesService.getCheckPermissionsPath(), {
      headers: {
        [_coreHttpCommon.ELASTIC_HTTP_VERSION_HEADER]: _constants.API_VERSIONS.public.v1
      },
      version: _constants.API_VERSIONS.public.v1
    }));

    // Set up license service
    _hooks.licenseService.start(deps.licensing.license$);
    registerExtension({
      package: _constants2.CUSTOM_LOGS_INTEGRATION_NAME,
      view: 'package-detail-assets',
      Component: _lazy_custom_logs_assets_extension.LazyCustomLogsAssetsExtension
    });
    const {
      capabilities
    } = core.application;

    // Set the custom integrations language clients
    (0, _custom_integrations.setCustomIntegrationsStart)(deps.customIntegrations);

    //  capabilities.fleetv2 returns fleet privileges and capabilities.fleet returns integrations privileges
    return {
      authz: {
        ...(0, _authz.calculateAuthz)({
          fleet: {
            all: capabilities.fleetv2.all,
            setup: false
          },
          integrations: {
            all: capabilities.fleet.all,
            read: capabilities.fleet.read
          },
          isSuperuser: false
        }),
        packagePrivileges: (0, _authz.calculatePackagePrivilegesFromCapabilities)(capabilities),
        endpointExceptionsPrivileges: (0, _authz.calculateEndpointExceptionsPrivilegesFromCapabilities)(capabilities)
      },
      isInitialized: (0, _lodash.once)(async () => {
        const permissionsResponse = await getPermissions();
        if (permissionsResponse !== null && permissionsResponse !== void 0 && permissionsResponse.success) {
          const {
            isInitialized
          } = await core.http.post(_common.setupRouteService.getSetupPath(), {
            version: _constants.API_VERSIONS.public.v1
          });
          if (!isInitialized) {
            throw new Error('Unknown setup error');
          }
          return true;
        } else {
          throw new Error((permissionsResponse === null || permissionsResponse === void 0 ? void 0 : permissionsResponse.error) || 'Unknown permissions error');
        }
      }),
      registerExtension,
      hooks: {
        epm: {
          // hook exported to be used in monitoring-ui
          getBulkAssets: _hooks.sendGetBulkAssets
        }
      }
    };
  }
  stop() {}
}
exports.FleetPlugin = FleetPlugin;