diesel-core 1.5.7 → 1.5.8
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/ctx.d.ts +2 -2
- package/dist/ctx.js +19 -19
- package/dist/handleRequest.js +25 -25
- package/dist/main.d.ts +2 -3
- package/dist/main.js +48 -48
- package/dist/request_pipeline.js +33 -33
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
package/dist/ctx.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export declare class Context implements ContextType {
|
|
|
6
6
|
path?: string | undefined;
|
|
7
7
|
routePattern?: string;
|
|
8
8
|
env?: Record<string, any>;
|
|
9
|
-
|
|
9
|
+
executionContext?: any | undefined;
|
|
10
10
|
headers: Headers;
|
|
11
11
|
private parsedQuery;
|
|
12
12
|
private parsedParams;
|
|
@@ -14,7 +14,7 @@ export declare class Context implements ContextType {
|
|
|
14
14
|
private parsedBody;
|
|
15
15
|
private contextData;
|
|
16
16
|
private urlObject;
|
|
17
|
-
constructor(req: Request, server?: Server, path?: string, routePattern?: string, env?: Record<string, any>,
|
|
17
|
+
constructor(req: Request, server?: Server, path?: string, routePattern?: string, env?: Record<string, any>, executionContext?: any);
|
|
18
18
|
setHeader(key: string, value: string): this;
|
|
19
19
|
removeHeader(key: string): this;
|
|
20
20
|
set<T>(key: string, value: T): this;
|
package/dist/ctx.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var U1=Object.create;var{getPrototypeOf:W1,defineProperty:
|
|
1
|
+
var U1=Object.create;var{getPrototypeOf:W1,defineProperty:X,getOwnPropertyNames:u,getOwnPropertyDescriptor:M1}=Object,r=Object.prototype.hasOwnProperty;var H1=(f,v,g)=>{g=f!=null?U1(W1(f)):{};let A=v||!f||!f.__esModule?X(g,"default",{value:f,enumerable:!0}):g;for(let C of u(f))if(!r.call(A,C))X(A,C,{get:()=>f[C],enumerable:!0});return A},E=new WeakMap,q1=(f)=>{var v=E.get(f),g;if(v)return v;if(v=X({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")u(f).map((A)=>!r.call(v,A)&&X(v,A,{get:()=>f[A],enumerable:!(g=M1(f,A))||g.enumerable}));return E.set(f,v),v},F=(f,v)=>()=>(v||f((v={exports:{}}).exports,v),v.exports);var N1=(f,v)=>{for(var g in v)X(f,g,{get:v[g],enumerable:!0,configurable:!0,set:(A)=>v[g]=()=>A})};var F1=(f,v)=>()=>(f&&(v=f(f=0)),v);var y1=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(v,g)=>(typeof require!=="undefined"?require:v)[g]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var p={};N1(p,{sep:()=>s,resolve:()=>M,relative:()=>h,posix:()=>o,parse:()=>e,normalize:()=>y,join:()=>T,isAbsolute:()=>c,format:()=>i,extname:()=>n,dirname:()=>m,delimiter:()=>a,default:()=>R1,basename:()=>l,_makeLong:()=>d});function Q(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function _(f,v){var g="",A=0,C=-1,b=0,w;for(var j=0;j<=f.length;++j){if(j<f.length)w=f.charCodeAt(j);else if(w===47)break;else w=47;if(w===47){if(C===j-1||b===1);else if(C!==j-1&&b===2){if(g.length<2||A!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var K=g.lastIndexOf("/");if(K!==g.length-1){if(K===-1)g="",A=0;else g=g.slice(0,K),A=g.length-1-g.lastIndexOf("/");C=j,b=0;continue}}else if(g.length===2||g.length===1){g="",A=0,C=j,b=0;continue}}if(v){if(g.length>0)g+="/..";else g="..";A=2}}else{if(g.length>0)g+="/"+f.slice(C+1,j);else g=f.slice(C+1,j);A=j-C-1}C=j,b=0}else if(w===46&&b!==-1)++b;else b=-1}return g}function D1(f,v){var g=v.dir||v.root,A=v.base||(v.name||"")+(v.ext||"");if(!g)return A;if(g===v.root)return g+A;return g+f+A}function M(){var f="",v=!1,g;for(var A=arguments.length-1;A>=-1&&!v;A--){var C;if(A>=0)C=arguments[A];else{if(g===void 0)g=process.cwd();C=g}if(Q(C),C.length===0)continue;f=C+"/"+f,v=C.charCodeAt(0)===47}if(f=_(f,!v),v)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function y(f){if(Q(f),f.length===0)return".";var v=f.charCodeAt(0)===47,g=f.charCodeAt(f.length-1)===47;if(f=_(f,!v),f.length===0&&!v)f=".";if(f.length>0&&g)f+="/";if(v)return"/"+f;return f}function c(f){return Q(f),f.length>0&&f.charCodeAt(0)===47}function T(){if(arguments.length===0)return".";var f;for(var v=0;v<arguments.length;++v){var g=arguments[v];if(Q(g),g.length>0)if(f===void 0)f=g;else f+="/"+g}if(f===void 0)return".";return y(f)}function h(f,v){if(Q(f),Q(v),f===v)return"";if(f=M(f),v=M(v),f===v)return"";var g=1;for(;g<f.length;++g)if(f.charCodeAt(g)!==47)break;var A=f.length,C=A-g,b=1;for(;b<v.length;++b)if(v.charCodeAt(b)!==47)break;var w=v.length,j=w-b,K=C<j?C:j,Y=-1,z=0;for(;z<=K;++z){if(z===K){if(j>K){if(v.charCodeAt(b+z)===47)return v.slice(b+z+1);else if(z===0)return v.slice(b+z)}else if(C>K){if(f.charCodeAt(g+z)===47)Y=z;else if(z===0)Y=0}break}var V=f.charCodeAt(g+z),G=v.charCodeAt(b+z);if(V!==G)break;else if(V===47)Y=z}var B="";for(z=g+Y+1;z<=A;++z)if(z===A||f.charCodeAt(z)===47)if(B.length===0)B+="..";else B+="/..";if(B.length>0)return B+v.slice(b+Y);else{if(b+=Y,v.charCodeAt(b)===47)++b;return v.slice(b)}}function d(f){return f}function m(f){if(Q(f),f.length===0)return".";var v=f.charCodeAt(0),g=v===47,A=-1,C=!0;for(var b=f.length-1;b>=1;--b)if(v=f.charCodeAt(b),v===47){if(!C){A=b;break}}else C=!1;if(A===-1)return g?"/":".";if(g&&A===1)return"//";return f.slice(0,A)}function l(f,v){if(v!==void 0&&typeof v!=="string")throw new TypeError('"ext" argument must be a string');Q(f);var g=0,A=-1,C=!0,b;if(v!==void 0&&v.length>0&&v.length<=f.length){if(v.length===f.length&&v===f)return"";var w=v.length-1,j=-1;for(b=f.length-1;b>=0;--b){var K=f.charCodeAt(b);if(K===47){if(!C){g=b+1;break}}else{if(j===-1)C=!1,j=b+1;if(w>=0)if(K===v.charCodeAt(w)){if(--w===-1)A=b}else w=-1,A=j}}if(g===A)A=j;else if(A===-1)A=f.length;return f.slice(g,A)}else{for(b=f.length-1;b>=0;--b)if(f.charCodeAt(b)===47){if(!C){g=b+1;break}}else if(A===-1)C=!1,A=b+1;if(A===-1)return"";return f.slice(g,A)}}function n(f){Q(f);var v=-1,g=0,A=-1,C=!0,b=0;for(var w=f.length-1;w>=0;--w){var j=f.charCodeAt(w);if(j===47){if(!C){g=w+1;break}continue}if(A===-1)C=!1,A=w+1;if(j===46){if(v===-1)v=w;else if(b!==1)b=1}else if(v!==-1)b=-1}if(v===-1||A===-1||b===0||b===1&&v===A-1&&v===g+1)return"";return f.slice(v,A)}function i(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return D1("/",f)}function e(f){Q(f);var v={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return v;var g=f.charCodeAt(0),A=g===47,C;if(A)v.root="/",C=1;else C=0;var b=-1,w=0,j=-1,K=!0,Y=f.length-1,z=0;for(;Y>=C;--Y){if(g=f.charCodeAt(Y),g===47){if(!K){w=Y+1;break}continue}if(j===-1)K=!1,j=Y+1;if(g===46){if(b===-1)b=Y;else if(z!==1)z=1}else if(b!==-1)z=-1}if(b===-1||j===-1||z===0||z===1&&b===j-1&&b===w+1){if(j!==-1)if(w===0&&A)v.base=v.name=f.slice(1,j);else v.base=v.name=f.slice(w,j)}else{if(w===0&&A)v.name=f.slice(1,b),v.base=f.slice(1,j);else v.name=f.slice(w,b),v.base=f.slice(w,j);v.ext=f.slice(b,j)}if(w>0)v.dir=f.slice(0,w-1);else if(A)v.dir="/";return v}var s="/",a=":",o,R1;var t=F1(()=>{o=((f)=>(f.posix=f,f))({resolve:M,normalize:y,isAbsolute:c,join:T,relative:h,_makeLong:d,dirname:m,basename:l,extname:n,format:i,parse:e,sep:s,delimiter:a,win32:null,posix:null}),R1=o});var v1=F((E1)=>{var L1=/[|\\{}()[\]^$+*?.]/g,O1=Object.prototype.hasOwnProperty,R=function(f,v){return O1.apply(f,[v])};E1.escapeRegExpChars=function(f){if(!f)return"";return String(f).replace(L1,"\\$&")};var x1={"&":"&","<":"<",">":">",'"':""","'":"'"},k1=/[&<>'"]/g;function I1(f){return x1[f]||f}var S1=`var _ENCODE_HTML_RULES = {
|
|
2
2
|
"&": "&"
|
|
3
3
|
, "<": "<"
|
|
4
4
|
, ">": ">"
|
|
@@ -9,22 +9,22 @@ var U1=Object.create;var{getPrototypeOf:W1,defineProperty:B,getOwnPropertyNames:
|
|
|
9
9
|
function encode_char(c) {
|
|
10
10
|
return _ENCODE_HTML_RULES[c] || c;
|
|
11
11
|
};
|
|
12
|
-
`;E1.escapeXML=function(f){return f==null?"":String(f).replace(
|
|
13
|
-
`+S1}try{if(typeof Object.defineProperty==="function")Object.defineProperty(E1.escapeXML,"toString",{value:f1});else E1.escapeXML.toString=f1}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}E1.shallowCopy=function(f,v){if(v=v||{},f!==null&&f!==void 0)for(var g in v){if(!R(v,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=v[g]}return f};E1.shallowCopyFromList=function(f,v,g){if(g=g||[],v=v||{},f!==null&&f!==void 0)for(var
|
|
14
|
-
`),w=Math.max(
|
|
15
|
-
`);throw f.path=K,f.message=(K||"ejs")+":"+
|
|
12
|
+
`;E1.escapeXML=function(f){return f==null?"":String(f).replace(k1,I1)};function f1(){return Function.prototype.toString.call(this)+`;
|
|
13
|
+
`+S1}try{if(typeof Object.defineProperty==="function")Object.defineProperty(E1.escapeXML,"toString",{value:f1});else E1.escapeXML.toString=f1}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}E1.shallowCopy=function(f,v){if(v=v||{},f!==null&&f!==void 0)for(var g in v){if(!R(v,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=v[g]}return f};E1.shallowCopyFromList=function(f,v,g){if(g=g||[],v=v||{},f!==null&&f!==void 0)for(var A=0;A<g.length;A++){var C=g[A];if(typeof v[C]!="undefined"){if(!R(v,C))continue;if(C==="__proto__"||C==="constructor")continue;f[C]=v[C]}}return f};E1.cache={_data:{},set:function(f,v){this._data[f]=v},get:function(f){return this._data[f]},remove:function(f){delete this._data[f]},reset:function(){this._data={}}};E1.hyphenToCamel=function(f){return f.replace(/-[a-z]/g,function(v){return v[1].toUpperCase()})};E1.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();E1.hasOwnOnlyObject=function(f){var v=E1.createNullProtoObjWherePossible();for(var g in f)if(R(f,g))v[g]=f[g];return v}});var A1=F((V0,h1)=>{h1.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}});var G1=F(($1)=>{var x=(()=>({})),U=(t(),q1(p)),Z=v1(),C1=!1,d1=A1().version,m1="<",l1=">",n1="%",Y1="locals",i1="ejs",e1="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",Z1=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],s1=Z1.concat("cache"),b1=/^\uFEFF/,L=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;$1.cache=Z.cache;$1.fileLoader=x.readFileSync;$1.localsName=Y1;$1.promiseImpl=new Function("return this;")().Promise;$1.resolveInclude=function(f,v,g){var{dirname:A,extname:C,resolve:b}=U,w=b(g?v:A(v),f),j=C(f);if(!j)w+=".ejs";return w};function w1(f,v){var g;if(v.some(function(A){return g=$1.resolveInclude(f,A,!0),x.existsSync(g)}))return g}function a1(f,v){var g,A,C=v.views,b=/^[A-Za-z]+:\\|^\//.exec(f);if(b&&b.length)if(f=f.replace(/^\/*/,""),Array.isArray(v.root))g=w1(f,v.root);else g=$1.resolveInclude(f,v.root||"/",!0);else{if(v.filename){if(A=$1.resolveInclude(f,v.filename),x.existsSync(A))g=A}if(!g&&Array.isArray(C))g=w1(f,C);if(!g&&typeof v.includer!=="function")throw new Error('Could not find the include file "'+v.escapeFunction(f)+'"')}return g}function W(f,v){var g,A=f.filename,C=arguments.length>1;if(f.cache){if(!A)throw new Error("cache option requires a filename");if(g=$1.cache.get(A),g)return g;if(!C)v=j1(A).toString().replace(b1,"")}else if(!C){if(!A)throw new Error("Internal EJS error: no file name or template provided");v=j1(A).toString().replace(b1,"")}if(g=$1.compile(v,f),f.cache)$1.cache.set(A,g);return g}function o1(f,v,g){var A;if(!g)if(typeof $1.promiseImpl=="function")return new $1.promiseImpl(function(C,b){try{A=W(f)(v),C(A)}catch(w){b(w)}});else throw new Error("Please provide a callback function");else{try{A=W(f)(v)}catch(C){return g(C)}g(null,A)}}function j1(f){return $1.fileLoader(f)}function p1(f,v){var g=Z.shallowCopy(Z.createNullProtoObjWherePossible(),v);if(g.filename=a1(f,g),typeof v.includer==="function"){var A=v.includer(f,g.filename);if(A){if(A.filename)g.filename=A.filename;if(A.template)return W(g,A.template)}}return W(g)}function z1(f,v,g,A,C){var b=v.split(`
|
|
14
|
+
`),w=Math.max(A-3,0),j=Math.min(b.length,A+3),K=C(g),Y=b.slice(w,j).map(function(z,V){var G=V+w+1;return(G==A?" >> ":" ")+G+"| "+z}).join(`
|
|
15
|
+
`);throw f.path=K,f.message=(K||"ejs")+":"+A+`
|
|
16
16
|
`+Y+`
|
|
17
17
|
|
|
18
|
-
`+f.message,f}function K1(f){return f.replace(/;(\s*$)/,"$1")}$1.compile=function f(v,g){var
|
|
18
|
+
`+f.message,f}function K1(f){return f.replace(/;(\s*$)/,"$1")}$1.compile=function f(v,g){var A;if(g&&g.scope){if(!C1)console.warn("`scope` option is deprecated and will be removed in EJS 3"),C1=!0;if(!g.context)g.context=g.scope;delete g.scope}return A=new $(v,g),A.compile()};$1.render=function(f,v,g){var A=v||Z.createNullProtoObjWherePossible(),C=g||Z.createNullProtoObjWherePossible();if(arguments.length==2)Z.shallowCopyFromList(C,A,Z1);return W(C,f)(A)};$1.renderFile=function(){var f=Array.prototype.slice.call(arguments),v=f.shift(),g,A={filename:v},C,b;if(typeof arguments[arguments.length-1]=="function")g=f.pop();if(f.length){if(C=f.shift(),f.length)Z.shallowCopy(A,f.pop());else{if(C.settings){if(C.settings.views)A.views=C.settings.views;if(C.settings["view cache"])A.cache=!0;if(b=C.settings["view options"],b)Z.shallowCopy(A,b)}Z.shallowCopyFromList(A,C,s1)}A.filename=v}else C=Z.createNullProtoObjWherePossible();return o1(A,C,g)};$1.Template=$;$1.clearCache=function(){$1.cache.reset()};function $(f,v){var g=Z.hasOwnOnlyObject(v),A=Z.createNullProtoObjWherePossible();if(this.templateText=f,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",A.client=g.client||!1,A.escapeFunction=g.escape||g.escapeFunction||Z.escapeXML,A.compileDebug=g.compileDebug!==!1,A.debug=!!g.debug,A.filename=g.filename,A.openDelimiter=g.openDelimiter||$1.openDelimiter||m1,A.closeDelimiter=g.closeDelimiter||$1.closeDelimiter||l1,A.delimiter=g.delimiter||$1.delimiter||n1,A.strict=g.strict||!1,A.context=g.context,A.cache=g.cache||!1,A.rmWhitespace=g.rmWhitespace,A.root=g.root,A.includer=g.includer,A.outputFunctionName=g.outputFunctionName,A.localsName=g.localsName||$1.localsName||Y1,A.views=g.views,A.async=g.async,A.destructuredLocals=g.destructuredLocals,A.legacyInclude=typeof g.legacyInclude!="undefined"?!!g.legacyInclude:!0,A.strict)A._with=!1;else A._with=typeof g._with!="undefined"?g._with:!0;this.opts=A,this.regex=this.createRegex()}$.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};$.prototype={createRegex:function(){var f=e1,v=Z.escapeRegExpChars(this.opts.delimiter),g=Z.escapeRegExpChars(this.opts.openDelimiter),A=Z.escapeRegExpChars(this.opts.closeDelimiter);return f=f.replace(/%/g,v).replace(/</g,g).replace(/>/g,A),new RegExp(f)},compile:function(){var f,v,g=this.opts,A="",C="",b=g.escapeFunction,w,j=g.filename?JSON.stringify(g.filename):"undefined";if(!this.source){if(this.generateSource(),A+=` var __output = "";
|
|
19
19
|
function __append(s) { if (s !== undefined && s !== null) __output += s }
|
|
20
|
-
`,g.outputFunctionName){if(!L.test(g.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");
|
|
20
|
+
`,g.outputFunctionName){if(!L.test(g.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");A+=" var "+g.outputFunctionName+` = __append;
|
|
21
21
|
`}if(g.localsName&&!L.test(g.localsName))throw new Error("localsName is not a valid JS identifier.");if(g.destructuredLocals&&g.destructuredLocals.length){var K=" var __locals = ("+g.localsName+` || {}),
|
|
22
22
|
`;for(var Y=0;Y<g.destructuredLocals.length;Y++){var z=g.destructuredLocals[Y];if(!L.test(z))throw new Error("destructuredLocals["+Y+"] is not a valid JS identifier.");if(Y>0)K+=`,
|
|
23
|
-
`;K+=z+" = __locals."+z}
|
|
24
|
-
`}if(g._with!==!1)
|
|
25
|
-
`,
|
|
26
|
-
`;
|
|
27
|
-
`,this.source=
|
|
23
|
+
`;K+=z+" = __locals."+z}A+=K+`;
|
|
24
|
+
`}if(g._with!==!1)A+=" with ("+g.localsName+` || {}) {
|
|
25
|
+
`,C+=` }
|
|
26
|
+
`;C+=` return __output;
|
|
27
|
+
`,this.source=A+this.source+C}if(g.compileDebug)f=`var __line = 1
|
|
28
28
|
, __lines = `+JSON.stringify(this.templateText)+`
|
|
29
29
|
, __filename = `+j+`;
|
|
30
30
|
try {
|
|
@@ -40,15 +40,15 @@ try {
|
|
|
40
40
|
|
|
41
41
|
`,J.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
42
|
`,J.message+="https://github.com/RyanZim/EJS-Lint",!g.async)J.message+=`
|
|
43
|
-
`,J.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw J}var V=g.client?v:function J(I){var
|
|
44
|
-
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var v=this,g=this.parseTemplateText(),
|
|
45
|
-
`},scanLine:function(f){var v=this,g=this.opts.delimiter,
|
|
46
|
-
`).length-1,f){case
|
|
47
|
-
`;break;case g+g+
|
|
48
|
-
`;break;case g+
|
|
43
|
+
`,J.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw J}var V=g.client?v:function J(I){var B1=function(X1,S){var N=Z.shallowCopy(Z.createNullProtoObjWherePossible(),I);if(S)N=Z.shallowCopy(N,S);return p1(X1,g)(N)};return v.apply(g.context,[I||Z.createNullProtoObjWherePossible(),b,B1,z1])};if(g.filename&&typeof Object.defineProperty==="function"){var G=g.filename,B=U.basename(G,U.extname(G));try{Object.defineProperty(V,"name",{value:B,writable:!1,enumerable:!1,configurable:!0})}catch(J){}}return V},generateSource:function(){var f=this.opts;if(f.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
|
+
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var v=this,g=this.parseTemplateText(),A=this.opts.delimiter,C=this.opts.openDelimiter,b=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(w,j){var K;if(w.indexOf(C+A)===0&&w.indexOf(C+A+A)!==0){if(K=g[j+2],!(K==A+b||K=="-"+A+b||K=="_"+A+b))throw new Error('Could not find matching close tag for "'+w+'".')}v.scanLine(w)})},parseTemplateText:function(){var f=this.templateText,v=this.regex,g=v.exec(f),A=[],C;while(g){if(C=g.index,C!==0)A.push(f.substring(0,C)),f=f.slice(C);A.push(g[0]),f=f.slice(g[0].length),g=v.exec(f)}if(f)A.push(f);return A},_addOutput:function(f){if(this.truncate)f=f.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!f)return f;f=f.replace(/\\/g,"\\\\"),f=f.replace(/\n/g,"\\n"),f=f.replace(/\r/g,"\\r"),f=f.replace(/"/g,"\\\""),this.source+=' ; __append("'+f+`")
|
|
45
|
+
`},scanLine:function(f){var v=this,g=this.opts.delimiter,A=this.opts.openDelimiter,C=this.opts.closeDelimiter,b=0;switch(b=f.split(`
|
|
46
|
+
`).length-1,f){case A+g:case A+g+"_":this.mode=$.modes.EVAL;break;case A+g+"=":this.mode=$.modes.ESCAPED;break;case A+g+"-":this.mode=$.modes.RAW;break;case A+g+"#":this.mode=$.modes.COMMENT;break;case A+g+g:this.mode=$.modes.LITERAL,this.source+=' ; __append("'+f.replace(A+g+g,A+g)+`")
|
|
47
|
+
`;break;case g+g+C:this.mode=$.modes.LITERAL,this.source+=' ; __append("'+f.replace(g+g+C,g+C)+`")
|
|
48
|
+
`;break;case g+C:case"-"+g+C:case"_"+g+C:if(this.mode==$.modes.LITERAL)this._addOutput(f);this.mode=null,this.truncate=f.indexOf("-")===0||f.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case $.modes.EVAL:case $.modes.ESCAPED:case $.modes.RAW:if(f.lastIndexOf("//")>f.lastIndexOf(`
|
|
49
49
|
`))f+=`
|
|
50
50
|
`}switch(this.mode){case $.modes.EVAL:this.source+=" ; "+f+`
|
|
51
51
|
`;break;case $.modes.ESCAPED:this.source+=" ; __append(escapeFn("+K1(f)+`))
|
|
52
52
|
`;break;case $.modes.RAW:this.source+=" ; __append("+K1(f)+`)
|
|
53
53
|
`;break;case $.modes.COMMENT:break;case $.modes.LITERAL:this._addOutput(f);break}}else this._addOutput(f)}if(v.opts.compileDebug&&b)this.currentLine+=b,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
-
`}};$1.escapeXML=Z.escapeXML;$1.__express=$1.renderFile;$1.VERSION=d1;$1.name=i1;if(typeof window!="undefined")window.ejs=$1});function
|
|
54
|
+
`}};$1.escapeXML=Z.escapeXML;$1.__express=$1.renderFile;$1.VERSION=d1;$1.name=i1;if(typeof window!="undefined")window.ejs=$1});function P(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var k=null;async function j0(){if(!k){let f=await Promise.resolve().then(() => H1(G1(),1));k=f.default||f}return k}class z0{req;server;path;routePattern;env;executionContext;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor(f,v,g,A,C,b){this.req=f,this.server=v,this.path=g,this.routePattern=A,this.executionContext=b,this.env=C}setHeader(f,v){return this.headers.set(f,v),this}removeHeader(f){return this.headers.delete(f),this}set(f,v){return this.contextData[f]=v,this}get(f){return this.contextData[f]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!this.parsedParams&&this.routePattern)try{this.parsedParams=Y0(this.routePattern,this.path)}catch(f){let v=f instanceof Error?f.message:String(f);throw new Error(`Failed to extract route parameters: ${v}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let f=await Z0(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f}catch(f){throw new Error("Invalid request body format")}})();return this.parsedBody}text(f,v=200){return new Response(f,{status:v,headers:this.headers})}send(f,v=200){let g;if(f instanceof Uint8Array)g="Uint8Array";else if(f instanceof ArrayBuffer)g="ArrayBuffer";else g=typeof f;let A=g==="object"&&f!==null?JSON.stringify(f):f;return new Response(A,{status:v,headers:this.headers})}json(f,v=200){return Response.json(f,{status:v,headers:this.headers})}file(f,v,g=200){let A=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",v??P(f));return new Response(A,{status:g,headers:this.headers})}async ejs(f,v={},g=200){let A=await j0();try{let C=await Bun.file(f).text(),b=A.render(C,v),w=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(b,{status:g,headers:w})}catch(C){return console.error("EJS Rendering Error:",C),new Response("Error rendering template",{status:500})}}redirect(f,v=302){return this.headers.set("Location",f),new Response(null,{status:v,headers:this.headers})}setCookie(f,v,g={}){let A=`${encodeURIComponent(f)}=${encodeURIComponent(v)}`;if(g.maxAge)A+=`; Max-Age=${g.maxAge}`;if(g.expires)A+=`; Expires=${g.expires.toUTCString()}`;if(g.path)A+=`; Path=${g.path}`;if(g.domain)A+=`; Domain=${g.domain}`;if(g.secure)A+="; Secure";if(g.httpOnly)A+="; HttpOnly";if(g.sameSite)A+=`; SameSite=${g.sameSite}`;return this.headers.append("Set-Cookie",A),this}get cookies(){if(!this.parsedCookies){let f=this.req.headers.get("cookie");this.parsedCookies=f?K0(f):{}}return this.parsedCookies}stream(f){let v=new Headers(this.headers),g=new ReadableStream({async start(A){await f(A),A.close()}});return new Response(g,{headers:v})}yieldStream(f){return new Response}}function K0(f){return Object.fromEntries(f.split(";").map((v)=>{let[g,...A]=v.trim().split("=");return[g,decodeURIComponent(A.join("="))]}))}function Y0(f,v){let g={},A=f.split("/"),[C]=v.split("?"),b=C.split("/");if(A.length!==b.length)return null;for(let w=0;w<A.length;w++){let j=A[w];if(j.charCodeAt(0)===58)g[j.slice(1)]=b[w]}return g}async function Z0(f){let v=f.headers.get("Content-Type")||"";if(!v)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};if(v.startsWith("application/json"))return await f.json();if(v.startsWith("application/x-www-form-urlencoded")){let A=await f.text();return Object.fromEntries(new URLSearchParams(A))}if(v.startsWith("multipart/form-data")){let A=await f.formData(),C={};for(let[b,w]of A.entries())C[b]=w;return C}return{error:"Unknown request body type"}}export{Y0 as extractDynamicParams,z0 as Context};
|
package/dist/handleRequest.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Of=Object.create;var{getPrototypeOf:Lf,defineProperty:M,getOwnPropertyNames:i,getOwnPropertyDescriptor:Sf}=Object,u=Object.prototype.hasOwnProperty;var bf=(f,w,g)=>{g=f!=null?Of(Lf(f)):{};let A=w||!f||!f.__esModule?M(g,"default",{value:f,enumerable:!0}):g;for(let $ of i(f))if(!u.call(A,$))M(A,$,{get:()=>f[$],enumerable:!0});return A},r=new WeakMap,Ef=(f)=>{var w=r.get(f),g;if(w)return w;if(w=M({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")i(f).map((A)=>!u.call(w,A)&&M(w,A,{get:()=>f[A],enumerable:!(g=Sf(f,A))||g.enumerable}));return r.set(f,w),w},L=(f,w)=>()=>(w||f((w={exports:{}}).exports,w),w.exports);var qf=(f,w)=>{for(var g in w)M(f,g,{get:w[g],enumerable:!0,configurable:!0,set:(A)=>w[g]=()=>A})};var Tf=(f,w)=>()=>(f&&(w=f(f=0)),w);var cf=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(w,g)=>(typeof require!=="undefined"?require:w)[g]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var wf={};qf(wf,{sep:()=>e,resolve:()=>
|
|
1
|
+
var Of=Object.create;var{getPrototypeOf:Lf,defineProperty:M,getOwnPropertyNames:i,getOwnPropertyDescriptor:Sf}=Object,u=Object.prototype.hasOwnProperty;var bf=(f,w,g)=>{g=f!=null?Of(Lf(f)):{};let A=w||!f||!f.__esModule?M(g,"default",{value:f,enumerable:!0}):g;for(let $ of i(f))if(!u.call(A,$))M(A,$,{get:()=>f[$],enumerable:!0});return A},r=new WeakMap,Ef=(f)=>{var w=r.get(f),g;if(w)return w;if(w=M({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")i(f).map((A)=>!u.call(w,A)&&M(w,A,{get:()=>f[A],enumerable:!(g=Sf(f,A))||g.enumerable}));return r.set(f,w),w},L=(f,w)=>()=>(w||f((w={exports:{}}).exports,w),w.exports);var qf=(f,w)=>{for(var g in w)M(f,g,{get:w[g],enumerable:!0,configurable:!0,set:(A)=>w[g]=()=>A})};var Tf=(f,w)=>()=>(f&&(w=f(f=0)),w);var cf=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(w,g)=>(typeof require!=="undefined"?require:w)[g]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var wf={};qf(wf,{sep:()=>e,resolve:()=>v,relative:()=>d,posix:()=>gf,parse:()=>t,normalize:()=>S,join:()=>m,isAbsolute:()=>h,format:()=>p,extname:()=>a,dirname:()=>o,delimiter:()=>ff,default:()=>_f,basename:()=>s,_makeLong:()=>l});function F(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function n(f,w){var g="",A=0,$=-1,z=0,J;for(var Y=0;Y<=f.length;++Y){if(Y<f.length)J=f.charCodeAt(Y);else if(J===47)break;else J=47;if(J===47){if($===Y-1||z===1);else if($!==Y-1&&z===2){if(g.length<2||A!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var j=g.lastIndexOf("/");if(j!==g.length-1){if(j===-1)g="",A=0;else g=g.slice(0,j),A=g.length-1-g.lastIndexOf("/");$=Y,z=0;continue}}else if(g.length===2||g.length===1){g="",A=0,$=Y,z=0;continue}}if(w){if(g.length>0)g+="/..";else g="..";A=2}}else{if(g.length>0)g+="/"+f.slice($+1,Y);else g=f.slice($+1,Y);A=Y-$-1}$=Y,z=0}else if(J===46&&z!==-1)++z;else z=-1}return g}function Pf(f,w){var g=w.dir||w.root,A=w.base||(w.name||"")+(w.ext||"");if(!g)return A;if(g===w.root)return g+A;return g+f+A}function v(){var f="",w=!1,g;for(var A=arguments.length-1;A>=-1&&!w;A--){var $;if(A>=0)$=arguments[A];else{if(g===void 0)g=process.cwd();$=g}if(F($),$.length===0)continue;f=$+"/"+f,w=$.charCodeAt(0)===47}if(f=n(f,!w),w)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function S(f){if(F(f),f.length===0)return".";var w=f.charCodeAt(0)===47,g=f.charCodeAt(f.length-1)===47;if(f=n(f,!w),f.length===0&&!w)f=".";if(f.length>0&&g)f+="/";if(w)return"/"+f;return f}function h(f){return F(f),f.length>0&&f.charCodeAt(0)===47}function m(){if(arguments.length===0)return".";var f;for(var w=0;w<arguments.length;++w){var g=arguments[w];if(F(g),g.length>0)if(f===void 0)f=g;else f+="/"+g}if(f===void 0)return".";return S(f)}function d(f,w){if(F(f),F(w),f===w)return"";if(f=v(f),w=v(w),f===w)return"";var g=1;for(;g<f.length;++g)if(f.charCodeAt(g)!==47)break;var A=f.length,$=A-g,z=1;for(;z<w.length;++z)if(w.charCodeAt(z)!==47)break;var J=w.length,Y=J-z,j=$<Y?$:Y,V=-1,Z=0;for(;Z<=j;++Z){if(Z===j){if(Y>j){if(w.charCodeAt(z+Z)===47)return w.slice(z+Z+1);else if(Z===0)return w.slice(z+Z)}else if($>j){if(f.charCodeAt(g+Z)===47)V=Z;else if(Z===0)V=0}break}var X=f.charCodeAt(g+Z),W=w.charCodeAt(z+Z);if(X!==W)break;else if(X===47)V=Z}var G="";for(Z=g+V+1;Z<=A;++Z)if(Z===A||f.charCodeAt(Z)===47)if(G.length===0)G+="..";else G+="/..";if(G.length>0)return G+w.slice(z+V);else{if(z+=V,w.charCodeAt(z)===47)++z;return w.slice(z)}}function l(f){return f}function o(f){if(F(f),f.length===0)return".";var w=f.charCodeAt(0),g=w===47,A=-1,$=!0;for(var z=f.length-1;z>=1;--z)if(w=f.charCodeAt(z),w===47){if(!$){A=z;break}}else $=!1;if(A===-1)return g?"/":".";if(g&&A===1)return"//";return f.slice(0,A)}function s(f,w){if(w!==void 0&&typeof w!=="string")throw new TypeError('"ext" argument must be a string');F(f);var g=0,A=-1,$=!0,z;if(w!==void 0&&w.length>0&&w.length<=f.length){if(w.length===f.length&&w===f)return"";var J=w.length-1,Y=-1;for(z=f.length-1;z>=0;--z){var j=f.charCodeAt(z);if(j===47){if(!$){g=z+1;break}}else{if(Y===-1)$=!1,Y=z+1;if(J>=0)if(j===w.charCodeAt(J)){if(--J===-1)A=z}else J=-1,A=Y}}if(g===A)A=Y;else if(A===-1)A=f.length;return f.slice(g,A)}else{for(z=f.length-1;z>=0;--z)if(f.charCodeAt(z)===47){if(!$){g=z+1;break}}else if(A===-1)$=!1,A=z+1;if(A===-1)return"";return f.slice(g,A)}}function a(f){F(f);var w=-1,g=0,A=-1,$=!0,z=0;for(var J=f.length-1;J>=0;--J){var Y=f.charCodeAt(J);if(Y===47){if(!$){g=J+1;break}continue}if(A===-1)$=!1,A=J+1;if(Y===46){if(w===-1)w=J;else if(z!==1)z=1}else if(w!==-1)z=-1}if(w===-1||A===-1||z===0||z===1&&w===A-1&&w===g+1)return"";return f.slice(w,A)}function p(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return Pf("/",f)}function t(f){F(f);var w={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return w;var g=f.charCodeAt(0),A=g===47,$;if(A)w.root="/",$=1;else $=0;var z=-1,J=0,Y=-1,j=!0,V=f.length-1,Z=0;for(;V>=$;--V){if(g=f.charCodeAt(V),g===47){if(!j){J=V+1;break}continue}if(Y===-1)j=!1,Y=V+1;if(g===46){if(z===-1)z=V;else if(Z!==1)Z=1}else if(z!==-1)Z=-1}if(z===-1||Y===-1||Z===0||Z===1&&z===Y-1&&z===J+1){if(Y!==-1)if(J===0&&A)w.base=w.name=f.slice(1,Y);else w.base=w.name=f.slice(J,Y)}else{if(J===0&&A)w.name=f.slice(1,z),w.base=f.slice(1,Y);else w.name=f.slice(J,z),w.base=f.slice(J,Y);w.ext=f.slice(z,Y)}if(J>0)w.dir=f.slice(0,J-1);else if(A)w.dir="/";return w}var e="/",ff=":",gf,_f;var Af=Tf(()=>{gf=((f)=>(f.posix=f,f))({resolve:v,normalize:S,isAbsolute:h,join:m,relative:d,_makeLong:l,dirname:o,basename:s,extname:a,format:p,parse:t,sep:e,delimiter:ff,win32:null,posix:null}),_f=gf});var Jf=L((nf)=>{var yf=/[|\\{}()[\]^$+*?.]/g,kf=Object.prototype.hasOwnProperty,E=function(f,w){return kf.apply(f,[w])};nf.escapeRegExpChars=function(f){if(!f)return"";return String(f).replace(yf,"\\$&")};var If={"&":"&","<":"<",">":">",'"':""","'":"'"},xf=/[&<>'"]/g;function rf(f){return If[f]||f}var uf=`var _ENCODE_HTML_RULES = {
|
|
2
2
|
"&": "&"
|
|
3
3
|
, "<": "<"
|
|
4
4
|
, ">": ">"
|
|
@@ -10,45 +10,45 @@ function encode_char(c) {
|
|
|
10
10
|
return _ENCODE_HTML_RULES[c] || c;
|
|
11
11
|
};
|
|
12
12
|
`;nf.escapeXML=function(f){return f==null?"":String(f).replace(xf,rf)};function $f(){return Function.prototype.toString.call(this)+`;
|
|
13
|
-
`+uf}try{if(typeof Object.defineProperty==="function")Object.defineProperty(nf.escapeXML,"toString",{value:$f});else nf.escapeXML.toString=$f}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}nf.shallowCopy=function(f,w){if(w=w||{},f!==null&&f!==void 0)for(var g in w){if(!E(w,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=w[g]}return f};nf.shallowCopyFromList=function(f,w,g){if(g=g||[],w=w||{},f!==null&&f!==void 0)for(var A=0;A<g.length;A++){var $=g[A];if(typeof w[$]!="undefined"){if(!E(w,$))continue;if($==="__proto__"||$==="constructor")continue;f[$]=w[$]}}return f};nf.cache={_data:{},set:function(f,w){this._data[f]=w},get:function(f){return this._data[f]},remove:function(f){delete this._data[f]},reset:function(){this._data={}}};nf.hyphenToCamel=function(f){return f.replace(/-[a-z]/g,function(w){return w[1].toUpperCase()})};nf.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();nf.hasOwnOnlyObject=function(f){var w=nf.createNullProtoObjWherePossible();for(var g in f)if(E(f,g))w[g]=f[g];return w}});var
|
|
14
|
-
`),
|
|
15
|
-
`);throw f.path=
|
|
16
|
-
`+
|
|
13
|
+
`+uf}try{if(typeof Object.defineProperty==="function")Object.defineProperty(nf.escapeXML,"toString",{value:$f});else nf.escapeXML.toString=$f}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}nf.shallowCopy=function(f,w){if(w=w||{},f!==null&&f!==void 0)for(var g in w){if(!E(w,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=w[g]}return f};nf.shallowCopyFromList=function(f,w,g){if(g=g||[],w=w||{},f!==null&&f!==void 0)for(var A=0;A<g.length;A++){var $=g[A];if(typeof w[$]!="undefined"){if(!E(w,$))continue;if($==="__proto__"||$==="constructor")continue;f[$]=w[$]}}return f};nf.cache={_data:{},set:function(f,w){this._data[f]=w},get:function(f){return this._data[f]},remove:function(f){delete this._data[f]},reset:function(){this._data={}}};nf.hyphenToCamel=function(f){return f.replace(/-[a-z]/g,function(w){return w[1].toUpperCase()})};nf.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();nf.hasOwnOnlyObject=function(f){var w=nf.createNullProtoObjWherePossible();for(var g in f)if(E(f,g))w[g]=f[g];return w}});var Yf=L((O1,af)=>{af.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}});var Nf=L((Ff)=>{var c=(()=>({})),R=(Af(),Ef(wf)),B=Jf(),Zf=!1,pf=Yf().version,tf="<",ef=">",f1="%",Wf="locals",g1="ejs",w1="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",Xf=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],A1=Xf.concat("cache"),jf=/^\uFEFF/,q=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;Ff.cache=B.cache;Ff.fileLoader=c.readFileSync;Ff.localsName=Wf;Ff.promiseImpl=new Function("return this;")().Promise;Ff.resolveInclude=function(f,w,g){var{dirname:A,extname:$,resolve:z}=R,J=z(g?w:A(w),f),Y=$(f);if(!Y)J+=".ejs";return J};function Vf(f,w){var g;if(w.some(function(A){return g=Ff.resolveInclude(f,A,!0),c.existsSync(g)}))return g}function $1(f,w){var g,A,$=w.views,z=/^[A-Za-z]+:\\|^\//.exec(f);if(z&&z.length)if(f=f.replace(/^\/*/,""),Array.isArray(w.root))g=Vf(f,w.root);else g=Ff.resolveInclude(f,w.root||"/",!0);else{if(w.filename){if(A=Ff.resolveInclude(f,w.filename),c.existsSync(A))g=A}if(!g&&Array.isArray($))g=Vf(f,$);if(!g&&typeof w.includer!=="function")throw new Error('Could not find the include file "'+w.escapeFunction(f)+'"')}return g}function N(f,w){var g,A=f.filename,$=arguments.length>1;if(f.cache){if(!A)throw new Error("cache option requires a filename");if(g=Ff.cache.get(A),g)return g;if(!$)w=Bf(A).toString().replace(jf,"")}else if(!$){if(!A)throw new Error("Internal EJS error: no file name or template provided");w=Bf(A).toString().replace(jf,"")}if(g=Ff.compile(w,f),f.cache)Ff.cache.set(A,g);return g}function z1(f,w,g){var A;if(!g)if(typeof Ff.promiseImpl=="function")return new Ff.promiseImpl(function($,z){try{A=N(f)(w),$(A)}catch(J){z(J)}});else throw new Error("Please provide a callback function");else{try{A=N(f)(w)}catch($){return g($)}g(null,A)}}function Bf(f){return Ff.fileLoader(f)}function J1(f,w){var g=B.shallowCopy(B.createNullProtoObjWherePossible(),w);if(g.filename=$1(f,g),typeof w.includer==="function"){var A=w.includer(f,g.filename);if(A){if(A.filename)g.filename=A.filename;if(A.template)return N(g,A.template)}}return N(g)}function Cf(f,w,g,A,$){var z=w.split(`
|
|
14
|
+
`),J=Math.max(A-3,0),Y=Math.min(z.length,A+3),j=$(g),V=z.slice(J,Y).map(function(Z,X){var W=X+J+1;return(W==A?" >> ":" ")+W+"| "+Z}).join(`
|
|
15
|
+
`);throw f.path=j,f.message=(j||"ejs")+":"+A+`
|
|
16
|
+
`+V+`
|
|
17
17
|
|
|
18
|
-
`+f.message,f}function
|
|
18
|
+
`+f.message,f}function Qf(f){return f.replace(/;(\s*$)/,"$1")}Ff.compile=function f(w,g){var A;if(g&&g.scope){if(!Zf)console.warn("`scope` option is deprecated and will be removed in EJS 3"),Zf=!0;if(!g.context)g.context=g.scope;delete g.scope}return A=new C(w,g),A.compile()};Ff.render=function(f,w,g){var A=w||B.createNullProtoObjWherePossible(),$=g||B.createNullProtoObjWherePossible();if(arguments.length==2)B.shallowCopyFromList($,A,Xf);return N($,f)(A)};Ff.renderFile=function(){var f=Array.prototype.slice.call(arguments),w=f.shift(),g,A={filename:w},$,z;if(typeof arguments[arguments.length-1]=="function")g=f.pop();if(f.length){if($=f.shift(),f.length)B.shallowCopy(A,f.pop());else{if($.settings){if($.settings.views)A.views=$.settings.views;if($.settings["view cache"])A.cache=!0;if(z=$.settings["view options"],z)B.shallowCopy(A,z)}B.shallowCopyFromList(A,$,A1)}A.filename=w}else $=B.createNullProtoObjWherePossible();return z1(A,$,g)};Ff.Template=C;Ff.clearCache=function(){Ff.cache.reset()};function C(f,w){var g=B.hasOwnOnlyObject(w),A=B.createNullProtoObjWherePossible();if(this.templateText=f,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",A.client=g.client||!1,A.escapeFunction=g.escape||g.escapeFunction||B.escapeXML,A.compileDebug=g.compileDebug!==!1,A.debug=!!g.debug,A.filename=g.filename,A.openDelimiter=g.openDelimiter||Ff.openDelimiter||tf,A.closeDelimiter=g.closeDelimiter||Ff.closeDelimiter||ef,A.delimiter=g.delimiter||Ff.delimiter||f1,A.strict=g.strict||!1,A.context=g.context,A.cache=g.cache||!1,A.rmWhitespace=g.rmWhitespace,A.root=g.root,A.includer=g.includer,A.outputFunctionName=g.outputFunctionName,A.localsName=g.localsName||Ff.localsName||Wf,A.views=g.views,A.async=g.async,A.destructuredLocals=g.destructuredLocals,A.legacyInclude=typeof g.legacyInclude!="undefined"?!!g.legacyInclude:!0,A.strict)A._with=!1;else A._with=typeof g._with!="undefined"?g._with:!0;this.opts=A,this.regex=this.createRegex()}C.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};C.prototype={createRegex:function(){var f=w1,w=B.escapeRegExpChars(this.opts.delimiter),g=B.escapeRegExpChars(this.opts.openDelimiter),A=B.escapeRegExpChars(this.opts.closeDelimiter);return f=f.replace(/%/g,w).replace(/</g,g).replace(/>/g,A),new RegExp(f)},compile:function(){var f,w,g=this.opts,A="",$="",z=g.escapeFunction,J,Y=g.filename?JSON.stringify(g.filename):"undefined";if(!this.source){if(this.generateSource(),A+=` var __output = "";
|
|
19
19
|
function __append(s) { if (s !== undefined && s !== null) __output += s }
|
|
20
20
|
`,g.outputFunctionName){if(!q.test(g.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");A+=" var "+g.outputFunctionName+` = __append;
|
|
21
|
-
`}if(g.localsName&&!q.test(g.localsName))throw new Error("localsName is not a valid JS identifier.");if(g.destructuredLocals&&g.destructuredLocals.length){var
|
|
22
|
-
`;for(var
|
|
23
|
-
`;Z
|
|
21
|
+
`}if(g.localsName&&!q.test(g.localsName))throw new Error("localsName is not a valid JS identifier.");if(g.destructuredLocals&&g.destructuredLocals.length){var j=" var __locals = ("+g.localsName+` || {}),
|
|
22
|
+
`;for(var V=0;V<g.destructuredLocals.length;V++){var Z=g.destructuredLocals[V];if(!q.test(Z))throw new Error("destructuredLocals["+V+"] is not a valid JS identifier.");if(V>0)j+=`,
|
|
23
|
+
`;j+=Z+" = __locals."+Z}A+=j+`;
|
|
24
24
|
`}if(g._with!==!1)A+=" with ("+g.localsName+` || {}) {
|
|
25
25
|
`,$+=` }
|
|
26
26
|
`;$+=` return __output;
|
|
27
27
|
`,this.source=A+this.source+$}if(g.compileDebug)f=`var __line = 1
|
|
28
28
|
, __lines = `+JSON.stringify(this.templateText)+`
|
|
29
|
-
, __filename = `+
|
|
29
|
+
, __filename = `+Y+`;
|
|
30
30
|
try {
|
|
31
31
|
`+this.source+`} catch (e) {
|
|
32
32
|
rethrow(e, __lines, __filename, __line, escapeFn);
|
|
33
33
|
}
|
|
34
34
|
`;else f=this.source;if(g.client){if(f="escapeFn = escapeFn || "+z.toString()+`;
|
|
35
|
-
`+f,g.compileDebug)f="rethrow = rethrow || "+
|
|
35
|
+
`+f,g.compileDebug)f="rethrow = rethrow || "+Cf.toString()+`;
|
|
36
36
|
`+f}if(g.strict)f=`"use strict";
|
|
37
37
|
`+f;if(g.debug)console.log(f);if(g.compileDebug&&g.filename)f=f+`
|
|
38
|
-
//# sourceURL=`+
|
|
39
|
-
`;try{if(g.async)try{
|
|
38
|
+
//# sourceURL=`+Y+`
|
|
39
|
+
`;try{if(g.async)try{J=new Function("return (async function(){}).constructor;")()}catch(Q){if(Q instanceof SyntaxError)throw new Error("This environment does not support async/await");else throw Q}else J=Function;w=new J(g.localsName+", escapeFn, include, rethrow",f)}catch(Q){if(Q instanceof SyntaxError){if(g.filename)Q.message+=" in "+g.filename;if(Q.message+=` while compiling ejs
|
|
40
40
|
|
|
41
|
-
`,
|
|
42
|
-
`,
|
|
43
|
-
`,
|
|
44
|
-
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var w=this,g=this.parseTemplateText(),A=this.opts.delimiter,$=this.opts.openDelimiter,z=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(
|
|
41
|
+
`,Q.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
|
+
`,Q.message+="https://github.com/RyanZim/EJS-Lint",!g.async)Q.message+=`
|
|
43
|
+
`,Q.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw Q}var X=g.client?w:function Q(I){var Df=function(Hf,x){var O=B.shallowCopy(B.createNullProtoObjWherePossible(),I);if(x)O=B.shallowCopy(O,x);return J1(Hf,g)(O)};return w.apply(g.context,[I||B.createNullProtoObjWherePossible(),z,Df,Cf])};if(g.filename&&typeof Object.defineProperty==="function"){var W=g.filename,G=R.basename(W,R.extname(W));try{Object.defineProperty(X,"name",{value:G,writable:!1,enumerable:!1,configurable:!0})}catch(Q){}}return X},generateSource:function(){var f=this.opts;if(f.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
|
+
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var w=this,g=this.parseTemplateText(),A=this.opts.delimiter,$=this.opts.openDelimiter,z=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(J,Y){var j;if(J.indexOf($+A)===0&&J.indexOf($+A+A)!==0){if(j=g[Y+2],!(j==A+z||j=="-"+A+z||j=="_"+A+z))throw new Error('Could not find matching close tag for "'+J+'".')}w.scanLine(J)})},parseTemplateText:function(){var f=this.templateText,w=this.regex,g=w.exec(f),A=[],$;while(g){if($=g.index,$!==0)A.push(f.substring(0,$)),f=f.slice($);A.push(g[0]),f=f.slice(g[0].length),g=w.exec(f)}if(f)A.push(f);return A},_addOutput:function(f){if(this.truncate)f=f.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!f)return f;f=f.replace(/\\/g,"\\\\"),f=f.replace(/\n/g,"\\n"),f=f.replace(/\r/g,"\\r"),f=f.replace(/"/g,"\\\""),this.source+=' ; __append("'+f+`")
|
|
45
45
|
`},scanLine:function(f){var w=this,g=this.opts.delimiter,A=this.opts.openDelimiter,$=this.opts.closeDelimiter,z=0;switch(z=f.split(`
|
|
46
|
-
`).length-1,f){case A+g:case A+g+"_":this.mode=
|
|
47
|
-
`;break;case g+g+$:this.mode=
|
|
48
|
-
`;break;case g+$:case"-"+g+$:case"_"+g+$:if(this.mode==
|
|
46
|
+
`).length-1,f){case A+g:case A+g+"_":this.mode=C.modes.EVAL;break;case A+g+"=":this.mode=C.modes.ESCAPED;break;case A+g+"-":this.mode=C.modes.RAW;break;case A+g+"#":this.mode=C.modes.COMMENT;break;case A+g+g:this.mode=C.modes.LITERAL,this.source+=' ; __append("'+f.replace(A+g+g,A+g)+`")
|
|
47
|
+
`;break;case g+g+$:this.mode=C.modes.LITERAL,this.source+=' ; __append("'+f.replace(g+g+$,g+$)+`")
|
|
48
|
+
`;break;case g+$:case"-"+g+$:case"_"+g+$:if(this.mode==C.modes.LITERAL)this._addOutput(f);this.mode=null,this.truncate=f.indexOf("-")===0||f.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case C.modes.EVAL:case C.modes.ESCAPED:case C.modes.RAW:if(f.lastIndexOf("//")>f.lastIndexOf(`
|
|
49
49
|
`))f+=`
|
|
50
|
-
`}switch(this.mode){case
|
|
51
|
-
`;break;case
|
|
52
|
-
`;break;case
|
|
53
|
-
`;break;case
|
|
54
|
-
`}};Ff.escapeXML=
|
|
50
|
+
`}switch(this.mode){case C.modes.EVAL:this.source+=" ; "+f+`
|
|
51
|
+
`;break;case C.modes.ESCAPED:this.source+=" ; __append(escapeFn("+Qf(f)+`))
|
|
52
|
+
`;break;case C.modes.RAW:this.source+=" ; __append("+Qf(f)+`)
|
|
53
|
+
`;break;case C.modes.COMMENT:break;case C.modes.LITERAL:this._addOutput(f);break}}else this._addOutput(f)}if(w.opts.compileDebug&&z)this.currentLine+=z,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
+
`}};Ff.escapeXML=B.escapeXML;Ff.__express=Ff.renderFile;Ff.VERSION=pf;Ff.name=g1;if(typeof window!="undefined")window.ejs=Ff});function U(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var P=null;async function X1(){if(!P){let f=await Promise.resolve().then(() => bf(Nf(),1));P=f.default||f}return P}class _{req;server;path;routePattern;env;executionContext;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor(f,w,g,A,$,z){this.req=f,this.server=w,this.path=g,this.routePattern=A,this.executionContext=z,this.env=$}setHeader(f,w){return this.headers.set(f,w),this}removeHeader(f){return this.headers.delete(f),this}set(f,w){return this.contextData[f]=w,this}get(f){return this.contextData[f]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!this.parsedParams&&this.routePattern)try{this.parsedParams=G1(this.routePattern,this.path)}catch(f){let w=f instanceof Error?f.message:String(f);throw new Error(`Failed to extract route parameters: ${w}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let f=await M1(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f}catch(f){throw new Error("Invalid request body format")}})();return this.parsedBody}text(f,w=200){return new Response(f,{status:w,headers:this.headers})}send(f,w=200){let g;if(f instanceof Uint8Array)g="Uint8Array";else if(f instanceof ArrayBuffer)g="ArrayBuffer";else g=typeof f;let A=g==="object"&&f!==null?JSON.stringify(f):f;return new Response(A,{status:w,headers:this.headers})}json(f,w=200){return Response.json(f,{status:w,headers:this.headers})}file(f,w,g=200){let A=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",w??U(f));return new Response(A,{status:g,headers:this.headers})}async ejs(f,w={},g=200){let A=await X1();try{let $=await Bun.file(f).text(),z=A.render($,w),J=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(z,{status:g,headers:J})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}}redirect(f,w=302){return this.headers.set("Location",f),new Response(null,{status:w,headers:this.headers})}setCookie(f,w,g={}){let A=`${encodeURIComponent(f)}=${encodeURIComponent(w)}`;if(g.maxAge)A+=`; Max-Age=${g.maxAge}`;if(g.expires)A+=`; Expires=${g.expires.toUTCString()}`;if(g.path)A+=`; Path=${g.path}`;if(g.domain)A+=`; Domain=${g.domain}`;if(g.secure)A+="; Secure";if(g.httpOnly)A+="; HttpOnly";if(g.sameSite)A+=`; SameSite=${g.sameSite}`;return this.headers.append("Set-Cookie",A),this}get cookies(){if(!this.parsedCookies){let f=this.req.headers.get("cookie");this.parsedCookies=f?F1(f):{}}return this.parsedCookies}stream(f){let w=new Headers(this.headers),g=new ReadableStream({async start(A){await f(A),A.close()}});return new Response(g,{headers:w})}yieldStream(f){return new Response}}function F1(f){return Object.fromEntries(f.split(";").map((w)=>{let[g,...A]=w.trim().split("=");return[g,decodeURIComponent(A.join("="))]}))}function G1(f,w){let g={},A=f.split("/"),[$]=w.split("?"),z=$.split("/");if(A.length!==z.length)return null;for(let J=0;J<A.length;J++){let Y=A[J];if(Y.charCodeAt(0)===58)g[Y.slice(1)]=z[J]}return g}async function M1(f){let w=f.headers.get("Content-Type")||"";if(!w)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};if(w.startsWith("application/json"))return await f.json();if(w.startsWith("application/x-www-form-urlencoded")){let A=await f.text();return Object.fromEntries(new URLSearchParams(A))}if(w.startsWith("multipart/form-data")){let A=await f.formData(),$={};for(let[z,J]of A.entries())$[z]=J;return $}return{error:"Unknown request body type"}}var R1=(f,w)=>{try{return w(f)}catch{return f.replace(/(?:%[0-9A-Fa-f]{2})+/g,(g)=>{try{return w(g)}catch{return g}})}},y=(f)=>R1(f,decodeURI),c1=(f)=>{let w=f.indexOf("/",f.indexOf(":")+4),g=w;for(;g<f.length;g++){let A=f.charCodeAt(g);if(A===37){let $=f.indexOf("?",g),z=f.slice(w,$===-1?void 0:$);return y(z.includes("%25")?z.replace(/%25/g,"%2525"):z)}else if(A===63)break}return f.slice(w,g)};async function H(f,w,g){if(!w?.length)return;for(let A=0;A<w.length;A++){let $=w[A](...g),z=$ instanceof Promise?await $:$;if(z&&f!=="onRequest")return z}}async function Uf(f,w,g){let A=f.globalMiddlewares;if(A.length)for(let z of A){let J=await z(g);if(J)return J}let $=f.middlewares.get(w);if($&&$.length)for(let z of $){let J=await z(g);if(J)return J}return null}async function y1(f,w,g){for(let A of f){let $=await A(w,g);if($)return $}}async function vf(f,w,g){let A=await N1(f,w,g),$=A instanceof Promise?await A:A;if($)return $}async function N1(f,w,g){if(w.endsWith("/"))w=w.slice(0,-1);if(!f.filters.has(w))if(f.filterFunction.length)for(let A of f.filterFunction){let $=await A(g);if($)return $}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function Kf(f,w,g){if(f.staticPath){let $=!0;if(f.staticRequestPath)$=g.startsWith(f.staticRequestPath);if($){let z=await U1(f,g,w);if(z)return z;let J=f.trie.search("*",w.req.method);if(J?.handler)return await J.handler(w)}}let A=f.routeNotFoundFunc(w);return A instanceof Promise?await A:A||k(404,`404 Route not found for ${g}`)}function k(f,w){return new Response(JSON.stringify({error:w}),{status:f,headers:{"Content-Type":"application/json"}})}async function U1(f,w,g){if(!f.staticPath)return null;let A=`${f.staticPath}${w}`;if(await Bun.file(A).exists()){let z=U(A);return g.file(A,z,200)}return null}async function v1(f,w,g){let A,$=f.url.indexOf("/",f.url.indexOf(":")+4),z=$;for(;z<f.url.length;z++){let Z=f.url.charCodeAt(z);if(Z===37){let X=f.url.indexOf("?",z),W=f.url.slice($,X===-1?void 0:X);A=y(W.includes("%25")?W.replace(/%25/g,"%2525"):W);break}else if(Z===63)break}if(!A)A=f.url.slice($,z);let J=g.trie.search(A,f.method),Y=new _(f,w,A,J?.path);if(g.hasOnReqHook)await H("onRequest",g.hooks.onRequest,[f,A,w]);if(g.hasMiddleware){let Z=await Uf(g,A,Y);if(Z)return Z}if(g.hasFilterEnabled){let Z=await vf(g,A,Y);if(Z)return Z}if(!J)return await Kf(g,Y,A);if(g.hasPreHandlerHook){let Z=await H("preHandler",g.hooks.preHandler,[Y]);if(Z)return Z}let j=J.handler(Y),V=j instanceof Promise?await j:j;if(g.hasOnSendHook){let Z=await H("onSend",g.hooks.onSend,[Y,V]);if(Z)return Z}if(V instanceof Response)return V;return k(500,"No response returned from handler.")}export{v1 as default};
|
package/dist/main.d.ts
CHANGED
|
@@ -7,7 +7,6 @@ type errorFormat = 'json' | 'text' | 'html' | string;
|
|
|
7
7
|
export default class Diesel {
|
|
8
8
|
#private;
|
|
9
9
|
private static instance;
|
|
10
|
-
fecth: any;
|
|
11
10
|
routes: Record<string, Function>;
|
|
12
11
|
private tempRoutes;
|
|
13
12
|
globalMiddlewares: middlewareFunc[];
|
|
@@ -72,8 +71,8 @@ export default class Diesel {
|
|
|
72
71
|
BunRoute(method: string, path: string, ...handlersOrResponse: any[]): this;
|
|
73
72
|
listen(port: any, ...args: listenArgsT[]): Server | void;
|
|
74
73
|
close(callback?: () => void): void;
|
|
75
|
-
cfFetch(request: Request, env: Record<string, any>, executionCtx: any)
|
|
76
|
-
fetch(): ((request: Request, env?: Record<string, any>, executionContext?: any) => Promise<any>) | ((req: Request, server: Server) => any) | ((req: Request, server?: Server, env?: Record<string, any>,
|
|
74
|
+
cfFetch(): (request: Request, env: Record<string, any>, executionCtx: any) => Promise<any>;
|
|
75
|
+
fetch(): ((request: Request, env?: Record<string, any>, executionContext?: any) => Promise<any>) | ((req: Request, server: Server) => any) | ((req: Request, server?: Server, env?: Record<string, any>, executionContext?: any) => Promise<any>);
|
|
77
76
|
private handleError;
|
|
78
77
|
/**
|
|
79
78
|
* Registers a router instance for subrouting.
|
package/dist/main.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var C0=Object.create;var{getPrototypeOf:V0,defineProperty:R,getOwnPropertyNames:K1,getOwnPropertyDescriptor:f0}=Object,U1=Object.prototype.hasOwnProperty;var G0=($,z,Z)=>{Z=$!=null?C0(V0($)):{};let Q=z||!$||!$.__esModule?R(Z,"default",{value:$,enumerable:!0}):Z;for(let J of K1($))if(!U1.call(Q,J))R(Q,J,{get:()=>$[J],enumerable:!0});return Q},W1=new WeakMap,W0=($)=>{var z=W1.get($),Z;if(z)return z;if(z=R({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function")K1($).map((Q)=>!U1.call(z,Q)&&R(z,Q,{get:()=>$[Q],enumerable:!(Z=f0($,Q))||Z.enumerable}));return W1.set($,z),z},p=($,z)=>()=>(z||$((z={exports:{}}).exports,z),z.exports);var K0=($,z)=>{for(var Z in z)R($,Z,{get:z[Z],enumerable:!0,configurable:!0,set:(Q)=>z[Z]=()=>Q})};var U0=($,z)=>()=>($&&(z=$($=0)),z);var F0=(($)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy($,{get:(z,Z)=>(typeof require!=="undefined"?require:z)[Z]}):$)(function($){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});var T1={};K0(T1,{sep:()=>M1,resolve:()=>y,relative:()=>q1,posix:()=>I1,parse:()=>H1,normalize:()=>s,join:()=>N1,isAbsolute:()=>D1,format:()=>L1,extname:()=>j1,dirname:()=>A1,delimiter:()=>O1,default:()=>O,basename:()=>w1,_makeLong:()=>S1});function A($){if(typeof $!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify($))}function F1($,z){var Z="",Q=0,J=-1,X=0,Y;for(var B=0;B<=$.length;++B){if(B<$.length)Y=$.charCodeAt(B);else if(Y===47)break;else Y=47;if(Y===47){if(J===B-1||X===1);else if(J!==B-1&&X===2){if(Z.length<2||Q!==2||Z.charCodeAt(Z.length-1)!==46||Z.charCodeAt(Z.length-2)!==46){if(Z.length>2){var C=Z.lastIndexOf("/");if(C!==Z.length-1){if(C===-1)Z="",Q=0;else Z=Z.slice(0,C),Q=Z.length-1-Z.lastIndexOf("/");J=B,X=0;continue}}else if(Z.length===2||Z.length===1){Z="",Q=0,J=B,X=0;continue}}if(z){if(Z.length>0)Z+="/..";else Z="..";Q=2}}else{if(Z.length>0)Z+="/"+$.slice(J+1,B);else Z=$.slice(J+1,B);Q=B-J-1}J=B,X=0}else if(Y===46&&X!==-1)++X;else X=-1}return Z}function D0($,z){var Z=z.dir||z.root,Q=z.base||(z.name||"")+(z.ext||"");if(!Z)return Q;if(Z===z.root)return Z+Q;return Z+$+Q}function y(){var $="",z=!1,Z;for(var Q=arguments.length-1;Q>=-1&&!z;Q--){var J;if(Q>=0)J=arguments[Q];else{if(Z===void 0)Z=process.cwd();J=Z}if(A(J),J.length===0)continue;$=J+"/"+$,z=J.charCodeAt(0)===47}if($=F1($,!z),z)if($.length>0)return"/"+$;else return"/";else if($.length>0)return $;else return"."}function s($){if(A($),$.length===0)return".";var z=$.charCodeAt(0)===47,Z=$.charCodeAt($.length-1)===47;if($=F1($,!z),$.length===0&&!z)$=".";if($.length>0&&Z)$+="/";if(z)return"/"+$;return $}function D1($){return A($),$.length>0&&$.charCodeAt(0)===47}function N1(){if(arguments.length===0)return".";var $;for(var z=0;z<arguments.length;++z){var Z=arguments[z];if(A(Z),Z.length>0)if($===void 0)$=Z;else $+="/"+Z}if($===void 0)return".";return s($)}function q1($,z){if(A($),A(z),$===z)return"";if($=y($),z=y(z),$===z)return"";var Z=1;for(;Z<$.length;++Z)if($.charCodeAt(Z)!==47)break;var Q=$.length,J=Q-Z,X=1;for(;X<z.length;++X)if(z.charCodeAt(X)!==47)break;var Y=z.length,B=Y-X,C=J<B?J:B,V=-1,f=0;for(;f<=C;++f){if(f===C){if(B>C){if(z.charCodeAt(X+f)===47)return z.slice(X+f+1);else if(f===0)return z.slice(X+f)}else if(J>C){if($.charCodeAt(Z+f)===47)V=f;else if(f===0)V=0}break}var G=$.charCodeAt(Z+f),N=z.charCodeAt(X+f);if(G!==N)break;else if(G===47)V=f}var S="";for(f=Z+V+1;f<=Q;++f)if(f===Q||$.charCodeAt(f)===47)if(S.length===0)S+="..";else S+="/..";if(S.length>0)return S+z.slice(X+V);else{if(X+=V,z.charCodeAt(X)===47)++X;return z.slice(X)}}function S1($){return $}function A1($){if(A($),$.length===0)return".";var z=$.charCodeAt(0),Z=z===47,Q=-1,J=!0;for(var X=$.length-1;X>=1;--X)if(z=$.charCodeAt(X),z===47){if(!J){Q=X;break}}else J=!1;if(Q===-1)return Z?"/":".";if(Z&&Q===1)return"//";return $.slice(0,Q)}function w1($,z){if(z!==void 0&&typeof z!=="string")throw new TypeError('"ext" argument must be a string');A($);var Z=0,Q=-1,J=!0,X;if(z!==void 0&&z.length>0&&z.length<=$.length){if(z.length===$.length&&z===$)return"";var Y=z.length-1,B=-1;for(X=$.length-1;X>=0;--X){var C=$.charCodeAt(X);if(C===47){if(!J){Z=X+1;break}}else{if(B===-1)J=!1,B=X+1;if(Y>=0)if(C===z.charCodeAt(Y)){if(--Y===-1)Q=X}else Y=-1,Q=B}}if(Z===Q)Q=B;else if(Q===-1)Q=$.length;return $.slice(Z,Q)}else{for(X=$.length-1;X>=0;--X)if($.charCodeAt(X)===47){if(!J){Z=X+1;break}}else if(Q===-1)J=!1,Q=X+1;if(Q===-1)return"";return $.slice(Z,Q)}}function j1($){A($);var z=-1,Z=0,Q=-1,J=!0,X=0;for(var Y=$.length-1;Y>=0;--Y){var B=$.charCodeAt(Y);if(B===47){if(!J){Z=Y+1;break}continue}if(Q===-1)J=!1,Q=Y+1;if(B===46){if(z===-1)z=Y;else if(X!==1)X=1}else if(z!==-1)X=-1}if(z===-1||Q===-1||X===0||X===1&&z===Q-1&&z===Z+1)return"";return $.slice(z,Q)}function L1($){if($===null||typeof $!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof $);return D0("/",$)}function H1($){A($);var z={root:"",dir:"",base:"",ext:"",name:""};if($.length===0)return z;var Z=$.charCodeAt(0),Q=Z===47,J;if(Q)z.root="/",J=1;else J=0;var X=-1,Y=0,B=-1,C=!0,V=$.length-1,f=0;for(;V>=J;--V){if(Z=$.charCodeAt(V),Z===47){if(!C){Y=V+1;break}continue}if(B===-1)C=!1,B=V+1;if(Z===46){if(X===-1)X=V;else if(f!==1)f=1}else if(X!==-1)f=-1}if(X===-1||B===-1||f===0||f===1&&X===B-1&&X===Y+1){if(B!==-1)if(Y===0&&Q)z.base=z.name=$.slice(1,B);else z.base=z.name=$.slice(Y,B)}else{if(Y===0&&Q)z.name=$.slice(1,X),z.base=$.slice(1,B);else z.name=$.slice(Y,X),z.base=$.slice(Y,B);z.ext=$.slice(X,B)}if(Y>0)z.dir=$.slice(0,Y-1);else if(Q)z.dir="/";return z}var M1="/",O1=":",I1,O;var r=U0(()=>{I1=(($)=>($.posix=$,$))({resolve:y,normalize:s,isAbsolute:D1,join:N1,relative:q1,_makeLong:S1,dirname:A1,basename:w1,extname:j1,format:L1,parse:H1,sep:M1,delimiter:O1,win32:null,posix:null}),O=I1});var _1=p((L0)=>{var N0=/[|\\{}()[\]^$+*?.]/g,q0=Object.prototype.hasOwnProperty,t=function($,z){return q0.apply($,[z])};L0.escapeRegExpChars=function($){if(!$)return"";return String($).replace(N0,"\\$&")};var S0={"&":"&","<":"<",">":">",'"':""","'":"'"},A0=/[&<>'"]/g;function w0($){return S0[$]||$}var j0=`var _ENCODE_HTML_RULES = {
|
|
2
2
|
"&": "&"
|
|
3
3
|
, "<": "<"
|
|
4
4
|
, ">": ">"
|
|
@@ -10,59 +10,59 @@ function encode_char(c) {
|
|
|
10
10
|
return _ENCODE_HTML_RULES[c] || c;
|
|
11
11
|
};
|
|
12
12
|
`;L0.escapeXML=function($){return $==null?"":String($).replace(A0,w0)};function R1(){return Function.prototype.toString.call(this)+`;
|
|
13
|
-
`+j0}try{if(typeof Object.defineProperty==="function")Object.defineProperty(L0.escapeXML,"toString",{value:R1});else L0.escapeXML.toString=R1}catch($){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}L0.shallowCopy=function($,z){if(z=z||{},$!==null&&$!==void 0)for(var Z in z){if(!t(z,Z))continue;if(Z==="__proto__"||Z==="constructor")continue;$[Z]=z[Z]}return $};L0.shallowCopyFromList=function($,z,Z){if(Z=Z||[],z=z||{},$!==null&&$!==void 0)for(var Q=0;Q<Z.length;Q++){var
|
|
14
|
-
`),
|
|
15
|
-
`);throw $.path=
|
|
16
|
-
`+
|
|
13
|
+
`+j0}try{if(typeof Object.defineProperty==="function")Object.defineProperty(L0.escapeXML,"toString",{value:R1});else L0.escapeXML.toString=R1}catch($){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}L0.shallowCopy=function($,z){if(z=z||{},$!==null&&$!==void 0)for(var Z in z){if(!t(z,Z))continue;if(Z==="__proto__"||Z==="constructor")continue;$[Z]=z[Z]}return $};L0.shallowCopyFromList=function($,z,Z){if(Z=Z||[],z=z||{},$!==null&&$!==void 0)for(var Q=0;Q<Z.length;Q++){var J=Z[Q];if(typeof z[J]!="undefined"){if(!t(z,J))continue;if(J==="__proto__"||J==="constructor")continue;$[J]=z[J]}}return $};L0.cache={_data:{},set:function($,z){this._data[$]=z},get:function($){return this._data[$]},remove:function($){delete this._data[$]},reset:function(){this._data={}}};L0.hyphenToCamel=function($){return $.replace(/-[a-z]/g,function(z){return z[1].toUpperCase()})};L0.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();L0.hasOwnOnlyObject=function($){var z=L0.createNullProtoObjWherePossible();for(var Z in $)if(t($,Z))z[Z]=$[Z];return z}});var E1=p((H4,b0)=>{b0.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}});var o1=p((m1)=>{var Z1=(()=>({})),b=(r(),W0(T1)),K=_1(),P1=!1,_0=E1().version,E0="<",P0=">",v0="%",c1="locals",g0="ejs",k0="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",u1=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],x0=u1.concat("cache"),v1=/^\uFEFF/,e=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;m1.cache=K.cache;m1.fileLoader=Z1.readFileSync;m1.localsName=c1;m1.promiseImpl=new Function("return this;")().Promise;m1.resolveInclude=function($,z,Z){var{dirname:Q,extname:J,resolve:X}=b,Y=X(Z?z:Q(z),$),B=J($);if(!B)Y+=".ejs";return Y};function g1($,z){var Z;if(z.some(function(Q){return Z=m1.resolveInclude($,Q,!0),Z1.existsSync(Z)}))return Z}function y0($,z){var Z,Q,J=z.views,X=/^[A-Za-z]+:\\|^\//.exec($);if(X&&X.length)if($=$.replace(/^\/*/,""),Array.isArray(z.root))Z=g1($,z.root);else Z=m1.resolveInclude($,z.root||"/",!0);else{if(z.filename){if(Q=m1.resolveInclude($,z.filename),Z1.existsSync(Q))Z=Q}if(!Z&&Array.isArray(J))Z=g1($,J);if(!Z&&typeof z.includer!=="function")throw new Error('Could not find the include file "'+z.escapeFunction($)+'"')}return Z}function _($,z){var Z,Q=$.filename,J=arguments.length>1;if($.cache){if(!Q)throw new Error("cache option requires a filename");if(Z=m1.cache.get(Q),Z)return Z;if(!J)z=k1(Q).toString().replace(v1,"")}else if(!J){if(!Q)throw new Error("Internal EJS error: no file name or template provided");z=k1(Q).toString().replace(v1,"")}if(Z=m1.compile(z,$),$.cache)m1.cache.set(Q,Z);return Z}function c0($,z,Z){var Q;if(!Z)if(typeof m1.promiseImpl=="function")return new m1.promiseImpl(function(J,X){try{Q=_($)(z),J(Q)}catch(Y){X(Y)}});else throw new Error("Please provide a callback function");else{try{Q=_($)(z)}catch(J){return Z(J)}Z(null,Q)}}function k1($){return m1.fileLoader($)}function u0($,z){var Z=K.shallowCopy(K.createNullProtoObjWherePossible(),z);if(Z.filename=y0($,Z),typeof z.includer==="function"){var Q=z.includer($,Z.filename);if(Q){if(Q.filename)Z.filename=Q.filename;if(Q.template)return _(Z,Q.template)}}return _(Z)}function x1($,z,Z,Q,J){var X=z.split(`
|
|
14
|
+
`),Y=Math.max(Q-3,0),B=Math.min(X.length,Q+3),C=J(Z),V=X.slice(Y,B).map(function(f,G){var N=G+Y+1;return(N==Q?" >> ":" ")+N+"| "+f}).join(`
|
|
15
|
+
`);throw $.path=C,$.message=(C||"ejs")+":"+Q+`
|
|
16
|
+
`+V+`
|
|
17
17
|
|
|
18
|
-
`+$.message,$}function y1($){return $.replace(/;(\s*$)/,"$1")}m1.compile=function $(z,Z){var Q;if(Z&&Z.scope){if(!P1)console.warn("`scope` option is deprecated and will be removed in EJS 3"),P1=!0;if(!Z.context)Z.context=Z.scope;delete Z.scope}return Q=new F(z,Z),Q.compile()};m1.render=function($,z,Z){var Q=z||K.createNullProtoObjWherePossible(),
|
|
18
|
+
`+$.message,$}function y1($){return $.replace(/;(\s*$)/,"$1")}m1.compile=function $(z,Z){var Q;if(Z&&Z.scope){if(!P1)console.warn("`scope` option is deprecated and will be removed in EJS 3"),P1=!0;if(!Z.context)Z.context=Z.scope;delete Z.scope}return Q=new F(z,Z),Q.compile()};m1.render=function($,z,Z){var Q=z||K.createNullProtoObjWherePossible(),J=Z||K.createNullProtoObjWherePossible();if(arguments.length==2)K.shallowCopyFromList(J,Q,u1);return _(J,$)(Q)};m1.renderFile=function(){var $=Array.prototype.slice.call(arguments),z=$.shift(),Z,Q={filename:z},J,X;if(typeof arguments[arguments.length-1]=="function")Z=$.pop();if($.length){if(J=$.shift(),$.length)K.shallowCopy(Q,$.pop());else{if(J.settings){if(J.settings.views)Q.views=J.settings.views;if(J.settings["view cache"])Q.cache=!0;if(X=J.settings["view options"],X)K.shallowCopy(Q,X)}K.shallowCopyFromList(Q,J,x0)}Q.filename=z}else J=K.createNullProtoObjWherePossible();return c0(Q,J,Z)};m1.Template=F;m1.clearCache=function(){m1.cache.reset()};function F($,z){var Z=K.hasOwnOnlyObject(z),Q=K.createNullProtoObjWherePossible();if(this.templateText=$,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",Q.client=Z.client||!1,Q.escapeFunction=Z.escape||Z.escapeFunction||K.escapeXML,Q.compileDebug=Z.compileDebug!==!1,Q.debug=!!Z.debug,Q.filename=Z.filename,Q.openDelimiter=Z.openDelimiter||m1.openDelimiter||E0,Q.closeDelimiter=Z.closeDelimiter||m1.closeDelimiter||P0,Q.delimiter=Z.delimiter||m1.delimiter||v0,Q.strict=Z.strict||!1,Q.context=Z.context,Q.cache=Z.cache||!1,Q.rmWhitespace=Z.rmWhitespace,Q.root=Z.root,Q.includer=Z.includer,Q.outputFunctionName=Z.outputFunctionName,Q.localsName=Z.localsName||m1.localsName||c1,Q.views=Z.views,Q.async=Z.async,Q.destructuredLocals=Z.destructuredLocals,Q.legacyInclude=typeof Z.legacyInclude!="undefined"?!!Z.legacyInclude:!0,Q.strict)Q._with=!1;else Q._with=typeof Z._with!="undefined"?Z._with:!0;this.opts=Q,this.regex=this.createRegex()}F.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};F.prototype={createRegex:function(){var $=k0,z=K.escapeRegExpChars(this.opts.delimiter),Z=K.escapeRegExpChars(this.opts.openDelimiter),Q=K.escapeRegExpChars(this.opts.closeDelimiter);return $=$.replace(/%/g,z).replace(/</g,Z).replace(/>/g,Q),new RegExp($)},compile:function(){var $,z,Z=this.opts,Q="",J="",X=Z.escapeFunction,Y,B=Z.filename?JSON.stringify(Z.filename):"undefined";if(!this.source){if(this.generateSource(),Q+=` var __output = "";
|
|
19
19
|
function __append(s) { if (s !== undefined && s !== null) __output += s }
|
|
20
20
|
`,Z.outputFunctionName){if(!e.test(Z.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");Q+=" var "+Z.outputFunctionName+` = __append;
|
|
21
|
-
`}if(Z.localsName&&!e.test(Z.localsName))throw new Error("localsName is not a valid JS identifier.");if(Z.destructuredLocals&&Z.destructuredLocals.length){var
|
|
22
|
-
`;for(var
|
|
23
|
-
`;
|
|
21
|
+
`}if(Z.localsName&&!e.test(Z.localsName))throw new Error("localsName is not a valid JS identifier.");if(Z.destructuredLocals&&Z.destructuredLocals.length){var C=" var __locals = ("+Z.localsName+` || {}),
|
|
22
|
+
`;for(var V=0;V<Z.destructuredLocals.length;V++){var f=Z.destructuredLocals[V];if(!e.test(f))throw new Error("destructuredLocals["+V+"] is not a valid JS identifier.");if(V>0)C+=`,
|
|
23
|
+
`;C+=f+" = __locals."+f}Q+=C+`;
|
|
24
24
|
`}if(Z._with!==!1)Q+=" with ("+Z.localsName+` || {}) {
|
|
25
|
-
`,
|
|
26
|
-
`;
|
|
27
|
-
`,this.source=Q+this.source+
|
|
25
|
+
`,J+=` }
|
|
26
|
+
`;J+=` return __output;
|
|
27
|
+
`,this.source=Q+this.source+J}if(Z.compileDebug)$=`var __line = 1
|
|
28
28
|
, __lines = `+JSON.stringify(this.templateText)+`
|
|
29
|
-
, __filename = `+
|
|
29
|
+
, __filename = `+B+`;
|
|
30
30
|
try {
|
|
31
31
|
`+this.source+`} catch (e) {
|
|
32
32
|
rethrow(e, __lines, __filename, __line, escapeFn);
|
|
33
33
|
}
|
|
34
|
-
`;else $=this.source;if(Z.client){if($="escapeFn = escapeFn || "+
|
|
34
|
+
`;else $=this.source;if(Z.client){if($="escapeFn = escapeFn || "+X.toString()+`;
|
|
35
35
|
`+$,Z.compileDebug)$="rethrow = rethrow || "+x1.toString()+`;
|
|
36
36
|
`+$}if(Z.strict)$=`"use strict";
|
|
37
37
|
`+$;if(Z.debug)console.log($);if(Z.compileDebug&&Z.filename)$=$+`
|
|
38
|
-
//# sourceURL=`+
|
|
39
|
-
`;try{if(Z.async)try{
|
|
38
|
+
//# sourceURL=`+B+`
|
|
39
|
+
`;try{if(Z.async)try{Y=new Function("return (async function(){}).constructor;")()}catch(D){if(D instanceof SyntaxError)throw new Error("This environment does not support async/await");else throw D}else Y=Function;z=new Y(Z.localsName+", escapeFn, include, rethrow",$)}catch(D){if(D instanceof SyntaxError){if(Z.filename)D.message+=" in "+Z.filename;if(D.message+=` while compiling ejs
|
|
40
40
|
|
|
41
41
|
`,D.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
42
|
`,D.message+="https://github.com/RyanZim/EJS-Lint",!Z.async)D.message+=`
|
|
43
|
-
`,D.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw D}var
|
|
44
|
-
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var z=this,Z=this.parseTemplateText(),Q=this.opts.delimiter,
|
|
45
|
-
`},scanLine:function($){var z=this,Z=this.opts.delimiter,Q=this.opts.openDelimiter,
|
|
43
|
+
`,D.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw D}var G=Z.client?z:function D(o){var L=function(q,l){var n=K.shallowCopy(K.createNullProtoObjWherePossible(),o);if(l)n=K.shallowCopy(n,l);return u0(q,Z)(n)};return z.apply(Z.context,[o||K.createNullProtoObjWherePossible(),X,L,x1])};if(Z.filename&&typeof Object.defineProperty==="function"){var N=Z.filename,S=b.basename(N,b.extname(N));try{Object.defineProperty(G,"name",{value:S,writable:!1,enumerable:!1,configurable:!0})}catch(D){}}return G},generateSource:function(){var $=this.opts;if($.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
|
+
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var z=this,Z=this.parseTemplateText(),Q=this.opts.delimiter,J=this.opts.openDelimiter,X=this.opts.closeDelimiter;if(Z&&Z.length)Z.forEach(function(Y,B){var C;if(Y.indexOf(J+Q)===0&&Y.indexOf(J+Q+Q)!==0){if(C=Z[B+2],!(C==Q+X||C=="-"+Q+X||C=="_"+Q+X))throw new Error('Could not find matching close tag for "'+Y+'".')}z.scanLine(Y)})},parseTemplateText:function(){var $=this.templateText,z=this.regex,Z=z.exec($),Q=[],J;while(Z){if(J=Z.index,J!==0)Q.push($.substring(0,J)),$=$.slice(J);Q.push(Z[0]),$=$.slice(Z[0].length),Z=z.exec($)}if($)Q.push($);return Q},_addOutput:function($){if(this.truncate)$=$.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!$)return $;$=$.replace(/\\/g,"\\\\"),$=$.replace(/\n/g,"\\n"),$=$.replace(/\r/g,"\\r"),$=$.replace(/"/g,"\\\""),this.source+=' ; __append("'+$+`")
|
|
45
|
+
`},scanLine:function($){var z=this,Z=this.opts.delimiter,Q=this.opts.openDelimiter,J=this.opts.closeDelimiter,X=0;switch(X=$.split(`
|
|
46
46
|
`).length-1,$){case Q+Z:case Q+Z+"_":this.mode=F.modes.EVAL;break;case Q+Z+"=":this.mode=F.modes.ESCAPED;break;case Q+Z+"-":this.mode=F.modes.RAW;break;case Q+Z+"#":this.mode=F.modes.COMMENT;break;case Q+Z+Z:this.mode=F.modes.LITERAL,this.source+=' ; __append("'+$.replace(Q+Z+Z,Q+Z)+`")
|
|
47
|
-
`;break;case Z+Z+
|
|
48
|
-
`;break;case Z+
|
|
47
|
+
`;break;case Z+Z+J:this.mode=F.modes.LITERAL,this.source+=' ; __append("'+$.replace(Z+Z+J,Z+J)+`")
|
|
48
|
+
`;break;case Z+J:case"-"+Z+J:case"_"+Z+J:if(this.mode==F.modes.LITERAL)this._addOutput($);this.mode=null,this.truncate=$.indexOf("-")===0||$.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case F.modes.EVAL:case F.modes.ESCAPED:case F.modes.RAW:if($.lastIndexOf("//")>$.lastIndexOf(`
|
|
49
49
|
`))$+=`
|
|
50
50
|
`}switch(this.mode){case F.modes.EVAL:this.source+=" ; "+$+`
|
|
51
51
|
`;break;case F.modes.ESCAPED:this.source+=" ; __append(escapeFn("+y1($)+`))
|
|
52
52
|
`;break;case F.modes.RAW:this.source+=" ; __append("+y1($)+`)
|
|
53
|
-
`;break;case F.modes.COMMENT:break;case F.modes.LITERAL:this._addOutput($);break}}else this._addOutput($)}if(z.opts.compileDebug&&
|
|
54
|
-
`}};m1.escapeXML=K.escapeXML;m1.__express=m1.renderFile;m1.VERSION=_0;m1.name=g0;if(typeof window!="undefined")window.ejs=m1});class g{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class k{root;constructor(){this.root=new g}pushMidl($,...z){let Z=this.root,Q=$.split("/").filter(Boolean);if($==="/"){Z.handler.push(...z);return}for(let
|
|
53
|
+
`;break;case F.modes.COMMENT:break;case F.modes.LITERAL:this._addOutput($);break}}else this._addOutput($)}if(z.opts.compileDebug&&X)this.currentLine+=X,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
+
`}};m1.escapeXML=K.escapeXML;m1.__express=m1.renderFile;m1.VERSION=_0;m1.name=g0;if(typeof window!="undefined")window.ejs=m1});class g{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class k{root;constructor(){this.root=new g}pushMidl($,...z){let Z=this.root,Q=$.split("/").filter(Boolean);if($==="/"){Z.handler.push(...z);return}for(let J of Q){let X=J;if(J.startsWith(":"))X=":";if(!Z.children[X])Z.children[X]=new g;Z=Z.children[X]}Z.handler.push(...z)}insert($,z){let Z=this.root,Q=$.split("/").filter(Boolean);if($==="/"){Z.isEndOfWord=!0,Z.handler.push(z.handler),Z.path=$,Z.method.push(z.method);return}for(let J of Q){let X=!1,Y=J;if(J.startsWith(":"))X=!0,Y=":";if(!Z.children[Y])Z.children[Y]=new g;Z=Z.children[Y],Z.isDynamic=X,Z.pattern=J}Z.isEndOfWord=!0,Z.path=$,Z.method.push(z.method),Z.handler.push(z.handler)}search($,z){let Z=this.root,Q=$.split("/").filter(Boolean),J=Q.length;for(let B of Q){let C=B;if(!Z.children[C])if(Z.children[":"])Z=Z.children[":"];else return null;else Z=Z.children[C]}let X=Z.path.split("/").filter(Boolean);if(J!==X.length)return null;if(Z.method.indexOf(z)!==-1)return{path:Z.path,handler:Z.handler[0],pattern:Z.pattern};return null}}function x($){switch($.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var z1=null;async function s0(){if(!z1){let $=await Promise.resolve().then(() => G0(o1(),1));z1=$.default||$}return z1}class E{req;server;path;routePattern;env;executionContext;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor($,z,Z,Q,J,X){this.req=$,this.server=z,this.path=Z,this.routePattern=Q,this.executionContext=X,this.env=J}setHeader($,z){return this.headers.set($,z),this}removeHeader($){return this.headers.delete($),this}set($,z){return this.contextData[$]=z,this}get($){return this.contextData[$]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!this.parsedParams&&this.routePattern)try{this.parsedParams=a0(this.routePattern,this.path)}catch($){let z=$ instanceof Error?$.message:String($);throw new Error(`Failed to extract route parameters: ${z}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let $=await t0(this.req);if($.error)throw new Error($.error);return Object.keys($).length===0?null:$}catch($){throw new Error("Invalid request body format")}})();return this.parsedBody}text($,z=200){return new Response($,{status:z,headers:this.headers})}send($,z=200){let Z;if($ instanceof Uint8Array)Z="Uint8Array";else if($ instanceof ArrayBuffer)Z="ArrayBuffer";else Z=typeof $;let Q=Z==="object"&&$!==null?JSON.stringify($):$;return new Response(Q,{status:z,headers:this.headers})}json($,z=200){return Response.json($,{status:z,headers:this.headers})}file($,z,Z=200){let Q=Bun.file($);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",z??x($));return new Response(Q,{status:Z,headers:this.headers})}async ejs($,z={},Z=200){let Q=await s0();try{let J=await Bun.file($).text(),X=Q.render(J,z),Y=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(X,{status:Z,headers:Y})}catch(J){return console.error("EJS Rendering Error:",J),new Response("Error rendering template",{status:500})}}redirect($,z=302){return this.headers.set("Location",$),new Response(null,{status:z,headers:this.headers})}setCookie($,z,Z={}){let Q=`${encodeURIComponent($)}=${encodeURIComponent(z)}`;if(Z.maxAge)Q+=`; Max-Age=${Z.maxAge}`;if(Z.expires)Q+=`; Expires=${Z.expires.toUTCString()}`;if(Z.path)Q+=`; Path=${Z.path}`;if(Z.domain)Q+=`; Domain=${Z.domain}`;if(Z.secure)Q+="; Secure";if(Z.httpOnly)Q+="; HttpOnly";if(Z.sameSite)Q+=`; SameSite=${Z.sameSite}`;return this.headers.append("Set-Cookie",Q),this}get cookies(){if(!this.parsedCookies){let $=this.req.headers.get("cookie");this.parsedCookies=$?r0($):{}}return this.parsedCookies}stream($){let z=new Headers(this.headers),Z=new ReadableStream({async start(Q){await $(Q),Q.close()}});return new Response(Z,{headers:z})}yieldStream($){return new Response}}function r0($){return Object.fromEntries($.split(";").map((z)=>{let[Z,...Q]=z.trim().split("=");return[Z,decodeURIComponent(Q.join("="))]}))}function a0($,z){let Z={},Q=$.split("/"),[J]=z.split("?"),X=J.split("/");if(Q.length!==X.length)return null;for(let Y=0;Y<Q.length;Y++){let B=Q[Y];if(B.charCodeAt(0)===58)Z[B.slice(1)]=X[Y]}return Z}async function t0($){let z=$.headers.get("Content-Type")||"";if(!z)return{};if($.headers.get("Content-Length")==="0"||!$.body)return{};if(z.startsWith("application/json"))return await $.json();if(z.startsWith("application/x-www-form-urlencoded")){let Q=await $.text();return Object.fromEntries(new URLSearchParams(Q))}if(z.startsWith("multipart/form-data")){let Q=await $.formData(),J={};for(let[X,Y]of Q.entries())J[X]=Y;return J}return{error:"Unknown request body type"}}async function w($,z,Z){if(!z?.length)return;for(let Q=0;Q<z.length;Q++){let J=z[Q](...Z),X=J instanceof Promise?await J:J;if(X&&$!=="onRequest")return X}}async function l1($,z,Z){let Q=$.globalMiddlewares;if(Q.length)for(let X of Q){let Y=await X(Z);if(Y)return Y}let J=$.middlewares.get(z);if(J&&J.length)for(let X of J){let Y=await X(Z);if(Y)return Y}return null}async function n1($,z,Z){for(let Q of $){let J=await Q(z,Z);if(J)return J}}async function m($,z,Z){let Q=await e0($,z,Z),J=Q instanceof Promise?await Q:Q;if(J)return J}async function e0($,z,Z){if(z.endsWith("/"))z=z.slice(0,-1);if(!$.filters.has(z))if($.filterFunction.length)for(let Q of $.filterFunction){let J=await Q(Z);if(J)return J}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function d($,z,Z){if($.staticPath){let J=!0;if($.staticRequestPath)J=Z.startsWith($.staticRequestPath);if(J){let X=await $4($,Z,z);if(X)return X;let Y=$.trie.search("*",z.req.method);if(Y?.handler)return await Y.handler(z)}}let Q=$.routeNotFoundFunc(z);return Q instanceof Promise?await Q:Q||I(404,`404 Route not found for ${Z}`)}function I($,z){return new Response(JSON.stringify({error:z}),{status:$,headers:{"Content-Type":"application/json"}})}async function $4($,z,Z){if(!$.staticPath)return null;let Q=`${$.staticPath}${z}`;if(await Bun.file(Q).exists()){let X=x(Q);return Z.file(Q,X,200)}return null}var h=($)=>$.constructor.name==="AsyncFunction",Q1=($,z,Z,...Q)=>{if(z.length>5)$.push(`
|
|
55
55
|
for (let i = 0; i < diesel.hooks.${Z}.length; i++) {
|
|
56
56
|
const result = diesel.hooks.${Z}[i](${Q});
|
|
57
57
|
const finalResult = result instanceof Promise ? await result : result;
|
|
58
58
|
if (finalResult && '${Z}' !== 'onRequest') return finalResult
|
|
59
59
|
}
|
|
60
|
-
`);else z?.forEach((
|
|
61
|
-
const ${Z}${
|
|
62
|
-
if (${Z}${
|
|
60
|
+
`);else z?.forEach((J,X)=>{if(h(J))$.push(`
|
|
61
|
+
const ${Z}${X}Result = await diesel.hooks.${Z}[${X}](${Q})
|
|
62
|
+
if (${Z}${X}Result && '${Z}' !== 'onRequest') return ${Z}${X}Result
|
|
63
63
|
`);else $.push(`
|
|
64
|
-
const ${Z}${
|
|
65
|
-
if (${Z}${
|
|
64
|
+
const ${Z}${X}Result = diesel.hooks.${Z}[${X}](${Q})
|
|
65
|
+
if (${Z}${X}Result && '${Z}' !== 'onRequest') return ${Z}${X}Result
|
|
66
66
|
`)})},Z4=($)=>{$.push(`
|
|
67
67
|
let pathname;
|
|
68
68
|
const start = req.url.indexOf('/', req.url.indexOf(':') + 4);
|
|
@@ -92,9 +92,9 @@ try {
|
|
|
92
92
|
const result = await globalMiddlewares[i](ctx);
|
|
93
93
|
if (result) return result;
|
|
94
94
|
}
|
|
95
|
-
`)},p1=($,z)=>{let Z=[],Q=z.globalMiddlewares||[],
|
|
95
|
+
`)},p1=($,z)=>{let Z=[],Q=z.globalMiddlewares||[],J=$?.hasOnReqHook?z.hooks.onRequest:[],X=$?.hasPreHandlerHook?z.hooks.preHandler:[],Y=$?.hasOnSendHook?z.hooks.onSend:[];if(Z4(Z),Z.push(`
|
|
96
96
|
const routeHandler = diesel.trie.search(pathname, req.method);
|
|
97
|
-
`),
|
|
97
|
+
`),J&&J.length>0)Q1(Z,J,"onRequest","req","pathname","server");if(Z.push(`
|
|
98
98
|
const ctx = new Context(req, server, pathname, routeHandler?.path)
|
|
99
99
|
`),$?.hasMiddleware){if(Q.length>0)z4(Z,Q);if(z.middlewares.size>0)Z.push(`
|
|
100
100
|
const local = diesel.middlewares.get(pathname)
|
|
@@ -109,64 +109,64 @@ try {
|
|
|
109
109
|
if (filterResponse) return filterResponse;
|
|
110
110
|
`);if(Z.push(`
|
|
111
111
|
if (!routeHandler) return await handleRouteNotFound(diesel, ctx, pathname);
|
|
112
|
-
`),$.hasPreHandlerHook)Q1(Z,
|
|
112
|
+
`),$.hasPreHandlerHook)Q1(Z,X,"preHandler","ctx");if(Z.push(`
|
|
113
113
|
const result = routeHandler.handler(ctx);
|
|
114
114
|
const finalResult = result instanceof Promise ? await result : result;
|
|
115
|
-
`),$.hasOnSendHook)Q1(Z,
|
|
115
|
+
`),$.hasOnSendHook)Q1(Z,Y,"onSend","ctx","finalResult");Z.push(`
|
|
116
116
|
if (finalResult instanceof Response) return finalResult;
|
|
117
117
|
return generateErrorResponse(500, "No response returned from handler.");
|
|
118
|
-
`);let
|
|
118
|
+
`);let B=`
|
|
119
119
|
return async function pipeline(req, server, diesel) {
|
|
120
120
|
${Z.join(`
|
|
121
121
|
`)}
|
|
122
122
|
}
|
|
123
|
-
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",
|
|
123
|
+
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",B)(m,d,I,Q,E)},s1=($,z,Z,Q,...J)=>{let X=[],Y;if(typeof J[0]==="string"||typeof J[0]==="object")Y=J[0];let B=J,C=$?.hasMiddleware?z.globalMiddlewares:[],V=$?.hasMiddleware?z.middlewares.get(Q)||[]:[],f=[...C,...V],G=$?.hasOnReqHook?z.hooks.onRequest:[],N=z.filters.has(Q),S=z.filterFunction;if(G&&G?.length>0)X.push(`
|
|
124
124
|
const onRequestResult = await runHooks(
|
|
125
125
|
"onRequest",
|
|
126
126
|
onRequestHooks,
|
|
127
127
|
[req, "${Q}", server]
|
|
128
128
|
);
|
|
129
129
|
if (onRequestResult) return onRequestResult;
|
|
130
|
-
`);if(
|
|
130
|
+
`);if(f.length)X.push(`
|
|
131
131
|
const globalMiddlewareResponse = await executeBunMiddlewares(
|
|
132
132
|
allMiddlewares,
|
|
133
133
|
req,
|
|
134
134
|
server
|
|
135
135
|
);
|
|
136
136
|
if (globalMiddlewareResponse) return globalMiddlewareResponse;
|
|
137
|
-
`);if($.hasFilterEnabled){if(!N)
|
|
137
|
+
`);if($.hasFilterEnabled){if(!N)X.push(`if (${S.length}) {
|
|
138
138
|
for (const filterFunction of filterFunctions) {
|
|
139
139
|
const filterResult = await filterFunction(req, server);
|
|
140
140
|
if (filterResult) return filterResult;
|
|
141
141
|
}
|
|
142
142
|
} else {
|
|
143
143
|
return Response.json({ error: "Protected route, authentication required" }, { status: 401 });
|
|
144
|
-
}`)}if(
|
|
144
|
+
}`)}if(X.push(`
|
|
145
145
|
if ("${Z}" !== req.method)
|
|
146
146
|
return new Response("Method Not Allowed", { status: 405 });
|
|
147
|
-
`),typeof
|
|
148
|
-
return new Response(${JSON.stringify(
|
|
149
|
-
`);else{let L=JSON.stringify(
|
|
147
|
+
`),typeof Y!=="undefined")if(typeof Y==="string")X.push(`
|
|
148
|
+
return new Response(${JSON.stringify(Y)});
|
|
149
|
+
`);else{let L=JSON.stringify(Y);X.push(`
|
|
150
150
|
return new Response(${JSON.stringify(L)}, {
|
|
151
151
|
headers: { "content-type": "application/json; charset=utf-8" }
|
|
152
152
|
});
|
|
153
|
-
`)}else if(
|
|
153
|
+
`)}else if(B.length===1){let L=B[0];if(h(L))X.push(`
|
|
154
154
|
const response = await handlers[0](req, server);
|
|
155
155
|
if (response instanceof Response) return response;
|
|
156
|
-
`);else
|
|
156
|
+
`);else X.push(`
|
|
157
157
|
const response = handlers[0](req, server);
|
|
158
158
|
if (response instanceof Response) return response;
|
|
159
|
-
`)}else
|
|
159
|
+
`)}else B.forEach((L,q)=>{if(h(L))X.push(`
|
|
160
160
|
const response${q} = await handlers[${q}](req, server);
|
|
161
161
|
if (response${q} instanceof Response) return response${q};
|
|
162
|
-
`);else
|
|
162
|
+
`);else X.push(`
|
|
163
163
|
const response${q} = handlers[${q}](req, server);
|
|
164
164
|
if (response${q} instanceof Response) return response${q};
|
|
165
165
|
`)});let D=`
|
|
166
166
|
return async function(req, server) {
|
|
167
|
-
${
|
|
167
|
+
${X.join(`
|
|
168
168
|
`)}
|
|
169
169
|
}
|
|
170
|
-
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",D)(n1,
|
|
171
|
-
${Q}[${$.toUpperCase()}]${U.reset} ${z} - ${
|
|
172
|
-
`)},r1=($)=>{let{app:z,logger:Z,logLevel:Q="info",onRequest:C,onSend:J,onError:X}=$||{};z?.addHooks("onRequest",(Y)=>{Y.req.startTime=Date.now(),Z?.()??C1(Q,"Incoming Request",{method:Y.req.method,url:Y.path,headers:{"user-agent":Y.req.headers.get("user-agent"),"content-type":Y.req.headers.get("content-type")}}),C?.(Y)}),z?.addHooks("onSend",async(Y,V)=>{let B=`${Date.now()-Y.req.startTime}ms`;Z?.()??C1(Q,"Response Sent",{method:Y.req.method,url:Y.url.toString(),status:V.status,duration:B,reqId:Y.get?.("requestId"),headers:{"content-type":V.headers.get("content-type")}});let G=await J?.(Y);if(G instanceof Response)return G}),z?.addHooks("onError",async(Y,V)=>{Z?.()??C1("error","Unhandled Error",{method:V.req.method,url:V.path,status:500,error:Y.message});let B=await X?.(Y,V);if(B instanceof Response)return B})},J1=($,z,Z,Q=0,C,J)=>{let X=U.method[z]||U.reset,Y=Q>=500?U.error:Q>=400?U.warn:U.info,V=J?`[${J}] `:"",B=$==="<--"?`${$} ${X}${z}${U.reset} ${Z} ${V}`:`${$} ${X}${z}${U.reset} ${Z} ${Y}${Q}${U.reset} ${C??""} ${V}`;console.log(B)},Q4=($)=>{let z=Date.now()-$;return z<1000?`${z}ms`:`${Math.round(z/1000)}s`},a1=($)=>{let{app:z,log:Z,onRequest:Q,onSend:C,onError:J}=$;z.addHooks("onRequest",(X)=>{let{req:Y,path:V}=X;Y.startTime=Date.now(),Z?.()??J1("<--",Y.method,V),Q?.(Y,V)}),z.addHooks("onSend",async(X,Y)=>{let{method:V,url:B}=X.req,G=new URL(B).pathname,f=X.get?.("requestId");Z?.()??J1("-->",V,G,Y.status,Q4(X.req.startTime),f);let N=await C?.(X);if(N instanceof Response)return N}),z.addHooks("onError",async(X,Y)=>{let{req:V,path:B}=Y;Z?.()??J1(X.message,V.method,B,500);let G=await J?.(X,V,B);if(G instanceof Response)return G})};function t1($,z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(Z)=>{try{let Q=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!Q)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(Q.startsWith("Bearer "))Q=Q.slice(7);let C=$?.verify(Q,z);if(!C)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);Z.set("user",C)}catch(Q){let C="Invalid token";if(Q.name==="TokenExpiredError")C="Token expired";else if(Q.name==="JsonWebTokenError")C="Malformed or tampered token";return Z.json({message:"Unauthorized",error:C},401)}}}function e1($,z,Z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!z)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(Q)=>{try{let C=Q.cookies?.accessToken??Q.req?.headers?.get("Authorization");if(!C)return Q.json({message:"Unauthorized",error:"No token provided"},401);if(C.startsWith("Bearer "))C=C.slice(7);let J=$?.verify(C,Z);if(!J)return Q.json({message:"Unauthorized",error:"Token could not be decoded"},401);let X=await z.findById(J._id).select("-password -refreshToken");if(!X)return Q.json({message:"Unauthorized: User not found"},404);Q.set("user",X);return}catch(C){let J="Invalid token";if(C.name==="TokenExpiredError")J="Token expired";else if(C.name==="JsonWebTokenError")J="Malformed or tampered token";return Q.json({message:"Unauthorized",error:J},401)}}}var C4=($,z)=>{try{return z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Z)=>{try{return z(Z)}catch{return Z}})}},X1=($)=>C4($,decodeURI),Y1=($)=>{let z=$.indexOf("/",$.indexOf(":")+4),Z=z;for(;Z<$.length;Z++){let Q=$.charCodeAt(Z);if(Q===37){let C=$.indexOf("?",Z),J=$.slice(z,C===-1?void 0:C);return X1(J.includes("%25")?J.replace(/%25/g,"%2525"):J)}else if(Q===63)break}return $.slice(z,Z)};var B1=Symbol.for,H=Symbol("kCapture"),Q0=B1("events.errorMonitor"),J4=Symbol("events.maxEventTargetListeners"),X4=Symbol("events.maxEventTargetListenersWarned"),$0=B1("nodejs.rejection"),Y4=B1("nodejs.rejection"),Z0=Array.prototype.slice,M=10,j=function $(z){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[H]=z?.captureRejections?Boolean(z?.captureRejections):W[H])this.emit=f4},W=j.prototype={};W._events=void 0;W._eventsCount=0;W._maxListeners=void 0;W.setMaxListeners=function $(z){return G1(z,"setMaxListeners",0),this._maxListeners=z,this};W.constructor=j;W.getMaxListeners=function $(){return this?._maxListeners??M};function C0($,z){var{_events:Z}=$;if(z[0]??=new Error("Unhandled error."),!Z)throw z[0];var Q=Z[Q0];if(Q)for(var C of Z0.call(Q))C.apply($,z);var J=Z.error;if(!J)throw z[0];for(var C of Z0.call(J))C.apply($,z);return!0}function V4($,z,Z,Q){z.then(void 0,function(C){queueMicrotask(()=>B4($,C,Z,Q))})}function B4($,z,Z,Q){if(typeof $[$0]==="function")$[$0](z,Z,...Q);else try{$[H]=!1,$.emit("error",z)}finally{$[H]=!0}}var G4=function $(z,...Z){if(z==="error")return C0(this,Z);var{_events:Q}=this;if(Q===void 0)return!1;var C=Q[z];if(C===void 0)return!1;let J=C.length>1?C.slice():C;for(let X=0,{length:Y}=J;X<Y;X++){let V=J[X];switch(Z.length){case 0:V.call(this);break;case 1:V.call(this,Z[0]);break;case 2:V.call(this,Z[0],Z[1]);break;case 3:V.call(this,Z[0],Z[1],Z[2]);break;default:V.apply(this,Z);break}}return!0},f4=function $(z,...Z){if(z==="error")return C0(this,Z);var{_events:Q}=this;if(Q===void 0)return!1;var C=Q[z];if(C===void 0)return!1;let J=C.length>1?C.slice():C;for(let X=0,{length:Y}=J;X<Y;X++){let V=J[X],B;switch(Z.length){case 0:B=V.call(this);break;case 1:B=V.call(this,Z[0]);break;case 2:B=V.call(this,Z[0],Z[1]);break;case 3:B=V.call(this,Z[0],Z[1],Z[2]);break;default:B=V.apply(this,Z);break}if(B!==void 0&&typeof B?.then==="function"&&B.then===Promise.prototype.then)V4(this,B,z,Z)}return!0};W.emit=G4;W.addListener=function $(z,Z){P(Z);var Q=this._events;if(!Q)Q=this._events={__proto__:null},this._eventsCount=0;else if(Q.newListener)this.emit("newListener",z,Z.listener??Z);var C=Q[z];if(!C)Q[z]=[Z],this._eventsCount++;else{C.push(Z);var J=this._maxListeners??M;if(J>0&&C.length>J&&!C.warned)J0(this,z,C)}return this};W.on=W.addListener;W.prependListener=function $(z,Z){P(Z);var Q=this._events;if(!Q)Q=this._events={__proto__:null},this._eventsCount=0;else if(Q.newListener)this.emit("newListener",z,Z.listener??Z);var C=Q[z];if(!C)Q[z]=[Z],this._eventsCount++;else{C.unshift(Z);var J=this._maxListeners??M;if(J>0&&C.length>J&&!C.warned)J0(this,z,C)}return this};function J0($,z,Z){Z.warned=!0;let Q=new Error(`Possible EventEmitter memory leak detected. ${Z.length} ${String(z)} listeners added to [${$.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);Q.name="MaxListenersExceededWarning",Q.emitter=$,Q.type=z,Q.count=Z.length,console.warn(Q)}function X0($,z,...Z){this.removeListener($,z),z.apply(this,Z)}W.once=function $(z,Z){P(Z);let Q=X0.bind(this,z,Z);return Q.listener=Z,this.addListener(z,Q),this};W.prependOnceListener=function $(z,Z){P(Z);let Q=X0.bind(this,z,Z);return Q.listener=Z,this.prependListener(z,Q),this};W.removeListener=function $(z,Z){P(Z);var{_events:Q}=this;if(!Q)return this;var C=Q[z];if(!C)return this;var J=C.length;let X=-1;for(let Y=J-1;Y>=0;Y--)if(C[Y]===Z||C[Y].listener===Z){X=Y;break}if(X<0)return this;if(X===0)C.shift();else C.splice(X,1);if(C.length===0)delete Q[z],this._eventsCount--;return this};W.off=W.removeListener;W.removeAllListeners=function $(z){var{_events:Z}=this;if(z&&Z){if(Z[z])delete Z[z],this._eventsCount--}else this._events={__proto__:null};return this};W.listeners=function $(z){var{_events:Z}=this;if(!Z)return[];var Q=Z[z];if(!Q)return[];return Q.map((C)=>C.listener??C)};W.rawListeners=function $(z){var{_events:Z}=this;if(!Z)return[];var Q=Z[z];if(!Q)return[];return Q.slice()};W.listenerCount=function $(z){var{_events:Z}=this;if(!Z)return 0;return Z[z]?.length??0};W.eventNames=function $(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};W[H]=!1;function W4($,z,Z){var Q=Z?.signal;if(Y0(Q,"options.signal"),Q?.aborted)throw new V1(void 0,{cause:Q?.reason});let{resolve:C,reject:J,promise:X}=$newPromiseCapability(Promise),Y=(G)=>{if($.removeListener(z,V),Q!=null)i(Q,"abort",B);J(G)},V=(...G)=>{if(typeof $.removeListener==="function")$.removeListener("error",Y);if(Q!=null)i(Q,"abort",B);C(G)};if(z0($,z,V,{once:!0}),z!=="error"&&typeof $.once==="function")$.once("error",Y);function B(){i($,z,V),i($,"error",Y),J(new V1(void 0,{cause:Q?.reason}))}if(Q!=null)z0(Q,"abort",B,{once:!0});return X}function K4($,z){return $.listeners(z)}function U4($,...z){G1($,"setMaxListeners",0);var Z;if(z&&(Z=z.length))for(let Q=0;Q<Z;Q++)z[Q].setMaxListeners($);else M=$}function F4($,z){return $.listenerCount(z)}function i($,z,Z,Q){if(typeof $.removeListener==="function")$.removeListener(z,Z);else $.removeEventListener(z,Z,Q)}function z0($,z,Z,Q){if(typeof $.on==="function")if(Q.once)$.once(z,Z);else $.on(z,Z);else $.addEventListener(z,Z,Q)}class V1 extends Error{constructor($="The operation was aborted",z=void 0){if(z!==void 0&&typeof z!=="object")throw T("options","Object",z);super($,z);this.code="ABORT_ERR",this.name="AbortError"}}function T($,z,Z){let Q=new TypeError(`The "${$}" argument must be of type ${z}. Received ${Z}`);return Q.code="ERR_INVALID_ARG_TYPE",Q}function D4($,z,Z){let Q=new RangeError(`The "${$}" argument is out of range. It must be ${z}. Received ${Z}`);return Q.code="ERR_OUT_OF_RANGE",Q}function Y0($,z){if($!==void 0&&($===null||typeof $!=="object"||!("aborted"in $)))throw T(z,"AbortSignal",$)}function G1($,z,Z,Q){if(typeof $!=="number")throw T(z,"number",$);if(Z!=null&&$<Z||Q!=null&&$>Q||(Z!=null||Q!=null)&&Number.isNaN($))throw D4(z,`${Z!=null?`>= ${Z}`:""}${Z!=null&&Q!=null?" && ":""}${Q!=null?`<= ${Q}`:""}`,$)}function P($){if(typeof $!=="function")throw new TypeError("The listener must be a function")}function N4($,z){if(typeof $!=="boolean")throw T(z,"boolean",$)}function q4($){return $?._maxListeners??M}function S4($,z){if($===void 0)throw T("signal","AbortSignal",$);if(Y0($,"signal"),typeof z!=="function")throw T("listener","function",z);let Z;if($.aborted)queueMicrotask(()=>z());else $.addEventListener("abort",z,{__proto__:null,once:!0}),Z=()=>{$.removeEventListener("abort",z)};return{__proto__:null,[Symbol.dispose](){Z?.()}}}Object.defineProperties(j,{captureRejections:{get(){return W[H]},set($){N4($,"EventEmitter.captureRejections"),W[H]=$},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return M},set:($)=>{G1($,"defaultMaxListeners",0),M=$}},kMaxEventTargetListeners:{value:J4,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:X4,enumerable:!1,configurable:!1,writable:!1}});Object.assign(j,{once:W4,getEventListeners:K4,getMaxListeners:q4,setMaxListeners:U4,EventEmitter:j,usingDomains:!1,captureRejectionSymbol:Y4,errorMonitor:Q0,addAbortListener:S4,init:j,listenerCount:F4});class v{static instance;fecth;routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#Z=!1;emitter;errorFormat;platform="bun";staticPath;staticRequestPath=void 0;constructor({jwtSecret:$,baseApiUrl:z,enableFileRouting:Z,idleTimeOut:Q,prefixApiUrl:C,onError:J,logger:X,pipelineArchitecture:Y,errorFormat:V="json",platform:B="bun"}={}){if(this.errorFormat=V,this.platform=B,!v.instance)v.instance=this;if(Y)this.#Z=!0;if(this.errorFormat=V,this.emitter=new j,this.prefixApiUrl=C??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=Q??10,this.enableFileRouter=Z??!1,this.baseApiUrl=z||"",this.user_jwt_secret=$||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new k,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},J)this.addHooks("onError",(G,f)=>{console.log("Got an exception:",G),console.log("Request Path:",f.path)});if(X)this.useLogger({app:this,onError(G){console.error("Got an exception:",G)}});this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{},this.compileConfig=null}static router($){if(!this.instance)this.instance=new v;return new Proxy(this.instance,{get(z,Z,Q){return(C,J)=>{let X=$+C;return z[Z](X,J)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...$)=>{return this.FilterRoutes=$,this.setupFilter()},permitAll:()=>{for(let $ of this?.FilterRoutes){if($.endsWith("/"))$=$.slice(0,-1);this.filters.add($)}return this.FilterRoutes=null,this.setupFilter()},authenticate:($)=>{if($?.length)for(let z of $)this.filterFunction.push(z)},authenticateJwt:($)=>{this.filterFunction.push(t1($,this.user_jwt_secret))},authenticateJwtDB:($,z)=>{this.filterFunction.push(e1($,z,this.user_jwt_secret))}}}redirect($,z,Z){return this.any($,(Q)=>{let C=Q.params,J=z;if(C)for(let Y in C)J=J.replace(`:${Y}`,C[Y]);let X=Q.url.search;if(X)J+=X;return Q.redirect(J,Z)}),this}serveStatic($,z){return this.staticPath=$,this.staticRequestPath=z,this}static($,z){return this.staticPath=$,this.staticRequestPath=z,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,z){if(typeof $!=="string")throw new Error("hookName must be a string");if(typeof z!=="function")throw new Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(z);break;case"preHandler":this.hooks.preHandler?.push(z);break;case"postHandler":this.hooks.postHandler?.push(z);break;case"onSend":this.hooks.onSend?.push(z);break;case"onError":this.hooks.onError?.push(z);break;case"onClose":this.hooks.onClose?.push(z);break;default:throw new Error(`Unknown hook type: ${$}`)}return this}compile(){let $={hasMiddleware:!1,hasOnReqHook:!1,hasPreHandlerHook:!1,hasOnError:!1,hasPostHandlerHook:!1,hasOnSendHook:!1,hasFilterEnabled:!1};if(this.hasFilterEnabled)$.hasFilterEnabled=!0,this.hasFilterEnabled=!0;if(this?.globalMiddlewares?.length>0)$.hasMiddleware=!0,this.hasMiddleware=!0;for(let[z,Z]of this?.middlewares?.entries())if(Z.length>0){$.hasMiddleware=!0,this.hasMiddleware=!0;break}if(this?.enableFileRouter){let z=process.cwd(),Z=O.join(z,"src","routes");if(f1?.existsSync(Z))this.loadRoutes(Z,"")}if(this?.hooks?.onRequest&&this.hooks.onRequest.length>0)$.hasOnReqHook=!0,this.hasOnReqHook=!0;if(this?.hooks?.preHandler&&this.hooks.preHandler.length>0)$.hasPreHandlerHook=!0,this.hasPreHandlerHook=!0;if(this?.hooks?.postHandler&&this.hooks.postHandler?.length>0)$.hasPostHandlerHook=!0,this.hasPostHandlerHook=!0;if(this?.hooks?.onSend&&this.hooks.onSend?.length>0)$.hasOnSendHook=!0,this.hasOnSendHook=!0;if(this?.hooks?.onError&&this.hooks.onError?.length>0)$.hasOnError=!0,this.hasOnError=!0;return this.tempRoutes=null,this.compileConfig=$,$}async registerFileRoutes($,z,Z){let Q=await import($),C;if(Z===".ts")C=O.basename($,".ts");else if(Z===".js")C=O.basename($,".js");let J=z+"/"+C;if(J.endsWith("/index"))J=z;else if(J.endsWith("/api"))J=z;J=J.replace(/\[(.*?)\]/g,":$1");let X=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let Y of X)if(Q[Y]){let V=Y.toLowerCase(),B=Q[Y];this[V](`${this.baseApiUrl}${J}`,B)}}async loadRoutes($,z){let Z=await f1.promises.readdir($);for(let Q of Z){let C=O.join($,Q);if((await f1.promises.stat(C)).isDirectory())await this.loadRoutes(C,z+"/"+Q);else if(Q.endsWith(".ts"))await this.registerFileRoutes(C,z,".ts");else if(Q.endsWith(".js"))await this.registerFileRoutes(C,z,".js")}}useLogger($){return a1($),this}useAdvancedLogger($){return r1($),this}BunRoute($,z,...Z){if(!z||typeof z!=="string")throw new Error("give a path in string format");if(!this.compileConfig)this.compile();let Q;if(typeof Z[0]==="string"||typeof Z[0]==="object")Q=Z[0];if(typeof Q!=="undefined"){let J=typeof Q==="string"?Q:JSON.stringify(Q)}let C=s1(this.compileConfig,this,$.toUpperCase(),z,...Z);return this.routes[z]=C,this}listen($,...z){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let Z="0.0.0.0",Q=void 0,C={};for(let X of z)if(typeof X==="string")Z=X;else if(typeof X==="function")Q=X;else if(typeof X==="object"&&X!==null)C=X;let J={port:$,hostname:Z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)J.routes=this.routes;if(C.cert&&C.key)J.certFile=C.cert,J.keyFile=C.key;if(this.serverInstance=Bun?.serve(J),Q)Q();return this.serverInstance}close($){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,$?$():console.log("Server has been stopped");else console.warn("Server is not running.")}cfFetch($,z,Z){return this.#$($,void 0,z,Z)}fetch(){let $=this.compile();if(this.platform==="cf"||this.platform==="cloudflare")return(z,Z,Q)=>{return this.#$(z,void 0,Z,Q)};if(this.#Z){let z=p1($,this);return(Z,Q)=>{return z(Z,Q,this).catch(async(C)=>{return console.error("Unhandled handler error:",C),await w("onError",this.hooks.onError,[C,Z,Y1(Z.url),Q])||I(500,"Internal Server Error")})}}return this.#$.bind(this)}async#$($,z,Z,Q){let C,J=$.url.indexOf("/",$.url.indexOf(":")+4),X=J;for(;X<$.url.length;X++){let B=$.url.charCodeAt(X);if(B===37){let G=$.url.indexOf("?",X),f=$.url.slice(J,G===-1?void 0:G);C=X1(f.includes("%25")?f.replace(/%25/g,"%2525"):f);break}else if(B===63)break}if(!C)C=$.url.slice(J,X);let Y=this.trie.search(C,$.method),V=new E($,z,C,Y?.path,Z,Q);try{if(this.hasOnReqHook)await w("onRequest",this.hooks.onRequest,[V]);if(this.hasMiddleware){let f=await l1(this,C,V);if(f)return f}if(this.hasFilterEnabled){let f=await m(this,C,V);if(f)return f}if(!Y)return await d(this,V,C);if(this.hasPreHandlerHook){let f=await w("preHandler",this.hooks.preHandler,[V]);if(f)return f}let B=Y.handler(V),G=B instanceof Promise?await B:B;if(this.hasOnSendHook){let f=await w("onSend",this.hooks.onSend,[V,G]);if(f)return f}if(G instanceof Response)return G}catch(B){return this.handleError(B,V)}return I(500,"No response returned from handler.")}async handleError($,z){let Q=this.errorFormat,C=Y1(z.req.url),J=await w("onError",this.hooks.onError,[$,z]);if(J)return J;if($&&typeof $==="object"&&$.name==="HTTPException"){let V=$;if(V.res)return V.res;return Q==="json"?Response.json({error:V.message},{status:V.status}):new Response(V.message,{status:V.status})}let X=$ instanceof Error?$.message:"Internal Server Error",Y=$ instanceof Error?$.stack:void 0;if(Q==="json"){let V={error:X,...!1,path:C};return Response.json(V,{status:500,headers:{"Content-Type":"application/json"}})}else{let V=`Error: ${X}`;return new Response(V,{headers:{"Content-Type":"text/plain"},status:500})}}route($,z){$=$&&$.length>0?$:z?.prefixApiUrl;let Z=z?.tempRoutes??new Map;for(let[Q,C]of Z.entries()){let J=Q.replace(/::\w+$/,""),X=`${$}${J}`;if(!this.middlewares.has(X))this.middlewares.set(X,[]);C.handlers.slice(0,-1).forEach((G)=>{let f=this.middlewares.get(X);if(!f.includes(G))f.push(G)});let V=C.handlers[C.handlers.length-1],B=C.method;try{this.trie.insert(X,{handler:V,method:B})}catch(G){console.error(`Error inserting ${X}:`,G)}}return z=null,this}register($,z){return this.route($,z)}addRoute($,z,Z){if(typeof z!=="string")throw new Error(`Error in ${Z[Z.length-1]}: Path must be a string. Received: ${typeof z}`);if(typeof $!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(z+"::"+$,{method:$,handlers:Z});let Q=Z.slice(0,-1),C=Z[Z.length-1];if(Q.length>0){if(!this.middlewares.has(z))this.middlewares.set(z,[]);Q.forEach((J)=>{if(z==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...Q])];else if(!this.middlewares.get(z)?.includes(J))this.middlewares.get(z)?.push(J)})}try{if($==="ANY"){let J=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let X of J)this.trie.insert(z,{handler:C,method:X})}this.trie.insert(z,{handler:C,method:$})}catch(J){console.error(`Error inserting ${z}:`,J)}}use($,z){if(Array.isArray($))$.forEach((Q)=>{if(typeof Q==="function")this.globalMiddlewares.push(Q)});if(typeof $==="function"){if(this.globalMiddlewares.push($),Array.isArray(z))z.forEach((Q)=>{this.globalMiddlewares.push(Q)});return this}return(Array.isArray($)?$.filter((Q)=>typeof Q==="string"):[$].filter((Q)=>typeof Q==="string")).forEach((Q)=>{if(!this.middlewares.has(Q))this.middlewares.set(Q,[]);if(z)(Array.isArray(z)?z:[z]).forEach((J)=>{this.middlewares.get(Q)?.push(J)})}),this}get($,...z){return this.addRoute("GET",$,z),this}post($,...z){return this.addRoute("POST",$,z),this}put($,...z){return this.addRoute("PUT",$,z),this}patch($,...z){return this.addRoute("PATCH",$,z),this}delete($,...z){return this.addRoute("DELETE",$,z),this}any($,...z){return this.addRoute("ANY",$,z),this}head($,...z){return this.addRoute("HEAD",$,z),this}options($,...z){return this.addRoute("OPTIONS",$,z),this}propfind($,...z){return this.addRoute("PROPFIND",$,z),this}routeNotFound($){return this.routeNotFoundFunc=$,this}on($,z){this.emitter.on($,z)}emit($,...z){this.emitter.emit($,...z)}}export{v as default};
|
|
170
|
+
`;return new Function("executeBunMiddlewares","handlers","runHooks","filterFunctions","onRequestHooks","allMiddlewares",D)(n1,B,w,S,G,f)};r();var{default:G1}=(()=>({}));var U={reset:"\x1B[0m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[34m",PUT:"\x1B[35m",DELETE:"\x1B[31m",PATCH:"\x1B[36m"}},J1=($,z,Z)=>{let Q=U[$]||U.reset,J=Z?.method?U.method[Z.method]||U.reset:U.reset,X=Z?.status?Z.status>=500?U.error:Z.status>=400?U.warn:U.info:U.reset;console.log(`
|
|
171
|
+
${Q}[${$.toUpperCase()}]${U.reset} ${z} - ${J}${Z?.method||""}${U.reset}`);let Y={timestamp:new Date().toISOString(),...Z,status:Z?.status?`${X}${Z.status}${U.reset}`:void 0,method:Z?.method?`${J>Q}${Z.method}${U.reset}`:void 0};console.log(JSON.stringify(Y,null,2)+`
|
|
172
|
+
`)},r1=($)=>{let{app:z,logger:Z,logLevel:Q="info",onRequest:J,onSend:X,onError:Y}=$||{};z?.addHooks("onRequest",(B)=>{B.req.startTime=Date.now(),Z?.()??J1(Q,"Incoming Request",{method:B.req.method,url:B.path,headers:{"user-agent":B.req.headers.get("user-agent"),"content-type":B.req.headers.get("content-type")}}),J?.(B)}),z?.addHooks("onSend",async(B,C)=>{let V=`${Date.now()-B.req.startTime}ms`;Z?.()??J1(Q,"Response Sent",{method:B.req.method,url:B.url.toString(),status:C.status,duration:V,reqId:B.get?.("requestId"),headers:{"content-type":C.headers.get("content-type")}});let f=await X?.(B);if(f instanceof Response)return f}),z?.addHooks("onError",async(B,C)=>{Z?.()??J1("error","Unhandled Error",{method:C.req.method,url:C.path,status:500,error:B.message});let V=await Y?.(B,C);if(V instanceof Response)return V})},X1=($,z,Z,Q=0,J,X)=>{let Y=U.method[z]||U.reset,B=Q>=500?U.error:Q>=400?U.warn:U.info,C=X?`[${X}] `:"",V=$==="<--"?`${$} ${Y}${z}${U.reset} ${Z} ${C}`:`${$} ${Y}${z}${U.reset} ${Z} ${B}${Q}${U.reset} ${J??""} ${C}`;console.log(V)},Q4=($)=>{let z=Date.now()-$;return z<1000?`${z}ms`:`${Math.round(z/1000)}s`},a1=($)=>{let{app:z,log:Z,onRequest:Q,onSend:J,onError:X}=$;z.addHooks("onRequest",(Y)=>{let{req:B,path:C}=Y;B.startTime=Date.now(),Z?.()??X1("<--",B.method,C),Q?.(B,C)}),z.addHooks("onSend",async(Y,B)=>{let{method:C,url:V}=Y.req,f=new URL(V).pathname,G=Y.get?.("requestId");Z?.()??X1("-->",C,f,B.status,Q4(Y.req.startTime),G);let N=await J?.(Y);if(N instanceof Response)return N}),z.addHooks("onError",async(Y,B)=>{let{req:C,path:V}=B;Z?.()??X1(Y.message,C.method,V,500);let f=await X?.(Y,C,V);if(f instanceof Response)return f})};function t1($,z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(Z)=>{try{let Q=Z.cookies?.accessToken??Z.req?.headers?.get("Authorization");if(!Q)return Z.json({message:"Unauthorized",error:"No token provided"},401);if(Q.startsWith("Bearer "))Q=Q.slice(7);let J=$?.verify(Q,z);if(!J)return Z.json({message:"Unauthorized",error:"Token could not be decoded"},401);Z.set("user",J)}catch(Q){let J="Invalid token";if(Q.name==="TokenExpiredError")J="Token expired";else if(Q.name==="JsonWebTokenError")J="Malformed or tampered token";return Z.json({message:"Unauthorized",error:J},401)}}}function e1($,z,Z){if(!$)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!z)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(Q)=>{try{let J=Q.cookies?.accessToken??Q.req?.headers?.get("Authorization");if(!J)return Q.json({message:"Unauthorized",error:"No token provided"},401);if(J.startsWith("Bearer "))J=J.slice(7);let X=$?.verify(J,Z);if(!X)return Q.json({message:"Unauthorized",error:"Token could not be decoded"},401);let Y=await z.findById(X._id).select("-password -refreshToken");if(!Y)return Q.json({message:"Unauthorized: User not found"},404);Q.set("user",Y);return}catch(J){let X="Invalid token";if(J.name==="TokenExpiredError")X="Token expired";else if(J.name==="JsonWebTokenError")X="Malformed or tampered token";return Q.json({message:"Unauthorized",error:X},401)}}}var J4=($,z)=>{try{return z($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Z)=>{try{return z(Z)}catch{return Z}})}},Y1=($)=>J4($,decodeURI),B1=($)=>{let z=$.indexOf("/",$.indexOf(":")+4),Z=z;for(;Z<$.length;Z++){let Q=$.charCodeAt(Z);if(Q===37){let J=$.indexOf("?",Z),X=$.slice(z,J===-1?void 0:J);return Y1(X.includes("%25")?X.replace(/%25/g,"%2525"):X)}else if(Q===63)break}return $.slice(z,Z)};var V1=Symbol.for,H=Symbol("kCapture"),Q0=V1("events.errorMonitor"),X4=Symbol("events.maxEventTargetListeners"),Y4=Symbol("events.maxEventTargetListenersWarned"),$0=V1("nodejs.rejection"),B4=V1("nodejs.rejection"),Z0=Array.prototype.slice,M=10,j=function $(z){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[H]=z?.captureRejections?Boolean(z?.captureRejections):W[H])this.emit=G4},W=j.prototype={};W._events=void 0;W._eventsCount=0;W._maxListeners=void 0;W.setMaxListeners=function $(z){return f1(z,"setMaxListeners",0),this._maxListeners=z,this};W.constructor=j;W.getMaxListeners=function $(){return this?._maxListeners??M};function J0($,z){var{_events:Z}=$;if(z[0]??=new Error("Unhandled error."),!Z)throw z[0];var Q=Z[Q0];if(Q)for(var J of Z0.call(Q))J.apply($,z);var X=Z.error;if(!X)throw z[0];for(var J of Z0.call(X))J.apply($,z);return!0}function C4($,z,Z,Q){z.then(void 0,function(J){queueMicrotask(()=>V4($,J,Z,Q))})}function V4($,z,Z,Q){if(typeof $[$0]==="function")$[$0](z,Z,...Q);else try{$[H]=!1,$.emit("error",z)}finally{$[H]=!0}}var f4=function $(z,...Z){if(z==="error")return J0(this,Z);var{_events:Q}=this;if(Q===void 0)return!1;var J=Q[z];if(J===void 0)return!1;let X=J.length>1?J.slice():J;for(let Y=0,{length:B}=X;Y<B;Y++){let C=X[Y];switch(Z.length){case 0:C.call(this);break;case 1:C.call(this,Z[0]);break;case 2:C.call(this,Z[0],Z[1]);break;case 3:C.call(this,Z[0],Z[1],Z[2]);break;default:C.apply(this,Z);break}}return!0},G4=function $(z,...Z){if(z==="error")return J0(this,Z);var{_events:Q}=this;if(Q===void 0)return!1;var J=Q[z];if(J===void 0)return!1;let X=J.length>1?J.slice():J;for(let Y=0,{length:B}=X;Y<B;Y++){let C=X[Y],V;switch(Z.length){case 0:V=C.call(this);break;case 1:V=C.call(this,Z[0]);break;case 2:V=C.call(this,Z[0],Z[1]);break;case 3:V=C.call(this,Z[0],Z[1],Z[2]);break;default:V=C.apply(this,Z);break}if(V!==void 0&&typeof V?.then==="function"&&V.then===Promise.prototype.then)C4(this,V,z,Z)}return!0};W.emit=f4;W.addListener=function $(z,Z){P(Z);var Q=this._events;if(!Q)Q=this._events={__proto__:null},this._eventsCount=0;else if(Q.newListener)this.emit("newListener",z,Z.listener??Z);var J=Q[z];if(!J)Q[z]=[Z],this._eventsCount++;else{J.push(Z);var X=this._maxListeners??M;if(X>0&&J.length>X&&!J.warned)X0(this,z,J)}return this};W.on=W.addListener;W.prependListener=function $(z,Z){P(Z);var Q=this._events;if(!Q)Q=this._events={__proto__:null},this._eventsCount=0;else if(Q.newListener)this.emit("newListener",z,Z.listener??Z);var J=Q[z];if(!J)Q[z]=[Z],this._eventsCount++;else{J.unshift(Z);var X=this._maxListeners??M;if(X>0&&J.length>X&&!J.warned)X0(this,z,J)}return this};function X0($,z,Z){Z.warned=!0;let Q=new Error(`Possible EventEmitter memory leak detected. ${Z.length} ${String(z)} listeners added to [${$.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);Q.name="MaxListenersExceededWarning",Q.emitter=$,Q.type=z,Q.count=Z.length,console.warn(Q)}function Y0($,z,...Z){this.removeListener($,z),z.apply(this,Z)}W.once=function $(z,Z){P(Z);let Q=Y0.bind(this,z,Z);return Q.listener=Z,this.addListener(z,Q),this};W.prependOnceListener=function $(z,Z){P(Z);let Q=Y0.bind(this,z,Z);return Q.listener=Z,this.prependListener(z,Q),this};W.removeListener=function $(z,Z){P(Z);var{_events:Q}=this;if(!Q)return this;var J=Q[z];if(!J)return this;var X=J.length;let Y=-1;for(let B=X-1;B>=0;B--)if(J[B]===Z||J[B].listener===Z){Y=B;break}if(Y<0)return this;if(Y===0)J.shift();else J.splice(Y,1);if(J.length===0)delete Q[z],this._eventsCount--;return this};W.off=W.removeListener;W.removeAllListeners=function $(z){var{_events:Z}=this;if(z&&Z){if(Z[z])delete Z[z],this._eventsCount--}else this._events={__proto__:null};return this};W.listeners=function $(z){var{_events:Z}=this;if(!Z)return[];var Q=Z[z];if(!Q)return[];return Q.map((J)=>J.listener??J)};W.rawListeners=function $(z){var{_events:Z}=this;if(!Z)return[];var Q=Z[z];if(!Q)return[];return Q.slice()};W.listenerCount=function $(z){var{_events:Z}=this;if(!Z)return 0;return Z[z]?.length??0};W.eventNames=function $(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};W[H]=!1;function W4($,z,Z){var Q=Z?.signal;if(B0(Q,"options.signal"),Q?.aborted)throw new C1(void 0,{cause:Q?.reason});let{resolve:J,reject:X,promise:Y}=$newPromiseCapability(Promise),B=(f)=>{if($.removeListener(z,C),Q!=null)i(Q,"abort",V);X(f)},C=(...f)=>{if(typeof $.removeListener==="function")$.removeListener("error",B);if(Q!=null)i(Q,"abort",V);J(f)};if(z0($,z,C,{once:!0}),z!=="error"&&typeof $.once==="function")$.once("error",B);function V(){i($,z,C),i($,"error",B),X(new C1(void 0,{cause:Q?.reason}))}if(Q!=null)z0(Q,"abort",V,{once:!0});return Y}function K4($,z){return $.listeners(z)}function U4($,...z){f1($,"setMaxListeners",0);var Z;if(z&&(Z=z.length))for(let Q=0;Q<Z;Q++)z[Q].setMaxListeners($);else M=$}function F4($,z){return $.listenerCount(z)}function i($,z,Z,Q){if(typeof $.removeListener==="function")$.removeListener(z,Z);else $.removeEventListener(z,Z,Q)}function z0($,z,Z,Q){if(typeof $.on==="function")if(Q.once)$.once(z,Z);else $.on(z,Z);else $.addEventListener(z,Z,Q)}class C1 extends Error{constructor($="The operation was aborted",z=void 0){if(z!==void 0&&typeof z!=="object")throw T("options","Object",z);super($,z);this.code="ABORT_ERR",this.name="AbortError"}}function T($,z,Z){let Q=new TypeError(`The "${$}" argument must be of type ${z}. Received ${Z}`);return Q.code="ERR_INVALID_ARG_TYPE",Q}function D4($,z,Z){let Q=new RangeError(`The "${$}" argument is out of range. It must be ${z}. Received ${Z}`);return Q.code="ERR_OUT_OF_RANGE",Q}function B0($,z){if($!==void 0&&($===null||typeof $!=="object"||!("aborted"in $)))throw T(z,"AbortSignal",$)}function f1($,z,Z,Q){if(typeof $!=="number")throw T(z,"number",$);if(Z!=null&&$<Z||Q!=null&&$>Q||(Z!=null||Q!=null)&&Number.isNaN($))throw D4(z,`${Z!=null?`>= ${Z}`:""}${Z!=null&&Q!=null?" && ":""}${Q!=null?`<= ${Q}`:""}`,$)}function P($){if(typeof $!=="function")throw new TypeError("The listener must be a function")}function N4($,z){if(typeof $!=="boolean")throw T(z,"boolean",$)}function q4($){return $?._maxListeners??M}function S4($,z){if($===void 0)throw T("signal","AbortSignal",$);if(B0($,"signal"),typeof z!=="function")throw T("listener","function",z);let Z;if($.aborted)queueMicrotask(()=>z());else $.addEventListener("abort",z,{__proto__:null,once:!0}),Z=()=>{$.removeEventListener("abort",z)};return{__proto__:null,[Symbol.dispose](){Z?.()}}}Object.defineProperties(j,{captureRejections:{get(){return W[H]},set($){N4($,"EventEmitter.captureRejections"),W[H]=$},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return M},set:($)=>{f1($,"defaultMaxListeners",0),M=$}},kMaxEventTargetListeners:{value:X4,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:Y4,enumerable:!1,configurable:!1,writable:!1}});Object.assign(j,{once:W4,getEventListeners:K4,getMaxListeners:q4,setMaxListeners:U4,EventEmitter:j,usingDomains:!1,captureRejectionSymbol:B4,errorMonitor:Q0,addAbortListener:S4,init:j,listenerCount:F4});class v{static instance;routes;tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;routeNotFoundFunc;prefixApiUrl;compileConfig;#Z=!1;emitter;errorFormat;platform="bun";staticPath;staticRequestPath=void 0;constructor({jwtSecret:$,baseApiUrl:z,enableFileRouting:Z,idleTimeOut:Q,prefixApiUrl:J,onError:X,logger:Y,pipelineArchitecture:B,errorFormat:C="json",platform:V="bun"}={}){if(this.errorFormat=C,this.platform=V,!v.instance)v.instance=this;if(B)this.#Z=!0;if(this.errorFormat=C,this.emitter=new j,this.prefixApiUrl=J??"",this.fetch=this.fetch.bind(this),this.routes={},this.idleTimeOut=Q??10,this.enableFileRouter=Z??!1,this.baseApiUrl=z||"",this.user_jwt_secret=$||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new k,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[]},X)this.addHooks("onError",(f,G)=>{console.log("Got an exception:",f),console.log("Request Path:",G.path)});if(Y)this.useLogger({app:this,onError(f){console.error("Got an exception:",f)}});this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={},this.routeNotFoundFunc=()=>{},this.compileConfig=null}static router($){if(!this.instance)this.instance=new v;return new Proxy(this.instance,{get(z,Z,Q){return(J,X)=>{let Y=$+J;return z[Z](Y,X)}}})}setupFilter(){return this.hasFilterEnabled=!0,{publicRoutes:(...$)=>{return this.FilterRoutes=$,this.setupFilter()},permitAll:()=>{for(let $ of this?.FilterRoutes){if($.endsWith("/"))$=$.slice(0,-1);this.filters.add($)}return this.FilterRoutes=null,this.setupFilter()},authenticate:($)=>{if($?.length)for(let z of $)this.filterFunction.push(z)},authenticateJwt:($)=>{this.filterFunction.push(t1($,this.user_jwt_secret))},authenticateJwtDB:($,z)=>{this.filterFunction.push(e1($,z,this.user_jwt_secret))}}}redirect($,z,Z){return this.any($,(Q)=>{let J=Q.params,X=z;if(J)for(let B in J)X=X.replace(`:${B}`,J[B]);let Y=Q.url.search;if(Y)X+=Y;return Q.redirect(X,Z)}),this}serveStatic($,z){return this.staticPath=$,this.staticRequestPath=z,this}static($,z){return this.staticPath=$,this.staticRequestPath=z,this}staticHtml($){return this.staticFiles={...this.staticFiles,...$},this}addHooks($,z){if(typeof $!=="string")throw new Error("hookName must be a string");if(typeof z!=="function")throw new Error("callback must be a instance of function");switch($){case"onRequest":this.hooks.onRequest?.push(z);break;case"preHandler":this.hooks.preHandler?.push(z);break;case"postHandler":this.hooks.postHandler?.push(z);break;case"onSend":this.hooks.onSend?.push(z);break;case"onError":this.hooks.onError?.push(z);break;case"onClose":this.hooks.onClose?.push(z);break;default:throw new Error(`Unknown hook type: ${$}`)}return this}compile(){let $={hasMiddleware:!1,hasOnReqHook:!1,hasPreHandlerHook:!1,hasOnError:!1,hasPostHandlerHook:!1,hasOnSendHook:!1,hasFilterEnabled:!1};if(this.hasFilterEnabled)$.hasFilterEnabled=!0,this.hasFilterEnabled=!0;if(this?.globalMiddlewares?.length>0)$.hasMiddleware=!0,this.hasMiddleware=!0;for(let[z,Z]of this?.middlewares?.entries())if(Z.length>0){$.hasMiddleware=!0,this.hasMiddleware=!0;break}if(this?.enableFileRouter){let z=process.cwd(),Z=O.join(z,"src","routes");if(G1?.existsSync(Z))this.loadRoutes(Z,"")}if(this?.hooks?.onRequest&&this.hooks.onRequest.length>0)$.hasOnReqHook=!0,this.hasOnReqHook=!0;if(this?.hooks?.preHandler&&this.hooks.preHandler.length>0)$.hasPreHandlerHook=!0,this.hasPreHandlerHook=!0;if(this?.hooks?.postHandler&&this.hooks.postHandler?.length>0)$.hasPostHandlerHook=!0,this.hasPostHandlerHook=!0;if(this?.hooks?.onSend&&this.hooks.onSend?.length>0)$.hasOnSendHook=!0,this.hasOnSendHook=!0;if(this?.hooks?.onError&&this.hooks.onError?.length>0)$.hasOnError=!0,this.hasOnError=!0;return this.tempRoutes=null,this.compileConfig=$,$}async registerFileRoutes($,z,Z){let Q=await import($),J;if(Z===".ts")J=O.basename($,".ts");else if(Z===".js")J=O.basename($,".js");let X=z+"/"+J;if(X.endsWith("/index"))X=z;else if(X.endsWith("/api"))X=z;X=X.replace(/\[(.*?)\]/g,":$1");let Y=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let B of Y)if(Q[B]){let C=B.toLowerCase(),V=Q[B];this[C](`${this.baseApiUrl}${X}`,V)}}async loadRoutes($,z){let Z=await G1.promises.readdir($);for(let Q of Z){let J=O.join($,Q);if((await G1.promises.stat(J)).isDirectory())await this.loadRoutes(J,z+"/"+Q);else if(Q.endsWith(".ts"))await this.registerFileRoutes(J,z,".ts");else if(Q.endsWith(".js"))await this.registerFileRoutes(J,z,".js")}}useLogger($){return a1($),this}useAdvancedLogger($){return r1($),this}BunRoute($,z,...Z){if(!z||typeof z!=="string")throw new Error("give a path in string format");if(!this.compileConfig)this.compile();let Q;if(typeof Z[0]==="string"||typeof Z[0]==="object")Q=Z[0];if(typeof Q!=="undefined"){let X=typeof Q==="string"?Q:JSON.stringify(Q)}let J=s1(this.compileConfig,this,$.toUpperCase(),z,...Z);return this.routes[z]=J,this}listen($,...z){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let Z="0.0.0.0",Q=void 0,J={};for(let Y of z)if(typeof Y==="string")Z=Y;else if(typeof Y==="function")Q=Y;else if(typeof Y==="object"&&Y!==null)J=Y;let X={port:$,hostname:Z,idleTimeOut:this.idleTimeOut,fetch:this.fetch(),static:this.staticFiles};if(this.routes&&Object.keys(this.routes).length>0)X.routes=this.routes;if(J.cert&&J.key)X.certFile=J.cert,X.keyFile=J.key;if(this.serverInstance=Bun?.serve(X),Q)Q();return this.serverInstance}close($){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,$?$():console.log("Server has been stopped");else console.warn("Server is not running.")}cfFetch(){return this.compile(),($,z,Z)=>{return this.#$($,void 0,z,Z)}}fetch(){let $=this.compile();if(this.platform==="cf"||this.platform==="cloudflare")return(z,Z,Q)=>{return this.#$(z,void 0,Z,Q)};if(this.#Z){let z=p1($,this);return(Z,Q)=>{return z(Z,Q,this).catch(async(J)=>{return console.error("Unhandled handler error:",J),await w("onError",this.hooks.onError,[J,Z,B1(Z.url),Q])||I(500,"Internal Server Error")})}}return this.#$.bind(this)}async#$($,z,Z,Q){let J,X=$.url.indexOf("/",$.url.indexOf(":")+4),Y=X;for(;Y<$.url.length;Y++){let V=$.url.charCodeAt(Y);if(V===37){let f=$.url.indexOf("?",Y),G=$.url.slice(X,f===-1?void 0:f);J=Y1(G.includes("%25")?G.replace(/%25/g,"%2525"):G);break}else if(V===63)break}if(!J)J=$.url.slice(X,Y);let B=this.trie.search(J,$.method),C=new E($,z,J,B?.path,Z,Q);try{if(this.hasOnReqHook)await w("onRequest",this.hooks.onRequest,[C]);if(this.hasMiddleware){let G=await l1(this,J,C);if(G)return G}if(this.hasFilterEnabled){let G=await m(this,J,C);if(G)return G}if(!B)return await d(this,C,J);if(this.hasPreHandlerHook){let G=await w("preHandler",this.hooks.preHandler,[C]);if(G)return G}let V=B.handler(C),f=V instanceof Promise?await V:V;if(this.hasOnSendHook){let G=await w("onSend",this.hooks.onSend,[C,f]);if(G)return G}if(f instanceof Response)return f}catch(V){return this.handleError(V,C)}return I(500,"No response returned from handler.")}async handleError($,z){let Q=this.errorFormat,J=B1(z.req.url),X=await w("onError",this.hooks.onError,[$,z]);if(X)return X;if($&&typeof $==="object"&&$.name==="HTTPException"){let C=$;if(C.res)return C.res;return Q==="json"?Response.json({error:C.message},{status:C.status}):new Response(C.message,{status:C.status})}let Y=$ instanceof Error?$.message:"Internal Server Error",B=$ instanceof Error?$.stack:void 0;if(Q==="json"){let C={error:Y,...!1,path:J};return Response.json(C,{status:500,headers:{"Content-Type":"application/json"}})}else{let C=`Error: ${Y}`;return new Response(C,{headers:{"Content-Type":"text/plain"},status:500})}}route($,z){$=$&&$.length>0?$:z?.prefixApiUrl;let Z=z?.tempRoutes??new Map;for(let[Q,J]of Z.entries()){let X=Q.replace(/::\w+$/,""),Y=`${$}${X}`;if(!this.middlewares.has(Y))this.middlewares.set(Y,[]);J.handlers.slice(0,-1).forEach((f)=>{let G=this.middlewares.get(Y);if(!G.includes(f))G.push(f)});let C=J.handlers[J.handlers.length-1],V=J.method;try{this.trie.insert(Y,{handler:C,method:V})}catch(f){console.error(`Error inserting ${Y}:`,f)}}return z=null,this}register($,z){return this.route($,z)}addRoute($,z,Z){if(typeof z!=="string")throw new Error(`Error in ${Z[Z.length-1]}: Path must be a string. Received: ${typeof z}`);if(typeof $!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof $}`);this.tempRoutes?.set(z+"::"+$,{method:$,handlers:Z});let Q=Z.slice(0,-1),J=Z[Z.length-1];if(Q.length>0){if(!this.middlewares.has(z))this.middlewares.set(z,[]);Q.forEach((X)=>{if(z==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...Q])];else if(!this.middlewares.get(z)?.includes(X))this.middlewares.get(z)?.push(X)})}try{if($==="ANY"){let X=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let Y of X)this.trie.insert(z,{handler:J,method:Y})}this.trie.insert(z,{handler:J,method:$})}catch(X){console.error(`Error inserting ${z}:`,X)}}use($,z){if(Array.isArray($))$.forEach((Q)=>{if(typeof Q==="function")this.globalMiddlewares.push(Q)});if(typeof $==="function"){if(this.globalMiddlewares.push($),Array.isArray(z))z.forEach((Q)=>{this.globalMiddlewares.push(Q)});return this}return(Array.isArray($)?$.filter((Q)=>typeof Q==="string"):[$].filter((Q)=>typeof Q==="string")).forEach((Q)=>{if(!this.middlewares.has(Q))this.middlewares.set(Q,[]);if(z)(Array.isArray(z)?z:[z]).forEach((X)=>{this.middlewares.get(Q)?.push(X)})}),this}get($,...z){return this.addRoute("GET",$,z),this}post($,...z){return this.addRoute("POST",$,z),this}put($,...z){return this.addRoute("PUT",$,z),this}patch($,...z){return this.addRoute("PATCH",$,z),this}delete($,...z){return this.addRoute("DELETE",$,z),this}any($,...z){return this.addRoute("ANY",$,z),this}head($,...z){return this.addRoute("HEAD",$,z),this}options($,...z){return this.addRoute("OPTIONS",$,z),this}propfind($,...z){return this.addRoute("PROPFIND",$,z),this}routeNotFound($){return this.routeNotFoundFunc=$,this}on($,z){this.emitter.on($,z)}emit($,...z){this.emitter.emit($,...z)}}export{v as default};
|
package/dist/request_pipeline.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Rf=Object.create;var{getPrototypeOf:cf,defineProperty:
|
|
1
|
+
var Rf=Object.create;var{getPrototypeOf:cf,defineProperty:W,getOwnPropertyNames:h,getOwnPropertyDescriptor:Lf}=Object,n=Object.prototype.hasOwnProperty;var Mf=(f,v,g)=>{g=f!=null?Rf(cf(f)):{};let u=v||!f||!f.__esModule?W(g,"default",{value:f,enumerable:!0}):g;for(let r of h(f))if(!n.call(u,r))W(u,r,{get:()=>f[r],enumerable:!0});return u},m=new WeakMap,Hf=(f)=>{var v=m.get(f),g;if(v)return v;if(v=W({},"__esModule",{value:!0}),f&&typeof f==="object"||typeof f==="function")h(f).map((u)=>!n.call(v,u)&&W(v,u,{get:()=>f[u],enumerable:!(g=Lf(f,u))||g.enumerable}));return m.set(f,v),v},H=(f,v)=>()=>(v||f((v={exports:{}}).exports,v),v.exports);var Sf=(f,v)=>{for(var g in v)W(f,g,{get:v[g],enumerable:!0,configurable:!0,set:(u)=>v[g]=()=>u})};var If=(f,v)=>()=>(f&&(v=f(f=0)),v);var yf=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(v,g)=>(typeof require!=="undefined"?require:v)[g]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var rf={};Sf(rf,{sep:()=>gf,resolve:()=>q,relative:()=>t,posix:()=>uf,parse:()=>ff,normalize:()=>S,join:()=>i,isAbsolute:()=>l,format:()=>p,extname:()=>o,dirname:()=>s,delimiter:()=>vf,default:()=>Ef,basename:()=>e,_makeLong:()=>a});function G(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function d(f,v){var g="",u=0,r=-1,C=0,w;for(var j=0;j<=f.length;++j){if(j<f.length)w=f.charCodeAt(j);else if(w===47)break;else w=47;if(w===47){if(r===j-1||C===1);else if(r!==j-1&&C===2){if(g.length<2||u!==2||g.charCodeAt(g.length-1)!==46||g.charCodeAt(g.length-2)!==46){if(g.length>2){var z=g.lastIndexOf("/");if(z!==g.length-1){if(z===-1)g="",u=0;else g=g.slice(0,z),u=g.length-1-g.lastIndexOf("/");r=j,C=0;continue}}else if(g.length===2||g.length===1){g="",u=0,r=j,C=0;continue}}if(v){if(g.length>0)g+="/..";else g="..";u=2}}else{if(g.length>0)g+="/"+f.slice(r+1,j);else g=f.slice(r+1,j);u=j-r-1}r=j,C=0}else if(w===46&&C!==-1)++C;else C=-1}return g}function Of(f,v){var g=v.dir||v.root,u=v.base||(v.name||"")+(v.ext||"");if(!g)return u;if(g===v.root)return g+u;return g+f+u}function q(){var f="",v=!1,g;for(var u=arguments.length-1;u>=-1&&!v;u--){var r;if(u>=0)r=arguments[u];else{if(g===void 0)g=process.cwd();r=g}if(G(r),r.length===0)continue;f=r+"/"+f,v=r.charCodeAt(0)===47}if(f=d(f,!v),v)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function S(f){if(G(f),f.length===0)return".";var v=f.charCodeAt(0)===47,g=f.charCodeAt(f.length-1)===47;if(f=d(f,!v),f.length===0&&!v)f=".";if(f.length>0&&g)f+="/";if(v)return"/"+f;return f}function l(f){return G(f),f.length>0&&f.charCodeAt(0)===47}function i(){if(arguments.length===0)return".";var f;for(var v=0;v<arguments.length;++v){var g=arguments[v];if(G(g),g.length>0)if(f===void 0)f=g;else f+="/"+g}if(f===void 0)return".";return S(f)}function t(f,v){if(G(f),G(v),f===v)return"";if(f=q(f),v=q(v),f===v)return"";var g=1;for(;g<f.length;++g)if(f.charCodeAt(g)!==47)break;var u=f.length,r=u-g,C=1;for(;C<v.length;++C)if(v.charCodeAt(C)!==47)break;var w=v.length,j=w-C,z=r<j?r:j,J=-1,$=0;for(;$<=z;++$){if($===z){if(j>z){if(v.charCodeAt(C+$)===47)return v.slice(C+$+1);else if($===0)return v.slice(C+$)}else if(r>z){if(f.charCodeAt(g+$)===47)J=$;else if($===0)J=0}break}var A=f.charCodeAt(g+$),b=v.charCodeAt(C+$);if(A!==b)break;else if(A===47)J=$}var V="";for($=g+J+1;$<=u;++$)if($===u||f.charCodeAt($)===47)if(V.length===0)V+="..";else V+="/..";if(V.length>0)return V+v.slice(C+J);else{if(C+=J,v.charCodeAt(C)===47)++C;return v.slice(C)}}function a(f){return f}function s(f){if(G(f),f.length===0)return".";var v=f.charCodeAt(0),g=v===47,u=-1,r=!0;for(var C=f.length-1;C>=1;--C)if(v=f.charCodeAt(C),v===47){if(!r){u=C;break}}else r=!1;if(u===-1)return g?"/":".";if(g&&u===1)return"//";return f.slice(0,u)}function e(f,v){if(v!==void 0&&typeof v!=="string")throw new TypeError('"ext" argument must be a string');G(f);var g=0,u=-1,r=!0,C;if(v!==void 0&&v.length>0&&v.length<=f.length){if(v.length===f.length&&v===f)return"";var w=v.length-1,j=-1;for(C=f.length-1;C>=0;--C){var z=f.charCodeAt(C);if(z===47){if(!r){g=C+1;break}}else{if(j===-1)r=!1,j=C+1;if(w>=0)if(z===v.charCodeAt(w)){if(--w===-1)u=C}else w=-1,u=j}}if(g===u)u=j;else if(u===-1)u=f.length;return f.slice(g,u)}else{for(C=f.length-1;C>=0;--C)if(f.charCodeAt(C)===47){if(!r){g=C+1;break}}else if(u===-1)r=!1,u=C+1;if(u===-1)return"";return f.slice(g,u)}}function o(f){G(f);var v=-1,g=0,u=-1,r=!0,C=0;for(var w=f.length-1;w>=0;--w){var j=f.charCodeAt(w);if(j===47){if(!r){g=w+1;break}continue}if(u===-1)r=!1,u=w+1;if(j===46){if(v===-1)v=w;else if(C!==1)C=1}else if(v!==-1)C=-1}if(v===-1||u===-1||C===0||C===1&&v===u-1&&v===g+1)return"";return f.slice(v,u)}function p(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return Of("/",f)}function ff(f){G(f);var v={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return v;var g=f.charCodeAt(0),u=g===47,r;if(u)v.root="/",r=1;else r=0;var C=-1,w=0,j=-1,z=!0,J=f.length-1,$=0;for(;J>=r;--J){if(g=f.charCodeAt(J),g===47){if(!z){w=J+1;break}continue}if(j===-1)z=!1,j=J+1;if(g===46){if(C===-1)C=J;else if($!==1)$=1}else if(C!==-1)$=-1}if(C===-1||j===-1||$===0||$===1&&C===j-1&&C===w+1){if(j!==-1)if(w===0&&u)v.base=v.name=f.slice(1,j);else v.base=v.name=f.slice(w,j)}else{if(w===0&&u)v.name=f.slice(1,C),v.base=f.slice(1,j);else v.name=f.slice(w,C),v.base=f.slice(w,j);v.ext=f.slice(C,j)}if(w>0)v.dir=f.slice(0,w-1);else if(u)v.dir="/";return v}var gf="/",vf=":",uf,Ef;var Cf=If(()=>{uf=((f)=>(f.posix=f,f))({resolve:q,normalize:S,isAbsolute:l,join:i,relative:t,_makeLong:a,dirname:s,basename:e,extname:o,format:p,parse:ff,sep:gf,delimiter:vf,win32:null,posix:null}),Ef=uf});var $f=H((hf)=>{var Pf=/[|\\{}()[\]^$+*?.]/g,xf=Object.prototype.hasOwnProperty,y=function(f,v){return xf.apply(f,[v])};hf.escapeRegExpChars=function(f){if(!f)return"";return String(f).replace(Pf,"\\$&")};var _f={"&":"&","<":"<",">":">",'"':""","'":"'"},Tf=/[&<>'"]/g;function kf(f){return _f[f]||f}var mf=`var _ENCODE_HTML_RULES = {
|
|
2
2
|
"&": "&"
|
|
3
3
|
, "<": "<"
|
|
4
4
|
, ">": ">"
|
|
@@ -10,21 +10,21 @@ function encode_char(c) {
|
|
|
10
10
|
return _ENCODE_HTML_RULES[c] || c;
|
|
11
11
|
};
|
|
12
12
|
`;hf.escapeXML=function(f){return f==null?"":String(f).replace(Tf,kf)};function wf(){return Function.prototype.toString.call(this)+`;
|
|
13
|
-
`+mf}try{if(typeof Object.defineProperty==="function")Object.defineProperty(hf.escapeXML,"toString",{value:wf});else hf.escapeXML.toString=wf}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}hf.shallowCopy=function(f,v){if(v=v||{},f!==null&&f!==void 0)for(var g in v){if(!
|
|
14
|
-
`),w=Math.max(
|
|
15
|
-
`);throw f.path=z,f.message=(z||"ejs")+":"+
|
|
13
|
+
`+mf}try{if(typeof Object.defineProperty==="function")Object.defineProperty(hf.escapeXML,"toString",{value:wf});else hf.escapeXML.toString=wf}catch(f){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}hf.shallowCopy=function(f,v){if(v=v||{},f!==null&&f!==void 0)for(var g in v){if(!y(v,g))continue;if(g==="__proto__"||g==="constructor")continue;f[g]=v[g]}return f};hf.shallowCopyFromList=function(f,v,g){if(g=g||[],v=v||{},f!==null&&f!==void 0)for(var u=0;u<g.length;u++){var r=g[u];if(typeof v[r]!="undefined"){if(!y(v,r))continue;if(r==="__proto__"||r==="constructor")continue;f[r]=v[r]}}return f};hf.cache={_data:{},set:function(f,v){this._data[f]=v},get:function(f){return this._data[f]},remove:function(f){delete this._data[f]},reset:function(){this._data={}}};hf.hyphenToCamel=function(f){return f.replace(/-[a-z]/g,function(v){return v[1].toUpperCase()})};hf.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function")return function(){return Object.create(null)};if(!({__proto__:null}instanceof Object))return function(){return{__proto__:null}};return function(){return{}}}();hf.hasOwnOnlyObject=function(f){var v=hf.createNullProtoObjWherePossible();for(var g in f)if(y(f,g))v[g]=f[g];return v}});var zf=H((R1,ef)=>{ef.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}});var Uf=H((bf)=>{var P=(()=>({})),X=(Cf(),Hf(rf)),K=$f(),Jf=!1,of=zf().version,pf="<",f1=">",g1="%",Vf="locals",v1="ejs",u1="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",Gf=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],r1=Gf.concat("cache"),Kf=/^\uFEFF/,O=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;bf.cache=K.cache;bf.fileLoader=P.readFileSync;bf.localsName=Vf;bf.promiseImpl=new Function("return this;")().Promise;bf.resolveInclude=function(f,v,g){var{dirname:u,extname:r,resolve:C}=X,w=C(g?v:u(v),f),j=r(f);if(!j)w+=".ejs";return w};function Yf(f,v){var g;if(v.some(function(u){return g=bf.resolveInclude(f,u,!0),P.existsSync(g)}))return g}function C1(f,v){var g,u,r=v.views,C=/^[A-Za-z]+:\\|^\//.exec(f);if(C&&C.length)if(f=f.replace(/^\/*/,""),Array.isArray(v.root))g=Yf(f,v.root);else g=bf.resolveInclude(f,v.root||"/",!0);else{if(v.filename){if(u=bf.resolveInclude(f,v.filename),P.existsSync(u))g=u}if(!g&&Array.isArray(r))g=Yf(f,r);if(!g&&typeof v.includer!=="function")throw new Error('Could not find the include file "'+v.escapeFunction(f)+'"')}return g}function U(f,v){var g,u=f.filename,r=arguments.length>1;if(f.cache){if(!u)throw new Error("cache option requires a filename");if(g=bf.cache.get(u),g)return g;if(!r)v=Zf(u).toString().replace(Kf,"")}else if(!r){if(!u)throw new Error("Internal EJS error: no file name or template provided");v=Zf(u).toString().replace(Kf,"")}if(g=bf.compile(v,f),f.cache)bf.cache.set(u,g);return g}function w1(f,v,g){var u;if(!g)if(typeof bf.promiseImpl=="function")return new bf.promiseImpl(function(r,C){try{u=U(f)(v),r(u)}catch(w){C(w)}});else throw new Error("Please provide a callback function");else{try{u=U(f)(v)}catch(r){return g(r)}g(null,u)}}function Zf(f){return bf.fileLoader(f)}function j1(f,v){var g=K.shallowCopy(K.createNullProtoObjWherePossible(),v);if(g.filename=C1(f,g),typeof v.includer==="function"){var u=v.includer(f,g.filename);if(u){if(u.filename)g.filename=u.filename;if(u.template)return U(g,u.template)}}return U(g)}function Af(f,v,g,u,r){var C=v.split(`
|
|
14
|
+
`),w=Math.max(u-3,0),j=Math.min(C.length,u+3),z=r(g),J=C.slice(w,j).map(function($,A){var b=A+w+1;return(b==u?" >> ":" ")+b+"| "+$}).join(`
|
|
15
|
+
`);throw f.path=z,f.message=(z||"ejs")+":"+u+`
|
|
16
16
|
`+J+`
|
|
17
17
|
|
|
18
|
-
`+f.message,f}function Qf(f){return f.replace(/;(\s*$)/,"$1")}bf.compile=function f(v,g){var
|
|
18
|
+
`+f.message,f}function Qf(f){return f.replace(/;(\s*$)/,"$1")}bf.compile=function f(v,g){var u;if(g&&g.scope){if(!Jf)console.warn("`scope` option is deprecated and will be removed in EJS 3"),Jf=!0;if(!g.context)g.context=g.scope;delete g.scope}return u=new Y(v,g),u.compile()};bf.render=function(f,v,g){var u=v||K.createNullProtoObjWherePossible(),r=g||K.createNullProtoObjWherePossible();if(arguments.length==2)K.shallowCopyFromList(r,u,Gf);return U(r,f)(u)};bf.renderFile=function(){var f=Array.prototype.slice.call(arguments),v=f.shift(),g,u={filename:v},r,C;if(typeof arguments[arguments.length-1]=="function")g=f.pop();if(f.length){if(r=f.shift(),f.length)K.shallowCopy(u,f.pop());else{if(r.settings){if(r.settings.views)u.views=r.settings.views;if(r.settings["view cache"])u.cache=!0;if(C=r.settings["view options"],C)K.shallowCopy(u,C)}K.shallowCopyFromList(u,r,r1)}u.filename=v}else r=K.createNullProtoObjWherePossible();return w1(u,r,g)};bf.Template=Y;bf.clearCache=function(){bf.cache.reset()};function Y(f,v){var g=K.hasOwnOnlyObject(v),u=K.createNullProtoObjWherePossible();if(this.templateText=f,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",u.client=g.client||!1,u.escapeFunction=g.escape||g.escapeFunction||K.escapeXML,u.compileDebug=g.compileDebug!==!1,u.debug=!!g.debug,u.filename=g.filename,u.openDelimiter=g.openDelimiter||bf.openDelimiter||pf,u.closeDelimiter=g.closeDelimiter||bf.closeDelimiter||f1,u.delimiter=g.delimiter||bf.delimiter||g1,u.strict=g.strict||!1,u.context=g.context,u.cache=g.cache||!1,u.rmWhitespace=g.rmWhitespace,u.root=g.root,u.includer=g.includer,u.outputFunctionName=g.outputFunctionName,u.localsName=g.localsName||bf.localsName||Vf,u.views=g.views,u.async=g.async,u.destructuredLocals=g.destructuredLocals,u.legacyInclude=typeof g.legacyInclude!="undefined"?!!g.legacyInclude:!0,u.strict)u._with=!1;else u._with=typeof g._with!="undefined"?g._with:!0;this.opts=u,this.regex=this.createRegex()}Y.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};Y.prototype={createRegex:function(){var f=u1,v=K.escapeRegExpChars(this.opts.delimiter),g=K.escapeRegExpChars(this.opts.openDelimiter),u=K.escapeRegExpChars(this.opts.closeDelimiter);return f=f.replace(/%/g,v).replace(/</g,g).replace(/>/g,u),new RegExp(f)},compile:function(){var f,v,g=this.opts,u="",r="",C=g.escapeFunction,w,j=g.filename?JSON.stringify(g.filename):"undefined";if(!this.source){if(this.generateSource(),u+=` var __output = "";
|
|
19
19
|
function __append(s) { if (s !== undefined && s !== null) __output += s }
|
|
20
|
-
`,g.outputFunctionName){if(!
|
|
21
|
-
`}if(g.localsName&&!
|
|
22
|
-
`;for(var J=0;J<g.destructuredLocals.length;J++){var $=g.destructuredLocals[J];if(!
|
|
23
|
-
`;z+=$+" = __locals."+$}
|
|
24
|
-
`}if(g._with!==!1)
|
|
25
|
-
`,
|
|
26
|
-
`;
|
|
27
|
-
`,this.source=
|
|
20
|
+
`,g.outputFunctionName){if(!O.test(g.outputFunctionName))throw new Error("outputFunctionName is not a valid JS identifier.");u+=" var "+g.outputFunctionName+` = __append;
|
|
21
|
+
`}if(g.localsName&&!O.test(g.localsName))throw new Error("localsName is not a valid JS identifier.");if(g.destructuredLocals&&g.destructuredLocals.length){var z=" var __locals = ("+g.localsName+` || {}),
|
|
22
|
+
`;for(var J=0;J<g.destructuredLocals.length;J++){var $=g.destructuredLocals[J];if(!O.test($))throw new Error("destructuredLocals["+J+"] is not a valid JS identifier.");if(J>0)z+=`,
|
|
23
|
+
`;z+=$+" = __locals."+$}u+=z+`;
|
|
24
|
+
`}if(g._with!==!1)u+=" with ("+g.localsName+` || {}) {
|
|
25
|
+
`,r+=` }
|
|
26
|
+
`;r+=` return __output;
|
|
27
|
+
`,this.source=u+this.source+r}if(g.compileDebug)f=`var __line = 1
|
|
28
28
|
, __lines = `+JSON.stringify(this.templateText)+`
|
|
29
29
|
, __filename = `+j+`;
|
|
30
30
|
try {
|
|
@@ -40,28 +40,28 @@ try {
|
|
|
40
40
|
|
|
41
41
|
`,Z.message+=`If the above error is not helpful, you may want to try EJS-Lint:
|
|
42
42
|
`,Z.message+="https://github.com/RyanZim/EJS-Lint",!g.async)Z.message+=`
|
|
43
|
-
`,Z.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw Z}var A=g.client?v:function Z(c){var
|
|
44
|
-
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var v=this,g=this.parseTemplateText(),
|
|
45
|
-
`},scanLine:function(f){var v=this,g=this.opts.delimiter,
|
|
46
|
-
`).length-1,f){case
|
|
47
|
-
`;break;case g+g+
|
|
48
|
-
`;break;case g+
|
|
43
|
+
`,Z.message+="Or, if you meant to create an async function, pass `async: true` as an option."}throw Z}var A=g.client?v:function Z(c){var B=function(Q,L){var M=K.shallowCopy(K.createNullProtoObjWherePossible(),c);if(L)M=K.shallowCopy(M,L);return j1(Q,g)(M)};return v.apply(g.context,[c||K.createNullProtoObjWherePossible(),C,B,Af])};if(g.filename&&typeof Object.defineProperty==="function"){var b=g.filename,V=X.basename(b,X.extname(b));try{Object.defineProperty(A,"name",{value:V,writable:!1,enumerable:!1,configurable:!0})}catch(Z){}}return A},generateSource:function(){var f=this.opts;if(f.rmWhitespace)this.templateText=this.templateText.replace(/[\r\n]+/g,`
|
|
44
|
+
`).replace(/^\s+|\s+$/gm,"");this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var v=this,g=this.parseTemplateText(),u=this.opts.delimiter,r=this.opts.openDelimiter,C=this.opts.closeDelimiter;if(g&&g.length)g.forEach(function(w,j){var z;if(w.indexOf(r+u)===0&&w.indexOf(r+u+u)!==0){if(z=g[j+2],!(z==u+C||z=="-"+u+C||z=="_"+u+C))throw new Error('Could not find matching close tag for "'+w+'".')}v.scanLine(w)})},parseTemplateText:function(){var f=this.templateText,v=this.regex,g=v.exec(f),u=[],r;while(g){if(r=g.index,r!==0)u.push(f.substring(0,r)),f=f.slice(r);u.push(g[0]),f=f.slice(g[0].length),g=v.exec(f)}if(f)u.push(f);return u},_addOutput:function(f){if(this.truncate)f=f.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1;if(!f)return f;f=f.replace(/\\/g,"\\\\"),f=f.replace(/\n/g,"\\n"),f=f.replace(/\r/g,"\\r"),f=f.replace(/"/g,"\\\""),this.source+=' ; __append("'+f+`")
|
|
45
|
+
`},scanLine:function(f){var v=this,g=this.opts.delimiter,u=this.opts.openDelimiter,r=this.opts.closeDelimiter,C=0;switch(C=f.split(`
|
|
46
|
+
`).length-1,f){case u+g:case u+g+"_":this.mode=Y.modes.EVAL;break;case u+g+"=":this.mode=Y.modes.ESCAPED;break;case u+g+"-":this.mode=Y.modes.RAW;break;case u+g+"#":this.mode=Y.modes.COMMENT;break;case u+g+g:this.mode=Y.modes.LITERAL,this.source+=' ; __append("'+f.replace(u+g+g,u+g)+`")
|
|
47
|
+
`;break;case g+g+r:this.mode=Y.modes.LITERAL,this.source+=' ; __append("'+f.replace(g+g+r,g+r)+`")
|
|
48
|
+
`;break;case g+r:case"-"+g+r:case"_"+g+r:if(this.mode==Y.modes.LITERAL)this._addOutput(f);this.mode=null,this.truncate=f.indexOf("-")===0||f.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Y.modes.EVAL:case Y.modes.ESCAPED:case Y.modes.RAW:if(f.lastIndexOf("//")>f.lastIndexOf(`
|
|
49
49
|
`))f+=`
|
|
50
50
|
`}switch(this.mode){case Y.modes.EVAL:this.source+=" ; "+f+`
|
|
51
51
|
`;break;case Y.modes.ESCAPED:this.source+=" ; __append(escapeFn("+Qf(f)+`))
|
|
52
52
|
`;break;case Y.modes.RAW:this.source+=" ; __append("+Qf(f)+`)
|
|
53
53
|
`;break;case Y.modes.COMMENT:break;case Y.modes.LITERAL:this._addOutput(f);break}}else this._addOutput(f)}if(v.opts.compileDebug&&C)this.currentLine+=C,this.source+=" ; __line = "+this.currentLine+`
|
|
54
|
-
`}};bf.escapeXML=K.escapeXML;bf.__express=bf.renderFile;bf.VERSION=of;bf.name=v1;if(typeof window!="undefined")window.ejs=bf});function F(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var x=null;async function V1(){if(!x){let f=await Promise.resolve().then(() =>
|
|
54
|
+
`}};bf.escapeXML=K.escapeXML;bf.__express=bf.renderFile;bf.VERSION=of;bf.name=v1;if(typeof window!="undefined")window.ejs=bf});function F(f){switch(f.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var x=null;async function V1(){if(!x){let f=await Promise.resolve().then(() => Mf(Uf(),1));x=f.default||f}return x}class _{req;server;path;routePattern;env;executionContext;headers=new Headers;parsedQuery=null;parsedParams=null;parsedCookies=null;parsedBody=null;contextData={};urlObject=null;constructor(f,v,g,u,r,C){this.req=f,this.server=v,this.path=g,this.routePattern=u,this.executionContext=C,this.env=r}setHeader(f,v){return this.headers.set(f,v),this}removeHeader(f){return this.headers.delete(f),this}set(f,v){return this.contextData[f]=v,this}get(f){return this.contextData[f]}get ip(){if(this.server)return this.server.requestIP(this.req)?.address??null;return this.req.headers.get("CF-Connecting-IP")||null}get url(){if(!this.urlObject)this.urlObject=new URL(this.req.url);return this.urlObject}get query(){if(!this.parsedQuery)this.parsedQuery=this.url.search?Object.fromEntries(this.url.searchParams):{};return this.parsedQuery}get params(){if(!this.parsedParams&&this.routePattern)try{this.parsedParams=b1(this.routePattern,this.path)}catch(f){let v=f instanceof Error?f.message:String(f);throw new Error(`Failed to extract route parameters: ${v}`)}return this.parsedParams??{}}get body(){if(this.req.method==="GET")return Promise.resolve({});if(!this.parsedBody)this.parsedBody=(async()=>{try{let f=await B1(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f}catch(f){throw new Error("Invalid request body format")}})();return this.parsedBody}text(f,v=200){return new Response(f,{status:v,headers:this.headers})}send(f,v=200){let g;if(f instanceof Uint8Array)g="Uint8Array";else if(f instanceof ArrayBuffer)g="ArrayBuffer";else g=typeof f;let u=g==="object"&&f!==null?JSON.stringify(f):f;return new Response(u,{status:v,headers:this.headers})}json(f,v=200){return Response.json(f,{status:v,headers:this.headers})}file(f,v,g=200){let u=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",v??F(f));return new Response(u,{status:g,headers:this.headers})}async ejs(f,v={},g=200){let u=await V1();try{let r=await Bun.file(f).text(),C=u.render(r,v),w=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(C,{status:g,headers:w})}catch(r){return console.error("EJS Rendering Error:",r),new Response("Error rendering template",{status:500})}}redirect(f,v=302){return this.headers.set("Location",f),new Response(null,{status:v,headers:this.headers})}setCookie(f,v,g={}){let u=`${encodeURIComponent(f)}=${encodeURIComponent(v)}`;if(g.maxAge)u+=`; Max-Age=${g.maxAge}`;if(g.expires)u+=`; Expires=${g.expires.toUTCString()}`;if(g.path)u+=`; Path=${g.path}`;if(g.domain)u+=`; Domain=${g.domain}`;if(g.secure)u+="; Secure";if(g.httpOnly)u+="; HttpOnly";if(g.sameSite)u+=`; SameSite=${g.sameSite}`;return this.headers.append("Set-Cookie",u),this}get cookies(){if(!this.parsedCookies){let f=this.req.headers.get("cookie");this.parsedCookies=f?G1(f):{}}return this.parsedCookies}stream(f){let v=new Headers(this.headers),g=new ReadableStream({async start(u){await f(u),u.close()}});return new Response(g,{headers:v})}yieldStream(f){return new Response}}function G1(f){return Object.fromEntries(f.split(";").map((v)=>{let[g,...u]=v.trim().split("=");return[g,decodeURIComponent(u.join("="))]}))}function b1(f,v){let g={},u=f.split("/"),[r]=v.split("?"),C=r.split("/");if(u.length!==C.length)return null;for(let w=0;w<u.length;w++){let j=u[w];if(j.charCodeAt(0)===58)g[j.slice(1)]=C[w]}return g}async function B1(f){let v=f.headers.get("Content-Type")||"";if(!v)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};if(v.startsWith("application/json"))return await f.json();if(v.startsWith("application/x-www-form-urlencoded")){let u=await f.text();return Object.fromEntries(new URLSearchParams(u))}if(v.startsWith("multipart/form-data")){let u=await f.formData(),r={};for(let[C,w]of u.entries())r[C]=w;return r}return{error:"Unknown request body type"}}async function Ff(f,v,g){if(!v?.length)return;for(let u=0;u<v.length;u++){let r=v[u](...g),C=r instanceof Promise?await r:r;if(C&&f!=="onRequest")return C}}async function O1(f,v,g){let u=f.globalMiddlewares;if(u.length)for(let C of u){let w=await C(g);if(w)return w}let r=f.middlewares.get(v);if(r&&r.length)for(let C of r){let w=await C(g);if(w)return w}return null}async function qf(f,v,g){for(let u of f){let r=await u(v,g);if(r)return r}}async function Df(f,v,g){let u=await W1(f,v,g),r=u instanceof Promise?await u:u;if(r)return r}async function W1(f,v,g){if(v.endsWith("/"))v=v.slice(0,-1);if(!f.filters.has(v))if(f.filterFunction.length)for(let u of f.filterFunction){let r=await u(g);if(r)return r}else return Response.json({error:"Protected route, authentication required"},{status:401})}async function Nf(f,v,g){if(f.staticPath){let r=!0;if(f.staticRequestPath)r=g.startsWith(f.staticRequestPath);if(r){let C=await X1(f,g,v);if(C)return C;let w=f.trie.search("*",v.req.method);if(w?.handler)return await w.handler(v)}}let u=f.routeNotFoundFunc(v);return u instanceof Promise?await u:u||T(404,`404 Route not found for ${g}`)}function T(f,v){return new Response(JSON.stringify({error:v}),{status:f,headers:{"Content-Type":"application/json"}})}async function X1(f,v,g){if(!f.staticPath)return null;let u=`${f.staticPath}${v}`;if(await Bun.file(u).exists()){let C=F(u);return g.file(u,C,200)}return null}var R=(f)=>f.constructor.name==="AsyncFunction",k=(f,v,g,...u)=>{if(v.length>5)f.push(`
|
|
55
55
|
for (let i = 0; i < diesel.hooks.${g}.length; i++) {
|
|
56
|
-
const result = diesel.hooks.${g}[i](${
|
|
56
|
+
const result = diesel.hooks.${g}[i](${u});
|
|
57
57
|
const finalResult = result instanceof Promise ? await result : result;
|
|
58
58
|
if (finalResult && '${g}' !== 'onRequest') return finalResult
|
|
59
59
|
}
|
|
60
|
-
`);else v?.forEach((
|
|
61
|
-
const ${g}${C}Result = await diesel.hooks.${g}[${C}](${
|
|
60
|
+
`);else v?.forEach((r,C)=>{if(R(r))f.push(`
|
|
61
|
+
const ${g}${C}Result = await diesel.hooks.${g}[${C}](${u})
|
|
62
62
|
if (${g}${C}Result && '${g}' !== 'onRequest') return ${g}${C}Result
|
|
63
63
|
`);else f.push(`
|
|
64
|
-
const ${g}${C}Result = diesel.hooks.${g}[${C}](${
|
|
64
|
+
const ${g}${C}Result = diesel.hooks.${g}[${C}](${u})
|
|
65
65
|
if (${g}${C}Result && '${g}' !== 'onRequest') return ${g}${C}Result
|
|
66
66
|
`)})},U1=(f)=>{f.push(`
|
|
67
67
|
let pathname;
|
|
@@ -92,11 +92,11 @@ try {
|
|
|
92
92
|
const result = await globalMiddlewares[i](ctx);
|
|
93
93
|
if (result) return result;
|
|
94
94
|
}
|
|
95
|
-
`)},_1=(f,v)=>{let g=[],
|
|
95
|
+
`)},_1=(f,v)=>{let g=[],u=v.globalMiddlewares||[],r=f?.hasOnReqHook?v.hooks.onRequest:[],C=f?.hasPreHandlerHook?v.hooks.preHandler:[],w=f?.hasOnSendHook?v.hooks.onSend:[];if(U1(g),g.push(`
|
|
96
96
|
const routeHandler = diesel.trie.search(pathname, req.method);
|
|
97
|
-
`),
|
|
97
|
+
`),r&&r.length>0)k(g,r,"onRequest","req","pathname","server");if(g.push(`
|
|
98
98
|
const ctx = new Context(req, server, pathname, routeHandler?.path)
|
|
99
|
-
`),f?.hasMiddleware){if(
|
|
99
|
+
`),f?.hasMiddleware){if(u.length>0)F1(g,u);if(v.middlewares.size>0)g.push(`
|
|
100
100
|
const local = diesel.middlewares.get(pathname)
|
|
101
101
|
if (local && local.length) {
|
|
102
102
|
for (const middleware of local) {
|
|
@@ -120,11 +120,11 @@ try {
|
|
|
120
120
|
${g.join(`
|
|
121
121
|
`)}
|
|
122
122
|
}
|
|
123
|
-
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",j)(Df,Nf,T,
|
|
123
|
+
`;return new Function("runFilter","handleRouteNotFound","generateErrorResponse","globalMiddlewares","Context",j)(Df,Nf,T,u,_)},T1=(f,v,g,u,...r)=>{let C=[],w;if(typeof r[0]==="string"||typeof r[0]==="object")w=r[0];let j=r,z=f?.hasMiddleware?v.globalMiddlewares:[],J=f?.hasMiddleware?v.middlewares.get(u)||[]:[],$=[...z,...J],A=f?.hasOnReqHook?v.hooks.onRequest:[],b=v.filters.has(u),V=v.filterFunction;if(A&&A?.length>0)C.push(`
|
|
124
124
|
const onRequestResult = await runHooks(
|
|
125
125
|
"onRequest",
|
|
126
126
|
onRequestHooks,
|
|
127
|
-
[req, "${
|
|
127
|
+
[req, "${u}", server]
|
|
128
128
|
);
|
|
129
129
|
if (onRequestResult) return onRequestResult;
|
|
130
130
|
`);if($.length)C.push(`
|
|
@@ -146,17 +146,17 @@ try {
|
|
|
146
146
|
return new Response("Method Not Allowed", { status: 405 });
|
|
147
147
|
`),typeof w!=="undefined")if(typeof w==="string")C.push(`
|
|
148
148
|
return new Response(${JSON.stringify(w)});
|
|
149
|
-
`);else{let
|
|
150
|
-
return new Response(${JSON.stringify(
|
|
149
|
+
`);else{let B=JSON.stringify(w);C.push(`
|
|
150
|
+
return new Response(${JSON.stringify(B)}, {
|
|
151
151
|
headers: { "content-type": "application/json; charset=utf-8" }
|
|
152
152
|
});
|
|
153
|
-
`)}else if(j.length===1){let
|
|
153
|
+
`)}else if(j.length===1){let B=j[0];if(R(B))C.push(`
|
|
154
154
|
const response = await handlers[0](req, server);
|
|
155
155
|
if (response instanceof Response) return response;
|
|
156
156
|
`);else C.push(`
|
|
157
157
|
const response = handlers[0](req, server);
|
|
158
158
|
if (response instanceof Response) return response;
|
|
159
|
-
`)}else j.forEach((
|
|
159
|
+
`)}else j.forEach((B,Q)=>{if(R(B))C.push(`
|
|
160
160
|
const response${Q} = await handlers[${Q}](req, server);
|
|
161
161
|
if (response${Q} instanceof Response) return response${Q};
|
|
162
162
|
`);else C.push(`
|
package/dist/types.d.ts
CHANGED
|
@@ -31,7 +31,7 @@ export interface ContextType {
|
|
|
31
31
|
path?: string | undefined;
|
|
32
32
|
routePattern?: string | undefined;
|
|
33
33
|
env?: Record<string, any>;
|
|
34
|
-
|
|
34
|
+
executionContext?: any | undefined;
|
|
35
35
|
headers: Headers;
|
|
36
36
|
setHeader: (key: string, value: string) => this;
|
|
37
37
|
json: (data: object, status?: number) => Response;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "diesel-core",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.8",
|
|
4
4
|
"description": "Web framework built on Web Standards",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -107,4 +107,4 @@
|
|
|
107
107
|
"ejs": "^3.1.10",
|
|
108
108
|
"uuid": "^11.1.0"
|
|
109
109
|
}
|
|
110
|
-
}
|
|
110
|
+
}
|