@niledatabase/express 5.0.0 → 5.0.1

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/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { Server, ExtensionState } from '@niledatabase/server';
2
- import { Express, Request, Response, NextFunction } from 'express';
2
+ import { Express, Request, Response as Response$1, NextFunction } from 'express';
3
3
 
4
4
  declare function cleaner(val: string): string;
5
5
  declare const express: (app?: Express) => (instance: Server) => {
6
6
  id: string;
7
7
  onConfigure: () => void;
8
- onHandleRequest: (params: [Request, Response, NextFunction]) => Promise<void | ExtensionState.onHandleRequest>;
8
+ onHandleRequest: (params: [Request, Response$1, NextFunction]) => Promise<void | Response | ExtensionState.onHandleRequest>;
9
9
  };
10
10
 
11
11
  export { cleaner, express };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { Server, ExtensionState } from '@niledatabase/server';
2
- import { Express, Request, Response, NextFunction } from 'express';
2
+ import { Express, Request, Response as Response$1, NextFunction } from 'express';
3
3
 
4
4
  declare function cleaner(val: string): string;
5
5
  declare const express: (app?: Express) => (instance: Server) => {
6
6
  id: string;
7
7
  onConfigure: () => void;
8
- onHandleRequest: (params: [Request, Response, NextFunction]) => Promise<void | ExtensionState.onHandleRequest>;
8
+ onHandleRequest: (params: [Request, Response$1, NextFunction]) => Promise<void | Response | ExtensionState.onHandleRequest>;
9
9
  };
10
10
 
11
11
  export { cleaner, express };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var U=(s,t)=>{for(var n in t)m(s,n,{get:t[n],enumerable:!0})},b=(s,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of O(t))!C.call(s,o)&&o!==n&&m(s,o,{get:()=>t[o],enumerable:!(i=I(t,o))||i.enumerable});return s};var L=s=>b(m({},"__esModule",{value:!0}),s);var $={};U($,{cleaner:()=>x,express:()=>A});module.exports=L($);var S=require("async_hooks"),T=require("@niledatabase/server");function x(s){return s.replaceAll(/\{([^}]+)\}/g,":$1")}var w=new S.AsyncLocalStorage,A=s=>{let t=!1;return n=>{let{error:i,debug:o}=n.logger("[EXTENSION][express]"),y=e=>{w.getStore()?.set("context",e),n.withContext(e)};function q(e){s&&(o("routes configured"),s.get(e.paths.get,e.handlers.GET),s.post(e.paths.post,e.handlers.POST),s.put(e.paths.put,e.handlers.PUT),s.delete(e.paths.delete,e.handlers.DELETE))}return!t&&s&&(o("initializing express extension with middleware"),s.use((e,r,a)=>{w.run(new Map,()=>a())}),s.param("tenantId",(e,r,a,h)=>{o(`tenantId param set: ${h}`),y({tenantId:h,headers:new Headers(H(e.headers))}),a()}),s.use((e,r,a)=>{y({headers:new Headers(H(e.headers))}),a()})),t=!0,{id:"express",onConfigure:()=>{let{paths:e}=n,r={get:e.get.map(x),post:e.post.map(x),put:e.put.map(x),delete:e.delete.map(x)};o(`paths configured ${JSON.stringify(r)}`),n.paths=r,q(n)},onHandleRequest:async e=>{let[r,a,h]=e;o("handling response");let f=r.protocol+"://"+r.get("host")+r.originalUrl;try{new URL(f)}catch{throw new Error("Invalid URL \u2014 are you running Express?")}let E=r.method,g={method:E,headers:new Headers};r.headers?.cookie&&g.headers.set("cookie",r.headers.cookie),["POST","PUT"].includes(E)&&r.body&&(g.body=JSON.stringify(r.body));let P=new Request(f,g);o(`[${E}] proxy: ${f} ${JSON.stringify(g)}`);let p,N={headers:new Headers(r.headers),tenantId:r.params?.tenantId||void 0};try{p=await n.withContext(N,async d=>await d.handlers[E](P,{disableExtensions:["express"]}))}catch(d){return i(d),h()}let u;try{u=await p.clone().json()}catch{u=await p.text()}let c={};return p.headers.forEach((d,l)=>{if(!["content-length","transfer-encoding"].includes(l.toLowerCase()))if(c[l]){let R=c[l];c[l]=Array.isArray(R)?[...R,d]:[R,d]}else c[l]=d}),a.headersSent||(o("sending response"),a.status(p.status).set(c),typeof u=="string"?a.send(u):a.json(u??{})),T.ExtensionState.onHandleRequest}}}};function H(s){let t={};for(let[n,i]of Object.entries(s))typeof i=="string"?t[n]=i:Array.isArray(i)&&(t[n]=i.join(","));return t}0&&(module.exports={cleaner,express});
