/// <reference types="node" />
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
import { LoggerService, RootConfigService, RootLoggerService, BackendFeature, ServiceFactoryOrFunction, DiscoveryService, LifecycleService, RootHttpRouterService, RootLifecycleService } from '@backstage/backend-plugin-api';
import { LoadConfigOptionsRemote, RemoteConfigSourceOptions } from '@backstage/config-loader';
import { Config, AppConfig } from '@backstage/config';
import * as http from 'http';
import { RequestListener } from 'http';
import { RequestHandler, ErrorRequestHandler, Express, Handler } from 'express';
import { CorsOptions } from 'cors';
import { HelmetOptions } from 'helmet';
import { JsonObject, HumanDuration } from '@backstage/types';
import { Format } from 'logform';
import { transport } from 'winston';
import * as _backstage_backend_common from '@backstage/backend-common';

/** @public */
declare function createConfigSecretEnumerator(options: {
    logger: LoggerService;
    dir?: string;
}): Promise<(config: Config) => Iterable<string>>;
/**
 * Load configuration for a Backend.
 *
 * This function should only be called once, during the initialization of the backend.
 *
 * @public
 */
declare function loadBackendConfig(options: {
    remote?: LoadConfigOptionsRemote;
    argv: string[];
    additionalConfigs?: AppConfig[];
    watch?: boolean;
}): Promise<{
    config: Config;
}>;

/**
 * An HTTP server extended with utility methods.
 *
 * @public
 */
interface ExtendedHttpServer extends http.Server {
    start(): Promise<void>;
    stop(): Promise<void>;
    port(): number;
}
/**
 * Options for starting up an HTTP server.
 *
 * @public
 */
type HttpServerOptions = {
    listen: {
        port: number;
        host: string;
    };
    https?: {
        certificate: HttpServerCertificateOptions;
    };
};
/**
 * Options for configuring HTTPS for an HTTP server.
 *
 * @public
 */
type HttpServerCertificateOptions = {
    type: 'pem';
    key: string;
    cert: string;
} | {
    type: 'generated';
    hostname: string;
};

/**
 * Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.
 *
 * @public
 * @remarks
 *
 * The provided configuration object should contain the `listen` and
 * additional keys directly.
 *
 * @example
 * ```ts
 * const opts = readHttpServerOptions(config.getConfig('backend'));
 * ```
 */
declare function readHttpServerOptions(config?: Config): HttpServerOptions;

/**
 * Creates a Node.js HTTP or HTTPS server instance.
 *
 * @public
 */
declare function createHttpServer(listener: RequestListener, options: HttpServerOptions, deps: {
    logger: LoggerService;
}): Promise<ExtendedHttpServer>;

/**
 * Options used to create a {@link MiddlewareFactory}.
 *
 * @public
 */
interface MiddlewareFactoryOptions {
    config: RootConfigService;
    logger: LoggerService;
}
/**
 * Options passed to the {@link MiddlewareFactory.error} middleware.
 *
 * @public
 */
interface MiddlewareFactoryErrorOptions {
    /**
     * Whether error response bodies should show error stack traces or not.
     *
     * If not specified, by default shows stack traces only in development mode.
     */
    showStackTraces?: boolean;
    /**
     * Whether any 4xx errors should be logged or not.
     *
     * If not specified, default to only logging 5xx errors.
     */
    logAllErrors?: boolean;
}
/**
 * A utility to configure common middleware.
 *
 * @public
 */
