@visulima/api-platform 3.0.55 → 3.0.56

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/error-handler/utils.ts","../src/error-handler/jsonapi-error-handler.ts","../src/error-handler/problem-error-handler.ts","../src/connect/handler.ts","../src/connect/middleware/http-header-normalizer.ts","../src/serializers/has-json-structure.ts","../src/serializers/transformer/xml.ts","../src/serializers/serialize.ts","../src/connect/middleware/serializers-middleware.ts","../src/connect/create-node-router.ts","../src/connect/middleware/cors-middleware.ts","../src/connect/middleware/rate-limiter-middleware.ts"],"names":["setErrorHeaders","response","error","headers","header","sendJson","jsonBody","addStatusCodeToResponse","StatusCodes","defaultTitle","jsonapiErrorHandler","_request","tsJapi","serializer","HttpError","message","statusCode","title","getReasonPhrase","jsonapi_error_handler_default","defaultType","problemErrorHandler","stack","expose","type","problem_error_handler_default","onError","errorHandlers","showTrace","request","apiFormat","errorHandler","handler","regex","onNoMatch","routes","uniqueMethods","route","createHttpError","exceptions","normalizeHeaderKey","key","canonical","lowerCaseKey","text","defaults","httpHeaderNormalizerMiddleware","options_","options","_","next","rawHeaders","normalizedKey","http_header_normalizer_default","hasJsonStructure","data","result","has_json_structure_default","xmlTransformer","toXML","xml_default","contentTypeKey","serialize","serializers","types","accepts","serializedData","breakTypes","yaml_default","toHeaderCase","serialize_default","log","debug","serializersMiddleware","defaultContentType","oldSend","oldEnd","arguments_","serializers_middleware_default","createNodeRouter","NodeRouter","create_node_router_default","corsMiddleware","expressWrapper","cors","cors_middleware_default","getIP","rateLimiterMiddleware","rateLimiter","ip","limiter","mergedHeaders","rate_limiter_middleware_default"],"mappings":"oyCAKO,IAAMA,CAAAA,CAAkB,CAACC,CAAAA,CAA0BC,CAAAA,GAAyB,CAC/E,IAAMC,CAAAA,CAAoED,CAAAA,CAAoB,SAAW,EAAC,CAE1G,MAAA,CAAO,IAAA,CAAKC,CAAO,CAAA,C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AI,CACA,IAAMoD,EAAU,MAAMF,CAAAA,CAAY,OAAA,CAAQC,CAAE,CAAA,CAEtCE,CAAAA,CAA6C,CAC/C,aAAA,CAAe,KAAK,KAAA,CAAMD,CAAAA,CAAQ,YAAA,CAAe,GAAI,CAAA,EAAK,CAAA,CAC1D,uBAAA,CAAyBA,CAAAA,CAAQ,gBACjC,mBAAA,CAAqB,IAAI,IAAA,CAAK,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAQ,YAAY,CAAA,CAAE,WAAA,EAAY,CAC7E,GAAGvF,CACP,CAAA,CAEA,MAAA,CAAO,IAAA,CAAKwF,CAAa,CAAA,CAAE,OAAA,CAASlD,CAAAA,EAAQ,CACxCxC,CAAAA,CAAS,SAAA,CAAUwC,CAAAA,CAAKkD,CAAAA,CAAclD,CAAG,CAAgB,EAC7D,CAAC,CAAA,CAED,MAAMS,CAAAA,GACV,CAAA,KAAQ,CACJ,MAAMZ,CAAAA,CAAgB,GAAA,CAAK,mBAAmB,CAClD,CACJ,CAAA,CAEDsD,EAAAA,CAAQL","file":"index-server.mjs","sourcesContent":["import type { ServerResponse } from \"node:http\";\n\nimport type { HttpError } from \"http-errors\";\nimport { StatusCodes } from \"http-status-codes\";\n\nexport const setErrorHeaders = (response: ServerResponse, error: unknown): void => {\n const headers: Record<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\n if ((error as HttpError).statusCode !== undefined) {\n response.statusCode = (error as HttpError).statusCode;\n }\n\n // respect err.status\n\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\";\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 { message, statusCode, title } = error;\n\n sendJson(response, {\n errors: [\n {\n code: statusCode,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n // eslint-disable-next-line perfectionist/sort-objects\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 // eslint-disable-next-line perfectionist/sort-objects\n detail: message,\n },\n ],\n });\n }\n};\n\nexport default jsonapiErrorHandler;\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/**\n * Normalizes errors according to the API Problem spec (RFC 7807).\n * @see https://tools.ietf.org/html/rfc7807\n */\nconst problemErrorHandler: ErrorHandler = (error: Error | HttpError, _request, response) => {\n const { message, stack } = error;\n\n if (error instanceof HttpError) {\n const { expose, statusCode, title, type } = error;\n\n response.statusCode = statusCode;\n\n setErrorHeaders(response, error);\n\n sendJson(response, {\n type: type || defaultType,\n // eslint-disable-next-line perfectionist/sort-objects\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n // eslint-disable-next-line perfectionist/sort-objects\n details: message,\n ...expose ? { trace: stack } : {},\n });\n } else {\n addStatusCodeToResponse(response, error);\n\n sendJson(response, {\n type: defaultType,\n // eslint-disable-next-line perfectionist/sort-objects\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n // eslint-disable-next-line perfectionist/sort-objects\n details: message,\n ...(error as Error & { expose: boolean }).expose ? { trace: stack } : {},\n });\n }\n};\n\nexport default problemErrorHandler;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { FunctionLike, Nextable, Route, ValueOrPromise } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\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\nexport const onError\n = <Request extends IncomingMessage, Response extends ServerResponse>(errorHandlers: ErrorHandlers, showTrace: boolean) =>\n 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-loops/no-loops\n for (const { handler, regex } 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 type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\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: string) => 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 - `rawHeaders` is not a property of `Request`\n request.rawHeaders = rawHeaders;\n\n return next();\n };\n};\n\nexport default httpHeaderNormalizerMiddleware;\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 { toXML } from \"jstoxml\";\n\nimport type { Serializer } from \"../types\";\n\nconst xmlTransformer: Serializer = (data?: XmlElement | XmlElement[]) =>\n toXML(data, {\n header: true,\n indent: \" \",\n });\n\nexport default xmlTransformer;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport accepts from \"accepts\";\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\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\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 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","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport debug from \"debug\";\nimport type { NextApiResponse } from \"next/types\";\n\nimport type { Serializers } from \"../../serializers\";\nimport { serialize } from \"../../serializers\";\n\nconst log = debug(\"api-platform:connect:serializers-middleware\");\n\nconst serializersMiddleware\n = (serializers: Serializers = [], defaultContentType = \"application/json; charset=utf-8\") =>\n async <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: NextApiResponse | Response,\n next: NextHandler,\n ): 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 (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 TS2322: Type\n (response as 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 return response.end(data, ...arguments_);\n };\n }\n\n return next();\n };\n\nexport default serializersMiddleware;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { NodeRouter } from \"@visulima/connect\";\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 errorHandlers?: ErrorHandlers;\n middlewares?: {\n \"http-header-normalizer\"?: { canonical?: boolean; normalizeHeaderKey?: (key: string, canonical: boolean) => string };\n serializers?: {\n defaultContentType?: string;\n serializers?: Serializers;\n };\n };\n showTrace?: boolean;\n } = {},\n): NodeRouter<Request, Response, Schema> => {\n const router = new NodeRouter<Request, Response, Schema>({\n onError: onError(options.errorHandlers ?? [], options.showTrace ?? false),\n onNoMatch,\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 { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { expressWrapper } from \"@visulima/connect\";\nimport type { CorsOptions, CorsOptionsDelegate } from \"cors\";\nimport cors from \"cors\";\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nconst corsMiddleware = <Request extends IncomingMessage, Response extends ServerResponse>(options?: CorsOptions | CorsOptionsDelegate) =>\n expressWrapper<Request, Response>(cors(options));\n\nexport default corsMiddleware;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { NextHandler } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { NextApiResponse } from \"next/types\";\nimport type { RateLimiterAbstract, RateLimiterRes } from \"rate-limiter-flexible\";\n\nconst getIP: (request: IncomingMessage & { ip?: string }) => string | undefined = (request) =>\n request.ip\n ?? (request.headers[\"x-forwarded-for\"] as string | undefined)\n ?? (request.headers[\"x-real-ip\"] as string | undefined)\n ?? request.socket.remoteAddress;\n\ntype HeaderValue = ReadonlyArray<string> | number | string;\n\nconst rateLimiterMiddleware\n = (rateLimiter: RateLimiterAbstract, headers?: (limiterResponse: RateLimiterRes) => Record<string, HeaderValue>) =>\n async <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: NextApiResponse | Response,\n next: NextHandler,\n ): 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: Record<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"]}
1
+ {"version":3,"sources":["../src/error-handler/utils.ts","../src/error-handler/jsonapi-error-handler.ts","../src/error-handler/problem-error-handler.ts","../src/connect/handler.ts","../src/connect/middleware/http-header-normalizer.ts","../src/serializers/has-json-structure.ts","../src/serializers/transformer/xml.ts","../src/serializers/serialize.ts","../src/connect/middleware/serializers-middleware.ts","../src/connect/create-node-router.ts","../src/connect/middleware/cors-middleware.ts","../src/connect/middleware/rate-limiter-middleware.ts"],"names":["setErrorHeaders","response","error","headers","header","sendJson","jsonBody","addStatusCodeToResponse","StatusCodes","defaultTitle","jsonapiErrorHandler","_request","tsJapi","serializer","HttpError","message","statusCode","title","getReasonPhrase","jsonapi_error_handler_default","defaultType","problemErrorHandler","stack","expose","type","problem_error_handler_default","onError","errorHandlers","showTrace","request","apiFormat","errorHandler","handler","regex","onNoMatch","routes","uniqueMethods","route","createHttpError","exceptions","normalizeHeaderKey","key","canonical","lowerCaseKey","text","defaults","httpHeaderNormalizerMiddleware","options_","options","_","next","rawHeaders","normalizedKey","http_header_normalizer_default","hasJsonStructure","data","result","has_json_structure_default","xmlTransformer","toXML","xml_default","contentTypeKey","serialize","serializers","types","accepts","serializedData","breakTypes","yaml_default","toHeaderCase","serialize_default","log","debug","serializersMiddleware","defaultContentType","oldSend","oldEnd","arguments_","serializers_middleware_default","createNodeRouter","NodeRouter","create_node_router_default","corsMiddleware","expressWrapper","cors","cors_middleware_default","getIP","rateLimiterMiddleware","rateLimiter","ip","limiter","mergedHeaders","rate_limiter_middleware_default"],"mappings":"oyCAKO,IAAMA,CAAAA,CAAkB,CAACC,CAAAA,CAA0BC,CAAAA,GAAyB,CAC/E,IAAMC,CAAAA,CAAoED,CAAAA,CAAoB,SAAW,EAAC,CAE1G,MAAA,CAAO,IAAA,CAAKC,CAAO,CAAA,CAAE,OAAA,CAASC,CAAAA,EAAmB,CAC7CH,CAAAA,CAAS,SAAA,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AE,CAAA,CAEtCE,CAAAA,CAA6C,CAC/C,aAAA,CAAe,KAAK,KAAA,CAAMD,CAAAA,CAAQ,YAAA,CAAe,GAAI,CAAA,EAAK,CAAA,CAC1D,uBAAA,CAAyBA,CAAAA,CAAQ,gBACjC,mBAAA,CAAqB,IAAI,IAAA,CAAK,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAQ,YAAY,CAAA,CAAE,WAAA,EAAY,CAC7E,GAAGvF,CACP,CAAA,CAEA,MAAA,CAAO,IAAA,CAAKwF,CAAa,CAAA,CAAE,OAAA,CAASlD,CAAAA,EAAQ,CACxCxC,CAAAA,CAAS,SAAA,CAAUwC,CAAAA,CAAKkD,CAAAA,CAAclD,CAAG,CAAgB,EAC7D,CAAC,CAAA,CAED,MAAMS,CAAAA,GACV,CAAA,KAAQ,CACJ,MAAMZ,CAAAA,CAAgB,GAAA,CAAK,mBAAmB,CAClD,CACJ,CAAA,CAEDsD,EAAAA,CAAQL","file":"index-server.mjs","sourcesContent":["import type { ServerResponse } from \"node:http\";\n\nimport type { HttpError } from \"http-errors\";\nimport { StatusCodes } from \"http-status-codes\";\n\nexport const setErrorHeaders = (response: ServerResponse, error: unknown): void => {\n const headers: Record<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\n if ((error as HttpError).statusCode !== undefined) {\n response.statusCode = (error as HttpError).statusCode;\n }\n\n // respect err.status\n\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\";\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 { message, statusCode, title } = error;\n\n sendJson(response, {\n errors: [\n {\n code: statusCode,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n // eslint-disable-next-line perfectionist/sort-objects\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 // eslint-disable-next-line perfectionist/sort-objects\n detail: message,\n },\n ],\n });\n }\n};\n\nexport default jsonapiErrorHandler;\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/**\n * Normalizes errors according to the API Problem spec (RFC 7807).\n * @see https://tools.ietf.org/html/rfc7807\n */\nconst problemErrorHandler: ErrorHandler = (error: Error | HttpError, _request, response) => {\n const { message, stack } = error;\n\n if (error instanceof HttpError) {\n const { expose, statusCode, title, type } = error;\n\n response.statusCode = statusCode;\n\n setErrorHeaders(response, error);\n\n sendJson(response, {\n type: type || defaultType,\n // eslint-disable-next-line perfectionist/sort-objects\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n // eslint-disable-next-line perfectionist/sort-objects\n details: message,\n ...expose ? { trace: stack } : {},\n });\n } else {\n addStatusCodeToResponse(response, error);\n\n sendJson(response, {\n type: defaultType,\n // eslint-disable-next-line perfectionist/sort-objects\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n // eslint-disable-next-line perfectionist/sort-objects\n details: message,\n ...(error as Error & { expose: boolean }).expose ? { trace: stack } : {},\n });\n }\n};\n\nexport default problemErrorHandler;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { FunctionLike, Nextable, Route, ValueOrPromise } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\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\nexport const onError\n = <Request extends IncomingMessage, Response extends ServerResponse>(errorHandlers: ErrorHandlers, showTrace: boolean) =>\n 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-loops/no-loops\n for (const { handler, regex } 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 type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\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: string) => 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 - `rawHeaders` is not a property of `Request`\n request.rawHeaders = rawHeaders;\n\n return next();\n };\n};\n\nexport default httpHeaderNormalizerMiddleware;\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 { toXML } from \"jstoxml\";\n\nimport type { Serializer } from \"../types\";\n\nconst xmlTransformer: Serializer = (data?: XmlElement | XmlElement[]) =>\n toXML(data, {\n header: true,\n indent: \" \",\n });\n\nexport default xmlTransformer;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport accepts from \"accepts\";\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\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): 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 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","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport debug from \"debug\";\nimport type { NextApiResponse } from \"next/types\";\n\nimport type { Serializers } from \"../../serializers\";\nimport { serialize } from \"../../serializers\";\n\nconst log = debug(\"api-platform:connect:serializers-middleware\");\n\nconst serializersMiddleware\n = (serializers: Serializers = [], defaultContentType = \"application/json; charset=utf-8\") =>\n async <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: NextApiResponse | Response,\n next: NextHandler,\n ): 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 (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 TS2322: Type\n (response as 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 return response.end(data, ...arguments_);\n };\n }\n\n return next();\n };\n\nexport default serializersMiddleware;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { NodeRouter } from \"@visulima/connect\";\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 errorHandlers?: ErrorHandlers;\n middlewares?: {\n \"http-header-normalizer\"?: { canonical?: boolean; normalizeHeaderKey?: (key: string, canonical: boolean) => string };\n serializers?: {\n defaultContentType?: string;\n serializers?: Serializers;\n };\n };\n showTrace?: boolean;\n } = {},\n): NodeRouter<Request, Response, Schema> => {\n const router = new NodeRouter<Request, Response, Schema>({\n onError: onError(options.errorHandlers ?? [], options.showTrace ?? false),\n onNoMatch,\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 { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { expressWrapper } from \"@visulima/connect\";\nimport type { CorsOptions, CorsOptionsDelegate } from \"cors\";\nimport cors from \"cors\";\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nconst corsMiddleware = <Request extends IncomingMessage, Response extends ServerResponse>(options?: CorsOptions | CorsOptionsDelegate) =>\n expressWrapper<Request, Response>(cors(options));\n\nexport default corsMiddleware;\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { NextHandler } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { NextApiResponse } from \"next/types\";\nimport type { RateLimiterAbstract, RateLimiterRes } from \"rate-limiter-flexible\";\n\nconst getIP: (request: IncomingMessage & { ip?: string }) => string | undefined = (request) =>\n request.ip\n ?? (request.headers[\"x-forwarded-for\"] as string | undefined)\n ?? (request.headers[\"x-real-ip\"] as string | undefined)\n ?? request.socket.remoteAddress;\n\ntype HeaderValue = ReadonlyArray<string> | number | string;\n\nconst rateLimiterMiddleware\n = (rateLimiter: RateLimiterAbstract, headers?: (limiterResponse: RateLimiterRes) => Record<string, HeaderValue>) =>\n async <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: NextApiResponse | Response,\n next: NextHandler,\n ): 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: Record<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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/api-platform",
3
- "version": "3.0.55",
3
+ "version": "3.0.56",
4
4
  "description": "Visulima API platform is a set of tools to build and consume web APIs",
5
5
  "keywords": [
6
6
  "anolilab",
@@ -125,10 +125,10 @@
125
125
  "LICENSE.md"
126
126
  ],
127
127
  "dependencies": {
128
- "@visulima/connect": "3.0.24",
129
- "@visulima/fs": "4.0.3",
130
- "@visulima/jsdoc-open-api": "2.0.91",
131
- "@visulima/path": "2.0.2",
128
+ "@visulima/connect": "3.0.25",
129
+ "@visulima/fs": "4.0.4",
130
+ "@visulima/jsdoc-open-api": "2.0.92",
131
+ "@visulima/path": "2.0.3",
132
132
  "accepts": "^1.3.8",
133
133
  "debug": "^4.4.3",
134
134
  "http-errors": "^2.0.0",
@@ -143,8 +143,7 @@
143
143
  "peerDependencies": {
144
144
  "@hapi/hapi": "^21.4.3",
145
145
  "@koa/router": "^12.0.1",
146
- "@visulima/crud": "2.0.43",
147
- "@visulima/readdir": "2.0.12",
146
+ "@visulima/crud": "2.0.44",
148
147
  "chalk": "5.6.2",
149
148
  "commander": "^12.1.0",
150
149
  "cors": "^2.8.5",
@@ -171,9 +170,6 @@
171
170
  "@visulima/crud": {
172
171
  "optional": true
173
172
  },
174
- "@visulima/readdir": {
175
- "optional": true
176
- },
177
173
  "chalk": {
178
174
  "optional": true
179
175
  },
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../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/utils.ts","../src/framework/cli/command/list/routes/next/collect-api-route-files.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","../src/framework/cli/command/list/list-command.ts"],"names":["mapKeysToPath","layerRegexPath","keys","convertedSubPath","key","map_keys_to_path_default","pathRegexParser","mappedPath","match","path_regex_parser_default","parseRouteLayer","layer","basePath","lastRequestHandler","pathParameters","filtered","element","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","extensionRegex","apiRouteFileParser","apiRouteFile","cwd","verbose","toNamespacedPath","cwdPath","nodeCwd","specs","parsedJsDocumentFile","parseFile","jsDocumentCommentsToOpenApi","parsedSwaggerJsDocumentFile","swaggerJsDocumentCommentsToOpenApi","readFileSync","spec","pathSpec","methodSpec","api_route_file_parser_default","ALLOWED_EXTENSIONS","getAppWorkingDirectoryPath","appFilePath","lastParsedPath","parse","readdirSync","getFrameworkName","directory","packageJSONFilePath","dependencies","getApp","appExport","frameworkName","isDirectory","statSync","collectApiRouteFiles","apiFolderPath","join","collect","collect_api_route_files_default","getRoutes","appOrPath","apiRouteFiles","routesGroupBy","list","keyGetter","map","collection","routes_group_by_default","renderRoute","routePath","colorMap","chalk","methodText","coloredMethod","spacesCount","dotsCount","dots","routeText","routesRender","routesMap","options","routes_render_default","listCommand","framework","frameworkPath","process","existsSync","appWorkingDirectoryPath","extname","environmentFilePath","isTypeScriptApp","tscPath","execSync","error","rmSync","appJsFilePath","defaultExport","ipath","epath","groupedMap","counter","groupedRoutes","renderedRoute","list_command_default"],"mappings":"+WAQA,IAAMA,CAAAA,CAAgB,CAACC,CAAAA,CAA8BC,CAAAA,GAAwB,CACzE,GAAIA,CAAAA,CAAK,SAAW,CAAA,CAChB,MAAM,IA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ys/path variables to the regex inside a given path\n * @param layerRegexPath The regex for a router with path parameters\n * @param keys The keys that represent the path parameters\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.length === 0) {\n throw new Error(\"must include at least 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(String.raw`(?:([^\\/]+?))`, `:${key.name}`);\n });\n\n return convertedSubPath\n .replace(String.raw`/?(?=\\/|$)/i`, \"\")\n .replace(\"/^\", \"\")\n .replaceAll(\"\\\\\", \"\")\n .replaceAll(/\\/{2,}/gu, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types\";\n\n/**\n * Parses an express layer's regex and converts it to the original format seen in code.\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.length > 0) {\n mappedPath = mapKeysToPath(layerRegexPath, keys);\n }\n\n const match = /^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//u.exec(\n layerRegexPath.toString().replace(String.raw`\\/?`, \"\").replace(String.raw`(?=\\/|$)`, \"$\"),\n ) as string[];\n\n if (Array.isArray(match) && match.length > 1) {\n return (match[1] as string).replaceAll(/\\\\(.)/gu, \"$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","import type { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport type { Key, Layer, Parameter, Route, RouteMetaData } from \"./types\";\n\n/**\n * Parses a route object. Route objects are the leafs of an express router tree\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: Required<Layer>, keys: Key[], basePath: string): RouteMetaData => {\n const lastRequestHandler = layer.route.stack.at(-1) as Layer;\n const pathParameters: Parameter[] = keys.map((key) => {\n return { in: \"path\", name: key.name, required: !key.optional };\n });\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).replaceAll(/\\/{2,}/gu, \"/\");\n\n if (filtered.length === 0) {\n return { method: lastRequestHandler.method, path, pathParams: pathParameters };\n }\n\n return {\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\n method: lastRequestHandler.method,\n path,\n pathParams: pathParameters,\n };\n};\n\n/**\n * Recursive traversal method for the express router and middleware tree.\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?.stack !== undefined) {\n for (const l of layer.handle.stack) {\n // eslint-disable-next-line no-param-reassign\n path = path || \"\";\n\n traverse(routes, `${path}/${pathRegexParser(layer.regexp, layer.keys)}`, l as Layer, keys);\n }\n }\n\n if (!layer.route || layer.route.stack.length === 0) {\n return;\n }\n\n routes.push(parseRouteLayer(layer as Required<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 * @param app The Express app reference. Must be used after all routes have been attached\n * @returns List of routes for this express app with meta-data that has been picked up\n */\nconst expressPathParser = (app: Express): RouteMetaData[] => {\n // eslint-disable-next-line no-underscore-dangle\n const router: Router = app._router || app.router;\n const routes: RouteMetaData[] = [];\n\n for (const layer of router.stack) {\n // @TODO: revisit this type assertion\n traverse(routes, \"\", layer as unknown as Layer, []);\n }\n\n return routes;\n};\n\nexport default expressPathParser;\n","import 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 file: \"unknown\",\n method: route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","import type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replaceAll(/ \\(.*\\)/gu, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ninterface Segment {\n depth: number;\n index: number;\n isRoute: boolean;\n methods: string[] | null;\n segment: string;\n}\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replaceAll(/[─│└├]/gu, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\n // eslint-disable-next-line unicorn/no-array-reduce\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.at(-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.replaceAll(/ \\(.*\\)/gu, \"\").match(/ /gu);\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 depth,\n index,\n isRoute,\n methods,\n segment,\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 file: \"unknown\",\n method: method.toUpperCase(),\n path: route,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","import type { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error TS2339: Property '_core' does not exist on type 'Server'. Internal API.\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 file: \"unknown\",\n method: route.route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","import type 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\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n file: \"unknown\",\n method: route.methods.join(\"|\").toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import { readFileSync } from \"node:fs\";\nimport { cwd as nodeCwd } from \"node:process\";\n\nimport type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\nimport { toNamespacedPath } from \"@visulima/path\";\n\nimport type { Route } from \"../types\";\n\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/u;\n\nconst apiRouteFileParser = (apiRouteFile: string, cwd: string, verbose = false): Route[] => {\n // eslint-disable-next-line no-param-reassign\n apiRouteFile = toNamespacedPath(apiRouteFile);\n\n const cwdPath = toNamespacedPath(nodeCwd());\n\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/u).forEach((line) => {\n const match = /[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/u.exec(line);\n\n if (match) {\n let [, method] = match;\n\n if (method === \"GET\") {\n method = \"GET|HEAD\";\n }\n\n routes.push({\n file: apiRouteFile.replace(`${cwdPath}/`, \"\"),\n method: method as string,\n path: toNamespacedPath(apiRouteFile.replace(cwd, \"\").replace(extensionRegex, \"\")),\n tags: [],\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n file: apiRouteFile.replace(`${cwdPath}/`, \"\"),\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: toNamespacedPath(apiRouteFile.replace(cwd, \"\").replace(extensionRegex, \"\")),\n tags: [],\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 file: apiRouteFile.replace(`${cwdPath}/`, \"\"),\n method: method.toUpperCase(),\n path: toNamespacedPath(path),\n tags: methodSpec.tags,\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","import { readdirSync, readFileSync } from \"node:fs\";\n\nimport { parse } from \"@visulima/path\";\nimport type { PackageJson } from \"type-fest\";\n\ninterface AppExport {\n [key: string]: any;\n app?: string | { app?: string };\n}\n\nexport const ALLOWED_EXTENSIONS = [\".js\", \".ts\", \".mjs\", \".cjs\"];\n\nexport const getAppWorkingDirectoryPath = (appFilePath: string): string | null => {\n let lastParsedPath = parse(appFilePath);\n\n // Once the following condition returns false it means we traversed the whole file system\n // eslint-disable-next-line no-loops/no-loops\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): \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null => {\n const packageJSONFilePath = `${directory}/package.json`;\n\n const { dependencies } = JSON.parse(readFileSync(packageJSONFilePath).toString()) as 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: AppExport, frameworkName: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null): AppExport | string | null => {\n const isExportEmpty = Object.keys(appExport).length === 0;\n\n if (isExportEmpty) {\n return null;\n }\n\n if (frameworkName === \"hapi\") {\n if (typeof (appExport.app as { app?: string }).app === \"string\") {\n return appExport.app as { app: string };\n }\n\n return appExport;\n }\n\n return appExport.app ?? appExport;\n};\n","import { statSync } from \"node:fs\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/fs\";\nimport { join } from \"@visulima/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 = \"\"): 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 });\n};\n\nexport default collectApiRouteFiles;\n","import type { Server } from \"@hapi/hapi\";\nimport type { Express } from \"express\";\nimport type { FastifyInstance } from \"fastify\";\nimport type 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\";\n\nexport type FrameworkName = \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | \"unknown\";\nexport const getRoutes = async (\n appOrPath: Express | FastifyInstance | Koa | Server | string,\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);\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<string, Route[]>();\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","import chalk from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n ANY: chalk.redBright,\n DELETE: chalk.redBright,\n GET: chalk.blue,\n HEAD: chalk.hex(\"#6C7280\"),\n OPTIONS: chalk.hex(\"#6C7280\"),\n PATCH: chalk.yellow,\n POST: chalk.yellow,\n PUT: chalk.yellow,\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${chalk.blue(\"GET\")}${chalk.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${chalk.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 ? chalk.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${chalk.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[] } = {}): (string | undefined)[] =>\n 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","import { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport { extname, join } from \"@visulima/path\";\nimport chalk from \"chalk\";\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\";\nimport { ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName } from \"./utils\";\n\ninterface RenderOptions {\n excludePaths: string[];\n group: string;\n includePaths: string[];\n methods: string[];\n verbose: boolean;\n}\n\nconst listCommand = async (\n framework: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | undefined,\n path: string,\n options: Partial<RenderOptions> = {},\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Promise<void> => {\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: Route[] | null = 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 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 as string) ? 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\n // eslint-disable-next-line no-console\n console.log(dots + chalk.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 ${chalk.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../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/utils.ts","../src/framework/cli/command/list/routes/next/collect-api-route-files.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","../src/framework/cli/command/list/list-command.ts"],"names":["mapKeysToPath","layerRegexPath","keys","convertedSubPath","key","map_keys_to_path_default","pathRegexParser","mappedPath","match","path_regex_parser_default","parseRouteLayer","layer","basePath","lastRequestHandler","pathParameters","filtered","element","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","extensionRegex","apiRouteFileParser","apiRouteFile","cwd","verbose","toNamespacedPath","cwdPath","nodeCwd","specs","parsedJsDocumentFile","parseFile","jsDocumentCommentsToOpenApi","parsedSwaggerJsDocumentFile","swaggerJsDocumentCommentsToOpenApi","readFileSync","spec","pathSpec","methodSpec","api_route_file_parser_default","ALLOWED_EXTENSIONS","getAppWorkingDirectoryPath","appFilePath","lastParsedPath","parse","readdirSync","getFrameworkName","directory","packageJSONFilePath","dependencies","getApp","appExport","frameworkName","isDirectory","statSync","collectApiRouteFiles","apiFolderPath","join","collect","collect_api_route_files_default","getRoutes","appOrPath","apiRouteFiles","routesGroupBy","list","keyGetter","map","collection","routes_group_by_default","renderRoute","routePath","colorMap","chalk","methodText","coloredMethod","spacesCount","dotsCount","dots","routeText","routesRender","routesMap","options","routes_render_default","listCommand","framework","frameworkPath","process","existsSync","appWorkingDirectoryPath","extname","environmentFilePath","isTypeScriptApp","tscPath","execSync","error","rmSync","appJsFilePath","defaultExport","ipath","epath","groupedMap","counter","groupedRoutes","renderedRoute","list_command_default"],"mappings":"6XAQA,IAAMA,CAAAA,CAAgB,CAACC,CAAAA,CAA8BC,CAAAA,GAAwB,CACzE,GAAIA,CAAAA,CAAK,SAAW,CAAA,CAChB,MAAM,IAAI,KAAA,CAAM,sCAAsC,CAAA,CAG1D,IAAIC,CAAAA,CAAmBF,CAAAA,CAAe,QAAA,EAAS,CAE/C,OAAAC,CAAAA,CAAK,QAASE,CAAAA,EAAQ,CAClBD,CAAAA,CAAmBC,CAAAA,CAAI,QAAA,CACjBD,CAAAA,CAAiB,QAAQ,sBAAA,CAAwB,CAAA,EAAA,EAAKC,EAAI,IAAI,CAAA,CAAA,CAAG,EACjED,CAAAA,CAAiB,OAAA,CAAQ,MAAA,CAAO,GAAA,CAAA,aAAA,CAAA,CAAoB,CAAA,CAAA,EAAIC,CAAAA,CAAI,IAAI,CAAA,CAAE,EAC5E,CAAC,CAAA,CAEMD,CAAAA,CACF,OAAA,CAAQ,OAAO,GAAA,CAAA,YAAA,CAAA,CAAmB,EAAE,CAAA,CACpC,OAAA,CAAQ,IAAA,CAAM,EAAE,EAChB,UAAA,CAAW,IAAA,CAAM,EAAE,CAAA,CACnB,UA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A,CAE5CgH,CAAAA,CAAaoB,EAAerB,CAAO,CAAA,CAAE,OAAA,CAASsB,CAAAA,EAAkB,CAE5D,OAAA,CAAQ,GAAA,CAAIA,CAAa,EAC7B,CAAC,CAAA,CAEDF,CAAAA,EAAW,EACf,CAAC,EACL,CAAA,KAEI,OAAA,CAAQ,GAAA,EAAI,CAEZnB,CAAAA,CAAajG,CAAAA,CAAQgG,CAAO,CAAA,CAAE,OAAA,CAASsB,CAAAA,EAAkB,CAErD,OAAA,CAAQ,GAAA,CAAIA,CAAa,EAC7B,CAAC,CAAA,CAIL,QAAQ,GAAA,CAAI;AAAA,SAAA,EAAc/B,kBAAAA,CAAM,WAAA,CAAY,MAAA,CAAOvF,CAAAA,CAAO,MAAM,CAAC,CAAC,CAAA,MAAA,EAASA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAI,OAAA,CAAU,QAAQ,CAAA;AAAA,CAAK,EAC5H,EAEOuH,EAAAA,CAAQrB","file":"chunk-LZE2IIIV.js","sourcesContent":["import type { ExpressRegex, Key } from \"./types\";\n\n/**\n * Map's the keys/path variables to the regex inside a given path\n * @param layerRegexPath The regex for a router with path parameters\n * @param keys The keys that represent the path parameters\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.length === 0) {\n throw new Error(\"must include at least 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(String.raw`(?:([^\\/]+?))`, `:${key.name}`);\n });\n\n return convertedSubPath\n .replace(String.raw`/?(?=\\/|$)/i`, \"\")\n .replace(\"/^\", \"\")\n .replaceAll(\"\\\\\", \"\")\n .replaceAll(/\\/{2,}/gu, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types\";\n\n/**\n * Parses an express layer's regex and converts it to the original format seen in code.\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.length > 0) {\n mappedPath = mapKeysToPath(layerRegexPath, keys);\n }\n\n const match = /^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//u.exec(\n layerRegexPath.toString().replace(String.raw`\\/?`, \"\").replace(String.raw`(?=\\/|$)`, \"$\"),\n ) as string[];\n\n if (Array.isArray(match) && match.length > 1) {\n return (match[1] as string).replaceAll(/\\\\(.)/gu, \"$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","import type { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport type { Key, Layer, Parameter, Route, RouteMetaData } from \"./types\";\n\n/**\n * Parses a route object. Route objects are the leafs of an express router tree\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: Required<Layer>, keys: Key[], basePath: string): RouteMetaData => {\n const lastRequestHandler = layer.route.stack.at(-1) as Layer;\n const pathParameters: Parameter[] = keys.map((key) => {\n return { in: \"path\", name: key.name, required: !key.optional };\n });\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).replaceAll(/\\/{2,}/gu, \"/\");\n\n if (filtered.length === 0) {\n return { method: lastRequestHandler.method, path, pathParams: pathParameters };\n }\n\n return {\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\n method: lastRequestHandler.method,\n path,\n pathParams: pathParameters,\n };\n};\n\n/**\n * Recursive traversal method for the express router and middleware tree.\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?.stack !== undefined) {\n for (const l of layer.handle.stack) {\n // eslint-disable-next-line no-param-reassign\n path = path || \"\";\n\n traverse(routes, `${path}/${pathRegexParser(layer.regexp, layer.keys)}`, l as Layer, keys);\n }\n }\n\n if (!layer.route || layer.route.stack.length === 0) {\n return;\n }\n\n routes.push(parseRouteLayer(layer as Required<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 * @param app The Express app reference. Must be used after all routes have been attached\n * @returns List of routes for this express app with meta-data that has been picked up\n */\nconst expressPathParser = (app: Express): RouteMetaData[] => {\n // eslint-disable-next-line no-underscore-dangle\n const router: Router = app._router || app.router;\n const routes: RouteMetaData[] = [];\n\n for (const layer of router.stack) {\n // @TODO: revisit this type assertion\n traverse(routes, \"\", layer as unknown as Layer, []);\n }\n\n return routes;\n};\n\nexport default expressPathParser;\n","import 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 file: \"unknown\",\n method: route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","import type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replaceAll(/ \\(.*\\)/gu, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ninterface Segment {\n depth: number;\n index: number;\n isRoute: boolean;\n methods: string[] | null;\n segment: string;\n}\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replaceAll(/[─│└├]/gu, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\n // eslint-disable-next-line unicorn/no-array-reduce\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.at(-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.replaceAll(/ \\(.*\\)/gu, \"\").match(/ /gu);\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 depth,\n index,\n isRoute,\n methods,\n segment,\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 file: \"unknown\",\n method: method.toUpperCase(),\n path: route,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","import type { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error TS2339: Property '_core' does not exist on type 'Server'. Internal API.\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 file: \"unknown\",\n method: route.route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","import type 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\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n file: \"unknown\",\n method: route.methods.join(\"|\").toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import { readFileSync } from \"node:fs\";\nimport { cwd as nodeCwd } from \"node:process\";\n\nimport type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\nimport { toNamespacedPath } from \"@visulima/path\";\n\nimport type { Route } from \"../types\";\n\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/u;\n\nconst apiRouteFileParser = (apiRouteFile: string, cwd: string, verbose = false): Route[] => {\n // eslint-disable-next-line no-param-reassign\n apiRouteFile = toNamespacedPath(apiRouteFile);\n\n const cwdPath = toNamespacedPath(nodeCwd());\n\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/u).forEach((line) => {\n const match = /[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/u.exec(line);\n\n if (match) {\n let [, method] = match;\n\n if (method === \"GET\") {\n method = \"GET|HEAD\";\n }\n\n routes.push({\n file: apiRouteFile.replace(`${cwdPath}/`, \"\"),\n method: method as string,\n path: toNamespacedPath(apiRouteFile.replace(cwd, \"\").replace(extensionRegex, \"\")),\n tags: [],\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n file: apiRouteFile.replace(`${cwdPath}/`, \"\"),\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: toNamespacedPath(apiRouteFile.replace(cwd, \"\").replace(extensionRegex, \"\")),\n tags: [],\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 file: apiRouteFile.replace(`${cwdPath}/`, \"\"),\n method: method.toUpperCase(),\n path: toNamespacedPath(path),\n tags: methodSpec.tags,\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","import { readdirSync, readFileSync } from \"node:fs\";\n\nimport { parse } from \"@visulima/path\";\nimport type { PackageJson } from \"type-fest\";\n\ninterface AppExport {\n [key: string]: any;\n app?: string | { app?: string };\n}\n\nexport const ALLOWED_EXTENSIONS = [\".js\", \".ts\", \".mjs\", \".cjs\"];\n\nexport const getAppWorkingDirectoryPath = (appFilePath: string): string | null => {\n let lastParsedPath = parse(appFilePath);\n\n // Once the following condition returns false it means we traversed the whole file system\n // eslint-disable-next-line no-loops/no-loops\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): \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null => {\n const packageJSONFilePath = `${directory}/package.json`;\n\n const { dependencies } = JSON.parse(readFileSync(packageJSONFilePath).toString()) as 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: AppExport, frameworkName: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null): AppExport | string | null => {\n const isExportEmpty = Object.keys(appExport).length === 0;\n\n if (isExportEmpty) {\n return null;\n }\n\n if (frameworkName === \"hapi\") {\n if (typeof (appExport.app as { app?: string }).app === \"string\") {\n return appExport.app as { app: string };\n }\n\n return appExport;\n }\n\n return appExport.app ?? appExport;\n};\n","import { statSync } from \"node:fs\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/fs\";\nimport { join } from \"@visulima/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 = \"\"): 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 });\n};\n\nexport default collectApiRouteFiles;\n","import type { Server } from \"@hapi/hapi\";\nimport type { Express } from \"express\";\nimport type { FastifyInstance } from \"fastify\";\nimport type 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\";\n\nexport type FrameworkName = \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | \"unknown\";\nexport const getRoutes = async (\n appOrPath: Express | FastifyInstance | Koa | Server | string,\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);\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<string, Route[]>();\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","import chalk from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n ANY: chalk.redBright,\n DELETE: chalk.redBright,\n GET: chalk.blue,\n HEAD: chalk.hex(\"#6C7280\"),\n OPTIONS: chalk.hex(\"#6C7280\"),\n PATCH: chalk.yellow,\n POST: chalk.yellow,\n PUT: chalk.yellow,\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${chalk.blue(\"GET\")}${chalk.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${chalk.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 ? chalk.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${chalk.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[] } = {}): (string | undefined)[] =>\n 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","import { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport { extname, join } from \"@visulima/path\";\nimport chalk from \"chalk\";\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\";\nimport { ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName } from \"./utils\";\n\ninterface RenderOptions {\n excludePaths: string[];\n group: string;\n includePaths: string[];\n methods: string[];\n verbose: boolean;\n}\n\nconst listCommand = async (\n framework: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | undefined,\n path: string,\n options: Partial<RenderOptions> = {},\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Promise<void> => {\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: Route[] | null = 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 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 as string) ? 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\n // eslint-disable-next-line no-console\n console.log(dots + chalk.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 ${chalk.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n"]}