@visulima/api-platform 1.2.1 → 1.2.3

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.
Files changed (67) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/chunk-EP2A5R2C.js +13 -0
  3. package/dist/chunk-EP2A5R2C.js.map +1 -0
  4. package/dist/chunk-ESKLEDNF.mjs +13 -0
  5. package/dist/chunk-ESKLEDNF.mjs.map +1 -0
  6. package/dist/chunk-IMU5ULVF.js +18 -0
  7. package/dist/chunk-IMU5ULVF.js.map +1 -0
  8. package/dist/chunk-OC7L637G.js +23 -0
  9. package/dist/chunk-OC7L637G.js.map +1 -0
  10. package/dist/chunk-OUWZ2PU5.js +6 -1
  11. package/dist/chunk-OUWZ2PU5.js.map +1 -1
  12. package/dist/chunk-PXVY7JQL.js +19 -0
  13. package/dist/chunk-PXVY7JQL.js.map +1 -0
  14. package/dist/chunk-R22PP2JL.mjs +17 -0
  15. package/dist/chunk-R22PP2JL.mjs.map +1 -0
  16. package/dist/chunk-SCOIFGN7.mjs +19 -0
  17. package/dist/chunk-SCOIFGN7.mjs.map +1 -0
  18. package/dist/chunk-WJDS32PO.mjs +9 -0
  19. package/dist/chunk-WJDS32PO.mjs.map +1 -0
  20. package/dist/chunk-YOXCJZNX.mjs +4 -1
  21. package/dist/chunk-YOXCJZNX.mjs.map +1 -1
  22. package/dist/framework/cli/commander/index.js +10 -1
  23. package/dist/framework/cli/commander/index.js.map +1 -1
  24. package/dist/framework/cli/commander/index.mjs +8 -1
  25. package/dist/framework/cli/commander/index.mjs.map +1 -1
  26. package/dist/framework/cli/index.d.ts +3 -3
  27. package/dist/framework/cli/index.js +12 -1
  28. package/dist/framework/cli/index.mjs +3 -1
  29. package/dist/framework/cli/index.mjs.map +1 -1
  30. package/dist/framework/next/index-browser.d.ts +1 -1
  31. package/dist/framework/next/index-browser.js +20 -1
  32. package/dist/framework/next/index-browser.mjs +3 -1
  33. package/dist/framework/next/index-browser.mjs.map +1 -1
  34. package/dist/framework/next/index-server.d.ts +5 -122
  35. package/dist/framework/next/index-server.js +26 -1
  36. package/dist/framework/next/index-server.js.map +1 -1
  37. package/dist/framework/next/index-server.mjs +11 -1
  38. package/dist/framework/next/index-server.mjs.map +1 -1
  39. package/dist/{index-3318b0da.d.ts → index-bd61921e.d.ts} +0 -0
  40. package/dist/index-browser.d.ts +1 -1
  41. package/dist/index-browser.js +12 -1
  42. package/dist/index-browser.mjs +3 -1
  43. package/dist/index-browser.mjs.map +1 -1
  44. package/dist/index-server.d.ts +9 -9
  45. package/dist/index-server.js +235 -1
  46. package/dist/index-server.js.map +1 -1
  47. package/dist/index-server.mjs +19 -1
  48. package/dist/index-server.mjs.map +1 -1
  49. package/dist/{swagger-e843ad44.d.ts → swagger-b2ff43e0.d.ts} +0 -0
  50. package/dist/{swagger-handler-2eeb6a85.d.ts → swagger-handler-8947e0f1.d.ts} +4 -4
  51. package/package.json +59 -58
  52. package/dist/chunk-5P4SXSAZ.js +0 -6
  53. package/dist/chunk-5P4SXSAZ.js.map +0 -1
  54. package/dist/chunk-GTXHW632.mjs +0 -10
  55. package/dist/chunk-GTXHW632.mjs.map +0 -1
  56. package/dist/chunk-HONWWBY6.mjs +0 -2
  57. package/dist/chunk-HONWWBY6.mjs.map +0 -1
  58. package/dist/chunk-JXD3457O.js +0 -2
  59. package/dist/chunk-JXD3457O.js.map +0 -1
  60. package/dist/chunk-KJQOIMY2.mjs +0 -2
  61. package/dist/chunk-KJQOIMY2.mjs.map +0 -1
  62. package/dist/chunk-LS3DG7TO.js +0 -2
  63. package/dist/chunk-LS3DG7TO.js.map +0 -1
  64. package/dist/chunk-NR4FOSWI.js +0 -10
  65. package/dist/chunk-NR4FOSWI.js.map +0 -1
  66. package/dist/chunk-O4X5VJKA.mjs +0 -6
  67. package/dist/chunk-O4X5VJKA.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index-server.ts","../src/connect/create-node-router.ts","../src/connect/handler.ts","../src/error-handler/jsonapi-error-handler.ts","../src/error-handler/utils.ts","../src/error-handler/problem-error-handler.ts","../src/connect/middleware/http-header-normalizer.ts","../src/connect/middleware/serializers-middleware.ts","../src/serializers/serialize.ts","../src/serializers/has-json-structure.ts","../src/serializers/transformer/xml.ts","../src/connect/middleware/rate-limiter-middleware.ts","../src/connect/middleware/cors-middleware.ts"],"sourcesContent":["export * from \"./index-browser\";\n\nexport {\n default as createHttpError,\n BadRequest,\n Forbidden,\n BadGateway,\n BandwidthLimitExceeded,\n Conflict,\n ExpectationFailed,\n FailedDependency,\n GatewayTimeout,\n Gone,\n HTTPVersionNotSupported,\n ImATeapot,\n InsufficientStorage,\n InternalServerError,\n VariantAlsoNegotiates,\n ProxyAuthenticationRequired,\n NetworkAuthenticationRequire,\n LengthRequired,\n LoopDetected,\n Locked,\n MethodNotAllowed,\n MisdirectedRequest,\n NotAcceptable,\n NotExtended,\n NotFound,\n NotImplemented,\n PayloadTooLarge,\n RequestHeaderFieldsTooLarge,\n PaymentRequired,\n PreconditionFailed,\n PreconditionRequired,\n RangeNotSatisfiable,\n RequestTimeout,\n ServiceUnavailable,\n TooManyRequests,\n Unauthorized,\n UnprocessableEntity,\n UnavailableForLegalReasons,\n UnsupportedMediaType,\n UpgradeRequired,\n URITooLong,\n} from \"http-errors\";\n\nexport { default as createNodeRouter } from \"./connect/create-node-router\";\nexport { onError, onNoMatch } from \"./connect/handler\";\nexport type {\n EdgeRequestHandler,\n ExpressRequestHandler,\n NodeRequestHandler,\n Route,\n HandlerOptions,\n NextHandler,\n FunctionLike,\n Nextable,\n ValueOrPromise,\n FindResult,\n RouteShortcutMethod,\n HttpMethod,\n} from \"@visulima/connect\";\nexport {\n createEdgeRouter, EdgeRouter, expressWrapper, NodeRouter, Router, withZod, sendJson,\n} from \"@visulima/connect\";\n\nexport type { Serializers, Serializer } from \"./serializers\";\nexport { serialize, yamlTransformer, xmlTransformer } from \"./serializers\";\n\nexport { default as rateLimiterMiddleware } from \"./connect/middleware/rate-limiter-middleware\";\nexport { default as corsMiddleware } from \"./connect/middleware/cors-middleware\";\nexport { default as serializersMiddleware } from \"./connect/middleware/serializers-middleware\";\nexport { default as httpHeaderNormalizerMiddleware } from \"./connect/middleware/http-header-normalizer\";\n\nexport { default as swaggerHandler } from \"./swagger/api/swagger-handler\";\n\nexport { dateIn, dateOut } from \"./zod\";\n","import { NodeRouter } from \"@visulima/connect\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { AnyZodObject } from \"zod\";\nimport { ZodObject } from \"zod\";\n\nimport type { ErrorHandlers } from \"../error-handler/types\";\nimport type { Serializers } from \"../serializers\";\nimport { onError, onNoMatch } from \"./handler\";\nimport httpHeaderNormalizerMiddleware from \"./middleware/http-header-normalizer\";\nimport serializersMiddleware from \"./middleware/serializers-middleware\";\n\nconst createNodeRouter = <\n Request extends IncomingMessage,\n Response extends ServerResponse,\n Schema extends AnyZodObject = ZodObject<{ body?: AnyZodObject; headers?: AnyZodObject; query?: AnyZodObject }>,\n>(\n options: {\n middlewares?: {\n \"http-header-normalizer\"?: { canonical?: boolean; normalizeHeaderKey?: (key: string, canonical: boolean) => string };\n serializers?: {\n serializers?: Serializers;\n defaultContentType?: string;\n };\n };\n errorHandlers?: ErrorHandlers;\n showTrace?: boolean;\n } = {},\n ) => {\n const router = new NodeRouter<Request, Response, Schema>({\n onNoMatch,\n onError: onError(options.errorHandlers || [], options.showTrace || false),\n });\n\n return router\n .use(httpHeaderNormalizerMiddleware(options?.middlewares?.[\"http-header-normalizer\"] || {}))\n .use(\n serializersMiddleware(\n options?.middlewares?.serializers?.serializers || [],\n options?.middlewares?.serializers?.defaultContentType || \"application/json; charset=utf-8\",\n ),\n );\n};\n\nexport default createNodeRouter;\n","import type {\n FunctionLike, Nextable, Route, ValueOrPromise,\n} from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport JsonapiErrorHandler from \"../error-handler/jsonapi-error-handler\";\nimport ProblemErrorHandler from \"../error-handler/problem-error-handler\";\nimport type { ErrorHandler, ErrorHandlers } from \"../error-handler/types\";\n\n// eslint-disable-next-line unicorn/consistent-function-scoping,max-len\nexport const onError = <Request extends IncomingMessage, Response extends ServerResponse>(errorHandlers: ErrorHandlers, showTrace: boolean) => async (error: unknown, request: Request, response: Response): Promise<void> => {\n const apiFormat: string = request.headers.accept as string;\n\n let errorHandler: ErrorHandler = ProblemErrorHandler;\n\n if (apiFormat === \"application/vnd.api+json\") {\n errorHandler = JsonapiErrorHandler;\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const { regex, handler } of errorHandlers) {\n if (regex.test(apiFormat)) {\n errorHandler = handler;\n break;\n }\n }\n\n // eslint-disable-next-line no-param-reassign\n (error as { expose: boolean } & Error).expose = showTrace;\n\n errorHandler(error, request, response);\n};\n\nexport const onNoMatch: <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: Response,\n routes: Route<Nextable<FunctionLike>>[],\n) => ValueOrPromise<void> = async (request, response, routes) => {\n const uniqueMethods = [...new Set(routes.map((route) => route.method))].join(\", \");\n\n response.setHeader(\"Allow\", uniqueMethods);\n response.statusCode = 405;\n\n throw createHttpError(405, `No route with [${request.method}] method found.`);\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\nimport tsJapi from \"ts-japi\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultTitle = \"An error occurred\";\n\nconst jsonapiErrorHandler: ErrorHandler = (error: HttpError | tsJapi.JapiError | Error, _request, response) => {\n addStatusCodeToResponse(response, error);\n\n setErrorHeaders(response, error);\n\n if (error instanceof tsJapi.JapiError || tsJapi.JapiError.isLikeJapiError(error)) {\n const serializer = new tsJapi.ErrorSerializer();\n\n sendJson(response, serializer.serialize(error));\n } else if (error instanceof HttpError) {\n const { statusCode, title, message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: statusCode,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n } else {\n const { message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: \"500\",\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n }\n};\n\nexport default jsonapiErrorHandler;\n","import { StatusCodes } from \"http-status-codes\";\nimport type { ServerResponse } from \"node:http\";\n\nexport const setErrorHeaders = (response: ServerResponse, error: any) => {\n const headers: { [key: string]: number | string | ReadonlyArray<string> } = error.headers || {};\n\n Object.keys(headers).forEach((header: string) => {\n response.setHeader(header, headers[header] as number | string | ReadonlyArray<string>);\n });\n};\n\n/**\n * Send `JSON` object\n * @param response response object\n * @param jsonBody of data\n */\nexport const sendJson = (response: ServerResponse, jsonBody: any): void => {\n // Set header to application/json\n response.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n\n response.end(JSON.stringify(jsonBody));\n};\n\nexport const addStatusCodeToResponse = (response: ServerResponse, error: any): void => {\n // respect err.statusCode\n if (error.statusCode !== undefined) {\n response.statusCode = error.statusCode;\n }\n\n // respect err.status\n if (error.status !== undefined) {\n response.statusCode = error.status;\n }\n\n // default status code to 500\n if (response.statusCode < 400) {\n response.statusCode = StatusCodes.INTERNAL_SERVER_ERROR;\n }\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultType = \"https://tools.ietf.org/html/rfc2616#section-10\";\nconst defaultTitle = \"An error occurred\";\n/**\n * Normalizes errors according to the API Problem spec (RFC 7807).\n *\n * @see https://tools.ietf.org/html/rfc7807\n */\nconst problemErrorHandler: ErrorHandler = (error: HttpError | Error, _request, response) => {\n const { stack, message } = error;\n\n if (error instanceof HttpError) {\n const {\n statusCode, expose, title, type,\n } = error;\n\n response.statusCode = statusCode;\n\n setErrorHeaders(response, error);\n\n sendJson(response, {\n type: type || defaultType,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n details: message,\n ...(expose ? { trace: stack } : {}),\n });\n } else {\n addStatusCodeToResponse(response, error);\n\n sendJson(response, {\n type: defaultType,\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n details: message,\n ...((error as { expose: boolean } & Error).expose ? { trace: stack } : {}),\n });\n }\n};\n\nexport default problemErrorHandler;\n","import type { NextHandler } from \"@visulima/connect\";\nimport type { IncomingHttpHeaders, IncomingMessage } from \"node:http\";\n\nconst exceptions = {\n alpn: \"ALPN\",\n \"c-pep\": \"C-PEP\",\n \"c-pep-info\": \"C-PEP-Info\",\n \"caldav-timezones\": \"CalDAV-Timezones\",\n \"content-id\": \"Content-ID\",\n \"content-md5\": \"Content-MD5\",\n dasl: \"DASL\",\n dav: \"DAV\",\n dnt: \"DNT\",\n etag: \"ETag\",\n getprofile: \"GetProfile\",\n \"http2-settings\": \"HTTP2-Settings\",\n \"last-event-id\": \"Last-Event-ID\",\n \"mime-version\": \"MIME-Version\",\n \"optional-www-authenticate\": \"Optional-WWW-Authenticate\",\n \"sec-websocket-accept\": \"Sec-WebSocket-Accept\",\n \"sec-websocket-extensions\": \"Sec-WebSocket-Extensions\",\n \"sec-webSocket-key\": \"Sec-WebSocket-Key\",\n \"sec-webSocket-protocol\": \"Sec-WebSocket-Protocol\",\n \"sec-webSocket-version\": \"Sec-WebSocket-Version\",\n slug: \"SLUG\",\n tcn: \"TCN\",\n te: \"TE\",\n ttl: \"TTL\",\n \"www-authenticate\": \"WWW-Authenticate\",\n \"x-att-deviceid\": \"X-ATT-DeviceId\",\n \"x-dnsprefetch-control\": \"X-DNSPrefetch-Control\",\n \"x-uidh\": \"X-UIDH\",\n};\n\nconst normalizeHeaderKey = (key: string, canonical: boolean) => {\n const lowerCaseKey = key.toLowerCase();\n\n if (!canonical) {\n return lowerCaseKey;\n }\n\n if (exceptions[lowerCaseKey as keyof typeof exceptions]) {\n return exceptions[lowerCaseKey as keyof typeof exceptions];\n }\n\n return (\n lowerCaseKey\n .split(\"-\")\n // eslint-disable-next-line no-unsafe-optional-chaining\n .map((text) => text[0]?.toUpperCase() + text.slice(1))\n .join(\"-\")\n );\n};\n\nconst defaults = {\n canonical: false,\n normalizeHeaderKey,\n};\n\n/**\n * HTTP headers are case-insensitive.\n * That's why NodeJS makes them lower case by default.\n * While sensible, sometimes, for example for compatibility reasons, you might need them in their more common form.\n */\nconst httpHeaderNormalizerMiddleware = (options_?: { canonical?: boolean; normalizeHeaderKey?: (key: string, canonical: boolean) => string }) => {\n const options = { ...defaults, ...options_ };\n\n return async <Request extends IncomingMessage>(request: Request, _: any, next: NextHandler) => {\n if (request.headers) {\n const rawHeaders: IncomingHttpHeaders = {};\n const headers: IncomingHttpHeaders = {};\n\n Object.keys(request.headers).forEach((key) => {\n rawHeaders[key] = request.headers[key];\n\n const normalizedKey = options.normalizeHeaderKey(key, options.canonical);\n\n if (normalizedKey !== undefined) {\n headers[normalizedKey] = request.headers[key];\n }\n });\n\n request.headers = headers;\n // @TODO at type `request.rawHeaders` to global scope\n // @ts-ignore\n request.rawHeaders = rawHeaders;\n }\n\n return next();\n };\n};\n\nexport default httpHeaderNormalizerMiddleware;\n","import type { NextHandler } from \"@visulima/connect\";\nimport debug from \"debug\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { Serializers } from \"../../serializers\";\nimport { serialize } from \"../../serializers\";\n\n// eslint-disable-next-line testing-library/no-debugging-utils\nconst log = debug(\"api-platform:connect:serializers-middleware\");\n\n// eslint-disable-next-line max-len\nconst serializersMiddleware = (serializers: Serializers = [], defaultContentType: string = \"application/json; charset=utf-8\") => async <Request extends IncomingMessage, Response extends ServerResponse>(request: Request, response: Response | NextApiResponse, next: NextHandler) => {\n if (typeof (response as NextApiResponse)?.send === \"function\") {\n const oldSend = (response as NextApiResponse).send;\n\n (response as NextApiResponse).send = (data) => {\n (response as NextApiResponse).send = oldSend;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, Response | NextApiResponse>(serializers, request, response, data, { defaultContentType });\n\n return (response as NextApiResponse).send(data);\n };\n } else if (typeof (response as NextApiResponse)?.json === \"function\") {\n log(\"response.json() is not supported by @visulima/api-platform serializer. Use response.send() or response.end() instead.\");\n } else {\n const oldEnd = response.end;\n\n // @ts-ignore\n response.end = (data, ...arguments_) => {\n response.end = oldEnd;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, Response | NextApiResponse>(serializers, request, response, data, { defaultContentType });\n\n // @ts-ignore\n return response.end(data, ...arguments_);\n };\n }\n\n return next();\n};\n\nexport default serializersMiddleware;\n","import accepts from \"accepts\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { toHeaderCase } from \"../utils\";\nimport hasJsonStructure from \"./has-json-structure\";\nimport xmlTransformer from \"./transformer/xml\";\nimport yamlTransformer from \"./transformer/yaml\";\nimport type { Serializers } from \"./types\";\n\nconst contentTypeKey = \"Content-Type\";\n\n// eslint-disable-next-line max-len\nconst serialize = <Request extends IncomingMessage, Response extends ServerResponse>(\n serializers: Serializers,\n request: Request,\n response: Response,\n data: any,\n options: {\n defaultContentType: string;\n },\n // eslint-disable-next-line radar/cognitive-complexity\n) => {\n const contentType = response.getHeader(contentTypeKey) as string | undefined;\n\n // skip serialization when Content-Type is already set\n if (typeof contentType === \"string\") {\n return data;\n }\n\n const accept = accepts(request);\n const types: string[] = [...(accept.types() as string[]), options.defaultContentType];\n\n let serializedData = data;\n let breakTypes = false;\n\n // eslint-disable-next-line no-restricted-syntax\n types.forEach((type) => {\n serializers.forEach(({ regex, serializer }) => {\n if (regex.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = serializer(serializedData);\n breakTypes = true;\n }\n });\n\n if (!breakTypes) {\n if (/yaml|yml/.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = yamlTransformer(hasJsonStructure(data) ? JSON.parse(data) : data);\n } else if (/xml/.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = xmlTransformer({\n [toHeaderCase(`${request.url?.replace(\"/api/\", \"\")}`.trim())]: hasJsonStructure(data) ? JSON.parse(data) : data,\n });\n }\n }\n });\n\n // eslint-disable-next-line no-param-reassign\n return serializedData;\n};\n\nexport default serialize;\n","const hasJsonStructure = (string_: any): boolean => {\n if (typeof string_ !== \"string\") {\n return false;\n }\n\n try {\n const result = JSON.parse(string_);\n const type = Object.prototype.toString.call(result);\n\n return type === \"[object Object]\" || type === \"[object Array]\";\n } catch {\n return false;\n }\n};\n\nexport default hasJsonStructure;\n","import type { XmlElement } from \"jstoxml\";\nimport xml from \"jstoxml\";\n\nimport type { Serializer } from \"../types\";\n\nconst xmlTransformer: Serializer = (data?: XmlElement | XmlElement[]) => xml.toXML(data, {\n header: true,\n indent: \" \",\n});\n\nexport default xmlTransformer;\n","import type { NextHandler } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { RateLimiterAbstract, RateLimiterRes } from \"rate-limiter-flexible\";\n\n// eslint-disable-next-line max-len\nconst getIP: (request: IncomingMessage & { ip?: string }) => string | undefined = (request) => request?.ip\n || (request.headers[\"x-forwarded-for\"] as string | undefined)\n || (request.headers[\"x-real-ip\"] as string | undefined)\n || request.connection.remoteAddress;\n\ntype HeaderValue = string | number | ReadonlyArray<string>;\n\n// eslint-disable-next-line max-len\nconst rateLimiterMiddleware = (rateLimiter: RateLimiterAbstract, headers?: (limiterResponse: RateLimiterRes) => { [key: string]: HeaderValue }) => async <Request extends IncomingMessage, Response extends ServerResponse>(request: Request, response: Response | NextApiResponse, next: NextHandler) => {\n const ip = getIP(request);\n\n if (ip === undefined) {\n throw createHttpError(400, \"Missing IP\");\n }\n\n try {\n const limiter = await rateLimiter.consume(ip);\n\n const mergedHeaders: { [key: string]: HeaderValue } = {\n \"Retry-After\": Math.round(limiter.msBeforeNext / 1000) || 1,\n \"X-RateLimit-Remaining\": limiter.remainingPoints,\n \"X-RateLimit-Reset\": new Date(Date.now() + limiter.msBeforeNext).toISOString(),\n ...headers,\n };\n\n Object.keys(mergedHeaders).forEach((key) => {\n response.setHeader(key, mergedHeaders[key] as HeaderValue);\n });\n\n await next();\n } catch {\n throw createHttpError(429, \"Too Many Requests\");\n }\n};\n\nexport default rateLimiterMiddleware;\n","import { expressWrapper } from \"@visulima/connect\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { CorsOptions, CorsOptionsDelegate } from \"cors\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport cors from \"cors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n// eslint-disable-next-line max-len\nconst corsMiddleware = <Request extends IncomingMessage, Response extends ServerResponse>(options?: CorsOptions | CorsOptionsDelegate) => expressWrapper<Request, Response>(cors(options));\n\nexport default corsMiddleware;\n"],"mappings":"4IAEA,OACe,WAAXA,GACA,cAAAC,GACA,aAAAC,GACA,cAAAC,GACA,0BAAAC,GACA,YAAAC,GACA,qBAAAC,GACA,oBAAAC,GACA,kBAAAC,GACA,QAAAC,GACA,2BAAAC,GACA,aAAAC,GACA,uBAAAC,GACA,uBAAAC,GACA,yBAAAC,GACA,+BAAAC,GACA,gCAAAC,GACA,kBAAAC,GACA,gBAAAC,GACA,UAAAC,GACA,oBAAAC,GACA,sBAAAC,GACA,iBAAAC,GACA,eAAAC,GACA,YAAAC,GACA,kBAAAC,GACA,mBAAAC,GACA,+BAAAC,GACA,mBAAAC,GACA,sBAAAC,GACA,wBAAAC,GACA,uBAAAC,GACA,kBAAAC,GACA,sBAAAC,GACA,mBAAAC,GACA,gBAAAC,GACA,uBAAAC,GACA,8BAAAC,GACA,wBAAAC,GACA,mBAAAC,GACA,cAAAC,OACG,cC5CP,OAAS,cAAAC,OAAkB,oBCG3B,OAAOC,MAAqB,cCH5B,OAAS,aAAAC,MAAiB,cAC1B,OAAS,mBAAAC,M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AAsB,cAAtB,YAAAC,EAAmC,cAAe,CAAC,IACnDE,GAAAD,EAAAJ,GAAA,YAAAA,EAAS,cAAT,YAAAI,EAAsB,cAAtB,YAAAC,EAAmC,qBAAsB,iCAC7D,CACJ,CACR,EAEOM,GAAQZ,GDmBf,OACI,oBAAAa,GAAkB,cAAAC,GAAY,kBAAAC,GAAgB,cAAAC,GAAY,UAAAC,GAAQ,WAAAC,GAAS,YAAAC,OACxE,oBW/DP,OAAOC,MAAqB,cAM5B,IAAMC,GAA6EC,IAAYA,GAAA,YAAAA,EAAS,KAChGA,EAAQ,QAAQ,oBAChBA,EAAQ,QAAQ,cACjBA,EAAQ,WAAW,cAKpBC,GAAwB,CAACC,EAAkCC,IAAkF,MAAyEH,EAAkBI,EAAsCC,IAAsB,CACtS,IAAMC,EAAKP,GAAMC,CAAO,EAExB,GAAIM,IAAO,OACP,MAAMR,EAAgB,IAAK,YAAY,EAG3C,GAAI,CACA,IAAMS,EAAU,MAAML,EAAY,QAAQI,CAAE,EAEtCE,EAAgD,CAClD,cAAe,KAAK,MAAMD,EAAQ,aAAe,GAAI,GAAK,EAC1D,wBAAyBA,EAAQ,gBACjC,oBAAqB,IAAI,KAAK,KAAK,IAAI,EAAIA,EAAQ,YAAY,EAAE,YAAY,EAC7E,GAAGJ,CACP,EAEA,OAAO,KAAKK,CAAa,EAAE,QAASC,GAAQ,CACxCL,EAAS,UAAUK,EAAKD,EAAcC,EAAmB,CAC7D,CAAC,EAED,MAAMJ,EAAK,CACf,MAAE,CACE,MAAMP,EAAgB,IAAK,mBAAmB,CAClD,CACJ,EAEOY,GAAQT,GC1Cf,OAAS,kBAAAU,OAAsB,oBAI/B,OAAOC,OAAU,OAIjB,IAAMC,GAAoFC,GAAgDH,GAAkCC,GAAKE,CAAO,CAAC,EAElLC,GAAQF","names":["default","BadRequest","Forbidden","BadGateway","BandwidthLimitExceeded","Conflict","ExpectationFailed","FailedDependency","GatewayTimeout","Gone","HTTPVersionNotSupported","ImATeapot","InsufficientStorage","InternalServerError","VariantAlsoNegotiates","ProxyAuthenticationRequired","NetworkAuthenticationRequire","LengthRequired","LoopDetected","Locked","MethodNotAllowed","MisdirectedRequest","NotAcceptable","NotExtended","NotFound","NotImplemented","PayloadTooLarge","RequestHeaderFieldsTooLarge","PaymentRequired","PreconditionFailed","PreconditionRequired","RangeNotSatisfiable","RequestTimeout","ServiceUnavailable","TooManyRequests","Unauthorized","UnprocessableEntity","UnavailableForLegalReasons","UnsupportedMediaType","UpgradeRequired","URITooLong","NodeRouter","createHttpError","HttpError","getReasonPhrase","tsJapi","StatusCodes","setErrorHeaders","response","error","headers","header","sendJson","jsonBody","addStatusCodeToResponse","defaultTitle","jsonapiErrorHandler","error","_request","response","addStatusCodeToResponse","setErrorHeaders","tsJapi","serializer","sendJson","HttpError","statusCode","title","message","getReasonPhrase","jsonapi_error_handler_default","HttpError","getReasonPhrase","defaultType","defaultTitle","problemErrorHandler","error","_request","response","stack","message","HttpError","statusCode","expose","title","type","setErrorHeaders","sendJson","getReasonPhrase","addStatusCodeToResponse","problem_error_handler_default","onError","errorHandlers","showTrace","error","request","response","apiFormat","errorHandler","problem_error_handler_default","jsonapi_error_handler_default","regex","handler","onNoMatch","routes","uniqueMethods","route","createHttpError","exceptions","normalizeHeaderKey","key","canonical","lowerCaseKey","text","_a","defaults","httpHeaderNormalizerMiddleware","options_","options","request","_","next","rawHeaders","headers","normalizedKey","http_header_normalizer_default","debug","accepts","hasJsonStructure","string_","result","type","has_json_structure_default","xml","xmlTransformer","data","xml_default","contentTypeKey","serialize","serializers","request","response","data","options","types","accepts","serializedData","breakTypes","type","_a","regex","serializer","yaml_default","has_json_structure_default","xml_default","toHeaderCase","serialize_default","log","debug","serializersMiddleware","serializers","defaultContentType","request","response","next","oldSend","data","serialize_default","oldEnd","arguments_","serializers_middleware_default","createNodeRouter","options","_a","_b","_c","_d","_e","NodeRouter","onNoMatch","onError","http_header_normalizer_default","serializers_middleware_default","create_node_router_default","createEdgeRouter","EdgeRouter","expressWrapper","NodeRouter","Router","withZod","sendJson","createHttpError","getIP","request","rateLimiterMiddleware","rateLimiter","headers","response","next","ip","limiter","mergedHeaders","key","rate_limiter_middleware_default","expressWrapper","cors","corsMiddleware","options","cors_middleware_default"]}
