@backstage/backend-openapi-utils 0.3.1-next.0 → 0.4.0-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,27 @@
1
1
  # @backstage/backend-openapi-utils
2
2
 
3
+ ## 0.4.0-next.2
4
+
5
+ ### Minor Changes
6
+
7
+ - afcebea: Fixed a Typescript error when trying to use the new OpenAPI server-side generated code.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies
12
+ - @backstage/backend-plugin-api@1.1.0-next.2
13
+ - @backstage/errors@1.2.6-next.0
14
+ - @backstage/types@1.2.0
15
+
16
+ ## 0.3.1-next.1
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies
21
+ - @backstage/backend-plugin-api@1.1.0-next.1
22
+ - @backstage/errors@1.2.5
23
+ - @backstage/types@1.2.0
24
+
3
25
  ## 0.3.1-next.0
4
26
 
5
27
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -466,15 +466,6 @@ interface EndpointMapRequestMatcher<Doc extends EndpointMap, T, Method extends H
466
466
  <TPath extends MethodAwareDocEndpoints<Doc, DocEndpoint<Doc>, Method & DocEndpointMethod<Doc, DocEndpoint<Doc>>>, TMethod extends Method & DocEndpointMethod<Doc, TemplateToDocEndpoint<Doc, TPath>>>(path: TPath, ...handlers: Array<EndpointMapRequestHandler<Doc, TemplateToDocEndpoint<Doc, TPath>, TMethod>>): T;
467
467
  <TPath extends MethodAwareDocEndpoints<Doc, DocEndpoint<Doc>, Method & DocEndpointMethod<Doc, DocEndpoint<Doc>>>, TMethod extends Method & DocEndpointMethod<Doc, TemplateToDocEndpoint<Doc, TPath>>>(path: TPath, ...handlers: Array<EndpointMapRequestHandlerParams<Doc, TemplateToDocEndpoint<Doc, TPath>, TMethod>>): T;
468
468
  }
469
- /**
470
- * @public
471
- */
472
- interface TypedRouter<GeneratedEndpointMap extends EndpointMap> extends Router {
473
- get: EndpointMapRequestMatcher<GeneratedEndpointMap, this, 'get'>;
474
- post: EndpointMapRequestMatcher<GeneratedEndpointMap, this, 'post'>;
475
- put: EndpointMapRequestMatcher<GeneratedEndpointMap, this, 'put'>;
476
- delete: EndpointMapRequestMatcher<GeneratedEndpointMap, this, '_delete'>;
477
- }
478
469
 
479
470
  type index_d_ComponentRef<Doc extends RequiredDoc, Type extends ComponentTypes<Doc>, Ref extends ImmutableReferenceObject> = ComponentRef<Doc, Type, Ref>;
480
471
  type index_d_ComponentTypes<Doc extends RequiredDoc> = ComponentTypes<Doc>;
@@ -564,12 +555,11 @@ type index_d_TemplateToDocEndpoint<Doc extends EndpointMap, Path extends DocEndp
564
555
  type index_d_TemplateToDocPath<Doc extends PathDoc, Path extends DocPathTemplate<Doc>> = TemplateToDocPath<Doc, Path>;
565
556
  type index_d_ToTypeSafe<T> = ToTypeSafe<T>;
566
557
  type index_d_TuplifyUnion<T, L = LastOf<T>, N = [T] extends [never] ? true : false> = TuplifyUnion<T, L, N>;
567
- type index_d_TypedRouter<GeneratedEndpointMap extends EndpointMap> = TypedRouter<GeneratedEndpointMap>;
568
558
  type index_d_UnionToIntersection<U> = UnionToIntersection<U>;
569
559
  type index_d_UnknownIfNever<P> = UnknownIfNever<P>;
570
560
  type index_d_ValueOf<T> = ValueOf<T>;
