"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.sourceMapsRouteRepository = exports.sourceMapRt = void 0;
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _ioTsUtils = require("@kbn/io-ts-utils");
var t = _interopRequireWildcard(require("io-ts"));
var _get_internal_saved_objects_client = require("../../lib/helpers/get_internal_saved_objects_client");
var _string_from_buffer_rt = require("../../utils/string_from_buffer_rt");
var _create_apm_server_route = require("../apm_routes/create_apm_server_route");
var _source_maps = require("../fleet/source_maps");
var _create_apm_source_map = require("./create_apm_source_map");
var _delete_apm_sourcemap = require("./delete_apm_sourcemap");
var _schedule_source_map_migration = require("./schedule_source_map_migration");
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.
 */

const sourceMapRt = t.intersection([t.type({
  version: t.number,
  sources: t.array(t.string),
  mappings: t.string
}), t.partial({
  names: t.array(t.string),
  file: t.string,
  sourceRoot: t.string,
  sourcesContent: t.array(t.union([t.string, t.null]))
})]);
exports.sourceMapRt = sourceMapRt;
function throwNotImplementedIfSourceMapNotAvailable(featureFlags) {
  if (!featureFlags.sourcemapApiAvailable) {
    throw _boom.default.notImplemented();
  }
}
const listSourceMapRoute = (0, _create_apm_server_route.createApmServerRoute)({
  endpoint: 'GET /api/apm/sourcemaps 2023-10-31',
  options: {
    tags: ['access:apm']
  },
  params: t.partial({
    query: t.partial({
      page: _ioTsUtils.toNumberRt,
      perPage: _ioTsUtils.toNumberRt
    })
  }),
  async handler({
    params,
    plugins,
    featureFlags
  }) {
    throwNotImplementedIfSourceMapNotAvailable(featureFlags);
    const {
      page,
      perPage
    } = params.query;
    try {
      var _plugins$fleet;
      const fleetPluginStart = await ((_plugins$fleet = plugins.fleet) === null || _plugins$fleet === void 0 ? void 0 : _plugins$fleet.start());
      if (fleetPluginStart) {
        const {
          artifacts,
          total
        } = await (0, _source_maps.listSourceMapArtifacts)({
          fleetPluginStart,
          page,
          perPage
        });
        return {
          artifacts,
          total
        };
      }
    } catch (e) {
      throw _boom.default.internal('Something went wrong while fetching artifacts source maps', e);
    }
  }
});
const uploadSourceMapRoute = (0, _create_apm_server_route.createApmServerRoute)({
  endpoint: 'POST /api/apm/sourcemaps 2023-10-31',
  options: {
    tags: ['access:apm', 'access:apm_write'],
    body: {
      accepts: ['multipart/form-data']
    }
  },
  params: t.type({
    body: t.type({
      service_name: t.string,
      service_version: t.string,
      bundle_filepath: t.string,
      sourcemap: t.union([t.string, _string_from_buffer_rt.stringFromBufferRt]).pipe(_ioTsUtils.jsonRt).pipe(sourceMapRt)
    })
  }),
  handler: async ({
    params,
    plugins,
    core,
    logger,
    featureFlags
  }) => {
    var _plugins$fleet2;
    throwNotImplementedIfSourceMapNotAvailable(featureFlags);
    const {
      service_name: serviceName,
      service_version: serviceVersion,
      bundle_filepath: bundleFilepath,
      sourcemap: sourceMapContent
    } = params.body;
    const cleanedBundleFilepath = (0, _source_maps.getCleanedBundleFilePath)(bundleFilepath);
    const fleetPluginStart = await ((_plugins$fleet2 = plugins.fleet) === null || _plugins$fleet2 === void 0 ? void 0 : _plugins$fleet2.start());
    const coreStart = await core.start();
    const internalESClient = coreStart.elasticsearch.client.asInternalUser;
    const savedObjectsClient = await (0, _get_internal_saved_objects_client.getInternalSavedObjectsClient)(coreStart);
    try {
      if (fleetPluginStart) {
        // create source map as fleet artifact
        const artifact = await (0, _source_maps.createFleetSourceMapArtifact)({
          fleetPluginStart,
          apmArtifactBody: {
            serviceName,
            serviceVersion,
            bundleFilepath: cleanedBundleFilepath,
            sourceMap: sourceMapContent
          }
        });

        // sync source map to APM managed index
        await (0, _create_apm_source_map.createApmSourceMap)({
          internalESClient,
          logger,
          fleetId: artifact.id,
          created: artifact.created,
          sourceMapContent,
          bundleFilepath: cleanedBundleFilepath,
          serviceName,
          serviceVersion
        });

        // sync source map to fleet policy
        await (0, _source_maps.updateSourceMapsOnFleetPolicies)({
          coreStart,
          fleetPluginStart,
          savedObjectsClient: savedObjectsClient,
          internalESClient
        });
        return artifact;
      }
    } catch (e) {
      throw _boom.default.internal('Something went wrong while creating a new source map', e);
    }
  }
});
const deleteSourceMapRoute = (0, _create_apm_server_route.createApmServerRoute)({
  endpoint: 'DELETE /api/apm/sourcemaps/{id} 2023-10-31',
  options: {
    tags: ['access:apm', 'access:apm_write']
  },
  params: t.type({
    path: t.type({
      id: t.string
    })
  }),
  handler: async ({
    params,
    plugins,
    core,
    featureFlags
  }) => {
    var _plugins$fleet3;
    throwNotImplementedIfSourceMapNotAvailable(featureFlags);
    const fleetPluginStart = await ((_plugins$fleet3 = plugins.fleet) === null || _plugins$fleet3 === void 0 ? void 0 : _plugins$fleet3.start());
    const {
      id
    } = params.path;
    const coreStart = await core.start();
    const internalESClient = coreStart.elasticsearch.client.asInternalUser;
    const savedObjectsClient = await (0, _get_internal_saved_objects_client.getInternalSavedObjectsClient)(coreStart);
    try {
      if (fleetPluginStart) {
        await (0, _source_maps.deleteFleetSourcemapArtifact)({
          id,
          fleetPluginStart
        });
        await (0, _delete_apm_sourcemap.deleteApmSourceMap)({
          internalESClient,
          fleetId: id
        });
        await (0, _source_maps.updateSourceMapsOnFleetPolicies)({
          coreStart,
          fleetPluginStart,
          savedObjectsClient: savedObjectsClient,
          internalESClient
        });
      }
    } catch (e) {
      throw _boom.default.internal(`Something went wrong while deleting source map. id: ${id}`, e);
    }
  }
});
const migrateFleetArtifactsSourceMapRoute = (0, _create_apm_server_route.createApmServerRoute)({
  endpoint: 'POST /internal/apm/sourcemaps/migrate_fleet_artifacts',
  options: {
    tags: ['access:apm', 'access:apm_write']
  },
  handler: async ({
    plugins,
    core,
    logger,
    featureFlags
  }) => {
    var _plugins$fleet4;
    throwNotImplementedIfSourceMapNotAvailable(featureFlags);
    const fleet = await ((_plugins$fleet4 = plugins.fleet) === null || _plugins$fleet4 === void 0 ? void 0 : _plugins$fleet4.start());
    const coreStart = await core.start();
    const internalESClient = coreStart.elasticsearch.client.asInternalUser;
    if (fleet) {
      return (0, _schedule_source_map_migration.runFleetSourcemapArtifactsMigration)({
        fleet,
        internalESClient,
        logger
      });
    }
  }
});
const sourceMapsRouteRepository = {
  ...listSourceMapRoute,
  ...uploadSourceMapRoute,
  ...deleteSourceMapRoute,
  ...migrateFleetArtifactsSourceMapRoute
};
exports.sourceMapsRouteRepository = sourceMapsRouteRepository;