@backstage-community/plugin-catalog-backend-module-scaffolder-relation-processor 2.6.1 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @backstage-community/plugin-catalog-backend-module-scaffolder-relation-processor
2
2
 
3
+ ## 2.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c729182: Backstage version bump to v1.42.5
8
+
9
+ ## 2.7.0
10
+
11
+ ### Minor Changes
12
+
13
+ - a271cd6: Add notifications support for scaffolder relation processor to send notifications when template versions are updated. The plugin uses Backstage's notification system to alert users when scaffolder templates have new versions available. This helps teams stay informed about template updates and ensures they can take advantage of the latest improvements and fixes. The notification feature is disabled by default and can be enabled via config.
14
+
3
15
  ## 2.6.1
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Catalog Backend Module for Scaffolder Relation Catalog Processor
2
2
 
3
- This is an extension module to the catalog-backend plugin, providing an additional catalog entity processor that adds a new relation that depends on the `spec.scaffoldedFrom` field to link scaffolder templates and the catalog entities they generated.
3
+ This is an extension module to the catalog-backend plugin, providing an additional catalog entity processor that adds a new relation that depends on the `spec.scaffoldedFrom` field to link scaffolder templates and the catalog entities they generated. Additionally, it includes a notification feature that automatically alerts entity owners when their scaffolder templates are updated.
4
4
 
5
5
  ## Getting Started
6
6
 
@@ -10,11 +10,17 @@ This is an extension module to the catalog-backend plugin, providing an addition
10
10
  yarn workspace backend add @backstage-community/plugin-catalog-backend-module-scaffolder-relation-processor
11
11
  ```
12
12
 
13
+ **Note**: If you plan to use the notification feature, you will also need to install and configure the notifications backend plugin:
14
+
15
+ ```console
16
+ yarn workspace backend add @backstage/plugin-notifications-backend
17
+ ```
18
+
13
19
  ### Installing on the new backend system
14
20
 
15
21
  To install this module into the [new backend system](https://backstage.io/docs/backend-system/), add the following into the `packages/backend/src/index.ts` file:
16
22
 
17
- ```ts title="packages/backend/src/index.ts
23
+ ```ts title="packages/backend/src/index.ts"
18
24
  const backend = createBackend();
19
25
 
20
26
  // highlight-add-start
@@ -28,6 +34,13 @@ backend.add(
28
34
  backend.start();
29
35
  ```
30
36
 
37
+ **For notification feature support**, also add the notifications backend module:
38
+
39
+ ```ts title="packages/backend/src/index.ts"
40
+ // Add this import for notification support
41
+ backend.add(import('@backstage/plugin-notifications-backend'));
42
+ ```
43
+
31
44
  ### Usage
32
45
 
33
46
  Catalog entities containing the `spec.scaffoldedFrom` field will have a relation link be formed between it and the `template` corresponding to the entity ref in the `spec.scaffoldedFrom` field.
@@ -49,3 +62,58 @@ These relations should also appear on the `EntityCatalogGraphView` component fro
49
62
 
50
63
  ![scaffoldedFrom Relation YAML View](./docs/example-images/scaffoldedFromYAMLView.png)
51
64
  ![scaffoldedOf Relation YAML View](./docs/example-images/scaffolderOfYAMLView.png)
65
+
66
+ ## Template Update Notifications
67
+
68
+ This plugin includes a notification feature that automatically notifies entity owners when the scaffolder template used to create their entities has been updated to a new version. When a template update is detected, the plugin finds all entities that were scaffolded from that template (using the `spec.scaffoldedFrom` field) and notifies the owners of those entities.
69
+
70
+ ### Prerequisites
71
+
72
+ To use the notification feature, you need to have the [`@backstage/plugin-notifications-backend`](https://github.com/backstage/backstage/tree/master/plugins/notifications-backend) Backstage plugin installed and configured.
73
+
74
+ ### Configuration
75
+
76
+ Add the following configuration to your `app-config.yaml` to enable and customize the notification feature:
77
+
78
+ ```yaml
79
+ scaffolder:
80
+ notifications:
81
+ templateUpdate:
82
+ enabled: true # Set to false to disable notifications
83
+ ```
84
+
85
+ Or, if you also wish to configure the notification title and description with custom text:
86
+
87
+ ```yaml
88
+ scaffolder:
89
+ notifications:
90
+ templateUpdate:
91
+ enabled: true # Set to false to disable notifications
92
+ message:
93
+ title: 'Custom title for $ENTITY_DISPLAY_NAME'
94
+ description: 'Custom description'
95
+ ```
96
+
97
+ #### Configuration Options
98
+
99
+ - `enabled` (boolean): Whether to enable template update notifications. Default: `false`
100
+ - `message.title` (string): The notification title. Supports `$ENTITY_DISPLAY_NAME` template variable. Default: `'$ENTITY_DISPLAY_NAME is out of sync with template'`
101
+ - `message.description` (string): The notification description. Supports `$ENTITY_DISPLAY_NAME` template variable. Default: `'The template used to create $ENTITY_DISPLAY_NAME has been updated to a new version. Review and update your entity to stay in sync with the template.'`
102
+
103
+ #### Template Variables
104
+
105
+ Both the title and description support the following template variables:
106
+
107
+ - `$ENTITY_DISPLAY_NAME`: The title (or name, in case title does not exist) of the entity that was scaffolded from the updated template
108
+
109
+ ### Example Notification Flow
110
+
111
+ 1. A scaffolder template `template:default/my-service-template` is updated from version `1.0.0` to `1.1.0`
112
+ 2. The plugin detects this version change and emits a `relationProcessor.template:version_updated` event
113
+ 3. The plugin queries the catalog for all entities with `spec.scaffoldedFrom: 'template:default/my-service-template'`
114
+ 4. For each found entity, notifications are sent to all entities listed in the `ownedBy` relations
115
+ 5. The notification includes a link to the entity's catalog page and the configured message
116
+
117
+ ### Disabling Notifications
118
+
119
+ To disable the notification feature, set `scaffolder.notifications.templateUpdate.enabled` to `false` in your configuration, or simply omit the entire `scaffolder.notifications.templateUpdate` section from your config (notifications are disabled by default).
package/config.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /*
2
+ * Copyright 2025 The Backstage Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export interface Config {
17
+ scaffolder?: {
18
+ /**
19
+ * Configuration for notifications
20
+ * @visibility frontend
21
+ */
22
+ notifications?: {
23
+ /**
24
+ * Configuration for template update notifications
25
+ * @visibility frontend
26
+ */
27
+ templateUpdate?: {
28
+ /**
29
+ * Whether to enable template update notifications
30
+ * @default false
31
+ * @visibility frontend
32
+ */
33
+ enabled?: boolean;
34
+ /**
35
+ * Custom message configuration for notifications
36
+ * @visibility frontend
37
+ */
38
+ message?: {
39
+ /**
40
+ * The notification title. Supports $ENTITY_DISPLAY_NAME template variable.
41
+ * @default '$ENTITY_DISPLAY_NAME is out of sync with template'
42
+ * @visibility frontend
43
+ */
44
+ title?: string;
45
+ /**
46
+ * The notification description. Supports $ENTITY_DISPLAY_NAME template variable.
47
+ * @default 'The template used to create $ENTITY_DISPLAY_NAME has been updated to a new version. Review and update your entity to stay in sync with the template.'
48
+ * @visibility frontend
49
+ */
50
+ description?: string;
51
+ };
52
+ };
53
+ };
54
+ };
55
+ }
@@ -3,11 +3,32 @@
3
3
  var catalogModel = require('@backstage/catalog-model');
