@orion-js/http
Advanced tools
+62
-32
@@ -34,3 +34,3 @@ var __create = Object.create; | ||
| Routes: () => Routes, | ||
| bodyParser: () => bodyParser2, | ||
| bodyParser: () => bodyParser3, | ||
| createRoute: () => createRoute, | ||
@@ -43,2 +43,3 @@ express: () => import_express2.default, | ||
| onError: () => onError, | ||
| registerReplEndpoint: () => registerReplEndpoint, | ||
| registerRoute: () => registerRoute, | ||
@@ -52,2 +53,4 @@ registerRoutes: () => registerRoutes, | ||
| module.exports = __toCommonJS(index_exports); | ||
| var import_body_parser3 = __toESM(require("body-parser"), 1); | ||
| var import_express2 = __toESM(require("express"), 1); | ||
@@ -90,21 +93,30 @@ // src/errors.ts | ||
| // src/viewer.ts | ||
| var import_helpers = require("@orion-js/helpers"); | ||
| global.getViewerRef = () => null; | ||
| var getViewer = async (req) => { | ||
| try { | ||
| const viewer = await global.getViewerRef(req); | ||
| if (!viewer) return {}; | ||
| return viewer; | ||
| } catch (err) { | ||
| throw new import_helpers.UserError("AuthError", err.message); | ||
| } | ||
| }; | ||
| var setGetViewer = (getViewerFunc) => { | ||
| global.getViewerRef = getViewerFunc; | ||
| }; | ||
| // src/routes/registerRoute.ts | ||
| var import_body_parser2 = __toESM(require("body-parser"), 1); | ||
| // src/start.ts | ||
| var import_node_fs = require("fs"); | ||
| var import_env = require("@orion-js/env"); | ||
| var import_express = __toESM(require("express"), 1); | ||
| // src/repl.ts | ||
| var import_services = require("@orion-js/services"); | ||
| var import_body_parser = __toESM(require("body-parser"), 1); | ||
| function registerReplEndpoint() { | ||
| const app = getApp(); | ||
| app.post("/__repl", import_body_parser.default.json(), async (req, res) => { | ||
| try { | ||
| const { expression } = req.body; | ||
| const AsyncFunction = Object.getPrototypeOf(async () => { | ||
| }).constructor; | ||
| const fn = new AsyncFunction("getInstance", expression); | ||
| const result = await fn(import_services.getInstance); | ||
| res.json({ success: true, result }); | ||
| } catch (error) { | ||
| res.json({ success: false, error: error.message, stack: error.stack }); | ||
| } | ||
| }); | ||
| } | ||
| // src/start.ts | ||
| global.appRef = null; | ||
@@ -120,2 +132,10 @@ global.serverRef = null; | ||
| } | ||
| if (process.env.ORION_REPL) { | ||
| registerReplEndpoint(); | ||
| try { | ||
| (0, import_node_fs.mkdirSync)(".orion", { recursive: true }); | ||
| (0, import_node_fs.writeFileSync)(".orion/port", String(port)); | ||
| } catch { | ||
| } | ||
| } | ||
| return app; | ||
@@ -133,8 +153,2 @@ }; | ||
| // src/index.ts | ||
| var import_express2 = __toESM(require("express"), 1); | ||
| // src/routes/registerRoute.ts | ||
| var import_body_parser = __toESM(require("body-parser"), 1); | ||
| // src/routes/executeRequest.ts | ||
@@ -145,2 +159,20 @@ var import_env2 = require("@orion-js/env"); | ||
| var import_schema = require("@orion-js/schema"); | ||
| // src/viewer.ts | ||
| var import_helpers = require("@orion-js/helpers"); | ||
| global.getViewerRef = () => null; | ||
| var getViewer = async (req) => { | ||
| try { | ||
| const viewer = await global.getViewerRef(req); | ||
| if (!viewer) return {}; | ||
| return viewer; | ||
| } catch (err) { | ||
| throw new import_helpers.UserError("AuthError", err.message); | ||
| } | ||
| }; | ||
| var setGetViewer = (getViewerFunc) => { | ||
| global.getViewerRef = getViewerFunc; | ||
| }; | ||
| // src/routes/executeRequest.ts | ||
| var simulateLatency = (0, import_env2.internalGetEnv)("simulate_latency", "SIMULATE_LATENCY"); | ||
@@ -226,7 +258,7 @@ var simulateLatencyMs = Number.parseInt(simulateLatency, 10); | ||
| if (route2.bodyParser) { | ||
| const parser = import_body_parser.default[route2.bodyParser](route2.bodyParserOptions); | ||
| const parser = import_body_parser2.default[route2.bodyParser](route2.bodyParserOptions); | ||
| handlers.unshift(parser); | ||
| } | ||
| if (!route2.bodyParser && route2.bodyParams) { | ||
| const parser = import_body_parser.default.json(route2.bodyParserOptions); | ||
| const parser = import_body_parser2.default.json(route2.bodyParserOptions); | ||
| handlers.unshift(parser); | ||
@@ -248,5 +280,2 @@ } | ||
| // src/index.ts | ||
| var import_body_parser2 = __toESM(require("body-parser"), 1); | ||
| // src/routes/route.ts | ||
@@ -261,3 +290,3 @@ function createRoute(options) { | ||
| // src/service/index.ts | ||
| var import_services = require("@orion-js/services"); | ||
| var import_services2 = require("@orion-js/services"); | ||
| var serviceMetadata = /* @__PURE__ */ new WeakMap(); | ||
@@ -269,3 +298,3 @@ var routeMetadata = /* @__PURE__ */ new WeakMap(); | ||
| return (target, context) => { | ||
| (0, import_services.Service)()(target, context); | ||
| (0, import_services2.Service)()(target, context); | ||
| serviceMetadata.set(target, { _serviceType: "routes" }); | ||
@@ -303,3 +332,3 @@ if (Object.keys(pendingRouteEntries).length > 0) { | ||
| function getServiceRoutes(target) { | ||
| const instance = (0, import_services.getInstance)(target); | ||
| const instance = (0, import_services2.getInstance)(target); | ||
| if (!serviceMetadata.has(instance.constructor)) { | ||
@@ -318,4 +347,4 @@ throw new Error("You must pass a class decorated with @Routes to getServiceRoutes"); | ||
| // src/index.ts | ||
| var { json, raw, text, urlencoded } = import_body_parser2.default; | ||
| var bodyParser2 = { json, raw, text, urlencoded }; | ||
| var { json, raw, text, urlencoded } = import_body_parser3.default; | ||
| var bodyParser3 = { json, raw, text, urlencoded }; | ||
| // Annotate the CommonJS export names for ESM import in node: | ||
@@ -333,2 +362,3 @@ 0 && (module.exports = { | ||
| onError, | ||
| registerReplEndpoint, | ||
| registerRoute, | ||
@@ -335,0 +365,0 @@ registerRoutes, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/viewer.ts","../src/start.ts","../src/routes/registerRoute.ts","../src/routes/executeRequest.ts","../src/routes/registerRoutes.ts","../src/routes/route.ts","../src/service/index.ts"],"sourcesContent":["import {setOnError, onError} from './errors'\nimport {getViewer, setGetViewer} from './viewer'\nimport {startServer, getApp, getServer} from './start'\nimport express from 'express'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport bodyParserLib from 'body-parser'\nimport {RequestHandler} from 'express'\n\nexport * from './routes/route'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport * from './types'\nexport * from './service'\n","import crypto from 'node:crypto'\nimport {logger} from '@orion-js/logger'\nimport express from 'express'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n logger.error(`[route/handler] OrionError in ${req.path}:`, {error})\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n logger.error(`[route/handler] GraphQLError in ${req.path}:`, {error})\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.status(statusCode)\n res.json(data)\n\n error.hash = hash\n logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n return onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","import bodyParser from 'body-parser'\nimport express from 'express'\nimport {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\n\nconst appRegisteredRoutes = new WeakMap<express.Application, WeakSet<RouteType>>()\n\nfunction getRegisteredRoutes(app: express.Application) {\n if (appRegisteredRoutes.has(app)) {\n return appRegisteredRoutes.get(app)\n }\n\n const routes = new WeakSet<RouteType>()\n appRegisteredRoutes.set(app, routes)\n return routes\n}\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const registeredRoutes = getRegisteredRoutes(app)\n if (registeredRoutes.has(route)) return\n\n const method = route.method\n\n const handler: express.RequestHandler = (req, res) => {\n void executeRequest(route, req as any, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (!route.bodyParser && route.bodyParams) {\n const parser = bodyParser.json(route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n registeredRoutes.add(route)\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\nimport {runWithOrionAsyncContext, updateOrionAsyncContext} from '@orion-js/logger'\nimport {cleanAndValidate} from '@orion-js/schema'\nimport express from 'express'\nimport {onError} from '../errors'\nimport {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\n\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\nconst simulateLatencyMs = Number.parseInt(simulateLatency, 10)\nconst hasSimulateLatency = Number.isFinite(simulateLatencyMs) && simulateLatencyMs > 0\nconst latencyMinMs = hasSimulateLatency ? Math.floor(simulateLatencyMs * 0.9) : 0\nconst latencyMaxMs = hasSimulateLatency ? Math.ceil(simulateLatencyMs * 1.1) : 0\n\nconst objectToString = Object.prototype.toString\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return objectToString.call(value) === '[object Object]'\n}\n\nexport async function executeRequest(\n route: RouteType<any>,\n req: OrionRequest,\n res: express.Response,\n) {\n try {\n if (hasSimulateLatency) {\n const delay = Math.floor(Math.random() * (latencyMaxMs - latencyMinMs + 1)) + latencyMinMs\n await sleep(delay)\n }\n\n const viewer = await getViewer(req)\n\n if (route.queryParams) {\n req.query = await cleanAndValidate(route.queryParams, req.query)\n }\n\n if (route.bodyParams) {\n req.body = await cleanAndValidate(route.bodyParams, req.body)\n }\n\n const context = {\n controllerType: 'route' as const,\n routeName: route.path,\n pathname: req.path,\n viewer,\n params: {\n body: req.body,\n query: req.query,\n params: req.params,\n },\n }\n\n const result = await runWithOrionAsyncContext(context, () => {\n updateOrionAsyncContext({viewer})\n return route.resolve(req, res, viewer)\n })\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n res.set(result.headers)\n }\n\n // add body to response\n if (result.body !== null && result.body !== undefined) {\n let body = result.body\n\n if (route.returns) {\n body = await cleanAndValidate(route.returns, result.body)\n }\n\n if (isPlainObject(body)) {\n res.json(body)\n } else {\n res.send(body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import {RoutesMap} from '../types'\nimport registerRoute from './registerRoute'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n for (const routeName in routesMap) {\n registerRoute(routesMap[routeName])\n }\n}\n","import {Schema, SchemaFieldType} from '@orion-js/schema'\nimport {RouteType, OrionRouteOptions} from '../types'\n\nexport function createRoute<\n TPath extends string,\n TQueryParamsSchema extends Schema | undefined,\n TBodyParamsSchema extends Schema | undefined,\n TReturnsSchema extends SchemaFieldType | undefined,\n>(\n options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>,\n): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema> {\n return {\n ...options,\n }\n}\n\n/**\n * @deprecated Use createRoute instead\n */\nexport const route = createRoute\n","import {getInstance, Service} from '@orion-js/services'\nimport {createRoute} from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\nconst routeEntriesByClass = new Map<Function, Record<string, (instance: any) => any>>()\nlet pendingRouteEntries: Record<string, (instance: any) => any> = {}\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'routes'})\n\n if (Object.keys(pendingRouteEntries).length > 0) {\n routeEntriesByClass.set(target, pendingRouteEntries)\n pendingRouteEntries = {}\n }\n }\n}\n\nexport function Route(): (method: any, context: ClassFieldDecoratorContext) => any\nexport function Route(\n options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>,\n): (method: any, context: ClassMethodDecoratorContext) => any\nexport function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>) {\n return (method: any, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext) => {\n const propertyKey = String(context.name)\n\n if (context.kind === 'method') {\n pendingRouteEntries[propertyKey] = (instance: any) =>\n createRoute({\n ...options,\n resolve: instance[propertyKey].bind(instance),\n })\n }\n\n if (context.kind === 'field') {\n pendingRouteEntries[propertyKey] = (instance: any) => instance[propertyKey]\n }\n\n return method\n }\n}\n\nfunction initializeRoutesIfNeeded(instance: any) {\n if (routeMetadata.has(instance)) return\n const entries = routeEntriesByClass.get(instance.constructor) || {}\n const routes: Record<string, any> = {}\n for (const [key, setup] of Object.entries(entries)) {\n routes[key] = setup(instance)\n }\n routeMetadata.set(instance, routes)\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n initializeRoutesIfNeeded(instance)\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAAA;AAAA,EAAA;AAAA,iCAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAmB;AACnB,oBAAqB;AAKrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,2BAAO,MAAM,iCAAiC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,IACpE;AAEA,UAAM,OAAO,MAAM,QAAQ;AAE3B,QAAI,OAAO,UAAU;AACrB,QAAI,KAAK,IAAI;AAAA,EACf,WAAW,MAAM,gBAAgB;AAC/B,QAAI,UAAU,MAAM,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EvC,QAAI,QAAQ,SAAS,UAAU;AAC7B,0BAAoB,WAAW,IAAI,CAAC,aAClC,YAAY;AAAA,QACV,GAAG;AAAA,QACH,SAAS,SAAS,WAAW,EAAE,KAAK,QAAQ;AAAA,MAC9C,CAAC;AAAA,IACL;AAEA,QAAI,QAAQ,SAAS,SAAS;AAC5B,0BAAoB,WAAW,IAAI,CAAC,aAAkB,SAAS,WAAW;AAAA,IAC5E;AAEA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,yBAAyB,UAAe;AAC/C,MAAI,cAAc,IAAI,QAAQ,EAAG;AACjC,QAAM,UAAU,oBAAoB,IAAI,SAAS,WAAW,KAAK,CAAC;AAClE,QAAM,SAA8B,CAAC;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AAClD,WAAO,GAAG,IAAI,MAAM,QAAQ;AAAA,EAC9B;AACA,gBAAc,IAAI,UAAU,MAAM;AACpC;AAEO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,eAAW,6BAAY,MAAM;AAEnC,MAAI,CAAC,gBAAgB,IAAI,SAAS,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,mBAAmB,gBAAgB,IAAI,SAAS,WAAW;AACjE,MAAI,iBAAiB,iBAAiB,UAAU;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,2BAAyB,QAAQ;AAEjC,QAAM,YAAY,cAAc,IAAI,QAAQ,KAAK,CAAC;AAElD,SAAO;AACT;;;AR9DA,IAAM,EAAC,MAAM,KAAK,MAAM,WAAU,IAAI,oBAAAC;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["bodyParser","express","crypto","express","import_express","import_env","import_helpers","import_logger","route","route","bodyParser","import_body_parser","bodyParserLib","bodyParser"]} | ||
| {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/routes/registerRoute.ts","../src/start.ts","../src/repl.ts","../src/routes/executeRequest.ts","../src/viewer.ts","../src/routes/registerRoutes.ts","../src/routes/route.ts","../src/service/index.ts"],"sourcesContent":["import bodyParserLib from 'body-parser'\nimport express, {RequestHandler} from 'express'\nimport {onError, setOnError} from './errors'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport {getApp, getServer, startServer} from './start'\nimport {getViewer, setGetViewer} from './viewer'\n\nexport * from './routes/route'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport {registerReplEndpoint} from './repl'\nexport * from './service'\nexport * from './types'\n","import crypto from 'node:crypto'\nimport {logger} from '@orion-js/logger'\nimport express from 'express'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n logger.error(`[route/handler] OrionError in ${req.path}:`, {error})\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n logger.error(`[route/handler] GraphQLError in ${req.path}:`, {error})\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.status(statusCode)\n res.json(data)\n\n error.hash = hash\n logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n return onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import bodyParser from 'body-parser'\nimport express from 'express'\nimport {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\n\nconst appRegisteredRoutes = new WeakMap<express.Application, WeakSet<RouteType>>()\n\nfunction getRegisteredRoutes(app: express.Application) {\n if (appRegisteredRoutes.has(app)) {\n return appRegisteredRoutes.get(app)\n }\n\n const routes = new WeakSet<RouteType>()\n appRegisteredRoutes.set(app, routes)\n return routes\n}\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const registeredRoutes = getRegisteredRoutes(app)\n if (registeredRoutes.has(route)) return\n\n const method = route.method\n\n const handler: express.RequestHandler = (req, res) => {\n void executeRequest(route, req as any, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (!route.bodyParser && route.bodyParams) {\n const parser = bodyParser.json(route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n registeredRoutes.add(route)\n}\n","import {mkdirSync, writeFileSync} from 'node:fs'\nimport {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\nimport {registerReplEndpoint} from './repl'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n if (process.env.ORION_REPL) {\n registerReplEndpoint()\n try {\n mkdirSync('.orion', {recursive: true})\n writeFileSync('.orion/port', String(port))\n } catch {}\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","import {getInstance} from '@orion-js/services'\nimport bodyParser from 'body-parser'\nimport {getApp} from './start'\n\nexport function registerReplEndpoint() {\n const app = getApp()\n\n app.post('/__repl', bodyParser.json(), async (req, res) => {\n try {\n const {expression} = req.body\n const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor\n const fn = new AsyncFunction('getInstance', expression)\n const result = await fn(getInstance)\n res.json({success: true, result})\n } catch (error) {\n res.json({success: false, error: error.message, stack: error.stack})\n }\n })\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\nimport {runWithOrionAsyncContext, updateOrionAsyncContext} from '@orion-js/logger'\nimport {cleanAndValidate} from '@orion-js/schema'\nimport express from 'express'\nimport {onError} from '../errors'\nimport {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\n\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\nconst simulateLatencyMs = Number.parseInt(simulateLatency, 10)\nconst hasSimulateLatency = Number.isFinite(simulateLatencyMs) && simulateLatencyMs > 0\nconst latencyMinMs = hasSimulateLatency ? Math.floor(simulateLatencyMs * 0.9) : 0\nconst latencyMaxMs = hasSimulateLatency ? Math.ceil(simulateLatencyMs * 1.1) : 0\n\nconst objectToString = Object.prototype.toString\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return objectToString.call(value) === '[object Object]'\n}\n\nexport async function executeRequest(\n route: RouteType<any>,\n req: OrionRequest,\n res: express.Response,\n) {\n try {\n if (hasSimulateLatency) {\n const delay = Math.floor(Math.random() * (latencyMaxMs - latencyMinMs + 1)) + latencyMinMs\n await sleep(delay)\n }\n\n const viewer = await getViewer(req)\n\n if (route.queryParams) {\n req.query = await cleanAndValidate(route.queryParams, req.query)\n }\n\n if (route.bodyParams) {\n req.body = await cleanAndValidate(route.bodyParams, req.body)\n }\n\n const context = {\n controllerType: 'route' as const,\n routeName: route.path,\n pathname: req.path,\n viewer,\n params: {\n body: req.body,\n query: req.query,\n params: req.params,\n },\n }\n\n const result = await runWithOrionAsyncContext(context, () => {\n updateOrionAsyncContext({viewer})\n return route.resolve(req, res, viewer)\n })\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n res.set(result.headers)\n }\n\n // add body to response\n if (result.body !== null && result.body !== undefined) {\n let body = result.body\n\n if (route.returns) {\n body = await cleanAndValidate(route.returns, result.body)\n }\n\n if (isPlainObject(body)) {\n res.json(body)\n } else {\n res.send(body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {RoutesMap} from '../types'\nimport registerRoute from './registerRoute'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n for (const routeName in routesMap) {\n registerRoute(routesMap[routeName])\n }\n}\n","import {Schema, SchemaFieldType} from '@orion-js/schema'\nimport {RouteType, OrionRouteOptions} from '../types'\n\nexport function createRoute<\n TPath extends string,\n TQueryParamsSchema extends Schema | undefined,\n TBodyParamsSchema extends Schema | undefined,\n TReturnsSchema extends SchemaFieldType | undefined,\n>(\n options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>,\n): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema> {\n return {\n ...options,\n }\n}\n\n/**\n * @deprecated Use createRoute instead\n */\nexport const route = createRoute\n","import {getInstance, Service} from '@orion-js/services'\nimport {createRoute} from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\nconst routeEntriesByClass = new Map<Function, Record<string, (instance: any) => any>>()\nlet pendingRouteEntries: Record<string, (instance: any) => any> = {}\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'routes'})\n\n if (Object.keys(pendingRouteEntries).length > 0) {\n routeEntriesByClass.set(target, pendingRouteEntries)\n pendingRouteEntries = {}\n }\n }\n}\n\nexport function Route(): (method: any, context: ClassFieldDecoratorContext) => any\nexport function Route(\n options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>,\n): (method: any, context: ClassMethodDecoratorContext) => any\nexport function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>) {\n return (method: any, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext) => {\n const propertyKey = String(context.name)\n\n if (context.kind === 'method') {\n pendingRouteEntries[propertyKey] = (instance: any) =>\n createRoute({\n ...options,\n resolve: instance[propertyKey].bind(instance),\n })\n }\n\n if (context.kind === 'field') {\n pendingRouteEntries[propertyKey] = (instance: any) => instance[propertyKey]\n }\n\n return method\n }\n}\n\nfunction initializeRoutesIfNeeded(instance: any) {\n if (routeMetadata.has(instance)) return\n const entries = routeEntriesByClass.get(instance.constructor) || {}\n const routes: Record<string, any> = {}\n for (const [key, setup] of Object.entries(entries)) {\n routes[key] = setup(instance)\n }\n routeMetadata.set(instance, routes)\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n initializeRoutesIfNeeded(instance)\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAAA;AAAA,EAAA;AAAA,iCAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAC,sBAA0B;AAC1B,IAAAC,kBAAsC;;;ACDtC,yBAAmB;AACnB,oBAAqB;AAKrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,2BAAO,MAAM,iCAAiC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,IACpE;AAEA,UAAM,OAAO,MAAM,QAAQ;AAE3B,QAAI,OAAO,UAAU;AACrB,QAAI,KAAK,IAAI;AAAA,EACf,WAAW,MAAM,gBAAgB;AAC/B,QAAI,UAAU,MAAM,UAAU;AAC9B,QAAI,IAAI,MAAM,OAAO;AACrB,yBAAO,MAAM,mCAAmC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,EACtE,OAAO;AACL,UAAM,OAAO,mBAAAC,QACV,WAAW,MAAM,EACjB,OAAO,MAAM,SAAS,MAAM,EAC5B,OAAO,KAAK,EACZ,UAAU,GAAG,EAAE;AAClB,UAAM,aAAa;AACnB,UAAM,OAAO,EAAC,OAAO,KAAK,SAAS,yBAAyB,KAAI;AAEhE,QAAI,OAAO,UAAU;AACrB,QAAI,KAAK,IAAI;AAEb,UAAM,OAAO;AACb,yBAAO,MAAM,yCAAyC,EAAC,OAAO,KAAK,IAAI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IAAM,EAAC,MAAM,KAAK,MAAM,WAAU,IAAI,oBAAAC;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["bodyParser","express","import_body_parser","import_express","crypto","import_body_parser","bodyParser","express","import_env","import_helpers","import_logger","route","route","bodyParser","import_services","bodyParserLib","bodyParser"]} |
+13
-11
@@ -10,12 +10,2 @@ import express, { RequestHandler } from 'express'; | ||
| declare const getViewer: (req: express.Request) => Promise<any>; | ||
| declare const setGetViewer: (getViewerFunc: (req: express.Request) => any) => void; | ||
| interface StartOrionOptions { | ||
| keepAliveTimeout?: number; | ||
| } | ||
| declare const startServer: (port?: number, otherOptions?: StartOrionOptions) => express.Express; | ||
| declare const getApp: () => express.Express; | ||
| declare const getServer: () => any; | ||
| interface RouteResponseObject<TReturnsSchema extends SchemaFieldType | undefined = undefined> { | ||
@@ -96,2 +86,12 @@ statusCode?: number; | ||
| interface StartOrionOptions { | ||
| keepAliveTimeout?: number; | ||
| } | ||
| declare const startServer: (port?: number, otherOptions?: StartOrionOptions) => express.Express; | ||
| declare const getApp: () => express.Express; | ||
| declare const getServer: () => any; | ||
| declare const getViewer: (req: express.Request) => Promise<any>; | ||
| declare const setGetViewer: (getViewerFunc: (req: express.Request) => any) => void; | ||
| declare function createRoute<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined>(options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>; | ||
@@ -103,2 +103,4 @@ /** | ||
| declare function registerReplEndpoint(): void; | ||
| declare function Routes(): (target: any, context: ClassDecoratorContext<any>) => void; | ||
@@ -118,2 +120,2 @@ declare function Route(): (method: any, context: ClassFieldDecoratorContext) => any; | ||
| export { type InferPathParams, type OrionRequest, type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, createRoute, getApp, getServer, getServiceRoutes, getViewer, onError, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer }; | ||
| export { type InferPathParams, type OrionRequest, type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, createRoute, getApp, getServer, getServiceRoutes, getViewer, onError, registerReplEndpoint, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer }; |
+13
-11
@@ -10,12 +10,2 @@ import express, { RequestHandler } from 'express'; | ||
| declare const getViewer: (req: express.Request) => Promise<any>; | ||
| declare const setGetViewer: (getViewerFunc: (req: express.Request) => any) => void; | ||
| interface StartOrionOptions { | ||
| keepAliveTimeout?: number; | ||
| } | ||
| declare const startServer: (port?: number, otherOptions?: StartOrionOptions) => express.Express; | ||
| declare const getApp: () => express.Express; | ||
| declare const getServer: () => any; | ||
| interface RouteResponseObject<TReturnsSchema extends SchemaFieldType | undefined = undefined> { | ||
@@ -96,2 +86,12 @@ statusCode?: number; | ||
| interface StartOrionOptions { | ||
| keepAliveTimeout?: number; | ||
| } | ||
| declare const startServer: (port?: number, otherOptions?: StartOrionOptions) => express.Express; | ||
| declare const getApp: () => express.Express; | ||
| declare const getServer: () => any; | ||
| declare const getViewer: (req: express.Request) => Promise<any>; | ||
| declare const setGetViewer: (getViewerFunc: (req: express.Request) => any) => void; | ||
| declare function createRoute<TPath extends string, TQueryParamsSchema extends Schema | undefined, TBodyParamsSchema extends Schema | undefined, TReturnsSchema extends SchemaFieldType | undefined>(options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>; | ||
@@ -103,2 +103,4 @@ /** | ||
| declare function registerReplEndpoint(): void; | ||
| declare function Routes(): (target: any, context: ClassDecoratorContext<any>) => void; | ||
@@ -118,2 +120,2 @@ declare function Route(): (method: any, context: ClassFieldDecoratorContext) => any; | ||
| export { type InferPathParams, type OrionRequest, type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, createRoute, getApp, getServer, getServiceRoutes, getViewer, onError, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer }; | ||
| export { type InferPathParams, type OrionRequest, type OrionRouteOptions, type Request, type Response, Route, type RouteResolve, type RouteResponse, type RouteResponseObject, type RouteType, Routes, type RoutesMap, bodyParser, createRoute, getApp, getServer, getServiceRoutes, getViewer, onError, registerReplEndpoint, registerRoute, registerRoutes, route, setGetViewer, setOnError, startServer }; |
+61
-30
@@ -0,1 +1,5 @@ | ||
| // src/index.ts | ||
| import bodyParserLib from "body-parser"; | ||
| import express2 from "express"; | ||
| // src/errors.ts | ||
@@ -37,21 +41,30 @@ import crypto from "crypto"; | ||
| // src/viewer.ts | ||
| import { UserError } from "@orion-js/helpers"; | ||
| global.getViewerRef = () => null; | ||
| var getViewer = async (req) => { | ||
| try { | ||
| const viewer = await global.getViewerRef(req); | ||
| if (!viewer) return {}; | ||
| return viewer; | ||
| } catch (err) { | ||
| throw new UserError("AuthError", err.message); | ||
| } | ||
| }; | ||
| var setGetViewer = (getViewerFunc) => { | ||
| global.getViewerRef = getViewerFunc; | ||
| }; | ||
| // src/routes/registerRoute.ts | ||
| import bodyParser2 from "body-parser"; | ||
| // src/start.ts | ||
| import { mkdirSync, writeFileSync } from "fs"; | ||
| import { internalGetEnv } from "@orion-js/env"; | ||
| import express from "express"; | ||
| // src/repl.ts | ||
| import { getInstance } from "@orion-js/services"; | ||
| import bodyParser from "body-parser"; | ||
| function registerReplEndpoint() { | ||
| const app = getApp(); | ||
| app.post("/__repl", bodyParser.json(), async (req, res) => { | ||
| try { | ||
| const { expression } = req.body; | ||
| const AsyncFunction = Object.getPrototypeOf(async () => { | ||
| }).constructor; | ||
| const fn = new AsyncFunction("getInstance", expression); | ||
| const result = await fn(getInstance); | ||
| res.json({ success: true, result }); | ||
| } catch (error) { | ||
| res.json({ success: false, error: error.message, stack: error.stack }); | ||
| } | ||
| }); | ||
| } | ||
| // src/start.ts | ||
| global.appRef = null; | ||
@@ -67,2 +80,10 @@ global.serverRef = null; | ||
| } | ||
| if (process.env.ORION_REPL) { | ||
| registerReplEndpoint(); | ||
| try { | ||
| mkdirSync(".orion", { recursive: true }); | ||
| writeFileSync(".orion/port", String(port)); | ||
| } catch { | ||
| } | ||
| } | ||
| return app; | ||
@@ -80,8 +101,2 @@ }; | ||
| // src/index.ts | ||
| import express2 from "express"; | ||
| // src/routes/registerRoute.ts | ||
| import bodyParser from "body-parser"; | ||
| // src/routes/executeRequest.ts | ||
@@ -92,2 +107,20 @@ import { internalGetEnv as internalGetEnv2 } from "@orion-js/env"; | ||
| import { cleanAndValidate } from "@orion-js/schema"; | ||
| // src/viewer.ts | ||
| import { UserError } from "@orion-js/helpers"; | ||
| global.getViewerRef = () => null; | ||
| var getViewer = async (req) => { | ||
| try { | ||
| const viewer = await global.getViewerRef(req); | ||
| if (!viewer) return {}; | ||
| return viewer; | ||
| } catch (err) { | ||
| throw new UserError("AuthError", err.message); | ||
| } | ||
| }; | ||
| var setGetViewer = (getViewerFunc) => { | ||
| global.getViewerRef = getViewerFunc; | ||
| }; | ||
| // src/routes/executeRequest.ts | ||
| var simulateLatency = internalGetEnv2("simulate_latency", "SIMULATE_LATENCY"); | ||
@@ -173,7 +206,7 @@ var simulateLatencyMs = Number.parseInt(simulateLatency, 10); | ||
| if (route2.bodyParser) { | ||
| const parser = bodyParser[route2.bodyParser](route2.bodyParserOptions); | ||
| const parser = bodyParser2[route2.bodyParser](route2.bodyParserOptions); | ||
| handlers.unshift(parser); | ||
| } | ||
| if (!route2.bodyParser && route2.bodyParams) { | ||
| const parser = bodyParser.json(route2.bodyParserOptions); | ||
| const parser = bodyParser2.json(route2.bodyParserOptions); | ||
| handlers.unshift(parser); | ||
@@ -195,5 +228,2 @@ } | ||
| // src/index.ts | ||
| import bodyParserLib from "body-parser"; | ||
| // src/routes/route.ts | ||
@@ -208,3 +238,3 @@ function createRoute(options) { | ||
| // src/service/index.ts | ||
| import { getInstance, Service } from "@orion-js/services"; | ||
| import { getInstance as getInstance2, Service } from "@orion-js/services"; | ||
| var serviceMetadata = /* @__PURE__ */ new WeakMap(); | ||
@@ -249,3 +279,3 @@ var routeMetadata = /* @__PURE__ */ new WeakMap(); | ||
| function getServiceRoutes(target) { | ||
| const instance = getInstance(target); | ||
| const instance = getInstance2(target); | ||
| if (!serviceMetadata.has(instance.constructor)) { | ||
@@ -265,7 +295,7 @@ throw new Error("You must pass a class decorated with @Routes to getServiceRoutes"); | ||
| var { json, raw, text, urlencoded } = bodyParserLib; | ||
| var bodyParser2 = { json, raw, text, urlencoded }; | ||
| var bodyParser3 = { json, raw, text, urlencoded }; | ||
| export { | ||
| Route, | ||
| Routes, | ||
| bodyParser2 as bodyParser, | ||
| bodyParser3 as bodyParser, | ||
| createRoute, | ||
@@ -278,2 +308,3 @@ express2 as express, | ||
| onError, | ||
| registerReplEndpoint, | ||
| registerRoute, | ||
@@ -280,0 +311,0 @@ registerRoutes, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../src/errors.ts","../src/viewer.ts","../src/start.ts","../src/index.ts","../src/routes/registerRoute.ts","../src/routes/executeRequest.ts","../src/routes/registerRoutes.ts","../src/routes/route.ts","../src/service/index.ts"],"sourcesContent":["import crypto from 'node:crypto'\nimport {logger} from '@orion-js/logger'\nimport express from 'express'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n logger.error(`[route/handler] OrionError in ${req.path}:`, {error})\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n logger.error(`[route/handler] GraphQLError in ${req.path}:`, {error})\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.status(statusCode)\n res.json(data)\n\n error.hash = hash\n logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n return onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","import {setOnError, onError} from './errors'\nimport {getViewer, setGetViewer} from './viewer'\nimport {startServer, getApp, getServer} from './start'\nimport express from 'express'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport bodyParserLib from 'body-parser'\nimport {RequestHandler} from 'express'\n\nexport * from './routes/route'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport * from './types'\nexport * from './service'\n","import bodyParser from 'body-parser'\nimport express from 'express'\nimport {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\n\nconst appRegisteredRoutes = new WeakMap<express.Application, WeakSet<RouteType>>()\n\nfunction getRegisteredRoutes(app: express.Application) {\n if (appRegisteredRoutes.has(app)) {\n return appRegisteredRoutes.get(app)\n }\n\n const routes = new WeakSet<RouteType>()\n appRegisteredRoutes.set(app, routes)\n return routes\n}\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const registeredRoutes = getRegisteredRoutes(app)\n if (registeredRoutes.has(route)) return\n\n const method = route.method\n\n const handler: express.RequestHandler = (req, res) => {\n void executeRequest(route, req as any, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (!route.bodyParser && route.bodyParams) {\n const parser = bodyParser.json(route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n registeredRoutes.add(route)\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\nimport {runWithOrionAsyncContext, updateOrionAsyncContext} from '@orion-js/logger'\nimport {cleanAndValidate} from '@orion-js/schema'\nimport express from 'express'\nimport {onError} from '../errors'\nimport {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\n\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\nconst simulateLatencyMs = Number.parseInt(simulateLatency, 10)\nconst hasSimulateLatency = Number.isFinite(simulateLatencyMs) && simulateLatencyMs > 0\nconst latencyMinMs = hasSimulateLatency ? Math.floor(simulateLatencyMs * 0.9) : 0\nconst latencyMaxMs = hasSimulateLatency ? Math.ceil(simulateLatencyMs * 1.1) : 0\n\nconst objectToString = Object.prototype.toString\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return objectToString.call(value) === '[object Object]'\n}\n\nexport async function executeRequest(\n route: RouteType<any>,\n req: OrionRequest,\n res: express.Response,\n) {\n try {\n if (hasSimulateLatency) {\n const delay = Math.floor(Math.random() * (latencyMaxMs - latencyMinMs + 1)) + latencyMinMs\n await sleep(delay)\n }\n\n const viewer = await getViewer(req)\n\n if (route.queryParams) {\n req.query = await cleanAndValidate(route.queryParams, req.query)\n }\n\n if (route.bodyParams) {\n req.body = await cleanAndValidate(route.bodyParams, req.body)\n }\n\n const context = {\n controllerType: 'route' as const,\n routeName: route.path,\n pathname: req.path,\n viewer,\n params: {\n body: req.body,\n query: req.query,\n params: req.params,\n },\n }\n\n const result = await runWithOrionAsyncContext(context, () => {\n updateOrionAsyncContext({viewer})\n return route.resolve(req, res, viewer)\n })\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n res.set(result.headers)\n }\n\n // add body to response\n if (result.body !== null && result.body !== undefined) {\n let body = result.body\n\n if (route.returns) {\n body = await cleanAndValidate(route.returns, result.body)\n }\n\n if (isPlainObject(body)) {\n res.json(body)\n } else {\n res.send(body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import {RoutesMap} from '../types'\nimport registerRoute from './registerRoute'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n for (const routeName in routesMap) {\n registerRoute(routesMap[routeName])\n }\n}\n","import {Schema, SchemaFieldType} from '@orion-js/schema'\nimport {RouteType, OrionRouteOptions} from '../types'\n\nexport function createRoute<\n TPath extends string,\n TQueryParamsSchema extends Schema | undefined,\n TBodyParamsSchema extends Schema | undefined,\n TReturnsSchema extends SchemaFieldType | undefined,\n>(\n options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>,\n): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema> {\n return {\n ...options,\n }\n}\n\n/**\n * @deprecated Use createRoute instead\n */\nexport const route = createRoute\n","import {getInstance, Service} from '@orion-js/services'\nimport {createRoute} from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\nconst routeEntriesByClass = new Map<Function, Record<string, (instance: any) => any>>()\nlet pendingRouteEntries: Record<string, (instance: any) => any> = {}\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'routes'})\n\n if (Object.keys(pendingRouteEntries).length > 0) {\n routeEntriesByClass.set(target, pendingRouteEntries)\n pendingRouteEntries = {}\n }\n }\n}\n\nexport function Route(): (method: any, context: ClassFieldDecoratorContext) => any\nexport function Route(\n options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>,\n): (method: any, context: ClassMethodDecoratorContext) => any\nexport function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>) {\n return (method: any, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext) => {\n const propertyKey = String(context.name)\n\n if (context.kind === 'method') {\n pendingRouteEntries[propertyKey] = (instance: any) =>\n createRoute({\n ...options,\n resolve: instance[propertyKey].bind(instance),\n })\n }\n\n if (context.kind === 'field') {\n pendingRouteEntries[propertyKey] = (instance: any) => instance[propertyKey]\n }\n\n return method\n }\n}\n\nfunction initializeRoutesIfNeeded(instance: any) {\n if (routeMetadata.has(instance)) return\n const entries = routeEntriesByClass.get(instance.constructor) || {}\n const routes: Record<string, any> = {}\n for (const [key, setup] of Object.entries(entries)) {\n routes[key] = setup(instance)\n }\n routeMetadata.set(instance, routes)\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n initializeRoutesIfNeeded(instance)\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,SAAQ,cAAa;AAKrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,aAAa;AAC9B,mBAAa;AAAA,IACf,OAAO;AACL,aAAO,MAAM,iCAAiC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,IACpE;AAEA,UAAM,OAAO,MAAM,QAAQ;AAE3B,QAAI,OAAO,UAAU;AACrB,QAAI,KAAK,IAAI;AAAA,EACf,WAAW,MAAM,gBAAgB;AAC/B,QAAI,UAAU,MAAM,UAAU;AAC9B,QAAI,IAAI,MAAM,OAAO;AACrB,WAAO,MAAM,mCAAmC,IAAI,IAAI,KAAK,EAAC,MAAK,CAAC;AAAA,EACtE,OAAO;AACL,UAAM,OAAO,OACV,WAAW,MAAM,EACjB,OAAO,MAAM,SAAS,MAAM,EAC5B,OAAO,KAAK,EACZ,UAAU,GAAG,EAAE;AAClB,UAAM,aAAa;AACnB,UAAM,OAAO,EAAC,OAAO,KAAK,SAAS,yBAAyB,KAAI;AAEhE,QAAI,OAAO,UAAU;AACrB,QAAI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;AAC/C,MAAI,cAAc,IAAI,QAAQ,EAAG;AACjC,QAAM,UAAU,oBAAoB,IAAI,SAAS,WAAW,KAAK,CAAC;AAClE,QAAM,SAA8B,CAAC;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AAClD,WAAO,GAAG,IAAI,MAAM,QAAQ;AAAA,EAC9B;AACA,gBAAc,IAAI,UAAU,MAAM;AACpC;AAEO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,WAAW,YAAY,MAAM;AAEnC,MAAI,CAAC,gBAAgB,IAAI,SAAS,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,mBAAmB,gBAAgB,IAAI,SAAS,WAAW;AACjE,MAAI,iBAAiB,iBAAiB,UAAU;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,2BAAyB,QAAQ;AAEjC,QAAM,YAAY,cAAc,IAAI,QAAQ,KAAK,CAAC;AAElD,SAAO;AACT;;;AL9DA,IAAM,EAAC,MAAM,KAAK,MAAM,WAAU,IAAI;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["express","internalGetEnv","internalGetEnv","route","route","bodyParser"]} | ||
| {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/routes/registerRoute.ts","../src/start.ts","../src/repl.ts","../src/routes/executeRequest.ts","../src/viewer.ts","../src/routes/registerRoutes.ts","../src/routes/route.ts","../src/service/index.ts"],"sourcesContent":["import bodyParserLib from 'body-parser'\nimport express, {RequestHandler} from 'express'\nimport {onError, setOnError} from './errors'\nimport registerRoute from './routes/registerRoute'\nimport registerRoutes from './routes/registerRoutes'\nimport {getApp, getServer, startServer} from './start'\nimport {getViewer, setGetViewer} from './viewer'\n\nexport * from './routes/route'\n\nconst {json, raw, text, urlencoded} = bodyParserLib\n\nconst bodyParser: {\n json: () => RequestHandler\n raw: () => RequestHandler\n text: () => RequestHandler\n urlencoded: (options?: {extended: boolean}) => RequestHandler\n} = {json, raw, text, urlencoded}\n\nexport {\n express,\n startServer,\n getApp,\n getServer,\n getViewer,\n setGetViewer,\n setOnError,\n onError,\n registerRoute,\n registerRoutes,\n bodyParser,\n}\n\nexport {registerReplEndpoint} from './repl'\nexport * from './service'\nexport * from './types'\n","import crypto from 'node:crypto'\nimport {logger} from '@orion-js/logger'\nimport express from 'express'\n\ntype onErrorFunction = (req: express.Request, res: express.Response, error: any) => Promise<void>\n\nconst defaultOnError: onErrorFunction = async (req, res, error) => {\n if (error.isOrionError) {\n let statusCode = 400\n if (error.code === 'AuthError') {\n statusCode = 401\n } else {\n logger.error(`[route/handler] OrionError in ${req.path}:`, {error})\n }\n\n const data = error.getInfo()\n\n res.status(statusCode)\n res.json(data)\n } else if (error.isGraphQLError) {\n res.writeHead(error.statusCode)\n res.end(error.message)\n logger.error(`[route/handler] GraphQLError in ${req.path}:`, {error})\n } else {\n const hash = crypto\n .createHash('sha1')\n .update(error.message, 'utf8')\n .digest('hex')\n .substring(0, 10)\n const statusCode = 500\n const data = {error: 500, message: 'Internal server error', hash}\n\n res.status(statusCode)\n res.json(data)\n\n error.hash = hash\n logger.error('[route/handler] Internal server error', {error, url: req.url, hash})\n }\n}\n\nlet onErrorRef: onErrorFunction = defaultOnError\n\nexport const onError: onErrorFunction = async (req, res, error) => {\n return onErrorRef(req, res, error)\n}\n\nexport const setOnError = (onErrorFunc: onErrorFunction): void => {\n onErrorRef = onErrorFunc\n}\n","import bodyParser from 'body-parser'\nimport express from 'express'\nimport {getApp} from './../start'\nimport {RouteType} from '../types'\nimport {executeRequest} from './executeRequest'\n\nconst appRegisteredRoutes = new WeakMap<express.Application, WeakSet<RouteType>>()\n\nfunction getRegisteredRoutes(app: express.Application) {\n if (appRegisteredRoutes.has(app)) {\n return appRegisteredRoutes.get(app)\n }\n\n const routes = new WeakSet<RouteType>()\n appRegisteredRoutes.set(app, routes)\n return routes\n}\n\nexport default function registerRoute(route: RouteType): void {\n const app = route.app || getApp()\n const registeredRoutes = getRegisteredRoutes(app)\n if (registeredRoutes.has(route)) return\n\n const method = route.method\n\n const handler: express.RequestHandler = (req, res) => {\n void executeRequest(route, req as any, res)\n }\n\n const handlers: Array<express.RequestHandler> = [handler]\n\n if (route.bodyParser) {\n const parser = bodyParser[route.bodyParser](route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (!route.bodyParser && route.bodyParams) {\n const parser = bodyParser.json(route.bodyParserOptions)\n handlers.unshift(parser)\n }\n\n if (route.middlewares) {\n handlers.unshift(...route.middlewares)\n }\n\n app[method](route.path, ...handlers)\n registeredRoutes.add(route)\n}\n","import {mkdirSync, writeFileSync} from 'node:fs'\nimport {internalGetEnv} from '@orion-js/env'\nimport express from 'express'\nimport {registerReplEndpoint} from './repl'\n\nglobal.appRef = null\nglobal.serverRef = null\n\nexport interface StartOrionOptions {\n keepAliveTimeout?: number\n}\n\nexport const startServer = (\n port: number = Number(internalGetEnv('http_port', 'PORT')),\n otherOptions: StartOrionOptions = {},\n) => {\n const app = getApp()\n\n const server = app.listen(port)\n global.serverRef = server\n\n if (otherOptions.keepAliveTimeout) {\n server.keepAliveTimeout = otherOptions.keepAliveTimeout // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n server.headersTimeout = otherOptions.keepAliveTimeout + 1000\n }\n\n if (process.env.ORION_REPL) {\n registerReplEndpoint()\n try {\n mkdirSync('.orion', {recursive: true})\n writeFileSync('.orion/port', String(port))\n } catch {}\n }\n\n return app\n}\n\nexport const getApp = (): express.Express => {\n if (global.appRef) return global.appRef as express.Express\n\n const app = express()\n\n global.appRef = app\n\n return app\n}\n\nexport const getServer = () => {\n return global.serverRef\n}\n","import {getInstance} from '@orion-js/services'\nimport bodyParser from 'body-parser'\nimport {getApp} from './start'\n\nexport function registerReplEndpoint() {\n const app = getApp()\n\n app.post('/__repl', bodyParser.json(), async (req, res) => {\n try {\n const {expression} = req.body\n const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor\n const fn = new AsyncFunction('getInstance', expression)\n const result = await fn(getInstance)\n res.json({success: true, result})\n } catch (error) {\n res.json({success: false, error: error.message, stack: error.stack})\n }\n })\n}\n","import {internalGetEnv} from '@orion-js/env'\nimport {sleep} from '@orion-js/helpers'\nimport {runWithOrionAsyncContext, updateOrionAsyncContext} from '@orion-js/logger'\nimport {cleanAndValidate} from '@orion-js/schema'\nimport express from 'express'\nimport {onError} from '../errors'\nimport {OrionRequest, RouteType} from './../types'\nimport {getViewer} from './../viewer'\n\nconst simulateLatency = internalGetEnv('simulate_latency', 'SIMULATE_LATENCY')\nconst simulateLatencyMs = Number.parseInt(simulateLatency, 10)\nconst hasSimulateLatency = Number.isFinite(simulateLatencyMs) && simulateLatencyMs > 0\nconst latencyMinMs = hasSimulateLatency ? Math.floor(simulateLatencyMs * 0.9) : 0\nconst latencyMaxMs = hasSimulateLatency ? Math.ceil(simulateLatencyMs * 1.1) : 0\n\nconst objectToString = Object.prototype.toString\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return objectToString.call(value) === '[object Object]'\n}\n\nexport async function executeRequest(\n route: RouteType<any>,\n req: OrionRequest,\n res: express.Response,\n) {\n try {\n if (hasSimulateLatency) {\n const delay = Math.floor(Math.random() * (latencyMaxMs - latencyMinMs + 1)) + latencyMinMs\n await sleep(delay)\n }\n\n const viewer = await getViewer(req)\n\n if (route.queryParams) {\n req.query = await cleanAndValidate(route.queryParams, req.query)\n }\n\n if (route.bodyParams) {\n req.body = await cleanAndValidate(route.bodyParams, req.body)\n }\n\n const context = {\n controllerType: 'route' as const,\n routeName: route.path,\n pathname: req.path,\n viewer,\n params: {\n body: req.body,\n query: req.query,\n params: req.params,\n },\n }\n\n const result = await runWithOrionAsyncContext(context, () => {\n updateOrionAsyncContext({viewer})\n return route.resolve(req, res, viewer)\n })\n if (!result) return\n\n // add status code to response\n if (result.statusCode) {\n res.status(result.statusCode)\n }\n\n // add headers to response\n if (result.headers) {\n res.set(result.headers)\n }\n\n // add body to response\n if (result.body !== null && result.body !== undefined) {\n let body = result.body\n\n if (route.returns) {\n body = await cleanAndValidate(route.returns, result.body)\n }\n\n if (isPlainObject(body)) {\n res.json(body)\n } else {\n res.send(body)\n }\n }\n } catch (error) {\n await onError(req, res, error)\n }\n}\n","import express from 'express'\nimport {UserError} from '@orion-js/helpers'\n\nglobal.getViewerRef = () => null\n\nexport const getViewer = async (req: express.Request): Promise<any> => {\n try {\n const viewer = await global.getViewerRef(req)\n if (!viewer) return {}\n return viewer\n } catch (err) {\n throw new UserError('AuthError', err.message)\n }\n}\n\nexport const setGetViewer = (getViewerFunc: (req: express.Request) => any): void => {\n global.getViewerRef = getViewerFunc\n}\n","import {RoutesMap} from '../types'\nimport registerRoute from './registerRoute'\n\nexport default function registerRoutes(routesMap: RoutesMap): void {\n for (const routeName in routesMap) {\n registerRoute(routesMap[routeName])\n }\n}\n","import {Schema, SchemaFieldType} from '@orion-js/schema'\nimport {RouteType, OrionRouteOptions} from '../types'\n\nexport function createRoute<\n TPath extends string,\n TQueryParamsSchema extends Schema | undefined,\n TBodyParamsSchema extends Schema | undefined,\n TReturnsSchema extends SchemaFieldType | undefined,\n>(\n options: OrionRouteOptions<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema>,\n): RouteType<TPath, TQueryParamsSchema, TBodyParamsSchema, TReturnsSchema> {\n return {\n ...options,\n }\n}\n\n/**\n * @deprecated Use createRoute instead\n */\nexport const route = createRoute\n","import {getInstance, Service} from '@orion-js/services'\nimport {createRoute} from '../routes/route'\nimport {OrionRouteOptions, RoutesMap} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\nconst routeMetadata = new WeakMap<any, Record<string, any>>()\nconst routeEntriesByClass = new Map<Function, Record<string, (instance: any) => any>>()\nlet pendingRouteEntries: Record<string, (instance: any) => any> = {}\n\nexport function Routes() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'routes'})\n\n if (Object.keys(pendingRouteEntries).length > 0) {\n routeEntriesByClass.set(target, pendingRouteEntries)\n pendingRouteEntries = {}\n }\n }\n}\n\nexport function Route(): (method: any, context: ClassFieldDecoratorContext) => any\nexport function Route(\n options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>,\n): (method: any, context: ClassMethodDecoratorContext) => any\nexport function Route(options?: Omit<OrionRouteOptions<any, any, any, any>, 'resolve'>) {\n return (method: any, context: ClassFieldDecoratorContext | ClassMethodDecoratorContext) => {\n const propertyKey = String(context.name)\n\n if (context.kind === 'method') {\n pendingRouteEntries[propertyKey] = (instance: any) =>\n createRoute({\n ...options,\n resolve: instance[propertyKey].bind(instance),\n })\n }\n\n if (context.kind === 'field') {\n pendingRouteEntries[propertyKey] = (instance: any) => instance[propertyKey]\n }\n\n return method\n }\n}\n\nfunction initializeRoutesIfNeeded(instance: any) {\n if (routeMetadata.has(instance)) return\n const entries = routeEntriesByClass.get(instance.constructor) || {}\n const routes: Record<string, any> = {}\n for (const [key, setup] of Object.entries(entries)) {\n routes[key] = setup(instance)\n }\n routeMetadata.set(instance, routes)\n}\n\nexport function getServiceRoutes(target: any): RoutesMap {\n const instance = getInstance(target)\n\n if (!serviceMetadata.has(instance.constructor)) {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n const instanceMetadata = serviceMetadata.get(instance.constructor)\n if (instanceMetadata._serviceType !== 'routes') {\n throw new Error('You must pass a class decorated with @Routes to getServiceRoutes')\n }\n\n initializeRoutesIfNeeded(instance)\n\n const routesMap = routeMetadata.get(instance) || {}\n\n return routesMap\n}\n"],"mappings":";AAAA,OAAO,mBAAmB;AAC1B,OAAOA,cAA+B;;;ACDtC,OAAO,YAAY;AACnB,SAAQ,cAAa;AAKrB,IAAM,iBAAkC,OAAO,KAAK,KAAK,UAAU;AACjE,MAAI,MAAM,cAAc;AACtB,QAAI,aAAa;AACjB,QAAI,MAAM,SAAS,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EA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,yBAAyB,UAAe;AAC/C,MAAI,cAAc,IAAI,QAAQ,EAAG;AACjC,QAAM,UAAU,oBAAoB,IAAI,SAAS,WAAW,KAAK,CAAC;AAClE,QAAM,SAA8B,CAAC;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AAClD,WAAO,GAAG,IAAI,MAAM,QAAQ;AAAA,EAC9B;AACA,gBAAc,IAAI,UAAU,MAAM;AACpC;AAEO,SAAS,iBAAiB,QAAwB;AACvD,QAAM,WAAWC,aAAY,MAAM;AAEnC,MAAI,CAAC,gBAAgB,IAAI,SAAS,WAAW,GAAG;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,QAAM,mBAAmB,gBAAgB,IAAI,SAAS,WAAW;AACjE,MAAI,iBAAiB,iBAAiB,UAAU;AAC9C,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AAEA,2BAAyB,QAAQ;AAEjC,QAAM,YAAY,cAAc,IAAI,QAAQ,KAAK,CAAC;AAElD,SAAO;AACT;;;AT/DA,IAAM,EAAC,MAAM,KAAK,MAAM,WAAU,IAAI;AAEtC,IAAMC,cAKF,EAAC,MAAM,KAAK,MAAM,WAAU;","names":["express","bodyParser","internalGetEnv","internalGetEnv","route","route","bodyParser","getInstance","getInstance","bodyParser"]} |
+1
-1
| { | ||
| "name": "@orion-js/http", | ||
| "version": "4.3.0", | ||
| "version": "4.3.1", | ||
| "main": "./dist/index.cjs", | ||
@@ -5,0 +5,0 @@ "types": "./dist/index.d.ts", |
AI-detected potential malware
Supply chain riskAI has identified this package as malware. This is a strong signal that the package may be malicious.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
72176
8.15%745
8.6%1
Infinity%5
400%