@cleverbrush/server 3.1.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +150 -0
- package/dist/CacheTag.d.ts +76 -0
- package/dist/Endpoint.d.ts +169 -39
- package/dist/Server.d.ts +3 -0
- package/dist/chunk-KDTWU6PS.js +2 -0
- package/dist/chunk-KDTWU6PS.js.map +1 -0
- package/dist/contract.d.ts +106 -0
- package/dist/contract.js +1 -1
- package/dist/contract.js.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/middlewares/Idempotency.d.ts +52 -0
- package/dist/middlewares/ResponseCache.d.ts +50 -0
- package/dist/types.d.ts +45 -0
- package/package.json +6 -4
- package/dist/chunk-W3HQGZZH.js +0 -2
- package/dist/chunk-W3HQGZZH.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as me,b as oe,c as ge,d as ye,e as be,f as Se,g as Re,h as ve}from"./chunk-W3HQGZZH.js";var P=class{static ok(e,t){return new v(e,200,t)}static created(e,t,r){let n={...r};return t&&(n.location=t),new v(e,201,n)}static accepted(e,t){return new v(e,202,t)}static noContent(){return new D}static badRequest(e,t){return new v(e,400,t)}static unauthorized(e,t){return new v(e,401,t)}static forbidden(e,t){return new v(e,403,t)}static notFound(e,t){return new v(e,404,t)}static conflict(e,t){return new v(e,409,t)}static redirect(e,t=!1){return new _(e,t)}static json(e,t=200,r){return new v(e,t,r)}static file(e,t,r="application/octet-stream"){return new j(e,t,r)}static content(e,t,r=200){return new q(e,t,r)}static stream(e,t,r){return new H(e,t,r)}static status(e,t){return new O(e,t)}},v=class extends P{body;status;headers;constructor(e,t=200,r){super(),this.body=e,this.status=t,this.headers=r??{}}async executeAsync(e,t,r){for(let[n,o]of Object.entries(this.headers))t.setHeader(n,o);if(this.body===null||this.body===void 0){t.writeHead(this.status),t.end();return}t.writeHead(this.status,{"content-type":"application/json"}),t.end(JSON.stringify(this.body))}},j=class extends P{content;fileName;contentType;constructor(e,t,r="application/octet-stream"){super(),this.content=e,this.fileName=t,this.contentType=r}async executeAsync(e,t,r){t.writeHead(200,{"content-type":this.contentType,"content-disposition":`attachment; filename="${this.fileName}"`,"content-length":String(this.content.byteLength)}),t.end(this.content)}},q=class extends P{body;contentType;status;constructor(e,t,r=200){super(),this.body=e,this.contentType=t,this.status=r}async executeAsync(e,t,r){t.writeHead(this.status,{"content-type":this.contentType}),t.end(this.body)}},H=class extends P{readable;contentType;fileName;constructor(e,t,r){super(),this.readable=e,this.contentType=t,this.fileName=r}async executeAsync(e,t,r){let n={"content-type":this.contentType};this.fileName&&(n["content-disposition"]=`attachment; filename="${this.fileName}"`),t.writeHead(200,n),await new Promise((o,i)=>{this.readable.on("error",i),t.on("error",i),this.readable.on("end",o),this.readable.pipe(t,{end:!0})})}},O=class extends P{status;headers;constructor(e,t){super(),this.status=e,this.headers=t??{}}async executeAsync(e,t,r){t.writeHead(this.status,this.headers),t.end()}},_=class extends P{url;permanent;constructor(e,t=!1){super(),this.url=e,this.permanent=t}async executeAsync(e,t,r){t.writeHead(this.permanent?301:302,{location:this.url}),t.end()}},D=class extends P{async executeAsync(e,t,r){t.writeHead(204),t.end()}};var we={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",415:"Unsupported Media Type",422:"Unprocessable Content",500:"Internal Server Error",503:"Service Unavailable"};function g(s,e,t,r){return{type:`https://httpstatuses.com/${s}`,status:s,title:e??we[s]??"Error",...t!==void 0?{detail:t}:{},...r}}function X(s){return g(400,"Bad Request","One or more validation errors occurred.",{errors:s})}function S(s){return JSON.stringify(s)}var R="application/problem+json";var w=class extends Error{status;title;detail;extensions;constructor(e,t,r,n){super(r??t??`HTTP ${e}`),this.name="HttpError",this.status=e,this.title=t??`HTTP ${e}`,this.detail=r,this.extensions=n}toProblemDetails(){return g(this.status,this.title,this.detail,this.extensions)}},Y=class extends w{constructor(e){super(404,"Not Found",e),this.name="NotFoundError"}},Z=class extends w{constructor(e){super(400,"Bad Request",e),this.name="BadRequestError"}},G=class extends w{constructor(e){super(401,"Unauthorized",e),this.name="UnauthorizedError"}},Q=class extends w{constructor(e){super(403,"Forbidden",e),this.name="ForbiddenError"}},K=class extends w{constructor(e){super(409,"Conflict",e),this.name="ConflictError"}};import{URL as Pe}from"url";import{any as te,boolean as Te,func as se,object as xe,promise as ie,record as re,string as C}from"@cleverbrush/schema";function T(s){return JSON.parse(s,(e,t)=>{if(!(e==="__proto__"||e==="constructor"))return t})}function x(s,e=64){ee(s,0,e)}function ee(s,e,t){if(!(s===null||typeof s!="object")){if(e>=t)throw new Error(`JSON nesting depth exceeds maximum of ${t}`);if(Array.isArray(s))for(let r of s)ee(r,e+1,t);else for(let r of Object.values(s))ee(r,e+1,t)}}var Ce=xe({method:C(),url:C(),pathParams:re(C(),C()),queryParams:re(C(),C()),headers:re(C(),C()),items:te(),body:se().hasReturnType(ie(te())),json:se().hasReturnType(ie(te())),responded:Te()}),E=5*1024*1024,k=class{request;response;url;method;headers;items=new Map;maxBodySize;#e={};_queryParams;#t;#r=null;#i=!1;#o=void 0;#d=!1;responded=!1;principal=void 0;constructor(e,t,r){this.request=e,this.response=t,this.method=(e.method??"GET").toUpperCase(),this.maxBodySize=r??E;let n=e.url??"/";this.url=new Pe(n,`http://${e.headers.host??"localhost"}`);let o={};for(let[i,c]of Object.entries(e.headers))typeof c=="string"?o[i]=c:Array.isArray(c)&&(o[i]=c.join(", "));this.headers=o}get pathParams(){return this.#e}set pathParams(e){this.#e=e}get queryParams(){if(this._queryParams)return this._queryParams;let e={};for(let[t,r]of this.url.searchParams)e[t]=r;return e}get services(){return this.#t}set services(e){this.#t=e}async body(){return this.#i?this.#r:(this.#r=await new Promise((e,t)=>{let r=[],n=0;this.request.on("data",o=>{if(n+=o.length,n>this.maxBodySize){this.request.destroy(),t(new w(413,"Payload Too Large"));return}r.push(o)}),this.request.on("end",()=>e(Buffer.concat(r))),this.request.on("error",t)}),this.#i=!0,this.#r)}async json(){if(this.#d)return this.#o;let t=(await this.body()).toString("utf-8");return t.length>0&&(this.#o=T(t),x(this.#o)),this.#d=!0,this.#o}};import*as $ from"http";import*as fe from"https";import{AuthorizationService as Me,PolicyBuilder as Ne,Principal as U,parseCookies as je,requireRole as qe}from"@cleverbrush/auth";import{ServiceCollection as He}from"@cleverbrush/di";import{WebSocketServer as Oe}from"ws";var Ae={mimeType:"application/json",serialize(s){return JSON.stringify(s)},deserialize(s){let e=T(s);return x(e),e}};function ke(s){return s.split(",").map(e=>{let t=e.trim(),[r,...n]=t.split(";").map(i=>i.trim()),o=1;for(let i of n){let[c,d]=i.split("=");c?.trim()==="q"&&d&&(o=parseFloat(d),Number.isNaN(o)&&(o=1))}return{mimeType:r.toLowerCase(),quality:o}}).sort((e,t)=>t.quality-e.quality)}var I=class{#e=new Map;constructor(){this.register(Ae)}register(e){this.#e.set(e.mimeType.toLowerCase(),e)}selectResponseHandler(e){if(!e)return this.#e.get("application/json")??null;let t=ke(e);for(let{mimeType:r}of t){if(r==="*/*")return this.#e.get("application/json")??null;let n=this.#e.get(r);if(n)return n}return null}selectRequestHandler(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return this.#e.get(t)??null}};var M=class{#e=[];add(e){this.#e.push(e)}async execute(e,t){let r=0,n=async()=>{if(r<this.#e.length){let o=this.#e[r++];await o(e,n)}else await t()};await n()}};function ae(s){return s.bodySchema!=null}async function de(s,e,t,r){let n=[],o={};if(o.context=t,s.authRoles!==null&&t.principal!==void 0&&(o.principal=t.principal),e&&Object.keys(e).length>0&&(o.params=e),s.bodySchema){let i=await s.bodySchema.validateAsync(r,{doNotStopOnFirstError:!0});if(i.valid)o.body=i.object;else{let c=typeof i.getInvalidProperties=="function"?i.getInvalidProperties:null,d=!1;if(c)for(let a of c()){let l=a.descriptor.toJsonPointer();for(let h of a.errors)n.push({pointer:`/body${l}`,detail:h}),d=!0}if(!d)for(let a of i.errors??[])n.push({pointer:"/body",detail:a.message})}}if(s.querySchema){let i=s.querySchema.introspect();if(i.type!=="object"||!i.properties)throw new Error("Endpoint query schema must be an object schema whose properties map to query parameter names.");let c=i.properties,d={};for(let[a,l]of Object.entries(c)){let h=t.queryParams[a],u=await l.validateAsync(h,{doNotStopOnFirstError:!0});if(u.valid)d[a]=u.object;else for(let y of u.errors??[])n.push({pointer:`/query/${a}`,detail:y.message})}o.query=d}if(s.headerSchema){let i=s.headerSchema.introspect();if(i.type!=="object"||!i.properties)throw new Error("Endpoint headers schema must be an object schema whose properties map to header names.");let c=i.properties,d={};for(let[a,l]of Object.entries(c)){let h=t.headers[a.toLowerCase()],u=await l.validateAsync(h,{doNotStopOnFirstError:!0});if(u.valid)d[a]=u.object;else for(let y of u.errors??[])n.push({pointer:`/headers/${a}`,detail:y.message})}o.headers=d}if(n.length>0)return{valid:!1,problemDetails:X(n)};if(s.serviceSchemas){if(!t.services)throw new Error("Endpoint declares .inject() dependencies but no service provider is available. Register services via createServer().services() before handling this endpoint.");let i={};for(let[c,d]of Object.entries(s.serviceSchemas))i[c]=t.services.get(d);return{valid:!0,args:[o,i]}}return{valid:!0,args:[o]}}function B(s){let e=decodeURI(s);return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function ce(s){return typeof s!="string"&&typeof s.validate=="function"}var J=class{#e=new Map;#t=[];addRoute(e){let{method:t,basePath:r,pathTemplate:n}=e.endpoint,o=t.toUpperCase(),c={basePath:B(r),routePath:n,registration:e};this.#e.has(o)||this.#e.set(o,[]),this.#e.get(o).push(c)}match(e,t){let r;try{r=B(t)}catch{return{match:null,methodNotAllowed:!1,badRequest:!0}}let n=e.toUpperCase(),o=this.#e.get(n);if(o)for(let c of o){let d=this.#r(c,r);if(d)return{match:d,methodNotAllowed:!1}}let i=[];for(let[c,d]of this.#e)if(c!==n){for(let a of d)if(this.#r(a,r)){i.push(c);break}}return i.length>0?{match:null,methodNotAllowed:!0,allowedMethods:i}:{match:null,methodNotAllowed:!1}}#r(e,t){let{basePath:r,routePath:n}=e;if(r&&!t.startsWith(r))return null;let o=r?t.slice(r.length):t;if(ce(n)){let d=n.validate(o);return d.valid?{registration:e.registration,parsedPath:d.object}:null}let i=B(n);return(o.length===0?"/":o)===i?{registration:e.registration,parsedPath:null}:null}addSubscriptionRoute(e){let{basePath:t,pathTemplate:r}=e.endpoint,n=B(t);this.#t.push({basePath:n,routePath:r,registration:e})}matchSubscription(e){let t;try{t=B(e)}catch{return null}for(let r of this.#t){let{basePath:n,routePath:o}=r;if(n&&!t.startsWith(n))continue;let i=n?t.slice(n.length):t;if(ce(o)){let a=o.validate(i);if(a.valid)return{registration:r.registration,parsedPath:a.object};continue}let c=B(o);if((i.length===0?"/":i)===c)return{registration:r.registration,parsedPath:null}}return null}};import{Readable as Be,Writable as Ee}from"stream";var F=class extends Be{method;url;headers;socket=null;#e;#t=!1;constructor(e){super(),this.method=e.method,this.url=e.url;let t={};for(let[r,n]of Object.entries(e.headers??{}))t[r.toLowerCase()]=n;this.headers={host:"localhost",...t},this.#e=e.body!=null&&e.body.length>0?Buffer.from(e.body,"utf-8"):Buffer.alloc(0)}_read(){this.#t||(this.#t=!0,this.#e.length>0&&this.push(this.#e),this.push(null))}},z=class extends Ee{statusCode=200;headersSent=!1;#e=[];#t={};#r=200;_write(e,t,r){this.#e.push(Buffer.isBuffer(e)?e:Buffer.from(e)),r()}writeHead(e,t){if(this.#r=e,this.statusCode=e,t!=null&&typeof t=="object"&&!Array.isArray(t))for(let[r,n]of Object.entries(t))this.#t[r.toLowerCase()]=Array.isArray(n)?n.join(", "):String(n);return this.headersSent=!0,this}setHeader(e,t){return this.#t[e.toLowerCase()]=Array.isArray(t)?t.join(", "):String(t),this}getHeader(e){return this.#t[e.toLowerCase()]}end(e,...t){if(e!=null&&typeof e!="function"){let r=Buffer.isBuffer(e)||e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf-8");this.#e.push(r),super.end(...t)}else typeof e=="function"?super.end(e):super.end(...t);return this}toResult(){return{status:this.#r,headers:{...this.#t},body:Buffer.concat(this.#e).toString("utf-8")}}};function le(s){return{type:"message",data:s}}function ue(s,e){return{type:"tracked",id:s,data:e}}function pe(){return{type:"pong"}}function A(s,e){return{type:"error",code:s,message:e}}function he(s){let e;try{e=T(s),x(e)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;return t.type==="ping"?{type:"ping"}:t.type==="message"&&"data"in t?{type:"message",data:t.data}:null}var L=class{#e=new He;#t=[];#r=[];#i=[];#o=[];#d=new I;#a={};#s=null;#n=null;#c=!1;#l=null;services(e){return e(this.#e),this}use(e){return this.#o.push(e),this}contentType(e){return this.#d.register(e),this}useAuthentication(e){return this.#s=e,this}useAuthorization(e){return this.#n=e??{},this}withHealthcheck(){return this.#c=!0,this}useBatching(e={}){return this.#l=e,this}handle(e,t,r){return this.#t.push({endpoint:e.introspect(),handler:t,middlewares:r?.middlewares}),this}handleAll(e){for(let t of e._entries)this.#t.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});for(let t of e._subscriptions)this.#r.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});return this}getRegistrations(){return[...this.#t]}getSubscriptionRegistrations(){return[...this.#r]}webhook(e){return this.#i.push(e),this}getWebhooks(){return[...this.#i]}getAuthenticationConfig(){return this.#s}async listen(e,t){let r=new J;for(let l of this.#t)r.addRoute(l);for(let l of this.#r)r.addSubscriptionRoute(l);let n=this.#e.buildServiceProvider({validateScopes:!1}),o=[];if(this.#s&&o.push(Je(this.#s)),this.#n!==null){let l=new Map;if(this.#n.policies)for(let[u,y]of Object.entries(this.#n.policies)){let p=new Ne;y(p),l.set(u,p.build(u))}let h=new Me(l);o.push(Fe(h,this.#s))}let i=[...o,...this.#o],c=new W(r,n,this.#d,i,this.#c,this.#r.length>0,this.#l,this.#a.maxBodySize),d=e??this.#a.port??3e3,a=t??this.#a.host??"0.0.0.0";return await c.start(d,a,this.#a),c}},_e=1024,W=class{#e;#t;#r;#i;#o;#d;#a;#s;#n=null;#c=null;#l=new Set;constructor(e,t,r,n,o=!1,i=!1,c=null,d=E){this.#e=e,this.#t=t,this.#r=r,this.#i=n,this.#o=o,this.#d=i,this.#a=c,this.#s=d}async start(e,t,r){let n=(o,i)=>{this.#u(o,i).catch(c=>{i.headersSent||(i.writeHead(500,{"content-type":R}),i.end(S(g(500))))})};r.https?this.#n=fe.createServer({key:r.https.key,cert:r.https.cert},n):this.#n=$.createServer(n),await new Promise(o=>{this.#n.listen(e,t,o)}),this.#d&&(this.#c=new Oe({noServer:!0,maxPayload:this.#s}),this.#n.on("upgrade",(o,i,c)=>{let d=new URL(o.url??"/",`http://${o.headers.host??"localhost"}`).pathname,a=this.#e.matchSubscription(d);if(!a){i.write(`HTTP/1.1 404 Not Found\r
|
|
1
|
+
import{a as be,b as Re,c as Se,d as ve,e as oe,f as we,g as Pe,h as Te,i as Ce,j as xe,k as Ae,l as Be,m as ke,n as Ee,o as Me}from"./chunk-KDTWU6PS.js";var T=class{static ok(e,t){return new w(e,200,t)}static created(e,t,r){let n={...r};return t&&(n.location=t),new w(e,201,n)}static accepted(e,t){return new w(e,202,t)}static noContent(){return new D}static badRequest(e,t){return new w(e,400,t)}static unauthorized(e,t){return new w(e,401,t)}static forbidden(e,t){return new w(e,403,t)}static notFound(e,t){return new w(e,404,t)}static conflict(e,t){return new w(e,409,t)}static redirect(e,t=!1){return new F(e,t)}static json(e,t=200,r){return new w(e,t,r)}static file(e,t,r="application/octet-stream"){return new N(e,t,r)}static content(e,t,r=200){return new O(e,t,r)}static stream(e,t,r){return new q(e,t,r)}static status(e,t){return new _(e,t)}},w=class extends T{body;status;headers;constructor(e,t=200,r){super(),this.body=e,this.status=t,this.headers=r??{}}async executeAsync(e,t,r){for(let[n,o]of Object.entries(this.headers))t.setHeader(n,o);if(this.body===null||this.body===void 0){t.writeHead(this.status),t.end();return}t.writeHead(this.status,{"content-type":"application/json"}),t.end(JSON.stringify(this.body))}},N=class extends T{content;fileName;contentType;constructor(e,t,r="application/octet-stream"){super(),this.content=e,this.fileName=t,this.contentType=r}async executeAsync(e,t,r){let n=this.fileName,o=n.replace(/[^\x20-\x7E]/g,"_"),s=o===n?`attachment; filename="${n}"`:`attachment; filename="${o}"; filename*=UTF-8''${encodeURIComponent(n)}`;t.writeHead(200,{"content-type":this.contentType,"content-disposition":s,"content-length":String(this.content.byteLength)}),t.end(this.content)}},O=class extends T{body;contentType;status;constructor(e,t,r=200){super(),this.body=e,this.contentType=t,this.status=r}async executeAsync(e,t,r){t.writeHead(this.status,{"content-type":this.contentType}),t.end(this.body)}},q=class extends T{readable;contentType;fileName;constructor(e,t,r){super(),this.readable=e,this.contentType=t,this.fileName=r}async executeAsync(e,t,r){let n={"content-type":this.contentType};this.fileName&&(n["content-disposition"]=`attachment; filename="${this.fileName}"`),t.writeHead(200,n),await new Promise((o,s)=>{this.readable.on("error",s),t.on("error",s),this.readable.on("end",o),this.readable.pipe(t,{end:!0})})}},_=class extends T{status;headers;constructor(e,t){super(),this.status=e,this.headers=t??{}}async executeAsync(e,t,r){t.writeHead(this.status,this.headers),t.end()}},F=class extends T{url;permanent;constructor(e,t=!1){super(),this.url=e,this.permanent=t}async executeAsync(e,t,r){t.writeHead(this.permanent?301:302,{location:this.url}),t.end()}},D=class extends T{async executeAsync(e,t,r){t.writeHead(204),t.end()}};var je={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",415:"Unsupported Media Type",422:"Unprocessable Content",500:"Internal Server Error",503:"Service Unavailable"};function R(i,e,t,r){return{type:`https://httpstatuses.com/${i}`,status:i,title:e??je[i]??"Error",...t!==void 0?{detail:t}:{},...r}}function G(i){return R(400,"Bad Request","One or more validation errors occurred.",{errors:i})}function S(i){return JSON.stringify(i)}var v="application/problem+json";var P=class extends Error{status;title;detail;extensions;constructor(e,t,r,n){super(r??t??`HTTP ${e}`),this.name="HttpError",this.status=e,this.title=t??`HTTP ${e}`,this.detail=r,this.extensions=n}toProblemDetails(){return R(this.status,this.title,this.detail,this.extensions)}},X=class extends P{constructor(e){super(404,"Not Found",e),this.name="NotFoundError"}},K=class extends P{constructor(e){super(400,"Bad Request",e),this.name="BadRequestError"}},Y=class extends P{constructor(e){super(401,"Unauthorized",e),this.name="UnauthorizedError"}},Z=class extends P{constructor(e){super(403,"Forbidden",e),this.name="ForbiddenError"}},Q=class extends P{constructor(e){super(409,"Conflict",e),this.name="ConflictError"}};function He(i){return["POST","PUT","DELETE","PATCH"].includes(i.toUpperCase())}var Ne=6e4;function Oe(i={}){let{ttl:e=864e5,headerName:t="x-idempotency-key",skip:r=s=>!He(s.method)}=i,n=new Map,o=setInterval(()=>{let s=Date.now();for(let[c,d]of n)d.expiresAt<=s&&n.delete(c)},Ne);return o.unref&&o.unref(),async(s,c)=>{if(r(s))return c();let d=s.headers[t]??s.headers[t.toLowerCase()];if(!d||typeof d!="string"||d.length===0)return c();let a=n.get(d);if(a)if(a.expiresAt<=Date.now())n.delete(d);else{let u=s.response;u.writeHead(a.status,a.headers),u.end(a.body),s.responded=!0;return}let h=s.response.writeHead.bind(s.response),f=s.response.end.bind(s.response),l=200,y={},m=[];if(s.response.writeHead=function(u,...p){return l=u,p.length>0&&(y=p[0]),h(u,...p)},s.response.end=function(u,...p){return u&&m.push(Buffer.isBuffer(u)?u:Buffer.from(u)),f(u,...p)},await c(),l>=200&&l<500){let u=Buffer.concat(m);n.set(d,{status:l,headers:y,body:u,expiresAt:Date.now()+e})}}}function qe(i){return["POST","PUT","DELETE","PATCH"].includes(i.toUpperCase())}function ie(i,e){return i.map(t=>{let r=[];for(let[n,o]of Object.entries(t.properties).sort(([s],[c])=>s.localeCompare(c))){let s=o.getValue(e);s.success&&s.value!==void 0&&r.push(`${n}=${String(s.value)}`)}return r.length>0?`${t.name}:${r.join(",")}`:t.name})}function _e(i={}){let{ttlByTag:e={},defaultTtl:t=6e4}=i,r=new Map;return async(n,o)=>{let c=n.items.get("__endpoint_meta")?.cacheTags??[];if(c.length===0)return o();if(qe(n.method)){if(await o(),n.response.statusCode>=200&&n.response.statusCode<300){let d=n.items.get("__raw_body"),a={params:n.pathParams??{},body:d,query:n.queryParams??{},headers:n.headers??{}},h=ie(c,a);for(let f of c){for(let[l]of r)(h.includes(l)||h.some(y=>l.startsWith(f.name)))&&r.delete(l);for(let[l]of r)l.startsWith(f.name)&&r.delete(l)}}return}if(n.method==="GET"){let d={params:n.pathParams??{},body:void 0,query:n.queryParams??{},headers:n.headers??{}},a=ie(c,d);for(let u of a){let p=r.get(u);if(p&&p.expiresAt>Date.now()){let g=n.response;g.writeHead(p.status,p.headers),g.end(p.body),n.responded=!0;return}p&&r.delete(u)}let h=n.response.writeHead.bind(n.response),f=n.response.end.bind(n.response),l=200,y={},m=[];if(n.response.writeHead=function(u,...p){return l=u,p.length>0&&(y=p[0]),h(u,...p)},n.response.end=function(u,...p){return u&&m.push(Buffer.isBuffer(u)?u:Buffer.from(u)),f(u,...p)},await o(),l>=200&&l<300){let u=Buffer.concat(m),p=c.reduce((g,b)=>{let C=e[b.name]!==void 0?e[b.name]:t;return C>g?C:g},0);if(p>0)for(let g of a)r.set(g,{status:l,headers:y,body:u,expiresAt:Date.now()+p})}return}return o()}}import{URL as Fe}from"url";import{any as te,boolean as De,func as ae,object as Ie,promise as de,record as re,string as B}from"@cleverbrush/schema";function x(i){return JSON.parse(i,(e,t)=>{if(!(e==="__proto__"||e==="constructor"))return t})}function A(i,e=64){ee(i,0,e)}function ee(i,e,t){if(!(i===null||typeof i!="object")){if(e>=t)throw new Error(`JSON nesting depth exceeds maximum of ${t}`);if(Array.isArray(i))for(let r of i)ee(r,e+1,t);else for(let r of Object.values(i))ee(r,e+1,t)}}var Je=Ie({method:B(),url:B(),pathParams:re(B(),B()),queryParams:re(B(),B()),headers:re(B(),B()),items:te(),body:ae().hasReturnType(de(te())),json:ae().hasReturnType(de(te())),responded:De()}),j=5*1024*1024,E=class{request;response;url;method;headers;items=new Map;maxBodySize;#e={};_queryParams;#t;#r=null;#a=!1;#s=void 0;#d=!1;responded=!1;principal=void 0;constructor(e,t,r){this.request=e,this.response=t,this.method=(e.method??"GET").toUpperCase(),this.maxBodySize=r??j;let n=e.url??"/";this.url=new Fe(n,`http://${e.headers.host??"localhost"}`);let o={};for(let[s,c]of Object.entries(e.headers))typeof c=="string"?o[s]=c:Array.isArray(c)&&(o[s]=c.join(", "));this.headers=o}get pathParams(){return this.#e}set pathParams(e){this.#e=e}get queryParams(){if(this._queryParams)return this._queryParams;let e={};for(let[t,r]of this.url.searchParams)e[t]=r;return e}get services(){return this.#t}set services(e){this.#t=e}async body(){return this.#a?this.#r:(this.#r=await new Promise((e,t)=>{let r=[],n=0;this.request.on("data",o=>{if(n+=o.length,n>this.maxBodySize){this.request.destroy(),t(new P(413,"Payload Too Large"));return}r.push(o)}),this.request.on("end",()=>e(Buffer.concat(r))),this.request.on("error",t)}),this.#a=!0,this.#r)}async json(){if(this.#d)return this.#s;let t=(await this.body()).toString("utf-8");return t.length>0&&(this.#s=x(t),A(this.#s)),this.#d=!0,this.#s}};import*as V from"http";import*as ye from"https";import{AuthorizationService as $e,PolicyBuilder as Ve,Principal as W,parseCookies as Ge,requireRole as Xe}from"@cleverbrush/auth";import{ServiceCollection as Ke}from"@cleverbrush/di";import{Busboy as Ye}from"@fastify/busboy";import{WebSocketServer as Ze}from"ws";var ze={mimeType:"application/json",serialize(i){return JSON.stringify(i)},deserialize(i){let e=x(i);return A(e),e}};function Ue(i){return i.split(",").map(e=>{let t=e.trim(),[r,...n]=t.split(";").map(s=>s.trim()),o=1;for(let s of n){let[c,d]=s.split("=");c?.trim()==="q"&&d&&(o=parseFloat(d),Number.isNaN(o)&&(o=1))}return{mimeType:r.toLowerCase(),quality:o}}).sort((e,t)=>t.quality-e.quality)}var I=class{#e=new Map;constructor(){this.register(ze)}register(e){this.#e.set(e.mimeType.toLowerCase(),e)}selectResponseHandler(e){if(!e)return this.#e.get("application/json")??null;let t=Ue(e);for(let{mimeType:r}of t){if(r==="*/*")return this.#e.get("application/json")??null;let n=this.#e.get(r);if(n)return n}return null}selectRequestHandler(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return this.#e.get(t)??null}};var H=class{#e=[];add(e){this.#e.push(e)}async execute(e,t){let r=0,n=async()=>{if(r<this.#e.length){let o=this.#e[r++];await o(e,n)}else await t()};await n()}};function ce(i){return i.bodySchema!=null}async function le(i,e,t,r){let n=[],o={};if(o.context=t,i.authRoles!==null&&t.principal!==void 0&&(o.principal=t.principal),e&&Object.keys(e).length>0&&(o.params=e),i.bodySchema){let s=await i.bodySchema.validateAsync(r,{doNotStopOnFirstError:!0});if(s.valid)o.body=s.object;else{let c=typeof s.getInvalidProperties=="function"?s.getInvalidProperties:null,d=!1;if(c)for(let a of c()){let h=a.descriptor.toJsonPointer();for(let f of a.errors)n.push({pointer:`/body${h}`,detail:f}),d=!0}if(!d)for(let a of s.errors??[])n.push({pointer:"/body",detail:a.message})}}if(i.querySchema){let s=i.querySchema.introspect();if(s.type!=="object"||!s.properties)throw new Error("Endpoint query schema must be an object schema whose properties map to query parameter names.");let c=s.properties,d={};for(let[a,h]of Object.entries(c)){let f=t.queryParams[a],l=await h.validateAsync(f,{doNotStopOnFirstError:!0});if(l.valid)d[a]=l.object;else for(let y of l.errors??[])n.push({pointer:`/query/${a}`,detail:y.message})}o.query=d}if(i.headerSchema){let s=i.headerSchema.introspect();if(s.type!=="object"||!s.properties)throw new Error("Endpoint headers schema must be an object schema whose properties map to header names.");let c=s.properties,d={};for(let[a,h]of Object.entries(c)){let f=t.headers[a.toLowerCase()],l=await h.validateAsync(f,{doNotStopOnFirstError:!0});if(l.valid)d[a]=l.object;else for(let y of l.errors??[])n.push({pointer:`/headers/${a}`,detail:y.message})}o.headers=d}if(n.length>0)return{valid:!1,problemDetails:G(n)};if(i.serviceSchemas){if(!t.services)throw new Error("Endpoint declares .inject() dependencies but no service provider is available. Register services via createServer().services() before handling this endpoint.");let s={};for(let[c,d]of Object.entries(i.serviceSchemas))s[c]=t.services.get(d);return{valid:!0,args:[o,s]}}return{valid:!0,args:[o]}}function M(i){let e=decodeURI(i);return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function ue(i){return typeof i!="string"&&typeof i.validate=="function"}var J=class{#e=new Map;#t=[];addRoute(e){let{method:t,basePath:r,pathTemplate:n}=e.endpoint,o=t.toUpperCase(),c={basePath:M(r),routePath:n,registration:e};this.#e.has(o)||this.#e.set(o,[]),this.#e.get(o).push(c)}match(e,t){let r;try{r=M(t)}catch{return{match:null,methodNotAllowed:!1,badRequest:!0}}let n=e.toUpperCase(),o=this.#e.get(n);if(o)for(let c of o){let d=this.#r(c,r);if(d)return{match:d,methodNotAllowed:!1}}let s=[];for(let[c,d]of this.#e)if(c!==n){for(let a of d)if(this.#r(a,r)){s.push(c);break}}return s.length>0?{match:null,methodNotAllowed:!0,allowedMethods:s}:{match:null,methodNotAllowed:!1}}#r(e,t){let{basePath:r,routePath:n}=e;if(r&&!t.startsWith(r))return null;let o=r?t.slice(r.length):t;if(ue(n)){let d=n.validate(o);return d.valid?{registration:e.registration,parsedPath:d.object}:null}let s=M(n);return(o.length===0?"/":o)===s?{registration:e.registration,parsedPath:null}:null}addSubscriptionRoute(e){let{basePath:t,pathTemplate:r}=e.endpoint,n=M(t);this.#t.push({basePath:n,routePath:r,registration:e})}matchSubscription(e){let t;try{t=M(e)}catch{return null}for(let r of this.#t){let{basePath:n,routePath:o}=r;if(n&&!t.startsWith(n))continue;let s=n?t.slice(n.length):t;if(ue(o)){let a=o.validate(s);if(a.valid)return{registration:r.registration,parsedPath:a.object};continue}let c=M(o);if((s.length===0?"/":s)===c)return{registration:r.registration,parsedPath:null}}return null}};import{Readable as We,Writable as Le}from"stream";var z=class extends We{method;url;headers;socket=null;#e;#t=!1;constructor(e){super(),this.method=e.method,this.url=e.url;let t={};for(let[r,n]of Object.entries(e.headers??{}))t[r.toLowerCase()]=n;this.headers={host:"localhost",...t},this.#e=e.body!=null&&e.body.length>0?Buffer.from(e.body,"utf-8"):Buffer.alloc(0)}_read(){this.#t||(this.#t=!0,this.#e.length>0&&this.push(this.#e),this.push(null))}},U=class extends Le{statusCode=200;headersSent=!1;#e=[];#t={};#r=200;_write(e,t,r){this.#e.push(Buffer.isBuffer(e)?e:Buffer.from(e)),r()}writeHead(e,t){if(this.#r=e,this.statusCode=e,t!=null&&typeof t=="object"&&!Array.isArray(t))for(let[r,n]of Object.entries(t))this.#t[r.toLowerCase()]=Array.isArray(n)?n.join(", "):String(n);return this.headersSent=!0,this}setHeader(e,t){return this.#t[e.toLowerCase()]=Array.isArray(t)?t.join(", "):String(t),this}getHeader(e){return this.#t[e.toLowerCase()]}end(e,...t){if(e!=null&&typeof e!="function"){let r=Buffer.isBuffer(e)||e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf-8");this.#e.push(r),super.end(...t)}else typeof e=="function"?super.end(e):super.end(...t);return this}toResult(){return{status:this.#r,headers:{...this.#t},body:Buffer.concat(this.#e).toString("utf-8")}}};function pe(i){return{type:"message",data:i}}function he(i,e){return{type:"tracked",id:i,data:e}}function fe(){return{type:"pong"}}function k(i,e){return{type:"error",code:i,message:e}}function me(i){let e;try{e=x(i),A(e)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;return t.type==="ping"?{type:"ping"}:t.type==="message"&&"data"in t?{type:"message",data:t.data}:null}async function Qe(i,e){let t=e.maxFileCount??10,r=e.maxFileSize??10*1024*1024,n=e.allowedMimeTypes;return new Promise((o,s)=>{let c={},d={},a=[],h=0,f=Ye({headers:i.headers,limits:{fileSize:r,files:t}});f.on("field",(l,y)=>{c[l]=y}),f.on("file",(l,y,m,u,p)=>{if(h>=t){a.push({filename:m,mimeType:p,reason:`Exceeded max file count (${t})`}),y.resume();return}if(n&&!n.some(C=>C.endsWith("/*")?p.startsWith(C.slice(0,-1)):p===C)){a.push({filename:m,mimeType:p,reason:`MIME type "${p}" not allowed (allowed: ${n.join(", ")})`}),y.resume();return}h++;let g=[];y.on("data",b=>{g.push(b)}),y.on("end",()=>{let b=Buffer.concat(g);d[l]={filename:m,mimeType:p,buffer:b,size:b.length}}),y.on("error",s)}),f.on("error",s),f.on("finish",()=>o({fields:c,files:d,rejectedFiles:a})),i.pipe(f)})}var L=class{#e=new Ke;#t=[];#r=[];#a=[];#s=[];#d=new I;#o;#i=null;#n=null;#c=!1;#l=null;constructor(e={}){this.#o=e}services(e){return e(this.#e),this}use(e){return this.#s.push(e),this}contentType(e){return this.#d.register(e),this}useAuthentication(e){return this.#i=e,this}useAuthorization(e){return this.#n=e??{},this}withHealthcheck(){return this.#c=!0,this}useBatching(e={}){return this.#l=e,this}handle(e,t,r){return this.#t.push({endpoint:e.introspect(),handler:t,middlewares:r?.middlewares}),this}handleAll(e){for(let t of e._entries)this.#t.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});for(let t of e._subscriptions)this.#r.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});return this}getRegistrations(){return[...this.#t]}getSubscriptionRegistrations(){return[...this.#r]}webhook(e){return this.#a.push(e),this}getWebhooks(){return[...this.#a]}getAuthenticationConfig(){return this.#i}async listen(e,t){let r=new J;for(let h of this.#t)r.addRoute(h);for(let h of this.#r)r.addSubscriptionRoute(h);let n=this.#e.buildServiceProvider({validateScopes:!1}),o=[];if(this.#i&&o.push(nt(this.#i)),this.#n!==null){let h=new Map;if(this.#n.policies)for(let[l,y]of Object.entries(this.#n.policies)){let m=new Ve;y(m),h.set(l,m.build(l))}let f=new $e(h);o.push(st(f,this.#i))}let s=[...o,...this.#s],c=new $(r,n,this.#d,s,this.#c,this.#r.length>0,this.#l,this.#o.maxBodySize),d=e??this.#o.port??3e3,a=t??this.#o.host??"0.0.0.0";return await c.start(d,a,this.#o),c}},et=1024,$=class{#e;#t;#r;#a;#s;#d;#o;#i;#n=null;#c=null;#l=new Set;constructor(e,t,r,n,o=!1,s=!1,c=null,d=j){this.#e=e,this.#t=t,this.#r=r,this.#a=n,this.#s=o,this.#d=s,this.#o=c,this.#i=d}async start(e,t,r){let n=(o,s)=>{this.#u(o,s).catch(c=>{s.headersSent||(s.writeHead(500,{"content-type":v}),s.end(S(R(500))))})};r.https?this.#n=ye.createServer({key:r.https.key,cert:r.https.cert},n):this.#n=V.createServer(n),await new Promise(o=>{this.#n.listen(e,t,o)}),this.#d&&(this.#c=new Ze({noServer:!0,maxPayload:this.#i}),this.#n.on("upgrade",(o,s,c)=>{let d=new URL(o.url??"/",`http://${o.headers.host??"localhost"}`).pathname,a=this.#e.matchSubscription(d);if(!a){s.write(`HTTP/1.1 404 Not Found\r
|
|
2
2
|
\r
|
|
3
|
-
`),
|
|
3
|
+
`),s.destroy();return}this.#c.handleUpgrade(o,s,c,h=>{this.#f(h,o,a.registration,a.parsedPath)})}))}async close(){for(let e of this.#l)e.close(1001,"Server shutting down");this.#l.clear(),this.#c&&(await new Promise((e,t)=>{this.#c.close(r=>{r?t(r):e()})}),this.#c=null),this.#n&&(await new Promise((e,t)=>{this.#n.close(r=>{r?t(r):e()})}),this.#n=null)}get address(){let e=this.#n?.address();return!e||typeof e=="string"?null:{port:e.port,host:e.address}}async#u(e,t){let r=this.#t.createScope();try{let n=new E(e,t,this.#i),o=n.url.pathname,s=n.method;if(this.#s&&s==="GET"&&o==="/health"){t.writeHead(200),t.end();return}if(this.#o!==null&&s==="POST"&&o===(this.#o.path??"/__batch")){await this.#p(e,t);return}let c=this.#e.match(s,o);if(!c.match){if(c.badRequest){let y=R(400);t.writeHead(400,{"content-type":v}),t.end(S(y));return}if(c.methodNotAllowed){let y=R(405,"Method Not Allowed");t.writeHead(405,{"content-type":v,allow:c.allowedMethods.join(", ")}),t.end(S(y));return}let l=R(404);t.writeHead(404,{"content-type":v}),t.end(S(l));return}let{registration:d,parsedPath:a}=c.match,h=d.endpoint;if(a){let l={};ne(a,"",l),n.pathParams=l}n.services=r.serviceProvider,n.items.set("__endpoint_meta",h);let f=new H;for(let l of this.#a)f.add(l);if(d.middlewares)for(let l of d.middlewares)f.add(l);await f.execute(n,async()=>{if(n.responded)return;let l,y,m;if(ce(h)){let g=e.headers["content-type"]??"";if(h.fileUpload&&g.startsWith("multipart/form-data"))try{let b=await Qe(e,h.fileUpload);l=b.fields,y=b.files,m=b.rejectedFiles}catch{let b=R(400,"Malformed multipart request");t.writeHead(400,{"content-type":v}),t.end(S(b)),n.responded=!0;return}else if(h.fileUpload){let b=R(400,"File upload endpoint requires multipart/form-data content type");t.writeHead(400,{"content-type":v}),t.end(S(b)),n.responded=!0;return}else{let b=this.#r.selectRequestHandler(g);if(b){let se=(await n.body()).toString("utf-8");if(se.length>0)try{l=b.deserialize(se)}catch{let ge=R(400,"Malformed request body");t.writeHead(400,{"content-type":v}),t.end(S(ge)),n.responded=!0;return}}else if(g){let C=R(415);t.writeHead(415,{"content-type":v}),t.end(S(C)),n.responded=!0;return}}}let u=await le(h,a,n,l);if(!u.valid){t.writeHead(400,{"content-type":v}),t.end(S(u.problemDetails)),n.responded=!0;return}if(y&&u.args.length>0){let g=u.args[0];g.files=y,m&&m.length>0&&(g.rejectedFiles=m)}let p=d.handler(...u.args);p instanceof Promise&&(p=await p),!n.responded&&(await this.#h(e,t,p),n.responded=!0)})}catch(n){if(t.headersSent)return;if(n instanceof P){let o=n.toProblemDetails();t.writeHead(o.status,{"content-type":v}),t.end(S(o))}else{console.error("[server] Unhandled error:",n);let o=R(500);t.writeHead(500,{"content-type":v}),t.end(S(o))}}finally{try{await r.asyncDispose()}catch{}}}async#p(e,t){let r=this.#o,n=r.maxSize??20,o=r.parallel??!0,s;try{let a=await rt(e,this.#i),h=x(a.toString("utf-8"));if(A(h),s=h,!Array.isArray(s?.requests))throw new Error("requests must be an array")}catch(a){if(a instanceof P&&a.status===413){let f=R(413,"Payload Too Large");t.writeHead(413,{"content-type":v}),t.end(S(f));return}let h=R(400,"Invalid batch request body");t.writeHead(400,{"content-type":v}),t.end(S(h));return}if(s.requests.length>n){let a=R(400,`Batch size ${s.requests.length} exceeds maximum of ${n}`);t.writeHead(400,{"content-type":v}),t.end(S(a));return}let c=async a=>{let h=new z({method:(a.method??"GET").toUpperCase(),url:a.url,headers:a.headers??{},body:a.body}),f=new U;return await this.#u(h,f),f.toResult()},d;if(o)d=await Promise.all(s.requests.map(c));else{d=[];for(let a of s.requests)d.push(await c(a))}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({responses:d}))}async#h(e,t,r){r instanceof T?await r.executeAsync(e,t,this.#r):r==null?(t.writeHead(204),t.end()):await new w(r,200).executeAsync(e,t,this.#r)}#f(e,t,r,n){this.#l.add(e);let o=this.#t.createScope(),s=new AbortController,c=r.endpoint,d=new V.ServerResponse(t),a=new E(t,d);if(n){let f={};ne(n,"",f),a.pathParams=f}a.services=o.serviceProvider,a.items.set("__endpoint_meta",c);let h=new H;for(let f of this.#a)h.add(f);if(r.middlewares)for(let f of r.middlewares)h.add(f);h.execute(a,async()=>{if(a.responded){e.close(1008,"Unauthorized");return}this.#m(e,a,c,r.handler,n,o,s)}).catch(()=>{e.close(1011,"Internal Server Error")}),e.on("close",()=>{this.#l.delete(e),s.abort(),o.asyncDispose().catch(()=>{})}),e.on("error",()=>{this.#l.delete(e),s.abort(),o.asyncDispose().catch(()=>{})})}#m(e,t,r,n,o,s,c){let d=[],a=null,h=!1,f={[Symbol.asyncIterator](){return{next(){return d.length>0?Promise.resolve({value:d.shift(),done:!1}):h?Promise.resolve({value:void 0,done:!0}):new Promise(m=>{a=()=>{a=null,d.length>0?m({value:d.shift(),done:!1}):m({value:void 0,done:!0})}})},return(){return h=!0,Promise.resolve({value:void 0,done:!0})}}}};e.on("message",m=>{let u=typeof m=="string"?m:m.toString("utf-8"),p=me(u);if(!p){e.send(JSON.stringify(k(400,"Invalid frame format")));return}if(p.type==="ping"){e.send(JSON.stringify(fe()));return}if(d.length>=et){e.send(JSON.stringify(k(429,"Message queue full \u2014 slow down or reconnect"))),e.close(1008,"Message queue overflow");return}if(r.incomingSchema){let g=r.incomingSchema.validate(p.data);if(!g.valid){let b=(g.errors??[]).map(C=>C.message).join("; ");e.send(JSON.stringify(k(422,`Validation failed: ${b}`)));return}d.push(g.object)}else d.push(p.data);a&&a()}),e.on("close",()=>{h=!0,a&&a()});let l={context:t,signal:c.signal};if(o&&Object.keys(o).length>0&&(l.params=o),r.querySchema){let m={};for(let[p,g]of t.url.searchParams.entries())m[p]=g;let u=r.querySchema.validate(m);if(!u.valid){let p=(u.errors??[]).map(g=>g.message).join("; ");e.close(1002,`Query validation failed: ${p}`);return}l.query=u.object}if(r.headerSchema){let m=r.headerSchema.validate(t.headers);if(!m.valid){let u=(m.errors??[]).map(p=>p.message).join("; ");e.close(1002,`Header validation failed: ${u}`);return}l.headers=m.object}t.principal!==void 0&&(l.principal=t.principal),r.incomingSchema,l.incoming=f;let y=[l];if(r.serviceSchemas){let m={};for(let[u,p]of Object.entries(r.serviceSchemas))m[u]=s.serviceProvider.get(p);y.push(m)}(async()=>{try{let m=n(...y);for await(let u of m){if(e.readyState!==e.OPEN)break;let p;if(oe(u)){let g=r.outgoingSchema?r.outgoingSchema.validate(u.data):{valid:!0,object:u.data};if(!g.valid){e.send(JSON.stringify(k(500,"Outgoing validation failed")));continue}p=JSON.stringify(he(u.id,g.object))}else{let g=r.outgoingSchema?r.outgoingSchema.validate(u):{valid:!0,object:u};if(!g.valid){e.send(JSON.stringify(k(500,"Outgoing validation failed")));continue}p=JSON.stringify(pe(g.object))}e.send(p)}}catch(m){e.readyState===e.OPEN&&(m instanceof Error&&console.error("[server] Subscription handler error:",m),e.send(JSON.stringify(k(500,"Internal error"))),e.close(1011,"Handler error"))}})()}};function tt(i){return new L(i)}function rt(i,e=j){return new Promise((t,r)=>{let n=[],o=0;i.on("data",s=>{if(o+=s.length,o>e){i.destroy(),r(new P(413,"Payload Too Large"));return}n.push(s)}),i.on("end",()=>t(Buffer.concat(n))),i.on("error",r)})}function ne(i,e,t){for(let[r,n]of Object.entries(i)){let o=e?`${e}.${r}`:r;n!==null&&typeof n=="object"&&!Array.isArray(n)?ne(n,o,t):t[o]=String(n)}}function nt(i){let e=new Map;for(let t of i.schemes)e.set(t.name,t);return async(t,r)=>{let n=e.get(i.defaultScheme);if(!n){t.principal=W.anonymous(),await r();return}let o={headers:t.headers,cookies:Ge(t.headers.cookie??""),items:t.items},s=await n.authenticate(o);s.succeeded?t.principal=s.principal:t.principal=W.anonymous(),await r()}}function st(i,e){let t={};if(e){for(let r of e.schemes)if(r.challenge){let n=r.challenge();t[n.headerName.toLowerCase()]=n.headerValue}}return async(r,n)=>{let o=r.items.get("__endpoint_meta");if(!o||o.authRoles===null){await n();return}let s=r.principal;if(!s||!(s instanceof W)||!s.isAuthenticated){let c=R(401,"Unauthorized"),d={"content-type":v,...t};r.response.writeHead(401,d),r.response.end(S(c)),r.responded=!0;return}if(o.authRoles.length>0&&!(await i.authorize(s,[Xe(...o.authRoles)])).allowed){let d=R(403,"Forbidden");r.response.writeHead(403,{"content-type":v}),r.response.end(S(d)),r.responded=!0;return}s instanceof W&&(r.principal=s.value),await n()}}function ot(i,e){return{name:i,...e}}export{T as ActionResult,K as BadRequestError,Q as ConflictError,O as ContentResult,j as DEFAULT_MAX_BODY_SIZE,Te as EndpointBuilder,N as FileResult,Z as ForbiddenError,P as HttpError,Je as IRequestContext,w as JsonResult,D as NoContentResult,X as NotFoundError,F as RedirectResult,E as RequestContext,$ as Server,L as ServerBuilder,_ as StatusCodeResult,q as StreamResult,we as SubscriptionBuilder,Y as UnauthorizedError,_e as cacheResponse,Se as computeCacheKey,be as createCacheTagTree,Ce as createEndpoints,R as createProblemDetails,tt as createServer,G as createValidationProblemDetails,Be as defineApi,ot as defineWebhook,xe as endpoint,Oe as idempotency,Pe as mapHandlers,ke as mergeContracts,Me as omitGroups,Ee as pickGroups,Ae as route,Re as serializeTag,ve as tracked};
|
|
4
4
|
//# sourceMappingURL=index.js.map
|