UNPKG

@moostjs/event-http

Version:
366 lines (359 loc) 13.8 kB
"use strict"; //#region rolldown:runtime var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion const moost = __toESM(require("moost")); const __wooksjs_event_core = __toESM(require("@wooksjs/event-core")); const __wooksjs_event_http = __toESM(require("@wooksjs/event-http")); const __wooksjs_http_body = __toESM(require("@wooksjs/http-body")); const __prostojs_infact = __toESM(require("@prostojs/infact")); const http = __toESM(require("http")); const https = __toESM(require("https")); //#region packages/event-http/src/decorators/http-method.decorator.ts function HttpMethod(method, path) { return (0, moost.getMoostMate)().decorate("handlers", { method, path, type: "HTTP" }, true); } const All = (path) => HttpMethod("*", path); const Get = (path) => HttpMethod("GET", path); const Post = (path) => HttpMethod("POST", path); const Put = (path) => HttpMethod("PUT", path); const Delete = (path) => HttpMethod("DELETE", path); const Patch = (path) => HttpMethod("PATCH", path); //#endregion //#region packages/event-http/src/decorators/resolve.decorator.ts const StatusHook = () => (0, moost.Resolve)((metas, level) => { const hook = (0, __wooksjs_event_http.useStatus)(); if (level === "PARAM") return hook; if (level === "PROP" && metas.instance && metas.key) { const initialValue = metas.instance[metas.key]; (0, __wooksjs_event_core.attachHook)(metas.instance, { get: () => hook.value, set: (v) => hook.value = v }, metas.key); return typeof initialValue === "number" ? initialValue : 200; } }, "statusCode"); const HeaderHook = (name) => (0, moost.Resolve)((metas, level) => { const hook = (0, __wooksjs_event_http.useSetHeader)(name); if (level === "PARAM") return hook; if (level === "PROP" && metas.instance && metas.key) { const initialValue = metas.instance[metas.key]; (0, __wooksjs_event_core.attachHook)(metas.instance, { get: () => hook.value, set: (v) => hook.value = v }, metas.key); return typeof initialValue === "string" ? initialValue : ""; } }, name); const CookieHook = (name) => (0, moost.Resolve)((metas, level) => { const hook = (0, __wooksjs_event_http.useSetCookie)(name); if (level === "PARAM") return hook; if (level === "PROP" && metas.instance && metas.key) { const initialValue = metas.instance[metas.key]; (0, __wooksjs_event_core.attachHook)(metas.instance, { get: () => hook.value, set: (v) => hook.value = v }, metas.key); return typeof initialValue === "string" ? initialValue : ""; } }, name); const CookieAttrsHook = (name) => (0, moost.Resolve)((metas, level) => { const hook = (0, __wooksjs_event_http.useSetCookie)(name); if (level === "PARAM") return (0, __wooksjs_event_core.attachHook)({}, { get: () => hook.attrs, set: (v) => hook.attrs = v }); if (level === "PROP" && metas.instance && metas.key) { const initialValue = metas.instance[metas.key]; (0, __wooksjs_event_core.attachHook)(metas.instance, { get: () => hook.attrs, set: (v) => hook.attrs = v }, metas.key); return typeof initialValue === "object" ? initialValue : {}; } }, name); function Authorization(name) { return (0, moost.Resolve)(() => { const auth = (0, __wooksjs_event_http.useAuthorization)(); switch (name) { case "username": return auth.isBasic() ? auth.basicCredentials()?.username : undefined; case "password": return auth.isBasic() ? auth.basicCredentials()?.password : undefined; case "bearer": return auth.isBearer() ? auth.authorization : undefined; case "raw": return auth.authRawCredentials(); case "type": return auth.authType(); } }, "authorization"); } function Header(name) { return (0, moost.Resolve)(() => { const headers = (0, __wooksjs_event_http.useHeaders)(); return headers[name]; }, `header: ${name}`); } function Cookie(name) { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useCookies)().getCookie(name), `cookie: ${name}`); } function Query(name) { const isItem = !!name; const _name = isItem ? name : "Query"; return (0, moost.getMoostMate)().apply((0, moost.getMoostMate)().decorate("paramSource", isItem ? "QUERY_ITEM" : "QUERY"), (0, moost.getMoostMate)().decorate("paramName", _name), (0, moost.Resolve)(() => { const { jsonSearchParams, urlSearchParams } = (0, __wooksjs_event_http.useSearchParams)(); if (isItem) { const p = urlSearchParams(); const value = p.get(name); return value === null ? undefined : value; } const json = jsonSearchParams(); return Object.keys(json).length > 0 ? json : undefined; }, _name)); } function Url() { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useRequest)().url || "", "url"); } function Method() { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useRequest)().method, "http_method"); } function Req() { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useRequest)().rawRequest, "request"); } function Res(opts) { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useResponse)().rawResponse(opts), "response"); } function ReqId() { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useRequest)().reqId(), "reqId"); } function Ip(opts) { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useRequest)().getIp(opts), "ip"); } function IpList() { return (0, moost.Resolve)(() => (0, __wooksjs_event_http.useRequest)().getIpList(), "ipList"); } function Body() { return (0, moost.getMoostMate)().apply((0, moost.getMoostMate)().decorate("paramSource", "BODY"), (0, moost.Resolve)(() => (0, __wooksjs_http_body.useBody)().parseBody(), "body")); } function RawBody() { return (0, moost.Resolve)(() => (0, __wooksjs_http_body.useBody)().rawBody(), "body"); } //#endregion //#region packages/event-http/src/decorators/set.decorator.ts const setHeaderInterceptor = (name, value, opts) => { const fn = (_before, after, onError) => { const h = (0, __wooksjs_event_http.useSetHeader)(name); const status = (0, __wooksjs_event_http.useStatus)(); const cb = () => { if ((!h.value || opts?.force) && (!opts?.status || opts.status === status.value)) h.value = value; }; if (opts?.when !== "error") after(cb); if (opts?.when === "always" || opts?.when === "error") onError(cb); }; fn.priority = moost.TInterceptorPriority.AFTER_ALL; return fn; }; function SetHeader(...args) { return (0, moost.Intercept)(setHeaderInterceptor(...args)); } const setCookieInterceptor = (name, value, attrs) => { const fn = (before, after) => { const { setCookie, getCookie } = (0, __wooksjs_event_http.useSetCookies)(); after(() => { if (!getCookie(name)) setCookie(name, value, attrs); }); }; fn.priority = moost.TInterceptorPriority.AFTER_ALL; return fn; }; function SetCookie(...args) { return (0, moost.Intercept)(setCookieInterceptor(...args)); } const setStatusInterceptor = (code, opts) => (0, moost.defineInterceptorFn)((before, after) => { const status = (0, __wooksjs_event_http.useStatus)(); after(() => { if (!status.isDefined || opts?.force) status.value = code; }); }); function SetStatus(...args) { return (0, moost.Intercept)(setStatusInterceptor(...args)); } //#endregion //#region packages/event-http/src/decorators/limits.decorator.ts const globalBodySizeLimit = (n) => (0, moost.defineInterceptorFn)(() => { (0, __wooksjs_event_http.useRequest)().setMaxInflated(n); }, moost.TInterceptorPriority.BEFORE_ALL); const globalCompressedBodySizeLimit = (n) => (0, moost.defineInterceptorFn)(() => { (0, __wooksjs_event_http.useRequest)().setMaxCompressed(n); }, moost.TInterceptorPriority.BEFORE_ALL); const globalBodyReadTimeoutMs = (n) => (0, moost.defineInterceptorFn)(() => { (0, __wooksjs_event_http.useRequest)().setReadTimeoutMs(n); }, moost.TInterceptorPriority.BEFORE_ALL); const BodySizeLimit = (n) => (0, moost.Intercept)(globalBodySizeLimit(n)); const CompressedBodySizeLimit = (n) => (0, moost.Intercept)(globalCompressedBodySizeLimit(n)); const BodyReadTimeoutMs = (n) => (0, moost.Intercept)(globalBodyReadTimeoutMs(n)); //#endregion //#region packages/event-http/src/event-http.ts function _define_property(obj, key, value) { if (key in obj) Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); else obj[key] = value; return obj; } const LOGGER_TITLE = "moost-http"; const CONTEXT_TYPE = "HTTP"; var MoostHttp = class { getHttpApp() { return this.httpApp; } getServerCb() { return this.httpApp.getServerCb(); } listen(port, hostname, backlog, listeningListener) { return this.httpApp.listen(port, hostname, backlog, listeningListener); } async onNotFound() { return (0, moost.defineMoostEventHandler)({ loggerTitle: LOGGER_TITLE, getIterceptorHandler: () => this.moost?.getGlobalInterceptorHandler(), getControllerInstance: () => this.moost, callControllerMethod: () => new __wooksjs_event_http.HttpError(404, "Resource Not Found"), targetPath: "", handlerType: "__SYSTEM__" })(); } onInit(moost$1) { this.moost = moost$1; } getProvideRegistry() { return (0, __prostojs_infact.createProvideRegistry)([__wooksjs_event_http.WooksHttp, () => this.getHttpApp()], ["WooksHttp", () => this.getHttpApp()], [http.Server, () => this.getHttpApp().getServer()], [https.Server, () => this.getHttpApp().getServer()]); } getLogger() { return this.getHttpApp().getLogger("[moost-http]"); } bindHandler(opts) { let fn; for (const handler of opts.handlers) { if (handler.type !== "HTTP") continue; const httpPath = handler.path; const path = typeof httpPath === "string" ? httpPath : typeof opts.method === "string" ? opts.method : ""; const targetPath = `${`${opts.prefix || ""}/${path}`.replace(/\/\/+/g, "/")}${path.endsWith("//") ? "/" : ""}`; fn = (0, moost.defineMoostEventHandler)({ contextType: CONTEXT_TYPE, loggerTitle: LOGGER_TITLE, getIterceptorHandler: opts.getIterceptorHandler, getControllerInstance: opts.getInstance, controllerMethod: opts.method, resolveArgs: opts.resolveArgs, manualUnscope: true, hooks: { init: ({ unscope }) => { const { rawRequest } = (0, __wooksjs_event_http.useRequest)(); rawRequest.on("end", unscope); } }, targetPath, handlerType: handler.type }); const routerBinding = this.httpApp.on(handler.method, targetPath, fn); const { getPath: pathBuilder } = routerBinding; const methodMeta = (0, moost.getMoostMate)().read(opts.fakeInstance, opts.method) || {}; const id = methodMeta.id || opts.method; if (id) { const methods = this.pathBuilders[id] = this.pathBuilders[id] || {}; if (handler.method === "*") { methods.GET = pathBuilder; methods.PUT = pathBuilder; methods.PATCH = pathBuilder; methods.POST = pathBuilder; methods.DELETE = pathBuilder; } else methods[handler.method] = pathBuilder; } opts.logHandler(`${"\x1B[36m"}(${handler.method})${"\x1B[32m"}${targetPath}`); const args = routerBinding.getArgs(); const params = {}; args.forEach((a) => params[a] = `{${a}}`); opts.register(handler, routerBinding.getPath(params), args); } } constructor(httpApp) { _define_property(this, "name", "http"); _define_property(this, "httpApp", void 0); _define_property(this, "pathBuilders", {}); _define_property(this, "moost", void 0); if (httpApp && httpApp instanceof __wooksjs_event_http.WooksHttp) this.httpApp = httpApp; else if (httpApp) this.httpApp = (0, __wooksjs_event_http.createHttpApp)({ ...httpApp, onNotFound: this.onNotFound.bind(this) }); else this.httpApp = (0, __wooksjs_event_http.createHttpApp)({ onNotFound: this.onNotFound.bind(this) }); } }; //#endregion exports.All = All exports.Authorization = Authorization exports.Body = Body exports.BodyReadTimeoutMs = BodyReadTimeoutMs exports.BodySizeLimit = BodySizeLimit exports.CompressedBodySizeLimit = CompressedBodySizeLimit exports.Cookie = Cookie exports.CookieAttrsHook = CookieAttrsHook exports.CookieHook = CookieHook exports.Delete = Delete exports.Get = Get exports.Header = Header exports.HeaderHook = HeaderHook Object.defineProperty(exports, 'HttpError', { enumerable: true, get: function () { return __wooksjs_event_http.HttpError; } }); exports.HttpMethod = HttpMethod exports.Ip = Ip exports.IpList = IpList exports.Method = Method exports.MoostHttp = MoostHttp exports.Patch = Patch exports.Post = Post exports.Put = Put exports.Query = Query exports.RawBody = RawBody exports.Req = Req exports.ReqId = ReqId exports.Res = Res exports.SetCookie = SetCookie exports.SetHeader = SetHeader exports.SetStatus = SetStatus exports.StatusHook = StatusHook exports.Url = Url exports.globalBodyReadTimeoutMs = globalBodyReadTimeoutMs exports.globalBodySizeLimit = globalBodySizeLimit exports.globalCompressedBodySizeLimit = globalCompressedBodySizeLimit Object.defineProperty(exports, 'useHttpContext', { enumerable: true, get: function () { return __wooksjs_event_http.useHttpContext; } });