4
4
  var pluginCatalogNode = require('@backstage/plugin-catalog-node');
5
5
  var relations = require('./relations.cjs.js');
6
+ var templateVersionUtils = require('./templateVersionUtils.cjs.js');
6
7
 
7
8
  class ScaffolderRelationEntityProcessor {
9
+ constructor(eventsService) {
10
+ this.eventsService = eventsService;
11
+ }
8
12
  getProcessorName() {
9
13
  return "ScaffolderRelationEntityProcessor";
10
14
  }
15
+ async preProcessEntity(entity, _location, _emit, _originLocation, cache) {
16
+ if (entity.kind !== "Template") {
17
+ return entity;
18
+ }
19
+ const currentVersion = entity.metadata.annotations?.["backstage.io/template-version"];
20
+ if (!currentVersion) {
21
+ return entity;
22
+ }
23
+ const entityRef = catalogModel.stringifyEntityRef(entity);
24
+ await templateVersionUtils.handleTemplateVersion(
25
+ entityRef,
26
+ currentVersion,
27
+ cache,
28
+ this.eventsService
29
+ );
30
+ return entity;
31
+ }
11
32
  async postProcessEntity(entity, _location, emit) {
12
33
  const selfRef = catalogModel.getCompoundEntityRef(entity);
13
34
  function doEmit(targets, context, outgoingRelation, incomingRelation) {
@@ -1 +1 @@
1
- {"version":3,"file":"ScaffolderRelationEntityProcessor.cjs.js","sources":["../src/ScaffolderRelationEntityProcessor.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Entity,\n getCompoundEntityRef,\n parseEntityRef,\n} from '@backstage/catalog-model';\nimport type { LocationSpec } from '@backstage/plugin-catalog-common';\nimport {\n CatalogProcessor,\n CatalogProcessorEmit,\n processingResult,\n} from '@backstage/plugin-catalog-node';\n\nimport { RELATION_SCAFFOLDED_FROM, RELATION_SCAFFOLDER_OF } from './relations';\nimport type { ScaffoldedFromSpec } from './types';\n\n/** @public */\nexport class ScaffolderRelationEntityProcessor implements CatalogProcessor {\n getProcessorName(): string {\n return 'ScaffolderRelationEntityProcessor';\n }\n\n async postProcessEntity(\n entity: Entity,\n _location: LocationSpec,\n emit: CatalogProcessorEmit,\n ): Promise<Entity> {\n const selfRef = getCompoundEntityRef(entity);\n\n /**\n * Utilities\n */\n function doEmit(\n targets: string | string[] | undefined,\n context: { defaultKind?: string; defaultNamespace: string },\n outgoingRelation: string,\n incomingRelation: string,\n ): void {\n if (!targets) {\n return;\n }\n for (const target of [targets].flat()) {\n const targetRef = parseEntityRef(target, context);\n emit(\n processingResult.relation({\n source: selfRef,\n type: outgoingRelation,\n target: {\n kind: targetRef.kind,\n namespace: targetRef.namespace,\n name: targetRef.name,\n },\n }),\n );\n emit(\n processingResult.relation({\n source: {\n kind: targetRef.kind,\n namespace: targetRef.namespace,\n name: targetRef.name,\n },\n type: incomingRelation,\n target: selfRef,\n }),\n );\n }\n }\n\n /**\n * Emit relations for entities generated by templates (can be any entity type)\n */\n const arbitraryEntity = entity as Entity & Partial<ScaffoldedFromSpec>;\n doEmit(\n arbitraryEntity.spec?.scaffoldedFrom,\n { defaultKind: 'Template', defaultNamespace: selfRef.namespace },\n RELATION_SCAFFOLDED_FROM,\n RELATION_SCAFFOLDER_OF,\n );\n return entity;\n }\n}\n"],"names":["getCompoundEntityRef","parseEntityRef","processingResult","RELATION_SCAFFOLDED_FROM","RELATION_SCAFFOLDER_OF"],"mappings":";;;;;;AA+BO,MAAM,iCAA8D,CAAA;AAAA,EACzE,gBAA2B,GAAA;AACzB,IAAO,OAAA,mCAAA;AAAA;AACT,EAEA,MAAM,iBAAA,CACJ,MACA,EAAA,SAAA,EACA,IACiB,EAAA;AACjB,IAAM,MAAA,OAAA,GAAUA,kCAAqB,MAAM,CAAA;AAK3C,IAAA,SAAS,MACP,CAAA,OAAA,EACA,OACA,EAAA,gBAAA,EACA,gBACM,EAAA;AACN,MAAA,IAAI,CAAC,OAAS,EAAA;AACZ,QAAA;AAAA;AAEF,MAAA,KAAA,MAAW,MAAU,IAAA,CAAC,OAAO,CAAA,CAAE,MAAQ,EAAA;AACrC,QAAM,MAAA,SAAA,GAAYC,2BAAe,CAAA,MAAA,EAAQ,OAAO,CAAA;AAChD,QAAA,IAAA;AAAA,UACEC,mCAAiB,QAAS,CAAA;AAAA,YACxB,MAAQ,EAAA,OAAA;AAAA,YACR,IAAM,EAAA,gBAAA;AAAA,YACN,MAAQ,EAAA;AAAA,cACN,MAAM,SAAU,CAAA,IAAA;AAAA,cAChB,WAAW,SAAU,CAAA,SAAA;AAAA,cACrB,MAAM,SAAU,CAAA;AAAA;AAClB,WACD;AAAA,SACH;AACA,QAAA,IAAA;AAAA,UACEA,mCAAiB,QAAS,CAAA;AAAA,YACxB,MAAQ,EAAA;AAAA,cACN,MAAM,SAAU,CAAA,IAAA;AAAA,cAChB,WAAW,SAAU,CAAA,SAAA;AAAA,cACrB,MAAM,SAAU,CAAA;AAAA,aAClB;AAAA,YACA,IAAM,EAAA,gBAAA;AAAA,YACN,MAAQ,EAAA;AAAA,WACT;AAAA,SACH;AAAA;AACF;AAMF,IAAA,MAAM,eAAkB,GAAA,MAAA;AACxB,IAAA,MAAA;AAAA,MACE,gBAAgB,IAAM,EAAA,cAAA;AAAA,MACtB,EAAE,WAAA,EAAa,UAAY,EAAA,gBAAA,EAAkB,QAAQ,SAAU,EAAA;AAAA,MAC/DC,kCAAA;AAAA,MACAC;AAAA,KACF;AACA,IAAO,OAAA,MAAA;AAAA;AAEX;;;;"}
1
+ {"version":3,"file":"ScaffolderRelationEntityProcessor.cjs.js","sources":["../src/ScaffolderRelationEntityProcessor.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Entity,\n getCompoundEntityRef,\n parseEntityRef,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport type { LocationSpec } from '@backstage/plugin-catalog-common';\nimport {\n CatalogProcessor,\n CatalogProcessorCache,\n CatalogProcessorEmit,\n processingResult,\n} from '@backstage/plugin-catalog-node';\nimport type { EventsService } from '@backstage/plugin-events-node';\n\nimport { RELATION_SCAFFOLDED_FROM, RELATION_SCAFFOLDER_OF } from './relations';\nimport type { ScaffoldedFromSpec } from './types';\nimport { handleTemplateVersion } from './templateVersionUtils';\n\n/** @public */\nexport class ScaffolderRelationEntityProcessor implements CatalogProcessor {\n constructor(private readonly eventsService?: EventsService) {}\n\n getProcessorName(): string {\n return 'ScaffolderRelationEntityProcessor';\n }\n\n async preProcessEntity(\n entity: Entity,\n _location: LocationSpec,\n _emit: CatalogProcessorEmit,\n _originLocation: LocationSpec,\n cache: CatalogProcessorCache,\n ): Promise<Entity> {\n if (entity.kind !== 'Template') {\n return entity;\n }\n\n const currentVersion =\n entity.metadata.annotations?.['backstage.io/template-version'];\n if (!currentVersion) {\n return entity;\n }\n\n const entityRef = stringifyEntityRef(entity);\n\n await handleTemplateVersion(\n entityRef,\n currentVersion,\n cache,\n this.eventsService,\n );\n\n return entity;\n }\n\n async postProcessEntity(\n entity: Entity,\n _location: LocationSpec,\n emit: CatalogProcessorEmit,\n ): Promise<Entity> {\n const selfRef = getCompoundEntityRef(entity);\n\n /**\n * Utilities\n */\n function doEmit(\n targets: string | string[] | undefined,\n context: { defaultKind?: string; defaultNamespace: string },\n outgoingRelation: string,\n incomingRelation: string,\n ): void {\n if (!targets) {\n return;\n }\n for (const target of [targets].flat()) {\n const targetRef = parseEntityRef(target, context);\n emit(\n processingResult.relation({\n source: selfRef,\n type: outgoingRelation,\n target: {\n kind: targetRef.kind,\n namespace: targetRef.namespace,\n name: targetRef.name,\n },\n }),\n );\n emit(\n processingResult.relation({\n source: {\n kind: targetRef.kind,\n namespace: targetRef.namespace,\n name: targetRef.name,\n },\n type: incomingRelation,\n target: selfRef,\n }),\n );\n }\n }\n\n /**\n * Emit relations for entities generated by templates (can be any entity type)\n */\n const arbitraryEntity = entity as Entity & Partial<ScaffoldedFromSpec>;\n doEmit(\n arbitraryEntity.spec?.scaffoldedFrom,\n { defaultKind: 'Template', defaultNamespace: selfRef.namespace },\n RELATION_SCAFFOLDED_FROM,\n RELATION_SCAFFOLDER_OF,\n );\n return entity;\n }\n}\n"],"names":["stringifyEntityRef","handleTemplateVersion","getCompoundEntityRef","parseEntityRef","processingResult","RELATION_SCAFFOLDED_FROM","RELATION_SCAFFOLDER_OF"],"mappings":";;;;;;;AAmCO,MAAM,iCAA8D,CAAA;AAAA,EACzE,YAA6B,aAA+B,EAAA;AAA/B,IAAA,IAAA,CAAA,aAAA,GAAA,aAAA;AAAA;AAAgC,EAE7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,mCAAiB,QAAS,CAAA;AAAA,YACxB,MAAQ,EAAA;AAAA,cACN,MAAM,SAAU,CAAA,IAAA;AAAA,cAChB,WAAW,SAAU,CAAA,SAAA;AAAA,cACrB,MAAM,SAAU,CAAA;AAAA,aAClB;AAAA,YACA,IAAM,EAAA,gBAAA;AAAA,YACN,MAAQ,EAAA;AAAA,WACT;AAAA,SACH;AAAA;AACF;AAMF,IAAA,MAAM,eAAkB,GAAA,MAAA;AACxB,IAAA,MAAA;AAAA,MACE,gBAAgB,IAAM,EAAA,cAAA;AAAA,MACtB,EAAE,WAAA,EAAa,UAAY,EAAA,gBAAA,EAAkB,QAAQ,SAAU,EAAA;AAAA,MAC/DC,kCAAA;AAAA,MACAC;AAAA,KACF;AACA,IAAO,OAAA,MAAA;AAAA;AAEX;;;;"}
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ const TEMPLATE_VERSION_UPDATED_TOPIC = "relationProcessor.template:version_updated";
4
+ const ENTITY_DISPLAY_NAME_TEMPLATE_VAR = "$ENTITY_DISPLAY_NAME";
5
+ const DEFAULT_NOTIFICATION_TITLE = `${ENTITY_DISPLAY_NAME_TEMPLATE_VAR} is out of sync with template`;
6
+ const DEFAULT_NOTIFICATION_DESCRIPTION = `The template used to create ${ENTITY_DISPLAY_NAME_TEMPLATE_VAR} has been updated to a new version. Review and update your entity to stay in sync with the template.`;
7
+ const DEFAULT_NOTIFICATION_ENABLED = false;
8
+
9
+ exports.DEFAULT_NOTIFICATION_DESCRIPTION = DEFAULT_NOTIFICATION_DESCRIPTION;
10
+ exports.DEFAULT_NOTIFICATION_ENABLED = DEFAULT_NOTIFICATION_ENABLED;
11
+ exports.DEFAULT_NOTIFICATION_TITLE = DEFAULT_NOTIFICATION_TITLE;
12
+ exports.ENTITY_DISPLAY_NAME_TEMPLATE_VAR = ENTITY_DISPLAY_NAME_TEMPLATE_VAR;
13
+ exports.TEMPLATE_VERSION_UPDATED_TOPIC = TEMPLATE_VERSION_UPDATED_TOPIC;
14
+ //# sourceMappingURL=constants.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.cjs.js","sources":["../src/constants.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Topic for template version update events\n *\n * @public\n */\nexport const TEMPLATE_VERSION_UPDATED_TOPIC =\n 'relationProcessor.template:version_updated';\n\n/**\n * Template variable name for entity name in notification messages\n *\n * @public\n */\nexport const ENTITY_DISPLAY_NAME_TEMPLATE_VAR = '$ENTITY_DISPLAY_NAME';\n\n/**\n * Default template update notification title\n *\n * @public\n */\nexport const DEFAULT_NOTIFICATION_TITLE = `${ENTITY_DISPLAY_NAME_TEMPLATE_VAR} is out of sync with template`;\n\n/**\n * Default template update notification description\n *\n * @public\n */\nexport const DEFAULT_NOTIFICATION_DESCRIPTION = `The template used to create ${ENTITY_DISPLAY_NAME_TEMPLATE_VAR} has been updated to a new version. Review and update your entity to stay in sync with the template.`;\n\n/**\n * Default notification enabled\n *\n * @public\n */\nexport const DEFAULT_NOTIFICATION_ENABLED = false;\n"],"names":[],"mappings":";;AAqBO,MAAM,8BACX,GAAA;AAOK,MAAM,gCAAmC,GAAA;AAOnC,MAAA,0BAAA,GAA6B,GAAG,gCAAgC,CAAA,6BAAA;AAOhE,MAAA,gCAAA,GAAmC,+BAA+B,gCAAgC,CAAA,oGAAA;AAOxG,MAAM,4BAA+B,GAAA;;;;;;;;"}
package/dist/index.cjs.js CHANGED
@@ -3,6 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var relations = require('./relations.cjs.js');
6
+ var constants = require('./constants.cjs.js');
6
7
  var module$1 = require('./module.cjs.js');
7
8
  var ScaffolderRelationEntityProcessor = require('./ScaffolderRelationEntityProcessor.cjs.js');
8
9
 
@@ -10,6 +11,11 @@ var ScaffolderRelationEntityProcessor = require('./ScaffolderRelationEntityProce
10
11
 
11
12
  exports.RELATION_SCAFFOLDED_FROM = relations.RELATION_SCAFFOLDED_FROM;
12
13
  exports.RELATION_SCAFFOLDER_OF = relations.RELATION_SCAFFOLDER_OF;
14
+ exports.DEFAULT_NOTIFICATION_DESCRIPTION = constants.DEFAULT_NOTIFICATION_DESCRIPTION;
15
+ exports.DEFAULT_NOTIFICATION_ENABLED = constants.DEFAULT_NOTIFICATION_ENABLED;
16
+ exports.DEFAULT_NOTIFICATION_TITLE = constants.DEFAULT_NOTIFICATION_TITLE;
17
+ exports.ENTITY_DISPLAY_NAME_TEMPLATE_VAR = constants.ENTITY_DISPLAY_NAME_TEMPLATE_VAR;
18
+ exports.TEMPLATE_VERSION_UPDATED_TOPIC = constants.TEMPLATE_VERSION_UPDATED_TOPIC;
13
19
  exports.default = module$1.catalogModuleScaffolderRelationProcessor;
14
20
  exports.ScaffolderRelationEntityProcessor = ScaffolderRelationEntityProcessor.ScaffolderRelationEntityProcessor;
15
21
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;"}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
2
2
  import { Entity } from '@backstage/catalog-model';
3
3
  import { LocationSpec } from '@backstage/plugin-catalog-common';
4
- import { CatalogProcessor, CatalogProcessorEmit } from '@backstage/plugin-catalog-node';
4
+ import { CatalogProcessor, CatalogProcessorEmit, CatalogProcessorCache } from '@backstage/plugin-catalog-node';
5
+ import { EventsService } from '@backstage/plugin-events-node';
5
6
 
6
7
  /**
7
8
  * A relation from a scaffolder template entity to the entity it generated.
@@ -29,6 +30,53 @@ type ScaffoldedFromSpec = {
29
30
  scaffoldedFrom: string;
30
31
  };
31
32
  };
33
+ /**
34
+ * Configuration interface for scaffolder relation processor notifications
35
+ *
36
+ * @public
37
+ */
38
+ interface ScaffolderRelationProcessorConfig {
39
+ notifications?: {
40
+ templateUpdate?: {
41
+ enabled: boolean;
42
+ message: {
43
+ title: string;
44
+ description: string;
45
+ };
46
+ };
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Topic for template version update events
52
+ *
53
+ * @public
54
+ */
55
+ declare const TEMPLATE_VERSION_UPDATED_TOPIC = "relationProcessor.template:version_updated";
56
+ /**
57
+ * Template variable name for entity name in notification messages
58
+ *
59
+ * @public
60
+ */
61
+ declare const ENTITY_DISPLAY_NAME_TEMPLATE_VAR = "$ENTITY_DISPLAY_NAME";
62
+ /**
63
+ * Default template update notification title
64
+ *
65
+ * @public
66
+ */
67
+ declare const DEFAULT_NOTIFICATION_TITLE = "$ENTITY_DISPLAY_NAME is out of sync with template";
68
+ /**
69
+ * Default template update notification description
70
+ *
71
+ * @public
72
+ */
73
+ declare const DEFAULT_NOTIFICATION_DESCRIPTION = "The template used to create $ENTITY_DISPLAY_NAME has been updated to a new version. Review and update your entity to stay in sync with the template.";
74
+ /**
75
+ * Default notification enabled
76
+ *
77
+ * @public
78
+ */
79
+ declare const DEFAULT_NOTIFICATION_ENABLED = false;
32
80
 
33
81
  /**
34
82
  * Catalog processor that adds link relation between scaffolder templates and their generated entities
@@ -39,8 +87,11 @@ declare const catalogModuleScaffolderRelationProcessor: _backstage_backend_plugi
39
87
 
40
88
  /** @public */
41
89
  declare class ScaffolderRelationEntityProcessor implements CatalogProcessor {
90
+ private readonly eventsService?;
91
+ constructor(eventsService?: EventsService | undefined);
42
92
  getProcessorName(): string;
93
+ preProcessEntity(entity: Entity, _location: LocationSpec, _emit: CatalogProcessorEmit, _originLocation: LocationSpec, cache: CatalogProcessorCache): Promise<Entity>;
43
94
  postProcessEntity(entity: Entity, _location: LocationSpec, emit: CatalogProcessorEmit): Promise<Entity>;
44
95
  }
45
96
 
46
- export { RELATION_SCAFFOLDED_FROM, RELATION_SCAFFOLDER_OF, type ScaffoldedFromSpec, ScaffolderRelationEntityProcessor, catalogModuleScaffolderRelationProcessor as default };
97
+ export { DEFAULT_NOTIFICATION_DESCRIPTION, DEFAULT_NOTIFICATION_ENABLED, DEFAULT_NOTIFICATION_TITLE, ENTITY_DISPLAY_NAME_TEMPLATE_VAR, RELATION_SCAFFOLDED_FROM, RELATION_SCAFFOLDER_OF, type ScaffoldedFromSpec, ScaffolderRelationEntityProcessor, type ScaffolderRelationProcessorConfig, TEMPLATE_VERSION_UPDATED_TOPIC, catalogModuleScaffolderRelationProcessor as default };
@@ -2,7 +2,12 @@
2
2
 
3
3
  var backendPluginApi = require('@backstage/backend-plugin-api');
4
4
  var alpha = require('@backstage/plugin-catalog-node/alpha');
5
+ var pluginEventsNode = require('@backstage/plugin-events-node');
6
+ var pluginNotificationsNode = require('@backstage/plugin-notifications-node');
7
+ var catalogClient = require('@backstage/catalog-client');
5
8
  var ScaffolderRelationEntityProcessor = require('./ScaffolderRelationEntityProcessor.cjs.js');
9
+ var templateVersionUtils = require('./templateVersionUtils.cjs.js');
10
+ var constants = require('./constants.cjs.js');
6
11
 
7
12
  const catalogModuleScaffolderRelationProcessor = backendPluginApi.createBackendModule({
8
13
  pluginId: "catalog",
@@ -11,13 +16,47 @@ const catalogModuleScaffolderRelationProcessor = backendPluginApi.createBackendM
11
16
  env.registerInit({
12
17
  deps: {
13
18
  catalog: alpha.catalogProcessingExtensionPoint,
14
- logger: backendPluginApi.coreServices.logger
19
+ logger: backendPluginApi.coreServices.logger,
20
+ config: backendPluginApi.coreServices.rootConfig,
21
+ events: pluginEventsNode.eventsServiceRef,
22
+ notifications: pluginNotificationsNode.notificationService,
23
+ auth: backendPluginApi.coreServices.auth,
24
+ discovery: backendPluginApi.coreServices.discovery
15
25
  },
16
- async init({ catalog, logger }) {
26
+ async init({
27
+ catalog,
28
+ logger,
29
+ config,
30
+ events,
31
+ notifications,
32
+ auth,
33
+ discovery
34
+ }) {
17
35
  logger.debug(
18
36
  "Registering the scaffolder-relation-processor catalog module"
19
37
  );
20
- catalog.addProcessor(new ScaffolderRelationEntityProcessor.ScaffolderRelationEntityProcessor());
38
+ const processorConfig = templateVersionUtils.readScaffolderRelationProcessorConfig(config);
39
+ const catalogClient$1 = new catalogClient.CatalogClient({ discoveryApi: discovery });
40
+ if (processorConfig.notifications?.templateUpdate?.enabled) {
41
+ await events.subscribe({
42
+ id: "scaffolder-relation-processor",
43
+ topics: [constants.TEMPLATE_VERSION_UPDATED_TOPIC],
44
+ async onEvent(params) {
45
+ const payload = params.eventPayload;
46
+ logger.info(
47
+ `Received template update event for ${payload.entityRef}: ${payload.previousVersion} -> ${payload.currentVersion}`
48
+ );
49
+ templateVersionUtils.handleTemplateUpdateNotifications(
50
+ catalogClient$1,
51
+ notifications,
52
+ auth,
53
+ processorConfig,
54
+ payload
55
+ );
56
+ }
57
+ });
58
+ }
59
+ catalog.addProcessor(new ScaffolderRelationEntityProcessor.ScaffolderRelationEntityProcessor(events));
21
60
  }
22
61
  });
23
62
  }
@@ -1 +1 @@
1
- {"version":3,"file":"module.cjs.js","sources":["../src/module.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n coreServices,\n createBackendModule,\n} from '@backstage/backend-plugin-api';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node/alpha';\n\nimport { ScaffolderRelationEntityProcessor } from './ScaffolderRelationEntityProcessor';\n\n/**\n * Catalog processor that adds link relation between scaffolder templates and their generated entities\n *\n * @public\n */\nexport const catalogModuleScaffolderRelationProcessor = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'scaffolder-relation-processor',\n register(env) {\n env.registerInit({\n deps: {\n catalog: catalogProcessingExtensionPoint,\n logger: coreServices.logger,\n },\n async init({ catalog, logger }) {\n logger.debug(\n 'Registering the scaffolder-relation-processor catalog module',\n );\n catalog.addProcessor(new ScaffolderRelationEntityProcessor());\n },\n });\n },\n});\n"],"names":["createBackendModule","catalogProcessingExtensionPoint","coreServices","ScaffolderRelationEntityProcessor"],"mappings":";;;;;;AA4BO,MAAM,2CAA2CA,oCAAoB,CAAA;AAAA,EAC1E,QAAU,EAAA,SAAA;AAAA,EACV,QAAU,EAAA,+BAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,OAAS,EAAAC,qCAAA;AAAA,QACT,QAAQC,6BAAa,CAAA;AAAA,OACvB;AAAA,MACA,MAAM,IAAA,CAAK,EAAE,OAAA,EAAS,QAAU,EAAA;AAC9B,QAAO,MAAA,CAAA,KAAA;AAAA,UACL;AAAA,SACF;AACA,QAAQ,OAAA,CAAA,YAAA,CAAa,IAAIC,mEAAA,EAAmC,CAAA;AAAA;AAC9D,KACD,CAAA;AAAA;AAEL,CAAC;;;;"}
1
+ {"version":3,"file":"module.cjs.js","sources":["../src/module.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n coreServices,\n createBackendModule,\n} from '@backstage/backend-plugin-api';\nimport { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node/alpha';\nimport { eventsServiceRef } from '@backstage/plugin-events-node';\nimport { notificationService } from '@backstage/plugin-notifications-node';\nimport { CatalogClient } from '@backstage/catalog-client';\n\nimport { ScaffolderRelationEntityProcessor } from './ScaffolderRelationEntityProcessor';\nimport { handleTemplateUpdateNotifications } from './templateVersionUtils';\nimport { readScaffolderRelationProcessorConfig } from './templateVersionUtils';\nimport { TEMPLATE_VERSION_UPDATED_TOPIC } from './constants';\n\n/**\n * Catalog processor that adds link relation between scaffolder templates and their generated entities\n *\n * @public\n */\nexport const catalogModuleScaffolderRelationProcessor = createBackendModule({\n pluginId: 'catalog',\n moduleId: 'scaffolder-relation-processor',\n register(env) {\n env.registerInit({\n deps: {\n catalog: catalogProcessingExtensionPoint,\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n events: eventsServiceRef,\n notifications: notificationService,\n auth: coreServices.auth,\n discovery: coreServices.discovery,\n },\n async init({\n catalog,\n logger,\n config,\n events,\n notifications,\n auth,\n discovery,\n }) {\n logger.debug(\n 'Registering the scaffolder-relation-processor catalog module',\n );\n\n const processorConfig = readScaffolderRelationProcessorConfig(config);\n\n const catalogClient = new CatalogClient({ discoveryApi: discovery });\n\n // Only subscribe to events if notifications are enabled\n if (processorConfig.notifications?.templateUpdate?.enabled) {\n await events.subscribe({\n id: 'scaffolder-relation-processor',\n topics: [TEMPLATE_VERSION_UPDATED_TOPIC],\n async onEvent(params) {\n const payload = params.eventPayload as {\n entityRef: string;\n previousVersion: string;\n currentVersion: string;\n };\n\n logger.info(\n `Received template update event for ${payload.entityRef}: ` +\n `${payload.previousVersion} -> ${payload.currentVersion}`,\n );\n\n handleTemplateUpdateNotifications(\n catalogClient,\n notifications,\n auth,\n processorConfig,\n payload,\n );\n },\n });\n }\n\n catalog.addProcessor(new ScaffolderRelationEntityProcessor(events));\n },\n });\n },\n});\n"],"names":["createBackendModule","catalogProcessingExtensionPoint","coreServices","eventsServiceRef","notificationService","readScaffolderRelationProcessorConfig","catalogClient","CatalogClient","TEMPLATE_VERSION_UPDATED_TOPIC","handleTemplateUpdateNotifications","ScaffolderRelationEntityProcessor"],"mappings":";;;;;;;;;;;AAkCO,MAAM,2CAA2CA,oCAAoB,CAAA;AAAA,EAC1E,QAAU,EAAA,SAAA;AAAA,EACV,QAAU,EAAA,+BAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,OAAS,EAAAC,qCAAA;AAAA,QACT,QAAQC,6BAAa,CAAA,MAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,QACrB,MAAQ,EAAAC,iCAAA;AAAA,QACR,aAAe,EAAAC,2CAAA;AAAA,QACf,MAAMF,6BAAa,CAAA,IAAA;AAAA,QACnB,WAAWA,6BAAa,CAAA;AAAA,OAC1B;AAAA,MACA,MAAM,IAAK,CAAA;AAAA,QACT,OAAA;AAAA,QACA,MAAA;AAAA,QACA,MAAA;AAAA,QACA,MAAA;AAAA,QACA,aAAA;AAAA,QACA,IAAA;AAAA,QACA;AAAA,OACC,EAAA;AACD,QAAO,MAAA,CAAA,KAAA;AAAA,UACL;AAAA,SACF;AAEA,QAAM,MAAA,eAAA,GAAkBG,2DAAsC,MAAM,CAAA;AAEpE,QAAA,MAAMC,kBAAgB,IAAIC,2BAAA,CAAc,EAAE,YAAA,EAAc,WAAW,CAAA;AAGnE,QAAI,IAAA,eAAA,CAAgB,aAAe,EAAA,cAAA,EAAgB,OAAS,EAAA;AAC1D,UAAA,MAAM,OAAO,SAAU,CAAA;AAAA,YACrB,EAAI,EAAA,+BAAA;AAAA,YACJ,MAAA,EAAQ,CAACC,wCAA8B,CAAA;AAAA,YACvC,MAAM,QAAQ,MAAQ,EAAA;AACpB,cAAA,MAAM,UAAU,MAAO,CAAA,YAAA;AAMvB,cAAO,MAAA,CAAA,IAAA;AAAA,gBACL,CAAA,mCAAA,EAAsC,QAAQ,SAAS,CAAA,EAAA,EAClD,QAAQ,eAAe,CAAA,IAAA,EAAO,QAAQ,cAAc,CAAA;AAAA,eAC3D;AAEA,cAAAC,sDAAA;AAAA,gBACEH,eAAA;AAAA,gBACA,aAAA;AAAA,gBACA,IAAA;AAAA,gBACA,eAAA;AAAA,gBACA;AAAA,eACF;AAAA;AACF,WACD,CAAA;AAAA;AAGH,QAAA,OAAA,CAAQ,YAAa,CAAA,IAAII,mEAAkC,CAAA,MAAM,CAAC,CAAA;AAAA;AACpE,KACD,CAAA;AAAA;AAEL,CAAC;;;;"}
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+
3
+ var constants = require('./constants.cjs.js');
4
+
5
+ async function handleTemplateVersion(entityRef, currentVersion, cache, eventsService) {
6
+ const cacheKey = `template-version-${entityRef}`;
7
+ const cachedData = await cache.get(cacheKey);
8
+ if (cachedData && cachedData.version < currentVersion) {
9
+ if (eventsService) {
10
+ await eventsService.publish({
11
+ topic: constants.TEMPLATE_VERSION_UPDATED_TOPIC,
12
+ eventPayload: {
13
+ entityRef,
14
+ previousVersion: cachedData.version,
15
+ currentVersion
16
+ }
17
+ });
18
+ }
19
+ }
20
+ await cache.set(cacheKey, {
21
+ version: currentVersion
22
+ });
23
+ }
24
+ function createEntityCatalogUrl(entity) {
25
+ const namespace = entity.metadata.namespace || "default";
26
+ const encodedNamespace = encodeURIComponent(namespace.toLowerCase());
27
+ const encodedKind = encodeURIComponent(entity.kind.toLowerCase());
28
+ const encodedName = encodeURIComponent(entity.metadata.name.toLowerCase());
29
+ return `/catalog/${encodedNamespace}/${encodedKind}/${encodedName}`;
30
+ }
31
+ async function sendNotificationsToOwners(notifications, entities, config) {
32
+ for (const entity of entities) {
33
+ const ownedByRelations = entity.relations?.filter((rel) => rel.type === "ownedBy") || [];
34
+ for (const relation of ownedByRelations) {
35
+ const recipients = {
36
+ type: "entity",
37
+ entityRef: relation.targetRef
38
+ };
39
+ const catalogUrl = createEntityCatalogUrl(entity);
40
+ const entityName = entity.metadata.title ?? entity.metadata.name;
41
+ const entityNameRegex = new RegExp(
42
+ constants.ENTITY_DISPLAY_NAME_TEMPLATE_VAR.replace(/\$/g, "\\$"),
43
+ "g"
44
+ );
45
+ const titleReplaced = config.notifications?.templateUpdate?.message.title.replace(
46
+ entityNameRegex,
47
+ entityName
48
+ ) || "";
49
+ const title = titleReplaced.charAt(0).toUpperCase() + titleReplaced.slice(1);
50
+ const description = config.notifications?.templateUpdate?.message.description.replace(
51
+ entityNameRegex,
52
+ entityName
53
+ ) || "";
54
+ const notificationPayload = {
55
+ title,
56
+ description,
57
+ link: catalogUrl
58
+ };
59
+ await notifications.send({
60
+ recipients,
61
+ payload: notificationPayload
62
+ });
63
+ }
64
+ }
65
+ }
66
+ async function handleTemplateUpdateNotifications(catalogClient, notifications, auth, processorConfig, payload) {
67
+ const { token } = await auth.getPluginRequestToken({
68
+ onBehalfOf: await auth.getOwnServiceCredentials(),
69
+ targetPluginId: "catalog"
70
+ });
71
+ const scaffoldedEntities = await catalogClient.getEntities(
72
+ {
73
+ filter: { "spec.scaffoldedFrom": payload.entityRef },
74
+ fields: [
75
+ "kind",
76
+ "metadata.namespace",
77
+ "metadata.name",
78
+ "metadata.title",
79
+ "relations"
80
+ ]
81
+ },
82
+ { token }
83
+ );
84
+ await sendNotificationsToOwners(
85
+ notifications,
86
+ scaffoldedEntities.items,
87
+ processorConfig
88
+ );
89
+ }
90
+ function readScaffolderRelationProcessorConfig(config) {
91
+ return {
92
+ notifications: {
93
+ templateUpdate: {
94
+ enabled: config.getOptionalBoolean(
95
+ "scaffolder.notifications.templateUpdate.enabled"
96
+ ) ?? constants.DEFAULT_NOTIFICATION_ENABLED,
97
+ message: {
98
+ title: config.getOptionalString(
99
+ "scaffolder.notifications.templateUpdate.message.title"
100
+ ) ?? constants.DEFAULT_NOTIFICATION_TITLE,
101
+ description: config.getOptionalString(
102
+ "scaffolder.notifications.templateUpdate.message.description"
103
+ ) ?? constants.DEFAULT_NOTIFICATION_DESCRIPTION
104
+ }
105
+ }
106
+ }
107
+ };
108
+ }
109
+
110
+ exports.handleTemplateUpdateNotifications = handleTemplateUpdateNotifications;
111
+ exports.handleTemplateVersion = handleTemplateVersion;
112
+ exports.readScaffolderRelationProcessorConfig = readScaffolderRelationProcessorConfig;
113
+ //# sourceMappingURL=templateVersionUtils.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templateVersionUtils.cjs.js","sources":["../src/templateVersionUtils.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { CatalogProcessorCache } from '@backstage/plugin-catalog-node';\nimport type { EventsService } from '@backstage/plugin-events-node';\nimport { CatalogClient } from '@backstage/catalog-client';\nimport {\n NotificationService,\n NotificationRecipients,\n} from '@backstage/plugin-notifications-node';\nimport { AuthService } from '@backstage/backend-plugin-api';\nimport { NotificationPayload } from '@backstage/plugin-notifications-common';\nimport type { Entity } from '@backstage/catalog-model';\nimport {\n DEFAULT_NOTIFICATION_DESCRIPTION,\n DEFAULT_NOTIFICATION_ENABLED,\n DEFAULT_NOTIFICATION_TITLE,\n ENTITY_DISPLAY_NAME_TEMPLATE_VAR,\n TEMPLATE_VERSION_UPDATED_TOPIC,\n} from './constants';\nimport { ScaffolderRelationProcessorConfig } from './types';\nimport type { Config } from '@backstage/config';\n\n/**\n * Cache structure for storing template version information\n *\n * @internal\n */\nexport interface TemplateVersionCache {\n version: string;\n}\n\n/**\n * Handles template version checking and caching\n *\n * @param entityRef - The string reference of the template entity\n * @param currentVersion - The current version of the template\n * @param cache - The catalog processor cache\n * @param eventsService - The events service for emitting events\n *\n * @internal\n */\nexport async function handleTemplateVersion(\n entityRef: string,\n currentVersion: string,\n cache: CatalogProcessorCache,\n eventsService?: EventsService,\n): Promise<void> {\n const cacheKey = `template-version-${entityRef}`;\n const cachedData = (await cache.get(cacheKey)) as\n | TemplateVersionCache\n | undefined;\n\n if (cachedData && cachedData.version < currentVersion) {\n if (eventsService) {\n await eventsService.publish({\n topic: TEMPLATE_VERSION_UPDATED_TOPIC,\n eventPayload: {\n entityRef,\n previousVersion: cachedData.version,\n currentVersion,\n },\n });\n }\n }\n\n await cache.set(cacheKey, {\n version: currentVersion,\n });\n}\n\n/**\n * Generates a catalog URL for an entity\n *\n * @param entity - The entity to generate URL for\n * @returns The catalog URL path for the entity\n *\n * @internal\n */\nfunction createEntityCatalogUrl(entity: Entity): string {\n const namespace = entity.metadata.namespace || 'default';\n const encodedNamespace = encodeURIComponent(namespace.toLowerCase());\n const encodedKind = encodeURIComponent(entity.kind.toLowerCase());\n const encodedName = encodeURIComponent(entity.metadata.name.toLowerCase());\n\n return `/catalog/${encodedNamespace}/${encodedKind}/${encodedName}`;\n}\n\n/**\n * Sends notifications to owners for each entity that should be updated\n *\n * @param notifications - Notification service to send notifications\n * @param entities - Array of entities that need update notifications sent to their owners\n * @param config - Configuration for notification title and description\n *\n * @internal\n */\nasync function sendNotificationsToOwners(\n notifications: NotificationService,\n entities: Entity[],\n config: ScaffolderRelationProcessorConfig,\n): Promise<void> {\n for (const entity of entities) {\n const ownedByRelations =\n entity.relations?.filter(rel => rel.type === 'ownedBy') || [];\n\n for (const relation of ownedByRelations) {\n const recipients: NotificationRecipients = {\n type: 'entity',\n entityRef: relation.targetRef,\n };\n\n const catalogUrl = createEntityCatalogUrl(entity);\n\n const entityName = entity.metadata.title ?? entity.metadata.name;\n const entityNameRegex = new RegExp(\n ENTITY_DISPLAY_NAME_TEMPLATE_VAR.replace(/\\$/g, '\\\\$'),\n 'g',\n );\n\n const titleReplaced =\n config.notifications?.templateUpdate?.message.title.replace(\n entityNameRegex,\n entityName,\n ) || '';\n\n // Capitalize the first word of the title\n const title =\n titleReplaced.charAt(0).toUpperCase() + titleReplaced.slice(1);\n\n const description =\n config.notifications?.templateUpdate?.message.description.replace(\n entityNameRegex,\n entityName,\n ) || '';\n\n const notificationPayload: NotificationPayload = {\n title,\n description,\n link: catalogUrl,\n };\n\n await notifications.send({\n recipients,\n payload: notificationPayload,\n });\n }\n }\n}\n\n/**\n * Handles template update notifications by finding scaffolded entities and notifying their owners\n *\n * @param catalogClient - Catalog client to query for entities\n * @param notifications - Notification service to send notifications\n * @param auth - Auth service to get authentication token\n * @param processorConfig - Parsed scaffolder relation processor config\n * @param payload - Template update payload containing entity ref and version info\n *\n * @internal\n */\nexport async function handleTemplateUpdateNotifications(\n catalogClient: CatalogClient,\n notifications: NotificationService,\n auth: AuthService,\n processorConfig: ScaffolderRelationProcessorConfig,\n payload: {\n entityRef: string;\n previousVersion: string;\n currentVersion: string;\n },\n): Promise<void> {\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: await auth.getOwnServiceCredentials(),\n targetPluginId: 'catalog',\n });\n\n const scaffoldedEntities = await catalogClient.getEntities(\n {\n filter: { 'spec.scaffoldedFrom': payload.entityRef },\n fields: [\n 'kind',\n 'metadata.namespace',\n 'metadata.name',\n 'metadata.title',\n 'relations',\n ],\n },\n { token },\n );\n\n await sendNotificationsToOwners(\n notifications,\n scaffoldedEntities.items,\n processorConfig,\n );\n}\n\n/**\n * Reads and parses the scaffolder relation processor configuration\n *\n * @param config - Backstage config\n * @returns Parsed config with defaults\n *\n * @internal\n */\nexport function readScaffolderRelationProcessorConfig(\n config: Config,\n): ScaffolderRelationProcessorConfig {\n return {\n notifications: {\n templateUpdate: {\n enabled:\n config.getOptionalBoolean(\n 'scaffolder.notifications.templateUpdate.enabled',\n ) ?? DEFAULT_NOTIFICATION_ENABLED,\n message: {\n title:\n config.getOptionalString(\n 'scaffolder.notifications.templateUpdate.message.title',\n ) ?? DEFAULT_NOTIFICATION_TITLE,\n description:\n config.getOptionalString(\n 'scaffolder.notifications.templateUpdate.message.description',\n ) ?? DEFAULT_NOTIFICATION_DESCRIPTION,\n },\n },\n },\n };\n}\n"],"names":["TEMPLATE_VERSION_UPDATED_TOPIC","ENTITY_DISPLAY_NAME_TEMPLATE_VAR","DEFAULT_NOTIFICATION_ENABLED","DEFAULT_NOTIFICATION_TITLE","DEFAULT_NOTIFICATION_DESCRIPTION"],"mappings":";;;;AAsDA,eAAsB,qBACpB,CAAA,SAAA,EACA,cACA,EAAA,KAAA,EACA,aACe,EAAA;AACf,EAAM,MAAA,QAAA,GAAW,oBAAoB,SAAS,CAAA,CAAA;AAC9C,EAAA,MAAM,UAAc,GAAA,MAAM,KAAM,CAAA,GAAA,CAAI,QAAQ,CAAA;AAI5C,EAAI,IAAA,UAAA,IAAc,UAAW,CAAA,OAAA,GAAU,cAAgB,EAAA;AACrD,IAAA,IAAI,aAAe,EAAA;AACjB,MAAA,MAAM,cAAc,OAAQ,CAAA;AAAA,QAC1B,KAAO,EAAAA,wCAAA;AAAA,QACP,YAAc,EAAA;AAAA,UACZ,SAAA;AAAA,UACA,iBAAiB,UAAW,CAAA,OAAA;AAAA,UAC5B;AAAA;AACF,OACD,CAAA;AAAA;AACH;AAGF,EAAM,MAAA,KAAA,CAAM,IAAI,QAAU,EAAA;AAAA,IACxB,OAAS,EAAA;AAAA,GACV,CAAA;AACH;AAUA,SAAS,uBAAuB,MAAwB,EAAA;AACtD,EAAM,MAAA,SAAA,GAAY,MAAO,CAAA,QAAA,CAAS,SAAa,IAAA,SAAA;AAC/C,EAAA,MAAM,gBAAmB,GAAA,kBAAA,CAAmB,SAAU,CAAA,WAAA,EAAa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A,YACL;AAAA,WACG,IAAAC;AAAA;AACT;AACF;AACF,GACF;AACF;;;;;;"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@backstage-community/plugin-catalog-backend-module-scaffolder-relation-processor",
3
3
  "description": "The scaffolder-relation-processor backend module for the catalog plugin.",
4
- "version": "2.6.1",
4
+ "version": "2.8.0",
5
5
  "main": "./dist/index.cjs.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "license": "Apache-2.0",
@@ -48,17 +48,23 @@
48
48
  "tsc": "tsc"
49
49
  },
50
50
  "dependencies": {
51
- "@backstage/backend-plugin-api": "^1.4.1",
51
+ "@backstage/backend-plugin-api": "^1.4.2",
52
+ "@backstage/catalog-client": "^1.11.0",
52
53
  "@backstage/catalog-model": "^1.7.5",
53
- "@backstage/plugin-catalog-node": "^1.17.2"
54
+ "@backstage/plugin-catalog-node": "^1.18.0",
55
+ "@backstage/plugin-events-node": "^0.4.14",
56
+ "@backstage/plugin-notifications-common": "^0.1.0",
57
+ "@backstage/plugin-notifications-node": "^0.2.18"
54
58
  },
55
59
  "devDependencies": {
56
- "@backstage/backend-test-utils": "^1.7.0",
57
- "@backstage/cli": "^0.33.1",
60
+ "@backstage/backend-test-utils": "^1.8.0",
61
+ "@backstage/cli": "^0.34.1",
62
+ "@backstage/config": "^1.3.3",
58
63
  "@backstage/plugin-catalog-common": "^1.1.5"
59
64
  },
60
65
  "files": [
61
66
  "config.d.ts",
62
67
  "dist"
63
- ]
68
+ ],
69
+ "configSchema": "config.d.ts"
64
70
  }