1
+ {"version":3,"sources":["../src/index-server.ts","../src/connect/create-node-router.ts","../src/connect/handler.ts","../src/error-handler/jsonapi-error-handler.ts","../src/error-handler/utils.ts","../src/error-handler/problem-error-handler.ts","../src/connect/middleware/http-header-normalizer.ts","../src/connect/middleware/serializers-middleware.ts","../src/serializers/serialize.ts","../src/serializers/has-json-structure.ts","../src/serializers/transformer/xml.ts","../src/connect/middleware/rate-limiter-middleware.ts","../src/connect/middleware/cors-middleware.ts"],"names":["default","BadRequest","Forbidden","BadGateway","BandwidthLimitExceeded","Conflict","ExpectationFailed","FailedDependency","GatewayTimeout","Gone","HTTPVersionNotSupported","ImATeapot","InsufficientStorage","InternalServerError","VariantAlsoNegotiates","ProxyAuthenticationRequired","NetworkAuthenticationRequire","LengthRequired","LoopDetected","Locked","MethodNotAllowed","MisdirectedRequest","NotAcceptable","NotExtended","NotFound","NotImplemented","PayloadTooLarge","RequestHeaderFieldsTooLarge","PaymentRequired","PreconditionFailed","PreconditionRequired","RangeNotSatisfiable","RequestTimeout","ServiceUnavailable","TooManyRequests","Unauthorized","UnprocessableEntity","UnavailableForLegalReasons","UnsupportedMediaType","UpgradeRequired","URITooLong","NodeRouter","createHttpError","HttpError","getReasonPhrase","tsJapi","StatusCodes","setErrorHeaders","response","error","headers","header","sendJson","jsonBody","addStatusCodeToResponse","defaultTitle","jsonapiErrorHandler","_request","serializer","statusCode","title","message","jsonapi_error_handler_default","defaultType","problemErrorHandler","stack","expose","type","problem_error_handler_default","onError","errorHandlers","showTrace","request","apiFormat","errorHandler","regex","handler","onNoMatch","routes","uniqueMethods","route","exceptions","normalizeHeaderKey","key","canonical","lowerCaseKey","text","defaults","httpHeaderNormalizerMiddleware","options_","options","_","next","rawHeaders","normalizedKey","http_header_normalizer_default","debug","accepts","hasJsonStructure","data","result","has_json_structure_default","xml","xmlTransformer","xml_default","contentTypeKey","serialize","serializers","types","serializedData","breakTypes","yaml_default","toHeaderCase","serialize_default","log","serializersMiddleware","defaultContentType","oldSend","oldEnd","arguments_","serializers_middleware_default","createNodeRouter","create_node_router_default","createEdgeRouter","EdgeRouter","expressWrapper","Router","withZod","getIP","rateLimiterMiddleware","rateLimiter","ip","limiter","mergedHeaders","rate_limiter_middleware_default","cors","corsMiddleware","cors_middleware_default"],"mappings":"4IAEA,OACe,WAAXA,GACA,cAAAC,GACA,aAAAC,GACA,cAAAC,GACA,0BAAAC,GACA,YAAAC,GACA,qBAAAC,GACA,oBAAAC,GACA,kBAAAC,GACA,QAAAC,GACA,2BAAAC,GACA,aAAAC,GACA,uBAAAC,GACA,uBAAAC,GACA,yBAAAC,GACA,+BAAAC,GACA,gCAAAC,GACA,kBAAAC,GACA,gBAAAC,GACA,UAAAC,GACA,oBAAAC,GACA,sBAAAC,GACA,iBAAAC,GACA,eAAAC,GACA,YAAAC,GACA,kBAAAC,GACA,mBAAAC,GACA,+BAAAC,GACA,mBAAAC,GACA,sBAAAC,GACA,wBAAAC,GACA,uBAAAC,GACA,kBAAAC,GACA,sBAAAC,GACA,mBAAAC,GACA,gBAAAC,GACA,uBAAAC,GACA,8BAAAC,GACA,wBAAAC,GACA,mBAAAC,GACA,cAAAC,OACG,cC5CP,OAAS,cAAAC,OAAkB,oBCG3B,OAAOC,MAAqB,cCH5B,OAAS,aAAAC,MAAiB,cAC1B,OAAS,mBAAAC,MAAuB,oBAChC,OAAOC,MAAY,UCDnB,OAAS,eAAAC,MAAmB,oBAGrB,IAAMC,EAAkB,CAACC,EAA0BC,IAAyB,CAC/E,IAAMC,EAAuED,EAAoB,SAAW,CAAC,EAE7G,OAAO,KAAKC,CAAO,EAAE,QAASC,GAAmB,CAC7CH,EAAS,UAAUG,EAAQD,EAAQC,EAAkD,CACzF,CAAC,CACL,EAOaC,EAA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4C,IAAqC,CACrT,IAAMuC,EAAKH,GAAMxD,CAAO,EAExB,GAAI2D,IAAO,OACP,MAAMzF,EAAgB,IAAK,YAAY,EAG3C,GAAI,CACA,IAAM0F,EAAU,MAAMF,EAAY,QAAQC,CAAE,EAEtCE,EAAgD,CAClD,cAAe,KAAK,MAAMD,EAAQ,aAAe,GAAI,GAAK,EAC1D,wBAAyBA,EAAQ,gBACjC,oBAAqB,IAAI,KAAK,KAAK,IAAI,EAAIA,EAAQ,YAAY,EAAE,YAAY,EAC7E,GAAGlF,CACP,EAEA,OAAO,KAAKmF,CAAa,EAAE,QAASlD,GAAQ,CACxCnC,EAAS,UAAUmC,EAAKkD,EAAclD,EAAmB,CAC7D,CAAC,EAED,MAAMS,EAAK,CACf,MAAE,CACE,MAAMlD,EAAgB,IAAK,mBAAmB,CAClD,CACJ,EAEO4F,GAAQL,GC1Cf,OAAS,kBAAAJ,OAAsB,oBAI/B,OAAOU,OAAU,OAIjB,IAAMC,GAAoF9C,GAAgDmC,GAAkCU,GAAK7C,CAAO,CAAC,EAElL+C,GAAQD","sourcesContent":["export * from \"./index-browser\";\n\nexport {\n default as createHttpError,\n BadRequest,\n Forbidden,\n BadGateway,\n BandwidthLimitExceeded,\n Conflict,\n ExpectationFailed,\n FailedDependency,\n GatewayTimeout,\n Gone,\n HTTPVersionNotSupported,\n ImATeapot,\n InsufficientStorage,\n InternalServerError,\n VariantAlsoNegotiates,\n ProxyAuthenticationRequired,\n NetworkAuthenticationRequire,\n LengthRequired,\n LoopDetected,\n Locked,\n MethodNotAllowed,\n MisdirectedRequest,\n NotAcceptable,\n NotExtended,\n NotFound,\n NotImplemented,\n PayloadTooLarge,\n RequestHeaderFieldsTooLarge,\n PaymentRequired,\n PreconditionFailed,\n PreconditionRequired,\n RangeNotSatisfiable,\n RequestTimeout,\n ServiceUnavailable,\n TooManyRequests,\n Unauthorized,\n UnprocessableEntity,\n UnavailableForLegalReasons,\n UnsupportedMediaType,\n UpgradeRequired,\n URITooLong,\n} from \"http-errors\";\n\nexport { default as createNodeRouter } from \"./connect/create-node-router\";\nexport { onError, onNoMatch } from \"./connect/handler\";\nexport type {\n EdgeRequestHandler,\n ExpressRequestHandler,\n NodeRequestHandler,\n Route,\n HandlerOptions,\n NextHandler,\n FunctionLike,\n Nextable,\n ValueOrPromise,\n FindResult,\n RouteShortcutMethod,\n HttpMethod,\n} from \"@visulima/connect\";\nexport {\n createEdgeRouter, EdgeRouter, expressWrapper, NodeRouter, Router, withZod, sendJson,\n} from \"@visulima/connect\";\n\nexport type { Serializers, Serializer } from \"./serializers\";\nexport { serialize, yamlTransformer, xmlTransformer } from \"./serializers\";\n\nexport { default as rateLimiterMiddleware } from \"./connect/middleware/rate-limiter-middleware\";\nexport { default as corsMiddleware } from \"./connect/middleware/cors-middleware\";\nexport { default as serializersMiddleware } from \"./connect/middleware/serializers-middleware\";\nexport { default as httpHeaderNormalizerMiddleware } from \"./connect/middleware/http-header-normalizer\";\n\nexport { default as swaggerHandler } from \"./swagger/api/swagger-handler\";\n\nexport { dateIn, dateOut } from \"./zod\";\n","import { NodeRouter } from \"@visulima/connect\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { AnyZodObject, ZodObject } from \"zod\";\n\nimport type { ErrorHandlers } from \"../error-handler/types\";\nimport type { Serializers } from \"../serializers\";\nimport { onError, onNoMatch } from \"./handler\";\nimport httpHeaderNormalizerMiddleware from \"./middleware/http-header-normalizer\";\nimport serializersMiddleware from \"./middleware/serializers-middleware\";\n\nconst createNodeRouter = <\n Request extends IncomingMessage,\n Response extends ServerResponse,\n Schema extends AnyZodObject = ZodObject<{ body?: AnyZodObject; headers?: AnyZodObject; query?: AnyZodObject }>,\n>(\n options: {\n middlewares?: {\n \"http-header-normalizer\"?: { canonical?: boolean; normalizeHeaderKey?: (key: string, canonical: boolean) => string };\n serializers?: {\n serializers?: Serializers;\n defaultContentType?: string;\n };\n };\n errorHandlers?: ErrorHandlers;\n showTrace?: boolean;\n } = {},\n ): NodeRouter<Request, Response, Schema> => {\n const router = new NodeRouter<Request, Response, Schema>({\n onNoMatch,\n onError: onError(options.errorHandlers ?? [], options.showTrace ?? false),\n });\n\n return router\n .use(httpHeaderNormalizerMiddleware(options.middlewares?.[\"http-header-normalizer\"] ?? {}))\n .use(\n serializersMiddleware(\n options.middlewares?.serializers?.serializers ?? [],\n options.middlewares?.serializers?.defaultContentType ?? \"application/json; charset=utf-8\",\n ),\n );\n};\n\nexport default createNodeRouter;\n","import type {\n FunctionLike, Nextable, Route, ValueOrPromise,\n} from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport JsonapiErrorHandler from \"../error-handler/jsonapi-error-handler\";\nimport ProblemErrorHandler from \"../error-handler/problem-error-handler\";\nimport type { ErrorHandler, ErrorHandlers } from \"../error-handler/types\";\n\n// eslint-disable-next-line unicorn/consistent-function-scoping,max-len\nexport const onError = <Request extends IncomingMessage, Response extends ServerResponse>(errorHandlers: ErrorHandlers, showTrace: boolean) => async (error: unknown, request: Request, response: Response): Promise<void> => {\n const apiFormat: string = request.headers.accept as string;\n\n let errorHandler: ErrorHandler = ProblemErrorHandler;\n\n if (apiFormat === \"application/vnd.api+json\") {\n errorHandler = JsonapiErrorHandler;\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const { regex, handler } of errorHandlers) {\n if (regex.test(apiFormat)) {\n errorHandler = handler;\n break;\n }\n }\n\n // eslint-disable-next-line no-param-reassign\n (error as Error & { expose: boolean }).expose = showTrace;\n\n errorHandler(error, request, response);\n};\n\nexport const onNoMatch: <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: Response,\n routes: Route<Nextable<FunctionLike>>[],\n) => ValueOrPromise<void> = async (request, response, routes) => {\n const uniqueMethods = [...new Set(routes.map((route) => route.method))].join(\", \");\n\n response.setHeader(\"Allow\", uniqueMethods);\n response.statusCode = 405;\n\n throw createHttpError(405, `No route with [${request.method}] method found.`);\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\nimport tsJapi from \"ts-japi\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultTitle = \"An error occurred\";\n\nconst jsonapiErrorHandler: ErrorHandler = (error: Error | HttpError | tsJapi.JapiError, _request, response) => {\n addStatusCodeToResponse(response, error);\n\n setErrorHeaders(response, error);\n\n if (error instanceof tsJapi.JapiError || tsJapi.JapiError.isLikeJapiError(error)) {\n const serializer = new tsJapi.ErrorSerializer();\n\n sendJson(response, serializer.serialize(error));\n } else if (error instanceof HttpError) {\n const { statusCode, title, message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: statusCode,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n } else {\n const { message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: \"500\",\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n }\n};\n\nexport default jsonapiErrorHandler;\n","import type { HttpError } from \"http-errors\";\nimport { StatusCodes } from \"http-status-codes\";\nimport type { ServerResponse } from \"node:http\";\n\nexport const setErrorHeaders = (response: ServerResponse, error: unknown): void => {\n const headers: { [key: string]: ReadonlyArray<string> | number | string } = (error as HttpError).headers ?? {};\n\n Object.keys(headers).forEach((header: string) => {\n response.setHeader(header, headers[header] as ReadonlyArray<string> | number | string);\n });\n};\n\n/**\n * Send `JSON` object\n * @param response response object\n * @param jsonBody of data\n */\nexport const sendJson = (response: ServerResponse, jsonBody: unknown): void => {\n // Set header to application/json\n response.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n\n response.end(JSON.stringify(jsonBody));\n};\n\nexport const addStatusCodeToResponse = (response: ServerResponse, error: unknown): void => {\n // respect err.statusCode\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ((error as HttpError).statusCode !== undefined) {\n response.statusCode = (error as HttpError).statusCode;\n }\n\n // respect err.status\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ((error as HttpError).status !== undefined) {\n response.statusCode = (error as HttpError).status;\n }\n\n // default status code to 500\n if (response.statusCode < 400) {\n response.statusCode = StatusCodes.INTERNAL_SERVER_ERROR;\n }\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultType = \"https://tools.ietf.org/html/rfc2616#section-10\";\nconst defaultTitle = \"An error occurred\";\n/**\n * Normalizes errors according to the API Problem spec (RFC 7807).\n *\n * @see https://tools.ietf.org/html/rfc7807\n */\nconst problemErrorHandler: ErrorHandler = (error: Error | HttpError, _request, response) => {\n const { stack, message } = error;\n\n if (error instanceof HttpError) {\n const {\n statusCode, expose, title, type,\n } = error;\n\n response.statusCode = statusCode;\n\n setErrorHeaders(response, error);\n\n sendJson(response, {\n type: type || defaultType,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n details: message,\n ...(expose ? { trace: stack } : {}),\n });\n } else {\n addStatusCodeToResponse(response, error);\n\n sendJson(response, {\n type: defaultType,\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n details: message,\n ...((error as Error & { expose: boolean }).expose ? { trace: stack } : {}),\n });\n }\n};\n\nexport default problemErrorHandler;\n","import type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from \"node:http\";\n\nconst exceptions = {\n alpn: \"ALPN\",\n \"c-pep\": \"C-PEP\",\n \"c-pep-info\": \"C-PEP-Info\",\n \"caldav-timezones\": \"CalDAV-Timezones\",\n \"content-id\": \"Content-ID\",\n \"content-md5\": \"Content-MD5\",\n dasl: \"DASL\",\n dav: \"DAV\",\n dnt: \"DNT\",\n etag: \"ETag\",\n getprofile: \"GetProfile\",\n \"http2-settings\": \"HTTP2-Settings\",\n \"last-event-id\": \"Last-Event-ID\",\n \"mime-version\": \"MIME-Version\",\n \"optional-www-authenticate\": \"Optional-WWW-Authenticate\",\n \"sec-websocket-accept\": \"Sec-WebSocket-Accept\",\n \"sec-websocket-extensions\": \"Sec-WebSocket-Extensions\",\n \"sec-webSocket-key\": \"Sec-WebSocket-Key\",\n \"sec-webSocket-protocol\": \"Sec-WebSocket-Protocol\",\n \"sec-webSocket-version\": \"Sec-WebSocket-Version\",\n slug: \"SLUG\",\n tcn: \"TCN\",\n te: \"TE\",\n ttl: \"TTL\",\n \"www-authenticate\": \"WWW-Authenticate\",\n \"x-att-deviceid\": \"X-ATT-DeviceId\",\n \"x-dnsprefetch-control\": \"X-DNSPrefetch-Control\",\n \"x-uidh\": \"X-UIDH\",\n};\n\nconst normalizeHeaderKey = (key: string, canonical: boolean) => {\n const lowerCaseKey = key.toLowerCase();\n\n if (!canonical) {\n return lowerCaseKey;\n }\n\n if (exceptions[lowerCaseKey as keyof typeof exceptions]) {\n return exceptions[lowerCaseKey as keyof typeof exceptions];\n }\n\n return (\n lowerCaseKey\n .split(\"-\")\n // eslint-disable-next-line no-unsafe-optional-chaining\n .map((text) => text[0]?.toUpperCase() + text.slice(1))\n .join(\"-\")\n );\n};\n\nconst defaults = {\n canonical: false,\n normalizeHeaderKey,\n};\n\n/**\n * HTTP headers are case-insensitive.\n * That's why NodeJS makes them lower case by default.\n * While sensible, sometimes, for example for compatibility reasons, you might need them in their more common form.\n */\nconst httpHeaderNormalizerMiddleware = (options_?: {\n canonical?: boolean;\n normalizeHeaderKey?: (key: string, canonical: boolean) => string;\n}): ((request: IncomingMessage, response: ServerResponse, next: NextHandler) => ValueOrPromise<void>) => {\n const options = { ...defaults, ...options_ };\n\n return async <Request extends IncomingMessage>(request: Request, _: any, next: NextHandler) => {\n const rawHeaders: IncomingHttpHeaders = {};\n const headers: IncomingHttpHeaders = {};\n\n Object.keys(request.headers).forEach((key) => {\n rawHeaders[key] = request.headers[key];\n\n const normalizedKey = options.normalizeHeaderKey(key, options.canonical);\n\n if (normalizedKey) {\n headers[normalizedKey] = request.headers[key];\n }\n });\n\n request.headers = headers;\n // @TODO at type `request.rawHeaders` to global scope\n // @ts-expect-error\n request.rawHeaders = rawHeaders;\n\n return next();\n };\n};\n\nexport default httpHeaderNormalizerMiddleware;\n","import type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport debug from \"debug\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { Serializers } from \"../../serializers\";\nimport { serialize } from \"../../serializers\";\n\n// eslint-disable-next-line testing-library/no-debugging-utils\nconst log = debug(\"api-platform:connect:serializers-middleware\");\n\n// eslint-disable-next-line max-len\nconst serializersMiddleware = (serializers: Serializers = [], defaultContentType: string = \"application/json; charset=utf-8\") => async <Request extends IncomingMessage, Response extends ServerResponse>(request: Request, response: NextApiResponse | Response, next: NextHandler): Promise<ValueOrPromise<void>> => {\n if (typeof (response as NextApiResponse).send === \"function\") {\n const oldSend = (response as NextApiResponse).send;\n\n (response as NextApiResponse).send = (data) => {\n (response as NextApiResponse).send = oldSend;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, NextApiResponse | Response>(serializers, request, response, data, { defaultContentType });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (response as NextApiResponse).send(data);\n };\n } else if (typeof (response as NextApiResponse).json === \"function\") {\n log(\"response.json() is not supported by @visulima/api-platform serializer. Use response.send() or response.end() instead.\");\n } else {\n const oldEnd = response.end;\n\n // @ts-expect-error\n response.end = (data, ...arguments_) => {\n response.end = oldEnd;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, NextApiResponse | Response>(serializers, request, response, data, { defaultContentType });\n\n // @ts-expect-error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'BufferEncoding'.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return response.end(data, ...arguments_);\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return next();\n};\n\nexport default serializersMiddleware;\n","import accepts from \"accepts\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { toHeaderCase } from \"../utils\";\nimport hasJsonStructure from \"./has-json-structure\";\nimport xmlTransformer from \"./transformer/xml\";\nimport yamlTransformer from \"./transformer/yaml\";\nimport type { Serializers } from \"./types\";\n\nconst contentTypeKey = \"Content-Type\";\n\n// eslint-disable-next-line max-len\nconst serialize = <Request extends IncomingMessage, Response extends ServerResponse>(\n serializers: Serializers,\n request: Request,\n response: Response,\n data: unknown,\n options: {\n defaultContentType: string;\n },\n // eslint-disable-next-line radar/cognitive-complexity\n): Buffer | Uint8Array | string => {\n const contentType = response.getHeader(contentTypeKey) as string | undefined;\n\n // skip serialization when Content-Type is already set\n if (typeof contentType === \"string\") {\n return data as string;\n }\n\n const accept = accepts(request);\n const types: string[] = [...(accept.types() as string[]), options.defaultContentType];\n\n let serializedData = data;\n let breakTypes = false;\n\n // eslint-disable-next-line no-restricted-syntax\n types.forEach((type) => {\n serializers.forEach(({ regex, serializer }) => {\n if (regex.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = serializer(serializedData);\n breakTypes = true;\n }\n });\n\n if (!breakTypes) {\n if (/yaml|yml/.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = yamlTransformer(hasJsonStructure(data) ? JSON.parse(data as string) : data);\n } else if (type.includes(\"xml\")) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = xmlTransformer({\n [toHeaderCase(`${request.url?.replace(\"/api/\", \"\")}`.trim())]: hasJsonStructure(data) ? JSON.parse(data as string) : data,\n });\n }\n }\n });\n\n return serializedData as Buffer | Uint8Array | string;\n};\n\nexport default serialize;\n","const hasJsonStructure = (data: unknown): boolean => {\n if (typeof data !== \"string\") {\n return false;\n }\n\n try {\n const result = JSON.parse(data);\n const type = Object.prototype.toString.call(result);\n\n return type === \"[object Object]\" || type === \"[object Array]\";\n } catch {\n return false;\n }\n};\n\nexport default hasJsonStructure;\n","import type { XmlElement } from \"jstoxml\";\nimport xml from \"jstoxml\";\n\nimport type { Serializer } from \"../types\";\n\nconst xmlTransformer: Serializer = (data?: XmlElement | XmlElement[]) => xml.toXML(data, {\n header: true,\n indent: \" \",\n});\n\nexport default xmlTransformer;\n","import type { NextHandler } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { RateLimiterAbstract, RateLimiterRes } from \"rate-limiter-flexible\";\n\n// eslint-disable-next-line max-len\nconst getIP: (request: IncomingMessage & { ip?: string }) => string | undefined = (request) => request.ip\n ?? (request.headers[\"x-forwarded-for\"] as string | undefined)\n ?? (request.headers[\"x-real-ip\"] as string | undefined)\n ?? request.connection.remoteAddress;\n\ntype HeaderValue = ReadonlyArray<string> | number | string;\n\n// eslint-disable-next-line max-len\nconst rateLimiterMiddleware = (rateLimiter: RateLimiterAbstract, headers?: (limiterResponse: RateLimiterRes) => { [key: string]: HeaderValue }) => async <Request extends IncomingMessage, Response extends ServerResponse>(request: Request, response: NextApiResponse | Response, next: NextHandler): Promise<void> => {\n const ip = getIP(request);\n\n if (ip === undefined) {\n throw createHttpError(400, \"Missing IP\");\n }\n\n try {\n const limiter = await rateLimiter.consume(ip);\n\n const mergedHeaders: { [key: string]: HeaderValue } = {\n \"Retry-After\": Math.round(limiter.msBeforeNext / 1000) || 1,\n \"X-RateLimit-Remaining\": limiter.remainingPoints,\n \"X-RateLimit-Reset\": new Date(Date.now() + limiter.msBeforeNext).toISOString(),\n ...headers,\n };\n\n Object.keys(mergedHeaders).forEach((key) => {\n response.setHeader(key, mergedHeaders[key] as HeaderValue);\n });\n\n await next();\n } catch {\n throw createHttpError(429, \"Too Many Requests\");\n }\n};\n\nexport default rateLimiterMiddleware;\n","import { expressWrapper } from \"@visulima/connect\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { CorsOptions, CorsOptionsDelegate } from \"cors\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport cors from \"cors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n// eslint-disable-next-line max-len,@typescript-eslint/explicit-module-boundary-types\nconst corsMiddleware = <Request extends IncomingMessage, Response extends ServerResponse>(options?: CorsOptions | CorsOptionsDelegate) => expressWrapper<Request, Response>(cors(options));\n\nexport default corsMiddleware;\n"]}
@@ -2,15 +2,15 @@ import { ModelsToOpenApiParameters, SwaggerModelsConfig } from '@visulima/crud';
2
2
  import { IncomingMessage, ServerResponse } from 'node:http';
