diff --git a/.changeset/afraid-chairs-warn.md b/.changeset/afraid-chairs-warn.md deleted file mode 100644 index 1ae2a7513e..0000000000 --- a/.changeset/afraid-chairs-warn.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@backstage/errors': patch ---- - -Deprecate `parseErrorResponse` in favour of `parseErrorResponseBody`. Deprecate `data` field inside `ErrorResponse` in favour of `body`. -Rename the error name for unknown errors from `unknown` to `error`. diff --git a/.changeset/curly-points-hide.md b/.changeset/curly-points-hide.md deleted file mode 100644 index ba513e5915..0000000000 --- a/.changeset/curly-points-hide.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@backstage/plugin-tech-insights-backend': patch -'@backstage/plugin-tech-insights-backend-module-jsonfc': patch ---- - -Update README docs to use correct function/parameter names diff --git a/.changeset/curly-rings-report.md b/.changeset/curly-rings-report.md new file mode 100644 index 0000000000..554cd0d1a8 --- /dev/null +++ b/.changeset/curly-rings-report.md @@ -0,0 +1,7 @@ +--- +'@backstage/core-components': patch +'@backstage/create-app': patch +'@backstage/plugin-catalog': patch +--- + +Addressed some peer dependency warnings diff --git a/.changeset/early-dragons-wave.md b/.changeset/early-dragons-wave.md deleted file mode 100644 index 641f36a9f3..0000000000 --- a/.changeset/early-dragons-wave.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-scaffolder': patch ---- - -Bump `react-jsonschema-form` diff --git a/.changeset/five-lies-care.md b/.changeset/five-lies-care.md new file mode 100644 index 0000000000..dab3f55d52 --- /dev/null +++ b/.changeset/five-lies-care.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder': patch +--- + +Can specify allowedOwners to the RepoUrlPicker picker in a template definition diff --git a/.changeset/fluffy-countries-knock.md b/.changeset/fluffy-countries-knock.md new file mode 100644 index 0000000000..44dddbbca7 --- /dev/null +++ b/.changeset/fluffy-countries-knock.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder-backend': patch +--- + +Bump esbuild to ^0.14.1 diff --git a/.changeset/forty-teachers-argue.md b/.changeset/forty-teachers-argue.md deleted file mode 100644 index 2e32719037..0000000000 --- a/.changeset/forty-teachers-argue.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-auth-backend': patch ---- - -Switched to using the standardized JSON error responses for all provider endpoints. diff --git a/.changeset/fresh-radios-compete.md b/.changeset/fresh-radios-compete.md new file mode 100644 index 0000000000..221072eb95 --- /dev/null +++ b/.changeset/fresh-radios-compete.md @@ -0,0 +1,14 @@ +--- +'@backstage/plugin-kubernetes': minor +'@backstage/plugin-kubernetes-backend': minor +'@backstage/plugin-kubernetes-common': minor +--- + +Add pod metrics lookup and display in pod table. + +## Backwards incompatible changes + +If your Kubernetes distribution does not have the [metrics server](https://github.com/kubernetes-sigs/metrics-server) installed, +you will need to set the `skipMetricsLookup` config flag to `false`. + +See the [configuration docs](https://backstage.io/docs/features/kubernetes/configuration) for more details. diff --git a/.changeset/giant-bees-applaud.md b/.changeset/giant-bees-applaud.md deleted file mode 100644 index c4591dbc64..0000000000 --- a/.changeset/giant-bees-applaud.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/cli': patch ---- - -Switch the default test coverage provider from the jest default one to `'v8'`, which provides much better coverage information when using the default Backstage test setup. This is considered a bug fix as the current coverage information is often very inaccurate. diff --git a/.changeset/heavy-tools-hang.md b/.changeset/heavy-tools-hang.md deleted file mode 100644 index 91a843b0a7..0000000000 --- a/.changeset/heavy-tools-hang.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-permission-node': patch ---- - -New package containing common permission and authorization utilities for backend plugins. For more information, see the [authorization PRFC](https://github.com/backstage/backstage/pull/7761). diff --git a/.changeset/hot-dragons-kneel.md b/.changeset/hot-dragons-kneel.md new file mode 100644 index 0000000000..a2b6241b69 --- /dev/null +++ b/.changeset/hot-dragons-kneel.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': patch +--- + +Reject catalog entities that have duplicate fields that vary only in casing. diff --git a/.changeset/large-mugs-repair.md b/.changeset/large-mugs-repair.md deleted file mode 100644 index 5043fb80e1..0000000000 --- a/.changeset/large-mugs-repair.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/cli': patch ---- - -Disable ES transforms in tests transformed by the `jestSucraseTransform.js`. This is not considered a breaking change since all code is already transpiled this way in the development setup. diff --git a/.changeset/large-pears-agree.md b/.changeset/large-pears-agree.md deleted file mode 100644 index 60f755eff0..0000000000 --- a/.changeset/large-pears-agree.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/create-app': patch ---- - -DefaultTechDocsCollator is now included in the search backend, and the Search Page updated with the SearchType component that includes the techdocs type diff --git a/.changeset/light-pigs-protect.md b/.changeset/light-pigs-protect.md new file mode 100644 index 0000000000..358547af8a --- /dev/null +++ b/.changeset/light-pigs-protect.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder': patch +--- + +Fix bug with setting owner in RepoUrlPicker causing validation failure diff --git a/.changeset/many-waves-visit.md b/.changeset/many-waves-visit.md deleted file mode 100644 index 4f4711f371..0000000000 --- a/.changeset/many-waves-visit.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-catalog-backend': patch ---- - -Providing an empty values array in an EntityFilter will now return no matches. diff --git a/.changeset/strong-seahorses-scream.md b/.changeset/old-dingos-shave.md similarity index 57% rename from .changeset/strong-seahorses-scream.md rename to .changeset/old-dingos-shave.md index bbd1d44378..3263a89c0d 100644 --- a/.changeset/strong-seahorses-scream.md +++ b/.changeset/old-dingos-shave.md @@ -2,4 +2,4 @@ '@backstage/plugin-catalog-backend': patch --- -Added Azure DevOps discovery processor +Honor database migration configuration diff --git a/.changeset/olive-pens-poke.md b/.changeset/olive-pens-poke.md new file mode 100644 index 0000000000..8a009af971 --- /dev/null +++ b/.changeset/olive-pens-poke.md @@ -0,0 +1,5 @@ +--- +'@backstage/core-components': patch +--- + +Use ellipsis style for overflowed text in sidebar menu diff --git a/.changeset/pretty-eagles-relate.md b/.changeset/pretty-eagles-relate.md new file mode 100644 index 0000000000..9e17be05d3 --- /dev/null +++ b/.changeset/pretty-eagles-relate.md @@ -0,0 +1,10 @@ +--- +'@backstage/cli': patch +--- + +Add cli option to minify the generated code of a plugin or backend package + +``` +backstage-cli plugin:build --minify +backstage-cli backend:build --minify +``` diff --git a/.changeset/pretty-trains-appear.md b/.changeset/pretty-trains-appear.md deleted file mode 100644 index 9a7b313524..0000000000 --- a/.changeset/pretty-trains-appear.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -'@backstage/backend-common': patch -'@backstage/cli': patch -'@backstage/core-app-api': patch -'@backstage/create-app': patch -'@backstage/techdocs-common': patch -'@backstage/plugin-auth-backend': patch -'@backstage/plugin-azure-devops-backend': patch -'@backstage/plugin-badges-backend': patch -'@backstage/plugin-bazaar-backend': patch -'@backstage/plugin-catalog-backend': patch -'@backstage/plugin-code-coverage-backend': patch -'@backstage/plugin-github-actions': patch -'@backstage/plugin-jenkins-backend': patch -'@backstage/plugin-proxy-backend': patch -'@backstage/plugin-rollbar-backend': patch -'@backstage/plugin-search-backend': patch -'@backstage/plugin-techdocs': patch -'@backstage/plugin-techdocs-backend': patch ---- - -Change default port of backend from 7000 to 7007. - -This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. - -You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: - -``` -backend: - listen: 0.0.0.0:7123 - baseUrl: http://localhost:7123 -``` - -More information can be found here: https://backstage.io/docs/conf/writing diff --git a/.changeset/purple-grapes-attack.md b/.changeset/purple-grapes-attack.md deleted file mode 100644 index a2a99690e9..0000000000 --- a/.changeset/purple-grapes-attack.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-permission-common': minor ---- - -Accept configApi rather than enabled flag in PermissionClient constructor. diff --git a/.changeset/search-hip-schools-burn.md b/.changeset/search-hip-schools-burn.md new file mode 100644 index 0000000000..12cef5f5ca --- /dev/null +++ b/.changeset/search-hip-schools-burn.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-search': patch +--- + +Export SearchApi interface from plugin diff --git a/.changeset/seven-rabbits-shave.md b/.changeset/seven-rabbits-shave.md new file mode 100644 index 0000000000..9e14cde2e7 --- /dev/null +++ b/.changeset/seven-rabbits-shave.md @@ -0,0 +1,5 @@ +--- +'@backstage/backend-common': patch +--- + +Add options argument to support additional database migrations configuration diff --git a/.changeset/sharp-carrots-press.md b/.changeset/sharp-carrots-press.md deleted file mode 100644 index a7c31d6759..0000000000 --- a/.changeset/sharp-carrots-press.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@backstage/plugin-config-schema': patch -'@backstage/plugin-scaffolder': patch ---- - -Fixed a missing `await` when throwing server side errors diff --git a/.changeset/shiny-insects-remember.md b/.changeset/shiny-insects-remember.md deleted file mode 100644 index a26882b65d..0000000000 --- a/.changeset/shiny-insects-remember.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-scaffolder-backend': patch ---- - -Fix bug where there was error log lines written when failing to `JSON.parse` things that were not `JSON` values. diff --git a/.changeset/sixty-files-talk.md b/.changeset/sixty-files-talk.md new file mode 100644 index 0000000000..67d8c48b7e --- /dev/null +++ b/.changeset/sixty-files-talk.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-analytics-module-ga': patch +--- + +Support self hosted analytics.js script via `scriptSrc` config option diff --git a/.changeset/slow-olives-confess.md b/.changeset/slow-olives-confess.md deleted file mode 100644 index 68b2539157..0000000000 --- a/.changeset/slow-olives-confess.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@backstage/core-plugin-api': patch ---- - -Deprecated `register` option of `createPlugin` and the `outputs` methods of the plugin instance. - -Introduces the `featureFlags` property to define your feature flags instead. diff --git a/.changeset/smart-fans-complain.md b/.changeset/smart-fans-complain.md deleted file mode 100644 index db404f110d..0000000000 --- a/.changeset/smart-fans-complain.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -'@backstage/plugin-catalog-backend': minor ---- - -**BREAKING** EntitiesSearchFilter fields have changed. - -EntitiesSearchFilter now has only two fields: `key` and `value`. The `matchValueIn` and `matchValueExists` fields are no longer are supported. Previous filters written using the `matchValueIn` and `matchValueExists` fields can be rewritten as follows: - -Filtering by existence of key only: - -```diff - filter: { - { - key: 'abc', -- matchValueExists: true, - }, - } -``` - -Filtering by key and values: - -```diff - filter: { - { - key: 'abc', -- matchValueExists: true, -- matchValueIn: ['xyz'], -+ values: ['xyz'], - }, - } -``` - -Negation of filters can now be achieved through a `not` object: - -``` -filter: { - not: { - key: 'abc', - values: ['xyz'], - }, -} -``` diff --git a/.changeset/smooth-vans-boil.md b/.changeset/smooth-vans-boil.md deleted file mode 100644 index 39b2ea386f..0000000000 --- a/.changeset/smooth-vans-boil.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-catalog-backend': patch ---- - -Index User entities by displayName to be able to search by full name. Added displayName (if present) to the 'text' field in the indexed document. diff --git a/.changeset/swift-clocks-cry.md b/.changeset/swift-clocks-cry.md new file mode 100644 index 0000000000..8f37a2e340 --- /dev/null +++ b/.changeset/swift-clocks-cry.md @@ -0,0 +1,5 @@ +--- +'@backstage/backend-common': patch +--- + +Add knexConfig config section diff --git a/.changeset/techdocs-blue-vans-care.md b/.changeset/techdocs-blue-vans-care.md new file mode 100644 index 0000000000..a648a7aea1 --- /dev/null +++ b/.changeset/techdocs-blue-vans-care.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-techdocs': patch +--- + +The problem of lowercase entity triplets which causes docs to not load on entity page is fixed. diff --git a/.changeset/techdocs-satisfied-you-blinked.md b/.changeset/techdocs-satisfied-you-blinked.md new file mode 100644 index 0000000000..4cbc9d4f3e --- /dev/null +++ b/.changeset/techdocs-satisfied-you-blinked.md @@ -0,0 +1,7 @@ +--- +'@backstage/techdocs-common': minor +'@backstage/plugin-techdocs-backend': minor +--- + +Added the ability for the TechDocs Backend to (optionally) leverage a cache +store to improve performance when reading files from a cloud storage provider. diff --git a/.changeset/the-renegade-feeling.md b/.changeset/the-renegade-feeling.md new file mode 100644 index 0000000000..c9a4b1965e --- /dev/null +++ b/.changeset/the-renegade-feeling.md @@ -0,0 +1,42 @@ +--- +'@backstage/create-app': patch +--- + +TechDocs Backend may now (optionally) leverage a cache store to improve +performance when reading content from a cloud storage provider. + +To apply this change to an existing app, pass the cache manager from the plugin +environment to the `createRouter` function in your backend: + +```diff +// packages/backend/src/plugins/techdocs.ts + +export default async function createPlugin({ + logger, + config, + discovery, + reader, ++ cache, +}: PluginEnvironment): Promise { + + // ... + + return await createRouter({ + preparers, + generators, + publisher, + logger, + config, + discovery, ++ cache, + }); +``` + +If your `PluginEnvironment` does not include a cache manager, be sure you've +applied [the cache management change][cm-change] to your backend as well. + +[Additional configuration][td-rec-arch] is required if you wish to enable +caching in TechDocs. + +[cm-change]: https://github.com/backstage/backstage/blob/master/packages/create-app/CHANGELOG.md#patch-changes-6 +[td-rec-arch]: https://backstage.io/docs/features/techdocs/architecture#recommended-deployment diff --git a/.changeset/thirty-fireants-occur.md b/.changeset/thirty-fireants-occur.md deleted file mode 100644 index dc9348ac6e..0000000000 --- a/.changeset/thirty-fireants-occur.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-catalog-backend': patch ---- - -Detect a duplicate entities when adding locations through dry run diff --git a/.changeset/thirty-readers-attack.md b/.changeset/thirty-readers-attack.md new file mode 100644 index 0000000000..cd05f4ebf4 --- /dev/null +++ b/.changeset/thirty-readers-attack.md @@ -0,0 +1,5 @@ +--- +'@backstage/create-app': patch +--- + +Bump @spotify/prettier-config diff --git a/.changeset/thirty-tigers-refuse.md b/.changeset/thirty-tigers-refuse.md deleted file mode 100644 index 0797d36747..0000000000 --- a/.changeset/thirty-tigers-refuse.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@backstage/create-app': patch -'@backstage/plugin-scaffolder-backend': patch ---- - -Bump gitbeaker to the latest version diff --git a/.changeset/three-coins-kiss.md b/.changeset/three-coins-kiss.md new file mode 100644 index 0000000000..a4b0c83288 --- /dev/null +++ b/.changeset/three-coins-kiss.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-xcmetrics': patch +--- + +Handle a case where XCode data from backend (before 0.0.8) could be missing diff --git a/.changeset/three-news-worry.md b/.changeset/three-news-worry.md new file mode 100644 index 0000000000..24c7daa240 --- /dev/null +++ b/.changeset/three-news-worry.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-bazaar-backend': patch +--- + +Handle migration error when old data is present in the database diff --git a/.changeset/tiny-trains-notice.md b/.changeset/tiny-trains-notice.md new file mode 100644 index 0000000000..e6d260633e --- /dev/null +++ b/.changeset/tiny-trains-notice.md @@ -0,0 +1,5 @@ +--- +'@backstage/create-app': patch +--- + +Removed the `scaffolder.github.visibility` configuration that is no longer used from the default app template. diff --git a/.changeset/weak-berries-sing.md b/.changeset/weak-berries-sing.md deleted file mode 100644 index 1b0cb8d719..0000000000 --- a/.changeset/weak-berries-sing.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/cli': patch ---- - -Update the default routes to use id instead of title diff --git a/.changeset/wet-seas-deliver.md b/.changeset/wet-seas-deliver.md deleted file mode 100644 index da5679eb8e..0000000000 --- a/.changeset/wet-seas-deliver.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -'@backstage/core-app-api': patch -'@backstage/test-utils': patch ---- - -The `ApiRegistry` from `@backstage/core-app-api` class has been deprecated and will be removed in a future release. To replace it, we have introduced two new helpers that are exported from `@backstage/test-utils`, namely `TestApiProvider` and `TestApiRegistry`. - -These two new helpers are more tailored for writing tests and development setups, as they allow for partial implementations of each of the APIs. - -When migrating existing code it is typically best to prefer usage of `TestApiProvider` when possible, so for example the following code: - -```tsx -render( - - {...} - -) -``` - -Would be migrated to this: - -```tsx -render( - - {...} - -) -``` - -In cases where the `ApiProvider` is used in a more standalone way, for example to reuse a set of APIs across multiple tests, the `TestApiRegistry` can be used instead. Note that the `TestApiRegistry` only has a single static factory method, `.from()`, and it is slightly different from the existing `.from()` method on `ApiRegistry` in that it doesn't require the API pairs to be wrapped in an outer array. - -Usage that looks like this: - -```ts -const apis = ApiRegistry.with( - identityApiRef, - mockIdentityApi as unknown as IdentityApi, -).with(configApiRef, new ConfigReader({})); -``` - -OR like this: - -```ts -const apis = ApiRegistry.from([ - [identityApiRef, mockIdentityApi as unknown as IdentityApi], - [configApiRef, new ConfigReader({})], -]); -``` - -Would be migrated to this: - -```ts -const apis = TestApiRegistry.from( - [identityApiRef, mockIdentityApi], - [configApiRef, new ConfigReader({})], -); -``` - -If your app is still using the `ApiRegistry` to construct the `apis` for `createApp`, we recommend that you move over to use the new method of supplying API factories instead, using `createApiFactory`. diff --git a/.changeset/yellow-apes-brush.md b/.changeset/yellow-apes-brush.md deleted file mode 100644 index 06b33e97d1..0000000000 --- a/.changeset/yellow-apes-brush.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-api-docs': patch ---- - -Adjusted some styles in the OpenAPI definition, for elements which were barely readable in dark mode. diff --git a/.changeset/yellow-pandas-draw.md b/.changeset/yellow-pandas-draw.md deleted file mode 100644 index 6d4f8116b3..0000000000 --- a/.changeset/yellow-pandas-draw.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/core-components': patch ---- - -Pin sidebar by default for easier navigation diff --git a/.changeset/young-hats-shop.md b/.changeset/young-hats-shop.md deleted file mode 100644 index 4db46cf9d9..0000000000 --- a/.changeset/young-hats-shop.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-cost-insights': patch ---- - -Supply featureFlags using featureFlag config option. diff --git a/.changeset/young-sheep-impress.md b/.changeset/young-sheep-impress.md deleted file mode 100644 index b69447d4d4..0000000000 --- a/.changeset/young-sheep-impress.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@backstage/plugin-graphiql': patch ---- - -Letting GraphiQL use headers diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 9be92d294e..ed4b61099f 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,6 +8,8 @@ /docs/features/techdocs @backstage/techdocs-core /docs/features/search @backstage/techdocs-core /docs/assets/search @backstage/techdocs-core +/plugins/allure @backstage/reviewers @deepak-bhardwaj-ps +/plugins/circleci @backstage/reviewers @adamdmharvey /plugins/code-coverage @backstage/reviewers @alde @nissayeva /plugins/code-coverage-backend @backstage/reviewers @alde @nissayeva /plugins/cost-insights @backstage/silver-lining @@ -18,6 +20,20 @@ /plugins/techdocs-backend @backstage/techdocs-core /plugins/ilert @backstage/reviewers @yacut /plugins/home @backstage/techdocs-core +/plugins/azure-devops @backstage/reviewers @marleypowell @awanlin +/plugins/azure-devops-backend @backstage/reviewers @marleypowell @awanlin +/plugins/azure-devops-common @backstage/reviewers @marleypowell @awanlin +/plugins/jenkins @backstage/reviewers @timja +/plugins/jenkins-backend @backstage/reviewers @timja +/plugins/kafka @backstage/reviewers @nirga +/plugins/kafka-backend @backstage/reviewers @nirga +/plugins/scaffolder-backend-module-yeoman @backstage/reviewers @pawelmitka +/plugins/scaffolder-backend-module-rails @backstage/reviewers @angeliski +/plugins/git-release-manager @backstage/reviewers @erikengervall +/tech-insights-backend @backstage/reviewers @xantier @iain-b +/tech-insights-backend-module-jsonfc @backstage/reviewers @xantier @iain-b +/tech-insights-tech-insights-common @backstage/reviewers @xantier @iain-b +/tech-insights-tech-insights-node @backstage/reviewers @xantier @iain-b /packages/embedded-techdocs-app @backstage/techdocs-core /packages/search-common @backstage/techdocs-core /packages/techdocs-cli @backstage/techdocs-core diff --git a/.github/stale.yml b/.github/stale.yml deleted file mode 100644 index 3cd0d53720..0000000000 --- a/.github/stale.yml +++ /dev/null @@ -1,21 +0,0 @@ -# Number of days of inactivity before an issue becomes stale -daysUntilStale: 60 -# Number of days of inactivity before a stale issue is closed -daysUntilClose: 7 -# Issues with these labels will never be considered stale -exemptLabels: - - pinned - - security - - plugin - - help wanted - - good first issue - - rfc -# Label to use when marking an issue as stale -staleLabel: stale -# Comment to post when marking an issue as stale. Set to `false` to disable -markComment: > - This issue has been automatically marked as stale because it has not had - recent activity. It will be closed if no further activity occurs. Thank you - for your contributions. -# Comment to post when closing a stale issue. Set to `false` to disable -closeComment: false diff --git a/.github/styles/vocab.txt b/.github/styles/vocab.txt index d65e31b4c4..4ec62923d8 100644 --- a/.github/styles/vocab.txt +++ b/.github/styles/vocab.txt @@ -189,6 +189,7 @@ oidc Okta onboarding Onboarding +OpenShift orgs pagerduty pageview diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000..96a2a20109 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,30 @@ +name: 'Stale workflow' +on: + workflow_dispatch: + schedule: + - cron: '*/10 * * * *' # run every 10 minutes as it also removes labels. + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@main + id: stale + with: + stale-issue-message: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. + days-before-issue-stale: 60 + days-before-issue-close: 7 + exempt-issue-labels: 'pinned,security,plugin,help wanted,good first issue,rfc' + stale-issue-label: stale + stale-pr-message: > + This PR has been automatically marked as stale because it has not had + recent activity from the author. It will be closed if no further activity occurs. + If you are the author and the PR has been closed, feel free to re-open the PR and continue the contribution! + days-before-pr-stale: 7 + days-before-pr-close: 3 + exempt-pr-labels: reviewer-approved,awaiting-review + stale-pr-label: stale + operations-per-run: 100 diff --git a/ADOPTERS.md b/ADOPTERS.md index c4c84d11be..3a04099812 100644 --- a/ADOPTERS.md +++ b/ADOPTERS.md @@ -72,3 +72,6 @@ | [Globo](https://globo.com) | [Carlos Gusmão](https://github.com/caeugusmao), [Guilherme Vierno](https://github.com/vierno), [Denis Aoki](https://github.com/dnsaoki2), [Maycon Dionisio](https://github.com/MayconDionisio), | Reduce the friction of accessing the information engineers need about Globo's digital services through a coherent and centralized experience. | | [QBE](https://www.qbe.com/) | [Daniel Steel](https://github.com/danielsteelqbe), [Pete Jespers](https://github.com/petejespersqbe) | Developer portal allowing our global teams to explore and create applications, documentation and cloud infrastructure easily and quickly 🚀 | | [LogMeIn](https://www.logmein.com) | [Lorenzo Orsatti](https://github.com/lorsatti) | Improve onboarding experience of new developers. Discover faster and painlessly developer documentation, API definitions and team information. Provide useful dev metrics in a central place. Provide easy-to-use templates for new services. | +| [Telstra](https://www.telstra.com.au) | [@kiranpatel11](https://github.com/kiranpatel11), [JasonC](https://github.com/JasonC17) | Primary usage: software catalog and templates
Emerging usage : TechDocs, Explore Ecosystem, TechRadar, etc | +| [Mosaico](https://www.mosaico.com.br/) | [Wédney Yuri](https://github.com/wedneyyuri),[@tino.milton](https://github.com/miltonjacomini) | A centralized service catalog of our documentation for our service engineers. | +| [Mox Bank](https://www.mox.com/) | [Nick Laqua](https://github.com/nick-laqua-dragon), [Gauthier Roebroeck](https://github.com/gauthier-roebroeck-mox) | "Single pane of glass" developer portal for providing a best-in-class developer experience to our product teams and making Mox the best tech environment in Hongkong 🥰🚀 | diff --git a/app-config.yaml b/app-config.yaml index 50ddb7ce89..4adaea0da4 100644 --- a/app-config.yaml +++ b/app-config.yaml @@ -23,6 +23,11 @@ app: title: '#backstage' backend: + # Used for enabling authentication, secret is shared by all backend plugins + # See backend-to-backend-auth.md in the docs for information on the format + # auth: + # keys: + # - secret: ${BACKEND_SECRET} baseUrl: http://localhost:7007 listen: port: 7007 @@ -272,24 +277,6 @@ scaffolder: # email: scaffolder@backstage.io # Use to customize the default commit message when new components are created # defaultCommitMessage: 'Initial commit' - github: - token: ${GITHUB_TOKEN} - visibility: public # or 'internal' or 'private' - gitlab: - api: - baseUrl: https://gitlab.com - token: ${GITLAB_TOKEN} - visibility: public # or 'internal' or 'private' - azure: - baseUrl: https://dev.azure.com/{your-organization} - api: - token: ${AZURE_TOKEN} - bitbucket: - api: - host: https://bitbucket.org - username: ${BITBUCKET_USERNAME} - token: ${BITBUCKET_TOKEN} - visibility: public # or or 'private' auth: ### Add auth.keyStore.provider to more granularly control how to store JWK data when running diff --git a/cypress/yarn.lock b/cypress/yarn.lock index baf0d92715..96bc765d0d 100644 --- a/cypress/yarn.lock +++ b/cypress/yarn.lock @@ -13,9 +13,9 @@ figures "^1.7.0" "@cypress/request@^2.88.5": - version "2.88.5" - resolved "https://registry.npmjs.org/@cypress/request/-/request-2.88.5.tgz#8d7ecd17b53a849cfd5ab06d5abe7d84976375d7" - integrity sha512-TzEC1XMi1hJkywWpRfD2clreTa/Z+lOrXDCxxBTBPEcY5azdPi56A6Xw+O4tWJnaJH3iIE7G5aDXZC6JgRZLcA== + version "2.88.10" + resolved "https://registry.npmjs.org/@cypress/request/-/request-2.88.10.tgz#b66d76b07f860d3a4b8d7a0604d020c662752cce" + integrity sha512-Zp7F+R93N0yZyG34GutyTNr+okam7s/Fzc1+i3kcqOP8vk6OuajuE9qZJ6Rs+10/1JFtXFYMdyarnU1rZuJesg== dependencies: aws-sign2 "~0.7.0" aws4 "^1.8.0" @@ -24,19 +24,17 @@ extend "~3.0.2" forever-agent "~0.6.1" form-data "~2.3.2" - har-validator "~5.1.3" - http-signature "~1.2.0" + http-signature "~1.3.6" is-typedarray "~1.0.0" isstream "~0.1.2" json-stringify-safe "~5.0.1" mime-types "~2.1.19" - oauth-sign "~0.9.0" performance-now "^2.1.0" qs "~6.5.2" safe-buffer "^5.1.2" tough-cookie "~2.5.0" tunnel-agent "^0.6.0" - uuid "^3.3.2" + uuid "^8.3.2" "@cypress/xvfb@^1.2.4": version "1.2.4" @@ -68,16 +66,6 @@ resolved "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.2.tgz#a811b8c18e2babab7d542b3365887ae2e4d9de47" integrity sha512-7EJYyKTL7tFR8+gDbB6Wwz/arpGa0Mywk1TJbNzKzHtzbwVmY4HR9WqS5VV7dsBUKQmPNr192jHr/VpBluj/hg== -ajv@^6.12.3: - version "6.12.6" - resolved "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" - integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== - dependencies: - fast-deep-equal "^3.1.1" - fast-json-stable-stringify "^2.0.0" - json-schema-traverse "^0.4.1" - uri-js "^4.2.2" - ansi-escapes@^3.0.0: version "3.2.0" resolved "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz#8780b98ff9dbf5638152d1f1fe5c1d7b4442976b" @@ -539,16 +527,6 @@ extsprintf@^1.2.0: resolved "https://registry.npmjs.org/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f" integrity sha1-4mifjzVvrWLMplo6kcXfX5VRaS8= -fast-deep-equal@^3.1.1: - version "3.1.3" - resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" - integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== - -fast-json-stable-stringify@^2.0.0: - version "2.1.0" - resolved "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" - integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== - fd-slicer@~1.1.0: version "1.1.0" resolved "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e" @@ -645,19 +623,6 @@ graceful-fs@^4.1.6, graceful-fs@^4.2.0: resolved "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.5.tgz#bc18864a6c9fc7b303f2e2abdb9155ad178fbe29" integrity sha512-kBBSQbz2K0Nyn+31j/w36fUfxkBW9/gfwRWdUY1ULReH3iokVJgddZAFcD1D0xlgTmFxJCbUkUclAlc6/IDJkw== -har-schema@^2.0.0: - version "2.0.0" - resolved "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" - integrity sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI= - -har-validator@~5.1.3: - version "5.1.5" - resolved "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz#1f0803b9f8cb20c0fa13822df1ecddb36bde1efd" - integrity sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w== - dependencies: - ajv "^6.12.3" - har-schema "^2.0.0" - has-ansi@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" @@ -675,14 +640,14 @@ has-flag@^4.0.0: resolved "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== -http-signature@~1.2.0: - version "1.2.0" - resolved "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" - integrity sha1-muzZJRFHcvPZW2WmCruPfBj7rOE= +http-signature@~1.3.6: + version "1.3.6" + resolved "https://registry.npmjs.org/http-signature/-/http-signature-1.3.6.tgz#cb6fbfdf86d1c974f343be94e87f7fc128662cf9" + integrity sha512-3adrsD6zqo4GsTqtO7FyrejHNv+NgiIfAfv68+jVlFmSr9OGy7zrxONceFRLKvnnZA5jbxQBX1u9PpB6Wi32Gw== dependencies: assert-plus "^1.0.0" - jsprim "^1.2.2" - sshpk "^1.7.0" + jsprim "^2.0.2" + sshpk "^1.14.1" human-signals@^1.1.1: version "1.1.1" @@ -796,15 +761,10 @@ jsbn@~0.1.0: resolved "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= -json-schema-traverse@^0.4.1: - version "0.4.1" - resolved "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" - integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== - -json-schema@0.2.3: - version "0.2.3" - resolved "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" - integrity sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM= +json-schema@0.4.0: + version "0.4.0" + resolved "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz#f7de4cf6efab838ebaeb3236474cbba5a1930ab5" + integrity sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA== json-stringify-safe@~5.0.1: version "5.0.1" @@ -820,14 +780,14 @@ jsonfile@^6.0.1: optionalDependencies: graceful-fs "^4.1.6" -jsprim@^1.2.2: - version "1.4.1" - resolved "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" - integrity sha1-MT5mvB5cwG5Di8G3SZwuXFastqI= +jsprim@^2.0.2: + version "2.0.2" + resolved "https://registry.npmjs.org/jsprim/-/jsprim-2.0.2.tgz#77ca23dbcd4135cd364800d22ff82c2185803d4d" + integrity sha512-gqXddjPqQ6G40VdnI6T6yObEC+pDNvyP95wdQhkWkg7crHH3km5qP1FsOXEkzEQwnz6gz5qGTn1c2Y52wP3OyQ== dependencies: assert-plus "1.0.0" extsprintf "1.3.0" - json-schema "0.2.3" + json-schema "0.4.0" verror "1.10.0" lazy-ass@^1.6.0: @@ -985,11 +945,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= -oauth-sign@~0.9.0: - version "0.9.0" - resolved "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455" - integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ== - object-assign@^4.1.0: version "4.1.1" resolved "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" @@ -1084,7 +1039,7 @@ punycode@1.3.2: resolved "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" integrity sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0= -punycode@^2.1.0, punycode@^2.1.1: +punycode@^2.1.1: version "2.1.1" resolved "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== @@ -1191,7 +1146,7 @@ slice-ansi@0.0.4: resolved "https://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz#edbf8903f66f7ce2f8eafd6ceed65e264c831b35" integrity sha1-7b+JA/ZvfOL46v1s7tZeJkyDGzU= -sshpk@^1.7.0: +sshpk@^1.14.1: version "1.16.1" resolved "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz#fb661c0bef29b39db40769ee39fa70093d6f6877" integrity sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg== @@ -1353,13 +1308,6 @@ untildify@^4.0.0: resolved "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz#2bc947b953652487e4600949fb091e3ae8cd919b" integrity sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw== -uri-js@^4.2.2: - version "4.4.1" - resolved "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" - integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== - dependencies: - punycode "^2.1.0" - url@^0.11.0: version "0.11.0" resolved "https://registry.npmjs.org/url/-/url-0.11.0.tgz#3838e97cfc60521eb73c525a8e55bfdd9e2e28f1" @@ -1373,10 +1321,10 @@ util-deprecate@~1.0.1: resolved "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= -uuid@^3.3.2: - version "3.4.0" - resolved "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee" - integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A== +uuid@^8.3.2: + version "8.3.2" + resolved "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" + integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== verror@1.10.0: version "1.10.0" diff --git a/docs/api/utility-apis.md b/docs/api/utility-apis.md index 133653df44..14920513af 100644 --- a/docs/api/utility-apis.md +++ b/docs/api/utility-apis.md @@ -291,7 +291,7 @@ The figure below shows the relationship between fooApiRef.
-Figure showing the relationship between utility APIs, the apps that provide them, and the plugins that consume them +Figure showing the relationship between utility APIs, the apps that provide them, and the plugins that consume them
The current method for connecting Utility API providers and consumers is via the diff --git a/docs/assets/software-templates/grouped-templates.png b/docs/assets/software-templates/grouped-templates.png new file mode 100644 index 0000000000..9a3689ad1e Binary files /dev/null and b/docs/assets/software-templates/grouped-templates.png differ diff --git a/docs/assets/techdocs/architecture-recommended.drawio.svg b/docs/assets/techdocs/architecture-recommended.drawio.svg index e3af4b6b5f..1768b5dc86 100644 --- a/docs/assets/techdocs/architecture-recommended.drawio.svg +++ b/docs/assets/techdocs/architecture-recommended.drawio.svg @@ -1,4 +1,4 @@ - + @@ -7,7 +7,7 @@ - + @@ -67,8 +67,8 @@ - - + + @@ -105,7 +105,7 @@ - + @@ -124,7 +124,7 @@ - + @@ -232,34 +232,17 @@
- TechDocs plugin + TechDocs Plugin
- TechDocs plugin + TechDocs Plugin - - - - -
-
-
- TechDocs Backend plugin -
-
-
-
- - TechDocs Backend plu... - -
-
- + @@ -268,21 +251,23 @@
- Request TechDocs site + + Request TechDocs Site +
- Request TechDocs site + Request TechDocs Site
- + -
+
Fetch files to render @@ -290,7 +275,7 @@
- + Fetch files to render @@ -302,15 +287,15 @@ - + - + -
+
Source code hosting @@ -323,28 +308,9 @@ - - - - - -
-
-
- Caching -
- (Optional) -
-
-
-
- - Caching... - -
-
- - + + + @@ -379,10 +345,132 @@ + + + + +
+
+
+ Cache Store +
+ (Optional) +
+
+
+
+ + Cache Store... + +
+
+ + + + +
+
+
+ Read/Write +
+ Objects +
+
+
+
+ + Read/Write... + +
+
+ + + + + + + +
+
+
+ + + Memcache + + +
+
+
+
+ + Memcache + +
+
+ + + + + +
+
+
+ + TechDocs Service + +
+
+
+
+ + TechDocs Service + +
+
+ + + + +
+
+
+ + Cache Middleware +
+ (Optional) +
+
+
+
+
+ + Cache Middleware... + +
+
+ + + + + + +
+
+
+ TechDocs Backend Plugin +
+
+
+
+ + TechDocs Backend Plugin + +
+
- + Viewer does not support full SVG 1.1 diff --git a/docs/auth/index.md b/docs/auth/index.md index 0c03e33900..4a8d225048 100644 --- a/docs/auth/index.md +++ b/docs/auth/index.md @@ -16,8 +16,10 @@ Backstage identity information in your app or plugins. Backstage comes with many common authentication providers in the core library: +- [Atlassian](atlassian/provider.md) - [Auth0](auth0/provider.md) - [Azure](microsoft/provider.md) +- [Bitbucket](bitbucket/provider.md) - [GitHub](github/provider.md) - [GitLab](gitlab/provider.md) - [Google](google/provider.md) diff --git a/docs/deployment/docker.md b/docs/deployment/docker.md index 7cbd3cea89..6f58abe769 100644 --- a/docs/deployment/docker.md +++ b/docs/deployment/docker.md @@ -7,9 +7,9 @@ description: How to build a Backstage Docker image for deployment This section describes how to build a Backstage App into a deployable Docker image. It is split into three sections, first covering the host build approach, -which is recommended due its speed and more efficient and often simpler caching. -The second section covers a full multi-stage Docker build, and the last section -covers how to deploy the frontend and backend as separate images. +which is recommended due to its speed and more efficient and often simpler +caching. The second section covers a full multi-stage Docker build, and the last +section covers how to deploy the frontend and backend as separate images. Something that goes for all of these docker deployment strategies is that they are stateless, so for a production deployment you will want to set up and diff --git a/docs/features/kubernetes/configuration.md b/docs/features/kubernetes/configuration.md index 6b3991144b..07a12f54a0 100644 --- a/docs/features/kubernetes/configuration.md +++ b/docs/features/kubernetes/configuration.md @@ -26,6 +26,7 @@ kubernetes: name: minikube authProvider: 'serviceAccount' skipTLSVerify: false + skipMetricsLookup: true serviceAccountToken: ${K8S_MINIKUBE_TOKEN} dashboardUrl: http://127.0.0.1:64713 # url copied from running the command: minikube service kubernetes-dashboard -n kubernetes-dashboard dashboardApp: standard @@ -37,6 +38,7 @@ kubernetes: projectId: 'gke-clusters' region: 'europe-west1' skipTLSVerify: true + skipMetricsLookup: true ``` ### `serviceLocatorMethod` @@ -86,8 +88,13 @@ cluster. Valid values are: ##### `clusters.\*.skipTLSVerify` -This determines whether or not the Kubernetes client verifies the TLS -certificate presented by the API server. Defaults to `false`. +This determines whether the Kubernetes client verifies the TLS certificate +presented by the API server. Defaults to `false`. + +##### `clusters.\*.skipMetricsLookup` + +This determines whether the Kubernetes client looks up resource metrics +CPU/Memory for pods returned by the API server. Defaults to `false`. ##### `clusters.\*.serviceAccountToken` (optional) @@ -188,8 +195,13 @@ regions. ##### `skipTLSVerify` -This determines whether or not the Kubernetes client verifies the TLS -certificate presented by the API server. Defaults to `false`. +This determines whether the Kubernetes client verifies the TLS certificate +presented by the API server. Defaults to `false`. + +##### `skipMetricsLookup` + +This determines whether the Kubernetes client looks up resource metrics +CPU/Memory for pods returned by the API server. Defaults to `false`. ### `customResources` (optional) @@ -219,6 +231,26 @@ The custom resource's apiVersion. The plural representing the custom resource. +### `apiVersionOverrides` (optional) + +Overrides for the API versions used to make requests for the corresponding +objects. If using a legacy Kubernetes version, you may use this config to +override the default API versions to ones that are supported by your cluster. + +Example: + +```yaml +--- +kubernetes: + apiVersionOverrides: + cronjobs: 'v1beta1' +``` + +For more information on which API versions are supported by your cluster, please +view the Kubernetes API docs for your Kubernetes version (e.g. +[API Groups for v1.22](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.22/#-strong-api-groups-strong-) +) + ### Role Based Access Control The current RBAC permissions required are read-only cluster wide, for the diff --git a/docs/features/search/getting-started.md b/docs/features/search/getting-started.md index 27219e529a..285e399cb4 100644 --- a/docs/features/search/getting-started.md +++ b/docs/features/search/getting-started.md @@ -114,13 +114,15 @@ const routes = ( In `Root.tsx`, add the `SidebarSearchModal` component: ```bash -import { SidebarSearchModal } from '@backstage/plugin-search'; +import { SidebarSearchModal, SearchContextProvider } from '@backstage/plugin-search'; export const Root = ({ children }: PropsWithChildren<{}>) => ( - + + + ... ``` @@ -154,13 +156,17 @@ import { DefaultCatalogCollator } from '@backstage/plugin-catalog-backend'; export default async function createPlugin({ logger, discovery, + tokenManager, }: PluginEnvironment) { const searchEngine = new LunrSearchEngine({ logger }); const indexBuilder = new IndexBuilder({ logger, searchEngine }); indexBuilder.addCollator({ defaultRefreshIntervalSeconds: 600, - collator: new DefaultCatalogCollator({ discovery }), + collator: new DefaultCatalogCollator({ + discovery, + tokenManager, + }), }); const { scheduler } = await indexBuilder.build(); @@ -285,7 +291,10 @@ const indexBuilder = new IndexBuilder({ logger, searchEngine }); indexBuilder.addCollator({ defaultRefreshIntervalSeconds: 600, - collator: new DefaultCatalogCollator({ discovery }), + collator: new DefaultCatalogCollator({ + discovery, + tokenManager, + }), }); indexBuilder.addCollator({ @@ -303,6 +312,9 @@ its `defaultRefreshIntervalSeconds` value, like this: ```typescript {3} indexBuilder.addCollator({ defaultRefreshIntervalSeconds: 600, - collator: new DefaultCatalogCollator({ discovery }), + collator: new DefaultCatalogCollator({ + discovery, + tokenManager, + }), }); ``` diff --git a/docs/features/search/how-to-guides.md b/docs/features/search/how-to-guides.md index 621d46b51e..4ba44b8ef4 100644 --- a/docs/features/search/how-to-guides.md +++ b/docs/features/search/how-to-guides.md @@ -2,7 +2,7 @@ id: how-to-guides title: Search "HOW TO" guides sidebar_label: "HOW TO" guides -description: Search "HOW TO" guides +description: Search "HOW TO" guides --- ## How to implement your own Search API @@ -74,6 +74,7 @@ indexBuilder.addCollator({ collator: DefaultTechDocsCollator.fromConfig(config, { discovery, logger, + tokenManager, }), }); ``` diff --git a/docs/features/search/search-engines.md b/docs/features/search/search-engines.md index a0302ce279..1331c73b72 100644 --- a/docs/features/search/search-engines.md +++ b/docs/features/search/search-engines.md @@ -4,9 +4,9 @@ title: Search Engines description: Choosing and configuring your search engine for Backstage --- -Backstage supports 2 search engines by default, an in-memory engine called Lunr -and ElasticSearch. You can configure your own search engines by implementing the -provided interface as mentioned in the +Backstage supports 3 search engines by default, an in-memory engine called Lunr, +ElasticSearch and Postgres. You can configure your own search engines by +implementing the provided interface as mentioned in the [search backend documentation.](./getting-started.md#Backend) Provided search engine implementations have their own way of constructing diff --git a/docs/features/software-templates/configuration.md b/docs/features/software-templates/configuration.md index 737f77f67b..d22b82bc16 100644 --- a/docs/features/software-templates/configuration.md +++ b/docs/features/software-templates/configuration.md @@ -18,17 +18,31 @@ The next step is to add [add templates](http://backstage.io/docs/features/software-templates/adding-templates) to your Backstage app. -### GitHub +### Publishing defaults -For GitHub, you can configure who can see the new repositories that are created -by specifying `visibility` option. Valid options are `public`, `private` and -`internal`. The `internal` option is for GitHub Enterprise clients, which means -public within the enterprise. +Software templates can define _publish_ actions, such as `publish:github`, to +create new repositories or submit pull / merge requests to existing +repositories. You can configure the author and commit message through the +`scaffolder` configuration in `app-config.yaml`: ```yaml scaffolder: - github: - visibility: public # or 'internal' or 'private' + defaultAuthor: + name: M.C. Hammer # Defaults to `Scaffolder` + email: hammer@donthurtem.com # Defaults to `scaffolder@backstage.io` + defaultCommitMessage: "U can't touch this" # Defaults to 'Initial commit' +``` + +To configure who can see the new repositories created from software templates, +add the `repoVisibility` key within a software template: + +```yaml +- id: publish + name: Publish + action: publish:github + input: + repoUrl: '{{ parameters.repoUrl }}' + repoVisibility: public # or 'internal' or 'private' ``` ### Disabling Docker in Docker situation (Optional) @@ -53,3 +67,30 @@ You can do so by including the following lines in the last step of your RUN apt-get update && apt-get install -y python3 python3-pip RUN pip3 install cookiecutter ``` + +### Customizing the ScaffolderPage with Grouping and Filtering + +Once you have more than a few software templates you may want to customize your +`ScaffolderPage` by grouping and surfacing certain templates together. You can +accomplish this by creating `groups` and passing them to your `ScaffolderPage` +like below + +``` + + entity?.metadata?.tags?.includes('recommended') ?? false, + }, + ]} +/> +``` + +This code will group all templates with the 'recommended' tag together at the +top of the page above any other templates not filtered by this group or others. + +You can also further customize groups by passing in a `titleComponent` instead +of a `title` which will be a component to use as the header instead of just the +default `ContentHeader` with the `title` set as it's value. +![Grouped Templates](../../assets/software-templates/grouped-templates.png) diff --git a/docs/features/software-templates/index.md b/docs/features/software-templates/index.md index 1434d62a29..a854543acb 100644 --- a/docs/features/software-templates/index.md +++ b/docs/features/software-templates/index.md @@ -12,7 +12,7 @@ code, template in some variables, and then publish the template to some locations like GitHub or GitLab. ### Getting Started diff --git a/docs/features/techdocs/architecture.md b/docs/features/techdocs/architecture.md index 8d25b4047f..23af83d09b 100644 --- a/docs/features/techdocs/architecture.md +++ b/docs/features/techdocs/architecture.md @@ -40,7 +40,7 @@ storage system (e.g. AWS S3, GCS or Azure Blob Storage). Read more in ## Recommended deployment -This is how we recommend deploying TechDocs in production environment. +This is how we recommend deploying TechDocs in a production environment. TechDocs Architecture diagram @@ -58,12 +58,12 @@ Similar to how it is done in the Basic setup, the TechDocs Reader requests your configured storage solution for the necessary files and returns them to TechDocs Reader. -Note about caching: We have noticed internally that some storage providers can -be quite slow, which is why we are recommending a cache that sits between the -TechDocs Reader and the Storage. - -_Feel free to suggest better ideas to us in #docs-like-code channel in Discord -or via a GitHub issue._ +Depending on your chosen cloud storage provider and its real-world proximity to +your backend server, there may be a comparably high amount of latency when +loading TechDocs sites using this deployment approach. If you encounter this, +you can optionally configure the `techdocs-backend` to cache responses in a +cache store +[supported by Backstage](../../overview/architecture-overview.md#cache). ### Security consideration diff --git a/docs/features/techdocs/configuration.md b/docs/features/techdocs/configuration.md index 4148749a62..6317ae365b 100644 --- a/docs/features/techdocs/configuration.md +++ b/docs/features/techdocs/configuration.md @@ -135,6 +135,22 @@ techdocs: # the old, case-sensitive entity triplet behavior. legacyUseCaseSensitiveTripletPaths: false + # techdocs.cache is optional, and is only recommended when you've configured + # an external techdocs.publisher.type above. Also requires backend.cache to + # be configured with a valid cache store. + cache: + # Represents the number of milliseconds a statically built asset should + # stay cached. Cache invalidation is handled automatically by the frontend, + # which compares the build times in cached metadata vs. canonical storage, + # allowing long TTLs (e.g. 1 month/year) + ttl: 3600000 + + # (Optional) The time (in milliseconds) that the TechDocs backend will wait + # for a cache service to respond before continuing on as though the cached + # object was not found (e.g. when the cache sercice is unavailable). The + # default value is 1000 + readTimeout: 500 + # (Optional and Legacy) TechDocs makes API calls to techdocs-backend using this URL. e.g. get docs of an entity, get metadata, etc. # You don't have to specify this anymore. diff --git a/docs/getting-started/create-an-app.md b/docs/getting-started/create-an-app.md index e5d15d5845..1d65f25d1b 100644 --- a/docs/getting-started/create-an-app.md +++ b/docs/getting-started/create-an-app.md @@ -36,7 +36,7 @@ This will create a new Backstage App inside the current folder. The name of the app-folder is the name that was provided when prompted.

- create app + create app

Inside that directory, it will generate all the files and folder structure diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index 5a970ef143..42b334c62b 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -23,7 +23,7 @@ guide to do a repository-based installation. - Access to a Linux-based operating system, such as Linux, MacOS or [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/) -- An account with elevated rights +- An account with elevated rights to install the dependencies - `curl` or `wget` installed - Node.js Active LTS Release installed (currently v14) using one of these methods: @@ -36,15 +36,16 @@ guide to do a repository-based installation. - `yarn` [Installation](https://classic.yarnpkg.com/en/docs/install) - `docker` [installation](https://docs.docker.com/engine/install/) - `git` [installation](https://github.com/git-guides/install-git) -- If the system is not directly accessible over your network, the following - ports need to be opened: 3000, 7007 +- If the system is not directly accessible over your network the following ports + need to be opened: 3000, 7007. This is quite uncommon, unless when you're + installing in a container, VM or remote system. ### Create your Backstage App To install the Backstage Standalone app, we make use of `npx`, a tool to run -Node executables straight from the registry. Running the command below will -install Backstage. The wizard will create a subdirectory inside your current -working directory. +Node executables straight from the registry. This tool is part of your Node.js +installation. Running the command below will install Backstage. The wizard will +create a subdirectory inside your current working directory. ```bash npx @backstage/create-app @@ -57,7 +58,7 @@ The wizard will ask you SQLite option.

- Screenshot of the wizard asking for a name for the app, and a selection menu for the database. + Screenshot of the wizard asking for a name for the app, and a selection menu for the database.

### Run the Backstage app @@ -72,18 +73,27 @@ yarn dev ```

- Screenshot of the command output, with the message web pack compiled successfully. + Screenshot of the command output, with the message web pack compiled successfully.

It might take a little while, but as soon as the message `[0] webpack compiled successfully` appears, you can open a browser and directly navigate to your freshly installed Backstage portal at `http://localhost:3000`. -You can start exploring the demo immediately. +You can start exploring the demo immediately. Please note that the in-memory +database will be cleared when you restart the app, so you'll most likely want to +carry on with the database steps.

- Screenshot of the Backstage portal. + Screenshot of the Backstage portal.

+The most common next steps are to move to a persistent database, configure +authentication, and add a plugin: + +- [Switching from SQLite to PostgresQL](https://backstage.io/docs/tutorials/switching-sqlite-postgres) +- [Setting up Authentication](https://backstage.io/docs/auth/) +- [Adding a plugin](https://backstage.io/docs/getting-started/configure-app-with-plugins) + Congratulations! That should be it. Let us know how it went: [on discord](https://discord.gg/EBHEGzX), file issues for any [feature](https://github.com/backstage/backstage/issues/new?labels=help+wanted&template=feature_template.md) @@ -93,10 +103,3 @@ or [bugs](https://github.com/backstage/backstage/issues/new?labels=bug&template=bug_template.md) you have, and feel free to [contribute](https://github.com/backstage/backstage/blob/master/CONTRIBUTING.md)! - -The most common next steps are to configure Backstage, add a plugin and moving -to a more persistent database: - -- [Setting up Authentication](https://backstage.io/docs/auth/) -- [Switching from SQLite to PostgresQL](https://backstage.io/docs/tutorials/switching-sqlite-postgres) -- [Adding a plugin](https://backstage.io/docs/getting-started/configure-app-with-plugins) diff --git a/docs/getting-started/project-structure.md b/docs/getting-started/project-structure.md index 687743f99d..a0390571b8 100644 --- a/docs/getting-started/project-structure.md +++ b/docs/getting-started/project-structure.md @@ -166,13 +166,9 @@ are separated out into their own folder, see further down. plugin and [techdocs-cli](https://github.com/backstage/techdocs-cli). - [`test-utils/`](https://github.com/backstage/backstage/tree/master/packages/test-utils) - - This package contains more general purpose testing facilities for testing a + This package contains general purpose testing facilities for testing a Backstage App or its plugins. -- [`test-utils-core/`](https://github.com/backstage/backstage/tree/master/packages/test-utils-core) - - This package contains specific testing facilities used when testing Backstage - core internals. - - [`theme/`](https://github.com/backstage/backstage/tree/master/packages/theme) - Holds the Backstage Theme. diff --git a/docs/local-dev/cli-commands.md b/docs/local-dev/cli-commands.md index 18fdef892a..318b37f34e 100644 --- a/docs/local-dev/cli-commands.md +++ b/docs/local-dev/cli-commands.md @@ -165,6 +165,7 @@ common example being the `migrations` directory. Usage: backstage-cli backend:build [options] Options: + --minify Minify the generated code -h, --help display help for command ``` @@ -371,6 +372,7 @@ the monorepo. Usage: backstage-cli plugin:build [options] Options: + --minify Minify the generated code -h, --help display help for command ``` diff --git a/docs/overview/stability-index.md b/docs/overview/stability-index.md index a79bcd6e11..a79989412d 100644 --- a/docs/overview/stability-index.md +++ b/docs/overview/stability-index.md @@ -27,7 +27,7 @@ point building on top of the previous one: and the new APIs can be used in parallel. This deprecation must have been released for at least two weeks before the deprecated API is removed in a minor version bump. -- **3** - The time limit for the deprecation is 3 months instead of two days. +- **3** - The time limit for the deprecation is 3 months instead of two weeks. TL;DR: @@ -175,15 +175,6 @@ Utilities for writing tests for Backstage plugins and apps. Stability: `2` -### `test-utils-core` [GitHub](https://github.com/backstage/backstage/tree/master/packages/test-utils-core/) - -Internal testing utilities that are separated out for usage in -@backstage/core-app-api and @backstage/core-plugin-api. All exports are -re-exported by @backstage/test-utils. This package should not be depended on -directly. - -Stability: See @backstage/test-utils - ### `theme` [GitHub](https://github.com/backstage/backstage/tree/master/packages/theme/) The core Backstage MUI theme along with customization utilities. diff --git a/docs/tutorials/backend-to-backend-auth.md b/docs/tutorials/backend-to-backend-auth.md new file mode 100644 index 0000000000..3cb72a4827 --- /dev/null +++ b/docs/tutorials/backend-to-backend-auth.md @@ -0,0 +1,68 @@ +--- +id: backend-to-backend-auth +title: Backend-to-Backend Authentication +description: + Guide for authenticating API requests between Backstage plugin backends +--- + +This tutorial describes the steps needed to handle _backend-to-backend +authentication_, which allows plugin backends to determine whether a given +request originates from a legitimate Backstage backend by verifying a token +signed with a shared secret. This system has limited use for now, but will be +needed to support the upcoming framework for permissions and authorization (see +[the PRFC on the topic](https://github.com/backstage/backstage/pull/7761) for +more details). + +Backends have no concept of a Backstage identity, so instead they use a token +generated using a shared key stored in config. You can generate a unique key for +your app in a terminal, and set the `BACKEND_SECRET` environment variable to the +resulting value. + +```bash +node -p 'require("crypto").randomBytes(24).toString("base64")' +``` + +Requests originating from a backend plugin can be authenticated by decorating +them with a backend token. Backend tokens can be generated using a +`TokenManager`, which can be passed to plugin backends via the +`PluginEnvironment`. The `TokenManager` provided in new Backstage instances +generated by `create-app` is a stub, which returns empty tokens and accepts any +input string as valid. To enable backend-to-backend authentication, you'll need +to instantiate a new one using the secret from your config instead: + +```diff +// packages/backend/src/index.ts + +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 cacheManager = CacheManager.fromConfig(config); + const databaseManager = DatabaseManager.fromConfig(config); +- const tokenManager = ServerTokenManager.noop(); ++ const tokenManager = ServerTokenManager.fromConfig(config); +``` + +With this `tokenManager`, you can then generate a server token for requests: + +```typescript +const { token } = await this.tokenManager.getToken(); + +const response = await fetch(pluginBackendApiUrl, { + method: 'GET', + headers: { + ...headers, + Authorization: `Bearer ${token}`, + }, +}); +``` + +You can use the same `tokenManager` to authenticate tokens supplied on incoming +requests: + +```typescript +await tokenManager.authenticate(token); // throws if token is invalid +``` diff --git a/microsite/blog/2020-08-05-announcing-backstage-software-templates.md b/microsite/blog/2020-08-05-announcing-backstage-software-templates.md index afda20e499..0bf8d7e581 100644 --- a/microsite/blog/2020-08-05-announcing-backstage-software-templates.md +++ b/microsite/blog/2020-08-05-announcing-backstage-software-templates.md @@ -7,7 +7,7 @@ authorURL: https://twitter.com/stalund **TL;DR** Today we are announcing a new Backstage feature: Software Templates. Simplify setup, standardize tooling, and deploy with the click of a button. Using automated templates, your engineers can spin up a new microservice, website, or other software component with your organization’s best practices built-in, right from the start. diff --git a/microsite/package.json b/microsite/package.json index a2a2fd98de..0a90cb2ec5 100644 --- a/microsite/package.json +++ b/microsite/package.json @@ -19,7 +19,7 @@ "@spotify/prettier-config": "^12.0.0", "docusaurus": "^2.0.0-alpha.70", "js-yaml": "^4.1.0", - "prettier": "^2.4.1", + "prettier": "^2.5.1", "yarn-lock-check": "^1.0.5" }, "prettier": "@spotify/prettier-config" diff --git a/microsite/yarn.lock b/microsite/yarn.lock index c03ecf989a..b4d97d549d 100644 --- a/microsite/yarn.lock +++ b/microsite/yarn.lock @@ -5190,10 +5190,10 @@ prepend-http@^2.0.0: resolved "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897" integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc= -prettier@^2.4.1: - version "2.4.1" - resolved "https://registry.npmjs.org/prettier/-/prettier-2.4.1.tgz#671e11c89c14a4cfc876ce564106c4a6726c9f5c" - integrity sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA== +prettier@^2.5.1: + version "2.5.1" + resolved "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz#fff75fa9d519c54cf0fce328c1017d94546bc56a" + integrity sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg== prismjs@^1.22.0: version "1.25.0" diff --git a/package.json b/package.json index 16ba8461ac..2d63f92d3a 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,8 @@ "prettier:check": "prettier --check .", "lerna": "lerna", "storybook": "yarn workspace storybook start", + "snyk:test": "npx snyk test --yarn-workspaces --strict-out-of-sync=false", + "snyk:test:package": "yarn snyk:test --include", "build-storybook": "yarn workspace storybook build-storybook", "techdocs-cli": "node scripts/techdocs-cli.js", "techdocs-cli:dev": "cross-env TECHDOCS_CLI_DEV_MODE=true node scripts/techdocs-cli.js", @@ -61,7 +63,8 @@ "devDependencies": { "@changesets/cli": "^2.14.0", "@octokit/rest": "^18.12.0", - "@spotify/prettier-config": "^11.0.0", + "@spotify/prettier-config": "^12.0.0", + "@types/node": "^14.14.32", "@types/webpack": "^5.28.0", "command-exists": "^1.2.9", "cross-env": "^7.0.0", diff --git a/packages/app-defaults/package.json b/packages/app-defaults/package.json index 7388a44ce0..695d457455 100644 --- a/packages/app-defaults/package.json +++ b/packages/app-defaults/package.json @@ -29,17 +29,17 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-app-api": "^0.1.21", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-app-api": "^0.1.24", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "react": "^16.12.0", "react-router-dom": "6.0.0-beta.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/test-utils": "^0.1.22", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", diff --git a/packages/app/CHANGELOG.md b/packages/app/CHANGELOG.md index f6f6049d68..2d006791e9 100644 --- a/packages/app/CHANGELOG.md +++ b/packages/app/CHANGELOG.md @@ -1,5 +1,25 @@ # example-app +## 0.2.55 + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-azure-devops@0.1.5 + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/plugin-user-settings@0.3.12 + - @backstage/plugin-api-docs@0.6.16 + - @backstage/cli@0.10.0 + - @backstage/plugin-circleci@0.2.30 + - @backstage/core-plugin-api@0.2.2 + - @backstage/plugin-search@0.5.0 + - @backstage/plugin-tech-insights@0.1.0 + - @backstage/core-app-api@0.1.24 + - @backstage/plugin-kubernetes@0.4.22 + - @backstage/plugin-scaffolder@0.11.13 + - @backstage/plugin-techdocs@0.12.8 + ## 0.2.53 ### Patch Changes diff --git a/packages/app/package.json b/packages/app/package.json index 09141f7cf7..36b811c27d 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,24 +1,24 @@ { "name": "example-app", - "version": "0.2.53", + "version": "0.2.55", "private": true, "bundled": true, "dependencies": { "@backstage/app-defaults": "^0.1.1", "@backstage/catalog-model": "^0.9.7", - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.21", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/integration-react": "^0.1.14", - "@backstage/plugin-api-docs": "^0.6.14", - "@backstage/plugin-azure-devops": "^0.1.4", + "@backstage/plugin-api-docs": "^0.6.16", + "@backstage/plugin-azure-devops": "^0.1.5", "@backstage/plugin-badges": "^0.2.14", "@backstage/plugin-catalog": "^0.7.3", "@backstage/plugin-catalog-graph": "^0.2.2", "@backstage/plugin-catalog-import": "^0.7.4", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/plugin-circleci": "^0.2.29", + "@backstage/plugin-circleci": "^0.2.30", "@backstage/plugin-cloudbuild": "^0.2.28", "@backstage/plugin-code-coverage": "^0.1.18", "@backstage/plugin-cost-insights": "^0.11.11", @@ -29,22 +29,23 @@ "@backstage/plugin-home": "^0.4.6", "@backstage/plugin-jenkins": "^0.5.12", "@backstage/plugin-kafka": "^0.2.21", - "@backstage/plugin-kubernetes": "^0.4.20", + "@backstage/plugin-kubernetes": "^0.4.22", "@backstage/plugin-lighthouse": "^0.2.30", "@backstage/plugin-newrelic": "^0.3.9", "@backstage/plugin-org": "^0.3.28", "@backstage/plugin-pagerduty": "0.3.18", "@backstage/plugin-rollbar": "^0.3.19", - "@backstage/plugin-scaffolder": "^0.11.11", - "@backstage/plugin-search": "^0.4.18", + "@backstage/plugin-scaffolder": "^0.11.13", + "@backstage/plugin-search": "^0.5.0", "@backstage/plugin-sentry": "^0.3.29", "@backstage/plugin-shortcuts": "^0.1.14", "@backstage/plugin-tech-radar": "^0.4.12", - "@backstage/plugin-techdocs": "^0.12.6", + "@backstage/plugin-techdocs": "^0.12.8", "@backstage/plugin-todo": "^0.1.15", - "@backstage/plugin-user-settings": "^0.3.11", + "@backstage/plugin-user-settings": "^0.3.12", "@backstage/search-common": "^0.2.0", - "@backstage/theme": "^0.2.11", + "@backstage/plugin-tech-insights": "^0.1.0", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx index 401665b62e..7e5d3db926 100644 --- a/packages/app/src/App.tsx +++ b/packages/app/src/App.tsx @@ -34,6 +34,7 @@ import { SignInPage, } from '@backstage/core-components'; import { apiDocsPlugin, ApiExplorerPage } from '@backstage/plugin-api-docs'; +import { AzurePullRequestsPage } from '@backstage/plugin-azure-devops'; import { CatalogEntityPage, CatalogIndexPage, @@ -175,7 +176,20 @@ const routes = ( > {techDocsPage} - }> + + entity?.metadata?.tags?.includes('recommended') ?? false, + }, + ]} + /> + } + > @@ -203,6 +217,7 @@ const routes = ( element={} /> } /> + } /> ); diff --git a/packages/app/src/components/Root/Root.tsx b/packages/app/src/components/Root/Root.tsx index f365310595..2d9b9b97f1 100644 --- a/packages/app/src/components/Root/Root.tsx +++ b/packages/app/src/components/Root/Root.tsx @@ -29,7 +29,10 @@ import LogoIcon from './LogoIcon'; import { NavLink } from 'react-router-dom'; import { GraphiQLIcon } from '@backstage/plugin-graphiql'; import { Settings as SidebarSettings } from '@backstage/plugin-user-settings'; -import { SidebarSearchModal } from '@backstage/plugin-search'; +import { + SidebarSearchModal, + SearchContextProvider, +} from '@backstage/plugin-search'; import { Shortcuts } from '@backstage/plugin-shortcuts'; import { Sidebar, @@ -41,6 +44,7 @@ import { SidebarSpace, SidebarScrollWrapper, } from '@backstage/core-components'; +import { AzurePullRequestsIcon } from '@backstage/plugin-azure-devops'; const useSidebarLogoStyles = makeStyles({ root: { @@ -79,7 +83,9 @@ export const Root = ({ children }: PropsWithChildren<{}>) => ( - + + + {/* Global nav, not org-specific */} @@ -94,6 +100,11 @@ export const Root = ({ children }: PropsWithChildren<{}>) => ( + diff --git a/packages/backend-common/CHANGELOG.md b/packages/backend-common/CHANGELOG.md index 3ab36cc679..b2bf629bed 100644 --- a/packages/backend-common/CHANGELOG.md +++ b/packages/backend-common/CHANGELOG.md @@ -1,5 +1,37 @@ # @backstage/backend-common +## 0.9.12 + +### Patch Changes + +- 905dd952ac: Create a `TokenManager` interface and `ServerTokenManager` implementation to generate and validate server tokens for authenticated backend-to-backend API requests. +- 6b500622d5: Move to using node-fetch internally instead of cross-fetch +- 54989b671d: Fixed a potential crash in the log redaction code +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/config-loader@0.8.1 + +## 0.9.11 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/errors@0.1.5 + ## 0.9.10 ### Patch Changes diff --git a/packages/backend-common/api-report.md b/packages/backend-common/api-report.md index e3119e78a8..e623f656ab 100644 --- a/packages/backend-common/api-report.md +++ b/packages/backend-common/api-report.md @@ -175,9 +175,17 @@ export function createStatusCheckRouter(options: { // @public (undocumented) export class DatabaseManager { forPlugin(pluginId: string): PluginDatabaseManager; - static fromConfig(config: Config): DatabaseManager; + static fromConfig( + config: Config, + options?: DatabaseManagerOptions, + ): DatabaseManager; } +// @public +export type DatabaseManagerOptions = { + migrations?: PluginDatabaseManager['migrations']; +}; + // @public (undocumented) export class DockerContainerRunner implements ContainerRunner { constructor({ dockerClient }: { dockerClient: Docker }); @@ -395,6 +403,9 @@ export type PluginCacheManager = { // @public export interface PluginDatabaseManager { getClient(): Promise; + migrations?: { + skip?: boolean; + }; } // @public @@ -526,6 +537,20 @@ export type SearchResponseFile = { content(): Promise; }; +// @public +export class ServerTokenManager implements TokenManager { + // (undocumented) + authenticate(token: string): Promise; + // (undocumented) + static fromConfig(config: Config): ServerTokenManager; + // (undocumented) + getToken(): Promise<{ + token: string; + }>; + // (undocumented) + static noop(): TokenManager; +} + // @public (undocumented) export type ServiceBuilder = { loadConfig(config: Config): ServiceBuilder; @@ -583,6 +608,16 @@ export interface StatusCheckHandlerOptions { statusCheck?: StatusCheck; } +// @public +export interface TokenManager { + // (undocumented) + authenticate: (token: string) => Promise; + // (undocumented) + getToken: () => Promise<{ + token: string; + }>; +} + // @public export type UrlReader = { read(url: string): Promise; @@ -618,4 +653,8 @@ export function useHotCleanup( // @public export function useHotMemoize(_module: NodeModule, valueFactory: () => T): T; + +// Warnings were encountered during analysis: +// +// src/database/types.d.ts:23:12 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration ``` diff --git a/packages/backend-common/config.d.ts b/packages/backend-common/config.d.ts index 3690069431..fe3c7a5bec 100644 --- a/packages/backend-common/config.d.ts +++ b/packages/backend-common/config.d.ts @@ -20,6 +20,20 @@ export interface Config { }; backend: { + /** Backend configuration for when request authentication is enabled */ + auth?: { + /** Keys shared by all backends for signing and validating backend tokens. */ + keys: { + /** + * Secret for generating tokens. Should be a base64 string, recommended + * length is 24 bytes. + * + * @visibility secret + */ + secret: string; + }[]; + }; + baseUrl: string; // defined in core, but repeated here without doc /** Address that the backend should listen to. */ @@ -82,6 +96,12 @@ export interface Config { * @default database */ pluginDivisionMode?: 'database' | 'schema'; + /** + * Arbitrary config object to pass to knex when initializing + * (https://knexjs.org/#Installation-client). Most notable is the debug + * and asyncStackTraces booleans + */ + knexConfig?: object; /** Plugin specific database configuration and client override */ plugin?: { [pluginId: string]: { @@ -97,6 +117,14 @@ export interface Config { * Defaults to base config if unspecified. */ ensureExists?: boolean; + /** + * Arbitrary config object to pass to knex when initializing + * (https://knexjs.org/#Installation-client). Most notable is the + * debug and asyncStackTraces booleans. + * + * This is merged recursively into the base knexConfig + */ + knexConfig?: object; }; }; }; diff --git a/packages/backend-common/package.json b/packages/backend-common/package.json index 9e0187137d..e46d659175 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.9.10", + "version": "0.9.12", "main": "src/index.ts", "types": "src/index.ts", "private": false, @@ -31,9 +31,9 @@ "dependencies": { "@backstage/cli-common": "^0.1.6", "@backstage/config": "^0.1.11", - "@backstage/config-loader": "^0.8.0", - "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", + "@backstage/config-loader": "^0.8.1", + "@backstage/errors": "^0.1.5", + "@backstage/integration": "^0.6.10", "@backstage/types": "^0.1.1", "@google-cloud/storage": "^5.8.0", "@lerna/project": "^4.0.0", @@ -46,7 +46,6 @@ "compression": "^1.7.4", "concat-stream": "^2.0.0", "cors": "^2.8.5", - "cross-fetch": "^3.0.6", "dockerode": "^3.3.1", "express": "^4.17.1", "express-promise-router": "^4.1.0", @@ -54,6 +53,7 @@ "git-url-parse": "^11.6.0", "helmet": "^4.0.0", "isomorphic-git": "^1.8.0", + "jose": "^1.27.1", "keyv": "^4.0.3", "keyv-memcache": "^1.2.5", "knex": "^0.95.1", @@ -63,6 +63,7 @@ "minimist": "^1.2.5", "morgan": "^1.10.0", "node-abort-controller": "^3.0.1", + "node-fetch": "^2.6.1", "raw-body": "^2.4.1", "selfsigned": "^1.10.7", "stoppable": "^1.1.0", @@ -80,8 +81,8 @@ } }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/test-utils": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.23", "@types/archiver": "^5.1.0", "@types/compression": "^1.7.0", "@types/concat-stream": "^1.6.0", diff --git a/packages/backend-common/src/database/DatabaseManager.test.ts b/packages/backend-common/src/database/DatabaseManager.test.ts index f2fe855234..bd2e7b9f71 100644 --- a/packages/backend-common/src/database/DatabaseManager.test.ts +++ b/packages/backend-common/src/database/DatabaseManager.test.ts @@ -36,25 +36,45 @@ describe('DatabaseManager', () => { afterEach(() => jest.resetAllMocks()); describe('DatabaseManager.fromConfig', () => { - it('accesses the backend.database key', () => { - const config = new ConfigReader({ - backend: { - database: { - client: 'pg', - connection: { - host: 'localhost', - user: 'foo', - password: 'bar', - database: 'foodb', - }, + const backendConfig = { + backend: { + database: { + client: 'pg', + connection: { + host: 'localhost', + user: 'foo', + password: 'bar', + database: 'foodb', }, }, - }); + }, + }; + + it('accesses the backend.database key', () => { + const config = new ConfigReader(backendConfig); const getConfigSpy = jest.spyOn(config, 'getConfig'); DatabaseManager.fromConfig(config); expect(getConfigSpy).toHaveBeenCalledWith('backend.database'); }); + + it('handles default options', () => { + const config = new ConfigReader(backendConfig); + const database = DatabaseManager.fromConfig(config); + const client = database.forPlugin('test'); + + expect(client.migrations?.skip).toBe(false); + }); + + it('handles migrations options', () => { + const config = new ConfigReader(backendConfig); + const database = DatabaseManager.fromConfig(config, { + migrations: { skip: true }, + }); + const client = database.forPlugin('test'); + + expect(client.migrations?.skip).toBe(true); + }); }); describe('DatabaseManager.forPlugin', () => { @@ -505,5 +525,42 @@ describe('DatabaseManager', () => { 'database_name_overriden', ); }); + + it('fetches and merges additional knex config', async () => { + const testManager = DatabaseManager.fromConfig( + new ConfigReader({ + backend: { + database: { + client: 'pg', + connection: { + host: 'localhost', + database: 'foodb', + }, + knexConfig: { + something: false, + }, + plugin: { + testdbname: { + knexConfig: { + debug: true, + }, + }, + }, + }, + }, + }), + ); + await testManager.forPlugin('testdbname').getClient(); + + const mockCalls = mocked(createDatabaseClient).mock.calls.splice(-1); + const [baseConfig] = mockCalls[0]; + + expect(baseConfig.data).toEqual( + expect.objectContaining({ + debug: true, + something: false, + }), + ); + }); }); }); diff --git a/packages/backend-common/src/database/DatabaseManager.ts b/packages/backend-common/src/database/DatabaseManager.ts index cf5e801d66..8e23a219ec 100644 --- a/packages/backend-common/src/database/DatabaseManager.ts +++ b/packages/backend-common/src/database/DatabaseManager.ts @@ -14,20 +14,20 @@ * limitations under the License. */ -import { Knex } from 'knex'; -import { omit } from 'lodash'; import { Config, ConfigReader } from '@backstage/config'; import { JsonObject } from '@backstage/types'; +import { Knex } from 'knex'; +import { merge, omit } from 'lodash'; +import { mergeDatabaseConfig } from './config'; import { - createNameOverride, - ensureDatabaseExists, - normalizeConnection, - createSchemaOverride, - ensureSchemaExists, createDatabaseClient, + createNameOverride, + createSchemaOverride, + ensureDatabaseExists, + ensureSchemaExists, + normalizeConnection, } from './connection'; import { PluginDatabaseManager } from './types'; -import { mergeDatabaseConfig } from './config'; /** * Provides a config lookup path for a plugin's config block. @@ -36,6 +36,15 @@ function pluginPath(pluginId: string): string { return `plugin.${pluginId}`; } +/** + * Configuration options object. + * + * @public + */ +export type DatabaseManagerOptions = { + migrations?: PluginDatabaseManager['migrations']; +}; + /** @public */ export class DatabaseManager { /** @@ -47,19 +56,25 @@ export class DatabaseManager { * names if config is not provided. * * @param config - The loaded application configuration. + * @param options - An optional configuration object. */ - static fromConfig(config: Config): DatabaseManager { + static fromConfig( + config: Config, + options?: DatabaseManagerOptions, + ): DatabaseManager { const databaseConfig = config.getConfig('backend.database'); return new DatabaseManager( databaseConfig, databaseConfig.getOptionalString('prefix'), + options, ); } private constructor( private readonly config: Config, private readonly prefix: string = 'backstage_plugin_', + private readonly options?: DatabaseManagerOptions, ) {} /** @@ -76,6 +91,10 @@ export class DatabaseManager { getClient(): Promise { return _this.getDatabase(pluginId); }, + migrations: { + skip: false, + ..._this.options?.migrations, + }, }; } @@ -138,6 +157,24 @@ export class DatabaseManager { }; } + /** + * Provides the knexConfig which should be used for a given plugin. + * + * @param pluginId Plugin to get the knexConfig for + * @returns the merged kexConfig value or undefined if it isn't specified + */ + private getAdditionalKnexConfig(pluginId: string): JsonObject | undefined { + const pluginConfig = this.config + .getOptionalConfig(`${pluginPath(pluginId)}.knexConfig`) + ?.get(); + + const baseConfig = this.config + .getOptionalConfig('knexConfig') + ?.get(); + + return merge(baseConfig, pluginConfig); + } + private getEnsureExistsConfig(pluginId: string): boolean { const baseConfig = this.config.getOptionalBoolean('ensureExists') ?? true; return ( @@ -200,6 +237,7 @@ export class DatabaseManager { const { client } = this.getClientType(pluginId); return { + ...this.getAdditionalKnexConfig(pluginId), client, connection: this.getConnectionConfig(pluginId), }; diff --git a/packages/backend-common/src/database/types.ts b/packages/backend-common/src/database/types.ts index e96f86980b..344f1088b8 100644 --- a/packages/backend-common/src/database/types.ts +++ b/packages/backend-common/src/database/types.ts @@ -30,6 +30,18 @@ export interface PluginDatabaseManager { * stores so that plugins are discouraged from database integration. */ getClient(): Promise; + + /** + * This property is used to control the behavior of database migrations. + */ + migrations?: { + /** + * skip database migrations. Useful if connecting to a read-only database. + * + * @default false + */ + skip?: boolean; + }; } /** diff --git a/packages/backend-common/src/index.ts b/packages/backend-common/src/index.ts index c214961a2e..e430ddc1a4 100644 --- a/packages/backend-common/src/index.ts +++ b/packages/backend-common/src/index.ts @@ -31,4 +31,5 @@ export * from './paths'; export * from './reading'; export * from './scm'; export * from './service'; +export * from './tokens'; export * from './util'; diff --git a/packages/backend-common/src/logging/rootLogger.ts b/packages/backend-common/src/logging/rootLogger.ts index 2a4226f88f..12db7d42a1 100644 --- a/packages/backend-common/src/logging/rootLogger.ts +++ b/packages/backend-common/src/logging/rootLogger.ts @@ -54,10 +54,13 @@ export function setRootLoggerRedactionList(redactionList: string[]) { * and replaces them with the corresponding identifier. */ function redactLogLine(info: winston.Logform.TransformableInfo) { - // TODO(hhogg): The logger is created before the config is loaded, - // because the logger is needed in the config loader. There is a risk of - // a secret being logged out during the config loading stage. - if (redactionRegExp) { + // TODO(hhogg): The logger is created before the config is loaded, because the + // logger is needed in the config loader. There is a risk of a secret being + // logged out during the config loading stage. + // TODO(freben): Added a check that info.message actually was a string, + // because it turned out that this was not necessarily guaranteed. + // https://github.com/backstage/backstage/issues/8306 + if (redactionRegExp && typeof info.message === 'string') { info.message = info.message.replace(redactionRegExp, '[REDACTED]'); } diff --git a/packages/backend-common/src/reading/AzureUrlReader.ts b/packages/backend-common/src/reading/AzureUrlReader.ts index 82d1192b17..37d97b8941 100644 --- a/packages/backend-common/src/reading/AzureUrlReader.ts +++ b/packages/backend-common/src/reading/AzureUrlReader.ts @@ -22,7 +22,7 @@ import { getAzureRequestOptions, ScmIntegrations, } from '@backstage/integration'; -import fetch from 'cross-fetch'; +import fetch, { Response } from 'node-fetch'; import { Minimatch } from 'minimatch'; import { Readable } from 'stream'; import { NotFoundError, NotModifiedError } from '@backstage/errors'; @@ -72,7 +72,13 @@ export class AzureUrlReader implements UrlReader { try { response = await fetch(builtUrl, { ...getAzureRequestOptions(this.integration.config), - ...(signal && { signal }), + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can + // be removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + ...(signal && { signal: signal as any }), }); } catch (e) { throw new Error(`Unable to read ${url}, ${e}`); @@ -123,7 +129,13 @@ export class AzureUrlReader implements UrlReader { ...getAzureRequestOptions(this.integration.config, { Accept: 'application/zip', }), - ...(signal && { signal }), + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can be + // removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + ...(signal && { signal: signal as any }), }); if (!archiveAzureResponse.ok) { const message = `Failed to read tree from ${url}, ${archiveAzureResponse.status} ${archiveAzureResponse.statusText}`; diff --git a/packages/backend-common/src/reading/BitbucketUrlReader.ts b/packages/backend-common/src/reading/BitbucketUrlReader.ts index c1a113a50d..b0e8056370 100644 --- a/packages/backend-common/src/reading/BitbucketUrlReader.ts +++ b/packages/backend-common/src/reading/BitbucketUrlReader.ts @@ -23,7 +23,7 @@ import { getBitbucketRequestOptions, ScmIntegrations, } from '@backstage/integration'; -import fetch from 'cross-fetch'; +import fetch, { Response } from 'node-fetch'; import parseGitUrl from 'git-url-parse'; import { trimEnd } from 'lodash'; import { Minimatch } from 'minimatch'; @@ -94,7 +94,13 @@ export class BitbucketUrlReader implements UrlReader { try { response = await fetch(bitbucketUrl.toString(), { ...requestOptions, - ...(signal && { signal }), + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can be + // removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + ...(signal && { signal: signal as any }), }); } catch (e) { throw new Error(`Unable to read ${url}, ${e}`); diff --git a/packages/backend-common/src/reading/FetchUrlReader.ts b/packages/backend-common/src/reading/FetchUrlReader.ts index d82b1f7f52..7090d26d35 100644 --- a/packages/backend-common/src/reading/FetchUrlReader.ts +++ b/packages/backend-common/src/reading/FetchUrlReader.ts @@ -15,7 +15,7 @@ */ import { NotFoundError, NotModifiedError } from '@backstage/errors'; -import fetch from 'cross-fetch'; +import fetch, { Response } from 'node-fetch'; import { ReaderFactory, ReadTreeResponse, @@ -86,7 +86,13 @@ export class FetchUrlReader implements UrlReader { headers: { ...(options?.etag && { 'If-None-Match': options.etag }), }, - signal: options?.signal, + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can + // be removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + signal: options?.signal as any, }); } catch (e) { throw new Error(`Unable to read ${url}, ${e}`); diff --git a/packages/backend-common/src/reading/GithubUrlReader.ts b/packages/backend-common/src/reading/GithubUrlReader.ts index 755e0f17e6..d0fbf6d8ae 100644 --- a/packages/backend-common/src/reading/GithubUrlReader.ts +++ b/packages/backend-common/src/reading/GithubUrlReader.ts @@ -21,7 +21,7 @@ import { ScmIntegrations, } from '@backstage/integration'; import { RestEndpointMethodTypes } from '@octokit/rest'; -import fetch from 'cross-fetch'; +import fetch, { RequestInit, Response } from 'node-fetch'; import parseGitUrl from 'git-url-parse'; import { Minimatch } from 'minimatch'; import { Readable } from 'stream'; @@ -110,7 +110,13 @@ export class GithubUrlReader implements UrlReader { ...(options?.etag && { 'If-None-Match': options.etag }), Accept: 'application/vnd.github.v3.raw', }, - signal: options?.signal, + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can + // be removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + signal: options?.signal as any, }); } catch (e) { throw new Error(`Unable to read ${url}, ${e}`); @@ -165,7 +171,13 @@ export class GithubUrlReader implements UrlReader { repoDetails.repo.archive_url, commitSha, filepath, - { headers, signal: options?.signal }, + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can be + // removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + { headers, signal: options?.signal as any }, options, ); } @@ -189,7 +201,7 @@ export class GithubUrlReader implements UrlReader { repoDetails.repo.archive_url, commitSha, filepath, - { headers, signal: options?.signal }, + { headers, signal: options?.signal as any }, ); return { files, etag: commitSha }; diff --git a/packages/backend-common/src/reading/GitlabUrlReader.ts b/packages/backend-common/src/reading/GitlabUrlReader.ts index 128aed3c85..2444e317a7 100644 --- a/packages/backend-common/src/reading/GitlabUrlReader.ts +++ b/packages/backend-common/src/reading/GitlabUrlReader.ts @@ -20,7 +20,7 @@ import { GitLabIntegration, ScmIntegrations, } from '@backstage/integration'; -import fetch from 'cross-fetch'; +import fetch, { Response } from 'node-fetch'; import parseGitUrl from 'git-url-parse'; import { Minimatch } from 'minimatch'; import { Readable } from 'stream'; @@ -76,7 +76,13 @@ export class GitlabUrlReader implements UrlReader { ...getGitLabRequestOptions(this.integration.config).headers, ...(etag && { 'If-None-Match': etag }), }, - ...(signal && { signal }), + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can be + // removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + ...(signal && { signal: signal as any }), }); } catch (e) { throw new Error(`Unable to read ${url}, ${e}`); @@ -145,7 +151,13 @@ export class GitlabUrlReader implements UrlReader { ).toString(), { ...getGitLabRequestOptions(this.integration.config), - ...(signal && { signal }), + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can + // be removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + ...(signal && { signal: signal as any }), }, ); if (!commitsGitlabResponse.ok) { @@ -169,7 +181,13 @@ export class GitlabUrlReader implements UrlReader { )}/repository/archive?sha=${branch}`, { ...getGitLabRequestOptions(this.integration.config), - ...(signal && { signal }), + // TODO(freben): The signal cast is there because pre-3.x versions of + // node-fetch have a very slightly deviating AbortSignal type signature. + // The difference does not affect us in practice however. The cast can + // be removed after we support ESM for CLI dependencies and migrate to + // version 3 of node-fetch. + // https://github.com/backstage/backstage/issues/8242 + ...(signal && { signal: signal as any }), }, ); if (!archiveGitLabResponse.ok) { diff --git a/packages/backend-common/src/tokens/ServerTokenManager.test.ts b/packages/backend-common/src/tokens/ServerTokenManager.test.ts new file mode 100644 index 0000000000..fe724a0a4b --- /dev/null +++ b/packages/backend-common/src/tokens/ServerTokenManager.test.ts @@ -0,0 +1,189 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { TokenManager } from './types'; +import { ServerTokenManager } from './ServerTokenManager'; + +const emptyConfig = new ConfigReader({}); +const configWithSecret = new ConfigReader({ + backend: { auth: { keys: [{ secret: 'a-secret-key' }] } }, +}); + +describe('ServerTokenManager', () => { + it('should throw if secret in config does not exist', () => { + expect(() => ServerTokenManager.fromConfig(emptyConfig)).toThrowError(); + }); + + describe('getToken', () => { + it('should return a token if secret in config exists', async () => { + const tokenManager = ServerTokenManager.fromConfig(configWithSecret); + expect((await tokenManager.getToken()).token).toBeDefined(); + }); + + it('should return a token string if using a noop TokenManager', async () => { + const tokenManager = ServerTokenManager.noop(); + expect((await tokenManager.getToken()).token).toBeDefined(); + }); + }); + + describe('authenticate', () => { + it('should not throw if token is valid', async () => { + const tokenManager = ServerTokenManager.fromConfig(configWithSecret); + const { token } = await tokenManager.getToken(); + await expect(tokenManager.authenticate(token)).resolves.not.toThrow(); + }); + + it('should throw if token is invalid', async () => { + const tokenManager = ServerTokenManager.fromConfig(configWithSecret); + await expect( + tokenManager.authenticate('random-string'), + ).rejects.toThrowError(/invalid server token/i); + }); + + it('should validate server tokens created by a different instance using the same secret', async () => { + const tokenManager1 = ServerTokenManager.fromConfig(configWithSecret); + const tokenManager2 = ServerTokenManager.fromConfig(configWithSecret); + + const { token } = await tokenManager1.getToken(); + + await expect(tokenManager2.authenticate(token)).resolves.not.toThrow(); + }); + + it('should validate server tokens created using any of the secrets', async () => { + const tokenManager1 = ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { auth: { keys: [{ secret: 'a1b2c3' }] } }, + }), + ); + const tokenManager2 = ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { auth: { keys: [{ secret: 'd4e5f6' }] } }, + }), + ); + const tokenManager3 = ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { + auth: { keys: [{ secret: 'a1b2c3' }, { secret: 'd4e5f6' }] }, + }, + }), + ); + + const { token: token1 } = await tokenManager1.getToken(); + await expect(tokenManager3.authenticate(token1)).resolves.not.toThrow(); + + const { token: token2 } = await tokenManager2.getToken(); + await expect(tokenManager3.authenticate(token2)).resolves.not.toThrow(); + }); + + it('should throw for server tokens created using a different secret', async () => { + const tokenManager1 = ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { auth: { keys: [{ secret: 'a1b2c3' }] } }, + }), + ); + const tokenManager2 = ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { auth: { keys: [{ secret: 'd4e5f6' }] } }, + }), + ); + + const { token } = await tokenManager1.getToken(); + + await expect(tokenManager2.authenticate(token)).rejects.toThrowError( + /invalid server token/i, + ); + }); + + it('should throw for server tokens created using a noop TokenManager', async () => { + const noopTokenManager = ServerTokenManager.noop(); + const tokenManager = ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { auth: { keys: [{ secret: 'a1b2c3' }] } }, + }), + ); + + const { token } = await noopTokenManager.getToken(); + + await expect(tokenManager.authenticate(token)).rejects.toThrowError( + /invalid server token/i, + ); + }); + }); + + describe('ServerTokenManager.fromConfig', () => { + it('should throw if backend auth configuration is missing', () => { + expect(() => + ServerTokenManager.fromConfig(new ConfigReader({})), + ).toThrow(); + }); + + it('should throw if no keys are included in the configuration', () => { + expect(() => + ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { auth: { keys: [] } }, + }), + ), + ).toThrow(); + }); + + it('should throw if any key is missing a secret property', () => { + expect(() => + ServerTokenManager.fromConfig( + new ConfigReader({ + backend: { + auth: { + keys: [{ secret: '123' }, {}, { secret: '789' }], + }, + }, + }), + ), + ).toThrow(); + }); + }); + + describe('ServerTokenManager.noop', () => { + let noopTokenManager: TokenManager; + + beforeEach(() => { + noopTokenManager = ServerTokenManager.noop(); + }); + + it('should accept tokens it generates', async () => { + const { token } = await noopTokenManager.getToken(); + + await expect(noopTokenManager.authenticate(token)).resolves.not.toThrow(); + }); + + it('should accept tokens generated by other noop token managers', async () => { + const noopTokenManager2 = ServerTokenManager.noop(); + await expect( + noopTokenManager.authenticate( + ( + await noopTokenManager2.getToken() + ).token, + ), + ).resolves.not.toThrow(); + }); + + it('should accept signed tokens', async () => { + const tokenManager = ServerTokenManager.fromConfig(configWithSecret); + await expect( + noopTokenManager.authenticate((await tokenManager.getToken()).token), + ).resolves.not.toThrow(); + }); + }); +}); diff --git a/packages/backend-common/src/tokens/ServerTokenManager.ts b/packages/backend-common/src/tokens/ServerTokenManager.ts new file mode 100644 index 0000000000..35a07509b6 --- /dev/null +++ b/packages/backend-common/src/tokens/ServerTokenManager.ts @@ -0,0 +1,80 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { JWKS, JWK, JWT } from 'jose'; +import { Config } from '@backstage/config'; +import { AuthenticationError } from '@backstage/errors'; +import { TokenManager } from './types'; + +class NoopTokenManager implements TokenManager { + async getToken() { + return { token: '' }; + } + + async authenticate() {} +} + +/** + * Creates and validates tokens for use during backend-to-backend + * authentication. + * + * @public + */ +export class ServerTokenManager implements TokenManager { + private readonly verificationKeys: JWKS.KeyStore; + private readonly signingKey: JWK.Key; + + static noop(): TokenManager { + return new NoopTokenManager(); + } + + static fromConfig(config: Config) { + return new ServerTokenManager( + config + .getConfigArray('backend.auth.keys') + .map(key => key.getString('secret')), + ); + } + + private constructor(secrets?: string[]) { + if (!secrets?.length) { + throw new Error( + 'No secrets provided when constructing ServerTokenManager', + ); + } + + this.verificationKeys = new JWKS.KeyStore( + secrets.map(k => JWK.asKey({ kty: 'oct', k })), + ); + this.signingKey = this.verificationKeys.all()[0]; + } + + async getToken(): Promise<{ token: string }> { + const jwt = JWT.sign({ sub: 'backstage-server' }, this.signingKey, { + algorithm: 'HS256', + }); + + return { token: jwt }; + } + + async authenticate(token: string): Promise { + try { + JWT.verify(token, this.verificationKeys); + } catch (e) { + throw new AuthenticationError('Invalid server token'); + } + } +} diff --git a/packages/backend-common/src/tokens/index.ts b/packages/backend-common/src/tokens/index.ts new file mode 100644 index 0000000000..43ff12e597 --- /dev/null +++ b/packages/backend-common/src/tokens/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { ServerTokenManager } from './ServerTokenManager'; +export type { TokenManager } from './types'; diff --git a/packages/backend-common/src/tokens/types.ts b/packages/backend-common/src/tokens/types.ts new file mode 100644 index 0000000000..1fea018db9 --- /dev/null +++ b/packages/backend-common/src/tokens/types.ts @@ -0,0 +1,25 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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. + */ + +/** + * Interface for creating and validating tokens. + * + * @public + */ +export interface TokenManager { + getToken: () => Promise<{ token: string }>; + authenticate: (token: string) => Promise; +} diff --git a/packages/backend-tasks/package.json b/packages/backend-tasks/package.json index 2bc6474615..a22895140e 100644 --- a/packages/backend-tasks/package.json +++ b/packages/backend-tasks/package.json @@ -29,7 +29,7 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/config": "^0.1.11", "@backstage/errors": "^0.1.4", "@backstage/types": "^0.1.1", @@ -43,8 +43,8 @@ "zod": "^3.9.5" }, "devDependencies": { - "@backstage/backend-test-utils": "^0.1.9", - "@backstage/cli": "^0.9.0", + "@backstage/backend-test-utils": "^0.1.10", + "@backstage/cli": "^0.10.0", "jest": "^26.0.1", "wait-for-expect": "^3.0.2" }, diff --git a/packages/backend-test-utils/CHANGELOG.md b/packages/backend-test-utils/CHANGELOG.md index 9927aa3cc7..584187b9d3 100644 --- a/packages/backend-test-utils/CHANGELOG.md +++ b/packages/backend-test-utils/CHANGELOG.md @@ -1,5 +1,13 @@ # @backstage/backend-test-utils +## 0.1.10 + +### Patch Changes + +- Updated dependencies + - @backstage/backend-common@0.9.12 + - @backstage/cli@0.10.0 + ## 0.1.9 ### Patch Changes diff --git a/packages/backend-test-utils/package.json b/packages/backend-test-utils/package.json index c3d4f730b7..2c1724e50f 100644 --- a/packages/backend-test-utils/package.json +++ b/packages/backend-test-utils/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/backend-test-utils", "description": "Test helpers library for Backstage backends", - "version": "0.1.9", + "version": "0.1.10", "main": "src/index.ts", "types": "src/index.ts", "private": false, @@ -30,8 +30,8 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", - "@backstage/cli": "^0.9.0", + "@backstage/backend-common": "^0.9.12", + "@backstage/cli": "^0.10.0", "@backstage/config": "^0.1.9", "knex": "^0.95.1", "mysql2": "^2.2.5", @@ -41,7 +41,7 @@ "uuid": "^8.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "jest": "^26.0.1" }, "files": [ diff --git a/packages/backend/CHANGELOG.md b/packages/backend/CHANGELOG.md index 7cf7d9ddaa..7aa2fb5f55 100644 --- a/packages/backend/CHANGELOG.md +++ b/packages/backend/CHANGELOG.md @@ -1,5 +1,49 @@ # example-backend +## 0.2.55 + +### Patch Changes + +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/plugin-scaffolder-backend@0.15.15 + - @backstage/plugin-auth-backend@0.4.10 + - @backstage/plugin-kubernetes-backend@0.3.20 + - @backstage/plugin-badges-backend@0.1.13 + - @backstage/plugin-catalog-backend@0.19.0 + - @backstage/plugin-code-coverage-backend@0.1.16 + - @backstage/plugin-jenkins-backend@0.1.9 + - @backstage/plugin-tech-insights-backend@0.1.3 + - @backstage/plugin-techdocs-backend@0.11.0 + - @backstage/plugin-todo-backend@0.1.14 + - @backstage/backend-common@0.9.12 + - @backstage/plugin-azure-devops-backend@0.2.3 + - @backstage/plugin-tech-insights-backend-module-jsonfc@0.1.2 + - @backstage/plugin-tech-insights-node@0.1.1 + - example-app@0.2.55 + +## 0.2.54 + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-kubernetes-backend@0.3.19 + - @backstage/plugin-tech-insights-backend@0.1.2 + - @backstage/plugin-tech-insights-backend-module-jsonfc@0.1.1 + - @backstage/plugin-auth-backend@0.4.9 + - @backstage/plugin-scaffolder-backend@0.15.14 + - @backstage/plugin-catalog-backend@0.18.0 + - @backstage/plugin-kafka-backend@0.2.12 + - @backstage/backend-common@0.9.11 + - @backstage/plugin-azure-devops-backend@0.2.2 + - @backstage/plugin-badges-backend@0.1.12 + - @backstage/plugin-code-coverage-backend@0.1.15 + - @backstage/plugin-jenkins-backend@0.1.8 + - @backstage/plugin-proxy-backend@0.2.14 + - @backstage/plugin-rollbar-backend@0.1.16 + - @backstage/plugin-search-backend@0.2.7 + - @backstage/plugin-techdocs-backend@0.10.9 + ## 0.2.52 ### Patch Changes diff --git a/packages/backend/package.json b/packages/backend/package.json index 1cef99c6a0..cc8a8ac76a 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -1,6 +1,6 @@ { "name": "example-backend", - "version": "0.2.52", + "version": "0.2.55", "main": "dist/index.cjs.js", "types": "src/index.ts", "license": "Apache-2.0", @@ -24,39 +24,39 @@ "migrate:create": "knex migrate:make -x ts" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", - "@backstage/integration": "^0.6.8", + "@backstage/integration": "^0.6.10", "@backstage/plugin-app-backend": "^0.3.19", - "@backstage/plugin-auth-backend": "^0.4.8", - "@backstage/plugin-azure-devops-backend": "^0.2.1", - "@backstage/plugin-badges-backend": "^0.1.11", - "@backstage/plugin-catalog-backend": "^0.17.4", - "@backstage/plugin-code-coverage-backend": "^0.1.14", + "@backstage/plugin-auth-backend": "^0.4.10", + "@backstage/plugin-azure-devops-backend": "^0.2.3", + "@backstage/plugin-badges-backend": "^0.1.13", + "@backstage/plugin-catalog-backend": "^0.19.0", + "@backstage/plugin-code-coverage-backend": "^0.1.16", "@backstage/plugin-graphql-backend": "^0.1.9", - "@backstage/plugin-jenkins-backend": "^0.1.7", - "@backstage/plugin-kubernetes-backend": "^0.3.18", - "@backstage/plugin-kafka-backend": "^0.2.11", - "@backstage/plugin-proxy-backend": "^0.2.13", - "@backstage/plugin-rollbar-backend": "^0.1.15", - "@backstage/plugin-scaffolder-backend": "^0.15.13", + "@backstage/plugin-jenkins-backend": "^0.1.9", + "@backstage/plugin-kubernetes-backend": "^0.3.20", + "@backstage/plugin-kafka-backend": "^0.2.12", + "@backstage/plugin-proxy-backend": "^0.2.14", + "@backstage/plugin-rollbar-backend": "^0.1.16", + "@backstage/plugin-scaffolder-backend": "^0.15.15", "@backstage/plugin-scaffolder-backend-module-rails": "^0.1.7", - "@backstage/plugin-search-backend": "^0.2.6", + "@backstage/plugin-search-backend": "^0.2.7", "@backstage/plugin-search-backend-node": "^0.4.2", "@backstage/plugin-search-backend-module-elasticsearch": "^0.0.5", "@backstage/plugin-search-backend-module-pg": "^0.2.1", - "@backstage/plugin-techdocs-backend": "^0.10.8", - "@backstage/plugin-tech-insights-backend": "^0.1.1", - "@backstage/plugin-tech-insights-node": "^0.1.0", - "@backstage/plugin-tech-insights-backend-module-jsonfc": "^0.1.0", - "@backstage/plugin-todo-backend": "^0.1.13", + "@backstage/plugin-techdocs-backend": "^0.11.0", + "@backstage/plugin-tech-insights-backend": "^0.1.3", + "@backstage/plugin-tech-insights-node": "^0.1.1", + "@backstage/plugin-tech-insights-backend-module-jsonfc": "^0.1.2", + "@backstage/plugin-todo-backend": "^0.1.14", "@gitbeaker/node": "^34.6.0", "@octokit/rest": "^18.5.3", "azure-devops-node-api": "^11.0.1", "dockerode": "^3.3.1", - "example-app": "^0.2.53", + "example-app": "^0.2.55", "express": "^4.17.1", "express-promise-router": "^4.1.0", "express-prom-bundle": "^6.3.6", @@ -68,7 +68,7 @@ "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/dockerode": "^3.3.0", "@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 ea1d643187..e3c15b95b6 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -33,6 +33,7 @@ import { SingleHostDiscovery, UrlReaders, useHotMemoize, + ServerTokenManager, } from '@backstage/backend-common'; import { Config } from '@backstage/config'; import healthcheck from './plugins/healthcheck'; @@ -60,6 +61,7 @@ function makeCreateEnv(config: Config) { const root = getRootLogger(); const reader = UrlReaders.default({ logger: root, config }); const discovery = SingleHostDiscovery.fromConfig(config); + const tokenManager = ServerTokenManager.noop(); root.info(`Created UrlReader ${reader}`); @@ -70,7 +72,7 @@ function makeCreateEnv(config: Config) { const logger = root.child({ type: 'plugin', plugin }); const database = databaseManager.forPlugin(plugin); const cache = cacheManager.forPlugin(plugin); - return { logger, cache, database, config, reader, discovery }; + return { logger, cache, database, config, reader, discovery, tokenManager }; }; } diff --git a/packages/backend/src/plugins/search.ts b/packages/backend/src/plugins/search.ts index 4cf9c10021..9a8db0f0f9 100644 --- a/packages/backend/src/plugins/search.ts +++ b/packages/backend/src/plugins/search.ts @@ -59,6 +59,7 @@ export default async function createPlugin({ discovery, config, database, + tokenManager, }: PluginEnvironment) { // Initialize a connection to a search engine. const searchEngine = await createSearchEngine({ config, logger, database }); @@ -68,7 +69,10 @@ export default async function createPlugin({ // particular collator gathers entities from the software catalog. indexBuilder.addCollator({ defaultRefreshIntervalSeconds: 600, - collator: DefaultCatalogCollator.fromConfig(config, { discovery }), + collator: DefaultCatalogCollator.fromConfig(config, { + discovery, + tokenManager, + }), }); indexBuilder.addCollator({ @@ -76,6 +80,7 @@ export default async function createPlugin({ collator: DefaultTechDocsCollator.fromConfig(config, { discovery, logger, + tokenManager, }), }); diff --git a/packages/backend/src/plugins/techdocs.ts b/packages/backend/src/plugins/techdocs.ts index eb1e0502db..c32bbccbb0 100644 --- a/packages/backend/src/plugins/techdocs.ts +++ b/packages/backend/src/plugins/techdocs.ts @@ -29,6 +29,7 @@ export default async function createPlugin({ config, discovery, reader, + cache, }: PluginEnvironment): Promise { // Preparers are responsible for fetching source files for documentation. const preparers = await Preparers.fromConfig(config, { @@ -64,5 +65,6 @@ export default async function createPlugin({ logger, config, discovery, + cache, }); } diff --git a/packages/backend/src/types.ts b/packages/backend/src/types.ts index 8290e569ef..4be9c036b3 100644 --- a/packages/backend/src/types.ts +++ b/packages/backend/src/types.ts @@ -20,6 +20,7 @@ import { PluginCacheManager, PluginDatabaseManager, PluginEndpointDiscovery, + TokenManager, UrlReader, } from '@backstage/backend-common'; @@ -30,4 +31,5 @@ export type PluginEnvironment = { config: Config; reader: UrlReader; discovery: PluginEndpointDiscovery; + tokenManager: TokenManager; }; diff --git a/packages/catalog-client/package.json b/packages/catalog-client/package.json index 4ab727b6b3..28a3d5f969 100644 --- a/packages/catalog-client/package.json +++ b/packages/catalog-client/package.json @@ -35,7 +35,7 @@ "cross-fetch": "^3.0.6" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest": "^26.0.7", "msw": "^0.35.0" }, diff --git a/packages/catalog-model/package.json b/packages/catalog-model/package.json index 0ba07aec3c..60331d9dc8 100644 --- a/packages/catalog-model/package.json +++ b/packages/catalog-model/package.json @@ -42,7 +42,7 @@ "yup": "^0.32.9" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest": "^26.0.7", "@types/lodash": "^4.14.151", "yaml": "^1.9.2" diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 407c4fcbf2..6be3a461bf 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,5 +1,42 @@ # @backstage/cli +## 0.10.0 + +### Minor Changes + +- ea99ef5198: Remove the `backend:build-image` command from the CLI and added more deprecation warnings to other deprecated fields like `--lax` and `remove-plugin` + +### Patch Changes + +- e7230ef814: Bump react-dev-utils to v12 +- 416b68675d: build(dependencies): bump `style-loader` from 1.2.1 to 3.3.1 +- Updated dependencies + - @backstage/config-loader@0.8.1 + +## 0.9.1 + +### Patch Changes + +- dde216acf4: Switch the default test coverage provider from the jest default one to `'v8'`, which provides much better coverage information when using the default Backstage test setup. This is considered a bug fix as the current coverage information is often very inaccurate. +- 719cc87d2f: Disable ES transforms in tests transformed by the `jestSucraseTransform.js`. This is not considered a breaking change since all code is already transpiled this way in the development setup. +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- ee055cf6db: Update the default routes to use id instead of title +- Updated dependencies + - @backstage/errors@0.1.5 + ## 0.9.0 ### Minor Changes diff --git a/packages/cli/package.json b/packages/cli/package.json index 1eed5a742c..fe8a529de1 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/cli", "description": "CLI for developing Backstage plugins and apps", - "version": "0.9.0", + "version": "0.10.0", "private": false, "publishConfig": { "access": "public" @@ -30,17 +30,17 @@ "dependencies": { "@backstage/cli-common": "^0.1.6", "@backstage/config": "^0.1.11", - "@backstage/config-loader": "^0.8.0", - "@backstage/errors": "^0.1.4", + "@backstage/config-loader": "^0.8.1", + "@backstage/errors": "^0.1.5", "@backstage/types": "^0.1.1", "@hot-loader/react-dom": "^16.13.0", "@lerna/package-graph": "^4.0.0", "@lerna/project": "^4.0.0", "@octokit/request": "^5.4.12", "@rollup/plugin-commonjs": "^21.0.1", - "@rollup/plugin-json": "^4.0.2", + "@rollup/plugin-json": "^4.1.0", "@rollup/plugin-node-resolve": "^13.0.0", - "@rollup/plugin-yaml": "^3.0.0", + "@rollup/plugin-yaml": "^3.1.0", "@spotify/eslint-config-base": "^12.0.0", "@spotify/eslint-config-react": "^12.0.0", "@spotify/eslint-config-typescript": "^12.0.0", @@ -62,7 +62,7 @@ "css-loader": "^5.2.6", "dashify": "^2.0.0", "diff": "^5.0.0", - "esbuild": "^0.8.56", + "esbuild": "^0.14.1", "eslint": "^7.30.0", "eslint-config-prettier": "^8.3.0", "eslint-formatter-friendly": "^7.0.0", @@ -90,19 +90,19 @@ "postcss": "^8.1.0", "process": "^0.11.10", "react": "^16.0.0", - "react-dev-utils": "^11.0.4", + "react-dev-utils": "^12.0.0-next.47", "react-hot-loader": "^4.12.21", "recursive-readdir": "^2.2.2", "replace-in-file": "^6.0.0", - "rollup": "2.44.x", - "rollup-plugin-dts": "^3.0.1", - "rollup-plugin-esbuild": "2.6.x", + "rollup": "^2.60.2", + "rollup-plugin-dts": "^4.0.1", + "rollup-plugin-esbuild": "^4.7.2", "rollup-plugin-peer-deps-external": "^2.2.2", "rollup-plugin-postcss": "^4.0.0", "rollup-pluginutils": "^2.8.2", "run-script-webpack-plugin": "^0.0.11", "semver": "^7.3.2", - "style-loader": "^1.2.1", + "style-loader": "^3.3.1", "sucrase": "^3.20.2", "tar": "^6.1.2", "terser-webpack-plugin": "^5.1.3", @@ -117,14 +117,14 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/core-app-api": "^0.1.21", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", - "@backstage/theme": "^0.2.13", + "@backstage/test-utils": "^0.1.23", + "@backstage/theme": "^0.2.14", "@types/diff": "^5.0.0", "@types/express": "^4.17.6", "@types/fs-extra": "^9.0.1", diff --git a/packages/cli/src/commands/app/build.ts b/packages/cli/src/commands/app/build.ts index 22e7fb9de9..4fa3d1ac6e 100644 --- a/packages/cli/src/commands/app/build.ts +++ b/packages/cli/src/commands/app/build.ts @@ -20,8 +20,17 @@ import { buildBundle } from '../../lib/bundler'; import { parseParallel, PARALLEL_ENV_VAR } from '../../lib/parallel'; import { loadCliConfig } from '../../lib/config'; import { paths } from '../../lib/paths'; +import chalk from 'chalk'; export default async (cmd: Command) => { + if (cmd.lax) { + console.warn( + chalk.yellow( + `[DEPRECATED] - The --lax option is deprecated and will be removed in the future. Please open an issue towards https://github.com/backstage/backstage that describes your use-case if you need the flag to stay around.`, + ), + ); + } + const { name } = await fs.readJson(paths.resolveTarget('package.json')); await buildBundle({ entry: 'src/index', diff --git a/packages/cli/src/commands/backend/build.ts b/packages/cli/src/commands/backend/build.ts index 6cb1347b1e..8c25f56746 100644 --- a/packages/cli/src/commands/backend/build.ts +++ b/packages/cli/src/commands/backend/build.ts @@ -14,10 +14,12 @@ * limitations under the License. */ +import { Command } from 'commander'; import { buildPackage, Output } from '../../lib/builder'; -export default async () => { +export default async (cmd: Command) => { await buildPackage({ outputs: new Set([Output.cjs, Output.types]), + minify: cmd.minify, }); }; diff --git a/packages/cli/src/commands/backend/buildImage.ts b/packages/cli/src/commands/backend/buildImage.ts deleted file mode 100644 index b352e38203..0000000000 --- a/packages/cli/src/commands/backend/buildImage.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2020 The Backstage Authors - * - * 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 { Command } from 'commander'; -import { yellow } from 'chalk'; -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 { parseParallel, PARALLEL_ENV_VAR } from '../../lib/parallel'; - -const PKG_PATH = 'package.json'; - -export default async (cmd: Command) => { - // Skip the preparation steps if we're being asked for help - if (cmd.args.includes('--help')) { - await run('docker', ['image', 'build', '--help']); - return; - } - - console.warn( - yellow(` -The backend:build-image command is deprecated and will be removed in the future. -Please use the backend:bundle command instead along with your own Docker setup. - - https://backstage.io/docs/deployment/docker -`), - ); - - const pkgPath = paths.resolveTarget(PKG_PATH); - const pkg = await fs.readJson(pkgPath); - const appConfigs = await findAppConfigs(); - const npmrc = (await fs.pathExists(paths.resolveTargetRoot('.npmrc'))) - ? ['.npmrc'] - : []; - const tempDistWorkspace = await createDistWorkspace([pkg.name], { - buildDependencies: Boolean(cmd.build), - files: [ - 'package.json', - 'yarn.lock', - ...npmrc, - ...appConfigs, - { src: paths.resolveTarget('Dockerfile'), dest: 'Dockerfile' }, - ], - parallel: parseParallel(process.env[PARALLEL_ENV_VAR]), - skeleton: 'skeleton.tar', - }); - console.log(`Dist workspace ready at ${tempDistWorkspace}`); - - // all args are forwarded to docker build - await run('docker', ['image', 'build', '.', ...cmd.args], { - cwd: tempDistWorkspace, - }); - - await fs.remove(tempDistWorkspace); -}; - -/** - * Find all config files to copy into the image - */ -async function findAppConfigs(): Promise { - const files = []; - - for (const name of await fs.readdir(paths.targetRoot)) { - if (name.startsWith('app-config.') && name.endsWith('.yaml')) { - files.push(name); - } - } - - if (paths.targetRoot !== paths.targetDir) { - const dirPath = relativePath(paths.targetRoot, paths.targetDir); - - for (const name of await fs.readdir(paths.targetDir)) { - if (name.startsWith('app-config.') && name.endsWith('.yaml')) { - files.push(joinPath(dirPath, name)); - } - } - } - - return files; -} diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index a37d5e9ffe..94a8104ff1 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -30,7 +30,10 @@ export function registerCommands(program: CommanderStatic) { .command('app:build') .description('Build an app for a production release') .option('--stats', 'Write bundle stats to output directory') - .option('--lax', 'Do not require environment variables to be set') + .option( + '--lax', + '[DEPRECATED] - Do not require environment variables to be set', + ) .option(...configOption) .action(lazy(() => import('./app/build').then(m => m.default))); @@ -44,6 +47,7 @@ export function registerCommands(program: CommanderStatic) { program .command('backend:build') .description('Build a backend plugin') + .option('--minify', 'Minify the generated code') .action(lazy(() => import('./backend/build').then(m => m.default))); program @@ -55,16 +59,6 @@ export function registerCommands(program: CommanderStatic) { ) .action(lazy(() => import('./backend/bundle').then(m => m.default))); - program - .command('backend:build-image') - .allowUnknownOption(true) - .helpOption(', --backstage-cli-help') // Let docker handle --help - .option('--build', 'Build packages before packing them into the image') - .description( - 'Bundles the package into a docker image. This command is deprecated and will be removed.', - ) - .action(lazy(() => import('./backend/buildImage').then(m => m.default))); - program .command('backend:dev') .description('Start local development server with HMR for the backend') @@ -115,7 +109,7 @@ export function registerCommands(program: CommanderStatic) { program .command('remove-plugin') - .description('Removes plugin in the current repository') + .description('[DEPRECATED] - Removes plugin in the current repository') .action( lazy(() => import('./remove-plugin/removePlugin').then(m => m.default)), ); @@ -123,6 +117,7 @@ export function registerCommands(program: CommanderStatic) { program .command('plugin:build') .description('Build a plugin') + .option('--minify', 'Minify the generated code') .action(lazy(() => import('./plugin/build').then(m => m.default))); program diff --git a/packages/cli/src/commands/plugin/build.ts b/packages/cli/src/commands/plugin/build.ts index 8a63a017a2..9c5e173989 100644 --- a/packages/cli/src/commands/plugin/build.ts +++ b/packages/cli/src/commands/plugin/build.ts @@ -14,10 +14,12 @@ * limitations under the License. */ +import { Command } from 'commander'; import { buildPackage, Output } from '../../lib/builder'; -export default async () => { +export default async (cmd: Command) => { await buildPackage({ outputs: new Set([Output.esm, Output.types]), + minify: cmd.minify, }); }; diff --git a/packages/cli/src/commands/remove-plugin/removePlugin.ts b/packages/cli/src/commands/remove-plugin/removePlugin.ts index 11fdc8bb11..a82bfda36d 100644 --- a/packages/cli/src/commands/remove-plugin/removePlugin.ts +++ b/packages/cli/src/commands/remove-plugin/removePlugin.ts @@ -184,6 +184,12 @@ export const removeReferencesFromAppPackage = async ( }; export default async () => { + console.warn( + chalk.yellow( + '[DEPRECATED] - The remove-plugin command is deprecated and will be removed in the future.', + ), + ); + const questions: Question[] = [ { type: 'input', diff --git a/packages/cli/src/lib/builder/config.ts b/packages/cli/src/lib/builder/config.ts index 3c95a87bdd..ba60e8fea9 100644 --- a/packages/cli/src/lib/builder/config.ts +++ b/packages/cli/src/lib/builder/config.ts @@ -100,6 +100,7 @@ export const makeConfigs = async ( }), esbuild({ target: 'es2019', + minify: options.minify, }), ], }); diff --git a/packages/cli/src/lib/builder/types.ts b/packages/cli/src/lib/builder/types.ts index f75d1b1dda..e88c388013 100644 --- a/packages/cli/src/lib/builder/types.ts +++ b/packages/cli/src/lib/builder/types.ts @@ -22,4 +22,5 @@ export enum Output { export type BuildOptions = { outputs: Set; + minify?: boolean; }; diff --git a/packages/codemods/CHANGELOG.md b/packages/codemods/CHANGELOG.md index bf0711ad6f..dc2cc744f3 100644 --- a/packages/codemods/CHANGELOG.md +++ b/packages/codemods/CHANGELOG.md @@ -1,5 +1,23 @@ # @backstage/codemods +## 0.1.24 + +### Patch Changes + +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/core-plugin-api@0.2.2 + - @backstage/core-app-api@0.1.24 + +## 0.1.23 + +### Patch Changes + +- Updated dependencies + - @backstage/core-app-api@0.1.23 + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.1.22 ### Patch Changes diff --git a/packages/codemods/package.json b/packages/codemods/package.json index bfb8d4d4b3..407c35c724 100644 --- a/packages/codemods/package.json +++ b/packages/codemods/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/codemods", "description": "A collection of codemods for Backstage projects", - "version": "0.1.22", + "version": "0.1.24", "private": false, "publishConfig": { "access": "public", diff --git a/packages/config-loader/CHANGELOG.md b/packages/config-loader/CHANGELOG.md index 00ace6e704..93fb5dd02c 100644 --- a/packages/config-loader/CHANGELOG.md +++ b/packages/config-loader/CHANGELOG.md @@ -1,5 +1,12 @@ # @backstage/config-loader +## 0.8.1 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- 4bea7b81d3: Uses key visibility as fallback in non-object arrays + ## 0.8.0 ### Minor Changes diff --git a/packages/config-loader/package.json b/packages/config-loader/package.json index b4c0350def..78f8da3443 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.8.0", + "version": "0.8.1", "private": false, "publishConfig": { "access": "public", @@ -41,10 +41,10 @@ "json-schema": "^0.4.0", "json-schema-merge-allof": "^0.8.1", "json-schema-traverse": "^1.0.0", + "node-fetch": "^2.6.1", "typescript-json-schema": "^0.51.0", "yaml": "^1.9.2", - "yup": "^0.32.9", - "node-fetch": "2.6.5" + "yup": "^0.32.9" }, "devDependencies": { "@types/jest": "^26.0.7", diff --git a/packages/config-loader/src/lib/schema/filtering.test.ts b/packages/config-loader/src/lib/schema/filtering.test.ts index 0395c7da6a..be07b915ed 100644 --- a/packages/config-loader/src/lib/schema/filtering.test.ts +++ b/packages/config-loader/src/lib/schema/filtering.test.ts @@ -20,6 +20,7 @@ import { filterByVisibility, filterErrorsByVisibility } from './filtering'; const data = { arr: ['f', 'b', 's'], + arrU: ['f', 'b', 't'], objArr: [ { f: 1, b: 2, s: 3 }, { f: 4, b: 5, s: 6 }, @@ -40,6 +41,8 @@ const data = { const visibility = new Map( Object.entries({ + '/arrU': 'frontend', + '/arrU/2': 'backend', '/arr/0': 'frontend', '/arr/1': 'backend', '/arr/2': 'secret', @@ -71,6 +74,9 @@ describe('filterByVisibility', () => { 'arr[0]', 'arr[1]', 'arr[2]', + 'arrU[0]', + 'arrU[1]', + 'arrU[2]', 'objArr[0].f', 'objArr[0].b', 'objArr[0].s', @@ -97,10 +103,12 @@ describe('filterByVisibility', () => { obj: { f: 'a' }, arrF: [], objF: {}, + arrU: ['f', 'b'], }, filteredKeys: [ 'arr[1]', 'arr[2]', + 'arrU[2]', 'objArr[0].b', 'objArr[0].s', 'objArr[1].b', @@ -120,6 +128,7 @@ describe('filterByVisibility', () => { { data: { arr: ['b'], + arrU: ['t'], objArr: [{ b: 2 }, { b: 5 }], obj: { b: {} }, arrF: [{ never: 'here' }], @@ -132,6 +141,8 @@ describe('filterByVisibility', () => { filteredKeys: [ 'arr[0]', 'arr[2]', + 'arrU[0]', + 'arrU[1]', 'objArr[0].f', 'objArr[0].s', 'objArr[1].f', @@ -154,6 +165,9 @@ describe('filterByVisibility', () => { filteredKeys: [ 'arr[0]', 'arr[1]', + 'arrU[0]', + 'arrU[1]', + 'arrU[2]', 'objArr[0].f', 'objArr[0].b', 'objArr[1].f', diff --git a/packages/config-loader/src/lib/schema/filtering.ts b/packages/config-loader/src/lib/schema/filtering.ts index b4226d7dad..b2f39d3cc4 100644 --- a/packages/config-loader/src/lib/schema/filtering.ts +++ b/packages/config-loader/src/lib/schema/filtering.ts @@ -61,11 +61,17 @@ export function filterByVisibility( const arr = new Array(); for (const [index, value] of jsonVal.entries()) { - const out = transform( - value, + let path = visibilityPath; + const hasVisibilityInIndex = visibilityByDataPath.get( `${visibilityPath}/${index}`, - `${filterPath}[${index}]`, ); + + if (hasVisibilityInIndex || typeof value === 'object') { + path = `${visibilityPath}/${index}`; + } + + const out = transform(value, path, `${filterPath}[${index}]`); + if (out !== undefined) { arr.push(out); } diff --git a/packages/core-app-api/CHANGELOG.md b/packages/core-app-api/CHANGELOG.md index b1d590a7bd..ff506f212f 100644 --- a/packages/core-app-api/CHANGELOG.md +++ b/packages/core-app-api/CHANGELOG.md @@ -1,5 +1,96 @@ # @backstage/core-app-api +## 0.1.24 + +### Patch Changes + +- 0e7f256034: Fixed a bug where `useRouteRef` would fail in situations where relative navigation was needed and the app was is mounted on a sub-path. This would typically show up as a failure to navigate to a tab on an entity page. +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + +## 0.1.23 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- 000190de69: The `ApiRegistry` from `@backstage/core-app-api` class has been deprecated and will be removed in a future release. To replace it, we have introduced two new helpers that are exported from `@backstage/test-utils`, namely `TestApiProvider` and `TestApiRegistry`. + + These two new helpers are more tailored for writing tests and development setups, as they allow for partial implementations of each of the APIs. + + When migrating existing code it is typically best to prefer usage of `TestApiProvider` when possible, so for example the following code: + + ```tsx + render( + + {...} + + ) + ``` + + Would be migrated to this: + + ```tsx + render( + + {...} + + ) + ``` + + In cases where the `ApiProvider` is used in a more standalone way, for example to reuse a set of APIs across multiple tests, the `TestApiRegistry` can be used instead. Note that the `TestApiRegistry` only has a single static factory method, `.from()`, and it is slightly different from the existing `.from()` method on `ApiRegistry` in that it doesn't require the API pairs to be wrapped in an outer array. + + Usage that looks like this: + + ```ts + const apis = ApiRegistry.with( + identityApiRef, + mockIdentityApi as unknown as IdentityApi, + ).with(configApiRef, new ConfigReader({})); + ``` + + OR like this: + + ```ts + const apis = ApiRegistry.from([ + [identityApiRef, mockIdentityApi as unknown as IdentityApi], + [configApiRef, new ConfigReader({})], + ]); + ``` + + Would be migrated to this: + + ```ts + const apis = TestApiRegistry.from( + [identityApiRef, mockIdentityApi], + [configApiRef, new ConfigReader({})], + ); + ``` + + If your app is still using the `ApiRegistry` to construct the `apis` for `createApp`, we recommend that you move over to use the new method of supplying API factories instead, using `createApiFactory`. + +- Updated dependencies + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.1.22 ### Patch Changes diff --git a/packages/core-app-api/package.json b/packages/core-app-api/package.json index 96c021b1ee..9ab3e097d1 100644 --- a/packages/core-app-api/package.json +++ b/packages/core-app-api/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/core-app-api", "description": "Core app API used by Backstage apps", - "version": "0.1.22", + "version": "0.1.24", "private": false, "publishConfig": { "access": "public", @@ -30,10 +30,10 @@ }, "dependencies": { "@backstage/app-defaults": "^0.1.1", - "@backstage/core-components": "^0.7.4", + "@backstage/core-components": "^0.7.6", "@backstage/config": "^0.1.11", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@backstage/types": "^0.1.1", "@backstage/version-bridge": "^0.1.0", "@material-ui/core": "^4.12.2", @@ -47,8 +47,8 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/test-utils": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/packages/core-app-api/src/routing/RouteResolver.test.ts b/packages/core-app-api/src/routing/RouteResolver.test.ts index 1b7eb10003..b068bd5e6d 100644 --- a/packages/core-app-api/src/routing/RouteResolver.test.ts +++ b/packages/core-app-api/src/routing/RouteResolver.test.ts @@ -100,23 +100,55 @@ describe('RouteResolver', () => { expect(r.resolve(externalRef4, '/')?.({ x: '6x' })).toBe(undefined); }); - it('should resolve an absolute route and an app base path', () => { + it('should resolve an absolute route and sub route with an app base path', () => { const r = new RouteResolver( - new Map([[ref1, '/my-route']]), - new Map(), - [{ routeRefs: new Set([ref1]), path: '/my-route', ...rest }], + new Map([ + [ref2, '/my-parent/:x'], + [ref1, '/my-route'], + ]), + new Map([[ref1, ref2]]), + [ + { + routeRefs: new Set([ref2]), + path: '/my-parent/:x', + ...rest, + children: [ + MATCH_ALL_ROUTE, + { routeRefs: new Set([ref1]), path: '/my-route', ...rest }, + ], + }, + ], new Map(), '/base', ); - expect(r.resolve(ref1, '/')?.()).toBe('/base/my-route'); - expect(r.resolve(ref2, '/')?.({ x: '1x' })).toBe(undefined); - expect(r.resolve(subRef1, '/')?.()).toBe('/base/my-route/foo'); - expect(r.resolve(subRef2, '/')?.({ a: '2a' })).toBe( - '/base/my-route/foo/2a', + expect(r.resolve(ref1, '/my-parent/1x')?.()).toBe( + '/base/my-parent/1x/my-route', + ); + expect(r.resolve(ref1, '/base/my-parent/1x')?.()).toBe( + '/base/my-parent/1x/my-route', + ); + expect(r.resolve(ref2, '/')?.({ x: '1x' })).toBe('/base/my-parent/1x'); + expect(r.resolve(ref2, '/base')?.({ x: '1x' })).toBe('/base/my-parent/1x'); + expect(r.resolve(ref3, '/')?.({ y: '1y' })).toBe(undefined); + expect(r.resolve(subRef1, '/my-parent/2x')?.()).toBe( + '/base/my-parent/2x/my-route/foo', + ); + expect(r.resolve(subRef1, '/base/my-parent/2x')?.()).toBe( + '/base/my-parent/2x/my-route/foo', + ); + expect(r.resolve(subRef2, '/my-parent/3x')?.({ a: '2a' })).toBe( + '/base/my-parent/3x/my-route/foo/2a', + ); + expect(r.resolve(subRef2, '/base/my-parent/3x')?.({ a: '2a' })).toBe( + '/base/my-parent/3x/my-route/foo/2a', + ); + expect(r.resolve(subRef3, '/')?.({ x: '5x' })).toBe( + '/base/my-parent/5x/bar', + ); + expect(r.resolve(subRef4, '/')?.({ x: '6x', a: '4a' })).toBe( + '/base/my-parent/6x/bar/4a', ); - expect(r.resolve(subRef3, '/')?.({ x: '3x' })).toBe(undefined); - expect(r.resolve(subRef4, '/')?.({ x: '4x', a: '4a' })).toBe(undefined); expect(r.resolve(externalRef1, '/')?.()).toBe(undefined); expect(r.resolve(externalRef2, '/')?.()).toBe(undefined); expect(r.resolve(externalRef3, '/')?.({ x: '5x' })).toBe(undefined); diff --git a/packages/core-app-api/src/routing/RouteResolver.ts b/packages/core-app-api/src/routing/RouteResolver.ts index b5be5f893e..f186b28586 100644 --- a/packages/core-app-api/src/routing/RouteResolver.ts +++ b/packages/core-app-api/src/routing/RouteResolver.ts @@ -207,6 +207,20 @@ export class RouteResolver { return undefined; } + // The location that we get passed in uses the full path, so start by trimming off + // the app base path prefix in case we're running the app on a sub-path. + let relativeSourceLocation: Parameters[1]; + if (typeof sourceLocation === 'string') { + relativeSourceLocation = this.trimPath(sourceLocation); + } else if (sourceLocation.pathname) { + relativeSourceLocation = { + ...sourceLocation, + pathname: this.trimPath(sourceLocation.pathname), + }; + } else { + relativeSourceLocation = sourceLocation; + } + // Next we figure out the base path, which is the combination of the common parent path // between our current location and our target location, as well as the additional path // that is the difference between the parent path and the base of our target location. @@ -214,7 +228,7 @@ export class RouteResolver { this.appBasePath + resolveBasePath( targetRef, - sourceLocation, + relativeSourceLocation, this.routePaths, this.routeParents, this.routeObjects, @@ -225,4 +239,15 @@ export class RouteResolver { }; return routeFunc; } + + private trimPath(targetPath: string) { + if (!targetPath) { + return targetPath; + } + + if (targetPath.startsWith(this.appBasePath)) { + return targetPath.slice(this.appBasePath.length); + } + return targetPath; + } } diff --git a/packages/core-components/CHANGELOG.md b/packages/core-components/CHANGELOG.md index c62ba9e90d..24d460279d 100644 --- a/packages/core-components/CHANGELOG.md +++ b/packages/core-components/CHANGELOG.md @@ -1,5 +1,26 @@ # @backstage/core-components +## 0.7.6 + +### Patch Changes + +- e34f174fc5: Added `` and `` to enable building better sidebars. You can check out the storybook for more inspiration and how to get started. + + Added two new theme props for styling the sidebar too, `navItem.hoverBackground` and `submenu.background`. + +- Updated dependencies + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + +## 0.7.5 + +### Patch Changes + +- 157530187a: Pin sidebar by default for easier navigation +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/core-plugin-api@0.2.1 + ## 0.7.4 ### Patch Changes diff --git a/packages/core-components/api-report.md b/packages/core-components/api-report.md index 0f1e3510ae..c1e021391e 100644 --- a/packages/core-components/api-report.md +++ b/packages/core-components/api-report.md @@ -832,6 +832,7 @@ export const SidebarContext: Context; // @public (undocumented) export type SidebarContextType = { isOpen: boolean; + setOpen: (open: boolean) => void; }; // Warning: (ae-missing-release-tag) "SidebarDivider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -1103,6 +1104,9 @@ export const SidebarDivider: React_2.ComponentType< } >; +// @public +export const SidebarExpandButton: () => JSX.Element | null; + // Warning: (ae-missing-release-tag) "SidebarIntro" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -1977,6 +1981,37 @@ export const SidebarSpacer: React_2.ComponentType< } >; +// @public +export const SidebarSubmenu: ({ + title, + children, +}: PropsWithChildren) => JSX.Element; + +// @public +export const SidebarSubmenuItem: ( + props: SidebarSubmenuItemProps, +) => JSX.Element; + +// @public +export type SidebarSubmenuItemDropdownItem = { + title: string; + to: string; +}; + +// @public +export type SidebarSubmenuItemProps = { + title: string; + to: string; + icon: IconComponent; + dropdownItems?: SidebarSubmenuItemDropdownItem[]; +}; + +// @public +export type SidebarSubmenuProps = { + title?: string; + children: ReactNode; +}; + // Warning: (ae-forgotten-export) The symbol "Props" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "SignInPage" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // diff --git a/packages/core-components/package.json b/packages/core-components/package.json index afa9af0341..80bfe64629 100644 --- a/packages/core-components/package.json +++ b/packages/core-components/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/core-components", "description": "Core components used by Backstage plugins and apps", - "version": "0.7.4", + "version": "0.7.6", "private": false, "publishConfig": { "access": "public", @@ -30,9 +30,9 @@ }, "dependencies": { "@backstage/config": "^0.1.11", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/errors": "^0.1.4", - "@backstage/theme": "^0.2.13", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/errors": "^0.1.5", + "@backstage/theme": "^0.2.14", "@material-table/core": "^3.1.0", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", @@ -46,6 +46,7 @@ "d3-shape": "^3.0.0", "d3-zoom": "^3.0.0", "dagre": "^0.8.5", + "history": "^5.0.0", "immer": "^9.0.1", "lodash": "^4.17.21", "pluralize": "^8.0.0", @@ -67,9 +68,9 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/core-app-api": "^0.1.21", - "@backstage/cli": "^0.9.0", - "@backstage/test-utils": "^0.1.22", + "@backstage/core-app-api": "^0.1.24", + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/packages/core-components/src/layout/Sidebar/Bar.test.tsx b/packages/core-components/src/layout/Sidebar/Bar.test.tsx new file mode 100644 index 0000000000..d288aa94c5 --- /dev/null +++ b/packages/core-components/src/layout/Sidebar/Bar.test.tsx @@ -0,0 +1,108 @@ +/* + * Copyright 2020 The Backstage Authors + * + * 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 { renderInTestApp } from '@backstage/test-utils'; +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import BuildRoundedIcon from '@material-ui/icons/BuildRounded'; +import CreateComponentIcon from '@material-ui/icons/AddCircleOutline'; +import MenuBookIcon from '@material-ui/icons/MenuBook'; +import AcUnitIcon from '@material-ui/icons/AcUnit'; +import { Sidebar, SidebarExpandButton } from './Bar'; +import { SidebarItem, SidebarSearchField } from './Items'; +import { SidebarSubmenuItem } from './SidebarSubmenuItem'; +import { SidebarSubmenu } from './SidebarSubmenu'; +import { SidebarPinStateContext } from '.'; + +async function renderScalableSidebar() { + await renderInTestApp( + {} }} + > + + {}} to="/search" /> + {}} text="Catalog"> + + + + + + + + + , + ); +} + +describe('Sidebar', () => { + beforeEach(async () => { + await renderScalableSidebar(); + }); + + describe('Click to Expand', () => { + it('Sidebar should show expanded items when expand button is clicked', async () => { + userEvent.click(screen.getByTestId('sidebar-expand-button')); + expect(await screen.findByText('Create...')).toBeInTheDocument(); + }); + it('Sidebar should not show expanded items when hovered on', async () => { + userEvent.hover(screen.getByTestId('sidebar-root')); + expect(screen.queryByText('Create...')).not.toBeInTheDocument(); + }); + }); + describe('Submenu Items', () => { + it('Extended sidebar with submenu content hidden by default', async () => { + expect(screen.queryByText('Tools')).not.toBeInTheDocument(); + expect(screen.queryByText('Misc')).not.toBeInTheDocument(); + }); + + it('Extended sidebar with submenu content visible when hover over submenu items', async () => { + userEvent.hover(screen.getByTestId('item-with-submenu')); + expect(await screen.findByText('Tools')).toBeInTheDocument(); + expect(await screen.findByText('Misc')).toBeInTheDocument(); + }); + + it('Multicategory item in submenu shows drop down on click', async () => { + userEvent.hover(screen.getByTestId('item-with-submenu')); + userEvent.click(screen.getByText('Misc')); + expect(screen.getByText('dropdown item 1')).toBeInTheDocument(); + expect(screen.getByText('dropdown item 2')).toBeInTheDocument(); + }); + + it('Dropdown item in submenu renders a link when `to` value is provided', async () => { + userEvent.hover(screen.getByTestId('item-with-submenu')); + userEvent.click(screen.getByText('Misc')); + expect(screen.getByText('dropdown item 1').closest('a')).toHaveAttribute( + 'href', + '/dropdownitemlink', + ); + }); + }); +}); diff --git a/packages/core-components/src/layout/Sidebar/Bar.tsx b/packages/core-components/src/layout/Sidebar/Bar.tsx index e6fa3820ad..775c537695 100644 --- a/packages/core-components/src/layout/Sidebar/Bar.tsx +++ b/packages/core-components/src/layout/Sidebar/Bar.tsx @@ -17,10 +17,12 @@ import { makeStyles } from '@material-ui/core/styles'; import useMediaQuery from '@material-ui/core/useMediaQuery'; import clsx from 'clsx'; -import React, { useRef, useState, useContext, PropsWithChildren } from 'react'; +import React, { useState, useContext, PropsWithChildren, useRef } from 'react'; import { sidebarConfig, SidebarContext } from './config'; import { BackstageTheme } from '@backstage/theme'; import { SidebarPinStateContext } from './Page'; +import DoubleArrowRight from './icons/DoubleArrowRight'; +import DoubleArrowLeft from './icons/DoubleArrowLeft'; export type SidebarClassKey = 'root' | 'drawer' | 'drawerOpen'; @@ -46,7 +48,6 @@ const useStyles = makeStyles( msOverflowStyle: 'none', scrollbarWidth: 'none', width: sidebarConfig.drawerWidthClosed, - borderRight: `1px solid #383838`, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.shortest, @@ -58,6 +59,19 @@ const useStyles = makeStyles( display: 'none', }, }, + expandButton: { + background: 'none', + border: 'none', + color: theme.palette.navigation.color, + width: '100%', + cursor: 'pointer', + position: 'relative', + height: 48, + }, + arrows: { + position: 'absolute', + right: 10, + }, drawerOpen: { width: sidebarConfig.drawerWidthOpen, transition: theme.transitions.create('width', { @@ -78,10 +92,12 @@ enum State { type Props = { openDelayMs?: number; closeDelayMs?: number; + disableExpandOnHover?: boolean; }; export function Sidebar(props: PropsWithChildren) { const { + disableExpandOnHover = false, openDelayMs = sidebarConfig.defaultOpenDelayMs, closeDelayMs = sidebarConfig.defaultCloseDelayMs, children, @@ -132,18 +148,27 @@ export function Sidebar(props: PropsWithChildren) { const isOpen = (state === State.Open && !isSmallScreen) || isPinned; + const setOpen = (open: boolean) => { + if (open) { + handleOpen(); + } else { + handleClose(); + } + }; + return (
{} : handleOpen} + onFocus={disableExpandOnHover ? () => {} : handleOpen} + onMouseLeave={disableExpandOnHover ? () => {} : handleClose} + onBlur={disableExpandOnHover ? () => {} : handleClose} >
) {
); } + +/** + * A button which allows you to expand the sidebar when clicked. + * Use optionally to replace sidebar's expand-on-hover feature with expand-on-click. + * + * @public + */ +export const SidebarExpandButton = () => { + const classes = useStyles(); + const { isOpen, setOpen } = useContext(SidebarContext); + const { isPinned } = useContext(SidebarPinStateContext); + const isSmallScreen = useMediaQuery(theme => + theme.breakpoints.down('md'), + ); + + const handleClick = () => { + setOpen(!isOpen); + }; + + if (isPinned || isSmallScreen) { + return null; + } + + return ( + + ); +}; diff --git a/packages/core-components/src/layout/Sidebar/Items.test.tsx b/packages/core-components/src/layout/Sidebar/Items.test.tsx index 123c30ceae..f4d699d09c 100644 --- a/packages/core-components/src/layout/Sidebar/Items.test.tsx +++ b/packages/core-components/src/layout/Sidebar/Items.test.tsx @@ -20,7 +20,7 @@ import { createEvent, fireEvent, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import HomeIcon from '@material-ui/icons/Home'; import CreateComponentIcon from '@material-ui/icons/AddCircleOutline'; -import { Sidebar } from './Bar'; +import { Sidebar, SidebarExpandButton } from './Bar'; import { SidebarItem, SidebarSearchField } from './Items'; import { renderHook } from '@testing-library/react-hooks'; import { hexToRgb, makeStyles } from '@material-ui/core/styles'; @@ -44,6 +44,7 @@ async function renderSidebar() { text="Create..." className={result.current.spotlight} /> + , ); userEvent.hover(screen.getByTestId('sidebar-root')); diff --git a/packages/core-components/src/layout/Sidebar/Items.tsx b/packages/core-components/src/layout/Sidebar/Items.tsx index 3f15ae4ea6..903053eda4 100644 --- a/packages/core-components/src/layout/Sidebar/Items.tsx +++ b/packages/core-components/src/layout/Sidebar/Items.tsx @@ -14,18 +14,21 @@ * limitations under the License. */ -import { IconComponent } from '@backstage/core-plugin-api'; +import { IconComponent, useElementFilter } from '@backstage/core-plugin-api'; import { BackstageTheme } from '@backstage/theme'; import { makeStyles, styled, Theme } from '@material-ui/core/styles'; import Badge from '@material-ui/core/Badge'; import TextField from '@material-ui/core/TextField'; import Typography from '@material-ui/core/Typography'; import { CreateCSSProperties } from '@material-ui/core/styles/withStyles'; +import ArrowRightIcon from '@material-ui/icons/ArrowRight'; import SearchIcon from '@material-ui/icons/Search'; import clsx from 'clsx'; import React, { + Children, forwardRef, KeyboardEventHandler, + PropsWithChildren, ReactNode, useContext, useState, @@ -33,10 +36,16 @@ import React, { import { Link, NavLinkProps, + resolvePath, useLocation, useResolvedPath, } from 'react-router-dom'; -import { sidebarConfig, SidebarContext } from './config'; +import { + sidebarConfig, + SidebarContext, + SidebarItemWithSubmenuContext, +} from './config'; +import { SidebarSubmenu } from './SidebarSubmenu'; export type SidebarItemClassKey = | 'root' @@ -85,6 +94,16 @@ const useStyles = makeStyles( open: { width: drawerWidthOpen, }, + highlightable: { + '&:hover': { + background: + theme.palette.navigation.navItem?.hoverBackground ?? '#404040', + }, + }, + highlighted: { + background: + theme.palette.navigation.navItem?.hoverBackground ?? '#404040', + }, label: { // XXX (@koroeskohr): I can't seem to achieve the desired font-weight from the designs fontWeight: 'bold', @@ -123,13 +142,24 @@ const useStyles = makeStyles( textAlign: 'center', marginRight: theme.spacing(1), }, + closedItemIcon: { + width: '100%', + justifyContent: 'center', + }, + submenuArrow: { + position: 'absolute', + right: 0, + }, selected: { '&$root': { borderLeft: `solid ${selectedIndicatorWidth}px ${theme.palette.navigation.indicator}`, color: theme.palette.navigation.selectedColor, }, '&$closed': { - width: drawerWidthClosed - selectedIndicatorWidth, + width: drawerWidthClosed, + }, + '& $closedItemIcon': { + paddingRight: selectedIndicatorWidth, }, '& $iconContainer': { marginLeft: -selectedIndicatorWidth, @@ -140,16 +170,124 @@ const useStyles = makeStyles( { name: 'BackstageSidebarItem' }, ); +function isSidebarItemWithSubmenuActive( + submenu: ReactNode, + locationPathname: string, +) { + // Item is active if any of submenu items have active paths + const toPathnames: string[] = []; + let isActive = false; + let submenuItems: ReactNode; + Children.forEach(submenu, element => { + if (!React.isValidElement(element)) return; + submenuItems = element.props.children; + }); + Children.forEach(submenuItems, element => { + if (!React.isValidElement(element)) return; + if (element.props.dropdownItems) { + element.props.dropdownItems.map((item: { to: string }) => + toPathnames.push(item.to), + ); + } else if (element.props.to) { + toPathnames.push(element.props.to); + } + }); + isActive = toPathnames.some(to => { + const toPathname = resolvePath(to); + return locationPathname === toPathname.pathname; + }); + return isActive; +} + +const SidebarItemWithSubmenu = ({ + text, + hasNotifications = false, + icon: Icon, + children, +}: PropsWithChildren) => { + const classes = useStyles(); + const [isHoveredOn, setIsHoveredOn] = useState(false); + const { pathname: locationPathname } = useLocation(); + const isActive = isSidebarItemWithSubmenuActive(children, locationPathname); + + const handleMouseEnter = () => { + setIsHoveredOn(true); + }; + const handleMouseLeave = () => { + setIsHoveredOn(false); + }; + + const { isOpen } = useContext(SidebarContext); + const itemIcon = ( + + + + ); + const openContent = ( + <> +
+ {itemIcon} +
+ {text && ( + + {text} + + )} +
{}
+ + ); + const closedContent = itemIcon; + + return ( + +
+
+ {isOpen ? openContent : closedContent} + {!isHoveredOn && ( + + )} +
+ {isHoveredOn && children} +
+
+ ); +}; + type SidebarItemBaseProps = { icon: IconComponent; text?: string; hasNotifications?: boolean; - children?: ReactNode; + disableHighlight?: boolean; className?: string; }; type SidebarItemButtonProps = SidebarItemBaseProps & { onClick: (ev: React.MouseEvent) => void; + children?: ReactNode; }; type SidebarItemLinkProps = SidebarItemBaseProps & { @@ -157,7 +295,21 @@ type SidebarItemLinkProps = SidebarItemBaseProps & { onClick?: (ev: React.MouseEvent) => void; } & NavLinkProps; -type SidebarItemProps = SidebarItemButtonProps | SidebarItemLinkProps; +type SidebarItemWithSubmenuProps = SidebarItemBaseProps & { + to?: string; + onClick?: (ev: React.MouseEvent) => void; + children: ReactNode; +}; + +/** + * SidebarItem with 'to' property will be a clickable link. + * SidebarItem with 'onClick' property and without 'to' property will be a clickable button. + * SidebarItem which wraps a SidebarSubmenu will be a clickable button which opens a submenu. + */ +type SidebarItemProps = + | SidebarItemLinkProps + | SidebarItemButtonProps + | SidebarItemWithSubmenuProps; function isButtonItem( props: SidebarItemProps, @@ -218,6 +370,7 @@ export const SidebarItem = forwardRef((props, ref) => { icon: Icon, text, hasNotifications = false, + disableHighlight = false, onClick, children, className, @@ -235,6 +388,7 @@ export const SidebarItem = forwardRef((props, ref) => { variant="dot" overlap="circular" invisible={!hasNotifications} + className={clsx({ [classes.closedItemIcon]: !isOpen })} > @@ -265,9 +419,43 @@ export const SidebarItem = forwardRef((props, ref) => { classes.root, isOpen ? classes.open : classes.closed, isButtonItem(props) && classes.buttonItem, + { [classes.highlightable]: !disableHighlight }, ), }; + let hasSubmenu = false; + let submenu: ReactNode; + const componentType = ( + + <> + + ).type; + // Filter children for SidebarSubmenu components + const submenus = useElementFilter(children, elements => + elements.getElements().filter(child => child.type === componentType), + ); + // Error thrown if more than one SidebarSubmenu in a SidebarItem + if (submenus.length > 1) { + throw new Error( + 'Cannot render more than one SidebarSubmenu inside a SidebarItem', + ); + } else if (submenus.length === 1) { + hasSubmenu = true; + submenu = submenus[0]; + } + + if (hasSubmenu) { + return ( + + {submenu} + + ); + } + if (isButtonItem(props)) { return ( + {dropdownItems && showDropDown && ( +
+ {dropdownItems.map((object, key) => ( + + + {object.title} + + + ))} +
+ )} +
+ ); + } + + return ( +
+ + + + {title} + + +
+ ); +}; diff --git a/packages/core-components/src/layout/Sidebar/config.ts b/packages/core-components/src/layout/Sidebar/config.ts index d2a690e38f..dbcdb7d788 100644 --- a/packages/core-components/src/layout/Sidebar/config.ts +++ b/packages/core-components/src/layout/Sidebar/config.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { createContext } from 'react'; +import { createContext, Dispatch, SetStateAction } from 'react'; const drawerWidthClosed = 72; const iconPadding = 24; @@ -37,13 +37,43 @@ export const sidebarConfig = { userBadgeDiameter: drawerWidthClosed - userBadgePadding * 2, }; +export const submenuConfig = { + drawerWidthClosed: 0, + drawerWidthOpen: 202, + // As per NN/g's guidance on timing for exposing hidden content + // See https://www.nngroup.com/articles/timing-exposing-content/ + defaultOpenDelayMs: 100, + defaultCloseDelayMs: 0, + defaultFadeDuration: 200, + logoHeight: 32, + iconContainerWidth: drawerWidthClosed, + iconSize: drawerWidthClosed - iconPadding * 2, + iconPadding, + selectedIndicatorWidth: 3, + userBadgePadding, + userBadgeDiameter: drawerWidthClosed - userBadgePadding * 2, +}; + export const SIDEBAR_INTRO_LOCAL_STORAGE = '@backstage/core/sidebar-intro-dismissed'; export type SidebarContextType = { isOpen: boolean; + setOpen: (open: boolean) => void; }; export const SidebarContext = createContext({ isOpen: false, + setOpen: _open => {}, }); + +export type SidebarItemWithSubmenuContextType = { + isHoveredOn: boolean; + setIsHoveredOn: Dispatch>; +}; + +export const SidebarItemWithSubmenuContext = + createContext({ + isHoveredOn: false, + setIsHoveredOn: () => {}, + }); diff --git a/packages/core-components/src/layout/Sidebar/icons/DoubleArrowLeft.tsx b/packages/core-components/src/layout/Sidebar/icons/DoubleArrowLeft.tsx new file mode 100644 index 0000000000..eb487940a8 --- /dev/null +++ b/packages/core-components/src/layout/Sidebar/icons/DoubleArrowLeft.tsx @@ -0,0 +1,48 @@ +/* + * Copyright 2020 The Backstage Authors + * + * 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 { makeStyles } from '@material-ui/core/styles'; +import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos'; + +const useStyles = makeStyles({ + iconContainer: { + display: 'flex', + position: 'relative', + width: '100%', + }, + arrow1: { + right: '6px', + position: 'absolute', + }, +}); + +const DoubleArrowLeft = () => { + const classes = useStyles(); + + return ( +
+
+ +
+
+ +
+
+ ); +}; + +export default DoubleArrowLeft; diff --git a/packages/core-components/src/layout/Sidebar/icons/DoubleArrowRight.tsx b/packages/core-components/src/layout/Sidebar/icons/DoubleArrowRight.tsx new file mode 100644 index 0000000000..e1e9b9476d --- /dev/null +++ b/packages/core-components/src/layout/Sidebar/icons/DoubleArrowRight.tsx @@ -0,0 +1,48 @@ +/* + * Copyright 2020 The Backstage Authors + * + * 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 { makeStyles } from '@material-ui/core/styles'; +import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos'; + +const useStyles = makeStyles({ + iconContainer: { + display: 'flex', + position: 'relative', + width: '100%', + }, + arrow1: { + right: '6px', + position: 'absolute', + }, +}); + +const DoubleArrowRight = () => { + const classes = useStyles(); + + return ( +
+
+ +
+
+ +
+
+ ); +}; + +export default DoubleArrowRight; diff --git a/packages/core-components/src/layout/Sidebar/index.ts b/packages/core-components/src/layout/Sidebar/index.ts index 067a9bf2eb..79a86023ee 100644 --- a/packages/core-components/src/layout/Sidebar/index.ts +++ b/packages/core-components/src/layout/Sidebar/index.ts @@ -14,7 +14,14 @@ * limitations under the License. */ -export { Sidebar } from './Bar'; +export { Sidebar, SidebarExpandButton } from './Bar'; +export { SidebarSubmenuItem } from './SidebarSubmenuItem'; +export { SidebarSubmenu } from './SidebarSubmenu'; +export type { SidebarSubmenuProps } from './SidebarSubmenu'; +export type { + SidebarSubmenuItemProps, + SidebarSubmenuItemDropdownItem, +} from './SidebarSubmenuItem'; export type { SidebarClassKey } from './Bar'; export { SidebarPage, SidebarPinStateContext } from './Page'; export type { SidebarPinStateContextType, SidebarPageClassKey } from './Page'; diff --git a/packages/core-plugin-api/CHANGELOG.md b/packages/core-plugin-api/CHANGELOG.md index a8d35e5a14..e0050f9f13 100644 --- a/packages/core-plugin-api/CHANGELOG.md +++ b/packages/core-plugin-api/CHANGELOG.md @@ -1,5 +1,22 @@ # @backstage/core-plugin-api +## 0.2.2 + +### Patch Changes + +- b291d0ed7e: Tweaked the logged deprecation warning for `createRouteRef` to hopefully make it more clear. +- bacb94ea8f: Documented the options of each of the extension creation functions. +- Updated dependencies + - @backstage/theme@0.2.14 + +## 0.2.1 + +### Patch Changes + +- 950b36393c: Deprecated `register` option of `createPlugin` and the `outputs` methods of the plugin instance. + + Introduces the `featureFlags` property to define your feature flags instead. + ## 0.2.0 ### Minor Changes diff --git a/packages/core-plugin-api/package.json b/packages/core-plugin-api/package.json index e5b4572dff..3e07207c9d 100644 --- a/packages/core-plugin-api/package.json +++ b/packages/core-plugin-api/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/core-plugin-api", "description": "Core API used by Backstage plugins", - "version": "0.2.0", + "version": "0.2.2", "private": false, "publishConfig": { "access": "public", @@ -30,7 +30,7 @@ }, "dependencies": { "@backstage/config": "^0.1.11", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@backstage/types": "^0.1.1", "@backstage/version-bridge": "^0.1.0", "@material-ui/core": "^4.12.2", @@ -43,9 +43,9 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.21", - "@backstage/test-utils": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/packages/core-plugin-api/src/extensions/extensions.tsx b/packages/core-plugin-api/src/extensions/extensions.tsx index ca5ada8478..19da082ee1 100644 --- a/packages/core-plugin-api/src/extensions/extensions.tsx +++ b/packages/core-plugin-api/src/extensions/extensions.tsx @@ -51,8 +51,27 @@ export type ComponentLoader = export function createRoutableExtension< T extends (props: any) => JSX.Element | null, >(options: { + /** + * A loader for the component that is rendered by this extension. + */ component: () => Promise; + + /** + * The mount point to bind this routable extension to. + * + * If this extension is placed somewhere in the app element tree of a Backstage + * app, callers will be able to route to this extensions by calling, + * `useRouteRef` with this mount point. + */ mountPoint: RouteRef; + + /** + * The name of this extension that will represent it at runtime. It is for example + * used to identify this extension in analytics data. + * + * If possible the name should always be the same as the name of the exported + * variable for this extension. + */ name?: string; }): Extension { const { component, mountPoint, name } = options; @@ -127,7 +146,21 @@ export function createRoutableExtension< */ export function createComponentExtension< T extends (props: any) => JSX.Element | null, ->(options: { component: ComponentLoader; name?: string }): Extension { +>(options: { + /** + * A loader or synchronously supplied component that is rendered by this extension. + */ + component: ComponentLoader; + + /** + * The name of this extension that will represent it at runtime. It is for example + * used to identify this extension in analytics data. + * + * If possible the name should always be the same as the name of the exported + * variable for this extension. + */ + name?: string; +}): Extension { const { component, name } = options; return createReactExtension({ component, name }); } @@ -148,8 +181,23 @@ export function createComponentExtension< export function createReactExtension< T extends (props: any) => JSX.Element | null, >(options: { + /** + * A loader or synchronously supplied component that is rendered by this extension. + */ component: ComponentLoader; + + /** + * Additional component data that is attached to the top-level extension component. + */ data?: Record; + + /** + * The name of this extension that will represent it at runtime. It is for example + * used to identify this extension in analytics data. + * + * If possible the name should always be the same as the name of the exported + * variable for this extension. + */ name?: string; }): Extension { const { data = {}, name } = options; diff --git a/packages/core-plugin-api/src/routing/RouteRef.ts b/packages/core-plugin-api/src/routing/RouteRef.ts index 26e63c8f3a..8bd3d604f6 100644 --- a/packages/core-plugin-api/src/routing/RouteRef.ts +++ b/packages/core-plugin-api/src/routing/RouteRef.ts @@ -59,21 +59,21 @@ export class RouteRefImpl if (config.path) { // eslint-disable-next-line no-console console.warn( - `[core-plugin-api] - routeRefs no longer decide their own path, please remove the path for ${this.toString()}. This will be removed in upcoming versions.`, + `DEPRECATION WARNING: Passing a path to createRouteRef is deprecated, please remove the path for ${this}.`, ); } if (config.icon) { // eslint-disable-next-line no-console console.warn( - `[core-plugin-api] - routeRefs no longer decide their own icon, please remove the icon for ${this.toString()}. This will be removed in upcoming versions.`, + `DEPRECATION WARNING: Passing an icon to createRouteRef is deprecated, please remove the icon for ${this}.`, ); } if (config.title) { // eslint-disable-next-line no-console console.warn( - `[core-plugin-api] - routeRefs no longer decide their own title, please remove the title for ${this.toString()}. This will be removed in upcoming versions.`, + `DEPRECATION WARNING: Passing a title to createRouteRef is deprecated, please remove the title for ${this}.`, ); } } diff --git a/packages/create-app/CHANGELOG.md b/packages/create-app/CHANGELOG.md index af1fd58ead..599fdf78f3 100644 --- a/packages/create-app/CHANGELOG.md +++ b/packages/create-app/CHANGELOG.md @@ -1,5 +1,94 @@ # @backstage/create-app +## 0.4.6 + +### Patch Changes + +- 24d2ce03f3: Search Modal now relies on the Search Context to access state and state setter. If you use the SidebarSearchModal as described in the [getting started documentation](https://backstage.io/docs/features/search/getting-started#using-the-search-modal), make sure to update your code with the SearchContextProvider. + + ```diff + export const Root = ({ children }: PropsWithChildren<{}>) => ( + + + + - + + + + + + + + ... + ``` + +- 905dd952ac: Incorporate usage of the tokenManager into the backend created using `create-app`. + + In existing backends, update the `PluginEnvironment` to include a `tokenManager`: + + ```diff + // packages/backend/src/types.ts + + ... + import { + ... + + TokenManager, + } from '@backstage/backend-common'; + + export type PluginEnvironment = { + ... + + tokenManager: TokenManager; + }; + ``` + + Then, create a `ServerTokenManager`. This can either be a `noop` that requires no secret and validates all requests by default, or one that uses a secret from your `app-config.yaml` to generate and validate tokens. + + ```diff + // packages/backend/src/index.ts + + ... + import { + ... + + ServerTokenManager, + } from '@backstage/backend-common'; + ... + + function makeCreateEnv(config: Config) { + ... + // CHOOSE ONE + // TokenManager not requiring a secret + + const tokenManager = ServerTokenManager.noop(); + // OR TokenManager requiring a secret + + const tokenManager = ServerTokenManager.fromConfig(config); + + ... + return (plugin: string): PluginEnvironment => { + ... + - return { logger, cache, database, config, reader, discovery }; + + return { logger, cache, database, config, reader, discovery, tokenManager }; + }; + } + ``` + +## 0.4.5 + +### Patch Changes + +- dcaeaac174: Cleaned out the `peerDependencies` in the published version of the package, making it much quicker to run `npx @backstage/create-app` as it no longer needs to install a long list of unnecessary. +- a5a5d7e1f1: DefaultTechDocsCollator is now included in the search backend, and the Search Page updated with the SearchType component that includes the techdocs type +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- 42ebbc18c0: Bump gitbeaker to the latest version + ## 0.4.4 ### Patch Changes diff --git a/packages/create-app/README.md b/packages/create-app/README.md index 9f86cdb448..d5b5039d4e 100644 --- a/packages/create-app/README.md +++ b/packages/create-app/README.md @@ -22,4 +22,4 @@ yarn backstage-create-app ## Documentation - [Backstage Readme](https://github.com/backstage/backstage/blob/master/README.md) -- [Backstage Documentation](https://github.com/backstage/backstage/blob/master/docs/README.md) +- [Backstage Documentation](https://backstage.io/docs/) diff --git a/packages/create-app/package.json b/packages/create-app/package.json index d5ee616ff5..b2fa1a1acf 100644 --- a/packages/create-app/package.json +++ b/packages/create-app/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/create-app", "description": "A CLI that helps you create your own Backstage app", - "version": "0.4.4", + "version": "0.4.6", "private": false, "publishConfig": { "access": "public" @@ -25,6 +25,8 @@ "lint": "backstage-cli lint", "test": "backstage-cli test", "clean": "backstage-cli clean", + "prepack": "node scripts/prepack.js", + "postpack": "node scripts/postpack.js", "start": "nodemon --" }, "dependencies": { @@ -40,6 +42,7 @@ "devDependencies": { "@types/fs-extra": "^9.0.1", "@types/inquirer": "^7.3.1", + "@types/node": "^14.14.32", "@types/recursive-readdir": "^2.2.0", "mock-fs": "^5.1.1", "ts-node": "^10.0.0" diff --git a/packages/create-app/scripts/postpack.js b/packages/create-app/scripts/postpack.js new file mode 100644 index 0000000000..f13db11e76 --- /dev/null +++ b/packages/create-app/scripts/postpack.js @@ -0,0 +1,37 @@ +#!/usr/bin/env node +/* + * Copyright 2021 The Backstage Authors + * + * 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-syntax */ + +const fs = require('fs-extra'); +const path = require('path'); + +async function main() { + const pkgPath = path.resolve(__dirname, '../package.json'); + const pkgBackupPath = path.resolve(__dirname, '../package.json-prepack'); + + try { + await fs.move(pkgBackupPath, pkgPath, { overwrite: true }); + } catch (err) { + console.error(`Failed to restore package.json during postpack, ${err}`); + } +} + +main().catch(err => { + console.error(err.stack); + process.exit(1); +}); diff --git a/packages/create-app/scripts/prepack.js b/packages/create-app/scripts/prepack.js new file mode 100644 index 0000000000..2caf865280 --- /dev/null +++ b/packages/create-app/scripts/prepack.js @@ -0,0 +1,36 @@ +#!/usr/bin/env node +/* + * Copyright 2021 The Backstage Authors + * + * 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-syntax */ + +const fs = require('fs-extra'); +const path = require('path'); + +async function main() { + const pkgPath = path.resolve(__dirname, '../package.json'); + const pkgBackupPath = path.resolve(__dirname, '../package.json-prepack'); + + const pkg = await fs.readJson(pkgPath); + await fs.writeJson(pkgBackupPath, pkg, { encoding: 'utf8', spaces: 2 }); + delete pkg.peerDependencies; + await fs.writeJson(pkgPath, pkg, { encoding: 'utf8', spaces: 2 }); +} + +main().catch(err => { + console.error(err.stack); + process.exit(1); +}); diff --git a/packages/create-app/src/createApp.ts b/packages/create-app/src/createApp.ts index d301792380..ac42ed0ff3 100644 --- a/packages/create-app/src/createApp.ts +++ b/packages/create-app/src/createApp.ts @@ -65,7 +65,7 @@ export default async (cmd: Command, version: string): Promise => { const templateDir = paths.resolveOwn('templates/default-app'); const tempDir = resolvePath(os.tmpdir(), answers.name); - // Use `--path` argument as applicaiton directory when specified, otherwise + // Use `--path` argument as application directory when specified, otherwise // create a directory using `answers.name` const appDir = cmd.path ? resolvePath(paths.targetDir, cmd.path) diff --git a/packages/create-app/templates/default-app/app-config.yaml.hbs b/packages/create-app/templates/default-app/app-config.yaml.hbs index ab4858edd6..c804b4b561 100644 --- a/packages/create-app/templates/default-app/app-config.yaml.hbs +++ b/packages/create-app/templates/default-app/app-config.yaml.hbs @@ -6,6 +6,11 @@ organization: name: My Company backend: + # Used for enabling authentication, secret is shared by all backend plugins + # See backend-to-backend-auth.md in the docs for information on the format + # auth: + # keys: + # - secret: ${BACKEND_SECRET} baseUrl: http://localhost:7007 listen: port: 7007 @@ -72,9 +77,7 @@ auth: providers: {} scaffolder: - github: - token: ${GITHUB_TOKEN} - visibility: public # or 'internal' or 'private' + # see https://backstage.io/docs/features/software-templates/configuration for software template options catalog: rules: diff --git a/packages/create-app/templates/default-app/package.json.hbs b/packages/create-app/templates/default-app/package.json.hbs index bdae71d9e3..b0747c4454 100644 --- a/packages/create-app/templates/default-app/package.json.hbs +++ b/packages/create-app/templates/default-app/package.json.hbs @@ -31,7 +31,7 @@ }, "devDependencies": { "@backstage/cli": "^{{version '@backstage/cli'}}", - "@spotify/prettier-config": "^11.0.0", + "@spotify/prettier-config": "^12.0.0", "concurrently": "^6.0.0", "lerna": "^4.0.0", "prettier": "^2.3.2" diff --git a/packages/create-app/templates/default-app/packages/app/package.json.hbs b/packages/create-app/templates/default-app/packages/app/package.json.hbs index 9e15608a01..68848d2de9 100644 --- a/packages/create-app/templates/default-app/packages/app/package.json.hbs +++ b/packages/create-app/templates/default-app/packages/app/package.json.hbs @@ -22,7 +22,6 @@ "@backstage/plugin-tech-radar": "^{{version '@backstage/plugin-tech-radar'}}", "@backstage/plugin-techdocs": "^{{version '@backstage/plugin-techdocs'}}", "@backstage/plugin-user-settings": "^{{version '@backstage/plugin-user-settings'}}", - "@backstage/test-utils": "^{{version '@backstage/test-utils'}}", "@backstage/theme": "^{{version '@backstage/theme'}}", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", @@ -34,6 +33,7 @@ "react-use": "^15.3.3" }, "devDependencies": { + "@backstage/test-utils": "^{{version '@backstage/test-utils'}}", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", @@ -48,11 +48,11 @@ "scripts": { "start": "backstage-cli app:serve", "build": "backstage-cli app:build", - "test": "backstage-cli test", - "lint": "backstage-cli lint", "clean": "backstage-cli clean", + "test": "backstage-cli test", "test:e2e": "cross-env PORT=3001 start-server-and-test start http://localhost:3001 cy:dev", "test:e2e:ci": "cross-env PORT=3001 start-server-and-test start http://localhost:3001 cy:run", + "lint": "backstage-cli lint", "cy:dev": "cypress open", "cy:run": "cypress run" }, diff --git a/packages/create-app/templates/default-app/packages/app/src/components/Root/Root.tsx b/packages/create-app/templates/default-app/packages/app/src/components/Root/Root.tsx index ec59b0b116..b4fa04f1fc 100644 --- a/packages/create-app/templates/default-app/packages/app/src/components/Root/Root.tsx +++ b/packages/create-app/templates/default-app/packages/app/src/components/Root/Root.tsx @@ -25,7 +25,10 @@ import LogoFull from './LogoFull'; import LogoIcon from './LogoIcon'; import { NavLink } from 'react-router-dom'; import { Settings as SidebarSettings } from '@backstage/plugin-user-settings'; -import { SidebarSearchModal } from '@backstage/plugin-search'; +import { + SidebarSearchModal, + SearchContextProvider, +} from '@backstage/plugin-search'; import { Sidebar, SidebarPage, @@ -74,7 +77,9 @@ export const Root = ({ children }: PropsWithChildren<{}>) => ( - + + + {/* Global nav, not org-specific */} diff --git a/packages/create-app/templates/default-app/packages/backend/src/index.ts b/packages/create-app/templates/default-app/packages/backend/src/index.ts index f2b14b23f9..3f12122a3f 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/index.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/index.ts @@ -17,6 +17,7 @@ import { DatabaseManager, SingleHostDiscovery, UrlReaders, + ServerTokenManager, } from '@backstage/backend-common'; import { Config } from '@backstage/config'; import app from './plugins/app'; @@ -37,12 +38,13 @@ function makeCreateEnv(config: Config) { const cacheManager = CacheManager.fromConfig(config); const databaseManager = DatabaseManager.fromConfig(config); + const tokenManager = ServerTokenManager.noop(); return (plugin: string): PluginEnvironment => { const logger = root.child({ type: 'plugin', plugin }); const database = databaseManager.forPlugin(plugin); const cache = cacheManager.forPlugin(plugin); - return { logger, database, cache, config, reader, discovery }; + return { logger, database, cache, config, reader, discovery, tokenManager }; }; } diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/search.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/search.ts index 63e196235c..f23b0c7bcf 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/search.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/plugins/search.ts @@ -12,6 +12,7 @@ export default async function createPlugin({ logger, discovery, config, + tokenManager, }: PluginEnvironment) { // Initialize a connection to a search engine. const searchEngine = new LunrSearchEngine({ logger }); @@ -21,13 +22,20 @@ export default async function createPlugin({ // collator gathers entities from the software catalog. indexBuilder.addCollator({ defaultRefreshIntervalSeconds: 600, - collator: DefaultCatalogCollator.fromConfig(config, { discovery }), + collator: DefaultCatalogCollator.fromConfig(config, { + discovery, + tokenManager, + }), }); // collator gathers entities from techdocs. indexBuilder.addCollator({ defaultRefreshIntervalSeconds: 600, - collator: DefaultTechDocsCollator.fromConfig(config, { discovery, logger }), + collator: DefaultTechDocsCollator.fromConfig(config, { + discovery, + logger, + tokenManager, + }), }); // The scheduler controls when documents are gathered from collators and sent diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts index 906d86d4a2..054c64db65 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts @@ -14,6 +14,7 @@ export default async function createPlugin({ config, discovery, reader, + cache, }: PluginEnvironment): Promise { // Preparers are responsible for fetching source files for documentation. const preparers = await Preparers.fromConfig(config, { @@ -49,5 +50,6 @@ export default async function createPlugin({ logger, config, discovery, + cache, }); } diff --git a/packages/create-app/templates/default-app/packages/backend/src/types.ts b/packages/create-app/templates/default-app/packages/backend/src/types.ts index 6c78a2a90c..b1e2e0a1df 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/types.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/types.ts @@ -4,6 +4,7 @@ import { PluginCacheManager, PluginDatabaseManager, PluginEndpointDiscovery, + TokenManager, UrlReader, } from '@backstage/backend-common'; @@ -14,4 +15,5 @@ export type PluginEnvironment = { config: Config; reader: UrlReader; discovery: PluginEndpointDiscovery; + tokenManager: TokenManager; }; diff --git a/packages/dev-utils/package.json b/packages/dev-utils/package.json index 32d287d35d..110d774777 100644 --- a/packages/dev-utils/package.json +++ b/packages/dev-utils/package.json @@ -30,14 +30,14 @@ }, "dependencies": { "@backstage/app-defaults": "^0.1.1", - "@backstage/core-app-api": "^0.1.21", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-app-api": "^0.1.24", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/catalog-model": "^0.9.7", "@backstage/integration-react": "^0.1.14", "@backstage/plugin-catalog-react": "^0.6.4", "@backstage/test-utils": "^0.1.22", - "@backstage/theme": "^0.2.11", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@testing-library/jest-dom": "^5.10.1", @@ -53,7 +53,7 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest": "^26.0.7", "@types/node": "^14.14.32" }, diff --git a/packages/embedded-techdocs-app/CHANGELOG.md b/packages/embedded-techdocs-app/CHANGELOG.md index 6a9583c2dc..13aa9aabe3 100644 --- a/packages/embedded-techdocs-app/CHANGELOG.md +++ b/packages/embedded-techdocs-app/CHANGELOG.md @@ -1,5 +1,17 @@ # embedded-techdocs-app +## 0.2.55 + +### Patch Changes + +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/cli@0.10.0 + - @backstage/core-plugin-api@0.2.2 + - @backstage/core-app-api@0.1.24 + - @backstage/plugin-techdocs@0.12.8 + ## 0.2.53 ### Patch Changes diff --git a/packages/embedded-techdocs-app/package.json b/packages/embedded-techdocs-app/package.json index b2d7882f8f..24db320eaa 100644 --- a/packages/embedded-techdocs-app/package.json +++ b/packages/embedded-techdocs-app/package.json @@ -1,21 +1,21 @@ { "name": "embedded-techdocs-app", - "version": "0.2.53", + "version": "0.2.55", "private": true, "bundled": true, "dependencies": { "@backstage/app-defaults": "^0.1.1", "@backstage/catalog-model": "^0.9.7", - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/config": "^0.1.10", - "@backstage/core-app-api": "^0.1.21", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-app-api": "^0.1.24", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/integration-react": "^0.1.14", "@backstage/plugin-catalog": "^0.7.3", - "@backstage/plugin-techdocs": "^0.12.6", + "@backstage/plugin-techdocs": "^0.12.8", "@backstage/test-utils": "^0.1.22", - "@backstage/theme": "^0.2.11", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "history": "^5.0.0", @@ -26,7 +26,7 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/packages/errors/CHANGELOG.md b/packages/errors/CHANGELOG.md index 9ea2f47cbb..02b28cdf1d 100644 --- a/packages/errors/CHANGELOG.md +++ b/packages/errors/CHANGELOG.md @@ -1,5 +1,12 @@ # @backstage/errors +## 0.1.5 + +### Patch Changes + +- 4d09c60256: Deprecate `parseErrorResponse` in favour of `parseErrorResponseBody`. Deprecate `data` field inside `ErrorResponse` in favour of `body`. + Rename the error name for unknown errors from `unknown` to `error`. + ## 0.1.4 ### Patch Changes diff --git a/packages/errors/package.json b/packages/errors/package.json index 38fe6c634e..d0d59ffd6a 100644 --- a/packages/errors/package.json +++ b/packages/errors/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/errors", "description": "Common utilities for error handling within Backstage", - "version": "0.1.4", + "version": "0.1.5", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -35,7 +35,7 @@ "serialize-error": "^8.0.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest": "^26.0.7" }, "files": [ diff --git a/packages/integration-react/package.json b/packages/integration-react/package.json index f3c79cc56c..be38d92b64 100644 --- a/packages/integration-react/package.json +++ b/packages/integration-react/package.json @@ -22,10 +22,10 @@ }, "dependencies": { "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/integration": "^0.6.9", - "@backstage/theme": "^0.2.12", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/integration": "^0.6.10", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -34,7 +34,7 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/dev-utils": "^0.2.13", "@backstage/test-utils": "^0.1.22", "@testing-library/jest-dom": "^5.10.1", diff --git a/packages/integration/CHANGELOG.md b/packages/integration/CHANGELOG.md index b9c6601e6c..e3380082f7 100644 --- a/packages/integration/CHANGELOG.md +++ b/packages/integration/CHANGELOG.md @@ -1,5 +1,11 @@ # @backstage/integration +## 0.6.10 + +### Patch Changes + +- 47619da24c: Narrow the types returned by the request option functions, to only the specifics that they actually do return. The reason for this change is that a full `RequestInit` is unfortunate to return because it's different between `cross-fetch` and `node-fetch`. + ## 0.6.9 ### Patch Changes diff --git a/packages/integration/api-report.md b/packages/integration/api-report.md index 4c2258779a..fcaa39b285 100644 --- a/packages/integration/api-report.md +++ b/packages/integration/api-report.md @@ -112,7 +112,9 @@ export function getAzureFileFetchUrl(url: string): string; export function getAzureRequestOptions( config: AzureIntegrationConfig, additionalHeaders?: Record, -): RequestInit; +): { + headers: Record; +}; // @public export function getBitbucketDefaultBranch( @@ -135,7 +137,9 @@ export function getBitbucketFileFetchUrl( // @public export function getBitbucketRequestOptions( config: BitbucketIntegrationConfig, -): RequestInit; +): { + headers: Record; +}; // @public export function getGitHubFileFetchUrl( @@ -148,7 +152,9 @@ export function getGitHubFileFetchUrl( export function getGitHubRequestOptions( config: GitHubIntegrationConfig, credentials: GithubCredentials, -): RequestInit; +): { + headers: Record; +}; // @public export function getGitLabFileFetchUrl( @@ -157,9 +163,9 @@ export function getGitLabFileFetchUrl( ): Promise; // @public -export function getGitLabRequestOptions( - config: GitLabIntegrationConfig, -): RequestInit; +export function getGitLabRequestOptions(config: GitLabIntegrationConfig): { + headers: Record; +}; // @public export type GithubAppConfig = { diff --git a/packages/integration/package.json b/packages/integration/package.json index 4ccde52a70..a6d91511c3 100644 --- a/packages/integration/package.json +++ b/packages/integration/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/integration", "description": "Helpers for managing integrations towards external systems", - "version": "0.6.9", + "version": "0.6.10", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -39,8 +39,8 @@ "lodash": "^4.17.21" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/config-loader": "^0.8.0", + "@backstage/cli": "^0.10.0", + "@backstage/config-loader": "^0.8.1", "@backstage/test-utils": "^0.1.22", "@types/jest": "^26.0.7", "@types/luxon": "^2.0.4", diff --git a/packages/integration/src/azure/core.ts b/packages/integration/src/azure/core.ts index 7461954267..1d5c4c3c89 100644 --- a/packages/integration/src/azure/core.ts +++ b/packages/integration/src/azure/core.ts @@ -64,8 +64,8 @@ export function getAzureCommitsUrl(url: string): string { export function getAzureRequestOptions( config: AzureIntegrationConfig, additionalHeaders?: Record, -): RequestInit { - const headers: HeadersInit = additionalHeaders +): { headers: Record } { + const headers: Record = additionalHeaders ? { ...additionalHeaders } : {}; diff --git a/packages/integration/src/bitbucket/core.ts b/packages/integration/src/bitbucket/core.ts index afcb9fcfdb..da10152bf8 100644 --- a/packages/integration/src/bitbucket/core.ts +++ b/packages/integration/src/bitbucket/core.ts @@ -158,8 +158,8 @@ export function getBitbucketFileFetchUrl( */ export function getBitbucketRequestOptions( config: BitbucketIntegrationConfig, -): RequestInit { - const headers: HeadersInit = {}; +): { headers: Record } { + const headers: Record = {}; if (config.token) { headers.Authorization = `Bearer ${config.token}`; diff --git a/packages/integration/src/github/core.ts b/packages/integration/src/github/core.ts index 2c5e739a26..76e54fd544 100644 --- a/packages/integration/src/github/core.ts +++ b/packages/integration/src/github/core.ts @@ -73,8 +73,8 @@ export function getGitHubFileFetchUrl( export function getGitHubRequestOptions( config: GitHubIntegrationConfig, credentials: GithubCredentials, -): RequestInit { - const headers: HeadersInit = {}; +): { headers: Record } { + const headers: Record = {}; if (chooseEndpoint(config, credentials) === 'api') { headers.Accept = 'application/vnd.github.v3.raw'; diff --git a/packages/integration/src/gitlab/core.ts b/packages/integration/src/gitlab/core.ts index e6f4dbc910..c5b0713340 100644 --- a/packages/integration/src/gitlab/core.ts +++ b/packages/integration/src/gitlab/core.ts @@ -54,9 +54,9 @@ export async function getGitLabFileFetchUrl( * @param config - The relevant provider config * @public */ -export function getGitLabRequestOptions( - config: GitLabIntegrationConfig, -): RequestInit { +export function getGitLabRequestOptions(config: GitLabIntegrationConfig): { + headers: Record; +} { const { token = '' } = config; return { headers: { diff --git a/packages/search-common/package.json b/packages/search-common/package.json index d65e9bcbdc..51cea5a28e 100644 --- a/packages/search-common/package.json +++ b/packages/search-common/package.json @@ -39,7 +39,7 @@ "@backstage/types": "^0.1.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" }, "jest": { "roots": [ diff --git a/packages/storybook/.storybook/apis.js b/packages/storybook/.storybook/apis.js index 2750324c17..4c0813a8e9 100644 --- a/packages/storybook/.storybook/apis.js +++ b/packages/storybook/.storybook/apis.js @@ -10,6 +10,7 @@ import { OktaAuth, Auth0Auth, ConfigReader, + LocalStorageFeatureFlags, } from '@backstage/core-app-api'; import { @@ -24,9 +25,11 @@ import { oktaAuthApiRef, auth0AuthApiRef, configApiRef, + featureFlagsApiRef, } from '@backstage/core-plugin-api'; const configApi = new ConfigReader({}); +const featureFlagsApi = new LocalStorageFeatureFlags(); const alertApi = new AlertApiForwarder(); const errorApi = new ErrorAlerter(alertApi, new ErrorApiForwarder()); const identityApi = { @@ -69,6 +72,7 @@ const oauth2Api = OAuth2.create({ export const apis = [ [configApiRef, configApi], + [featureFlagsApiRef, featureFlagsApi], [alertApiRef, alertApi], [errorApiRef, errorApi], [identityApiRef, identityApi], diff --git a/packages/techdocs-cli/CHANGELOG.md b/packages/techdocs-cli/CHANGELOG.md index 6d69e452ad..d07361e915 100644 --- a/packages/techdocs-cli/CHANGELOG.md +++ b/packages/techdocs-cli/CHANGELOG.md @@ -1,5 +1,13 @@ # @techdocs/cli +## 0.8.7 + +### Patch Changes + +- e7230ef814: Bump react-dev-utils to v12 +- Updated dependencies + - @backstage/backend-common@0.9.12 + ## 0.8.6 ### Patch Changes diff --git a/packages/techdocs-cli/package.json b/packages/techdocs-cli/package.json index 70ca0a9668..34d67d4dc9 100644 --- a/packages/techdocs-cli/package.json +++ b/packages/techdocs-cli/package.json @@ -1,7 +1,7 @@ { "name": "@techdocs/cli", "description": "Utility CLI for managing TechDocs sites in Backstage.", - "version": "0.8.6", + "version": "0.8.7", "private": false, "publishConfig": { "access": "public" @@ -32,7 +32,7 @@ "techdocs-cli": "bin/techdocs-cli" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/commander": "^2.12.2", "@types/fs-extra": "^9.0.6", "@types/http-proxy": "^1.17.4", @@ -41,7 +41,7 @@ "@types/react-dev-utils": "^9.0.4", "@types/serve-handler": "^6.1.0", "@types/webpack-env": "^1.15.3", - "embedded-techdocs-app": "0.2.53", + "embedded-techdocs-app": "0.2.55", "find-process": "^1.4.5", "nodemon": "^2.0.2", "ts-node": "^10.0.0" @@ -56,7 +56,7 @@ "ext": "ts" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", "@backstage/techdocs-common": "^0.10.7", @@ -65,7 +65,7 @@ "dockerode": "^3.3.1", "fs-extra": "^9.0.1", "http-proxy": "^1.18.1", - "react-dev-utils": "^11.0.4", + "react-dev-utils": "^12.0.0-next.47", "serve-handler": "^6.1.3", "winston": "^3.2.1" } diff --git a/packages/techdocs-common/CHANGELOG.md b/packages/techdocs-common/CHANGELOG.md index 0207ea409d..386c584196 100644 --- a/packages/techdocs-common/CHANGELOG.md +++ b/packages/techdocs-common/CHANGELOG.md @@ -1,5 +1,27 @@ # @backstage/techdocs-common +## 0.10.8 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/backend-common@0.9.11 + ## 0.10.7 ### Patch Changes diff --git a/packages/techdocs-common/api-report.md b/packages/techdocs-common/api-report.md index 61371525e5..b2f9e40d0a 100644 --- a/packages/techdocs-common/api-report.md +++ b/packages/techdocs-common/api-report.md @@ -287,6 +287,8 @@ export type TechDocsMetadata = { site_name: string; site_description: string; etag: string; + build_timestamp: number; + files?: string[]; }; // Warning: (ae-missing-release-tag) "transformDirLocation" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) diff --git a/packages/techdocs-common/package.json b/packages/techdocs-common/package.json index b13b94a1a7..e6956b87e6 100644 --- a/packages/techdocs-common/package.json +++ b/packages/techdocs-common/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/techdocs-common", "description": "Common functionalities for TechDocs, to be shared between techdocs-backend plugin and techdocs-cli", - "version": "0.10.7", + "version": "0.10.8", "main": "src/index.ts", "types": "src/index.ts", "private": false, @@ -38,12 +38,12 @@ "dependencies": { "@azure/identity": "^1.5.0", "@azure/storage-blob": "^12.5.0", - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/errors": "^0.1.4", + "@backstage/errors": "^0.1.5", "@backstage/search-common": "^0.2.1", - "@backstage/integration": "^0.6.9", + "@backstage/integration": "^0.6.10", "@google-cloud/storage": "^5.6.0", "@trendyol-js/openstack-swift-sdk": "^0.0.5", "@types/express": "^4.17.6", @@ -60,7 +60,7 @@ "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/fs-extra": "^9.0.5", "@types/js-yaml": "^4.0.0", "@types/mime-types": "^2.1.0", diff --git a/packages/techdocs-common/src/stages/generate/helpers.test.ts b/packages/techdocs-common/src/stages/generate/helpers.test.ts index 9e01c3e2ad..9323ab4f18 100644 --- a/packages/techdocs-common/src/stages/generate/helpers.test.ts +++ b/packages/techdocs-common/src/stages/generate/helpers.test.ts @@ -23,7 +23,7 @@ import os from 'os'; import path, { resolve as resolvePath } from 'path'; import { ParsedLocationAnnotation } from '../../helpers'; import { - addBuildTimestampMetadata, + createOrUpdateMetadata, getGeneratorKey, getMkdocsYml, getRepoUrlFromLocationAnnotation, @@ -369,13 +369,15 @@ describe('helpers', () => { }); describe('addBuildTimestampMetadata', () => { + const mockFiles = { + 'invalid_techdocs_metadata.json': 'dsds', + 'techdocs_metadata.json': '{"site_name": "Tech Docs"}', + }; + beforeEach(() => { mockFs.restore(); mockFs({ - [rootDir]: { - 'invalid_techdocs_metadata.json': 'dsds', - 'techdocs_metadata.json': '{"site_name": "Tech Docs"}', - }, + [rootDir]: mockFiles, }); }); @@ -385,7 +387,7 @@ describe('helpers', () => { it('should create the file if it does not exist', async () => { const filePath = path.join(rootDir, 'wrong_techdocs_metadata.json'); - await addBuildTimestampMetadata(filePath, mockLogger); + await createOrUpdateMetadata(filePath, mockLogger); // Check if the file exists await expect( @@ -397,18 +399,28 @@ describe('helpers', () => { const filePath = path.join(rootDir, 'invalid_techdocs_metadata.json'); await expect( - addBuildTimestampMetadata(filePath, mockLogger), + createOrUpdateMetadata(filePath, mockLogger), ).rejects.toThrowError('Unexpected token d in JSON at position 0'); }); it('should add build timestamp to the metadata json', async () => { const filePath = path.join(rootDir, 'techdocs_metadata.json'); - await addBuildTimestampMetadata(filePath, mockLogger); + await createOrUpdateMetadata(filePath, mockLogger); const json = await fs.readJson(filePath); expect(json.build_timestamp).toBeLessThanOrEqual(Date.now()); }); + + it('should add list of files to the metadata json', async () => { + const filePath = path.join(rootDir, 'techdocs_metadata.json'); + + await createOrUpdateMetadata(filePath, mockLogger); + + const json = await fs.readJson(filePath); + expect(json.files[0]).toEqual(Object.keys(mockFiles)[0]); + expect(json.files[1]).toEqual(Object.keys(mockFiles)[1]); + }); }); describe('storeEtagMetadata', () => { diff --git a/packages/techdocs-common/src/stages/generate/helpers.ts b/packages/techdocs-common/src/stages/generate/helpers.ts index f77b557076..794200fb7d 100644 --- a/packages/techdocs-common/src/stages/generate/helpers.ts +++ b/packages/techdocs-common/src/stages/generate/helpers.ts @@ -27,6 +27,7 @@ import { PassThrough, Writable } from 'stream'; import { Logger } from 'winston'; import { ParsedLocationAnnotation } from '../../helpers'; import { SupportedGeneratorKey } from './types'; +import { getFileTreeRecursively } from '../publish/helpers'; // TODO: Implement proper support for more generators. export function getGeneratorKey(entity: Entity): SupportedGeneratorKey { @@ -345,14 +346,20 @@ export const patchIndexPreBuild = async ({ }; /** - * Update the techdocs_metadata.json to add a new build timestamp metadata. Create the .json file if it doesn't exist. + * Create or update the techdocs_metadata.json. Values initialized/updated are: + * - The build_timestamp (now) + * - The list of files generated * * @param {string} techdocsMetadataPath File path to techdocs_metadata.json */ -export const addBuildTimestampMetadata = async ( +export const createOrUpdateMetadata = async ( techdocsMetadataPath: string, logger: Logger, ): Promise => { + const techdocsMetadataDir = techdocsMetadataPath + .split(path.sep) + .slice(0, -1) + .join(path.sep); // check if file exists, create if it does not. try { await fs.access(techdocsMetadataPath, fs.constants.F_OK); @@ -372,6 +379,19 @@ export const addBuildTimestampMetadata = async ( } json.build_timestamp = Date.now(); + + // Get and write generated files to the metadata JSON. Each file string is in + // a form appropriate for invalidating the associated object from cache. + try { + json.files = (await getFileTreeRecursively(techdocsMetadataDir)).map(file => + file.replace(`${techdocsMetadataDir}${path.sep}`, ''), + ); + } catch (err) { + assertError(err); + json.files = []; + logger.warn(`Unable to add files list to metadata: ${err.message}`); + } + await fs.writeJson(techdocsMetadataPath, json); return; }; diff --git a/packages/techdocs-common/src/stages/generate/techdocs.ts b/packages/techdocs-common/src/stages/generate/techdocs.ts index 728cab5a81..8681736815 100644 --- a/packages/techdocs-common/src/stages/generate/techdocs.ts +++ b/packages/techdocs-common/src/stages/generate/techdocs.ts @@ -23,7 +23,7 @@ import { ScmIntegrations, } from '@backstage/integration'; import { - addBuildTimestampMetadata, + createOrUpdateMetadata, getMkdocsYml, patchIndexPreBuild, patchMkdocsYmlPreBuild, @@ -164,9 +164,9 @@ export class TechdocsGenerator implements GeneratorBase { * Post Generate steps */ - // Add build timestamp to techdocs_metadata.json + // Add build timestamp and files to techdocs_metadata.json // Creates techdocs_metadata.json if file does not exist. - await addBuildTimestampMetadata( + await createOrUpdateMetadata( path.join(outputDir, 'techdocs_metadata.json'), childLogger, ); diff --git a/packages/techdocs-common/src/stages/publish/awsS3.test.ts b/packages/techdocs-common/src/stages/publish/awsS3.test.ts index 1f49668d35..3e4c4c705b 100644 --- a/packages/techdocs-common/src/stages/publish/awsS3.test.ts +++ b/packages/techdocs-common/src/stages/publish/awsS3.test.ts @@ -95,6 +95,7 @@ describe('AwsS3Publish', () => { site_name: 'backstage', site_description: 'site_content', etag: 'etag', + build_timestamp: 612741599, }; const directory = getEntityRootDir(entity); @@ -149,21 +150,39 @@ describe('AwsS3Publish', () => { describe('publish', () => { it('should publish a directory', async () => { const publisher = createPublisherFromConfig(); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'default/component/backstage/404.html', + `default/component/backstage/index.html`, + `default/component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory as well when legacy casing is used', async () => { const publisher = createPublisherFromConfig({ legacyUseCaseSensitiveTripletPaths: true, }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'default/Component/backstage/404.html', + `default/Component/backstage/index.html`, + `default/Component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory when root path is specified', async () => { const publisher = createPublisherFromConfig({ bucketRootPath: 'backstage-data/techdocs', }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'backstage-data/techdocs/default/component/backstage/404.html', + `backstage-data/techdocs/default/component/backstage/index.html`, + `backstage-data/techdocs/default/component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory when root path is specified and legacy casing is used', async () => { @@ -171,14 +190,26 @@ describe('AwsS3Publish', () => { bucketRootPath: 'backstage-data/techdocs', legacyUseCaseSensitiveTripletPaths: true, }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'backstage-data/techdocs/default/Component/backstage/404.html', + `backstage-data/techdocs/default/Component/backstage/index.html`, + `backstage-data/techdocs/default/Component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory when sse is specified', async () => { const publisher = createPublisherFromConfig({ sse: 'aws:kms', }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'default/component/backstage/404.html', + 'default/component/backstage/index.html', + 'default/component/backstage/assets/main.css', + ]), + }); }); it('should fail to publish a directory', async () => { diff --git a/packages/techdocs-common/src/stages/publish/awsS3.ts b/packages/techdocs-common/src/stages/publish/awsS3.ts index abfa8ddd24..ed76edc0cb 100644 --- a/packages/techdocs-common/src/stages/publish/awsS3.ts +++ b/packages/techdocs-common/src/stages/publish/awsS3.ts @@ -39,6 +39,7 @@ import { import { PublisherBase, PublishRequest, + PublishResponse, ReadinessResponse, TechDocsMetadata, } from './types'; @@ -214,7 +215,11 @@ export class AwsS3Publish implements PublisherBase { * Upload all the files from the generated `directory` to the S3 bucket. * Directory structure used in the bucket is - entityNamespace/entityKind/entityName/index.html */ - async publish({ entity, directory }: PublishRequest): Promise { + async publish({ + entity, + directory, + }: PublishRequest): Promise { + const objects: string[] = []; const useLegacyPathCasing = this.legacyPathCasing; const bucketRootPath = this.bucketRootPath; const sse = this.sse; @@ -263,6 +268,7 @@ export class AwsS3Publish implements PublisherBase { ...(sse && { ServerSideEncryption: sse }), } as aws.S3.PutObjectRequest; + objects.push(params.Key); return this.storageClient.upload(params).promise(); }, absoluteFilesToUpload, @@ -311,6 +317,7 @@ export class AwsS3Publish implements PublisherBase { const errorMessage = `Unable to delete file(s) from AWS S3. ${error}`; this.logger.error(errorMessage); } + return { objects }; } async fetchTechDocsMetadata( diff --git a/packages/techdocs-common/src/stages/publish/azureBlobStorage.test.ts b/packages/techdocs-common/src/stages/publish/azureBlobStorage.test.ts index a2503bd7b2..e6fd45eed7 100644 --- a/packages/techdocs-common/src/stages/publish/azureBlobStorage.test.ts +++ b/packages/techdocs-common/src/stages/publish/azureBlobStorage.test.ts @@ -89,6 +89,7 @@ describe('AzureBlobStoragePublish', () => { site_name: 'backstage', site_description: 'site_content', etag: 'etag', + build_timestamp: 612741599, }; const directory = getEntityRootDir(entity); @@ -154,14 +155,26 @@ describe('AzureBlobStoragePublish', () => { describe('publish', () => { it('should publish a directory', async () => { const publisher = createPublisherFromConfig(); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'default/component/backstage/404.html', + `default/component/backstage/index.html`, + `default/component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory as well when legacy casing is used', async () => { const publisher = createPublisherFromConfig({ legacyUseCaseSensitiveTripletPaths: true, }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'default/Component/backstage/404.html', + `default/Component/backstage/index.html`, + `default/Component/backstage/assets/main.css`, + ]), + }); }); it('should fail to publish a directory', async () => { diff --git a/packages/techdocs-common/src/stages/publish/azureBlobStorage.ts b/packages/techdocs-common/src/stages/publish/azureBlobStorage.ts index 7a58d92095..b082079be2 100644 --- a/packages/techdocs-common/src/stages/publish/azureBlobStorage.ts +++ b/packages/techdocs-common/src/stages/publish/azureBlobStorage.ts @@ -39,6 +39,7 @@ import { import { PublisherBase, PublishRequest, + PublishResponse, ReadinessResponse, TechDocsMetadata, } from './types'; @@ -156,7 +157,11 @@ export class AzureBlobStoragePublish implements PublisherBase { * Upload all the files from the generated `directory` to the Azure Blob Storage container. * Directory structure used in the container is - entityNamespace/entityKind/entityName/index.html */ - async publish({ entity, directory }: PublishRequest): Promise { + async publish({ + entity, + directory, + }: PublishRequest): Promise { + const objects: string[] = []; const useLegacyPathCasing = this.legacyPathCasing; // First, try to retrieve a list of all individual files currently existing @@ -194,14 +199,14 @@ export class AzureBlobStoragePublish implements PublisherBase { const relativeFilePath = path.normalize( path.relative(directory, absoluteFilePath), ); + const remotePath = getCloudPathForLocalPath( + entity, + relativeFilePath, + useLegacyPathCasing, + ); + objects.push(remotePath); const response = await container - .getBlockBlobClient( - getCloudPathForLocalPath( - entity, - relativeFilePath, - useLegacyPathCasing, - ), - ) + .getBlockBlobClient(remotePath) .uploadFile(absoluteFilePath); if (response._response.status >= 400) { @@ -264,6 +269,8 @@ export class AzureBlobStoragePublish implements PublisherBase { const errorMessage = `Unable to delete file(s) from Azure. ${error}`; this.logger.error(errorMessage); } + + return { objects }; } private download(containerName: string, blobPath: string): Promise { diff --git a/packages/techdocs-common/src/stages/publish/googleStorage.test.ts b/packages/techdocs-common/src/stages/publish/googleStorage.test.ts index a52fd0f0bd..ed35f2e445 100644 --- a/packages/techdocs-common/src/stages/publish/googleStorage.test.ts +++ b/packages/techdocs-common/src/stages/publish/googleStorage.test.ts @@ -88,6 +88,7 @@ describe('GoogleGCSPublish', () => { site_name: 'backstage', site_description: 'site_content', etag: 'etag', + build_timestamp: 612741599, }; const directory = getEntityRootDir(entity); @@ -142,21 +143,39 @@ describe('GoogleGCSPublish', () => { describe('publish', () => { it('should publish a directory', async () => { const publisher = createPublisherFromConfig(); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'default/component/backstage/404.html', + `default/component/backstage/index.html`, + `default/component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory as well when legacy casing is used', async () => { const publisher = createPublisherFromConfig({ legacyUseCaseSensitiveTripletPaths: true, }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'default/Component/backstage/404.html', + `default/Component/backstage/index.html`, + `default/Component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory when root path is specified', async () => { const publisher = createPublisherFromConfig({ bucketRootPath: 'backstage-data/techdocs', }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'backstage-data/techdocs/default/component/backstage/404.html', + `backstage-data/techdocs/default/component/backstage/index.html`, + `backstage-data/techdocs/default/component/backstage/assets/main.css`, + ]), + }); }); it('should publish a directory when root path is specified and legacy casing is used', async () => { @@ -164,7 +183,13 @@ describe('GoogleGCSPublish', () => { bucketRootPath: 'backstage-data/techdocs', legacyUseCaseSensitiveTripletPaths: true, }); - expect(await publisher.publish({ entity, directory })).toBeUndefined(); + expect(await publisher.publish({ entity, directory })).toMatchObject({ + objects: expect.arrayContaining([ + 'backstage-data/techdocs/default/Component/backstage/404.html', + `backstage-data/techdocs/default/Component/backstage/index.html`, + `backstage-data/techdocs/default/Component/backstage/assets/main.css`, + ]), + }); }); it('should fail to publish a directory', async () => { diff --git a/packages/techdocs-common/src/stages/publish/googleStorage.ts b/packages/techdocs-common/src/stages/publish/googleStorage.ts index f072412c20..ba70c36e27 100644 --- a/packages/techdocs-common/src/stages/publish/googleStorage.ts +++ b/packages/techdocs-common/src/stages/publish/googleStorage.ts @@ -36,6 +36,7 @@ import { MigrateWriteStream } from './migrations'; import { PublisherBase, PublishRequest, + PublishResponse, ReadinessResponse, TechDocsMetadata, } from './types'; @@ -145,7 +146,11 @@ export class GoogleGCSPublish implements PublisherBase { * Upload all the files from the generated `directory` to the GCS bucket. * Directory structure used in the bucket is - entityNamespace/entityKind/entityName/index.html */ - async publish({ entity, directory }: PublishRequest): Promise { + async publish({ + entity, + directory, + }: PublishRequest): Promise { + const objects: string[] = []; const useLegacyPathCasing = this.legacyPathCasing; const bucket = this.storageClient.bucket(this.bucketName); const bucketRootPath = this.bucketRootPath; @@ -178,14 +183,14 @@ export class GoogleGCSPublish implements PublisherBase { await bulkStorageOperation( async absoluteFilePath => { const relativeFilePath = path.relative(directory, absoluteFilePath); - return await bucket.upload(absoluteFilePath, { - destination: getCloudPathForLocalPath( - entity, - relativeFilePath, - useLegacyPathCasing, - bucketRootPath, - ), - }); + const destination = getCloudPathForLocalPath( + entity, + relativeFilePath, + useLegacyPathCasing, + bucketRootPath, + ); + objects.push(destination); + return await bucket.upload(absoluteFilePath, { destination }); }, absoluteFilesToUpload, { concurrencyLimit: 10 }, @@ -228,6 +233,8 @@ export class GoogleGCSPublish implements PublisherBase { const errorMessage = `Unable to delete file(s) from Google Cloud Storage. ${error}`; this.logger.error(errorMessage); } + + return { objects }; } fetchTechDocsMetadata(entityName: EntityName): Promise { diff --git a/packages/techdocs-common/src/stages/publish/local.ts b/packages/techdocs-common/src/stages/publish/local.ts index 70b4eb3ff2..9c146d2935 100644 --- a/packages/techdocs-common/src/stages/publish/local.ts +++ b/packages/techdocs-common/src/stages/publish/local.ts @@ -98,7 +98,10 @@ export class LocalPublish implements PublisherBase { }; } - publish({ entity, directory }: PublishRequest): Promise { + async publish({ + entity, + directory, + }: PublishRequest): Promise { const entityNamespace = entity.metadata.namespace ?? 'default'; const publishDir = this.staticEntityPathJoin( @@ -112,27 +115,30 @@ export class LocalPublish implements PublisherBase { fs.mkdirSync(publishDir, { recursive: true }); } - return new Promise((resolve, reject) => { - fs.copy(directory, publishDir, err => { - if (err) { - this.logger.debug( - `Failed to copy docs from ${directory} to ${publishDir}`, - ); - reject(err); - } - this.logger.info(`Published site stored at ${publishDir}`); - this.discovery - .getBaseUrl('techdocs') - .then(techdocsApiUrl => { - resolve({ - remoteUrl: `${techdocsApiUrl}/static/docs/${entity.metadata.name}`, - }); - }) - .catch(reason => { - reject(reason); - }); - }); - }); + try { + await fs.copy(directory, publishDir); + this.logger.info(`Published site stored at ${publishDir}`); + } catch (error) { + this.logger.debug( + `Failed to copy docs from ${directory} to ${publishDir}`, + ); + throw error; + } + + // Generate publish response. + const techdocsApiUrl = await this.discovery.getBaseUrl('techdocs'); + const publishedFilePaths = (await getFileTreeRecursively(publishDir)).map( + abs => { + return abs.split(`${staticDocsDir}/`)[1]; + }, + ); + + return { + remoteUrl: `${techdocsApiUrl}/static/docs/${encodeURIComponent( + entity.metadata.name, + )}`, + objects: publishedFilePaths, + }; } async fetchTechDocsMetadata( diff --git a/packages/techdocs-common/src/stages/publish/openStackSwift.test.ts b/packages/techdocs-common/src/stages/publish/openStackSwift.test.ts index c2236fb880..ef06e26cfa 100644 --- a/packages/techdocs-common/src/stages/publish/openStackSwift.test.ts +++ b/packages/techdocs-common/src/stages/publish/openStackSwift.test.ts @@ -170,7 +170,13 @@ describe('OpenStackSwiftPublish', () => { entity, directory: entityRootDir, }), - ).toBeUndefined(); + ).toMatchObject({ + objects: expect.arrayContaining([ + 'test-namespace/TestKind/test-component-name/404.html', + `test-namespace/TestKind/test-component-name/index.html`, + `test-namespace/TestKind/test-component-name/assets/main.css`, + ]), + }); }); it('should fail to publish a directory', async () => { @@ -241,7 +247,7 @@ describe('OpenStackSwiftPublish', () => { mockFs({ [entityRootDir]: { 'techdocs_metadata.json': - '{"site_name": "backstage", "site_description": "site_content", "etag": "etag"}', + '{"site_name": "backstage", "site_description": "site_content", "etag": "etag", "build_timestamp": 612741599}', }, }); @@ -249,6 +255,7 @@ describe('OpenStackSwiftPublish', () => { site_name: 'backstage', site_description: 'site_content', etag: 'etag', + build_timestamp: 612741599, }; expect( await publisher.fetchTechDocsMetadata(entityNameMock), @@ -263,7 +270,7 @@ describe('OpenStackSwiftPublish', () => { mockFs({ [entityRootDir]: { - 'techdocs_metadata.json': `{'site_name': 'backstage', 'site_description': 'site_content', 'etag': 'etag'}`, + 'techdocs_metadata.json': `{'site_name': 'backstage', 'site_description': 'site_content', 'etag': 'etag', 'build_timestamp': 612741599}`, }, }); @@ -271,6 +278,7 @@ describe('OpenStackSwiftPublish', () => { site_name: 'backstage', site_description: 'site_content', etag: 'etag', + build_timestamp: 612741599, }; expect( await publisher.fetchTechDocsMetadata(entityNameMock), diff --git a/packages/techdocs-common/src/stages/publish/openStackSwift.ts b/packages/techdocs-common/src/stages/publish/openStackSwift.ts index 7b623933e3..62b40f9a76 100644 --- a/packages/techdocs-common/src/stages/publish/openStackSwift.ts +++ b/packages/techdocs-common/src/stages/publish/openStackSwift.ts @@ -32,6 +32,7 @@ import { import { PublisherBase, PublishRequest, + PublishResponse, ReadinessResponse, TechDocsMetadata, } from './types'; @@ -139,8 +140,13 @@ export class OpenStackSwiftPublish implements PublisherBase { * Upload all the files from the generated `directory` to the OpenStack Swift container. * Directory structure used in the bucket is - entityNamespace/entityKind/entityName/index.html */ - async publish({ entity, directory }: PublishRequest): Promise { + async publish({ + entity, + directory, + }: PublishRequest): Promise { try { + const objects: string[] = []; + // Note: OpenStack Swift manages creation of parent directories if they do not exist. // So collecting path of only the files is good enough. const allFilesToUpload = await getFileTreeRecursively(directory); @@ -161,6 +167,7 @@ export class OpenStackSwiftPublish implements PublisherBase { // The / delimiter is intentional since it represents the cloud storage and not the local file system. const entityRootDir = `${entity.metadata.namespace}/${entity.kind}/${entity.metadata.name}`; const destination = `${entityRootDir}/${relativeFilePathPosix}`; // Swift container file relative path + objects.push(destination); // Rate limit the concurrent execution of file uploads to batches of 10 (per publish) const uploadFile = limiter(async () => { @@ -178,7 +185,7 @@ export class OpenStackSwiftPublish implements PublisherBase { this.logger.info( `Successfully uploaded all the generated files for Entity ${entity.metadata.name}. Total number of files: ${allFilesToUpload.length}`, ); - return; + return { objects }; } catch (e) { const errorMessage = `Unable to upload file(s) to OpenStack Swift. ${e}`; this.logger.error(errorMessage); diff --git a/packages/techdocs-common/src/stages/publish/types.ts b/packages/techdocs-common/src/stages/publish/types.ts index 229c853427..1fb301340b 100644 --- a/packages/techdocs-common/src/stages/publish/types.ts +++ b/packages/techdocs-common/src/stages/publish/types.ts @@ -32,9 +32,21 @@ export type PublishRequest = { directory: string; }; -/* `remoteUrl` is the URL which serves files from the local publisher's static directory. */ +/** + * Response containing metadata about where files were published and what may + * have been published or updated. + */ export type PublishResponse = { + /** + * The URL which serves files from the local publisher's static directory. + */ remoteUrl?: string; + /** + * The list of objects (specifically their paths) that were published. + * Objects do not have a preceding slash, and match how one would load the + * object over the `/static/docs/*` TechDocs Backend Plugin endpoint. + */ + objects?: string[]; } | void; /** @@ -53,6 +65,8 @@ export type TechDocsMetadata = { site_name: string; site_description: string; etag: string; + build_timestamp: number; + files?: string[]; }; export type MigrateRequest = { diff --git a/packages/test-utils-core/.npmrc b/packages/test-utils-core/.npmrc deleted file mode 100644 index 214c29d139..0000000000 --- a/packages/test-utils-core/.npmrc +++ /dev/null @@ -1 +0,0 @@ -registry=https://registry.npmjs.org/ diff --git a/packages/test-utils-core/.snyk b/packages/test-utils-core/.snyk deleted file mode 100644 index f368a3ddb9..0000000000 --- a/packages/test-utils-core/.snyk +++ /dev/null @@ -1,10 +0,0 @@ -# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities. -version: v1.22.1 -# ignores vulnerabilities until expiry date; change duration by modifying expiry date -ignore: - SNYK-JS-ANSIREGEX-1583908: - - '*': - reason: This only exposes the user's machine or build worker to a ReDos attack, which we don't consider an issue - expires: 2022-03-06T17:18:55.019Z - created: 2021-09-06T17:18:55.027Z -patch: {} diff --git a/packages/test-utils-core/CHANGELOG.md b/packages/test-utils-core/CHANGELOG.md deleted file mode 100644 index 35bdf1b2c6..0000000000 --- a/packages/test-utils-core/CHANGELOG.md +++ /dev/null @@ -1,22 +0,0 @@ -# @backstage/test-utils-core - -## 0.1.4 - -### Patch Changes - -- bb12aae352: Migrates all utility methods from `test-utils-core` into `test-utils` and delete exports from the old package. - This should have no impact since this package is considered internal and have no usages outside core packages. - - Notable changes are that the testing tool `msw.setupDefaultHandlers()` have been deprecated in favour of `setupRequestMockHandlers()`. - -## 0.1.3 - -### Patch Changes - -- ca0559444c: Avoid usage of `.to*Case()`, preferring `.toLocale*Case('en-US')` instead. - -## 0.1.2 - -### Patch Changes - -- 56c773909: Switched `@types/react` dependency to request `*` rather than a specific version. diff --git a/packages/test-utils-core/README.md b/packages/test-utils-core/README.md deleted file mode 100644 index 63b6ece0a6..0000000000 --- a/packages/test-utils-core/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# @backstage/test-utils-core - -This package provides utilities for testing the Backstage core packages. - -## Installation - -This package should not be used directly, use `@backstage/test-utils` instead. All exports from this -package are re-exported by `@backstage/test-utils`. - -The reason this package exists is to allow the Backstage core packages to use the testing utils exposed in this package. Since `@backstage/test-utils` needs to depend on `@backstage/core`, core is not able to use those test-utils. We put any test-utils that don't need to depend on other Backstage packages in this package, in order for them to be usable by any other `@backstage` packages. - -## Documentation - -- [Backstage Readme](https://github.com/backstage/backstage/blob/master/README.md) -- [Backstage Documentation](https://github.com/backstage/backstage/blob/master/docs/README.md) diff --git a/packages/test-utils-core/api-report.md b/packages/test-utils-core/api-report.md deleted file mode 100644 index f21c749727..0000000000 --- a/packages/test-utils-core/api-report.md +++ /dev/null @@ -1,7 +0,0 @@ -## API Report File for "@backstage/test-utils-core" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts -// (No @packageDocumentation comment for this package) -``` diff --git a/packages/test-utils-core/package.json b/packages/test-utils-core/package.json deleted file mode 100644 index ebe6decddb..0000000000 --- a/packages/test-utils-core/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "@backstage/test-utils-core", - "description": "Utilities to test Backstage core", - "version": "0.1.4", - "private": false, - "publishConfig": { - "access": "public", - "main": "dist/index.esm.js", - "types": "dist/index.d.ts" - }, - "homepage": "https://backstage.io", - "repository": { - "type": "git", - "url": "https://github.com/backstage/backstage", - "directory": "packages/test-utils-core" - }, - "keywords": [ - "backstage" - ], - "license": "Apache-2.0", - "main": "src/index.ts", - "types": "src/index.ts", - "scripts": { - "build": "backstage-cli build --outputs types,esm", - "lint": "backstage-cli lint", - "test": "backstage-cli test --passWithNoTests", - "prepack": "backstage-cli prepack", - "postpack": "backstage-cli postpack", - "clean": "backstage-cli clean" - }, - "dependencies": {}, - "devDependencies": { - "@types/jest": "^26.0.7", - "@types/node": "^14.14.32" - }, - "files": [ - "dist" - ] -} diff --git a/packages/test-utils/CHANGELOG.md b/packages/test-utils/CHANGELOG.md index 3460e6c714..fd8ce852db 100644 --- a/packages/test-utils/CHANGELOG.md +++ b/packages/test-utils/CHANGELOG.md @@ -1,5 +1,72 @@ # @backstage/test-utils +## 0.1.23 + +### Patch Changes + +- 000190de69: The `ApiRegistry` from `@backstage/core-app-api` class has been deprecated and will be removed in a future release. To replace it, we have introduced two new helpers that are exported from `@backstage/test-utils`, namely `TestApiProvider` and `TestApiRegistry`. + + These two new helpers are more tailored for writing tests and development setups, as they allow for partial implementations of each of the APIs. + + When migrating existing code it is typically best to prefer usage of `TestApiProvider` when possible, so for example the following code: + + ```tsx + render( + + {...} + + ) + ``` + + Would be migrated to this: + + ```tsx + render( + + {...} + + ) + ``` + + In cases where the `ApiProvider` is used in a more standalone way, for example to reuse a set of APIs across multiple tests, the `TestApiRegistry` can be used instead. Note that the `TestApiRegistry` only has a single static factory method, `.from()`, and it is slightly different from the existing `.from()` method on `ApiRegistry` in that it doesn't require the API pairs to be wrapped in an outer array. + + Usage that looks like this: + + ```ts + const apis = ApiRegistry.with( + identityApiRef, + mockIdentityApi as unknown as IdentityApi, + ).with(configApiRef, new ConfigReader({})); + ``` + + OR like this: + + ```ts + const apis = ApiRegistry.from([ + [identityApiRef, mockIdentityApi as unknown as IdentityApi], + [configApiRef, new ConfigReader({})], + ]); + ``` + + Would be migrated to this: + + ```ts + const apis = TestApiRegistry.from( + [identityApiRef, mockIdentityApi], + [configApiRef, new ConfigReader({})], + ); + ``` + + If your app is still using the `ApiRegistry` to construct the `apis` for `createApp`, we recommend that you move over to use the new method of supplying API factories instead, using `createApiFactory`. + +- Updated dependencies + - @backstage/core-app-api@0.1.23 + - @backstage/core-plugin-api@0.2.1 + ## 0.1.22 ### Patch Changes diff --git a/packages/test-utils/package.json b/packages/test-utils/package.json index 79667c236a..87c5b346f6 100644 --- a/packages/test-utils/package.json +++ b/packages/test-utils/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/test-utils", "description": "Utilities to test Backstage plugins and apps.", - "version": "0.1.22", + "version": "0.1.23", "private": false, "publishConfig": { "access": "public", @@ -29,9 +29,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-app-api": "^0.1.21", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-app-api": "^0.1.24", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@backstage/types": "^0.1.1", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.11.2", @@ -46,7 +46,7 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest": "^26.0.7", "@types/node": "^14.14.32" }, diff --git a/packages/theme/CHANGELOG.md b/packages/theme/CHANGELOG.md index 1c8661d7cc..cfa6ee3633 100644 --- a/packages/theme/CHANGELOG.md +++ b/packages/theme/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/theme +## 0.2.14 + +### Patch Changes + +- e34f174fc5: Added `` and `` to enable building better sidebars. You can check out the storybook for more inspiration and how to get started. + + Added two new theme props for styling the sidebar too, `navItem.hoverBackground` and `submenu.background`. + +- 59677fadb1: Improvements to API Reference documentation + ## 0.2.13 ### Patch Changes diff --git a/packages/theme/api-report.md b/packages/theme/api-report.md index 2dc6ab7b55..f650636710 100644 --- a/packages/theme/api-report.md +++ b/packages/theme/api-report.md @@ -41,6 +41,12 @@ export type BackstagePaletteAdditions = { indicator: string; color: string; selectedColor: string; + navItem?: { + hoverBackground: string; + }; + submenu?: { + background: string; + }; }; tabbar: { indicator: string; diff --git a/packages/theme/package.json b/packages/theme/package.json index 28a05af98d..08477dccd0 100644 --- a/packages/theme/package.json +++ b/packages/theme/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/theme", "description": "material-ui theme for use with Backstage.", - "version": "0.2.13", + "version": "0.2.14", "private": false, "publishConfig": { "access": "public", @@ -31,7 +31,7 @@ "@material-ui/core": "^4.12.2" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" }, "files": [ "dist" diff --git a/packages/theme/src/index.ts b/packages/theme/src/index.ts index 93fec977f9..41f827bf43 100644 --- a/packages/theme/src/index.ts +++ b/packages/theme/src/index.ts @@ -15,7 +15,7 @@ */ /** - * material-ui theme for use with Backstage. + * {@link https://mui.com | material-ui} theme for use with Backstage * * @packageDocumentation */ diff --git a/packages/theme/src/themes.ts b/packages/theme/src/themes.ts index 7e99ce8e8a..b048c70fec 100644 --- a/packages/theme/src/themes.ts +++ b/packages/theme/src/themes.ts @@ -76,6 +76,12 @@ export const lightTheme = createTheme({ indicator: '#9BF0E1', color: '#b5b5b5', selectedColor: '#FFF', + navItem: { + hoverBackground: '#404040', + }, + submenu: { + background: '#404040', + }, }, pinSidebarButton: { icon: '#181818', @@ -151,6 +157,12 @@ export const darkTheme = createTheme({ indicator: '#9BF0E1', color: '#b5b5b5', selectedColor: '#FFF', + navItem: { + hoverBackground: '#404040', + }, + submenu: { + background: '#404040', + }, }, pinSidebarButton: { icon: '#404040', diff --git a/packages/theme/src/types.ts b/packages/theme/src/types.ts index e1acba3a01..3d1a64c38f 100644 --- a/packages/theme/src/types.ts +++ b/packages/theme/src/types.ts @@ -53,6 +53,12 @@ export type BackstagePaletteAdditions = { indicator: string; color: string; selectedColor: string; + navItem?: { + hoverBackground: string; + }; + submenu?: { + background: string; + }; }; tabbar: { indicator: string; diff --git a/packages/types/package.json b/packages/types/package.json index 197d51b061..822b2d678e 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -31,7 +31,7 @@ }, "dependencies": {}, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/zen-observable": "^0.8.0", "zen-observable": "^0.8.15" }, diff --git a/packages/version-bridge/package.json b/packages/version-bridge/package.json index 35a6e8f71d..89baaea2f5 100644 --- a/packages/version-bridge/package.json +++ b/packages/version-bridge/package.json @@ -33,7 +33,7 @@ "react": "^16.12.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2" diff --git a/plugins/allure/package.json b/plugins/allure/package.json index 9efe6132e8..5c795e919f 100644 --- a/plugins/allure/package.json +++ b/plugins/allure/package.json @@ -23,10 +23,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -36,10 +36,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/analytics-module-ga/config.d.ts b/plugins/analytics-module-ga/config.d.ts index 4ccd66e1dd..ac534daae8 100644 --- a/plugins/analytics-module-ga/config.d.ts +++ b/plugins/analytics-module-ga/config.d.ts @@ -27,6 +27,13 @@ export interface Config { */ trackingId: string; + /** + * URL to Google Analytics analytics.js script + * Defaults to fetching from GA source (eg. https://www.google-analytics.com/analytics.js) + * @visibility frontend + */ + scriptSrc?: string; + /** * Whether or not to log analytics debug statements to the console. * Defaults to false. diff --git a/plugins/analytics-module-ga/package.json b/plugins/analytics-module-ga/package.json index e0a32960c5..e3a3c74111 100644 --- a/plugins/analytics-module-ga/package.json +++ b/plugins/analytics-module-ga/package.json @@ -22,9 +22,9 @@ }, "dependencies": { "@backstage/config": "^0.1.5", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -34,10 +34,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/analytics-module-ga/src/apis/implementations/AnalyticsApi/GoogleAnalytics.ts b/plugins/analytics-module-ga/src/apis/implementations/AnalyticsApi/GoogleAnalytics.ts index 1e6216936c..23da7c8589 100644 --- a/plugins/analytics-module-ga/src/apis/implementations/AnalyticsApi/GoogleAnalytics.ts +++ b/plugins/analytics-module-ga/src/apis/implementations/AnalyticsApi/GoogleAnalytics.ts @@ -42,18 +42,25 @@ export class GoogleAnalytics implements AnalyticsApi { private constructor({ cdmConfig, trackingId, + scriptSrc, testMode, debug, }: { cdmConfig: CustomDimensionOrMetricConfig[]; trackingId: string; + scriptSrc?: string; testMode: boolean; debug: boolean; }) { this.cdmConfig = cdmConfig; // Initialize Google Analytics. - ReactGA.initialize(trackingId, { testMode, debug, titleCase: false }); + ReactGA.initialize(trackingId, { + testMode, + debug, + gaAddress: scriptSrc, + titleCase: false, + }); } /** @@ -62,6 +69,7 @@ export class GoogleAnalytics implements AnalyticsApi { static fromConfig(config: Config) { // Get all necessary configuration. const trackingId = config.getString('app.analytics.ga.trackingId'); + const scriptSrc = config.getOptionalString('app.analytics.ga.scriptSrc'); const debug = config.getOptionalBoolean('app.analytics.ga.debug') ?? false; const testMode = config.getOptionalBoolean('app.analytics.ga.testMode') ?? false; @@ -82,6 +90,7 @@ export class GoogleAnalytics implements AnalyticsApi { // Return an implementation instance. return new GoogleAnalytics({ trackingId, + scriptSrc, cdmConfig, testMode, debug, diff --git a/plugins/api-docs/CHANGELOG.md b/plugins/api-docs/CHANGELOG.md index 0b0bd4890c..5eeaf14cb6 100644 --- a/plugins/api-docs/CHANGELOG.md +++ b/plugins/api-docs/CHANGELOG.md @@ -1,5 +1,31 @@ # @backstage/plugin-api-docs +## 0.6.17 + +### Patch Changes + +- dde1681f33: chore(dependencies): bump `graphiql` package to latest +- ef64a444ca: Update AsyncAPI component to 1.0.0-x releases + +## 0.6.16 + +### Patch Changes + +- 752a53d94e: Improve theme integration for OpenApi definition +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + +## 0.6.15 + +### Patch Changes + +- c982fc12cb: Adjusted some styles in the OpenAPI definition, for elements which were barely readable in dark mode. +- Updated dependencies + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.6.14 ### Patch Changes diff --git a/plugins/api-docs/README.md b/plugins/api-docs/README.md index d5ed198dc1..4919690568 100644 --- a/plugins/api-docs/README.md +++ b/plugins/api-docs/README.md @@ -160,6 +160,14 @@ by this plugin. Grab a copy of [oauth2-redirect.html](https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html) and put it in the `app/public/` directory in order to enable Swagger UI to complete this redirection. +This also may require you to adjust `Content Security Policy` header settings of your Backstage application, so that the script in `oauth2-redirect.html` can be executed. Since the script is static we can add the hash of it directly to our CSP policy, which we do by adding the following to the `csp` section of the app configuration: + +```yaml +script-src: + - "'self'" + - "'sha256-GeDavzSZ8O71Jggf/pQkKbt52dfZkrdNMQ3e+Ox+AkI='" # oauth2-redirect.html +``` + #### Configuring your OAuth2 Client You'll need to make sure your OAuth2 client has been registered in your OAuth2 Authentication Server (AS) diff --git a/plugins/api-docs/package.json b/plugins/api-docs/package.json index a4aa15c419..984b534850 100644 --- a/plugins/api-docs/package.json +++ b/plugins/api-docs/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-api-docs", "description": "A Backstage plugin that helps represent API entities in the frontend", - "version": "0.6.14", + "version": "0.6.17", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -30,19 +30,19 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@asyncapi/react-component": "^0.23.0", + "@asyncapi/react-component": "^1.0.0-next.25", "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog": "^0.7.3", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", "@types/react": "*", - "graphiql": "^1.0.0-alpha.10", - "graphql": "^15.3.0", + "graphiql": "^1.5.12", + "graphql": "^16.0.0", "isomorphic-form-data": "^2.0.0", "react": "^16.13.1", "react-dom": "^16.13.1", @@ -53,10 +53,10 @@ "swagger-ui-react": "^4.0.0-rc.3" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.test.tsx b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.test.tsx index cb89476c03..c9f979edad 100644 --- a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.test.tsx +++ b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.test.tsx @@ -18,6 +18,15 @@ import { renderInTestApp } from '@backstage/test-utils'; import React from 'react'; import { AsyncApiDefinition } from './AsyncApiDefinition'; +jest.mock('use-resize-observer', () => ({ + __esModule: true, + default: jest.fn().mockImplementation(() => ({ + observe: jest.fn(), + unobserve: jest.fn(), + disconnect: jest.fn(), + })), +})); + describe('', () => { it('renders asyncapi spec', async () => { const definition = ` @@ -45,15 +54,7 @@ components: expect(getByText(/Account Service/i)).toBeInTheDocument(); expect(getByText(/user\/signedup/i)).toBeInTheDocument(); - expect(getByText(/UserSignedUp/i)).toBeInTheDocument(); - expect(getAllByText(/displayName/i)).toHaveLength(4); - }); - - it('renders error if definition is missing', async () => { - const { getByText } = await renderInTestApp( - , - ); - expect(getByText(/Error/i)).toBeInTheDocument(); - expect(getByText(/Document can't be null or falsey/i)).toBeInTheDocument(); + expect(getAllByText(/UserSignedUp/i)).toHaveLength(2); + expect(getAllByText(/displayName/i)).toHaveLength(3); }); }); diff --git a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.tsx b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.tsx index 1c993f67d7..3f9375921d 100644 --- a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.tsx +++ b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinition.tsx @@ -15,23 +15,72 @@ */ import AsyncApi from '@asyncapi/react-component'; -import '@asyncapi/react-component/lib/styles/fiori.css'; -import { alpha, makeStyles } from '@material-ui/core/styles'; +import '@asyncapi/react-component/styles/default.css'; +import { makeStyles, alpha, darken } from '@material-ui/core/styles'; +import { BackstageTheme } from '@backstage/theme'; import React from 'react'; +import { useTheme } from '@material-ui/core'; -const useStyles = makeStyles(theme => ({ +const useStyles = makeStyles((theme: BackstageTheme) => ({ root: { - '& .asyncapi': { - 'font-family': 'inherit', + fontFamily: 'inherit', + '& .bg-white': { background: 'none', }, - '& h2': { - ...theme.typography.h6, + '& .text-4xl': { + ...theme.typography.h3, }, - '& .text-teal': { - color: theme.palette.primary.main, + ' & h2': { + ...theme.typography.h4, + }, + '& .border': { + borderColor: alpha(theme.palette.border, 0.1), + }, + '& .min-w-min': { + minWidth: 'fit-content', + }, + '& .examples': { + padding: '1rem', + }, + '& .bg-teal-500': { + backgroundColor: theme.palette.status.ok, + }, + '& .bg-blue-500': { + backgroundColor: theme.palette.info.main, + }, + '& .bg-blue-400': { + backgroundColor: theme.palette.info.light, + }, + '& .bg-indigo-400': { + backgroundColor: theme.palette.warning.main, + }, + '& .text-teal-50': { + color: theme.palette.status.ok, + }, + '& .text-red-600': { + color: theme.palette.error.main, + }, + '& .text-orange-600': { + color: theme.palette.warning.main, + }, + '& .text-teal-500': { + color: theme.palette.status.ok, + }, + '& .text-blue-500': { + color: theme.palette.info.main, + }, + '& .-rotate-90': { + '--tw-rotate': '0deg', }, '& button': { + ...theme.typography.button, + borderRadius: theme.shape.borderRadius, + color: theme.palette.primary.main, + }, + '& a': { + color: theme.palette.link, + }, + '& a.no-underline': { ...theme.typography.button, background: 'none', boxSizing: 'border-box', @@ -48,84 +97,47 @@ const useStyles = makeStyles(theme => ({ border: `1px solid ${alpha(theme.palette.primary.main, 0.5)}`, '&:hover': { textDecoration: 'none', - '&.Mui-disabled': { - backgroundColor: 'transparent', - }, border: `1px solid ${theme.palette.primary.main}`, backgroundColor: alpha( theme.palette.primary.main, theme.palette.action.hoverOpacity, ), - // Reset on touch devices, it doesn't add specificity - '@media (hover: none)': { - backgroundColor: 'transparent', - }, - }, - '&.Mui-disabled': { - color: theme.palette.action.disabled, }, }, - '& .asyncapi__collapse-button:hover': { - color: theme.palette.primary.main, - }, - '& button.asyncapi__toggle-button': { - 'min-width': 'inherit', - }, - '& .asyncapi__info-list li': { - 'border-color': theme.palette.primary.main, - '&:hover': { - color: theme.palette.text.primary, - 'border-color': theme.palette.primary.main, - 'background-color': theme.palette.primary.main, - }, - }, - '& .asyncapi__info-list li a': { - color: theme.palette.primary.main, - '&:hover': { + '& li.no-underline': { + '& a': { + textDecoration: 'none', color: theme.palette.getContrastText(theme.palette.primary.main), }, }, - '& .asyncapi__enum': { - color: theme.palette.secondary.main, + }, + dark: { + '& svg': { + fill: theme.palette.text.primary, }, - '& .asyncapi__info, .asyncapi__channel, .asyncapi__channels > div, .asyncapi__schema, .asyncapi__channel-operations-list .asyncapi__messages-list-item .asyncapi__message, .asyncapi__message, .asyncapi__server, .asyncapi__servers > div, .asyncapi__messages > div, .asyncapi__schemas > div': - { - 'background-color': 'inherit', - }, - '& .asyncapi__channel-parameters-header, .asyncapi__channel-operations-header, .asyncapi__channel-operation-oneOf-subscribe-header, .asyncapi__channel-operation-oneOf-publish-header, .asyncapi__channel-operation-message-header, .asyncapi__message-header, .asyncapi__message-header-title, .asyncapi__message-header-title > h3, .asyncapi__bindings, .asyncapi__bindings-header, .asyncapi__bindings-header > h4': - { - 'background-color': 'inherit', + '& .prose': { + color: theme.palette.text.secondary, + '& h3': { color: theme.palette.text.primary, }, - '& .asyncapi__additional-properties-notice': { - color: theme.palette.text.hint, }, - '& .asyncapi__code, .asyncapi__code-pre': { - background: theme.palette.background.default, + '& .bg-gray-100, .bg-gray-200': { + backgroundColor: theme.palette.background.default, }, - '& .asyncapi__schema-example-header-title': { - color: theme.palette.text.secondary, + '& .text-gray-600': { + color: theme.palette.grey['50'], }, - '& .asyncapi__message-headers-header, .asyncapi__message-payload-header, .asyncapi__server-variables-header, .asyncapi__server-security-header': - { - 'background-color': 'inherit', - color: theme.palette.text.secondary, + '& .text-gray-700': { + color: theme.palette.grey['100'], + }, + '& .panel--right': { + background: darken(theme.palette.navigation.background, 0.1), + }, + '& .examples': { + backgroundColor: darken(theme.palette.navigation.background, 0.1), + '& pre': { + backgroundColor: darken(theme.palette.background.default, 0.2), }, - '& .asyncapi__table-header': { - background: theme.palette.background.default, - }, - '& .asyncapi__table-body': { - color: theme.palette.text.primary, - }, - '& .asyncapi__server-security-flow': { - background: theme.palette.background.default, - border: 'none', - }, - '& .asyncapi__server-security-flows-list a': { - color: theme.palette.primary.main, - }, - '& .asyncapi__table-row--nested': { - color: theme.palette.text.secondary, }, }, })); @@ -134,11 +146,15 @@ type Props = { definition: string; }; -export const AsyncApiDefinition = ({ definition }: Props) => { +export const AsyncApiDefinition = ({ definition }: Props): JSX.Element => { const classes = useStyles(); + const theme = useTheme(); + const classNames = `${classes.root} ${ + theme.palette.type === 'dark' ? classes.dark : '' + }`; return ( -
+
); diff --git a/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinition.tsx b/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinition.tsx index 8d0accb254..601352f21a 100644 --- a/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinition.tsx +++ b/plugins/api-docs/src/components/OpenApiDefinitionWidget/OpenApiDefinition.tsx @@ -22,18 +22,9 @@ import 'swagger-ui-react/swagger-ui.css'; const useStyles = makeStyles(theme => ({ root: { '& .swagger-ui': { - fontFamily: 'inherit', + fontFamily: theme.typography.fontFamily, color: theme.palette.text.primary, - [`& .info h1, - .info h2, - .info h3, - .info h4, - .info h5, - .info h6`]: { - fontFamily: 'inherit', - color: theme.palette.text.primary, - }, [`& .scheme-container`]: { backgroundColor: theme.palette.background.default, }, @@ -41,7 +32,7 @@ const useStyles = makeStyles(theme => ({ .opblock-tag small, table thead tr td, table thead tr th`]: { - fontFamily: 'inherit', + fontFamily: theme.typography.fontFamily, color: theme.palette.text.primary, borderColor: theme.palette.divider, }, @@ -49,35 +40,30 @@ const useStyles = makeStyles(theme => ({ section.models.is-open h4`]: { borderColor: theme.palette.divider, }, - [`& .opblock .opblock-summary-description, - .parameter__type, - table.headers td, - .model-title, - .model .property.primitive, - section h3`]: { - fontFamily: 'inherit', - color: theme.palette.text.secondary, + [`& .model-title, + .model .renderedMarkdown, + .model .description`]: { + fontFamily: theme.typography.fontFamily, + fontWeight: theme.typography.fontWeightRegular, }, - [`& .opblock .opblock-summary-operation-id, - .opblock .opblock-summary-path, - .opblock .opblock-summary-path__deprecated, - .opblock h4, - .opblock h5, - .opblock a, - .opblock li, + [`& h1, h2, h3, h4, h5, h6, + .errors h4, .error h4, .opblock h4, section.models h4, + .response-control-media-type__accept-message, + .opblock-summary-description, + .opblock-summary-operation-id, + .opblock-summary-path, + .opblock-summary-path__deprecated, + .opblock-external-docs-wrapper, + .opblock-section-header .btn, + .opblock-section-header>label, + .scheme-container .schemes>label,a.nostyle, .parameter__name, .response-col_status, .response-col_links, - .opblock-section-header .btn, - .tab li, - .info li, - .info p, - .info table, - section.models h4, + .error .btn, .info .title, - table.model tr.description, - .property-row`]: { - fontFamily: 'inherit', + .info .base-url`]: { + fontFamily: theme.typography.fontFamily, color: theme.palette.text.primary, }, [`& .opblock .opblock-section-header, @@ -89,23 +75,57 @@ const useStyles = makeStyles(theme => ({ .parameter__in`]: { color: theme.palette.text.disabled, }, - [`& .opblock-description-wrapper p, - .opblock-description-wrapper li, - .opblock-external-docs-wrapper p, - .opblock-title_normal p, - .response-control-media-type__accept-message, - .opblock .opblock-section-header>label, - .scheme-container .schemes>label, - .info .base-url, - .model`]: { - color: theme.palette.text.hint, + [`& table.model, + .parameter__type, + .model.model-title, + .model-title, + .model span, + .model .brace-open, + .model .brace-close, + .model .property.primitive, + .model .renderedMarkdown, + .model .description, + .errors small`]: { + color: theme.palette.text.secondary, }, [`& .parameter__name.required:after`]: { color: theme.palette.warning.dark, }, - [`& .prop-type`]: { + [`& table.model, + table.model .model, + .opblock-external-docs-wrapper`]: { + fontSize: theme.typography.fontSize, + }, + [`& table.headers td`]: { + color: theme.palette.text.primary, + fontWeight: theme.typography.fontWeightRegular, + }, + [`& .model-hint`]: { + color: theme.palette.text.hint, + backgroundColor: theme.palette.background.paper, + }, + [`& .opblock-summary-method, + .info a`]: { + fontFamily: theme.typography.fontFamily, + }, + [`& .info, .opblock, .tab`]: { + [`& li, p`]: { + fontFamily: theme.typography.fontFamily, + color: theme.palette.text.primary, + }, + }, + [`& a`]: { color: theme.palette.primary.main, }, + [`& .renderedMarkdown code`]: { + color: theme.palette.secondary.light, + }, + [`& .property-row td:first-child`]: { + color: theme.palette.text.primary, + }, + [`& span.prop-type`]: { + color: theme.palette.success.light, + }, }, }, })); diff --git a/plugins/app-backend/package.json b/plugins/app-backend/package.json index ebb0393192..927eae7022 100644 --- a/plugins/app-backend/package.json +++ b/plugins/app-backend/package.json @@ -30,8 +30,8 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", - "@backstage/config-loader": "^0.8.0", + "@backstage/backend-common": "^0.9.12", + "@backstage/config-loader": "^0.8.1", "@backstage/config": "^0.1.11", "@backstage/types": "^0.1.1", "@types/express": "^4.17.6", @@ -42,7 +42,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/types": "^0.1.1", "@types/supertest": "^2.0.8", "msw": "^0.35.0", diff --git a/plugins/auth-backend/CHANGELOG.md b/plugins/auth-backend/CHANGELOG.md index 5dc0cdb861..d7492ba5b4 100644 --- a/plugins/auth-backend/CHANGELOG.md +++ b/plugins/auth-backend/CHANGELOG.md @@ -1,5 +1,41 @@ # @backstage/plugin-auth-backend +## 0.4.10 + +### Patch Changes + +- 4bf4111902: Migrated the SAML provider to implement the `authHandler` and `signIn.resolver` options. +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- 36fa32216f: Added signIn and authHandler resolver for oidc provider +- 7071dce02d: Expose catalog lib in plugin-auth-backend, i.e `CatalogIdentityClient` class is exposed now. +- 1b69ed44f2: Added custom OAuth2.0 authorization header for generic oauth2 provider. +- Updated dependencies + - @backstage/backend-common@0.9.12 + +## 0.4.9 + +### Patch Changes + +- 9312572360: Switched to using the standardized JSON error responses for all provider endpoints. +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/backend-common@0.9.11 + - @backstage/test-utils@0.1.23 + ## 0.4.8 ### Patch Changes diff --git a/plugins/auth-backend/api-report.md b/plugins/auth-backend/api-report.md index 35c93e9537..46d8b03cbb 100644 --- a/plugins/auth-backend/api-report.md +++ b/plugins/auth-backend/api-report.md @@ -14,7 +14,9 @@ import { Logger as Logger_2 } from 'winston'; import { PluginDatabaseManager } from '@backstage/backend-common'; import { PluginEndpointDiscovery } from '@backstage/backend-common'; import { Profile } from 'passport'; +import { TokenSet } from 'openid-client'; import { UserEntity } from '@backstage/catalog-model'; +import { UserinfoResponse } from 'openid-client'; // Warning: (ae-missing-release-tag) "AtlassianAuthProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -175,6 +177,20 @@ export const bitbucketUserIdSignInResolver: SignInResolver // @public (undocumented) export const bitbucketUsernameSignInResolver: SignInResolver; +// Warning: (ae-missing-release-tag) "CatalogIdentityClient" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public +export class CatalogIdentityClient { + constructor(options: { catalogApi: CatalogApi; tokenIssuer: TokenIssuer }); + // Warning: (ae-forgotten-export) The symbol "UserQuery" needs to be exported by the entry point index.d.ts + findUser(query: UserQuery): Promise; + // Warning: (ae-forgotten-export) The symbol "MemberClaimQuery" needs to be exported by the entry point index.d.ts + resolveCatalogMembership({ + entityRefs, + logger, + }: MemberClaimQuery): Promise; +} + // Warning: (ae-missing-release-tag) "createAtlassianProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -231,6 +247,14 @@ export const createOAuth2Provider: ( options?: OAuth2ProviderOptions | undefined, ) => AuthProviderFactory; +// Warning: (ae-forgotten-export) The symbol "OidcProviderOptions" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "createOidcProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export const createOidcProvider: ( + options?: OidcProviderOptions | undefined, +) => AuthProviderFactory; + // Warning: (ae-missing-release-tag) "createOktaProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -254,6 +278,11 @@ export function createRouter({ providerFactories, }: RouterOptions): Promise; +// @public (undocumented) +export const createSamlProvider: ( + options?: SamlProviderOptions | undefined, +) => AuthProviderFactory; + // Warning: (ae-missing-release-tag) "factories" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -271,6 +300,12 @@ export const encodeState: (state: OAuthState) => string; // @public (undocumented) export const ensuresXRequestedWith: (req: express.Request) => boolean; +// Warning: (ae-forgotten-export) The symbol "TokenParams" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "getEntityClaims" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export function getEntityClaims(entity: UserEntity): TokenParams['claims']; + // Warning: (ae-missing-release-tag) "GithubOAuthResult" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -548,6 +583,19 @@ export interface RouterOptions { providerFactories?: ProviderFactories; } +// @public (undocumented) +export type SamlAuthResult = { + fullProfile: any; +}; + +// @public (undocumented) +export type SamlProviderOptions = { + authHandler?: AuthHandler; + signIn?: { + resolver?: SignInResolver; + }; +}; + // Warning: (ae-missing-release-tag) "TokenIssuer" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public @@ -578,7 +626,6 @@ export type WebMessageResponse = // Warnings were encountered during analysis: // -// src/identity/types.d.ts:25:5 - (ae-forgotten-export) The symbol "TokenParams" needs to be exported by the entry point index.d.ts // src/identity/types.d.ts:31:9 - (ae-forgotten-export) The symbol "AnyJWK" needs to be exported by the entry point index.d.ts // src/providers/atlassian/provider.d.ts:37:5 - (ae-forgotten-export) The symbol "AuthHandler" needs to be exported by the entry point index.d.ts // src/providers/atlassian/provider.d.ts:42:9 - (ae-forgotten-export) The symbol "SignInResolver" needs to be exported by the entry point index.d.ts diff --git a/plugins/auth-backend/package.json b/plugins/auth-backend/package.json index 3a9e8102eb..6f95c9850a 100644 --- a/plugins/auth-backend/package.json +++ b/plugins/auth-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-auth-backend", "description": "A Backstage backend plugin that handles authentication", - "version": "0.4.8", + "version": "0.4.10", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -30,19 +30,18 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/errors": "^0.1.4", - "@backstage/test-utils": "^0.1.22", + "@backstage/errors": "^0.1.5", + "@backstage/test-utils": "^0.1.23", "@google-cloud/firestore": "^4.15.1", "@types/express": "^4.17.6", "@types/passport": "^1.0.3", "compression": "^1.7.4", "cookie-parser": "^1.4.5", "cors": "^2.8.5", - "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", "express-session": "^1.17.1", @@ -56,6 +55,7 @@ "luxon": "^2.0.2", "minimatch": "^3.0.3", "morgan": "^1.10.0", + "node-fetch": "^2.6.1", "node-cache": "^5.1.2", "openid-client": "^4.2.1", "passport": "^0.4.1", @@ -73,7 +73,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/body-parser": "^1.19.0", "@types/cookie-parser": "^1.4.2", "@types/express-session": "^1.17.2", diff --git a/plugins/auth-backend/src/identity/IdentityClient.ts b/plugins/auth-backend/src/identity/IdentityClient.ts index 2af30e4b6a..d60829bf59 100644 --- a/plugins/auth-backend/src/identity/IdentityClient.ts +++ b/plugins/auth-backend/src/identity/IdentityClient.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import { JWK, JWT, JWKS, JSONWebKey } from 'jose'; import { BackstageIdentity } from '../providers'; import { PluginEndpointDiscovery } from '@backstage/backend-common'; diff --git a/plugins/auth-backend/src/index.ts b/plugins/auth-backend/src/index.ts index 432da00142..894f8c1e55 100644 --- a/plugins/auth-backend/src/index.ts +++ b/plugins/auth-backend/src/index.ts @@ -31,3 +31,5 @@ export * from './lib/flow'; // OAuth wrapper over a passport or a custom `startegy`. export * from './lib/oauth'; + +export * from './lib/catalog'; diff --git a/plugins/auth-backend/src/providers/aws-alb/provider.test.ts b/plugins/auth-backend/src/providers/aws-alb/provider.test.ts index 2f5ffa1833..3f72004d48 100644 --- a/plugins/auth-backend/src/providers/aws-alb/provider.test.ts +++ b/plugins/auth-backend/src/providers/aws-alb/provider.test.ts @@ -50,7 +50,7 @@ const mockClaims = { }; jest.mock('jose'); -jest.mock('cross-fetch', () => ({ +jest.mock('node-fetch', () => ({ __esModule: true, default: async () => { return { diff --git a/plugins/auth-backend/src/providers/aws-alb/provider.ts b/plugins/auth-backend/src/providers/aws-alb/provider.ts index ac5db5e69f..b0b9070d50 100644 --- a/plugins/auth-backend/src/providers/aws-alb/provider.ts +++ b/plugins/auth-backend/src/providers/aws-alb/provider.ts @@ -21,7 +21,7 @@ import { SignInResolver, } from '../types'; import express from 'express'; -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import * as crypto from 'crypto'; import { KeyObject } from 'crypto'; import { Logger } from 'winston'; diff --git a/plugins/auth-backend/src/providers/index.ts b/plugins/auth-backend/src/providers/index.ts index 4a9221ce21..88c6ecb6fe 100644 --- a/plugins/auth-backend/src/providers/index.ts +++ b/plugins/auth-backend/src/providers/index.ts @@ -19,10 +19,12 @@ export * from './gitlab'; export * from './google'; export * from './microsoft'; export * from './oauth2'; +export * from './oidc'; export * from './okta'; export * from './bitbucket'; export * from './atlassian'; export * from './aws-alb'; +export * from './saml'; export { factories as defaultAuthProviderFactories } from './factories'; diff --git a/plugins/auth-backend/src/providers/oauth2/provider.ts b/plugins/auth-backend/src/providers/oauth2/provider.ts index cf70580664..1160ad19c9 100644 --- a/plugins/auth-backend/src/providers/oauth2/provider.ts +++ b/plugins/auth-backend/src/providers/oauth2/provider.ts @@ -85,6 +85,12 @@ export class OAuth2AuthProvider implements OAuthHandlers { tokenURL: options.tokenUrl, passReqToCallback: false as true, scope: options.scope, + customHeaders: { + Authorization: `Basic ${this.encodeClientCredentials( + options.clientId, + options.clientSecret, + )}`, + }, }, ( accessToken: any, @@ -187,6 +193,10 @@ export class OAuth2AuthProvider implements OAuthHandlers { return response; } + + encodeClientCredentials(clientID: string, clientSecret: string): string { + return Buffer.from(`${clientID}:${clientSecret}`).toString('base64'); + } } export const oAuth2DefaultSignInResolver: SignInResolver = async ( diff --git a/plugins/auth-backend/src/providers/oidc/index.ts b/plugins/auth-backend/src/providers/oidc/index.ts index 8c755cd501..20d014a783 100644 --- a/plugins/auth-backend/src/providers/oidc/index.ts +++ b/plugins/auth-backend/src/providers/oidc/index.ts @@ -15,4 +15,3 @@ */ export { createOidcProvider } from './provider'; -export type { OidcProviderOptions } from './provider'; diff --git a/plugins/auth-backend/src/providers/oidc/provider.test.ts b/plugins/auth-backend/src/providers/oidc/provider.test.ts index ac5035e9a5..da96ae1a25 100644 --- a/plugins/auth-backend/src/providers/oidc/provider.test.ts +++ b/plugins/auth-backend/src/providers/oidc/provider.test.ts @@ -24,7 +24,8 @@ import { setupServer } from 'msw/node'; import { ClientMetadata, IssuerMetadata } from 'openid-client'; import { OAuthAdapter } from '../../lib/oauth'; import { AuthProviderFactoryOptions } from '../types'; -import { createOidcProvider, OidcAuthProvider } from './provider'; +import { createOidcProvider, OidcAuthProvider, Options } from './provider'; +import { getVoidLogger } from '@backstage/backend-common'; const issuerMetadata = { issuer: 'https://oidc.test', @@ -42,7 +43,23 @@ const issuerMetadata = { request_object_signing_alg_values_supported: ['RS256', 'RS512', 'HS256'], }; -const clientMetadata = { +const catalogIdentityClient = { + findUser: jest.fn(), +}; +const tokenIssuer = { + issueToken: jest.fn(), + listPublicKeys: jest.fn(), +}; + +const clientMetadata: Options = { + authHandler: async input => ({ + profile: { + displayName: input.userinfo.email, + }, + }), + catalogIdentityClient: catalogIdentityClient as unknown as any, + logger: getVoidLogger(), + tokenIssuer: tokenIssuer as unknown as any, callbackUrl: 'https://oidc.test/callback', clientId: 'testclientid', clientSecret: 'testclientsecret', @@ -160,7 +177,7 @@ describe('OidcAuthProvider', () => { ...clientMetadata, metadataUrl: 'https://oidc.test/.well-known/openid-configuration', }, - }); + } as any); const options = { globalConfig: { appUrl: 'https://oidc.test', diff --git a/plugins/auth-backend/src/providers/oidc/provider.ts b/plugins/auth-backend/src/providers/oidc/provider.ts index 092ffa7099..eba9c72e41 100644 --- a/plugins/auth-backend/src/providers/oidc/provider.ts +++ b/plugins/auth-backend/src/providers/oidc/provider.ts @@ -16,28 +16,36 @@ import express from 'express'; import { - Issuer, Client, + Issuer, Strategy as OidcStrategy, TokenSet, UserinfoResponse, } from 'openid-client'; import { - OAuthAdapter, - OAuthProviderOptions, - OAuthHandlers, - OAuthResponse, - OAuthEnvironmentHandler, - OAuthStartRequest, encodeState, + OAuthAdapter, + OAuthEnvironmentHandler, + OAuthHandlers, + OAuthProviderOptions, OAuthRefreshRequest, + OAuthResponse, + OAuthStartRequest, } from '../../lib/oauth'; import { executeFrameHandlerStrategy, executeRedirectStrategy, PassportDoneCallback, } from '../../lib/passport'; -import { RedirectInfo, AuthProviderFactory } from '../types'; +import { + AuthHandler, + AuthProviderFactory, + RedirectInfo, + SignInResolver, +} from '../types'; +import { CatalogIdentityClient } from '../../lib/catalog'; +import { TokenIssuer } from '../../identity'; +import { Logger } from 'winston'; type PrivateInfo = { refreshToken?: string; @@ -58,6 +66,11 @@ export type Options = OAuthProviderOptions & { scope?: string; prompt?: string; tokenSignedResponseAlg?: string; + signInResolver?: SignInResolver; + authHandler: AuthHandler; + tokenIssuer: TokenIssuer; + catalogIdentityClient: CatalogIdentityClient; + logger: Logger; }; export class OidcAuthProvider implements OAuthHandlers { @@ -65,16 +78,26 @@ export class OidcAuthProvider implements OAuthHandlers { private readonly scope?: string; private readonly prompt?: string; + private readonly signInResolver?: SignInResolver; + private readonly authHandler: AuthHandler; + private readonly tokenIssuer: TokenIssuer; + private readonly catalogIdentityClient: CatalogIdentityClient; + private readonly logger: Logger; + constructor(options: Options) { this.implementation = this.setupStrategy(options); this.scope = options.scope; this.prompt = options.prompt; + this.signInResolver = options.signInResolver; + this.authHandler = options.authHandler; + this.tokenIssuer = options.tokenIssuer; + this.catalogIdentityClient = options.catalogIdentityClient; + this.logger = options.logger; } async start(req: OAuthStartRequest): Promise { const { strategy } = await this.implementation; const options: Record = { - accessType: 'offline', scope: req.scope || this.scope || 'openid profile email', state: encodeState(req.state), }; @@ -97,19 +120,8 @@ export class OidcAuthProvider implements OAuthHandlers { result: { userinfo, tokenset }, privateInfo, } = strategyResponse; - const identityResponse = await this.populateIdentity({ - profile: { - displayName: userinfo.name, - email: userinfo.email, - picture: userinfo.picture, - }, - providerInfo: { - idToken: tokenset.id_token, - accessToken: tokenset.access_token || '', - scope: tokenset.scope || '', - expiresInSeconds: tokenset.expires_in, - }, - }); + + const identityResponse = await this.handleResult({ tokenset, userinfo }); return { response: identityResponse, refreshToken: privateInfo.refreshToken, @@ -123,22 +135,13 @@ export class OidcAuthProvider implements OAuthHandlers { throw new Error('Refresh failed'); } const profile = await client.userinfo(tokenset.access_token); - - return this.populateIdentity({ - providerInfo: { - accessToken: tokenset.access_token, - refreshToken: tokenset.refresh_token, - expiresInSeconds: tokenset.expires_in, - idToken: tokenset.id_token, - scope: tokenset.scope || '', - }, - profile, - }); + return this.handleResult({ tokenset, userinfo: profile }); } private async setupStrategy(options: Options): Promise { const issuer = await Issuer.discover(options.metadataUrl); const client = new issuer.Client({ + access_type: 'offline', // this option must be passed to provider to receive a refresh token client_id: options.clientId, client_secret: options.clientSecret, redirect_uris: [options.callbackUrl], @@ -177,26 +180,70 @@ export class OidcAuthProvider implements OAuthHandlers { // Use this function to grab the user profile info from the token // Then populate the profile with it - private async populateIdentity( - response: OAuthResponse, - ): Promise { - const { profile } = response; - - if (!profile.email) { - throw new Error('Profile does not contain an email'); + private async handleResult(result: AuthResult): Promise { + const { profile } = await this.authHandler(result); + const response: OAuthResponse = { + providerInfo: { + idToken: result.tokenset.id_token, + accessToken: result.tokenset.access_token!, + refreshToken: result.tokenset.refresh_token, + scope: result.tokenset.scope!, + expiresInSeconds: result.tokenset.expires_in, + }, + profile, + }; + if (this.signInResolver) { + response.backstageIdentity = await this.signInResolver( + { + result, + profile, + }, + { + tokenIssuer: this.tokenIssuer, + catalogIdentityClient: this.catalogIdentityClient, + logger: this.logger, + }, + ); } - const id = profile.email.split('@')[0]; - - return { ...response, backstageIdentity: { id } }; + return response; } } -export type OidcProviderOptions = {}; +export const oAuth2DefaultSignInResolver: SignInResolver = async ( + info, + ctx, +) => { + const { profile } = info; + + if (!profile.email) { + throw new Error('Profile contained no email'); + } + const userId = profile.email.split('@')[0]; + const token = await ctx.tokenIssuer.issueToken({ + claims: { sub: userId, ent: [`user:default/${userId}`] }, + }); + return { id: userId, token }; +}; + +export type OidcProviderOptions = { + authHandler?: AuthHandler; + + signIn?: { + resolver?: SignInResolver; + }; +}; export const createOidcProvider = ( - _options?: OidcProviderOptions, + options?: OidcProviderOptions, ): AuthProviderFactory => { - return ({ providerId, globalConfig, config, tokenIssuer }) => + return ({ + providerId, + globalConfig, + config, + tokenIssuer, + catalogApi, + logger, + }) => OAuthEnvironmentHandler.mapConfig(config, envConfig => { const clientId = envConfig.getString('clientId'); const clientSecret = envConfig.getString('clientSecret'); @@ -207,6 +254,28 @@ export const createOidcProvider = ( ); const scope = envConfig.getOptionalString('scope'); const prompt = envConfig.getOptionalString('prompt'); + const catalogIdentityClient = new CatalogIdentityClient({ + catalogApi, + tokenIssuer, + }); + + const authHandler: AuthHandler = options?.authHandler + ? options.authHandler + : async ({ userinfo }) => ({ + profile: { + displayName: userinfo.name, + email: userinfo.email, + picture: userinfo.picture, + }, + }); + const signInResolverFn = + options?.signIn?.resolver ?? oAuth2DefaultSignInResolver; + const signInResolver: SignInResolver = info => + signInResolverFn(info, { + catalogIdentityClient, + tokenIssuer, + logger, + }); const provider = new OidcAuthProvider({ clientId, @@ -216,6 +285,11 @@ export const createOidcProvider = ( metadataUrl, scope, prompt, + signInResolver, + authHandler, + logger, + tokenIssuer, + catalogIdentityClient, }); return OAuthAdapter.fromConfig(globalConfig, provider, { diff --git a/plugins/auth-backend/src/providers/saml/index.ts b/plugins/auth-backend/src/providers/saml/index.ts index fa5d9d9a82..0aea660941 100644 --- a/plugins/auth-backend/src/providers/saml/index.ts +++ b/plugins/auth-backend/src/providers/saml/index.ts @@ -15,4 +15,4 @@ */ export { createSamlProvider } from './provider'; -export type { SamlProviderOptions } from './provider'; +export type { SamlProviderOptions, SamlAuthResult } from './provider'; diff --git a/plugins/auth-backend/src/providers/saml/provider.ts b/plugins/auth-backend/src/providers/saml/provider.ts index 8929a1dbf0..3ab00ce401 100644 --- a/plugins/auth-backend/src/providers/saml/provider.ts +++ b/plugins/auth-backend/src/providers/saml/provider.ts @@ -26,31 +26,52 @@ import { executeRedirectStrategy, PassportDoneCallback, } from '../../lib/passport'; -import { AuthProviderRouteHandlers, AuthProviderFactory } from '../types'; +import { + AuthProviderRouteHandlers, + AuthProviderFactory, + AuthHandler, + SignInResolver, + AuthResponse, +} from '../types'; import { postMessageResponse } from '../../lib/flow'; import { TokenIssuer } from '../../identity/types'; import { isError } from '@backstage/errors'; +import { CatalogIdentityClient } from '../../lib/catalog'; +import { Logger } from 'winston'; -type SamlInfo = { +/** @public */ +export type SamlAuthResult = { fullProfile: any; }; type Options = SamlConfig & { + signInResolver?: SignInResolver; + authHandler: AuthHandler; tokenIssuer: TokenIssuer; + catalogIdentityClient: CatalogIdentityClient; + logger: Logger; appUrl: string; }; export class SamlAuthProvider implements AuthProviderRouteHandlers { private readonly strategy: SamlStrategy; + private readonly signInResolver?: SignInResolver; + private readonly authHandler: AuthHandler; private readonly tokenIssuer: TokenIssuer; + private readonly catalogIdentityClient: CatalogIdentityClient; + private readonly logger: Logger; private readonly appUrl: string; constructor(options: Options) { this.appUrl = options.appUrl; + this.signInResolver = options.signInResolver; + this.authHandler = options.authHandler; this.tokenIssuer = options.tokenIssuer; + this.catalogIdentityClient = options.catalogIdentityClient; + this.logger = options.logger; this.strategy = new SamlStrategy({ ...options }, (( fullProfile: SamlProfile, - done: PassportDoneCallback, + done: PassportDoneCallback, ) => { // TODO: There's plenty more validation and profile handling to do here, // this provider is currently only intended to validate the provider pattern @@ -71,27 +92,35 @@ export class SamlAuthProvider implements AuthProviderRouteHandlers { res: express.Response, ): Promise { try { - const { result } = await executeFrameHandlerStrategy( + const { result } = await executeFrameHandlerStrategy( req, this.strategy, ); - const id = result.fullProfile.nameID; + const { profile } = await this.authHandler(result); - const idToken = await this.tokenIssuer.issueToken({ - claims: { sub: id }, - }); + const response: AuthResponse<{}> = { + profile, + providerInfo: {}, + }; + + if (this.signInResolver) { + response.backstageIdentity = await this.signInResolver( + { + result, + profile, + }, + { + tokenIssuer: this.tokenIssuer, + catalogIdentityClient: this.catalogIdentityClient, + logger: this.logger, + }, + ); + } return postMessageResponse(res, this.appUrl, { type: 'authorization_response', - response: { - profile: { - email: result.fullProfile.email, - displayName: result.fullProfile.displayName, - }, - providerInfo: {}, - backstageIdentity: { id, idToken }, - }, + response, }); } catch (error) { const { name, message } = isError(error) @@ -105,30 +134,88 @@ export class SamlAuthProvider implements AuthProviderRouteHandlers { } async logout(_req: express.Request, res: express.Response): Promise { - res.send('noop'); - } - - identifyEnv(): string | undefined { - return undefined; + res.end(); } } +const samlDefaultSignInResolver: SignInResolver = async ( + info, + ctx, +) => { + const id = info.result.fullProfile.nameID; + + const token = await ctx.tokenIssuer.issueToken({ + claims: { sub: id }, + }); + + return { id, token }; +}; + type SignatureAlgorithm = 'sha1' | 'sha256' | 'sha512'; -export type SamlProviderOptions = {}; +/** @public */ +export type SamlProviderOptions = { + /** + * The profile transformation function used to verify and convert the auth response + * into the profile that will be presented to the user. + */ + authHandler?: AuthHandler; + /** + * Configure sign-in for this provider, without it the provider can not be used to sign users in. + */ + signIn?: { + /** + * Maps an auth result to a Backstage identity for the user. + */ + resolver?: SignInResolver; + }; +}; + +/** @public */ export const createSamlProvider = ( - _options?: SamlProviderOptions, + options?: SamlProviderOptions, ): AuthProviderFactory => { - return ({ providerId, globalConfig, config, tokenIssuer }) => { - const opts = { + return ({ + providerId, + globalConfig, + config, + tokenIssuer, + catalogApi, + logger, + }) => { + const catalogIdentityClient = new CatalogIdentityClient({ + catalogApi, + tokenIssuer, + }); + + const authHandler: AuthHandler = options?.authHandler + ? options.authHandler + : async ({ fullProfile }) => ({ + profile: { + email: fullProfile.email, + displayName: fullProfile.displayName, + }, + }); + + const signInResolverFn = + options?.signIn?.resolver ?? samlDefaultSignInResolver; + + const signInResolver: SignInResolver = info => + signInResolverFn(info, { + catalogIdentityClient, + tokenIssuer, + logger, + }); + + return new SamlAuthProvider({ callbackUrl: `${globalConfig.baseUrl}/${providerId}/handler/frame`, entryPoint: config.getString('entryPoint'), logoutUrl: config.getOptionalString('logoutUrl'), audience: config.getOptionalString('audience'), issuer: config.getString('issuer'), cert: config.getString('cert'), - privateCert: config.getOptionalString('privateKey'), + privateKey: config.getOptionalString('privateKey'), authnContext: config.getOptionalStringArray('authnContext'), identifierFormat: config.getOptionalString('identifierFormat'), decryptionPvk: config.getOptionalString('decryptionPvk'), @@ -140,8 +227,10 @@ export const createSamlProvider = ( tokenIssuer, appUrl: globalConfig.appUrl, - }; - - return new SamlAuthProvider(opts); + authHandler, + signInResolver, + logger, + catalogIdentityClient, + }); }; }; diff --git a/plugins/azure-devops-backend/CHANGELOG.md b/plugins/azure-devops-backend/CHANGELOG.md index 06fc4833c4..9c94a04a68 100644 --- a/plugins/azure-devops-backend/CHANGELOG.md +++ b/plugins/azure-devops-backend/CHANGELOG.md @@ -1,5 +1,47 @@ # @backstage/plugin-azure-devops-backend +## 0.2.3 + +### Patch Changes + +- 82cd709fdb: **Backend** + + - Created new `/dashboard-pull-requests/:projectName` endpoint + - Created new `/all-teams` endpoint + - Implemented pull request policy evaluation conversion + + **Frontend** + + - Refactored `PullRequestsPage` and added new properties for `projectName` and `pollingInterval` + - Fixed spacing issue between repo link and creation date in `PullRequestCard` + - Added missing condition to `PullRequestCardPolicy` for `RequiredReviewers` + - Updated `useDashboardPullRequests` hook to implement long polling for pull requests + +- Updated dependencies + - @backstage/plugin-azure-devops-common@0.1.1 + - @backstage/backend-common@0.9.12 + +## 0.2.2 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/backend-common@0.9.11 + ## 0.2.1 ### Patch Changes diff --git a/plugins/azure-devops-backend/api-report.md b/plugins/azure-devops-backend/api-report.md index 1eabccc720..19d96dc728 100644 --- a/plugins/azure-devops-backend/api-report.md +++ b/plugins/azure-devops-backend/api-report.md @@ -5,12 +5,14 @@ ```ts import { Build } from 'azure-devops-node-api/interfaces/BuildInterfaces'; import { Config } from '@backstage/config'; +import { DashboardPullRequest } from '@backstage/plugin-azure-devops-common'; import express from 'express'; import { GitRepository } from 'azure-devops-node-api/interfaces/GitInterfaces'; import { Logger as Logger_2 } from 'winston'; import { PullRequest } from '@backstage/plugin-azure-devops-common'; import { PullRequestOptions } from '@backstage/plugin-azure-devops-common'; import { RepoBuild } from '@backstage/plugin-azure-devops-common'; +import { Team } from '@backstage/plugin-azure-devops-common'; import { WebApi } from 'azure-devops-node-api'; // Warning: (ae-missing-release-tag) "AzureDevOpsApi" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -19,12 +21,19 @@ import { WebApi } from 'azure-devops-node-api'; export class AzureDevOpsApi { constructor(logger: Logger_2, webApi: WebApi); // (undocumented) + getAllTeams(): Promise; + // (undocumented) getBuildList( projectName: string, repoId: string, top: number, ): Promise; // (undocumented) + getDashboardPullRequests( + projectName: string, + options: PullRequestOptions, + ): Promise; + // (undocumented) getGitRepository( projectName: string, repoName: string, diff --git a/plugins/azure-devops-backend/package.json b/plugins/azure-devops-backend/package.json index 6d213cbce6..c587f97837 100644 --- a/plugins/azure-devops-backend/package.json +++ b/plugins/azure-devops-backend/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-azure-devops-backend", - "version": "0.2.1", + "version": "0.2.3", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,9 +20,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/config": "^0.1.11", - "@backstage/plugin-azure-devops-common": "^0.1.0", + "@backstage/plugin-azure-devops-common": "^0.1.1", "@types/express": "^4.17.6", "azure-devops-node-api": "^11.0.1", "express": "^4.17.1", @@ -31,7 +31,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/supertest": "^2.0.8", "supertest": "^4.0.2", "msw": "^0.35.0" diff --git a/plugins/azure-devops-backend/src/api/AzureDevOpsApi.ts b/plugins/azure-devops-backend/src/api/AzureDevOpsApi.ts index 23ea3311f0..53dc19c68d 100644 --- a/plugins/azure-devops-backend/src/api/AzureDevOpsApi.ts +++ b/plugins/azure-devops-backend/src/api/AzureDevOpsApi.ts @@ -17,19 +17,30 @@ import { BuildResult, BuildStatus, + DashboardPullRequest, + Policy, PullRequest, PullRequestOptions, RepoBuild, + Team, } from '@backstage/plugin-azure-devops-common'; import { GitPullRequest, GitPullRequestSearchCriteria, GitRepository, } from 'azure-devops-node-api/interfaces/GitInterfaces'; +import { + convertDashboardPullRequest, + convertPolicy, + getArtifactId, +} from '../utils'; import { Build } from 'azure-devops-node-api/interfaces/BuildInterfaces'; import { Logger } from 'winston'; +import { PolicyEvaluationRecord } from 'azure-devops-node-api/interfaces/PolicyInterfaces'; +import { TeamMember } from 'azure-devops-node-api/interfaces/common/VSSInterfaces'; import { WebApi } from 'azure-devops-node-api'; +import { WebApiTeam } from 'azure-devops-node-api/interfaces/CoreInterfaces'; export class AzureDevOpsApi { public constructor( @@ -138,6 +149,115 @@ export class AzureDevOpsApi { return pullRequests; } + + public async getDashboardPullRequests( + projectName: string, + options: PullRequestOptions, + ): Promise { + this.logger?.debug( + `Getting dashboard pull requests for project '${projectName}'.`, + ); + + const client = await this.webApi.getGitApi(); + + const searchCriteria: GitPullRequestSearchCriteria = { + status: options.status, + }; + + const gitPullRequests: GitPullRequest[] = + await client.getPullRequestsByProject( + projectName, + searchCriteria, + undefined, + undefined, + options.top, + ); + + return Promise.all( + gitPullRequests.map(async gitPullRequest => { + const projectId = gitPullRequest.repository?.project?.id; + const prId = gitPullRequest.pullRequestId; + + let policies: Policy[] | undefined; + + if (projectId && prId) { + policies = await this.getPullRequestPolicies( + projectName, + projectId, + prId, + ); + } + + return convertDashboardPullRequest( + gitPullRequest, + this.webApi.serverUrl, + policies, + ); + }), + ); + } + + private async getPullRequestPolicies( + projectName: string, + projectId: string, + pullRequestId: number, + ): Promise { + this.logger?.debug( + `Getting pull request policies for pull request id '${pullRequestId}'.`, + ); + + const client = await this.webApi.getPolicyApi(); + + const artifactId = getArtifactId(projectId, pullRequestId); + + const policyEvaluationRecords: PolicyEvaluationRecord[] = + await client.getPolicyEvaluations(projectName, artifactId); + + return policyEvaluationRecords + .map(convertPolicy) + .filter((policy): policy is Policy => Boolean(policy)); + } + + public async getAllTeams(): Promise { + this.logger?.debug('Getting all teams.'); + + const client = await this.webApi.getCoreApi(); + const webApiTeams: WebApiTeam[] = await client.getAllTeams(); + + const teams: Team[] = await Promise.all( + webApiTeams.map(async team => ({ + id: team.id, + name: team.name, + memberIds: await this.getTeamMemberIds(team), + })), + ); + + return teams.sort((a, b) => + a.name && b.name ? a.name.localeCompare(b.name) : 0, + ); + } + + private async getTeamMemberIds( + team: WebApiTeam, + ): Promise { + this.logger?.debug(`Getting team member ids for team '${team.name}'.`); + + if (!team.projectId || !team.id) { + return undefined; + } + + const client = await this.webApi.getCoreApi(); + + const teamMembers: TeamMember[] = + await client.getTeamMembersWithExtendedProperties( + team.projectId, + team.id, + ); + + return teamMembers + .map(teamMember => teamMember.identity?.id) + .filter((id): id is string => Boolean(id)); + } } export function mappedRepoBuild(build: Build): RepoBuild { diff --git a/plugins/azure-devops-backend/src/service/router.ts b/plugins/azure-devops-backend/src/service/router.ts index d61148b4ff..57d54df18f 100644 --- a/plugins/azure-devops-backend/src/service/router.ts +++ b/plugins/azure-devops-backend/src/service/router.ts @@ -15,6 +15,7 @@ */ import { + DashboardPullRequest, PullRequestOptions, PullRequestStatus, } from '@backstage/plugin-azure-devops-common'; @@ -27,7 +28,7 @@ import Router from 'express-promise-router'; import { errorHandler } from '@backstage/backend-common'; import express from 'express'; -const DEFAULT_TOP: number = 10; +const DEFAULT_TOP = 10; export interface RouterOptions { azureDevOpsApi?: AzureDevOpsApi; @@ -80,33 +81,69 @@ export async function createRouter( router.get('/repo-builds/:projectName/:repoName', async (req, res) => { const { projectName, repoName } = req.params; + const top = req.query.top ? Number(req.query.top) : DEFAULT_TOP; + const gitRepository = await azureDevOpsApi.getRepoBuilds( projectName, repoName, top, ); + res.status(200).json(gitRepository); }); router.get('/pull-requests/:projectName/:repoName', async (req, res) => { const { projectName, repoName } = req.params; + const top = req.query.top ? Number(req.query.top) : DEFAULT_TOP; + const status = req.query.status ? Number(req.query.status) : PullRequestStatus.Active; + const pullRequestOptions: PullRequestOptions = { top: top, status: status, }; + const gitPullRequest = await azureDevOpsApi.getPullRequests( projectName, repoName, pullRequestOptions, ); + res.status(200).json(gitPullRequest); }); + router.get('/dashboard-pull-requests/:projectName', async (req, res) => { + const { projectName } = req.params; + + const top = req.query.top ? Number(req.query.top) : DEFAULT_TOP; + + const status = req.query.status + ? Number(req.query.status) + : PullRequestStatus.Active; + + const pullRequestOptions: PullRequestOptions = { + top: top, + status: status, + }; + + const pullRequests: DashboardPullRequest[] = + await azureDevOpsApi.getDashboardPullRequests( + projectName, + pullRequestOptions, + ); + + res.status(200).json(pullRequests); + }); + + router.get('/all-teams', async (_req, res) => { + const allTeams = await azureDevOpsApi.getAllTeams(); + res.status(200).json(allTeams); + }); + router.use(errorHandler()); return router; } diff --git a/plugins/azure-devops-backend/src/utils/azure-devops-utils.test.ts b/plugins/azure-devops-backend/src/utils/azure-devops-utils.test.ts new file mode 100644 index 0000000000..8aed436710 --- /dev/null +++ b/plugins/azure-devops-backend/src/utils/azure-devops-utils.test.ts @@ -0,0 +1,161 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + DashboardPullRequest, + PullRequestStatus, + PullRequestVoteStatus, +} from '@backstage/plugin-azure-devops-common'; +import { + convertDashboardPullRequest, + getArtifactId, + getAvatarUrl, + getPullRequestLink, +} from './azure-devops-utils'; + +import { GitPullRequest } from 'azure-devops-node-api/interfaces/GitInterfaces'; + +describe('convertDashboardPullRequest', () => { + it('should return DashboardPullRequest', () => { + const baseUrl = 'https://dev.azure.com'; + + const pullRequest: GitPullRequest = { + pullRequestId: 1, + title: 'Pull Request 1', + description: 'Test description', + repository: { + id: 'repo1', + name: 'azure-devops', + url: 'https://dev.azure.com/backstage/backstage/_apis/git/repositories/azure-devops', + project: { + name: 'backstage', + }, + }, + createdBy: { + id: 'user1', + displayName: 'User 1', + uniqueName: 'user1@backstage.io', + _links: { + avatar: { + href: 'avatar-href', + }, + }, + imageUrl: 'avatar-url', + }, + reviewers: [ + { + id: 'user2', + displayName: 'User 2', + _links: { + avatar: { + href: 'avatar-href', + }, + }, + isRequired: true, + isContainer: false, + vote: 10, + }, + ], + creationDate: new Date('2021-10-15T09:30:00.0000000Z'), + status: PullRequestStatus.Active, + isDraft: false, + completionOptions: {}, + }; + + const expectedPullRequest: DashboardPullRequest = { + pullRequestId: 1, + title: 'Pull Request 1', + description: 'Test description', + repository: { + id: 'repo1', + name: 'azure-devops', + url: 'https://dev.azure.com/backstage/backstage/_git/azure-devops', + }, + createdBy: { + id: 'user1', + displayName: 'User 1', + uniqueName: 'user1@backstage.io', + imageUrl: 'avatar-href', + }, + hasAutoComplete: true, + policies: [], + reviewers: [ + { + id: 'user2', + displayName: 'User 2', + imageUrl: 'avatar-href', + isRequired: true, + isContainer: false, + voteStatus: PullRequestVoteStatus.Approved, + }, + ], + creationDate: '2021-10-15T09:30:00.000Z', + status: PullRequestStatus.Active, + isDraft: false, + link: 'https://dev.azure.com/backstage/_git/azure-devops/pullrequest/1', + }; + + const result = convertDashboardPullRequest(pullRequest, baseUrl, []); + expect(result).toEqual(expectedPullRequest); + }); +}); + +describe('getPullRequestLink', () => { + it('should return pull request link', () => { + const baseUrl = 'dev.azure.com'; + const pullRequest = { + pullRequestId: 1, + repository: { + name: 'azure-devops', + project: { + name: 'backstage', + }, + }, + }; + const result = getPullRequestLink(baseUrl, pullRequest); + expect(result).toBe(`${baseUrl}/backstage/_git/azure-devops/pullrequest/1`); + }); +}); + +describe('getAvatarUrl', () => { + it('should return avatar href', () => { + const identity = { + _links: { + avatar: { + href: 'avatar-href', + }, + }, + imageUrl: 'avatar-url', + }; + const result = getAvatarUrl(identity); + expect(result).toBe('avatar-href'); + }); + + it('should return avatar image url', () => { + const identity = { + imageUrl: 'avatar-url', + }; + const result = getAvatarUrl(identity); + expect(result).toBe('avatar-url'); + }); +}); + +describe('getArtifactId', () => { + it('should return artifact id', () => { + const result = getArtifactId('project1', 1); + expect(result).toBe('vstfs:///CodeReview/CodeReviewId/project1/1'); + }); +}); diff --git a/plugins/azure-devops-backend/src/utils/azure-devops-utils.ts b/plugins/azure-devops-backend/src/utils/azure-devops-utils.ts new file mode 100644 index 0000000000..aa843e9c17 --- /dev/null +++ b/plugins/azure-devops-backend/src/utils/azure-devops-utils.ts @@ -0,0 +1,264 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + CreatedBy, + DashboardPullRequest, + Policy, + PolicyEvaluationStatus, + PolicyType, + PolicyTypeId, + PullRequestVoteStatus, + Repository, + Reviewer, +} from '@backstage/plugin-azure-devops-common'; +import { + GitPullRequest, + GitRepository, + IdentityRefWithVote, +} from 'azure-devops-node-api/interfaces/GitInterfaces'; + +import { IdentityRef } from 'azure-devops-node-api/interfaces/common/VSSInterfaces'; +import { PolicyEvaluationRecord } from 'azure-devops-node-api/interfaces/PolicyInterfaces'; + +export function convertDashboardPullRequest( + pullRequest: GitPullRequest, + baseUrl: string, + policies: Policy[] | undefined, +): DashboardPullRequest { + return { + pullRequestId: pullRequest.pullRequestId, + title: pullRequest.title, + description: pullRequest.description, + repository: convertRepository(pullRequest.repository), + createdBy: convertCreatedBy(pullRequest.createdBy), + hasAutoComplete: hasAutoComplete(pullRequest), + policies, + reviewers: convertReviewers(pullRequest.reviewers), + creationDate: pullRequest.creationDate?.toISOString(), + status: pullRequest.status, + isDraft: pullRequest.isDraft, + link: getPullRequestLink(baseUrl, pullRequest), + }; +} + +export function getPullRequestLink( + baseUrl: string, + pullRequest: GitPullRequest, +): string | undefined { + const projectName = pullRequest.repository?.project?.name; + const repoName = pullRequest.repository?.name; + const pullRequestId = pullRequest.pullRequestId; + + if (!projectName || !repoName || !pullRequestId) { + return undefined; + } + + const encodedProjectName = encodeURIComponent(projectName); + const encodedRepoName = encodeURIComponent(repoName); + + return `${baseUrl}/${encodedProjectName}/_git/${encodedRepoName}/pullrequest/${pullRequestId}`; +} + +/** + * Tries to get the avatar from the new property if not then falls-back to deprecated `imageUrl`. + * https://docs.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/get-pull-requests-by-project?view=azure-devops-rest-6.0#identityref + */ +export function getAvatarUrl(identity: IdentityRef): string | undefined { + return identity._links?.avatar?.href ?? identity.imageUrl; +} + +export function getArtifactId( + projectId: string, + pullRequestId: number, +): string { + return `vstfs:///CodeReview/CodeReviewId/${projectId}/${pullRequestId}`; +} + +export function convertPolicy( + policyEvaluationRecord: PolicyEvaluationRecord, +): Policy | undefined { + const policyConfig = policyEvaluationRecord.configuration; + const policyStatus = policyEvaluationRecord.status; + + if (!policyConfig) { + return undefined; + } + + if ( + !( + policyConfig.isEnabled && + !policyConfig.isDeleted && + (policyConfig.isBlocking || + policyConfig.type?.id === PolicyType.Status) && // Optional "Status" policies are actually required for automatic completion. + policyStatus !== PolicyEvaluationStatus.Approved + ) + ) { + return undefined; + } + + const policyTypeId = policyConfig.type?.id; + + if (!policyTypeId) { + return undefined; + } + + const policyType: PolicyType | undefined = ( + { + [PolicyTypeId.Build]: PolicyType.Build, + [PolicyTypeId.Status]: PolicyType.Status, + [PolicyTypeId.MinimumReviewers]: PolicyType.MinimumReviewers, + [PolicyTypeId.Comments]: PolicyType.Comments, + [PolicyTypeId.RequiredReviewers]: PolicyType.RequiredReviewers, + [PolicyTypeId.MergeStrategy]: PolicyType.MergeStrategy, + } as Record + )[policyTypeId]; + + if (!policyType) { + return undefined; + } + + const policyConfigSettings = policyConfig.settings; + let policyText = policyConfig.type?.displayName; + let policyLink: string | undefined; + + switch (policyType) { + case PolicyType.Build: { + const buildDisplayName = policyConfigSettings.displayName; + + if (buildDisplayName) { + policyText += `: ${buildDisplayName}`; + } + + const buildId = policyEvaluationRecord.context?.buildId; + const policyConfigUrl = policyConfig.url; + + if (buildId && policyConfigUrl) { + policyLink = policyConfigUrl.replace( + `_apis/policy/configurations/${policyConfig.id}`, + `_build/results?buildId=${buildId}`, + ); + } + + if (!policyStatus) { + break; + } + + const buildExpired = Boolean(policyConfigSettings.isExpired); + const buildPolicyStatus = + ( + { + [PolicyEvaluationStatus.Queued]: buildExpired + ? 'expired' + : 'queued', + [PolicyEvaluationStatus.Rejected]: 'failed', + } as Record + )[policyStatus] ?? PolicyEvaluationStatus[policyStatus].toLowerCase(); + + policyText += ` (${buildPolicyStatus})`; + + break; + } + case PolicyType.Status: { + const statusGenre = policyConfigSettings.statusGenre; + const statusName = policyConfigSettings.statusGenre; + + if (statusName) { + policyText += `: ${statusGenre}/${statusName}`; + } + + break; + } + case PolicyType.MinimumReviewers: { + const minimumApproverCount = policyConfigSettings.minimumApproverCount; + policyText += ` (${minimumApproverCount})`; + break; + } + case PolicyType.Comments: + break; + case PolicyType.RequiredReviewers: + break; + case PolicyType.MergeStrategy: + default: + return undefined; + } + + return { + id: policyConfig.id, + type: policyType, + status: policyStatus, + text: policyText, + link: policyLink, + }; +} + +function convertReviewer( + identityRef?: IdentityRefWithVote, +): Reviewer | undefined { + if (!identityRef) { + return undefined; + } + + return { + id: identityRef.id, + displayName: identityRef.displayName, + imageUrl: getAvatarUrl(identityRef), + isRequired: identityRef.isRequired, + isContainer: identityRef.isContainer, + voteStatus: (identityRef.vote ?? 0) as PullRequestVoteStatus, + }; +} + +function convertReviewers( + identityRefs?: IdentityRefWithVote[], +): Reviewer[] | undefined { + if (!identityRefs) { + return undefined; + } + + return identityRefs + .map(convertReviewer) + .filter((reviewer): reviewer is Reviewer => Boolean(reviewer)); +} + +function convertRepository(repository?: GitRepository): Repository | undefined { + if (!repository) { + return undefined; + } + + return { + id: repository.id, + name: repository.name, + url: repository.url?.replace('_apis/git/repositories', '_git'), + }; +} + +function convertCreatedBy(identityRef?: IdentityRef): CreatedBy | undefined { + if (!identityRef) { + return undefined; + } + + return { + id: identityRef.id, + displayName: identityRef.displayName, + uniqueName: identityRef.uniqueName, + imageUrl: getAvatarUrl(identityRef), + }; +} + +function hasAutoComplete(pullRequest: GitPullRequest): boolean { + return pullRequest.isDraft !== true && !!pullRequest.completionOptions; +} diff --git a/plugins/azure-devops-backend/src/utils/index.ts b/plugins/azure-devops-backend/src/utils/index.ts new file mode 100644 index 0000000000..415503091a --- /dev/null +++ b/plugins/azure-devops-backend/src/utils/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 './azure-devops-utils'; diff --git a/plugins/azure-devops-common/CHANGELOG.md b/plugins/azure-devops-common/CHANGELOG.md index 4a834fb068..7b2c1be0e7 100644 --- a/plugins/azure-devops-common/CHANGELOG.md +++ b/plugins/azure-devops-common/CHANGELOG.md @@ -1,5 +1,11 @@ # @backstage/plugin-azure-devops-common +## 0.1.1 + +### Patch Changes + +- 0749dd0307: feat: Created pull request card component and initial pull request dashboard page. + ## 0.1.0 ### Minor Changes diff --git a/plugins/azure-devops-common/api-report.md b/plugins/azure-devops-common/api-report.md index 71f0b8b807..17cccb05cb 100644 --- a/plugins/azure-devops-common/api-report.md +++ b/plugins/azure-devops-common/api-report.md @@ -27,6 +27,108 @@ export enum BuildStatus { Postponed = 8, } +// Warning: (ae-missing-release-tag) "CreatedBy" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface CreatedBy { + // (undocumented) + displayName?: string; + // (undocumented) + id?: string; + // (undocumented) + imageUrl?: string; + // (undocumented) + uniqueName?: string; +} + +// Warning: (ae-missing-release-tag) "DashboardPullRequest" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface DashboardPullRequest { + // (undocumented) + createdBy?: CreatedBy; + // (undocumented) + creationDate?: string; + // (undocumented) + description?: string; + // (undocumented) + hasAutoComplete: boolean; + // (undocumented) + isDraft?: boolean; + // (undocumented) + link?: string; + // (undocumented) + policies?: Policy[]; + // (undocumented) + pullRequestId?: number; + // (undocumented) + repository?: Repository; + // (undocumented) + reviewers?: Reviewer[]; + // (undocumented) + status?: PullRequestStatus; + // (undocumented) + title?: string; +} + +// Warning: (ae-missing-release-tag) "Policy" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface Policy { + // (undocumented) + id?: number; + // (undocumented) + link?: string; + // (undocumented) + status?: PolicyEvaluationStatus; + // (undocumented) + text?: string; + // (undocumented) + type: PolicyType; +} + +// Warning: (ae-missing-release-tag) "PolicyEvaluationStatus" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public +export enum PolicyEvaluationStatus { + Approved = 2, + Broken = 5, + NotApplicable = 4, + Queued = 0, + Rejected = 3, + Running = 1, +} + +// Warning: (ae-missing-release-tag) "PolicyType" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export enum PolicyType { + // (undocumented) + Build = 'Build', + // (undocumented) + Comments = 'Comments', + // (undocumented) + MergeStrategy = 'MergeStrategy', + // (undocumented) + MinimumReviewers = 'MinimumReviewers', + // (undocumented) + RequiredReviewers = 'RequiredReviewers', + // (undocumented) + Status = 'Status', +} + +// Warning: (ae-missing-release-tag) "PolicyTypeId" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export enum PolicyTypeId { + Build = '0609b952-1397-4640-95ec-e00a01b2c241', + Comments = 'c6a1889d-b943-4856-b76f-9e46bb6b0df2', + MergeStrategy = 'fa4e907d-c16b-4a4c-9dfa-4916e5d171ab', + MinimumReviewers = 'fa4e907d-c16b-4a4c-9dfa-4906e5d171dd', + RequiredReviewers = 'fd2167ab-b0be-447a-8ec8-39368250530e', + Status = 'cbdc66da-9728-4af8-aada-9a5a32e4a226', +} + // Warning: (ae-missing-release-tag) "PullRequest" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -63,6 +165,22 @@ export enum PullRequestStatus { NotSet = 0, } +// Warning: (ae-missing-release-tag) "PullRequestVoteStatus" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export enum PullRequestVoteStatus { + // (undocumented) + Approved = 10, + // (undocumented) + ApprovedWithSuggestions = 5, + // (undocumented) + NoVote = 0, + // (undocumented) + Rejected = -10, + // (undocumented) + WaitingForAuthor = -5, +} + // Warning: (ae-missing-release-tag) "RepoBuild" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -86,5 +204,47 @@ export type RepoBuildOptions = { top?: number; }; +// Warning: (ae-missing-release-tag) "Repository" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface Repository { + // (undocumented) + id?: string; + // (undocumented) + name?: string; + // (undocumented) + url?: string; +} + +// Warning: (ae-missing-release-tag) "Reviewer" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface Reviewer { + // (undocumented) + displayName?: string; + // (undocumented) + id?: string; + // (undocumented) + imageUrl?: string; + // (undocumented) + isContainer?: boolean; + // (undocumented) + isRequired?: boolean; + // (undocumented) + voteStatus: PullRequestVoteStatus; +} + +// Warning: (ae-missing-release-tag) "Team" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface Team { + // (undocumented) + id?: string; + // (undocumented) + memberIds?: string[]; + // (undocumented) + name?: string; +} + // (No @packageDocumentation comment for this package) ``` diff --git a/plugins/azure-devops-common/package.json b/plugins/azure-devops-common/package.json index fe9df644b1..0b64178a68 100644 --- a/plugins/azure-devops-common/package.json +++ b/plugins/azure-devops-common/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-azure-devops-common", - "version": "0.1.0", + "version": "0.1.1", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -29,7 +29,7 @@ "clean": "backstage-cli clean" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" }, "files": [ "dist" diff --git a/plugins/azure-devops-common/src/types.ts b/plugins/azure-devops-common/src/types.ts index a647f87300..da41e08d1f 100644 --- a/plugins/azure-devops-common/src/types.ts +++ b/plugins/azure-devops-common/src/types.ts @@ -126,3 +126,128 @@ export type PullRequestOptions = { top: number; status: PullRequestStatus; }; + +export interface DashboardPullRequest { + pullRequestId?: number; + title?: string; + description?: string; + repository?: Repository; + createdBy?: CreatedBy; + hasAutoComplete: boolean; + policies?: Policy[]; + reviewers?: Reviewer[]; + creationDate?: string; + status?: PullRequestStatus; + isDraft?: boolean; + link?: string; +} + +export interface Reviewer { + id?: string; + displayName?: string; + imageUrl?: string; + isRequired?: boolean; + isContainer?: boolean; + voteStatus: PullRequestVoteStatus; +} + +export interface Policy { + id?: number; + type: PolicyType; + status?: PolicyEvaluationStatus; + text?: string; + link?: string; +} + +export interface CreatedBy { + id?: string; + displayName?: string; + uniqueName?: string; + imageUrl?: string; +} + +export interface Repository { + id?: string; + name?: string; + url?: string; +} + +export interface Team { + id?: string; + name?: string; + memberIds?: string[]; +} + +/** + * Status of a policy which is running against a specific pull request. + */ +export enum PolicyEvaluationStatus { + /** + * The policy is either queued to run, or is waiting for some event before progressing. + */ + Queued = 0, + /** + * The policy is currently running. + */ + Running = 1, + /** + * The policy has been fulfilled for this pull request. + */ + Approved = 2, + /** + * The policy has rejected this pull request. + */ + Rejected = 3, + /** + * The policy does not apply to this pull request. + */ + NotApplicable = 4, + /** + * The policy has encountered an unexpected error. + */ + Broken = 5, +} + +export enum PolicyType { + Build = 'Build', + Status = 'Status', + MinimumReviewers = 'MinimumReviewers', + Comments = 'Comments', + RequiredReviewers = 'RequiredReviewers', + MergeStrategy = 'MergeStrategy', +} + +export enum PolicyTypeId { + /** + * This policy will require a successful build has been performed before updating protected refs. + */ + Build = '0609b952-1397-4640-95ec-e00a01b2c241', + /** + * This policy will require a successful status to be posted before updating protected refs. + */ + Status = 'cbdc66da-9728-4af8-aada-9a5a32e4a226', + /** + * This policy will ensure that a minimum number of reviewers have approved a pull request before completion. + */ + MinimumReviewers = 'fa4e907d-c16b-4a4c-9dfa-4906e5d171dd', + /** + * Check if the pull request has any active comments. + */ + Comments = 'c6a1889d-b943-4856-b76f-9e46bb6b0df2', + /** + * This policy will ensure that required reviewers are added for modified files matching specified patterns. + */ + RequiredReviewers = 'fd2167ab-b0be-447a-8ec8-39368250530e', + /** + * This policy ensures that pull requests use a consistent merge strategy. + */ + MergeStrategy = 'fa4e907d-c16b-4a4c-9dfa-4916e5d171ab', +} + +export enum PullRequestVoteStatus { + Approved = 10, + ApprovedWithSuggestions = 5, + NoVote = 0, + WaitingForAuthor = -5, + Rejected = -10, +} diff --git a/plugins/azure-devops/CHANGELOG.md b/plugins/azure-devops/CHANGELOG.md index 0bcd9bc686..9f460d4837 100644 --- a/plugins/azure-devops/CHANGELOG.md +++ b/plugins/azure-devops/CHANGELOG.md @@ -1,5 +1,29 @@ # @backstage/plugin-azure-devops +## 0.1.5 + +### Patch Changes + +- 0749dd0307: feat: Created pull request card component and initial pull request dashboard page. +- 82cd709fdb: **Backend** + + - Created new `/dashboard-pull-requests/:projectName` endpoint + - Created new `/all-teams` endpoint + - Implemented pull request policy evaluation conversion + + **Frontend** + + - Refactored `PullRequestsPage` and added new properties for `projectName` and `pollingInterval` + - Fixed spacing issue between repo link and creation date in `PullRequestCard` + - Added missing condition to `PullRequestCardPolicy` for `RequiredReviewers` + - Updated `useDashboardPullRequests` hook to implement long polling for pull requests + +- Updated dependencies + - @backstage/plugin-azure-devops-common@0.1.1 + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + ## 0.1.4 ### Patch Changes diff --git a/plugins/azure-devops/api-report.md b/plugins/azure-devops/api-report.md index ab659534c1..0f3e3310ef 100644 --- a/plugins/azure-devops/api-report.md +++ b/plugins/azure-devops/api-report.md @@ -7,12 +7,29 @@ import { BackstagePlugin } from '@backstage/core-plugin-api'; import { Entity } from '@backstage/catalog-model'; +import { SvgIconProps } from '@material-ui/core'; // Warning: (ae-missing-release-tag) "azureDevOpsPlugin" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) export const azureDevOpsPlugin: BackstagePlugin<{}, {}>; +// Warning: (ae-missing-release-tag) "AzurePullRequestsIcon" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export const AzurePullRequestsIcon: (props: SvgIconProps) => JSX.Element; + +// Warning: (ae-missing-release-tag) "AzurePullRequestsPage" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export const AzurePullRequestsPage: ({ + projectName, + pollingInterval, +}: { + projectName?: string | undefined; + pollingInterval?: number | undefined; +}) => JSX.Element; + // Warning: (ae-missing-release-tag) "EntityAzurePipelinesContent" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) diff --git a/plugins/azure-devops/package.json b/plugins/azure-devops/package.json index 9d235b0641..29f133ab5b 100644 --- a/plugins/azure-devops/package.json +++ b/plugins/azure-devops/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-azure-devops", - "version": "0.1.4", + "version": "0.1.5", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -28,12 +28,12 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.4", - "@backstage/plugin-azure-devops-common": "^0.1.0", + "@backstage/plugin-azure-devops-common": "^0.1.1", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -45,10 +45,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/azure-devops/src/api/AzureDevOpsApi.ts b/plugins/azure-devops/src/api/AzureDevOpsApi.ts index 90d291b25d..80d36f0adf 100644 --- a/plugins/azure-devops/src/api/AzureDevOpsApi.ts +++ b/plugins/azure-devops/src/api/AzureDevOpsApi.ts @@ -15,10 +15,12 @@ */ import { + DashboardPullRequest, PullRequest, PullRequestOptions, RepoBuild, RepoBuildOptions, + Team, } from '@backstage/plugin-azure-devops-common'; import { createApiRef } from '@backstage/core-plugin-api'; @@ -41,4 +43,10 @@ export interface AzureDevOpsApi { repoName: string, options?: PullRequestOptions, ): Promise<{ items: PullRequest[] }>; + + getDashboardPullRequests( + projectName: string, + ): Promise; + + getAllTeams(): Promise; } diff --git a/plugins/azure-devops/src/api/AzureDevOpsClient.ts b/plugins/azure-devops/src/api/AzureDevOpsClient.ts index cbcc496725..28d7e19cff 100644 --- a/plugins/azure-devops/src/api/AzureDevOpsClient.ts +++ b/plugins/azure-devops/src/api/AzureDevOpsClient.ts @@ -14,13 +14,15 @@ * limitations under the License. */ -import { DiscoveryApi, IdentityApi } from '@backstage/core-plugin-api'; import { + DashboardPullRequest, PullRequest, PullRequestOptions, RepoBuild, RepoBuildOptions, + Team, } from '@backstage/plugin-azure-devops-common'; +import { DiscoveryApi, IdentityApi } from '@backstage/core-plugin-api'; import { AzureDevOpsApi } from './AzureDevOpsApi'; import { ResponseError } from '@backstage/errors'; @@ -29,7 +31,7 @@ export class AzureDevOpsClient implements AzureDevOpsApi { private readonly discoveryApi: DiscoveryApi; private readonly identityApi: IdentityApi; - constructor(options: { + public constructor(options: { discoveryApi: DiscoveryApi; identityApi: IdentityApi; }) { @@ -74,6 +76,18 @@ export class AzureDevOpsClient implements AzureDevOpsApi { return { items }; } + public getDashboardPullRequests( + projectName: string, + ): Promise { + return this.get( + `dashboard-pull-requests/${projectName}?top=100`, + ); + } + + public getAllTeams(): Promise { + return this.get('all-teams'); + } + private async get(path: string): Promise { const baseUrl = `${await this.discoveryApi.getBaseUrl('azure-devops')}/`; const url = new URL(path, baseUrl); diff --git a/plugins/azure-devops/src/components/PullRequestsPage/PullRequestsPage.tsx b/plugins/azure-devops/src/components/PullRequestsPage/PullRequestsPage.tsx new file mode 100644 index 0000000000..9f21c4b81b --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/PullRequestsPage.tsx @@ -0,0 +1,126 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + Content, + Header, + Page, + Progress, + ResponseErrorPanel, +} from '@backstage/core-components'; +import { PullRequestGroup, PullRequestGroupConfig } from './lib/types'; +import React, { useEffect, useState } from 'react'; +import { getCreatedByUserFilter, getPullRequestGroups } from './lib/utils'; +import { useDashboardPullRequests, useUserEmail } from '../../hooks'; + +import { DashboardPullRequest } from '@backstage/plugin-azure-devops-common'; +import { PullRequestGrid } from './lib/PullRequestGrid'; + +function usePullRequestGroupConfigs( + userEmail: string | undefined, +): PullRequestGroupConfig[] { + const [pullRequestGroupConfigs, setPullRequestGroupConfigs] = useState< + PullRequestGroupConfig[] + >([]); + + useEffect(() => { + const prGroupConfigs: PullRequestGroupConfig[] = [ + { title: 'Created by me', filter: getCreatedByUserFilter(userEmail) }, + { title: 'Other PRs', filter: _ => true, simplified: false }, + ]; + + setPullRequestGroupConfigs(prGroupConfigs); + }, [userEmail]); + + return pullRequestGroupConfigs; +} + +function usePullRequestGroups( + pullRequests: DashboardPullRequest[] | undefined, + pullRequestGroupConfigs: PullRequestGroupConfig[], +): PullRequestGroup[] { + const [pullRequestGroups, setPullRequestGroups] = useState< + PullRequestGroup[] + >([]); + + useEffect(() => { + if (pullRequests) { + const groups = getPullRequestGroups( + pullRequests, + pullRequestGroupConfigs, + ); + setPullRequestGroups(groups); + } + }, [pullRequests, pullRequestGroupConfigs]); + + return pullRequestGroups; +} + +type PullRequestsPageContentProps = { + pullRequestGroups: PullRequestGroup[]; + loading: boolean; + error?: Error; +}; + +const PullRequestsPageContent = ({ + pullRequestGroups, + loading, + error, +}: PullRequestsPageContentProps) => { + if (loading && pullRequestGroups.length <= 0) { + return ; + } + + if (error) { + return ; + } + + return ; +}; + +type PullRequestsPageProps = { + projectName?: string; + pollingInterval?: number; +}; + +export const PullRequestsPage = ({ + projectName, + pollingInterval, +}: PullRequestsPageProps) => { + const { pullRequests, loading, error } = useDashboardPullRequests( + projectName, + pollingInterval, + ); + const userEmail = useUserEmail(); + const pullRequestGroupConfigs = usePullRequestGroupConfigs(userEmail); + const pullRequestGroups = usePullRequestGroups( + pullRequests, + pullRequestGroupConfigs, + ); + + return ( + +
+ + + + + ); +}; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/index.ts b/plugins/azure-devops/src/components/PullRequestsPage/index.ts new file mode 100644 index 0000000000..e8b6cfa6bb --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PullRequestsPage } from './PullRequestsPage'; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/AutoCompleteIcon/AutoCompleteIcon.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/AutoCompleteIcon/AutoCompleteIcon.tsx new file mode 100644 index 0000000000..ca43b8e27b --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/AutoCompleteIcon/AutoCompleteIcon.tsx @@ -0,0 +1,32 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 DoneAllIcon from '@material-ui/icons/DoneAll'; +import React from 'react'; +import { makeStyles } from '@material-ui/core/styles'; + +const useStyles = makeStyles(theme => ({ + root: (props: { hasAutoComplete: boolean }) => ({ + color: props.hasAutoComplete + ? theme.palette.success.main + : theme.palette.grey[400], + }), +})); + +export const AutoCompleteIcon = (props: { hasAutoComplete: boolean }) => { + const classes = useStyles(props); + return ; +}; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/AutoCompleteIcon/index.ts b/plugins/azure-devops/src/components/PullRequestsPage/lib/AutoCompleteIcon/index.ts new file mode 100644 index 0000000000..d83b0ffad0 --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/AutoCompleteIcon/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { AutoCompleteIcon } from './AutoCompleteIcon'; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCard.stories.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCard.stories.tsx new file mode 100644 index 0000000000..b948b616bd --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCard.stories.tsx @@ -0,0 +1,118 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + DashboardPullRequest, + PolicyEvaluationStatus, + PolicyType, + PullRequestStatus, + PullRequestVoteStatus, +} from '@backstage/plugin-azure-devops-common'; + +import { MemoryRouter } from 'react-router'; +import { PullRequestCard } from './PullRequestCard'; +import React from 'react'; + +export default { + title: 'Plugins/Azure Devops/Pull Request Card', + component: PullRequestCard, +}; + +const pullRequest: DashboardPullRequest = { + pullRequestId: 1, + title: + "feat(EXUX-4091): 🛂 Added the admin role authorization to the backend API's", + description: + 'This PR contains the following updates:\n\n| Package | Type | Update | Change |\n|---|---|---|---|\n| [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint) | devDependencies | major | [`4.33.0` -> `5.0.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2feslint-plugin/4.33.0/5.0.0) |\n| [@typescript-eslint/parser](https://github.com/typescript-eslint/typescrip', + link: undefined, + repository: { + id: undefined, + name: 'backstage', + url: undefined, + }, + createdBy: { + id: '', + displayName: 'Marley', + uniqueName: 'marley@test.com', + imageUrl: + 'https://dev.azure.com/exclaimerltd/_api/_common/identityImage?id=e6c0634b-68d2-6e6f-aa7d-adccada23216', + }, + reviewers: [ + { + id: undefined, + displayName: 'Marley', + imageUrl: '', + isRequired: true, + isContainer: false, + voteStatus: PullRequestVoteStatus.Approved, + }, + { + id: undefined, + displayName: 'User 1', + imageUrl: '', + isRequired: false, + isContainer: false, + voteStatus: PullRequestVoteStatus.WaitingForAuthor, + }, + { + id: undefined, + displayName: 'User 2', + imageUrl: '', + isRequired: true, + isContainer: false, + voteStatus: PullRequestVoteStatus.NoVote, + }, + ], + policies: [ + { + id: undefined, + type: PolicyType.Build, + status: PolicyEvaluationStatus.Running, + text: 'Build: UI (running)', + link: undefined, + }, + { + id: undefined, + type: PolicyType.MinimumReviewers, + text: 'Minimum number of reviewers (2)', + status: undefined, + link: undefined, + }, + { + id: undefined, + type: PolicyType.Comments, + text: 'Comment requirements', + status: undefined, + link: undefined, + }, + ], + hasAutoComplete: true, + creationDate: new Date(Date.now() - 10000000).toISOString(), + status: PullRequestStatus.Active, + isDraft: false, +}; + +export const Default = () => ( + + + +); + +export const Simplified = () => ( + + + +); diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCard.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCard.tsx new file mode 100644 index 0000000000..4b2823814e --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCard.tsx @@ -0,0 +1,130 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { Avatar, Link } from '@backstage/core-components'; +import { Card, CardContent, CardHeader } from '@material-ui/core'; + +import { AutoCompleteIcon } from '../AutoCompleteIcon'; +import { DashboardPullRequest } from '@backstage/plugin-azure-devops-common'; +import { DateTime } from 'luxon'; +import { PullRequestCardPolicies } from './PullRequestCardPolicies'; +import { PullRequestCardReviewers } from './PullRequestCardReviewers'; +import React from 'react'; +import { makeStyles } from '@material-ui/core/styles'; + +const useStyles = makeStyles( + theme => ({ + card: { + backgroundColor: + theme.palette.type === 'dark' + ? theme.palette.grey[700] + : theme.palette.common.white, + }, + cardHeaderSimplified: { + paddingBottom: theme.spacing(2), + }, + cardHeaderAction: { + display: 'flex', + alignSelf: 'center', + margin: 0, + }, + content: { + display: 'flex', + flexDirection: 'row', + }, + policies: { + flex: 1, + }, + }), + { name: 'PullRequestCard' }, +); + +type PullRequestCardProps = { + pullRequest: DashboardPullRequest; + simplified?: boolean; +}; + +export const PullRequestCard = ({ + pullRequest, + simplified, +}: PullRequestCardProps) => { + const title = ( + + {pullRequest.title} + + ); + + const repoLink = ( + + {pullRequest.repository?.name} + + ); + + const creationDate = pullRequest.creationDate + ? DateTime.fromISO(pullRequest.creationDate).toRelative() + : undefined; + + const subheader = ( + + {repoLink} · {creationDate} + + ); + + const avatar = ( + + ); + + const classes = useStyles(); + + return ( + + + } + classes={{ + ...(simplified && { root: classes.cardHeaderSimplified }), + action: classes.cardHeaderAction, + }} + /> + + {!simplified && ( + + {pullRequest.policies && ( + + )} + + {pullRequest.reviewers && ( + + )} + + )} + + ); +}; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardPolicies.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardPolicies.tsx new file mode 100644 index 0000000000..ec6389ab1e --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardPolicies.tsx @@ -0,0 +1,35 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { Policy } from '@backstage/plugin-azure-devops-common'; +import { PullRequestCardPolicy } from './PullRequestCardPolicy'; +import React from 'react'; + +type PullRequestCardProps = { + policies: Policy[]; + className: string; +}; + +export const PullRequestCardPolicies = ({ + policies, + className, +}: PullRequestCardProps) => ( +
+ {policies.map(policy => ( + + ))} +
+); diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardPolicy.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardPolicy.tsx new file mode 100644 index 0000000000..580f8c571f --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardPolicy.tsx @@ -0,0 +1,96 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + Policy, + PolicyEvaluationStatus, + PolicyType, +} from '@backstage/plugin-azure-devops-common'; +import { styled, withStyles } from '@material-ui/core/styles'; + +import CancelIcon from '@material-ui/icons/Cancel'; +import GroupWorkIcon from '@material-ui/icons/GroupWork'; +import React from 'react'; +import WatchLaterIcon from '@material-ui/icons/WatchLater'; + +const PolicyRequiredIcon = withStyles( + theme => ({ + root: { + color: theme.palette.info.main, + }, + }), + { name: 'PolicyRequiredIcon' }, +)(WatchLaterIcon); + +const PolicyIssueIcon = withStyles( + theme => ({ + root: { + color: theme.palette.error.main, + }, + }), + { name: 'PolicyIssueIcon' }, +)(CancelIcon); + +const PolicyInProgressIcon = withStyles( + theme => ({ + root: { + color: theme.palette.info.main, + }, + }), + { name: 'PolicyInProgressIcon' }, +)(GroupWorkIcon); + +function getPolicyIcon(policy: Policy): JSX.Element | null { + switch (policy.type) { + case PolicyType.Build: + switch (policy.status) { + case PolicyEvaluationStatus.Running: + return ; + case PolicyEvaluationStatus.Rejected: + return ; + case PolicyEvaluationStatus.Queued: + return ; + default: + return null; + } + case PolicyType.MinimumReviewers: + case PolicyType.RequiredReviewers: + return ; + case PolicyType.Status: + case PolicyType.Comments: + return ; + default: + return null; + } +} + +const PullRequestCardPolicyContainer = styled('div')({ + display: 'flex', + alignItems: 'center', + flexWrap: 'wrap', +}); + +type PullRequestCardPolicyProps = { + policy: Policy; +}; + +export const PullRequestCardPolicy = ({ + policy, +}: PullRequestCardPolicyProps) => ( + + {getPolicyIcon(policy)} {policy.text} + +); diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardReviewer.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardReviewer.tsx new file mode 100644 index 0000000000..1d2049728b --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardReviewer.tsx @@ -0,0 +1,38 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { Avatar } from '@backstage/core-components'; +import React from 'react'; +import { Reviewer } from '@backstage/plugin-azure-devops-common'; + +type PullRequestCardReviewerProps = { + reviewer: Reviewer; +}; + +export const PullRequestCardReviewer = ({ + reviewer, +}: PullRequestCardReviewerProps) => ( + +); diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardReviewers.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardReviewers.tsx new file mode 100644 index 0000000000..e3bf0c8a03 --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/PullRequestCardReviewers.tsx @@ -0,0 +1,42 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PullRequestCardReviewer } from './PullRequestCardReviewer'; +import React from 'react'; +import { Reviewer } from '@backstage/plugin-azure-devops-common'; +import { reviewerFilter } from '../utils'; +import { styled } from '@material-ui/core/styles'; + +const PullRequestCardReviewersContainer = styled('div')({ + '& > *': { + marginTop: 4, + marginBottom: 4, + }, +}); + +type PullRequestCardReviewersProps = { + reviewers: Reviewer[]; +}; + +export const PullRequestCardReviewers = ({ + reviewers, +}: PullRequestCardReviewersProps) => ( + + {reviewers.filter(reviewerFilter).map(reviewer => ( + + ))} + +); diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/index.ts b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/index.ts new file mode 100644 index 0000000000..5d6a49d09e --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestCard/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PullRequestCard } from './PullRequestCard'; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGrid/PullRequestGrid.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGrid/PullRequestGrid.tsx new file mode 100644 index 0000000000..8b9c49beb4 --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGrid/PullRequestGrid.tsx @@ -0,0 +1,51 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PullRequestGridColumn } from '../PullRequestGridColumn'; +import { PullRequestGroup } from '../types'; +import React from 'react'; +import { styled } from '@material-ui/core'; + +const GridDiv = styled('div')(({ theme }) => ({ + display: 'flex', + flexDirection: 'row', + justifyContent: 'space-between', + '& > *': { + marginRight: theme.spacing(2), + }, + '& > :last-of-type': { + marginRight: 0, + }, +})); + +type PullRequestGridProps = { + pullRequestGroups: PullRequestGroup[]; +}; + +export const PullRequestGrid = ({ + pullRequestGroups, +}: PullRequestGridProps) => { + return ( + + {pullRequestGroups.map((pullRequestGroup, index) => ( + + ))} + + ); +}; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGrid/index.ts b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGrid/index.ts new file mode 100644 index 0000000000..902680f80d --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGrid/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PullRequestGrid } from './PullRequestGrid'; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGridColumn/PullRequestGridColumn.tsx b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGridColumn/PullRequestGridColumn.tsx new file mode 100644 index 0000000000..94a648188d --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGridColumn/PullRequestGridColumn.tsx @@ -0,0 +1,87 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { Paper, Typography, styled, withStyles } from '@material-ui/core'; + +import { PullRequestCard } from '../PullRequestCard'; +import { PullRequestGroup } from '../types'; +import React from 'react'; + +const ColumnPaper = withStyles(theme => ({ + root: { + display: 'flex', + flexDirection: 'column', + flex: 1, + padding: theme.spacing(2), + backgroundColor: + theme.palette.type === 'dark' + ? theme.palette.grey[800] + : theme.palette.grey[300], + height: '100%', + }, +}))(Paper); + +const ColumnTitleDiv = styled('div')(({ theme }) => ({ + display: 'flex', + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + marginBottom: theme.spacing(2), +})); + +export const PullRequestCardContainer = styled('div')(({ theme }) => ({ + display: 'flex', + flexDirection: 'column', + '& > *': { + marginBottom: theme.spacing(2), + }, + '& > :last-of-type': { + marginBottom: 0, + }, +})); + +type PullRequestGridColumnProps = { + pullRequestGroup: PullRequestGroup; +}; + +export const PullRequestGridColumn = ({ + pullRequestGroup, +}: PullRequestGridColumnProps) => { + const columnTitle = ( + + {pullRequestGroup.title} + + ); + + const pullRequests = ( + + {pullRequestGroup.pullRequests.map(pullRequest => ( + + ))} + + ); + + return ( + + {columnTitle} + {pullRequests} + + ); +}; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGridColumn/index.ts b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGridColumn/index.ts new file mode 100644 index 0000000000..aa3cf82554 --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/PullRequestGridColumn/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PullRequestGridColumn } from './PullRequestGridColumn'; diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/types.ts b/plugins/azure-devops/src/components/PullRequestsPage/lib/types.ts new file mode 100644 index 0000000000..2d936f7b64 --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/types.ts @@ -0,0 +1,36 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + DashboardPullRequest, + Team, +} from '@backstage/plugin-azure-devops-common'; + +export interface PullRequestGroup { + title: string; + pullRequests: DashboardPullRequest[]; + simplified?: boolean; +} + +export type PullRequestFilter = (pullRequest: DashboardPullRequest) => boolean; + +export type TeamFilter = (team: Team) => boolean; + +export interface PullRequestGroupConfig { + title: string; + filter: PullRequestFilter; + simplified?: boolean; +} diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/utils.test.ts b/plugins/azure-devops/src/components/PullRequestsPage/lib/utils.test.ts new file mode 100644 index 0000000000..da27b2e06e --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/utils.test.ts @@ -0,0 +1,161 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + DashboardPullRequest, + PullRequestVoteStatus, + Reviewer, +} from '@backstage/plugin-azure-devops-common'; +import { + arrayExtract, + getCreatedByUserFilter, + getPullRequestGroups, + reviewerFilter, +} from './utils'; + +describe('getCreatedByUserFilter', () => { + it('should filter if pull request is created by user', () => { + const userEmail = 'user1@backstage.com'; + const pr = { + createdBy: { uniqueName: userEmail }, + } as DashboardPullRequest; + const result = getCreatedByUserFilter(userEmail)(pr); + expect(result).toBe(true); + }); + + it('should not filter if pull request is not created by user', () => { + const userEmail1 = 'user1@backstage.com'; + const userEmail2 = 'user2@backstage.com'; + const pr = { + createdBy: { uniqueName: userEmail1 }, + } as DashboardPullRequest; + const result = getCreatedByUserFilter(userEmail2)(pr); + expect(result).toBe(false); + }); +}); + +describe('reviewerFilter', () => { + it('should return false if reviewer has no vote and is not required', () => { + const reviewer = { + voteStatus: PullRequestVoteStatus.NoVote, + isRequired: false, + } as Reviewer; + const result = reviewerFilter(reviewer); + expect(result).toBe(false); + }); + + it('should return true if reviewer has no vote and is required', () => { + const reviewer = { + voteStatus: PullRequestVoteStatus.NoVote, + isRequired: true, + } as Reviewer; + const result = reviewerFilter(reviewer); + expect(result).toBe(true); + }); + + it('should return true if reviewer has a vote and is not a container', () => { + const reviewer = { + voteStatus: PullRequestVoteStatus.Approved, + isContainer: false, + } as Reviewer; + const result = reviewerFilter(reviewer); + expect(result).toBe(true); + }); + + it('should return true if reviewer has a vote and is a container', () => { + const reviewer = { + voteStatus: PullRequestVoteStatus.Approved, + isContainer: true, + } as Reviewer; + const result = reviewerFilter(reviewer); + expect(result).toBe(false); + }); +}); + +describe('arrayExtract', () => { + it('should extract numbers greater than 3', () => { + const numbers = [1, 2, 3, 4, 5, 6]; + const numberFilter = (num: number): boolean => num > 3; + const extractedNumbers = arrayExtract(numbers, numberFilter); + expect(numbers).toEqual([1, 2, 3]); + expect(extractedNumbers).toEqual([4, 5, 6]); + }); + + it('should extract even numbers', () => { + const numbers = [1, 2, 3, 4, 5, 6]; + const numberFilter = (num: number): boolean => num % 2 === 0; + const extractedNumbers = arrayExtract(numbers, numberFilter); + expect(numbers).toEqual([1, 3, 5]); + expect(extractedNumbers).toEqual([2, 4, 6]); + }); +}); + +describe('getPullRequestGroups', () => { + it('should create groups of pull requests based on the provided configs', () => { + const userEmail = 'user1@backstage.com'; + const userEmail2 = 'user2@backstage.com'; + + const pullRequests = [ + { + pullRequestId: 1, + createdBy: { uniqueName: userEmail }, + } as DashboardPullRequest, + { + pullRequestId: 2, + createdBy: { uniqueName: userEmail }, + } as DashboardPullRequest, + { + pullRequestId: 3, + createdBy: { uniqueName: userEmail2 }, + } as DashboardPullRequest, + { + pullRequestId: 4, + createdBy: { uniqueName: userEmail2 }, + } as DashboardPullRequest, + ]; + + const configs = [ + { title: 'Created by me', filter: getCreatedByUserFilter(userEmail) }, + { title: 'Other PRs', filter: (_: unknown) => true, simplified: true }, + ]; + + const result = getPullRequestGroups(pullRequests, configs); + + expect(result.length).toBe(2); + + const group1 = result[0]; + expect(group1.title).toBe('Created by me'); + expect(group1.simplified).toBeFalsy(); + expect(group1.pullRequests.length).toBe(2); + expect(group1.pullRequests).toContainEqual( + expect.objectContaining({ pullRequestId: 1 }), + ); + expect(group1.pullRequests).toContainEqual( + expect.objectContaining({ pullRequestId: 2 }), + ); + + const group2 = result[1]; + expect(group2.title).toBe('Other PRs'); + expect(group2.simplified).toBe(true); + expect(group2.pullRequests.length).toBe(2); + expect(group2.pullRequests).toContainEqual( + expect.objectContaining({ pullRequestId: 3 }), + ); + expect(group2.pullRequests).toContainEqual( + expect.objectContaining({ pullRequestId: 4 }), + ); + }); +}); diff --git a/plugins/azure-devops/src/components/PullRequestsPage/lib/utils.ts b/plugins/azure-devops/src/components/PullRequestsPage/lib/utils.ts new file mode 100644 index 0000000000..c9cf866010 --- /dev/null +++ b/plugins/azure-devops/src/components/PullRequestsPage/lib/utils.ts @@ -0,0 +1,117 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + DashboardPullRequest, + PullRequestVoteStatus, + Reviewer, +} from '@backstage/plugin-azure-devops-common'; +import { + PullRequestFilter, + PullRequestGroup, + PullRequestGroupConfig, +} from './types'; + +/** + * Creates a filter that matches pull requests created by `userEmail`. + * @param userEmail an email to filter by. + * @returns a filter for pull requests created by `userEmail`. + */ +export function getCreatedByUserFilter( + userEmail: string | undefined, +): PullRequestFilter { + return (pullRequest: DashboardPullRequest): boolean => + pullRequest.createdBy?.uniqueName?.toLocaleLowerCase() === + userEmail?.toLocaleLowerCase(); +} + +/** + * Filters a reviewer based on vote status and if the reviewer is required. + * @param reviewer a reviewer to filter. + * @returns whether or not to filter the `reviewer`. + */ +export function reviewerFilter(reviewer: Reviewer): boolean { + return reviewer.voteStatus === PullRequestVoteStatus.NoVote + ? !!reviewer.isRequired + : !reviewer.isContainer; +} + +/** + * Removes values from the provided array and returns them. + * @param arr the array to extract values from. + * @param filter a filter used to extract values from the provided array. + * @returns the values that were extracted from the array. + * + * @example + * ```ts + * const numbers = [1, 2, 3, 4, 5, 6]; + * const numberFilter = (num: number): boolean => num > 3; + * const extractedNumbers = arrayExtract(numbers, numberFilter); + * console.log(numbers); // [1, 2, 3] + * console.log(extractedNumbers); // [4, 5, 6] + * ``` + * + * @example + * ```ts + * const numbers = [1, 2, 3, 4, 5, 6]; + * const numberFilter = (num: number): boolean => num % 2 === 0; + * const extractedNumbers = arrayExtract(numbers, numberFilter); + * console.log(numbers); // [1, 3, 5] + * console.log(extractedNumbers); // [2, 4, 6] + * ``` + */ +export function arrayExtract(arr: T[], filter: (value: T) => unknown): T[] { + const extractedValues: T[] = []; + + for (let i = 0; i - extractedValues.length < arr.length; i++) { + const offsetIndex = i - extractedValues.length; + + const value = arr[offsetIndex]; + + if (filter(value)) { + arr.splice(offsetIndex, 1); + extractedValues.push(value); + } + } + + return extractedValues; +} + +/** + * Creates groups of pull requests based on a list of `PullRequestGroupConfig`. + * @param pullRequests all pull requests to be split up into groups. + * @param configs the config used for splitting up the pull request groups. + * @returns a list of pull request groups. + */ +export function getPullRequestGroups( + pullRequests: DashboardPullRequest[], + configs: PullRequestGroupConfig[], +): PullRequestGroup[] { + const remainingPullRequests: DashboardPullRequest[] = [...pullRequests]; + const pullRequestGroups: PullRequestGroup[] = []; + + configs.forEach(({ title, filter: configFilter, simplified }) => { + const groupPullRequests = arrayExtract(remainingPullRequests, configFilter); + + pullRequestGroups.push({ + title, + pullRequests: groupPullRequests, + simplified, + }); + }); + + return pullRequestGroups; +} diff --git a/plugins/azure-devops/src/hooks/index.ts b/plugins/azure-devops/src/hooks/index.ts new file mode 100644 index 0000000000..44b94f3f4b --- /dev/null +++ b/plugins/azure-devops/src/hooks/index.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 './useAllTeams'; +export * from './useDashboardPullRequests'; +export * from './useProjectRepoFromEntity'; +export * from './usePullRequests'; +export * from './useRepoBuilds'; +export * from './useUserEmail'; diff --git a/plugins/azure-devops/src/hooks/useAllTeams.ts b/plugins/azure-devops/src/hooks/useAllTeams.ts new file mode 100644 index 0000000000..d32aa5e136 --- /dev/null +++ b/plugins/azure-devops/src/hooks/useAllTeams.ts @@ -0,0 +1,42 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { Team } from '@backstage/plugin-azure-devops-common'; +import { azureDevOpsApiRef } from '../api'; +import { useApi } from '@backstage/core-plugin-api'; +import { useAsync } from 'react-use'; + +export function useAllTeams(): { + teams?: Team[]; + loading: boolean; + error?: Error; +} { + const api = useApi(azureDevOpsApiRef); + + const { + value: teams, + loading, + error, + } = useAsync(() => { + return api.getAllTeams(); + }, [api]); + + return { + teams, + loading, + error, + }; +} diff --git a/plugins/azure-devops/src/hooks/useDashboardPullRequests.ts b/plugins/azure-devops/src/hooks/useDashboardPullRequests.ts new file mode 100644 index 0000000000..1b2333ba1c --- /dev/null +++ b/plugins/azure-devops/src/hooks/useDashboardPullRequests.ts @@ -0,0 +1,72 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { errorApiRef, useApi } from '@backstage/core-plugin-api'; +import { useAsyncRetry, useInterval } from 'react-use'; + +import { DashboardPullRequest } from '@backstage/plugin-azure-devops-common'; +import { azureDevOpsApiRef } from '../api'; +import { useCallback } from 'react'; + +const POLLING_INTERVAL = 10000; + +export function useDashboardPullRequests( + project?: string, + pollingInterval: number = POLLING_INTERVAL, +): { + pullRequests?: DashboardPullRequest[]; + loading: boolean; + error?: Error; +} { + const api = useApi(azureDevOpsApiRef); + const errorApi = useApi(errorApiRef); + + const getDashboardPullRequests = useCallback(async (): Promise< + DashboardPullRequest[] + > => { + if (!project) { + return Promise.reject(new Error('Missing project name')); + } + + try { + return await api.getDashboardPullRequests(project); + } catch (error) { + if (error instanceof Error) { + errorApi.post(error); + } + + return Promise.reject(error); + } + }, [project, api, errorApi]); + + const { + value: pullRequests, + loading, + error, + retry, + } = useAsyncRetry( + () => getDashboardPullRequests(), + [getDashboardPullRequests], + ); + + useInterval(() => retry(), pollingInterval); + + return { + pullRequests, + loading, + error, + }; +} diff --git a/plugins/azure-devops/src/hooks/useUserEmail.ts b/plugins/azure-devops/src/hooks/useUserEmail.ts new file mode 100644 index 0000000000..4655815297 --- /dev/null +++ b/plugins/azure-devops/src/hooks/useUserEmail.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { identityApiRef, useApi } from '@backstage/core-plugin-api'; + +export function useUserEmail(): string | undefined { + const identityApi = useApi(identityApiRef); + return identityApi.getProfile().email; +} diff --git a/plugins/azure-devops/src/index.ts b/plugins/azure-devops/src/index.ts index 4da533b534..c9b804bc8d 100644 --- a/plugins/azure-devops/src/index.ts +++ b/plugins/azure-devops/src/index.ts @@ -13,9 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + export { azureDevOpsPlugin, EntityAzurePipelinesContent, EntityAzurePullRequestsContent, isAzureDevOpsAvailable, + AzurePullRequestsPage, } from './plugin'; + +export { AzurePullRequestsIcon } from './components/AzurePullRequestsIcon'; diff --git a/plugins/azure-devops/src/plugin.ts b/plugins/azure-devops/src/plugin.ts index 7a5f80d0d3..003c7b7eee 100644 --- a/plugins/azure-devops/src/plugin.ts +++ b/plugins/azure-devops/src/plugin.ts @@ -16,6 +16,7 @@ import { azurePipelinesEntityContentRouteRef, + azurePullRequestDashboardRouteRef, azurePullRequestsEntityContentRouteRef, } from './routes'; import { @@ -46,6 +47,15 @@ export const azureDevOpsPlugin = createPlugin({ ], }); +export const AzurePullRequestsPage = azureDevOpsPlugin.provide( + createRoutableExtension({ + name: 'AzurePullRequestsPage', + component: () => + import('./components/PullRequestsPage').then(m => m.PullRequestsPage), + mountPoint: azurePullRequestDashboardRouteRef, + }), +); + export const EntityAzurePipelinesContent = azureDevOpsPlugin.provide( createRoutableExtension({ name: 'EntityAzurePipelinesContent', diff --git a/plugins/azure-devops/src/routes.ts b/plugins/azure-devops/src/routes.ts index 7a4adea33e..0d20c12beb 100644 --- a/plugins/azure-devops/src/routes.ts +++ b/plugins/azure-devops/src/routes.ts @@ -16,6 +16,10 @@ import { createRouteRef } from '@backstage/core-plugin-api'; +export const azurePullRequestDashboardRouteRef = createRouteRef({ + id: 'azure-pull-request-dashboard', +}); + export const azurePipelinesEntityContentRouteRef = createRouteRef({ id: 'azure-pipelines-entity-content', }); diff --git a/plugins/badges-backend/CHANGELOG.md b/plugins/badges-backend/CHANGELOG.md index 5cd063d960..e1cdfa1490 100644 --- a/plugins/badges-backend/CHANGELOG.md +++ b/plugins/badges-backend/CHANGELOG.md @@ -1,5 +1,35 @@ # @backstage/plugin-badges-backend +## 0.1.13 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/backend-common@0.9.12 + +## 0.1.12 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/backend-common@0.9.11 + ## 0.1.11 ### Patch Changes diff --git a/plugins/badges-backend/package.json b/plugins/badges-backend/package.json index 2186c8d52e..c481866a0a 100644 --- a/plugins/badges-backend/package.json +++ b/plugins/badges-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-badges-backend", "description": "A Backstage backend plugin that generates README badges for your entities", - "version": "0.1.11", + "version": "0.1.13", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -31,22 +31,21 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", - "@backstage/errors": "^0.1.3", + "@backstage/errors": "^0.1.5", "@types/express": "^4.17.6", "badge-maker": "^3.3.0", "cors": "^2.8.5", - "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", "winston": "^3.2.1", "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/supertest": "^2.0.8", "supertest": "^6.1.3" }, diff --git a/plugins/badges/CHANGELOG.md b/plugins/badges/CHANGELOG.md index 44bc597d0a..449352f87b 100644 --- a/plugins/badges/CHANGELOG.md +++ b/plugins/badges/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/plugin-badges +## 0.2.15 + +### Patch Changes + +- 4149d74c10: Fix the path that the Badges client uses towards the `plugin-badges-backend` +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.2.14 ### Patch Changes diff --git a/plugins/badges/package.json b/plugins/badges/package.json index 4d02d64237..7c478c0a26 100644 --- a/plugins/badges/package.json +++ b/plugins/badges/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-badges", "description": "A Backstage plugin that generates README badges for your entities", - "version": "0.2.14", + "version": "0.2.15", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -28,11 +28,11 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/errors": "^0.1.3", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/errors": "^0.1.5", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -42,10 +42,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/badges/src/api/BadgesClient.ts b/plugins/badges/src/api/BadgesClient.ts index 432a485a6b..8ad5d313e4 100644 --- a/plugins/badges/src/api/BadgesClient.ts +++ b/plugins/badges/src/api/BadgesClient.ts @@ -52,7 +52,7 @@ export class BadgesClient implements BadgesApi { private async getEntityBadgeSpecsUrl(entity: Entity): Promise { const routeParams = this.getEntityRouteParams(entity); - const path = generatePath(`:kind/:namespace/:name`, routeParams); + const path = generatePath(`:namespace/:kind/:name`, routeParams); return `${await this.discoveryApi.getBaseUrl( 'badges', )}/entity/${path}/badge-specs`; diff --git a/plugins/bazaar-backend/CHANGELOG.md b/plugins/bazaar-backend/CHANGELOG.md index 88e646b5e3..812ae8f5e3 100644 --- a/plugins/bazaar-backend/CHANGELOG.md +++ b/plugins/bazaar-backend/CHANGELOG.md @@ -1,5 +1,26 @@ # @backstage/plugin-bazaar-backend +## 0.1.3 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/backend-common@0.9.11 + ## 0.1.2 ### Patch Changes diff --git a/plugins/bazaar-backend/migrations/20211020073922_add_columns.js b/plugins/bazaar-backend/migrations/20211020073922_add_columns.js index d4cb87bd82..ea3a89ea72 100644 --- a/plugins/bazaar-backend/migrations/20211020073922_add_columns.js +++ b/plugins/bazaar-backend/migrations/20211020073922_add_columns.js @@ -29,6 +29,7 @@ exports.up = async function up(knex) { .comment('Optional end date of the project (ISO 8601 format)'); table .text('responsible') + .defaultTo('') .notNullable() .comment('Contact person of the project'); }); diff --git a/plugins/bazaar-backend/package.json b/plugins/bazaar-backend/package.json index a6610493e2..aec96bb021 100644 --- a/plugins/bazaar-backend/package.json +++ b/plugins/bazaar-backend/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-bazaar-backend", - "version": "0.1.2", + "version": "0.1.3", "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.9.10", - "@backstage/backend-test-utils": "^0.1.9", + "@backstage/backend-common": "^0.9.12", + "@backstage/backend-test-utils": "^0.1.10", "@backstage/config": "^0.1.5", "@types/express": "^4.17.6", "express": "^4.17.1", @@ -31,7 +31,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" }, "files": [ "dist", diff --git a/plugins/bazaar/CHANGELOG.md b/plugins/bazaar/CHANGELOG.md index 8988bf5d62..2a21310347 100644 --- a/plugins/bazaar/CHANGELOG.md +++ b/plugins/bazaar/CHANGELOG.md @@ -1,5 +1,14 @@ # @backstage/plugin-bazaar +## 0.1.5 + +### Patch Changes + +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/cli@0.10.0 + - @backstage/core-plugin-api@0.2.2 + ## 0.1.4 ### Patch Changes diff --git a/plugins/bazaar/package.json b/plugins/bazaar/package.json index fd07a3b5c7..2defba5cca 100644 --- a/plugins/bazaar/package.json +++ b/plugins/bazaar/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-bazaar", - "version": "0.1.4", + "version": "0.1.5", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -22,17 +22,17 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/cli": "^0.9.0", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/cli": "^0.10.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog": "^0.7.3", "@backstage/plugin-catalog-react": "^0.6.4", + "@date-io/luxon": "1.x", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", "@material-ui/pickers": "^3.3.10", "@testing-library/jest-dom": "^5.10.1", - "@date-io/luxon": "1.x", "luxon": "^2.0.2", "react": "^16.13.1", "react-dom": "^16.13.1", @@ -41,7 +41,7 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/dev-utils": "^0.2.13", "@testing-library/jest-dom": "^5.10.1", "cross-fetch": "^3.0.6" diff --git a/plugins/bitrise/CHANGELOG.md b/plugins/bitrise/CHANGELOG.md index 874cbe2c6c..05f12c9fdd 100644 --- a/plugins/bitrise/CHANGELOG.md +++ b/plugins/bitrise/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/plugin-bitrise +## 0.1.18 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + ## 0.1.17 ### Patch Changes diff --git a/plugins/bitrise/package.json b/plugins/bitrise/package.json index 92cd9693e1..b036610f0a 100644 --- a/plugins/bitrise/package.json +++ b/plugins/bitrise/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-bitrise", "description": "A Backstage plugin that integrates towards Bitrise", - "version": "0.1.17", + "version": "0.1.18", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -22,10 +22,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -39,17 +39,16 @@ "recharts": "^1.8.5" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", "@types/jest": "^26.0.7", "@types/node": "^14.14.32", "@types/recharts": "^1.8.15", - "cross-fetch": "^3.0.6", "msw": "^0.35.0" }, "files": [ diff --git a/plugins/catalog-backend-module-ldap/CHANGELOG.md b/plugins/catalog-backend-module-ldap/CHANGELOG.md index a776f3f329..b8e48924dc 100644 --- a/plugins/catalog-backend-module-ldap/CHANGELOG.md +++ b/plugins/catalog-backend-module-ldap/CHANGELOG.md @@ -1,5 +1,20 @@ # @backstage/plugin-catalog-backend-module-ldap +## 0.3.8 + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-catalog-backend@0.19.0 + +## 0.3.7 + +### Patch Changes + +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/plugin-catalog-backend@0.18.0 + ## 0.3.6 ### Patch Changes diff --git a/plugins/catalog-backend-module-ldap/package.json b/plugins/catalog-backend-module-ldap/package.json index 5e3cec24d9..2817a0e209 100644 --- a/plugins/catalog-backend-module-ldap/package.json +++ b/plugins/catalog-backend-module-ldap/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-catalog-backend-module-ldap", "description": "A Backstage catalog backend modules that helps integrate towards LDAP", - "version": "0.3.6", + "version": "0.3.8", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -31,8 +31,8 @@ "dependencies": { "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/errors": "^0.1.4", - "@backstage/plugin-catalog-backend": "^0.17.4", + "@backstage/errors": "^0.1.5", + "@backstage/plugin-catalog-backend": "^0.19.0", "@backstage/types": "^0.1.1", "@types/ldapjs": "^2.2.0", "ldapjs": "^2.2.0", @@ -40,7 +40,7 @@ "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/lodash": "^4.14.151" }, "files": [ diff --git a/plugins/catalog-backend-module-msgraph/CHANGELOG.md b/plugins/catalog-backend-module-msgraph/CHANGELOG.md index ee8aa49065..3db08d02fc 100644 --- a/plugins/catalog-backend-module-msgraph/CHANGELOG.md +++ b/plugins/catalog-backend-module-msgraph/CHANGELOG.md @@ -1,5 +1,20 @@ # @backstage/plugin-catalog-backend-module-msgraph +## 0.2.11 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/plugin-catalog-backend@0.19.0 + +## 0.2.10 + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-catalog-backend@0.18.0 + ## 0.2.9 ### Patch Changes diff --git a/plugins/catalog-backend-module-msgraph/api-report.md b/plugins/catalog-backend-module-msgraph/api-report.md index 1357659739..e1a837d0c1 100644 --- a/plugins/catalog-backend-module-msgraph/api-report.md +++ b/plugins/catalog-backend-module-msgraph/api-report.md @@ -13,6 +13,7 @@ import { LocationSpec } from '@backstage/catalog-model'; import { Logger as Logger_2 } from 'winston'; import * as MicrosoftGraph from '@microsoft/microsoft-graph-types'; import * as msal from '@azure/msal-node'; +import { Response as Response_2 } from 'node-fetch'; import { UserEntity } from '@backstage/catalog-model'; // Warning: (ae-missing-release-tag) "defaultGroupTransformer" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -88,11 +89,11 @@ export class MicrosoftGraphClient { // Warning: (ae-unresolved-link) The @link reference could not be resolved: The package "@backstage/plugin-catalog-backend-module-msgraph" does not have an export "ODataQuery" getUsers(query?: ODataQuery): AsyncIterable; // Warning: (ae-unresolved-link) The @link reference could not be resolved: The package "@backstage/plugin-catalog-backend-module-msgraph" does not have an export "ODataQuery" - requestApi(path: string, query?: ODataQuery): Promise; + requestApi(path: string, query?: ODataQuery): Promise; // Warning: (ae-forgotten-export) The symbol "ODataQuery" needs to be exported by the entry point index.d.ts // Warning: (ae-unresolved-link) The @link reference could not be resolved: The package "@backstage/plugin-catalog-backend-module-msgraph" does not have an export "ODataQuery" requestCollection(path: string, query?: ODataQuery): AsyncIterable; - requestRaw(url: string): Promise; + requestRaw(url: string): Promise; } // Warning: (ae-missing-release-tag) "MicrosoftGraphOrgEntityProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) diff --git a/plugins/catalog-backend-module-msgraph/package.json b/plugins/catalog-backend-module-msgraph/package.json index 222f56b022..8e9b99931c 100644 --- a/plugins/catalog-backend-module-msgraph/package.json +++ b/plugins/catalog-backend-module-msgraph/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-catalog-backend-module-msgraph", "description": "A Backstage catalog backend modules that helps integrate towards Microsoft Graph", - "version": "0.2.9", + "version": "0.2.11", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -32,18 +32,19 @@ "@azure/msal-node": "^1.1.0", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", - "@backstage/plugin-catalog-backend": "^0.17.4", + "@backstage/plugin-catalog-backend": "^0.19.0", "@microsoft/microsoft-graph-types": "^2.6.0", - "cross-fetch": "^3.0.6", + "@types/node-fetch": "^2.5.12", "lodash": "^4.17.21", + "node-fetch": "^2.6.1", "p-limit": "^3.0.2", "winston": "^3.2.1", "qs": "^6.9.4" }, "devDependencies": { - "@backstage/backend-common": "^0.9.10", - "@backstage/cli": "^0.9.0", - "@backstage/test-utils": "^0.1.22", + "@backstage/backend-common": "^0.9.12", + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.23", "@types/lodash": "^4.14.151", "msw": "^0.35.0" }, diff --git a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.ts b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.ts index 83b4371c0d..63f256afbd 100644 --- a/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.ts +++ b/plugins/catalog-backend-module-msgraph/src/microsoftGraph/client.ts @@ -16,7 +16,7 @@ import * as msal from '@azure/msal-node'; import * as MicrosoftGraph from '@microsoft/microsoft-graph-types'; -import fetch from 'cross-fetch'; +import fetch, { Response } from 'node-fetch'; import qs from 'qs'; import { MicrosoftGraphProviderConfig } from './config'; diff --git a/plugins/catalog-backend/CHANGELOG.md b/plugins/catalog-backend/CHANGELOG.md index 92b57f3483..93e41cfddc 100644 --- a/plugins/catalog-backend/CHANGELOG.md +++ b/plugins/catalog-backend/CHANGELOG.md @@ -1,5 +1,107 @@ # @backstage/plugin-catalog-backend +## 0.19.0 + +### Minor Changes + +- 905dd952ac: **BREAKING** `DefaultCatalogCollator` has a new required option `tokenManager`. See the create-app changelog for how to create a `tokenManager` and add it to the `PluginEnvironment`. It can then be passed to the collator in `createPlugin`: + + ```diff + // packages/backend/src/plugins/search.ts + + ... + export default async function createPlugin({ + ... + + tokenManager, + }: PluginEnvironment) { + ... + + indexBuilder.addCollator({ + defaultRefreshIntervalSeconds: 600, + collator: DefaultCatalogCollator.fromConfig(config, { + discovery, + + tokenManager, + }), + }); + + ... + } + ``` + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/backend-common@0.9.12 + +## 0.18.0 + +### Minor Changes + +- 7f82ce9f51: **BREAKING** EntitiesSearchFilter fields have changed. + + EntitiesSearchFilter now has only two fields: `key` and `value`. The `matchValueIn` and `matchValueExists` fields are no longer are supported. Previous filters written using the `matchValueIn` and `matchValueExists` fields can be rewritten as follows: + + Filtering by existence of key only: + + ```diff + filter: { + { + key: 'abc', + - matchValueExists: true, + }, + } + ``` + + Filtering by key and values: + + ```diff + filter: { + { + key: 'abc', + - matchValueExists: true, + - matchValueIn: ['xyz'], + + values: ['xyz'], + }, + } + ``` + + Negation of filters can now be achieved through a `not` object: + + ``` + filter: { + not: { + key: 'abc', + values: ['xyz'], + }, + } + ``` + +### Patch Changes + +- 740f958290: Providing an empty values array in an EntityFilter will now return no matches. +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- eddb82ab7c: Index User entities by displayName to be able to search by full name. Added displayName (if present) to the 'text' field in the indexed document. +- 563b039f0b: Added Azure DevOps discovery processor +- 8866b62f3d: Detect a duplicate entities when adding locations through dry run +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/backend-common@0.9.11 + ## 0.17.4 ### Patch Changes diff --git a/plugins/catalog-backend/api-report.md b/plugins/catalog-backend/api-report.md index 7363a803c8..43eb8d61b7 100644 --- a/plugins/catalog-backend/api-report.md +++ b/plugins/catalog-backend/api-report.md @@ -31,6 +31,7 @@ import { ResourceEntityV1alpha1 } from '@backstage/catalog-model'; import { Router } from 'express'; import { ScmIntegrationRegistry } from '@backstage/integration'; import { ScmIntegrations } from '@backstage/integration'; +import { TokenManager } from '@backstage/backend-common'; import { UrlReader } from '@backstage/backend-common'; import { Validators } from '@backstage/catalog-model'; @@ -756,8 +757,10 @@ export class DefaultCatalogCollator implements DocumentCollator { locationTemplate, filter, catalogClient, + tokenManager, }: { discovery: PluginEndpointDiscovery; + tokenManager: TokenManager; locationTemplate?: string; filter?: CatalogEntitiesRequest['filter']; catalogClient?: CatalogApi; @@ -780,12 +783,15 @@ export class DefaultCatalogCollator implements DocumentCollator { _config: Config, options: { discovery: PluginEndpointDiscovery; + tokenManager: TokenManager; filter?: CatalogEntitiesRequest['filter']; }, ): DefaultCatalogCollator; // (undocumented) protected locationTemplate: string; // (undocumented) + protected tokenManager: TokenManager; + // (undocumented) readonly type: string; } diff --git a/plugins/catalog-backend/package.json b/plugins/catalog-backend/package.json index a9a35d5858..694db42877 100644 --- a/plugins/catalog-backend/package.json +++ b/plugins/catalog-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-catalog-backend", "description": "The Backstage backend plugin that provides the Backstage catalog", - "version": "0.17.4", + "version": "0.19.0", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -30,12 +30,12 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", + "@backstage/errors": "^0.1.5", + "@backstage/integration": "^0.6.10", "@backstage/search-common": "^0.2.1", "@backstage/types": "^0.1.1", "@octokit/graphql": "^4.5.8", @@ -43,7 +43,6 @@ "aws-sdk": "^2.840.0", "codeowners-utils": "^1.0.2", "core-js": "^3.6.5", - "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", "fast-json-stable-stringify": "^2.1.0", @@ -53,6 +52,7 @@ "knex": "^0.95.1", "lodash": "^4.17.21", "luxon": "^2.0.2", + "node-fetch": "^2.6.1", "p-limit": "^3.0.2", "prom-client": "^13.2.0", "uuid": "^8.0.0", @@ -62,9 +62,9 @@ "yup": "^0.32.9" }, "devDependencies": { - "@backstage/backend-test-utils": "^0.1.9", - "@backstage/cli": "^0.9.0", - "@backstage/test-utils": "^0.1.22", + "@backstage/backend-test-utils": "^0.1.10", + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.23", "@types/core-js": "^2.5.4", "@types/git-url-parse": "^9.0.0", "@types/lodash": "^4.14.151", diff --git a/plugins/catalog-backend/src/ingestion/processors/azure/azure.ts b/plugins/catalog-backend/src/ingestion/processors/azure/azure.ts index 0c7b17483a..316c9b0b8c 100644 --- a/plugins/catalog-backend/src/ingestion/processors/azure/azure.ts +++ b/plugins/catalog-backend/src/ingestion/processors/azure/azure.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import { AzureIntegrationConfig, getAzureRequestOptions, diff --git a/plugins/catalog-backend/src/ingestion/processors/bitbucket/client.ts b/plugins/catalog-backend/src/ingestion/processors/bitbucket/client.ts index b578799229..0c132bb61b 100644 --- a/plugins/catalog-backend/src/ingestion/processors/bitbucket/client.ts +++ b/plugins/catalog-backend/src/ingestion/processors/bitbucket/client.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import { BitbucketIntegrationConfig, diff --git a/plugins/catalog-backend/src/ingestion/processors/gitlab/client.ts b/plugins/catalog-backend/src/ingestion/processors/gitlab/client.ts index 8781e071f7..d1765521a3 100644 --- a/plugins/catalog-backend/src/ingestion/processors/gitlab/client.ts +++ b/plugins/catalog-backend/src/ingestion/processors/gitlab/client.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import { getGitLabRequestOptions, GitLabIntegrationConfig, diff --git a/plugins/catalog-backend/src/search/DefaultCatalogCollator.test.ts b/plugins/catalog-backend/src/search/DefaultCatalogCollator.test.ts index 8f1af6f615..1360ca2647 100644 --- a/plugins/catalog-backend/src/search/DefaultCatalogCollator.test.ts +++ b/plugins/catalog-backend/src/search/DefaultCatalogCollator.test.ts @@ -14,7 +14,10 @@ * limitations under the License. */ -import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { + PluginEndpointDiscovery, + TokenManager, +} from '@backstage/backend-common'; import { Entity } from '@backstage/catalog-model'; import { DefaultCatalogCollator } from './DefaultCatalogCollator'; import { setupServer } from 'msw/node'; @@ -55,6 +58,7 @@ const expectedEntities: Entity[] = [ describe('DefaultCatalogCollator', () => { let mockDiscoveryApi: jest.Mocked; + let mockTokenManager: jest.Mocked; let collator: DefaultCatalogCollator; beforeAll(() => { @@ -62,7 +66,14 @@ describe('DefaultCatalogCollator', () => { getBaseUrl: jest.fn().mockResolvedValue('http://localhost:7007'), getExternalBaseUrl: jest.fn(), }; - collator = new DefaultCatalogCollator({ discovery: mockDiscoveryApi }); + mockTokenManager = { + getToken: jest.fn().mockResolvedValue({ token: '' }), + authenticate: jest.fn(), + }; + collator = new DefaultCatalogCollator({ + discovery: mockDiscoveryApi, + tokenManager: mockTokenManager, + }); server.listen(); }); beforeEach(() => { @@ -118,6 +129,7 @@ describe('DefaultCatalogCollator', () => { // Provide an alternate location template. collator = new DefaultCatalogCollator({ discovery: mockDiscoveryApi, + tokenManager: mockTokenManager, locationTemplate: '/software/:name', }); @@ -131,6 +143,7 @@ describe('DefaultCatalogCollator', () => { // Provide an alternate location template. collator = DefaultCatalogCollator.fromConfig(new ConfigReader({}), { discovery: mockDiscoveryApi, + tokenManager: mockTokenManager, filter: { kind: ['Foo', 'Bar'], }, diff --git a/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts b/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts index 3e19b38ea6..4c6342c6c6 100644 --- a/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts +++ b/plugins/catalog-backend/src/search/DefaultCatalogCollator.ts @@ -14,7 +14,10 @@ * limitations under the License. */ -import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { + PluginEndpointDiscovery, + TokenManager, +} from '@backstage/backend-common'; import { Entity, UserEntity } from '@backstage/catalog-model'; import { IndexableDocument, DocumentCollator } from '@backstage/search-common'; import { Config } from '@backstage/config'; @@ -38,11 +41,13 @@ export class DefaultCatalogCollator implements DocumentCollator { protected filter?: CatalogEntitiesRequest['filter']; protected readonly catalogClient: CatalogApi; public readonly type: string = 'software-catalog'; + protected tokenManager: TokenManager; static fromConfig( _config: Config, options: { discovery: PluginEndpointDiscovery; + tokenManager: TokenManager; filter?: CatalogEntitiesRequest['filter']; }, ) { @@ -56,8 +61,10 @@ export class DefaultCatalogCollator implements DocumentCollator { locationTemplate, filter, catalogClient, + tokenManager, }: { discovery: PluginEndpointDiscovery; + tokenManager: TokenManager; locationTemplate?: string; filter?: CatalogEntitiesRequest['filter']; catalogClient?: CatalogApi; @@ -68,6 +75,7 @@ export class DefaultCatalogCollator implements DocumentCollator { this.filter = filter; this.catalogClient = catalogClient || new CatalogClient({ discoveryApi: discovery }); + this.tokenManager = tokenManager; } protected applyArgsToFormat( @@ -100,9 +108,13 @@ export class DefaultCatalogCollator implements DocumentCollator { } async execute() { - const response = await this.catalogClient.getEntities({ - filter: this.filter, - }); + const { token } = await this.tokenManager.getToken(); + const response = await this.catalogClient.getEntities( + { + filter: this.filter, + }, + { token }, + ); return response.items.map((entity: Entity): CatalogEntityDocument => { return { title: entity.metadata.title ?? entity.metadata.name, diff --git a/plugins/catalog-backend/src/service/NextCatalogBuilder.ts b/plugins/catalog-backend/src/service/NextCatalogBuilder.ts index c9ebc8f723..1618ef8d7b 100644 --- a/plugins/catalog-backend/src/service/NextCatalogBuilder.ts +++ b/plugins/catalog-backend/src/service/NextCatalogBuilder.ts @@ -336,7 +336,10 @@ export class NextCatalogBuilder { const parser = this.parser || defaultEntityDataParser; const dbClient = await database.getClient(); - await applyDatabaseMigrations(dbClient); + if (!database.migrations?.skip) { + logger.info('Performing database migration'); + await applyDatabaseMigrations(dbClient); + } const db = new CommonDatabase(dbClient, logger); diff --git a/plugins/catalog-backend/src/stitching/Stitcher.ts b/plugins/catalog-backend/src/stitching/Stitcher.ts index 507f3aa53e..b4a693a4fa 100644 --- a/plugins/catalog-backend/src/stitching/Stitcher.ts +++ b/plugins/catalog-backend/src/stitching/Stitcher.ts @@ -209,6 +209,11 @@ export class Stitcher { entity.metadata.etag = hash; } + // This may throw if the entity is invalid, so we call it before + // the final_entites write, even though we may end up not needing + // to write the search index. + const searchEntries = buildEntitySearch(entityId, entity); + const rowsChanged = await this.database( 'final_entities', ) @@ -235,7 +240,6 @@ export class Stitcher { // B writes the entity -> // B writes search -> // A writes search - const searchEntries = buildEntitySearch(entityId, entity); await this.database('search') .where({ entity_id: entityId }) .delete(); diff --git a/plugins/catalog-backend/src/stitching/buildEntitySearch.test.ts b/plugins/catalog-backend/src/stitching/buildEntitySearch.test.ts index 9043dab9ba..58551a461f 100644 --- a/plugins/catalog-backend/src/stitching/buildEntitySearch.test.ts +++ b/plugins/catalog-backend/src/stitching/buildEntitySearch.test.ts @@ -163,5 +163,51 @@ describe('buildEntitySearch', () => { { entity_id: 'eid', key: 'relations.t2', value: 'k:ns/b' }, ]); }); + + it('rejects duplicate keys', () => { + expect(() => + buildEntitySearch('eid', { + relations: [], + apiVersion: 'a', + kind: 'b', + metadata: { + name: 'n', + Namespace: 'ns', + }, + }), + ).toThrow( + `Entity has duplicate keys that vary only in casing, 'metadata.namespace'`, + ); + + expect(() => + buildEntitySearch('eid', { + relations: [ + { type: 'dup', target: { kind: 'k', namespace: 'ns', name: 'a' } }, + { type: 'DUP', target: { kind: 'k', namespace: 'ns', name: 'b' } }, + ], + apiVersion: 'a', + kind: 'b', + metadata: { name: 'n' }, + }), + ).toThrow( + `Entity has duplicate keys that vary only in casing, 'relations.dup'`, + ); + + expect(() => + buildEntitySearch('eid', { + apiVersion: 'a', + kind: 'b', + metadata: { name: 'n' }, + spec: { + owner: 'o', + OWNER: 'o', + lifecycle: 'production', + lifeCycle: 'production', + }, + }), + ).toThrow( + `Entity has duplicate keys that vary only in casing, 'spec.owner', 'spec.lifecycle'`, + ); + }); }); }); diff --git a/plugins/catalog-backend/src/stitching/buildEntitySearch.ts b/plugins/catalog-backend/src/stitching/buildEntitySearch.ts index ed84dfa018..b6c3eead2a 100644 --- a/plugins/catalog-backend/src/stitching/buildEntitySearch.ts +++ b/plugins/catalog-backend/src/stitching/buildEntitySearch.ts @@ -19,6 +19,7 @@ import { ENTITY_DEFAULT_NAMESPACE, stringifyEntityRef, } from '@backstage/catalog-model'; +import { InputError } from '@backstage/errors'; import { DbSearchRow } from '../database/tables'; // These are excluded in the generic loop, either because they do not make sense @@ -184,5 +185,23 @@ export function buildEntitySearch( }); } + // This validates that there are no keys that vary only in casing, such + // as `spec.foo` and `spec.Foo`. + const keys = new Set(raw.map(r => r.key)); + const lowerKeys = new Set(raw.map(r => r.key.toLocaleLowerCase('en-US'))); + if (keys.size !== lowerKeys.size) { + const difference = []; + for (const key of keys) { + const lower = key.toLocaleLowerCase('en-US'); + if (!lowerKeys.delete(lower)) { + difference.push(lower); + } + } + const badKeys = `'${difference.join("', '")}'`; + throw new InputError( + `Entity has duplicate keys that vary only in casing, ${badKeys}`, + ); + } + return mapToRows(raw, entityId); } diff --git a/plugins/catalog-graph/package.json b/plugins/catalog-graph/package.json index 13869cfd38..2a44593a4a 100644 --- a/plugins/catalog-graph/package.json +++ b/plugins/catalog-graph/package.json @@ -23,10 +23,10 @@ "dependencies": { "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -41,10 +41,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/catalog-graphql/CHANGELOG.md b/plugins/catalog-graphql/CHANGELOG.md index e123f3b17f..fe6cc4cc00 100644 --- a/plugins/catalog-graphql/CHANGELOG.md +++ b/plugins/catalog-graphql/CHANGELOG.md @@ -1,5 +1,11 @@ # @backstage/plugin-catalog-graphql +## 0.2.14 + +### Patch Changes + +- 6b500622d5: Move to using node-fetch internally instead of cross-fetch + ## 0.2.13 ### Patch Changes diff --git a/plugins/catalog-graphql/package.json b/plugins/catalog-graphql/package.json index a7070a1634..9ed6918110 100644 --- a/plugins/catalog-graphql/package.json +++ b/plugins/catalog-graphql/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-catalog-graphql", "description": "An experimental Backstage catalog GraphQL module", - "version": "0.2.13", + "version": "0.2.14", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -36,14 +36,14 @@ "@backstage/types": "^0.1.1", "@graphql-modules/core": "^0.7.17", "apollo-server": "^2.16.1", - "cross-fetch": "^3.0.6", "graphql": "^15.3.0", "graphql-tag": "^2.11.0", "graphql-type-json": "^0.3.2", + "node-fetch": "^2.6.1", "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/test-utils": "^0.1.22", "@graphql-codegen/cli": "^1.21.3", "@graphql-codegen/typescript": "^1.17.7", diff --git a/plugins/catalog-graphql/src/service/client.ts b/plugins/catalog-graphql/src/service/client.ts index 4328a5bd5a..8d517fcbd6 100644 --- a/plugins/catalog-graphql/src/service/client.ts +++ b/plugins/catalog-graphql/src/service/client.ts @@ -15,7 +15,7 @@ */ import { Entity, EntityMeta } from '@backstage/catalog-model'; -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import { JsonObject } from '@backstage/types'; export interface ReaderEntityMeta extends EntityMeta { @@ -26,11 +26,14 @@ export interface ReaderEntityMeta extends EntityMeta { annotations: Record; labels: Record; } + export interface ReaderEntity extends Entity { metadata: JsonObject & ReaderEntityMeta; } + export class CatalogClient { constructor(private baseUrl: string) {} + async list(): Promise { const res = await fetch(`${this.baseUrl}/catalog/entities`); if (!res.ok) { @@ -39,7 +42,7 @@ export class CatalogClient { throw new Error(await res.text()); } - const entities: ReaderEntity[] = await res.json(); + const entities = (await res.json()) as ReaderEntity[]; return entities; } } diff --git a/plugins/catalog-import/package.json b/plugins/catalog-import/package.json index 933a84f13e..b370c9fa33 100644 --- a/plugins/catalog-import/package.json +++ b/plugins/catalog-import/package.json @@ -33,10 +33,10 @@ "dependencies": { "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.3", - "@backstage/integration": "^0.6.8", + "@backstage/integration": "^0.6.10", "@backstage/integration-react": "^0.1.14", "@backstage/plugin-catalog-react": "^0.6.4", "@material-ui/core": "^4.12.2", @@ -55,10 +55,10 @@ "yaml": "^1.10.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/catalog-react/package.json b/plugins/catalog-react/package.json index 2ae853650a..c65f9144e5 100644 --- a/plugins/catalog-react/package.json +++ b/plugins/catalog-react/package.json @@ -31,11 +31,11 @@ "dependencies": { "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", - "@backstage/core-app-api": "^0.1.21", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-app-api": "^0.1.24", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", + "@backstage/integration": "^0.6.10", "@backstage/types": "^0.1.1", "@backstage/version-bridge": "^0.1.0", "@material-ui/core": "^4.12.2", @@ -51,7 +51,7 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/test-utils": "^0.1.22", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", diff --git a/plugins/catalog/package.json b/plugins/catalog/package.json index ddee20c488..6caadb7b42 100644 --- a/plugins/catalog/package.json +++ b/plugins/catalog/package.json @@ -33,16 +33,17 @@ "dependencies": { "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.3", "@backstage/integration-react": "^0.1.14", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", "@types/react": "*", + "history": "^5.0.0", "lodash": "^4.17.21", "react": "^16.13.1", "react-dom": "^16.13.1", @@ -51,10 +52,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/circleci/CHANGELOG.md b/plugins/circleci/CHANGELOG.md index 18e227627b..aa0b5a08a7 100644 --- a/plugins/circleci/CHANGELOG.md +++ b/plugins/circleci/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/plugin-circleci +## 0.2.30 + +### Patch Changes + +- 5a46712a7d: Fixed a bug in the `CircleCI` plugin where restarting builds was hard-coded to GitHub rather than introspecting the entity source location. +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + ## 0.2.29 ### Patch Changes diff --git a/plugins/circleci/package.json b/plugins/circleci/package.json index 7228044f4f..45579ab82b 100644 --- a/plugins/circleci/package.json +++ b/plugins/circleci/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-circleci", "description": "A Backstage plugin that integrates towards Circle CI", - "version": "0.2.29", + "version": "0.2.30", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -33,10 +33,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -52,10 +52,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/circleci/src/state/useBuilds.ts b/plugins/circleci/src/state/useBuilds.ts index a9869644a3..521a55e922 100644 --- a/plugins/circleci/src/state/useBuilds.ts +++ b/plugins/circleci/src/state/useBuilds.ts @@ -162,7 +162,7 @@ export function useBuilds() { vcs: { owner: owner, repo: repo, - type: GitType.GITHUB, + type: mapVcsType(vcs), }, }); } catch (e) { diff --git a/plugins/cloudbuild/package.json b/plugins/cloudbuild/package.json index 4125a8c82e..3c9e14c9e7 100644 --- a/plugins/cloudbuild/package.json +++ b/plugins/cloudbuild/package.json @@ -32,10 +32,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -49,10 +49,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/code-coverage-backend/CHANGELOG.md b/plugins/code-coverage-backend/CHANGELOG.md index 8e8f9ceac8..387e86bc46 100644 --- a/plugins/code-coverage-backend/CHANGELOG.md +++ b/plugins/code-coverage-backend/CHANGELOG.md @@ -1,5 +1,36 @@ # @backstage/plugin-code-coverage-backend +## 0.1.16 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/backend-common@0.9.12 + +## 0.1.15 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/backend-common@0.9.11 + ## 0.1.14 ### Patch Changes diff --git a/plugins/code-coverage-backend/package.json b/plugins/code-coverage-backend/package.json index 90320d0e41..83a0acf9c2 100644 --- a/plugins/code-coverage-backend/package.json +++ b/plugins/code-coverage-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-code-coverage-backend", "description": "A Backstage backend plugin that helps you keep track of your code coverage", - "version": "0.1.14", + "version": "0.1.16", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,14 +20,13 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", - "@backstage/errors": "^0.1.3", - "@backstage/integration": "^0.6.8", + "@backstage/errors": "^0.1.5", + "@backstage/integration": "^0.6.10", "@types/express": "^4.17.6", - "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", "express-xml-bodyparser": "^0.3.0", @@ -37,7 +36,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/express-xml-bodyparser": "^0.3.2", "@types/supertest": "^2.0.8", "msw": "^0.35.0", diff --git a/plugins/code-coverage/package.json b/plugins/code-coverage/package.json index e5b51e90b4..907a0abcd7 100644 --- a/plugins/code-coverage/package.json +++ b/plugins/code-coverage/package.json @@ -23,11 +23,11 @@ "dependencies": { "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.4", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -42,10 +42,10 @@ "recharts": "^1.8.5" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/config-schema/CHANGELOG.md b/plugins/config-schema/CHANGELOG.md index ca889ebdbd..fc4f8697b8 100644 --- a/plugins/config-schema/CHANGELOG.md +++ b/plugins/config-schema/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/plugin-config-schema +## 0.1.14 + +### Patch Changes + +- 9f21236a29: Fixed a missing `await` when throwing server side errors +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.1.13 ### Patch Changes diff --git a/plugins/config-schema/package.json b/plugins/config-schema/package.json index c9abbc7e4e..6b79c5493c 100644 --- a/plugins/config-schema/package.json +++ b/plugins/config-schema/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-config-schema", "description": "A Backstage plugin that lets you browse the configuration schema of your app", - "version": "0.1.13", + "version": "0.1.14", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -22,10 +22,10 @@ }, "dependencies": { "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/errors": "^0.1.4", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/errors": "^0.1.5", + "@backstage/theme": "^0.2.14", "@backstage/types": "^0.1.1", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", @@ -37,10 +37,10 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/cost-insights/CHANGELOG.md b/plugins/cost-insights/CHANGELOG.md index 7096af37c6..c43d7c0612 100644 --- a/plugins/cost-insights/CHANGELOG.md +++ b/plugins/cost-insights/CHANGELOG.md @@ -1,5 +1,14 @@ # @backstage/plugin-cost-insights +## 0.11.12 + +### Patch Changes + +- 950b36393c: Supply featureFlags using featureFlag config option. +- Updated dependencies + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.11.11 ### Patch Changes diff --git a/plugins/cost-insights/package.json b/plugins/cost-insights/package.json index da9ba8b1f6..6a2d582d63 100644 --- a/plugins/cost-insights/package.json +++ b/plugins/cost-insights/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-cost-insights", "description": "A Backstage plugin that helps you keep track of your cloud spend", - "version": "0.11.11", + "version": "0.11.12", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -32,9 +32,9 @@ }, "dependencies": { "@backstage/config": "^0.1.10", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -55,10 +55,10 @@ "yup": "^0.32.9" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/explore-react/package.json b/plugins/explore-react/package.json index a67f8b6892..00e5e87918 100644 --- a/plugins/explore-react/package.json +++ b/plugins/explore-react/package.json @@ -29,10 +29,10 @@ "postpack": "backstage-cli postpack" }, "dependencies": { - "@backstage/core-plugin-api": "^0.2.0" + "@backstage/core-plugin-api": "^0.2.2" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@backstage/dev-utils": "^0.2.13", "@backstage/test-utils": "^0.1.22", "@testing-library/jest-dom": "^5.10.1", diff --git a/plugins/explore/package.json b/plugins/explore/package.json index d9945edc51..b4e08a526f 100644 --- a/plugins/explore/package.json +++ b/plugins/explore/package.json @@ -32,11 +32,11 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", "@backstage/plugin-explore-react": "^0.0.7", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -49,10 +49,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/firehydrant/package.json b/plugins/firehydrant/package.json index f332efc150..2b3bf05b1e 100644 --- a/plugins/firehydrant/package.json +++ b/plugins/firehydrant/package.json @@ -22,10 +22,10 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -35,10 +35,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/fossa/CHANGELOG.md b/plugins/fossa/CHANGELOG.md index af99e13c4a..e0ad30ef69 100644 --- a/plugins/fossa/CHANGELOG.md +++ b/plugins/fossa/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/plugin-fossa +## 0.2.23 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + ## 0.2.22 ### Patch Changes diff --git a/plugins/fossa/package.json b/plugins/fossa/package.json index cc0b486d60..7d56fdc333 100644 --- a/plugins/fossa/package.json +++ b/plugins/fossa/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-fossa", "description": "A Backstage plugin that integrates towards FOSSA", - "version": "0.2.22", + "version": "0.2.23", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -33,11 +33,11 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.3", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -49,16 +49,15 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", "@types/jest": "^26.0.7", "@types/node": "^14.14.32", - "cross-fetch": "^3.0.6", "msw": "^0.35.0" }, "files": [ diff --git a/plugins/gcp-projects/package.json b/plugins/gcp-projects/package.json index cd1c3ac4a1..a3a53b317e 100644 --- a/plugins/gcp-projects/package.json +++ b/plugins/gcp-projects/package.json @@ -31,9 +31,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -43,10 +43,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/git-release-manager/package.json b/plugins/git-release-manager/package.json index 7f7ff6184d..c5ef82ac16 100644 --- a/plugins/git-release-manager/package.json +++ b/plugins/git-release-manager/package.json @@ -21,10 +21,10 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/integration": "^0.6.8", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/integration": "^0.6.10", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -39,10 +39,10 @@ "recharts": "^1.8.5" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/github-actions/CHANGELOG.md b/plugins/github-actions/CHANGELOG.md index 5eed309d68..7992f201cf 100644 --- a/plugins/github-actions/CHANGELOG.md +++ b/plugins/github-actions/CHANGELOG.md @@ -1,5 +1,27 @@ # @backstage/plugin-github-actions +## 0.4.25 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.4.24 ### Patch Changes diff --git a/plugins/github-actions/package.json b/plugins/github-actions/package.json index ae7f32be1f..b0fa469a50 100644 --- a/plugins/github-actions/package.json +++ b/plugins/github-actions/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-github-actions", "description": "A Backstage plugin that integrates towards GitHub Actions", - "version": "0.4.24", + "version": "0.4.25", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -34,11 +34,11 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/integration": "^0.6.8", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/integration": "^0.6.10", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -52,10 +52,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/github-deployments/package.json b/plugins/github-deployments/package.json index 062113a8ef..a1dad4ecca 100644 --- a/plugins/github-deployments/package.json +++ b/plugins/github-deployments/package.json @@ -22,13 +22,13 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.3", - "@backstage/integration": "^0.6.8", + "@backstage/integration": "^0.6.10", "@backstage/integration-react": "^0.1.14", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -39,10 +39,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/gitops-profiles/package.json b/plugins/gitops-profiles/package.json index dfbd6297cf..6b211f59ed 100644 --- a/plugins/gitops-profiles/package.json +++ b/plugins/gitops-profiles/package.json @@ -32,9 +32,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -44,10 +44,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/graphiql/CHANGELOG.md b/plugins/graphiql/CHANGELOG.md index f6c8b9fde8..571024eaec 100644 --- a/plugins/graphiql/CHANGELOG.md +++ b/plugins/graphiql/CHANGELOG.md @@ -1,5 +1,20 @@ # @backstage/plugin-graphiql +## 0.2.23 + +### Patch Changes + +- dde1681f33: chore(dependencies): bump `graphiql` package to latest + +## 0.2.22 + +### Patch Changes + +- cd398cd4ab: Letting GraphiQL use headers +- Updated dependencies + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.2.21 ### Patch Changes diff --git a/plugins/graphiql/package.json b/plugins/graphiql/package.json index 5c72a4c728..a3aaf7fa69 100644 --- a/plugins/graphiql/package.json +++ b/plugins/graphiql/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-graphiql", "description": "Backstage plugin for browsing GraphQL APIs", - "version": "0.2.21", + "version": "0.2.23", "private": false, "publishConfig": { "access": "public", @@ -31,23 +31,23 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", - "graphiql": "^1.0.0-alpha.10", - "graphql": "15.5.0", + "graphiql": "^1.5.12", + "graphql": "^16.0.0", "react": "^16.13.1", "react-dom": "^16.13.1", "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/graphql-backend/package.json b/plugins/graphql-backend/package.json index 335545021e..5b505ee828 100644 --- a/plugins/graphql-backend/package.json +++ b/plugins/graphql-backend/package.json @@ -31,9 +31,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/config": "^0.1.8", - "@backstage/plugin-catalog-graphql": "^0.2.12", + "@backstage/plugin-catalog-graphql": "^0.2.14", "@graphql-modules/core": "^0.7.17", "@types/express": "^4.17.6", "apollo-server": "^2.16.1", @@ -47,7 +47,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/supertest": "^2.0.8", "eslint-plugin-graphql": "^4.0.0", "msw": "^0.35.0", diff --git a/plugins/home/package.json b/plugins/home/package.json index ef13ce3a00..97ec5fdfc2 100644 --- a/plugins/home/package.json +++ b/plugins/home/package.json @@ -21,9 +21,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -35,10 +35,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/ilert/package.json b/plugins/ilert/package.json index 6011dd4f46..2e477b2f06 100644 --- a/plugins/ilert/package.json +++ b/plugins/ilert/package.json @@ -22,11 +22,11 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.3", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@date-io/luxon": "1.x", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", @@ -39,10 +39,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/jenkins-backend/CHANGELOG.md b/plugins/jenkins-backend/CHANGELOG.md index 48f4461f7f..19d743b250 100644 --- a/plugins/jenkins-backend/CHANGELOG.md +++ b/plugins/jenkins-backend/CHANGELOG.md @@ -1,5 +1,34 @@ # @backstage/plugin-jenkins-backend +## 0.1.9 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/backend-common@0.9.12 + +## 0.1.8 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/backend-common@0.9.11 + ## 0.1.7 ### Patch Changes diff --git a/plugins/jenkins-backend/package.json b/plugins/jenkins-backend/package.json index ac9efb3ffd..db4298e6c2 100644 --- a/plugins/jenkins-backend/package.json +++ b/plugins/jenkins-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-jenkins-backend", "description": "A Backstage backend plugin that integrates towards Jenkins", - "version": "0.1.7", + "version": "0.1.9", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -22,12 +22,11 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", "@types/express": "^4.17.6", - "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", "jenkins": "^0.28.1", @@ -35,7 +34,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jenkins": "^0.23.1", "@types/supertest": "^2.0.8", "msw": "^0.35.0", diff --git a/plugins/jenkins/CHANGELOG.md b/plugins/jenkins/CHANGELOG.md index 369676b195..1daba68a1d 100644 --- a/plugins/jenkins/CHANGELOG.md +++ b/plugins/jenkins/CHANGELOG.md @@ -1,5 +1,14 @@ # @backstage/plugin-jenkins +## 0.5.13 + +### Patch Changes + +- ad433b346f: Fix Jenkins project table pagination. +- Updated dependencies + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.5.12 ### Patch Changes diff --git a/plugins/jenkins/package.json b/plugins/jenkins/package.json index 4456b15284..e879d13a88 100644 --- a/plugins/jenkins/package.json +++ b/plugins/jenkins/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-jenkins", "description": "A Backstage plugin that integrates towards Jenkins", - "version": "0.5.12", + "version": "0.5.13", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -33,10 +33,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -48,10 +48,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx b/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx index 39187fe859..b1eaf2c24c 100644 --- a/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx +++ b/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx @@ -205,6 +205,10 @@ export const CITableView = ({ onChangePageSize, total, }: Props) => { + const projectsInPage = projects?.slice( + page * pageSize, + Math.min(projects.length, (page + 1) * pageSize), + ); return ( retry(), }, ]} - data={projects ?? []} + data={projectsInPage ?? []} onPageChange={onChangePage} onRowsPerPageChange={onChangePageSize} title={ diff --git a/plugins/kafka-backend/CHANGELOG.md b/plugins/kafka-backend/CHANGELOG.md index 482c1f75b1..9a417b04b0 100644 --- a/plugins/kafka-backend/CHANGELOG.md +++ b/plugins/kafka-backend/CHANGELOG.md @@ -1,5 +1,14 @@ # @backstage/plugin-kafka-backend +## 0.2.12 + +### Patch Changes + +- 4f81bfd356: Add ACL requirements for kafka-backend plugin +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/backend-common@0.9.11 + ## 0.2.11 ### Patch Changes diff --git a/plugins/kafka-backend/README.md b/plugins/kafka-backend/README.md index d18a232fa4..637a5773e0 100644 --- a/plugins/kafka-backend/README.md +++ b/plugins/kafka-backend/README.md @@ -49,3 +49,7 @@ kafka: username: my-username password: my-password ``` + +### ACLs + +If you are using ACLs on Kafka, you will need to have the `DESCRIBE` ACL on both consumer groups and topics. diff --git a/plugins/kafka-backend/package.json b/plugins/kafka-backend/package.json index dea803890f..7fb5578628 100644 --- a/plugins/kafka-backend/package.json +++ b/plugins/kafka-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-kafka-backend", "description": "A Backstage backend plugin that integrates towards Kafka", - "version": "0.2.11", + "version": "0.2.12", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -32,10 +32,10 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", - "@backstage/errors": "^0.1.3", + "@backstage/errors": "^0.1.5", "@types/express": "^4.17.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", @@ -44,7 +44,7 @@ "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest-when": "^2.7.2", "@types/lodash": "^4.14.151", "jest-when": "^3.1.0", diff --git a/plugins/kafka/package.json b/plugins/kafka/package.json index a6fbe36e99..41d677aece 100644 --- a/plugins/kafka/package.json +++ b/plugins/kafka/package.json @@ -22,10 +22,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -35,10 +35,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/kubernetes-backend/CHANGELOG.md b/plugins/kubernetes-backend/CHANGELOG.md index d506571a3f..15a69b3967 100644 --- a/plugins/kubernetes-backend/CHANGELOG.md +++ b/plugins/kubernetes-backend/CHANGELOG.md @@ -1,5 +1,25 @@ # @backstage/plugin-kubernetes-backend +## 0.3.20 + +### Patch Changes + +- 65ddccb5e8: Added apiVersionOverrides config to allow for specifying api versions to use for kubernetes objects +- f6087fc8f8: Query CronJobs from Kubernetes with apiGroup BatchV1beta1 +- Updated dependencies + - @backstage/backend-common@0.9.12 + - @backstage/plugin-kubernetes-common@0.1.7 + +## 0.3.19 + +### Patch Changes + +- 37dc844728: Include CronJobs and Jobs as default objects returned by the kubernetes backend and add/update relevant types. +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/plugin-kubernetes-common@0.1.6 + - @backstage/backend-common@0.9.11 + ## 0.3.18 ### Patch Changes diff --git a/plugins/kubernetes-backend/api-report.md b/plugins/kubernetes-backend/api-report.md index f34815f328..7d3adac1c4 100644 --- a/plugins/kubernetes-backend/api-report.md +++ b/plugins/kubernetes-backend/api-report.md @@ -10,6 +10,7 @@ import type { KubernetesFetchError } from '@backstage/plugin-kubernetes-common'; import type { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common'; import { Logger as Logger_2 } from 'winston'; import type { ObjectsByEntityResponse } from '@backstage/plugin-kubernetes-common'; +import { PodStatus } from '@kubernetes/client-node/dist/top'; // Warning: (ae-missing-release-tag) "AWSClusterDetails" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -34,6 +35,7 @@ export interface ClusterDetails { name: string; // (undocumented) serviceAccountToken?: string | undefined; + skipMetricsLookup?: boolean; // (undocumented) skipTLSVerify?: boolean; // (undocumented) @@ -164,6 +166,11 @@ export interface KubernetesFetcher { fetchObjectsForService( params: ObjectFetchParams, ): Promise; + // (undocumented) + fetchPodMetricsByNamespace( + clusterDetails: ClusterDetails, + namespace: string, + ): Promise; } // Warning: (ae-missing-release-tag) "KubernetesObjectsProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -202,6 +209,8 @@ export type KubernetesObjectTypes = | 'deployments' | 'replicasets' | 'horizontalpodautoscalers' + | 'jobs' + | 'cronjobs' | 'ingresses' | 'customresources'; diff --git a/plugins/kubernetes-backend/examples/dice-roller/README.md b/plugins/kubernetes-backend/examples/dice-roller/README.md index 5f541bb61d..d4725e38c0 100644 --- a/plugins/kubernetes-backend/examples/dice-roller/README.md +++ b/plugins/kubernetes-backend/examples/dice-roller/README.md @@ -27,14 +27,15 @@ Add or update `app-config.local.yaml` with the following: ```yaml kubernetes: - serviceLocatorMethod: 'multiTenant' + serviceLocatorMethod: + type: 'multiTenant' clusterLocatorMethods: - - 'config' - clusters: - - url: - name: minikube - serviceAccountToken: - authProvider: 'serviceAccount' + - type: 'config' + clusters: + - url: + name: minikube + serviceAccountToken: + authProvider: 'serviceAccount' ``` ### Getting the service account token diff --git a/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml b/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml index 68ef489170..fb71037129 100644 --- a/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml +++ b/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml @@ -200,6 +200,35 @@ spec: maxReplicas: 15 targetCPUUtilizationPercentage: 50 +--- +apiVersion: batch/v1 +kind: CronJob +metadata: + name: dice-roller-cronjob + labels: + 'backstage.io/kubernetes-id': dice-roller +spec: + schedule: '*/1 * * * *' + jobTemplate: + metadata: + labels: + 'backstage.io/kubernetes-id': dice-roller + spec: + template: + metadata: + labels: + 'backstage.io/kubernetes-id': dice-roller + spec: + containers: + - name: busybox + image: busybox + imagePullPolicy: IfNotPresent + command: + - /bin/sh + - -c + - date; echo Rolling a die! + restartPolicy: OnFailure + --- apiVersion: networking.k8s.io/v1beta1 kind: Ingress diff --git a/plugins/kubernetes-backend/examples/dice-roller/metrics-server.yaml b/plugins/kubernetes-backend/examples/dice-roller/metrics-server.yaml new file mode 100644 index 0000000000..673064aaf2 --- /dev/null +++ b/plugins/kubernetes-backend/examples/dice-roller/metrics-server.yaml @@ -0,0 +1,137 @@ +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: system:aggregated-metrics-reader + labels: + rbac.authorization.k8s.io/aggregate-to-view: 'true' + rbac.authorization.k8s.io/aggregate-to-edit: 'true' + rbac.authorization.k8s.io/aggregate-to-admin: 'true' +rules: + - apiGroups: ['metrics.k8s.io'] + resources: ['pods'] + verbs: ['get', 'list', 'watch'] +--- +apiVersion: rbac.authorization.k8s.io/v1beta1 +kind: ClusterRoleBinding +metadata: + name: metrics-server:system:auth-delegator +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: system:auth-delegator +subjects: + - kind: ServiceAccount + name: metrics-server + namespace: kube-system +--- +apiVersion: rbac.authorization.k8s.io/v1beta1 +kind: RoleBinding +metadata: + name: metrics-server-auth-reader + namespace: kube-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: extension-apiserver-authentication-reader +subjects: + - kind: ServiceAccount + name: metrics-server + namespace: kube-system +--- +apiVersion: apiregistration.k8s.io/v1beta1 +kind: APIService +metadata: + name: v1beta1.metrics.k8s.io +spec: + service: + name: metrics-server + namespace: kube-system + group: metrics.k8s.io + version: v1beta1 + insecureSkipTLSVerify: true + groupPriorityMinimum: 100 + versionPriority: 100 +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: metrics-server + namespace: kube-system +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: metrics-server + namespace: kube-system + labels: + k8s-app: metrics-server +spec: + selector: + matchLabels: + k8s-app: metrics-server + template: + metadata: + name: metrics-server + labels: + k8s-app: metrics-server + spec: + serviceAccountName: metrics-server + volumes: + # mount in tmp so we can safely use from-scratch images and/or read-only containers + - name: tmp-dir + emptyDir: {} + containers: + - name: metrics-server + image: k8s.gcr.io/metrics-server-amd64:v0.3.1 + args: + - --kubelet-insecure-tls + - --kubelet-preferred-address-types=InternalIP + imagePullPolicy: Always + volumeMounts: + - name: tmp-dir + mountPath: /tmp + +--- +apiVersion: v1 +kind: Service +metadata: + name: metrics-server + namespace: kube-system + labels: + kubernetes.io/name: 'Metrics-server' +spec: + selector: + k8s-app: metrics-server + ports: + - port: 443 + protocol: TCP + targetPort: 443 +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: system:metrics-server +rules: + - apiGroups: + - '' + resources: + - pods + - nodes + - nodes/stats + verbs: + - get + - list + - watch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: system:metrics-server +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: system:metrics-server +subjects: + - kind: ServiceAccount + name: metrics-server + namespace: kube-system diff --git a/plugins/kubernetes-backend/package.json b/plugins/kubernetes-backend/package.json index 4edc7b238a..c2f4eae4ba 100644 --- a/plugins/kubernetes-backend/package.json +++ b/plugins/kubernetes-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-kubernetes-backend", "description": "A Backstage backend plugin that integrates towards Kubernetes", - "version": "0.3.18", + "version": "0.3.20", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -32,13 +32,13 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", - "@backstage/errors": "^0.1.3", - "@backstage/plugin-kubernetes-common": "^0.1.4", + "@backstage/errors": "^0.1.5", + "@backstage/plugin-kubernetes-common": "^0.1.7", "@google-cloud/container": "^2.2.0", - "@kubernetes/client-node": "^0.15.0", + "@kubernetes/client-node": "^0.16.0", "@types/express": "^4.17.6", "aws-sdk": "^2.840.0", "aws4": "^1.11.0", @@ -55,7 +55,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/aws4": "^1.5.1", "supertest": "^6.1.3", "aws-sdk-mock": "^5.2.1", diff --git a/plugins/kubernetes-backend/schema.d.ts b/plugins/kubernetes-backend/schema.d.ts index 8b96d5ceca..7f5183e337 100644 --- a/plugins/kubernetes-backend/schema.d.ts +++ b/plugins/kubernetes-backend/schema.d.ts @@ -23,6 +23,8 @@ export interface Config { | 'deployments' | 'replicasets' | 'horizontalpodautoscalers' + | 'jobs' + | 'cronjobs' | 'ingresses' >; serviceLocatorMethod: { @@ -61,5 +63,23 @@ export interface Config { apiVersion: string; plural: string; }>; + + /** + * (Optional) API Version Overrides + * If set, the specified api version will be used to make requests for the corresponding object. + * If running a legacy Kubernetes version, you may use this to override the default api versions + * that are not supported in your cluster. + */ + apiVersionOverrides?: { + pods?: string; + services?: string; + configmaps?: string; + deployments?: string; + replicasets?: string; + horizontalpodautoscalers?: string; + cronjobs?: string; + jobs?: string; + ingresses?: string; + } & { [pluralKind: string]: string }; }; } diff --git a/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.test.ts b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.test.ts index 62346ac6c3..f5d6b56893 100644 --- a/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.test.ts +++ b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.test.ts @@ -52,6 +52,7 @@ describe('ConfigClusterLocator', () => { serviceAccountToken: undefined, url: 'http://localhost:8080', authProvider: 'serviceAccount', + skipMetricsLookup: false, skipTLSVerify: false, caData: undefined, }, @@ -67,6 +68,7 @@ describe('ConfigClusterLocator', () => { url: 'http://localhost:8080', authProvider: 'serviceAccount', skipTLSVerify: false, + skipMetricsLookup: true, dashboardUrl: 'https://k8s.foo.com', }, { @@ -74,6 +76,7 @@ describe('ConfigClusterLocator', () => { url: 'http://localhost:8081', authProvider: 'google', skipTLSVerify: true, + skipMetricsLookup: false, }, ], }); @@ -90,6 +93,7 @@ describe('ConfigClusterLocator', () => { url: 'http://localhost:8080', authProvider: 'serviceAccount', skipTLSVerify: false, + skipMetricsLookup: true, caData: undefined, }, { @@ -98,6 +102,7 @@ describe('ConfigClusterLocator', () => { url: 'http://localhost:8081', authProvider: 'google', skipTLSVerify: true, + skipMetricsLookup: false, caData: undefined, }, ]); @@ -144,6 +149,7 @@ describe('ConfigClusterLocator', () => { url: 'http://localhost:8080', authProvider: 'aws', skipTLSVerify: false, + skipMetricsLookup: false, caData: undefined, }, { @@ -154,6 +160,7 @@ describe('ConfigClusterLocator', () => { url: 'http://localhost:8081', authProvider: 'aws', skipTLSVerify: true, + skipMetricsLookup: false, caData: undefined, }, { @@ -164,6 +171,7 @@ describe('ConfigClusterLocator', () => { serviceAccountToken: undefined, authProvider: 'aws', skipTLSVerify: true, + skipMetricsLookup: false, caData: undefined, }, ]); diff --git a/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.ts b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.ts index bb9dbfe13f..36b5f58f2c 100644 --- a/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.ts +++ b/plugins/kubernetes-backend/src/cluster-locator/ConfigClusterLocator.ts @@ -35,6 +35,7 @@ export class ConfigClusterLocator implements KubernetesClustersSupplier { url: c.getString('url'), serviceAccountToken: c.getOptionalString('serviceAccountToken'), skipTLSVerify: c.getOptionalBoolean('skipTLSVerify') ?? false, + skipMetricsLookup: c.getOptionalBoolean('skipMetricsLookup') ?? false, caData: c.getOptionalString('caData'), authProvider: authProvider, }; diff --git a/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.test.ts b/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.test.ts index 545f839907..bd342f566b 100644 --- a/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.test.ts +++ b/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.test.ts @@ -93,6 +93,7 @@ describe('GkeClusterLocator', () => { type: 'gke', projectId: 'some-project', region: 'some-region', + skipMetricsLookup: true, }); const sut = GkeClusterLocator.fromConfigWithClient(config, { @@ -107,6 +108,7 @@ describe('GkeClusterLocator', () => { name: 'some-cluster', url: 'https://1.2.3.4', skipTLSVerify: false, + skipMetricsLookup: true, }, ]); expect(mockedListClusters).toBeCalledTimes(1); @@ -143,6 +145,7 @@ describe('GkeClusterLocator', () => { name: 'some-cluster', url: 'https://1.2.3.4', skipTLSVerify: false, + skipMetricsLookup: false, }, ]); expect(mockedListClusters).toBeCalledTimes(1); @@ -184,12 +187,14 @@ describe('GkeClusterLocator', () => { name: 'some-cluster', url: 'https://1.2.3.4', skipTLSVerify: false, + skipMetricsLookup: false, }, { authProvider: 'google', name: 'some-other-cluster', url: 'https://6.7.8.9', skipTLSVerify: false, + skipMetricsLookup: false, }, ]); expect(mockedListClusters).toBeCalledTimes(1); diff --git a/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.ts b/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.ts index 3aa4a3e941..d7f5050399 100644 --- a/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.ts +++ b/plugins/kubernetes-backend/src/cluster-locator/GkeClusterLocator.ts @@ -23,6 +23,7 @@ type GkeClusterLocatorOptions = { projectId: string; region?: string; skipTLSVerify?: boolean; + skipMetricsLookup?: boolean; }; export class GkeClusterLocator implements KubernetesClustersSupplier { @@ -39,6 +40,8 @@ export class GkeClusterLocator implements KubernetesClustersSupplier { projectId: config.getString('projectId'), region: config.getOptionalString('region') ?? '-', skipTLSVerify: config.getOptionalBoolean('skipTLSVerify') ?? false, + skipMetricsLookup: + config.getOptionalBoolean('skipMetricsLookup') ?? false, }; return new GkeClusterLocator(options, client); } @@ -52,7 +55,8 @@ export class GkeClusterLocator implements KubernetesClustersSupplier { // TODO pass caData into the object async getClusters(): Promise { - const { projectId, region, skipTLSVerify } = this.options; + const { projectId, region, skipTLSVerify, skipMetricsLookup } = + this.options; const request = { parent: `projects/${projectId}/locations/${region}`, }; @@ -65,6 +69,7 @@ export class GkeClusterLocator implements KubernetesClustersSupplier { url: `https://${r.endpoint ?? ''}`, authProvider: 'google', skipTLSVerify, + skipMetricsLookup, })); } catch (e) { throw new ForwardedError( diff --git a/plugins/kubernetes-backend/src/cluster-locator/index.test.ts b/plugins/kubernetes-backend/src/cluster-locator/index.test.ts index dde4dc1d93..2bc2c719a0 100644 --- a/plugins/kubernetes-backend/src/cluster-locator/index.test.ts +++ b/plugins/kubernetes-backend/src/cluster-locator/index.test.ts @@ -53,6 +53,7 @@ describe('getCombinedClusterDetails', () => { serviceAccountToken: 'token', url: 'http://localhost:8080', authProvider: 'serviceAccount', + skipMetricsLookup: false, skipTLSVerify: false, caData: undefined, }, @@ -61,6 +62,7 @@ describe('getCombinedClusterDetails', () => { serviceAccountToken: undefined, url: 'http://localhost:8081', authProvider: 'google', + skipMetricsLookup: false, skipTLSVerify: false, caData: undefined, }, diff --git a/plugins/kubernetes-backend/src/service/KubernetesBuilder.test.ts b/plugins/kubernetes-backend/src/service/KubernetesBuilder.test.ts index de0dcdf373..37dad8c3e4 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesBuilder.test.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesBuilder.test.ts @@ -29,6 +29,7 @@ import { } from '../types/types'; import { KubernetesBuilder } from './KubernetesBuilder'; import { KubernetesFanOutHandler } from './KubernetesFanOutHandler'; +import { PodStatus } from '@kubernetes/client-node'; describe('KubernetesBuilder', () => { let app: express.Express; @@ -194,6 +195,7 @@ describe('KubernetesBuilder', () => { name: someCluster.name, }, errors: [], + podMetrics: [], resources: [ { type: 'pods', @@ -211,6 +213,12 @@ describe('KubernetesBuilder', () => { }; const fetcher: KubernetesFetcher = { + fetchPodMetricsByNamespace( + _clusterDetails: ClusterDetails, + _namespace: string, + ): Promise { + return Promise.resolve([]); + }, fetchObjectsForService( _params: ObjectFetchParams, ): Promise { diff --git a/plugins/kubernetes-backend/src/service/KubernetesBuilder.ts b/plugins/kubernetes-backend/src/service/KubernetesBuilder.ts index 11cca4917f..3333f7a0fc 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesBuilder.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesBuilder.ts @@ -243,6 +243,10 @@ export class KubernetesBuilder { 'kubernetes.objectTypes', ) as KubernetesObjectTypes[]; + const apiVersionOverrides = this.env.config.getOptionalConfig( + 'kubernetes.apiVersionOverrides', + ); + let objectTypesToFetch; if (objectTypesToFetchStrings) { @@ -250,6 +254,17 @@ export class KubernetesBuilder { objectTypesToFetchStrings.includes(obj.objectType), ); } + + if (apiVersionOverrides) { + objectTypesToFetch = objectTypesToFetch ?? DEFAULT_OBJECTS; + + for (const obj of objectTypesToFetch) { + if (apiVersionOverrides.has(obj.objectType)) { + obj.apiVersion = apiVersionOverrides.getString(obj.objectType); + } + } + } + return objectTypesToFetch; } } diff --git a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.test.ts b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.test.ts index 96bd1fe7c1..e813a63f0d 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.test.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.test.ts @@ -47,14 +47,14 @@ describe('KubernetesClientProvider', () => { expect(mockGetKubeConfig.mock.calls.length).toBe(1); }); - it('can get apps client by cluster details', async () => { + it('can get custom objects client by cluster details', async () => { const sut = new KubernetesClientProvider(); const mockGetKubeConfig = jest.fn(sut.getKubeConfig.bind({})); sut.getKubeConfig = mockGetKubeConfig; - const result = sut.getAppsClientByClusterDetails({ + const result = sut.getCustomObjectsClient({ name: 'cluster-name', url: 'http://localhost:9999', serviceAccountToken: 'TOKEN', diff --git a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts index 4b2848508e..031e40547c 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts @@ -15,11 +15,9 @@ */ import { - AppsV1Api, - AutoscalingV1Api, CoreV1Api, KubeConfig, - NetworkingV1beta1Api, + Metrics, CustomObjectsApi, } from '@kubernetes/client-node'; import { ClusterDetails } from '../types/types'; @@ -62,22 +60,10 @@ export class KubernetesClientProvider { return kc.makeApiClient(CoreV1Api); } - getAppsClientByClusterDetails(clusterDetails: ClusterDetails) { + getMetricsClient(clusterDetails: ClusterDetails) { const kc = this.getKubeConfig(clusterDetails); - return kc.makeApiClient(AppsV1Api); - } - - getAutoscalingClientByClusterDetails(clusterDetails: ClusterDetails) { - const kc = this.getKubeConfig(clusterDetails); - - return kc.makeApiClient(AutoscalingV1Api); - } - - getNetworkingBeta1Client(clusterDetails: ClusterDetails) { - const kc = this.getKubeConfig(clusterDetails); - - return kc.makeApiClient(NetworkingV1beta1Api); + return new Metrics(kc); } getCustomObjectsClient(clusterDetails: ClusterDetails) { diff --git a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts index 7973448467..da8f703ba0 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts @@ -15,13 +15,30 @@ */ import { getVoidLogger } from '@backstage/backend-common'; -import { ObjectFetchParams } from '../types/types'; +import { ClusterDetails, ObjectFetchParams } from '../types/types'; import { KubernetesFanOutHandler } from './KubernetesFanOutHandler'; +import { PodStatus } from '@kubernetes/client-node/dist/top'; const fetchObjectsForService = jest.fn(); +const fetchPodMetricsByNamespace = jest.fn(); const getClustersByServiceId = jest.fn(); +const POD_METRICS_FIXTURE = { + containers: [], + cpu: { + currentUsage: 100, + limitTotal: 102, + requestTotal: 101, + }, + memory: { + currentUsage: '1000', + limitTotal: '1002', + requestTotal: '1001', + }, + pod: {}, +}; + const mockFetch = (mock: jest.Mock) => { mock.mockImplementation((params: ObjectFetchParams) => Promise.resolve( @@ -33,6 +50,34 @@ const mockFetch = (mock: jest.Mock) => { ); }; +const mockMetrics = (mock: jest.Mock) => { + mock.mockImplementation((clusterDetails: ClusterDetails, namespace: string) => + Promise.resolve(generatePodStatus(clusterDetails.name, namespace)), + ); +}; + +function generatePodStatus( + _clusterName: string, + _namespace: string, +): PodStatus[] { + return [ + { + Pod: {}, + CPU: { + CurrentUsage: 100, + RequestTotal: 101, + LimitTotal: 102, + }, + Memory: { + CurrentUsage: BigInt('1000'), + RequestTotal: BigInt('1001'), + LimitTotal: BigInt('1002'), + }, + Containers: [], + }, + ] as any; +} + function generateMockResourcesAndErrors( serviceId: string, clusterName: string, @@ -84,6 +129,7 @@ function generateMockResourcesAndErrors( { metadata: { name: `my-pods-${serviceId}-${clusterName}`, + namespace: `ns-${serviceId}-${clusterName}`, }, }, ], @@ -94,6 +140,7 @@ function generateMockResourcesAndErrors( { metadata: { name: `my-configmaps-${serviceId}-${clusterName}`, + namespace: `ns-${serviceId}-${clusterName}`, }, }, ], @@ -104,6 +151,7 @@ function generateMockResourcesAndErrors( { metadata: { name: `my-services-${serviceId}-${clusterName}`, + namespace: `ns-${serviceId}-${clusterName}`, }, }, ], @@ -128,11 +176,13 @@ describe('handleGetKubernetesObjectsForService', () => { ); mockFetch(fetchObjectsForService); + mockMetrics(fetchPodMetricsByNamespace); const sut = new KubernetesFanOutHandler({ logger: getVoidLogger(), fetcher: { fetchObjectsForService, + fetchPodMetricsByNamespace, }, serviceLocator: { getClustersByServiceId, @@ -161,6 +211,11 @@ describe('handleGetKubernetesObjectsForService', () => { expect(getClustersByServiceId.mock.calls.length).toBe(1); expect(fetchObjectsForService.mock.calls.length).toBe(1); + expect(fetchPodMetricsByNamespace.mock.calls.length).toBe(1); + expect(fetchPodMetricsByNamespace.mock.calls[0][1]).toBe( + 'ns-test-component-test-cluster', + ); + expect(result).toStrictEqual({ items: [ { @@ -168,12 +223,14 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'test-cluster', }, errors: [], + podMetrics: [POD_METRICS_FIXTURE], resources: [ { resources: [ { metadata: { name: 'my-pods-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -184,6 +241,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-configmaps-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -194,6 +252,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-services-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -205,6 +264,124 @@ describe('handleGetKubernetesObjectsForService', () => { }); }); + it('dont call top for the same namespace twice', async () => { + getClustersByServiceId.mockImplementation(() => + Promise.resolve([ + { + name: 'test-cluster', + authProvider: 'serviceAccount', + }, + ]), + ); + + fetchObjectsForService.mockImplementation((_: ObjectFetchParams) => + Promise.resolve({ + errors: [], + responses: [ + { + type: 'pods', + resources: [ + { + metadata: { + name: `pod1`, + namespace: `ns-a`, + }, + }, + { + metadata: { + name: `pod2`, + namespace: `ns-a`, + }, + }, + { + metadata: { + name: `pod3`, + namespace: `ns-b`, + }, + }, + ], + }, + ], + }), + ); + + mockMetrics(fetchPodMetricsByNamespace); + + const sut = new KubernetesFanOutHandler({ + logger: getVoidLogger(), + fetcher: { + fetchObjectsForService, + fetchPodMetricsByNamespace, + }, + serviceLocator: { + getClustersByServiceId, + }, + customResources: [], + }); + + const result = await sut.getKubernetesObjectsByEntity({ + entity: { + apiVersion: 'backstage.io/v1beta1', + kind: 'Component', + metadata: { + name: 'test-component', + annotations: { + 'backstage.io/kubernetes-labels-selector': + 'backstage.io/test-label=test-component', + }, + }, + spec: { + type: 'service', + lifecycle: 'production', + owner: 'joe', + }, + }, + }); + + expect(getClustersByServiceId.mock.calls.length).toBe(1); + expect(fetchObjectsForService.mock.calls.length).toBe(1); + expect(fetchPodMetricsByNamespace.mock.calls.length).toBe(2); + expect(fetchPodMetricsByNamespace.mock.calls[0][1]).toBe('ns-a'); + expect(fetchPodMetricsByNamespace.mock.calls[1][1]).toBe('ns-b'); + + expect(result).toStrictEqual({ + items: [ + { + cluster: { + name: 'test-cluster', + }, + errors: [], + podMetrics: [POD_METRICS_FIXTURE, POD_METRICS_FIXTURE], + resources: [ + { + resources: [ + { + metadata: { + name: 'pod1', + namespace: 'ns-a', + }, + }, + { + metadata: { + name: 'pod2', + namespace: 'ns-a', + }, + }, + { + metadata: { + name: 'pod3', + namespace: 'ns-b', + }, + }, + ], + type: 'pods', + }, + ], + }, + ], + }); + }); + it('retrieve objects for two clusters', async () => { getClustersByServiceId.mockImplementation(() => Promise.resolve([ @@ -221,11 +398,13 @@ describe('handleGetKubernetesObjectsForService', () => { ); mockFetch(fetchObjectsForService); + mockMetrics(fetchPodMetricsByNamespace); const sut = new KubernetesFanOutHandler({ logger: getVoidLogger(), fetcher: { fetchObjectsForService, + fetchPodMetricsByNamespace, }, serviceLocator: { getClustersByServiceId, @@ -265,12 +444,14 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'test-cluster', }, errors: [], + podMetrics: [POD_METRICS_FIXTURE], resources: [ { resources: [ { metadata: { name: 'my-pods-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -281,6 +462,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-configmaps-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -291,6 +473,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-services-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -303,12 +486,14 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'other-cluster', }, errors: [], + podMetrics: [POD_METRICS_FIXTURE], resources: [ { resources: [ { metadata: { name: 'my-pods-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -319,6 +504,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-configmaps-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -329,6 +515,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-services-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -358,11 +545,13 @@ describe('handleGetKubernetesObjectsForService', () => { ); mockFetch(fetchObjectsForService); + mockMetrics(fetchPodMetricsByNamespace); const sut = new KubernetesFanOutHandler({ logger: getVoidLogger(), fetcher: { fetchObjectsForService, + fetchPodMetricsByNamespace, }, serviceLocator: { getClustersByServiceId, @@ -401,12 +590,14 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'test-cluster', }, errors: [], + podMetrics: [POD_METRICS_FIXTURE], resources: [ { resources: [ { metadata: { name: 'my-pods-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -417,6 +608,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-configmaps-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -427,6 +619,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-services-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -439,12 +632,14 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'other-cluster', }, errors: [], + podMetrics: [POD_METRICS_FIXTURE], resources: [ { resources: [ { metadata: { name: 'my-pods-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -455,6 +650,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-configmaps-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -465,6 +661,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-services-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -498,11 +695,13 @@ describe('handleGetKubernetesObjectsForService', () => { ); mockFetch(fetchObjectsForService); + mockMetrics(fetchPodMetricsByNamespace); const sut = new KubernetesFanOutHandler({ logger: getVoidLogger(), fetcher: { fetchObjectsForService, + fetchPodMetricsByNamespace, }, serviceLocator: { getClustersByServiceId, @@ -541,12 +740,14 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'test-cluster', }, errors: [], + podMetrics: [POD_METRICS_FIXTURE], resources: [ { resources: [ { metadata: { name: 'my-pods-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -557,6 +758,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-configmaps-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -567,6 +769,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-services-test-component-test-cluster', + namespace: 'ns-test-component-test-cluster', }, }, ], @@ -579,12 +782,14 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'other-cluster', }, errors: [], + podMetrics: [POD_METRICS_FIXTURE], resources: [ { resources: [ { metadata: { name: 'my-pods-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -595,6 +800,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-configmaps-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -605,6 +811,7 @@ describe('handleGetKubernetesObjectsForService', () => { { metadata: { name: 'my-services-test-component-other-cluster', + namespace: 'ns-test-component-other-cluster', }, }, ], @@ -617,6 +824,7 @@ describe('handleGetKubernetesObjectsForService', () => { name: 'error-cluster', }, errors: ['some random cluster error'], + podMetrics: [], resources: [ { type: 'pods', diff --git a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts index 1f856e90a9..a25c220b80 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.ts @@ -27,9 +27,19 @@ import { import { KubernetesAuthTranslator } from '../kubernetes-auth-translator/types'; import { KubernetesAuthTranslatorGenerator } from '../kubernetes-auth-translator/KubernetesAuthTranslatorGenerator'; import { + ClientContainerStatus, + ClientCurrentResourceUsage, + ClientPodStatus, ClusterObjects, + FetchResponse, ObjectsByEntityResponse, + PodFetchResponse, } from '@backstage/plugin-kubernetes-common'; +import { + ContainerStatus, + CurrentResourceUsage, + PodStatus, +} from '@kubernetes/client-node'; export const DEFAULT_OBJECTS: ObjectToFetch[] = [ { @@ -68,6 +78,18 @@ export const DEFAULT_OBJECTS: ObjectToFetch[] = [ plural: 'horizontalpodautoscalers', objectType: 'horizontalpodautoscalers', }, + { + group: 'batch', + apiVersion: 'v1', + plural: 'jobs', + objectType: 'jobs', + }, + { + group: 'batch', + apiVersion: 'v1', + plural: 'cronjobs', + objectType: 'cronjobs', + }, { group: 'networking.k8s.io', apiVersion: 'v1', @@ -81,6 +103,50 @@ export interface KubernetesFanOutHandlerOptions export interface KubernetesRequestBody extends ObjectsByEntityRequest {} +const isPodFetchResponse = (fr: FetchResponse): fr is PodFetchResponse => + fr.type === 'pods'; +const isString = (str: string | undefined): str is string => str !== undefined; + +const numberOrBigIntToNumberOrString = ( + value: number | BigInt, +): number | string => { + // @ts-ignore + return typeof value === 'bigint' ? value.toString() : value; +}; + +const toClientSafeResource = ( + current: CurrentResourceUsage, +): ClientCurrentResourceUsage => { + return { + currentUsage: numberOrBigIntToNumberOrString(current.CurrentUsage), + requestTotal: numberOrBigIntToNumberOrString(current.RequestTotal), + limitTotal: numberOrBigIntToNumberOrString(current.LimitTotal), + }; +}; + +const toClientSafeContainer = ( + container: ContainerStatus, +): ClientContainerStatus => { + return { + container: container.Container, + cpuUsage: toClientSafeResource(container.CPUUsage), + memoryUsage: toClientSafeResource(container.MemoryUsage), + }; +}; + +const toClientSafePodMetrics = ( + podMetrics: PodStatus[][], +): ClientPodStatus[] => { + return podMetrics.flat().map((pd: PodStatus): ClientPodStatus => { + return { + pod: pd.Pod, + memory: toClientSafeResource(pd.Memory), + cpu: toClientSafeResource(pd.CPU), + containers: pd.Containers.map(toClientSafeContainer), + }; + }); +}; + export class KubernetesFanOutHandler { private readonly logger: Logger; private readonly fetcher: KubernetesFetcher; @@ -150,10 +216,36 @@ export class KubernetesFanOutHandler { customResources: this.customResources, }) .then(result => { + if (clusterDetailsItem.skipMetricsLookup) { + return Promise.all([ + Promise.resolve(result), + Promise.resolve([]), + ]); + } + // TODO refactor, extract as method + const namespaces: Set = new Set( + result.responses + .filter(isPodFetchResponse) + .flatMap(r => r.resources) + .map(p => p.metadata?.namespace) + .filter(isString), + ); + + const podMetrics = Array.from(namespaces).map(ns => + this.fetcher.fetchPodMetricsByNamespace(clusterDetailsItem, ns), + ); + + return Promise.all([ + Promise.resolve(result), + Promise.all(podMetrics), + ]); + }) + .then(([result, metrics]) => { const objects: ClusterObjects = { cluster: { name: clusterDetailsItem.name, }, + podMetrics: toClientSafePodMetrics(metrics), resources: result.responses, errors: result.errors, }; diff --git a/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts b/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts index e86901ef92..e1f701b75c 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts @@ -106,6 +106,7 @@ describe('KubernetesFetcher', () => { 'v1', 'pods', '', + false, '', '', 'backstage.io/kubernetes-id=some-service', @@ -116,6 +117,7 @@ describe('KubernetesFetcher', () => { 'v1', 'services', '', + false, '', '', 'backstage.io/kubernetes-id=some-service', @@ -197,6 +199,7 @@ describe('KubernetesFetcher', () => { 'v1', 'pods', '', + false, '', '', 'backstage.io/kubernetes-id=some-service', @@ -207,6 +210,7 @@ describe('KubernetesFetcher', () => { 'v1', 'services', '', + false, '', '', 'backstage.io/kubernetes-id=some-service', @@ -316,6 +320,7 @@ describe('KubernetesFetcher', () => { 'v1', 'pods', '', + false, '', '', 'backstage.io/kubernetes-id=some-service', @@ -326,6 +331,7 @@ describe('KubernetesFetcher', () => { 'v1', 'services', '', + false, '', '', 'backstage.io/kubernetes-id=some-service', @@ -336,6 +342,7 @@ describe('KubernetesFetcher', () => { 'v2', 'things', '', + false, '', '', 'backstage.io/kubernetes-id=some-service', diff --git a/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts index 308b7a10be..a2c3b9a6a8 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts @@ -14,12 +14,7 @@ * limitations under the License. */ -import { - AppsV1Api, - AutoscalingV1Api, - CoreV1Api, - NetworkingV1beta1Api, -} from '@kubernetes/client-node'; +import { CoreV1Api, topPods } from '@kubernetes/client-node'; import lodash, { Dictionary } from 'lodash'; import { Logger } from 'winston'; import { @@ -36,12 +31,10 @@ import { KubernetesErrorTypes, } from '@backstage/plugin-kubernetes-common'; import { KubernetesClientProvider } from './KubernetesClientProvider'; +import { PodStatus } from '@kubernetes/client-node/dist/top'; export interface Clients { core: CoreV1Api; - apps: AppsV1Api; - autoscaling: AutoscalingV1Api; - networkingBeta1: NetworkingV1beta1Api; } export interface KubernetesClientBasedFetcherOptions { @@ -110,10 +103,26 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { return Promise.all(fetchResults).then(fetchResultsToResponseWrapper); } + fetchPodMetricsByNamespace( + clusterDetails: ClusterDetails, + namespace: string, + ): Promise { + const metricsClient = + this.kubernetesClientProvider.getMetricsClient(clusterDetails); + const coreApi = + this.kubernetesClientProvider.getCoreClientByClusterDetails( + clusterDetails, + ); + + return topPods(coreApi, metricsClient, namespace); + } + private captureKubernetesErrorsRethrowOthers(e: any): KubernetesFetchError { if (e.response && e.response.statusCode) { - this.logger.info( - `statusCode=${e.response.statusCode} for resource ${e.response.request.uri.pathname}`, + this.logger.warn( + `statusCode=${e.response.statusCode} for resource ${ + e.response.request.uri.pathname + } body=[${JSON.stringify(e.response.body)}]`, ); return { errorType: statusCodeToErrorType(e.response.statusCode), @@ -143,6 +152,7 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { resource.apiVersion, resource.plural, '', + false, '', '', labelSelector, diff --git a/plugins/kubernetes-backend/src/types/types.ts b/plugins/kubernetes-backend/src/types/types.ts index 90485fcaee..a0ec0832c1 100644 --- a/plugins/kubernetes-backend/src/types/types.ts +++ b/plugins/kubernetes-backend/src/types/types.ts @@ -21,6 +21,7 @@ import type { KubernetesRequestBody, ObjectsByEntityResponse, } from '@backstage/plugin-kubernetes-common'; +import { PodStatus } from '@kubernetes/client-node/dist/top'; export interface ObjectFetchParams { serviceId: string; @@ -40,6 +41,10 @@ export interface KubernetesFetcher { fetchObjectsForService( params: ObjectFetchParams, ): Promise; + fetchPodMetricsByNamespace( + clusterDetails: ClusterDetails, + namespace: string, + ): Promise; } export interface FetchResponseWrapper { @@ -67,6 +72,8 @@ export type KubernetesObjectTypes = | 'deployments' | 'replicasets' | 'horizontalpodautoscalers' + | 'jobs' + | 'cronjobs' | 'ingresses' | 'customresources'; @@ -91,6 +98,11 @@ export interface ClusterDetails { authProvider: string; serviceAccountToken?: string | undefined; skipTLSVerify?: boolean; + /** + * Whether to skip the lookup to the metrics server to retrieve pod resource usage. + * It is not guaranteed that the Kubernetes distro has the metrics server installed. + */ + skipMetricsLookup?: boolean; caData?: string | undefined; /** * Specifies the link to the Kubernetes dashboard managing this cluster. diff --git a/plugins/kubernetes-common/CHANGELOG.md b/plugins/kubernetes-common/CHANGELOG.md index 0f685bd4d4..db18c64482 100644 --- a/plugins/kubernetes-common/CHANGELOG.md +++ b/plugins/kubernetes-common/CHANGELOG.md @@ -1,5 +1,17 @@ # @backstage/plugin-kubernetes-common +## 0.1.7 + +### Patch Changes + +- 59677fadb1: Improvements to API Reference documentation + +## 0.1.6 + +### Patch Changes + +- 37dc844728: Include CronJobs and Jobs as default objects returned by the kubernetes backend and add/update relevant types. + ## 0.1.5 ### Patch Changes diff --git a/plugins/kubernetes-common/api-report.md b/plugins/kubernetes-common/api-report.md index 9f9669275f..f3500aa271 100644 --- a/plugins/kubernetes-common/api-report.md +++ b/plugins/kubernetes-common/api-report.md @@ -4,10 +4,12 @@ ```ts import { Entity } from '@backstage/catalog-model'; -import { ExtensionsV1beta1Ingress } from '@kubernetes/client-node'; import { V1ConfigMap } from '@kubernetes/client-node'; +import { V1CronJob } from '@kubernetes/client-node'; import { V1Deployment } from '@kubernetes/client-node'; import { V1HorizontalPodAutoscaler } from '@kubernetes/client-node'; +import { V1Ingress } from '@kubernetes/client-node'; +import { V1Job } from '@kubernetes/client-node'; import { V1Pod } from '@kubernetes/client-node'; import { V1ReplicaSet } from '@kubernetes/client-node'; import { V1Service } from '@kubernetes/client-node'; @@ -17,6 +19,44 @@ import { V1Service } from '@kubernetes/client-node'; // @public (undocumented) export type AuthProviderType = 'google' | 'serviceAccount' | 'aws'; +// Warning: (ae-missing-release-tag) "ClientContainerStatus" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface ClientContainerStatus { + // (undocumented) + container: string; + // (undocumented) + cpuUsage: ClientCurrentResourceUsage; + // (undocumented) + memoryUsage: ClientCurrentResourceUsage; +} + +// Warning: (ae-missing-release-tag) "ClientCurrentResourceUsage" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface ClientCurrentResourceUsage { + // (undocumented) + currentUsage: number | string; + // (undocumented) + limitTotal: number | string; + // (undocumented) + requestTotal: number | string; +} + +// Warning: (ae-missing-release-tag) "ClientPodStatus" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface ClientPodStatus { + // (undocumented) + containers: ClientContainerStatus[]; + // (undocumented) + cpu: ClientCurrentResourceUsage; + // (undocumented) + memory: ClientCurrentResourceUsage; + // (undocumented) + pod: V1Pod; +} + // Warning: (ae-missing-release-tag) "ClusterAttributes" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -35,6 +75,8 @@ export interface ClusterObjects { // (undocumented) errors: KubernetesFetchError[]; // (undocumented) + podMetrics: ClientPodStatus[]; + // (undocumented) resources: FetchResponse[]; } @@ -48,6 +90,16 @@ export interface ConfigMapFetchResponse { type: 'configmaps'; } +// Warning: (ae-missing-release-tag) "CronJobsFetchResponse" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface CronJobsFetchResponse { + // (undocumented) + resources: Array; + // (undocumented) + type: 'cronjobs'; +} + // Warning: (ae-missing-release-tag) "CustomResourceFetchResponse" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -78,6 +130,8 @@ export type FetchResponse = | DeploymentFetchResponse | ReplicaSetsFetchResponse | HorizontalPodAutoscalersFetchResponse + | JobsFetchResponse + | CronJobsFetchResponse | IngressesFetchResponse | CustomResourceFetchResponse; @@ -96,11 +150,21 @@ export interface HorizontalPodAutoscalersFetchResponse { // @public (undocumented) export interface IngressesFetchResponse { // (undocumented) - resources: Array; + resources: Array; // (undocumented) type: 'ingresses'; } +// Warning: (ae-missing-release-tag) "JobsFetchResponse" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface JobsFetchResponse { + // (undocumented) + resources: Array; + // (undocumented) + type: 'jobs'; +} + // Warning: (ae-missing-release-tag) "KubernetesErrorTypes" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) diff --git a/plugins/kubernetes-common/package.json b/plugins/kubernetes-common/package.json index 3c9cb5e357..b3de378021 100644 --- a/plugins/kubernetes-common/package.json +++ b/plugins/kubernetes-common/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-kubernetes-common", "description": "Common functionalities for kubernetes, to be shared between kubernetes and kubernetes-backend plugin", - "version": "0.1.5", + "version": "0.1.7", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -36,10 +36,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@kubernetes/client-node": "^0.15.0" + "@kubernetes/client-node": "^0.16.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" }, "jest": { "roots": [ diff --git a/plugins/kubernetes-common/src/index.ts b/plugins/kubernetes-common/src/index.ts index af146ae9fa..6b97c0eb7d 100644 --- a/plugins/kubernetes-common/src/index.ts +++ b/plugins/kubernetes-common/src/index.ts @@ -15,7 +15,7 @@ */ /** - * Common functionalities for kubernetes, to be shared between kubernetes and kubernetes-backend plugin + * Common functionalities for Kubernetes, to be shared between the `kubernetes` and `kubernetes-backend` plugins * * @packageDocumentation */ diff --git a/plugins/kubernetes-common/src/types.ts b/plugins/kubernetes-common/src/types.ts index add661a5f8..0c5af00a97 100644 --- a/plugins/kubernetes-common/src/types.ts +++ b/plugins/kubernetes-common/src/types.ts @@ -15,10 +15,12 @@ */ import { - ExtensionsV1beta1Ingress, V1ConfigMap, + V1CronJob, V1Deployment, V1HorizontalPodAutoscaler, + V1Ingress, + V1Job, V1Pod, V1ReplicaSet, V1Service, @@ -67,6 +69,7 @@ export interface ClusterAttributes { export interface ClusterObjects { cluster: ClusterAttributes; resources: FetchResponse[]; + podMetrics: ClientPodStatus[]; errors: KubernetesFetchError[]; } @@ -83,6 +86,8 @@ export type FetchResponse = | DeploymentFetchResponse | ReplicaSetsFetchResponse | HorizontalPodAutoscalersFetchResponse + | JobsFetchResponse + | CronJobsFetchResponse | IngressesFetchResponse | CustomResourceFetchResponse; @@ -116,9 +121,19 @@ export interface HorizontalPodAutoscalersFetchResponse { resources: Array; } +export interface JobsFetchResponse { + type: 'jobs'; + resources: Array; +} + +export interface CronJobsFetchResponse { + type: 'cronjobs'; + resources: Array; +} + export interface IngressesFetchResponse { type: 'ingresses'; - resources: Array; + resources: Array; } export interface CustomResourceFetchResponse { @@ -137,3 +152,22 @@ export type KubernetesErrorTypes = | 'UNAUTHORIZED_ERROR' | 'SYSTEM_ERROR' | 'UNKNOWN_ERROR'; + +export interface ClientCurrentResourceUsage { + currentUsage: number | string; + requestTotal: number | string; + limitTotal: number | string; +} + +export interface ClientContainerStatus { + container: string; + cpuUsage: ClientCurrentResourceUsage; + memoryUsage: ClientCurrentResourceUsage; +} + +export interface ClientPodStatus { + pod: V1Pod; + cpu: ClientCurrentResourceUsage; + memory: ClientCurrentResourceUsage; + containers: ClientContainerStatus[]; +} diff --git a/plugins/kubernetes/CHANGELOG.md b/plugins/kubernetes/CHANGELOG.md index 0ae3a6c012..819709599f 100644 --- a/plugins/kubernetes/CHANGELOG.md +++ b/plugins/kubernetes/CHANGELOG.md @@ -1,5 +1,26 @@ # @backstage/plugin-kubernetes +## 0.4.22 + +### Patch Changes + +- 86ed770308: Added accordions to display information on Jobs and CronJobs in the kubernetes plugin. Updated the PodsTable with fewer default columns and the ability to pass in additional ones depending on the use case. +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + - @backstage/plugin-kubernetes-common@0.1.7 + +## 0.4.21 + +### Patch Changes + +- 3739d3f773: Implement support for formatting OpenShift dashboard url links +- Updated dependencies + - @backstage/plugin-kubernetes-common@0.1.6 + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.4.20 ### Patch Changes diff --git a/plugins/kubernetes/dev/index.tsx b/plugins/kubernetes/dev/index.tsx index 12de5f098f..068f26b7f5 100644 --- a/plugins/kubernetes/dev/index.tsx +++ b/plugins/kubernetes/dev/index.tsx @@ -29,6 +29,8 @@ import { } from '@backstage/plugin-kubernetes-common'; import fixture1 from '../src/__fixtures__/1-deployments.json'; import fixture2 from '../src/__fixtures__/2-deployments.json'; +import fixture3 from '../src/__fixtures__/1-cronjobs.json'; +import fixture4 from '../src/__fixtures__/2-cronjobs.json'; import { TestApiProvider } from '@backstage/test-utils'; const mockEntity: Entity = { @@ -64,6 +66,7 @@ class MockKubernetesClient implements KubernetesApi { { cluster: { name: 'mock-cluster' }, resources: this.resources, + podMetrics: [], errors: [], }, ], @@ -102,5 +105,31 @@ createDevApp() ), }) + .addPage({ + path: '/fixture-3', + title: 'Fixture 3', + element: ( + + + + + + ), + }) + .addPage({ + path: '/fixture-4', + title: 'Fixture 4', + element: ( + + + + + + ), + }) .registerPlugin(kubernetesPlugin) .render(); diff --git a/plugins/kubernetes/package.json b/plugins/kubernetes/package.json index 618f814c21..5e7a5bdf8d 100644 --- a/plugins/kubernetes/package.json +++ b/plugins/kubernetes/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-kubernetes", "description": "A Backstage plugin that integrates towards Kubernetes", - "version": "0.4.20", + "version": "0.4.22", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -33,15 +33,16 @@ "dependencies": { "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/plugin-kubernetes-common": "^0.1.5", - "@backstage/theme": "^0.2.13", - "@kubernetes/client-node": "^0.15.0", + "@backstage/plugin-kubernetes-common": "^0.1.7", + "@kubernetes/client-node": "^0.16.0", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", + "cronstrue": "^1.122.0", "js-yaml": "^4.0.0", "lodash": "^4.17.21", "luxon": "^2.0.2", @@ -51,10 +52,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/kubernetes/src/__fixtures__/1-cronjobs.json b/plugins/kubernetes/src/__fixtures__/1-cronjobs.json new file mode 100644 index 0000000000..1edc43710d --- /dev/null +++ b/plugins/kubernetes/src/__fixtures__/1-cronjobs.json @@ -0,0 +1,446 @@ +{ + "cronJobs": [ + { + "metadata": { + "name": "dice-roller-cronjob", + "namespace": "default", + "uid": "9ea073bc-7a4b-4b99-8321-0305bce85568", + "resourceVersion": "1362732552", + "creationTimestamp": "2021-07-16T22:39:58Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "annotations": {} + }, + "spec": { + "schedule": "30 5 * * *", + "startingDeadlineSeconds": 1800, + "concurrencyPolicy": "Forbid", + "suspend": false, + "jobTemplate": { + "metadata": { "creationTimestamp": null }, + "spec": { + "backoffLimit": 2, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "annotations": {} + }, + "spec": { + "containers": [ + { + "name": "busybox", + "image": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "imagePullPolicy": "IfNotPresent", + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"] + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "securityContext": {}, + "schedulerName": "default-scheduler" + } + } + } + }, + "successfulJobsHistoryLimit": 2, + "failedJobsHistoryLimit": 2 + }, + "status": { + "active": [ + { + "kind": "Job", + "namespace": "default", + "name": "dice-roller-cronjob-1637028600", + "uid": "32be1b89-5b53-45b2-aa84-277e75214f61", + "apiVersion": "batch/v1", + "resourceVersion": "1361174163" + } + ], + "lastScheduleTime": "2021-11-16T02:10:00Z" + } + } + ], + "jobs": [ + { + "metadata": { + "name": "dice-roller-cronjob-1637025000", + "namespace": "default", + "uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "resourceVersion": "1361029181", + "creationTimestamp": "2021-11-16T01:10:24Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "ownerReferences": [ + { + "apiVersion": "batch/v1", + "kind": "CronJob", + "name": "dice-roller-cronjob", + "uid": "9ea073bc-7a4b-4b99-8321-0305bce85568", + "controller": true, + "blockOwnerDeletion": true + } + ] + }, + "spec": { + "parallelism": 1, + "completions": 1, + "backoffLimit": 2, + "selector": { + "matchLabels": { + "controller-uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a" + } + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "backstage.io/kubernetes-id": "dice-roller", + "controller-uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "job-name": "dice-roller-cronjob-1637025000" + }, + "annotations": {} + }, + "spec": { + "containers": [ + { + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"], + "image": "busybox", + "imagePullPolicy": "IfNotPresent", + "name": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "securityContext": {}, + "schedulerName": "default-scheduler" + } + } + }, + "status": { + "conditions": [ + { + "type": "Complete", + "status": "True", + "lastProbeTime": "2021-11-16T01:11:31Z", + "lastTransitionTime": "2021-11-16T01:11:31Z" + } + ], + "startTime": "2021-11-16T01:10:24Z", + "completionTime": "2021-11-16T01:11:31Z", + "succeeded": 1 + } + }, + { + "metadata": { + "name": "dice-roller-cronjob-1637028600", + "namespace": "default", + "uid": "32be1b89-5b53-45b2-aa84-277e75214f61", + "resourceVersion": "1361174166", + "creationTimestamp": "2021-11-16T02:10:22Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "ownerReferences": [ + { + "apiVersion": "batch/v1", + "kind": "CronJob", + "name": "dice-roller-cronjob", + "uid": "9ea073bc-7a4b-4b99-8321-0305bce85568", + "controller": true, + "blockOwnerDeletion": true + } + ] + }, + "spec": { + "parallelism": 1, + "completions": 1, + "backoffLimit": 2, + "selector": { + "matchLabels": { + "controller-uid": "32be1b89-5b53-45b2-aa84-277e75214f61" + } + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "backstage.io/kubernetes-id": "dice-roller", + "controller-uid": "32be1b89-5b53-45b2-aa84-277e75214f61", + "job-name": "dice-roller-cronjob-1637028600" + }, + "annotations": {} + }, + "spec": { + "containers": [ + { + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"], + "image": "busybox", + "imagePullPolicy": "IfNotPresent", + "name": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "securityContext": {}, + "schedulerName": "default-scheduler" + } + } + }, + "status": { "startTime": "2021-11-16T02:10:22Z", "active": 1 } + } + ], + "pods": [ + { + "metadata": { + "name": "dice-roller-cronjob-1637025000-gstc4", + "generateName": "dice-roller-cronjob-1637025000-", + "namespace": "default", + "uid": "3b0f2b65-5ae2-441a-beda-bdc92bcafaf0", + "resourceVersion": "1361029179", + "creationTimestamp": "2021-11-16T01:10:24Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller", + "controller-uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "job-name": "dice-roller-cronjob-1637025000" + }, + "annotations": {}, + "ownerReferences": [ + { + "apiVersion": "batch/v1", + "kind": "Job", + "name": "dice-roller-cronjob-1637025000", + "uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "controller": true, + "blockOwnerDeletion": true + } + ] + }, + "spec": { + "volumes": [], + "containers": [ + { + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"], + "image": "busybox", + "imagePullPolicy": "IfNotPresent", + "name": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "serviceAccountName": "default", + "serviceAccount": "default", + "nodeName": "minikube", + "securityContext": {}, + "schedulerName": "default-scheduler", + "tolerations": [ + { + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + }, + { + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + } + ], + "priority": 0, + "enableServiceLinks": true + }, + "status": { + "phase": "Succeeded", + "conditions": [ + { + "type": "Initialized", + "status": "True", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T01:10:27Z", + "reason": "PodCompleted" + }, + { + "type": "Ready", + "status": "False", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T01:11:31Z", + "reason": "PodCompleted" + }, + { + "type": "ContainersReady", + "status": "False", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T01:11:31Z", + "reason": "PodCompleted" + }, + { + "type": "PodScheduled", + "status": "True", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T01:10:24Z" + } + ], + "hostIP": "192.168.49.2", + "podIP": "172.17.0.25", + "podIPs": [{ "ip": "172.17.0.25" }], + "startTime": "2021-11-16T01:10:24Z", + "containerStatuses": [ + { + "name": "busybox", + "state": { + "terminated": { + "exitCode": 0, + "reason": "Completed", + "startedAt": "2021-11-16T01:10:31Z", + "finishedAt": "2021-11-16T01:11:30Z", + "containerID": "docker://1062343e1bb3625e36717bc15617c1bbca976366c3c9dd87035c71f33d015615" + } + }, + "lastState": {}, + "ready": false, + "restartCount": 0, + "image": "busybox:latest/node", + "imageID": "docker-pullable://busybox@sha256:e7157b6d7ebbe2cce5eaa8cfe8aa4fa82d173999b9f90a9ec42e57323546c353", + "containerID": "docker://1062343e1bb3625e36717bc15617c1bbca976366c3c9dd87035c71f33d015615", + "started": false + } + ], + "qosClass": "Burstable" + } + }, + { + "metadata": { + "name": "dice-roller-cronjob-1637028600-p4mlc", + "generateName": "dice-roller-cronjob-1637028600-", + "namespace": "default", + "uid": "acddd5d2-ac7f-473b-a9d8-17a89f99ac39", + "resourceVersion": "1361174579", + "creationTimestamp": "2021-11-16T02:10:22Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller", + "controller-uid": "32be1b89-5b53-45b2-aa84-277e75214f61", + "job-name": "dice-roller-cronjob-1637028600" + }, + "annotations": {}, + "ownerReferences": [ + { + "apiVersion": "batch/v1", + "kind": "Job", + "name": "dice-roller-cronjob-1637028600", + "uid": "32be1b89-5b53-45b2-aa84-277e75214f61", + "controller": true, + "blockOwnerDeletion": true + } + ] + }, + "spec": { + "volumes": [], + "containers": [ + { + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"], + "image": "busybox", + "imagePullPolicy": "IfNotPresent", + "name": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "serviceAccountName": "default", + "serviceAccount": "default", + "nodeName": "minikube", + "securityContext": {}, + "schedulerName": "default-scheduler", + "tolerations": [ + { + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + }, + { + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + } + ], + "priority": 0, + "enableServiceLinks": true + }, + "status": { + "phase": "Running", + "conditions": [ + { + "type": "Initialized", + "status": "True", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T02:10:25Z" + }, + { + "type": "Ready", + "status": "True", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T02:10:35Z" + }, + { + "type": "ContainersReady", + "status": "True", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T02:10:35Z" + }, + { + "type": "PodScheduled", + "status": "True", + "lastProbeTime": null, + "lastTransitionTime": "2021-11-16T02:10:22Z" + } + ], + "hostIP": "192.168.49.2", + "podIP": "172.17.0.25", + "podIPs": [{ "ip": "172.17.0.25" }], + "startTime": "2021-11-16T02:10:22Z", + "containerStatuses": [ + { + "name": "busybox", + "state": { + "running": { "startedAt": "2021-11-16T02:10:31Z" } + }, + "lastState": {}, + "ready": true, + "restartCount": 0, + "image": "busybox:latest", + "imageID": "docker-pullable://busybox@sha256:e7157b6d7ebbe2cce5eaa8cfe8aa4fa82d173999b9f90a9ec42e57323546c353", + "containerID": "docker://1062343e1bb3625e36717bc15617c1bbca976366c3c9dd87035c71f33d015615", + "started": true + } + ], + "qosClass": "Burstable" + } + } + ] +} diff --git a/plugins/kubernetes/src/__fixtures__/2-cronjobs.json b/plugins/kubernetes/src/__fixtures__/2-cronjobs.json new file mode 100644 index 0000000000..6c087023b7 --- /dev/null +++ b/plugins/kubernetes/src/__fixtures__/2-cronjobs.json @@ -0,0 +1,385 @@ +{ + "cronJobs": [ + { + "metadata": { + "name": "dice-roller-cronjob", + "namespace": "default", + "uid": "9ea073bc-7a4b-4b99-8321-0305bce85568", + "resourceVersion": "1362732552", + "creationTimestamp": "2021-07-16T22:39:58Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "annotations": {} + }, + "spec": { + "schedule": "* */2 * * *", + "startingDeadlineSeconds": 1800, + "concurrencyPolicy": "Forbid", + "suspend": true, + "jobTemplate": { + "metadata": { "creationTimestamp": null }, + "spec": { + "backoffLimit": 2, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "annotations": {} + }, + "spec": { + "containers": [ + { + "name": "busybox", + "image": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "imagePullPolicy": "IfNotPresent", + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"] + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "securityContext": {}, + "schedulerName": "default-scheduler" + } + } + } + }, + "successfulJobsHistoryLimit": 2, + "failedJobsHistoryLimit": 2 + }, + "status": { + "lastScheduleTime": "2021-11-16T02:10:00Z" + } + } + ], + "jobs": [ + { + "metadata": { + "name": "dice-roller-cronjob-1637025000", + "namespace": "default", + "uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "resourceVersion": "1361029181", + "creationTimestamp": "2021-11-16T01:10:24Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "ownerReferences": [ + { + "apiVersion": "batch/v1", + "kind": "CronJob", + "name": "dice-roller-cronjob", + "uid": "9ea073bc-7a4b-4b99-8321-0305bce85568", + "controller": true, + "blockOwnerDeletion": true + } + ] + }, + "spec": { + "parallelism": 1, + "completions": 1, + "backoffLimit": 2, + "selector": { + "matchLabels": { + "controller-uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a" + } + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "backstage.io/kubernetes-id": "dice-roller", + "controller-uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "job-name": "dice-roller-cronjob-1637025000" + }, + "annotations": {} + }, + "spec": { + "containers": [ + { + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"], + "image": "busybox", + "imagePullPolicy": "IfNotPresent", + "name": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "securityContext": {}, + "schedulerName": "default-scheduler" + } + } + }, + "status": { + "conditions": [ + { + "type": "Failed", + "status": "True", + "reason": "BackoffLimitExceeded", + "lastProbeTime": "2021-11-16T01:11:31Z", + "lastTransitionTime": "2021-11-16T01:11:31Z" + } + ], + "startTime": "2021-11-16T01:10:24Z", + "failed": 2 + } + } + ], + "pods": [ + { + "metadata": { + "name": "dice-roller-cronjob-1637025000-gstc4", + "generateName": "dice-roller-cronjob-1637025000-", + "namespace": "default", + "uid": "3b0f2b65-5ae2-441a-beda-bdc92bcafaf0", + "resourceVersion": "1361029179", + "creationTimestamp": "2021-11-16T01:10:24Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller", + "controller-uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "job-name": "dice-roller-cronjob-1637025000" + }, + "annotations": {}, + "ownerReferences": [ + { + "apiVersion": "batch/v1", + "kind": "Job", + "name": "dice-roller-cronjob-1637025000", + "uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "controller": true, + "blockOwnerDeletion": true + } + ] + }, + "spec": { + "volumes": [], + "containers": [ + { + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"], + "image": "busybox", + "imagePullPolicy": "IfNotPresent", + "name": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "serviceAccountName": "default", + "serviceAccount": "default", + "nodeName": "minikube", + "securityContext": {}, + "schedulerName": "default-scheduler", + "tolerations": [ + { + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + }, + { + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + } + ], + "priority": 0, + "enableServiceLinks": true + }, + "status": { + "phase": "Failed", + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:10:13Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:11:02Z", + "message": "containers with unready status: [busybox]", + "reason": "ContainersNotReady", + "status": "False", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:11:02Z", + "message": "containers with unready status: [busybox]", + "reason": "ContainersNotReady", + "status": "False", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:10:08Z", + "status": "True", + "type": "PodScheduled" + } + ], + "hostIP": "192.168.49.2", + "podIP": "172.17.0.25", + "podIPs": [{ "ip": "172.17.0.25" }], + "startTime": "2021-11-18T19:10:08Z", + "containerStatuses": [ + { + "name": "busybox", + "state": { + "terminated": { + "exitCode": 1, + "finishedAt": "2021-11-18T19:11:01Z", + "reason": "Error", + "startedAt": "2021-11-18T19:10:17Z", + "containerID": "docker://1062343e1bb3625e36717bc15617c1bbca976366c3c9dd87035c71f33d015615" + } + }, + "lastState": {}, + "ready": false, + "restartCount": 0, + "image": "busybox:latest", + "imageID": "docker-pullable://busybox@sha256:e7157b6d7ebbe2cce5eaa8cfe8aa4fa82d173999b9f90a9ec42e57323546c353", + "containerID": "docker://1062343e1bb3625e36717bc15617c1bbca976366c3c9dd87035c71f33d015615", + "started": false + } + ], + "qosClass": "Burstable" + } + }, + { + "metadata": { + "name": "dice-roller-cronjob-1637025000-p4mlc", + "generateName": "dice-roller-cronjob-1637025000-", + "namespace": "default", + "uid": "acddd5d2-ac7f-473b-a9d8-17a89f99ac39", + "resourceVersion": "1361174579", + "creationTimestamp": "2021-11-16T02:10:22Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller", + "controller-uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "job-name": "dice-roller-cronjob-1637025000" + }, + "annotations": {}, + "ownerReferences": [ + { + "apiVersion": "batch/v1", + "kind": "Job", + "name": "dice-roller-cronjob-1637025000", + "uid": "69d5d242-a9a4-47b8-b9c7-c536ae8f151a", + "controller": true, + "blockOwnerDeletion": true + } + ] + }, + "spec": { + "volumes": [], + "containers": [ + { + "command": ["/bin/sh", "-c", "date; echo Rolling a die!"], + "image": "busybox", + "imagePullPolicy": "IfNotPresent", + "name": "busybox", + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "restartPolicy": "Never", + "terminationGracePeriodSeconds": 30, + "dnsPolicy": "ClusterFirst", + "serviceAccountName": "default", + "serviceAccount": "default", + "nodeName": "minikube", + "securityContext": {}, + "schedulerName": "default-scheduler", + "tolerations": [ + { + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + }, + { + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "effect": "NoExecute", + "tolerationSeconds": 300 + } + ], + "priority": 0, + "enableServiceLinks": true + }, + "status": { + "phase": "Failed", + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:10:13Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:11:02Z", + "message": "containers with unready status: [busybox]", + "reason": "ContainersNotReady", + "status": "False", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:11:02Z", + "message": "containers with unready status: [busybox]", + "reason": "ContainersNotReady", + "status": "False", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2021-11-18T19:10:08Z", + "status": "True", + "type": "PodScheduled" + } + ], + "hostIP": "192.168.49.2", + "podIP": "172.17.0.25", + "podIPs": [{ "ip": "172.17.0.25" }], + "startTime": "2021-11-16T02:10:22Z", + "containerStatuses": [ + { + "name": "busybox", + "state": { + "terminated": { + "exitCode": 1, + "finishedAt": "2021-11-18T19:11:01Z", + "reason": "Error", + "startedAt": "2021-11-18T19:10:17Z", + "containerID": "docker://2659c4d0f8a68f2b49863c18738322f1686d5b87275428e5e641fd9fd9e06739" + } + }, + "lastState": {}, + "ready": true, + "restartCount": 0, + "image": "busybox:latest", + "imageID": "docker-pullable://busybox@sha256:e7157b6d7ebbe2cce5eaa8cfe8aa4fa82d173999b9f90a9ec42e57323546c353", + "containerID": "docker://2659c4d0f8a68f2b49863c18738322f1686d5b87275428e5e641fd9fd9e06739", + "started": true + } + ], + "qosClass": "Burstable" + } + } + ] +} diff --git a/plugins/kubernetes/src/components/Cluster/Cluster.test.tsx b/plugins/kubernetes/src/components/Cluster/Cluster.test.tsx index ddadd95272..620af05e69 100644 --- a/plugins/kubernetes/src/components/Cluster/Cluster.test.tsx +++ b/plugins/kubernetes/src/components/Cluster/Cluster.test.tsx @@ -46,6 +46,7 @@ describe('Cluster', () => { resources: oneDeployment.pods, }, ], + podMetrics: [], errors: [], }, podsWithErrors: new Set(), diff --git a/plugins/kubernetes/src/components/Cluster/Cluster.tsx b/plugins/kubernetes/src/components/Cluster/Cluster.tsx index d238396f53..b7a819cdbf 100644 --- a/plugins/kubernetes/src/components/Cluster/Cluster.tsx +++ b/plugins/kubernetes/src/components/Cluster/Cluster.tsx @@ -23,12 +23,16 @@ import { Grid, Typography, } from '@material-ui/core'; -import { ClusterObjects } from '@backstage/plugin-kubernetes-common'; +import { + ClientPodStatus, + ClusterObjects, +} from '@backstage/plugin-kubernetes-common'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import { DeploymentsAccordions } from '../DeploymentsAccordions'; import { groupResponses } from '../../utils/response'; import { IngressesAccordions } from '../IngressesAccordions'; import { ServicesAccordions } from '../ServicesAccordions'; +import { CronJobsAccordions } from '../CronJobsAccordions'; import { CustomResources } from '../CustomResources'; import { ClusterContext, @@ -37,6 +41,7 @@ import { } from '../../hooks'; import { StatusError, StatusOK } from '@backstage/core-components'; +import { PodNamesWithMetricsContext } from '../../hooks/PodNamesWithMetrics'; type ClusterSummaryProps = { clusterName: string; @@ -107,36 +112,50 @@ type ClusterProps = { export const Cluster = ({ clusterObjects, podsWithErrors }: ClusterProps) => { const groupedResponses = groupResponses(clusterObjects.resources); + const podNameToMetrics = clusterObjects.podMetrics + .flat() + .reduce((accum, next) => { + const name = next.pod.metadata?.name; + if (name !== undefined) { + accum.set(name, next); + } + return accum; + }, new Map()); return ( - - - }> - - - - - - + + + + }> + + + + + + + + + + + + + + + + - + - - - - - - - - - - + + + + ); diff --git a/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsAccordions.test.tsx b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsAccordions.test.tsx new file mode 100644 index 0000000000..9d2df328d2 --- /dev/null +++ b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsAccordions.test.tsx @@ -0,0 +1,50 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { render } from '@testing-library/react'; +import { CronJobsAccordions } from './CronJobsAccordions'; +import * as oneCronJobsFixture from '../../__fixtures__/1-cronjobs.json'; +import * as twoCronJobsFixture from '../../__fixtures__/2-cronjobs.json'; +import { wrapInTestApp } from '@backstage/test-utils'; +import { kubernetesProviders } from '../../hooks/test-utils'; + +describe('CronJobsAccordions', () => { + it('should render 1 active cronjobs', async () => { + const wrapper = kubernetesProviders(oneCronJobsFixture, new Set()); + + const { getByText } = render( + wrapper(wrapInTestApp()), + ); + + expect(getByText('dice-roller-cronjob')).toBeInTheDocument(); + expect(getByText('CronJob')).toBeInTheDocument(); + expect(getByText('namespace: default')).toBeInTheDocument(); + expect(getByText('Active')).toBeInTheDocument(); + }); + + it('should render 1 suspended cronjobs', async () => { + const wrapper = kubernetesProviders(twoCronJobsFixture, new Set()); + + const { getByText } = render( + wrapper(wrapInTestApp()), + ); + + expect(getByText('dice-roller-cronjob')).toBeInTheDocument(); + expect(getByText('CronJob')).toBeInTheDocument(); + expect(getByText('namespace: default')).toBeInTheDocument(); + expect(getByText('Suspended')).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsAccordions.tsx b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsAccordions.tsx new file mode 100644 index 0000000000..2581678928 --- /dev/null +++ b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsAccordions.tsx @@ -0,0 +1,128 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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, { useContext } from 'react'; +import { + Accordion, + AccordionDetails, + AccordionSummary, + Divider, + Grid, + Typography, +} from '@material-ui/core'; +import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; +import { V1CronJob, V1Job } from '@kubernetes/client-node'; +import { JobsAccordions } from '../JobsAccordions'; +import { CronJobDrawer } from './CronJobsDrawer'; +import { getOwnedResources } from '../../utils/owner'; +import { GroupedResponsesContext } from '../../hooks'; +import { StatusError, StatusOK } from '@backstage/core-components'; +import cronstrue from 'cronstrue'; + +type CronJobsAccordionsProps = { + children?: React.ReactNode; +}; + +type CronJobAccordionProps = { + cronJob: V1CronJob; + ownedJobs: V1Job[]; + children?: React.ReactNode; +}; + +type CronJobSummaryProps = { + cronJob: V1CronJob; + children?: React.ReactNode; +}; + +const CronJobSummary = ({ cronJob }: CronJobSummaryProps) => { + return ( + + + + + + + + + + {cronJob.spec?.suspend ? ( + Suspended + ) : ( + Active + )} + + + + Schedule:{' '} + {cronJob.spec?.schedule + ? `${cronJob.spec.schedule} (${cronstrue.toString( + cronJob.spec.schedule, + )})` + : 'N/A'} + + + + + ); +}; + +const CronJobAccordion = ({ cronJob, ownedJobs }: CronJobAccordionProps) => { + return ( + + }> + + + + + + + ); +}; + +export const CronJobsAccordions = ({}: CronJobsAccordionsProps) => { + const groupedResponses = useContext(GroupedResponsesContext); + + return ( + + {groupedResponses.cronJobs.map((cronJob, i) => ( + + + + + + ))} + + ); +}; diff --git a/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsDrawer.test.tsx b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsDrawer.test.tsx new file mode 100644 index 0000000000..b16e83ee50 --- /dev/null +++ b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsDrawer.test.tsx @@ -0,0 +1,38 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 * as oneCronJobsFixture from '../../__fixtures__/1-cronjobs.json'; +import { renderInTestApp } from '@backstage/test-utils'; +import { CronJobDrawer } from './CronJobsDrawer'; + +describe('CronJobDrawer', () => { + it('should render cronJob drawer', async () => { + const { getByText, getAllByText } = await renderInTestApp( + , + ); + + expect(getAllByText('dice-roller-cronjob')).toHaveLength(2); + expect(getAllByText('CronJob')).toHaveLength(2); + expect(getByText('YAML')).toBeInTheDocument(); + expect(getByText('Schedule')).toBeInTheDocument(); + expect(getByText('30 5 * * *')).toBeInTheDocument(); + expect(getByText('Starting Deadline Seconds')).toBeInTheDocument(); + expect(getByText('Last Schedule Time')).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsDrawer.tsx b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsDrawer.tsx new file mode 100644 index 0000000000..758f17ade0 --- /dev/null +++ b/plugins/kubernetes/src/components/CronJobsAccordions/CronJobsDrawer.tsx @@ -0,0 +1,67 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { V1CronJob } from '@kubernetes/client-node'; +import { KubernetesDrawer } from '../KubernetesDrawer/KubernetesDrawer'; +import { Typography, Grid, Chip } from '@material-ui/core'; + +export const CronJobDrawer = ({ + cronJob, + expanded, +}: { + cronJob: V1CronJob; + expanded?: boolean; +}) => { + const namespace = cronJob.metadata?.namespace; + return ( + ({ + schedule: cronJobObj.spec?.schedule ?? '???', + startingDeadlineSeconds: + cronJobObj.spec?.startingDeadlineSeconds ?? '???', + concurrencyPolicy: cronJobObj.spec?.concurrencyPolicy ?? '???', + lastScheduleTime: cronJobObj.status?.lastScheduleTime ?? '???', + })} + > + + + + {cronJob.metadata?.name ?? 'unknown object'} + + + + + CronJob + + + {namespace && ( + + + + )} + + + ); +}; diff --git a/plugins/kubernetes/src/components/CronJobsAccordions/index.ts b/plugins/kubernetes/src/components/CronJobsAccordions/index.ts new file mode 100644 index 0000000000..e72e3f7e6d --- /dev/null +++ b/plugins/kubernetes/src/components/CronJobsAccordions/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { CronJobsAccordions } from './CronJobsAccordions'; diff --git a/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.tsx b/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.tsx index e14cd9093a..52734e39a8 100644 --- a/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.tsx +++ b/plugins/kubernetes/src/components/CustomResources/ArgoRollouts/Rollout.tsx @@ -41,6 +41,7 @@ import { getOwnedPodsThroughReplicaSets, } from '../../../utils/owner'; import { StatusError, StatusOK } from '@backstage/core-components'; +import { READY_COLUMNS, RESOURCE_COLUMNS } from '../../Pods/PodsTable'; type RolloutAccordionsProps = { rollouts: any[]; @@ -237,7 +238,10 @@ const RolloutAccordion = ({ />
- +
diff --git a/plugins/kubernetes/src/components/DeploymentsAccordions/DeploymentsAccordions.tsx b/plugins/kubernetes/src/components/DeploymentsAccordions/DeploymentsAccordions.tsx index e27c2bfbe1..58ab2fc2ba 100644 --- a/plugins/kubernetes/src/components/DeploymentsAccordions/DeploymentsAccordions.tsx +++ b/plugins/kubernetes/src/components/DeploymentsAccordions/DeploymentsAccordions.tsx @@ -41,6 +41,7 @@ import { PodNamesWithErrorsContext, } from '../../hooks'; import { StatusError, StatusOK } from '@backstage/core-components'; +import { READY_COLUMNS, RESOURCE_COLUMNS } from '../Pods/PodsTable'; type DeploymentsAccordionsProps = { children?: React.ReactNode; @@ -161,7 +162,10 @@ const DeploymentAccordion = ({ /> - + ); diff --git a/plugins/kubernetes/src/components/ErrorPanel/ErrorPanel.test.tsx b/plugins/kubernetes/src/components/ErrorPanel/ErrorPanel.test.tsx index 02154c4825..832d6eed91 100644 --- a/plugins/kubernetes/src/components/ErrorPanel/ErrorPanel.test.tsx +++ b/plugins/kubernetes/src/components/ErrorPanel/ErrorPanel.test.tsx @@ -51,6 +51,7 @@ describe('ErrorPanel', () => { name: 'THIS_CLUSTER', }, resources: [], + podMetrics: [], errors: [ { errorType: 'SYSTEM_ERROR', diff --git a/plugins/kubernetes/src/components/IngressesAccordions/IngressDrawer.tsx b/plugins/kubernetes/src/components/IngressesAccordions/IngressDrawer.tsx index 0018c4b070..dc88987d53 100644 --- a/plugins/kubernetes/src/components/IngressesAccordions/IngressDrawer.tsx +++ b/plugins/kubernetes/src/components/IngressesAccordions/IngressDrawer.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import { ExtensionsV1beta1Ingress } from '@kubernetes/client-node'; +import { V1Ingress } from '@kubernetes/client-node'; import { KubernetesDrawer } from '../KubernetesDrawer/KubernetesDrawer'; import { Typography, Grid } from '@material-ui/core'; @@ -23,7 +23,7 @@ export const IngressDrawer = ({ ingress, expanded, }: { - ingress: ExtensionsV1beta1Ingress; + ingress: V1Ingress; expanded?: boolean; }) => { return ( @@ -31,7 +31,7 @@ export const IngressDrawer = ({ object={ingress} expanded={expanded} kind="Ingress" - renderObject={(ingressObject: ExtensionsV1beta1Ingress) => { + renderObject={(ingressObject: V1Ingress) => { return ingressObject.spec || {}; }} > diff --git a/plugins/kubernetes/src/components/IngressesAccordions/IngressesAccordions.tsx b/plugins/kubernetes/src/components/IngressesAccordions/IngressesAccordions.tsx index c1d94fef7b..f6d6e4bf68 100644 --- a/plugins/kubernetes/src/components/IngressesAccordions/IngressesAccordions.tsx +++ b/plugins/kubernetes/src/components/IngressesAccordions/IngressesAccordions.tsx @@ -23,7 +23,7 @@ import { Grid, } from '@material-ui/core'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; -import { ExtensionsV1beta1Ingress } from '@kubernetes/client-node'; +import { V1Ingress } from '@kubernetes/client-node'; import { IngressDrawer } from './IngressDrawer'; import { GroupedResponsesContext } from '../../hooks'; import { StructuredMetadataTable } from '@backstage/core-components'; @@ -31,11 +31,11 @@ import { StructuredMetadataTable } from '@backstage/core-components'; type IngressesAccordionsProps = {}; type IngressAccordionProps = { - ingress: ExtensionsV1beta1Ingress; + ingress: V1Ingress; }; type IngressSummaryProps = { - ingress: ExtensionsV1beta1Ingress; + ingress: V1Ingress; }; const IngressSummary = ({ ingress }: IngressSummaryProps) => { @@ -58,7 +58,7 @@ const IngressSummary = ({ ingress }: IngressSummaryProps) => { }; type IngressCardProps = { - ingress: ExtensionsV1beta1Ingress; + ingress: V1Ingress; }; const IngressCard = ({ ingress }: IngressCardProps) => { diff --git a/plugins/kubernetes/src/components/JobsAccordions/JobsAccordions.test.tsx b/plugins/kubernetes/src/components/JobsAccordions/JobsAccordions.test.tsx new file mode 100644 index 0000000000..ea16e933c6 --- /dev/null +++ b/plugins/kubernetes/src/components/JobsAccordions/JobsAccordions.test.tsx @@ -0,0 +1,42 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { render } from '@testing-library/react'; +import { JobsAccordions } from './JobsAccordions'; +import * as oneCronJobsFixture from '../../__fixtures__/1-cronjobs.json'; +import { wrapInTestApp } from '@backstage/test-utils'; +import { kubernetesProviders } from '../../hooks/test-utils'; +import { V1Job, ObjectSerializer } from '@kubernetes/client-node'; + +describe('JobsAccordions', () => { + it('should render 2 jobs', async () => { + const wrapper = kubernetesProviders(oneCronJobsFixture, new Set()); + + const jobs: V1Job[] = oneCronJobsFixture.jobs.map( + job => ObjectSerializer.deserialize(job, 'V1Job') as V1Job, + ); + + const { getByText } = render( + wrapper(wrapInTestApp()), + ); + + expect(getByText('dice-roller-cronjob-1637028600')).toBeInTheDocument(); + expect(getByText('Running')).toBeInTheDocument(); + + expect(getByText('dice-roller-cronjob-1637025000')).toBeInTheDocument(); + expect(getByText('Succeeded')).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/JobsAccordions/JobsAccordions.tsx b/plugins/kubernetes/src/components/JobsAccordions/JobsAccordions.tsx new file mode 100644 index 0000000000..715be4c88a --- /dev/null +++ b/plugins/kubernetes/src/components/JobsAccordions/JobsAccordions.tsx @@ -0,0 +1,125 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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, { useContext } from 'react'; +import { + Accordion, + AccordionDetails, + AccordionSummary, + Divider, + Grid, +} from '@material-ui/core'; +import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; +import { V1Job, V1Pod } from '@kubernetes/client-node'; +import { PodsTable } from '../Pods'; +import { JobDrawer } from './JobsDrawer'; +import { getOwnedResources } from '../../utils/owner'; +import { GroupedResponsesContext } from '../../hooks'; +import { + StatusError, + StatusOK, + StatusPending, +} from '@backstage/core-components'; + +type JobsAccordionsProps = { + jobs: V1Job[]; + children?: React.ReactNode; +}; + +type JobAccordionProps = { + job: V1Job; + ownedPods: V1Pod[]; + children?: React.ReactNode; +}; + +type JobSummaryProps = { + job: V1Job; + children?: React.ReactNode; +}; + +const JobSummary = ({ job }: JobSummaryProps) => { + return ( + + + + + + + + + + {job.status?.succeeded && Succeeded} + {job.status?.active && Running} + {job.status?.failed && Failed} + + Start time: {job.status?.startTime?.toString()} + {job.status?.completionTime && ( + + Completion time: {job.status.completionTime.toString()} + + )} + + + ); +}; + +const JobAccordion = ({ job, ownedPods }: JobAccordionProps) => { + return ( + + }> + + + + + + + ); +}; + +export const JobsAccordions = ({ jobs }: JobsAccordionsProps) => { + const groupedResponses = useContext(GroupedResponsesContext); + + return ( + + {jobs.map((job, i) => ( + + + + + + ))} + + ); +}; diff --git a/plugins/kubernetes/src/components/JobsAccordions/JobsDrawer.test.tsx b/plugins/kubernetes/src/components/JobsAccordions/JobsDrawer.test.tsx new file mode 100644 index 0000000000..48a4e6fe7e --- /dev/null +++ b/plugins/kubernetes/src/components/JobsAccordions/JobsDrawer.test.tsx @@ -0,0 +1,35 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 * as oneCronJobsFixture from '../../__fixtures__/1-cronjobs.json'; +import { renderInTestApp } from '@backstage/test-utils'; +import { JobDrawer } from './JobsDrawer'; + +describe('JobDrawer', () => { + it('should render job drawer', async () => { + const { getByText, getAllByText } = await renderInTestApp( + , + ); + + expect(getAllByText('dice-roller-cronjob-1637025000')).toHaveLength(2); + expect(getAllByText('Job')).toHaveLength(2); + expect(getByText('YAML')).toBeInTheDocument(); + expect(getByText('Parallelism')).toBeInTheDocument(); + expect(getByText('Completions')).toBeInTheDocument(); + expect(getByText('Backoff Limit')).toBeInTheDocument(); + expect(getByText('Start Time')).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/JobsAccordions/JobsDrawer.tsx b/plugins/kubernetes/src/components/JobsAccordions/JobsDrawer.tsx new file mode 100644 index 0000000000..a7217725b2 --- /dev/null +++ b/plugins/kubernetes/src/components/JobsAccordions/JobsDrawer.tsx @@ -0,0 +1,62 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { V1Job } from '@kubernetes/client-node'; +import { KubernetesDrawer } from '../KubernetesDrawer/KubernetesDrawer'; +import { Typography, Grid } from '@material-ui/core'; + +export const JobDrawer = ({ + job, + expanded, +}: { + job: V1Job; + expanded?: boolean; +}) => { + return ( + { + return { + parallelism: jobObj.spec?.parallelism ?? '???', + completions: jobObj.spec?.completions ?? '???', + backoffLimit: jobObj.spec?.backoffLimit ?? '???', + startTime: jobObj.status?.startTime ?? '???', + }; + }} + > + + + + {job.metadata?.name ?? 'unknown object'} + + + + + Job + + + + + ); +}; diff --git a/plugins/kubernetes/src/components/JobsAccordions/index.ts b/plugins/kubernetes/src/components/JobsAccordions/index.ts new file mode 100644 index 0000000000..392309de79 --- /dev/null +++ b/plugins/kubernetes/src/components/JobsAccordions/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { JobsAccordions } from './JobsAccordions'; diff --git a/plugins/kubernetes/src/components/KubernetesContent.test.tsx b/plugins/kubernetes/src/components/KubernetesContent.test.tsx index db8cd06782..231eb3b37a 100644 --- a/plugins/kubernetes/src/components/KubernetesContent.test.tsx +++ b/plugins/kubernetes/src/components/KubernetesContent.test.tsx @@ -73,6 +73,7 @@ describe('KubernetesContent', () => { resources: oneDeployment.pods, }, ], + podMetrics: [], errors: [], }, ], @@ -121,6 +122,7 @@ describe('KubernetesContent', () => { resources: twoDeployments.pods, }, ], + podMetrics: [], errors: [], }, { @@ -139,6 +141,7 @@ describe('KubernetesContent', () => { resources: oneDeployment.pods, }, ], + podMetrics: [], errors: [], }, ], diff --git a/plugins/kubernetes/src/components/Pods/PodsTable.test.tsx b/plugins/kubernetes/src/components/Pods/PodsTable.test.tsx index 7c6c7e97f7..1201ad106d 100644 --- a/plugins/kubernetes/src/components/Pods/PodsTable.test.tsx +++ b/plugins/kubernetes/src/components/Pods/PodsTable.test.tsx @@ -19,7 +19,9 @@ import { render } from '@testing-library/react'; import * as pod from './__fixtures__/pod.json'; import * as crashingPod from './__fixtures__/crashing-pod.json'; import { wrapInTestApp } from '@backstage/test-utils'; -import { PodsTable } from './PodsTable'; +import { PodsTable, READY_COLUMNS, RESOURCE_COLUMNS } from './PodsTable'; +import { kubernetesProviders } from '../../hooks/test-utils'; +import { ClientPodStatus } from '@backstage/plugin-kubernetes-common'; describe('PodsTable', () => { it('should render pod', async () => { @@ -27,6 +29,24 @@ describe('PodsTable', () => { wrapInTestApp(), ); + // titles + expect(getByText('name')).toBeInTheDocument(); + expect(getByText('phase')).toBeInTheDocument(); + expect(getByText('status')).toBeInTheDocument(); + + // values + expect(getByText('dice-roller-6c8646bfd-2m5hv')).toBeInTheDocument(); + expect(getByText('Running')).toBeInTheDocument(); + expect(getByText('OK')).toBeInTheDocument(); + }); + + it('should render pod with extra columns', async () => { + const { getByText } = render( + wrapInTestApp( + , + ), + ); + // titles expect(getByText('name')).toBeInTheDocument(); expect(getByText('phase')).toBeInTheDocument(); @@ -41,9 +61,102 @@ describe('PodsTable', () => { expect(getByText('0')).toBeInTheDocument(); expect(getByText('OK')).toBeInTheDocument(); }); - it('should render crashing pod', async () => { + it('should render pod, with metrics context', async () => { + const podNameToClientPodStatus = new Map(); + + podNameToClientPodStatus.set('dice-roller-6c8646bfd-2m5hv', { + memory: { + currentUsage: '1069056', + requestTotal: '67108864', + limitTotal: '134217728', + }, + cpu: { + currentUsage: 0.4966115, + requestTotal: 0.05, + limitTotal: 0.05, + }, + } as any); + + const wrapper = kubernetesProviders( + undefined, + undefined, + podNameToClientPodStatus, + ); + const { getByText } = render( + wrapper( + wrapInTestApp( + , + ), + ), + ); + + // titles + expect(getByText('name')).toBeInTheDocument(); + expect(getByText('phase')).toBeInTheDocument(); + expect(getByText('containers ready')).toBeInTheDocument(); + expect(getByText('total restarts')).toBeInTheDocument(); + expect(getByText('status')).toBeInTheDocument(); + expect(getByText('CPU usage %')).toBeInTheDocument(); + expect(getByText('Memory usage %')).toBeInTheDocument(); + + // values + expect(getByText('dice-roller-6c8646bfd-2m5hv')).toBeInTheDocument(); + expect(getByText('Running')).toBeInTheDocument(); + expect(getByText('1/1')).toBeInTheDocument(); + expect(getByText('0')).toBeInTheDocument(); + expect(getByText('OK')).toBeInTheDocument(); + expect(getByText('requests: 99%')).toBeInTheDocument(); + expect(getByText('limits: 99%')).toBeInTheDocument(); + expect(getByText('requests: 1%')).toBeInTheDocument(); + expect(getByText('limits: 0%')).toBeInTheDocument(); + }); + it('should render placehoplder when empty metrics context', async () => { + const podNameToClientPodStatus = new Map(); + + const wrapper = kubernetesProviders( + undefined, + undefined, + podNameToClientPodStatus, + ); const { getByText, getAllByText } = render( - wrapInTestApp(), + wrapper( + wrapInTestApp( + , + ), + ), + ); + + // titles + expect(getByText('name')).toBeInTheDocument(); + expect(getByText('phase')).toBeInTheDocument(); + expect(getByText('containers ready')).toBeInTheDocument(); + expect(getByText('total restarts')).toBeInTheDocument(); + expect(getByText('status')).toBeInTheDocument(); + expect(getByText('CPU usage %')).toBeInTheDocument(); + expect(getByText('Memory usage %')).toBeInTheDocument(); + + // values + expect(getByText('dice-roller-6c8646bfd-2m5hv')).toBeInTheDocument(); + expect(getByText('Running')).toBeInTheDocument(); + expect(getByText('1/1')).toBeInTheDocument(); + expect(getByText('0')).toBeInTheDocument(); + expect(getByText('OK')).toBeInTheDocument(); + expect(getAllByText('unknown')).toHaveLength(2); + }); + it('should render crashing pod with extra columns', async () => { + const { getByText, getAllByText } = render( + wrapInTestApp( + , + ), ); // titles diff --git a/plugins/kubernetes/src/components/Pods/PodsTable.tsx b/plugins/kubernetes/src/components/Pods/PodsTable.tsx index 7b5497ff37..1d2369e322 100644 --- a/plugins/kubernetes/src/components/Pods/PodsTable.tsx +++ b/plugins/kubernetes/src/components/Pods/PodsTable.tsx @@ -14,17 +14,30 @@ * limitations under the License. */ -import React from 'react'; +import React, { useContext } from 'react'; import { V1Pod } from '@kubernetes/client-node'; import { PodDrawer } from './PodDrawer'; import { containersReady, containerStatuses, + podStatusToCpuUtil, + podStatusToMemoryUtil, totalRestarts, } from '../../utils/pod'; import { Table, TableColumn } from '@backstage/core-components'; +import { PodNamesWithMetricsContext } from '../../hooks/PodNamesWithMetrics'; -const columns: TableColumn[] = [ +export const READY_COLUMNS: PodColumns = 'READY'; +export const RESOURCE_COLUMNS: PodColumns = 'RESOURCE'; +export type PodColumns = 'READY' | 'RESOURCE'; + +type PodsTablesProps = { + pods: V1Pod[]; + extraColumns?: PodColumns[]; + children?: React.ReactNode; +}; + +const DEFAULT_COLUMNS: TableColumn[] = [ { title: 'name', highlight: true, @@ -34,6 +47,13 @@ const columns: TableColumn[] = [ title: 'phase', render: (pod: V1Pod) => pod.status?.phase ?? 'unknown', }, + { + title: 'status', + render: containerStatuses, + }, +]; + +const READY: TableColumn[] = [ { title: 'containers ready', align: 'center', @@ -45,18 +65,45 @@ const columns: TableColumn[] = [ render: totalRestarts, type: 'numeric', }, - { - title: 'status', - render: containerStatuses, - }, ]; -type DeploymentTablesProps = { - pods: V1Pod[]; - children?: React.ReactNode; -}; +export const PodsTable = ({ pods, extraColumns = [] }: PodsTablesProps) => { + const podNamesWithMetrics = useContext(PodNamesWithMetricsContext); + const columns: TableColumn[] = [...DEFAULT_COLUMNS]; + + if (extraColumns.includes(READY_COLUMNS)) { + columns.push(...READY); + } + if (extraColumns.includes(RESOURCE_COLUMNS)) { + const resourceColumns: TableColumn[] = [ + { + title: 'CPU usage %', + render: (pod: V1Pod) => { + const metrics = podNamesWithMetrics.get(pod.metadata?.name ?? ''); + + if (!metrics) { + return 'unknown'; + } + + return podStatusToCpuUtil(metrics); + }, + }, + { + title: 'Memory usage %', + render: (pod: V1Pod) => { + const metrics = podNamesWithMetrics.get(pod.metadata?.name ?? ''); + + if (!metrics) { + return 'unknown'; + } + + return podStatusToMemoryUtil(metrics); + }, + }, + ]; + columns.push(...resourceColumns); + } -export const PodsTable = ({ pods }: DeploymentTablesProps) => { const tableStyle = { minWidth: '0', width: '100%', diff --git a/plugins/kubernetes/src/error-detection/error-detection.test.ts b/plugins/kubernetes/src/error-detection/error-detection.test.ts index 2e982f25f7..dcac7db907 100644 --- a/plugins/kubernetes/src/error-detection/error-detection.test.ts +++ b/plugins/kubernetes/src/error-detection/error-detection.test.ts @@ -40,6 +40,7 @@ const oneItem = (value: FetchResponse): ObjectsByEntityResponse => { { cluster: { name: CLUSTER_NAME }, errors: [], + podMetrics: [], resources: [value], }, ], @@ -74,6 +75,7 @@ describe('detectErrors', () => { { cluster: { name: 'cluster-a' }, errors: [], + podMetrics: [], resources: [ { type: 'pods', @@ -84,6 +86,7 @@ describe('detectErrors', () => { { cluster: { name: 'cluster-b' }, errors: [], + podMetrics: [], resources: [ { type: 'horizontalpodautoscalers', @@ -94,6 +97,7 @@ describe('detectErrors', () => { { cluster: { name: 'cluster-c' }, errors: [], + podMetrics: [], resources: [ { type: 'deployments', diff --git a/plugins/kubernetes/src/hooks/GroupedResponses.ts b/plugins/kubernetes/src/hooks/GroupedResponses.ts index d000086b7c..35f7e10b5c 100644 --- a/plugins/kubernetes/src/hooks/GroupedResponses.ts +++ b/plugins/kubernetes/src/hooks/GroupedResponses.ts @@ -24,5 +24,7 @@ export const GroupedResponsesContext = React.createContext({ configMaps: [], horizontalPodAutoscalers: [], ingresses: [], + jobs: [], + cronJobs: [], customResources: [], }); diff --git a/plugins/kubernetes/src/hooks/PodNamesWithMetrics.ts b/plugins/kubernetes/src/hooks/PodNamesWithMetrics.ts new file mode 100644 index 0000000000..66a833ad88 --- /dev/null +++ b/plugins/kubernetes/src/hooks/PodNamesWithMetrics.ts @@ -0,0 +1,21 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { ClientPodStatus } from '@backstage/plugin-kubernetes-common'; + +export const PodNamesWithMetricsContext = React.createContext< + Map +>(new Map()); diff --git a/plugins/kubernetes/src/hooks/test-utils.tsx b/plugins/kubernetes/src/hooks/test-utils.tsx index c5b7a8f5d9..a7a6f42512 100644 --- a/plugins/kubernetes/src/hooks/test-utils.tsx +++ b/plugins/kubernetes/src/hooks/test-utils.tsx @@ -17,17 +17,25 @@ import React from 'react'; import { GroupedResponsesContext } from './GroupedResponses'; import { PodNamesWithErrorsContext } from './PodNamesWithErrors'; +import { PodNamesWithMetricsContext } from './PodNamesWithMetrics'; +import { ClientPodStatus } from '@backstage/plugin-kubernetes-common'; export const kubernetesProviders = ( - groupedResponses: any, - podsWithErrors: any, + groupedResponses: any = undefined, + podsWithErrors: Set = new Set(), + podNameToMetrics: Map = new Map< + string, + ClientPodStatus + >(), ) => { return (node: React.ReactNode) => ( <> - - {node} - + + + {node} + + ); diff --git a/plugins/kubernetes/src/types/types.ts b/plugins/kubernetes/src/types/types.ts index 05337086be..d6ef8fa784 100644 --- a/plugins/kubernetes/src/types/types.ts +++ b/plugins/kubernetes/src/types/types.ts @@ -21,7 +21,9 @@ import { V1HorizontalPodAutoscaler, V1Service, V1ConfigMap, - ExtensionsV1beta1Ingress, + V1Ingress, + V1Job, + V1CronJob, } from '@kubernetes/client-node'; export interface DeploymentResources { @@ -34,7 +36,9 @@ export interface DeploymentResources { export interface GroupedResponses extends DeploymentResources { services: V1Service[]; configMaps: V1ConfigMap[]; - ingresses: ExtensionsV1beta1Ingress[]; + ingresses: V1Ingress[]; + jobs: V1Job[]; + cronJobs: V1CronJob[]; customResources: any[]; } diff --git a/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.test.ts b/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.test.ts index afc53d9509..31e07a0f14 100644 --- a/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.test.ts +++ b/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.test.ts @@ -78,21 +78,6 @@ describe('clusterLinks', () => { 'https://k8s.foo.com/#/service/bar/foobar?namespace=bar', ); }); - it('should return an url on the deployment properly url encoded', () => { - const url = formatClusterLink({ - dashboardUrl: 'https://k8s.foo.com/', - object: { - metadata: { - name: 'foobar', - namespace: 'bar bar', - }, - }, - kind: 'Deployment', - }); - expect(url).toBe( - 'https://k8s.foo.com/#/deployment/bar%20bar/foobar?namespace=bar+bar', - ); - }); }); describe('standard app', () => { diff --git a/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.ts b/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.ts index 83e970248b..a8f83a9c76 100644 --- a/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.ts +++ b/plugins/kubernetes/src/utils/clusterLinks/formatClusterLink.ts @@ -40,8 +40,5 @@ export function formatClusterLink(options: FormatClusterLinkOptions) { object: options.object, kind: options.kind, }); - // Note that we can't rely on 'url.href' since it will put the search before the hash - // and this won't be properly recognized by SPAs such as Angular in the standard dashboard. - // Note also that pathname, hash and search will be properly url encoded. - return `${url.origin}${url.pathname}${url.hash}${url.search}`; + return url.toString(); } diff --git a/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.test.ts b/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.test.ts index df2529a8ac..f0b85cad49 100644 --- a/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.test.ts +++ b/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.test.ts @@ -17,19 +17,126 @@ import { openshiftFormatter } from './openshift'; describe('clusterLinks - OpenShift formatter', () => { it('should return an url on the workloads when there is a namespace only', () => { - expect(() => - openshiftFormatter({ - dashboardUrl: new URL('https://k8s.foo.com'), - object: { - metadata: { - name: 'foobar', - namespace: 'bar', - }, + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com'), + object: { + metadata: { + namespace: 'bar', }, - kind: 'Deployment', - }), - ).toThrowError( - 'OpenShift formatter is not yet implemented. Please, contribute!', + }, + kind: 'foo', + }); + expect(url.href).toBe('https://k8s.foo.com/k8s/cluster/projects/bar'); + }); + it('should return an url on the workloads when the kind is not recognizeed', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'UnknownKind', + }); + expect(url.href).toBe('https://k8s.foo.com/k8s/cluster/projects/bar'); + }); + it('should return an url on the deployment', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'Deployment', + }); + expect(url.href).toBe('https://k8s.foo.com/k8s/ns/bar/deployments/foobar'); + }); + it('should return an url on the deployment and keep the path prefix 1', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/some/prefix/'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'Deployment', + }); + expect(url.href).toBe( + 'https://k8s.foo.com/some/prefix/k8s/ns/bar/deployments/foobar', + ); + }); + it('should return an url on the deployment and keep the path prefix 2', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/some/prefix'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'Deployment', + }); + expect(url.href).toBe( + 'https://k8s.foo.com/some/prefix/k8s/ns/bar/deployments/foobar', + ); + }); + it('should return an url on the service', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'Service', + }); + expect(url.href).toBe('https://k8s.foo.com/k8s/ns/bar/services/foobar'); + }); + it('should return an url on the ingress', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'Ingress', + }); + expect(url.href).toBe('https://k8s.foo.com/k8s/ns/bar/ingresses/foobar'); + }); + it('should return an url on the deployment for a hpa', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'HorizontalPodAutoscaler', + }); + expect(url.href).toBe( + 'https://k8s.foo.com/k8s/ns/bar/horizontalpodautoscalers/foobar', + ); + }); + it('should return an url on the PV', () => { + const url = openshiftFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/'), + object: { + metadata: { + name: 'foobar', + }, + }, + kind: 'PersistentVolume', + }); + expect(url.href).toBe( + 'https://k8s.foo.com/k8s/cluster/persistentvolumes/foobar', ); }); }); diff --git a/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.ts b/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.ts index bacb747ebb..6c20cd4720 100644 --- a/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.ts +++ b/plugins/kubernetes/src/utils/clusterLinks/formatters/openshift.ts @@ -15,10 +15,40 @@ */ import { ClusterLinksFormatterOptions } from '../../../types/types'; -export function openshiftFormatter( - _options: ClusterLinksFormatterOptions, -): URL { - throw new Error( - 'OpenShift formatter is not yet implemented. Please, contribute!', +const kindMappings: Record = { + deployment: 'deployments', + ingress: 'ingresses', + service: 'services', + horizontalpodautoscaler: 'horizontalpodautoscalers', + persistentvolume: 'persistentvolumes', +}; + +export function openshiftFormatter(options: ClusterLinksFormatterOptions): URL { + const basePath = new URL(options.dashboardUrl.href); + const name = encodeURIComponent(options.object.metadata?.name ?? ''); + const namespace = encodeURIComponent( + options.object.metadata?.namespace ?? '', ); + const validKind = kindMappings[options.kind.toLocaleLowerCase('en-US')]; + if (!basePath.pathname.endsWith('/')) { + // a dashboard url with a path should end with a slash otherwise + // the new combined URL will replace the last segment with the appended path! + // https://foobar.com/abc/def + k8s/cluster/projects/test --> https://foobar.com/abc/k8s/cluster/projects/test + // https://foobar.com/abc/def/ + k8s/cluster/projects/test --> https://foobar.com/abc/def/k8s/cluster/projects/test + basePath.pathname += '/'; + } + let path = ''; + if (namespace) { + if (name && validKind) { + path = `k8s/ns/${namespace}/${validKind}/${name}`; + } else { + path = `k8s/cluster/projects/${namespace}`; + } + } else if (validKind) { + path = `k8s/cluster/${validKind}`; + if (name) { + path += `/${name}`; + } + } + return new URL(path, basePath); } diff --git a/plugins/kubernetes/src/utils/clusterLinks/formatters/rancher.ts b/plugins/kubernetes/src/utils/clusterLinks/formatters/rancher.ts index a3a274496e..1ace39ec59 100644 --- a/plugins/kubernetes/src/utils/clusterLinks/formatters/rancher.ts +++ b/plugins/kubernetes/src/utils/clusterLinks/formatters/rancher.ts @@ -23,14 +23,24 @@ const kindMappings: Record = { }; export function rancherFormatter(options: ClusterLinksFormatterOptions): URL { - const result = new URL(options.dashboardUrl.href); - const name = options.object.metadata?.name; - const namespace = options.object.metadata?.namespace; + const basePath = new URL(options.dashboardUrl.href); + const name = encodeURIComponent(options.object.metadata?.name ?? ''); + const namespace = encodeURIComponent( + options.object.metadata?.namespace ?? '', + ); const validKind = kindMappings[options.kind.toLocaleLowerCase('en-US')]; - if (validKind && name && namespace) { - result.pathname += `explorer/${validKind}/${namespace}/${name}`; - } else if (namespace) { - result.pathname += 'explorer/workload'; + if (!basePath.pathname.endsWith('/')) { + // a dashboard url with a path should end with a slash otherwise + // the new combined URL will replace the last segment with the appended path! + // https://foobar.com/abc/def + explorer/service/test --> https://foobar.com/abc/explorer/service/test + // https://foobar.com/abc/def/ + explorer/service/test --> https://foobar.com/abc/def/explorer/service/test + basePath.pathname += '/'; } - return result; + let path = ''; + if (validKind && name && namespace) { + path = `explorer/${validKind}/${namespace}/${name}`; + } else if (namespace) { + path = 'explorer/workload'; + } + return new URL(path, basePath); } diff --git a/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.test.ts b/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.test.ts index 76bbf5643d..0b3c21a627 100644 --- a/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.test.ts +++ b/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.test.ts @@ -67,6 +67,51 @@ describe('clusterLinks - standard formatter', () => { 'https://k8s.foo.com/#/deployment/bar/foobar?namespace=bar', ); }); + it('should return an url on the deployment with a prefix 1', () => { + const url = standardFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/some/prefix'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'Deployment', + }); + expect(formatUrl(url)).toBe( + 'https://k8s.foo.com/some/prefix/#/deployment/bar/foobar?namespace=bar', + ); + }); + it('should return an url on the deployment with a prefix 2', () => { + const url = standardFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/some/prefix/'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar', + }, + }, + kind: 'Deployment', + }); + expect(formatUrl(url)).toBe( + 'https://k8s.foo.com/some/prefix/#/deployment/bar/foobar?namespace=bar', + ); + }); + it('should return an url on the deployment properly url encoded', () => { + const url = standardFormatter({ + dashboardUrl: new URL('https://k8s.foo.com/'), + object: { + metadata: { + name: 'foobar', + namespace: 'bar bar', + }, + }, + kind: 'Deployment', + }); + expect(formatUrl(url)).toBe( + 'https://k8s.foo.com/#/deployment/bar%20bar/foobar?namespace=bar%20bar', + ); + }); it('should return an url on the service', () => { const url = standardFormatter({ dashboardUrl: new URL('https://k8s.foo.com/'), diff --git a/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.ts b/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.ts index fb26cf220d..e28c9fae2b 100644 --- a/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.ts +++ b/plugins/kubernetes/src/utils/clusterLinks/formatters/standard.ts @@ -24,16 +24,22 @@ const kindMappings: Record = { export function standardFormatter(options: ClusterLinksFormatterOptions) { const result = new URL(options.dashboardUrl.href); - const name = options.object.metadata?.name; - const namespace = options.object.metadata?.namespace; + const name = encodeURIComponent(options.object.metadata?.name ?? ''); + const namespace = encodeURIComponent( + options.object.metadata?.namespace ?? '', + ); const validKind = kindMappings[options.kind.toLocaleLowerCase('en-US')]; - if (namespace) { - result.searchParams.set('namespace', namespace); + if (!result.pathname.endsWith('/')) { + result.pathname += '/'; } if (validKind && name && namespace) { result.hash = `/${validKind}/${namespace}/${name}`; } else if (namespace) { result.hash = '/workloads'; } + if (namespace) { + // Note that Angular SPA requires a hash and the query parameter should be part of it + result.hash += `?namespace=${namespace}`; + } return result; } diff --git a/plugins/kubernetes/src/utils/pod.test.tsx b/plugins/kubernetes/src/utils/pod.test.tsx new file mode 100644 index 0000000000..5822a16b86 --- /dev/null +++ b/plugins/kubernetes/src/utils/pod.test.tsx @@ -0,0 +1,53 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { currentToDeclaredResourceToPerc, podStatusToCpuUtil } from './pod'; +import { SubvalueCell } from '@backstage/core-components'; + +describe('pod', () => { + describe('currentToDeclaredResourceToPerc', () => { + it('10%', () => { + const tests: (number | string)[][] = [ + [10, 100], + [10, '100'], + ['10', 100], + ['10', '100'], + ]; + tests.forEach(([a, b]) => { + const result = currentToDeclaredResourceToPerc(a, b); + expect(result).toBe('10%'); + }); + }); + }); + describe('podStatusToCpuUtil', () => { + it('does use correct units', () => { + const result = podStatusToCpuUtil({ + cpu: { + // ~50m + currentUsage: 0.4966115, + // 50m + requestTotal: 0.05, + // 100m + limitTotal: 0.1, + }, + } as any); + expect(result).toStrictEqual( + , + ); + }); + }); +}); diff --git a/plugins/kubernetes/src/utils/pod.tsx b/plugins/kubernetes/src/utils/pod.tsx index 8be2d839c3..bfb40750cd 100644 --- a/plugins/kubernetes/src/utils/pod.tsx +++ b/plugins/kubernetes/src/utils/pod.tsx @@ -14,16 +14,20 @@ * limitations under the License. */ -import { V1Pod, V1PodCondition } from '@kubernetes/client-node'; +import { + V1Pod, + V1PodCondition, + V1DeploymentCondition, +} from '@kubernetes/client-node'; import React, { Fragment, ReactNode } from 'react'; import { Chip } from '@material-ui/core'; -import { V1DeploymentCondition } from '@kubernetes/client-node/dist/gen/model/v1DeploymentCondition'; import { StatusAborted, StatusError, StatusOK, SubvalueCell, } from '@backstage/core-components'; +import { ClientPodStatus } from '@backstage/plugin-kubernetes-common'; export const imageChips = (pod: V1Pod): ReactNode => { const containerStatuses = pod.status?.containerStatuses ?? []; @@ -102,3 +106,62 @@ export const renderCondition = ( } return [condition.type, ]; }; + +// visible for testing +export const currentToDeclaredResourceToPerc = ( + current: number | string, + resource: number | string, +): string => { + if (typeof current === 'number' && typeof resource === 'number') { + return `${Math.round((current / resource) * 100)}%`; + } + + const numerator: bigint = BigInt(current); + const denominator: bigint = BigInt(resource); + + return `${(numerator * BigInt(100)) / denominator}%`; +}; + +export const podStatusToCpuUtil = (podStatus: ClientPodStatus): ReactNode => { + const cpuUtil = podStatus.cpu; + + let currentUsage: number | string = cpuUtil.currentUsage; + + // current usage number for CPU is a different unit than request/limit total + // this might be a bug in the k8s library + if (typeof cpuUtil.currentUsage === 'number') { + currentUsage = cpuUtil.currentUsage / 10; + } + + return ( + + ); +}; + +export const podStatusToMemoryUtil = ( + podStatus: ClientPodStatus, +): ReactNode => { + const memUtil = podStatus.memory; + + return ( + + ); +}; diff --git a/plugins/kubernetes/src/utils/response.ts b/plugins/kubernetes/src/utils/response.ts index 97501bb102..cfe3d20580 100644 --- a/plugins/kubernetes/src/utils/response.ts +++ b/plugins/kubernetes/src/utils/response.ts @@ -45,6 +45,12 @@ export const groupResponses = ( case 'ingresses': prev.ingresses.push(...next.resources); break; + case 'jobs': + prev.jobs.push(...next.resources); + break; + case 'cronjobs': + prev.cronJobs.push(...next.resources); + break; case 'customresources': prev.customResources.push(...next.resources); break; @@ -60,6 +66,8 @@ export const groupResponses = ( configMaps: [], horizontalPodAutoscalers: [], ingresses: [], + jobs: [], + cronJobs: [], customResources: [], } as GroupedResponses, ); diff --git a/plugins/lighthouse/package.json b/plugins/lighthouse/package.json index e53f6ee261..cbd5db27b4 100644 --- a/plugins/lighthouse/package.json +++ b/plugins/lighthouse/package.json @@ -34,10 +34,10 @@ "dependencies": { "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -47,10 +47,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/newrelic/package.json b/plugins/newrelic/package.json index 16029f1783..6676547a85 100644 --- a/plugins/newrelic/package.json +++ b/plugins/newrelic/package.json @@ -32,9 +32,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -43,10 +43,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/org/CHANGELOG.md b/plugins/org/CHANGELOG.md index f46095f46a..37c3320810 100644 --- a/plugins/org/CHANGELOG.md +++ b/plugins/org/CHANGELOG.md @@ -1,5 +1,14 @@ # @backstage/plugin-org +## 0.3.29 + +### Patch Changes + +- 2f4a686411: Use email links in the catalog's members list instead of text to display a member's email +- Updated dependencies + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.3.28 ### Patch Changes diff --git a/plugins/org/package.json b/plugins/org/package.json index db6cfe4d0b..2adb6c5d18 100644 --- a/plugins/org/package.json +++ b/plugins/org/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-org", "description": "A Backstage plugin that helps you create entity pages for your organization", - "version": "0.3.28", + "version": "0.3.29", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -22,10 +22,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -37,10 +37,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx b/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx index 0642e80a7b..7a15bd2122 100644 --- a/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx +++ b/plugins/org/src/components/Cards/Group/MembersList/MembersListCard.tsx @@ -28,14 +28,13 @@ import { Box, createStyles, Grid, - Link, makeStyles, Theme, Typography, } from '@material-ui/core'; import Pagination from '@material-ui/lab/Pagination'; import React from 'react'; -import { generatePath, Link as RouterLink } from 'react-router-dom'; +import { generatePath } from 'react-router-dom'; import { useAsync } from 'react-use'; import { @@ -43,6 +42,7 @@ import { InfoCard, Progress, ResponseErrorPanel, + Link, } from '@backstage/core-components'; import { useApi } from '@backstage/core-plugin-api'; @@ -90,7 +90,6 @@ const MemberComponent = ({ member }: { member: UserEntity }) => { { {displayName} - {profile?.email} + {profile?.email && ( + {profile.email} + )} diff --git a/plugins/pagerduty/package.json b/plugins/pagerduty/package.json index 7981b2c104..13cb8854ae 100644 --- a/plugins/pagerduty/package.json +++ b/plugins/pagerduty/package.json @@ -32,10 +32,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -48,10 +48,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/permission-backend/.eslintrc.js b/plugins/permission-backend/.eslintrc.js new file mode 100644 index 0000000000..16a033dbc6 --- /dev/null +++ b/plugins/permission-backend/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: [require.resolve('@backstage/cli/config/eslint.backend')], +}; diff --git a/plugins/permission-backend/CHANGELOG.md b/plugins/permission-backend/CHANGELOG.md new file mode 100644 index 0000000000..28df6bccbc --- /dev/null +++ b/plugins/permission-backend/CHANGELOG.md @@ -0,0 +1,29 @@ +# @backstage/plugin-permission-backend + +## 0.2.0 + +### Minor Changes + +- 450ca92330: Change route used for integration between the authorization framework and other plugin backends to use the /.well-known prefix. + +### Patch Changes + +- e7851efa9e: Rename and adjust permission policy return type to reduce nesting +- Updated dependencies + - @backstage/plugin-auth-backend@0.4.10 + - @backstage/plugin-permission-node@0.2.0 + - @backstage/backend-common@0.9.12 + +## 0.1.0 + +### Minor Changes + +- 7a8312f126: New package containing the backend for authorization and permissions. For more information, see the [authorization PRFC](https://github.com/backstage/backstage/pull/7761). + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-auth-backend@0.4.9 + - @backstage/plugin-permission-node@0.1.0 + - @backstage/backend-common@0.9.11 + - @backstage/plugin-permission-common@0.2.0 diff --git a/plugins/permission-backend/README.md b/plugins/permission-backend/README.md new file mode 100644 index 0000000000..59fe1730ba --- /dev/null +++ b/plugins/permission-backend/README.md @@ -0,0 +1,6 @@ +# @backstage/plugin-permission-backend + +> NOTE: THIS PACKAGE IS EXPERIMENTAL, HERE BE DRAGONS + +Backend for Backstage authorization and permissions. For more information, see +the [authorization PRFC](https://github.com/backstage/backstage/pull/7761). diff --git a/plugins/permission-backend/api-report.md b/plugins/permission-backend/api-report.md new file mode 100644 index 0000000000..4857c8b044 --- /dev/null +++ b/plugins/permission-backend/api-report.md @@ -0,0 +1,26 @@ +## API Report File for "@backstage/plugin-permission-backend" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts +import express from 'express'; +import { IdentityClient } from '@backstage/plugin-auth-backend'; +import { Logger as Logger_2 } from 'winston'; +import { PermissionPolicy } from '@backstage/plugin-permission-node'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; + +// @public +export function createRouter(options: RouterOptions): Promise; + +// @public +export interface RouterOptions { + // (undocumented) + discovery: PluginEndpointDiscovery; + // (undocumented) + identity: IdentityClient; + // (undocumented) + logger: Logger_2; + // (undocumented) + policy: PermissionPolicy; +} +``` diff --git a/plugins/permission-backend/package.json b/plugins/permission-backend/package.json new file mode 100644 index 0000000000..2018439398 --- /dev/null +++ b/plugins/permission-backend/package.json @@ -0,0 +1,44 @@ +{ + "name": "@backstage/plugin-permission-backend", + "version": "0.2.0", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + "publishConfig": { + "access": "public", + "main": "dist/index.cjs.js", + "types": "dist/index.d.ts" + }, + "scripts": { + "start": "backstage-cli backend:dev", + "build": "backstage-cli backend:build", + "lint": "backstage-cli lint", + "test": "backstage-cli test", + "prepack": "backstage-cli prepack", + "postpack": "backstage-cli postpack", + "clean": "backstage-cli clean" + }, + "dependencies": { + "@backstage/backend-common": "^0.9.12", + "@backstage/config": "^0.1.11", + "@backstage/plugin-auth-backend": "^0.4.10", + "@backstage/plugin-permission-common": "^0.2.0", + "@backstage/plugin-permission-node": "^0.2.0", + "@types/express": "*", + "express": "^4.17.1", + "express-promise-router": "^4.1.0", + "node-fetch": "^2.6.1", + "winston": "^3.2.1", + "yn": "^4.0.0", + "zod": "^3.11.6" + }, + "devDependencies": { + "@backstage/cli": "^0.10.0", + "@types/supertest": "^2.0.8", + "supertest": "^4.0.2", + "msw": "^0.35.0" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/permission-backend/src/index.ts b/plugins/permission-backend/src/index.ts new file mode 100644 index 0000000000..877b9070c3 --- /dev/null +++ b/plugins/permission-backend/src/index.ts @@ -0,0 +1,21 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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. + */ + +/** + * Backend for Backstage authorization and permissions. + * @packageDocumentation + */ +export * from './service'; diff --git a/plugins/permission-backend/src/service/PermissionIntegrationClient.test.ts b/plugins/permission-backend/src/service/PermissionIntegrationClient.test.ts new file mode 100644 index 0000000000..7f46490ce2 --- /dev/null +++ b/plugins/permission-backend/src/service/PermissionIntegrationClient.test.ts @@ -0,0 +1,292 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { AddressInfo } from 'net'; +import { Server } from 'http'; +import express, { Router } from 'express'; +import { RestContext, rest } from 'msw'; +import { setupServer, SetupServerApi } from 'msw/node'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { AuthorizeResult } from '@backstage/plugin-permission-common'; +import { createPermissionIntegrationRouter } from '@backstage/plugin-permission-node'; +import { PermissionIntegrationClient } from './PermissionIntegrationClient'; + +describe('PermissionIntegrationClient', () => { + describe('applyConditions', () => { + let server: SetupServerApi; + + const mockConditions = { + not: { + allOf: [ + { rule: 'RULE_1', params: [] }, + { rule: 'RULE_2', params: ['abc'] }, + ], + }, + }; + + const mockApplyConditionsHandler = jest.fn( + (_req, res, { json }: RestContext) => { + return res(json({ result: AuthorizeResult.ALLOW })); + }, + ); + + const mockBaseUrl = 'http://backstage:9191/i-am-a-mock-base'; + const discovery: PluginEndpointDiscovery = { + async getBaseUrl() { + return mockBaseUrl; + }, + async getExternalBaseUrl() { + throw new Error('Not implemented.'); + }, + }; + + const client: PermissionIntegrationClient = new PermissionIntegrationClient( + { + discovery, + }, + ); + + beforeAll(() => { + server = setupServer(); + server.listen({ onUnhandledRequest: 'error' }); + server.use( + rest.post( + `${mockBaseUrl}/.well-known/backstage/permissions/apply-conditions`, + mockApplyConditionsHandler, + ), + ); + }); + + afterAll(() => server.close()); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('should make a POST request to the correct endpoint', async () => { + await client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }); + + expect(mockApplyConditionsHandler).toHaveBeenCalled(); + }); + + it('should include a request body', async () => { + await client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }); + + expect(mockApplyConditionsHandler).toHaveBeenCalledWith( + expect.objectContaining({ + body: { + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }, + }), + expect.anything(), + expect.anything(), + ); + }); + + it('should return the response from the fetch request', async () => { + const response = await client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }); + + expect(response).toEqual( + expect.objectContaining({ result: AuthorizeResult.ALLOW }), + ); + }); + + it('should not include authorization headers if no token is supplied', async () => { + await client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }); + + const request = mockApplyConditionsHandler.mock.calls[0][0]; + expect(request.headers.has('authorization')).toEqual(false); + }); + + it('should include correctly-constructed authorization header if token is supplied', async () => { + await client.applyConditions( + { + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }, + 'Bearer fake-token', + ); + + const request = mockApplyConditionsHandler.mock.calls[0][0]; + expect(request.headers.get('authorization')).toEqual('Bearer fake-token'); + }); + + it('should forward response errors', async () => { + mockApplyConditionsHandler.mockImplementationOnce( + (_req, res, { status }: RestContext) => { + return res(status(401)); + }, + ); + + await expect( + client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }), + ).rejects.toThrowError(/401/i); + }); + + it('should reject invalid responses', async () => { + mockApplyConditionsHandler.mockImplementationOnce( + (_req, res, { json }: RestContext) => { + return res(json({ outcome: AuthorizeResult.ALLOW })); + }, + ); + + await expect( + client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: mockConditions, + }), + ).rejects.toThrowError(/invalid input/i); + }); + }); + + describe('integration with @backstage/plugin-permission-node', () => { + let server: Server; + let client: PermissionIntegrationClient; + + beforeAll(async () => { + const router = Router(); + + router.use( + createPermissionIntegrationRouter({ + resourceType: 'test-resource', + getResource: async resourceRef => ({ id: resourceRef }), + rules: [ + { + name: 'RULE_1', + description: 'Test rule 1', + apply: (_resource: any, input: 'yes' | 'no') => input === 'yes', + toQuery: () => { + throw new Error('Not implemented'); + }, + }, + { + name: 'RULE_2', + description: 'Test rule 2', + apply: (_resource: any, input: 'yes' | 'no') => input === 'yes', + toQuery: () => { + throw new Error('Not implemented'); + }, + }, + ], + }), + ); + + const app = express(); + + app.use('/test-plugin', router); + + await new Promise(resolve => { + server = app.listen(resolve); + }); + + const discovery: PluginEndpointDiscovery = { + async getBaseUrl(pluginId: string) { + const listenPort = (server.address()! as AddressInfo).port; + + return `http://0.0.0.0:${listenPort}/${pluginId}`; + }, + async getExternalBaseUrl() { + throw new Error('Not implemented.'); + }, + }; + + client = new PermissionIntegrationClient({ + discovery, + }); + }); + + afterAll( + async () => + new Promise((resolve, reject) => + server.close(err => (err ? reject(err) : resolve())), + ), + ); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('works for simple conditions', async () => { + await expect( + client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: { rule: 'RULE_1', params: ['no'] }, + }), + ).resolves.toEqual({ result: AuthorizeResult.DENY }); + }); + + it('works for complex criteria', async () => { + await expect( + client.applyConditions({ + pluginId: 'test-plugin', + resourceRef: 'testResource1', + resourceType: 'test-resource', + conditions: { + allOf: [ + { + allOf: [ + { rule: 'RULE_1', params: ['yes'] }, + { not: { rule: 'RULE_2', params: ['no'] } }, + ], + }, + { + not: { + allOf: [ + { rule: 'RULE_1', params: ['no'] }, + { rule: 'RULE_2', params: ['yes'] }, + ], + }, + }, + ], + }, + }), + ).resolves.toEqual({ result: AuthorizeResult.ALLOW }); + }); + }); +}); diff --git a/plugins/permission-backend/src/service/PermissionIntegrationClient.ts b/plugins/permission-backend/src/service/PermissionIntegrationClient.ts new file mode 100644 index 0000000000..de42a7f194 --- /dev/null +++ b/plugins/permission-backend/src/service/PermissionIntegrationClient.ts @@ -0,0 +1,82 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 fetch from 'node-fetch'; +import { z } from 'zod'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { + AuthorizeResult, + PermissionCondition, + PermissionCriteria, +} from '@backstage/plugin-permission-common'; +import { + ApplyConditionsRequest, + ApplyConditionsResponse, +} from '@backstage/plugin-permission-node'; + +const responseSchema = z.object({ + result: z.literal(AuthorizeResult.ALLOW).or(z.literal(AuthorizeResult.DENY)), +}); + +export class PermissionIntegrationClient { + private readonly discovery: PluginEndpointDiscovery; + + constructor(options: { discovery: PluginEndpointDiscovery }) { + this.discovery = options.discovery; + } + + async applyConditions( + { + pluginId, + resourceRef, + resourceType, + conditions, + }: { + resourceRef: string; + pluginId: string; + resourceType: string; + conditions: PermissionCriteria; + }, + authHeader?: string, + ): Promise { + const endpoint = `${await this.discovery.getBaseUrl( + pluginId, + )}/.well-known/backstage/permissions/apply-conditions`; + + const request: ApplyConditionsRequest = { + resourceRef, + resourceType, + conditions, + }; + + const response = await fetch(endpoint, { + method: 'POST', + body: JSON.stringify(request), + headers: { + ...(authHeader ? { authorization: authHeader } : {}), + 'content-type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error( + `Unexpected response from plugin upstream when applying conditions. Expected 200 but got ${response.status} - ${response.statusText}`, + ); + } + + return responseSchema.parse(await response.json()); + } +} diff --git a/plugins/permission-backend/src/service/index.ts b/plugins/permission-backend/src/service/index.ts new file mode 100644 index 0000000000..3ce8cdbcc4 --- /dev/null +++ b/plugins/permission-backend/src/service/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { createRouter } from './router'; +export type { RouterOptions } from './router'; diff --git a/plugins/permission-backend/src/service/router.test.ts b/plugins/permission-backend/src/service/router.test.ts new file mode 100644 index 0000000000..26fa7ef8a6 --- /dev/null +++ b/plugins/permission-backend/src/service/router.test.ts @@ -0,0 +1,294 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 express from 'express'; +import request from 'supertest'; +import { getVoidLogger } from '@backstage/backend-common'; +import { IdentityClient } from '@backstage/plugin-auth-backend'; +import { AuthorizeResult } from '@backstage/plugin-permission-common'; +import { ApplyConditionsResponse } from '@backstage/plugin-permission-node'; +import { PermissionIntegrationClient } from './PermissionIntegrationClient'; + +import { createRouter } from './router'; + +const mockApplyConditions: jest.MockedFunction< + InstanceType['applyConditions'] +> = jest.fn(); +jest.mock('./PermissionIntegrationClient', () => ({ + PermissionIntegrationClient: jest.fn(() => ({ + applyConditions: mockApplyConditions, + })), +})); + +const policy = { + handle: jest.fn().mockImplementation((_req, identity) => { + if (identity) { + return { result: AuthorizeResult.ALLOW }; + } + return { result: AuthorizeResult.DENY }; + }), +}; + +describe('createRouter', () => { + let app: express.Express; + + beforeAll(async () => { + const router = await createRouter({ + logger: getVoidLogger(), + discovery: { + getBaseUrl: jest.fn(), + getExternalBaseUrl: jest.fn(), + }, + identity: { + authenticate: jest.fn(token => { + if (!token) { + throw new Error('No token supplied!'); + } + + return Promise.resolve({ + id: 'test-user', + token, + }); + }), + } as unknown as IdentityClient, + policy, + }); + + app = express().use(router); + }); + + describe('GET /health', () => { + it('returns ok', async () => { + const response = await request(app).get('/health'); + + expect(response.status).toEqual(200); + expect(response.body).toEqual({ status: 'ok' }); + }); + }); + + describe('POST /authorize', () => { + it('calls the permission policy', async () => { + const response = await request(app) + .post('/authorize') + .send([ + { + id: '123', + permission: { + name: 'test.permission1', + attributes: {}, + }, + }, + { + id: '234', + permission: { + name: 'test.permission2', + attributes: {}, + }, + }, + ]); + + expect(response.status).toEqual(200); + + expect(policy.handle).toHaveBeenCalledWith( + { + permission: { + name: 'test.permission1', + attributes: {}, + }, + }, + undefined, + ); + expect(policy.handle).toHaveBeenCalledWith( + { + permission: { + name: 'test.permission2', + attributes: {}, + }, + }, + undefined, + ); + + expect(response.body).toEqual([ + { id: '123', result: AuthorizeResult.DENY }, + { id: '234', result: AuthorizeResult.DENY }, + ]); + }); + + it('resolves identity from the Authorization header', async () => { + const token = 'test-token'; + const response = await request(app) + .post('/authorize') + .auth(token, { type: 'bearer' }) + .send([ + { + id: '123', + permission: { + name: 'test.permission', + attributes: {}, + }, + }, + ]); + + expect(response.status).toEqual(200); + expect(policy.handle).toHaveBeenCalledWith( + { + permission: { + name: 'test.permission', + attributes: {}, + }, + }, + { id: 'test-user', token: 'test-token' }, + ); + expect(response.body).toEqual([ + { id: '123', result: AuthorizeResult.ALLOW }, + ]); + }); + + describe('conditional policy result', () => { + beforeEach(() => { + policy.handle.mockReturnValueOnce({ + result: AuthorizeResult.CONDITIONAL, + pluginId: 'test-plugin', + resourceType: 'test-resource-1', + conditions: { + anyOf: [{ rule: 'test-rule', params: ['abc'] }], + }, + }); + }); + + it('returns conditions if no resourceRef is supplied', async () => { + const response = await request(app) + .post('/authorize') + .send([ + { + id: '123', + permission: { + name: 'test.permission', + resourceType: 'test-resource-1', + attributes: {}, + }, + }, + ]); + + expect(response.status).toEqual(200); + expect(response.body).toEqual([ + { + id: '123', + result: AuthorizeResult.CONDITIONAL, + conditions: { anyOf: [{ rule: 'test-rule', params: ['abc'] }] }, + }, + ]); + }); + + it.each([ + AuthorizeResult.ALLOW, + AuthorizeResult.DENY, + ])( + 'applies conditions and returns %s if resourceRef is supplied', + async result => { + mockApplyConditions.mockResolvedValueOnce({ + result, + }); + + const response = await request(app) + .post('/authorize') + .auth('test-token', { type: 'bearer' }) + .send([ + { + id: '123', + resourceRef: 'test/resource', + permission: { + name: 'test.permission', + resourceType: 'test-resource-1', + attributes: {}, + }, + }, + ]); + + expect(mockApplyConditions).toHaveBeenCalledWith( + { + pluginId: 'test-plugin', + resourceType: 'test-resource-1', + resourceRef: 'test/resource', + conditions: { anyOf: [{ rule: 'test-rule', params: ['abc'] }] }, + }, + 'Bearer test-token', + ); + + expect(response.status).toEqual(200); + expect(response.body).toEqual([ + { + id: '123', + result, + }, + ]); + }, + ); + }); + + it.each([ + undefined, + '', + {}, + [{ permission: { name: 'test.permission', attributes: {} } }], + [{ id: '123' }], + [{ id: '123', permission: { name: 'test.permission' } }], + [{ id: '123', permission: { attributes: { invalid: 'attribute' } } }], + ])('returns a 500 error for invalid request %#', async requestBody => { + const response = await request(app).post('/authorize').send(requestBody); + + expect(response.status).toEqual(500); + expect(response.body).toEqual( + expect.objectContaining({ + error: expect.objectContaining({ + message: expect.stringMatching(/invalid/i), + }), + }), + ); + }); + + it('returns a 500 error if the policy returns a different resourceType', async () => { + policy.handle.mockReturnValueOnce({ + result: AuthorizeResult.CONDITIONAL, + pluginId: 'test-plugin', + resourceType: 'test-resource-2', + conditions: {}, + }); + + const response = await request(app) + .post('/authorize') + .send([ + { + id: '123', + permission: { + name: 'test.permission', + resourceType: 'test-resource-1', + attributes: {}, + }, + }, + ]); + + expect(response.status).toEqual(500); + expect(response.body).toEqual( + expect.objectContaining({ + error: expect.objectContaining({ + message: expect.stringMatching(/invalid resource conditions/i), + }), + }), + ); + }); + }); +}); diff --git a/plugins/permission-backend/src/service/router.ts b/plugins/permission-backend/src/service/router.ts new file mode 100644 index 0000000000..b85e7feb85 --- /dev/null +++ b/plugins/permission-backend/src/service/router.ts @@ -0,0 +1,165 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { z } from 'zod'; +import express, { Request, Response } from 'express'; +import Router from 'express-promise-router'; +import { Logger } from 'winston'; +import { + errorHandler, + PluginEndpointDiscovery, +} from '@backstage/backend-common'; +import { + BackstageIdentity, + IdentityClient, +} from '@backstage/plugin-auth-backend'; +import { + AuthorizeResult, + AuthorizeResponse, + AuthorizeRequest, + Identified, +} from '@backstage/plugin-permission-common'; +import { PermissionPolicy } from '@backstage/plugin-permission-node'; +import { PermissionIntegrationClient } from './PermissionIntegrationClient'; + +const requestSchema: z.ZodSchema[]> = z.array( + z.object({ + id: z.string(), + resourceRef: z.string().optional(), + permission: z.object({ + name: z.string(), + resourceType: z.string().optional(), + attributes: z.object({ + action: z + .union([ + z.literal('create'), + z.literal('read'), + z.literal('update'), + z.literal('delete'), + ]) + .optional(), + }), + }), + }), +); + +/** + * Options required when constructing a new {@link express#Router} using + * {@link createRouter}. + * + * @public + */ +export interface RouterOptions { + logger: Logger; + discovery: PluginEndpointDiscovery; + policy: PermissionPolicy; + identity: IdentityClient; +} + +const handleRequest = async ( + { id, resourceRef, ...request }: Identified, + user: BackstageIdentity | undefined, + policy: PermissionPolicy, + permissionIntegrationClient: PermissionIntegrationClient, + authHeader?: string, +): Promise> => { + const response = await policy.handle(request, user); + + if (response.result === AuthorizeResult.CONDITIONAL) { + // Sanity check that any resource provided matches the one expected by the permission + if (request.permission.resourceType !== response.resourceType) { + throw new Error( + `Invalid resource conditions returned from permission policy for permission ${request.permission.name}`, + ); + } + + if (resourceRef) { + return { + id, + ...(await permissionIntegrationClient.applyConditions( + { + resourceRef, + pluginId: response.pluginId, + resourceType: response.resourceType, + conditions: response.conditions, + }, + authHeader, + )), + }; + } + + return { + id, + result: AuthorizeResult.CONDITIONAL, + conditions: response.conditions, + }; + } + + return { id, ...response }; +}; + +/** + * Creates a new {@link express#Router} which provides the backend API + * for the permission system. + * + * @public + */ +export async function createRouter( + options: RouterOptions, +): Promise { + const { policy, discovery, identity } = options; + + const permissionIntegrationClient = new PermissionIntegrationClient({ + discovery, + }); + + const router = Router(); + router.use(express.json()); + + router.get('/health', (_, response) => { + response.send({ status: 'ok' }); + }); + + router.post( + '/authorize', + async ( + req: Request[]>, + res: Response[]>, + ) => { + const token = IdentityClient.getBearerToken(req.header('authorization')); + const user = token ? await identity.authenticate(token) : undefined; + + const body = requestSchema.parse(req.body); + + res.json( + await Promise.all( + body.map(request => + handleRequest( + request, + user, + policy, + permissionIntegrationClient, + req.header('authorization'), + ), + ), + ), + ); + }, + ); + + router.use(errorHandler()); + return router; +} diff --git a/packages/test-utils-core/src/index.ts b/plugins/permission-backend/src/setupTests.ts similarity index 81% rename from packages/test-utils-core/src/index.ts rename to plugins/permission-backend/src/setupTests.ts index 8f0a5b31e1..a330613afb 100644 --- a/packages/test-utils-core/src/index.ts +++ b/plugins/permission-backend/src/setupTests.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 The Backstage Authors + * Copyright 2021 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,3 @@ */ export {}; -throw new Error( - 'This module has been removed. Use @backstage/dev-utils instead', -); diff --git a/plugins/permission-common/CHANGELOG.md b/plugins/permission-common/CHANGELOG.md new file mode 100644 index 0000000000..c2ee5a3ecf --- /dev/null +++ b/plugins/permission-common/CHANGELOG.md @@ -0,0 +1,12 @@ +# @backstage/plugin-permission-common + +## 0.2.0 + +### Minor Changes + +- 92439056fb: Accept configApi rather than enabled flag in PermissionClient constructor. + +### Patch Changes + +- Updated dependencies + - @backstage/errors@0.1.5 diff --git a/plugins/permission-common/package.json b/plugins/permission-common/package.json index 9e1d60f782..495c262b03 100644 --- a/plugins/permission-common/package.json +++ b/plugins/permission-common/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-permission-common", "description": "Isomorphic types and client for Backstage permissions and authorization", - "version": "0.1.0", + "version": "0.2.0", "main": "src/index.ts", "types": "src/index.ts", "publishConfig": { @@ -39,13 +39,13 @@ }, "dependencies": { "@backstage/config": "^0.1.11", - "@backstage/errors": "^0.1.2", + "@backstage/errors": "^0.1.5", "cross-fetch": "^3.0.6", "uuid": "^8.0.0", "zod": "^3.11.6" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest": "^26.0.7", "msw": "^0.35.0" } diff --git a/plugins/permission-node/CHANGELOG.md b/plugins/permission-node/CHANGELOG.md new file mode 100644 index 0000000000..64af0e353b --- /dev/null +++ b/plugins/permission-node/CHANGELOG.md @@ -0,0 +1,25 @@ +# @backstage/plugin-permission-node + +## 0.2.0 + +### Minor Changes + +- e7851efa9e: Rename and adjust permission policy return type to reduce nesting +- 450ca92330: Change route used for integration between the authorization framework and other plugin backends to use the /.well-known prefix. + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-auth-backend@0.4.10 + +## 0.1.0 + +### Minor Changes + +- 44b46644d9: New package containing common permission and authorization utilities for backend plugins. For more information, see the [authorization PRFC](https://github.com/backstage/backstage/pull/7761). + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-auth-backend@0.4.9 + - @backstage/plugin-permission-common@0.2.0 diff --git a/plugins/permission-node/api-report.md b/plugins/permission-node/api-report.md index e5fe9a7087..75c45a9250 100644 --- a/plugins/permission-node/api-report.md +++ b/plugins/permission-node/api-report.md @@ -32,13 +32,11 @@ export type Condition = TRule extends PermissionRule< : never; // @public -export type ConditionalPolicyResult = { +export type ConditionalPolicyDecision = { result: AuthorizeResult.CONDITIONAL; - conditions: { - pluginId: string; - resourceType: string; - conditions: PermissionCriteria; - }; + pluginId: string; + resourceType: string; + conditions: PermissionCriteria; }; // @public @@ -63,11 +61,9 @@ export const createConditionExports: < rules: TRules; }) => { conditions: Conditions; - createConditions: (conditions: PermissionCriteria) => { - pluginId: string; - resourceType: string; - conditions: PermissionCriteria; - }; + createPolicyDecision: ( + conditions: PermissionCriteria, + ) => ConditionalPolicyDecision; }; // @public @@ -103,7 +99,7 @@ export interface PermissionPolicy { handle( request: PolicyAuthorizeRequest, user?: BackstageIdentity, - ): Promise; + ): Promise; } // @public @@ -122,9 +118,9 @@ export type PermissionRule< export type PolicyAuthorizeRequest = Omit; // @public -export type PolicyResult = +export type PolicyDecision = | { result: AuthorizeResult.ALLOW | AuthorizeResult.DENY; } - | ConditionalPolicyResult; + | ConditionalPolicyDecision; ``` diff --git a/plugins/permission-node/package.json b/plugins/permission-node/package.json index e22e2d2de4..1a3d3688d1 100644 --- a/plugins/permission-node/package.json +++ b/plugins/permission-node/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-permission-node", "description": "Common permission and authorization utilities for backend plugins", - "version": "0.0.0", + "version": "0.2.0", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -29,14 +29,14 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/plugin-auth-backend": "^0.4.6", - "@backstage/plugin-permission-common": "^0.1.0", + "@backstage/plugin-auth-backend": "^0.4.10", + "@backstage/plugin-permission-common": "^0.2.0", "@types/express": "^4.17.6", "express": "^4.17.1", "zod": "^3.11.6" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/supertest": "^2.0.8", "supertest": "^6.1.3" }, diff --git a/plugins/permission-node/src/integration/createConditionExports.test.ts b/plugins/permission-node/src/integration/createConditionExports.test.ts index 6f0f8f8632..f3585d11ad 100644 --- a/plugins/permission-node/src/integration/createConditionExports.test.ts +++ b/plugins/permission-node/src/integration/createConditionExports.test.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +import { AuthorizeResult } from '@backstage/plugin-permission-common'; import { createConditionExports } from './createConditionExports'; const testIntegration = () => @@ -61,13 +62,16 @@ describe('createConditionExports', () => { }); }); - describe('createConditions', () => { + describe('createPolicyDecisions', () => { it('wraps conditions in an object with resourceType and pluginId', () => { - const { createConditions } = testIntegration(); + const { createPolicyDecision } = testIntegration(); expect( - createConditions({ allOf: [{ rule: 'testRule1', params: ['a', 1] }] }), + createPolicyDecision({ + allOf: [{ rule: 'testRule1', params: ['a', 1] }], + }), ).toEqual({ + result: AuthorizeResult.CONDITIONAL, pluginId: 'test-plugin', resourceType: 'test-resource', conditions: { diff --git a/plugins/permission-node/src/integration/createConditionExports.ts b/plugins/permission-node/src/integration/createConditionExports.ts index 30cff6628a..fd351128ed 100644 --- a/plugins/permission-node/src/integration/createConditionExports.ts +++ b/plugins/permission-node/src/integration/createConditionExports.ts @@ -15,9 +15,11 @@ */ import { + AuthorizeResult, PermissionCondition, PermissionCriteria, } from '@backstage/plugin-permission-common'; +import { ConditionalPolicyDecision } from '../policy'; import { PermissionRule } from '../types'; import { createConditionFactory } from './createConditionFactory'; @@ -73,11 +75,9 @@ export const createConditionExports = < rules: TRules; }): { conditions: Conditions; - createConditions: (conditions: PermissionCriteria) => { - pluginId: string; - resourceType: string; - conditions: PermissionCriteria; - }; + createPolicyDecision: ( + conditions: PermissionCriteria, + ) => ConditionalPolicyDecision; } => { const { pluginId, resourceType, rules } = options; @@ -89,9 +89,10 @@ export const createConditionExports = < }), {} as Conditions, ), - createConditions: ( + createPolicyDecision: ( conditions: PermissionCriteria, ) => ({ + result: AuthorizeResult.CONDITIONAL, pluginId, resourceType, conditions, diff --git a/plugins/permission-node/src/integration/createPermissionIntegrationRouter.test.ts b/plugins/permission-node/src/integration/createPermissionIntegrationRouter.test.ts index af216dfcb8..15c9cf4003 100644 --- a/plugins/permission-node/src/integration/createPermissionIntegrationRouter.test.ts +++ b/plugins/permission-node/src/integration/createPermissionIntegrationRouter.test.ts @@ -61,7 +61,7 @@ describe('createPermissionIntegrationRouter', () => { expect(router).toBeDefined(); }); - describe('POST /permissions/apply-conditions', () => { + describe('POST /.well-known/backstage/permissions/apply-conditions', () => { it.each([ { rule: 'test-rule-1', params: ['abc', 123] }, { @@ -94,7 +94,7 @@ describe('createPermissionIntegrationRouter', () => { }, ])('returns 200/ALLOW when criteria match (case %#)', async conditions => { const response = await request(app) - .post('/permissions/apply-conditions') + .post('/.well-known/backstage/permissions/apply-conditions') .send({ resourceRef: 'default:test/resource', resourceType: 'test-resource', @@ -135,7 +135,7 @@ describe('createPermissionIntegrationRouter', () => { 'returns 200/DENY when criteria do not match (case %#)', async conditions => { const response = await request(app) - .post('/permissions/apply-conditions') + .post('/.well-known/backstage/permissions/apply-conditions') .send({ resourceRef: 'default:test/resource', resourceType: 'test-resource', @@ -149,7 +149,7 @@ describe('createPermissionIntegrationRouter', () => { it('returns 400 when called with incorrect resource type', async () => { const response = await request(app) - .post('/permissions/apply-conditions') + .post('/.well-known/backstage/permissions/apply-conditions') .send({ resourceRef: 'default:test/resource', resourceType: 'test-incorrect-resource', @@ -168,7 +168,7 @@ describe('createPermissionIntegrationRouter', () => { mockGetResource.mockReturnValueOnce(Promise.resolve(undefined)); const response = await request(app) - .post('/permissions/apply-conditions') + .post('/.well-known/backstage/permissions/apply-conditions') .send({ resourceRef: 'default:test/resource', resourceType: 'test-resource', @@ -198,7 +198,7 @@ describe('createPermissionIntegrationRouter', () => { { conditions: { anyOf: [] } }, ])(`returns 400 for invalid input %#`, async input => { const response = await request(app) - .post('/permissions/apply-conditions') + .post('/.well-known/backstage/permissions/apply-conditions') .send(input); expect(response.status).toEqual(400); diff --git a/plugins/permission-node/src/integration/createPermissionIntegrationRouter.ts b/plugins/permission-node/src/integration/createPermissionIntegrationRouter.ts index 99e282b144..70b72fef7e 100644 --- a/plugins/permission-node/src/integration/createPermissionIntegrationRouter.ts +++ b/plugins/permission-node/src/integration/createPermissionIntegrationRouter.ts @@ -132,7 +132,7 @@ export const createPermissionIntegrationRouter = ({ const getRule = createGetRule(rules); router.post( - '/permissions/apply-conditions', + '/.well-known/backstage/permissions/apply-conditions', express.json(), async ( req, diff --git a/plugins/permission-node/src/policy/index.ts b/plugins/permission-node/src/policy/index.ts index f04c2a094c..c8216989a1 100644 --- a/plugins/permission-node/src/policy/index.ts +++ b/plugins/permission-node/src/policy/index.ts @@ -15,8 +15,8 @@ */ export type { - ConditionalPolicyResult, + ConditionalPolicyDecision, PermissionPolicy, PolicyAuthorizeRequest, - PolicyResult, + PolicyDecision, } from './types'; diff --git a/plugins/permission-node/src/policy/types.ts b/plugins/permission-node/src/policy/types.ts index 44380bad26..3548d051f6 100644 --- a/plugins/permission-node/src/policy/types.ts +++ b/plugins/permission-node/src/policy/types.ts @@ -48,13 +48,11 @@ export type PolicyAuthorizeRequest = Omit; * identifiers needed to evaluate the returned conditions. * @public */ -export type ConditionalPolicyResult = { +export type ConditionalPolicyDecision = { result: AuthorizeResult.CONDITIONAL; - conditions: { - pluginId: string; - resourceType: string; - conditions: PermissionCriteria; - }; + pluginId: string; + resourceType: string; + conditions: PermissionCriteria; }; /** @@ -62,9 +60,9 @@ export type ConditionalPolicyResult = { * * @public */ -export type PolicyResult = +export type PolicyDecision = | { result: AuthorizeResult.ALLOW | AuthorizeResult.DENY } - | ConditionalPolicyResult; + | ConditionalPolicyDecision; /** * A policy to evaluate authorization requests for any permissioned action performed in Backstage. @@ -86,5 +84,5 @@ export interface PermissionPolicy { handle( request: PolicyAuthorizeRequest, user?: BackstageIdentity, - ): Promise; + ): Promise; } diff --git a/packages/test-utils-core/.eslintrc.js b/plugins/permission-react/.eslintrc.js similarity index 100% rename from packages/test-utils-core/.eslintrc.js rename to plugins/permission-react/.eslintrc.js diff --git a/plugins/permission-react/CHANGELOG.md b/plugins/permission-react/CHANGELOG.md new file mode 100644 index 0000000000..9592985354 --- /dev/null +++ b/plugins/permission-react/CHANGELOG.md @@ -0,0 +1,14 @@ +# @backstage/plugin-permission-react + +## 0.1.0 + +### Minor Changes + +- 6ed24445a9: Add @backstage/plugin-permission-react + + @backstage/plugin-permission-react is a library containing utils for implementing permissions in your frontend Backstage plugins. See [the authorization PRFC](https://github.com/backstage/backstage/pull/7761) for more details. + +### Patch Changes + +- Updated dependencies + - @backstage/core-plugin-api@0.2.2 diff --git a/plugins/permission-react/README.md b/plugins/permission-react/README.md new file mode 100644 index 0000000000..72383f024d --- /dev/null +++ b/plugins/permission-react/README.md @@ -0,0 +1,5 @@ +# permission + +**NOTE: THIS PACKAGE IS EXPERIMENTAL!** + +Components and hooks to help implement permissions in Backstage frontend plugins. For more information, see the [authorization PRFC](https://github.com/backstage/backstage/pull/7761). diff --git a/plugins/permission-react/api-report.md b/plugins/permission-react/api-report.md new file mode 100644 index 0000000000..65f93de8a0 --- /dev/null +++ b/plugins/permission-react/api-report.md @@ -0,0 +1,69 @@ +## API Report File for "@backstage/plugin-permission-react" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts +import { ApiRef } from '@backstage/core-plugin-api'; +import { AuthorizeRequest } from '@backstage/plugin-permission-common'; +import { AuthorizeResponse } from '@backstage/plugin-permission-common'; +import { Config } from '@backstage/config'; +import { DiscoveryApi } from '@backstage/core-plugin-api'; +import { IdentityApi } from '@backstage/core-plugin-api'; +import { Permission } from '@backstage/plugin-permission-common'; +import { default as React_2 } from 'react'; +import { RouteProps } from 'react-router'; + +// @public (undocumented) +export type AsyncPermissionResult = { + loading: boolean; + allowed: boolean; + error?: Error; +}; + +// @public +export class IdentityPermissionApi implements PermissionApi { + // (undocumented) + authorize(request: AuthorizeRequest): Promise; + // (undocumented) + static create({ + configApi, + discoveryApi, + identityApi, + }: { + configApi: Config; + discoveryApi: DiscoveryApi; + identityApi: IdentityApi; + }): IdentityPermissionApi; +} + +// @public +export type PermissionApi = { + authorize(request: AuthorizeRequest): Promise; +}; + +// @public +export const permissionApiRef: ApiRef; + +// @public +export const PermissionedRoute: ({ + permission, + resourceRef, + errorComponent, + ...props +}: RouteProps & { + permission: Permission; + resourceRef?: string | undefined; + errorComponent?: + | React_2.ReactElement> + | null + | undefined; +}) => JSX.Element; + +// @public +export const usePermission: ( + permission: Permission, + resourceRef?: string | undefined, +) => AsyncPermissionResult; + +// (No @packageDocumentation comment for this package) +``` diff --git a/plugins/permission-react/package.json b/plugins/permission-react/package.json new file mode 100644 index 0000000000..26c5f71da0 --- /dev/null +++ b/plugins/permission-react/package.json @@ -0,0 +1,49 @@ +{ + "name": "@backstage/plugin-permission-react", + "version": "0.1.0", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + "publishConfig": { + "access": "public", + "main": "dist/index.esm.js", + "types": "dist/index.d.ts" + }, + "homepage": "https://backstage.io", + "repository": { + "type": "git", + "url": "https://github.com/backstage/backstage", + "directory": "plugins/permission-react" + }, + "keywords": [ + "backstage" + ], + "scripts": { + "build": "backstage-cli build", + "lint": "backstage-cli lint", + "test": "backstage-cli test", + "prepack": "backstage-cli prepack", + "postpack": "backstage-cli postpack", + "clean": "backstage-cli clean" + }, + "dependencies": { + "@backstage/config": "^0.1.11", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/plugin-permission-common": "^0.2.0", + "@types/react": "*", + "cross-fetch": "^3.0.6", + "react": "^16.13.1", + "react-router": "6.0.0-beta.0", + "react-use": "^17.2.4" + }, + "devDependencies": { + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.22", + "@testing-library/jest-dom": "^5.10.1", + "@testing-library/react": "^11.2.5", + "@types/jest": "^26.0.7" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/permission-react/src/apis/IdentityPermissionApi.ts b/plugins/permission-react/src/apis/IdentityPermissionApi.ts new file mode 100644 index 0000000000..a68060a61d --- /dev/null +++ b/plugins/permission-react/src/apis/IdentityPermissionApi.ts @@ -0,0 +1,56 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { DiscoveryApi, IdentityApi } from '@backstage/core-plugin-api'; +import { PermissionApi } from './PermissionApi'; +import { + AuthorizeRequest, + AuthorizeResponse, + PermissionClient, +} from '@backstage/plugin-permission-common'; +import { Config } from '@backstage/config'; + +/** + * The default implementation of the PermissionApi, which simply calls the authorize method of the given + * {@link @backstage/plugin-permission-common#PermissionClient}. + * @public + */ +export class IdentityPermissionApi implements PermissionApi { + private constructor( + private readonly permissionClient: PermissionClient, + private readonly identityApi: IdentityApi, + ) {} + + static create({ + configApi, + discoveryApi, + identityApi, + }: { + configApi: Config; + discoveryApi: DiscoveryApi; + identityApi: IdentityApi; + }) { + const permissionClient = new PermissionClient({ discoveryApi, configApi }); + return new IdentityPermissionApi(permissionClient, identityApi); + } + + async authorize(request: AuthorizeRequest): Promise { + const response = await this.permissionClient.authorize([request], { + token: await this.identityApi.getIdToken(), + }); + return response[0]; + } +} diff --git a/plugins/permission-react/src/apis/PermissionApi.ts b/plugins/permission-react/src/apis/PermissionApi.ts new file mode 100644 index 0000000000..5c224ff06d --- /dev/null +++ b/plugins/permission-react/src/apis/PermissionApi.ts @@ -0,0 +1,40 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + AuthorizeRequest, + AuthorizeResponse, +} from '@backstage/plugin-permission-common'; +import { ApiRef, createApiRef } from '@backstage/core-plugin-api'; + +/** + * This API is used by various frontend utilities that allow developers to implement authorization wihtin their frontend + * plugins. A plugin developer will likely not have to interact with this API or its implementations directly, but + * rather with the aforementioned utility components/hooks. + * @public + */ +export type PermissionApi = { + authorize(request: AuthorizeRequest): Promise; +}; + +/** + * A Backstage ApiRef for the Permission API. See https://backstage.io/docs/api/utility-apis for more information on + * Backstage ApiRefs. + * @public + */ +export const permissionApiRef: ApiRef = createApiRef({ + id: 'plugin.permission.api', +}); diff --git a/plugins/permission-react/src/apis/index.ts b/plugins/permission-react/src/apis/index.ts new file mode 100644 index 0000000000..223339f891 --- /dev/null +++ b/plugins/permission-react/src/apis/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { permissionApiRef } from './PermissionApi'; +export type { PermissionApi } from './PermissionApi'; +export { IdentityPermissionApi } from './IdentityPermissionApi'; diff --git a/plugins/permission-react/src/components/PermissionedRoute.test.tsx b/plugins/permission-react/src/components/PermissionedRoute.test.tsx new file mode 100644 index 0000000000..3d7d1b7af7 --- /dev/null +++ b/plugins/permission-react/src/components/PermissionedRoute.test.tsx @@ -0,0 +1,87 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PermissionedRoute } from '.'; +import { usePermission } from '../hooks'; +import { renderInTestApp } from '@backstage/test-utils'; + +jest.mock('../hooks', () => ({ + usePermission: jest.fn(), +})); +const mockUsePermission = usePermission as jest.MockedFunction< + typeof usePermission +>; + +const permission = { + name: 'access.something', + attributes: { action: 'read' as const }, +}; + +describe('PermissionedRoute', () => { + it('Does not render when loading', async () => { + mockUsePermission.mockReturnValue({ loading: true, allowed: false }); + + const { queryByText } = await renderInTestApp( + content} + />, + ); + + expect(queryByText('content')).not.toBeTruthy(); + }); + + it('Renders given element if authorized', async () => { + mockUsePermission.mockReturnValue({ loading: false, allowed: true }); + + const { getByText } = await renderInTestApp( + content} + />, + ); + + expect(getByText('content')).toBeTruthy(); + }); + + it('Renders not found page if not authorized', async () => { + mockUsePermission.mockReturnValue({ loading: false, allowed: false }); + + await expect( + renderInTestApp( + content} + />, + ), + ).rejects.toThrowError('Reached NotFound Page'); + }); + + it('Renders custom error page if not authorized', async () => { + mockUsePermission.mockReturnValue({ loading: false, allowed: false }); + + const { getByText } = await renderInTestApp( + content} + errorComponent={

Custom Error

} + />, + ); + + expect(getByText('Custom Error')).toBeTruthy(); + }); +}); diff --git a/plugins/permission-react/src/components/PermissionedRoute.tsx b/plugins/permission-react/src/components/PermissionedRoute.tsx new file mode 100644 index 0000000000..1a3668205b --- /dev/null +++ b/plugins/permission-react/src/components/PermissionedRoute.tsx @@ -0,0 +1,52 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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, { ComponentProps, ReactElement } from 'react'; +import { Route } from 'react-router'; +import { useApp } from '@backstage/core-plugin-api'; +import { usePermission } from '../hooks'; +import { Permission } from '@backstage/plugin-permission-common'; + +/** + * Returns a React Router Route which only renders the element when authorized. If unathorized, the Route will render a + * NotFoundErrorPage (see {@link @backstage/core-app-api#AppComponents}). + * @public + */ +export const PermissionedRoute = ({ + permission, + resourceRef, + errorComponent, + ...props +}: ComponentProps & { + permission: Permission; + resourceRef?: string; + errorComponent?: ReactElement | null; +}) => { + const permissionResult = usePermission(permission, resourceRef); + const app = useApp(); + const { NotFoundErrorPage } = app.getComponents(); + + let shownElement: ReactElement | null | undefined = + errorComponent === undefined ? : errorComponent; + + if (permissionResult.loading) { + shownElement = null; + } else if (permissionResult.allowed) { + shownElement = props.element; + } + + return ; +}; diff --git a/plugins/permission-react/src/components/index.ts b/plugins/permission-react/src/components/index.ts new file mode 100644 index 0000000000..05f13bca81 --- /dev/null +++ b/plugins/permission-react/src/components/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { PermissionedRoute } from './PermissionedRoute'; diff --git a/plugins/permission-react/src/hooks/index.ts b/plugins/permission-react/src/hooks/index.ts new file mode 100644 index 0000000000..5fca80b89e --- /dev/null +++ b/plugins/permission-react/src/hooks/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { usePermission } from './usePermission'; +export type { AsyncPermissionResult } from './usePermission'; diff --git a/plugins/permission-react/src/hooks/usePermission.test.tsx b/plugins/permission-react/src/hooks/usePermission.test.tsx new file mode 100644 index 0000000000..4cf0bc6530 --- /dev/null +++ b/plugins/permission-react/src/hooks/usePermission.test.tsx @@ -0,0 +1,87 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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, { FC } from 'react'; +import { render } from '@testing-library/react'; +import { usePermission } from './usePermission'; +import { AuthorizeResult } from '@backstage/plugin-permission-common'; +import { TestApiProvider } from '@backstage/test-utils'; +import { permissionApiRef } from '../apis'; + +const mockAuthorize = jest.fn(); + +const permission = { + name: 'access.something', + attributes: { action: 'read' as const }, +}; + +const TestComponent: FC = () => { + const { loading, allowed, error } = usePermission(permission); + return ( +
+ {loading && 'loading'} + {error && 'error'} + {allowed ? 'content' : null} +
+ ); +}; + +describe('usePermission', () => { + it('Returns loading when permissionApi has not yet responded.', () => { + mockAuthorize.mockReturnValueOnce(new Promise(() => {})); + + const { getByText } = render( + + + , + ); + + expect(mockAuthorize).toHaveBeenCalledWith({ permission }); + expect(getByText('loading')).toBeTruthy(); + }); + + it('Returns allowed when permissionApi allows authorization.', async () => { + mockAuthorize.mockResolvedValueOnce({ result: AuthorizeResult.ALLOW }); + + const { findByText } = render( + + + , + ); + + expect(mockAuthorize).toHaveBeenCalledWith({ permission }); + expect(await findByText('content')).toBeTruthy(); + }); + + it('Returns not allowed when permissionApi denies authorization.', async () => { + mockAuthorize.mockResolvedValueOnce({ result: AuthorizeResult.DENY }); + + const { findByText } = render( + + + , + ); + + expect(mockAuthorize).toHaveBeenCalledWith({ permission }); + await expect(findByText('content')).rejects.toThrowError(); + }); +}); diff --git a/plugins/permission-react/src/hooks/usePermission.ts b/plugins/permission-react/src/hooks/usePermission.ts new file mode 100644 index 0000000000..129904d7df --- /dev/null +++ b/plugins/permission-react/src/hooks/usePermission.ts @@ -0,0 +1,60 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { useAsync } from 'react-use'; +import { useApi } from '@backstage/core-plugin-api'; +import { permissionApiRef } from '../apis'; +import { + AuthorizeResult, + Permission, +} from '@backstage/plugin-permission-common'; + +/** @public */ +export type AsyncPermissionResult = { + loading: boolean; + allowed: boolean; + error?: Error; +}; + +/** + * React hook utlity for authorization. Given a {@link @backstage/plugin-permission-common#Permission} and an optional + * resourceRef, it will return whether or not access is allowed (for the given resource, if resourceRef is provided). See + * {@link @backstage/plugin-permission-common/PermissionClient#authorize} for more details. + * @public + */ +export const usePermission = ( + permission: Permission, + resourceRef?: string, +): AsyncPermissionResult => { + const permissionApi = useApi(permissionApiRef); + + const { loading, error, value } = useAsync(async () => { + const { result } = await permissionApi.authorize({ + permission, + resourceRef, + }); + + return result; + }, [permissionApi, permission, resourceRef]); + + if (loading) { + return { loading: true, allowed: false }; + } + if (error) { + return { error, loading: false, allowed: false }; + } + return { loading: false, allowed: value === AuthorizeResult.ALLOW }; +}; diff --git a/plugins/permission-react/src/index.ts b/plugins/permission-react/src/index.ts new file mode 100644 index 0000000000..57352c5cdd --- /dev/null +++ b/plugins/permission-react/src/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 './components'; +export * from './hooks'; +export * from './apis'; diff --git a/plugins/permission-react/src/setupTests.ts b/plugins/permission-react/src/setupTests.ts new file mode 100644 index 0000000000..992b60d3a4 --- /dev/null +++ b/plugins/permission-react/src/setupTests.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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/proxy-backend/CHANGELOG.md b/plugins/proxy-backend/CHANGELOG.md index a7408c161f..57b3441fa5 100644 --- a/plugins/proxy-backend/CHANGELOG.md +++ b/plugins/proxy-backend/CHANGELOG.md @@ -1,5 +1,26 @@ # @backstage/plugin-proxy-backend +## 0.2.14 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/backend-common@0.9.11 + ## 0.2.13 ### Patch Changes diff --git a/plugins/proxy-backend/package.json b/plugins/proxy-backend/package.json index 05499d88e8..68be26391e 100644 --- a/plugins/proxy-backend/package.json +++ b/plugins/proxy-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-proxy-backend", "description": "A Backstage backend plugin that helps you set up proxy endpoints in the backend", - "version": "0.2.13", + "version": "0.2.14", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -29,7 +29,7 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/config": "^0.1.8", "@types/express": "^4.17.6", "express": "^4.17.1", @@ -43,7 +43,7 @@ "yup": "^0.32.9" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/http-proxy-middleware": "^0.19.3", "@types/supertest": "^2.0.8", "@types/uuid": "^8.0.0", diff --git a/plugins/rollbar-backend/CHANGELOG.md b/plugins/rollbar-backend/CHANGELOG.md index d2bc07ab7e..9c0f70ea6a 100644 --- a/plugins/rollbar-backend/CHANGELOG.md +++ b/plugins/rollbar-backend/CHANGELOG.md @@ -1,5 +1,26 @@ # @backstage/plugin-rollbar-backend +## 0.1.16 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/backend-common@0.9.11 + ## 0.1.15 ### Patch Changes diff --git a/plugins/rollbar-backend/package.json b/plugins/rollbar-backend/package.json index be8b6e65e5..96c1002e5e 100644 --- a/plugins/rollbar-backend/package.json +++ b/plugins/rollbar-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-rollbar-backend", "description": "A Backstage backend plugin that integrates towards Rollbar", - "version": "0.1.15", + "version": "0.1.16", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -31,7 +31,7 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/config": "^0.1.10", "@types/express": "^4.17.6", "axios": "^0.21.1", @@ -48,7 +48,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/supertest": "^2.0.8", "supertest": "^6.1.3" }, diff --git a/plugins/rollbar/package.json b/plugins/rollbar/package.json index ee3fc9f5a6..d71c5e1cfe 100644 --- a/plugins/rollbar/package.json +++ b/plugins/rollbar/package.json @@ -33,10 +33,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -49,10 +49,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/scaffolder-backend-module-cookiecutter/CHANGELOG.md b/plugins/scaffolder-backend-module-cookiecutter/CHANGELOG.md index 43a522482f..b177521d8b 100644 --- a/plugins/scaffolder-backend-module-cookiecutter/CHANGELOG.md +++ b/plugins/scaffolder-backend-module-cookiecutter/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/plugin-scaffolder-backend-module-cookiecutter +## 0.1.5 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/plugin-scaffolder-backend@0.15.15 + - @backstage/backend-common@0.9.12 + ## 0.1.4 ### Patch Changes diff --git a/plugins/scaffolder-backend-module-cookiecutter/package.json b/plugins/scaffolder-backend-module-cookiecutter/package.json index 90258d3c28..bff3f49c83 100644 --- a/plugins/scaffolder-backend-module-cookiecutter/package.json +++ b/plugins/scaffolder-backend-module-cookiecutter/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-scaffolder-backend-module-cookiecutter", "description": "A module for the scaffolder backend that lets you template projects using cookiecutter", - "version": "0.1.4", + "version": "0.1.5", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -20,20 +20,19 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", - "@backstage/plugin-scaffolder-backend": "^0.15.13", + "@backstage/integration": "^0.6.10", + "@backstage/plugin-scaffolder-backend": "^0.15.15", "@backstage/config": "^0.1.11", "@backstage/types": "^0.1.1", "command-exists": "^1.2.9", "fs-extra": "10.0.0", "winston": "^3.2.1", - "cross-fetch": "^3.0.6", "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/fs-extra": "^9.0.1", "@types/mock-fs": "^4.13.0", "@types/jest": "^26.0.7", diff --git a/plugins/scaffolder-backend-module-rails/package.json b/plugins/scaffolder-backend-module-rails/package.json index 37b077568e..cac3d7ea9b 100644 --- a/plugins/scaffolder-backend-module-rails/package.json +++ b/plugins/scaffolder-backend-module-rails/package.json @@ -21,17 +21,17 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", - "@backstage/plugin-scaffolder-backend": "^0.15.13", + "@backstage/backend-common": "^0.9.12", + "@backstage/plugin-scaffolder-backend": "^0.15.15", "@backstage/config": "^0.1.11", "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", + "@backstage/integration": "^0.6.10", "@backstage/types": "^0.1.1", "command-exists": "^1.2.9", "fs-extra": "^9.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/jest": "^26.0.7", "@types/node": "^14.14.32", "@types/command-exists": "^1.2.0", diff --git a/plugins/scaffolder-backend/.eslintrc.js b/plugins/scaffolder-backend/.eslintrc.js index 19c9ad7395..2632b5e089 100644 --- a/plugins/scaffolder-backend/.eslintrc.js +++ b/plugins/scaffolder-backend/.eslintrc.js @@ -1,8 +1,41 @@ +const parent = require('@backstage/cli/config/eslint.backend'); + module.exports = { extends: [require.resolve('@backstage/cli/config/eslint.backend')], ignorePatterns: ['sample-templates/'], rules: { 'no-console': 0, // Permitted in console programs 'new-cap': ['error', { capIsNew: false }], // Because Express constructs things e.g. like 'const r = express.Router()' + // Usage of path.resolve is extra sensitive in the scaffolder, so forbid it in non-test code + 'no-restricted-imports': [ + 'error', + { + ...parent.rules['no-restricted-imports'][1], + paths: [ + { + name: 'path', + importNames: ['resolve'], + message: + 'Do not use path.resolve, use `resolveSafeChildPath` from `@backstage/backend-common` instead as it prevents security issues', + }, + ], + }, + ], + 'no-restricted-syntax': parent.rules['no-restricted-syntax'].concat([ + { + message: + 'Do not use path.resolve, use `resolveSafeChildPath` from `@backstage/backend-common` instead as it prevents security issues', + selector: + 'MemberExpression[object.name="path"][property.name="resolve"]', + }, + ]), }, + overrides: [ + { + files: ['*.test.*', 'src/setupTests.*', 'dev/**'], + rules: { + 'no-restricted-imports': parent.rules['no-restricted-imports'], + }, + }, + ], }; diff --git a/plugins/scaffolder-backend/CHANGELOG.md b/plugins/scaffolder-backend/CHANGELOG.md index f71849a1d2..3b0add9cd6 100644 --- a/plugins/scaffolder-backend/CHANGELOG.md +++ b/plugins/scaffolder-backend/CHANGELOG.md @@ -1,5 +1,31 @@ # @backstage/plugin-scaffolder-backend +## 0.15.15 + +### Patch Changes + +- 0398ea25d3: Removed unused scaffolder visibility configuration; this has been moved to publish actions. Deprecated scaffolder provider configuration keys; these should use the integrations configuration instead. +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- c6b44d80ad: Add options to spawn in runCommand helper +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/plugin-catalog-backend@0.19.0 + - @backstage/plugin-scaffolder-backend-module-cookiecutter@0.1.5 + - @backstage/backend-common@0.9.12 + +## 0.15.14 + +### Patch Changes + +- a096e4c4d7: Switched to executing scaffolder templating in a secure context for any template based on nunjucks, as it is [not secure by default](https://mozilla.github.io/nunjucks/api.html#user-defined-templates-warning). +- f9352ab606: Removed all usages of `path.resolve` in order to ensure that template paths are resolved in a safe way. +- e634a47ce5: Fix bug where there was error log lines written when failing to `JSON.parse` things that were not `JSON` values. +- 42ebbc18c0: Bump gitbeaker to the latest version +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/plugin-catalog-backend@0.18.0 + - @backstage/backend-common@0.9.11 + ## 0.15.13 ### Patch Changes diff --git a/plugins/scaffolder-backend/api-report.md b/plugins/scaffolder-backend/api-report.md index 4b27b938c9..6ed4625f66 100644 --- a/plugins/scaffolder-backend/api-report.md +++ b/plugins/scaffolder-backend/api-report.md @@ -24,6 +24,7 @@ import { PluginDatabaseManager } from '@backstage/backend-common'; import { Schema } from 'jsonschema'; import { ScmIntegrationRegistry } from '@backstage/integration'; import { ScmIntegrations } from '@backstage/integration'; +import { SpawnOptionsWithoutStdio } from 'child_process'; import { TemplateEntityV1beta2 } from '@backstage/catalog-model'; import { UrlReader } from '@backstage/backend-common'; import { Writable } from 'stream'; @@ -304,11 +305,12 @@ export interface RouterOptions { // Warning: (ae-forgotten-export) The symbol "RunCommandOptions" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "runCommand" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // -// @public (undocumented) +// @public export const runCommand: ({ command, args, logStream, + options, }: RunCommandOptions) => Promise; // @public (undocumented) diff --git a/plugins/scaffolder-backend/assets/nunjucks.js.txt b/plugins/scaffolder-backend/assets/nunjucks.js.txt new file mode 100644 index 0000000000..b78d1d98ac --- /dev/null +++ b/plugins/scaffolder-backend/assets/nunjucks.js.txt @@ -0,0 +1,10385 @@ + +/** + * Copyright (c) 2012-2015, James Long + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var __commonJS = (callback, module2) => () => { + if (!module2) { + module2 = {exports: {}}; + callback(module2.exports, module2); + } + return module2.exports; +}; + +// ../../node_modules/nunjucks/src/lib.js +var require_lib = __commonJS((exports2, module2) => { + "use strict"; + var ArrayProto = Array.prototype; + var ObjProto = Object.prototype; + var escapeMap = { + "&": "&", + '"': """, + "'": "'", + "<": "<", + ">": ">" + }; + var escapeRegex = /[&"'<>]/g; + var _exports = module2.exports = {}; + function hasOwnProp(obj, k) { + return ObjProto.hasOwnProperty.call(obj, k); + } + _exports.hasOwnProp = hasOwnProp; + function lookupEscape(ch) { + return escapeMap[ch]; + } + function _prettifyError(path, withInternals, err) { + if (!err.Update) { + err = new _exports.TemplateError(err); + } + err.Update(path); + if (!withInternals) { + var old = err; + err = new Error(old.message); + err.name = old.name; + } + return err; + } + _exports._prettifyError = _prettifyError; + function TemplateError(message, lineno, colno) { + var err; + var cause; + if (message instanceof Error) { + cause = message; + message = cause.name + ": " + cause.message; + } + if (Object.setPrototypeOf) { + err = new Error(message); + Object.setPrototypeOf(err, TemplateError.prototype); + } else { + err = this; + Object.defineProperty(err, "message", { + enumerable: false, + writable: true, + value: message + }); + } + Object.defineProperty(err, "name", { + value: "Template render error" + }); + if (Error.captureStackTrace) { + Error.captureStackTrace(err, this.constructor); + } + var getStack; + if (cause) { + var stackDescriptor = Object.getOwnPropertyDescriptor(cause, "stack"); + getStack = stackDescriptor && (stackDescriptor.get || function() { + return stackDescriptor.value; + }); + if (!getStack) { + getStack = function getStack2() { + return cause.stack; + }; + } + } else { + var stack = new Error(message).stack; + getStack = function getStack2() { + return stack; + }; + } + Object.defineProperty(err, "stack", { + get: function get() { + return getStack.call(err); + } + }); + Object.defineProperty(err, "cause", { + value: cause + }); + err.lineno = lineno; + err.colno = colno; + err.firstUpdate = true; + err.Update = function Update(path) { + var msg = "(" + (path || "unknown path") + ")"; + if (this.firstUpdate) { + if (this.lineno && this.colno) { + msg += " [Line " + this.lineno + ", Column " + this.colno + "]"; + } else if (this.lineno) { + msg += " [Line " + this.lineno + "]"; + } + } + msg += "\n "; + if (this.firstUpdate) { + msg += " "; + } + this.message = msg + (this.message || ""); + this.firstUpdate = false; + return this; + }; + return err; + } + if (Object.setPrototypeOf) { + Object.setPrototypeOf(TemplateError.prototype, Error.prototype); + } else { + TemplateError.prototype = Object.create(Error.prototype, { + constructor: { + value: TemplateError + } + }); + } + _exports.TemplateError = TemplateError; + function escape(val) { + return val.replace(escapeRegex, lookupEscape); + } + _exports.escape = escape; + function isFunction(obj) { + return ObjProto.toString.call(obj) === "[object Function]"; + } + _exports.isFunction = isFunction; + function isArray(obj) { + return ObjProto.toString.call(obj) === "[object Array]"; + } + _exports.isArray = isArray; + function isString(obj) { + return ObjProto.toString.call(obj) === "[object String]"; + } + _exports.isString = isString; + function isObject(obj) { + return ObjProto.toString.call(obj) === "[object Object]"; + } + _exports.isObject = isObject; + function _prepareAttributeParts(attr) { + if (!attr) { + return []; + } + if (typeof attr === "string") { + return attr.split("."); + } + return [attr]; + } + function getAttrGetter(attribute) { + var parts = _prepareAttributeParts(attribute); + return function attrGetter(item) { + var _item = item; + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (hasOwnProp(_item, part)) { + _item = _item[part]; + } else { + return void 0; + } + } + return _item; + }; + } + _exports.getAttrGetter = getAttrGetter; + function groupBy(obj, val, throwOnUndefined) { + var result = {}; + var iterator = isFunction(val) ? val : getAttrGetter(val); + for (var i = 0; i < obj.length; i++) { + var value = obj[i]; + var key = iterator(value, i); + if (key === void 0 && throwOnUndefined === true) { + throw new TypeError('groupby: attribute "' + val + '" resolved to undefined'); + } + (result[key] || (result[key] = [])).push(value); + } + return result; + } + _exports.groupBy = groupBy; + function toArray(obj) { + return Array.prototype.slice.call(obj); + } + _exports.toArray = toArray; + function without(array) { + var result = []; + if (!array) { + return result; + } + var length = array.length; + var contains = toArray(arguments).slice(1); + var index = -1; + while (++index < length) { + if (indexOf(contains, array[index]) === -1) { + result.push(array[index]); + } + } + return result; + } + _exports.without = without; + function repeat(char_, n) { + var str = ""; + for (var i = 0; i < n; i++) { + str += char_; + } + return str; + } + _exports.repeat = repeat; + function each(obj, func, context) { + if (obj == null) { + return; + } + if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) { + obj.forEach(func, context); + } else if (obj.length === +obj.length) { + for (var i = 0, l = obj.length; i < l; i++) { + func.call(context, obj[i], i, obj); + } + } + } + _exports.each = each; + function map(obj, func) { + var results = []; + if (obj == null) { + return results; + } + if (ArrayProto.map && obj.map === ArrayProto.map) { + return obj.map(func); + } + for (var i = 0; i < obj.length; i++) { + results[results.length] = func(obj[i], i); + } + if (obj.length === +obj.length) { + results.length = obj.length; + } + return results; + } + _exports.map = map; + function asyncIter(arr, iter, cb) { + var i = -1; + function next() { + i++; + if (i < arr.length) { + iter(arr[i], i, next, cb); + } else { + cb(); + } + } + next(); + } + _exports.asyncIter = asyncIter; + function asyncFor(obj, iter, cb) { + var keys = keys_(obj || {}); + var len = keys.length; + var i = -1; + function next() { + i++; + var k = keys[i]; + if (i < len) { + iter(k, obj[k], i, len, next); + } else { + cb(); + } + } + next(); + } + _exports.asyncFor = asyncFor; + function indexOf(arr, searchElement, fromIndex) { + return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex); + } + _exports.indexOf = indexOf; + function keys_(obj) { + var arr = []; + for (var k in obj) { + if (hasOwnProp(obj, k)) { + arr.push(k); + } + } + return arr; + } + _exports.keys = keys_; + function _entries(obj) { + return keys_(obj).map(function(k) { + return [k, obj[k]]; + }); + } + _exports._entries = _entries; + function _values(obj) { + return keys_(obj).map(function(k) { + return obj[k]; + }); + } + _exports._values = _values; + function extend(obj1, obj2) { + obj1 = obj1 || {}; + keys_(obj2).forEach(function(k) { + obj1[k] = obj2[k]; + }); + return obj1; + } + _exports._assign = _exports.extend = extend; + function inOperator(key, val) { + if (isArray(val) || isString(val)) { + return val.indexOf(key) !== -1; + } else if (isObject(val)) { + return key in val; + } + throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.'); + } + _exports.inOperator = inOperator; +}); + +// ../../node_modules/asap/raw.js +var require_raw = __commonJS((exports2, module2) => { + "use strict"; + var domain; + var hasSetImmediate = typeof setImmediate === "function"; + module2.exports = rawAsap; + function rawAsap(task) { + if (!queue.length) { + requestFlush(); + flushing = true; + } + queue[queue.length] = task; + } + var queue = []; + var flushing = false; + var index = 0; + var capacity = 1024; + function flush() { + while (index < queue.length) { + var currentIndex = index; + index = index + 1; + queue[currentIndex].call(); + if (index > capacity) { + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; + flushing = false; + } + rawAsap.requestFlush = requestFlush; + function requestFlush() { + var parentDomain = process.domain; + if (parentDomain) { + if (!domain) { + domain = require("domain"); + } + domain.active = process.domain = null; + } + if (flushing && hasSetImmediate) { + setImmediate(flush); + } else { + process.nextTick(flush); + } + if (parentDomain) { + domain.active = process.domain = parentDomain; + } + } +}); + +// ../../node_modules/asap/asap.js +var require_asap = __commonJS((exports2, module2) => { + "use strict"; + var rawAsap = require_raw(); + var freeTasks = []; + module2.exports = asap; + function asap(task) { + var rawTask; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); + } + rawTask.task = task; + rawTask.domain = process.domain; + rawAsap(rawTask); + } + function RawTask() { + this.task = null; + this.domain = null; + } + RawTask.prototype.call = function() { + if (this.domain) { + this.domain.enter(); + } + var threw = true; + try { + this.task.call(); + threw = false; + if (this.domain) { + this.domain.exit(); + } + } finally { + if (threw) { + rawAsap.requestFlush(); + } + this.task = null; + this.domain = null; + freeTasks.push(this); + } + }; +}); + +// ../../node_modules/a-sync-waterfall/index.js +var require_a_sync_waterfall = __commonJS((exports2, module2) => { + (function(globals) { + "use strict"; + var executeSync = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === "function") { + args[0].apply(null, args.splice(1)); + } + }; + var executeAsync = function(fn) { + if (typeof setImmediate === "function") { + setImmediate(fn); + } else if (typeof process !== "undefined" && process.nextTick) { + process.nextTick(fn); + } else { + setTimeout(fn, 0); + } + }; + var makeIterator = function(tasks) { + var makeCallback = function(index) { + var fn = function() { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function() { + return index < tasks.length - 1 ? makeCallback(index + 1) : null; + }; + return fn; + }; + return makeCallback(0); + }; + var _isArray = Array.isArray || function(maybeArray) { + return Object.prototype.toString.call(maybeArray) === "[object Array]"; + }; + var waterfall = function(tasks, callback, forceAsync) { + var nextTick = forceAsync ? executeAsync : executeSync; + callback = callback || function() { + }; + if (!_isArray(tasks)) { + var err = new Error("First argument to waterfall must be an array of functions"); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function(iterator) { + return function(err2) { + if (err2) { + callback.apply(null, arguments); + callback = function() { + }; + } else { + var args = Array.prototype.slice.call(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } else { + args.push(callback); + } + nextTick(function() { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(makeIterator(tasks))(); + }; + if (typeof define !== "undefined" && define.amd) { + define([], function() { + return waterfall; + }); + } else if (typeof module2 !== "undefined" && module2.exports) { + module2.exports = waterfall; + } else { + globals.waterfall = waterfall; + } + })(exports2); +}); + +// ../../node_modules/nunjucks/src/lexer.js +var require_lexer = __commonJS((exports2, module2) => { + "use strict"; + var lib2 = require_lib(); + var whitespaceChars = " \n \r\xA0"; + var delimChars = "()[]{}%*-+~/#,:|.<>=!"; + var intChars = "0123456789"; + var BLOCK_START = "{%"; + var BLOCK_END = "%}"; + var VARIABLE_START = "{{"; + var VARIABLE_END = "}}"; + var COMMENT_START = "{#"; + var COMMENT_END = "#}"; + var TOKEN_STRING = "string"; + var TOKEN_WHITESPACE = "whitespace"; + var TOKEN_DATA = "data"; + var TOKEN_BLOCK_START = "block-start"; + var TOKEN_BLOCK_END = "block-end"; + var TOKEN_VARIABLE_START = "variable-start"; + var TOKEN_VARIABLE_END = "variable-end"; + var TOKEN_COMMENT = "comment"; + var TOKEN_LEFT_PAREN = "left-paren"; + var TOKEN_RIGHT_PAREN = "right-paren"; + var TOKEN_LEFT_BRACKET = "left-bracket"; + var TOKEN_RIGHT_BRACKET = "right-bracket"; + var TOKEN_LEFT_CURLY = "left-curly"; + var TOKEN_RIGHT_CURLY = "right-curly"; + var TOKEN_OPERATOR = "operator"; + var TOKEN_COMMA = "comma"; + var TOKEN_COLON = "colon"; + var TOKEN_TILDE = "tilde"; + var TOKEN_PIPE = "pipe"; + var TOKEN_INT = "int"; + var TOKEN_FLOAT = "float"; + var TOKEN_BOOLEAN = "boolean"; + var TOKEN_NONE = "none"; + var TOKEN_SYMBOL = "symbol"; + var TOKEN_SPECIAL = "special"; + var TOKEN_REGEX = "regex"; + function token(type, value, lineno, colno) { + return { + type, + value, + lineno, + colno + }; + } + var Tokenizer = /* @__PURE__ */ function() { + function Tokenizer2(str, opts) { + this.str = str; + this.index = 0; + this.len = str.length; + this.lineno = 0; + this.colno = 0; + this.in_code = false; + opts = opts || {}; + var tags = opts.tags || {}; + this.tags = { + BLOCK_START: tags.blockStart || BLOCK_START, + BLOCK_END: tags.blockEnd || BLOCK_END, + VARIABLE_START: tags.variableStart || VARIABLE_START, + VARIABLE_END: tags.variableEnd || VARIABLE_END, + COMMENT_START: tags.commentStart || COMMENT_START, + COMMENT_END: tags.commentEnd || COMMENT_END + }; + this.trimBlocks = !!opts.trimBlocks; + this.lstripBlocks = !!opts.lstripBlocks; + } + var _proto = Tokenizer2.prototype; + _proto.nextToken = function nextToken() { + var lineno = this.lineno; + var colno = this.colno; + var tok; + if (this.in_code) { + var cur = this.current(); + if (this.isFinished()) { + return null; + } else if (cur === '"' || cur === "'") { + return token(TOKEN_STRING, this._parseString(cur), lineno, colno); + } else if (tok = this._extract(whitespaceChars)) { + return token(TOKEN_WHITESPACE, tok, lineno, colno); + } else if ((tok = this._extractString(this.tags.BLOCK_END)) || (tok = this._extractString("-" + this.tags.BLOCK_END))) { + this.in_code = false; + if (this.trimBlocks) { + cur = this.current(); + if (cur === "\n") { + this.forward(); + } else if (cur === "\r") { + this.forward(); + cur = this.current(); + if (cur === "\n") { + this.forward(); + } else { + this.back(); + } + } + } + return token(TOKEN_BLOCK_END, tok, lineno, colno); + } else if ((tok = this._extractString(this.tags.VARIABLE_END)) || (tok = this._extractString("-" + this.tags.VARIABLE_END))) { + this.in_code = false; + return token(TOKEN_VARIABLE_END, tok, lineno, colno); + } else if (cur === "r" && this.str.charAt(this.index + 1) === "/") { + this.forwardN(2); + var regexBody = ""; + while (!this.isFinished()) { + if (this.current() === "/" && this.previous() !== "\\") { + this.forward(); + break; + } else { + regexBody += this.current(); + this.forward(); + } + } + var POSSIBLE_FLAGS = ["g", "i", "m", "y"]; + var regexFlags = ""; + while (!this.isFinished()) { + var isCurrentAFlag = POSSIBLE_FLAGS.indexOf(this.current()) !== -1; + if (isCurrentAFlag) { + regexFlags += this.current(); + this.forward(); + } else { + break; + } + } + return token(TOKEN_REGEX, { + body: regexBody, + flags: regexFlags + }, lineno, colno); + } else if (delimChars.indexOf(cur) !== -1) { + this.forward(); + var complexOps = ["==", "===", "!=", "!==", "<=", ">=", "//", "**"]; + var curComplex = cur + this.current(); + var type; + if (lib2.indexOf(complexOps, curComplex) !== -1) { + this.forward(); + cur = curComplex; + if (lib2.indexOf(complexOps, curComplex + this.current()) !== -1) { + cur = curComplex + this.current(); + this.forward(); + } + } + switch (cur) { + case "(": + type = TOKEN_LEFT_PAREN; + break; + case ")": + type = TOKEN_RIGHT_PAREN; + break; + case "[": + type = TOKEN_LEFT_BRACKET; + break; + case "]": + type = TOKEN_RIGHT_BRACKET; + break; + case "{": + type = TOKEN_LEFT_CURLY; + break; + case "}": + type = TOKEN_RIGHT_CURLY; + break; + case ",": + type = TOKEN_COMMA; + break; + case ":": + type = TOKEN_COLON; + break; + case "~": + type = TOKEN_TILDE; + break; + case "|": + type = TOKEN_PIPE; + break; + default: + type = TOKEN_OPERATOR; + } + return token(type, cur, lineno, colno); + } else { + tok = this._extractUntil(whitespaceChars + delimChars); + if (tok.match(/^[-+]?[0-9]+$/)) { + if (this.current() === ".") { + this.forward(); + var dec = this._extract(intChars); + return token(TOKEN_FLOAT, tok + "." + dec, lineno, colno); + } else { + return token(TOKEN_INT, tok, lineno, colno); + } + } else if (tok.match(/^(true|false)$/)) { + return token(TOKEN_BOOLEAN, tok, lineno, colno); + } else if (tok === "none") { + return token(TOKEN_NONE, tok, lineno, colno); + } else if (tok === "null") { + return token(TOKEN_NONE, tok, lineno, colno); + } else if (tok) { + return token(TOKEN_SYMBOL, tok, lineno, colno); + } else { + throw new Error("Unexpected value while parsing: " + tok); + } + } + } else { + var beginChars = this.tags.BLOCK_START.charAt(0) + this.tags.VARIABLE_START.charAt(0) + this.tags.COMMENT_START.charAt(0) + this.tags.COMMENT_END.charAt(0); + if (this.isFinished()) { + return null; + } else if ((tok = this._extractString(this.tags.BLOCK_START + "-")) || (tok = this._extractString(this.tags.BLOCK_START))) { + this.in_code = true; + return token(TOKEN_BLOCK_START, tok, lineno, colno); + } else if ((tok = this._extractString(this.tags.VARIABLE_START + "-")) || (tok = this._extractString(this.tags.VARIABLE_START))) { + this.in_code = true; + return token(TOKEN_VARIABLE_START, tok, lineno, colno); + } else { + tok = ""; + var data; + var inComment = false; + if (this._matches(this.tags.COMMENT_START)) { + inComment = true; + tok = this._extractString(this.tags.COMMENT_START); + } + while ((data = this._extractUntil(beginChars)) !== null) { + tok += data; + if ((this._matches(this.tags.BLOCK_START) || this._matches(this.tags.VARIABLE_START) || this._matches(this.tags.COMMENT_START)) && !inComment) { + if (this.lstripBlocks && this._matches(this.tags.BLOCK_START) && this.colno > 0 && this.colno <= tok.length) { + var lastLine = tok.slice(-this.colno); + if (/^\s+$/.test(lastLine)) { + tok = tok.slice(0, -this.colno); + if (!tok.length) { + return this.nextToken(); + } + } + } + break; + } else if (this._matches(this.tags.COMMENT_END)) { + if (!inComment) { + throw new Error("unexpected end of comment"); + } + tok += this._extractString(this.tags.COMMENT_END); + break; + } else { + tok += this.current(); + this.forward(); + } + } + if (data === null && inComment) { + throw new Error("expected end of comment, got end of file"); + } + return token(inComment ? TOKEN_COMMENT : TOKEN_DATA, tok, lineno, colno); + } + } + }; + _proto._parseString = function _parseString(delimiter) { + this.forward(); + var str = ""; + while (!this.isFinished() && this.current() !== delimiter) { + var cur = this.current(); + if (cur === "\\") { + this.forward(); + switch (this.current()) { + case "n": + str += "\n"; + break; + case "t": + str += " "; + break; + case "r": + str += "\r"; + break; + default: + str += this.current(); + } + this.forward(); + } else { + str += cur; + this.forward(); + } + } + this.forward(); + return str; + }; + _proto._matches = function _matches(str) { + if (this.index + str.length > this.len) { + return null; + } + var m = this.str.slice(this.index, this.index + str.length); + return m === str; + }; + _proto._extractString = function _extractString(str) { + if (this._matches(str)) { + this.forwardN(str.length); + return str; + } + return null; + }; + _proto._extractUntil = function _extractUntil(charString) { + return this._extractMatching(true, charString || ""); + }; + _proto._extract = function _extract(charString) { + return this._extractMatching(false, charString); + }; + _proto._extractMatching = function _extractMatching(breakOnMatch, charString) { + if (this.isFinished()) { + return null; + } + var first = charString.indexOf(this.current()); + if (breakOnMatch && first === -1 || !breakOnMatch && first !== -1) { + var t = this.current(); + this.forward(); + var idx = charString.indexOf(this.current()); + while ((breakOnMatch && idx === -1 || !breakOnMatch && idx !== -1) && !this.isFinished()) { + t += this.current(); + this.forward(); + idx = charString.indexOf(this.current()); + } + return t; + } + return ""; + }; + _proto._extractRegex = function _extractRegex(regex) { + var matches = this.currentStr().match(regex); + if (!matches) { + return null; + } + this.forwardN(matches[0].length); + return matches; + }; + _proto.isFinished = function isFinished() { + return this.index >= this.len; + }; + _proto.forwardN = function forwardN(n) { + for (var i = 0; i < n; i++) { + this.forward(); + } + }; + _proto.forward = function forward() { + this.index++; + if (this.previous() === "\n") { + this.lineno++; + this.colno = 0; + } else { + this.colno++; + } + }; + _proto.backN = function backN(n) { + for (var i = 0; i < n; i++) { + this.back(); + } + }; + _proto.back = function back() { + this.index--; + if (this.current() === "\n") { + this.lineno--; + var idx = this.src.lastIndexOf("\n", this.index - 1); + if (idx === -1) { + this.colno = this.index; + } else { + this.colno = this.index - idx; + } + } else { + this.colno--; + } + }; + _proto.current = function current() { + if (!this.isFinished()) { + return this.str.charAt(this.index); + } + return ""; + }; + _proto.currentStr = function currentStr() { + if (!this.isFinished()) { + return this.str.substr(this.index); + } + return ""; + }; + _proto.previous = function previous() { + return this.str.charAt(this.index - 1); + }; + return Tokenizer2; + }(); + module2.exports = { + lex: function lex(src, opts) { + return new Tokenizer(src, opts); + }, + TOKEN_STRING, + TOKEN_WHITESPACE, + TOKEN_DATA, + TOKEN_BLOCK_START, + TOKEN_BLOCK_END, + TOKEN_VARIABLE_START, + TOKEN_VARIABLE_END, + TOKEN_COMMENT, + TOKEN_LEFT_PAREN, + TOKEN_RIGHT_PAREN, + TOKEN_LEFT_BRACKET, + TOKEN_RIGHT_BRACKET, + TOKEN_LEFT_CURLY, + TOKEN_RIGHT_CURLY, + TOKEN_OPERATOR, + TOKEN_COMMA, + TOKEN_COLON, + TOKEN_TILDE, + TOKEN_PIPE, + TOKEN_INT, + TOKEN_FLOAT, + TOKEN_BOOLEAN, + TOKEN_NONE, + TOKEN_SYMBOL, + TOKEN_SPECIAL, + TOKEN_REGEX + }; +}); + +// ../../node_modules/nunjucks/src/object.js +var require_object = __commonJS((exports2, module2) => { + "use strict"; + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + if (staticProps) + _defineProperties(Constructor, staticProps); + return Constructor; + } + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var EventEmitter = require("events"); + var lib2 = require_lib(); + function parentWrap(parent, prop) { + if (typeof parent !== "function" || typeof prop !== "function") { + return prop; + } + return function wrap() { + var tmp = this.parent; + this.parent = parent; + var res = prop.apply(this, arguments); + this.parent = tmp; + return res; + }; + } + function extendClass(cls, name, props) { + props = props || {}; + lib2.keys(props).forEach(function(k) { + props[k] = parentWrap(cls.prototype[k], props[k]); + }); + var subclass = /* @__PURE__ */ function(_cls) { + _inheritsLoose(subclass2, _cls); + function subclass2() { + return _cls.apply(this, arguments) || this; + } + _createClass(subclass2, [{ + key: "typename", + get: function get() { + return name; + } + }]); + return subclass2; + }(cls); + lib2._assign(subclass.prototype, props); + return subclass; + } + var Obj = /* @__PURE__ */ function() { + function Obj2() { + this.init.apply(this, arguments); + } + var _proto = Obj2.prototype; + _proto.init = function init() { + }; + Obj2.extend = function extend(name, props) { + if (typeof name === "object") { + props = name; + name = "anonymous"; + } + return extendClass(this, name, props); + }; + _createClass(Obj2, [{ + key: "typename", + get: function get() { + return this.constructor.name; + } + }]); + return Obj2; + }(); + var EmitterObj = /* @__PURE__ */ function(_EventEmitter) { + _inheritsLoose(EmitterObj2, _EventEmitter); + function EmitterObj2() { + var _this2; + var _this; + _this = _EventEmitter.call(this) || this; + (_this2 = _this).init.apply(_this2, arguments); + return _this; + } + var _proto2 = EmitterObj2.prototype; + _proto2.init = function init() { + }; + EmitterObj2.extend = function extend(name, props) { + if (typeof name === "object") { + props = name; + name = "anonymous"; + } + return extendClass(this, name, props); + }; + _createClass(EmitterObj2, [{ + key: "typename", + get: function get() { + return this.constructor.name; + } + }]); + return EmitterObj2; + }(EventEmitter); + module2.exports = { + Obj, + EmitterObj + }; +}); + +// ../../node_modules/nunjucks/src/nodes.js +var require_nodes = __commonJS((exports2, module2) => { + "use strict"; + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + if (staticProps) + _defineProperties(Constructor, staticProps); + return Constructor; + } + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var _require2 = require_object(); + var Obj = _require2.Obj; + function traverseAndCheck(obj, type, results) { + if (obj instanceof type) { + results.push(obj); + } + if (obj instanceof Node) { + obj.findAll(type, results); + } + } + var Node = /* @__PURE__ */ function(_Obj) { + _inheritsLoose(Node2, _Obj); + function Node2() { + return _Obj.apply(this, arguments) || this; + } + var _proto = Node2.prototype; + _proto.init = function init(lineno, colno) { + var _arguments = arguments, _this = this; + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + this.lineno = lineno; + this.colno = colno; + this.fields.forEach(function(field, i) { + var val = _arguments[i + 2]; + if (val === void 0) { + val = null; + } + _this[field] = val; + }); + }; + _proto.findAll = function findAll(type, results) { + var _this2 = this; + results = results || []; + if (this instanceof NodeList) { + this.children.forEach(function(child) { + return traverseAndCheck(child, type, results); + }); + } else { + this.fields.forEach(function(field) { + return traverseAndCheck(_this2[field], type, results); + }); + } + return results; + }; + _proto.iterFields = function iterFields(func) { + var _this3 = this; + this.fields.forEach(function(field) { + func(_this3[field], field); + }); + }; + return Node2; + }(Obj); + var Value = /* @__PURE__ */ function(_Node) { + _inheritsLoose(Value2, _Node); + function Value2() { + return _Node.apply(this, arguments) || this; + } + _createClass(Value2, [{ + key: "typename", + get: function get() { + return "Value"; + } + }, { + key: "fields", + get: function get() { + return ["value"]; + } + }]); + return Value2; + }(Node); + var NodeList = /* @__PURE__ */ function(_Node2) { + _inheritsLoose(NodeList2, _Node2); + function NodeList2() { + return _Node2.apply(this, arguments) || this; + } + var _proto2 = NodeList2.prototype; + _proto2.init = function init(lineno, colno, nodes2) { + _Node2.prototype.init.call(this, lineno, colno, nodes2 || []); + }; + _proto2.addChild = function addChild(node) { + this.children.push(node); + }; + _createClass(NodeList2, [{ + key: "typename", + get: function get() { + return "NodeList"; + } + }, { + key: "fields", + get: function get() { + return ["children"]; + } + }]); + return NodeList2; + }(Node); + var Root = NodeList.extend("Root"); + var Literal = Value.extend("Literal"); + var Symbol2 = Value.extend("Symbol"); + var Group = NodeList.extend("Group"); + var ArrayNode = NodeList.extend("Array"); + var Pair = Node.extend("Pair", { + fields: ["key", "value"] + }); + var Dict = NodeList.extend("Dict"); + var LookupVal = Node.extend("LookupVal", { + fields: ["target", "val"] + }); + var If = Node.extend("If", { + fields: ["cond", "body", "else_"] + }); + var IfAsync = If.extend("IfAsync"); + var InlineIf = Node.extend("InlineIf", { + fields: ["cond", "body", "else_"] + }); + var For = Node.extend("For", { + fields: ["arr", "name", "body", "else_"] + }); + var AsyncEach = For.extend("AsyncEach"); + var AsyncAll = For.extend("AsyncAll"); + var Macro = Node.extend("Macro", { + fields: ["name", "args", "body"] + }); + var Caller = Macro.extend("Caller"); + var Import = Node.extend("Import", { + fields: ["template", "target", "withContext"] + }); + var FromImport = /* @__PURE__ */ function(_Node3) { + _inheritsLoose(FromImport2, _Node3); + function FromImport2() { + return _Node3.apply(this, arguments) || this; + } + var _proto3 = FromImport2.prototype; + _proto3.init = function init(lineno, colno, template, names, withContext) { + _Node3.prototype.init.call(this, lineno, colno, template, names || new NodeList(), withContext); + }; + _createClass(FromImport2, [{ + key: "typename", + get: function get() { + return "FromImport"; + } + }, { + key: "fields", + get: function get() { + return ["template", "names", "withContext"]; + } + }]); + return FromImport2; + }(Node); + var FunCall = Node.extend("FunCall", { + fields: ["name", "args"] + }); + var Filter = FunCall.extend("Filter"); + var FilterAsync = Filter.extend("FilterAsync", { + fields: ["name", "args", "symbol"] + }); + var KeywordArgs = Dict.extend("KeywordArgs"); + var Block = Node.extend("Block", { + fields: ["name", "body"] + }); + var Super = Node.extend("Super", { + fields: ["blockName", "symbol"] + }); + var TemplateRef = Node.extend("TemplateRef", { + fields: ["template"] + }); + var Extends = TemplateRef.extend("Extends"); + var Include = Node.extend("Include", { + fields: ["template", "ignoreMissing"] + }); + var Set2 = Node.extend("Set", { + fields: ["targets", "value"] + }); + var Switch = Node.extend("Switch", { + fields: ["expr", "cases", "default"] + }); + var Case = Node.extend("Case", { + fields: ["cond", "body"] + }); + var Output = NodeList.extend("Output"); + var Capture = Node.extend("Capture", { + fields: ["body"] + }); + var TemplateData = Literal.extend("TemplateData"); + var UnaryOp = Node.extend("UnaryOp", { + fields: ["target"] + }); + var BinOp = Node.extend("BinOp", { + fields: ["left", "right"] + }); + var In = BinOp.extend("In"); + var Is = BinOp.extend("Is"); + var Or = BinOp.extend("Or"); + var And = BinOp.extend("And"); + var Not = UnaryOp.extend("Not"); + var Add = BinOp.extend("Add"); + var Concat = BinOp.extend("Concat"); + var Sub = BinOp.extend("Sub"); + var Mul = BinOp.extend("Mul"); + var Div = BinOp.extend("Div"); + var FloorDiv = BinOp.extend("FloorDiv"); + var Mod = BinOp.extend("Mod"); + var Pow = BinOp.extend("Pow"); + var Neg = UnaryOp.extend("Neg"); + var Pos = UnaryOp.extend("Pos"); + var Compare = Node.extend("Compare", { + fields: ["expr", "ops"] + }); + var CompareOperand = Node.extend("CompareOperand", { + fields: ["expr", "type"] + }); + var CallExtension = Node.extend("CallExtension", { + init: function init(ext, prop, args, contentArgs) { + this.parent(); + this.extName = ext.__name || ext; + this.prop = prop; + this.args = args || new NodeList(); + this.contentArgs = contentArgs || []; + this.autoescape = ext.autoescape; + }, + fields: ["extName", "prop", "args", "contentArgs"] + }); + var CallExtensionAsync = CallExtension.extend("CallExtensionAsync"); + function print(str, indent, inline) { + var lines = str.split("\n"); + lines.forEach(function(line, i) { + if (line && (inline && i > 0 || !inline)) { + process.stdout.write(" ".repeat(indent)); + } + var nl = i === lines.length - 1 ? "" : "\n"; + process.stdout.write("" + line + nl); + }); + } + function printNodes(node, indent) { + indent = indent || 0; + print(node.typename + ": ", indent); + if (node instanceof NodeList) { + print("\n"); + node.children.forEach(function(n) { + printNodes(n, indent + 2); + }); + } else if (node instanceof CallExtension) { + print(node.extName + "." + node.prop + "\n"); + if (node.args) { + printNodes(node.args, indent + 2); + } + if (node.contentArgs) { + node.contentArgs.forEach(function(n) { + printNodes(n, indent + 2); + }); + } + } else { + var nodes2 = []; + var props = null; + node.iterFields(function(val, fieldName) { + if (val instanceof Node) { + nodes2.push([fieldName, val]); + } else { + props = props || {}; + props[fieldName] = val; + } + }); + if (props) { + print(JSON.stringify(props, null, 2) + "\n", null, true); + } else { + print("\n"); + } + nodes2.forEach(function(_ref) { + var fieldName = _ref[0], n = _ref[1]; + print("[" + fieldName + "] =>", indent + 2); + printNodes(n, indent + 4); + }); + } + } + module2.exports = { + Node, + Root, + NodeList, + Value, + Literal, + Symbol: Symbol2, + Group, + Array: ArrayNode, + Pair, + Dict, + Output, + Capture, + TemplateData, + If, + IfAsync, + InlineIf, + For, + AsyncEach, + AsyncAll, + Macro, + Caller, + Import, + FromImport, + FunCall, + Filter, + FilterAsync, + KeywordArgs, + Block, + Super, + Extends, + Include, + Set: Set2, + Switch, + Case, + LookupVal, + BinOp, + In, + Is, + Or, + And, + Not, + Add, + Concat, + Sub, + Mul, + Div, + FloorDiv, + Mod, + Pow, + Neg, + Pos, + Compare, + CompareOperand, + CallExtension, + CallExtensionAsync, + printNodes + }; +}); + +// ../../node_modules/nunjucks/src/parser.js +var require_parser = __commonJS((exports2, module2) => { + "use strict"; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var lexer2 = require_lexer(); + var nodes2 = require_nodes(); + var Obj = require_object().Obj; + var lib2 = require_lib(); + var Parser = /* @__PURE__ */ function(_Obj) { + _inheritsLoose(Parser2, _Obj); + function Parser2() { + return _Obj.apply(this, arguments) || this; + } + var _proto = Parser2.prototype; + _proto.init = function init(tokens) { + this.tokens = tokens; + this.peeked = null; + this.breakOnBlocks = null; + this.dropLeadingWhitespace = false; + this.extensions = []; + }; + _proto.nextToken = function nextToken(withWhitespace) { + var tok; + if (this.peeked) { + if (!withWhitespace && this.peeked.type === lexer2.TOKEN_WHITESPACE) { + this.peeked = null; + } else { + tok = this.peeked; + this.peeked = null; + return tok; + } + } + tok = this.tokens.nextToken(); + if (!withWhitespace) { + while (tok && tok.type === lexer2.TOKEN_WHITESPACE) { + tok = this.tokens.nextToken(); + } + } + return tok; + }; + _proto.peekToken = function peekToken() { + this.peeked = this.peeked || this.nextToken(); + return this.peeked; + }; + _proto.pushToken = function pushToken(tok) { + if (this.peeked) { + throw new Error("pushToken: can only push one token on between reads"); + } + this.peeked = tok; + }; + _proto.error = function error(msg, lineno, colno) { + if (lineno === void 0 || colno === void 0) { + var tok = this.peekToken() || {}; + lineno = tok.lineno; + colno = tok.colno; + } + if (lineno !== void 0) { + lineno += 1; + } + if (colno !== void 0) { + colno += 1; + } + return new lib2.TemplateError(msg, lineno, colno); + }; + _proto.fail = function fail(msg, lineno, colno) { + throw this.error(msg, lineno, colno); + }; + _proto.skip = function skip(type) { + var tok = this.nextToken(); + if (!tok || tok.type !== type) { + this.pushToken(tok); + return false; + } + return true; + }; + _proto.expect = function expect(type) { + var tok = this.nextToken(); + if (tok.type !== type) { + this.fail("expected " + type + ", got " + tok.type, tok.lineno, tok.colno); + } + return tok; + }; + _proto.skipValue = function skipValue(type, val) { + var tok = this.nextToken(); + if (!tok || tok.type !== type || tok.value !== val) { + this.pushToken(tok); + return false; + } + return true; + }; + _proto.skipSymbol = function skipSymbol(val) { + return this.skipValue(lexer2.TOKEN_SYMBOL, val); + }; + _proto.advanceAfterBlockEnd = function advanceAfterBlockEnd(name) { + var tok; + if (!name) { + tok = this.peekToken(); + if (!tok) { + this.fail("unexpected end of file"); + } + if (tok.type !== lexer2.TOKEN_SYMBOL) { + this.fail("advanceAfterBlockEnd: expected symbol token or explicit name to be passed"); + } + name = this.nextToken().value; + } + tok = this.nextToken(); + if (tok && tok.type === lexer2.TOKEN_BLOCK_END) { + if (tok.value.charAt(0) === "-") { + this.dropLeadingWhitespace = true; + } + } else { + this.fail("expected block end in " + name + " statement"); + } + return tok; + }; + _proto.advanceAfterVariableEnd = function advanceAfterVariableEnd() { + var tok = this.nextToken(); + if (tok && tok.type === lexer2.TOKEN_VARIABLE_END) { + this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.VARIABLE_END.length - 1) === "-"; + } else { + this.pushToken(tok); + this.fail("expected variable end"); + } + }; + _proto.parseFor = function parseFor() { + var forTok = this.peekToken(); + var node; + var endBlock; + if (this.skipSymbol("for")) { + node = new nodes2.For(forTok.lineno, forTok.colno); + endBlock = "endfor"; + } else if (this.skipSymbol("asyncEach")) { + node = new nodes2.AsyncEach(forTok.lineno, forTok.colno); + endBlock = "endeach"; + } else if (this.skipSymbol("asyncAll")) { + node = new nodes2.AsyncAll(forTok.lineno, forTok.colno); + endBlock = "endall"; + } else { + this.fail("parseFor: expected for{Async}", forTok.lineno, forTok.colno); + } + node.name = this.parsePrimary(); + if (!(node.name instanceof nodes2.Symbol)) { + this.fail("parseFor: variable name expected for loop"); + } + var type = this.peekToken().type; + if (type === lexer2.TOKEN_COMMA) { + var key = node.name; + node.name = new nodes2.Array(key.lineno, key.colno); + node.name.addChild(key); + while (this.skip(lexer2.TOKEN_COMMA)) { + var prim = this.parsePrimary(); + node.name.addChild(prim); + } + } + if (!this.skipSymbol("in")) { + this.fail('parseFor: expected "in" keyword for loop', forTok.lineno, forTok.colno); + } + node.arr = this.parseExpression(); + this.advanceAfterBlockEnd(forTok.value); + node.body = this.parseUntilBlocks(endBlock, "else"); + if (this.skipSymbol("else")) { + this.advanceAfterBlockEnd("else"); + node.else_ = this.parseUntilBlocks(endBlock); + } + this.advanceAfterBlockEnd(); + return node; + }; + _proto.parseMacro = function parseMacro() { + var macroTok = this.peekToken(); + if (!this.skipSymbol("macro")) { + this.fail("expected macro"); + } + var name = this.parsePrimary(true); + var args = this.parseSignature(); + var node = new nodes2.Macro(macroTok.lineno, macroTok.colno, name, args); + this.advanceAfterBlockEnd(macroTok.value); + node.body = this.parseUntilBlocks("endmacro"); + this.advanceAfterBlockEnd(); + return node; + }; + _proto.parseCall = function parseCall() { + var callTok = this.peekToken(); + if (!this.skipSymbol("call")) { + this.fail("expected call"); + } + var callerArgs = this.parseSignature(true) || new nodes2.NodeList(); + var macroCall = this.parsePrimary(); + this.advanceAfterBlockEnd(callTok.value); + var body = this.parseUntilBlocks("endcall"); + this.advanceAfterBlockEnd(); + var callerName = new nodes2.Symbol(callTok.lineno, callTok.colno, "caller"); + var callerNode = new nodes2.Caller(callTok.lineno, callTok.colno, callerName, callerArgs, body); + var args = macroCall.args.children; + if (!(args[args.length - 1] instanceof nodes2.KeywordArgs)) { + args.push(new nodes2.KeywordArgs()); + } + var kwargs = args[args.length - 1]; + kwargs.addChild(new nodes2.Pair(callTok.lineno, callTok.colno, callerName, callerNode)); + return new nodes2.Output(callTok.lineno, callTok.colno, [macroCall]); + }; + _proto.parseWithContext = function parseWithContext() { + var tok = this.peekToken(); + var withContext = null; + if (this.skipSymbol("with")) { + withContext = true; + } else if (this.skipSymbol("without")) { + withContext = false; + } + if (withContext !== null) { + if (!this.skipSymbol("context")) { + this.fail("parseFrom: expected context after with/without", tok.lineno, tok.colno); + } + } + return withContext; + }; + _proto.parseImport = function parseImport() { + var importTok = this.peekToken(); + if (!this.skipSymbol("import")) { + this.fail("parseImport: expected import", importTok.lineno, importTok.colno); + } + var template = this.parseExpression(); + if (!this.skipSymbol("as")) { + this.fail('parseImport: expected "as" keyword', importTok.lineno, importTok.colno); + } + var target = this.parseExpression(); + var withContext = this.parseWithContext(); + var node = new nodes2.Import(importTok.lineno, importTok.colno, template, target, withContext); + this.advanceAfterBlockEnd(importTok.value); + return node; + }; + _proto.parseFrom = function parseFrom() { + var fromTok = this.peekToken(); + if (!this.skipSymbol("from")) { + this.fail("parseFrom: expected from"); + } + var template = this.parseExpression(); + if (!this.skipSymbol("import")) { + this.fail("parseFrom: expected import", fromTok.lineno, fromTok.colno); + } + var names = new nodes2.NodeList(); + var withContext; + while (1) { + var nextTok = this.peekToken(); + if (nextTok.type === lexer2.TOKEN_BLOCK_END) { + if (!names.children.length) { + this.fail("parseFrom: Expected at least one import name", fromTok.lineno, fromTok.colno); + } + if (nextTok.value.charAt(0) === "-") { + this.dropLeadingWhitespace = true; + } + this.nextToken(); + break; + } + if (names.children.length > 0 && !this.skip(lexer2.TOKEN_COMMA)) { + this.fail("parseFrom: expected comma", fromTok.lineno, fromTok.colno); + } + var name = this.parsePrimary(); + if (name.value.charAt(0) === "_") { + this.fail("parseFrom: names starting with an underscore cannot be imported", name.lineno, name.colno); + } + if (this.skipSymbol("as")) { + var alias = this.parsePrimary(); + names.addChild(new nodes2.Pair(name.lineno, name.colno, name, alias)); + } else { + names.addChild(name); + } + withContext = this.parseWithContext(); + } + return new nodes2.FromImport(fromTok.lineno, fromTok.colno, template, names, withContext); + }; + _proto.parseBlock = function parseBlock() { + var tag = this.peekToken(); + if (!this.skipSymbol("block")) { + this.fail("parseBlock: expected block", tag.lineno, tag.colno); + } + var node = new nodes2.Block(tag.lineno, tag.colno); + node.name = this.parsePrimary(); + if (!(node.name instanceof nodes2.Symbol)) { + this.fail("parseBlock: variable name expected", tag.lineno, tag.colno); + } + this.advanceAfterBlockEnd(tag.value); + node.body = this.parseUntilBlocks("endblock"); + this.skipSymbol("endblock"); + this.skipSymbol(node.name.value); + var tok = this.peekToken(); + if (!tok) { + this.fail("parseBlock: expected endblock, got end of file"); + } + this.advanceAfterBlockEnd(tok.value); + return node; + }; + _proto.parseExtends = function parseExtends() { + var tagName = "extends"; + var tag = this.peekToken(); + if (!this.skipSymbol(tagName)) { + this.fail("parseTemplateRef: expected " + tagName); + } + var node = new nodes2.Extends(tag.lineno, tag.colno); + node.template = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + return node; + }; + _proto.parseInclude = function parseInclude() { + var tagName = "include"; + var tag = this.peekToken(); + if (!this.skipSymbol(tagName)) { + this.fail("parseInclude: expected " + tagName); + } + var node = new nodes2.Include(tag.lineno, tag.colno); + node.template = this.parseExpression(); + if (this.skipSymbol("ignore") && this.skipSymbol("missing")) { + node.ignoreMissing = true; + } + this.advanceAfterBlockEnd(tag.value); + return node; + }; + _proto.parseIf = function parseIf() { + var tag = this.peekToken(); + var node; + if (this.skipSymbol("if") || this.skipSymbol("elif") || this.skipSymbol("elseif")) { + node = new nodes2.If(tag.lineno, tag.colno); + } else if (this.skipSymbol("ifAsync")) { + node = new nodes2.IfAsync(tag.lineno, tag.colno); + } else { + this.fail("parseIf: expected if, elif, or elseif", tag.lineno, tag.colno); + } + node.cond = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + node.body = this.parseUntilBlocks("elif", "elseif", "else", "endif"); + var tok = this.peekToken(); + switch (tok && tok.value) { + case "elseif": + case "elif": + node.else_ = this.parseIf(); + break; + case "else": + this.advanceAfterBlockEnd(); + node.else_ = this.parseUntilBlocks("endif"); + this.advanceAfterBlockEnd(); + break; + case "endif": + node.else_ = null; + this.advanceAfterBlockEnd(); + break; + default: + this.fail("parseIf: expected elif, else, or endif, got end of file"); + } + return node; + }; + _proto.parseSet = function parseSet() { + var tag = this.peekToken(); + if (!this.skipSymbol("set")) { + this.fail("parseSet: expected set", tag.lineno, tag.colno); + } + var node = new nodes2.Set(tag.lineno, tag.colno, []); + var target; + while (target = this.parsePrimary()) { + node.targets.push(target); + if (!this.skip(lexer2.TOKEN_COMMA)) { + break; + } + } + if (!this.skipValue(lexer2.TOKEN_OPERATOR, "=")) { + if (!this.skip(lexer2.TOKEN_BLOCK_END)) { + this.fail("parseSet: expected = or block end in set tag", tag.lineno, tag.colno); + } else { + node.body = new nodes2.Capture(tag.lineno, tag.colno, this.parseUntilBlocks("endset")); + node.value = null; + this.advanceAfterBlockEnd(); + } + } else { + node.value = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + } + return node; + }; + _proto.parseSwitch = function parseSwitch() { + var switchStart = "switch"; + var switchEnd = "endswitch"; + var caseStart = "case"; + var caseDefault = "default"; + var tag = this.peekToken(); + if (!this.skipSymbol(switchStart) && !this.skipSymbol(caseStart) && !this.skipSymbol(caseDefault)) { + this.fail('parseSwitch: expected "switch," "case" or "default"', tag.lineno, tag.colno); + } + var expr = this.parseExpression(); + this.advanceAfterBlockEnd(switchStart); + this.parseUntilBlocks(caseStart, caseDefault, switchEnd); + var tok = this.peekToken(); + var cases = []; + var defaultCase; + do { + this.skipSymbol(caseStart); + var cond = this.parseExpression(); + this.advanceAfterBlockEnd(switchStart); + var body = this.parseUntilBlocks(caseStart, caseDefault, switchEnd); + cases.push(new nodes2.Case(tok.line, tok.col, cond, body)); + tok = this.peekToken(); + } while (tok && tok.value === caseStart); + switch (tok.value) { + case caseDefault: + this.advanceAfterBlockEnd(); + defaultCase = this.parseUntilBlocks(switchEnd); + this.advanceAfterBlockEnd(); + break; + case switchEnd: + this.advanceAfterBlockEnd(); + break; + default: + this.fail('parseSwitch: expected "case," "default" or "endswitch," got EOF.'); + } + return new nodes2.Switch(tag.lineno, tag.colno, expr, cases, defaultCase); + }; + _proto.parseStatement = function parseStatement() { + var tok = this.peekToken(); + var node; + if (tok.type !== lexer2.TOKEN_SYMBOL) { + this.fail("tag name expected", tok.lineno, tok.colno); + } + if (this.breakOnBlocks && lib2.indexOf(this.breakOnBlocks, tok.value) !== -1) { + return null; + } + switch (tok.value) { + case "raw": + return this.parseRaw(); + case "verbatim": + return this.parseRaw("verbatim"); + case "if": + case "ifAsync": + return this.parseIf(); + case "for": + case "asyncEach": + case "asyncAll": + return this.parseFor(); + case "block": + return this.parseBlock(); + case "extends": + return this.parseExtends(); + case "include": + return this.parseInclude(); + case "set": + return this.parseSet(); + case "macro": + return this.parseMacro(); + case "call": + return this.parseCall(); + case "import": + return this.parseImport(); + case "from": + return this.parseFrom(); + case "filter": + return this.parseFilterStatement(); + case "switch": + return this.parseSwitch(); + default: + if (this.extensions.length) { + for (var i = 0; i < this.extensions.length; i++) { + var ext = this.extensions[i]; + if (lib2.indexOf(ext.tags || [], tok.value) !== -1) { + return ext.parse(this, nodes2, lexer2); + } + } + } + this.fail("unknown block tag: " + tok.value, tok.lineno, tok.colno); + } + return node; + }; + _proto.parseRaw = function parseRaw(tagName) { + tagName = tagName || "raw"; + var endTagName = "end" + tagName; + var rawBlockRegex = new RegExp("([\\s\\S]*?){%\\s*(" + tagName + "|" + endTagName + ")\\s*(?=%})%}"); + var rawLevel = 1; + var str = ""; + var matches = null; + var begun = this.advanceAfterBlockEnd(); + while ((matches = this.tokens._extractRegex(rawBlockRegex)) && rawLevel > 0) { + var all = matches[0]; + var pre = matches[1]; + var blockName = matches[2]; + if (blockName === tagName) { + rawLevel += 1; + } else if (blockName === endTagName) { + rawLevel -= 1; + } + if (rawLevel === 0) { + str += pre; + this.tokens.backN(all.length - pre.length); + } else { + str += all; + } + } + return new nodes2.Output(begun.lineno, begun.colno, [new nodes2.TemplateData(begun.lineno, begun.colno, str)]); + }; + _proto.parsePostfix = function parsePostfix(node) { + var lookup; + var tok = this.peekToken(); + while (tok) { + if (tok.type === lexer2.TOKEN_LEFT_PAREN) { + node = new nodes2.FunCall(tok.lineno, tok.colno, node, this.parseSignature()); + } else if (tok.type === lexer2.TOKEN_LEFT_BRACKET) { + lookup = this.parseAggregate(); + if (lookup.children.length > 1) { + this.fail("invalid index"); + } + node = new nodes2.LookupVal(tok.lineno, tok.colno, node, lookup.children[0]); + } else if (tok.type === lexer2.TOKEN_OPERATOR && tok.value === ".") { + this.nextToken(); + var val = this.nextToken(); + if (val.type !== lexer2.TOKEN_SYMBOL) { + this.fail("expected name as lookup value, got " + val.value, val.lineno, val.colno); + } + lookup = new nodes2.Literal(val.lineno, val.colno, val.value); + node = new nodes2.LookupVal(tok.lineno, tok.colno, node, lookup); + } else { + break; + } + tok = this.peekToken(); + } + return node; + }; + _proto.parseExpression = function parseExpression() { + var node = this.parseInlineIf(); + return node; + }; + _proto.parseInlineIf = function parseInlineIf() { + var node = this.parseOr(); + if (this.skipSymbol("if")) { + var condNode = this.parseOr(); + var bodyNode = node; + node = new nodes2.InlineIf(node.lineno, node.colno); + node.body = bodyNode; + node.cond = condNode; + if (this.skipSymbol("else")) { + node.else_ = this.parseOr(); + } else { + node.else_ = null; + } + } + return node; + }; + _proto.parseOr = function parseOr() { + var node = this.parseAnd(); + while (this.skipSymbol("or")) { + var node2 = this.parseAnd(); + node = new nodes2.Or(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseAnd = function parseAnd() { + var node = this.parseNot(); + while (this.skipSymbol("and")) { + var node2 = this.parseNot(); + node = new nodes2.And(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseNot = function parseNot() { + var tok = this.peekToken(); + if (this.skipSymbol("not")) { + return new nodes2.Not(tok.lineno, tok.colno, this.parseNot()); + } + return this.parseIn(); + }; + _proto.parseIn = function parseIn() { + var node = this.parseIs(); + while (1) { + var tok = this.nextToken(); + if (!tok) { + break; + } + var invert = tok.type === lexer2.TOKEN_SYMBOL && tok.value === "not"; + if (!invert) { + this.pushToken(tok); + } + if (this.skipSymbol("in")) { + var node2 = this.parseIs(); + node = new nodes2.In(node.lineno, node.colno, node, node2); + if (invert) { + node = new nodes2.Not(node.lineno, node.colno, node); + } + } else { + if (invert) { + this.pushToken(tok); + } + break; + } + } + return node; + }; + _proto.parseIs = function parseIs() { + var node = this.parseCompare(); + if (this.skipSymbol("is")) { + var not = this.skipSymbol("not"); + var node2 = this.parseCompare(); + node = new nodes2.Is(node.lineno, node.colno, node, node2); + if (not) { + node = new nodes2.Not(node.lineno, node.colno, node); + } + } + return node; + }; + _proto.parseCompare = function parseCompare() { + var compareOps = ["==", "===", "!=", "!==", "<", ">", "<=", ">="]; + var expr = this.parseConcat(); + var ops = []; + while (1) { + var tok = this.nextToken(); + if (!tok) { + break; + } else if (compareOps.indexOf(tok.value) !== -1) { + ops.push(new nodes2.CompareOperand(tok.lineno, tok.colno, this.parseConcat(), tok.value)); + } else { + this.pushToken(tok); + break; + } + } + if (ops.length) { + return new nodes2.Compare(ops[0].lineno, ops[0].colno, expr, ops); + } else { + return expr; + } + }; + _proto.parseConcat = function parseConcat() { + var node = this.parseAdd(); + while (this.skipValue(lexer2.TOKEN_TILDE, "~")) { + var node2 = this.parseAdd(); + node = new nodes2.Concat(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseAdd = function parseAdd() { + var node = this.parseSub(); + while (this.skipValue(lexer2.TOKEN_OPERATOR, "+")) { + var node2 = this.parseSub(); + node = new nodes2.Add(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseSub = function parseSub() { + var node = this.parseMul(); + while (this.skipValue(lexer2.TOKEN_OPERATOR, "-")) { + var node2 = this.parseMul(); + node = new nodes2.Sub(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseMul = function parseMul() { + var node = this.parseDiv(); + while (this.skipValue(lexer2.TOKEN_OPERATOR, "*")) { + var node2 = this.parseDiv(); + node = new nodes2.Mul(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseDiv = function parseDiv() { + var node = this.parseFloorDiv(); + while (this.skipValue(lexer2.TOKEN_OPERATOR, "/")) { + var node2 = this.parseFloorDiv(); + node = new nodes2.Div(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseFloorDiv = function parseFloorDiv() { + var node = this.parseMod(); + while (this.skipValue(lexer2.TOKEN_OPERATOR, "//")) { + var node2 = this.parseMod(); + node = new nodes2.FloorDiv(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseMod = function parseMod() { + var node = this.parsePow(); + while (this.skipValue(lexer2.TOKEN_OPERATOR, "%")) { + var node2 = this.parsePow(); + node = new nodes2.Mod(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parsePow = function parsePow() { + var node = this.parseUnary(); + while (this.skipValue(lexer2.TOKEN_OPERATOR, "**")) { + var node2 = this.parseUnary(); + node = new nodes2.Pow(node.lineno, node.colno, node, node2); + } + return node; + }; + _proto.parseUnary = function parseUnary(noFilters) { + var tok = this.peekToken(); + var node; + if (this.skipValue(lexer2.TOKEN_OPERATOR, "-")) { + node = new nodes2.Neg(tok.lineno, tok.colno, this.parseUnary(true)); + } else if (this.skipValue(lexer2.TOKEN_OPERATOR, "+")) { + node = new nodes2.Pos(tok.lineno, tok.colno, this.parseUnary(true)); + } else { + node = this.parsePrimary(); + } + if (!noFilters) { + node = this.parseFilter(node); + } + return node; + }; + _proto.parsePrimary = function parsePrimary(noPostfix) { + var tok = this.nextToken(); + var val; + var node = null; + if (!tok) { + this.fail("expected expression, got end of file"); + } else if (tok.type === lexer2.TOKEN_STRING) { + val = tok.value; + } else if (tok.type === lexer2.TOKEN_INT) { + val = parseInt(tok.value, 10); + } else if (tok.type === lexer2.TOKEN_FLOAT) { + val = parseFloat(tok.value); + } else if (tok.type === lexer2.TOKEN_BOOLEAN) { + if (tok.value === "true") { + val = true; + } else if (tok.value === "false") { + val = false; + } else { + this.fail("invalid boolean: " + tok.value, tok.lineno, tok.colno); + } + } else if (tok.type === lexer2.TOKEN_NONE) { + val = null; + } else if (tok.type === lexer2.TOKEN_REGEX) { + val = new RegExp(tok.value.body, tok.value.flags); + } + if (val !== void 0) { + node = new nodes2.Literal(tok.lineno, tok.colno, val); + } else if (tok.type === lexer2.TOKEN_SYMBOL) { + node = new nodes2.Symbol(tok.lineno, tok.colno, tok.value); + } else { + this.pushToken(tok); + node = this.parseAggregate(); + } + if (!noPostfix) { + node = this.parsePostfix(node); + } + if (node) { + return node; + } else { + throw this.error("unexpected token: " + tok.value, tok.lineno, tok.colno); + } + }; + _proto.parseFilterName = function parseFilterName() { + var tok = this.expect(lexer2.TOKEN_SYMBOL); + var name = tok.value; + while (this.skipValue(lexer2.TOKEN_OPERATOR, ".")) { + name += "." + this.expect(lexer2.TOKEN_SYMBOL).value; + } + return new nodes2.Symbol(tok.lineno, tok.colno, name); + }; + _proto.parseFilterArgs = function parseFilterArgs(node) { + if (this.peekToken().type === lexer2.TOKEN_LEFT_PAREN) { + var call = this.parsePostfix(node); + return call.args.children; + } + return []; + }; + _proto.parseFilter = function parseFilter(node) { + while (this.skip(lexer2.TOKEN_PIPE)) { + var name = this.parseFilterName(); + node = new nodes2.Filter(name.lineno, name.colno, name, new nodes2.NodeList(name.lineno, name.colno, [node].concat(this.parseFilterArgs(node)))); + } + return node; + }; + _proto.parseFilterStatement = function parseFilterStatement() { + var filterTok = this.peekToken(); + if (!this.skipSymbol("filter")) { + this.fail("parseFilterStatement: expected filter"); + } + var name = this.parseFilterName(); + var args = this.parseFilterArgs(name); + this.advanceAfterBlockEnd(filterTok.value); + var body = new nodes2.Capture(name.lineno, name.colno, this.parseUntilBlocks("endfilter")); + this.advanceAfterBlockEnd(); + var node = new nodes2.Filter(name.lineno, name.colno, name, new nodes2.NodeList(name.lineno, name.colno, [body].concat(args))); + return new nodes2.Output(name.lineno, name.colno, [node]); + }; + _proto.parseAggregate = function parseAggregate() { + var tok = this.nextToken(); + var node; + switch (tok.type) { + case lexer2.TOKEN_LEFT_PAREN: + node = new nodes2.Group(tok.lineno, tok.colno); + break; + case lexer2.TOKEN_LEFT_BRACKET: + node = new nodes2.Array(tok.lineno, tok.colno); + break; + case lexer2.TOKEN_LEFT_CURLY: + node = new nodes2.Dict(tok.lineno, tok.colno); + break; + default: + return null; + } + while (1) { + var type = this.peekToken().type; + if (type === lexer2.TOKEN_RIGHT_PAREN || type === lexer2.TOKEN_RIGHT_BRACKET || type === lexer2.TOKEN_RIGHT_CURLY) { + this.nextToken(); + break; + } + if (node.children.length > 0) { + if (!this.skip(lexer2.TOKEN_COMMA)) { + this.fail("parseAggregate: expected comma after expression", tok.lineno, tok.colno); + } + } + if (node instanceof nodes2.Dict) { + var key = this.parsePrimary(); + if (!this.skip(lexer2.TOKEN_COLON)) { + this.fail("parseAggregate: expected colon after dict key", tok.lineno, tok.colno); + } + var value = this.parseExpression(); + node.addChild(new nodes2.Pair(key.lineno, key.colno, key, value)); + } else { + var expr = this.parseExpression(); + node.addChild(expr); + } + } + return node; + }; + _proto.parseSignature = function parseSignature(tolerant, noParens) { + var tok = this.peekToken(); + if (!noParens && tok.type !== lexer2.TOKEN_LEFT_PAREN) { + if (tolerant) { + return null; + } else { + this.fail("expected arguments", tok.lineno, tok.colno); + } + } + if (tok.type === lexer2.TOKEN_LEFT_PAREN) { + tok = this.nextToken(); + } + var args = new nodes2.NodeList(tok.lineno, tok.colno); + var kwargs = new nodes2.KeywordArgs(tok.lineno, tok.colno); + var checkComma = false; + while (1) { + tok = this.peekToken(); + if (!noParens && tok.type === lexer2.TOKEN_RIGHT_PAREN) { + this.nextToken(); + break; + } else if (noParens && tok.type === lexer2.TOKEN_BLOCK_END) { + break; + } + if (checkComma && !this.skip(lexer2.TOKEN_COMMA)) { + this.fail("parseSignature: expected comma after expression", tok.lineno, tok.colno); + } else { + var arg = this.parseExpression(); + if (this.skipValue(lexer2.TOKEN_OPERATOR, "=")) { + kwargs.addChild(new nodes2.Pair(arg.lineno, arg.colno, arg, this.parseExpression())); + } else { + args.addChild(arg); + } + } + checkComma = true; + } + if (kwargs.children.length) { + args.addChild(kwargs); + } + return args; + }; + _proto.parseUntilBlocks = function parseUntilBlocks() { + var prev = this.breakOnBlocks; + for (var _len = arguments.length, blockNames = new Array(_len), _key = 0; _key < _len; _key++) { + blockNames[_key] = arguments[_key]; + } + this.breakOnBlocks = blockNames; + var ret = this.parse(); + this.breakOnBlocks = prev; + return ret; + }; + _proto.parseNodes = function parseNodes() { + var tok; + var buf = []; + while (tok = this.nextToken()) { + if (tok.type === lexer2.TOKEN_DATA) { + var data = tok.value; + var nextToken = this.peekToken(); + var nextVal = nextToken && nextToken.value; + if (this.dropLeadingWhitespace) { + data = data.replace(/^\s*/, ""); + this.dropLeadingWhitespace = false; + } + if (nextToken && (nextToken.type === lexer2.TOKEN_BLOCK_START && nextVal.charAt(nextVal.length - 1) === "-" || nextToken.type === lexer2.TOKEN_VARIABLE_START && nextVal.charAt(this.tokens.tags.VARIABLE_START.length) === "-" || nextToken.type === lexer2.TOKEN_COMMENT && nextVal.charAt(this.tokens.tags.COMMENT_START.length) === "-")) { + data = data.replace(/\s*$/, ""); + } + buf.push(new nodes2.Output(tok.lineno, tok.colno, [new nodes2.TemplateData(tok.lineno, tok.colno, data)])); + } else if (tok.type === lexer2.TOKEN_BLOCK_START) { + this.dropLeadingWhitespace = false; + var n = this.parseStatement(); + if (!n) { + break; + } + buf.push(n); + } else if (tok.type === lexer2.TOKEN_VARIABLE_START) { + var e2 = this.parseExpression(); + this.dropLeadingWhitespace = false; + this.advanceAfterVariableEnd(); + buf.push(new nodes2.Output(tok.lineno, tok.colno, [e2])); + } else if (tok.type === lexer2.TOKEN_COMMENT) { + this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.COMMENT_END.length - 1) === "-"; + } else { + this.fail("Unexpected token at top-level: " + tok.type, tok.lineno, tok.colno); + } + } + return buf; + }; + _proto.parse = function parse() { + return new nodes2.NodeList(0, 0, this.parseNodes()); + }; + _proto.parseAsRoot = function parseAsRoot() { + return new nodes2.Root(0, 0, this.parseNodes()); + }; + return Parser2; + }(Obj); + module2.exports = { + parse: function parse(src, extensions, opts) { + var p = new Parser(lexer2.lex(src, opts)); + if (extensions !== void 0) { + p.extensions = extensions; + } + return p.parseAsRoot(); + }, + Parser + }; +}); + +// ../../node_modules/nunjucks/src/transformer.js +var require_transformer = __commonJS((exports2, module2) => { + "use strict"; + var nodes2 = require_nodes(); + var lib2 = require_lib(); + var sym = 0; + function gensym() { + return "hole_" + sym++; + } + function mapCOW(arr, func) { + var res = null; + for (var i = 0; i < arr.length; i++) { + var item = func(arr[i]); + if (item !== arr[i]) { + if (!res) { + res = arr.slice(); + } + res[i] = item; + } + } + return res || arr; + } + function walk(ast, func, depthFirst) { + if (!(ast instanceof nodes2.Node)) { + return ast; + } + if (!depthFirst) { + var astT = func(ast); + if (astT && astT !== ast) { + return astT; + } + } + if (ast instanceof nodes2.NodeList) { + var children = mapCOW(ast.children, function(node) { + return walk(node, func, depthFirst); + }); + if (children !== ast.children) { + ast = new nodes2[ast.typename](ast.lineno, ast.colno, children); + } + } else if (ast instanceof nodes2.CallExtension) { + var args = walk(ast.args, func, depthFirst); + var contentArgs = mapCOW(ast.contentArgs, function(node) { + return walk(node, func, depthFirst); + }); + if (args !== ast.args || contentArgs !== ast.contentArgs) { + ast = new nodes2[ast.typename](ast.extName, ast.prop, args, contentArgs); + } + } else { + var props = ast.fields.map(function(field) { + return ast[field]; + }); + var propsT = mapCOW(props, function(prop) { + return walk(prop, func, depthFirst); + }); + if (propsT !== props) { + ast = new nodes2[ast.typename](ast.lineno, ast.colno); + propsT.forEach(function(prop, i) { + ast[ast.fields[i]] = prop; + }); + } + } + return depthFirst ? func(ast) || ast : ast; + } + function depthWalk(ast, func) { + return walk(ast, func, true); + } + function _liftFilters(node, asyncFilters, prop) { + var children = []; + var walked = depthWalk(prop ? node[prop] : node, function(descNode) { + var symbol; + if (descNode instanceof nodes2.Block) { + return descNode; + } else if (descNode instanceof nodes2.Filter && lib2.indexOf(asyncFilters, descNode.name.value) !== -1 || descNode instanceof nodes2.CallExtensionAsync) { + symbol = new nodes2.Symbol(descNode.lineno, descNode.colno, gensym()); + children.push(new nodes2.FilterAsync(descNode.lineno, descNode.colno, descNode.name, descNode.args, symbol)); + } + return symbol; + }); + if (prop) { + node[prop] = walked; + } else { + node = walked; + } + if (children.length) { + children.push(node); + return new nodes2.NodeList(node.lineno, node.colno, children); + } else { + return node; + } + } + function liftFilters(ast, asyncFilters) { + return depthWalk(ast, function(node) { + if (node instanceof nodes2.Output) { + return _liftFilters(node, asyncFilters); + } else if (node instanceof nodes2.Set) { + return _liftFilters(node, asyncFilters, "value"); + } else if (node instanceof nodes2.For) { + return _liftFilters(node, asyncFilters, "arr"); + } else if (node instanceof nodes2.If) { + return _liftFilters(node, asyncFilters, "cond"); + } else if (node instanceof nodes2.CallExtension) { + return _liftFilters(node, asyncFilters, "args"); + } else { + return void 0; + } + }); + } + function liftSuper(ast) { + return walk(ast, function(blockNode) { + if (!(blockNode instanceof nodes2.Block)) { + return; + } + var hasSuper = false; + var symbol = gensym(); + blockNode.body = walk(blockNode.body, function(node) { + if (node instanceof nodes2.FunCall && node.name.value === "super") { + hasSuper = true; + return new nodes2.Symbol(node.lineno, node.colno, symbol); + } + }); + if (hasSuper) { + blockNode.body.children.unshift(new nodes2.Super(0, 0, blockNode.name, new nodes2.Symbol(0, 0, symbol))); + } + }); + } + function convertStatements(ast) { + return depthWalk(ast, function(node) { + if (!(node instanceof nodes2.If) && !(node instanceof nodes2.For)) { + return void 0; + } + var async = false; + walk(node, function(child) { + if (child instanceof nodes2.FilterAsync || child instanceof nodes2.IfAsync || child instanceof nodes2.AsyncEach || child instanceof nodes2.AsyncAll || child instanceof nodes2.CallExtensionAsync) { + async = true; + return child; + } + return void 0; + }); + if (async) { + if (node instanceof nodes2.If) { + return new nodes2.IfAsync(node.lineno, node.colno, node.cond, node.body, node.else_); + } else if (node instanceof nodes2.For && !(node instanceof nodes2.AsyncAll)) { + return new nodes2.AsyncEach(node.lineno, node.colno, node.arr, node.name, node.body, node.else_); + } + } + return void 0; + }); + } + function cps(ast, asyncFilters) { + return convertStatements(liftSuper(liftFilters(ast, asyncFilters))); + } + function transform(ast, asyncFilters) { + return cps(ast, asyncFilters || []); + } + module2.exports = { + transform + }; +}); + +// ../../node_modules/nunjucks/src/runtime.js +var require_runtime = __commonJS((exports2, module2) => { + "use strict"; + var lib2 = require_lib(); + var arrayFrom = Array.from; + var supportsIterators = typeof Symbol === "function" && Symbol.iterator && typeof arrayFrom === "function"; + var Frame = /* @__PURE__ */ function() { + function Frame2(parent, isolateWrites) { + this.variables = Object.create(null); + this.parent = parent; + this.topLevel = false; + this.isolateWrites = isolateWrites; + } + var _proto = Frame2.prototype; + _proto.set = function set(name, val, resolveUp) { + var parts = name.split("."); + var obj = this.variables; + var frame = this; + if (resolveUp) { + if (frame = this.resolve(parts[0], true)) { + frame.set(name, val); + return; + } + } + for (var i = 0; i < parts.length - 1; i++) { + var id = parts[i]; + if (!obj[id]) { + obj[id] = {}; + } + obj = obj[id]; + } + obj[parts[parts.length - 1]] = val; + }; + _proto.get = function get(name) { + var val = this.variables[name]; + if (val !== void 0) { + return val; + } + return null; + }; + _proto.lookup = function lookup(name) { + var p = this.parent; + var val = this.variables[name]; + if (val !== void 0) { + return val; + } + return p && p.lookup(name); + }; + _proto.resolve = function resolve(name, forWrite) { + var p = forWrite && this.isolateWrites ? void 0 : this.parent; + var val = this.variables[name]; + if (val !== void 0) { + return this; + } + return p && p.resolve(name); + }; + _proto.push = function push(isolateWrites) { + return new Frame2(this, isolateWrites); + }; + _proto.pop = function pop() { + return this.parent; + }; + return Frame2; + }(); + function makeMacro(argNames, kwargNames, func) { + return function macro() { + for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0; _key < _len; _key++) { + macroArgs[_key] = arguments[_key]; + } + var argCount = numArgs(macroArgs); + var args; + var kwargs = getKeywordArgs(macroArgs); + if (argCount > argNames.length) { + args = macroArgs.slice(0, argNames.length); + macroArgs.slice(args.length, argCount).forEach(function(val, i2) { + if (i2 < kwargNames.length) { + kwargs[kwargNames[i2]] = val; + } + }); + args.push(kwargs); + } else if (argCount < argNames.length) { + args = macroArgs.slice(0, argCount); + for (var i = argCount; i < argNames.length; i++) { + var arg = argNames[i]; + args.push(kwargs[arg]); + delete kwargs[arg]; + } + args.push(kwargs); + } else { + args = macroArgs; + } + return func.apply(this, args); + }; + } + function makeKeywordArgs(obj) { + obj.__keywords = true; + return obj; + } + function isKeywordArgs(obj) { + return obj && Object.prototype.hasOwnProperty.call(obj, "__keywords"); + } + function getKeywordArgs(args) { + var len = args.length; + if (len) { + var lastArg = args[len - 1]; + if (isKeywordArgs(lastArg)) { + return lastArg; + } + } + return {}; + } + function numArgs(args) { + var len = args.length; + if (len === 0) { + return 0; + } + var lastArg = args[len - 1]; + if (isKeywordArgs(lastArg)) { + return len - 1; + } else { + return len; + } + } + function SafeString(val) { + if (typeof val !== "string") { + return val; + } + this.val = val; + this.length = val.length; + } + SafeString.prototype = Object.create(String.prototype, { + length: { + writable: true, + configurable: true, + value: 0 + } + }); + SafeString.prototype.valueOf = function valueOf() { + return this.val; + }; + SafeString.prototype.toString = function toString() { + return this.val; + }; + function copySafeness(dest, target) { + if (dest instanceof SafeString) { + return new SafeString(target); + } + return target.toString(); + } + function markSafe(val) { + var type = typeof val; + if (type === "string") { + return new SafeString(val); + } else if (type !== "function") { + return val; + } else { + return function wrapSafe(args) { + var ret = val.apply(this, arguments); + if (typeof ret === "string") { + return new SafeString(ret); + } + return ret; + }; + } + } + function suppressValue(val, autoescape) { + val = val !== void 0 && val !== null ? val : ""; + if (autoescape && !(val instanceof SafeString)) { + val = lib2.escape(val.toString()); + } + return val; + } + function ensureDefined(val, lineno, colno) { + if (val === null || val === void 0) { + throw new lib2.TemplateError("attempted to output null or undefined value", lineno + 1, colno + 1); + } + return val; + } + function memberLookup(obj, val) { + if (obj === void 0 || obj === null) { + return void 0; + } + if (typeof obj[val] === "function") { + return function() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + return obj[val].apply(obj, args); + }; + } + return obj[val]; + } + function callWrap(obj, name, context, args) { + if (!obj) { + throw new Error("Unable to call `" + name + "`, which is undefined or falsey"); + } else if (typeof obj !== "function") { + throw new Error("Unable to call `" + name + "`, which is not a function"); + } + return obj.apply(context, args); + } + function contextOrFrameLookup(context, frame, name) { + var val = frame.lookup(name); + return val !== void 0 ? val : context.lookup(name); + } + function handleError(error, lineno, colno) { + if (error.lineno) { + return error; + } else { + return new lib2.TemplateError(error, lineno, colno); + } + } + function asyncEach(arr, dimen, iter, cb) { + if (lib2.isArray(arr)) { + var len = arr.length; + lib2.asyncIter(arr, function iterCallback(item, i, next) { + switch (dimen) { + case 1: + iter(item, i, len, next); + break; + case 2: + iter(item[0], item[1], i, len, next); + break; + case 3: + iter(item[0], item[1], item[2], i, len, next); + break; + default: + item.push(i, len, next); + iter.apply(this, item); + } + }, cb); + } else { + lib2.asyncFor(arr, function iterCallback(key, val, i, len2, next) { + iter(key, val, i, len2, next); + }, cb); + } + } + function asyncAll(arr, dimen, func, cb) { + var finished = 0; + var len; + var outputArr; + function done(i2, output) { + finished++; + outputArr[i2] = output; + if (finished === len) { + cb(null, outputArr.join("")); + } + } + if (lib2.isArray(arr)) { + len = arr.length; + outputArr = new Array(len); + if (len === 0) { + cb(null, ""); + } else { + for (var i = 0; i < arr.length; i++) { + var item = arr[i]; + switch (dimen) { + case 1: + func(item, i, len, done); + break; + case 2: + func(item[0], item[1], i, len, done); + break; + case 3: + func(item[0], item[1], item[2], i, len, done); + break; + default: + item.push(i, len, done); + func.apply(this, item); + } + } + } + } else { + var keys = lib2.keys(arr || {}); + len = keys.length; + outputArr = new Array(len); + if (len === 0) { + cb(null, ""); + } else { + for (var _i = 0; _i < keys.length; _i++) { + var k = keys[_i]; + func(k, arr[k], _i, len, done); + } + } + } + } + function fromIterator(arr) { + if (typeof arr !== "object" || arr === null || lib2.isArray(arr)) { + return arr; + } else if (supportsIterators && Symbol.iterator in arr) { + return arrayFrom(arr); + } else { + return arr; + } + } + module2.exports = { + Frame, + makeMacro, + makeKeywordArgs, + numArgs, + suppressValue, + ensureDefined, + memberLookup, + contextOrFrameLookup, + callWrap, + handleError, + isArray: lib2.isArray, + keys: lib2.keys, + SafeString, + copySafeness, + markSafe, + asyncEach, + asyncAll, + inOperator: lib2.inOperator, + fromIterator + }; +}); + +// ../../node_modules/nunjucks/src/compiler.js +var require_compiler = __commonJS((exports2, module2) => { + "use strict"; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var parser2 = require_parser(); + var transformer = require_transformer(); + var nodes2 = require_nodes(); + var _require2 = require_lib(); + var TemplateError = _require2.TemplateError; + var _require22 = require_runtime(); + var Frame = _require22.Frame; + var _require3 = require_object(); + var Obj = _require3.Obj; + var compareOps = { + "==": "==", + "===": "===", + "!=": "!=", + "!==": "!==", + "<": "<", + ">": ">", + "<=": "<=", + ">=": ">=" + }; + var Compiler = /* @__PURE__ */ function(_Obj) { + _inheritsLoose(Compiler2, _Obj); + function Compiler2() { + return _Obj.apply(this, arguments) || this; + } + var _proto = Compiler2.prototype; + _proto.init = function init(templateName, throwOnUndefined) { + this.templateName = templateName; + this.codebuf = []; + this.lastId = 0; + this.buffer = null; + this.bufferStack = []; + this._scopeClosers = ""; + this.inBlock = false; + this.throwOnUndefined = throwOnUndefined; + }; + _proto.fail = function fail(msg, lineno, colno) { + if (lineno !== void 0) { + lineno += 1; + } + if (colno !== void 0) { + colno += 1; + } + throw new TemplateError(msg, lineno, colno); + }; + _proto._pushBuffer = function _pushBuffer() { + var id = this._tmpid(); + this.bufferStack.push(this.buffer); + this.buffer = id; + this._emit("var " + this.buffer + ' = "";'); + return id; + }; + _proto._popBuffer = function _popBuffer() { + this.buffer = this.bufferStack.pop(); + }; + _proto._emit = function _emit(code) { + this.codebuf.push(code); + }; + _proto._emitLine = function _emitLine(code) { + this._emit(code + "\n"); + }; + _proto._emitLines = function _emitLines() { + var _this = this; + for (var _len = arguments.length, lines = new Array(_len), _key = 0; _key < _len; _key++) { + lines[_key] = arguments[_key]; + } + lines.forEach(function(line) { + return _this._emitLine(line); + }); + }; + _proto._emitFuncBegin = function _emitFuncBegin(node, name) { + this.buffer = "output"; + this._scopeClosers = ""; + this._emitLine("function " + name + "(env, context, frame, runtime, cb) {"); + this._emitLine("var lineno = " + node.lineno + ";"); + this._emitLine("var colno = " + node.colno + ";"); + this._emitLine("var " + this.buffer + ' = "";'); + this._emitLine("try {"); + }; + _proto._emitFuncEnd = function _emitFuncEnd(noReturn) { + if (!noReturn) { + this._emitLine("cb(null, " + this.buffer + ");"); + } + this._closeScopeLevels(); + this._emitLine("} catch (e) {"); + this._emitLine(" cb(runtime.handleError(e, lineno, colno));"); + this._emitLine("}"); + this._emitLine("}"); + this.buffer = null; + }; + _proto._addScopeLevel = function _addScopeLevel() { + this._scopeClosers += "})"; + }; + _proto._closeScopeLevels = function _closeScopeLevels() { + this._emitLine(this._scopeClosers + ";"); + this._scopeClosers = ""; + }; + _proto._withScopedSyntax = function _withScopedSyntax(func) { + var _scopeClosers = this._scopeClosers; + this._scopeClosers = ""; + func.call(this); + this._closeScopeLevels(); + this._scopeClosers = _scopeClosers; + }; + _proto._makeCallback = function _makeCallback(res) { + var err = this._tmpid(); + return "function(" + err + (res ? "," + res : "") + ") {\nif(" + err + ") { cb(" + err + "); return; }"; + }; + _proto._tmpid = function _tmpid() { + this.lastId++; + return "t_" + this.lastId; + }; + _proto._templateName = function _templateName() { + return this.templateName == null ? "undefined" : JSON.stringify(this.templateName); + }; + _proto._compileChildren = function _compileChildren(node, frame) { + var _this2 = this; + node.children.forEach(function(child) { + _this2.compile(child, frame); + }); + }; + _proto._compileAggregate = function _compileAggregate(node, frame, startChar, endChar) { + var _this3 = this; + if (startChar) { + this._emit(startChar); + } + node.children.forEach(function(child, i) { + if (i > 0) { + _this3._emit(","); + } + _this3.compile(child, frame); + }); + if (endChar) { + this._emit(endChar); + } + }; + _proto._compileExpression = function _compileExpression(node, frame) { + this.assertType(node, nodes2.Literal, nodes2.Symbol, nodes2.Group, nodes2.Array, nodes2.Dict, nodes2.FunCall, nodes2.Caller, nodes2.Filter, nodes2.LookupVal, nodes2.Compare, nodes2.InlineIf, nodes2.In, nodes2.Is, nodes2.And, nodes2.Or, nodes2.Not, nodes2.Add, nodes2.Concat, nodes2.Sub, nodes2.Mul, nodes2.Div, nodes2.FloorDiv, nodes2.Mod, nodes2.Pow, nodes2.Neg, nodes2.Pos, nodes2.Compare, nodes2.NodeList); + this.compile(node, frame); + }; + _proto.assertType = function assertType(node) { + for (var _len2 = arguments.length, types = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + types[_key2 - 1] = arguments[_key2]; + } + if (!types.some(function(t) { + return node instanceof t; + })) { + this.fail("assertType: invalid type: " + node.typename, node.lineno, node.colno); + } + }; + _proto.compileCallExtension = function compileCallExtension(node, frame, async) { + var _this4 = this; + var args = node.args; + var contentArgs = node.contentArgs; + var autoescape = typeof node.autoescape === "boolean" ? node.autoescape : true; + if (!async) { + this._emit(this.buffer + " += runtime.suppressValue("); + } + this._emit('env.getExtension("' + node.extName + '")["' + node.prop + '"]('); + this._emit("context"); + if (args || contentArgs) { + this._emit(","); + } + if (args) { + if (!(args instanceof nodes2.NodeList)) { + this.fail("compileCallExtension: arguments must be a NodeList, use `parser.parseSignature`"); + } + args.children.forEach(function(arg, i) { + _this4._compileExpression(arg, frame); + if (i !== args.children.length - 1 || contentArgs.length) { + _this4._emit(","); + } + }); + } + if (contentArgs.length) { + contentArgs.forEach(function(arg, i) { + if (i > 0) { + _this4._emit(","); + } + if (arg) { + _this4._emitLine("function(cb) {"); + _this4._emitLine("if(!cb) { cb = function(err) { if(err) { throw err; }}}"); + var id = _this4._pushBuffer(); + _this4._withScopedSyntax(function() { + _this4.compile(arg, frame); + _this4._emitLine("cb(null, " + id + ");"); + }); + _this4._popBuffer(); + _this4._emitLine("return " + id + ";"); + _this4._emitLine("}"); + } else { + _this4._emit("null"); + } + }); + } + if (async) { + var res = this._tmpid(); + this._emitLine(", " + this._makeCallback(res)); + this._emitLine(this.buffer + " += runtime.suppressValue(" + res + ", " + autoescape + " && env.opts.autoescape);"); + this._addScopeLevel(); + } else { + this._emit(")"); + this._emit(", " + autoescape + " && env.opts.autoescape);\n"); + } + }; + _proto.compileCallExtensionAsync = function compileCallExtensionAsync(node, frame) { + this.compileCallExtension(node, frame, true); + }; + _proto.compileNodeList = function compileNodeList(node, frame) { + this._compileChildren(node, frame); + }; + _proto.compileLiteral = function compileLiteral(node) { + if (typeof node.value === "string") { + var val = node.value.replace(/\\/g, "\\\\"); + val = val.replace(/"/g, '\\"'); + val = val.replace(/\n/g, "\\n"); + val = val.replace(/\r/g, "\\r"); + val = val.replace(/\t/g, "\\t"); + val = val.replace(/\u2028/g, "\\u2028"); + this._emit('"' + val + '"'); + } else if (node.value === null) { + this._emit("null"); + } else { + this._emit(node.value.toString()); + } + }; + _proto.compileSymbol = function compileSymbol(node, frame) { + var name = node.value; + var v = frame.lookup(name); + if (v) { + this._emit(v); + } else { + this._emit('runtime.contextOrFrameLookup(context, frame, "' + name + '")'); + } + }; + _proto.compileGroup = function compileGroup(node, frame) { + this._compileAggregate(node, frame, "(", ")"); + }; + _proto.compileArray = function compileArray(node, frame) { + this._compileAggregate(node, frame, "[", "]"); + }; + _proto.compileDict = function compileDict(node, frame) { + this._compileAggregate(node, frame, "{", "}"); + }; + _proto.compilePair = function compilePair(node, frame) { + var key = node.key; + var val = node.value; + if (key instanceof nodes2.Symbol) { + key = new nodes2.Literal(key.lineno, key.colno, key.value); + } else if (!(key instanceof nodes2.Literal && typeof key.value === "string")) { + this.fail("compilePair: Dict keys must be strings or names", key.lineno, key.colno); + } + this.compile(key, frame); + this._emit(": "); + this._compileExpression(val, frame); + }; + _proto.compileInlineIf = function compileInlineIf(node, frame) { + this._emit("("); + this.compile(node.cond, frame); + this._emit("?"); + this.compile(node.body, frame); + this._emit(":"); + if (node.else_ !== null) { + this.compile(node.else_, frame); + } else { + this._emit('""'); + } + this._emit(")"); + }; + _proto.compileIn = function compileIn(node, frame) { + this._emit("runtime.inOperator("); + this.compile(node.left, frame); + this._emit(","); + this.compile(node.right, frame); + this._emit(")"); + }; + _proto.compileIs = function compileIs(node, frame) { + var right = node.right.name ? node.right.name.value : node.right.value; + this._emit('env.getTest("' + right + '").call(context, '); + this.compile(node.left, frame); + if (node.right.args) { + this._emit(","); + this.compile(node.right.args, frame); + } + this._emit(") === true"); + }; + _proto._binOpEmitter = function _binOpEmitter(node, frame, str) { + this.compile(node.left, frame); + this._emit(str); + this.compile(node.right, frame); + }; + _proto.compileOr = function compileOr(node, frame) { + return this._binOpEmitter(node, frame, " || "); + }; + _proto.compileAnd = function compileAnd(node, frame) { + return this._binOpEmitter(node, frame, " && "); + }; + _proto.compileAdd = function compileAdd(node, frame) { + return this._binOpEmitter(node, frame, " + "); + }; + _proto.compileConcat = function compileConcat(node, frame) { + return this._binOpEmitter(node, frame, ' + "" + '); + }; + _proto.compileSub = function compileSub(node, frame) { + return this._binOpEmitter(node, frame, " - "); + }; + _proto.compileMul = function compileMul(node, frame) { + return this._binOpEmitter(node, frame, " * "); + }; + _proto.compileDiv = function compileDiv(node, frame) { + return this._binOpEmitter(node, frame, " / "); + }; + _proto.compileMod = function compileMod(node, frame) { + return this._binOpEmitter(node, frame, " % "); + }; + _proto.compileNot = function compileNot(node, frame) { + this._emit("!"); + this.compile(node.target, frame); + }; + _proto.compileFloorDiv = function compileFloorDiv(node, frame) { + this._emit("Math.floor("); + this.compile(node.left, frame); + this._emit(" / "); + this.compile(node.right, frame); + this._emit(")"); + }; + _proto.compilePow = function compilePow(node, frame) { + this._emit("Math.pow("); + this.compile(node.left, frame); + this._emit(", "); + this.compile(node.right, frame); + this._emit(")"); + }; + _proto.compileNeg = function compileNeg(node, frame) { + this._emit("-"); + this.compile(node.target, frame); + }; + _proto.compilePos = function compilePos(node, frame) { + this._emit("+"); + this.compile(node.target, frame); + }; + _proto.compileCompare = function compileCompare(node, frame) { + var _this5 = this; + this.compile(node.expr, frame); + node.ops.forEach(function(op) { + _this5._emit(" " + compareOps[op.type] + " "); + _this5.compile(op.expr, frame); + }); + }; + _proto.compileLookupVal = function compileLookupVal(node, frame) { + this._emit("runtime.memberLookup(("); + this._compileExpression(node.target, frame); + this._emit("),"); + this._compileExpression(node.val, frame); + this._emit(")"); + }; + _proto._getNodeName = function _getNodeName(node) { + switch (node.typename) { + case "Symbol": + return node.value; + case "FunCall": + return "the return value of (" + this._getNodeName(node.name) + ")"; + case "LookupVal": + return this._getNodeName(node.target) + '["' + this._getNodeName(node.val) + '"]'; + case "Literal": + return node.value.toString(); + default: + return "--expression--"; + } + }; + _proto.compileFunCall = function compileFunCall(node, frame) { + this._emit("(lineno = " + node.lineno + ", colno = " + node.colno + ", "); + this._emit("runtime.callWrap("); + this._compileExpression(node.name, frame); + this._emit(', "' + this._getNodeName(node.name).replace(/"/g, '\\"') + '", context, '); + this._compileAggregate(node.args, frame, "[", "])"); + this._emit(")"); + }; + _proto.compileFilter = function compileFilter(node, frame) { + var name = node.name; + this.assertType(name, nodes2.Symbol); + this._emit('env.getFilter("' + name.value + '").call(context, '); + this._compileAggregate(node.args, frame); + this._emit(")"); + }; + _proto.compileFilterAsync = function compileFilterAsync(node, frame) { + var name = node.name; + var symbol = node.symbol.value; + this.assertType(name, nodes2.Symbol); + frame.set(symbol, symbol); + this._emit('env.getFilter("' + name.value + '").call(context, '); + this._compileAggregate(node.args, frame); + this._emitLine(", " + this._makeCallback(symbol)); + this._addScopeLevel(); + }; + _proto.compileKeywordArgs = function compileKeywordArgs(node, frame) { + this._emit("runtime.makeKeywordArgs("); + this.compileDict(node, frame); + this._emit(")"); + }; + _proto.compileSet = function compileSet(node, frame) { + var _this6 = this; + var ids = []; + node.targets.forEach(function(target) { + var name = target.value; + var id = frame.lookup(name); + if (id === null || id === void 0) { + id = _this6._tmpid(); + _this6._emitLine("var " + id + ";"); + } + ids.push(id); + }); + if (node.value) { + this._emit(ids.join(" = ") + " = "); + this._compileExpression(node.value, frame); + this._emitLine(";"); + } else { + this._emit(ids.join(" = ") + " = "); + this.compile(node.body, frame); + this._emitLine(";"); + } + node.targets.forEach(function(target, i) { + var id = ids[i]; + var name = target.value; + _this6._emitLine('frame.set("' + name + '", ' + id + ", true);"); + _this6._emitLine("if(frame.topLevel) {"); + _this6._emitLine('context.setVariable("' + name + '", ' + id + ");"); + _this6._emitLine("}"); + if (name.charAt(0) !== "_") { + _this6._emitLine("if(frame.topLevel) {"); + _this6._emitLine('context.addExport("' + name + '", ' + id + ");"); + _this6._emitLine("}"); + } + }); + }; + _proto.compileSwitch = function compileSwitch(node, frame) { + var _this7 = this; + this._emit("switch ("); + this.compile(node.expr, frame); + this._emit(") {"); + node.cases.forEach(function(c, i) { + _this7._emit("case "); + _this7.compile(c.cond, frame); + _this7._emit(": "); + _this7.compile(c.body, frame); + if (c.body.children.length) { + _this7._emitLine("break;"); + } + }); + if (node.default) { + this._emit("default:"); + this.compile(node.default, frame); + } + this._emit("}"); + }; + _proto.compileIf = function compileIf(node, frame, async) { + var _this8 = this; + this._emit("if("); + this._compileExpression(node.cond, frame); + this._emitLine(") {"); + this._withScopedSyntax(function() { + _this8.compile(node.body, frame); + if (async) { + _this8._emit("cb()"); + } + }); + if (node.else_) { + this._emitLine("}\nelse {"); + this._withScopedSyntax(function() { + _this8.compile(node.else_, frame); + if (async) { + _this8._emit("cb()"); + } + }); + } else if (async) { + this._emitLine("}\nelse {"); + this._emit("cb()"); + } + this._emitLine("}"); + }; + _proto.compileIfAsync = function compileIfAsync(node, frame) { + this._emit("(function(cb) {"); + this.compileIf(node, frame, true); + this._emit("})(" + this._makeCallback()); + this._addScopeLevel(); + }; + _proto._emitLoopBindings = function _emitLoopBindings(node, arr, i, len) { + var _this9 = this; + var bindings = [{ + name: "index", + val: i + " + 1" + }, { + name: "index0", + val: i + }, { + name: "revindex", + val: len + " - " + i + }, { + name: "revindex0", + val: len + " - " + i + " - 1" + }, { + name: "first", + val: i + " === 0" + }, { + name: "last", + val: i + " === " + len + " - 1" + }, { + name: "length", + val: len + }]; + bindings.forEach(function(b) { + _this9._emitLine('frame.set("loop.' + b.name + '", ' + b.val + ");"); + }); + }; + _proto.compileFor = function compileFor(node, frame) { + var _this10 = this; + var i = this._tmpid(); + var len = this._tmpid(); + var arr = this._tmpid(); + frame = frame.push(); + this._emitLine("frame = frame.push();"); + this._emit("var " + arr + " = "); + this._compileExpression(node.arr, frame); + this._emitLine(";"); + this._emit("if(" + arr + ") {"); + this._emitLine(arr + " = runtime.fromIterator(" + arr + ");"); + if (node.name instanceof nodes2.Array) { + this._emitLine("var " + i + ";"); + this._emitLine("if(runtime.isArray(" + arr + ")) {"); + this._emitLine("var " + len + " = " + arr + ".length;"); + this._emitLine("for(" + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); + node.name.children.forEach(function(child, u) { + var tid = _this10._tmpid(); + _this10._emitLine("var " + tid + " = " + arr + "[" + i + "][" + u + "];"); + _this10._emitLine('frame.set("' + child + '", ' + arr + "[" + i + "][" + u + "]);"); + frame.set(node.name.children[u].value, tid); + }); + this._emitLoopBindings(node, arr, i, len); + this._withScopedSyntax(function() { + _this10.compile(node.body, frame); + }); + this._emitLine("}"); + this._emitLine("} else {"); + var _node$name$children = node.name.children, key = _node$name$children[0], val = _node$name$children[1]; + var k = this._tmpid(); + var v = this._tmpid(); + frame.set(key.value, k); + frame.set(val.value, v); + this._emitLine(i + " = -1;"); + this._emitLine("var " + len + " = runtime.keys(" + arr + ").length;"); + this._emitLine("for(var " + k + " in " + arr + ") {"); + this._emitLine(i + "++;"); + this._emitLine("var " + v + " = " + arr + "[" + k + "];"); + this._emitLine('frame.set("' + key.value + '", ' + k + ");"); + this._emitLine('frame.set("' + val.value + '", ' + v + ");"); + this._emitLoopBindings(node, arr, i, len); + this._withScopedSyntax(function() { + _this10.compile(node.body, frame); + }); + this._emitLine("}"); + this._emitLine("}"); + } else { + var _v = this._tmpid(); + frame.set(node.name.value, _v); + this._emitLine("var " + len + " = " + arr + ".length;"); + this._emitLine("for(var " + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); + this._emitLine("var " + _v + " = " + arr + "[" + i + "];"); + this._emitLine('frame.set("' + node.name.value + '", ' + _v + ");"); + this._emitLoopBindings(node, arr, i, len); + this._withScopedSyntax(function() { + _this10.compile(node.body, frame); + }); + this._emitLine("}"); + } + this._emitLine("}"); + if (node.else_) { + this._emitLine("if (!" + len + ") {"); + this.compile(node.else_, frame); + this._emitLine("}"); + } + this._emitLine("frame = frame.pop();"); + }; + _proto._compileAsyncLoop = function _compileAsyncLoop(node, frame, parallel) { + var _this11 = this; + var i = this._tmpid(); + var len = this._tmpid(); + var arr = this._tmpid(); + var asyncMethod = parallel ? "asyncAll" : "asyncEach"; + frame = frame.push(); + this._emitLine("frame = frame.push();"); + this._emit("var " + arr + " = runtime.fromIterator("); + this._compileExpression(node.arr, frame); + this._emitLine(");"); + if (node.name instanceof nodes2.Array) { + var arrayLen = node.name.children.length; + this._emit("runtime." + asyncMethod + "(" + arr + ", " + arrayLen + ", function("); + node.name.children.forEach(function(name) { + _this11._emit(name.value + ","); + }); + this._emit(i + "," + len + ",next) {"); + node.name.children.forEach(function(name) { + var id2 = name.value; + frame.set(id2, id2); + _this11._emitLine('frame.set("' + id2 + '", ' + id2 + ");"); + }); + } else { + var id = node.name.value; + this._emitLine("runtime." + asyncMethod + "(" + arr + ", 1, function(" + id + ", " + i + ", " + len + ",next) {"); + this._emitLine('frame.set("' + id + '", ' + id + ");"); + frame.set(id, id); + } + this._emitLoopBindings(node, arr, i, len); + this._withScopedSyntax(function() { + var buf; + if (parallel) { + buf = _this11._pushBuffer(); + } + _this11.compile(node.body, frame); + _this11._emitLine("next(" + i + (buf ? "," + buf : "") + ");"); + if (parallel) { + _this11._popBuffer(); + } + }); + var output = this._tmpid(); + this._emitLine("}, " + this._makeCallback(output)); + this._addScopeLevel(); + if (parallel) { + this._emitLine(this.buffer + " += " + output + ";"); + } + if (node.else_) { + this._emitLine("if (!" + arr + ".length) {"); + this.compile(node.else_, frame); + this._emitLine("}"); + } + this._emitLine("frame = frame.pop();"); + }; + _proto.compileAsyncEach = function compileAsyncEach(node, frame) { + this._compileAsyncLoop(node, frame); + }; + _proto.compileAsyncAll = function compileAsyncAll(node, frame) { + this._compileAsyncLoop(node, frame, true); + }; + _proto._compileMacro = function _compileMacro(node, frame) { + var _this12 = this; + var args = []; + var kwargs = null; + var funcId = "macro_" + this._tmpid(); + var keepFrame = frame !== void 0; + node.args.children.forEach(function(arg, i) { + if (i === node.args.children.length - 1 && arg instanceof nodes2.Dict) { + kwargs = arg; + } else { + _this12.assertType(arg, nodes2.Symbol); + args.push(arg); + } + }); + var realNames = [].concat(args.map(function(n) { + return "l_" + n.value; + }), ["kwargs"]); + var argNames = args.map(function(n) { + return '"' + n.value + '"'; + }); + var kwargNames = (kwargs && kwargs.children || []).map(function(n) { + return '"' + n.key.value + '"'; + }); + var currFrame; + if (keepFrame) { + currFrame = frame.push(true); + } else { + currFrame = new Frame(); + } + this._emitLines("var " + funcId + " = runtime.makeMacro(", "[" + argNames.join(", ") + "], ", "[" + kwargNames.join(", ") + "], ", "function (" + realNames.join(", ") + ") {", "var callerFrame = frame;", "frame = " + (keepFrame ? "frame.push(true);" : "new runtime.Frame();"), "kwargs = kwargs || {};", 'if (Object.prototype.hasOwnProperty.call(kwargs, "caller")) {', 'frame.set("caller", kwargs.caller); }'); + args.forEach(function(arg) { + _this12._emitLine('frame.set("' + arg.value + '", l_' + arg.value + ");"); + currFrame.set(arg.value, "l_" + arg.value); + }); + if (kwargs) { + kwargs.children.forEach(function(pair) { + var name = pair.key.value; + _this12._emit('frame.set("' + name + '", '); + _this12._emit('Object.prototype.hasOwnProperty.call(kwargs, "' + name + '")'); + _this12._emit(' ? kwargs["' + name + '"] : '); + _this12._compileExpression(pair.value, currFrame); + _this12._emit(");"); + }); + } + var bufferId = this._pushBuffer(); + this._withScopedSyntax(function() { + _this12.compile(node.body, currFrame); + }); + this._emitLine("frame = " + (keepFrame ? "frame.pop();" : "callerFrame;")); + this._emitLine("return new runtime.SafeString(" + bufferId + ");"); + this._emitLine("});"); + this._popBuffer(); + return funcId; + }; + _proto.compileMacro = function compileMacro(node, frame) { + var funcId = this._compileMacro(node); + var name = node.name.value; + frame.set(name, funcId); + if (frame.parent) { + this._emitLine('frame.set("' + name + '", ' + funcId + ");"); + } else { + if (node.name.value.charAt(0) !== "_") { + this._emitLine('context.addExport("' + name + '");'); + } + this._emitLine('context.setVariable("' + name + '", ' + funcId + ");"); + } + }; + _proto.compileCaller = function compileCaller(node, frame) { + this._emit("(function (){"); + var funcId = this._compileMacro(node, frame); + this._emit("return " + funcId + ";})()"); + }; + _proto._compileGetTemplate = function _compileGetTemplate(node, frame, eagerCompile, ignoreMissing) { + var parentTemplateId = this._tmpid(); + var parentName = this._templateName(); + var cb = this._makeCallback(parentTemplateId); + var eagerCompileArg = eagerCompile ? "true" : "false"; + var ignoreMissingArg = ignoreMissing ? "true" : "false"; + this._emit("env.getTemplate("); + this._compileExpression(node.template, frame); + this._emitLine(", " + eagerCompileArg + ", " + parentName + ", " + ignoreMissingArg + ", " + cb); + return parentTemplateId; + }; + _proto.compileImport = function compileImport(node, frame) { + var target = node.target.value; + var id = this._compileGetTemplate(node, frame, false, false); + this._addScopeLevel(); + this._emitLine(id + ".getExported(" + (node.withContext ? "context.getVariables(), frame, " : "") + this._makeCallback(id)); + this._addScopeLevel(); + frame.set(target, id); + if (frame.parent) { + this._emitLine('frame.set("' + target + '", ' + id + ");"); + } else { + this._emitLine('context.setVariable("' + target + '", ' + id + ");"); + } + }; + _proto.compileFromImport = function compileFromImport(node, frame) { + var _this13 = this; + var importedId = this._compileGetTemplate(node, frame, false, false); + this._addScopeLevel(); + this._emitLine(importedId + ".getExported(" + (node.withContext ? "context.getVariables(), frame, " : "") + this._makeCallback(importedId)); + this._addScopeLevel(); + node.names.children.forEach(function(nameNode) { + var name; + var alias; + var id = _this13._tmpid(); + if (nameNode instanceof nodes2.Pair) { + name = nameNode.key.value; + alias = nameNode.value.value; + } else { + name = nameNode.value; + alias = name; + } + _this13._emitLine("if(Object.prototype.hasOwnProperty.call(" + importedId + ', "' + name + '")) {'); + _this13._emitLine("var " + id + " = " + importedId + "." + name + ";"); + _this13._emitLine("} else {"); + _this13._emitLine(`cb(new Error("cannot import '` + name + `'")); return;`); + _this13._emitLine("}"); + frame.set(alias, id); + if (frame.parent) { + _this13._emitLine('frame.set("' + alias + '", ' + id + ");"); + } else { + _this13._emitLine('context.setVariable("' + alias + '", ' + id + ");"); + } + }); + }; + _proto.compileBlock = function compileBlock(node) { + var id = this._tmpid(); + if (!this.inBlock) { + this._emit('(parentTemplate ? function(e, c, f, r, cb) { cb(""); } : '); + } + this._emit('context.getBlock("' + node.name.value + '")'); + if (!this.inBlock) { + this._emit(")"); + } + this._emitLine("(env, context, frame, runtime, " + this._makeCallback(id)); + this._emitLine(this.buffer + " += " + id + ";"); + this._addScopeLevel(); + }; + _proto.compileSuper = function compileSuper(node, frame) { + var name = node.blockName.value; + var id = node.symbol.value; + var cb = this._makeCallback(id); + this._emitLine('context.getSuper(env, "' + name + '", b_' + name + ", frame, runtime, " + cb); + this._emitLine(id + " = runtime.markSafe(" + id + ");"); + this._addScopeLevel(); + frame.set(id, id); + }; + _proto.compileExtends = function compileExtends(node, frame) { + var k = this._tmpid(); + var parentTemplateId = this._compileGetTemplate(node, frame, true, false); + this._emitLine("parentTemplate = " + parentTemplateId); + this._emitLine("for(var " + k + " in parentTemplate.blocks) {"); + this._emitLine("context.addBlock(" + k + ", parentTemplate.blocks[" + k + "]);"); + this._emitLine("}"); + this._addScopeLevel(); + }; + _proto.compileInclude = function compileInclude(node, frame) { + this._emitLine("var tasks = [];"); + this._emitLine("tasks.push("); + this._emitLine("function(callback) {"); + var id = this._compileGetTemplate(node, frame, false, node.ignoreMissing); + this._emitLine("callback(null," + id + ");});"); + this._emitLine("});"); + var id2 = this._tmpid(); + this._emitLine("tasks.push("); + this._emitLine("function(template, callback){"); + this._emitLine("template.render(context.getVariables(), frame, " + this._makeCallback(id2)); + this._emitLine("callback(null," + id2 + ");});"); + this._emitLine("});"); + this._emitLine("tasks.push("); + this._emitLine("function(result, callback){"); + this._emitLine(this.buffer + " += result;"); + this._emitLine("callback(null);"); + this._emitLine("});"); + this._emitLine("env.waterfall(tasks, function(){"); + this._addScopeLevel(); + }; + _proto.compileTemplateData = function compileTemplateData(node, frame) { + this.compileLiteral(node, frame); + }; + _proto.compileCapture = function compileCapture(node, frame) { + var _this14 = this; + var buffer = this.buffer; + this.buffer = "output"; + this._emitLine("(function() {"); + this._emitLine('var output = "";'); + this._withScopedSyntax(function() { + _this14.compile(node.body, frame); + }); + this._emitLine("return output;"); + this._emitLine("})()"); + this.buffer = buffer; + }; + _proto.compileOutput = function compileOutput(node, frame) { + var _this15 = this; + var children = node.children; + children.forEach(function(child) { + if (child instanceof nodes2.TemplateData) { + if (child.value) { + _this15._emit(_this15.buffer + " += "); + _this15.compileLiteral(child, frame); + _this15._emitLine(";"); + } + } else { + _this15._emit(_this15.buffer + " += runtime.suppressValue("); + if (_this15.throwOnUndefined) { + _this15._emit("runtime.ensureDefined("); + } + _this15.compile(child, frame); + if (_this15.throwOnUndefined) { + _this15._emit("," + node.lineno + "," + node.colno + ")"); + } + _this15._emit(", env.opts.autoescape);\n"); + } + }); + }; + _proto.compileRoot = function compileRoot(node, frame) { + var _this16 = this; + if (frame) { + this.fail("compileRoot: root node can't have frame"); + } + frame = new Frame(); + this._emitFuncBegin(node, "root"); + this._emitLine("var parentTemplate = null;"); + this._compileChildren(node, frame); + this._emitLine("if(parentTemplate) {"); + this._emitLine("parentTemplate.rootRenderFunc(env, context, frame, runtime, cb);"); + this._emitLine("} else {"); + this._emitLine("cb(null, " + this.buffer + ");"); + this._emitLine("}"); + this._emitFuncEnd(true); + this.inBlock = true; + var blockNames = []; + var blocks = node.findAll(nodes2.Block); + blocks.forEach(function(block, i) { + var name = block.name.value; + if (blockNames.indexOf(name) !== -1) { + throw new Error('Block "' + name + '" defined more than once.'); + } + blockNames.push(name); + _this16._emitFuncBegin(block, "b_" + name); + var tmpFrame = new Frame(); + _this16._emitLine("var frame = frame.push(true);"); + _this16.compile(block.body, tmpFrame); + _this16._emitFuncEnd(); + }); + this._emitLine("return {"); + blocks.forEach(function(block, i) { + var blockName = "b_" + block.name.value; + _this16._emitLine(blockName + ": " + blockName + ","); + }); + this._emitLine("root: root\n};"); + }; + _proto.compile = function compile2(node, frame) { + var _compile = this["compile" + node.typename]; + if (_compile) { + _compile.call(this, node, frame); + } else { + this.fail("compile: Cannot compile node: " + node.typename, node.lineno, node.colno); + } + }; + _proto.getCode = function getCode() { + return this.codebuf.join(""); + }; + return Compiler2; + }(Obj); + module2.exports = { + compile: function compile2(src, asyncFilters, extensions, name, opts) { + if (opts === void 0) { + opts = {}; + } + var c = new Compiler(name, opts.throwOnUndefined); + var preprocessors = (extensions || []).map(function(ext) { + return ext.preprocess; + }).filter(function(f) { + return !!f; + }); + var processedSrc = preprocessors.reduce(function(s, processor) { + return processor(s); + }, src); + c.compile(transformer.transform(parser2.parse(processedSrc, extensions, opts), asyncFilters, name)); + return c.getCode(); + }, + Compiler + }; +}); + +// ../../node_modules/nunjucks/src/filters.js +var require_filters = __commonJS((exports2, module2) => { + "use strict"; + var lib2 = require_lib(); + var r = require_runtime(); + var _exports = module2.exports = {}; + function normalize(value, defaultValue) { + if (value === null || value === void 0 || value === false) { + return defaultValue; + } + return value; + } + _exports.abs = Math.abs; + function isNaN2(num) { + return num !== num; + } + function batch(arr, linecount, fillWith) { + var i; + var res = []; + var tmp = []; + for (i = 0; i < arr.length; i++) { + if (i % linecount === 0 && tmp.length) { + res.push(tmp); + tmp = []; + } + tmp.push(arr[i]); + } + if (tmp.length) { + if (fillWith) { + for (i = tmp.length; i < linecount; i++) { + tmp.push(fillWith); + } + } + res.push(tmp); + } + return res; + } + _exports.batch = batch; + function capitalize(str) { + str = normalize(str, ""); + var ret = str.toLowerCase(); + return r.copySafeness(str, ret.charAt(0).toUpperCase() + ret.slice(1)); + } + _exports.capitalize = capitalize; + function center(str, width) { + str = normalize(str, ""); + width = width || 80; + if (str.length >= width) { + return str; + } + var spaces = width - str.length; + var pre = lib2.repeat(" ", spaces / 2 - spaces % 2); + var post = lib2.repeat(" ", spaces / 2); + return r.copySafeness(str, pre + str + post); + } + _exports.center = center; + function default_(val, def, bool) { + if (bool) { + return val || def; + } else { + return val !== void 0 ? val : def; + } + } + _exports["default"] = default_; + function dictsort(val, caseSensitive, by) { + if (!lib2.isObject(val)) { + throw new lib2.TemplateError("dictsort filter: val must be an object"); + } + var array = []; + for (var k in val) { + array.push([k, val[k]]); + } + var si; + if (by === void 0 || by === "key") { + si = 0; + } else if (by === "value") { + si = 1; + } else { + throw new lib2.TemplateError("dictsort filter: You can only sort by either key or value"); + } + array.sort(function(t1, t2) { + var a = t1[si]; + var b = t2[si]; + if (!caseSensitive) { + if (lib2.isString(a)) { + a = a.toUpperCase(); + } + if (lib2.isString(b)) { + b = b.toUpperCase(); + } + } + return a > b ? 1 : a === b ? 0 : -1; + }); + return array; + } + _exports.dictsort = dictsort; + function dump(obj, spaces) { + return JSON.stringify(obj, null, spaces); + } + _exports.dump = dump; + function escape(str) { + if (str instanceof r.SafeString) { + return str; + } + str = str === null || str === void 0 ? "" : str; + return r.markSafe(lib2.escape(str.toString())); + } + _exports.escape = escape; + function safe(str) { + if (str instanceof r.SafeString) { + return str; + } + str = str === null || str === void 0 ? "" : str; + return r.markSafe(str.toString()); + } + _exports.safe = safe; + function first(arr) { + return arr[0]; + } + _exports.first = first; + function forceescape(str) { + str = str === null || str === void 0 ? "" : str; + return r.markSafe(lib2.escape(str.toString())); + } + _exports.forceescape = forceescape; + function groupby(arr, attr) { + return lib2.groupBy(arr, attr, this.env.opts.throwOnUndefined); + } + _exports.groupby = groupby; + function indent(str, width, indentfirst) { + str = normalize(str, ""); + if (str === "") { + return ""; + } + width = width || 4; + var lines = str.split("\n"); + var sp = lib2.repeat(" ", width); + var res = lines.map(function(l, i) { + return i === 0 && !indentfirst ? l : "" + sp + l; + }).join("\n"); + return r.copySafeness(str, res); + } + _exports.indent = indent; + function join(arr, del, attr) { + del = del || ""; + if (attr) { + arr = lib2.map(arr, function(v) { + return v[attr]; + }); + } + return arr.join(del); + } + _exports.join = join; + function last(arr) { + return arr[arr.length - 1]; + } + _exports.last = last; + function lengthFilter(val) { + var value = normalize(val, ""); + if (value !== void 0) { + if (typeof Map === "function" && value instanceof Map || typeof Set === "function" && value instanceof Set) { + return value.size; + } + if (lib2.isObject(value) && !(value instanceof r.SafeString)) { + return lib2.keys(value).length; + } + return value.length; + } + return 0; + } + _exports.length = lengthFilter; + function list(val) { + if (lib2.isString(val)) { + return val.split(""); + } else if (lib2.isObject(val)) { + return lib2._entries(val || {}).map(function(_ref) { + var key = _ref[0], value = _ref[1]; + return { + key, + value + }; + }); + } else if (lib2.isArray(val)) { + return val; + } else { + throw new lib2.TemplateError("list filter: type not iterable"); + } + } + _exports.list = list; + function lower(str) { + str = normalize(str, ""); + return str.toLowerCase(); + } + _exports.lower = lower; + function nl2br(str) { + if (str === null || str === void 0) { + return ""; + } + return r.copySafeness(str, str.replace(/\r\n|\n/g, "
\n")); + } + _exports.nl2br = nl2br; + function random(arr) { + return arr[Math.floor(Math.random() * arr.length)]; + } + _exports.random = random; + function getSelectOrReject(expectedTestResult) { + function filter(arr, testName, secondArg) { + if (testName === void 0) { + testName = "truthy"; + } + var context = this; + var test = context.env.getTest(testName); + return lib2.toArray(arr).filter(function examineTestResult(item) { + return test.call(context, item, secondArg) === expectedTestResult; + }); + } + return filter; + } + _exports.reject = getSelectOrReject(false); + function rejectattr(arr, attr) { + return arr.filter(function(item) { + return !item[attr]; + }); + } + _exports.rejectattr = rejectattr; + _exports.select = getSelectOrReject(true); + function selectattr(arr, attr) { + return arr.filter(function(item) { + return !!item[attr]; + }); + } + _exports.selectattr = selectattr; + function replace(str, old, new_, maxCount) { + var originalStr = str; + if (old instanceof RegExp) { + return str.replace(old, new_); + } + if (typeof maxCount === "undefined") { + maxCount = -1; + } + var res = ""; + if (typeof old === "number") { + old = "" + old; + } else if (typeof old !== "string") { + return str; + } + if (typeof str === "number") { + str = "" + str; + } + if (typeof str !== "string" && !(str instanceof r.SafeString)) { + return str; + } + if (old === "") { + res = new_ + str.split("").join(new_) + new_; + return r.copySafeness(str, res); + } + var nextIndex = str.indexOf(old); + if (maxCount === 0 || nextIndex === -1) { + return str; + } + var pos = 0; + var count = 0; + while (nextIndex > -1 && (maxCount === -1 || count < maxCount)) { + res += str.substring(pos, nextIndex) + new_; + pos = nextIndex + old.length; + count++; + nextIndex = str.indexOf(old, pos); + } + if (pos < str.length) { + res += str.substring(pos); + } + return r.copySafeness(originalStr, res); + } + _exports.replace = replace; + function reverse(val) { + var arr; + if (lib2.isString(val)) { + arr = list(val); + } else { + arr = lib2.map(val, function(v) { + return v; + }); + } + arr.reverse(); + if (lib2.isString(val)) { + return r.copySafeness(val, arr.join("")); + } + return arr; + } + _exports.reverse = reverse; + function round(val, precision, method) { + precision = precision || 0; + var factor = Math.pow(10, precision); + var rounder; + if (method === "ceil") { + rounder = Math.ceil; + } else if (method === "floor") { + rounder = Math.floor; + } else { + rounder = Math.round; + } + return rounder(val * factor) / factor; + } + _exports.round = round; + function slice(arr, slices, fillWith) { + var sliceLength = Math.floor(arr.length / slices); + var extra = arr.length % slices; + var res = []; + var offset = 0; + for (var i = 0; i < slices; i++) { + var start = offset + i * sliceLength; + if (i < extra) { + offset++; + } + var end = offset + (i + 1) * sliceLength; + var currSlice = arr.slice(start, end); + if (fillWith && i >= extra) { + currSlice.push(fillWith); + } + res.push(currSlice); + } + return res; + } + _exports.slice = slice; + function sum(arr, attr, start) { + if (start === void 0) { + start = 0; + } + if (attr) { + arr = lib2.map(arr, function(v) { + return v[attr]; + }); + } + return start + arr.reduce(function(a, b) { + return a + b; + }, 0); + } + _exports.sum = sum; + _exports.sort = r.makeMacro(["value", "reverse", "case_sensitive", "attribute"], [], function sortFilter(arr, reversed, caseSens, attr) { + var _this = this; + var array = lib2.map(arr, function(v) { + return v; + }); + var getAttribute = lib2.getAttrGetter(attr); + array.sort(function(a, b) { + var x = attr ? getAttribute(a) : a; + var y = attr ? getAttribute(b) : b; + if (_this.env.opts.throwOnUndefined && attr && (x === void 0 || y === void 0)) { + throw new TypeError('sort: attribute "' + attr + '" resolved to undefined'); + } + if (!caseSens && lib2.isString(x) && lib2.isString(y)) { + x = x.toLowerCase(); + y = y.toLowerCase(); + } + if (x < y) { + return reversed ? 1 : -1; + } else if (x > y) { + return reversed ? -1 : 1; + } else { + return 0; + } + }); + return array; + }); + function string(obj) { + return r.copySafeness(obj, obj); + } + _exports.string = string; + function striptags(input, preserveLinebreaks) { + input = normalize(input, ""); + var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|/gi; + var trimmedInput = trim(input.replace(tags, "")); + var res = ""; + if (preserveLinebreaks) { + res = trimmedInput.replace(/^ +| +$/gm, "").replace(/ +/g, " ").replace(/(\r\n)/g, "\n").replace(/\n\n\n+/g, "\n\n"); + } else { + res = trimmedInput.replace(/\s+/gi, " "); + } + return r.copySafeness(input, res); + } + _exports.striptags = striptags; + function title(str) { + str = normalize(str, ""); + var words = str.split(" ").map(function(word) { + return capitalize(word); + }); + return r.copySafeness(str, words.join(" ")); + } + _exports.title = title; + function trim(str) { + return r.copySafeness(str, str.replace(/^\s*|\s*$/g, "")); + } + _exports.trim = trim; + function truncate(input, length, killwords, end) { + var orig = input; + input = normalize(input, ""); + length = length || 255; + if (input.length <= length) { + return input; + } + if (killwords) { + input = input.substring(0, length); + } else { + var idx = input.lastIndexOf(" ", length); + if (idx === -1) { + idx = length; + } + input = input.substring(0, idx); + } + input += end !== void 0 && end !== null ? end : "..."; + return r.copySafeness(orig, input); + } + _exports.truncate = truncate; + function upper(str) { + str = normalize(str, ""); + return str.toUpperCase(); + } + _exports.upper = upper; + function urlencode(obj) { + var enc = encodeURIComponent; + if (lib2.isString(obj)) { + return enc(obj); + } else { + var keyvals = lib2.isArray(obj) ? obj : lib2._entries(obj); + return keyvals.map(function(_ref2) { + var k = _ref2[0], v = _ref2[1]; + return enc(k) + "=" + enc(v); + }).join("&"); + } + } + _exports.urlencode = urlencode; + var puncRe = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; + var emailRe = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i; + var httpHttpsRe = /^https?:\/\/.*$/; + var wwwRe = /^www\./; + var tldRe = /\.(?:org|net|com)(?:\:|\/|$)/; + function urlize(str, length, nofollow) { + if (isNaN2(length)) { + length = Infinity; + } + var noFollowAttr = nofollow === true ? ' rel="nofollow"' : ""; + var words = str.split(/(\s+)/).filter(function(word) { + return word && word.length; + }).map(function(word) { + var matches = word.match(puncRe); + var possibleUrl = matches ? matches[1] : word; + var shortUrl = possibleUrl.substr(0, length); + if (httpHttpsRe.test(possibleUrl)) { + return '" + shortUrl + ""; + } + if (wwwRe.test(possibleUrl)) { + return '" + shortUrl + ""; + } + if (emailRe.test(possibleUrl)) { + return '' + possibleUrl + ""; + } + if (tldRe.test(possibleUrl)) { + return '" + shortUrl + ""; + } + return word; + }); + return words.join(""); + } + _exports.urlize = urlize; + function wordcount(str) { + str = normalize(str, ""); + var words = str ? str.match(/\w+/g) : null; + return words ? words.length : null; + } + _exports.wordcount = wordcount; + function float(val, def) { + var res = parseFloat(val); + return isNaN2(res) ? def : res; + } + _exports.float = float; + var intFilter = r.makeMacro(["value", "default", "base"], [], function doInt(value, defaultValue, base) { + if (base === void 0) { + base = 10; + } + var res = parseInt(value, base); + return isNaN2(res) ? defaultValue : res; + }); + _exports.int = intFilter; + _exports.d = _exports.default; + _exports.e = _exports.escape; +}); + +// ../../node_modules/nunjucks/src/loader.js +var require_loader = __commonJS((exports2, module2) => { + "use strict"; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var path = require("path"); + var _require2 = require_object(); + var EmitterObj = _require2.EmitterObj; + module2.exports = /* @__PURE__ */ function(_EmitterObj) { + _inheritsLoose(Loader2, _EmitterObj); + function Loader2() { + return _EmitterObj.apply(this, arguments) || this; + } + var _proto = Loader2.prototype; + _proto.resolve = function resolve(from, to) { + return path.resolve(path.dirname(from), to); + }; + _proto.isRelative = function isRelative(filename) { + return filename.indexOf("./") === 0 || filename.indexOf("../") === 0; + }; + return Loader2; + }(EmitterObj); +}); + +// ../../node_modules/nunjucks/src/precompiled-loader.js +var require_precompiled_loader = __commonJS((exports2, module2) => { + "use strict"; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var Loader2 = require_loader(); + var PrecompiledLoader = /* @__PURE__ */ function(_Loader) { + _inheritsLoose(PrecompiledLoader2, _Loader); + function PrecompiledLoader2(compiledTemplates) { + var _this; + _this = _Loader.call(this) || this; + _this.precompiled = compiledTemplates || {}; + return _this; + } + var _proto = PrecompiledLoader2.prototype; + _proto.getSource = function getSource(name) { + if (this.precompiled[name]) { + return { + src: { + type: "code", + obj: this.precompiled[name] + }, + path: name + }; + } + return null; + }; + return PrecompiledLoader2; + }(Loader2); + module2.exports = { + PrecompiledLoader + }; +}); + +// ../../node_modules/picomatch/lib/constants.js +var require_constants = __commonJS((exports2, module2) => { + "use strict"; + var path = require("path"); + var WIN_SLASH = "\\\\/"; + var WIN_NO_SLASH = `[^${WIN_SLASH}]`; + var DOT_LITERAL = "\\."; + var PLUS_LITERAL = "\\+"; + var QMARK_LITERAL = "\\?"; + var SLASH_LITERAL = "\\/"; + var ONE_CHAR = "(?=.)"; + var QMARK = "[^/]"; + var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; + var START_ANCHOR = `(?:^|${SLASH_LITERAL})`; + var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; + var NO_DOT = `(?!${DOT_LITERAL})`; + var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; + var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; + var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; + var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; + var STAR = `${QMARK}*?`; + var POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR + }; + var WINDOWS_CHARS = { + ...POSIX_CHARS, + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` + }; + var POSIX_REGEX_SOURCE = { + alnum: "a-zA-Z0-9", + alpha: "a-zA-Z", + ascii: "\\x00-\\x7F", + blank: " \\t", + cntrl: "\\x00-\\x1F\\x7F", + digit: "0-9", + graph: "\\x21-\\x7E", + lower: "a-z", + print: "\\x20-\\x7E ", + punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", + space: " \\t\\r\\n\\v\\f", + upper: "A-Z", + word: "A-Za-z0-9_", + xdigit: "A-Fa-f0-9" + }; + module2.exports = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + REPLACEMENTS: { + "***": "*", + "**/**": "**", + "**/**/**": "**" + }, + CHAR_0: 48, + CHAR_9: 57, + CHAR_UPPERCASE_A: 65, + CHAR_LOWERCASE_A: 97, + CHAR_UPPERCASE_Z: 90, + CHAR_LOWERCASE_Z: 122, + CHAR_LEFT_PARENTHESES: 40, + CHAR_RIGHT_PARENTHESES: 41, + CHAR_ASTERISK: 42, + CHAR_AMPERSAND: 38, + CHAR_AT: 64, + CHAR_BACKWARD_SLASH: 92, + CHAR_CARRIAGE_RETURN: 13, + CHAR_CIRCUMFLEX_ACCENT: 94, + CHAR_COLON: 58, + CHAR_COMMA: 44, + CHAR_DOT: 46, + CHAR_DOUBLE_QUOTE: 34, + CHAR_EQUAL: 61, + CHAR_EXCLAMATION_MARK: 33, + CHAR_FORM_FEED: 12, + CHAR_FORWARD_SLASH: 47, + CHAR_GRAVE_ACCENT: 96, + CHAR_HASH: 35, + CHAR_HYPHEN_MINUS: 45, + CHAR_LEFT_ANGLE_BRACKET: 60, + CHAR_LEFT_CURLY_BRACE: 123, + CHAR_LEFT_SQUARE_BRACKET: 91, + CHAR_LINE_FEED: 10, + CHAR_NO_BREAK_SPACE: 160, + CHAR_PERCENT: 37, + CHAR_PLUS: 43, + CHAR_QUESTION_MARK: 63, + CHAR_RIGHT_ANGLE_BRACKET: 62, + CHAR_RIGHT_CURLY_BRACE: 125, + CHAR_RIGHT_SQUARE_BRACKET: 93, + CHAR_SEMICOLON: 59, + CHAR_SINGLE_QUOTE: 39, + CHAR_SPACE: 32, + CHAR_TAB: 9, + CHAR_UNDERSCORE: 95, + CHAR_VERTICAL_LINE: 124, + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, + SEP: path.sep, + extglobChars(chars) { + return { + "!": {type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})`}, + "?": {type: "qmark", open: "(?:", close: ")?"}, + "+": {type: "plus", open: "(?:", close: ")+"}, + "*": {type: "star", open: "(?:", close: ")*"}, + "@": {type: "at", open: "(?:", close: ")"} + }; + }, + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } + }; +}); + +// ../../node_modules/picomatch/lib/utils.js +var require_utils = __commonJS((exports2) => { + "use strict"; + var path = require("path"); + var win32 = process.platform === "win32"; + var { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = require_constants(); + exports2.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + exports2.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); + exports2.isRegexChar = (str) => str.length === 1 && exports2.hasRegexChars(str); + exports2.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); + exports2.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); + exports2.removeBackslashes = (str) => { + return str.replace(REGEX_REMOVE_BACKSLASH, (match) => { + return match === "\\" ? "" : match; + }); + }; + exports2.supportsLookbehinds = () => { + const segs = process.version.slice(1).split(".").map(Number); + if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { + return true; + } + return false; + }; + exports2.isWindows = (options) => { + if (options && typeof options.windows === "boolean") { + return options.windows; + } + return win32 === true || path.sep === "\\"; + }; + exports2.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) + return input; + if (input[idx - 1] === "\\") + return exports2.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + exports2.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith("./")) { + output = output.slice(2); + state.prefix = "./"; + } + return output; + }; + exports2.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? "" : "^"; + const append = options.contains ? "" : "$"; + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; + }; +}); + +// ../../node_modules/picomatch/lib/scan.js +var require_scan = __commonJS((exports2, module2) => { + "use strict"; + var utils = require_utils(); + var { + CHAR_ASTERISK, + CHAR_AT, + CHAR_BACKWARD_SLASH, + CHAR_COMMA, + CHAR_DOT, + CHAR_EXCLAMATION_MARK, + CHAR_FORWARD_SLASH, + CHAR_LEFT_CURLY_BRACE, + CHAR_LEFT_PARENTHESES, + CHAR_LEFT_SQUARE_BRACKET, + CHAR_PLUS, + CHAR_QUESTION_MARK, + CHAR_RIGHT_CURLY_BRACE, + CHAR_RIGHT_PARENTHESES, + CHAR_RIGHT_SQUARE_BRACKET + } = require_constants(); + var isPathSeparator = (code) => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; + }; + var depth = (token) => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } + }; + var scan = (input, options) => { + const opts = options || {}; + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = {value: "", depth: 0, isGlob: false}; + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + while (index < length) { + code = advance(); + let next; + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = {value: "", depth: 0, isGlob: false}; + if (finished === true) + continue; + if (prev === CHAR_DOT && index === start + 1) { + start += 2; + continue; + } + lastIndex = index + 1; + continue; + } + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) + isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + if (scanToEnd === true) { + continue; + } + break; + } + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + if (isGlob === true) { + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + } + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + let base = str; + let prefix = ""; + let glob = ""; + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ""; + glob = str; + } else { + base = str; + } + if (base && base !== "" && base !== "/" && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + if (opts.unescape === true) { + if (glob) + glob = utils.removeBackslashes(glob); + if (base && backslashes === true) { + base = utils.removeBackslashes(base); + } + } + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== "") { + parts.push(value); + } + prevIndex = i; + } + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + state.slashes = slashes; + state.parts = parts; + } + return state; + }; + module2.exports = scan; +}); + +// ../../node_modules/picomatch/lib/parse.js +var require_parse = __commonJS((exports2, module2) => { + "use strict"; + var constants = require_constants(); + var utils = require_utils(); + var { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS + } = constants; + var expandRange = (args, options) => { + if (typeof options.expandRange === "function") { + return options.expandRange(...args, options); + } + args.sort(); + const value = `[${args.join("-")}]`; + try { + new RegExp(value); + } catch (ex) { + return args.map((v) => utils.escapeRegex(v)).join(".."); + } + return value; + }; + var syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; + }; + var parse = (input, options) => { + if (typeof input !== "string") { + throw new TypeError("Expected a string"); + } + input = REPLACEMENTS[input] || input; + const opts = {...options}; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + const bos = {type: "bos", value: "", output: opts.prepend || ""}; + const tokens = [bos]; + const capture = opts.capture ? "" : "?:"; + const win32 = utils.isWindows(options); + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + const globstar = (opts2) => { + return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + const nodot = opts.dot ? "" : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + if (opts.capture) { + star = `(${star})`; + } + if (typeof opts.noext === "boolean") { + opts.noextglob = opts.noext; + } + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: "", + output: "", + prefix: "", + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + input = utils.removePrefix(input, state); + len = input.length; + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ""; + const remaining = () => input.slice(state.index + 1); + const consume = (value2 = "", num = 0) => { + state.consumed += value2; + state.index += num; + }; + const append = (token) => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + const negate = () => { + let count = 1; + while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { + advance(); + state.start++; + count++; + } + if (count % 2 === 0) { + return false; + } + state.negated = true; + state.start++; + return true; + }; + const increment = (type) => { + state[type]++; + stack.push(type); + }; + const decrement = (type) => { + state[type]--; + stack.pop(); + }; + const push = (tok) => { + if (prev.type === "globstar") { + const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); + const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); + if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = "star"; + prev.value = "*"; + prev.output = star; + state.output += prev.output; + } + } + if (extglobs.length && tok.type !== "paren") { + extglobs[extglobs.length - 1].inner += tok.value; + } + if (tok.value || tok.output) + append(tok); + if (prev && prev.type === "text" && tok.type === "text") { + prev.value += tok.value; + prev.output = (prev.output || "") + tok.value; + return; + } + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + const extglobOpen = (type, value2) => { + const token = {...EXTGLOB_CHARS[value2], conditions: 1, inner: ""}; + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? "(" : "") + token.open; + increment("parens"); + push({type, value: value2, output: state.output ? "" : ONE_CHAR}); + push({type: "paren", extglob: true, value: advance(), output}); + extglobs.push(token); + }; + const extglobClose = (token) => { + let output = token.close + (opts.capture ? ")" : ""); + let rest; + if (token.type === "negate") { + let extglobStar = star; + if (token.inner && token.inner.length > 1 && token.inner.includes("/")) { + extglobStar = globstar(opts); + } + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + output = token.close = `)${rest})${extglobStar})`; + } + if (token.prev.type === "bos") { + state.negatedExtglob = true; + } + } + push({type: "paren", extglob: true, value, output}); + decrement("parens"); + }; + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === "\\") { + backslashes = true; + return m; + } + if (first === "?") { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ""); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ""); + } + return QMARK.repeat(chars.length); + } + if (first === ".") { + return DOT_LITERAL.repeat(chars.length); + } + if (first === "*") { + if (esc) { + return esc + first + (rest ? star : ""); + } + return star; + } + return esc ? m : `\\${m}`; + }); + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ""); + } else { + output = output.replace(/\\+/g, (m) => { + return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; + }); + } + } + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + state.output = utils.wrapOutput(output, state, options); + return state; + } + while (!eos()) { + value = advance(); + if (value === "\0") { + continue; + } + if (value === "\\") { + const next = peek(); + if (next === "/" && opts.bash !== true) { + continue; + } + if (next === "." || next === ";") { + continue; + } + if (!next) { + value += "\\"; + push({type: "text", value}); + continue; + } + const match = /^\\+/.exec(remaining()); + let slashes = 0; + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += "\\"; + } + } + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + if (state.brackets === 0) { + push({type: "text", value}); + continue; + } + } + if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) { + if (opts.posix !== false && value === ":") { + const inner = prev.value.slice(1); + if (inner.includes("[")) { + prev.posix = true; + if (inner.includes(":")) { + const idx = prev.value.lastIndexOf("["); + const pre = prev.value.slice(0, idx); + const rest2 = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest2]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") { + value = `\\${value}`; + } + if (value === "]" && (prev.value === "[" || prev.value === "[^")) { + value = `\\${value}`; + } + if (opts.posix === true && value === "!" && prev.value === "[") { + value = "^"; + } + prev.value += value; + append({value}); + continue; + } + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({value}); + continue; + } + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({type: "text", value}); + } + continue; + } + if (value === "(") { + increment("parens"); + push({type: "paren", value}); + continue; + } + if (value === ")") { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError("opening", "(")); + } + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + push({type: "paren", value, output: state.parens ? ")" : "\\)"}); + decrement("parens"); + continue; + } + if (value === "[") { + if (opts.nobracket === true || !remaining().includes("]")) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError("closing", "]")); + } + value = `\\${value}`; + } else { + increment("brackets"); + } + push({type: "bracket", value}); + continue; + } + if (value === "]") { + if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { + push({type: "text", value, output: `\\${value}`}); + continue; + } + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError("opening", "[")); + } + push({type: "text", value, output: `\\${value}`}); + continue; + } + decrement("brackets"); + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) { + value = `/${value}`; + } + prev.value += value; + append({value}); + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + if (value === "{" && opts.nobrace !== true) { + increment("braces"); + const open = { + type: "brace", + value, + output: "(", + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + braces.push(open); + push(open); + continue; + } + if (value === "}") { + const brace = braces[braces.length - 1]; + if (opts.nobrace === true || !brace) { + push({type: "text", value, output: value}); + continue; + } + let output = ")"; + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === "brace") { + break; + } + if (arr[i].type !== "dots") { + range.unshift(arr[i].value); + } + } + output = expandRange(range, opts); + state.backtrack = true; + } + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = "\\{"; + value = output = "\\}"; + state.output = out; + for (const t of toks) { + state.output += t.output || t.value; + } + } + push({type: "brace", value, output}); + decrement("braces"); + braces.pop(); + continue; + } + if (value === "|") { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({type: "text", value}); + continue; + } + if (value === ",") { + let output = value; + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === "braces") { + brace.comma = true; + output = "|"; + } + push({type: "comma", value, output}); + continue; + } + if (value === "/") { + if (prev.type === "dot" && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ""; + state.output = ""; + tokens.pop(); + prev = bos; + continue; + } + push({type: "slash", value, output: SLASH_LITERAL}); + continue; + } + if (value === ".") { + if (state.braces > 0 && prev.type === "dot") { + if (prev.value === ".") + prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = "dots"; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { + push({type: "text", value, output: DOT_LITERAL}); + continue; + } + push({type: "dot", value, output: DOT_LITERAL}); + continue; + } + if (value === "?") { + const isGroup = prev && prev.value === "("; + if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + extglobOpen("qmark", value); + continue; + } + if (prev && prev.type === "paren") { + const next = peek(); + let output = value; + if (next === "<" && !utils.supportsLookbehinds()) { + throw new Error("Node.js v10 or higher is required for regex lookbehinds"); + } + if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) { + output = `\\${value}`; + } + push({type: "text", value, output}); + continue; + } + if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { + push({type: "qmark", value, output: QMARK_NO_DOT}); + continue; + } + push({type: "qmark", value, output: QMARK}); + continue; + } + if (value === "!") { + if (opts.noextglob !== true && peek() === "(") { + if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { + extglobOpen("negate", value); + continue; + } + } + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + if (value === "+") { + if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + extglobOpen("plus", value); + continue; + } + if (prev && prev.value === "(" || opts.regex === false) { + push({type: "plus", value, output: PLUS_LITERAL}); + continue; + } + if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { + push({type: "plus", value}); + continue; + } + push({type: "plus", value: PLUS_LITERAL}); + continue; + } + if (value === "@") { + if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + push({type: "at", extglob: true, value, output: ""}); + continue; + } + push({type: "text", value}); + continue; + } + if (value !== "*") { + if (value === "$" || value === "^") { + value = `\\${value}`; + } + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + push({type: "text", value}); + continue; + } + if (prev && (prev.type === "globstar" || prev.star === true)) { + prev.type = "star"; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen("star", value); + continue; + } + if (prev.type === "star") { + if (opts.noglobstar === true) { + consume(value); + continue; + } + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === "slash" || prior.type === "bos"; + const afterStar = before && (before.type === "star" || before.type === "globstar"); + if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { + push({type: "star", value, output: ""}); + continue; + } + const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); + const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); + if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) { + push({type: "star", value, output: ""}); + continue; + } + while (rest.slice(0, 3) === "/**") { + const after = input[state.index + 4]; + if (after && after !== "/") { + break; + } + rest = rest.slice(3); + consume("/**", 3); + } + if (prior.type === "bos" && eos()) { + prev.type = "globstar"; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = "globstar"; + prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { + const end = rest[1] !== void 0 ? "|$" : ""; + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = "globstar"; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + state.output += prior.output + prev.output; + state.globstar = true; + consume(value + advance()); + push({type: "slash", value: "/", output: ""}); + continue; + } + if (prior.type === "bos" && rest[0] === "/") { + prev.type = "globstar"; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({type: "slash", value: "/", output: ""}); + continue; + } + state.output = state.output.slice(0, -prev.output.length); + prev.type = "globstar"; + prev.output = globstar(opts); + prev.value += value; + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + const token = {type: "star", value, output: star}; + if (opts.bash === true) { + token.output = ".*?"; + if (prev.type === "bos" || prev.type === "slash") { + token.output = nodot + token.output; + } + push(token); + continue; + } + if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { + token.output = value; + push(token); + continue; + } + if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { + if (prev.type === "dot") { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + } else { + state.output += nodot; + prev.output += nodot; + } + if (peek() !== "*") { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + push(token); + } + while (state.brackets > 0) { + if (opts.strictBrackets === true) + throw new SyntaxError(syntaxError("closing", "]")); + state.output = utils.escapeLast(state.output, "["); + decrement("brackets"); + } + while (state.parens > 0) { + if (opts.strictBrackets === true) + throw new SyntaxError(syntaxError("closing", ")")); + state.output = utils.escapeLast(state.output, "("); + decrement("parens"); + } + while (state.braces > 0) { + if (opts.strictBrackets === true) + throw new SyntaxError(syntaxError("closing", "}")); + state.output = utils.escapeLast(state.output, "{"); + decrement("braces"); + } + if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) { + push({type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?`}); + } + if (state.backtrack === true) { + state.output = ""; + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + if (token.suffix) { + state.output += token.suffix; + } + } + } + return state; + }; + parse.fastpaths = (input, options) => { + const opts = {...options}; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? "" : "?:"; + const state = {negated: false, prefix: ""}; + let star = opts.bash === true ? ".*?" : STAR; + if (opts.capture) { + star = `(${star})`; + } + const globstar = (opts2) => { + if (opts2.noglobstar === true) + return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + const create = (str) => { + switch (str) { + case "*": + return `${nodot}${ONE_CHAR}${star}`; + case ".*": + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + case "*.*": + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + case "*/*": + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + case "**": + return nodot + globstar(opts); + case "**/*": + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + case "**/*.*": + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + case "**/.*": + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) + return; + const source2 = create(match[1]); + if (!source2) + return; + return source2 + DOT_LITERAL + match[2]; + } + } + }; + const output = utils.removePrefix(input, state); + let source = create(output); + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + return source; + }; + module2.exports = parse; +}); + +// ../../node_modules/picomatch/lib/picomatch.js +var require_picomatch = __commonJS((exports2, module2) => { + "use strict"; + var path = require("path"); + var scan = require_scan(); + var parse = require_parse(); + var utils = require_utils(); + var constants = require_constants(); + var isObject = (val) => val && typeof val === "object" && !Array.isArray(val); + var picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map((input) => picomatch(input, options, returnState)); + const arrayMatcher = (str) => { + for (const isMatch of fns) { + const state2 = isMatch(str); + if (state2) + return state2; + } + return false; + }; + return arrayMatcher; + } + const isState = isObject(glob) && glob.tokens && glob.input; + if (glob === "" || typeof glob !== "string" && !isState) { + throw new TypeError("Expected pattern to be a non-empty string"); + } + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); + const state = regex.state; + delete regex.state; + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = {...options, ignore: null, onMatch: null, onResult: null}; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + const matcher = (input, returnObject = false) => { + const {isMatch, match, output} = picomatch.test(input, regex, options, {glob, posix}); + const result = {glob, state, regex, posix, input, output, match, isMatch}; + if (typeof opts.onResult === "function") { + opts.onResult(result); + } + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + if (isIgnored(input)) { + if (typeof opts.onIgnore === "function") { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + if (typeof opts.onMatch === "function") { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + if (returnState) { + matcher.state = state; + } + return matcher; + }; + picomatch.test = (input, regex, options, {glob, posix} = {}) => { + if (typeof input !== "string") { + throw new TypeError("Expected input to be a string"); + } + if (input === "") { + return {isMatch: false, output: ""}; + } + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = match && format ? format(input) : input; + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + return {isMatch: Boolean(match), match, output}; + }; + picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path.basename(input)); + }; + picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) + return pattern.map((p) => picomatch.parse(p, options)); + return parse(pattern, {...options, fastpaths: false}); + }; + picomatch.scan = (input, options) => scan(input, options); + picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + const opts = options || {}; + const prepend = opts.contains ? "" : "^"; + const append = opts.contains ? "" : "$"; + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + return regex; + }; + picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== "string") { + throw new TypeError("Expected a non-empty string"); + } + let parsed = {negated: false, fastpaths: true}; + if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) { + parsed.output = parse.fastpaths(input, options); + } + if (!parsed.output) { + parsed = parse(input, options); + } + return picomatch.compileRe(parsed, options, returnOutput, returnState); + }; + picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); + } catch (err) { + if (options && options.debug === true) + throw err; + return /$^/; + } + }; + picomatch.constants = constants; + module2.exports = picomatch; +}); + +// ../../node_modules/picomatch/index.js +var require_picomatch2 = __commonJS((exports2, module2) => { + "use strict"; + module2.exports = require_picomatch(); +}); + +// ../../node_modules/readdirp/index.js +var require_readdirp = __commonJS((exports2, module2) => { + "use strict"; + var fs = require("fs"); + var {Readable} = require("stream"); + var sysPath = require("path"); + var {promisify} = require("util"); + var picomatch = require_picomatch2(); + var readdir = promisify(fs.readdir); + var stat = promisify(fs.stat); + var lstat = promisify(fs.lstat); + var realpath = promisify(fs.realpath); + var BANG = "!"; + var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR"; + var NORMAL_FLOW_ERRORS = new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]); + var FILE_TYPE = "files"; + var DIR_TYPE = "directories"; + var FILE_DIR_TYPE = "files_directories"; + var EVERYTHING_TYPE = "all"; + var ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; + var isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code); + var [maj, min] = process.versions.node.split(".").slice(0, 2).map((n) => Number.parseInt(n, 10)); + var wantBigintFsStats = process.platform === "win32" && (maj > 10 || maj === 10 && min >= 5); + var normalizeFilter = (filter) => { + if (filter === void 0) + return; + if (typeof filter === "function") + return filter; + if (typeof filter === "string") { + const glob = picomatch(filter.trim()); + return (entry) => glob(entry.basename); + } + if (Array.isArray(filter)) { + const positive = []; + const negative = []; + for (const item of filter) { + const trimmed = item.trim(); + if (trimmed.charAt(0) === BANG) { + negative.push(picomatch(trimmed.slice(1))); + } else { + positive.push(picomatch(trimmed)); + } + } + if (negative.length > 0) { + if (positive.length > 0) { + return (entry) => positive.some((f) => f(entry.basename)) && !negative.some((f) => f(entry.basename)); + } + return (entry) => !negative.some((f) => f(entry.basename)); + } + return (entry) => positive.some((f) => f(entry.basename)); + } + }; + var ReaddirpStream = class extends Readable { + static get defaultOptions() { + return { + root: ".", + fileFilter: (path) => true, + directoryFilter: (path) => true, + type: FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false + }; + } + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark || 4096 + }); + const opts = {...ReaddirpStream.defaultOptions, ...options}; + const {root, type} = opts; + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + const statMethod = opts.lstat ? lstat : stat; + if (wantBigintFsStats) { + this._stat = (path) => statMethod(path, {bigint: true}); + } else { + this._stat = statMethod; + } + this._maxDepth = opts.depth; + this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsEverything = type === EVERYTHING_TYPE; + this._root = sysPath.resolve(root); + this._isDirent = "Dirent" in fs && !opts.alwaysStat; + this._statsProp = this._isDirent ? "dirent" : "stats"; + this._rdOptions = {encoding: "utf8", withFileTypes: this._isDirent}; + this.parents = [this._exploreDir(root, 1)]; + this.reading = false; + this.parent = void 0; + } + async _read(batch) { + if (this.reading) + return; + this.reading = true; + try { + while (!this.destroyed && batch > 0) { + const {path, depth, files = []} = this.parent || {}; + if (files.length > 0) { + const slice = files.splice(0, batch).map((dirent) => this._formatEntry(dirent, path)); + for (const entry of await Promise.all(slice)) { + if (this.destroyed) + return; + const entryType = await this._getEntryType(entry); + if (entryType === "directory" && this._directoryFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + if (this.destroyed) + return; + } + } + } catch (error) { + this.destroy(error); + } finally { + this.reading = false; + } + } + async _exploreDir(path, depth) { + let files; + try { + files = await readdir(path, this._rdOptions); + } catch (error) { + this._onError(error); + } + return {files, depth, path}; + } + async _formatEntry(dirent, path) { + let entry; + try { + const basename = this._isDirent ? dirent.name : dirent; + const fullPath = sysPath.resolve(sysPath.join(path, basename)); + entry = {path: sysPath.relative(this._root, fullPath), fullPath, basename}; + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + } + return entry; + } + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit("warn", err); + } else { + this.destroy(err); + } + } + async _getEntryType(entry) { + const stats = entry && entry[this._statsProp]; + if (!stats) { + return; + } + if (stats.isFile()) { + return "file"; + } + if (stats.isDirectory()) { + return "directory"; + } + if (stats && stats.isSymbolicLink()) { + const full = entry.fullPath; + try { + const entryRealPath = await realpath(full); + const entryRealPathStats = await lstat(entryRealPath); + if (entryRealPathStats.isFile()) { + return "file"; + } + if (entryRealPathStats.isDirectory()) { + const len = entryRealPath.length; + if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) { + const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`); + recursiveError.code = RECURSIVE_ERROR_CODE; + return this._onError(recursiveError); + } + return "directory"; + } + } catch (error) { + this._onError(error); + } + } + } + _includeAsFile(entry) { + const stats = entry && entry[this._statsProp]; + return stats && this._wantsEverything && !stats.isDirectory(); + } + }; + var readdirp = (root, options = {}) => { + let type = options.entryType || options.type; + if (type === "both") + type = FILE_DIR_TYPE; + if (type) + options.type = type; + if (!root) { + throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)"); + } else if (typeof root !== "string") { + throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)"); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`); + } + options.root = root; + return new ReaddirpStream(options); + }; + var readdirpPromise = (root, options = {}) => { + return new Promise((resolve, reject) => { + const files = []; + readdirp(root, options).on("data", (entry) => files.push(entry)).on("end", () => resolve(files)).on("error", (error) => reject(error)); + }); + }; + readdirp.promise = readdirpPromise; + readdirp.ReaddirpStream = ReaddirpStream; + readdirp.default = readdirp; + module2.exports = readdirp; +}); + +// ../../node_modules/normalize-path/index.js +var require_normalize_path = __commonJS((exports2, module2) => { + /*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ + module2.exports = function(path, stripTrailing) { + if (typeof path !== "string") { + throw new TypeError("expected path to be a string"); + } + if (path === "\\" || path === "/") + return "/"; + var len = path.length; + if (len <= 1) + return path; + var prefix = ""; + if (len > 4 && path[3] === "\\") { + var ch = path[2]; + if ((ch === "?" || ch === ".") && path.slice(0, 2) === "\\\\") { + path = path.slice(2); + prefix = "//"; + } + } + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === "") { + segs.pop(); + } + return prefix + segs.join("/"); + }; +}); + +// ../../node_modules/anymatch/index.js +var require_anymatch = __commonJS((exports2, module2) => { + "use strict"; + Object.defineProperty(exports2, "__esModule", {value: true}); + var picomatch = require_picomatch2(); + var normalizePath = require_normalize_path(); + var BANG = "!"; + var DEFAULT_OPTIONS = {returnIndex: false}; + var arrify = (item) => Array.isArray(item) ? item : [item]; + var createPattern = (matcher, options) => { + if (typeof matcher === "function") { + return matcher; + } + if (typeof matcher === "string") { + const glob = picomatch(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; + }; + var matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== "string") { + throw new TypeError("anymatch: second argument must be a string: got " + Object.prototype.toString.call(_path)); + } + const path = normalizePath(_path); + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + return returnIndex ? -1 : false; + }; + var anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError("anymatch: specify first argument"); + } + const opts = typeof options === "boolean" ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + const mtchers = arrify(matchers); + const negatedGlobs = mtchers.filter((item) => typeof item === "string" && item.charAt(0) === BANG).map((item) => item.slice(1)).map((item) => picomatch(item, opts)); + const patterns = mtchers.filter((item) => typeof item !== "string" || typeof item === "string" && item.charAt(0) !== BANG).map((matcher) => createPattern(matcher, opts)); + if (testString == null) { + return (testString2, ri = false) => { + const returnIndex2 = typeof ri === "boolean" ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString2, returnIndex2); + }; + } + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + }; + anymatch.default = anymatch; + module2.exports = anymatch; +}); + +// ../../node_modules/is-extglob/index.js +var require_is_extglob = __commonJS((exports2, module2) => { + /*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + module2.exports = function isExtglob(str) { + if (typeof str !== "string" || str === "") { + return false; + } + var match; + while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) { + if (match[2]) + return true; + str = str.slice(match.index + match[0].length); + } + return false; + }; +}); + +// ../../node_modules/is-glob/index.js +var require_is_glob = __commonJS((exports2, module2) => { + /*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + var isExtglob = require_is_extglob(); + var chars = {"{": "}", "(": ")", "[": "]"}; + var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; + var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; + module2.exports = function isGlob(str, options) { + if (typeof str !== "string" || str === "") { + return false; + } + if (isExtglob(str)) { + return true; + } + var regex = strictRegex; + var match; + if (options && options.strict === false) { + regex = relaxedRegex; + } + while (match = regex.exec(str)) { + if (match[2]) + return true; + var idx = match.index + match[0].length; + var open = match[1]; + var close = open ? chars[open] : null; + if (open && close) { + var n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + str = str.slice(idx); + } + return false; + }; +}); + +// ../../node_modules/glob-parent/index.js +var require_glob_parent = __commonJS((exports2, module2) => { + "use strict"; + var isGlob = require_is_glob(); + var pathPosixDirname = require("path").posix.dirname; + var isWin32 = require("os").platform() === "win32"; + var slash = "/"; + var backslash = /\\/g; + var enclosure = /[\{\[].*[\}\]]$/; + var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; + var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + module2.exports = function globParent(str, opts) { + var options = Object.assign({flipBackslashes: true}, opts); + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + if (enclosure.test(str)) { + str += slash; + } + str += "a"; + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + return str.replace(escaped, "$1"); + }; +}); + +// ../../node_modules/chokidar/node_modules/braces/lib/utils.js +var require_utils2 = __commonJS((exports2) => { + "use strict"; + exports2.isInteger = (num) => { + if (typeof num === "number") { + return Number.isInteger(num); + } + if (typeof num === "string" && num.trim() !== "") { + return Number.isInteger(Number(num)); + } + return false; + }; + exports2.find = (node, type) => node.nodes.find((node2) => node2.type === type); + exports2.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) + return false; + if (!exports2.isInteger(min) || !exports2.isInteger(max)) + return false; + return (Number(max) - Number(min)) / Number(step) >= limit; + }; + exports2.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) + return; + if (type && node.type === type || node.type === "open" || node.type === "close") { + if (node.escaped !== true) { + node.value = "\\" + node.value; + node.escaped = true; + } + } + }; + exports2.encloseBrace = (node) => { + if (node.type !== "brace") + return false; + if (node.commas >> 0 + node.ranges >> 0 === 0) { + node.invalid = true; + return true; + } + return false; + }; + exports2.isInvalidBrace = (block) => { + if (block.type !== "brace") + return false; + if (block.invalid === true || block.dollar) + return true; + if (block.commas >> 0 + block.ranges >> 0 === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; + }; + exports2.isOpenOrClose = (node) => { + if (node.type === "open" || node.type === "close") { + return true; + } + return node.open === true || node.close === true; + }; + exports2.reduce = (nodes2) => nodes2.reduce((acc, node) => { + if (node.type === "text") + acc.push(node.value); + if (node.type === "range") + node.type = "text"; + return acc; + }, []); + exports2.flatten = (...args) => { + const result = []; + const flat = (arr) => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; + }; +}); + +// ../../node_modules/chokidar/node_modules/braces/lib/stringify.js +var require_stringify = __commonJS((exports2, module2) => { + "use strict"; + var utils = require_utils2(); + module2.exports = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ""; + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return "\\" + node.value; + } + return node.value; + } + if (node.value) { + return node.value; + } + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + return stringify(ast); + }; +}); + +// ../../node_modules/chokidar/node_modules/is-number/index.js +var require_is_number = __commonJS((exports2, module2) => { + /*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + "use strict"; + module2.exports = function(num) { + if (typeof num === "number") { + return num - num === 0; + } + if (typeof num === "string" && num.trim() !== "") { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; + }; +}); + +// ../../node_modules/chokidar/node_modules/to-regex-range/index.js +var require_to_regex_range = __commonJS((exports2, module2) => { + /*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + "use strict"; + var isNumber = require_is_number(); + var toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError("toRegexRange: expected the first argument to be a number"); + } + if (max === void 0 || min === max) { + return String(min); + } + if (isNumber(max) === false) { + throw new TypeError("toRegexRange: expected the second argument to be a number."); + } + let opts = {relaxZeros: true, ...options}; + if (typeof opts.strictZeros === "boolean") { + opts.relaxZeros = opts.strictZeros === false; + } + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ":" + max + "=" + relax + shorthand + capture + wrap; + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + let a = Math.min(min, max); + let b = Math.max(min, max); + if (Math.abs(a - b) === 1) { + let result = min + "|" + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + let isPadded = hasPadding(min) || hasPadding(max); + let state = {min, max, a, b}; + let positives = []; + let negatives = []; + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && positives.length + negatives.length > 1) { + state.result = `(?:${state.result})`; + } + toRegexRange.cache[cacheKey] = state; + return state.result; + }; + function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, "-", false, options) || []; + let onlyPositive = filterPatterns(pos, neg, "", false, options) || []; + let intersected = filterPatterns(neg, pos, "-?", true, options) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join("|"); + } + function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + let stop = countNines(min, nines); + let stops = new Set([max]); + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + stop = countZeros(max + 1, zeros) - 1; + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + stops = [...stops]; + stops.sort(compare); + return stops; + } + function rangeToPattern(start, stop, options) { + if (start === stop) { + return {pattern: start, count: [], digits: 0}; + } + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ""; + let count = 0; + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + if (startDigit === stopDigit) { + pattern += startDigit; + } else if (startDigit !== "0" || stopDigit !== "9") { + pattern += toCharacterClass(startDigit, stopDigit, options); + } else { + count++; + } + } + if (count) { + pattern += options.shorthand === true ? "\\d" : "[0-9]"; + } + return {pattern, count: [count], digits}; + } + function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + for (let i = 0; i < ranges.length; i++) { + let max2 = ranges[i]; + let obj = rangeToPattern(String(start), String(max2), options); + let zeros = ""; + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max2 + 1; + continue; + } + if (tok.isPadded) { + zeros = padZeros(max2, tok, options); + } + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max2 + 1; + prev = obj; + } + return tokens; + } + function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + for (let ele of arr) { + let {string} = ele; + if (!intersection && !contains(comparison, "string", string)) { + result.push(prefix + string); + } + if (intersection && contains(comparison, "string", string)) { + result.push(prefix + string); + } + } + return result; + } + function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) + arr.push([a[i], b[i]]); + return arr; + } + function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; + } + function contains(arr, key, val) { + return arr.some((ele) => ele[key] === val); + } + function countNines(min, len) { + return Number(String(min).slice(0, -len) + "9".repeat(len)); + } + function countZeros(integer, zeros) { + return integer - integer % Math.pow(10, zeros); + } + function toQuantifier(digits) { + let [start = 0, stop = ""] = digits; + if (stop || start > 1) { + return `{${start + (stop ? "," + stop : "")}}`; + } + return ""; + } + function toCharacterClass(a, b, options) { + return `[${a}${b - a === 1 ? "" : "-"}${b}]`; + } + function hasPadding(str) { + return /^-?(0+)\d/.test(str); + } + function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + switch (diff) { + case 0: + return ""; + case 1: + return relax ? "0?" : "0"; + case 2: + return relax ? "0{0,2}" : "00"; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } + } + toRegexRange.cache = {}; + toRegexRange.clearCache = () => toRegexRange.cache = {}; + module2.exports = toRegexRange; +}); + +// ../../node_modules/chokidar/node_modules/fill-range/index.js +var require_fill_range = __commonJS((exports2, module2) => { + /*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + "use strict"; + var util = require("util"); + var toRegexRange = require_to_regex_range(); + var isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + var transform = (toNumber) => { + return (value) => toNumber === true ? Number(value) : String(value); + }; + var isValidValue = (value) => { + return typeof value === "number" || typeof value === "string" && value !== ""; + }; + var isNumber = (num) => Number.isInteger(+num); + var zeros = (input) => { + let value = `${input}`; + let index = -1; + if (value[0] === "-") + value = value.slice(1); + if (value === "0") + return false; + while (value[++index] === "0") + ; + return index > 0; + }; + var stringify = (start, end, options) => { + if (typeof start === "string" || typeof end === "string") { + return true; + } + return options.stringify === true; + }; + var pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === "-" ? "-" : ""; + if (dash) + input = input.slice(1); + input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0"); + } + if (toNumber === false) { + return String(input); + } + return input; + }; + var toMaxLen = (input, maxLength) => { + let negative = input[0] === "-" ? "-" : ""; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) + input = "0" + input; + return negative ? "-" + input : input; + }; + var toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + let prefix = options.capture ? "" : "?:"; + let positives = ""; + let negatives = ""; + let result; + if (parts.positives.length) { + positives = parts.positives.join("|"); + } + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join("|")})`; + } + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + if (options.wrap) { + return `(${prefix}${result})`; + } + return result; + }; + var toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, {wrap: false, ...options}); + } + let start = String.fromCharCode(a); + if (a === b) + return start; + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; + }; + var toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? "" : "?:"; + return wrap ? `(${prefix}${start.join("|")})` : start.join("|"); + } + return toRegexRange(start, end, options); + }; + var rangeError = (...args) => { + return new RangeError("Invalid range arguments: " + util.inspect(...args)); + }; + var invalidRange = (start, end, options) => { + if (options.strictRanges === true) + throw rangeError([start, end]); + return []; + }; + var invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; + }; + var fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) + throw rangeError([start, end]); + return []; + } + if (a === 0) + a = 0; + if (b === 0) + b = 0; + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + let parts = {negatives: [], positives: []}; + let push = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num)); + let range = []; + let index = 0; + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + if (options.toRegex === true) { + return step > 1 ? toSequence(parts, options) : toRegex(range, null, {wrap: false, ...options}); + } + return range; + }; + var fillLetters = (start, end, step = 1, options = {}) => { + if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) { + return invalidRange(start, end, options); + } + let format = options.transform || ((val) => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + let range = []; + let index = 0; + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + if (options.toRegex === true) { + return toRegex(range, null, {wrap: false, options}); + } + return range; + }; + var fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + if (typeof step === "function") { + return fill(start, end, 1, {transform: step}); + } + if (isObject(step)) { + return fill(start, end, 0, step); + } + let opts = {...options}; + if (opts.capture === true) + opts.wrap = true; + step = step || opts.step || 1; + if (!isNumber(step)) { + if (step != null && !isObject(step)) + return invalidStep(step, opts); + return fill(start, end, 1, step); + } + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); + }; + module2.exports = fill; +}); + +// ../../node_modules/chokidar/node_modules/braces/lib/compile.js +var require_compile = __commonJS((exports2, module2) => { + "use strict"; + var fill = require_fill_range(); + var utils = require_utils2(); + var compile2 = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? "\\" : ""; + let output = ""; + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + if (node.type === "open") { + return invalid ? prefix + node.value : "("; + } + if (node.type === "close") { + return invalid ? prefix + node.value : ")"; + } + if (node.type === "comma") { + return node.prev.type === "comma" ? "" : invalid ? node.value : "|"; + } + if (node.value) { + return node.value; + } + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + let range = fill(...args, {...options, wrap: false, toRegex: true}); + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + return walk(ast); + }; + module2.exports = compile2; +}); + +// ../../node_modules/chokidar/node_modules/braces/lib/expand.js +var require_expand = __commonJS((exports2, module2) => { + "use strict"; + var fill = require_fill_range(); + var stringify = require_stringify(); + var utils = require_utils2(); + var append = (queue = "", stash = "", enclose = false) => { + let result = []; + queue = [].concat(queue); + stash = [].concat(stash); + if (!stash.length) + return queue; + if (!queue.length) { + return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash; + } + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === "string") + ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + } + } + return utils.flatten(result); + }; + var expand = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1e3 : options.rangeLimit; + let walk = (node, parent = {}) => { + node.queue = []; + let p = parent; + let q = parent.queue; + while (p.type !== "brace" && p.type !== "root" && p.parent) { + p = p.parent; + q = p.queue; + } + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ["{}"])); + return; + } + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit."); + } + let range = fill(...args, options); + if (range.length === 0) { + range = stringify(node, options); + } + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + let enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + while (block.type !== "brace" && block.type !== "root" && block.parent) { + block = block.parent; + queue = block.queue; + } + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + if (child.type === "comma" && node.type === "brace") { + if (i === 1) + queue.push(""); + queue.push(""); + continue; + } + if (child.type === "close") { + q.push(append(q.pop(), queue, enclose)); + continue; + } + if (child.value && child.type !== "open") { + queue.push(append(queue.pop(), child.value)); + continue; + } + if (child.nodes) { + walk(child, node); + } + } + return queue; + }; + return utils.flatten(walk(ast)); + }; + module2.exports = expand; +}); + +// ../../node_modules/chokidar/node_modules/braces/lib/constants.js +var require_constants2 = __commonJS((exports2, module2) => { + "use strict"; + module2.exports = { + MAX_LENGTH: 1024 * 64, + CHAR_0: "0", + CHAR_9: "9", + CHAR_UPPERCASE_A: "A", + CHAR_LOWERCASE_A: "a", + CHAR_UPPERCASE_Z: "Z", + CHAR_LOWERCASE_Z: "z", + CHAR_LEFT_PARENTHESES: "(", + CHAR_RIGHT_PARENTHESES: ")", + CHAR_ASTERISK: "*", + CHAR_AMPERSAND: "&", + CHAR_AT: "@", + CHAR_BACKSLASH: "\\", + CHAR_BACKTICK: "`", + CHAR_CARRIAGE_RETURN: "\r", + CHAR_CIRCUMFLEX_ACCENT: "^", + CHAR_COLON: ":", + CHAR_COMMA: ",", + CHAR_DOLLAR: "$", + CHAR_DOT: ".", + CHAR_DOUBLE_QUOTE: '"', + CHAR_EQUAL: "=", + CHAR_EXCLAMATION_MARK: "!", + CHAR_FORM_FEED: "\f", + CHAR_FORWARD_SLASH: "/", + CHAR_HASH: "#", + CHAR_HYPHEN_MINUS: "-", + CHAR_LEFT_ANGLE_BRACKET: "<", + CHAR_LEFT_CURLY_BRACE: "{", + CHAR_LEFT_SQUARE_BRACKET: "[", + CHAR_LINE_FEED: "\n", + CHAR_NO_BREAK_SPACE: "\xA0", + CHAR_PERCENT: "%", + CHAR_PLUS: "+", + CHAR_QUESTION_MARK: "?", + CHAR_RIGHT_ANGLE_BRACKET: ">", + CHAR_RIGHT_CURLY_BRACE: "}", + CHAR_RIGHT_SQUARE_BRACKET: "]", + CHAR_SEMICOLON: ";", + CHAR_SINGLE_QUOTE: "'", + CHAR_SPACE: " ", + CHAR_TAB: " ", + CHAR_UNDERSCORE: "_", + CHAR_VERTICAL_LINE: "|", + CHAR_ZERO_WIDTH_NOBREAK_SPACE: "\uFEFF" + }; +}); + +// ../../node_modules/chokidar/node_modules/braces/lib/parse.js +var require_parse2 = __commonJS((exports2, module2) => { + "use strict"; + var stringify = require_stringify(); + var { + MAX_LENGTH, + CHAR_BACKSLASH, + CHAR_BACKTICK, + CHAR_COMMA, + CHAR_DOT, + CHAR_LEFT_PARENTHESES, + CHAR_RIGHT_PARENTHESES, + CHAR_LEFT_CURLY_BRACE, + CHAR_RIGHT_CURLY_BRACE, + CHAR_LEFT_SQUARE_BRACKET, + CHAR_RIGHT_SQUARE_BRACKET, + CHAR_DOUBLE_QUOTE, + CHAR_SINGLE_QUOTE, + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE + } = require_constants2(); + var parse = (input, options = {}) => { + if (typeof input !== "string") { + throw new TypeError("Expected a string"); + } + let opts = options || {}; + let max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + let ast = {type: "root", input, nodes: []}; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + let memo = {}; + const advance = () => input[index++]; + const push = (node) => { + if (node.type === "text" && prev.type === "dot") { + prev.type = "text"; + } + if (prev && prev.type === "text" && node.type === "text") { + prev.value += node.value; + return; + } + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + push({type: "bos"}); + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + if (value === CHAR_BACKSLASH) { + push({type: "text", value: (options.keepEscaping ? value : "") + advance()}); + continue; + } + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({type: "text", value: "\\" + value}); + continue; + } + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + let closed = true; + let next; + while (index < length && (next = advance())) { + value += next; + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + if (brackets === 0) { + break; + } + } + } + push({type: "text", value}); + continue; + } + if (value === CHAR_LEFT_PARENTHESES) { + block = push({type: "paren", nodes: []}); + stack.push(block); + push({type: "text", value}); + continue; + } + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== "paren") { + push({type: "text", value}); + continue; + } + block = stack.pop(); + push({type: "text", value}); + block = stack[stack.length - 1]; + continue; + } + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + if (options.keepQuotes !== true) { + value = ""; + } + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + if (next === open) { + if (options.keepQuotes === true) + value += next; + break; + } + value += next; + } + push({type: "text", value}); + continue; + } + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + let dollar = prev.value && prev.value.slice(-1) === "$" || block.dollar === true; + let brace = { + type: "brace", + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + block = push(brace); + stack.push(block); + push({type: "open", value}); + continue; + } + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== "brace") { + push({type: "text", value}); + continue; + } + let type = "close"; + block = stack.pop(); + block.close = true; + push({type, value}); + depth--; + block = stack[stack.length - 1]; + continue; + } + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, {type: "text", value: stringify(block)}]; + } + push({type: "comma", value}); + block.commas++; + continue; + } + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + if (depth === 0 || siblings.length === 0) { + push({type: "text", value}); + continue; + } + if (prev.type === "dot") { + block.range = []; + prev.value += value; + prev.type = "range"; + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = "text"; + continue; + } + block.ranges++; + block.args = []; + continue; + } + if (prev.type === "range") { + siblings.pop(); + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + push({type: "dot", value}); + continue; + } + push({type: "text", value}); + } + do { + block = stack.pop(); + if (block.type !== "root") { + block.nodes.forEach((node) => { + if (!node.nodes) { + if (node.type === "open") + node.isOpen = true; + if (node.type === "close") + node.isClose = true; + if (!node.nodes) + node.type = "text"; + node.invalid = true; + } + }); + let parent = stack[stack.length - 1]; + let index2 = parent.nodes.indexOf(block); + parent.nodes.splice(index2, 1, ...block.nodes); + } + } while (stack.length > 0); + push({type: "eos"}); + return ast; + }; + module2.exports = parse; +}); + +// ../../node_modules/chokidar/node_modules/braces/index.js +var require_braces = __commonJS((exports2, module2) => { + "use strict"; + var stringify = require_stringify(); + var compile2 = require_compile(); + var expand = require_expand(); + var parse = require_parse2(); + var braces = (input, options = {}) => { + let output = []; + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; + }; + braces.parse = (input, options = {}) => parse(input, options); + braces.stringify = (input, options = {}) => { + if (typeof input === "string") { + return stringify(braces.parse(input, options), options); + } + return stringify(input, options); + }; + braces.compile = (input, options = {}) => { + if (typeof input === "string") { + input = braces.parse(input, options); + } + return compile2(input, options); + }; + braces.expand = (input, options = {}) => { + if (typeof input === "string") { + input = braces.parse(input, options); + } + let result = expand(input, options); + if (options.noempty === true) { + result = result.filter(Boolean); + } + if (options.nodupes === true) { + result = [...new Set(result)]; + } + return result; + }; + braces.create = (input, options = {}) => { + if (input === "" || input.length < 3) { + return [input]; + } + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); + }; + module2.exports = braces; +}); + +// ../../node_modules/binary-extensions/binary-extensions.json +var require_binary_extensions = __commonJS((exports2, module2) => { + module2.exports = [ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "oga", + "ogg", + "ogv", + "otf", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" + ]; +}); + +// ../../node_modules/binary-extensions/index.js +var require_binary_extensions2 = __commonJS((exports2, module2) => { + module2.exports = require_binary_extensions(); +}); + +// ../../node_modules/is-binary-path/index.js +var require_is_binary_path = __commonJS((exports2, module2) => { + "use strict"; + var path = require("path"); + var binaryExtensions = require_binary_extensions2(); + var extensions = new Set(binaryExtensions); + module2.exports = (filePath) => extensions.has(path.extname(filePath).slice(1).toLowerCase()); +}); + +// ../../node_modules/chokidar/lib/constants.js +var require_constants3 = __commonJS((exports2) => { + "use strict"; + var {sep} = require("path"); + var {platform} = process; + var os = require("os"); + exports2.EV_ALL = "all"; + exports2.EV_READY = "ready"; + exports2.EV_ADD = "add"; + exports2.EV_CHANGE = "change"; + exports2.EV_ADD_DIR = "addDir"; + exports2.EV_UNLINK = "unlink"; + exports2.EV_UNLINK_DIR = "unlinkDir"; + exports2.EV_RAW = "raw"; + exports2.EV_ERROR = "error"; + exports2.STR_DATA = "data"; + exports2.STR_END = "end"; + exports2.STR_CLOSE = "close"; + exports2.FSEVENT_CREATED = "created"; + exports2.FSEVENT_MODIFIED = "modified"; + exports2.FSEVENT_DELETED = "deleted"; + exports2.FSEVENT_MOVED = "moved"; + exports2.FSEVENT_CLONED = "cloned"; + exports2.FSEVENT_UNKNOWN = "unknown"; + exports2.FSEVENT_TYPE_FILE = "file"; + exports2.FSEVENT_TYPE_DIRECTORY = "directory"; + exports2.FSEVENT_TYPE_SYMLINK = "symlink"; + exports2.KEY_LISTENERS = "listeners"; + exports2.KEY_ERR = "errHandlers"; + exports2.KEY_RAW = "rawEmitters"; + exports2.HANDLER_KEYS = [exports2.KEY_LISTENERS, exports2.KEY_ERR, exports2.KEY_RAW]; + exports2.DOT_SLASH = `.${sep}`; + exports2.BACK_SLASH_RE = /\\/g; + exports2.DOUBLE_SLASH_RE = /\/\//; + exports2.SLASH_OR_BACK_SLASH_RE = /[/\\]/; + exports2.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; + exports2.REPLACER_RE = /^\.[/\\]/; + exports2.SLASH = "/"; + exports2.SLASH_SLASH = "//"; + exports2.BRACE_START = "{"; + exports2.BANG = "!"; + exports2.ONE_DOT = "."; + exports2.TWO_DOTS = ".."; + exports2.STAR = "*"; + exports2.GLOBSTAR = "**"; + exports2.ROOT_GLOBSTAR = "/**/*"; + exports2.SLASH_GLOBSTAR = "/**"; + exports2.DIR_SUFFIX = "Dir"; + exports2.ANYMATCH_OPTS = {dot: true}; + exports2.STRING_TYPE = "string"; + exports2.FUNCTION_TYPE = "function"; + exports2.EMPTY_STR = ""; + exports2.EMPTY_FN = () => { + }; + exports2.IDENTITY_FN = (val) => val; + exports2.isWindows = platform === "win32"; + exports2.isMacos = platform === "darwin"; + exports2.isLinux = platform === "linux"; + exports2.isIBMi = os.type() === "OS400"; +}); + +// ../../node_modules/chokidar/lib/nodefs-handler.js +var require_nodefs_handler = __commonJS((exports2, module2) => { + "use strict"; + var fs = require("fs"); + var sysPath = require("path"); + var {promisify} = require("util"); + var isBinaryPath = require_is_binary_path(); + var { + isWindows, + isLinux, + EMPTY_FN, + EMPTY_STR, + KEY_LISTENERS, + KEY_ERR, + KEY_RAW, + HANDLER_KEYS, + EV_CHANGE, + EV_ADD, + EV_ADD_DIR, + EV_ERROR, + STR_DATA, + STR_END, + BRACE_START, + STAR + } = require_constants3(); + var THROTTLE_MODE_WATCH = "watch"; + var open = promisify(fs.open); + var stat = promisify(fs.stat); + var lstat = promisify(fs.lstat); + var close = promisify(fs.close); + var fsrealpath = promisify(fs.realpath); + var statMethods = {lstat, stat}; + var foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } + }; + var addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = new Set([container]); + } + container.add(item); + }; + var clearItem = (cont) => (key) => { + const set = cont[key]; + if (set instanceof Set) { + set.clear(); + } else { + delete cont[key]; + } + }; + var delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } + }; + var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; + var FsWatchInstances = new Map(); + function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path); + emitRaw(rawEvent, evPath, {watchedPath: path}); + if (evPath && path !== evPath) { + fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)); + } + }; + try { + return fs.watch(path, options, handleEvent); + } catch (error) { + errHandler(error); + } + } + var fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) + return; + foreach(cont[type], (listener) => { + listener(val1, val2, val3); + }); + }; + var setFsWatchListener = (path, fullPath, options, handlers) => { + const {listener, errHandler, rawEmitter} = handlers; + let cont = FsWatchInstances.get(fullPath); + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter); + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW)); + if (!watcher) + return; + watcher.on(EV_ERROR, async (error) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + cont.watcherUnusable = true; + if (isWindows && error.code === "EPERM") { + try { + const fd = await open(path, "r"); + await close(fd); + broadcastErr(error); + } catch (err) { + } + } else { + broadcastErr(error); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + cont.watcher.close(); + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = void 0; + Object.freeze(cont); + } + }; + }; + var FsWatchFileInstances = new Map(); + var setFsWatchFileListener = (path, fullPath, options, handlers) => { + const {listener, rawEmitter} = handlers; + let cont = FsWatchFileInstances.get(fullPath); + let listeners = new Set(); + let rawEmitters = new Set(); + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + listeners = cont.listeners; + rawEmitters = cont.rawEmitters; + fs.unwatchFile(fullPath); + cont = void 0; + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: fs.watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter2) => { + rawEmitter2(EV_CHANGE, fullPath, {curr, prev}); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener2) => listener2(path, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + fs.unwatchFile(fullPath); + cont.options = cont.watcher = void 0; + Object.freeze(cont); + } + }; + }; + var NodeFsHandler = class { + constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error) => fsW._handleError(error); + } + _watchWithNodeFs(path, listener) { + const opts = this.fsw.options; + const directory = sysPath.dirname(path); + const basename = sysPath.basename(path); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename); + const absolutePath = sysPath.resolve(path); + const options = {persistent: opts.persistent}; + if (!listener) + listener = EMPTY_FN; + let closer; + if (opts.usePolling) { + options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; + } + _handleFile(file, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname = sysPath.dirname(file); + const basename = sysPath.basename(file); + const parent = this.fsw._getWatchedDir(dirname); + let prevStats = stats; + if (parent.has(basename)) + return; + const listener = async (path, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) + return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats2 = await stat(file); + if (this.fsw.closed) + return; + const at = newStats2.atimeMs; + const mt = newStats2.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats2); + } + if (isLinux && prevStats.ino !== newStats2.ino) { + this.fsw._closeFile(path); + prevStats = newStats2; + this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener)); + } else { + prevStats = newStats2; + } + } catch (error) { + this.fsw._remove(dirname, basename); + } + } else if (parent.has(basename)) { + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } + }; + const closer = this._watchWithNodeFs(file, listener); + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { + if (!this.fsw._throttle(EV_ADD, file, 0)) + return; + this.fsw._emit(EV_ADD, file, stats); + } + return closer; + } + async _handleSymlink(entry, directory, path, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + if (!this.fsw.options.followSymlinks) { + this.fsw._incrReadyCount(); + const linkPath = await fsrealpath(path); + if (this.fsw.closed) + return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_CHANGE, path, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_ADD, path, entry.stats); + } + this.fsw._emitReady(); + return true; + } + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + this.fsw._symlinkPaths.set(full, true); + } + _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + directory = sysPath.join(directory, EMPTY_STR); + if (!wh.hasGlob) { + throttler = this.fsw._throttle("readdir", directory, 1e3); + if (!throttler) + return; + } + const previous = this.fsw._getWatchedDir(wh.path); + const current = new Set(); + let stream = this.fsw._readdirp(directory, { + fileFilter: (entry) => wh.filterPath(entry), + directoryFilter: (entry) => wh.filterDir(entry), + depth: 0 + }).on(STR_DATA, async (entry) => { + if (this.fsw.closed) { + stream = void 0; + return; + } + const item = entry.path; + let path = sysPath.join(directory, item); + current.add(item); + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { + return; + } + if (this.fsw.closed) { + stream = void 0; + return; + } + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + path = sysPath.join(dir, sysPath.relative(dir, path)); + this._addToNodeFs(path, initialAdd, wh, depth + 1); + } + }).on(EV_ERROR, this._boundHandleError); + return new Promise((resolve) => stream.once(STR_END, () => { + if (this.fsw.closed) { + stream = void 0; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + resolve(); + previous.getChildren().filter((item) => { + return item !== directory && !current.has(item) && (!wh.hasGlob || wh.filterPath({ + fullPath: sysPath.resolve(directory, item) + })); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + stream = void 0; + if (wasThrottled) + this._handleRead(directory, false, wh, target, dir, depth, throttler); + })); + } + async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { + const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); + const tracked = parentDir.has(sysPath.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + if (!wh.hasGlob || wh.globFilter(dir)) + this.fsw._emit(EV_ADD_DIR, dir, stats); + } + parentDir.add(sysPath.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) + return; + } + closer = this._watchWithNodeFs(dir, (dirPath, stats2) => { + if (stats2 && stats2.mtimeMs === 0) + return; + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; + } + async _addToNodeFs(path, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path) || this.fsw.closed) { + ready(); + return false; + } + const wh = this.fsw._getWatchHelpers(path, depth); + if (!wh.hasGlob && priorWh) { + wh.hasGlob = priorWh.hasGlob; + wh.globFilter = priorWh.globFilter; + wh.filterPath = (entry) => priorWh.filterPath(entry); + wh.filterDir = (entry) => priorWh.filterDir(entry); + } + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) + return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START); + let closer; + if (stats.isDirectory()) { + const absPath = sysPath.resolve(path); + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) + return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) + return; + if (absPath !== targetPath && targetPath !== void 0) { + this.fsw._symlinkPaths.set(absPath, targetPath); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) + return; + const parent = sysPath.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV_ADD, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); + if (this.fsw.closed) + return; + if (targetPath !== void 0) { + this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + this.fsw._addPathCloser(path, closer); + return false; + } catch (error) { + if (this.fsw._handleError(error)) { + ready(); + return path; + } + } + } + }; + module2.exports = NodeFsHandler; +}); + +// ../../node_modules/chokidar/lib/fsevents-handler.js +var require_fsevents_handler = __commonJS((exports2, module2) => { + "use strict"; + var fs = require("fs"); + var sysPath = require("path"); + var {promisify} = require("util"); + var fsevents; + try { + fsevents = require("fsevents"); + } catch (error) { + if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) + console.error(error); + } + if (fsevents) { + const mtch = process.version.match(/v(\d+)\.(\d+)/); + if (mtch && mtch[1] && mtch[2]) { + const maj = Number.parseInt(mtch[1], 10); + const min = Number.parseInt(mtch[2], 10); + if (maj === 8 && min < 16) { + fsevents = void 0; + } + } + } + var { + EV_ADD, + EV_CHANGE, + EV_ADD_DIR, + EV_UNLINK, + EV_ERROR, + STR_DATA, + STR_END, + FSEVENT_CREATED, + FSEVENT_MODIFIED, + FSEVENT_DELETED, + FSEVENT_MOVED, + FSEVENT_UNKNOWN, + FSEVENT_TYPE_FILE, + FSEVENT_TYPE_DIRECTORY, + FSEVENT_TYPE_SYMLINK, + ROOT_GLOBSTAR, + DIR_SUFFIX, + DOT_SLASH, + FUNCTION_TYPE, + EMPTY_FN, + IDENTITY_FN + } = require_constants3(); + var Depth = (value) => isNaN(value) ? {} : {depth: value}; + var stat = promisify(fs.stat); + var lstat = promisify(fs.lstat); + var realpath = promisify(fs.realpath); + var statMethods = {stat, lstat}; + var FSEventsWatchers = new Map(); + var consolidateThreshhold = 10; + var wrongEventFlags = new Set([ + 69888, + 70400, + 71424, + 72704, + 73472, + 131328, + 131840, + 262912 + ]); + var createFSEventsInstance = (path, callback) => { + const stop = fsevents.watch(path, callback); + return {stop}; + }; + function setFSEventsListener(path, realPath, listener, rawEmitter) { + let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath; + const parentPath = sysPath.dirname(watchPath); + let cont = FSEventsWatchers.get(watchPath); + if (couldConsolidate(parentPath)) { + watchPath = parentPath; + } + const resolvedPath = sysPath.resolve(path); + const hasSymlink = resolvedPath !== realPath; + const filteredListener = (fullPath, flags, info) => { + if (hasSymlink) + fullPath = fullPath.replace(realPath, resolvedPath); + if (fullPath === resolvedPath || !fullPath.indexOf(resolvedPath + sysPath.sep)) + listener(fullPath, flags, info); + }; + let watchedParent = false; + for (const watchedPath of FSEventsWatchers.keys()) { + if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) { + watchPath = watchedPath; + cont = FSEventsWatchers.get(watchPath); + watchedParent = true; + break; + } + } + if (cont || watchedParent) { + cont.listeners.add(filteredListener); + } else { + cont = { + listeners: new Set([filteredListener]), + rawEmitter, + watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { + if (!cont.listeners.size) + return; + const info = fsevents.getInfo(fullPath, flags); + cont.listeners.forEach((list) => { + list(fullPath, flags, info); + }); + cont.rawEmitter(info.event, fullPath, info); + }) + }; + FSEventsWatchers.set(watchPath, cont); + } + return () => { + const lst = cont.listeners; + lst.delete(filteredListener); + if (!lst.size) { + FSEventsWatchers.delete(watchPath); + if (cont.watcher) + return cont.watcher.stop().then(() => { + cont.rawEmitter = cont.watcher = void 0; + Object.freeze(cont); + }); + } + }; + } + var couldConsolidate = (path) => { + let count = 0; + for (const watchPath of FSEventsWatchers.keys()) { + if (watchPath.indexOf(path) === 0) { + count++; + if (count >= consolidateThreshhold) { + return true; + } + } + } + return false; + }; + var canUse = () => fsevents && FSEventsWatchers.size < 128; + var calcDepth = (path, root) => { + let i = 0; + while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) + i++; + return i; + }; + var sameTypes = (info, stats) => info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || info.type === FSEVENT_TYPE_FILE && stats.isFile(); + var FsEventsHandler = class { + constructor(fsw) { + this.fsw = fsw; + } + checkIgnored(path, stats) { + const ipaths = this.fsw._ignoredPaths; + if (this.fsw._isIgnored(path, stats)) { + ipaths.add(path); + if (stats && stats.isDirectory()) { + ipaths.add(path + ROOT_GLOBSTAR); + } + return true; + } + ipaths.delete(path); + ipaths.delete(path + ROOT_GLOBSTAR); + } + addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD; + this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + try { + const stats = await stat(path); + if (this.fsw.closed) + return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } catch (error) { + if (error.code === "EACCES") { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + } + handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { + if (this.fsw.closed || this.checkIgnored(path)) + return; + if (event === EV_UNLINK) { + const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY; + if (isDirectory || watchedDir.has(item)) { + this.fsw._remove(parent, item, isDirectory); + } + } else { + if (event === EV_ADD) { + if (info.type === FSEVENT_TYPE_DIRECTORY) + this.fsw._getWatchedDir(path); + if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { + const curDepth = opts.depth === void 0 ? void 0 : calcDepth(fullPath, realPath) + 1; + return this._addToFsEvents(path, false, true, curDepth); + } + this.fsw._getWatchedDir(parent).add(item); + } + const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; + this.fsw._emit(eventName, path); + if (eventName === EV_ADD_DIR) + this._addToFsEvents(path, false, true); + } + } + _watchWithFsEvents(watchPath, realPath, transform, globFilter) { + if (this.fsw.closed || this.fsw._isIgnored(watchPath)) + return; + const opts = this.fsw.options; + const watchCallback = async (fullPath, flags, info) => { + if (this.fsw.closed) + return; + if (opts.depth !== void 0 && calcDepth(fullPath, realPath) > opts.depth) + return; + const path = transform(sysPath.join(watchPath, sysPath.relative(watchPath, fullPath))); + if (globFilter && !globFilter(path)) + return; + const parent = sysPath.dirname(path); + const item = sysPath.basename(path); + const watchedDir = this.fsw._getWatchedDir(info.type === FSEVENT_TYPE_DIRECTORY ? path : parent); + if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { + if (typeof opts.ignored === FUNCTION_TYPE) { + let stats; + try { + stats = await stat(path); + } catch (error) { + } + if (this.fsw.closed) + return; + if (this.checkIgnored(path, stats)) + return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + switch (info.event) { + case FSEVENT_CREATED: + case FSEVENT_MODIFIED: + return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + case FSEVENT_DELETED: + case FSEVENT_MOVED: + return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + }; + const closer = setFSEventsListener(watchPath, realPath, watchCallback, this.fsw._emitRaw); + this.fsw._emitReady(); + return closer; + } + async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { + if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) + return; + this.fsw._symlinkPaths.set(fullPath, true); + this.fsw._incrReadyCount(); + try { + const linkTarget = await realpath(linkPath); + if (this.fsw.closed) + return; + if (this.fsw._isIgnored(linkTarget)) { + return this.fsw._emitReady(); + } + this.fsw._incrReadyCount(); + this._addToFsEvents(linkTarget || linkPath, (path) => { + let aliasedPath = linkPath; + if (linkTarget && linkTarget !== DOT_SLASH) { + aliasedPath = path.replace(linkTarget, linkPath); + } else if (path !== DOT_SLASH) { + aliasedPath = sysPath.join(linkPath, path); + } + return transform(aliasedPath); + }, false, curDepth); + } catch (error) { + if (this.fsw._handleError(error)) { + return this.fsw._emitReady(); + } + } + } + emitAdd(newPath, stats, processPath, opts, forceAdd) { + const pp = processPath(newPath); + const isDir = stats.isDirectory(); + const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp)); + const base = sysPath.basename(pp); + if (isDir) + this.fsw._getWatchedDir(pp); + if (dirObj.has(base)) + return; + dirObj.add(base); + if (!opts.ignoreInitial || forceAdd === true) { + this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats); + } + } + initWatch(realPath, path, wh, processPath) { + if (this.fsw.closed) + return; + const closer = this._watchWithFsEvents(wh.watchPath, sysPath.resolve(realPath || wh.watchPath), processPath, wh.globFilter); + this.fsw._addPathCloser(path, closer); + } + async _addToFsEvents(path, transform, forceAdd, priorDepth) { + if (this.fsw.closed) { + return; + } + const opts = this.fsw.options; + const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN; + const wh = this.fsw._getWatchHelpers(path); + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) + return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + throw null; + } + if (stats.isDirectory()) { + if (!wh.globFilter) + this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); + if (priorDepth && priorDepth > opts.depth) + return; + this.fsw._readdirp(wh.watchPath, { + fileFilter: (entry) => wh.filterPath(entry), + directoryFilter: (entry) => wh.filterDir(entry), + ...Depth(opts.depth - (priorDepth || 0)) + }).on(STR_DATA, (entry) => { + if (this.fsw.closed) { + return; + } + if (entry.stats.isDirectory() && !wh.filterPath(entry)) + return; + const joinedPath = sysPath.join(wh.watchPath, entry.path); + const {fullPath} = entry; + if (wh.followSymlinks && entry.stats.isSymbolicLink()) { + const curDepth = opts.depth === void 0 ? void 0 : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1; + this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); + } else { + this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); + } + }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => { + this.fsw._emitReady(); + }); + } else { + this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); + this.fsw._emitReady(); + } + } catch (error) { + if (!error || this.fsw._handleError(error)) { + this.fsw._emitReady(); + this.fsw._emitReady(); + } + } + if (opts.persistent && forceAdd !== true) { + if (typeof transform === FUNCTION_TYPE) { + this.initWatch(void 0, path, wh, processPath); + } else { + let realPath; + try { + realPath = await realpath(wh.watchPath); + } catch (e2) { + } + this.initWatch(realPath, path, wh, processPath); + } + } + } + }; + module2.exports = FsEventsHandler; + module2.exports.canUse = canUse; +}); + +// ../../node_modules/chokidar/index.js +var require_chokidar = __commonJS((exports2) => { + "use strict"; + var {EventEmitter} = require("events"); + var fs = require("fs"); + var sysPath = require("path"); + var {promisify} = require("util"); + var readdirp = require_readdirp(); + var anymatch = require_anymatch().default; + var globParent = require_glob_parent(); + var isGlob = require_is_glob(); + var braces = require_braces(); + var normalizePath = require_normalize_path(); + var NodeFsHandler = require_nodefs_handler(); + var FsEventsHandler = require_fsevents_handler(); + var { + EV_ALL, + EV_READY, + EV_ADD, + EV_CHANGE, + EV_UNLINK, + EV_ADD_DIR, + EV_UNLINK_DIR, + EV_RAW, + EV_ERROR, + STR_CLOSE, + STR_END, + BACK_SLASH_RE, + DOUBLE_SLASH_RE, + SLASH_OR_BACK_SLASH_RE, + DOT_RE, + REPLACER_RE, + SLASH, + SLASH_SLASH, + BRACE_START, + BANG, + ONE_DOT, + TWO_DOTS, + GLOBSTAR, + SLASH_GLOBSTAR, + ANYMATCH_OPTS, + STRING_TYPE, + FUNCTION_TYPE, + EMPTY_STR, + EMPTY_FN, + isWindows, + isMacos, + isIBMi + } = require_constants3(); + var stat = promisify(fs.stat); + var readdir = promisify(fs.readdir); + var arrify = (value = []) => Array.isArray(value) ? value : [value]; + var flatten = (list, result = []) => { + list.forEach((item) => { + if (Array.isArray(item)) { + flatten(item, result); + } else { + result.push(item); + } + }); + return result; + }; + var unifyPaths = (paths_) => { + const paths = flatten(arrify(paths_)); + if (!paths.every((p) => typeof p === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths}`); + } + return paths.map(normalizePathToUnix); + }; + var toUnix = (string) => { + let str = string.replace(BACK_SLASH_RE, SLASH); + let prepend = false; + if (str.startsWith(SLASH_SLASH)) { + prepend = true; + } + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH); + } + if (prepend) { + str = SLASH + str; + } + return str; + }; + var normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path))); + var normalizeIgnored = (cwd = EMPTY_STR) => (path) => { + if (typeof path !== STRING_TYPE) + return path; + return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path)); + }; + var getAbsolutePath = (path, cwd) => { + if (sysPath.isAbsolute(path)) { + return path; + } + if (path.startsWith(BANG)) { + return BANG + sysPath.join(cwd, path.slice(1)); + } + return sysPath.join(cwd, path); + }; + var undef = (opts, key) => opts[key] === void 0; + var DirEntry = class { + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + this.items = new Set(); + } + add(item) { + const {items} = this; + if (!items) + return; + if (item !== ONE_DOT && item !== TWO_DOTS) + items.add(item); + } + async remove(item) { + const {items} = this; + if (!items) + return; + items.delete(item); + if (items.size > 0) + return; + const dir = this.path; + try { + await readdir(dir); + } catch (err) { + if (this._removeWatcher) { + this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); + } + } + } + has(item) { + const {items} = this; + if (!items) + return; + return items.has(item); + } + getChildren() { + const {items} = this; + if (!items) + return; + return [...items.values()]; + } + dispose() { + this.items.clear(); + delete this.path; + delete this._removeWatcher; + delete this.items; + Object.freeze(this); + } + }; + var STAT_METHOD_F = "stat"; + var STAT_METHOD_L = "lstat"; + var WatchHelper = class { + constructor(path, watchPath, follow, fsw) { + this.fsw = fsw; + this.path = path = path.replace(REPLACER_RE, EMPTY_STR); + this.watchPath = watchPath; + this.fullWatchPath = sysPath.resolve(watchPath); + this.hasGlob = watchPath !== path; + if (path === EMPTY_STR) + this.hasGlob = false; + this.globSymlink = this.hasGlob && follow ? void 0 : false; + this.globFilter = this.hasGlob ? anymatch(path, void 0, ANYMATCH_OPTS) : false; + this.dirParts = this.getDirParts(path); + this.dirParts.forEach((parts) => { + if (parts.length > 1) + parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + checkGlobSymlink(entry) { + if (this.globSymlink === void 0) { + this.globSymlink = entry.fullParentDir === this.fullWatchPath ? false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; + } + if (this.globSymlink) { + return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); + } + return entry.fullPath; + } + entryPath(entry) { + return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))); + } + filterPath(entry) { + const {stats} = entry; + if (stats && stats.isSymbolicLink()) + return this.filterDir(entry); + const resolvedPath = this.entryPath(entry); + const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? this.globFilter(resolvedPath) : true; + return matchesGlob && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats); + } + getDirParts(path) { + if (!this.hasGlob) + return []; + const parts = []; + const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path]; + expandedPath.forEach((path2) => { + parts.push(sysPath.relative(this.watchPath, path2).split(SLASH_OR_BACK_SLASH_RE)); + }); + return parts; + } + filterDir(entry) { + if (this.hasGlob) { + const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); + let globstar = false; + this.unmatchedGlob = !this.dirParts.some((parts) => { + return parts.every((part, i) => { + if (part === GLOBSTAR) + globstar = true; + return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); + }); + }); + } + return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } + }; + var FSWatcher = class extends EventEmitter { + constructor(_opts) { + super(); + const opts = {}; + if (_opts) + Object.assign(opts, _opts); + this._watched = new Map(); + this._closers = new Map(); + this._ignoredPaths = new Set(); + this._throttled = new Map(); + this._symlinkPaths = new Map(); + this._streams = new Set(); + this.closed = false; + if (undef(opts, "persistent")) + opts.persistent = true; + if (undef(opts, "ignoreInitial")) + opts.ignoreInitial = false; + if (undef(opts, "ignorePermissionErrors")) + opts.ignorePermissionErrors = false; + if (undef(opts, "interval")) + opts.interval = 100; + if (undef(opts, "binaryInterval")) + opts.binaryInterval = 300; + if (undef(opts, "disableGlobbing")) + opts.disableGlobbing = false; + opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; + if (undef(opts, "useFsEvents")) + opts.useFsEvents = !opts.usePolling; + const canUseFsEvents = FsEventsHandler.canUse(); + if (!canUseFsEvents) + opts.useFsEvents = false; + if (undef(opts, "usePolling") && !opts.useFsEvents) { + opts.usePolling = isMacos; + } + if (isIBMi) { + opts.usePolling = true; + } + const envPoll = process.env.CHOKIDAR_USEPOLLING; + if (envPoll !== void 0) { + const envLower = envPoll.toLowerCase(); + if (envLower === "false" || envLower === "0") { + opts.usePolling = false; + } else if (envLower === "true" || envLower === "1") { + opts.usePolling = true; + } else { + opts.usePolling = !!envLower; + } + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) { + opts.interval = Number.parseInt(envInterval, 10); + } + if (undef(opts, "atomic")) + opts.atomic = !opts.usePolling && !opts.useFsEvents; + if (opts.atomic) + this._pendingUnlinks = new Map(); + if (undef(opts, "followSymlinks")) + opts.followSymlinks = true; + if (undef(opts, "awaitWriteFinish")) + opts.awaitWriteFinish = false; + if (opts.awaitWriteFinish === true) + opts.awaitWriteFinish = {}; + const awf = opts.awaitWriteFinish; + if (awf) { + if (!awf.stabilityThreshold) + awf.stabilityThreshold = 2e3; + if (!awf.pollInterval) + awf.pollInterval = 100; + this._pendingWrites = new Map(); + } + if (opts.ignored) + opts.ignored = arrify(opts.ignored); + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN; + this._readyEmitted = true; + process.nextTick(() => this.emit(EV_READY)); + } + }; + this._emitRaw = (...args) => this.emit(EV_RAW, ...args); + this._readyEmitted = false; + this.options = opts; + if (opts.useFsEvents) { + this._fsEventsHandler = new FsEventsHandler(this); + } else { + this._nodeFsHandler = new NodeFsHandler(this); + } + Object.freeze(opts); + } + add(paths_, _origAdd, _internal) { + const {cwd, disableGlobbing} = this.options; + this.closed = false; + let paths = unifyPaths(paths_); + if (cwd) { + paths = paths.map((path) => { + const absPath = getAbsolutePath(path, cwd); + if (disableGlobbing || !isGlob(path)) { + return absPath; + } + return normalizePath(absPath); + }); + } + paths = paths.filter((path) => { + if (path.startsWith(BANG)) { + this._ignoredPaths.add(path.slice(1)); + return false; + } + this._ignoredPaths.delete(path); + this._ignoredPaths.delete(path + SLASH_GLOBSTAR); + this._userIgnored = void 0; + return true; + }); + if (this.options.useFsEvents && this._fsEventsHandler) { + if (!this._readyCount) + this._readyCount = paths.length; + if (this.options.persistent) + this._readyCount *= 2; + paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); + } else { + if (!this._readyCount) + this._readyCount = 0; + this._readyCount += paths.length; + Promise.all(paths.map(async (path) => { + const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); + if (res) + this._emitReady(); + return res; + })).then((results) => { + if (this.closed) + return; + results.filter((item) => item).forEach((item) => { + this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); + }); + }); + } + return this; + } + unwatch(paths_) { + if (this.closed) + return this; + const paths = unifyPaths(paths_); + const {cwd} = this.options; + paths.forEach((path) => { + if (!sysPath.isAbsolute(path) && !this._closers.has(path)) { + if (cwd) + path = sysPath.join(cwd, path); + path = sysPath.resolve(path); + } + this._closePath(path); + this._ignoredPaths.add(path); + if (this._watched.has(path)) { + this._ignoredPaths.add(path + SLASH_GLOBSTAR); + } + this._userIgnored = void 0; + }); + return this; + } + close() { + if (this.closed) + return this._closePromise; + this.closed = true; + this.removeAllListeners(); + const closers = []; + this._closers.forEach((closerList) => closerList.forEach((closer) => { + const promise = closer(); + if (promise instanceof Promise) + closers.push(promise); + })); + this._streams.forEach((stream) => stream.destroy()); + this._userIgnored = void 0; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach((dirent) => dirent.dispose()); + ["closers", "watched", "streams", "symlinkPaths", "throttled"].forEach((key) => { + this[`_${key}`].clear(); + }); + this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve(); + return this._closePromise; + } + getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir; + watchList[key || ONE_DOT] = entry.getChildren().sort(); + }); + return watchList; + } + emitWithAll(event, args) { + this.emit(...args); + if (event !== EV_ERROR) + this.emit(EV_ALL, ...args); + } + async _emit(event, path, val1, val2, val3) { + if (this.closed) + return; + const opts = this.options; + if (isWindows) + path = sysPath.normalize(path); + if (opts.cwd) + path = sysPath.relative(opts.cwd, path); + const args = [event, path]; + if (val3 !== void 0) + args.push(val1, val2, val3); + else if (val2 !== void 0) + args.push(val1, val2); + else if (val1 !== void 0) + args.push(val1); + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path))) { + pw.lastChange = new Date(); + return this; + } + if (opts.atomic) { + if (event === EV_UNLINK) { + this._pendingUnlinks.set(path, args); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path2) => { + this.emit(...entry); + this.emit(EV_ALL, ...entry); + this._pendingUnlinks.delete(path2); + }); + }, typeof opts.atomic === "number" ? opts.atomic : 100); + return this; + } + if (event === EV_ADD && this._pendingUnlinks.has(path)) { + event = args[0] = EV_CHANGE; + this._pendingUnlinks.delete(path); + } + } + if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) { + const awfEmit = (err, stats) => { + if (err) { + event = args[0] = EV_ERROR; + args[1] = err; + this.emitWithAll(event, args); + } else if (stats) { + if (args.length > 2) { + args[2] = stats; + } else { + args.push(stats); + } + this.emitWithAll(event, args); + } + }; + this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); + return this; + } + if (event === EV_CHANGE) { + const isThrottled = !this._throttle(EV_CHANGE, path, 50); + if (isThrottled) + return this; + } + if (opts.alwaysStat && val1 === void 0 && (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)) { + const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path; + let stats; + try { + stats = await stat(fullPath); + } catch (err) { + } + if (!stats || this.closed) + return; + args.push(stats); + } + this.emitWithAll(event, args); + return this; + } + _handleError(error) { + const code = error && error.code; + if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) { + this.emit(EV_ERROR, error); + } + return error || this.closed; + } + _throttle(actionType, path, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, new Map()); + } + const action = this._throttled.get(actionType); + const actionPath = action.get(path); + if (actionPath) { + actionPath.count++; + return false; + } + let timeoutObject; + const clear = () => { + const item = action.get(path); + const count = item ? item.count : 0; + action.delete(path); + clearTimeout(timeoutObject); + if (item) + clearTimeout(item.timeoutObject); + return count; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = {timeoutObject, clear, count: 0}; + action.set(path, thr); + return thr; + } + _incrReadyCount() { + return this._readyCount++; + } + _awaitWriteFinish(path, threshold, event, awfEmit) { + let timeoutHandler; + let fullPath = path; + if (this.options.cwd && !sysPath.isAbsolute(path)) { + fullPath = sysPath.join(this.options.cwd, path); + } + const now = new Date(); + const awaitWriteFinish = (prevStat) => { + fs.stat(fullPath, (err, curStat) => { + if (err || !this._pendingWrites.has(path)) { + if (err && err.code !== "ENOENT") + awfEmit(err); + return; + } + const now2 = Number(new Date()); + if (prevStat && curStat.size !== prevStat.size) { + this._pendingWrites.get(path).lastChange = now2; + } + const pw = this._pendingWrites.get(path); + const df = now2 - pw.lastChange; + if (df >= threshold) { + this._pendingWrites.delete(path); + awfEmit(void 0, curStat); + } else { + timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval, curStat); + } + }); + }; + if (!this._pendingWrites.has(path)) { + this._pendingWrites.set(path, { + lastChange: now, + cancelWait: () => { + this._pendingWrites.delete(path); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval); + } + } + _getGlobIgnored() { + return [...this._ignoredPaths.values()]; + } + _isIgnored(path, stats) { + if (this.options.atomic && DOT_RE.test(path)) + return true; + if (!this._userIgnored) { + const {cwd} = this.options; + const ign = this.options.ignored; + const ignored = ign && ign.map(normalizeIgnored(cwd)); + const paths = arrify(ignored).filter((path2) => typeof path2 === STRING_TYPE && !isGlob(path2)).map((path2) => path2 + SLASH_GLOBSTAR); + const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); + this._userIgnored = anymatch(list, void 0, ANYMATCH_OPTS); + } + return this._userIgnored([path, stats]); + } + _isntIgnored(path, stat2) { + return !this._isIgnored(path, stat2); + } + _getWatchHelpers(path, depth) { + const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); + const follow = this.options.followSymlinks; + return new WatchHelper(path, watchPath, follow, this); + } + _getWatchedDir(directory) { + if (!this._boundRemove) + this._boundRemove = this._remove.bind(this); + const dir = sysPath.resolve(directory); + if (!this._watched.has(dir)) + this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); + } + _hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) + return true; + const md = stats && Number.parseInt(stats.mode, 10); + const st = md & 511; + const it = Number.parseInt(st.toString(8)[0], 10); + return Boolean(4 & it); + } + _remove(directory, item, isDirectory) { + const path = sysPath.join(directory, item); + const fullPath = sysPath.resolve(path); + isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath); + if (!this._throttle("remove", path, 100)) + return; + if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { + this.add(directory, item, true); + } + const wp = this._getWatchedDir(path); + const nestedDirectoryChildren = wp.getChildren(); + nestedDirectoryChildren.forEach((nested) => this._remove(path, nested)); + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + if (this._symlinkPaths.has(fullPath)) { + this._symlinkPaths.delete(fullPath); + } + let relPath = path; + if (this.options.cwd) + relPath = sysPath.relative(this.options.cwd, path); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EV_ADD) + return; + } + this._watched.delete(path); + this._watched.delete(fullPath); + const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK; + if (wasTracked && !this._isIgnored(path)) + this._emit(eventName, path); + if (!this.options.useFsEvents) { + this._closePath(path); + } + } + _closePath(path) { + this._closeFile(path); + const dir = sysPath.dirname(path); + this._getWatchedDir(dir).remove(sysPath.basename(path)); + } + _closeFile(path) { + const closers = this._closers.get(path); + if (!closers) + return; + closers.forEach((closer) => closer()); + this._closers.delete(path); + } + _addPathCloser(path, closer) { + if (!closer) + return; + let list = this._closers.get(path); + if (!list) { + list = []; + this._closers.set(path, list); + } + list.push(closer); + } + _readdirp(root, opts) { + if (this.closed) + return; + const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; + let stream = readdirp(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = void 0; + }); + stream.once(STR_END, () => { + if (stream) { + this._streams.delete(stream); + stream = void 0; + } + }); + return stream; + } + }; + exports2.FSWatcher = FSWatcher; + var watch = (paths, options) => { + const watcher = new FSWatcher(options); + watcher.add(paths); + return watcher; + }; + exports2.watch = watch; +}); + +// ../../node_modules/nunjucks/src/node-loaders.js +var require_node_loaders = __commonJS((exports2, module2) => { + "use strict"; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var fs = require("fs"); + var path = require("path"); + var Loader2 = require_loader(); + var _require2 = require_precompiled_loader(); + var PrecompiledLoader = _require2.PrecompiledLoader; + var chokidar; + var FileSystemLoader = /* @__PURE__ */ function(_Loader) { + _inheritsLoose(FileSystemLoader2, _Loader); + function FileSystemLoader2(searchPaths, opts) { + var _this; + _this = _Loader.call(this) || this; + if (typeof opts === "boolean") { + console.log("[nunjucks] Warning: you passed a boolean as the second argument to FileSystemLoader, but it now takes an options object. See http://mozilla.github.io/nunjucks/api.html#filesystemloader"); + } + opts = opts || {}; + _this.pathsToNames = {}; + _this.noCache = !!opts.noCache; + if (searchPaths) { + searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths]; + _this.searchPaths = searchPaths.map(path.normalize); + } else { + _this.searchPaths = ["."]; + } + if (opts.watch) { + try { + chokidar = require_chokidar(); + } catch (e2) { + throw new Error("watch requires chokidar to be installed"); + } + var paths = _this.searchPaths.filter(fs.existsSync); + var watcher = chokidar.watch(paths); + watcher.on("all", function(event, fullname) { + fullname = path.resolve(fullname); + if (event === "change" && fullname in _this.pathsToNames) { + _this.emit("update", _this.pathsToNames[fullname], fullname); + } + }); + watcher.on("error", function(error) { + console.log("Watcher error: " + error); + }); + } + return _this; + } + var _proto = FileSystemLoader2.prototype; + _proto.getSource = function getSource(name) { + var fullpath = null; + var paths = this.searchPaths; + for (var i = 0; i < paths.length; i++) { + var basePath = path.resolve(paths[i]); + var p = path.resolve(paths[i], name); + if (p.indexOf(basePath) === 0 && fs.existsSync(p)) { + fullpath = p; + break; + } + } + if (!fullpath) { + return null; + } + this.pathsToNames[fullpath] = name; + var source = { + src: fs.readFileSync(fullpath, "utf-8"), + path: fullpath, + noCache: this.noCache + }; + this.emit("load", name, source); + return source; + }; + return FileSystemLoader2; + }(Loader2); + var NodeResolveLoader = /* @__PURE__ */ function(_Loader2) { + _inheritsLoose(NodeResolveLoader2, _Loader2); + function NodeResolveLoader2(opts) { + var _this2; + _this2 = _Loader2.call(this) || this; + opts = opts || {}; + _this2.pathsToNames = {}; + _this2.noCache = !!opts.noCache; + if (opts.watch) { + try { + chokidar = require_chokidar(); + } catch (e2) { + throw new Error("watch requires chokidar to be installed"); + } + _this2.watcher = chokidar.watch(); + _this2.watcher.on("change", function(fullname) { + _this2.emit("update", _this2.pathsToNames[fullname], fullname); + }); + _this2.watcher.on("error", function(error) { + console.log("Watcher error: " + error); + }); + _this2.on("load", function(name, source) { + _this2.watcher.add(source.path); + }); + } + return _this2; + } + var _proto2 = NodeResolveLoader2.prototype; + _proto2.getSource = function getSource(name) { + if (/^\.?\.?(\/|\\)/.test(name)) { + return null; + } + if (/^[A-Z]:/.test(name)) { + return null; + } + var fullpath; + try { + fullpath = require.resolve(name); + } catch (e2) { + return null; + } + this.pathsToNames[fullpath] = name; + var source = { + src: fs.readFileSync(fullpath, "utf-8"), + path: fullpath, + noCache: this.noCache + }; + this.emit("load", name, source); + return source; + }; + return NodeResolveLoader2; + }(Loader2); + module2.exports = { + FileSystemLoader, + PrecompiledLoader, + NodeResolveLoader + }; +}); + +// ../../node_modules/nunjucks/src/loaders.js +var require_loaders = __commonJS((exports2, module2) => { + "use strict"; + module2.exports = require_node_loaders(); +}); + +// ../../node_modules/nunjucks/src/tests.js +var require_tests = __commonJS((exports2) => { + "use strict"; + var SafeString = require_runtime().SafeString; + function callable(value) { + return typeof value === "function"; + } + exports2.callable = callable; + function defined(value) { + return value !== void 0; + } + exports2.defined = defined; + function divisibleby(one, two) { + return one % two === 0; + } + exports2.divisibleby = divisibleby; + function escaped(value) { + return value instanceof SafeString; + } + exports2.escaped = escaped; + function equalto(one, two) { + return one === two; + } + exports2.equalto = equalto; + exports2.eq = exports2.equalto; + exports2.sameas = exports2.equalto; + function even(value) { + return value % 2 === 0; + } + exports2.even = even; + function falsy(value) { + return !value; + } + exports2.falsy = falsy; + function ge(one, two) { + return one >= two; + } + exports2.ge = ge; + function greaterthan(one, two) { + return one > two; + } + exports2.greaterthan = greaterthan; + exports2.gt = exports2.greaterthan; + function le(one, two) { + return one <= two; + } + exports2.le = le; + function lessthan(one, two) { + return one < two; + } + exports2.lessthan = lessthan; + exports2.lt = exports2.lessthan; + function lower(value) { + return value.toLowerCase() === value; + } + exports2.lower = lower; + function ne(one, two) { + return one !== two; + } + exports2.ne = ne; + function nullTest(value) { + return value === null; + } + exports2.null = nullTest; + function number(value) { + return typeof value === "number"; + } + exports2.number = number; + function odd(value) { + return value % 2 === 1; + } + exports2.odd = odd; + function string(value) { + return typeof value === "string"; + } + exports2.string = string; + function truthy(value) { + return !!value; + } + exports2.truthy = truthy; + function undefinedTest(value) { + return value === void 0; + } + exports2.undefined = undefinedTest; + function upper(value) { + return value.toUpperCase() === value; + } + exports2.upper = upper; + function iterable(value) { + if (typeof Symbol !== "undefined") { + return !!value[Symbol.iterator]; + } else { + return Array.isArray(value) || typeof value === "string"; + } + } + exports2.iterable = iterable; + function mapping(value) { + var bool = value !== null && value !== void 0 && typeof value === "object" && !Array.isArray(value); + if (Set) { + return bool && !(value instanceof Set); + } else { + return bool; + } + } + exports2.mapping = mapping; +}); + +// ../../node_modules/nunjucks/src/globals.js +var require_globals = __commonJS((exports2, module2) => { + "use strict"; + function _cycler(items) { + var index = -1; + return { + current: null, + reset: function reset2() { + index = -1; + this.current = null; + }, + next: function next() { + index++; + if (index >= items.length) { + index = 0; + } + this.current = items[index]; + return this.current; + } + }; + } + function _joiner(sep) { + sep = sep || ","; + var first = true; + return function() { + var val = first ? "" : sep; + first = false; + return val; + }; + } + function globals() { + return { + range: function range(start, stop, step) { + if (typeof stop === "undefined") { + stop = start; + start = 0; + step = 1; + } else if (!step) { + step = 1; + } + var arr = []; + if (step > 0) { + for (var i = start; i < stop; i += step) { + arr.push(i); + } + } else { + for (var _i = start; _i > stop; _i += step) { + arr.push(_i); + } + } + return arr; + }, + cycler: function cycler() { + return _cycler(Array.prototype.slice.call(arguments)); + }, + joiner: function joiner(sep) { + return _joiner(sep); + } + }; + } + module2.exports = globals; +}); + +// ../../node_modules/nunjucks/src/express-app.js +var require_express_app = __commonJS((exports2, module2) => { + "use strict"; + var path = require("path"); + module2.exports = function express(env, app) { + function NunjucksView(name, opts) { + this.name = name; + this.path = name; + this.defaultEngine = opts.defaultEngine; + this.ext = path.extname(name); + if (!this.ext && !this.defaultEngine) { + throw new Error("No default engine was specified and no extension was provided."); + } + if (!this.ext) { + this.name += this.ext = (this.defaultEngine[0] !== "." ? "." : "") + this.defaultEngine; + } + } + NunjucksView.prototype.render = function render2(opts, cb) { + env.render(this.name, opts, cb); + }; + app.set("view", NunjucksView); + app.set("nunjucksEnv", env); + return env; + }; +}); + +// ../../node_modules/nunjucks/src/environment.js +var require_environment = __commonJS((exports2, module2) => { + "use strict"; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + var asap = require_asap(); + var _waterfall = require_a_sync_waterfall(); + var lib2 = require_lib(); + var compiler2 = require_compiler(); + var filters = require_filters(); + var _require2 = require_loaders(); + var FileSystemLoader = _require2.FileSystemLoader; + var WebLoader = _require2.WebLoader; + var PrecompiledLoader = _require2.PrecompiledLoader; + var tests = require_tests(); + var globals = require_globals(); + var _require22 = require_object(); + var Obj = _require22.Obj; + var EmitterObj = _require22.EmitterObj; + var globalRuntime = require_runtime(); + var handleError = globalRuntime.handleError; + var Frame = globalRuntime.Frame; + var expressApp = require_express_app(); + function callbackAsap(cb, err, res) { + asap(function() { + cb(err, res); + }); + } + var noopTmplSrc = { + type: "code", + obj: { + root: function root(env, context, frame, runtime2, cb) { + try { + cb(null, ""); + } catch (e2) { + cb(handleError(e2, null, null)); + } + } + } + }; + var Environment2 = /* @__PURE__ */ function(_EmitterObj) { + _inheritsLoose(Environment3, _EmitterObj); + function Environment3() { + return _EmitterObj.apply(this, arguments) || this; + } + var _proto = Environment3.prototype; + _proto.init = function init(loaders2, opts) { + var _this = this; + opts = this.opts = opts || {}; + this.opts.dev = !!opts.dev; + this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true; + this.opts.throwOnUndefined = !!opts.throwOnUndefined; + this.opts.trimBlocks = !!opts.trimBlocks; + this.opts.lstripBlocks = !!opts.lstripBlocks; + this.loaders = []; + if (!loaders2) { + if (FileSystemLoader) { + this.loaders = [new FileSystemLoader("views")]; + } else if (WebLoader) { + this.loaders = [new WebLoader("/views")]; + } + } else { + this.loaders = lib2.isArray(loaders2) ? loaders2 : [loaders2]; + } + if (typeof window !== "undefined" && window.nunjucksPrecompiled) { + this.loaders.unshift(new PrecompiledLoader(window.nunjucksPrecompiled)); + } + this._initLoaders(); + this.globals = globals(); + this.filters = {}; + this.tests = {}; + this.asyncFilters = []; + this.extensions = {}; + this.extensionsList = []; + lib2._entries(filters).forEach(function(_ref) { + var name = _ref[0], filter = _ref[1]; + return _this.addFilter(name, filter); + }); + lib2._entries(tests).forEach(function(_ref2) { + var name = _ref2[0], test = _ref2[1]; + return _this.addTest(name, test); + }); + }; + _proto._initLoaders = function _initLoaders() { + var _this2 = this; + this.loaders.forEach(function(loader) { + loader.cache = {}; + if (typeof loader.on === "function") { + loader.on("update", function(name, fullname) { + loader.cache[name] = null; + _this2.emit("update", name, fullname, loader); + }); + loader.on("load", function(name, source) { + _this2.emit("load", name, source, loader); + }); + } + }); + }; + _proto.invalidateCache = function invalidateCache() { + this.loaders.forEach(function(loader) { + loader.cache = {}; + }); + }; + _proto.addExtension = function addExtension(name, extension) { + extension.__name = name; + this.extensions[name] = extension; + this.extensionsList.push(extension); + return this; + }; + _proto.removeExtension = function removeExtension(name) { + var extension = this.getExtension(name); + if (!extension) { + return; + } + this.extensionsList = lib2.without(this.extensionsList, extension); + delete this.extensions[name]; + }; + _proto.getExtension = function getExtension(name) { + return this.extensions[name]; + }; + _proto.hasExtension = function hasExtension(name) { + return !!this.extensions[name]; + }; + _proto.addGlobal = function addGlobal(name, value) { + this.globals[name] = value; + return this; + }; + _proto.getGlobal = function getGlobal(name) { + if (typeof this.globals[name] === "undefined") { + throw new Error("global not found: " + name); + } + return this.globals[name]; + }; + _proto.addFilter = function addFilter(name, func, async) { + var wrapped = func; + if (async) { + this.asyncFilters.push(name); + } + this.filters[name] = wrapped; + return this; + }; + _proto.getFilter = function getFilter(name) { + if (!this.filters[name]) { + throw new Error("filter not found: " + name); + } + return this.filters[name]; + }; + _proto.addTest = function addTest(name, func) { + this.tests[name] = func; + return this; + }; + _proto.getTest = function getTest(name) { + if (!this.tests[name]) { + throw new Error("test not found: " + name); + } + return this.tests[name]; + }; + _proto.resolveTemplate = function resolveTemplate(loader, parentName, filename) { + var isRelative = loader.isRelative && parentName ? loader.isRelative(filename) : false; + return isRelative && loader.resolve ? loader.resolve(parentName, filename) : filename; + }; + _proto.getTemplate = function getTemplate(name, eagerCompile, parentName, ignoreMissing, cb) { + var _this3 = this; + var that = this; + var tmpl = null; + if (name && name.raw) { + name = name.raw; + } + if (lib2.isFunction(parentName)) { + cb = parentName; + parentName = null; + eagerCompile = eagerCompile || false; + } + if (lib2.isFunction(eagerCompile)) { + cb = eagerCompile; + eagerCompile = false; + } + if (name instanceof Template2) { + tmpl = name; + } else if (typeof name !== "string") { + throw new Error("template names must be a string: " + name); + } else { + for (var i = 0; i < this.loaders.length; i++) { + var loader = this.loaders[i]; + tmpl = loader.cache[this.resolveTemplate(loader, parentName, name)]; + if (tmpl) { + break; + } + } + } + if (tmpl) { + if (eagerCompile) { + tmpl.compile(); + } + if (cb) { + cb(null, tmpl); + return void 0; + } else { + return tmpl; + } + } + var syncResult; + var createTemplate = function createTemplate2(err, info) { + if (!info && !err && !ignoreMissing) { + err = new Error("template not found: " + name); + } + if (err) { + if (cb) { + cb(err); + return; + } else { + throw err; + } + } + var newTmpl; + if (!info) { + newTmpl = new Template2(noopTmplSrc, _this3, "", eagerCompile); + } else { + newTmpl = new Template2(info.src, _this3, info.path, eagerCompile); + if (!info.noCache) { + info.loader.cache[name] = newTmpl; + } + } + if (cb) { + cb(null, newTmpl); + } else { + syncResult = newTmpl; + } + }; + lib2.asyncIter(this.loaders, function(loader2, i2, next, done) { + function handle(err, src) { + if (err) { + done(err); + } else if (src) { + src.loader = loader2; + done(null, src); + } else { + next(); + } + } + name = that.resolveTemplate(loader2, parentName, name); + if (loader2.async) { + loader2.getSource(name, handle); + } else { + handle(null, loader2.getSource(name)); + } + }, createTemplate); + return syncResult; + }; + _proto.express = function express(app) { + return expressApp(this, app); + }; + _proto.render = function render2(name, ctx, cb) { + if (lib2.isFunction(ctx)) { + cb = ctx; + ctx = null; + } + var syncResult = null; + this.getTemplate(name, function(err, tmpl) { + if (err && cb) { + callbackAsap(cb, err); + } else if (err) { + throw err; + } else { + syncResult = tmpl.render(ctx, cb); + } + }); + return syncResult; + }; + _proto.renderString = function renderString2(src, ctx, opts, cb) { + if (lib2.isFunction(opts)) { + cb = opts; + opts = {}; + } + opts = opts || {}; + var tmpl = new Template2(src, this, opts.path); + return tmpl.render(ctx, cb); + }; + _proto.waterfall = function waterfall(tasks, callback, forceAsync) { + return _waterfall(tasks, callback, forceAsync); + }; + return Environment3; + }(EmitterObj); + var Context = /* @__PURE__ */ function(_Obj) { + _inheritsLoose(Context2, _Obj); + function Context2() { + return _Obj.apply(this, arguments) || this; + } + var _proto2 = Context2.prototype; + _proto2.init = function init(ctx, blocks, env) { + var _this4 = this; + this.env = env || new Environment2(); + this.ctx = lib2.extend({}, ctx); + this.blocks = {}; + this.exported = []; + lib2.keys(blocks).forEach(function(name) { + _this4.addBlock(name, blocks[name]); + }); + }; + _proto2.lookup = function lookup(name) { + if (name in this.env.globals && !(name in this.ctx)) { + return this.env.globals[name]; + } else { + return this.ctx[name]; + } + }; + _proto2.setVariable = function setVariable(name, val) { + this.ctx[name] = val; + }; + _proto2.getVariables = function getVariables() { + return this.ctx; + }; + _proto2.addBlock = function addBlock(name, block) { + this.blocks[name] = this.blocks[name] || []; + this.blocks[name].push(block); + return this; + }; + _proto2.getBlock = function getBlock(name) { + if (!this.blocks[name]) { + throw new Error('unknown block "' + name + '"'); + } + return this.blocks[name][0]; + }; + _proto2.getSuper = function getSuper(env, name, block, frame, runtime2, cb) { + var idx = lib2.indexOf(this.blocks[name] || [], block); + var blk = this.blocks[name][idx + 1]; + var context = this; + if (idx === -1 || !blk) { + throw new Error('no super block available for "' + name + '"'); + } + blk(env, context, frame, runtime2, cb); + }; + _proto2.addExport = function addExport(name) { + this.exported.push(name); + }; + _proto2.getExported = function getExported() { + var _this5 = this; + var exported = {}; + this.exported.forEach(function(name) { + exported[name] = _this5.ctx[name]; + }); + return exported; + }; + return Context2; + }(Obj); + var Template2 = /* @__PURE__ */ function(_Obj2) { + _inheritsLoose(Template3, _Obj2); + function Template3() { + return _Obj2.apply(this, arguments) || this; + } + var _proto3 = Template3.prototype; + _proto3.init = function init(src, env, path, eagerCompile) { + this.env = env || new Environment2(); + if (lib2.isObject(src)) { + switch (src.type) { + case "code": + this.tmplProps = src.obj; + break; + case "string": + this.tmplStr = src.obj; + break; + default: + throw new Error("Unexpected template object type " + src.type + "; expected 'code', or 'string'"); + } + } else if (lib2.isString(src)) { + this.tmplStr = src; + } else { + throw new Error("src must be a string or an object describing the source"); + } + this.path = path; + if (eagerCompile) { + try { + this._compile(); + } catch (err) { + throw lib2._prettifyError(this.path, this.env.opts.dev, err); + } + } else { + this.compiled = false; + } + }; + _proto3.render = function render2(ctx, parentFrame, cb) { + var _this6 = this; + if (typeof ctx === "function") { + cb = ctx; + ctx = {}; + } else if (typeof parentFrame === "function") { + cb = parentFrame; + parentFrame = null; + } + var forceAsync = !parentFrame; + try { + this.compile(); + } catch (e2) { + var err = lib2._prettifyError(this.path, this.env.opts.dev, e2); + if (cb) { + return callbackAsap(cb, err); + } else { + throw err; + } + } + var context = new Context(ctx || {}, this.blocks, this.env); + var frame = parentFrame ? parentFrame.push(true) : new Frame(); + frame.topLevel = true; + var syncResult = null; + var didError = false; + this.rootRenderFunc(this.env, context, frame, globalRuntime, function(err2, res) { + if (didError && cb && typeof res !== "undefined") { + return; + } + if (err2) { + err2 = lib2._prettifyError(_this6.path, _this6.env.opts.dev, err2); + didError = true; + } + if (cb) { + if (forceAsync) { + callbackAsap(cb, err2, res); + } else { + cb(err2, res); + } + } else { + if (err2) { + throw err2; + } + syncResult = res; + } + }); + return syncResult; + }; + _proto3.getExported = function getExported(ctx, parentFrame, cb) { + if (typeof ctx === "function") { + cb = ctx; + ctx = {}; + } + if (typeof parentFrame === "function") { + cb = parentFrame; + parentFrame = null; + } + try { + this.compile(); + } catch (e2) { + if (cb) { + return cb(e2); + } else { + throw e2; + } + } + var frame = parentFrame ? parentFrame.push() : new Frame(); + frame.topLevel = true; + var context = new Context(ctx || {}, this.blocks, this.env); + this.rootRenderFunc(this.env, context, frame, globalRuntime, function(err) { + if (err) { + cb(err, null); + } else { + cb(null, context.getExported()); + } + }); + }; + _proto3.compile = function compile2() { + if (!this.compiled) { + this._compile(); + } + }; + _proto3._compile = function _compile() { + var props; + if (this.tmplProps) { + props = this.tmplProps; + } else { + var source = compiler2.compile(this.tmplStr, this.env.asyncFilters, this.env.extensionsList, this.path, this.env.opts); + var func = new Function(source); + props = func(); + } + this.blocks = this._getBlocks(props); + this.rootRenderFunc = props.root; + this.compiled = true; + }; + _proto3._getBlocks = function _getBlocks(props) { + var blocks = {}; + lib2.keys(props).forEach(function(k) { + if (k.slice(0, 2) === "b_") { + blocks[k.slice(2)] = props[k]; + } + }); + return blocks; + }; + return Template3; + }(Obj); + module2.exports = { + Environment: Environment2, + Template: Template2 + }; +}); + +// ../../node_modules/nunjucks/src/precompile-global.js +var require_precompile_global = __commonJS((exports2, module2) => { + "use strict"; + function precompileGlobal(templates, opts) { + var out = ""; + opts = opts || {}; + for (var i = 0; i < templates.length; i++) { + var name = JSON.stringify(templates[i].name); + var template = templates[i].template; + out += "(function() {(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})[" + name + "] = (function() {\n" + template + "\n})();\n"; + if (opts.asFunction) { + out += "return function(ctx, cb) { return nunjucks.render(" + name + ", ctx, cb); }\n"; + } + out += "})();\n"; + } + return out; + } + module2.exports = precompileGlobal; +}); + +// ../../node_modules/nunjucks/src/precompile.js +var require_precompile = __commonJS((exports2, module2) => { + "use strict"; + var fs = require("fs"); + var path = require("path"); + var _require2 = require_lib(); + var _prettifyError = _require2._prettifyError; + var compiler2 = require_compiler(); + var _require22 = require_environment(); + var Environment2 = _require22.Environment; + var precompileGlobal = require_precompile_global(); + function match(filename, patterns) { + if (!Array.isArray(patterns)) { + return false; + } + return patterns.some(function(pattern) { + return filename.match(pattern); + }); + } + function precompileString(str, opts) { + opts = opts || {}; + opts.isString = true; + var env = opts.env || new Environment2([]); + var wrapper = opts.wrapper || precompileGlobal; + if (!opts.name) { + throw new Error('the "name" option is required when compiling a string'); + } + return wrapper([_precompile(str, opts.name, env)], opts); + } + function precompile2(input, opts) { + opts = opts || {}; + var env = opts.env || new Environment2([]); + var wrapper = opts.wrapper || precompileGlobal; + if (opts.isString) { + return precompileString(input, opts); + } + var pathStats = fs.existsSync(input) && fs.statSync(input); + var precompiled = []; + var templates = []; + function addTemplates(dir) { + fs.readdirSync(dir).forEach(function(file) { + var filepath = path.join(dir, file); + var subpath = filepath.substr(path.join(input, "/").length); + var stat = fs.statSync(filepath); + if (stat && stat.isDirectory()) { + subpath += "/"; + if (!match(subpath, opts.exclude)) { + addTemplates(filepath); + } + } else if (match(subpath, opts.include)) { + templates.push(filepath); + } + }); + } + if (pathStats.isFile()) { + precompiled.push(_precompile(fs.readFileSync(input, "utf-8"), opts.name || input, env)); + } else if (pathStats.isDirectory()) { + addTemplates(input); + for (var i = 0; i < templates.length; i++) { + var name = templates[i].replace(path.join(input, "/"), ""); + try { + precompiled.push(_precompile(fs.readFileSync(templates[i], "utf-8"), name, env)); + } catch (e2) { + if (opts.force) { + console.error(e2); + } else { + throw e2; + } + } + } + } + return wrapper(precompiled, opts); + } + function _precompile(str, name, env) { + env = env || new Environment2([]); + var asyncFilters = env.asyncFilters; + var extensions = env.extensionsList; + var template; + name = name.replace(/\\/g, "/"); + try { + template = compiler2.compile(str, asyncFilters, extensions, name, env.opts); + } catch (err) { + throw _prettifyError(name, false, err); + } + return { + name, + template + }; + } + module2.exports = { + precompile: precompile2, + precompileString + }; +}); + +// ../../node_modules/nunjucks/src/jinja-compat.js +var require_jinja_compat = __commonJS((exports2, module2) => { + "use strict"; + function installCompat() { + "use strict"; + var runtime2 = this.runtime; + var lib2 = this.lib; + var Compiler = this.compiler.Compiler; + var Parser = this.parser.Parser; + var nodes2 = this.nodes; + var lexer2 = this.lexer; + var orig_contextOrFrameLookup = runtime2.contextOrFrameLookup; + var orig_memberLookup = runtime2.memberLookup; + var orig_Compiler_assertType; + var orig_Parser_parseAggregate; + if (Compiler) { + orig_Compiler_assertType = Compiler.prototype.assertType; + } + if (Parser) { + orig_Parser_parseAggregate = Parser.prototype.parseAggregate; + } + function uninstall() { + runtime2.contextOrFrameLookup = orig_contextOrFrameLookup; + runtime2.memberLookup = orig_memberLookup; + if (Compiler) { + Compiler.prototype.assertType = orig_Compiler_assertType; + } + if (Parser) { + Parser.prototype.parseAggregate = orig_Parser_parseAggregate; + } + } + runtime2.contextOrFrameLookup = function contextOrFrameLookup(context, frame, key) { + var val = orig_contextOrFrameLookup.apply(this, arguments); + if (val !== void 0) { + return val; + } + switch (key) { + case "True": + return true; + case "False": + return false; + case "None": + return null; + default: + return void 0; + } + }; + function getTokensState(tokens) { + return { + index: tokens.index, + lineno: tokens.lineno, + colno: tokens.colno + }; + } + if (process.env.BUILD_TYPE !== "SLIM" && nodes2 && Compiler && Parser) { + var Slice = nodes2.Node.extend("Slice", { + fields: ["start", "stop", "step"], + init: function init(lineno, colno, start, stop, step) { + start = start || new nodes2.Literal(lineno, colno, null); + stop = stop || new nodes2.Literal(lineno, colno, null); + step = step || new nodes2.Literal(lineno, colno, 1); + this.parent(lineno, colno, start, stop, step); + } + }); + Compiler.prototype.assertType = function assertType(node) { + if (node instanceof Slice) { + return; + } + orig_Compiler_assertType.apply(this, arguments); + }; + Compiler.prototype.compileSlice = function compileSlice(node, frame) { + this._emit("("); + this._compileExpression(node.start, frame); + this._emit("),("); + this._compileExpression(node.stop, frame); + this._emit("),("); + this._compileExpression(node.step, frame); + this._emit(")"); + }; + Parser.prototype.parseAggregate = function parseAggregate() { + var _this = this; + var origState = getTokensState(this.tokens); + origState.colno--; + origState.index--; + try { + return orig_Parser_parseAggregate.apply(this); + } catch (e2) { + var errState = getTokensState(this.tokens); + var rethrow = function rethrow2() { + lib2._assign(_this.tokens, errState); + return e2; + }; + lib2._assign(this.tokens, origState); + this.peeked = false; + var tok = this.peekToken(); + if (tok.type !== lexer2.TOKEN_LEFT_BRACKET) { + throw rethrow(); + } else { + this.nextToken(); + } + var node = new Slice(tok.lineno, tok.colno); + var isSlice = false; + for (var i = 0; i <= node.fields.length; i++) { + if (this.skip(lexer2.TOKEN_RIGHT_BRACKET)) { + break; + } + if (i === node.fields.length) { + if (isSlice) { + this.fail("parseSlice: too many slice components", tok.lineno, tok.colno); + } else { + break; + } + } + if (this.skip(lexer2.TOKEN_COLON)) { + isSlice = true; + } else { + var field = node.fields[i]; + node[field] = this.parseExpression(); + isSlice = this.skip(lexer2.TOKEN_COLON) || isSlice; + } + } + if (!isSlice) { + throw rethrow(); + } + return new nodes2.Array(tok.lineno, tok.colno, [node]); + } + }; + } + function sliceLookup(obj, start, stop, step) { + obj = obj || []; + if (start === null) { + start = step < 0 ? obj.length - 1 : 0; + } + if (stop === null) { + stop = step < 0 ? -1 : obj.length; + } else if (stop < 0) { + stop += obj.length; + } + if (start < 0) { + start += obj.length; + } + var results = []; + for (var i = start; ; i += step) { + if (i < 0 || i > obj.length) { + break; + } + if (step > 0 && i >= stop) { + break; + } + if (step < 0 && i <= stop) { + break; + } + results.push(runtime2.memberLookup(obj, i)); + } + return results; + } + function hasOwnProp(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + var ARRAY_MEMBERS = { + pop: function pop(index) { + if (index === void 0) { + return this.pop(); + } + if (index >= this.length || index < 0) { + throw new Error("KeyError"); + } + return this.splice(index, 1); + }, + append: function append(element) { + return this.push(element); + }, + remove: function remove(element) { + for (var i = 0; i < this.length; i++) { + if (this[i] === element) { + return this.splice(i, 1); + } + } + throw new Error("ValueError"); + }, + count: function count(element) { + var count2 = 0; + for (var i = 0; i < this.length; i++) { + if (this[i] === element) { + count2++; + } + } + return count2; + }, + index: function index(element) { + var i; + if ((i = this.indexOf(element)) === -1) { + throw new Error("ValueError"); + } + return i; + }, + find: function find(element) { + return this.indexOf(element); + }, + insert: function insert(index, elem) { + return this.splice(index, 0, elem); + } + }; + var OBJECT_MEMBERS = { + items: function items() { + return lib2._entries(this); + }, + values: function values() { + return lib2._values(this); + }, + keys: function keys() { + return lib2.keys(this); + }, + get: function get(key, def) { + var output = this[key]; + if (output === void 0) { + output = def; + } + return output; + }, + has_key: function has_key(key) { + return hasOwnProp(this, key); + }, + pop: function pop(key, def) { + var output = this[key]; + if (output === void 0 && def !== void 0) { + output = def; + } else if (output === void 0) { + throw new Error("KeyError"); + } else { + delete this[key]; + } + return output; + }, + popitem: function popitem() { + var keys = lib2.keys(this); + if (!keys.length) { + throw new Error("KeyError"); + } + var k = keys[0]; + var val = this[k]; + delete this[k]; + return [k, val]; + }, + setdefault: function setdefault(key, def) { + if (def === void 0) { + def = null; + } + if (!(key in this)) { + this[key] = def; + } + return this[key]; + }, + update: function update(kwargs) { + lib2._assign(this, kwargs); + return null; + } + }; + OBJECT_MEMBERS.iteritems = OBJECT_MEMBERS.items; + OBJECT_MEMBERS.itervalues = OBJECT_MEMBERS.values; + OBJECT_MEMBERS.iterkeys = OBJECT_MEMBERS.keys; + runtime2.memberLookup = function memberLookup(obj, val, autoescape) { + if (arguments.length === 4) { + return sliceLookup.apply(this, arguments); + } + obj = obj || {}; + if (lib2.isArray(obj) && hasOwnProp(ARRAY_MEMBERS, val)) { + return ARRAY_MEMBERS[val].bind(obj); + } + if (lib2.isObject(obj) && hasOwnProp(OBJECT_MEMBERS, val)) { + return OBJECT_MEMBERS[val].bind(obj); + } + return orig_memberLookup.apply(this, arguments); + }; + return uninstall; + } + module2.exports = installCompat; +}); + +// ../../node_modules/nunjucks/index.js +"use strict"; +var lib = require_lib(); +var _require = require_environment(); +var Environment = _require.Environment; +var Template = _require.Template; +var Loader = require_loader(); +var loaders = require_loaders(); +var precompile = require_precompile(); +var compiler = require_compiler(); +var parser = require_parser(); +var lexer = require_lexer(); +var runtime = require_runtime(); +var nodes = require_nodes(); +var installJinjaCompat = require_jinja_compat(); +var e; +function configure(templatesPath, opts) { + opts = opts || {}; + if (lib.isObject(templatesPath)) { + opts = templatesPath; + templatesPath = null; + } + var TemplateLoader; + if (loaders.FileSystemLoader) { + TemplateLoader = new loaders.FileSystemLoader(templatesPath, { + watch: opts.watch, + noCache: opts.noCache + }); + } else if (loaders.WebLoader) { + TemplateLoader = new loaders.WebLoader(templatesPath, { + useCache: opts.web && opts.web.useCache, + async: opts.web && opts.web.async + }); + } + e = new Environment(TemplateLoader, opts); + if (opts && opts.express) { + e.express(opts.express); + } + return e; +} +module.exports = { + Environment, + Template, + Loader, + FileSystemLoader: loaders.FileSystemLoader, + NodeResolveLoader: loaders.NodeResolveLoader, + PrecompiledLoader: loaders.PrecompiledLoader, + WebLoader: loaders.WebLoader, + compiler, + parser, + lexer, + runtime, + lib, + nodes, + installJinjaCompat, + configure, + reset: function reset() { + e = void 0; + }, + compile: function compile(src, env, path, eagerCompile) { + if (!e) { + configure(); + } + return new Template(src, env, path, eagerCompile); + }, + render: function render(name, ctx, cb) { + if (!e) { + configure(); + } + return e.render(name, ctx, cb); + }, + renderString: function renderString(src, ctx, cb) { + if (!e) { + configure(); + } + return e.renderString(src, ctx, cb); + }, + precompile: precompile ? precompile.precompile : void 0, + precompileString: precompile ? precompile.precompileString : void 0 +}; diff --git a/plugins/scaffolder-backend/config.d.ts b/plugins/scaffolder-backend/config.d.ts index 126c55e166..aa4ecf8053 100644 --- a/plugins/scaffolder-backend/config.d.ts +++ b/plugins/scaffolder-backend/config.d.ts @@ -28,30 +28,30 @@ export interface Config { * The commit message used when new components are created. */ defaultCommitMessage?: string; + /** + * @deprecated Replaced by parameters for the publish:github action + */ github?: { [key: string]: string; - /** - * The visibility to set on created repositories. - */ - visibility?: 'public' | 'internal' | 'private'; }; + /** + * @deprecated Use the Gitlab integration instead + */ gitlab?: { api: { [key: string]: string }; - /** - * The visibility to set on created repositories. - */ - visibility?: 'public' | 'internal' | 'private'; }; + /** + * @deprecated Use the Azure integration instead + */ azure?: { baseUrl: string; api: { [key: string]: string }; }; + /** + * @deprecated Use the Bitbucket integration instead + */ bitbucket?: { api: { [key: string]: string }; - /** - * The visibility to set on created repositories. - */ - visibility?: 'public' | 'private'; }; }; } diff --git a/plugins/scaffolder-backend/package.json b/plugins/scaffolder-backend/package.json index 36ac76c95f..bbe59d6458 100644 --- a/plugins/scaffolder-backend/package.json +++ b/plugins/scaffolder-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-scaffolder-backend", "description": "The Backstage backend plugin that helps you create new things", - "version": "0.15.13", + "version": "0.15.15", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -27,18 +27,19 @@ "test": "backstage-cli test", "prepack": "backstage-cli prepack", "postpack": "backstage-cli postpack", - "clean": "backstage-cli clean" + "clean": "backstage-cli clean", + "build:assets": "node scripts/build-nunjucks.js" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", - "@backstage/plugin-catalog-backend": "^0.17.4", + "@backstage/errors": "^0.1.5", + "@backstage/integration": "^0.6.10", + "@backstage/plugin-catalog-backend": "^0.19.0", "@backstage/plugin-scaffolder-common": "^0.1.1", - "@backstage/plugin-scaffolder-backend-module-cookiecutter": "^0.1.4", + "@backstage/plugin-scaffolder-backend-module-cookiecutter": "^0.1.5", "@backstage/types": "^0.1.1", "@gitbeaker/core": "^34.6.0", "@gitbeaker/node": "^34.6.0", @@ -49,7 +50,6 @@ "command-exists": "^1.2.9", "compression": "^1.7.4", "cors": "^2.8.5", - "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", "fs-extra": "10.0.0", @@ -64,21 +64,24 @@ "lodash": "^4.17.21", "luxon": "^2.0.2", "morgan": "^1.10.0", + "node-fetch": "^2.6.1", "nunjucks": "^3.2.3", "octokit-plugin-create-pull-request": "^3.10.0", "uuid": "^8.2.0", "winston": "^3.2.1", - "yaml": "^1.10.0" + "yaml": "^1.10.0", + "vm2": "^3.9.5" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/test-utils": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.23", "@types/command-exists": "^1.2.0", "@types/fs-extra": "^9.0.1", "@types/git-url-parse": "^9.0.0", "@types/mock-fs": "^4.13.0", "@types/nunjucks": "^3.1.4", "@types/supertest": "^2.0.8", + "esbuild": "^0.14.1", "jest-when": "^3.1.0", "mock-fs": "^5.1.0", "msw": "^0.35.0", @@ -88,7 +91,8 @@ "files": [ "dist", "migrations", - "config.d.ts" + "config.d.ts", + "assets" ], "configSchema": "config.d.ts" } diff --git a/plugins/scaffolder-backend/scripts/build-nunjucks.js b/plugins/scaffolder-backend/scripts/build-nunjucks.js new file mode 100755 index 0000000000..b195f96159 --- /dev/null +++ b/plugins/scaffolder-backend/scripts/build-nunjucks.js @@ -0,0 +1,69 @@ +#!/usr/bin/env node +/* + * Copyright 2021 The Backstage Authors + * + * 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-syntax */ +/* eslint-disable import/no-extraneous-dependencies */ + +const path = require('path'); + +const NUNJUCKS_LICENSE = `/** + * Copyright (c) 2012-2015, James Long + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +`; + +// This script is used to bundle nunjucks into a single script that is +// loaded into a sandbox for executing templates. +require('esbuild') + .build({ + entryPoints: [require.resolve('nunjucks')], + bundle: true, + format: 'cjs', + platform: 'node', + target: 'node14', + banner: { js: NUNJUCKS_LICENSE }, + external: ['fsevents'], + outfile: path.resolve(__dirname, '../assets/nunjucks.js.txt'), + }) + .catch(err => { + console.log(err.stack); + process.exit(1); + }); diff --git a/plugins/scaffolder-backend/src/lib/templating/SecureTemplater.test.ts b/plugins/scaffolder-backend/src/lib/templating/SecureTemplater.test.ts new file mode 100644 index 0000000000..134b877efe --- /dev/null +++ b/plugins/scaffolder-backend/src/lib/templating/SecureTemplater.test.ts @@ -0,0 +1,145 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { SecureTemplater } from './SecureTemplater'; + +describe('SecureTemplater', () => { + it('should render some templates', async () => { + const render = await SecureTemplater.loadRenderer(); + expect(render('${{ test }}', { test: 'my-value' })).toBe('my-value'); + + expect(render('${{ test | dump }}', { test: 'my-value' })).toBe( + '"my-value"', + ); + + expect( + render('${{ test | replace("my-", "our-") }}', { + test: 'my-value', + }), + ).toBe('our-value'); + + expect(() => + render('${{ invalid...syntax }}', { + test: 'my-value', + }), + ).toThrow(/expected name as lookup value, got ./); + }); + + it('should make cookiecutter compatibility available when requested', async () => { + const renderWith = await SecureTemplater.loadRenderer({ + cookiecutterCompat: true, + }); + const renderWithout = await SecureTemplater.loadRenderer(); + + // Same two tests repeated to make sure switching back and forth works + expect(renderWith('{{ 1 | jsonify }}', {})).toBe('1'); + expect(renderWith('{{ 1 | jsonify }}', {})).toBe('1'); + expect(() => renderWithout('${{ 1 | jsonify }}', {})).toThrow( + /Error: filter not found: jsonify/, + ); + expect(renderWith('{{ 1 | jsonify }}', {})).toBe('1'); + expect(() => renderWithout('${{ 1 | jsonify }}', {})).toThrow( + /Error: filter not found: jsonify/, + ); + expect(() => renderWithout('${{ 1 | jsonify }}', {})).toThrow( + /Error: filter not found: jsonify/, + ); + expect(() => renderWithout('${{ 1 | jsonify }}', {})).toThrow( + /Error: filter not found: jsonify/, + ); + expect(renderWith('{{ 1 | jsonify }}', {})).toBe('1'); + }); + + it('should make parseRepoUrl available when requested', async () => { + const parseRepoUrl = jest.fn(() => ({ + repo: 'my-repo', + owner: 'my-owner', + host: 'my-host.com', + })); + const renderWith = await SecureTemplater.loadRenderer({ parseRepoUrl }); + const renderWithout = await SecureTemplater.loadRenderer(); + + const ctx = { + repoUrl: 'https://my-host.com/my-owner/my-repo', + }; + + expect(renderWith('${{ repoUrl | parseRepoUrl | dump }}', ctx)).toBe( + JSON.stringify({ + repo: 'my-repo', + owner: 'my-owner', + host: 'my-host.com', + }), + ); + expect(renderWith('${{ repoUrl | projectSlug }}', ctx)).toBe( + 'my-owner/my-repo', + ); + expect(() => + renderWithout('${{ repoUrl | parseRepoUrl | dump }}', ctx), + ).toThrow(/Error: filter not found: parseRepoUrl/); + expect(() => renderWithout('${{ repoUrl | projectSlug }}', ctx)).toThrow( + /Error: filter not found: projectSlug/, + ); + + expect(parseRepoUrl.mock.calls).toEqual([ + ['https://my-host.com/my-owner/my-repo'], + ['https://my-host.com/my-owner/my-repo'], + ]); + }); + + it('should not allow helpers to be rewritten', async () => { + const render = await SecureTemplater.loadRenderer({ + parseRepoUrl: () => ({ + repo: 'my-repo', + owner: 'my-owner', + host: 'my-host.com', + }), + }); + + const ctx = { + repoUrl: 'https://my-host.com/my-owner/my-repo', + }; + expect( + render( + '${{ ({}).constructor.constructor("parseRepoUrl = () => JSON.stringify(`inject`)")() }}', + ctx, + ), + ).toBe(''); + + expect(render('${{ repoUrl | parseRepoUrl | dump }}', ctx)).toBe( + JSON.stringify({ + repo: 'my-repo', + owner: 'my-owner', + host: 'my-host.com', + }), + ); + }); + + it('allows pollution during a single template execution', async () => { + const render = await SecureTemplater.loadRenderer(); + + const ctx = { + x: 'foo', + }; + expect(render('${{ x }}', ctx)).toBe('foo'); + expect( + render( + '${{ ({}).constructor.constructor("Array.prototype.forEach = () => {}")() }}', + ctx, + ), + ).toBe(''); + expect(() => render('${{ x }}', ctx)).toThrow(); + }); +}); diff --git a/plugins/scaffolder-backend/src/lib/templating/SecureTemplater.ts b/plugins/scaffolder-backend/src/lib/templating/SecureTemplater.ts new file mode 100644 index 0000000000..54c9166020 --- /dev/null +++ b/plugins/scaffolder-backend/src/lib/templating/SecureTemplater.ts @@ -0,0 +1,141 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { VM } from 'vm2'; +import { resolvePackagePath } from '@backstage/backend-common'; +import fs from 'fs-extra'; +import { RepoSpec } from '../../scaffolder/actions/builtin/publish/util'; + +const mkScript = (nunjucksSource: string) => ` +const { render, renderCompat } = (() => { + const module = {}; + const process = { env: {} }; + const require = (pkg) => { if (pkg === 'events') { return function (){}; }}; + + ${nunjucksSource} + + const env = module.exports.configure({ + autoescape: false, + tags: { + variableStart: '\${{', + variableEnd: '}}', + }, + }); + + const compatEnv = module.exports.configure({ + autoescape: false, + tags: { + variableStart: '{{', + variableEnd: '}}', + }, + }); + compatEnv.addFilter('jsonify', compatEnv.getFilter('dump')); + + if (typeof parseRepoUrl !== 'undefined') { + const safeHelperRef = parseRepoUrl; + + env.addFilter('parseRepoUrl', repoUrl => { + return JSON.parse(safeHelperRef(repoUrl)) + }); + env.addFilter('projectSlug', repoUrl => { + const { owner, repo } = JSON.parse(safeHelperRef(repoUrl)); + return owner + '/' + repo; + }); + } + + let uninstallCompat = undefined; + + function render(str, values) { + try { + if (uninstallCompat) { + uninstallCompat(); + uninstallCompat = undefined; + } + return env.renderString(str, JSON.parse(values)); + } catch (error) { + // Make sure errors don't leak anything + throw new Error(String(error.message)); + } + } + + function renderCompat(str, values) { + try { + if (!uninstallCompat) { + uninstallCompat = module.exports.installJinjaCompat(); + } + return compatEnv.renderString(str, JSON.parse(values)); + } catch (error) { + // Make sure errors don't leak anything + throw new Error(String(error.message)); + } + } + + return { render, renderCompat }; +})(); +`; + +export interface SecureTemplaterOptions { + /* Optional implementation of the parseRepoUrl filter */ + parseRepoUrl?(repoUrl: string): RepoSpec; + + /* Enables jinja compatibility and the "jsonify" filter */ + cookiecutterCompat?: boolean; +} + +export type SecureTemplateRenderer = ( + template: string, + values: unknown, +) => string; + +export class SecureTemplater { + static async loadRenderer(options: SecureTemplaterOptions = {}) { + const { parseRepoUrl, cookiecutterCompat } = options; + let sandbox = undefined; + + if (parseRepoUrl) { + sandbox = { + parseRepoUrl: (url: string) => JSON.stringify(parseRepoUrl(url)), + }; + } + + const vm = new VM({ sandbox }); + + const nunjucksSource = await fs.readFile( + resolvePackagePath( + '@backstage/plugin-scaffolder-backend', + 'assets/nunjucks.js.txt', + ), + 'utf-8', + ); + + vm.run(mkScript(nunjucksSource)); + + const render: SecureTemplateRenderer = (template, values) => { + if (!vm) { + throw new Error('SecureTemplater has not been initialized'); + } + vm.setGlobal('templateStr', template); + vm.setGlobal('templateValues', JSON.stringify(values)); + + if (cookiecutterCompat) { + return vm.run(`renderCompat(templateStr, templateValues)`); + } + + return vm.run(`render(templateStr, templateValues)`); + }; + return render; + } +} diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/write.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/write.ts index 45481b47e6..b813244020 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/write.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/catalog/write.ts @@ -15,10 +15,10 @@ */ import fs from 'fs-extra'; -import { resolve as resolvePath } from 'path'; import { createTemplateAction } from '../../createTemplateAction'; import * as yaml from 'yaml'; import { Entity } from '@backstage/catalog-model'; +import { resolveSafeChildPath } from '@backstage/backend-common'; export function createCatalogWriteAction() { return createTemplateAction<{ name?: string; entity: Entity }>({ @@ -42,7 +42,7 @@ export function createCatalogWriteAction() { const { entity } = ctx.input; await fs.writeFile( - resolvePath(ctx.workspacePath, 'catalog-info.yaml'), + resolveSafeChildPath(ctx.workspacePath, 'catalog-info.yaml'), yaml.stringify(entity), ); }, diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.ts index 9bf9b7fb90..36ea842a66 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/debug/log.ts @@ -15,7 +15,7 @@ */ import { readdir, stat } from 'fs-extra'; -import { relative, resolve } from 'path'; +import { relative, join } from 'path'; import { createTemplateAction } from '../../createTemplateAction'; /** @@ -68,7 +68,7 @@ export async function recursiveReadDir(dir: string): Promise { const subdirs = await readdir(dir); const files = await Promise.all( subdirs.map(async subdir => { - const res = resolve(dir, subdir); + const res = join(dir, subdir); return (await stat(res)).isDirectory() ? recursiveReadDir(res) : [res]; }), ); diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/helpers.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/helpers.ts index 3946110d42..b56bab0d53 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/helpers.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/helpers.ts @@ -19,7 +19,7 @@ import { JsonValue } from '@backstage/types'; import { InputError } from '@backstage/errors'; import { ScmIntegrations } from '@backstage/integration'; import fs from 'fs-extra'; -import * as path from 'path'; +import path from 'path'; export async function fetchContents({ reader, diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts index 755b435149..cf1662307c 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.test.ts @@ -33,6 +33,17 @@ jest.mock('./helpers', () => ({ fetchContents: jest.fn(), })); +const realFiles = Object.fromEntries( + [ + require.resolve('vm2/lib/fixasync'), + resolvePackagePath( + '@backstage/plugin-scaffolder-backend', + 'assets', + 'nunjucks.js.txt', + ), + ].map(k => [k, mockFs.load(k)]), +); + const aBinaryFile = fs.readFileSync( resolvePackagePath( '@backstage/plugin-scaffolder-backend', @@ -76,7 +87,9 @@ describe('fetch:template', () => { }); beforeEach(() => { - mockFs(); + mockFs({ + ...realFiles, + }); action = createFetchTemplateAction({ reader: Symbol('UrlReader') as unknown as UrlReader, @@ -150,6 +163,7 @@ describe('fetch:template', () => { mockFetchContents.mockImplementation(({ outputPath }) => { mockFs({ + ...realFiles, [outputPath]: { 'an-executable.sh': mockFs.file({ content: '#!/usr/bin/env bash', @@ -259,6 +273,7 @@ describe('fetch:template', () => { mockFetchContents.mockImplementation(({ outputPath }) => { mockFs({ + ...realFiles, [outputPath]: { processed: { 'templated-content-${{ values.name }}.txt': @@ -312,6 +327,7 @@ describe('fetch:template', () => { mockFetchContents.mockImplementation(({ outputPath }) => { mockFs({ + ...realFiles, [outputPath]: { '{{ cookiecutter.name }}.txt': 'static content', subdir: { @@ -366,6 +382,7 @@ describe('fetch:template', () => { mockFetchContents.mockImplementation(({ outputPath }) => { mockFs({ + ...realFiles, [outputPath]: { 'empty-dir-${{ values.count }}': {}, 'static.txt': 'static content', @@ -447,6 +464,7 @@ describe('fetch:template', () => { mockFetchContents.mockImplementation(({ outputPath }) => { mockFs({ + ...realFiles, [outputPath]: { '${{ values.name }}.njk': '${{ values.name }}: ${{ values.count }}', '${{ values.name }}.txt.jinja2': diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.ts index 47bfcccfdf..2e25547e61 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/fetch/template.ts @@ -14,29 +14,16 @@ * limitations under the License. */ -import { resolve as resolvePath, extname } from 'path'; +import { extname } from 'path'; import { resolveSafeChildPath, UrlReader } from '@backstage/backend-common'; import { InputError } from '@backstage/errors'; import { ScmIntegrations } from '@backstage/integration'; import { fetchContents } from './helpers'; import { createTemplateAction } from '../../createTemplateAction'; import globby from 'globby'; -import nunjucks from 'nunjucks'; import fs from 'fs-extra'; import { isBinaryFile } from 'isbinaryfile'; - -/* - * Maximise compatibility with Jinja (and therefore cookiecutter) - * using nunjucks jinja compat mode. Since this method mutates - * the global nunjucks instance, we can't enable this per-template, - * or only for templates with cookiecutter compat enabled, so the - * next best option is to explicitly enable it globally and allow - * folks to rely on jinja compatibility behaviour in fetch:template - * templates if they wish. - * - * cf. https://mozilla.github.io/nunjucks/api.html#installjinjacompat - */ -nunjucks.installJinjaCompat(); +import { SecureTemplater } from '../../../../lib/templating/SecureTemplater'; type CookieCompatInput = { copyWithoutRender?: string[]; @@ -114,7 +101,7 @@ export function createFetchTemplateAction(options: { ctx.logger.info('Fetching template content from remote URL'); const workDir = await ctx.createTemporaryDirectory(); - const templateDir = resolvePath(workDir, 'template'); + const templateDir = resolveSafeChildPath(workDir, 'template'); const targetPath = ctx.input.targetPath ?? './'; const outputDir = resolveSafeChildPath(ctx.workspacePath, targetPath); @@ -179,36 +166,6 @@ export function createFetchTemplateAction(options: { ).flat(), ); - // Create a templater - const templater = nunjucks.configure({ - ...(ctx.input.cookiecutterCompat - ? {} - : { - tags: { - // TODO(mtlewis/orkohunter): Document Why we are changing the literals? Not here, but on scaffolder docs. ADR? - variableStart: '${{', - variableEnd: '}}', - }, - }), - // We don't want this builtin auto-escaping, since uses HTML escape sequences - // like `"` - the correct way to escape strings in our case depends on - // the file type. - autoescape: false, - }); - - if (ctx.input.cookiecutterCompat) { - // The "jsonify" filter built into cookiecutter is common - // in fetch:cookiecutter templates, so when compat mode - // is enabled we alias the "dump" filter from nunjucks as - // jsonify. Dump accepts an optional `spaces` parameter - // which enables indented output, but when this parameter - // is not supplied it works identically to jsonify. - // - // cf. https://cookiecutter.readthedocs.io/en/latest/advanced/template_extensions.html?highlight=jsonify#jsonify-extension - // cf. https://mozilla.github.io/nunjucks/templating.html#dump - templater.addFilter('jsonify', templater.getFilter('dump')); - } - // Cookiecutter prefixes all parameters in templates with // `cookiecutter.`. To replicate this, we wrap our parameters // in an object with a `cookiecutter` property when compat @@ -223,6 +180,10 @@ export function createFetchTemplateAction(options: { ctx.input.values, ); + const renderTemplate = await SecureTemplater.loadRenderer({ + cookiecutterCompat: ctx.input.cookiecutterCompat, + }); + for (const location of allEntriesInTemplate) { let renderFilename: boolean; let renderContents: boolean; @@ -238,9 +199,9 @@ export function createFetchTemplateAction(options: { renderFilename = renderContents = !nonTemplatedEntries.has(location); } if (renderFilename) { - localOutputPath = templater.renderString(localOutputPath, context); + localOutputPath = renderTemplate(localOutputPath, context); } - const outputPath = resolvePath(outputDir, localOutputPath); + const outputPath = resolveSafeChildPath(outputDir, localOutputPath); // variables have been expanded to make an empty file name // this is due to a conditional like if values.my_condition then file-name.txt else empty string so skip if (outputDir === outputPath) { @@ -259,7 +220,7 @@ export function createFetchTemplateAction(options: { ); await fs.ensureDir(outputPath); } else { - const inputFilePath = resolvePath(templateDir, location); + const inputFilePath = resolveSafeChildPath(templateDir, location); if (await isBinaryFile(inputFilePath)) { ctx.logger.info( @@ -275,7 +236,7 @@ export function createFetchTemplateAction(options: { await fs.outputFile( outputPath, renderContents - ? templater.renderString(inputFileContents, context) + ? renderTemplate(inputFileContents, context) : inputFileContents, { mode: statsObj.mode }, ); diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/helpers.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/helpers.ts index eff65e329f..90f060fd88 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/helpers.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/helpers.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { spawn } from 'child_process'; +import { SpawnOptionsWithoutStdio, spawn } from 'child_process'; import { PassThrough, Writable } from 'stream'; import { Logger } from 'winston'; import { Git } from '@backstage/backend-common'; @@ -22,18 +22,27 @@ import { Octokit } from '@octokit/rest'; import { assertError } from '@backstage/errors'; export type RunCommandOptions = { + /** command to run */ command: string; + /** arguments to pass the command */ args: string[]; + /** options to pass to spawn */ + options?: SpawnOptionsWithoutStdio; + /** stream to capture stdout and stderr output */ logStream?: Writable; }; +/** + * Run a command in a sub-process, normally a shell command. + */ export const runCommand = async ({ command, args, logStream = new PassThrough(), + options, }: RunCommandOptions) => { await new Promise((resolve, reject) => { - const process = spawn(command, args); + const process = spawn(command, args, options); process.stdout.on('data', stream => { logStream.write(stream); diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.ts index daa6bc249b..fbfe87b076 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/bitbucket.ts @@ -19,7 +19,7 @@ import { BitbucketIntegrationConfig, ScmIntegrationRegistry, } from '@backstage/integration'; -import fetch from 'cross-fetch'; +import fetch, { Response, RequestInit } from 'node-fetch'; import { initRepoAndPush } from '../helpers'; import { createTemplateAction } from '../../createTemplateAction'; import { getRepoSourceDirectory, parseRepoUrl } from './util'; diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts index 0cceb47d71..3a9dd01686 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts @@ -15,7 +15,6 @@ */ import fs from 'fs-extra'; -import path from 'path'; import { parseRepoUrl, isExecutable } from './util'; import { @@ -197,7 +196,7 @@ export const createPublishGithubPullRequestAction = ({ const fileContents = await Promise.all( localFilePaths.map(filePath => { - const absPath = path.resolve(fileRoot, filePath); + const absPath = resolveSafeChildPath(fileRoot, filePath); const base64EncodedContent = fs .readFileSync(absPath) .toString('base64'); diff --git a/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.test.ts b/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.test.ts index b2e2e85a6c..b933990953 100644 --- a/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.test.ts @@ -17,13 +17,24 @@ import mockFs from 'mock-fs'; import * as winston from 'winston'; -import { getVoidLogger } from '@backstage/backend-common'; +import { getVoidLogger, resolvePackagePath } from '@backstage/backend-common'; import { NunjucksWorkflowRunner } from './NunjucksWorkflowRunner'; import { TemplateActionRegistry } from '../actions'; import { ScmIntegrations } from '@backstage/integration'; import { ConfigReader } from '@backstage/config'; import { TaskContext, TaskSpec } from './types'; +const realFiles = Object.fromEntries( + [ + require.resolve('vm2/lib/fixasync'), + resolvePackagePath( + '@backstage/plugin-scaffolder-backend', + 'assets', + 'nunjucks.js.txt', + ), + ].map(k => [k, mockFs.load(k)]), +); + describe('DefaultWorkflowRunner', () => { const logger = getVoidLogger(); let actionRegistry = new TemplateActionRegistry(); @@ -50,6 +61,7 @@ describe('DefaultWorkflowRunner', () => { winston.format.simple(); // put logform the require cache before mocking fs mockFs({ '/tmp': mockFs.directory(), + ...realFiles, }); jest.resetAllMocks(); diff --git a/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.ts b/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.ts index 5b42eef459..a3e30c65fe 100644 --- a/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.ts +++ b/plugins/scaffolder-backend/src/scaffolder/tasks/NunjucksWorkflowRunner.ts @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import { ScmIntegrations } from '@backstage/integration'; import { TaskContext, @@ -23,9 +24,9 @@ import { WorkflowRunner, } from './types'; import * as winston from 'winston'; -import nunjucks from 'nunjucks'; import fs from 'fs-extra'; import path from 'path'; +import nunjucks from 'nunjucks'; import { JsonObject, JsonValue } from '@backstage/types'; import { InputError } from '@backstage/errors'; import { PassThrough } from 'stream'; @@ -33,6 +34,10 @@ import { isTruthy } from './helper'; import { validate as validateJsonSchema } from 'jsonschema'; import { parseRepoUrl } from '../actions/builtin/publish/util'; import { TemplateActionRegistry } from '../actions'; +import { + SecureTemplater, + SecureTemplateRenderer, +} from '../../lib/templating/SecureTemplater'; type NunjucksWorkflowRunnerOptions = { workingDirectory: string; @@ -84,36 +89,31 @@ const createStepLogger = ({ }; export class NunjucksWorkflowRunner implements WorkflowRunner { - private readonly nunjucks: nunjucks.Environment; - - private readonly nunjucksOptions: nunjucks.ConfigureOptions = { - autoescape: false, - tags: { - variableStart: '${{', - variableEnd: '}}', - }, - }; - - constructor(private readonly options: NunjucksWorkflowRunnerOptions) { - this.nunjucks = nunjucks.configure(this.nunjucksOptions); - - // TODO(blam): let's work out how we can deprecate these. - // We shouldn't really need to be exposing these now we can deal with - // objects in the params block. - // Maybe we can expose a new RepoUrlPicker with secrets for V3 that provides an object already. - this.nunjucks.addFilter('parseRepoUrl', repoUrl => { - return parseRepoUrl(repoUrl, this.options.integrations); - }); - - this.nunjucks.addFilter('projectSlug', repoUrl => { - const { owner, repo } = parseRepoUrl(repoUrl, this.options.integrations); - return `${owner}/${repo}`; - }); - } + constructor(private readonly options: NunjucksWorkflowRunnerOptions) {} private isSingleTemplateString(input: string) { - const { parser, nodes } = require('nunjucks'); - const parsed = parser.parse(input, {}, this.nunjucksOptions); + const { parser, nodes } = nunjucks as unknown as { + parser: { + parse( + template: string, + ctx: object, + options: nunjucks.ConfigureOptions, + ): { children: { children?: unknown[] }[] }; + }; + nodes: { TemplateData: Function }; + }; + + const parsed = parser.parse( + input, + {}, + { + autoescape: false, + tags: { + variableStart: '${{', + variableEnd: '}}', + }, + }, + ); return ( parsed.children.length === 1 && @@ -121,7 +121,11 @@ export class NunjucksWorkflowRunner implements WorkflowRunner { ); } - private render(input: T, context: TemplateContext): T { + private render( + input: T, + context: TemplateContext, + renderTemplate: SecureTemplateRenderer, + ): T { return JSON.parse(JSON.stringify(input), (_key, value) => { try { if (typeof value === 'string') { @@ -134,10 +138,7 @@ export class NunjucksWorkflowRunner implements WorkflowRunner { ); // Run the templating - const templated = this.nunjucks.renderString( - wrappedDumped, - context, - ); + const templated = renderTemplate(wrappedDumped, context); // If there's an empty string returned, then it's undefined if (templated === '') { @@ -154,7 +155,7 @@ export class NunjucksWorkflowRunner implements WorkflowRunner { } // Fallback to default behaviour - const templated = this.nunjucks.renderString(value, context); + const templated = renderTemplate(value, context); if (templated === '') { return undefined; @@ -179,6 +180,18 @@ export class NunjucksWorkflowRunner implements WorkflowRunner { this.options.workingDirectory, await task.getWorkspaceName(), ); + + const { integrations } = this.options; + const renderTemplate = await SecureTemplater.loadRenderer({ + // TODO(blam): let's work out how we can deprecate this. + // We shouldn't really need to be exposing these now we can deal with + // objects in the params block. + // Maybe we can expose a new RepoUrlPicker with secrets for V3 that provides an object already. + parseRepoUrl(url: string) { + return parseRepoUrl(url, integrations); + }, + }); + try { await fs.ensureDir(workspacePath); await task.emitLog( @@ -193,7 +206,11 @@ export class NunjucksWorkflowRunner implements WorkflowRunner { for (const step of task.spec.steps) { try { if (step.if) { - const ifResult = await this.render(step.if, context); + const ifResult = await this.render( + step.if, + context, + renderTemplate, + ); if (!isTruthy(ifResult)) { await task.emitLog( `Skipping step ${step.id} because it's if condition was false`, @@ -211,7 +228,9 @@ export class NunjucksWorkflowRunner implements WorkflowRunner { const action = this.options.actionRegistry.get(step.action); const { taskLogger, streamLogger } = createStepLogger({ task, step }); - const input = (step.input && this.render(step.input, context)) ?? {}; + const input = + (step.input && this.render(step.input, context, renderTemplate)) ?? + {}; if (action.schema?.input) { const validateResult = validateJsonSchema( @@ -274,7 +293,7 @@ export class NunjucksWorkflowRunner implements WorkflowRunner { } } - const output = this.render(task.spec.output, context); + const output = this.render(task.spec.output, context, renderTemplate); return { output }; } finally { diff --git a/plugins/scaffolder-common/package.json b/plugins/scaffolder-common/package.json index 05d5ae3031..9099eda99d 100644 --- a/plugins/scaffolder-common/package.json +++ b/plugins/scaffolder-common/package.json @@ -40,6 +40,6 @@ "@backstage/types": "^0.1.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" } } diff --git a/plugins/scaffolder/CHANGELOG.md b/plugins/scaffolder/CHANGELOG.md index 8c43d8d010..b445ec873c 100644 --- a/plugins/scaffolder/CHANGELOG.md +++ b/plugins/scaffolder/CHANGELOG.md @@ -1,5 +1,40 @@ # @backstage/plugin-scaffolder +## 0.11.13 + +### Patch Changes + +- ed5bef529e: Add group filtering to the scaffolder page so that individuals can surface specific templates to end users ahead of others, or group templates together. This can be accomplished by passing in a `groups` prop to the `ScaffolderPage` + + ``` + + entity?.metadata?.tags?.includes('recommended') ?? false, + }, + ]} + /> + ``` + +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + +## 0.11.12 + +### Patch Changes + +- 2d7d165737: Bump `react-jsonschema-form` +- 9f21236a29: Fixed a missing `await` when throwing server side errors +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.11.11 ### Patch Changes diff --git a/plugins/scaffolder/api-report.md b/plugins/scaffolder/api-report.md index 0ac6910264..73fd8fae72 100644 --- a/plugins/scaffolder/api-report.md +++ b/plugins/scaffolder/api-report.md @@ -24,6 +24,7 @@ import { JSONSchema } from '@backstage/catalog-model'; import { JsonValue } from '@backstage/types'; import { Observable } from '@backstage/types'; import { default as React_2 } from 'react'; +import { ReactNode } from 'react'; import { RouteRef } from '@backstage/core-plugin-api'; import { ScmIntegrationRegistry } from '@backstage/integration'; import { TemplateEntityV1beta2 } from '@backstage/catalog-model'; @@ -213,12 +214,20 @@ export const ScaffolderFieldExtensions: React_2.ComponentType; // @public (undocumented) export const ScaffolderPage: ({ TemplateCardComponent, + groups, }: { TemplateCardComponent?: | ComponentType<{ template: TemplateEntityV1beta2; }> | undefined; + groups?: + | { + title?: string | undefined; + titleComponent?: ReactNode; + filter: (entity: Entity) => boolean; + }[] + | undefined; }) => JSX.Element; // Warning: (ae-missing-release-tag) "scaffolderPlugin" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -240,7 +249,8 @@ export { scaffolderPlugin }; // @public (undocumented) export const TemplateList: ({ TemplateCardComponent, -}: TemplateListProps) => JSX.Element; + group, +}: TemplateListProps) => JSX.Element | null; // Warning: (ae-missing-release-tag) "TemplateListProps" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -251,6 +261,11 @@ export type TemplateListProps = { template: TemplateEntityV1beta2; }> | undefined; + group?: { + title?: string; + titleComponent?: React_2.ReactNode; + filter: (entity: Entity) => boolean; + }; }; // Warning: (ae-missing-release-tag) "TemplateTypePicker" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) diff --git a/plugins/scaffolder/package.json b/plugins/scaffolder/package.json index ce185403bb..404bfcd387 100644 --- a/plugins/scaffolder/package.json +++ b/plugins/scaffolder/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-scaffolder", "description": "The Backstage plugin that helps you create new things", - "version": "0.11.11", + "version": "0.11.13", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -34,13 +34,13 @@ "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/errors": "^0.1.5", + "@backstage/integration": "^0.6.10", "@backstage/integration-react": "^0.1.14", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@backstage/types": "^0.1.1", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", @@ -66,10 +66,10 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/scaffolder/src/components/Router.tsx b/plugins/scaffolder/src/components/Router.tsx index 9e4736ab9f..e667c676f2 100644 --- a/plugins/scaffolder/src/components/Router.tsx +++ b/plugins/scaffolder/src/components/Router.tsx @@ -16,7 +16,7 @@ import React, { ComponentType } from 'react'; import { Routes, Route, useOutlet } from 'react-router'; -import { TemplateEntityV1beta2 } from '@backstage/catalog-model'; +import { TemplateEntityV1beta2, Entity } from '@backstage/catalog-model'; import { ScaffolderPage } from './ScaffolderPage'; import { TemplatePage } from './TemplatePage'; import { TaskPage } from './TaskPage'; @@ -34,9 +34,14 @@ type RouterProps = { TemplateCardComponent?: | ComponentType<{ template: TemplateEntityV1beta2 }> | undefined; + groups?: Array<{ + title?: string; + titleComponent?: React.ReactNode; + filter: (entity: Entity) => boolean; + }>; }; -export const Router = ({ TemplateCardComponent }: RouterProps) => { +export const Router = ({ TemplateCardComponent, groups }: RouterProps) => { const outlet = useOutlet(); const customFieldExtensions = useElementFilter(outlet, elements => @@ -64,7 +69,10 @@ export const Router = ({ TemplateCardComponent }: RouterProps) => { + } /> | undefined; + groups?: Array<{ + title?: string; + titleComponent?: React.ReactNode; + filter: (entity: Entity) => boolean; + }>; }; export const ScaffolderPageContents = ({ TemplateCardComponent, + groups, }: ScaffolderPageProps) => { const styles = useStyles(); - const registerComponentLink = useRouteRef(registerComponentRouteRef); + const otherTemplatesGroup = { + title: groups ? 'Other Templates' : 'Templates', + filter: (entity: Entity) => { + const filtered = (groups ?? []).map(group => group.filter(entity)); + return !filtered.some(result => result === true); + }, + }; return ( @@ -96,7 +108,17 @@ export const ScaffolderPageContents = ({
- + {groups && + groups.map(group => ( + + ))} +
@@ -106,8 +128,12 @@ export const ScaffolderPageContents = ({ export const ScaffolderPage = ({ TemplateCardComponent, + groups, }: ScaffolderPageProps) => ( - + ); diff --git a/plugins/scaffolder/src/components/TemplateList/TemplateList.tsx b/plugins/scaffolder/src/components/TemplateList/TemplateList.tsx index dcf708db10..9b66a0a9b6 100644 --- a/plugins/scaffolder/src/components/TemplateList/TemplateList.tsx +++ b/plugins/scaffolder/src/components/TemplateList/TemplateList.tsx @@ -16,10 +16,13 @@ import React, { ComponentType } from 'react'; import { + Entity, stringifyEntityRef, TemplateEntityV1beta2, } from '@backstage/catalog-model'; import { + Content, + ContentHeader, ItemCardGrid, Progress, WarningPanel, @@ -32,11 +35,31 @@ export type TemplateListProps = { TemplateCardComponent?: | ComponentType<{ template: TemplateEntityV1beta2 }> | undefined; + group?: { + title?: string; + titleComponent?: React.ReactNode; + filter: (entity: Entity) => boolean; + }; }; -export const TemplateList = ({ TemplateCardComponent }: TemplateListProps) => { +export const TemplateList = ({ + TemplateCardComponent, + group, +}: TemplateListProps) => { const { loading, error, entities } = useEntityListProvider(); const Card = TemplateCardComponent || TemplateCard; + const maybeFilteredEntities = group + ? entities.filter(e => group.filter(e)) + : entities; + const title = group ? ( + group.titleComponent || + ) : ( + + ); + + if (group && maybeFilteredEntities.length === 0) { + return null; + } return ( <> {loading && } @@ -57,16 +80,19 @@ export const TemplateList = ({ TemplateCardComponent }: TemplateListProps) => { )} - - {entities && - entities?.length > 0 && - entities.map(template => ( - - ))} - + + {title} + + {maybeFilteredEntities && + maybeFilteredEntities?.length > 0 && + maybeFilteredEntities.map((template: Entity) => ( + + ))} + + ); }; diff --git a/plugins/scaffolder/src/components/fields/RepoUrlPicker/RepoUrlPicker.tsx b/plugins/scaffolder/src/components/fields/RepoUrlPicker/RepoUrlPicker.tsx index f862fa66fe..c4b1e79262 100644 --- a/plugins/scaffolder/src/components/fields/RepoUrlPicker/RepoUrlPicker.tsx +++ b/plugins/scaffolder/src/components/fields/RepoUrlPicker/RepoUrlPicker.tsx @@ -27,7 +27,7 @@ import FormHelperText from '@material-ui/core/FormHelperText'; import { useApi } from '@backstage/core-plugin-api'; import { Progress } from '@backstage/core-components'; -function splitFormData(url: string | undefined) { +function splitFormData(url: string | undefined, allowedOwners?: string[]) { let host = undefined; let owner = undefined; let repo = undefined; @@ -39,7 +39,7 @@ function splitFormData(url: string | undefined) { if (url) { const parsed = new URL(`https://${url}`); host = parsed.host; - owner = parsed.searchParams.get('owner') || undefined; + owner = parsed.searchParams.get('owner') || allowedOwners?.[0]; repo = parsed.searchParams.get('repo') || undefined; // This is azure dev ops specific. not used for any other provider. organization = parsed.searchParams.get('organization') || undefined; @@ -95,13 +95,16 @@ export const RepoUrlPicker = ({ const scaffolderApi = useApi(scaffolderApiRef); const integrationApi = useApi(scmIntegrationsApiRef); const allowedHosts = uiSchema['ui:options']?.allowedHosts as string[]; + const allowedOwners = uiSchema['ui:options']?.allowedOwners as string[]; const { value: integrations, loading } = useAsync(async () => { return await scaffolderApi.getIntegrationsList({ allowedHosts }); }); - const { host, owner, repo, organization, workspace, project } = - splitFormData(formData); + const { host, owner, repo, organization, workspace, project } = splitFormData( + formData, + allowedOwners, + ); const updateHost = useCallback( (evt: React.ChangeEvent<{ name?: string; value: unknown }>) => { onChange( @@ -300,21 +303,57 @@ export const RepoUrlPicker = ({ )} {/* Show this for all hosts except bitbucket */} - {host && integrationApi.byHost(host)?.type !== 'bitbucket' && ( - <> - 0 && !owner} - > - Owner - - - The organization, user or project that this repo will belong to - - - - )} + {host && + integrationApi.byHost(host)?.type !== 'bitbucket' && + !allowedOwners && ( + <> + 0 && !owner} + > + Owner + + + The organization, user or project that this repo will belong to + + + + )} + {/* Show this for all hosts except bitbucket where allowed owner is set */} + {host && + integrationApi.byHost(host)?.type !== 'bitbucket' && + allowedOwners && ( + <> + 0 && !owner} + > + Owner Available + + + The organization, user or project that this repo will belong to + + + + )} {/* Show this for all hosts */} ) => ( + + + + - + + + + + + + + ... + ``` + +### Patch Changes + +- f06ecd09a7: Add optional icon and secondaryAction properties for DefaultResultListItem component +- c5941d5c30: Add a new optional clearButton property to the SearchBar component. The default value for this new property is true. +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + ## 0.4.18 ### Patch Changes diff --git a/plugins/search/api-report.md b/plugins/search/api-report.md index c211c48e53..3db26579e3 100644 --- a/plugins/search/api-report.md +++ b/plugins/search/api-report.md @@ -12,6 +12,7 @@ import { IndexableDocument } from '@backstage/search-common'; import { JsonObject } from '@backstage/types'; import { default as React_2 } from 'react'; import { ReactElement } from 'react'; +import { ReactNode } from 'react'; import { RouteRef } from '@backstage/core-plugin-api'; import { SearchQuery } from '@backstage/search-common'; import { SearchResult as SearchResult_2 } from '@backstage/search-common'; @@ -22,7 +23,11 @@ import { SearchResultSet } from '@backstage/search-common'; // @public (undocumented) export const DefaultResultListItem: ({ result, + icon, + secondaryAction, }: { + icon?: ReactNode; + secondaryAction?: ReactNode; result: IndexableDocument; }) => JSX.Element; @@ -69,7 +74,14 @@ export const HomePageSearchBar: ({ // @public (undocumented) export const Router: () => JSX.Element; -// Warning: (ae-forgotten-export) The symbol "SearchApi" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "SearchApi" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface SearchApi { + // (undocumented) + query(query: SearchQuery): Promise; +} + // Warning: (ae-missing-release-tag) "searchApiRef" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -84,6 +96,7 @@ export const SearchBar: ({ className, debounceTime, placeholder, + clearButton, }: Props) => JSX.Element; // Warning: (ae-missing-release-tag) "SearchBarNext" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -94,11 +107,13 @@ export const SearchBarNext: ({ className, debounceTime, placeholder, + clearButton, }: { autoFocus?: boolean | undefined; className?: string | undefined; debounceTime?: number | undefined; placeholder?: string | undefined; + clearButton?: boolean | undefined; }) => JSX.Element; // Warning: (ae-missing-release-tag) "SearchContextProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -213,7 +228,7 @@ export const useSearch: () => SearchContextValue; // Warnings were encountered during analysis: // -// src/components/SearchContext/SearchContext.d.ts:21:5 - (ae-forgotten-export) The symbol "SettableSearchContext" needs to be exported by the entry point index.d.ts +// src/components/SearchContext/SearchContext.d.ts:23:5 - (ae-forgotten-export) The symbol "SettableSearchContext" needs to be exported by the entry point index.d.ts // src/components/SearchFilter/SearchFilter.d.ts:13:5 - (ae-forgotten-export) The symbol "Props" needs to be exported by the entry point index.d.ts // src/components/SearchFilter/SearchFilter.d.ts:14:5 - (ae-forgotten-export) The symbol "Component" needs to be exported by the entry point index.d.ts ``` diff --git a/plugins/search/package.json b/plugins/search/package.json index aaddf130bf..1804a7aca8 100644 --- a/plugins/search/package.json +++ b/plugins/search/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-search", "description": "The Backstage plugin that provides your backstage app with search", - "version": "0.4.18", + "version": "0.5.0", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -32,12 +32,12 @@ "dependencies": { "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.4", "@backstage/plugin-catalog-react": "^0.6.4", "@backstage/search-common": "^0.2.1", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@backstage/types": "^0.1.1", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", @@ -51,10 +51,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.stories.tsx b/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.stories.tsx index 34436f9f93..0445a35943 100644 --- a/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.stories.tsx +++ b/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.stories.tsx @@ -16,6 +16,9 @@ import React from 'react'; import { Grid } from '@material-ui/core'; +import FindInPageIcon from '@material-ui/icons/FindInPage'; +import GroupIcon from '@material-ui/icons/Group'; +import { Button } from '@backstage/core-components'; import { DefaultResultListItem } from '../index'; import { MemoryRouter } from 'react-router'; @@ -24,17 +27,59 @@ export default { component: DefaultResultListItem, }; +const mockSearchResult = { + location: 'search/search-result', + title: 'Search Result 1', + text: 'some text from the search result', + owner: 'some-example-owner', +}; + export const Default = () => { + return ( + + + + + + + + ); +}; + +export const WithIcon = () => { return ( } + /> + + + + ); +}; + +export const WithSecondaryAction = () => { + return ( + + + + } + style={{ textTransform: 'lowercase' }} + > + {mockSearchResult.owner} + + } /> diff --git a/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.test.jsx b/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.test.jsx index 97698487ee..0a8e413107 100644 --- a/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.test.jsx +++ b/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.test.jsx @@ -17,7 +17,7 @@ import React from 'react'; import { screen } from '@testing-library/react'; import { renderInTestApp } from '@backstage/test-utils'; - +import FindInPageIcon from '@material-ui/icons/FindInPage'; import { DefaultResultListItem } from './DefaultResultListItem'; describe('DefaultResultListItem', () => { @@ -25,6 +25,7 @@ describe('DefaultResultListItem', () => { title: 'title', text: 'text', location: '/location', + owner: 'owner', }; it('Links to result.location', async () => { @@ -38,4 +39,21 @@ describe('DefaultResultListItem', () => { result.title + result.text, ); }); + + it('should render icon if prop is specified', async () => { + await renderInTestApp( + } + />, + ); + expect(screen.getByTitle('icon')).toBeInTheDocument(); + }); + + it('should render secondary action if prop is specified', async () => { + await renderInTestApp( + , + ); + expect(screen.getByText('owner')).toBeInTheDocument(); + }); }); diff --git a/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.tsx b/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.tsx index ed508aa671..dd541b6e21 100644 --- a/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.tsx +++ b/plugins/search/src/components/DefaultResultListItem/DefaultResultListItem.tsx @@ -14,24 +14,38 @@ * limitations under the License. */ -import React from 'react'; +import React, { ReactNode } from 'react'; import { IndexableDocument } from '@backstage/search-common'; -import { ListItem, ListItemText, Divider } from '@material-ui/core'; +import { + ListItem, + ListItemIcon, + ListItemText, + Box, + Divider, +} from '@material-ui/core'; import { Link } from '@backstage/core-components'; type Props = { + icon?: ReactNode; + secondaryAction?: ReactNode; result: IndexableDocument; }; -export const DefaultResultListItem = ({ result }: Props) => { +export const DefaultResultListItem = ({ + result, + icon, + secondaryAction, +}: Props) => { return ( - + + {icon && {icon}} + {secondaryAction && {secondaryAction}} diff --git a/plugins/search/src/components/SearchBar/SearchBar.stories.tsx b/plugins/search/src/components/SearchBar/SearchBar.stories.tsx index 72b8429026..d00f391bc7 100644 --- a/plugins/search/src/components/SearchBar/SearchBar.stories.tsx +++ b/plugins/search/src/components/SearchBar/SearchBar.stories.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import { Paper, Grid } from '@material-ui/core'; +import { Paper, Grid, makeStyles } from '@material-ui/core'; import { SearchBar, SearchContext } from '../index'; import { MemoryRouter } from 'react-router'; @@ -81,3 +81,48 @@ export const Focused = () => { ); }; + +export const WithoutClearButton = () => { + return ( + + {/* @ts-ignore (defaultValue requires more than what is used here) */} + + + + + + + + + + + ); +}; + +const useStyles = makeStyles({ + search: { + display: 'flex', + justifyContent: 'space-between', + padding: '8px 0', + borderRadius: '50px', + margin: 'auto', + }, +}); + +export const CustomStyles = () => { + const classes = useStyles(); + return ( + + {/* @ts-ignore (defaultValue requires more than what is used here) */} + + + + + + + + + + + ); +}; diff --git a/plugins/search/src/components/SearchBar/SearchBar.test.tsx b/plugins/search/src/components/SearchBar/SearchBar.test.tsx index 81f90640c1..4ac4c95224 100644 --- a/plugins/search/src/components/SearchBar/SearchBar.test.tsx +++ b/plugins/search/src/components/SearchBar/SearchBar.test.tsx @@ -149,6 +149,20 @@ describe('SearchBar', () => { ); }); + it('Should not show clear button', async () => { + render( + + + + + , + ); + + expect( + screen.queryByRole('button', { name: 'Clear' }), + ).not.toBeInTheDocument(); + }); + it('Adheres to provided debounceTime', async () => { jest.useFakeTimers(); diff --git a/plugins/search/src/components/SearchBar/SearchBar.tsx b/plugins/search/src/components/SearchBar/SearchBar.tsx index 4ab680d8fa..693cf98adf 100644 --- a/plugins/search/src/components/SearchBar/SearchBar.tsx +++ b/plugins/search/src/components/SearchBar/SearchBar.tsx @@ -31,6 +31,7 @@ type PresenterProps = { className?: string; placeholder?: string; autoFocus?: boolean; + clearButton?: boolean; }; export const SearchBarBase = ({ @@ -40,6 +41,7 @@ export const SearchBarBase = ({ onSubmit, className, placeholder: overridePlaceholder, + clearButton = true, }: PresenterProps) => { const configApi = useApi(configApiRef); @@ -79,11 +81,13 @@ export const SearchBarBase = ({ } endAdornment={ - - - - - + clearButton && ( + + + + + + ) } {...(className && { className })} {...(onSubmit && { onKeyDown })} @@ -96,6 +100,7 @@ type Props = { className?: string; debounceTime?: number; placeholder?: string; + clearButton?: boolean; }; export const SearchBar = ({ @@ -103,6 +108,7 @@ export const SearchBar = ({ className, debounceTime = 0, placeholder, + clearButton = true, }: Props) => { const { term, setTerm } = useSearch(); const [value, setValue] = useState(term); @@ -129,6 +135,7 @@ export const SearchBar = ({ onChange={handleQuery} onClear={handleClear} placeholder={placeholder} + clearButton={clearButton} /> ); }; diff --git a/plugins/search/src/components/SearchContext/SearchContext.tsx b/plugins/search/src/components/SearchContext/SearchContext.tsx index 11d6a2786e..dd9310d782 100644 --- a/plugins/search/src/components/SearchContext/SearchContext.tsx +++ b/plugins/search/src/components/SearchContext/SearchContext.tsx @@ -37,6 +37,8 @@ type SearchContextValue = { setTypes: React.Dispatch>; filters: JsonObject; setFilters: React.Dispatch>; + open?: boolean; + toggleModal: () => void; pageCursor?: string; setPageCursor: React.Dispatch>; fetchNextPage?: React.DispatchWithoutAction; @@ -49,6 +51,7 @@ type SettableSearchContext = Omit< | 'setTerm' | 'setTypes' | 'setFilters' + | 'toggleModal' | 'setPageCursor' | 'fetchNextPage' | 'fetchPreviousPage' @@ -74,6 +77,12 @@ export const SearchContextProvider = ({ const [filters, setFilters] = useState(initialState.filters); const [term, setTerm] = useState(initialState.term); const [types, setTypes] = useState(initialState.types); + const [open, setOpen] = useState(false); + const toggleModal = useCallback( + (): void => setOpen(prevState => !prevState), + [], + ); + const prevTerm = usePrevious(term); const result = useAsync( @@ -109,6 +118,8 @@ export const SearchContextProvider = ({ result, filters, setFilters, + open, + toggleModal, term, setTerm, types, diff --git a/plugins/search/src/components/SearchModal/SearchModal.stories.tsx b/plugins/search/src/components/SearchModal/SearchModal.stories.tsx index 5eefad8e0d..6fa93c6588 100644 --- a/plugins/search/src/components/SearchModal/SearchModal.stories.tsx +++ b/plugins/search/src/components/SearchModal/SearchModal.stories.tsx @@ -14,28 +14,15 @@ * limitations under the License. */ -import React, { useState, ComponentType } from 'react'; +import React, { ComponentType } from 'react'; import { Button } from '@material-ui/core'; import { ApiProvider, ApiRegistry } from '@backstage/core-app-api'; import { wrapInTestApp } from '@backstage/test-utils'; import { SearchModal } from '../index'; +import { useSearch, SearchContextProvider } from '../SearchContext'; import { searchApiRef } from '../../apis'; import { rootRouteRef } from '../../plugin'; -export default { - title: 'Plugins/Search/SearchModal', - component: SearchModal, - decorators: [ - (Story: ComponentType<{}>) => - wrapInTestApp( - <> - - , - { mountedRoutes: { '/search': rootRouteRef } }, - ), - ], -}; - const mockSearchApi = { query: () => Promise.resolve({ @@ -70,16 +57,33 @@ const mockSearchApi = { const apiRegistry = () => ApiRegistry.from([[searchApiRef, mockSearchApi]]); +export default { + title: 'Plugins/Search/SearchModal', + component: SearchModal, + decorators: [ + (Story: ComponentType<{}>) => + wrapInTestApp( + <> + + + + + + , + { mountedRoutes: { '/search': rootRouteRef } }, + ), + ], +}; + export const Default = () => { - const [open, setOpen] = useState(false); - const toggleModal = (): void => setOpen(prevState => !prevState); + const { open, toggleModal } = useSearch(); return ( - + <> - + ); }; diff --git a/plugins/search/src/components/SidebarSearchModal/SidebarSearchModal.tsx b/plugins/search/src/components/SidebarSearchModal/SidebarSearchModal.tsx index 4d4fa1a9fc..ae38526c9d 100644 --- a/plugins/search/src/components/SidebarSearchModal/SidebarSearchModal.tsx +++ b/plugins/search/src/components/SidebarSearchModal/SidebarSearchModal.tsx @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import React, { useState } from 'react'; +import React from 'react'; import SearchIcon from '@material-ui/icons/Search'; -import { SearchModal } from '../SearchModal'; import { SidebarItem } from '@backstage/core-components'; +import { SearchModal } from '../SearchModal'; +import { useSearch } from '../SearchContext'; export const SidebarSearchModal = () => { - const [open, setOpen] = useState(false); - const toggleModal = (): void => setOpen(prevState => !prevState); + const { open, toggleModal } = useSearch(); return ( <> diff --git a/plugins/search/src/index.ts b/plugins/search/src/index.ts index 09cf204017..f5c58450fc 100644 --- a/plugins/search/src/index.ts +++ b/plugins/search/src/index.ts @@ -21,6 +21,7 @@ */ export { searchApiRef } from './apis'; +export type { SearchApi } from './apis'; export { Filters, FiltersButton, diff --git a/plugins/sentry/package.json b/plugins/sentry/package.json index a04043c789..bb99225479 100644 --- a/plugins/sentry/package.json +++ b/plugins/sentry/package.json @@ -33,10 +33,10 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -48,10 +48,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/shortcuts/package.json b/plugins/shortcuts/package.json index f0139d5728..f1f41854ef 100644 --- a/plugins/shortcuts/package.json +++ b/plugins/shortcuts/package.json @@ -21,9 +21,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@backstage/types": "^0.1.1", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", @@ -38,10 +38,10 @@ "zen-observable": "^0.8.15" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/shortcuts/src/ShortcutItem.test.tsx b/plugins/shortcuts/src/ShortcutItem.test.tsx index 0b5c5fc919..e080026f00 100644 --- a/plugins/shortcuts/src/ShortcutItem.test.tsx +++ b/plugins/shortcuts/src/ShortcutItem.test.tsx @@ -37,7 +37,7 @@ describe('ShortcutItem', () => { it('displays the shortcut', async () => { await renderInTestApp( - + {} }}> , ); diff --git a/plugins/shortcuts/src/Shortcuts.test.tsx b/plugins/shortcuts/src/Shortcuts.test.tsx index e0a70d6069..8cee9a6622 100644 --- a/plugins/shortcuts/src/Shortcuts.test.tsx +++ b/plugins/shortcuts/src/Shortcuts.test.tsx @@ -29,7 +29,7 @@ import { SidebarContext } from '@backstage/core-components'; describe('Shortcuts', () => { it('displays an add button', async () => { await renderInTestApp( - + {} }}> { const { namespace, kind, name } = req.params; try { - if (!('checks' in req.body)) { - return res.status(422).send({ - message: 'Failed to get checks from request.', - }); - } const { checks }: { checks: string[] } = req.body; const entityTriplet = stringifyEntityRef({ namespace, kind, name }); const checkResult = await factChecker.runChecks(entityTriplet, checks); diff --git a/plugins/tech-insights-common/CHANGELOG.md b/plugins/tech-insights-common/CHANGELOG.md new file mode 100644 index 0000000000..9e72ce8ace --- /dev/null +++ b/plugins/tech-insights-common/CHANGELOG.md @@ -0,0 +1,7 @@ +# @backstage/plugin-tech-insights-common + +## 0.2.0 + +### Minor Changes + +- b5bd60fddc: Added new property 'result' in CheckResult in @backstage/plugin-tech-insights-common. This property is later used in `@backstage/plugin-tech-insights` package. diff --git a/plugins/tech-insights-common/api-report.md b/plugins/tech-insights-common/api-report.md index ddb38cfa85..8618f6266b 100644 --- a/plugins/tech-insights-common/api-report.md +++ b/plugins/tech-insights-common/api-report.md @@ -4,6 +4,7 @@ ```ts import { DateTime } from 'luxon'; +import { JsonValue } from '@backstage/types'; // @public export interface BooleanCheckResult extends CheckResult { @@ -25,6 +26,7 @@ export interface CheckResponse { export type CheckResult = { facts: FactResponse; check: CheckResponse; + result: JsonValue; }; // @public diff --git a/plugins/tech-insights-common/package.json b/plugins/tech-insights-common/package.json index 26d8922329..7bf668a24e 100644 --- a/plugins/tech-insights-common/package.json +++ b/plugins/tech-insights-common/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-tech-insights-common", - "version": "0.1.0", + "version": "0.2.0", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -31,10 +31,11 @@ }, "dependencies": { "@types/luxon": "^2.0.5", - "luxon": "^2.0.2" + "luxon": "^2.0.2", + "@backstage/types": "^0.1.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" }, "files": [ "dist" diff --git a/plugins/tech-insights-common/src/index.ts b/plugins/tech-insights-common/src/index.ts index 4bfc660748..ecdaa298c1 100644 --- a/plugins/tech-insights-common/src/index.ts +++ b/plugins/tech-insights-common/src/index.ts @@ -15,6 +15,7 @@ */ import { DateTime } from 'luxon'; +import { JsonValue } from '@backstage/types'; /** * @public @@ -112,6 +113,7 @@ export type FactResponse = { export type CheckResult = { facts: FactResponse; check: CheckResponse; + result: JsonValue; }; /** diff --git a/plugins/tech-insights-node/CHANGELOG.md b/plugins/tech-insights-node/CHANGELOG.md new file mode 100644 index 0000000000..83a42bb41e --- /dev/null +++ b/plugins/tech-insights-node/CHANGELOG.md @@ -0,0 +1,9 @@ +# @backstage/plugin-tech-insights-node + +## 0.1.1 + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-tech-insights-common@0.2.0 + - @backstage/backend-common@0.9.12 diff --git a/plugins/tech-insights-node/package.json b/plugins/tech-insights-node/package.json index 3c2ba5da08..5ba94a2ff8 100644 --- a/plugins/tech-insights-node/package.json +++ b/plugins/tech-insights-node/package.json @@ -1,6 +1,6 @@ { "name": "@backstage/plugin-tech-insights-node", - "version": "0.1.0", + "version": "0.1.1", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -30,15 +30,15 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/config": "^0.1.8", - "@backstage/plugin-tech-insights-common": "^0.1.0 ", + "@backstage/plugin-tech-insights-common": "^0.2.0", "@types/luxon": "^2.0.5", "luxon": "^2.0.2", "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0" + "@backstage/cli": "^0.10.0" }, "files": [ "dist" diff --git a/plugins/tech-insights/.eslintrc.js b/plugins/tech-insights/.eslintrc.js new file mode 100644 index 0000000000..13573efa9c --- /dev/null +++ b/plugins/tech-insights/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: [require.resolve('@backstage/cli/config/eslint')], +}; diff --git a/plugins/tech-insights/CHANGELOG.md b/plugins/tech-insights/CHANGELOG.md new file mode 100644 index 0000000000..d0c5e4fcdc --- /dev/null +++ b/plugins/tech-insights/CHANGELOG.md @@ -0,0 +1,15 @@ +# @backstage/plugin-tech-insights + +## 0.1.0 + +### Minor Changes + +- b5bd60fddc: New package containing UI components for the Tech Insights plugin. + +### Patch Changes + +- Updated dependencies + - @backstage/plugin-tech-insights-common@0.2.0 + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 diff --git a/plugins/tech-insights/README.md b/plugins/tech-insights/README.md new file mode 100644 index 0000000000..b61cea48ec --- /dev/null +++ b/plugins/tech-insights/README.md @@ -0,0 +1,47 @@ +# Tech Insights + +This plugin provides the UI for the `@backstage/tech-insights-backend` plugin, in order to display results of the checks running following the rules and the logic defined in the `@backstage/tech-insights-backend` plugin itself. + +Main areas covered by this plugin currently are: + +- Providing an overview for default boolean checks in a form of Scorecards. + +- Providing an option to render different custom components based on type of the checks running in the backend. + +## Installation + +### Install the plugin + +```bash +# From your Backstage root directory +cd packages/app +yarn add @backstage/plugin-tech-insights +``` + +### Add boolean checks overview (Scorecards) page to the EntityPage: + +```tsx +// packages/app/src/components/catalog/EntityPage.tsx + +import { EntityTechInsightsScorecardContent } from '@backstage/plugin-tech-insights'; + +const serviceEntityPage = ( + + + {overviewContent} + + + {cicdContent} + + ... + + + + ... + +); +``` + +## Links + +- [The Backstage homepage](https://backstage.io) diff --git a/plugins/tech-insights/api-report.md b/plugins/tech-insights/api-report.md new file mode 100644 index 0000000000..e7f30a2b30 --- /dev/null +++ b/plugins/tech-insights/api-report.md @@ -0,0 +1,23 @@ +## API Report File for "@backstage/plugin-tech-insights" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts +/// + +import { BackstagePlugin } from '@backstage/core-plugin-api'; +import { RouteRef } from '@backstage/core-plugin-api'; + +// @public (undocumented) +export const EntityTechInsightsScorecardContent: () => JSX.Element; + +// @public (undocumented) +export const techInsightsPlugin: BackstagePlugin< + { + root: RouteRef; + }, + {} +>; + +// (No @packageDocumentation comment for this package) +``` diff --git a/plugins/tech-insights/dev/index.tsx b/plugins/tech-insights/dev/index.tsx new file mode 100644 index 0000000000..17b1fca00e --- /dev/null +++ b/plugins/tech-insights/dev/index.tsx @@ -0,0 +1,30 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { createDevApp } from '@backstage/dev-utils'; +import { + techInsightsPlugin, + EntityTechInsightsScorecardContent, +} from '../src/plugin'; + +createDevApp() + .registerPlugin(techInsightsPlugin) + .addPage({ + element: , + title: 'Root Page', + path: '/tech-insight-scorecard', + }) + .render(); diff --git a/plugins/tech-insights/package.json b/plugins/tech-insights/package.json new file mode 100644 index 0000000000..a55a0ce904 --- /dev/null +++ b/plugins/tech-insights/package.json @@ -0,0 +1,55 @@ +{ + "name": "@backstage/plugin-tech-insights", + "version": "0.1.0", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + "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-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", + "@material-ui/core": "^4.12.2", + "@material-ui/icons": "^4.9.1", + "@material-ui/lab": "4.0.0-alpha.57", + "react": "^16.13.1", + "react-dom": "^16.13.1", + "react-use": "^17.2.4", + "react-router-dom": "6.0.0-beta.0", + "@backstage/plugin-catalog-react": "^0.6.4", + "@backstage/plugin-tech-insights-common": "^0.2.0", + "@backstage/catalog-model": "^0.9.7", + "@backstage/errors": "^0.1.4", + "@backstage/types": "^0.1.1" + }, + "devDependencies": { + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", + "@backstage/dev-utils": "^0.2.13", + "@backstage/test-utils": "^0.1.23", + "@testing-library/jest-dom": "^5.10.1", + "@testing-library/react": "^11.2.5", + "@testing-library/user-event": "^13.1.8", + "@types/jest": "^26.0.7", + "@types/node": "^14.14.32", + "msw": "^0.35.0", + "cross-fetch": "^3.0.6" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/tech-insights/src/api/TechInsightsApi.ts b/plugins/tech-insights/src/api/TechInsightsApi.ts new file mode 100644 index 0000000000..2c55930f0a --- /dev/null +++ b/plugins/tech-insights/src/api/TechInsightsApi.ts @@ -0,0 +1,35 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 } from '@backstage/core-plugin-api'; +import { CheckResult } from '@backstage/plugin-tech-insights-common'; +import { Check } from './types'; +import { CheckResultRenderer } from '../components/CheckResultRenderer'; +import { EntityName } from '@backstage/catalog-model'; + +export const techInsightsApiRef = createApiRef({ + id: 'plugin.techinsights.service', + description: 'Used by the tech insights plugin to make requests', +}); + +export interface TechInsightsApi { + getScorecardsDefinition: ( + type: string, + value: CheckResult[], + ) => CheckResultRenderer | undefined; + getAllChecks(): Promise; + runChecks(entityParams: EntityName, checks?: Check[]): Promise; +} diff --git a/plugins/tech-insights/src/api/TechInsightsClient.ts b/plugins/tech-insights/src/api/TechInsightsClient.ts new file mode 100644 index 0000000000..25002e30a1 --- /dev/null +++ b/plugins/tech-insights/src/api/TechInsightsClient.ts @@ -0,0 +1,82 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { TechInsightsApi } from './TechInsightsApi'; +import { CheckResult } from '@backstage/plugin-tech-insights-common'; +import { Check } from './types'; +import { DiscoveryApi } from '@backstage/core-plugin-api'; +import { ResponseError } from '@backstage/errors'; +import { EntityName } from '@backstage/catalog-model'; + +import { + CheckResultRenderer, + defaultCheckResultRenderers, +} from '../components/CheckResultRenderer'; + +export type Options = { + discoveryApi: DiscoveryApi; +}; + +export class TechInsightsClient implements TechInsightsApi { + private readonly discoveryApi: DiscoveryApi; + + constructor(options: Options) { + this.discoveryApi = options.discoveryApi; + } + + getScorecardsDefinition( + type: string, + value: CheckResult[], + ): CheckResultRenderer | undefined { + const resultRenderers = defaultCheckResultRenderers(value); + return resultRenderers.find(d => d.type === type); + } + + async getAllChecks(): Promise { + const url = await this.discoveryApi.getBaseUrl('tech-insights'); + const response = await fetch(`${url}/checks`); + if (!response.ok) { + throw await ResponseError.fromResponse(response); + } + return await response.json(); + } + + async runChecks( + entityParams: EntityName, + checks: Check[], + ): Promise { + const url = await this.discoveryApi.getBaseUrl('tech-insights'); + const { namespace, kind, name } = entityParams; + const allChecks = checks ? checks : await this.getAllChecks(); + const checkIds = allChecks.map((check: Check) => check.id); + const response = await fetch( + `${url}/checks/run/${encodeURIComponent(namespace)}/${encodeURIComponent( + kind, + )}/${encodeURIComponent(name)}`, + { + method: 'POST', + body: JSON.stringify({ checks: checkIds }), + headers: { + 'Content-Type': 'application/json', + }, + }, + ); + if (!response.ok) { + throw await ResponseError.fromResponse(response); + } + return await response.json(); + } +} diff --git a/plugins/tech-insights/src/api/index.ts b/plugins/tech-insights/src/api/index.ts new file mode 100644 index 0000000000..bcd2575a52 --- /dev/null +++ b/plugins/tech-insights/src/api/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 './TechInsightsApi'; +export * from './TechInsightsClient'; diff --git a/plugins/tech-insights/src/api/types.ts b/plugins/tech-insights/src/api/types.ts new file mode 100644 index 0000000000..20071ba0c9 --- /dev/null +++ b/plugins/tech-insights/src/api/types.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 Check = { + id: string; + type: string; + name: string; + description: string; + factIds: string[]; +}; diff --git a/plugins/tech-insights/src/components/BooleanCheck/BooleanCheck.tsx b/plugins/tech-insights/src/components/BooleanCheck/BooleanCheck.tsx new file mode 100644 index 0000000000..e38e0aa7b3 --- /dev/null +++ b/plugins/tech-insights/src/components/BooleanCheck/BooleanCheck.tsx @@ -0,0 +1,60 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { makeStyles, List, ListItem, ListItemText } from '@material-ui/core'; +import CheckCircleOutline from '@material-ui/icons/CheckCircleOutline'; +import ErrorOutlineIcon from '@material-ui/icons/ErrorOutline'; +import { CheckResult } from '@backstage/plugin-tech-insights-common'; +import { BackstageTheme } from '@backstage/theme'; + +const useStyles = makeStyles((theme: BackstageTheme) => ({ + listItemText: { + paddingRight: theme.spacing(0.5), + flex: '0 1 auto', + }, + icon: { + marginLeft: 'auto', + }, +})); + +type Prop = { + checkResult: CheckResult[]; +}; + +export const BooleanCheck = ({ checkResult }: Prop) => { + const classes = useStyles(); + + return ( + + {checkResult.map((check, index) => ( + + + {check.result ? ( + + ) : ( + + )} + + ))} + + ); +}; diff --git a/plugins/tech-insights/src/components/BooleanCheck/index.ts b/plugins/tech-insights/src/components/BooleanCheck/index.ts new file mode 100644 index 0000000000..729ab4d62e --- /dev/null +++ b/plugins/tech-insights/src/components/BooleanCheck/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { BooleanCheck } from './BooleanCheck'; diff --git a/plugins/tech-insights/src/components/CheckResultRenderer.tsx b/plugins/tech-insights/src/components/CheckResultRenderer.tsx new file mode 100644 index 0000000000..60e0fad9c5 --- /dev/null +++ b/plugins/tech-insights/src/components/CheckResultRenderer.tsx @@ -0,0 +1,40 @@ +/* + * Copyright 2020 The Backstage Authors + * + * 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 { CheckResult } from '@backstage/plugin-tech-insights-common'; +import React from 'react'; +import { BooleanCheck } from './BooleanCheck'; + +export type CheckResultRenderer = { + type: string; + title: string; + description: string; + component: React.ReactElement; +}; + +export function defaultCheckResultRenderers( + value: CheckResult[], +): CheckResultRenderer[] { + return [ + { + type: 'json-rules-engine', + title: 'Boolean scorecard', + description: + 'This card represents an overview of default boolean Backstage checks:', + component: , + }, + ]; +} diff --git a/plugins/tech-insights/src/components/ScorecardsOverview/ChecksOverview.tsx b/plugins/tech-insights/src/components/ScorecardsOverview/ChecksOverview.tsx new file mode 100644 index 0000000000..10025d1ba6 --- /dev/null +++ b/plugins/tech-insights/src/components/ScorecardsOverview/ChecksOverview.tsx @@ -0,0 +1,68 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { makeStyles, Grid, Typography } from '@material-ui/core'; +import { useApi } from '@backstage/core-plugin-api'; +import { Content, Page, InfoCard } from '@backstage/core-components'; +import { CheckResult } from '@backstage/plugin-tech-insights-common'; +import { techInsightsApiRef } from '../../api/TechInsightsApi'; +import { BackstageTheme } from '@backstage/theme'; + +const useStyles = makeStyles((theme: BackstageTheme) => ({ + contentScorecards: { + paddingLeft: 0, + paddingRight: 0, + }, + subheader: { + fontWeight: 'bold', + paddingLeft: theme.spacing(0.5), + }, +})); + +type Checks = { + checks: CheckResult[]; +}; + +export const ChecksOverview = ({ checks }: Checks) => { + const classes = useStyles(); + const api = useApi(techInsightsApiRef); + const checkRenderType = api.getScorecardsDefinition( + checks[0].check.type, + checks, + ); + + if (checkRenderType) { + return ( + + + + + + {checkRenderType.description} + + + {checkRenderType.component} + + + + + + ); + } + + return <>; +}; diff --git a/plugins/tech-insights/src/components/ScorecardsOverview/ScorecardsOverview.tsx b/plugins/tech-insights/src/components/ScorecardsOverview/ScorecardsOverview.tsx new file mode 100644 index 0000000000..92a57bd643 --- /dev/null +++ b/plugins/tech-insights/src/components/ScorecardsOverview/ScorecardsOverview.tsx @@ -0,0 +1,41 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { useParams } from 'react-router-dom'; +import { useAsync } from 'react-use'; +import { Progress } from '@backstage/core-components'; +import { useApi } from '@backstage/core-plugin-api'; +import { ChecksOverview } from './ChecksOverview'; +import Alert from '@material-ui/lab/Alert'; +import { techInsightsApiRef } from '../../api/TechInsightsApi'; + +export const ScorecardsOverview = () => { + const api = useApi(techInsightsApiRef); + const { namespace, kind, name } = useParams(); + + const { value, loading, error } = useAsync( + async () => await api.runChecks({ namespace, kind, name }), + ); + + if (loading) { + return ; + } else if (error) { + return {error.message}; + } + + return ; +}; diff --git a/plugins/tech-insights/src/components/ScorecardsOverview/index.ts b/plugins/tech-insights/src/components/ScorecardsOverview/index.ts new file mode 100644 index 0000000000..64198790d9 --- /dev/null +++ b/plugins/tech-insights/src/components/ScorecardsOverview/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { ScorecardsOverview } from './ScorecardsOverview'; diff --git a/plugins/tech-insights/src/index.ts b/plugins/tech-insights/src/index.ts new file mode 100644 index 0000000000..273c11fd71 --- /dev/null +++ b/plugins/tech-insights/src/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { + techInsightsPlugin, + EntityTechInsightsScorecardContent, +} from './plugin'; diff --git a/plugins/tech-insights/src/plugin.test.ts b/plugins/tech-insights/src/plugin.test.ts new file mode 100644 index 0000000000..a4a9e6f308 --- /dev/null +++ b/plugins/tech-insights/src/plugin.test.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { techInsightsPlugin } from './plugin'; + +describe('tech insights', () => { + it('should export plugin', () => { + expect(techInsightsPlugin).toBeDefined(); + }); +}); diff --git a/plugins/tech-insights/src/plugin.ts b/plugins/tech-insights/src/plugin.ts new file mode 100644 index 0000000000..f229b654f3 --- /dev/null +++ b/plugins/tech-insights/src/plugin.ts @@ -0,0 +1,53 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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, + createRoutableExtension, + createApiFactory, + discoveryApiRef, +} from '@backstage/core-plugin-api'; +import { rootRouteRef } from './routes'; +import { techInsightsApiRef } from './api/TechInsightsApi'; +import { TechInsightsClient } from './api/TechInsightsClient'; + +/** + * @public + */ +export const techInsightsPlugin = createPlugin({ + id: 'tech-insights', + apis: [ + createApiFactory({ + api: techInsightsApiRef, + deps: { discoveryApi: discoveryApiRef }, + factory: ({ discoveryApi }) => new TechInsightsClient({ discoveryApi }), + }), + ], + routes: { + root: rootRouteRef, + }, +}); + +/** + * @public + */ +export const EntityTechInsightsScorecardContent = techInsightsPlugin.provide( + createRoutableExtension({ + name: 'EntityTechInsightsScorecardContent', + component: () => + import('./components/ScorecardsOverview').then(m => m.ScorecardsOverview), + mountPoint: rootRouteRef, + }), +); diff --git a/plugins/tech-insights/src/routes.ts b/plugins/tech-insights/src/routes.ts new file mode 100644 index 0000000000..b1b7900074 --- /dev/null +++ b/plugins/tech-insights/src/routes.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { createRouteRef } from '@backstage/core-plugin-api'; + +export const rootRouteRef = createRouteRef({ + id: 'tech-insights', +}); diff --git a/plugins/tech-insights/src/setupTests.ts b/plugins/tech-insights/src/setupTests.ts new file mode 100644 index 0000000000..fc6dbd98f8 --- /dev/null +++ b/plugins/tech-insights/src/setupTests.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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'; +import 'cross-fetch/polyfill'; diff --git a/plugins/tech-radar/package.json b/plugins/tech-radar/package.json index 99fce10345..d377318e4b 100644 --- a/plugins/tech-radar/package.json +++ b/plugins/tech-radar/package.json @@ -31,9 +31,9 @@ "start": "backstage-cli plugin:serve" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -45,10 +45,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/techdocs-backend/CHANGELOG.md b/plugins/techdocs-backend/CHANGELOG.md index ad7a8af85e..099049a896 100644 --- a/plugins/techdocs-backend/CHANGELOG.md +++ b/plugins/techdocs-backend/CHANGELOG.md @@ -1,5 +1,64 @@ # @backstage/plugin-techdocs-backend +## 0.11.0 + +### Minor Changes + +- 905dd952ac: **BREAKING** `DefaultTechDocsCollator` has a new required option `tokenManager`. See the create-app changelog for how to create a `tokenManager` and add it to the `PluginEnvironment`. It can then be passed to the collator in `createPlugin`: + + ```diff + // packages/backend/src/plugins/search.ts + + ... + export default async function createPlugin({ + ... + + tokenManager, + }: PluginEnvironment) { + ... + + indexBuilder.addCollator({ + defaultRefreshIntervalSeconds: 600, + collator: DefaultTechDocsCollator.fromConfig(config, { + discovery, + logger, + + tokenManager, + }), + }); + + ... + } + ``` + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/backend-common@0.9.12 + +## 0.10.9 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/backend-common@0.9.11 + - @backstage/techdocs-common@0.10.8 + ## 0.10.8 ### Patch Changes diff --git a/plugins/techdocs-backend/api-report.md b/plugins/techdocs-backend/api-report.md index a6094c2bdd..9736555687 100644 --- a/plugins/techdocs-backend/api-report.md +++ b/plugins/techdocs-backend/api-report.md @@ -10,10 +10,12 @@ import express from 'express'; import { GeneratorBuilder } from '@backstage/techdocs-common'; import { Knex } from 'knex'; import { Logger as Logger_2 } from 'winston'; +import { PluginCacheManager } from '@backstage/backend-common'; import { PluginEndpointDiscovery } from '@backstage/backend-common'; import { PreparerBuilder } from '@backstage/techdocs-common'; import { PublisherBase } from '@backstage/techdocs-common'; import { TechDocsDocument } from '@backstage/techdocs-common'; +import { TokenManager } from '@backstage/backend-common'; // Warning: (ae-forgotten-export) The symbol "RouterOptions" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "createRouter" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -31,6 +33,7 @@ export class DefaultTechDocsCollator implements DocumentCollator { locationTemplate, logger, catalogClient, + tokenManager, parallelismLimit, legacyPathCasing, }: TechDocsCollatorOptions); @@ -60,6 +63,7 @@ export class DefaultTechDocsCollator implements DocumentCollator { export type TechDocsCollatorOptions = { discovery: PluginEndpointDiscovery; logger: Logger_2; + tokenManager: TokenManager; locationTemplate?: string; catalogClient?: CatalogApi; parallelismLimit?: number; diff --git a/plugins/techdocs-backend/config.d.ts b/plugins/techdocs-backend/config.d.ts index 9e563137bd..8d531e0536 100644 --- a/plugins/techdocs-backend/config.d.ts +++ b/plugins/techdocs-backend/config.d.ts @@ -226,6 +226,32 @@ export interface Config { }; }; + /** + * @example http://localhost:7007/api/techdocs + * Techdocs cache information + */ + cache?: { + /** + * The cache time-to-live for TechDocs sites (in milliseconds). Set this + * to a non-zero value to cache TechDocs sites and assets as they are + * read from storage. + * + * Note: you must also configure `backend.cache` appropriately as well, + * and to pass a PluginCacheManager instance to TechDocs Backend's + * createRouter method in your backend. + */ + ttl: number; + + /** + * The time (in milliseconds) that the TechDocs backend will wait for + * a cache service to respond before continuing on as though the cached + * object was not found (e.g. when the cache sercice is unavailable). + * + * Defaults to 1000 milliseconds. + */ + readTimeout?: number; + }; + /** * @example http://localhost:7007/api/techdocs * @visibility frontend diff --git a/plugins/techdocs-backend/package.json b/plugins/techdocs-backend/package.json index 332884c694..b2e7fee261 100644 --- a/plugins/techdocs-backend/package.json +++ b/plugins/techdocs-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-techdocs-backend", "description": "The Backstage backend plugin that renders technical documentation for your components", - "version": "0.10.8", + "version": "0.11.0", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -31,14 +31,14 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", + "@backstage/errors": "^0.1.5", + "@backstage/integration": "^0.6.10", "@backstage/search-common": "^0.2.1", - "@backstage/techdocs-common": "^0.10.7", + "@backstage/techdocs-common": "^0.10.8", "@types/express": "^4.17.6", "cross-fetch": "^3.0.6", "dockerode": "^3.3.1", @@ -47,12 +47,13 @@ "fs-extra": "9.1.0", "knex": "^0.95.1", "lodash": "^4.17.21", + "node-fetch": "^2.6.1", "p-limit": "^3.1.0", "winston": "^3.2.1" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/test-utils": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/test-utils": "^0.1.23", "@types/dockerode": "^3.3.0", "msw": "^0.35.0", "supertest": "^6.1.3" diff --git a/plugins/techdocs-backend/src/DocsBuilder/builder.ts b/plugins/techdocs-backend/src/DocsBuilder/builder.ts index 821b3478a0..66eb52c1aa 100644 --- a/plugins/techdocs-backend/src/DocsBuilder/builder.ts +++ b/plugins/techdocs-backend/src/DocsBuilder/builder.ts @@ -36,6 +36,7 @@ import path from 'path'; import { Writable } from 'stream'; import { Logger } from 'winston'; import { BuildMetadataStorage } from './BuildMetadataStorage'; +import { TechDocsCache } from '../cache'; type DocsBuilderArguments = { preparers: PreparerBuilder; @@ -46,6 +47,7 @@ type DocsBuilderArguments = { config: Config; scmIntegrations: ScmIntegrationRegistry; logStream?: Writable; + cache?: TechDocsCache; }; export class DocsBuilder { @@ -57,6 +59,7 @@ export class DocsBuilder { private config: Config; private scmIntegrations: ScmIntegrationRegistry; private logStream: Writable | undefined; + private cache?: TechDocsCache; constructor({ preparers, @@ -67,6 +70,7 @@ export class DocsBuilder { config, scmIntegrations, logStream, + cache, }: DocsBuilderArguments) { this.preparer = preparers.get(entity); this.generator = generators.get(entity); @@ -76,6 +80,7 @@ export class DocsBuilder { this.config = config; this.scmIntegrations = scmIntegrations; this.logStream = logStream; + this.cache = cache; } /** @@ -210,11 +215,19 @@ export class DocsBuilder { )}`, ); - await this.publisher.publish({ + const published = await this.publisher.publish({ entity: this.entity, directory: outputDir, }); + // Invalidate the cache for any published objects. + if (this.cache && published && published?.objects?.length) { + this.logger.debug( + `Invalidating ${published.objects.length} cache objects`, + ); + await this.cache.invalidateMultiple(published.objects); + } + try { // Not a blocker hence no need to await this. fs.remove(outputDir); diff --git a/plugins/techdocs-backend/src/cache/TechDocsCache.test.ts b/plugins/techdocs-backend/src/cache/TechDocsCache.test.ts new file mode 100644 index 0000000000..17613e1b58 --- /dev/null +++ b/plugins/techdocs-backend/src/cache/TechDocsCache.test.ts @@ -0,0 +1,168 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { CacheClient, getVoidLogger } from '@backstage/backend-common'; +import { ConfigReader } from '@backstage/config'; +import { CacheInvalidationError, TechDocsCache } from './TechDocsCache'; + +const cached = (str: string): string => { + return Buffer.from(str).toString('base64'); +}; + +describe('TechDocsCache', () => { + let CacheUnderTest: TechDocsCache; + let MockClient: jest.Mocked; + + beforeEach(() => { + MockClient = { + get: jest.fn(), + set: jest.fn(), + delete: jest.fn(), + }; + CacheUnderTest = TechDocsCache.fromConfig(new ConfigReader({}), { + cache: MockClient, + logger: getVoidLogger(), + }); + }); + + describe('get', () => { + it('returns undefined if no response', async () => { + const expectedPath = 'some/index.html'; + MockClient.get.mockResolvedValueOnce(undefined); + + const actual = await CacheUnderTest.get(expectedPath); + expect(MockClient.get).toHaveBeenCalledWith(expectedPath); + expect(actual).toBe(undefined); + }); + + it('returns undefined if cache get throws', async () => { + const expectedPath = 'some/index.html'; + MockClient.get.mockRejectedValueOnce(new Error()); + + const actual = await CacheUnderTest.get(expectedPath); + expect(actual).toBe(undefined); + }); + + it('returns undefined if no response after 1s by default', async () => { + const expectedPath = 'some/index.html'; + MockClient.get.mockImplementationOnce(() => { + return new Promise(resolve => { + setTimeout(() => resolve(cached('value')), 1500); + }); + }); + const actual = await CacheUnderTest.get(expectedPath); + expect(actual).toBe(undefined); + }); + + it('returns undefined if no response after configured readTimeout', async () => { + const expectedPath = 'some/index.html'; + MockClient.get.mockImplementationOnce(() => { + return new Promise(resolve => { + setTimeout(() => resolve(cached('value')), 20); + }); + }); + + CacheUnderTest = TechDocsCache.fromConfig( + new ConfigReader({ + techdocs: { cache: { readTimeout: 10 } }, + }), + { + cache: MockClient, + logger: getVoidLogger(), + }, + ); + + const actual = await CacheUnderTest.get(expectedPath); + expect(actual).toBe(undefined); + }); + + it('returns data if cache get returns it', async () => { + const expectedPath = 'some/index.html'; + MockClient.get.mockResolvedValueOnce(cached('expected value')); + + const actual = await CacheUnderTest.get(expectedPath); + expect(actual?.toString()).toBe('expected value'); + }); + }); + + describe('set', () => { + it('sets a base64-encoded string', async () => { + const expectedPath = 'some/index.html'; + MockClient.set.mockResolvedValueOnce(undefined); + + await CacheUnderTest.set(expectedPath, Buffer.from('some data')); + expect(MockClient.set).toHaveBeenCalledWith( + expectedPath, + cached('some data'), + ); + }); + + it('does not throw if client throws', () => { + MockClient.set.mockRejectedValueOnce(new Error()); + expect(() => CacheUnderTest.set('i.html', Buffer.from(''))).not.toThrow(); + }); + }); + + describe('invalidate', () => { + it('calls delete on client', async () => { + const expectedPath = 'some/index.html'; + MockClient.delete.mockResolvedValueOnce(undefined); + + await CacheUnderTest.invalidate(expectedPath); + expect(MockClient.delete).toHaveBeenCalledWith(expectedPath); + }); + }); + + describe('invalidateMultiple', () => { + it('calls delete once per given path', async () => { + const expectedPaths = ['one/index.html', 'two/index.html']; + MockClient.delete.mockResolvedValue(undefined); + + await CacheUnderTest.invalidateMultiple(expectedPaths); + expect(MockClient.delete).toHaveBeenNthCalledWith(1, expectedPaths[0]); + expect(MockClient.delete).toHaveBeenNthCalledWith(2, expectedPaths[1]); + }); + + it('returns an array of as many paths provided', async () => { + const expectedPaths = ['one/index.html', 'two/index.html']; + MockClient.delete.mockResolvedValue(undefined); + + const actual = await CacheUnderTest.invalidateMultiple(expectedPaths); + expect(actual.length).toBe(2); + }); + + it('calls delete on all paths even if the first rejects', async () => { + const expectedPaths = ['one/index.html', 'two/index.html']; + MockClient.delete.mockRejectedValueOnce(new Error()); + MockClient.delete.mockResolvedValueOnce(undefined); + + await expect( + CacheUnderTest.invalidateMultiple(expectedPaths), + ).rejects.toThrowError(CacheInvalidationError); + expect(MockClient.delete).toHaveBeenCalledTimes(2); + }); + + it('rejects with invalidations error response', async () => { + const expectedPaths = ['one/index.html', 'two/index.html']; + MockClient.delete.mockResolvedValueOnce(undefined); + MockClient.delete.mockRejectedValueOnce(new Error()); + + await expect( + CacheUnderTest.invalidateMultiple.bind(CacheUnderTest, expectedPaths), + ).rejects.toThrow(CacheInvalidationError); + }); + }); +}); diff --git a/plugins/techdocs-backend/src/cache/TechDocsCache.ts b/plugins/techdocs-backend/src/cache/TechDocsCache.ts new file mode 100644 index 0000000000..807d6ca87b --- /dev/null +++ b/plugins/techdocs-backend/src/cache/TechDocsCache.ts @@ -0,0 +1,105 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { CacheClient } from '@backstage/backend-common'; +import { assertError, CustomErrorBase } from '@backstage/errors'; +import { Config } from '@backstage/config'; +import { Logger } from 'winston'; + +export class CacheInvalidationError extends CustomErrorBase {} + +export class TechDocsCache { + protected readonly cache: CacheClient; + protected readonly logger: Logger; + protected readonly readTimeout: number; + + private constructor({ + cache, + logger, + readTimeout, + }: { + cache: CacheClient; + logger: Logger; + readTimeout: number; + }) { + this.cache = cache; + this.logger = logger; + this.readTimeout = readTimeout; + } + + static fromConfig( + config: Config, + { cache, logger }: { cache: CacheClient; logger: Logger }, + ) { + const timeout = config.getOptionalNumber('techdocs.cache.readTimeout'); + const readTimeout = timeout === undefined ? 1000 : timeout; + return new TechDocsCache({ cache, logger, readTimeout }); + } + + async get(path: string): Promise { + try { + // Promise.race ensures we don't hang the client for long if the cache is + // temporarily unreachable. + const response = (await Promise.race([ + this.cache.get(path), + new Promise(cancelAfter => setTimeout(cancelAfter, this.readTimeout)), + ])) as string | undefined; + + if (response !== undefined) { + this.logger.debug(`Cache hit: ${path}`); + return Buffer.from(response, 'base64'); + } + + this.logger.debug(`Cache miss: ${path}`); + return response; + } catch (e) { + assertError(e); + this.logger.warn(`Error getting cache entry ${path}: ${e.message}`); + this.logger.debug(e.stack); + return undefined; + } + } + + async set(path: string, data: Buffer): Promise { + this.logger.debug(`Writing cache entry for ${path}`); + this.cache + .set(path, data.toString('base64')) + .catch(e => this.logger.error('write error', e)); + } + + async invalidate(path: string): Promise { + return this.cache.delete(path); + } + + async invalidateMultiple( + paths: string[], + ): Promise[]> { + const settled = await Promise.allSettled( + paths.map(path => this.cache.delete(path)), + ); + const rejected = settled.filter( + s => s.status === 'rejected', + ) as PromiseRejectedResult[]; + + if (rejected.length) { + throw new CacheInvalidationError( + 'TechDocs cache invalidation error', + rejected, + ); + } + + return settled; + } +} diff --git a/plugins/techdocs-backend/src/cache/cacheMiddleware.test.ts b/plugins/techdocs-backend/src/cache/cacheMiddleware.test.ts new file mode 100644 index 0000000000..312674a5bf --- /dev/null +++ b/plugins/techdocs-backend/src/cache/cacheMiddleware.test.ts @@ -0,0 +1,109 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 express from 'express'; +import request from 'supertest'; +import { createCacheMiddleware, TechDocsCache } from '.'; + +/** + * Mocks cached HTTP response. + */ +const getMockHttpResponseFor = (content: string): Buffer => { + return Buffer.concat([ + Buffer.from(`HTTP/1.1 200 OK +Content-Type: text/plain; charset=utf-8 +Accept-Ranges: bytes +Cache-Control: public, max-age=0 +Last-Modified: Sat, 1 Jul 2021 12:00:00 GMT +Date: Sat, 1 Jul 2021 12:00:00 GMT +Connection: close +Content-Length: ${content.length}\n\n`), + Buffer.from(content), + ]); +}; + +/** + * Wait for the socket to close. Works because, above, we set connection: close + */ +const waitForSocketClose = () => new Promise(resolve => setTimeout(resolve, 0)); + +describe('createCacheMiddleware', () => { + let cache: jest.Mocked; + let app: express.Express; + + beforeEach(async () => { + cache = { + get: jest.fn().mockResolvedValue(undefined), + set: jest.fn().mockResolvedValue(undefined), + invalidate: jest.fn().mockResolvedValue(undefined), + invalidateMultiple: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const router = await createCacheMiddleware({ + logger: getVoidLogger(), + cache, + }); + app = express().use(router); + app.use((req, res, next) => { + // By default, send cacheable content. + if (req.path !== '/static/docs/error.png') { + res.send('default-response'); + } else { + next(new Error()); + } + }); + }); + + describe('middleware', () => { + it('does not apply to non-static/docs paths', async () => { + await request(app) + .get('/static/not-docs') + .expect(200, 'default-response'); + + expect(cache.set).not.toHaveBeenCalled(); + }); + + it('responds with cached response', async () => { + cache.get.mockResolvedValueOnce(getMockHttpResponseFor('xyz')); + + await request(app).get('/static/docs/foo.html').expect(200, 'xyz'); + + await waitForSocketClose(); + expect(cache.set).not.toHaveBeenCalled(); + }); + + it('sets cache when content is cacheable', async () => { + const expectedPath = 'default/api/xyz/index.html'; + await request(app) + .get(`/static/docs/${expectedPath}`) + .expect(200, 'default-response'); + + await waitForSocketClose(); + expect(cache.set).toHaveBeenCalled(); + + const [actualPath, actualBuffer] = (cache.set as jest.Mock).mock.calls[0]; + expect(actualPath).toBe(expectedPath); + expect(actualBuffer.toString()).toContain('default-response'); + }); + + it('does not set cache on error', async () => { + await request(app).get('/static/docs/error.png').expect(500); + + await waitForSocketClose(); + expect(cache.set).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/plugins/techdocs-backend/src/cache/cacheMiddleware.ts b/plugins/techdocs-backend/src/cache/cacheMiddleware.ts new file mode 100644 index 0000000000..cb59681304 --- /dev/null +++ b/plugins/techdocs-backend/src/cache/cacheMiddleware.ts @@ -0,0 +1,94 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { Router } from 'express'; +import router from 'express-promise-router'; +import { Logger } from 'winston'; +import { TechDocsCache } from './TechDocsCache'; + +type CacheMiddlewareOptions = { + cache: TechDocsCache; + logger: Logger; +}; + +type ErrorCallback = (err?: Error) => void; + +export const createCacheMiddleware = ({ + cache, +}: CacheMiddlewareOptions): Router => { + const cacheMiddleware = router(); + + // Middleware that, through socket monkey patching, captures responses as + // they're sent over /static/docs/* and caches them. Subsequent requests are + // loaded from cache. Cache key is the object's path (after `/static/docs/`). + cacheMiddleware.use(async (req, res, next) => { + const socket = res.socket; + const isCacheable = req.path.startsWith('/static/docs/'); + + // Continue early if this is non-cacheable, or there's no socket. + if (!isCacheable || !socket) { + next(); + return; + } + + // Make concrete references to these things. + const reqPath = decodeURI(req.path.match(/\/static\/docs\/(.*)$/)![1]); + const realEnd = socket.end.bind(socket); + const realWrite = socket.write.bind(socket); + let writeToCache = true; + const chunks: Buffer[] = []; + + // Monkey-patch the response's socket to keep track of chunks as they are + // written over the wire. + socket.write = ( + data: string | Uint8Array, + encoding?: BufferEncoding | ErrorCallback, + callback?: ErrorCallback, + ) => { + chunks.push(Buffer.from(data)); + if (typeof encoding === 'function') { + return realWrite(data, encoding); + } + return realWrite(data, encoding, callback); + }; + + // When a socket is closed, if there were no errors and the data written + // over the socket should be cached, cache it! + socket.on('close', async hadError => { + const content = Buffer.concat(chunks); + const head = content.toString('utf8', 0, 12); + if (writeToCache && !hadError && head.match(/HTTP\/\d\.\d 200/)) { + await cache.set(reqPath, content); + } + }); + + // Attempt to retrieve data from the cache. + const cached = await cache.get(reqPath); + + // If there is a cache hit, write it out on the socket, ensure we don't re- + // cache the data, and prevent going back to canonical storage by never + // calling next(). + if (cached) { + writeToCache = false; + realEnd(cached); + return; + } + + // No data retrieved from cache: allow retrieval from canonical storage. + next(); + }); + + return cacheMiddleware; +}; diff --git a/plugins/techdocs-backend/src/cache/index.ts b/plugins/techdocs-backend/src/cache/index.ts new file mode 100644 index 0000000000..751d8e8625 --- /dev/null +++ b/plugins/techdocs-backend/src/cache/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 { createCacheMiddleware } from './cacheMiddleware'; +export { TechDocsCache } from './TechDocsCache'; diff --git a/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.test.ts b/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.test.ts index 21be228636..5f0bed55dd 100644 --- a/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.test.ts +++ b/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.test.ts @@ -17,6 +17,7 @@ import { PluginEndpointDiscovery, getVoidLogger, + TokenManager, } from '@backstage/backend-common'; import { Entity } from '@backstage/catalog-model'; import { DefaultTechDocsCollator } from './DefaultTechDocsCollator'; @@ -87,6 +88,7 @@ const expectedEntities: Entity[] = [ describe('DefaultTechDocsCollator with legacyPathCasing configuration', () => { let mockDiscoveryApi: jest.Mocked; + let mockTokenManager: jest.Mocked; let collator: DefaultTechDocsCollator; const worker = setupServer(); @@ -96,6 +98,10 @@ describe('DefaultTechDocsCollator with legacyPathCasing configuration', () => { getBaseUrl: jest.fn().mockResolvedValue('http://test-backend'), getExternalBaseUrl: jest.fn(), }; + mockTokenManager = { + getToken: jest.fn().mockResolvedValue({ token: '' }), + authenticate: jest.fn(), + }; const mockConfig = new ConfigReader({ techdocs: { legacyUseCaseSensitiveTripletPaths: true, @@ -103,6 +109,7 @@ describe('DefaultTechDocsCollator with legacyPathCasing configuration', () => { }); collator = DefaultTechDocsCollator.fromConfig(mockConfig, { discovery: mockDiscoveryApi, + tokenManager: mockTokenManager, logger, legacyPathCasing: true, }); @@ -147,6 +154,7 @@ describe('DefaultTechDocsCollator with legacyPathCasing configuration', () => { describe('DefaultTechDocsCollator', () => { let mockDiscoveryApi: jest.Mocked; + let mockTokenManager: jest.Mocked; let collator: DefaultTechDocsCollator; const worker = setupServer(); @@ -156,8 +164,13 @@ describe('DefaultTechDocsCollator', () => { getBaseUrl: jest.fn().mockResolvedValue('http://test-backend'), getExternalBaseUrl: jest.fn(), }; + mockTokenManager = { + getToken: jest.fn().mockResolvedValue({ token: '' }), + authenticate: jest.fn(), + }; collator = DefaultTechDocsCollator.fromConfig(new ConfigReader({}), { discovery: mockDiscoveryApi, + tokenManager: mockTokenManager, logger, }); @@ -195,6 +208,7 @@ describe('DefaultTechDocsCollator', () => { // Provide an alternate location template. collator = new DefaultTechDocsCollator({ discovery: mockDiscoveryApi, + tokenManager: mockTokenManager, locationTemplate: '/software/:name', logger, }); diff --git a/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts b/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts index 121ef6e46d..283d0264e4 100644 --- a/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts +++ b/plugins/techdocs-backend/src/search/DefaultTechDocsCollator.ts @@ -14,10 +14,13 @@ * limitations under the License. */ -import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { + PluginEndpointDiscovery, + TokenManager, +} from '@backstage/backend-common'; import { Entity, RELATION_OWNED_BY } from '@backstage/catalog-model'; import { DocumentCollator } from '@backstage/search-common'; -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import unescape from 'lodash/unescape'; import { Logger } from 'winston'; import pLimit from 'p-limit'; @@ -34,6 +37,7 @@ interface MkSearchIndexDoc { export type TechDocsCollatorOptions = { discovery: PluginEndpointDiscovery; logger: Logger; + tokenManager: TokenManager; locationTemplate?: string; catalogClient?: CatalogApi; parallelismLimit?: number; @@ -51,6 +55,7 @@ export class DefaultTechDocsCollator implements DocumentCollator { protected locationTemplate: string; private readonly logger: Logger; private readonly catalogClient: CatalogApi; + private readonly tokenManager: TokenManager; private readonly parallelismLimit: number; private readonly legacyPathCasing: boolean; public readonly type: string = 'techdocs'; @@ -63,6 +68,7 @@ export class DefaultTechDocsCollator implements DocumentCollator { locationTemplate, logger, catalogClient, + tokenManager, parallelismLimit = 10, legacyPathCasing = false, }: TechDocsCollatorOptions) { @@ -74,6 +80,7 @@ export class DefaultTechDocsCollator implements DocumentCollator { catalogClient || new CatalogClient({ discoveryApi: discovery }); this.parallelismLimit = parallelismLimit; this.legacyPathCasing = legacyPathCasing; + this.tokenManager = tokenManager; } static fromConfig(config: Config, options: TechDocsCollatorOptions) { @@ -87,19 +94,23 @@ export class DefaultTechDocsCollator implements DocumentCollator { async execute() { const limit = pLimit(this.parallelismLimit); const techDocsBaseUrl = await this.discovery.getBaseUrl('techdocs'); - const entities = await this.catalogClient.getEntities({ - fields: [ - 'kind', - 'namespace', - 'metadata.annotations', - 'metadata.name', - 'metadata.title', - 'metadata.namespace', - 'spec.type', - 'spec.lifecycle', - 'relations', - ], - }); + const { token } = await this.tokenManager.getToken(); + const entities = await this.catalogClient.getEntities( + { + fields: [ + 'kind', + 'namespace', + 'metadata.annotations', + 'metadata.name', + 'metadata.title', + 'metadata.namespace', + 'spec.type', + 'spec.lifecycle', + 'relations', + ], + }, + { token }, + ); const docPromises = entities.items .filter(it => it.metadata?.annotations?.['backstage.io/techdocs-ref']) .map((entity: Entity) => diff --git a/plugins/techdocs-backend/src/service/DocsSynchronizer.test.ts b/plugins/techdocs-backend/src/service/DocsSynchronizer.test.ts index ac60f3da3a..1eb8c8f56f 100644 --- a/plugins/techdocs-backend/src/service/DocsSynchronizer.test.ts +++ b/plugins/techdocs-backend/src/service/DocsSynchronizer.test.ts @@ -25,11 +25,25 @@ import { PreparerBuilder, PublisherBase, } from '@backstage/techdocs-common'; +import { TechDocsCache } from '../cache'; import { DocsBuilder, shouldCheckForUpdate } from '../DocsBuilder'; import { DocsSynchronizer, DocsSynchronizerSyncOpts } from './DocsSynchronizer'; jest.mock('../DocsBuilder'); +jest.mock('cross-fetch', () => ({ + __esModule: true, + default: async () => { + return { + json: async () => { + return { + build_timestamp: 123, + }; + }, + }; + }, +})); + const MockedDocsBuilder = DocsBuilder as jest.MockedClass; describe('DocsSynchronizer', () => { @@ -52,6 +66,12 @@ describe('DocsSynchronizer', () => { getBaseUrl: jest.fn(), getExternalBaseUrl: jest.fn(), }; + const cache: jest.Mocked = { + get: jest.fn(), + set: jest.fn(), + invalidate: jest.fn(), + invalidateMultiple: jest.fn(), + } as unknown as jest.Mocked; let docsSynchronizer: DocsSynchronizer; const mockResponseHandler: jest.Mocked = { @@ -71,6 +91,7 @@ describe('DocsSynchronizer', () => { config: new ConfigReader({}), logger: getVoidLogger(), scmIntegrations: ScmIntegrations.fromConfig(new ConfigReader({})), + cache, }); }); @@ -193,4 +214,112 @@ describe('DocsSynchronizer', () => { expect(mockResponseHandler.error).toBeCalledWith(error); }); }); + + describe('doCacheSync', () => { + const entity = { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Component', + metadata: { + uid: '0', + name: 'test', + namespace: 'default', + }, + }; + + it('should not check metadata too often', async () => { + (shouldCheckForUpdate as jest.Mock).mockReturnValue(false); + + await docsSynchronizer.doCacheSync({ + responseHandler: mockResponseHandler, + discovery, + token: undefined, + entity, + }); + + expect(mockResponseHandler.finish).toBeCalledWith({ updated: false }); + expect(shouldCheckForUpdate).toBeCalledTimes(1); + }); + + it('should do nothing if source/cached metadata matches', async () => { + (shouldCheckForUpdate as jest.Mock).mockReturnValue(true); + (publisher.fetchTechDocsMetadata as jest.Mock).mockResolvedValue({ + build_timestamp: 123, + }); + + await docsSynchronizer.doCacheSync({ + responseHandler: mockResponseHandler, + discovery, + token: undefined, + entity, + }); + + expect(mockResponseHandler.finish).toBeCalledWith({ updated: false }); + }); + + it('should invalidate expected files when source/cached metadata differ', async () => { + (shouldCheckForUpdate as jest.Mock).mockReturnValue(true); + (publisher.fetchTechDocsMetadata as jest.Mock).mockResolvedValue({ + build_timestamp: 456, + files: ['index.html'], + }); + + await docsSynchronizer.doCacheSync({ + responseHandler: mockResponseHandler, + discovery, + token: undefined, + entity, + }); + + expect(mockResponseHandler.finish).toBeCalledWith({ updated: true }); + expect(cache.invalidateMultiple).toHaveBeenCalledWith([ + 'default/component/test/index.html', + ]); + }); + + it('should invalidate expected files when source/cached metadata differ with legacy casing', async () => { + (shouldCheckForUpdate as jest.Mock).mockReturnValue(true); + (publisher.fetchTechDocsMetadata as jest.Mock).mockResolvedValue({ + build_timestamp: 456, + files: ['index.html'], + }); + + const docsSynchronizerWithLegacy = new DocsSynchronizer({ + publisher, + config: new ConfigReader({ + techdocs: { legacyUseCaseSensitiveTripletPaths: true }, + }), + logger: getVoidLogger(), + scmIntegrations: ScmIntegrations.fromConfig(new ConfigReader({})), + cache, + }); + + await docsSynchronizerWithLegacy.doCacheSync({ + responseHandler: mockResponseHandler, + discovery, + token: undefined, + entity, + }); + + expect(mockResponseHandler.finish).toBeCalledWith({ updated: true }); + expect(cache.invalidateMultiple).toHaveBeenCalledWith([ + 'default/Component/test/index.html', + ]); + }); + + it('should gracefully handle errors', async () => { + (shouldCheckForUpdate as jest.Mock).mockReturnValue(true); + (publisher.fetchTechDocsMetadata as jest.Mock).mockRejectedValue( + new Error(), + ); + + await docsSynchronizer.doCacheSync({ + responseHandler: mockResponseHandler, + discovery, + token: undefined, + entity, + }); + + expect(mockResponseHandler.finish).toBeCalledWith({ updated: false }); + }); + }); }); diff --git a/plugins/techdocs-backend/src/service/DocsSynchronizer.ts b/plugins/techdocs-backend/src/service/DocsSynchronizer.ts index 6f977dcb47..4d407ab54a 100644 --- a/plugins/techdocs-backend/src/service/DocsSynchronizer.ts +++ b/plugins/techdocs-backend/src/service/DocsSynchronizer.ts @@ -14,7 +14,8 @@ * limitations under the License. */ -import { Entity } from '@backstage/catalog-model'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { Entity, ENTITY_DEFAULT_NAMESPACE } from '@backstage/catalog-model'; import { Config } from '@backstage/config'; import { assertError, NotFoundError } from '@backstage/errors'; import { ScmIntegrationRegistry } from '@backstage/integration'; @@ -23,9 +24,15 @@ import { PreparerBuilder, PublisherBase, } from '@backstage/techdocs-common'; +import fetch from 'cross-fetch'; import { PassThrough } from 'stream'; import * as winston from 'winston'; -import { DocsBuilder, shouldCheckForUpdate } from '../DocsBuilder'; +import { TechDocsCache } from '../cache'; +import { + BuildMetadataStorage, + DocsBuilder, + shouldCheckForUpdate, +} from '../DocsBuilder'; export type DocsSynchronizerSyncOpts = { log: (message: string) => void; @@ -38,22 +45,26 @@ export class DocsSynchronizer { private readonly logger: winston.Logger; private readonly config: Config; private readonly scmIntegrations: ScmIntegrationRegistry; + private readonly cache: TechDocsCache | undefined; constructor({ publisher, logger, config, scmIntegrations, + cache, }: { publisher: PublisherBase; logger: winston.Logger; config: Config; scmIntegrations: ScmIntegrationRegistry; + cache: TechDocsCache | undefined; }) { this.config = config; this.logger = logger; this.publisher = publisher; this.scmIntegrations = scmIntegrations; + this.cache = cache; } async doSync({ @@ -104,6 +115,7 @@ export class DocsSynchronizer { config: this.config, scmIntegrations: this.scmIntegrations, logStream, + cache: this.cache, }); const updated = await docsBuilder.build(); @@ -145,4 +157,76 @@ export class DocsSynchronizer { finish({ updated: true }); } + + async doCacheSync({ + responseHandler: { finish }, + discovery, + token, + entity, + }: { + responseHandler: DocsSynchronizerSyncOpts; + discovery: PluginEndpointDiscovery; + token: string | undefined; + entity: Entity; + }) { + // Check if the last update check was too recent. + if (!shouldCheckForUpdate(entity.metadata.uid!) || !this.cache) { + finish({ updated: false }); + return; + } + + // Fetch techdocs_metadata.json from the publisher and from cache. + const baseUrl = await discovery.getBaseUrl('techdocs'); + const namespace = entity.metadata?.namespace || ENTITY_DEFAULT_NAMESPACE; + const kind = entity.kind; + const name = entity.metadata.name; + const legacyPathCasing = + this.config.getOptionalBoolean( + 'techdocs.legacyUseCaseSensitiveTripletPaths', + ) || false; + const tripletPath = `${namespace}/${kind}/${name}`; + const entityTripletPath = `${ + legacyPathCasing ? tripletPath : tripletPath.toLocaleLowerCase('en-US') + }`; + try { + const [sourceMetadata, cachedMetadata] = await Promise.all([ + this.publisher.fetchTechDocsMetadata({ namespace, kind, name }), + fetch( + `${baseUrl}/static/docs/${entityTripletPath}/techdocs_metadata.json`, + { + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }, + ).then( + f => + f.json().catch(() => undefined) as ReturnType< + PublisherBase['fetchTechDocsMetadata'] + >, + ), + ]); + + // If build timestamps differ, merge their files[] lists and invalidate all objects. + if (sourceMetadata.build_timestamp !== cachedMetadata.build_timestamp) { + const files = [ + ...new Set([ + ...(sourceMetadata.files || []), + ...(cachedMetadata.files || []), + ]), + ].map(f => `${entityTripletPath}/${f}`); + await this.cache.invalidateMultiple(files); + finish({ updated: true }); + } else { + finish({ updated: false }); + } + } catch (e) { + assertError(e); + // In case of error, log and allow the user to go about their business. + this.logger.error( + `Error syncing cache for ${entityTripletPath}: ${e.message}`, + ); + finish({ updated: false }); + } finally { + // Update the last check time for the entity + new BuildMetadataStorage(entity.metadata.uid!).setLastUpdated(); + } + } } diff --git a/plugins/techdocs-backend/src/service/router.ts b/plugins/techdocs-backend/src/service/router.ts index e560a895b6..8f48342683 100644 --- a/plugins/techdocs-backend/src/service/router.ts +++ b/plugins/techdocs-backend/src/service/router.ts @@ -13,7 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { + PluginEndpointDiscovery, + PluginCacheManager, +} from '@backstage/backend-common'; import { CatalogClient } from '@backstage/catalog-client'; import { Entity, stringifyEntityRef } from '@backstage/catalog-model'; import { Config } from '@backstage/config'; @@ -24,13 +27,14 @@ import { PreparerBuilder, PublisherBase, } from '@backstage/techdocs-common'; -import fetch from 'cross-fetch'; +import fetch from 'node-fetch'; import express, { Response } from 'express'; import Router from 'express-promise-router'; import { Knex } from 'knex'; import { Logger } from 'winston'; import { ScmIntegrations } from '@backstage/integration'; import { DocsSynchronizer, DocsSynchronizerSyncOpts } from './DocsSynchronizer'; +import { createCacheMiddleware, TechDocsCache } from '../cache'; /** * All of the required dependencies for running TechDocs in the "out-of-the-box" @@ -44,6 +48,7 @@ type OutOfTheBoxDeploymentOptions = { discovery: PluginEndpointDiscovery; database?: Knex; // TODO: Make database required when we're implementing database stuff. config: Config; + cache?: PluginCacheManager; }; /** @@ -80,12 +85,22 @@ export async function createRouter( const router = Router(); const { publisher, config, logger, discovery } = options; const catalogClient = new CatalogClient({ discoveryApi: discovery }); + + // Set up a cache client if configured. + let cache: TechDocsCache | undefined; + const defaultTtl = config.getOptionalNumber('techdocs.cache.ttl'); + if (isOutOfTheBoxOption(options) && options.cache && defaultTtl) { + const cacheClient = options.cache.getClient({ defaultTtl }); + cache = TechDocsCache.fromConfig(config, { cache: cacheClient, logger }); + } + const scmIntegrations = ScmIntegrations.fromConfig(config); const docsSynchronizer = new DocsSynchronizer({ publisher, logger, config, scmIntegrations, + cache, }); router.get('/metadata/techdocs/:namespace/:kind/:name', async (req, res) => { @@ -175,6 +190,17 @@ export async function createRouter( // If set to 'external', it will assume that an external process (e.g. CI/CD pipeline // of the repository) is responsible for building and publishing documentation to the storage provider if (config.getString('techdocs.builder') !== 'local') { + // However, if caching is enabled, take the opportunity to check and + // invalidate stale cache entries. + if (cache) { + await docsSynchronizer.doCacheSync({ + responseHandler, + discovery, + token, + entity, + }); + return; + } responseHandler.finish({ updated: false }); return; } @@ -199,6 +225,11 @@ export async function createRouter( ); }); + // If a cache manager was provided, attach the cache middleware. + if (cache) { + router.use(createCacheMiddleware({ logger, cache })); + } + // Route middleware which serves files from the storage set in the publisher. router.use('/static/docs', publisher.docsRouter()); diff --git a/plugins/techdocs/CHANGELOG.md b/plugins/techdocs/CHANGELOG.md index 6b8a8f0ff9..22501e0ad7 100644 --- a/plugins/techdocs/CHANGELOG.md +++ b/plugins/techdocs/CHANGELOG.md @@ -1,5 +1,39 @@ # @backstage/plugin-techdocs +## 0.12.8 + +### Patch Changes + +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + - @backstage/plugin-search@0.5.0 + +## 0.12.7 + +### Patch Changes + +- bab752e2b3: Change default port of backend from 7000 to 7007. + + This is due to the AirPlay Receiver process occupying port 7000 and preventing local Backstage instances on MacOS to start. + + You can change the port back to 7000 or any other value by providing an `app-config.yaml` with the following values: + + ``` + backend: + listen: 0.0.0.0:7123 + baseUrl: http://localhost:7123 + ``` + + More information can be found here: https://backstage.io/docs/conf/writing + +- Updated dependencies + - @backstage/errors@0.1.5 + - @backstage/core-plugin-api@0.2.1 + - @backstage/core-components@0.7.5 + ## 0.12.6 ### Patch Changes diff --git a/plugins/techdocs/package.json b/plugins/techdocs/package.json index 663c83118e..c65fba7210 100644 --- a/plugins/techdocs/package.json +++ b/plugins/techdocs/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-techdocs", "description": "The Backstage plugin that renders technical documentation for your components", - "version": "0.12.6", + "version": "0.12.8", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -34,15 +34,15 @@ "dependencies": { "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.11", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/errors": "^0.1.4", - "@backstage/integration": "^0.6.9", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/errors": "^0.1.5", + "@backstage/integration": "^0.6.10", "@backstage/integration-react": "^0.1.14", "@backstage/plugin-catalog": "^0.7.3", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/plugin-search": "^0.4.18", - "@backstage/theme": "^0.2.13", + "@backstage/plugin-search": "^0.5.0", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -61,10 +61,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/react-hooks": "^7.0.2", diff --git a/plugins/techdocs/src/EntityPageDocs.tsx b/plugins/techdocs/src/EntityPageDocs.tsx index c5356289f0..b10fba6d2e 100644 --- a/plugins/techdocs/src/EntityPageDocs.tsx +++ b/plugins/techdocs/src/EntityPageDocs.tsx @@ -17,15 +17,18 @@ import React from 'react'; import { Entity } from '@backstage/catalog-model'; import { Reader } from './reader'; +import { toLowerMaybe } from './helpers'; +import { configApiRef, useApi } from '@backstage/core-plugin-api'; export const EntityPageDocs = ({ entity }: { entity: Entity }) => { + const config = useApi(configApiRef); return ( ); diff --git a/plugins/techdocs/src/helpers.ts b/plugins/techdocs/src/helpers.ts new file mode 100644 index 0000000000..7ff4dec6e7 --- /dev/null +++ b/plugins/techdocs/src/helpers.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2021 The Backstage Authors + * + * 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 } from '@backstage/config'; + +// Lower-case entity triplets by default, but allow override. +export function toLowerMaybe(str: string, config: Config) { + return config.getOptionalBoolean( + 'techdocs.legacyUseCaseSensitiveTripletPaths', + ) + ? str + : str.toLocaleLowerCase('en-US'); +} diff --git a/plugins/techdocs/src/home/components/DocsCardGrid.tsx b/plugins/techdocs/src/home/components/DocsCardGrid.tsx index 77e69995ae..1aef793bd2 100644 --- a/plugins/techdocs/src/home/components/DocsCardGrid.tsx +++ b/plugins/techdocs/src/home/components/DocsCardGrid.tsx @@ -17,7 +17,7 @@ import React from 'react'; import { Entity } from '@backstage/catalog-model'; -import { configApiRef, useApi, useRouteRef } from '@backstage/core-plugin-api'; +import { useApi, useRouteRef, configApiRef } from '@backstage/core-plugin-api'; import { Card, CardActions, CardContent, CardMedia } from '@material-ui/core'; import { rootDocsRouteRef } from '../../routes'; @@ -26,6 +26,7 @@ import { ItemCardGrid, ItemCardHeader, } from '@backstage/core-components'; +import { toLowerMaybe } from '../../helpers'; export const DocsCardGrid = ({ entities, @@ -33,14 +34,7 @@ export const DocsCardGrid = ({ entities: Entity[] | undefined; }) => { const getRouteToReaderPageFor = useRouteRef(rootDocsRouteRef); - - // Lower-case entity triplets by default, but allow override. - const toLowerMaybe = useApi(configApiRef).getOptionalBoolean( - 'techdocs.legacyUseCaseSensitiveTripletPaths', - ) - ? (str: string) => str - : (str: string) => str.toLocaleLowerCase('en-US'); - + const config = useApi(configApiRef); if (!entities) return null; return ( @@ -59,9 +53,10 @@ export const DocsCardGrid = ({ to={getRouteToReaderPageFor({ namespace: toLowerMaybe( entity.metadata.namespace ?? 'default', + config, ), - kind: toLowerMaybe(entity.kind), - name: toLowerMaybe(entity.metadata.name), + kind: toLowerMaybe(entity.kind, config), + name: toLowerMaybe(entity.metadata.name, config), })} color="primary" data-testid="read_docs" diff --git a/plugins/techdocs/src/home/components/DocsTable.tsx b/plugins/techdocs/src/home/components/DocsTable.tsx index 0e64c2e2e8..83d6f05788 100644 --- a/plugins/techdocs/src/home/components/DocsTable.tsx +++ b/plugins/techdocs/src/home/components/DocsTable.tsx @@ -17,7 +17,7 @@ import React from 'react'; import { useCopyToClipboard } from 'react-use'; -import { configApiRef, useApi, useRouteRef } from '@backstage/core-plugin-api'; +import { useRouteRef, useApi, configApiRef } from '@backstage/core-plugin-api'; import { Entity, RELATION_OWNED_BY } from '@backstage/catalog-model'; import { formatEntityRefTitle, @@ -34,6 +34,7 @@ import { import * as actionFactories from './actions'; import * as columnFactories from './columns'; import { DocsTableRow } from './types'; +import { toLowerMaybe } from '../../helpers'; export const DocsTable = ({ entities, @@ -50,26 +51,21 @@ export const DocsTable = ({ }) => { const [, copyToClipboard] = useCopyToClipboard(); const getRouteToReaderPageFor = useRouteRef(rootDocsRouteRef); - - // Lower-case entity triplets by default, but allow override. - const toLowerMaybe = useApi(configApiRef).getOptionalBoolean( - 'techdocs.legacyUseCaseSensitiveTripletPaths', - ) - ? (str: string) => str - : (str: string) => str.toLocaleLowerCase('en-US'); - + const config = useApi(configApiRef); if (!entities) return null; const documents = entities.map(entity => { const ownedByRelations = getEntityRelations(entity, RELATION_OWNED_BY); - return { entity, resolved: { docsUrl: getRouteToReaderPageFor({ - namespace: toLowerMaybe(entity.metadata.namespace ?? 'default'), - kind: toLowerMaybe(entity.kind), - name: toLowerMaybe(entity.metadata.name), + namespace: toLowerMaybe( + entity.metadata.namespace ?? 'default', + config, + ), + kind: toLowerMaybe(entity.kind, config), + name: toLowerMaybe(entity.metadata.name, config), }), ownedByRelations, ownedByRelationsTitle: ownedByRelations diff --git a/plugins/todo-backend/CHANGELOG.md b/plugins/todo-backend/CHANGELOG.md index 60fd7a5490..f27dba351d 100644 --- a/plugins/todo-backend/CHANGELOG.md +++ b/plugins/todo-backend/CHANGELOG.md @@ -1,5 +1,14 @@ # @backstage/plugin-todo-backend +## 0.1.14 + +### Patch Changes + +- b055a6addc: Align on usage of `cross-fetch` vs `node-fetch` in frontend vs backend packages, and remove some unnecessary imports of either one of them +- Updated dependencies + - @backstage/integration@0.6.10 + - @backstage/backend-common@0.9.12 + ## 0.1.13 ### Patch Changes diff --git a/plugins/todo-backend/package.json b/plugins/todo-backend/package.json index be1dc658f1..dd69f60072 100644 --- a/plugins/todo-backend/package.json +++ b/plugins/todo-backend/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-todo-backend", "description": "A Backstage backend plugin that lets you browse TODO comments in your source code", - "version": "0.1.13", + "version": "0.1.14", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -25,14 +25,13 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/backend-common": "^0.9.10", + "@backstage/backend-common": "^0.9.12", "@backstage/catalog-client": "^0.5.2", "@backstage/catalog-model": "^0.9.7", "@backstage/config": "^0.1.10", "@backstage/errors": "^0.1.3", - "@backstage/integration": "^0.6.7", + "@backstage/integration": "^0.6.10", "@types/express": "^4.17.6", - "cross-fetch": "^3.0.6", "express": "^4.17.1", "express-promise-router": "^4.1.0", "leasot": "^12.0.0", @@ -40,7 +39,7 @@ "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.9.0", + "@backstage/cli": "^0.10.0", "@types/supertest": "^2.0.8", "msw": "^0.35.0", "supertest": "^6.1.3" diff --git a/plugins/todo/package.json b/plugins/todo/package.json index 22a8e6b1e2..1fadc213af 100644 --- a/plugins/todo/package.json +++ b/plugins/todo/package.json @@ -28,11 +28,11 @@ }, "dependencies": { "@backstage/catalog-model": "^0.9.7", - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", "@backstage/errors": "^0.1.3", "@backstage/plugin-catalog-react": "^0.6.4", - "@backstage/theme": "^0.2.13", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -41,10 +41,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/user-settings/CHANGELOG.md b/plugins/user-settings/CHANGELOG.md index a309afb497..8511860dd1 100644 --- a/plugins/user-settings/CHANGELOG.md +++ b/plugins/user-settings/CHANGELOG.md @@ -1,5 +1,15 @@ # @backstage/plugin-user-settings +## 0.3.12 + +### Patch Changes + +- 9a1c8e92eb: The theme switcher now renders the title of themes instead of their variant +- Updated dependencies + - @backstage/core-components@0.7.6 + - @backstage/theme@0.2.14 + - @backstage/core-plugin-api@0.2.2 + ## 0.3.11 ### Patch Changes diff --git a/plugins/user-settings/package.json b/plugins/user-settings/package.json index def12ac1d2..feab9dcf93 100644 --- a/plugins/user-settings/package.json +++ b/plugins/user-settings/package.json @@ -1,7 +1,7 @@ { "name": "@backstage/plugin-user-settings", "description": "A Backstage plugin that provides a settings page", - "version": "0.3.11", + "version": "0.3.12", "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", @@ -31,9 +31,9 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@backstage/core-components": "^0.7.4", - "@backstage/core-plugin-api": "^0.2.0", - "@backstage/theme": "^0.2.13", + "@backstage/core-components": "^0.7.6", + "@backstage/core-plugin-api": "^0.2.2", + "@backstage/theme": "^0.2.14", "@material-ui/core": "^4.12.2", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.57", @@ -43,10 +43,10 @@ "react-use": "^17.2.4" }, "devDependencies": { - "@backstage/cli": "^0.9.0", - "@backstage/core-app-api": "^0.1.22", + "@backstage/cli": "^0.10.0", + "@backstage/core-app-api": "^0.1.24", "@backstage/dev-utils": "^0.2.13", - "@backstage/test-utils": "^0.1.22", + "@backstage/test-utils": "^0.1.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^13.1.8", diff --git a/plugins/user-settings/src/components/General/UserSettingsThemeToggle.tsx b/plugins/user-settings/src/components/General/UserSettingsThemeToggle.tsx index 4261218c44..35850b9d82 100644 --- a/plugins/user-settings/src/components/General/UserSettingsThemeToggle.tsx +++ b/plugins/user-settings/src/components/General/UserSettingsThemeToggle.tsx @@ -131,7 +131,7 @@ export const UserSettingsThemeToggle = () => { value={theme.id} > <> - {theme.variant}  + {theme.title}  { ).toBeInTheDocument(); expect(rendered.getByText(client.mockBuild.schema)).toBeInTheDocument(); }); + + it('should render if xcode data is not present', async () => { + const rendered = await renderInTestApp( + + + , + ); + + expect( + rendered.getByText('Xcode').parentNode?.childNodes[1].textContent, + ).toEqual('Unknown'); + }); }); describe('BuildDetails with request', () => { diff --git a/plugins/xcmetrics/src/components/BuildDetails/BuildDetails.tsx b/plugins/xcmetrics/src/components/BuildDetails/BuildDetails.tsx index 1d77bf7a7a..8732bd92d8 100644 --- a/plugins/xcmetrics/src/components/BuildDetails/BuildDetails.tsx +++ b/plugins/xcmetrics/src/components/BuildDetails/BuildDetails.tsx @@ -78,7 +78,7 @@ export const BuildDetails = ({ {formatStatus(build.buildStatus)} ), - xcode: `${xcode.version} (${xcode.buildNumber})`, + xcode: xcode ? `${xcode.version} (${xcode.buildNumber})` : 'Unknown', CI: build.isCi, }; diff --git a/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.test.tsx b/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.test.tsx index a208432f59..0801a34b48 100644 --- a/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.test.tsx +++ b/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.test.tsx @@ -17,6 +17,7 @@ import React from 'react'; import { renderInTestApp } from '@backstage/test-utils'; import { StatusIcon } from './StatusIcon'; +import { BuildStatus } from '../../api'; describe('StatusIcon', () => { it('should render', async () => { @@ -31,4 +32,11 @@ describe('StatusIcon', () => { rendered = await renderInTestApp(); expect(rendered.getByLabelText('Status warning')).toBeInTheDocument(); }); + + it('should render invalid statuses', async () => { + const rendered = await renderInTestApp( + , + ); + expect(rendered.getByLabelText('Status aborted')).toBeInTheDocument(); + }); }); diff --git a/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.tsx b/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.tsx index 610575b817..f28b5e4fe4 100644 --- a/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.tsx +++ b/plugins/xcmetrics/src/components/StatusIcon/StatusIcon.tsx @@ -15,6 +15,7 @@ */ import React from 'react'; import { + StatusAborted, StatusError, StatusOK, StatusWarning, @@ -32,4 +33,4 @@ interface StatusIconProps { } export const StatusIcon = ({ buildStatus }: StatusIconProps) => - STATUS_ICONS[buildStatus]; + STATUS_ICONS[buildStatus] ?? ; diff --git a/scripts/api-extractor.ts b/scripts/api-extractor.ts index 22eae267ee..8ca7743cf2 100644 --- a/scripts/api-extractor.ts +++ b/scripts/api-extractor.ts @@ -35,6 +35,7 @@ import { import { Program } from 'typescript'; import { DocNode, + DocSection, IDocNodeContainerParameters, TSDocTagSyntaxKind, } from '@microsoft/tsdoc'; @@ -50,6 +51,7 @@ import { DocHeading } from '@microsoft/api-documenter/lib/nodes/DocHeading'; import { CustomMarkdownEmitter } from '@microsoft/api-documenter/lib/markdown/CustomMarkdownEmitter'; import { IMarkdownEmitterContext } from '@microsoft/api-documenter/lib/markdown/MarkdownEmitter'; import { AstDeclaration } from '@microsoft/api-extractor/lib/analyzer/AstDeclaration'; +import { DocTableCell } from '@microsoft/api-documenter/lib/nodes/DocTableCell'; const tmpDir = resolvePath(__dirname, '../node_modules/.cache/api-extractor'); @@ -603,9 +605,18 @@ async function buildDocs({ }); for (const apiMember of apiModel.members) { + // This is a workaround for this check failing: https://github.com/microsoft/rushstack/blob/915aca8d8847b65981892f44f0544ccb00752792/apps/api-documenter/src/documenters/MarkdownDocumenter.ts#L991 + const description = new DocSection({ configuration }); + if (apiMember.tsdocComment !== undefined) { + this._appendAndMergeSection( + description, + apiMember.tsdocComment.summarySection, + ); + } + const row = new DocTableRow({ configuration }, [ this._createTitleCell(apiMember), - this._createDescriptionCell(apiMember), + new DocTableCell({ configuration }, description.nodes), ]); if (apiMember.kind === 'Package') { diff --git a/yarn.lock b/yarn.lock index 1e4d402072..35059f4b70 100644 --- a/yarn.lock +++ b/yarn.lock @@ -69,25 +69,25 @@ dependencies: tslib "~2.0.1" -"@asyncapi/avro-schema-parser@^0.2.1": - version "0.2.1" - resolved "https://registry.npmjs.org/@asyncapi/avro-schema-parser/-/avro-schema-parser-0.2.1.tgz#0b7d9953e12084e6f556db261ae08bd8f6690faa" - integrity sha512-RZJaHsdYM4dChYSrb/TWrVCn/r2qcus+9/8iLL8+SMINHb0ECgH8tFZFJpr3Tq+LV2SBFaRQ+9kuecjQ8BNDSA== +"@asyncapi/avro-schema-parser@^0.3.0": + version "0.3.0" + resolved "https://registry.npmjs.org/@asyncapi/avro-schema-parser/-/avro-schema-parser-0.3.0.tgz#6922acc559ef999c57e81297d78ffe680fc92b3c" + integrity sha512-gWAqS2CKxbChdX8hZY+5EYQl6atP8FTSBvoG5mGGQ89XUoNdlLX14lsvbgvBnDj5sSwqfs+b5Mh5PUZMR/8maA== -"@asyncapi/openapi-schema-parser@^2.0.1": +"@asyncapi/openapi-schema-parser@^2.0.0": version "2.0.1" resolved "https://registry.npmjs.org/@asyncapi/openapi-schema-parser/-/openapi-schema-parser-2.0.1.tgz#4d6e82cced907b14e0ad6f98261ff2562d968d96" integrity sha512-algbtdM1gcAOa8+V8kp7WeBhdaNac82jmZUXx8YjyNfRVo02N2juDrjeBAGJd+FNva9Mb4MM7qfkJoAFpTL5VQ== dependencies: "@openapi-contrib/openapi-schema-to-json-schema" "^3.0.0" -"@asyncapi/parser@^1.5.0": - version "1.5.0" - resolved "https://registry.npmjs.org/@asyncapi/parser/-/parser-1.5.0.tgz#d70616a1e6081c7dd86957befd5dccc46b9a77df" - integrity sha512-HzrehCcT6R+iqtktNmrUM9wRUEMBqnCeXIrGJT0txBMS1QduNRmXGjvuDpxqwyaATPH/xu1gSp2l6pFP/hyVbA== +"@asyncapi/parser@^1.13.0": + version "1.13.0" + resolved "https://registry.npmjs.org/@asyncapi/parser/-/parser-1.13.0.tgz#bc20d53ba870ead9d26d5a4e3a838c5765ba8d4c" + integrity sha512-UnTYSjx2Sc+VKWIIeIV5I+ogFbN5iWzNgx1UgTXQ5oPhtNlsdIkF+w7qV8GyiraaKbBqAuwepv4xbBvlEi8hkw== dependencies: "@apidevtools/json-schema-ref-parser" "^9.0.6" - "@asyncapi/specs" "^2.7.7" + "@asyncapi/specs" "^2.11.0" "@fmvilas/pseudo-yaml-ast" "^0.3.1" ajv "^6.10.1" js-yaml "^3.13.1" @@ -96,25 +96,24 @@ node-fetch "^2.6.0" tiny-merge-patch "^0.1.2" -"@asyncapi/react-component@^0.23.0": - version "0.23.1" - resolved "https://registry.npmjs.org/@asyncapi/react-component/-/react-component-0.23.1.tgz#6ae574aac86d835e6845268d49803c4808f37b97" - integrity sha512-xBH8F//sF4Sb7M95eVDnQDG+czklQieFKHkCr8SJmmb2j4NylAOTJBoYSZJ3QTC9r0O+SxdQglwh+u1mhMAU+A== +"@asyncapi/react-component@^1.0.0-next.25": + version "1.0.0-next.25" + resolved "https://registry.npmjs.org/@asyncapi/react-component/-/react-component-1.0.0-next.25.tgz#76b27e0e239b03c32499ee5cd8977e5ceb74f754" + integrity sha512-S+HguQ6IltQWiy+jO7hlmANJYxJ2UOvH7iMAw+YTcDtYGOe/mrDr7vbrrB3HigZRYIyZSV34cNgNOhw/psVHlg== dependencies: - "@asyncapi/avro-schema-parser" "^0.2.1" - "@asyncapi/openapi-schema-parser" "^2.0.1" - "@asyncapi/parser" "^1.5.0" - constate "^1.2.0" - dompurify "^2.1.1" - markdown-it "^11.0.1" - merge "^2.1.0" - openapi-sampler "^1.0.0-beta.15" - react-use "^12.2.0" + "@asyncapi/avro-schema-parser" "^0.3.0" + "@asyncapi/openapi-schema-parser" "^2.0.0" + "@asyncapi/parser" "^1.13.0" + highlight.js "^10.7.2" + isomorphic-dompurify "^0.13.0" + marked "^2.1.1" + openapi-sampler "^1.1.0" + use-resize-observer "^7.0.0" -"@asyncapi/specs@^2.7.7": - version "2.7.7" - resolved "https://registry.npmjs.org/@asyncapi/specs/-/specs-2.7.7.tgz#10f72c95153a3cc10039f6ba9c3a6f7c3b7fecfc" - integrity sha512-z8kj4GDJ640DU4msRsWprvmuC9n7vIeJW+D7Tp1xdefoLX5ZJrK7+4Xruna513wV0fSLpFzCmGz7McEP6CtKDg== +"@asyncapi/specs@^2.11.0": + version "2.12.0" + resolved "https://registry.npmjs.org/@asyncapi/specs/-/specs-2.12.0.tgz#15534ca9e518b561d33edfdfdbb234f9b274f261" + integrity sha512-X4Xkrl+9WXSk5EJhsueIxNx6ymHI5wpkw4ofetV+VRnPLNob/XO4trPSJClrL5hlknxbGADLvlrkI5d3XJ996g== "@azure/abort-controller@^1.0.0": version "1.0.2" @@ -2627,6 +2626,71 @@ exec-sh "^0.3.2" minimist "^1.2.0" +"@codemirror/highlight@^0.19.0": + version "0.19.6" + resolved "https://registry.npmjs.org/@codemirror/highlight/-/highlight-0.19.6.tgz#7f2e066f83f5649e8e0748a3abe0aaeaf64b8ac2" + integrity sha512-+eibu6on9quY8uN3xJ/n3rH+YIDLlpX7YulVmFvqAIz/ukRQ5tWaBmB7fMixHmnmRIRBRZgB8rNtonuMwZSAHQ== + dependencies: + "@codemirror/language" "^0.19.0" + "@codemirror/rangeset" "^0.19.0" + "@codemirror/state" "^0.19.0" + "@codemirror/view" "^0.19.0" + "@lezer/common" "^0.15.0" + style-mod "^4.0.0" + +"@codemirror/language@^0.19.0": + version "0.19.7" + resolved "https://registry.npmjs.org/@codemirror/language/-/language-0.19.7.tgz#9eef8e827692d93a701b18db9d46a42be34ecca6" + integrity sha512-pNNUtYWMIMG0lUSKyUXJr8U0rFiCKsKFXbA2Oj17PC+S1FY99hV0z1vcntW67ekAIZw9DMEUQnLsKBuIbAUX7Q== + dependencies: + "@codemirror/state" "^0.19.0" + "@codemirror/text" "^0.19.0" + "@codemirror/view" "^0.19.0" + "@lezer/common" "^0.15.5" + "@lezer/lr" "^0.15.0" + +"@codemirror/rangeset@^0.19.0": + version "0.19.2" + resolved "https://registry.npmjs.org/@codemirror/rangeset/-/rangeset-0.19.2.tgz#d7a999e4273c00fecef4aba8535a426073cdcddf" + integrity sha512-5d+X8LtmeZtfFtKrSx57bIHRUpKv2HD0b74clp4fGA7qJLLfYehF6FGkJJxJb8lKsqAga1gdjjWr0jiypmIxoQ== + dependencies: + "@codemirror/state" "^0.19.0" + +"@codemirror/state@^0.19.0", "@codemirror/state@^0.19.3": + version "0.19.6" + resolved "https://registry.npmjs.org/@codemirror/state/-/state-0.19.6.tgz#d631f041d39ce41b7891b099fca26cb1fdb9763e" + integrity sha512-sqIQZE9VqwQj7D4c2oz9mfLhlT1ElAzGB5lO1lE33BPyrdNy1cJyCIOecT4cn4VeJOFrnjOeu+IftZ3zqdFETw== + dependencies: + "@codemirror/text" "^0.19.0" + +"@codemirror/stream-parser@^0.19.2": + version "0.19.2" + resolved "https://registry.npmjs.org/@codemirror/stream-parser/-/stream-parser-0.19.2.tgz#793428e55aa7b9daa64cb733973e5d5e3d9a2306" + integrity sha512-hBKRQlyu8GUOrY33xZ6/1kAfNZ8ZUm6cX9a7mPx8zAAqnpz/fpksC/qJRrkg1mPMBwxm+JG4fqAwDGJ3gLVniQ== + dependencies: + "@codemirror/highlight" "^0.19.0" + "@codemirror/language" "^0.19.0" + "@codemirror/state" "^0.19.0" + "@codemirror/text" "^0.19.0" + "@lezer/common" "^0.15.0" + "@lezer/lr" "^0.15.0" + +"@codemirror/text@^0.19.0": + version "0.19.5" + resolved "https://registry.npmjs.org/@codemirror/text/-/text-0.19.5.tgz#75033af2476214e79eae22b81ada618815441c18" + integrity sha512-Syu5Xc7tZzeUAM/y4fETkT0zgGr48rDG+w4U38bPwSIUr+L9S/7w2wDE1WGNzjaZPz12F6gb1gxWiSTg9ocLow== + +"@codemirror/view@^0.19.0": + version "0.19.27" + resolved "https://registry.npmjs.org/@codemirror/view/-/view-0.19.27.tgz#76e5dc19ecb4ce53e9fef1d29245040d7ff64183" + integrity sha512-Uz/LecEf7CyvMWaQBlKtbJCYn0hRnEZ2yYvuZVy9YMhmvGmES6ec7FaKw7lDFFOMLwLbBThc9kfw4DCHreHN1w== + dependencies: + "@codemirror/rangeset" "^0.19.0" + "@codemirror/state" "^0.19.3" + "@codemirror/text" "^0.19.0" + style-mod "^4.0.0" + w3c-keyname "^2.2.4" + "@cspotcode/source-map-consumer@0.8.0": version "0.8.0" resolved "https://registry.npmjs.org/@cspotcode/source-map-consumer/-/source-map-consumer-0.8.0.tgz#33bf4b7b39c178821606f669bbc447a6a629786b" @@ -2650,9 +2714,9 @@ figures "^1.7.0" "@cypress/request@^2.88.5": - version "2.88.5" - resolved "https://registry.npmjs.org/@cypress/request/-/request-2.88.5.tgz#8d7ecd17b53a849cfd5ab06d5abe7d84976375d7" - integrity sha512-TzEC1XMi1hJkywWpRfD2clreTa/Z+lOrXDCxxBTBPEcY5azdPi56A6Xw+O4tWJnaJH3iIE7G5aDXZC6JgRZLcA== + version "2.88.10" + resolved "https://registry.npmjs.org/@cypress/request/-/request-2.88.10.tgz#b66d76b07f860d3a4b8d7a0604d020c662752cce" + integrity sha512-Zp7F+R93N0yZyG34GutyTNr+okam7s/Fzc1+i3kcqOP8vk6OuajuE9qZJ6Rs+10/1JFtXFYMdyarnU1rZuJesg== dependencies: aws-sign2 "~0.7.0" aws4 "^1.8.0" @@ -2661,19 +2725,17 @@ extend "~3.0.2" forever-agent "~0.6.1" form-data "~2.3.2" - har-validator "~5.1.3" - http-signature "~1.2.0" + http-signature "~1.3.6" is-typedarray "~1.0.0" isstream "~0.1.2" json-stringify-safe "~5.0.1" mime-types "~2.1.19" - oauth-sign "~0.9.0" performance-now "^2.1.0" qs "~6.5.2" safe-buffer "^5.1.2" tough-cookie "~2.5.0" tunnel-agent "^0.6.0" - uuid "^3.3.2" + uuid "^8.3.2" "@cypress/xvfb@^1.2.4": version "1.2.4" @@ -2987,13 +3049,12 @@ stream-events "^1.0.1" xdg-basedir "^4.0.0" -"@graphiql/toolkit@^0.3.2": - version "0.3.2" - resolved "https://registry.npmjs.org/@graphiql/toolkit/-/toolkit-0.3.2.tgz#551753436ada2bc27ea870b7668e5199a958ccfb" - integrity sha512-IweIT9VC8uDovg7kuCO9YqZcnIuWU8IGzrpUisXv6CUNK2Ed1ke8yERDTMmF/rjvLd2DeVZwM8iEOjEs4sUJQw== +"@graphiql/toolkit@^0.4.2": + version "0.4.2" + resolved "https://registry.npmjs.org/@graphiql/toolkit/-/toolkit-0.4.2.tgz#34de819add64672f3f7d4830dffb2094fb8d5366" + integrity sha512-14uG67QrONbRrhXwvBJFsMfcQfexmGhj7dgkputesx9xuPUkcCDNmVULnVA8sGYt8P/rSvjkfQYx3rtfW+GhAQ== dependencies: - "@n1ru4l/push-pull-async-iterable-iterator" "^3.0.0" - graphql-ws "^4.9.0" + "@n1ru4l/push-pull-async-iterable-iterator" "^3.1.0" meros "^1.1.4" "@graphql-codegen/cli@^1.21.3": @@ -3176,6 +3237,16 @@ tslib "~2.2.0" value-or-promise "1.0.6" +"@graphql-tools/batch-execute@^8.3.1": + version "8.3.1" + resolved "https://registry.npmjs.org/@graphql-tools/batch-execute/-/batch-execute-8.3.1.tgz#0b74c54db5ac1c5b9a273baefc034c2343ebbb74" + integrity sha512-63kHY8ZdoO5FoeDXYHnAak1R3ysMViMPwWC2XUblFckuVLMUPmB2ONje8rjr2CvzWBHAW8c1Zsex+U3xhKtGIA== + dependencies: + "@graphql-tools/utils" "^8.5.1" + dataloader "2.0.0" + tslib "~2.3.0" + value-or-promise "1.0.11" + "@graphql-tools/code-file-loader@^6.3.1": version "6.3.1" resolved "https://registry.npmjs.org/@graphql-tools/code-file-loader/-/code-file-loader-6.3.1.tgz#42dfd4db5b968acdb453382f172ec684fa0c34ed" @@ -3198,6 +3269,18 @@ tslib "~2.2.0" value-or-promise "1.0.6" +"@graphql-tools/delegate@^8.4.1", "@graphql-tools/delegate@^8.4.2": + version "8.4.2" + resolved "https://registry.npmjs.org/@graphql-tools/delegate/-/delegate-8.4.2.tgz#a61d45719855720304e3656800342cfa17d82558" + integrity sha512-CjggOhiL4WtyG2I3kux+1/p8lQxSFHBj0gwa0NxnQ6Vsnpw7Ig5VP1ovPnitFuBv2k4QdC37Nj2xv2n7DRn8fw== + dependencies: + "@graphql-tools/batch-execute" "^8.3.1" + "@graphql-tools/schema" "^8.3.1" + "@graphql-tools/utils" "^8.5.3" + dataloader "2.0.0" + tslib "~2.3.0" + value-or-promise "1.0.11" + "@graphql-tools/git-loader@^6.2.6": version "6.2.6" resolved "https://registry.npmjs.org/@graphql-tools/git-loader/-/git-loader-6.2.6.tgz#c2226f4b8f51f1c05c9ab2649ba32d49c68cd077" @@ -3226,6 +3309,17 @@ "@graphql-tools/utils" "^7.0.0" tslib "~2.1.0" +"@graphql-tools/graphql-file-loader@^7.3.2": + version "7.3.3" + resolved "https://registry.npmjs.org/@graphql-tools/graphql-file-loader/-/graphql-file-loader-7.3.3.tgz#7cee2f84f08dc13fa756820b510248b857583d36" + integrity sha512-6kUJZiNpYKVhum9E5wfl5PyLLupEDYdH7c8l6oMrk6c7EPEVs6iSUyB7yQoWrtJccJLULBW2CRQ5IHp5JYK0mA== + dependencies: + "@graphql-tools/import" "^6.5.7" + "@graphql-tools/utils" "^8.5.1" + globby "^11.0.3" + tslib "~2.3.0" + unixify "^1.0.0" + "@graphql-tools/graphql-tag-pluck@^6.2.6", "@graphql-tools/graphql-tag-pluck@^6.5.1": version "6.5.1" resolved "https://registry.npmjs.org/@graphql-tools/graphql-tag-pluck/-/graphql-tag-pluck-6.5.1.tgz#5fb227dbb1e19f4b037792b50f646f16a2d4c686" @@ -3245,6 +3339,15 @@ resolve-from "5.0.0" tslib "~2.2.0" +"@graphql-tools/import@^6.5.7": + version "6.6.1" + resolved "https://registry.npmjs.org/@graphql-tools/import/-/import-6.6.1.tgz#2a7e1ceda10103ffeb8652a48ddc47150b035485" + integrity sha512-i9WA6k+erJMci822o9w9DoX+uncVBK60LGGYW8mdbhX0l7wEubUpA000thJ1aarCusYh0u+ZT9qX0HyVPXu25Q== + dependencies: + "@graphql-tools/utils" "8.5.3" + resolve-from "5.0.0" + tslib "~2.3.0" + "@graphql-tools/json-file-loader@^6.0.0", "@graphql-tools/json-file-loader@^6.2.6": version "6.2.6" resolved "https://registry.npmjs.org/@graphql-tools/json-file-loader/-/json-file-loader-6.2.6.tgz#830482cfd3721a0799cbf2fe5b09959d9332739a" @@ -3253,6 +3356,16 @@ "@graphql-tools/utils" "^7.0.0" tslib "~2.0.1" +"@graphql-tools/json-file-loader@^7.3.2": + version "7.3.3" + resolved "https://registry.npmjs.org/@graphql-tools/json-file-loader/-/json-file-loader-7.3.3.tgz#45cfde77b9dc4ab6c21575305ae537d2814d237f" + integrity sha512-CN2Qk9rt+Gepa3rb3X/mpxYA5MIYLwZBPj2Njw6lbZ6AaxG+O1ArDCL5ACoiWiBimn1FCOM778uhRM9znd0b3Q== + dependencies: + "@graphql-tools/utils" "^8.5.1" + globby "^11.0.3" + tslib "~2.3.0" + unixify "^1.0.0" + "@graphql-tools/load@^6.0.0", "@graphql-tools/load@^6.2.8": version "6.2.8" resolved "https://registry.npmjs.org/@graphql-tools/load/-/load-6.2.8.tgz#16900fb6e75e1d075cad8f7ea439b334feb0b96a" @@ -3268,6 +3381,16 @@ unixify "1.0.0" valid-url "1.0.9" +"@graphql-tools/load@^7.4.1": + version "7.4.1" + resolved "https://registry.npmjs.org/@graphql-tools/load/-/load-7.4.1.tgz#aa572fcef11d6028097b6ef39c13fa9d62e5a441" + integrity sha512-UvBodW5hRHpgBUBVz5K5VIhJDOTFIbRRAGD6sQ2l9J5FDKBEs3u/6JjZDzbdL96br94D5cEd2Tk6auaHpTn7mQ== + dependencies: + "@graphql-tools/schema" "8.3.1" + "@graphql-tools/utils" "^8.5.1" + p-limit "3.1.0" + tslib "~2.3.0" + "@graphql-tools/merge@^6.0.0", "@graphql-tools/merge@^6.2.12", "@graphql-tools/merge@^6.2.14": version "6.2.14" resolved "https://registry.npmjs.org/@graphql-tools/merge/-/merge-6.2.14.tgz#694e2a2785ba47558e5665687feddd2935e9d94e" @@ -3277,6 +3400,14 @@ "@graphql-tools/utils" "^7.7.0" tslib "~2.2.0" +"@graphql-tools/merge@^8.2.1": + version "8.2.1" + resolved "https://registry.npmjs.org/@graphql-tools/merge/-/merge-8.2.1.tgz#bf83aa06a0cfc6a839e52a58057a84498d0d51ff" + integrity sha512-Q240kcUszhXiAYudjuJgNuLgy9CryDP3wp83NOZQezfA6h3ByYKU7xI6DiKrdjyVaGpYN3ppUmdj0uf5GaXzMA== + dependencies: + "@graphql-tools/utils" "^8.5.1" + tslib "~2.3.0" + "@graphql-tools/optimize@^1.0.1": version "1.0.1" resolved "https://registry.npmjs.org/@graphql-tools/optimize/-/optimize-1.0.1.tgz#9933fffc5a3c63f95102b1cb6076fb16ac7bb22d" @@ -3320,6 +3451,16 @@ relay-compiler "10.1.0" tslib "~2.0.1" +"@graphql-tools/schema@8.3.1", "@graphql-tools/schema@^8.3.1": + version "8.3.1" + resolved "https://registry.npmjs.org/@graphql-tools/schema/-/schema-8.3.1.tgz#1ee9da494d2da457643b3c93502b94c3c4b68c74" + integrity sha512-3R0AJFe715p4GwF067G5i0KCr/XIdvSfDLvTLEiTDQ8V/hwbOHEKHKWlEBHGRQwkG5lwFQlW1aOn7VnlPERnWQ== + dependencies: + "@graphql-tools/merge" "^8.2.1" + "@graphql-tools/utils" "^8.5.1" + tslib "~2.3.0" + value-or-promise "1.0.11" + "@graphql-tools/schema@^7.0.0", "@graphql-tools/schema@^7.1.5": version "7.1.5" resolved "https://registry.npmjs.org/@graphql-tools/schema/-/schema-7.1.5.tgz#07b24e52b182e736a6b77c829fc48b84d89aa711" @@ -3354,6 +3495,38 @@ valid-url "1.0.9" ws "7.4.5" +"@graphql-tools/url-loader@^7.4.2": + version "7.5.3" + resolved "https://registry.npmjs.org/@graphql-tools/url-loader/-/url-loader-7.5.3.tgz#a594be40e3bc68d22f76746356e7f0b8117b7137" + integrity sha512-VKMRJ4TOeVIdulkCLGSBUr4stRRwOGcVRXDeoUF+86K32Ufo0H2V0lz7QwS/bCl8GXV19FMgHZCDl4BMJyOXEA== + dependencies: + "@graphql-tools/delegate" "^8.4.1" + "@graphql-tools/utils" "^8.5.1" + "@graphql-tools/wrap" "^8.3.1" + "@n1ru4l/graphql-live-query" "0.9.0" + "@types/websocket" "1.0.4" + "@types/ws" "^8.0.0" + cross-undici-fetch "^0.0.26" + dset "^3.1.0" + extract-files "11.0.0" + graphql-sse "^1.0.1" + graphql-ws "^5.4.1" + isomorphic-ws "4.0.1" + meros "1.1.4" + subscriptions-transport-ws "^0.11.0" + sync-fetch "0.3.1" + tslib "~2.3.0" + valid-url "1.0.9" + value-or-promise "1.0.11" + ws "8.3.0" + +"@graphql-tools/utils@8.5.3", "@graphql-tools/utils@^8.5.1", "@graphql-tools/utils@^8.5.3": + version "8.5.3" + resolved "https://registry.npmjs.org/@graphql-tools/utils/-/utils-8.5.3.tgz#404062e62cae9453501197039687749c4885356e" + integrity sha512-HDNGWFVa8QQkoQB0H1lftvaO1X5xUaUDk1zr1qDe0xN1NL0E/CrQdJ5UKLqOvH4hkqVUPxQsyOoAZFkaH6rLHg== + dependencies: + tslib "~2.3.0" + "@graphql-tools/utils@^7.0.0", "@graphql-tools/utils@^7.1.0", "@graphql-tools/utils@^7.1.2", "@graphql-tools/utils@^7.5.0", "@graphql-tools/utils@^7.7.0", "@graphql-tools/utils@^7.7.1", "@graphql-tools/utils@^7.8.1", "@graphql-tools/utils@^7.9.0", "@graphql-tools/utils@^7.9.1": version "7.10.0" resolved "https://registry.npmjs.org/@graphql-tools/utils/-/utils-7.10.0.tgz#07a4cb5d1bec1ff1dc1d47a935919ee6abd38699" @@ -3374,6 +3547,17 @@ tslib "~2.2.0" value-or-promise "1.0.6" +"@graphql-tools/wrap@^8.3.1": + version "8.3.2" + resolved "https://registry.npmjs.org/@graphql-tools/wrap/-/wrap-8.3.2.tgz#d3bcecb7529d071e4ecc4dfc75b9566e3da79d4f" + integrity sha512-7DcOBFB+Dd84x9dxSm7qS4iJONMyfLnCJb8A19vGPffpu4SMJ3sFcgwibKFu5l6mMUiigKgXna2RRgWI+02bKQ== + dependencies: + "@graphql-tools/delegate" "^8.4.2" + "@graphql-tools/schema" "^8.3.1" + "@graphql-tools/utils" "^8.5.3" + tslib "~2.3.0" + value-or-promise "1.0.11" + "@grpc/grpc-js@~1.3.0": version "1.3.2" resolved "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.3.2.tgz#eae97e6daf5abd49a7818aadeca0744dfb1ebca1" @@ -3676,12 +3860,17 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz#9df03bbd7c696a5c58885c34aa06da41c8543796" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== -"@kubernetes/client-node@^0.15.0": - version "0.15.0" - resolved "https://registry.npmjs.org/@kubernetes/client-node/-/client-node-0.15.0.tgz#aa5cfcfa9ba3055fe0b510c430d19bbda715d8e7" - integrity sha512-AnEcsWWadl5IWOzzvO/gWpTnJb1d1CzA/rbV/qK1c0fD1SOxTDPj6jFllyQ9icGDfCgNw3TafZftmuepm6z9JA== +"@juggle/resize-observer@^3.3.1": + version "3.3.1" + resolved "https://registry.npmjs.org/@juggle/resize-observer/-/resize-observer-3.3.1.tgz#b50a781709c81e10701004214340f25475a171a0" + integrity sha512-zMM9Ds+SawiUkakS7y94Ymqx+S0ORzpG3frZirN3l+UlXUmSUR7hF4wxCVqW+ei94JzV5kt0uXBcoOEAuiydrw== + +"@kubernetes/client-node@^0.16.0": + version "0.16.1" + resolved "https://registry.npmjs.org/@kubernetes/client-node/-/client-node-0.16.1.tgz#c78ef667579777c1a532983922807e228dbc9b90" + integrity sha512-/Ah+3gFSjXFeqDMGGTyYBKug44Eu2D2qowKLdiZqxCkHdSNgy+CNk6FU1Vy80WrTvGkF/CZr4az6O5AopAiJEw== dependencies: - "@types/js-yaml" "^3.12.1" + "@types/js-yaml" "^4.0.1" "@types/node" "^10.12.0" "@types/request" "^2.47.1" "@types/stream-buffers" "^3.0.3" @@ -3691,7 +3880,7 @@ byline "^5.0.0" execa "5.0.0" isomorphic-ws "^4.0.1" - js-yaml "^3.13.1" + js-yaml "^4.1.0" jsonpath-plus "^0.19.0" openid-client "^4.1.1" request "^2.88.0" @@ -4375,6 +4564,18 @@ npmlog "^4.1.2" write-file-atomic "^3.0.3" +"@lezer/common@^0.15.0", "@lezer/common@^0.15.5": + version "0.15.10" + resolved "https://registry.npmjs.org/@lezer/common/-/common-0.15.10.tgz#662da668f46244fb20bfaada67b43b3d0463b344" + integrity sha512-vlr+be73zTDoQBIknBVOh/633tmbQcjxUu9PIeVeYESeBK3V6TuBW96RRFg93Y2cyK9lglz241gOgSn452HFvA== + +"@lezer/lr@^0.15.0": + version "0.15.5" + resolved "https://registry.npmjs.org/@lezer/lr/-/lr-0.15.5.tgz#4bce44169c441d9dda7be398f5202ea65c5f1138" + integrity sha512-DEcLyhdmBxD1foQe7RegLrSlfS/XaTMGLkO5evkzHWAQKh/JnFWp7j7iNB7s2EpxzRrBCh0U+W7JDCeFhv2mng== + dependencies: + "@lezer/common" "^0.15.0" + "@manypkg/find-root@^1.1.0": version "1.1.0" resolved "https://registry.npmjs.org/@manypkg/find-root/-/find-root-1.1.0.tgz#a62d8ed1cd7e7d4c11d9d52a8397460b5d4ad29f" @@ -4672,7 +4873,12 @@ outvariant "^1.2.0" strict-event-emitter "^0.2.0" -"@n1ru4l/push-pull-async-iterable-iterator@^3.0.0": +"@n1ru4l/graphql-live-query@0.9.0": + version "0.9.0" + resolved "https://registry.npmjs.org/@n1ru4l/graphql-live-query/-/graphql-live-query-0.9.0.tgz#defaebdd31f625bee49e6745934f36312532b2bc" + integrity sha512-BTpWy1e+FxN82RnLz4x1+JcEewVdfmUhV1C6/XYD5AjS7PQp9QFF7K8bCD6gzPTr2l+prvqOyVueQhFJxB1vfg== + +"@n1ru4l/push-pull-async-iterable-iterator@^3.1.0": version "3.1.0" resolved "https://registry.npmjs.org/@n1ru4l/push-pull-async-iterable-iterator/-/push-pull-async-iterable-iterator-3.1.0.tgz#be450c97d1c7cd6af1a992d53232704454345df9" integrity sha512-K4scWxGhdQM0masHHy4gIQs2iGiLEXCrXttumknyPJqtdl4J179BjpibWSSQ1fxKdCcHgIlCTKXJU6cMM6D6Wg== @@ -5346,7 +5552,7 @@ magic-string "^0.25.7" resolve "^1.17.0" -"@rollup/plugin-json@^4.0.2": +"@rollup/plugin-json@^4.1.0": version "4.1.0" resolved "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.1.0.tgz#54e09867ae6963c593844d8bd7a9c718294496f3" integrity sha512-yfLbTdNS6amI/2OpmbiBoW12vngr5NW2jCJVZSBEz+H5KfUJZ2M7sDjk0U6GOOdCWFVScShte29o9NezJ53TPw== @@ -5365,10 +5571,10 @@ is-module "^1.0.0" resolve "^1.19.0" -"@rollup/plugin-yaml@^3.0.0": - version "3.0.0" - resolved "https://registry.npmjs.org/@rollup/plugin-yaml/-/plugin-yaml-3.0.0.tgz#632af397a6faaea10c885680c575ae01f4556c1d" - integrity sha512-nXYI3WsfG7Oq5K5k7evGQ1ZABGCPhHxMaMX4T3GRSDi9VyhkaU1+8R1RzTRFXITFJHx0QEGn8jR+P9pux5FuBQ== +"@rollup/plugin-yaml@^3.1.0": + version "3.1.0" + resolved "https://registry.npmjs.org/@rollup/plugin-yaml/-/plugin-yaml-3.1.0.tgz#03a13039ba366fc8d39a1ab94a7debacdd776c2f" + integrity sha512-61PsAXqN7YNYdg/nezK3NkqAu6e3Qu2wjHYW3r52Nx0aLi+rG7gkkIqtvxG8EtSqE2rra5CUcWBZj+v362qt9A== dependencies: "@rollup/pluginutils" "^3.1.0" js-yaml "^3.14.0" @@ -5383,10 +5589,10 @@ estree-walker "^1.0.1" picomatch "^2.2.2" -"@rollup/pluginutils@^4.1.0": - version "4.1.0" - resolved "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.1.0.tgz#0dcc61c780e39257554feb7f77207dceca13c838" - integrity sha512-TrBhfJkFxA+ER+ew2U2/fHbebhLT/l/2pRk0hfj9KusXUuRXd2v0R58AfaZK9VXDQ4TogOSEmICVrQAA3zFnHQ== +"@rollup/pluginutils@^4.1.1": + version "4.1.1" + resolved "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.1.1.tgz#1d4da86dd4eded15656a57d933fda2b9a08d47ec" + integrity sha512-clDjivHqWGXi7u+0d2r2sBi4Ie6VLEAzWMIkvJLnDmxoOhBYOTfzGbOQBA32THHm11/LiJbd01tJUpJsbshSWQ== dependencies: estree-walker "^2.0.1" picomatch "^2.2.2" @@ -5540,10 +5746,10 @@ resolved "https://registry.npmjs.org/@spotify/eslint-config-typescript/-/eslint-config-typescript-12.0.0.tgz#4c7af3f74a47668bec0c860b72e2a0103e78a138" integrity sha512-nMVll8ZkN/W8+IHn6Iz3YzCKW0qhrn3TVfyxkAr3qmXm5cex+GzyUdZEuxb8rdN2inZL6A1Il2NFfO5p/UKxog== -"@spotify/prettier-config@^11.0.0": - version "11.0.0" - resolved "https://registry.npmjs.org/@spotify/prettier-config/-/prettier-config-11.0.0.tgz#d91e0546a8c1c0f7299e2edc7e44306e9be210f6" - integrity sha512-dOI13j1uHMZkRxhZuge/ugOE7Aqcg7Nxki932lDZuXyY4G8CGxkc/66PeQ8pR4PCzThHORXo7Ptvau6bh101lQ== +"@spotify/prettier-config@^12.0.0": + version "12.0.0" + resolved "https://registry.npmjs.org/@spotify/prettier-config/-/prettier-config-12.0.0.tgz#936ca5e977cfccbccd1731ab98b1f2bf65852b5d" + integrity sha512-64WWqE40U/WwWV8iIQBseTU+b2t+SdJSyQoCLdVPCKM9uf7KOjRivVwXe4KlWoV3y7duNSGuB2UgWhkXzscVmQ== "@storybook/addon-a11y@^6.3.4": version "6.3.12" @@ -6925,9 +7131,9 @@ commander "*" "@types/compression@^1.7.0": - version "1.7.0" - resolved "https://registry.npmjs.org/@types/compression/-/compression-1.7.0.tgz#8dc2a56604873cf0dd4e746d9ae4d31ae77b2390" - integrity sha512-3LzWUM+3k3XdWOUk/RO+uSjv7YWOatYq2QADJntK1pjkk4DfVP0KrIEPDnXRJxAAGKe0VpIPRmlINLDuCedZWw== + version "1.7.2" + resolved "https://registry.npmjs.org/@types/compression/-/compression-1.7.2.tgz#7cc1cdb01b4730eea284615a68fc70a2cdfd5e71" + integrity sha512-lwEL4M/uAGWngWFLSG87ZDr2kLrbuR8p7X+QZB1OQlT+qkHsCPDVFnHPyXf4Vyl4yDDorNY+mAhosxkCvppatg== dependencies: "@types/express" "*" @@ -7094,6 +7300,13 @@ "@types/docker-modem" "*" "@types/node" "*" +"@types/dompurify@^2.1.0": + version "2.3.1" + resolved "https://registry.npmjs.org/@types/dompurify/-/dompurify-2.3.1.tgz#2934adcd31c4e6b02676f9c22f9756e5091c04dd" + integrity sha512-YJth9qa0V/E6/XPH1Jq4BC8uCMmO8V1fKWn8PCvuZcAhMn7q0ez9LW6naQT04UZzjFfAPhyRMZmI2a2rbMlEFA== + dependencies: + "@types/trusted-types" "*" + "@types/dompurify@^2.2.2": version "2.2.3" resolved "https://registry.npmjs.org/@types/dompurify/-/dompurify-2.2.3.tgz#6e89677a07902ac1b6821c345f34bd85da239b08" @@ -7397,16 +7610,16 @@ resolved "https://registry.npmjs.org/@types/js-levenshtein/-/js-levenshtein-1.1.0.tgz#9541eec4ad6e3ec5633270a3a2b55d981edc44a9" integrity sha512-14t0v1ICYRtRVcHASzes0v/O+TIeASb8aD55cWF1PidtInhFWSXcmhzhHqGjUWf9SUq1w70cvd1cWKUULubAfQ== -"@types/js-yaml@^3.12.1": - version "3.12.5" - resolved "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-3.12.5.tgz#136d5e6a57a931e1cce6f9d8126aa98a9c92a6bb" - integrity sha512-JCcp6J0GV66Y4ZMDAQCXot4xprYB+Zfd3meK9+INSJeVZwJmHAW30BBEEkPzXswMXuiyReUGOP3GxrADc9wPww== - "@types/js-yaml@^4.0.0": version "4.0.1" resolved "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.1.tgz#5544730b65a480b18ace6b6ce914e519cec2d43b" integrity sha512-xdOvNmXmrZqqPy3kuCQ+fz6wA0xU5pji9cd1nDrflWaAWtYLLGk5ykW0H6yg5TVyehHP1pfmuuSaZkhP+kspVA== +"@types/js-yaml@^4.0.1": + version "4.0.5" + resolved "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.5.tgz#738dd390a6ecc5442f35e7f03fa1431353f7e138" + integrity sha512-FhpRzf927MNQdRZP0J5DLIdTXhjLYzeUTmLAu69mnVksLH9CJY3IuSeEgbKUki7GQZm0WqDkGzyxju2EZGD2wA== + "@types/jscodeshift@^0.11.0": version "0.11.0" resolved "https://registry.npmjs.org/@types/jscodeshift/-/jscodeshift-0.11.0.tgz#7224cf1a4d0383b4fb2694ffed52f57b45c3325b" @@ -7422,7 +7635,7 @@ dependencies: "@types/json-schema" "*" -"@types/json-schema@*", "@types/json-schema@^7.0.4", "@types/json-schema@^7.0.5", "@types/json-schema@^7.0.6", "@types/json-schema@^7.0.7", "@types/json-schema@^7.0.8", "@types/json-schema@^7.0.9": +"@types/json-schema@*", "@types/json-schema@7.0.9", "@types/json-schema@^7.0.4", "@types/json-schema@^7.0.5", "@types/json-schema@^7.0.6", "@types/json-schema@^7.0.7", "@types/json-schema@^7.0.8", "@types/json-schema@^7.0.9": version "7.0.9" resolved "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz#97edc9037ea0c38585320b28964dde3b39e4660d" integrity sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ== @@ -7617,6 +7830,14 @@ "@types/node" "*" form-data "^3.0.0" +"@types/node-fetch@^2.5.12": + version "2.5.12" + resolved "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.12.tgz#8a6f779b1d4e60b7a57fb6fd48d84fb545b9cc66" + integrity sha512-MKgC4dlq4kKNa/mYrwpKfzQMB5X3ee5U6fSprkKpToBqBmX4nFZL9cW5jl6sWn+xpRJ7ypWh2yyqqr8UUCstSw== + dependencies: + "@types/node" "*" + form-data "^3.0.0" + "@types/node@*", "@types/node@>= 8", "@types/node@>=12.12.47", "@types/node@>=13.7.0", "@types/node@^14.0.10", "@types/node@^14.14.31", "@types/node@^14.14.32": version "14.17.8" resolved "https://registry.npmjs.org/@types/node/-/node-14.17.8.tgz#813b73ab7d82ac06ddfd2458b13c88459a3b319f" @@ -7875,13 +8096,6 @@ dependencies: "@types/react" "*" -"@types/react-wait@^0.3.0": - version "0.3.1" - resolved "https://registry.npmjs.org/@types/react-wait/-/react-wait-0.3.1.tgz#193cbd8fe86baa53b6f65dfa73f03d562f462a27" - integrity sha512-BS9AEjWZItDgpx6LlICcuf53M27zBFCsHx/llCbrmrt/WI7ecG2LGquCss3n8O8bwEDiTX4yYLjy8yLeIfgYTg== - dependencies: - "@types/react" "*" - "@types/react@*", "@types/react@>=16.9.0": version "16.14.18" resolved "https://registry.npmjs.org/@types/react/-/react-16.14.18.tgz#b2bcea05ee244fde92d409f91bd888ca8e54b20f" @@ -8266,6 +8480,13 @@ dependencies: "@types/node" "*" +"@types/websocket@1.0.4": + version "1.0.4" + resolved "https://registry.npmjs.org/@types/websocket/-/websocket-1.0.4.tgz#1dc497280d8049a5450854dd698ee7e6ea9e60b8" + integrity sha512-qn1LkcFEKK8RPp459jkjzsfpbsx36BBt3oC3pITYtkoBw/aVX+EZFa5j3ThCRTNpLFvIMr5dSTD4RaMdilIOpA== + dependencies: + "@types/node" "*" + "@types/whatwg-streams@^0.0.7": version "0.0.7" resolved "https://registry.npmjs.org/@types/whatwg-streams/-/whatwg-streams-0.0.7.tgz#28bfe73dc850562296367249c4b32a50db81e9d3" @@ -8285,6 +8506,13 @@ dependencies: "@types/node" "*" +"@types/ws@^8.0.0": + version "8.2.2" + resolved "https://registry.npmjs.org/@types/ws/-/ws-8.2.2.tgz#7c5be4decb19500ae6b3d563043cd407bf366c21" + integrity sha512-NOn5eIcgWLOo6qW8AcuLZ7G8PycXu0xTxxkS6Q18VWFxgPUSOwV0pBj2a/4viNZVu25i7RIB7GttdkAIUUXOOg== + dependencies: + "@types/node" "*" + "@types/xml2js@*", "@types/xml2js@^0.4.7": version "0.4.8" resolved "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.8.tgz#84c120c864a5976d0b5cf2f930a75d850fc2b03a" @@ -8759,6 +8987,11 @@ abab@^2.0.3: resolved "https://registry.npmjs.org/abab/-/abab-2.0.3.tgz#623e2075e02eb2d3f2475e49f99c91846467907a" integrity sha512-tsFzPpcttalNjFBCFMqsKYQcWxxen1pgJR56by//QwvJc4/OUS3kPOOttx2tSIfjsylB0pYu7f5D3K1RCxUnUg== +abab@^2.0.5: + version "2.0.5" + resolved "https://registry.npmjs.org/abab/-/abab-2.0.5.tgz#c0b678fb32d60fc1219c784d6a826fe385aeb79a" + integrity sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q== + abbrev@1: version "1.1.1" resolved "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" @@ -8822,6 +9055,11 @@ acorn@^7.1.1, acorn@^7.4.0: resolved "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz#feaed255973d2e77555b83dbc08851a6c63520fa" integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A== +acorn@^8.2.4: + version "8.6.0" + resolved "https://registry.npmjs.org/acorn/-/acorn-8.6.0.tgz#e3692ba0eb1a0c83eaa4f37f5fa7368dd7142895" + integrity sha512-U1riIR+lBSNi3IbxtaHOIKdH8sLFv3NYfNv8sg7ZsNhcfl4HF2++BfqqrNAxoCLQW1iiylOj76ecnaUxz+z9yw== + acorn@^8.4.1: version "8.4.1" resolved "https://registry.npmjs.org/acorn/-/acorn-8.4.1.tgz#56c36251fc7cabc7096adc18f05afe814321a28c" @@ -8832,7 +9070,7 @@ add-stream@^1.0.0: resolved "https://registry.npmjs.org/add-stream/-/add-stream-1.0.0.tgz#6a7990437ca736d5e1288db92bd3266d5f5cb2aa" integrity sha1-anmQQ3ynNtXhKI25K9MmbV9csqo= -address@1.1.2, address@^1.0.1: +address@1.1.2, address@^1.0.1, address@^1.1.2: version "1.1.2" resolved "https://registry.npmjs.org/address/-/address-1.1.2.tgz#bf1116c9c758c51b7a933d296b72c221ed9428b6" integrity sha512-aT6camzM4xEA54YVJYSqxz1kv4IHnQZRtThJJHhUMRExaU5spC7jX5ugSwTaTgJliIgs4VhZOk7htClvQ/LmRA== @@ -9418,16 +9656,16 @@ array-ify@^1.0.0: resolved "https://registry.npmjs.org/array-ify/-/array-ify-1.0.0.tgz#9e528762b4a9066ad163a6962a364418e9626ece" integrity sha1-nlKHYrSpBmrRY6aWKjZEGOlibs4= -array-includes@^3.0.3, array-includes@^3.1.1, array-includes@^3.1.2: - version "3.1.3" - resolved "https://registry.npmjs.org/array-includes/-/array-includes-3.1.3.tgz#c7f619b382ad2afaf5326cddfdc0afc61af7690a" - integrity sha512-gcem1KlBU7c9rB+Rq8/3PPKsK2kjqeEBa3bD5kkQo4nYlOHQCJqIJFqBXDEfwaRuYTT4E+FxA9xez7Gf/e3Q7A== +array-includes@^3.0.3, array-includes@^3.1.1, array-includes@^3.1.2, array-includes@^3.1.4: + version "3.1.4" + resolved "https://registry.npmjs.org/array-includes/-/array-includes-3.1.4.tgz#f5b493162c760f3539631f005ba2bb46acb45ba9" + integrity sha512-ZTNSQkmWumEbiHO2GF4GmWxYVTiQyJy2XOTa15sdQSrvKn7l+180egQMqlrMOUMCyLMD7pmyQe4mMDUT6Behrw== dependencies: call-bind "^1.0.2" define-properties "^1.1.3" - es-abstract "^1.18.0-next.2" + es-abstract "^1.19.1" get-intrinsic "^1.1.1" - is-string "^1.0.5" + is-string "^1.0.7" array-union@^1.0.1, array-union@^1.0.2: version "1.0.2" @@ -9459,15 +9697,14 @@ array.prototype.flat@^1.2.1, array.prototype.flat@^1.2.3: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" -array.prototype.flatmap@^1.2.1, array.prototype.flatmap@^1.2.3, array.prototype.flatmap@^1.2.4: - version "1.2.4" - resolved "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.2.4.tgz#94cfd47cc1556ec0747d97f7c7738c58122004c9" - integrity sha512-r9Z0zYoxqHz60vvQbWEdXIEtCwHF0yxaWfno9qzXeNHvfyl3BZqygmGzb84dsubyaXLH4husF+NFgMSdpZhk2Q== +array.prototype.flatmap@^1.2.1, array.prototype.flatmap@^1.2.4, array.prototype.flatmap@^1.2.5: + version "1.2.5" + resolved "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.2.5.tgz#908dc82d8a406930fdf38598d51e7411d18d4446" + integrity sha512-08u6rVyi1Lj7oqWbS9nUxliETrtIROT4XGTA4D/LWGten6E3ocm7cy9SIrmNHOL5XVbVuckUp3X6Xyg8/zpvHA== dependencies: call-bind "^1.0.0" define-properties "^1.1.3" - es-abstract "^1.18.0-next.1" - function-bind "^1.1.1" + es-abstract "^1.19.0" array.prototype.map@^1.0.1: version "1.0.2" @@ -10399,7 +10636,7 @@ browserslist@4.14.2: escalade "^3.0.2" node-releases "^1.1.61" -browserslist@^4.0.0, browserslist@^4.12.0, browserslist@^4.14.5, browserslist@^4.16.0, browserslist@^4.16.6: +browserslist@^4.0.0, browserslist@^4.12.0, browserslist@^4.14.5, browserslist@^4.16.0, browserslist@^4.16.5, browserslist@^4.16.6: version "4.18.1" resolved "https://registry.npmjs.org/browserslist/-/browserslist-4.18.1.tgz#60d3920f25b6860eb917c6c7b185576f4d8b017f" integrity sha512-8ScCzdpPwR2wQh8IT82CA2VgDwjHyqMovPBZSNH54+tm4Jk2pCuv90gmAdH6J84OCRWi0b4gMe6O6XPXuJnjgQ== @@ -11254,13 +11491,13 @@ code-point-at@^1.0.0: resolved "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= -codemirror-graphql@^1.0.3: - version "1.1.0" - resolved "https://registry.npmjs.org/codemirror-graphql/-/codemirror-graphql-1.1.0.tgz#dd22ddf7761efa9131fa99a70a4a85fe653484e5" - integrity sha512-bp2XUg7epL07kJcylM8VCISK6X+rFsHL2lUkPQAw2v721MVhn+80FgjMP8tiZCOfJgHn1+JgsA71L5nOHWgUdA== +codemirror-graphql@^1.2.8: + version "1.2.8" + resolved "https://registry.npmjs.org/codemirror-graphql/-/codemirror-graphql-1.2.8.tgz#4d3845d786665776eb5c44b0948bfa8f9860077f" + integrity sha512-/SlF24YNWirA8SyyaiFkrwPVIhPS/OkMNRHkL3TeZKhJIv3wuGAa90B4DYqY17MBN2QN1+RYd/71eYZD/fvj1Q== dependencies: - graphql-language-service-interface "^2.9.0" - graphql-language-service-parser "^1.10.0" + "@codemirror/stream-parser" "^0.19.2" + graphql-language-service "^4.1.1" codemirror@^5.58.2: version "5.63.3" @@ -11634,11 +11871,6 @@ constants-browserify@^1.0.0: resolved "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz#c20b96d8c617748aaf1c16021760cd27fcb8cb75" integrity sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U= -constate@^1.2.0: - version "1.3.2" - resolved "https://registry.npmjs.org/constate/-/constate-1.3.2.tgz#fa5f0fc292207f1ec21b46a5eb81f59c8b0a8b84" - integrity sha512-aaILV4vXwGTUZaQZHS5F1xBV8wRCR0Ow1505fdkS5/BPg6hbQrhNqdHL4wgxWgaDeEj43mu/Fb+LhqOKTMcrgQ== - contains-path@^0.1.0: version "0.1.0" resolved "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a" @@ -11798,7 +12030,7 @@ copy-descriptor@^0.1.0: resolved "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= -copy-to-clipboard@^3, copy-to-clipboard@^3.1.0, copy-to-clipboard@^3.2.0, copy-to-clipboard@^3.3.1: +copy-to-clipboard@^3, copy-to-clipboard@^3.2.0, copy-to-clipboard@^3.3.1: version "3.3.1" resolved "https://registry.npmjs.org/copy-to-clipboard/-/copy-to-clipboard-3.3.1.tgz#115aa1a9998ffab6196f93076ad6da3b913662ae" integrity sha512-i13qo6kIHTTpCm8/Wup+0b1mVWETvu2kIMzKoK8FpkLkFxlt0znUAHcMzox+T8sPlqtZXq3CulEjQHsYiGFJUw== @@ -11867,6 +12099,17 @@ cosmiconfig@7.0.0, cosmiconfig@^7.0.0: path-type "^4.0.0" yaml "^1.10.0" +cosmiconfig@7.0.1: + version "7.0.1" + resolved "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.1.tgz#714d756522cace867867ccb4474c5d01bbae5d6d" + integrity sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ== + dependencies: + "@types/parse-json" "^4.0.0" + import-fresh "^3.2.1" + parse-json "^5.0.0" + path-type "^4.0.0" + yaml "^1.10.0" + cosmiconfig@^6.0.0: version "6.0.0" resolved "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-6.0.0.tgz#da4fee853c52f6b1e6935f41c1a2fc50bd4a9982" @@ -11970,6 +12213,11 @@ create-require@^1.1.0: resolved "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== +cronstrue@^1.122.0: + version "1.122.0" + resolved "https://registry.npmjs.org/cronstrue/-/cronstrue-1.122.0.tgz#bd6838077b476d28f61d381398b47b8c3912a126" + integrity sha512-PFuhZd+iPQQ0AWTXIEYX+t3nFGzBrWxmTWUKJOrsGRewaBSLKZ4I1f8s2kryU75nNxgyugZgiGh2OJsCTA/XlA== + cross-env@^7.0.0: version "7.0.3" resolved "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz#865264b29677dc015ba8418918965dd232fc54cf" @@ -12020,6 +12268,16 @@ cross-spawn@^6.0.0: shebang-command "^1.2.0" which "^1.2.9" +cross-undici-fetch@^0.0.26: + version "0.0.26" + resolved "https://registry.npmjs.org/cross-undici-fetch/-/cross-undici-fetch-0.0.26.tgz#29d93d56609f4d2334f9d5333d23ef7a242842a7" + integrity sha512-aMDRrLbWr0TGXfY92stlV+XOGpskeqFmWmrKSWsnc8w6gK5LPE83NBh7O7N6gCb2xjwHcm1Yn2nBXMEVH2RBcA== + dependencies: + abort-controller "^3.0.0" + form-data "^4.0.0" + node-fetch "^2.6.5" + undici "^4.9.3" + crypto-browserify@^3.11.0: version "3.12.0" resolved "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz#396cf9f3137f03e4b8e532c58f698254e00f80ec" @@ -12284,7 +12542,7 @@ cssom@~0.3.6: resolved "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz#9f1276f5b2b463f2114d3f2c75250af8c1a36f4a" integrity sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg== -cssstyle@^2.2.0: +cssstyle@^2.2.0, cssstyle@^2.3.0: version "2.3.0" resolved "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz#ff665a0ddbdc31864b09647f34163443d90b0852" integrity sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A== @@ -12751,6 +13009,11 @@ decimal.js@^10.2.0: resolved "https://registry.npmjs.org/decimal.js/-/decimal.js-10.2.0.tgz#39466113a9e036111d02f82489b5fd6b0b5ed231" integrity sha512-vDPw+rDgn3bZe1+F/pyEwb1oMG2XTlRVgAa6B4KccTEpYgF8w6eQllVbQcfIJnZyvzFtFpxnpGtx8dd7DJp/Rw== +decimal.js@^10.2.1: + version "10.3.1" + resolved "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz#d8c3a444a9c6774ba60ca6ad7261c3a94fd5e783" + integrity sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ== + decode-uri-component@^0.2.0: version "0.2.0" resolved "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" @@ -12976,7 +13239,7 @@ detect-node@^2.0.4: resolved "https://registry.npmjs.org/detect-node/-/detect-node-2.0.4.tgz#014ee8f8f669c5c58023da64b8179c083a28c46c" integrity sha512-ZIzRpLJrOj7jjP2miAtgqIfmzbxa4ZOr5jJc601zklsfEx9oTzmmj2nVpIPRpNlRTIh8lc1kyViIY7BWSGNmKw== -detect-port-alt@1.1.6: +detect-port-alt@1.1.6, detect-port-alt@^1.1.6: version "1.1.6" resolved "https://registry.npmjs.org/detect-port-alt/-/detect-port-alt-1.1.6.tgz#24707deabe932d4a3cf621302027c2b266568275" integrity sha512-5tQykt+LqfJFBEYaDITx7S7cR7mJ/zQmLXZ2qt5w04ainYZw6tBf9dBunMjVeVOdYVRUzUOE4HkY5J7+uttb5Q== @@ -13229,7 +13492,7 @@ domhandler@^4.2.0: dependencies: domelementtype "^2.2.0" -dompurify@^2.1.1, dompurify@^2.2.9: +dompurify@^2.2.7, dompurify@^2.2.9: version "2.3.3" resolved "https://registry.npmjs.org/dompurify/-/dompurify-2.3.3.tgz#c1af3eb88be47324432964d8abc75cf4b98d634c" integrity sha512-dqnqRkPMAjOZE0FogZ+ceJNM2dZ3V/yNOuFB7+39qpO93hHhfRpHw3heYQC7DPK9FqbQTfBKUJhiSfz4MvXYwg== @@ -13548,11 +13811,6 @@ entities@^2.0.0, entities@~2.1.0: resolved "https://registry.npmjs.org/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5" integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w== -entities@~2.0.0: - version "2.0.0" - resolved "https://registry.npmjs.org/entities/-/entities-2.0.0.tgz#68d6084cab1b079767540d80e56a39b423e4abf4" - integrity sha512-D9f7V0JSRwIxlRI2mjMqufDrRDnx8p+eEOz7aUM9SuvF8gsBzra0/6tbjl1m8eQHrZlYj6PxqE00hZ1SAIKPLw== - env-paths@^2.2.0: version "2.2.0" resolved "https://registry.npmjs.org/env-paths/-/env-paths-2.2.0.tgz#cdca557dc009152917d6166e2febe1f039685e43" @@ -13599,7 +13857,7 @@ error@^10.4.0: resolved "https://registry.npmjs.org/error/-/error-10.4.0.tgz#6fcf0fd64bceb1e750f8ed9a3dd880f00e46a487" integrity sha512-YxIFEJuhgcICugOUvRx5th0UM+ActZ9sjY0QJmeVwsQdvosZ7kYzc9QqS0Da3R5iUmgU5meGIxh0xBeZpMVeLw== -es-abstract@^1.17.0, es-abstract@^1.17.0-next.0, es-abstract@^1.17.0-next.1, es-abstract@^1.17.2, es-abstract@^1.17.4, es-abstract@^1.17.5, es-abstract@^1.18.0-next.1, es-abstract@^1.18.0-next.2: +es-abstract@^1.17.0-next.0, es-abstract@^1.17.0-next.1, es-abstract@^1.17.2, es-abstract@^1.17.4, es-abstract@^1.18.0-next.1, es-abstract@^1.18.0-next.2: version "1.18.0" resolved "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz#ab80b359eecb7ede4c298000390bc5ac3ec7b5a4" integrity sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw== @@ -13621,6 +13879,32 @@ es-abstract@^1.17.0, es-abstract@^1.17.0-next.0, es-abstract@^1.17.0-next.1, es- string.prototype.trimstart "^1.0.4" unbox-primitive "^1.0.0" +es-abstract@^1.19.0, es-abstract@^1.19.1: + version "1.19.1" + resolved "https://registry.npmjs.org/es-abstract/-/es-abstract-1.19.1.tgz#d4885796876916959de78edaa0df456627115ec3" + integrity sha512-2vJ6tjA/UfqLm2MPs7jxVybLoB8i1t1Jd9R3kISld20sIxPcTbLuggQOUxeWeAvIUkduv/CfMjuh4WmiXr2v9w== + dependencies: + call-bind "^1.0.2" + es-to-primitive "^1.2.1" + function-bind "^1.1.1" + get-intrinsic "^1.1.1" + get-symbol-description "^1.0.0" + has "^1.0.3" + has-symbols "^1.0.2" + internal-slot "^1.0.3" + is-callable "^1.2.4" + is-negative-zero "^2.0.1" + is-regex "^1.1.4" + is-shared-array-buffer "^1.0.1" + is-string "^1.0.7" + is-weakref "^1.0.1" + object-inspect "^1.11.0" + object-keys "^1.1.1" + object.assign "^4.1.2" + string.prototype.trimend "^1.0.4" + string.prototype.trimstart "^1.0.4" + unbox-primitive "^1.0.1" + es-array-method-boxes-properly@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/es-array-method-boxes-properly/-/es-array-method-boxes-properly-1.0.0.tgz#873f3e84418de4ee19c5be752990b2e44718d09e" @@ -13699,10 +13983,113 @@ es6-weak-map@^2.0.3: es6-iterator "^2.0.3" es6-symbol "^3.1.1" -esbuild@^0.8.56: - version "0.8.57" - resolved "https://registry.npmjs.org/esbuild/-/esbuild-0.8.57.tgz#a42d02bc2b57c70bcd0ef897fe244766bb6dd926" - integrity sha512-j02SFrUwFTRUqiY0Kjplwjm1psuzO1d6AjaXKuOR9hrY0HuPsT6sV42B6myW34h1q4CRy+Y3g4RU/cGJeI/nNA== +esbuild-android-arm64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.14.1.tgz#470b99c1c4b49f33fd0a20ed153b15008173fd63" + integrity sha512-elQd3hTg93nU2GQ5PPCDAFe5+utxZX96RG8RixqIPxf8pzmyIzcpKG76L/9FabPf3LT1z+nLF1sajCU8eVRDyg== + +esbuild-darwin-64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.14.1.tgz#135f48f299f2ce3eb3ca1b1f3ec03d81108ab79e" + integrity sha512-PR3HZgbPRwsQbbOR1fJrfkt/Cs0JDyI3yzOKg2PPWk0H1AseZDBqPUY9b/0+BIjFwA5Jz/aAiq832hppsuJtNw== + +esbuild-darwin-arm64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.1.tgz#7117a857bac99ece28ebba859a47dce47f565f9f" + integrity sha512-/fiSSOkOEa3co6yYtwgXouz8jZrG0qnXPEKiktFf2BQE8NON3ARTw43ZegaH+xMRFNgYBJEOOZIdzI3sIFEAxw== + +esbuild-freebsd-64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.1.tgz#2b7ca5ec572f2800b1ec88988affc4482c5ac4b7" + integrity sha512-ZJV+nfa8E8PdXnRc05PO3YMfgSj7Ko+kdHyGDE6OaNo1cO8ZyfacqLaWkY35shDDaeacklhD8ZR4qq5nbJKX1A== + +esbuild-freebsd-arm64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.1.tgz#63e8b77643ea8270d878cfab7dd9201a114f20fb" + integrity sha512-6N9zTD+SecJr2g9Ohl9C10WIk5FpQ+52bNamRy0sJoHwP31G5ObzKzq8jAtg1Jeggpu6P8auz3P/UL+3YioSwQ== + +esbuild-linux-32@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.14.1.tgz#f00ae7f12d2abc0dc37e2a7e7c7c29764da87093" + integrity sha512-RtPgE6e7WefbAxRjVryisKFJ0nUwR2DMjwmYW/a1a0F1+Ge6FR+RqvgiY0DrM9TtxSUU0eryDXNF4n3UfxX3mg== + +esbuild-linux-64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.1.tgz#2ee9dd76be1185abb1e967052e3b6ab16a1d3da4" + integrity sha512-JpxM0ar6Z+2v3vfFrxP7bFb8Wzb6gcGL9MxRqAJplDfGnee8HbfPge6svaazXeX9XJceeEqwxwWGB0qyCcxo7A== + +esbuild-linux-arm64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.1.tgz#601e855b78e0636e120771296b43eb4f7d68a314" + integrity sha512-cFbeZf171bIf+PPLlQDBzagK85lCCxxVdMV1IVUA96Y3kvEgqcy2n9mha+QE1M/T+lIOPDsmLRgH1XqMFwLTSg== + +esbuild-linux-arm@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.14.1.tgz#c0d364a20f12a653bdd2f41436788b99502dc287" + integrity sha512-eBRHexCijAYWzcvQLGHxyxIlYOkYhXvcb/O7HvzJfCAVWCnTx9TxxYJ3UppBC6dDFbAq4HwKhskvmesQdKMeBg== + +esbuild-linux-mips64le@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.1.tgz#a5f6e9c6e7950a3fad08bb3653bc3f5d71b4e249" + integrity sha512-UGb+sqHkL7wOQFLH0RoFhcRAlJNqbqs6GtJd1It5jJ2juOGqAkCv8V12aGDX9oRB6a+Om7cdHcH+6AMZ+qlaww== + +esbuild-linux-ppc64le@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.1.tgz#762cec24cf5afeee3f805a4679a3f5e29702173a" + integrity sha512-LIHGkGdy9wYlmkkoVHm6feWhkoi4VBXDiEVyNjXEhlzsBcP/CaRy+B8IJulzaU1ALLiGcsCQ2MC5UbFn/iTvmA== + +esbuild-netbsd-64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.1.tgz#66ec7ac0b3eeb84f8c1ac27eecf16f59d93706a8" + integrity sha512-TWc1QIgtPwaK5nC1GT2ASTuy/CJhNKHN4h5PJRP1186VfI+k2uvXakS7bqO/M26F6jAMy8jDeCtilacqpwsvfA== + +esbuild-openbsd-64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.1.tgz#7515049bc7032ca2fb6811dc260f5ec9e1d9fe65" + integrity sha512-Z9/Zb77K+pK9s7mAsvwS56K8tCbLvNZ9UI4QVJSYqDgOmmDJOBT4owWnCqZ5cJI+2y4/F9KwCpFFTNUdPglPKA== + +esbuild-sunos-64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.14.1.tgz#795f6bc7ce8c5177afb65f8d6c161a02f0c3e125" + integrity sha512-c4sF8146kNW8529wfkB6vO0ZqPgokyS2hORqKa4p/QKZdp+xrF2NPmvX5aN+Zt14oe6wVZuhYo6LGv7V4Gg04g== + +esbuild-windows-32@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.14.1.tgz#ffffa6378733eeaa23ed5cfe539e2fbe1e635ef6" + integrity sha512-XP8yElaJtLGGjH7D72t5IWtP0jmc1Jqm4IjQARB17l0LTJO/n+N2X64rDWePJv6qimYxa5p2vTjkZc5v+YZTSQ== + +esbuild-windows-64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.14.1.tgz#46f3b4a90f937a8ad6456cd70478ebfc6771814f" + integrity sha512-fe+ShdyfiuGcCEdVKW//6MaM4MwikiWBWSBn8mebNAbjRqicH0injDOFVI7aUovAfrEt7+FGkf402s//hi0BVg== + +esbuild-windows-arm64@0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.1.tgz#c7067389d28139e6a18db1996178c3a3e07a22b3" + integrity sha512-wBVakhcIzQ3NZ33DFM6TjIObXPHaXOsqzvPwefXHvwBSC/N/e/g6fBeM7N/Moj3AmxLjKaB+vePvTGdxk6RPCg== + +esbuild@^0.14.1: + version "0.14.1" + resolved "https://registry.npmjs.org/esbuild/-/esbuild-0.14.1.tgz#b834da3aa5858073205a6d4f948ffde0d650e4e3" + integrity sha512-J/LhUwELcmz0+CJfiaKzu7Rnj9ffWFLvMx+dKvdOfg+fQmoP6q9glla26LCm9BxpnPUjXChHeubLiMlKab/PYg== + optionalDependencies: + esbuild-android-arm64 "0.14.1" + esbuild-darwin-64 "0.14.1" + esbuild-darwin-arm64 "0.14.1" + esbuild-freebsd-64 "0.14.1" + esbuild-freebsd-arm64 "0.14.1" + esbuild-linux-32 "0.14.1" + esbuild-linux-64 "0.14.1" + esbuild-linux-arm "0.14.1" + esbuild-linux-arm64 "0.14.1" + esbuild-linux-mips64le "0.14.1" + esbuild-linux-ppc64le "0.14.1" + esbuild-netbsd-64 "0.14.1" + esbuild-openbsd-64 "0.14.1" + esbuild-sunos-64 "0.14.1" + esbuild-windows-32 "0.14.1" + esbuild-windows-64 "0.14.1" + esbuild-windows-arm64 "0.14.1" escalade@^3.0.2, escalade@^3.1.1: version "3.1.1" @@ -13751,6 +14138,18 @@ escodegen@^1.14.1: optionalDependencies: source-map "~0.6.1" +escodegen@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz#5e32b12833e8aa8fa35e1bf0befa89380484c7dd" + integrity sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw== + dependencies: + esprima "^4.0.1" + estraverse "^5.2.0" + esutils "^2.0.2" + optionator "^0.8.1" + optionalDependencies: + source-map "~0.6.1" + eslint-config-prettier@^8.3.0: version "8.3.0" resolved "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz#f7471b20b6fe8a9a9254cc684454202886a2dd7a" @@ -13871,21 +14270,24 @@ eslint-plugin-react-hooks@^4.0.0: integrity sha512-623WEiZJqxR7VdxFCKLI6d6LLpwJkGPYKODnkH3D7WpOG5KM8yWueBd8TLsNAetEJNF5iJmolaAKO3F8yzyVBQ== eslint-plugin-react@^7.12.4: - version "7.22.0" - resolved "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.22.0.tgz#3d1c542d1d3169c45421c1215d9470e341707269" - integrity sha512-p30tuX3VS+NWv9nQot9xIGAHBXR0+xJVaZriEsHoJrASGCJZDJ8JLNM0YqKqI0AKm6Uxaa1VUHoNEibxRCMQHA== + version "7.27.1" + resolved "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.27.1.tgz#469202442506616f77a854d91babaae1ec174b45" + integrity sha512-meyunDjMMYeWr/4EBLTV1op3iSG3mjT/pz5gti38UzfM4OPpNc2m0t2xvKCOMU5D6FSdd34BIMFOvQbW+i8GAA== dependencies: - array-includes "^3.1.1" - array.prototype.flatmap "^1.2.3" + array-includes "^3.1.4" + array.prototype.flatmap "^1.2.5" doctrine "^2.1.0" - has "^1.0.3" + estraverse "^5.3.0" jsx-ast-utils "^2.4.1 || ^3.0.0" - object.entries "^1.1.2" - object.fromentries "^2.0.2" - object.values "^1.1.1" + minimatch "^3.0.4" + object.entries "^1.1.5" + object.fromentries "^2.0.5" + object.hasown "^1.1.0" + object.values "^1.1.5" prop-types "^15.7.2" - resolve "^1.18.1" - string.prototype.matchall "^4.0.2" + resolve "^2.0.0-next.3" + semver "^6.3.0" + string.prototype.matchall "^4.0.6" eslint-scope@5.1.1, eslint-scope@^5.1.1: version "5.1.1" @@ -14011,10 +14413,10 @@ estraverse@^4.1.1, estraverse@^4.2.0: resolved "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== -estraverse@^5.1.0, estraverse@^5.2.0: - version "5.2.0" - resolved "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz#307df42547e6cc7324d3cf03c155d5cdb8c53880" - integrity sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ== +estraverse@^5.1.0, estraverse@^5.2.0, estraverse@^5.3.0: + version "5.3.0" + resolved "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" + integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== estree-walker@^0.6.1: version "0.6.1" @@ -14256,9 +14658,9 @@ expect@^26.6.2: jest-regex-util "^26.0.0" express-prom-bundle@^6.3.6: - version "6.3.6" - resolved "https://registry.npmjs.org/express-prom-bundle/-/express-prom-bundle-6.3.6.tgz#c8da1c1024edfcc54953c365991aca57ffd0cfda" - integrity sha512-IRsTRCEKCVCHEriQlZ1FuutjEFc89KASsveXh+1HcGEnuZKiAC4LugxrsGEIdySqYvqOYSr2SWHJ6L8/BK2SHA== + version "6.4.1" + resolved "https://registry.npmjs.org/express-prom-bundle/-/express-prom-bundle-6.4.1.tgz#a688050b9e090f6969825c33143106d3e0e5a70e" + integrity sha512-Sg0svLQe/SS5z1tHDTVfZVjNumobiDlXM0jmemt5Dm9K6BX8z9yCwEr93zbko6fNMR4zKav77iPfxUWi6gAjNA== dependencies: on-finished "^2.3.0" url-value-parser "^2.0.0" @@ -14384,6 +14786,11 @@ extglob@^2.0.4: snapdragon "^0.8.1" to-regex "^3.0.1" +extract-files@11.0.0: + version "11.0.0" + resolved "https://registry.npmjs.org/extract-files/-/extract-files-11.0.0.tgz#b72d428712f787eef1f5193aff8ab5351ca8469a" + integrity sha512-FuoE1qtbJ4bBVvv94CC7s0oTnKUGvQs+Rjf1L2SJFfS+HTVVjhPFtehPdQ0JiGPqVNfSSZvL5yzHHQq2Z4WNhQ== + extract-files@9.0.0, extract-files@^9.0.0: version "9.0.0" resolved "https://registry.npmjs.org/extract-files/-/extract-files-9.0.0.tgz#8a7744f2437f81f5ed3250ed9f1550de902fe54a" @@ -14651,6 +15058,11 @@ filesize@6.1.0: resolved "https://registry.npmjs.org/filesize/-/filesize-6.1.0.tgz#e81bdaa780e2451d714d71c0d7a4f3238d37ad00" integrity sha512-LpCHtPQ3sFx67z+uh2HnSyWSLLu5Jxo21795uRDuar/EOuYWXib5EmPaGIBuSnRqH2IODiKA2k5re/K9OnN/Yg== +filesize@^6.1.0: + version "6.4.0" + resolved "https://registry.npmjs.org/filesize/-/filesize-6.4.0.tgz#914f50471dd66fdca3cefe628bd0cde4ef769bcd" + integrity sha512-mjFIpOHC4jbfcTfoh4rkWpI31mF7viw9ikj/JyLoKzqlwG/YsefKfvYlYhdYdg/9mtK2z1AzgN/0LvVQ3zdlSQ== + fill-range@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" @@ -14885,6 +15297,25 @@ fork-ts-checker-webpack-plugin@^6.0.4: semver "^7.3.2" tapable "^1.0.0" +fork-ts-checker-webpack-plugin@^6.0.5: + version "6.4.2" + resolved "https://registry.npmjs.org/fork-ts-checker-webpack-plugin/-/fork-ts-checker-webpack-plugin-6.4.2.tgz#6d307fb4072ce4abe4d56a89c8ef060066f33d81" + integrity sha512-EqtzzRdx2mldr0KEydSN9jaNrf419gMpwkloumG6K/S7jtJc9Fl7wMJ+y+o7DLLGMMU/kouYr06agTD/YkxzIQ== + dependencies: + "@babel/code-frame" "^7.8.3" + "@types/json-schema" "^7.0.5" + chalk "^4.1.0" + chokidar "^3.4.2" + cosmiconfig "^6.0.0" + deepmerge "^4.2.2" + fs-extra "^9.0.0" + glob "^7.1.6" + memfs "^3.1.2" + minimatch "^3.0.4" + schema-utils "2.7.0" + semver "^7.3.2" + tapable "^1.0.0" + form-data-encoder@^1.4.3: version "1.6.0" resolved "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.6.0.tgz#9dd1f479836c1b1b47201667c68f8daafa800943" @@ -15074,7 +15505,7 @@ fsevents@^1.2.7: bindings "^1.5.0" nan "^2.12.1" -fsevents@^2.1.2, fsevents@~2.3.1, fsevents@~2.3.2: +fsevents@^2.1.2, fsevents@~2.3.2: version "2.3.2" resolved "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== @@ -15198,7 +15629,7 @@ get-caller-file@^2.0.1, get-caller-file@^2.0.5: resolved "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== -get-intrinsic@^1.0.2, get-intrinsic@^1.1.1: +get-intrinsic@^1.0.2, get-intrinsic@^1.1.0, get-intrinsic@^1.1.1: version "1.1.1" resolved "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz#15f59f376f855c446963948f0d24cd3637b4abc6" integrity sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q== @@ -15270,6 +15701,14 @@ get-stream@^6.0.0: resolved "https://registry.npmjs.org/get-stream/-/get-stream-6.0.0.tgz#3e0012cb6827319da2706e601a1583e8629a6718" integrity sha512-A1B3Bh1UmL0bidM/YX2NsCOTnGJePL9rO/M+Mw3m9f2gUpfokS0hi5Eah0WSUEWZdZhIZtMjkIYS7mDfOqNHbg== +get-symbol-description@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz#7fdb81c900101fbd564dd5f1a30af5aadc1e58d6" + integrity sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw== + dependencies: + call-bind "^1.0.2" + get-intrinsic "^1.1.1" + get-value@^2.0.3, get-value@^2.0.6: version "2.0.6" resolved "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" @@ -15463,7 +15902,7 @@ global-dirs@^3.0.0: dependencies: ini "2.0.0" -global-modules@2.0.0: +global-modules@2.0.0, global-modules@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/global-modules/-/global-modules-2.0.0.tgz#997605ad2345f27f51539bea26574421215c7780" integrity sha512-NGbfmJBp9x8IxyJSd1P+otYK8vonoJactOogrVfFRIAEY1ukil8RSKDz2Yo7wh1oihl51l/r6W4epkeKJHqL8A== @@ -15698,19 +16137,19 @@ grapheme-splitter@^1.0.4: resolved "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz#9cf3a665c6247479896834af35cf1dbb4400767e" integrity sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ== -graphiql@^1.0.0-alpha.10: - version "1.4.7" - resolved "https://registry.npmjs.org/graphiql/-/graphiql-1.4.7.tgz#6a35acf0786d7518fbb986b75bf0a3d752c19c1a" - integrity sha512-oHsBTzdWTbRJhqazbjrC6wY7YInViErAeXLqetCxdFFu2Zk5FV3V3rs7KPrCyr7kM6lW0nfXMzIfKuIgxAqx7g== +graphiql@^1.5.12: + version "1.5.13" + resolved "https://registry.npmjs.org/graphiql/-/graphiql-1.5.13.tgz#7706c56504213598641e8300a612a7dccaba95d5" + integrity sha512-lfG7FZzjDb4jwAP5mU+IiYvkTcZ/OygbIlk6JJrB0CPBqMl4k/3dEaZFmyKjmy54xTo8bkiH28VgpcF8VPc1eg== dependencies: - "@graphiql/toolkit" "^0.3.2" + "@graphiql/toolkit" "^0.4.2" codemirror "^5.58.2" - codemirror-graphql "^1.0.3" + codemirror-graphql "^1.2.8" copy-to-clipboard "^3.2.0" dset "^3.1.0" entities "^2.0.0" escape-html "^1.0.3" - graphql-language-service "^3.1.6" + graphql-language-service "^4.1.1" markdown-it "^12.2.0" graphlib@^2.1.8: @@ -15737,6 +16176,23 @@ graphql-config@^3.0.2, graphql-config@^3.3.0: minimatch "3.0.4" string-env-interpolation "1.0.1" +graphql-config@^4.1.0: + version "4.1.0" + resolved "https://registry.npmjs.org/graphql-config/-/graphql-config-4.1.0.tgz#a3b28d3fb537952ebeb69c75e4430605a10695e3" + integrity sha512-Myqay6pmdcmX3KqoH+bMbeKZ1cTODpHS2CxF1ZzNnfTE+YUpGTcp01bOw6LpzamRb0T/WTYtGFbZeXGo9Hab2Q== + dependencies: + "@endemolshinegroup/cosmiconfig-typescript-loader" "3.0.2" + "@graphql-tools/graphql-file-loader" "^7.3.2" + "@graphql-tools/json-file-loader" "^7.3.2" + "@graphql-tools/load" "^7.4.1" + "@graphql-tools/merge" "^8.2.1" + "@graphql-tools/url-loader" "^7.4.2" + "@graphql-tools/utils" "^8.5.1" + cosmiconfig "7.0.1" + cosmiconfig-toml-loader "1.0.0" + minimatch "3.0.4" + string-env-interpolation "1.0.1" + graphql-extensions@^0.15.0: version "0.15.0" resolved "https://registry.npmjs.org/graphql-extensions/-/graphql-extensions-0.15.0.tgz#3f291f9274876b0c289fa4061909a12678bd9817" @@ -15746,63 +16202,51 @@ graphql-extensions@^0.15.0: apollo-server-env "^3.1.0" apollo-server-types "^0.9.0" -graphql-language-service-interface@^2.9.0: - version "2.9.1" - resolved "https://registry.npmjs.org/graphql-language-service-interface/-/graphql-language-service-interface-2.9.1.tgz#be0b11b06b78730ea9d250e0e2290e7ed9c8d283" - integrity sha512-yGsE67fxJBXxY82+rLDMvUpmzpOUM8XFB+k+xOTUyABWs27osKaoGiuDDXAVGg1adhm+cpunWbipe763ZJkAVA== +graphql-language-service-interface@^2.10.1: + version "2.10.1" + resolved "https://registry.npmjs.org/graphql-language-service-interface/-/graphql-language-service-interface-2.10.1.tgz#0f81a3da576bad61da878b59c228901236358426" + integrity sha512-2n/nrt0QD8UnxzDKKHWomYuLK9uxGxyPztA6wI24Kng8Iw7jQk/doIti63z4xPKNi4CtbumSjk1TRYUZ/bgViw== dependencies: - graphql-language-service-parser "^1.10.0" - graphql-language-service-types "^1.8.3" - graphql-language-service-utils "^2.6.0" + graphql-config "^4.1.0" + graphql-language-service-parser "^1.10.4" + graphql-language-service-types "^1.8.7" + graphql-language-service-utils "^2.7.1" vscode-languageserver-types "^3.15.1" -graphql-language-service-parser@^1.10.0: - version "1.10.0" - resolved "https://registry.npmjs.org/graphql-language-service-parser/-/graphql-language-service-parser-1.10.0.tgz#116f4be849754f6afb4c196421a43fe96d87b278" - integrity sha512-cLExv0EjqT2hsKdwVTPmKU6eMfjZAjxqywgCPnWD48eJn6tyuePMyG7ye+jpX1PRPPx/cDHfFJGf8sUclchvng== +graphql-language-service-parser@^1.10.4: + version "1.10.4" + resolved "https://registry.npmjs.org/graphql-language-service-parser/-/graphql-language-service-parser-1.10.4.tgz#b2979deefc5c0df571dacd409b2d5fbf1cdf7a9d" + integrity sha512-duDE+0aeKLFVrb9Kf28U84ZEHhHcvTjWIT6dJbIAQJWBaDoht0D4BK9EIhd94I3DtKRc1JCJb2+70y1lvP/hiA== dependencies: - graphql-language-service-types "^1.8.0" + graphql-language-service-types "^1.8.7" -graphql-language-service-types@^1.8.0: - version "1.8.1" - resolved "https://registry.npmjs.org/graphql-language-service-types/-/graphql-language-service-types-1.8.1.tgz#963810010924f2b5eaea415d5b8eb0b7d42c479b" - integrity sha512-IpYS0mEHEmRsFlq+loWCpSYYYizAID7Alri6GoFN1QqUdux+8rp1Tkp2NGsGDpDmm3Dbz5ojmJWzNWQGpuwveA== - -graphql-language-service-types@^1.8.2: - version "1.8.2" - resolved "https://registry.npmjs.org/graphql-language-service-types/-/graphql-language-service-types-1.8.2.tgz#50ae56f69cc24fcfc3daa129b68b0eb9421e8578" - integrity sha512-Sj07RHnMwAhEvAt7Jdt1l/x56ZpoNh+V6g+T58CF6GiYqI5l4vXqqRB4d4xHDcNQX98GpJfnf3o8BqPgP3C5Sw== - -graphql-language-service-types@^1.8.3: - version "1.8.3" - resolved "https://registry.npmjs.org/graphql-language-service-types/-/graphql-language-service-types-1.8.3.tgz#d7d688d74c122c4d9cc4cceae761a1f2a3c396a1" - integrity sha512-m+RHnlGkKDcesW/gC4M7I2pSmWJB84uWS6LtnjplO/07JN312nJCJYCwV/DBny2m1fmSOxN7H/o+JW0l56KwBA== - -graphql-language-service-utils@^2.5.3: - version "2.5.3" - resolved "https://registry.npmjs.org/graphql-language-service-utils/-/graphql-language-service-utils-2.5.3.tgz#185f4f65cf8c010871eb9405452a3a0bfdf88748" - integrity sha512-ydevEZ0AgzEKQF3hiCbLXuS0o7189Ww/T30WtCKCLaRHDYk9Yyb2PZWdhSTWLxYZTaX2TccV6NtFWvzIC7UP3g== +graphql-language-service-types@^1.8.7: + version "1.8.7" + resolved "https://registry.npmjs.org/graphql-language-service-types/-/graphql-language-service-types-1.8.7.tgz#f5e909e6d9334ea2d8d1f7281b695b6f5602c07f" + integrity sha512-LP/Mx0nFBshYEyD0Ny6EVGfacJAGVx+qXtlJP4hLzUdBNOGimfDNtMVIdZANBXHXcM41MDgMHTnyEx2g6/Ttbw== dependencies: - graphql-language-service-types "^1.8.0" + graphql-config "^4.1.0" + vscode-languageserver-types "^3.15.1" + +graphql-language-service-utils@^2.7.1: + version "2.7.1" + resolved "https://registry.npmjs.org/graphql-language-service-utils/-/graphql-language-service-utils-2.7.1.tgz#c97c8d744a761480aba7e03e4a42adf28b6fce39" + integrity sha512-Wci5MbrQj+6d7rfvbORrA9uDlfMysBWYaG49ST5TKylNaXYFf3ixFOa74iM1KtM9eidosUbI3E1JlWi0JaidJA== + dependencies: + "@types/json-schema" "7.0.9" + graphql-language-service-types "^1.8.7" nullthrows "^1.0.0" -graphql-language-service-utils@^2.6.0: - version "2.6.0" - resolved "https://registry.npmjs.org/graphql-language-service-utils/-/graphql-language-service-utils-2.6.0.tgz#d04904641248167ccbb381d8705ba97daa784954" - integrity sha512-idqwmbREixhDuQMcYp8WH0btQT02xZny8MO/HduNTVjnPrmTYnZUbpZ9AejdflmaKoS0o8nNvgXQ0GpIOzbG5g== +graphql-language-service@^4.1.1: + version "4.1.1" + resolved "https://registry.npmjs.org/graphql-language-service/-/graphql-language-service-4.1.1.tgz#8093655c23af6a3f3eee3f92e6a5b0a3e2a21d70" + integrity sha512-7XP+XSzTnpnmh+EYbofnK/YdSaI7/mj7bS8ffP3A1UQtNBLb9mUErgYju6VegcV6Df0bJObLG+XxSBSlgV4kXQ== dependencies: - graphql-language-service-types "^1.8.3" - nullthrows "^1.0.0" - -graphql-language-service@^3.1.6: - version "3.2.0" - resolved "https://registry.npmjs.org/graphql-language-service/-/graphql-language-service-3.2.0.tgz#e0eb6d5dea2cab92549a253d7a6b4fa0cce178b7" - integrity sha512-xM5Ua5p7ttG/oEaDy2zk35FP2O2I9qD2N0DOrjCDUVDRC06FNDG+/CvF4qX9+i8DWOI65xch5vAhSQEfS2jFsA== - dependencies: - graphql-language-service-interface "^2.9.0" - graphql-language-service-parser "^1.10.0" - graphql-language-service-types "^1.8.2" - graphql-language-service-utils "^2.5.3" + graphql-language-service-interface "^2.10.1" + graphql-language-service-parser "^1.10.4" + graphql-language-service-types "^1.8.7" + graphql-language-service-utils "^2.7.1" + picomatch "^2.3.0" graphql-request@^3.3.0: version "3.4.0" @@ -15813,6 +16257,11 @@ graphql-request@^3.3.0: extract-files "^9.0.0" form-data "^3.0.0" +graphql-sse@^1.0.1: + version "1.0.6" + resolved "https://registry.npmjs.org/graphql-sse/-/graphql-sse-1.0.6.tgz#4f98e0a06f2020542ed054399116108491263224" + integrity sha512-y2mVBN2KwNrzxX2KBncQ6kzc6JWvecxuBernrl0j65hsr6MAS3+Yn8PTFSOgRmtolxugepxveyZVQEuaNEbw3w== + graphql-subscriptions@^1.0.0: version "1.1.0" resolved "https://registry.npmjs.org/graphql-subscriptions/-/graphql-subscriptions-1.1.0.tgz#5f2fa4233eda44cf7570526adfcf3c16937aef11" @@ -15862,15 +16311,10 @@ graphql-ws@^4.4.1: resolved "https://registry.npmjs.org/graphql-ws/-/graphql-ws-4.7.0.tgz#b323fbf35a3736eed85dac24c0054d6d10c93e62" integrity sha512-Md8SsmC9ZlsogFPd3Ot8HbIAAqsHh8Xoq7j4AmcIat1Bh6k91tjVyQvA0Au1/BolXSYq+RDvib6rATU2Hcf1Xw== -graphql-ws@^4.9.0: - version "4.9.0" - resolved "https://registry.npmjs.org/graphql-ws/-/graphql-ws-4.9.0.tgz#5cfd8bb490b35e86583d8322f5d5d099c26e365c" - integrity sha512-sHkK9+lUm20/BGawNEWNtVAeJzhZeBg21VmvmLoT5NdGVeZWv5PdIhkcayQIAgjSyyQ17WMKmbDijIPG2On+Ag== - -graphql@15.5.0: - version "15.5.0" - resolved "https://registry.npmjs.org/graphql/-/graphql-15.5.0.tgz#39d19494dbe69d1ea719915b578bf920344a69d5" - integrity sha512-OmaM7y0kaK31NKG31q4YbD2beNYa6jBBKtMFT6gLYJljHLJr42IqJ8KX08u3Li/0ifzTU5HjmoOOrwa5BRLeDA== +graphql-ws@^5.4.1: + version "5.5.5" + resolved "https://registry.npmjs.org/graphql-ws/-/graphql-ws-5.5.5.tgz#f375486d3f196e2a2527b503644693ae3a8670a9" + integrity sha512-hvyIS71vs4Tu/yUYHPvGXsTgo0t3arU820+lT5VjZS2go0ewp2LqyCgxEN56CzOG7Iys52eRhHBiD1gGRdiQtw== graphql@^15.3.0: version "15.5.1" @@ -15882,6 +16326,11 @@ graphql@^15.5.1: resolved "https://registry.npmjs.org/graphql/-/graphql-15.6.1.tgz#9125bdf057553525da251e19e96dab3d3855ddfc" integrity sha512-3i5lu0z6dRvJ48QP9kFxBkJ7h4Kso7PS8eahyTFz5Jm6CvQfLtNIE8LX9N6JLnXTuwR+sIYnXzaWp6anOg0QQw== +graphql@^16.0.0: + version "16.0.1" + resolved "https://registry.npmjs.org/graphql/-/graphql-16.0.1.tgz#93a13cd4e0e38ca8d0832e79614c8578bfd34f10" + integrity sha512-oPvCuu6dlLdiz8gZupJ47o1clgb72r1u8NDBcQYjcV6G/iEdmE11B1bBlkhXRvV0LisP/SXRFP7tT6AgaTjpzg== + grouped-queue@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/grouped-queue/-/grouped-queue-2.0.0.tgz#a2c6713f2171e45db2c300a3a9d7c119d694dac8" @@ -15907,7 +16356,7 @@ gud@^1.0.0: resolved "https://registry.npmjs.org/gud/-/gud-1.0.0.tgz#a489581b17e6a70beca9abe3ae57de7a499852c0" integrity sha512-zGEOVKFM5sVPPrYs7J5/hYEw2Pof8KCyOwyhG8sAF26mCAeUFAcYPu1mwB7hhpIP29zOIBaDqwuHdLp0jvZXjw== -gzip-size@5.1.1: +gzip-size@5.1.1, gzip-size@^5.1.1: version "5.1.1" resolved "https://registry.npmjs.org/gzip-size/-/gzip-size-5.1.1.tgz#cb9bee692f87c0612b232840a873904e4c135274" integrity sha512-FNHi6mmoHvs1mxZAds4PpdCS6QG8B4C1krxJsMutgxl5t3+GlRTzzI3NEkifXx2pVsOvJdOGSmIgDhQ55FwdPA== @@ -15962,7 +16411,7 @@ has-ansi@^2.0.0: dependencies: ansi-regex "^2.0.0" -has-bigints@^1.0.0: +has-bigints@^1.0.0, has-bigints@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz#64fe6acb020673e3b78db035a5af69aa9d07b113" integrity sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA== @@ -15989,6 +16438,13 @@ has-symbols@^1.0.0, has-symbols@^1.0.1, has-symbols@^1.0.2: resolved "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz#165d3070c00309752a1236a479331e3ac56f1423" integrity sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw== +has-tostringtag@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz#7e133818a7d394734f941e73c3d3f9291e658b25" + integrity sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ== + dependencies: + has-symbols "^1.0.2" + has-unicode@^2.0.0, has-unicode@^2.0.1: version "2.0.1" resolved "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" @@ -16159,15 +16615,15 @@ highlight.js@^10.1.0, highlight.js@^10.1.1, highlight.js@^10.4.1, highlight.js@^ resolved "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.2.tgz#89319b861edc66c48854ed1e6da21ea89f847360" integrity sha512-oFLl873u4usRM9K63j4ME9u3etNF0PLiJhSQ8rdfuL51Wn3zkD6drf9ZW0dOzjnZI22YYG24z30JcmfCZjMgYg== -highlight.js@~10.7.0: +highlight.js@^10.7.2, highlight.js@~10.7.0: version "10.7.3" resolved "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz#697272e3991356e40c3cac566a74eef681756531" integrity sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A== history@^5.0.0: - version "5.0.1" - resolved "https://registry.npmjs.org/history/-/history-5.0.1.tgz#de35025ed08bce0db62364b47ebbf9d97b5eb06a" - integrity sha512-5qC/tFUKfVci5kzgRxZxN5Mf1CV8NmJx9ByaPX0YTLx5Vz3Svh7NYp6eA4CpDq4iA9D0C1t8BNIfvQIrUI3mVw== + version "5.1.0" + resolved "https://registry.npmjs.org/history/-/history-5.1.0.tgz#2e93c09c064194d38d52ed62afd0afc9d9b01ece" + integrity sha512-zPuQgPacm2vH2xdORvGGz1wQMuHSIB56yNAy5FnLuwOwgSYyPKptJtcMm6Ev+hRGeS+GzhbmRacHzvlESbFwDg== dependencies: "@babel/runtime" "^7.7.6" @@ -16434,6 +16890,15 @@ http-signature@~1.2.0: jsprim "^1.2.2" sshpk "^1.7.0" +http-signature@~1.3.6: + version "1.3.6" + resolved "https://registry.npmjs.org/http-signature/-/http-signature-1.3.6.tgz#cb6fbfdf86d1c974f343be94e87f7fc128662cf9" + integrity sha512-3adrsD6zqo4GsTqtO7FyrejHNv+NgiIfAfv68+jVlFmSr9OGy7zrxONceFRLKvnnZA5jbxQBX1u9PpB6Wi32Gw== + dependencies: + assert-plus "^1.0.0" + jsprim "^2.0.2" + sshpk "^1.14.1" + http2-wrapper@^1.0.0-beta.5.2: version "1.0.0-beta.5.2" resolved "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.0-beta.5.2.tgz#8b923deb90144aea65cf834b016a340fc98556f3" @@ -16577,10 +17042,10 @@ immer@8.0.1: resolved "https://registry.npmjs.org/immer/-/immer-8.0.1.tgz#9c73db683e2b3975c424fb0572af5889877ae656" integrity sha512-aqXhGP7//Gui2+UrEtvxZxSquQVXTpZ7KDxfCcKAF3Vysvw0CViVaW9RZ1j1xlIYqaaaipBoqdqeibkc18PNvA== -immer@^9.0.1: - version "9.0.6" - resolved "https://registry.npmjs.org/immer/-/immer-9.0.6.tgz#7a96bf2674d06c8143e327cbf73539388ddf1a73" - integrity sha512-G95ivKpy+EvVAnAab4fVa4YGYn24J1SpEktnJX7JJ45Bd7xqME/SCplFzYFmTbrkwZbQ4xJK1xMTUYBkN6pWsQ== +immer@^9.0.1, immer@^9.0.6: + version "9.0.7" + resolved "https://registry.npmjs.org/immer/-/immer-9.0.7.tgz#b6156bd7db55db7abc73fd2fdadf4e579a701075" + integrity sha512-KGllzpbamZDvOIxnmJ0jI840g7Oikx58lBPWV0hUh7dtAyZpFqqrBZdKka5GlTwMTZ1Tjc/bKKW4VSFAt6BqMA== immutable@>=3.8.2, immutable@^3.8.2, immutable@^3.x.x: version "3.8.2" @@ -16804,14 +17269,14 @@ internal-ip@^6.2.0: is-ip "^3.1.0" p-event "^4.2.0" -internal-slot@^1.0.2: - version "1.0.2" - resolved "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.2.tgz#9c2e9fb3cd8e5e4256c6f45fe310067fcfa378a3" - integrity sha512-2cQNfwhAfJIkU4KZPkDI+Gj5yNNnbqi40W9Gge6dfnk4TocEVm00B3bdiL+JINrbGJil2TeHvM4rETGzk/f/0g== +internal-slot@^1.0.3: + version "1.0.3" + resolved "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.3.tgz#7347e307deeea2faac2ac6205d4bc7d34967f59c" + integrity sha512-O0DB1JC/sPyZl7cIo78n5dR7eUSwwpYPiXRhTzNxZVAMUuB8vlnRFyLxdrVToks6XPLVnFfbzaVd5WLjhgg+vA== dependencies: - es-abstract "^1.17.0-next.1" + get-intrinsic "^1.1.0" has "^1.0.3" - side-channel "^1.0.2" + side-channel "^1.0.4" interpret@^1.0.0: version "1.2.0" @@ -16977,6 +17442,11 @@ is-callable@^1.1.4, is-callable@^1.2.3: resolved "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz#8b1e0500b73a1d76c70487636f368e519de8db8e" integrity sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ== +is-callable@^1.2.4: + version "1.2.4" + resolved "https://registry.npmjs.org/is-callable/-/is-callable-1.2.4.tgz#47301d58dd0259407865547853df6d61fe471945" + integrity sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w== + is-ci@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz#6bc6334181810e04b5c22b3d589fdca55026404c" @@ -17316,6 +17786,11 @@ is-potential-custom-element-name@^1.0.0: resolved "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.0.tgz#0c52e54bcca391bb2c494b21e8626d7336c6e397" integrity sha1-DFLlS8yjkbssSUsh6GJtczbG45c= +is-potential-custom-element-name@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz#171ed6f19e3ac554394edf78caa05784a45bebb5" + integrity sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ== + is-promise@4.0.0, is-promise@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz#42ff9f84206c1991d26debf520dd5c01042dd2f3" @@ -17346,6 +17821,14 @@ is-regex@^1.0.4, is-regex@^1.1.2: call-bind "^1.0.2" has-symbols "^1.0.1" +is-regex@^1.1.4: + version "1.1.4" + resolved "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz#eef5663cd59fa4c0ae339505323df6854bb15958" + integrity sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg== + dependencies: + call-bind "^1.0.2" + has-tostringtag "^1.0.0" + is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" @@ -17363,7 +17846,7 @@ is-resolvable@^1.1.0: resolved "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz#fb18f87ce1feb925169c9a407c19318a3206ed88" integrity sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg== -is-root@2.1.0: +is-root@2.1.0, is-root@^2.1.0: version "2.1.0" resolved "https://registry.npmjs.org/is-root/-/is-root-2.1.0.tgz#809e18129cf1129644302a4f8544035d51984a9c" integrity sha512-AGOriNp96vNBd3HtU+RzFEc75FfR5ymiYv8E553I71SCeXBiMsVDUtdio1OEFvrPyLIQ9tVR5RxXIFe5PUFjMg== @@ -17380,6 +17863,11 @@ is-set@^2.0.1: resolved "https://registry.npmjs.org/is-set/-/is-set-2.0.1.tgz#d1604afdab1724986d30091575f54945da7e5f43" integrity sha512-eJEzOtVyenDs1TMzSQ3kU3K+E0GUS9sno+F0OBT97xsgcJsF9nXMBtkT9/kut5JEpM7oL7X/0qxR17K3mcwIAA== +is-shared-array-buffer@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.1.tgz#97b0c85fbdacb59c9c446fe653b82cf2b5b7cfe6" + integrity sha512-IU0NmyknYZN0rChcKhRO1X8LYz5Isj/Fsqh8NJOSf+N/hCOTwy29F32Ik7a+QszE63IdvmwdTPDd6cZ5pg4cwA== + is-ssh@^1.3.0: version "1.3.1" resolved "https://registry.npmjs.org/is-ssh/-/is-ssh-1.3.1.tgz#f349a8cadd24e65298037a522cf7520f2e81a0f3" @@ -17407,6 +17895,13 @@ is-string@^1.0.4, is-string@^1.0.5: resolved "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz#40493ed198ef3ff477b8c7f92f644ec82a5cd3a6" integrity sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ== +is-string@^1.0.7: + version "1.0.7" + resolved "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz#0dd12bf2006f255bb58f695110eff7491eebc0fd" + integrity sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg== + dependencies: + has-tostringtag "^1.0.0" + is-subdir@^1.1.1: version "1.1.1" resolved "https://registry.npmjs.org/is-subdir/-/is-subdir-1.1.1.tgz#423e66902f9c5f159b9cc4826c820df083059538" @@ -17468,6 +17963,13 @@ is-utf8@^0.2.0, is-utf8@^0.2.1: resolved "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" integrity sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI= +is-weakref@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.1.tgz#842dba4ec17fa9ac9850df2d6efbc1737274f2a2" + integrity sha512-b2jKc2pQZjaeFYWEf7ScFj+Be1I+PXmlu572Q8coTXZ+LD/QQZ7ShPMst8h16riVgyXTQwUsFEl74mDvc/3MHQ== + dependencies: + call-bind "^1.0.0" + is-whitespace-character@^1.0.0: version "1.0.4" resolved "https://registry.npmjs.org/is-whitespace-character/-/is-whitespace-character-1.0.4.tgz#0858edd94a95594c7c9dd0b5c174ec6e45ee4aa7" @@ -17547,6 +18049,15 @@ isobject@^4.0.0: resolved "https://registry.npmjs.org/isobject/-/isobject-4.0.0.tgz#3f1c9155e73b192022a80819bacd0343711697b0" integrity sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA== +isomorphic-dompurify@^0.13.0: + version "0.13.0" + resolved "https://registry.npmjs.org/isomorphic-dompurify/-/isomorphic-dompurify-0.13.0.tgz#a4dde357e8531018a85ebb2dd56c4794b6739ba3" + integrity sha512-j2/kt/PGbxvfeEm1uiRLlttZkQdn3hFe1rMr/wm3qFnMXSIw0Nmqu79k+TIoSj+KOwO98Sz9TbuNHU7ejv7IZA== + dependencies: + "@types/dompurify" "^2.1.0" + dompurify "^2.2.7" + jsdom "^16.5.2" + isomorphic-fetch@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-3.0.0.tgz#0267b005049046d2421207215d45d6a262b8b8b4" @@ -18149,10 +18660,10 @@ jose@^2.0.5: dependencies: "@panva/asn1.js" "^1.0.0" -joycon@^2.2.5: - version "2.2.5" - resolved "https://registry.npmjs.org/joycon/-/joycon-2.2.5.tgz#8d4cf4cbb2544d7b7583c216fcdfec19f6be1615" - integrity sha512-YqvUxoOcVPnCp0VU1/56f+iKSdvIRJYPznH22BdXV3xMk75SFXhWeJkZ8C9XxUWt1b5x2X1SxuFygW1U0FmkEQ== +joycon@^3.0.1: + version "3.1.0" + resolved "https://registry.npmjs.org/joycon/-/joycon-3.1.0.tgz#33bb2b6b5a6849a1e251bed623bdf610f477d49f" + integrity sha512-5Y/YJghKF/IzaUXTut0JtbQyHfBShTaIsH7hHhGXEzYO07zWdWZm5hr3Q6miqhrwsRqqm3mgOnUEZdn+1aRxKQ== js-base64@^3.6.0: version "3.7.2" @@ -18282,6 +18793,39 @@ jsdom@^16.4.0: ws "^7.2.3" xml-name-validator "^3.0.0" +jsdom@^16.5.2: + version "16.7.0" + resolved "https://registry.npmjs.org/jsdom/-/jsdom-16.7.0.tgz#918ae71965424b197c819f8183a754e18977b710" + integrity sha512-u9Smc2G1USStM+s/x1ru5Sxrl6mPYCbByG1U/hUmqaVsm4tbNyS7CicOSRyuGQYZhTu0h84qkZZQ/I+dzizSVw== + dependencies: + abab "^2.0.5" + acorn "^8.2.4" + acorn-globals "^6.0.0" + cssom "^0.4.4" + cssstyle "^2.3.0" + data-urls "^2.0.0" + decimal.js "^10.2.1" + domexception "^2.0.1" + escodegen "^2.0.0" + form-data "^3.0.0" + html-encoding-sniffer "^2.0.1" + http-proxy-agent "^4.0.1" + https-proxy-agent "^5.0.0" + is-potential-custom-element-name "^1.0.1" + nwsapi "^2.2.0" + parse5 "6.0.1" + saxes "^5.0.1" + symbol-tree "^3.2.4" + tough-cookie "^4.0.0" + w3c-hr-time "^1.0.2" + w3c-xmlserializer "^2.0.0" + webidl-conversions "^6.1.0" + whatwg-encoding "^1.0.5" + whatwg-mimetype "^2.3.0" + whatwg-url "^8.5.0" + ws "^7.4.6" + xml-name-validator "^3.0.0" + jsesc@^2.5.1: version "2.5.2" resolved "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4" @@ -18319,7 +18863,7 @@ json-parse-even-better-errors@^2.3.0, json-parse-even-better-errors@^2.3.1: resolved "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== -json-pointer@^0.6.0: +json-pointer@^0.6.1: version "0.6.1" resolved "https://registry.npmjs.org/json-pointer/-/json-pointer-0.6.1.tgz#3c6caa6ac139e2599f5a1659d39852154015054d" integrity sha512-3OvjqKdCBvH41DLpV4iSt6v2XhZXV1bPB4OROuknvUXI7ZQNofieCPkmE26stEJ9zdQuvIxDHCuYhfgxFAAs+Q== @@ -18377,7 +18921,7 @@ json-schema@0.2.3: resolved "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" integrity sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM= -json-schema@^0.4.0: +json-schema@0.4.0, json-schema@^0.4.0: version "0.4.0" resolved "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz#f7de4cf6efab838ebaeb3236474cbba5a1930ab5" integrity sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA== @@ -18439,6 +18983,11 @@ json5@^2.1.2, json5@^2.1.3: dependencies: minimist "^1.2.5" +jsonc-parser@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.0.0.tgz#abdd785701c7e7eaca8a9ec8cf070ca51a745a22" + integrity sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA== + jsonfile@^2.1.0: version "2.4.0" resolved "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz#3736a2b428b87bbda0cc83b53fa3d633a35c2ae8" @@ -18518,6 +19067,16 @@ jsprim@^1.2.2: json-schema "0.2.3" verror "1.10.0" +jsprim@^2.0.2: + version "2.0.2" + resolved "https://registry.npmjs.org/jsprim/-/jsprim-2.0.2.tgz#77ca23dbcd4135cd364800d22ff82c2185803d4d" + integrity sha512-gqXddjPqQ6G40VdnI6T6yObEC+pDNvyP95wdQhkWkg7crHH3km5qP1FsOXEkzEQwnz6gz5qGTn1c2Y52wP3OyQ== + dependencies: + assert-plus "1.0.0" + extsprintf "1.3.0" + json-schema "0.4.0" + verror "1.10.0" + jss-plugin-camel-case@^10.5.1: version "10.6.0" resolved "https://registry.npmjs.org/jss-plugin-camel-case/-/jss-plugin-camel-case-10.6.0.tgz#93d2cd704bf0c4af70cc40fb52d74b8a2554b170" @@ -19349,7 +19908,7 @@ lodash@4.17.15: resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== -lodash@4.17.21, lodash@^4.17.10, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.20, lodash@^4.17.21, lodash@^4.17.4, lodash@^4.17.5, lodash@~4.17.0, lodash@~4.17.15, lodash@~4.17.4: +lodash@4.17.21, lodash@^4.17.10, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.20, lodash@^4.17.21, lodash@^4.17.4, lodash@^4.17.5, lodash@^4.7.0, lodash@~4.17.0, lodash@~4.17.15, lodash@~4.17.4: version "4.17.21" resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== @@ -19641,17 +20200,6 @@ markdown-escapes@^1.0.0: resolved "https://registry.npmjs.org/markdown-escapes/-/markdown-escapes-1.0.4.tgz#c95415ef451499d7602b91095f3c8e8975f78535" integrity sha512-8z4efJYk43E0upd0NbVXwgSTQs6cT3T06etieCMEg7dRbzCbxUCK/GHlX8mhHRDcp+OLlHkPKsvqQTCvsRl2cg== -markdown-it@^11.0.1: - version "11.0.1" - resolved "https://registry.npmjs.org/markdown-it/-/markdown-it-11.0.1.tgz#b54f15ec2a2193efa66dda1eb4173baea08993d6" - integrity sha512-aU1TzmBKcWNNYvH9pjq6u92BML+Hz3h5S/QpfTFwiQF852pLT+9qHsrhM9JYipkOXZxGn+sGH8oyJE9FD9WezQ== - dependencies: - argparse "^1.0.7" - entities "~2.0.0" - linkify-it "^3.0.1" - mdurl "^1.0.1" - uc.micro "^1.0.5" - markdown-it@^12.2.0: version "12.2.0" resolved "https://registry.npmjs.org/markdown-it/-/markdown-it-12.2.0.tgz#091f720fd5db206f80de7a8d1f1a7035fd0d38db" @@ -19688,6 +20236,11 @@ markdown-to-jsx@^7.1.3: resolved "https://registry.npmjs.org/markdown-to-jsx/-/markdown-to-jsx-7.1.3.tgz#f00bae66c0abe7dd2d274123f84cb6bd2a2c7c6a" integrity sha512-jtQ6VyT7rMT5tPV0g2EJakEnXLiPksnvlYtwQsVVZ611JsWGN8bQ1tVSDX4s6JllfEH6wmsYxNjTUAMrPmNA8w== +marked@^2.1.1: + version "2.1.3" + resolved "https://registry.npmjs.org/marked/-/marked-2.1.3.tgz#bd017cef6431724fd4b27e0657f5ceb14bff3753" + integrity sha512-/Q+7MGzaETqifOMWYEA7HVMaZb4XbcRfaOzcSsHZEith83KGlvaSG33u0SKu89Mj5h+T8V2hM+8O45Qc5XTgwA== + math-expression-evaluator@^1.2.14: version "1.2.22" resolved "https://registry.npmjs.org/math-expression-evaluator/-/math-expression-evaluator-1.2.22.tgz#c14dcb3d8b4d150e5dcea9c68c8dad80309b0d5e" @@ -20087,11 +20640,6 @@ merge2@^1.2.3, merge2@^1.3.0: resolved "https://registry.npmjs.org/merge2/-/merge2-1.3.0.tgz#5b366ee83b2f1582c48f87e47cf1a9352103ca81" integrity sha512-2j4DAdlBOkiSZIsaXk4mTE3sRS02yBHAtfy127xRV3bQUFqXkjHCHLW6Scv7DwNRbIWNHH8zpnz9zMaKXIdvYw== -merge@^2.1.0: - version "2.1.1" - resolved "https://registry.npmjs.org/merge/-/merge-2.1.1.tgz#59ef4bf7e0b3e879186436e8481c06a6c162ca98" - integrity sha512-jz+Cfrg9GWOZbQAnDQ4hlVnQky+341Yk5ru8bZSe6sIDTCIg8n9i/u7hSQGSVOF3C7lH6mGtqjkiT9G4wFLL0w== - meros@1.1.4, meros@^1.1.4: version "1.1.4" resolved "https://registry.npmjs.org/meros/-/meros-1.1.4.tgz#c17994d3133db8b23807f62bec7f0cb276cfd948" @@ -20910,7 +21458,7 @@ nan@^2.14.1, nan@^2.15.0: resolved "https://registry.npmjs.org/nan/-/nan-2.15.0.tgz#3f34a473ff18e15c1b5626b62903b5ad6e665fee" integrity sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ== -nano-css@^5.1.0, nano-css@^5.3.1: +nano-css@^5.3.1: version "5.3.1" resolved "https://registry.npmjs.org/nano-css/-/nano-css-5.3.1.tgz#b709383e07ad3be61f64edffacb9d98250b87a1f" integrity sha512-ENPIyNzANQRyYVvb62ajDd7PAyIgS2LIUnT9ewih4yrXSZX4hKoUwssy8WjUH++kEOA5wUTMgNnV7ko5n34kUA== @@ -21079,10 +21627,10 @@ node-fetch@2.6.1, node-fetch@^2.3.0, node-fetch@^2.6.0, node-fetch@^2.6.1: resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052" integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw== -node-fetch@2.6.5: - version "2.6.5" - resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.5.tgz#42735537d7f080a7e5f78b6c549b7146be1742fd" - integrity sha512-mmlIVHJEu5rnIxgEgez6b9GgWXbkZj5YZ7fx+2r94a2E+Uirsp6HsPTPlomfdHtpt/B0cdKviwkoaM6pyvUOpQ== +node-fetch@^2.6.5: + version "2.6.6" + resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.6.tgz#1751a7c01834e8e1697758732e9efb6eeadfaf89" + integrity sha512-Z8/6vRlTUChSdIgMa51jxQ4lrw/Jy5SOW10ObaA47/RElsAN2c5Pn8bTgFGWn/ibwzXTE8qwr1Yzx28vsecXEA== dependencies: whatwg-url "^5.0.0" @@ -21537,6 +22085,11 @@ object-hash@^2.0.1, object-hash@^2.1.1: resolved "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz#5ad518581eefc443bd763472b8ff2e9c2c0d54a5" integrity sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw== +object-inspect@^1.11.0: + version "1.11.0" + resolved "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz#9dceb146cedd4148a0d9e51ab88d34cf509922b1" + integrity sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg== + object-inspect@^1.9.0: version "1.9.0" resolved "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz#c90521d74e1127b67266ded3394ad6116986533a" @@ -21574,24 +22127,23 @@ object.assign@^4.1.0, object.assign@^4.1.2: has-symbols "^1.0.1" object-keys "^1.1.1" -object.entries@^1.1.0, object.entries@^1.1.2: - version "1.1.2" - resolved "https://registry.npmjs.org/object.entries/-/object.entries-1.1.2.tgz#bc73f00acb6b6bb16c203434b10f9a7e797d3add" - integrity sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA== +object.entries@^1.1.0, object.entries@^1.1.5: + version "1.1.5" + resolved "https://registry.npmjs.org/object.entries/-/object.entries-1.1.5.tgz#e1acdd17c4de2cd96d5a08487cfb9db84d881861" + integrity sha512-TyxmjUoZggd4OrrU1W66FMDG6CuqJxsFvymeyXI51+vQLN67zYfZseptRge703kKQdo4uccgAKebXFcRCzk4+g== dependencies: + call-bind "^1.0.2" define-properties "^1.1.3" - es-abstract "^1.17.5" - has "^1.0.3" + es-abstract "^1.19.1" -"object.fromentries@^2.0.0 || ^1.0.0", object.fromentries@^2.0.2: - version "2.0.2" - resolved "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.2.tgz#4a09c9b9bb3843dd0f89acdb517a794d4f355ac9" - integrity sha512-r3ZiBH7MQppDJVLx6fhD618GKNG40CZYH9wgwdhKxBDDbQgjeWGGd4AtkZad84d291YxvWe7bJGuE65Anh0dxQ== +"object.fromentries@^2.0.0 || ^1.0.0", object.fromentries@^2.0.5: + version "2.0.5" + resolved "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.5.tgz#7b37b205109c21e741e605727fe8b0ad5fa08251" + integrity sha512-CAyG5mWQRRiBU57Re4FKoTBjXfDoNwdFVH2Y1tS9PqCsfUTymAohOkEMSG3aRNKmv4lV3O7p1et7c187q6bynw== dependencies: + call-bind "^1.0.2" define-properties "^1.1.3" - es-abstract "^1.17.0-next.1" - function-bind "^1.1.1" - has "^1.0.3" + es-abstract "^1.19.1" object.getownpropertydescriptors@^2.0.3, object.getownpropertydescriptors@^2.1.0: version "2.1.0" @@ -21601,6 +22153,14 @@ object.getownpropertydescriptors@^2.0.3, object.getownpropertydescriptors@^2.1.0 define-properties "^1.1.3" es-abstract "^1.17.0-next.1" +object.hasown@^1.1.0: + version "1.1.0" + resolved "https://registry.npmjs.org/object.hasown/-/object.hasown-1.1.0.tgz#7232ed266f34d197d15cac5880232f7a4790afe5" + integrity sha512-MhjYRfj3GBlhSkDHo6QmvgjRLXQ2zndabdf3nX0yTyZK9rPfxb6uRpAac8HXNLy1GpqWtZ81Qh4v3uOls2sRAg== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.19.1" + object.pick@^1.3.0: version "1.3.0" resolved "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" @@ -21608,15 +22168,14 @@ object.pick@^1.3.0: dependencies: isobject "^3.0.1" -object.values@^1.1.0, object.values@^1.1.1: - version "1.1.1" - resolved "https://registry.npmjs.org/object.values/-/object.values-1.1.1.tgz#68a99ecde356b7e9295a3c5e0ce31dc8c953de5e" - integrity sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA== +object.values@^1.1.0, object.values@^1.1.1, object.values@^1.1.5: + version "1.1.5" + resolved "https://registry.npmjs.org/object.values/-/object.values-1.1.5.tgz#959f63e3ce9ef108720333082131e4a459b716ac" + integrity sha512-QUZRW0ilQ3PnPpbNtgdNV1PDbEqLIiSFB3l+EnGtBQ/8SUTLj1PZwtQHABZtLgwpJZTSZhuGLOGk57Drx2IvYg== dependencies: + call-bind "^1.0.2" define-properties "^1.1.3" - es-abstract "^1.17.0-next.1" - function-bind "^1.1.1" - has "^1.0.3" + es-abstract "^1.19.1" objectorarray@^1.0.4: version "1.0.4" @@ -21702,12 +22261,13 @@ open@^8.0.9: is-docker "^2.1.1" is-wsl "^2.2.0" -openapi-sampler@^1.0.0-beta.15: - version "1.0.0-beta.16" - resolved "https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-1.0.0-beta.16.tgz#7813524d5b88d222efb772ceb5a809075d6d9174" - integrity sha512-05+GvwMagTY7GxoDQoWJfmAUFlxfebciiEzqKmu4iq6+MqBEn62AMUkn0CTxyKhnUGIaR2KXjTeslxIeJwVIOw== +openapi-sampler@^1.1.0: + version "1.1.1" + resolved "https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-1.1.1.tgz#7bba7000a03cd8a4630bfbe5b3ef258990c78400" + integrity sha512-WAFsl5SPYuhQwaMTDFOcKhnEY1G1rmamrMiPmJdqwfl1lr81g63/befcsN9BNi0w5/R0L+hfcUj13PANEBeLgg== dependencies: - json-pointer "^0.6.0" + "@types/json-schema" "^7.0.7" + json-pointer "^0.6.1" openid-client@^4.1.1, openid-client@^4.2.1: version "4.9.0" @@ -22204,7 +22764,7 @@ 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@^6.0.0: +parse5@6.0.1, parse5@^6.0.0: version "6.0.1" resolved "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz#e1a1c085c569b3dc08321184f19a39cc27f7c30b" integrity sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw== @@ -22609,7 +23169,7 @@ picocolors@^1.0.0: resolved "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== -picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.2, picomatch@^2.2.3: +picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.2, picomatch@^2.2.3, picomatch@^2.3.0: version "2.3.0" resolved "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz#f1f061de8f6a4bf022892e2d128234fb98302972" integrity sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw== @@ -22713,7 +23273,7 @@ pkg-dir@^5.0.0: dependencies: find-up "^5.0.0" -pkg-up@3.1.0: +pkg-up@3.1.0, pkg-up@^3.1.0: version "3.1.0" resolved "https://registry.npmjs.org/pkg-up/-/pkg-up-3.1.0.tgz#100ec235cc150e4fd42519412596a28512a0def5" integrity sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA== @@ -23740,9 +24300,9 @@ raw-loader@^4.0.2: schema-utils "^3.0.0" rc-progress@^3.0.0: - version "3.1.3" - resolved "https://registry.npmjs.org/rc-progress/-/rc-progress-3.1.3.tgz#d77d8fd26d9d948d72c2a28b64b71a6e86df2426" - integrity sha512-Jl4fzbBExHYMoC6HBPzel0a9VmhcSXx24LVt/mdhDM90MuzoMCJjXZAlhA0V0CJi+SKjMhfBoIQ6Lla1nD4QNw== + version "3.1.4" + resolved "https://registry.npmjs.org/rc-progress/-/rc-progress-3.1.4.tgz#66040d0fae7d8ced2b38588378eccb2864bad615" + integrity sha512-XBAif08eunHssGeIdxMXOmRQRULdHaDdIFENQ578CMb4dyewahmmfJRyab+hw4KH4XssEzzYOkAInTLS7JJG+Q== dependencies: "@babel/runtime" "^7.10.1" classnames "^2.2.6" @@ -23791,7 +24351,7 @@ react-debounce-input@=3.2.4: lodash.debounce "^4" prop-types "^15.7.2" -react-dev-utils@^11.0.3, react-dev-utils@^11.0.4: +react-dev-utils@^11.0.3: version "11.0.4" resolved "https://registry.npmjs.org/react-dev-utils/-/react-dev-utils-11.0.4.tgz#a7ccb60257a1ca2e0efe7a83e38e6700d17aa37a" integrity sha512-dx0LvIGHcOPtKbeiSUM4jqpBl3TcY7CDjZdfOIcKeznE7BWr9dg0iPG90G5yfVQ+p/rGNMXdbfStvzQZEVEi4A== @@ -23821,6 +24381,36 @@ react-dev-utils@^11.0.3, react-dev-utils@^11.0.4: strip-ansi "6.0.0" text-table "0.2.0" +react-dev-utils@^12.0.0-next.47: + version "12.0.0-next.47" + resolved "https://registry.npmjs.org/react-dev-utils/-/react-dev-utils-12.0.0-next.47.tgz#e55c31a05eb30cfd69ca516e8b87d61724e880fb" + integrity sha512-PsE71vP15TZMmp/RZKOJC4fYD5Pvt0+wCoyG3QHclto0d4FyIJI78xGRICOOThZFROqgXYlZP6ddmeybm+jO4w== + dependencies: + "@babel/code-frame" "^7.10.4" + address "^1.1.2" + browserslist "^4.16.5" + chalk "^2.4.2" + cross-spawn "^7.0.3" + detect-port-alt "^1.1.6" + escape-string-regexp "^2.0.0" + filesize "^6.1.0" + find-up "^4.1.0" + fork-ts-checker-webpack-plugin "^6.0.5" + global-modules "^2.0.0" + globby "^11.0.1" + gzip-size "^5.1.1" + immer "^9.0.6" + is-root "^2.1.0" + loader-utils "^2.0.0" + open "^7.0.2" + pkg-up "^3.1.0" + prompts "^2.4.0" + react-error-overlay "7.0.0-next.54+1465357b" + recursive-readdir "^2.2.2" + shell-quote "^1.7.2" + strip-ansi "^6.0.0" + text-table "^0.2.0" + react-docgen-typescript@^2.0.0: version "2.1.0" resolved "https://registry.npmjs.org/react-docgen-typescript/-/react-docgen-typescript-2.1.0.tgz#20db64a7fd62e63a8a9469fb4abd90600878cbb2" @@ -23870,16 +24460,16 @@ react-error-boundary@^3.1.0: dependencies: "@babel/runtime" "^7.12.5" +react-error-overlay@7.0.0-next.54+1465357b: + version "7.0.0-next.54" + resolved "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-7.0.0-next.54.tgz#c1eb5ab86aee15e9552e6d97897b08f2bd06d140" + integrity sha512-b96CiTnZahXPDNH9MKplvt5+jD+BkxDw7q5R3jnkUXze/ux1pLv32BBZmlj0OfCUeMqyz4sAmF+0ccJGVMlpXw== + react-error-overlay@^6.0.9: version "6.0.9" resolved "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-6.0.9.tgz#3c743010c9359608c375ecd6bc76f35d93995b0a" integrity sha512-nQTTcUu+ATDbrSD1BZHr5kgSD4oF8OFjxun8uAaL8RwPBacGBNPf/yAuVVdx17N8XNzRDMrZ9XcKZHCjPW+9ew== -react-fast-compare@^2.0.4: - version "2.0.4" - resolved "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-2.0.4.tgz#e84b4d455b0fec113e0402c329352715196f81f9" - integrity sha512-suNP+J1VU1MWFKcyt7RtjiSWUjvidmQSlqu+eHslq+342xCbGTYmC0mEhPCOHxlW0CywylOC1u2DFAT+bv4dBw== - react-fast-compare@^3.0.1, react-fast-compare@^3.1.1, react-fast-compare@^3.2.0: version "3.2.0" resolved "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.0.tgz#641a9da81b6a6320f270e89724fb45a0b39e43bb" @@ -24197,23 +24787,6 @@ react-universal-interface@^0.6.2: resolved "https://registry.npmjs.org/react-universal-interface/-/react-universal-interface-0.6.2.tgz#5e8d438a01729a4dbbcbeeceb0b86be146fe2b3b" integrity sha512-dg8yXdcQmvgR13RIlZbTRQOoUrDciFVoSBZILwjE2LFISxZZ8loVJKAkuzswl5js8BHda79bIb2b84ehU8IjXw== -react-use@^12.2.0: - version "12.13.0" - resolved "https://registry.npmjs.org/react-use/-/react-use-12.13.0.tgz#dfefd8145552841f1c2213c2e79966b505a264ba" - integrity sha512-Kh0m9ezIn9xfRycx4jdAgvsYGstGfjTBO2ecIM3+G0RqrpMxTIL5jjYraHYfUzjGBHf7dUhNYBzm5vw5LItVZA== - dependencies: - "@types/react-wait" "^0.3.0" - copy-to-clipboard "^3.1.0" - nano-css "^5.1.0" - react-fast-compare "^2.0.4" - react-wait "^0.3.0" - resize-observer-polyfill "^1.5.1" - screenfull "^5.0.0" - set-harmonic-interval "^1.0.1" - throttle-debounce "^2.0.1" - ts-easing "^0.2.0" - tslib "^1.10.0" - react-use@^17.2.4: version "17.2.4" resolved "https://registry.npmjs.org/react-use/-/react-use-17.2.4.tgz#1f89be3db0a8237c79253db0a15e12bbe3cfeff1" @@ -24246,11 +24819,6 @@ react-virtualized@^9.21.0: prop-types "^15.6.0" react-lifecycles-compat "^3.0.4" -react-wait@^0.3.0: - version "0.3.0" - resolved "https://registry.npmjs.org/react-wait/-/react-wait-0.3.0.tgz#0cdd4d919012451a5bc3ab0a16d00c6fd9a8c10b" - integrity sha512-kB5x/kMKWcn0uVr9gBdNz21/oGbQwEQnF3P9p6E9yLfJ9DRcKS0fagbgYMFI0YFOoyKDj+2q6Rwax0kTYJF37g== - react@^16.0.0, react@^16.12.0, react@^16.13.1: version "16.13.1" resolved "https://registry.npmjs.org/react/-/react-16.13.1.tgz#2e818822f1a9743122c063d6410d85c1e3afe48e" @@ -24625,7 +25193,7 @@ regex-not@^1.0.0, regex-not@^1.0.2: extend-shallow "^3.0.2" safe-regex "^1.1.0" -regexp.prototype.flags@^1.2.0, regexp.prototype.flags@^1.3.0: +regexp.prototype.flags@^1.2.0: version "1.3.0" resolved "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.3.0.tgz#7aba89b3c13a64509dabcf3ca8d9fbb9bdf5cb75" integrity sha512-2+Q0C5g951OlYlJz6yu5/M33IcsESLlLfsyIaLJaG4FA2r4yP8MvVMJUUP/fVBkSpbbbZlS5gynbEWLipiiXiQ== @@ -24633,6 +25201,14 @@ regexp.prototype.flags@^1.2.0, regexp.prototype.flags@^1.3.0: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" +regexp.prototype.flags@^1.3.1: + version "1.3.1" + resolved "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.3.1.tgz#7ef352ae8d159e758c0eadca6f8fcb4eef07be26" + integrity sha512-JiBdRBq91WlY7uRJ0ds7R+dU02i6LKi8r3BuQhNXn+kmeLN+EfHhfjqMRis1zJxnlu88hq/4dx0P2OP3APRTOA== + dependencies: + call-bind "^1.0.2" + define-properties "^1.1.3" + regexpp@^3.1.0: version "3.1.0" resolved "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" @@ -25002,6 +25578,14 @@ resolve@^1.1.6, resolve@^1.10.0, resolve@^1.12.0, resolve@^1.13.1, resolve@^1.14 is-core-module "^2.2.0" path-parse "^1.0.6" +resolve@^2.0.0-next.3: + version "2.0.0-next.3" + resolved "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.3.tgz#d41016293d4a8586a39ca5d9b5f15cbea1f55e46" + integrity sha512-W8LucSynKUIDu9ylraa7ueVZ7hc0uAgJBxVsQSKOXOyle8a93qXhcz+XAXZ8bIq2d6i4Ehddn6Evt+0/UwKk6Q== + dependencies: + is-core-module "^2.2.0" + path-parse "^1.0.6" + resolve@~1.17.0: version "1.17.0" resolved "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" @@ -25138,23 +25722,23 @@ ripemd160@^2.0.0, ripemd160@^2.0.1: hash-base "^3.0.0" inherits "^2.0.1" -rollup-plugin-dts@^3.0.1: - version "3.0.2" - resolved "https://registry.npmjs.org/rollup-plugin-dts/-/rollup-plugin-dts-3.0.2.tgz#2b628d88f864d271d6eaec2e4c2a60ae4e944c5c" - integrity sha512-hswlsdWu/x7k5pXzaLP6OvKRKcx8Bzprksz9i9mUe72zvt8LvqAb/AZpzs6FkLgmyRaN8B6rUQOVtzA3yEt9Yw== +rollup-plugin-dts@^4.0.1: + version "4.0.1" + resolved "https://registry.npmjs.org/rollup-plugin-dts/-/rollup-plugin-dts-4.0.1.tgz#930cbd5aaaa64a55e895ecd6ae8234e1a5467710" + integrity sha512-DNv5F8pro/r0Hkx3JWKRtJZocDnqXfgypoajeiaNq134rYaFcEIl/oas5PogD1qexMadVijsHyVko1Chig0OOQ== dependencies: magic-string "^0.25.7" optionalDependencies: - "@babel/code-frame" "^7.12.13" + "@babel/code-frame" "^7.14.5" -rollup-plugin-esbuild@2.6.x: - version "2.6.1" - resolved "https://registry.npmjs.org/rollup-plugin-esbuild/-/rollup-plugin-esbuild-2.6.1.tgz#5785532940d49adf1bff5b38e9bd9089262d4e7a" - integrity sha512-hskMEQQ4Vxlyoeg1OWlFTwWHIhpNaw6q+diOT7p9pdkk34m9Mbk3aymS/JbTqLXy/AbJi22iuXrucknKpeczfg== +rollup-plugin-esbuild@^4.7.2: + version "4.7.2" + resolved "https://registry.npmjs.org/rollup-plugin-esbuild/-/rollup-plugin-esbuild-4.7.2.tgz#1a496a9f96257cdf5ed800e818932859232471f8" + integrity sha512-rBS2hTedtG+wL/yyIWQ84zju5rtfF15gkaCLN0vsWGmBdRd0UPm52meAwkmrsPQf3mB/H2o+k9Q8Ce8A66SE5A== dependencies: - "@rollup/pluginutils" "^4.1.0" - joycon "^2.2.5" - strip-json-comments "^3.1.1" + "@rollup/pluginutils" "^4.1.1" + joycon "^3.0.1" + jsonc-parser "^3.0.0" rollup-plugin-peer-deps-external@^2.2.2: version "2.2.4" @@ -25187,13 +25771,6 @@ rollup-pluginutils@^2.8.2: dependencies: estree-walker "^0.6.1" -rollup@2.44.x: - version "2.44.0" - resolved "https://registry.npmjs.org/rollup/-/rollup-2.44.0.tgz#8da324d1c4fd12beef9ae6e12f4068265b6d95eb" - integrity sha512-rGSF4pLwvuaH/x4nAS+zP6UNn5YUDWf/TeEU5IoXSZKBbKRNTCI3qMnYXKZgrC0D2KzS2baiOZt1OlqhMu5rnQ== - optionalDependencies: - fsevents "~2.3.1" - rollup@^0.63.4: version "0.63.5" resolved "https://registry.npmjs.org/rollup/-/rollup-0.63.5.tgz#5543eecac9a1b83b7e1be598b5be84c9c0a089db" @@ -25202,6 +25779,13 @@ rollup@^0.63.4: "@types/estree" "0.0.39" "@types/node" "*" +rollup@^2.60.2: + version "2.60.2" + resolved "https://registry.npmjs.org/rollup/-/rollup-2.60.2.tgz#3f45ace36a9b10b4297181831ea0719922513463" + integrity sha512-1Bgjpq61sPjgoZzuiDSGvbI1tD91giZABgjCQBKM5aYLnzjq52GoDuWVwT/cm/MCxCMPU8gqQvkj8doQ5C8Oqw== + optionalDependencies: + fsevents "~2.3.2" + rsvp@^4.8.4: version "4.8.5" resolved "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz#c8f155311d167f68f21e168df71ec5b083113734" @@ -25340,7 +25924,7 @@ sax@>=0.6.0, sax@^1.2.4, sax@~1.2.4: resolved "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== -saxes@^5.0.0: +saxes@^5.0.0, saxes@^5.0.1: version "5.0.1" resolved "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz#eebab953fa3b7608dbe94e5dadb15c888fa6696d" integrity sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw== @@ -25373,7 +25957,7 @@ schema-utils@^1.0.0: ajv-errors "^1.0.0" ajv-keywords "^3.1.0" -schema-utils@^2.6.5, schema-utils@^2.6.6, schema-utils@^2.7.0: +schema-utils@^2.6.5, schema-utils@^2.7.0: version "2.7.1" resolved "https://registry.npmjs.org/schema-utils/-/schema-utils-2.7.1.tgz#1ca4f32d1b24c590c203b8e7a50bf0ea4cd394d7" integrity sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg== @@ -25396,7 +25980,7 @@ scoped-regex@^2.0.0: resolved "https://registry.npmjs.org/scoped-regex/-/scoped-regex-2.1.0.tgz#7b9be845d81fd9d21d1ec97c61a0b7cf86d2015f" integrity sha512-g3WxHrqSWCZHGHlSrF51VXFdjImhwvH8ZO/pryFH56Qi0cDsZfylQa/t0jCzVQFNbNvM00HfHjkDPEuarKDSWQ== -screenfull@^5.0.0, screenfull@^5.1.0: +screenfull@^5.1.0: version "5.1.0" resolved "https://registry.npmjs.org/screenfull/-/screenfull-5.1.0.tgz#85c13c70f4ead4c1b8a935c70010dfdcd2c0e5c8" integrity sha512-dYaNuOdzr+kc6J6CFcBrzkLCfyGcMg+gWkJ8us93IQ7y1cevhQAugFsaCdMHb6lw8KV3xPzSxzH7zM1dQap9mA== @@ -25685,6 +26269,11 @@ shell-quote@1.7.2: resolved "https://registry.npmjs.org/shell-quote/-/shell-quote-1.7.2.tgz#67a7d02c76c9da24f99d20808fcaded0e0e04be2" integrity sha512-mRz/m/JVscCrkMyPqHc/bczi3OQHkLTqXHEFu0zDhK/qfv3UcOA4SVmRCLmos4bhjr9ekVQubj/R7waKapmiQg== +shell-quote@^1.7.2: + version "1.7.3" + resolved "https://registry.npmjs.org/shell-quote/-/shell-quote-1.7.3.tgz#aa40edac170445b9a431e17bb62c0b881b9c4123" + integrity sha512-Vpfqwm4EnqGdlsBFNmHhxhElJYrdfcxPThu+ryKS5J8L/fhAwLazFZtq+S+TWZ9ANj2piSQLGj6NQg+lKPmxrw== + shelljs@^0.8.3, shelljs@^0.8.4: version "0.8.4" resolved "https://registry.npmjs.org/shelljs/-/shelljs-0.8.4.tgz#de7684feeb767f8716b326078a8a00875890e3c2" @@ -25707,7 +26296,7 @@ shx@^0.3.2: minimist "^1.2.3" shelljs "^0.8.4" -side-channel@^1.0.2, side-channel@^1.0.4: +side-channel@^1.0.4: version "1.0.4" resolved "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw== @@ -26162,7 +26751,7 @@ ssh2@^1.4.0: cpu-features "0.0.2" nan "^2.15.0" -sshpk@^1.7.0: +sshpk@^1.14.1, sshpk@^1.7.0: version "1.16.1" resolved "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz#fb661c0bef29b39db40769ee39fa70093d6f6877" integrity sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg== @@ -26436,17 +27025,19 @@ string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0: is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.0" -"string.prototype.matchall@^4.0.0 || ^3.0.1", string.prototype.matchall@^4.0.2: - version "4.0.2" - resolved "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.2.tgz#48bb510326fb9fdeb6a33ceaa81a6ea04ef7648e" - integrity sha512-N/jp6O5fMf9os0JU3E72Qhf590RSRZU/ungsL/qJUYVTNv7hTG0P/dbPjxINVN9jpscu3nzYwKESU3P3RY5tOg== +"string.prototype.matchall@^4.0.0 || ^3.0.1", string.prototype.matchall@^4.0.6: + version "4.0.6" + resolved "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.6.tgz#5abb5dabc94c7b0ea2380f65ba610b3a544b15fa" + integrity sha512-6WgDX8HmQqvEd7J+G6VtAahhsQIssiZ8zl7zKh1VDMFyL3hRTJP4FTNA3RbIp2TOQ9AYNDcc7e3fH0Qbup+DBg== dependencies: + call-bind "^1.0.2" define-properties "^1.1.3" - es-abstract "^1.17.0" - has-symbols "^1.0.1" - internal-slot "^1.0.2" - regexp.prototype.flags "^1.3.0" - side-channel "^1.0.2" + es-abstract "^1.19.1" + get-intrinsic "^1.1.1" + has-symbols "^1.0.2" + internal-slot "^1.0.3" + regexp.prototype.flags "^1.3.1" + side-channel "^1.0.4" string.prototype.padend@^3.0.0: version "3.1.0" @@ -26631,14 +27222,6 @@ style-inject@^0.3.0: resolved "https://registry.npmjs.org/style-inject/-/style-inject-0.3.0.tgz#d21c477affec91811cc82355832a700d22bf8dd3" integrity sha512-IezA2qp+vcdlhJaVm5SOdPPTUu0FCEqfNSli2vRuSIBbu5Nq5UvygTk/VzeCqfLz2Atj3dVII5QBKGZRZ0edzw== -style-loader@^1.2.1: - version "1.2.1" - resolved "https://registry.npmjs.org/style-loader/-/style-loader-1.2.1.tgz#c5cbbfbf1170d076cfdd86e0109c5bba114baa1a" - integrity sha512-ByHSTQvHLkWE9Ir5+lGbVOXhxX10fbprhLvdg96wedFZb4NDekDPxVKv5Fwmio+QcMlkkNfuK+5W1peQ5CUhZg== - dependencies: - loader-utils "^2.0.0" - schema-utils "^2.6.6" - style-loader@^1.3.0: version "1.3.0" resolved "https://registry.npmjs.org/style-loader/-/style-loader-1.3.0.tgz#828b4a3b3b7e7aa5847ce7bae9e874512114249e" @@ -26647,6 +27230,16 @@ style-loader@^1.3.0: loader-utils "^2.0.0" schema-utils "^2.7.0" +style-loader@^3.3.1: + version "3.3.1" + resolved "https://registry.npmjs.org/style-loader/-/style-loader-3.3.1.tgz#057dfa6b3d4d7c7064462830f9113ed417d38575" + integrity sha512-GPcQ+LDJbrcxHORTRes6Jy2sfvK2kS6hpSfI/fXhPt+spVzxF6LJ1dHLN9zIGmVaaP044YKaIatFaufENRiDoQ== + +style-mod@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/style-mod/-/style-mod-4.0.0.tgz#97e7c2d68b592975f2ca7a63d0dd6fcacfe35a01" + integrity sha512-OPhtyEjyyN9x3nhPsu76f52yUGXiZcgvsrFVtvTkyGRQJ0XK+GPc6ov1z+lRpbeabka+MYEQxOYRnt5nF30aMw== + style-to-object@0.3.0, style-to-object@^0.3.0: version "0.3.0" resolved "https://registry.npmjs.org/style-to-object/-/style-to-object-0.3.0.tgz#b1b790d205991cc783801967214979ee19a76e46" @@ -26667,6 +27260,17 @@ stylis@^4.0.6: resolved "https://registry.npmjs.org/stylis/-/stylis-4.0.7.tgz#412a90c28079417f3d27c028035095e4232d2904" integrity sha512-OFFeUXFgwnGOKvEXaSv0D0KQ5ADP0n6g3SVONx6I/85JzNZ3u50FRwB3lVIk1QO2HNdI75tbVzc4Z66Gdp9voA== +subscriptions-transport-ws@^0.11.0: + version "0.11.0" + resolved "https://registry.npmjs.org/subscriptions-transport-ws/-/subscriptions-transport-ws-0.11.0.tgz#baf88f050cba51d52afe781de5e81b3c31f89883" + integrity sha512-8D4C6DIH5tGiAIpp5I0wD/xRlNiZAPGHygzCe7VzyzUoxHtawzjNAY9SUTXU05/EY2NMY9/9GF0ycizkXr1CWQ== + dependencies: + backo2 "^1.0.2" + eventemitter3 "^3.1.0" + iterall "^1.2.1" + symbol-observable "^1.0.4" + ws "^5.2.0 || ^6.0.0 || ^7.0.0" + subscriptions-transport-ws@^0.9.18, subscriptions-transport-ws@^0.9.19: version "0.9.19" resolved "https://registry.npmjs.org/subscriptions-transport-ws/-/subscriptions-transport-ws-0.9.19.tgz#10ca32f7e291d5ee8eb728b9c02e43c52606cdcf" @@ -26917,6 +27521,14 @@ sync-fetch@0.3.0: buffer "^5.7.0" node-fetch "^2.6.1" +sync-fetch@0.3.1: + version "0.3.1" + resolved "https://registry.npmjs.org/sync-fetch/-/sync-fetch-0.3.1.tgz#62aa82c4b4d43afd6906bfd7b5f92056458509f0" + integrity sha512-xj5qiCDap/03kpci5a+qc5wSJjc8ZSixgG2EUmH1B8Ea2sfWclQA7eH40hiHPCtkCn6MCk4Wb+dqcXdCy2PP3g== + dependencies: + buffer "^5.7.0" + node-fetch "^2.6.1" + table@^6.0.9: version "6.7.1" resolved "https://registry.npmjs.org/table/-/table-6.7.1.tgz#ee05592b7143831a8c94f3cee6aae4c1ccef33e2" @@ -27234,11 +27846,6 @@ throat@^5.0.0: resolved "https://registry.npmjs.org/throat/-/throat-5.0.0.tgz#c5199235803aad18754a667d659b5e72ce16764b" integrity sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA== -throttle-debounce@^2.0.1: - version "2.2.1" - resolved "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-2.2.1.tgz#fbd933ae6793448816f7d5b3cae259d464c98137" - integrity sha512-i9hAVld1f+woAiyNGqWelpDD5W1tpMroL3NofTz9xzwq6acWBlO2dC8k5EFSZepU6oOINtV5Q3aSPoRg7o4+fA== - throttle-debounce@^3.0.1: version "3.0.1" resolved "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-3.0.1.tgz#32f94d84dfa894f786c9a1f290e7a645b6a19abb" @@ -27462,6 +28069,13 @@ tr46@^2.0.2: dependencies: punycode "^2.1.1" +tr46@^2.1.0: + version "2.1.0" + resolved "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz#fa87aa81ca5d5941da8cbf1f9b749dc969a4e240" + integrity sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw== + 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" @@ -27880,6 +28494,16 @@ unbox-primitive@^1.0.0: has-symbols "^1.0.0" which-boxed-primitive "^1.0.1" +unbox-primitive@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz#085e215625ec3162574dc8859abee78a59b14471" + integrity sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw== + dependencies: + function-bind "^1.1.1" + has-bigints "^1.0.1" + has-symbols "^1.0.2" + which-boxed-primitive "^1.0.2" + unbzip2-stream@1.3.3: version "1.3.3" resolved "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.3.3.tgz#d156d205e670d8d8c393e1c02ebd506422873f6a" @@ -27905,6 +28529,11 @@ underscore@^1.12.1, underscore@^1.9.1: resolved "https://registry.npmjs.org/underscore/-/underscore-1.13.1.tgz#0c1c6bd2df54b6b69f2314066d65b6cde6fcf9d1" integrity sha512-hzSoAVtJF+3ZtiFX0VgfFPHEDRm7Y/QPjGyNo4TVdnDTdft3tr8hEkD25a1jC+TjTuE7tkHGKkhwCgs9dgBB2g== +undici@^4.9.3: + version "4.11.0" + resolved "https://registry.npmjs.org/undici/-/undici-4.11.0.tgz#41fb4f944704d77e1c9fb472d40d2dbece64ccf2" + integrity sha512-gofXRqAdm81rzaZgPbMf98qvrNGd3ptJ26+mCcF3EXoC817p//MtL8XcDpTvHUXxdW27rAM2jvTae+KyAchorw== + unfetch@^4.2.0: version "4.2.0" resolved "https://registry.npmjs.org/unfetch/-/unfetch-4.2.0.tgz#7e21b0ef7d363d8d9af0fb929a5555f6ef97a3be" @@ -28163,7 +28792,7 @@ universalify@^2.0.0: resolved "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== -unixify@1.0.0: +unixify@1.0.0, unixify@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/unixify/-/unixify-1.0.0.tgz#3a641c8c2ffbce4da683a5c70f03a462940c2090" integrity sha1-OmQcjC/7zk2mg6XHDwOkYpQMIJA= @@ -28338,6 +28967,13 @@ use-memo-one@^1.1.1: resolved "https://registry.npmjs.org/use-memo-one/-/use-memo-one-1.1.1.tgz#39e6f08fe27e422a7d7b234b5f9056af313bd22c" integrity sha512-oFfsyun+bP7RX8X2AskHNTxu+R3QdE/RC5IefMbqptmACAA/gfol1KDD5KRzPsGMa62sWxGZw+Ui43u6x4ddoQ== +use-resize-observer@^7.0.0: + version "7.1.0" + resolved "https://registry.npmjs.org/use-resize-observer/-/use-resize-observer-7.1.0.tgz#709ea7540fbe0a60ceae41ee2bef933d7782e4d4" + integrity sha512-6DGWOnZpjAGP/MtslGg7OunZptyueQduMi0i8DC5nVKXtJ8Bdt0wR/1tSxugFRndzYCi/jtD+SlNs5PK8ijvXQ== + dependencies: + "@juggle/resize-observer" "^3.3.1" + use@^3.1.0: version "3.1.1" resolved "https://registry.npmjs.org/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" @@ -28503,6 +29139,11 @@ validator@^8.0.0: resolved "https://registry.npmjs.org/validator/-/validator-8.2.0.tgz#3c1237290e37092355344fef78c231249dab77b9" integrity sha512-Yw5wW34fSv5spzTXNkokD6S6/Oq92d8q/t14TqsS3fAiA1RYnxSFSIZ+CY3n6PGGRCq5HhJTSepQvFUS2QUDxA== +value-or-promise@1.0.11: + version "1.0.11" + resolved "https://registry.npmjs.org/value-or-promise/-/value-or-promise-1.0.11.tgz#3e90299af31dd014fe843fe309cefa7c1d94b140" + integrity sha512-41BrgH+dIbCFXClcSapVs5M6GkENd3gQOJpEfPDNa71LsUGMXDL0jMWpI/Rh7WhX+Aalfz2TTS3Zt5pUsbnhLg== + value-or-promise@1.0.6: version "1.0.6" resolved "https://registry.npmjs.org/value-or-promise/-/value-or-promise-1.0.6.tgz#218aa4794aa2ee24dcf48a29aba4413ed584747f" @@ -28599,6 +29240,11 @@ vm-browserify@^1.0.1: resolved "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz#78641c488b8e6ca91a75f511e7a3b32a86e5dda0" integrity sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ== +vm2@^3.9.5: + version "3.9.5" + resolved "https://registry.npmjs.org/vm2/-/vm2-3.9.5.tgz#5288044860b4bbace443101fcd3bddb2a0aa2496" + integrity sha512-LuCAHZN75H9tdrAiLFf030oW7nJV5xwNMuk1ymOZwopmuK3d2H4L1Kv4+GFHgarKiLfXXLFU+7LDABHnwOkWng== + vscode-languageserver-types@^3.15.1: version "3.15.1" resolved "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.15.1.tgz#17be71d78d2f6236d414f0001ce1ef4d23e6b6de" @@ -28611,6 +29257,11 @@ w3c-hr-time@^1.0.2: dependencies: browser-process-hrtime "^1.0.0" +w3c-keyname@^2.2.4: + version "2.2.4" + resolved "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.4.tgz#4ade6916f6290224cdbd1db8ac49eab03d0eef6b" + integrity sha512-tOhfEwEzFLJzf6d1ZPkYfGj+FWhIpBux9ppoP3rlclw3Z0BZv3N7b7030Z1kYth+6rDuAsXUFr+d0VE6Ed1ikw== + w3c-xmlserializer@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz#3e7104a05b75146cc60f564380b7f683acf1020a" @@ -28940,7 +29591,16 @@ whatwg-url@^8.0.0, whatwg-url@^8.4.0: tr46 "^2.0.2" webidl-conversions "^6.1.0" -which-boxed-primitive@^1.0.1: +whatwg-url@^8.5.0: + version "8.7.0" + resolved "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.7.0.tgz#656a78e510ff8f3937bc0bcbe9f5c0ac35941b77" + integrity sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg== + dependencies: + lodash "^4.7.0" + tr46 "^2.1.0" + webidl-conversions "^6.1.0" + +which-boxed-primitive@^1.0.1, which-boxed-primitive@^1.0.2: version "1.0.2" resolved "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz#13757bc89b209b049fe5d86430e21cf40a89a8e6" integrity sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg== @@ -29177,6 +29837,11 @@ ws@7.4.6: resolved "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz#5654ca8ecdeee47c33a9a4bf6d28e2be2980377c" integrity sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A== +ws@8.3.0: + version "8.3.0" + resolved "https://registry.npmjs.org/ws/-/ws-8.3.0.tgz#7185e252c8973a60d57170175ff55fdbd116070d" + integrity sha512-Gs5EZtpqZzLvmIM59w4igITU57lrtYVFneaa434VROv4thzJyV6UjIL3D42lslWlI+D4KzLYnxSwtfuiO79sNw== + "ws@^5.2.0 || ^6.0.0 || ^7.0.0", ws@^7.2.3, ws@^7.3.1: version "7.5.0" resolved "https://registry.npmjs.org/ws/-/ws-7.5.0.tgz#0033bafea031fb9df041b2026fc72a571ca44691"