@backstage/plugin-events-backend 0.4.4-next.0 → 0.4.4-next.2

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,30 @@
1
1
  # @backstage/plugin-events-backend
2
2
 
3
+ ## 0.4.4-next.2
4
+
5
+ ### Patch Changes
6
+
7
+ - b95aa77: add `addHttpPostBodyParser` to events extension to allow body parse customization. This feature will enhance flexibility in handling HTTP POST requests in event-related operations.
8
+ - Updated dependencies
9
+ - @backstage/plugin-events-node@0.4.9-next.2
10
+ - @backstage/backend-openapi-utils@0.5.1-next.1
11
+ - @backstage/backend-plugin-api@1.2.1-next.1
12
+ - @backstage/config@1.3.2
13
+ - @backstage/errors@1.2.7
14
+ - @backstage/types@1.2.1
15
+
16
+ ## 0.4.4-next.1
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies
21
+ - @backstage/backend-openapi-utils@0.5.1-next.1
22
+ - @backstage/backend-plugin-api@1.2.1-next.1
23
+ - @backstage/config@1.3.2
24
+ - @backstage/errors@1.2.7
25
+ - @backstage/types@1.2.1
26
+ - @backstage/plugin-events-node@0.4.9-next.1
27
+
3
28
  ## 0.4.4-next.0
4
29
 
5
30
  ### Patch Changes
package/README.md CHANGED
@@ -140,6 +140,48 @@ export const eventsModuleYourFeature = createBackendModule({
140
140
  });
141
141
  ```
142
142
 
143
+ ### Request Body Parse
144
+
145
+ We need to parse the request body before we can validate it. We have some default parsers but you can provide your own when necessary.
146
+
147
+ ```ts
148
+ import { eventsExtensionPoint } from '@backstage/plugin-events-node/alpha';
149
+
150
+ // [...]
151
+
152
+ export const eventsModuleYourFeature = createBackendModule({
153
+ pluginId: 'events',
154
+ moduleId: 'your-feature',
155
+ register(env) {
156
+ // [...]
157
+ env.registerInit({
158
+ deps: {
159
+ // [...]
160
+ events: eventsExtensionPoint,
161
+ // [...]
162
+ },
163
+ async init({ /* ... */ events /*, ... */ }) {
164
+ // [...]
165
+ events.addHttpPostBodyParser({
166
+ contentType: 'application/x-www-form-urlencoded',
167
+ parser: async (req, _topic) => {
168
+ return {
169
+ bodyParsed: req.body.toString('utf-8'),
170
+ bodyBuffer: req.body,
171
+ encoding: 'utf-8',
172
+ };
173
+ },
174
+ });
175
+ },
176
+ });
177
+ },
178
+ });
179
+ ```
180
+
181
+ We have the following default parsers:
182
+
183
+ - `application/json`
184
+
143
185
  #### Legacy Backend System
144
186
 
145
187
  ```ts
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
2
2
  import { LoggerService } from '@backstage/backend-plugin-api';
3
- import { EventBroker, EventPublisher, EventSubscriber, EventsService, EventParams, HttpPostIngressOptions } from '@backstage/plugin-events-node';
3
+ import { EventBroker, EventPublisher, EventSubscriber, EventsService, EventParams, HttpPostIngressOptions, HttpBodyParser } from '@backstage/plugin-events-node';
4
4
  import { Logger } from 'winston';
5
5
  import { Config } from '@backstage/config';
6
6
  import express from 'express';