3
3
  import { OpenAPIV3 } from 'openapi-types';
4
4
 
5
- declare const swaggerHandler: (options?: Partial<SwaggerHandlerOptions>) => <Request_1 extends IncomingMessage, Response_1 extends ServerResponse<IncomingMessage>>(request: Request_1, response: Response_1) => Promise<void>;
6
- declare type SwaggerHandlerOptions = {
5
+ declare const swaggerHandler: <M extends string, PrismaClient>(options?: Partial<SwaggerHandlerOptions<M, PrismaClient>>) => (request: IncomingMessage, response: ServerResponse) => Promise<void>;
6
+ type SwaggerHandlerOptions<M extends string, PrismaClient> = {
7
7
  allowedMediaTypes: {
8
8
  [key: string]: boolean;
9
9
  };
10
10
  swaggerFilePath: string;
11
- crud: Exclude<ModelsToOpenApiParameters, "swagger"> & {
11
+ crud: Exclude<ModelsToOpenApiParameters<M, PrismaClient>, "swagger"> & {
12
12
  swagger?: {
13
- models?: SwaggerModelsConfig<string>;
13
+ models?: SwaggerModelsConfig<M>;
14
14
  };
15
15
  };
16
16
  specs?: Partial<OpenAPIV3.Document>[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/api-platform",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "description": "Visulima API platform is a set of tools to build and consume web APIs",
5
5
  "keywords": [
6
6
  "anolilab",
@@ -91,106 +91,107 @@
91
91
  "scripts": {
92
92
  "build": "rimraf dist && cross-env NODE_ENV=development tsup",
93
93
  "build:prod": "rimraf dist && cross-env NODE_ENV=production tsup",
94
- "clean": "rimraf node_modules dist",
94
+ "clean": "rimraf node_modules dist .eslintcache",
95
95
  "coverage": "vitest run --coverage",
96
96
  "dev": "pnpm predev && pnpm run build --watch",
97
97
  "lint:eslint": "cross-env NO_LOGS=true eslint . --ext js,jsx,ts,tsx --max-warnings=0 --config .eslintrc.cjs --cache --cache-strategy content .",
98
98
  "lint:eslint:fix": "pnpm run lint:eslint --fix",
99
- "test": "vitest"
99
+ "test": "vitest run",
100
+ "test:watch": "vitest"
100
101
  },
101
102
  "dependencies": {
102
- "@visulima/connect": "1.3.1",
103
- "@visulima/jsdoc-open-api": "1.3.0",
103
+ "@visulima/connect": "1.3.3",
104
+ "@visulima/jsdoc-open-api": "1.3.2",
104
105
  "accepts": "^1.3.8",
105
106
  "debug": "^4.3.4",
106
107
  "http-errors": "^2.0.0",
107
108
  "http-status-codes": "^2.2.0",
108
- "jstoxml": "^3.2.5",
109
+ "jstoxml": "^3.2.6",
109
110
  "lodash.merge": "^4.6.2",
110
111
  "schema-dts": "^1.1.0",
111
112
  "ts-japi": "^1.8.0",
112
- "yaml": "^2.1.3",
113
- "zod-to-ts": "^1.1.1"
113
+ "yaml": "^2.2.1",
114
+ "zod-to-ts": "^1.1.2"
114
115
  },
115
116
  "devDependencies": {
116
- "@anolilab/eslint-config": "^4.0.9",
117
- "@anolilab/semantic-release-preset": "^2.0.7",
118
- "@hapi/hapi": "^21.1.0",
117
+ "@anolilab/eslint-config": "^5.0.2",
118
+ "@anolilab/semantic-release-preset": "^2.2.0",
119
+ "@hapi/hapi": "^21.2.0",
119
120
  "@koa/router": "^12.0.0",
120
121
  "@rushstack/eslint-plugin-security": "^0.5.0",
121
122
  "@testing-library/react": "^13.4.0",
122
123
  "@testing-library/react-hooks": "^8.0.1",
123
124
  "@types/accepts": "^1.3.5",
124
- "@types/cors": "^2.8.12",
125
+ "@types/cors": "^2.8.13",
125
126
  "@types/debug": "^4.1.7",
126
- "@types/express": "^4.17.15",
127
- "@types/express-serve-static-core": "^4.17.31",
128
- "@types/http-errors": "^2.0.0",
127
+ "@types/express": "^4.17.16",
128
+ "@types/express-serve-static-core": "^4.17.33",
129
+ "@types/http-errors": "^2.0.1",
129
130
  "@types/jstoxml": "^2.0.2",
130
131
  "@types/koa": "^2.13.5",
131
132
  "@types/koa__router": "^12.0.0",
132
133
  "@types/lodash.merge": "^4.6.7",
133
134
  "@types/lodash.set": "^4.3.7",
134
- "@types/node": "^18.8.4",
135
+ "@types/node": "^18.11.18",
135
136
  "@types/qs": "^6.9.7",
136
- "@types/react": "^18.0.21",
137
- "@types/react-dom": "^18.0.6",
137
+ "@types/react": "^18.0.27",
138
+ "@types/react-dom": "^18.0.10",
138
139
  "@types/swagger-ui-react": "^4.11.0",
139
140
  "@types/webpack": "^5.28.0",
140
- "@typescript-eslint/eslint-plugin": "^5.40.0",
141
- "@typescript-eslint/parser": "^5.40.0",
142
- "@visulima/crud": "1.0.8",
143
- "@visulima/readdir": "1.3.2",
141
+ "@typescript-eslint/eslint-plugin": "^5.49.0",
142
+ "@typescript-eslint/parser": "^5.49.0",
143
+ "@visulima/crud": "1.0.10",
144
+ "@visulima/readdir": "1.3.4",
144
145
  "chalk": "4.1.2",
145
- "commander": "^9.4.1",
146
- "core-js": "^3.25.5",
146
+ "commander": "^10.0.0",
147
+ "core-js": "^3.27.2",
147
148
  "cors": "^2.8.5",
148
149
  "cross-env": "^7.0.3",
149
- "eslint": "^8.25.0",
150
+ "eslint": "^8.32.0",
150
151
  "eslint-plugin-compat": "^4.0.2",
151
152
  "eslint-plugin-eslint-comments": "^3.2.0",
152
- "eslint-plugin-import": "^2.26.0",
153
+ "eslint-plugin-import": "^2.27.5",
153
154
  "eslint-plugin-json": "^3.1.0",
154
- "eslint-plugin-jsx-a11y": "^6.6.1",
155
+ "eslint-plugin-jsx-a11y": "^6.7.1",
155
156
  "eslint-plugin-markdown": "^3.0.0",
156
157
  "eslint-plugin-no-loops": "^0.3.0",
157
158
  "eslint-plugin-no-secrets": "^0.8.9",
158
159
  "eslint-plugin-node": "^11.1.0",
159
160
  "eslint-plugin-optimize-regex": "^1.2.1",
160
- "eslint-plugin-promise": "^6.0.1",
161
+ "eslint-plugin-promise": "^6.1.1",
161
162
  "eslint-plugin-radar": "^0.2.1",
162
- "eslint-plugin-react": "7.31.11",
163
+ "eslint-plugin-react": "7.32.1",
163
164
  "eslint-plugin-react-hooks": "4.6.0",
164
- "eslint-plugin-simple-import-sort": "^8.0.0",
165
+ "eslint-plugin-simple-import-sort": "^9.0.0",
165
166
  "eslint-plugin-sort-keys-fix": "^1.1.2",
166
- "eslint-plugin-testing-library": "^5.7.2",
167
- "eslint-plugin-unicorn": "^45.0.0",
167
+ "eslint-plugin-testing-library": "^5.10.0",
168
+ "eslint-plugin-unicorn": "^45.0.2",
168
169
  "eslint-plugin-you-dont-need-lodash-underscore": "^6.12.0",
169
170
  "eslint-plugin-you-dont-need-momentjs": "^1.6.0",
170
171
  "express": "^4.18.2",
171
- "fastify": "^4.10.2",
172
+ "fastify": "^4.12.0",
172
173
  "koa": "^2.14.1",
173
- "mobx": "^6.6.2",
174
- "next": "^12.0.0 || ^13.0.0",
174
+ "mobx": "^6.7.0",
175
+ "next": "^13.1.4",
175
176
  "next-test-api-route-handler": "^4.0.0-canary.1",
176
- "node-mocks-http": "^1.11.0",
177
- "openapi-types": "^12.0.2",
178
- "prettier": "^2.7.1",
179
- "rate-limiter-flexible": "^2.3.11",
177
+ "node-mocks-http": "^1.12.1",
178
+ "openapi-types": "^12.1.0",
179
+ "prettier": "^2.8.3",
180
+ "rate-limiter-flexible": "^2.4.1",
180
181
  "react": "^18.2.0",
181
182
  "react-dom": "^18.2.0",
182
183
  "read-pkg": "^7.1.0",
183
184
  "redoc": "^2.0.0",
184
- "rimraf": "^3.0.2",
185
- "semantic-release": "^20.0.0",
185
+ "rimraf": "^4.1.2",
186
+ "semantic-release": "^20.1.0",
186
187
  "styled-components": "^5.3.6",
187
188
  "swagger-ui-dist": "^4.15.5",
188
- "swagger-ui-react": "^4.14.3",
189
- "tsup": "^6.2.3",
190
- "typescript": "^4.8.4",
191
- "vitest": "^0.26.1",
192
- "webpack": "^5.74.0",
193
- "zod": "^3.19.1"
189
+ "swagger-ui-react": "^4.15.5",
190
+ "tsup": "^6.5.0",
191
+ "typescript": "^4.9.4",
192
+ "vitest": "^0.28.2",
193
+ "webpack": "^5.75.0",
194
+ "zod": "^3.20.2"
194
195
  },
195
196
  "peerDependencies": {
196
197
  "react": "^18.2.0",
@@ -198,25 +199,25 @@
198
199
  "zod": "^3.19.1"
199
200
  },
200
201
  "optionalDependencies": {
201
- "@hapi/hapi": "^21.1.0",
202
+ "@hapi/hapi": "^21.2.0",
202
203
  "@koa/router": "^12.0.0",
203
- "@visulima/crud": "1.0.8",
204
- "@visulima/readdir": "1.3.2",
205
- "chalk": "4.1.2",
206
- "commander": "^9.4.1",
204
+ "@visulima/crud": "1.0.10",
205
+ "@visulima/readdir": "1.3.4",
206
+ "chalk": "5.2.0",
207
+ "commander": "^10.0.0",
207
208
  "cors": "^2.8.5",
208
209
  "express": "^4.18.2",
209
- "fastify": "^4.10.2",
210
+ "fastify": "^4.12.0",
210
211
  "koa": "^2.14.1",
211
- "next": "^12.0.0 || ^13.0.0",
212
- "rate-limiter-flexible": "^2.3.11",
212
+ "next": "^13.1.5",
213
+ "rate-limiter-flexible": "^2.4.1",
213
214
  "redoc": "^2.0.0",
214
215
  "swagger-ui-dist": "^4.15.5",
215
- "swagger-ui-react": "^4.14.3",
216
- "webpack": "^5.74.0"
216
+ "swagger-ui-react": "^4.15.5",
217
+ "webpack": "^5.75.0"
217
218
  },
218
219
  "engines": {
219
- "node": ">=16"
220
+ "node": ">=16.18.0 <=19.*"
220
221
  },
221
222
  "publishConfig": {
222
223
  "access": "public"
@@ -1,6 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);var _child_process = require('child_process');var _fs = require('fs');var _path = require('path');var _process = require('process'); var _process2 = _interopRequireDefault(_process);var Y=(t,o)=>{if(!o||o.length===0)throw new Error("must include atleast one key to map");let e=t.toString();return o.forEach(r=>{e=r.optional?e.replace("(?:\\/([^\\/]+?))?\\",`/:${r.name}?`):e.replace("(?:([^\\/]+?))",`:${r.name}`)}),e.replace("/?(?=\\/|$)/i","").replace("/^","").replace(/\\/gi,"").replace(/\/{2,}/gi,"/")},T=Y;var z=(t,o)=>{if(typeof t=="string")return t;if(t.fast_slash)return"";if(t.fast_star)return"*";let e="";o&&o.length>0&&(e=T(t,o));let r=t.toString().replace("\\/?","").replace("(?=\\/|$)","$").match(/^\/\^((?:\\[$()*+./?[\\\]^{|}]|[^$()*+./?[\\\]^{|}])*)\$\//);return r?r[1].replace(/\\(.)/g,"$1").slice(1):e?e.slice(1):t.toString()},A=z;var Q=(t,o,e)=>{let r=t.route.stack[t.route.stack.length-1],i=o.map(a=>({name:a.name,in:"path",required:!a.optional})),s=t.route.stack.filter(a=>{var p;return(p=a==null?void 0:a.handle)==null?void 0:p.metadata});if(s.length>1)throw new Error("Only one metadata middleware is allowed per route");let n=(e+t.route.path).replace(/\/{2,}/gi,"/");return s.length===0?{path:n,pathParams:i,method:r.method}:{path:n,pathParams:i,method:r.method,metadata:s[0].handle.metadata}},D=(t,o,e,r)=>{r=[...r,...e.keys],e.name==="router"&&e.handle&&e.handle.stack.forEach(i=>{o=o||"",D(t,`${o}/${A(e.regexp,e.keys)}`,i,r)}),!(!e.route||e.route.stack.length===0)&&t.push(Q(e,r,o))},V=t=>{let o=t._router||t.router,e=[];return o&&o.stack.forEach(r=>{D(e,"",r,[])}),e},k=V;var Z=t=>{let o=[];return k(t).forEach(e=>{o.push({path:e.path,method:e.method.toUpperCase(),tags:[],file:"unknown"})}),o},$=Z;var j=t=>t.replace(/ \(.*\)/g,"").trim(),O=t=>t.trim().split(" ")[1].slice(1,-1),tt=t=>{let e=t.printRoutes().replace(/[─│└├]/g," ").trimEnd().split(`
2
- `),r=e.reduce((s,n,a)=>{let p=j(n);if(j(e[a-1]||"")===p){let w=s.filter(S=>S.index<a&&S.segment===p),{methods:P}=w[w.length-1];return P!==null&&P.push(O(n)),s}let u=n.replace(/ \(.*\)/g,"").match(/ /g);if(u===null)throw new Error("Invalid spaces");let m=u.length/4,f=n.includes("("),g=f?[O(n)]:null;return s.push({segment:p,index:a,depth:m,isRoute:f,methods:g}),s},[]),i=[];return r.filter(s=>s.isRoute).forEach(s=>{let a=[...r.filter(p=>p.index<s.index&&p.depth<s.depth).filter((p,c,u)=>!u.find(m=>m.depth===p.depth&&m.index>p.index)).map(p=>p.segment),s.segment].join("");if(s.methods===null)throw new Error("Invalid methods");s.methods.forEach(p=>{i.push({path:a,method:p.toUpperCase(),tags:[],file:"unknown"})})}),i},v=tt;var et=t=>{let e=t._core.router.routes,r=[];return[...e.keys()].forEach(i=>{e.get(i).routes.forEach(s=>{r.push({path:s.path,method:s.route.method.toUpperCase(),tags:[],file:"unknown"})})}),r},b=et;var rt=t=>{let o=[];return t.middleware.filter(e=>e.router).flatMap(e=>e.router.stack).forEach(e=>{o.push({path:e.path,method:e.methods.join("|").toUpperCase(),tags:[],file:"unknown"})}),o},F=rt;var _jsdocopenapi = require('@visulima/jsdoc-open-api');var N=/\.(js|ts|mjs|cjs)$/,at=(t,o,e=!1)=>{let r=[],i=_jsdocopenapi.parseFile.call(void 0, t,_jsdocopenapi.jsDocumentCommentsToOpenApi,e);r=[...r,...i.map(a=>a.spec)];let s=_jsdocopenapi.parseFile.call(void 0, t,_jsdocopenapi.swaggerJsDocumentCommentsToOpenApi,e);r=[...r,...s.map(a=>a.spec)];let n=[];return r.length===0?(_fs.readFileSync.call(void 0, t,"utf8").split(/\r?\n/).forEach(p=>{let c=p.match(/[=aces|]+\s["'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)["'|]/);if(c){let[,u]=c;u==="GET"&&(u="GET|HEAD"),n.push({method:u,path:t.replace(o,"").replace(N,""),tags:[],file:t.replace(`${_process2.default.cwd()}/`,"")})}}),n.length===0&&n.push({method:"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS",path:t.replace(o,"").replace(N,""),tags:[],file:t.replace(`${_process2.default.cwd()}/`,"")}),n):(r.forEach(a=>{Object.entries(a.paths).forEach(([c,u])=>{Object.entries(u).forEach(([f,g])=>{n.push({path:c,method:f.toUpperCase(),tags:g.tags,file:t.replace(`${_process2.default.cwd()}/`,"")})})})}),n)},L=at;var _readdir = require('@visulima/readdir');var h=[".js",".ts",".mjs",".cjs"],M=t=>{let o=_path.parse.call(void 0, t);for(;o.base&&o.root!==o.dir;){if(_fs.readdirSync.call(void 0, o.dir).find(i=>i==="package.json"))return o.dir;o=_path.parse.call(void 0, o.dir)}return null},H=t=>{let o=`${t}/package.json`,e=JSON.parse(_fs.readFileSync.call(void 0, o).toString()),{dependencies:r}=e;return r.express?"express":r.koa&&(r["@koa/router"]||r["koa-router"])?"koa":r.next?"next":r["@hapi/hapi"]?"hapi":r.fastify?"fastify":null},K=(t,o)=>{var r;return Object.keys(t).length===0?null:o==="hapi"?(r=t.app)!=null&&r.app?t.app:t:t.app||t};var _=t=>{try{return _fs.statSync.call(void 0, t).isDirectory()}catch (e2){return!1}},lt=async(t="",o=!1)=>{let e=_path.join.call(void 0, t,"pages/api");return!_(e)&&(e=_path.join.call(void 0, t,"src/pages/api"),!_(e))?[]:_readdir.collect.call(void 0, e,{extensions:h,includeDirs:!1,minimatchOptions:{match:{debug:o,matchBase:!0},skip:{debug:o,matchBase:!0}}})},B=lt;async function E(t,o,e){if(o==="express")return $(t);if(o==="koa")return F(t);if(o==="hapi")return b(t);if(o==="fastify")return v(t);if(o==="next"){let r=await B(t,e);if(r.length===0)throw new Error(`No API routes found, in "${t}".`);return r.flatMap(i=>L(i,t,e))}return null}var mt=(t,o)=>{let e=new Map;return t.forEach(r=>{let i=o(r),s=e.get(i);s?s.push(r):e.set(i,[r])}),e},J=mt;var ft=(t,o)=>{let e={GET:_chalk2.default.blue,POST:_chalk2.default.yellow,PATCH:_chalk2.default.yellow,PUT:_chalk2.default.yellow,DELETE:_chalk2.default.redBright,OPTIONS:_chalk2.default.hex("#6C7280"),ANY:_chalk2.default.redBright,HEAD:_chalk2.default.hex("#6C7280")},r;if(t==="GET|HEAD")r=`${_chalk2.default.blue("GET")}${_chalk2.default.grey("|HEAD")}`;else{let c=e[t](t);r=t==="GET"?`${c}${_chalk2.default.grey("|HEAD")}`:c}let i=t==="GET"?6:14-t.length,s=Array.from({length:i}).fill(" ").join(""),n=process.stdout.columns-16-o.length-4,a=n>0?Array.from({length:n}).fill(".").join(""):"",p=o.split("/").map(c=>["[",":"].includes(c[0]||"")?_chalk2.default.yellowBright(c):c).join("/");return` ${r}${s}${p}${_chalk2.default.grey(a)}`},dt=(t,o={})=>t.map(e=>{if(!(Array.isArray(o.methods)&&o.methods.includes(e.method)))return e.method==="GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS"&&(e.method="ANY"),ft(e.method,e.path.replace("/pages",""))}).filter(Boolean),x=dt;var yt=async(t,o,e={})=>{let r=_path.join.call(void 0, _process2.default.cwd(),o);if(!_fs.existsSync.call(void 0, r))throw new Error("No such file, invalid path provided.");let i=M(r);if(!i)throw new Error("Please initialize local package.json.");if(t===void 0){let n=H(i);if(!n)throw new Error("Couldn't detect supported back-end framework.");t=n}let s=null;if(t==="next")s=await E(r,"next",e.verbose||!1);else{if(!_fs.statSync.call(void 0, r).isFile())throw new Error(`${r} is directory, but file expected.`);if(!h.includes(_path.extname.call(void 0, r)))throw new Error("Please specify application .ts/.js/.mjs/.cjs file.");let n=`${i}/.env`;_fs.existsSync.call(void 0, n)&&(await Promise.resolve().then(() => require(`${i}/node_modules/dotenv/lib/main.js`))).config({path:n});let a=_path.extname.call(void 0, r)===".ts",p=_path.join.call(void 0, i,"node_modules/.bin/tsc");if(a&&!_fs.existsSync.call(void 0, p))throw new Error(`Please install typescript in ${i}`);try{if(a)try{_child_process.execSync.call(void 0, `${p} --outDir framework-list >&2`,{cwd:i})}catch(m){console.log(`TSC compilation failed. Please resolve issues in your project.
3
- `),console.log(m),_fs.rmSync.call(void 0, _path.join.call(void 0, i,"framework-list"),{recursive:!0})}let c=a?_path.join.call(void 0, i,"framework-list",r.replace(i,"").replace(".ts",".js")):r,{default:u}=await Promise.resolve().then(() => require(c));s=await E(["AsyncFunction","Function"].includes(u.constructor.name)?await u():K(u,t),t,e.verbose||!1)}finally{a&&_fs.rmSync.call(void 0, _path.join.call(void 0, i,"framework-list"),{recursive:!0})}}if(s===null)throw new Error(`Framework "${t}" is not supported.`);if(Array.isArray(e.includePaths)&&e.includePaths.length>0&&(s=e.includePaths.flatMap(n=>s.filter(a=>a.path.startsWith(n)))),Array.isArray(e.excludePaths)&&e.excludePaths.length>0&&(s=e.excludePaths.flatMap(n=>s.filter(a=>!a.path.startsWith(n)))),typeof e.group=="string"&&e.group!==""){console.log();let n=J(s,p=>e.group==="path"?p.path.replace("/pages","").split("/")[1]:p.tags[0]||"unsorted"),a=0;n.forEach((p,c)=>{a>0&&console.log();let u=(_process2.default.stdout.columns-16-c.length)/2,m=u>0?Array.from({length:u}).fill(" ").join(""):"";console.log(m+_chalk2.default.bold.underline(c)),x(p,e).forEach(f=>{console.log(f)}),a+=1})}else console.log(),x(s,e).forEach(n=>{console.log(n)});console.log(`
4
- Listed ${_chalk2.default.greenBright(String(s.length))} HTTP ${s.length===1?"route":"routes"}.
5
- `)},ne= exports.a =yt;exports.a = ne;
6
- //# sourceMappingURL=chunk-5P4SXSAZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/framework/cli/command/list/list-command.ts","../src/framework/cli/command/list/routes/express/map-keys-to-path.ts","../src/framework/cli/command/list/routes/express/path-regex-parser.ts","../src/framework/cli/command/list/routes/express/express-path-parser.ts","../src/framework/cli/command/list/routes/express-routes.ts","../src/framework/cli/command/list/routes/fastify-routes.ts","../src/framework/cli/command/list/routes/hapi-routes.ts","../src/framework/cli/command/list/routes/koa-routes.ts","../src/framework/cli/command/list/routes/next/api-route-file-parser.ts","../src/framework/cli/command/list/routes/next/collect-api-route-files.ts","../src/framework/cli/command/list/utils.ts","../src/framework/cli/command/list/get-routes.ts","../src/framework/cli/command/list/routes/routes-group-by.ts","../src/framework/cli/command/list/routes/routes-render.ts"],"names":["colors","execSync","existsSync","rmSync","statSync","extname","join","process","mapKeysToPath","layerRegexPath","keys","convertedSubPath","key","map_keys_to_path_default","pathRegexParser","mappedPath","match","path_regex_parser_default","parseRouteLayer","layer","basePath","lastRequestHandler","pathParameters","filtered","element","_a","path","traverse","routes","l","expressPathParser","app","router","express_path_parser_default","expressRoutes","route","express_routes_default","getSegment","line","getMethod","fastifyRoutes","lines","segments","allSegments","index","segment","entries","item","methods","spaces","depth","isRoute","seg","_index","previousArray","r","method","fastify_routes_default","hapiRoutes","coreRoutes","hapi_routes_default","koaRoutes","middlewareFunction","koa_routes_default","jsDocumentCommentsToOpenApi","parseFile","swaggerJsDocumentCommentsToOpenApi","readFileSync","extensionRegex","apiRouteFileParser","apiRouteFile","cwdPath","verbose","specs","parsedJsDocumentFile","parsedSwaggerJsDocumentFile","spec","pathSpec","methodSpec","api_route_file_parser_default","collect","readdirSync","parse","ALLOWED_EXTENSIONS","getAppWorkingDirectoryPath","appFilePath","lastParsedPath","getFrameworkName","directory","packageJSONFilePath","packageJSON","dependencies","getApp","appExport","frameworkName","isDirectory","collectApiRouteFiles","apiFolderPath","collect_api_route_files_default","getRoutes","appOrPath","apiRouteFiles","routesGroupBy","list","keyGetter","map","collection","routes_group_by_default","renderRoute","routePath","colorMap","methodText","coloredMethod","spacesCount","dotsCount","dots","routeText","routesRender","routesMap","options","routes_render_default","listCommand","framework","frameworkPath","appWorkingDirectoryPath","environmentFilePath","isTypeScriptApp","tscPath","error","appJsFilePath","defaultExport","ipath","epath","groupedMap","counter","groupedRoutes","renderedRoute","list_command_default"],"mappings":"AACA,OAAOA,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AAG,EAAE,GAGhDA,EAAM,KAAK,IAAM,UAC3B,EAEGmG,EAAU,EAEdD,EAAW,QAAQ,CAACE,EAAe3H,IAAQ,CACnC0H,EAAU,GAEV,QAAQ,IAAI,EAGhB,IAAMpB,GAAa3G,EAAQ,OAAO,QAAU,GAAKK,EAAI,QAAU,EACzDuG,EAAOD,EAAY,EAAI,MAAM,KAAK,CAAE,OAAQA,CAAU,CAAC,EAAE,KAAK,GAAG,EAAE,KAAK,EAAE,EAAI,GAEpF,QAAQ,IAAIC,EAAOnH,EAAO,KAAK,UAAUY,CAAG,CAAC,EAE7C4G,EAAae,EAAehB,CAAO,EAAE,QAASiB,GAAkB,CAE5D,QAAQ,IAAIA,CAAa,CAC7B,CAAC,EAEDF,GAAW,CACf,CAAC,CACL,MAEI,QAAQ,IAAI,EAEZd,EAAa5F,EAAQ2F,CAAO,EAAE,QAASiB,GAAkB,CAErD,QAAQ,IAAIA,CAAa,CAC7B,CAAC,EAIL,QAAQ,IAAI;AAAA,WAAcxI,EAAO,YAAY,OAAO4B,EAAO,MAAM,CAAC,UAAUA,EAAO,SAAW,EAAI,QAAU;AAAA,CAAa,CAC7H,EAEO6G,GAAQhB","sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nimport colors from \"chalk\";\nimport { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport process from \"node:process\";\n\nimport { getRoutes } from \"./get-routes\";\nimport routesGroupBy from \"./routes/routes-group-by\";\nimport routesRender from \"./routes/routes-render\";\nimport type { Route } from \"./routes/types.d\";\nimport {\n ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName,\n} from \"./utils\";\n\ntype RenderOptions = {\n includePaths: string[];\n excludePaths: string[];\n methods: string[];\n group: string;\n};\n\nconst listCommand = async (\n framework: \"express\" | \"koa\" | \"hapi\" | \"fastify\" | \"next\" | undefined,\n path: string,\n options: Partial<\n {\n verbose: boolean;\n } & RenderOptions\n > = {},\n // eslint-disable-next-line radar/cognitive-complexity\n) => {\n const frameworkPath = join(process.cwd(), path);\n\n if (!existsSync(frameworkPath)) {\n throw new Error(\"No such file, invalid path provided.\");\n }\n\n const appWorkingDirectoryPath = getAppWorkingDirectoryPath(frameworkPath);\n\n if (!appWorkingDirectoryPath) {\n throw new Error(\"Please initialize local package.json.\");\n }\n\n if (framework === undefined) {\n const frameworkName = getFrameworkName(appWorkingDirectoryPath);\n\n if (!frameworkName) {\n throw new Error(\"Couldn't detect supported back-end framework.\");\n }\n\n // eslint-disable-next-line no-param-reassign\n framework = frameworkName;\n }\n\n let routes: null | Route[] = null;\n\n if (framework === \"next\") {\n routes = await getRoutes(frameworkPath, \"next\", options.verbose || false);\n } else {\n if (!statSync(frameworkPath).isFile()) {\n throw new Error(`${frameworkPath} is directory, but file expected.`);\n }\n\n if (!ALLOWED_EXTENSIONS.includes(extname(frameworkPath))) {\n throw new Error(\"Please specify application .ts/.js/.mjs/.cjs file.\");\n }\n\n const environmentFilePath = `${appWorkingDirectoryPath}/.env`;\n\n if (existsSync(environmentFilePath)) {\n // Loads environment vars in the current process so application\n // that depends on them can be loaded properly below\n const dotEnvironmentFilePath = `${appWorkingDirectoryPath}/node_modules/dotenv/lib/main.js`;\n const dotenv = await import(dotEnvironmentFilePath);\n\n dotenv.config({ path: environmentFilePath });\n }\n\n const isTypeScriptApp = extname(frameworkPath) === \".ts\";\n const tscPath = join(appWorkingDirectoryPath, \"node_modules/.bin/tsc\");\n\n if (isTypeScriptApp && !existsSync(tscPath)) {\n throw new Error(`Please install typescript in ${appWorkingDirectoryPath}`);\n }\n\n try {\n if (isTypeScriptApp) {\n // || rm -r ./framework-list removes framework-list directory in case tsc fails\n\n try {\n execSync(`${tscPath} --outDir framework-list >&2`, { cwd: appWorkingDirectoryPath });\n } catch (error: any) {\n // eslint-disable-next-line no-console\n console.log(\"TSC compilation failed. Please resolve issues in your project.\\n\");\n // eslint-disable-next-line no-console\n console.log(error);\n\n // eslint-disable-next-line radar/no-duplicate-string\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n\n const appJsFilePath = isTypeScriptApp\n ? join(appWorkingDirectoryPath, \"framework-list\", frameworkPath.replace(appWorkingDirectoryPath, \"\").replace(\".ts\", \".js\"))\n : frameworkPath;\n\n const { default: defaultExport } = await import(appJsFilePath);\n\n routes = await getRoutes(\n [\"AsyncFunction\", \"Function\"].includes(defaultExport.constructor.name) ? await defaultExport() : getApp(defaultExport, framework),\n framework,\n options.verbose || false,\n );\n } finally {\n if (isTypeScriptApp) {\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n }\n\n if (routes === null) {\n throw new Error(`Framework \"${framework}\" is not supported.`);\n }\n\n if (Array.isArray(options.includePaths) && options.includePaths.length > 0) {\n routes = options.includePaths.flatMap((ipath) => (routes as Route[]).filter((route) => route.path.startsWith(ipath)));\n }\n\n if (Array.isArray(options.excludePaths) && options.excludePaths.length > 0) {\n routes = options.excludePaths.flatMap((epath) => (routes as Route[]).filter((route) => !route.path.startsWith(epath)));\n }\n\n if (typeof options.group === \"string\" && options.group !== \"\") {\n // eslint-disable-next-line no-console\n console.log();\n\n const groupedMap = routesGroupBy(routes, (route) => {\n if (options.group === \"path\") {\n return route.path.replace(\"/pages\", \"\").split(\"/\")[1];\n }\n\n return route.tags[0] || \"unsorted\";\n });\n\n let counter = 0;\n\n groupedMap.forEach((groupedRoutes, key) => {\n if (counter > 0) {\n // eslint-disable-next-line no-console\n console.log();\n }\n\n const dotsCount = (process.stdout.columns - 16 - key.length) / 2;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\" \").join(\"\") : \"\";\n // eslint-disable-next-line no-console\n console.log(dots + colors.bold.underline(key));\n\n routesRender(groupedRoutes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n\n counter += 1;\n });\n } else {\n // eslint-disable-next-line no-console\n console.log();\n\n routesRender(routes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(`\\n Listed ${colors.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n","import type { ExpressRegex, Key } from \"./types.d\";\n\n/**\n * Map's the keys/path variables to the regex inside a given path\n *\n * @param layerRegexPath The regex for a router with path parameters\n * @param keys The keys that represent the path parameters\n *\n * @returns The regex for a path variable converted to original string on the express route\n */\nconst mapKeysToPath = (layerRegexPath: ExpressRegex, keys: Key[]): string => {\n if (!keys || keys.length === 0) {\n throw new Error(\"must include atleast one key to map\");\n }\n\n let convertedSubPath = layerRegexPath.toString();\n\n keys.forEach((key) => {\n convertedSubPath = key.optional\n ? convertedSubPath.replace(\"(?:\\\\/([^\\\\/]+?))?\\\\\", `/:${key.name}?`)\n : convertedSubPath.replace(\"(?:([^\\\\/]+?))\", `:${key.name}`);\n });\n\n return convertedSubPath\n .replace(\"/?(?=\\\\/|$)/i\", \"\")\n .replace(\"/^\", \"\")\n .replace(/\\\\/gi, \"\")\n .replace(/\\/{2,}/gi, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types.d\";\n\n/** Parses an express layer's regex and converts it to the original format seen in code.\n *\n * @param layerRegexPath The layer's regex pattern\n * @param keys The keys that represent the layer's path parameters\n * @returns The path string for that layer\n * Code inspired and modify from:\n * https://github.com/expressjs/express/issues/3308#issuecomment-300957572\n */\nconst pathRegexParser = (layerRegexPath: ExpressRegex | string, keys: Key[]): string => {\n if (typeof layerRegexPath === \"string\") {\n return layerRegexPath;\n }\n\n if (layerRegexPath.fast_slash) {\n return \"\";\n }\n\n if (layerRegexPath.fast_star) {\n return \"*\";\n }\n\n let mappedPath = \"\";\n\n if (keys && keys.length > 0) {\n mappedPath = mapKeysToPath(layerRegexPath, keys);\n }\n\n const match = layerRegexPath\n .toString()\n .replace(\"\\\\/?\", \"\")\n .replace(\"(?=\\\\/|$)\", \"$\")\n .match(/^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//) as string[];\n\n if (match) {\n return (match[1] as string).replace(/\\\\(.)/g, \"$1\").slice(1);\n }\n\n if (mappedPath) {\n return mappedPath.slice(1);\n }\n\n return layerRegexPath.toString();\n};\n\nexport default pathRegexParser;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport {\n Key, Layer, Parameter, Route, RouteMetaData,\n} from \"./types\";\n\n/**\n * Parses a route object. Route objects are the leafs of an express router tree\n *\n * @param layer The layer of this route object - represents the stack of middleware and other metadata\n * @param keys The full set of keys for this particular route\n * @param basePath The base path as it was initial declared for this route\n * @returns A ExpressPath object holding the metadata for a given route\n */\nconst parseRouteLayer = (layer: Layer, keys: Key[], basePath: string): RouteMetaData => {\n const lastRequestHandler = layer.route.stack[layer.route.stack.length - 1] as Layer;\n const pathParameters: Parameter[] = keys.map((key) => {\n return { name: key.name, in: \"path\", required: !key.optional };\n });\n const filtered = layer.route.stack.filter((element) => (element?.handle as Route)?.metadata);\n\n if (filtered.length > 1) {\n throw new Error(\"Only one metadata middleware is allowed per route\");\n }\n\n const path = (basePath + layer.route.path).replace(/\\/{2,}/gi, \"/\");\n\n if (filtered.length === 0) {\n return { path, pathParams: pathParameters, method: lastRequestHandler.method };\n }\n\n return {\n path,\n pathParams: pathParameters,\n method: lastRequestHandler.method,\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\n };\n};\n\n/**\n * Recursive traversal method for the express router and middleware tree.\n *\n * @param routes The array of routes to add to\n * @param path The current path segment that we have traversed so far\n * @param layer The current 'layer' of the router tree\n * @param keys The keys for the parameter's in the current path branch of the traversal\n * @returns void - base case saves result to internal object\n */\nconst traverse = (routes: RouteMetaData[], path: string, layer: Layer, keys: Key[]): void => {\n // eslint-disable-next-line no-param-reassign\n keys = [...keys, ...layer.keys];\n\n if (layer.name === \"router\" && layer.handle) {\n layer.handle.stack.forEach((l: Layer) => {\n // eslint-disable-next-line no-param-reassign\n path = path || \"\";\n\n traverse(routes, `${path}/${pathRegexParser(layer.regexp, layer.keys)}`, l, keys);\n });\n }\n\n if (!layer.route || layer.route.stack.length === 0) {\n return;\n }\n\n routes.push(parseRouteLayer(layer, keys, path));\n};\n\n// @TODO use this to parse the express swagger\n\n/**\n * Parses an Express app and generates list of routes with metadata.\n *\n * Can Parse:\n * - Nested Routers and Complex Express Projects\n * - Optional parameters e.g. /:name?\n * - Complex Matching routes e.g. /ma*tch, /ex(ab)?mple\n * - Regex routes e.g. /\\/abc|\\/xyz/\n * - Array of paths e.g. app.get(['/abc', '/xyz']) -> /abc,xyz/\n *\n * @param app The Express app reference. Must be used after all routes have been attached\n *\n * @returns List of routes for this express app with meta-data that has been picked up\n */\nconst expressPathParser = (app: Express) => {\n // eslint-disable-next-line no-underscore-dangle\n const router: Router = app._router || app.router;\n const routes: RouteMetaData[] = [];\n\n if (router) {\n router.stack.forEach((layer: Layer) => {\n traverse(routes, \"\", layer, []);\n });\n }\n\n return routes;\n};\n\nexport default expressPathParser;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { Express } from \"express\";\n\nimport expressPathParser from \"./express/express-path-parser\";\nimport type { RouteMetaData } from \"./express/types\";\nimport type { Route } from \"./types\";\n\nconst expressRoutes = (app: Express): Route[] => {\n const routes: Route[] = [];\n\n expressPathParser(app).forEach((route: RouteMetaData) => {\n routes.push({\n path: route.path,\n method: route.method.toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replace(/ \\(.*\\)/g, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ntype Segment = { index: number; segment: string; methods: string[] | null, depth: number, isRoute: boolean };\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replace(/[─│└├]/g, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\n const segments = lines.reduce((allSegments: Segment[], line, index) => {\n const segment = getSegment(line);\n const previousSegment = getSegment(lines[index - 1] || \"\");\n\n if (previousSegment === segment) {\n const entries: Segment[] = allSegments.filter((item) => item.index < index && item.segment === segment);\n\n const { methods } = entries[entries.length - 1] as Segment;\n\n if (methods !== null) {\n methods.push(getMethod(line));\n }\n\n return allSegments;\n }\n\n // spaces preceding segment / not counting single space between segment and (METHOD)\n const spaces = line.replace(/ \\(.*\\)/g, \"\").match(/ /g);\n\n if (spaces === null) {\n throw new Error(\"Invalid spaces\");\n }\n\n const depth = spaces.length / 4;\n const isRoute = line.includes(\"(\");\n const methods = isRoute ? [getMethod(line)] : null;\n\n allSegments.push({\n segment, index, depth, isRoute, methods,\n });\n\n return allSegments;\n }, []);\n\n const routes: Route[] = [];\n\n segments\n .filter((item) => item.isRoute)\n .forEach((item) => {\n const ancestorSegments = segments\n .filter((seg) => seg.index < item.index && seg.depth < item.depth)\n // eslint-disable-next-line unicorn/prefer-array-some\n .filter((seg, _index, previousArray) => !previousArray.find((segment) => segment.depth === seg.depth && segment.index > seg.index));\n\n const route = [...ancestorSegments.map((r) => r.segment), item.segment].join(\"\");\n\n if (item.methods === null) {\n throw new Error(\"Invalid methods\");\n }\n\n item.methods.forEach((method: string) => {\n routes.push({\n path: route,\n method: method.toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error\n // eslint-disable-next-line no-underscore-dangle\n const core = app._core as any;\n const coreRoutes = core.router.routes;\n const routes: Route[] = [];\n\n [...coreRoutes.keys()].forEach((method: string) => {\n coreRoutes.get(method).routes.forEach((route: any) => {\n routes.push({\n path: route.path,\n method: route.route.method.toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport Koa from \"koa\";\n\nimport type { Route } from \"./types\";\n\nconst koaRoutes = (app: Koa): Route[] => {\n const routes: Route[] = [];\n\n app.middleware\n .filter((middlewareFunction) => (middlewareFunction as any).router)\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n path: route.path,\n method: route.methods.join(\"|\").toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\nimport { readFileSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport type { Route } from \"../types.d\";\n\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/;\n\nconst apiRouteFileParser = (apiRouteFile: string, cwdPath: string, verbose: boolean = false): Route[] => {\n let specs: OpenApiObject[] = [];\n\n const parsedJsDocumentFile = parseFile(apiRouteFile, jsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedJsDocumentFile.map((item) => item.spec)];\n\n const parsedSwaggerJsDocumentFile = parseFile(apiRouteFile, swaggerJsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedSwaggerJsDocumentFile.map((item) => item.spec)];\n\n const routes: Route[] = [];\n\n if (specs.length === 0) {\n const apiRouteFileContent = readFileSync(apiRouteFile, \"utf8\");\n\n apiRouteFileContent.split(/\\r?\\n/).forEach((line) => {\n const match = line.match(/[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/);\n\n if (match) {\n let [, method] = match;\n\n if (method === \"GET\") {\n method = \"GET|HEAD\";\n }\n\n routes.push({\n method: method as string,\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\"),\n tags: [],\n file: apiRouteFile.replace(`${process.cwd()}/`, \"\"),\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\"),\n tags: [],\n file: apiRouteFile.replace(`${process.cwd()}/`, \"\"),\n });\n }\n\n return routes;\n }\n\n specs.forEach((spec) => {\n const paths = Object.entries(spec.paths);\n\n paths.forEach(([path, pathSpec]) => {\n const methods = Object.entries(pathSpec);\n\n methods.forEach(([method, methodSpec]) => {\n routes.push({\n path, method: method.toUpperCase(), tags: methodSpec.tags, file: apiRouteFile.replace(`${process.cwd()}/`, \"\"),\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/readdir\";\nimport { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ALLOWED_EXTENSIONS } from \"../../utils\";\n\nconst isDirectory = (path: string): boolean => {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst collectApiRouteFiles = async (path: string = \"\", verbose: boolean = false): Promise<string[]> => {\n let apiFolderPath = join(path, \"pages/api\");\n\n // src/pages will be ignored if pages is present in the root directory\n if (!isDirectory(apiFolderPath)) {\n apiFolderPath = join(path, \"src/pages/api\");\n\n if (!isDirectory(apiFolderPath)) {\n return [];\n }\n }\n\n return collect(apiFolderPath, {\n extensions: ALLOWED_EXTENSIONS,\n includeDirs: false,\n minimatchOptions: {\n match: {\n debug: verbose,\n matchBase: true,\n },\n skip: {\n debug: verbose,\n matchBase: true,\n },\n },\n });\n};\n\nexport default collectApiRouteFiles;\n","import { readdirSync, readFileSync } from \"node:fs\";\nimport { parse } from \"node:path\";\n\nexport const ALLOWED_EXTENSIONS = [\".js\", \".ts\", \".mjs\", \".cjs\"];\n\nexport const getAppWorkingDirectoryPath = (appFilePath: string) => {\n let lastParsedPath = parse(appFilePath);\n\n // Once the following condition returns false it means we traversed the whole file system\n while (lastParsedPath.base && lastParsedPath.root !== lastParsedPath.dir) {\n const parentDirectionItems = readdirSync(lastParsedPath.dir);\n\n const packageJSON = parentDirectionItems.find((item) => item === \"package.json\");\n\n if (packageJSON) {\n return lastParsedPath.dir;\n }\n\n lastParsedPath = parse(lastParsedPath.dir);\n }\n\n return null;\n};\n\nexport const getFrameworkName = (directory: string) => {\n const packageJSONFilePath = `${directory}/package.json`;\n const packageJSON = JSON.parse(readFileSync(packageJSONFilePath).toString());\n const { dependencies } = packageJSON;\n\n if (dependencies.express) {\n return \"express\";\n }\n\n if (dependencies.koa && (dependencies[\"@koa/router\"] || dependencies[\"koa-router\"])) {\n return \"koa\";\n }\n\n if (dependencies.next) {\n return \"next\";\n }\n\n if (dependencies[\"@hapi/hapi\"]) {\n return \"hapi\";\n }\n\n if (dependencies.fastify) {\n return \"fastify\";\n }\n\n return null;\n};\n\nexport const getApp = (appExport: { [key: string]: any }, frameworkName: string) => {\n const isExportEmpty = Object.keys(appExport).length === 0;\n\n if (isExportEmpty) {\n return null;\n }\n\n if (frameworkName === \"hapi\") {\n return appExport.app?.app ? appExport.app : appExport;\n }\n\n return appExport.app || appExport;\n};\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport { Server } from \"@hapi/hapi\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { Express } from \"express\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { FastifyInstance } from \"fastify\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport Koa from \"koa\";\n\nimport expressRoutes from \"./routes/express-routes\";\nimport fastifyRoutes from \"./routes/fastify-routes\";\nimport hapiRoutes from \"./routes/hapi-routes\";\nimport koaRoutes from \"./routes/koa-routes\";\nimport apiRouteFileParser from \"./routes/next/api-route-file-parser\";\nimport collectApiRouteFiles from \"./routes/next/collect-api-route-files\";\nimport type { Route } from \"./routes/types.d\";\n\nexport type FrameworkName = \"express\" | \"koa\" | \"hapi\" | \"fastify\" | \"next\";\nexport async function getRoutes(\n appOrPath: string | Express | Koa | Server | FastifyInstance,\n frameworkName: FrameworkName,\n verbose: boolean,\n): Promise<Route[] | null> {\n if (frameworkName === \"express\") {\n return expressRoutes(appOrPath as Express);\n }\n\n if (frameworkName === \"koa\") {\n return koaRoutes(appOrPath as Koa);\n }\n\n if (frameworkName === \"hapi\") {\n return hapiRoutes(appOrPath as Server);\n }\n\n if (frameworkName === \"fastify\") {\n return fastifyRoutes(appOrPath as FastifyInstance);\n }\n\n if (frameworkName === \"next\") {\n const apiRouteFiles = await collectApiRouteFiles(appOrPath as string, verbose);\n\n if (apiRouteFiles.length === 0) {\n throw new Error(`No API routes found, in \"${appOrPath}\".`);\n }\n\n return apiRouteFiles.flatMap((apiRouteFile) => apiRouteFileParser(apiRouteFile, appOrPath as string, verbose));\n }\n\n return null;\n}\n","import type { Route } from \"./types\";\n\nconst routesGroupBy = (list: Route[], keyGetter: (item: Route) => keyof Route): Map<string, Route[]> => {\n const map = new Map();\n\n list.forEach((item) => {\n const key = keyGetter(item);\n const collection = map.get(key);\n\n if (collection) {\n collection.push(item);\n } else {\n map.set(key, [item]);\n }\n });\n\n return map;\n};\n\nexport default routesGroupBy;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport colors from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n GET: colors.blue,\n POST: colors.yellow,\n PATCH: colors.yellow,\n PUT: colors.yellow,\n DELETE: colors.redBright,\n OPTIONS: colors.hex(\"#6C7280\"),\n ANY: colors.redBright,\n HEAD: colors.hex(\"#6C7280\"),\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${colors.blue(\"GET\")}${colors.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${colors.grey(\"|HEAD\")}` : coloredMethod;\n }\n\n const spacesCount = method === \"GET\" ? 6 : 14 - method.length;\n const spaces = Array.from({ length: spacesCount }).fill(\" \").join(\"\");\n\n const dotsCount = process.stdout.columns - 16 - routePath.length - 4;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\".\").join(\"\") : \"\";\n\n const routeText = routePath\n .split(\"/\")\n .map((segment) => {\n const isDynamicSegment = [\"[\", \":\"].includes(segment[0] || \"\");\n\n return isDynamicSegment ? colors.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${colors.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[]; } = {}) => routesMap\n .map((route) => {\n if (Array.isArray(options.methods) && options.methods.includes(route.method)) {\n return;\n }\n\n if (route.method === \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\") {\n // eslint-disable-next-line no-param-reassign\n route.method = \"ANY\";\n }\n\n // eslint-disable-next-line consistent-return\n return renderRoute(route.method, route.path.replace(\"/pages\", \"\"));\n })\n .filter(Boolean);\n\nexport default routesRender;\n"]}
@@ -1,10 +0,0 @@
1
- import g from"next/head";import{RedocStandalone as i}from"redoc";import{Fragment as f,jsx as o,jsxs as p}from"react/jsx-runtime";var c=(t,r={})=>({swaggerData:e})=>p(f,{children:[p(g,{children:[o("title",{children:t}),o("style",{children:`
2
- body {
3
- background: #fafafa !important;
4
- }
5
- `})]}),o(i,{...r,spec:e})]}),n=c;import m from"next/dynamic";import P from"next/head";import{Fragment as l,jsx as a,jsxs as s}from"react/jsx-runtime";var d=m(()=>import("swagger-ui-react"),{ssr:!1}),S=(t,r={})=>({swaggerData:e})=>s(l,{children:[s(P,{children:[a("title",{children:t}),a("style",{children:`
6
- body {
7
- background: #fafafa !important;
8
- }
9
- `})]}),a(d,{...r,spec:e})]}),y=S;import w from"debug";var u=w("visulima:api-platform:swagger:get-static-properties-swagger"),x=t=>async()=>{let e=await(await fetch(t)).json();return u(e),{props:{swaggerUrl:t,swaggerData:JSON.parse(JSON.stringify(e))}}},I=x;export{n as a,y as b,I as c};
10
- //# sourceMappingURL=chunk-GTXHW632.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/framework/next/routes/pages/swagger/redoc.tsx","../src/framework/next/routes/pages/swagger/swagger.tsx","../src/framework/next/routes/pages/swagger/get-static-properties-swagger.ts"],"sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { InferGetStaticPropsType, NextPage } from \"next\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport Head from \"next/head\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { RedocStandaloneProps } from \"redoc\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { RedocStandalone } from \"redoc\";\n\nimport getStaticProps from \"./get-static-properties-swagger\";\n\n// eslint-disable-next-line max-len\nconst RedocApiDocument: (\n name: string,\n swagger?: Exclude<RedocStandaloneProps, \"spec\">,\n // eslint-disable-next-line max-len,unicorn/no-useless-undefined\n) => NextPage<InferGetStaticPropsType<typeof getStaticProps>> = (name, swagger = {}) => ({ swaggerData }: InferGetStaticPropsType<typeof getStaticProps>) => (\n <>\n <Head>\n <title>{name}</title>\n <style>\n {`\nbody {\n background: #fafafa !important;\n}\n`}\n </style>\n </Head>\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n <RedocStandalone {...swagger} spec={swaggerData} />\n </>\n);\n\nexport default RedocApiDocument;\n","import type { InferGetStaticPropsType, NextPage } from \"next\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport dynamic from \"next/dynamic\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport Head from \"next/head\";\nimport type { SwaggerUIProps } from \"swagger-ui-react\";\n\nimport getStaticProps from \"./get-static-properties-swagger\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nconst SwaggerUI = dynamic(() => import(\"swagger-ui-react\"), { ssr: false });\n\n// eslint-disable-next-line max-len\nconst SwaggerApiDocument: (\n name: string,\n swagger?: Exclude<SwaggerUIProps, \"spec\">,\n // eslint-disable-next-line max-len,unicorn/no-useless-undefined\n) => NextPage<InferGetStaticPropsType<typeof getStaticProps>> = (name, swagger = {}) => ({ swaggerData }: InferGetStaticPropsType<typeof getStaticProps>) => (\n <>\n <Head>\n <title>{name}</title>\n <style>\n {`\nbody {\n background: #fafafa !important;\n}\n`}\n </style>\n </Head>\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n <SwaggerUI {...swagger} spec={swaggerData} />\n </>\n);\n\nexport default SwaggerApiDocument;\n","// eslint-disable-next-line unicorn/prevent-abbreviations\nimport debug from \"debug\";\nimport type { GetStaticProps } from \"next\";\nimport type { OpenAPIV3 } from \"openapi-types\";\n\n// eslint-disable-next-line testing-library/no-debugging-utils\nconst swaggerDebug = debug(\"visulima:api-platform:swagger:get-static-properties-swagger\");\n\n// eslint-disable-next-line unicorn/consistent-function-scoping\nconst getStaticProps: (\n swaggerUrl: string,\n) => GetStaticProps = (swaggerUrl) => async (): Promise<{\n props: {\n swaggerUrl: string;\n swaggerData: OpenAPIV3.Document;\n };\n}> => {\n // eslint-disable-next-line compat/compat\n const response = await fetch(swaggerUrl);\n const swaggerData = await response.json();\n\n swaggerDebug(swaggerData);\n\n return {\n props: {\n swaggerUrl,\n swaggerData: JSON.parse(JSON.stringify(swaggerData)),\n },\n };\n};\n\nexport default getStaticProps;\n"],"mappings":"AAGA,OAAOA,MAAU,YAIjB,OAAS,mBAAAC,MAAuB,QAUpB,mBAAAC,EAEQ,OAAAC,EADJ,QAAAC,MADJ,oBALZ,IAAMC,EAI0D,CAACC,EAAMC,EAAU,CAAC,IAAM,CAAC,CAAE,YAAAC,CAAY,IAC3FJ,EAAAF,EAAA,CACI,UAAAE,EAACJ,EAAA,CACG,UAAAG,EAAC,SAAO,SAAAG,EAAK,EACbH,EAAC,SACI;AAAA;AAAA;AAAA;AAAA,EAKL,GACJ,EAEAA,EAACF,EAAA,CAAiB,GAAGM,EAAS,KAAMC,EAAa,GACrD,EAGLC,EAAQJ,EC/Bf,OAAOK,MAAa,eAEpB,OAAOC,MAAU,YAaL,mBAAAC,EAEQ,OAAAC,EADJ,QAAAC,MADJ,oBARZ,IAAMC,EAAYL,EAAQ,IAAM,OAAO,oBAAqB,CAAE,IAAK,EAAM,CAAC,EAGpEM,EAI0D,CAACC,EAAMC,EAAU,CAAC,IAAM,CAAC,CAAE,YAAAC,CAAY,IAC3FL,EAAAF,EAAA,CACI,UAAAE,EAACH,EAAA,CACG,UAAAE,EAAC,SAAO,SAAAI,EAAK,EACbJ,EAAC,SACI;AAAA;AAAA;AAAA;AAAA,EAKL,GACJ,EAEAA,EAACE,EAAA,CAAW,GAAGG,EAAS,KAAMC,EAAa,GAC/C,EAGLC,EAAQJ,EChCf,OAAOK,MAAW,QAKlB,IAAMC,EAAeD,EAAM,6DAA6D,EAGlFE,EAEiBC,GAAe,SAKhC,CAGF,IAAMC,EAAc,MADH,MAAM,MAAMD,CAAU,GACJ,KAAK,EAExC,OAAAF,EAAaG,CAAW,EAEjB,CACH,MAAO,CACH,WAAAD,EACA,YAAa,KAAK,MAAM,KAAK,UAAUC,CAAW,CAAC,CACvD,CACJ,CACJ,EAEOC,EAAQH","names":["Head","RedocStandalone","Fragment","jsx","jsxs","RedocApiDocument","name","swagger","swaggerData","redoc_default","dynamic","Head","Fragment","jsx","jsxs","SwaggerUI","SwaggerApiDocument","name","swagger","swaggerData","swagger_default","debug","swaggerDebug","getStaticProps","swaggerUrl","swaggerData","get_static_properties_swagger_default"]}
@@ -1,2 +0,0 @@
1
- import{a as Z}from"./chunk-YOXCJZNX.mjs";var I={};Z(I,{dateIn:()=>K,dateOut:()=>w});import{withGetType as x}from"zod-to-ts";import{addIssueToContext as s,INVALID as c,ZodIssueCode as n,ZodParsedType as u,ZodType as g}from"zod";var N="ZodDateIn",P=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?)?Z?$/,p=class extends g{_parse(t){let{status:d,ctx:e}=this._processInputParams(t);if(e.parsedType!==u.string)return s(e,{code:n.invalid_type,expected:u.string,received:e.parsedType}),c;P.test(e.data)||(s(e,{code:n.invalid_string,validation:"regex"}),d.dirty());let y=new Date(e.data);return Number.isNaN(y.getTime())?(s(e,{code:n.invalid_date}),c):{status:d.value,value:y}}},a=p;a.create=()=>new p({typeName:N});import{addIssueToContext as f,INVALID as m,ZodIssueCode as D,ZodParsedType as T,ZodType as l}from"zod";var v="ZodDateOut",i=class extends l{_parse(t){let{status:d,ctx:e}=this._processInputParams(t);return e.parsedType!==T.date?(f(e,{code:D.invalid_type,expected:T.date,received:e.parsedType}),m):Number.isNaN(e.data.getTime())?(f(e,{code:D.invalid_date}),m):{status:d.value,value:e.data.toISOString()}}},r=i;r.create=()=>new i({typeName:v});var K=(...o)=>x(a.create(...o),t=>t.factory.createKeywordTypeNode(t.SyntaxKind.StringKeyword)),w=(...o)=>x(r.create(...o),t=>t.factory.createKeywordTypeNode(t.SyntaxKind.StringKeyword));export{K as a,w as b,I as c};
2
- //# sourceMappingURL=chunk-HONWWBY6.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/zod/index.ts","../src/zod/date-in-schema.ts","../src/zod/date-out-schema.ts"],"sourcesContent":["import { withGetType } from \"zod-to-ts\";\n\nimport { ZodDateIn } from \"./date-in-schema\";\nimport { ZodDateOut } from \"./date-out-schema\";\n\n// eslint-disable-next-line max-len\nexport const dateIn = (...parameters: Parameters<typeof ZodDateIn.create>) => withGetType(ZodDateIn.create(...parameters), (ts) => ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword));\n// eslint-disable-next-line max-len\nexport const dateOut = (...parameters: Parameters<typeof ZodDateOut.create>) => withGetType(ZodDateOut.create(...parameters), (ts) => ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword));\n","import type { ParseInput, ParseReturnType, ZodTypeDef } from \"zod\";\nimport {\n addIssueToContext, INVALID, ZodIssueCode, ZodParsedType, ZodType,\n} from \"zod\";\n\nconst zodDateInKind = \"ZodDateIn\";\n\n// simple regex for ISO date, supports the following formats:\n// 2021-01-01T00:00:00.000Z\n// 2021-01-01T00:00:00Z\n// 2021-01-01T00:00:00\n// 2021-01-01\nexport const isoDateRegex = /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?)?Z?$/;\n\n// eslint-disable-next-line unicorn/prevent-abbreviations\nexport interface ZodDateInDef extends ZodTypeDef {\n typeName: typeof zodDateInKind;\n}\n\nexport class ZodDateIn extends ZodType<Date, ZodDateInDef, string> {\n // eslint-disable-next-line no-underscore-dangle\n _parse(input: ParseInput): ParseReturnType<Date> {\n // eslint-disable-next-line no-underscore-dangle\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.string) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n\n if (!isoDateRegex.test(ctx.data as string)) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"regex\",\n });\n status.dirty();\n }\n\n const date = new Date(ctx.data);\n\n if (Number.isNaN(date.getTime())) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n\n return { status: status.value, value: date };\n }\n\n static create = () => new ZodDateIn({\n typeName: zodDateInKind,\n });\n}\n","import type { ParseInput, ParseReturnType, ZodTypeDef } from \"zod\";\nimport {\n addIssueToContext, INVALID, ZodIssueCode, ZodParsedType, ZodType,\n} from \"zod\";\n\nconst zodDateOutKind = \"ZodDateOut\";\n\n// eslint-disable-next-line unicorn/prevent-abbreviations\nexport interface ZodDateOutDef extends ZodTypeDef {\n typeName: typeof zodDateOutKind;\n}\n\nexport class ZodDateOut extends ZodType<string, ZodDateOutDef, Date> {\n // eslint-disable-next-line no-underscore-dangle\n _parse(input: ParseInput): ParseReturnType<string> {\n // eslint-disable-next-line no-underscore-dangle\n const { status, ctx } = this._processInputParams(input);\n\n if (ctx.parsedType !== ZodParsedType.date) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n\n if (Number.isNaN(ctx.data.getTime())) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n\n return { status: status.value, value: (ctx.data as Date).toISOString() };\n }\n\n static create = () => new ZodDateOut({\n typeName: zodDateOutKind,\n });\n}\n"],"mappings":"yCAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,YAAAC,IAAA,OAAS,eAAAC,MAAmB,YCC5B,OACI,qBAAAC,EAAmB,WAAAC,EAAS,gBAAAC,EAAc,iBAAAC,EAAe,WAAAC,MACtD,MAEP,IAAMC,EAAgB,YAOTC,EAAe,uDAOfC,EAAN,cAAwBH,CAAoC,CAE/D,OAAOI,EAA0C,CAE7C,GAAM,CAAE,OAAAC,EAAQ,IAAAC,CAAI,EAAI,KAAK,oBAAoBF,CAAK,EACtD,GAAIE,EAAI,aAAeP,EAAc,OACjC,OAAAH,EAAkBU,EAAK,CACnB,KAAMR,EAAa,aACnB,SAAUC,EAAc,OACxB,SAAUO,EAAI,UAClB,CAAC,EACMT,EAGNK,EAAa,KAAKI,EAAI,IAAc,IACrCV,EAAkBU,EAAK,CACnB,KAAMR,EAAa,eACnB,WAAY,OAChB,CAAC,EACDO,EAAO,MAAM,GAGjB,IAAME,EAAO,IAAI,KAAKD,EAAI,IAAI,EAE9B,OAAI,OAAO,MAAMC,EAAK,QAAQ,CAAC,GAC3BX,EAAkBU,EAAK,CACnB,KAAMR,EAAa,YACvB,CAAC,EACMD,GAGJ,CAAE,OAAQQ,EAAO,MAAO,MAAOE,CAAK,CAC/C,CAKJ,EArCaC,EAANL,EAAMK,EAkCF,OAAS,IAAM,IAAIL,EAAU,CAChC,SAAUF,CACd,CAAC,ECtDL,OACI,qBAAAQ,EAAmB,WAAAC,EAAS,gBAAAC,EAAc,iBAAAC,EAAe,WAAAC,MACtD,MAEP,IAAMC,EAAiB,aAOVC,EAAN,cAAyBF,CAAqC,CAEjE,OAAOG,EAA4C,CAE/C,GAAM,CAAE,OAAAC,EAAQ,IAAAC,CAAI,EAAI,KAAK,oBAAoBF,CAAK,EAEtD,OAAIE,EAAI,aAAeN,EAAc,MACjCH,EAAkBS,EAAK,CACnB,KAAMP,EAAa,aACnB,SAAUC,EAAc,KACxB,SAAUM,EAAI,UAClB,CAAC,EACMR,GAGP,OAAO,MAAMQ,EAAI,KAAK,QAAQ,CAAC,GAC/BT,EAAkBS,EAAK,CACnB,KAAMP,EAAa,YACvB,CAAC,EACMD,GAGJ,CAAE,OAAQO,EAAO,MAAO,MAAQC,EAAI,KAAc,YAAY,CAAE,CAC3E,CAKJ,EA5BaC,EAANJ,EAAMI,EAyBF,OAAS,IAAM,IAAIJ,EAAW,CACjC,SAAUD,CACd,CAAC,EFjCE,IAAMM,EAAS,IAAIC,IAAoDC,EAAYC,EAAU,OAAO,GAAGF,CAAU,EAAIG,GAAOA,EAAG,QAAQ,sBAAsBA,EAAG,WAAW,aAAa,CAAC,EAEnLC,EAAU,IAAIJ,IAAqDC,EAAYI,EAAW,OAAO,GAAGL,CAAU,EAAIG,GAAOA,EAAG,QAAQ,sBAAsBA,EAAG,WAAW,aAAa,CAAC","names":["zod_exports","__export","dateIn","dateOut","withGetType","addIssueToContext","INVALID","ZodIssueCode","ZodParsedType","ZodType","zodDateInKind","isoDateRegex","_ZodDateIn","input","status","ctx","date","ZodDateIn","addIssueToContext","INVALID","ZodIssueCode","ZodParsedType","ZodType","zodDateOutKind","_ZodDateOut","input","status","ctx","ZodDateOut","dateIn","parameters","withGetType","ZodDateIn","ts","dateOut","ZodDateOut"]}
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkOUWZ2PU5js = require('./chunk-OUWZ2PU5.js');var I={};_chunkOUWZ2PU5js.a.call(void 0, I,{dateIn:()=>K,dateOut:()=>w});var _zodtots = require('zod-to-ts');var _zod = require('zod');var N="ZodDateIn",P=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?)?Z?$/,p=class extends _zod.ZodType{_parse(t){let{status:d,ctx:e}=this._processInputParams(t);if(e.parsedType!==_zod.ZodParsedType.string)return _zod.addIssueToContext.call(void 0, e,{code:_zod.ZodIssueCode.invalid_type,expected:_zod.ZodParsedType.string,received:e.parsedType}),_zod.INVALID;P.test(e.data)||(_zod.addIssueToContext.call(void 0, e,{code:_zod.ZodIssueCode.invalid_string,validation:"regex"}),d.dirty());let y=new Date(e.data);return Number.isNaN(y.getTime())?(_zod.addIssueToContext.call(void 0, e,{code:_zod.ZodIssueCode.invalid_date}),_zod.INVALID):{status:d.value,value:y}}},a=p;a.create=()=>new p({typeName:N});var v="ZodDateOut",i=class extends _zod.ZodType{_parse(t){let{status:d,ctx:e}=this._processInputParams(t);return e.parsedType!==_zod.ZodParsedType.date?(_zod.addIssueToContext.call(void 0, e,{code:_zod.ZodIssueCode.invalid_type,expected:_zod.ZodParsedType.date,received:e.parsedType}),_zod.INVALID):Number.isNaN(e.data.getTime())?(_zod.addIssueToContext.call(void 0, e,{code:_zod.ZodIssueCode.invalid_date}),_zod.INVALID):{status:d.value,value:e.data.toISOString()}}},r=i;r.create=()=>new i({typeName:v});var K=(...o)=>_zodtots.withGetType.call(void 0, a.create(...o),t=>t.factory.createKeywordTypeNode(t.SyntaxKind.StringKeyword)),w= exports.b =(...o)=>_zodtots.withGetType.call(void 0, r.create(...o),t=>t.factory.createKeywordTypeNode(t.SyntaxKind.StringKeyword));exports.a = K; exports.b = w; exports.c = I;
2
- //# sourceMappingURL=chunk-JXD3457O.js.map