declare class MiddlewareFactory {
    #private;
    /**
     * Creates a new {@link MiddlewareFactory}.
     */
    static create(options: MiddlewareFactoryOptions): MiddlewareFactory;
    private constructor();
    /**
     * Returns a middleware that unconditionally produces a 404 error response.
     *
     * @remarks
     *
     * Typically you want to place this middleware at the end of the chain, such
     * that it's the last one attempted after no other routes matched.
     *
     * @returns An Express request handler
     */
    notFound(): RequestHandler;
    /**
     * Returns the compression middleware.
     *
     * @remarks
     *
     * The middleware will attempt to compress response bodies for all requests
     * that traverse through the middleware.
     */
    compression(): RequestHandler;
    /**
     * Returns a request logging middleware.
     *
     * @remarks
     *
     * Typically you want to place this middleware at the start of the chain, such
     * that it always logs requests whether they are "caught" by handlers farther
     * down or not.
     *
     * @returns An Express request handler
     */
    logging(): RequestHandler;
    /**
     * Returns a middleware that implements the helmet library.
     *
     * @remarks
     *
     * This middleware applies security policies to incoming requests and outgoing
     * responses. It is configured using config keys such as `backend.csp`.
     *
     * @see {@link https://helmetjs.github.io/}
     *
     * @returns An Express request handler
     */
    helmet(): RequestHandler;
    /**
     * Returns a middleware that implements the cors library.
     *
     * @remarks
     *
     * This middleware handles CORS. It is configured using the config key
     * `backend.cors`.
     *
     * @see {@link https://github.com/expressjs/cors}
     *
     * @returns An Express request handler
     */
    cors(): RequestHandler;
    /**
     * Express middleware to handle errors during request processing.
     *
     * @remarks
     *
     * This is commonly the very last middleware in the chain.
     *
     * Its primary purpose is not to do translation of business logic exceptions,
     * but rather to be a global catch-all for uncaught "fatal" errors that are
     * expected to result in a 500 error. However, it also does handle some common
     * error types (such as http-error exceptions, and the well-known error types
     * in the `@backstage/errors` package) and returns the enclosed status code
     * accordingly.
     *
     * It will also produce a response body with a serialized form of the error,
     * unless a previous handler already did send a body. See
     * {@link @backstage/errors#ErrorResponseBody} for the response shape used.
     *
     * @returns An Express error request handler
     */
    error(options?: MiddlewareFactoryErrorOptions): ErrorRequestHandler;
}

/**
 * Attempts to read a CORS options object from the backend configuration object.
 *
 * @public
 * @param config - The backend configuration object.
 * @returns A CORS options object, or undefined if no cors configuration is present.
 *
 * @example
 * ```ts
 * const corsOptions = readCorsOptions(config.getConfig('backend'));
 * ```
 */
declare function readCorsOptions(config?: Config): CorsOptions;

/**
 * Attempts to read Helmet options from the backend configuration object.
 *
 * @public
 * @param config - The backend configuration object.
 * @returns A Helmet options object, or undefined if no Helmet configuration is present.
 *
 * @example
 * ```ts
 * const helmetOptions = readHelmetOptions(config.getConfig('backend'));
 * ```
 */
declare function readHelmetOptions(config?: Config): HelmetOptions;

/**
 * @public
 */
interface WinstonLoggerOptions {
    meta?: JsonObject;
    level: string;
    format: Format;
    transports: transport[];
}
/**
 * A {@link @backstage/backend-plugin-api#LoggerService} implementation based on winston.
 *
 * @public
 */
declare class WinstonLogger implements RootLoggerService {
    #private;
    /**
     * Creates a {@link WinstonLogger} instance.
     */
    static create(options: WinstonLoggerOptions): WinstonLogger;
    /**
     * Creates a winston log formatter for redacting secrets.
     */
    static redacter(): {
        format: Format;
        add: (redactions: Iterable<string>) => void;
    };
    /**
     * Creates a pretty printed winston log formatter.
     */
    static colorFormat(): Format;
    private constructor();
    error(message: string, meta?: JsonObject): void;
    warn(message: string, meta?: JsonObject): void;
    info(message: string, meta?: JsonObject): void;
    debug(message: string, meta?: JsonObject): void;
    child(meta: JsonObject): LoggerService;
    addRedactions(redactions: Iterable<string>): void;
}

/**
 * @public
 */
