diff --git a/.changeset/2798.md b/.changeset/2798.md new file mode 100644 index 0000000000..2b202142ef --- /dev/null +++ b/.changeset/2798.md @@ -0,0 +1,7 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Use the new `UrlReader` in `PlaceholderProcessor`. +This allows to use the placeholder processor to include API definitions in API entities. +Previously it was only possible to do this if the definition comes from the same location type as the entity itself. diff --git a/.changeset/2800.md b/.changeset/2800.md new file mode 100644 index 0000000000..0e051b0557 --- /dev/null +++ b/.changeset/2800.md @@ -0,0 +1,15 @@ +--- +'@backstage/core': minor +'@backstage/core-api': minor +--- + +Updated the `GithubAuth.create` method to configure the default scope of the Github Auth Api. As a result the +default scope is configurable when overwriting the Core Api in the app. + +``` +GithubAuth.create({ + discoveryApi, + oauthRequestApi, + defaultScopes: ['read:user', 'repo'], +}), +``` diff --git a/.changeset/2803.md b/.changeset/2803.md new file mode 100644 index 0000000000..3a4773757f --- /dev/null +++ b/.changeset/2803.md @@ -0,0 +1,26 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Remove the backstage.io/definition-at-location annotation. +The annotation was superseded by the placeholder processor. + +```yaml +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: spotify + description: The Spotify web API + tags: + - spotify + - rest + annotations: + # Don't use this annotation, but the placeholder $text instead (see below). + backstage.io/definition-at-location: 'url:https://raw.githubusercontent.com/APIs-guru/openapi-directory/master/APIs/spotify.com/v1/swagger.yaml' +spec: + type: openapi + lifecycle: production + owner: spotify@example.com + definition: + $text: https://raw.githubusercontent.com/APIs-guru/openapi-directory/master/APIs/spotify.com/v1/swagger.yaml +``` diff --git a/.changeset/2804.md b/.changeset/2804.md new file mode 100644 index 0000000000..5223a24791 --- /dev/null +++ b/.changeset/2804.md @@ -0,0 +1,15 @@ +--- +'@backstage/plugin-proxy-backend': minor +--- + +Limit the http headers that are forwarded from the request to a safe set of defaults. +A user can configure additional headers that should be forwarded if the specific applications needs that. + +```yaml +proxy: + '/my-api': + target: 'https://my-api.com/get' + allowedHeaders: + # We need to forward the Authorization header that was provided by the caller + - Authorization +``` diff --git a/.changeset/2826.md b/.changeset/2826.md new file mode 100644 index 0000000000..fb2dbb6877 --- /dev/null +++ b/.changeset/2826.md @@ -0,0 +1,20 @@ +--- +'example-app': minor +'@backstage/core': minor +'@backstage/create-app': minor +'@backstage/plugin-catalog': minor +'@backstage/plugin-github-actions': minor +'@backstage/plugin-jenkins': minor +'@backstage/plugin-lighthouse': minor +--- + +The InfoCard variant `'height100'` is deprecated. Use variant `'gridItem'` instead. + +When the InfoCard is displayed as a grid item within a grid, you may want items to have the same height for all items. +Set to the `'gridItem'` variant to display the InfoCard with full height suitable for Grid: +`...` + +Changed the InfoCards in '@backstage/plugin-github-actions', '@backstage/plugin-jenkins', '@backstage/plugin-lighthouse' +to pass an optional variant to the corresponding card of the plugin. + +As a result the overview content of the EntityPage shows cards with full height suitable for Grid. diff --git a/.changeset/2874.md b/.changeset/2874.md new file mode 100644 index 0000000000..693962314f --- /dev/null +++ b/.changeset/2874.md @@ -0,0 +1,12 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +The way that wiring together a catalog happens, has changed drastically. Now +there is a new class `CatalogBuilder` that does almost all of the heavy lifting +of how to augment/replace pieces of catalog functionality, such as adding +support for custom entities or adding additional processors. + +As the builder was added, a lot of the static methods and builders for default +setups have been removed from classes deep in the hierarchy. Instead, the +builder contains the knowledge of what the defaults are. diff --git a/.changeset/3030.md b/.changeset/3030.md new file mode 100644 index 0000000000..89730dc14c --- /dev/null +++ b/.changeset/3030.md @@ -0,0 +1,5 @@ +--- +'@backstage/backend-common': minor +--- + +Add the ability to import components from Bitbucket Server to the service catalog diff --git a/.changeset/3066.md b/.changeset/3066.md new file mode 100644 index 0000000000..7bb67e70d1 --- /dev/null +++ b/.changeset/3066.md @@ -0,0 +1,12 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Filters passed to the `/entities` endpoint of the catalog has changed format. + +The old way was to pass things on the form `?a=b&c=d`; the new way is to pass +things on the form `?filter=a=b,c=d`. See discussion in +[#2910](https://github.com/spotify/backstage/issues/2910) for details. + +The comma separated items within a single filter have an AND between them. If +multiple such filters are passed, they have an OR between those item groups. diff --git a/.changeset/3130.md b/.changeset/3130.md new file mode 100644 index 0000000000..6edac9372b --- /dev/null +++ b/.changeset/3130.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': patch +--- + +Fix `CatalogBuilder#addProcessor`. diff --git a/.changeset/beige-apes-serve.md b/.changeset/beige-apes-serve.md new file mode 100644 index 0000000000..54ee39a85e --- /dev/null +++ b/.changeset/beige-apes-serve.md @@ -0,0 +1,5 @@ +--- +'example-app': patch +--- + +Add Pull Request tab to components view. diff --git a/.changeset/blue-donkeys-exercise.md b/.changeset/blue-donkeys-exercise.md new file mode 100644 index 0000000000..4f714e3c97 --- /dev/null +++ b/.changeset/blue-donkeys-exercise.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog': minor +--- + +Add client side paging for catalog table diff --git a/.changeset/carpal-tunnel-driver.md b/.changeset/carpal-tunnel-driver.md new file mode 100644 index 0000000000..2e6a814533 --- /dev/null +++ b/.changeset/carpal-tunnel-driver.md @@ -0,0 +1,13 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +- The `CatalogProcessor` API was updated to have `preProcessEntity` and + `postProcessEntity` methods, instead of just one `processEntity`. This makes + it easier to make processors that have several stages in one, and to make + different processors more position independent in the list of processors. +- The `EntityPolicy` is now given directly to the `LocationReaders`, instead of + being enforced inside a policy. We have decided to separate out the act of + validating an entity to be outside of the processing flow, to make it + possible to apply more liberally and to evolve it as a separate concept. +- Because of the above, the `EntityPolicyProcessor` has been removed. diff --git a/.changeset/chilly-emus-fetch.md b/.changeset/chilly-emus-fetch.md new file mode 100644 index 0000000000..ad77c90f4e --- /dev/null +++ b/.changeset/chilly-emus-fetch.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder-backend': patch +--- + +Added .fromConfig static factories for Preparers and Publishers + read integrations config to support url location types diff --git a/.changeset/clean-phones-vanish.md b/.changeset/clean-phones-vanish.md new file mode 100644 index 0000000000..4c80b82f24 --- /dev/null +++ b/.changeset/clean-phones-vanish.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-cost-insights': patch +--- + +export test utilities for mocking context diff --git a/.changeset/cli-parallel-build-options.md b/.changeset/cli-parallel-build-options.md new file mode 100644 index 0000000000..95f9360738 --- /dev/null +++ b/.changeset/cli-parallel-build-options.md @@ -0,0 +1,12 @@ +--- +'@backstage/cli': minor +--- + +Adds a new `BACKSTAGE_CLI_BUILD_PARELLEL` environment variable to control +parallelism for some build steps. + +This is useful in CI to help avoid out of memory issues when using `terser`. The +`BACKSTAGE_CLI_BUILD_PARELLEL` environment variable can be set to +`true | false | [integer]` to override the default behaviour. See +[terser-webpack-plugin](https://github.com/webpack-contrib/terser-webpack-plugin#parallel) +for more details. diff --git a/.changeset/codeowner-processor-url-reader.md b/.changeset/codeowner-processor-url-reader.md new file mode 100644 index 0000000000..af4eb0997f --- /dev/null +++ b/.changeset/codeowner-processor-url-reader.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Use the new `UrlReader` in the `CodeOwnersProcessor`. diff --git a/.changeset/config.json b/.changeset/config.json index c7c4f11e57..44a8523265 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -2,55 +2,7 @@ "$schema": "https://unpkg.com/@changesets/config@1.3.0/schema.json", "changelog": "@changesets/cli/changelog", "commit": false, - "linked": [ - [ - "example-app", - "@backstage/backend-common", - "example-backend", - "@backstage/catalog-model", - "@backstage/cli-common", - "@backstage/cli", - "@backstage/config-loader", - "@backstage/config", - "@backstage/core-api", - "@backstage/core", - "@backstage/create-app", - "@backstage/dev-utils", - "docgen", - "e2e-test", - "storybook", - "@techdocs/cli", - "@backstage/test-utils-core", - "@backstage/test-utils", - "@backstage/theme", - "@backstage/plugin-api-docs", - "@backstage/plugin-app-backend", - "@backstage/plugin-auth-backend", - "@backstage/plugin-catalog-backend", - "@backstage/plugin-catalog", - "@backstage/plugin-circleci", - "@backstage/plugin-gcp-projects", - "@backstage/plugin-github-actions", - "@backstage/plugin-gitops-profiles", - "@backstage/plugin-graphiql", - "@backstage/plugin-graphql-backend", - "@backstage/plugin-jenkins", - "@backstage/plugin-lighthouse", - "@backstage/plugin-newrelic", - "@backstage/plugin-proxy-backend", - "@backstage/plugin-register-component", - "@backstage/plugin-rollbar-backend", - "@backstage/plugin-rollbar", - "@backstage/plugin-scaffolder-backend", - "@backstage/plugin-scaffolder", - "@backstage/plugin-sentry-backend", - "@backstage/plugin-sentry", - "@backstage/plugin-tech-radar", - "@backstage/plugin-techdocs-backend", - "@backstage/plugin-techdocs", - "@backstage/plugin-welcome" - ] - ], + "linked": [["*"]], "access": "public", "baseBranch": "master", "updateInternalDependencies": "patch", diff --git a/.changeset/cost-insights-sparkle.md b/.changeset/cost-insights-sparkle.md new file mode 100644 index 0000000000..c332502476 --- /dev/null +++ b/.changeset/cost-insights-sparkle.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-cost-insights': minor +--- + +Added getLastCompleteBillingDate to the CostInsightsApi to reason about completeness of billing data diff --git a/.changeset/cost-insights-swift-carrots-bake.md b/.changeset/cost-insights-swift-carrots-bake.md new file mode 100644 index 0000000000..bc378ad247 --- /dev/null +++ b/.changeset/cost-insights-swift-carrots-bake.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-cost-insights': patch +--- + +prefer named exports diff --git a/.changeset/cyan-plants-dress.md b/.changeset/cyan-plants-dress.md new file mode 100644 index 0000000000..19ebc63e53 --- /dev/null +++ b/.changeset/cyan-plants-dress.md @@ -0,0 +1,5 @@ +--- +'example-backend': patch +--- + +Pass GitHub token into Scaffolder GitHub Preparer diff --git a/.changeset/dull-icons-share.md b/.changeset/dull-icons-share.md new file mode 100644 index 0000000000..aa4c01e422 --- /dev/null +++ b/.changeset/dull-icons-share.md @@ -0,0 +1,21 @@ +--- +'@backstage/backend-common': minor +'@backstage/cli': minor +'@backstage/config-loader': minor +'example-backend': patch +'@backstage/create-app': patch +--- + +**BREAKING CHANGE** + +The existing loading of additional config files like `app-config.development.yaml` using APP_ENV or NODE_ENV has been removed. +Instead, the CLI and backend process now accept one or more `--config` flags to load config files. + +Without passing any flags, `app-config.yaml` and, if it exists, `app-config.local.yaml` will be loaded. +If passing any `--config ` flags, only those files will be loaded, **NOT** the default `app-config.yaml` one. + +The old behaviour of for example `APP_ENV=development` can be replicated using the following flags: + +```bash +--config ../../app-config.yaml --config ../../app-config.development.yaml +``` diff --git a/.changeset/eighty-lamps-smell.md b/.changeset/eighty-lamps-smell.md new file mode 100644 index 0000000000..85dfba4f82 --- /dev/null +++ b/.changeset/eighty-lamps-smell.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog': patch +--- + +handle the case where no entities are available to show diff --git a/.changeset/eighty-stingrays-type.md b/.changeset/eighty-stingrays-type.md new file mode 100644 index 0000000000..731c401b77 --- /dev/null +++ b/.changeset/eighty-stingrays-type.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +Add forwardRef to the SidebarItem diff --git a/.changeset/flat-bugs-do.md b/.changeset/flat-bugs-do.md new file mode 100644 index 0000000000..672daf657d --- /dev/null +++ b/.changeset/flat-bugs-do.md @@ -0,0 +1,8 @@ +--- +'@backstage/core': patch +'@backstage/plugin-graphiql': patch +'@backstage/plugin-tech-radar': patch +'@backstage/plugin-techdocs': patch +--- + +add test case for Progress component diff --git a/.changeset/flat-yaks-march.md b/.changeset/flat-yaks-march.md new file mode 100644 index 0000000000..6b26206eb8 --- /dev/null +++ b/.changeset/flat-yaks-march.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder': patch +--- + +fix the accordion details design when job stage fail diff --git a/.changeset/funny-readers-breathe.md b/.changeset/funny-readers-breathe.md new file mode 100644 index 0000000000..8897b24cf6 --- /dev/null +++ b/.changeset/funny-readers-breathe.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +fix the warning of all the core components test cases diff --git a/.changeset/fuzzy-falcons-happen.md b/.changeset/fuzzy-falcons-happen.md new file mode 100644 index 0000000000..461ac195d9 --- /dev/null +++ b/.changeset/fuzzy-falcons-happen.md @@ -0,0 +1,5 @@ +--- +'e2e-test': minor +--- + +Converted into a CLI, use `yarn e2e-test run` to run diff --git a/.changeset/good-islands-cheer.md b/.changeset/good-islands-cheer.md new file mode 100644 index 0000000000..2e7109b312 --- /dev/null +++ b/.changeset/good-islands-cheer.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-cost-insights': minor +--- + +Enable custom alert types in Cost Insights diff --git a/.changeset/great-apples-flash.md b/.changeset/great-apples-flash.md new file mode 100644 index 0000000000..78ad89dee0 --- /dev/null +++ b/.changeset/great-apples-flash.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': patch +--- + +Fix CodeOwnersProcessor to handle non team users diff --git a/.changeset/happy-ads-behave.md b/.changeset/happy-ads-behave.md new file mode 100644 index 0000000000..f8b889f85c --- /dev/null +++ b/.changeset/happy-ads-behave.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder-backend': patch +--- + +Allow templates to be located on non-default branch diff --git a/.changeset/heavy-berries-hear.md b/.changeset/heavy-berries-hear.md new file mode 100644 index 0000000000..66aa6d93e1 --- /dev/null +++ b/.changeset/heavy-berries-hear.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +Update ItemCard headers to pass color contrast standards. diff --git a/.changeset/hungry-parrots-work.md b/.changeset/hungry-parrots-work.md new file mode 100644 index 0000000000..a18218b542 --- /dev/null +++ b/.changeset/hungry-parrots-work.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +rename stories folder top Chip diff --git a/.changeset/little-wasps-pull.md b/.changeset/little-wasps-pull.md new file mode 100644 index 0000000000..732c7506b0 --- /dev/null +++ b/.changeset/little-wasps-pull.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog': patch +--- + +Remove "in default" in component name diff --git a/.changeset/long-ways-count.md b/.changeset/long-ways-count.md new file mode 100644 index 0000000000..e04c1225cc --- /dev/null +++ b/.changeset/long-ways-count.md @@ -0,0 +1,57 @@ +--- +'@backstage/plugin-techdocs-backend': minor +'@backstage/create-app': patch +--- + +Updated naming of environment variables. New pattern [NAME]\_TOKEN for Github, Gitlab, Azure & Github enterprise access tokens. + +### Detail: + +- Previously we have to export same token for both, catalog & scaffolder + +```bash +export GITHUB_ACCESS_TOKEN=foo +export GITHUB_PRIVATE_TOKEN=foo +``` + +with latest changes, only single export is sufficient. + +```bash +export GITHUB_TOKEN=foo +export GITLAB_TOKEN=foo +export GHE_TOKEN=foo +export AZURE_TOKEN=foo +``` + +### list: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Old nameNew name
GITHUB_ACCESS_TOKENGITHUB_TOKEN
GITHUB_PRIVATE_TOKENGITHUB_TOKEN
GITLAB_ACCESS_TOKENGITLAB_TOKEN
GITLAB_PRIVATE_TOKENGITLAB_TOKEN
AZURE_PRIVATE_TOKENAZURE_TOKEN
GHE_PRIVATE_TOKENGHE_TOKEN
diff --git a/.changeset/loud-lamps-visit.md b/.changeset/loud-lamps-visit.md new file mode 100644 index 0000000000..9023061643 --- /dev/null +++ b/.changeset/loud-lamps-visit.md @@ -0,0 +1,5 @@ +--- +'@backstage/cli': patch +--- + +Including source maps with all packages diff --git a/.changeset/lovely-suits-flash.md b/.changeset/lovely-suits-flash.md new file mode 100644 index 0000000000..f093290c85 --- /dev/null +++ b/.changeset/lovely-suits-flash.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +update the test cases of CodeSnippet component diff --git a/.changeset/mighty-starfishes-taste.md b/.changeset/mighty-starfishes-taste.md new file mode 100644 index 0000000000..eb43ce69b8 --- /dev/null +++ b/.changeset/mighty-starfishes-taste.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Removed the parseData step from catalog processors. Locations readers should emit full entities instead. diff --git a/.changeset/ninety-pens-poke.md b/.changeset/ninety-pens-poke.md new file mode 100644 index 0000000000..94bcb06749 --- /dev/null +++ b/.changeset/ninety-pens-poke.md @@ -0,0 +1,5 @@ +--- +'@backstage/create-app': patch +--- + +Fix for configured templates using 'url' locations even though it's not supported yet diff --git a/.changeset/old-eagles-admire.md b/.changeset/old-eagles-admire.md new file mode 100644 index 0000000000..0729b6439d --- /dev/null +++ b/.changeset/old-eagles-admire.md @@ -0,0 +1,6 @@ +--- +'@backstage/backend-common': minor +'@backstage/cli': minor +--- + +Use APP_ENV before NODE_ENV for determining what config to load diff --git a/.changeset/old-falcons-jump.md b/.changeset/old-falcons-jump.md new file mode 100644 index 0000000000..107d75ff88 --- /dev/null +++ b/.changeset/old-falcons-jump.md @@ -0,0 +1,25 @@ +--- +'@backstage/plugin-newrelic': minor +--- + +The New Relic plugin now uses the Backstage proxy to communicate with New Relic's API. + +Please update your `app-config.yaml` as follows: + +```yaml +# Old Config +newrelic: + api: + baseUrl: 'https://api.newrelic.com/v2' + key: NEW_RELIC_REST_API_KEY +``` + +```yaml +# New Config +proxy: + '/newrelic/apm/api': + target: https://api.newrelic.com/v2 + headers: + X-Api-Key: + $env: NEW_RELIC_REST_API_KEY +``` diff --git a/.changeset/olive-bikes-jog.md b/.changeset/olive-bikes-jog.md new file mode 100644 index 0000000000..fdbf1e0d9f --- /dev/null +++ b/.changeset/olive-bikes-jog.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +add test cases for Status components diff --git a/.changeset/pink-spies-rule.md b/.changeset/pink-spies-rule.md new file mode 100644 index 0000000000..71653a1841 --- /dev/null +++ b/.changeset/pink-spies-rule.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-techdocs-backend': patch +--- + +Replacing the hard coded `baseApiUrl` by reading the value from configuration to enable private GitHub setup for TechDocs. diff --git a/.changeset/polite-laws-think.md b/.changeset/polite-laws-think.md new file mode 100644 index 0000000000..a5eb7f9883 --- /dev/null +++ b/.changeset/polite-laws-think.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Removed support for deprecated `catalog.providers` config that have been moved to `integrations` diff --git a/.changeset/polite-moose-cough.md b/.changeset/polite-moose-cough.md new file mode 100644 index 0000000000..b66227bb24 --- /dev/null +++ b/.changeset/polite-moose-cough.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +update ItemCard component and it's story diff --git a/.changeset/popular-jars-serve.md b/.changeset/popular-jars-serve.md new file mode 100644 index 0000000000..6ee40195fc --- /dev/null +++ b/.changeset/popular-jars-serve.md @@ -0,0 +1,5 @@ +--- +'@backstage/catalog-model': minor +--- + +Enable adding locations for config files that does not yet exist by adding a flag to api request diff --git a/.changeset/pretty-cups-joke.md b/.changeset/pretty-cups-joke.md new file mode 100644 index 0000000000..49a1db2a75 --- /dev/null +++ b/.changeset/pretty-cups-joke.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder-backend': patch +--- + +Add authentication token to Scaffolder GitHub Preparer diff --git a/.changeset/proud-eagles-grow.md b/.changeset/proud-eagles-grow.md new file mode 100644 index 0000000000..ef83a4ad26 --- /dev/null +++ b/.changeset/proud-eagles-grow.md @@ -0,0 +1,5 @@ +--- +'@backstage/cli': patch +--- + +Fixed duplicate help output, and print help on invalid command diff --git a/.changeset/raghu-is-great.md b/.changeset/raghu-is-great.md new file mode 100644 index 0000000000..805e49f3e8 --- /dev/null +++ b/.changeset/raghu-is-great.md @@ -0,0 +1,10 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Renamed the `LocationProcessor` class to `CatalogProcessor`. + +Likewise, renamed `LocationProcessorResult`, `LocationProcessorLocationResult`, +`LocationProcessorDataResult`, `LocationProcessorEntityResult`, +`LocationProcessorErrorResult`, and `LocationProcessorEmit` to their `Catalog*` +counterparts. diff --git a/.changeset/red-games-float.md b/.changeset/red-games-float.md new file mode 100644 index 0000000000..6eabba26a4 --- /dev/null +++ b/.changeset/red-games-float.md @@ -0,0 +1,10 @@ +--- +'@backstage/plugin-cost-insights': minor +--- + +- getProjectDailyCost and getGroupDailyCost no longer accept a metric as a parameter +- getDailyMetricData added to API for fetching daily metric data for given interval +- dailyCost removed as configurable metric +- default field added to metric configuration for displaying comparison metric data in top panel +- Metric.kind can no longer be null +- MetricData type added diff --git a/.changeset/remove-location-processor-read.md b/.changeset/remove-location-processor-read.md new file mode 100644 index 0000000000..78aea6d820 --- /dev/null +++ b/.changeset/remove-location-processor-read.md @@ -0,0 +1,6 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +Remove the `read` argument of `LocationProcessor.processEntity`. +Instead, pass the `UrlReader` into the constructor of your `LocationProcessor`. diff --git a/.changeset/selfish-bats-perform.md b/.changeset/selfish-bats-perform.md new file mode 100644 index 0000000000..e4d05c088c --- /dev/null +++ b/.changeset/selfish-bats-perform.md @@ -0,0 +1,6 @@ +--- +'@backstage/plugin-scaffolder': patch +'@backstage/plugin-scaffolder-backend': patch +--- + +The new `scaffolder.github.baseUrl` config property allows to specify a custom base url for GitHub enterprise instances diff --git a/.changeset/selfish-mugs-itch.md b/.changeset/selfish-mugs-itch.md new file mode 100644 index 0000000000..39ed236352 --- /dev/null +++ b/.changeset/selfish-mugs-itch.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-cost-insights': minor +--- + +Remove product filters from query parameters diff --git a/.changeset/seven-humans-check.md b/.changeset/seven-humans-check.md new file mode 100644 index 0000000000..f2fb784cc0 --- /dev/null +++ b/.changeset/seven-humans-check.md @@ -0,0 +1,9 @@ +--- +'example-app': patch +'@backstage/core-api': patch +'@backstage/plugin-cost-insights': patch +--- + +Remove cost insights example client from demo app and export from plugin +Create cost insights dev plugin using example client +Make PluginConfig and dependent types public diff --git a/.changeset/slimy-garlics-eat.md b/.changeset/slimy-garlics-eat.md new file mode 100644 index 0000000000..3ecc0ce495 --- /dev/null +++ b/.changeset/slimy-garlics-eat.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog': patch +--- + +update the EntityNotFound component diff --git a/.changeset/slow-experts-peel.md b/.changeset/slow-experts-peel.md new file mode 100644 index 0000000000..ed9c7af21e --- /dev/null +++ b/.changeset/slow-experts-peel.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-tech-radar': patch +--- + +fix the horizontal scrolling issue in the RadarPage component diff --git a/.changeset/spicy-moles-yell.md b/.changeset/spicy-moles-yell.md new file mode 100644 index 0000000000..72b648b30b --- /dev/null +++ b/.changeset/spicy-moles-yell.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +make ErrorPage responsive + fix the test case diff --git a/.changeset/spicy-rockets-ring.md b/.changeset/spicy-rockets-ring.md new file mode 100644 index 0000000000..b39b433c1b --- /dev/null +++ b/.changeset/spicy-rockets-ring.md @@ -0,0 +1,10 @@ +--- +'@backstage/plugin-scaffolder-backend': patch +--- + +Added support for configuring the working directory of the Scaffolder: + +```yaml +backend: + workingDirectory: /some-dir # Use this to configure a working directory for the scaffolder, defaults to the OS temp-dir +``` diff --git a/.changeset/spotty-apples-visit.md b/.changeset/spotty-apples-visit.md new file mode 100644 index 0000000000..ba481fa052 --- /dev/null +++ b/.changeset/spotty-apples-visit.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-auth-backend': patch +--- + +Better presentation of authentication errors diff --git a/.changeset/sweet-bikes-battle.md b/.changeset/sweet-bikes-battle.md new file mode 100644 index 0000000000..68ed8caeeb --- /dev/null +++ b/.changeset/sweet-bikes-battle.md @@ -0,0 +1,5 @@ +--- +'example-app': patch +--- + +cleaning up because external plugins have already implemented new api for creating diff --git a/.changeset/swift-peas-argue.md b/.changeset/swift-peas-argue.md new file mode 100644 index 0000000000..d78d844d45 --- /dev/null +++ b/.changeset/swift-peas-argue.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +give aria-label attribute to Status Ok, Warning and Error diff --git a/.changeset/tough-weeks-pull.md b/.changeset/tough-weeks-pull.md new file mode 100644 index 0000000000..e79355de90 --- /dev/null +++ b/.changeset/tough-weeks-pull.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +fix the responsive of page story diff --git a/.changeset/weak-ducks-tan.md b/.changeset/weak-ducks-tan.md new file mode 100644 index 0000000000..64b1c3f117 --- /dev/null +++ b/.changeset/weak-ducks-tan.md @@ -0,0 +1,8 @@ +--- +'@backstage/backend-common': minor +'example-backend': patch +'@backstage/cli': patch +'@backstage/create-app': patch +--- + +Change loadBackendConfig to return the config directly diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 3df1031034..d161a8e1a9 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -14,3 +14,4 @@ /packages/techdocs-container @spotify/techdocs-core /.github/workflows/techdocs.yml @spotify/techdocs-core /.github/workflows/techdocs-pypi.yml @spotify/techdocs-core +/.changeset/cost-insights-* @spotify/silver-lining diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 0437698301..de7ce773bb 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -5,11 +5,9 @@ #### :heavy_check_mark: Checklist - + -- [ ] All tests are passing `yarn test` +- [ ] A changeset describing the change and affected packages. ([more info](https://github.com/spotify/backstage/blob/master/CONTRIBUTING.md#creating-changesets)) +- [ ] Added or updated documentation +- [ ] Tests for new functionality and regression tests for bug fixes - [ ] Screenshots attached (for UI changes) -- [ ] Relevant documentation updated -- [ ] Prettier run on changed files -- [ ] Tests added for new functionality -- [ ] Regression tests added for bug fixes diff --git a/.codecov.yml b/.github/codecov.yml similarity index 92% rename from .codecov.yml rename to .github/codecov.yml index 1b8e770b59..d39038615f 100644 --- a/.codecov.yml +++ b/.github/codecov.yml @@ -6,6 +6,7 @@ coverage: default: threshold: 0% # Ref: https://docs.codecov.io/docs/codecovyml-reference#coveragestatus target: auto + informational: true # Don't block PRs # Since Backstage is a mono repo, flags here help in getting the code coverage of individual packages. # Documentation: https://docs.codecov.io/docs/flags diff --git a/.github/styles/vocab.txt b/.github/styles/vocab.txt index c9774ae237..0cbd0ffa05 100644 --- a/.github/styles/vocab.txt +++ b/.github/styles/vocab.txt @@ -68,6 +68,7 @@ graphviz Hackathons haproxy heroku +Heroku horizontalpodautoscalers Hostname http @@ -105,6 +106,7 @@ Monorepo monorepos msw namespace +namespaces Namespaces neuro newrelic @@ -141,6 +143,7 @@ Raghunandan rankdir readme Readme +Recharts Redash replicasets repo @@ -195,6 +198,7 @@ validators Voi Wealthsimple Weaveworks +Webpack xyz yaml Zalando @@ -204,3 +208,5 @@ cloudbuild Grafana Iain Snyk +www +WWW diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 65e092676d..d00f304b58 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,7 +97,7 @@ jobs: if: ${{ steps.yarn-lock.outcome == 'failure' }} run: | yarn lerna -- run test -- --coverage - bash <(curl -s https://codecov.io/bash) + bash <(curl -s https://codecov.io/bash) -N $(git rev-parse FETCH_HEAD) - name: verify plugin template run: yarn lerna -- run diff -- --check diff --git a/.github/workflows/e2e-win.yml b/.github/workflows/e2e-win.yml index c48d779962..570d857c48 100644 --- a/.github/workflows/e2e-win.yml +++ b/.github/workflows/e2e-win.yml @@ -40,4 +40,4 @@ jobs: - name: yarn build run: yarn build --ignore example-app --ignore example-backend --ignore @techdocs/cli - name: run E2E test - run: yarn workspace e2e-test start + run: yarn e2e-test run diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index e280bf59a3..62be0a6cea 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -70,7 +70,7 @@ jobs: - name: run E2E test run: | sudo sysctl fs.inotify.max_user_watches=524288 - yarn workspace e2e-test start + yarn e2e-test run env: POSTGRES_HOST: localhost POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }} diff --git a/.gitignore b/.gitignore index e7d294d55a..5c27601791 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,11 @@ -.idea/ +# macOS .DS_Store + +# IntelliJ +.idea/ +*.iml + +# Visual Studio Code .vscode/ .vsls.json diff --git a/.prettierignore b/.prettierignore index 4b1acbb594..c4e675a5d7 100644 --- a/.prettierignore +++ b/.prettierignore @@ -6,3 +6,4 @@ coverage templates plugins/scaffolder-backend/sample-templates .vscode +dist-types diff --git a/.yarnrc b/.yarnrc index f465c5c5e6..6b56b971d7 100644 --- a/.yarnrc +++ b/.yarnrc @@ -3,6 +3,7 @@ registry "https://registry.npmjs.org/" +disable-self-update-check true lastUpdateCheck 1580389148099 yarn-path ".yarn/releases/yarn-1.22.1.js" network-timeout 600000 diff --git a/CHANGELOG.md b/CHANGELOG.md index 1860a4de6f..0ab3459628 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,26 @@ If you encounter issues while upgrading to a newer version, don't hesitate to re > Collect changes for the next release below +## v0.1.1-alpha.26 + +### @backstage/cli + +- Configuration files are no longer selected through `APP_ENV` or `NODE_ENV`. The default configuration files are `app-config.yaml` and, fix it exists, `app-config.local.yaml` in the repo root. To load a different set of files, use `--config ` arguments. + +### @backstage/backend-common + +- Configuration files are no longer selected through `APP_ENV` or `NODE_ENV`. The default configuration files are `app-config.yaml` and, fix it exists, `app-config.local.yaml` in the repo root. To load a different set of files, use `--config ` arguments. + +## v0.1.1-alpha.25 + +### @backstage/cli + +- The recommended way to set the configuration environment is now to use `APP_ENV` instead of `NODE_ENV`. + +### Backend (example-backend, or backends created with @backstage/create-app) + +- A plugin database manager has been created, and plugins can now accept that interface as an argument during initialisation. Notably, the `auth` plugin has a [`createRouter` signature change](./plugins/auth-backend/src/service/router.ts). See [packages/backend/src/index.ts](./packages/backend/src/index.ts) on how to set it up. [#2697](https://github.com/spotify/backstage/pull/2697) + ## v0.1.1-alpha.24 ### Backend (example-backend, or backends created with @backstage/create-app) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85834076d4..7edbc6d17b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,7 +87,7 @@ We use [changesets](https://github.com/atlassian/changesets) to help us prepare 1. Run `yarn changeset` 2. Select which packages you want to include a changeset for 3. Select impact of change that you're introducing (minor, major or patch) -4. Add generated changset to Git +4. Add generated changeset to Git 5. Push the commit with your changeset to the branch associated with your PR 6. Accept our gratitude for making the release process easier on the maintainer diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md deleted file mode 100644 index 1aebbeb0eb..0000000000 --- a/DEPLOYMENT.md +++ /dev/null @@ -1,27 +0,0 @@ -# Deploying Backstage - -## Heroku - -Deploying to heroku is relatively easy following these steps. - -First, make sure you have the [heroku CLI installed](https://devcenter.heroku.com/articles/heroku-cli) and log into it as well as login into Heroku's [container registry](https://devcenter.heroku.com/articles/container-registry-and-runtime). - -```bash -$ heroku login -$ heroku container:login -``` - -You _might_ also need to set your Heroku app's stack to `container` - -```bash -$ heroku stack:set container -a -``` - -We can now build/push the Docker image to Heroku's container registry and release it to the `web` worker. - -```bash -$ heroku container:push web -a -$ heroku container:release web -a -``` - -With that, you should have Backstage up and running! diff --git a/README.md b/README.md index e05c1eb16e..70badd5321 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,8 @@ # [Backstage](https://backstage.io) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -![](https://github.com/spotify/backstage/workflows/Frontend%20CI/badge.svg) +[![CNCF Status](https://img.shields.io/badge/cncf%20status-sandbox-blue.svg)](https://www.cncf.io/projects) +[![Main CI Build](https://github.com/spotify/backstage/workflows/Main%20Master%20Build/badge.svg)](https://github.com/spotify/backstage/actions?query=workflow%3A%22Main+Master+Build%22) [![Discord](https://img.shields.io/discord/687207715902193673)](https://discord.gg/EBHEGzX) ![Code style](https://img.shields.io/badge/code_style-prettier-ff69b4.svg) [![Codecov](https://img.shields.io/codecov/c/github/spotify/backstage)](https://codecov.io/gh/spotify/backstage) @@ -24,9 +25,7 @@ Out of the box, Backstage includes: - [Backstage TechDocs](https://backstage.io/docs/features/techdocs/techdocs-overview) for making it easy to create, maintain, find, and use technical documentation, using a "docs like code" approach - Plus, a growing ecosystem of [open source plugins](https://github.com/spotify/backstage/tree/master/plugins) that further expand Backstage’s customizability and functionality -For more information go to [backstage.io](https://backstage.io) or join our [Discord chatroom](https://discord.gg/EBHEGzX). - -🎉 Backstage is a CNCF Sandbox project. Read the announcement [here](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox). +Backstage was created by Spotify but is now hosted by the [Cloud Native Computing Foundation (CNCF)](https://www.cncf.io) as a Sandbox level project. Read the announcement [here](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox). ## Project roadmap @@ -58,6 +57,6 @@ Check out [the documentation](https://backstage.io/docs/getting-started) on how ## License -Copyright 2020 Spotify AB. +Copyright 2020 © Backstage Project Authors. All rights reserved. The Linux Foundation has registered trademarks and uses trademarks. For a list of trademarks of The Linux Foundation, please see our Trademark Usage page: https://www.linuxfoundation.org/trademark-usage Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 diff --git a/app-config.development.yaml b/app-config.development.yaml deleted file mode 100644 index 817847c6d6..0000000000 --- a/app-config.development.yaml +++ /dev/null @@ -1,13 +0,0 @@ -app: - baseUrl: http://localhost:3000 - -backend: - baseUrl: http://localhost:7000 - listen: - port: 7000 - cors: - origin: http://localhost:3000 - methods: [GET, POST, PUT, DELETE] - credentials: true - csp: - connect-src: ["'self'", 'http:', 'https:'] diff --git a/app-config.yaml b/app-config.yaml index d670771a31..4746e822da 100644 --- a/app-config.yaml +++ b/app-config.yaml @@ -1,6 +1,7 @@ app: title: Backstage Example App - baseUrl: http://localhost:7000 + baseUrl: http://localhost:3000 + googleAnalyticsTrackingId: # UA-000000-0 backend: baseUrl: http://localhost:7000 @@ -9,8 +10,13 @@ backend: database: client: sqlite3 connection: ':memory:' + cors: + origin: http://localhost:3000 + methods: [GET, POST, PUT, DELETE] + credentials: true csp: - connect-src: ["'self'", 'https:'] + connect-src: ["'self'", 'http:', 'https:'] + # workingDirectory: /tmp # Use this to configure a working direcotry for the scaffolder, defaults to the OS temp-dir # See README.md in the proxy-backend plugin for information on the configuration format proxy: @@ -34,8 +40,14 @@ proxy: $env: TRAVISCI_AUTH_TOKEN travis-api-version: 3 + '/newrelic/apm/api': + target: https://api.newrelic.com/v2 + headers: + X-Api-Key: + $env: NEW_RELIC_REST_API_KEY + organization: - name: Spotify + name: My Company techdocs: storageUrl: http://localhost:7000/api/techdocs/static/docs @@ -44,44 +56,41 @@ techdocs: techdocs: 'docker' sentry: - organization: spotify + organization: my-company rollbar: - organization: spotify + organization: my-company accountToken: $env: ROLLBAR_ACCOUNT_TOKEN -newrelic: - api: - baseUrl: 'https://api.newrelic.com/v2' - key: NEW_RELIC_REST_API_KEY - lighthouse: baseUrl: http://localhost:3003 kubernetes: - clusterLocatorMethod: 'configMultiTenant' + serviceLocatorMethod: 'multiTenant' + clusterLocatorMethods: + - 'config' clusters: [] integrations: github: - host: github.com token: - $env: GITHUB_PRIVATE_TOKEN + $env: GITHUB_TOKEN ### Example for how to add your GitHub Enterprise instance using the API: # - host: ghe.example.net # apiBaseUrl: https://ghe.example.net/api/v3 # token: - # $env: GHE_PRIVATE_TOKEN + # $env: GHE_TOKEN ### Example for how to add your GitHub Enterprise instance using raw HTTP fetches (token is optional): # - host: ghe.example.net # rawBaseUrl: https://ghe.example.net/raw # token: - # $env: GHE_PRIVATE_TOKEN + # $env: GHE_TOKEN gitlab: - host: gitlab.com token: - $env: GITLAB_PRIVATE_TOKEN + $env: GITLAB_TOKEN bitbucket: - host: bitbucket.org username: @@ -91,7 +100,7 @@ integrations: azure: - host: dev.azure.com token: - $env: AZURE_PRIVATE_TOKEN + $env: AZURE_TOKEN catalog: rules: @@ -102,12 +111,12 @@ catalog: providers: - target: https://github.com token: - $env: GITHUB_PRIVATE_TOKEN + $env: GITHUB_TOKEN #### Example for how to add your GitHub Enterprise instance using the API: # - target: https://ghe.example.net # apiBaseUrl: https://ghe.example.net/api/v3 # token: - # $env: GHE_PRIVATE_TOKEN + # $env: GHE_TOKEN ldapOrg: ### Example for how to add your enterprise LDAP server # providers: @@ -142,22 +151,25 @@ catalog: # Backstage example templates - type: url target: https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/sample-templates/all-templates.yaml + # Backstage example groups and users + - type: url + target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme-corp.yaml scaffolder: github: token: - $env: GITHUB_ACCESS_TOKEN + $env: GITHUB_TOKEN visibility: public # or 'internal' or 'private' gitlab: api: baseUrl: https://gitlab.com token: - $env: GITLAB_ACCESS_TOKEN + $env: GITLAB_TOKEN azure: baseUrl: https://dev.azure.com/{your-organization} api: token: - $env: AZURE_PRIVATE_TOKEN + $env: AZURE_TOKEN auth: providers: @@ -236,10 +248,11 @@ costInsights: name: Big Query icon: search metrics: - dailyCost: - name: Your Company's Daily Cost DAU: - name: Cost Per DAU + name: Daily Active Users + default: true + MSC: + name: Monthly Subscribers homepage: clocks: - label: UTC diff --git a/catalog-info.yaml b/catalog-info.yaml index 937a55bfca..405c3f31b4 100644 --- a/catalog-info.yaml +++ b/catalog-info.yaml @@ -7,6 +7,7 @@ metadata: annotations: github.com/project-slug: spotify/backstage backstage.io/techdocs-ref: github:https://github.com/spotify/backstage.git + lighthouse.com/website-url: https://backstage.io spec: type: library owner: Spotify diff --git a/contrib/chart/backstage/Chart.lock b/contrib/chart/backstage/Chart.lock new file mode 100644 index 0000000000..e390bf21ba --- /dev/null +++ b/contrib/chart/backstage/Chart.lock @@ -0,0 +1,6 @@ +dependencies: +- name: postgresql + repository: https://charts.bitnami.com/bitnami + version: 9.4.1 +digest: sha256:f949ec0fe7d146610ce2ee78fbfb4e52d235883a797968b0a1e61aa88ada2786 +generated: "2020-09-25T08:59:54.255582519+02:00" diff --git a/contrib/chart/backstage/Chart.yaml b/contrib/chart/backstage/Chart.yaml new file mode 100644 index 0000000000..24c6f2a4d7 --- /dev/null +++ b/contrib/chart/backstage/Chart.yaml @@ -0,0 +1,30 @@ +apiVersion: v2 +name: backstage +description: A Helm chart for Spotify Backstage +type: application + +# This is the chart version. This version number should be incremented each time you make changes +# to the chart and its templates, including the app version. +version: 0.1.1 + +# This is the version number of the application being deployed. This version number should be +# incremented each time you make changes to the application. +appVersion: v0.1.1-alpha.23 + +sources: + - https://github.com/spotify/backstage + - https://github.com/spotify/lighthouse-audit-service + +dependencies: + - name: postgresql + condition: postgresql.enabled + version: 9.4.1 + repository: https://charts.bitnami.com/bitnami + +maintainers: + - name: Martina Iglesias Fernández + email: martina@roadie.io + url: https://roadie.io + - name: David Tuite + email: david@roadie.io + url: https://roadie.io diff --git a/contrib/chart/backstage/README.md b/contrib/chart/backstage/README.md new file mode 100644 index 0000000000..9d1c93765b --- /dev/null +++ b/contrib/chart/backstage/README.md @@ -0,0 +1,235 @@ +# Backstage demo helm charts + +This folder contains Helm charts that can easily create a Kubernetes deployment of a demo Backstage app. + +### Pre-requisites + +These charts depend on the `nginx-ingress` controller being present in the cluster. If it's not already installed you +can run: + +``` +helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx +helm install nginx-ingress ingress-nginx/ingress-nginx +``` + +### Installing the charts + +After choosing a DNS name where backstage will be hosted create a yaml file for your custom configuration. + +``` +appConfig: + app: + baseUrl: https://backstage.mydomain.com + title: Backstage + backend: + baseUrl: https://backstage.mydomain.com + cors: + origin: https://backstage.mydomain.com + lighthouse: + baseUrl: https://backstage.mydomain.com/lighthouse-api + techdocs: + storageUrl: https://backstage.mydomain.com/api/techdocs/static/docs + requestUrl: https://backstage.mydomain.com/api/techdocs + +``` + +Then use it to run: + +``` +git clone https://github.com/spotify/backstage.git +cd contrib/chart/backstage +helm dependency update +helm install -f backstage-mydomain.yaml backstage . +``` + +This command will deploy the following pieces: + +- Backstage frontend +- Backstage backend with scaffolder and auth plugins +- (optional) a PostgreSQL instance +- lighthouse plugin +- ingress + +After a few minutes Backstage should be up and running in your cluster under the DNS specified earlier. + +Make sure to create the appropriate DNS entry in your infrastructure. To find the public IP address run: + +```bash +$ kubectl get ingress +NAME HOSTS ADDRESS PORTS AGE +backstage-ingress * 123.1.2.3 80 17m +``` + +> **NOTE**: this is not a production ready deployment. + +## Customization + +### Issue certificates + +These charts can install or reuse a `clusterIssuer` to generate certificates for the backstage `ingress`. To do that: + +1. [Install][install-cert-manager] or make sure [cert-manager][cert-manager] is installed in the cluster. +2. Enable the issuer in the charts. This will first check if there is a `letsencrypt` issuer already deployed in your + cluster and deploy one if it doesn't exist. + +To enable it you need to provide a valid email address in the chart's values: + +``` +issuer: + email: me@example.com + clusterIssuer: "letsencrypt-prod" +``` + +By default, the charts use `letsencrypt-staging` so in the above example we instruct helm to use the production issuer +instead. + +[cert-manager]: https://cert-manager.io/docs/ +[install-cert-manager]: https://cert-manager.io/docs/installation/kubernetes/#installing-with-helm + +### Custom PostgreSQL instance + +Configuring a connection to an existing PostgreSQL instance is possible through the chart's values. + +First create a yaml file with the configuration you want to override, for example `backstage-prod.yaml`: + +```bash +postgresql: + enabled: false + +appConfig: + app: + baseUrl: https://backstage-demo.mydomain.com + title: Backstage + backend: + baseUrl: https://backstage-demo.mydomain.com + cors: + origin: https://backstage-demo.mydomain.com + database: + client: pg + connection: + database: backstage_plugin_catalog + host: + user: + password: + lighthouse: + baseUrl: https://backstage-demo.mydomain.com/lighthouse-api + +lighthouse: + database: + client: pg + connection: + host: + user: + password: + database: lighthouse_audit_service + +``` + +For the CA, create a `configMap` named `-postgres-ca` with a file called `ca.crt`: + +``` +kubectl create configmap my-backstage --from-file=ca.crt" +``` + +Now install the helm chart: + +``` +cd contrib/chart/backstage +helm install -f backstage-prod.yaml my-backstage . +``` + +### Use your own docker images + +The docker images used for the deployment can be configured through the charts values: + +``` +frontend: + image: + repository: + tag: + +backend: + image: + repository: + tag: + +lighthouse: + image: + repository: +``` + +### Different namespace + +To install the charts a specific namespace use `--namespace `: + +``` +helm install -f my_values.yaml --namespace demos backstage . +``` + +### Disable loading of demo data + +To deploy backstage with the pre-loaded demo data disable `backend.demoData`: + +``` +helm install -f my_values.yaml --set backend.demoData=false backstage . +``` + +### Other options + +For more customization options take a look at the [values.yaml](/contrib/chart/backstage/values.yaml) file. + +## Troubleshooting + +Some resources created by these charts are meant to survive after upgrades and even after uninstalls. When +troubleshooting these charts it can be useful to delete these resources between re-installs. + +Secrets: + +``` +-postgresql-certs -- contains the certificates used by the deployed PostgreSQL +``` + +Persistent volumes: + +``` +data--postgresql-0 -- this is the data volume used by PostgreSQL to store data and configuration +``` + +> **NOTE**: this volume also stores the configuration for PostgreSQL which includes things like the password for the +> `postgres` user. This means that uninstalling and re-installing the charts with `postgres.enabled` set to `true` and +> auto generated passwords will fail. The solution is to delete this volume with +> `kubectl delete pvc data--postgresql-0` + +ConfigMaps: + +``` +-postgres-ca -- contains the generated CA certificate for PostgreSQL when `postgres` is enabled +``` + +#### Unable to verify signature + +``` +Backend failed to start up Error: unable to verify the first certificate + at TLSSocket.onConnectSecure (_tls_wrap.js:1501:34) + at TLSSocket.emit (events.js:315:20) + at TLSSocket._finishInit (_tls_wrap.js:936:8) + at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:710:12) { + code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' +``` + +This error happens in the backend when it tries to connect to the configured PostgreSQL database and the specified CA is not correct. The solution is to make sure that the contents of the `configMap` that holds the certificate match the CA for the PostgreSQL instance. A workaround is to set `appConfig.backend.database.connection.ssl.rejectUnauthorized` to `false` in the chart's values. + + + +## Uninstalling Backstage + +To uninstall Backstage simply run: + +``` +RELEASE_NAME= # use `helm list` to find out the name +helm uninstall ${RELEASE_NAME} +kubectl delete pvc data-${RELEASE_NAME}-postgresql-0 +kubectl delete secret ${RELEASE_NAME}-postgresql-certs +kubectl delete configMap ${RELEASE_NAME}-postgres-ca +``` diff --git a/contrib/chart/backstage/files/app-config.development.yaml.tpl b/contrib/chart/backstage/files/app-config.development.yaml.tpl new file mode 100644 index 0000000000..76d6499145 --- /dev/null +++ b/contrib/chart/backstage/files/app-config.development.yaml.tpl @@ -0,0 +1,51 @@ +backend: + lighthouseHostname: {{ include "lighthouse.serviceName" . | quote }} + listen: + port: {{ .Values.appConfig.backend.listen.port | default 7000 }} + database: + client: {{ .Values.appConfig.backend.database.client | quote }} + connection: + host: {{ include "backend.postgresql.host" . | quote }} + port: {{ include "backend.postgresql.port" . | quote }} + user: {{ include "backend.postgresql.user" . | quote }} + database: {{ .Values.appConfig.backend.database.connection.database | quote }} + ssl: + rejectUnauthorized: {{ .Values.appConfig.backend.database.connection.ssl.rejectUnauthorized | quote }} + ca: {{ include "backstage.backend.postgresCaFilename" . | quote }} + +catalog: +{{- if .Values.backend.demoData }} + locations: + # Backstage example components + - type: github + target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/all-components.yaml + # Example component for github-actions + - type: github + target: https://github.com/spotify/backstage/blob/master/plugins/github-actions/examples/sample.yaml + # Example component for techdocs + - type: github + target: https://github.com/spotify/backstage/blob/master/plugins/techdocs-backend/examples/documented-component/documented-component.yaml + # Backstage example APIs + - type: github + target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/all-apis.yaml + # Backstage example templates + - type: github + target: https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/sample-templates/all-templates.yaml +{{- else }} + locations: [] +{{- end }} + +auth: + providers: + microsoft: null + +scaffolder: + azure: null + + +sentry: + organization: {{ .Values.appConfig.sentry.organization | quote }} + +techdocs: + generators: + techdocs: 'local' diff --git a/contrib/chart/backstage/files/create-backend-dbs.sql b/contrib/chart/backstage/files/create-backend-dbs.sql new file mode 100644 index 0000000000..043ff7daf5 --- /dev/null +++ b/contrib/chart/backstage/files/create-backend-dbs.sql @@ -0,0 +1,13 @@ +{{ $backendDb := .Values.appConfig.backend.database.connection.database }} +{{ $lighthouseDb := .Values.lighthouse.database.connection.database }} +{{ $user := .Values.global.postgresql.postgresqlUsername }} + +grant all privileges on database {{ $backendDb }} to {{ $user }}; + +create database backstage_plugin_auth; +grant all privileges on database backstage_plugin_auth to {{ $user }}; + +{{ if not (eq $backendDb $lighthouseDb) }} +create database {{ $lighthouseDb }}; +grant all privileges on database {{ $lighthouseDb }} to {{ $user }}; +{{ end }} diff --git a/contrib/chart/backstage/templates/_helpers.tpl b/contrib/chart/backstage/templates/_helpers.tpl new file mode 100644 index 0000000000..5d49ba6975 --- /dev/null +++ b/contrib/chart/backstage/templates/_helpers.tpl @@ -0,0 +1,286 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "backstage.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "backstage.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .Chart.Name .Values.nameOverride -}} +{{- if contains $name .Release.Name -}} +{{- .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "backstage.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Common App labels +*/}} +{{- define "backstage.app.labels" -}} +app.kubernetes.io/name: {{ include "backstage.name" . }}-app +helm.sh/chart: {{ include "backstage.chart" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end -}} + +{{/* +Common Backend labels +*/}} +{{- define "backstage.backend.labels" -}} +app.kubernetes.io/name: {{ include "backstage.name" . }}-backend +helm.sh/chart: {{ include "backstage.chart" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end -}} + +{{/* +Name for postgresql dependency +See https://github.com/helm/helm/issues/3920#issuecomment-686913512 +*/}} +{{- define "backstage.postgresql.fullname" -}} +{{ printf "%s-%s" .Release.Name .Values.postgresql.nameOverride }} +{{- end -}} + + +{{/* +Create the name of the service account to use for the app +*/}} +{{- define "backstage.app.serviceAccountName" -}} +{{- if .Values.app.serviceAccount.create -}} + {{ default "default" .Values.app.serviceAccount.name }} +{{- else -}} + {{ default "default" .Values.app.serviceAccount.name }} +{{- end -}} +{{- end -}} + +{{/* +Create the name of the service account to use for the backend +*/}} +{{- define "backstage.backend.serviceAccountName" -}} +{{- if .Values.backend.serviceAccount.create -}} + {{ default default .Values.backend.serviceAccount.name }} +{{- else -}} + {{ default "default" .Values.backend.serviceAccount.name }} +{{- end -}} +{{- end -}} + +{{/* +Path to the CA certificate file in the backend +*/}} +{{- define "backstage.backend.postgresCaFilename" -}} +{{ include "backstage.backend.postgresCaDir" . }}/{{- required "The name for the CA certificate file for postgresql is required" .Values.global.postgresql.caFilename }} +{{- end -}} +{{/* + +{{/* +Directory path to the CA certificate file in the backend +*/}} +{{- define "backstage.backend.postgresCaDir" -}} +{{- if .Values.appConfig.backend.database.connection.ssl.ca -}} + {{ .Values.appConfig.backend.database.connection.ssl.ca }} +{{- else -}} +/etc/postgresql +{{- end -}} +{{- end -}} +{{/* + +Path to the CA certificate file in lighthouse +*/}} +{{- define "backstage.lighthouse.postgresCaFilename" -}} +{{ include "backstage.lighthouse.postgresCaDir" . }}/{{- required "The name for the CA certificate file for postgresql is required" .Values.global.postgresql.caFilename }} +{{- end -}} + +{{/* +Directory path to the CA certificate file in lighthouse +*/}} +{{- define "backstage.lighthouse.postgresCaDir" -}} +{{- if .Values.lighthouse.database.pathToDatabaseCa -}} + {{ .Values.lighthouse.database.pathToDatabaseCa }} +{{- else -}} +/etc/postgresql +{{- end -}} +{{- end -}} +{{/* + +{{/* +Generate ca for postgresql +*/}} +{{- define "backstage.postgresql.generateCA" -}} +{{- $ca := .ca | default (genCA (include "backstage.postgresql.fullname" .) 365) -}} +{{- $_ := set . "ca" $ca -}} +{{- $ca.Cert -}} +{{- end -}} + +{{/* +Generate certificates for postgresql +*/}} +{{- define "generateCerts" -}} +{{- $postgresName := (include "backstage.postgresql.fullname" .) }} +{{- $altNames := list $postgresName ( printf "%s.%s" $postgresName .Release.Namespace ) ( printf "%s.%s.svc" ( $postgresName ) .Release.Namespace ) -}} +{{- $ca := .ca | default (genCA (include "backstage.postgresql.fullname" .) 365) -}} +{{- $_ := set . "ca" $ca -}} +{{- $cert := genSignedCert ( $postgresName ) nil $altNames 365 $ca -}} +tls.crt: {{ $cert.Cert | b64enc }} +tls.key: {{ $cert.Key | b64enc }} +{{- end -}} + +{{/* +Generate a password for the postgres user used for the connections from the backend and lighthouse +*/}} +{{- define "postgresql.generateUserPassword" -}} +{{- $pgPassword := .pgPassword | default ( randAlphaNum 12 ) -}} +{{- $_ := set . "pgPassword" $pgPassword -}} +{{ $pgPassword}} +{{- end -}} + +{{/* +Name of the backend service +*/}} +{{- define "backend.serviceName" -}} +{{ include "backstage.fullname" . }}-backend +{{- end -}} + +{{/* +Name of the frontend service +*/}} +{{- define "frontend.serviceName" -}} +{{ include "backstage.fullname" . }}-frontend +{{- end -}} + +{{/* +Name of the lighthouse backend service +*/}} +{{- define "lighthouse.serviceName" -}} +{{ include "backstage.fullname" . }}-lighthouse +{{- end -}} + +{{/* +Name of the postgresql service +*/}} +{{- define "postgresql.serviceName" -}} +{{- include "backstage.postgresql.fullname" . }} +{{- end -}} + +{{/* +Postgres host for lighthouse +*/}} +{{- define "lighthouse.postgresql.host" -}} +{{- if .Values.postgresql.enabled }} +{{- include "postgresql.serviceName" . }} +{{- else -}} +{{- required "A valid .Values.lighthouse.database.connection.host is required when postgresql is not enabled" .Values.lighthouse.database.connection.host -}} +{{- end -}} +{{- end -}} + +{{/* +Postgres host for the backend +*/}} +{{- define "backend.postgresql.host" -}} +{{- if .Values.postgresql.enabled }} +{{- include "postgresql.serviceName" . }} +{{- else -}} +{{- required "A valid .Values.appConfig.backend.database.connection.host is required when postgresql is not enabled" .Values.appConfig.backend.database.connection.host -}} +{{- end -}} +{{- end -}} + +{{/* +Postgres port for the backend +*/}} +{{- define "backend.postgresql.port" -}} +{{- if .Values.postgresql.enabled }} +{{- .Values.postgresql.service.port }} +{{- else if .Values.appConfig.backend.database.connection.port -}} +{{- .Values.appConfig.backend.database.connection.port }} +{{ else }} +5432 +{{- end -}} +{{- end -}} + +{{/* +Postgres port for lighthouse +*/}} +{{- define "lighthouse.postgresql.port" -}} +{{- if .Values.postgresql.enabled }} +{{- .Values.postgresql.service.port }} +{{- else if .Values.lighthouse.database.connection.port -}} +{{- .Values.lighthouse.database.connection.port }} +{{- else -}} +5432 +{{- end -}} +{{- end -}} + +{{/* +Postgres user for backend +*/}} +{{- define "backend.postgresql.user" -}} +{{- if .Values.postgresql.enabled }} +{{- .Values.global.postgresql.postgresqlUsername }} +{{- else -}} +{{- required "A valid .Values.appConfig.backend.database.connection.user is required when postgresql is not enabled" .Values.appConfig.backend.database.connection.user -}} +{{- end -}} +{{- end -}} + +{{/* +Postgres user for lighthouse +*/}} +{{- define "lighthouse.postgresql.user" -}} +{{- if .Values.postgresql.enabled }} +{{- .Values.global.postgresql.postgresqlUsername }} +{{- else -}} +{{- required "A valid .Values.lighthouse.database.connection.user is required when postgresql is not enabled" .Values.lighthouse.database.connection.user -}} +{{- end -}} +{{- end -}} + +{{/* +Postgres password secret for backend +*/}} +{{- define "backend.postgresql.passwordSecret" -}} +{{- if .Values.postgresql.enabled }} +{{- template "backstage.postgresql.fullname" . }} +{{- else -}} +{{ $secretName := (printf "%s-backend-postgres" (include "backstage.fullname" . )) }} +{{- required "A valid .Values.appConfig.backend.database.connection.password is required when postgresql is not enabled" $secretName -}} +{{- end -}} +{{- end -}} + +{{/* +Postgres password for lighthouse +*/}} +{{- define "lighthouse.postgresql.passwordSecret" -}} +{{- if .Values.postgresql.enabled }} +{{- template "backstage.postgresql.fullname" . }} +{{- else -}} +{{ $secretName := (printf "%s-lighthouse-postgres" (include "backstage.fullname" . )) }} +{{- required "A valid .Values.lighthouse.database.connection.password is required when postgresql is not enabled" $secretName -}} +{{- end -}} +{{- end -}} + +{{/* +app-config file name +*/}} +{{- define "backstage.appConfigFilename" -}} +{{- "app-config.development.yaml" -}} +{{- end -}} diff --git a/contrib/chart/backstage/templates/backend-deployment.yaml b/contrib/chart/backstage/templates/backend-deployment.yaml new file mode 100644 index 0000000000..c57764db8e --- /dev/null +++ b/contrib/chart/backstage/templates/backend-deployment.yaml @@ -0,0 +1,79 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "backstage.fullname" . }}-backend + +spec: + replicas: {{ .Values.backend.replicaCount }} + + selector: + matchLabels: + app: backstage + component: backend + + template: + metadata: + annotations: + ad.datadoghq.com/backstage.logs: '[{"source":"backstage","service":"backend"}]' + labels: + app: backstage + component: backend + + spec: + containers: + - name: {{ .Chart.Name }}-backend + image: {{ .Values.backend.image.repository }}:{{ .Values.backend.image.tag }} + imagePullPolicy: {{ .Values.backend.image.pullPolicy }} + ports: + - containerPort: {{ .Values.backend.containerPort }} + resources: + {{- toYaml .Values.backend.resources | nindent 12 }} + + envFrom: + - secretRef: + name: {{ include "backstage.fullname" . }}-backend + - configMapRef: + name: {{ include "backstage.fullname" . }}-app-env + - configMapRef: + name: {{ include "backstage.fullname" . }}-auth + env: + - name: NODE_ENV + value: {{ .Values.backend.nodeEnv | default "development" }} + - name: APP_CONFIG_backend_database_connection_password + valueFrom: + secretKeyRef: + name: {{ include "backend.postgresql.passwordSecret" .}} + key: postgresql-password + volumeMounts: + - name: postgres-ca + mountPath: {{ include "backstage.backend.postgresCaDir" . }} + - name: app-config + mountPath: {{ printf "/usr/src/app/%s" (include "backstage.appConfigFilename" .) }} + subPath: {{ include "backstage.appConfigFilename" . }} + + volumes: + - name: postgres-ca + configMap: + name: {{ include "backstage.fullname" . }}-postgres-ca + - name: app-config + configMap: + name: {{ include "backstage.fullname" . }}-app-config + +{{- if .Values.backend.enabled }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "backend.serviceName" . }} + +spec: + ports: + - port: 80 + targetPort: {{ .Values.backend.containerPort }} + + selector: + app: backstage + component: backend + + type: ClusterIP +{{- end }} diff --git a/contrib/chart/backstage/templates/backend-secret.yaml b/contrib/chart/backstage/templates/backend-secret.yaml new file mode 100644 index 0000000000..b340f39d7c --- /dev/null +++ b/contrib/chart/backstage/templates/backend-secret.yaml @@ -0,0 +1,23 @@ +{{- if .Values.backend.enabled }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "backstage.fullname" . }}-backend +type: Opaque +stringData: + AUTH_GOOGLE_CLIENT_SECRET: {{ .Values.auth.google.clientSecret }} + AUTH_GITHUB_CLIENT_SECRET: {{ .Values.auth.github.clientSecret }} + AUTH_GITLAB_CLIENT_SECRET: {{ .Values.auth.gitlab.clientSecret }} + AUTH_OKTA_CLIENT_SECRET: {{ .Values.auth.okta.clientSecret }} + AUTH_OAUTH2_CLIENT_SECRET: {{ .Values.auth.oauth2.clientSecret }} + AUTH_AUTH0_CLIENT_SECRET: {{ .Values.auth.auth0.clientSecret }} + AUTH_MICROSOFT_CLIENT_SECRET: {{ .Values.auth.microsoft.clientSecret }} + SENTRY_TOKEN: {{ .Values.auth.sentryToken }} + ROLLBAR_ACCOUNT_TOKEN: {{ .Values.auth.rollbarAccountToken }} + CIRCLECI_AUTH_TOKEN: {{ .Values.auth.circleciAuthToken }} + GITHUB_TOKEN: {{ .Values.auth.githubToken }} + GITLAB_TOKEN: {{ .Values.auth.gitlabToken }} + AZURE_TOKEN: {{ .Values.auth.azure.api.token }} + NEW_RELIC_REST_API_KEY: {{ .Values.auth.newRelicRestApiKey }} + TRAVISCI_AUTH_TOKEN: {{ .Values.auth.travisciAuthToken }} +{{- end }} diff --git a/contrib/chart/backstage/templates/backstage-app-config.yaml b/contrib/chart/backstage/templates/backstage-app-config.yaml new file mode 100644 index 0000000000..f06e47feab --- /dev/null +++ b/contrib/chart/backstage/templates/backstage-app-config.yaml @@ -0,0 +1,28 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "backstage.fullname" . }}-app-config +data: +{{ include "backstage.appConfigFilename" . | indent 2 }}: | +{{ tpl (.Files.Get "files/app-config.development.yaml.tpl") . | indent 4 }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "backstage.fullname" . }}-app-env +data: + APP_CONFIG_app_baseUrl: {{ .Values.appConfig.app.baseUrl | quote | quote }} + APP_CONFIG_app_title: {{ .Values.appConfig.app.title | quote | quote }} + APP_CONFIG_app_googleAnalyticsTrackingId: {{ .Values.appConfig.app.googleAnalyticsTrackingId | quote | quote }} + APP_CONFIG_backend_baseUrl: {{ .Values.appConfig.backend.baseUrl | quote | quote }} + APP_CONFIG_backend_cors_origin: {{ .Values.appConfig.backend.cors.origin | quote | quote }} + APP_CONFIG_techdocs_storageUrl: {{ .Values.appConfig.techdocs.storageUrl | quote | quote }} + APP_CONFIG_techdocs_requestUrl: {{ .Values.appConfig.techdocs.requestUrl | quote | quote }} + APP_CONFIG_lighthouse_baseUrl: {{ .Values.appConfig.lighthouse.baseUrl | quote | quote }} + APP_CONFIG_backend_database_connection_ssl_rejectUnauthorized: "false" + APP_CONFIG_auth_providers_github_development_appOrigin: {{ .Values.appConfig.auth.providers.github.development.appOrigin | quote | quote }} + APP_CONFIG_auth_providers_google_development_appOrigin: {{ .Values.appConfig.auth.providers.google.development.appOrigin | quote | quote }} + APP_CONFIG_auth_providers_gitlab_development_appOrigin: {{ .Values.appConfig.auth.providers.gitlab.development.appOrigin | quote | quote }} + APP_CONFIG_auth_providers_okta_development_appOrigin: {{ .Values.appConfig.auth.providers.okta.development.appOrigin | quote | quote }} + APP_CONFIG_auth_providers_oauth2_development_appOrigin: {{ .Values.appConfig.auth.providers.oauth2.development.appOrigin | quote | quote }} + diff --git a/contrib/chart/backstage/templates/backstage-auth-config.yaml b/contrib/chart/backstage/templates/backstage-auth-config.yaml new file mode 100644 index 0000000000..7dcf8379aa --- /dev/null +++ b/contrib/chart/backstage/templates/backstage-auth-config.yaml @@ -0,0 +1,21 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "backstage.fullname" . }}-auth +data: + AUTH_GOOGLE_CLIENT_ID: {{ .Values.auth.google.clientId }} + AUTH_GITHUB_CLIENT_ID: {{ .Values.auth.github.clientId }} + AUTH_GITLAB_CLIENT_ID: {{ .Values.auth.gitlab.clientId }} + # This should not be prefixed with AUTH_. This could be a typo in the Backstage app config. + # Regardless, it is not decided by me. + GITLAB_BASE_URL: {{ .Values.auth.gitlab.baseUrl }} + AUTH_OKTA_CLIENT_ID: {{ .Values.auth.okta.clientId }} + AUTH_OKTA_AUDIENCE: {{ .Values.auth.okta.audience }} + AUTH_OAUTH2_CLIENT_ID: {{ .Values.auth.oauth2.clientId }} + AUTH_OAUTH2_AUTH_URL: {{ .Values.auth.oauth2.authUrl }} + AUTH_OAUTH2_TOKEN_URL: {{ .Values.auth.oauth2.tokenUrl }} + AUTH_AUTH0_CLIENT_ID: {{ .Values.auth.auth0.clientId }} + AUTH_AUTH0_DOMAIN: {{ .Values.auth.auth0.domain }} + AUTH_MICROSOFT_CLIENT_ID: {{ .Values.auth.microsoft.clientId }} + AUTH_MICROSOFT_TENANT_ID: {{ .Values.auth.microsoft.tenantId }} + diff --git a/contrib/chart/backstage/templates/frontend-deployment.yaml b/contrib/chart/backstage/templates/frontend-deployment.yaml new file mode 100644 index 0000000000..a5d84be2b2 --- /dev/null +++ b/contrib/chart/backstage/templates/frontend-deployment.yaml @@ -0,0 +1,59 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "backstage.fullname" . }}-frontend + +spec: + replicas: {{ .Values.frontend.replicaCount }} + + selector: + matchLabels: + app: backstage + component: frontend + + template: + metadata: + annotations: + ad.datadoghq.com/backstage.logs: '[{"source":"backstage","service":"frontend"}]' + labels: + app: backstage + component: frontend + + spec: + containers: + - name: {{ .Chart.Name }}-frontend + image: {{ .Values.frontend.image.repository }}:{{ .Values.frontend.image.tag }} + imagePullPolicy: {{ .Values.frontend.image.pullPolicy }} + ports: + - containerPort: {{ .Values.frontend.containerPort }} + resources: + {{- toYaml .Values.backend.resources | nindent 12 }} + envFrom: + - configMapRef: + name: {{ include "backstage.fullname" . }}-app-env + volumeMounts: + - name: app-config + mountPath: {{ printf "/usr/share/nginx/html/static/%s" (include "backstage.appConfigFilename" .) }} + subPath: {{ include "backstage.appConfigFilename" . }} + volumes: + - name: app-config + configMap: + name: {{ include "backstage.fullname" . }}-app-config +{{- if .Values.frontend.enabled }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "frontend.serviceName" . }} + +spec: + ports: + - port: 80 + targetPort: {{ .Values.frontend.containerPort }} + + selector: + app: backstage + component: frontend + + type: ClusterIP +{{- end }} diff --git a/contrib/chart/backstage/templates/ingress.yaml b/contrib/chart/backstage/templates/ingress.yaml new file mode 100644 index 0000000000..7231afda13 --- /dev/null +++ b/contrib/chart/backstage/templates/ingress.yaml @@ -0,0 +1,92 @@ +{{- $frontendUrl := urlParse .Values.appConfig.app.baseUrl}} +{{- $backendUrl := urlParse .Values.appConfig.backend.baseUrl}} +{{- $lighthouseUrl := urlParse .Values.appConfig.lighthouse.baseUrl}} +apiVersion: networking.k8s.io/v1beta1 +kind: Ingress +metadata: + name: {{ include "backstage.fullname" . }}-ingress + annotations: + {{- if .Values.issuer.email }} + cert-manager.io/cluster-issuer: {{ .Values.issuer.clusterIssuer }} + {{- end }} + kubernetes.io/ingress.class: nginx + nginx.ingress.kubernetes.io/ssl-redirect: "false" + nginx.ingress.kubernetes.io/configuration-snippet: | + if ($scheme = https) { + add_header Strict-Transport-Security "max-age=0;"; + } + {{- toYaml .Values.ingress.annotations | nindent 4 }} +spec: + tls: + - secretName: {{ include "backstage.fullname" . }}-tls + hosts: + - {{ $frontendUrl.host }} + - {{ $backendUrl.host }} + - {{ $lighthouseUrl.host }} + + rules: + - host: {{ $frontendUrl.host }} + http: + paths: + - path: / + backend: + serviceName: {{ include "frontend.serviceName" . }} + servicePort: 80 + {{/* Route the backend inside the same hostname as the frontend when they are the same */}} + {{- if eq $frontendUrl.host $backendUrl.host}} + - path: /api + backend: + serviceName: {{ include "backend.serviceName" . }} + servicePort: 80 + {{/* Route the backend through a different host */}} + {{- else -}} + - host: {{ $backendUrl.host }} + http: + paths: + - path: {{ $backendUrl.path | default "/" }} + backend: + serviceName: {{ include "backend.serviceName" . }} + servicePort: 80 + {{- end }} + +{{/* Route lighthouse through a different host */}} +{{- if not ( eq $frontendUrl.host $lighthouseUrl.host ) }} + - host: {{ $lighthouseUrl.host }} + http: + paths: + - path: {{ $lighthouseUrl.path | default "/" }} + backend: + serviceName: {{ include "lighthouse.serviceName" . }} + servicePort: 80 +{{- else }} +{{/* Route lighthouse by path with re-write rules when it is hosted under the same hostname */}} +--- +apiVersion: networking.k8s.io/v1beta1 +kind: Ingress +metadata: + name: {{ include "backstage.fullname" . }}-ingress-lighthouse + annotations: + {{- if .Values.issuer.email }} + cert-manager.io/cluster-issuer: {{ .Values.issuer.clusterIssuer }} + {{- end }} + nginx.ingress.kubernetes.io/rewrite-target: /$2 + nginx.ingress.kubernetes.io/ssl-redirect: "false" + nginx.ingress.kubernetes.io/configuration-snippet: | + if ($scheme = https) { + add_header Strict-Transport-Security "max-age=0;"; + } + {{- toYaml .Values.ingress.annotations | nindent 4 }} +spec: + tls: + - secretName: {{ include "backstage.fullname" . }}-tls + hosts: + - {{ $lighthouseUrl.host }} + rules: + - host: {{ $frontendUrl.host }} + http: + paths: + - path: {{$lighthouseUrl.path}}(/|$)(.*) + backend: + serviceName: {{ include "lighthouse.serviceName" . }} + servicePort: 80 +{{- end }} diff --git a/contrib/chart/backstage/templates/issuer.yaml b/contrib/chart/backstage/templates/issuer.yaml new file mode 100644 index 0000000000..d129c8c701 --- /dev/null +++ b/contrib/chart/backstage/templates/issuer.yaml @@ -0,0 +1,19 @@ +{{- if (and (.Capabilities.APIVersions.Has "cert-manager.io/v1alpha2") .Values.issuer.email ) -}} +{{/* Only install issuer if it doesn't already exist in the cluster */}} +{{- if not ( lookup "cert-manager.io/v1alpha2" "ClusterIssuer" "" .Values.issuer.clusterIssuer ) }} +apiVersion: cert-manager.io/v1alpha2 +kind: ClusterIssuer +metadata: + name: {{ .Values.issuer.clusterIssuer }} +spec: + acme: + server: https://acme-v02.api.letsencrypt.org/directory + email: {{ required "expected a valid .Values.issuer.email to enable ClusterIssuer" .Values.issuer.email }} + privateKeySecretRef: + name: {{ required "expected .Values.issuer.cluster-issuer to not be empty (letsencrypt-prod | letsencrypt-staging)" .Values.issuer.clusterIssuer }} + solvers: + - http01: + ingress: + class: nginx +{{- end -}} +{{- end -}} diff --git a/contrib/chart/backstage/templates/lighthouse-config.yaml b/contrib/chart/backstage/templates/lighthouse-config.yaml new file mode 100644 index 0000000000..fdf4bd8b06 --- /dev/null +++ b/contrib/chart/backstage/templates/lighthouse-config.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "backstage.fullname" . -}}-lighthouse +data: + PGDATABASE: {{ .Values.lighthouse.database.connection.database | quote }} + PGUSER: {{ include "lighthouse.postgresql.user" . | quote }} + PGPORT: {{ include "lighthouse.postgresql.port" . | quote }} + PGHOST: {{ include "lighthouse.postgresql.host" . | quote }} + PGPATH_TO_CA: {{ include "backstage.lighthouse.postgresCaFilename" . | quote }} \ No newline at end of file diff --git a/contrib/chart/backstage/templates/lighthouse-deployment.yaml b/contrib/chart/backstage/templates/lighthouse-deployment.yaml new file mode 100644 index 0000000000..70341a2a22 --- /dev/null +++ b/contrib/chart/backstage/templates/lighthouse-deployment.yaml @@ -0,0 +1,74 @@ +{{- if .Values.lighthouse.enabled }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "backstage.fullname" . }}-lighthouse + +spec: + replicas: {{ .Values.lighthouse.replicaCount }} + + selector: + matchLabels: + app: backstage + component: lighthouse-audit-service + + template: + metadata: + annotations: + ad.datadoghq.com/backstage.logs: '[{"source":"backstage","service":"lighthouse"}]' + labels: + app: backstage + component: lighthouse-audit-service + + spec: + containers: + - name: lighthouse-audit-service + image: {{ .Values.lighthouse.image.repository }}:{{ .Values.lighthouse.image.tag }} + imagePullPolicy: {{ .Values.lighthouse.image.pullPolicy }} + ports: + - containerPort: {{ .Values.lighthouse.containerPort }} + resources: + {{- toYaml .Values.lighthouse.resources | nindent 12 }} + + envFrom: + - configMapRef: + name: {{ include "backstage.fullname" . -}}-lighthouse + - configMapRef: + name: {{ include "backstage.fullname" . }}-app-env + + env: + - name: LAS_PORT + value: {{ .Values.lighthouse.containerPort | quote }} + - name: LAS_CORS + value: "true" + - name: PGPASSWORD + valueFrom: + secretKeyRef: + name: {{ include "lighthouse.postgresql.passwordSecret" . }} + key: postgresql-password + + volumeMounts: + - name: postgres-ca + mountPath: {{ include "backstage.lighthouse.postgresCaDir" . }} + + volumes: + - name: postgres-ca + configMap: + name: {{ include "backstage.fullname" . }}-postgres-ca +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "lighthouse.serviceName" . }} + +spec: + ports: + - port: 80 + targetPort: {{ .Values.lighthouse.containerPort }} + + selector: + app: backstage + component: lighthouse-audit-service + + type: ClusterIP +{{- end }} diff --git a/contrib/chart/backstage/templates/postgresql-ca-config.yaml b/contrib/chart/backstage/templates/postgresql-ca-config.yaml new file mode 100644 index 0000000000..2631989f4e --- /dev/null +++ b/contrib/chart/backstage/templates/postgresql-ca-config.yaml @@ -0,0 +1,21 @@ +{{- if .Values.postgresql.enabled }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "backstage.fullname" . }}-postgres-ca + labels: + app: {{ include "backstage.postgresql.fullname" . }} + release: {{ .Release.Name }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: + {{ .Values.global.postgresql.caFilename }}: | +{{ include "backstage.postgresql.generateCA" . | indent 4}} +{{- else }} +{{- $caConfig := printf "%s-postgres-ca" (include "backstage.fullname" .) }} +{{- if not ( lookup "v1" "ConfigMap" .Release.Namespace $caConfig ) }} +{{- fail (printf "\n\nPlease create the '%s' configmap with the CA certificate for your existing postgresql: kubectl create configmap %s --from-file=ca.crt" $caConfig $caConfig) }} +{{- end }} +{{- end }} \ No newline at end of file diff --git a/contrib/chart/backstage/templates/postgresql-certs-secret.yaml b/contrib/chart/backstage/templates/postgresql-certs-secret.yaml new file mode 100644 index 0000000000..c6845caa7e --- /dev/null +++ b/contrib/chart/backstage/templates/postgresql-certs-secret.yaml @@ -0,0 +1,16 @@ +{{- if .Values.postgresql.enabled }} +--- +apiVersion: v1 +kind: Secret +type: kubernetes.io/tls +metadata: + name: {{ required ".Values.postgresql.tls.certificatesSecret is required" .Values.postgresql.tls.certificatesSecret }} + labels: + app: {{ include "backstage.postgresql.fullname" . }} + release: {{ .Release.Name }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: +{{ include "generateCerts" . | indent 2 }} +{{- end }} diff --git a/contrib/chart/backstage/templates/postgresql-initdb-secret.yaml b/contrib/chart/backstage/templates/postgresql-initdb-secret.yaml new file mode 100644 index 0000000000..d1c446f79f --- /dev/null +++ b/contrib/chart/backstage/templates/postgresql-initdb-secret.yaml @@ -0,0 +1,14 @@ +{{- if .Values.postgresql.enabled }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ required ".Values.postgresql.initdbScriptsSecret is required" .Values.postgresql.initdbScriptsSecret }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +type: Opaque +data: + create-backend-dbs.sql: | + {{ tpl (.Files.Get "files/create-backend-dbs.sql") . | b64enc }} +{{- end }} + diff --git a/contrib/chart/backstage/templates/postgresql-password-secret.yaml b/contrib/chart/backstage/templates/postgresql-password-secret.yaml new file mode 100644 index 0000000000..9685130a03 --- /dev/null +++ b/contrib/chart/backstage/templates/postgresql-password-secret.yaml @@ -0,0 +1,30 @@ +{{- if not .Values.postgresql.enabled }} +--- +apiVersion: v1 +kind: Secret +type: Opaque +metadata: + name: {{ include "backend.postgresql.passwordSecret" . }} + labels: + release: {{ .Release.Name }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: + postgresql-password: {{ .Values.appConfig.backend.database.connection.password | b64enc }} +{{- end }} +{{- if not .Values.postgresql.enabled }} +--- +apiVersion: v1 +kind: Secret +type: Opaque +metadata: + name: {{ include "lighthouse.postgresql.passwordSecret" . }} + labels: + release: {{ .Release.Name }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: + postgresql-password: {{ .Values.lighthouse.database.connection.password | b64enc }} +{{- end }} diff --git a/contrib/chart/backstage/templates/tests/test-app-connection.yaml b/contrib/chart/backstage/templates/tests/test-app-connection.yaml new file mode 100644 index 0000000000..93f51f3f09 --- /dev/null +++ b/contrib/chart/backstage/templates/tests/test-app-connection.yaml @@ -0,0 +1,23 @@ +--- +apiVersion: v1 +kind: Pod +metadata: + name: {{ include "backstage.fullname" . -}}-test-app-connection + annotations: + "helm.sh/hook": test +spec: + containers: + - name: test-app + image: busybox + command: + - /bin/sh + - -ecx + - | + echo -e "===== Testing the connection with the frontend...\n" + wget -q -O - {{ printf "%s.%s" (include "frontend.serviceName" .) .Release.Namespace | quote }} + echo -e "\n\n===== Testing the connection with the backend...\n" + wget -q -O - {{ printf "http://%s.%s/catalog/entities" (include "backend.serviceName" .) .Release.Namespace | quote }} + echo -e "\n\n===== Testing the connection with the lighthouse plugin...\n" + wget -q -O - {{ printf "%s.%s/v1/audits" (include "lighthouse.serviceName" .) .Release.Namespace | quote }} + echo -e "\n" + restartPolicy: Never \ No newline at end of file diff --git a/contrib/chart/backstage/templates/tests/test-postgresql.yaml b/contrib/chart/backstage/templates/tests/test-postgresql.yaml new file mode 100644 index 0000000000..8eec1db452 --- /dev/null +++ b/contrib/chart/backstage/templates/tests/test-postgresql.yaml @@ -0,0 +1,33 @@ +{{- if .Values.postgresql.enabled}} +--- +apiVersion: v1 +kind: Pod +metadata: + name: {{ include "backstage.name" . -}}-test-postgres + annotations: + "helm.sh/hook": test +spec: + containers: + - name: postgresql-client + image: bitnami/postgresql + env: + - name: PG_HOST + value: {{ include "postgresql.serviceName" . | quote }} + - name: PG_PORT + value: {{ .Values.postgresql.service.port | quote }} + - name: PG_USER + value: {{ .Values.global.postgresql.postgresqlUsername | quote }} + - name: PGPASSWORD + valueFrom: + secretKeyRef: + name: {{ include "backend.postgresql.passwordSecret" .}} + key: postgresql-password + - name: PG_DBNAME + value: {{ .Values.appConfig.backend.database.connection.database }} + command: + - /bin/bash + - -ecx + - | + psql --host=$PG_HOST --port=$PG_PORT --username=$PG_USER --dbname=$PG_DBNAME --no-password + restartPolicy: Never +{{- end }} \ No newline at end of file diff --git a/contrib/chart/backstage/values.yaml b/contrib/chart/backstage/values.yaml new file mode 100644 index 0000000000..eb06422d34 --- /dev/null +++ b/contrib/chart/backstage/values.yaml @@ -0,0 +1,252 @@ +# Default values for backstage. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +frontend: + enabled: true + replicaCount: 1 + image: + repository: martinaif/backstage-k8s-demo-frontend + tag: test1 + pullPolicy: IfNotPresent + containerPort: 80 + resources: + requests: + memory: 128Mi + limits: + memory: 256Mi + +backend: + enabled: true + nodeEnv: development + demoData: true + replicaCount: 1 + image: + repository: martinaif/backstage-k8s-demo-backend + tag: test1 + pullPolicy: IfNotPresent + containerPort: 7000 + resources: + requests: + memory: 512Mi + limits: + memory: 1024Mi + +lighthouse: + enabled: true + replicaCount: 1 + image: + repository: roadiehq/lighthouse-audit-service + tag: latest + pullPolicy: IfNotPresent + containerPort: 3003 + resources: + requests: + memory: 128Mi + limits: + memory: 256Mi + database: + connection: + port: + host: + user: + password: + database: lighthouse_audit_service + pathToDatabaseCa: + +nameOverride: '' +fullnameOverride: '' + +ingress: + annotations: + kubernetes.io/ingress.class: nginx + +issuer: + email: + clusterIssuer: 'letsencrypt-staging' + +global: + postgresql: + postgresqlUsername: backend-user + caFilename: ca.crt + +postgresql: + enabled: true + nameOverride: postgresql + tls: + enabled: true + certificatesSecret: backstage-postgresql-certs + certFilename: tls.crt + certKeyFilename: tls.key + volumePermissions: + enabled: true + initdbScriptsSecret: backstage-postgresql-initdb + +appConfig: + app: + baseUrl: https://demo.example.com + title: Backstage + googleAnalyticsTrackingId: + backend: + baseUrl: https://demo.example.com + listen: + port: 7000 + cors: + origin: https://demo.example.com + database: + client: pg + connection: + database: backstage_plugin_catalog + host: + user: + port: + password: + ssl: + rejectUnauthorized: false + ca: + sentry: + organization: spotify + techdocs: + storageUrl: https://demo.example.com/api/techdocs/static/docs + requestUrl: https://demo.example.com/api/techdocs + lighthouse: + baseUrl: https://demo.example.com/lighthouse-api + rollbar: + organization: roadie + + # Auth config has recently moved into the app config file in upstream Backstage. However, + # most of this config simply mandates that items like the client id and client secret should + # be picked up from the environment variables named below. Those environment variables are + # set in this helm controlled environment by the 'auth' configuration below this section. + # Thus, the only key in this config which directly controls an app config is the + # auth.providers.github.development.appOrigin property. + auth: + providers: + google: + development: + appOrigin: 'http://localhost:3000/' + secure: false + clientId: + $secret: + env: AUTH_GOOGLE_CLIENT_ID + clientSecret: + $secret: + env: AUTH_GOOGLE_CLIENT_SECRET + github: + development: + appOrigin: 'http://localhost:3000/' + secure: false + clientId: + $secret: + env: AUTH_GITHUB_CLIENT_ID + clientSecret: + $secret: + env: AUTH_GITHUB_CLIENT_SECRET + enterpriseInstanceUrl: + $secret: + env: AUTH_GITHUB_ENTERPRISE_INSTANCE_URL + gitlab: + development: + appOrigin: 'http://localhost:3000/' + secure: false + clientId: + $secret: + env: AUTH_GITLAB_CLIENT_ID + clientSecret: + $secret: + env: AUTH_GITLAB_CLIENT_SECRET + audience: + $secret: + env: GITLAB_BASE_URL + okta: + development: + appOrigin: 'http://localhost:3000/' + secure: false + clientId: + $secret: + env: AUTH_OKTA_CLIENT_ID + clientSecret: + $secret: + env: AUTH_OKTA_CLIENT_SECRET + audience: + $secret: + env: AUTH_OKTA_AUDIENCE + oauth2: + development: + appOrigin: 'http://localhost:3000/' + secure: false + clientId: + $secret: + env: AUTH_OAUTH2_CLIENT_ID + clientSecret: + $secret: + env: AUTH_OAUTH2_CLIENT_SECRET + authorizationURL: + $secret: + env: AUTH_OAUTH2_AUTH_URL + tokenURL: + $secret: + env: AUTH_OAUTH2_TOKEN_URL + auth0: + development: + clientId: + $secret: + env: AUTH_AUTH0_CLIENT_ID + clientSecret: + $secret: + env: AUTH_AUTH0_CLIENT_SECRET + domain: + $secret: + env: AUTH_AUTH0_DOMAIN + microsoft: + development: + clientId: + $secret: + env: AUTH_MICROSOFT_CLIENT_ID + clientSecret: + $secret: + env: AUTH_MICROSOFT_CLIENT_SECRET + tenantId: + $secret: + env: AUTH_MICROSOFT_TENANT_ID + +auth: + google: + clientId: a + clientSecret: a + github: + clientId: c + clientSecret: c + gitlab: + clientId: b + clientSecret: b + baseUrl: b + okta: + clientId: b + clientSecret: b + audience: b + oauth2: + clientId: b + clientSecret: b + authUrl: b + tokenUrl: b + auth0: + clientId: b + clientSecret: b + domain: b + microsoft: + clientId: f + clientSecret: f + tenantId: f + azure: + api: + token: h + sentryToken: e + rollbarAccountToken: f + # This is a 'Personal Access Token' + circleciAuthToken: r + # Used by the scaffolder to create GitHub repos. Must have 'repo' scope. + githubToken: g + gitlabToken: g + newRelicRestApiKey: r + travisciAuthToken: fake-travis-ci-auth-token diff --git a/contrib/docker/kubernetes-example-backend/Dockerfile b/contrib/docker/kubernetes-example-backend/Dockerfile new file mode 100644 index 0000000000..df617decf5 --- /dev/null +++ b/contrib/docker/kubernetes-example-backend/Dockerfile @@ -0,0 +1,35 @@ +FROM node:12-buster + +WORKDIR /usr/src/app + +# (workaround) Install cookiecutter and mkdocs to avoid the need to run docker in docker +RUN cd /tmp && curl -O https://www.python.org/ftp/python/3.8.2/Python-3.8.2.tar.xz && \ + tar -xvf Python-3.8.2.tar.xz && \ + cd Python-3.8.2 && \ + ./configure --enable-optimizations && \ + make -j 4 && \ + make altinstall + +RUN apt update +RUN apt install -y mkdocs + +RUN pip3.8 install mkdocs-techdocs-core + +RUN pip3.8 install cookiecutter && \ + apt remove -y build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev g++ python-pip python-dev && \ + rm -rf /var/cache/apt/* /tmp/Python-3.8.2 + +# Copy repo skeleton first, to avoid unnecessary docker cache invalidation. +# The skeleton contains the package.json of each package in the monorepo, +# and along with yarn.lock and the root package.json, that's enough to run yarn install. +ADD yarn.lock package.json skeleton.tar ./ + +RUN yarn install --frozen-lockfile --production + +# This will copy the contents of the dist-workspace when running the build-image command. +# Do not use this Dockerfile outside of that command, as it will copy in the source code instead. +COPY . . + +CMD ["node", "packages/backend"] + + diff --git a/contrib/docker/kubernetes-example-backend/README.md b/contrib/docker/kubernetes-example-backend/README.md new file mode 100644 index 0000000000..d0f9d57022 --- /dev/null +++ b/contrib/docker/kubernetes-example-backend/README.md @@ -0,0 +1,13 @@ +# Example backend Dockerfile + +This Dockerfile will build the example backend with certain additional binaries needed to workaround +the docker requirement in the scaffolder and techdocs. + +# Usage + +```bash +yarn docker-build -f --tag +``` + +> The absolute path is necessary as this directory is not copied to the build workspace when building +> the docker image. diff --git a/contrib/docs/tutorials/help-im-behind-a-corporate-proxy.md b/contrib/docs/tutorials/help-im-behind-a-corporate-proxy.md new file mode 100644 index 0000000000..4f8351ac15 --- /dev/null +++ b/contrib/docs/tutorials/help-im-behind-a-corporate-proxy.md @@ -0,0 +1,58 @@ +# Running the backend behind a Corporate Proxy + +Let's admit it, we've all been there. Sometimes you've gotta run stuff with no way out to the public internet, only the smallest of corporate proxy tunnels. + +Whilst this isn't supported natively by Backstage, this might help you get your installation up and running making calls through the said proxy tunnel. + +Unfortunately, `nodejs` does not respect `HTTP(S)_PROXY` environment variables by default, and the library that we use to provide `fetch` functionality `node-fetch` (provided by `cross-fetch`) does not also respect these environment variables. + +There are however some ways to get this to work without too much effort. It's most likely that you're going to run into these issues from the `backend` part of `backstage` as that's the part that isn't helped by your browser or OS's settings for the corporate proxy. + +**Note:** You're gonna want to be in your backend working directory for these solutions as that's where the requests come from that don't go through this proxy. + +### Using `global-agent` + +1. Install `global-agent` using `yarn install global-agent` +2. Go to the entry file for the backend (`src/index.ts`) +3. At the top of the file paste the following: + +```ts +import 'global-agent/bootstrap'; +``` + +4. Start the backend with the `global-agent` variables + +```sh +export GLOBAL_AGENT_HTTP_PROXY=$HTTP_PROXY +yarn start +``` + +More information and more options for configuring `global-agent` including just using the default environment variables can be found here: https://github.com/gajus/global-agent + +### Using `proxy-agent` + +`proxy-agent` is a library that you can use to override the `globalAgents` of `node` land with a tunnel to use for each request. + +1. Install `proxy-agent` using `yarn install proxy-agent` +2. Go to the entry file for the backend (`src/index.ts`) +3. At the top of the file paste the following: + +```ts +import ProxyAgent from 'proxy-agent'; +import http from 'http'; +import https from 'https'; + +/* + Something to note here, this might need different configuration depending on your own setup. + If you only have an http_proxy then you'll need to set that as both the http and https globalAgent instead. +*/ +if (process.env.HTTP_PROXY) { + http.globalAgent = new ProxyAgent(process.env.HTTP_PROXY); +} + +if (process.env.HTTPS_PROXY) { + https.globalAgent = new ProxyAgent(process.env.HTTPS_PROXY); +} +``` + +4. Start the backend with `yarn start` diff --git a/contrib/docs/tutorials/quickstart-app-plugin/ExampleComponent.md b/contrib/docs/tutorials/quickstart-app-plugin/ExampleComponent.md index 855608c8b1..5d633544e3 100644 --- a/contrib/docs/tutorials/quickstart-app-plugin/ExampleComponent.md +++ b/contrib/docs/tutorials/quickstart-app-plugin/ExampleComponent.md @@ -9,7 +9,6 @@ import { InfoCard, Header, Page, - pageTheme, Content, ContentHeader, HeaderLabel, @@ -25,7 +24,7 @@ const ExampleComponent: FC<{}> = () => { const profile = identityApi.getProfile(); return ( - +
` flags. The configuration files themselves +contain plain YAML, but with support for loading in secrets from various sources +using for example `$env` and `$file` keys. It is also possible to supply configuration through environment variables, for example `APP_CONFIG_app_baseUrl=https://staging.example.com`. However these diff --git a/docs/conf/writing.md b/docs/conf/writing.md index 5564e780bb..06d4b52f3f 100644 --- a/docs/conf/writing.md +++ b/docs/conf/writing.md @@ -55,19 +55,28 @@ picked up by the serve tasks of `@backstage/cli` for local development, and are injected by the entrypoint of the nginx container serving the frontend in a production build. -## File Resolution +## Configuration Files It is possible to have multiple configuration files, both to support different environments, but also to define configuration that is local to specific -packages. +packages. The configuration files to load are selected using a `--config ` +flag, and it is possible to load any number of files. Paths are relative to the +working directory of the executed process, for example `package/backend`. This +means that to select a config file in the repo root when running the backend, +you would use `--config ../../my-config.yaml`. -All `app-config.yaml` files inside the monorepo root and package root are -considered, as are files with additional `local` and environment affixes such as -`development`, for example `app-config.local.yaml`, -`app-config.production.yaml`, and `app-config.development.local.yaml`. Which -environment config files are loaded is determined by the `NODE_ENV` environment -variable. Local configuration files are always loaded, but are meant for local -development overrides and should typically be `.gitignore`'d. +If no `config` flags are specified, the default behavior is to load +`app-config.yaml` and, if it exists, `app-config.local.yaml` from the repo root. +In the provided project setup, `app-config.local.yaml` is `.gitignore`'d, making +it a good place to add config overrides and secrets for local development. + +Note that if any config flags are provided, the default `app-config.yaml` files +are NOT loaded. To include them you need to explicitly include them with a flag, +for example: + +``` +yarn start --config ../../app-config.yaml --config ../../app-config.staging.yaml +``` All loaded configuration files are merged together using the following rules: @@ -83,10 +92,10 @@ order: - Configuration from the `APP_CONFIG_` environment variables has the highest priority, followed by files. -- Files inside package directories have higher priority than those in the root - directory. -- Files with environment affixes have higher priority than ones without. -- Files with the `local` affix have higher priority than ones without. +- Files loaded with config flags are ordered by priority, where the last flag + has the highest priority. +- If no config flags are provided, `app-config.local.yaml` has higher priority + than `app-config.yaml`. ## Secrets diff --git a/docs/features/software-catalog/configuration.md b/docs/features/software-catalog/configuration.md index 46de2d3d67..dd19d4cd51 100644 --- a/docs/features/software-catalog/configuration.md +++ b/docs/features/software-catalog/configuration.md @@ -1,5 +1,5 @@ --- -id: software-catalog-configuration +id: configuration title: Catalog Configuration description: Documentation on Software Catalog Configuration --- diff --git a/docs/features/software-catalog/descriptor-format.md b/docs/features/software-catalog/descriptor-format.md index 0c50e3669a..62ac9da8d8 100644 --- a/docs/features/software-catalog/descriptor-format.md +++ b/docs/features/software-catalog/descriptor-format.md @@ -12,7 +12,10 @@ This both applies to objects given to and returned from the software catalog API, as well as to the descriptor files that the software catalog can ingest natively. In the API request/response cycle, a JSON representation is used, while the descriptor files are on YAML format to be more easily maintainable by -humans. However, the structure and semantics is the same in both cases. +humans. However, the structure and semantics are the same in both cases. + +Although it's possible to name catalog entity descriptor files however you wish, +we recommend that you name them `catalog-info.yaml`. ## Contents @@ -110,7 +113,7 @@ data. Backstage specific entities have an `apiVersion` that is prefixed with `backstage.io/`, to distinguish them from other types of object that share the same type of structure. This may be relevant when co-hosting these -specifications with e.g. kubernetes object manifests, or when an organization +specifications with e.g. Kubernetes object manifests, or when an organization adds their own specific kinds of entity to the catalog. Early versions of the catalog will be using alpha/beta versions, e.g. diff --git a/docs/features/software-catalog/index.md b/docs/features/software-catalog/index.md index 4ba83146db..953540227c 100644 --- a/docs/features/software-catalog/index.md +++ b/docs/features/software-catalog/index.md @@ -19,7 +19,7 @@ are then harvested and visualized in Backstage. ## How it works -Backstage and the Backstage Service Catalog makes it easy for one team to manage +Backstage and the Backstage Service Catalog make it easy for one team to manage 10 services — and makes it possible for your company to manage thousands of them. diff --git a/docs/features/software-catalog/well-known-annotations.md b/docs/features/software-catalog/well-known-annotations.md index 757e0461a9..40a4ca3ea1 100644 --- a/docs/features/software-catalog/well-known-annotations.md +++ b/docs/features/software-catalog/well-known-annotations.md @@ -41,27 +41,6 @@ expecting a two-item array out of it. The format of the target part is type-dependent and could conceivably even be an empty string, but the separator colon is always present. -### backstage.io/definition-at-location - -```yaml -# Example -apiVersion: backstage.io/v1alpha1 -kind: API -metadata: - name: petstore - annotations: - backstage.io/definition-at-location: 'url:https://petstore.swagger.io/v2/swagger.json' -spec: - type: openapi -``` - -This annotation allows to fetch an API definition from another location, instead -of wrapping the API definition inside the definition field. This allows to -easily consume existing API definition. The definition is fetched during -ingestion by a processor and included in the entity. It is updated on every -refresh. The annotation contains a location reference string that contains the -location processor type and the target. - ### backstage.io/techdocs-ref ```yaml @@ -205,6 +184,25 @@ This annotation was used for a while to enable the GitHub Actions feature. This is now instead using the [github.com/project-slug](#github-com-project-slug) annotation, with the same value format. +### backstage.io/definition-at-location + +This annotation allowed to load the API definition from another location. Now +placeholders can be used instead: + +``` +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: petstore + description: The Petstore API +spec: + type: openapi + lifecycle: production + owner: petstore@example.com + definition: + $text: https://petstore.swagger.io/v2/swagger.json +``` + ## Links - [Descriptor Format: annotations](descriptor-format.md#annotations-optional) diff --git a/docs/features/software-templates/adding-templates.md b/docs/features/software-templates/adding-templates.md index 5a4e0049ab..75a75003f7 100644 --- a/docs/features/software-templates/adding-templates.md +++ b/docs/features/software-templates/adding-templates.md @@ -5,8 +5,8 @@ description: Documentation on Adding your own Templates --- Templates are stored in the **Service Catalog** under a kind `Template`. The -minimum that the template skeleton needs is a `template.yaml` but it would be -good to also have some files in there that can be templated in. +minimum that is needed to define a template is a `template.yaml` file, but it +would be good to also have some files in there that can be templated in. A simple `template.yaml` definition might look something like this: @@ -61,7 +61,7 @@ support to load the location will also need to be added to the Catalog. You can add the template files to the catalog through [static location configuration](../software-catalog/configuration.md#static-location-configuration), -for example +for example: ```yaml catalog: @@ -100,11 +100,11 @@ curl \ --location \ --request POST 'localhost:7000/api/catalog/locations' \ --header 'Content-Type: application/json' \ - --data-raw "{\"type\": \"github\", \"target\": \"https://${YOUR GITHUB REPO}blob/master/${PATH TO FOLDER}/template.yaml\"}" + --data-raw "{\"type\": \"github\", \"target\": \"https://${GITHUB URL}/${YOUR GITHUB ORG/REPO}/blob/master/${PATH TO FOLDER}/template.yaml\"}" ``` -This should then have added the catalog, and also should now be listed under the -create page at http://localhost:3000/create. +This should then have been added the catalog, and be listed under the create +page at http://localhost:3000/create. The `type` field which is chosen in the request to add the `template.yaml` to the Service Catalog here, will become the `PreparerKey` which will be used to diff --git a/docs/features/software-templates/extending/create-your-own-preparer.md b/docs/features/software-templates/extending/create-your-own-preparer.md index 80287c6ce1..ef9d709bce 100644 --- a/docs/features/software-templates/extending/create-your-own-preparer.md +++ b/docs/features/software-templates/extending/create-your-own-preparer.md @@ -15,10 +15,10 @@ location protocols: - `github://` These two are added to the `PreparersBuilder` and then passed into the -`createRouter` function of the `@spotify/plugin-scaffolder-backend` +`createRouter` function of the `@spotify/plugin-scaffolder-backend`. -A full example backend can be found -[here](https://github.com/spotify/backstage/blob/d91c10f654475a60829fa33a5c81018e517a319a/packages/backend/src/plugins/scaffolder.ts), +A full example backend can be found in +[`scaffolder.ts`](https://github.com/spotify/backstage/blob/d91c10f654475a60829fa33a5c81018e517a319a/packages/backend/src/plugins/scaffolder.ts), but it looks something like the following ```ts @@ -56,7 +56,7 @@ when added to the service catalog. You can see more about this `PreparerKey` here in [Register your own template](../adding-templates.md) **note:** Currently the catalog supports loading definitions from GitHub + Local -Files, which translate into the two `PreparerKeys` `file` and `github`. To load +Files, which translate into the two `PreparerKeys`: `file` and `github`. To load from other places, not only will there need to be another preparer, but the support to load the location will also need to be added to the Catalog. diff --git a/docs/features/software-templates/extending/create-your-own-publisher.md b/docs/features/software-templates/extending/create-your-own-publisher.md index ecb097f9d9..546980f033 100644 --- a/docs/features/software-templates/extending/create-your-own-publisher.md +++ b/docs/features/software-templates/extending/create-your-own-publisher.md @@ -34,7 +34,7 @@ import { Octokit } from '@octokit/rest'; import type { PluginEnvironment } from '../types'; export default async function createPlugin({ logger }: PluginEnvironment) { - const githubClient = new Octokit({ auth: process.env.GITHUB_ACCESS_TOKEN }); + const githubClient = new Octokit({ auth: process.env.GITHUB_TOKEN }); const publisher = new GithubPublisher({ client: githubClient }); return await createRouter({ diff --git a/docs/features/software-templates/index.md b/docs/features/software-templates/index.md index ae121f8029..3ebb426466 100644 --- a/docs/features/software-templates/index.md +++ b/docs/features/software-templates/index.md @@ -39,17 +39,17 @@ internally. ![Enter some variables](../../assets/software-templates/template-picked.png) After filling in these variables, you'll get some more fields to fill out which -are required for backstage usage: the owner, (which is a `user` in the backstage +are required for backstage usage: the owner (which is a `user` in the backstage system), the `storePath` (which right now must be a GitHub Organisation or -GitHub user), a non-existing github repository name in the format -`organisation/reponame`, and a GitHub team or user account which should be +GitHub user and a non-existing GitHub repository name in the format +`organisation/reponame`), and a GitHub team or user account which should be granted admin access to the repository. ![Enter backstage vars](../../assets/software-templates/template-picked-2.png) ### Run! -Once you've entered values and confirmed, you'll then get a modal with live +Once you've entered values and confirmed, you'll then get a popup box with live progress of what is currently happening with the creation of your template. ![Templating Running](../../assets/software-templates/running.png) @@ -70,6 +70,6 @@ you to the registered component in the catalog: ![Catalog](../../assets/software-templates/go-to-catalog.png) -And then you'll also be able to see it in the Catalog View table +And then you'll also be able to see it in the Catalog View table: ![Catalog](../../assets/software-templates/added-to-the-catalog-list.png) diff --git a/docs/features/software-templates/installation.md b/docs/features/software-templates/installation.md index 60f73ad0c3..bac5f60789 100644 --- a/docs/features/software-templates/installation.md +++ b/docs/features/software-templates/installation.md @@ -111,44 +111,8 @@ export default async function createPlugin({ templaters.register('cookiecutter', cookiecutterTemplater); templaters.register('cra', craTemplater); - const filePreparer = new FilePreparer(); - const githubPreparer = new GithubPreparer(); - const gitlabPreparer = new GitlabPreparer(config); - const preparers = new Preparers(); - - preparers.register('file', filePreparer); - preparers.register('github', githubPreparer); - preparers.register('gitlab', gitlabPreparer); - preparers.register('gitlab/api', gitlabPreparer); - - const publishers = new Publishers(); - - const githubToken = config.getString('scaffolder.github.token'); - const repoVisibility = config.getString( - 'scaffolder.github.visibility', - ) as RepoVisibilityOptions; - - const githubClient = new Octokit({ auth: githubToken }); - const githubPublisher = new GithubPublisher({ - client: githubClient, - token: githubToken, - repoVisibility, - }); - publishers.register('file', githubPublisher); - publishers.register('github', githubPublisher); - - const gitLabConfig = config.getOptionalConfig('scaffolder.gitlab.api'); - - if (gitLabConfig) { - const gitLabToken = gitLabConfig.getString('token'); - const gitLabClient = new Gitlab({ - host: gitLabConfig.getOptionalString('baseUrl'), - token: gitLabToken, - }); - const gitLabPublisher = new GitlabPublisher(gitLabClient, gitLabToken); - publishers.register('gitlab', gitLabPublisher); - publishers.register('gitlab/api', gitLabPublisher); - } + const preparers = await Preparers.fromConfig(config, { logger }); + const publishers = await Publishers.fromConfig(config, { logger }); const dockerClient = new Docker(); return await createRouter({ @@ -211,34 +175,38 @@ docs on creating private GitHub access tokens is available Note that the need for private GitHub access tokens will be replaced with GitHub Apps integration further down the line. -#### Github +#### GitHub -The Github access token is retrieved from environment variables via the config. +The GitHub access token is retrieved from environment variables via the config. The config file needs to specify what environment variable the token is retrieved from. Your config should have the following objects. You can configure who can see the new repositories that the scaffolder creates by specifying `visibility` option. Valid options are `public`, `private` and -`internal`. `internal` options is for GitHub Enterprise clients, which means -public within the organization. - -#### Gitlab - -For Gitlab, we currently support the configuration of the GitLab publisher and -allows to configure the private access token and the base URL of a GitLab -instance: +`internal`. The `internal` option is for GitHub Enterprise clients, which means +public within the enterprise. ```yaml scaffolder: github: token: - $env: GITHUB_ACCESS_TOKEN + $env: GITHUB_TOKEN visibility: public # or 'internal' or 'private' +``` + +#### GitLab + +For GitLab, we currently support the configuration of the GitLab publisher and +allows to configure the private access token and the base URL of a GitLab +instance: + +```yaml +scaffolder: gitlab: api: baseUrl: https://gitlab.com token: - $env: SCAFFOLDER_GITLAB_PRIVATE_TOKEN + $env: GITLAB_TOKEN ``` #### Azure DevOps @@ -255,7 +223,7 @@ scaffolder: baseUrl: https://dev.azure.com/{your-organization} api: token: - $env: AZURE_PRIVATE_TOKEN + $env: AZURE_TOKEN ``` ### Running the Backend @@ -265,7 +233,7 @@ backend with the new configuration: ```bash cd packages/backend -GITHUB_ACCESS_TOKEN= yarn start +GITHUB_TOKEN= yarn start ``` If you've also set up the frontend plugin, so you should be ready to go browse diff --git a/docs/features/techdocs/README.md b/docs/features/techdocs/README.md index cec5b63cc7..e2b81b4a53 100644 --- a/docs/features/techdocs/README.md +++ b/docs/features/techdocs/README.md @@ -82,7 +82,9 @@ for companies to adopt. This involves (something like) the following work items. - “Solidify” work and “Mkdocs stabilization” work that has come out of our Q3 end-to-end work. - Improve/simplify the get up and running process. -- Introduce doc template Software Templates. +- Introduce new documentation templates. +- Extend the already existing docs-template to have options of different + documentation types. - Enable companies to choose their own storage (S3 for example). - Enable companies to choose their own source code hosting provider (GitHub, GitLab, and so). diff --git a/docs/features/techdocs/creating-and-publishing.md b/docs/features/techdocs/creating-and-publishing.md index e1adedf25e..38f452dcf3 100644 --- a/docs/features/techdocs/creating-and-publishing.md +++ b/docs/features/techdocs/creating-and-publishing.md @@ -19,12 +19,20 @@ This section will guide you through: ## Create a basic documentation setup +If you have an existing repository that you'd like to add documentation to, skip +to the +[Manually add documentation setup](#manually-add-documentation-setup-to-already-existing-repository) +section below. Otherwise, continue reading to start a documentation repo from +scratch. + ### Use the documentation template Your working Backstage instance should by default have a documentation template added. If not, follow these [instructions](../software-templates/installation.md#adding-templates) to add -the documentation template. +the documentation template. The template creates a component with only TechDocs +configuration and default markdown files as below mentioned in manual +documentation setup, and is otherwise empty. ![Documentation Template](../../assets/techdocs/documentation-template.png) @@ -35,9 +43,11 @@ setup for free. Prerequisities: -- `catalog-info.yml` file registered to Backstage. +- An existing component + [registered in backstage](../software-catalog/index.md#adding-components-to-the-catalog) + (e.g. via a `catalog-info.yaml` file). -Create a `mkdocs.yml` file in the root of the repository with the following +Create an `mkdocs.yml` file in the root of your repository with the following content: ```yaml @@ -50,8 +60,8 @@ plugins: - techdocs-core ``` -Update your `catalog-info.yaml` file in the root of the repository with the -following content: +Update your component's entity description by adding the following lines to its +`catalog-info.yaml` in the root of its repository: ```yaml metadata: @@ -59,7 +69,7 @@ metadata: backstage.io/techdocs-ref: dir:./ ``` -Create a `/docs` folder in the root of the project with at least a `index.md` +Create a `/docs` folder in the root of the project with at least an `index.md` file. _(If you add more markdown files, make sure to update the nav in the mkdocs.yml file to get a proper navigation for your documentation.)_ diff --git a/docs/features/techdocs/getting-started.md b/docs/features/techdocs/getting-started.md index 2e5c8d000d..72efb6eee0 100644 --- a/docs/features/techdocs/getting-started.md +++ b/docs/features/techdocs/getting-started.md @@ -58,7 +58,7 @@ The default storage and request URLs: ```yaml techdocs: storageUrl: http://localhost:7000/api/techdocs/static/docs - requestUrl: http://localhost:7000/api/techdocs/docs + requestUrl: http://localhost:7000/api/techdocs/ ``` If you want `techdocs-backend` to manage building and publishing, you want diff --git a/docs/getting-started/create-an-app.md b/docs/getting-started/create-an-app.md index 9be0e24452..c35eded6a5 100644 --- a/docs/getting-started/create-an-app.md +++ b/docs/getting-started/create-an-app.md @@ -13,7 +13,7 @@ need to run Backstage in your own environment. ## Create an app To create a Backstage app, you will need to have -[NodeJS](https://nodejs.org/en/download/) Active LTS Release installed +[Node.js](https://nodejs.org/en/download/) Active LTS Release installed (currently v12). Backstage provides a utility for creating new apps. It guides you through the @@ -124,3 +124,21 @@ the root directory: ```bash yarn workspace backend start ``` + +### Troubleshooting + +#### Cannot find module + +You may encounter an error similar to below: + +``` +internal/modules/cjs/loader.js:968 + throw err; + ^ + +Error: Cannot find module '../build/Debug/nodegit.node' +``` + +This can occur if an npm dependency is not completely installed. Because some +dependencies run a post-install script, ensure that both your npm and yarn +configs have the `ignore-scripts` flag set to `false`. diff --git a/docs/getting-started/deployment-helm.md b/docs/getting-started/deployment-helm.md new file mode 100644 index 0000000000..c062ed3951 --- /dev/null +++ b/docs/getting-started/deployment-helm.md @@ -0,0 +1,64 @@ +--- +id: deployment-helm +title: Helm +description: Documentation on Kubernetes and Helm Deployment +sidebar_label: Kubernetes and Helm +--- + +# Helm charts + +An example Backstage app can be deployed in Kubernetes using the +[Backstage Helm charts](https://github.com/spotify/backstage/tree/master/contrib/chart/backstage). + +First, choose a DNS name where Backstage will be hosted, and create a YAML file +for your custom configuration. + +```yaml +appConfig: + app: + baseUrl: https://backstage.mydomain.com + title: Backstage + backend: + baseUrl: https://backstage.mydomain.com + cors: + origin: https://backstage.mydomain.com + lighthouse: + baseUrl: https://backstage.mydomain.com/lighthouse-api + techdocs: + storageUrl: https://backstage.mydomain.com/api/techdocs/static/docs + requestUrl: https://backstage.mydomain.com/api/techdocs +``` + +Then use it to run: + +```bash +git clone https://github.com/spotify/backstage.git +cd contrib/chart/backstage +helm dependency update +helm install -f backstage-mydomain.yaml backstage . +``` + +This command will deploy the following pieces: + +- Backstage frontend +- Backstage backend with scaffolder and auth plugins +- (optional) a PostgreSQL instance +- lighthouse plugin +- ingress + +After a few minutes Backstage should be up and running in your cluster under the +DNS specified earlier. + +Make sure to create the appropriate DNS entry in your infrastructure. To find +the public IP address run: + +```bash +$ kubectl get ingress +NAME HOSTS ADDRESS PORTS AGE +backstage-ingress * 123.1.2.3 80 17m +``` + +> **NOTE**: this is not a production ready deployment. + +For more information on how to customize the deployment check the +[README](https://github.com/spotify/backstage/tree/master/contrib/chart/backstage/README.md). diff --git a/docs/getting-started/deployment-k8s.md b/docs/getting-started/deployment-k8s.md index ddcbd290c6..f123dd2548 100644 --- a/docs/getting-started/deployment-k8s.md +++ b/docs/getting-started/deployment-k8s.md @@ -4,4 +4,10 @@ title: Kubernetes description: Documentation on Kubernetes and K8s Deployment --- -Coming soon! +Backstage itself provides tooling up to the point of building Docker images. +Beyond that point we do not have an opinionated way to deploy Backstage within +Kubernetes, as each cluster has its own unique set of tooling and patterns. + +We do provide examples to help you get started though. Check out +[this example](https://github.com/spotify/backstage/tree/master/contrib/kubernetes/plain_single_backend_deplyoment/) +for a basic single-deployment setup. diff --git a/docs/getting-started/deployment-other.md b/docs/getting-started/deployment-other.md index 2cd9708e2a..cfd2e903d9 100644 --- a/docs/getting-started/deployment-other.md +++ b/docs/getting-started/deployment-other.md @@ -13,18 +13,37 @@ Run the following commands if you have Docker environment ```bash $ yarn install $ yarn docker-build -$ docker run --rm -it -p 7000:7000 -e NODE_ENV=development example-backend:latest +$ docker run --rm -it -p 7000:7000 -e APP_ENV=production -e NODE_ENV=development example-backend:latest ``` Then open http://localhost/ on your browser. -### Running with `docker-compose` +## Heroku -There is also a `docker-compose.yaml` that you can use to replace the previous -`docker run` command: +Deploying to Heroku is relatively easy following these steps. + +First, make sure you have the +[Heroku CLI installed](https://devcenter.heroku.com/articles/heroku-cli) and log +into it as well as login into Heroku's +[container registry](https://devcenter.heroku.com/articles/container-registry-and-runtime). ```bash -$ yarn install -$ yarn docker-build -$ docker-compose up +$ heroku login +$ heroku container:login ``` + +You _might_ also need to set your Heroku app's stack to `container`. + +```bash +$ heroku stack:set container -a +``` + +We can now build/push the Docker image to Heroku's container registry and +release it to the `web` worker. + +```bash +$ heroku container:push web -a +$ heroku container:release web -a +``` + +With that, you should have Backstage up and running! diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index 4ca2f431a7..855c8b0634 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -23,8 +23,8 @@ Requests towards this repo. Backstage provides the `@backstage/create-app` package to scaffold standalone instances of Backstage. You will need to have -[NodeJS](https://nodejs.org/en/download/) Active LTS Release installed -(currently v12), [yarn](https://classic.yarnpkg.com/en/docs/install) and +[Node.js](https://nodejs.org/en/download/) Active LTS Release installed +(currently v12), [Yarn](https://classic.yarnpkg.com/en/docs/install) and [Python](https://www.python.org/downloads/) (although you likely have it already). You will also need to have [Docker](https://docs.docker.com/engine/install/) installed to use some features @@ -38,8 +38,8 @@ npx @backstage/create-app ``` You will be taken through a wizard to create your app, and the output should -look something like this. You can read more about this process -[here](https://backstage.io/docs/getting-started/create-an-app). +look something like this. You can read more about this process in +[Create an app](https://backstage.io/docs/getting-started/create-an-app). ### Contributing to Backstage diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md deleted file mode 100644 index 3b11d2b8e1..0000000000 --- a/docs/getting-started/installation.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -id: installation -title: Installation -description: Documentation on Installation ---- - -Coming soon! diff --git a/docs/getting-started/running-backstage-locally.md b/docs/getting-started/running-backstage-locally.md index 6e6c8b2733..1a9097afd3 100644 --- a/docs/getting-started/running-backstage-locally.md +++ b/docs/getting-started/running-backstage-locally.md @@ -8,7 +8,7 @@ description: Documentation on How to run Backstage Locally - Node.js -First make sure you are using NodeJS with an Active LTS Release, currently v12. +First make sure you are using Node.js with an Active LTS Release, currently v12. This is made easy with a version manager such as [nvm](https://github.com/nvm-sh/nvm) which allows for version switching. @@ -23,10 +23,10 @@ node --version > v12.18.3 ``` -- yarn +- Yarn Please refer to the -[installation instructions for yarn](https://classic.yarnpkg.com/en/docs/install/). +[installation instructions for Yarn](https://classic.yarnpkg.com/en/docs/install/). - Docker diff --git a/docs/overview/architecture-overview.md b/docs/overview/architecture-overview.md index 8edf3e9e4c..ee2d3c6097 100644 --- a/docs/overview/architecture-overview.md +++ b/docs/overview/architecture-overview.md @@ -24,7 +24,7 @@ different ways. ## Overview The following diagram shows how Backstage might look when deployed inside a -company which uses the Tech Radar plugin, the Lighthouse plugin, the Circle CI +company which uses the Tech Radar plugin, the Lighthouse plugin, the CircleCI plugin and the service catalog. There are 3 main components in this architecture: @@ -48,14 +48,14 @@ management. [[live demo](https://backstage-demo.roadie.io/)] ![UI with different components highlighted](../assets/architecture-overview/core-vs-plugin-components-highlighted.png) Each plugin typically makes itself available in the UI on a dedicated URL. For -example, the lighthouse plugin is registered with the UI on `/lighthouse`. +example, the Lighthouse plugin is registered with the UI on `/lighthouse`. [[live demo](https://backstage-demo.roadie.io/lighthouse)] ![The lighthouse plugin UI](../assets/architecture-overview/lighthouse-plugin.png) -The Circle CI plugin is available on `/circleci`. +The CircleCI plugin is available on `/circleci`. -![Circle CI Plugin UI](../assets/architecture-overview/circle-ci.png) +![CircleCI Plugin UI](../assets/architecture-overview/circle-ci.png) ## Plugins and plugin backends @@ -76,7 +76,7 @@ Plugins can be enabled, and passed configuration in `apis.ts`. For example, [here](https://github.com/spotify/backstage/blob/master/packages/app/src/apis.ts) is that file in the Backstage sample app. -This is how the lighthouse plugin would be enabled in a typical Backstage +This is how the Lighthouse plugin would be enabled in a typical Backstage application: ```tsx @@ -108,7 +108,7 @@ Architecturally, plugins can take three forms: #### Standalone plugins Standalone plugins run entirely in the browser. -[The tech radar plugin](https://backstage-demo.roadie.io/tech-radar), for +[The Tech Radar plugin](https://backstage-demo.roadie.io/tech-radar), for example, simply renders hard-coded information. It doesn't make any API requests to other services. @@ -124,9 +124,9 @@ simple. Service backed plugins make API requests to a service which is within the purview of the organisation running Backstage. -The lighthouse plugin, for example, makes requests to the +The Lighthouse plugin, for example, makes requests to the [lighthouse-audit-service](https://github.com/spotify/lighthouse-audit-service). -The lighthouse-audit-service is a microservice which runs a copy of Google's +The `lighthouse-audit-service` is a microservice which runs a copy of Google's [Lighthouse library](https://github.com/GoogleChrome/lighthouse/) and stores the results in a PostgreSQL database. @@ -144,43 +144,42 @@ Third-party backed plugins are similar to service backed plugins. The main difference is that the service which backs the plugin is hosted outside of the ecosystem of the company hosting Backstage. -The Circle CI plugin is an example of a third-party backed plugin. Circle CI is -a SaaS service which can be used without any knowledge of Backstage. It has an -API which a Backstage plugin consumes to display content. +The CircleCI plugin is an example of a third-party backed plugin. CircleCI is a +SaaS service which can be used without any knowledge of Backstage. It has an API +which a Backstage plugin consumes to display content. -Requests which go to Circle CI from the users browser are passed through a proxy +Requests which go to CircleCI from the users browser are passed through a proxy service that Backstage provides. Without this, the requests would be blocked by Cross Origin Resource Sharing policies which prevent a browser page served at [https://example.com](https://example.com) from serving resources hosted at https://circleci.com. -![CircleCi plugin talking to proxy talking to SaaS Circle CI](../assets/architecture-overview/circle-ci-plugin-architecture.png) +![CircleCI plugin talking to proxy talking to SaaS Circle CI](../assets/architecture-overview/circle-ci-plugin-architecture.png) ## Databases -As we have seen, both the lighthouse-audit-service and catalog-backend require a -database to work with. +As we have seen, both the `lighthouse-audit-service` and `catalog-backend` +require a database to work with. -At the time of writing, the lighthouse-audit-service requires PostgreSQL to work -with. The service catalog backend uses an in-memory Sqlite3 instance. This is a -development oriented setup and there are plans to support other databases in the -future. +At the time of writing, the `lighthouse-audit-service` requires PostgreSQL to +work with. The service catalog backend uses an in-memory Sqlite3 instance. This +is a development-oriented setup and there are plans to support other databases +in the future. -To learn more about the future of databases and Backstage, see the following two +To learn more about the future of databases and Backstage, see the following GitHub issues. -[Knex + Plugins (Multiple vs Single Database) · Issue #1598 · spotify/backstage](https://github.com/spotify/backstage/issues/1598) - -[Update migrations to support postgres by dariddler · Pull Request #1527 · spotify/backstage](https://github.com/spotify/backstage/pull/1527#discussion_r450374145) +- [Knex + Plugins (Multiple vs Single Database) · Issue #1598 · spotify/backstage](https://github.com/spotify/backstage/issues/1598) +- [Update migrations to support postgres by dariddler · Pull Request #1527 · spotify/backstage](https://github.com/spotify/backstage/pull/1527#discussion_r450374145) ## Containerization The example Backstage architecture shown above would Dockerize into three -separate docker images. +separate Docker images. 1. The frontend container 2. The backend container -3. The lighthouse audit service container +3. The Lighthouse audit service container ![Boxes around the architecture to indicate how it is containerised](../assets/architecture-overview/containerised.png) @@ -204,7 +203,7 @@ yarn run docker-build This will create a container called `example-backend`. The lighthouse-audit-service container is already publicly available in Docker -Hub and can be downloaded and ran with +Hub and can be downloaded and run with ```bash docker run spotify/lighthouse-audit-service:latest diff --git a/docs/overview/roadmap.md b/docs/overview/roadmap.md index 1c90916fb5..51f09347ce 100644 --- a/docs/overview/roadmap.md +++ b/docs/overview/roadmap.md @@ -47,46 +47,29 @@ guidelines to get started. ### Ongoing work 🚧 -- **[Plugins for managing micro services end-2-end](https://github.com/spotify/backstage/milestone/14)** - +- **[Plugins for managing micro services end-2-end](https://github.com/spotify/backstage/milestone/14)** Out of the box Backstage will ship with a set of plugins (Overview, CI, API and Docs) that will demonstrate how a user can manage a micro service and follow a change all the way out in production. Completing this work will make it much easier to see how a plugin can be built that integrates with the Backstage Service Catalog. -- **[Kubernetes support](https://github.com/spotify/backstage/milestone/20)** - - Native support for Kubernetes, making it easier for developers to see and - manage their services running in k8s. - -- **[Helm charts](https://github.com/spotify/backstage/issues/2540)** - Provide - Helm charts for easy deployments of Backstage and its subsystems on - Kubernetes. +- **[Users and teams](https://github.com/spotify/backstage/issues/1807)** + Ownership is a central concept in Backstage. It should be easy to import your + existing organizational data, such as users and groups/teams, into Backstage. + A user the logs into Backstage should see software components owned by the + team(s) they are in. - **[Backstage platform is stable](https://github.com/spotify/backstage/milestone/19)** - The platform APIs and features are stable and can be depended on for production use. After this plugins will require little to no maintenance. -- **Backstage Design System** - By providing design guidelines for common plugin - layouts together, rich set of reusable UI components - ([Storybook](https://backstage.io/storybook)) and Figma design resources. The - Design System will make it easy to design and build plugins that are - consistent across the platform -- supporting both developers and designers. +* **[Improved Kubernetes plugin](https://github.com/spotify/backstage/issues/2857)** - + Native support for Kubernetes, making it easier for developers to see and + manage their services running in k8s. -- Further improvements to platform documentation - -### Plugins - -Building and maintaining [plugins](https://backstage.io/plugins) is the work of -the entire Backstage community. - -A list of plugins that are in development is -[available here](https://github.com/spotify/backstage/issues?q=is%3Aissue+is%3Aopen+label%3Aplugin+sort%3Areactions-%2B1-desc). -We strongly recommend to upvote 👍 plugins you are interested in. This helps us -and the community prioritize what plugins to build. - -Are you missing a plugin for your favorite tool? Please -[suggest a new one](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME). -Chances are that someone will jump in and help build it. +- Further improvements to platform documentation. Examples include a Golden Path + for plugin development. ### Future work 🔮 @@ -113,8 +96,25 @@ Chances are that someone will jump in and help build it. query. Plugins can easily query this API as well as extend the model where needed. +### Plugins + +Building and maintaining [plugins](https://backstage.io/plugins) is the work of +the entire Backstage community. + +A list of plugins that are in development is +[available here](https://github.com/spotify/backstage/issues?q=is%3Aissue+is%3Aopen+label%3Aplugin+sort%3Areactions-%2B1-desc). +We strongly recommend to upvote 👍 plugins you are interested in. This helps us +and the community prioritize what plugins to build. + +Are you missing a plugin for your favorite tool? Please +[suggest a new one](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME). +Chances are that someone will jump in and help build it. + ### Completed milestones ✅ +- [Kubernetes plugin - v1](https://github.com/spotify/backstage/tree/master/plugins/kubernetes) +- [Helm charts](https://github.com/spotify/backstage/tree/master/contrib/chart/backstage) +- [Backstage Design System 💅](https://backstage.io/blog/2020/09/30/backstage-design-system) - [Cost Insights plugin 💸](https://engineering.atspotify.com/2020/09/29/managing-clouds-from-the-ground-up-cost-engineering-at-spotify/) - [Donate Backstage to the CNCF 🎉](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox) - [TechDocs v1](https://backstage.io/blog/2020/09/08/announcing-tech-docs) diff --git a/docs/plugins/call-existing-api.md b/docs/plugins/call-existing-api.md index 14ea4c1f5a..3fff90c3f6 100644 --- a/docs/plugins/call-existing-api.md +++ b/docs/plugins/call-existing-api.md @@ -88,7 +88,7 @@ The proxy is powered by the `http-proxy-middleware` package. See [Proxying](proxying.md) for a full description of its configuration options. Internally at Spotify, the proxy option has been the overwhelmingly most popular -choice for plugin makers. Since we have DNS based service discovery in place and +choice for plugin makers. Since we have DNS-based service discovery in place and a microservices framework that made it trivial to expose plain HTTP, it has been a matter of just adding a few lines of Backstage config to get the benefit of being easily and robustly reachable from users' web browsers as well. diff --git a/docs/plugins/proxying.md b/docs/plugins/proxying.md index 3d9aa90447..f55b4d9229 100644 --- a/docs/plugins/proxying.md +++ b/docs/plugins/proxying.md @@ -57,6 +57,15 @@ is also possible to limit the forwarded HTTP methods with the configuration `allowedMethods`, for example `allowedMethods: ['GET']` to enforce read-only access. +By default, the proxy will only forward safe HTTP request headers to the target. +Those are based on the headers that are considered safe for CORS and includes +headers like `content-type` or `last-modified`, as well as all headers that are +set by the proxy. If the proxy should forward other headers like +`authorization`, this must be enabled by the `allowedHeaders` config, for +example `allowedHeaders: ['Authorization']`. This should help to not +accidentally forward confidential headers (`cookie`, `X-Auth-Request-User`) to +third-parties. + If the value is a string, it is assumed to correspond to: ```yaml diff --git a/docs/plugins/structure-of-a-plugin.md b/docs/plugins/structure-of-a-plugin.md index ee0a27cde2..0f11896f7a 100644 --- a/docs/plugins/structure-of-a-plugin.md +++ b/docs/plugins/structure-of-a-plugin.md @@ -73,7 +73,7 @@ export const plugin = createPlugin({ ``` This is where the plugin is created and where it hooks into the app by declaring -what component should be shown on what url. See reference docs for +what component should be shown on what URL. See reference docs for [createPlugin](../reference/createPlugin.md) or [router](../reference/createPlugin-router.md). @@ -101,11 +101,11 @@ Backstage CLI. ## Talking to the outside world -If your plugin needs to communicate with services outside the backstage +If your plugin needs to communicate with services outside the Backstage environment you will probably face challenges like CORS policies and/or backend-side authorization. To smooth this process out you can use proxy - -either the one you already have (like nginx/haproxy/etc) or the proxy-backend -plugin that we provide for the backstage backend. +either the one you already have (like Nginx, HAProxy, etc.) or the proxy-backend +plugin that we provide for the Backstage backend. [Read more](https://github.com/spotify/backstage/blob/master/plugins/proxy-backend/README.md) [Back to Getting Started](../README.md) diff --git a/docs/plugins/testing.md b/docs/plugins/testing.md index c6e1599786..e60b5fa8b7 100644 --- a/docs/plugins/testing.md +++ b/docs/plugins/testing.md @@ -248,15 +248,15 @@ Testing an API involves verifying four things: ### Mocking API Calls -[Mocking in jest](https://facebook.github.io/jest/docs/en/mock-functions.html) +[Mocking in Jest](https://facebook.github.io/jest/docs/en/mock-functions.html) involves wrapping existing functions (like an API call function) with an alternative. For example: -**./Api.js** +**`./MyApi.js`** -``` +```js export { fetchSomethingFromServer: () => { // Live production call to a URI. Must be avoided during testing! @@ -265,9 +265,9 @@ export { }; ``` -**./\_\_mocks\_\_/Api.js** +**`./\_\_mocks\_\_/MyApi.js`** -``` +```js export { fetchSomethingFromServer: () => { // Simulate a production call, but avoid jest and just use a promise @@ -276,16 +276,16 @@ export { } ``` -**./Api.test.js** +**`./MyApi.test.js`** -``` +```js /* eslint-disable import/first */ jest.mock('./MyApi'); // Instruct Jest to swap all future imports of './MyApi.js' to './__mocks__/MyApi.js' import MyApi from './MyApi'; // Will actually return the contents of the file in the __mocks__ folder now -it ('loads data', (done) => { +it('loads data', done => { MyApi.fetchSomethingFromServer().then(result => { expect(result).toBe('some result object simulating server data here'); done(); diff --git a/docs/support/project-structure.md b/docs/support/project-structure.md new file mode 100644 index 0000000000..9720c4db3e --- /dev/null +++ b/docs/support/project-structure.md @@ -0,0 +1,237 @@ +--- +id: project-structure +title: Backstage Project Structure +description: + Introduction to files and folders in the Backstage Project repository +--- + +Backstage is a complex project, and the GitHub repository contains many +different files and folders. This document aims to clarify what purpose of those +files and folders are. + +## General purpose files and folders + +In the project root, there are a set of files and folders which are not part of +the project as such, and may or may not be familiar to someone looking through +the code. + +- [`.changeset/`](https://github.com/spotify/backstage/tree/master/.changeset) - + This folder contains files outlining which changes occurred in the project + since the last release. These files are added manually, but managed by + [changesets](https://github.com/atlassian/changesets) and will be removed at + every new release. They are essentially building-blocks of a CHANGELOG. + +- [`.github/`](https://github.com/spotify/backstage/tree/master/.github) - + Standard GitHub folder. It contains - amongst other things - our workflow + definitions and templates. Worth noting is the + [styles](https://github.com/spotify/backstage/tree/master/.github/styles) + folder which is used for a markdown spellchecker. + +- [`.yarn/`](https://github.com/spotify/backstage/tree/master/.yarn) - Backstage + ships with it's own `yarn` implementation. This allows us to have better + control over our `yarn.lock` file and hopefully avoid problems due to yarn + versioning differences. + +- [`docker/`](https://github.com/spotify/backstage/tree/master/docker) - Files + related to our root Dockerfile. We are planning to refactor this, so expect + this folder to be moved in the future. + +- [`contrib/`](https://github.com/spotify/backstage/tree/master/contrib) - + Collection of examples or resources provided by the community. We really + appreciate contributions in here and encourage them being kept up to date. + +- [`docs/`](https://github.com/spotify/backstage/tree/master/docs) - This is + where we keep all of our documentation Markdown files. These ends up on + http://backstage.io/docs. Just keep in mind that changes to the + [`sidebars.json`](https://github.com/spotify/backstage/blob/master/microsite/sidebars.json) + file may be needed as sections are added/removed. + +- [`.editorconfig`](https://github.com/spotify/backstage/tree/master/.editorconfig) - + A configuration file used by most common code editors. + +- [`.imgbotconfig`](https://github.com/spotify/backstage/tree/master/.imgbotconfig) - + Configuration for a [bot](https://imgbot.net/) + +## Monorepo packages + +Every folder in both `packages/` and `plugins/` is within our monorepo setup, as +defined in +[`package.json`](https://github.com/spotify/backstage/blob/master/package.json): + +```json + "workspaces": { + "packages": [ + "packages/*", + "plugins/*" + ] + }, +``` + +Let's look at them individually. + +### `packages/` + +These are all the packages that we use within the project. [Plugins](#plugins) +are separated out into their own folder, see further down. + +- [`app/`](https://github.com/spotify/backstage/tree/master/packages/app) - This + is our take on how an App could look like, bringing together a set of packages + and plugins into a working Backstage App. This is not a published package, and + the main goals are to provide a demo of what an App could look like and to + enable local development. + +- [`backend/`](https://github.com/spotify/backstage/tree/master/packages/backend) - + Every standalone Backstage project will have both an `app` _and_ a `backend` + package. The `backend` uses plugins to construct a working backend that the + frontend (`app`) can use. + +- [`backend-common/`](https://github.com/spotify/backstage/tree/master/packages/backend-common) - + There are no "core" packages in the backend. Instead we have `backend-common` + which contains helper middleware and other utils. + +- [`catalog-model/`](https://github.com/spotify/backstage/tree/master/packages/catalog-model) - + You can consider this to be a library for working with the catalog of sorts. + It contains the definition of an + [Entity](https://backstage.io/docs/features/software-catalog/references#docsNav), + as well as validation and other logic related to it. This package can be used + in both the frontend and the backend. + +- [`cli/`](https://github.com/spotify/backstage/tree/master/packages/cli) - One + of the biggest packages in our project, the `cli` is used to build, serve, + diff, create-plugins and more. In the early days of this project, we started + out with calling tools directly - such as `eslint` - through `package.json`. + But as it was tricky to have a good development experience around that when we + change named tooling, we opted for wrapping those in our own cli. That way + everything looks the same in `package.json`. Much like + [react-scripts](https://github.com/facebook/create-react-app/tree/master/packages/react-scripts). + +- [`cli-common/`](https://github.com/spotify/backstage/tree/master/packages/cli-common) - + This package mainly handles path resolving. It is a separate package to reduce + bugs in [cli](https://github.com/spotify/backstage/tree/master/packages/cli). + We also want as few dependencies as possible to reduce download time when + running the cli which is another reason this is a separate package. + +- [`config/`](https://github.com/spotify/backstage/tree/master/packages/config) - + The way we read configuration data. This package can take a bunch of config + objects and merge them together. + [app-config.yaml](https://github.com/spotify/backstage/blob/master/app-config.yaml) + is an example of an config object. + +- [`config-loader/`](https://github.com/spotify/backstage/tree/master/packages/config-loader) - + This package is used to read config objects. It does not know how to merge, + but only reads files and passes them on to the config. As this part is only + used by the backend, we chose to separate `config` and `config-loader` into + two different packages. + +- [`core/`](https://github.com/spotify/backstage/tree/master/packages/core) - + This package contains our visual React components, some of which you can find + in + [plugin examples](https://backstage.io/storybook/?path=/story/plugins-examples--plugin-with-data). + Apart from that it re-exports everything from [`core-api`] so that users only + need to rely on one package. + +- [`core-api/`](https://github.com/spotify/backstage/tree/master/packages/core-api) - + This package contains APIs and definitions of such. It is it's own package + because we needed to split our `test-utils` package. It's an implementation + detail that we try to hide from our users, and no one should have to depend on + it directly. + +- [`test-utils/`](https://github.com/spotify/backstage/tree/master/packages/test-utils) - + This package contains specific testing facilities used when testing + `core-api`. + +- [`test-utils-core/`](https://github.com/spotify/backstage/tree/master/packages/test-utils-core) - + This package contains more general purpose testing facilities for testing a + Backstage App. + +- [`create-app/`](https://github.com/spotify/backstage/tree/master/packages/create-app) - + An CLI to specifically scaffold a new Backstage App. It does so by using a + [template](https://github.com/spotify/backstage/tree/master/packages/create-app/templates/default-app). + +- [`dev-utils/`](https://github.com/spotify/backstage/tree/master/packages/dev-utils) - + Helps you setup a plugin for isolated development so that it can be served + separately. + +- [`docgen/`](https://github.com/spotify/backstage/tree/master/packages/docgen) - + Uses the + [Typescript Compiler API](https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API) + to read out definitions and generate documentation for it. + +- [`e2e-test/`](https://github.com/spotify/backstage/tree/master/packages/e2e-test) - + Another CLI that can be run to try out what would happen if you built all the + packages, publish them, created a new app, and the run it. CI uses this for + e2e-tests. + +- [`storybook/`](https://github.com/spotify/backstage/tree/master/packages/storybook) - + This folder contains only the storybook config. Stories are within the core + package. The Backstage Storybook is found + [here](https://backstage.io/storybook) + +- [`techdocs-cli/`](https://github.com/spotify/backstage/tree/master/packages/techdocs-cli) - + Used for verifying TechDocs locally. + +- [`techdocs-container/`](https://github.com/spotify/backstage/tree/master/packages/techdocs-container) - + Used by the `techdocs-cli` + +- [`test-utils-core/`](https://github.com/spotify/backstage/tree/master/packages/test-utils-core) + +- [`test-utils/`](https://github.com/spotify/backstage/tree/master/packages/test-utils) + +- [`theme/`](https://github.com/spotify/backstage/tree/master/packages/theme) - + Holds the Backstage Theme. + +### `plugins/` + +Most of the functionality of a Backstage App comes from plugins. Even core +features can be plugins, take the +[catalog](https://github.com/spotify/backstage/tree/master/plugins/catalog) as +an example. + +We can categorize plugins into three different types; **Frontend**, **Backend** +and **GraphQL**. We differentiate these types of plugins when we name them, with +a dash-suffix. `-backend` means it’s a backend plugin and so on. + +One reason for splitting a plugin is because of to it's dependencies. Another +reason is for clear separation of concerns. + +Take a look at our [Plugin Gallery](https://backstage.io/plugins) or browse +through the +[`plugins/`](https://github.com/spotify/backstage/tree/master/plugins) folder. + +## Packages outside of the monorepo + +For convenience we include packages in our project that are not part of our +monorepo setup. + +- [`microsite/`](https://github.com/spotify/backstage/blob/master/microsite) - + This folder contains the source code for backstage.io. It is built with + [Docusaurus](https://docusaurus.io/). This folder is not part of the monorepo + due to dependency reasons. Look at the + [README](https://github.com/spotify/backstage/blob/master/microsite/README.md) + for instructions on how to run it locally. + +## Root files specifically used by the `app` + +These files are kept in the root of the project mostly by historical reasons. +Some of these files may be subject to be moved out of the root sometime in the +future. + +- [`.npmrc`](https://github.com/spotify/backstage/tree/master/.npmrc) - It's + common for companies to have their own npm registry, this files makes sure + that this folder use the public registry. + +- [`.vale.ini`](https://github.com/spotify/backstage/tree/master/.vale.ini) - + [Spell checker](https://github.com/errata-ai/vale) for Markdown files. + +- [`.yarnrc`](https://github.com/spotify/backstage/tree/master/.yarnrc) - + Enforces "our" version of Yarn. + +- [`app-config.yaml`](https://github.com/spotify/backstage/tree/master/app-config.yaml) - + Configuration for the app, both frontend and backend. + +- [`catalog-info.yaml`](https://github.com/spotify/backstage/tree/master/catalog-info.yaml) - + Description of Backstage in the Backstage Entity format. + +- [`lerna.json`](https://github.com/spotify/backstage/tree/master/lerna.json) - + [Lerna](https://github.com/lerna/lerna) monorepo config. We are using + `yarn workspaces`, so this will only be used for executing scripts. diff --git a/docs/overview/support.md b/docs/support/support.md similarity index 100% rename from docs/overview/support.md rename to docs/support/support.md diff --git a/docs/tutorials/journey.md b/docs/tutorials/journey.md index 908d7fc61b..7627920a75 100644 --- a/docs/tutorials/journey.md +++ b/docs/tutorials/journey.md @@ -179,7 +179,7 @@ const onSave = async () => { ``` Now it's much simpler for users to change the theme tune, as they no longer need -to go look up a track ID and edit a yaml file. Instead, they can now stay inside +to go look up a track ID and edit a YAML file. Instead, they can now stay inside Backstage and search for the track and request the change from there. In addition, the requested change can be reviewed by the regular process of each organization. @@ -239,12 +239,12 @@ hits merge. # 8. Attack of the Clones Sam just released v1.8.4 of the plugin, and at this point it's so popular that a -couple of other plugins has started depending on the `sam.wise/spotify-track-id` -annotation. One such plugin being the `spotify-album-art` plugin that can -display the album art of the theme tune as the background of the entity header. -Sam thinks it's all pretty cool, but doesn't like that the annotation that was -once an internal concern of the plugin is now becoming a standard in the -community. +couple of other plugins have started depending on the +`sam.wise/spotify-track-id` annotation. One such plugin being the +`spotify-album-art` plugin that can display the album art of the theme tune as +the background of the entity header. Sam thinks it's all pretty cool, but +doesn't like that the annotation that was once an internal concern of the plugin +is now becoming a standard in the community. In order to standardize the annotation in Backstage, Sam submits a Pull Request to the Backstage Core repo. The request suggests a new well-known metadata diff --git a/docs/tutorials/quickstart-app-auth.md b/docs/tutorials/quickstart-app-auth.md index 8f6b35617b..1dcca9d7e0 100644 --- a/docs/tutorials/quickstart-app-auth.md +++ b/docs/tutorials/quickstart-app-auth.md @@ -7,11 +7,11 @@ title: Monorepo App Setup With Authentication
-> This document takes you through setting up a backstage app that runs in your +> This document takes you through setting up a Backstage app that runs in your > own environment. It starts with a skeleton install and verifying of the > monorepo's functionality. Next, GitHub authentication is added and tested. > -> This document assumes you have NodeJS 12 active along with Yarn and Python. +> This document assumes you have Node.js 12 active along with Yarn and Python. > Please note, that at the time of this writing, the current version is > 0.1.1-alpha.21. This guide can still be used with future versions, just, > verify as you go. If you run into issues, you can compare your setup with mine diff --git a/docs/tutorials/quickstart-app-plugin.md b/docs/tutorials/quickstart-app-plugin.md index 9f571b0c9a..daf76aa1cd 100644 --- a/docs/tutorials/quickstart-app-plugin.md +++ b/docs/tutorials/quickstart-app-plugin.md @@ -20,7 +20,7 @@ title: Adding Custom Plugin to Existing Monorepo App > functionality, extend the Sidebar to make our life easy. Finally, we add > custom code to display GitHub repository information. > -> This document assumes you have NodeJS 12 active along with Yarn and Python. +> This document assumes you have Node.js 12 active along with Yarn and Python. > Please note, that at the time of this writing, the current version is > 0.1.1-alpha.21. This guide can still be used with future versions, just, > verify as you go. If you run into issues, you can compare your setup with mine @@ -161,7 +161,7 @@ export default ExampleFetchComponent; # The Graph Model -GitHub has a graphql API available for interacting. Let's start by adding our +GitHub has a GraphQL API available for interacting. Let's start by adding our basic repository query 1. Add the query const statement outside ExampleFetchComponent diff --git a/lerna.json b/lerna.json index 7d514abb97..5871423f78 100644 --- a/lerna.json +++ b/lerna.json @@ -2,5 +2,5 @@ "packages": ["packages/*", "plugins/*"], "npmClient": "yarn", "useWorkspaces": true, - "version": "0.1.1-alpha.24" + "version": "0.1.1-alpha.26" } diff --git a/microsite/blog/2020-09-30-plugin-marketplace.md b/microsite/blog/2020-09-30-plugin-marketplace.md index b7a799097f..0b96abbc60 100644 --- a/microsite/blog/2020-09-30-plugin-marketplace.md +++ b/microsite/blog/2020-09-30-plugin-marketplace.md @@ -40,4 +40,4 @@ We are really excited to see all the amazing plugins that have already been buil What plugins would you like to see in the Plugin Marketplace? [Tell us](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME)! -_Special shout-out to community member [Iain Billett](https://github.com/iain-b) from Roadie for helping build and contribute the [Plugin Marketplace page](https://backstage.io/plugins) (as his first PR no less!)._ +_Special shout-out to community member [Iain Billett](https://github.com/iain-b) from [Roadie](https://roadie.io) for helping build and contribute the [Plugin Marketplace page](https://backstage.io/plugins) (as his first PR no less!)._ diff --git a/microsite/blog/2020-10-22-cost-insights-plugin.md b/microsite/blog/2020-10-22-cost-insights-plugin.md new file mode 100644 index 0000000000..421ebacdd2 --- /dev/null +++ b/microsite/blog/2020-10-22-cost-insights-plugin.md @@ -0,0 +1,79 @@ +--- +title: New Cost Insights plugin: The engineer’s solution to taming cloud costs +author: Janisa Anandamohan +authorURL: https://twitter.com/janisa_a +--- + +How did Spotify save millions on cloud costs within a matter of months?? We made cost optimization just another part of the daily development process. Our newly open sourced [Cost Insights plugin](https://github.com/spotify/backstage/tree/master/plugins/cost-insights) makes a team’s cloud costs visible — and actionable — right inside Backstage. So engineers can see the impact of their cloud usage (down to a product and resource level) and make optimizations wherever and whenever it makes sense. By managing cloud costs from the ground up, you can make smarter decisions that let you continue to build and scale quickly, without wasting resources. + + + +Are we turning engineers into accountants? Nope, we’re just letting engineers do what they do best, in the place that feels natural to them: inside Backstage. + + + +## Why put a cost management tool in the hands of engineers? + +Engineers are closest to the metal in terms of knowing why a specific feature, product, or service is using cloud resources. So they’re in the best position to understand how costs impact ongoing development (and vice versa). + +If you manage costs top-down from a 10,000-foot view of your cloud infrastructure, you’re likely making decisions far removed from products, especially in larger organizations. Set a broad cost-cutting goal, and you could be creating unintended consequences — curtailing spending at the expense of growth or experimentation. + +## Ground-level intelligence, data-driven solutions + +Our hypothesis at Spotify was, if you bring spending data into an engineer’s everyday development workflow, they’ll naturally look for cost optimizations just like they look for any other optimization. And the cost optimizations will be more efficient and effective, because the decisions are informed at the ground level. + +The problem is that most cloud platforms don’t provide cost data at a granular enough level to make those decisions. And the bigger your organization (say, two-thousand-microservices and four-thousand-data-pipelines big, like Spotify), then the less you can attribute these large, fuzzy numbers to the right team, let alone a shipping product or internal service. + +That’s where Cost Insights comes in. Instead of making cost management and product development separate departments on the org chart, Backstage brings them together — with a level of detail and specificity engineers relate and respond to. + +## How to turn dollars into sense + +It’s not enough to make costs visible. To be useful, the numbers need to be relevant, relatable, and actionable. In other words, not just cost information, but insights. There are several ways the plugin puts data from your cloud provider in a more helpful context. + +### Use business metrics to evaluate costs + +Cost Insights will show you trends at a glance and also let you compare costs quarter over quarter. More importantly, you can also evaluate costs against business metrics that you care most about. In the example below, should the upward slope shown in the first screen be cause for worry? Perhaps not — if you switch views, you’ll see that cost per daily average user (DAU) is actually going down. Exactly what you hope to see as you scale. + +![Comparing costs to DAU](assets/20-10-22/cost-insights-1-dau.gif) +_(Note: Screens are examples; they do not show real data.)_ + +### Illustrate costs with relatable, real-world comparisons + +In addition to dollar amounts, Cost Insights allows teams to visualize and convert cost overages into more relatable terms. In the example below, we equate the growth in costs for virtual machine instances (100% increase) to developer time spent (about 1 engineer). We use this particular comparison in the plugin because we found it resonated with our own engineers — providing a useful perspective for spending increases. You can configure what the “cost of an engineer” means to your organization. Or engineers can build in their own comparisons — cups of coffee, carbon offset credits, electric luxury vehicles — whatever makes costs more tangible for them. + +![Cost growth as engineering time](assets/20-10-22/cost-insights-2-engineer.png) +_(Note: Screens are examples; they do not show real data.)_ + +### Tie spending to specific products and resources + +The more detailed the cost data, the more relevant, actionable, and helpful it is. Cost Insights allows you to attribute costs to products and resources in a way that makes sense to your engineers. For example, here we see a breakdown of data processing costs by individual pipelines. This allows your team to target optimizations more precisely. + +![Data Processing costs by pipeline](assets/20-10-22/cost-insights-3-data.png) +_(Note: Screens are examples; they do not show real data.)_ + +## Driving down costs without slowing down development + +When it comes to cutting costs, we actually want to guard against over-optimization. Growth and costs can go hand in hand. The trick is knowing when one is out of balance and needs addressing. Our product highlights when there’s been a large increase in spending, so that engineers are thinking about cost only when they must and aren’t distracted from their set goals and priorities. + +Engineers can then determine for themselves if the time invested in an optimization was valuable compared to the costs saved. Cost Insights puts the decision in our engineers’ hands for them to choose when to focus on growth efforts and when to focus on cost. Control, as ever, remains with our developers, where we think it belongs. + +## Getting started + +You can begin working with the Cost Insights plugin today on [GitHub](https://github.com/spotify/backstage/tree/master/plugins/cost-insights). We include an example client with static data in the expected format. The `CostInsightsApi` should talk with a cloud billing backend that aggregates billing data from your cloud provider. + +The current release of Cost Insights includes: + +- Daily cost graph by team or billing account +- Cost comparisons against configurable business metrics (including an option for Daily Active Users) +- Insights panels — configurable for the cloud products your company uses +- Cost alerts and recommendations +- Selectable time periods for month-over-month or quarter-over-quarter comparisons +- Conversion of cost growth into “cost of average engineer” to help optimization trade-off decisions + +Our hope is to help other companies translate their cloud cost in a relatable way for their engineers to better understand their impact and accurately identify their opportunities for optimizations. + +And if you’re interested in contributing to our outstanding issues, you can find them in the issues queue, filtered under the [‘cost-insights’ label](https://github.com/spotify/backstage/labels/cost-insights). + +## Ready for DevSecCostOpsPlus (and whatever’s next) + +There’s DevOps, there’s DevSecOps, and then there’s Backstage: one frontend for all your infrastructure. From building, testing, and deploying to monitoring and security — Backstage helps you manage your entire tech organization and provides a seamless developer experience for engineers, from end to end to end. And now that also extends to cost management for your cloud infrastructure and tooling. Happy building and [happy optimizing](https://github.com/spotify/backstage/tree/master/plugins/cost-insights). diff --git a/microsite/blog/assets/20-10-22/cost-insights-1-dau.gif b/microsite/blog/assets/20-10-22/cost-insights-1-dau.gif new file mode 100644 index 0000000000..df9396439d Binary files /dev/null and b/microsite/blog/assets/20-10-22/cost-insights-1-dau.gif differ diff --git a/microsite/blog/assets/20-10-22/cost-insights-2-engineer.png b/microsite/blog/assets/20-10-22/cost-insights-2-engineer.png new file mode 100644 index 0000000000..1e9293f5c1 Binary files /dev/null and b/microsite/blog/assets/20-10-22/cost-insights-2-engineer.png differ diff --git a/microsite/blog/assets/20-10-22/cost-insights-3-data.png b/microsite/blog/assets/20-10-22/cost-insights-3-data.png new file mode 100644 index 0000000000..941f0487da Binary files /dev/null and b/microsite/blog/assets/20-10-22/cost-insights-3-data.png differ diff --git a/microsite/core/Footer.js b/microsite/core/Footer.js index 8e3c4c086d..1bebf2f399 100644 --- a/microsite/core/Footer.js +++ b/microsite/core/Footer.js @@ -1,8 +1,17 @@ -/** - * Copyright (c) 2017-present, Facebook, Inc. +/* + * Copyright 2020 Backstage Project Authors. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ const React = require('react'); @@ -82,15 +91,6 @@ class Footer extends React.Component { )} - - - Made with at {this.props.config.organizationName} -

{this.props.config.copyright}

); diff --git a/microsite/data/plugins/aws-lambda.yaml b/microsite/data/plugins/aws-lambda.yaml new file mode 100644 index 0000000000..7fa276f444 --- /dev/null +++ b/microsite/data/plugins/aws-lambda.yaml @@ -0,0 +1,9 @@ +--- +title: AWS Lambda +author: roadie.io +authorUrl: https://roadie.io +category: Monitoring +description: View AWS Lambda functions for your components in Backstage. +documentation: https://roadie.io/backstage/plugins/aws-lambda +iconUrl: https://roadie.io/static/77f62f79e27ae8565496e4df7eef8be5/45f2b/logo.png +npmPackageName: '@roadiehq/backstage-plugin-aws-lambda' diff --git a/microsite/data/plugins/github-insights.yaml b/microsite/data/plugins/github-insights.yaml new file mode 100644 index 0000000000..8ac8321da0 --- /dev/null +++ b/microsite/data/plugins/github-insights.yaml @@ -0,0 +1,9 @@ +--- +title: GitHub Insights +author: roadie.io +authorUrl: https://roadie.io +category: Monitoring +description: View GitHub Insights for your components in Backstage. +documentation: https://roadie.io/backstage/plugins/github-insights +iconUrl: https://roadie.io/static/2ad5123c425908efde0c922d707e737b/06c84/code-icon.png +npmPackageName: '@roadiehq/backstage-plugin-github-insights' diff --git a/microsite/data/plugins/security-insights.yaml b/microsite/data/plugins/security-insights.yaml new file mode 100644 index 0000000000..1cbcfbc3aa --- /dev/null +++ b/microsite/data/plugins/security-insights.yaml @@ -0,0 +1,9 @@ +--- +title: Security Insights +author: roadie.io +authorUrl: https://roadie.io/ +category: Security +description: View Security Insights for your components in Backstage. +documentation: https://roadie.io/backstage/plugins/security-insights +iconUrl: https://roadie.io/static/7f13bb8d861d8dedc5112fb939d215f9/351f2/GitHub-Mark-Light-120px-plus.png +npmPackageName: '@roadiehq/backstage-plugin-security-insights' diff --git a/microsite/package.json b/microsite/package.json index 335ada7212..a84364c214 100644 --- a/microsite/package.json +++ b/microsite/package.json @@ -14,8 +14,8 @@ "rename-version": "docusaurus-rename-version" }, "devDependencies": { - "@spotify/prettier-config": "^8.0.0", - "docusaurus": "^2.0.0-alpha.65", + "@spotify/prettier-config": "^9.0.0", + "docusaurus": "^2.0.0-alpha.66", "js-yaml": "^3.14.0", "prettier": "^2.0.5" }, diff --git a/microsite/pages/en/demos.js b/microsite/pages/en/demos.js index c6657c6a31..63c15ab698 100644 --- a/microsite/pages/en/demos.js +++ b/microsite/pages/en/demos.js @@ -78,7 +78,41 @@ const Background = props => { - + + + + Control cloud costs + + How do you control cloud costs while maintaining the speed and + independence of your development teams? With the{' '} + Cost Insights plugin{' '} + for Backstage, managing cloud costs becomes just another part of + an engineer’s daily development process. They get a clear view of + their spending — and can decide for themselves how they want to + optimize it. Learn more about the{' '} + + Cost Insights plugin + + . + + + Watch now + + + + + + + + + @@ -96,7 +130,7 @@ const Background = props => { . - + Watch now diff --git a/microsite/pages/en/plugins.js b/microsite/pages/en/plugins.js index a8255bcd0d..36957c2b4e 100644 --- a/microsite/pages/en/plugins.js +++ b/microsite/pages/en/plugins.js @@ -16,9 +16,8 @@ const { const pluginsDirectory = require('path').join(process.cwd(), 'data/plugins'); const pluginMetadata = fs .readdirSync(pluginsDirectory) - .map(file => - yaml.safeLoad(fs.readFileSync(`./data/plugins/${file}`, 'utf8')), - ); + .map(file => yaml.safeLoad(fs.readFileSync(`./data/plugins/${file}`, 'utf8'))) + .sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase())); const truncate = text => text.length > 170 ? text.substr(0, 170) + '...' : text; @@ -44,7 +43,7 @@ const Plugins = () => ( - + {pluginMetadata.map( ({ iconUrl, @@ -57,26 +56,25 @@ const Plugins = () => ( }) => (
- {title} -

{title}

-

- by {author} -

- {category} +
+ {title} +
+
+

{title}

+

+ by {author} +

+ {category} +

{truncate(description)}

- - - - Explore - - - +
), )} diff --git a/microsite/sidebars.json b/microsite/sidebars.json index 7081e2bb1c..64fdd2f420 100644 --- a/microsite/sidebars.json +++ b/microsite/sidebars.json @@ -28,6 +28,7 @@ "label": "Deployment", "ids": [ "getting-started/deployment-k8s", + "getting-started/deployment-helm", "getting-started/deployment-other" ] } @@ -163,7 +164,7 @@ "architecture-decisions/adrs-adr009" ], "Contribute": ["../CONTRIBUTING"], - "Support": ["overview/support"], + "Support": ["support/support", "support/project-structure"], "FAQ": ["FAQ"] } } diff --git a/microsite/siteConfig.js b/microsite/siteConfig.js index d034321d6c..06ae8453a0 100644 --- a/microsite/siteConfig.js +++ b/microsite/siteConfig.js @@ -60,7 +60,7 @@ const siteConfig = { /* path to images for header/footer */ // headerIcon: "img/android-chrome-192x192.png", footerIcon: 'img/android-chrome-192x192.png', - favicon: 'img/favicon.svg', + favicon: 'img/favicon.ico', /* Colors for website */ colors: { @@ -78,7 +78,7 @@ const siteConfig = { }, // This copyright info is used in /core/Footer.js and blog RSS/Atom feeds. - copyright: `Copyright © ${new Date().getFullYear()} Spotify AB`, + copyright: `Copyright © ${new Date().getFullYear()} Backstage Project Authors. All rights reserved. The Linux Foundation has registered trademarks and uses trademarks. For a list of trademarks of The Linux Foundation, please see our Trademark Usage page: https://www.linuxfoundation.org/trademark-usage`, highlight: { // Highlight.js theme to use for syntax highlighting in code blocks. diff --git a/microsite/static/css/custom.css b/microsite/static/css/custom.css index 738478724f..22855a2b4d 100644 --- a/microsite/static/css/custom.css +++ b/microsite/static/css/custom.css @@ -15,9 +15,6 @@ table tr:nth-child(2n) { background-color: #2b2b2b; } -@media only screen and (min-device-width: 360px) and (max-device-width: 736px) { -} - @media only screen and (min-width: 1024px) and (max-width: 1500px) { /* Experience */ .content-experience { @@ -857,7 +854,6 @@ code { position: relative; padding-top: 75%; width: 100%; - /* border: 1px dotted #f00; */ } .Block__Graphic { @@ -1084,3 +1080,17 @@ code { margin-bottom: 40px; margin-top: 20px; } + +.nav-footer .copyright { + width: 600px; + color: #fff; + margin: 0 auto; + font-size: 10pt; +} + +@media only screen and (max-width: 485px) { + .nav-footer .copyright { + width: auto; + margin: 0 1.5em; + } +} diff --git a/microsite/static/css/plugins.css b/microsite/static/css/plugins.css index 9a8bbafa46..8a0d843dc9 100644 --- a/microsite/static/css/plugins.css +++ b/microsite/static/css/plugins.css @@ -6,7 +6,7 @@ flex-direction: column; } -.grid { +.PluginGrid { display: grid; grid-gap: 1rem; grid-template-columns: repeat(4, 1fr); @@ -15,17 +15,23 @@ } @media (max-width: 1200px) { - .grid { + .PluginGrid { grid-template-columns: repeat(3, 1fr); } } @media only screen and (max-width: 815px) { - .grid { + .PluginGrid { grid-template-columns: repeat(2, 1fr); } } +@media only screen and (max-width: 485px) { + .PluginGrid { + grid-template-columns: 1fr; + } +} + .PluginCard img { float: left; margin: 0px 16px 8px 0px; @@ -34,14 +40,32 @@ } .PluginCardHeader { + display: flex; + flex-direction: row; + align-items: center; max-height: fit-content; min-height: fit-content; } +.PluginCardImage { + width: 80px; + height: 80px; + margin-right: 16px; +} + +.PluginCardImage img { + width: 100%; + max-width: 100%; +} + .PluginCardTitle { color: white; vertical-align: top; - margin: 8px 0px 0px 16px; + margin: 8px 0 0; +} + +.PluginCardInfo { + flex: 1; } .PluginAddNewButton { @@ -50,11 +74,16 @@ right: 0px; } +@media only screen and (max-width: 485px) { + .PluginAddNewButton { + bottom: -4px; + } +} + .ButtonFilled { padding: 4px 8px; border-radius: 4px; color: #69ddc7; - margin-top: 36px; } .ButtonFilled:hover { @@ -62,7 +91,7 @@ background-color: transparent; } -.ChipOutlined { +.PluginCardChipOutlined { font-size: small; border-radius: 16px; padding: 2px 8px; @@ -70,11 +99,16 @@ color: #69ddc7; } -.PluginCardLink { +.PluginCardFooter { + display: flex; + justify-content: flex-end; + align-items: flex-end; + margin-top: auto; + min-height: 2em; +} + +.PluginCardFooter a { padding: 2px 8px; - position: absolute; - bottom: 0; - right: 0; } .PluginPageLayout { @@ -95,18 +129,13 @@ padding-top: 8px; } -.PluginCardFooter { - position: relative; - min-height: 2em; -} - -.Author, -.Author a { +.PluginCardAuthor, +.PluginCardAuthor a { margin-bottom: 0.25em; color: rgba(255, 255, 255, 0.6); } -.Author a:hover { +.PluginCardAuthor a:hover { color: white; } diff --git a/microsite/yarn.lock b/microsite/yarn.lock index 40e46c3545..b120cb2d47 100644 --- a/microsite/yarn.lock +++ b/microsite/yarn.lock @@ -959,10 +959,10 @@ resolved "https://registry.npmjs.org/@sindresorhus/is/-/is-0.7.0.tgz#9a06f4f137ee84d7df0460c1fdb1135ffa6c50fd" integrity sha512-ONhaKPIufzzrlNbqtWFFd+jlnemX6lJAgq9ZeiZtS7I1PIf/la7CW4m83rTXRnVnsMbW2k56pGYu7AUFJD9Pow== -"@spotify/prettier-config@^8.0.0": - version "8.0.0" - resolved "https://registry.npmjs.org/@spotify/prettier-config/-/prettier-config-8.0.0.tgz#8b6c2bd579ddc54887155a0721fe04e96c89f7f2" - integrity sha512-so8w32ZV42CHWxOEXcBtbNO/hLXFrQNXVmhfzhUI6dVB9cq2xjRaiqu8GjFj8LvKbWpPj+S+KwTIS4aDVWqrFQ== +"@spotify/prettier-config@^9.0.0": + version "9.0.0" + resolved "https://registry.yarnpkg.com/@spotify/prettier-config/-/prettier-config-9.0.0.tgz#7b562d56573c6fc0094446fbc92b22bc318945dc" + integrity sha512-In1q0tIiqTYKAGe3KOHDcFDdZRFISyQeSeipeTHGfki23ebHRZcjxvqj5SSdBkw65D4VpSREMi0s9i5iJiMcTw== "@types/cheerio@^0.22.8": version "0.22.21" @@ -2233,10 +2233,10 @@ dir-glob@2.0.0: arrify "^1.0.1" path-type "^3.0.0" -docusaurus@^2.0.0-alpha.65: - version "2.0.0-alpha.65" - resolved "https://registry.yarnpkg.com/docusaurus/-/docusaurus-2.0.0-alpha.65.tgz#e2b84985529deb79797aff52aa39ffbe03cd8a20" - integrity sha512-OEnKbXLPy3EpbQA/Dj0kakB6fg/Qni1LORTIero+5Q5G0QT5OH4FAbBQOy3L1qQH0S5Bv18zESxX9Nvclg20ag== +docusaurus@^2.0.0-alpha.66: + version "2.0.0-alpha.66" + resolved "https://registry.yarnpkg.com/docusaurus/-/docusaurus-2.0.0-alpha.66.tgz#4dece48b838f773c4c973d9fe2546dd0bf2637cf" + integrity sha512-/HmRt3hEqpvZRdR2JRYKpwNUgalO14exxuwQu2vXW5eYzcKbQ922+3SxG7mF+LE8f7KOmgY+A3eS3SEyq+S3XA== dependencies: "@babel/core" "^7.9.0" "@babel/plugin-proposal-class-properties" "^7.8.3" diff --git a/mkdocs.yml b/mkdocs.yml index 4fbec4650d..8a4a78ddf1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -13,7 +13,6 @@ nav: - Getting started: - Getting Started: 'getting-started/index.md' - Running Backstage locally: 'getting-started/running-backstage-locally.md' - - Installation: 'getting-started/installation.md' - Local development: 'getting-started/development-environment.md' - Demo deployment: https://backstage-demo.roadie.io - Production deployments: @@ -23,6 +22,7 @@ nav: - Customize the look-and-feel of your App: 'getting-started/app-custom-theme.md' - Deployment scenarios: - Kubernetes: 'getting-started/deployment-k8s.md' + - Kubernetes and Helm: 'getting-started/deployment-helm.md' - Other: 'getting-started/deployment-other.md' - Features: - Software Catalog: @@ -107,7 +107,9 @@ nav: - ADR008 - Default Catalog File Name: 'architecture-decisions/adr008-default-catalog-file-name.md' - ADR009 - Entity References: 'architecture-decisions/adr009-entity-references.md' - Contribute: '../CONTRIBUTING.md' - - Support: 'overview/support.md' + - Support: + - 'support/support.md' + - 'support/project-structure.md' - FAQ: FAQ.md plugins: diff --git a/package.json b/package.json index b9c84a4d90..96e02e33f9 100644 --- a/package.json +++ b/package.json @@ -38,9 +38,10 @@ }, "version": "1.0.0", "devDependencies": { - "@changesets/cli": "2.10.2", + "@changesets/cli": "^2.11.0", "@spotify/eslint-config-oss": "^1.0.1", "@spotify/prettier-config": "^8.0.0", + "command-exists": "^1.2.9", "concurrently": "^5.2.0", "fs-extra": "^9.0.0", "husky": "^4.2.3", @@ -65,7 +66,7 @@ "prettier --write" ], "*.md": [ - "vale" + "node ./scripts/check-docs-quality" ] }, "jest": { diff --git a/packages/app/package.json b/packages/app/package.json index 20b9e24701..594c12b5e5 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,40 +1,42 @@ { "name": "example-app", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "private": true, "bundled": true, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/plugin-api-docs": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/plugin-circleci": "^0.1.1-alpha.24", - "@backstage/plugin-cloudbuild": "^0.1.1-alpha.24", - "@backstage/plugin-cost-insights": "^0.1.1-alpha.24", - "@backstage/plugin-explore": "^0.1.1-alpha.24", - "@backstage/plugin-gcp-projects": "^0.1.1-alpha.24", - "@backstage/plugin-github-actions": "^0.1.1-alpha.24", - "@backstage/plugin-gitops-profiles": "^0.1.1-alpha.24", - "@backstage/plugin-graphiql": "^0.1.1-alpha.24", - "@backstage/plugin-jenkins": "^0.1.1-alpha.24", - "@backstage/plugin-kubernetes": "^0.1.1-alpha.24", - "@backstage/plugin-lighthouse": "^0.1.1-alpha.24", - "@backstage/plugin-newrelic": "^0.1.1-alpha.24", - "@backstage/plugin-register-component": "^0.1.1-alpha.24", - "@backstage/plugin-rollbar": "^0.1.1-alpha.24", - "@backstage/plugin-scaffolder": "^0.1.1-alpha.24", - "@backstage/plugin-sentry": "^0.1.1-alpha.24", - "@backstage/plugin-tech-radar": "^0.1.1-alpha.24", - "@backstage/plugin-techdocs": "^0.1.1-alpha.24", - "@backstage/plugin-welcome": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/plugin-api-docs": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/plugin-circleci": "^0.1.1-alpha.26", + "@backstage/plugin-cloudbuild": "^0.1.1-alpha.26", + "@backstage/plugin-cost-insights": "^0.1.1-alpha.26", + "@backstage/plugin-explore": "^0.1.1-alpha.26", + "@backstage/plugin-gcp-projects": "^0.1.1-alpha.26", + "@backstage/plugin-github-actions": "^0.1.1-alpha.26", + "@backstage/plugin-gitops-profiles": "^0.1.1-alpha.26", + "@backstage/plugin-graphiql": "^0.1.1-alpha.26", + "@backstage/plugin-jenkins": "^0.1.1-alpha.26", + "@backstage/plugin-kubernetes": "^0.1.1-alpha.26", + "@backstage/plugin-lighthouse": "^0.1.1-alpha.26", + "@backstage/plugin-newrelic": "^0.1.1-alpha.26", + "@backstage/plugin-register-component": "^0.1.1-alpha.26", + "@backstage/plugin-rollbar": "^0.1.1-alpha.26", + "@backstage/plugin-scaffolder": "^0.1.1-alpha.26", + "@backstage/plugin-sentry": "^0.1.1-alpha.26", + "@backstage/plugin-tech-radar": "^0.1.1-alpha.26", + "@backstage/plugin-techdocs": "^0.1.1-alpha.26", + "@backstage/plugin-user-settings": "^0.1.1-alpha.26", + "@backstage/plugin-welcome": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@octokit/rest": "^18.0.0", - "@roadiehq/backstage-plugin-github-pull-requests": "^0.4.3", - "@roadiehq/backstage-plugin-travis-ci": "^0.2.3", + "@roadiehq/backstage-plugin-github-insights": "^0.2.7", + "@roadiehq/backstage-plugin-github-pull-requests": "^0.5.2", + "@roadiehq/backstage-plugin-travis-ci": "^0.2.5", "history": "^5.0.0", "prop-types": "^15.7.2", "react": "^16.12.0", diff --git a/packages/app/public/index.html b/packages/app/public/index.html index ea9208ca57..77e5c01e19 100644 --- a/packages/app/public/index.html +++ b/packages/app/public/index.html @@ -48,6 +48,23 @@ } <%= app.title %> + + <% if (app.googleAnalyticsTrackingId && typeof app.googleAnalyticsTrackingId + === 'string') { %> + + + <% } %> diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx index 667b14366f..81d08f58a9 100644 --- a/packages/app/src/App.tsx +++ b/packages/app/src/App.tsx @@ -33,6 +33,7 @@ import { Router as GraphiQLRouter } from '@backstage/plugin-graphiql'; import { Router as TechRadarRouter } from '@backstage/plugin-tech-radar'; import { Router as LighthouseRouter } from '@backstage/plugin-lighthouse'; import { Router as RegisterComponentRouter } from '@backstage/plugin-register-component'; +import { Router as SettingsRouter } from '@backstage/plugin-user-settings'; import { Route, Routes, Navigate } from 'react-router'; import { EntityPage } from './components/catalog/EntityPage'; @@ -81,6 +82,7 @@ const AppRoutes = () => ( path="/register-component" element={} /> + } /> {...deprecatedAppRoutes} ); diff --git a/packages/app/src/apis.ts b/packages/app/src/apis.ts index c129bebfa2..bd16cd74ef 100644 --- a/packages/app/src/apis.ts +++ b/packages/app/src/apis.ts @@ -26,17 +26,9 @@ import { } from '@backstage/plugin-graphiql'; import { - TravisCIApi, - travisCIApiRef, -} from '@roadiehq/backstage-plugin-travis-ci'; - -import { - GithubPullRequestsClient, - githubPullRequestsApiRef, -} from '@roadiehq/backstage-plugin-github-pull-requests'; - -import { costInsightsApiRef } from '@backstage/plugin-cost-insights'; -import { ExampleCostInsightsClient } from './plugins/cost-insights'; + costInsightsApiRef, + ExampleCostInsightsClient, +} from '@backstage/plugin-cost-insights'; export const apis = [ createApiFactory({ @@ -59,8 +51,4 @@ export const apis = [ }), createApiFactory(costInsightsApiRef, new ExampleCostInsightsClient()), - - // TODO: move to plugins - createApiFactory(travisCIApiRef, new TravisCIApi()), - createApiFactory(githubPullRequestsApiRef, new GithubPullRequestsClient()), ]; diff --git a/packages/app/src/components/Root/Root.tsx b/packages/app/src/components/Root/Root.tsx index 45ffca7801..e947e5c91d 100644 --- a/packages/app/src/components/Root/Root.tsx +++ b/packages/app/src/components/Root/Root.tsx @@ -35,11 +35,10 @@ import { SidebarDivider, SidebarSearchField, SidebarSpace, - SidebarUserSettings, - DefaultProviderSettings, } from '@backstage/core'; import { NavLink } from 'react-router-dom'; import { graphiQLRouteRef } from '@backstage/plugin-graphiql'; +import { Settings as SidebarSettings } from '@backstage/plugin-user-settings'; const useSidebarLogoStyles = makeStyles({ root: { @@ -103,7 +102,7 @@ const Root: FC<{}> = ({ children }) => ( /> - } /> + {children} diff --git a/packages/app/src/components/catalog/EntityPage.tsx b/packages/app/src/components/catalog/EntityPage.tsx index 393ffe2631..0a3007237e 100644 --- a/packages/app/src/components/catalog/EntityPage.tsx +++ b/packages/app/src/components/catalog/EntityPage.tsx @@ -40,6 +40,13 @@ import { Router as ApiDocsRouter } from '@backstage/plugin-api-docs'; import { Router as SentryRouter } from '@backstage/plugin-sentry'; import { EmbeddedDocsRouter as DocsRouter } from '@backstage/plugin-techdocs'; import { Router as KubernetesRouter } from '@backstage/plugin-kubernetes'; +import { + Router as GitHubInsightsRouter, + isPluginApplicableToEntity as isGitHubAvailable, + ReadMeCard, + LanguagesCard, + ReleasesCard, +} from '@roadiehq/backstage-plugin-github-insights'; import React, { ReactNode } from 'react'; import { AboutCard, @@ -54,6 +61,11 @@ import { LastLighthouseAuditCard, isPluginApplicableToEntity as isLighthouseAvailable, } from '@backstage/plugin-lighthouse/'; +import { + Router as PullRequestsRouter, + isPluginApplicableToEntity as isPullRequestsAvailable, + PullRequestsStatsCard, +} from '@roadiehq/backstage-plugin-github-pull-requests'; const CICDSwitcher = ({ entity }: { entity: Entity }) => { // This component is just an example of how you can implement your company's logic in entity page. @@ -93,10 +105,12 @@ const RecentCICDRunsSwitcher = ({ entity }: { entity: Entity }) => { let content: ReactNode; switch (true) { case isJenkinsAvailable(entity): - content = ; + content = ; break; case isGitHubActionsAvailable(entity): - content = ; + content = ( + + ); break; case isTravisCIAvailable(entity): content = ; @@ -115,14 +129,30 @@ const RecentCICDRunsSwitcher = ({ entity }: { entity: Entity }) => { }; const OverviewContent = ({ entity }: { entity: Entity }) => ( - + - + + {isGitHubAvailable(entity) && ( + <> + + + + + + + + + )} {isLighthouseAvailable(entity) && ( - + + + )} + {isPullRequestsAvailable(entity) && ( + + )} @@ -160,6 +190,16 @@ const ServiceEntityPage = ({ entity }: { entity: Entity }) => ( title="Kubernetes" element={} /> + } + /> + } + /> ); @@ -195,6 +235,16 @@ const WebsiteEntityPage = ({ entity }: { entity: Entity }) => ( title="Kubernetes" element={} /> + } + /> + } + /> ); const DefaultEntityPage = ({ entity }: { entity: Entity }) => ( diff --git a/packages/app/src/plugins.ts b/packages/app/src/plugins.ts index 85c4977d67..bdc3851318 100644 --- a/packages/app/src/plugins.ts +++ b/packages/app/src/plugins.ts @@ -36,3 +36,5 @@ export { plugin as GcpProjects } from '@backstage/plugin-gcp-projects'; export { plugin as Kubernetes } from '@backstage/plugin-kubernetes'; export { plugin as Cloudbuild } from '@backstage/plugin-cloudbuild'; export { plugin as CostInsights } from '@backstage/plugin-cost-insights'; +export { plugin as GitHubInsights } from '@roadiehq/backstage-plugin-github-insights'; +export { plugin as UserSettings } from '@backstage/plugin-user-settings'; diff --git a/packages/app/src/plugins/cost-insights/ExampleCostInsightsClient.ts b/packages/app/src/plugins/cost-insights/ExampleCostInsightsClient.ts deleted file mode 100644 index c01092dc51..0000000000 --- a/packages/app/src/plugins/cost-insights/ExampleCostInsightsClient.ts +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* eslint-disable no-restricted-imports */ - -import { - CostInsightsApi, - Alert, - Cost, - Duration, - Project, - ProductCost, - Group, -} from '@backstage/plugin-cost-insights'; - -export class ExampleCostInsightsClient implements CostInsightsApi { - private request(_: any, res: any): Promise { - return new Promise(resolve => setTimeout(resolve, 0, res)); - } - - async getUserGroups(userId: string): Promise { - const groups: Group[] = await this.request({ userId }, [ - { id: 'pied-piper' }, - ]); - - return groups; - } - - async getGroupProjects(group: string): Promise { - const projects: Project[] = await this.request({ group }, [ - { id: 'project-a' }, - { id: 'project-b' }, - { id: 'project-c' }, - ]); - - return projects; - } - - async getGroupDailyCost( - group: string, - metric: string | null, - intervals: string, - ): Promise { - const groupDailyCost: Cost = await this.request( - { group, metric, intervals }, - { - id: metric, // costs with null ids will appear as "All Projects" in Cost Overview panel - aggregation: [ - { date: '2020-08-01', amount: 75_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-02', amount: 120_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-03', amount: 110_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-04', amount: 90_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-05', amount: 80_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-06', amount: 85_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-07', amount: 82_500 / (metric ? 200_000 : 1) }, - { date: '2020-08-08', amount: 100_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-09', amount: 130_000 / (metric ? 200_000 : 1) }, - { date: '2020-08-10', amount: 140_000 / (metric ? 200_000 : 1) }, - ], - change: { - ratio: 0.86, - amount: 65_000, - }, - trendline: { - slope: 0, - intercept: 90_000, - }, - }, - ); - - return groupDailyCost; - } - - async getProjectDailyCost( - project: string, - metric: string | null, - intervals: string, - ): Promise { - const projectDailyCost: Cost = await this.request( - { project, metric, intervals }, - { - id: 'project-a', - aggregation: [ - { date: '2020-08-01', amount: 1000 }, - { date: '2020-08-02', amount: 2000 }, - { date: '2020-08-03', amount: 3000 }, - { date: '2020-08-04', amount: 4000 }, - { date: '2020-08-05', amount: 5000 }, - { date: '2020-08-06', amount: 6000 }, - { date: '2020-08-07', amount: 7000 }, - { date: '2020-08-08', amount: 8000 }, - { date: '2020-08-09', amount: 9000 }, - { date: '2020-08-10', amount: 10_000 }, - ], - change: { - ratio: 0.5, - amount: 10000, - }, - trendline: { - slope: 0, - intercept: 0, - }, - }, - ); - - return projectDailyCost; - } - - async getProductInsights( - product: string, - group: string, - duration: Duration, - ): Promise { - const productInsights: ProductCost = await this.request( - { product, group, duration }, - { - aggregation: [200_000, 250_000], - change: { - ratio: 0.2, - amount: 50_000, - }, - entities: [ - { - id: null, // entities with null ids will be appear as "Unlabeled" in product panels - aggregation: [45_000, 50_000], - }, - { - id: 'entity-a', - aggregation: [15_000, 20_000], - }, - { - id: 'entity-b', - aggregation: [20_000, 30_000], - }, - { - id: 'entity-c', - aggregation: [18_000, 25_000], - }, - { - id: 'entity-d', - aggregation: [36_000, 42_000], - }, - { - id: 'entity-e', - aggregation: [0, 10_000], - }, - { - id: 'entity-f', - aggregation: [17_000, 19_000], - }, - { - id: 'entity-g', - aggregation: [49_000, 30_000], - }, - { - id: 'entity-h', - aggregation: [0, 34_000], - }, - ], - }, - ); - - return productInsights; - } - - async getAlerts(group: string): Promise { - const alerts: Alert[] = await this.request({ group }, [ - { - id: 'projectGrowth', - project: 'example-project', - periodStart: 'Q1 2020', - periodEnd: 'Q2 2020', - aggregation: [60_000, 120_000], - change: { - ratio: 1, - amount: 60000, - }, - products: [ - { - id: 'Compute Engine', - aggregation: [58_000, 118_000], - }, - { - id: 'Cloud Dataflow', - aggregation: [1200, 1500], - }, - { - id: 'Cloud Storage', - aggregation: [800, 500], - }, - ], - }, - ]); - - return alerts; - } -} diff --git a/packages/backend-common/package.json b/packages/backend-common/package.json index 1c888ab8fe..dea2f16bae 100644 --- a/packages/backend-common/package.json +++ b/packages/backend-common/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/backend-common", "description": "Common functionality library for Backstage backends", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "private": false, @@ -29,23 +29,25 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/cli-common": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", - "@backstage/config-loader": "^0.1.1-alpha.24", + "@backstage/cli-common": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", + "@backstage/config-loader": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@types/cors": "^2.8.6", "@types/express": "^4.17.6", "compression": "^1.7.4", "cors": "^2.8.5", + "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-prom-bundle": "^6.1.0", "express-promise-router": "^3.0.3", - "git-url-parse": "^11.2.0", + "git-url-parse": "^11.4.0", "helmet": "^4.0.0", "knex": "^0.21.1", "lodash": "^4.17.15", "logform": "^2.1.1", + "minimist": "^1.2.5", "morgan": "^1.10.0", - "node-fetch": "^2.6.0", "prom-client": "^12.0.0", "selfsigned": "^1.10.7", "stoppable": "^1.1.0", @@ -60,11 +62,11 @@ } }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", "@types/compression": "^1.7.0", "@types/http-errors": "^1.6.3", + "@types/minimist": "^1.2.0", "@types/morgan": "^1.9.0", - "@types/node-fetch": "^2.5.7", "@types/stoppable": "^1.1.0", "@types/supertest": "^2.0.8", "@types/webpack-env": "^1.15.2", @@ -72,8 +74,7 @@ "get-port": "^5.1.1", "http-errors": "^1.7.3", "jest": "^26.0.1", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", + "msw": "^0.21.2", "supertest": "^4.0.2" }, "files": [ diff --git a/packages/backend-common/src/config.ts b/packages/backend-common/src/config.ts index 247eb593cc..69e46bd5b4 100644 --- a/packages/backend-common/src/config.ts +++ b/packages/backend-common/src/config.ts @@ -14,18 +14,38 @@ * limitations under the License. */ +import { resolve as resolvePath } from 'path'; +import parseArgs from 'minimist'; +import { Logger } from 'winston'; import { findPaths } from '@backstage/cli-common'; +import { Config, ConfigReader } from '@backstage/config'; import { loadConfig } from '@backstage/config-loader'; +type Options = { + logger: Logger; + // process.argv or any other overrides + argv: string[]; +}; + /** * Load configuration for a Backend */ -export async function loadBackendConfig() { +export async function loadBackendConfig(options: Options): Promise { + const args = parseArgs(options.argv); + const configOpts: string[] = [args.config ?? []].flat(); + + /* eslint-disable-next-line no-restricted-syntax */ const paths = findPaths(__dirname); const configs = await loadConfig({ - env: process.env.NODE_ENV ?? 'development', - rootPaths: [paths.targetRoot, paths.targetDir], + env: process.env.APP_ENV ?? process.env.NODE_ENV ?? 'development', + configRoot: paths.targetRoot, + configPaths: configOpts.map(opt => resolvePath(opt)), shouldReadSecrets: true, }); - return configs; + + options.logger.info( + `Loaded config from ${configs.map(c => c.context).join(', ')}`, + ); + + return ConfigReader.fromConfigs(configs); } diff --git a/packages/backend-common/src/database/SingleConnection.test.ts b/packages/backend-common/src/database/SingleConnection.test.ts new file mode 100644 index 0000000000..6278e4ecad --- /dev/null +++ b/packages/backend-common/src/database/SingleConnection.test.ts @@ -0,0 +1,97 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ConfigReader } from '@backstage/config'; +import { createDatabaseClient } from './connection'; +import { SingleConnectionDatabaseManager } from './SingleConnection'; + +jest.mock('./connection'); + +describe('SingleConnectionDatabaseManager', () => { + const createConfig = (data: any) => + ConfigReader.fromConfigs([ + { + context: '', + data, + }, + ]); + + const defaultConfigOptions = { + backend: { + database: { + client: 'pg', + connection: { + host: 'localhost', + user: 'foo', + password: 'bar', + database: 'foodb', + }, + }, + }, + }; + const defaultConfig = () => createConfig(defaultConfigOptions); + + // This is similar to the ts-jest `mocked` helper. + const mocked = (f: Function) => f as jest.Mock; + + afterEach(() => jest.resetAllMocks()); + + describe('SingleConnectionDatabaseManager.fromConfig', () => { + it('accesses the backend.database key', () => { + const getConfig = jest.fn(); + const config = defaultConfig(); + config.getConfig = getConfig; + + SingleConnectionDatabaseManager.fromConfig(config); + + expect(getConfig.mock.calls[0][0]).toEqual('backend.database'); + }); + }); + + describe('SingleConnectionDatabaseManager.forPlugin', () => { + const manager = SingleConnectionDatabaseManager.fromConfig(defaultConfig()); + + it('connects to a database scoped to the plugin', async () => { + const pluginId = 'test1'; + await manager.forPlugin(pluginId).getClient(); + + expect(mocked(createDatabaseClient)).toHaveBeenCalledTimes(1); + + const mockCalls = mocked(createDatabaseClient).mock.calls.splice(-1); + const callArgs = mockCalls[0]; + expect(callArgs[0].get()).toEqual(defaultConfigOptions.backend.database); + expect(callArgs[1].connection.database).toEqual( + `backstage_plugin_${pluginId}`, + ); + }); + + it('provides different plugins different databases', async () => { + const plugin1Id = 'test1'; + const plugin2Id = 'test2'; + await manager.forPlugin(plugin1Id).getClient(); + await manager.forPlugin(plugin2Id).getClient(); + + expect(mocked(createDatabaseClient)).toHaveBeenCalledTimes(2); + + const mockCalls = mocked(createDatabaseClient).mock.calls; + const plugin1CallArgs = mockCalls[0]; + const plugin2CallArgs = mockCalls[1]; + expect(plugin1CallArgs[1].connection.database).not.toEqual( + plugin2CallArgs[1].connection.database, + ); + }); + }); +}); diff --git a/packages/backend-common/src/database/SingleConnection.ts b/packages/backend-common/src/database/SingleConnection.ts new file mode 100644 index 0000000000..777ced54a0 --- /dev/null +++ b/packages/backend-common/src/database/SingleConnection.ts @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Knex from 'knex'; +import { Config } from '@backstage/config'; +import { createDatabaseClient, ensureDatabaseExists } from './connection'; +import { PluginDatabaseManager } from './types'; + +/** + * Implements a Database Manager which will automatically create new databases + * for plugins when requested. All requested databases are created with the + * credentials provided; if the database already exists no attempt to create + * the database will be made. + */ +export class SingleConnectionDatabaseManager { + /** + * Creates a new SingleConnectionDatabaseManager instance by reading from the `backend` + * config section, specifically the `.database` key for discovering the management + * database configuration. + * + * @param config The loaded application configuration. + */ + static fromConfig(config: Config): SingleConnectionDatabaseManager { + return new SingleConnectionDatabaseManager( + config.getConfig('backend.database'), + ); + } + + private constructor(private readonly config: Config) {} + + /** + * Generates a PluginDatabaseManager for consumption by plugins. + * + * @param pluginId The plugin that the database manager should be created for. Plugin names should be unique. + */ + forPlugin(pluginId: string): PluginDatabaseManager { + const _this = this; + + return { + getClient(): Promise { + return _this.getDatabase(pluginId); + }, + }; + } + + private async getDatabase(pluginId: string): Promise { + const config = this.config; + const overrides = SingleConnectionDatabaseManager.getDatabaseOverrides( + pluginId, + ); + const overrideConfig = overrides.connection as Knex.ConnectionConfig; + await this.ensureDatabase(overrideConfig.database); + + return createDatabaseClient(config, overrides); + } + + private static getDatabaseOverrides(pluginId: string): Knex.Config { + return { + connection: { + database: `backstage_plugin_${pluginId}`, + }, + }; + } + + private async ensureDatabase(database: string) { + const config = this.config; + await ensureDatabaseExists(config, database); + } +} diff --git a/packages/backend-common/src/database/config.test.ts b/packages/backend-common/src/database/config.test.ts index ab29bc19ba..eb26013b4b 100644 --- a/packages/backend-common/src/database/config.test.ts +++ b/packages/backend-common/src/database/config.test.ts @@ -17,7 +17,19 @@ import { mergeDatabaseConfig } from './config'; describe('config', () => { - describe(mergeDatabaseConfig, () => { + describe('mergeDatabaseConfig', () => { + it('does not mutate the input object', () => { + const input = { + original: 'key', + }; + const override = { + added: 'value', + }; + + mergeDatabaseConfig(input, override); + expect(input).not.toHaveProperty('added'); + }); + it('does not require overrides', () => { expect( mergeDatabaseConfig({ diff --git a/packages/backend-common/src/database/config.ts b/packages/backend-common/src/database/config.ts index 80abc06aa2..af32556c28 100644 --- a/packages/backend-common/src/database/config.ts +++ b/packages/backend-common/src/database/config.ts @@ -19,9 +19,9 @@ import { merge } from 'lodash'; /** * Merges database objects together * - * @param config The base config + * @param config The base config. The input is not modified * @param overrides Any additional overrides */ export function mergeDatabaseConfig(config: any, ...overrides: any[]) { - return merge(config, ...overrides); + return merge({}, config, ...overrides); } diff --git a/packages/backend-common/src/database/connection.test.ts b/packages/backend-common/src/database/connection.test.ts index 2cc3a54e06..de0b0e40dc 100644 --- a/packages/backend-common/src/database/connection.test.ts +++ b/packages/backend-common/src/database/connection.test.ts @@ -26,7 +26,7 @@ describe('database connection', () => { }, ]); - describe(createDatabaseClient, () => { + describe('createDatabaseClient', () => { it('returns a postgres connection', () => { expect( createDatabaseClient( diff --git a/packages/backend-common/src/database/index.ts b/packages/backend-common/src/database/index.ts index 38d3d6224b..c81153aa62 100644 --- a/packages/backend-common/src/database/index.ts +++ b/packages/backend-common/src/database/index.ts @@ -15,3 +15,5 @@ */ export * from './connection'; +export * from './types'; +export * from './SingleConnection'; diff --git a/packages/backend-common/src/database/postgres.test.ts b/packages/backend-common/src/database/postgres.test.ts index 82161dc53c..8d139e4481 100644 --- a/packages/backend-common/src/database/postgres.test.ts +++ b/packages/backend-common/src/database/postgres.test.ts @@ -44,7 +44,7 @@ describe('postgres', () => { }, ]); - describe(buildPgDatabaseConfig, () => { + describe('buildPgDatabaseConfig', () => { it('builds a postgres config', () => { const mockConnection = createMockConnection(); @@ -125,7 +125,7 @@ describe('postgres', () => { }); }); - describe(getPgConnectionConfig, () => { + describe('getPgConnectionConfig', () => { it('returns the connection object back', () => { const mockConnection = createMockConnection(); const config = createConfig(mockConnection); @@ -163,7 +163,7 @@ describe('postgres', () => { }); }); - describe(createPgDatabaseClient, () => { + describe('createPgDatabaseClient', () => { it('creates a postgres knex instance', () => { expect( createPgDatabaseClient( @@ -188,8 +188,8 @@ describe('postgres', () => { }); }); - describe(parsePgConnectionString, () => { - it('parses a connection string uri ', () => { + describe('parsePgConnectionString', () => { + it('parses a connection string uri', () => { expect( parsePgConnectionString( 'postgresql://postgres:pass@foobar:5432/dbname?ssl=true', diff --git a/packages/backend-common/src/database/postgres.ts b/packages/backend-common/src/database/postgres.ts index 82e971f081..04bd3615b6 100644 --- a/packages/backend-common/src/database/postgres.ts +++ b/packages/backend-common/src/database/postgres.ts @@ -57,7 +57,7 @@ export function buildPgDatabaseConfig( * Gets the postgres connection config * * @param dbConfig The database config - * @param parseConnectionString Flag to explictly control connection string parsing + * @param parseConnectionString Flag to explicitly control connection string parsing */ export function getPgConnectionConfig( dbConfig: Config, diff --git a/packages/backend-common/src/database/sqlite3.test.ts b/packages/backend-common/src/database/sqlite3.test.ts index dbff5ee354..a3ab331c2d 100644 --- a/packages/backend-common/src/database/sqlite3.test.ts +++ b/packages/backend-common/src/database/sqlite3.test.ts @@ -32,7 +32,7 @@ describe('sqlite3', () => { }, ]); - describe(buildSqliteDatabaseConfig, () => { + describe('buildSqliteDatabaseConfig', () => { it('buidls a string connection', () => { expect(buildSqliteDatabaseConfig(createConfig(':memory:'))).toEqual({ client: 'sqlite3', @@ -72,7 +72,7 @@ describe('sqlite3', () => { }); }); - describe(createSqliteDatabaseClient, () => { + describe('createSqliteDatabaseClient', () => { it('creates an in memory knex instance', () => { expect( createSqliteDatabaseClient( diff --git a/packages/core/src/layout/Sidebar/Settings/AuthProviderList.tsx b/packages/backend-common/src/database/types.ts similarity index 58% rename from packages/core/src/layout/Sidebar/Settings/AuthProviderList.tsx rename to packages/backend-common/src/database/types.ts index 34cf6fb837..7eaa05f173 100644 --- a/packages/core/src/layout/Sidebar/Settings/AuthProviderList.tsx +++ b/packages/backend-common/src/database/types.ts @@ -14,16 +14,17 @@ * limitations under the License. */ -import React from 'react'; -import List from '@material-ui/core/List'; -import ListSubheader from '@material-ui/core/ListSubheader'; +import knex from 'knex'; -type Props = { - providerSettings: React.ReactNode; -}; - -export const AuthProvidersList = ({ providerSettings }: Props) => ( - Available Auth Providers}> - {providerSettings} - -); +/** + * The PluginDatabaseManager manages access to databases that Plugins get. + */ +export interface PluginDatabaseManager { + /** + * getClient provides backend plugins database connections for itself. + * + * The purpose of this method is to allow plugins to get isolated data + * stores so that plugins are discouraged from database integration. + */ + getClient(): Promise; +} diff --git a/packages/backend-common/src/paths.ts b/packages/backend-common/src/paths.ts index 402c0e2252..262be366f6 100644 --- a/packages/backend-common/src/paths.ts +++ b/packages/backend-common/src/paths.ts @@ -14,8 +14,6 @@ * limitations under the License. */ -/* eslint-disable @typescript-eslint/camelcase */ - import { resolve as resolvePath } from 'path'; /** diff --git a/packages/backend-common/src/reading/AzureUrlReader.test.ts b/packages/backend-common/src/reading/AzureUrlReader.test.ts index c9e1fc5bc7..24b435006a 100644 --- a/packages/backend-common/src/reading/AzureUrlReader.test.ts +++ b/packages/backend-common/src/reading/AzureUrlReader.test.ts @@ -19,14 +19,13 @@ import { setupServer } from 'msw/node'; import { ConfigReader } from '@backstage/config'; import { getVoidLogger } from '../logging'; import { AzureUrlReader } from './AzureUrlReader'; +import { msw } from '@backstage/test-utils'; const logger = getVoidLogger(); describe('AzureUrlReader', () => { const worker = setupServer(); - - beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); - afterAll(() => worker.close()); + msw.setupDefaultHandlers(worker); beforeEach(() => { worker.use( @@ -41,7 +40,6 @@ describe('AzureUrlReader', () => { ), ); }); - afterEach(() => worker.resetHandlers()); const createConfig = (token?: string) => new ConfigReader( diff --git a/packages/backend-common/src/reading/AzureUrlReader.ts b/packages/backend-common/src/reading/AzureUrlReader.ts index 28fbf25eea..8e6e6a75df 100644 --- a/packages/backend-common/src/reading/AzureUrlReader.ts +++ b/packages/backend-common/src/reading/AzureUrlReader.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import fetch, { RequestInit, HeadersInit, Response } from 'node-fetch'; +import fetch from 'cross-fetch'; import { Config } from '@backstage/config'; import { NotFoundError } from '../errors'; import { ReaderFactory, UrlReader } from './types'; @@ -76,7 +76,7 @@ export class AzureUrlReader implements UrlReader { // for private repos when PAT is not valid, Azure API returns a http status code 203 with sign in page html if (response.ok && response.status !== 203) { - return response.buffer(); + return Buffer.from(await response.text()); } const message = `${url} could not be read as ${builtUrl}, ${response.status} ${response.statusText}`; diff --git a/packages/backend-common/src/reading/BitbucketUrlReader.test.ts b/packages/backend-common/src/reading/BitbucketUrlReader.test.ts index c3e61fb821..210ee16873 100644 --- a/packages/backend-common/src/reading/BitbucketUrlReader.test.ts +++ b/packages/backend-common/src/reading/BitbucketUrlReader.test.ts @@ -14,140 +14,167 @@ * limitations under the License. */ -import { rest } from 'msw'; -import { setupServer } from 'msw/node'; import { ConfigReader } from '@backstage/config'; -import { getVoidLogger } from '../logging'; -import { BitbucketUrlReader } from './BitbucketUrlReader'; - -const logger = getVoidLogger(); +import { + BitbucketUrlReader, + getApiRequestOptions, + getApiUrl, + ProviderConfig, + readConfig, +} from './BitbucketUrlReader'; describe('BitbucketUrlReader', () => { - const worker = setupServer(); + describe('getApiRequestOptions', () => { + it('inserts a token when needed', () => { + const withToken: ProviderConfig = { + host: '', + apiBaseUrl: '', + token: 'A', + }; + const withoutToken: ProviderConfig = { + host: '', + apiBaseUrl: '', + }; + expect( + (getApiRequestOptions(withToken).headers as any).Authorization, + ).toEqual('Bearer A'); + expect( + (getApiRequestOptions(withoutToken).headers as any).Authorization, + ).toBeUndefined(); + }); - beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); - afterAll(() => worker.close()); + it('insert basic auth when needed', () => { + const withUsernameAndPassword: ProviderConfig = { + host: '', + apiBaseUrl: '', + username: 'some-user', + appPassword: 'my-secret', + }; + const withoutUsernameAndPassword: ProviderConfig = { + host: '', + apiBaseUrl: '', + }; + expect( + (getApiRequestOptions(withUsernameAndPassword).headers as any) + .Authorization, + ).toEqual('Basic c29tZS11c2VyOm15LXNlY3JldA=='); + expect( + (getApiRequestOptions(withoutUsernameAndPassword).headers as any) + .Authorization, + ).toBeUndefined(); + }); + }); - beforeEach(() => { - worker.use( - rest.get('*', (req, res, ctx) => - res( - ctx.status(200), - ctx.json({ - url: req.url.toString(), - headers: req.headers.getAllHeaders(), - }), + describe('getApiUrl', () => { + it('rejects targets that do not look like URLs', () => { + const config: ProviderConfig = { host: '', apiBaseUrl: '' }; + expect(() => getApiUrl('a/b', config)).toThrow(/Incorrect URL: a\/b/); + }); + it('happy path for Bitbucket Cloud', () => { + const config: ProviderConfig = { + host: 'bitbucket.org', + apiBaseUrl: 'https://api.bitbucket.org/2.0', + }; + expect( + getApiUrl( + 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', + config, ), - ), - ); - }); - afterEach(() => worker.resetHandlers()); - - const createConfig = (username?: string, appPassword?: string) => - new ConfigReader( - { - integrations: { - bitbucket: [ - { - host: 'bitbucket.org', - username: username, - appPassword: appPassword, - }, - ], - }, - }, - 'test-config', - ); - - it.each([ - { - url: - 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', - config: createConfig(), - response: expect.objectContaining({ - url: + ).toEqual( + new URL( 'https://api.bitbucket.org/2.0/repositories/org-name/repo-name/src/master/templates/my-template.yaml', - }), - }, - { - url: - 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', - config: createConfig('some-user', 'my-secret'), - response: expect.objectContaining({ - headers: expect.objectContaining({ - authorization: 'Basic c29tZS11c2VyOm15LXNlY3JldA==', - }), - }), - }, - { - url: - 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', - config: createConfig(), - response: expect.objectContaining({ - headers: expect.not.objectContaining({ - authorization: expect.anything(), - }), - }), - }, - { - url: - 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', - config: createConfig(undefined, 'only-password-provided'), - response: expect.objectContaining({ - headers: expect.not.objectContaining({ - authorization: expect.anything(), - }), - }), - }, - ])('should handle happy path %#', async ({ url, config, response }) => { - const [{ reader }] = BitbucketUrlReader.factory({ config, logger }); - - const data = await reader.read(url); - const res = await JSON.parse(data.toString('utf-8')); - expect(res).toEqual(response); + ), + ); + }); + it('happy path for Bitbucket Server', () => { + const config: ProviderConfig = { + host: 'bitbucket.mycompany.net', + apiBaseUrl: 'https://bitbucket.mycompany.net/rest/api/1.0', + }; + expect( + getApiUrl( + 'https://bitbucket.mycompany.net/projects/a/repos/b/browse/path/to/c.yaml', + config, + ), + ).toEqual( + new URL( + 'https://bitbucket.mycompany.net/rest/api/1.0/projects/a/repos/b/raw/path/to/c.yaml', + ), + ); + }); }); - it.each([ - { - url: 'https://api.com/a/b/blob/master/path/to/c.yaml', - config: createConfig(), - error: - 'Incorrect url: https://api.com/a/b/blob/master/path/to/c.yaml, Error: Wrong Bitbucket URL or Invalid file path', - }, - { - url: 'com/a/b/blob/master/path/to/c.yaml', - config: createConfig(), - error: - 'Incorrect url: com/a/b/blob/master/path/to/c.yaml, TypeError: Invalid URL: com/a/b/blob/master/path/to/c.yaml', - }, - { - url: '', - config: createConfig('', ''), - error: - "Invalid type in config for key 'integrations.bitbucket[0].username' in 'test-config', got empty-string, wanted string", - }, - { - url: '', - config: createConfig('only-user-provided', ''), - error: - "Invalid type in config for key 'integrations.bitbucket[0].appPassword' in 'test-config', got empty-string, wanted string", - }, - { - url: '', - config: createConfig('', 'only-password-provided'), - error: - "Invalid type in config for key 'integrations.bitbucket[0].username' in 'test-config', got empty-string, wanted string", - }, - { - url: '', - config: createConfig('only-user-provided', undefined), - error: - "Missing required config value at 'integrations.bitbucket[0].appPassword'", - }, - ])('should handle error path %#', async ({ url, config, error }) => { - await expect(async () => { - const [{ reader }] = BitbucketUrlReader.factory({ config, logger }); - await reader.read(url); - }).rejects.toThrow(error); + describe('readConfig', () => { + function config( + providers: { + host: string; + apiBaseUrl?: string; + token?: string; + username?: string; + password?: string; + }[], + ) { + return ConfigReader.fromConfigs([ + { + context: '', + data: { + integrations: { bitbucket: providers }, + }, + }, + ]); + } + + it('adds a default Bitbucket Cloud entry when missing', () => { + const output = readConfig(config([])); + expect(output).toEqual([ + { + host: 'bitbucket.org', + apiBaseUrl: 'https://api.bitbucket.org/2.0', + }, + ]); + }); + + it('injects the correct Bitbucket Cloud API base URL when missing', () => { + const output = readConfig(config([{ host: 'bitbucket.org' }])); + expect(output).toEqual([ + { + host: 'bitbucket.org', + apiBaseUrl: 'https://api.bitbucket.org/2.0', + }, + ]); + }); + + it('rejects custom targets with no base URLs', () => { + expect(() => + readConfig(config([{ host: 'bitbucket.mycompany.net' }])), + ).toThrow( + "Bitbucket integration for 'bitbucket.mycompany.net' must configure an explicit apiBaseUrl", + ); + }); + + it('rejects funky configs', () => { + expect(() => readConfig(config([{ host: 7 } as any]))).toThrow(/host/); + expect(() => readConfig(config([{ token: 7 } as any]))).toThrow(/token/); + expect(() => + readConfig(config([{ host: 'bitbucket.org', apiBaseUrl: 7 } as any])), + ).toThrow(/apiBaseUrl/); + expect(() => + readConfig(config([{ host: 'bitbucket.org', token: 7 } as any])), + ).toThrow(/token/); + }); + }); + + describe('implementation', () => { + it('rejects unknown targets', async () => { + const processor = new BitbucketUrlReader({ + host: 'bitbucket.org', + apiBaseUrl: 'https://api.bitbucket.org/2.0', + }); + await expect( + processor.read('https://not.bitbucket.com/apa'), + ).rejects.toThrow( + 'Incorrect URL: https://not.bitbucket.com/apa, Error: Invalid Bitbucket URL or file path', + ); + }); }); }); diff --git a/packages/backend-common/src/reading/BitbucketUrlReader.ts b/packages/backend-common/src/reading/BitbucketUrlReader.ts index e2576eed47..348426fd34 100644 --- a/packages/backend-common/src/reading/BitbucketUrlReader.ts +++ b/packages/backend-common/src/reading/BitbucketUrlReader.ts @@ -14,149 +14,207 @@ * limitations under the License. */ -import fetch, { RequestInit, HeadersInit, Response } from 'node-fetch'; import { Config } from '@backstage/config'; -import { ReaderFactory, UrlReader } from './types'; +import parseGitUri from 'git-url-parse'; +import fetch from 'cross-fetch'; import { NotFoundError } from '../errors'; +import { ReaderFactory, UrlReader } from './types'; -type Options = { - // TODO: added here for future support, but we only allow bitbucket.org for now +const DEFAULT_BASE_URL = 'https://api.bitbucket.org/2.0'; + +/** + * The configuration parameters for a single Bitbucket API provider. + */ +export type ProviderConfig = { + /** + * The host of the target that this matches on, e.g. "bitbucket.com" + */ host: string; - auth?: { - username: string; - appPassword: string; - }; + + /** + * The base URL of the API of this provider, e.g. "https://api.bitbucket.org/2.0", + * with no trailing slash. + * + * May be omitted specifically for Bitbucket Cloud; then it will be deduced. + * + * The API will always be preferred if both its base URL and a token are + * present. + */ + apiBaseUrl?: string; + + /** + * The authorization token to use for requests to a Bitbucket Server provider. + * + * See https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html + * + * If no token is specified, anonymous access is used. + */ + token?: string; + + /** + * The username to use for requests to Bitbucket Cloud (bitbucket.org). + */ + username?: string; + + /** + * Authentication with Bitbucket Cloud (bitbucket.org) is done using app passwords. + * + * See https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/ + */ + appPassword?: string; }; -function readConfig(config: Config): Options[] { - const optionsArr = Array(); +export function getApiRequestOptions(provider: ProviderConfig): RequestInit { + const headers: HeadersInit = {}; + + if (provider.token) { + headers.Authorization = `Bearer ${provider.token}`; + } else if (provider.username && provider.appPassword) { + headers.Authorization = `Basic ${Buffer.from( + `${provider.username}:${provider.appPassword}`, + 'utf8', + ).toString('base64')}`; + } + + return { + headers, + }; +} + +// Converts for example +// from: https://bitbucket.org/orgname/reponame/src/master/file.yaml +// to: https://api.bitbucket.org/2.0/repositories/orgname/reponame/src/master/file.yaml +export function getApiUrl(target: string, provider: ProviderConfig): URL { + try { + const { owner, name, ref, filepathtype, filepath } = parseGitUri(target); + if ( + !owner || + !name || + (filepathtype !== 'browse' && + filepathtype !== 'raw' && + filepathtype !== 'src') + ) { + throw new Error('Invalid Bitbucket URL or file path'); + } + + const pathWithoutSlash = filepath.replace(/^\//, ''); + + if (provider.host === 'bitbucket.org') { + if (!ref) { + throw new Error('Invalid Bitbucket URL or file path'); + } + return new URL( + `${provider.apiBaseUrl}/repositories/${owner}/${name}/src/${ref}/${pathWithoutSlash}`, + ); + } + return new URL( + `${provider.apiBaseUrl}/projects/${owner}/repos/${name}/raw/${pathWithoutSlash}?at=${ref}`, + ); + } catch (e) { + throw new Error(`Incorrect URL: ${target}, ${e}`); + } +} + +export function readConfig(config: Config): ProviderConfig[] { + const providers: ProviderConfig[] = []; const providerConfigs = config.getOptionalConfigArray('integrations.bitbucket') ?? []; + // First read all the explicit providers for (const providerConfig of providerConfigs) { const host = providerConfig.getOptionalString('host') ?? 'bitbucket.org'; + let apiBaseUrl = providerConfig.getOptionalString('apiBaseUrl'); + const token = providerConfig.getOptionalString('token'); + const username = providerConfig.getOptionalString('username'); + const appPassword = providerConfig.getOptionalString('appPassword'); - let auth; - if (providerConfig.has('username')) { - const username = providerConfig.getString('username'); - const appPassword = providerConfig.getString('appPassword'); - auth = { username, appPassword }; + if (apiBaseUrl) { + apiBaseUrl = apiBaseUrl.replace(/\/+$/, ''); + } else if (host === 'bitbucket.org') { + apiBaseUrl = DEFAULT_BASE_URL; } - optionsArr.push({ host, auth }); + if (!apiBaseUrl) { + throw new Error( + `Bitbucket integration for '${host}' must configure an explicit apiBaseUrl`, + ); + } + if (!token && username && !appPassword) { + throw new Error( + `Bitbucket integration for '${host}' has configured a username but is missing a required appPassword.`, + ); + } + + providers.push({ + host, + apiBaseUrl, + token, + username, + appPassword, + }); } - // As a convenience we always make sure there's at least an unauthenticated - // reader for public bitbucket repos. - if (!optionsArr.some(p => p.host === 'bitbucket.org')) { - optionsArr.push({ host: 'bitbucket.org' }); + // If no explicit bitbucket.org provider was added, put one in the list as + // a convenience + if (!providers.some(p => p.host === 'bitbucket.org')) { + providers.push({ + host: 'bitbucket.org', + apiBaseUrl: DEFAULT_BASE_URL, + }); } - return optionsArr; + return providers; } +/** + * A processor that adds the ability to read files from Bitbucket v1 and v2 APIs, such as + * the one exposed by Bitbucket Cloud itself. + */ export class BitbucketUrlReader implements UrlReader { + private config: ProviderConfig; + static factory: ReaderFactory = ({ config }) => { - return readConfig(config).map(options => { - const reader = new BitbucketUrlReader(options); - const predicate = (url: URL) => url.host === options.host; + return readConfig(config).map(provider => { + const reader = new BitbucketUrlReader(provider); + const predicate = (url: URL) => url.host === provider.host; return { reader, predicate }; }); }; - constructor(private readonly options: Options) { - if (options.host !== 'bitbucket.org') { - throw Error( - `Bitbucket integration currently only supports 'bitbucket.org', tried to use host '${options.host}'`, - ); - } + constructor(config: ProviderConfig) { + this.config = config; } async read(url: string): Promise { - const builtUrl = this.buildRawUrl(url); + const bitbucketUrl = getApiUrl(url, this.config); + + const options = getApiRequestOptions(this.config); let response: Response; try { - response = await fetch(builtUrl.toString(), this.getRequestOptions()); + response = await fetch(bitbucketUrl.toString(), options); } catch (e) { throw new Error(`Unable to read ${url}, ${e}`); } if (response.ok) { - return response.buffer(); + return Buffer.from(await response.text()); } - const message = `${url} could not be read as ${builtUrl}, ${response.status} ${response.statusText}`; + const message = `${url} could not be read as ${bitbucketUrl}, ${response.status} ${response.statusText}`; if (response.status === 404) { throw new NotFoundError(message); } throw new Error(message); } - // Converts - // from: https://bitbucket.org/orgname/reponame/src/master/file.yaml - // to: https://api.bitbucket.org/2.0/repositories/orgname/reponame/src/master/file.yaml - private buildRawUrl(target: string): URL { - try { - const url = new URL(target); - - const [ - empty, - userOrOrg, - repoName, - srcKeyword, - ref, - ...restOfPath - ] = url.pathname.split('/'); - - if ( - url.hostname !== 'bitbucket.org' || - empty !== '' || - userOrOrg === '' || - repoName === '' || - srcKeyword !== 'src' - ) { - throw new Error('Wrong Bitbucket URL or Invalid file path'); - } - - // transform to api - url.pathname = [ - empty, - '2.0', - 'repositories', - userOrOrg, - repoName, - 'src', - ref, - ...restOfPath, - ].join('/'); - url.hostname = 'api.bitbucket.org'; - url.protocol = 'https'; - - return url; - } catch (e) { - throw new Error(`Incorrect url: ${target}, ${e}`); - } - } - - private getRequestOptions(): RequestInit { - const headers: HeadersInit = {}; - - if (this.options.auth) { - headers.Authorization = `Basic ${Buffer.from( - `${this.options.auth.username}:${this.options.auth.appPassword}`, - 'utf8', - ).toString('base64')}`; - } - - return { - headers, - }; - } - toString() { - const { host, auth } = this.options; - return `bitbucket{host=${host},authed=${Boolean(auth)}}`; + const { host, token, username, appPassword } = this.config; + let authed = Boolean(token); + if (!authed) { + authed = Boolean(username && appPassword); + } + return `bitbucket{host=${host},authed=${authed}}`; } } diff --git a/packages/backend-common/src/reading/FetchUrlReader.ts b/packages/backend-common/src/reading/FetchUrlReader.ts index ea56f2182d..d2e5c45620 100644 --- a/packages/backend-common/src/reading/FetchUrlReader.ts +++ b/packages/backend-common/src/reading/FetchUrlReader.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import fetch, { Response } from 'node-fetch'; +import fetch from 'cross-fetch'; import { NotFoundError } from '../errors'; import { UrlReader } from './types'; @@ -31,7 +31,7 @@ export class FetchUrlReader implements UrlReader { } if (response.ok) { - return response.buffer(); + return Buffer.from(await response.text()); } const message = `could not read ${url}, ${response.status} ${response.statusText}`; diff --git a/packages/backend-common/src/reading/GithubUrlReader.ts b/packages/backend-common/src/reading/GithubUrlReader.ts index e5bed6dd26..d12344ec91 100644 --- a/packages/backend-common/src/reading/GithubUrlReader.ts +++ b/packages/backend-common/src/reading/GithubUrlReader.ts @@ -16,7 +16,7 @@ import { Config } from '@backstage/config'; import parseGitUri from 'git-url-parse'; -import fetch, { HeadersInit, RequestInit, Response } from 'node-fetch'; +import fetch from 'cross-fetch'; import { NotFoundError } from '../errors'; import { ReaderFactory, UrlReader } from './types'; @@ -219,7 +219,7 @@ export class GithubUrlReader implements UrlReader { } if (response.ok) { - return response.buffer(); + return Buffer.from(await response.text()); } const message = `${url} could not be read as ${ghUrl}, ${response.status} ${response.statusText}`; diff --git a/packages/backend-common/src/reading/GitlabUrlReader.test.ts b/packages/backend-common/src/reading/GitlabUrlReader.test.ts index 09da9c4e0a..4b3aa471c3 100644 --- a/packages/backend-common/src/reading/GitlabUrlReader.test.ts +++ b/packages/backend-common/src/reading/GitlabUrlReader.test.ts @@ -19,14 +19,14 @@ import { setupServer } from 'msw/node'; import { ConfigReader } from '@backstage/config'; import { getVoidLogger } from '../logging'; import { GitlabUrlReader } from './GitlabUrlReader'; +import { msw } from '@backstage/test-utils'; const logger = getVoidLogger(); describe('GitlabUrlReader', () => { const worker = setupServer(); - beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); - afterAll(() => worker.close()); + msw.setupDefaultHandlers(worker); beforeEach(() => { worker.use( @@ -44,7 +44,6 @@ describe('GitlabUrlReader', () => { ), ); }); - afterEach(() => worker.resetHandlers()); const createConfig = (token?: string) => new ConfigReader( diff --git a/packages/backend-common/src/reading/GitlabUrlReader.ts b/packages/backend-common/src/reading/GitlabUrlReader.ts index 0e430d650c..378e76fb61 100644 --- a/packages/backend-common/src/reading/GitlabUrlReader.ts +++ b/packages/backend-common/src/reading/GitlabUrlReader.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import fetch, { RequestInit, Response } from 'node-fetch'; +import fetch from 'cross-fetch'; import { Config } from '@backstage/config'; import { NotFoundError } from '../errors'; import { ReaderFactory, UrlReader } from './types'; @@ -77,7 +77,7 @@ export class GitlabUrlReader implements UrlReader { } if (response.ok) { - return response.buffer(); + return Buffer.from(await response.text()); } const message = `${url} could not be read as ${builtUrl}, ${response.status} ${response.statusText}`; diff --git a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts index 5ff7ed4271..710de6f1d7 100644 --- a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts +++ b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { ConfigReader } from '@backstage/config'; +import { Config } from '@backstage/config'; import compression from 'compression'; import cors from 'cors'; import express, { Router } from 'express'; @@ -77,7 +77,7 @@ export class ServiceBuilderImpl implements ServiceBuilder { this.module = moduleRef; } - loadConfig(config: ConfigReader): ServiceBuilder { + loadConfig(config: Config): ServiceBuilder { const backendConfig = config.getOptionalConfig('backend'); if (!backendConfig) { return this; diff --git a/packages/backend/package.json b/packages/backend/package.json index c3a912c93e..9f8e66bc61 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -1,6 +1,6 @@ { "name": "example-backend", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "dist/index.cjs.js", "types": "src/index.ts", "private": true, @@ -18,24 +18,24 @@ "migrate:create": "knex migrate:make -x ts" }, "dependencies": { - "@backstage/backend-common": "^0.1.1-alpha.24", - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", - "@backstage/plugin-app-backend": "^0.1.1-alpha.24", - "@backstage/plugin-auth-backend": "^0.1.1-alpha.24", - "@backstage/plugin-catalog-backend": "^0.1.1-alpha.24", - "@backstage/plugin-graphql-backend": "^0.1.1-alpha.24", - "@backstage/plugin-kubernetes-backend": "^0.1.1-alpha.24", - "@backstage/plugin-proxy-backend": "^0.1.1-alpha.24", - "@backstage/plugin-rollbar-backend": "^0.1.1-alpha.24", - "@backstage/plugin-scaffolder-backend": "^0.1.1-alpha.24", - "@backstage/plugin-sentry-backend": "^0.1.1-alpha.24", - "@backstage/plugin-techdocs-backend": "^0.1.1-alpha.24", + "@backstage/backend-common": "^0.1.1-alpha.26", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", + "@backstage/plugin-app-backend": "^0.1.1-alpha.26", + "@backstage/plugin-auth-backend": "^0.1.1-alpha.26", + "@backstage/plugin-catalog-backend": "^0.1.1-alpha.26", + "@backstage/plugin-graphql-backend": "^0.1.1-alpha.26", + "@backstage/plugin-kubernetes-backend": "^0.1.1-alpha.26", + "@backstage/plugin-proxy-backend": "^0.1.1-alpha.26", + "@backstage/plugin-rollbar-backend": "^0.1.1-alpha.26", + "@backstage/plugin-scaffolder-backend": "^0.1.1-alpha.26", + "@backstage/plugin-sentry-backend": "^0.1.1-alpha.26", + "@backstage/plugin-techdocs-backend": "^0.1.1-alpha.26", "@gitbeaker/node": "^23.5.0", "@octokit/rest": "^18.0.0", "azure-devops-node-api": "^10.1.1", "dockerode": "^3.2.0", - "example-app": "^0.1.1-alpha.24", + "example-app": "^0.1.1-alpha.26", "express": "^4.17.1", "express-promise-router": "^3.0.3", "knex": "^0.21.1", @@ -45,7 +45,7 @@ "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", "@types/dockerode": "^2.5.32", "@types/express": "^4.17.6", "@types/express-serve-static-core": "^4.17.5", diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts index 959af71427..b74954ecc5 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -24,17 +24,16 @@ import Router from 'express-promise-router'; import { - ensureDatabaseExists, - createDatabaseClient, createServiceBuilder, loadBackendConfig, getRootLogger, useHotMemoize, notFoundHandler, + SingleConnectionDatabaseManager, SingleHostDiscovery, UrlReaders, } from '@backstage/backend-common'; -import { ConfigReader, AppConfig } from '@backstage/config'; +import { Config } from '@backstage/config'; import healthcheck from './plugins/healthcheck'; import auth from './plugins/auth'; import catalog from './plugins/catalog'; @@ -48,37 +47,28 @@ import graphql from './plugins/graphql'; import app from './plugins/app'; import { PluginEnvironment } from './types'; -function makeCreateEnv(loadedConfigs: AppConfig[]) { - const config = ConfigReader.fromConfigs(loadedConfigs); +function makeCreateEnv(config: Config) { const root = getRootLogger(); const reader = UrlReaders.default({ logger: root, config }); const discovery = SingleHostDiscovery.fromConfig(config); root.info(`Created UrlReader ${reader}`); + const databaseManager = SingleConnectionDatabaseManager.fromConfig(config); + return (plugin: string): PluginEnvironment => { const logger = root.child({ type: 'plugin', plugin }); - const database = createDatabaseClient( - config.getConfig('backend.database'), - { - connection: { - database: `backstage_plugin_${plugin}`, - }, - }, - ); + const database = databaseManager.forPlugin(plugin); return { logger, database, config, reader, discovery }; }; } async function main() { - const configs = await loadBackendConfig(); - const configReader = ConfigReader.fromConfigs(configs); - const createEnv = makeCreateEnv(configs); - await ensureDatabaseExists( - configReader.getConfig('backend.database'), - 'backstage_plugin_catalog', - 'backstage_plugin_auth', - ); + const config = await loadBackendConfig({ + argv: process.argv, + logger: getRootLogger(), + }); + const createEnv = makeCreateEnv(config); const healthcheckEnv = useHotMemoize(module, () => createEnv('healthcheck')); const catalogEnv = useHotMemoize(module, () => createEnv('catalog')); @@ -105,7 +95,7 @@ async function main() { apiRouter.use(notFoundHandler()); const service = createServiceBuilder(module) - .loadConfig(configReader) + .loadConfig(config) .addRouter('', await healthcheck(healthcheckEnv)) .addRouter('/api', apiRouter) .addRouter('', await app(appEnv)); diff --git a/packages/backend/src/plugins/catalog.ts b/packages/backend/src/plugins/catalog.ts index c1d390f8cc..3c205a3800 100644 --- a/packages/backend/src/plugins/catalog.ts +++ b/packages/backend/src/plugins/catalog.ts @@ -14,35 +14,21 @@ * limitations under the License. */ +import { useHotCleanup } from '@backstage/backend-common'; import { + CatalogBuilder, createRouter, - DatabaseEntitiesCatalog, - DatabaseLocationsCatalog, - DatabaseManager, - HigherOrderOperations, - LocationReaders, runPeriodically, } from '@backstage/plugin-catalog-backend'; import { PluginEnvironment } from '../types'; -import { useHotCleanup } from '@backstage/backend-common'; -export default async function createPlugin({ - logger, - config, - reader, - database, -}: PluginEnvironment) { - const locationReader = new LocationReaders({ logger, reader, config }); - - const db = await DatabaseManager.createDatabase(database, { logger }); - const entitiesCatalog = new DatabaseEntitiesCatalog(db); - const locationsCatalog = new DatabaseLocationsCatalog(db); - const higherOrderOperation = new HigherOrderOperations( +export default async function createPlugin(env: PluginEnvironment) { + const builder = new CatalogBuilder(env); + const { entitiesCatalog, locationsCatalog, - locationReader, - logger, - ); + higherOrderOperation, + } = await builder.build(); useHotCleanup( module, @@ -53,6 +39,6 @@ export default async function createPlugin({ entitiesCatalog, locationsCatalog, higherOrderOperation, - logger, + logger: env.logger, }); } diff --git a/packages/backend/src/plugins/scaffolder.ts b/packages/backend/src/plugins/scaffolder.ts index c5b36ab8da..6eacd143c1 100644 --- a/packages/backend/src/plugins/scaffolder.ts +++ b/packages/backend/src/plugins/scaffolder.ts @@ -17,22 +17,11 @@ import { CookieCutter, createRouter, - FilePreparer, - GithubPreparer, - GitlabPreparer, - AzurePreparer, Preparers, Publishers, - GithubPublisher, - GitlabPublisher, - AzurePublisher, CreateReactAppTemplater, Templaters, - RepoVisibilityOptions, } from '@backstage/plugin-scaffolder-backend'; -import { Octokit } from '@octokit/rest'; -import { Gitlab } from '@gitbeaker/node'; -import { getPersonalAccessTokenHandler, WebApi } from 'azure-devops-node-api'; import type { PluginEnvironment } from '../types'; import Docker from 'dockerode'; @@ -46,108 +35,17 @@ export default async function createPlugin({ templaters.register('cookiecutter', cookiecutterTemplater); templaters.register('cra', craTemplater); - const filePreparer = new FilePreparer(); - const githubPreparer = new GithubPreparer(); - const gitlabPreparer = new GitlabPreparer(config); - const azurePreparer = new AzurePreparer(config); - const preparers = new Preparers(); - - preparers.register('file', filePreparer); - preparers.register('github', githubPreparer); - preparers.register('gitlab', gitlabPreparer); - preparers.register('gitlab/api', gitlabPreparer); - preparers.register('azure/api', azurePreparer); - - const publishers = new Publishers(); - - const githubConfig = config.getOptionalConfig('scaffolder.github'); - - if (githubConfig) { - try { - const repoVisibility = githubConfig.getString( - 'visibility', - ) as RepoVisibilityOptions; - - const githubToken = githubConfig.getString('token'); - const githubClient = new Octokit({ auth: githubToken }); - const githubPublisher = new GithubPublisher({ - client: githubClient, - token: githubToken, - repoVisibility, - }); - publishers.register('file', githubPublisher); - publishers.register('github', githubPublisher); - } catch (e) { - const providerName = 'github'; - if (process.env.NODE_ENV !== 'development') { - throw new Error( - `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, - ); - } - - logger.warn( - `Skipping ${providerName} scaffolding provider, ${e.message}`, - ); - } - } - - const gitLabConfig = config.getOptionalConfig('scaffolder.gitlab.api'); - if (gitLabConfig) { - try { - const gitLabToken = gitLabConfig.getString('token'); - const gitLabClient = new Gitlab({ - host: gitLabConfig.getOptionalString('baseUrl'), - token: gitLabToken, - }); - const gitLabPublisher = new GitlabPublisher(gitLabClient, gitLabToken); - publishers.register('gitlab', gitLabPublisher); - publishers.register('gitlab/api', gitLabPublisher); - } catch (e) { - const providerName = 'gitlab'; - if (process.env.NODE_ENV !== 'development') { - throw new Error( - `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, - ); - } - - logger.warn( - `Skipping ${providerName} scaffolding provider, ${e.message}`, - ); - } - } - - const azureConfig = config.getOptionalConfig('scaffolder.azure'); - if (azureConfig) { - try { - const baseUrl = azureConfig.getString('baseUrl'); - const azureToken = azureConfig.getConfig('api').getString('token'); - - const authHandler = getPersonalAccessTokenHandler(azureToken); - const webApi = new WebApi(baseUrl, authHandler); - const azureClient = await webApi.getGitApi(); - - const azurePublisher = new AzurePublisher(azureClient, azureToken); - publishers.register('azure/api', azurePublisher); - } catch (e) { - const providerName = 'azure'; - if (process.env.NODE_ENV !== 'development') { - throw new Error( - `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, - ); - } - - logger.warn( - `Skipping ${providerName} scaffolding provider, ${e.message}`, - ); - } - } + const preparers = await Preparers.fromConfig(config, { logger }); + const publishers = await Publishers.fromConfig(config, { logger }); const dockerClient = new Docker(); + return await createRouter({ preparers, templaters, publishers, logger, + config, dockerClient, }); } diff --git a/packages/backend/src/plugins/techdocs.ts b/packages/backend/src/plugins/techdocs.ts index e04d2a2732..dea31c763b 100644 --- a/packages/backend/src/plugins/techdocs.ts +++ b/packages/backend/src/plugins/techdocs.ts @@ -21,8 +21,7 @@ import { Generators, LocalPublish, TechdocsGenerator, - GithubPreparer, - GitlabPreparer, + CommonGitPreparer, } from '@backstage/plugin-techdocs-backend'; import { PluginEnvironment } from '../types'; import Docker from 'dockerode'; @@ -37,12 +36,13 @@ export default async function createPlugin({ generators.register('techdocs', techdocsGenerator); const preparers = new Preparers(); - const githubPreparer = new GithubPreparer(logger); - const gitlabPreparer = new GitlabPreparer(logger); + const commonGitPreparer = new CommonGitPreparer(logger); + const directoryPreparer = new DirectoryPreparer(logger); preparers.register('dir', directoryPreparer); - preparers.register('github', githubPreparer); - preparers.register('gitlab', gitlabPreparer); + preparers.register('github', commonGitPreparer); + preparers.register('gitlab', commonGitPreparer); + preparers.register('azure/api', commonGitPreparer); const publisher = new LocalPublish(logger); diff --git a/packages/backend/src/types.ts b/packages/backend/src/types.ts index 9257fcc9cf..f63b9dd780 100644 --- a/packages/backend/src/types.ts +++ b/packages/backend/src/types.ts @@ -14,14 +14,17 @@ * limitations under the License. */ -import Knex from 'knex'; import { Logger } from 'winston'; import { Config } from '@backstage/config'; -import { PluginEndpointDiscovery, UrlReader } from '@backstage/backend-common'; +import { + PluginDatabaseManager, + PluginEndpointDiscovery, + UrlReader, +} from '@backstage/backend-common'; export type PluginEnvironment = { logger: Logger; - database: Knex; + database: PluginDatabaseManager; config: Config; reader: UrlReader; discovery: PluginEndpointDiscovery; diff --git a/packages/catalog-model/examples/acme-corp.yaml b/packages/catalog-model/examples/acme-corp.yaml new file mode 100644 index 0000000000..7e5c5ebc61 --- /dev/null +++ b/packages/catalog-model/examples/acme-corp.yaml @@ -0,0 +1,9 @@ +apiVersion: backstage.io/v1alpha1 +kind: Location +metadata: + name: acme-corp + description: A collection of all Backstage example Groups +spec: + type: github + targets: + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/org.yaml diff --git a/packages/catalog-model/examples/acme/backstage-group.yaml b/packages/catalog-model/examples/acme/backstage-group.yaml new file mode 100644 index 0000000000..f992d155bc --- /dev/null +++ b/packages/catalog-model/examples/acme/backstage-group.yaml @@ -0,0 +1,11 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: backstage + description: The backstage sub-department +spec: + type: sub-department + parent: infrastructure + ancestors: [infrastructure, acme-corp] + children: [team-a, team-b] + descendants: [team-a, team-b] diff --git a/packages/catalog-model/examples/acme/boxoffice-group.yaml b/packages/catalog-model/examples/acme/boxoffice-group.yaml new file mode 100644 index 0000000000..0be1fe58cb --- /dev/null +++ b/packages/catalog-model/examples/acme/boxoffice-group.yaml @@ -0,0 +1,11 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: boxoffice + description: The boxoffice sub-department +spec: + type: sub-department + parent: infrastructure + ancestors: [infrastructure, acme-corp] + children: [team-c, team-d] + descendants: [team-c, team-d] diff --git a/packages/catalog-model/examples/acme/infrastructure-group.yaml b/packages/catalog-model/examples/acme/infrastructure-group.yaml new file mode 100644 index 0000000000..2341782944 --- /dev/null +++ b/packages/catalog-model/examples/acme/infrastructure-group.yaml @@ -0,0 +1,11 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: infrastructure + description: The infra department +spec: + type: department + parent: acme-corp + ancestors: [acme-corp] + children: [backstage, boxoffice] + descendants: [backstage, boxoffice, team-a, team-b, team-c, team-d] diff --git a/packages/catalog-model/examples/acme/org.yaml b/packages/catalog-model/examples/acme/org.yaml new file mode 100644 index 0000000000..2d6a6a2666 --- /dev/null +++ b/packages/catalog-model/examples/acme/org.yaml @@ -0,0 +1,27 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: acme-corp + description: The acme-corp organization +spec: + type: organization + ancestors: [] + children: [infrastructure] + descendants: + [infrastructure, backstage, boxoffice, team-a, team-b, team-c, team-d] +--- +apiVersion: backstage.io/v1alpha1 +kind: Location +metadata: + name: example-groups + description: A collection of all Backstage example Groups +spec: + type: github + targets: + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/infrastructure-group.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/boxoffice-group.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/backstage-group.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/team-a-group.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/team-b-group.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/team-c-group.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/acme/team-d-group.yaml diff --git a/packages/catalog-model/examples/acme/team-a-group.yaml b/packages/catalog-model/examples/acme/team-a-group.yaml new file mode 100644 index 0000000000..dacc4c6c3c --- /dev/null +++ b/packages/catalog-model/examples/acme/team-a-group.yaml @@ -0,0 +1,44 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: team-a + description: Team A +spec: + type: team + parent: backstage + ancestors: [backstage, infrastructure, acme-corp] + children: [] + descendants: [] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: breanna.davison +spec: + profile: + displayName: Breanna Davison + email: breanna-davison@example.com + picture: https://example.com/staff/breanna.jpeg + memberOf: [team-a] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: janelle.dawe +spec: + profile: + displayName: Janelle Dawe + email: janelle-dawe@example.com + picture: https://example.com/staff/janelle.jpeg + memberOf: [team-a] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: nigel.manning +spec: + profile: + displayName: Nigel Manning + email: nigel-manning@example.com + picture: https://example.com/staff/nigel.jpeg + memberOf: [team-a] diff --git a/packages/catalog-model/examples/acme/team-b-group.yaml b/packages/catalog-model/examples/acme/team-b-group.yaml new file mode 100644 index 0000000000..00e9e41d80 --- /dev/null +++ b/packages/catalog-model/examples/acme/team-b-group.yaml @@ -0,0 +1,66 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: team-b + description: Team B +spec: + type: team + parent: backstage + ancestors: [backstage, infrastructure, acme-corp] + children: [] + descendants: [] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: amelia.park +spec: + profile: + displayName: Amelia Park + email: amelia-park@example.com + picture: https://example.com/staff/amelia.jpeg + memberOf: [team-b] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: colette.brock +spec: + profile: + displayName: Colette Brock + email: colette-brock@example.com + picture: https://example.com/staff/colette.jpeg + memberOf: [team-b] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: jenny.doe +spec: + profile: + displayName: Jenny Doe + email: jenny-doe@example.com + picture: https://example.com/staff/jenny.jpeg + memberOf: [team-b] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: jonathon.page +spec: + profile: + displayName: Jonathon Page + email: jonathon-page@example.com + picture: https://example.com/staff/jonathon.jpeg + memberOf: [team-b] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: justine.barrow +spec: + profile: + displayName: Justine Barrow + email: justine-barrow@example.com + picture: https://example.com/staff/justine.jpeg + memberOf: [team-b] diff --git a/packages/catalog-model/examples/acme/team-c-group.yaml b/packages/catalog-model/examples/acme/team-c-group.yaml new file mode 100644 index 0000000000..0f97f69cb3 --- /dev/null +++ b/packages/catalog-model/examples/acme/team-c-group.yaml @@ -0,0 +1,66 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: team-c + description: Team C +spec: + type: team + parent: boxoffice + ancestors: [boxoffice, infrastructure, acme-corp] + children: [] + descendants: [] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: calum.leavy +spec: + profile: + displayName: Calum Leavy + email: calum-leavy@example.com + picture: https://example.com/staff/calum.jpeg + memberOf: [team-c] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: frank.tiernan +spec: + profile: + displayName: Frank Tiernan + email: frank-tiernan@example.com + picture: https://example.com/staff/frank.jpeg + memberOf: [team-c] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: peadar.macmahon +spec: + profile: + displayName: Peadar MacMahon + email: peadar-macmahon@example.com + picture: https://example.com/staff/peadar.jpeg + memberOf: [team-c] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: sarah.gilroy +spec: + profile: + displayName: Sarah Gilroy + email: sarah-gilroy@example.com + picture: https://example.com/staff/sarah.jpeg + memberOf: [team-c] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: tara.macgovern +spec: + profile: + displayName: Tara MacGovern + email: tara-macgovern@example.com + picture: https://example.com/staff/tara.jpeg + memberOf: [team-c] diff --git a/packages/catalog-model/examples/acme/team-d-group.yaml b/packages/catalog-model/examples/acme/team-d-group.yaml new file mode 100644 index 0000000000..5a1a53a2e6 --- /dev/null +++ b/packages/catalog-model/examples/acme/team-d-group.yaml @@ -0,0 +1,33 @@ +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: team-d + description: Team D +spec: + type: team + parent: boxoffice + ancestors: [boxoffice, infrastructure, acme-corp] + children: [] + descendants: [] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: eva.macdowell +spec: + profile: + displayName: Eva MacDowell + email: eva-macdowell@example.com + picture: https://example.com/staff/eva.jpeg + memberOf: [team-d] +--- +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: lucy.sheehan +spec: + profile: + displayName: Lucy Sheehan + email: lucy-sheehan@example.com + picture: https://example.com/staff/lucy.jpeg + memberOf: [team-d] diff --git a/packages/catalog-model/examples/all-apis.yaml b/packages/catalog-model/examples/all-apis.yaml index 3c4f7804bf..64586fdddd 100644 --- a/packages/catalog-model/examples/all-apis.yaml +++ b/packages/catalog-model/examples/all-apis.yaml @@ -6,7 +6,8 @@ metadata: spec: type: github targets: - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/hello-world-api.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/streetlights-api.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/spotify-api.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/swapi-graphql.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/apis/hello-world-api.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/apis/petstore-api.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/apis/spotify-api.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/apis/streetlights-api.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/apis/swapi-graphql.yaml diff --git a/packages/catalog-model/examples/all-components.yaml b/packages/catalog-model/examples/all-components.yaml index cad4eee044..bef38df0b1 100644 --- a/packages/catalog-model/examples/all-components.yaml +++ b/packages/catalog-model/examples/all-components.yaml @@ -6,11 +6,12 @@ metadata: spec: type: github targets: - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/artist-lookup-component.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/playback-order-component.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/podcast-api-component.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/queue-proxy-component.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/searcher-component.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/playback-lib-component.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/www-artist-component.yaml - - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/shuffle-api-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/artist-lookup-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/petstore-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/playback-order-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/podcast-api-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/queue-proxy-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/searcher-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/playback-lib-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/www-artist-component.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/components/shuffle-api-component.yaml diff --git a/packages/catalog-model/examples/hello-world-api.yaml b/packages/catalog-model/examples/apis/hello-world-api.yaml similarity index 100% rename from packages/catalog-model/examples/hello-world-api.yaml rename to packages/catalog-model/examples/apis/hello-world-api.yaml diff --git a/packages/catalog-model/examples/petstore-api.yaml b/packages/catalog-model/examples/apis/petstore-api.yaml similarity index 100% rename from packages/catalog-model/examples/petstore-api.yaml rename to packages/catalog-model/examples/apis/petstore-api.yaml diff --git a/packages/catalog-model/examples/spotify-api.yaml b/packages/catalog-model/examples/apis/spotify-api.yaml similarity index 64% rename from packages/catalog-model/examples/spotify-api.yaml rename to packages/catalog-model/examples/apis/spotify-api.yaml index 30524dfdd4..14deb17abe 100644 --- a/packages/catalog-model/examples/spotify-api.yaml +++ b/packages/catalog-model/examples/apis/spotify-api.yaml @@ -7,8 +7,11 @@ metadata: - spotify - rest annotations: + # The annotation is deprecated, we use placeholders (see below) instead, remove it later. backstage.io/definition-at-location: 'url:https://raw.githubusercontent.com/APIs-guru/openapi-directory/master/APIs/spotify.com/v1/swagger.yaml' spec: type: openapi lifecycle: production owner: spotify@example.com + definition: + $text: https://github.com/APIs-guru/openapi-directory/blob/master/APIs/spotify.com/v1/swagger.yaml diff --git a/packages/catalog-model/examples/streetlights-api.yaml b/packages/catalog-model/examples/apis/streetlights-api.yaml similarity index 100% rename from packages/catalog-model/examples/streetlights-api.yaml rename to packages/catalog-model/examples/apis/streetlights-api.yaml diff --git a/packages/catalog-model/examples/swapi-graphql.yaml b/packages/catalog-model/examples/apis/swapi-graphql.yaml similarity index 99% rename from packages/catalog-model/examples/swapi-graphql.yaml rename to packages/catalog-model/examples/apis/swapi-graphql.yaml index 152d9c0afa..bc5e8e60ac 100644 --- a/packages/catalog-model/examples/swapi-graphql.yaml +++ b/packages/catalog-model/examples/apis/swapi-graphql.yaml @@ -5,6 +5,8 @@ metadata: description: SWAPI GraphQL Schema spec: type: graphql + lifecycle: production + owner: yoda@dagobah.space definition: | schema { query: Root diff --git a/packages/catalog-model/examples/artist-lookup-component.yaml b/packages/catalog-model/examples/components/artist-lookup-component.yaml similarity index 100% rename from packages/catalog-model/examples/artist-lookup-component.yaml rename to packages/catalog-model/examples/components/artist-lookup-component.yaml diff --git a/packages/catalog-model/examples/petstore-component.yaml b/packages/catalog-model/examples/components/petstore-component.yaml similarity index 100% rename from packages/catalog-model/examples/petstore-component.yaml rename to packages/catalog-model/examples/components/petstore-component.yaml diff --git a/packages/catalog-model/examples/playback-lib-component.yaml b/packages/catalog-model/examples/components/playback-lib-component.yaml similarity index 100% rename from packages/catalog-model/examples/playback-lib-component.yaml rename to packages/catalog-model/examples/components/playback-lib-component.yaml diff --git a/packages/catalog-model/examples/playback-order-component.yaml b/packages/catalog-model/examples/components/playback-order-component.yaml similarity index 100% rename from packages/catalog-model/examples/playback-order-component.yaml rename to packages/catalog-model/examples/components/playback-order-component.yaml diff --git a/packages/catalog-model/examples/podcast-api-component.yaml b/packages/catalog-model/examples/components/podcast-api-component.yaml similarity index 100% rename from packages/catalog-model/examples/podcast-api-component.yaml rename to packages/catalog-model/examples/components/podcast-api-component.yaml diff --git a/packages/catalog-model/examples/queue-proxy-component.yaml b/packages/catalog-model/examples/components/queue-proxy-component.yaml similarity index 100% rename from packages/catalog-model/examples/queue-proxy-component.yaml rename to packages/catalog-model/examples/components/queue-proxy-component.yaml diff --git a/packages/catalog-model/examples/searcher-component.yaml b/packages/catalog-model/examples/components/searcher-component.yaml similarity index 100% rename from packages/catalog-model/examples/searcher-component.yaml rename to packages/catalog-model/examples/components/searcher-component.yaml diff --git a/packages/catalog-model/examples/shuffle-api-component.yaml b/packages/catalog-model/examples/components/shuffle-api-component.yaml similarity index 100% rename from packages/catalog-model/examples/shuffle-api-component.yaml rename to packages/catalog-model/examples/components/shuffle-api-component.yaml diff --git a/packages/catalog-model/examples/www-artist-component.yaml b/packages/catalog-model/examples/components/www-artist-component.yaml similarity index 100% rename from packages/catalog-model/examples/www-artist-component.yaml rename to packages/catalog-model/examples/components/www-artist-component.yaml diff --git a/packages/catalog-model/package.json b/packages/catalog-model/package.json index 6a543f7f84..c97aea9572 100644 --- a/packages/catalog-model/package.json +++ b/packages/catalog-model/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/catalog-model", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,16 +20,16 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/config": "^0.1.1-alpha.24", + "@backstage/config": "^0.1.1-alpha.26", "@types/json-schema": "^7.0.5", - "@types/yup": "^0.28.2", + "@types/yup": "^0.29.8", "json-schema": "^0.2.5", "lodash": "^4.17.15", "uuid": "^8.0.0", - "yup": "^0.29.1" + "yup": "^0.29.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", "@types/express": "^4.17.6", "@types/jest": "^26.0.7", "@types/lodash": "^4.14.151", diff --git a/packages/catalog-model/src/EntityPolicies.test.ts b/packages/catalog-model/src/EntityPolicies.test.ts new file mode 100644 index 0000000000..cd869f798c --- /dev/null +++ b/packages/catalog-model/src/EntityPolicies.test.ts @@ -0,0 +1,110 @@ +import { Entity } from './entity'; +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { EntityPolicies } from './EntityPolicies'; +import { EntityPolicy } from './types'; + +describe('EntityPolicies', () => { + const p1: jest.Mocked = { enforce: jest.fn() }; + const p2: jest.Mocked = { enforce: jest.fn() }; + const entity1: Entity = { + apiVersion: 'a1', + kind: 'k1', + metadata: { name: 'n1' }, + }; + const entity2: Entity = { + apiVersion: 'a2', + kind: 'k2', + metadata: { name: 'n2' }, + }; + + afterEach(() => jest.resetAllMocks()); + + describe('allOf', () => { + it('resolves when no policies', async () => { + const policy = EntityPolicies.allOf([]); + await expect(policy.enforce(entity1)).resolves.toBe(entity1); + }); + + it('resolves when all resolve', async () => { + p1.enforce.mockResolvedValue(entity1); + p2.enforce.mockResolvedValue(entity1); + const policy = EntityPolicies.allOf([p1, p2]); + await expect(policy.enforce(entity1)).resolves.toBe(entity1); + }); + + it('rejects when any rejects', async () => { + p1.enforce.mockResolvedValue(entity1); + p2.enforce.mockRejectedValue(new Error('a')); + const policy = EntityPolicies.allOf([p1, p2]); + await expect(policy.enforce(entity1)).rejects.toThrow('a'); + }); + + it('rejects when any ignores', async () => { + p1.enforce.mockResolvedValue(entity1); + p2.enforce.mockResolvedValue(undefined); + const policy = EntityPolicies.allOf([p1, p2]); + await expect(policy.enforce(entity1)).rejects.toThrow( + /did not return a result/, + ); + }); + + it('passes through transforms properly', async () => { + p1.enforce.mockResolvedValue(entity2); + p2.enforce.mockResolvedValue(entity2); + const policy = EntityPolicies.allOf([p1, p2]); + await expect(policy.enforce(entity1)).resolves.toBe(entity2); + expect(p1.enforce).toBeCalledWith(entity1); + expect(p2.enforce).toBeCalledWith(entity2); + }); + }); + + describe('oneOf', () => { + it('rejects when no policies', async () => { + const policy = EntityPolicies.oneOf([]); + await expect(policy.enforce(entity1)).rejects.toThrow(/did not match/); + }); + + it('resolves when one resolves', async () => { + p1.enforce.mockResolvedValue(undefined); + p2.enforce.mockResolvedValue(entity1); + const policy = EntityPolicies.oneOf([p1, p2]); + await expect(policy.enforce(entity1)).resolves.toBe(entity1); + }); + + it('rejects when one rejects first', async () => { + p1.enforce.mockRejectedValue(new Error('a')); + p2.enforce.mockResolvedValue(entity1); + const policy = EntityPolicies.oneOf([p1, p2]); + await expect(policy.enforce(entity1)).rejects.toThrow('a'); + }); + + it('resolves first resolution when several resolve', async () => { + p1.enforce.mockResolvedValue(entity1); + p2.enforce.mockResolvedValue(entity2); + const policy = EntityPolicies.oneOf([p1, p2]); + await expect(policy.enforce(entity1)).resolves.toBe(entity1); + }); + + it('rejects when all ignore', async () => { + p1.enforce.mockResolvedValue(undefined); + p2.enforce.mockResolvedValue(undefined); + const policy = EntityPolicies.oneOf([p1, p2]); + await expect(policy.enforce(entity1)).rejects.toThrow(/did not match/); + }); + }); +}); diff --git a/packages/catalog-model/src/EntityPolicies.ts b/packages/catalog-model/src/EntityPolicies.ts index ca59338c16..1f304f8f27 100644 --- a/packages/catalog-model/src/EntityPolicies.ts +++ b/packages/catalog-model/src/EntityPolicies.ts @@ -14,22 +14,7 @@ * limitations under the License. */ -import { - DefaultNamespaceEntityPolicy, - Entity, - FieldFormatEntityPolicy, - NoForeignRootFieldsEntityPolicy, - ReservedFieldsEntityPolicy, - SchemaValidEntityPolicy, -} from './entity'; -import { - apiEntityV1alpha1Policy, - componentEntityV1alpha1Policy, - groupEntityV1alpha1Policy, - locationEntityV1alpha1Policy, - templateEntityV1alpha1Policy, - userEntityV1alpha1Policy, -} from './kinds'; +import { Entity } from './entity'; import { EntityPolicy } from './types'; // Helper that requires that all of a set of policies can be successfully @@ -40,10 +25,13 @@ class AllEntityPolicies implements EntityPolicy { async enforce(entity: Entity): Promise { let result = entity; for (const policy of this.policies) { - const output = await policy.enforce(entity); - if (output) { - result = output; + const output = await policy.enforce(result); + if (!output) { + throw new Error( + `Policy ${policy.constructor.name} did not return a result`, + ); } + result = output; } return result; } @@ -54,10 +42,10 @@ class AllEntityPolicies implements EntityPolicy { class AnyEntityPolicy implements EntityPolicy { constructor(private readonly policies: EntityPolicy[]) {} - async enforce(entity: Entity): Promise { + async enforce(entity: Entity): Promise { for (const policy of this.policies) { const output = await policy.enforce(entity); - if (output !== null) { + if (output) { return output; } } @@ -65,42 +53,11 @@ class AnyEntityPolicy implements EntityPolicy { } } -export class EntityPolicies implements EntityPolicy { - private readonly policy: EntityPolicy; - - static defaultPolicies(): EntityPolicy { - return EntityPolicies.allOf([ - EntityPolicies.allOf([ - new SchemaValidEntityPolicy(), - new DefaultNamespaceEntityPolicy(), - new NoForeignRootFieldsEntityPolicy(), - new FieldFormatEntityPolicy(), - new ReservedFieldsEntityPolicy(), - ]), - EntityPolicies.anyOf([ - componentEntityV1alpha1Policy, - groupEntityV1alpha1Policy, - userEntityV1alpha1Policy, - locationEntityV1alpha1Policy, - templateEntityV1alpha1Policy, - apiEntityV1alpha1Policy, - ]), - ]); - } - - static allOf(policies: EntityPolicy[]): EntityPolicy { +export const EntityPolicies = { + allOf(policies: EntityPolicy[]) { return new AllEntityPolicies(policies); - } - - static anyOf(policies: EntityPolicy[]): EntityPolicy { + }, + oneOf(policies: EntityPolicy[]) { return new AnyEntityPolicy(policies); - } - - constructor(policy: EntityPolicy = EntityPolicies.defaultPolicies()) { - this.policy = policy; - } - - enforce(entity: Entity): Promise { - return this.policy.enforce(entity); - } -} + }, +}; diff --git a/packages/catalog-model/src/entity/Entity.ts b/packages/catalog-model/src/entity/Entity.ts index 9e0aec7de6..ac43137546 100644 --- a/packages/catalog-model/src/entity/Entity.ts +++ b/packages/catalog-model/src/entity/Entity.ts @@ -15,6 +15,7 @@ */ import { JsonObject } from '@backstage/config'; +import { EntityName } from '../types'; /** * The format envelope that's common to all versions/kinds of entity. @@ -42,6 +43,11 @@ export type Entity = { * The specification data describing the entity itself. */ spec?: JsonObject; + + /** + * The relations that this entity has with other entities. + */ + relations?: EntityRelation[]; }; /** @@ -120,3 +126,38 @@ export type EntityMeta = JsonObject & { */ tags?: string[]; }; + +/** + * A relation of a specific type to another entity in the catalog. + */ +export type EntityRelation = { + /** + * The type of the relation. + */ + type: string; + + /** + * The target entity of this relation. + */ + target: EntityName; +}; + +/** + * Holds the relation data for entities. + */ +export type EntityRelationSpec = { + /** + * The source entity of this relation. + */ + source: EntityName; + + /** + * The type of the relation. + */ + type: string; + + /** + * The target entity of this relation. + */ + target: EntityName; +}; diff --git a/packages/catalog-model/src/entity/index.ts b/packages/catalog-model/src/entity/index.ts index 759a94ca67..d450119f0a 100644 --- a/packages/catalog-model/src/entity/index.ts +++ b/packages/catalog-model/src/entity/index.ts @@ -18,7 +18,12 @@ export { ENTITY_DEFAULT_NAMESPACE, ENTITY_META_GENERATED_FIELDS, } from './constants'; -export type { Entity, EntityMeta } from './Entity'; +export type { + Entity, + EntityMeta, + EntityRelation, + EntityRelationSpec, +} from './Entity'; export * from './policies'; export { getEntityName, diff --git a/packages/catalog-model/src/entity/policies/FieldFormatEntityPolicy.ts b/packages/catalog-model/src/entity/policies/FieldFormatEntityPolicy.ts index 20a3724079..7193c1a89b 100644 --- a/packages/catalog-model/src/entity/policies/FieldFormatEntityPolicy.ts +++ b/packages/catalog-model/src/entity/policies/FieldFormatEntityPolicy.ts @@ -15,7 +15,12 @@ */ import { EntityPolicy } from '../../types'; -import { makeValidator, Validators } from '../../validation'; +import { + CommonValidatorFunctions, + KubernetesValidatorFunctions, + makeValidator, + Validators, +} from '../../validation'; import { Entity } from '../Entity'; /** @@ -50,7 +55,47 @@ export class FieldFormatEntityPolicy implements EntityPolicy { } if (!isValid) { - throw new Error(`${field} "${value}" is not valid`); + let expectation; + switch ( + validator.name as + | keyof typeof KubernetesValidatorFunctions + | keyof typeof CommonValidatorFunctions + ) { + case 'isValidLabelValue': + case 'isValidObjectName': + expectation = + 'a string that is sequences of [a-zA-Z0-9] separated by any of [-_.], at most 63 characters in total'; + break; + case 'isValidLabelKey': + case 'isValidApiVersion': + case 'isValidAnnotationKey': + expectation = 'a valid prefix and/or suffix'; + break; + case 'isValidNamespace': + case 'isValidDnsLabel': + expectation = + 'a string that is sequences of [a-zA-Z0-9] separated by [-], at most 63 characters in total'; + break; + case 'isValidAnnotationValue': + expectation = 'a string'; + break; + case 'isValidKind': + expectation = + 'a string that is a sequence of [a-zA-Z][a-z0-9A-Z], at most 63 characters in total'; + break; + default: + expectation = undefined; + break; + } + + // ensure that if there are other/future validators, the error message defaults to a general "is not valid, visit link" + const message = expectation + ? ` expected ${expectation} but found "${value}".` + : ''; + + throw new Error( + `"${field}" is not valid;${message} To learn more about catalog file format, visit: https://github.com/spotify/backstage/blob/master/docs/architecture-decisions/adr002-default-catalog-file-format.md`, + ); } } diff --git a/packages/catalog-model/src/entity/policies/ReservedFieldsEntityPolicy.test.ts b/packages/catalog-model/src/entity/policies/ReservedFieldsEntityPolicy.test.ts deleted file mode 100644 index 5d4e60a1a3..0000000000 --- a/packages/catalog-model/src/entity/policies/ReservedFieldsEntityPolicy.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import yaml from 'yaml'; -import { ReservedFieldsEntityPolicy } from './ReservedFieldsEntityPolicy'; - -describe('ReservedFieldsEntityPolicy', () => { - let data: any; - let policy: ReservedFieldsEntityPolicy; - - beforeEach(() => { - data = yaml.parse(` - apiVersion: backstage.io/v1alpha1 - kind: Component - metadata: - uid: e01199ab-08cc-44c2-8e19-5c29ded82521 - etag: lsndfkjsndfkjnsdfkjnsd== - generation: 13 - name: my-component-yay - namespace: the-namespace - labels: - backstage.io/custom: ValueStuff - annotations: - example.com/bindings: are-secret - tags: - - java - - data - spec: - custom: stuff - `); - policy = new ReservedFieldsEntityPolicy(); - }); - - it('works for the happy path', async () => { - await expect(policy.enforce(data)).resolves.toBe(data); - }); - - it('rejects reserved keys in the spec root', async () => { - data.spec.apiVersion = 'a/b'; - await expect(policy.enforce(data)).rejects.toThrow(/spec.*apiVersion/i); - }); - - it('rejects reserved keys in labels', async () => { - data.metadata.labels.apiVersion = 'a'; - await expect(policy.enforce(data)).rejects.toThrow(/label.*apiVersion/i); - }); - - it('rejects reserved keys in annotations', async () => { - data.metadata.annotations.apiVersion = 'a'; - await expect(policy.enforce(data)).rejects.toThrow( - /annotation.*apiVersion/i, - ); - }); - - it('rejects core fields mistakenly placed in metadata', async () => { - data.metadata.owner = 'emma'; - await expect(policy.enforce(data)).rejects.toThrow(/owner/i); - }); -}); diff --git a/packages/catalog-model/src/entity/policies/ReservedFieldsEntityPolicy.ts b/packages/catalog-model/src/entity/policies/ReservedFieldsEntityPolicy.ts deleted file mode 100644 index edb63cf05c..0000000000 --- a/packages/catalog-model/src/entity/policies/ReservedFieldsEntityPolicy.ts +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { EntityPolicy } from '../../types'; -import { Entity } from '../Entity'; - -const DEFAULT_RESERVED_ENTITY_FIELDS: string[] = [ - 'apiVersion', - 'kind', - 'spec', - 'metadata.uid', - 'metadata.etag', - 'metadata.generation', - 'metadata.name', - 'metadata.namespace', - 'metadata.description', - 'metadata.labels', - 'metadata.annotations', - 'metadata.tags', - // The below items are known to appear in core kinds, and therefore should - // not be appearing in metadata (which would indicate that the user made a - // mistake in where to place them). - 'spec.lifecycle', - 'spec.owner', -]; - -/** - * Ensures that fields are not given certain reserved names. - */ -export class ReservedFieldsEntityPolicy implements EntityPolicy { - private readonly reservedFields: string[]; - - constructor(fields?: string[]) { - this.reservedFields = [ - ...(fields ?? []), - ...DEFAULT_RESERVED_ENTITY_FIELDS, - ]; - } - - async enforce(entity: Entity): Promise { - for (const path of this.reservedFields) { - const [where, name] = path.includes('.') - ? path.split('.') - : [undefined, path]; - - if (where !== 'metadata' && entity.metadata.hasOwnProperty(name)) { - throw new Error( - `The metadata may not contain the field ${name}, because it has reserved meaning`, - ); - } - if (where !== 'spec' && entity.spec?.hasOwnProperty(name)) { - throw new Error( - `The spec may not contain the field ${name}, because it has reserved meaning`, - ); - } - if (where !== 'labels' && entity.metadata.labels?.hasOwnProperty(name)) { - throw new Error( - `A label may not have the field ${name}, because it has reserved meaning`, - ); - } - if ( - where !== 'annotations' && - entity.metadata.annotations?.hasOwnProperty(name) - ) { - throw new Error( - `An annotation may not have the field ${name}, because it has reserved meaning`, - ); - } - } - return entity; - } -} diff --git a/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.ts b/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.ts index a6d376b4ac..4ff73e9a49 100644 --- a/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.ts +++ b/packages/catalog-model/src/entity/policies/SchemaValidEntityPolicy.ts @@ -18,24 +18,26 @@ import * as yup from 'yup'; import { EntityPolicy } from '../../types'; import { Entity } from '../Entity'; -const DEFAULT_ENTITY_SCHEMA = yup.object({ - apiVersion: yup.string().required(), - kind: yup.string().required(), - metadata: yup - .object({ - uid: yup.string().notRequired().min(1), - etag: yup.string().notRequired().min(1), - generation: yup.number().notRequired().integer().min(1), - name: yup.string().required(), - namespace: yup.string().notRequired(), - description: yup.string().notRequired(), - labels: yup.object>().notRequired(), - annotations: yup.object>().notRequired(), - tags: yup.array().notRequired(), - }) - .required(), - spec: yup.object({}).notRequired(), -}); +const DEFAULT_ENTITY_SCHEMA = yup + .object({ + apiVersion: yup.string().required(), + kind: yup.string().required(), + metadata: yup + .object({ + uid: yup.string().notRequired().min(1), + etag: yup.string().notRequired().min(1), + generation: yup.number().notRequired().integer().min(1), + name: yup.string().required(), + namespace: yup.string().notRequired(), + description: yup.string().notRequired(), + labels: yup.object>().notRequired(), + annotations: yup.object>().notRequired(), + tags: yup.array().notRequired(), + }) + .required(), + spec: yup.object({}).notRequired(), + }) + .required(); /** * Ensures that the entity spec is valid according to a schema. diff --git a/packages/catalog-model/src/entity/policies/index.ts b/packages/catalog-model/src/entity/policies/index.ts index eb7c0e8378..c381d29a23 100644 --- a/packages/catalog-model/src/entity/policies/index.ts +++ b/packages/catalog-model/src/entity/policies/index.ts @@ -17,5 +17,4 @@ export { DefaultNamespaceEntityPolicy } from './DefaultNamespaceEntityPolicy'; export { FieldFormatEntityPolicy } from './FieldFormatEntityPolicy'; export { NoForeignRootFieldsEntityPolicy } from './NoForeignRootFieldsEntityPolicy'; -export { ReservedFieldsEntityPolicy } from './ReservedFieldsEntityPolicy'; export { SchemaValidEntityPolicy } from './SchemaValidEntityPolicy'; diff --git a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts index 57d6d47388..11434937cd 100644 --- a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts @@ -101,4 +101,24 @@ describe('ComponentV1alpha1Policy', () => { (entity as any).spec.owner = ''; await expect(policy.enforce(entity)).rejects.toThrow(/owner/); }); + + it('accepts missing implementsApis', async () => { + delete (entity as any).spec.implementsApis; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + it('rejects empty implementsApis', async () => { + (entity as any).spec.implementsApis = ['']; + await expect(policy.enforce(entity)).rejects.toThrow(/implementsApis/); + }); + + it('rejects undefined implementsApis', async () => { + (entity as any).spec.implementsApis = [undefined]; + await expect(policy.enforce(entity)).rejects.toThrow(/implementsApis/); + }); + + it('accepts no implementsApis', async () => { + (entity as any).spec.implementsApis = []; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); }); diff --git a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts index 9efc491ca9..662ce28b52 100644 --- a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts @@ -29,7 +29,7 @@ const schema = yup.object>({ type: yup.string().required().min(1), lifecycle: yup.string().required().min(1), owner: yup.string().required().min(1), - implementsApis: yup.array(yup.string()).notRequired(), + implementsApis: yup.array(yup.string().required()).notRequired(), }) .required(), }); diff --git a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts index dc0ecd3fa3..9137727c6e 100644 --- a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts @@ -90,9 +90,14 @@ describe('GroupV1alpha1Policy', () => { await expect(policy.enforce(entity)).rejects.toThrow(/ancestor/); }); - it('accepts empty ancestors', async () => { + it('rejects empty ancestors', async () => { (entity as any).spec.ancestors = ['']; - await expect(policy.enforce(entity)).resolves.toBe(entity); + await expect(policy.enforce(entity)).rejects.toThrow(/ancestor/); + }); + + it('rejects undefined ancestors', async () => { + (entity as any).spec.ancestors = [undefined]; + await expect(policy.enforce(entity)).rejects.toThrow(/ancestor/); }); it('accepts no ancestors', async () => { @@ -105,9 +110,14 @@ describe('GroupV1alpha1Policy', () => { await expect(policy.enforce(entity)).rejects.toThrow(/children/); }); - it('accepts empty children', async () => { + it('rejects empty children', async () => { (entity as any).spec.children = ['']; - await expect(policy.enforce(entity)).resolves.toBe(entity); + await expect(policy.enforce(entity)).rejects.toThrow(/children/); + }); + + it('rejects undefined children', async () => { + (entity as any).spec.children = [undefined]; + await expect(policy.enforce(entity)).rejects.toThrow(/children/); }); it('accepts no children', async () => { @@ -120,9 +130,14 @@ describe('GroupV1alpha1Policy', () => { await expect(policy.enforce(entity)).rejects.toThrow(/descendants/); }); - it('accepts empty descendants', async () => { + it('rejects empty descendants', async () => { (entity as any).spec.descendants = ['']; - await expect(policy.enforce(entity)).resolves.toBe(entity); + await expect(policy.enforce(entity)).rejects.toThrow(/descendants/); + }); + + it('rejects undefined descendants', async () => { + (entity as any).spec.descendants = [undefined]; + await expect(policy.enforce(entity)).rejects.toThrow(/descendants/); }); it('accepts no descendants', async () => { diff --git a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts index 073332d707..f0e91ddce8 100644 --- a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts @@ -30,21 +30,23 @@ const schema = yup.object>({ parent: yup.string().notRequired().min(1), // Use these manual tests because yup .required() requires at least // one element and there is no simple workaround -_- - ancestors: yup.array(yup.string()).test({ + // the cast is there to convince typescript that the array itself is + // required without using .required() + ancestors: yup.array(yup.string().required()).test({ name: 'isDefined', message: 'ancestors must be defined', test: v => Boolean(v), - }), - children: yup.array(yup.string()).test({ + }) as yup.ArraySchema, + children: yup.array(yup.string().required()).test({ name: 'isDefined', message: 'children must be defined', test: v => Boolean(v), - }), - descendants: yup.array(yup.string()).test({ + }) as yup.ArraySchema, + descendants: yup.array(yup.string().required()).test({ name: 'isDefined', message: 'descendants must be defined', test: v => Boolean(v), - }), + }) as yup.ArraySchema, }) .required(), }); diff --git a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts index a259eaeca8..865ceda53e 100644 --- a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts @@ -93,6 +93,11 @@ describe('LocationV1alpha1Policy', () => { await expect(policy.enforce(entity)).resolves.toBe(entity); }); + it('accepts empty targets', async () => { + (entity as any).spec.targets = []; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + it('rejects wrong targets', async () => { (entity as any).spec.targets = 7; await expect(policy.enforce(entity)).rejects.toThrow(/targets/); diff --git a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts index 6d1f1f5515..dc2485f11b 100644 --- a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts @@ -28,7 +28,7 @@ const schema = yup.object>({ .object({ type: yup.string().required().min(1), target: yup.string().notRequired().min(1), - targets: yup.array(yup.string()).notRequired(), + targets: yup.array(yup.string().required()).notRequired(), }) .required(), }); diff --git a/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts b/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts index ff4edcc8a2..6086b3776e 100644 --- a/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts @@ -35,11 +35,13 @@ const schema = yup.object>({ .notRequired(), // Use this manual test because yup .required() requires at least one // element and there is no simple workaround -_- - memberOf: yup.array(yup.string()).test({ + // the cast is there to convince typescript that the array itself is + // required without using .required() + memberOf: yup.array(yup.string().required()).test({ name: 'isDefined', message: 'memberOf must be defined', test: v => Boolean(v), - }), + }) as yup.ArraySchema, }) .required(), }); diff --git a/packages/catalog-model/src/kinds/index.ts b/packages/catalog-model/src/kinds/index.ts index 6df4f1212a..4a3faf977b 100644 --- a/packages/catalog-model/src/kinds/index.ts +++ b/packages/catalog-model/src/kinds/index.ts @@ -44,3 +44,4 @@ export type { UserEntityV1alpha1 as UserEntity, UserEntityV1alpha1, } from './UserEntityV1alpha1'; +export * from './relations'; diff --git a/packages/catalog-model/src/kinds/relations.ts b/packages/catalog-model/src/kinds/relations.ts new file mode 100644 index 0000000000..846313ec8c --- /dev/null +++ b/packages/catalog-model/src/kinds/relations.ts @@ -0,0 +1,55 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* +Naming rules for relations in priority order: + +1. Use at most two words. One main verb and a specifier, e.g. "ownerOf" +2. Reading out " " should make sense in English. +3. Maintain symmetry between pairs, e.g. "ownedBy" and "ownerOf" rather than "owns". +*/ + +/** + * An ownership relation where the owner is usually an organizational + * entity (user or group), and the other entity can be anything. + */ +export const RELATION_OWNED_BY = 'ownedBy'; +export const RELATION_OWNER_OF = 'ownerOf'; + +/** + * A relation with an API entity, typically from a component or system + */ +export const RELATION_CONSUMES_API = 'consumesApi'; +export const RELATION_PROVIDES_API = 'providesApi'; + +/** + * A relation denoting a dependency on another entity. + */ +export const RELATION_DEPENDS_ON = 'dependsOn'; +export const RELATION_DEPENDENCY_OF = 'dependencyOf'; + +/** + * A parent/child relation to build up a tree, used for example to describe + * the organizational structure between groups. + */ +export const RELATION_PARENT_OF = 'parentOf'; +export const RELATION_CHILD_OF = 'childOf'; + +/** + * A membership relation, typically for users in a group. + */ +export const RELATION_MEMBER_OF = 'memberOf'; +export const RELATION_HAS_MEMBER = 'hasMember'; diff --git a/packages/catalog-model/src/location/types.ts b/packages/catalog-model/src/location/types.ts index 50e6e82a54..33e443e04f 100644 --- a/packages/catalog-model/src/location/types.ts +++ b/packages/catalog-model/src/location/types.ts @@ -17,6 +17,10 @@ export type LocationSpec = { type: string; target: string; + // When using repo importer plugin, location is being created before the component yaml file is merged to the main branch. + // This flag is then set to indicate that the file can be not present. + // default value: 'required'. + presence?: 'optional' | 'required'; }; export type Location = { diff --git a/packages/catalog-model/src/location/validation.ts b/packages/catalog-model/src/location/validation.ts index 5fad47bdd0..27d74b9a82 100644 --- a/packages/catalog-model/src/location/validation.ts +++ b/packages/catalog-model/src/location/validation.ts @@ -21,8 +21,10 @@ export const locationSpecSchema = yup .object({ type: yup.string().required(), target: yup.string().required(), + presence: yup.string(), }) - .noUnknown(); + .noUnknown() + .required(); export const locationSchema = yup .object({ @@ -30,4 +32,5 @@ export const locationSchema = yup type: yup.string().required(), target: yup.string().required(), }) - .noUnknown(); + .noUnknown() + .required(); diff --git a/packages/catalog-model/src/validation/CommonValidatorFunctions.test.ts b/packages/catalog-model/src/validation/CommonValidatorFunctions.test.ts index 457ef64611..129fdd2b62 100644 --- a/packages/catalog-model/src/validation/CommonValidatorFunctions.test.ts +++ b/packages/catalog-model/src/validation/CommonValidatorFunctions.test.ts @@ -113,7 +113,7 @@ describe('CommonValidatorFunctions', () => { [{}, true], [{ a: 1 }, true], [{ a: undefined }, false], - ] as [any, boolean][])(`isJsonSafe %p ? %p`, (value, result) => { + ] as [unknown, boolean][])(`isJsonSafe %p ? %p`, (value, result) => { expect(CommonValidatorFunctions.isJsonSafe(value)).toBe(result); }); diff --git a/packages/catalog-model/src/validation/CommonValidatorFunctions.ts b/packages/catalog-model/src/validation/CommonValidatorFunctions.ts index 349d6d7f72..90b4e1a611 100644 --- a/packages/catalog-model/src/validation/CommonValidatorFunctions.ts +++ b/packages/catalog-model/src/validation/CommonValidatorFunctions.ts @@ -31,7 +31,7 @@ export class CommonValidatorFunctions { * @param isValidSuffix Checks that the part after the separator (or the entire value if there is no separator) is valid */ static isValidPrefixAndOrSuffix( - value: any, + value: unknown, separator: string, isValidPrefix: (value: string) => boolean, isValidSuffix: (value: string) => boolean, @@ -55,7 +55,7 @@ export class CommonValidatorFunctions { * * @param value The value to check */ - static isJsonSafe(value: any): boolean { + static isJsonSafe(value: unknown): boolean { try { return lodash.isEqual(value, JSON.parse(JSON.stringify(value))); } catch { @@ -69,7 +69,7 @@ export class CommonValidatorFunctions { * @param value The value to check * @see https://tools.ietf.org/html/rfc1123 */ - static isValidDnsSubdomain(value: any): boolean { + static isValidDnsSubdomain(value: unknown): boolean { return ( typeof value === 'string' && value.length >= 1 && @@ -84,7 +84,7 @@ export class CommonValidatorFunctions { * @param value The value to check * @see https://tools.ietf.org/html/rfc1123 */ - static isValidDnsLabel(value: any): boolean { + static isValidDnsLabel(value: unknown): boolean { return ( typeof value === 'string' && value.length >= 1 && diff --git a/packages/catalog-model/src/validation/KubernetesValidatorFunctions.ts b/packages/catalog-model/src/validation/KubernetesValidatorFunctions.ts index fa938f5fcb..ada0aa71ff 100644 --- a/packages/catalog-model/src/validation/KubernetesValidatorFunctions.ts +++ b/packages/catalog-model/src/validation/KubernetesValidatorFunctions.ts @@ -25,7 +25,7 @@ import { CommonValidatorFunctions } from './CommonValidatorFunctions'; * @see https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/#syntax-and-character-set */ export class KubernetesValidatorFunctions { - static isValidApiVersion(value: any): boolean { + static isValidApiVersion(value: unknown): boolean { return CommonValidatorFunctions.isValidPrefixAndOrSuffix( value, '/', @@ -34,7 +34,7 @@ export class KubernetesValidatorFunctions { ); } - static isValidKind(value: any): boolean { + static isValidKind(value: unknown): boolean { return ( typeof value === 'string' && value.length >= 1 && @@ -43,7 +43,7 @@ export class KubernetesValidatorFunctions { ); } - static isValidObjectName(value: any): boolean { + static isValidObjectName(value: unknown): boolean { return ( typeof value === 'string' && value.length >= 1 && @@ -52,11 +52,11 @@ export class KubernetesValidatorFunctions { ); } - static isValidNamespace(value: any): boolean { + static isValidNamespace(value: unknown): boolean { return CommonValidatorFunctions.isValidDnsLabel(value); } - static isValidLabelKey(value: any): boolean { + static isValidLabelKey(value: unknown): boolean { return CommonValidatorFunctions.isValidPrefixAndOrSuffix( value, '/', @@ -65,13 +65,13 @@ export class KubernetesValidatorFunctions { ); } - static isValidLabelValue(value: any): boolean { + static isValidLabelValue(value: unknown): boolean { return ( value === '' || KubernetesValidatorFunctions.isValidObjectName(value) ); } - static isValidAnnotationKey(value: any): boolean { + static isValidAnnotationKey(value: unknown): boolean { return CommonValidatorFunctions.isValidPrefixAndOrSuffix( value, '/', @@ -80,7 +80,7 @@ export class KubernetesValidatorFunctions { ); } - static isValidAnnotationValue(value: any): boolean { + static isValidAnnotationValue(value: unknown): boolean { return typeof value === 'string'; } } diff --git a/packages/catalog-model/src/validation/types.ts b/packages/catalog-model/src/validation/types.ts index 14706485ca..a4475c4809 100644 --- a/packages/catalog-model/src/validation/types.ts +++ b/packages/catalog-model/src/validation/types.ts @@ -15,13 +15,13 @@ */ export type Validators = { - isValidApiVersion(value: any): boolean; - isValidKind(value: any): boolean; - isValidEntityName(value: any): boolean; - isValidNamespace(value: any): boolean; - isValidLabelKey(value: any): boolean; - isValidLabelValue(value: any): boolean; - isValidAnnotationKey(value: any): boolean; - isValidAnnotationValue(value: any): boolean; - isValidTag(value: any): boolean; + isValidApiVersion(value: unknown): boolean; + isValidKind(value: unknown): boolean; + isValidEntityName(value: unknown): boolean; + isValidNamespace(value: unknown): boolean; + isValidLabelKey(value: unknown): boolean; + isValidLabelValue(value: unknown): boolean; + isValidAnnotationKey(value: unknown): boolean; + isValidAnnotationValue(value: unknown): boolean; + isValidTag(value: unknown): boolean; }; diff --git a/packages/cli-common/package.json b/packages/cli-common/package.json index abb4b5f9a1..56fb0d3417 100644 --- a/packages/cli-common/package.json +++ b/packages/cli-common/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/cli-common", "description": "Common functionality used by cli, backend, and create-app", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "private": false, "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/cli-common/src/paths.test.ts b/packages/cli-common/src/paths.test.ts index 087f95af38..2278ee3581 100644 --- a/packages/cli-common/src/paths.test.ts +++ b/packages/cli-common/src/paths.test.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +/* eslint-disable no-restricted-syntax */ import { resolve as resolvePath } from 'path'; import { findPaths, findRootPath, findOwnDir, findOwnRootDir } from './paths'; diff --git a/packages/cli/bin/backstage-cli b/packages/cli/bin/backstage-cli index a065b8ac5a..5c127af2ec 100755 --- a/packages/cli/bin/backstage-cli +++ b/packages/cli/bin/backstage-cli @@ -18,6 +18,7 @@ const path = require('path'); // Figure out whether we're running inside the backstage repo or as an installed dependency +/* eslint-disable-next-line no-restricted-syntax */ const isLocal = require('fs').existsSync(path.resolve(__dirname, '../src')); if (!isLocal || process.env.BACKSTAGE_E2E_CLI_TEST) { @@ -25,6 +26,7 @@ if (!isLocal || process.env.BACKSTAGE_E2E_CLI_TEST) { } else { require('ts-node').register({ transpileOnly: true, + /* eslint-disable-next-line no-restricted-syntax */ project: path.resolve(__dirname, '../../../tsconfig.json'), compilerOptions: { module: 'CommonJS', diff --git a/packages/cli/config/eslint.backend.js b/packages/cli/config/eslint.backend.js index 113ba55818..2c0b05c196 100644 --- a/packages/cli/config/eslint.backend.js +++ b/packages/cli/config/eslint.backend.js @@ -67,6 +67,11 @@ module.exports = { selector: 'ImportDeclaration[source.value="winston"] ImportDefaultSpecifier', }, + { + message: + "`__dirname` doesn't refer to the same dir in production builds, try `resolvePackagePath()` from `@backstage/backend-common` instead.", + selector: 'Identifier[name="__dirname"]', + }, ], }, overrides: [ diff --git a/packages/cli/config/jest.js b/packages/cli/config/jest.js index f69e18190d..b9f709241c 100644 --- a/packages/cli/config/jest.js +++ b/packages/cli/config/jest.js @@ -96,7 +96,7 @@ async function getConfig() { // Default behaviour is to not apply transforms for node_modules, but we still want // to apply the esm-transformer to .esm.js files, since that's what we use in backstage packages. transformIgnorePatterns: [ - `/node_modules/${transformModulePattern}(?:(?!\\.esm).)*\\.(?:js|json)$`, + `/node_modules/${transformModulePattern}.*\\.(?:(? { - const appConfigs = await loadConfig({ - env: process.env.NODE_ENV ?? 'production', - rootPaths: [paths.targetRoot, paths.targetDir], - }); await buildBundle({ entry: 'src/index', + parallel: parseParallel(process.env[PARALLEL_ENV_VAR]), statsJsonEnabled: cmd.stats, - config: ConfigReader.fromConfigs(appConfigs), - appConfigs, + ...(await loadCliConfig(cmd.config)), }); }; diff --git a/packages/cli/src/commands/app/serve.ts b/packages/cli/src/commands/app/serve.ts index c748d12a75..c3f58774b5 100644 --- a/packages/cli/src/commands/app/serve.ts +++ b/packages/cli/src/commands/app/serve.ts @@ -15,21 +15,14 @@ */ import { Command } from 'commander'; -import { loadConfig } from '@backstage/config-loader'; -import { ConfigReader } from '@backstage/config'; -import { paths } from '../../lib/paths'; import { serveBundle } from '../../lib/bundler'; +import { loadCliConfig } from '../../lib/config'; export default async (cmd: Command) => { - const appConfigs = await loadConfig({ - env: process.env.NODE_ENV ?? 'development', - rootPaths: [paths.targetRoot, paths.targetDir], - }); const waitForExit = await serveBundle({ entry: 'src/index', checksEnabled: cmd.check, - config: ConfigReader.fromConfigs(appConfigs), - appConfigs, + ...(await loadCliConfig(cmd.config)), }); await waitForExit(); diff --git a/packages/cli/src/commands/backend/buildImage.ts b/packages/cli/src/commands/backend/buildImage.ts index b6e9da7b39..b6ae0dd579 100644 --- a/packages/cli/src/commands/backend/buildImage.ts +++ b/packages/cli/src/commands/backend/buildImage.ts @@ -14,12 +14,13 @@ * limitations under the License. */ +import { Command } from 'commander'; import fs from 'fs-extra'; import { join as joinPath, relative as relativePath } from 'path'; import { createDistWorkspace } from '../../lib/packager'; import { paths } from '../../lib/paths'; import { run } from '../../lib/run'; -import { Command } from 'commander'; +import { parseParallel, PARALLEL_ENV_VAR } from '../../lib/parallel'; const PKG_PATH = 'package.json'; @@ -41,6 +42,7 @@ export default async (cmd: Command) => { ...appConfigs, { src: paths.resolveTarget('Dockerfile'), dest: 'Dockerfile' }, ], + parallel: parseParallel(process.env[PARALLEL_ENV_VAR]), skeleton: 'skeleton.tar', }); console.log(`Dist workspace ready at ${tempDistWorkspace}`); diff --git a/packages/cli/src/commands/backend/dev.ts b/packages/cli/src/commands/backend/dev.ts index 8b2ff9285a..88c069a92b 100644 --- a/packages/cli/src/commands/backend/dev.ts +++ b/packages/cli/src/commands/backend/dev.ts @@ -14,24 +14,14 @@ * limitations under the License. */ -import { ConfigReader } from '@backstage/config'; -import { loadConfig } from '@backstage/config-loader'; import { Command } from 'commander'; -import { paths } from '../../lib/paths'; import { serveBackend } from '../../lib/bundler/backend'; export default async (cmd: Command) => { - const appConfigs = await loadConfig({ - env: process.env.NODE_ENV ?? 'development', - rootPaths: [paths.targetRoot, paths.targetDir], - }); - const waitForExit = await serveBackend({ entry: 'src/index', checksEnabled: cmd.check, inspectEnabled: cmd.inspect, - config: ConfigReader.fromConfigs(appConfigs), - appConfigs, }); await waitForExit(); diff --git a/packages/cli/src/commands/config/print.ts b/packages/cli/src/commands/config/print.ts index bb626f520f..eb814a5bee 100644 --- a/packages/cli/src/commands/config/print.ts +++ b/packages/cli/src/commands/config/print.ts @@ -15,19 +15,13 @@ */ import { Command } from 'commander'; -import { loadConfig } from '@backstage/config-loader'; -import { ConfigReader } from '@backstage/config'; -import { paths } from '../../lib/paths'; import { stringify as stringifyYaml } from 'yaml'; +import { loadCliConfig } from '../../lib/config'; export default async (cmd: Command) => { - const appConfigs = await loadConfig({ - env: cmd.env ?? process.env.NODE_ENV ?? 'development', - shouldReadSecrets: cmd.withSecrets ?? false, - rootPaths: [paths.targetRoot, paths.targetDir], - }); + const { config } = await loadCliConfig(cmd.config, cmd.withSecrets ?? false); - const flatConfig = ConfigReader.fromConfigs(appConfigs).get(); + const flatConfig = config.get(); if (cmd.format === 'json') { process.stdout.write(`${JSON.stringify(flatConfig, null, 2)}\n`); diff --git a/packages/cli/src/commands/create-plugin/createPlugin.test.ts b/packages/cli/src/commands/create-plugin/createPlugin.test.ts index 72b95b072c..a08bb0da87 100644 --- a/packages/cli/src/commands/create-plugin/createPlugin.test.ts +++ b/packages/cli/src/commands/create-plugin/createPlugin.test.ts @@ -16,14 +16,20 @@ import fs from 'fs-extra'; import path from 'path'; +import mockFs from 'mock-fs'; import os from 'os'; import del from 'del'; import { createTemporaryPluginFolder, movePlugin } from './createPlugin'; +const id = 'testPluginMock'; + describe('createPlugin', () => { + afterAll(() => { + mockFs.restore(); + }); + describe('createPluginFolder', () => { it('should create a temporary plugin directory in the correct place', async () => { - const id = 'testPlugin'; const tempDir = path.join(os.tmpdir(), id); try { await createTemporaryPluginFolder(tempDir); @@ -35,35 +41,27 @@ describe('createPlugin', () => { }); it('should not create a temporary plugin directory if it already exists', async () => { - const id = 'testPlugin'; - const tempDir = path.join(os.tmpdir(), id); - try { - await createTemporaryPluginFolder(tempDir); - await expect(fs.pathExists(tempDir)).resolves.toBe(true); - await expect(createTemporaryPluginFolder(tempDir)).rejects.toThrow( - /Failed to create temporary plugin directory/, - ); - } finally { - await del(tempDir, { force: true }); - } + mockFs({ + [id]: {}, + }); + + await expect(createTemporaryPluginFolder(id)).rejects.toThrow( + /Failed to create temporary plugin directory/, + ); }); }); describe('movePlugin', () => { it('should move the temporary plugin directory to its final place', async () => { - const id = 'testPlugin'; - const tempDir = path.join(os.tmpdir(), id); - const rootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'test-')); - const pluginDir = path.join(rootDir, 'plugins', id); - try { - await createTemporaryPluginFolder(tempDir); - await movePlugin(tempDir, pluginDir, id); - await expect(fs.pathExists(pluginDir)).resolves.toBe(true); - expect(pluginDir).toMatch(path.join('', 'plugins', id)); - } finally { - await del(tempDir, { force: true }); - await del(rootDir, { force: true }); - } + mockFs({ + [id]: {}, + }); + const tempDir = id; + const pluginDir = path.join('test-temp', 'plugins', id); + + await movePlugin(tempDir, pluginDir, id); + await expect(fs.pathExists(pluginDir)).resolves.toBe(true); + expect(pluginDir).toMatch(path.join('', 'plugins', id)); }); }); }); diff --git a/packages/cli/src/commands/create-plugin/createPlugin.ts b/packages/cli/src/commands/create-plugin/createPlugin.ts index cbaf956bdb..057e36ceb9 100644 --- a/packages/cli/src/commands/create-plugin/createPlugin.ts +++ b/packages/cli/src/commands/create-plugin/createPlugin.ts @@ -224,9 +224,11 @@ export default async (cmd: Command) => { } const answers: Answers = await inquirer.prompt(questions); + const pluginId = cmd.backend ? `${answers.id}-backend` : answers.id; + const name = cmd.scope - ? `@${cmd.scope.replace(/^@/, '')}/plugin-${answers.id}` - : `plugin-${answers.id}`; + ? `@${cmd.scope.replace(/^@/, '')}/plugin-${pluginId}` + : `plugin-${pluginId}`; const npmRegistry = cmd.npmRegistry && cmd.scope ? cmd.npmRegistry : ''; const privatePackage = cmd.private === false ? false : true; const isMonoRepo = await fs.pathExists(paths.resolveTargetRoot('lerna.json')); @@ -236,10 +238,10 @@ export default async (cmd: Command) => { ? 'templates/default-backend-plugin' : 'templates/default-plugin', ); - const tempDir = resolvePath(os.tmpdir(), answers.id); + const tempDir = resolvePath(os.tmpdir(), pluginId); const pluginDir = isMonoRepo - ? paths.resolveTargetRoot('plugins', answers.id) - : paths.resolveTargetRoot(answers.id); + ? paths.resolveTargetRoot('plugins', pluginId) + : paths.resolveTargetRoot(pluginId); const ownerIds = parseOwnerIds(answers.owner); const { version } = isMonoRepo ? await fs.readJson(paths.resolveTargetRoot('lerna.json')) @@ -267,7 +269,7 @@ export default async (cmd: Command) => { }); Task.section('Moving to final location'); - await movePlugin(tempDir, pluginDir, answers.id); + await movePlugin(tempDir, pluginDir, pluginId); Task.section('Building the plugin'); await buildPlugin(pluginDir); @@ -277,13 +279,13 @@ export default async (cmd: Command) => { await addPluginDependencyToApp(paths.targetRoot, name, version); Task.section('Import plugin in app'); - await addPluginToApp(paths.targetRoot, answers.id, name); + await addPluginToApp(paths.targetRoot, pluginId, name); } if (ownerIds && ownerIds.length) { await addCodeownersEntry( codeownersPath!, - `/plugins/${answers.id}`, + `/plugins/${pluginId}`, ownerIds, ); } diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index fea250cd55..7f028919f7 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -18,16 +18,25 @@ import { CommanderStatic } from 'commander'; import { exitWithError } from '../lib/errors'; export function registerCommands(program: CommanderStatic) { + const configOption = [ + '--config ', + 'Config files to load instead of app-config.yaml', + (opt: string, opts: string[]) => [...opts, opt], + Array(), + ] as const; + program .command('app:build') .description('Build an app for a production release') .option('--stats', 'Write bundle stats to output directory') + .option(...configOption) .action(lazy(() => import('./app/build').then(m => m.default))); program .command('app:serve') .description('Serve an app for local development') .option('--check', 'Enable type checking and linting') + .option(...configOption) .action(lazy(() => import('./app/serve').then(m => m.default))); program @@ -50,6 +59,8 @@ export function registerCommands(program: CommanderStatic) { .description('Start local development server with HMR for the backend') .option('--check', 'Enable type checking and linting') .option('--inspect', 'Enable debugger') + // We don't actually use the config in the CLI, just pass them on to the NodeJS process + .option(...configOption) .action(lazy(() => import('./backend/dev').then(m => m.default))); program @@ -89,12 +100,14 @@ export function registerCommands(program: CommanderStatic) { .command('plugin:serve') .description('Serves the dev/ folder of a plugin') .option('--check', 'Enable type checking and linting') + .option(...configOption) .action(lazy(() => import('./plugin/serve').then(m => m.default))); program .command('plugin:export') .description('Exports the dev/ folder of a plugin') .option('--stats', 'Write bundle stats to output directory') + .option(...configOption) .action(lazy(() => import('./plugin/export').then(m => m.default))); program @@ -131,14 +144,11 @@ export function registerCommands(program: CommanderStatic) { program .command('config:print') .option('--with-secrets', 'Include secrets in the printed configuration') - .option( - '--env ', - 'The environment to print configuration for [NODE_ENV or development]', - ) .option( '--format ', 'Format to print the configuration in, either json or yaml [yaml]', ) + .option(...configOption) .description('Print the app configuration for the current package') .action(lazy(() => import('./config/print').then(m => m.default))); diff --git a/packages/cli/src/commands/plugin/diff.ts b/packages/cli/src/commands/plugin/diff.ts index f5dfa670b7..012c061f74 100644 --- a/packages/cli/src/commands/plugin/diff.ts +++ b/packages/cli/src/commands/plugin/diff.ts @@ -40,17 +40,13 @@ const fileHandlers = [ patterns: ['package.json'], handler: handlers.packageJson, }, - { - patterns: ['tsconfig.json'], - handler: handlers.exactMatch, - }, { // make sure files in 1st level of src/ and dev/ exist patterns: ['.eslintrc.js', /^(src|dev)\/[^/]+$/], handler: handlers.exists, }, { - patterns: ['README.md', /^src\//], + patterns: ['README.md', 'tsconfig.json', /^src\//], handler: handlers.skip, }, ]; diff --git a/packages/cli/src/commands/plugin/export.ts b/packages/cli/src/commands/plugin/export.ts index 8cbbe5b3ee..69955a2e5f 100644 --- a/packages/cli/src/commands/plugin/export.ts +++ b/packages/cli/src/commands/plugin/export.ts @@ -15,20 +15,13 @@ */ import { Command } from 'commander'; -import { loadConfig } from '@backstage/config-loader'; -import { ConfigReader } from '@backstage/config'; -import { paths } from '../../lib/paths'; import { buildBundle } from '../../lib/bundler'; +import { loadCliConfig } from '../../lib/config'; export default async (cmd: Command) => { - const appConfigs = await loadConfig({ - env: process.env.NODE_ENV ?? 'production', - rootPaths: [paths.targetRoot, paths.targetDir], - }); await buildBundle({ entry: 'dev/index', statsJsonEnabled: cmd.stats, - config: ConfigReader.fromConfigs(appConfigs), - appConfigs, + ...(await loadCliConfig(cmd.config)), }); }; diff --git a/packages/cli/src/commands/plugin/serve.ts b/packages/cli/src/commands/plugin/serve.ts index 8a04df8837..cb9def3158 100644 --- a/packages/cli/src/commands/plugin/serve.ts +++ b/packages/cli/src/commands/plugin/serve.ts @@ -15,21 +15,14 @@ */ import { Command } from 'commander'; -import { loadConfig } from '@backstage/config-loader'; -import { ConfigReader } from '@backstage/config'; -import { paths } from '../../lib/paths'; import { serveBundle } from '../../lib/bundler'; +import { loadCliConfig } from '../../lib/config'; export default async (cmd: Command) => { - const appConfigs = await loadConfig({ - env: process.env.NODE_ENV ?? 'development', - rootPaths: [paths.targetRoot, paths.targetDir], - }); const waitForExit = await serveBundle({ entry: 'dev/index', checksEnabled: cmd.check, - config: ConfigReader.fromConfigs(appConfigs), - appConfigs, + ...(await loadCliConfig(cmd.config)), }); await waitForExit(); diff --git a/packages/cli/src/commands/remove-plugin/file-mocks.ts b/packages/cli/src/commands/remove-plugin/file-mocks.ts new file mode 100644 index 0000000000..5768f5c398 --- /dev/null +++ b/packages/cli/src/commands/remove-plugin/file-mocks.ts @@ -0,0 +1,32 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export const pluginsFileContent = ` +export { plugin as WelcomePlugin } from '@backstage/plugin-welcome'; +export { plugin as LighthousePlugin } from '@backstage/plugin-lighthouse';`; + +export const codeownersFileContent = ` +* @spotify/backstage-core +/docs/features/techdocs @spotify/techdocs-core +/plugins/cost-insights @spotify/silver-lining +`; + +export const packageFileContent = { + name: 'example-app', + version: '0.1.1', + dependencies: {}, + devDependencies: {}, + scripts: {}, +}; diff --git a/packages/cli/src/commands/remove-plugin/removePlugin.test.ts b/packages/cli/src/commands/remove-plugin/removePlugin.test.ts index 3ffa8d63cf..56cde2ca9e 100644 --- a/packages/cli/src/commands/remove-plugin/removePlugin.test.ts +++ b/packages/cli/src/commands/remove-plugin/removePlugin.test.ts @@ -16,13 +16,9 @@ import fse from 'fs-extra'; import path from 'path'; -import os from 'os'; +import mockFs from 'mock-fs'; import { paths } from '../../lib/paths'; -import { - addExportStatement, - capitalize, - createTemporaryPluginFolder, -} from '../create-plugin/createPlugin'; +import { addExportStatement, capitalize } from '../create-plugin/createPlugin'; import { addCodeownersEntry } from '../../lib/codeowners'; import { removeReferencesFromAppPackage, @@ -31,160 +27,209 @@ import { removeSymLink, removePluginFromCodeOwners, } from './removePlugin'; +import { + codeownersFileContent, + packageFileContent, + pluginsFileContent, +} from './file-mocks'; -// Some constant variables const BACKSTAGE = `@backstage`; const testPluginName = 'yarn-test-package'; const testPluginPackage = `${BACKSTAGE}/plugin-${testPluginName}`; -const tempDir = path.join(os.tmpdir(), 'remove-plugin-test'); +const tempDir = '/remove-plugin-test'; const removeEmptyLines = (file: string): string => file.split(/\r?\n/).filter(Boolean).join('\n'); -const createTestPackageFile = async ( - testFilePath: string, - packageFile: string, -) => { - // Copy contents of package file for test - const packageFileContent = JSON.parse(fse.readFileSync(packageFile, 'utf8')); +const createTestPackageFile = async (testFilePath: string) => { + const testFileContent = { + ...packageFileContent, + dependencies: { + ...packageFileContent.dependencies, + [testPluginPackage]: '0.1.0', + }, + }; - packageFileContent.dependencies[testPluginPackage] = '0.1.0'; - fse.createFileSync(testFilePath); - fse.writeFileSync( - testFilePath, - `${JSON.stringify(packageFileContent, null, 2)}\n`, - 'utf8', - ); + mockFs({ + packages: { + app: { + 'package.json': `${JSON.stringify(packageFileContent, null, 2)}\n`, + }, + }, + [tempDir]: { + [testFilePath]: `${JSON.stringify(testFileContent, null, 2)}\n`, + }, + }); return; }; const createTestPluginFile = async ( - testFilePath: string, - pluginsFilePath: string, + testFileName: string, + pluginsFileName: string, ) => { - // Copy contents of package file for test - fse.copyFileSync(pluginsFilePath, testFilePath); + mockFs({ + [tempDir]: { + [testFileName]: `${pluginsFileContent}\n`, + [pluginsFileName]: `${pluginsFileContent}\n`, + }, + packages: { + app: { + src: { + 'plugin.ts': `${pluginsFileContent}\n`, + }, + }, + }, + }); + const pluginNameCapitalized = testPluginName .split('-') .map(name => capitalize(name)) .join(''); - const exportStatement = `export { default as ${pluginNameCapitalized}} from @backstage/plugin-${testPluginName}`; - addExportStatement(testFilePath, exportStatement); + const exportStatement = `export { plugin as ${pluginNameCapitalized}} from ${testPluginPackage}`; + await addExportStatement(path.join(tempDir, testFileName), exportStatement); }; const mkTestPluginDir = (testDirPath: string) => { - fse.mkdirSync(testDirPath); - for (let i = 0; i < 50; i++) - fse.createFileSync(path.join(testDirPath, `testFile${i}.ts`)); + const pluginFiles: { [index: string]: string } = {}; + for (let i = 0; i < 50; i++) { + pluginFiles[`testFile${i}.ts`] = ''; + } + + mockFs({ + [testDirPath]: pluginFiles, + }); }; -beforeAll(() => { - // Create temporary directory for all tests - createTemporaryPluginFolder(tempDir); -}); - describe('removePlugin', () => { - describe('Remove Plugin Dependencies', () => { - const appPath = paths.resolveTargetRoot('packages', 'app'); - const githubDir = paths.resolveTargetRoot('.github'); - it('removes plugin references from /packages/app/package.json', async () => { - // Set up test - const packageFilePath = path.join(appPath, 'package.json'); - const testFilePath = path.join(tempDir, 'test.json'); - createTestPackageFile(testFilePath, packageFilePath); - try { - await removeReferencesFromAppPackage(testFilePath, testPluginName); - const testFileContent = removeEmptyLines( - fse.readFileSync(testFilePath, 'utf8'), - ); - const packageFileContent = removeEmptyLines( - fse.readFileSync(packageFilePath, 'utf8'), - ); - expect(testFileContent).toBe(packageFileContent); - } finally { - fse.removeSync(testFilePath); - } - }); - it('removes plugin exports from /packages/app/src/packacge.json', async () => { - const testFilePath = path.join(tempDir, 'test.ts'); - const pluginsFilePaths = path.join(appPath, 'src', 'plugins.ts'); - createTestPluginFile(testFilePath, pluginsFilePaths); - try { - await removeReferencesFromPluginsFile(testFilePath, testPluginName); - const testFileContent = removeEmptyLines( - fse.readFileSync(testFilePath, 'utf8'), - ); - const pluginsFileContent = removeEmptyLines( - fse.readFileSync(pluginsFilePaths, 'utf8'), - ); - expect(testFileContent).toBe(pluginsFileContent); - } finally { - fse.removeSync(testFilePath); - } - }); - it('removes codeOwners references', async () => { - const testFilePath = path.join(tempDir, 'test'); - const codeownersPath = path.join(githubDir, 'CODEOWNERS'); - try { - fse.copySync(codeownersPath, testFilePath); - const testFileContent = removeEmptyLines( - fse.readFileSync(testFilePath, 'utf8'), - ); - const codeOwnersFileContent = removeEmptyLines( - fse.readFileSync(codeownersPath, 'utf8'), - ); - await addCodeownersEntry(testFilePath!, `/plugins/${testPluginName}`, [ - '@thisIsAtestTeam', - 'test@gmail.com', - ]); - await removePluginFromCodeOwners(testFilePath, testPluginName); - expect(testFileContent).toBe(codeOwnersFileContent); - } finally { - if (fse.existsSync(testFilePath)) fse.removeSync(testFilePath); - } + beforeAll(() => { + // Create temporary directory for all tests + mockFs({ + [tempDir]: { + 'package.json': packageFileContent, + src: { + 'plugin.ts': pluginsFileContent, + }, + }, }); }); + + afterAll(() => { + mockFs.restore(); + }); + + describe('Remove Plugin Dependencies', () => { + it('removes plugin references from /packages/app/package.json', async () => { + // Set up test + const testFilePath = 'test.json'; + createTestPackageFile(testFilePath); + await removeReferencesFromAppPackage( + path.join(tempDir, testFilePath), + testPluginName, + ); + const testFileContent = removeEmptyLines( + fse.readFileSync(path.join(tempDir, testFilePath), 'utf8'), + ); + + const mockedPackageFileContent = removeEmptyLines( + fse.readFileSync(path.join('packages', 'app', 'package.json'), 'utf8'), + ); + expect(testFileContent).toBe(mockedPackageFileContent); + }); + it('removes plugin exports from /packages/app/src/package.json', async () => { + const testFileName = 'test.ts'; + const pluginsFileName = 'plugin.ts'; + createTestPluginFile(testFileName, pluginsFileName); + await removeReferencesFromPluginsFile( + path.join(tempDir, testFileName), + testPluginName, + ); + const testFileContent = removeEmptyLines( + fse.readFileSync(path.join(tempDir, testFileName), 'utf8'), + ); + const mockedPluginsFileContent = removeEmptyLines( + fse.readFileSync( + path.join('packages', 'app', 'src', pluginsFileName), + 'utf8', + ), + ); + expect(testFileContent).toBe(mockedPluginsFileContent); + }); + + it('removes codeOwners references', async () => { + const testFileName = 'test'; + const testFilePath = path.join(tempDir, testFileName); + + const mockedCodeownersPath = path.join('.github', 'CODEOWNERS'); + + mockFs({ + [tempDir]: { + [testFileName]: '', + }, + '.github': { + CODEOWNERS: codeownersFileContent, + }, + }); + fse.copySync(mockedCodeownersPath, testFilePath); + const testFileContent = removeEmptyLines( + fse.readFileSync(testFilePath, 'utf8'), + ); + const codeOwnersFileContent = removeEmptyLines( + fse.readFileSync(mockedCodeownersPath, 'utf8'), + ); + await addCodeownersEntry( + testFilePath!, + path.join('plugins', testPluginName), + ['@thisIsAtestTeam', 'test@gmail.com'], + ); + await removePluginFromCodeOwners(testFilePath, testPluginName); + expect(testFileContent).toBe(codeOwnersFileContent); + }); + }); + describe('Remove files', () => { const testDirPath = path.join( paths.resolveTargetRoot(), 'plugins', testPluginName, ); + describe('Removes Plugin Directory', () => { it('removes plugin directory from /plugins', async () => { - try { - mkTestPluginDir(testDirPath); - expect(fse.existsSync(testDirPath)).toBeTruthy(); - await removePluginDirectory(testDirPath); - expect(fse.existsSync(testDirPath)).toBeFalsy(); - } finally { - if (fse.existsSync(testDirPath)) fse.removeSync(testDirPath); - } + mkTestPluginDir(testDirPath); + expect(fse.existsSync(testDirPath)).toBeTruthy(); + await removePluginDirectory(testDirPath); + expect(fse.existsSync(testDirPath)).toBeFalsy(); }); }); + describe('Removes System Link', () => { it('removes system link from @backstage', async () => { - const scopedDir = paths.resolveTargetRoot('node_modules', '@backstage'); + const symLink = `plugin-${testPluginName}`; const testSymLinkPath = path.join( - scopedDir, - `plugin-${testPluginName}`, + '/', + 'node_modules', + '@backstage', + symLink, ); - try { - mkTestPluginDir(testDirPath); - fse.ensureSymlinkSync(testSymLinkPath, testDirPath); + const mockedTestDirPath = path.join('/', 'plugins', testPluginName); - await removeSymLink(testSymLinkPath); - expect(fse.existsSync(testSymLinkPath)).toBeFalsy(); - } finally { - if (fse.existsSync(testDirPath)) fse.removeSync(testDirPath); - if (fse.existsSync(testSymLinkPath)) fse.removeSync(testSymLinkPath); - } + mockFs({ + '/plugins': { + [testPluginName]: {}, + }, + '/node_modules': { + '@backstage': { + [symLink]: mockFs.symlink({ + path: mockedTestDirPath, + }), + }, + }, + }); + + expect(fse.existsSync(testSymLinkPath)).toBeTruthy(); + await removeSymLink(testSymLinkPath); + expect(fse.existsSync(testSymLinkPath)).toBeFalsy(); }); }); }); }); - -afterAll(() => { - // Remove temporary directory - fse.removeSync(tempDir); -}); diff --git a/packages/cli/src/commands/remove-plugin/removePlugin.ts b/packages/cli/src/commands/remove-plugin/removePlugin.ts index 1395384022..81d8322ffa 100644 --- a/packages/cli/src/commands/remove-plugin/removePlugin.ts +++ b/packages/cli/src/commands/remove-plugin/removePlugin.ts @@ -20,7 +20,6 @@ import inquirer, { Answers, Question } from 'inquirer'; import { getCodeownersFilePath } from '../../lib/codeowners'; import { paths } from '../../lib/paths'; import { Task } from '../../lib/tasks'; -// import os from 'os'; const BACKSTAGE = '@backstage'; @@ -63,7 +62,7 @@ export const removePluginDirectory = async (destination: string) => { export const removeSymLink = async (destination: string) => { await Task.forItem('removing', 'symbolic link', async () => { - const symLinkExists = fse.pathExists(destination); + const symLinkExists = await fse.pathExists(destination); if (symLinkExists) { try { await fse.remove(destination); @@ -190,7 +189,7 @@ export default async () => { return chalk.red('Please enter an ID for the plugin'); } else if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(value)) { return chalk.red( - 'Plugin IDs must be kehbab-cased and contain only letters, digits and dashes.', + 'Plugin IDs must be kebab-cased and contain only letters, digits and dashes.', ); } return true; diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index e278164f4c..28e46bbd1a 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -27,18 +27,12 @@ const main = (argv: string[]) => { program.on('command:*', () => { console.log(); - console.log( - chalk.red(`Invalid command: ${chalk.cyan(program.args.join(' '))}`), - ); - console.log(chalk.red('See --help for a list of available commands.')); + console.log(chalk.red(`Invalid command: ${program.args.join(' ')}`)); console.log(); + program.outputHelp(); process.exit(1); }); - if (!process.argv.slice(2).length) { - program.outputHelp(chalk.yellow); - } - program.parse(argv); }; diff --git a/packages/cli/src/lib/builder/config.ts b/packages/cli/src/lib/builder/config.ts index 2566460494..2e7847fdb1 100644 --- a/packages/cli/src/lib/builder/config.ts +++ b/packages/cli/src/lib/builder/config.ts @@ -64,6 +64,7 @@ export const makeConfigs = async ( entryFileNames: 'index.cjs.js', chunkFileNames: 'cjs/[name]-[hash].js', format: 'commonjs', + sourcemap: true, }); } if (options.outputs.has(Output.esm)) { @@ -72,6 +73,7 @@ export const makeConfigs = async ( entryFileNames: 'index.esm.js', chunkFileNames: 'esm/[name]-[hash].js', format: 'module', + sourcemap: true, }); // Assume we're building for the browser if ESM output is included mainFields.unshift('browser'); diff --git a/packages/cli/src/lib/bundler/backend.ts b/packages/cli/src/lib/bundler/backend.ts index e3cc8af8d1..9633c1b963 100644 --- a/packages/cli/src/lib/bundler/backend.ts +++ b/packages/cli/src/lib/bundler/backend.ts @@ -17,13 +17,9 @@ import webpack from 'webpack'; import { createBackendConfig } from './config'; import { resolveBundlingPaths } from './paths'; -import { ServeOptions } from './types'; +import { BackendServeOptions } from './types'; -export async function serveBackend( - options: ServeOptions & { - inspectEnabled: boolean; - }, -) { +export async function serveBackend(options: BackendServeOptions) { const paths = resolveBundlingPaths(options); const config = await createBackendConfig(paths, { ...options, diff --git a/packages/cli/src/lib/bundler/config.ts b/packages/cli/src/lib/bundler/config.ts index 118cb1b40c..34b9f498ad 100644 --- a/packages/cli/src/lib/bundler/config.ts +++ b/packages/cli/src/lib/bundler/config.ts @@ -111,6 +111,9 @@ export async function createConfig( app: { title: options.config.getString('app.title'), baseUrl: validBaseUrl.href, + googleAnalyticsTrackingId: options.config.getOptionalString( + 'app.googleAnalyticsTrackingId', + ), }, }, }), @@ -209,6 +212,7 @@ export async function createBackendConfig( ], target: 'node' as const, node: { + /* eslint-disable-next-line no-restricted-syntax */ __dirname: true, __filename: true, global: true, diff --git a/packages/cli/src/lib/bundler/optimization.ts b/packages/cli/src/lib/bundler/optimization.ts index acd6a937d9..665eb10b21 100644 --- a/packages/cli/src/lib/bundler/optimization.ts +++ b/packages/cli/src/lib/bundler/optimization.ts @@ -15,7 +15,9 @@ */ import { Options } from 'webpack'; +import TerserPlugin from 'terser-webpack-plugin'; import { BundlingOptions } from './types'; +import { isParallelDefault } from '../parallel'; export const optimization = ( options: BundlingOptions, @@ -24,6 +26,16 @@ export const optimization = ( return { minimize: !isDev, + // Only configure when parallel is explicitly overriden from the default + ...(!isParallelDefault(options.parallel) + ? { + minimizer: [ + new TerserPlugin({ + parallel: options.parallel, + }), + ], + } + : {}), runtimeChunk: 'single', splitChunks: { automaticNameDelimiter: '-', diff --git a/packages/cli/src/lib/bundler/types.ts b/packages/cli/src/lib/bundler/types.ts index 03d68d9bb8..00f1895725 100644 --- a/packages/cli/src/lib/bundler/types.ts +++ b/packages/cli/src/lib/bundler/types.ts @@ -16,6 +16,7 @@ import { AppConfig, Config } from '@backstage/config'; import { BundlingPathsOptions } from './paths'; +import { ParallelOption } from '../parallel'; export type BundlingOptions = { checksEnabled: boolean; @@ -23,10 +24,7 @@ export type BundlingOptions = { config: Config; appConfigs: AppConfig[]; baseUrl: URL; -}; - -export type BackendBundlingOptions = Omit & { - inspectEnabled: boolean; + parallel?: ParallelOption; }; export type ServeOptions = BundlingPathsOptions & { @@ -37,6 +35,19 @@ export type ServeOptions = BundlingPathsOptions & { export type BuildOptions = BundlingPathsOptions & { statsJsonEnabled: boolean; + parallel?: ParallelOption; config: Config; appConfigs: AppConfig[]; }; + +export type BackendBundlingOptions = { + checksEnabled: boolean; + isDev: boolean; + parallel?: ParallelOption; + inspectEnabled: boolean; +}; + +export type BackendServeOptions = BundlingPathsOptions & { + checksEnabled: boolean; + inspectEnabled: boolean; +}; diff --git a/packages/cli/src/lib/config.ts b/packages/cli/src/lib/config.ts new file mode 100644 index 0000000000..5801632ea5 --- /dev/null +++ b/packages/cli/src/lib/config.ts @@ -0,0 +1,42 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { loadConfig } from '@backstage/config-loader'; +import { ConfigReader } from '@backstage/config'; +import { paths } from './paths'; + +export async function loadCliConfig( + configArgs: string[], + shouldReadSecrets: boolean = false, +) { + const configPaths = configArgs.map(arg => paths.resolveTarget(arg)); + + const appConfigs = await loadConfig({ + shouldReadSecrets, + env: process.env.APP_ENV ?? process.env.NODE_ENV ?? 'production', + configRoot: paths.targetRoot, + configPaths, + }); + + console.log( + `Loaded config from ${appConfigs.map(c => c.context).join(', ')}`, + ); + + return { + appConfigs, + config: ConfigReader.fromConfigs(appConfigs), + }; +} diff --git a/packages/cli/src/lib/packager/index.ts b/packages/cli/src/lib/packager/index.ts index 564317e46a..56f1ee453c 100644 --- a/packages/cli/src/lib/packager/index.ts +++ b/packages/cli/src/lib/packager/index.ts @@ -20,10 +20,11 @@ import { resolve as resolvePath, relative as relativePath, } from 'path'; +import { tmpdir } from 'os'; +import tar, { CreateOptions } from 'tar'; import { paths } from '../paths'; import { run } from '../run'; -import tar, { CreateOptions } from 'tar'; -import { tmpdir } from 'os'; +import { ParallelOption } from '../parallel'; type LernaPackage = { name: string; @@ -58,6 +59,11 @@ type Options = { */ buildDependencies?: boolean; + /** + * Enable (true/false) or control amount of (number) parallelism in some build steps. + */ + parallel?: ParallelOption; + /** * If set, creates a skeleton tarball that contains all package.json files * with the same structure as the workspace dir. @@ -85,7 +91,12 @@ export async function createDistWorkspace( if (options.buildDependencies) { const scopeArgs = targets.flatMap(target => ['--scope', target.name]); - await run('yarn', ['lerna', 'run', ...scopeArgs, 'build'], { + const lernaArgs = + options.parallel && Number.isInteger(options.parallel) + ? ['--concurrency', options.parallel.toString()] + : []; + + await run('yarn', ['lerna', ...lernaArgs, 'run', ...scopeArgs, 'build'], { cwd: paths.targetRoot, }); } diff --git a/packages/cli/src/lib/parallel.test.ts b/packages/cli/src/lib/parallel.test.ts new file mode 100644 index 0000000000..8047774a6e --- /dev/null +++ b/packages/cli/src/lib/parallel.test.ts @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isParallelDefault, parseParallel } from './parallel'; + +describe('parallel', () => { + describe('parseParallel', () => { + it('coerces "false" string to boolean', () => { + expect(parseParallel('false')).toBeFalsy(); + }); + + it('coerces "true" to boolean', () => { + expect(parseParallel('true')).toBeTruthy(); + }); + + it('coerces number string to number', () => { + expect(parseParallel('2')).toBe(2); + }); + it.each([[true], [false], [2]])('returns itself for %p', value => { + expect(parseParallel(value as any)).toEqual(value); + }); + + it.each([[undefined], [null]])('returns true for %p', value => { + expect(parseParallel(value as any)).toBe(true); + }); + + it.each([['on'], [2.5], ['2.5']])('throws error for %p', value => { + expect(() => parseParallel(value as any)).toThrowError( + `Parallel option value '${value}' is not a boolean or integer`, + ); + }); + }); + + describe('isParallelDefault', () => { + it('returns true if default value', () => { + expect(isParallelDefault(undefined)).toBeTruthy(); + expect(isParallelDefault(true)).toBeTruthy(); + }); + + it('returns false if not default value', () => { + expect(isParallelDefault(false)).toBeFalsy(); + expect(isParallelDefault(2)).toBeFalsy(); + expect(isParallelDefault('true' as any)).toBeFalsy(); + }); + }); +}); diff --git a/packages/cli/src/lib/parallel.ts b/packages/cli/src/lib/parallel.ts new file mode 100644 index 0000000000..b6926115aa --- /dev/null +++ b/packages/cli/src/lib/parallel.ts @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const PARALLEL_ENV_VAR = 'BACKSTAGE_CLI_BUILD_PARALLEL'; + +export type ParallelOption = boolean | number | undefined; + +export function isParallelDefault(parallel: ParallelOption) { + return parallel === undefined || parallel === true; +} + +export function parseParallel( + parallel: boolean | string | number | undefined, +): ParallelOption { + if (parallel === undefined || parallel === null) { + return true; + } else if (typeof parallel === 'boolean') { + return parallel; + } else if (typeof parallel === 'number' && Number.isInteger(parallel)) { + return parallel; + } else if (typeof parallel === 'string') { + if (parallel === 'true') { + return true; + } else if (parallel === 'false') { + return false; + } else if (Number.isInteger(parseFloat(parallel.toString()))) { + return Number(parallel); + } + } + + throw Error( + `Parallel option value '${parallel}' is not a boolean or integer`, + ); +} diff --git a/packages/cli/src/lib/paths.ts b/packages/cli/src/lib/paths.ts index 06c8f2ab38..a17034344d 100644 --- a/packages/cli/src/lib/paths.ts +++ b/packages/cli/src/lib/paths.ts @@ -16,4 +16,5 @@ import { findPaths } from '@backstage/cli-common'; +/* eslint-disable-next-line no-restricted-syntax */ export const paths = findPaths(__dirname); diff --git a/packages/cli/src/lib/tasks.test.ts b/packages/cli/src/lib/tasks.test.ts index 871d5a4d37..d80fcbe9b0 100644 --- a/packages/cli/src/lib/tasks.test.ts +++ b/packages/cli/src/lib/tasks.test.ts @@ -15,39 +15,45 @@ */ import fs from 'fs-extra'; +import mockFs from 'mock-fs'; import { resolve as resolvePath } from 'path'; -import os from 'os'; -import del from 'del'; import { templatingTask } from './tasks'; describe('templatingTask', () => { + afterEach(() => { + mockFs.restore(); + }); + it('should template a directory with mix of regular files and templates', async () => { - // Set up a testing template directory - const tmplDir = await fs.mkdtemp(resolvePath(os.tmpdir(), 'test-')); - await fs.ensureDir(resolvePath(tmplDir, 'sub')); - await fs.writeFile(resolvePath(tmplDir, 'test.txt'), 'testing'); - await fs.writeFile( - resolvePath(tmplDir, 'sub/version.txt.hbs'), - 'version: {{version}}', - ); + // Testing template directory + const tmplDir = 'test-tmpl'; - // Set up a temporary dest dir to write the template to - const destDir = await fs.mkdtemp(resolvePath(os.tmpdir(), 'test-')); + // Temporary dest dir to write the template to + const destDir = 'test-dest'; - try { - await templatingTask(tmplDir, destDir, { - version: '0.0.0', - }); + // Files content + const testFileContent = 'testing'; + const testVersionFileContent = 'version: {{version}}'; - await expect( - fs.readFile(resolvePath(destDir, 'test.txt'), 'utf8'), - ).resolves.toBe('testing'); - await expect( - fs.readFile(resolvePath(destDir, 'sub/version.txt'), 'utf8'), - ).resolves.toBe('version: 0.0.0'); - } finally { - await del(tmplDir, { force: true }); - await del(destDir, { force: true }); - } + mockFs({ + [tmplDir]: { + sub: { + 'version.txt.hbs': testVersionFileContent, + }, + 'test.txt': testFileContent, + }, + [destDir]: {}, + }); + + await templatingTask(tmplDir, destDir, { + version: '0.0.0', + }); + + await expect( + fs.readFile(resolvePath(destDir, 'test.txt'), 'utf8'), + ).resolves.toBe(testFileContent); + await expect( + fs.readFile(resolvePath(destDir, 'sub/version.txt'), 'utf8'), + ).resolves.toBe('version: 0.0.0'); }); }); diff --git a/packages/cli/src/lib/tasks.ts b/packages/cli/src/lib/tasks.ts index 0753301b78..80dc1a5ed7 100644 --- a/packages/cli/src/lib/tasks.ts +++ b/packages/cli/src/lib/tasks.ts @@ -20,6 +20,7 @@ import handlebars from 'handlebars'; import ora from 'ora'; import { basename, dirname } from 'path'; import recursive from 'recursive-readdir'; +import { paths } from './paths'; const TASK_NAME_MAX_LENGTH = 14; @@ -72,6 +73,7 @@ export async function templatingTask( const files = await recursive(templateDir).catch(error => { throw new Error(`Failed to read template directory: ${error.message}`); }); + const isMonoRepo = await fs.pathExists(paths.resolveTargetRoot('lerna.json')); for (const file of files) { const destinationFile = file.replace(templateDir, destinationDir); @@ -92,6 +94,10 @@ export async function templatingTask( }); }); } else { + if (isMonoRepo && file.match('tsconfig.json')) { + continue; + } + await Task.forItem('copying', basename(file), async () => { await fs.copyFile(file, destinationFile).catch(error => { const destination = destinationFile; diff --git a/packages/cli/src/types.d.ts b/packages/cli/src/types.d.ts index 94136f1dbc..828819ad17 100644 --- a/packages/cli/src/types.d.ts +++ b/packages/cli/src/types.d.ts @@ -29,3 +29,5 @@ declare module '@svgr/rollup' { } declare module '@rollup/plugin-yaml'; + +declare module 'terser-webpack-plugin'; diff --git a/packages/cli/templates/default-backend-plugin/package.json.hbs b/packages/cli/templates/default-backend-plugin/package.json.hbs index 40e612609a..1a73515622 100644 --- a/packages/cli/templates/default-backend-plugin/package.json.hbs +++ b/packages/cli/templates/default-backend-plugin/package.json.hbs @@ -23,20 +23,20 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^{{version}}", - "@backstage/config": "^{{version}}", + "@backstage/backend-common": "^{{backstageVersion}}", + "@backstage/config": "^{{backstageVersion}}", "@types/express": "^4.17.6", "express": "^4.17.1", "express-promise-router": "^3.0.3", "winston": "^3.2.1", - "node-fetch": "^2.6.1", + "cross-fetch": "^3.0.6", "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^{{version}}", + "@backstage/cli": "^{{backstageVersion}}", "@types/supertest": "^2.0.8", "supertest": "^4.0.2", - "msw": "^0.20.5" + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/packages/cli/templates/default-backend-plugin/src/setupTests.ts b/packages/cli/templates/default-backend-plugin/src/setupTests.ts index a5907fd52f..ba33cf996b 100644 --- a/packages/cli/templates/default-backend-plugin/src/setupTests.ts +++ b/packages/cli/templates/default-backend-plugin/src/setupTests.ts @@ -15,4 +15,3 @@ */ export {}; -global.fetch = require('node-fetch'); diff --git a/packages/cli/templates/default-backend-plugin/tsconfig.json b/packages/cli/templates/default-backend-plugin/tsconfig.json new file mode 100644 index 0000000000..d77f0fe3b4 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "@backstage/cli/config/tsconfig.json", + "include": [ + "src", + "dev", + "migrations" + ], + "exclude": ["node_modules"], + "compilerOptions": { + "outDir": "dist-types", + "rootDir": "." + } +} diff --git a/packages/cli/templates/default-plugin/package.json.hbs b/packages/cli/templates/default-plugin/package.json.hbs index e024884547..41f942fb79 100644 --- a/packages/cli/templates/default-plugin/package.json.hbs +++ b/packages/cli/templates/default-plugin/package.json.hbs @@ -36,13 +36,14 @@ "devDependencies": { "@backstage/cli": "^{{backstageVersion}}", "@backstage/dev-utils": "^{{backstageVersion}}", + "@backstage/test-utils": "^{{backstageVersion}}", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "msw": "^0.21.2", + "cross-fetch": "^3.0.6" }, "files": [ "dist" diff --git a/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs b/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs index fdb39444d8..e805900f36 100644 --- a/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs +++ b/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs @@ -5,18 +5,13 @@ import { ThemeProvider } from '@material-ui/core'; import { lightTheme } from '@backstage/theme'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; +import { msw } from '@backstage/test-utils'; describe('ExampleComponent', () => { const server = setupServer(); - // Enable API mocking before tests. - beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) - - // Reset any runtime request handlers we may add during the tests. - afterEach(() => server.resetHandlers()) - - // Disable API mocking after the tests are done. - afterAll(() => server.close()) + // Enable sane handlers for network requests + msw.setupDefaultHandlers(server); // setup mock response beforeEach(() => { diff --git a/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.tsx.hbs b/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.tsx.hbs index 79adaefaa8..e08f1650d5 100644 --- a/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.tsx.hbs +++ b/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.tsx.hbs @@ -4,7 +4,6 @@ import { InfoCard, Header, Page, - pageTheme, Content, ContentHeader, HeaderLabel, @@ -13,7 +12,7 @@ import { import ExampleFetchComponent from '../ExampleFetchComponent'; const ExampleComponent: FC<{}> = () => ( - +
@@ -37,5 +36,5 @@ const ExampleComponent: FC<{}> = () => ( ); - + export default ExampleComponent; diff --git a/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs b/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs index ca1990b4bc..81e1b4be09 100644 --- a/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs +++ b/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs @@ -3,18 +3,13 @@ import { render } from '@testing-library/react'; import ExampleFetchComponent from './ExampleFetchComponent'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; +import { msw } from '@backstage/test-utils'; describe('ExampleFetchComponent', () => { const server = setupServer(); - // Enable API mocking before tests. - beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) - - // Reset any runtime request handlers we may add during the tests. - afterEach(() => server.resetHandlers()) - - // Disable API mocking after the tests are done. - afterAll(() => server.close()) - + // Enable sane handlers for network requests + msw.setupDefaultHandlers(server); + // setup mock response beforeEach(() => { server.use(rest.get('https://randomuser.me/*', (_, res, ctx) => res(ctx.status(200), ctx.delay(2000), ctx.json({})))) diff --git a/packages/cli/templates/default-plugin/src/setupTests.ts b/packages/cli/templates/default-plugin/src/setupTests.ts index cc559f672e..292b0cc471 100644 --- a/packages/cli/templates/default-plugin/src/setupTests.ts +++ b/packages/cli/templates/default-plugin/src/setupTests.ts @@ -1,2 +1,2 @@ import '@testing-library/jest-dom'; -global.fetch = require('node-fetch'); +import 'cross-fetch/polyfill' diff --git a/packages/cli/templates/default-plugin/tsconfig.json b/packages/cli/templates/default-plugin/tsconfig.json new file mode 100644 index 0000000000..b61e496175 --- /dev/null +++ b/packages/cli/templates/default-plugin/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "@backstage/cli/config/tsconfig.json", + "include": [ + "src", + "dev" + ], + "exclude": ["node_modules"], + "compilerOptions": { + "outDir": "dist-types", + "rootDir": "." + } +} diff --git a/packages/config-loader/package.json b/packages/config-loader/package.json index 6a17eba76c..2eef7db027 100644 --- a/packages/config-loader/package.json +++ b/packages/config-loader/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/config-loader", "description": "Config loading functionality used by Backstage backend, and CLI", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "private": false, "publishConfig": { "access": "public", @@ -30,16 +30,16 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/config": "^0.1.1-alpha.24", + "@backstage/config": "^0.1.1-alpha.26", "fs-extra": "^9.0.0", "yaml": "^1.9.2", - "yup": "^0.29.1" + "yup": "^0.29.3" }, "devDependencies": { "@types/jest": "^26.0.7", "@types/mock-fs": "^4.10.0", "@types/node": "^12.0.0", - "@types/yup": "^0.28.2", + "@types/yup": "^0.29.8", "mock-fs": "^4.13.0" }, "files": [ diff --git a/packages/config-loader/src/lib/index.ts b/packages/config-loader/src/lib/index.ts index 40252b9cec..1b5ad2ef50 100644 --- a/packages/config-loader/src/lib/index.ts +++ b/packages/config-loader/src/lib/index.ts @@ -14,7 +14,6 @@ * limitations under the License. */ -export { resolveStaticConfig } from './resolver'; export { readConfigFile } from './reader'; export { readEnvConfig } from './env'; export { readSecret } from './secrets'; diff --git a/packages/config-loader/src/lib/resolver.test.ts b/packages/config-loader/src/lib/resolver.test.ts deleted file mode 100644 index 9fd71f2486..0000000000 --- a/packages/config-loader/src/lib/resolver.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import mockFs from 'mock-fs'; -import { resolveStaticConfig } from './resolver'; - -function normalizePaths(paths: string[]) { - return paths.map(p => - p - .replace(/^[a-z]:/i, '') - .split('\\') - .join('/'), - ); -} - -describe('resolveStaticConfig', () => { - afterEach(() => { - mockFs.restore(); - }); - - it('should resolve no files for empty roots', async () => { - mockFs({}); - const resolved = await resolveStaticConfig({ - env: 'development', - rootPaths: [], - }); - - expect(normalizePaths(resolved)).toEqual([]); - }); - - it('should resolve a single app-config', async () => { - mockFs({ '/repo/app-config.yaml': '' }); - const resolved = await resolveStaticConfig({ - env: 'development', - rootPaths: ['/repo'], - }); - - expect(normalizePaths(resolved)).toEqual(['/repo/app-config.yaml']); - }); - - it('should resolve a app-configs in different directories', async () => { - mockFs({ - '/repo/app-config.yaml': '', - '/repo/packages/a/app-config.yaml': '', - }); - const resolved = await resolveStaticConfig({ - env: 'development', - rootPaths: [ - '/repo', - '/other-repo', - '/repo/packages/a', - '/repo/packages/b', - ], - }); - - expect(normalizePaths(resolved)).toEqual([ - '/repo/app-config.yaml', - '/repo/packages/a/app-config.yaml', - ]); - }); - - it('should resolve env and local configs', async () => { - mockFs({ - '/repo/app-config.yaml': '', - '/repo/app-config.local.yaml': '', - '/repo/app-config.production.yaml': '', - '/repo/app-config.production.local.yaml': '', - '/repo/app-config.development.local.yaml': '', - '/repo/packages/a/app-config.development.yaml': '', - '/repo/packages/a/app-config.local.yaml': '', - }); - const resolved = await resolveStaticConfig({ - env: 'development', - rootPaths: ['/repo', '/repo/packages/a'], - }); - - expect(normalizePaths(resolved)).toEqual([ - '/repo/app-config.yaml', - '/repo/app-config.local.yaml', - '/repo/app-config.development.local.yaml', - '/repo/packages/a/app-config.local.yaml', - '/repo/packages/a/app-config.development.yaml', - ]); - }); - - it('resolves suffixed configs in the correct order', async () => { - mockFs({ - '/repo/app-config.yaml': '', - '/repo/app-config.local.yaml': '', - '/repo/app-config.production.yaml': '', - '/repo/app-config.production.local.yaml': '', - }); - - const resolved = await resolveStaticConfig({ - env: 'production', - rootPaths: ['/repo'], - }); - - expect(normalizePaths(resolved)).toEqual([ - '/repo/app-config.yaml', - '/repo/app-config.local.yaml', - '/repo/app-config.production.yaml', - '/repo/app-config.production.local.yaml', - ]); - }); -}); diff --git a/packages/config-loader/src/lib/resolver.ts b/packages/config-loader/src/lib/resolver.ts deleted file mode 100644 index 44f0f6ea9e..0000000000 --- a/packages/config-loader/src/lib/resolver.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { resolve as resolvePath } from 'path'; -import { pathExists } from 'fs-extra'; - -type ResolveOptions = { - // Root paths to search for config files. Config from earlier paths has lower priority. - rootPaths: string[]; - // The environment that we're loading config for, e.g. 'development', 'production'. - env: string; -}; - -/** - * Resolves all configuration files that should be loaded in the given environment. - * - * For each root directory, search for the default app-config.yaml, along with suffixed - * NODE_ENV and local variants, e.g. app-config.production.yaml or app-config.development.local.yaml - * - * The priority order of config loaded through suffixes is `env > local > none`, meaning that - * for example app-config.development.yaml has higher priority than `app-config.local.yaml`. - * - */ -export async function resolveStaticConfig( - options: ResolveOptions, -): Promise { - const filePaths = [ - `app-config.yaml`, - `app-config.local.yaml`, - `app-config.${options.env}.yaml`, - `app-config.${options.env}.local.yaml`, - ]; - - const resolvedPaths = []; - - for (const rootPath of options.rootPaths) { - for (const filePath of filePaths) { - const path = resolvePath(rootPath, filePath); - if (await pathExists(path)) { - resolvedPaths.push(path); - } - } - } - - return resolvedPaths; -} diff --git a/packages/config-loader/src/lib/secrets.ts b/packages/config-loader/src/lib/secrets.ts index 4c3812d527..97f0de2940 100644 --- a/packages/config-loader/src/lib/secrets.ts +++ b/packages/config-loader/src/lib/secrets.ts @@ -58,7 +58,7 @@ const secretLoaderSchemas = { }; // The top-level secret schema, which figures out what type of secret it is. -const secretSchema = yup.lazy(value => { +const secretSchema = yup.lazy(value => { if (typeof value !== 'object' || value === null) { return yup.object().required().label('secret'); } diff --git a/packages/config-loader/src/loader.test.ts b/packages/config-loader/src/loader.test.ts index 087e2309c0..3b0d8e6e92 100644 --- a/packages/config-loader/src/loader.test.ts +++ b/packages/config-loader/src/loader.test.ts @@ -38,10 +38,31 @@ describe('loadConfig', () => { mockFs.restore(); }); + it('load config from default path', async () => { + await expect( + loadConfig({ + configRoot: '/root', + configPaths: [], + env: 'production', + shouldReadSecrets: false, + }), + ).resolves.toEqual([ + { + context: 'app-config.yaml', + data: { + app: { + title: 'Example App', + }, + }, + }, + ]); + }); + it('loads config without secrets', async () => { await expect( loadConfig({ - rootPaths: ['/root'], + configRoot: '/root', + configPaths: ['/root/app-config.yaml'], env: 'production', shouldReadSecrets: false, }), @@ -60,7 +81,8 @@ describe('loadConfig', () => { it('loads config with secrets', async () => { await expect( loadConfig({ - rootPaths: ['/root'], + configRoot: '/root', + configPaths: ['/root/app-config.yaml'], env: 'production', shouldReadSecrets: true, }), @@ -80,7 +102,11 @@ describe('loadConfig', () => { it('loads development config without secrets', async () => { await expect( loadConfig({ - rootPaths: ['/root'], + configRoot: '/root', + configPaths: [ + '/root/app-config.yaml', + '/root/app-config.development.yaml', + ], env: 'development', shouldReadSecrets: false, }), @@ -105,7 +131,11 @@ describe('loadConfig', () => { it('loads development config with secrets', async () => { await expect( loadConfig({ - rootPaths: ['/root'], + configRoot: '/root', + configPaths: [ + '/root/app-config.yaml', + '/root/app-config.development.yaml', + ], env: 'development', shouldReadSecrets: true, }), diff --git a/packages/config-loader/src/loader.ts b/packages/config-loader/src/loader.ts index cf5edd3ce3..e7eb2a38fa 100644 --- a/packages/config-loader/src/loader.ts +++ b/packages/config-loader/src/loader.ts @@ -15,20 +15,18 @@ */ import fs from 'fs-extra'; -import { resolve as resolvePath, dirname } from 'path'; +import { resolve as resolvePath, dirname, isAbsolute } from 'path'; import { AppConfig, JsonObject } from '@backstage/config'; -import { - resolveStaticConfig, - readConfigFile, - readEnvConfig, - readSecret, -} from './lib'; +import { readConfigFile, readEnvConfig, readSecret } from './lib'; export type LoadConfigOptions = { - // Root paths to search for config files. Config from earlier paths has lower priority. - rootPaths: string[]; + // The root directory of the config loading context. Used to find default configs. + configRoot: string; - // The environment that we're loading config for, e.g. 'development', 'production'. + // Absolute paths to load config files from. Configs from earlier paths have lower priority. + configPaths: string[]; + + // TODO(Rugvip): This will be removed in the future, but for now we use it to warn about possible mistakes. env: string; // Whether to read secrets or omit them, defaults to false. @@ -77,13 +75,37 @@ export async function loadConfig( options: LoadConfigOptions, ): Promise { const configs = []; + const { configRoot } = options; + const configPaths = options.configPaths.slice(); - const configPaths = await resolveStaticConfig(options); + // If no paths are provided, we default to reading + // `app-config.yaml` and, if it exists, `app-config.local.yaml` + if (configPaths.length === 0) { + configPaths.push(resolvePath(configRoot, 'app-config.yaml')); + + const localConfig = resolvePath(configRoot, 'app-config.local.yaml'); + if (await fs.pathExists(localConfig)) { + configPaths.push(localConfig); + } + + const envFile = `app-config.${options.env}.yaml`; + if (await fs.pathExists(resolvePath(configRoot, envFile))) { + console.error( + `Env config file '${envFile}' is not loaded as APP_ENV and NODE_ENV-based config loading has been removed`, + ); + console.error( + `To load the config file, use --config , listing every config file that you want to load`, + ); + } + } try { const secretPaths = new Set(); for (const configPath of configPaths) { + if (!isAbsolute(configPath)) { + throw new Error(`Config load path is not absolute: '${configPath}'`); + } const config = await readConfigFile( configPath, new Context({ diff --git a/packages/config/package.json b/packages/config/package.json index d3695ebf33..d8ee50e97c 100644 --- a/packages/config/package.json +++ b/packages/config/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/config", "description": "Config API used by Backstage core, backend, and CLI", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "private": false, "publishConfig": { "access": "public", diff --git a/packages/core-api/package.json b/packages/core-api/package.json index c925471695..34949e4315 100644 --- a/packages/core-api/package.json +++ b/packages/core-api/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/core-api", "description": "Internal Core API used by Backstage plugins and apps", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "private": false, "publishConfig": { "access": "public", @@ -29,8 +29,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/config": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/config": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@types/react": "^16.9", @@ -41,15 +42,16 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/test-utils-core": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/test-utils-core": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/zen-observable": "^0.8.0", - "jest-fetch-mock": "^3.0.3" + "cross-fetch": "^3.0.6", + "msw": "^0.21.3" }, "files": [ "dist" diff --git a/packages/core-api/src/apis/definitions/AlertApi.ts b/packages/core-api/src/apis/definitions/AlertApi.ts index 123cd47651..91641ac35b 100644 --- a/packages/core-api/src/apis/definitions/AlertApi.ts +++ b/packages/core-api/src/apis/definitions/AlertApi.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { createApiRef } from '../ApiRef'; +import { createApiRef, ApiRef } from '../system'; import { Observable } from '../../types'; export type AlertMessage = { @@ -38,7 +38,7 @@ export type AlertApi = { alert$(): Observable; }; -export const alertApiRef = createApiRef({ +export const alertApiRef: ApiRef = createApiRef({ id: 'core.alert', description: 'Used to report alerts and forward them to the app', }); diff --git a/packages/core-api/src/apis/definitions/AppThemeApi.ts b/packages/core-api/src/apis/definitions/AppThemeApi.ts index de70adabd9..515e8df082 100644 --- a/packages/core-api/src/apis/definitions/AppThemeApi.ts +++ b/packages/core-api/src/apis/definitions/AppThemeApi.ts @@ -14,9 +14,10 @@ * limitations under the License. */ -import { createApiRef } from '../ApiRef'; +import { ApiRef, createApiRef } from '../system'; import { BackstageTheme } from '@backstage/theme'; import { Observable } from '../../types'; +import { SvgIconProps } from '@material-ui/core'; /** * Describes a theme provided by the app. @@ -41,6 +42,11 @@ export type AppTheme = { * The specialized MaterialUI theme instance. */ theme: BackstageTheme; + + /** + * An Icon for the theme mode setting. + */ + icon?: React.ReactElement; }; /** @@ -71,7 +77,7 @@ export type AppThemeApi = { setActiveThemeId(themeId?: string): void; }; -export const appThemeApiRef = createApiRef({ +export const appThemeApiRef: ApiRef = createApiRef({ id: 'core.apptheme', description: 'API Used to configure the app theme, and enumerate options', }); diff --git a/packages/core-api/src/apis/definitions/ConfigApi.ts b/packages/core-api/src/apis/definitions/ConfigApi.ts index 1fa6e70d1f..2ce972af0e 100644 --- a/packages/core-api/src/apis/definitions/ConfigApi.ts +++ b/packages/core-api/src/apis/definitions/ConfigApi.ts @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { createApiRef } from '../ApiRef'; +import { ApiRef, createApiRef } from '../system'; import { Config } from '@backstage/config'; // Using interface to make the ConfigApi name show up in docs export type ConfigApi = Config; -export const configApiRef = createApiRef({ +export const configApiRef: ApiRef = createApiRef({ id: 'core.config', description: 'Used to access runtime configuration', }); diff --git a/packages/core-api/src/apis/definitions/DiscoveryApi.ts b/packages/core-api/src/apis/definitions/DiscoveryApi.ts index b0773086c7..9777835ec8 100644 --- a/packages/core-api/src/apis/definitions/DiscoveryApi.ts +++ b/packages/core-api/src/apis/definitions/DiscoveryApi.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { createApiRef } from '../ApiRef'; +import { ApiRef, createApiRef } from '../system'; /** * The discovery API is used to provide a mechanism for plugins to @@ -41,7 +41,7 @@ export type DiscoveryApi = { getBaseUrl(pluginId: string): Promise; }; -export const discoveryApiRef = createApiRef({ +export const discoveryApiRef: ApiRef = createApiRef({ id: 'core.discovery', description: 'Provides service discovery of backend plugins', }); diff --git a/packages/core-api/src/apis/definitions/ErrorApi.ts b/packages/core-api/src/apis/definitions/ErrorApi.ts index 7f9676ea5a..edd6966968 100644 --- a/packages/core-api/src/apis/definitions/ErrorApi.ts +++ b/packages/core-api/src/apis/definitions/ErrorApi.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { createApiRef } from '../ApiRef'; +import { ApiRef, createApiRef } from '../system'; import { Observable } from '../../types'; /** @@ -62,7 +62,7 @@ export type ErrorApi = { error$(): Observable<{ error: Error; context?: ErrorContext }>; }; -export const errorApiRef = createApiRef({ +export const errorApiRef: ApiRef = createApiRef({ id: 'core.error', description: 'Used to report errors and forward them to the app', }); diff --git a/packages/core-api/src/apis/definitions/FeatureFlagsApi.ts b/packages/core-api/src/apis/definitions/FeatureFlagsApi.ts index b6aac75620..6e8c8cd8fc 100644 --- a/packages/core-api/src/apis/definitions/FeatureFlagsApi.ts +++ b/packages/core-api/src/apis/definitions/FeatureFlagsApi.ts @@ -14,12 +14,9 @@ * limitations under the License. */ -import { createApiRef } from '../ApiRef'; -import { - UserFlags, - FeatureFlagsRegistry, - FeatureFlagsRegistryItem, -} from '../../app/FeatureFlags'; +import { ApiRef, createApiRef } from '../system'; +import { UserFlags, FeatureFlagsRegistry } from '../../app/FeatureFlags'; +import { FeatureFlagName } from '../../plugin'; /** * The feature flags API is used to toggle functionality to users across plugins and Backstage. @@ -55,7 +52,12 @@ export interface FeatureFlagsApi { getRegisteredFlags(): FeatureFlagsRegistry; } -export const featureFlagsApiRef = createApiRef({ +export interface FeatureFlagsRegistryItem { + pluginId: string; + name: FeatureFlagName; +} + +export const featureFlagsApiRef: ApiRef = createApiRef({ id: 'core.featureflags', description: 'Used to toggle functionality in features across Backstage', }); diff --git a/packages/core-api/src/apis/definitions/IdentityApi.ts b/packages/core-api/src/apis/definitions/IdentityApi.ts index 2684422b1e..5cfc4723e0 100644 --- a/packages/core-api/src/apis/definitions/IdentityApi.ts +++ b/packages/core-api/src/apis/definitions/IdentityApi.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { createApiRef } from '../ApiRef'; +import { ApiRef, createApiRef } from '../system'; import { ProfileInfo } from './auth'; /** @@ -51,7 +51,7 @@ export type IdentityApi = { signOut(): Promise; }; -export const identityApiRef = createApiRef({ +export const identityApiRef: ApiRef = createApiRef({ id: 'core.identity', description: 'Provides access to the identity of the signed in user', }); diff --git a/packages/core-api/src/apis/definitions/OAuthRequestApi.ts b/packages/core-api/src/apis/definitions/OAuthRequestApi.ts index 6fefbd1b9c..7514a88dc1 100644 --- a/packages/core-api/src/apis/definitions/OAuthRequestApi.ts +++ b/packages/core-api/src/apis/definitions/OAuthRequestApi.ts @@ -16,7 +16,7 @@ import { IconComponent } from '../../icons'; import { Observable } from '../../types'; -import { createApiRef } from '../ApiRef'; +import { ApiRef, createApiRef } from '../system'; /** * Information about the auth provider that we're requesting a login towards. @@ -127,7 +127,7 @@ export type OAuthRequestApi = { authRequest$(): Observable; }; -export const oauthRequestApiRef = createApiRef({ +export const oauthRequestApiRef: ApiRef = createApiRef({ id: 'core.oauthrequest', description: 'An API for implementing unified OAuth flows in Backstage', }); diff --git a/packages/core-api/src/apis/definitions/StorageApi.ts b/packages/core-api/src/apis/definitions/StorageApi.ts index 920ee56811..d0f71ea3a4 100644 --- a/packages/core-api/src/apis/definitions/StorageApi.ts +++ b/packages/core-api/src/apis/definitions/StorageApi.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { createApiRef } from '../ApiRef'; +import { ApiRef, createApiRef } from '../system'; import { Observable } from '../../types'; import { ErrorApi } from './ErrorApi'; @@ -65,7 +65,7 @@ export interface StorageApi { observe$(key: string): Observable>; } -export const storageApiRef = createApiRef({ +export const storageApiRef: ApiRef = createApiRef({ id: 'core.storage', description: 'Provides the ability to store data which is unique to the user', }); diff --git a/packages/core-api/src/apis/definitions/auth.ts b/packages/core-api/src/apis/definitions/auth.ts index 109f15b26e..946baeabd9 100644 --- a/packages/core-api/src/apis/definitions/auth.ts +++ b/packages/core-api/src/apis/definitions/auth.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import { createApiRef } from '../ApiRef'; -import { Observable } from '../..'; +import { ApiRef, createApiRef } from '../system'; +import { Observable } from '../../types'; /** * This file contains declarations for common interfaces of auth-related APIs. @@ -212,13 +212,13 @@ export type SessionApi = { * Note that the ID token payload is only guaranteed to contain the user's numerical Google ID, * email and expiration information. Do not rely on any other fields, as they might not be present. */ -export const googleAuthApiRef = createApiRef< +export const googleAuthApiRef: ApiRef< OAuthApi & OpenIdConnectApi & ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.google', description: 'Provides authentication towards Google APIs and identities', }); @@ -229,9 +229,9 @@ export const googleAuthApiRef = createApiRef< * See https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/ * for a full list of supported scopes. */ -export const githubAuthApiRef = createApiRef< +export const githubAuthApiRef: ApiRef< OAuthApi & ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.github', description: 'Provides authentication towards GitHub APIs', }); @@ -242,13 +242,13 @@ export const githubAuthApiRef = createApiRef< * See https://developer.okta.com/docs/guides/implement-oauth-for-okta/scopes/ * for a full list of supported scopes. */ -export const oktaAuthApiRef = createApiRef< +export const oktaAuthApiRef: ApiRef< OAuthApi & OpenIdConnectApi & ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.okta', description: 'Provides authentication towards Okta APIs', }); @@ -259,9 +259,9 @@ export const oktaAuthApiRef = createApiRef< * See https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#limiting-scopes-of-a-personal-access-token * for a full list of supported scopes. */ -export const gitlabAuthApiRef = createApiRef< +export const gitlabAuthApiRef: ApiRef< OAuthApi & ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.gitlab', description: 'Provides authentication towards GitLab APIs', }); @@ -272,9 +272,9 @@ export const gitlabAuthApiRef = createApiRef< * See https://auth0.com/docs/scopes/current/oidc-scopes * for a full list of supported scopes. */ -export const auth0AuthApiRef = createApiRef< +export const auth0AuthApiRef: ApiRef< OpenIdConnectApi & ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.auth0', description: 'Provides authentication towards Auth0 APIs', }); @@ -286,13 +286,13 @@ export const auth0AuthApiRef = createApiRef< * - https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent * - https://docs.microsoft.com/en-us/graph/permissions-reference */ -export const microsoftAuthApiRef = createApiRef< +export const microsoftAuthApiRef: ApiRef< OAuthApi & OpenIdConnectApi & ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.microsoft', description: 'Provides authentication towards Microsoft APIs and identities', }); @@ -300,13 +300,13 @@ export const microsoftAuthApiRef = createApiRef< /** * Provides authentication for custom identity providers. */ -export const oauth2ApiRef = createApiRef< +export const oauth2ApiRef: ApiRef< OAuthApi & OpenIdConnectApi & ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.oauth2', description: 'Example of how to use oauth2 custom provider', }); @@ -314,9 +314,9 @@ export const oauth2ApiRef = createApiRef< /** * Provides authentication for saml based identity providers */ -export const samlAuthApiRef = createApiRef< +export const samlAuthApiRef: ApiRef< ProfileInfoApi & BackstageIdentityApi & SessionApi ->({ +> = createApiRef({ id: 'core.auth.saml', description: 'Example of how to use SAML custom provider', }); diff --git a/packages/core-api/src/apis/implementations/auth/github/GithubAuth.ts b/packages/core-api/src/apis/implementations/auth/github/GithubAuth.ts index 1d87ff3720..eb2f375ab0 100644 --- a/packages/core-api/src/apis/implementations/auth/github/GithubAuth.ts +++ b/packages/core-api/src/apis/implementations/auth/github/GithubAuth.ts @@ -41,6 +41,7 @@ type CreateOptions = { discoveryApi: DiscoveryApi; oauthRequestApi: OAuthRequestApi; + defaultScopes?: string[]; environment?: string; provider?: AuthProvider & { id: string }; }; @@ -67,6 +68,7 @@ class GithubAuth implements OAuthApi, SessionApi { environment = 'development', provider = DEFAULT_PROVIDER, oauthRequestApi, + defaultScopes = ['read:user'], }: CreateOptions) { const connector = new DefaultAuthConnector({ discoveryApi, @@ -89,7 +91,7 @@ class GithubAuth implements OAuthApi, SessionApi { const sessionManager = new StaticAuthSessionManager({ connector, - defaultScopes: new Set(['read:user']), + defaultScopes: new Set(defaultScopes), sessionScopes: (session: GithubSession) => session.providerInfo.scopes, }); diff --git a/packages/core-api/src/apis/index.ts b/packages/core-api/src/apis/index.ts index c856a13668..03569f9570 100644 --- a/packages/core-api/src/apis/index.ts +++ b/packages/core-api/src/apis/index.ts @@ -14,10 +14,6 @@ * limitations under the License. */ -export { ApiProvider, useApi, useApiHolder } from './ApiProvider'; -export { ApiRegistry } from './ApiRegistry'; -export * from './ApiRef'; -export * from './types'; -export * from './helpers'; +export * from './system'; export * from './definitions'; export * from './implementations'; diff --git a/packages/core-api/src/apis/ApiAggregator.test.ts b/packages/core-api/src/apis/system/ApiAggregator.test.ts similarity index 100% rename from packages/core-api/src/apis/ApiAggregator.test.ts rename to packages/core-api/src/apis/system/ApiAggregator.test.ts diff --git a/packages/core-api/src/apis/ApiAggregator.ts b/packages/core-api/src/apis/system/ApiAggregator.ts similarity index 93% rename from packages/core-api/src/apis/ApiAggregator.ts rename to packages/core-api/src/apis/system/ApiAggregator.ts index da49ee6488..1587a1d10b 100644 --- a/packages/core-api/src/apis/ApiAggregator.ts +++ b/packages/core-api/src/apis/system/ApiAggregator.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { ApiRef } from './ApiRef'; -import { ApiHolder } from './types'; +import { ApiRef, ApiHolder } from './types'; /** * An ApiHolder that queries multiple other holders from for diff --git a/packages/core-api/src/apis/ApiFactoryRegistry.test.ts b/packages/core-api/src/apis/system/ApiFactoryRegistry.test.ts similarity index 100% rename from packages/core-api/src/apis/ApiFactoryRegistry.test.ts rename to packages/core-api/src/apis/system/ApiFactoryRegistry.test.ts diff --git a/packages/core-api/src/apis/ApiFactoryRegistry.ts b/packages/core-api/src/apis/system/ApiFactoryRegistry.ts similarity index 98% rename from packages/core-api/src/apis/ApiFactoryRegistry.ts rename to packages/core-api/src/apis/system/ApiFactoryRegistry.ts index 0d36e6c550..556f63589c 100644 --- a/packages/core-api/src/apis/ApiFactoryRegistry.ts +++ b/packages/core-api/src/apis/system/ApiFactoryRegistry.ts @@ -15,12 +15,12 @@ */ import { + ApiRef, ApiFactoryHolder, ApiFactory, AnyApiRef, AnyApiFactory, } from './types'; -import { ApiRef } from './ApiRef'; type ApiFactoryScope = | 'default' // Default factories registered by core and plugins diff --git a/packages/core-api/src/apis/ApiProvider.test.tsx b/packages/core-api/src/apis/system/ApiProvider.test.tsx similarity index 100% rename from packages/core-api/src/apis/ApiProvider.test.tsx rename to packages/core-api/src/apis/system/ApiProvider.test.tsx diff --git a/packages/core-api/src/apis/ApiProvider.tsx b/packages/core-api/src/apis/system/ApiProvider.tsx similarity index 96% rename from packages/core-api/src/apis/ApiProvider.tsx rename to packages/core-api/src/apis/system/ApiProvider.tsx index 24610a1372..f2aa70244e 100644 --- a/packages/core-api/src/apis/ApiProvider.tsx +++ b/packages/core-api/src/apis/system/ApiProvider.tsx @@ -16,8 +16,7 @@ import React, { FC, createContext, useContext, ReactNode } from 'react'; import PropTypes from 'prop-types'; -import { ApiRef } from './ApiRef'; -import { ApiHolder, TypesToApiRefs } from './types'; +import { ApiRef, ApiHolder, TypesToApiRefs } from './types'; import { ApiAggregator } from './ApiAggregator'; type ApiProviderProps = { diff --git a/packages/core-api/src/apis/ApiRef.test.ts b/packages/core-api/src/apis/system/ApiRef.test.ts similarity index 100% rename from packages/core-api/src/apis/ApiRef.test.ts rename to packages/core-api/src/apis/system/ApiRef.test.ts diff --git a/packages/core-api/src/apis/ApiRef.ts b/packages/core-api/src/apis/system/ApiRef.ts similarity index 95% rename from packages/core-api/src/apis/ApiRef.ts rename to packages/core-api/src/apis/system/ApiRef.ts index 793c1e5386..0e1eb177c8 100644 --- a/packages/core-api/src/apis/ApiRef.ts +++ b/packages/core-api/src/apis/system/ApiRef.ts @@ -14,17 +14,13 @@ * limitations under the License. */ +import type { ApiRef } from './types'; + export type ApiRefConfig = { id: string; description: string; }; -export type ApiRef = { - id: string; - description: string; - T: T; -}; - class ApiRefImpl implements ApiRef { constructor(private readonly config: ApiRefConfig) { const valid = config.id diff --git a/packages/core-api/src/apis/ApiRegistry.test.ts b/packages/core-api/src/apis/system/ApiRegistry.test.ts similarity index 100% rename from packages/core-api/src/apis/ApiRegistry.test.ts rename to packages/core-api/src/apis/system/ApiRegistry.test.ts diff --git a/packages/core-api/src/apis/ApiRegistry.ts b/packages/core-api/src/apis/system/ApiRegistry.ts similarity index 96% rename from packages/core-api/src/apis/ApiRegistry.ts rename to packages/core-api/src/apis/system/ApiRegistry.ts index 64d97ba234..14f58268b4 100644 --- a/packages/core-api/src/apis/ApiRegistry.ts +++ b/packages/core-api/src/apis/system/ApiRegistry.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { ApiRef } from './ApiRef'; -import { ApiHolder } from './types'; +import { ApiRef, ApiHolder } from './types'; type ApiImpl = readonly [ApiRef, T]; diff --git a/packages/core-api/src/apis/ApiResolver.test.ts b/packages/core-api/src/apis/system/ApiResolver.test.ts similarity index 100% rename from packages/core-api/src/apis/ApiResolver.test.ts rename to packages/core-api/src/apis/system/ApiResolver.test.ts diff --git a/packages/core-api/src/apis/ApiResolver.ts b/packages/core-api/src/apis/system/ApiResolver.ts similarity index 98% rename from packages/core-api/src/apis/ApiResolver.ts rename to packages/core-api/src/apis/system/ApiResolver.ts index cb65186a37..0dfeaeedd0 100644 --- a/packages/core-api/src/apis/ApiResolver.ts +++ b/packages/core-api/src/apis/system/ApiResolver.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import { ApiRef } from './ApiRef'; import { + ApiRef, ApiHolder, ApiFactoryHolder, AnyApiRef, diff --git a/packages/core-api/src/apis/helpers.ts b/packages/core-api/src/apis/system/helpers.ts similarity index 93% rename from packages/core-api/src/apis/helpers.ts rename to packages/core-api/src/apis/system/helpers.ts index 7d616acd01..0ccd0cdb80 100644 --- a/packages/core-api/src/apis/helpers.ts +++ b/packages/core-api/src/apis/system/helpers.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { ApiFactory, TypesToApiRefs } from './types'; -import { ApiRef } from './ApiRef'; +import { ApiRef, ApiFactory, TypesToApiRefs } from './types'; /** * Used to infer types for a standalone ApiFactory that isn't immediately passed diff --git a/packages/core-api/src/apis/system/index.ts b/packages/core-api/src/apis/system/index.ts new file mode 100644 index 0000000000..10b2e0f084 --- /dev/null +++ b/packages/core-api/src/apis/system/index.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { ApiProvider, useApi, useApiHolder } from './ApiProvider'; +export { ApiRegistry } from './ApiRegistry'; +export { ApiResolver } from './ApiResolver'; +export { ApiFactoryRegistry } from './ApiFactoryRegistry'; +export { createApiRef } from './ApiRef'; +export * from './types'; +export * from './helpers'; diff --git a/packages/core-api/src/apis/types.ts b/packages/core-api/src/apis/system/types.ts similarity index 94% rename from packages/core-api/src/apis/types.ts rename to packages/core-api/src/apis/system/types.ts index 61c229b18e..b0c19e551c 100644 --- a/packages/core-api/src/apis/types.ts +++ b/packages/core-api/src/apis/system/types.ts @@ -14,7 +14,11 @@ * limitations under the License. */ -import { ApiRef } from './ApiRef'; +export type ApiRef = { + id: string; + description: string; + T: T; +}; export type AnyApiRef = ApiRef; diff --git a/packages/core-api/src/app/App.tsx b/packages/core-api/src/app/App.tsx index 9dd2fb138f..0588cd819c 100644 --- a/packages/core-api/src/app/App.tsx +++ b/packages/core-api/src/app/App.tsx @@ -30,12 +30,12 @@ import { SignInPageProps, } from './types'; import { BackstagePlugin } from '../plugin'; -import { FeatureFlagsRegistryItem } from './FeatureFlags'; import { featureFlagsApiRef, AppThemeApi, ConfigApi, identityApiRef, + FeatureFlagsRegistryItem, } from '../apis/definitions'; import { AppThemeProvider } from './AppThemeProvider'; @@ -54,8 +54,7 @@ import { } from '../apis'; import { useAsync } from 'react-use'; import { AppIdentity } from './AppIdentity'; -import { ApiFactoryRegistry } from '../apis/ApiFactoryRegistry'; -import { ApiResolver } from '../apis/ApiResolver'; +import { ApiResolver, ApiFactoryRegistry } from '../apis/system'; type FullAppOptions = { apis: Iterable; diff --git a/packages/core-api/src/app/FeatureFlags.tsx b/packages/core-api/src/app/FeatureFlags.tsx index 3db2a18a02..7a69fa5456 100644 --- a/packages/core-api/src/app/FeatureFlags.tsx +++ b/packages/core-api/src/app/FeatureFlags.tsx @@ -15,7 +15,11 @@ */ import { FeatureFlagName } from '../plugin/types'; -import { FeatureFlagState, FeatureFlagsApi } from '../apis/definitions'; +import { + FeatureFlagState, + FeatureFlagsApi, + FeatureFlagsRegistryItem, +} from '../apis/definitions'; /** * Helper method for validating compatibility and flag name. @@ -129,10 +133,6 @@ export class UserFlags extends Map { * This acts as a holding data structure for feature flags * that plugins wish to register for use in Backstage. */ -export interface FeatureFlagsRegistryItem { - pluginId: string; - name: FeatureFlagName; -} export class FeatureFlagsRegistry extends Array { static from(entries: FeatureFlagsRegistryItem[]) { diff --git a/packages/core-api/src/app/types.ts b/packages/core-api/src/app/types.ts index 882ecd3d8b..8a1eb92e8e 100644 --- a/packages/core-api/src/app/types.ts +++ b/packages/core-api/src/app/types.ts @@ -112,11 +112,13 @@ export type AppOptions = { * title: 'Light Theme', * variant: 'light', * theme: lightTheme, + * icon: , * }, { * id: 'dark', * title: 'Dark Theme', * variant: 'dark', * theme: darkTheme, + * icon: , * }] * ``` */ diff --git a/packages/core-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts b/packages/core-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts index 5781130799..391b86952d 100644 --- a/packages/core-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts +++ b/packages/core-api/src/lib/AuthConnector/DefaultAuthConnector.test.ts @@ -19,8 +19,9 @@ import { DefaultAuthConnector } from './DefaultAuthConnector'; import MockOAuthApi from '../../apis/implementations/OAuthRequestApi/MockOAuthApi'; import * as loginPopup from '../loginPopup'; import { UrlPatternDiscovery } from '../../apis'; - -const anyFetch = fetch as any; +import { msw } from '@backstage/test-utils'; +import { setupServer } from 'msw/node'; +import { rest } from 'msw'; const defaultOptions = { discoveryApi: UrlPatternDiscovery.compile('http://my-host/api/{{pluginId}}'), @@ -39,19 +40,25 @@ const defaultOptions = { }; describe('DefaultAuthConnector', () => { + const server = setupServer(); + msw.setupDefaultHandlers(server); + afterEach(() => { jest.resetAllMocks(); - anyFetch.resetMocks(); }); it('should refresh a session', async () => { - anyFetch.mockResponseOnce( - JSON.stringify({ - idToken: 'mock-id-token', - accessToken: 'mock-access-token', - scopes: 'a b c', - expiresInSeconds: '60', - }), + server.use( + rest.get('*', (_req, res, ctx) => + res( + ctx.json({ + idToken: 'mock-id-token', + accessToken: 'mock-access-token', + scopes: 'a b c', + expiresInSeconds: '60', + }), + ), + ), ); const helper = new DefaultAuthConnector(defaultOptions); @@ -64,7 +71,11 @@ describe('DefaultAuthConnector', () => { }); it('should handle failure to refresh session', async () => { - anyFetch.mockRejectOnce(new Error('Network NOPE')); + server.use( + rest.get('*', (_req, res, ctx) => + res(ctx.status(500, 'Error: Network NOPE')), + ), + ); const helper = new DefaultAuthConnector(defaultOptions); await expect(helper.refreshSession()).rejects.toThrow( @@ -73,7 +84,7 @@ describe('DefaultAuthConnector', () => { }); it('should handle failure response when refreshing session', async () => { - anyFetch.mockResponseOnce({}, { status: 401, statusText: 'NOPE' }); + server.use(rest.get('*', (_req, res, ctx) => res(ctx.status(401, 'NOPE')))); const helper = new DefaultAuthConnector(defaultOptions); await expect(helper.refreshSession()).rejects.toThrow( diff --git a/packages/core-api/src/plugin/Plugin.tsx b/packages/core-api/src/plugin/Plugin.tsx index 1835ec03ad..866d430070 100644 --- a/packages/core-api/src/plugin/Plugin.tsx +++ b/packages/core-api/src/plugin/Plugin.tsx @@ -14,50 +14,10 @@ * limitations under the License. */ -import { ComponentType } from 'react'; -import { - PluginOutput, - RoutePath, - RouteOptions, - FeatureFlagName, - BackstagePlugin, -} from './types'; +import { PluginConfig, PluginOutput, BackstagePlugin } from './types'; import { validateBrowserCompat, validateFlagName } from '../app/FeatureFlags'; -import { RouteRef } from '../routing'; import { AnyApiFactory } from '../apis'; -export type PluginConfig = { - id: string; - apis?: Iterable; - register?(hooks: PluginHooks): void; -}; - -export type PluginHooks = { - router: RouterHooks; - featureFlags: FeatureFlagsHooks; -}; - -export type RouterHooks = { - addRoute( - target: RouteRef, - Component: ComponentType, - options?: RouteOptions, - ): void; - - /** - * @deprecated See the `addRoute` method - */ - registerRoute( - path: RoutePath, - Component: ComponentType, - options?: RouteOptions, - ): void; -}; - -export type FeatureFlagsHooks = { - register(name: FeatureFlagName): void; -}; - export class PluginImpl { private storedOutput?: PluginOutput[]; diff --git a/packages/core-api/src/plugin/types.ts b/packages/core-api/src/plugin/types.ts index 12992f3620..76c05f7b04 100644 --- a/packages/core-api/src/plugin/types.ts +++ b/packages/core-api/src/plugin/types.ts @@ -16,7 +16,7 @@ import { ComponentType } from 'react'; import { RouteRef } from '../routing'; -import { AnyApiFactory } from '../apis'; +import { AnyApiFactory } from '../apis/system'; export type RouteOptions = { // Whether the route path must match exactly, defaults to true. @@ -73,3 +73,35 @@ export type BackstagePlugin = { output(): PluginOutput[]; getApis(): Iterable; }; + +export type PluginConfig = { + id: string; + apis?: Iterable; + register?(hooks: PluginHooks): void; +}; + +export type PluginHooks = { + router: RouterHooks; + featureFlags: FeatureFlagsHooks; +}; + +export type RouterHooks = { + addRoute( + target: RouteRef, + Component: ComponentType, + options?: RouteOptions, + ): void; + + /** + * @deprecated See the `addRoute` method + */ + registerRoute( + path: RoutePath, + Component: ComponentType, + options?: RouteOptions, + ): void; +}; + +export type FeatureFlagsHooks = { + register(name: FeatureFlagName): void; +}; diff --git a/packages/core-api/src/setupTests.ts b/packages/core-api/src/setupTests.ts index 8553642152..aea2220869 100644 --- a/packages/core-api/src/setupTests.ts +++ b/packages/core-api/src/setupTests.ts @@ -15,5 +15,4 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); +import 'cross-fetch/polyfill'; diff --git a/packages/core/package.json b/packages/core/package.json index 0a0dc7576c..ec4411b390 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/core", "description": "Core API used by Backstage plugins and apps", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "private": false, "publishConfig": { "access": "public", @@ -29,9 +29,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/config": "^0.1.1-alpha.24", - "@backstage/core-api": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/config": "^0.1.1-alpha.26", + "@backstage/core-api": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -39,8 +39,9 @@ "@types/react-sparklines": "^1.7.0", "classnames": "^2.2.6", "clsx": "^1.1.0", + "immer": "^7.0.9", "lodash": "^4.17.15", - "material-table": "1.68.0", + "material-table": "^1.69.1", "prop-types": "^15.7.2", "rc-progress": "^3.0.0", "react": "^16.12.0", @@ -54,8 +55,8 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", @@ -64,8 +65,7 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/react-helmet": "^6.1.0", - "@types/zen-observable": "^0.8.0", - "jest-fetch-mock": "^3.0.3" + "@types/zen-observable": "^0.8.0" }, "files": [ "dist" diff --git a/packages/core/src/api-wrappers/createApp.tsx b/packages/core/src/api-wrappers/createApp.tsx index 7fe77423e2..c7d0f5ce01 100644 --- a/packages/core/src/api-wrappers/createApp.tsx +++ b/packages/core/src/api-wrappers/createApp.tsx @@ -22,7 +22,8 @@ import privateExports, { AppConfigLoader, } from '@backstage/core-api'; import { BrowserRouter, MemoryRouter } from 'react-router-dom'; - +import LightIcon from '@material-ui/icons/WbSunny'; +import DarkIcon from '@material-ui/icons/Brightness2'; import { ErrorPage } from '../layout/ErrorPage'; import { Progress } from '../components/Progress'; import { defaultApis } from './defaultApis'; @@ -110,12 +111,14 @@ export function createApp(options?: AppOptions) { title: 'Light Theme', variant: 'light', theme: lightTheme, + icon: , }, { id: 'dark', title: 'Dark Theme', variant: 'dark', theme: darkTheme, + icon: , }, ]; const configLoader = options?.configLoader ?? defaultConfigLoader; diff --git a/packages/core/src/api-wrappers/defaultApis.ts b/packages/core/src/api-wrappers/defaultApis.ts index dedadf0456..e735e4d371 100644 --- a/packages/core/src/api-wrappers/defaultApis.ts +++ b/packages/core/src/api-wrappers/defaultApis.ts @@ -96,7 +96,11 @@ export const defaultApis = [ oauthRequestApi: oauthRequestApiRef, }, factory: ({ discoveryApi, oauthRequestApi }) => - GithubAuth.create({ discoveryApi, oauthRequestApi }), + GithubAuth.create({ + discoveryApi, + oauthRequestApi, + defaultScopes: ['read:user'], + }), }), createApiFactory({ api: oktaAuthApiRef, diff --git a/packages/core/src/components/Button/Button.stories.tsx b/packages/core/src/components/Button/Button.stories.tsx index aaca389f82..a5005574fe 100644 --- a/packages/core/src/components/Button/Button.stories.tsx +++ b/packages/core/src/components/Button/Button.stories.tsx @@ -24,7 +24,7 @@ const Location = () => { }; export default { - title: 'Button', + title: 'Inputs/Button', component: Button, decorators: [ (storyFn: FunctionComponentFactory<{}>) => ( diff --git a/packages/core/src/components/Button/Button.test.jsx b/packages/core/src/components/Button/Button.test.tsx similarity index 94% rename from packages/core/src/components/Button/Button.test.jsx rename to packages/core/src/components/Button/Button.test.tsx index 115835be3f..8bae5f2767 100644 --- a/packages/core/src/components/Button/Button.test.jsx +++ b/packages/core/src/components/Button/Button.test.tsx @@ -34,7 +34,9 @@ describe(' + +
+ {filters?.length && + filters.map(filter => + filter.type === 'checkbox-tree' ? ( + + setSelectedFilters({ + ...selectedFilters, + [filter.element.label]: el + .filter( + (checkboxFilter: any) => + checkboxFilter.category !== null || + checkboxFilter.selectedChilds.length, + ) + .map((checkboxFilter: any) => + checkboxFilter.category !== null + ? [ + ...checkboxFilter.selectedChilds, + checkboxFilter.category, + ] + : checkboxFilter.selectedChilds, + ) + .flat(), + }) + } + /> + ) : ( + ); }; - -export default CurrencySelect; diff --git a/plugins/cost-insights/src/components/CurrencySelect/index.ts b/plugins/cost-insights/src/components/CurrencySelect/index.ts index 322b67d4ce..5e42217fe1 100644 --- a/plugins/cost-insights/src/components/CurrencySelect/index.ts +++ b/plugins/cost-insights/src/components/CurrencySelect/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './CurrencySelect'; +export { CurrencySelect } from './CurrencySelect'; diff --git a/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/LabelDataflowInstructionsPage.tsx b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/LabelDataflowInstructionsPage.tsx index 9783fadcb2..3442de49fc 100644 --- a/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/LabelDataflowInstructionsPage.tsx +++ b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/LabelDataflowInstructionsPage.tsx @@ -17,9 +17,9 @@ import React from 'react'; import { Box, Typography } from '@material-ui/core'; import { CodeSnippet } from '@backstage/core'; -import AlertInstructionsLayout from '../AlertInstructionsLayout'; +import { AlertInstructionsLayout } from '../AlertInstructionsLayout'; -const LabelDataflowInstructionsPage = () => { +export const LabelDataflowInstructionsPage = () => { return ( Labeling Dataflow Jobs @@ -92,5 +92,3 @@ sc.optionsAs[DataflowPipelineOptions].setLabels(Map("job-id" -> "my-dataflow-job ); }; - -export default LabelDataflowInstructionsPage; diff --git a/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/index.ts b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/index.ts index 052ed379ec..de2136f033 100644 --- a/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/index.ts +++ b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './LabelDataflowInstructionsPage'; +export { LabelDataflowInstructionsPage } from './LabelDataflowInstructionsPage'; diff --git a/plugins/cost-insights/src/components/LegendItem/LegendItem.tsx b/plugins/cost-insights/src/components/LegendItem/LegendItem.tsx index dd87ecc8a1..9424c50bf7 100644 --- a/plugins/cost-insights/src/components/LegendItem/LegendItem.tsx +++ b/plugins/cost-insights/src/components/LegendItem/LegendItem.tsx @@ -14,25 +14,24 @@ * limitations under the License. */ -import React from 'react'; +import React, { PropsWithChildren } from 'react'; import { Box, Typography, Tooltip } from '@material-ui/core'; import LensIcon from '@material-ui/icons/Lens'; import HelpOutlineOutlinedIcon from '@material-ui/icons/HelpOutlineOutlined'; import { useCostGrowthLegendStyles } from '../../utils/styles'; -type LegendItemProps = { +export type LegendItemProps = { title: string; tooltipText?: string; markerColor?: string; - children?: React.ReactNode; }; -const LegendItem = ({ +export const LegendItem = ({ title, tooltipText, markerColor, children, -}: LegendItemProps) => { +}: PropsWithChildren) => { const classes = useCostGrowthLegendStyles(); return ( @@ -74,5 +73,3 @@ const LegendItem = ({ ); }; - -export default LegendItem; diff --git a/plugins/cost-insights/src/components/LegendItem/index.ts b/plugins/cost-insights/src/components/LegendItem/index.ts index 763b8fc4f4..e97af0c97f 100644 --- a/plugins/cost-insights/src/components/LegendItem/index.ts +++ b/plugins/cost-insights/src/components/LegendItem/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './LegendItem'; +export { LegendItem } from './LegendItem'; diff --git a/plugins/cost-insights/src/components/MetricSelect/MetricSelect.test.tsx b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.test.tsx index 67d1ec3ad3..bfb6daedd6 100644 --- a/plugins/cost-insights/src/components/MetricSelect/MetricSelect.test.tsx +++ b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.test.tsx @@ -16,14 +16,14 @@ import React from 'react'; import { waitFor } from '@testing-library/react'; import UserEvent from '@testing-library/user-event'; -import MetricSelect, { MetricSelectProps } from './MetricSelect'; +import { MetricSelect, MetricSelectProps } from './MetricSelect'; import { renderInTestApp } from '@backstage/test-utils'; describe('', () => { it('should display a metric', async () => { const mockProps: MetricSelectProps = { metric: 'test', - metrics: [{ kind: 'test', name: 'some-name' }], + metrics: [{ kind: 'test', name: 'some-name', default: false }], onSelect: jest.fn(), }; const { getByText } = await renderInTestApp( @@ -32,25 +32,12 @@ describe('', () => { expect(getByText(/some-name/)).toBeInTheDocument(); }); - it('should display a null metric', async () => { - const mockProps: MetricSelectProps = { - metric: null, - metrics: [{ kind: null, name: 'billie-nullish' }], - onSelect: jest.fn(), - }; - const { getByText } = await renderInTestApp( - , - ); - expect(getByText(/billie-nullish/)).toBeInTheDocument(); - }); - it('should display all metrics', async () => { const mockProps: MetricSelectProps = { metric: null, metrics: [ - { kind: null, name: 'billie-nullish' }, - { kind: 'MAU1M', name: 'Cost Per Million MAU' }, - { kind: 'my-cool-metric', name: 'metric-mcmetric-face' }, + { kind: 'DAU', name: 'Daily Active Users', default: true }, + { kind: 'MSC', name: 'Monthly Subscribers', default: false }, ], onSelect: jest.fn(), }; @@ -61,11 +48,10 @@ describe('', () => { UserEvent.click(button); - await waitFor(() => getAllByText(/billie-nullish/)); + await waitFor(() => getAllByText(/None/)); // The active metric should display in the popver list and in the input - expect(getAllByText(/billie-nullish/).length).toBe(2); - expect(getByText(/Cost Per Million MAU/)).toBeInTheDocument(); - expect(getByText(/metric-mcmetric-face/)).toBeInTheDocument(); + expect(getByText(/Daily Active Users/)).toBeInTheDocument(); + expect(getByText(/Monthly Subscribers/)).toBeInTheDocument(); }); }); diff --git a/plugins/cost-insights/src/components/MetricSelect/MetricSelect.tsx b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.tsx index 1d3af911d4..a8197fd7e9 100644 --- a/plugins/cost-insights/src/components/MetricSelect/MetricSelect.tsx +++ b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.tsx @@ -15,10 +15,9 @@ */ import React from 'react'; -import { Select, MenuItem } from '@material-ui/core'; -import { Maybe, Metric, findAlways } from '../../types'; +import { InputLabel, FormControl, Select, MenuItem } from '@material-ui/core'; +import { Maybe, Metric } from '../../types'; import { useSelectStyles as useStyles } from '../../utils/styles'; -import { NULL_METRIC } from '../../hooks/useConfig'; export type MetricSelectProps = { metric: Maybe; @@ -26,42 +25,43 @@ export type MetricSelectProps = { onSelect: (metric: Maybe) => void; }; -const MetricSelect = ({ metric, metrics, onSelect }: MetricSelectProps) => { +export const MetricSelect = ({ + metric, + metrics, + onSelect, +}: MetricSelectProps) => { const classes = useStyles(); - const handleOnChange = (e: React.ChangeEvent<{ value: unknown }>) => { - if (e.target.value === NULL_METRIC) { + function onChange(e: React.ChangeEvent<{ value: unknown }>) { + if (e.target.value === 'none') { onSelect(null); } else { onSelect(e.target.value as string); } - }; - - const renderValue = (value: unknown) => { - const kind = (value === NULL_METRIC ? null : value) as Maybe; - const { name } = findAlways(metrics, m => m.kind === kind); - return {name}; - }; + } return ( - + + None - ))} - + {metrics.map((m: Metric) => ( + + {m.name} + + ))} + + ); }; - -export default MetricSelect; diff --git a/plugins/cost-insights/src/components/MetricSelect/index.ts b/plugins/cost-insights/src/components/MetricSelect/index.ts index f68e5031c1..4be7e97e90 100644 --- a/plugins/cost-insights/src/components/MetricSelect/index.ts +++ b/plugins/cost-insights/src/components/MetricSelect/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './MetricSelect'; +export { MetricSelect } from './MetricSelect'; diff --git a/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.test.tsx b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.test.tsx index c632ebad34..e2cf1b7480 100644 --- a/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.test.tsx +++ b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.test.tsx @@ -16,33 +16,41 @@ import React from 'react'; import { getByRole, waitFor } from '@testing-library/react'; -import UserEvent from '@testing-library/user-event'; -import PeriodSelect, { DEFAULT_OPTIONS as options } from './PeriodSelect'; -import { Duration, getDefaultPageFilters, Group } from '../../types'; - import { renderInTestApp } from '@backstage/test-utils'; +import UserEvent from '@testing-library/user-event'; +import { PeriodSelect, getDefaultOptions } from './PeriodSelect'; +import { Duration, getDefaultPageFilters, Group } from '../../types'; +import { MockBillingDateProvider } from '../../utils/tests'; const DefaultPageFilters = getDefaultPageFilters([{ id: 'tools' }] as Group[]); - -Date.now = jest.fn(() => new Date(Date.parse('2020-05-01')).valueOf()); +const lastCompleteBillingDate = '2020-05-01'; +const options = getDefaultOptions(lastCompleteBillingDate); describe('', () => { it('Renders without exploding', async () => { const rendered = await renderInTestApp( - , + + + , ); expect(rendered.getByTestId('period-select')).toBeInTheDocument(); }); it('Should display all costGrowth period options', async () => { const rendered = await renderInTestApp( - , + + + , ); const periodSelectContainer = rendered.getByTestId('period-select'); const button = getByRole(periodSelectContainer, 'button'); @@ -70,7 +78,11 @@ describe('', () => { : DefaultPageFilters.duration; const rendered = await renderInTestApp( - , + + , + , ); const periodSelect = rendered.getByTestId('period-select'); const button = getByRole(periodSelect, 'button'); diff --git a/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.tsx b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.tsx index 688e22452e..07365c32eb 100644 --- a/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.tsx +++ b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.tsx @@ -22,35 +22,35 @@ import { } from '../../utils/formatters'; import { Duration, findAlways } from '../../types'; import { useSelectStyles as useStyles } from '../../utils/styles'; +import { useLastCompleteBillingDate } from '../../hooks'; export type PeriodOption = { value: Duration; label: string; }; -const LAST_6_MONTHS = 'Past 6 Months'; -const LAST_60_DAYS = 'Past 60 Days'; -const LAST_2_COMPLETED_MONTHS = formatLastTwoMonths(); -const LAST_2_LOOKAHEAD_QUARTERS = formatLastTwoLookaheadQuarters(); - -export const DEFAULT_OPTIONS: PeriodOption[] = [ - { - value: Duration.P90D, - label: LAST_6_MONTHS, - }, - { - value: Duration.P30D, - label: LAST_60_DAYS, - }, - { - value: Duration.P1M, - label: LAST_2_COMPLETED_MONTHS, - }, - { - value: Duration.P3M, - label: LAST_2_LOOKAHEAD_QUARTERS, - }, -]; +export function getDefaultOptions( + lastCompleteBillingDate: string, +): PeriodOption[] { + return [ + { + value: Duration.P90D, + label: 'Past 6 Months', + }, + { + value: Duration.P30D, + label: 'Past 60 Days', + }, + { + value: Duration.P1M, + label: formatLastTwoMonths(lastCompleteBillingDate), + }, + { + value: Duration.P3M, + label: formatLastTwoLookaheadQuarters(lastCompleteBillingDate), + }, + ]; +} type PeriodSelectProps = { duration: Duration; @@ -58,19 +58,22 @@ type PeriodSelectProps = { options?: PeriodOption[]; }; -const PeriodSelect = ({ +export const PeriodSelect = ({ duration, onSelect, - options = DEFAULT_OPTIONS, + options, }: PeriodSelectProps) => { const classes = useStyles(); + const lastCompleteBillingDate = useLastCompleteBillingDate(); + const optionsOrDefault = + options ?? getDefaultOptions(lastCompleteBillingDate); const handleOnChange: SelectProps['onChange'] = e => { onSelect(e.target.value as Duration); }; const renderValue: SelectProps['renderValue'] = value => { - const option = findAlways(DEFAULT_OPTIONS, o => o.value === value); + const option = findAlways(optionsOrDefault, o => o.value === value); return {option.label}; }; @@ -83,7 +86,7 @@ const PeriodSelect = ({ renderValue={renderValue} data-testid="period-select" > - {options.map(option => ( + {optionsOrDefault.map(option => ( ); }; - -export default PeriodSelect; diff --git a/plugins/cost-insights/src/components/PeriodSelect/index.ts b/plugins/cost-insights/src/components/PeriodSelect/index.ts index 7bd70b3358..31ca2a649c 100644 --- a/plugins/cost-insights/src/components/PeriodSelect/index.ts +++ b/plugins/cost-insights/src/components/PeriodSelect/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './PeriodSelect'; +export { PeriodSelect } from './PeriodSelect'; diff --git a/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx index cc52012543..16146cb045 100644 --- a/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx +++ b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx @@ -16,12 +16,11 @@ import React from 'react'; import { Box, Typography, Grid } from '@material-ui/core'; -import ProductInsightsCard from '../ProductInsightsCard'; +import { ProductInsightsCard } from '../ProductInsightsCard'; import { useConfig } from '../../hooks'; -const ProductInsights = ({}) => { - const { products } = useConfig(); - +export const ProductInsights = ({}) => { + const config = useConfig(); return ( <> @@ -30,7 +29,7 @@ const ProductInsights = ({}) => { - {products.map(product => ( + {config.products.map(product => ( @@ -39,5 +38,3 @@ const ProductInsights = ({}) => { ); }; - -export default ProductInsights; diff --git a/plugins/cost-insights/src/components/ProductInsights/index.ts b/plugins/cost-insights/src/components/ProductInsights/index.ts index 0a20d3c322..84c2d410b0 100644 --- a/plugins/cost-insights/src/components/ProductInsights/index.ts +++ b/plugins/cost-insights/src/components/ProductInsights/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './ProductInsights'; +export { ProductInsights } from './ProductInsights'; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx index 6d40fc276a..9d1610e298 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx @@ -15,48 +15,27 @@ */ import React from 'react'; -import ProductInsightsCard from './ProductInsightsCard'; +import { renderInTestApp } from '@backstage/test-utils'; +import { ProductInsightsCard } from './ProductInsightsCard'; +import { CostInsightsApi } from '../../api'; import { - MockComputeEngine, createMockEntity, - mockDefaultState, createMockProductCost, + mockDefaultLoadingState, + MockComputeEngine, + MockProductFilters, } from '../../utils/mockData'; import { - IdentityApi, - ApiRegistry, - identityApiRef, - ApiProvider, -} from '@backstage/core'; -import { costInsightsApiRef, CostInsightsApi } from '../../api'; -import { renderInTestApp } from '@backstage/test-utils'; -import { GroupsContext } from '../../hooks/useGroups'; -import { LoadingContext } from '../../hooks/useLoading'; -import { - Product, - ProductCost, - defaultCurrencies, - findAlways, -} from '../../types'; -import { + MockCostInsightsApiProvider, + MockBillingDateProvider, MockConfigProvider, - MockFilterProvider, MockCurrencyProvider, + MockFilterProvider, + MockGroupsProvider, MockScrollProvider, + MockLoadingProvider, } from '../../utils/tests'; - -const mockLoadingDispatch = jest.fn(); -const mockSetPageFilters = jest.fn(); -const mockSetProductFilters = jest.fn(); -const mockSetCurrency = jest.fn(); -const engineers = findAlways(defaultCurrencies, c => c.kind === null); - -const identityApi: Partial = { - getProfile: () => ({ - email: 'test-email@example.com', - displayName: 'User 1', - }), -}; +import { Duration, Product, ProductCost, ProductPeriod } from '../../types'; const costInsightsApi = ( productCost: ProductCost, @@ -65,13 +44,6 @@ const costInsightsApi = ( Promise.resolve(productCost) as Promise, }); -const getApis = (productCost: ProductCost) => { - return ApiRegistry.from([ - [identityApiRef, identityApi], - [costInsightsApiRef, costInsightsApi(productCost)], - ]); -}; - const mockProductCost = createMockProductCost(() => ({ entities: [], aggregation: [3000, 4000], @@ -84,41 +56,31 @@ const mockProductCost = createMockProductCost(() => ({ const renderProductInsightsCardInTestApp = async ( productCost: ProductCost, product: Product, + duration: Duration, ) => await renderInTestApp( - - - - - - - - - - - - - + + + + + + ({ + ...p, + duration: duration, + }))} + > + + + + + + + + + - , + , ); describe('', () => { @@ -126,6 +88,7 @@ describe('', () => { const rendered = await renderProductInsightsCardInTestApp( mockProductCost, MockComputeEngine, + Duration.P1M, ); expect( rendered.queryByTestId(`scroll-test-compute-engine`), @@ -140,6 +103,7 @@ describe('', () => { const rendered = await renderProductInsightsCardInTestApp( productCost, MockComputeEngine, + Duration.P1M, ); const subheader = 'entities, sorted by cost'; const subheaderRgx = new RegExp( @@ -154,6 +118,7 @@ describe('', () => { const rendered = await renderProductInsightsCardInTestApp( productCost, MockComputeEngine, + Duration.P1M, ); const subheaderRgx = new RegExp(subheader); expect(rendered.getByText(subheaderRgx)).toBeInTheDocument(); @@ -164,4 +129,27 @@ describe('', () => { rendered.queryByTestId('.insights-bar-chart'), ).not.toBeInTheDocument(); }); + + describe.each` + duration | periodStartText | periodEndText + ${Duration.P30D} | ${'First 30 Days'} | ${'Last 30 Days'} + ${Duration.P90D} | ${'First 90 Days'} | ${'Last 90 Days'} + `( + 'Should display the correct relative time', + ({ duration, periodStartText, periodEndText }) => { + it(`Should display the correct relative time for ${duration}`, async () => { + const productCost = { + ...mockProductCost, + entities: [...Array(3)].map(createMockEntity), + }; + const rendered = await renderProductInsightsCardInTestApp( + productCost, + MockComputeEngine, + duration, + ); + expect(rendered.getByText(periodStartText)).toBeInTheDocument(); + expect(rendered.getByText(periodEndText)).toBeInTheDocument(); + }); + }, + ); }); diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx index 1d24139c64..840c99522a 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx @@ -19,27 +19,34 @@ import { InfoCard, useApi } from '@backstage/core'; import { Box } from '@material-ui/core'; import Alert from '@material-ui/lab/Alert'; import { costInsightsApiRef } from '../../api'; -import PeriodSelect from '../PeriodSelect'; -import ResourceGrowthBarChart from '../ResourceGrowthBarChart'; -import ResourceGrowthBarChartLegend from '../ResourceGrowthBarChartLegend'; -import { useFilters, useLoading, useScroll } from '../../hooks'; +import { PeriodSelect } from '../PeriodSelect'; +import { ResourceGrowthBarChart } from '../ResourceGrowthBarChart'; +import { ResourceGrowthBarChartLegend } from '../ResourceGrowthBarChartLegend'; +import { + useFilters, + useLastCompleteBillingDate, + useLoading, + useScroll, +} from '../../hooks'; import { useProductInsightsCardStyles as useStyles } from '../../utils/styles'; import { mapFiltersToProps, mapLoadingToProps } from './selector'; import { Duration, Maybe, Product, ProductCost } from '../../types'; import { pluralOf } from '../../utils/grammar'; +import { formatPeriod } from '../../utils/formatters'; type ProductInsightsCardProps = { product: Product; }; -const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { +export const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { const client = useApi(costInsightsApiRef); const classes = useStyles(); const { ScrollAnchor } = useScroll(product.kind); + const lastCompleteBillingDate = useLastCompleteBillingDate(); const [resource, setResource] = useState>(null); const [error, setError] = useState>(null); - const { group, product: productFilter, setProduct } = useFilters( + const { group, product: productFilter, setProduct, project } = useFilters( mapFiltersToProps(product.kind), ); const { loadingProduct, dispatchLoading } = useLoading( @@ -51,7 +58,18 @@ const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { const dispatchLoadingProduct = useCallback(dispatchLoading, [product.kind]); const amount = resource?.entities?.length || 0; - const hasCostsWithinTimeframe = resource?.change && amount; + const hasCostsWithinTimeframe = resource?.change && !!amount; + + const previousName = formatPeriod( + productFilter.duration, + lastCompleteBillingDate, + false, + ); + const currentName = formatPeriod( + productFilter.duration, + lastCompleteBillingDate, + true, + ); const subheader = amount ? `${amount} ${pluralOf(amount, 'entity', 'entities')}, sorted by cost` @@ -68,6 +86,7 @@ const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { product.kind, group!, productFilter!.duration, + project, ); setResource(p); } catch (e) { @@ -87,6 +106,7 @@ const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { productFilter, group, product.kind, + project, ]); const onPeriodSelect = (duration: Duration) => { @@ -129,12 +149,15 @@ const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { @@ -143,5 +166,3 @@ const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { ); }; - -export default ProductInsightsCard; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/index.ts b/plugins/cost-insights/src/components/ProductInsightsCard/index.ts index ef378004f0..61222f9466 100644 --- a/plugins/cost-insights/src/components/ProductInsightsCard/index.ts +++ b/plugins/cost-insights/src/components/ProductInsightsCard/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './ProductInsightsCard'; +export { ProductInsightsCard } from './ProductInsightsCard'; diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.test.tsx b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.test.tsx index 5c3856cc9e..4b5da409a4 100644 --- a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.test.tsx +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.test.tsx @@ -16,9 +16,13 @@ import React from 'react'; import { renderInTestApp } from '@backstage/test-utils'; -import ProjectGrowthAlertCard from './ProjectGrowthAlertCard'; -import { createMockProjectGrowthAlert } from '../../utils/mockData'; -import { MockCurrencyProvider, MockConfigProvider } from '../../utils/tests'; +import { ProjectGrowthAlertCard } from './ProjectGrowthAlertCard'; +import { createMockProjectGrowthData } from '../../utils/mockData'; +import { + MockCurrencyProvider, + MockConfigProvider, + MockBillingDateProvider, +} from '../../utils/tests'; import { AlertCost, defaultCurrencies, findAlways } from '../../types'; const engineers = findAlways(defaultCurrencies, c => c.kind === null); @@ -29,8 +33,8 @@ const MockAlertCosts: AlertCost[] = [ { id: 'test-id-2', aggregation: [235, 400] }, ]; -const MockProjectGrowthAlert = createMockProjectGrowthAlert(alert => ({ - ...alert, +const MockProjectGrowthAlert = createMockProjectGrowthData(data => ({ + ...data, project: MockProject, products: MockAlertCosts, })); @@ -42,41 +46,36 @@ describe('', () => { ); const title = new RegExp(`Project growth for ${MockProject}`); const rendered = await renderInTestApp( - - - , - + + + + , + + , ); expect(rendered.getByText(title)).toBeInTheDocument(); expect(rendered.getByText(subheader)).toBeInTheDocument(); + // ISO 8601 quarter format (YYYY-QX) should be transformed to QX YYYY + expect(rendered.getByText('Q4 2019')).toBeInTheDocument(); + expect(rendered.getByText('Q1 2020')).toBeInTheDocument(); }); it('renders the correct title and subheader for a single service', async () => { const subheader = new RegExp('1 product'); const title = new RegExp(`Project growth for ${MockProject}`); const rendered = await renderInTestApp( - - - - + + + + + + , ); expect(rendered.getByText(title)).toBeInTheDocument(); diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx index c27b201202..4311bcc1bf 100644 --- a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx @@ -15,24 +15,29 @@ */ import React from 'react'; +import moment from 'moment'; import { Box } from '@material-ui/core'; import { InfoCard } from '@backstage/core'; -import ResourceGrowthBarChart from '../ResourceGrowthBarChart'; -import ResourceGrowthBarChartLegend from '../ResourceGrowthBarChartLegend'; -import { Duration, ProjectGrowthAlert } from '../../types'; +import { ResourceGrowthBarChart } from '../ResourceGrowthBarChart'; +import { ResourceGrowthBarChartLegend } from '../ResourceGrowthBarChartLegend'; +import { Duration, ProjectGrowthData } from '../../types'; import { pluralOf } from '../../utils/grammar'; type ProjectGrowthAlertProps = { - alert: ProjectGrowthAlert; + alert: ProjectGrowthData; }; -const ProjectGrowthAlertCard = ({ alert }: ProjectGrowthAlertProps) => { +export const ProjectGrowthAlertCard = ({ alert }: ProjectGrowthAlertProps) => { const [costStart, costEnd] = alert.aggregation; const subheader = ` ${alert.products.length} ${pluralOf(alert.products.length, 'product')}${ alert.products.length > 1 ? ', sorted by cost' : '' }`; + const previousName = moment(alert.periodStart, 'YYYY-[Q]Q').format( + '[Q]Q YYYY', + ); + const currentName = moment(alert.periodEnd, 'YYYY-[Q]Q').format('[Q]Q YYYY'); return ( { ); }; - -export default ProjectGrowthAlertCard; diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/index.ts b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/index.ts index ab608f5f4c..75656f105c 100644 --- a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/index.ts +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './ProjectGrowthAlertCard'; +export { ProjectGrowthAlertCard } from './ProjectGrowthAlertCard'; diff --git a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx index f8f4a90a9e..3c2d241222 100644 --- a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx +++ b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx @@ -17,21 +17,20 @@ import React from 'react'; import { Box, Typography } from '@material-ui/core'; import { InfoCard } from '@backstage/core'; -import AlertInstructionsLayout from '../AlertInstructionsLayout'; -import ProjectGrowthAlertCard from '../ProjectGrowthAlertCard'; +import { AlertInstructionsLayout } from '../AlertInstructionsLayout'; import { - AlertType, + Alert, Duration, Entity, Product, ProjectGrowthAlert, + ProjectGrowthData, } from '../../types'; -import ResourceGrowthBarChartLegend from '../ResourceGrowthBarChartLegend'; -import ResourceGrowthBarChart from '../ResourceGrowthBarChart'; +import { ResourceGrowthBarChartLegend } from '../ResourceGrowthBarChartLegend'; +import { ResourceGrowthBarChart } from '../ResourceGrowthBarChart'; -const ProjectGrowthInstructionsPage = () => { - const projectGrowthAlert: ProjectGrowthAlert = { - id: AlertType.ProjectGrowth, +export const ProjectGrowthInstructionsPage = () => { + const alertData: ProjectGrowthData = { project: 'example-project', periodStart: 'Q1 2020', periodEnd: 'Q2 2020', @@ -55,6 +54,7 @@ const ProjectGrowthInstructionsPage = () => { }, ], }; + const projectGrowthAlert: Alert = new ProjectGrowthAlert(alertData); const product: Product = { kind: 'ComputeEngine', @@ -135,7 +135,7 @@ const ProjectGrowthInstructionsPage = () => { comparison of cloud products over the examined time period: - + {projectGrowthAlert.element} This allows you to quickly see which cloud products contributed to the @@ -160,14 +160,17 @@ const ProjectGrowthInstructionsPage = () => { @@ -208,5 +211,3 @@ const ProjectGrowthInstructionsPage = () => { ); }; - -export default ProjectGrowthInstructionsPage; diff --git a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/index.ts b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/index.ts index c75240405c..053289b2e2 100644 --- a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/index.ts +++ b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './ProjectGrowthInstructionsPage'; +export { ProjectGrowthInstructionsPage } from './ProjectGrowthInstructionsPage'; diff --git a/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.test.tsx b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.test.tsx index 92de819fe0..16270429e8 100644 --- a/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.test.tsx +++ b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.test.tsx @@ -17,7 +17,7 @@ import React from 'react'; import { getByRole, waitFor } from '@testing-library/react'; import UserEvent from '@testing-library/user-event'; -import ProjectSelect from './ProjectSelect'; +import { ProjectSelect } from './ProjectSelect'; import { MockFilterProvider } from '../../utils/tests'; import { renderInTestApp } from '@backstage/test-utils'; @@ -27,20 +27,15 @@ const mockProjects = [ { id: 'project3' }, ]; -const mockSetPageFilters = jest.fn(); - describe('', () => { let Component: React.ReactNode; beforeEach(() => { Component = () => ( - + ); @@ -59,10 +54,9 @@ describe('', () => { const button = getByRole(projectSelectContainer, 'button'); UserEvent.click(button); await waitFor(() => rendered.getByTestId('option-all')); - mockProjects.forEach( - project => - project.id && - expect(rendered.getByText(project.id)).toBeInTheDocument(), + + mockProjects.forEach(project => + expect(rendered.getByText(project.id)).toBeInTheDocument(), ); }); }); diff --git a/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.tsx b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.tsx index cbcd8ede4e..ee4641a4eb 100644 --- a/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.tsx +++ b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.tsx @@ -24,7 +24,11 @@ type ProjectSelectProps = { onSelect: (project: Maybe) => void; }; -const ProjectSelect = ({ project, projects, onSelect }: ProjectSelectProps) => { +export const ProjectSelect = ({ + project, + projects, + onSelect, +}: ProjectSelectProps) => { const classes = useStyles(); const projectOptions = [{ id: 'all' } as Project, ...projects] @@ -48,7 +52,7 @@ const ProjectSelect = ({ project, projects, onSelect }: ProjectSelectProps) => { ); }; - -export default ProjectSelect; diff --git a/plugins/cost-insights/src/components/ProjectSelect/index.ts b/plugins/cost-insights/src/components/ProjectSelect/index.ts index 47a2b9e22c..06a553444d 100644 --- a/plugins/cost-insights/src/components/ProjectSelect/index.ts +++ b/plugins/cost-insights/src/components/ProjectSelect/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './ProjectSelect'; +export { ProjectSelect } from './ProjectSelect'; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx index 8355deab7d..e3d9d61d1b 100644 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx @@ -15,8 +15,7 @@ */ import React from 'react'; -import ResourceGrowthBarChart from './ResourceGrowthBarChart'; -import { Duration } from '../../types'; +import { ResourceGrowthBarChart } from './ResourceGrowthBarChart'; import { renderInTestApp } from '@backstage/test-utils'; import { createMockEntity } from '../../utils/mockData'; @@ -32,8 +31,9 @@ describe('', () => { it('Pre-renders without exploding', async () => { const rendered = await renderInTestApp( , ); expect(rendered.queryByTestId('bar-chart-wrapper')).toBeInTheDocument(); diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx index 3ae35ba871..b4014bf00f 100644 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx @@ -16,41 +16,33 @@ import React from 'react'; import { TooltipPayload } from 'recharts'; +import { currencyFormatter } from '../../utils/formatters'; import { - currencyFormatter, - dateRegex, - formatDuration, -} from '../../utils/formatters'; -import { + AlertCost, BarChartData, CostInsightsTheme, DataKey, - Duration, Entity, - inclusiveEndDateOf, - inclusiveStartDateOf, Maybe, ResourceData, - AlertCost, } from '../../types'; -import BarChart from '../BarChart'; +import { BarChart } from '../BarChart'; import { TooltipItemProps } from '../Tooltip'; import { useTheme } from '@material-ui/core'; export type ResourceGrowthBarChartProps = { - duration: Duration; resources: Array; + previousName: string; + currentName: string; }; -const ResourceGrowthBarChart = ({ - duration, +export const ResourceGrowthBarChart = ({ resources, + previousName, + currentName, }: ResourceGrowthBarChartProps) => { const theme = useTheme(); const getTooltipItem = (payload: TooltipPayload): Maybe => { - const label = dateRegex.test(payload.name) - ? formatDuration(payload.name, duration) - : payload.name; const value = typeof payload.value === 'number' ? currencyFormatter.format(payload.value) @@ -61,7 +53,7 @@ const ResourceGrowthBarChart = ({ case DataKey.Current: case DataKey.Previous: return { - label: label, + label: payload.name, value: value, fill: fill, }; @@ -73,8 +65,8 @@ const ResourceGrowthBarChart = ({ const barChartData: BarChartData = { previousFill: theme.palette.lightBlue, currentFill: theme.palette.darkBlue, - previousName: inclusiveStartDateOf(duration), - currentName: inclusiveEndDateOf(duration), + previousName: previousName, + currentName: currentName, }; const resourceData: ResourceData[] = resources.map(resource => { @@ -93,5 +85,3 @@ const ResourceGrowthBarChart = ({ /> ); }; - -export default ResourceGrowthBarChart; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts b/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts index b1388143e4..ef649a17af 100644 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './ResourceGrowthBarChart'; +export { ResourceGrowthBarChart } from './ResourceGrowthBarChart'; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx index 1e432ff3bc..2bc998d9df 100644 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx @@ -14,31 +14,17 @@ * limitations under the License. */ -import React, { ReactNode } from 'react'; +import React, { PropsWithChildren } from 'react'; import { renderInTestApp } from '@backstage/test-utils'; -import ResourceGrowthBarChartLegend from './ResourceGrowthBarChartLegend'; -import { Currency, defaultCurrencies, Duration, findAlways } from '../../types'; +import { ResourceGrowthBarChartLegend } from './ResourceGrowthBarChartLegend'; +import { defaultCurrencies, Duration, findAlways } from '../../types'; import { MockConfigProvider, MockCurrencyProvider } from '../../utils/tests'; const engineers = findAlways(defaultCurrencies, c => c.kind === null); -const MockContext = ({ - children, - currency, -}: { - children: ReactNode; - currency: Currency; -}) => ( - - - {children} - +const MockContext = ({ children }: PropsWithChildren<{}>) => ( + + {children} ); @@ -52,10 +38,12 @@ describe('', () => { ({ ratio, amount, costText, engineerTest }) => { it(`Should display the correct cost and engineer text for ${ratio} percent change`, async () => { const rendered = await renderInTestApp( - + @@ -66,28 +54,4 @@ describe('', () => { }); }, ); - - describe.each` - duration | periodStartText | periodEndText - ${Duration.P30D} | ${'First 30 Days'} | ${'Last 30 Days'} - ${Duration.P90D} | ${'First 90 Days'} | ${'Last 90 Days'} - `( - 'Should display the correct relative time', - ({ duration, periodStartText, periodEndText }) => { - it(`Should display the correct relative time for ${duration}`, async () => { - const rendered = await renderInTestApp( - - - , - ); - expect(rendered.getByText(periodStartText)).toBeInTheDocument(); - expect(rendered.getByText(periodEndText)).toBeInTheDocument(); - }); - }, - ); }); diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx index 1466e18ee1..6b5ce17c95 100644 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx @@ -16,49 +16,39 @@ import React from 'react'; import { Box, useTheme } from '@material-ui/core'; -import LegendItem from '../LegendItem'; -import CostGrowth from '../CostGrowth'; -import { currencyFormatter, formatDuration } from '../../utils/formatters'; -import { - ChangeStatistic, - CostInsightsTheme, - Duration, - inclusiveEndDateOf, - inclusiveStartDateOf, -} from '../../types'; +import { LegendItem } from '../LegendItem'; +import { CostGrowth } from '../CostGrowth'; +import { currencyFormatter } from '../../utils/formatters'; +import { ChangeStatistic, CostInsightsTheme, Duration } from '../../types'; export type ResourceGrowthBarChartLegendProps = { change: ChangeStatistic; duration: Duration; + previousName: string; + currentName: string; costStart: number; costEnd: number; }; -const ResourceGrowthBarChartLegend = ({ +export const ResourceGrowthBarChartLegend = ({ change, duration, + previousName, + currentName, costStart, costEnd, }: ResourceGrowthBarChartLegendProps) => { const theme = useTheme(); - const startOf = inclusiveStartDateOf(duration); - const endOf = inclusiveEndDateOf(duration); - const periodStartTitle = formatDuration(startOf, duration); - const periodEndTitle = formatDuration(endOf, duration); - return ( - + {currencyFormatter.format(costStart)} - + {currencyFormatter.format(costEnd)} @@ -68,5 +58,3 @@ const ResourceGrowthBarChartLegend = ({ ); }; - -export default ResourceGrowthBarChartLegend; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts index 7071799805..ee77a483e6 100644 --- a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './ResourceGrowthBarChartLegend'; +export { ResourceGrowthBarChartLegend } from './ResourceGrowthBarChartLegend'; diff --git a/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx b/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx index 8c12b34ffb..2f1f8fe7e1 100644 --- a/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx +++ b/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx @@ -16,7 +16,7 @@ import React from 'react'; import { renderInTestApp } from '@backstage/test-utils'; -import Tooltip from './Tooltip'; +import { Tooltip } from './Tooltip'; import { CostInsightsThemeProvider } from '../CostInsightsPage/CostInsightsThemeProvider'; const mockTooltipItems = [ diff --git a/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx b/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx index 727b2476c8..e0ee93c669 100644 --- a/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx +++ b/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx @@ -16,7 +16,7 @@ import React from 'react'; import { Box, Typography } from '@material-ui/core'; -import TooltipItem, { TooltipItemProps } from './TooltipItem'; +import { TooltipItem, TooltipItemProps } from './TooltipItem'; import { useTooltipStyles } from '../../utils/styles'; export type TooltipProps = { @@ -24,7 +24,7 @@ export type TooltipProps = { items?: Array; }; -const Tooltip = ({ label, items }: TooltipProps) => { +export const Tooltip = ({ label, items }: TooltipProps) => { const classes = useTooltipStyles(); return ( { ); }; - -export default Tooltip; diff --git a/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx b/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx index 67d4eac15f..a084a0fd1d 100644 --- a/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx +++ b/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx @@ -25,7 +25,7 @@ export type TooltipItemProps = { fill: string; }; -const TooltipItem = ({ fill, label, value }: TooltipItemProps) => { +export const TooltipItem = ({ fill, label, value }: TooltipItemProps) => { const classes = useStyles(); const style = { fill: fill }; return ( @@ -45,5 +45,3 @@ const TooltipItem = ({ fill, label, value }: TooltipItemProps) => { ); }; - -export default TooltipItem; diff --git a/plugins/cost-insights/src/components/Tooltip/index.ts b/plugins/cost-insights/src/components/Tooltip/index.ts index ca20ab1242..b26409480e 100644 --- a/plugins/cost-insights/src/components/Tooltip/index.ts +++ b/plugins/cost-insights/src/components/Tooltip/index.ts @@ -14,5 +14,7 @@ * limitations under the License. */ -export { default } from './Tooltip'; -export * from './TooltipItem'; +export { Tooltip } from './Tooltip'; +export type { TooltipProps } from './Tooltip'; +export { TooltipItem } from './TooltipItem'; +export type { TooltipItemProps } from './TooltipItem'; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx index 6beb204b0d..df38c78a03 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx @@ -15,25 +15,25 @@ */ import React from 'react'; -import UnlabeledDataflowAlertCard from './UnlabeledDataflowAlertCard'; +import { UnlabeledDataflowAlertCard } from './UnlabeledDataflowAlertCard'; import { - createMockUnlabeledDataflowAlert, + createMockUnlabeledDataflowData, createMockUnlabeledDataflowAlertProject, } from '../../utils/mockData'; import { renderInTestApp } from '@backstage/test-utils'; -const MockUnlabeledDataflowAlertMultipleProjects = createMockUnlabeledDataflowAlert( - alert => ({ - ...alert, +const MockUnlabeledDataflowAlertMultipleProjects = createMockUnlabeledDataflowData( + data => ({ + ...data, projects: [...Array(10)].map(() => createMockUnlabeledDataflowAlertProject(), ), }), ); -const MockUnlabeledDataflowAlertSingleProject = createMockUnlabeledDataflowAlert( - alert => ({ - ...alert, +const MockUnlabeledDataflowAlertSingleProject = createMockUnlabeledDataflowData( + data => ({ + ...data, projects: [...Array(1)].map(() => createMockUnlabeledDataflowAlertProject(), ), diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx index 8dff85e867..8bc5ebfb6e 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx @@ -17,16 +17,18 @@ import React from 'react'; import { Box } from '@material-ui/core'; import { InfoCard } from '@backstage/core'; -import UnlabeledDataflowBarChart from '../UnlabeledDataflowBarChart'; -import UnlabeledDataflowBarChartLegend from '../UnlabeledDataflowBarChartLegend'; -import { UnlabeledDataflowAlert } from '../../types'; +import { UnlabeledDataflowBarChart } from './UnlabeledDataflowBarChart'; +import { UnlabeledDataflowBarChartLegend } from './UnlabeledDataflowBarChartLegend'; +import { UnlabeledDataflowData } from '../../types'; import { pluralOf } from '../../utils/grammar'; type UnlabeledDataflowAlertProps = { - alert: UnlabeledDataflowAlert; + alert: UnlabeledDataflowData; }; -const UnlabeledDataflowAlertCard = ({ alert }: UnlabeledDataflowAlertProps) => { +export const UnlabeledDataflowAlertCard = ({ + alert, +}: UnlabeledDataflowAlertProps) => { const projects = pluralOf(alert.projects.length, 'project'); const subheader = ` Showing costs from ${alert.projects.length} ${projects} with unlabeled Dataflow jobs in the last 30 days. @@ -47,5 +49,3 @@ const UnlabeledDataflowAlertCard = ({ alert }: UnlabeledDataflowAlertProps) => { ); }; - -export default UnlabeledDataflowAlertCard; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/UnlabeledDataflowBarChart.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChart.tsx similarity index 96% rename from plugins/cost-insights/src/components/UnlabeledDataflowBarChart/UnlabeledDataflowBarChart.tsx rename to plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChart.tsx index 7b1f4e31ec..faf27ba04f 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/UnlabeledDataflowBarChart.tsx +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChart.tsx @@ -16,7 +16,7 @@ import React from 'react'; import { TooltipPayload } from 'recharts'; -import BarChart from '../BarChart'; +import { BarChart } from '../BarChart'; import { TooltipItemProps } from '../Tooltip'; import { BarChartData, @@ -69,5 +69,3 @@ export const UnlabeledDataflowBarChart = ({ /> ); }; - -export default UnlabeledDataflowBarChart; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.test.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.test.tsx similarity index 93% rename from plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.test.tsx rename to plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.test.tsx index 9ab4e90001..ab38ba8d44 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.test.tsx +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.test.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import UnlabeledDataflowBarChartLegend from './UnlabeledDataflowBarChartLegend'; +import { UnlabeledDataflowBarChartLegend } from './UnlabeledDataflowBarChartLegend'; import { renderInTestApp } from '@backstage/test-utils'; describe('', () => { diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.tsx similarity index 92% rename from plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.tsx rename to plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.tsx index 68caaed6d0..aac37c799d 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.tsx +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowBarChartLegend.tsx @@ -16,7 +16,7 @@ import React from 'react'; import { Box, useTheme } from '@material-ui/core'; -import LegendItem from '../LegendItem'; +import { LegendItem } from '../LegendItem'; import { currencyFormatter } from '../../utils/formatters'; import { CostInsightsTheme } from '../../types'; @@ -25,7 +25,7 @@ type UnlabeledDataflowBarChartLegendProps = { unlabeledCost: number; }; -const UnlabeledDataflowBarChartLegend = ({ +export const UnlabeledDataflowBarChartLegend = ({ unlabeledCost, labeledCost, }: UnlabeledDataflowBarChartLegendProps) => { @@ -55,5 +55,3 @@ const UnlabeledDataflowBarChartLegend = ({ ); }; - -export default UnlabeledDataflowBarChartLegend; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/index.ts b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/index.ts index 6f22abc062..11f7a6b6dd 100644 --- a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/index.ts +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './UnlabeledDataflowAlertCard'; +export { UnlabeledDataflowAlertCard } from './UnlabeledDataflowAlertCard'; diff --git a/plugins/cost-insights/src/components/WhyCostsMatter/WhyCostsMatter.tsx b/plugins/cost-insights/src/components/WhyCostsMatter/WhyCostsMatter.tsx index 69de854b00..18b5307d86 100644 --- a/plugins/cost-insights/src/components/WhyCostsMatter/WhyCostsMatter.tsx +++ b/plugins/cost-insights/src/components/WhyCostsMatter/WhyCostsMatter.tsx @@ -17,7 +17,7 @@ import React from 'react'; import { Typography, Box, Grid, Container, Divider } from '@material-ui/core'; -const WhyCostsMatter = () => { +export const WhyCostsMatter = () => { return ( @@ -73,5 +73,3 @@ const WhyCostsMatter = () => { ); }; - -export default WhyCostsMatter; diff --git a/plugins/cost-insights/src/components/WhyCostsMatter/index.ts b/plugins/cost-insights/src/components/WhyCostsMatter/index.ts index ed60207fde..ef847d20aa 100644 --- a/plugins/cost-insights/src/components/WhyCostsMatter/index.ts +++ b/plugins/cost-insights/src/components/WhyCostsMatter/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './WhyCostsMatter'; +export { WhyCostsMatter } from './WhyCostsMatter'; diff --git a/plugins/cost-insights/src/components/index.ts b/plugins/cost-insights/src/components/index.ts new file mode 100644 index 0000000000..5b918144d9 --- /dev/null +++ b/plugins/cost-insights/src/components/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './BarChart'; +export * from './CostGrowth'; +export * from './LegendItem'; +export * from './Tooltip'; diff --git a/plugins/cost-insights/src/hooks/index.ts b/plugins/cost-insights/src/hooks/index.ts index 7065bcf91b..94c556763c 100644 --- a/plugins/cost-insights/src/hooks/index.ts +++ b/plugins/cost-insights/src/hooks/index.ts @@ -20,5 +20,5 @@ export * from './useFilters'; export * from './useCurrency'; export * from './useGroups'; export * from './useLoading'; -export * from './useQueryParams'; export * from './useScroll'; +export * from './useLastCompleteBillingDate'; diff --git a/plugins/cost-insights/src/hooks/useConfig.tsx b/plugins/cost-insights/src/hooks/useConfig.tsx index aee6567056..f63b9228a9 100644 --- a/plugins/cost-insights/src/hooks/useConfig.tsx +++ b/plugins/cost-insights/src/hooks/useConfig.tsx @@ -15,22 +15,20 @@ */ import React, { - ReactNode, createContext, + PropsWithChildren, useContext, useEffect, useState, } from 'react'; -import { useApi, configApiRef } from '@backstage/core'; +import { configApiRef, useApi } from '@backstage/core'; import { Config as BackstageConfig } from '@backstage/config'; -import { Currency, defaultCurrencies, Product, Icon, Metric } from '../types'; +import { Currency, defaultCurrencies, Icon, Metric, Product } from '../types'; import { getIcon } from '../utils/navigation'; - -export const NULL_METRIC = 'dailyCost'; -export const NULL_METRIC_NAME = 'Daily Cost'; +import { validateMetrics } from '../utils/config'; /* - * Config schema 2020-09-28 + * Config schema 2020-10-15 * * costInsights: * engineerCost: 200000 @@ -44,6 +42,7 @@ export const NULL_METRIC_NAME = 'Daily Cost'; * metrics: * metricA: * name: Metric A + * default: true * metricB: * name: Metric B */ @@ -61,14 +60,14 @@ export const ConfigContext = createContext( ); const defaultState: ConfigContextProps = { - metrics: [{ kind: null, name: NULL_METRIC_NAME }], + metrics: [], products: [], icons: [], engineerCost: 0, currencies: defaultCurrencies, }; -export const ConfigProvider = ({ children }: { children: ReactNode }) => { +export const ConfigProvider = ({ children }: PropsWithChildren<{}>) => { const c: BackstageConfig = useApi(configApiRef); const [config, setConfig] = useState(defaultState); const [loading, setLoading] = useState(true); @@ -87,8 +86,9 @@ export const ConfigProvider = ({ children }: { children: ReactNode }) => { const metrics = c.getOptionalConfig('costInsights.metrics'); if (metrics) { return metrics.keys().map(key => ({ - kind: key === NULL_METRIC ? null : key, + kind: key, name: metrics.getString(`${key}.name`), + default: metrics.getOptionalBoolean(`${key}.default`) ?? false, })); } @@ -115,23 +115,16 @@ export const ConfigProvider = ({ children }: { children: ReactNode }) => { const engineerCost = getEngineerCost(); const icons = getIcons(); - if (metrics.find((m: Metric) => m.kind === null)) { - setConfig(prevState => ({ - ...prevState, - metrics, - products, - engineerCost, - icons, - })); - } else { - setConfig(prevState => ({ - ...prevState, - metrics: [...prevState.metrics, ...metrics], - products, - engineerCost, - icons, - })); - } + validateMetrics(metrics); + + setConfig(prevState => ({ + ...prevState, + metrics, + products, + engineerCost, + icons, + })); + setLoading(false); } @@ -149,12 +142,7 @@ export const ConfigProvider = ({ children }: { children: ReactNode }) => { export function useConfig(): ConfigContextProps { const config = useContext(ConfigContext); - - if (!config) { - assertNever(); - } - - return config; + return config ? config : assertNever(); } function assertNever(): never { diff --git a/plugins/cost-insights/src/hooks/useCurrency.tsx b/plugins/cost-insights/src/hooks/useCurrency.tsx index f5d0df929a..34a4f54d5f 100644 --- a/plugins/cost-insights/src/hooks/useCurrency.tsx +++ b/plugins/cost-insights/src/hooks/useCurrency.tsx @@ -16,9 +16,9 @@ import React, { Dispatch, SetStateAction, - ReactNode, useState, useContext, + PropsWithChildren, } from 'react'; import { Currency, defaultCurrencies, findAlways } from '../types'; @@ -27,15 +27,11 @@ export type CurrencyContextProps = { setCurrency: Dispatch>; }; -export type CurrencyProviderProps = { - children: ReactNode; -}; - export const CurrencyContext = React.createContext< CurrencyContextProps | undefined >(undefined); -export const CurrencyProvider = ({ children }: CurrencyProviderProps) => { +export const CurrencyProvider = ({ children }: PropsWithChildren<{}>) => { const engineers = findAlways(defaultCurrencies, c => c.kind === null); const [currency, setCurrency] = useState(engineers); return ( diff --git a/plugins/cost-insights/src/hooks/useFilters.tsx b/plugins/cost-insights/src/hooks/useFilters.tsx index c2053d6b0f..22ef735186 100644 --- a/plugins/cost-insights/src/hooks/useFilters.tsx +++ b/plugins/cost-insights/src/hooks/useFilters.tsx @@ -16,112 +16,98 @@ import React, { Dispatch, - ReactNode, + PropsWithChildren, SetStateAction, useContext, useEffect, - useRef, useState, } from 'react'; -import { - getDefaultPageFilters, - PageFilters, - ProductFilters, - Duration, - Group, -} from '../types'; +import { Alert } from '@material-ui/lab'; +import { Maybe, PageFilters, ProductFilters } from '../types'; import { useLocation, useNavigate } from 'react-router-dom'; -import { useQueryParams } from './useQueryParams'; -import { stringify } from '../utils/history'; +import { + stringify, + validate, + getInitialPageState, + getInitialProductState, +} from '../utils/history'; import { useGroups } from './useGroups'; import { useConfig } from './useConfig'; -const getInitialPageState = ( - groups: Group[], - queryParams?: Partial, -) => { - // The group is written initially to queryParams as null, since user groups are asynchronously - // loaded. We preserve nulls in queryParams for other parameters where null is meaningful; for - // group, avoid overwriting the default with null after groups are loaded. - const { group, ...otherParams } = queryParams || {}; - return { - ...getDefaultPageFilters(groups), - ...otherParams, - ...(group ? { group: group } : {}), - }; -}; - export type FilterContextProps = { pageFilters: PageFilters; productFilters: ProductFilters; - setPageFilters: Dispatch>; - setProductFilters: Dispatch>; + setPageFilters: Dispatch>>; + setProductFilters: Dispatch>>; }; export type MapFiltersToProps = (props: FilterContextProps) => T; -export type FilterProviderProps = { - children: ReactNode; -}; - export const FilterContext = React.createContext< FilterContextProps | undefined >(undefined); -export const FilterProvider = ({ children }: FilterProviderProps) => { +export const FilterProvider = ({ children }: PropsWithChildren<{}>) => { + const config = useConfig(); const navigate = useNavigate(); const location = useLocation(); - const queryParams = useQueryParams(); - const qsRef = useRef(''); const groups = useGroups(); - const { products } = useConfig(); - - const defaultProductFilters = products.map(product => ({ - productType: product.kind, - duration: Duration.P1M, - })); - - const getInitialProductState = (productFilters?: ProductFilters) => { - if (!productFilters) return defaultProductFilters; - return defaultProductFilters.map(product => { - return ( - productFilters.find( - param => param.productType === product.productType, - ) || product - ); - }); - }; - - const [productFilters, setProductFilters] = useState( - getInitialProductState(queryParams.productFilters), - ); - const [pageFilters, setPageFilters] = useState( - getInitialPageState(groups, queryParams.pageFilters), + const [error, setError] = useState>(null); + const [pageFilters, setPageFilters] = useState>(null); + const [productFilters, setProductFilters] = useState>( + null, ); - // TODO: Figure out why pageFilters doesn't get updated by the above when groups are loaded. useEffect(() => { - setPageFilters(getInitialPageState(groups, queryParams.pageFilters)); + async function setPageFiltersFromLocation() { + try { + // strip extraneous parameters, validate and transform + const queryParams = await validate(location.search); + const defaultMetric = config.metrics.find(m => m.default)?.kind ?? null; + + // Group or project parameters should override defaults + const initialPageState = getInitialPageState(groups, queryParams); + const initialProductState = getInitialProductState(config); + + setProductFilters(initialProductState); + setPageFilters({ ...initialPageState, metric: defaultMetric }); + } catch (e) { + setError(e); + } + } + + setPageFiltersFromLocation(); }, [groups]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { - const queryString = stringify({ ...pageFilters, products: productFilters }); - if (queryString === qsRef.current) return; - qsRef.current = queryString; - // TODO Remove workaround once issue is resolved in react-router - // (https://github.com/ReactTraining/react-router/issues/7496) - // navigate({ ...location, search: queryString }); - navigate({ ...location, search: `?${queryString}` }); - }, [pageFilters, productFilters]); // eslint-disable-line react-hooks/exhaustive-deps + function setLocationFromPageFilters(filters: PageFilters) { + const queryString = stringify({ + group: filters.group, + ...(filters.project ? { project: filters.project } : {}), + }); + // TODO Remove workaround once issue is resolved in react-router + // (https://github.com/ReactTraining/react-router/issues/7496) + // navigate({ ...location, search: queryString }); + navigate({ ...location, search: `?${queryString}` }); + } + + if (pageFilters) { + setLocationFromPageFilters(pageFilters); + } + }, [pageFilters]); // eslint-disable-line react-hooks/exhaustive-deps + + if (error) { + return {error.message}; + } + + // Wait for filters to load + if (!pageFilters || !productFilters) { + return null; + } return ( {children} @@ -130,17 +116,7 @@ export const FilterProvider = ({ children }: FilterProviderProps) => { export function useFilters(mapFiltersToProps: MapFiltersToProps): T { const context = useContext(FilterContext); - - if (!context) { - assertNever(); - } - - return mapFiltersToProps({ - pageFilters: context.pageFilters, - productFilters: context.productFilters, - setPageFilters: context.setPageFilters, - setProductFilters: context.setProductFilters, - }); + return context ? mapFiltersToProps(context) : assertNever(); } function assertNever(): never { diff --git a/plugins/cost-insights/src/hooks/useGroups.tsx b/plugins/cost-insights/src/hooks/useGroups.tsx index 02c32e7920..13cec25017 100644 --- a/plugins/cost-insights/src/hooks/useGroups.tsx +++ b/plugins/cost-insights/src/hooks/useGroups.tsx @@ -14,54 +14,68 @@ * limitations under the License. */ -import React, { ReactNode, useContext, useEffect, useState } from 'react'; +import React, { + PropsWithChildren, + useContext, + useEffect, + useState, +} from 'react'; +import { Alert } from '@material-ui/lab'; import { useApi, identityApiRef } from '@backstage/core'; import { costInsightsApiRef } from '../api'; import { MapLoadingToProps, useLoading } from './useLoading'; -import { DefaultLoadingAction, Group } from '../types'; +import { DefaultLoadingAction, Group, Maybe } from '../types'; type GroupsProviderLoadingProps = { dispatchLoadingGroups: (isLoading: boolean) => void; }; -export const mapLoadingToProps: MapLoadingToProps = ({ +const mapLoadingToProps: MapLoadingToProps = ({ dispatch, }) => ({ dispatchLoadingGroups: (isLoading: boolean) => dispatch({ [DefaultLoadingAction.UserGroups]: isLoading }), }); -type GroupsContextProps = { +export type GroupsContextProps = { groups: Group[]; }; -export type GroupsProviderProps = { - children: ReactNode; -}; +export const GroupsContext = React.createContext< + GroupsContextProps | undefined +>(undefined); -export const GroupsContext = React.createContext({ - groups: [], -}); - -export const GroupsProvider = ({ children }: GroupsProviderProps) => { +export const GroupsProvider = ({ children }: PropsWithChildren<{}>) => { const userId = useApi(identityApiRef).getUserId(); const client = useApi(costInsightsApiRef); + const [error, setError] = useState>(null); const { dispatchLoadingGroups } = useLoading(mapLoadingToProps); - const [groups, setGroups] = useState([]); + const [groups, setGroups] = useState>(null); useEffect(() => { dispatchLoadingGroups(true); async function getUserGroups() { - const g = await client.getUserGroups(userId); - setGroups(g); - dispatchLoadingGroups(false); + try { + const g = await client.getUserGroups(userId); + setGroups(g); + } catch (e) { + setError(e); + } finally { + dispatchLoadingGroups(false); + } } getUserGroups(); }, [userId, client]); // eslint-disable-line react-hooks/exhaustive-deps + if (error) { + return {error.message}; + } + + if (!groups) return null; + return ( {children} @@ -70,13 +84,8 @@ export const GroupsProvider = ({ children }: GroupsProviderProps) => { }; export function useGroups(): Group[] { - const { groups } = useContext(GroupsContext); - - if (!groups) { - assertNever(); - } - - return groups; + const context = useContext(GroupsContext); + return context ? context.groups : assertNever(); } function assertNever(): never { diff --git a/plugins/cost-insights/src/hooks/useLastCompleteBillingDate.tsx b/plugins/cost-insights/src/hooks/useLastCompleteBillingDate.tsx new file mode 100644 index 0000000000..33d037267d --- /dev/null +++ b/plugins/cost-insights/src/hooks/useLastCompleteBillingDate.tsx @@ -0,0 +1,111 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { + PropsWithChildren, + useContext, + useEffect, + useState, +} from 'react'; +import * as yup from 'yup'; +import { Alert } from '@material-ui/lab'; +import { useApi } from '@backstage/core'; +import { costInsightsApiRef } from '../api'; +import { MapLoadingToProps, useLoading } from './useLoading'; +import { DefaultLoadingAction, Maybe } from '../types'; + +type BillingDateProviderLoadingProps = { + dispatchLoadingBillingDate: (isLoading: boolean) => void; +}; + +const mapLoadingToProps: MapLoadingToProps = ({ + dispatch, +}) => ({ + dispatchLoadingBillingDate: (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.LastCompleteBillingDate]: isLoading }), +}); + +export type BillingDateContextProps = { + lastCompleteBillingDate: string; // YYYY-MM-DD +}; + +export const BillingDateContext = React.createContext< + BillingDateContextProps | undefined +>(undefined); + +export const dateRegex: RegExp = /^\d{4}-\d{2}-\d{2}$/; +const dateFormatSchema = yup.string().matches(dateRegex, { + message: + 'Unsupported billing date format: ${value}. Date should be in YYYY-MM-DD format.', + excludeEmptyString: true, +}); + +export const BillingDateProvider = ({ children }: PropsWithChildren<{}>) => { + const client = useApi(costInsightsApiRef); + const [error, setError] = useState>(null); + const { dispatchLoadingBillingDate } = useLoading(mapLoadingToProps); + + const [lastCompleteBillingDate, setLastCompeteBillingDate] = useState< + Maybe + >(null); + + useEffect(() => { + dispatchLoadingBillingDate(true); + + async function getLastCompleteBillingDate() { + try { + const d = await client.getLastCompleteBillingDate(); + const validDate = await dateFormatSchema.validate(d); + if (validDate) setLastCompeteBillingDate(validDate); + } catch (e) { + setError(e); + } finally { + dispatchLoadingBillingDate(false); + } + } + + getLastCompleteBillingDate(); + }, [client]); // eslint-disable-line react-hooks/exhaustive-deps + + if (error) { + return {error.message}; + } + + if (!lastCompleteBillingDate) return null; + + return ( + + {children} + + ); +}; + +export function useLastCompleteBillingDate(): string { + const context = useContext(BillingDateContext); + return context ? context.lastCompleteBillingDate : assertNever(); +} + +function assertNever(): never { + throw Error( + 'Cannot use useLastCompleteBillingDate outside of BillingDateProvider', + ); +} diff --git a/plugins/cost-insights/src/hooks/useLoading.tsx b/plugins/cost-insights/src/hooks/useLoading.tsx index bc0df4bbc7..31402ba0d1 100644 --- a/plugins/cost-insights/src/hooks/useLoading.tsx +++ b/plugins/cost-insights/src/hooks/useLoading.tsx @@ -15,10 +15,10 @@ */ import React, { - Dispatch, - ReactNode, - SetStateAction, createContext, + Dispatch, + PropsWithChildren, + SetStateAction, useContext, useEffect, useMemo, @@ -27,10 +27,10 @@ import React, { } from 'react'; import { Backdrop, CircularProgress } from '@material-ui/core'; import { - Loading, - getDefaultState, DefaultLoadingAction, + getDefaultState, getLoadingActions, + Loading, } from '../types'; import { useBackdropStyles as useStyles } from '../utils/styles'; import { useConfig } from './useConfig'; @@ -41,10 +41,6 @@ export type LoadingContextProps = { actions: Array; }; -export type LoadingProviderProps = { - children: ReactNode; -}; - export type MapLoadingToProps = (props: LoadingContextProps) => T; export const LoadingContext = createContext( @@ -58,7 +54,7 @@ function reducer(prevState: Loading, action: Partial): Loading { } as Record; } -export const LoadingProvider = ({ children }: LoadingProviderProps) => { +export const LoadingProvider = ({ children }: PropsWithChildren<{}>) => { const classes = useStyles(); const { products } = useConfig(); const actions = useMemo(() => getLoadingActions(products.map(p => p.kind)), [ diff --git a/plugins/cost-insights/src/hooks/useQueryParams.tsx b/plugins/cost-insights/src/hooks/useQueryParams.tsx deleted file mode 100644 index 1e6ce8f0fd..0000000000 --- a/plugins/cost-insights/src/hooks/useQueryParams.tsx +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { useLocation } from 'react-router-dom'; -import { Location } from 'history'; -import { PageFilters, ProductFilters } from '../types'; -import { parse } from '../utils/history'; - -export type FilterParams = { - pageFilters?: Partial; - productFilters?: ProductFilters; -}; - -export function useQueryParams(): FilterParams { - const location: Location = useLocation(); - const { products: productFilters, ...pageFilters } = parse(location.search); - - return { - productFilters: productFilters, - pageFilters: pageFilters, - }; -} diff --git a/plugins/cost-insights/src/hooks/useScroll.tsx b/plugins/cost-insights/src/hooks/useScroll.tsx index 480495a257..0a1abbdad3 100644 --- a/plugins/cost-insights/src/hooks/useScroll.tsx +++ b/plugins/cost-insights/src/hooks/useScroll.tsx @@ -15,12 +15,12 @@ */ import React, { Dispatch, - ReactNode, SetStateAction, useState, useContext, useEffect, useRef, + PropsWithChildren, } from 'react'; import { CSSProperties } from '@material-ui/styles'; import { Maybe } from '../types'; @@ -32,10 +32,6 @@ export type ScrollContextProps = { setScrollTo: Dispatch>; }; -export type ScrollProviderProps = { - children: ReactNode; -}; - export type ScrollUtils = { ScrollAnchor: (props: Omit) => JSX.Element; scrollIntoView: () => void; @@ -96,7 +92,7 @@ export const ScrollAnchor = ({ return
; }; -export const ScrollProvider = ({ children }: ScrollProviderProps) => { +export const ScrollProvider = ({ children }: PropsWithChildren<{}>) => { const [scrollTo, setScrollTo] = useState(null); return ( diff --git a/plugins/cost-insights/src/index.ts b/plugins/cost-insights/src/index.ts index cf7aa3ea8c..71cc66dba6 100644 --- a/plugins/cost-insights/src/index.ts +++ b/plugins/cost-insights/src/index.ts @@ -16,4 +16,7 @@ export { plugin } from './plugin'; export * from './api'; +export * from './components'; +export { useCurrency } from './hooks'; export * from './types'; +export * from './utils/tests'; diff --git a/plugins/cost-insights/src/plugin.ts b/plugins/cost-insights/src/plugin.ts index d8d54ae71b..58465f6711 100644 --- a/plugins/cost-insights/src/plugin.ts +++ b/plugins/cost-insights/src/plugin.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import { createPlugin, createRouteRef } from '@backstage/core'; -import CostInsightsPage from './components/CostInsightsPage'; -import ProjectGrowthInstructionsPage from './components/ProjectGrowthInstructionsPage'; -import LabelDataflowInstructionsPage from './components/LabelDataflowInstructionsPage'; +import { createPlugin, createRouteRef, PluginConfig } from '@backstage/core'; +import { CostInsightsPage } from './components/CostInsightsPage'; +import { ProjectGrowthInstructionsPage } from './components/ProjectGrowthInstructionsPage'; +import { LabelDataflowInstructionsPage } from './components/LabelDataflowInstructionsPage'; export const rootRouteRef = createRouteRef({ path: '/cost-insights', @@ -34,7 +34,7 @@ export const unlabeledDataflowAlertRef = createRouteRef({ title: 'Labeling Dataflow Jobs', }); -export const plugin = createPlugin({ +export const pluginConfig: PluginConfig = { id: 'cost-insights', register({ router, featureFlags }) { router.addRoute(rootRouteRef, CostInsightsPage); @@ -42,4 +42,6 @@ export const plugin = createPlugin({ router.addRoute(unlabeledDataflowAlertRef, LabelDataflowInstructionsPage); featureFlags.register('cost-insights-currencies'); }, -}); +}; + +export const plugin = createPlugin(pluginConfig); diff --git a/plugins/cost-insights/src/setupTests.ts b/plugins/cost-insights/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/cost-insights/src/setupTests.ts +++ b/plugins/cost-insights/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/cost-insights/src/types/Alert.ts b/plugins/cost-insights/src/types/Alert.ts deleted file mode 100644 index 8d560096e3..0000000000 --- a/plugins/cost-insights/src/types/Alert.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { ChangeStatistic } from './ChangeStatistic'; -import { Maybe } from './Maybe'; - -export type Alert = ProjectGrowthAlert | UnlabeledDataflowAlert; - -export interface AlertProps { - alert: Alert; -} - -export enum AlertType { - ProjectGrowth = 'projectGrowth', - UnlabeledDataflow = 'unlabeledDataflow', -} - -export interface AlertCost { - id: string; - aggregation: [number, number]; -} - -export interface ResourceData { - previous: number; - current: number; - name: Maybe; -} - -export interface BarChartData { - previousFill: string; - currentFill: string; - previousName: string; - currentName: string; -} - -export enum DataKey { - Previous = 'previous', - Current = 'current', - Name = 'name', -} - -export interface ProjectGrowthAlert { - id: AlertType.ProjectGrowth; - project: string; - periodStart: string; - periodEnd: string; - aggregation: [number, number]; - change: ChangeStatistic; - products: Array; -} - -export interface UnlabeledDataflowAlert { - id: AlertType.UnlabeledDataflow; - periodStart: string; - periodEnd: string; - projects: Array; - unlabeledCost: number; - labeledCost: number; -} - -export interface UnlabeledDataflowAlertProject { - id: string; - unlabeledCost: number; - labeledCost: number; -} diff --git a/plugins/cost-insights/src/types/Alert.tsx b/plugins/cost-insights/src/types/Alert.tsx new file mode 100644 index 0000000000..4ed55a844c --- /dev/null +++ b/plugins/cost-insights/src/types/Alert.tsx @@ -0,0 +1,123 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { ChangeStatistic } from './ChangeStatistic'; +import { Maybe } from './Maybe'; +import { UnlabeledDataflowAlertCard } from '../components/UnlabeledDataflowAlertCard'; +import { ProjectGrowthAlertCard } from '../components/ProjectGrowthAlertCard'; + +/** + * Generic alert type with required fields for display. The `element` field will be rendered in + * the Cost Insights "Action Items" section. This should use data fetched in the CostInsightsApi + * implementation to render an InfoCard or other visualization. + */ +export type Alert = { + title: string; + subtitle: string; + url: string; + buttonText?: string; // Default: View Instructions + element: JSX.Element; +}; + +export interface AlertCost { + id: string; + aggregation: [number, number]; +} + +export interface ResourceData { + previous: number; + current: number; + name: Maybe; +} + +export interface BarChartData { + previousFill: string; + currentFill: string; + previousName: string; + currentName: string; +} + +export enum DataKey { + Previous = 'previous', + Current = 'current', + Name = 'name', +} + +/** + * The alerts below are examples of Alert implementation; the CostInsightsApi permits returning + * any implementation of the Alert type, so adopters can create their own. The CostInsightsApi + * fetches alert data from the backend, then creates Alert classes with the data. + */ +export interface ProjectGrowthData { + project: string; + periodStart: string; + periodEnd: string; + aggregation: [number, number]; + change: ChangeStatistic; + products: Array; +} + +export class ProjectGrowthAlert implements Alert { + data: ProjectGrowthData; + + constructor(data: ProjectGrowthData) { + this.data = data; + } + + get title() { + return `Investigate cost growth in project ${this.data.project}`; + } + + subtitle = + 'Cost growth outpacing business growth is unsustainable long-term.'; + url = '/cost-insights/investigating-growth'; + + get element() { + return ; + } +} + +export interface UnlabeledDataflowData { + periodStart: string; + periodEnd: string; + projects: Array; + unlabeledCost: number; + labeledCost: number; +} + +export class UnlabeledDataflowAlert implements Alert { + data: UnlabeledDataflowData; + + constructor(data: UnlabeledDataflowData) { + this.data = data; + } + + title = 'Add labels to workflows'; + subtitle = + 'Labels show in billing data, enabling cost insights for each workflow.'; + url = '/cost-insights/labeling-jobs'; + + get element() { + return ; + } +} + +export interface UnlabeledDataflowAlertProject { + id: string; + unlabeledCost: number; + labeledCost: number; +} diff --git a/plugins/cost-insights/src/types/ChangeStatistic.ts b/plugins/cost-insights/src/types/ChangeStatistic.ts index 538692bb1d..cdd2e02da6 100644 --- a/plugins/cost-insights/src/types/ChangeStatistic.ts +++ b/plugins/cost-insights/src/types/ChangeStatistic.ts @@ -14,6 +14,10 @@ * limitations under the License. */ +import { Cost } from './Cost'; +import { MetricData } from './MetricData'; +import { aggregationSort } from '../utils/sort'; + export interface ChangeStatistic { // The ratio of change from one duration to another, expressed as: (newSum - oldSum) / oldSum ratio: number; @@ -46,3 +50,16 @@ export function growthOf(amount: number, ratio: number) { return Growth.Negligible; } + +// Used by for displaying engineer totals +export function getComparedChange( + dailyCost: Cost, + metricData: MetricData, +): ChangeStatistic { + const ratio = dailyCost.change.ratio - metricData.change.ratio; + const amount = dailyCost.aggregation.slice().sort(aggregationSort)[0].amount; + return { + ratio: ratio, + amount: amount * ratio, + }; +} diff --git a/plugins/cost-insights/src/types/ChartData.tsx b/plugins/cost-insights/src/types/ChartData.tsx new file mode 100644 index 0000000000..d99e9d9bc3 --- /dev/null +++ b/plugins/cost-insights/src/types/ChartData.tsx @@ -0,0 +1,22 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type ChartData = { + date: number; + trend: number; + dailyCost: number; + [key: string]: number; +}; diff --git a/plugins/cost-insights/src/types/Duration.test.ts b/plugins/cost-insights/src/types/Duration.test.ts index 5b9f7b4a9b..4ab84de974 100644 --- a/plugins/cost-insights/src/types/Duration.test.ts +++ b/plugins/cost-insights/src/types/Duration.test.ts @@ -16,7 +16,7 @@ import { Duration, inclusiveEndDateOf, inclusiveStartDateOf } from './Duration'; -Date.now = jest.fn(() => new Date(Date.parse('2020-06-05')).valueOf()); +const lastCompleteBillingDate = '2020-06-05'; describe.each` duration | startDate | endDate @@ -26,7 +26,9 @@ describe.each` ${Duration.P3M} | ${'2019-10-01'} | ${'2020-03-31'} `('Calculates interval dates correctly', ({ duration, startDate, endDate }) => { it(`Calculates dates correctly for ${duration}`, () => { - expect(inclusiveStartDateOf(duration)).toBe(startDate); - expect(inclusiveEndDateOf(duration)).toBe(endDate); + expect(inclusiveStartDateOf(duration, lastCompleteBillingDate)).toBe( + startDate, + ); + expect(inclusiveEndDateOf(duration, lastCompleteBillingDate)).toBe(endDate); }); }); diff --git a/plugins/cost-insights/src/types/Duration.ts b/plugins/cost-insights/src/types/Duration.ts index 6e6c5b1100..72501d46d5 100644 --- a/plugins/cost-insights/src/types/Duration.ts +++ b/plugins/cost-insights/src/types/Duration.ts @@ -32,23 +32,31 @@ export enum Duration { export const DEFAULT_DATE_FORMAT = 'YYYY-MM-DD'; -// Derive the start date of a given period, assuming two repeating intervals -export function inclusiveStartDateOf(duration: Duration): string { +/** + * Derive the start date of a given period, assuming two repeating intervals. + * + * @param duration see comment on Duration enum + * @param endDate from CostInsightsApi.getLastCompleteBillingDate + */ +export function inclusiveStartDateOf( + duration: Duration, + endDate: string, +): string { switch (duration) { case Duration.P30D: case Duration.P90D: - return moment() + return moment(endDate) .utc() .subtract(moment.duration(duration).add(moment.duration(duration))) .format(DEFAULT_DATE_FORMAT); case Duration.P1M: - return moment() + return moment(endDate) .utc() .startOf('month') .subtract(moment.duration(duration).add(moment.duration(duration))) .format(DEFAULT_DATE_FORMAT); case Duration.P3M: - return moment() + return moment(endDate) .utc() .startOf('quarter') .subtract(moment.duration(duration).add(moment.duration(duration))) @@ -58,28 +66,37 @@ export function inclusiveStartDateOf(duration: Duration): string { } } -export function exclusiveEndDateOf(duration: Duration): string { +export function exclusiveEndDateOf( + duration: Duration, + endDate: string, +): string { switch (duration) { case Duration.P30D: case Duration.P90D: - return moment().utc().add(1, 'day').format(DEFAULT_DATE_FORMAT); + return moment(endDate).utc().add(1, 'day').format(DEFAULT_DATE_FORMAT); case Duration.P1M: - return moment().utc().startOf('month').format(DEFAULT_DATE_FORMAT); + return moment(endDate).utc().startOf('month').format(DEFAULT_DATE_FORMAT); case Duration.P3M: - return moment().utc().startOf('quarter').format(DEFAULT_DATE_FORMAT); + return moment(endDate) + .utc() + .startOf('quarter') + .format(DEFAULT_DATE_FORMAT); default: return assertNever(duration); } } -export function inclusiveEndDateOf(duration: Duration): string { - return moment(exclusiveEndDateOf(duration)) +export function inclusiveEndDateOf( + duration: Duration, + endDate: string, +): string { + return moment(exclusiveEndDateOf(duration, endDate)) .utc() .subtract(1, 'day') .format(DEFAULT_DATE_FORMAT); } // https://en.wikipedia.org/wiki/ISO_8601#Repeating_intervals -export function intervalsOf(duration: Duration) { - return `R2/${duration}/${exclusiveEndDateOf(duration)}`; +export function intervalsOf(duration: Duration, endDate: string) { + return `R2/${duration}/${exclusiveEndDateOf(duration, endDate)}`; } diff --git a/plugins/cost-insights/src/types/Filters.ts b/plugins/cost-insights/src/types/Filters.ts index def1d74d1a..b1fbbb2848 100644 --- a/plugins/cost-insights/src/types/Filters.ts +++ b/plugins/cost-insights/src/types/Filters.ts @@ -22,13 +22,11 @@ export interface PageFilters { group: Maybe; project: Maybe; duration: Duration; - metric: Maybe; + metric: string | null; } export type ProductFilters = Array; -export type QueryParams = PageFilters & { products: ProductFilters }; - export interface ProductPeriod { duration: Duration; productType: string; diff --git a/plugins/cost-insights/src/types/Loading.ts b/plugins/cost-insights/src/types/Loading.ts index f5da1d2b07..8bc0c4eaef 100644 --- a/plugins/cost-insights/src/types/Loading.ts +++ b/plugins/cost-insights/src/types/Loading.ts @@ -18,6 +18,7 @@ export type Loading = Record; export enum DefaultLoadingAction { UserGroups = 'user-groups', + LastCompleteBillingDate = 'billing-date', CostInsightsInitial = 'cost-insights-initial', CostInsightsPage = 'cost-insights-page', } diff --git a/plugins/cost-insights/src/types/Metric.ts b/plugins/cost-insights/src/types/Metric.ts index 5a440a8d1f..b0a0c9cc76 100644 --- a/plugins/cost-insights/src/types/Metric.ts +++ b/plugins/cost-insights/src/types/Metric.ts @@ -14,9 +14,8 @@ * limitations under the License. */ -import { Maybe } from './Maybe'; - export type Metric = { - kind: Maybe; + kind: string; name: string; + default: boolean; }; diff --git a/plugins/cost-insights/src/types/MetricData.ts b/plugins/cost-insights/src/types/MetricData.ts new file mode 100644 index 0000000000..bd3bdde735 --- /dev/null +++ b/plugins/cost-insights/src/types/MetricData.ts @@ -0,0 +1,25 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { DateAggregation } from './DateAggregation'; +import { ChangeStatistic } from './ChangeStatistic'; + +export interface MetricData { + id: string; + format: 'number' | 'currency'; + aggregation: DateAggregation[]; + change: ChangeStatistic; +} diff --git a/plugins/cost-insights/src/types/index.ts b/plugins/cost-insights/src/types/index.ts index c3d9a87886..398110ec80 100644 --- a/plugins/cost-insights/src/types/index.ts +++ b/plugins/cost-insights/src/types/index.ts @@ -16,6 +16,7 @@ export * from './Alert'; export * from './ChangeStatistic'; +export * from './ChartData'; export * from './Cost'; export * from './DateAggregation'; export * from './Duration'; @@ -26,6 +27,7 @@ export * from './Filters'; export * from './Group'; export * from './Loading'; export * from './Maybe'; +export * from './MetricData'; export * from './Metric'; export * from './Product'; export * from './Project'; diff --git a/plugins/cost-insights/src/utils/alerts.tsx b/plugins/cost-insights/src/utils/alerts.tsx deleted file mode 100644 index 07602be191..0000000000 --- a/plugins/cost-insights/src/utils/alerts.tsx +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import React from 'react'; -import { Alert, AlertType, assertNever } from '../types'; -import ProjectGrowthAlertCard from '../components/ProjectGrowthAlertCard'; -import UnlabeledDataflowAlertCard from '../components/UnlabeledDataflowAlertCard'; - -export function getAlertText(alert: Alert) { - switch (alert.id) { - case AlertType.ProjectGrowth: - return { - title: `Investigate cost growth in project ${alert.project}`, - subtitle: - 'Cost growth outpacing business growth is unsustainable long-term.', - } as AlertText; - case AlertType.UnlabeledDataflow: - return { - title: 'Add labels to workflows', - subtitle: - 'Labels show in billing data, enabling cost insights for each workflow.', - }; - default: - return assertNever(alert); - } -} - -export function getAlertUrl(alert: Alert) { - switch (alert.id) { - case AlertType.ProjectGrowth: - return '/cost-insights/investigating-growth' as AlertUrl; - case AlertType.UnlabeledDataflow: - return '/cost-insights/labeling-jobs' as AlertUrl; - default: - return assertNever(alert); - } -} - -export function getAlertButtonText(alert: Alert) { - switch (alert.id) { - case AlertType.ProjectGrowth: - case AlertType.UnlabeledDataflow: - return 'View Instructions' as AlertButtonText; - default: - return assertNever(alert); - } -} - -export function getAlertNavigation(alert: Alert, number: number) { - return `${alert.id}-${number}`; -} - -export function renderAlert(alert: Alert) { - switch (alert.id) { - case AlertType.ProjectGrowth: - return ; - case AlertType.UnlabeledDataflow: - return ; - default: - return assertNever(alert); - } -} - -export type AlertUrl = string; -export type AlertButtonText = string; - -export interface AlertText { - title: string; - subtitle: string; -} diff --git a/plugins/cost-insights/src/utils/charts.ts b/plugins/cost-insights/src/utils/charts.ts new file mode 100644 index 0000000000..60a8e85816 --- /dev/null +++ b/plugins/cost-insights/src/utils/charts.ts @@ -0,0 +1,39 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { DateAggregation, Trendline, ChartData } from '../types'; + +export function trendFrom(trendline: Trendline, date: number): number { + return trendline.slope * (date / 1000) + trendline.intercept; +} + +export function groupByDate( + acc: Record, + entry: DateAggregation, +): Record { + return { ...acc, [entry.date]: entry.amount }; +} + +export function toMaxCost(acc: ChartData, entry: ChartData): ChartData { + return acc.dailyCost > entry.dailyCost ? acc : entry; +} + +export function toDataMax(metric: string, data: ChartData[]): number { + return ( + (data.reduce(toMaxCost).dailyCost / Math.abs(data[0].trend)) * + data[0][metric] + ); +} diff --git a/plugins/cost-insights/src/utils/config.ts b/plugins/cost-insights/src/utils/config.ts new file mode 100644 index 0000000000..4af7140d9c --- /dev/null +++ b/plugins/cost-insights/src/utils/config.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Metric } from '../types'; + +export function validateMetrics(metrics: Metric[]) { + const defaults = metrics.filter(metric => metric.default); + if (defaults.length > 1) { + throw new Error( + `Only one default metric can be set at a time. Found ${defaults.length}`, + ); + } +} diff --git a/plugins/cost-insights/src/utils/formatters.test.ts b/plugins/cost-insights/src/utils/formatters.test.ts index a76e838b53..69e9086be1 100644 --- a/plugins/cost-insights/src/utils/formatters.test.ts +++ b/plugins/cost-insights/src/utils/formatters.test.ts @@ -14,7 +14,12 @@ * limitations under the License. */ -import { lengthyCurrencyFormatter, quarterOf } from './formatters'; +import { + formatPeriod, + lengthyCurrencyFormatter, + quarterOf, +} from './formatters'; +import { Duration } from '../types'; Date.now = jest.fn(() => new Date(Date.parse('2019-12-07')).valueOf()); @@ -48,3 +53,19 @@ describe('date formatters', () => { ]); }); }); + +describe.each` + duration | date | isEndDate | output + ${Duration.P1M} | ${'2020-10-11'} | ${true} | ${'September 2020'} + ${Duration.P1M} | ${'2020-10-11'} | ${false} | ${'August 2020'} + ${Duration.P3M} | ${'2020-10-11'} | ${true} | ${'Q3 2020'} + ${Duration.P3M} | ${'2020-10-11'} | ${false} | ${'Q2 2020'} + ${Duration.P30D} | ${'2020-10-11'} | ${true} | ${'Last 30 Days'} + ${Duration.P30D} | ${'2020-10-11'} | ${false} | ${'First 30 Days'} + ${Duration.P90D} | ${'2020-10-11'} | ${true} | ${'Last 90 Days'} + ${Duration.P90D} | ${'2020-10-11'} | ${false} | ${'First 90 Days'} +`('formatPeriod', ({ duration, date, isEndDate, output }) => { + it(`Correctly formats ${duration} with date ${date}`, async () => { + expect(formatPeriod(duration, date, isEndDate)).toBe(output); + }); +}); diff --git a/plugins/cost-insights/src/utils/formatters.ts b/plugins/cost-insights/src/utils/formatters.ts index f3790f315e..44c7517351 100644 --- a/plugins/cost-insights/src/utils/formatters.ts +++ b/plugins/cost-insights/src/utils/formatters.ts @@ -87,26 +87,33 @@ export function formatPercent(n: number): string { return `${(n * 100).toFixed(0)}%`; } -export const formatLastTwoLookaheadQuarters = () => { - const start = moment(inclusiveStartDateOf(Duration.P3M)).format('[Q]Q YYYY'); - const end = moment(inclusiveEndDateOf(Duration.P3M)).format('[Q]Q YYYY'); +export function formatLastTwoLookaheadQuarters(endDate: string) { + const start = moment(inclusiveStartDateOf(Duration.P3M, endDate)).format( + '[Q]Q YYYY', + ); + const end = moment(inclusiveEndDateOf(Duration.P3M, endDate)).format( + '[Q]Q YYYY', + ); return `${start} vs ${end}`; -}; +} -export const formatLastTwoMonths = () => { - const start = moment(inclusiveStartDateOf(Duration.P1M)).utc().format('MMMM'); - const end = moment(inclusiveEndDateOf(Duration.P1M)).utc().format('MMMM'); +export function formatLastTwoMonths(endDate: string) { + const start = moment(inclusiveStartDateOf(Duration.P1M, endDate)) + .utc() + .format('MMMM'); + const end = moment(inclusiveEndDateOf(Duration.P1M, endDate)) + .utc() + .format('MMMM'); return `${start} vs ${end}`; -}; +} -export const dateRegex: RegExp = /^\d{4}-\d{2}-\d{2}$/; - -export const formatRelativeDuration = ( - date: string, +const formatRelativePeriod = ( duration: Duration, + date: string, + isEndDate: boolean, ): string => { - const periodStart = inclusiveStartDateOf(duration); - const periodEnd = inclusiveEndDateOf(duration); + const periodStart = isEndDate ? inclusiveStartDateOf(duration, date) : date; + const periodEnd = isEndDate ? date : inclusiveEndDateOf(duration, date); const days = moment.duration(duration).asDays(); if (![periodStart, periodEnd].includes(date)) { throw new Error(`Invalid relative date ${date} for duration ${duration}`); @@ -114,13 +121,25 @@ export const formatRelativeDuration = ( return date === periodStart ? `First ${days} Days` : `Last ${days} Days`; }; -export function formatDuration(date: string, duration: Duration) { +export function formatPeriod( + duration: Duration, + date: string, + isEndDate: boolean, +) { switch (duration) { case Duration.P1M: - return monthOf(date); + return monthOf( + isEndDate + ? inclusiveEndDateOf(duration, date) + : inclusiveStartDateOf(duration, date), + ); case Duration.P3M: - return quarterOf(date); + return quarterOf( + isEndDate + ? inclusiveEndDateOf(duration, date) + : inclusiveStartDateOf(duration, date), + ); default: - return formatRelativeDuration(date, duration); + return formatRelativePeriod(duration, date, isEndDate); } } diff --git a/plugins/cost-insights/src/utils/graphs.tsx b/plugins/cost-insights/src/utils/graphs.tsx index 5200b14b1f..167132cb36 100644 --- a/plugins/cost-insights/src/utils/graphs.tsx +++ b/plugins/cost-insights/src/utils/graphs.tsx @@ -20,10 +20,15 @@ import { lengthyCurrencyFormatter, } from './formatters'; -export function formatGraphValue(value: number) { +export function formatGraphValue(value: number, format?: string) { + if (format === 'number') { + return value.toLocaleString(); + } + if (value < 1) { return lengthyCurrencyFormatter.format(value); } + return currencyFormatter.format(value); } diff --git a/plugins/cost-insights/src/utils/history.test.ts b/plugins/cost-insights/src/utils/history.test.ts new file mode 100644 index 0000000000..e4310e13c6 --- /dev/null +++ b/plugins/cost-insights/src/utils/history.test.ts @@ -0,0 +1,80 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { validate, getInitialPageState } from './history'; + +describe('getInitialPageState', () => { + describe('groups', () => { + it('should set defaults if params or group is not provided', () => { + const initialState = getInitialPageState([]); + expect(initialState.group).toBe(null); + }); + + it('should set defaults if a group is fetched but no group is present on query params', () => { + const initialState = getInitialPageState([{ id: 'group' }]); + expect(initialState.group).toMatch(/group/); + }); + + it('group param should always override fetched group', () => { + const initialState = getInitialPageState( + [{ id: 'group' }, { id: 'second-group' }], + { group: 'other-group' }, + ); + expect(initialState.group).toMatch(/other-group/); + }); + + it('first group should be set as default group if user belongs to multiple groups', () => { + const initialState = getInitialPageState([ + { id: 'group' }, + { id: 'other-group' }, + ]); + expect(initialState.group).toMatch(/group/); + }); + }); + + describe('projects', () => { + it("should set defaults if project param doesn't exist", () => { + const initialState = getInitialPageState([], {}); + expect(initialState.project).toBeNull(); + }); + + it('should override defaults if project param exists', () => { + const initialState = getInitialPageState([], { project: 'some-project' }); + expect(initialState.project).toMatch(/some-project/); + }); + }); +}); + +describe.each` + params | expected + ${''} | ${{}} + ${'?foo=bar'} | ${{}} + ${'?project'} | ${{ project: null }} + ${'?group=some-group'} | ${{ group: 'some-group' }} + ${'?group=some-group&project'} | ${{ group: 'some-group', project: null }} + ${'?group=some-group&project=some-project'} | ${{ group: 'some-group', project: 'some-project' }} + ${'?group=some-group&project=some-project&foo=bar'} | ${{ group: 'some-group', project: 'some-project' }} +`('validate', ({ params, expected }) => { + it(`should validate ${params}`, async () => { + const pageFilters = await validate(params); + expect(pageFilters).toMatchObject(expected); + }); +}); + +describe('invalidate', () => { + it("should throw an error if param values don't match schema", async () => { + await expect(validate('?group')).rejects.toThrowError(); + }); +}); diff --git a/plugins/cost-insights/src/utils/history.ts b/plugins/cost-insights/src/utils/history.ts index 71e8e2c219..90df574acf 100644 --- a/plugins/cost-insights/src/utils/history.ts +++ b/plugins/cost-insights/src/utils/history.ts @@ -15,9 +15,44 @@ */ import qs from 'qs'; -import { QueryParams } from '../types'; +import * as yup from 'yup'; +import { Group, PageFilters, getDefaultPageFilters, Duration } from '../types'; +import { ConfigContextProps } from '../hooks/useConfig'; -export const stringify = (queryParams: Partial) => +const schema = yup + .object() + .shape({ + group: yup.string(), + project: yup.string().nullable(), + }) + .required(); + +export const stringify = (queryParams: Partial) => qs.stringify(queryParams, { strictNullHandling: true }); -export const parse = (queryString: string): Partial => + +export const parse = (queryString: string): Partial => qs.parse(queryString, { ignoreQueryPrefix: true, strictNullHandling: true }); + +export const validate = (queryString: string): Promise => { + return schema.validate(parse(queryString), { + stripUnknown: true, + strict: true, + }) as Promise; +}; + +export const getInitialPageState = ( + groups: Group[], + queryParams: Partial = {}, +) => { + return { + ...getDefaultPageFilters(groups), + ...(queryParams.project ? { project: queryParams.project } : {}), + ...(queryParams.group ? { group: queryParams.group } : {}), + }; +}; + +export const getInitialProductState = (config: ConfigContextProps) => + config.products.map(product => ({ + productType: product.kind, + duration: Duration.P30D, + })); diff --git a/plugins/cost-insights/src/utils/mockData.ts b/plugins/cost-insights/src/utils/mockData.ts index 87dbcf8158..11c70eee25 100644 --- a/plugins/cost-insights/src/utils/mockData.ts +++ b/plugins/cost-insights/src/utils/mockData.ts @@ -15,17 +15,17 @@ */ import { - AlertType, - Entity, - ProjectGrowthAlert, - Product, - UnlabeledDataflowAlert, - UnlabeledDataflowAlertProject, - getDefaultState, DefaultLoadingAction, Duration, - ProductCost, + Entity, findAlways, + getDefaultState as getDefaultLoadingState, + Product, + ProductCost, + ProductFilters, + ProjectGrowthData, + UnlabeledDataflowAlertProject, + UnlabeledDataflowData, } from '../types'; import { Config } from '@backstage/config'; import { ConfigApi } from '@backstage/core'; @@ -73,14 +73,13 @@ export const createMockProductCost = ( return { ...defaultProduct }; }; -export const createMockProjectGrowthAlert = ( - callback?: mockAlertRenderer, -): ProjectGrowthAlert => { - const defaultAlert: ProjectGrowthAlert = { - id: AlertType.ProjectGrowth, +export const createMockProjectGrowthData = ( + callback?: mockAlertRenderer, +): ProjectGrowthData => { + const data: ProjectGrowthData = { project: 'test-project-growth-alert', - periodStart: '2019-10-01', - periodEnd: '2020-03-31', + periodStart: '2019-Q4', + periodEnd: '2020-Q1', aggregation: [670532.1, 970502.8], change: { ratio: 0.5, @@ -90,17 +89,16 @@ export const createMockProjectGrowthAlert = ( }; if (typeof callback === 'function') { - return callback({ ...defaultAlert }); + return callback({ ...data }); } - return { ...defaultAlert }; + return { ...data }; }; -export const createMockUnlabeledDataflowAlert = ( - callback?: mockAlertRenderer, -): UnlabeledDataflowAlert => { - const defaultAlert: UnlabeledDataflowAlert = { - id: AlertType.UnlabeledDataflow, +export const createMockUnlabeledDataflowData = ( + callback?: mockAlertRenderer, +): UnlabeledDataflowData => { + const data: UnlabeledDataflowData = { periodStart: '2020-05-01', periodEnd: '2020-06-1', projects: [], @@ -109,10 +107,10 @@ export const createMockUnlabeledDataflowAlert = ( }; if (typeof callback === 'function') { - return callback({ ...defaultAlert }); + return callback({ ...data }); } - return { ...defaultAlert }; + return { ...data }; }; export const createMockUnlabeledDataflowAlertProject = ( @@ -138,7 +136,7 @@ export const MockProductTypes: Record = { 'cloud-pub-sub': 'Cloud Pub/Sub', }; -export const MockProductFilters = Object.keys( +export const MockProductFilters: ProductFilters = Object.keys( MockProductTypes, ).map(productType => ({ duration: Duration.P1M, productType })); @@ -156,7 +154,9 @@ export const MockLoadingActions = ([ DefaultLoadingAction.CostInsightsPage, ] as string[]).concat(MockProducts.map(product => product.kind)); -export const mockDefaultState = getDefaultState(MockLoadingActions); +export const mockDefaultLoadingState = getDefaultLoadingState( + MockLoadingActions, +); export const MockComputeEngine = findAlways( MockProducts, diff --git a/plugins/cost-insights/src/utils/styles.ts b/plugins/cost-insights/src/utils/styles.ts index e6b38ee719..b20c601276 100644 --- a/plugins/cost-insights/src/utils/styles.ts +++ b/plugins/cost-insights/src/utils/styles.ts @@ -385,6 +385,7 @@ export const useSelectStyles = makeStyles( select: { minWidth: 200, textAlign: 'start', + backgroundColor: theme.palette.background.paper, }, menuItem: { minWidth: 200, @@ -453,3 +454,12 @@ export const useBackdropStyles = makeStyles( }, }), ); + +export const useSubtleTypographyStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + root: { + color: theme.palette.textSubtle, + }, + }), +); diff --git a/plugins/cost-insights/src/utils/tests.tsx b/plugins/cost-insights/src/utils/tests.tsx index 807232555b..db47bd72bd 100644 --- a/plugins/cost-insights/src/utils/tests.tsx +++ b/plugins/cost-insights/src/utils/tests.tsx @@ -13,74 +13,221 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import React, { Dispatch, ReactNode, SetStateAction } from 'react'; + +import React, { PropsWithChildren } from 'react'; +import { costInsightsApiRef, CostInsightsApi } from '../api'; import { - getDefaultPageFilters, - PageFilters, - ProductFilters, - Group, -} from '../types'; -import { FilterContext } from '../hooks/useFilters'; + ApiProvider, + ApiRegistry, + IdentityApi, + identityApiRef, +} from '@backstage/core'; +import { LoadingContext, LoadingContextProps } from '../hooks/useLoading'; +import { GroupsContext, GroupsContextProps } from '../hooks/useGroups'; +import { FilterContext, FilterContextProps } from '../hooks/useFilters'; import { ConfigContext, ConfigContextProps } from '../hooks/useConfig'; import { CurrencyContext, CurrencyContextProps } from '../hooks/useCurrency'; -import { ScrollContext, ScrollProviderProps } from '../hooks/useScroll'; -import { MockProductFilters } from './mockData'; +import { + BillingDateContext, + BillingDateContextProps, +} from '../hooks/useLastCompleteBillingDate'; +import { ScrollContext, ScrollContextProps } from '../hooks/useScroll'; +import { Duration, Group } from '../types'; + +/* + Mock Providers and types are exposed publicly to allow users to test custom implementations + such as alerts, which may require context. + + Utility functions such as getDefaultPageFilters, etc. are intentionally + omitted as we do not want to expose explictly or implicitly internal implementations + that may be subject to change. + + Each Mock Provider provides minimal defaults which can be overridden, allowing users to define + context props only when necessary. +*/ + +type PartialPropsWithChildren = PropsWithChildren>; export const MockGroups: Group[] = [{ id: 'tech' }, { id: 'mock-group' }]; -type MockFilterProviderProps = { - setPageFilters: Dispatch>; - setProductFilters: Dispatch>; - children: ReactNode; -}; +export type MockFilterProviderProps = PartialPropsWithChildren< + FilterContextProps +>; export const MockFilterProvider = ({ - setPageFilters, - setProductFilters, children, + ...context }: MockFilterProviderProps) => { - const pageFilters = getDefaultPageFilters(MockGroups); + const defaultContext: FilterContextProps = { + pageFilters: { + group: 'tech', + project: null, + duration: Duration.P90D, + metric: null, + }, + productFilters: [], + setPageFilters: jest.fn(), + setProductFilters: jest.fn(), + }; return ( - + {children} ); }; -export const MockConfigProvider = ({ - metrics, - products, - icons, - engineerCost, - currencies, +export type MockLoadingProviderProps = PartialPropsWithChildren< + LoadingContextProps +>; + +export const MockLoadingProvider = ({ children, -}: ConfigContextProps & { children: React.ReactNode }) => ( - - {children} - -); + ...context +}: MockLoadingProviderProps) => { + const defaultContext: LoadingContextProps = { + state: {}, + actions: [], + dispatch: jest.fn(), + }; + return ( + + {children} + + ); +}; + +export type MockConfigProviderProps = PartialPropsWithChildren< + ConfigContextProps +>; + +export const MockConfigProvider = ({ + children, + ...context +}: MockConfigProviderProps) => { + const defaultContext: ConfigContextProps = { + metrics: [], + products: [], + icons: [], + engineerCost: 0, + currencies: [], + }; + return ( + + {children} + + ); +}; + +export type MockCurrencyProviderProps = PartialPropsWithChildren< + CurrencyContextProps +>; export const MockCurrencyProvider = ({ - currency, - setCurrency, children, -}: CurrencyContextProps & { children: React.ReactNode }) => ( - - {children} - -); + ...context +}: MockCurrencyProviderProps) => { + const defaultContext: CurrencyContextProps = { + currency: { + kind: null, + label: 'Engineers 🛠', + unit: 'engineer', + }, + setCurrency: jest.fn(), + }; + return ( + + {children} + + ); +}; -export const MockScrollProvider = ({ children }: ScrollProviderProps) => ( - - {children} - -); +export type MockBillingDateProviderProps = PartialPropsWithChildren< + BillingDateContextProps +>; + +export const MockBillingDateProvider = ({ + children, + ...context +}: MockBillingDateProviderProps) => { + const defaultContext: BillingDateContextProps = { + lastCompleteBillingDate: '2020-10-01', + }; + return ( + + {children} + + ); +}; + +export type MockScrollProviderProps = PropsWithChildren<{}>; + +export const MockScrollProvider = ({ children }: MockScrollProviderProps) => { + const defaultContext: ScrollContextProps = { + scrollTo: null, + setScrollTo: jest.fn(), + }; + return ( + + {children} + + ); +}; + +export type MockGroupsProviderProps = PartialPropsWithChildren< + GroupsContextProps +>; + +export const MockGroupsProvider = ({ + children, + ...context +}: MockGroupsProviderProps) => { + const defaultContext: GroupsContextProps = { + groups: [], + }; + return ( + + {children} + + ); +}; + +export type MockCostInsightsApiProviderProps = PartialPropsWithChildren<{ + identityApi: Partial; + costInsightsApi: Partial; +}>; + +export const MockCostInsightsApiProvider = ({ + children, + ...context +}: MockCostInsightsApiProviderProps) => { + const defaultIdentityApi: IdentityApi = { + getProfile: jest.fn(), + getIdToken: jest.fn(), + getUserId: jest.fn(), + signOut: jest.fn(), + }; + + const defaultCostInsightsApi: CostInsightsApi = { + getAlerts: jest.fn(), + getDailyMetricData: jest.fn(), + getGroupDailyCost: jest.fn(), + getGroupProjects: jest.fn(), + getLastCompleteBillingDate: jest.fn(), + getProductInsights: jest.fn(), + getProjectDailyCost: jest.fn(), + getUserGroups: jest.fn(), + }; + + // TODO: defaultConfigApiRef: ConfigApiRef + + const defaultContext = ApiRegistry.from([ + [identityApiRef, { ...defaultIdentityApi, ...context.identityApi }], + [ + costInsightsApiRef, + { ...defaultCostInsightsApi, ...context.costInsightsApi }, + ], + // [configApiRef, { ...defaultConfigApiRef, ...context.configApiRef }] + ]); + + return {children}; +}; diff --git a/plugins/explore/package.json b/plugins/explore/package.json index 5bd78ab088..4db68909b9 100644 --- a/plugins/explore/package.json +++ b/plugins/explore/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-explore", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,8 +21,8 @@ "start": "backstage-cli plugin:serve" }, "dependencies": { - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -33,17 +33,16 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/explore/src/components/ExplorePluginPage.tsx b/plugins/explore/src/components/ExplorePluginPage.tsx index 83402d8062..f3e75e0011 100644 --- a/plugins/explore/src/components/ExplorePluginPage.tsx +++ b/plugins/explore/src/components/ExplorePluginPage.tsx @@ -21,7 +21,6 @@ import { ContentHeader, Header, Page, - pageTheme, SupportButton, } from '@backstage/core'; import ExploreCard, { CardData } from './ExploreCard'; @@ -116,8 +115,9 @@ const toolsCards = [ export const ExplorePluginPage = () => { const classes = useStyles(); + return ( - +
); -export const NewProjectPage = () => { - return ( - -
- {labels} -
- - - - This plugin allows you to view and interact with your gcp projects. - - - - -
- ); -}; +export const NewProjectPage = () => ( + +
+ {labels} +
+ + + + This plugin allows you to view and interact with your gcp projects. + + + + +
+); diff --git a/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx b/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx index 3dfb4e886b..0c6350b849 100644 --- a/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx +++ b/plugins/gcp-projects/src/components/ProjectDetailsPage/ProjectDetailsPage.tsx @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import { Content, ContentHeader, Header, HeaderLabel, Page, - pageTheme, SupportButton, useApi, WarningPanel, @@ -147,18 +145,16 @@ const labels = ( ); -export const ProjectDetailsPage = () => { - return ( - -
- {labels} -
- - - Support Button - - - -
- ); -}; +export const ProjectDetailsPage = () => ( + +
+ {labels} +
+ + + Support Button + + + +
+); diff --git a/plugins/gcp-projects/src/components/ProjectListPage/ProjectListPage.tsx b/plugins/gcp-projects/src/components/ProjectListPage/ProjectListPage.tsx index 542d03d5fd..b911040535 100644 --- a/plugins/gcp-projects/src/components/ProjectListPage/ProjectListPage.tsx +++ b/plugins/gcp-projects/src/components/ProjectListPage/ProjectListPage.tsx @@ -15,7 +15,6 @@ */ // NEEDS WORK - import { Content, ContentHeader, @@ -23,7 +22,6 @@ import { HeaderLabel, Link, Page, - pageTheme, SupportButton, useApi, WarningPanel, @@ -134,21 +132,19 @@ const PageContents = () => { ); }; -export const ProjectListPage = () => { - return ( - -
- {labels} -
- - - - All your software catalog entities - - - -
- ); -}; +export const ProjectListPage = () => ( + +
+ {labels} +
+ + + + All your software catalog entities + + + +
+); diff --git a/plugins/gcp-projects/src/setupTests.ts b/plugins/gcp-projects/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/gcp-projects/src/setupTests.ts +++ b/plugins/gcp-projects/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/github-actions/package.json b/plugins/github-actions/package.json index a43e351d47..75fed63465 100644 --- a/plugins/github-actions/package.json +++ b/plugins/github-actions/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-github-actions", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,11 +21,11 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/core-api": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/core-api": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -40,16 +40,16 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/github-actions/src/api/types.ts b/plugins/github-actions/src/api/types.ts index ccc9198e58..00d622cccf 100644 --- a/plugins/github-actions/src/api/types.ts +++ b/plugins/github-actions/src/api/types.ts @@ -17,7 +17,7 @@ export type Step = { name: string; status: string; - conclusion: string; + conclusion?: string; number: number; // starts from 1 started_at: string; completed_at: string; diff --git a/plugins/github-actions/src/components/Cards/Cards.tsx b/plugins/github-actions/src/components/Cards/Cards.tsx index 7e4d5f5fb6..1f1e2997df 100644 --- a/plugins/github-actions/src/components/Cards/Cards.tsx +++ b/plugins/github-actions/src/components/Cards/Cards.tsx @@ -81,10 +81,9 @@ const WidgetContent = ({ export const LatestWorkflowRunCard = ({ entity, branch = 'master', -}: { - entity: Entity; - branch: string; -}) => { + // Display the card full height suitable for + variant, +}: Props) => { const errorApi = useApi(errorApiRef); const [owner, repo] = ( entity?.metadata.annotations?.[GITHUB_ACTIONS_ANNOTATION] ?? '/' @@ -102,7 +101,7 @@ export const LatestWorkflowRunCard = ({ }, [error, errorApi]); return ( - + ( - + variant, +}: Props) => ( + ); diff --git a/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.tsx b/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.tsx index e5bba7fad9..46f60981a0 100644 --- a/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.tsx +++ b/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.tsx @@ -18,9 +18,9 @@ import { errorApiRef, useApi } from '@backstage/core-api'; import { GITHUB_ACTIONS_ANNOTATION } from '../useProjectName'; import { useWorkflowRuns } from '../useWorkflowRuns'; import React, { useEffect } from 'react'; -import { EmptyState, Table } from '@backstage/core'; +import { EmptyState, InfoCard, Table } from '@backstage/core'; import { WorkflowRunStatus } from '../WorkflowRunStatus'; -import { Button, Card, Link, TableContainer } from '@material-ui/core'; +import { Button, Link } from '@material-ui/core'; import { generatePath, Link as RouterLink } from 'react-router-dom'; const firstLine = (message: string): string => message.split('\n')[0]; @@ -30,6 +30,7 @@ export type Props = { branch?: string; dense?: boolean; limit?: number; + variant?: string; }; export const RecentWorkflowRunsCard = ({ @@ -37,6 +38,7 @@ export const RecentWorkflowRunsCard = ({ branch, dense = false, limit = 5, + variant, }: Props) => { const errorApi = useApi(errorApiRef); const [owner, repo] = ( @@ -70,15 +72,19 @@ export const RecentWorkflowRunsCard = ({ } /> ) : ( - + - + ); }; diff --git a/plugins/github-actions/src/components/WorkflowRunDetails/WorkflowRunDetails.tsx b/plugins/github-actions/src/components/WorkflowRunDetails/WorkflowRunDetails.tsx index 7714ad6cb6..a2753589eb 100644 --- a/plugins/github-actions/src/components/WorkflowRunDetails/WorkflowRunDetails.tsx +++ b/plugins/github-actions/src/components/WorkflowRunDetails/WorkflowRunDetails.tsx @@ -77,8 +77,9 @@ const JobsList = ({ jobs, entity }: { jobs?: Jobs; entity: Entity }) => { {jobs && jobs.total_count > 0 && - jobs.jobs.map((job: Job) => ( + jobs.jobs.map(job => ( { @@ -142,8 +143,8 @@ const JobListItem = ({
- {job.steps.map((step: Step) => ( - + {job.steps.map(step => ( + ))}
diff --git a/plugins/github-actions/src/setupTests.ts b/plugins/github-actions/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/github-actions/src/setupTests.ts +++ b/plugins/github-actions/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/gitops-profiles/package.json b/plugins/gitops-profiles/package.json index 7c63ea350c..18486bc2b7 100644 --- a/plugins/gitops-profiles/package.json +++ b/plugins/gitops-profiles/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-gitops-profiles", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,8 +21,8 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -32,16 +32,16 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/gitops-profiles/src/components/ClusterList/ClusterList.tsx b/plugins/gitops-profiles/src/components/ClusterList/ClusterList.tsx index baab018415..70bf4c8c3f 100644 --- a/plugins/gitops-profiles/src/components/ClusterList/ClusterList.tsx +++ b/plugins/gitops-profiles/src/components/ClusterList/ClusterList.tsx @@ -21,7 +21,6 @@ import { Header, SupportButton, Page, - pageTheme, Progress, HeaderLabel, useApi, @@ -91,7 +90,7 @@ const ClusterList: FC<{}> = () => { } return ( - +
diff --git a/plugins/gitops-profiles/src/components/ClusterPage/ClusterPage.tsx b/plugins/gitops-profiles/src/components/ClusterPage/ClusterPage.tsx index b2d62e8650..9b6e5bdb08 100644 --- a/plugins/gitops-profiles/src/components/ClusterPage/ClusterPage.tsx +++ b/plugins/gitops-profiles/src/components/ClusterPage/ClusterPage.tsx @@ -13,13 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import React, { FC, useEffect, useState } from 'react'; import { Content, Header, Page, - pageTheme, Table, Progress, HeaderLabel, @@ -85,7 +83,7 @@ const ClusterPage: FC<{}> = () => { }, [pollingLog, api, params, githubAuth, githubAccessToken, githubUsername]); return ( - +
diff --git a/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.test.tsx b/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.test.tsx index 06074ff84d..f01ac70e64 100644 --- a/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.test.tsx +++ b/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.test.tsx @@ -16,7 +16,6 @@ import React from 'react'; import { render } from '@testing-library/react'; -import mockFetch from 'jest-fetch-mock'; import ProfileCatalog from './ProfileCatalog'; import { ThemeProvider } from '@material-ui/core'; import { lightTheme } from '@backstage/theme'; @@ -45,7 +44,6 @@ describe('ProfileCatalog', () => { }), ], ]); - mockFetch.mockResponse(() => new Promise(() => {})); const rendered = render( diff --git a/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.tsx b/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.tsx index a5125fb006..a70cf97342 100644 --- a/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.tsx +++ b/plugins/gitops-profiles/src/components/ProfileCatalog/ProfileCatalog.tsx @@ -18,7 +18,6 @@ import React, { FC, useEffect, useState } from 'react'; import { Header, Page, - pageTheme, Content, ContentHeader, HeaderLabel, @@ -259,7 +258,7 @@ const ProfileCatalog: FC<{}> = () => { ]; return ( - +
({ describe('GraphiQLPage', () => { it('should show progress', async () => { + jest.useFakeTimers(); const loadingApi: GraphQLBrowseApi = { async getEndpoints() { await new Promise(() => {}); @@ -43,9 +45,12 @@ describe('GraphiQLPage', () => { , , ); - + act(() => { + jest.advanceTimersByTime(250); + }); rendered.getByText('GraphiQL'); rendered.getByTestId('progress'); + jest.useRealTimers(); }); it('should show error', async () => { diff --git a/plugins/graphiql/src/components/GraphiQLPage/GraphiQLPage.tsx b/plugins/graphiql/src/components/GraphiQLPage/GraphiQLPage.tsx index 7eb91b59d8..224def1d78 100644 --- a/plugins/graphiql/src/components/GraphiQLPage/GraphiQLPage.tsx +++ b/plugins/graphiql/src/components/GraphiQLPage/GraphiQLPage.tsx @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import React from 'react'; import { Content, @@ -21,7 +20,6 @@ import { HeaderLabel, Page, Progress, - pageTheme, useApi, } from '@backstage/core'; import { useAsync } from 'react-use'; @@ -60,7 +58,7 @@ export const GraphiQLPage = () => { } return ( - +
diff --git a/plugins/graphiql/src/setupTests.ts b/plugins/graphiql/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/graphiql/src/setupTests.ts +++ b/plugins/graphiql/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/graphql/package.json b/plugins/graphql/package.json index edd3f2782e..58b6c763c6 100644 --- a/plugins/graphql/package.json +++ b/plugins/graphql/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-graphql-backend", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -19,9 +19,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", - "@backstage/plugin-catalog-graphql": "^0.1.1-alpha.24", + "@backstage/backend-common": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", + "@backstage/plugin-catalog-graphql": "^0.1.1-alpha.26", "@graphql-modules/core": "^0.7.17", "@types/express": "^4.17.6", "apollo-server": "^2.16.1", @@ -30,13 +30,12 @@ "express-promise-router": "^3.0.3", "graphql": "^15.3.0", "helmet": "^4.0.0", - "node-fetch": "^2.6.0", "reflect-metadata": "^0.1.13", "winston": "^3.2.1", "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", "@types/supertest": "^2.0.8", "eslint-plugin-graphql": "^4.0.0", "msw": "^0.20.5", diff --git a/plugins/jenkins/README.md b/plugins/jenkins/README.md index 565906ca85..1d3e7f60e5 100644 --- a/plugins/jenkins/README.md +++ b/plugins/jenkins/README.md @@ -33,7 +33,7 @@ proxy: $env: JENKINS_BASIC_AUTH_HEADER ``` -4. Add an environment variable which contains the Jenkins credentials, (note: use an API token not your password) +4. Add an environment variable which contains the Jenkins credentials, (note: use an API token not your password). Here user is the name of the user created in Jenkins. ```shell HEADER=$(echo -n user:api-token | base64) @@ -61,6 +61,21 @@ spec: 8. Click the component in the catalog you should now see Jenkins builds, and a last build result for your master build. +Note: + +If you are not using environment variable then you can directly type API token in app-config.yaml + +```yaml +proxy: + '/jenkins/api': + target: 'http://localhost:8080' # your Jenkins URL + changeOrigin: true + headers: + Authorization: Basic YWRtaW46MTFlYzI1NmU0Mzg1MDFjM2Y1Yzc2Yjc1MWE3ZTQ3YWY4Mw== +``` + +YWRtaW46MTFlYzI1NmU0Mzg1MDFjM2Y1Yzc2Yjc1MWE3ZTQ3YWY4Mw== is the base64 of user and it's API token e.g. admin:11ec256e438501c3f5c76b751a7e47af83 + ## Features - View all runs inside a folder diff --git a/plugins/jenkins/package.json b/plugins/jenkins/package.json index 186fdbcc33..194ae71429 100644 --- a/plugins/jenkins/package.json +++ b/plugins/jenkins/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-jenkins", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,10 +21,10 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -36,17 +36,17 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/testing-library__jest-dom": "^5.9.1", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/jenkins/src/components/Cards/Cards.tsx b/plugins/jenkins/src/components/Cards/Cards.tsx index 5034effdcf..31acedc180 100644 --- a/plugins/jenkins/src/components/Cards/Cards.tsx +++ b/plugins/jenkins/src/components/Cards/Cards.tsx @@ -61,12 +61,18 @@ const WidgetContent = ({ ); }; -export const LatestRunCard = ({ branch = 'master' }: { branch: string }) => { +export const LatestRunCard = ({ + branch = 'master', + variant, +}: { + branch: string; + variant?: string; +}) => { const { owner, repo } = useProjectSlugFromEntity(); const [{ builds, loading }] = useBuilds(owner, repo, branch); const lastRun = builds ?? {}; return ( - + ); diff --git a/plugins/jenkins/src/components/Router.tsx b/plugins/jenkins/src/components/Router.tsx index a4c7314691..91bcde2a8b 100644 --- a/plugins/jenkins/src/components/Router.tsx +++ b/plugins/jenkins/src/components/Router.tsx @@ -19,7 +19,7 @@ import { buildRouteRef, rootRouteRef } from '../plugin'; import { DetailedViewPage } from './BuildWithStepsPage/'; import { JENKINS_ANNOTATION } from '../constants'; import { Entity } from '@backstage/catalog-model'; -import { WarningPanel } from '@backstage/core'; +import { MissingAnnotationEmptyState } from '@backstage/core'; import { CITable } from './BuildsPage/lib/CITable'; export const isPluginApplicableToEntity = (entity: Entity) => @@ -27,10 +27,7 @@ export const isPluginApplicableToEntity = (entity: Entity) => export const Router = ({ entity }: { entity: Entity }) => { return !isPluginApplicableToEntity(entity) ? ( - -
entity.metadata.annotations['{JENKINS_ANNOTATION}']
- key is missing on the entity. -
+ ) : ( } /> diff --git a/plugins/jenkins/src/setupTests.ts b/plugins/jenkins/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/jenkins/src/setupTests.ts +++ b/plugins/jenkins/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/kubernetes-backend/README.md b/plugins/kubernetes-backend/README.md index fbbde1fe65..a9fdc14707 100644 --- a/plugins/kubernetes-backend/README.md +++ b/plugins/kubernetes-backend/README.md @@ -8,21 +8,33 @@ It responds to Kubernetes requests from the frontend. ## Configuration -### clusterLocatorMethod +### serviceLocatorMethod This configures how to determine which clusters a component is running in. -Currently, the only valid locator method is: +Currently, the only valid serviceLocatorMethod is: -#### configMultiTenant +#### multiTenant This configuration assumes that all components run on all the provided clusters. +### clusterLocatorMethods + +This is used to determine where to retrieve cluster configuration from. + +Currently, the only valid serviceLocatorMethod is: + +#### config + +This clusterLocatorMethod will read cluster information in from config + Example: ```yaml kubernetes: - clusterLocatorMethod: 'configMultiTenant' + serviceLocatorMethod: 'multiTenant' + clusterLocatorMethods: + - 'config' clusters: - url: http://127.0.0.1:9999 name: minikube @@ -35,7 +47,7 @@ kubernetes: ##### clusters -Used by the `configMultiTenant` `clusterLocatorMethod` to construct Kubernetes clients. +Used by the `config` `clusterLocatorMethods` to construct Kubernetes clients. ###### url diff --git a/plugins/kubernetes-backend/examples/dice-roller/README.md b/plugins/kubernetes-backend/examples/dice-roller/README.md index f97f760c9f..bf3e7d261a 100644 --- a/plugins/kubernetes-backend/examples/dice-roller/README.md +++ b/plugins/kubernetes-backend/examples/dice-roller/README.md @@ -23,11 +23,13 @@ This can be used to run the kubernetes plugin locally against a mock service. 6. Register existing component in Backstage - https://github.com/mclarke47/dice-roller/blob/master/catalog-info.yaml -Update `app-config.development.yaml` as follows. +Add or update `app-config.local.yaml` with the following: ```yaml kubernetes: - clusterLocatorMethod: 'configMultiTenant' + serviceLocatorMethod: 'multiTenant' + clusterLocatorMethods: + - 'config' clusters: - url: name: minikube @@ -43,4 +45,4 @@ Mac copy to clipboard: kubectl get secret $(kubectl get sa dice-roller -o=json | jq -r .secrets[0].name) -o=json | jq -r '.data["token"]' | base64 --decode | pbcopy ``` -Paste into `app-config.development.yaml` `kubernetes.clusters[0].serviceAccountToken` +Paste into `app-config.local.yaml` `kubernetes.clusters[0].serviceAccountToken` diff --git a/plugins/kubernetes-backend/package.json b/plugins/kubernetes-backend/package.json index a44199ec8b..26cc842db9 100644 --- a/plugins/kubernetes-backend/package.json +++ b/plugins/kubernetes-backend/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-kubernetes-backend", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,8 +20,8 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", + "@backstage/backend-common": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", "@kubernetes/client-node": "^0.12.1", "@types/express": "^4.17.6", "compression": "^1.7.4", @@ -37,8 +37,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "jest-fetch-mock": "^3.0.3", + "@backstage/cli": "^0.1.1-alpha.26", "supertest": "^4.0.2" }, "files": [ diff --git a/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.test.ts b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.test.ts similarity index 82% rename from plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.test.ts rename to plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.test.ts index dd77a11bae..550703e430 100644 --- a/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.test.ts +++ b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.test.ts @@ -15,10 +15,10 @@ */ import '@backstage/backend-common'; -import { MultiTenantConfigClusterLocator } from './MultiTenantConfigClusterLocator'; import { ConfigReader, Config } from '@backstage/config'; +import { ConfigClusterLocator } from './ConfigClusterLocator'; -describe('MultiTenantConfigClusterLocator', () => { +describe('ConfigClusterLocator', () => { it('empty clusters returns empty cluster details', async () => { const config: Config = new ConfigReader( { @@ -27,11 +27,11 @@ describe('MultiTenantConfigClusterLocator', () => { 'ctx', ); - const sut = MultiTenantConfigClusterLocator.fromConfig( + const sut = ConfigClusterLocator.fromConfig( config.getConfigArray('clusters'), ); - const result = await sut.getClusterByServiceId('ignored'); + const result = await sut.getClusters(); expect(result).toStrictEqual([]); }); @@ -50,11 +50,11 @@ describe('MultiTenantConfigClusterLocator', () => { 'ctx', ); - const sut = MultiTenantConfigClusterLocator.fromConfig( + const sut = ConfigClusterLocator.fromConfig( config.getConfigArray('clusters'), ); - const result = await sut.getClusterByServiceId('ignored'); + const result = await sut.getClusters(); expect(result).toStrictEqual([ { @@ -86,11 +86,11 @@ describe('MultiTenantConfigClusterLocator', () => { 'ctx', ); - const sut = MultiTenantConfigClusterLocator.fromConfig( + const sut = ConfigClusterLocator.fromConfig( config.getConfigArray('clusters'), ); - const result = await sut.getClusterByServiceId('ignored'); + const result = await sut.getClusters(); expect(result).toStrictEqual([ { diff --git a/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.ts b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.ts similarity index 65% rename from plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.ts rename to plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.ts index 5a1f0f3839..5ff4581f71 100644 --- a/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.ts +++ b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.ts @@ -14,23 +14,20 @@ * limitations under the License. */ +import { ClusterDetails, KubernetesClustersSupplier } from '..'; import { Config } from '@backstage/config'; -import { ClusterDetails, KubernetesClusterLocator } from '..'; -// This cluster locator assumes that every service is located on every cluster -// Therefore it will always return all clusters in an app configuration file -export class MultiTenantConfigClusterLocator - implements KubernetesClusterLocator { +export class ConfigClusterLocator implements KubernetesClustersSupplier { private readonly clusterDetails: ClusterDetails[]; constructor(clusterDetails: ClusterDetails[]) { this.clusterDetails = clusterDetails; } - static fromConfig(config: Config[]): MultiTenantConfigClusterLocator { + static fromConfig(config: Config[]): ConfigClusterLocator { // TODO: Add validation that authProvider is required and serviceAccountToken // is required if authProvider is serviceAccount - return new MultiTenantConfigClusterLocator( + return new ConfigClusterLocator( config.map(c => { return { name: c.getString('name'), @@ -42,9 +39,7 @@ export class MultiTenantConfigClusterLocator ); } - // As this implementation always returns all clusters serviceId is ignored here - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async getClusterByServiceId(_serviceId: string): Promise { + async getClusters(): Promise { return this.clusterDetails; } } diff --git a/plugins/kubernetes-backend/src/cluster-locator/index.test.ts b/plugins/kubernetes-backend/src/cluster-locator/index.test.ts new file mode 100644 index 0000000000..32a09cb496 --- /dev/null +++ b/plugins/kubernetes-backend/src/cluster-locator/index.test.ts @@ -0,0 +1,68 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Config, ConfigReader } from '../../../../packages/config/src'; +import { getCombinedClusterDetails } from './index'; + +describe('getCombinedClusterDetails', () => { + it('should retrieve cluster details from config', async () => { + const config: Config = new ConfigReader( + { + kubernetes: { + clusters: [ + { + name: 'cluster1', + serviceAccountToken: 'token', + url: 'http://localhost:8080', + authProvider: 'serviceAccount', + }, + { + name: 'cluster2', + url: 'http://localhost:8081', + authProvider: 'google', + }, + ], + }, + }, + 'ctx', + ); + + const result = await getCombinedClusterDetails(['config'], config); + + expect(result).toStrictEqual([ + { + name: 'cluster1', + serviceAccountToken: 'token', + url: 'http://localhost:8080', + authProvider: 'serviceAccount', + }, + { + name: 'cluster2', + serviceAccountToken: undefined, + url: 'http://localhost:8081', + authProvider: 'google', + }, + ]); + }); + + it('throws an error when using an unsupported cluster locator', async () => { + await expect( + getCombinedClusterDetails(['magic' as any], new ConfigReader({}, 'ctx')), + ).rejects.toStrictEqual( + new Error('Unsupported kubernetes.clusterLocatorMethods: "magic"'), + ); + }); +}); diff --git a/plugins/kubernetes-backend/src/cluster-locator/index.ts b/plugins/kubernetes-backend/src/cluster-locator/index.ts new file mode 100644 index 0000000000..ea418768b4 --- /dev/null +++ b/plugins/kubernetes-backend/src/cluster-locator/index.ts @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClusterDetails, ClusterLocatorMethod } from '..'; +import { Config } from '../../../../packages/config/src'; +import { ConfigClusterLocator } from './ConfigClusterLocator'; + +export { ConfigClusterLocator } from './ConfigClusterLocator'; + +export const getCombinedClusterDetails = async ( + clusterLocatorMethods: ClusterLocatorMethod[], + rootConfig: Config, +): Promise => { + return Promise.all( + clusterLocatorMethods.map(clusterLocatorMethod => { + switch (clusterLocatorMethod) { + case 'config': + return ConfigClusterLocator.fromConfig( + rootConfig.getConfigArray('kubernetes.clusters'), + ).getClusters(); + default: + throw new Error( + `Unsupported kubernetes.clusterLocatorMethods: "${clusterLocatorMethod}"`, + ); + } + }), + ) + .then(res => { + return res.flat(); + }) + .catch(e => { + throw e; + }); +}; diff --git a/plugins/kubernetes-backend/src/service-locator/MultiTenantServiceLocator.test.ts b/plugins/kubernetes-backend/src/service-locator/MultiTenantServiceLocator.test.ts new file mode 100644 index 0000000000..13761e2671 --- /dev/null +++ b/plugins/kubernetes-backend/src/service-locator/MultiTenantServiceLocator.test.ts @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import '@backstage/backend-common'; +import { MultiTenantServiceLocator } from './MultiTenantServiceLocator'; + +describe('MultiTenantConfigClusterLocator', () => { + it('empty clusters returns empty cluster details', async () => { + const sut = new MultiTenantServiceLocator([]); + + const result = await sut.getClustersByServiceId('ignored'); + + expect(result).toStrictEqual([]); + }); + + it('one clusters returns one cluster details', async () => { + const sut = new MultiTenantServiceLocator([ + { + name: 'cluster1', + url: 'http://localhost:8080', + authProvider: 'serviceAccount', + serviceAccountToken: '12345', + }, + ]); + + const result = await sut.getClustersByServiceId('ignored'); + + expect(result).toStrictEqual([ + { + name: 'cluster1', + serviceAccountToken: '12345', + url: 'http://localhost:8080', + authProvider: 'serviceAccount', + }, + ]); + }); + + it('two clusters returns two cluster details', async () => { + const sut = new MultiTenantServiceLocator([ + { + name: 'cluster1', + serviceAccountToken: 'token', + url: 'http://localhost:8080', + authProvider: 'serviceAccount', + }, + { + name: 'cluster2', + url: 'http://localhost:8081', + authProvider: 'google', + }, + ]); + + const result = await sut.getClustersByServiceId('ignored'); + + expect(result).toStrictEqual([ + { + name: 'cluster1', + serviceAccountToken: 'token', + url: 'http://localhost:8080', + authProvider: 'serviceAccount', + }, + { + name: 'cluster2', + url: 'http://localhost:8081', + authProvider: 'google', + }, + ]); + }); +}); diff --git a/plugins/kubernetes-backend/src/service-locator/MultiTenantServiceLocator.ts b/plugins/kubernetes-backend/src/service-locator/MultiTenantServiceLocator.ts new file mode 100644 index 0000000000..a5822a2078 --- /dev/null +++ b/plugins/kubernetes-backend/src/service-locator/MultiTenantServiceLocator.ts @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClusterDetails, KubernetesServiceLocator } from '..'; + +// This locator assumes that every service is located on every cluster +// Therefore it will always return all clusters provided +export class MultiTenantServiceLocator implements KubernetesServiceLocator { + private readonly clusterDetails: ClusterDetails[]; + + constructor(clusterDetails: ClusterDetails[]) { + this.clusterDetails = clusterDetails; + } + + // As this implementation always returns all clusters serviceId is ignored here + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async getClustersByServiceId(_serviceId: string): Promise { + return this.clusterDetails; + } +} diff --git a/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.test.ts b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.test.ts index 4218c64e80..8c26ded2d4 100644 --- a/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.test.ts +++ b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.test.ts @@ -22,7 +22,7 @@ const TEST_SERVICE_ID = 'my-service'; const fetchObjectsByServiceId = jest.fn(); -const getClusterByServiceId = jest.fn(); +const getClustersByServiceId = jest.fn(); const mockFetch = (mock: jest.Mock) => { mock.mockImplementation((serviceId: string, clusterDetails: ClusterDetails) => @@ -70,7 +70,7 @@ describe('handleGetKubernetesObjectsByServiceId', () => { }); it('retrieve objects for one cluster', async () => { - getClusterByServiceId.mockImplementation(() => + getClustersByServiceId.mockImplementation(() => Promise.resolve([ { name: 'test-cluster', @@ -87,13 +87,13 @@ describe('handleGetKubernetesObjectsByServiceId', () => { fetchObjectsByServiceId, }, { - getClusterByServiceId, + getClustersByServiceId, }, getVoidLogger(), {}, ); - expect(getClusterByServiceId.mock.calls.length).toBe(1); + expect(getClustersByServiceId.mock.calls.length).toBe(1); expect(fetchObjectsByServiceId.mock.calls.length).toBe(1); expect(result).toStrictEqual({ items: [ @@ -140,7 +140,7 @@ describe('handleGetKubernetesObjectsByServiceId', () => { }); it('retrieve objects for two clusters', async () => { - getClusterByServiceId.mockImplementation(() => + getClustersByServiceId.mockImplementation(() => Promise.resolve([ { name: 'test-cluster', @@ -161,7 +161,7 @@ describe('handleGetKubernetesObjectsByServiceId', () => { fetchObjectsByServiceId, }, { - getClusterByServiceId, + getClustersByServiceId, }, getVoidLogger(), { @@ -171,7 +171,7 @@ describe('handleGetKubernetesObjectsByServiceId', () => { }, ); - expect(getClusterByServiceId.mock.calls.length).toBe(1); + expect(getClustersByServiceId.mock.calls.length).toBe(1); expect(fetchObjectsByServiceId.mock.calls.length).toBe(2); expect(result).toStrictEqual({ items: [ diff --git a/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts index f0b21cbc0c..6fc6092bd6 100644 --- a/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts +++ b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts @@ -18,7 +18,7 @@ import { Logger } from 'winston'; import { AuthRequestBody, ClusterDetails, - KubernetesClusterLocator, + KubernetesServiceLocator, KubernetesFetcher, KubernetesObjectTypes, ObjectsByServiceIdResponse, @@ -29,7 +29,7 @@ import { KubernetesAuthTranslatorGenerator } from '../kubernetes-auth-translator export type GetKubernetesObjectsByServiceIdHandler = ( serviceId: string, fetcher: KubernetesFetcher, - clusterLocator: KubernetesClusterLocator, + serviceLocator: KubernetesServiceLocator, logger: Logger, requestBody: AuthRequestBody, objectsToFetch?: Set, @@ -49,12 +49,12 @@ const DEFAULT_OBJECTS = new Set([ export const handleGetKubernetesObjectsByServiceId: GetKubernetesObjectsByServiceIdHandler = async ( serviceId, fetcher, - clusterLocator, + serviceLocator, logger, requestBody, objectsToFetch = DEFAULT_OBJECTS, ) => { - const clusterDetails: ClusterDetails[] = await clusterLocator.getClusterByServiceId( + const clusterDetails: ClusterDetails[] = await serviceLocator.getClustersByServiceId( serviceId, ); diff --git a/plugins/kubernetes-backend/src/service/router.test.ts b/plugins/kubernetes-backend/src/service/router.test.ts index 4e9a206eb4..6f9fbbf70f 100644 --- a/plugins/kubernetes-backend/src/service/router.test.ts +++ b/plugins/kubernetes-backend/src/service/router.test.ts @@ -19,7 +19,7 @@ import express from 'express'; import request from 'supertest'; import { makeRouter } from './router'; import { - KubernetesClusterLocator, + KubernetesServiceLocator, KubernetesFetcher, ObjectsByServiceIdResponse, } from '..'; @@ -27,7 +27,7 @@ import { describe('router', () => { let app: express.Express; let kubernetesFetcher: jest.Mocked; - let kubernetesClusterLocator: jest.Mocked; + let kubernetesServiceLocator: jest.Mocked; let handleGetByServiceId: jest.Mock>; beforeAll(async () => { @@ -35,8 +35,8 @@ describe('router', () => { fetchObjectsByServiceId: jest.fn(), }; - kubernetesClusterLocator = { - getClusterByServiceId: jest.fn(), + kubernetesServiceLocator = { + getClustersByServiceId: jest.fn(), }; handleGetByServiceId = jest.fn(); @@ -44,7 +44,7 @@ describe('router', () => { const router = makeRouter( getVoidLogger(), kubernetesFetcher, - kubernetesClusterLocator, + kubernetesServiceLocator, handleGetByServiceId as any, ); app = express().use(router); diff --git a/plugins/kubernetes-backend/src/service/router.ts b/plugins/kubernetes-backend/src/service/router.ts index 9e9b4ab2f5..b73115e1e4 100644 --- a/plugins/kubernetes-backend/src/service/router.ts +++ b/plugins/kubernetes-backend/src/service/router.ts @@ -18,8 +18,7 @@ import express from 'express'; import Router from 'express-promise-router'; import { Logger } from 'winston'; import { Config } from '@backstage/config'; -import { ClusterLocatorMethod } from '../cluster-locator/types'; -import { MultiTenantConfigClusterLocator } from '../cluster-locator/MultiTenantConfigClusterLocator'; +import { MultiTenantServiceLocator } from '../service-locator/MultiTenantServiceLocator'; import { KubernetesClientBasedFetcher } from './KubernetesFetcher'; import { KubernetesClientProvider } from './KubernetesClientProvider'; import { @@ -28,30 +27,35 @@ import { } from './getKubernetesObjectsByServiceIdHandler'; import { AuthRequestBody, - KubernetesClusterLocator, + KubernetesServiceLocator, KubernetesFetcher, -} from '../types/types'; + ServiceLocatorMethod, + ClusterLocatorMethod, + ClusterDetails, +} from '..'; +import { getCombinedClusterDetails } from '../cluster-locator'; export interface RouterOptions { logger: Logger; config: Config; } -const getClusterLocator = (config: Config): KubernetesClusterLocator => { - const clusterLocatorMethod = config.getString( - 'kubernetes.clusterLocatorMethod', - ) as ClusterLocatorMethod; +const getServiceLocator = ( + config: Config, + clusterDetails: ClusterDetails[], +): KubernetesServiceLocator => { + const serviceLocatorMethod = config.getString( + 'kubernetes.serviceLocatorMethod', + ) as ServiceLocatorMethod; - switch (clusterLocatorMethod) { - case 'configMultiTenant': - return MultiTenantConfigClusterLocator.fromConfig( - config.getConfigArray('kubernetes.clusters'), - ); + switch (serviceLocatorMethod) { + case 'multiTenant': + return new MultiTenantServiceLocator(clusterDetails); case 'http': throw new Error('not implemented'); default: throw new Error( - `Unsupported kubernetes.clusterLocatorMethod "${clusterLocatorMethod}"`, + `Unsupported kubernetes.clusterLocatorMethod "${serviceLocatorMethod}"`, ); } }; @@ -59,13 +63,12 @@ const getClusterLocator = (config: Config): KubernetesClusterLocator => { export const makeRouter = ( logger: Logger, fetcher: KubernetesFetcher, - clusterLocator: KubernetesClusterLocator, + serviceLocator: KubernetesServiceLocator, handleGetByServiceId: GetKubernetesObjectsByServiceIdHandler, ): express.Router => { const router = Router(); router.use(express.json()); - // TODO error handling router.post('/services/:serviceId', async (req, res) => { const serviceId = req.params.serviceId; const requestBody: AuthRequestBody = req.body; @@ -73,7 +76,7 @@ export const makeRouter = ( const response = await handleGetByServiceId( serviceId, fetcher, - clusterLocator, + serviceLocator, logger, requestBody, ); @@ -96,17 +99,26 @@ export async function createRouter( logger.info('Initializing Kubernetes backend'); - const clusterLocator = getClusterLocator(options.config); - const fetcher = new KubernetesClientBasedFetcher({ kubernetesClientProvider: new KubernetesClientProvider(), logger, }); + const clusterLocatorMethods = options.config.getStringArray( + 'kubernetes.clusterLocatorMethods', + ) as ClusterLocatorMethod[]; + + const clusterDetails = await getCombinedClusterDetails( + clusterLocatorMethods, + options.config, + ); + + const serviceLocator = getServiceLocator(options.config, clusterDetails); + return makeRouter( logger, fetcher, - clusterLocator, + serviceLocator, handleGetKubernetesObjectsByServiceId, ); } diff --git a/plugins/kubernetes-backend/src/setupTests.ts b/plugins/kubernetes-backend/src/setupTests.ts index f7b6ca962d..ba33cf996b 100644 --- a/plugins/kubernetes-backend/src/setupTests.ts +++ b/plugins/kubernetes-backend/src/setupTests.ts @@ -14,6 +14,4 @@ * limitations under the License. */ -require('jest-fetch-mock').enableMocks(); - export {}; diff --git a/plugins/kubernetes-backend/src/types/types.ts b/plugins/kubernetes-backend/src/types/types.ts index eb2817f268..1422511c21 100644 --- a/plugins/kubernetes-backend/src/types/types.ts +++ b/plugins/kubernetes-backend/src/types/types.ts @@ -118,8 +118,13 @@ export interface KubernetesFetcher { } // Used to locate which cluster(s) a service is running on -export interface KubernetesClusterLocator { - getClusterByServiceId(serviceId: string): Promise; +export interface KubernetesServiceLocator { + getClustersByServiceId(serviceId: string): Promise; +} + +// Used to load cluster details from different sources +export interface KubernetesClustersSupplier { + getClusters(): Promise; } export type KubernetesErrorTypes = @@ -132,3 +137,7 @@ export interface KubernetesFetchError { statusCode?: number; resourcePath?: string; } + +export type ServiceLocatorMethod = 'multiTenant' | 'http'; // TODO implement http +export type ClusterLocatorMethod = 'config'; +export type AuthProviderType = 'google' | 'serviceAccount'; diff --git a/plugins/kubernetes/package.json b/plugins/kubernetes/package.json index 2adefebbd6..6544d751e1 100644 --- a/plugins/kubernetes/package.json +++ b/plugins/kubernetes/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-kubernetes", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,11 +20,11 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/plugin-kubernetes-backend": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/plugin-kubernetes-backend": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@kubernetes/client-node": "^0.12.1", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", @@ -35,17 +35,16 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/kubernetes/src/Router.tsx b/plugins/kubernetes/src/Router.tsx index 41f534fbef..20a4c04285 100644 --- a/plugins/kubernetes/src/Router.tsx +++ b/plugins/kubernetes/src/Router.tsx @@ -20,7 +20,7 @@ import { Route, Routes } from 'react-router-dom'; import { rootCatalogKubernetesRouteRef } from './plugin'; import { KubernetesContent } from './components/KubernetesContent'; -import { WarningPanel } from '@backstage/core'; +import { MissingAnnotationEmptyState } from '@backstage/core'; const KUBERNETES_ANNOTATION = 'backstage.io/kubernetes-id'; @@ -29,11 +29,7 @@ export const Router = ({ entity }: { entity: Entity }) => { entity.metadata.annotations?.[KUBERNETES_ANNOTATION]; if (!kubernetesAnnotationValue) { - return ( - -
{KUBERNETES_ANNOTATION}
annotation is missing on the entity. -
- ); + return ; } return ( diff --git a/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.test.tsx b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.test.tsx index 6985423a10..6fa6b3114c 100644 --- a/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.test.tsx +++ b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.test.tsx @@ -76,7 +76,7 @@ describe('ErrorPanel', () => { expect(getByText('Cluster: THIS_CLUSTER')).toBeInTheDocument(); expect( getByText( - "Error fetching Kubernetes resource: 'some/resource', error: SYSTEM_ERROR", + "Error fetching Kubernetes resource: 'some/resource', error: SYSTEM_ERROR, status code: 500", ), ).toBeInTheDocument(); }); diff --git a/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.tsx b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.tsx index 1fe5714b09..1b8336dd72 100644 --- a/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.tsx +++ b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.tsx @@ -29,7 +29,7 @@ const clustersWithErrorsToErrorMessage = ( {c.errors.map((e, j) => { return ( - {`Error fetching Kubernetes resource: '${e.resourcePath}', error: ${e.errorType}`} + {`Error fetching Kubernetes resource: '${e.resourcePath}', error: ${e.errorType}, status code: ${e.statusCode}`} ); })} diff --git a/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx b/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx index 013c7ad002..a3e82e79a4 100644 --- a/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx +++ b/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx @@ -22,7 +22,6 @@ import { configApiRef, Content, Page, - pageTheme, Progress, TabbedCard, useApi, @@ -148,7 +147,7 @@ export const KubernetesContent = ({ entity }: KubernetesContentProps) => { kubernetesObjects?.items.filter(r => r.errors.length > 0) ?? []; return ( - + {kubernetesObjects === undefined && error === undefined && ( diff --git a/plugins/kubernetes/src/setupTests.ts b/plugins/kubernetes/src/setupTests.ts index 4b4cdbdaaf..0bfa67b49a 100644 --- a/plugins/kubernetes/src/setupTests.ts +++ b/plugins/kubernetes/src/setupTests.ts @@ -14,5 +14,3 @@ * limitations under the License. */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/lighthouse/package.json b/plugins/lighthouse/package.json index 7446f09ed4..8285d29635 100644 --- a/plugins/lighthouse/package.json +++ b/plugins/lighthouse/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-lighthouse", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,35 +21,34 @@ "start": "backstage-cli plugin:serve" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/core-api": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/core-api": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", "@testing-library/react-hooks": "^3.4.2", + "@types/react": "^16.9", "react": "^16.13.1", "react-dom": "^16.13.1", "react-markdown": "^4.3.1", "react-router-dom": "6.0.0-beta.0", - "react-use": "^15.3.3", - "@types/react": "^16.9" + "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/lighthouse/src/Router.tsx b/plugins/lighthouse/src/Router.tsx index df481483c3..d264f3bc1b 100644 --- a/plugins/lighthouse/src/Router.tsx +++ b/plugins/lighthouse/src/Router.tsx @@ -23,7 +23,7 @@ import CreateAudit, { CreateAuditContent } from './components/CreateAudit'; import { Entity } from '@backstage/catalog-model'; import { LIGHTHOUSE_WEBSITE_URL_ANNOTATION } from '../constants'; import { AuditListForEntity } from './components/AuditList/AuditListForEntity'; -import { EmptyState } from '@backstage/core'; +import { MissingAnnotationEmptyState } from '@backstage/core'; export const isPluginApplicableToEntity = (entity: Entity) => Boolean(entity.metadata.annotations?.[LIGHTHOUSE_WEBSITE_URL_ANNOTATION]); @@ -38,10 +38,8 @@ export const Router = () => ( export const EmbeddedRouter = ({ entity }: { entity: Entity }) => !isPluginApplicableToEntity(entity) ? ( - ) : ( diff --git a/plugins/lighthouse/src/components/AuditList/AuditListForEntity.test.tsx b/plugins/lighthouse/src/components/AuditList/AuditListForEntity.test.tsx index 7f10914d9c..15a4ba3255 100644 --- a/plugins/lighthouse/src/components/AuditList/AuditListForEntity.test.tsx +++ b/plugins/lighthouse/src/components/AuditList/AuditListForEntity.test.tsx @@ -22,7 +22,6 @@ import { LighthouseRestApi, WebsiteListResponse, } from '../../api'; -import mockFetch from 'jest-fetch-mock'; import * as data from '../../__fixtures__/website-list-response.json'; import { EntityContext } from '@backstage/plugin-catalog'; @@ -53,7 +52,7 @@ describe('', () => { [lighthouseApiRef, new LighthouseRestApi('http://lighthouse')], [errorApiRef, mockErrorApi], ]); - mockFetch.mockResponse(JSON.stringify(entityWebsite)); + (useWebsiteForEntity as jest.Mock).mockReturnValue({ value: entityWebsite, loading: false, diff --git a/plugins/lighthouse/src/components/AuditList/AuditListTable.test.tsx b/plugins/lighthouse/src/components/AuditList/AuditListTable.test.tsx index e67f939ba1..5c67fec10a 100644 --- a/plugins/lighthouse/src/components/AuditList/AuditListTable.test.tsx +++ b/plugins/lighthouse/src/components/AuditList/AuditListTable.test.tsx @@ -16,7 +16,7 @@ import React from 'react'; import { render } from '@testing-library/react'; -import { wrapInTestApp } from '@backstage/test-utils'; +import { wrapInTestApp, msw } from '@backstage/test-utils'; import { ApiRegistry, ApiProvider } from '@backstage/core'; import AuditListTable from './AuditListTable'; @@ -26,7 +26,7 @@ import { LighthouseRestApi, } from '../../api'; import { formatTime } from '../../utils'; -import mockFetch from 'jest-fetch-mock'; +import { setupServer } from 'msw/node'; import * as data from '../../__fixtures__/website-list-response.json'; @@ -35,11 +35,13 @@ const websiteListResponse = data as WebsiteListResponse; describe('AuditListTable', () => { let apis: ApiRegistry; + const server = setupServer(); + msw.setupDefaultHandlers(server); + beforeEach(() => { apis = ApiRegistry.from([ [lighthouseApiRef, new LighthouseRestApi('http://lighthouse')], ]); - mockFetch.mockResponse(JSON.stringify(websiteListResponse)); }); const auditList = (websiteList: WebsiteListResponse) => { diff --git a/plugins/lighthouse/src/components/AuditList/index.test.tsx b/plugins/lighthouse/src/components/AuditList/index.test.tsx index 34fd760801..5fdc4781ce 100644 --- a/plugins/lighthouse/src/components/AuditList/index.test.tsx +++ b/plugins/lighthouse/src/components/AuditList/index.test.tsx @@ -24,10 +24,9 @@ jest.mock('react-router-dom', () => { }); import React from 'react'; -import mockFetch from 'jest-fetch-mock'; import { render, fireEvent } from '@testing-library/react'; import { ApiRegistry, ApiProvider } from '@backstage/core'; -import { wrapInTestApp } from '@backstage/test-utils'; +import { wrapInTestApp, msw } from '@backstage/test-utils'; import { lighthouseApiRef, @@ -40,18 +39,23 @@ import * as data from '../../__fixtures__/website-list-response.json'; const { useNavigate } = jest.requireMock('react-router-dom'); const websiteListResponse = data as WebsiteListResponse; +import { rest } from 'msw'; +import { setupServer } from 'msw/node'; describe('AuditList', () => { let apis: ApiRegistry; + const server = setupServer(); + msw.setupDefaultHandlers(server); + beforeEach(() => { apis = ApiRegistry.from([ [lighthouseApiRef, new LighthouseRestApi('http://lighthouse')], ]); - mockFetch.mockResponse(JSON.stringify(websiteListResponse)); }); it('should render the table', async () => { + server.use(rest.get('*', (_req, res, ctx) => res(ctx.json(data)))); const rendered = render( wrapInTestApp( @@ -76,22 +80,6 @@ describe('AuditList', () => { }); describe('pagination', () => { - it('requests the correct limit and offset from the api based on the query', () => { - mockFetch.mockClear(); - render( - wrapInTestApp( - - - , - { routeEntries: ['?page=2'] }, - ), - ); - expect(mockFetch).toHaveBeenLastCalledWith( - 'http://lighthouse/v1/websites?limit=10&offset=10', - undefined, - ); - }); - describe('when only one page is needed', () => { it('hides pagination elements', () => { const rendered = render( @@ -111,7 +99,8 @@ describe('AuditList', () => { response.limit = 5; response.offset = 5; response.total = 7; - mockFetch.mockResponseOnce(JSON.stringify(response)); + server.use(rest.get('*', (_req, res, ctx) => res(ctx.json(response)))); + server.use(rest.post('*', (_req, res, ctx) => res(ctx.json(response)))); }); it('shows pagination elements', async () => { @@ -146,7 +135,7 @@ describe('AuditList', () => { describe('when waiting on the request', () => { it('should render the loader', async () => { - mockFetch.mockResponseOnce(() => new Promise(() => {})); + server.use(rest.get('*', (_req, res, ctx) => res(ctx.delay(20000)))); const rendered = render( wrapInTestApp( @@ -161,7 +150,11 @@ describe('AuditList', () => { describe('when the audits fail', () => { it('should render an error', async () => { - mockFetch.mockRejectOnce(new Error('failed to fetch')); + server.use( + rest.get('*', (_req, res, ctx) => + res(ctx.status(500, 'something broke')), + ), + ); const rendered = render( wrapInTestApp( diff --git a/plugins/lighthouse/src/components/AuditList/index.tsx b/plugins/lighthouse/src/components/AuditList/index.tsx index a75bb25a0d..c6411a9baa 100644 --- a/plugins/lighthouse/src/components/AuditList/index.tsx +++ b/plugins/lighthouse/src/components/AuditList/index.tsx @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import React, { useState, useMemo, FC, ReactNode } from 'react'; import { useLocalStorage, useAsync } from 'react-use'; import { useNavigate } from 'react-router-dom'; @@ -28,7 +27,6 @@ import { ContentHeader, HeaderLabel, Progress, - pageTheme, useApi, } from '@backstage/core'; @@ -95,7 +93,7 @@ const AuditList: FC<{}> = () => { } return ( - +
= () => { - {content} + {content} diff --git a/plugins/lighthouse/src/components/AuditView/index.test.tsx b/plugins/lighthouse/src/components/AuditView/index.test.tsx index 742be67fed..df223150bc 100644 --- a/plugins/lighthouse/src/components/AuditView/index.test.tsx +++ b/plugins/lighthouse/src/components/AuditView/index.test.tsx @@ -27,29 +27,36 @@ jest.mock('react-router-dom', () => { }); import React from 'react'; -import mockFetch from 'jest-fetch-mock'; -import { render, fireEvent } from '@testing-library/react'; -import { wrapInTestApp } from '@backstage/test-utils'; +import { render } from '@testing-library/react'; +import { wrapInTestApp, msw } from '@backstage/test-utils'; import { ApiRegistry, ApiProvider } from '@backstage/core'; - import AuditView from '.'; import { lighthouseApiRef, LighthouseRestApi, Audit, Website } from '../../api'; import { formatTime } from '../../utils'; import * as data from '../../__fixtures__/website-response.json'; -import { act } from 'react-dom/test-utils'; + +import { setupServer } from 'msw/node'; +import { rest } from 'msw'; const { useParams }: { useParams: jest.Mock } = jest.requireMock( 'react-router-dom', ); const websiteResponse = data as Website; -const { useNavigate } = jest.requireMock('react-router-dom'); describe('AuditView', () => { let apis: ApiRegistry; let id: string; + const server = setupServer(); + msw.setupDefaultHandlers(server); + beforeEach(() => { - mockFetch.mockResponse(JSON.stringify(websiteResponse)); + server.use( + rest.get('https://lighthouse/*', async (_req, res, ctx) => + res(ctx.json(websiteResponse)), + ), + ); + apis = ApiRegistry.from([ [lighthouseApiRef, new LighthouseRestApi('https://lighthouse')], ]); @@ -74,27 +81,6 @@ describe('AuditView', () => { expect(iframe).toHaveAttribute('src', `https://lighthouse/v1/audits/${id}`); }); - it('renders a button to click to create a new audit for this website', async () => { - const rendered = render( - wrapInTestApp( - - - , - ), - ); - - const button = await rendered.findByText('Create New Audit'); - expect(button).toBeInTheDocument(); - - act(() => { - fireEvent.click(button); - }); - - expect(useNavigate()).toHaveBeenCalledWith( - `../../create-audit?url=${encodeURIComponent('https://spotify.com')}`, - ); - }); - describe('sidebar', () => { it('renders a list of all audits for the website', async () => { const rendered = render( @@ -163,8 +149,8 @@ describe('AuditView', () => { }); describe('when the request for the website by id is pending', () => { - it('it shows the loading', async () => { - mockFetch.mockImplementationOnce(() => new Promise(() => {})); + it('shows the loading', async () => { + server.use(rest.get('*', (_req, res, ctx) => res(ctx.delay(20000)))); const rendered = render( wrapInTestApp( @@ -177,8 +163,12 @@ describe('AuditView', () => { }); describe('when the request for the website by id fails', () => { - it('it shows an error', async () => { - mockFetch.mockRejectOnce(new Error('failed to fetch')); + it('shows an error', async () => { + server.use( + rest.get('*', (_req, res, ctx) => + res(ctx.status(500), ctx.body('failed to fetch')), + ), + ); const rendered = render( wrapInTestApp( @@ -186,7 +176,7 @@ describe('AuditView', () => { , ), ); - expect(await rendered.findByText('failed to fetch')).toBeInTheDocument(); + expect(await rendered.findByText(/failed to fetch/)).toBeInTheDocument(); }); }); diff --git a/plugins/lighthouse/src/components/AuditView/index.tsx b/plugins/lighthouse/src/components/AuditView/index.tsx index 54bd179418..ac38a329f1 100644 --- a/plugins/lighthouse/src/components/AuditView/index.tsx +++ b/plugins/lighthouse/src/components/AuditView/index.tsx @@ -34,7 +34,6 @@ import { import Alert from '@material-ui/lab/Alert'; import { useApi, - pageTheme, InfoCard, Header, Page, @@ -193,7 +192,7 @@ export const AuditViewContent: FC<{}> = () => { }; const ConnectedAuditView = () => ( - +
diff --git a/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.tsx b/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.tsx index d3bc362877..3f7020cba5 100644 --- a/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.tsx +++ b/plugins/lighthouse/src/components/Cards/LastLighthouseAuditCard.tsx @@ -88,9 +88,10 @@ const LighthouseAuditSummary: FC<{ audit: Audit; dense?: boolean }> = ({ return ; }; -export const LastLighthouseAuditCard: FC<{ dense?: boolean }> = ({ - dense = false, -}) => { +export const LastLighthouseAuditCard: FC<{ + dense?: boolean; + variant?: string; +}> = ({ dense = false, variant }) => { const { value: website, loading, error } = useWebsiteForEntity(); let content; @@ -105,5 +106,9 @@ export const LastLighthouseAuditCard: FC<{ dense?: boolean }> = ({ ); } - return {content}; + return ( + + {content} + + ); }; diff --git a/plugins/lighthouse/src/components/CreateAudit/index.test.tsx b/plugins/lighthouse/src/components/CreateAudit/index.test.tsx index b2348bf5ff..96829926b5 100644 --- a/plugins/lighthouse/src/components/CreateAudit/index.test.tsx +++ b/plugins/lighthouse/src/components/CreateAudit/index.test.tsx @@ -24,20 +24,22 @@ jest.mock('react-router-dom', () => { }); import React from 'react'; -import mockFetch from 'jest-fetch-mock'; -import { wait, render, fireEvent } from '@testing-library/react'; +import { waitFor, render, fireEvent } from '@testing-library/react'; import { ApiRegistry, ApiProvider, ErrorApi, errorApiRef, } from '@backstage/core'; -import { wrapInTestApp } from '@backstage/test-utils'; +import { wrapInTestApp, msw } from '@backstage/test-utils'; import { lighthouseApiRef, LighthouseRestApi, Audit } from '../../api'; import CreateAudit from '.'; import * as data from '../../__fixtures__/create-audit-response.json'; +import { setupServer } from 'msw/node'; +import { rest } from 'msw'; + const { useNavigate }: { useNavigate: jest.Mock } = jest.requireMock( 'react-router-dom', ); @@ -47,6 +49,8 @@ const createAuditResponse = data as Audit; describe('CreateAudit', () => { let apis: ApiRegistry; let errorApi: ErrorApi; + const server = setupServer(); + msw.setupDefaultHandlers(server); beforeEach(() => { errorApi = { post: jest.fn(), error$: jest.fn() }; @@ -88,7 +92,7 @@ describe('CreateAudit', () => { describe('when waiting on the request', () => { it('disables the form fields', () => { - mockFetch.mockResponseOnce(() => new Promise(() => {})); + server.use(rest.get('*', (_req, res, ctx) => res(ctx.delay(20000)))); const rendered = render( wrapInTestApp( @@ -111,7 +115,11 @@ describe('CreateAudit', () => { describe('when the audit is successfully created', () => { it('triggers a location change to the table', async () => { useNavigate.mockClear(); - mockFetch.mockResponseOnce(JSON.stringify(createAuditResponse)); + server.use( + rest.post('http://lighthouse/v1/audits', (_req, res, ctx) => + res(ctx.json(createAuditResponse)), + ), + ); const rendered = render( wrapInTestApp( @@ -126,14 +134,7 @@ describe('CreateAudit', () => { }); fireEvent.click(rendered.getByText(/Create Audit/)); - expect(mockFetch).toHaveBeenCalledWith( - 'http://lighthouse/v1/audits', - expect.objectContaining({ - method: 'POST', - }), - ); - - await wait(() => expect(rendered.getByLabelText(/URL/)).toBeEnabled()); + await waitFor(() => expect(rendered.getByLabelText(/URL/)).toBeEnabled()); expect(useNavigate()).toHaveBeenCalledWith('..'); }); @@ -141,9 +142,11 @@ describe('CreateAudit', () => { describe('when the audits fail', () => { it('should render an error', async () => { - (errorApi.post as jest.Mock).mockClear(); - mockFetch.mockRejectOnce(new Error('failed to post')); - + server.use( + rest.post('http://lighthouse/v1/audits', (_req, res, ctx) => + res(ctx.status(500, 'failed to post')), + ), + ); const rendered = render( wrapInTestApp( @@ -157,8 +160,7 @@ describe('CreateAudit', () => { }); fireEvent.click(rendered.getByText(/Create Audit/)); - await wait(() => expect(rendered.getByLabelText(/URL/)).toBeEnabled()); - await new Promise(r => setTimeout(r, 0)); + await waitFor(() => expect(rendered.getByLabelText(/URL/)).toBeEnabled()); expect(errorApi.post).toHaveBeenCalledWith(expect.any(Error)); }); diff --git a/plugins/lighthouse/src/components/CreateAudit/index.tsx b/plugins/lighthouse/src/components/CreateAudit/index.tsx index ad46b06020..55800d79ec 100644 --- a/plugins/lighthouse/src/components/CreateAudit/index.tsx +++ b/plugins/lighthouse/src/components/CreateAudit/index.tsx @@ -30,7 +30,6 @@ import { InfoCard, Header, Page, - pageTheme, Content, ContentHeader, HeaderLabel, @@ -43,6 +42,9 @@ import LighthouseSupportButton from '../SupportButton'; const useStyles = makeStyles(theme => ({ input: { minWidth: 300, + [theme.breakpoints.down('xs')]: { + minWidth: '100%', + }, }, buttonList: { marginLeft: theme.spacing(-1), @@ -50,6 +52,14 @@ const useStyles = makeStyles(theme => ({ '& > *': { margin: theme.spacing(1), }, + [theme.breakpoints.down('xs')]: { + marginLeft: 0, + marginRight: 0, + flexDirection: 'column', + '& > *': { + width: '100%', + }, + }, }, })); @@ -170,7 +180,7 @@ export const CreateAuditContent: FC<{}> = () => { }; const CreateAudit = () => ( - +
diff --git a/plugins/lighthouse/src/hooks/useWebsiteForEntity.test.tsx b/plugins/lighthouse/src/hooks/useWebsiteForEntity.test.tsx index 868e26f04c..580162f182 100644 --- a/plugins/lighthouse/src/hooks/useWebsiteForEntity.test.tsx +++ b/plugins/lighthouse/src/hooks/useWebsiteForEntity.test.tsx @@ -75,7 +75,7 @@ describe('useWebsiteForEntity', () => { (mockLighthouseApi.getWebsiteByUrl as jest.Mock).mockResolvedValue(website); }); - it('returns the lighthouse information for the website url in annotations ', async () => { + it('returns the lighthouse information for the website url in annotations', async () => { const { result, waitForNextUpdate } = subject(); await waitForNextUpdate(); expect(result.current?.value).toBe(website); diff --git a/plugins/lighthouse/src/setupTests.ts b/plugins/lighthouse/src/setupTests.ts index 8553642152..aea2220869 100644 --- a/plugins/lighthouse/src/setupTests.ts +++ b/plugins/lighthouse/src/setupTests.ts @@ -15,5 +15,4 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); +import 'cross-fetch/polyfill'; diff --git a/plugins/newrelic/README.md b/plugins/newrelic/README.md index 19bd24950c..e14acedef2 100644 --- a/plugins/newrelic/README.md +++ b/plugins/newrelic/README.md @@ -7,16 +7,38 @@ Website: [https://newrelic.com](https://newrelic.com) ## Getting Started -Add New Relic REST API Key to `app-config.yaml` +This plugin uses the Backstage proxy to securely communicate with New Relic's +APIs. Add the following to your `app-config.yaml` to enable this configuration: ```yaml -newrelic: - api: - baseUrl: 'https://api.newrelic.com/v2' - key: +proxy: + '/newrelic/apm/api': + target: https://api.newrelic.com/v2 + headers: + X-Api-Key: + $env: NEW_RELIC_REST_API_KEY ``` -New Relic Plugin Path: [/newrelic](http://localhost:3000/newrelic) +In your production deployment of Backstage, you would also need to ensure that +you've set the `NEW_RELIC_REST_API_KEY` environment variable before starting +the backend. + +While working locally, you may wish to hard-code your API key in your +`app-config.local.yaml` like this: + +```yaml +# app-config.local.yaml +proxy: + '/newrelic/apm/api': + headers: + X-Api-Key: NRRA-YourActualApiKey +``` + +Read more about how to find or generate this key in +[New Relic's Documentation](https://docs.newrelic.com/docs/apis/get-started/intro-apis/types-new-relic-api-keys#rest-api-key). + +See if it's working by visiting the New Relic Plugin Path: +[/newrelic](http://localhost:3000/newrelic) ## Features diff --git a/plugins/newrelic/package.json b/plugins/newrelic/package.json index 603d01d62b..b9a12cc648 100644 --- a/plugins/newrelic/package.json +++ b/plugins/newrelic/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-newrelic", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,8 +21,8 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -31,16 +31,16 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/newrelic/src/api/index.ts b/plugins/newrelic/src/api/index.ts new file mode 100644 index 0000000000..d76a87875c --- /dev/null +++ b/plugins/newrelic/src/api/index.ts @@ -0,0 +1,110 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createApiRef, DiscoveryApi } from '@backstage/core'; + +export type NewRelicApplication = { + id: number; + application_summary: NewRelicApplicationSummary; + name: string; + language: string; + health_status: string; + reporting: boolean; + settings: NewRelicApplicationSettings; + links?: NewRelicApplicationLinks; +}; + +export type NewRelicApplicationSummary = { + apdex_score: number; + error_rate: number; + host_count: number; + instance_count: number; + response_time: number; + throughput: number; +}; + +export type NewRelicApplicationSettings = { + app_apdex_threshold: number; + end_user_apdex_threshold: number; + enable_real_user_monitoring: boolean; + use_server_side_config: boolean; +}; + +export type NewRelicApplicationLinks = { + application_instances: Array; + servers: Array; + application_hosts: Array; +}; + +export type NewRelicApplications = { + applications: NewRelicApplication[]; +}; + +export const newRelicApiRef = createApiRef({ + id: 'plugin.newrelic.service', + description: 'Used by the NewRelic plugin to make requests', +}); + +const DEFAULT_PROXY_PATH_BASE = '/newrelic'; + +type Options = { + discoveryApi: DiscoveryApi; + /** + * Path to use for requests via the proxy, defaults to /newrelic + */ + proxyPathBase?: string; +}; + +export interface NewRelicApi { + getApplications(): Promise; +} + +export class NewRelicClient implements NewRelicApi { + private readonly discoveryApi: DiscoveryApi; + private readonly proxyPathBase: string; + + constructor(options: Options) { + this.discoveryApi = options.discoveryApi; + this.proxyPathBase = options.proxyPathBase ?? DEFAULT_PROXY_PATH_BASE; + } + + async getApplications(): Promise { + const url = await this.getApiUrl('apm', 'applications.json'); + const response = await fetch(url); + let responseJson; + + try { + responseJson = await response.json(); + } catch (e) { + responseJson = { applications: [] }; + } + + if (response.status !== 200) { + throw new Error( + `Error communicating with New Relic: ${ + responseJson?.error?.title || response.statusText + }`, + ); + } + + return responseJson; + } + + private async getApiUrl(product: string, path: string) { + const proxyUrl = await this.discoveryApi.getBaseUrl('proxy'); + return `${proxyUrl}${this.proxyPathBase}/${product}/api/${path}`; + } +} diff --git a/plugins/newrelic/src/components/NewRelicComponent/NewRelicComponent.tsx b/plugins/newrelic/src/components/NewRelicComponent/NewRelicComponent.tsx index 94d5c530a1..81e28a8c80 100644 --- a/plugins/newrelic/src/components/NewRelicComponent/NewRelicComponent.tsx +++ b/plugins/newrelic/src/components/NewRelicComponent/NewRelicComponent.tsx @@ -19,7 +19,6 @@ import { Grid } from '@material-ui/core'; import { Header, Page, - pageTheme, Content, ContentHeader, HeaderLabel, @@ -28,7 +27,7 @@ import { import NewRelicFetchComponent from '../NewRelicFetchComponent'; const NewRelicComponent: FC<{}> = () => ( - +
diff --git a/plugins/newrelic/src/components/NewRelicFetchComponent/NewRelicFetchComponent.tsx b/plugins/newrelic/src/components/NewRelicFetchComponent/NewRelicFetchComponent.tsx index 9b3791e062..62f52e7875 100644 --- a/plugins/newrelic/src/components/NewRelicFetchComponent/NewRelicFetchComponent.tsx +++ b/plugins/newrelic/src/components/NewRelicFetchComponent/NewRelicFetchComponent.tsx @@ -15,52 +15,10 @@ */ import React, { FC } from 'react'; -import { - configApiRef, - Progress, - Table, - TableColumn, - useApi, -} from '@backstage/core'; +import { Progress, Table, TableColumn, useApi } from '@backstage/core'; import Alert from '@material-ui/lab/Alert'; import { useAsync } from 'react-use'; - -type NewRelicApplication = { - id: number; - application_summary: NewRelicApplicationSummary; - name: string; - language: string; - health_status: string; - reporting: boolean; - settings: NewRelicApplicationSettings; - links?: NewRelicApplicationLinks; -}; - -type NewRelicApplicationSummary = { - apdex_score: number; - error_rate: number; - host_count: number; - instance_count: number; - response_time: number; - throughput: number; -}; - -type NewRelicApplicationSettings = { - app_apdex_threshold: number; - end_user_apdex_threshold: number; - enable_real_user_monitoring: boolean; - use_server_side_config: boolean; -}; - -type NewRelicApplicationLinks = { - application_instances: Array; - servers: Array; - application_hosts: Array; -}; - -type NewRelicApplications = { - applications: NewRelicApplication[]; -}; +import { newRelicApiRef, NewRelicApplications } from '../../api'; export const NewRelicAPMTable: FC = ({ applications, @@ -73,7 +31,7 @@ export const NewRelicAPMTable: FC = ({ { title: 'Instance Count', field: 'instanceCount' }, { title: 'Apdex', field: 'apdexScore' }, ]; - const data = applications.map((app: NewRelicApplication) => { + const data = applications.map(app => { const { name, application_summary: applicationSummary } = app; const { response_time: responseTime, @@ -104,20 +62,11 @@ export const NewRelicAPMTable: FC = ({ }; const NewRelicFetchComponent: FC<{}> = () => { - const configApi = useApi(configApiRef); - const apiBaseUrl = configApi.getString('newrelic.api.baseUrl'); - const apiKey = configApi.getString('newrelic.api.key'); + const api = useApi(newRelicApiRef); - const { value, loading, error } = useAsync(async (): Promise< - NewRelicApplication[] - > => { - const response = await fetch(`${apiBaseUrl}/applications.json`, { - headers: { - 'X-Api-Key': apiKey, - }, - }); - const data: NewRelicApplications = await response.json(); - return data.applications.filter((application: NewRelicApplication) => { + const { value, loading, error } = useAsync(async () => { + const data = await api.getApplications(); + return data.applications.filter(application => { return application.hasOwnProperty('application_summary'); }); }, []); diff --git a/plugins/newrelic/src/plugin.ts b/plugins/newrelic/src/plugin.ts index 21aac69e8f..5f5ba88617 100644 --- a/plugins/newrelic/src/plugin.ts +++ b/plugins/newrelic/src/plugin.ts @@ -14,7 +14,13 @@ * limitations under the License. */ -import { createPlugin, createRouteRef } from '@backstage/core'; +import { + createApiFactory, + createPlugin, + createRouteRef, + discoveryApiRef, +} from '@backstage/core'; +import { NewRelicClient, newRelicApiRef } from './api'; import NewRelicComponent from './components/NewRelicComponent'; export const rootRouteRef = createRouteRef({ @@ -24,6 +30,13 @@ export const rootRouteRef = createRouteRef({ export const plugin = createPlugin({ id: 'newrelic', + apis: [ + createApiFactory({ + api: newRelicApiRef, + deps: { discoveryApi: discoveryApiRef }, + factory: ({ discoveryApi }) => new NewRelicClient({ discoveryApi }), + }), + ], register({ router }) { router.addRoute(rootRouteRef, NewRelicComponent); }, diff --git a/plugins/newrelic/src/setupTests.ts b/plugins/newrelic/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/newrelic/src/setupTests.ts +++ b/plugins/newrelic/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/proxy-backend/package.json b/plugins/proxy-backend/package.json index 723c3e395e..fcb68dcd78 100644 --- a/plugins/proxy-backend/package.json +++ b/plugins/proxy-backend/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-proxy-backend", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -19,28 +19,25 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", + "@backstage/backend-common": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", "@types/express": "^4.17.6", - "@types/http-proxy-middleware": "^0.19.3", "express": "^4.17.1", "express-promise-router": "^3.0.3", "http-proxy-middleware": "^0.19.1", "morgan": "^1.10.0", - "node-fetch": "^2.6.0", "uuid": "^8.0.0", "winston": "^3.2.1", "yaml": "^1.9.2", "yn": "^4.0.0", - "yup": "^0.29.1" + "yup": "^0.29.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@types/node-fetch": "^2.5.7", + "@backstage/cli": "^0.1.1-alpha.26", + "@types/http-proxy-middleware": "^0.19.3", "@types/supertest": "^2.0.8", "@types/uuid": "^8.0.0", - "@types/yup": "^0.28.2", - "jest-fetch-mock": "^3.0.3", + "@types/yup": "^0.29.8", "supertest": "^4.0.2" }, "files": [ diff --git a/plugins/proxy-backend/src/index.ts b/plugins/proxy-backend/src/index.ts index 7612c392a2..de2be19b6d 100644 --- a/plugins/proxy-backend/src/index.ts +++ b/plugins/proxy-backend/src/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './service/router'; +export * from './service'; diff --git a/plugins/cost-insights/src/components/CostOverviewChart/index.ts b/plugins/proxy-backend/src/service/index.ts similarity index 92% rename from plugins/cost-insights/src/components/CostOverviewChart/index.ts rename to plugins/proxy-backend/src/service/index.ts index 21f345a282..38fbb697c4 100644 --- a/plugins/cost-insights/src/components/CostOverviewChart/index.ts +++ b/plugins/proxy-backend/src/service/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './CostOverviewChart'; +export { createRouter } from './router'; diff --git a/plugins/proxy-backend/src/service/router.test.ts b/plugins/proxy-backend/src/service/router.test.ts index 07737e9ea8..77db35c917 100644 --- a/plugins/proxy-backend/src/service/router.test.ts +++ b/plugins/proxy-backend/src/service/router.test.ts @@ -14,18 +14,34 @@ * limitations under the License. */ -import { createRouter } from './router'; +import { buildMiddleware, createRouter } from './router'; import * as winston from 'winston'; -import { ConfigReader } from '@backstage/config'; import { loadBackendConfig, SingleHostDiscovery, } from '@backstage/backend-common'; +import createProxyMiddleware, { + Config as ProxyMiddlewareConfig, + Proxy, +} from 'http-proxy-middleware'; +import * as http from 'http'; + +jest.mock('http-proxy-middleware', () => { + return jest.fn().mockImplementation( + (): Proxy => { + return () => undefined; + }, + ); +}); + +const mockCreateProxyMiddleware = createProxyMiddleware as jest.MockedFunction< + typeof createProxyMiddleware +>; describe('createRouter', () => { it('works', async () => { const logger = winston.createLogger(); - const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const config = await loadBackendConfig({ logger, argv: [] }); const discovery = SingleHostDiscovery.fromConfig(config); const router = await createRouter({ config, @@ -35,3 +51,151 @@ describe('createRouter', () => { expect(router).toBeDefined(); }); }); + +describe('buildMiddleware', () => { + const logger = winston.createLogger(); + + beforeEach(() => { + mockCreateProxyMiddleware.mockClear(); + }); + + it('accepts strings', async () => { + buildMiddleware('/api/', logger, 'test', 'http://mocked'); + + expect(createProxyMiddleware).toHaveBeenCalledTimes(1); + + const [filter, fullConfig] = mockCreateProxyMiddleware.mock.calls[0] as [ + (pathname: string, req: Partial) => boolean, + ProxyMiddlewareConfig, + ]; + expect(filter('', { method: 'GET' })).toBe(true); + expect(filter('', { method: 'POST' })).toBe(true); + expect(filter('', { method: 'PUT' })).toBe(true); + expect(filter('', { method: 'PATCH' })).toBe(true); + expect(filter('', { method: 'DELETE' })).toBe(true); + + expect(fullConfig.pathRewrite).toEqual({ '^/api/test/': '/' }); + expect(fullConfig.changeOrigin).toBe(true); + expect(fullConfig.logProvider!(logger)).toBe(logger); + }); + + it('limits allowedMethods', async () => { + buildMiddleware('/api/', logger, 'test', { + target: 'http://mocked', + allowedMethods: ['GET', 'DELETE'], + }); + + expect(createProxyMiddleware).toHaveBeenCalledTimes(1); + + const [filter, fullConfig] = mockCreateProxyMiddleware.mock.calls[0] as [ + (pathname: string, req: Partial) => boolean, + ProxyMiddlewareConfig, + ]; + expect(filter('', { method: 'GET' })).toBe(true); + expect(filter('', { method: 'POST' })).toBe(false); + expect(filter('', { method: 'PUT' })).toBe(false); + expect(filter('', { method: 'PATCH' })).toBe(false); + expect(filter('', { method: 'DELETE' })).toBe(true); + + expect(fullConfig.pathRewrite).toEqual({ '^/api/test/': '/' }); + expect(fullConfig.changeOrigin).toBe(true); + expect(fullConfig.logProvider!(logger)).toBe(logger); + }); + + it('permits default headers', async () => { + buildMiddleware('/api/', logger, 'test', { + target: 'http://mocked', + }); + + expect(createProxyMiddleware).toHaveBeenCalledTimes(1); + + const config = mockCreateProxyMiddleware.mock + .calls[0][1] as ProxyMiddlewareConfig; + + const testClientRequest = { + getHeaderNames: () => [ + 'cache-control', + 'content-language', + 'content-length', + 'content-type', + 'expires', + 'last-modified', + 'pragma', + 'host', + 'accept', + 'accept-language', + 'user-agent', + 'cookie', + ], + removeHeader: jest.fn(), + } as Partial; + + expect(config).toBeDefined(); + expect(config.onProxyReq).toBeDefined(); + + config.onProxyReq!( + testClientRequest as http.ClientRequest, + {} as http.IncomingMessage, + {} as http.ServerResponse, + ); + + expect(testClientRequest.removeHeader).toHaveBeenCalledTimes(1); + expect(testClientRequest.removeHeader).toHaveBeenCalledWith('cookie'); + }); + + it('permits default and configured headers', async () => { + buildMiddleware('/api/', logger, 'test', { + target: 'http://mocked', + headers: { + Authorization: 'my-token', + }, + }); + + expect(createProxyMiddleware).toHaveBeenCalledTimes(1); + + const config = mockCreateProxyMiddleware.mock + .calls[0][1] as ProxyMiddlewareConfig; + + const testClientRequest = { + getHeaderNames: () => ['authorization', 'Cookie'], + removeHeader: jest.fn(), + } as Partial; + + config.onProxyReq!( + testClientRequest as http.ClientRequest, + {} as http.IncomingMessage, + {} as http.ServerResponse, + ); + + expect(testClientRequest.removeHeader).toHaveBeenCalledTimes(1); + expect(testClientRequest.removeHeader).toHaveBeenCalledWith('Cookie'); + }); + + it('permits configured headers', async () => { + buildMiddleware('/api/', logger, 'test', { + target: 'http://mocked', + allowedHeaders: ['authorization', 'cookie'], + }); + + expect(createProxyMiddleware).toHaveBeenCalledTimes(1); + + const config = mockCreateProxyMiddleware.mock + .calls[0][1] as ProxyMiddlewareConfig; + + const testClientRequest = { + getHeaderNames: () => ['authorization', 'Cookie', 'X-Auth-Request-User'], + removeHeader: jest.fn(), + } as Partial; + + config.onProxyReq!( + testClientRequest as http.ClientRequest, + {} as http.IncomingMessage, + {} as http.ServerResponse, + ); + + expect(testClientRequest.removeHeader).toHaveBeenCalledTimes(1); + expect(testClientRequest.removeHeader).toHaveBeenCalledWith( + 'X-Auth-Request-User', + ); + }); +}); diff --git a/plugins/proxy-backend/src/service/router.ts b/plugins/proxy-backend/src/service/router.ts index 8cec31719c..75eab029b5 100644 --- a/plugins/proxy-backend/src/service/router.ts +++ b/plugins/proxy-backend/src/service/router.ts @@ -25,6 +25,27 @@ import { Logger } from 'winston'; import http from 'http'; import { PluginEndpointDiscovery } from '@backstage/backend-common'; +// A list of headers that are always forwarded to the proxy targets. +const safeForwardHeaders = [ + // https://fetch.spec.whatwg.org/#cors-safelisted-request-header + 'cache-control', + 'content-language', + 'content-length', + 'content-type', + 'expires', + 'last-modified', + 'pragma', + + // host is overridden by default. if changeOrigin is configured to false, + // we assume this is a intentional and should also be forwarded. + 'host', + + // other headers that we assume to be ok + 'accept', + 'accept-language', + 'user-agent', +]; + export interface RouterOptions { logger: Logger; config: Config; @@ -33,11 +54,12 @@ export interface RouterOptions { export interface ProxyConfig extends ProxyMiddlewareConfig { allowedMethods?: string[]; + allowedHeaders?: string[]; } // Creates a proxy middleware, possibly with defaults added on top of the // given config. -function buildMiddleware( +export function buildMiddleware( pathPrefix: string, logger: Logger, route: string, @@ -68,6 +90,30 @@ function buildMiddleware( return fullConfig?.allowedMethods?.includes(req.method!) ?? true; }; + // Only forward the allowed HTTP headers to not forward unwanted secret headers + const headerAllowList = new Set( + [ + // allow all safe headers + ...safeForwardHeaders, + + // allow all headers that are set by the proxy + ...((fullConfig.headers && Object.keys(fullConfig.headers)) || []), + + // allow all configured headers + ...(fullConfig.allowedHeaders || []), + ].map(h => h.toLocaleLowerCase()), + ); + + fullConfig.onProxyReq = (proxyReq: http.ClientRequest) => { + const headerNames = proxyReq.getHeaderNames(); + + headerNames.forEach(h => { + if (!headerAllowList.has(h.toLocaleLowerCase())) { + proxyReq.removeHeader(h); + } + }); + }; + return createProxyMiddleware(filter, fullConfig); } diff --git a/plugins/proxy-backend/src/service/standaloneServer.ts b/plugins/proxy-backend/src/service/standaloneServer.ts index 83980729d8..c64d69e2a4 100644 --- a/plugins/proxy-backend/src/service/standaloneServer.ts +++ b/plugins/proxy-backend/src/service/standaloneServer.ts @@ -22,7 +22,6 @@ import { import { Server } from 'http'; import { Logger } from 'winston'; import { createRouter } from './router'; -import { ConfigReader } from '@backstage/config'; export interface ServerOptions { port: number; @@ -37,7 +36,7 @@ export async function startStandaloneServer( logger.debug('Creating application...'); - const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const config = await loadBackendConfig({ logger, argv: process.argv }); const discovery = SingleHostDiscovery.fromConfig(config); const router = await createRouter({ config, diff --git a/plugins/proxy-backend/src/setupTests.ts b/plugins/proxy-backend/src/setupTests.ts index f7b6ca962d..ba33cf996b 100644 --- a/plugins/proxy-backend/src/setupTests.ts +++ b/plugins/proxy-backend/src/setupTests.ts @@ -14,6 +14,4 @@ * limitations under the License. */ -require('jest-fetch-mock').enableMocks(); - export {}; diff --git a/plugins/register-component/package.json b/plugins/register-component/package.json index 9dbd598dee..5c3f985b4d 100644 --- a/plugins/register-component/package.json +++ b/plugins/register-component/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-register-component", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,10 +21,10 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -36,16 +36,16 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/register-component/src/components/RegisterComponentForm/RegisterComponentForm.test.tsx b/plugins/register-component/src/components/RegisterComponentForm/RegisterComponentForm.test.tsx index 10c3d9fcd1..875b1f8660 100644 --- a/plugins/register-component/src/components/RegisterComponentForm/RegisterComponentForm.test.tsx +++ b/plugins/register-component/src/components/RegisterComponentForm/RegisterComponentForm.test.tsx @@ -30,7 +30,7 @@ describe('RegisterComponentForm', () => { expect(screen.getByText('Submit').closest('button')).toBeDisabled(); }); - it('should enable a submit button when the target url is set ', async () => { + it('should enable a submit button when the target url is set', async () => { render(); await act(async () => { diff --git a/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx b/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx index 933b67060a..cd3eb1adbb 100644 --- a/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx +++ b/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx @@ -19,7 +19,6 @@ import { Grid, makeStyles } from '@material-ui/core'; import { InfoCard, Page, - pageTheme, Content, useApi, errorApiRef, @@ -113,7 +112,7 @@ export const RegisterComponentPage = ({ }; return ( - +
diff --git a/plugins/register-component/src/setupTests.ts b/plugins/register-component/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/register-component/src/setupTests.ts +++ b/plugins/register-component/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/rollbar-backend/package.json b/plugins/rollbar-backend/package.json index cda105a73f..cb553d859b 100644 --- a/plugins/rollbar-backend/package.json +++ b/plugins/rollbar-backend/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-rollbar-backend", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,8 +20,8 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", + "@backstage/backend-common": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", "@types/express": "^4.17.6", "axios": "^0.20.0", "camelcase-keys": "^6.2.2", @@ -37,9 +37,8 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", "@types/supertest": "^2.0.8", - "jest-fetch-mock": "^3.0.3", "supertest": "^4.0.2" }, "files": [ diff --git a/plugins/rollbar-backend/src/service/standaloneServer.ts b/plugins/rollbar-backend/src/service/standaloneServer.ts index a96d30d836..b30bf6fc6b 100644 --- a/plugins/rollbar-backend/src/service/standaloneServer.ts +++ b/plugins/rollbar-backend/src/service/standaloneServer.ts @@ -20,7 +20,6 @@ import { createServiceBuilder, loadBackendConfig, } from '@backstage/backend-common'; -import { ConfigReader } from '@backstage/config'; import { createRouter } from './router'; export interface ServerOptions { @@ -33,7 +32,7 @@ export async function startStandaloneServer( options: ServerOptions, ): Promise { const logger = options.logger.child({ service: 'rollbar-backend' }); - const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const config = await loadBackendConfig({ logger, argv: process.argv }); logger.debug('Creating application...'); diff --git a/plugins/rollbar-backend/src/setupTests.ts b/plugins/rollbar-backend/src/setupTests.ts index f7b6ca962d..ba33cf996b 100644 --- a/plugins/rollbar-backend/src/setupTests.ts +++ b/plugins/rollbar-backend/src/setupTests.ts @@ -14,6 +14,4 @@ * limitations under the License. */ -require('jest-fetch-mock').enableMocks(); - export {}; diff --git a/plugins/rollbar/package.json b/plugins/rollbar/package.json index ba690fde64..27421cfd4d 100644 --- a/plugins/rollbar/package.json +++ b/plugins/rollbar/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-rollbar", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,10 +21,10 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -37,9 +37,9 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/react-hooks": "^3.3.0", @@ -47,9 +47,8 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/react": "^16.9", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/rollbar/src/components/RollbarHome/RollbarHome.tsx b/plugins/rollbar/src/components/RollbarHome/RollbarHome.tsx index d09c2054b1..fe99e70575 100644 --- a/plugins/rollbar/src/components/RollbarHome/RollbarHome.tsx +++ b/plugins/rollbar/src/components/RollbarHome/RollbarHome.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import { Content, Header, Page, pageTheme } from '@backstage/core'; +import { Content, Header, Page } from '@backstage/core'; import { RollbarProjectTable } from '../RollbarProjectTable/RollbarProjectTable'; import { useRollbarEntities } from '../../hooks/useRollbarEntities'; @@ -23,7 +23,7 @@ export const RollbarHome = () => { const { entities, loading, error } = useRollbarEntities(); return ( - +
{ const { entity } = useCatalogEntity(); return ( - +
diff --git a/plugins/rollbar/src/components/Router.tsx b/plugins/rollbar/src/components/Router.tsx index 192ef33a61..f0756cb02a 100644 --- a/plugins/rollbar/src/components/Router.tsx +++ b/plugins/rollbar/src/components/Router.tsx @@ -17,7 +17,7 @@ import React from 'react'; import { Routes, Route } from 'react-router'; import { Entity } from '@backstage/catalog-model'; -import { WarningPanel } from '@backstage/core'; +import { MissingAnnotationEmptyState } from '@backstage/core'; import { catalogRouteRef } from '../routes'; import { ROLLBAR_ANNOTATION } from '../constants'; import { EntityPageRollbar } from './EntityPageRollbar/EntityPageRollbar'; @@ -31,9 +31,7 @@ type Props = { export const Router = ({ entity }: Props) => !isPluginApplicableToEntity(entity) ? ( - -
{ROLLBAR_ANNOTATION}
annotation is missing on the entity. -
+ ) : ( { describe('parseLocationAnnotation', () => { @@ -253,4 +257,29 @@ describe('Helpers', () => { }); }); }); + + describe('makeDeprecatedLocationTypeDetector', () => { + it('detects deprecated location types', () => { + const detector = makeDeprecatedLocationTypeDetector( + new ConfigReader({ + integrations: { + github: [{ host: 'derp.com' }, { host: 'foo.com' }], + gitlab: [{ host: 'derp.org' }, { host: 'foo.org' }], + azure: [{ host: 'derp.net' }, { host: 'foo.net' }], + }, + }), + ); + + expect(detector('http://lol:wut@derp.com/wat')).toBe('github'); + expect(detector('https://foo.com/wat')).toBe('github'); + expect(detector('http://derp.org:80/wat')).toBe('gitlab'); + expect(detector('https://foo.org/wat')).toBe('gitlab'); + expect(detector('http://not.derp.net')).toBe(undefined); + expect(detector('http://derp.net')).toBe('azure/api'); + expect(detector('http://derp.net:8080/wat')).toBe('azure/api'); + expect(detector('http://github.com')).toBe('github'); + expect(detector('http://gitlab.com')).toBe('gitlab'); + expect(detector('http://dev.azure.com')).toBe('azure/api'); + }); + }); }); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/helpers.ts b/plugins/scaffolder-backend/src/scaffolder/stages/helpers.ts index 3f31f19d59..e54e796b3b 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/helpers.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/helpers.ts @@ -17,6 +17,7 @@ import { TemplateEntityV1alpha1, LOCATION_ANNOTATION, } from '@backstage/catalog-model'; +import { Config } from '@backstage/config'; import { InputError } from '@backstage/backend-common'; import { RemoteProtocol } from './types'; @@ -54,3 +55,39 @@ export const parseLocationAnnotation = ( location, }; }; + +export type DeprecatedLocationTypeDetector = ( + url: string, +) => string | undefined; + +// The reason for the existence of this is to help in migration to using mostly locations +// of type 'url'. This allows us to detect the deprecated location type based on the host, +// which we in turn can use to select out preparer or publisher. +// +// TODO(Rugvip): This should be removed in the future once we fully migrate to using +// integrations configuration for the scaffolder. +export function makeDeprecatedLocationTypeDetector( + config: Config, +): DeprecatedLocationTypeDetector { + const hostMap = new Map(); + + // These are installed by default by the integrations + hostMap.set('github.com', 'github'); + hostMap.set('gitlab.com', 'gitlab'); + hostMap.set('dev.azure.com', 'azure/api'); + + config.getOptionalConfigArray('integrations.github')?.forEach(sub => { + hostMap.set(sub.getString('host'), 'github'); + }); + config.getOptionalConfigArray('integrations.gitlab')?.forEach(sub => { + hostMap.set(sub.getString('host'), 'gitlab'); + }); + config.getOptionalConfigArray('integrations.azure')?.forEach(sub => { + hostMap.set(sub.getString('host'), 'azure/api'); + }); + + return (url: string): string | undefined => { + const parsed = new URL(url); + return hostMap.get(parsed.hostname); + }; +} diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.test.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.test.ts index 7a7973e981..97f01e6b7d 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.test.ts @@ -19,6 +19,11 @@ const mocks = { CheckoutOptions: jest.fn(() => {}), }; jest.doMock('nodegit', () => mocks); +jest.doMock('fs-extra', () => ({ + promises: { + mkdtemp: jest.fn(dir => `${dir}-static`), + }, +})); import { AzurePreparer } from './azure'; import { @@ -135,4 +140,16 @@ describe('AzurePreparer', () => { /\/template\/test\/1\/2\/3$/, ); }); + + it('return the working directory with the path to the folder if it is specified', async () => { + const preparer = new AzurePreparer(ConfigReader.fromConfigs([])); + mockEntity.spec.path = './template/test/1/2/3'; + const response = await preparer.prepare(mockEntity, { + workingDirectory: '/workDir', + }); + + expect(response).toBe( + '/workDir/graphql-starter-static/template/test/1/2/3', + ); + }); }); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.ts index c2cb97e505..bdcc7e07de 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.ts @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import os from 'os'; import fs from 'fs-extra'; import path from 'path'; -import os from 'os'; import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; import { parseLocationAnnotation } from '../helpers'; import { InputError } from '@backstage/backend-common'; @@ -32,28 +32,28 @@ export class AzurePreparer implements PreparerBase { config.getOptionalString('scaffolder.azure.api.token') ?? ''; } - async prepare(template: TemplateEntityV1alpha1): Promise { + async prepare( + template: TemplateEntityV1alpha1, + opts?: { workingDirectory?: string }, + ): Promise { const { protocol, location } = parseLocationAnnotation(template); + const workingDirectory = opts?.workingDirectory ?? os.tmpdir(); - if (protocol !== 'azure/api') { + if (!['azure/api', 'url'].includes(protocol)) { throw new InputError( - `Wrong location protocol: ${protocol}, should be 'azure/api'`, + `Wrong location protocol: ${protocol}, should be 'url'`, ); } const templateId = template.metadata.name; - const url = new URL(location); // Need to extract filepath from search parameter const parsedGitLocation = GitUriParser(location); const repositoryCheckoutUrl = parsedGitLocation.toString('https'); - const tempDir = await fs.promises.mkdtemp( - path.join(os.tmpdir(), templateId), + path.join(workingDirectory, templateId), ); const templateDirectory = path.join( - `${path - .dirname(url.searchParams.get('path') || '') - .replace(/^\/+/g, '')}`, // Strip leading slash + `${path.dirname(parsedGitLocation.filepath)}`, template.spec.path ?? '.', ); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.test.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.test.ts index b9472fbc8d..d226736efe 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.test.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +import os from 'os'; import fs from 'fs-extra'; import YAML from 'yaml'; import { FilePreparer } from './file'; @@ -42,7 +43,9 @@ const setupTest = async (fixturePath: string) => { }; const filePreparer = new FilePreparer(); - const resultDir = await filePreparer.prepare(template); + const resultDir = await filePreparer.prepare(template, { + workingDirectory: os.tmpdir(), + }); return { filePreparer, template, resultDir }; }; diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.ts index b5ac846cf2..683d0c8cfb 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.ts @@ -13,17 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import os from 'os'; import fs from 'fs-extra'; import path from 'path'; -import os from 'os'; import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; import { parseLocationAnnotation } from '../helpers'; import { InputError } from '@backstage/backend-common'; import { PreparerBase } from './types'; export class FilePreparer implements PreparerBase { - async prepare(template: TemplateEntityV1alpha1): Promise { + async prepare( + template: TemplateEntityV1alpha1, + opts?: { workingDirectory?: string }, + ): Promise { const { protocol, location } = parseLocationAnnotation(template); + const workingDirectory = opts?.workingDirectory ?? os.tmpdir(); if (protocol !== 'file') { throw new InputError( @@ -33,7 +37,7 @@ export class FilePreparer implements PreparerBase { const templateId = template.metadata.name; const tempDir = await fs.promises.mkdtemp( - path.join(os.tmpdir(), templateId), + path.join(workingDirectory, templateId), ); const parentDirectory = path.resolve( diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.test.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.test.ts index 4409d815b5..f251a39d28 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.test.ts @@ -19,6 +19,11 @@ const mocks = { CheckoutOptions: jest.fn(() => {}), }; jest.doMock('nodegit', () => mocks); +jest.doMock('fs-extra', () => ({ + promises: { + mkdtemp: jest.fn(dir => `${dir}-static`), + }, +})); import { GithubPreparer } from './github'; import { @@ -76,7 +81,9 @@ describe('GitHubPreparer', () => { 1, 'https://github.com/benjdlambert/backstage-graphql-template', expect.any(String), - {}, + { + checkoutBranch: 'master', + }, ); }); it('calls the clone command with the correct arguments for a repository when no path is provided', async () => { @@ -87,7 +94,9 @@ describe('GitHubPreparer', () => { 1, 'https://github.com/benjdlambert/backstage-graphql-template', expect.any(String), - {}, + { + checkoutBranch: 'master', + }, ); }); @@ -100,4 +109,34 @@ describe('GitHubPreparer', () => { /\/template\/test\/1\/2\/3$/, ); }); + + it('return the working directory with the path to the folder if it is specified', async () => { + const preparer = new GithubPreparer(); + mockEntity.spec.path = './template/test/1/2/3'; + const response = await preparer.prepare(mockEntity, { + workingDirectory: '/workDir', + }); + + expect(response).toBe( + '/workDir/graphql-starter-static/template/test/1/2/3', + ); + }); + + it('calls the clone command with the token when provided', async () => { + const preparer = new GithubPreparer({ token: 'abc' }); + await preparer.prepare(mockEntity); + expect(mocks.Clone.clone).toHaveBeenNthCalledWith( + 1, + 'https://github.com/benjdlambert/backstage-graphql-template', + expect.any(String), + { + checkoutBranch: 'master', + fetchOpts: { + callbacks: { + credentials: expect.any(Function), + }, + }, + }, + ); + }); }); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.ts index ba4adcabd9..04b0bbcce1 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.ts @@ -13,23 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import os from 'os'; import fs from 'fs-extra'; import path from 'path'; -import os from 'os'; import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; import { parseLocationAnnotation } from '../helpers'; import { InputError } from '@backstage/backend-common'; import { PreparerBase } from './types'; import GitUriParser from 'git-url-parse'; -import { Clone } from 'nodegit'; +import { Clone, CloneOptions, Cred } from 'nodegit'; export class GithubPreparer implements PreparerBase { - async prepare(template: TemplateEntityV1alpha1): Promise { - const { protocol, location } = parseLocationAnnotation(template); + token?: string; - if (protocol !== 'github') { + constructor(params: { token?: string } = {}) { + this.token = params.token; + } + + async prepare( + template: TemplateEntityV1alpha1, + opts?: { workingDirectory?: string }, + ): Promise { + const { protocol, location } = parseLocationAnnotation(template); + const workingDirectory = opts?.workingDirectory ?? os.tmpdir(); + const { token } = this; + + if (!['github', 'url'].includes(protocol)) { throw new InputError( - `Wrong location protocol: ${protocol}, should be 'github'`, + `Wrong location protocol: ${protocol}, should be 'url'`, ); } const templateId = template.metadata.name; @@ -37,7 +48,7 @@ export class GithubPreparer implements PreparerBase { const parsedGitLocation = GitUriParser(location); const repositoryCheckoutUrl = parsedGitLocation.toString('https'); const tempDir = await fs.promises.mkdtemp( - path.join(os.tmpdir(), templateId), + path.join(workingDirectory, templateId), ); const templateDirectory = path.join( @@ -45,9 +56,24 @@ export class GithubPreparer implements PreparerBase { template.spec.path ?? '.', ); - await Clone.clone(repositoryCheckoutUrl, tempDir, { - // TODO(blam): Maybe need some auth here? - }); + let cloneOptions: CloneOptions = { + checkoutBranch: parsedGitLocation.ref, + }; + + if (token) { + cloneOptions = { + ...cloneOptions, + fetchOpts: { + callbacks: { + credentials() { + return Cred.userpassPlaintextNew(token, 'x-oauth-basic'); + }, + }, + }, + }; + } + + await Clone.clone(repositoryCheckoutUrl, tempDir, cloneOptions); return path.resolve(tempDir, templateDirectory); } diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.test.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.test.ts index b25886b027..a229c4f394 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.test.ts @@ -18,6 +18,11 @@ const mocks = { CheckoutOptions: jest.fn(() => {}), }; jest.doMock('nodegit', () => mocks); +jest.doMock('fs-extra', () => ({ + promises: { + mkdtemp: jest.fn(dir => `${dir}-static`), + }, +})); import { GitlabPreparer } from './gitlab'; import { @@ -139,5 +144,17 @@ describe('GitLabPreparer', () => { /\/template\/test\/1\/2\/3$/, ); }); + + it('return the working directory with the path to the folder if it is specified', async () => { + const preparer = new GitlabPreparer(ConfigReader.fromConfigs([])); + mockEntity.spec.path = './template/test/1/2/3'; + const response = await preparer.prepare(mockEntity, { + workingDirectory: '/workDir', + }); + + expect(response).toBe( + '/workDir/graphql-starter-static/template/test/1/2/3', + ); + }); }); }); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.ts index 8efc158a96..4553137c26 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/gitlab.ts @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import os from 'os'; import fs from 'fs-extra'; import path from 'path'; -import os from 'os'; import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; import { parseLocationAnnotation } from '../helpers'; import { InputError } from '@backstage/backend-common'; @@ -33,21 +33,24 @@ export class GitlabPreparer implements PreparerBase { ''; } - async prepare(template: TemplateEntityV1alpha1): Promise { + async prepare( + template: TemplateEntityV1alpha1, + opts?: { workingDirectory?: string }, + ): Promise { const { protocol, location } = parseLocationAnnotation(template); + const workingDirectory = opts?.workingDirectory ?? os.tmpdir(); - if (['gitlab', 'gitlab/api'].indexOf(protocol) < 0) { + if (!['gitlab', 'gitlab/api', 'url'].includes(protocol)) { throw new InputError( - `Wrong location protocol: ${protocol}, should be 'gitlab' or 'gitlab/api'`, + `Wrong location protocol: ${protocol}, should be 'url'`, ); } const templateId = template.metadata.name; const parsedGitLocation = GitUriParser(location); const repositoryCheckoutUrl = parsedGitLocation.toString('https'); - const tempDir = await fs.promises.mkdtemp( - path.join(os.tmpdir(), templateId), + path.join(workingDirectory, templateId), ); const templateDirectory = path.join( diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/preparers.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/preparers.ts index 5efb3ad60d..226f7e3836 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/preparers.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/preparers.ts @@ -14,26 +14,85 @@ * limitations under the License. */ +import { Config } from '@backstage/config'; +import { Logger } from 'winston'; import { PreparerBase, PreparerBuilder } from './types'; import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; -import { parseLocationAnnotation } from '../helpers'; +import { + DeprecatedLocationTypeDetector, + makeDeprecatedLocationTypeDetector, + parseLocationAnnotation, +} from '../helpers'; import { RemoteProtocol } from '../types'; +import { FilePreparer } from './file'; +import { GitlabPreparer } from './gitlab'; +import { AzurePreparer } from './azure'; +import { GithubPreparer } from './github'; export class Preparers implements PreparerBuilder { private preparerMap = new Map(); + constructor(private readonly typeDetector?: DeprecatedLocationTypeDetector) {} + register(protocol: RemoteProtocol, preparer: PreparerBase) { this.preparerMap.set(protocol, preparer); } get(template: TemplateEntityV1alpha1): PreparerBase { - const { protocol } = parseLocationAnnotation(template); + const { protocol, location } = parseLocationAnnotation(template); + const preparer = this.preparerMap.get(protocol); if (!preparer) { + if ((protocol as string) === 'url') { + const type = this.typeDetector?.(location); + const detected = type && this.preparerMap.get(type as RemoteProtocol); + if (detected) { + return detected; + } + throw new Error(`No preparer integration found for url "${location}"`); + } throw new Error(`No preparer registered for type: "${protocol}"`); } return preparer; } + + static async fromConfig( + config: Config, + { logger }: { logger: Logger }, + ): Promise { + const typeDetector = makeDeprecatedLocationTypeDetector(config); + + const preparers = new Preparers(typeDetector); + + const filePreparer = new FilePreparer(); + const gitlabPreparer = new GitlabPreparer(config); + const azurePreparer = new AzurePreparer(config); + + preparers.register('file', filePreparer); + preparers.register('gitlab', gitlabPreparer); + preparers.register('gitlab/api', gitlabPreparer); + preparers.register('azure/api', azurePreparer); + + const githubConfig = config.getOptionalConfig('scaffolder.github'); + if (githubConfig) { + try { + const githubToken = githubConfig.getString('token'); + const githubPreparer = new GithubPreparer({ token: githubToken }); + + preparers.register('github', githubPreparer); + } catch (e) { + if (process.env.NODE_ENV !== 'development') { + throw new Error( + `Failed to initialize github scaffolding provider, ${e.message}`, + ); + } + + logger.warn(`Skipping github scaffolding provider, ${e.message}`); + } + } + + return preparers; + } } diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/types.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/types.ts index c9dd14c0a3..c17edc24a4 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/types.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/types.ts @@ -25,7 +25,7 @@ export type PreparerBase = { */ prepare( template: TemplateEntityV1alpha1, - opts: { logger: Logger }, + opts?: { logger: Logger; workingDirectory?: string }, ): Promise; }; diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/publish/publishers.ts b/plugins/scaffolder-backend/src/scaffolder/stages/publish/publishers.ts index a88acc518d..db383aaf7f 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/publish/publishers.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/publish/publishers.ts @@ -14,26 +14,145 @@ * limitations under the License. */ +import { Logger } from 'winston'; +import { Octokit } from '@octokit/rest'; +import { Gitlab } from '@gitbeaker/node'; +import { getPersonalAccessTokenHandler, WebApi } from 'azure-devops-node-api'; +import { Config } from '@backstage/config'; import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; -import { parseLocationAnnotation } from '../helpers'; +import { + DeprecatedLocationTypeDetector, + makeDeprecatedLocationTypeDetector, + parseLocationAnnotation, +} from '../helpers'; import { PublisherBase, PublisherBuilder } from './types'; import { RemoteProtocol } from '../types'; +import { GithubPublisher, RepoVisibilityOptions } from './github'; +import { GitlabPublisher } from './gitlab'; +import { AzurePublisher } from './azure'; export class Publishers implements PublisherBuilder { private publisherMap = new Map(); + constructor(private readonly typeDetector?: DeprecatedLocationTypeDetector) {} + register(protocol: RemoteProtocol, publisher: PublisherBase) { this.publisherMap.set(protocol, publisher); } get(template: TemplateEntityV1alpha1): PublisherBase { - const { protocol } = parseLocationAnnotation(template); + const { protocol, location } = parseLocationAnnotation(template); const publisher = this.publisherMap.get(protocol); if (!publisher) { + if ((protocol as string) === 'url') { + const type = this.typeDetector?.(location); + const detected = type && this.publisherMap.get(type as RemoteProtocol); + if (detected) { + return detected; + } + throw new Error(`No preparer integration found for url "${location}"`); + } throw new Error(`No publisher registered for type: "${protocol}"`); } return publisher; } + + static async fromConfig( + config: Config, + { logger }: { logger: Logger }, + ): Promise { + const typeDetector = makeDeprecatedLocationTypeDetector(config); + const publishers = new Publishers(typeDetector); + + const githubConfig = config.getOptionalConfig('scaffolder.github'); + if (githubConfig) { + try { + const repoVisibility = githubConfig.getString( + 'visibility', + ) as RepoVisibilityOptions; + + const githubToken = githubConfig.getString('token'); + const githubHost = + githubConfig.getOptionalString('host') ?? 'https://api.github.com'; + const githubClient = new Octokit({ + auth: githubToken, + baseUrl: githubHost, + }); + const githubPublisher = new GithubPublisher({ + client: githubClient, + token: githubToken, + repoVisibility, + }); + + publishers.register('file', githubPublisher); + publishers.register('github', githubPublisher); + } catch (e) { + const providerName = 'github'; + if (process.env.NODE_ENV !== 'development') { + throw new Error( + `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, + ); + } + + logger.warn( + `Skipping ${providerName} scaffolding provider, ${e.message}`, + ); + } + } + + const gitLabConfig = config.getOptionalConfig('scaffolder.gitlab.api'); + if (gitLabConfig) { + try { + const gitLabToken = gitLabConfig.getString('token'); + const gitLabClient = new Gitlab({ + host: gitLabConfig.getOptionalString('baseUrl'), + token: gitLabToken, + }); + const gitLabPublisher = new GitlabPublisher(gitLabClient, gitLabToken); + publishers.register('gitlab', gitLabPublisher); + publishers.register('gitlab/api', gitLabPublisher); + } catch (e) { + const providerName = 'gitlab'; + if (process.env.NODE_ENV !== 'development') { + throw new Error( + `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, + ); + } + + logger.warn( + `Skipping ${providerName} scaffolding provider, ${e.message}`, + ); + } + } + + const azureConfig = config.getOptionalConfig('scaffolder.azure'); + if (azureConfig) { + try { + const baseUrl = azureConfig.getString('baseUrl'); + const azureToken = azureConfig.getConfig('api').getString('token'); + + const authHandler = getPersonalAccessTokenHandler(azureToken); + const webApi = new WebApi(baseUrl, authHandler); + const azureClient = await webApi.getGitApi(); + + const azurePublisher = new AzurePublisher(azureClient, azureToken); + publishers.register('azure/api', azurePublisher); + } catch (e) { + const providerName = 'azure'; + if (process.env.NODE_ENV !== 'development') { + throw new Error( + `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, + ); + } + + logger.warn( + `Skipping ${providerName} scaffolding provider, ${e.message}`, + ); + } + } + + return publishers; + } } diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.test.ts b/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.test.ts index 31bcdf189b..106a448d7c 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.test.ts @@ -13,16 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -jest.mock('./helpers', () => ({ runDockerContainer: jest.fn() })); +jest.mock('./helpers', () => ({ + runDockerContainer: jest.fn(), + runCommand: jest.fn(), +})); +jest.mock('command-exists-promise', () => jest.fn()); import { CookieCutter } from './cookiecutter'; import fs from 'fs-extra'; import os from 'os'; import path from 'path'; -import { RunDockerContainerOptions } from './helpers'; +import { RunDockerContainerOptions, RunCommandOptions } from './helpers'; import { PassThrough } from 'stream'; import Docker from 'dockerode'; +const commandExists = require('command-exists-promise'); + describe('CookieCutter Templater', () => { const cookie = new CookieCutter(); const mockDocker = {} as Docker; @@ -32,6 +38,10 @@ describe('CookieCutter Templater', () => { runDockerContainer: jest.Mock; } = require('./helpers'); + jest + .spyOn(fs, 'readdir') + .mockImplementation(() => Promise.resolve(['newthing'])); + beforeEach(async () => { jest.clearAllMocks(); }); @@ -174,4 +184,71 @@ describe('CookieCutter Templater', () => { dockerClient: mockDocker, }); }); + + describe('when cookiecutter is available', () => { + beforeAll(() => { + commandExists.mockImplementation(() => () => true); + }); + + it('use the binary', async () => { + const { + runCommand, + }: { + runCommand: jest.Mock; + } = require('./helpers'); + + const stream = new PassThrough(); + + const tempdir = await mkTemp(); + + const values = { + owner: 'blobby', + storePath: 'spotify/end-repo', + component_id: 'newthing', + }; + + await cookie.run({ + directory: tempdir, + values, + logStream: stream, + dockerClient: mockDocker, + }); + + expect(runCommand).toHaveBeenCalledWith({ + command: 'cookiecutter', + args: expect.arrayContaining([ + '--no-input', + '-o', + tempdir, + expect.stringContaining(`${tempdir}-result`), + '--verbose', + ]), + logStream: stream, + }); + }); + }); + + describe('when nothing was generated', () => { + beforeEach(() => { + jest.spyOn(fs, 'readdir').mockImplementation(() => Promise.resolve([])); + }); + + it('throws an error', async () => { + const stream = new PassThrough(); + + const tempdir = await mkTemp(); + + return expect( + cookie.run({ + directory: tempdir, + values: { + owner: 'blobby', + storePath: 'spotify/end-repo', + }, + logStream: stream, + dockerClient: mockDocker, + }), + ).rejects.toThrow(/Cookie Cutter did not generate anything/); + }); + }); }); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.ts b/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.ts index 21b6fc3dde..7be8730bd9 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/templater/cookiecutter.ts @@ -78,8 +78,16 @@ export class CookieCutter implements TemplaterBase { }); } + // if cookiecutter was successful, resultDir will contain + // exactly one directory. + const [generated] = await fs.readdir(resultDir); + + if (generated === undefined) { + throw new Error('Cookie Cutter did not generate anything'); + } + return { - resultDir: path.resolve(resultDir, options.values.component_id as string), + resultDir: path.resolve(resultDir, generated), }; } } diff --git a/plugins/scaffolder-backend/src/service/router.test.ts b/plugins/scaffolder-backend/src/service/router.test.ts index 35d6b50ece..fae7ee8beb 100644 --- a/plugins/scaffolder-backend/src/service/router.test.ts +++ b/plugins/scaffolder-backend/src/service/router.test.ts @@ -14,7 +14,19 @@ * limitations under the License. */ +const mockAccess = jest.fn(); +jest.doMock('fs-extra', () => ({ + promises: { + access: mockAccess, + }, + constants: { + F_OK: 0, + W_OK: 1, + }, +})); + import { getVoidLogger } from '@backstage/backend-common'; +import { ConfigReader } from '@backstage/config'; import express from 'express'; import request from 'supertest'; import { createRouter } from './router'; @@ -23,6 +35,106 @@ import Docker from 'dockerode'; jest.mock('dockerode'); +describe('createRouter - working directory', () => { + const mockPrepare = jest.fn(); + const mockPreparers = new Preparers(); + + beforeAll(() => { + const mockPreparer = { + prepare: mockPrepare, + }; + mockPreparers.register('azure/api', mockPreparer); + }); + + beforeEach(() => { + jest.resetAllMocks(); + }); + + const workDirConfig = (path: string) => ({ + context: '', + data: { + backend: { + workingDirectory: path, + }, + }, + }); + + const template = { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Template', + metadata: { + annotations: { + 'backstage.io/managed-by-location': 'azure/api:dev.azure.com', + }, + }, + spec: { + owner: 'template@backstage.io', + path: '.', + schema: {}, + }, + }; + + it('should throw an error when working directory does not exist or is not writable', async () => { + mockAccess.mockImplementation(() => { + throw new Error('access error'); + }); + + await expect( + createRouter({ + logger: getVoidLogger(), + preparers: new Preparers(), + templaters: new Templaters(), + publishers: new Publishers(), + config: ConfigReader.fromConfigs([workDirConfig('/path')]), + dockerClient: new Docker(), + }), + ).rejects.toThrow('access error'); + }); + + it('should use the working directory when configured', async () => { + const router = await createRouter({ + logger: getVoidLogger(), + preparers: mockPreparers, + templaters: new Templaters(), + publishers: new Publishers(), + config: ConfigReader.fromConfigs([workDirConfig('/path')]), + dockerClient: new Docker(), + }); + + const app = express().use(router); + await request(app).post('/v1/jobs').send({ + template, + values: {}, + }); + + expect(mockPrepare).toBeCalledWith(expect.anything(), { + logger: expect.anything(), + workingDirectory: '/path', + }); + }); + + it('should not pass along anything when no working directory is configured', async () => { + const router = await createRouter({ + logger: getVoidLogger(), + preparers: mockPreparers, + templaters: new Templaters(), + publishers: new Publishers(), + config: ConfigReader.fromConfigs([]), + dockerClient: new Docker(), + }); + + const app = express().use(router); + await request(app).post('/v1/jobs').send({ + template, + values: {}, + }); + + expect(mockPrepare).toBeCalledWith(expect.anything(), { + logger: expect.anything(), + }); + }); +}); + describe('createRouter', () => { let app: express.Express; @@ -32,6 +144,7 @@ describe('createRouter', () => { preparers: new Preparers(), templaters: new Templaters(), publishers: new Publishers(), + config: ConfigReader.fromConfigs([]), dockerClient: new Docker(), }); app = express().use(router); diff --git a/plugins/scaffolder-backend/src/service/router.ts b/plugins/scaffolder-backend/src/service/router.ts index f61d2566b9..fb40489622 100644 --- a/plugins/scaffolder-backend/src/service/router.ts +++ b/plugins/scaffolder-backend/src/service/router.ts @@ -15,7 +15,8 @@ */ import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; -import { JsonValue } from '@backstage/config'; +import { Config, JsonValue } from '@backstage/config'; +import fs from 'fs-extra'; import Docker from 'dockerode'; import express from 'express'; import Router from 'express-promise-router'; @@ -36,6 +37,7 @@ export interface RouterOptions { publishers: PublisherBuilder; logger: Logger; + config: Config; dockerClient: Docker; } @@ -50,12 +52,33 @@ export async function createRouter( templaters, publishers, logger: parentLogger, + config, dockerClient, } = options; const logger = parentLogger.child({ plugin: 'scaffolder' }); const jobProcessor = new JobProcessor(); + let workingDirectory: string; + if (config.has('backend.workingDirectory')) { + workingDirectory = config.getString('backend.workingDirectory'); + try { + // Check if working directory exists and is writable + await fs.promises.access( + workingDirectory, + fs.constants.F_OK | fs.constants.W_OK, + ); + logger.info(`using working directory: ${workingDirectory}`); + } catch (err) { + logger.error( + `working directory ${workingDirectory} ${ + err.code === 'ENOENT' ? 'does not exist' : 'is not writable' + }`, + ); + throw err; + } + } + router .get('/v1/job/:jobId', ({ params }, res) => { const job = jobProcessor.get(params.jobId); @@ -104,6 +127,7 @@ export async function createRouter( const preparer = preparers.get(ctx.entity); const skeletonDir = await preparer.prepare(ctx.entity, { logger: ctx.logger, + workingDirectory, }); return { skeletonDir }; }, diff --git a/plugins/scaffolder/package.json b/plugins/scaffolder/package.json index 1e59019ad7..751f4075b2 100644 --- a/plugins/scaffolder/package.json +++ b/plugins/scaffolder/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-scaffolder", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,15 +21,15 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", - "@rjsf/core": "^2.1.0", - "@rjsf/material-ui": "^2.1.0", + "@rjsf/core": "^2.4.0", + "@rjsf/material-ui": "^2.4.0", "classnames": "^2.2.6", "moment": "^2.26.0", "react": "^16.13.1", @@ -41,17 +41,16 @@ "swr": "^0.3.0" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/scaffolder/src/components/JobStage/JobStage.tsx b/plugins/scaffolder/src/components/JobStage/JobStage.tsx index 0baba0c9b9..5128a761ec 100644 --- a/plugins/scaffolder/src/components/JobStage/JobStage.tsx +++ b/plugins/scaffolder/src/components/JobStage/JobStage.tsx @@ -125,7 +125,9 @@ export const JobStage = ({ endedAt, startedAt, name, log, status }: Props) => { {log.length === 0 ? ( - No logs available for this step + + No logs available for this step + ) : ( }>
diff --git a/plugins/scaffolder/src/components/ScaffolderPage/ScaffolderPage.tsx b/plugins/scaffolder/src/components/ScaffolderPage/ScaffolderPage.tsx index b5bdaaef4a..d0cb25f254 100644 --- a/plugins/scaffolder/src/components/ScaffolderPage/ScaffolderPage.tsx +++ b/plugins/scaffolder/src/components/ScaffolderPage/ScaffolderPage.tsx @@ -22,7 +22,6 @@ import { Header, Lifecycle, Page, - pageTheme, Progress, SupportButton, useApi, @@ -66,7 +65,7 @@ export const ScaffolderPage = () => { }, [error, errorApi]); return ( - +
({ padding: theme.spacing(2, 2, 6), backgroundImage: (props: { backgroundImage: string }) => props.backgroundImage, + backgroundPosition: 0, }, content: { padding: theme.spacing(2), @@ -55,7 +63,10 @@ export const TemplateCard = ({ type, name, }: TemplateCardProps) => { - const theme = pageTheme[type] ?? pageTheme.other; + const backstageTheme = useTheme(); + + const themeId = pageTheme[type] ? type : 'other'; + const theme = backstageTheme.getPageTheme({ themeId }); const classes = useStyles({ backgroundImage: theme.backgroundImage }); const href = generatePath(templateRoute.path, { templateName: name }); diff --git a/plugins/scaffolder/src/components/TemplatePage/TemplatePage.tsx b/plugins/scaffolder/src/components/TemplatePage/TemplatePage.tsx index 4ead44ab99..ccbdff9aba 100644 --- a/plugins/scaffolder/src/components/TemplatePage/TemplatePage.tsx +++ b/plugins/scaffolder/src/components/TemplatePage/TemplatePage.tsx @@ -22,7 +22,6 @@ import { Lifecycle, Page, useApi, - pageTheme, } from '@backstage/core'; import { catalogApiRef } from '@backstage/plugin-catalog'; import { LinearProgress } from '@material-ui/core'; @@ -148,7 +147,7 @@ export const TemplatePage = () => { } return ( - +
{ const projectId = entity.metadata.annotations?.[SENTRY_ANNOTATION]; if (!projectId) { - return ( - -
{SENTRY_ANNOTATION}
annotation is missing on the entity. -
- ); + return ; } return ( diff --git a/plugins/sentry/src/components/SentryPluginPage/SentryPluginPage.test.tsx b/plugins/sentry/src/components/SentryPluginPage/SentryPluginPage.test.tsx index d508ddf7c2..21c21ce385 100644 --- a/plugins/sentry/src/components/SentryPluginPage/SentryPluginPage.test.tsx +++ b/plugins/sentry/src/components/SentryPluginPage/SentryPluginPage.test.tsx @@ -16,10 +16,13 @@ import React from 'react'; import { render } from '@testing-library/react'; -import mockFetch from 'jest-fetch-mock'; import SentryPluginPage from './SentryPluginPage'; import { ThemeProvider } from '@material-ui/core'; import { lightTheme } from '@backstage/theme'; +import { msw } from '@backstage/test-utils'; +import { setupServer } from 'msw/node'; +import { rest } from 'msw'; + import { ApiProvider, ApiRegistry, @@ -31,8 +34,11 @@ const errorApi = { post: () => {} }; const ConfigApi = { getString: () => 'test' }; describe('SentryPluginPage', () => { + const server = setupServer(); + msw.setupDefaultHandlers(server); + it('should render header and time switched', () => { - mockFetch.mockResponse('{}'); + server.use(rest.get('/', (_req, res, ctx) => res(ctx.json({})))); const rendered = render( = () => { const sentryProjectId = 'sample-sentry-project-id'; return ( - +
diff --git a/plugins/sentry/src/setupTests.ts b/plugins/sentry/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/sentry/src/setupTests.ts +++ b/plugins/sentry/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/tech-radar/package.json b/plugins/tech-radar/package.json index d6067ba3e2..f27f4c1784 100644 --- a/plugins/tech-radar/package.json +++ b/plugins/tech-radar/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-tech-radar", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -21,9 +21,9 @@ "start": "backstage-cli plugin:serve" }, "dependencies": { - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -35,8 +35,9 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", @@ -45,9 +46,8 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/react": "^16.9", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/tech-radar/src/components/RadarComponent.test.tsx b/plugins/tech-radar/src/components/RadarComponent.test.tsx index 5591d74b82..59cababbc9 100644 --- a/plugins/tech-radar/src/components/RadarComponent.test.tsx +++ b/plugins/tech-radar/src/components/RadarComponent.test.tsx @@ -19,6 +19,7 @@ import { render, waitForElement } from '@testing-library/react'; import { ThemeProvider } from '@material-ui/core'; import { lightTheme } from '@backstage/theme'; import { ApiRegistry, ApiProvider, errorApiRef } from '@backstage/core'; +import { act } from 'react-dom/test-utils'; import { withLogCollector } from '@backstage/test-utils'; import GetBBoxPolyfill from '../utils/polyfills/getBBox'; @@ -34,8 +35,9 @@ describe('RadarComponent', () => { }); it('should render a progress bar', async () => { - const errorApi = { post: () => {} }; + jest.useFakeTimers(); + const errorApi = { post: () => {} }; const { getByTestId, queryByTestId } = render( @@ -48,9 +50,13 @@ describe('RadarComponent', () => { , ); + act(() => { + jest.advanceTimersByTime(250); + }); expect(getByTestId('progress')).toBeInTheDocument(); await waitForElement(() => queryByTestId('tech-radar-svg')); + jest.useRealTimers(); }); it('should call the errorApi if load fails', async () => { diff --git a/plugins/tech-radar/src/components/RadarPage.test.tsx b/plugins/tech-radar/src/components/RadarPage.test.tsx index 97fae16380..ee5cf8e131 100644 --- a/plugins/tech-radar/src/components/RadarPage.test.tsx +++ b/plugins/tech-radar/src/components/RadarPage.test.tsx @@ -22,6 +22,7 @@ import { ApiRegistry, ApiProvider, errorApiRef } from '@backstage/core'; import GetBBoxPolyfill from '../utils/polyfills/getBBox'; import { RadarPage } from './RadarPage'; +import { act } from 'react-dom/test-utils'; import { MockErrorApi, wrapInTestApp } from '@backstage/test-utils'; describe('RadarPage', () => { @@ -34,6 +35,8 @@ describe('RadarPage', () => { }); it('should render a progress bar', async () => { + jest.useFakeTimers(); + const techRadarProps = { width: 1200, height: 800, @@ -48,9 +51,13 @@ describe('RadarPage', () => { ), ); + act(() => { + jest.advanceTimersByTime(250); + }); expect(getByTestId('progress')).toBeInTheDocument(); await waitForElement(() => queryByTestId('tech-radar-svg')); + jest.useRealTimers(); }); it('should render a header with a svg', async () => { diff --git a/plugins/tech-radar/src/components/RadarPage.tsx b/plugins/tech-radar/src/components/RadarPage.tsx index 519c9afeee..779d1fa088 100644 --- a/plugins/tech-radar/src/components/RadarPage.tsx +++ b/plugins/tech-radar/src/components/RadarPage.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import { Grid } from '@material-ui/core'; +import { Grid, makeStyles } from '@material-ui/core'; import { Content, ContentHeader, @@ -23,11 +23,16 @@ import { Header, HeaderLabel, SupportButton, - pageTheme, } from '@backstage/core'; import RadarComponent from '../components/RadarComponent'; import { TechRadarComponentProps } from '../api'; +const useStyles = makeStyles(() => ({ + overflowXScroll: { + overflowX: 'scroll', + }, +})); + export type TechRadarPageProps = TechRadarComponentProps & { title?: string; subtitle?: string; @@ -39,28 +44,31 @@ export const RadarPage = ({ subtitle, pageTitle, ...props -}: TechRadarPageProps): JSX.Element => ( - -
- - -
- - - - This is used for visualizing the official guidelines of different - areas of software development such as languages, frameworks, - infrastructure and processes. - - - - - +}: TechRadarPageProps): JSX.Element => { + const classes = useStyles(); + return ( + +
+ + +
+ + + + This is used for visualizing the official guidelines of different + areas of software development such as languages, frameworks, + infrastructure and processes. + + + + + + -
-
-
-); +
+ + ); +}; RadarPage.defaultProps = { title: 'Tech Radar', diff --git a/plugins/tech-radar/src/setupTests.ts b/plugins/tech-radar/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/tech-radar/src/setupTests.ts +++ b/plugins/tech-radar/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/techdocs-backend/package.json b/plugins/techdocs-backend/package.json index 75f6071464..5bdc7ba282 100644 --- a/plugins/techdocs-backend/package.json +++ b/plugins/techdocs-backend/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-techdocs-backend", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,26 +20,24 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.1.1-alpha.24", - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/config": "^0.1.1-alpha.24", + "@backstage/backend-common": "^0.1.1-alpha.26", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/config": "^0.1.1-alpha.26", "@types/dockerode": "^2.5.34", "@types/express": "^4.17.6", "command-exists-promise": "^2.0.2", - "default-branch": "^1.0.8", + "cross-fetch": "^3.0.6", "dockerode": "^3.2.1", "express": "^4.17.1", "express-promise-router": "^3.0.3", "fs-extra": "^9.0.1", - "git-url-parse": "^11.2.0", + "git-url-parse": "^11.4.0", "knex": "^0.21.1", - "node-fetch": "^2.6.0", "nodegit": "^0.27.0", "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@types/node-fetch": "^2.5.7", + "@backstage/cli": "^0.1.1-alpha.26", "supertest": "^4.0.2" }, "files": [ diff --git a/plugins/techdocs-backend/src/default-branch.ts b/plugins/techdocs-backend/src/default-branch.ts index 05a8f666ce..1090fcb3d3 100644 --- a/plugins/techdocs-backend/src/default-branch.ts +++ b/plugins/techdocs-backend/src/default-branch.ts @@ -13,10 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import fetch, { RequestInit } from 'node-fetch'; +import fetch from 'cross-fetch'; import parseGitUrl from 'git-url-parse'; -import { ConfigReader, Config } from '@backstage/config'; -import { loadBackendConfig } from '@backstage/backend-common'; +import { Config } from '@backstage/config'; +import { getRootLogger, loadBackendConfig } from '@backstage/backend-common'; +import { + getAzureHostToken, + getGitHost, + getGithubHostToken, + getGitlabHostToken, + getGitRepoType, +} from './git-auth'; interface IGitlabBranch { name: string; @@ -42,9 +49,17 @@ interface IGitlabBranch { }; } -function getGithubApiUrl(url: string): URL { +function getGithubApiUrl(config: Config, url: string): URL { const { protocol, owner, name } = parseGitUrl(url); - const apiBaseUrl = 'api.github.com'; + const providerConfigs = + config.getOptionalConfigArray('integrations.github') ?? []; + + // TODO: Maybe we need to filter by host in the array, not sure about GHE + const targetProviderConfig = providerConfigs[0]; + + const apiBaseUrl = + targetProviderConfig?.getOptionalString('integrations.github.apiBaseUrl') ?? + 'api.github.com'; const apiRepos = 'repos'; return new URL(`${protocol}://${apiBaseUrl}/${apiRepos}/${owner}/${name}`); @@ -61,15 +76,22 @@ function getGitlabApiUrl(url: string): URL { ); } -function getGithubRequestOptions(config: Config): RequestInit { +function getAzureApiUrl(url: string): URL { + const { protocol, resource, organization, owner, name } = parseGitUrl(url); + const apiRepoPath = '_apis/git/repositories'; + const apiVersion = 'api-version=6.0'; + + return new URL( + `${protocol}://${resource}/${organization}/${owner}/${apiRepoPath}/${name}?${apiVersion}`, + ); +} + +function getGithubRequestOptions(config: Config, host: string): RequestInit { const headers: HeadersInit = { Accept: 'application/vnd.github.v3.raw', }; - const token = - config.getOptionalString('catalog.processors.github.privateToken') ?? - config.getOptionalString('catalog.processors.githubApi.privateToken') ?? - process.env.GITHUB_PRIVATE_TOKEN; + const token = getGithubHostToken(config, host); if (token) { headers.Authorization = `token ${token}`; @@ -80,16 +102,12 @@ function getGithubRequestOptions(config: Config): RequestInit { }; } -function getGitlabRequestOptions(config: Config): RequestInit { +function getGitlabRequestOptions(config: Config, host: string): RequestInit { const headers: HeadersInit = { 'PRIVATE-TOKEN': '', }; - const token = - config.getOptionalString('catalog.processors.gitlab.privateToken') ?? - config.getOptionalString('catalog.processors.gitlabApi.privateToken') ?? - process.env.GITLAB_ACCESS_TOKEN; - + const token = getGitlabHostToken(config, host); if (token) { headers['PRIVATE-TOKEN'] = token; } @@ -99,12 +117,31 @@ function getGitlabRequestOptions(config: Config): RequestInit { }; } +function getAzureRequestOptions(config: Config, host: string): RequestInit { + const headers: HeadersInit = {}; + + const token = getAzureHostToken(config, host); + + if (token !== '') { + headers.Authorization = `Basic ${Buffer.from(`:${token}`, 'utf8').toString( + 'base64', + )}`; + } + + const requestOptions: RequestInit = { + headers, + }; + + return requestOptions; +} + async function getGithubDefaultBranch( repositoryUrl: string, config: Config, ): Promise { - const path = getGithubApiUrl(repositoryUrl).toString(); - const options = getGithubRequestOptions(config); + const path = getGithubApiUrl(config, repositoryUrl).toString(); + const host = getGitHost(repositoryUrl); + const options = getGithubRequestOptions(config, host); try { const raw = await fetch(path, options); @@ -133,7 +170,8 @@ async function getGitlabDefaultBranch( ): Promise { const path = getGitlabApiUrl(repositoryUrl).toString(); - const options = getGitlabRequestOptions(config); + const gitlabHost = getGitHost(repositoryUrl); + const options = getGitlabRequestOptions(config, gitlabHost); try { const raw = await fetch(path, options); @@ -159,17 +197,51 @@ async function getGitlabDefaultBranch( } } +async function getAzureDefaultBranch( + repositoryUrl: string, + config: Config, +): Promise { + const path = getAzureApiUrl(repositoryUrl).toString(); + const host = getGitHost(repositoryUrl); + const options = getAzureRequestOptions(config, host); + + try { + const urlResponse = await fetch(path, options); + if (!urlResponse.ok) { + throw new Error( + `Failed to load url: ${urlResponse.status} ${urlResponse.statusText}. Make sure you have permission to repository: ${repositoryUrl}`, + ); + } + const urlResult = await urlResponse.json(); + + const idResponse = await fetch(urlResult.url, options); + if (!idResponse.ok) { + throw new Error( + `Failed to load url: ${idResponse.status} ${idResponse.statusText}. Make sure you have permission to repository: ${urlResult.repository.url}`, + ); + } + const idResult = await idResponse.json(); + const name = idResult.defaultBranch; + + if (!name) { + throw new Error('Not found Azure DevOps default branch'); + } + + return name; + } catch (error) { + throw new Error(`Failed to get Azure DevOps default branch: ${error}`); + } +} + export const getDefaultBranch = async ( repositoryUrl: string, ): Promise => { - const config = ConfigReader.fromConfigs(await loadBackendConfig()); - const typeMapping = [ - { url: /github*/g, type: 'github' }, - { url: /gitlab*/g, type: 'gitlab' }, - ]; - - const type = typeMapping.filter(item => item.url.test(repositoryUrl))[0] - ?.type; + // TODO(Rugvip): Config should not be loaded here, pass it in instead + const config = await loadBackendConfig({ + logger: getRootLogger(), + argv: process.argv, + }); + const type = getGitRepoType(repositoryUrl); try { switch (type) { @@ -177,6 +249,8 @@ export const getDefaultBranch = async ( return await getGithubDefaultBranch(repositoryUrl, config); case 'gitlab': return await getGitlabDefaultBranch(repositoryUrl, config); + case 'azure/api': + return await getAzureDefaultBranch(repositoryUrl, config); default: throw new Error('Failed to get repository type'); diff --git a/plugins/techdocs-backend/src/git-auth.ts b/plugins/techdocs-backend/src/git-auth.ts new file mode 100644 index 0000000000..b580a6f05b --- /dev/null +++ b/plugins/techdocs-backend/src/git-auth.ts @@ -0,0 +1,120 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import parseGitUrl from 'git-url-parse'; +import { Config } from '@backstage/config'; +import { getRootLogger, loadBackendConfig } from '@backstage/backend-common'; + +export function getGitHost(url: string): string { + const { resource } = parseGitUrl(url); + return resource; +} + +export function getGitRepoType(url: string): string { + const typeMapping = [ + { url: /github*/g, type: 'github' }, + { url: /gitlab*/g, type: 'gitlab' }, + { url: /azure*/g, type: 'azure/api' }, + ]; + + const type = typeMapping.filter(item => item.url.test(url))[0]?.type; + + return type; +} + +export function getGithubHostToken( + config: Config, + host: string, +): string | undefined { + const providerConfigs = + config.getOptionalConfigArray('integrations.github') ?? []; + + const hostConfig = providerConfigs.filter( + providerConfig => providerConfig.getOptionalString('host') === host, + ); + const token = + hostConfig[0]?.getOptionalString('token') ?? + config.getOptionalString('catalog.processors.github.privateToken') ?? + config.getOptionalString('catalog.processors.githubApi.privateToken') ?? + process.env.GITHUB_TOKEN; + + return token; +} + +export function getGitlabHostToken( + config: Config, + host: string, +): string | undefined { + const providerConfigs = + config.getOptionalConfigArray('integrations.gitlab') ?? []; + + const hostConfig = providerConfigs.filter( + providerConfig => providerConfig.getOptionalString('host') === host, + ); + const token = + hostConfig[0]?.getOptionalString('token') ?? + config.getOptionalString('catalog.processors.gitlab.privateToken') ?? + config.getOptionalString('catalog.processors.gitlabApi.privateToken') ?? + process.env.GITLAB_TOKEN; + + return token; +} + +export function getAzureHostToken( + config: Config, + host: string, +): string | undefined { + const providerConfigs = + config.getOptionalConfigArray('integrations.azure') ?? []; + + const hostConfig = providerConfigs.filter( + providerConfig => providerConfig.getOptionalString('host') === host, + ); + const token = + hostConfig[0]?.getOptionalString('token') ?? + config.getOptionalString('catalog.processors.azureApi.privateToken') ?? + process.env.AZURE_TOKEN; + + return token; +} + +export const getTokenForGitRepo = async ( + repositoryUrl: string, +): Promise => { + // TODO(Rugvip): Config should not be loaded here, pass it in instead + const config = await loadBackendConfig({ + logger: getRootLogger(), + argv: process.argv, + }); + + const host = getGitHost(repositoryUrl); + const type = getGitRepoType(repositoryUrl); + + try { + switch (type) { + case 'github': + return getGithubHostToken(config, host); + case 'gitlab': + return getGitlabHostToken(config, host); + case 'azure/api': + return getAzureHostToken(config, host); + + default: + throw new Error('Failed to get repository type'); + } + } catch (error) { + throw error; + } +}; diff --git a/plugins/techdocs-backend/src/helpers.ts b/plugins/techdocs-backend/src/helpers.ts index d6a275f183..4cbf46516f 100644 --- a/plugins/techdocs-backend/src/helpers.ts +++ b/plugins/techdocs-backend/src/helpers.ts @@ -20,6 +20,7 @@ import parseGitUrl from 'git-url-parse'; import NodeGit, { Clone, Repository } from 'nodegit'; import fs from 'fs-extra'; import { getDefaultBranch } from './default-branch'; +import { getGitRepoType, getTokenForGitRepo } from './git-auth'; import { Entity } from '@backstage/catalog-model'; import { InputError } from '@backstage/backend-common'; import { RemoteProtocol } from './techdocs/stages/prepare/types'; @@ -76,6 +77,7 @@ export const getLocationForEntity = ( switch (type) { case 'github': case 'gitlab': + case 'azure/api': return { type, target }; case 'dir': if (path.isAbsolute(target)) return { type, target }; @@ -119,16 +121,7 @@ export const checkoutGitRepository = async ( ): Promise => { const parsedGitLocation = parseGitUrl(repoUrl); const repositoryTmpPath = await getGitRepositoryTempFolder(repoUrl); - - // TODO: Should propably not be hardcoded names of env variables, but seems too hard to access config down here - const user = - process.env.GITHUB_PRIVATE_TOKEN_USER || - process.env.GITLAB_PRIVATE_TOKEN_USER || - ''; - const token = - process.env.GITHUB_PRIVATE_TOKEN || - process.env.GITLAB_PRIVATE_TOKEN_USER || - ''; + const token = await getTokenForGitRepo(repoUrl); if (fs.existsSync(repositoryTmpPath)) { try { @@ -150,8 +143,10 @@ export const checkoutGitRepository = async ( } } - if (user && token) { - parsedGitLocation.token = `${user}:${token}`; + if (token) { + const type = getGitRepoType(repoUrl); + const auth = type === 'github' ? `${token}:x-oauth-basic` : `:${token}`; + parsedGitLocation.token = auth; } const repositoryCheckoutUrl = parsedGitLocation.toString('https'); diff --git a/plugins/techdocs-backend/src/service/helpers.ts b/plugins/techdocs-backend/src/service/helpers.ts index 1b8e130ec0..b308dc28af 100644 --- a/plugins/techdocs-backend/src/service/helpers.ts +++ b/plugins/techdocs-backend/src/service/helpers.ts @@ -66,22 +66,16 @@ export class DocsBuilder { } public async build() { - this.logger.info( - `[TechDocs] Running preparer on entity ${getEntityId(this.entity)}`, - ); + this.logger.info(`Running preparer on entity ${getEntityId(this.entity)}`); const preparedDir = await this.preparer.prepare(this.entity); - this.logger.info( - `[TechDocs] Running generator on entity ${getEntityId(this.entity)}`, - ); + this.logger.info(`Running generator on entity ${getEntityId(this.entity)}`); const { resultDir } = await this.generator.run({ directory: preparedDir, dockerClient: this.dockerClient, }); - this.logger.info( - `[TechDocs] Running publisher on entity ${getEntityId(this.entity)}`, - ); + this.logger.info(`Running publisher on entity ${getEntityId(this.entity)}`); await this.publisher.publish({ entity: this.entity, directory: resultDir, @@ -117,16 +111,14 @@ export class DocsBuilder { // Check if documentation source is newer than what we have if (storageTimeStamp && storageTimeStamp >= lastCommit) { this.logger.debug( - `[TechDocs] Docs for entity ${getEntityId( - this.entity, - )} is up to date.`, + `Docs for entity ${getEntityId(this.entity)} is up to date.`, ); return true; } } this.logger.debug( - `[TechDocs] Docs for entity ${getEntityId(this.entity)} was outdated.`, + `Docs for entity ${getEntityId(this.entity)} was outdated.`, ); return false; } diff --git a/plugins/techdocs-backend/src/service/metadata.ts b/plugins/techdocs-backend/src/service/metadata.ts index 671fcdda17..760180f8d2 100644 --- a/plugins/techdocs-backend/src/service/metadata.ts +++ b/plugins/techdocs-backend/src/service/metadata.ts @@ -1,4 +1,3 @@ -import fetch from 'node-fetch'; /* * Copyright 2020 Spotify AB * @@ -15,6 +14,8 @@ import fetch from 'node-fetch'; * limitations under the License. */ +import fetch from 'cross-fetch'; + export class TechDocsMetadata { private async getMetadataFile(docsUrl: String) { const metadataURL = `${docsUrl}/techdocs_metadata.json`; diff --git a/plugins/techdocs-backend/src/service/router.ts b/plugins/techdocs-backend/src/service/router.ts index 365534b9d0..2254e721bd 100644 --- a/plugins/techdocs-backend/src/service/router.ts +++ b/plugins/techdocs-backend/src/service/router.ts @@ -17,7 +17,7 @@ import { Logger } from 'winston'; import Router from 'express-promise-router'; import express from 'express'; import Knex from 'knex'; -import fetch from 'node-fetch'; +import fetch from 'cross-fetch'; import { Config } from '@backstage/config'; import Docker from 'dockerode'; import { @@ -71,14 +71,12 @@ export async function createRouter({ const mkDocsMetadata = await (await fetch(metadataURL)).json(); res.send(mkDocsMetadata); } catch (err) { - logger.info( - `[TechDocs] Unable to get metadata for ${path} with error ${err}`, - ); + logger.info(`Unable to get metadata for ${path} with error ${err}`); throw new Error(`Unable to get metadata for ${path} with error ${err}`); } }); - router.get('/metadata/entity/:kind/:namespace/:name', async (req, res) => { + router.get('/metadata/entity/:namespace/:kind/:name', async (req, res) => { const baseUrl = config.getString('backend.baseUrl'); const { kind, namespace, name } = req.params; @@ -93,7 +91,7 @@ export async function createRouter({ res.send({ ...entity, locationMetadata }); } catch (err) { logger.info( - `[TechDocs] Unable to get metadata for ${kind}/${namespace}/${name} with error ${err}`, + `Unable to get metadata for ${kind}/${namespace}/${name} with error ${err}`, ); throw new Error( `Unable to get metadata for ${kind}/${namespace}/${name} with error ${err}`, @@ -101,7 +99,7 @@ export async function createRouter({ } }); - router.get('/docs/:kind/:namespace/:name/*', async (req, res) => { + router.get('/docs/:namespace/:kind/:name/*', async (req, res) => { const storageUrl = config.getString('techdocs.storageUrl'); const { kind, namespace, name } = req.params; @@ -111,7 +109,9 @@ export async function createRouter({ const catalogRes = await fetch(`${catalogUrl}/entities/by-name/${triple}`); if (!catalogRes.ok) { - catalogRes.body.pipe(res.status(catalogRes.status)); + const catalogResText = await catalogRes.text(); + res.status(catalogRes.status); + res.send(catalogResText); return; } diff --git a/plugins/techdocs-backend/src/techdocs/stages/generate/techdocs.ts b/plugins/techdocs-backend/src/techdocs/stages/generate/techdocs.ts index ac73963f9a..1160ff1ade 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/generate/techdocs.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/generate/techdocs.ts @@ -83,7 +83,7 @@ export class TechdocsGenerator implements GeneratorBase { logStream, }); this.logger.info( - `[TechDocs]: Successfully generated docs from ${directory} into ${resultDir} using local mkdocs`, + `Successfully generated docs from ${directory} into ${resultDir} using local mkdocs`, ); break; case 'docker': @@ -96,7 +96,7 @@ export class TechdocsGenerator implements GeneratorBase { dockerClient, }); this.logger.info( - `[TechDocs]: Successfully generated docs from ${directory} into ${resultDir} using techdocs-container`, + `Successfully generated docs from ${directory} into ${resultDir} using techdocs-container`, ); break; default: @@ -106,9 +106,9 @@ export class TechdocsGenerator implements GeneratorBase { } } catch (error) { this.logger.debug( - `[TechDocs]: Failed to generate docs from ${directory} into ${resultDir}`, + `Failed to generate docs from ${directory} into ${resultDir}`, ); - this.logger.debug(`[TechDocs]: Build failed with error: ${log}`); + this.logger.debug(`Build failed with error: ${log}`); throw new Error( `Failed to generate docs from ${directory} into ${resultDir} with error ${error.message}`, ); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.test.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/commonGit.test.ts similarity index 59% rename from plugins/techdocs-backend/src/techdocs/stages/prepare/github.test.ts rename to plugins/techdocs-backend/src/techdocs/stages/prepare/commonGit.test.ts index a657cd1697..cec1110f97 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.test.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/commonGit.test.ts @@ -15,7 +15,7 @@ */ import { getVoidLogger } from '@backstage/backend-common'; -import { GithubPreparer } from './github'; +import { CommonGitPreparer } from './commonGit'; import { checkoutGitRepository } from '../../../helpers'; function normalizePath(path: string) { @@ -45,9 +45,9 @@ const createMockEntity = (annotations = {}) => { const logger = getVoidLogger(); -describe('github preparer', () => { +describe('commonGit preparer', () => { it('should prepare temp docs path from github repo', async () => { - const preparer = new GithubPreparer(logger); + const preparer = new CommonGitPreparer(logger); const mockEntity = createMockEntity({ 'backstage.io/techdocs-ref': @@ -60,4 +60,34 @@ describe('github preparer', () => { '/tmp/backstage-repo/org/name/branch/plugins/techdocs-backend/examples/documented-component', ); }); + + it('should prepare temp docs path from gitlab repo', async () => { + const preparer = new CommonGitPreparer(logger); + + const mockEntity = createMockEntity({ + 'backstage.io/techdocs-ref': + 'gitlab:https://gitlab.com/xesjkeee/go-logger/blob/master/catalog-info.yaml', + }); + + const tempDocsPath = await preparer.prepare(mockEntity); + expect(checkoutGitRepository).toHaveBeenCalledTimes(2); + expect(normalizePath(tempDocsPath)).toEqual( + '/tmp/backstage-repo/org/name/branch/catalog-info.yaml', + ); + }); + + it('should prepare temp docs path from azure repo', async () => { + const preparer = new CommonGitPreparer(logger); + + const mockEntity = createMockEntity({ + 'backstage.io/techdocs-ref': + 'azure/api:https://dev.azure.com/backstage-org/backstage-project/_git/template-repo?path=%2Ftemplate.yaml', + }); + + const tempDocsPath = await preparer.prepare(mockEntity); + expect(checkoutGitRepository).toHaveBeenCalledTimes(3); + expect(normalizePath(tempDocsPath)).toEqual( + '/tmp/backstage-repo/org/name/branch/template.yaml', + ); + }); }); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/commonGit.ts similarity index 83% rename from plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.ts rename to plugins/techdocs-backend/src/techdocs/stages/prepare/commonGit.ts index 56f3793fbb..d9ba96a031 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/commonGit.ts @@ -15,7 +15,6 @@ */ import path from 'path'; import { Entity } from '@backstage/catalog-model'; -import { InputError } from '@backstage/backend-common'; import { PreparerBase } from './types'; import parseGitUrl from 'git-url-parse'; import { @@ -25,7 +24,7 @@ import { import { Logger } from 'winston'; -export class GitlabPreparer implements PreparerBase { +export class CommonGitPreparer implements PreparerBase { private readonly logger: Logger; constructor(logger: Logger) { @@ -33,15 +32,11 @@ export class GitlabPreparer implements PreparerBase { } async prepare(entity: Entity): Promise { - const { type, target } = parseReferenceAnnotation( + const { target } = parseReferenceAnnotation( 'backstage.io/techdocs-ref', entity, ); - if (type !== 'gitlab') { - throw new InputError(`Wrong target type: ${type}, should be 'gitlab'`); - } - try { const repoPath = await checkoutGitRepository(target, this.logger); const parsedGitLocation = parseGitUrl(target); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts index cad8a7effa..1effcf61b5 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts @@ -38,11 +38,12 @@ export class DirectoryPreparer implements PreparerBase { ); this.logger.debug( - `[TechDocs] Building docs for entity with type 'dir' and managed-by-location '${type}'`, + `Building docs for entity with type 'dir' and managed-by-location '${type}'`, ); switch (type) { case 'github': - case 'gitlab': { + case 'gitlab': + case 'azure/api': { const parsedGitLocation = parseGitUrl(target); const repoLocation = await checkoutGitRepository(target, this.logger); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/github.ts deleted file mode 100644 index a0f91a375a..0000000000 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import path from 'path'; -import { Entity } from '@backstage/catalog-model'; -import { InputError } from '@backstage/backend-common'; -import { PreparerBase } from './types'; -import parseGitUrl from 'git-url-parse'; -import { - parseReferenceAnnotation, - checkoutGitRepository, -} from '../../../helpers'; - -import { Logger } from 'winston'; - -export class GithubPreparer implements PreparerBase { - private readonly logger: Logger; - - constructor(logger: Logger) { - this.logger = logger; - } - - async prepare(entity: Entity): Promise { - const { type, target } = parseReferenceAnnotation( - 'backstage.io/techdocs-ref', - entity, - ); - - if (type !== 'github') { - throw new InputError(`Wrong target type: ${type}, should be 'github'`); - } - - try { - const repoPath = await checkoutGitRepository(target, this.logger); - - const parsedGitLocation = parseGitUrl(target); - return path.join(repoPath, parsedGitLocation.filepath); - } catch (error) { - this.logger.debug(`Repo checkout failed with error ${error.message}`); - throw error; - } - } -} diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.test.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.test.ts deleted file mode 100644 index 75cad50224..0000000000 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { getVoidLogger } from '@backstage/backend-common'; -import { GitlabPreparer } from './gitlab'; -import { checkoutGitRepository } from '../../../helpers'; - -function normalizePath(path: string) { - return path - .replace(/^[a-z]:/i, '') - .split('\\') - .join('/'); -} - -jest.mock('../../../helpers', () => ({ - ...jest.requireActual<{}>('../../../helpers'), - checkoutGitRepository: jest.fn(() => '/tmp/backstage-repo/org/name/branch'), -})); - -const createMockEntity = (annotations = {}) => { - return { - apiVersion: 'version', - kind: 'TestKind', - metadata: { - name: 'test-component-name', - annotations: { - ...annotations, - }, - }, - }; -}; - -const logger = getVoidLogger(); - -describe('gitlab preparer', () => { - it('should prepare temp docs path from gitlab repo', async () => { - const preparer = new GitlabPreparer(logger); - - // TODO: fix url repo - const mockEntity = createMockEntity({ - 'backstage.io/techdocs-ref': - 'gitlab:https://gitlab.com/xesjkeee/go-logger/blob/master/catalog-info.yaml', - }); - - const tempDocsPath = await preparer.prepare(mockEntity); - expect(checkoutGitRepository).toHaveBeenCalledTimes(1); - expect(normalizePath(tempDocsPath)).toEqual( - '/tmp/backstage-repo/org/name/branch/catalog-info.yaml', - ); - }); -}); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts index 9e91958bd7..46e1d84c69 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts @@ -14,7 +14,6 @@ * limitations under the License. */ export { DirectoryPreparer } from './dir'; -export { GithubPreparer } from './github'; -export { GitlabPreparer } from './gitlab'; +export { CommonGitPreparer } from './commonGit'; export { Preparers } from './preparers'; export type { PreparerBuilder, PreparerBase } from './types'; diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts index 4cb1e1e006..1dd091e107 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts @@ -30,4 +30,4 @@ export type PreparerBuilder = { get(entity: Entity): PreparerBase; }; -export type RemoteProtocol = 'dir' | 'github' | 'gitlab' | 'file'; +export type RemoteProtocol = 'dir' | 'github' | 'gitlab' | 'file' | 'azure/api'; diff --git a/plugins/techdocs-backend/src/techdocs/stages/publish/local.test.ts b/plugins/techdocs-backend/src/techdocs/stages/publish/local.test.ts index 55e0a547e9..d97a4014f6 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/publish/local.test.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/publish/local.test.ts @@ -13,6 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +/* eslint-disable no-restricted-syntax */ import fs from 'fs-extra'; import path from 'path'; import { getVoidLogger } from '@backstage/backend-common'; @@ -53,7 +55,7 @@ describe('local publisher', () => { const resultDir = path.resolve( __dirname, - `../../../../static/docs/${mockEntity.kind}/default/${mockEntity.metadata.name}`, + `../../../../static/docs/default/${mockEntity.kind}/${mockEntity.metadata.name}`, ); expect(fs.existsSync(resultDir)).toBeTruthy(); diff --git a/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts b/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts index f328443965..6d655d4632 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts @@ -42,8 +42,8 @@ export class LocalPublish implements PublisherBase { const publishDir = resolvePackagePath( '@backstage/plugin-techdocs-backend', 'static/docs', - entity.kind, entityNamespace, + entity.kind, entity.metadata.name, ); diff --git a/plugins/techdocs/package.json b/plugins/techdocs/package.json index 27b0b0b881..9d14f0a919 100644 --- a/plugins/techdocs/package.json +++ b/plugins/techdocs/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-techdocs", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -22,12 +22,12 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/catalog-model": "^0.1.1-alpha.24", - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/core-api": "^0.1.1-alpha.24", - "@backstage/plugin-catalog": "^0.1.1-alpha.24", - "@backstage/test-utils": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/catalog-model": "^0.1.1-alpha.26", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/core-api": "^0.1.1-alpha.26", + "@backstage/plugin-catalog": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -40,17 +40,17 @@ "sanitize-html": "^1.27.0" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "canvas": "^2.6.1", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/techdocs/src/EntityPageDocs.tsx b/plugins/techdocs/src/EntityPageDocs.tsx index d10c7a5932..544c2cdadd 100644 --- a/plugins/techdocs/src/EntityPageDocs.tsx +++ b/plugins/techdocs/src/EntityPageDocs.tsx @@ -23,7 +23,7 @@ export const EntityPageDocs = ({ entity }: { entity: Entity }) => { diff --git a/plugins/techdocs/src/Router.tsx b/plugins/techdocs/src/Router.tsx index 6dc0dd02ad..262f542ee6 100644 --- a/plugins/techdocs/src/Router.tsx +++ b/plugins/techdocs/src/Router.tsx @@ -17,8 +17,7 @@ import React from 'react'; import { Entity } from '@backstage/catalog-model'; import { Route, Routes } from 'react-router-dom'; -import { WarningPanel } from '@backstage/core'; - +import { MissingAnnotationEmptyState } from '@backstage/core'; import { rootRouteRef, rootDocsRouteRef, @@ -43,15 +42,7 @@ export const EmbeddedDocsRouter = ({ entity }: { entity: Entity }) => { const projectId = entity.metadata.annotations?.[TECHDOCS_ANNOTATION]; if (!projectId) { - return ( - -
{TECHDOCS_ANNOTATION}
annotation is missing on the entity. -
- - Getting Started - -
- ); + return ; } return ( diff --git a/plugins/techdocs/src/api.test.ts b/plugins/techdocs/src/api.test.ts index f7c52f8a7d..132976e280 100644 --- a/plugins/techdocs/src/api.test.ts +++ b/plugins/techdocs/src/api.test.ts @@ -28,7 +28,7 @@ describe('TechDocsStorageApi', () => { const storageApi = new TechDocsStorageApi({ apiOrigin: DOC_STORAGE_URL }); expect(storageApi.getBaseUrl('test.js', mockEntity, '')).toEqual( - `${DOC_STORAGE_URL}/docs/${mockEntity.kind}/${mockEntity.namespace}/${mockEntity.name}/test.js`, + `${DOC_STORAGE_URL}/docs/${mockEntity.namespace}/${mockEntity.kind}/${mockEntity.name}/test.js`, ); }); @@ -36,7 +36,7 @@ describe('TechDocsStorageApi', () => { const storageApi = new TechDocsStorageApi({ apiOrigin: DOC_STORAGE_URL }); expect(storageApi.getBaseUrl('test/', mockEntity, '')).toEqual( - `${DOC_STORAGE_URL}/docs/${mockEntity.kind}/${mockEntity.namespace}/${mockEntity.name}/test/`, + `${DOC_STORAGE_URL}/docs/${mockEntity.namespace}/${mockEntity.kind}/${mockEntity.name}/test/`, ); }); }); diff --git a/plugins/techdocs/src/api.ts b/plugins/techdocs/src/api.ts index 87a0a56a01..31e4a10e4c 100644 --- a/plugins/techdocs/src/api.ts +++ b/plugins/techdocs/src/api.ts @@ -51,9 +51,7 @@ export class TechDocsApi implements TechDocs { async getMetadata(metadataType: string, entityId: ParsedEntityId) { const { kind, namespace, name } = entityId; - const requestUrl = `${this.apiOrigin}/metadata/${metadataType}/${kind}/${ - namespace ? namespace : 'default' - }/${name}`; + const requestUrl = `${this.apiOrigin}/metadata/${metadataType}/${namespace}/${kind}/${name}`; const request = await fetch(`${requestUrl}`); const res = await request.json(); @@ -72,9 +70,7 @@ export class TechDocsStorageApi implements TechDocsStorage { async getEntityDocs(entityId: ParsedEntityId, path: string) { const { kind, namespace, name } = entityId; - const url = `${this.apiOrigin}/docs/${kind}/${ - namespace ? namespace : 'default' - }/${name}/${path}`; + const url = `${this.apiOrigin}/docs/${namespace}/${kind}/${name}/${path}`; const request = await fetch( `${url.endsWith('/') ? url : `${url}/`}index.html`, @@ -96,9 +92,7 @@ export class TechDocsStorageApi implements TechDocsStorage { return new URL( oldBaseUrl, - `${this.apiOrigin}/docs/${kind}/${ - namespace ? namespace : 'default' - }/${name}/${path}`, + `${this.apiOrigin}/docs/${namespace}/${kind}/${name}/${path}`, ).toString(); } } diff --git a/plugins/techdocs/src/plugin.ts b/plugins/techdocs/src/plugin.ts index b197bdfb76..ee2cab60fa 100644 --- a/plugins/techdocs/src/plugin.ts +++ b/plugins/techdocs/src/plugin.ts @@ -48,7 +48,7 @@ export const rootRouteRef = createRouteRef({ }); export const rootDocsRouteRef = createRouteRef({ - path: ':entityId/*', + path: ':namespace/:kind/:name/*', title: 'Docs', }); diff --git a/plugins/techdocs/src/reader/components/Reader.tsx b/plugins/techdocs/src/reader/components/Reader.tsx index 550b8df923..785c6f1c6b 100644 --- a/plugins/techdocs/src/reader/components/Reader.tsx +++ b/plugins/techdocs/src/reader/components/Reader.tsx @@ -30,6 +30,7 @@ import transformer, { rewriteDocLinks, addLinkClickListener, removeMkdocsHeader, + simplifyMkdocsFooter, modifyCss, onCssReady, sanitizeDOM, @@ -81,6 +82,7 @@ export const Reader = ({ entityId, onReady }: Props) => { }, }), removeMkdocsHeader(), + simplifyMkdocsFooter(), injectCss({ css: ` body { @@ -116,6 +118,7 @@ export const Reader = ({ entityId, onReady }: Props) => { return dom; }, addLinkClickListener({ + baseUrl: window.location.origin, onClick: (_: MouseEvent, url: string) => { const parsedUrl = new URL(url); navigate(`${parsedUrl.pathname}${parsedUrl.hash}`); diff --git a/plugins/techdocs/src/reader/components/TechDocsHome.tsx b/plugins/techdocs/src/reader/components/TechDocsHome.tsx index c478a52127..0408a540ca 100644 --- a/plugins/techdocs/src/reader/components/TechDocsHome.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsHome.tsx @@ -24,7 +24,6 @@ import { useApi, Content, Page, - pageTheme, Header, } from '@backstage/core'; import { catalogApiRef } from '@backstage/plugin-catalog'; @@ -43,7 +42,7 @@ export const TechDocsHome = () => { if (loading) { return ( - +
{ if (error) { return ( - +
{ } return ( - +
{ onClick={() => navigate( generatePath(rootDocsRouteRef.path, { - entityId: `${entity.kind}:${ - entity.metadata.namespace ?? '' - }:${entity.metadata.name}`, + namespace: entity.metadata.namespace ?? 'default', + kind: entity.kind, + name: entity.metadata.name, }), ) } diff --git a/plugins/techdocs/src/reader/components/TechDocsPage.tsx b/plugins/techdocs/src/reader/components/TechDocsPage.tsx index a70ce76191..00f0b3c9d3 100644 --- a/plugins/techdocs/src/reader/components/TechDocsPage.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsPage.tsx @@ -16,7 +16,7 @@ import React, { useState } from 'react'; import { useParams } from 'react-router-dom'; -import { Content, Page, pageTheme, useApi } from '@backstage/core'; +import { Content, Page, useApi } from '@backstage/core'; import { Reader } from './Reader'; import { useAsync } from 'react-use'; import { TechDocsPageHeader } from './TechDocsPageHeader'; @@ -24,8 +24,7 @@ import { techdocsApiRef } from '../../api'; export const TechDocsPage = () => { const [documentReady, setDocumentReady] = useState(false); - const { entityId } = useParams(); - const [kind, namespace, name] = entityId.split(':'); + const { namespace, kind, name } = useParams(); const techDocsApi = useApi(techdocsApiRef); @@ -46,7 +45,7 @@ export const TechDocsPage = () => { }; return ( - + ', () => { ), ); expect(rendered.container.innerHTML).toContain('header'); - expect(rendered.getByText('test-site-name')).toBeDefined(); + expect(rendered.getAllByText('test-site-name')).toHaveLength(2); expect(rendered.getByText('test-site-desc')).toBeDefined(); }); }); diff --git a/plugins/techdocs/src/reader/components/TechDocsPageHeader.tsx b/plugins/techdocs/src/reader/components/TechDocsPageHeader.tsx index b01ace4994..a7db342544 100644 --- a/plugins/techdocs/src/reader/components/TechDocsPageHeader.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsPageHeader.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import GitHubIcon from '@material-ui/icons/GitHub'; +import CodeIcon from '@material-ui/icons/Code'; import { Header, HeaderLabel, Link } from '@backstage/core'; import { CircularProgress } from '@material-ui/core'; import { ParsedEntityId } from '../../types'; @@ -48,12 +48,14 @@ export const TechDocsPageHeader = ({ spec: { owner, lifecycle }, } = entityMetadataValues || { spec: {} }; + const componentLink = `/catalog/${kind}/${name}`; + const labels = ( <> + {name} } @@ -66,8 +68,12 @@ export const TechDocsPageHeader = ({ - + + } /> @@ -81,6 +87,8 @@ export const TechDocsPageHeader = ({ subtitle={ siteDescription && siteDescription !== 'None' ? siteDescription : '' } + type={name} + typeLink={componentLink} > {labels}
diff --git a/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx b/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx index be464bd485..f97fcda3f1 100644 --- a/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx @@ -25,12 +25,14 @@ jest.useFakeTimers(); describe('', () => { it('should render a message if techdocs page takes more time to load', () => { const rendered = render(wrapInTestApp()); - - expect(rendered.getByTestId('progress')).toBeDefined(); + act(() => { + jest.advanceTimersByTime(250); + }); + expect(rendered.getByTestId('progress')).toBeInTheDocument(); expect(rendered.queryByTestId('delay-reason')).toBeNull(); act(() => { jest.advanceTimersByTime(5000); }); - expect(rendered.getByTestId('delay-reason')).toBeDefined(); + expect(rendered.getByTestId('delay-reason')).toBeInTheDocument(); }); }); diff --git a/plugins/techdocs/src/reader/transformers/addLinkClickListener.test.ts b/plugins/techdocs/src/reader/transformers/addLinkClickListener.test.ts index 8e942b8be1..775780fe4d 100644 --- a/plugins/techdocs/src/reader/transformers/addLinkClickListener.test.ts +++ b/plugins/techdocs/src/reader/transformers/addLinkClickListener.test.ts @@ -14,23 +14,61 @@ * limitations under the License. */ -import { createTestShadowDom, FIXTURES } from '../../test-utils'; +import { createTestShadowDom } from '../../test-utils'; import { addLinkClickListener } from '.'; describe('addLinkClickListener', () => { it('calls onClick when a link has been clicked', () => { const fn = jest.fn(); - const shadowDom = createTestShadowDom(FIXTURES.FIXTURE_STANDARD_PAGE, { - preTransformers: [], - postTransformers: [ - addLinkClickListener({ - onClick: fn, - }), - ], - }); + const shadowDom = createTestShadowDom( + ` + + + + Link + + + `, + { + preTransformers: [], + postTransformers: [ + addLinkClickListener({ + baseUrl: 'http://localhost:3000', + onClick: fn, + }), + ], + }, + ); shadowDom.querySelector('a')?.click(); expect(fn).toHaveBeenCalledTimes(1); }); + + it('does not call onClick when a link links to another baseUrl', () => { + const fn = jest.fn(); + const shadowDom = createTestShadowDom( + ` + + + + Link + + + `, + { + preTransformers: [], + postTransformers: [ + addLinkClickListener({ + baseUrl: 'http://localhost:3000', + onClick: fn, + }), + ], + }, + ); + + shadowDom.querySelector('a')?.click(); + + expect(fn).toHaveBeenCalledTimes(0); + }); }); diff --git a/plugins/techdocs/src/reader/transformers/addLinkClickListener.ts b/plugins/techdocs/src/reader/transformers/addLinkClickListener.ts index 3566b403a2..b6a6509550 100644 --- a/plugins/techdocs/src/reader/transformers/addLinkClickListener.ts +++ b/plugins/techdocs/src/reader/transformers/addLinkClickListener.ts @@ -17,10 +17,12 @@ import type { Transformer } from './index'; type AddLinkClickListenerOptions = { + baseUrl: string; onClick: (e: MouseEvent, newUrl: string) => void; }; export const addLinkClickListener = ({ + baseUrl, onClick, }: AddLinkClickListenerOptions): Transformer => { return dom => { @@ -28,8 +30,9 @@ export const addLinkClickListener = ({ elem.addEventListener('click', (e: MouseEvent) => { const target = e.target as HTMLAnchorElement; const href = target?.getAttribute('href'); + if (!href) return; - if (!href.match(/^https?:\/\//i)) { + if (href.startsWith(baseUrl)) { e.preventDefault(); onClick(e, target.getAttribute('href')!); } diff --git a/plugins/techdocs/src/reader/transformers/index.ts b/plugins/techdocs/src/reader/transformers/index.ts index ddbaadd071..0bab085abe 100644 --- a/plugins/techdocs/src/reader/transformers/index.ts +++ b/plugins/techdocs/src/reader/transformers/index.ts @@ -18,6 +18,7 @@ export * from './addBaseUrl'; export * from './rewriteDocLinks'; export * from './addLinkClickListener'; export * from './removeMkdocsHeader'; +export * from './simplifyMkdocsFooter'; export * from './modifyCss'; export * from './onCssReady'; export * from './sanitizeDOM'; diff --git a/plugins/techdocs/src/reader/transformers/onCssReady.test.ts b/plugins/techdocs/src/reader/transformers/onCssReady.test.ts index c83a94f35d..67ae38c56b 100644 --- a/plugins/techdocs/src/reader/transformers/onCssReady.test.ts +++ b/plugins/techdocs/src/reader/transformers/onCssReady.test.ts @@ -25,14 +25,20 @@ import { onCssReady } from '../transformers'; const docStorageUrl: string = 'https://techdocs-mock-sites.storage.googleapis.com'; -jest.useFakeTimers(); - const fixture = ` `; describe('onCssReady', () => { + beforeAll(() => { + jest.useFakeTimers(); + }); + + afterAll(() => { + jest.useRealTimers(); + }); + beforeEach(() => { mockStylesheetEventListener(100); }); diff --git a/plugins/techdocs/src/reader/transformers/simplifyMkdocsFooter.test.ts b/plugins/techdocs/src/reader/transformers/simplifyMkdocsFooter.test.ts new file mode 100644 index 0000000000..5af62a43c5 --- /dev/null +++ b/plugins/techdocs/src/reader/transformers/simplifyMkdocsFooter.test.ts @@ -0,0 +1,38 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createTestShadowDom, FIXTURES } from '../../test-utils'; +import { simplifyMkdocsFooter } from '.'; + +describe('simplifyMkdocsFooter', () => { + it('does not remove mkdocs copyright', () => { + const shadowDom = createTestShadowDom(FIXTURES.FIXTURE_STANDARD_PAGE, { + preTransformers: [], + postTransformers: [], + }); + + expect(shadowDom.querySelector('.md-footer-copyright')).toBeTruthy(); + }); + + it('does remove mkdocs copyright', () => { + const shadowDom = createTestShadowDom(FIXTURES.FIXTURE_STANDARD_PAGE, { + preTransformers: [simplifyMkdocsFooter()], + postTransformers: [], + }); + + expect(shadowDom.querySelector('.md-footer-copyright')).toBeFalsy(); + }); +}); diff --git a/plugins/techdocs/src/reader/transformers/simplifyMkdocsFooter.ts b/plugins/techdocs/src/reader/transformers/simplifyMkdocsFooter.ts new file mode 100644 index 0000000000..0d0745724d --- /dev/null +++ b/plugins/techdocs/src/reader/transformers/simplifyMkdocsFooter.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Transformer } from './index'; + +export const simplifyMkdocsFooter = (): Transformer => { + return dom => { + // Remove mkdocs copyright + dom.querySelector('.md-footer-copyright')?.remove(); + + return dom; + }; +}; diff --git a/plugins/techdocs/src/setupTests.ts b/plugins/techdocs/src/setupTests.ts index 8553642152..825bcd4115 100644 --- a/plugins/techdocs/src/setupTests.ts +++ b/plugins/techdocs/src/setupTests.ts @@ -15,5 +15,3 @@ */ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); diff --git a/plugins/user-settings/.eslintrc.js b/plugins/user-settings/.eslintrc.js new file mode 100644 index 0000000000..13573efa9c --- /dev/null +++ b/plugins/user-settings/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: [require.resolve('@backstage/cli/config/eslint')], +}; diff --git a/plugins/user-settings/README.md b/plugins/user-settings/README.md new file mode 100644 index 0000000000..db0b01681f --- /dev/null +++ b/plugins/user-settings/README.md @@ -0,0 +1,65 @@ +# user-settings + +Welcome to the user-settings plugin! + +_This plugin was created through the Backstage CLI_ + +## About the plugin + +This plugin provides two components, `` is intended to be used within the [``](https://backstage.io/storybook/?path=/story/sidebar--sample-sidebar) and displays the signed-in users profile picture and name. + +The second component is a settings page where the user can control different settings across the App. + +## Usage + +Add the item to the Sidebar: + +```ts +import { Settings as SidebarSettings } from '@backstage/plugin-user-settings'; + + + + + +; +``` + +Add the page to the App routing: + +```ts +import { Router as SettingsRouter } from '@backstage/plugin-user-settings'; + +const AppRoutes = () => ( + + } /> + +); +``` + +### Props + +**Auth Providers** + +By default, the plugin provides a list of configured authentication providers fetched from `app-config.yaml` and displayed in the "Authentication Providers" tab. + +If you want to supply your own custom list of Authentication Providers, use the `providerSettings` prop: + +```ts +const MyAuthProviders = () => ( + + + {someAction} + +); + +const AppRoutes = () => ( + + } />} + /> + +); +``` + +> **Note that the list of providers expects to be rendered within a MUI [``](https://material-ui.com/components/lists/)** diff --git a/plugins/user-settings/dev/index.tsx b/plugins/user-settings/dev/index.tsx new file mode 100644 index 0000000000..264d6f801f --- /dev/null +++ b/plugins/user-settings/dev/index.tsx @@ -0,0 +1,19 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createDevApp } from '@backstage/dev-utils'; +import { plugin } from '../src/plugin'; + +createDevApp().registerPlugin(plugin).render(); diff --git a/plugins/user-settings/package.json b/plugins/user-settings/package.json new file mode 100644 index 0000000000..6f96d7b2fd --- /dev/null +++ b/plugins/user-settings/package.json @@ -0,0 +1,49 @@ +{ + "name": "@backstage/plugin-user-settings", + "version": "0.1.1-alpha.26", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + "private": false, + "publishConfig": { + "access": "public", + "main": "dist/index.esm.js", + "types": "dist/index.d.ts" + }, + "scripts": { + "build": "backstage-cli plugin:build", + "start": "backstage-cli plugin:serve", + "lint": "backstage-cli lint", + "test": "backstage-cli test", + "diff": "backstage-cli plugin:diff", + "prepack": "backstage-cli prepack", + "postpack": "backstage-cli postpack", + "clean": "backstage-cli clean" + }, + "dependencies": { + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", + "@material-ui/core": "^4.11.0", + "@material-ui/icons": "^4.9.1", + "@material-ui/lab": "4.0.0-alpha.45", + "react": "^16.13.1", + "react-dom": "^16.13.1", + "react-router": "6.0.0-beta.0", + "react-use": "^15.3.3" + }, + "devDependencies": { + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", + "@testing-library/jest-dom": "^5.10.1", + "@testing-library/react": "^10.4.1", + "@testing-library/user-event": "^12.0.7", + "@types/jest": "^26.0.7", + "@types/node": "^12.0.0", + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/user-settings/src/components/AuthProviders/AuthProviders.test.tsx b/plugins/user-settings/src/components/AuthProviders/AuthProviders.test.tsx new file mode 100644 index 0000000000..4399b6bd3e --- /dev/null +++ b/plugins/user-settings/src/components/AuthProviders/AuthProviders.test.tsx @@ -0,0 +1,79 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ApiProvider, + ApiRegistry, + configApiRef, + ConfigReader, + googleAuthApiRef, +} from '@backstage/core'; +import { renderWithEffects, wrapInTestApp } from '@backstage/test-utils'; +import { fireEvent } from '@testing-library/react'; +import React from 'react'; +import { AuthProviders } from './AuthProviders'; + +const mockSignInHandler = jest.fn().mockReturnValue(''); +const mockGoogleAuth = { + sessionState$: () => ({ + subscribe: () => ({ + unsubscribe: () => null, + }), + }), + signIn: mockSignInHandler, +}; + +const createConfig = () => + ConfigReader.fromConfigs([ + { + context: '', + data: { + auth: { + providers: { + google: { development: {} }, + }, + }, + }, + }, + ]); + +const config = createConfig(); + +const apiRegistry = ApiRegistry.from([ + [configApiRef, config], + [googleAuthApiRef, mockGoogleAuth], +]); + +describe('', () => { + it('displays a provider and calls its sign-in handler on click', async () => { + const rendered = await renderWithEffects( + wrapInTestApp( + + + , + ), + ); + + expect(rendered.getByText('Google')).toBeInTheDocument(); + expect( + rendered.getByText(googleAuthApiRef.description), + ).toBeInTheDocument(); + + const button = rendered.getByTitle('Sign in to Google'); + fireEvent.click(button); + expect(mockSignInHandler).toHaveBeenCalledTimes(1); + }); +}); diff --git a/plugins/user-settings/src/components/AuthProviders/AuthProviders.tsx b/plugins/user-settings/src/components/AuthProviders/AuthProviders.tsx new file mode 100644 index 0000000000..bc2a68578d --- /dev/null +++ b/plugins/user-settings/src/components/AuthProviders/AuthProviders.tsx @@ -0,0 +1,44 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { List } from '@material-ui/core'; +import { configApiRef, InfoCard, useApi } from '@backstage/core'; +import { EmptyProviders } from './EmptyProviders'; +import { DefaultProviderSettings } from './DefaultProviderSettings'; + +type Props = { + providerSettings?: JSX.Element; +}; + +export const AuthProviders = ({ providerSettings }: Props) => { + const configApi = useApi(configApiRef); + const providersConfig = configApi.getOptionalConfig('auth.providers'); + const configuredProviders = providersConfig?.keys() || []; + const providers = providerSettings ?? ( + + ); + + if (!providerSettings && !configuredProviders?.length) { + return ; + } + + return ( + + {providers} + + ); +}; diff --git a/plugins/user-settings/src/components/AuthProviders/DefaultProviderSettings.tsx b/plugins/user-settings/src/components/AuthProviders/DefaultProviderSettings.tsx new file mode 100644 index 0000000000..a1dab1e7d4 --- /dev/null +++ b/plugins/user-settings/src/components/AuthProviders/DefaultProviderSettings.tsx @@ -0,0 +1,83 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + githubAuthApiRef, + gitlabAuthApiRef, + googleAuthApiRef, + oauth2ApiRef, + oktaAuthApiRef, + microsoftAuthApiRef, +} from '@backstage/core'; +import Star from '@material-ui/icons/Star'; +import React from 'react'; +import { ProviderSettingsItem } from './ProviderSettingsItem'; + +type Props = { + configuredProviders: string[]; +}; + +export const DefaultProviderSettings = ({ configuredProviders }: Props) => ( + <> + {configuredProviders.includes('google') && ( + + )} + {configuredProviders.includes('microsoft') && ( + + )} + {configuredProviders.includes('github') && ( + + )} + {configuredProviders.includes('gitlab') && ( + + )} + {configuredProviders.includes('okta') && ( + + )} + {configuredProviders.includes('oauth2') && ( + + )} + +); diff --git a/plugins/user-settings/src/components/AuthProviders/EmptyProviders.tsx b/plugins/user-settings/src/components/AuthProviders/EmptyProviders.tsx new file mode 100644 index 0000000000..653f449e92 --- /dev/null +++ b/plugins/user-settings/src/components/AuthProviders/EmptyProviders.tsx @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { CodeSnippet, EmptyState } from '@backstage/core'; +import { Button, Typography } from '@material-ui/core'; + +const EXAMPLE = `auth: + providers: + google: + development: + clientId: + $env: AUTH_GOOGLE_CLIENT_ID + clientSecret: + $env: AUTH_GOOGLE_CLIENT_SECRET +`; + +export const EmptyProviders = () => ( + + + Open app-config.yaml and make the changes as highlighted + below: + + + + + } + /> +); diff --git a/packages/core/src/layout/Sidebar/Settings/ProviderSettingsItem.tsx b/plugins/user-settings/src/components/AuthProviders/ProviderSettingsItem.tsx similarity index 65% rename from packages/core/src/layout/Sidebar/Settings/ProviderSettingsItem.tsx rename to plugins/user-settings/src/components/AuthProviders/ProviderSettingsItem.tsx index 4db7ea0823..4bae3dbfbb 100644 --- a/packages/core/src/layout/Sidebar/Settings/ProviderSettingsItem.tsx +++ b/plugins/user-settings/src/components/AuthProviders/ProviderSettingsItem.tsx @@ -13,36 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import React, { FC, useState, useEffect } from 'react'; -import { - ListItem, - ListItemIcon, - ListItemSecondaryAction, - ListItemText, - Tooltip, -} from '@material-ui/core'; -import PowerButton from '@material-ui/icons/PowerSettingsNew'; -import { ToggleButton } from '@material-ui/lab'; +import React, { useEffect, useState } from 'react'; import { ApiRef, SessionApi, useApi, IconComponent, SessionState, -} from '@backstage/core-api'; +} from '@backstage/core'; +import { + Button, + ListItem, + ListItemIcon, + ListItemSecondaryAction, + ListItemText, + Tooltip, +} from '@material-ui/core'; -type OAuthProviderSidebarProps = { +type Props = { title: string; + description: string; icon: IconComponent; apiRef: ApiRef; }; -export const ProviderSettingsItem: FC = ({ +export const ProviderSettingsItem = ({ title, + description, icon: Icon, apiRef, -}) => { +}: Props) => { const api = useApi(apiRef); const [signedIn, setSignedIn] = useState(false); @@ -68,22 +68,29 @@ export const ProviderSettingsItem: FC = ({ - - - (signedIn ? api.signOut() : api.signIn())} - > - - + + {description} - + } + secondaryTypographyProps={{ noWrap: true, style: { width: '80%' } }} + /> + + + + ); diff --git a/packages/core/src/layout/Sidebar/Settings/index.ts b/plugins/user-settings/src/components/AuthProviders/index.ts similarity index 83% rename from packages/core/src/layout/Sidebar/Settings/index.ts rename to plugins/user-settings/src/components/AuthProviders/index.ts index 15042dc85d..2f6a2b5ab1 100644 --- a/packages/core/src/layout/Sidebar/Settings/index.ts +++ b/plugins/user-settings/src/components/AuthProviders/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export { ProviderSettingsItem } from './ProviderSettingsItem'; -export { SidebarUserSettings } from './UserSettings'; +export { AuthProviders } from './AuthProviders'; +export { DefaultProviderSettings } from './DefaultProviderSettings'; diff --git a/plugins/user-settings/src/components/FeatureFlags/EmptyFlags.tsx b/plugins/user-settings/src/components/FeatureFlags/EmptyFlags.tsx new file mode 100644 index 0000000000..5df4df4450 --- /dev/null +++ b/plugins/user-settings/src/components/FeatureFlags/EmptyFlags.tsx @@ -0,0 +1,58 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { CodeSnippet, EmptyState } from '@backstage/core'; +import { Button, Typography } from '@material-ui/core'; + +const EXAMPLE = `import { createPlugin } from '@backstage/core'; + +export default createPlugin({ + id: 'welcome', + register({ router, featureFlags }) { + featureFlags.register('enable-example-feature'); + }, +}); +`; + +export const EmptyFlags = () => ( + + + An example how how to add a feature flags is highlighted below: + + + + + } + /> +); diff --git a/plugins/user-settings/src/components/FeatureFlags/FeatureFlags.tsx b/plugins/user-settings/src/components/FeatureFlags/FeatureFlags.tsx new file mode 100644 index 0000000000..e0f4d6f40e --- /dev/null +++ b/plugins/user-settings/src/components/FeatureFlags/FeatureFlags.tsx @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useCallback, useState } from 'react'; +import { + FeatureFlagName, + featureFlagsApiRef, + FeatureFlagsRegistryItem, + FeatureFlagState, + InfoCard, + useApi, +} from '@backstage/core'; +import { List } from '@material-ui/core'; +import { EmptyFlags } from './EmptyFlags'; +import { FlagItem } from './FeatureFlagsItem'; + +export const FeatureFlags = () => { + const featureFlagsApi = useApi(featureFlagsApiRef); + const featureFlags = featureFlagsApi.getRegisteredFlags(); + const initialFlagState = featureFlags.reduce( + (result, featureFlag: FeatureFlagsRegistryItem) => { + const state = featureFlagsApi.getFlags().get(featureFlag.name); + + result[featureFlag.name] = state; + return result; + }, + {} as Record, + ); + + const [state, setState] = useState>( + initialFlagState, + ); + + const toggleFlag = useCallback( + (flagName: FeatureFlagName) => { + const newState = featureFlagsApi.getFlags().toggle(flagName); + + setState(prevState => ({ + ...prevState, + [flagName]: newState, + })); + featureFlagsApi.getFlags().save(); + }, + [featureFlagsApi], + ); + + if (!featureFlags.length) { + return ; + } + + return ( + + + {featureFlags.map(featureFlag => { + const enabled = Boolean(state[featureFlag.name]); + + return ( + + ); + })} + + + ); +}; diff --git a/plugins/user-settings/src/components/FeatureFlags/FeatureFlagsItem.tsx b/plugins/user-settings/src/components/FeatureFlags/FeatureFlagsItem.tsx new file mode 100644 index 0000000000..460a15f56b --- /dev/null +++ b/plugins/user-settings/src/components/FeatureFlags/FeatureFlagsItem.tsx @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { + ListItem, + ListItemSecondaryAction, + ListItemText, + Switch, + Tooltip, +} from '@material-ui/core'; +import { FeatureFlagsRegistryItem } from '@backstage/core'; + +type Props = { + flag: FeatureFlagsRegistryItem; + enabled: boolean; + toggleHandler: Function; +}; + +export const FlagItem = ({ flag, enabled, toggleHandler }: Props) => ( + + + + + toggleHandler(flag.name)} + name={flag.name} + /> + + + +); diff --git a/plugins/cost-insights/src/components/CostOverviewChartLegend/index.ts b/plugins/user-settings/src/components/FeatureFlags/index.ts similarity index 91% rename from plugins/cost-insights/src/components/CostOverviewChartLegend/index.ts rename to plugins/user-settings/src/components/FeatureFlags/index.ts index 1b6c1fe975..37c9fd1fd2 100644 --- a/plugins/cost-insights/src/components/CostOverviewChartLegend/index.ts +++ b/plugins/user-settings/src/components/FeatureFlags/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { default } from './CostOverviewChartLegend'; +export { FeatureFlags } from './FeatureFlags'; diff --git a/plugins/user-settings/src/components/General/General.tsx b/plugins/user-settings/src/components/General/General.tsx new file mode 100644 index 0000000000..2d30c00eec --- /dev/null +++ b/plugins/user-settings/src/components/General/General.tsx @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { InfoCard } from '@backstage/core'; +import { Grid, List, useMediaQuery, useTheme } from '@material-ui/core'; +import React from 'react'; +import { PinButton } from './PinButton'; +import { Profile } from './Profile'; +import { ThemeToggle } from './ThemeToggle'; + +export const General = () => { + const theme = useTheme(); + const fullScreen = useMediaQuery(theme.breakpoints.down('sm')); + return ( + + + + + + + + + {!fullScreen && } + + + + + ); +}; diff --git a/plugins/user-settings/src/components/General/PinButton.test.tsx b/plugins/user-settings/src/components/General/PinButton.test.tsx new file mode 100644 index 0000000000..939588a9ee --- /dev/null +++ b/plugins/user-settings/src/components/General/PinButton.test.tsx @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { SidebarPinStateContext } from '@backstage/core'; +import { renderWithEffects, wrapInTestApp } from '@backstage/test-utils'; +import { fireEvent } from '@testing-library/react'; +import React from 'react'; +import { PinButton } from './PinButton'; + +describe('', () => { + it('toggles the pin sidebar button', async () => { + const mockToggleFn = jest.fn(); + const rendered = await renderWithEffects( + wrapInTestApp( + + + , + ), + ); + expect(rendered.getByText('Pin Sidebar')).toBeInTheDocument(); + + const pinButton = rendered.getByLabelText('Pin Sidebar Switch'); + fireEvent.click(pinButton); + expect(mockToggleFn).toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/layout/Sidebar/Settings/PinButton.tsx b/plugins/user-settings/src/components/General/PinButton.tsx similarity index 61% rename from packages/core/src/layout/Sidebar/Settings/PinButton.tsx rename to plugins/user-settings/src/components/General/PinButton.tsx index 2727313ede..d44e5c9a3b 100644 --- a/packages/core/src/layout/Sidebar/Settings/PinButton.tsx +++ b/plugins/user-settings/src/components/General/PinButton.tsx @@ -19,28 +19,16 @@ import { ListItem, ListItemSecondaryAction, ListItemText, + Switch, Tooltip, } from '@material-ui/core'; -import LockIcon from '@material-ui/icons/Lock'; -import LockOpenIcon from '@material-ui/icons/LockOpen'; -import { ToggleButton } from '@material-ui/lab'; -import { SidebarPinStateContext } from '../Page'; +import { SidebarPinStateContext } from '@backstage/core'; -export const SidebarPinButton = () => { +export const PinButton = () => { const { isPinned, toggleSidebarPinState } = useContext( SidebarPinStateContext, ); - const PinIcon = () => ( - - {isPinned ? : } - - ); - return ( { secondary="Prevent the sidebar from collapsing" /> - { - toggleSidebarPinState(); - }} + - - + toggleSidebarPinState()} + name="pin" + inputProps={{ 'aria-label': 'Pin Sidebar Switch' }} + /> + ); diff --git a/plugins/user-settings/src/components/General/Profile.tsx b/plugins/user-settings/src/components/General/Profile.tsx new file mode 100644 index 0000000000..b0231d95b6 --- /dev/null +++ b/plugins/user-settings/src/components/General/Profile.tsx @@ -0,0 +1,54 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { InfoCard } from '@backstage/core'; +import { Grid, Typography } from '@material-ui/core'; +import React from 'react'; +import { SignInAvatar } from './SignInAvatar'; +import { UserSettingsMenu } from './UserSettingsMenu'; +import { useUserProfile } from '../useUserProfileInfo'; + +export const Profile = () => { + const { profile, displayName } = useUserProfile(); + + return ( + + + + + + + + + + + + {displayName} + + + {profile.email} + + + + + + + + + + + + ); +}; diff --git a/packages/core/src/layout/Sidebar/Settings/SignInAvatar.tsx b/plugins/user-settings/src/components/General/SignInAvatar.tsx similarity index 72% rename from packages/core/src/layout/Sidebar/Settings/SignInAvatar.tsx rename to plugins/user-settings/src/components/General/SignInAvatar.tsx index f0430edfcf..8a5bbd75bf 100644 --- a/packages/core/src/layout/Sidebar/Settings/SignInAvatar.tsx +++ b/plugins/user-settings/src/components/General/SignInAvatar.tsx @@ -17,26 +17,24 @@ import React from 'react'; import { BackstageTheme } from '@backstage/theme'; import { makeStyles, Avatar } from '@material-ui/core'; -import { useUserProfile } from './useUserProfileInfo'; -import { sidebarConfig } from '../config'; +import { useUserProfile } from '../useUserProfileInfo'; +import { sidebarConfig } from '@backstage/core'; -const useStyles = makeStyles({ +const useStyles = makeStyles(theme => ({ avatar: { width: ({ size }) => size, height: ({ size }) => size, + fontSize: ({ size }) => size * 0.7, + border: `1px solid ${theme.palette.textSubtle}`, }, -}); +})); type Props = { size?: number }; export const SignInAvatar = ({ size }: Props) => { const { iconSize } = sidebarConfig; const classes = useStyles(size ? { size } : { size: iconSize }); - const { profile, displayName } = useUserProfile(); + const { profile } = useUserProfile(); - return ( - - {displayName[0]} - - ); + return ; }; diff --git a/plugins/user-settings/src/components/General/ThemeToggle.test.tsx b/plugins/user-settings/src/components/General/ThemeToggle.test.tsx new file mode 100644 index 0000000000..79d9210826 --- /dev/null +++ b/plugins/user-settings/src/components/General/ThemeToggle.test.tsx @@ -0,0 +1,58 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ApiProvider, + ApiRegistry, + appThemeApiRef, + AppThemeSelector, +} from '@backstage/core'; +import { renderWithEffects, wrapInTestApp } from '@backstage/test-utils'; +import { lightTheme } from '@backstage/theme'; +import { fireEvent } from '@testing-library/react'; +import React from 'react'; +import { ThemeToggle } from './ThemeToggle'; + +const mockTheme = { + id: 'light', + title: 'Mock Theme', + variant: 'light' as 'light', // wut? + theme: lightTheme, +}; + +const apiRegistry = ApiRegistry.from([ + [appThemeApiRef, AppThemeSelector.createWithStorage([mockTheme])], +]); + +describe('', () => { + it('toggles the theme select button', async () => { + const themeApi = apiRegistry.get(appThemeApiRef); + const rendered = await renderWithEffects( + wrapInTestApp( + + + , + ), + ); + + expect(rendered.getByText('Theme')).toBeInTheDocument(); + + const themeButton = rendered.getByTitle('Select Mock Theme'); + expect(themeApi?.getActiveThemeId()).toBe(undefined); + fireEvent.click(themeButton); + expect(themeApi?.getActiveThemeId()).toBe('light'); + }); +}); diff --git a/plugins/user-settings/src/components/General/ThemeToggle.tsx b/plugins/user-settings/src/components/General/ThemeToggle.tsx new file mode 100644 index 0000000000..e142b6bf1e --- /dev/null +++ b/plugins/user-settings/src/components/General/ThemeToggle.tsx @@ -0,0 +1,154 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { cloneElement } from 'react'; +import { useObservable } from 'react-use'; +import AutoIcon from '@material-ui/icons/BrightnessAuto'; +import { appThemeApiRef, useApi } from '@backstage/core'; +import ToggleButton from '@material-ui/lab/ToggleButton'; +import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup'; +import { + ListItem, + ListItemText, + ListItemSecondaryAction, + Tooltip, + makeStyles, +} from '@material-ui/core'; + +type ThemeIconProps = { + id: string; + activeId: string | undefined; + icon: JSX.Element | undefined; +}; + +const ThemeIcon = ({ id, activeId, icon }: ThemeIconProps) => + icon ? ( + cloneElement(icon, { + color: activeId === id ? 'primary' : undefined, + }) + ) : ( + + ); + +type TooltipToggleButtonProps = { + children: JSX.Element; + title: string; + value: string; +}; + +const useStyles = makeStyles(theme => ({ + list: { + [theme.breakpoints.down('xs')]: { + padding: `0 0 12px`, + }, + }, + listItemText: { + [theme.breakpoints.down('xs')]: { + paddingRight: 0, + paddingLeft: 0, + }, + }, + listItemSecondaryAction: { + [theme.breakpoints.down('xs')]: { + width: '100%', + top: 'auto', + right: 'auto', + position: 'relative', + transform: 'unset', + }, + }, +})); + +// ToggleButtonGroup uses React.children.map instead of context +// so wrapping with Tooltip breaks ToggleButton functionality. +const TooltipToggleButton = ({ + children, + title, + value, + ...props +}: TooltipToggleButtonProps) => ( + + + {children} + + +); + +export const ThemeToggle = () => { + const classes = useStyles(); + const appThemeApi = useApi(appThemeApiRef); + const themeId = useObservable( + appThemeApi.activeThemeId$(), + appThemeApi.getActiveThemeId(), + ); + + const themeIds = appThemeApi.getInstalledThemes(); + + const handleSetTheme = ( + _event: React.MouseEvent, + newThemeId: string | undefined, + ) => { + if (themeIds.some(t => t.id === newThemeId)) { + appThemeApi.setActiveThemeId(newThemeId); + } else { + appThemeApi.setActiveThemeId(undefined); + } + }; + + return ( + + + + + {themeIds.map(theme => { + const themeIcon = themeIds.find(t => t.id === theme.id)?.icon; + return ( + + <> + {theme.variant}  + + + + ); + })} + + + Auto  + + + + + + + ); +}; diff --git a/plugins/user-settings/src/components/General/UserSettingsMenu.test.tsx b/plugins/user-settings/src/components/General/UserSettingsMenu.test.tsx new file mode 100644 index 0000000000..c86d702e30 --- /dev/null +++ b/plugins/user-settings/src/components/General/UserSettingsMenu.test.tsx @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { renderWithEffects, wrapInTestApp } from '@backstage/test-utils'; +import { fireEvent } from '@testing-library/react'; +import React from 'react'; +import { UserSettingsMenu } from './UserSettingsMenu'; + +describe('', () => { + it('displays a menu button with a sign-out option', async () => { + const rendered = await renderWithEffects( + wrapInTestApp(), + ); + + const menuButton = rendered.getByLabelText('more'); + fireEvent.click(menuButton); + + expect(rendered.getByText('Sign Out')).toBeInTheDocument(); + }); +}); diff --git a/packages/core/src/layout/Sidebar/Settings/UserSettingsMenu.tsx b/plugins/user-settings/src/components/General/UserSettingsMenu.tsx similarity index 93% rename from packages/core/src/layout/Sidebar/Settings/UserSettingsMenu.tsx rename to plugins/user-settings/src/components/General/UserSettingsMenu.tsx index 151ddb6e75..19c3ee4e2d 100644 --- a/packages/core/src/layout/Sidebar/Settings/UserSettingsMenu.tsx +++ b/plugins/user-settings/src/components/General/UserSettingsMenu.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import { identityApiRef, useApi } from '@backstage/core-api'; +import { identityApiRef, useApi } from '@backstage/core'; import { IconButton, ListItemIcon, Menu, MenuItem } from '@material-ui/core'; import SignOutIcon from '@material-ui/icons/MeetingRoom'; import MoreVertIcon from '@material-ui/icons/MoreVert'; @@ -39,7 +39,7 @@ export const UserSettingsMenu = () => { return ( <> - + diff --git a/packages/app/src/plugins/cost-insights/index.ts b/plugins/user-settings/src/components/General/index.ts similarity index 87% rename from packages/app/src/plugins/cost-insights/index.ts rename to plugins/user-settings/src/components/General/index.ts index 47d540049f..2015d345fe 100644 --- a/packages/app/src/plugins/cost-insights/index.ts +++ b/plugins/user-settings/src/components/General/index.ts @@ -14,4 +14,5 @@ * limitations under the License. */ -export { ExampleCostInsightsClient } from './ExampleCostInsightsClient'; +export { General } from './General'; +export { SignInAvatar } from './SignInAvatar'; diff --git a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx b/plugins/user-settings/src/components/Settings.tsx similarity index 58% rename from plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx rename to plugins/user-settings/src/components/Settings.tsx index 03920887b8..f754f1e7c3 100644 --- a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx +++ b/plugins/user-settings/src/components/Settings.tsx @@ -13,24 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import React from 'react'; -import { Box } from '@material-ui/core'; +import { SidebarItem } from '@backstage/core'; +import { SignInAvatar } from './General'; +import { useUserProfile } from './useUserProfileInfo'; +import { settingsRouteRef } from '../plugin'; -type CostOverviewFooterProps = { - children?: React.ReactNode; +export const Settings = () => { + const { displayName } = useUserProfile(); + const SidebarAvatar = () => ; + + return ( + + ); }; - -const CostOverviewFooter = ({ children }: CostOverviewFooterProps) => ( - - {React.Children.map(children, child => ( - {child} - ))} - -); - -export default CostOverviewFooter; diff --git a/plugins/user-settings/src/components/SettingsPage.tsx b/plugins/user-settings/src/components/SettingsPage.tsx new file mode 100644 index 0000000000..0b4a86c99d --- /dev/null +++ b/plugins/user-settings/src/components/SettingsPage.tsx @@ -0,0 +1,52 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useState } from 'react'; +import { Content, Header, HeaderTabs, Page } from '@backstage/core'; +import { General } from './General'; +import { AuthProviders } from './AuthProviders'; +import { FeatureFlags } from './FeatureFlags'; + +type Props = { + providerSettings?: JSX.Element; +}; + +export const SettingsPage = ({ providerSettings }: Props) => { + const [activeTab, setActiveTab] = useState(0); + const onTabChange = (index: number) => { + setActiveTab(index); + }; + + const tabs = [ + { id: 'general', label: 'General' }, + { id: 'auth-providers', label: 'Authentication Providers' }, + { id: 'feature-flags', label: 'Feature Flags' }, + ]; + + const content = [ + , + , + , + ]; + + return ( + +
+ + {content[activeTab]} + + ); +}; diff --git a/packages/core/src/layout/Sidebar/Settings/useUserProfileInfo.ts b/plugins/user-settings/src/components/useUserProfileInfo.ts similarity index 93% rename from packages/core/src/layout/Sidebar/Settings/useUserProfileInfo.ts rename to plugins/user-settings/src/components/useUserProfileInfo.ts index 60dae294a5..428719160d 100644 --- a/packages/core/src/layout/Sidebar/Settings/useUserProfileInfo.ts +++ b/plugins/user-settings/src/components/useUserProfileInfo.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { useApi, identityApiRef } from '@backstage/core-api'; +import { useApi, identityApiRef } from '@backstage/core'; export const useUserProfile = () => { const identityApi = useApi(identityApiRef); diff --git a/plugins/user-settings/src/index.ts b/plugins/user-settings/src/index.ts new file mode 100644 index 0000000000..113930902a --- /dev/null +++ b/plugins/user-settings/src/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { plugin } from './plugin'; +export { Settings } from './components/Settings'; +export { SettingsPage as Router } from './components/SettingsPage'; diff --git a/plugins/user-settings/src/plugin.test.ts b/plugins/user-settings/src/plugin.test.ts new file mode 100644 index 0000000000..810a2cda12 --- /dev/null +++ b/plugins/user-settings/src/plugin.test.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { plugin } from './plugin'; + +describe('user-settings', () => { + it('should export plugin', () => { + expect(plugin).toBeDefined(); + }); +}); diff --git a/plugins/user-settings/src/plugin.ts b/plugins/user-settings/src/plugin.ts new file mode 100644 index 0000000000..2f896c8197 --- /dev/null +++ b/plugins/user-settings/src/plugin.ts @@ -0,0 +1,25 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createPlugin, createRouteRef } from '@backstage/core'; + +export const settingsRouteRef = createRouteRef({ + path: '/settings', + title: 'Settings', +}); + +export const plugin = createPlugin({ + id: 'user-settings', +}); diff --git a/plugins/user-settings/src/setupTests.ts b/plugins/user-settings/src/setupTests.ts new file mode 100644 index 0000000000..0bfa67b49a --- /dev/null +++ b/plugins/user-settings/src/setupTests.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '@testing-library/jest-dom'; diff --git a/plugins/welcome/package.json b/plugins/welcome/package.json index 80f930bbc2..380a4b0a46 100644 --- a/plugins/welcome/package.json +++ b/plugins/welcome/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-welcome", - "version": "0.1.1-alpha.24", + "version": "0.1.1-alpha.26", "main": "src/index.ts", "types": "src/index.ts", "private": false, @@ -21,8 +21,8 @@ "start": "backstage-cli plugin:serve" }, "dependencies": { - "@backstage/core": "^0.1.1-alpha.24", - "@backstage/theme": "^0.1.1-alpha.24", + "@backstage/core": "^0.1.1-alpha.26", + "@backstage/theme": "^0.1.1-alpha.26", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -32,16 +32,16 @@ "react-use": "^15.3.3" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.24", - "@backstage/dev-utils": "^0.1.1-alpha.24", + "@backstage/cli": "^0.1.1-alpha.26", + "@backstage/dev-utils": "^0.1.1-alpha.26", + "@backstage/test-utils": "^0.1.1-alpha.26", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5", - "node-fetch": "^2.6.1" + "cross-fetch": "^3.0.6", + "msw": "^0.21.2" }, "files": [ "dist" diff --git a/plugins/welcome/src/components/WelcomePage/WelcomePage.tsx b/plugins/welcome/src/components/WelcomePage/WelcomePage.tsx index 3ceb0af58d..7b94024948 100644 --- a/plugins/welcome/src/components/WelcomePage/WelcomePage.tsx +++ b/plugins/welcome/src/components/WelcomePage/WelcomePage.tsx @@ -30,7 +30,6 @@ import { Header, HomepageTimer, Page, - pageTheme, ContentHeader, SupportButton, WarningPanel, @@ -44,7 +43,7 @@ const WelcomePage = () => { const profile = { givenName: '' }; return ( - +
{ the project and we have already begun work on various aspects of these phases. The best way to keep track of the progress is through the  - + Milestones . @@ -113,7 +115,10 @@ const WelcomePage = () => { We suggest you either check out the documentation for{' '} - + creating a plugin {' '} or have a look in the code for the{' '} @@ -121,7 +126,10 @@ const WelcomePage = () => { existing plugins {' '} in the directory{' '} - + plugins/ . @@ -135,7 +143,10 @@ const WelcomePage = () => { backstage.io - + Create a plugin diff --git a/scripts/check-docs-quality.js b/scripts/check-docs-quality.js index 61968a2ac0..f29463939b 100755 --- a/scripts/check-docs-quality.js +++ b/scripts/check-docs-quality.js @@ -1,4 +1,3 @@ -#!/usr/bin/env node /* * Copyright 2020 Spotify AB * @@ -15,54 +14,76 @@ * limitations under the License. */ const { execSync, spawnSync } = require('child_process'); -const path = require('path'); - -const listFilesTrackedByGit = 'git ls-files'; +// eslint-disable-next-line import/no-extraneous-dependencies +const commandExists = require('command-exists'); const inheritStdIo = { stdio: 'inherit', }; -const ERROR_MESSAGE = - 'Please install vale linter(https://docs.errata.ai/vale/install). Ignore this message if already installed.\n'; +const LINT_SKIPPED_MESSAGE = + 'Skipping documentation quality check (vale not found). Install vale linter (https://docs.errata.ai/vale/install) to enable.\n'; +const LINT_ERROR_MESSAGE = `Language linter (vale) generated errors. Please check the errors and review any markdown files that you changed. + Possibly update .github/styles/vocab.txt to add new valid words.\n`; +const VALE_NOT_FOUND_MESSAGE = `Language linter (vale) was not found. Please install vale linter (https://docs.errata.ai/vale/install).\n`; -// xargs is not supported by shx. -if (process.platform === 'win32') { - const validMDFilesCommand = `${listFilesTrackedByGit} | .\\node_modules\\.bin\\shx grep ".md"`; - try { - // get list of all md files except in directories of gitignore. - let filesToLint = execSync(validMDFilesCommand, { - stdio: ['ignore', 'pipe', 'inherit'], - }); +// Note: Make sure the script is run as `node check-docs-quality.js [FILES]` instead of `./check-docs-quality.js [FILES]` +// If the script receives arguments (file paths), the script is run exclusively on them. (e.g. when run via pre-commit hook) +const getFilesToLint = () => { + // Files have been provided as arguments + if (process.argv.length > 2) { + return process.argv.slice(2); + } - // set all file(s) path as absolute path - filesToLint = filesToLint - .toString() - .split('\n') - .map(filepath => (filepath ? path.join(process.cwd(), filepath) : null)) - .filter(Boolean); + let command = `git ls-files | ./node_modules/.bin/shx grep ".md"`; + if (process.platform === 'win32') { + command = `git ls-files | .\\node_modules\\.bin\\shx grep ".md"`; + } - const output = spawnSync('vale', filesToLint, inheritStdIo); + return execSync(command, { + stdio: ['ignore', 'pipe', 'inherit'], + }) + .toString() + .split('\n'); +}; - // if the command does not succeed - if (output.status !== 0) { - // if it contains system level error. [in this case vale does not exist] - if (output.error) { - console.error(ERROR_MESSAGE); - } +// Proceed with the script only if Vale linter is installed. Limit the friction and surprises caused by the script. +// On CI, we want to ensure vale linter is run. +commandExists('vale') + .catch(() => { + if (process.env.CI) { + console.log(VALE_NOT_FOUND_MESSAGE); process.exit(1); } - } catch (e) { - console.error(e.message); - process.exit(1); - } -} else { - const validMDFilesCommand = `${listFilesTrackedByGit} | ./node_modules/.bin/shx grep ".md"`; - // use xargs - try { - execSync(`${validMDFilesCommand} | xargs vale`, inheritStdIo); - } catch (e) { - console.error(ERROR_MESSAGE); - process.exit(1); - } -} + console.log(LINT_SKIPPED_MESSAGE); + process.exit(0); + }) + .then(() => { + const filesToLint = getFilesToLint(); + + if (process.platform === 'win32') { + // Windows + try { + const output = spawnSync('vale', filesToLint, inheritStdIo); + + // If the command does not succeed + if (output.status !== 0) { + // If it contains system level error. In this case vale does not exist. + if (output.error) { + console.log(LINT_ERROR_MESSAGE); + } + process.exit(1); + } + } catch (e) { + console.log(e.message); + process.exit(1); + } + } else { + // Unix + const output = spawnSync('vale', filesToLint, inheritStdIo); + if (output.status !== 0) { + console.log(LINT_ERROR_MESSAGE); + process.exit(1); + } + } + }); diff --git a/yarn.lock b/yarn.lock index 9d7c53fb8c..ef52ed9918 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1194,7 +1194,7 @@ core-js-pure "^3.0.0" regenerator-runtime "^0.13.4" -"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.0", "@babel/runtime@^7.10.2", "@babel/runtime@^7.10.3", "@babel/runtime@^7.10.4", "@babel/runtime@^7.10.5", "@babel/runtime@^7.11.2", "@babel/runtime@^7.3.1", "@babel/runtime@^7.3.4", "@babel/runtime@^7.4.4", "@babel/runtime@^7.4.5", "@babel/runtime@^7.5.0", "@babel/runtime@^7.5.4", "@babel/runtime@^7.5.5", "@babel/runtime@^7.6.0", "@babel/runtime@^7.6.2", "@babel/runtime@^7.7.2", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2": +"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.0", "@babel/runtime@^7.10.2", "@babel/runtime@^7.10.3", "@babel/runtime@^7.10.4", "@babel/runtime@^7.10.5", "@babel/runtime@^7.11.2", "@babel/runtime@^7.3.1", "@babel/runtime@^7.3.4", "@babel/runtime@^7.4.4", "@babel/runtime@^7.4.5", "@babel/runtime@^7.5.0", "@babel/runtime@^7.5.4", "@babel/runtime@^7.5.5", "@babel/runtime@^7.6.0", "@babel/runtime@^7.6.2", "@babel/runtime@^7.6.3", "@babel/runtime@^7.7.2", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2": version "7.11.2" resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.11.2.tgz#f549c13c754cc40b87644b9fa9f09a6a95fe0736" integrity sha512-TeWkU52so0mPtDcaCTxNBI/IHiz0pZgr8VEFqXFtZWpYD08ZB6FaSwVAS8MKRQAP3bYKiVjwysOJgMFY28o6Tw== @@ -1325,10 +1325,10 @@ resolve-from "^5.0.0" semver "^5.4.1" -"@changesets/assemble-release-plan@^3.0.0", "@changesets/assemble-release-plan@^3.0.1": - version "3.0.1" - resolved "https://registry.npmjs.org/@changesets/assemble-release-plan/-/assemble-release-plan-3.0.1.tgz#cd501d0c57d435a594fc7bb630fa589d5b75c2a0" - integrity sha512-PChmYuibH8RPiebMIzuYZ/DFS8ehf7yq+X5X0rJklg2njP3zYWJX7nlctpnBhZ0zpgvP2IgrtUigoVGNkv5m/Q== +"@changesets/assemble-release-plan@^4.0.0": + version "4.0.0" + resolved "https://registry.npmjs.org/@changesets/assemble-release-plan/-/assemble-release-plan-4.0.0.tgz#60c2392c0e2c99f24778ab3a5c8e8c80ddaaaa59" + integrity sha512-3Kv21FNvysTQvZs3fHr6aZeDibhZHtgI1++fMZplzVtwNVmpjow3zv9lcZmJP26LthbpVH3I8+nqlU7M43lfWA== dependencies: "@babel/runtime" "^7.10.4" "@changesets/errors" "^0.1.4" @@ -1337,23 +1337,23 @@ "@manypkg/get-packages" "^1.0.1" semver "^5.4.1" -"@changesets/cli@2.10.2": - version "2.10.2" - resolved "https://registry.npmjs.org/@changesets/cli/-/cli-2.10.2.tgz#85a7a8d8aca2ef682c671f352645bc75c72f9b85" - integrity sha512-m4YwTmT0ElOuBD3GCbbT75EWmdU4uCFARE4X+Ml1/knc4Z/MEzOjV0bi0/9eHACcQIMNg7rdB6f4vXtHiQU6bA== +"@changesets/cli@^2.11.0": + version "2.11.0" + resolved "https://registry.npmjs.org/@changesets/cli/-/cli-2.11.0.tgz#048449289da95f24d96b187f3148c2955065d609" + integrity sha512-imsXWxl+QpLt6PYHSiuZS7xPdKrGs2c8saSG4ENzeZBgnTBMiJdxDloOT6Bmv15ICggHZj9mnaUBNOMPbvnlbA== dependencies: "@babel/runtime" "^7.10.4" "@changesets/apply-release-plan" "^4.0.0" - "@changesets/assemble-release-plan" "^3.0.1" - "@changesets/config" "^1.3.0" + "@changesets/assemble-release-plan" "^4.0.0" + "@changesets/config" "^1.4.0" "@changesets/errors" "^0.1.4" "@changesets/get-dependents-graph" "^1.1.3" - "@changesets/get-release-plan" "^2.0.0" + "@changesets/get-release-plan" "^2.0.1" "@changesets/git" "^1.0.6" "@changesets/logger" "^0.0.5" "@changesets/pre" "^1.0.4" "@changesets/read" "^0.4.6" - "@changesets/types" "^3.1.1" + "@changesets/types" "^3.2.0" "@changesets/write" "^0.1.3" "@manypkg/get-packages" "^1.0.1" "@types/semver" "^6.0.0" @@ -1373,7 +1373,7 @@ term-size "^2.1.0" tty-table "^2.7.0" -"@changesets/config@^1.2.0", "@changesets/config@^1.3.0": +"@changesets/config@^1.2.0": version "1.3.0" resolved "https://registry.npmjs.org/@changesets/config/-/config-1.3.0.tgz#82fcbf572b00ba16636be9ea45167983f1fc203b" integrity sha512-IeAHmN5kI7OywBUNJXsk/v4vcXDDscwgTe/K5D3FSng5QTvzbgiMAe5K1iwBxBvuT4u/33n89kxSJdg4TTTFfA== @@ -1385,6 +1385,19 @@ "@manypkg/get-packages" "^1.0.1" fs-extra "^7.0.1" +"@changesets/config@^1.4.0": + version "1.4.0" + resolved "https://registry.npmjs.org/@changesets/config/-/config-1.4.0.tgz#c157a4121f198b749f2bbc2e9015b6e976ece7d6" + integrity sha512-eoTOcJ6py7jBDY8rUXwEGxR5UtvUX+p//0NhkVpPGcnvIeITHq+DOIsuWyGzWcb+1FaYkof3CCr32/komZTu4Q== + dependencies: + "@changesets/errors" "^0.1.4" + "@changesets/get-dependents-graph" "^1.1.3" + "@changesets/logger" "^0.0.5" + "@changesets/types" "^3.2.0" + "@manypkg/get-packages" "^1.0.1" + fs-extra "^7.0.1" + micromatch "^4.0.2" + "@changesets/errors@^0.1.4": version "0.1.4" resolved "https://registry.npmjs.org/@changesets/errors/-/errors-0.1.4.tgz#f79851746c43679a66b383fdff4c012f480f480d" @@ -1403,13 +1416,13 @@ fs-extra "^7.0.1" semver "^5.4.1" -"@changesets/get-release-plan@^2.0.0": - version "2.0.0" - resolved "https://registry.npmjs.org/@changesets/get-release-plan/-/get-release-plan-2.0.0.tgz#570dbd0abcdd4169a73e8332ec139a01130f3b72" - integrity sha512-MHbgXMhkfWhXH1zUefrdtQ8IR+H46lAcKthKjptV28k0qGEcDk7KriYLukJ6BNkWiZkkZ/aycaivbNDclF9zaw== +"@changesets/get-release-plan@^2.0.1": + version "2.0.1" + resolved "https://registry.npmjs.org/@changesets/get-release-plan/-/get-release-plan-2.0.1.tgz#b95d8f1a3cc719ff4b42b9b9aae72458d8787c13" + integrity sha512-+x5N9/Iaka+c0Kq7+3JsboMNyffKYlWPmdm+VeafDcMwJFhBDkxm84qaCJ93ydmnzQOTig6gYVqw0k8BbHExyQ== dependencies: - "@babel/runtime" "^7.4.4" - "@changesets/assemble-release-plan" "^3.0.0" + "@babel/runtime" "^7.10.4" + "@changesets/assemble-release-plan" "^4.0.0" "@changesets/config" "^1.2.0" "@changesets/pre" "^1.0.4" "@changesets/read" "^0.4.6" @@ -1478,6 +1491,11 @@ resolved "https://registry.npmjs.org/@changesets/types/-/types-3.1.1.tgz#447481380c42044a8788e46c0dbdf592b338b62f" integrity sha512-XWGEGWXhM92zvBWiQt2sOwhjTt8eCQbrsRbqkv4WYwW3Zsl4qPpvhHsNt845S42dJXrxgjWvId+jxFQocCayNQ== +"@changesets/types@^3.2.0": + version "3.2.0" + resolved "https://registry.npmjs.org/@changesets/types/-/types-3.2.0.tgz#d8306d7219c3b19b6d860ddeb9d7374e2dd6b035" + integrity sha512-rAmPtOyXpisEEE25CchKNUAf2ApyAeuZ/h78YDoqKZaCk5tUD0lgYZGPIRV9WTPoqNjJULIym37ogc6pkax5jg== + "@changesets/write@^0.1.3": version "0.1.3" resolved "https://registry.npmjs.org/@changesets/write/-/write-0.1.3.tgz#00ae575af50274773d7493e77fb96838a08ad8ad" @@ -2235,93 +2253,93 @@ resolved "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.2.tgz#26520bf09abe4a5644cd5414e37125a8954241dd" integrity sha512-tsAQNx32a8CoFhjhijUIhI4kccIAgmGhy8LZMZgGfmXcpMbPRUqn5LWmgRttILi6yeGmBJd2xsPkFMs0PzgPCw== -"@jest/console@^26.3.0": - version "26.3.0" - resolved "https://registry.npmjs.org/@jest/console/-/console-26.3.0.tgz#ed04063efb280c88ba87388b6f16427c0a85c856" - integrity sha512-/5Pn6sJev0nPUcAdpJHMVIsA8sKizL2ZkcKPE5+dJrCccks7tcM7c9wbgHudBJbxXLoTbqsHkG1Dofoem4F09w== +"@jest/console@^26.5.2": + version "26.5.2" + resolved "https://registry.npmjs.org/@jest/console/-/console-26.5.2.tgz#94fc4865b1abed7c352b5e21e6c57be4b95604a6" + integrity sha512-lJELzKINpF1v74DXHbCRIkQ/+nUV1M+ntj+X1J8LxCgpmJZjfLmhFejiMSbjjD66fayxl5Z06tbs3HMyuik6rw== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" "@types/node" "*" chalk "^4.0.0" - jest-message-util "^26.3.0" - jest-util "^26.3.0" + jest-message-util "^26.5.2" + jest-util "^26.5.2" slash "^3.0.0" -"@jest/core@^26.4.2": - version "26.4.2" - resolved "https://registry.npmjs.org/@jest/core/-/core-26.4.2.tgz#85d0894f31ac29b5bab07aa86806d03dd3d33edc" - integrity sha512-sDva7YkeNprxJfepOctzS8cAk9TOekldh+5FhVuXS40+94SHbiicRO1VV2tSoRtgIo+POs/Cdyf8p76vPTd6dg== +"@jest/core@^26.5.3": + version "26.5.3" + resolved "https://registry.npmjs.org/@jest/core/-/core-26.5.3.tgz#712ed4adb64c3bda256a3f400ff1d3eb2a031f13" + integrity sha512-CiU0UKFF1V7KzYTVEtFbFmGLdb2g4aTtY0WlyUfLgj/RtoTnJFhh50xKKr7OYkdmBUlGFSa2mD1TU3UZ6OLd4g== dependencies: - "@jest/console" "^26.3.0" - "@jest/reporters" "^26.4.1" - "@jest/test-result" "^26.3.0" - "@jest/transform" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/console" "^26.5.2" + "@jest/reporters" "^26.5.3" + "@jest/test-result" "^26.5.2" + "@jest/transform" "^26.5.2" + "@jest/types" "^26.5.2" "@types/node" "*" ansi-escapes "^4.2.1" chalk "^4.0.0" exit "^0.1.2" graceful-fs "^4.2.4" - jest-changed-files "^26.3.0" - jest-config "^26.4.2" - jest-haste-map "^26.3.0" - jest-message-util "^26.3.0" + jest-changed-files "^26.5.2" + jest-config "^26.5.3" + jest-haste-map "^26.5.2" + jest-message-util "^26.5.2" jest-regex-util "^26.0.0" - jest-resolve "^26.4.0" - jest-resolve-dependencies "^26.4.2" - jest-runner "^26.4.2" - jest-runtime "^26.4.2" - jest-snapshot "^26.4.2" - jest-util "^26.3.0" - jest-validate "^26.4.2" - jest-watcher "^26.3.0" + jest-resolve "^26.5.2" + jest-resolve-dependencies "^26.5.3" + jest-runner "^26.5.3" + jest-runtime "^26.5.3" + jest-snapshot "^26.5.3" + jest-util "^26.5.2" + jest-validate "^26.5.3" + jest-watcher "^26.5.2" micromatch "^4.0.2" p-each-series "^2.1.0" rimraf "^3.0.0" slash "^3.0.0" strip-ansi "^6.0.0" -"@jest/environment@^26.3.0": - version "26.3.0" - resolved "https://registry.npmjs.org/@jest/environment/-/environment-26.3.0.tgz#e6953ab711ae3e44754a025f838bde1a7fd236a0" - integrity sha512-EW+MFEo0DGHahf83RAaiqQx688qpXgl99wdb8Fy67ybyzHwR1a58LHcO376xQJHfmoXTu89M09dH3J509cx2AA== +"@jest/environment@^26.5.2": + version "26.5.2" + resolved "https://registry.npmjs.org/@jest/environment/-/environment-26.5.2.tgz#eba3cfc698f6e03739628f699c28e8a07f5e65fe" + integrity sha512-YjhCD/Zhkz0/1vdlS/QN6QmuUdDkpgBdK4SdiVg4Y19e29g4VQYN5Xg8+YuHjdoWGY7wJHMxc79uDTeTOy9Ngw== dependencies: - "@jest/fake-timers" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/fake-timers" "^26.5.2" + "@jest/types" "^26.5.2" "@types/node" "*" - jest-mock "^26.3.0" + jest-mock "^26.5.2" -"@jest/fake-timers@^26.3.0": - version "26.3.0" - resolved "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-26.3.0.tgz#f515d4667a6770f60ae06ae050f4e001126c666a" - integrity sha512-ZL9ytUiRwVP8ujfRepffokBvD2KbxbqMhrXSBhSdAhISCw3gOkuntisiSFv+A6HN0n0fF4cxzICEKZENLmW+1A== +"@jest/fake-timers@^26.5.2": + version "26.5.2" + resolved "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-26.5.2.tgz#1291ac81680ceb0dc7daa1f92c059307eea6400a" + integrity sha512-09Hn5Oraqt36V1akxQeWMVL0fR9c6PnEhpgLaYvREXZJAh2H2Y+QLCsl0g7uMoJeoWJAuz4tozk1prbR1Fc1sw== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" "@sinonjs/fake-timers" "^6.0.1" "@types/node" "*" - jest-message-util "^26.3.0" - jest-mock "^26.3.0" - jest-util "^26.3.0" + jest-message-util "^26.5.2" + jest-mock "^26.5.2" + jest-util "^26.5.2" -"@jest/globals@^26.4.2": - version "26.4.2" - resolved "https://registry.npmjs.org/@jest/globals/-/globals-26.4.2.tgz#73c2a862ac691d998889a241beb3dc9cada40d4a" - integrity sha512-Ot5ouAlehhHLRhc+sDz2/9bmNv9p5ZWZ9LE1pXGGTCXBasmi5jnYjlgYcYt03FBwLmZXCZ7GrL29c33/XRQiow== +"@jest/globals@^26.5.3": + version "26.5.3" + resolved "https://registry.npmjs.org/@jest/globals/-/globals-26.5.3.tgz#90769b40e0af3fa0b28f6d8c5bbe3712467243fd" + integrity sha512-7QztI0JC2CuB+Wx1VdnOUNeIGm8+PIaqngYsZXQCkH2QV0GFqzAYc9BZfU0nuqA6cbYrWh5wkuMzyii3P7deug== dependencies: - "@jest/environment" "^26.3.0" - "@jest/types" "^26.3.0" - expect "^26.4.2" + "@jest/environment" "^26.5.2" + "@jest/types" "^26.5.2" + expect "^26.5.3" -"@jest/reporters@^26.4.1": - version "26.4.1" - resolved "https://registry.npmjs.org/@jest/reporters/-/reporters-26.4.1.tgz#3b4d6faf28650f3965f8b97bc3d114077fb71795" - integrity sha512-aROTkCLU8++yiRGVxLsuDmZsQEKO6LprlrxtAuzvtpbIFl3eIjgIf3EUxDKgomkS25R9ZzwGEdB5weCcBZlrpQ== +"@jest/reporters@^26.5.3": + version "26.5.3" + resolved "https://registry.npmjs.org/@jest/reporters/-/reporters-26.5.3.tgz#e810e9c2b670f33f1c09e9975749260ca12f1c17" + integrity sha512-X+vR0CpfMQzYcYmMFKNY9n4jklcb14Kffffp7+H/MqitWnb0440bW2L76NGWKAa+bnXhNoZr+lCVtdtPmfJVOQ== dependencies: "@bcoe/v8-coverage" "^0.2.3" - "@jest/console" "^26.3.0" - "@jest/test-result" "^26.3.0" - "@jest/transform" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/console" "^26.5.2" + "@jest/test-result" "^26.5.2" + "@jest/transform" "^26.5.2" + "@jest/types" "^26.5.2" chalk "^4.0.0" collect-v8-coverage "^1.0.0" exit "^0.1.2" @@ -2332,63 +2350,63 @@ istanbul-lib-report "^3.0.0" istanbul-lib-source-maps "^4.0.0" istanbul-reports "^3.0.2" - jest-haste-map "^26.3.0" - jest-resolve "^26.4.0" - jest-util "^26.3.0" - jest-worker "^26.3.0" + jest-haste-map "^26.5.2" + jest-resolve "^26.5.2" + jest-util "^26.5.2" + jest-worker "^26.5.0" slash "^3.0.0" source-map "^0.6.0" string-length "^4.0.1" terminal-link "^2.0.0" - v8-to-istanbul "^5.0.1" + v8-to-istanbul "^6.0.1" optionalDependencies: node-notifier "^8.0.0" -"@jest/source-map@^26.3.0": - version "26.3.0" - resolved "https://registry.npmjs.org/@jest/source-map/-/source-map-26.3.0.tgz#0e646e519883c14c551f7b5ae4ff5f1bfe4fc3d9" - integrity sha512-hWX5IHmMDWe1kyrKl7IhFwqOuAreIwHhbe44+XH2ZRHjrKIh0LO5eLQ/vxHFeAfRwJapmxuqlGAEYLadDq6ZGQ== +"@jest/source-map@^26.5.0": + version "26.5.0" + resolved "https://registry.npmjs.org/@jest/source-map/-/source-map-26.5.0.tgz#98792457c85bdd902365cd2847b58fff05d96367" + integrity sha512-jWAw9ZwYHJMe9eZq/WrsHlwF8E3hM9gynlcDpOyCb9bR8wEd9ZNBZCi7/jZyzHxC7t3thZ10gO2IDhu0bPKS5g== dependencies: callsites "^3.0.0" graceful-fs "^4.2.4" source-map "^0.6.0" -"@jest/test-result@^26.3.0": - version "26.3.0" - resolved "https://registry.npmjs.org/@jest/test-result/-/test-result-26.3.0.tgz#46cde01fa10c0aaeb7431bf71e4a20d885bc7fdb" - integrity sha512-a8rbLqzW/q7HWheFVMtghXV79Xk+GWwOK1FrtimpI5n1la2SY0qHri3/b0/1F0Ve0/yJmV8pEhxDfVwiUBGtgg== +"@jest/test-result@^26.5.2": + version "26.5.2" + resolved "https://registry.npmjs.org/@jest/test-result/-/test-result-26.5.2.tgz#cc1a44cfd4db2ecee3fb0bc4e9fe087aa54b5230" + integrity sha512-E/Zp6LURJEGSCWpoMGmCFuuEI1OWuI3hmZwmULV0GsgJBh7u0rwqioxhRU95euUuviqBDN8ruX/vP/4bwYolXw== dependencies: - "@jest/console" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/console" "^26.5.2" + "@jest/types" "^26.5.2" "@types/istanbul-lib-coverage" "^2.0.0" collect-v8-coverage "^1.0.0" -"@jest/test-sequencer@^26.4.2": - version "26.4.2" - resolved "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-26.4.2.tgz#58a3760a61eec758a2ce6080201424580d97cbba" - integrity sha512-83DRD8N3M0tOhz9h0bn6Kl6dSp+US6DazuVF8J9m21WAp5x7CqSMaNycMP0aemC/SH/pDQQddbsfHRTBXVUgog== +"@jest/test-sequencer@^26.5.3": + version "26.5.3" + resolved "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-26.5.3.tgz#9ae0ab9bc37d5171b28424029192e50229814f8d" + integrity sha512-Wqzb7aQ13L3T47xHdpUqYMOpiqz6Dx2QDDghp5AV/eUDXR7JieY+E1s233TQlNyl+PqtqgjVokmyjzX/HA51BA== dependencies: - "@jest/test-result" "^26.3.0" + "@jest/test-result" "^26.5.2" graceful-fs "^4.2.4" - jest-haste-map "^26.3.0" - jest-runner "^26.4.2" - jest-runtime "^26.4.2" + jest-haste-map "^26.5.2" + jest-runner "^26.5.3" + jest-runtime "^26.5.3" -"@jest/transform@^26.3.0": - version "26.3.0" - resolved "https://registry.npmjs.org/@jest/transform/-/transform-26.3.0.tgz#c393e0e01459da8a8bfc6d2a7c2ece1a13e8ba55" - integrity sha512-Isj6NB68QorGoFWvcOjlUhpkT56PqNIsXKR7XfvoDlCANn/IANlh8DrKAA2l2JKC3yWSMH5wS0GwuQM20w3b2A== +"@jest/transform@^26.5.2": + version "26.5.2" + resolved "https://registry.npmjs.org/@jest/transform/-/transform-26.5.2.tgz#6a0033a1d24316a1c75184d010d864f2c681bef5" + integrity sha512-AUNjvexh+APhhmS8S+KboPz+D3pCxPvEAGduffaAJYxIFxGi/ytZQkrqcKDUU0ERBAo5R7087fyOYr2oms1seg== dependencies: "@babel/core" "^7.1.0" - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" babel-plugin-istanbul "^6.0.0" chalk "^4.0.0" convert-source-map "^1.4.0" fast-json-stable-stringify "^2.0.0" graceful-fs "^4.2.4" - jest-haste-map "^26.3.0" + jest-haste-map "^26.5.2" jest-regex-util "^26.0.0" - jest-util "^26.3.0" + jest-util "^26.5.2" micromatch "^4.0.2" pirates "^4.0.1" slash "^3.0.0" @@ -2416,6 +2434,17 @@ "@types/yargs" "^15.0.0" chalk "^4.0.0" +"@jest/types@^26.5.2": + version "26.5.2" + resolved "https://registry.npmjs.org/@jest/types/-/types-26.5.2.tgz#44c24f30c8ee6c7f492ead9ec3f3c62a5289756d" + integrity sha512-QDs5d0gYiyetI8q+2xWdkixVQMklReZr4ltw7GFDtb4fuJIBCE6mzj2LnitGqCuAlLap6wPyb8fpoHgwZz5fdg== + dependencies: + "@types/istanbul-lib-coverage" "^2.0.0" + "@types/istanbul-reports" "^3.0.0" + "@types/node" "*" + "@types/yargs" "^15.0.0" + chalk "^4.0.0" + "@jsdevtools/ono@^7.1.3": version "7.1.3" resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz#9df03bbd7c696a5c58885c34aa06da41c8543796" @@ -3599,10 +3628,10 @@ prop-types "^15.6.1" react-lifecycles-compat "^3.0.4" -"@rjsf/core@^2.1.0": - version "2.3.0" - resolved "https://registry.npmjs.org/@rjsf/core/-/core-2.3.0.tgz#334c73d2262ef1a8cda477e238067af7336c5599" - integrity sha512-OZKYHt9tjKhzOH4CvsPiCwepuIacqI++cNmnL2fsxh1IF+uEWGlo3NLDWhhSaBbOv9jps6a5YQcLbLtjNuSwug== +"@rjsf/core@^2.4.0": + version "2.4.0" + resolved "https://registry.npmjs.org/@rjsf/core/-/core-2.4.0.tgz#c50bcff0d8178948ce08123177399d8816d51929" + integrity sha512-8zlydBkGldOxGXFEwNGFa1gzTxpcxaYn7ofegcu8XHJ7IKMCfpnU3ABg+H3eml1KZCX3FODmj1tHFJKuTmfynw== dependencies: "@babel/runtime-corejs2" "^7.8.7" "@types/json-schema" "^7.0.4" @@ -3616,20 +3645,40 @@ react-is "^16.9.0" shortid "^2.2.14" -"@rjsf/material-ui@^2.1.0": - version "2.3.0" - resolved "https://registry.npmjs.org/@rjsf/material-ui/-/material-ui-2.3.0.tgz#a051eb4db2ad778e39933a31ba806f415dd3ba90" - integrity sha512-v/xZ4Xk18ZgBARcCe99IDqdO97GU0UC784gG8PhGGFDdy5Rbdy7ixTjHkGYttkr43PB7SX6ttohNhkKSW4nATQ== +"@rjsf/material-ui@^2.4.0": + version "2.4.0" + resolved "https://registry.npmjs.org/@rjsf/material-ui/-/material-ui-2.4.0.tgz#1b5859298bf3f61137d7b05084f058a775d6fd73" + integrity sha512-U8F/suzg4MuV+8mK1/ufs0Y6c3O8hc1wnuD2IKoOVJvegGfz5JCafyoyGAW6iyuT1DZBMPzVWEqfiuYPmoE7pw== -"@roadiehq/backstage-plugin-github-pull-requests@^0.4.3": - version "0.4.3" - resolved "https://registry.npmjs.org/@roadiehq/backstage-plugin-github-pull-requests/-/backstage-plugin-github-pull-requests-0.4.3.tgz#720fd3c53ae8e61d8cfc727cda47e236af442b02" - integrity sha512-IJGMys5FJ512sitaMwWgACll3ZTuE3nZUX05MNXly/WXty6VBcfboiPbSB6IzLAEWMmvYlV1YUwwL7hAl/62GQ== +"@roadiehq/backstage-plugin-github-insights@^0.2.7": + version "0.2.7" + resolved "https://registry.npmjs.org/@roadiehq/backstage-plugin-github-insights/-/backstage-plugin-github-insights-0.2.7.tgz#b8e86af9215270d8c02fca4f2f32880ff84c0503" + integrity sha512-oYqGkAkPa2pvlk+tDgTOkdhTUdLvc71x4FRZI82h1aaPzrz7DODooU644Qsduc5yYiXicbFkvMUk1b3fjL4Dxw== dependencies: - "@backstage/catalog-model" "^0.1.1-alpha.23" - "@backstage/core" "^0.1.1-alpha.23" - "@backstage/plugin-catalog" "^0.1.1-alpha.23" - "@backstage/theme" "^0.1.1-alpha.23" + "@backstage/catalog-model" "^0.1.1-alpha.24" + "@backstage/core" "^0.1.1-alpha.24" + "@backstage/theme" "^0.1.1-alpha.24" + "@material-ui/core" "^4.11.0" + "@material-ui/icons" "^4.9.1" + "@material-ui/lab" "4.0.0-alpha.45" + "@octokit/rest" "^18.0.0" + "@octokit/types" "^5.0.1" + history "^5.0.0" + react "^16.13.1" + react-dom "^16.13.1" + react-markdown "^4.3.1" + react-router "^6.0.0-beta.0" + react-use "^15.3.3" + +"@roadiehq/backstage-plugin-github-pull-requests@^0.5.2": + version "0.5.2" + resolved "https://registry.npmjs.org/@roadiehq/backstage-plugin-github-pull-requests/-/backstage-plugin-github-pull-requests-0.5.2.tgz#455355fe5cdcc43c22b80a8ef3697378084680a1" + integrity sha512-GM+nWQZ+aehMclN70Pp35UQe3I46SQCjWiGZ6/0TfDzrueHln39L2UspUj1L/713xDDtDK8ZnTJdFn/qKx7j4A== + dependencies: + "@backstage/catalog-model" "^0.1.1-alpha.25" + "@backstage/core" "^0.1.1-alpha.25" + "@backstage/plugin-catalog" "^0.1.1-alpha.25" + "@backstage/theme" "^0.1.1-alpha.25" "@material-ui/core" "^4.11.0" "@material-ui/icons" "^4.9.1" "@material-ui/lab" "^4.0.0-alpha.56" @@ -3643,16 +3692,16 @@ react-router "6.0.0-beta.0" react-use "^15.3.3" -"@roadiehq/backstage-plugin-travis-ci@^0.2.3": - version "0.2.3" - resolved "https://registry.npmjs.org/@roadiehq/backstage-plugin-travis-ci/-/backstage-plugin-travis-ci-0.2.3.tgz#2d1c5a7ed3eab4fdcf95243b73dee44c0cff5a57" - integrity sha512-Xi8vZFbcm+D4ykyU3I9hImAd22F1v6M1F/H9CJanRHqj5esJxnuCS2+Kf+w09bwb9DuM8/c68PuMlf3PMIsOwg== +"@roadiehq/backstage-plugin-travis-ci@^0.2.5": + version "0.2.5" + resolved "https://registry.npmjs.org/@roadiehq/backstage-plugin-travis-ci/-/backstage-plugin-travis-ci-0.2.5.tgz#588cd8b4a4dd4bd426c0012f8d35eae4504b55f4" + integrity sha512-4aJizmvIeunpl8D/YDvzagNzikPU51DSZFz1tN0XCwRR+buTPknV141qsKP+yxUbs6nx3Xuh+T/vNkb9lk6FlA== dependencies: - "@backstage/catalog-model" "^0.1.1-alpha.22" - "@backstage/core" "^0.1.1-alpha.22" - "@backstage/core-api" "^0.1.1-alpha.22" - "@backstage/plugin-catalog" "^0.1.1-alpha.22" - "@backstage/theme" "^0.1.1-alpha.22" + "@backstage/catalog-model" "^0.1.1-alpha.24" + "@backstage/core" "^0.1.1-alpha.24" + "@backstage/core-api" "^0.1.1-alpha.24" + "@backstage/plugin-catalog" "^0.1.1-alpha.24" + "@backstage/theme" "^0.1.1-alpha.24" "@material-ui/core" "^4.9.1" "@material-ui/icons" "^4.9.1" "@material-ui/lab" "4.0.0-alpha.45" @@ -3666,18 +3715,18 @@ react-router-dom "6.0.0-beta.0" react-use "^15.3.3" -"@rollup/plugin-commonjs@^13.0.0": - version "13.0.0" - resolved "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-13.0.0.tgz#8a1d684ba6848afe8b9e3d85649d4b2f6f7217ec" - integrity sha512-Anxc3qgkAi7peAyesTqGYidG5GRim9jtg8xhmykNaZkImtvjA7Wsqep08D2mYsqw1IF7rA3lYfciLgzUSgRoqw== +"@rollup/plugin-commonjs@^16.0.0": + version "16.0.0" + resolved "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-16.0.0.tgz#169004d56cd0f0a1d0f35915d31a036b0efe281f" + integrity sha512-LuNyypCP3msCGVQJ7ki8PqYdpjfEkE/xtFa5DqlF+7IBD0JsfMZ87C58heSwIMint58sAUZbt3ITqOmdQv/dXw== dependencies: - "@rollup/pluginutils" "^3.0.8" + "@rollup/pluginutils" "^3.1.0" commondir "^1.0.1" - estree-walker "^1.0.1" - glob "^7.1.2" - is-reference "^1.1.2" - magic-string "^0.25.2" - resolve "^1.11.0" + estree-walker "^2.0.1" + glob "^7.1.6" + is-reference "^1.2.1" + magic-string "^0.25.7" + resolve "^1.17.0" "@rollup/plugin-json@^4.0.2": version "4.1.0" @@ -3686,15 +3735,14 @@ dependencies: "@rollup/pluginutils" "^3.0.8" -"@rollup/plugin-node-resolve@^8.1.0": - version "8.4.0" - resolved "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-8.4.0.tgz#261d79a680e9dc3d86761c14462f24126ba83575" - integrity sha512-LFqKdRLn0ShtQyf6SBYO69bGE1upV6wUhBX0vFOUnLAyzx5cwp8svA0eHUnu8+YU57XOkrMtfG63QOpQx25pHQ== +"@rollup/plugin-node-resolve@^9.0.0": + version "9.0.0" + resolved "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-9.0.0.tgz#39bd0034ce9126b39c1699695f440b4b7d2b62e6" + integrity sha512-gPz+utFHLRrd41WMP13Jq5mqqzHL3OXrfj3/MkSyB6UBIcuNt9j60GCbarzMzdf1VHFpOxfQh/ez7wyadLMqkg== dependencies: "@rollup/pluginutils" "^3.1.0" "@types/resolve" "1.17.1" builtin-modules "^3.1.0" - deep-freeze "^0.0.1" deepmerge "^4.2.2" is-module "^1.0.0" resolve "^1.17.0" @@ -3753,11 +3801,6 @@ dependencies: "@sinonjs/commons" "^1.7.0" -"@spotify/eslint-config-base@^7.0.0": - version "7.0.0" - resolved "https://registry.npmjs.org/@spotify/eslint-config-base/-/eslint-config-base-7.0.0.tgz#36804ae09ec938f1aa5f9464ea993f3f151cfaa8" - integrity sha512-XRTrTRyRRYBxPYINKNHw4B8QWlA3p4I+id/Po2sMdejtXH3LZgDgIjdschUZSdQ6J6dVYDdaVykdizRM9I+G6Q== - "@spotify/eslint-config-base@^8.0.0": version "8.0.0" resolved "https://registry.npmjs.org/@spotify/eslint-config-base/-/eslint-config-base-8.0.0.tgz#c3d10d8a05ad9129d579952cb80063e4c4fa216e" @@ -3770,103 +3813,32 @@ dependencies: eslint-plugin-notice "^0.9.10" -"@spotify/eslint-config-react@^7.0.1": - version "7.0.1" - resolved "https://registry.npmjs.org/@spotify/eslint-config-react/-/eslint-config-react-7.0.1.tgz#2e70de9d7911ea9aeaa55a83a332220a28f6c431" - integrity sha512-HNDHvm19EaBXiDgsg52mjMgKWZTeA0hO2Q75ACNwb8UtjIKkANqyyuzyDGo8jiGMbWIm6wJjShlRtT95emNlqQ== - -"@spotify/eslint-config-react@^8.0.2": +"@spotify/eslint-config-react@^8.0.0": version "8.0.2" resolved "https://registry.npmjs.org/@spotify/eslint-config-react/-/eslint-config-react-8.0.2.tgz#91af3c58b22d49a96795336ed66927e722cda430" integrity sha512-V0gzO/jWmjhODLINAfeunHj+OBdj/cQeVDw+92ZUlkonAg6BZLjX6Vy8jeIUFjfgmVOtI9eKbcApxaurj1jN6g== -"@spotify/eslint-config-typescript@^7.0.0": - version "7.0.0" - resolved "https://registry.npmjs.org/@spotify/eslint-config-typescript/-/eslint-config-typescript-7.0.0.tgz#fc5227e3344f74b41ac3a530df24a95ac13254e4" - integrity sha512-28I/SAf68NKbWZ5IY0WYMa0D18PxWdC9DP9gRbOTlZufmsS8jEgqf3zBUWmP6XOf1nihpKWcqvbFUG5H7/JYXA== - -"@spotify/eslint-config-typescript@^8.0.1": - version "8.0.1" - resolved "https://registry.npmjs.org/@spotify/eslint-config-typescript/-/eslint-config-typescript-8.0.1.tgz#2d3ee56a8a3f945454109086639cde47251d1e62" - integrity sha512-ALkA4WA2ZikX7grkptZ36J1N/iap0IJeViy6/ZcxSkm6yEy2BYslmS2MdoJ5PV/DfZ3Z/21d/+XYFqVEpcbrXg== - -"@spotify/eslint-config@^7.0.0": - version "7.0.1" - resolved "https://registry.npmjs.org/@spotify/eslint-config/-/eslint-config-7.0.1.tgz#07a21cfd7fce89cfc2c6dd5ea5d747e741201b66" - integrity sha512-8GI/TZGUhS4pr7oipT2MjrZFRgXcKzk9YImEusUdD2f5vlCniRFIBQNrvTMkyjfdQqvIVqJPLcdVPXeAgprsMw== - dependencies: - "@spotify/eslint-config-base" "^7.0.0" - "@spotify/eslint-config-react" "^7.0.1" - "@spotify/eslint-config-typescript" "^7.0.0" - "@spotify/web-scripts-utils" "^7.0.0" - "@typescript-eslint/eslint-plugin" "^2.14.0" - "@typescript-eslint/parser" "^2.14.0" - eslint-config-prettier "^6.0.0" - eslint-plugin-jest "^23.6.0" - eslint-plugin-jsx-a11y "^6.2.1" - eslint-plugin-react "^7.12.4" - eslint-plugin-react-hooks "^4.0.0" - -"@spotify/eslint-config@^8.1.0": - version "8.1.0" - resolved "https://registry.npmjs.org/@spotify/eslint-config/-/eslint-config-8.1.0.tgz#00801a892a8f51df3f1074f7bc695052df4c9cd6" - integrity sha512-A3THg4Y2eK+hijUO+kt2ZL278XciFo/s/pwZ93c4/cYwFXYf1mcB2tmnmhP/6kK4QxF7rYmO8nYJMwPZ1sOkyQ== - dependencies: - "@spotify/eslint-config-base" "^8.0.0" - "@spotify/eslint-config-react" "^8.0.2" - "@spotify/eslint-config-typescript" "^8.0.1" - "@spotify/eslint-plugin" "^8.1.0" - "@spotify/web-scripts-utils" "^8.0.0" - "@typescript-eslint/eslint-plugin" "^3.4.0" - "@typescript-eslint/parser" "^3.4.0" - eslint-config-prettier "^6.0.0" - eslint-plugin-jest "^23.17.1" - eslint-plugin-jsx-a11y "^6.2.1" - eslint-plugin-react "^7.12.4" - eslint-plugin-react-hooks "^4.0.0" - -"@spotify/eslint-plugin@^8.1.0": - version "8.1.0" - resolved "https://registry.npmjs.org/@spotify/eslint-plugin/-/eslint-plugin-8.1.0.tgz#a9c5f971537c647d20d6f8c608018aec8d1b882a" - integrity sha512-/VBOF0vMRhVQFqdsNQ5NKhZeD8IWimqKZzsp2yrjLKDajXOfCsA8VpCtm/j4T6/8j/mqb7Rz9ePT+thHfGtBxg== - -"@spotify/prettier-config@^7.0.0": - version "7.0.0" - resolved "https://registry.npmjs.org/@spotify/prettier-config/-/prettier-config-7.0.0.tgz#47750979d1282197295108b6958360660a955c16" - integrity sha512-lIMcx/2oDqTtW84iHKkRJe+8U6HK6GPwWH5sJp9UEHcDpdXomOQYvwcGXy2I2zwPQQ14gYYE6nEJuSnnYqsYRw== +"@spotify/eslint-config-typescript@^8.0.0": + version "8.1.1" + resolved "https://registry.npmjs.org/@spotify/eslint-config-typescript/-/eslint-config-typescript-8.1.1.tgz#a8c6f74ef9445fe740008ae3a26003a2eef78f93" + integrity sha512-0NkE6ZiSRf9IBWwCxzn/l7UdwcL/KZsbzjjOSweafyYueajEn+eIpKjOgDGUL/ebxSrOtjEp+YeFc4lSPkP0qg== "@spotify/prettier-config@^8.0.0": version "8.0.0" resolved "https://registry.npmjs.org/@spotify/prettier-config/-/prettier-config-8.0.0.tgz#8b6c2bd579ddc54887155a0721fe04e96c89f7f2" integrity sha512-so8w32ZV42CHWxOEXcBtbNO/hLXFrQNXVmhfzhUI6dVB9cq2xjRaiqu8GjFj8LvKbWpPj+S+KwTIS4aDVWqrFQ== -"@spotify/web-scripts-utils@^7.0.0": - version "7.0.0" - resolved "https://registry.npmjs.org/@spotify/web-scripts-utils/-/web-scripts-utils-7.0.0.tgz#8c6b8039fc645a36ac48629eb9ba06600f4d828a" - integrity sha512-McMy0j60lxOHjgDjegthZqEWN/PabphiM30A/mI/Y7xh9+JFnYWBTSm/wgn6EW2BsPpV631xSYYkk6B1Ph14Fw== - dependencies: - glob "^7.1.4" - read-pkg-up "^7.0.1" - -"@spotify/web-scripts-utils@^8.0.0": - version "8.0.0" - resolved "https://registry.npmjs.org/@spotify/web-scripts-utils/-/web-scripts-utils-8.0.0.tgz#83e49a0050e0ca553769cea4052fe438bc0378a7" - integrity sha512-5ADUaRRW+ZJHYhfSiaJVVq+9hVfAin+WYaJzEd/3oTvd6P1BrVsAdyxBdmXtacTHu+vjlVoye/kxdpUhlIq9Iw== - dependencies: - glob "^7.1.4" - read-pkg-up "^7.0.1" - "@storybook/addon-actions@^6.0.21": - version "6.0.21" - resolved "https://registry.npmjs.org/@storybook/addon-actions/-/addon-actions-6.0.21.tgz#0de1d109d4b1eb99f644bbe84e74c25cfd2b1b6b" - integrity sha512-9y3ve+3GK1TsxQ5pxDjhB7E/XJXY+WqcSNlOX8Mb+XbS6AAgpFbkZCw1q8CGzyEUclHsQ6UK2+lo+IRGs4TLpA== + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/addon-actions/-/addon-actions-6.0.26.tgz#d0de9e4d78a8f8f5bf8730c04d0b6d1741c29273" + integrity sha512-9tWbAqSwzWWVz8zwAndZFusZYjIcRYgZUC0LqC8QlH79DgF3ASjw9y97+w1VTTAzdb6LYnsMuSpX6+8m5hrR4g== dependencies: - "@storybook/addons" "6.0.21" - "@storybook/api" "6.0.21" - "@storybook/client-api" "6.0.21" - "@storybook/components" "6.0.21" - "@storybook/core-events" "6.0.21" - "@storybook/theming" "6.0.21" + "@storybook/addons" "6.0.26" + "@storybook/api" "6.0.26" + "@storybook/client-api" "6.0.26" + "@storybook/components" "6.0.26" + "@storybook/core-events" "6.0.26" + "@storybook/theming" "6.0.26" core-js "^3.0.1" fast-deep-equal "^3.1.1" global "^4.3.2" @@ -3919,7 +3891,7 @@ react-syntax-highlighter "^12.2.1" regenerator-runtime "^0.13.3" -"@storybook/addons@6.0.21", "@storybook/addons@^6.0.21": +"@storybook/addons@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/addons/-/addons-6.0.21.tgz#bd5229652102c3aed59b78ef6920ff6b482b4d78" integrity sha512-yDttNLc3vXqBxwK795ykgzTC6MpvuXDQuF4LHSlHZQe6wsMu1m3fljnbYdafJWdx6cNZwUblU3KYcR11PqhkPg== @@ -3934,6 +3906,21 @@ global "^4.3.2" regenerator-runtime "^0.13.3" +"@storybook/addons@6.0.26", "@storybook/addons@^6.0.21": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/addons/-/addons-6.0.26.tgz#343cbea3eee2d39413b80bc2d66535a7f61488fc" + integrity sha512-OhAApFKgsj9an7FLYfHI4cJQuZ4Zm6yoGOpaxhOvKQMw7dXUPsLvbCyw/6dZOLvaFhjJjQiXtbxtZG+UjR8nvA== + dependencies: + "@storybook/api" "6.0.26" + "@storybook/channels" "6.0.26" + "@storybook/client-logger" "6.0.26" + "@storybook/core-events" "6.0.26" + "@storybook/router" "6.0.26" + "@storybook/theming" "6.0.26" + core-js "^3.0.1" + global "^4.3.2" + regenerator-runtime "^0.13.3" + "@storybook/api@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/api/-/api-6.0.21.tgz#a25a1eb4d07dc43500e03c856db43baba46726f1" @@ -3960,6 +3947,32 @@ ts-dedent "^1.1.1" util-deprecate "^1.0.2" +"@storybook/api@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/api/-/api-6.0.26.tgz#c45222c132eb8bc2e383536adfebbeb7a89867d0" + integrity sha512-aszDoz1c6T+eRtTUwWvySoyd3gRXmQxsingD084NnEp4VfFLA5H7VS/0sre0ZvU5GWh8d9COxY0DS2Ry/QSKvw== + dependencies: + "@reach/router" "^1.3.3" + "@storybook/channels" "6.0.26" + "@storybook/client-logger" "6.0.26" + "@storybook/core-events" "6.0.26" + "@storybook/csf" "0.0.1" + "@storybook/router" "6.0.26" + "@storybook/semver" "^7.3.2" + "@storybook/theming" "6.0.26" + "@types/reach__router" "^1.3.5" + core-js "^3.0.1" + fast-deep-equal "^3.1.1" + global "^4.3.2" + lodash "^4.17.15" + memoizerific "^1.11.3" + react "^16.8.3" + regenerator-runtime "^0.13.3" + store2 "^2.7.1" + telejson "^5.0.2" + ts-dedent "^1.1.1" + util-deprecate "^1.0.2" + "@storybook/channel-postmessage@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/channel-postmessage/-/channel-postmessage-6.0.21.tgz#97e8f43c1b66f84c7b8271e447d45d4f66d355d1" @@ -3973,6 +3986,19 @@ qs "^6.6.0" telejson "^5.0.2" +"@storybook/channel-postmessage@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/channel-postmessage/-/channel-postmessage-6.0.26.tgz#a98a0132d6bdf06741afac2607e9feabe34ab98b" + integrity sha512-FT6lC8M5JlNBxPT0rYfmF1yl9mBv04nfYs82TZpp1CzpLxf7wxdCBZ8SSRmvWIVBoNwGZPDhIk5+6JWyDEISBg== + dependencies: + "@storybook/channels" "6.0.26" + "@storybook/client-logger" "6.0.26" + "@storybook/core-events" "6.0.26" + core-js "^3.0.1" + global "^4.3.2" + qs "^6.6.0" + telejson "^5.0.2" + "@storybook/channels@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/channels/-/channels-6.0.21.tgz#bc0951efacbaa5f8827693fba4fe7c2290b5772c" @@ -3982,6 +4008,15 @@ ts-dedent "^1.1.1" util-deprecate "^1.0.2" +"@storybook/channels@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/channels/-/channels-6.0.26.tgz#3e8678b4b40085081257a39b9e85fab13a19943c" + integrity sha512-H0iUorayYqS+zfhbjd+cYRzAdRLGLWUeWFu2Aa+oJ4/zeAQNL+DafWboHc567RQ4Vb5KqE5QZoCFskWUUYqJYA== + dependencies: + core-js "^3.0.1" + ts-dedent "^1.1.1" + util-deprecate "^1.0.2" + "@storybook/client-api@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/client-api/-/client-api-6.0.21.tgz#6a652dea67d219a31d18af0e05b9f17ba6c7c316" @@ -4005,6 +4040,29 @@ ts-dedent "^1.1.1" util-deprecate "^1.0.2" +"@storybook/client-api@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/client-api/-/client-api-6.0.26.tgz#ac9334ba86834e5cb23fc4fb577de60bda66164d" + integrity sha512-Qd5wR5b5lio/EchuJMhAmmJAE1pfvnEyu+JnyFGwMZLV9mN9NSspz+YsqbSCCDZsYcP5ewvPEnumIWqmj/wagQ== + dependencies: + "@storybook/addons" "6.0.26" + "@storybook/channel-postmessage" "6.0.26" + "@storybook/channels" "6.0.26" + "@storybook/client-logger" "6.0.26" + "@storybook/core-events" "6.0.26" + "@storybook/csf" "0.0.1" + "@types/qs" "^6.9.0" + "@types/webpack-env" "^1.15.2" + core-js "^3.0.1" + global "^4.3.2" + lodash "^4.17.15" + memoizerific "^1.11.3" + qs "^6.6.0" + stable "^0.1.8" + store2 "^2.7.1" + ts-dedent "^1.1.1" + util-deprecate "^1.0.2" + "@storybook/client-logger@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/client-logger/-/client-logger-6.0.21.tgz#20369addf9eb79fc0c85a2e0dcb48f5a1a544532" @@ -4013,6 +4071,14 @@ core-js "^3.0.1" global "^4.3.2" +"@storybook/client-logger@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/client-logger/-/client-logger-6.0.26.tgz#e3d28bd8dc02ec2c53a9d69773a68189590b746f" + integrity sha512-VNoL6/oehVhn3hZi9vrTNT+C/3oAZKV+smfZFnPtsCR/Fq7CKbmsBd0pGPL57f81RU8e8WygwrIlAGJTDSNIjw== + dependencies: + core-js "^3.0.1" + global "^4.3.2" + "@storybook/components@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/components/-/components-6.0.21.tgz#2f355370f993e0b7b9062094a03dffc2cdda91db" @@ -4041,6 +4107,34 @@ react-textarea-autosize "^8.1.1" ts-dedent "^1.1.1" +"@storybook/components@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/components/-/components-6.0.26.tgz#e1f6e16aae850a71c9ac7bdd1d44a068ec9cfdc1" + integrity sha512-8wigI1pDFJO1m1IQWPguOK+nOsaAVRWkVdu+2te/rDcIR9QNvMzzou0+Lhfp3zKSVT4E6mEoGB/TWXXF5Iq0sQ== + dependencies: + "@storybook/client-logger" "6.0.26" + "@storybook/csf" "0.0.1" + "@storybook/theming" "6.0.26" + "@types/overlayscrollbars" "^1.9.0" + "@types/react-color" "^3.0.1" + "@types/react-syntax-highlighter" "11.0.4" + core-js "^3.0.1" + fast-deep-equal "^3.1.1" + global "^4.3.2" + lodash "^4.17.15" + markdown-to-jsx "^6.11.4" + memoizerific "^1.11.3" + overlayscrollbars "^1.10.2" + polished "^3.4.4" + popper.js "^1.14.7" + react "^16.8.3" + react-color "^2.17.0" + react-dom "^16.8.3" + react-popper-tooltip "^2.11.0" + react-syntax-highlighter "^12.2.1" + react-textarea-autosize "^8.1.1" + ts-dedent "^1.1.1" + "@storybook/core-events@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/core-events/-/core-events-6.0.21.tgz#2ce51e6d7524e7543dbb29571beac1dbeb4e5f40" @@ -4048,6 +4142,13 @@ dependencies: core-js "^3.0.1" +"@storybook/core-events@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/core-events/-/core-events-6.0.26.tgz#61181c9a8610d26cc85d47f133a563879044ca2d" + integrity sha512-nWjS/+kMiw31OPgeJQaiFsJk9ZJJo3/d4c+kc6GOl2iC1H3Q4/5cm3NvJBn/7bUtKHmSFwfbDouj+XjUk5rZbQ== + dependencies: + core-js "^3.0.1" + "@storybook/core@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/core/-/core-6.0.21.tgz#105c2b90ab27e7b478cb1b7d10e9fe5aba5e0708" @@ -4207,6 +4308,18 @@ memoizerific "^1.11.3" qs "^6.6.0" +"@storybook/router@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/router/-/router-6.0.26.tgz#5b991001afa7d7eb5e40c53cd4c58266b6f9edfd" + integrity sha512-kQ1LF/2gX3IkjS1wX7CsoeBc9ptHQzOsyax16rUyJa769DT5vMNtFtQxjNXMqSiSapPg2yrXJFKQNaoWvKgQEQ== + dependencies: + "@reach/router" "^1.3.3" + "@types/reach__router" "^1.3.5" + core-js "^3.0.1" + global "^4.3.2" + memoizerific "^1.11.3" + qs "^6.6.0" + "@storybook/semver@^7.3.2": version "7.3.2" resolved "https://registry.npmjs.org/@storybook/semver/-/semver-7.3.2.tgz#f3b9c44a1c9a0b933c04e66d0048fcf2fa10dac0" @@ -4249,6 +4362,24 @@ resolve-from "^5.0.0" ts-dedent "^1.1.1" +"@storybook/theming@6.0.26": + version "6.0.26" + resolved "https://registry.npmjs.org/@storybook/theming/-/theming-6.0.26.tgz#e5b545fb2653dfd1b043b567197d490b1c3c0da3" + integrity sha512-9yon2ofb9a+RT1pdvn8Njydy7XRw0qXcIsMqGsJRKoZecmRRozqB6DxH9Gbdf1vRSbM9gYUUDjbiMDFz7+4RiQ== + dependencies: + "@emotion/core" "^10.0.20" + "@emotion/is-prop-valid" "^0.8.6" + "@emotion/styled" "^10.0.17" + "@storybook/client-logger" "6.0.26" + core-js "^3.0.1" + deep-object-diff "^1.1.0" + emotion-theming "^10.0.19" + global "^4.3.2" + memoizerific "^1.11.3" + polished "^3.4.4" + resolve-from "^5.0.0" + ts-dedent "^1.1.1" + "@storybook/ui@6.0.21": version "6.0.21" resolved "https://registry.npmjs.org/@storybook/ui/-/ui-6.0.21.tgz#5dac2b68a30f5dba5457e0315f58977e07138968" @@ -4544,17 +4675,16 @@ pretty-format "^26.4.2" "@testing-library/jest-dom@^5.10.1": - version "5.10.1" - resolved "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-5.10.1.tgz#6508a9f007bd74e5d3c0b3135b668027ab663989" - integrity sha512-uv9lLAnEFRzwUTN/y9lVVXVXlEzazDkelJtM5u92PsGkEasmdI+sfzhZHxSDzlhZVTrlLfuMh2safMr8YmzXLg== + version "5.11.4" + resolved "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-5.11.4.tgz#f325c600db352afb92995c2576022b35621ddc99" + integrity sha512-6RRn3epuweBODDIv3dAlWjOEHQLpGJHB2i912VS3JQtsD22+ENInhdDNl4ZZQiViLlIfFinkSET/J736ytV9sw== dependencies: "@babel/runtime" "^7.9.2" "@types/testing-library__jest-dom" "^5.9.1" + aria-query "^4.2.2" chalk "^3.0.0" - css "^2.2.4" + css "^3.0.0" css.escape "^1.5.1" - jest-diff "^25.1.0" - jest-matcher-utils "^25.1.0" lodash "^4.17.15" redent "^3.0.0" @@ -4699,6 +4829,13 @@ dependencies: "@babel/types" "^7.3.0" +"@types/babel__traverse@^7.0.4": + version "7.0.15" + resolved "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.0.15.tgz#db9e4238931eb69ef8aab0ad6523d4d4caa39d03" + integrity sha512-Pzh9O3sTK8V6I1olsXpCfj2k/ygO2q1X0vhhnDrEQyYLHZesWz+zMZMVcwXLCYf0U36EtmyYaFGPfXlTtDHe3A== + dependencies: + "@babel/types" "^7.3.0" + "@types/body-parser@*", "@types/body-parser@1.19.0", "@types/body-parser@^1.19.0": version "1.19.0" resolved "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.0.tgz#0685b3c47eb3006ffed117cdd55164b61f80538f" @@ -5213,6 +5350,11 @@ resolved "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== +"@types/minimist@^1.2.0": + version "1.2.0" + resolved "https://registry.npmjs.org/@types/minimist/-/minimist-1.2.0.tgz#69a23a3ad29caf0097f06eda59b361ee2f0639f6" + integrity sha1-aaI6OtKcrwCX8G7aWbNh7i8GOfY= + "@types/minipass@*": version "2.2.0" resolved "https://registry.npmjs.org/@types/minipass/-/minipass-2.2.0.tgz#51ad404e8eb1fa961f75ec61205796807b6f9651" @@ -5227,6 +5369,13 @@ dependencies: "@types/node" "*" +"@types/mock-fs@^4.13.0": + version "4.13.0" + resolved "https://registry.npmjs.org/@types/mock-fs/-/mock-fs-4.13.0.tgz#b8b01cd2db588668b2532ecd21b1babd3fffb2c0" + integrity sha512-FUqxhURwqFtFBCuUj3uQMp7rPSQs//b3O9XecAVxhqS9y4/W8SIJEZFq2mmpnFVZBXwR/2OyPLE97CpyYiB8Mw== + dependencies: + "@types/node" "*" + "@types/morgan@^1.9.0": version "1.9.1" resolved "https://registry.npmjs.org/@types/morgan/-/morgan-1.9.1.tgz#6457872df95647c1dbc6b3741e8146b71ece74bf" @@ -5234,7 +5383,7 @@ dependencies: "@types/node" "*" -"@types/node-fetch@2.5.7", "@types/node-fetch@^2.5.4", "@types/node-fetch@^2.5.7": +"@types/node-fetch@2.5.7", "@types/node-fetch@^2.5.4": version "2.5.7" resolved "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.7.tgz#20a2afffa882ab04d44ca786449a276f9f6bbf3c" integrity sha512-o2WVNf5UhWRkxlf6eq+jMZDu7kjgpgJfl4xVNlvryc95O/6F2ld8ztKX+qu+Rjyet93WAWm5LjeX9H5FGkODvw== @@ -5247,22 +5396,12 @@ resolved "https://registry.npmjs.org/@types/node/-/node-14.0.26.tgz#22a3b8a46510da8944b67bfc27df02c34a35331c" integrity sha512-W+fpe5s91FBGE0pEa0lnqGLL4USgpLgs4nokw16SrBBco/gQxuua7KnArSEOd5iaMqbbSHV10vUDkJYJJqpXKA== -"@types/node@^10.1.0": - version "10.17.28" - resolved "https://registry.npmjs.org/@types/node/-/node-10.17.28.tgz#0e36d718a29355ee51cec83b42d921299200f6d9" - integrity sha512-dzjES1Egb4c1a89C7lKwQh8pwjYmlOAG9dW1pBgxEk57tMrLnssOfEthz8kdkNaBd7lIqQx7APm5+mZ619IiCQ== - -"@types/node@^10.12.0": +"@types/node@^10.1.0", "@types/node@^10.12.0": version "10.17.35" resolved "https://registry.npmjs.org/@types/node/-/node-10.17.35.tgz#58058f29b870e6ae57b20e4f6e928f02b7129f56" integrity sha512-gXx7jAWpMddu0f7a+L+txMplp3FnHl53OhQIF9puXKq3hDGY/GjH+MF04oWnV/adPSCrbtHumDCFwzq2VhltWA== -"@types/node@^12.0.0": - version "12.12.53" - resolved "https://registry.npmjs.org/@types/node/-/node-12.12.53.tgz#be0d375933c3d15ef2380dafb3b0350ea7021129" - integrity sha512-51MYTDTyCziHb70wtGNFRwB4l+5JNvdqzFSkbDvpbftEgVUBEE+T5f7pROhWMp/fxp07oNIEQZd5bbfAH22ohQ== - -"@types/node@^12.7.1": +"@types/node@^12.0.0", "@types/node@^12.7.1": version "12.12.58" resolved "https://registry.npmjs.org/@types/node/-/node-12.12.58.tgz#46dae9b2b9ee5992818c8f7cee01ff4ce03ab44c" integrity sha512-Be46CNIHWAagEfINOjmriSxuv7IVcqbGe+sDSg2SYCEz/0CRBy7LRASGfRbD8KZkqoePU73Wsx3UvOSFcq/9hA== @@ -5272,10 +5411,10 @@ resolved "https://registry.npmjs.org/@types/node/-/node-13.13.15.tgz#fe1cc3aa465a3ea6858b793fd380b66c39919766" integrity sha512-kwbcs0jySLxzLsa2nWUAGOd/s21WU1jebrEdtzhsj1D4Yps1EOuyI1Qcu+FD56dL7NRNIJtDDjcqIG22NwkgLw== -"@types/nodegit@0.26.8": - version "0.26.8" - resolved "https://registry.npmjs.org/@types/nodegit/-/nodegit-0.26.8.tgz#81a79307fbdd1cf028a8ec7cbc94020bac54be6f" - integrity sha512-CwcynPazar6cJxjn8PG2RIujNgFvH2pAoA/bBBvPTUrONVzc9hj0DRMYzioy7zI/+e8TfJJLP+DK26mEU0eErg== +"@types/nodegit@0.26.11": + version "0.26.11" + resolved "https://registry.npmjs.org/@types/nodegit/-/nodegit-0.26.11.tgz#0cbc5e929f23e5ffc536920e3a887e0b3f46d1a4" + integrity sha512-BGrY9F8lBtfU+Ne1Pjb9k/PUsfSCUAqPXgKkTkM6mc5213H5VAoM12zG/sz/cr3jI3AXcngNbAYWlqSrXsWJug== dependencies: "@types/node" "*" @@ -5356,9 +5495,9 @@ "@types/passport" "*" "@types/passport@*", "@types/passport@^1.0.3": - version "1.0.3" - resolved "https://registry.npmjs.org/@types/passport/-/passport-1.0.3.tgz#e459ed6c262bf0686684d1b05901be0d0b192a9c" - integrity sha512-nyztuxtDPQv9utCzU0qW7Gl8BY2Dn8BKlYAFFyxKipFxjaVd96celbkLCV/tRqqBUZ+JB8If3UfgV8347DTo3Q== + version "1.0.4" + resolved "https://registry.npmjs.org/@types/passport/-/passport-1.0.4.tgz#1b35c4e197560d3974fa5f71711b6e9cce0711f0" + integrity sha512-h5OfAbfBBYSzjeU0GTuuqYEk9McTgWeGQql9g3gUw2/NNCfD7VgExVRYJVVeU13Twn202Mvk9BT0bUrl30sEgA== dependencies: "@types/express" "*" @@ -5382,6 +5521,11 @@ resolved "https://registry.npmjs.org/@types/qs/-/qs-6.9.4.tgz#a59e851c1ba16c0513ea123830dd639a0a15cb6a" integrity sha512-+wYo+L6ZF6BMoEjtf8zB2esQsqdV6WsjRK/GP9WOgLPrq87PbNWgIxS76dS5uvl/QXtHGakZmwTznIfcPXcKlQ== +"@types/raf@^3.4.0": + version "3.4.0" + resolved "https://registry.npmjs.org/@types/raf/-/raf-3.4.0.tgz#2b72cbd55405e071f1c4d29992638e022b20acc2" + integrity sha512-taW5/WYqo36N7V39oYyHP9Ipfd5pNFvGTIQsNGj86xV88YQ7GnI30/yMfKDF7Zgin0m3e+ikX88FvImnK4RjGw== + "@types/range-parser@*": version "1.2.3" resolved "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.3.tgz#7ee330ba7caafb98090bece86a5ee44115904c2c" @@ -5508,6 +5652,11 @@ dependencies: "@types/node" "*" +"@types/regression@^2.0.0": + version "2.0.0" + resolved "https://registry.npmjs.org/@types/regression/-/regression-2.0.0.tgz#0677ea78d7bdb37039c02ebbccf062042f756ae3" + integrity sha512-Ch2FD53M1HpFLL6zSTc/sfuyqQcIPy+/PV3xFT6QYtk9EOiMI29XOYmLNxBb1Y0lfMOR/NNa86J1gRc/1jGLyw== + "@types/relateurl@*": version "0.2.28" resolved "https://registry.npmjs.org/@types/relateurl/-/relateurl-0.2.28.tgz#6bda7db8653fa62643f5ee69e9f69c11a392e3a6" @@ -5589,10 +5738,10 @@ resolved "https://registry.npmjs.org/@types/source-list-map/-/source-list-map-0.1.2.tgz#0078836063ffaf17412349bba364087e0ac02ec9" integrity sha512-K5K+yml8LTo9bWJI/rECfIPrGgxdpeNbj+d53lwN4QjW1MCwlkhUms+gtdzigTeUyBr09+u8BwOIY3MXvHdcsA== -"@types/stack-utils@^1.0.1": - version "1.0.1" - resolved "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-1.0.1.tgz#0a851d3bd96498fa25c33ab7278ed3bd65f06c3e" - integrity sha512-l42BggppR6zLmpfU6fq9HEa2oGPEI8yrSPL3GITjfRInppYFahObbIQOQK3UGxEnyQpltZLaPe75046NOZQikw== +"@types/stack-utils@^2.0.0": + version "2.0.0" + resolved "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.0.tgz#7036640b4e21cc2f259ae826ce843d277dad8cff" + integrity sha512-RJJrrySY7A8havqpGObOB4W92QXKJo63/jFLLgpvOtsGUqbQZ9Sbgl35KMm1DjC6j7AvmmU2bIno+3IyEaemaw== "@types/start-server-webpack-plugin@^2.2.0": version "2.2.0" @@ -5755,9 +5904,9 @@ source-map "^0.6.1" "@types/webpack@*", "@types/webpack@^4.41.7", "@types/webpack@^4.41.8": - version "4.41.21" - resolved "https://registry.npmjs.org/@types/webpack/-/webpack-4.41.21.tgz#cc685b332c33f153bb2f5fc1fa3ac8adeb592dee" - integrity sha512-2j9WVnNrr/8PLAB5csW44xzQSJwS26aOnICsP3pSGCEdsu6KYtfQ6QJsVUKHWRnm1bL7HziJsfh5fHqth87yKA== + version "4.41.22" + resolved "https://registry.npmjs.org/@types/webpack/-/webpack-4.41.22.tgz#ff9758a17c6bd499e459b91e78539848c32d0731" + integrity sha512-JQDJK6pj8OMV9gWOnN1dcLCyU9Hzs6lux0wBO4lr1+gyEhIBR9U3FMrz12t2GPkg110XAxEAw2WHF6g7nZIbRQ== dependencies: "@types/anymatch" "*" "@types/node" "*" @@ -5811,28 +5960,17 @@ dependencies: "@types/yargs-parser" "*" -"@types/yup@^0.28.2": - version "0.28.3" - resolved "https://registry.npmjs.org/@types/yup/-/yup-0.28.3.tgz#387c35f9a6a36b8d3561f6601eb4e72518b92899" - integrity sha512-0Sir2LxOmupF8HBUvpJoZghLmOqKfZsBk1GYlMwSIccLDDUoN04LHvo0KzDp9qxt1IKf9Fudpj35SrJ8VqetkQ== +"@types/yup@^0.29.8": + version "0.29.8" + resolved "https://registry.npmjs.org/@types/yup/-/yup-0.29.8.tgz#83db15735987db9fe5a38772a0fb9500e3c5bf39" + integrity sha512-MBSp62AjB1KrSOI3gX9GekddXU5YYQAVA93+aSl78biBqoSzxg876aQY2KJK5Gnfbpqq7O2cadVX5kPAtBqIXw== "@types/zen-observable@^0.8.0": version "0.8.0" resolved "https://registry.npmjs.org/@types/zen-observable/-/zen-observable-0.8.0.tgz#8b63ab7f1aa5321248aad5ac890a485656dcea4d" integrity sha512-te5lMAWii1uEJ4FwLjzdlbw3+n0FZNOvFXHxQDKeT0dilh7HOzdMzV2TrJVUzq8ep7J4Na8OUYPRLSQkJHAlrg== -"@typescript-eslint/eslint-plugin@^2.14.0": - version "2.24.0" - resolved "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.24.0.tgz#a86cf618c965a462cddf3601f594544b134d6d68" - integrity sha512-wJRBeaMeT7RLQ27UQkDFOu25MqFOBus8PtOa9KaT5ZuxC1kAsd7JEHqWt4YXuY9eancX0GK9C68i5OROnlIzBA== - dependencies: - "@typescript-eslint/experimental-utils" "2.24.0" - eslint-utils "^1.4.3" - functional-red-black-tree "^1.0.1" - regexpp "^3.0.0" - tsutils "^3.17.1" - -"@typescript-eslint/eslint-plugin@^3.4.0": +"@typescript-eslint/eslint-plugin@^v3.10.1": version "3.10.1" resolved "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-3.10.1.tgz#7e061338a1383f59edc204c605899f93dc2e2c8f" integrity sha512-PQg0emRtzZFWq6PxBcdxRH3QIQiyFO3WCVpRL3fgj5oQS3CDs3AeAKfv4DxNhzn8ITdNJGJ4D3Qw8eAJf3lXeQ== @@ -5844,15 +5982,6 @@ semver "^7.3.2" tsutils "^3.17.1" -"@typescript-eslint/experimental-utils@2.24.0", "@typescript-eslint/experimental-utils@^2.5.0": - version "2.24.0" - resolved "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.24.0.tgz#a5cb2ed89fedf8b59638dc83484eb0c8c35e1143" - integrity sha512-DXrwuXTdVh3ycNCMYmWhUzn/gfqu9N0VzNnahjiDJvcyhfBy4gb59ncVZVxdp5XzBC77dCncu0daQgOkbvPwBw== - dependencies: - "@types/json-schema" "^7.0.3" - "@typescript-eslint/typescript-estree" "2.24.0" - eslint-scope "^5.0.0" - "@typescript-eslint/experimental-utils@3.10.1": version "3.10.1" resolved "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-3.10.1.tgz#e179ffc81a80ebcae2ea04e0332f8b251345a686" @@ -5864,17 +5993,19 @@ eslint-scope "^5.0.0" eslint-utils "^2.0.0" -"@typescript-eslint/parser@^2.14.0": - version "2.24.0" - resolved "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-2.24.0.tgz#2cf0eae6e6dd44d162486ad949c126b887f11eb8" - integrity sha512-H2Y7uacwSSg8IbVxdYExSI3T7uM1DzmOn2COGtCahCC3g8YtM1xYAPi2MAHyfPs61VKxP/J/UiSctcRgw4G8aw== +"@typescript-eslint/experimental-utils@^4.0.1": + version "4.4.1" + resolved "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.4.1.tgz#40613b9757fa0170de3e0043254dbb077cafac0c" + integrity sha512-Nt4EVlb1mqExW9cWhpV6pd1a3DkUbX9DeyYsdoeziKOpIJ04S2KMVDO+SEidsXRH/XHDpbzXykKcMTLdTXH6cQ== dependencies: - "@types/eslint-visitor-keys" "^1.0.0" - "@typescript-eslint/experimental-utils" "2.24.0" - "@typescript-eslint/typescript-estree" "2.24.0" - eslint-visitor-keys "^1.1.0" + "@types/json-schema" "^7.0.3" + "@typescript-eslint/scope-manager" "4.4.1" + "@typescript-eslint/types" "4.4.1" + "@typescript-eslint/typescript-estree" "4.4.1" + eslint-scope "^5.0.0" + eslint-utils "^2.0.0" -"@typescript-eslint/parser@^3.4.0": +"@typescript-eslint/parser@^v3.10.1": version "3.10.1" resolved "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-3.10.1.tgz#1883858e83e8b442627e1ac6f408925211155467" integrity sha512-Ug1RcWcrJP02hmtaXVS3axPPTTPnZjupqhgj+NnZ6BCkwSImWk/283347+x9wN+lqOdK9Eo3vsyiyDHgsmiEJw== @@ -5885,23 +6016,23 @@ "@typescript-eslint/typescript-estree" "3.10.1" eslint-visitor-keys "^1.1.0" +"@typescript-eslint/scope-manager@4.4.1": + version "4.4.1" + resolved "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.4.1.tgz#d19447e60db2ce9c425898d62fa03b2cce8ea3f9" + integrity sha512-2oD/ZqD4Gj41UdFeWZxegH3cVEEH/Z6Bhr/XvwTtGv66737XkR4C9IqEkebCuqArqBJQSj4AgNHHiN1okzD/wQ== + dependencies: + "@typescript-eslint/types" "4.4.1" + "@typescript-eslint/visitor-keys" "4.4.1" + "@typescript-eslint/types@3.10.1": version "3.10.1" resolved "https://registry.npmjs.org/@typescript-eslint/types/-/types-3.10.1.tgz#1d7463fa7c32d8a23ab508a803ca2fe26e758727" integrity sha512-+3+FCUJIahE9q0lDi1WleYzjCwJs5hIsbugIgnbB+dSCYUxl8L6PwmsyOPFZde2hc1DlTo/xnkOgiTLSyAbHiQ== -"@typescript-eslint/typescript-estree@2.24.0": - version "2.24.0" - resolved "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.24.0.tgz#38bbc8bb479790d2f324797ffbcdb346d897c62a" - integrity sha512-RJ0yMe5owMSix55qX7Mi9V6z2FDuuDpN6eR5fzRJrp+8in9UF41IGNQHbg5aMK4/PjVaEQksLvz0IA8n+Mr/FA== - dependencies: - debug "^4.1.1" - eslint-visitor-keys "^1.1.0" - glob "^7.1.6" - is-glob "^4.0.1" - lodash "^4.17.15" - semver "^6.3.0" - tsutils "^3.17.1" +"@typescript-eslint/types@4.4.1": + version "4.4.1" + resolved "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.4.1.tgz#c507b35cf523bc7ba00aae5f75ee9b810cdabbc1" + integrity sha512-KNDfH2bCyax5db+KKIZT4rfA8rEk5N0EJ8P0T5AJjo5xrV26UAzaiqoJCxeaibqc0c/IvZxp7v2g3difn2Pn3w== "@typescript-eslint/typescript-estree@3.10.1": version "3.10.1" @@ -5917,6 +6048,20 @@ semver "^7.3.2" tsutils "^3.17.1" +"@typescript-eslint/typescript-estree@4.4.1": + version "4.4.1" + resolved "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.4.1.tgz#598f6de488106c2587d47ca2462c60f6e2797cb8" + integrity sha512-wP/V7ScKzgSdtcY1a0pZYBoCxrCstLrgRQ2O9MmCUZDtmgxCO/TCqOTGRVwpP4/2hVfqMz/Vw1ZYrG8cVxvN3g== + dependencies: + "@typescript-eslint/types" "4.4.1" + "@typescript-eslint/visitor-keys" "4.4.1" + debug "^4.1.1" + globby "^11.0.1" + is-glob "^4.0.1" + lodash "^4.17.15" + semver "^7.3.2" + tsutils "^3.17.1" + "@typescript-eslint/visitor-keys@3.10.1": version "3.10.1" resolved "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-3.10.1.tgz#cd4274773e3eb63b2e870ac602274487ecd1e931" @@ -5924,6 +6069,14 @@ dependencies: eslint-visitor-keys "^1.1.0" +"@typescript-eslint/visitor-keys@4.4.1": + version "4.4.1" + resolved "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.4.1.tgz#1769dc7a9e2d7d2cfd3318b77ed8249187aed5c3" + integrity sha512-H2JMWhLaJNeaylSnMSQFEhT/S/FsJbebQALmoJxMPMxLtlVAMy2uJP/Z543n9IizhjRayLSqoInehCeNW9rWcw== + dependencies: + "@typescript-eslint/types" "4.4.1" + eslint-visitor-keys "^2.0.0" + "@webassemblyjs/ast@1.9.0": version "1.9.0" resolved "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.9.0.tgz#bd850604b4042459a5a41cd7d338cbed695ed964" @@ -6120,11 +6273,6 @@ JSONStream@^1.0.4, JSONStream@^1.3.4: jsonparse "^1.2.0" through ">=2.2.7 <3" -abab@^1.0.0: - version "1.0.4" - resolved "https://registry.npmjs.org/abab/-/abab-1.0.4.tgz#5faad9c2c07f60dd76770f71cf025b62a63cfd4e" - integrity sha1-X6rZwsB/YN12dw9xzwJbYqY8/U4= - abab@^2.0.0, abab@^2.0.3: version "2.0.3" resolved "https://registry.npmjs.org/abab/-/abab-2.0.3.tgz#623e2075e02eb2d3f2475e49f99c91846467907a" @@ -6148,13 +6296,6 @@ accepts@^1.3.5, accepts@~1.3.4, accepts@~1.3.5, accepts@~1.3.7: mime-types "~2.1.24" negotiator "0.6.2" -acorn-globals@^1.0.4: - version "1.0.9" - resolved "https://registry.npmjs.org/acorn-globals/-/acorn-globals-1.0.9.tgz#55bb5e98691507b74579d0513413217c380c54cf" - integrity sha1-VbtemGkVB7dFedBRNBMhfDgMVM8= - dependencies: - acorn "^2.1.0" - acorn-globals@^4.1.0: version "4.3.4" resolved "https://registry.npmjs.org/acorn-globals/-/acorn-globals-4.3.4.tgz#9fa1926addc11c97308c4e66d7add0d40c3272e7" @@ -6186,11 +6327,6 @@ acorn-walk@^7.1.1: resolved "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.1.1.tgz#345f0dffad5c735e7373d2fec9a1023e6a44b83e" integrity sha512-wdlPY2tm/9XBr7QkKlq0WQVgiuGTX6YWPyRyBviSoScBuLfTVQhvwg6wJ369GJ/1nPfTLMfnrFIfjqVg6d+jQQ== -acorn@^2.1.0, acorn@^2.4.0: - version "2.7.0" - resolved "https://registry.npmjs.org/acorn/-/acorn-2.7.0.tgz#ab6e7d9d886aaca8b085bc3312b79a198433f0e7" - integrity sha1-q259nYhqrKiwhbwzEreaGYQz8Oc= - acorn@^5.5.3: version "5.7.4" resolved "https://registry.npmjs.org/acorn/-/acorn-5.7.4.tgz#3e8d8a9947d0599a1796d10225d7432f4a4acf5e" @@ -6973,7 +7109,7 @@ aws4@^1.8.0: resolved "https://registry.npmjs.org/aws4/-/aws4-1.9.1.tgz#7e33d8f7d449b3f673cd72deb9abdc552dbe528e" integrity sha512-wMHVg2EOHaMRxbzgFJ9gtjOOCrI80OHLG14rxi28XwOW8ux6IiEbRCGGGqCtdAIg4FQCbW20k9RsT4y3gJlFug== -axios@^0.19.0, axios@^0.19.2: +axios@^0.19.2: version "0.19.2" resolved "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz#3ea36c5d8818d0d5f8a8a97a6d36b86cdc00cb27" integrity sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA== @@ -7045,16 +7181,16 @@ babel-helper-to-multiple-sequence-expressions@^0.5.0: resolved "https://registry.npmjs.org/babel-helper-to-multiple-sequence-expressions/-/babel-helper-to-multiple-sequence-expressions-0.5.0.tgz#a3f924e3561882d42fcf48907aa98f7979a4588d" integrity sha512-m2CvfDW4+1qfDdsrtf4dwOslQC3yhbgyBFptncp4wvtdrDHqueW7slsYv4gArie056phvQFhT2nRcGS4bnm6mA== -babel-jest@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/babel-jest/-/babel-jest-26.3.0.tgz#10d0ca4b529ca3e7d1417855ef7d7bd6fc0c3463" - integrity sha512-sxPnQGEyHAOPF8NcUsD0g7hDCnvLL2XyblRBcgrzTWBB/mAIpWow3n1bEL+VghnnZfreLhFSBsFluRoK2tRK4g== +babel-jest@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/babel-jest/-/babel-jest-26.5.2.tgz#164f367a35946c6cf54eaccde8762dec50422250" + integrity sha512-U3KvymF3SczA3vOL/cgiUFOznfMET+XDIXiWnoJV45siAp2pLMG8i2+/MGZlAC3f/F6Q40LR4M4qDrWZ9wkK8A== dependencies: - "@jest/transform" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/transform" "^26.5.2" + "@jest/types" "^26.5.2" "@types/babel__core" "^7.1.7" babel-plugin-istanbul "^6.0.0" - babel-preset-jest "^26.3.0" + babel-preset-jest "^26.5.0" chalk "^4.0.0" graceful-fs "^4.2.4" slash "^3.0.0" @@ -7109,10 +7245,10 @@ babel-plugin-istanbul@^6.0.0: istanbul-lib-instrument "^4.0.0" test-exclude "^6.0.0" -babel-plugin-jest-hoist@^26.2.0: - version "26.2.0" - resolved "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-26.2.0.tgz#bdd0011df0d3d513e5e95f76bd53b51147aca2dd" - integrity sha512-B/hVMRv8Nh1sQ1a3EY8I0n4Y1Wty3NrR5ebOyVT302op+DOAau+xNEImGMsUWOC3++ZlMooCytKz+NgN8aKGbA== +babel-plugin-jest-hoist@^26.5.0: + version "26.5.0" + resolved "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-26.5.0.tgz#3916b3a28129c29528de91e5784a44680db46385" + integrity sha512-ck17uZFD3CDfuwCLATWZxkkuGGFhMij8quP8CNhwj8ek1mqFgbFzRJ30xwC04LLscj/aKsVFfRST+b5PT7rSuw== dependencies: "@babel/template" "^7.3.3" "@babel/types" "^7.3.3" @@ -7337,12 +7473,12 @@ babel-preset-fbjs@^3.3.0: "@babel/plugin-transform-template-literals" "^7.0.0" babel-plugin-syntax-trailing-function-commas "^7.0.0-beta.0" -babel-preset-jest@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-26.3.0.tgz#ed6344506225c065fd8a0b53e191986f74890776" - integrity sha512-5WPdf7nyYi2/eRxCbVrE1kKCWxgWY4RsPEbdJWFm7QsesFGqjdkyLeu1zRkwM1cxK6EPIlNd6d2AxLk7J+t4pw== +babel-preset-jest@^26.5.0: + version "26.5.0" + resolved "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-26.5.0.tgz#f1b166045cd21437d1188d29f7fba470d5bdb0e7" + integrity sha512-F2vTluljhqkiGSJGBg/jOruA8vIIIL11YrxRcO7nviNTMbbofPSHwnm8mgP7d/wS7wRSexRoI6X1A6T74d4LQA== dependencies: - babel-plugin-jest-hoist "^26.2.0" + babel-plugin-jest-hoist "^26.5.0" babel-preset-current-node-syntax "^0.1.3" "babel-preset-minify@^0.5.0 || 0.6.0-alpha.5": @@ -7409,10 +7545,10 @@ balanced-match@^1.0.0: resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= -base64-arraybuffer@^0.1.5: - version "0.1.5" - resolved "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz#73926771923b5a19747ad666aa5cd4bf9c6e9ce8" - integrity sha1-c5JncZI7Whl0etZmqlzUv5xunOg= +base64-arraybuffer@^0.2.0: + version "0.2.0" + resolved "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.2.0.tgz#4b944fac0191aa5907afe2d8c999ccc57ce80f45" + integrity sha512-7emyCsu1/xiBXgQZrscw/8KPRT44I4Yq9Pe6EGs3aPRTsWuggML1/1DTuZUuIaJPIm1FTDUVXl4x/yW8s0kQDQ== base64-js@^1.0.2, base64-js@^1.2.0: version "1.3.1" @@ -8101,15 +8237,17 @@ canvas@^2.6.1: node-pre-gyp "^0.11.0" simple-get "^3.0.3" -canvg@1.5.3: - version "1.5.3" - resolved "https://registry.npmjs.org/canvg/-/canvg-1.5.3.tgz#aad17915f33368bf8eb80b25d129e3ae922ddc5f" - integrity sha512-7Gn2IuQzvUQWPIuZuFHrzsTM0gkPz2RRT9OcbdmA03jeKk8kltrD8gqUzNX15ghY/4PV5bbe5lmD6yDLDY6Ybg== +canvg@^3.0.6: + version "3.0.6" + resolved "https://registry.npmjs.org/canvg/-/canvg-3.0.6.tgz#4f82a34acc433daa06c494fc255420cbbb05f903" + integrity sha512-eFUy8R/4DgocR93LF8lr+YUxW4PYblUe/Q1gz2osk/cI5n8AsYdassvln0D9QPhLXQ6Lx7l8hwtT8FLvOn2Ihg== dependencies: - jsdom "^8.1.0" + "@babel/runtime" "^7.6.3" + "@types/raf" "^3.4.0" + core-js "3" + raf "^3.4.1" rgbcolor "^1.0.1" - stackblur-canvas "^1.4.1" - xmldom "^0.1.22" + stackblur-canvas "^2.0.0" capture-exit@^2.0.0: version "2.0.0" @@ -8264,11 +8402,11 @@ cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3: safe-buffer "^5.0.1" circleci-api@^4.0.0: - version "4.0.0" - resolved "https://registry.npmjs.org/circleci-api/-/circleci-api-4.0.0.tgz#d773fe68f4a59e1968881269883a23b0805b3546" - integrity sha512-D/THFyhOv6THSkYXJhrOLIOmV7fmyDqgs1+pBFMAqDR+ywXszxa2Dqx1Zw+YD3O2zD2y5LQOifCDT96VidRG7Q== + version "4.1.3" + resolved "https://registry.npmjs.org/circleci-api/-/circleci-api-4.1.3.tgz#cafd80bc1905c6064724636741b4b5b231ed34d0" + integrity sha512-Km6H8LB3nNbFUjErhI+sNQrcHcU7dCBnQEi4ckBtQMkCXh+2gDvaYchfkeuIaA1hkakQT5sLmdPbYzhKbvsOMg== dependencies: - axios "^0.19.0" + axios "^0.20.0" class-utils@^0.3.5: version "0.3.6" @@ -8622,6 +8760,11 @@ command-exists-promise@^2.0.2: resolved "https://registry.npmjs.org/command-exists-promise/-/command-exists-promise-2.0.2.tgz#7beecc4b218299f3c61fa69a4047aa0b36a64a99" integrity sha512-T6PB6vdFrwnHXg/I0kivM3DqaCGZLjjYSOe0a5WgFKcz1sOnmOeIjnhQPXVXX3QjVbLyTJ85lJkX6lUpukTzaA== +command-exists@^1.2.9: + version "1.2.9" + resolved "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz#c50725af3808c8ab0260fd60b01fbfa25b954f69" + integrity sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w== + commander@^2.11.0, commander@^2.19.0, commander@^2.20.0, commander@^2.20.3, commander@~2.20.3: version "2.20.3" resolved "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" @@ -8987,16 +9130,16 @@ core-js-pure@^3.0.0, core-js-pure@^3.0.1: resolved "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.6.4.tgz#4bf1ba866e25814f149d4e9aaa08c36173506e3a" integrity sha512-epIhRLkXdgv32xIUFaaAry2wdxZYBi6bgM7cB136dzzXXa+dFyRLTZeLUJxnd8ShrmyVXBub63n2NHo2JAt8Cw== +core-js@3, core-js@^3.0.1, core-js@^3.0.4, core-js@^3.5.0, core-js@^3.6.0, core-js@^3.6.5: + version "3.6.5" + resolved "https://registry.npmjs.org/core-js/-/core-js-3.6.5.tgz#7395dc273af37fb2e50e9bd3d9fe841285231d1a" + integrity sha512-vZVEEwZoIsI+vPEuoF9Iqf5H7/M3eeQqWlQnYa8FSKKePuYTf5MWnxb5SDAzCa60b3JBRS5g9b+Dq7b1y/RCrA== + core-js@^2.4.0, core-js@^2.4.1, core-js@^2.5.7, core-js@^2.6.10, core-js@^2.6.11, core-js@^2.6.5: version "2.6.11" resolved "https://registry.npmjs.org/core-js/-/core-js-2.6.11.tgz#38831469f9922bded8ee21c9dc46985e0399308c" integrity sha512-5wjnpaT/3dV+XB4borEsnAYQchn00XSgTAWKDkEqv+K8KevjbzmofK6hfJ9TZIlpj2N0xQpazy7PiRQiWHqzWg== -core-js@^3.0.1, core-js@^3.0.4, core-js@^3.5.0, core-js@^3.6.5: - version "3.6.5" - resolved "https://registry.npmjs.org/core-js/-/core-js-3.6.5.tgz#7395dc273af37fb2e50e9bd3d9fe841285231d1a" - integrity sha512-vZVEEwZoIsI+vPEuoF9Iqf5H7/M3eeQqWlQnYa8FSKKePuYTf5MWnxb5SDAzCa60b3JBRS5g9b+Dq7b1y/RCrA== - core-util-is@1.0.2, core-util-is@~1.0.0: version "1.0.2" resolved "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" @@ -9088,7 +9231,7 @@ cross-env@^7.0.0: dependencies: cross-spawn "^7.0.1" -cross-fetch@3.0.6, cross-fetch@^3.0.4, cross-fetch@^3.0.5: +cross-fetch@3.0.6, cross-fetch@^3.0.5, cross-fetch@^3.0.6: version "3.0.6" resolved "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.0.6.tgz#3a4040bc8941e653e0e9cf17f29ebcd177d3365c" integrity sha512-KBPUbqgFjzWlVcURG+Svp9TlhA5uliYtiNx/0r8nv0pdypeQCRJ9IaSIc3q/x3q8t3F75cHuwxVql1HFGHCNJQ== @@ -9183,12 +9326,12 @@ css-in-js-utils@^2.0.0: hyphenate-style-name "^1.0.2" isobject "^3.0.1" -css-line-break@1.0.1: - version "1.0.1" - resolved "https://registry.npmjs.org/css-line-break/-/css-line-break-1.0.1.tgz#19f2063a33e95fb2831b86446c0b80c188af450a" - integrity sha1-GfIGOjPpX7KDG4ZEbAuAwYivRQo= +css-line-break@1.1.1: + version "1.1.1" + resolved "https://registry.npmjs.org/css-line-break/-/css-line-break-1.1.1.tgz#d5e9bdd297840099eb0503c7310fd34927a026ef" + integrity sha512-1feNVaM4Fyzdj4mKPIQNL2n70MmuYzAXZ1aytlROFX1JsOo070OsugwGjj7nl6jnDJWHDM8zRZswkmeYVWZJQA== dependencies: - base64-arraybuffer "^0.1.5" + base64-arraybuffer "^0.2.0" css-loader@^3.5.3: version "3.6.0" @@ -9294,15 +9437,14 @@ css.escape@1.5.1, css.escape@^1.5.1: resolved "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz#42e27d4fa04ae32f931a4b4d4191fa9cddee97cb" integrity sha1-QuJ9T6BK4y+TGktNQZH6nN3ul8s= -css@^2.2.4: - version "2.2.4" - resolved "https://registry.npmjs.org/css/-/css-2.2.4.tgz#c646755c73971f2bba6a601e2cf2fd71b1298929" - integrity sha512-oUnjmWpy0niI3x/mPL8dVEI1l7MnG3+HHyRPHf+YFSbK+svOhXpmSOcDURUh2aOCgl2grzrOPt1nHLuCVFULLw== +css@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/css/-/css-3.0.0.tgz#4447a4d58fdd03367c516ca9f64ae365cee4aa5d" + integrity sha512-DG9pFfwOrzc+hawpmqX/dHYHJG+Bsdb0klhyi1sDneOgGOXy9wQIC8hzyVp1e4NRYDBdxcylvywPkkXCHAzTyQ== dependencies: - inherits "^2.0.3" + inherits "^2.0.4" source-map "^0.6.1" - source-map-resolve "^0.5.2" - urix "^0.1.0" + source-map-resolve "^0.6.0" cssesc@^3.0.0: version "3.0.0" @@ -9389,7 +9531,7 @@ csso@^4.0.2: dependencies: css-tree "1.0.0-alpha.37" -cssom@0.3.x, "cssom@>= 0.3.0 < 0.4.0", "cssom@>= 0.3.2 < 0.4.0", cssom@~0.3.6: +cssom@0.3.x, "cssom@>= 0.3.2 < 0.4.0", cssom@~0.3.6: version "0.3.8" resolved "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz#9f1276f5b2b463f2114d3f2c75250af8c1a36f4a" integrity sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg== @@ -9399,13 +9541,6 @@ cssom@^0.4.4: resolved "https://registry.npmjs.org/cssom/-/cssom-0.4.4.tgz#5a66cf93d2d0b661d80bf6a44fb65f5c2e4e0a10" integrity sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw== -"cssstyle@>= 0.2.34 < 0.3.0": - version "0.2.37" - resolved "https://registry.npmjs.org/cssstyle/-/cssstyle-0.2.37.tgz#541097234cb2513c83ceed3acddc27ff27987d54" - integrity sha1-VBCXI0yyUTyDzu06zdwn/yeYfVQ= - dependencies: - cssom "0.3.x" - cssstyle@^1.0.0: version "1.4.0" resolved "https://registry.npmjs.org/cssstyle/-/cssstyle-1.4.0.tgz#9d31328229d3c565c61e586b02041a28fccdccf1" @@ -9662,6 +9797,11 @@ dateformat@^3.0.0: resolved "https://registry.npmjs.org/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae" integrity sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q== +dayjs@^1.9.4: + version "1.9.4" + resolved "https://registry.npmjs.org/dayjs/-/dayjs-1.9.4.tgz#fcde984e227f4296f04e7b05720adad2e1071f1b" + integrity sha512-ABSF3alrldf7nM9sQ2U+Ln67NRwmzlLOqG7kK03kck0mw3wlSSEKv/XhKGGxUjQcS57QeiCyNdrFgtj9nWlrng== + de-indent@^1.0.2: version "1.0.2" resolved "https://registry.npmjs.org/de-indent/-/de-indent-1.0.2.tgz#b2038e846dc33baa5796128d0804b455b8c1e21d" @@ -9790,11 +9930,6 @@ deep-extend@0.6.0, deep-extend@^0.6.0, deep-extend@~0.6.0: resolved "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== -deep-freeze@^0.0.1: - version "0.0.1" - resolved "https://registry.npmjs.org/deep-freeze/-/deep-freeze-0.0.1.tgz#3a0b0005de18672819dfd38cd31f91179c893e84" - integrity sha1-OgsABd4YZygZ39OM0x+RF5yJPoQ= - deep-is@^0.1.3, deep-is@~0.1.3: version "0.1.3" resolved "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" @@ -9810,11 +9945,6 @@ deepmerge@4.2.2, deepmerge@^4.2.2: resolved "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955" integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg== -default-branch@^1.0.8: - version "1.0.8" - resolved "https://registry.npmjs.org/default-branch/-/default-branch-1.0.8.tgz#0e2f36a90e3b0d9f73cdf8e02841364ed35b8b54" - integrity sha512-pViUZEnaxd/Hbu880MEXF7XqV8RJ1ssDlkvzx+woQhcKW8px3BrVDvwBGn09zRiKZ+gOLipK7ft5x3no+3vb8A== - default-gateway@^4.2.0: version "4.2.0" resolved "https://registry.npmjs.org/default-gateway/-/default-gateway-4.2.0.tgz#167104c7500c2115f6dd69b0a536bb8ed720552b" @@ -10024,10 +10154,10 @@ diff-sequences@^25.2.6: resolved "https://registry.npmjs.org/diff-sequences/-/diff-sequences-25.2.6.tgz#5f467c00edd35352b7bca46d7927d60e687a76dd" integrity sha512-Hq8o7+6GaZeoFjtpgvRBUknSXNeJiCx7V9Fr94ZMljNiCr9n9L8H8aJqgWOQiDDGdyn29fRNcDdRVJ5fdyihfg== -diff-sequences@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/diff-sequences/-/diff-sequences-26.3.0.tgz#62a59b1b29ab7fd27cef2a33ae52abe73042d0a2" - integrity sha512-5j5vdRcw3CNctePNYN0Wy2e/JbWT6cAYnXv5OuqPhDpyCGc0uLu2TK0zOCJWNB9kOIfYMSpIulRaDgIi4HJ6Ig== +diff-sequences@^26.5.0: + version "26.5.0" + resolved "https://registry.npmjs.org/diff-sequences/-/diff-sequences-26.5.0.tgz#ef766cf09d43ed40406611f11c6d8d9dd8b2fefd" + integrity sha512-ZXx86srb/iYy6jG71k++wBN9P9J05UNQ5hQHQd9MtMPvcqXPx/vKU69jfHV637D00Q2gSgPk2D+jSx3l1lDW/Q== diff@^4.0.1, diff@^4.0.2: version "4.0.2" @@ -10213,6 +10343,11 @@ dompurify@^1.0.11: resolved "https://registry.npmjs.org/dompurify/-/dompurify-1.0.11.tgz#fe0f4a40d147f7cebbe31a50a1357539cfc1eb4d" integrity sha512-XywCTXZtc/qCX3iprD1pIklRVk/uhl8BKpkTxr+ZyMVUzSUg7wkQXRBp/euJ5J5moa1QvfpvaPQVP71z1O59dQ== +dompurify@^2.0.12: + version "2.1.1" + resolved "https://registry.npmjs.org/dompurify/-/dompurify-2.1.1.tgz#b5aa988676b093a9c836d8b855680a8598af25fe" + integrity sha512-NijiNVkS/OL8mdQL1hUbCD6uty/cgFpmNiuFxrmJ5YPH2cXrPKIewoixoji56rbZ6XBPmtM8GA8/sf9unlSuwg== + dompurify@^2.0.7: version "2.0.12" resolved "https://registry.npmjs.org/dompurify/-/dompurify-2.0.12.tgz#284a2b041e1c60b8e72d7b4d2fadad36141254ae" @@ -10673,7 +10808,7 @@ escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= -escodegen@^1.14.1, escodegen@^1.6.1, escodegen@^1.9.1: +escodegen@^1.14.1, escodegen@^1.9.1: version "1.14.3" resolved "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz#4e7b81fba61581dc97582ed78cab7f0e8d63f503" integrity sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw== @@ -10686,9 +10821,9 @@ escodegen@^1.14.1, escodegen@^1.6.1, escodegen@^1.9.1: source-map "~0.6.1" eslint-config-prettier@^6.0.0: - version "6.10.0" - resolved "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-6.10.0.tgz#7b15e303bf9c956875c948f6b21500e48ded6a7f" - integrity sha512-AtndijGte1rPILInUdHjvKEGbIV06NuvPrqlIEaEaWtbtvJh464mDeyGMdZEQMsGvC0ZVkiex1fSNcC4HAbRGg== + version "6.14.0" + resolved "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-6.14.0.tgz#390e7863a8ae99970981933826476169285b3a27" + integrity sha512-DbVwh0qZhAC7CNDWcq8cBdK6FcVHiMTKmCypOPWeZkp9hJ8xYwTaWSa6bb6cjfi8KOeJy0e9a8Izxyx+O4+gCQ== dependencies: get-stdin "^6.0.0" @@ -10736,7 +10871,7 @@ eslint-plugin-graphql@^4.0.0: lodash.flatten "^4.4.0" lodash.without "^4.4.0" -eslint-plugin-import@^2.20.2, eslint-plugin-import@^2.22.0: +eslint-plugin-import@^2.20.2: version "2.22.0" resolved "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.22.0.tgz#92f7736fe1fde3e2de77623c838dd992ff5ffb7e" integrity sha512-66Fpf1Ln6aIS5Gr/55ts19eUuoDhAbZgnr6UxK5hbDx6l/QgQgx61AePq+BV4PP2uXQFClgMVzep5zZ94qqsxg== @@ -10755,19 +10890,12 @@ eslint-plugin-import@^2.20.2, eslint-plugin-import@^2.22.0: resolve "^1.17.0" tsconfig-paths "^3.9.0" -eslint-plugin-jest@^23.17.1: - version "23.20.0" - resolved "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-23.20.0.tgz#e1d69c75f639e99d836642453c4e75ed22da4099" - integrity sha512-+6BGQt85OREevBDWCvhqj1yYA4+BFK4XnRZSGJionuEYmcglMZYLNNBBemwzbqUAckURaHdJSBcjHPyrtypZOw== +eslint-plugin-jest@^24.1.0: + version "24.1.0" + resolved "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-24.1.0.tgz#6708037d7602e5288ce877fd0103f329dc978361" + integrity sha512-827YJ+E8B9PvXu/0eiVSNFfxxndbKv+qE/3GSMhdorCaeaOehtqHGX2YDW9B85TEOre9n/zscledkFW/KbnyGg== dependencies: - "@typescript-eslint/experimental-utils" "^2.5.0" - -eslint-plugin-jest@^23.6.0: - version "23.8.2" - resolved "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-23.8.2.tgz#6f28b41c67ef635f803ebd9e168f6b73858eb8d4" - integrity sha512-xwbnvOsotSV27MtAe7s8uGWOori0nUsrXh2f1EnpmXua8sDfY6VZhHAhHg2sqK7HBNycRQExF074XSZ7DvfoFg== - dependencies: - "@typescript-eslint/experimental-utils" "^2.5.0" + "@typescript-eslint/experimental-utils" "^4.0.1" eslint-plugin-jsx-a11y@^6.2.1: version "6.2.3" @@ -10845,13 +10973,6 @@ eslint-scope@^5.0.0, eslint-scope@^5.1.0: esrecurse "^4.1.0" estraverse "^4.1.1" -eslint-utils@^1.4.3: - version "1.4.3" - resolved "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f" - integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q== - dependencies: - eslint-visitor-keys "^1.1.0" - eslint-utils@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.0.0.tgz#7be1cc70f27a72a76cd14aa698bcabed6890e1cd" @@ -10864,6 +10985,11 @@ eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.2.0: resolved "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.2.0.tgz#74415ac884874495f78ec2a97349525344c981fa" integrity sha512-WFb4ihckKil6hu3Dp798xdzSfddwKKU3+nGniKF6HfeW6OLd2OUDEPP7TcHtB5+QXOKg2s6B2DaMPE1Nn/kxKQ== +eslint-visitor-keys@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz#21fdc8fbcd9c795cc0321f0563702095751511a8" + integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ== + eslint@^7.1.0: version "7.4.0" resolved "https://registry.npmjs.org/eslint/-/eslint-7.4.0.tgz#4e35a2697e6c1972f9d6ef2b690ad319f80f206f" @@ -10959,6 +11085,11 @@ estree-walker@^1.0.1: resolved "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz#31bc5d612c96b704106b477e6dd5d8aa138cb700" integrity sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg== +estree-walker@^2.0.1: + version "2.0.1" + resolved "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.1.tgz#f8e030fb21cefa183b44b7ad516b747434e7a3e0" + integrity sha512-tF0hv+Yi2Ot1cwj9eYHtxC0jB9bmjacjQs6ZBTj82H8JwUywFuc+7E83NWfNMwHXZc11mjfFcVXPe9gEP4B8dg== + esutils@^2.0.2: version "2.0.3" resolved "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" @@ -11124,16 +11255,16 @@ expand-tilde@^2.0.0, expand-tilde@^2.0.2: dependencies: homedir-polyfill "^1.0.1" -expect@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/expect/-/expect-26.4.2.tgz#36db120928a5a2d7d9736643032de32f24e1b2a1" - integrity sha512-IlJ3X52Z0lDHm7gjEp+m76uX46ldH5VpqmU0006vqDju/285twh7zaWMRhs67VpQhBwjjMchk+p5aA0VkERCAA== +expect@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/expect/-/expect-26.5.3.tgz#89d9795036f7358b0a9a5243238eb8086482d741" + integrity sha512-kkpOhGRWGOr+TEFUnYAjfGvv35bfP+OlPtqPIJpOCR9DVtv8QV+p8zG0Edqafh80fsjeE+7RBcVUq1xApnYglw== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" ansi-styles "^4.0.0" jest-get-type "^26.3.0" - jest-matcher-utils "^26.4.2" - jest-message-util "^26.3.0" + jest-matcher-utils "^26.5.2" + jest-message-util "^26.5.2" jest-regex-util "^26.0.0" express-prom-bundle@^6.1.0: @@ -11475,10 +11606,6 @@ file-loader@^6.0.0: loader-utils "^2.0.0" schema-utils "^2.7.1" -file-saver@eligrey/FileSaver.js#1.3.8: - version "1.3.8" - resolved "https://codeload.github.com/eligrey/FileSaver.js/tar.gz/e865e37af9f9947ddcced76b549e27dc45c1cb2e" - file-system-cache@^1.0.5: version "1.0.5" resolved "https://registry.npmjs.org/file-system-cache/-/file-system-cache-1.0.5.tgz#84259b36a2bbb8d3d6eb1021d3132ffe64cfff4f" @@ -12114,10 +12241,10 @@ git-url-parse@^11.1.2: dependencies: git-up "^4.0.0" -git-url-parse@^11.2.0: - version "11.2.0" - resolved "https://registry.npmjs.org/git-url-parse/-/git-url-parse-11.2.0.tgz#2955fd51befd6d96ea1389bbe2ef57e8e6042b04" - integrity sha512-KPoHZg8v+plarZvto4ruIzzJLFQoRx+sUs5DQSr07By9IBKguVd+e6jwrFR6/TP6xrCJlNV1tPqLO1aREc7O2g== +git-url-parse@^11.4.0: + version "11.4.0" + resolved "https://registry.npmjs.org/git-url-parse/-/git-url-parse-11.4.0.tgz#f2bb1f2b00f05552540e95a62e31399a639a6aa6" + integrity sha512-KlIa5jvMYLjXMQXkqpFzobsyD/V2K5DRHl5OAf+6oDFPlPLxrGDVQlIdI63c4/Kt6kai4kALENSALlzTGST3GQ== dependencies: git-up "^4.0.0" @@ -12259,7 +12386,7 @@ globalthis@^1.0.0: dependencies: define-properties "^1.1.3" -globby@11.0.1, globby@^11.0.0: +globby@11.0.1, globby@^11.0.0, globby@^11.0.1: version "11.0.1" resolved "https://registry.npmjs.org/globby/-/globby-11.0.1.tgz#9a2bf107a068f3ffeabc49ad702c79ede8cfd357" integrity sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ== @@ -12923,12 +13050,12 @@ html-webpack-plugin@^4.2.1, html-webpack-plugin@^4.3.0: tapable "^1.1.3" util.promisify "1.0.0" -html2canvas@1.0.0-alpha.12: - version "1.0.0-alpha.12" - resolved "https://registry.npmjs.org/html2canvas/-/html2canvas-1.0.0-alpha.12.tgz#3b1992e3c9b3f56063c35fd620494f37eba88513" - integrity sha1-OxmS48mz9WBjw1/WIElPN+uohRM= +html2canvas@^1.0.0-rc.5: + version "1.0.0-rc.7" + resolved "https://registry.npmjs.org/html2canvas/-/html2canvas-1.0.0-rc.7.tgz#70c159ce0e63954a91169531894d08ad5627ac98" + integrity sha512-yvPNZGejB2KOyKleZspjK/NruXVQuowu8NnV2HYG7gW7ytzl+umffbtUI62v2dCHQLDdsK6HIDtyJZ0W3neerA== dependencies: - css-line-break "1.0.1" + css-line-break "1.1.1" htmlparser2@^3.3.0: version "3.10.1" @@ -13137,7 +13264,7 @@ hyphenate-style-name@^1.0.2, hyphenate-style-name@^1.0.3: resolved "https://registry.npmjs.org/hyphenate-style-name/-/hyphenate-style-name-1.0.3.tgz#097bb7fa0b8f1a9cf0bd5c734cf95899981a9b48" integrity sha512-EcuixamT82oplpoJ2XU4pDtKGWQ7b00CD9f1ug9IaQ3p1bkHMiKCZ9ut9QDI6qsa6cpUuB+A/I+zLtdNK4n2DQ== -iconv-lite@0.4.24, iconv-lite@^0.4.13, iconv-lite@^0.4.21, iconv-lite@^0.4.24, iconv-lite@^0.4.4, iconv-lite@~0.4.13: +iconv-lite@0.4.24, iconv-lite@^0.4.21, iconv-lite@^0.4.24, iconv-lite@^0.4.4, iconv-lite@~0.4.13: version "0.4.24" resolved "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== @@ -13205,6 +13332,11 @@ immer@1.10.0: resolved "https://registry.npmjs.org/immer/-/immer-1.10.0.tgz#bad67605ba9c810275d91e1c2a47d4582e98286d" integrity sha512-O3sR1/opvCDGLEVcvrGTMtLac8GJ5IwZC4puPrLuRj3l7ICKvkmA0vGuU9OW8mV9WIBRnaxp5GJh9IEAaNOoYg== +immer@^7.0.9: + version "7.0.9" + resolved "https://registry.npmjs.org/immer/-/immer-7.0.9.tgz#28e7552c21d39dd76feccd2b800b7bc86ee4a62e" + integrity sha512-Vs/gxoM4DqNAYR7pugIxi0Xc8XAun/uy7AQu4fLLqaTBHxjOP9pJ266Q9MWA/ly4z6rAFZbvViOtihxUZ7O28A== + immutable@>=3.8.2, immutable@^3.8.1, immutable@^3.8.2, immutable@^3.x.x: version "3.8.2" resolved "https://registry.npmjs.org/immutable/-/immutable-3.8.2.tgz#c2439951455bb39913daf281376f1530e104adf3" @@ -13841,12 +13973,12 @@ is-promise@^2.1, is-promise@^2.1.0: resolved "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz#39ab959ccbf9a774cf079f7b40c7a26f763135f1" integrity sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ== -is-reference@^1.1.2: - version "1.1.4" - resolved "https://registry.npmjs.org/is-reference/-/is-reference-1.1.4.tgz#3f95849886ddb70256a3e6d062b1a68c13c51427" - integrity sha512-uJA/CDPO3Tao3GTrxYn6AwkM4nUPJiGGYu5+cB8qbC7WGFlrKZbiRo7SFKxUAEpFUfiHofWCXBUNhvYJMh+6zw== +is-reference@^1.2.1: + version "1.2.1" + resolved "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz#8b2dac0b371f4bc994fdeaba9eb542d03002d0b7" + integrity sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ== dependencies: - "@types/estree" "0.0.39" + "@types/estree" "*" is-regex@^1.0.4, is-regex@^1.0.5, is-regex@^1.1.1: version "1.1.1" @@ -14132,57 +14264,57 @@ jenkins@^0.28.0: dependencies: papi "^0.29.0" -jest-changed-files@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-26.3.0.tgz#68fb2a7eb125f50839dab1f5a17db3607fe195b1" - integrity sha512-1C4R4nijgPltX6fugKxM4oQ18zimS7LqQ+zTTY8lMCMFPrxqBFb7KJH0Z2fRQJvw2Slbaipsqq7s1mgX5Iot+g== +jest-changed-files@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-26.5.2.tgz#330232c6a5c09a7f040a5870e8f0a9c6abcdbed5" + integrity sha512-qSmssmiIdvM5BWVtyK/nqVpN3spR5YyvkvPqz1x3BR1bwIxsWmU/MGwLoCrPNLbkG2ASAKfvmJpOduEApBPh2w== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" execa "^4.0.0" throat "^5.0.0" -jest-cli@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-cli/-/jest-cli-26.4.2.tgz#24afc6e4dfc25cde4c7ec4226fb7db5f157c21da" - integrity sha512-zb+lGd/SfrPvoRSC/0LWdaWCnscXc1mGYW//NP4/tmBvRPT3VntZ2jtKUONsRi59zc5JqmsSajA9ewJKFYp8Cw== +jest-cli@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-cli/-/jest-cli-26.5.3.tgz#f936b98f247b76b7bc89c7af50af82c88e356a80" + integrity sha512-HkbSvtugpSXBf2660v9FrNVUgxvPkssN8CRGj9gPM8PLhnaa6zziFiCEKQAkQS4uRzseww45o0TR+l6KeRYV9A== dependencies: - "@jest/core" "^26.4.2" - "@jest/test-result" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/core" "^26.5.3" + "@jest/test-result" "^26.5.2" + "@jest/types" "^26.5.2" chalk "^4.0.0" exit "^0.1.2" graceful-fs "^4.2.4" import-local "^3.0.2" is-ci "^2.0.0" - jest-config "^26.4.2" - jest-util "^26.3.0" - jest-validate "^26.4.2" + jest-config "^26.5.3" + jest-util "^26.5.2" + jest-validate "^26.5.3" prompts "^2.0.1" - yargs "^15.3.1" + yargs "^15.4.1" -jest-config@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-config/-/jest-config-26.4.2.tgz#da0cbb7dc2c131ffe831f0f7f2a36256e6086558" - integrity sha512-QBf7YGLuToiM8PmTnJEdRxyYy3mHWLh24LJZKVdXZ2PNdizSe1B/E8bVm+HYcjbEzGuVXDv/di+EzdO/6Gq80A== +jest-config@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-config/-/jest-config-26.5.3.tgz#baf51c9be078c2c755c8f8a51ec0f06c762c1d3f" + integrity sha512-NVhZiIuN0GQM6b6as4CI5FSCyXKxdrx5ACMCcv/7Pf+TeCajJhJc+6dwgdAVPyerUFB9pRBIz3bE7clSrRge/w== dependencies: "@babel/core" "^7.1.0" - "@jest/test-sequencer" "^26.4.2" - "@jest/types" "^26.3.0" - babel-jest "^26.3.0" + "@jest/test-sequencer" "^26.5.3" + "@jest/types" "^26.5.2" + babel-jest "^26.5.2" chalk "^4.0.0" deepmerge "^4.2.2" glob "^7.1.1" graceful-fs "^4.2.4" - jest-environment-jsdom "^26.3.0" - jest-environment-node "^26.3.0" + jest-environment-jsdom "^26.5.2" + jest-environment-node "^26.5.2" jest-get-type "^26.3.0" - jest-jasmine2 "^26.4.2" + jest-jasmine2 "^26.5.3" jest-regex-util "^26.0.0" - jest-resolve "^26.4.0" - jest-util "^26.3.0" - jest-validate "^26.4.2" + jest-resolve "^26.5.2" + jest-util "^26.5.2" + jest-validate "^26.5.3" micromatch "^4.0.2" - pretty-format "^26.4.2" + pretty-format "^26.5.2" jest-css-modules@^2.1.0: version "2.1.0" @@ -14191,7 +14323,7 @@ jest-css-modules@^2.1.0: dependencies: identity-obj-proxy "3.0.0" -jest-diff@^25.1.0, jest-diff@^25.2.1: +jest-diff@^25.2.1: version "25.5.0" resolved "https://registry.npmjs.org/jest-diff/-/jest-diff-25.5.0.tgz#1dd26ed64f96667c068cef026b677dfa01afcfa9" integrity sha512-z1kygetuPiREYdNIumRpAHY6RXiGmp70YHptjdaxTWGmA085W3iCnXNx0DhflK3vwrKmrRWyY1wUpkPMVxMK7A== @@ -14201,15 +14333,15 @@ jest-diff@^25.1.0, jest-diff@^25.2.1: jest-get-type "^25.2.6" pretty-format "^25.5.0" -jest-diff@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-diff/-/jest-diff-26.4.2.tgz#a1b7b303bcc534aabdb3bd4a7caf594ac059f5aa" - integrity sha512-6T1XQY8U28WH0Z5rGpQ+VqZSZz8EN8rZcBtfvXaOkbwxIEeRre6qnuZQlbY1AJ4MKDxQF8EkrCvK+hL/VkyYLQ== +jest-diff@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-diff/-/jest-diff-26.5.2.tgz#8e26cb32dc598e8b8a1b9deff55316f8313c8053" + integrity sha512-HCSWDUGwsov5oTlGzrRM+UPJI/Dpqi9jzeV0fdRNi3Ch5bnoXhnyJMmVg2juv9081zLIy3HGPI5mcuGgXM2xRA== dependencies: chalk "^4.0.0" - diff-sequences "^26.3.0" + diff-sequences "^26.5.0" jest-get-type "^26.3.0" - pretty-format "^26.4.2" + pretty-format "^26.5.2" jest-docblock@^26.0.0: version "26.0.0" @@ -14218,41 +14350,41 @@ jest-docblock@^26.0.0: dependencies: detect-newline "^3.0.0" -jest-each@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-each/-/jest-each-26.4.2.tgz#bb14f7f4304f2bb2e2b81f783f989449b8b6ffae" - integrity sha512-p15rt8r8cUcRY0Mvo1fpkOGYm7iI8S6ySxgIdfh3oOIv+gHwrHTy5VWCGOecWUhDsit4Nz8avJWdT07WLpbwDA== +jest-each@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-each/-/jest-each-26.5.2.tgz#35e68d6906a7f826d3ca5803cfe91d17a5a34c31" + integrity sha512-w7D9FNe0m2D3yZ0Drj9CLkyF/mGhmBSULMQTypzAKR746xXnjUrK8GUJdlLTWUF6dd0ks3MtvGP7/xNFr9Aphg== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" chalk "^4.0.0" jest-get-type "^26.3.0" - jest-util "^26.3.0" - pretty-format "^26.4.2" + jest-util "^26.5.2" + pretty-format "^26.5.2" -jest-environment-jsdom@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-26.3.0.tgz#3b749ba0f3a78e92ba2c9ce519e16e5dd515220c" - integrity sha512-zra8He2btIMJkAzvLaiZ9QwEPGEetbxqmjEBQwhH3CA+Hhhu0jSiEJxnJMbX28TGUvPLxBt/zyaTLrOPF4yMJA== +jest-environment-jsdom@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-26.5.2.tgz#5feab05b828fd3e4b96bee5e0493464ddd2bb4bc" + integrity sha512-fWZPx0bluJaTQ36+PmRpvUtUlUFlGGBNyGX1SN3dLUHHMcQ4WseNEzcGGKOw4U5towXgxI4qDoI3vwR18H0RTw== dependencies: - "@jest/environment" "^26.3.0" - "@jest/fake-timers" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/environment" "^26.5.2" + "@jest/fake-timers" "^26.5.2" + "@jest/types" "^26.5.2" "@types/node" "*" - jest-mock "^26.3.0" - jest-util "^26.3.0" - jsdom "^16.2.2" + jest-mock "^26.5.2" + jest-util "^26.5.2" + jsdom "^16.4.0" -jest-environment-node@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-26.3.0.tgz#56c6cfb506d1597f94ee8d717072bda7228df849" - integrity sha512-c9BvYoo+FGcMj5FunbBgtBnbR5qk3uky8PKyRVpSfe2/8+LrNQMiXX53z6q2kY+j15SkjQCOSL/6LHnCPLVHNw== +jest-environment-node@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-26.5.2.tgz#275a0f01b5e47447056f1541a15ed4da14acca03" + integrity sha512-YHjnDsf/GKFCYMGF1V+6HF7jhY1fcLfLNBDjhAOvFGvt6d8vXvNdJGVM7uTZ2VO/TuIyEFhPGaXMX5j3h7fsrA== dependencies: - "@jest/environment" "^26.3.0" - "@jest/fake-timers" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/environment" "^26.5.2" + "@jest/fake-timers" "^26.5.2" + "@jest/types" "^26.5.2" "@types/node" "*" - jest-mock "^26.3.0" - jest-util "^26.3.0" + jest-mock "^26.5.2" + jest-util "^26.5.2" jest-esm-transformer@^1.0.0: version "1.0.0" @@ -14262,15 +14394,7 @@ jest-esm-transformer@^1.0.0: "@babel/core" "^7.4.4" "@babel/plugin-transform-modules-commonjs" "^7.4.4" -jest-fetch-mock@^3.0.3: - version "3.0.3" - resolved "https://registry.npmjs.org/jest-fetch-mock/-/jest-fetch-mock-3.0.3.tgz#31749c456ae27b8919d69824f1c2bd85fe0a1f3b" - integrity sha512-Ux1nWprtLrdrH4XwE7O7InRY6psIi3GOsqNESJgMJ+M5cv4A8Lh7SN9d2V2kKRZ8ebAfcd1LNyZguAOb6JiDqw== - dependencies: - cross-fetch "^3.0.4" - promise-polyfill "^8.1.3" - -jest-get-type@^25.1.0, jest-get-type@^25.2.6: +jest-get-type@^25.2.6: version "25.2.6" resolved "https://registry.npmjs.org/jest-get-type/-/jest-get-type-25.2.6.tgz#0b0a32fab8908b44d508be81681487dbabb8d877" integrity sha512-DxjtyzOHjObRM+sM1knti6or+eOgcGU4xVSb2HNP1TqO4ahsT+rqZg+nyqHWJSvWgKC5cG3QjGFBqxLghiF/Ig== @@ -14280,99 +14404,89 @@ jest-get-type@^26.3.0: resolved "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz#e97dc3c3f53c2b406ca7afaed4493b1d099199e0" integrity sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig== -jest-haste-map@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-26.3.0.tgz#c51a3b40100d53ab777bfdad382d2e7a00e5c726" - integrity sha512-DHWBpTJgJhLLGwE5Z1ZaqLTYqeODQIZpby0zMBsCU9iRFHYyhklYqP4EiG73j5dkbaAdSZhgB938mL51Q5LeZA== +jest-haste-map@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-26.5.2.tgz#a15008abfc502c18aa56e4919ed8c96304ceb23d" + integrity sha512-lJIAVJN3gtO3k4xy+7i2Xjtwh8CfPcH08WYjZpe9xzveDaqGw9fVNCpkYu6M525wKFVkLmyi7ku+DxCAP1lyMA== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" "@types/graceful-fs" "^4.1.2" "@types/node" "*" anymatch "^3.0.3" fb-watchman "^2.0.0" graceful-fs "^4.2.4" jest-regex-util "^26.0.0" - jest-serializer "^26.3.0" - jest-util "^26.3.0" - jest-worker "^26.3.0" + jest-serializer "^26.5.0" + jest-util "^26.5.2" + jest-worker "^26.5.0" micromatch "^4.0.2" sane "^4.0.3" walker "^1.0.7" optionalDependencies: fsevents "^2.1.2" -jest-jasmine2@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-26.4.2.tgz#18a9d5bec30904267ac5e9797570932aec1e2257" - integrity sha512-z7H4EpCldHN1J8fNgsja58QftxBSL+JcwZmaXIvV9WKIM+x49F4GLHu/+BQh2kzRKHAgaN/E82od+8rTOBPyPA== +jest-jasmine2@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-26.5.3.tgz#baad2114ce32d16aff25aeb877d18bb4e332dc4c" + integrity sha512-nFlZOpnGlNc7y/+UkkeHnvbOM+rLz4wB1AimgI9QhtnqSZte0wYjbAm8hf7TCwXlXgDwZxAXo6z0a2Wzn9FoOg== dependencies: "@babel/traverse" "^7.1.0" - "@jest/environment" "^26.3.0" - "@jest/source-map" "^26.3.0" - "@jest/test-result" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/environment" "^26.5.2" + "@jest/source-map" "^26.5.0" + "@jest/test-result" "^26.5.2" + "@jest/types" "^26.5.2" "@types/node" "*" chalk "^4.0.0" co "^4.6.0" - expect "^26.4.2" + expect "^26.5.3" is-generator-fn "^2.0.0" - jest-each "^26.4.2" - jest-matcher-utils "^26.4.2" - jest-message-util "^26.3.0" - jest-runtime "^26.4.2" - jest-snapshot "^26.4.2" - jest-util "^26.3.0" - pretty-format "^26.4.2" + jest-each "^26.5.2" + jest-matcher-utils "^26.5.2" + jest-message-util "^26.5.2" + jest-runtime "^26.5.3" + jest-snapshot "^26.5.3" + jest-util "^26.5.2" + pretty-format "^26.5.2" throat "^5.0.0" -jest-leak-detector@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-26.4.2.tgz#c73e2fa8757bf905f6f66fb9e0070b70fa0f573f" - integrity sha512-akzGcxwxtE+9ZJZRW+M2o+nTNnmQZxrHJxX/HjgDaU5+PLmY1qnQPnMjgADPGCRPhB+Yawe1iij0REe+k/aHoA== +jest-leak-detector@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-26.5.2.tgz#83fcf9a4a6ef157549552cb4f32ca1d6221eea69" + integrity sha512-h7ia3dLzBFItmYERaLPEtEKxy3YlcbcRSjj0XRNJgBEyODuu+3DM2o62kvIFvs3PsaYoIIv+e+nLRI61Dj1CNw== dependencies: jest-get-type "^26.3.0" - pretty-format "^26.4.2" + pretty-format "^26.5.2" -jest-matcher-utils@^25.1.0: - version "25.1.0" - resolved "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-25.1.0.tgz#fa5996c45c7193a3c24e73066fc14acdee020220" - integrity sha512-KGOAFcSFbclXIFE7bS4C53iYobKI20ZWleAdAFun4W1Wz1Kkej8Ng6RRbhL8leaEvIOjGXhGf/a1JjO8bkxIWQ== - dependencies: - chalk "^3.0.0" - jest-diff "^25.1.0" - jest-get-type "^25.1.0" - pretty-format "^25.1.0" - -jest-matcher-utils@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-26.4.2.tgz#fa81f3693f7cb67e5fc1537317525ef3b85f4b06" - integrity sha512-KcbNqWfWUG24R7tu9WcAOKKdiXiXCbMvQYT6iodZ9k1f7065k0keUOW6XpJMMvah+hTfqkhJhRXmA3r3zMAg0Q== +jest-matcher-utils@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-26.5.2.tgz#6aa2c76ce8b9c33e66f8856ff3a52bab59e6c85a" + integrity sha512-W9GO9KBIC4gIArsNqDUKsLnhivaqf8MSs6ujO/JDcPIQrmY+aasewweXVET8KdrJ6ADQaUne5UzysvF/RR7JYA== dependencies: chalk "^4.0.0" - jest-diff "^26.4.2" + jest-diff "^26.5.2" jest-get-type "^26.3.0" - pretty-format "^26.4.2" + pretty-format "^26.5.2" -jest-message-util@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-message-util/-/jest-message-util-26.3.0.tgz#3bdb538af27bb417f2d4d16557606fd082d5841a" - integrity sha512-xIavRYqr4/otGOiLxLZGj3ieMmjcNE73Ui+LdSW/Y790j5acqCsAdDiLIbzHCZMpN07JOENRWX5DcU+OQ+TjTA== +jest-message-util@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-message-util/-/jest-message-util-26.5.2.tgz#6c4c4c46dcfbabb47cd1ba2f6351559729bc11bb" + integrity sha512-Ocp9UYZ5Jl15C5PNsoDiGEk14A4NG0zZKknpWdZGoMzJuGAkVt10e97tnEVMYpk7LnQHZOfuK2j/izLBMcuCZw== dependencies: "@babel/code-frame" "^7.0.0" - "@jest/types" "^26.3.0" - "@types/stack-utils" "^1.0.1" + "@jest/types" "^26.5.2" + "@types/stack-utils" "^2.0.0" chalk "^4.0.0" graceful-fs "^4.2.4" micromatch "^4.0.2" slash "^3.0.0" stack-utils "^2.0.2" -jest-mock@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-mock/-/jest-mock-26.3.0.tgz#ee62207c3c5ebe5f35b760e1267fee19a1cfdeba" - integrity sha512-PeaRrg8Dc6mnS35gOo/CbZovoDPKAeB1FICZiuagAgGvbWdNNyjQjkOaGUa/3N3JtpQ/Mh9P4A2D4Fv51NnP8Q== +jest-mock@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-mock/-/jest-mock-26.5.2.tgz#c9302e8ef807f2bfc749ee52e65ad11166a1b6a1" + integrity sha512-9SiU4b5PtO51v0MtJwVRqeGEroH66Bnwtq4ARdNP7jNXbpT7+ByeWNAk4NeT/uHfNSVDXEXgQo1XRuwEqS6Rdw== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" "@types/node" "*" jest-pnp-resolver@^1.2.2: @@ -14385,154 +14499,155 @@ jest-regex-util@^26.0.0: resolved "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-26.0.0.tgz#d25e7184b36e39fd466c3bc41be0971e821fee28" integrity sha512-Gv3ZIs/nA48/Zvjrl34bf+oD76JHiGDUxNOVgUjh3j890sblXryjY4rss71fPtD/njchl6PSE2hIhvyWa1eT0A== -jest-resolve-dependencies@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-26.4.2.tgz#739bdb027c14befb2fe5aabbd03f7bab355f1dc5" - integrity sha512-ADHaOwqEcVc71uTfySzSowA/RdxUpCxhxa2FNLiin9vWLB1uLPad3we+JSSROq5+SrL9iYPdZZF8bdKM7XABTQ== +jest-resolve-dependencies@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-26.5.3.tgz#11483f91e534bdcd257ab21e8622799e59701aba" + integrity sha512-+KMDeke/BFK+mIQ2IYSyBz010h7zQaVt4Xie6cLqUGChorx66vVeQVv4ErNoMwInnyYHi1Ud73tDS01UbXbfLQ== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" jest-regex-util "^26.0.0" - jest-snapshot "^26.4.2" + jest-snapshot "^26.5.3" -jest-resolve@^26.4.0: - version "26.4.0" - resolved "https://registry.npmjs.org/jest-resolve/-/jest-resolve-26.4.0.tgz#6dc0af7fb93e65b73fec0368ca2b76f3eb59a6d7" - integrity sha512-bn/JoZTEXRSlEx3+SfgZcJAVuTMOksYq9xe9O6s4Ekg84aKBObEaVXKOEilULRqviSLAYJldnoWV9c07kwtiCg== +jest-resolve@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-resolve/-/jest-resolve-26.5.2.tgz#0d719144f61944a428657b755a0e5c6af4fc8602" + integrity sha512-XsPxojXGRA0CoDD7Vis59ucz2p3cQFU5C+19tz3tLEAlhYKkK77IL0cjYjikY9wXnOaBeEdm1rOgSJjbZWpcZg== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" chalk "^4.0.0" graceful-fs "^4.2.4" jest-pnp-resolver "^1.2.2" - jest-util "^26.3.0" + jest-util "^26.5.2" read-pkg-up "^7.0.1" resolve "^1.17.0" slash "^3.0.0" -jest-runner@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-runner/-/jest-runner-26.4.2.tgz#c3ec5482c8edd31973bd3935df5a449a45b5b853" - integrity sha512-FgjDHeVknDjw1gRAYaoUoShe1K3XUuFMkIaXbdhEys+1O4bEJS8Avmn4lBwoMfL8O5oFTdWYKcf3tEJyyYyk8g== +jest-runner@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-runner/-/jest-runner-26.5.3.tgz#800787459ea59c68e7505952933e33981dc3db38" + integrity sha512-qproP0Pq7IIule+263W57k2+8kWCszVJTC9TJWGUz0xJBr+gNiniGXlG8rotd0XxwonD5UiJloYoSO5vbUr5FQ== dependencies: - "@jest/console" "^26.3.0" - "@jest/environment" "^26.3.0" - "@jest/test-result" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/console" "^26.5.2" + "@jest/environment" "^26.5.2" + "@jest/test-result" "^26.5.2" + "@jest/types" "^26.5.2" "@types/node" "*" chalk "^4.0.0" emittery "^0.7.1" exit "^0.1.2" graceful-fs "^4.2.4" - jest-config "^26.4.2" + jest-config "^26.5.3" jest-docblock "^26.0.0" - jest-haste-map "^26.3.0" - jest-leak-detector "^26.4.2" - jest-message-util "^26.3.0" - jest-resolve "^26.4.0" - jest-runtime "^26.4.2" - jest-util "^26.3.0" - jest-worker "^26.3.0" + jest-haste-map "^26.5.2" + jest-leak-detector "^26.5.2" + jest-message-util "^26.5.2" + jest-resolve "^26.5.2" + jest-runtime "^26.5.3" + jest-util "^26.5.2" + jest-worker "^26.5.0" source-map-support "^0.5.6" throat "^5.0.0" -jest-runtime@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-runtime/-/jest-runtime-26.4.2.tgz#94ce17890353c92e4206580c73a8f0c024c33c42" - integrity sha512-4Pe7Uk5a80FnbHwSOk7ojNCJvz3Ks2CNQWT5Z7MJo4tX0jb3V/LThKvD9tKPNVNyeMH98J/nzGlcwc00R2dSHQ== +jest-runtime@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-runtime/-/jest-runtime-26.5.3.tgz#5882ae91fd88304310f069549e6bf82f3f198bea" + integrity sha512-IDjalmn2s/Tc4GvUwhPHZ0iaXCdMRq5p6taW9P8RpU+FpG01O3+H8z+p3rDCQ9mbyyyviDgxy/LHPLzrIOKBkQ== dependencies: - "@jest/console" "^26.3.0" - "@jest/environment" "^26.3.0" - "@jest/fake-timers" "^26.3.0" - "@jest/globals" "^26.4.2" - "@jest/source-map" "^26.3.0" - "@jest/test-result" "^26.3.0" - "@jest/transform" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/console" "^26.5.2" + "@jest/environment" "^26.5.2" + "@jest/fake-timers" "^26.5.2" + "@jest/globals" "^26.5.3" + "@jest/source-map" "^26.5.0" + "@jest/test-result" "^26.5.2" + "@jest/transform" "^26.5.2" + "@jest/types" "^26.5.2" "@types/yargs" "^15.0.0" chalk "^4.0.0" collect-v8-coverage "^1.0.0" exit "^0.1.2" glob "^7.1.3" graceful-fs "^4.2.4" - jest-config "^26.4.2" - jest-haste-map "^26.3.0" - jest-message-util "^26.3.0" - jest-mock "^26.3.0" + jest-config "^26.5.3" + jest-haste-map "^26.5.2" + jest-message-util "^26.5.2" + jest-mock "^26.5.2" jest-regex-util "^26.0.0" - jest-resolve "^26.4.0" - jest-snapshot "^26.4.2" - jest-util "^26.3.0" - jest-validate "^26.4.2" + jest-resolve "^26.5.2" + jest-snapshot "^26.5.3" + jest-util "^26.5.2" + jest-validate "^26.5.3" slash "^3.0.0" strip-bom "^4.0.0" - yargs "^15.3.1" + yargs "^15.4.1" -jest-serializer@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-serializer/-/jest-serializer-26.3.0.tgz#1c9d5e1b74d6e5f7e7f9627080fa205d976c33ef" - integrity sha512-IDRBQBLPlKa4flg77fqg0n/pH87tcRKwe8zxOVTWISxGpPHYkRZ1dXKyh04JOja7gppc60+soKVZ791mruVdow== +jest-serializer@^26.5.0: + version "26.5.0" + resolved "https://registry.npmjs.org/jest-serializer/-/jest-serializer-26.5.0.tgz#f5425cc4c5f6b4b355f854b5f0f23ec6b962bc13" + integrity sha512-+h3Gf5CDRlSLdgTv7y0vPIAoLgX/SI7T4v6hy+TEXMgYbv+ztzbg5PSN6mUXAT/hXYHvZRWm+MaObVfqkhCGxA== dependencies: "@types/node" "*" graceful-fs "^4.2.4" -jest-snapshot@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-26.4.2.tgz#87d3ac2f2bd87ea8003602fbebd8fcb9e94104f6" - integrity sha512-N6Uub8FccKlf5SBFnL2Ri/xofbaA68Cc3MGjP/NuwgnsvWh+9hLIR/DhrxbSiKXMY9vUW5dI6EW1eHaDHqe9sg== +jest-snapshot@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-26.5.3.tgz#f6b4b4b845f85d4b0dadd7cf119c55d0c1688601" + integrity sha512-ZgAk0Wm0JJ75WS4lGaeRfa0zIgpL0KD595+XmtwlIEMe8j4FaYHyZhP1LNOO+8fXq7HJ3hll54+sFV9X4+CGVw== dependencies: "@babel/types" "^7.0.0" - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" + "@types/babel__traverse" "^7.0.4" "@types/prettier" "^2.0.0" chalk "^4.0.0" - expect "^26.4.2" + expect "^26.5.3" graceful-fs "^4.2.4" - jest-diff "^26.4.2" + jest-diff "^26.5.2" jest-get-type "^26.3.0" - jest-haste-map "^26.3.0" - jest-matcher-utils "^26.4.2" - jest-message-util "^26.3.0" - jest-resolve "^26.4.0" + jest-haste-map "^26.5.2" + jest-matcher-utils "^26.5.2" + jest-message-util "^26.5.2" + jest-resolve "^26.5.2" natural-compare "^1.4.0" - pretty-format "^26.4.2" + pretty-format "^26.5.2" semver "^7.3.2" -jest-util@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-util/-/jest-util-26.3.0.tgz#a8974b191df30e2bf523ebbfdbaeb8efca535b3e" - integrity sha512-4zpn6bwV0+AMFN0IYhH/wnzIQzRaYVrz1A8sYnRnj4UXDXbOVtWmlaZkO9mipFqZ13okIfN87aDoJWB7VH6hcw== +jest-util@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-util/-/jest-util-26.5.2.tgz#8403f75677902cc52a1b2140f568e91f8ed4f4d7" + integrity sha512-WTL675bK+GSSAYgS8z9FWdCT2nccO1yTIplNLPlP0OD8tUk/H5IrWKMMRudIQQ0qp8bb4k+1Qa8CxGKq9qnYdg== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" "@types/node" "*" chalk "^4.0.0" graceful-fs "^4.2.4" is-ci "^2.0.0" micromatch "^4.0.2" -jest-validate@^26.4.2: - version "26.4.2" - resolved "https://registry.npmjs.org/jest-validate/-/jest-validate-26.4.2.tgz#e871b0dfe97747133014dcf6445ee8018398f39c" - integrity sha512-blft+xDX7XXghfhY0mrsBCYhX365n8K5wNDC4XAcNKqqjEzsRUSXP44m6PL0QJEW2crxQFLLztVnJ4j7oPlQrQ== +jest-validate@^26.5.3: + version "26.5.3" + resolved "https://registry.npmjs.org/jest-validate/-/jest-validate-26.5.3.tgz#eefd5a5c87059550548c5ad8d6589746c66929e3" + integrity sha512-LX07qKeAtY+lsU0o3IvfDdN5KH9OulEGOMN1sFo6PnEf5/qjS1LZIwNk9blcBeW94pQUI9dLN9FlDYDWI5tyaA== dependencies: - "@jest/types" "^26.3.0" + "@jest/types" "^26.5.2" camelcase "^6.0.0" chalk "^4.0.0" jest-get-type "^26.3.0" leven "^3.1.0" - pretty-format "^26.4.2" + pretty-format "^26.5.2" -jest-watcher@^26.3.0: - version "26.3.0" - resolved "https://registry.npmjs.org/jest-watcher/-/jest-watcher-26.3.0.tgz#f8ef3068ddb8af160ef868400318dc4a898eed08" - integrity sha512-XnLdKmyCGJ3VoF6G/p5ohbJ04q/vv5aH9ENI+i6BL0uu9WWB6Z7Z2lhQQk0d2AVZcRGp1yW+/TsoToMhBFPRdQ== +jest-watcher@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/jest-watcher/-/jest-watcher-26.5.2.tgz#2957f4461007e0769d74b537379ecf6b7c696916" + integrity sha512-i3m1NtWzF+FXfJ3ljLBB/WQEp4uaNhX7QcQUWMokcifFTUQBDFyUMEwk0JkJ1kopHbx7Een3KX0Q7+9koGM/Pw== dependencies: - "@jest/test-result" "^26.3.0" - "@jest/types" "^26.3.0" + "@jest/test-result" "^26.5.2" + "@jest/types" "^26.5.2" "@types/node" "*" ansi-escapes "^4.2.1" chalk "^4.0.0" - jest-util "^26.3.0" + jest-util "^26.5.2" string-length "^4.0.1" -jest-worker@^26.2.1, jest-worker@^26.3.0: +jest-worker@^26.2.1: version "26.3.0" resolved "https://registry.npmjs.org/jest-worker/-/jest-worker-26.3.0.tgz#7c8a97e4f4364b4f05ed8bca8ca0c24de091871f" integrity sha512-Vmpn2F6IASefL+DVBhPzI2J9/GJUsqzomdeN+P+dK8/jKxbh8R3BtFnx3FIta7wYlPU62cpJMJQo4kuOowcMnw== @@ -14541,14 +14656,23 @@ jest-worker@^26.2.1, jest-worker@^26.3.0: merge-stream "^2.0.0" supports-color "^7.0.0" -jest@^26.0.1: - version "26.4.2" - resolved "https://registry.npmjs.org/jest/-/jest-26.4.2.tgz#7e8bfb348ec33f5459adeaffc1a25d5752d9d312" - integrity sha512-LLCjPrUh98Ik8CzW8LLVnSCfLaiY+wbK53U7VxnFSX7Q+kWC4noVeDvGWIFw0Amfq1lq2VfGm7YHWSLBV62MJw== +jest-worker@^26.5.0: + version "26.5.0" + resolved "https://registry.npmjs.org/jest-worker/-/jest-worker-26.5.0.tgz#87deee86dbbc5f98d9919e0dadf2c40e3152fa30" + integrity sha512-kTw66Dn4ZX7WpjZ7T/SUDgRhapFRKWmisVAF0Rv4Fu8SLFD7eLbqpLvbxVqYhSgaWa7I+bW7pHnbyfNsH6stug== dependencies: - "@jest/core" "^26.4.2" + "@types/node" "*" + merge-stream "^2.0.0" + supports-color "^7.0.0" + +jest@^26.0.1: + version "26.5.3" + resolved "https://registry.npmjs.org/jest/-/jest-26.5.3.tgz#5e7a322d16f558dc565ca97639e85993ef5affe6" + integrity sha512-uJi3FuVSLmkZrWvaDyaVTZGLL8WcfynbRnFXyAHuEtYiSZ+ijDDIMOw1ytmftK+y/+OdAtsG9QrtbF7WIBmOyA== + dependencies: + "@jest/core" "^26.5.3" import-local "^3.0.2" - jest-cli "^26.4.2" + jest-cli "^26.5.3" jose@^1.27.1: version "1.27.1" @@ -14634,10 +14758,10 @@ jsdom@11.12.0: ws "^5.2.0" xml-name-validator "^3.0.0" -jsdom@^16.2.2: - version "16.2.2" - resolved "https://registry.npmjs.org/jsdom/-/jsdom-16.2.2.tgz#76f2f7541646beb46a938f5dc476b88705bedf2b" - integrity sha512-pDFQbcYtKBHxRaP55zGXCJWgFHkDAYbKcsXEK/3Icu9nKYZkutUXfLBwbD+09XDutkYSHcgfQLZ0qvpAAm9mvg== +jsdom@^16.4.0: + version "16.4.0" + resolved "https://registry.npmjs.org/jsdom/-/jsdom-16.4.0.tgz#36005bde2d136f73eee1a830c6d45e55408edddb" + integrity sha512-lYMm3wYdgPhrl7pDcRmvzPhhrGVBeVhPIqeHjzeiHN3DFmD1RBpbExbi8vU7BJdH8VAZYovR8DMt0PNNDM7k8w== dependencies: abab "^2.0.3" acorn "^7.1.1" @@ -14659,36 +14783,13 @@ jsdom@^16.2.2: tough-cookie "^3.0.1" w3c-hr-time "^1.0.2" w3c-xmlserializer "^2.0.0" - webidl-conversions "^6.0.0" + webidl-conversions "^6.1.0" whatwg-encoding "^1.0.5" whatwg-mimetype "^2.3.0" whatwg-url "^8.0.0" ws "^7.2.3" xml-name-validator "^3.0.0" -jsdom@^8.1.0: - version "8.5.0" - resolved "https://registry.npmjs.org/jsdom/-/jsdom-8.5.0.tgz#d4d8f5dbf2768635b62a62823b947cf7071ebc98" - integrity sha1-1Nj12/J2hjW2KmKCO5R89wcevJg= - dependencies: - abab "^1.0.0" - acorn "^2.4.0" - acorn-globals "^1.0.4" - array-equal "^1.0.0" - cssom ">= 0.3.0 < 0.4.0" - cssstyle ">= 0.2.34 < 0.3.0" - escodegen "^1.6.1" - iconv-lite "^0.4.13" - nwmatcher ">= 1.3.7 < 2.0.0" - parse5 "^1.5.1" - request "^2.55.0" - sax "^1.1.4" - symbol-tree ">= 3.1.0 < 4.0.0" - tough-cookie "^2.2.0" - webidl-conversions "^3.0.1" - whatwg-url "^2.0.1" - xml-name-validator ">= 2.0.1 < 3.0.0" - jsesc@^2.5.1: version "2.5.2" resolved "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4" @@ -14887,22 +14988,23 @@ jsonwebtoken@^8.5.1: ms "^2.1.1" semver "^5.6.0" -jspdf-autotable@3.5.3: - version "3.5.3" - resolved "https://registry.npmjs.org/jspdf-autotable/-/jspdf-autotable-3.5.3.tgz#2f73adb07f340e7dbf22950e3e6c8bf853991479" - integrity sha512-K+cNWW3x6w0R/1B5m6PYOm6v8CTTDXy/g32lZouc7SuC6zhvzMN2dauhk6dDYxPD0pky0oyPIJFwSJ/tV8PAeg== +jspdf-autotable@3.5.9: + version "3.5.9" + resolved "https://registry.npmjs.org/jspdf-autotable/-/jspdf-autotable-3.5.9.tgz#8a625ef2aead44271da95e9f649843c401536925" + integrity sha512-ZRfiI5P7leJuWmvC0jGVXu227m68C2Jfz1dkDckshmDYDeVFCGxwIBYdCUXJ8Eb2CyFQC2ok82fEWO+xRDovDQ== -jspdf@1.5.3: - version "1.5.3" - resolved "https://registry.npmjs.org/jspdf/-/jspdf-1.5.3.tgz#5a12c011479defabef5735de55c913060ed219f2" - integrity sha512-J9X76xnncMw+wIqb15HeWfPMqPwYxSpPY8yWPJ7rAZN/ZDzFkjCSZObryCyUe8zbrVRNiuCnIeQteCzMn7GnWw== +jspdf@2.1.0: + version "2.1.0" + resolved "https://registry.npmjs.org/jspdf/-/jspdf-2.1.0.tgz#2322f8644bc41845b3abe20db4c3ca0adeadb84c" + integrity sha512-NQygqZEKhSw+nExySJxB72Ge/027YEyIM450Vh/hgay/H9cgZNnkXXOQPRspe9EuCW4sq92zg8hpAXyyBdnaIQ== dependencies: - canvg "1.5.3" - file-saver eligrey/FileSaver.js#1.3.8 - html2canvas "1.0.0-alpha.12" - omggif "1.0.7" - promise-polyfill "8.1.0" - stackblur-canvas "2.2.0" + atob "^2.1.2" + btoa "^1.2.1" + optionalDependencies: + canvg "^3.0.6" + core-js "^3.6.0" + dompurify "^2.0.12" + html2canvas "^1.0.0-rc.5" jsprim@^1.2.2: version "1.4.1" @@ -15748,7 +15850,7 @@ macos-release@^2.2.0: resolved "https://registry.npmjs.org/macos-release/-/macos-release-2.3.0.tgz#eb1930b036c0800adebccd5f17bc4c12de8bb71f" integrity sha512-OHhSbtcviqMPt7yfw5ef5aghS2jzFVKEFyCJndQt2YpSQ9qRVSEv2axSJI1paVThEu+FFGs584h/1YhxjVqajA== -magic-string@^0.25.2: +magic-string@^0.25.7: version "0.25.7" resolved "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz#3f497d6fd34c669c6798dcb821f2ef31f5445051" integrity sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA== @@ -15890,10 +15992,10 @@ material-colors@^1.2.1: resolved "https://registry.npmjs.org/material-colors/-/material-colors-1.2.6.tgz#6d1958871126992ceecc72f4bcc4d8f010865f46" integrity sha512-6qE4B9deFBIa9YSpOc9O0Sgc43zTeVYbgDT5veRKSlB2+ZuHNoVVxA1L/ckMUayV9Ay9y7Z/SZCLcGteW9i7bg== -material-table@1.68.0: - version "1.68.0" - resolved "https://registry.npmjs.org/material-table/-/material-table-1.68.0.tgz#275c3d9a885c40ae4bc5a7461c00e877f92397b9" - integrity sha512-dyJJaVsS3m+i6sn71AvYcVdA1P9X1XiUOM2PekfvEeeMtkdQb66oChGkk77ndYi3Ja6j4DovGVNrgeVLwXLZiw== +material-table@^1.69.1: + version "1.69.1" + resolved "https://registry.npmjs.org/material-table/-/material-table-1.69.1.tgz#8d1c8b23207f18bd3328cae1b5775ede284682e6" + integrity sha512-7MA8kMtr8ToPE6gNUbOGIb4g+RGOLWK8s9gXZYNwFtg6fGAjWEJ+iqBrMmdq7fkMmTRcyOd7/sC/5OPPY8CNGg== dependencies: "@date-io/date-fns" "^1.1.0" "@material-ui/pickers" "^3.2.2" @@ -15902,8 +16004,8 @@ material-table@1.68.0: debounce "^1.2.0" fast-deep-equal "2.0.1" filefy "0.1.10" - jspdf "1.5.3" - jspdf-autotable "3.5.3" + jspdf "2.1.0" + jspdf-autotable "3.5.9" prop-types "^15.6.2" react-beautiful-dnd "^13.0.0" react-double-scrollbar "0.0.15" @@ -16436,6 +16538,42 @@ msw@^0.20.5: statuses "^2.0.0" yargs "^15.4.1" +msw@^0.21.2: + version "0.21.2" + resolved "https://registry.npmjs.org/msw/-/msw-0.21.2.tgz#74ed10b8eb224325652a3c3812b5460dac297bd8" + integrity sha512-XOJehxtJThNFdMJdVjxDAbZ8KuC3UltOlO5nQDks0Q1yzSUqqKcVUjbKrH7T+K2hckBr0KEY2fwJHv21R4BV2A== + dependencies: + "@open-draft/until" "^1.0.3" + "@types/cookie" "^0.4.0" + chalk "^4.1.0" + chokidar "^3.4.2" + cookie "^0.4.1" + graphql "^15.3.0" + headers-utils "^1.2.0" + node-fetch "^2.6.1" + node-match-path "^0.4.4" + node-request-interceptor "^0.5.1" + statuses "^2.0.0" + yargs "^16.0.3" + +msw@^0.21.3: + version "0.21.3" + resolved "https://registry.npmjs.org/msw/-/msw-0.21.3.tgz#d073842f9570a08f4041806a2c7303a9b8494602" + integrity sha512-voPc/EJsjarvi454vSEuozZQQqLG4AUHT6qQL5Ah47lq7sGCpc7icByeUlfvEj5+MvaugN0c7JwXyCa2rxu8cA== + dependencies: + "@open-draft/until" "^1.0.3" + "@types/cookie" "^0.4.0" + chalk "^4.1.0" + chokidar "^3.4.2" + cookie "^0.4.1" + graphql "^15.3.0" + headers-utils "^1.2.0" + node-fetch "^2.6.1" + node-match-path "^0.4.4" + node-request-interceptor "^0.5.1" + statuses "^2.0.0" + yargs "^16.0.3" + multicast-dns-service-types@^1.1.0: version "1.1.0" resolved "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz#899f11d9686e5e05cb91b35d5f0e63b773cfc901" @@ -16764,6 +16902,15 @@ node-request-interceptor@^0.3.5: debug "^4.1.1" headers-utils "^1.2.0" +node-request-interceptor@^0.5.1: + version "0.5.1" + resolved "https://registry.npmjs.org/node-request-interceptor/-/node-request-interceptor-0.5.1.tgz#b4757a033bde4412d9ffc4503804abb28ed962d2" + integrity sha512-ex5mlI5nGokxocomS2Rj2r1aspmt7qZoI8OvKLt24ylp1bYCzGQ+0XD911guCNDb/kKLMIGC67HHyeFrJCz7jA== + dependencies: + "@open-draft/until" "^1.0.3" + debug "^4.1.1" + headers-utils "^1.2.0" + nodegit@0.27.0, nodegit@^0.27.0: version "0.27.0" resolved "https://registry.npmjs.org/nodegit/-/nodegit-0.27.0.tgz#4e8cc236f60e1c97324a5acff99056fe116a6ebe" @@ -16964,11 +17111,6 @@ number-is-nan@^1.0.0: resolved "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= -"nwmatcher@>= 1.3.7 < 2.0.0": - version "1.4.4" - resolved "https://registry.npmjs.org/nwmatcher/-/nwmatcher-1.4.4.tgz#2285631f34a95f0d0395cd900c96ed39b58f346e" - integrity sha512-3iuY4N5dhgMpCUrOVnuAdGrgxVqV2cJpM+XNccjR2DKOB1RUP0aA+wGXEiNziG/UKboFyGBIoKOaNlJxx8bciQ== - nwsapi@^2.0.7, nwsapi@^2.2.0: version "2.2.0" resolved "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz#204879a9e3d068ff2a55139c2c772780681a38b7" @@ -17024,9 +17166,9 @@ object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== object-path@^0.11.4: - version "0.11.4" - resolved "https://registry.npmjs.org/object-path/-/object-path-0.11.4.tgz#370ae752fbf37de3ea70a861c23bba8915691949" - integrity sha1-NwrnUvvzfePqcKhhwju6iRVpGUk= + version "0.11.5" + resolved "https://registry.yarnpkg.com/object-path/-/object-path-0.11.5.tgz#d4e3cf19601a5140a55a16ad712019a9c50b577a" + integrity sha512-jgSbThcoR/s+XumvGMTMf81QVBmah+/Q7K7YduKeKVWL7N111unR2d6pZZarSk6kY/caeNxUDyxOvMWyzoU2eg== object-visit@^1.0.0: version "1.0.1" @@ -17128,11 +17270,6 @@ oidc-token-hash@^5.0.0: resolved "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.0.0.tgz#acdfb1f4310f58e64d5d74a4e8671a426986e888" integrity sha512-8Yr4CZSv+Tn8ZkN3iN2i2w2G92mUKClp4z7EGUfdsERiYSbj7P4i/NHm72ft+aUdsiFx9UdIPSTwbyzQ6C4URg== -omggif@1.0.7: - version "1.0.7" - resolved "https://registry.npmjs.org/omggif/-/omggif-1.0.7.tgz#59d2eecb0263de84635b3feb887c0c9973f1e49d" - integrity sha1-WdLuywJj3oRjWz/riHwMmXPx5J0= - on-finished@^2.3.0, on-finished@~2.3.0: version "2.3.0" resolved "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947" @@ -17668,11 +17805,6 @@ parse5@5.1.1: resolved "https://registry.npmjs.org/parse5/-/parse5-5.1.1.tgz#f68e4e5ba1852ac2cadc00f4555fff6c2abb6178" integrity sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug== -parse5@^1.5.1: - version "1.5.1" - resolved "https://registry.npmjs.org/parse5/-/parse5-1.5.1.tgz#9b7f3b0de32be78dc2401b17573ccaf0f6f59d94" - integrity sha1-m387DeMr543CQBsXVzzK8Pb1nZQ= - parseurl@^1.3.2, parseurl@~1.3.2, parseurl@~1.3.3: version "1.3.3" resolved "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" @@ -18654,7 +18786,7 @@ pretty-error@^2.1.1: renderkid "^2.0.1" utila "~0.4" -pretty-format@^25.1.0, pretty-format@^25.2.1, pretty-format@^25.5.0: +pretty-format@^25.2.1, pretty-format@^25.5.0: version "25.5.0" resolved "https://registry.npmjs.org/pretty-format/-/pretty-format-25.5.0.tgz#7873c1d774f682c34b8d48b6743a2bf2ac55791a" integrity sha512-kbo/kq2LQ/A/is0PQwsEHM7Ca6//bGPPvU6UnsdDRSKTWxT/ru/xb88v4BJf6a69H+uTytOEsTusT9ksd/1iWQ== @@ -18674,6 +18806,16 @@ pretty-format@^26.4.2: ansi-styles "^4.0.0" react-is "^16.12.0" +pretty-format@^26.5.2: + version "26.5.2" + resolved "https://registry.npmjs.org/pretty-format/-/pretty-format-26.5.2.tgz#5d896acfdaa09210683d34b6dc0e6e21423cd3e1" + integrity sha512-VizyV669eqESlkOikKJI8Ryxl/kPpbdLwNdPs2GrbQs18MpySB5S0Yo0N7zkg2xTRiFq4CFw8ct5Vg4a0xP0og== + dependencies: + "@jest/types" "^26.5.2" + ansi-regex "^5.0.0" + ansi-styles "^4.0.0" + react-is "^16.12.0" + pretty-hrtime@^1.0.3: version "1.0.3" resolved "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz#b7e3ea42435a4c9b2759d99e0f201eb195802ee1" @@ -18725,16 +18867,6 @@ promise-inflight@^1.0.1: resolved "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3" integrity sha1-mEcocL8igTL8vdhoEputEsPAKeM= -promise-polyfill@8.1.0: - version "8.1.0" - resolved "https://registry.npmjs.org/promise-polyfill/-/promise-polyfill-8.1.0.tgz#30059da54d1358ce905ac581f287e184aedf995d" - integrity sha512-OzSf6gcCUQ01byV4BgwyUCswlaQQ6gzXc23aLQWhicvfX9kfsUiUhgt3CCQej8jDnl8/PhGF31JdHX2/MzF3WA== - -promise-polyfill@^8.1.3: - version "8.1.3" - resolved "https://registry.npmjs.org/promise-polyfill/-/promise-polyfill-8.1.3.tgz#8c99b3cf53f3a91c68226ffde7bde81d7f904116" - integrity sha512-MG5r82wBzh7pSKDRa9y+vllNHz3e3d4CNj1PQE4BQYxLme0gKYYBm9YENq+UkEikyZ0XbiGWxYlVw3Rl9O/U8g== - promise-retry@^1.1.1: version "1.1.1" resolved "https://registry.npmjs.org/promise-retry/-/promise-retry-1.1.1.tgz#6739e968e3051da20ce6497fb2b50f6911df3d6d" @@ -19484,7 +19616,7 @@ react-router@5.2.0: tiny-invariant "^1.0.2" tiny-warning "^1.0.0" -react-router@6.0.0-beta.0: +react-router@6.0.0-beta.0, react-router@^6.0.0-beta.0: version "6.0.0-beta.0" resolved "https://registry.npmjs.org/react-router/-/react-router-6.0.0-beta.0.tgz#3e11f39b6ded4412c2fed9e4f989dd4c8156724d" integrity sha512-VgMdfpVcmFQki/LZuLh8E/MNACekDetz4xqft+a6fBZvvJnVqKbLqebF7hyoawGrV1HcO5tVaUang2Og4W2j1Q== @@ -20053,6 +20185,11 @@ regjsparser@^0.6.4: dependencies: jsesc "~0.5.0" +regression@^2.0.1: + version "2.0.1" + resolved "https://registry.npmjs.org/regression/-/regression-2.0.1.tgz#8d29c3e8224a10850c35e337e85a8b2fac3b0c87" + integrity sha1-jSnD6CJKEIUMNeM36FqLL6w7DIc= + relateurl@^0.2.7: version "0.2.7" resolved "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz#54dbf377e51440aca90a4cd274600d3ff2d888a9" @@ -20202,7 +20339,7 @@ request-promise-native@^1.0.5, request-promise-native@^1.0.8: stealthy-require "^1.1.1" tough-cookie "^2.3.3" -request@^2.55.0, request@^2.85.0, request@^2.87.0, request@^2.88.0, request@^2.88.2: +request@^2.85.0, request@^2.87.0, request@^2.88.0, request@^2.88.2: version "2.88.2" resolved "https://registry.npmjs.org/request/-/request-2.88.2.tgz#d73c918731cb5a87da047e207234146f664d12b3" integrity sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw== @@ -20310,7 +20447,7 @@ resolve-url@^0.2.1: resolved "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= -resolve@1.17.0, resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.11.0, resolve@^1.12.0, resolve@^1.13.1, resolve@^1.15.1, resolve@^1.16.1, resolve@^1.17.0, resolve@^1.3.2: +resolve@1.17.0, resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.12.0, resolve@^1.13.1, resolve@^1.15.1, resolve@^1.16.1, resolve@^1.17.0, resolve@^1.3.2: version "1.17.0" resolved "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== @@ -20431,10 +20568,10 @@ ripemd160@^2.0.0, ripemd160@^2.0.1: hash-base "^3.0.0" inherits "^2.0.1" -rollup-plugin-dts@1.4.11: - version "1.4.11" - resolved "https://registry.npmjs.org/rollup-plugin-dts/-/rollup-plugin-dts-1.4.11.tgz#aedf0b7bb91d51e20b755e2c18e840edfc7af7a1" - integrity sha512-yiScAMKgwH77b44a/IFGgjLsmwSlNfQhEM+eCb2uMrupQMPE1n/12wrnT431+v1u6wYMF1XuHqldh+v/7mTvYA== +rollup-plugin-dts@1.4.13: + version "1.4.13" + resolved "https://registry.npmjs.org/rollup-plugin-dts/-/rollup-plugin-dts-1.4.13.tgz#4f086e84f4fdcc1f49160799ebc66f6b09db292b" + integrity sha512-7mxoQ6PcmCkBE5ZhrjGDL4k42XLy8BkSqpiRi1MipwiGs+7lwi4mQkp2afX+OzzLjJp/TGM8llfe8uayIUhPEw== optionalDependencies: "@babel/code-frame" "^7.10.4" @@ -20600,7 +20737,7 @@ sanitize-html@^1.27.0: srcset "^2.0.1" xtend "^4.0.1" -sax@>=0.6.0, sax@^1.1.4, sax@^1.2.4, sax@~1.2.4: +sax@>=0.6.0, sax@^1.2.4, sax@~1.2.4: version "1.2.4" resolved "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== @@ -21123,7 +21260,7 @@ source-list-map@^2.0.0: resolved "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz#3993bd873bfc48479cca9ea3a547835c7c154b34" integrity sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw== -source-map-resolve@^0.5.0, source-map-resolve@^0.5.2: +source-map-resolve@^0.5.0: version "0.5.3" resolved "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz#190866bece7553e1f8f267a2ee82c606b5509a1a" integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw== @@ -21134,6 +21271,14 @@ source-map-resolve@^0.5.0, source-map-resolve@^0.5.2: source-map-url "^0.4.0" urix "^0.1.0" +source-map-resolve@^0.6.0: + version "0.6.0" + resolved "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.6.0.tgz#3d9df87e236b53f16d01e58150fc7711138e5ed2" + integrity sha512-KXBr9d/fO/bWo97NXsPIAW1bFSBOuCnjbNTBMO7N59hsv5i9yzRDfcYwwt0l04+VqnKC+EwzvJZIP/qkuMgR/w== + dependencies: + atob "^2.1.2" + decode-uri-component "^0.2.0" + source-map-support@^0.5.16, source-map-support@^0.5.17, source-map-support@^0.5.6, source-map-support@~0.5.12: version "0.5.19" resolved "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" @@ -21366,15 +21511,10 @@ stack-utils@^2.0.2: dependencies: escape-string-regexp "^2.0.0" -stackblur-canvas@2.2.0: - version "2.2.0" - resolved "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.2.0.tgz#cacc5924a0744b3e183eb2e6c1d8559c1a17c26e" - integrity sha512-5Gf8dtlf8k6NbLzuly2NkGrkS/Ahh+I5VUjO7TnFizdJtgpfpLLEdQlLe9umbcnZlitU84kfYjXE67xlSXfhfQ== - -stackblur-canvas@^1.4.1: - version "1.4.1" - resolved "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-1.4.1.tgz#849aa6f94b272ff26f6471fa4130ed1f7e47955b" - integrity sha1-hJqm+UsnL/JvZHH6QTDtH35HlVs= +stackblur-canvas@^2.0.0: + version "2.4.0" + resolved "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.4.0.tgz#2b2eba910cb46f6feae918e1c402f863d602c01b" + integrity sha512-Z+HixfgYV0ss3C342DxPwc+UvN1SYWqoz7Wsi3xEDWEnaBkSCL3Ey21gF4io+WlLm8/RIrSnCrDBIEcH4O+q5Q== stackframe@^1.1.1: version "1.1.1" @@ -21821,10 +21961,10 @@ subscriptions-transport-ws@^0.9.11, subscriptions-transport-ws@^0.9.16: symbol-observable "^1.0.4" ws "^5.2.0" -sucrase@^3.14.1: - version "3.15.0" - resolved "https://registry.npmjs.org/sucrase/-/sucrase-3.15.0.tgz#78596a78be7264a65b52ed8d873883413ef0220c" - integrity sha512-05TJOUfMgckH7wKqfk/1p4G6q16nIeW/GHQwD44vkT0mQMqqzgfHCwkX3whNmwyOo7nVF0jDLwVu/qOBTtsscw== +sucrase@^3.16.0: + version "3.16.0" + resolved "https://registry.npmjs.org/sucrase/-/sucrase-3.16.0.tgz#19b5b886ccca270dd5ca12ff060eeaf0b599735f" + integrity sha512-ovVuswxV5TayCPXfTk8bgBgk6uNRvsinIkEpq0J6zS1xXCx5N/LLGcbsKdRhqn/ToZylMX6+yXaR1LSn1I42Pg== dependencies: commander "^4.0.0" glob "7.1.6" @@ -21996,7 +22136,7 @@ symbol-observable@^1.0.4, symbol-observable@^1.1.0, symbol-observable@^1.2.0: resolved "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804" integrity sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ== -"symbol-tree@>= 3.1.0 < 4.0.0", symbol-tree@^3.2.2, symbol-tree@^3.2.4: +symbol-tree@^3.2.2, symbol-tree@^3.2.4: version "3.2.4" resolved "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== @@ -22476,7 +22616,7 @@ touch@^3.1.0: dependencies: nopt "~1.0.10" -tough-cookie@^2.2.0, tough-cookie@^2.3.3, tough-cookie@^2.3.4, tough-cookie@~2.5.0: +tough-cookie@^2.3.3, tough-cookie@^2.3.4, tough-cookie@~2.5.0: version "2.5.0" resolved "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz#cd9fb2a0aa1d5a12b473bd9fb96fa3dcff65ade2" integrity sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g== @@ -22507,11 +22647,6 @@ tr46@^2.0.2: dependencies: punycode "^2.1.1" -tr46@~0.0.3: - version "0.0.3" - resolved "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" - integrity sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o= - traverse@~0.6.6: version "0.6.6" resolved "https://registry.npmjs.org/traverse/-/traverse-0.6.6.tgz#cbdf560fd7b9af632502fed40f918c157ea97137" @@ -22796,10 +22931,10 @@ typedarray@^0.0.6: resolved "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= -typescript@^3.9.3: - version "3.9.7" - resolved "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz#98d600a5ebdc38f40cb277522f12dc800e9e25fa" - integrity sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw== +typescript@^4.0.3: + version "4.0.3" + resolved "https://registry.npmjs.org/typescript/-/typescript-4.0.3.tgz#153bbd468ef07725c1df9c77e8b453f8d36abba5" + integrity sha512-tEu6DGxGgRJPb/mVPIZ48e69xCn2yRmCgYmDugAVwmJ6o+0u1RI18eO7E7WBTLYLaEVVOhwQmcdhQHweux/WPg== ua-parser-js@^0.7.18: version "0.7.21" @@ -23230,10 +23365,10 @@ v8-compile-cache@^2.0.3: resolved "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.1.0.tgz#e14de37b31a6d194f5690d67efc4e7f6fc6ab30e" integrity sha512-usZBT3PW+LOjM25wbqIlZwPeJV+3OSz3M1k1Ws8snlW39dZyYL9lOGC5FgPVHfk0jKmjiDV8Z0mIbVQPiwFs7g== -v8-to-istanbul@^5.0.1: - version "5.0.1" - resolved "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-5.0.1.tgz#0608f5b49a481458625edb058488607f25498ba5" - integrity sha512-mbDNjuDajqYe3TXFk5qxcQy8L1msXNE37WTlLoqqpBfRsimbNcrlhQlDPntmECEcUvdC+AQ8CyMMf6EUx1r74Q== +v8-to-istanbul@^6.0.1: + version "6.0.1" + resolved "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-6.0.1.tgz#7ef0e32faa10f841fe4c1b0f8de96ed067c0be1e" + integrity sha512-PzM1WlqquhBvsV+Gco6WSFeg1AGdD53ccMRkFeyHRE/KRZaVacPOmQYP3EeVgDBtKD2BJ8kgynBQ5OtKiHCH+w== dependencies: "@types/istanbul-lib-coverage" "^2.0.1" convert-source-map "^1.6.0" @@ -23445,11 +23580,6 @@ webapi-parser@^0.5.0: dependencies: ajv "6.5.2" -webidl-conversions@^3.0.0, webidl-conversions@^3.0.1: - version "3.0.1" - resolved "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" - integrity sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE= - webidl-conversions@^4.0.2: version "4.0.2" resolved "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad" @@ -23460,7 +23590,7 @@ webidl-conversions@^5.0.0: resolved "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-5.0.0.tgz#ae59c8a00b121543a2acc65c0434f57b0fc11aff" integrity sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA== -webidl-conversions@^6.0.0: +webidl-conversions@^6.1.0: version "6.1.0" resolved "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz#9111b4d7ea80acd40f5270d666621afa78b69514" integrity sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w== @@ -23642,7 +23772,7 @@ whatwg-fetch@^2.0.4: resolved "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.4.tgz#dde6a5df315f9d39991aa17621853d720b85566f" integrity sha512-dcQ1GWpOD/eEQ97k66aiEVpNnapVj90/+R+SXTPYGHpYBBypfKJEQjLrvMZ7YXbKm21gXd4NcuxUTjiv1YtLng== -whatwg-fetch@^3.0.0, whatwg-fetch@^3.4.0, whatwg-fetch@^3.4.1: +whatwg-fetch@^3.0.0, whatwg-fetch@^3.4.1: version "3.4.1" resolved "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.4.1.tgz#e5f871572d6879663fa5674c8f833f15a8425ab3" integrity sha512-sofZVzE1wKwO+EYPbWfiwzaKovWiZXf4coEzjGP9b2GBVgQRLQUZ2QcuPpQExGDAW5GItpEm6Tl4OU5mywnAoQ== @@ -23652,14 +23782,6 @@ whatwg-mimetype@^2.1.0, whatwg-mimetype@^2.2.0, whatwg-mimetype@^2.3.0: resolved "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz#3d4b1e0312d2079879f826aff18dbeeca5960fbf" integrity sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g== -whatwg-url@^2.0.1: - version "2.0.1" - resolved "https://registry.npmjs.org/whatwg-url/-/whatwg-url-2.0.1.tgz#5396b2043f020ee6f704d9c45ea8519e724de659" - integrity sha1-U5ayBD8CDub3BNnEXqhRnnJN5lk= - dependencies: - tr46 "~0.0.3" - webidl-conversions "^3.0.0" - whatwg-url@^6.4.1: version "6.5.0" resolved "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.5.0.tgz#f2df02bff176fd65070df74ad5ccbb5a199965a8" @@ -23974,11 +24096,6 @@ xml-encryption@^1.0.0: xmldom "~0.1.15" xpath "0.0.27" -"xml-name-validator@>= 2.0.1 < 3.0.0": - version "2.0.1" - resolved "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-2.0.1.tgz#4d8b8f1eccd3419aa362061becef515e1e559635" - integrity sha1-TYuPHszTQZqjYgYb7O9RXh5VljU= - xml-name-validator@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a" @@ -24007,7 +24124,7 @@ xmldom@0.1.27: resolved "https://registry.npmjs.org/xmldom/-/xmldom-0.1.27.tgz#d501f97b3bdb403af8ef9ecc20573187aadac0e9" integrity sha1-1QH5ezvbQDr4757MIFcxh6rawOk= -xmldom@0.1.x, xmldom@^0.1.22, xmldom@~0.1.15: +xmldom@0.1.x, xmldom@~0.1.15: version "0.1.31" resolved "https://registry.npmjs.org/xmldom/-/xmldom-0.1.31.tgz#b76c9a1bd9f0a9737e5a72dc37231cf38375e2ff" integrity sha512-yS2uJflVQs6n+CyjHoaBmVSqIDevTAWrzMmjG1Gc7h1qQ7uVozNhEPJAwZXWyGQ/Gafo3fCwrcaokezLPupVyQ== @@ -24235,7 +24352,7 @@ yn@^4.0.0: resolved "https://registry.npmjs.org/yn/-/yn-4.0.0.tgz#611480051ea43b510da1dfdbe177ed159f00a979" integrity sha512-huWiiCS4TxKc4SfgmTwW1K7JmXPPAmuXWYy4j9qjQo4+27Kni8mGhAAi1cloRWmBe2EqcLgt3IGqQoRL/MtPgg== -yup@^0.29.1: +yup@^0.29.3: version "0.29.3" resolved "https://registry.npmjs.org/yup/-/yup-0.29.3.tgz#69a30fd3f1c19f5d9e31b1cf1c2b851ce8045fea" integrity sha512-RNUGiZ/sQ37CkhzKFoedkeMfJM0vNQyaz+wRZJzxdKE7VfDeVKH8bb4rr7XhRLbHJz5hSjoDNwMEIaKhuMZ8gQ==