1
+ "use strict";var y=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var U=(s,r)=>{for(var n in r)y(s,n,{get:r[n],enumerable:!0})},b=(s,r,n,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of O(r))!C.call(s,o)&&o!==n&&y(s,o,{get:()=>r[o],enumerable:!(i=I(r,o))||i.enumerable});return s};var L=s=>b(y({},"__esModule",{value:!0}),s);var $={};U($,{cleaner:()=>E,express:()=>A});module.exports=L($);var S=require("async_hooks"),q=require("@niledatabase/server");function E(s){return s.replaceAll(/\{([^}]+)\}/g,":$1")}var w=new S.AsyncLocalStorage,A=s=>{let r=!1;return n=>{let{error:i,debug:o}=n.logger("[EXTENSION][express]"),m=e=>{w.getStore()?.set("context",e),n.withContext(e)};function T(e){s&&(o("routes configured"),s.get(e.paths.get,e.handlers.GET),s.post(e.paths.post,e.handlers.POST),s.put(e.paths.put,e.handlers.PUT),s.delete(e.paths.delete,e.handlers.DELETE))}return!r&&s&&(o("initializing express extension with middleware"),s.use((e,t,a)=>{w.run(new Map,()=>a())}),s.param("tenantId",(e,t,a,g)=>{o(`tenantId param set: ${g}`),m({tenantId:g,headers:new Headers(H(e.headers))}),a()}),s.use((e,t,a)=>{m({headers:new Headers(H(e.headers))}),a()})),r=!0,{id:"express",onConfigure:()=>{let{paths:e}=n,t={get:e.get.map(E),post:e.post.map(E),put:e.put.map(E),delete:e.delete.map(E)};o(`paths configured ${JSON.stringify(t)}`),n.paths=t,T(n)},onHandleRequest:async e=>{let[t,a,g]=e;o("handling response");let u="",f=t.method,c={method:f,headers:new Headers};if(t instanceof Request)u=t.url,c.headers=t.headers;else try{u=t.protocol+"://"+t.get("host")+t.originalUrl}catch{}try{new URL(u)}catch{throw new Error("Invalid URL \u2014 are you running Express?")}t.headers?.cookie&&c.headers.set("cookie",t.headers.cookie),["POST","PUT"].includes(f)&&t.body&&(c.body=JSON.stringify(t.body));let P=new Request(u,c);o(`[${f}] proxy: ${u} ${JSON.stringify(c)}`);let p,N={headers:new Headers(t.headers),tenantId:t.params?.tenantId||void 0};try{p=await n.withContext(N,async d=>await d.handlers[f](P,{disableExtensions:["express"]}))}catch(d){return i(d),g()}let l;try{l=await p.clone().json()}catch{l=await p.text()}let h={};return p.headers.forEach((d,x)=>{if(!["content-length","transfer-encoding"].includes(x.toLowerCase()))if(h[x]){let R=h[x];h[x]=Array.isArray(R)?[...R,d]:[R,d]}else h[x]=d}),a?(a.headersSent||(o("sending response"),a.status(p.status).set(h),typeof l=="string"?a.send(l):a.json(l??{})),q.ExtensionState.onHandleRequest):p}}}};function H(s){let r={};for(let[n,i]of Object.entries(s))typeof i=="string"?r[n]=i:Array.isArray(i)&&(r[n]=i.join(","));return r}0&&(module.exports={cleaner,express});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\nimport { IncomingHttpHeaders } from 'http';\n\nimport { PartialContext, ExtensionState, Server } from '@niledatabase/server';\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Express,\n} from 'express';\n\nexport function cleaner(val: string) {\n return val.replaceAll(/\\{([^}]+)\\}/g, ':$1');\n}\n\ntype ExpressRouteHandler = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction\n) => void | Promise<void>;\n\ntype ExpressRouteFunctions = {\n GET: ExpressRouteHandler;\n POST: ExpressRouteHandler;\n PUT: ExpressRouteHandler;\n DELETE: ExpressRouteHandler;\n};\n\ntype NileWithExpress = Server & {\n handlers: ExpressRouteFunctions;\n};\n\n// AsyncLocalStorage to persist context per request\nconst contextStore = new AsyncLocalStorage<Map<string, unknown>>();\n\n// Express extension factory\nexport const express = (app?: Express) => {\n let init = false;\n\n return (instance: Server) => {\n const { error, debug } = instance.logger('[EXTENSION][express]');\n\n // Internal context helpers - I think we delete this now?\n const setRequestContext = (context: PartialContext) => {\n contextStore.getStore()?.set('context', context);\n\n instance.withContext(context);\n };\n\n function doConfigure(server: NileWithExpress) {\n if (app) {\n debug('routes configured');\n app.get(server.paths.get, server.handlers.GET);\n app.post(server.paths.post, server.handlers.POST);\n app.put(server.paths.put, server.handlers.PUT);\n app.delete(server.paths.delete, server.handlers.DELETE);\n }\n }\n\n if (!init && app) {\n debug('initializing express extension with middleware');\n\n app.use((req, res, next) => {\n contextStore.run(new Map(), () => next());\n });\n\n app.param('tenantId', (req, res, next, tenantId) => {\n debug(`tenantId param set: ${tenantId}`);\n setRequestContext({\n tenantId,\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n\n app.use((req, res, next) => {\n setRequestContext({\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n }\n\n init = true;\n\n return {\n id: 'express',\n\n onConfigure: () => {\n const { paths: rawPaths } = instance;\n const paths = {\n get: rawPaths.get.map(cleaner),\n post: rawPaths.post.map(cleaner),\n put: rawPaths.put.map(cleaner),\n delete: rawPaths.delete.map(cleaner),\n };\n debug(`paths configured ${JSON.stringify(paths)}`);\n instance.paths = paths;\n doConfigure(instance as NileWithExpress);\n },\n\n onHandleRequest: async (\n params: [ExpressRequest, ExpressResponse, NextFunction]\n ) => {\n const [req, res, next] = params;\n debug('handling response');\n\n const reqUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\n\n try {\n new URL(reqUrl);\n } catch {\n throw new Error('Invalid URL — are you running Express?');\n }\n\n const method = req.method;\n const init: RequestInit = { method, headers: new Headers() };\n\n if (req.headers?.cookie) {\n (init.headers as Headers).set('cookie', req.headers.cookie);\n }\n\n if (['POST', 'PUT'].includes(method) && req.body) {\n init.body = JSON.stringify(req.body);\n }\n\n const proxyRequest = new Request(reqUrl, init);\n debug(`[${method}] proxy: ${reqUrl} ${JSON.stringify(init)}`);\n\n let response: Response;\n const context = {\n headers: new Headers(req.headers as HeadersInit),\n tenantId: req.params?.tenantId || undefined,\n };\n try {\n response = await instance.withContext(context, async (ctx) => {\n return (await ctx.handlers[\n method as 'GET' | 'POST' | 'PUT' | 'DELETE'\n ](proxyRequest, { disableExtensions: ['express'] })) as Response;\n });\n } catch (e) {\n error(e);\n return next();\n }\n\n let body;\n try {\n body = await response.clone().json();\n } catch {\n body = await response.text();\n }\n\n const newHeaders: Record<string, string | string[]> = {};\n response.headers.forEach((value, key) => {\n if (\n !['content-length', 'transfer-encoding'].includes(key.toLowerCase())\n ) {\n if (newHeaders[key]) {\n const prev = newHeaders[key];\n newHeaders[key] = Array.isArray(prev)\n ? [...prev, value]\n : [prev, value];\n } else {\n newHeaders[key] = value;\n }\n }\n });\n if (!res.headersSent) {\n debug('sending response');\n res.status(response.status).set(newHeaders);\n typeof body === 'string' ? res.send(body) : res.json(body ?? {});\n }\n\n return ExtensionState.onHandleRequest;\n },\n };\n };\n};\n\nfunction normalizeHeaders(headers: IncomingHttpHeaders): HeadersInit {\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (typeof value === 'string') {\n normalized[key] = value;\n } else if (Array.isArray(value)) {\n normalized[key] = value.join(','); // Join multi-values with commas\n }\n }\n return normalized;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAkC,uBAGlCC,EAAuD,gCAQhD,SAASJ,EAAQK,EAAa,CACnC,OAAOA,EAAI,WAAW,eAAgB,KAAK,CAC7C,CAoBA,IAAMC,EAAe,IAAI,oBAGZL,EAAWM,GAAkB,CACxC,IAAIC,EAAO,GAEX,OAAQC,GAAqB,CAC3B,GAAM,CA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AAAJ,EAAS,QAAQ,QAAQ,CAACK,EAAOC,IAAQ,CACvC,GACE,CAAC,CAAC,iBAAkB,mBAAmB,EAAE,SAASA,EAAI,YAAY,CAAC,EAEnE,GAAIF,EAAWE,CAAG,EAAG,CACnB,IAAMC,EAAOH,EAAWE,CAAG,EAC3BF,EAAWE,CAAG,EAAI,MAAM,QAAQC,CAAI,EAChC,CAAC,GAAGA,EAAMF,CAAK,EACf,CAACE,EAAMF,CAAK,CAClB,MACED,EAAWE,CAAG,EAAID,CAGxB,CAAC,EACIf,EAAI,cACPN,EAAM,kBAAkB,EACxBM,EAAI,OAAOU,EAAS,MAAM,EAAE,IAAII,CAAU,EAC1C,OAAOD,GAAS,SAAWb,EAAI,KAAKa,CAAI,EAAIb,EAAI,KAAKa,GAAQ,CAAC,CAAC,GAG1D,iBAAe,eACxB,CACF,CACF,CACF,EAEA,SAASV,EAAiBe,EAA2C,CACnE,IAAMC,EAAqC,CAAC,EAC5C,OAAW,CAACH,EAAKD,CAAK,IAAK,OAAO,QAAQG,CAAO,EAC3C,OAAOH,GAAU,SACnBI,EAAWH,CAAG,EAAID,EACT,MAAM,QAAQA,CAAK,IAC5BI,EAAWH,CAAG,EAAID,EAAM,KAAK,GAAG,GAGpC,OAAOI,CACT","names":["index_exports","__export","cleaner","express","__toCommonJS","import_async_hooks","import_server","val","contextStore","app","init","instance","error","debug","setRequestContext","context","doConfigure","server","req","res","next","tenantId","normalizeHeaders","rawPaths","paths","params","reqUrl","method","proxyRequest","response","ctx","e","body","newHeaders","value","key","prev","headers","normalized"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\nimport { IncomingHttpHeaders } from 'http';\n\nimport { PartialContext, ExtensionState, Server } from '@niledatabase/server';\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Express,\n} from 'express';\n\nexport function cleaner(val: string) {\n return val.replaceAll(/\\{([^}]+)\\}/g, ':$1');\n}\n\ntype ExpressRouteHandler = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction\n) => void | Promise<void>;\n\ntype ExpressRouteFunctions = {\n GET: ExpressRouteHandler;\n POST: ExpressRouteHandler;\n PUT: ExpressRouteHandler;\n DELETE: ExpressRouteHandler;\n};\n\ntype NileWithExpress = Server & {\n handlers: ExpressRouteFunctions;\n};\n\n// AsyncLocalStorage to persist context per request\nconst contextStore = new AsyncLocalStorage<Map<string, unknown>>();\n\n// Express extension factory\nexport const express = (app?: Express) => {\n let init = false;\n\n return (instance: Server) => {\n const { error, debug } = instance.logger('[EXTENSION][express]');\n\n // Internal context helpers - I think we delete this now?\n const setRequestContext = (context: PartialContext) => {\n contextStore.getStore()?.set('context', context);\n\n instance.withContext(context);\n };\n\n function doConfigure(server: NileWithExpress) {\n if (app) {\n debug('routes configured');\n app.get(server.paths.get, server.handlers.GET);\n app.post(server.paths.post, server.handlers.POST);\n app.put(server.paths.put, server.handlers.PUT);\n app.delete(server.paths.delete, server.handlers.DELETE);\n }\n }\n\n if (!init && app) {\n debug('initializing express extension with middleware');\n\n app.use((req, res, next) => {\n contextStore.run(new Map(), () => next());\n });\n\n app.param('tenantId', (req, res, next, tenantId) => {\n debug(`tenantId param set: ${tenantId}`);\n setRequestContext({\n tenantId,\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n\n app.use((req, res, next) => {\n setRequestContext({\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n }\n\n init = true;\n\n return {\n id: 'express',\n\n onConfigure: () => {\n const { paths: rawPaths } = instance;\n const paths = {\n get: rawPaths.get.map(cleaner),\n post: rawPaths.post.map(cleaner),\n put: rawPaths.put.map(cleaner),\n delete: rawPaths.delete.map(cleaner),\n };\n debug(`paths configured ${JSON.stringify(paths)}`);\n instance.paths = paths;\n doConfigure(instance as NileWithExpress);\n },\n\n onHandleRequest: async (\n params: [ExpressRequest, ExpressResponse, NextFunction]\n ) => {\n // there are two cases here.\n // One is a server side request (normal Request/Response, the other is GET/POST/PUT/DELETE)\n const [req, res, next] = params;\n debug('handling response');\n\n let reqUrl = '';\n const method = req.method;\n const init: RequestInit = { method, headers: new Headers() };\n if (req instanceof Request) {\n reqUrl = req.url;\n init.headers = req.headers;\n } else {\n try {\n reqUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\n } catch {\n // handled later\n }\n }\n\n try {\n new URL(reqUrl);\n } catch {\n throw new Error('Invalid URL — are you running Express?');\n }\n\n if (req.headers?.cookie) {\n (init.headers as Headers).set('cookie', req.headers.cookie);\n }\n\n if (['POST', 'PUT'].includes(method) && req.body) {\n init.body = JSON.stringify(req.body);\n }\n\n const proxyRequest = new Request(reqUrl, init);\n debug(`[${method}] proxy: ${reqUrl} ${JSON.stringify(init)}`);\n\n let response: Response;\n const context = {\n headers: new Headers(req.headers as HeadersInit),\n tenantId: req.params?.tenantId || undefined,\n };\n try {\n response = await instance.withContext(context, async (ctx) => {\n return (await ctx.handlers[\n method as 'GET' | 'POST' | 'PUT' | 'DELETE'\n ](proxyRequest, { disableExtensions: ['express'] })) as Response;\n });\n } catch (e) {\n error(e);\n return next();\n }\n\n let body;\n try {\n body = await response.clone().json();\n } catch {\n body = await response.text();\n }\n\n const newHeaders: Record<string, string | string[]> = {};\n response.headers.forEach((value, key) => {\n if (\n !['content-length', 'transfer-encoding'].includes(key.toLowerCase())\n ) {\n if (newHeaders[key]) {\n const prev = newHeaders[key];\n newHeaders[key] = Array.isArray(prev)\n ? [...prev, value]\n : [prev, value];\n } else {\n newHeaders[key] = value;\n }\n }\n });\n\n if (!res) {\n return response;\n }\n\n if (!res.headersSent) {\n debug('sending response');\n res.status(response.status).set(newHeaders);\n typeof body === 'string' ? res.send(body) : res.json(body ?? {});\n }\n\n return ExtensionState.onHandleRequest;\n },\n };\n };\n};\n\nfunction normalizeHeaders(headers: IncomingHttpHeaders): HeadersInit {\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (typeof value === 'string') {\n normalized[key] = value;\n } else if (Array.isArray(value)) {\n normalized[key] = value.join(','); // Join multi-values with commas\n }\n }\n return normalized;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAkC,uBAGlCC,EAAuD,gCAQhD,SAASJ,EAAQK,EAAa,CACnC,OAAOA,EAAI,WAAW,eAAgB,KAAK,CAC7C,CAoBA,IAAMC,EAAe,IAAI,oBAGZL,EAAWM,GAAkB,CACxC,IAAIC,EAAO,GAEX,OAAQC,GAAqB,CAC3B,GAAM,CAAE,MAAAC,EAAO,MAAAC,CAAM,EAAIF,EAAS,OAAO,sBAAsB,EAGzDG,EAAqBC,GAA4B,CACrDP,EAAa,SAAS,GAAG,IAAI,UAAWO,CAAO,EAE/CJ,EAAS,YAAYI,CAAO,CAC9B,EAEA,SAASC,EAAYC,EAAyB,CACxCR,IACFI,EAAM,mBAAmB,EACzBJ,EAAI,IAAIQ,EAAO,MAAM,IAAKA,EAAO,SAAS,GAAG,EAC7CR,EAAI,KAAKQ,EAAO,MAAM,KAAMA,EAAO,SAAS,IAAI,EAChDR,EAAI,IAAIQ,EAAO,MAAM,IAAKA,EAAO,SAAS,GAAG,EAC7CR,EAAI,OAAOQ,EAAO,MAAM,OAAQA,EAAO,SAAS,MAAM,EAE1D,CAEA,MAAI,CAACP,GAAQD,IACXI,EAAM,gDAAgD,EAEtDJ,EAAI,IAAI,CAACS,EAAKC,EAAKC,IAAS,CAC1BZ,EAAa,IAAI,IAAI,IAAO,IAAMY,EAAK,CAAC,CAC1C,CAAC,EAEDX,EAAI,MAAM,WAAY,CAACS,EAAKC,EAAKC,EAAMC,IAAa,CAClDR,EAAM,uBAAuBQ,CAAQ,EAAE,EACvCP,EAAkB,CAChB,SAAAO,EACA,QAAS,IAAI,QAAQC,EAAiBJ,EAAI,OAAO,CAAC,CACpD,CAAC,EACDE,EAAK,CACP,CAAC,EAEDX,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IAC5BI,EAAWH,CAAG,EAAID,EAAM,KAAK,GAAG,GAGpC,OAAOI,CACT","names":["index_exports","__export","cleaner","express","__toCommonJS","import_async_hooks","import_server","val","contextStore","app","init","instance","error","debug","setRequestContext","context","doConfigure","server","req","res","next","tenantId","normalizeHeaders","rawPaths","paths","params","reqUrl","method","proxyRequest","response","ctx","e","body","newHeaders","value","key","prev","headers","normalized"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{AsyncLocalStorage as q}from"async_hooks";import{ExtensionState as P}from"@niledatabase/server";function g(t){return t.replaceAll(/\{([^}]+)\}/g,":$1")}var y=new q,U=t=>{let i=!1;return n=>{let{error:d,debug:o}=n.logger("[EXTENSION][express]"),m=e=>{y.getStore()?.set("context",e),n.withContext(e)};function H(e){t&&(o("routes configured"),t.get(e.paths.get,e.handlers.GET),t.post(e.paths.post,e.handlers.POST),t.put(e.paths.put,e.handlers.PUT),t.delete(e.paths.delete,e.handlers.DELETE))}return!i&&t&&(o("initializing express extension with middleware"),t.use((e,s,r)=>{y.run(new Map,()=>r())}),t.param("tenantId",(e,s,r,x)=>{o(`tenantId param set: ${x}`),m({tenantId:x,headers:new Headers(w(e.headers))}),r()}),t.use((e,s,r)=>{m({headers:new Headers(w(e.headers))}),r()})),i=!0,{id:"express",onConfigure:()=>{let{paths:e}=n,s={get:e.get.map(g),post:e.post.map(g),put:e.put.map(g),delete:e.delete.map(g)};o(`paths configured ${JSON.stringify(s)}`),n.paths=s,H(n)},onHandleRequest:async e=>{let[s,r,x]=e;o("handling response");let f=s.protocol+"://"+s.get("host")+s.originalUrl;try{new URL(f)}catch{throw new Error("Invalid URL \u2014 are you running Express?")}let h=s.method,E={method:h,headers:new Headers};s.headers?.cookie&&E.headers.set("cookie",s.headers.cookie),["POST","PUT"].includes(h)&&s.body&&(E.body=JSON.stringify(s.body));let S=new Request(f,E);o(`[${h}] proxy: ${f} ${JSON.stringify(E)}`);let p,T={headers:new Headers(s.headers),tenantId:s.params?.tenantId||void 0};try{p=await n.withContext(T,async a=>await a.handlers[h](S,{disableExtensions:["express"]}))}catch(a){return d(a),x()}let u;try{u=await p.clone().json()}catch{u=await p.text()}let c={};return p.headers.forEach((a,l)=>{if(!["content-length","transfer-encoding"].includes(l.toLowerCase()))if(c[l]){let R=c[l];c[l]=Array.isArray(R)?[...R,a]:[R,a]}else c[l]=a}),r.headersSent||(o("sending response"),r.status(p.status).set(c),typeof u=="string"?r.send(u):r.json(u??{})),P.onHandleRequest}}}};function w(t){let i={};for(let[n,d]of Object.entries(t))typeof d=="string"?i[n]=d:Array.isArray(d)&&(i[n]=d.join(","));return i}export{g as cleaner,U as express};
1
+ import{AsyncLocalStorage as T}from"async_hooks";import{ExtensionState as P}from"@niledatabase/server";function f(t){return t.replaceAll(/\{([^}]+)\}/g,":$1")}var m=new T,U=t=>{let i=!1;return n=>{let{error:d,debug:o}=n.logger("[EXTENSION][express]"),y=e=>{m.getStore()?.set("context",e),n.withContext(e)};function H(e){t&&(o("routes configured"),t.get(e.paths.get,e.handlers.GET),t.post(e.paths.post,e.handlers.POST),t.put(e.paths.put,e.handlers.PUT),t.delete(e.paths.delete,e.handlers.DELETE))}return!i&&t&&(o("initializing express extension with middleware"),t.use((e,s,r)=>{m.run(new Map,()=>r())}),t.param("tenantId",(e,s,r,E)=>{o(`tenantId param set: ${E}`),y({tenantId:E,headers:new Headers(w(e.headers))}),r()}),t.use((e,s,r)=>{y({headers:new Headers(w(e.headers))}),r()})),i=!0,{id:"express",onConfigure:()=>{let{paths:e}=n,s={get:e.get.map(f),post:e.post.map(f),put:e.put.map(f),delete:e.delete.map(f)};o(`paths configured ${JSON.stringify(s)}`),n.paths=s,H(n)},onHandleRequest:async e=>{let[s,r,E]=e;o("handling response");let u="",g=s.method,c={method:g,headers:new Headers};if(s instanceof Request)u=s.url,c.headers=s.headers;else try{u=s.protocol+"://"+s.get("host")+s.originalUrl}catch{}try{new URL(u)}catch{throw new Error("Invalid URL \u2014 are you running Express?")}s.headers?.cookie&&c.headers.set("cookie",s.headers.cookie),["POST","PUT"].includes(g)&&s.body&&(c.body=JSON.stringify(s.body));let S=new Request(u,c);o(`[${g}] proxy: ${u} ${JSON.stringify(c)}`);let p,q={headers:new Headers(s.headers),tenantId:s.params?.tenantId||void 0};try{p=await n.withContext(q,async a=>await a.handlers[g](S,{disableExtensions:["express"]}))}catch(a){return d(a),E()}let l;try{l=await p.clone().json()}catch{l=await p.text()}let h={};return p.headers.forEach((a,x)=>{if(!["content-length","transfer-encoding"].includes(x.toLowerCase()))if(h[x]){let R=h[x];h[x]=Array.isArray(R)?[...R,a]:[R,a]}else h[x]=a}),r?(r.headersSent||(o("sending response"),r.status(p.status).set(h),typeof l=="string"?r.send(l):r.json(l??{})),P.onHandleRequest):p}}}};function w(t){let i={};for(let[n,d]of Object.entries(t))typeof d=="string"?i[n]=d:Array.isArray(d)&&(i[n]=d.join(","));return i}export{f as cleaner,U as express};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\nimport { IncomingHttpHeaders } from 'http';\n\nimport { PartialContext, ExtensionState, Server } from '@niledatabase/server';\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Express,\n} from 'express';\n\nexport function cleaner(val: string) {\n return val.replaceAll(/\\{([^}]+)\\}/g, ':$1');\n}\n\ntype ExpressRouteHandler = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction\n) => void | Promise<void>;\n\ntype ExpressRouteFunctions = {\n GET: ExpressRouteHandler;\n POST: ExpressRouteHandler;\n PUT: ExpressRouteHandler;\n DELETE: ExpressRouteHandler;\n};\n\ntype NileWithExpress = Server & {\n handlers: ExpressRouteFunctions;\n};\n\n// AsyncLocalStorage to persist context per request\nconst contextStore = new AsyncLocalStorage<Map<string, unknown>>();\n\n// Express extension factory\nexport const express = (app?: Express) => {\n let init = false;\n\n return (instance: Server) => {\n const { error, debug } = instance.logger('[EXTENSION][express]');\n\n // Internal context helpers - I think we delete this now?\n const setRequestContext = (context: PartialContext) => {\n contextStore.getStore()?.set('context', context);\n\n instance.withContext(context);\n };\n\n function doConfigure(server: NileWithExpress) {\n if (app) {\n debug('routes configured');\n app.get(server.paths.get, server.handlers.GET);\n app.post(server.paths.post, server.handlers.POST);\n app.put(server.paths.put, server.handlers.PUT);\n app.delete(server.paths.delete, server.handlers.DELETE);\n }\n }\n\n if (!init && app) {\n debug('initializing express extension with middleware');\n\n app.use((req, res, next) => {\n contextStore.run(new Map(), () => next());\n });\n\n app.param('tenantId', (req, res, next, tenantId) => {\n debug(`tenantId param set: ${tenantId}`);\n setRequestContext({\n tenantId,\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n\n app.use((req, res, next) => {\n setRequestContext({\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n }\n\n init = true;\n\n return {\n id: 'express',\n\n onConfigure: () => {\n const { paths: rawPaths } = instance;\n const paths = {\n get: rawPaths.get.map(cleaner),\n post: rawPaths.post.map(cleaner),\n put: rawPaths.put.map(cleaner),\n delete: rawPaths.delete.map(cleaner),\n };\n debug(`paths configured ${JSON.stringify(paths)}`);\n instance.paths = paths;\n doConfigure(instance as NileWithExpress);\n },\n\n onHandleRequest: async (\n params: [ExpressRequest, ExpressResponse, NextFunction]\n ) => {\n const [req, res, next] = params;\n debug('handling response');\n\n const reqUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\n\n try {\n new URL(reqUrl);\n } catch {\n throw new Error('Invalid URL — are you running Express?');\n }\n\n const method = req.method;\n const init: RequestInit = { method, headers: new Headers() };\n\n if (req.headers?.cookie) {\n (init.headers as Headers).set('cookie', req.headers.cookie);\n }\n\n if (['POST', 'PUT'].includes(method) && req.body) {\n init.body = JSON.stringify(req.body);\n }\n\n const proxyRequest = new Request(reqUrl, init);\n debug(`[${method}] proxy: ${reqUrl} ${JSON.stringify(init)}`);\n\n let response: Response;\n const context = {\n headers: new Headers(req.headers as HeadersInit),\n tenantId: req.params?.tenantId || undefined,\n };\n try {\n response = await instance.withContext(context, async (ctx) => {\n return (await ctx.handlers[\n method as 'GET' | 'POST' | 'PUT' | 'DELETE'\n ](proxyRequest, { disableExtensions: ['express'] })) as Response;\n });\n } catch (e) {\n error(e);\n return next();\n }\n\n let body;\n try {\n body = await response.clone().json();\n } catch {\n body = await response.text();\n }\n\n const newHeaders: Record<string, string | string[]> = {};\n response.headers.forEach((value, key) => {\n if (\n !['content-length', 'transfer-encoding'].includes(key.toLowerCase())\n ) {\n if (newHeaders[key]) {\n const prev = newHeaders[key];\n newHeaders[key] = Array.isArray(prev)\n ? [...prev, value]\n : [prev, value];\n } else {\n newHeaders[key] = value;\n }\n }\n });\n if (!res.headersSent) {\n debug('sending response');\n res.status(response.status).set(newHeaders);\n typeof body === 'string' ? res.send(body) : res.json(body ?? {});\n }\n\n return ExtensionState.onHandleRequest;\n },\n };\n };\n};\n\nfunction normalizeHeaders(headers: IncomingHttpHeaders): HeadersInit {\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (typeof value === 'string') {\n normalized[key] = value;\n } else if (Array.isArray(value)) {\n normalized[key] = value.join(','); // Join multi-values with commas\n }\n }\n return normalized;\n}\n"],"mappings":"AAAA,OAAS,qBAAAA,MAAyB,cAGlC,OAAyB,kBAAAC,MAA8B,uBAQhD,SAASC,EAAQC,EAAa,CACnC,OAAOA,EAAI,WAAW,eAAgB,KAAK,CAC7C,CAoBA,IAAMC,EAAe,IAAIJ,EAGZK,EAAWC,GAAkB,CACxC,IAAIC,EAAO,GAEX,OAAQC,GAAqB,CAC3B,GAAM,CAAE,MAAAC,EAAO,MAAAC,CAAM,EAAIF,EAAS,OAAO,sBAAsB,EAGzDG,EAAqBC,GAA4B,CACrDR,EAAa,SAAS,GAAG,IAAI,UAAWQ,CAAO,EAE/CJ,EAAS,YAAYI,CAAO,CAC9B,EAEA,SAASC,EAAYC,EAA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,EAC3BF,EAAWE,CAAG,EAAI,MAAM,QAAQC,CAAI,EAChC,CAAC,GAAGA,EAAMF,CAAK,EACf,CAACE,EAAMF,CAAK,CAClB,MACED,EAAWE,CAAG,EAAID,CAGxB,CAAC,EACIf,EAAI,cACPN,EAAM,kBAAkB,EACxBM,EAAI,OAAOU,EAAS,MAAM,EAAE,IAAII,CAAU,EAC1C,OAAOD,GAAS,SAAWb,EAAI,KAAKa,CAAI,EAAIb,EAAI,KAAKa,GAAQ,CAAC,CAAC,GAG1D5B,EAAe,eACxB,CACF,CACF,CACF,EAEA,SAASkB,EAAiBe,EAA2C,CACnE,IAAMC,EAAqC,CAAC,EAC5C,OAAW,CAACH,EAAKD,CAAK,IAAK,OAAO,QAAQG,CAAO,EAC3C,OAAOH,GAAU,SACnBI,EAAWH,CAAG,EAAID,EACT,MAAM,QAAQA,CAAK,IAC5BI,EAAWH,CAAG,EAAID,EAAM,KAAK,GAAG,GAGpC,OAAOI,CACT","names":["AsyncLocalStorage","ExtensionState","cleaner","val","contextStore","express","app","init","instance","error","debug","setRequestContext","context","doConfigure","server","req","res","next","tenantId","normalizeHeaders","rawPaths","paths","params","reqUrl","method","proxyRequest","response","ctx","e","body","newHeaders","value","key","prev","headers","normalized"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\nimport { IncomingHttpHeaders } from 'http';\n\nimport { PartialContext, ExtensionState, Server } from '@niledatabase/server';\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Express,\n} from 'express';\n\nexport function cleaner(val: string) {\n return val.replaceAll(/\\{([^}]+)\\}/g, ':$1');\n}\n\ntype ExpressRouteHandler = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction\n) => void | Promise<void>;\n\ntype ExpressRouteFunctions = {\n GET: ExpressRouteHandler;\n POST: ExpressRouteHandler;\n PUT: ExpressRouteHandler;\n DELETE: ExpressRouteHandler;\n};\n\ntype NileWithExpress = Server & {\n handlers: ExpressRouteFunctions;\n};\n\n// AsyncLocalStorage to persist context per request\nconst contextStore = new AsyncLocalStorage<Map<string, unknown>>();\n\n// Express extension factory\nexport const express = (app?: Express) => {\n let init = false;\n\n return (instance: Server) => {\n const { error, debug } = instance.logger('[EXTENSION][express]');\n\n // Internal context helpers - I think we delete this now?\n const setRequestContext = (context: PartialContext) => {\n contextStore.getStore()?.set('context', context);\n\n instance.withContext(context);\n };\n\n function doConfigure(server: NileWithExpress) {\n if (app) {\n debug('routes configured');\n app.get(server.paths.get, server.handlers.GET);\n app.post(server.paths.post, server.handlers.POST);\n app.put(server.paths.put, server.handlers.PUT);\n app.delete(server.paths.delete, server.handlers.DELETE);\n }\n }\n\n if (!init && app) {\n debug('initializing express extension with middleware');\n\n app.use((req, res, next) => {\n contextStore.run(new Map(), () => next());\n });\n\n app.param('tenantId', (req, res, next, tenantId) => {\n debug(`tenantId param set: ${tenantId}`);\n setRequestContext({\n tenantId,\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n\n app.use((req, res, next) => {\n setRequestContext({\n headers: new Headers(normalizeHeaders(req.headers)),\n });\n next();\n });\n }\n\n init = true;\n\n return {\n id: 'express',\n\n onConfigure: () => {\n const { paths: rawPaths } = instance;\n const paths = {\n get: rawPaths.get.map(cleaner),\n post: rawPaths.post.map(cleaner),\n put: rawPaths.put.map(cleaner),\n delete: rawPaths.delete.map(cleaner),\n };\n debug(`paths configured ${JSON.stringify(paths)}`);\n instance.paths = paths;\n doConfigure(instance as NileWithExpress);\n },\n\n onHandleRequest: async (\n params: [ExpressRequest, ExpressResponse, NextFunction]\n ) => {\n // there are two cases here.\n // One is a server side request (normal Request/Response, the other is GET/POST/PUT/DELETE)\n const [req, res, next] = params;\n debug('handling response');\n\n let reqUrl = '';\n const method = req.method;\n const init: RequestInit = { method, headers: new Headers() };\n if (req instanceof Request) {\n reqUrl = req.url;\n init.headers = req.headers;\n } else {\n try {\n reqUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\n } catch {\n // handled later\n }\n }\n\n try {\n new URL(reqUrl);\n } catch {\n throw new Error('Invalid URL — are you running Express?');\n }\n\n if (req.headers?.cookie) {\n (init.headers as Headers).set('cookie', req.headers.cookie);\n }\n\n if (['POST', 'PUT'].includes(method) && req.body) {\n init.body = JSON.stringify(req.body);\n }\n\n const proxyRequest = new Request(reqUrl, init);\n debug(`[${method}] proxy: ${reqUrl} ${JSON.stringify(init)}`);\n\n let response: Response;\n const context = {\n headers: new Headers(req.headers as HeadersInit),\n tenantId: req.params?.tenantId || undefined,\n };\n try {\n response = await instance.withContext(context, async (ctx) => {\n return (await ctx.handlers[\n method as 'GET' | 'POST' | 'PUT' | 'DELETE'\n ](proxyRequest, { disableExtensions: ['express'] })) as Response;\n });\n } catch (e) {\n error(e);\n return next();\n }\n\n let body;\n try {\n body = await response.clone().json();\n } catch {\n body = await response.text();\n }\n\n const newHeaders: Record<string, string | string[]> = {};\n response.headers.forEach((value, key) => {\n if (\n !['content-length', 'transfer-encoding'].includes(key.toLowerCase())\n ) {\n if (newHeaders[key]) {\n const prev = newHeaders[key];\n newHeaders[key] = Array.isArray(prev)\n ? [...prev, value]\n : [prev, value];\n } else {\n newHeaders[key] = value;\n }\n }\n });\n\n if (!res) {\n return response;\n }\n\n if (!res.headersSent) {\n debug('sending response');\n res.status(response.status).set(newHeaders);\n typeof body === 'string' ? res.send(body) : res.json(body ?? {});\n }\n\n return ExtensionState.onHandleRequest;\n },\n };\n };\n};\n\nfunction normalizeHeaders(headers: IncomingHttpHeaders): HeadersInit {\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (typeof value === 'string') {\n normalized[key] = value;\n } else if (Array.isArray(value)) {\n normalized[key] = value.join(','); // Join multi-values with commas\n }\n }\n return normalized;\n}\n"],"mappings":"AAAA,OAAS,qBAAAA,MAAyB,cAGlC,OAAyB,kBAAAC,MAA8B,uBAQhD,SAASC,EAAQC,EAAa,CACnC,OAAOA,EAA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,SAAS,CAAE,CAAC,CACnD,CACH,OAASG,EAAG,CACV,OAAAnB,EAAMmB,CAAC,EACAX,EAAK,CACd,CAEA,IAAIY,EACJ,GAAI,CACFA,EAAO,MAAMH,EAAS,MAAM,EAAE,KAAK,CACrC,MAAQ,CACNG,EAAO,MAAMH,EAAS,KAAK,CAC7B,CAEA,IAAMI,EAAgD,CAAC,EAgBvD,OAfAJ,EAAS,QAAQ,QAAQ,CAACK,EAAOC,IAAQ,CACvC,GACE,CAAC,CAAC,iBAAkB,mBAAmB,EAAE,SAASA,EAAI,YAAY,CAAC,EAEnE,GAAIF,EAAWE,CAAG,EAAG,CACnB,IAAMC,EAAOH,EAAWE,CAAG,EAC3BF,EAAWE,CAAG,EAAI,MAAM,QAAQC,CAAI,EAChC,CAAC,GAAGA,EAAMF,CAAK,EACf,CAACE,EAAMF,CAAK,CAClB,MACED,EAAWE,CAAG,EAAID,CAGxB,CAAC,EAEIf,GAIAA,EAAI,cACPN,EAAM,kBAAkB,EACxBM,EAAI,OAAOU,EAAS,MAAM,EAAE,IAAII,CAAU,EAC1C,OAAOD,GAAS,SAAWb,EAAI,KAAKa,CAAI,EAAIb,EAAI,KAAKa,GAAQ,CAAC,CAAC,GAG1D5B,EAAe,iBATbyB,CAUX,CACF,CACF,CACF,EAEA,SAASP,EAAiBe,EAA2C,CACnE,IAAMC,EAAqC,CAAC,EAC5C,OAAW,CAACH,EAAKD,CAAK,IAAK,OAAO,QAAQG,CAAO,EAC3C,OAAOH,GAAU,SACnBI,EAAWH,CAAG,EAAID,EACT,MAAM,QAAQA,CAAK,IAC5BI,EAAWH,CAAG,EAAID,EAAM,KAAK,GAAG,GAGpC,OAAOI,CACT","names":["AsyncLocalStorage","ExtensionState","cleaner","val","contextStore","express","app","init","instance","error","debug","setRequestContext","context","doConfigure","server","req","res","next","tenantId","normalizeHeaders","rawPaths","paths","params","reqUrl","method","proxyRequest","response","ctx","e","body","newHeaders","value","key","prev","headers","normalized"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@niledatabase/express",
3
- "version": "5.0.0",
3
+ "version": "5.0.1",
4
4
  "license": "MIT",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -44,5 +44,5 @@
44
44
  "ts-jest": "^29.3.4",
45
45
  "tsup": "^8.5.0"
46
46
  },
47
- "gitHead": "bc6ee6499ed130cb605ea2a373e0054072ea8fb0"
47
+ "gitHead": "6f523b9793818c6620ad374f55608b543e1d9ed4"
48
48
  }