interface Backend {
    add(feature: BackendFeature | (() => BackendFeature) | Promise<{
        default: BackendFeature | (() => BackendFeature);
    }>): void;
    start(): Promise<void>;
    stop(): Promise<void>;
}
/**
 * @public
 */
interface CreateSpecializedBackendOptions {
    defaultServiceFactories: ServiceFactoryOrFunction[];
}

/**
 * @public
 */
declare function createSpecializedBackend(options: CreateSpecializedBackendOptions): Backend;

/** @public */
declare const cacheServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_common.CacheClient, "plugin">;

/** @public */
interface RootConfigFactoryOptions {
    /**
     * Process arguments to use instead of the default `process.argv()`.
     */
    argv?: string[];
    /**
     * Enables and sets options for remote configuration loading.
     */
    remote?: Pick<RemoteConfigSourceOptions, 'reloadInterval'>;
}
/** @public */
declare const rootConfigServiceFactory: (options?: RootConfigFactoryOptions | undefined) => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.RootConfigService, "root">;

/** @public */
declare const databaseServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_common.PluginDatabaseManager, "plugin">;

/** @public */
declare const discoveryServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.DiscoveryService, "plugin">;

/**
 * HostDiscovery is a basic PluginEndpointDiscovery implementation
 * that can handle plugins that are hosted in a single or multiple deployments.
 *
 * The deployment may be scaled horizontally, as long as the external URL
 * is the same for all instances. However, internal URLs will always be
 * resolved to the same host, so there won't be any balancing of internal traffic.
 *
 * @public
 */
declare class HostDiscovery implements DiscoveryService {
    private readonly internalBaseUrl;
    private readonly externalBaseUrl;
    private readonly discoveryConfig;
    /**
     * Creates a new HostDiscovery discovery instance by reading
     * from the `backend` config section, specifically the `.baseUrl` for
     * discovering the external URL, and the `.listen` and `.https` config
     * for the internal one.
     *
     * Can be overridden in config by providing a target and corresponding plugins in `discovery.endpoints`.
     * eg.
     * ```yaml
     * discovery:
     *  endpoints:
     *    - target: https://internal.example.com/internal-catalog
     *      plugins: [catalog]
     *    - target: https://internal.example.com/secure/api/{{pluginId}}
     *      plugins: [auth, permission]
     *    - target:
     *        internal: https://internal.example.com/search
     *        external: https://example.com/search
     *      plugins: [search]
     * ```
     *
     * The basePath defaults to `/api`, meaning the default full internal
     * path for the `catalog` plugin will be `http://localhost:7007/api/catalog`.
     */
    static fromConfig(config: Config, options?: {
        basePath?: string;
    }): HostDiscovery;
    private constructor();
    private getTargetFromConfig;
    getBaseUrl(pluginId: string): Promise<string>;
    getExternalBaseUrl(pluginId: string): Promise<string>;
}

/**
 * @public
 */
interface HttpRouterFactoryOptions {
    /**
     * A callback used to generate the path for each plugin, defaults to `/api/{pluginId}`.
     */
    getPath?(pluginId: string): string;
}
/** @public */
declare const httpRouterServiceFactory: (options?: HttpRouterFactoryOptions | undefined) => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.HttpRouterService, "plugin">;

/**
 * Options for {@link createLifecycleMiddleware}.
 * @public
 */
interface LifecycleMiddlewareOptions {
    lifecycle: LifecycleService;
    /**
     * The maximum time that paused requests will wait for the service to start, before returning an error.
     *
     * Defaults to 5 seconds.
     */
    startupRequestPauseTimeout?: HumanDuration;
}
/**
 * Creates a middleware that pauses requests until the service has started.
 *
 * @remarks
 *
 * Requests that arrive before the service has started will be paused until startup is complete.
 * If the service does not start within the provided timeout, the request will be rejected with a
 * {@link @backstage/errors#ServiceUnavailableError}.
 *
 * If the service is shutting down, all requests will be rejected with a
 * {@link @backstage/errors#ServiceUnavailableError}.
 *
 * @public
 */