571
561
  declare namespace index_d {
572
- export type { index_d_ComponentRef as ComponentRef, index_d_ComponentTypes as ComponentTypes, index_d_ConvertAll as ConvertAll, index_d_CookieObject as CookieObject, index_d_CookieSchema as CookieSchema, index_d_DiscriminateUnion as DiscriminateUnion, index_d_DocEndpoint as DocEndpoint, index_d_DocEndpointMethod as DocEndpointMethod, index_d_DocEndpointTemplate as DocEndpointTemplate, index_d_DocOperation as DocOperation, index_d_DocParameter as DocParameter, index_d_DocParameters as DocParameters, index_d_DocPath as DocPath, index_d_DocPathMethod as DocPathMethod, index_d_DocPathTemplate as DocPathTemplate, index_d_DocPathTemplateMethod as DocPathTemplateMethod, index_d_DocRequestHandler as DocRequestHandler, index_d_DocRequestHandlerParams as DocRequestHandlerParams, index_d_DocRequestMatcher as DocRequestMatcher, index_d_EndpointMap as EndpointMap, index_d_EndpointMapRequestHandler as EndpointMapRequestHandler, index_d_EndpointMapRequestHandlerParams as EndpointMapRequestHandlerParams, index_d_EndpointMapRequestMatcher as EndpointMapRequestMatcher, index_d_Filter as Filter, index_d_FromNumberStringToNumber as FromNumberStringToNumber, index_d_FullMap as FullMap, index_d_HeaderObject as HeaderObject, index_d_HeaderSchema as HeaderSchema, index_d_HttpMethods as HttpMethods, index_d_Immutable as Immutable, index_d_ImmutableContentObject as ImmutableContentObject, index_d_ImmutableCookieObject as ImmutableCookieObject, index_d_ImmutableHeaderObject as ImmutableHeaderObject, index_d_ImmutableObject as ImmutableObject, index_d_ImmutableOpenAPIObject as ImmutableOpenAPIObject, index_d_ImmutableParameterObject as ImmutableParameterObject, index_d_ImmutablePathObject as ImmutablePathObject, index_d_ImmutableQueryObject as ImmutableQueryObject, index_d_ImmutableReferenceObject as ImmutableReferenceObject, index_d_ImmutableRequestBodyObject as ImmutableRequestBodyObject, index_d_ImmutableResponseObject as ImmutableResponseObject, index_d_ImmutableSchemaObject as ImmutableSchemaObject, index_d_LastOf as LastOf, index_d_MapDiscriminatedUnion as MapDiscriminatedUnion, index_d_MapToSchema as MapToSchema, index_d_MethodAwareDocEndpoints as MethodAwareDocEndpoints, index_d_MethodAwareDocPath as MethodAwareDocPath, index_d_ObjectWithContentSchema as ObjectWithContentSchema, index_d_OptionalMap as OptionalMap, index_d_ParameterSchema as ParameterSchema, index_d_ParametersSchema as ParametersSchema, index_d_PathDoc as PathDoc, index_d_PathObject as PathObject, index_d_PathSchema as PathSchema, index_d_PathTemplate as PathTemplate, index_d_PickOptionalKeys as PickOptionalKeys, index_d_PickRequiredKeys as PickRequiredKeys, index_d_Push as Push, index_d_QueryObject as QueryObject, index_d_QuerySchema as QuerySchema, index_d_RequestBody as RequestBody, index_d_RequestBodySchema as RequestBodySchema, index_d_RequestBodyToJsonSchema as RequestBodyToJsonSchema, index_d_RequiredDoc as RequiredDoc, index_d_RequiredMap as RequiredMap, Response$1 as Response, index_d_ResponseBodyToJsonSchema as ResponseBodyToJsonSchema, index_d_ResponseSchemas as ResponseSchemas, index_d_SchemaRef as SchemaRef, index_d_StaticPathParamsSchema as StaticPathParamsSchema, index_d_StaticQueryParamsSchema as StaticQueryParamsSchema, index_d_StaticRequestBodySchema as StaticRequestBodySchema, index_d_StaticResponseSchema as StaticResponseSchema, index_d_TemplateToDocEndpoint as TemplateToDocEndpoint, index_d_TemplateToDocPath as TemplateToDocPath, index_d_ToTypeSafe as ToTypeSafe, index_d_TuplifyUnion as TuplifyUnion, index_d_TypedRouter as TypedRouter, index_d_UnionToIntersection as UnionToIntersection, index_d_UnknownIfNever as UnknownIfNever, index_d_ValueOf as ValueOf };
562
+ export type { index_d_ComponentRef as ComponentRef, index_d_ComponentTypes as ComponentTypes, index_d_ConvertAll as ConvertAll, index_d_CookieObject as CookieObject, index_d_CookieSchema as CookieSchema, index_d_DiscriminateUnion as DiscriminateUnion, index_d_DocEndpoint as DocEndpoint, index_d_DocEndpointMethod as DocEndpointMethod, index_d_DocEndpointTemplate as DocEndpointTemplate, index_d_DocOperation as DocOperation, index_d_DocParameter as DocParameter, index_d_DocParameters as DocParameters, index_d_DocPath as DocPath, index_d_DocPathMethod as DocPathMethod, index_d_DocPathTemplate as DocPathTemplate, index_d_DocPathTemplateMethod as DocPathTemplateMethod, index_d_DocRequestHandler as DocRequestHandler, index_d_DocRequestHandlerParams as DocRequestHandlerParams, index_d_DocRequestMatcher as DocRequestMatcher, index_d_EndpointMap as EndpointMap, index_d_EndpointMapRequestHandler as EndpointMapRequestHandler, index_d_EndpointMapRequestHandlerParams as EndpointMapRequestHandlerParams, index_d_EndpointMapRequestMatcher as EndpointMapRequestMatcher, index_d_Filter as Filter, index_d_FromNumberStringToNumber as FromNumberStringToNumber, index_d_FullMap as FullMap, index_d_HeaderObject as HeaderObject, index_d_HeaderSchema as HeaderSchema, index_d_HttpMethods as HttpMethods, index_d_Immutable as Immutable, index_d_ImmutableContentObject as ImmutableContentObject, index_d_ImmutableCookieObject as ImmutableCookieObject, index_d_ImmutableHeaderObject as ImmutableHeaderObject, index_d_ImmutableObject as ImmutableObject, index_d_ImmutableOpenAPIObject as ImmutableOpenAPIObject, index_d_ImmutableParameterObject as ImmutableParameterObject, index_d_ImmutablePathObject as ImmutablePathObject, index_d_ImmutableQueryObject as ImmutableQueryObject, index_d_ImmutableReferenceObject as ImmutableReferenceObject, index_d_ImmutableRequestBodyObject as ImmutableRequestBodyObject, index_d_ImmutableResponseObject as ImmutableResponseObject, index_d_ImmutableSchemaObject as ImmutableSchemaObject, index_d_LastOf as LastOf, index_d_MapDiscriminatedUnion as MapDiscriminatedUnion, index_d_MapToSchema as MapToSchema, index_d_MethodAwareDocEndpoints as MethodAwareDocEndpoints, index_d_MethodAwareDocPath as MethodAwareDocPath, index_d_ObjectWithContentSchema as ObjectWithContentSchema, index_d_OptionalMap as OptionalMap, index_d_ParameterSchema as ParameterSchema, index_d_ParametersSchema as ParametersSchema, index_d_PathDoc as PathDoc, index_d_PathObject as PathObject, index_d_PathSchema as PathSchema, index_d_PathTemplate as PathTemplate, index_d_PickOptionalKeys as PickOptionalKeys, index_d_PickRequiredKeys as PickRequiredKeys, index_d_Push as Push, index_d_QueryObject as QueryObject, index_d_QuerySchema as QuerySchema, index_d_RequestBody as RequestBody, index_d_RequestBodySchema as RequestBodySchema, index_d_RequestBodyToJsonSchema as RequestBodyToJsonSchema, index_d_RequiredDoc as RequiredDoc, index_d_RequiredMap as RequiredMap, Response$1 as Response, index_d_ResponseBodyToJsonSchema as ResponseBodyToJsonSchema, index_d_ResponseSchemas as ResponseSchemas, index_d_SchemaRef as SchemaRef, index_d_StaticPathParamsSchema as StaticPathParamsSchema, index_d_StaticQueryParamsSchema as StaticQueryParamsSchema, index_d_StaticRequestBodySchema as StaticRequestBodySchema, index_d_StaticResponseSchema as StaticResponseSchema, index_d_TemplateToDocEndpoint as TemplateToDocEndpoint, index_d_TemplateToDocPath as TemplateToDocPath, index_d_ToTypeSafe as ToTypeSafe, index_d_TuplifyUnion as TuplifyUnion, index_d_UnionToIntersection as UnionToIntersection, index_d_UnknownIfNever as UnknownIfNever, index_d_ValueOf as ValueOf };
573
563
  }
