@backstage/backend-app-api 0.4.6-next.0 → 0.5.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @backstage/backend-app-api might be problematic. Click here for more details.

package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @backstage/backend-app-api
2
2
 
3
+ ## 0.5.0-next.1
4
+
5
+ ### Minor Changes
6
+
7
+ - b9c57a4f857e: **BREAKING**: Renamed `configServiceFactory` to `rootConfigServiceFactory`.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies
12
+ - @backstage/backend-common@0.19.2-next.1
13
+ - @backstage/config-loader@1.4.0-next.1
14
+ - @backstage/plugin-auth-node@0.2.17-next.1
15
+ - @backstage/backend-plugin-api@0.6.0-next.1
16
+ - @backstage/backend-tasks@0.5.5-next.1
17
+ - @backstage/plugin-permission-node@0.7.11-next.1
18
+ - @backstage/cli-common@0.1.12
19
+ - @backstage/config@1.0.8
20
+ - @backstage/errors@1.2.1
21
+ - @backstage/types@1.1.0
22
+
3
23
  ## 0.4.6-next.0
4
24
 
5
25
  ### Patch Changes
package/dist/index.cjs.js CHANGED
@@ -1565,7 +1565,7 @@ function createSpecializedBackend(options) {
1565
1565
  const cacheServiceFactory = backendPluginApi.createServiceFactory({
1566
1566
  service: backendPluginApi.coreServices.cache,
1567
1567
  deps: {
1568
- config: backendPluginApi.coreServices.config,
1568
+ config: backendPluginApi.coreServices.rootConfig,
1569
1569
  plugin: backendPluginApi.coreServices.pluginMetadata
1570
1570
  },
1571
1571
  async createRootContext({ config }) {
@@ -1576,9 +1576,9 @@ const cacheServiceFactory = backendPluginApi.createServiceFactory({
1576
1576
  }
1577
1577
  });
1578
1578
 
1579
- const configServiceFactory = backendPluginApi.createServiceFactory(
1579
+ const rootConfigServiceFactory = backendPluginApi.createServiceFactory(
1580
1580
  (options) => ({
1581
- service: backendPluginApi.coreServices.config,
1581
+ service: backendPluginApi.coreServices.rootConfig,
1582
1582
  deps: {},
1583
1583
  async factory() {
1584
1584
  const source = configLoader.ConfigSources.default({
@@ -1594,7 +1594,7 @@ const configServiceFactory = backendPluginApi.createServiceFactory(
1594
1594
  const databaseServiceFactory = backendPluginApi.createServiceFactory({
1595
1595
  service: backendPluginApi.coreServices.database,
1596
1596
  deps: {
1597
- config: backendPluginApi.coreServices.config,
1597
+ config: backendPluginApi.coreServices.rootConfig,
1598
1598
  lifecycle: backendPluginApi.coreServices.lifecycle,
1599
1599
  pluginMetadata: backendPluginApi.coreServices.pluginMetadata
1600
1600
  },
@@ -1618,7 +1618,7 @@ const databaseServiceFactory = backendPluginApi.createServiceFactory({
1618
1618
  const discoveryServiceFactory = backendPluginApi.createServiceFactory({
1619
1619
  service: backendPluginApi.coreServices.discovery,
1620
1620
  deps: {
1621
- config: backendPluginApi.coreServices.config
1621
+ config: backendPluginApi.coreServices.rootConfig
1622
1622
  },
1623
1623
  async factory({ config }) {
1624
1624
  return backendCommon.HostDiscovery.fromConfig(config);
@@ -1719,7 +1719,7 @@ const loggerServiceFactory = backendPluginApi.createServiceFactory({
1719
1719
  const permissionsServiceFactory = backendPluginApi.createServiceFactory({
1720
1720
  service: backendPluginApi.coreServices.permissions,
1721
1721
  deps: {
1722
- config: backendPluginApi.coreServices.config,
1722
+ config: backendPluginApi.coreServices.rootConfig,
1723
1723
  discovery: backendPluginApi.coreServices.discovery,
1724
1724
  tokenManager: backendPluginApi.coreServices.tokenManager
1725
1725
  },
@@ -1839,7 +1839,7 @@ const rootHttpRouterServiceFactory = backendPluginApi.createServiceFactory(
1839
1839
  (options) => ({
1840
1840
  service: backendPluginApi.coreServices.rootHttpRouter,
1841
1841
  deps: {
1842
- config: backendPluginApi.coreServices.config,
1842
+ config: backendPluginApi.coreServices.rootConfig,
1843
1843
  rootLogger: backendPluginApi.coreServices.rootLogger,
1844
1844
  lifecycle: backendPluginApi.coreServices.rootLifecycle
1845
1845
  },
@@ -1872,7 +1872,7 @@ const rootHttpRouterServiceFactory = backendPluginApi.createServiceFactory(
1872
1872
  const rootLoggerServiceFactory = backendPluginApi.createServiceFactory({
1873
1873
  service: backendPluginApi.coreServices.rootLogger,
1874
1874
  deps: {
1875
- config: backendPluginApi.coreServices.config
1875
+ config: backendPluginApi.coreServices.rootConfig
1876
1876
  },
1877
1877
  async factory({ config }) {
1878
1878
  var _a;
@@ -1910,7 +1910,7 @@ const schedulerServiceFactory = backendPluginApi.createServiceFactory({
1910
1910
  const tokenManagerServiceFactory = backendPluginApi.createServiceFactory({
1911
1911
  service: backendPluginApi.coreServices.tokenManager,
1912
1912
  deps: {
1913
- config: backendPluginApi.coreServices.config,
1913
+ config: backendPluginApi.coreServices.rootConfig,
1914
1914
  logger: backendPluginApi.coreServices.rootLogger
1915
1915
  },
1916
1916
  createRootContext({ config, logger }) {
@@ -1926,7 +1926,7 @@ const tokenManagerServiceFactory = backendPluginApi.createServiceFactory({
1926
1926
  const urlReaderServiceFactory = backendPluginApi.createServiceFactory({
1927
1927
  service: backendPluginApi.coreServices.urlReader,
1928
1928
  deps: {
1929
- config: backendPluginApi.coreServices.config,
1929
+ config: backendPluginApi.coreServices.rootConfig,
1930
1930
  logger: backendPluginApi.coreServices.logger
1931
1931
  },
1932
1932
  async factory({ config, logger }) {
@@ -1941,7 +1941,6 @@ exports.DefaultRootHttpRouter = DefaultRootHttpRouter;
1941
1941
  exports.MiddlewareFactory = MiddlewareFactory;
1942
1942
  exports.WinstonLogger = WinstonLogger;
1943
1943
  exports.cacheServiceFactory = cacheServiceFactory;
1944
- exports.configServiceFactory = configServiceFactory;
1945
1944
  exports.createConfigSecretEnumerator = createConfigSecretEnumerator;
1946
1945
  exports.createHttpServer = createHttpServer;
1947
1946
  exports.createLifecycleMiddleware = createLifecycleMiddleware;
@@ -1957,6 +1956,7 @@ exports.permissionsServiceFactory = permissionsServiceFactory;
1957
1956
  exports.readCorsOptions = readCorsOptions;
1958
1957
  exports.readHelmetOptions = readHelmetOptions;
1959
1958
  exports.readHttpServerOptions = readHttpServerOptions;
1959
+ exports.rootConfigServiceFactory = rootConfigServiceFactory;
1960
1960
  exports.rootHttpRouterServiceFactory = rootHttpRouterServiceFactory;
1961
1961
  exports.rootLifecycleServiceFactory = rootLifecycleServiceFactory;
1962
1962
  exports.rootLoggerServiceFactory = rootLoggerServiceFactory;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/config/ObservableConfigProxy.ts","../src/lib/urls.ts","../src/config/config.ts","../src/http/config.ts","../src/http/getGeneratedCertificate.ts","../src/http/createHttpServer.ts","../src/http/readHelmetOptions.ts","../src/http/readCorsOptions.ts","../src/http/MiddlewareFactory.ts","../src/lib/escapeRegExp.ts","../src/logging/WinstonLogger.ts","../src/services/implementations/rootLifecycle/rootLifecycleServiceFactory.ts","../src/services/implementations/lifecycle/lifecycleServiceFactory.ts","../src/wiring/BackendInitializer.ts","../src/wiring/ServiceRegistry.ts","../src/wiring/BackstageBackend.ts","../src/wiring/createSpecializedBackend.ts","../src/services/implementations/cache/cacheServiceFactory.ts","../src/services/implementations/config/configServiceFactory.ts","../src/services/implementations/database/databaseServiceFactory.ts","../src/services/implementations/discovery/discoveryServiceFactory.ts","../src/services/implementations/httpRouter/createLifecycleMiddleware.ts","../src/services/implementations/httpRouter/httpRouterServiceFactory.ts","../src/services/implementations/identity/identityServiceFactory.ts","../src/services/implementations/logger/loggerServiceFactory.ts","../src/services/implementations/permissions/permissionsServiceFactory.ts","../src/services/implementations/rootHttpRouter/DefaultRootHttpRouter.ts","../src/services/implementations/rootHttpRouter/rootHttpRouterServiceFactory.ts","../src/services/implementations/rootLogger/rootLoggerServiceFactory.ts","../src/services/implementations/scheduler/schedulerServiceFactory.ts","../src/services/implementations/tokenManager/tokenManagerServiceFactory.ts","../src/services/implementations/urlReader/urlReaderServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigService } from '@backstage/backend-plugin-api';\nimport { ConfigReader } from '@backstage/config';\nimport { JsonValue } from '@backstage/types';\n\nexport class ObservableConfigProxy implements ConfigService {\n private config: ConfigService = new ConfigReader({});\n\n private readonly subscribers: (() => void)[] = [];\n\n constructor(\n private readonly parent?: ObservableConfigProxy,\n private parentKey?: string,\n ) {\n if (parent && !parentKey) {\n throw new Error('parentKey is required if parent is set');\n }\n }\n\n setConfig(config: ConfigService) {\n if (this.parent) {\n throw new Error('immutable');\n }\n this.config = config;\n for (const subscriber of this.subscribers) {\n try {\n subscriber();\n } catch (error) {\n console.error(`Config subscriber threw error, ${error}`);\n }\n }\n }\n\n subscribe(onChange: () => void): { unsubscribe: () => void } {\n if (this.parent) {\n return this.parent.subscribe(onChange);\n }\n\n this.subscribers.push(onChange);\n return {\n unsubscribe: () => {\n const index = this.subscribers.indexOf(onChange);\n if (index >= 0) {\n this.subscribers.splice(index, 1);\n }\n },\n };\n }\n\n private select(required: true): ConfigService;\n private select(required: false): ConfigService | undefined;\n private select(required: boolean): ConfigService | undefined {\n if (this.parent && this.parentKey) {\n if (required) {\n return this.parent.select(true).getConfig(this.parentKey);\n }\n return this.parent.select(false)?.getOptionalConfig(this.parentKey);\n }\n\n return this.config;\n }\n\n has(key: string): boolean {\n return this.select(false)?.has(key) ?? false;\n }\n keys(): string[] {\n return this.select(false)?.keys() ?? [];\n }\n get<T = JsonValue>(key?: string): T {\n return this.select(true).get(key);\n }\n getOptional<T = JsonValue>(key?: string): T | undefined {\n return this.select(false)?.getOptional(key);\n }\n getConfig(key: string): ConfigService {\n return new ObservableConfigProxy(this, key);\n }\n getOptionalConfig(key: string): ConfigService | undefined {\n if (this.select(false)?.has(key)) {\n return new ObservableConfigProxy(this, key);\n }\n return undefined;\n }\n getConfigArray(key: string): ConfigService[] {\n return this.select(true).getConfigArray(key);\n }\n getOptionalConfigArray(key: string): ConfigService[] | undefined {\n return this.select(false)?.getOptionalConfigArray(key);\n }\n getNumber(key: string): number {\n return this.select(true).getNumber(key);\n }\n getOptionalNumber(key: string): number | undefined {\n return this.select(false)?.getOptionalNumber(key);\n }\n getBoolean(key: string): boolean {\n return this.select(true).getBoolean(key);\n }\n getOptionalBoolean(key: string): boolean | undefined {\n return this.select(false)?.getOptionalBoolean(key);\n }\n getString(key: string): string {\n return this.select(true).getString(key);\n }\n getOptionalString(key: string): string | undefined {\n return this.select(false)?.getOptionalString(key);\n }\n getStringArray(key: string): string[] {\n return this.select(true).getStringArray(key);\n }\n getOptionalStringArray(key: string): string[] | undefined {\n return this.select(false)?.getOptionalStringArray(key);\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isValidUrl(url: string): boolean {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolve as resolvePath } from 'path';\nimport parseArgs from 'minimist';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { findPaths } from '@backstage/cli-common';\nimport {\n loadConfigSchema,\n loadConfig,\n ConfigTarget,\n LoadConfigOptionsRemote,\n} from '@backstage/config-loader';\nimport { ConfigReader } from '@backstage/config';\nimport type { Config, AppConfig } from '@backstage/config';\nimport { getPackages } from '@manypkg/get-packages';\nimport { ObservableConfigProxy } from './ObservableConfigProxy';\nimport { isValidUrl } from '../lib/urls';\n\n/** @public */\nexport async function createConfigSecretEnumerator(options: {\n logger: LoggerService;\n dir?: string;\n}): Promise<(config: Config) => Iterable<string>> {\n const { logger, dir = process.cwd() } = options;\n const { packages } = await getPackages(dir);\n const schema = await loadConfigSchema({\n dependencies: packages.map(p => p.packageJson.name),\n });\n\n return (config: Config) => {\n const [secretsData] = schema.process(\n [{ data: config.getOptional() ?? {}, context: 'schema-enumerator' }],\n {\n visibility: ['secret'],\n ignoreSchemaErrors: true,\n },\n );\n const secrets = new Set<string>();\n JSON.parse(\n JSON.stringify(secretsData),\n (_, v) => typeof v === 'string' && secrets.add(v),\n );\n logger.info(\n `Found ${secrets.size} new secrets in config that will be redacted`,\n );\n return secrets;\n };\n}\n\n/**\n * Load configuration for a Backend.\n *\n * This function should only be called once, during the initialization of the backend.\n *\n * @public\n */\nexport async function loadBackendConfig(options: {\n remote?: LoadConfigOptionsRemote;\n argv: string[];\n additionalConfigs?: AppConfig[];\n}): Promise<{ config: Config }> {\n const args = parseArgs(options.argv);\n\n const configTargets: ConfigTarget[] = [args.config ?? []]\n .flat()\n .map(arg => (isValidUrl(arg) ? { url: arg } : { path: resolvePath(arg) }));\n\n /* eslint-disable-next-line no-restricted-syntax */\n const paths = findPaths(__dirname);\n\n let currentCancelFunc: (() => void) | undefined = undefined;\n\n const config = new ObservableConfigProxy();\n const { appConfigs } = await loadConfig({\n configRoot: paths.targetRoot,\n configTargets: configTargets,\n remote: options.remote,\n watch: {\n onChange(newConfigs) {\n console.info(\n `Reloaded config from ${newConfigs.map(c => c.context).join(', ')}`,\n );\n const configsToMerge = [...newConfigs];\n if (options.additionalConfigs) {\n configsToMerge.push(...options.additionalConfigs);\n }\n config.setConfig(ConfigReader.fromConfigs(configsToMerge));\n },\n stopSignal: new Promise(resolve => {\n if (currentCancelFunc) {\n currentCancelFunc();\n }\n currentCancelFunc = resolve;\n\n // TODO(Rugvip): We keep this here for now to avoid breaking the old system\n // since this is re-used in backend-common\n if (module.hot) {\n module.hot.addDisposeHandler(resolve);\n }\n }),\n },\n });\n console.info(\n `Loaded config from ${appConfigs.map(c => c.context).join(', ')}`,\n );\n\n const finalAppConfigs = [...appConfigs];\n if (options.additionalConfigs) {\n finalAppConfigs.push(...options.additionalConfigs);\n }\n config.setConfig(ConfigReader.fromConfigs(finalAppConfigs));\n\n return { config };\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { HttpServerOptions } from './types';\n\nconst DEFAULT_PORT = 7007;\nconst DEFAULT_HOST = '';\n\n/**\n * Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.\n *\n * @public\n * @remarks\n *\n * The provided configuration object should contain the `listen` and\n * additional keys directly.\n *\n * @example\n * ```ts\n * const opts = readHttpServerOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHttpServerOptions(config?: Config): HttpServerOptions {\n return {\n listen: readHttpListenOptions(config),\n https: readHttpsOptions(config),\n };\n}\n\nfunction readHttpListenOptions(config?: Config): HttpServerOptions['listen'] {\n const listen = config?.getOptional('listen');\n if (typeof listen === 'string') {\n const parts = String(listen).split(':');\n const port = parseInt(parts[parts.length - 1], 10);\n if (!isNaN(port)) {\n if (parts.length === 1) {\n return { port, host: DEFAULT_HOST };\n }\n if (parts.length === 2) {\n return { host: parts[0], port };\n }\n }\n throw new Error(\n `Unable to parse listen address ${listen}, expected <port> or <host>:<port>`,\n );\n }\n\n // Workaround to allow empty string\n const host = config?.getOptional('listen.host') ?? DEFAULT_HOST;\n if (typeof host !== 'string') {\n config?.getOptionalString('listen.host'); // will throw\n throw new Error('unreachable');\n }\n\n return {\n port: config?.getOptionalNumber('listen.port') ?? DEFAULT_PORT,\n host,\n };\n}\n\nfunction readHttpsOptions(config?: Config): HttpServerOptions['https'] {\n const https = config?.getOptional('https');\n if (https === true) {\n const baseUrl = config!.getString('baseUrl');\n let hostname;\n try {\n hostname = new URL(baseUrl).hostname;\n } catch (error) {\n throw new Error(`Invalid baseUrl \"${baseUrl}\"`);\n }\n\n return { certificate: { type: 'generated', hostname } };\n }\n\n const cc = config?.getOptionalConfig('https');\n if (!cc) {\n return undefined;\n }\n\n return {\n certificate: {\n type: 'pem',\n cert: cc.getString('certificate.cert'),\n key: cc.getString('certificate.key'),\n },\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath, dirname } from 'path';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport forge from 'node-forge';\n\nconst FIVE_DAYS_IN_MS = 5 * 24 * 60 * 60 * 1000;\n\nconst IP_HOSTNAME_REGEX = /:|^\\d+\\.\\d+\\.\\d+\\.\\d+$/;\n\nexport async function getGeneratedCertificate(\n hostname: string,\n logger: LoggerService,\n) {\n const hasModules = await fs.pathExists('node_modules');\n let certPath;\n if (hasModules) {\n certPath = resolvePath(\n 'node_modules/.cache/backstage-backend/dev-cert.pem',\n );\n await fs.ensureDir(dirname(certPath));\n } else {\n certPath = resolvePath('.dev-cert.pem');\n }\n\n if (await fs.pathExists(certPath)) {\n try {\n const cert = await fs.readFile(certPath);\n\n const crt = forge.pki.certificateFromPem(cert.toString());\n const remainingMs = crt.validity.notAfter.getTime() - Date.now();\n if (remainingMs > FIVE_DAYS_IN_MS) {\n logger.info('Using existing self-signed certificate');\n return {\n key: cert,\n cert,\n };\n }\n } catch (error) {\n logger.warn(`Unable to use existing self-signed certificate, ${error}`);\n }\n }\n\n logger.info('Generating new self-signed certificate');\n const newCert = await generateCertificate(hostname);\n await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');\n return newCert;\n}\n\nasync function generateCertificate(hostname: string) {\n const attributes = [\n {\n name: 'commonName',\n value: 'dev-cert',\n },\n ];\n\n const sans = [\n {\n type: 2, // DNS\n value: 'localhost',\n },\n {\n type: 2,\n value: 'localhost.localdomain',\n },\n {\n type: 2,\n value: '[::1]',\n },\n {\n type: 7, // IP\n ip: '127.0.0.1',\n },\n {\n type: 7,\n ip: 'fe80::1',\n },\n ];\n\n // Add hostname from backend.baseUrl if it doesn't already exist in our list of SANs\n if (!sans.find(({ value, ip }) => value === hostname || ip === hostname)) {\n sans.push(\n IP_HOSTNAME_REGEX.test(hostname)\n ? {\n type: 7,\n ip: hostname,\n }\n : {\n type: 2,\n value: hostname,\n },\n );\n }\n\n const params = {\n algorithm: 'sha256',\n keySize: 2048,\n days: 30,\n extensions: [\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true,\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n timeStamping: true,\n },\n {\n name: 'subjectAltName',\n altNames: sans,\n },\n ],\n };\n\n return new Promise<{ key: string; cert: string }>((resolve, reject) =>\n require('selfsigned').generate(\n attributes,\n params,\n (err: Error, bundle: { private: string; cert: string }) => {\n if (err) {\n reject(err);\n } else {\n resolve({ key: bundle.private, cert: bundle.cert });\n }\n },\n ),\n );\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as http from 'http';\nimport * as https from 'https';\nimport stoppableServer from 'stoppable';\nimport { RequestListener } from 'http';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { HttpServerOptions, ExtendedHttpServer } from './types';\nimport { getGeneratedCertificate } from './getGeneratedCertificate';\n\n/**\n * Creates a Node.js HTTP or HTTPS server instance.\n *\n * @public\n */\nexport async function createHttpServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<ExtendedHttpServer> {\n const server = await createServer(listener, options, deps);\n\n const stopper = stoppableServer(server, 0);\n // The stopper here is actually the server itself, so if we try\n // to call stopper.stop() down in the stop implementation, we'll\n // be calling ourselves.\n const stopServer = stopper.stop.bind(stopper);\n\n return Object.assign(server, {\n start() {\n return new Promise<void>((resolve, reject) => {\n const handleStartupError = (error: Error) => {\n server.close();\n reject(error);\n };\n\n server.on('error', handleStartupError);\n\n const { host, port } = options.listen;\n server.listen(port, host, () => {\n server.off('error', handleStartupError);\n deps.logger.info(`Listening on ${host}:${port}`);\n resolve();\n });\n });\n },\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n stopServer((error?: Error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n },\n\n port() {\n const address = server.address();\n if (typeof address === 'string' || address === null) {\n throw new Error(`Unexpected server address '${address}'`);\n }\n return address.port;\n },\n });\n}\n\nasync function createServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<http.Server> {\n if (options.https) {\n const { certificate } = options.https;\n if (certificate.type === 'generated') {\n const credentials = await getGeneratedCertificate(\n certificate.hostname,\n deps.logger,\n );\n return https.createServer(credentials, listener);\n }\n return https.createServer(certificate, listener);\n }\n\n return http.createServer(listener);\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport { HelmetOptions } from 'helmet';\nimport { ContentSecurityPolicyOptions } from 'helmet/dist/types/middlewares/content-security-policy';\n\n/**\n * Attempts to read Helmet options from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A Helmet options object, or undefined if no Helmet configuration is present.\n *\n * @example\n * ```ts\n * const helmetOptions = readHelmetOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHelmetOptions(config?: Config): HelmetOptions {\n const cspOptions = readCspDirectives(config);\n return {\n contentSecurityPolicy: {\n useDefaults: false,\n directives: applyCspDirectives(cspOptions),\n },\n // These are all disabled in order to maintain backwards compatibility\n // when bumping helmet v5. We can't enable these by default because\n // there is no way for users to configure them.\n // TODO(Rugvip): We should give control of this setup to consumers\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n };\n}\n\ntype CspDirectives = Record<string, string[] | false> | undefined;\n\n/**\n * Attempts to read a CSP directives from the backend configuration object.\n *\n * @example\n * ```yaml\n * backend:\n * csp:\n * connect-src: [\"'self'\", 'http:', 'https:']\n * upgrade-insecure-requests: false\n * ```\n */\nfunction readCspDirectives(config?: Config): CspDirectives {\n const cc = config?.getOptionalConfig('csp');\n if (!cc) {\n return undefined;\n }\n\n const result: Record<string, string[] | false> = {};\n for (const key of cc.keys()) {\n if (cc.get(key) === false) {\n result[key] = false;\n } else {\n result[key] = cc.getStringArray(key);\n }\n }\n\n return result;\n}\n\nexport function applyCspDirectives(\n directives: CspDirectives,\n): ContentSecurityPolicyOptions['directives'] {\n const result: ContentSecurityPolicyOptions['directives'] =\n helmet.contentSecurityPolicy.getDefaultDirectives();\n\n // TODO(Rugvip): We currently use non-precompiled AJV for validation in the frontend, which uses eval.\n // It should be replaced by any other solution that doesn't require unsafe-eval.\n result['script-src'] = [\"'self'\", \"'unsafe-eval'\"];\n\n // TODO(Rugvip): This is removed so that we maintained backwards compatibility\n // when bumping to helmet v5, we could remove this as well as\n // skip setting `useDefaults: false` in the future.\n delete result['form-action'];\n\n if (directives) {\n for (const [key, value] of Object.entries(directives)) {\n if (value === false) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n }\n\n return result;\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { CorsOptions } from 'cors';\nimport { Minimatch } from 'minimatch';\n\n/**\n * Attempts to read a CORS options object from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A CORS options object, or undefined if no cors configuration is present.\n *\n * @example\n * ```ts\n * const corsOptions = readCorsOptions(config.getConfig('backend'));\n * ```\n */\nexport function readCorsOptions(config?: Config): CorsOptions {\n const cc = config?.getOptionalConfig('cors');\n if (!cc) {\n return { origin: false }; // Disable CORS\n }\n\n return removeUnknown({\n origin: createCorsOriginMatcher(readStringArray(cc, 'origin')),\n methods: readStringArray(cc, 'methods'),\n allowedHeaders: readStringArray(cc, 'allowedHeaders'),\n exposedHeaders: readStringArray(cc, 'exposedHeaders'),\n credentials: cc.getOptionalBoolean('credentials'),\n maxAge: cc.getOptionalNumber('maxAge'),\n preflightContinue: cc.getOptionalBoolean('preflightContinue'),\n optionsSuccessStatus: cc.getOptionalNumber('optionsSuccessStatus'),\n });\n}\n\nfunction removeUnknown<T extends object>(obj: T): T {\n return Object.fromEntries(\n Object.entries(obj).filter(([, v]) => v !== undefined),\n ) as T;\n}\n\nfunction readStringArray(config: Config, key: string): string[] | undefined {\n const value = config.getOptional(key);\n if (typeof value === 'string') {\n return [value];\n } else if (!value) {\n return undefined;\n }\n return config.getStringArray(key);\n}\n\nfunction createCorsOriginMatcher(allowedOriginPatterns: string[] | undefined) {\n if (!allowedOriginPatterns) {\n return undefined;\n }\n\n const allowedOriginMatchers = allowedOriginPatterns.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n );\n\n return (\n origin: string | undefined,\n callback: (\n err: Error | null,\n origin: boolean | string | RegExp | (boolean | string | RegExp)[],\n ) => void,\n ) => {\n return callback(\n null,\n allowedOriginMatchers.some(pattern => pattern.match(origin ?? '')),\n );\n };\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigService, LoggerService } from '@backstage/backend-plugin-api';\nimport {\n Request,\n Response,\n ErrorRequestHandler,\n NextFunction,\n RequestHandler,\n} from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport morgan from 'morgan';\nimport compression from 'compression';\nimport { readHelmetOptions } from './readHelmetOptions';\nimport { readCorsOptions } from './readCorsOptions';\nimport {\n AuthenticationError,\n ConflictError,\n ErrorResponseBody,\n InputError,\n NotAllowedError,\n NotFoundError,\n NotModifiedError,\n ServiceUnavailableError,\n serializeError,\n} from '@backstage/errors';\nimport { NotImplementedError } from '@backstage/errors';\n\n/**\n * Options used to create a {@link MiddlewareFactory}.\n *\n * @public\n */\nexport interface MiddlewareFactoryOptions {\n config: ConfigService;\n logger: LoggerService;\n}\n\n/**\n * Options passed to the {@link MiddlewareFactory.error} middleware.\n *\n * @public\n */\nexport interface MiddlewareFactoryErrorOptions {\n /**\n * Whether error response bodies should show error stack traces or not.\n *\n * If not specified, by default shows stack traces only in development mode.\n */\n showStackTraces?: boolean;\n\n /**\n * Whether any 4xx errors should be logged or not.\n *\n * If not specified, default to only logging 5xx errors.\n */\n logAllErrors?: boolean;\n}\n\n/**\n * A utility to configure common middleware.\n *\n * @public\n */\nexport class MiddlewareFactory {\n #config: ConfigService;\n #logger: LoggerService;\n\n /**\n * Creates a new {@link MiddlewareFactory}.\n */\n static create(options: MiddlewareFactoryOptions) {\n return new MiddlewareFactory(options);\n }\n\n private constructor(options: MiddlewareFactoryOptions) {\n this.#config = options.config;\n this.#logger = options.logger;\n }\n\n /**\n * Returns a middleware that unconditionally produces a 404 error response.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the end of the chain, such\n * that it's the last one attempted after no other routes matched.\n *\n * @returns An Express request handler\n */\n notFound(): RequestHandler {\n return (_req: Request, res: Response) => {\n res.status(404).end();\n };\n }\n\n /**\n * Returns the compression middleware.\n *\n * @remarks\n *\n * The middleware will attempt to compress response bodies for all requests\n * that traverse through the middleware.\n */\n compression(): RequestHandler {\n return compression();\n }\n\n /**\n * Returns a request logging middleware.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the start of the chain, such\n * that it always logs requests whether they are \"caught\" by handlers farther\n * down or not.\n *\n * @returns An Express request handler\n */\n logging(): RequestHandler {\n const logger = this.#logger.child({\n type: 'incomingRequest',\n });\n\n return morgan('combined', {\n stream: {\n write(message: string) {\n logger.info(message.trimEnd());\n },\n },\n });\n }\n\n /**\n * Returns a middleware that implements the helmet library.\n *\n * @remarks\n *\n * This middleware applies security policies to incoming requests and outgoing\n * responses. It is configured using config keys such as `backend.csp`.\n *\n * @see {@link https://helmetjs.github.io/}\n *\n * @returns An Express request handler\n */\n helmet(): RequestHandler {\n return helmet(readHelmetOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements the cors library.\n *\n * @remarks\n *\n * This middleware handles CORS. It is configured using the config key\n * `backend.cors`.\n *\n * @see {@link https://github.com/expressjs/cors}\n *\n * @returns An Express request handler\n */\n cors(): RequestHandler {\n return cors(readCorsOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Express middleware to handle errors during request processing.\n *\n * @remarks\n *\n * This is commonly the very last middleware in the chain.\n *\n * Its primary purpose is not to do translation of business logic exceptions,\n * but rather to be a global catch-all for uncaught \"fatal\" errors that are\n * expected to result in a 500 error. However, it also does handle some common\n * error types (such as http-error exceptions, and the well-known error types\n * in the `@backstage/errors` package) and returns the enclosed status code\n * accordingly.\n *\n * It will also produce a response body with a serialized form of the error,\n * unless a previous handler already did send a body. See\n * {@link @backstage/errors#ErrorResponseBody} for the response shape used.\n *\n * @returns An Express error request handler\n */\n error(options: MiddlewareFactoryErrorOptions = {}): ErrorRequestHandler {\n const showStackTraces =\n options.showStackTraces ?? process.env.NODE_ENV === 'development';\n\n const logger = this.#logger.child({\n type: 'errorHandler',\n });\n\n return (error: Error, req: Request, res: Response, next: NextFunction) => {\n const statusCode = getStatusCode(error);\n if (options.logAllErrors || statusCode >= 500) {\n logger.error(`Request failed with status ${statusCode}`, error);\n }\n\n if (res.headersSent) {\n // If the headers have already been sent, do not send the response again\n // as this will throw an error in the backend.\n next(error);\n return;\n }\n\n const body: ErrorResponseBody = {\n error: serializeError(error, { includeStack: showStackTraces }),\n request: { method: req.method, url: req.url },\n response: { statusCode },\n };\n\n res.status(statusCode).json(body);\n };\n }\n}\n\nfunction getStatusCode(error: Error): number {\n // Look for common http library status codes\n const knownStatusCodeFields = ['statusCode', 'status'];\n for (const field of knownStatusCodeFields) {\n const statusCode = (error as any)[field];\n if (\n typeof statusCode === 'number' &&\n (statusCode | 0) === statusCode && // is whole integer\n statusCode >= 100 &&\n statusCode <= 599\n ) {\n return statusCode;\n }\n }\n\n // Handle well-known error types\n switch (error.name) {\n case NotModifiedError.name:\n return 304;\n case InputError.name:\n return 400;\n case AuthenticationError.name:\n return 401;\n case NotAllowedError.name:\n return 403;\n case NotFoundError.name:\n return 404;\n case ConflictError.name:\n return 409;\n case NotImplementedError.name:\n return 501;\n case ServiceUnavailableError.name:\n return 503;\n default:\n break;\n }\n\n // Fall back to internal server error\n return 500;\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Escapes a given string to be used inside a RegExp.\n *\n * Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n */\nexport const escapeRegExp = (text: string) => {\n return text.replace(/[.*+?^${}(\\)|[\\]\\\\]/g, '\\\\$&');\n};\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n LoggerService,\n RootLoggerService,\n} from '@backstage/backend-plugin-api';\nimport { JsonObject } from '@backstage/types';\nimport { Format, TransformableInfo } from 'logform';\nimport {\n Logger,\n format,\n createLogger,\n transports,\n transport as Transport,\n} from 'winston';\nimport { escapeRegExp } from '../lib/escapeRegExp';\n\n/**\n * @public\n */\nexport interface WinstonLoggerOptions {\n meta?: JsonObject;\n level: string;\n format: Format;\n transports: Transport[];\n}\n\n/**\n * A {@link @backstage/backend-plugin-api#LoggerService} implementation based on winston.\n *\n * @public\n */\nexport class WinstonLogger implements RootLoggerService {\n #winston: Logger;\n #addRedactions?: (redactions: Iterable<string>) => void;\n\n /**\n * Creates a {@link WinstonLogger} instance.\n */\n static create(options: WinstonLoggerOptions): WinstonLogger {\n const redacter = WinstonLogger.redacter();\n\n let logger = createLogger({\n level: options.level,\n format: format.combine(redacter.format, options.format),\n transports: options.transports ?? new transports.Console(),\n });\n if (options.meta) {\n logger = logger.child(options.meta);\n }\n\n return new WinstonLogger(logger, redacter.add);\n }\n\n /**\n * Creates a winston log formatter for redacting secrets.\n */\n static redacter(): {\n format: Format;\n add: (redactions: Iterable<string>) => void;\n } {\n const redactionSet = new Set<string>();\n\n let redactionPattern: RegExp | undefined = undefined;\n\n return {\n format: format(info => {\n if (redactionPattern && typeof info.message === 'string') {\n info.message = info.message.replace(redactionPattern, '[REDACTED]');\n }\n return info;\n })(),\n add(newRedactions) {\n let added = 0;\n for (const redaction of newRedactions) {\n // Exclude secrets that are empty or just one character in length. These\n // typically mean that you are running local dev or tests, or using the\n // --lax flag which sets things to just 'x'.\n if (redaction.length <= 1) {\n continue;\n }\n if (!redactionSet.has(redaction)) {\n redactionSet.add(redaction);\n added += 1;\n }\n }\n if (added > 0) {\n const redactions = Array.from(redactionSet)\n .map(r => escapeRegExp(r))\n .join('|');\n redactionPattern = new RegExp(`(${redactions})`, 'g');\n }\n },\n };\n }\n\n /**\n * Creates a pretty printed winston log formatter.\n */\n static colorFormat(): Format {\n const colorizer = format.colorize();\n\n return format.combine(\n format.timestamp(),\n format.colorize({\n colors: {\n timestamp: 'dim',\n prefix: 'blue',\n field: 'cyan',\n debug: 'grey',\n },\n }),\n format.printf((info: TransformableInfo) => {\n const { timestamp, level, message, plugin, service, ...fields } = info;\n const prefix = plugin || service;\n const timestampColor = colorizer.colorize('timestamp', timestamp);\n const prefixColor = colorizer.colorize('prefix', prefix);\n\n const extraFields = Object.entries(fields)\n .map(\n ([key, value]) =>\n `${colorizer.colorize('field', `${key}`)}=${value}`,\n )\n .join(' ');\n\n return `${timestampColor} ${prefixColor} ${level} ${message} ${extraFields}`;\n }),\n );\n }\n\n private constructor(\n winston: Logger,\n addRedactions?: (redactions: Iterable<string>) => void,\n ) {\n this.#winston = winston;\n this.#addRedactions = addRedactions;\n }\n\n error(message: string, meta?: JsonObject): void {\n this.#winston.error(message, meta);\n }\n\n warn(message: string, meta?: JsonObject): void {\n this.#winston.warn(message, meta);\n }\n\n info(message: string, meta?: JsonObject): void {\n this.#winston.info(message, meta);\n }\n\n debug(message: string, meta?: JsonObject): void {\n this.#winston.debug(message, meta);\n }\n\n child(meta: JsonObject): LoggerService {\n return new WinstonLogger(this.#winston.child(meta));\n }\n\n addRedactions(redactions: Iterable<string>) {\n this.#addRedactions?.(redactions);\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n LifecycleServiceStartupHook,\n LifecycleServiceStartupOptions,\n LifecycleServiceShutdownHook,\n LifecycleServiceShutdownOptions,\n RootLifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class BackendLifecycleImpl implements RootLifecycleService {\n constructor(private readonly logger: LoggerService) {}\n\n #hasStarted = false;\n #startupTasks: Array<{\n hook: LifecycleServiceStartupHook;\n options?: LifecycleServiceStartupOptions;\n }> = [];\n\n addStartupHook(\n hook: LifecycleServiceStartupHook,\n options?: LifecycleServiceStartupOptions,\n ): void {\n if (this.#hasStarted) {\n throw new Error('Attempted to add startup hook after startup');\n }\n this.#startupTasks.push({ hook, options });\n }\n\n async startup(): Promise<void> {\n if (this.#hasStarted) {\n return;\n }\n this.#hasStarted = true;\n\n this.logger.debug(`Running ${this.#startupTasks.length} startup tasks...`);\n await Promise.all(\n this.#startupTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Startup hook succeeded`);\n } catch (error) {\n logger.error(`Startup hook failed, ${error}`);\n }\n }),\n );\n }\n\n #hasShutdown = false;\n #shutdownTasks: Array<{\n hook: LifecycleServiceShutdownHook;\n options?: LifecycleServiceShutdownOptions;\n }> = [];\n\n addShutdownHook(\n hook: LifecycleServiceShutdownHook,\n options?: LifecycleServiceShutdownOptions,\n ): void {\n if (this.#hasShutdown) {\n throw new Error('Attempted to add shutdown hook after shutdown');\n }\n this.#shutdownTasks.push({ hook, options });\n }\n\n async shutdown(): Promise<void> {\n if (this.#hasShutdown) {\n return;\n }\n this.#hasShutdown = true;\n\n this.logger.debug(\n `Running ${this.#shutdownTasks.length} shutdown tasks...`,\n );\n await Promise.all(\n this.#shutdownTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Shutdown hook succeeded`);\n } catch (error) {\n logger.error(`Shutdown hook failed, ${error}`);\n }\n }),\n );\n }\n}\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n *\n * @public\n */\nexport const rootLifecycleServiceFactory = createServiceFactory({\n service: coreServices.rootLifecycle,\n deps: {\n logger: coreServices.rootLogger,\n },\n async factory({ logger }) {\n return new BackendLifecycleImpl(logger);\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n LifecycleService,\n LifecycleServiceShutdownHook,\n LifecycleServiceShutdownOptions,\n LifecycleServiceStartupHook,\n LifecycleServiceStartupOptions,\n LoggerService,\n PluginMetadataService,\n RootLifecycleService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class BackendPluginLifecycleImpl implements LifecycleService {\n constructor(\n private readonly logger: LoggerService,\n private readonly rootLifecycle: RootLifecycleService,\n private readonly pluginMetadata: PluginMetadataService,\n ) {}\n\n #hasStarted = false;\n #startupTasks: Array<{\n hook: LifecycleServiceStartupHook;\n options?: LifecycleServiceStartupOptions;\n }> = [];\n\n addStartupHook(\n hook: LifecycleServiceStartupHook,\n options?: LifecycleServiceStartupOptions,\n ): void {\n if (this.#hasStarted) {\n throw new Error('Attempted to add startup hook after startup');\n }\n this.#startupTasks.push({ hook, options });\n }\n\n async startup(): Promise<void> {\n if (this.#hasStarted) {\n return;\n }\n this.#hasStarted = true;\n\n this.logger.debug(\n `Running ${this.#startupTasks.length} plugin startup tasks...`,\n );\n await Promise.all(\n this.#startupTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Plugin startup hook succeeded`);\n } catch (error) {\n logger.error(`Plugin startup hook failed, ${error}`);\n }\n }),\n );\n }\n\n addShutdownHook(\n hook: LifecycleServiceShutdownHook,\n options?: LifecycleServiceShutdownOptions,\n ): void {\n const plugin = this.pluginMetadata.getId();\n this.rootLifecycle.addShutdownHook(hook, {\n logger: options?.logger?.child({ plugin }) ?? this.logger,\n });\n }\n}\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n * @public\n */\nexport const lifecycleServiceFactory = createServiceFactory({\n service: coreServices.lifecycle,\n deps: {\n logger: coreServices.logger,\n rootLifecycle: coreServices.rootLifecycle,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ rootLifecycle, logger, pluginMetadata }) {\n return new BackendPluginLifecycleImpl(\n logger,\n rootLifecycle,\n pluginMetadata,\n );\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n} from '@backstage/backend-plugin-api';\nimport { BackendLifecycleImpl } from '../services/implementations/rootLifecycle/rootLifecycleServiceFactory';\nimport { BackendPluginLifecycleImpl } from '../services/implementations/lifecycle/lifecycleServiceFactory';\nimport { EnumerableServiceHolder, ServiceOrExtensionPoint } from './types';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-forbidden-package-imports\nimport { InternalBackendFeature } from '@backstage/backend-plugin-api/src/wiring/types';\nimport { ForwardedError } from '@backstage/errors';\n\nexport interface BackendRegisterInit {\n consumes: Set<ServiceOrExtensionPoint>;\n provides: Set<ServiceOrExtensionPoint>;\n init: {\n deps: { [name: string]: ServiceOrExtensionPoint };\n func: (deps: { [name: string]: unknown }) => Promise<void>;\n };\n}\n\nexport class BackendInitializer {\n #startPromise?: Promise<void>;\n #features = new Array<InternalBackendFeature>();\n #extensionPoints = new Map<ExtensionPoint<unknown>, unknown>();\n #serviceHolder: EnumerableServiceHolder;\n\n constructor(serviceHolder: EnumerableServiceHolder) {\n this.#serviceHolder = serviceHolder;\n }\n\n async #getInitDeps(\n deps: { [name: string]: ServiceOrExtensionPoint },\n pluginId: string,\n ) {\n const result = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(deps)) {\n const extensionPoint = this.#extensionPoints.get(\n ref as ExtensionPoint<unknown>,\n );\n if (extensionPoint) {\n result.set(name, extensionPoint);\n } else {\n const impl = await this.#serviceHolder.get(\n ref as ServiceRef<unknown>,\n pluginId,\n );\n if (impl) {\n result.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No extension point or service available for the following ref(s): ${missing}`,\n );\n }\n\n return Object.fromEntries(result);\n }\n\n add(feature: BackendFeature) {\n if (this.#startPromise) {\n throw new Error('feature can not be added after the backend has started');\n }\n if (feature.$$type !== '@backstage/BackendFeature') {\n throw new Error(\n `Failed to add feature, invalid type '${feature.$$type}'`,\n );\n }\n const internalFeature = feature as InternalBackendFeature;\n if (internalFeature.version !== 'v1') {\n throw new Error(\n `Failed to add feature, invalid version '${internalFeature.version}'`,\n );\n }\n this.#features.push(internalFeature);\n }\n\n async start(): Promise<void> {\n if (this.#startPromise) {\n throw new Error('Backend has already started');\n }\n\n const exitHandler = async () => {\n process.removeListener('SIGTERM', exitHandler);\n process.removeListener('SIGINT', exitHandler);\n process.removeListener('beforeExit', exitHandler);\n\n try {\n await this.stop();\n process.exit(0);\n } catch (error) {\n console.error(error);\n process.exit(1);\n }\n };\n\n process.addListener('SIGTERM', exitHandler);\n process.addListener('SIGINT', exitHandler);\n process.addListener('beforeExit', exitHandler);\n\n this.#startPromise = this.#doStart();\n await this.#startPromise;\n }\n\n async #doStart(): Promise<void> {\n // Initialize all root scoped services\n for (const ref of this.#serviceHolder.getServiceRefs()) {\n if (ref.scope === 'root') {\n await this.#serviceHolder.get(ref, 'root');\n }\n }\n\n const pluginInits = new Map<string, BackendRegisterInit>();\n const moduleInits = new Map<string, Map<string, BackendRegisterInit>>();\n\n // Enumerate all features\n for (const feature of this.#features) {\n for (const r of feature.getRegistrations()) {\n const provides = new Set<ExtensionPoint<unknown>>();\n\n if (r.type === 'plugin') {\n for (const [extRef, extImpl] of r.extensionPoints) {\n if (this.#extensionPoints.has(extRef)) {\n throw new Error(\n `ExtensionPoint with ID '${extRef.id}' is already registered`,\n );\n }\n this.#extensionPoints.set(extRef, extImpl);\n provides.add(extRef);\n }\n }\n\n if (r.type === 'plugin') {\n if (pluginInits.has(r.pluginId)) {\n throw new Error(`Plugin '${r.pluginId}' is already registered`);\n }\n pluginInits.set(r.pluginId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n } else {\n let modules = moduleInits.get(r.pluginId);\n if (!modules) {\n modules = new Map();\n moduleInits.set(r.pluginId, modules);\n }\n if (modules.has(r.moduleId)) {\n throw new Error(\n `Module '${r.moduleId}' for plugin '${r.pluginId}' is already registered`,\n );\n }\n modules.set(r.moduleId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n }\n }\n }\n\n const allPluginIds = [\n ...new Set([...pluginInits.keys(), ...moduleInits.keys()]),\n ];\n\n // All plugins are initialized in parallel\n await Promise.all(\n allPluginIds.map(async pluginId => {\n // Modules are initialized before plugins, so that they can provide extension to the plugin\n const modules = moduleInits.get(pluginId) ?? [];\n await Promise.all(\n Array.from(modules).map(async ([moduleId, moduleInit]) => {\n const moduleDeps = await this.#getInitDeps(\n moduleInit.init.deps,\n pluginId,\n );\n await moduleInit.init.func(moduleDeps).catch(error => {\n throw new ForwardedError(\n `Module '${moduleId}' for plugin '${pluginId}' startup failed`,\n error,\n );\n });\n }),\n );\n\n // Once all modules have been initialized, we can initialize the plugin itself\n const pluginInit = pluginInits.get(pluginId);\n // We allow modules to be installed without the accompanying plugin, so the plugin may not exist\n if (pluginInit) {\n const pluginDeps = await this.#getInitDeps(\n pluginInit.init.deps,\n pluginId,\n );\n await pluginInit.init.func(pluginDeps).catch(error => {\n throw new ForwardedError(\n `Plugin '${pluginId}' startup failed`,\n error,\n );\n });\n }\n\n // Once the plugin and all modules have been initialized, we can signal that the plugin has stared up successfully\n const lifecycleService = await this.#getPluginLifecycleImpl(pluginId);\n await lifecycleService.startup();\n }),\n );\n\n // Once all plugins and modules have been initialized, we can signal that the backend has started up successfully\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.startup();\n\n // Once the backend is started, any uncaught errors or unhandled rejections are caught\n // and logged, in order to avoid crashing the entire backend on local failures.\n if (process.env.NODE_ENV !== 'test') {\n const rootLogger = await this.#serviceHolder.get(\n coreServices.rootLogger,\n 'root',\n );\n process.on('unhandledRejection', (reason: Error) => {\n rootLogger\n ?.child({ type: 'unhandledRejection' })\n ?.error('Unhandled rejection', reason);\n });\n process.on('uncaughtException', error => {\n rootLogger\n ?.child({ type: 'uncaughtException' })\n ?.error('Uncaught exception', error);\n });\n }\n }\n\n async stop(): Promise<void> {\n if (!this.#startPromise) {\n return;\n }\n await this.#startPromise;\n\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.shutdown();\n }\n\n // Bit of a hacky way to grab the lifecycle services, potentially find a nicer way to do this\n async #getRootLifecycleImpl(): Promise<BackendLifecycleImpl> {\n const lifecycleService = await this.#serviceHolder.get(\n coreServices.rootLifecycle,\n 'root',\n );\n if (lifecycleService instanceof BackendLifecycleImpl) {\n return lifecycleService;\n }\n throw new Error('Unexpected root lifecycle service implementation');\n }\n\n async #getPluginLifecycleImpl(\n pluginId: string,\n ): Promise<BackendPluginLifecycleImpl> {\n const lifecycleService = await this.#serviceHolder.get(\n coreServices.lifecycle,\n pluginId,\n );\n if (lifecycleService instanceof BackendPluginLifecycleImpl) {\n return lifecycleService;\n }\n throw new Error('Unexpected plugin lifecycle service implementation');\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ServiceFactory,\n ServiceRef,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { stringifyError } from '@backstage/errors';\nimport { EnumerableServiceHolder } from './types';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-forbidden-package-imports\nimport { InternalServiceFactory } from '@backstage/backend-plugin-api/src/services/system/types';\n/**\n * Keep in sync with `@backstage/backend-plugin-api/src/services/system/types.ts`\n * @internal\n */\nexport type InternalServiceRef = ServiceRef<unknown> & {\n __defaultFactory?: (\n service: ServiceRef<unknown>,\n ) => Promise<ServiceFactory | (() => ServiceFactory)>;\n};\n\nfunction toInternalServiceFactory<TService, TScope extends 'plugin' | 'root'>(\n factory: ServiceFactory<TService, TScope>,\n): InternalServiceFactory<TService, TScope> {\n const f = factory as InternalServiceFactory<TService, TScope>;\n if (f.$$type !== '@backstage/ServiceFactory') {\n throw new Error(`Invalid service factory, bad type '${f.$$type}'`);\n }\n if (f.version !== 'v1') {\n throw new Error(`Invalid service factory, bad version '${f.version}'`);\n }\n return f;\n}\n\nconst pluginMetadataServiceFactory = createServiceFactory(\n (options: { pluginId: string }) => ({\n service: coreServices.pluginMetadata,\n deps: {},\n factory: async () => ({ getId: () => options.pluginId }),\n }),\n);\n\nexport class ServiceRegistry implements EnumerableServiceHolder {\n readonly #providedFactories: Map<string, InternalServiceFactory>;\n readonly #loadedDefaultFactories: Map<\n Function,\n Promise<InternalServiceFactory>\n >;\n readonly #implementations: Map<\n InternalServiceFactory,\n {\n context: Promise<unknown>;\n byPlugin: Map<string, Promise<unknown>>;\n }\n >;\n readonly #rootServiceImplementations = new Map<\n InternalServiceFactory,\n Promise<unknown>\n >();\n\n constructor(factories: Array<ServiceFactory>) {\n this.#providedFactories = new Map(\n factories.map(sf => [sf.service.id, toInternalServiceFactory(sf)]),\n );\n this.#loadedDefaultFactories = new Map();\n this.#implementations = new Map();\n }\n\n #resolveFactory(\n ref: ServiceRef<unknown>,\n pluginId: string,\n ): Promise<InternalServiceFactory> | undefined {\n // Special case handling of the plugin metadata service, generating a custom factory for it each time\n if (ref.id === coreServices.pluginMetadata.id) {\n return Promise.resolve(\n toInternalServiceFactory(pluginMetadataServiceFactory({ pluginId })),\n );\n }\n\n let resolvedFactory:\n | Promise<InternalServiceFactory>\n | InternalServiceFactory\n | undefined = this.#providedFactories.get(ref.id);\n const { __defaultFactory: defaultFactory } = ref as InternalServiceRef;\n if (!resolvedFactory && !defaultFactory) {\n return undefined;\n }\n\n if (!resolvedFactory) {\n let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory!);\n if (!loadedFactory) {\n loadedFactory = Promise.resolve()\n .then(() => defaultFactory!(ref))\n .then(f =>\n toInternalServiceFactory(typeof f === 'function' ? f() : f),\n );\n this.#loadedDefaultFactories.set(defaultFactory!, loadedFactory);\n }\n resolvedFactory = loadedFactory.catch(error => {\n throw new Error(\n `Failed to instantiate service '${\n ref.id\n }' because the default factory loader threw an error, ${stringifyError(\n error,\n )}`,\n );\n });\n }\n\n return Promise.resolve(resolvedFactory);\n }\n\n #checkForMissingDeps(factory: InternalServiceFactory, pluginId: string) {\n const missingDeps = Object.values(factory.deps).filter(ref => {\n if (ref.id === coreServices.pluginMetadata.id) {\n return false;\n }\n if (this.#providedFactories.get(ref.id)) {\n return false;\n }\n\n return !(ref as InternalServiceRef).__defaultFactory;\n });\n\n if (missingDeps.length) {\n const missing = missingDeps.map(r => `'${r.id}'`).join(', ');\n throw new Error(\n `Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`,\n );\n }\n }\n\n getServiceRefs(): ServiceRef<unknown>[] {\n return Array.from(this.#providedFactories.values()).map(f => f.service);\n }\n\n get<T>(ref: ServiceRef<T>, pluginId: string): Promise<T> | undefined {\n return this.#resolveFactory(ref, pluginId)?.then(factory => {\n if (factory.service.scope === 'root') {\n let existing = this.#rootServiceImplementations.get(factory);\n if (!existing) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope !== 'root') {\n throw new Error(\n `Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`,\n );\n }\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n\n existing = Promise.all(rootDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), undefined),\n );\n this.#rootServiceImplementations.set(factory, existing);\n }\n return existing as Promise<T>;\n }\n\n let implementation = this.#implementations.get(factory);\n if (!implementation) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope === 'root') {\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n }\n\n implementation = {\n context: Promise.all(rootDeps)\n .then(entries =>\n factory.createRootContext?.(Object.fromEntries(entries)),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' because createRootContext threw an error, ${cause}`,\n );\n }),\n byPlugin: new Map(),\n };\n\n this.#implementations.set(factory, implementation);\n }\n\n let result = implementation.byPlugin.get(pluginId) as Promise<any>;\n if (!result) {\n const allDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n const target = this.get(serviceRef, pluginId)!;\n allDeps.push(target.then(impl => [name, impl]));\n }\n\n result = implementation.context\n .then(context =>\n Promise.all(allDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), context),\n ),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`,\n );\n });\n implementation.byPlugin.set(pluginId, result);\n }\n\n return result;\n });\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ServiceFactory, BackendFeature } from '@backstage/backend-plugin-api';\nimport { BackendInitializer } from './BackendInitializer';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport { Backend } from './types';\n\nexport class BackstageBackend implements Backend {\n #services: ServiceRegistry;\n #initializer: BackendInitializer;\n\n constructor(apiFactories: ServiceFactory[]) {\n this.#services = new ServiceRegistry(apiFactories);\n this.#initializer = new BackendInitializer(this.#services);\n }\n\n add(feature: BackendFeature): void {\n this.#initializer.add(feature);\n }\n\n async start(): Promise<void> {\n await this.#initializer.start();\n }\n\n async stop(): Promise<void> {\n await this.#initializer.stop();\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { coreServices } from '@backstage/backend-plugin-api';\nimport { BackstageBackend } from './BackstageBackend';\nimport { Backend, CreateSpecializedBackendOptions } from './types';\n\n/**\n * @public\n */\nexport function createSpecializedBackend(\n options: CreateSpecializedBackendOptions,\n): Backend {\n const services = options.services.map(sf =>\n typeof sf === 'function' ? sf() : sf,\n );\n\n const exists = new Set<string>();\n const duplicates = new Set<string>();\n for (const { service } of services) {\n if (exists.has(service.id)) {\n duplicates.add(service.id);\n } else {\n exists.add(service.id);\n }\n }\n if (duplicates.size > 0) {\n const ids = Array.from(duplicates).join(', ');\n throw new Error(`Duplicate service implementations provided for ${ids}`);\n }\n if (exists.has(coreServices.pluginMetadata.id)) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n return new BackstageBackend(services);\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CacheManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const cacheServiceFactory = createServiceFactory({\n service: coreServices.cache,\n deps: {\n config: coreServices.config,\n plugin: coreServices.pluginMetadata,\n },\n async createRootContext({ config }) {\n return CacheManager.fromConfig(config);\n },\n async factory({ plugin }, manager) {\n return manager.forPlugin(plugin.getId()).getClient();\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n ConfigSources,\n RemoteConfigSourceOptions,\n} from '@backstage/config-loader';\n\n/** @public */\nexport interface ConfigFactoryOptions {\n /**\n * Process arguments to use instead of the default `process.argv()`.\n */\n argv?: string[];\n\n /**\n * Enables and sets options for remote configuration loading.\n */\n remote?: Pick<RemoteConfigSourceOptions, 'reloadInterval'>;\n}\n\n/** @public */\nexport const configServiceFactory = createServiceFactory(\n (options?: ConfigFactoryOptions) => ({\n service: coreServices.config,\n deps: {},\n async factory() {\n const source = ConfigSources.default({\n argv: options?.argv,\n remote: options?.remote,\n });\n console.log(`Loading config from ${source}`);\n return await ConfigSources.toConfig(source);\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ConfigReader } from '@backstage/config';\n\n/** @public */\nexport const databaseServiceFactory = createServiceFactory({\n service: coreServices.database,\n deps: {\n config: coreServices.config,\n lifecycle: coreServices.lifecycle,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async createRootContext({ config }) {\n return config.getOptional('backend.database')\n ? DatabaseManager.fromConfig(config)\n : DatabaseManager.fromConfig(\n new ConfigReader({\n backend: {\n database: { client: 'better-sqlite3', connection: ':memory:' },\n },\n }),\n );\n },\n async factory({ pluginMetadata, lifecycle }, databaseManager) {\n return databaseManager.forPlugin(pluginMetadata.getId(), {\n pluginMetadata,\n lifecycle,\n });\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HostDiscovery } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const discoveryServiceFactory = createServiceFactory({\n service: coreServices.discovery,\n deps: {\n config: coreServices.config,\n },\n async factory({ config }) {\n return HostDiscovery.fromConfig(config);\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LifecycleService } from '@backstage/backend-plugin-api';\nimport { ServiceUnavailableError } from '@backstage/errors';\nimport { HumanDuration, durationToMilliseconds } from '@backstage/types';\nimport { RequestHandler } from 'express';\n\nexport const DEFAULT_TIMEOUT = { seconds: 5 };\n\n/**\n * Options for {@link createLifecycleMiddleware}.\n * @public\n */\nexport interface LifecycleMiddlewareOptions {\n lifecycle: LifecycleService;\n /**\n * The maximum time that paused requests will wait for the service to start, before returning an error.\n *\n * Defaults to 5 seconds.\n */\n startupRequestPauseTimeout?: HumanDuration;\n}\n\n/**\n * Creates a middleware that pauses requests until the service has started.\n *\n * @remarks\n *\n * Requests that arrive before the service has started will be paused until startup is complete.\n * If the service does not start within the provided timeout, the request will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * If the service is shutting down, all requests will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * @public\n */\nexport function createLifecycleMiddleware(\n options: LifecycleMiddlewareOptions,\n): RequestHandler {\n const { lifecycle, startupRequestPauseTimeout = DEFAULT_TIMEOUT } = options;\n\n let state: 'init' | 'up' | 'down' = 'init';\n const waiting = new Set<{\n next: (err?: Error) => void;\n timeout: NodeJS.Timeout;\n }>();\n\n lifecycle.addStartupHook(async () => {\n if (state === 'init') {\n state = 'up';\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next();\n }\n waiting.clear();\n }\n });\n\n lifecycle.addShutdownHook(async () => {\n state = 'down';\n\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next(new ServiceUnavailableError('Service is shutting down'));\n }\n waiting.clear();\n });\n\n const timeoutMs = durationToMilliseconds(startupRequestPauseTimeout);\n\n return (_req, _res, next) => {\n if (state === 'up') {\n next();\n return;\n } else if (state === 'down') {\n next(new ServiceUnavailableError('Service is shutting down'));\n return;\n }\n\n const item = {\n next,\n timeout: setTimeout(() => {\n if (waiting.delete(item)) {\n next(new ServiceUnavailableError('Service has not started up yet'));\n }\n }, timeoutMs),\n };\n\n waiting.add(item);\n };\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { Handler } from 'express';\nimport PromiseRouter from 'express-promise-router';\nimport { createLifecycleMiddleware } from './createLifecycleMiddleware';\n\n/**\n * @public\n */\nexport interface HttpRouterFactoryOptions {\n /**\n * A callback used to generate the path for each plugin, defaults to `/api/{pluginId}`.\n */\n getPath?(pluginId: string): string;\n}\n\n/** @public */\nexport const httpRouterServiceFactory = createServiceFactory(\n (options?: HttpRouterFactoryOptions) => ({\n service: coreServices.httpRouter,\n deps: {\n plugin: coreServices.pluginMetadata,\n lifecycle: coreServices.lifecycle,\n rootHttpRouter: coreServices.rootHttpRouter,\n },\n async factory({ plugin, rootHttpRouter, lifecycle }) {\n const getPath = options?.getPath ?? (id => `/api/${id}`);\n const path = getPath(plugin.getId());\n\n const router = PromiseRouter();\n rootHttpRouter.use(path, router);\n\n router.use(createLifecycleMiddleware({ lifecycle }));\n\n return {\n use(handler: Handler) {\n router.use(handler);\n },\n };\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { DefaultIdentityClient } from '@backstage/plugin-auth-node';\n\n/**\n * An identity client options object which allows extra configurations\n *\n * @public\n */\nexport type IdentityFactoryOptions = {\n issuer?: string;\n\n /** JWS \"alg\" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.\n * More info on supported algorithms: https://github.com/panva/jose */\n algorithms?: string[];\n};\n\n/** @public */\nexport const identityServiceFactory = createServiceFactory(\n (options?: IdentityFactoryOptions) => ({\n service: coreServices.identity,\n deps: {\n discovery: coreServices.discovery,\n },\n async factory({ discovery }) {\n return DefaultIdentityClient.create({ discovery, ...options });\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const loggerServiceFactory = createServiceFactory({\n service: coreServices.logger,\n deps: {\n rootLogger: coreServices.rootLogger,\n plugin: coreServices.pluginMetadata,\n },\n factory({ rootLogger, plugin }) {\n return rootLogger.child({ plugin: plugin.getId() });\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerPermissionClient } from '@backstage/plugin-permission-node';\n\n/** @public */\nexport const permissionsServiceFactory = createServiceFactory({\n service: coreServices.permissions,\n deps: {\n config: coreServices.config,\n discovery: coreServices.discovery,\n tokenManager: coreServices.tokenManager,\n },\n async factory({ config, discovery, tokenManager }) {\n return ServerPermissionClient.fromConfig(config, {\n discovery,\n tokenManager,\n });\n },\n});\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RootHttpRouterService } from '@backstage/backend-plugin-api';\nimport { Handler, Router } from 'express';\nimport trimEnd from 'lodash/trimEnd';\n\nfunction normalizePath(path: string): string {\n return `${trimEnd(path, '/')}/`;\n}\n\n/**\n * Options for the {@link DefaultRootHttpRouter} class.\n *\n * @public\n */\nexport interface DefaultRootHttpRouterOptions {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n}\n\n/**\n * The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for\n * {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.\n *\n * @public\n */\nexport class DefaultRootHttpRouter implements RootHttpRouterService {\n #indexPath?: string;\n\n #router = Router();\n #namedRoutes = Router();\n #indexRouter = Router();\n #existingPaths = new Array<string>();\n\n static create(options?: DefaultRootHttpRouterOptions) {\n let indexPath;\n if (options?.indexPath === false) {\n indexPath = undefined;\n } else if (options?.indexPath === undefined) {\n indexPath = '/api/app';\n } else if (options?.indexPath === '') {\n throw new Error('indexPath option may not be an empty string');\n } else {\n indexPath = options.indexPath;\n }\n return new DefaultRootHttpRouter(indexPath);\n }\n\n private constructor(indexPath?: string) {\n this.#indexPath = indexPath;\n this.#router.use(this.#namedRoutes);\n if (this.#indexPath) {\n this.#router.use(this.#indexRouter);\n }\n }\n\n use(path: string, handler: Handler) {\n if (path.match(/^[/\\s]*$/)) {\n throw new Error(`Root router path may not be empty`);\n }\n const conflictingPath = this.#findConflictingPath(path);\n if (conflictingPath) {\n throw new Error(\n `Path ${path} conflicts with the existing path ${conflictingPath}`,\n );\n }\n this.#existingPaths.push(path);\n this.#namedRoutes.use(path, handler);\n\n if (this.#indexPath === path) {\n this.#indexRouter.use(handler);\n }\n }\n\n handler(): Handler {\n return this.#router;\n }\n\n #findConflictingPath(newPath: string): string | undefined {\n const normalizedNewPath = normalizePath(newPath);\n for (const path of this.#existingPaths) {\n const normalizedPath = normalizePath(path);\n if (normalizedPath.startsWith(normalizedNewPath)) {\n return path;\n }\n if (normalizedNewPath.startsWith(normalizedPath)) {\n return path;\n }\n }\n return undefined;\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ConfigService,\n coreServices,\n createServiceFactory,\n LifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport express, { RequestHandler, Express } from 'express';\nimport {\n createHttpServer,\n MiddlewareFactory,\n readHttpServerOptions,\n} from '../../../http';\nimport { DefaultRootHttpRouter } from './DefaultRootHttpRouter';\n\n/**\n * @public\n */\nexport interface RootHttpRouterConfigureContext {\n app: Express;\n middleware: MiddlewareFactory;\n routes: RequestHandler;\n config: ConfigService;\n logger: LoggerService;\n lifecycle: LifecycleService;\n}\n\n/**\n * @public\n */\nexport type RootHttpRouterFactoryOptions = {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n\n configure?(context: RootHttpRouterConfigureContext): void;\n};\n\nfunction defaultConfigure(context: RootHttpRouterConfigureContext) {\n const { app, routes, middleware } = context;\n app.use(middleware.helmet());\n app.use(middleware.cors());\n app.use(middleware.compression());\n app.use(middleware.logging());\n app.use(routes);\n app.use(middleware.notFound());\n app.use(middleware.error());\n}\n\n/** @public */\nexport const rootHttpRouterServiceFactory = createServiceFactory(\n (options?: RootHttpRouterFactoryOptions) => ({\n service: coreServices.rootHttpRouter,\n deps: {\n config: coreServices.config,\n rootLogger: coreServices.rootLogger,\n lifecycle: coreServices.rootLifecycle,\n },\n async factory({ config, rootLogger, lifecycle }) {\n const { indexPath, configure = defaultConfigure } = options ?? {};\n const logger = rootLogger.child({ service: 'rootHttpRouter' });\n const app = express();\n\n const router = DefaultRootHttpRouter.create({ indexPath });\n const middleware = MiddlewareFactory.create({ config, logger });\n\n configure({\n app,\n routes: router.handler(),\n middleware,\n config,\n logger,\n lifecycle,\n });\n\n const server = await createHttpServer(\n app,\n readHttpServerOptions(config.getOptionalConfig('backend')),\n { logger },\n );\n\n lifecycle.addShutdownHook(() => server.stop());\n\n await server.start();\n\n return router;\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { WinstonLogger } from '../../../logging';\nimport { transports, format } from 'winston';\nimport { createConfigSecretEnumerator } from '../../../config';\n\n/** @public */\nexport const rootLoggerServiceFactory = createServiceFactory({\n service: coreServices.rootLogger,\n deps: {\n config: coreServices.config,\n },\n async factory({ config }) {\n const logger = WinstonLogger.create({\n meta: {\n service: 'backstage',\n },\n level: process.env.LOG_LEVEL || 'info',\n format:\n process.env.NODE_ENV === 'production'\n ? format.json()\n : WinstonLogger.colorFormat(),\n transports: [new transports.Console()],\n });\n\n const secretEnumerator = await createConfigSecretEnumerator({ logger });\n logger.addRedactions(secretEnumerator(config));\n config.subscribe?.(() => logger.addRedactions(secretEnumerator(config)));\n\n return logger;\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { TaskScheduler } from '@backstage/backend-tasks';\n\n/** @public */\nexport const schedulerServiceFactory = createServiceFactory({\n service: coreServices.scheduler,\n deps: {\n plugin: coreServices.pluginMetadata,\n databaseManager: coreServices.database,\n logger: coreServices.logger,\n },\n async factory({ plugin, databaseManager, logger }) {\n return TaskScheduler.forPlugin({\n pluginId: plugin.getId(),\n databaseManager,\n logger: loggerToWinstonLogger(logger),\n });\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerTokenManager } from '@backstage/backend-common';\n\n/** @public */\nexport const tokenManagerServiceFactory = createServiceFactory({\n service: coreServices.tokenManager,\n deps: {\n config: coreServices.config,\n logger: coreServices.rootLogger,\n },\n createRootContext({ config, logger }) {\n return ServerTokenManager.fromConfig(config, {\n logger,\n });\n },\n async factory(_deps, tokenManager) {\n return tokenManager;\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { loggerToWinstonLogger, UrlReaders } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const urlReaderServiceFactory = createServiceFactory({\n service: coreServices.urlReader,\n deps: {\n config: coreServices.config,\n logger: coreServices.logger,\n },\n async factory({ config, logger }) {\n return UrlReaders.default({\n config,\n logger: loggerToWinstonLogger(logger),\n });\n },\n});\n"],"names":["ConfigReader","getPackages","loadConfigSchema","parseArgs","resolvePath","findPaths","config","loadConfig","fs","dirname","forge","stoppableServer","https","http","helmet","Minimatch","__privateAdd","__privateSet","compression","__privateGet","morgan","cors","serializeError","NotModifiedError","InputError","AuthenticationError","NotAllowedError","NotFoundError","ConflictError","NotImplementedError","ServiceUnavailableError","createLogger","format","transports","_hasStarted","_startupTasks","createServiceFactory","coreServices","__privateMethod","ForwardedError","lifecycleService","_a","stringifyError","CacheManager","ConfigSources","DatabaseManager","HostDiscovery","durationToMilliseconds","PromiseRouter","DefaultIdentityClient","ServerPermissionClient","trimEnd","Router","express","TaskScheduler","loggerToWinstonLogger","ServerTokenManager","UrlReaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,MAAM,qBAA+C,CAAA;AAAA,EAK1D,WAAA,CACmB,QACT,SACR,EAAA;AAFiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AACT,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA,CAAA;AANV,IAAA,aAAA,CAAA,IAAA,EAAQ,QAAwB,EAAA,IAAIA,mBAAa,CAAA,EAAE,CAAA,CAAA,CAAA;AAEnD,IAAA,aAAA,CAAA,IAAA,EAAiB,eAA8B,EAAC,CAAA,CAAA;AAM9C,IAAI,IAAA,MAAA,IAAU,CAAC,SAAW,EAAA;AACxB,MAAM,MAAA,IAAI,MAAM,wCAAwC,CAAA,CAAA;AAAA,KAC1D;AAAA,GACF;AAAA,EAEA,UAAU,MAAuB,EAAA;AAC/B,IAAA,IAAI,KAAK,MAAQ,EAAA;AACf,MAAM,MAAA,IAAI,MAAM,WAAW,CAAA,CAAA;AAAA,KAC7B;AACA,IAAA,IAAA,CAAK,MAAS,GAAA,MAAA,CAAA;AACd,IAAW,KAAA,MAAA,UAAA,IAAc,KAAK,WAAa,EAAA;AACzC,MAAI,IAAA;AACF,QAAW,UAAA,EAAA,CAAA;AAAA,eACJ,KAAO,EAAA;AACd,QAAQ,OAAA,CAAA,KAAA,CAAM,CAAkC,+BAAA,EAAA,KAAK,CAAE,CAAA,CAAA,CAAA;AAAA,OACzD;AAAA,KACF;AAAA,GACF;AAAA,EAEA,UAAU,QAAmD,EAAA;AAC3D,IAAA,IAAI,KAAK,MAAQ,EAAA;AACf,MAAO,OAAA,IAAA,CAAK,MAAO,CAAA,SAAA,CAAU,QAAQ,CAAA,CAAA;AAAA,KACvC;AAEA,IAAK,IA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,IAAO,OAAAmB,gCAAA,CAAmB,WAAW,MAAQ,EAAA;AAAA,MAC3C,MAAA;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AAAA,EACA,MAAM,OAAQ,CAAA,KAAA,EAAO,YAAc,EAAA;AACjC,IAAO,OAAA,YAAA,CAAA;AAAA,GACT;AACF,CAAC;;ACdM,MAAM,0BAA0BpB,qCAAqB,CAAA;AAAA,EAC1D,SAASC,6BAAa,CAAA,SAAA;AAAA,EACtB,IAAM,EAAA;AAAA,IACJ,QAAQA,6BAAa,CAAA,MAAA;AAAA,IACrB,QAAQA,6BAAa,CAAA,MAAA;AAAA,GACvB;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,MAAA,EAAQ,QAAU,EAAA;AAChC,IAAA,OAAOoB,yBAAW,OAAQ,CAAA;AAAA,MACxB,MAAA;AAAA,MACA,MAAA,EAAQF,oCAAsB,MAAM,CAAA;AAAA,KACrC,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/config/ObservableConfigProxy.ts","../src/lib/urls.ts","../src/config/config.ts","../src/http/config.ts","../src/http/getGeneratedCertificate.ts","../src/http/createHttpServer.ts","../src/http/readHelmetOptions.ts","../src/http/readCorsOptions.ts","../src/http/MiddlewareFactory.ts","../src/lib/escapeRegExp.ts","../src/logging/WinstonLogger.ts","../src/services/implementations/rootLifecycle/rootLifecycleServiceFactory.ts","../src/services/implementations/lifecycle/lifecycleServiceFactory.ts","../src/wiring/BackendInitializer.ts","../src/wiring/ServiceRegistry.ts","../src/wiring/BackstageBackend.ts","../src/wiring/createSpecializedBackend.ts","../src/services/implementations/cache/cacheServiceFactory.ts","../src/services/implementations/config/rootConfigServiceFactory.ts","../src/services/implementations/database/databaseServiceFactory.ts","../src/services/implementations/discovery/discoveryServiceFactory.ts","../src/services/implementations/httpRouter/createLifecycleMiddleware.ts","../src/services/implementations/httpRouter/httpRouterServiceFactory.ts","../src/services/implementations/identity/identityServiceFactory.ts","../src/services/implementations/logger/loggerServiceFactory.ts","../src/services/implementations/permissions/permissionsServiceFactory.ts","../src/services/implementations/rootHttpRouter/DefaultRootHttpRouter.ts","../src/services/implementations/rootHttpRouter/rootHttpRouterServiceFactory.ts","../src/services/implementations/rootLogger/rootLoggerServiceFactory.ts","../src/services/implementations/scheduler/schedulerServiceFactory.ts","../src/services/implementations/tokenManager/tokenManagerServiceFactory.ts","../src/services/implementations/urlReader/urlReaderServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config, ConfigReader } from '@backstage/config';\nimport { JsonValue } from '@backstage/types';\n\nexport class ObservableConfigProxy implements Config {\n private config: Config = new ConfigReader({});\n\n private readonly subscribers: (() => void)[] = [];\n\n constructor(\n private readonly parent?: ObservableConfigProxy,\n private parentKey?: string,\n ) {\n if (parent && !parentKey) {\n throw new Error('parentKey is required if parent is set');\n }\n }\n\n setConfig(config: Config) {\n if (this.parent) {\n throw new Error('immutable');\n }\n this.config = config;\n for (const subscriber of this.subscribers) {\n try {\n subscriber();\n } catch (error) {\n console.error(`Config subscriber threw error, ${error}`);\n }\n }\n }\n\n subscribe(onChange: () => void): { unsubscribe: () => void } {\n if (this.parent) {\n return this.parent.subscribe(onChange);\n }\n\n this.subscribers.push(onChange);\n return {\n unsubscribe: () => {\n const index = this.subscribers.indexOf(onChange);\n if (index >= 0) {\n this.subscribers.splice(index, 1);\n }\n },\n };\n }\n\n private select(required: true): Config;\n private select(required: false): Config | undefined;\n private select(required: boolean): Config | undefined {\n if (this.parent && this.parentKey) {\n if (required) {\n return this.parent.select(true).getConfig(this.parentKey);\n }\n return this.parent.select(false)?.getOptionalConfig(this.parentKey);\n }\n\n return this.config;\n }\n\n has(key: string): boolean {\n return this.select(false)?.has(key) ?? false;\n }\n keys(): string[] {\n return this.select(false)?.keys() ?? [];\n }\n get<T = JsonValue>(key?: string): T {\n return this.select(true).get(key);\n }\n getOptional<T = JsonValue>(key?: string): T | undefined {\n return this.select(false)?.getOptional(key);\n }\n getConfig(key: string): Config {\n return new ObservableConfigProxy(this, key);\n }\n getOptionalConfig(key: string): Config | undefined {\n if (this.select(false)?.has(key)) {\n return new ObservableConfigProxy(this, key);\n }\n return undefined;\n }\n getConfigArray(key: string): Config[] {\n return this.select(true).getConfigArray(key);\n }\n getOptionalConfigArray(key: string): Config[] | undefined {\n return this.select(false)?.getOptionalConfigArray(key);\n }\n getNumber(key: string): number {\n return this.select(true).getNumber(key);\n }\n getOptionalNumber(key: string): number | undefined {\n return this.select(false)?.getOptionalNumber(key);\n }\n getBoolean(key: string): boolean {\n return this.select(true).getBoolean(key);\n }\n getOptionalBoolean(key: string): boolean | undefined {\n return this.select(false)?.getOptionalBoolean(key);\n }\n getString(key: string): string {\n return this.select(true).getString(key);\n }\n getOptionalString(key: string): string | undefined {\n return this.select(false)?.getOptionalString(key);\n }\n getStringArray(key: string): string[] {\n return this.select(true).getStringArray(key);\n }\n getOptionalStringArray(key: string): string[] | undefined {\n return this.select(false)?.getOptionalStringArray(key);\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isValidUrl(url: string): boolean {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolve as resolvePath } from 'path';\nimport parseArgs from 'minimist';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { findPaths } from '@backstage/cli-common';\nimport {\n loadConfigSchema,\n loadConfig,\n ConfigTarget,\n LoadConfigOptionsRemote,\n} from '@backstage/config-loader';\nimport { ConfigReader } from '@backstage/config';\nimport type { Config, AppConfig } from '@backstage/config';\nimport { getPackages } from '@manypkg/get-packages';\nimport { ObservableConfigProxy } from './ObservableConfigProxy';\nimport { isValidUrl } from '../lib/urls';\n\n/** @public */\nexport async function createConfigSecretEnumerator(options: {\n logger: LoggerService;\n dir?: string;\n}): Promise<(config: Config) => Iterable<string>> {\n const { logger, dir = process.cwd() } = options;\n const { packages } = await getPackages(dir);\n const schema = await loadConfigSchema({\n dependencies: packages.map(p => p.packageJson.name),\n });\n\n return (config: Config) => {\n const [secretsData] = schema.process(\n [{ data: config.getOptional() ?? {}, context: 'schema-enumerator' }],\n {\n visibility: ['secret'],\n ignoreSchemaErrors: true,\n },\n );\n const secrets = new Set<string>();\n JSON.parse(\n JSON.stringify(secretsData),\n (_, v) => typeof v === 'string' && secrets.add(v),\n );\n logger.info(\n `Found ${secrets.size} new secrets in config that will be redacted`,\n );\n return secrets;\n };\n}\n\n/**\n * Load configuration for a Backend.\n *\n * This function should only be called once, during the initialization of the backend.\n *\n * @public\n */\nexport async function loadBackendConfig(options: {\n remote?: LoadConfigOptionsRemote;\n argv: string[];\n additionalConfigs?: AppConfig[];\n}): Promise<{ config: Config }> {\n const args = parseArgs(options.argv);\n\n const configTargets: ConfigTarget[] = [args.config ?? []]\n .flat()\n .map(arg => (isValidUrl(arg) ? { url: arg } : { path: resolvePath(arg) }));\n\n /* eslint-disable-next-line no-restricted-syntax */\n const paths = findPaths(__dirname);\n\n let currentCancelFunc: (() => void) | undefined = undefined;\n\n const config = new ObservableConfigProxy();\n const { appConfigs } = await loadConfig({\n configRoot: paths.targetRoot,\n configTargets: configTargets,\n remote: options.remote,\n watch: {\n onChange(newConfigs) {\n console.info(\n `Reloaded config from ${newConfigs.map(c => c.context).join(', ')}`,\n );\n const configsToMerge = [...newConfigs];\n if (options.additionalConfigs) {\n configsToMerge.push(...options.additionalConfigs);\n }\n config.setConfig(ConfigReader.fromConfigs(configsToMerge));\n },\n stopSignal: new Promise(resolve => {\n if (currentCancelFunc) {\n currentCancelFunc();\n }\n currentCancelFunc = resolve;\n\n // TODO(Rugvip): We keep this here for now to avoid breaking the old system\n // since this is re-used in backend-common\n if (module.hot) {\n module.hot.addDisposeHandler(resolve);\n }\n }),\n },\n });\n console.info(\n `Loaded config from ${appConfigs.map(c => c.context).join(', ')}`,\n );\n\n const finalAppConfigs = [...appConfigs];\n if (options.additionalConfigs) {\n finalAppConfigs.push(...options.additionalConfigs);\n }\n config.setConfig(ConfigReader.fromConfigs(finalAppConfigs));\n\n return { config };\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { HttpServerOptions } from './types';\n\nconst DEFAULT_PORT = 7007;\nconst DEFAULT_HOST = '';\n\n/**\n * Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.\n *\n * @public\n * @remarks\n *\n * The provided configuration object should contain the `listen` and\n * additional keys directly.\n *\n * @example\n * ```ts\n * const opts = readHttpServerOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHttpServerOptions(config?: Config): HttpServerOptions {\n return {\n listen: readHttpListenOptions(config),\n https: readHttpsOptions(config),\n };\n}\n\nfunction readHttpListenOptions(config?: Config): HttpServerOptions['listen'] {\n const listen = config?.getOptional('listen');\n if (typeof listen === 'string') {\n const parts = String(listen).split(':');\n const port = parseInt(parts[parts.length - 1], 10);\n if (!isNaN(port)) {\n if (parts.length === 1) {\n return { port, host: DEFAULT_HOST };\n }\n if (parts.length === 2) {\n return { host: parts[0], port };\n }\n }\n throw new Error(\n `Unable to parse listen address ${listen}, expected <port> or <host>:<port>`,\n );\n }\n\n // Workaround to allow empty string\n const host = config?.getOptional('listen.host') ?? DEFAULT_HOST;\n if (typeof host !== 'string') {\n config?.getOptionalString('listen.host'); // will throw\n throw new Error('unreachable');\n }\n\n return {\n port: config?.getOptionalNumber('listen.port') ?? DEFAULT_PORT,\n host,\n };\n}\n\nfunction readHttpsOptions(config?: Config): HttpServerOptions['https'] {\n const https = config?.getOptional('https');\n if (https === true) {\n const baseUrl = config!.getString('baseUrl');\n let hostname;\n try {\n hostname = new URL(baseUrl).hostname;\n } catch (error) {\n throw new Error(`Invalid baseUrl \"${baseUrl}\"`);\n }\n\n return { certificate: { type: 'generated', hostname } };\n }\n\n const cc = config?.getOptionalConfig('https');\n if (!cc) {\n return undefined;\n }\n\n return {\n certificate: {\n type: 'pem',\n cert: cc.getString('certificate.cert'),\n key: cc.getString('certificate.key'),\n },\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath, dirname } from 'path';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport forge from 'node-forge';\n\nconst FIVE_DAYS_IN_MS = 5 * 24 * 60 * 60 * 1000;\n\nconst IP_HOSTNAME_REGEX = /:|^\\d+\\.\\d+\\.\\d+\\.\\d+$/;\n\nexport async function getGeneratedCertificate(\n hostname: string,\n logger: LoggerService,\n) {\n const hasModules = await fs.pathExists('node_modules');\n let certPath;\n if (hasModules) {\n certPath = resolvePath(\n 'node_modules/.cache/backstage-backend/dev-cert.pem',\n );\n await fs.ensureDir(dirname(certPath));\n } else {\n certPath = resolvePath('.dev-cert.pem');\n }\n\n if (await fs.pathExists(certPath)) {\n try {\n const cert = await fs.readFile(certPath);\n\n const crt = forge.pki.certificateFromPem(cert.toString());\n const remainingMs = crt.validity.notAfter.getTime() - Date.now();\n if (remainingMs > FIVE_DAYS_IN_MS) {\n logger.info('Using existing self-signed certificate');\n return {\n key: cert,\n cert,\n };\n }\n } catch (error) {\n logger.warn(`Unable to use existing self-signed certificate, ${error}`);\n }\n }\n\n logger.info('Generating new self-signed certificate');\n const newCert = await generateCertificate(hostname);\n await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');\n return newCert;\n}\n\nasync function generateCertificate(hostname: string) {\n const attributes = [\n {\n name: 'commonName',\n value: 'dev-cert',\n },\n ];\n\n const sans = [\n {\n type: 2, // DNS\n value: 'localhost',\n },\n {\n type: 2,\n value: 'localhost.localdomain',\n },\n {\n type: 2,\n value: '[::1]',\n },\n {\n type: 7, // IP\n ip: '127.0.0.1',\n },\n {\n type: 7,\n ip: 'fe80::1',\n },\n ];\n\n // Add hostname from backend.baseUrl if it doesn't already exist in our list of SANs\n if (!sans.find(({ value, ip }) => value === hostname || ip === hostname)) {\n sans.push(\n IP_HOSTNAME_REGEX.test(hostname)\n ? {\n type: 7,\n ip: hostname,\n }\n : {\n type: 2,\n value: hostname,\n },\n );\n }\n\n const params = {\n algorithm: 'sha256',\n keySize: 2048,\n days: 30,\n extensions: [\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true,\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n timeStamping: true,\n },\n {\n name: 'subjectAltName',\n altNames: sans,\n },\n ],\n };\n\n return new Promise<{ key: string; cert: string }>((resolve, reject) =>\n require('selfsigned').generate(\n attributes,\n params,\n (err: Error, bundle: { private: string; cert: string }) => {\n if (err) {\n reject(err);\n } else {\n resolve({ key: bundle.private, cert: bundle.cert });\n }\n },\n ),\n );\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as http from 'http';\nimport * as https from 'https';\nimport stoppableServer from 'stoppable';\nimport { RequestListener } from 'http';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { HttpServerOptions, ExtendedHttpServer } from './types';\nimport { getGeneratedCertificate } from './getGeneratedCertificate';\n\n/**\n * Creates a Node.js HTTP or HTTPS server instance.\n *\n * @public\n */\nexport async function createHttpServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<ExtendedHttpServer> {\n const server = await createServer(listener, options, deps);\n\n const stopper = stoppableServer(server, 0);\n // The stopper here is actually the server itself, so if we try\n // to call stopper.stop() down in the stop implementation, we'll\n // be calling ourselves.\n const stopServer = stopper.stop.bind(stopper);\n\n return Object.assign(server, {\n start() {\n return new Promise<void>((resolve, reject) => {\n const handleStartupError = (error: Error) => {\n server.close();\n reject(error);\n };\n\n server.on('error', handleStartupError);\n\n const { host, port } = options.listen;\n server.listen(port, host, () => {\n server.off('error', handleStartupError);\n deps.logger.info(`Listening on ${host}:${port}`);\n resolve();\n });\n });\n },\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n stopServer((error?: Error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n },\n\n port() {\n const address = server.address();\n if (typeof address === 'string' || address === null) {\n throw new Error(`Unexpected server address '${address}'`);\n }\n return address.port;\n },\n });\n}\n\nasync function createServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<http.Server> {\n if (options.https) {\n const { certificate } = options.https;\n if (certificate.type === 'generated') {\n const credentials = await getGeneratedCertificate(\n certificate.hostname,\n deps.logger,\n );\n return https.createServer(credentials, listener);\n }\n return https.createServer(certificate, listener);\n }\n\n return http.createServer(listener);\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport { HelmetOptions } from 'helmet';\nimport { ContentSecurityPolicyOptions } from 'helmet/dist/types/middlewares/content-security-policy';\n\n/**\n * Attempts to read Helmet options from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A Helmet options object, or undefined if no Helmet configuration is present.\n *\n * @example\n * ```ts\n * const helmetOptions = readHelmetOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHelmetOptions(config?: Config): HelmetOptions {\n const cspOptions = readCspDirectives(config);\n return {\n contentSecurityPolicy: {\n useDefaults: false,\n directives: applyCspDirectives(cspOptions),\n },\n // These are all disabled in order to maintain backwards compatibility\n // when bumping helmet v5. We can't enable these by default because\n // there is no way for users to configure them.\n // TODO(Rugvip): We should give control of this setup to consumers\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n };\n}\n\ntype CspDirectives = Record<string, string[] | false> | undefined;\n\n/**\n * Attempts to read a CSP directives from the backend configuration object.\n *\n * @example\n * ```yaml\n * backend:\n * csp:\n * connect-src: [\"'self'\", 'http:', 'https:']\n * upgrade-insecure-requests: false\n * ```\n */\nfunction readCspDirectives(config?: Config): CspDirectives {\n const cc = config?.getOptionalConfig('csp');\n if (!cc) {\n return undefined;\n }\n\n const result: Record<string, string[] | false> = {};\n for (const key of cc.keys()) {\n if (cc.get(key) === false) {\n result[key] = false;\n } else {\n result[key] = cc.getStringArray(key);\n }\n }\n\n return result;\n}\n\nexport function applyCspDirectives(\n directives: CspDirectives,\n): ContentSecurityPolicyOptions['directives'] {\n const result: ContentSecurityPolicyOptions['directives'] =\n helmet.contentSecurityPolicy.getDefaultDirectives();\n\n // TODO(Rugvip): We currently use non-precompiled AJV for validation in the frontend, which uses eval.\n // It should be replaced by any other solution that doesn't require unsafe-eval.\n result['script-src'] = [\"'self'\", \"'unsafe-eval'\"];\n\n // TODO(Rugvip): This is removed so that we maintained backwards compatibility\n // when bumping to helmet v5, we could remove this as well as\n // skip setting `useDefaults: false` in the future.\n delete result['form-action'];\n\n if (directives) {\n for (const [key, value] of Object.entries(directives)) {\n if (value === false) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n }\n\n return result;\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { CorsOptions } from 'cors';\nimport { Minimatch } from 'minimatch';\n\n/**\n * Attempts to read a CORS options object from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A CORS options object, or undefined if no cors configuration is present.\n *\n * @example\n * ```ts\n * const corsOptions = readCorsOptions(config.getConfig('backend'));\n * ```\n */\nexport function readCorsOptions(config?: Config): CorsOptions {\n const cc = config?.getOptionalConfig('cors');\n if (!cc) {\n return { origin: false }; // Disable CORS\n }\n\n return removeUnknown({\n origin: createCorsOriginMatcher(readStringArray(cc, 'origin')),\n methods: readStringArray(cc, 'methods'),\n allowedHeaders: readStringArray(cc, 'allowedHeaders'),\n exposedHeaders: readStringArray(cc, 'exposedHeaders'),\n credentials: cc.getOptionalBoolean('credentials'),\n maxAge: cc.getOptionalNumber('maxAge'),\n preflightContinue: cc.getOptionalBoolean('preflightContinue'),\n optionsSuccessStatus: cc.getOptionalNumber('optionsSuccessStatus'),\n });\n}\n\nfunction removeUnknown<T extends object>(obj: T): T {\n return Object.fromEntries(\n Object.entries(obj).filter(([, v]) => v !== undefined),\n ) as T;\n}\n\nfunction readStringArray(config: Config, key: string): string[] | undefined {\n const value = config.getOptional(key);\n if (typeof value === 'string') {\n return [value];\n } else if (!value) {\n return undefined;\n }\n return config.getStringArray(key);\n}\n\nfunction createCorsOriginMatcher(allowedOriginPatterns: string[] | undefined) {\n if (!allowedOriginPatterns) {\n return undefined;\n }\n\n const allowedOriginMatchers = allowedOriginPatterns.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n );\n\n return (\n origin: string | undefined,\n callback: (\n err: Error | null,\n origin: boolean | string | RegExp | (boolean | string | RegExp)[],\n ) => void,\n ) => {\n return callback(\n null,\n allowedOriginMatchers.some(pattern => pattern.match(origin ?? '')),\n );\n };\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RootConfigService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport {\n Request,\n Response,\n ErrorRequestHandler,\n NextFunction,\n RequestHandler,\n} from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport morgan from 'morgan';\nimport compression from 'compression';\nimport { readHelmetOptions } from './readHelmetOptions';\nimport { readCorsOptions } from './readCorsOptions';\nimport {\n AuthenticationError,\n ConflictError,\n ErrorResponseBody,\n InputError,\n NotAllowedError,\n NotFoundError,\n NotModifiedError,\n ServiceUnavailableError,\n serializeError,\n} from '@backstage/errors';\nimport { NotImplementedError } from '@backstage/errors';\n\n/**\n * Options used to create a {@link MiddlewareFactory}.\n *\n * @public\n */\nexport interface MiddlewareFactoryOptions {\n config: RootConfigService;\n logger: LoggerService;\n}\n\n/**\n * Options passed to the {@link MiddlewareFactory.error} middleware.\n *\n * @public\n */\nexport interface MiddlewareFactoryErrorOptions {\n /**\n * Whether error response bodies should show error stack traces or not.\n *\n * If not specified, by default shows stack traces only in development mode.\n */\n showStackTraces?: boolean;\n\n /**\n * Whether any 4xx errors should be logged or not.\n *\n * If not specified, default to only logging 5xx errors.\n */\n logAllErrors?: boolean;\n}\n\n/**\n * A utility to configure common middleware.\n *\n * @public\n */\nexport class MiddlewareFactory {\n #config: RootConfigService;\n #logger: LoggerService;\n\n /**\n * Creates a new {@link MiddlewareFactory}.\n */\n static create(options: MiddlewareFactoryOptions) {\n return new MiddlewareFactory(options);\n }\n\n private constructor(options: MiddlewareFactoryOptions) {\n this.#config = options.config;\n this.#logger = options.logger;\n }\n\n /**\n * Returns a middleware that unconditionally produces a 404 error response.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the end of the chain, such\n * that it's the last one attempted after no other routes matched.\n *\n * @returns An Express request handler\n */\n notFound(): RequestHandler {\n return (_req: Request, res: Response) => {\n res.status(404).end();\n };\n }\n\n /**\n * Returns the compression middleware.\n *\n * @remarks\n *\n * The middleware will attempt to compress response bodies for all requests\n * that traverse through the middleware.\n */\n compression(): RequestHandler {\n return compression();\n }\n\n /**\n * Returns a request logging middleware.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the start of the chain, such\n * that it always logs requests whether they are \"caught\" by handlers farther\n * down or not.\n *\n * @returns An Express request handler\n */\n logging(): RequestHandler {\n const logger = this.#logger.child({\n type: 'incomingRequest',\n });\n\n return morgan('combined', {\n stream: {\n write(message: string) {\n logger.info(message.trimEnd());\n },\n },\n });\n }\n\n /**\n * Returns a middleware that implements the helmet library.\n *\n * @remarks\n *\n * This middleware applies security policies to incoming requests and outgoing\n * responses. It is configured using config keys such as `backend.csp`.\n *\n * @see {@link https://helmetjs.github.io/}\n *\n * @returns An Express request handler\n */\n helmet(): RequestHandler {\n return helmet(readHelmetOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements the cors library.\n *\n * @remarks\n *\n * This middleware handles CORS. It is configured using the config key\n * `backend.cors`.\n *\n * @see {@link https://github.com/expressjs/cors}\n *\n * @returns An Express request handler\n */\n cors(): RequestHandler {\n return cors(readCorsOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Express middleware to handle errors during request processing.\n *\n * @remarks\n *\n * This is commonly the very last middleware in the chain.\n *\n * Its primary purpose is not to do translation of business logic exceptions,\n * but rather to be a global catch-all for uncaught \"fatal\" errors that are\n * expected to result in a 500 error. However, it also does handle some common\n * error types (such as http-error exceptions, and the well-known error types\n * in the `@backstage/errors` package) and returns the enclosed status code\n * accordingly.\n *\n * It will also produce a response body with a serialized form of the error,\n * unless a previous handler already did send a body. See\n * {@link @backstage/errors#ErrorResponseBody} for the response shape used.\n *\n * @returns An Express error request handler\n */\n error(options: MiddlewareFactoryErrorOptions = {}): ErrorRequestHandler {\n const showStackTraces =\n options.showStackTraces ?? process.env.NODE_ENV === 'development';\n\n const logger = this.#logger.child({\n type: 'errorHandler',\n });\n\n return (error: Error, req: Request, res: Response, next: NextFunction) => {\n const statusCode = getStatusCode(error);\n if (options.logAllErrors || statusCode >= 500) {\n logger.error(`Request failed with status ${statusCode}`, error);\n }\n\n if (res.headersSent) {\n // If the headers have already been sent, do not send the response again\n // as this will throw an error in the backend.\n next(error);\n return;\n }\n\n const body: ErrorResponseBody = {\n error: serializeError(error, { includeStack: showStackTraces }),\n request: { method: req.method, url: req.url },\n response: { statusCode },\n };\n\n res.status(statusCode).json(body);\n };\n }\n}\n\nfunction getStatusCode(error: Error): number {\n // Look for common http library status codes\n const knownStatusCodeFields = ['statusCode', 'status'];\n for (const field of knownStatusCodeFields) {\n const statusCode = (error as any)[field];\n if (\n typeof statusCode === 'number' &&\n (statusCode | 0) === statusCode && // is whole integer\n statusCode >= 100 &&\n statusCode <= 599\n ) {\n return statusCode;\n }\n }\n\n // Handle well-known error types\n switch (error.name) {\n case NotModifiedError.name:\n return 304;\n case InputError.name:\n return 400;\n case AuthenticationError.name:\n return 401;\n case NotAllowedError.name:\n return 403;\n case NotFoundError.name:\n return 404;\n case ConflictError.name:\n return 409;\n case NotImplementedError.name:\n return 501;\n case ServiceUnavailableError.name:\n return 503;\n default:\n break;\n }\n\n // Fall back to internal server error\n return 500;\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Escapes a given string to be used inside a RegExp.\n *\n * Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n */\nexport const escapeRegExp = (text: string) => {\n return text.replace(/[.*+?^${}(\\)|[\\]\\\\]/g, '\\\\$&');\n};\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n LoggerService,\n RootLoggerService,\n} from '@backstage/backend-plugin-api';\nimport { JsonObject } from '@backstage/types';\nimport { Format, TransformableInfo } from 'logform';\nimport {\n Logger,\n format,\n createLogger,\n transports,\n transport as Transport,\n} from 'winston';\nimport { escapeRegExp } from '../lib/escapeRegExp';\n\n/**\n * @public\n */\nexport interface WinstonLoggerOptions {\n meta?: JsonObject;\n level: string;\n format: Format;\n transports: Transport[];\n}\n\n/**\n * A {@link @backstage/backend-plugin-api#LoggerService} implementation based on winston.\n *\n * @public\n */\nexport class WinstonLogger implements RootLoggerService {\n #winston: Logger;\n #addRedactions?: (redactions: Iterable<string>) => void;\n\n /**\n * Creates a {@link WinstonLogger} instance.\n */\n static create(options: WinstonLoggerOptions): WinstonLogger {\n const redacter = WinstonLogger.redacter();\n\n let logger = createLogger({\n level: options.level,\n format: format.combine(redacter.format, options.format),\n transports: options.transports ?? new transports.Console(),\n });\n if (options.meta) {\n logger = logger.child(options.meta);\n }\n\n return new WinstonLogger(logger, redacter.add);\n }\n\n /**\n * Creates a winston log formatter for redacting secrets.\n */\n static redacter(): {\n format: Format;\n add: (redactions: Iterable<string>) => void;\n } {\n const redactionSet = new Set<string>();\n\n let redactionPattern: RegExp | undefined = undefined;\n\n return {\n format: format(info => {\n if (redactionPattern && typeof info.message === 'string') {\n info.message = info.message.replace(redactionPattern, '[REDACTED]');\n }\n return info;\n })(),\n add(newRedactions) {\n let added = 0;\n for (const redaction of newRedactions) {\n // Exclude secrets that are empty or just one character in length. These\n // typically mean that you are running local dev or tests, or using the\n // --lax flag which sets things to just 'x'.\n if (redaction.length <= 1) {\n continue;\n }\n if (!redactionSet.has(redaction)) {\n redactionSet.add(redaction);\n added += 1;\n }\n }\n if (added > 0) {\n const redactions = Array.from(redactionSet)\n .map(r => escapeRegExp(r))\n .join('|');\n redactionPattern = new RegExp(`(${redactions})`, 'g');\n }\n },\n };\n }\n\n /**\n * Creates a pretty printed winston log formatter.\n */\n static colorFormat(): Format {\n const colorizer = format.colorize();\n\n return format.combine(\n format.timestamp(),\n format.colorize({\n colors: {\n timestamp: 'dim',\n prefix: 'blue',\n field: 'cyan',\n debug: 'grey',\n },\n }),\n format.printf((info: TransformableInfo) => {\n const { timestamp, level, message, plugin, service, ...fields } = info;\n const prefix = plugin || service;\n const timestampColor = colorizer.colorize('timestamp', timestamp);\n const prefixColor = colorizer.colorize('prefix', prefix);\n\n const extraFields = Object.entries(fields)\n .map(\n ([key, value]) =>\n `${colorizer.colorize('field', `${key}`)}=${value}`,\n )\n .join(' ');\n\n return `${timestampColor} ${prefixColor} ${level} ${message} ${extraFields}`;\n }),\n );\n }\n\n private constructor(\n winston: Logger,\n addRedactions?: (redactions: Iterable<string>) => void,\n ) {\n this.#winston = winston;\n this.#addRedactions = addRedactions;\n }\n\n error(message: string, meta?: JsonObject): void {\n this.#winston.error(message, meta);\n }\n\n warn(message: string, meta?: JsonObject): void {\n this.#winston.warn(message, meta);\n }\n\n info(message: string, meta?: JsonObject): void {\n this.#winston.info(message, meta);\n }\n\n debug(message: string, meta?: JsonObject): void {\n this.#winston.debug(message, meta);\n }\n\n child(meta: JsonObject): LoggerService {\n return new WinstonLogger(this.#winston.child(meta));\n }\n\n addRedactions(redactions: Iterable<string>) {\n this.#addRedactions?.(redactions);\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n LifecycleServiceStartupHook,\n LifecycleServiceStartupOptions,\n LifecycleServiceShutdownHook,\n LifecycleServiceShutdownOptions,\n RootLifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class BackendLifecycleImpl implements RootLifecycleService {\n constructor(private readonly logger: LoggerService) {}\n\n #hasStarted = false;\n #startupTasks: Array<{\n hook: LifecycleServiceStartupHook;\n options?: LifecycleServiceStartupOptions;\n }> = [];\n\n addStartupHook(\n hook: LifecycleServiceStartupHook,\n options?: LifecycleServiceStartupOptions,\n ): void {\n if (this.#hasStarted) {\n throw new Error('Attempted to add startup hook after startup');\n }\n this.#startupTasks.push({ hook, options });\n }\n\n async startup(): Promise<void> {\n if (this.#hasStarted) {\n return;\n }\n this.#hasStarted = true;\n\n this.logger.debug(`Running ${this.#startupTasks.length} startup tasks...`);\n await Promise.all(\n this.#startupTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Startup hook succeeded`);\n } catch (error) {\n logger.error(`Startup hook failed, ${error}`);\n }\n }),\n );\n }\n\n #hasShutdown = false;\n #shutdownTasks: Array<{\n hook: LifecycleServiceShutdownHook;\n options?: LifecycleServiceShutdownOptions;\n }> = [];\n\n addShutdownHook(\n hook: LifecycleServiceShutdownHook,\n options?: LifecycleServiceShutdownOptions,\n ): void {\n if (this.#hasShutdown) {\n throw new Error('Attempted to add shutdown hook after shutdown');\n }\n this.#shutdownTasks.push({ hook, options });\n }\n\n async shutdown(): Promise<void> {\n if (this.#hasShutdown) {\n return;\n }\n this.#hasShutdown = true;\n\n this.logger.debug(\n `Running ${this.#shutdownTasks.length} shutdown tasks...`,\n );\n await Promise.all(\n this.#shutdownTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Shutdown hook succeeded`);\n } catch (error) {\n logger.error(`Shutdown hook failed, ${error}`);\n }\n }),\n );\n }\n}\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n *\n * @public\n */\nexport const rootLifecycleServiceFactory = createServiceFactory({\n service: coreServices.rootLifecycle,\n deps: {\n logger: coreServices.rootLogger,\n },\n async factory({ logger }) {\n return new BackendLifecycleImpl(logger);\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n LifecycleService,\n LifecycleServiceShutdownHook,\n LifecycleServiceShutdownOptions,\n LifecycleServiceStartupHook,\n LifecycleServiceStartupOptions,\n LoggerService,\n PluginMetadataService,\n RootLifecycleService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport class BackendPluginLifecycleImpl implements LifecycleService {\n constructor(\n private readonly logger: LoggerService,\n private readonly rootLifecycle: RootLifecycleService,\n private readonly pluginMetadata: PluginMetadataService,\n ) {}\n\n #hasStarted = false;\n #startupTasks: Array<{\n hook: LifecycleServiceStartupHook;\n options?: LifecycleServiceStartupOptions;\n }> = [];\n\n addStartupHook(\n hook: LifecycleServiceStartupHook,\n options?: LifecycleServiceStartupOptions,\n ): void {\n if (this.#hasStarted) {\n throw new Error('Attempted to add startup hook after startup');\n }\n this.#startupTasks.push({ hook, options });\n }\n\n async startup(): Promise<void> {\n if (this.#hasStarted) {\n return;\n }\n this.#hasStarted = true;\n\n this.logger.debug(\n `Running ${this.#startupTasks.length} plugin startup tasks...`,\n );\n await Promise.all(\n this.#startupTasks.map(async ({ hook, options }) => {\n const logger = options?.logger ?? this.logger;\n try {\n await hook();\n logger.debug(`Plugin startup hook succeeded`);\n } catch (error) {\n logger.error(`Plugin startup hook failed, ${error}`);\n }\n }),\n );\n }\n\n addShutdownHook(\n hook: LifecycleServiceShutdownHook,\n options?: LifecycleServiceShutdownOptions,\n ): void {\n const plugin = this.pluginMetadata.getId();\n this.rootLifecycle.addShutdownHook(hook, {\n logger: options?.logger?.child({ plugin }) ?? this.logger,\n });\n }\n}\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n * @public\n */\nexport const lifecycleServiceFactory = createServiceFactory({\n service: coreServices.lifecycle,\n deps: {\n logger: coreServices.logger,\n rootLifecycle: coreServices.rootLifecycle,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ rootLifecycle, logger, pluginMetadata }) {\n return new BackendPluginLifecycleImpl(\n logger,\n rootLifecycle,\n pluginMetadata,\n );\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n} from '@backstage/backend-plugin-api';\nimport { BackendLifecycleImpl } from '../services/implementations/rootLifecycle/rootLifecycleServiceFactory';\nimport { BackendPluginLifecycleImpl } from '../services/implementations/lifecycle/lifecycleServiceFactory';\nimport { EnumerableServiceHolder, ServiceOrExtensionPoint } from './types';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-forbidden-package-imports\nimport { InternalBackendFeature } from '@backstage/backend-plugin-api/src/wiring/types';\nimport { ForwardedError } from '@backstage/errors';\n\nexport interface BackendRegisterInit {\n consumes: Set<ServiceOrExtensionPoint>;\n provides: Set<ServiceOrExtensionPoint>;\n init: {\n deps: { [name: string]: ServiceOrExtensionPoint };\n func: (deps: { [name: string]: unknown }) => Promise<void>;\n };\n}\n\nexport class BackendInitializer {\n #startPromise?: Promise<void>;\n #features = new Array<InternalBackendFeature>();\n #extensionPoints = new Map<ExtensionPoint<unknown>, unknown>();\n #serviceHolder: EnumerableServiceHolder;\n\n constructor(serviceHolder: EnumerableServiceHolder) {\n this.#serviceHolder = serviceHolder;\n }\n\n async #getInitDeps(\n deps: { [name: string]: ServiceOrExtensionPoint },\n pluginId: string,\n ) {\n const result = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(deps)) {\n const extensionPoint = this.#extensionPoints.get(\n ref as ExtensionPoint<unknown>,\n );\n if (extensionPoint) {\n result.set(name, extensionPoint);\n } else {\n const impl = await this.#serviceHolder.get(\n ref as ServiceRef<unknown>,\n pluginId,\n );\n if (impl) {\n result.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No extension point or service available for the following ref(s): ${missing}`,\n );\n }\n\n return Object.fromEntries(result);\n }\n\n add(feature: BackendFeature) {\n if (this.#startPromise) {\n throw new Error('feature can not be added after the backend has started');\n }\n if (feature.$$type !== '@backstage/BackendFeature') {\n throw new Error(\n `Failed to add feature, invalid type '${feature.$$type}'`,\n );\n }\n const internalFeature = feature as InternalBackendFeature;\n if (internalFeature.version !== 'v1') {\n throw new Error(\n `Failed to add feature, invalid version '${internalFeature.version}'`,\n );\n }\n this.#features.push(internalFeature);\n }\n\n async start(): Promise<void> {\n if (this.#startPromise) {\n throw new Error('Backend has already started');\n }\n\n const exitHandler = async () => {\n process.removeListener('SIGTERM', exitHandler);\n process.removeListener('SIGINT', exitHandler);\n process.removeListener('beforeExit', exitHandler);\n\n try {\n await this.stop();\n process.exit(0);\n } catch (error) {\n console.error(error);\n process.exit(1);\n }\n };\n\n process.addListener('SIGTERM', exitHandler);\n process.addListener('SIGINT', exitHandler);\n process.addListener('beforeExit', exitHandler);\n\n this.#startPromise = this.#doStart();\n await this.#startPromise;\n }\n\n async #doStart(): Promise<void> {\n // Initialize all root scoped services\n for (const ref of this.#serviceHolder.getServiceRefs()) {\n if (ref.scope === 'root') {\n await this.#serviceHolder.get(ref, 'root');\n }\n }\n\n const pluginInits = new Map<string, BackendRegisterInit>();\n const moduleInits = new Map<string, Map<string, BackendRegisterInit>>();\n\n // Enumerate all features\n for (const feature of this.#features) {\n for (const r of feature.getRegistrations()) {\n const provides = new Set<ExtensionPoint<unknown>>();\n\n if (r.type === 'plugin') {\n for (const [extRef, extImpl] of r.extensionPoints) {\n if (this.#extensionPoints.has(extRef)) {\n throw new Error(\n `ExtensionPoint with ID '${extRef.id}' is already registered`,\n );\n }\n this.#extensionPoints.set(extRef, extImpl);\n provides.add(extRef);\n }\n }\n\n if (r.type === 'plugin') {\n if (pluginInits.has(r.pluginId)) {\n throw new Error(`Plugin '${r.pluginId}' is already registered`);\n }\n pluginInits.set(r.pluginId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n } else {\n let modules = moduleInits.get(r.pluginId);\n if (!modules) {\n modules = new Map();\n moduleInits.set(r.pluginId, modules);\n }\n if (modules.has(r.moduleId)) {\n throw new Error(\n `Module '${r.moduleId}' for plugin '${r.pluginId}' is already registered`,\n );\n }\n modules.set(r.moduleId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n }\n }\n }\n\n const allPluginIds = [\n ...new Set([...pluginInits.keys(), ...moduleInits.keys()]),\n ];\n\n // All plugins are initialized in parallel\n await Promise.all(\n allPluginIds.map(async pluginId => {\n // Modules are initialized before plugins, so that they can provide extension to the plugin\n const modules = moduleInits.get(pluginId) ?? [];\n await Promise.all(\n Array.from(modules).map(async ([moduleId, moduleInit]) => {\n const moduleDeps = await this.#getInitDeps(\n moduleInit.init.deps,\n pluginId,\n );\n await moduleInit.init.func(moduleDeps).catch(error => {\n throw new ForwardedError(\n `Module '${moduleId}' for plugin '${pluginId}' startup failed`,\n error,\n );\n });\n }),\n );\n\n // Once all modules have been initialized, we can initialize the plugin itself\n const pluginInit = pluginInits.get(pluginId);\n // We allow modules to be installed without the accompanying plugin, so the plugin may not exist\n if (pluginInit) {\n const pluginDeps = await this.#getInitDeps(\n pluginInit.init.deps,\n pluginId,\n );\n await pluginInit.init.func(pluginDeps).catch(error => {\n throw new ForwardedError(\n `Plugin '${pluginId}' startup failed`,\n error,\n );\n });\n }\n\n // Once the plugin and all modules have been initialized, we can signal that the plugin has stared up successfully\n const lifecycleService = await this.#getPluginLifecycleImpl(pluginId);\n await lifecycleService.startup();\n }),\n );\n\n // Once all plugins and modules have been initialized, we can signal that the backend has started up successfully\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.startup();\n\n // Once the backend is started, any uncaught errors or unhandled rejections are caught\n // and logged, in order to avoid crashing the entire backend on local failures.\n if (process.env.NODE_ENV !== 'test') {\n const rootLogger = await this.#serviceHolder.get(\n coreServices.rootLogger,\n 'root',\n );\n process.on('unhandledRejection', (reason: Error) => {\n rootLogger\n ?.child({ type: 'unhandledRejection' })\n ?.error('Unhandled rejection', reason);\n });\n process.on('uncaughtException', error => {\n rootLogger\n ?.child({ type: 'uncaughtException' })\n ?.error('Uncaught exception', error);\n });\n }\n }\n\n async stop(): Promise<void> {\n if (!this.#startPromise) {\n return;\n }\n await this.#startPromise;\n\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.shutdown();\n }\n\n // Bit of a hacky way to grab the lifecycle services, potentially find a nicer way to do this\n async #getRootLifecycleImpl(): Promise<BackendLifecycleImpl> {\n const lifecycleService = await this.#serviceHolder.get(\n coreServices.rootLifecycle,\n 'root',\n );\n if (lifecycleService instanceof BackendLifecycleImpl) {\n return lifecycleService;\n }\n throw new Error('Unexpected root lifecycle service implementation');\n }\n\n async #getPluginLifecycleImpl(\n pluginId: string,\n ): Promise<BackendPluginLifecycleImpl> {\n const lifecycleService = await this.#serviceHolder.get(\n coreServices.lifecycle,\n pluginId,\n );\n if (lifecycleService instanceof BackendPluginLifecycleImpl) {\n return lifecycleService;\n }\n throw new Error('Unexpected plugin lifecycle service implementation');\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ServiceFactory,\n ServiceRef,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { stringifyError } from '@backstage/errors';\nimport { EnumerableServiceHolder } from './types';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-forbidden-package-imports\nimport { InternalServiceFactory } from '@backstage/backend-plugin-api/src/services/system/types';\n/**\n * Keep in sync with `@backstage/backend-plugin-api/src/services/system/types.ts`\n * @internal\n */\nexport type InternalServiceRef = ServiceRef<unknown> & {\n __defaultFactory?: (\n service: ServiceRef<unknown>,\n ) => Promise<ServiceFactory | (() => ServiceFactory)>;\n};\n\nfunction toInternalServiceFactory<TService, TScope extends 'plugin' | 'root'>(\n factory: ServiceFactory<TService, TScope>,\n): InternalServiceFactory<TService, TScope> {\n const f = factory as InternalServiceFactory<TService, TScope>;\n if (f.$$type !== '@backstage/ServiceFactory') {\n throw new Error(`Invalid service factory, bad type '${f.$$type}'`);\n }\n if (f.version !== 'v1') {\n throw new Error(`Invalid service factory, bad version '${f.version}'`);\n }\n return f;\n}\n\nconst pluginMetadataServiceFactory = createServiceFactory(\n (options: { pluginId: string }) => ({\n service: coreServices.pluginMetadata,\n deps: {},\n factory: async () => ({ getId: () => options.pluginId }),\n }),\n);\n\nexport class ServiceRegistry implements EnumerableServiceHolder {\n readonly #providedFactories: Map<string, InternalServiceFactory>;\n readonly #loadedDefaultFactories: Map<\n Function,\n Promise<InternalServiceFactory>\n >;\n readonly #implementations: Map<\n InternalServiceFactory,\n {\n context: Promise<unknown>;\n byPlugin: Map<string, Promise<unknown>>;\n }\n >;\n readonly #rootServiceImplementations = new Map<\n InternalServiceFactory,\n Promise<unknown>\n >();\n\n constructor(factories: Array<ServiceFactory>) {\n this.#providedFactories = new Map(\n factories.map(sf => [sf.service.id, toInternalServiceFactory(sf)]),\n );\n this.#loadedDefaultFactories = new Map();\n this.#implementations = new Map();\n }\n\n #resolveFactory(\n ref: ServiceRef<unknown>,\n pluginId: string,\n ): Promise<InternalServiceFactory> | undefined {\n // Special case handling of the plugin metadata service, generating a custom factory for it each time\n if (ref.id === coreServices.pluginMetadata.id) {\n return Promise.resolve(\n toInternalServiceFactory(pluginMetadataServiceFactory({ pluginId })),\n );\n }\n\n let resolvedFactory:\n | Promise<InternalServiceFactory>\n | InternalServiceFactory\n | undefined = this.#providedFactories.get(ref.id);\n const { __defaultFactory: defaultFactory } = ref as InternalServiceRef;\n if (!resolvedFactory && !defaultFactory) {\n return undefined;\n }\n\n if (!resolvedFactory) {\n let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory!);\n if (!loadedFactory) {\n loadedFactory = Promise.resolve()\n .then(() => defaultFactory!(ref))\n .then(f =>\n toInternalServiceFactory(typeof f === 'function' ? f() : f),\n );\n this.#loadedDefaultFactories.set(defaultFactory!, loadedFactory);\n }\n resolvedFactory = loadedFactory.catch(error => {\n throw new Error(\n `Failed to instantiate service '${\n ref.id\n }' because the default factory loader threw an error, ${stringifyError(\n error,\n )}`,\n );\n });\n }\n\n return Promise.resolve(resolvedFactory);\n }\n\n #checkForMissingDeps(factory: InternalServiceFactory, pluginId: string) {\n const missingDeps = Object.values(factory.deps).filter(ref => {\n if (ref.id === coreServices.pluginMetadata.id) {\n return false;\n }\n if (this.#providedFactories.get(ref.id)) {\n return false;\n }\n\n return !(ref as InternalServiceRef).__defaultFactory;\n });\n\n if (missingDeps.length) {\n const missing = missingDeps.map(r => `'${r.id}'`).join(', ');\n throw new Error(\n `Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`,\n );\n }\n }\n\n getServiceRefs(): ServiceRef<unknown>[] {\n return Array.from(this.#providedFactories.values()).map(f => f.service);\n }\n\n get<T>(ref: ServiceRef<T>, pluginId: string): Promise<T> | undefined {\n return this.#resolveFactory(ref, pluginId)?.then(factory => {\n if (factory.service.scope === 'root') {\n let existing = this.#rootServiceImplementations.get(factory);\n if (!existing) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope !== 'root') {\n throw new Error(\n `Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`,\n );\n }\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n\n existing = Promise.all(rootDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), undefined),\n );\n this.#rootServiceImplementations.set(factory, existing);\n }\n return existing as Promise<T>;\n }\n\n let implementation = this.#implementations.get(factory);\n if (!implementation) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope === 'root') {\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n }\n\n implementation = {\n context: Promise.all(rootDeps)\n .then(entries =>\n factory.createRootContext?.(Object.fromEntries(entries)),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' because createRootContext threw an error, ${cause}`,\n );\n }),\n byPlugin: new Map(),\n };\n\n this.#implementations.set(factory, implementation);\n }\n\n let result = implementation.byPlugin.get(pluginId) as Promise<any>;\n if (!result) {\n const allDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n const target = this.get(serviceRef, pluginId)!;\n allDeps.push(target.then(impl => [name, impl]));\n }\n\n result = implementation.context\n .then(context =>\n Promise.all(allDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), context),\n ),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`,\n );\n });\n implementation.byPlugin.set(pluginId, result);\n }\n\n return result;\n });\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ServiceFactory, BackendFeature } from '@backstage/backend-plugin-api';\nimport { BackendInitializer } from './BackendInitializer';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport { Backend } from './types';\n\nexport class BackstageBackend implements Backend {\n #services: ServiceRegistry;\n #initializer: BackendInitializer;\n\n constructor(apiFactories: ServiceFactory[]) {\n this.#services = new ServiceRegistry(apiFactories);\n this.#initializer = new BackendInitializer(this.#services);\n }\n\n add(feature: BackendFeature): void {\n this.#initializer.add(feature);\n }\n\n async start(): Promise<void> {\n await this.#initializer.start();\n }\n\n async stop(): Promise<void> {\n await this.#initializer.stop();\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { coreServices } from '@backstage/backend-plugin-api';\nimport { BackstageBackend } from './BackstageBackend';\nimport { Backend, CreateSpecializedBackendOptions } from './types';\n\n/**\n * @public\n */\nexport function createSpecializedBackend(\n options: CreateSpecializedBackendOptions,\n): Backend {\n const services = options.services.map(sf =>\n typeof sf === 'function' ? sf() : sf,\n );\n\n const exists = new Set<string>();\n const duplicates = new Set<string>();\n for (const { service } of services) {\n if (exists.has(service.id)) {\n duplicates.add(service.id);\n } else {\n exists.add(service.id);\n }\n }\n if (duplicates.size > 0) {\n const ids = Array.from(duplicates).join(', ');\n throw new Error(`Duplicate service implementations provided for ${ids}`);\n }\n if (exists.has(coreServices.pluginMetadata.id)) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n return new BackstageBackend(services);\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CacheManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const cacheServiceFactory = createServiceFactory({\n service: coreServices.cache,\n deps: {\n config: coreServices.rootConfig,\n plugin: coreServices.pluginMetadata,\n },\n async createRootContext({ config }) {\n return CacheManager.fromConfig(config);\n },\n async factory({ plugin }, manager) {\n return manager.forPlugin(plugin.getId()).getClient();\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n ConfigSources,\n RemoteConfigSourceOptions,\n} from '@backstage/config-loader';\n\n/** @public */\nexport interface RootConfigFactoryOptions {\n /**\n * Process arguments to use instead of the default `process.argv()`.\n */\n argv?: string[];\n\n /**\n * Enables and sets options for remote configuration loading.\n */\n remote?: Pick<RemoteConfigSourceOptions, 'reloadInterval'>;\n}\n\n/** @public */\nexport const rootConfigServiceFactory = createServiceFactory(\n (options?: RootConfigFactoryOptions) => ({\n service: coreServices.rootConfig,\n deps: {},\n async factory() {\n const source = ConfigSources.default({\n argv: options?.argv,\n remote: options?.remote,\n });\n console.log(`Loading config from ${source}`);\n return await ConfigSources.toConfig(source);\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ConfigReader } from '@backstage/config';\n\n/** @public */\nexport const databaseServiceFactory = createServiceFactory({\n service: coreServices.database,\n deps: {\n config: coreServices.rootConfig,\n lifecycle: coreServices.lifecycle,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async createRootContext({ config }) {\n return config.getOptional('backend.database')\n ? DatabaseManager.fromConfig(config)\n : DatabaseManager.fromConfig(\n new ConfigReader({\n backend: {\n database: { client: 'better-sqlite3', connection: ':memory:' },\n },\n }),\n );\n },\n async factory({ pluginMetadata, lifecycle }, databaseManager) {\n return databaseManager.forPlugin(pluginMetadata.getId(), {\n pluginMetadata,\n lifecycle,\n });\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HostDiscovery } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const discoveryServiceFactory = createServiceFactory({\n service: coreServices.discovery,\n deps: {\n config: coreServices.rootConfig,\n },\n async factory({ config }) {\n return HostDiscovery.fromConfig(config);\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LifecycleService } from '@backstage/backend-plugin-api';\nimport { ServiceUnavailableError } from '@backstage/errors';\nimport { HumanDuration, durationToMilliseconds } from '@backstage/types';\nimport { RequestHandler } from 'express';\n\nexport const DEFAULT_TIMEOUT = { seconds: 5 };\n\n/**\n * Options for {@link createLifecycleMiddleware}.\n * @public\n */\nexport interface LifecycleMiddlewareOptions {\n lifecycle: LifecycleService;\n /**\n * The maximum time that paused requests will wait for the service to start, before returning an error.\n *\n * Defaults to 5 seconds.\n */\n startupRequestPauseTimeout?: HumanDuration;\n}\n\n/**\n * Creates a middleware that pauses requests until the service has started.\n *\n * @remarks\n *\n * Requests that arrive before the service has started will be paused until startup is complete.\n * If the service does not start within the provided timeout, the request will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * If the service is shutting down, all requests will be rejected with a\n * {@link @backstage/errors#ServiceUnavailableError}.\n *\n * @public\n */\nexport function createLifecycleMiddleware(\n options: LifecycleMiddlewareOptions,\n): RequestHandler {\n const { lifecycle, startupRequestPauseTimeout = DEFAULT_TIMEOUT } = options;\n\n let state: 'init' | 'up' | 'down' = 'init';\n const waiting = new Set<{\n next: (err?: Error) => void;\n timeout: NodeJS.Timeout;\n }>();\n\n lifecycle.addStartupHook(async () => {\n if (state === 'init') {\n state = 'up';\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next();\n }\n waiting.clear();\n }\n });\n\n lifecycle.addShutdownHook(async () => {\n state = 'down';\n\n for (const item of waiting) {\n clearTimeout(item.timeout);\n item.next(new ServiceUnavailableError('Service is shutting down'));\n }\n waiting.clear();\n });\n\n const timeoutMs = durationToMilliseconds(startupRequestPauseTimeout);\n\n return (_req, _res, next) => {\n if (state === 'up') {\n next();\n return;\n } else if (state === 'down') {\n next(new ServiceUnavailableError('Service is shutting down'));\n return;\n }\n\n const item = {\n next,\n timeout: setTimeout(() => {\n if (waiting.delete(item)) {\n next(new ServiceUnavailableError('Service has not started up yet'));\n }\n }, timeoutMs),\n };\n\n waiting.add(item);\n };\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { Handler } from 'express';\nimport PromiseRouter from 'express-promise-router';\nimport { createLifecycleMiddleware } from './createLifecycleMiddleware';\n\n/**\n * @public\n */\nexport interface HttpRouterFactoryOptions {\n /**\n * A callback used to generate the path for each plugin, defaults to `/api/{pluginId}`.\n */\n getPath?(pluginId: string): string;\n}\n\n/** @public */\nexport const httpRouterServiceFactory = createServiceFactory(\n (options?: HttpRouterFactoryOptions) => ({\n service: coreServices.httpRouter,\n deps: {\n plugin: coreServices.pluginMetadata,\n lifecycle: coreServices.lifecycle,\n rootHttpRouter: coreServices.rootHttpRouter,\n },\n async factory({ plugin, rootHttpRouter, lifecycle }) {\n const getPath = options?.getPath ?? (id => `/api/${id}`);\n const path = getPath(plugin.getId());\n\n const router = PromiseRouter();\n rootHttpRouter.use(path, router);\n\n router.use(createLifecycleMiddleware({ lifecycle }));\n\n return {\n use(handler: Handler) {\n router.use(handler);\n },\n };\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { DefaultIdentityClient } from '@backstage/plugin-auth-node';\n\n/**\n * An identity client options object which allows extra configurations\n *\n * @public\n */\nexport type IdentityFactoryOptions = {\n issuer?: string;\n\n /** JWS \"alg\" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.\n * More info on supported algorithms: https://github.com/panva/jose */\n algorithms?: string[];\n};\n\n/** @public */\nexport const identityServiceFactory = createServiceFactory(\n (options?: IdentityFactoryOptions) => ({\n service: coreServices.identity,\n deps: {\n discovery: coreServices.discovery,\n },\n async factory({ discovery }) {\n return DefaultIdentityClient.create({ discovery, ...options });\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const loggerServiceFactory = createServiceFactory({\n service: coreServices.logger,\n deps: {\n rootLogger: coreServices.rootLogger,\n plugin: coreServices.pluginMetadata,\n },\n factory({ rootLogger, plugin }) {\n return rootLogger.child({ plugin: plugin.getId() });\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerPermissionClient } from '@backstage/plugin-permission-node';\n\n/** @public */\nexport const permissionsServiceFactory = createServiceFactory({\n service: coreServices.permissions,\n deps: {\n config: coreServices.rootConfig,\n discovery: coreServices.discovery,\n tokenManager: coreServices.tokenManager,\n },\n async factory({ config, discovery, tokenManager }) {\n return ServerPermissionClient.fromConfig(config, {\n discovery,\n tokenManager,\n });\n },\n});\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RootHttpRouterService } from '@backstage/backend-plugin-api';\nimport { Handler, Router } from 'express';\nimport trimEnd from 'lodash/trimEnd';\n\nfunction normalizePath(path: string): string {\n return `${trimEnd(path, '/')}/`;\n}\n\n/**\n * Options for the {@link DefaultRootHttpRouter} class.\n *\n * @public\n */\nexport interface DefaultRootHttpRouterOptions {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n}\n\n/**\n * The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for\n * {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.\n *\n * @public\n */\nexport class DefaultRootHttpRouter implements RootHttpRouterService {\n #indexPath?: string;\n\n #router = Router();\n #namedRoutes = Router();\n #indexRouter = Router();\n #existingPaths = new Array<string>();\n\n static create(options?: DefaultRootHttpRouterOptions) {\n let indexPath;\n if (options?.indexPath === false) {\n indexPath = undefined;\n } else if (options?.indexPath === undefined) {\n indexPath = '/api/app';\n } else if (options?.indexPath === '') {\n throw new Error('indexPath option may not be an empty string');\n } else {\n indexPath = options.indexPath;\n }\n return new DefaultRootHttpRouter(indexPath);\n }\n\n private constructor(indexPath?: string) {\n this.#indexPath = indexPath;\n this.#router.use(this.#namedRoutes);\n if (this.#indexPath) {\n this.#router.use(this.#indexRouter);\n }\n }\n\n use(path: string, handler: Handler) {\n if (path.match(/^[/\\s]*$/)) {\n throw new Error(`Root router path may not be empty`);\n }\n const conflictingPath = this.#findConflictingPath(path);\n if (conflictingPath) {\n throw new Error(\n `Path ${path} conflicts with the existing path ${conflictingPath}`,\n );\n }\n this.#existingPaths.push(path);\n this.#namedRoutes.use(path, handler);\n\n if (this.#indexPath === path) {\n this.#indexRouter.use(handler);\n }\n }\n\n handler(): Handler {\n return this.#router;\n }\n\n #findConflictingPath(newPath: string): string | undefined {\n const normalizedNewPath = normalizePath(newPath);\n for (const path of this.#existingPaths) {\n const normalizedPath = normalizePath(path);\n if (normalizedPath.startsWith(normalizedNewPath)) {\n return path;\n }\n if (normalizedNewPath.startsWith(normalizedPath)) {\n return path;\n }\n }\n return undefined;\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RootConfigService,\n coreServices,\n createServiceFactory,\n LifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport express, { RequestHandler, Express } from 'express';\nimport {\n createHttpServer,\n MiddlewareFactory,\n readHttpServerOptions,\n} from '../../../http';\nimport { DefaultRootHttpRouter } from './DefaultRootHttpRouter';\n\n/**\n * @public\n */\nexport interface RootHttpRouterConfigureContext {\n app: Express;\n middleware: MiddlewareFactory;\n routes: RequestHandler;\n config: RootConfigService;\n logger: LoggerService;\n lifecycle: LifecycleService;\n}\n\n/**\n * @public\n */\nexport type RootHttpRouterFactoryOptions = {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n\n configure?(context: RootHttpRouterConfigureContext): void;\n};\n\nfunction defaultConfigure(context: RootHttpRouterConfigureContext) {\n const { app, routes, middleware } = context;\n app.use(middleware.helmet());\n app.use(middleware.cors());\n app.use(middleware.compression());\n app.use(middleware.logging());\n app.use(routes);\n app.use(middleware.notFound());\n app.use(middleware.error());\n}\n\n/** @public */\nexport const rootHttpRouterServiceFactory = createServiceFactory(\n (options?: RootHttpRouterFactoryOptions) => ({\n service: coreServices.rootHttpRouter,\n deps: {\n config: coreServices.rootConfig,\n rootLogger: coreServices.rootLogger,\n lifecycle: coreServices.rootLifecycle,\n },\n async factory({ config, rootLogger, lifecycle }) {\n const { indexPath, configure = defaultConfigure } = options ?? {};\n const logger = rootLogger.child({ service: 'rootHttpRouter' });\n const app = express();\n\n const router = DefaultRootHttpRouter.create({ indexPath });\n const middleware = MiddlewareFactory.create({ config, logger });\n\n configure({\n app,\n routes: router.handler(),\n middleware,\n config,\n logger,\n lifecycle,\n });\n\n const server = await createHttpServer(\n app,\n readHttpServerOptions(config.getOptionalConfig('backend')),\n { logger },\n );\n\n lifecycle.addShutdownHook(() => server.stop());\n\n await server.start();\n\n return router;\n },\n }),\n);\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { WinstonLogger } from '../../../logging';\nimport { transports, format } from 'winston';\nimport { createConfigSecretEnumerator } from '../../../config';\n\n/** @public */\nexport const rootLoggerServiceFactory = createServiceFactory({\n service: coreServices.rootLogger,\n deps: {\n config: coreServices.rootConfig,\n },\n async factory({ config }) {\n const logger = WinstonLogger.create({\n meta: {\n service: 'backstage',\n },\n level: process.env.LOG_LEVEL || 'info',\n format:\n process.env.NODE_ENV === 'production'\n ? format.json()\n : WinstonLogger.colorFormat(),\n transports: [new transports.Console()],\n });\n\n const secretEnumerator = await createConfigSecretEnumerator({ logger });\n logger.addRedactions(secretEnumerator(config));\n config.subscribe?.(() => logger.addRedactions(secretEnumerator(config)));\n\n return logger;\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { TaskScheduler } from '@backstage/backend-tasks';\n\n/** @public */\nexport const schedulerServiceFactory = createServiceFactory({\n service: coreServices.scheduler,\n deps: {\n plugin: coreServices.pluginMetadata,\n databaseManager: coreServices.database,\n logger: coreServices.logger,\n },\n async factory({ plugin, databaseManager, logger }) {\n return TaskScheduler.forPlugin({\n pluginId: plugin.getId(),\n databaseManager,\n logger: loggerToWinstonLogger(logger),\n });\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerTokenManager } from '@backstage/backend-common';\n\n/** @public */\nexport const tokenManagerServiceFactory = createServiceFactory({\n service: coreServices.tokenManager,\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.rootLogger,\n },\n createRootContext({ config, logger }) {\n return ServerTokenManager.fromConfig(config, {\n logger,\n });\n },\n async factory(_deps, tokenManager) {\n return tokenManager;\n },\n});\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { loggerToWinstonLogger, UrlReaders } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const urlReaderServiceFactory = createServiceFactory({\n service: coreServices.urlReader,\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.logger,\n },\n async factory({ config, logger }) {\n return UrlReaders.default({\n config,\n logger: loggerToWinstonLogger(logger),\n });\n },\n});\n"],"names":["ConfigReader","getPackages","loadConfigSchema","parseArgs","resolvePath","findPaths","config","loadConfig","fs","dirname","forge","stoppableServer","https","http","helmet","Minimatch","__privateAdd","__privateSet","compression","__privateGet","morgan","cors","serializeError","NotModifiedError","InputError","AuthenticationError","NotAllowedError","NotFoundError","ConflictError","NotImplementedError","ServiceUnavailableError","createLogger","format","transports","_hasStarted","_startupTasks","createServiceFactory","coreServices","__privateMethod","ForwardedError","lifecycleService","_a","stringifyError","CacheManager","ConfigSources","DatabaseManager","HostDiscovery","durationToMilliseconds","PromiseRouter","DefaultIdentityClient","ServerPermissionClient","trimEnd","Router","express","TaskScheduler","loggerToWinstonLogger","ServerTokenManager","UrlReaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBO,MAAM,qBAAwC,CAAA;AAAA,EAKnD,WAAA,CACmB,QACT,SACR,EAAA;AAFiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AACT,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA,CAAA;AANV,IAAA,aAAA,CAAA,IAAA,EAAQ,QAAiB,EAAA,IAAIA,mBAAa,CAAA,EAAE,CAAA,CAAA,CAAA;AAE5C,IAAA,aAAA,CAAA,IAAA,EAAiB,eAA8B,EAAC,CAAA,CAAA;AAM9C,IAAI,IAAA,MAAA,IAAU,CAAC,SAAW,EAAA;AACxB,MAAM,MAAA,IAAI,MAAM,wCAAwC,CAAA,CAAA;AAAA,KAC1D;AAAA,GACF;AAAA,EAEA,UAAU,MAAgB,EAAA;AACxB,IAAA,IAAI,KAAK,MAAQ,EAAA;AACf,MAAM,MAAA,IAAI,MAAM,WAAW,CAAA,CAAA;AAAA,KAC7B;AACA,IAAA,IAAA,CAAK,MAAS,GAAA,MA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SAAU,CAAA;AAAA,MAC7B,QAAA,EAAU,OAAO,KAAM,EAAA;AAAA,MACvB,eAAA;AAAA,MACA,MAAA,EAAQC,oCAAsB,MAAM,CAAA;AAAA,KACrC,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;ACfM,MAAM,6BAA6BnB,qCAAqB,CAAA;AAAA,EAC7D,SAASC,6BAAa,CAAA,YAAA;AAAA,EACtB,IAAM,EAAA;AAAA,IACJ,QAAQA,6BAAa,CAAA,UAAA;AAAA,IACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,GACvB;AAAA,EACA,iBAAkB,CAAA,EAAE,MAAQ,EAAA,MAAA,EAAU,EAAA;AACpC,IAAO,OAAAmB,gCAAA,CAAmB,WAAW,MAAQ,EAAA;AAAA,MAC3C,MAAA;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AAAA,EACA,MAAM,OAAQ,CAAA,KAAA,EAAO,YAAc,EAAA;AACjC,IAAO,OAAA,YAAA,CAAA;AAAA,GACT;AACF,CAAC;;ACdM,MAAM,0BAA0BpB,qCAAqB,CAAA;AAAA,EAC1D,SAASC,6BAAa,CAAA,SAAA;AAAA,EACtB,IAAM,EAAA;AAAA,IACJ,QAAQA,6BAAa,CAAA,UAAA;AAAA,IACrB,QAAQA,6BAAa,CAAA,MAAA;AAAA,GACvB;AAAA,EACA,MAAM,OAAA,CAAQ,EAAE,MAAA,EAAQ,QAAU,EAAA;AAChC,IAAA,OAAOoB,yBAAW,OAAQ,CAAA;AAAA,MACxB,MAAA;AAAA,MACA,MAAA,EAAQF,oCAAsB,MAAM,CAAA;AAAA,KACrC,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
3
- import { LoggerService, ConfigService, RootLoggerService, BackendFeature, ServiceFactoryOrFunction, LifecycleService, RootHttpRouterService, RootLifecycleService } from '@backstage/backend-plugin-api';
3
+ import { LoggerService, RootConfigService, RootLoggerService, BackendFeature, ServiceFactoryOrFunction, LifecycleService, RootHttpRouterService, RootLifecycleService } from '@backstage/backend-plugin-api';
4
4
  import { LoadConfigOptionsRemote, RemoteConfigSourceOptions } from '@backstage/config-loader';
5
5
  import { Config, AppConfig } from '@backstage/config';
6
6
  import * as http from 'http';
@@ -102,7 +102,7 @@ declare function createHttpServer(listener: RequestListener, options: HttpServer
102
102
  * @public
103
103
  */
104
104
  interface MiddlewareFactoryOptions {
105
- config: ConfigService;
105
+ config: RootConfigService;
106
106
  logger: LoggerService;
107
107
  }
108
108
  /**
@@ -309,7 +309,7 @@ declare function createSpecializedBackend(options: CreateSpecializedBackendOptio
309
309
  declare const cacheServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_common.CacheClient, "plugin">;
310
310
 
311
311
  /** @public */
312
- interface ConfigFactoryOptions {
312
+ interface RootConfigFactoryOptions {
313
313
  /**
314
314
  * Process arguments to use instead of the default `process.argv()`.
315
315
  */
@@ -320,7 +320,7 @@ interface ConfigFactoryOptions {
320
320
  remote?: Pick<RemoteConfigSourceOptions, 'reloadInterval'>;
321
321
  }
322
322
  /** @public */
323
- declare const configServiceFactory: (options?: ConfigFactoryOptions | undefined) => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.ConfigService, "root">;
323
+ declare const rootConfigServiceFactory: (options?: RootConfigFactoryOptions | undefined) => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.RootConfigService, "root">;
324
324
 
325
325
  /** @public */
326
326
  declare const databaseServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_common.PluginDatabaseManager, "plugin">;
@@ -402,7 +402,7 @@ interface RootHttpRouterConfigureContext {
402
402
  app: Express;
403
403
  middleware: MiddlewareFactory;
404
404
  routes: RequestHandler;
405
- config: ConfigService;
405
+ config: RootConfigService;
406
406
  logger: LoggerService;
407
407
  lifecycle: LifecycleService;
408
408
  }
@@ -465,4 +465,4 @@ declare const tokenManagerServiceFactory: () => _backstage_backend_plugin_api.Se
465
465
  /** @public */
466
466
  declare const urlReaderServiceFactory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_common.UrlReader, "plugin">;
467
467
 
468
- export { Backend, ConfigFactoryOptions, CreateSpecializedBackendOptions, DefaultRootHttpRouter, DefaultRootHttpRouterOptions, ExtendedHttpServer, HttpRouterFactoryOptions, HttpServerCertificateOptions, HttpServerOptions, IdentityFactoryOptions, LifecycleMiddlewareOptions, MiddlewareFactory, MiddlewareFactoryErrorOptions, MiddlewareFactoryOptions, RootHttpRouterConfigureContext, RootHttpRouterFactoryOptions, WinstonLogger, WinstonLoggerOptions, cacheServiceFactory, configServiceFactory, createConfigSecretEnumerator, createHttpServer, createLifecycleMiddleware, createSpecializedBackend, databaseServiceFactory, discoveryServiceFactory, httpRouterServiceFactory, identityServiceFactory, lifecycleServiceFactory, loadBackendConfig, loggerServiceFactory, permissionsServiceFactory, readCorsOptions, readHelmetOptions, readHttpServerOptions, rootHttpRouterServiceFactory, rootLifecycleServiceFactory, rootLoggerServiceFactory, schedulerServiceFactory, tokenManagerServiceFactory, urlReaderServiceFactory };
468
+ export { Backend, CreateSpecializedBackendOptions, DefaultRootHttpRouter, DefaultRootHttpRouterOptions, ExtendedHttpServer, 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 };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@backstage/backend-app-api",
3
3
  "description": "Core API used by Backstage backend apps",
4
- "version": "0.4.6-next.0",
4
+ "version": "0.5.0-next.1",
5
5
  "main": "dist/index.cjs.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "publishConfig": {
@@ -32,15 +32,15 @@
32
32
  "start": "backstage-cli package start"
33
33
  },
34
34
  "dependencies": {
35
- "@backstage/backend-common": "^0.19.2-next.0",
36
- "@backstage/backend-plugin-api": "^0.5.5-next.0",
37
- "@backstage/backend-tasks": "^0.5.5-next.0",
35
+ "@backstage/backend-common": "^0.19.2-next.1",
36
+ "@backstage/backend-plugin-api": "^0.6.0-next.1",
37
+ "@backstage/backend-tasks": "^0.5.5-next.1",
38
38
  "@backstage/cli-common": "^0.1.12",
39
39
  "@backstage/config": "^1.0.8",
40
- "@backstage/config-loader": "^1.4.0-next.0",
40
+ "@backstage/config-loader": "^1.4.0-next.1",
41
41
  "@backstage/errors": "^1.2.1",
42
- "@backstage/plugin-auth-node": "^0.2.17-next.0",
43
- "@backstage/plugin-permission-node": "^0.7.11-next.0",
42
+ "@backstage/plugin-auth-node": "^0.2.17-next.1",
43
+ "@backstage/plugin-permission-node": "^0.7.11-next.1",
44
44
  "@backstage/types": "^1.1.0",
45
45
  "@manypkg/get-packages": "^1.1.3",
46
46
  "@types/cors": "^2.8.6",
@@ -63,8 +63,8 @@
63
63
  "winston-transport": "^4.5.0"
64
64
  },
65
65
  "devDependencies": {
66
- "@backstage/backend-test-utils": "^0.1.40-next.0",
67
- "@backstage/cli": "^0.22.10-next.0",
66
+ "@backstage/backend-test-utils": "^0.2.0-next.1",
67
+ "@backstage/cli": "^0.22.10-next.1",
68
68
  "@types/compression": "^1.7.0",
69
69
  "@types/fs-extra": "^9.0.3",
70
70
  "@types/http-errors": "^2.0.0",