declare function createLifecycleMiddleware(options: LifecycleMiddlewareOptions): RequestHandler;

/**
 * An identity client options object which allows extra configurations
 *
 * @public
 */
type IdentityFactoryOptions = {
    issuer?: string;
    /** JWS "alg" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.
     * More info on supported algorithms: https://github.com/panva/jose */
    algorithms?: string[];
};
/** @public */
declare const identityServiceFactory: (options?: IdentityFactoryOptions | undefined) => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.IdentityService, "plugin">;

/**
 * Allows plugins to register shutdown hooks that are run when the process is about to exit.
 * @public
 */
declare const lifecycleServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<LifecycleService, "plugin">;

/** @public */
declare const loggerServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.LoggerService, "plugin">;

/** @public */
declare const permissionsServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.PermissionsService, "plugin">;

/**
 * @public
 */
interface RootHttpRouterConfigureContext {
    app: Express;
    middleware: MiddlewareFactory;
    routes: RequestHandler;
    config: RootConfigService;
    logger: LoggerService;
    lifecycle: LifecycleService;
}
/**
 * @public
 */
type RootHttpRouterFactoryOptions = {
    /**
     * The path to forward all unmatched requests to. Defaults to '/api/app' if
     * not given. Disables index path behavior if false is given.
     */
    indexPath?: string | false;
    configure?(context: RootHttpRouterConfigureContext): void;
};
/** @public */
declare const rootHttpRouterServiceFactory: (options?: RootHttpRouterFactoryOptions | undefined) => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.RootHttpRouterService, "root">;

/**
 * Options for the {@link DefaultRootHttpRouter} class.
 *
 * @public
 */
interface DefaultRootHttpRouterOptions {
    /**
     * The path to forward all unmatched requests to. Defaults to '/api/app' if
     * not given. Disables index path behavior if false is given.
     */
    indexPath?: string | false;
}
/**
 * The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for
 * {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.
 *
 * @public
 */
declare class DefaultRootHttpRouter implements RootHttpRouterService {
    #private;
    static create(options?: DefaultRootHttpRouterOptions): DefaultRootHttpRouter;
    private constructor();
    use(path: string, handler: Handler): void;
    handler(): Handler;
}

/**
 * Allows plugins to register shutdown hooks that are run when the process is about to exit.
 *
 * @public
 */
declare const rootLifecycleServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<RootLifecycleService, "root">;

/** @public */
declare const rootLoggerServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.RootLoggerService, "root">;

/** @public */
declare const schedulerServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.SchedulerService, "plugin">;

/** @public */
declare const tokenManagerServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.TokenManagerService, "plugin">;

/** @public */
declare const urlReaderServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_common.UrlReader, "plugin">;

export { Backend, CreateSpecializedBackendOptions, DefaultRootHttpRouter, DefaultRootHttpRouterOptions, ExtendedHttpServer, HostDiscovery, HttpRouterFactoryOptions, HttpServerCertificateOptions, HttpServerOptions, IdentityFactoryOptions, LifecycleMiddlewareOptions, MiddlewareFactory, MiddlewareFactoryErrorOptions, MiddlewareFactoryOptions, RootConfigFactoryOptions, RootHttpRouterConfigureContext, RootHttpRouterFactoryOptions, WinstonLogger, WinstonLoggerOptions, cacheServiceFactory, createConfigSecretEnumerator, createHttpServer, createLifecycleMiddleware, createSpecializedBackend, databaseServiceFactory, discoveryServiceFactory, httpRouterServiceFactory, identityServiceFactory, lifecycleServiceFactory, loadBackendConfig, loggerServiceFactory, permissionsServiceFactory, readCorsOptions, readHelmetOptions, readHttpServerOptions, rootConfigServiceFactory, rootHttpRouterServiceFactory, rootLifecycleServiceFactory, rootLoggerServiceFactory, schedulerServiceFactory, tokenManagerServiceFactory, urlReaderServiceFactory };