574
564
 
575
565
  /**
@@ -611,6 +601,15 @@ interface ApiRouter<Doc extends RequiredDoc> extends Router {
611
601
  options: DocRequestMatcher<Doc, this, 'options'>;
612
602
  head: DocRequestMatcher<Doc, this, 'head'>;
613
603
  }
604
+ /**
605
+ * @public
606
+ */
607
+ interface TypedRouter<GeneratedEndpointMap extends EndpointMap> extends Router {
608
+ get: EndpointMapRequestMatcher<GeneratedEndpointMap, this, 'get'>;
609
+ post: EndpointMapRequestMatcher<GeneratedEndpointMap, this, 'post'>;
610
+ put: EndpointMapRequestMatcher<GeneratedEndpointMap, this, 'put'>;
611
+ delete: EndpointMapRequestMatcher<GeneratedEndpointMap, this, '_delete'>;
612
+ }
614
613
 
615
614
  /**
616
615
  * !!! THIS CURRENTLY ONLY SUPPORTS SUPERTEST !!!
@@ -661,4 +660,4 @@ declare function createValidatedOpenApiRouterFromGeneratedEndpointMap<T extends
661
660
  middleware?: RequestHandler[];
662
661
  }): TypedRouter<T>;
663
662
 
664
- export { type ApiRouter, type CookieParameters, type HeaderParameters, type PathParameters, type PathTemplate, type QueryParameters, type Request, type Response, createValidatedOpenApiRouter, createValidatedOpenApiRouterFromGeneratedEndpointMap, getOpenApiSpecRoute, index_d as internal, wrapInOpenApiTestServer, wrapServer };
663
+ export { type ApiRouter, type CookieParameters, type HeaderParameters, type PathParameters, type PathTemplate, type QueryParameters, type Request, type Response, type TypedRouter, createValidatedOpenApiRouter, createValidatedOpenApiRouterFromGeneratedEndpointMap, getOpenApiSpecRoute, index_d as internal, wrapInOpenApiTestServer, wrapServer };
@@ -1 +1 @@
1
- {"version":3,"file":"stub.cjs.js","sources":["../src/stub.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport PromiseRouter from 'express-promise-router';\nimport { ApiRouter } from './router';\nimport { EndpointMap, RequiredDoc, TypedRouter } from './types';\nimport {\n ErrorRequestHandler,\n RequestHandler,\n NextFunction,\n Request,\n Response,\n json,\n Router,\n} from 'express';\nimport { InputError } from '@backstage/errors';\nimport { middleware as OpenApiValidator } from 'express-openapi-validator';\nimport { OPENAPI_SPEC_ROUTE } from './constants';\nimport { isErrorResult, merge } from 'openapi-merge';\n\ntype PropertyOverrideRequest = Request & {\n [key: symbol]: string;\n};\n\nconst baseUrlSymbol = Symbol();\nconst originalUrlSymbol = Symbol();\n\nfunction validatorErrorTransformer(): ErrorRequestHandler {\n return (error: Error, _: Request, _2: Response, next: NextFunction) => {\n next(new InputError(error.message));\n };\n}\n\nexport function getDefaultRouterMiddleware() {\n return [json()];\n}\n\n/**\n * Given a base url for a plugin, find the given OpenAPI spec for that plugin.\n * @param baseUrl - Plugin base url.\n * @returns OpenAPI spec route for the base url.\n * @public\n */\nexport function getOpenApiSpecRoute(baseUrl: string) {\n return `${baseUrl}${OPENAPI_SPEC_ROUTE}`;\n}\n\n/**\n * Create a router with validation middleware. This is used by typing methods to create an\n * \"OpenAPI router\" with all of the expected validation + metadata.\n * @param spec - Your OpenAPI spec imported as a JSON object.\n * @param validatorOptions - `openapi-express-validator` options to override the defaults.\n * @returns A new express router with validation middleware.\n */\nfunction createRouterWithValidation(\n spec: RequiredDoc,\n options?: {\n validatorOptions?: Partial<Parameters<typeof OpenApiValidator>['0']>;\n middleware?: RequestHandler[];\n },\n): Router {\n const router = PromiseRouter();\n router.use(options?.middleware || getDefaultRouterMiddleware());\n\n /**\n * Middleware to setup the routing for OpenApiValidator. OpenApiValidator expects `req.originalUrl`\n * and `req.baseUrl` to be the full path. We adjust them here to basically be nothing and then\n * revive the old values in the last function in this method. We could instead update `req.path`\n * but that might affect the routing and I'd rather not.\n *\n * TODO: I opened https://github.com/cdimascio/express-openapi-validator/issues/843\n * to track this on the middleware side, but there was a similar ticket, https://github.com/cdimascio/express-openapi-validator/issues/113\n * that has had minimal activity. If that changes, update this to use a new option on their side.\n */\n router.use((req: Request, _, next) => {\n /**\n * Express typings are weird. They don't recognize PropertyOverrideRequest as a valid\n * Request child and try to overload as PathParams. Just cast it here, since we know\n * what we're doing.\n */\n const customRequest = req as PropertyOverrideRequest;\n customRequest[baseUrlSymbol] = customRequest.baseUrl;\n customRequest.baseUrl = '';\n customRequest[originalUrlSymbol] = customRequest.originalUrl;\n customRequest.originalUrl = customRequest.url;\n next();\n });\n\n // TODO: Handle errors by converting from OpenApiValidator errors to known @backstage/errors errors.\n router.use(\n OpenApiValidator({\n validateRequests: {\n coerceTypes: false,\n allowUnknownQueryParameters: false,\n },\n ignoreUndocumented: true,\n validateResponses: false,\n ...options?.validatorOptions,\n apiSpec: spec as any,\n }),\n );\n\n /**\n * Revert `req.baseUrl` and `req.originalUrl` changes. This ensures that any further usage\n * of these variables will be unchanged.\n */\n router.use((req: Request, _, next) => {\n const customRequest = req as PropertyOverrideRequest;\n customRequest.baseUrl = customRequest[baseUrlSymbol];\n customRequest.originalUrl = customRequest[originalUrlSymbol];\n delete customRequest[baseUrlSymbol];\n delete customRequest[originalUrlSymbol];\n next();\n });\n\n // Any errors from the middleware get through here.\n router.use(validatorErrorTransformer());\n\n router.get(OPENAPI_SPEC_ROUTE, async (req, res) => {\n const mergeOutput = merge([\n {\n oas: spec as any,\n pathModification: {\n /**\n * Get the route that this OpenAPI spec is hosted on. The other\n * approach of using the discovery API increases the router constructor\n * significantly and since we're just looking for path and not full URL,\n * this works.\n *\n * If we wanted to add a list of servers, there may be a case for adding\n * discovery API to get an exhaustive list of upstream servers, but that's\n * also not currently supported.\n */\n prepend: req.originalUrl.replace(OPENAPI_SPEC_ROUTE, ''),\n },\n },\n ]);\n if (isErrorResult(mergeOutput)) {\n throw new InputError('Invalid spec defined');\n }\n res.json(mergeOutput.output);\n });\n return router;\n}\n\n/**\n * Create a new OpenAPI router with some default middleware.\n * @param spec - Your OpenAPI spec imported as a JSON object.\n * @param validatorOptions - `openapi-express-validator` options to override the defaults.\n * @returns A new express router with validation middleware.\n * @public\n */\nexport function createValidatedOpenApiRouter<T extends RequiredDoc>(\n spec: T,\n options?: {\n validatorOptions?: Partial<Parameters<typeof OpenApiValidator>['0']>;\n middleware?: RequestHandler[];\n },\n) {\n return createRouterWithValidation(spec, options) as ApiRouter<typeof spec>;\n}\n\n/**\n * Create a new OpenAPI router with some default middleware.\n * @param spec - Your OpenAPI spec imported as a JSON object.\n * @param validatorOptions - `openapi-express-validator` options to override the defaults.\n * @returns A new express router with validation middleware.\n * @public\n */\nexport function createValidatedOpenApiRouterFromGeneratedEndpointMap<\n T extends EndpointMap,\n>(\n spec: RequiredDoc,\n options?: {\n validatorOptions?: Partial<Parameters<typeof OpenApiValidator>['0']>;\n middleware?: RequestHandler[];\n },\n) {\n return createRouterWithValidation(spec, options) as TypedRouter<T>;\n}\n"],"names":["InputError","json","OPENAPI_SPEC_ROUTE","PromiseRouter","OpenApiValidator","merge","isErrorResult"],"mappings":";;;;;;;;;;;;;AAqCA,MAAM,gBAAgB,MAAO,EAAA;AAC7B,MAAM,oBAAoB,MAAO,EAAA;AAEjC,SAAS,yBAAiD,GAAA;AACxD,EAAA,OAAO,CAAC,KAAA,EAAc,CAAY,EAAA,EAAA,EAAc,IAAuB,KAAA;AACrE,IAAA,IAAA,CAAK,IAAIA,iBAAA,CAAW,KAAM,CAAA,OAAO,CAAC,CAAA;AAAA,GACpC;AACF;AAEO,SAA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,cAAc,aAAa,CAAA;AAClC,IAAA,OAAO,cAAc,iBAAiB,CAAA;AACtC,IAAK,IAAA,EAAA;AAAA,GACN,CAAA;AAGD,EAAO,MAAA,CAAA,GAAA,CAAI,2BAA2B,CAAA;AAEtC,EAAA,MAAA,CAAO,GAAI,CAAAF,4BAAA,EAAoB,OAAO,GAAA,EAAK,GAAQ,KAAA;AACjD,IAAA,MAAM,cAAcG,kBAAM,CAAA;AAAA,MACxB;AAAA,QACE,GAAK,EAAA,IAAA;AAAA,QACL,gBAAkB,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAWhB,OAAS,EAAA,GAAA,CAAI,WAAY,CAAA,OAAA,CAAQH,8BAAoB,EAAE;AAAA;AACzD;AACF,KACD,CAAA;AACD,IAAI,IAAAI,0BAAA,CAAc,WAAW,CAAG,EAAA;AAC9B,MAAM,MAAA,IAAIN,kBAAW,sBAAsB,CAAA;AAAA;AAE7C,IAAI,GAAA,CAAA,IAAA,CAAK,YAAY,MAAM,CAAA;AAAA,GAC5B,CAAA;AACD,EAAO,OAAA,MAAA;AACT;AASgB,SAAA,4BAAA,CACd,MACA,OAIA,EAAA;AACA,EAAO,OAAA,0BAAA,CAA2B,MAAM,OAAO,CAAA;AACjD;AASgB,SAAA,oDAAA,CAGd,MACA,OAIA,EAAA;AACA,EAAO,OAAA,0BAAA,CAA2B,MAAM,OAAO,CAAA;AACjD;;;;;;;"}
1
+ {"version":3,"file":"stub.cjs.js","sources":["../src/stub.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport PromiseRouter from 'express-promise-router';\nimport { ApiRouter, TypedRouter } from './router';\nimport { EndpointMap, RequiredDoc } from './types';\nimport {\n ErrorRequestHandler,\n RequestHandler,\n NextFunction,\n Request,\n Response,\n json,\n Router,\n} from 'express';\nimport { InputError } from '@backstage/errors';\nimport { middleware as OpenApiValidator } from 'express-openapi-validator';\nimport { OPENAPI_SPEC_ROUTE } from './constants';\nimport { isErrorResult, merge } from 'openapi-merge';\n\ntype PropertyOverrideRequest = Request & {\n [key: symbol]: string;\n};\n\nconst baseUrlSymbol = Symbol();\nconst originalUrlSymbol = Symbol();\n\nfunction validatorErrorTransformer(): ErrorRequestHandler {\n return (error: Error, _: Request, _2: Response, next: NextFunction) => {\n next(new InputError(error.message));\n };\n}\n\nexport function getDefaultRouterMiddleware() {\n return [json()];\n}\n\n/**\n * Given a base url for a plugin, find the given OpenAPI spec for that plugin.\n * @param baseUrl - Plugin base url.\n * @returns OpenAPI spec route for the base url.\n * @public\n */\nexport function getOpenApiSpecRoute(baseUrl: string) {\n return `${baseUrl}${OPENAPI_SPEC_ROUTE}`;\n}\n\n/**\n * Create a router with validation middleware. This is used by typing methods to create an\n * \"OpenAPI router\" with all of the expected validation + metadata.\n * @param spec - Your OpenAPI spec imported as a JSON object.\n * @param validatorOptions - `openapi-express-validator` options to override the defaults.\n * @returns A new express router with validation middleware.\n */\nfunction createRouterWithValidation(\n spec: RequiredDoc,\n options?: {\n validatorOptions?: Partial<Parameters<typeof OpenApiValidator>['0']>;\n middleware?: RequestHandler[];\n },\n): Router {\n const router = PromiseRouter();\n router.use(options?.middleware || getDefaultRouterMiddleware());\n\n /**\n * Middleware to setup the routing for OpenApiValidator. OpenApiValidator expects `req.originalUrl`\n * and `req.baseUrl` to be the full path. We adjust them here to basically be nothing and then\n * revive the old values in the last function in this method. We could instead update `req.path`\n * but that might affect the routing and I'd rather not.\n *\n * TODO: I opened https://github.com/cdimascio/express-openapi-validator/issues/843\n * to track this on the middleware side, but there was a similar ticket, https://github.com/cdimascio/express-openapi-validator/issues/113\n * that has had minimal activity. If that changes, update this to use a new option on their side.\n */\n router.use((req: Request, _, next) => {\n /**\n * Express typings are weird. They don't recognize PropertyOverrideRequest as a valid\n * Request child and try to overload as PathParams. Just cast it here, since we know\n * what we're doing.\n */\n const customRequest = req as PropertyOverrideRequest;\n customRequest[baseUrlSymbol] = customRequest.baseUrl;\n customRequest.baseUrl = '';\n customRequest[originalUrlSymbol] = customRequest.originalUrl;\n customRequest.originalUrl = customRequest.url;\n next();\n });\n\n // TODO: Handle errors by converting from OpenApiValidator errors to known @backstage/errors errors.\n router.use(\n OpenApiValidator({\n validateRequests: {\n coerceTypes: false,\n allowUnknownQueryParameters: false,\n },\n ignoreUndocumented: true,\n validateResponses: false,\n ...options?.validatorOptions,\n apiSpec: spec as any,\n }),\n );\n\n /**\n * Revert `req.baseUrl` and `req.originalUrl` changes. This ensures that any further usage\n * of these variables will be unchanged.\n */\n router.use((req: Request, _, next) => {\n const customRequest = req as PropertyOverrideRequest;\n customRequest.baseUrl = customRequest[baseUrlSymbol];\n customRequest.originalUrl = customRequest[originalUrlSymbol];\n delete customRequest[baseUrlSymbol];\n delete customRequest[originalUrlSymbol];\n next();\n });\n\n // Any errors from the middleware get through here.\n router.use(validatorErrorTransformer());\n\n router.get(OPENAPI_SPEC_ROUTE, async (req, res) => {\n const mergeOutput = merge([\n {\n oas: spec as any,\n pathModification: {\n /**\n * Get the route that this OpenAPI spec is hosted on. The other\n * approach of using the discovery API increases the router constructor\n * significantly and since we're just looking for path and not full URL,\n * this works.\n *\n * If we wanted to add a list of servers, there may be a case for adding\n * discovery API to get an exhaustive list of upstream servers, but that's\n * also not currently supported.\n */\n prepend: req.originalUrl.replace(OPENAPI_SPEC_ROUTE, ''),\n },\n },\n ]);\n if (isErrorResult(mergeOutput)) {\n throw new InputError('Invalid spec defined');\n }\n res.json(mergeOutput.output);\n });\n return router;\n}\n\n/**\n * Create a new OpenAPI router with some default middleware.\n * @param spec - Your OpenAPI spec imported as a JSON object.\n * @param validatorOptions - `openapi-express-validator` options to override the defaults.\n * @returns A new express router with validation middleware.\n * @public\n */\nexport function createValidatedOpenApiRouter<T extends RequiredDoc>(\n spec: T,\n options?: {\n validatorOptions?: Partial<Parameters<typeof OpenApiValidator>['0']>;\n middleware?: RequestHandler[];\n },\n) {\n return createRouterWithValidation(spec, options) as ApiRouter<typeof spec>;\n}\n\n/**\n * Create a new OpenAPI router with some default middleware.\n * @param spec - Your OpenAPI spec imported as a JSON object.\n * @param validatorOptions - `openapi-express-validator` options to override the defaults.\n * @returns A new express router with validation middleware.\n * @public\n */\nexport function createValidatedOpenApiRouterFromGeneratedEndpointMap<\n T extends EndpointMap,\n>(\n spec: RequiredDoc,\n options?: {\n validatorOptions?: Partial<Parameters<typeof OpenApiValidator>['0']>;\n middleware?: RequestHandler[];\n },\n) {\n return createRouterWithValidation(spec, options) as TypedRouter<T>;\n}\n"],"names":["InputError","json","OPENAPI_SPEC_ROUTE","PromiseRouter","OpenApiValidator","merge","isErrorResult"],"mappings":";;;;;;;;;;;;;AAqCA,MAAM,gBAAgB,MAAO,EAAA;AAC7B,MAAM,oBAAoB,MAAO,EAAA;AAEjC,SAAS,yBAAiD,GAAA;AACxD,EAAA,OAAO,CAAC,KAAA,EAAc,CAAY,EAAA,EAAA,EAAc,IAAuB,KAAA;AACrE,IAAA,IAAA,CAAK,IAAIA,iBAAA,CAAW,KAAM,CAAA,OAAO,CAAC,CAAA;AAAA,GACpC;AACF;AAEO,SAAS,0BAA6B,GAAA;AAC3C,EAAO,OAAA,CAACC,cAAM,CAAA;AAChB;AAQO,SAAS,oBAAoB,OAAiB,EAAA;AACnD,EAAO,OAAA,CAAA,EAAG,OAAO,CAAA,EAAGC,4BAAkB,CAAA,CAAA;AACxC;AASA,SAAS,0BAAA,CACP,MACA,OAIQ,EAAA;AACR,EAAA,MAAM,SAASC,8BAAc,EAAA;AAC7B,EAAA,MAAA,CAAO,GAAI,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MACxB;AAAA,QACE,GAAK,EAAA,IAAA;AAAA,QACL,gBAAkB,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAWhB,OAAS,EAAA,GAAA,CAAI,WAAY,CAAA,OAAA,CAAQH,8BAAoB,EAAE;AAAA;AACzD;AACF,KACD,CAAA;AACD,IAAI,IAAAI,0BAAA,CAAc,WAAW,CAAG,EAAA;AAC9B,MAAM,MAAA,IAAIN,kBAAW,sBAAsB,CAAA;AAAA;AAE7C,IAAI,GAAA,CAAA,IAAA,CAAK,YAAY,MAAM,CAAA;AAAA,GAC5B,CAAA;AACD,EAAO,OAAA,MAAA;AACT;AASgB,SAAA,4BAAA,CACd,MACA,OAIA,EAAA;AACA,EAAO,OAAA,0BAAA,CAA2B,MAAM,OAAO,CAAA;AACjD;AASgB,SAAA,oDAAA,CAGd,MACA,OAIA,EAAA;AACA,EAAO,OAAA,0BAAA,CAA2B,MAAM,OAAO,CAAA;AACjD;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/backend-openapi-utils",
3
- "version": "0.3.1-next.0",
3
+ "version": "0.4.0-next.2",
4
4
  "description": "OpenAPI typescript support.",
5
5
  "backstage": {
6
6
  "role": "node-library"
@@ -34,8 +34,8 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@apidevtools/swagger-parser": "^10.1.0",
37
- "@backstage/backend-plugin-api": "1.0.3-next.0",
38
- "@backstage/errors": "1.2.5",
37
+ "@backstage/backend-plugin-api": "1.1.0-next.2",
38
+ "@backstage/errors": "1.2.6-next.0",
39
39
  "@backstage/types": "1.2.0",
40
40
  "@types/express": "^4.17.6",
41
41
  "@types/express-serve-static-core": "^4.17.5",
@@ -51,8 +51,8 @@
51
51
  "openapi3-ts": "^3.1.2"
52
52
  },
53
53
  "devDependencies": {
54
- "@backstage/cli": "0.29.3-next.0",
55
- "@backstage/test-utils": "1.7.3-next.0",
54
+ "@backstage/cli": "0.29.3-next.2",
55
+ "@backstage/test-utils": "1.7.3-next.1",
56
56
  "msw": "^1.0.0",
57
57
  "supertest": "^7.0.0"
58
58
  },