@@ -64,12 +64,16 @@ declare class HttpPostIngressEventPublisher {
64
64
  private readonly events;
65
65
  private readonly logger;
66
66
  private readonly ingresses;
67
+ private readonly bodyParsers;
67
68
  static fromConfig(env: {
68
69
  config: Config;
69
70
  events: EventsService;
70
71
  ingresses?: {
71
72
  [topic: string]: Omit<HttpPostIngressOptions, 'topic'>;
72
73
  };
74
+ bodyParsers?: {
75
+ [contentType: string]: HttpBodyParser;
76
+ };
73
77
  logger: LoggerService;
74
78
  }): HttpPostIngressEventPublisher;
75
79
  private constructor();
@@ -13,6 +13,7 @@ var Router__default = /*#__PURE__*/_interopDefaultCompat(Router);
13
13
 
14
14
  class EventsExtensionPointImpl {
15
15
  #httpPostIngresses = [];
16
+ #httpBodyParsers = [];
16
17
  setEventBroker(_) {
17
18
  throw new Error(
18
19
  "setEventBroker is not supported anymore; use eventsServiceRef instead"
@@ -31,9 +32,15 @@ class EventsExtensionPointImpl {
31
32
  addHttpPostIngress(options) {
32
33
  this.#httpPostIngresses.push(options);
33
34
  }
35
+ addHttpPostBodyParser(options) {
36
+ this.#httpBodyParsers.push(options);
37
+ }
34
38
  get httpPostIngresses() {
35
39
  return this.#httpPostIngresses;
36
40
  }
41
+ get httpBodyParsers() {
42
+ return this.#httpBodyParsers;
43
+ }
37
44
  }
38
45
  const eventsPlugin = backendPluginApi.createBackendPlugin({
39
46
  pluginId: "events",
@@ -67,10 +74,17 @@ const eventsPlugin = backendPluginApi.createBackendPlugin({
67
74
  ingress
68
75
  ])
69
76
  );
77
+ const bodyParsers = Object.fromEntries(
78
+ extensionPoint.httpBodyParsers.map((option) => [
79
+ option.contentType,
80
+ option.parser
81
+ ])
82
+ );
70
83
  const http = HttpPostIngressEventPublisher.HttpPostIngressEventPublisher.fromConfig({
71
84
  config,
72
85
  events,
73
86
  ingresses,
87
+ bodyParsers,
74
88
  logger
75
89
  });
76
90
  const eventsRouter = Router__default.default();
@@ -1 +1 @@
1
- {"version":3,"file":"EventsPlugin.cjs.js","sources":["../../src/service/EventsPlugin.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createBackendPlugin,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport {\n eventsExtensionPoint,\n EventsExtensionPoint,\n} from '@backstage/plugin-events-node/alpha';\nimport {\n eventsServiceRef,\n HttpPostIngressOptions,\n} from '@backstage/plugin-events-node';\nimport Router from 'express-promise-router';\nimport { HttpPostIngressEventPublisher } from './http';\nimport { createEventBusRouter } from './hub';\n\nclass EventsExtensionPointImpl implements EventsExtensionPoint {\n #httpPostIngresses: HttpPostIngressOptions[] = [];\n\n setEventBroker(_: any): void {\n throw new Error(\n 'setEventBroker is not supported anymore; use eventsServiceRef instead',\n );\n }\n\n addPublishers(_: any): void {\n throw new Error(\n 'addPublishers is not supported anymore; use EventsService instead',\n );\n }\n\n addSubscribers(_: any): void {\n throw new Error(\n 'addSubscribers is not supported anymore; use EventsService instead',\n );\n }\n\n addHttpPostIngress(options: HttpPostIngressOptions) {\n this.#httpPostIngresses.push(options);\n }\n\n get httpPostIngresses() {\n return this.#httpPostIngresses;\n }\n}\n\n/**\n * Events plugin\n *\n * @public\n */\nexport const eventsPlugin = createBackendPlugin({\n pluginId: 'events',\n register(env) {\n const extensionPoint = new EventsExtensionPointImpl();\n env.registerExtensionPoint(eventsExtensionPoint, extensionPoint);\n\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n events: eventsServiceRef,\n database: coreServices.database,\n httpAuth: coreServices.httpAuth,\n httpRouter: coreServices.httpRouter,\n lifecycle: coreServices.lifecycle,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n },\n async init({\n config,\n events,\n database,\n httpAuth,\n httpRouter,\n lifecycle,\n logger,\n scheduler,\n }) {\n const ingresses = Object.fromEntries(\n extensionPoint.httpPostIngresses.map(ingress => [\n ingress.topic,\n ingress as Omit<HttpPostIngressOptions, 'topic'>,\n ]),\n );\n\n const http = HttpPostIngressEventPublisher.fromConfig({\n config,\n events,\n ingresses,\n logger,\n });\n const eventsRouter = Router();\n http.bind(eventsRouter);\n\n // MUST be registered *before* the event bus router.\n // Otherwise, it would already make use of `express.json()`\n // that is used there as part of the middleware stack.\n httpRouter.use(eventsRouter);\n\n const notifyTimeoutMs = config.getOptionalNumber(\n 'events.notifyTimeoutMs',\n );\n\n httpRouter.use(\n await createEventBusRouter({\n database,\n lifecycle,\n logger,\n httpAuth,\n scheduler,\n notifyTimeoutMs,\n }),\n );\n\n httpRouter.addAuthPolicy({\n allow: 'unauthenticated',\n path: '/http',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","eventsExtensionPoint","coreServices","eventsServiceRef","HttpPostIngressEventPublisher","Router","createEventBusRouter"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,wBAAyD,CAAA;AAAA,EAC7D,qBAA+C,EAAC;AAAA,EAEhD,eAAe,CAAc,EAAA;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA;AACF,EAEA,cAAc,CAAc,EAAA;AAC1B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA;AACF,EAEA,eAAe,CAAc,EAAA;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA;AACF,EAEA,mBAAmB,OAAiC,EAAA;AAClD,IAAK,IAAA,CAAA,kBAAA,CAAmB,KAAK,OAAO,CAAA;AAAA;AACtC,EAEA,IAAI,iBAAoB,GAAA;AACtB,IAAA,OAAO,IAAK,CAAA,kBAAA;AAAA;AAEhB;AAOO,MAAM,eAAeA,oCAAoB,CAAA;AAAA,EAC9C,QAAU,EAAA,QAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAM,MAAA,cAAA,GAAiB,IAAI,wBAAyB,EAAA;AACpD,IAAI,GAAA,CAAA,sBAAA,CAAuBC,4BAAsB,cAAc,CAAA;AAE/D,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,QAAQC,6BAAa,CAAA,UAAA;AAAA,QACrB,MAAQ,EAAAC,iCAAA;AAAA,QACR,UAAUD,6BAAa,CAAA,QAAA;AAAA,QACvB,UAAUA,6BAAa,CAAA,QAAA;AAAA,QACvB,YAAYA,6BAAa,CAAA,UAAA;AAAA,QACzB,WAAWA,6BAAa,CAAA,SAAA;AAAA,QACxB,QAAQA,6BAAa,CAAA,MAAA;AAAA,QACrB,WAAWA,6BAAa,CAAA;AAAA,OAC1B;AAAA,MACA,MAAM,IAAK,CAAA;AAAA,QACT,MAAA;AAAA,QACA,MAAA;AAAA,QACA,QAAA;AAAA,QACA,QAAA;AAAA,QACA,UAAA;AAAA,QACA,SAAA;AAAA,QACA,MAAA;AAAA,QACA;AAAA,OACC,EAAA;AACD,QAAA,MAAM,YAAY,MAAO,CAAA,WAAA;AAAA,UACvB,cAAA,CAAe,iBAAkB,CAAA,GAAA,CAAI,CAAW,OAAA,KAAA;AAAA,YAC9C,OAAQ,CAAA,KAAA;AAAA,YACR;AAAA,WACD;AAAA,SACH;AAEA,QAAM,MAAA,IAAA,GAAOE,4DAA8B,UAAW,CAAA;AAAA,UACpD,MAAA;AAAA,UACA,MAAA;AAAA,UACA,SAAA;AAAA,UACA;AAAA,SACD,CAAA;AACD,QAAA,MAAM,eAAeC,uBAAO,EAAA;AAC5B,QAAA,IAAA,CAAK,KAAK,YAAY,CAAA;AAKtB,QAAA,UAAA,CAAW,IAAI,YAAY,CAAA;AAE3B,QAAA,MAAM,kBAAkB,MAAO,CAAA,iBAAA;AAAA,UAC7B;AAAA,SACF;AAEA,QAAW,UAAA,CAAA,GAAA;AAAA,UACT,MAAMC,yCAAqB,CAAA;AAAA,YACzB,QAAA;AAAA,YACA,SAAA;AAAA,YACA,MAAA;AAAA,YACA,QAAA;AAAA,YACA,SAAA;AAAA,YACA;AAAA,WACD;AAAA,SACH;AAEA,QAAA,UAAA,CAAW,aAAc,CAAA;AAAA,UACvB,KAAO,EAAA,iBAAA;AAAA,UACP,IAAM,EAAA;AAAA,SACP,CAAA;AAAA;AACH,KACD,CAAA;AAAA;AAEL,CAAC;;;;"}
1
+ {"version":3,"file":"EventsPlugin.cjs.js","sources":["../../src/service/EventsPlugin.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createBackendPlugin,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport {\n eventsExtensionPoint,\n EventsExtensionPoint,\n} from '@backstage/plugin-events-node/alpha';\nimport {\n eventsServiceRef,\n HttpBodyParserOptions,\n HttpPostIngressOptions,\n} from '@backstage/plugin-events-node';\nimport Router from 'express-promise-router';\nimport { HttpPostIngressEventPublisher } from './http';\nimport { createEventBusRouter } from './hub';\n\nclass EventsExtensionPointImpl implements EventsExtensionPoint {\n readonly #httpPostIngresses: HttpPostIngressOptions[] = [];\n readonly #httpBodyParsers: HttpBodyParserOptions[] = [];\n\n setEventBroker(_: any): void {\n throw new Error(\n 'setEventBroker is not supported anymore; use eventsServiceRef instead',\n );\n }\n\n addPublishers(_: any): void {\n throw new Error(\n 'addPublishers is not supported anymore; use EventsService instead',\n );\n }\n\n addSubscribers(_: any): void {\n throw new Error(\n 'addSubscribers is not supported anymore; use EventsService instead',\n );\n }\n\n addHttpPostIngress(options: HttpPostIngressOptions) {\n this.#httpPostIngresses.push(options);\n }\n\n addHttpPostBodyParser(options: HttpBodyParserOptions): void {\n this.#httpBodyParsers.push(options);\n }\n\n get httpPostIngresses() {\n return this.#httpPostIngresses;\n }\n\n get httpBodyParsers() {\n return this.#httpBodyParsers;\n }\n}\n\n/**\n * Events plugin\n *\n * @public\n */\nexport const eventsPlugin = createBackendPlugin({\n pluginId: 'events',\n register(env) {\n const extensionPoint = new EventsExtensionPointImpl();\n env.registerExtensionPoint(eventsExtensionPoint, extensionPoint);\n\n env.registerInit({\n deps: {\n config: coreServices.rootConfig,\n events: eventsServiceRef,\n database: coreServices.database,\n httpAuth: coreServices.httpAuth,\n httpRouter: coreServices.httpRouter,\n lifecycle: coreServices.lifecycle,\n logger: coreServices.logger,\n scheduler: coreServices.scheduler,\n },\n async init({\n config,\n events,\n database,\n httpAuth,\n httpRouter,\n lifecycle,\n logger,\n scheduler,\n }) {\n const ingresses = Object.fromEntries(\n extensionPoint.httpPostIngresses.map(ingress => [\n ingress.topic,\n ingress as Omit<HttpPostIngressOptions, 'topic'>,\n ]),\n );\n\n const bodyParsers = Object.fromEntries(\n extensionPoint.httpBodyParsers.map(option => [\n option.contentType,\n option.parser,\n ]),\n );\n\n const http = HttpPostIngressEventPublisher.fromConfig({\n config,\n events,\n ingresses,\n bodyParsers,\n logger,\n });\n const eventsRouter = Router();\n http.bind(eventsRouter);\n\n // MUST be registered *before* the event bus router.\n // Otherwise, it would already make use of `express.json()`\n // that is used there as part of the middleware stack.\n httpRouter.use(eventsRouter);\n\n const notifyTimeoutMs = config.getOptionalNumber(\n 'events.notifyTimeoutMs',\n );\n\n httpRouter.use(\n await createEventBusRouter({\n database,\n lifecycle,\n logger,\n httpAuth,\n scheduler,\n notifyTimeoutMs,\n }),\n );\n\n httpRouter.addAuthPolicy({\n allow: 'unauthenticated',\n path: '/http',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","eventsExtensionPoint","coreServices","eventsServiceRef","HttpPostIngressEventPublisher","Router","createEventBusRouter"],"mappings":";;;;;;;;;;;;;AAiCA,MAAM,wBAAyD,CAAA;AAAA,EACpD,qBAA+C,EAAC;AAAA,EAChD,mBAA4C,EAAC;AAAA,EAEtD,eAAe,CAAc,EAAA;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA;AACF,EAEA,cAAc,CAAc,EAAA;AAC1B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA;AACF,EAEA,eAAe,CAAc,EAAA;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA;AACF,EAEA,mBAAmB,OAAiC,EAAA;AAClD,IAAK,IAAA,CAAA,kBAAA,CAAmB,KAAK,OAAO,CAAA;AAAA;AACtC,EAEA,sBAAsB,OAAsC,EAAA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AAI,CAAU,MAAA,KAAA;AAAA,YAC3C,MAAO,CAAA,WAAA;AAAA,YACP,MAAO,CAAA;AAAA,WACR;AAAA,SACH;AAEA,QAAM,MAAA,IAAA,GAAOE,4DAA8B,UAAW,CAAA;AAAA,UACpD,MAAA;AAAA,UACA,MAAA;AAAA,UACA,SAAA;AAAA,UACA,WAAA;AAAA,UACA;AAAA,SACD,CAAA;AACD,QAAA,MAAM,eAAeC,uBAAO,EAAA;AAC5B,QAAA,IAAA,CAAK,KAAK,YAAY,CAAA;AAKtB,QAAA,UAAA,CAAW,IAAI,YAAY,CAAA;AAE3B,QAAA,MAAM,kBAAkB,MAAO,CAAA,iBAAA;AAAA,UAC7B;AAAA,SACF;AAEA,QAAW,UAAA,CAAA,GAAA;AAAA,UACT,MAAMC,yCAAqB,CAAA;AAAA,YACzB,QAAA;AAAA,YACA,SAAA;AAAA,YACA,MAAA;AAAA,YACA,QAAA;AAAA,YACA,SAAA;AAAA,YACA;AAAA,WACD;AAAA,SACH;AAEA,QAAA,UAAA,CAAW,aAAc,CAAA;AAAA,UACvB,KAAO,EAAA,iBAAA;AAAA,UACP,IAAM,EAAA;AAAA,SACP,CAAA;AAAA;AACH,KACD,CAAA;AAAA;AAEL,CAAC;;;;"}
@@ -1,10 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var errors = require('@backstage/errors');
4
3
  var contentType = require('content-type');
5
4
  var express = require('express');
6
5
  var Router = require('express-promise-router');
6
+ var index = require('./body-parser/index.cjs.js');
7
7
  var RequestValidationContextImpl = require('./validation/RequestValidationContextImpl.cjs.js');
8
+ var errors = require('./errors.cjs.js');
8
9
 
9
10
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
10
11
 
@@ -12,25 +13,12 @@ var contentType__default = /*#__PURE__*/_interopDefaultCompat(contentType);
12
13
  var express__default = /*#__PURE__*/_interopDefaultCompat(express);
13
14
  var Router__default = /*#__PURE__*/_interopDefaultCompat(Router);
14
15
 
15
- class UnsupportedCharsetError extends errors.CustomErrorBase {
16
- name = "UnsupportedCharsetError";
17
- statusCode = 415;
18
- constructor(charset) {
19
- super(`Unsupported charset: ${charset}`);
20
- }
21
- }
22
- class UnsupportedMediaTypeError extends errors.CustomErrorBase {
23
- name = "UnsupportedMediaTypeError";
24
- statusCode = 415;
25
- constructor(mediaType) {
26
- super(`Unsupported media type: ${mediaType ?? "unknown"}`);
27
- }
28
- }
29
16
  class HttpPostIngressEventPublisher {
30
- constructor(events, logger, ingresses) {
17
+ constructor(events, logger, ingresses, bodyParsers) {
31
18
  this.events = events;
32
19
  this.logger = logger;
33
20
  this.ingresses = ingresses;
21
+ this.bodyParsers = bodyParsers;
34
22
  }
35
23
  static fromConfig(env) {
36
24
  const topics = env.config.getOptionalStringArray("events.http.topics") ?? [];
@@ -40,7 +28,13 @@ class HttpPostIngressEventPublisher {
40
28
  ingresses[topic] = {};
41
29
  }
42
30
  });
43
- return new HttpPostIngressEventPublisher(env.events, env.logger, ingresses);
31
+ const parsers = { ...index.defaultHttpBodyParsers, ...env.bodyParsers };
32
+ return new HttpPostIngressEventPublisher(
33
+ env.events,
34
+ env.logger,
35
+ ingresses,
36
+ parsers
37
+ );
44
38
  }
45
39
  bind(router) {
46
40
  router.use("/http", this.createRouter(this.ingresses));
@@ -57,23 +51,16 @@ class HttpPostIngressEventPublisher {
57
51
  const path = `/${topic}`;
58
52
  const logger = this.logger;
59
53
  router.post(path, async (request, response) => {
60
- const requestBody = request.body;
61
- if (!Buffer.isBuffer(requestBody)) {
62
- throw new Error(
63
- `Failed to retrieve raw body from incoming event for topic ${topic}; not a buffer: ${typeof requestBody}`
64
- );
65
- }
66
- const bodyBuffer = requestBody;
67
- const parsedContentType = contentType__default.default.parse(request);
68
- if (!parsedContentType.type || parsedContentType.type !== "application/json") {
69
- throw new UnsupportedMediaTypeError(parsedContentType.type);
70
- }
71
- const encoding = parsedContentType.parameters.charset ?? "utf-8";
72
- if (!Buffer.isEncoding(encoding)) {
73
- throw new UnsupportedCharsetError(encoding);
54
+ const requestContentType = contentType__default.default.parse(request);
55
+ const bodyParser = this.bodyParsers[requestContentType.type ?? ""];
56
+ if (!bodyParser) {
57
+ throw new errors.UnsupportedMediaTypeError(requestContentType.type);
74
58
  }
75
- const bodyString = bodyBuffer.toString(encoding);
76
- const bodyParsed = parsedContentType.type === "application/json" ? JSON.parse(bodyString) : bodyString;
59
+ const { bodyParsed, bodyBuffer, encoding } = await bodyParser(
60
+ request,
61
+ requestContentType,
62
+ topic
63
+ );
77
64
  if (validator) {
78
65
  const requestDetails = {
79
66
  body: bodyParsed,
@@ -1 +1 @@
1
- {"version":3,"file":"HttpPostIngressEventPublisher.cjs.js","sources":["../../../src/service/http/HttpPostIngressEventPublisher.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\nimport { CustomErrorBase } from '@backstage/errors';\nimport {\n EventsService,\n HttpPostIngressOptions,\n RequestValidator,\n} from '@backstage/plugin-events-node';\nimport contentType from 'content-type';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { RequestValidationContextImpl } from './validation';\n\nclass UnsupportedCharsetError extends CustomErrorBase {\n name = 'UnsupportedCharsetError' as const;\n statusCode = 415 as const;\n\n constructor(charset: string) {\n super(`Unsupported charset: ${charset}`);\n }\n}\n\nclass UnsupportedMediaTypeError extends CustomErrorBase {\n name = 'UnsupportedMediaTypeError' as const;\n statusCode = 415 as const;\n\n constructor(mediaType?: string) {\n super(`Unsupported media type: ${mediaType ?? 'unknown'}`);\n }\n}\n\n/**\n * Publishes events received from their origin (e.g., webhook events from an SCM system)\n * via HTTP POST endpoint and passes the request body as event payload to the registered subscribers.\n *\n * @public\n */\n// TODO(pjungermann): add prom metrics? (see plugins/catalog-backend/src/util/metrics.ts, etc.)\nexport class HttpPostIngressEventPublisher {\n static fromConfig(env: {\n config: Config;\n events: EventsService;\n ingresses?: { [topic: string]: Omit<HttpPostIngressOptions, 'topic'> };\n logger: LoggerService;\n }): HttpPostIngressEventPublisher {\n const topics =\n env.config.getOptionalStringArray('events.http.topics') ?? [];\n\n const ingresses = env.ingresses ?? {};\n topics.forEach(topic => {\n // don't overwrite topic settings\n // (e.g., added at the config as well as argument)\n if (!ingresses[topic]) {\n ingresses[topic] = {};\n }\n });\n\n return new HttpPostIngressEventPublisher(env.events, env.logger, ingresses);\n }\n\n private constructor(\n private readonly events: EventsService,\n private readonly logger: LoggerService,\n private readonly ingresses: {\n [topic: string]: Omit<HttpPostIngressOptions, 'topic'>;\n },\n ) {}\n\n bind(router: express.Router): void {\n router.use('/http', this.createRouter(this.ingresses));\n }\n\n private createRouter(ingresses: {\n [topic: string]: Omit<HttpPostIngressOptions, 'topic'>;\n }): express.Router {\n const router = Router();\n router.use(express.raw({ type: '*/*', limit: '5mb' }));\n\n Object.keys(ingresses).forEach(topic =>\n this.addRouteForTopic(router, topic, ingresses[topic].validator),\n );\n\n return router;\n }\n\n private addRouteForTopic(\n router: express.Router,\n topic: string,\n validator?: RequestValidator,\n ): void {\n const path = `/${topic}`;\n const logger = this.logger;\n\n router.post(path, async (request, response) => {\n const requestBody = request.body;\n if (!Buffer.isBuffer(requestBody)) {\n throw new Error(\n `Failed to retrieve raw body from incoming event for topic ${topic}; not a buffer: ${typeof requestBody}`,\n );\n }\n\n const bodyBuffer: Buffer = requestBody;\n const parsedContentType = contentType.parse(request);\n if (\n !parsedContentType.type ||\n parsedContentType.type !== 'application/json'\n ) {\n throw new UnsupportedMediaTypeError(parsedContentType.type);\n }\n\n const encoding = parsedContentType.parameters.charset ?? 'utf-8';\n if (!Buffer.isEncoding(encoding)) {\n throw new UnsupportedCharsetError(encoding);\n }\n\n const bodyString = bodyBuffer.toString(encoding);\n const bodyParsed =\n parsedContentType.type === 'application/json'\n ? JSON.parse(bodyString)\n : bodyString;\n\n if (validator) {\n const requestDetails = {\n body: bodyParsed,\n headers: request.headers,\n raw: {\n body: bodyBuffer,\n encoding: encoding as BufferEncoding,\n },\n };\n\n const context = new RequestValidationContextImpl();\n await validator(requestDetails, context);\n\n if (context.wasRejected()) {\n response\n .status(context.rejectionDetails!.status)\n .json(context.rejectionDetails!.payload);\n return;\n }\n }\n\n await this.events.publish({\n topic,\n eventPayload: bodyParsed,\n metadata: request.headers,\n });\n\n response.status(202).json({ status: 'accepted' });\n });\n\n // TODO(pjungermann): We don't really know the externally defined path prefix here,\n // however it is more useful for users to have it. Is there a better way?\n logger.info(`Registered /api/events/http${path} to receive events`);\n }\n}\n"],"names":["CustomErrorBase","Router","express","contentType","RequestValidationContextImpl"],"mappings":";;;;;;;;;;;;;;AA6BA,MAAM,gCAAgCA,sBAAgB,CAAA;AAAA,EACpD,IAAO,GAAA,yBAAA;AAAA,EACP,UAAa,GAAA,GAAA;AAAA,EAEb,YAAY,OAAiB,EAAA;AAC3B,IAAM,KAAA,CAAA,CAAA,qBAAA,EAAwB,OAAO,CAAE,CAAA,CAAA;AAAA;AAE3C;AAEA,MAAM,kCAAkCA,sBAAgB,CAAA;AAAA,EACtD,IAAO,GAAA,2BAAA;AAAA,EACP,UAAa,GAAA,GAAA;AAAA,EAEb,YAAY,SAAoB,EAAA;AAC9B,IAAM,KAAA,CAAA,CAAA,wBAAA,EAA2B,SAAa,IAAA,SAAS,CAAE,CAAA,CAAA;AAAA;AAE7D;AASO,MAAM,6BAA8B,CAAA;AAAA,EAsBjC,WAAA,CACW,MACA,EAAA,MAAA,EACA,SAGjB,EAAA;AALiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,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;AAEvC,QAAI,IAAA,OAAA,CAAQ,aAAe,EAAA;AACzB,UACG,QAAA,CAAA,MAAA,CAAO,QAAQ,gBAAkB,CAAA,MAAM,EACvC,IAAK,CAAA,OAAA,CAAQ,iBAAkB,OAAO,CAAA;AACzC,UAAA;AAAA;AACF;AAGF,MAAM,MAAA,IAAA,CAAK,OAAO,OAAQ,CAAA;AAAA,QACxB,KAAA;AAAA,QACA,YAAc,EAAA,UAAA;AAAA,QACd,UAAU,OAAQ,CAAA;AAAA,OACnB,CAAA;AAED,MAAA,QAAA,CAAS,OAAO,GAAG,CAAA,CAAE,KAAK,EAAE,MAAA,EAAQ,YAAY,CAAA;AAAA,KACjD,CAAA;AAID,IAAO,MAAA,CAAA,IAAA,CAAK,CAA8B,2BAAA,EAAA,IAAI,CAAoB,kBAAA,CAAA,CAAA;AAAA;AAEtE;;;;"}
1
+ {"version":3,"file":"HttpPostIngressEventPublisher.cjs.js","sources":["../../../src/service/http/HttpPostIngressEventPublisher.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\nimport {\n EventsService,\n HttpBodyParser,\n HttpPostIngressOptions,\n RequestValidator,\n} from '@backstage/plugin-events-node';\nimport contentType from 'content-type';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { defaultHttpBodyParsers } from './body-parser';\nimport { RequestValidationContextImpl } from './validation';\nimport { UnsupportedMediaTypeError } from './errors';\n/**\n * Publishes events received from their origin (e.g., webhook events from an SCM system)\n * via HTTP POST endpoint and passes the request body as event payload to the registered subscribers.\n *\n * @public\n */\n// TODO(pjungermann): add prom metrics? (see plugins/catalog-backend/src/util/metrics.ts, etc.)\nexport class HttpPostIngressEventPublisher {\n static fromConfig(env: {\n config: Config;\n events: EventsService;\n ingresses?: { [topic: string]: Omit<HttpPostIngressOptions, 'topic'> };\n bodyParsers?: { [contentType: string]: HttpBodyParser };\n logger: LoggerService;\n }): HttpPostIngressEventPublisher {\n const topics =\n env.config.getOptionalStringArray('events.http.topics') ?? [];\n\n const ingresses = env.ingresses ?? {};\n topics.forEach(topic => {\n // don't overwrite topic settings\n // (e.g., added at the config as well as argument)\n if (!ingresses[topic]) {\n ingresses[topic] = {};\n }\n });\n\n const parsers = { ...defaultHttpBodyParsers, ...env.bodyParsers };\n\n return new HttpPostIngressEventPublisher(\n env.events,\n env.logger,\n ingresses,\n parsers,\n );\n }\n\n private constructor(\n private readonly events: EventsService,\n private readonly logger: LoggerService,\n private readonly ingresses: {\n [topic: string]: Omit<HttpPostIngressOptions, 'topic'>;\n },\n private readonly bodyParsers: {\n [contentType: string]: HttpBodyParser;\n },\n ) {}\n\n bind(router: express.Router): void {\n router.use('/http', this.createRouter(this.ingresses));\n }\n\n private createRouter(ingresses: {\n [topic: string]: Omit<HttpPostIngressOptions, 'topic'>;\n }): express.Router {\n const router = Router();\n router.use(express.raw({ type: '*/*', limit: '5mb' }));\n\n Object.keys(ingresses).forEach(topic =>\n this.addRouteForTopic(router, topic, ingresses[topic].validator),\n );\n\n return router;\n }\n\n private addRouteForTopic(\n router: express.Router,\n topic: string,\n validator?: RequestValidator,\n ): void {\n const path = `/${topic}`;\n const logger = this.logger;\n\n router.post(path, async (request, response) => {\n const requestContentType = contentType.parse(request);\n const bodyParser = this.bodyParsers[requestContentType.type ?? ''];\n\n if (!bodyParser) {\n throw new UnsupportedMediaTypeError(requestContentType.type);\n }\n\n const { bodyParsed, bodyBuffer, encoding } = await bodyParser(\n request,\n requestContentType,\n topic,\n );\n\n if (validator) {\n const requestDetails = {\n body: bodyParsed,\n headers: request.headers,\n raw: {\n body: bodyBuffer,\n encoding: encoding as BufferEncoding,\n },\n };\n\n const context = new RequestValidationContextImpl();\n await validator(requestDetails, context);\n\n if (context.wasRejected()) {\n response\n .status(context.rejectionDetails!.status)\n .json(context.rejectionDetails!.payload);\n return;\n }\n }\n\n await this.events.publish({\n topic,\n eventPayload: bodyParsed,\n metadata: request.headers,\n });\n\n response.status(202).json({ status: 'accepted' });\n });\n\n // TODO(pjungermann): We don't really know the externally defined path prefix here,\n // however it is more useful for users to have it. Is there a better way?\n logger.info(`Registered /api/events/http${path} to receive events`);\n }\n}\n"],"names":["defaultHttpBodyParsers","Router","express","contentType","UnsupportedMediaTypeError","RequestValidationContextImpl"],"mappings":";;;;;;;;;;;;;;;AAqCO,MAAM,6BAA8B,CAAA;AAAA,EA8BjC,WACW,CAAA,MAAA,EACA,MACA,EAAA,SAAA,EAGA,WAGjB,EAAA;AARiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAGA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA;AAGhB,EAtCH,OAAO,WAAW,GAMgB,EAAA;AAChC,IAAA,MAAM,SACJ,GAAI,CAAA,MAAA,CAAO,sBAAuB,CAAA,oBAAoB,KAAK,EAAC;AAE9D,IAAM,MAAA,SAAA,GAAY,GAAI,CAAA,SAAA,IAAa,EAAC;AACpC,IAAA,MAAA,CAAO,QAAQ,CAAS,KAAA,KAAA;AAGtB,MAAI,IAAA,CAAC,SAAU,CAAA,KAAK,CAAG,EAAA;AACrB,QAAU,SAAA,CAAA,KAAK,IAAI,EAAC;AAAA;AACtB,KACD,CAAA;AAED,IAAA,MAAM,UAAU,EAAE,GAAGA,4BAAwB,EAAA,GAAG,IAAI,WAAY,EAAA;AAEhE,IAAA,OAAO,IAAI,6BAAA;AAAA,MACT,GA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A;AAAA,OACF;AAEA,MAAA,IAAI,SAAW,EAAA;AACb,QAAA,MAAM,cAAiB,GAAA;AAAA,UACrB,IAAM,EAAA,UAAA;AAAA,UACN,SAAS,OAAQ,CAAA,OAAA;AAAA,UACjB,GAAK,EAAA;AAAA,YACH,IAAM,EAAA,UAAA;AAAA,YACN;AAAA;AACF,SACF;AAEA,QAAM,MAAA,OAAA,GAAU,IAAIC,yDAA6B,EAAA;AACjD,QAAM,MAAA,SAAA,CAAU,gBAAgB,OAAO,CAAA;AAEvC,QAAI,IAAA,OAAA,CAAQ,aAAe,EAAA;AACzB,UACG,QAAA,CAAA,MAAA,CAAO,QAAQ,gBAAkB,CAAA,MAAM,EACvC,IAAK,CAAA,OAAA,CAAQ,iBAAkB,OAAO,CAAA;AACzC,UAAA;AAAA;AACF;AAGF,MAAM,MAAA,IAAA,CAAK,OAAO,OAAQ,CAAA;AAAA,QACxB,KAAA;AAAA,QACA,YAAc,EAAA,UAAA;AAAA,QACd,UAAU,OAAQ,CAAA;AAAA,OACnB,CAAA;AAED,MAAA,QAAA,CAAS,OAAO,GAAG,CAAA,CAAE,KAAK,EAAE,MAAA,EAAQ,YAAY,CAAA;AAAA,KACjD,CAAA;AAID,IAAO,MAAA,CAAA,IAAA,CAAK,CAA8B,2BAAA,EAAA,IAAI,CAAoB,kBAAA,CAAA,CAAA;AAAA;AAEtE;;;;"}
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ var errors = require('../errors.cjs.js');
4
+
5
+ const HttpApplicationJsonBodyParser = async (request, parsedMediaType, topic) => {
6
+ const requestBody = request.body;
7
+ if (!Buffer.isBuffer(requestBody)) {
8
+ throw new Error(
9
+ `Failed to retrieve raw body from incoming event for topic ${topic}; not a buffer: ${typeof requestBody}`
10
+ );
11
+ }
12
+ const bodyBuffer = requestBody;
13
+ const encoding = parsedMediaType.parameters.charset ?? "utf-8";
14
+ if (!Buffer.isEncoding(encoding)) {
15
+ throw new errors.UnsupportedCharsetError(encoding);
16
+ }
17
+ const bodyString = bodyBuffer.toString(encoding);
18
+ const bodyParsed = parsedMediaType.type === "application/json" ? JSON.parse(bodyString) : bodyString;
19
+ return { bodyParsed, bodyBuffer, encoding };
20
+ };
21
+
22
+ exports.HttpApplicationJsonBodyParser = HttpApplicationJsonBodyParser;
23
+ //# sourceMappingURL=HttpApplicationJsonBodyParser.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpApplicationJsonBodyParser.cjs.js","sources":["../../../../src/service/http/body-parser/HttpApplicationJsonBodyParser.ts"],"sourcesContent":["/*\n * Copyright 2025 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 { HttpBodyParser } from '@backstage/plugin-events-node';\nimport { UnsupportedCharsetError } from '../errors';\n\nexport const HttpApplicationJsonBodyParser: HttpBodyParser = async (\n request,\n parsedMediaType,\n topic,\n) => {\n const requestBody = request.body;\n if (!Buffer.isBuffer(requestBody)) {\n throw new Error(\n `Failed to retrieve raw body from incoming event for topic ${topic}; not a buffer: ${typeof requestBody}`,\n );\n }\n\n const bodyBuffer: Buffer = requestBody;\n\n const encoding = parsedMediaType.parameters.charset ?? 'utf-8';\n if (!Buffer.isEncoding(encoding)) {\n throw new UnsupportedCharsetError(encoding);\n }\n\n const bodyString = bodyBuffer.toString(encoding);\n const bodyParsed =\n parsedMediaType.type === 'application/json'\n ? JSON.parse(bodyString)\n : bodyString;\n return { bodyParsed, bodyBuffer, encoding };\n};\n"],"names":["UnsupportedCharsetError"],"mappings":";;;;AAkBO,MAAM,6BAAgD,GAAA,OAC3D,OACA,EAAA,eAAA,EACA,KACG,KAAA;AACH,EAAA,MAAM,cAAc,OAAQ,CAAA,IAAA;AAC5B,EAAA,IAAI,CAAC,MAAA,CAAO,QAAS,CAAA,WAAW,CAAG,EAAA;AACjC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAA6D,0DAAA,EAAA,KAAK,CAAmB,gBAAA,EAAA,OAAO,WAAW,CAAA;AAAA,KACzG;AAAA;AAGF,EAAA,MAAM,UAAqB,GAAA,WAAA;AAE3B,EAAM,MAAA,QAAA,GAAW,eAAgB,CAAA,UAAA,CAAW,OAAW,IAAA,OAAA;AACvD,EAAA,IAAI,CAAC,MAAA,CAAO,UAAW,CAAA,QAAQ,CAAG,EAAA;AAChC,IAAM,MAAA,IAAIA,+BAAwB,QAAQ,CAAA;AAAA;AAG5C,EAAM,MAAA,UAAA,GAAa,UAAW,CAAA,QAAA,CAAS,QAAQ,CAAA;AAC/C,EAAA,MAAM,aACJ,eAAgB,CAAA,IAAA,KAAS,qBACrB,IAAK,CAAA,KAAA,CAAM,UAAU,CACrB,GAAA,UAAA;AACN,EAAO,OAAA,EAAE,UAAY,EAAA,UAAA,EAAY,QAAS,EAAA;AAC5C;;;;"}
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ var HttpApplicationJsonBodyParser = require('./HttpApplicationJsonBodyParser.cjs.js');
4
+
5
+ const defaultHttpBodyParsers = {
6
+ "application/json": HttpApplicationJsonBodyParser.HttpApplicationJsonBodyParser
7
+ };
8
+
9
+ exports.defaultHttpBodyParsers = defaultHttpBodyParsers;
10
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs.js","sources":["../../../../src/service/http/body-parser/index.ts"],"sourcesContent":["/*\n * Copyright 2025 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 { HttpBodyParser } from '@backstage/plugin-events-node';\nimport { HttpApplicationJsonBodyParser } from './HttpApplicationJsonBodyParser';\n\nexport const defaultHttpBodyParsers: { [contentType: string]: HttpBodyParser } =\n {\n 'application/json': HttpApplicationJsonBodyParser,\n };\n"],"names":["HttpApplicationJsonBodyParser"],"mappings":";;;;AAkBO,MAAM,sBACX,GAAA;AAAA,EACE,kBAAoB,EAAAA;AACtB;;;;"}
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ var errors = require('@backstage/errors');
4
+
5
+ class UnsupportedCharsetError extends errors.CustomErrorBase {
6
+ name = "UnsupportedCharsetError";
7
+ statusCode = 415;
8
+ constructor(charset) {
9
+ super(`Unsupported charset: ${charset}`);
10
+ }
11
+ }
12
+ class UnsupportedMediaTypeError extends errors.CustomErrorBase {
13
+ name = "UnsupportedMediaTypeError";
14
+ statusCode = 415;
15
+ constructor(mediaType) {
16
+ super(
17
+ `Unsupported media type: ${mediaType ?? "unknown"}. You need to provide a custom body parser for this media type using the EventsExtensionPoint.`
18
+ );
19
+ }
20
+ }
21
+
22
+ exports.UnsupportedCharsetError = UnsupportedCharsetError;
23
+ exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError;
24
+ //# sourceMappingURL=errors.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs.js","sources":["../../../src/service/http/errors.ts"],"sourcesContent":["/*\n * Copyright 2025 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 { CustomErrorBase } from '@backstage/errors';\n\nexport class UnsupportedCharsetError extends CustomErrorBase {\n name = 'UnsupportedCharsetError' as const;\n statusCode = 415 as const;\n\n constructor(charset: string) {\n super(`Unsupported charset: ${charset}`);\n }\n}\n\nexport class UnsupportedMediaTypeError extends CustomErrorBase {\n name = 'UnsupportedMediaTypeError' as const;\n statusCode = 415 as const;\n\n constructor(mediaType?: string) {\n super(\n `Unsupported media type: ${\n mediaType ?? 'unknown'\n }. You need to provide a custom body parser for this media type using the EventsExtensionPoint.`,\n );\n }\n}\n"],"names":["CustomErrorBase"],"mappings":";;;;AAiBO,MAAM,gCAAgCA,sBAAgB,CAAA;AAAA,EAC3D,IAAO,GAAA,yBAAA;AAAA,EACP,UAAa,GAAA,GAAA;AAAA,EAEb,YAAY,OAAiB,EAAA;AAC3B,IAAM,KAAA,CAAA,CAAA,qBAAA,EAAwB,OAAO,CAAE,CAAA,CAAA;AAAA;AAE3C;AAEO,MAAM,kCAAkCA,sBAAgB,CAAA;AAAA,EAC7D,IAAO,GAAA,2BAAA;AAAA,EACP,UAAa,GAAA,GAAA;AAAA,EAEb,YAAY,SAAoB,EAAA;AAC9B,IAAA,KAAA;AAAA,MACE,CAAA,wBAAA,EACE,aAAa,SACf,CAAA,8FAAA;AAAA,KACF;AAAA;AAEJ;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-events-backend",
3
- "version": "0.4.4-next.0",
3
+ "version": "0.4.4-next.2",
4
4
  "backstage": {
5
5
  "role": "backend-plugin",
6
6
  "pluginId": "events",
@@ -43,7 +43,7 @@
43
43
  "types": "./dist/index.d.ts",
44
44
  "typesVersions": {
45
45
  "*": {
46
- "index": [
46
+ "*": [
47
47
  "dist/index.d.ts"
48
48
  ],
49
49
  "alpha": [
@@ -68,11 +68,11 @@
68
68
  },
69
69
  "dependencies": {
70
70
  "@backstage/backend-common": "^0.25.0",
71
- "@backstage/backend-openapi-utils": "0.5.1-next.0",
72
- "@backstage/backend-plugin-api": "1.2.1-next.0",
71
+ "@backstage/backend-openapi-utils": "0.5.1-next.1",
72
+ "@backstage/backend-plugin-api": "1.2.1-next.1",
73
73
  "@backstage/config": "1.3.2",
74
74
  "@backstage/errors": "1.2.7",
75
- "@backstage/plugin-events-node": "0.4.9-next.0",
75
+ "@backstage/plugin-events-node": "0.4.9-next.2",
76
76
  "@backstage/types": "1.2.1",
77
77
  "@types/express": "^4.17.6",
78
78
  "content-type": "^1.0.5",
@@ -82,12 +82,12 @@
82
82
  "winston": "^3.2.1"
83
83
  },
84
84
  "devDependencies": {
85
- "@backstage/backend-app-api": "1.2.1-next.0",
86
- "@backstage/backend-defaults": "0.8.2-next.0",
87
- "@backstage/backend-test-utils": "1.3.1-next.0",
88
- "@backstage/cli": "0.30.0",
89
- "@backstage/plugin-events-backend-test-utils": "0.1.42-next.0",
90
- "@backstage/repo-tools": "0.13.1-next.0",
85
+ "@backstage/backend-app-api": "1.2.1-next.2",
86
+ "@backstage/backend-defaults": "0.8.2-next.2",
87
+ "@backstage/backend-test-utils": "1.3.1-next.2",
88
+ "@backstage/cli": "0.31.0-next.1",
89
+ "@backstage/plugin-events-backend-test-utils": "0.1.42-next.2",
90
+ "@backstage/repo-tools": "0.13.1-next.2",
91
91
  "@types/content-type": "^1.1.8",
92
92
  "supertest": "^7.0.0"
93
93
  },