@zuplo/core 6.2.18 → 6.2.21

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.
@@ -707,7 +707,7 @@ export default {
707
707
  `),pluginName:qO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}),{warnings:Sr,errors:[]}}catch(b){s.error(b);let k={message:`Error validating tsconfig.json : ${b.message}`,severity:"error",pluginName:qO};return{warnings:[],errors:[k]}}})},"validateTSConfig");import{parse as U_r}from"@swc/core";import B_r from"vm";var{hasOwnProperty:nb}=Object.prototype;function zO(a,s){return a=a.slice(),a.push(s),a}t(zO,"push");function V4e(a,s){return s=s.slice(),s.unshift(a),s}t(V4e,"unshift");var W4e=class extends Error{static{t(this,"NewError")}constructor(s){super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'),this.avoidNew=!0,this.value=s,this.name="NewError"}};function s_(a,s,u,p,y){if(!(this instanceof s_))try{return new s_(a,s,u,p,y)}catch(k){if(!k.avoidNew)throw k;return k.value}typeof a=="string"&&(y=p,p=u,u=s,s=a,a=null);let b=a&&typeof a=="object";if(a=a||{},this.json=a.json||u,this.path=a.path||s,this.resultType=a.resultType||"value",this.flatten=a.flatten||!1,this.wrap=nb.call(a,"wrap")?a.wrap:!0,this.sandbox=a.sandbox||{},this.preventEval=a.preventEval||!1,this.parent=a.parent||null,this.parentProperty=a.parentProperty||null,this.callback=a.callback||p||null,this.otherTypeCallback=a.otherTypeCallback||y||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},a.autostart!==!1){let k={path:b?a.path:s};b?"json"in a&&(k.json=a.json):k.json=u;let A=this.evaluate(k);if(!A||typeof A!="object")throw new W4e(A);return A}}t(s_,"JSONPath");s_.prototype.evaluate=function(a,s,u,p){let y=this.parent,b=this.parentProperty,{flatten:k,wrap:A}=this;if(this.currResultType=this.resultType,this.currPreventEval=this.preventEval,this.currSandbox=this.sandbox,u=u||this.callback,this.currOtherTypeCallback=p||this.otherTypeCallback,s=s||this.json,a=a||this.path,a&&typeof a=="object"&&!Array.isArray(a)){if(!a.path&&a.path!=="")throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!nb.call(a,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');({json:s}=a),k=nb.call(a,"flatten")?a.flatten:k,this.currResultType=nb.call(a,"resultType")?a.resultType:this.currResultType,this.currSandbox=nb.call(a,"sandbox")?a.sandbox:this.currSandbox,A=nb.call(a,"wrap")?a.wrap:A,this.currPreventEval=nb.call(a,"preventEval")?a.preventEval:this.currPreventEval,u=nb.call(a,"callback")?a.callback:u,this.currOtherTypeCallback=nb.call(a,"otherTypeCallback")?a.otherTypeCallback:this.currOtherTypeCallback,y=nb.call(a,"parent")?a.parent:y,b=nb.call(a,"parentProperty")?a.parentProperty:b,a=a.path}if(y=y||null,b=b||null,Array.isArray(a)&&(a=s_.toPathString(a)),!a&&a!==""||!s)return;let M=s_.toPathArray(a);M[0]==="$"&&M.length>1&&M.shift(),this._hasParentSelector=null;let U=this._trace(M,s,["$"],y,b,u).filter(function(re){return re&&!re.isParentSelector});return U.length?!A&&U.length===1&&!U[0].hasArrExpr?this._getPreferredOutput(U[0]):U.reduce((re,Z)=>{let H=this._getPreferredOutput(Z);return k&&Array.isArray(H)?re=re.concat(H):re.push(H),re},[]):A?[]:void 0};s_.prototype._getPreferredOutput=function(a){let s=this.currResultType;switch(s){case"all":{let u=Array.isArray(a.path)?a.path:s_.toPathArray(a.path);return a.pointer=s_.toPointer(u),a.path=typeof a.path=="string"?a.path:s_.toPathString(a.path),a}case"value":case"parent":case"parentProperty":return a[s];case"path":return s_.toPathString(a[s]);case"pointer":return s_.toPointer(a.path);default:throw new TypeError("Unknown result type")}};s_.prototype._handleCallback=function(a,s,u){if(s){let p=this._getPreferredOutput(a);a.path=typeof a.path=="string"?a.path:s_.toPathString(a.path),s(p,u,a)}};s_.prototype._trace=function(a,s,u,p,y,b,k,A){let M;if(!a.length)return M={path:u,value:s,parent:p,parentProperty:y,hasArrExpr:k},this._handleCallback(M,b,"value"),M;let U=a[0],re=a.slice(1),Z=[];function H(Te){Array.isArray(Te)?Te.forEach(ge=>{Z.push(ge)}):Z.push(Te)}if(t(H,"addRet"),(typeof U!="string"||A)&&s&&nb.call(s,U))H(this._trace(re,s[U],zO(u,U),s,U,b,k));else if(U==="*")this._walk(s,Te=>{H(this._trace(re,s[Te],zO(u,Te),s,Te,b,!0,!0))});else if(U==="..")H(this._trace(re,s,u,p,y,b,k)),this._walk(s,Te=>{typeof s[Te]=="object"&&H(this._trace(a.slice(),s[Te],zO(u,Te),s,Te,b,!0))});else{if(U==="^")return this._hasParentSelector=!0,{path:u.slice(0,-1),expr:re,isParentSelector:!0};if(U==="~")return M={path:zO(u,U),value:y,parent:p,parentProperty:null},this._handleCallback(M,b,"property"),M;if(U==="$")H(this._trace(re,s,u,null,null,b,k));else if(/^(-?\d*):(-?\d*):?(\d*)$/u.test(U))H(this._slice(U,re,s,u,p,y,b));else if(U.indexOf("?(")===0){if(this.currPreventEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");let Te=U.replace(/^\?\((.*?)\)$/u,"$1");this._walk(s,ge=>{this._eval(Te,s[ge],ge,u,p,y)&&H(this._trace(re,s[ge],zO(u,ge),s,ge,b,!0))})}else if(U[0]==="("){if(this.currPreventEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");H(this._trace(V4e(this._eval(U,s,u[u.length-1],u.slice(0,-1),p,y),re),s,u,p,y,b,k))}else if(U[0]==="@"){let Te=!1,ge=U.slice(1,-2);switch(ge){case"scalar":(!s||!["object","function"].includes(typeof s))&&(Te=!0);break;case"boolean":case"string":case"undefined":case"function":typeof s===ge&&(Te=!0);break;case"integer":Number.isFinite(s)&&!(s%1)&&(Te=!0);break;case"number":Number.isFinite(s)&&(Te=!0);break;case"nonFinite":typeof s=="number"&&!Number.isFinite(s)&&(Te=!0);break;case"object":s&&typeof s===ge&&(Te=!0);break;case"array":Array.isArray(s)&&(Te=!0);break;case"other":Te=this.currOtherTypeCallback(s,u,p,y);break;case"null":s===null&&(Te=!0);break;default:throw new TypeError("Unknown value type "+ge)}if(Te)return M={path:u,value:s,parent:p,parentProperty:y},this._handleCallback(M,b,"value"),M}else if(U[0]==="`"&&s&&nb.call(s,U.slice(1))){let Te=U.slice(1);H(this._trace(re,s[Te],zO(u,Te),s,Te,b,k,!0))}else if(U.includes(",")){let Te=U.split(",");for(let ge of Te)H(this._trace(V4e(ge,re),s,u,p,y,b,!0))}else!A&&s&&nb.call(s,U)&&H(this._trace(re,s[U],zO(u,U),s,U,b,k,!0))}if(this._hasParentSelector)for(let Te=0;Te<Z.length;Te++){let ge=Z[Te];if(ge&&ge.isParentSelector){let ve=this._trace(ge.expr,s,ge.path,p,y,b,k);if(Array.isArray(ve)){Z[Te]=ve[0];let dt=ve.length;for(let _t=1;_t<dt;_t++)Te++,Z.splice(Te,0,ve[_t])}else Z[Te]=ve}}return Z};s_.prototype._walk=function(a,s){if(Array.isArray(a)){let u=a.length;for(let p=0;p<u;p++)s(p)}else a&&typeof a=="object"&&Object.keys(a).forEach(u=>{s(u)})};s_.prototype._slice=function(a,s,u,p,y,b,k){if(!Array.isArray(u))return;let A=u.length,M=a.split(":"),U=M[2]&&Number.parseInt(M[2])||1,re=M[0]&&Number.parseInt(M[0])||0,Z=M[1]&&Number.parseInt(M[1])||A;re=re<0?Math.max(0,re+A):Math.min(A,re),Z=Z<0?Math.max(0,Z+A):Math.min(A,Z);let H=[];for(let Te=re;Te<Z;Te+=U)this._trace(V4e(Te,s),u,p,y,b,k,!0).forEach(ve=>{H.push(ve)});return H};s_.prototype._eval=function(a,s,u,p,y,b){this.currSandbox._$_parentProperty=b,this.currSandbox._$_parent=y,this.currSandbox._$_property=u,this.currSandbox._$_root=this.json,this.currSandbox._$_v=s;let k=a.includes("@path");k&&(this.currSandbox._$_path=s_.toPathString(p.concat([u])));let A="script:"+a;if(!s_.cache[A]){let M=a.replace(/@parentProperty/gu,"_$_parentProperty").replace(/@parent/gu,"_$_parent").replace(/@property/gu,"_$_property").replace(/@root/gu,"_$_root").replace(/@([.\s)[])/gu,"_$_v$1");k&&(M=M.replace(/@path/gu,"_$_path")),s_.cache[A]=new this.vm.Script(M)}try{return s_.cache[A].runInNewContext(this.currSandbox)}catch(M){throw new Error("jsonPath: "+M.message+": "+a)}};s_.cache={};s_.toPathString=function(a){let s=a,u=s.length,p="$";for(let y=1;y<u;y++)/^(~|\^|@.*?\(\))$/u.test(s[y])||(p+=/^[0-9*]+$/u.test(s[y])?"["+s[y]+"]":"['"+s[y]+"']");return p};s_.toPointer=function(a){let s=a,u=s.length,p="";for(let y=1;y<u;y++)/^(~|\^|@.*?\(\))$/u.test(s[y])||(p+="/"+s[y].toString().replace(/~/gu,"~0").replace(/\//gu,"~1"));return p};s_.toPathArray=function(a){let{cache:s}=s_;if(s[a])return s[a].concat();let u=[],y=a.replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu,";$&;").replace(/[['](\??\(.*?\))[\]']/gu,function(b,k){return"[#"+(u.push(k)-1)+"]"}).replace(/\[['"]([^'\]]*)['"]\]/gu,function(b,k){return"['"+k.replace(/\./gu,"%@%").replace(/~/gu,"%%@@%%")+"']"}).replace(/~/gu,";~;").replace(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu,";").replace(/%@%/gu,".").replace(/%%@@%%/gu,"~").replace(/(?:;)?(\^+)(?:;)?/gu,function(b,k){return";"+k.split("").join(";")+";"}).replace(/;;;|;;/gu,";..;").replace(/;$|'?\]|'$/gu,"").split(";").map(function(b){let k=b.match(/#(\d+)/u);return!k||!k[1]?b:u[k[1]]});return s[a]=y,s[a].concat()};s_.prototype.vm=B_r;import $_r from"fs/promises";import J_r from"path";var ndt=t(async function({outputDirectory:a,logger:s}){return hf.timeFn("Verify Worker output",async()=>{s.debug("Verify Worker output");let u=J_r.join(a,"worker.js");try{if(await Mc.fileExists(u)){let p=await $_r.readFile(u,"utf-8"),y=await U_r(p,{syntax:"ecmascript"}),b=s_({path:"$..callee[?(@property === 'value' && (@ === 'Function'|| @ === 'eval'))]^",json:y.body});if(b&&b.length>0)return{warnings:[{message:"We do not support the use of 'eval' or 'new Function(...)'",severity:"warning",pluginName:"verify-worker-output"}],errors:[]}}}catch(p){s.error(p);let y={message:`Error validating build output : ${p.message}`,severity:"error",pluginName:"verify-worker-output"};return{warnings:[],errors:[y]}}return{warnings:[],errors:[]}})},"verifyWorkerOutput");import*as o2t from"esbuild";import{randomUUID as q_r}from"crypto";var VO=class{static{t(this,"CompilerResult")}buildId;buildTime;buildTimeMs;errors;warnings;status;assets;metafile;constructor(s,u){this.buildId=u?.buildId??q_r(),this.buildTime=u?.startBuildTime.toISOString(),this.buildTimeMs=u?.endBuildTime.getTime()-u?.startBuildTime.getTime(),this.errors=s.errors.map(p=>({message:p.text,severity:iH,...p})),this.warnings=s.warnings.map(p=>({message:p.text,severity:sH,...p})),s.metafile&&(this.metafile=s.metafile),this.status=AO,this.warnings&&this.warnings.length>0&&(this.status=pM),this.errors&&this.errors.length>0&&(this.status=eb)}};var z_r=!1;function BM(a,s){return{open:`\x1B[${a.join(";")}m`,close:`\x1B[${s}m`,regexp:new RegExp(`\\x1b\\[${s}m`,"g")}}t(BM,"code");function UM(a,s){return z_r?`${s.open}${a.replace(s.regexp,s.open)}${s.close}`:a}t(UM,"run");function V_r(a){return UM(a,BM([31],39))}t(V_r,"red");function W_r(a){return UM(a,BM([32],39))}t(W_r,"green");function H_r(a){return UM(a,BM([33],39))}t(H_r,"yellow");function G_r(a){return UM(a,BM([34],39))}t(G_r,"blue");function K_r(a){return UM(a,BM([35],39))}t(K_r,"magenta");function Y_r(a){return UM(a,BM([36],39))}t(Y_r,"cyan");var q5r=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var idt=[V_r,W_r,H_r,G_r,K_r,Y_r];function X_r(a){let s=0,u=a.length,p=0;if(u>0)for(;p<u;)s=(s<<5)-s+a.charCodeAt(p++)|0;return s}t(X_r,"hashCode");function sdt(a){let s=Math.abs(X_r(a));return idt[s%idt.length]}t(sdt,"generateColor");import{inspect as Q_r}from"util";function adt(a,s,...u){let p=0,y=u.length,b=String(s).replace(/%[sdjoO%]/g,k=>{if(k==="%%")return"%";if(p>=y)return k;switch(k){case"%s":return String(u[p++]);case"%d":return Number(u[p++]).toString();case"%o":return a(u[p++]).split(`
708
708
  `).map(A=>A.trim()).join(" ");case"%O":return a(u[p++]);case"%j":try{return JSON.stringify(u[p++])}catch{return"[Circular]"}default:return k}});for(let k of u.splice(p))k===null||!(typeof k=="object"&&k!==null)?b+=" "+k:b+=" "+a(k);return b}t(adt,"format");var odt=t((a,...s)=>adt(Q_r,a,s),"format");var H4e=class{static{t(this,"Debugger")}manager;ns;color;last;enabled;constructor(s,u){this.manager=s,this.ns=u,this.color=sdt(u),this.last=0,this.enabled=s.enabled.some(p=>p.test(u))}log(...s){if(!this.enabled)return;let u,p=s[0];typeof p=="function"?u=p():u=String(p);let y=Date.now()-(this.last||Date.now());u=odt(u,...s);let b=`${this.color(this.ns)} ${u} ${this.color(`+${y}ms`)}`;console.log(b),this.last=Date.now()}},G4e=class{static{t(this,"DebugManager")}debuggers;enabled;constructor(s){this.debuggers=new Map,this.enabled=s??[]}};function Z_r(a){return!a||a.length===0?[]:(a=a.replace(/\s/g,"").replace(/\*/g,".+"),a.split(",").map(s=>new RegExp(`^${s}$`)))}t(Z_r,"extract");var hue;function cdt(a){hue||(hue=new G4e(Z_r(process.env.DEBUG)));let s=new H4e(hue,a);return hue.debuggers.set(a,s),Object.assign(s.log.bind(s),{self:s})}t(cdt,"debug");import W_e,{dirname as i2t}from"path";import{fileURLToPath as s2t}from"url";var K4e="no-remote-module";function ldt({logger:a}){return{name:K4e,async setup(s){s.onResolve({filter:/^https?:\/\//},u=>(a.error(u,"User attempted to load a remote module"),{errors:[{text:`Remote modules are not supported. Attempted to load module ${u.path}`,detail:"InvalidRemoteModule",pluginName:K4e,location:{line:0,column:0,file:""}}],pluginName:K4e}))}}}t(ldt,"blockRemoteModulePlugin");import udt from"fs/promises";import gue from"path";import epr from"prettier";var fdt="/docs",tpr="/__zuplo/dev-portal";function rpr(a){let s=a.trim().toLowerCase();return s.endsWith("/")&&(s=s.slice(0,-1)),s}t(rpr,"normalizePathname");function npr(a){let s={sitePathname:a?.sitePathname===tpr?fdt:a?.sitePathname?rpr(a.sitePathname):fdt,enabled:a?a.enabled??!0:!1};return`const devPortal = ${JSON.stringify(s)};
709
709
  export default devPortal;`}t(npr,"generateSource");function _dt(a){return{name:"dev-portal-config",setup(s){s.onResolve({filter:/dev-portal.json$/},u=>({namespace:"dev-portal-json",path:gue.isAbsolute(u.path)?u.path:gue.join(u.resolveDir,u.path),pluginName:"dev-portal"})),s.onLoad({filter:/.*/,namespace:"dev-portal-json"},async u=>hf.timeFn("Generating dev-portal.json data",async()=>{let p,y,b=[];if(await Mc.fileExists(u.path)){y=await udt.readFile(u.path,"utf-8");try{p=JSON.parse(y)}catch{b.push({id:"dev-portal-build-error",text:"Could not parse dev-portal.json. Ensure that the file is valid JSON.",location:{file:"dev-portal.json",namespace:"dev-portal-json",line:1,column:0,length:0,lineText:"",suggestion:""},detail:"DevPortalValidationError",pluginName:"dev-portal",notes:[{text:"Could not parse dev-portal.json. Ensure that the file is valid JSON.",location:null}]})}}if(b&&b.length>0)throw b;let k;try{if(k=npr(p),zg.DEBUG_BUILD_MODE&&k&&await Mc.dirExists(a.sourceDirectory)){let A=await epr.format(k,{parser:"babel"});await udt.writeFile(gue.join(a.sourceDirectory,GN,"dev-portal.js"),A)}if(b&&b.length>0)throw b}catch(A){A.length>0?A.forEach(M=>{let U={id:"dev-portal-build-error",text:M.message,location:{file:"dev-portal.json",namespace:"dev-portal-json",line:1,column:0,length:0,lineText:"issue",suggestion:""},detail:"DevPortalValidationError",pluginName:"dev-portal",notes:[{text:M.message,location:null}]};b.push(U)}):b.push({id:"dev-portal-build-error",text:A.message,location:{file:"dev-portal.json",namespace:"dev-portal-json",line:1,column:0,length:0,lineText:"issue",suggestion:""},detail:"DevPortalValidationError",pluginName:"dev-portal",notes:[{text:A.message,location:null}]})}return{contents:k,errors:b,pluginName:"dev-portal",loader:"js",resolveDir:gue.dirname(u.path),watchFiles:[u.path]}}))}}}t(_dt,"devPortalConfigPlugin");import pdt from"path";var ddt="legacy-environment",mdt="legacy-environment",ipr=`import { environment } from "@zuplo/runtime";
710
- export default environment;`;function hdt(a){return{name:"environment",setup(s){s.onResolve({filter:/@app\/environment$/},()=>({namespace:mdt,pluginName:ddt,path:pdt.join(a.sourceDirectory,GN,"environment.js")})),s.onLoad({filter:/.*/,namespace:mdt},async u=>({contents:ipr,loader:"ts",resolveDir:pdt.dirname(u.path),pluginName:ddt}))}}}t(hdt,"environmentPlugin");var Agt=Pd(B3e(),1),Ngt=Pd(Xht(),1),Igt=Pd(u8e(),1),Ogt=Pd(f8e(),1);import Pgt from"fs/promises";import $S from"path";import i1r from"prettier";var nw="schemas",efe="json-schema";function Fgt(a){return{name:nw,async setup(s){let u=new Igt.Ajv2020({code:{source:!0},allErrors:!0,strict:!1,verbose:!0,meta:!0});(0,Ngt.default)(u,{mode:"fast"}),u.opts.code.formats=Agt._`require("ajv-formats/dist/formats").fastFormats`;let p=$S.join(a.sourceDirectory,hM),y,b=[],k=[];if(await Mc.dirExists(p)&&(u.addKeyword("faker"),y=await Mc.listFolderContents(p,hM),await Promise.all(y.map(async A=>{try{let M=Mc.safePath(a.sourceDirectory).resolve(p,A);if(!M.startsWith(p))throw new Error("All schemas must be in the schemas directory");let U=await Pgt.readFile(M,"utf-8");if(U===""||U===void 0)throw new Error(`Schema 'schemas/${A}' is empty and will be ignored.`);let re=JSON.parse(U);if(re.$schema&&re.$schema!=="https://json-schema.org/draft/2020-12/schema")throw new Error(`Error in ${A}: All JSON schemas must use version 2020-12. See release notes for changes: https://json-schema.org/draft/2020-12/release-notes.html`);if(u.$dataMetaSchema,u.addSchema(re,A),u.errors?.length){let Z=u.errors[0];b.push({id:"json-schema-validation-error",pluginName:nw,text:`Error: ${Z.message}`,location:{file:$S.join(hM,A)},detail:{params:Z.params,propertyName:Z.propertyName,schemaPath:Z.schemaPath,data:Z.data}})}}catch(M){if(M.message.endsWith("is empty and will be ignored.")){k.push({id:"empty-json-schema-file",pluginName:nw,text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."},detail:"EmptyJSONSchemaFile",notes:[{text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."}}]});return}let U=await d4e(A,a.sourceDirectory,M.message);b.push({id:"json-schema-add-error",pluginName:nw,text:`Error: ${M.message}`,location:U,detail:"InvalidAddSchemaError",notes:[{text:M.message}]})}})),await Promise.all(y.map(async A=>{try{let M=u.getSchema(A);M&&u.compile(M.schema).errors?.forEach(re=>{b.push({text:`Failed to compile ${A}: ${re.message}`})})}catch(M){let U=await d4e(A,a.sourceDirectory,M.message);b.push({id:"json-schema-compile-error",pluginName:nw,text:`The schema file '${A}' is not valid. Error: ${M.message}`,location:U,detail:"InvalidSchemaError",notes:[{text:M.message}]})}})),zg.DEBUG_BUILD_MODE)){let A=$S.resolve(a.outputDirectory,hM);await Mc.mkdirIfNotExists(A)}s.onStart(async()=>{if(y)return{errors:b,warnings:k}}),s.onResolve({filter:/schemas\/.*\.json$/},async A=>{let M=$S.isAbsolute(A.path)?A.path:$S.join(A.resolveDir,A.path);if(A.importer&&A.importer!==$S.join(a.sourceDirectory,"config/routes.json"))return{path:M};if(!await Mc.fileExists(M)){let U="policies.json";return{errors:[{id:"json-schema-build-error",text:`Unable to resolve reference to '${A.path}' from ${U}`,location:{file:$S.join(A.resolveDir,U),namespace:efe,line:1,column:0,length:0,lineText:`Invalid JSON schema reference in ${U}`,suggestion:""},detail:"RouteReferenceError",pluginName:nw,notes:[{text:`Unable to resolve reference to '${A.path}' from ${U}`,location:null}]}],namespace:efe,path:M,pluginName:nw}}return{path:M,namespace:efe,pluginName:nw}}),s.onLoad({filter:/.*/,namespace:efe},async A=>hf.timeFn(`Generating json schema data: ${$S.basename(A.path)}`,async()=>{let M=[],U;try{let re=$S.relative(p,A.path),Z=u.getSchema(re);if(!Z)throw new Error(`Could not load schema at ${A.path}`);U=Z.source?.validateCode;let H=u.compile(Z.schema);U=(0,Ogt.default)(u,H)}catch(re){M.push({pluginName:nw,text:`Cannot parse project's schemas/${$S.basename(A.path)} file. Error: ${re.message}`,location:null,notes:[{text:re.message,location:null}],detail:re})}if(zg.DEBUG_BUILD_MODE&&U){let re=$S.resolve(a.outputDirectory,hM),Z=$S.relative(p,A.path),H=await i1r.format(U,{parser:"babel"}),Te=Mc.safePath(a.sourceDirectory).resolve(re,`${Z}.js`);await Mc.mkdirForFilePathIfNotExits(Te),await Pgt.writeFile(Te,H,"utf-8")}return{contents:U,errors:M,pluginName:nw,resolveDir:$S.dirname(A.path),watchFiles:[A.path]}}))}}}t(Fgt,"jsonSchemaPlugin");import{relative as s1r,resolve as a1r}from"path";import{dirname as o1r}from"path";import{fileURLToPath as c1r}from"url";var Lgt=["node:assert","node:async_hooks","node:buffer","node:crypto","node:diagnostics_channel","node:events","node:path","node:process","node:stream","node:string_decoder","node:util"],l1r="nodejs-compat-plugin";function Rgt({nodeCompatEnabled:a,sourceDirectory:s}){return{name:l1r,setup(u){let p=new Set;u.onStart(()=>{p.clear()}),u.onResolve({filter:/node:.*/},async({path:y,kind:b,resolveDir:k,...A})=>{let M=`${y}:${b}:${k}:${A.importer}`;if(p.has(M))return;if(p.add(M),!a&&y==="node:async_hooks")return{path:a1r(o1r(c1r(import.meta.url)),"../../../polyfills/async_hooks.js")};let U=await u.resolve(y,{kind:b,resolveDir:k,importer:A.importer});return U.errors.length>0?a&&Lgt.includes(y)||y.includes("/")&&Lgt.includes(y.split("/")[0])?{external:!0}:{external:!0,warnings:U.errors.map(Z=>({...Z,location:{file:s1r(s,A.importer),line:0,column:0,namespace:"",length:0,lineText:"",suggestion:"Remove the imported node module"},detail:`The package "${y}" wasn't found on the file system but is built into node. If this code is executed it will fail.`}))}:U})}}}t(Rgt,"nodejsCompatPlugin");function u1r(a){if(a.length>=255)throw new TypeError("Alphabet too long");let s=new Uint8Array(256);for(let U=0;U<s.length;U++)s[U]=255;for(let U=0;U<a.length;U++){let re=a.charAt(U),Z=re.charCodeAt(0);if(s[Z]!==255)throw new TypeError(re+" is ambiguous");s[Z]=U}let u=a.length,p=a.charAt(0),y=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function k(U){if(U instanceof Uint8Array||(ArrayBuffer.isView(U)?U=new Uint8Array(U.buffer,U.byteOffset,U.byteLength):Array.isArray(U)&&(U=Uint8Array.from(U))),!(U instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(U.length===0)return"";let re=0,Z=0,H=0,Te=U.length;for(;H!==Te&&U[H]===0;)H++,re++;let ge=(Te-H)*b+1>>>0,ve=new Uint8Array(ge);for(;H!==Te;){let Vt=U[H],hr=0;for(let Sr=ge-1;(Vt!==0||hr<Z)&&Sr!==-1;Sr--,hr++)Vt+=256*ve[Sr]>>>0,ve[Sr]=Vt%u>>>0,Vt=Vt/u>>>0;if(Vt!==0)throw new Error("Non-zero carry");Z=hr,H++}let dt=ge-Z;for(;dt!==ge&&ve[dt]===0;)dt++;let _t=p.repeat(re);for(;dt<ge;++dt)_t+=a.charAt(ve[dt]);return _t}t(k,"encode");function A(U){if(typeof U!="string")throw new TypeError("Expected String");if(U.length===0)return new Uint8Array;let re=0,Z=0,H=0;for(;U[re]===p;)Z++,re++;let Te=(U.length-re)*y+1>>>0,ge=new Uint8Array(Te);for(;U[re];){let Vt=s[U.charCodeAt(re)];if(Vt===255)return;let hr=0;for(let Sr=Te-1;(Vt!==0||hr<H)&&Sr!==-1;Sr--,hr++)Vt+=u*ge[Sr]>>>0,ge[Sr]=Vt%256>>>0,Vt=Vt/256>>>0;if(Vt!==0)throw new Error("Non-zero carry");H=hr,re++}let ve=Te-H;for(;ve!==Te&&ge[ve]===0;)ve++;let dt=new Uint8Array(Z+(Te-ve)),_t=Z;for(;ve!==Te;)dt[_t++]=ge[ve++];return dt}t(A,"decodeUnsafe");function M(U){let re=A(U);if(re)return re;throw new Error("Non-base"+u+" character")}return t(M,"decode"),{encode:k,decodeUnsafe:A,decode:M}}t(u1r,"base");var Mgt=u1r;var f1r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",tfe=Mgt(f1r);var _8e="2024-09-02",jgt=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function Bgt(){return new DT({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:_8e,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:jgt[_8e]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}t(Bgt,"getMockEnvironment");var DT=class a{static{t(this,"Environment")}config;static#t;static#r=!1;static initialize(s){this.#t||(this.#t=new a(s),this.#r=!0)}static get instance(){return this.#r||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#t=Bgt()),this.#t}constructor({build:s,runtime:u}){let p;try{if(u.__ZUPLO_CONFIG){let y=atob(u.__ZUPLO_CONFIG);p=JSON.parse(y)}if(u.ZUPLO_SYSTEM_CONFIGURATIONS){let y=new TextDecoder().decode(tfe.decode(u.ZUPLO_SYSTEM_CONFIGURATIONS)),b=JSON.parse(y);for(let k of Object.keys(b))u[k]=b[k]}}catch(y){console.error("Failed to parse runtime configuration",y)}this.config=p??{},this.build=s,this.runtime=u,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get enableRuntimeUserLogs(){return this.config.runtime_user_logs==="true"}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var _1r=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ugt(a){return a.startsWith("__ZUPLO")||a.startsWith("ZUPLO_")?!_1r.includes(a)&&!a.startsWith("ZUPLO_PUBLIC_"):!1}t(Ugt,"isRestrictedEnvVariableName");function $gt(a){return!!a.startsWith("ZUPLO_")}t($gt,"isZuploReadableEnvVariableName");var JMr=new Proxy({},{get(a,s){let u=String(s);switch(u){case"ZUPLO_ENVIRONMENT_TYPE":return DT.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return DT.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return DT.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return DT.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return DT.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return DT.instance.build.BUILD_ID}if(!(Ugt(u)&&!$gt(u)))return DT.instance.runtime[u]}});function dG(a,s,u){return`_${zP(a+"_"+s+"_"+u)}`}t(dG,"getRawOperationDataIdentifierName");function p8e(a,s,u,p){return`_${zP(a.toLowerCase())}_`+s.toLowerCase()+"_"+u.toLowerCase()+`_${p.toLowerCase()}`}t(p8e,"getIdForParameterSchema");function d8e(a,s,u){return`_${zP(a.toLowerCase())}_`+s.toLowerCase()+`_rb_${zP(u.toLowerCase())}`}t(d8e,"getIdForRequestBodySchema");function mG(a,s){return`_${zP(a)}__${zP(s)}`}t(mG,"getIdForRefSchema");function zP(a){let s=[];for(let u=0;u<a.length;u++){let p=a.charCodeAt(u);p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122?s.push(a.charAt(u)):s.push("_")}return s.join("")}t(zP,"sanitizedIdentifierName");var Wbt=Pd(cyt(),1);import{findNodeAtLocation as fK,getNodeValue as S_e,printParseErrorCode as wwr}from"jsonc-parser";import hFe from"path";var DG=class{static{t(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(a,s,u,p,y,b){this.type=a,this.name=s,this.prefix=u,this.value=p,this.suffix=y,this.modifier=b}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},Bbr=/[$_\p{ID_Start}]/u,Ubr=/[$_\u200C\u200D\p{ID_Continue}]/u,G8e=".*";function $br(a,s){return(s?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(a)}t($br,"Re");function fyt(a,s=!1){let u=[],p=0;for(;p<a.length;){let y=a[p],b=t(function(k){if(!s)throw new TypeError(k);u.push({type:"INVALID_CHAR",index:p,value:a[p++]})},"c");if(y==="*"){u.push({type:"ASTERISK",index:p,value:a[p++]});continue}if(y==="+"||y==="?"){u.push({type:"OTHER_MODIFIER",index:p,value:a[p++]});continue}if(y==="\\"){u.push({type:"ESCAPED_CHAR",index:p++,value:a[p++]});continue}if(y==="{"){u.push({type:"OPEN",index:p,value:a[p++]});continue}if(y==="}"){u.push({type:"CLOSE",index:p,value:a[p++]});continue}if(y===":"){let k="",A=p+1;for(;A<a.length;){let M=a.substr(A,1);if(A===p+1&&Bbr.test(M)||A!==p+1&&Ubr.test(M)){k+=a[A++];continue}break}if(!k){b(`Missing parameter name at ${p}`);continue}u.push({type:"NAME",index:p,value:k}),p=A;continue}if(y==="("){let k=1,A="",M=p+1,U=!1;if(a[M]==="?"){b(`Pattern cannot start with "?" at ${M}`);continue}for(;M<a.length;){if(!$br(a[M],!1)){b(`Invalid character '${a[M]}' at ${M}.`),U=!0;break}if(a[M]==="\\"){A+=a[M++]+a[M++];continue}if(a[M]===")"){if(k--,k===0){M++;break}}else if(a[M]==="("&&(k++,a[M+1]!=="?")){b(`Capturing groups are not allowed at ${M}`),U=!0;break}A+=a[M++]}if(U)continue;if(k){b(`Unbalanced pattern at ${p}`);continue}if(!A){b(`Missing pattern at ${p}`);continue}u.push({type:"REGEX",index:p,value:A}),p=M;continue}u.push({type:"CHAR",index:p,value:a[p++]})}return u.push({type:"END",index:p,value:""}),u}t(fyt,"v");function _yt(a,s={}){let u=fyt(a);s.delimiter??="/#?",s.prefixes??="./";let p=`[^${NT(s.delimiter)}]+?`,y=[],b=0,k=0,A="",M=new Set,U=t(hr=>{if(k<u.length&&u[k].type===hr)return u[k++].value},"a"),re=t(()=>U("OTHER_MODIFIER")??U("ASTERISK"),"f"),Z=t(hr=>{let Sr=U(hr);if(Sr!==void 0)return Sr;let{type:Zt,index:lr}=u[k];throw new TypeError(`Unexpected ${Zt} at ${lr}, expected ${hr}`)},"d"),H=t(()=>{let hr="",Sr;for(;Sr=U("CHAR")??U("ESCAPED_CHAR");)hr+=Sr;return hr},"T"),Te=t(hr=>hr,"Se"),ge=s.encodePart||Te,ve="",dt=t(hr=>{ve+=hr},"U"),_t=t(()=>{ve.length&&(y.push(new DG(3,"","",ge(ve),"",3)),ve="")},"$"),Vt=t((hr,Sr,Zt,lr,Xt)=>{let ei=3;switch(Xt){case"?":ei=1;break;case"*":ei=0;break;case"+":ei=2;break}if(!Sr&&!Zt&&ei===3){dt(hr);return}if(_t(),!Sr&&!Zt){if(!hr)return;y.push(new DG(3,"","",ge(hr),"",ei));return}let fr;Zt?Zt==="*"?fr=G8e:fr=Zt:fr=p;let wi=2;fr===p?(wi=1,fr=""):fr===G8e&&(wi=0,fr="");let un;if(Sr?un=Sr:Zt&&(un=b++),M.has(un))throw new TypeError(`Duplicate name '${un}'.`);M.add(un),y.push(new DG(wi,un,ge(hr),fr,ge(lr),ei))},"V");for(;k<u.length;){let hr=U("CHAR"),Sr=U("NAME"),Zt=U("REGEX");if(!Sr&&!Zt&&(Zt=U("ASTERISK")),Sr||Zt){let Xt=hr??"";s.prefixes.indexOf(Xt)===-1&&(dt(Xt),Xt=""),_t();let ei=re();Vt(Xt,Sr,Zt,"",ei);continue}let lr=hr??U("ESCAPED_CHAR");if(lr){dt(lr);continue}if(U("OPEN")){let Xt=H(),ei=U("NAME"),fr=U("REGEX");!ei&&!fr&&(fr=U("ASTERISK"));let wi=H();Z("CLOSE");let un=re();Vt(Xt,ei,fr,wi,un);continue}_t(),Z("END")}return y}t(_yt,"D");function NT(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(NT,"S");function lyt(a){return a&&a.ignoreCase?"ui":"u"}t(lyt,"X");function Jbr(a,s,u){return pyt(_yt(a,u),s,u)}t(Jbr,"Z");function _j(a){switch(a){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}t(_j,"k");function pyt(a,s,u={}){u.delimiter??="/#?",u.prefixes??="./",u.sensitive??=!1,u.strict??=!1,u.end??=!0,u.start??=!0,u.endsWith="";let p=u.start?"^":"";for(let A of a){if(A.type===3){A.modifier===3?p+=NT(A.value):p+=`(?:${NT(A.value)})${_j(A.modifier)}`;continue}s&&s.push(A.name);let M=`[^${NT(u.delimiter)}]+?`,U=A.value;if(A.type===1?U=M:A.type===0&&(U=G8e),!A.prefix.length&&!A.suffix.length){A.modifier===3||A.modifier===1?p+=`(${U})${_j(A.modifier)}`:p+=`((?:${U})${_j(A.modifier)})`;continue}if(A.modifier===3||A.modifier===1){p+=`(?:${NT(A.prefix)}(${U})${NT(A.suffix)})`,p+=_j(A.modifier);continue}p+=`(?:${NT(A.prefix)}`,p+=`((?:${U})(?:`,p+=NT(A.suffix),p+=NT(A.prefix),p+=`(?:${U}))*)${NT(A.suffix)})`,A.modifier===0&&(p+="?")}let y=`[${NT(u.endsWith)}]|$`,b=`[${NT(u.delimiter)}]`;if(u.end)return u.strict||(p+=`${b}?`),u.endsWith.length?p+=`(?=${y})`:p+="$",new RegExp(p,lyt(u));u.strict||(p+=`(?:${b}(?=${y}))?`);let k=!1;if(a.length){let A=a[a.length-1];A.type===3&&A.modifier===3&&(k=u.delimiter.indexOf(A)>-1)}return k||(p+=`(?=${b}|${y})`),new RegExp(p,lyt(u))}t(pyt,"F");var E4={delimiter:"",prefixes:"",sensitive:!0,strict:!0},qbr={delimiter:".",prefixes:"",sensitive:!0,strict:!0},zbr={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function Vbr(a,s){return a.length?a[0]==="/"?!0:!s||a.length<2?!1:(a[0]=="\\"||a[0]=="{")&&a[1]=="/":!1}t(Vbr,"J");function dyt(a,s){return a.startsWith(s)?a.substring(s.length,a.length):a}t(dyt,"Q");function Wbr(a,s){return a.endsWith(s)?a.substr(0,a.length-s.length):a}t(Wbr,"Ee");function myt(a){return!a||a.length<2?!1:a[0]==="["||(a[0]==="\\"||a[0]==="{")&&a[1]==="["}t(myt,"W");var hyt=["ftp","file","http","https","ws","wss"];function gyt(a){if(!a)return!0;for(let s of hyt)if(a.test(s))return!0;return!1}t(gyt,"N");function Hbr(a,s){if(a=dyt(a,"#"),s||a==="")return a;let u=new URL("https://example.com");return u.hash=a,u.hash?u.hash.substring(1,u.hash.length):""}t(Hbr,"te");function Gbr(a,s){if(a=dyt(a,"?"),s||a==="")return a;let u=new URL("https://example.com");return u.search=a,u.search?u.search.substring(1,u.search.length):""}t(Gbr,"re");function Kbr(a,s){return s||a===""?a:myt(a)?byt(a):vyt(a)}t(Kbr,"ne");function Ybr(a,s){if(s||a==="")return a;let u=new URL("https://example.com");return u.password=a,u.password}t(Ybr,"se");function Xbr(a,s){if(s||a==="")return a;let u=new URL("https://example.com");return u.username=a,u.username}t(Xbr,"ie");function Qbr(a,s,u){if(u||a==="")return a;if(s&&!hyt.includes(s))return new URL(`${s}:${a}`).pathname;let p=a[0]=="/";return a=new URL(p?a:"/-"+a,"https://example.com").pathname,p||(a=a.substring(2,a.length)),a}t(Qbr,"ae");function Zbr(a,s,u){return yyt(s)===a&&(a=""),u||a===""?a:Syt(a)}t(Zbr,"oe");function eSr(a,s){return a=Wbr(a,":"),s||a===""?a:K8e(a)}t(eSr,"ce");function yyt(a){switch(a){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}t(yyt,"_");function K8e(a){if(a==="")return a;if(/^[-+.A-Za-z0-9]*$/.test(a))return a.toLowerCase();throw new TypeError(`Invalid protocol '${a}'.`)}t(K8e,"y");function tSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.username=a,s.username}t(tSr,"le");function rSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.password=a,s.password}t(rSr,"fe");function vyt(a){if(a==="")return a;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(a))throw new TypeError(`Invalid hostname '${a}'`);let s=new URL("https://example.com");return s.hostname=a,s.hostname}t(vyt,"z");function byt(a){if(a==="")return a;if(/[^0-9a-fA-F[\]:]/g.test(a))throw new TypeError(`Invalid IPv6 hostname '${a}'`);return a.toLowerCase()}t(byt,"j");function Syt(a){if(a===""||/^[0-9]*$/.test(a)&&parseInt(a)<=65535)return a;throw new TypeError(`Invalid port '${a}'.`)}t(Syt,"K");function nSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.pathname=a[0]!=="/"?"/-"+a:a,a[0]!=="/"?s.pathname.substring(2,s.pathname.length):s.pathname}t(nSr,"he");function iSr(a){return a===""?a:new URL(`data:${a}`).pathname}t(iSr,"ue");function sSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.search=a,s.search.substring(1,s.search.length)}t(sSr,"de");function aSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.hash=a,s.hash.substring(1,s.hash.length)}t(aSr,"pe");var oSr=class{static{t(this,"H")}#t;#r=[];#i={};#e=0;#a=1;#m=0;#o=0;#u=0;#c=0;#l=!1;constructor(a){this.#t=a}get result(){return this.#i}parse(){for(this.#r=fyt(this.#t,!0);this.#e<this.#r.length;this.#e+=this.#a){if(this.#a=1,this.#r[this.#e].type==="END"){if(this.#o===0){this.#y(),this.#E()?this.#n(9,1):this.#_()?this.#n(8,1):this.#n(7,0);continue}else if(this.#o===2){this.#p(5);continue}this.#n(10,0);break}if(this.#u>0)if(this.#s())this.#u-=1;else continue;if(this.#D()){this.#u+=1;continue}switch(this.#o){case 0:this.#g()&&this.#p(1);break;case 1:if(this.#g()){this.#I();let a=7,s=1;this.#w()?(a=2,s=3):this.#l&&(a=2),this.#n(a,s)}break;case 2:this.#C()?this.#p(3):(this.#x()||this.#_()||this.#E())&&this.#p(5);break;case 3:this.#T()?this.#n(4,1):this.#C()&&this.#n(5,1);break;case 4:this.#C()&&this.#n(5,1);break;case 5:this.#N()?this.#c+=1:this.#b()&&(this.#c-=1),this.#k()&&!this.#c?this.#n(6,1):this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 6:this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 7:this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 8:this.#E()&&this.#n(9,1);break;case 9:break;case 10:break}}this.#i.hostname!==void 0&&this.#i.port===void 0&&(this.#i.port="")}#n(a,s){switch(this.#o){case 0:break;case 1:this.#i.protocol=this.#S();break;case 2:break;case 3:this.#i.username=this.#S();break;case 4:this.#i.password=this.#S();break;case 5:this.#i.hostname=this.#S();break;case 6:this.#i.port=this.#S();break;case 7:this.#i.pathname=this.#S();break;case 8:this.#i.search=this.#S();break;case 9:this.#i.hash=this.#S();break;case 10:break}this.#o!==0&&a!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(a)&&(this.#i.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(a)&&(this.#i.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&a===9&&(this.#i.search??="")),this.#v(a,s)}#v(a,s){this.#o=a,this.#m=this.#e+s,this.#e+=s,this.#a=0}#y(){this.#e=this.#m,this.#a=0}#p(a){this.#y(),this.#o=a}#d(a){return a<0&&(a=this.#r.length-a),a<this.#r.length?this.#r[a]:this.#r[this.#r.length-1]}#h(a,s){let u=this.#d(a);return u.value===s&&(u.type==="CHAR"||u.type==="ESCAPED_CHAR"||u.type==="INVALID_CHAR")}#g(){return this.#h(this.#e,":")}#w(){return this.#h(this.#e+1,"/")&&this.#h(this.#e+2,"/")}#C(){return this.#h(this.#e,"@")}#T(){return this.#h(this.#e,":")}#k(){return this.#h(this.#e,":")}#x(){return this.#h(this.#e,"/")}#_(){if(this.#h(this.#e,"?"))return!0;if(this.#r[this.#e].value!=="?")return!1;let a=this.#d(this.#e-1);return a.type!=="NAME"&&a.type!=="REGEX"&&a.type!=="CLOSE"&&a.type!=="ASTERISK"}#E(){return this.#h(this.#e,"#")}#D(){return this.#r[this.#e].type=="OPEN"}#s(){return this.#r[this.#e].type=="CLOSE"}#N(){return this.#h(this.#e,"[")}#b(){return this.#h(this.#e,"]")}#S(){let a=this.#r[this.#e],s=this.#d(this.#m).index;return this.#t.substring(s,a.index)}#I(){let a={};Object.assign(a,E4),a.encodePart=K8e;let s=Jbr(this.#S(),void 0,a);this.#l=gyt(s)}},H8e=["protocol","username","password","hostname","port","pathname","search","hash"],x4="*";function uyt(a,s){if(typeof a!="string")throw new TypeError("parameter 1 is not of type 'string'.");let u=new URL(a,s);return{protocol:u.protocol.substring(0,u.protocol.length-1),username:u.username,password:u.password,hostname:u.hostname,port:u.port,pathname:u.pathname,search:u.search!==""?u.search.substring(1,u.search.length):void 0,hash:u.hash!==""?u.hash.substring(1,u.hash.length):void 0}}t(uyt,"ge");function GP(a,s){return s?wG(a):a}t(GP,"b");function kG(a,s,u){let p;if(typeof s.baseURL=="string")try{p=new URL(s.baseURL),s.protocol===void 0&&(a.protocol=GP(p.protocol.substring(0,p.protocol.length-1),u)),!u&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&(a.username=GP(p.username,u)),!u&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&s.password===void 0&&(a.password=GP(p.password,u)),s.protocol===void 0&&s.hostname===void 0&&(a.hostname=GP(p.hostname,u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&(a.port=GP(p.port,u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&(a.pathname=GP(p.pathname,u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&(a.search=GP(p.search.substring(1,p.search.length),u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&s.hash===void 0&&(a.hash=GP(p.hash.substring(1,p.hash.length),u))}catch{throw new TypeError(`invalid baseURL '${s.baseURL}'.`)}if(typeof s.protocol=="string"&&(a.protocol=eSr(s.protocol,u)),typeof s.username=="string"&&(a.username=Xbr(s.username,u)),typeof s.password=="string"&&(a.password=Ybr(s.password,u)),typeof s.hostname=="string"&&(a.hostname=Kbr(s.hostname,u)),typeof s.port=="string"&&(a.port=Zbr(s.port,a.protocol,u)),typeof s.pathname=="string"){if(a.pathname=s.pathname,p&&!Vbr(a.pathname,u)){let y=p.pathname.lastIndexOf("/");y>=0&&(a.pathname=GP(p.pathname.substring(0,y+1),u)+a.pathname)}a.pathname=Qbr(a.pathname,a.protocol,u)}return typeof s.search=="string"&&(a.search=Gbr(s.search,u)),typeof s.hash=="string"&&(a.hash=Hbr(s.hash,u)),a}t(kG,"w");function wG(a){return a.replace(/([+*?:{}()\\])/g,"\\$1")}t(wG,"C");function cSr(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(cSr,"Oe");function lSr(a,s){s.delimiter??="/#?",s.prefixes??="./",s.sensitive??=!1,s.strict??=!1,s.end??=!0,s.start??=!0,s.endsWith="";let u=".*",p=`[^${cSr(s.delimiter)}]+?`,y=/[$_\u200C\u200D\p{ID_Continue}]/u,b="";for(let k=0;k<a.length;++k){let A=a[k];if(A.type===3){if(A.modifier===3){b+=wG(A.value);continue}b+=`{${wG(A.value)}}${_j(A.modifier)}`;continue}let M=A.hasCustomName(),U=!!A.suffix.length||!!A.prefix.length&&(A.prefix.length!==1||!s.prefixes.includes(A.prefix)),re=k>0?a[k-1]:null,Z=k<a.length-1?a[k+1]:null;if(!U&&M&&A.type===1&&A.modifier===3&&Z&&!Z.prefix.length&&!Z.suffix.length)if(Z.type===3){let H=Z.value.length>0?Z.value[0]:"";U=y.test(H)}else U=!Z.hasCustomName();if(!U&&!A.prefix.length&&re&&re.type===3){let H=re.value[re.value.length-1];U=s.prefixes.includes(H)}U&&(b+="{"),b+=wG(A.prefix),M&&(b+=`:${A.name}`),A.type===2?b+=`(${A.value})`:A.type===1?M||(b+=`(${p})`):A.type===0&&(!M&&(!re||re.type===3||re.modifier!==3||U||A.prefix!=="")?b+="*":b+=`(${u})`),A.type===1&&M&&A.suffix.length&&y.test(A.suffix[0])&&(b+="\\"),b+=wG(A.suffix),U&&(b+="}"),A.modifier!==3&&(b+=_j(A.modifier))}return b}t(lSr,"ke");var Tyt=class{static{t(this,"me")}#t;#r={};#i={};#e={};#a={};#m=!1;constructor(a={},s,u){try{let p;if(typeof s=="string"?p=s:u=s,typeof a=="string"){let A=new oSr(a);if(A.parse(),a=A.result,p===void 0&&typeof a.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");a.baseURL=p}else{if(!a||typeof a!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(p)throw new TypeError("parameter 1 is not of type 'string'.")}typeof u>"u"&&(u={ignoreCase:!1});let y={ignoreCase:u.ignoreCase===!0},b={pathname:x4,protocol:x4,username:x4,password:x4,hostname:x4,port:x4,search:x4,hash:x4};this.#t=kG(b,a,!0),yyt(this.#t.protocol)===this.#t.port&&(this.#t.port="");let k;for(k of H8e){if(!(k in this.#t))continue;let A={},M=this.#t[k];switch(this.#i[k]=[],k){case"protocol":Object.assign(A,E4),A.encodePart=K8e;break;case"username":Object.assign(A,E4),A.encodePart=tSr;break;case"password":Object.assign(A,E4),A.encodePart=rSr;break;case"hostname":Object.assign(A,qbr),myt(M)?A.encodePart=byt:A.encodePart=vyt;break;case"port":Object.assign(A,E4),A.encodePart=Syt;break;case"pathname":gyt(this.#r.protocol)?(Object.assign(A,zbr,y),A.encodePart=nSr):(Object.assign(A,E4,y),A.encodePart=iSr);break;case"search":Object.assign(A,E4,y),A.encodePart=sSr;break;case"hash":Object.assign(A,E4,y),A.encodePart=aSr;break}try{this.#a[k]=_yt(M,A),this.#r[k]=pyt(this.#a[k],this.#i[k],A),this.#e[k]=lSr(this.#a[k],A),this.#m=this.#m||this.#a[k].some(U=>U.type===2)}catch{throw new TypeError(`invalid ${k} pattern '${this.#t[k]}'.`)}}}catch(p){throw new TypeError(`Failed to construct 'URLPattern': ${p.message}`)}}test(a={},s){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return!1;try{typeof a=="object"?u=kG(u,a,!1):u=kG(u,uyt(a,s),!1)}catch{return!1}let p;for(p of H8e)if(!this.#r[p].exec(u[p]))return!1;return!0}exec(a={},s){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return;try{typeof a=="object"?u=kG(u,a,!1):u=kG(u,uyt(a,s),!1)}catch{return null}let p={};s?p.inputs=[a,s]:p.inputs=[a];let y;for(y of H8e){let b=this.#r[y].exec(u[y]);if(!b)return null;let k={};for(let[A,M]of this.#i[y].entries())if(typeof M=="string"||typeof M=="number"){let U=b[A+1];k[M]=U}p[y]={input:u[y]??"",groups:k}}return p}static compareComponent(a,s,u){let p=t((A,M)=>{for(let U of["type","modifier","prefix","value","suffix"]){if(A[U]<M[U])return-1;if(A[U]!==M[U])return 1}return 0},"o"),y=new DG(3,"","","","",3),b=new DG(0,"","","","",3),k=t((A,M)=>{let U=0;for(;U<Math.min(A.length,M.length);++U){let re=p(A[U],M[U]);if(re)return re}return A.length===M.length?0:p(A[U]??y,M[U]??y)},"s");return!s.#e[a]&&!u.#e[a]?0:s.#e[a]&&!u.#e[a]?k(s.#a[a],[b]):!s.#e[a]&&u.#e[a]?k([b],u.#a[a]):k(s.#a[a],u.#a[a])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#m}};globalThis.URLPattern||(globalThis.URLPattern=Tyt);import{AssertionError as uSr}from"assert";function o7(a,s){if(a===!1)throw new uSr({message:s})}t(o7,"assert");var vc;(function(a){a.Object="Object",a.Property="Property",a.Array="Array",a.Literal="Literal",a.TemplateString="TemplateString",a.Identifier="Identifier",a.FunctionCall="FunctionCall",a.FunctionBody="FunctionBody"})(vc||(vc={}));function PG(a){return a.type===vc.Object}t(PG,"isAstObject");function KP(a){return a.type===vc.Property}t(KP,"isAstProperty");function xyt(a){return a.type===vc.Array}t(xyt,"isAstArray");function pj(a){return a.type===vc.Literal}t(pj,"isAstLiteral");import{visit as fSr}from"jsonc-parser";var _Sr={DEFAULT:{allowTrailingComma:!1}};function AG(a,s=[],u=_Sr.DEFAULT){let p={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(M){p.type==="property"&&(p.length=M-p.offset,p=p.parent)}t(y,"ensurePropertyComplete");function b(M){return p.children?.push(M),M}t(b,"onValue"),fSr(a,{onObjectBegin:t((M,U,re)=>{p=b({type:"object",offset:M,length:-1,line:U+1,column:re+1,parent:p,children:[]})},"onObjectBegin"),onObjectProperty:t((M,U,re,Z,H)=>{p=b({type:"property",offset:U,length:-1,line:Z+1,column:H+1,parent:p,children:[]}),p.children?.push({type:"string",value:M,offset:U,length:re,line:Z,column:H,parent:p})},"onObjectProperty"),onObjectEnd:t((M,U)=>{y(M+U),p.length=M+U-p.offset,p=p.parent,y(M+U)},"onObjectEnd"),onArrayBegin:t((M,U,re,Z)=>{p=b({type:"array",offset:M,length:-1,line:re+1,column:Z+1,parent:p,children:[]})},"onArrayBegin"),onArrayEnd:t((M,U)=>{p.length=M+U-p.offset,p=p.parent,y(M+U)},"onArrayEnd"),onLiteralValue:t((M,U,re,Z,H)=>{b({type:pSr(M),offset:U,length:re,line:Z+1,column:H+1,parent:p,value:M}),y(U+re)},"onLiteralValue"),onSeparator:t((M,U)=>{p.type==="property"&&(M===":"?p.colonOffset=U:M===","&&y(U))},"onSeparator"),onError:t((M,U,re,Z,H)=>{s.push({error:M,offset:U,length:re,line:Z+1,column:H+1})},"onError")},u);let A=p.children[0];return A&&delete A.parent,A}t(AG,"parse");function pSr(a){switch(typeof a){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(a){if(Array.isArray(a))return"array"}else return"null";return"object"}default:return"null"}}t(pSr,"getNodeType");var NG=class{static{t(this,"AstAdapter")}parse(s){let p=AG(s,[]);if(p)return this.parseNode(p,void 0);throw new Error("Failed to parse JSON")}convert(s){return this.parseNode(s,void 0)}parseNode(s,u){switch(s.type){case"object":return this.createObject(s,u);case"array":return this.createArray(s,u);case"property":return this.createProperty(s,u);case"string":return this.createLiteral(s,u);case"number":return this.createLiteral(s,u);case"boolean":return this.createLiteral(s,u);case"null":return this.createLiteral(s,u)}}createLiteral(s,u){return{type:vc.Literal,location:{line:s.line,column:s.column},parent:u,value:s.type==="null"?null:s.value}}createObject(s,u){let p={type:vc.Object,children:[],parent:u,location:{line:s.line,column:s.column}};return s.children?.forEach(y=>{p.children.push(this.parseNode(y,p))}),p}createProperty(s,u){o7(s.children?.length===2,"Invalid property node");let p={type:vc.Property,location:{line:s.line,column:s.column},parent:u,name:null,value:null};return p.name={value:s.children[0].value,location:{line:s.line,column:s.column},type:vc.Identifier,parent:p},p.value=this.parseNode(s.children[1],p),p}createArray(s,u){let p={type:vc.Array,location:{line:s.line,column:s.column},parent:u,children:[]};return s.children?.forEach(y=>p.children.push(this.parseNode(y,p))),p}};var IT={createLiteral:t((a,s)=>({type:vc.Literal,parent:s,value:a}),"createLiteral"),createTemplateString:t((a,s)=>({type:vc.TemplateString,parent:s,value:a}),"createTemplateString"),createIdentifier:t((a,s)=>({type:vc.Identifier,value:a,parent:s}),"createIdentifier"),createProperty:t((a,s,u)=>{let p={type:vc.Property,parent:u,name:null,value:s};return p.name={value:a,type:vc.Identifier,parent:p},p.value.parent=p,p},"createProperty"),createArrayOfLiterals:t((a,s)=>{let u={type:vc.Array,parent:s,children:[]};for(let p of a)u.children.push(IT.createLiteral(p,u));return u},"createArrayOfLiterals")};var IG=class{static{t(this,"SourceGenerator")}generate(s){let u=[];return this.generateSource(u,s),u.join("")}generateSource(s,u){switch(u.type){case vc.Array:return this.generateArray(s,u);case vc.Object:return this.generateObject(s,u);case vc.Property:return this.generateProperty(s,u);case vc.Literal:return this.generateLiteral(s,u);case vc.FunctionCall:return this.generateFunctionCall(s,u);case vc.Identifier:return this.generateIdentifier(s,u);case vc.FunctionBody:return this.generateFunctionBody(s,u);case vc.TemplateString:return this.generateTemplateString(s,u)}}generateArray(s,u){s.push("["),u.children.map(p=>{this.generateSource(s,p),s.push(",")}),s.push("]")}generateObject(s,u){s.push("{"),u.children.forEach(p=>{this.generateSource(s,p),s.push(",")}),s.push("}")}generateProperty(s,u){let p=u.name.value,y=p.search(/(\/|\\|-|\+|@|#|%|\^|&|\*|:|\.)/g)<0?p:`'${p}'`;s.push(y),s.push(":"),this.generateSource(s,u.value)}generateFunctionCall(s,u){s.push(u.name.value),s.push("("),u.children.forEach((p,y,b)=>{this.generateSource(s,p),y<b.length&&s.push(",")}),s.push(")")}generateFunctionBody(s,u){s.push(u.value)}generateTemplateString(s,u){s.push("`"),s.push(u.value.replaceAll("`","\\`")),s.push("`")}generateLiteral(s,u){if(u.value===null)return s.push("null");switch(typeof u.value){case"number":case"boolean":return s.push(`${u.value}`);case"string":{let p=u.value,y=JSON.stringify(p);return s.push(`${y}`)}}}generateIdentifier(s,u){s.push(u.value)}};import{parse as dSr}from"@swc/core";import mSr from"fs/promises";var Eyt=t(async a=>{let s=new Set;try{let u=await mSr.readFile(a,"utf-8");(await dSr(u,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?s.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?s.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&s.add(y.declaration.declarations[0].id.value)})}catch{return null}return s},"getJSFileExports");var Cyt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var Y8e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var kyt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var X8e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var Q8e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler","version"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},version:{type:"string",pattern:"^[0-9a-z-]+$"},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var wyt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/routes.schema.json",title:"Route Config File",type:"object",additionalProperties:!1,required:["routes","versions"],$defs:{info:{type:"object",required:["title","version"],properties:{title:{type:"string"},summary:{type:"string"},description:{type:"string"},termsOfService:{type:"string",format:"uri"},version:{type:"string"}}},versionData:{type:"object",required:["name","pathPrefix"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},pathPrefix:{type:"string",pattern:"(^$|^/[^\\s]*$)"},info:{$ref:"#/$defs/info"},openApiFile:{description:"The project relative path to the OpenAPI spec.",type:"string"},excludeFromOpenApi:{type:"boolean",description:"If false, OpenAPI documentation will not be generated for this version. If openApiFile is set this setting is ignored."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."}}}},properties:{$schema:{type:"string"},versions:{type:"array",minItems:1,items:{$ref:"#/$defs/versionData"}},routes:{type:"array",minItems:0,items:{$ref:"route-configuration.schema.json"}},policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}},requestErrorHandler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"}}};var jbt=Pd(obt(),1),Bbt=Pd(Mbt(),1);var p_e=class a{static{t(this,"JsonValidator")}static#t=new a;static get instance(){return a.#t}ajv;constructor(){this.ajv=new Bbt.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,jbt.default)(this.ajv,{mode:"fast"})}addSchema(s,u){this.ajv.addSchema(s,u)}compile(s){let u=this.ajv.compile(s);return t(y=>({isValid:u(y),errors:this.toSimpleErrors(u.errors,y),warnings:[]}),"validator")}toSimpleErrors(s,u){let p=[];return s?.forEach(y=>{y.keyword==="enum"&&y.params.allowedValues&&Array.isArray(y.params.allowedValues)&&(y.message+=`; ${y.params.allowedValues.join(", ")}`),y.instancePath&&(y.instancePath=y.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let b={details:{}},k=y.instancePath.split("/");if(k.length>2){let M=k[1],U=k[2]?parseInt(k[2]):0,re=k[3],Z=isNaN(U)?void 0:u[M][U][re];b={details:{property:M,index:U,field:re,fieldValue:Z}}}if(y.keyword==="required"&&y.params.missingProperty&&y.instancePath&&(y.message=`A 'path' is missing required property '${y.params.missingProperty}'`),y.keyword==="additionalProperties"&&y.params.additionalProperty&&y.instancePath&&(y.message=`A 'path' should NOT include property '${y.params.additionalProperty}'`),y.keyword==="type"&&y.params.type&&y.instancePath){let M=y.instancePath.split("/"),U=M[M.length-1];y.message=`Value of property '${U}' must be '${y.params.type}'`}let A=Object.assign(y,b);p.push(A)}),p}};var eA=p_e.instance;eA.addSchema(wyt,"routes.schema.json");eA.addSchema(Q8e,"route-configuration.schema.json");eA.addSchema(kyt,"policy-configuration.schema.json");eA.addSchema(Y8e,"policies.schema.json");eA.addSchema(X8e,"open-api-route-configuration.schema.json");eA.addSchema(Cyt,"fragments.schema.json");var bwr=eA.compile(Q8e),Ubt=eA.compile(X8e),_Fe=eA.compile(Y8e);var d_e=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(s){return this.results=_Fe(s),this.results}};var m_e=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(s){return this.results=Ubt(s),this.results}};import Twr from"path";var pFe=/\$import\((.*)\)/,h_e=/\$env\((.*?)\)/g;var tA=class extends Error{static{t(this,"CodeGenError")}location;constructor(s,u,p,y){super(s),this.location={file:u,namespace:"",line:p?p.line:0,column:p?p.column:0,length:0,lineText:y??"",suggestion:""}}},Swr=t(a=>{let s=[],u=a;for(;u.parent;)s.push(u),u=u.parent;return s.reverse()},"invertTree"),O4=t((a,s)=>{if(!a)return!1;let u=Swr(a);return s.split("/").every((b,k)=>{let A=u[k];return A?b==="*"||KP(A)&&A.name.value===b?!0:b==="{}"?A.type===vc.Object:b==="[]"?A.type===vc.Array:!1:!1})},"testPosition");var g_e=class{static{t(this,"AstTransformer")}errors=[];transform(s){return this.visitor(s),s}visitor(s){this.visit(s),PG(s)?s.children.forEach(u=>{this.visitor(u)}):xyt(s)?s.children.forEach(u=>{this.visitor(u)}):KP(s)&&this.visitor(s.value)}},$bt=t((a,s,u)=>p=>{if(!KP(p)||!pj(p.value)||typeof p.value.value!="string")return;if(!a.some(b=>O4(p,b))){h_e.test(p.value.value)&&s.push(new tA("An $env() statement is not expected at this location.",u,p.location,p.value.value));return}let y=new RegExp(h_e).exec(p.value.value);if(y?.length===2&&y[0]===p.value.value){let b={type:vc.FunctionBody,parent:null,value:`environment["${y[1]}"]`};p.value=b}else{let b=p.value.value.replaceAll(new RegExp(h_e),(k,A)=>`\${environment["${A}"] ? environment["${A}"] : ""}`);b!==p.value.value&&(p.value=IT.createTemplateString(b,p))}},"getEnvStatementTransformer");var uK="config/routes.json",xwr=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*","corsPolicies/[]/{}/*"],Ewr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Jbt=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],Cwr="handler/{}/options/{}/rewritePattern",kwr="handler/{}/options/{}/baseUrl",y_e=class extends g_e{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(s){this.addedImports.has(s)||this.addedImports.set(s,`__import${this.importCount++}`);let u=this.addedImports.get(s);if(!u)throw new Error("Import name is undefined. This should not happen.");return u}getImports(){let s=[];return this.addedImports.forEach((u,p)=>{s.push({name:u,path:p})}),s}visit(s){this.rewriteHandlerFunction(s),this.rewriteForwardFunction(s),this.replaceImportStatements(s),this.replaceEnvStatements(s)}rewriteHandlerFunction(s){if(!(!KP(s)||!pj(s.value)||typeof s.value.value!="string")&&O4(s,Cwr)){if(!s.parent||!PG(s.parent)){this.errors.push(new tA("Invalid node, expected object",uK,s.parent?s.parent.location:s.location,void 0));return}let u=s.value.value,p={type:vc.FunctionBody,parent:null,value:qbt(u)},y=IT.createProperty("__rewriteFunction",p,s);s.parent.children.push(y)}}rewriteForwardFunction(s){if(!(!KP(s)||!pj(s.value)||typeof s.value.value!="string")&&O4(s,kwr)){if(!s.parent||!PG(s.parent)){this.errors.push(new tA("Invalid node, expected object",uK,s.parent?s.parent.location:s.location,void 0));return}let u=s.value.value,p={type:vc.FunctionBody,parent:null,value:qbt(u)},y=IT.createProperty("__rewriteFunction",p,s);s.parent.children.push(y)}}replaceImportStatements(s){if(!KP(s)||!pj(s.value))return;let u=s.value.value;if(typeof u!="string")return;if(!Ewr.some(A=>O4(s,A))&&!Jbt.some(A=>O4(s,A))){if(pFe.test(u)){if(s.name.value==="$ref")return;this.errors.push(new tA("An $import() statement is not expected at this location.",uK,s.location,u))}return}let p=pFe.exec(u);if(Jbt.some(A=>O4(s,A))&&!p)return;if(!p){this.errors.push(new tA("Invalid $import() statement",uK,s.location,u));return}let y=p[1];y.startsWith(".")&&(y=Twr.join("..",y));let b=this.getImportName(y),k={type:vc.Identifier,parent:s.parent,value:b};s.value=k}replaceEnvStatements=$bt(xwr,this.errors,uK)};function qbt(a){return`(request, context) => {
710
+ export default environment;`;function hdt(a){return{name:"environment",setup(s){s.onResolve({filter:/@app\/environment$/},()=>({namespace:mdt,pluginName:ddt,path:pdt.join(a.sourceDirectory,GN,"environment.js")})),s.onLoad({filter:/.*/,namespace:mdt},async u=>({contents:ipr,loader:"ts",resolveDir:pdt.dirname(u.path),pluginName:ddt}))}}}t(hdt,"environmentPlugin");var Agt=Pd(B3e(),1),Ngt=Pd(Xht(),1),Igt=Pd(u8e(),1),Ogt=Pd(f8e(),1);import Pgt from"fs/promises";import $S from"path";import i1r from"prettier";var nw="schemas",efe="json-schema";function Fgt(a){return{name:nw,async setup(s){let u=new Igt.Ajv2020({code:{source:!0},allErrors:!0,strict:!1,verbose:!0,meta:!0});(0,Ngt.default)(u,{mode:"fast"}),u.opts.code.formats=Agt._`require("ajv-formats/dist/formats").fastFormats`;let p=$S.join(a.sourceDirectory,hM),y,b=[],k=[];if(await Mc.dirExists(p)&&(u.addKeyword("faker"),y=await Mc.listFolderContents(p,hM),await Promise.all(y.map(async A=>{try{let M=Mc.safePath(a.sourceDirectory).resolve(p,A);if(!M.startsWith(p))throw new Error("All schemas must be in the schemas directory");let U=await Pgt.readFile(M,"utf-8");if(U===""||U===void 0)throw new Error(`Schema 'schemas/${A}' is empty and will be ignored.`);let re=JSON.parse(U);if(re.$schema&&re.$schema!=="https://json-schema.org/draft/2020-12/schema")throw new Error(`Error in ${A}: All JSON schemas must use version 2020-12. See release notes for changes: https://json-schema.org/draft/2020-12/release-notes.html`);if(u.$dataMetaSchema,u.addSchema(re,A),u.errors?.length){let Z=u.errors[0];b.push({id:"json-schema-validation-error",pluginName:nw,text:`Error: ${Z.message}`,location:{file:$S.join(hM,A)},detail:{params:Z.params,propertyName:Z.propertyName,schemaPath:Z.schemaPath,data:Z.data}})}}catch(M){if(M.message.endsWith("is empty and will be ignored.")){k.push({id:"empty-json-schema-file",pluginName:nw,text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."},detail:"EmptyJSONSchemaFile",notes:[{text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."}}]});return}let U=await d4e(A,a.sourceDirectory,M.message);b.push({id:"json-schema-add-error",pluginName:nw,text:`Error: ${M.message}`,location:U,detail:"InvalidAddSchemaError",notes:[{text:M.message}]})}})),await Promise.all(y.map(async A=>{try{let M=u.getSchema(A);M&&u.compile(M.schema).errors?.forEach(re=>{b.push({text:`Failed to compile ${A}: ${re.message}`})})}catch(M){let U=await d4e(A,a.sourceDirectory,M.message);b.push({id:"json-schema-compile-error",pluginName:nw,text:`The schema file '${A}' is not valid. Error: ${M.message}`,location:U,detail:"InvalidSchemaError",notes:[{text:M.message}]})}})),zg.DEBUG_BUILD_MODE)){let A=$S.resolve(a.outputDirectory,hM);await Mc.mkdirIfNotExists(A)}s.onStart(async()=>{if(y)return{errors:b,warnings:k}}),s.onResolve({filter:/schemas\/.*\.json$/},async A=>{let M=$S.isAbsolute(A.path)?A.path:$S.join(A.resolveDir,A.path);if(A.importer&&A.importer!==$S.join(a.sourceDirectory,"config/routes.json"))return{path:M};if(!await Mc.fileExists(M)){let U="policies.json";return{errors:[{id:"json-schema-build-error",text:`Unable to resolve reference to '${A.path}' from ${U}`,location:{file:$S.join(A.resolveDir,U),namespace:efe,line:1,column:0,length:0,lineText:`Invalid JSON schema reference in ${U}`,suggestion:""},detail:"RouteReferenceError",pluginName:nw,notes:[{text:`Unable to resolve reference to '${A.path}' from ${U}`,location:null}]}],namespace:efe,path:M,pluginName:nw}}return{path:M,namespace:efe,pluginName:nw}}),s.onLoad({filter:/.*/,namespace:efe},async A=>hf.timeFn(`Generating json schema data: ${$S.basename(A.path)}`,async()=>{let M=[],U;try{let re=$S.relative(p,A.path),Z=u.getSchema(re);if(!Z)throw new Error(`Could not load schema at ${A.path}`);U=Z.source?.validateCode;let H=u.compile(Z.schema);U=(0,Ogt.default)(u,H)}catch(re){M.push({pluginName:nw,text:`Cannot parse project's schemas/${$S.basename(A.path)} file. Error: ${re.message}`,location:null,notes:[{text:re.message,location:null}],detail:re})}if(zg.DEBUG_BUILD_MODE&&U){let re=$S.resolve(a.outputDirectory,hM),Z=$S.relative(p,A.path),H=await i1r.format(U,{parser:"babel"}),Te=Mc.safePath(a.sourceDirectory).resolve(re,`${Z}.js`);await Mc.mkdirForFilePathIfNotExits(Te),await Pgt.writeFile(Te,H,"utf-8")}return{contents:U,errors:M,pluginName:nw,resolveDir:$S.dirname(A.path),watchFiles:[A.path]}}))}}}t(Fgt,"jsonSchemaPlugin");import{relative as s1r,resolve as a1r}from"path";import{dirname as o1r}from"path";import{fileURLToPath as c1r}from"url";var Lgt=["node:assert","node:async_hooks","node:buffer","node:crypto","node:diagnostics_channel","node:events","node:path","node:process","node:stream","node:string_decoder","node:util"],l1r="nodejs-compat-plugin";function Rgt({nodeCompatEnabled:a,sourceDirectory:s}){return{name:l1r,setup(u){let p=new Set;u.onStart(()=>{p.clear()}),u.onResolve({filter:/node:.*/},async({path:y,kind:b,resolveDir:k,...A})=>{let M=`${y}:${b}:${k}:${A.importer}`;if(p.has(M))return;if(p.add(M),!a&&y==="node:async_hooks")return{path:a1r(o1r(c1r(import.meta.url)),"../../../polyfills/async_hooks.js")};let U=await u.resolve(y,{kind:b,resolveDir:k,importer:A.importer});return U.errors.length>0?a&&Lgt.includes(y)||y.includes("/")&&Lgt.includes(y.split("/")[0])?{external:!0}:{external:!0,warnings:U.errors.map(Z=>({...Z,location:{file:s1r(s,A.importer),line:0,column:0,namespace:"",length:0,lineText:"",suggestion:"Remove the imported node module"},detail:`The package "${y}" wasn't found on the file system but is built into node. If this code is executed it will fail.`}))}:U})}}}t(Rgt,"nodejsCompatPlugin");function u1r(a){if(a.length>=255)throw new TypeError("Alphabet too long");let s=new Uint8Array(256);for(let U=0;U<s.length;U++)s[U]=255;for(let U=0;U<a.length;U++){let re=a.charAt(U),Z=re.charCodeAt(0);if(s[Z]!==255)throw new TypeError(re+" is ambiguous");s[Z]=U}let u=a.length,p=a.charAt(0),y=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function k(U){if(U instanceof Uint8Array||(ArrayBuffer.isView(U)?U=new Uint8Array(U.buffer,U.byteOffset,U.byteLength):Array.isArray(U)&&(U=Uint8Array.from(U))),!(U instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(U.length===0)return"";let re=0,Z=0,H=0,Te=U.length;for(;H!==Te&&U[H]===0;)H++,re++;let ge=(Te-H)*b+1>>>0,ve=new Uint8Array(ge);for(;H!==Te;){let Vt=U[H],hr=0;for(let Sr=ge-1;(Vt!==0||hr<Z)&&Sr!==-1;Sr--,hr++)Vt+=256*ve[Sr]>>>0,ve[Sr]=Vt%u>>>0,Vt=Vt/u>>>0;if(Vt!==0)throw new Error("Non-zero carry");Z=hr,H++}let dt=ge-Z;for(;dt!==ge&&ve[dt]===0;)dt++;let _t=p.repeat(re);for(;dt<ge;++dt)_t+=a.charAt(ve[dt]);return _t}t(k,"encode");function A(U){if(typeof U!="string")throw new TypeError("Expected String");if(U.length===0)return new Uint8Array;let re=0,Z=0,H=0;for(;U[re]===p;)Z++,re++;let Te=(U.length-re)*y+1>>>0,ge=new Uint8Array(Te);for(;U[re];){let Vt=s[U.charCodeAt(re)];if(Vt===255)return;let hr=0;for(let Sr=Te-1;(Vt!==0||hr<H)&&Sr!==-1;Sr--,hr++)Vt+=u*ge[Sr]>>>0,ge[Sr]=Vt%256>>>0,Vt=Vt/256>>>0;if(Vt!==0)throw new Error("Non-zero carry");H=hr,re++}let ve=Te-H;for(;ve!==Te&&ge[ve]===0;)ve++;let dt=new Uint8Array(Z+(Te-ve)),_t=Z;for(;ve!==Te;)dt[_t++]=ge[ve++];return dt}t(A,"decodeUnsafe");function M(U){let re=A(U);if(re)return re;throw new Error("Non-base"+u+" character")}return t(M,"decode"),{encode:k,decodeUnsafe:A,decode:M}}t(u1r,"base");var Mgt=u1r;var f1r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",tfe=Mgt(f1r);var _8e="2024-09-02",jgt=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function Bgt(){return new DT({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:_8e,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:jgt[_8e]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}t(Bgt,"getMockEnvironment");var DT=class a{static{t(this,"Environment")}config;static#t;static#r=!1;static initialize(s){this.#t||(this.#t=new a(s),this.#r=!0)}static get instance(){return this.#r||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#t=Bgt()),this.#t}constructor({build:s,runtime:u}){let p;try{if(u.__ZUPLO_CONFIG){let y=atob(u.__ZUPLO_CONFIG);p=JSON.parse(y)}if(u.ZUPLO_SYSTEM_CONFIGURATIONS){let y=new TextDecoder().decode(tfe.decode(u.ZUPLO_SYSTEM_CONFIGURATIONS)),b=JSON.parse(y);for(let k of Object.keys(b))u[k]=b[k]}}catch(y){console.error("Failed to parse runtime configuration",y)}this.config=p??{},this.build=s,this.runtime=u,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var _1r=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ugt(a){return a.startsWith("__ZUPLO")||a.startsWith("ZUPLO_")?!_1r.includes(a)&&!a.startsWith("ZUPLO_PUBLIC_"):!1}t(Ugt,"isRestrictedEnvVariableName");function $gt(a){return!!a.startsWith("ZUPLO_")}t($gt,"isZuploReadableEnvVariableName");var JMr=new Proxy({},{get(a,s){let u=String(s);switch(u){case"ZUPLO_ENVIRONMENT_TYPE":return DT.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return DT.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return DT.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return DT.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return DT.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return DT.instance.build.BUILD_ID}if(!(Ugt(u)&&!$gt(u)))return DT.instance.runtime[u]}});function dG(a,s,u){return`_${zP(a+"_"+s+"_"+u)}`}t(dG,"getRawOperationDataIdentifierName");function p8e(a,s,u,p){return`_${zP(a.toLowerCase())}_`+s.toLowerCase()+"_"+u.toLowerCase()+`_${p.toLowerCase()}`}t(p8e,"getIdForParameterSchema");function d8e(a,s,u){return`_${zP(a.toLowerCase())}_`+s.toLowerCase()+`_rb_${zP(u.toLowerCase())}`}t(d8e,"getIdForRequestBodySchema");function mG(a,s){return`_${zP(a)}__${zP(s)}`}t(mG,"getIdForRefSchema");function zP(a){let s=[];for(let u=0;u<a.length;u++){let p=a.charCodeAt(u);p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122?s.push(a.charAt(u)):s.push("_")}return s.join("")}t(zP,"sanitizedIdentifierName");var Wbt=Pd(cyt(),1);import{findNodeAtLocation as fK,getNodeValue as S_e,printParseErrorCode as wwr}from"jsonc-parser";import hFe from"path";var DG=class{static{t(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(a,s,u,p,y,b){this.type=a,this.name=s,this.prefix=u,this.value=p,this.suffix=y,this.modifier=b}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},Bbr=/[$_\p{ID_Start}]/u,Ubr=/[$_\u200C\u200D\p{ID_Continue}]/u,G8e=".*";function $br(a,s){return(s?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(a)}t($br,"Re");function fyt(a,s=!1){let u=[],p=0;for(;p<a.length;){let y=a[p],b=t(function(k){if(!s)throw new TypeError(k);u.push({type:"INVALID_CHAR",index:p,value:a[p++]})},"c");if(y==="*"){u.push({type:"ASTERISK",index:p,value:a[p++]});continue}if(y==="+"||y==="?"){u.push({type:"OTHER_MODIFIER",index:p,value:a[p++]});continue}if(y==="\\"){u.push({type:"ESCAPED_CHAR",index:p++,value:a[p++]});continue}if(y==="{"){u.push({type:"OPEN",index:p,value:a[p++]});continue}if(y==="}"){u.push({type:"CLOSE",index:p,value:a[p++]});continue}if(y===":"){let k="",A=p+1;for(;A<a.length;){let M=a.substr(A,1);if(A===p+1&&Bbr.test(M)||A!==p+1&&Ubr.test(M)){k+=a[A++];continue}break}if(!k){b(`Missing parameter name at ${p}`);continue}u.push({type:"NAME",index:p,value:k}),p=A;continue}if(y==="("){let k=1,A="",M=p+1,U=!1;if(a[M]==="?"){b(`Pattern cannot start with "?" at ${M}`);continue}for(;M<a.length;){if(!$br(a[M],!1)){b(`Invalid character '${a[M]}' at ${M}.`),U=!0;break}if(a[M]==="\\"){A+=a[M++]+a[M++];continue}if(a[M]===")"){if(k--,k===0){M++;break}}else if(a[M]==="("&&(k++,a[M+1]!=="?")){b(`Capturing groups are not allowed at ${M}`),U=!0;break}A+=a[M++]}if(U)continue;if(k){b(`Unbalanced pattern at ${p}`);continue}if(!A){b(`Missing pattern at ${p}`);continue}u.push({type:"REGEX",index:p,value:A}),p=M;continue}u.push({type:"CHAR",index:p,value:a[p++]})}return u.push({type:"END",index:p,value:""}),u}t(fyt,"v");function _yt(a,s={}){let u=fyt(a);s.delimiter??="/#?",s.prefixes??="./";let p=`[^${NT(s.delimiter)}]+?`,y=[],b=0,k=0,A="",M=new Set,U=t(hr=>{if(k<u.length&&u[k].type===hr)return u[k++].value},"a"),re=t(()=>U("OTHER_MODIFIER")??U("ASTERISK"),"f"),Z=t(hr=>{let Sr=U(hr);if(Sr!==void 0)return Sr;let{type:Zt,index:lr}=u[k];throw new TypeError(`Unexpected ${Zt} at ${lr}, expected ${hr}`)},"d"),H=t(()=>{let hr="",Sr;for(;Sr=U("CHAR")??U("ESCAPED_CHAR");)hr+=Sr;return hr},"T"),Te=t(hr=>hr,"Se"),ge=s.encodePart||Te,ve="",dt=t(hr=>{ve+=hr},"U"),_t=t(()=>{ve.length&&(y.push(new DG(3,"","",ge(ve),"",3)),ve="")},"$"),Vt=t((hr,Sr,Zt,lr,Xt)=>{let ei=3;switch(Xt){case"?":ei=1;break;case"*":ei=0;break;case"+":ei=2;break}if(!Sr&&!Zt&&ei===3){dt(hr);return}if(_t(),!Sr&&!Zt){if(!hr)return;y.push(new DG(3,"","",ge(hr),"",ei));return}let fr;Zt?Zt==="*"?fr=G8e:fr=Zt:fr=p;let wi=2;fr===p?(wi=1,fr=""):fr===G8e&&(wi=0,fr="");let un;if(Sr?un=Sr:Zt&&(un=b++),M.has(un))throw new TypeError(`Duplicate name '${un}'.`);M.add(un),y.push(new DG(wi,un,ge(hr),fr,ge(lr),ei))},"V");for(;k<u.length;){let hr=U("CHAR"),Sr=U("NAME"),Zt=U("REGEX");if(!Sr&&!Zt&&(Zt=U("ASTERISK")),Sr||Zt){let Xt=hr??"";s.prefixes.indexOf(Xt)===-1&&(dt(Xt),Xt=""),_t();let ei=re();Vt(Xt,Sr,Zt,"",ei);continue}let lr=hr??U("ESCAPED_CHAR");if(lr){dt(lr);continue}if(U("OPEN")){let Xt=H(),ei=U("NAME"),fr=U("REGEX");!ei&&!fr&&(fr=U("ASTERISK"));let wi=H();Z("CLOSE");let un=re();Vt(Xt,ei,fr,wi,un);continue}_t(),Z("END")}return y}t(_yt,"D");function NT(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(NT,"S");function lyt(a){return a&&a.ignoreCase?"ui":"u"}t(lyt,"X");function Jbr(a,s,u){return pyt(_yt(a,u),s,u)}t(Jbr,"Z");function _j(a){switch(a){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}t(_j,"k");function pyt(a,s,u={}){u.delimiter??="/#?",u.prefixes??="./",u.sensitive??=!1,u.strict??=!1,u.end??=!0,u.start??=!0,u.endsWith="";let p=u.start?"^":"";for(let A of a){if(A.type===3){A.modifier===3?p+=NT(A.value):p+=`(?:${NT(A.value)})${_j(A.modifier)}`;continue}s&&s.push(A.name);let M=`[^${NT(u.delimiter)}]+?`,U=A.value;if(A.type===1?U=M:A.type===0&&(U=G8e),!A.prefix.length&&!A.suffix.length){A.modifier===3||A.modifier===1?p+=`(${U})${_j(A.modifier)}`:p+=`((?:${U})${_j(A.modifier)})`;continue}if(A.modifier===3||A.modifier===1){p+=`(?:${NT(A.prefix)}(${U})${NT(A.suffix)})`,p+=_j(A.modifier);continue}p+=`(?:${NT(A.prefix)}`,p+=`((?:${U})(?:`,p+=NT(A.suffix),p+=NT(A.prefix),p+=`(?:${U}))*)${NT(A.suffix)})`,A.modifier===0&&(p+="?")}let y=`[${NT(u.endsWith)}]|$`,b=`[${NT(u.delimiter)}]`;if(u.end)return u.strict||(p+=`${b}?`),u.endsWith.length?p+=`(?=${y})`:p+="$",new RegExp(p,lyt(u));u.strict||(p+=`(?:${b}(?=${y}))?`);let k=!1;if(a.length){let A=a[a.length-1];A.type===3&&A.modifier===3&&(k=u.delimiter.indexOf(A)>-1)}return k||(p+=`(?=${b}|${y})`),new RegExp(p,lyt(u))}t(pyt,"F");var E4={delimiter:"",prefixes:"",sensitive:!0,strict:!0},qbr={delimiter:".",prefixes:"",sensitive:!0,strict:!0},zbr={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function Vbr(a,s){return a.length?a[0]==="/"?!0:!s||a.length<2?!1:(a[0]=="\\"||a[0]=="{")&&a[1]=="/":!1}t(Vbr,"J");function dyt(a,s){return a.startsWith(s)?a.substring(s.length,a.length):a}t(dyt,"Q");function Wbr(a,s){return a.endsWith(s)?a.substr(0,a.length-s.length):a}t(Wbr,"Ee");function myt(a){return!a||a.length<2?!1:a[0]==="["||(a[0]==="\\"||a[0]==="{")&&a[1]==="["}t(myt,"W");var hyt=["ftp","file","http","https","ws","wss"];function gyt(a){if(!a)return!0;for(let s of hyt)if(a.test(s))return!0;return!1}t(gyt,"N");function Hbr(a,s){if(a=dyt(a,"#"),s||a==="")return a;let u=new URL("https://example.com");return u.hash=a,u.hash?u.hash.substring(1,u.hash.length):""}t(Hbr,"te");function Gbr(a,s){if(a=dyt(a,"?"),s||a==="")return a;let u=new URL("https://example.com");return u.search=a,u.search?u.search.substring(1,u.search.length):""}t(Gbr,"re");function Kbr(a,s){return s||a===""?a:myt(a)?byt(a):vyt(a)}t(Kbr,"ne");function Ybr(a,s){if(s||a==="")return a;let u=new URL("https://example.com");return u.password=a,u.password}t(Ybr,"se");function Xbr(a,s){if(s||a==="")return a;let u=new URL("https://example.com");return u.username=a,u.username}t(Xbr,"ie");function Qbr(a,s,u){if(u||a==="")return a;if(s&&!hyt.includes(s))return new URL(`${s}:${a}`).pathname;let p=a[0]=="/";return a=new URL(p?a:"/-"+a,"https://example.com").pathname,p||(a=a.substring(2,a.length)),a}t(Qbr,"ae");function Zbr(a,s,u){return yyt(s)===a&&(a=""),u||a===""?a:Syt(a)}t(Zbr,"oe");function eSr(a,s){return a=Wbr(a,":"),s||a===""?a:K8e(a)}t(eSr,"ce");function yyt(a){switch(a){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}t(yyt,"_");function K8e(a){if(a==="")return a;if(/^[-+.A-Za-z0-9]*$/.test(a))return a.toLowerCase();throw new TypeError(`Invalid protocol '${a}'.`)}t(K8e,"y");function tSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.username=a,s.username}t(tSr,"le");function rSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.password=a,s.password}t(rSr,"fe");function vyt(a){if(a==="")return a;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(a))throw new TypeError(`Invalid hostname '${a}'`);let s=new URL("https://example.com");return s.hostname=a,s.hostname}t(vyt,"z");function byt(a){if(a==="")return a;if(/[^0-9a-fA-F[\]:]/g.test(a))throw new TypeError(`Invalid IPv6 hostname '${a}'`);return a.toLowerCase()}t(byt,"j");function Syt(a){if(a===""||/^[0-9]*$/.test(a)&&parseInt(a)<=65535)return a;throw new TypeError(`Invalid port '${a}'.`)}t(Syt,"K");function nSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.pathname=a[0]!=="/"?"/-"+a:a,a[0]!=="/"?s.pathname.substring(2,s.pathname.length):s.pathname}t(nSr,"he");function iSr(a){return a===""?a:new URL(`data:${a}`).pathname}t(iSr,"ue");function sSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.search=a,s.search.substring(1,s.search.length)}t(sSr,"de");function aSr(a){if(a==="")return a;let s=new URL("https://example.com");return s.hash=a,s.hash.substring(1,s.hash.length)}t(aSr,"pe");var oSr=class{static{t(this,"H")}#t;#r=[];#i={};#e=0;#a=1;#m=0;#o=0;#u=0;#c=0;#l=!1;constructor(a){this.#t=a}get result(){return this.#i}parse(){for(this.#r=fyt(this.#t,!0);this.#e<this.#r.length;this.#e+=this.#a){if(this.#a=1,this.#r[this.#e].type==="END"){if(this.#o===0){this.#y(),this.#E()?this.#n(9,1):this.#_()?this.#n(8,1):this.#n(7,0);continue}else if(this.#o===2){this.#p(5);continue}this.#n(10,0);break}if(this.#u>0)if(this.#s())this.#u-=1;else continue;if(this.#D()){this.#u+=1;continue}switch(this.#o){case 0:this.#g()&&this.#p(1);break;case 1:if(this.#g()){this.#I();let a=7,s=1;this.#w()?(a=2,s=3):this.#l&&(a=2),this.#n(a,s)}break;case 2:this.#C()?this.#p(3):(this.#x()||this.#_()||this.#E())&&this.#p(5);break;case 3:this.#T()?this.#n(4,1):this.#C()&&this.#n(5,1);break;case 4:this.#C()&&this.#n(5,1);break;case 5:this.#N()?this.#c+=1:this.#b()&&(this.#c-=1),this.#k()&&!this.#c?this.#n(6,1):this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 6:this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 7:this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 8:this.#E()&&this.#n(9,1);break;case 9:break;case 10:break}}this.#i.hostname!==void 0&&this.#i.port===void 0&&(this.#i.port="")}#n(a,s){switch(this.#o){case 0:break;case 1:this.#i.protocol=this.#S();break;case 2:break;case 3:this.#i.username=this.#S();break;case 4:this.#i.password=this.#S();break;case 5:this.#i.hostname=this.#S();break;case 6:this.#i.port=this.#S();break;case 7:this.#i.pathname=this.#S();break;case 8:this.#i.search=this.#S();break;case 9:this.#i.hash=this.#S();break;case 10:break}this.#o!==0&&a!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(a)&&(this.#i.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(a)&&(this.#i.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&a===9&&(this.#i.search??="")),this.#v(a,s)}#v(a,s){this.#o=a,this.#m=this.#e+s,this.#e+=s,this.#a=0}#y(){this.#e=this.#m,this.#a=0}#p(a){this.#y(),this.#o=a}#d(a){return a<0&&(a=this.#r.length-a),a<this.#r.length?this.#r[a]:this.#r[this.#r.length-1]}#h(a,s){let u=this.#d(a);return u.value===s&&(u.type==="CHAR"||u.type==="ESCAPED_CHAR"||u.type==="INVALID_CHAR")}#g(){return this.#h(this.#e,":")}#w(){return this.#h(this.#e+1,"/")&&this.#h(this.#e+2,"/")}#C(){return this.#h(this.#e,"@")}#T(){return this.#h(this.#e,":")}#k(){return this.#h(this.#e,":")}#x(){return this.#h(this.#e,"/")}#_(){if(this.#h(this.#e,"?"))return!0;if(this.#r[this.#e].value!=="?")return!1;let a=this.#d(this.#e-1);return a.type!=="NAME"&&a.type!=="REGEX"&&a.type!=="CLOSE"&&a.type!=="ASTERISK"}#E(){return this.#h(this.#e,"#")}#D(){return this.#r[this.#e].type=="OPEN"}#s(){return this.#r[this.#e].type=="CLOSE"}#N(){return this.#h(this.#e,"[")}#b(){return this.#h(this.#e,"]")}#S(){let a=this.#r[this.#e],s=this.#d(this.#m).index;return this.#t.substring(s,a.index)}#I(){let a={};Object.assign(a,E4),a.encodePart=K8e;let s=Jbr(this.#S(),void 0,a);this.#l=gyt(s)}},H8e=["protocol","username","password","hostname","port","pathname","search","hash"],x4="*";function uyt(a,s){if(typeof a!="string")throw new TypeError("parameter 1 is not of type 'string'.");let u=new URL(a,s);return{protocol:u.protocol.substring(0,u.protocol.length-1),username:u.username,password:u.password,hostname:u.hostname,port:u.port,pathname:u.pathname,search:u.search!==""?u.search.substring(1,u.search.length):void 0,hash:u.hash!==""?u.hash.substring(1,u.hash.length):void 0}}t(uyt,"ge");function GP(a,s){return s?wG(a):a}t(GP,"b");function kG(a,s,u){let p;if(typeof s.baseURL=="string")try{p=new URL(s.baseURL),s.protocol===void 0&&(a.protocol=GP(p.protocol.substring(0,p.protocol.length-1),u)),!u&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&(a.username=GP(p.username,u)),!u&&s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.username===void 0&&s.password===void 0&&(a.password=GP(p.password,u)),s.protocol===void 0&&s.hostname===void 0&&(a.hostname=GP(p.hostname,u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&(a.port=GP(p.port,u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&(a.pathname=GP(p.pathname,u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&(a.search=GP(p.search.substring(1,p.search.length),u)),s.protocol===void 0&&s.hostname===void 0&&s.port===void 0&&s.pathname===void 0&&s.search===void 0&&s.hash===void 0&&(a.hash=GP(p.hash.substring(1,p.hash.length),u))}catch{throw new TypeError(`invalid baseURL '${s.baseURL}'.`)}if(typeof s.protocol=="string"&&(a.protocol=eSr(s.protocol,u)),typeof s.username=="string"&&(a.username=Xbr(s.username,u)),typeof s.password=="string"&&(a.password=Ybr(s.password,u)),typeof s.hostname=="string"&&(a.hostname=Kbr(s.hostname,u)),typeof s.port=="string"&&(a.port=Zbr(s.port,a.protocol,u)),typeof s.pathname=="string"){if(a.pathname=s.pathname,p&&!Vbr(a.pathname,u)){let y=p.pathname.lastIndexOf("/");y>=0&&(a.pathname=GP(p.pathname.substring(0,y+1),u)+a.pathname)}a.pathname=Qbr(a.pathname,a.protocol,u)}return typeof s.search=="string"&&(a.search=Gbr(s.search,u)),typeof s.hash=="string"&&(a.hash=Hbr(s.hash,u)),a}t(kG,"w");function wG(a){return a.replace(/([+*?:{}()\\])/g,"\\$1")}t(wG,"C");function cSr(a){return a.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(cSr,"Oe");function lSr(a,s){s.delimiter??="/#?",s.prefixes??="./",s.sensitive??=!1,s.strict??=!1,s.end??=!0,s.start??=!0,s.endsWith="";let u=".*",p=`[^${cSr(s.delimiter)}]+?`,y=/[$_\u200C\u200D\p{ID_Continue}]/u,b="";for(let k=0;k<a.length;++k){let A=a[k];if(A.type===3){if(A.modifier===3){b+=wG(A.value);continue}b+=`{${wG(A.value)}}${_j(A.modifier)}`;continue}let M=A.hasCustomName(),U=!!A.suffix.length||!!A.prefix.length&&(A.prefix.length!==1||!s.prefixes.includes(A.prefix)),re=k>0?a[k-1]:null,Z=k<a.length-1?a[k+1]:null;if(!U&&M&&A.type===1&&A.modifier===3&&Z&&!Z.prefix.length&&!Z.suffix.length)if(Z.type===3){let H=Z.value.length>0?Z.value[0]:"";U=y.test(H)}else U=!Z.hasCustomName();if(!U&&!A.prefix.length&&re&&re.type===3){let H=re.value[re.value.length-1];U=s.prefixes.includes(H)}U&&(b+="{"),b+=wG(A.prefix),M&&(b+=`:${A.name}`),A.type===2?b+=`(${A.value})`:A.type===1?M||(b+=`(${p})`):A.type===0&&(!M&&(!re||re.type===3||re.modifier!==3||U||A.prefix!=="")?b+="*":b+=`(${u})`),A.type===1&&M&&A.suffix.length&&y.test(A.suffix[0])&&(b+="\\"),b+=wG(A.suffix),U&&(b+="}"),A.modifier!==3&&(b+=_j(A.modifier))}return b}t(lSr,"ke");var Tyt=class{static{t(this,"me")}#t;#r={};#i={};#e={};#a={};#m=!1;constructor(a={},s,u){try{let p;if(typeof s=="string"?p=s:u=s,typeof a=="string"){let A=new oSr(a);if(A.parse(),a=A.result,p===void 0&&typeof a.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");a.baseURL=p}else{if(!a||typeof a!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(p)throw new TypeError("parameter 1 is not of type 'string'.")}typeof u>"u"&&(u={ignoreCase:!1});let y={ignoreCase:u.ignoreCase===!0},b={pathname:x4,protocol:x4,username:x4,password:x4,hostname:x4,port:x4,search:x4,hash:x4};this.#t=kG(b,a,!0),yyt(this.#t.protocol)===this.#t.port&&(this.#t.port="");let k;for(k of H8e){if(!(k in this.#t))continue;let A={},M=this.#t[k];switch(this.#i[k]=[],k){case"protocol":Object.assign(A,E4),A.encodePart=K8e;break;case"username":Object.assign(A,E4),A.encodePart=tSr;break;case"password":Object.assign(A,E4),A.encodePart=rSr;break;case"hostname":Object.assign(A,qbr),myt(M)?A.encodePart=byt:A.encodePart=vyt;break;case"port":Object.assign(A,E4),A.encodePart=Syt;break;case"pathname":gyt(this.#r.protocol)?(Object.assign(A,zbr,y),A.encodePart=nSr):(Object.assign(A,E4,y),A.encodePart=iSr);break;case"search":Object.assign(A,E4,y),A.encodePart=sSr;break;case"hash":Object.assign(A,E4,y),A.encodePart=aSr;break}try{this.#a[k]=_yt(M,A),this.#r[k]=pyt(this.#a[k],this.#i[k],A),this.#e[k]=lSr(this.#a[k],A),this.#m=this.#m||this.#a[k].some(U=>U.type===2)}catch{throw new TypeError(`invalid ${k} pattern '${this.#t[k]}'.`)}}}catch(p){throw new TypeError(`Failed to construct 'URLPattern': ${p.message}`)}}test(a={},s){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return!1;try{typeof a=="object"?u=kG(u,a,!1):u=kG(u,uyt(a,s),!1)}catch{return!1}let p;for(p of H8e)if(!this.#r[p].exec(u[p]))return!1;return!0}exec(a={},s){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof a!="string"&&s)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof a>"u")return;try{typeof a=="object"?u=kG(u,a,!1):u=kG(u,uyt(a,s),!1)}catch{return null}let p={};s?p.inputs=[a,s]:p.inputs=[a];let y;for(y of H8e){let b=this.#r[y].exec(u[y]);if(!b)return null;let k={};for(let[A,M]of this.#i[y].entries())if(typeof M=="string"||typeof M=="number"){let U=b[A+1];k[M]=U}p[y]={input:u[y]??"",groups:k}}return p}static compareComponent(a,s,u){let p=t((A,M)=>{for(let U of["type","modifier","prefix","value","suffix"]){if(A[U]<M[U])return-1;if(A[U]!==M[U])return 1}return 0},"o"),y=new DG(3,"","","","",3),b=new DG(0,"","","","",3),k=t((A,M)=>{let U=0;for(;U<Math.min(A.length,M.length);++U){let re=p(A[U],M[U]);if(re)return re}return A.length===M.length?0:p(A[U]??y,M[U]??y)},"s");return!s.#e[a]&&!u.#e[a]?0:s.#e[a]&&!u.#e[a]?k(s.#a[a],[b]):!s.#e[a]&&u.#e[a]?k([b],u.#a[a]):k(s.#a[a],u.#a[a])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#m}};globalThis.URLPattern||(globalThis.URLPattern=Tyt);import{AssertionError as uSr}from"assert";function o7(a,s){if(a===!1)throw new uSr({message:s})}t(o7,"assert");var vc;(function(a){a.Object="Object",a.Property="Property",a.Array="Array",a.Literal="Literal",a.TemplateString="TemplateString",a.Identifier="Identifier",a.FunctionCall="FunctionCall",a.FunctionBody="FunctionBody"})(vc||(vc={}));function PG(a){return a.type===vc.Object}t(PG,"isAstObject");function KP(a){return a.type===vc.Property}t(KP,"isAstProperty");function xyt(a){return a.type===vc.Array}t(xyt,"isAstArray");function pj(a){return a.type===vc.Literal}t(pj,"isAstLiteral");import{visit as fSr}from"jsonc-parser";var _Sr={DEFAULT:{allowTrailingComma:!1}};function AG(a,s=[],u=_Sr.DEFAULT){let p={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(M){p.type==="property"&&(p.length=M-p.offset,p=p.parent)}t(y,"ensurePropertyComplete");function b(M){return p.children?.push(M),M}t(b,"onValue"),fSr(a,{onObjectBegin:t((M,U,re)=>{p=b({type:"object",offset:M,length:-1,line:U+1,column:re+1,parent:p,children:[]})},"onObjectBegin"),onObjectProperty:t((M,U,re,Z,H)=>{p=b({type:"property",offset:U,length:-1,line:Z+1,column:H+1,parent:p,children:[]}),p.children?.push({type:"string",value:M,offset:U,length:re,line:Z,column:H,parent:p})},"onObjectProperty"),onObjectEnd:t((M,U)=>{y(M+U),p.length=M+U-p.offset,p=p.parent,y(M+U)},"onObjectEnd"),onArrayBegin:t((M,U,re,Z)=>{p=b({type:"array",offset:M,length:-1,line:re+1,column:Z+1,parent:p,children:[]})},"onArrayBegin"),onArrayEnd:t((M,U)=>{p.length=M+U-p.offset,p=p.parent,y(M+U)},"onArrayEnd"),onLiteralValue:t((M,U,re,Z,H)=>{b({type:pSr(M),offset:U,length:re,line:Z+1,column:H+1,parent:p,value:M}),y(U+re)},"onLiteralValue"),onSeparator:t((M,U)=>{p.type==="property"&&(M===":"?p.colonOffset=U:M===","&&y(U))},"onSeparator"),onError:t((M,U,re,Z,H)=>{s.push({error:M,offset:U,length:re,line:Z+1,column:H+1})},"onError")},u);let A=p.children[0];return A&&delete A.parent,A}t(AG,"parse");function pSr(a){switch(typeof a){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(a){if(Array.isArray(a))return"array"}else return"null";return"object"}default:return"null"}}t(pSr,"getNodeType");var NG=class{static{t(this,"AstAdapter")}parse(s){let p=AG(s,[]);if(p)return this.parseNode(p,void 0);throw new Error("Failed to parse JSON")}convert(s){return this.parseNode(s,void 0)}parseNode(s,u){switch(s.type){case"object":return this.createObject(s,u);case"array":return this.createArray(s,u);case"property":return this.createProperty(s,u);case"string":return this.createLiteral(s,u);case"number":return this.createLiteral(s,u);case"boolean":return this.createLiteral(s,u);case"null":return this.createLiteral(s,u)}}createLiteral(s,u){return{type:vc.Literal,location:{line:s.line,column:s.column},parent:u,value:s.type==="null"?null:s.value}}createObject(s,u){let p={type:vc.Object,children:[],parent:u,location:{line:s.line,column:s.column}};return s.children?.forEach(y=>{p.children.push(this.parseNode(y,p))}),p}createProperty(s,u){o7(s.children?.length===2,"Invalid property node");let p={type:vc.Property,location:{line:s.line,column:s.column},parent:u,name:null,value:null};return p.name={value:s.children[0].value,location:{line:s.line,column:s.column},type:vc.Identifier,parent:p},p.value=this.parseNode(s.children[1],p),p}createArray(s,u){let p={type:vc.Array,location:{line:s.line,column:s.column},parent:u,children:[]};return s.children?.forEach(y=>p.children.push(this.parseNode(y,p))),p}};var IT={createLiteral:t((a,s)=>({type:vc.Literal,parent:s,value:a}),"createLiteral"),createTemplateString:t((a,s)=>({type:vc.TemplateString,parent:s,value:a}),"createTemplateString"),createIdentifier:t((a,s)=>({type:vc.Identifier,value:a,parent:s}),"createIdentifier"),createProperty:t((a,s,u)=>{let p={type:vc.Property,parent:u,name:null,value:s};return p.name={value:a,type:vc.Identifier,parent:p},p.value.parent=p,p},"createProperty"),createArrayOfLiterals:t((a,s)=>{let u={type:vc.Array,parent:s,children:[]};for(let p of a)u.children.push(IT.createLiteral(p,u));return u},"createArrayOfLiterals")};var IG=class{static{t(this,"SourceGenerator")}generate(s){let u=[];return this.generateSource(u,s),u.join("")}generateSource(s,u){switch(u.type){case vc.Array:return this.generateArray(s,u);case vc.Object:return this.generateObject(s,u);case vc.Property:return this.generateProperty(s,u);case vc.Literal:return this.generateLiteral(s,u);case vc.FunctionCall:return this.generateFunctionCall(s,u);case vc.Identifier:return this.generateIdentifier(s,u);case vc.FunctionBody:return this.generateFunctionBody(s,u);case vc.TemplateString:return this.generateTemplateString(s,u)}}generateArray(s,u){s.push("["),u.children.map(p=>{this.generateSource(s,p),s.push(",")}),s.push("]")}generateObject(s,u){s.push("{"),u.children.forEach(p=>{this.generateSource(s,p),s.push(",")}),s.push("}")}generateProperty(s,u){let p=u.name.value,y=p.search(/(\/|\\|-|\+|@|#|%|\^|&|\*|:|\.)/g)<0?p:`'${p}'`;s.push(y),s.push(":"),this.generateSource(s,u.value)}generateFunctionCall(s,u){s.push(u.name.value),s.push("("),u.children.forEach((p,y,b)=>{this.generateSource(s,p),y<b.length&&s.push(",")}),s.push(")")}generateFunctionBody(s,u){s.push(u.value)}generateTemplateString(s,u){s.push("`"),s.push(u.value.replaceAll("`","\\`")),s.push("`")}generateLiteral(s,u){if(u.value===null)return s.push("null");switch(typeof u.value){case"number":case"boolean":return s.push(`${u.value}`);case"string":{let p=u.value,y=JSON.stringify(p);return s.push(`${y}`)}}}generateIdentifier(s,u){s.push(u.value)}};import{parse as dSr}from"@swc/core";import mSr from"fs/promises";var Eyt=t(async a=>{let s=new Set;try{let u=await mSr.readFile(a,"utf-8");(await dSr(u,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?s.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?s.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&s.add(y.declaration.declarations[0].id.value)})}catch{return null}return s},"getJSFileExports");var Cyt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var Y8e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var kyt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var X8e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var Q8e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler","version"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},version:{type:"string",pattern:"^[0-9a-z-]+$"},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var wyt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/routes.schema.json",title:"Route Config File",type:"object",additionalProperties:!1,required:["routes","versions"],$defs:{info:{type:"object",required:["title","version"],properties:{title:{type:"string"},summary:{type:"string"},description:{type:"string"},termsOfService:{type:"string",format:"uri"},version:{type:"string"}}},versionData:{type:"object",required:["name","pathPrefix"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},pathPrefix:{type:"string",pattern:"(^$|^/[^\\s]*$)"},info:{$ref:"#/$defs/info"},openApiFile:{description:"The project relative path to the OpenAPI spec.",type:"string"},excludeFromOpenApi:{type:"boolean",description:"If false, OpenAPI documentation will not be generated for this version. If openApiFile is set this setting is ignored."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."}}}},properties:{$schema:{type:"string"},versions:{type:"array",minItems:1,items:{$ref:"#/$defs/versionData"}},routes:{type:"array",minItems:0,items:{$ref:"route-configuration.schema.json"}},policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}},requestErrorHandler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"}}};var jbt=Pd(obt(),1),Bbt=Pd(Mbt(),1);var p_e=class a{static{t(this,"JsonValidator")}static#t=new a;static get instance(){return a.#t}ajv;constructor(){this.ajv=new Bbt.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,jbt.default)(this.ajv,{mode:"fast"})}addSchema(s,u){this.ajv.addSchema(s,u)}compile(s){let u=this.ajv.compile(s);return t(y=>({isValid:u(y),errors:this.toSimpleErrors(u.errors,y),warnings:[]}),"validator")}toSimpleErrors(s,u){let p=[];return s?.forEach(y=>{y.keyword==="enum"&&y.params.allowedValues&&Array.isArray(y.params.allowedValues)&&(y.message+=`; ${y.params.allowedValues.join(", ")}`),y.instancePath&&(y.instancePath=y.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let b={details:{}},k=y.instancePath.split("/");if(k.length>2){let M=k[1],U=k[2]?parseInt(k[2]):0,re=k[3],Z=isNaN(U)?void 0:u[M][U][re];b={details:{property:M,index:U,field:re,fieldValue:Z}}}if(y.keyword==="required"&&y.params.missingProperty&&y.instancePath&&(y.message=`A 'path' is missing required property '${y.params.missingProperty}'`),y.keyword==="additionalProperties"&&y.params.additionalProperty&&y.instancePath&&(y.message=`A 'path' should NOT include property '${y.params.additionalProperty}'`),y.keyword==="type"&&y.params.type&&y.instancePath){let M=y.instancePath.split("/"),U=M[M.length-1];y.message=`Value of property '${U}' must be '${y.params.type}'`}let A=Object.assign(y,b);p.push(A)}),p}};var eA=p_e.instance;eA.addSchema(wyt,"routes.schema.json");eA.addSchema(Q8e,"route-configuration.schema.json");eA.addSchema(kyt,"policy-configuration.schema.json");eA.addSchema(Y8e,"policies.schema.json");eA.addSchema(X8e,"open-api-route-configuration.schema.json");eA.addSchema(Cyt,"fragments.schema.json");var bwr=eA.compile(Q8e),Ubt=eA.compile(X8e),_Fe=eA.compile(Y8e);var d_e=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(s){return this.results=_Fe(s),this.results}};var m_e=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(s){return this.results=Ubt(s),this.results}};import Twr from"path";var pFe=/\$import\((.*)\)/,h_e=/\$env\((.*?)\)/g;var tA=class extends Error{static{t(this,"CodeGenError")}location;constructor(s,u,p,y){super(s),this.location={file:u,namespace:"",line:p?p.line:0,column:p?p.column:0,length:0,lineText:y??"",suggestion:""}}},Swr=t(a=>{let s=[],u=a;for(;u.parent;)s.push(u),u=u.parent;return s.reverse()},"invertTree"),O4=t((a,s)=>{if(!a)return!1;let u=Swr(a);return s.split("/").every((b,k)=>{let A=u[k];return A?b==="*"||KP(A)&&A.name.value===b?!0:b==="{}"?A.type===vc.Object:b==="[]"?A.type===vc.Array:!1:!1})},"testPosition");var g_e=class{static{t(this,"AstTransformer")}errors=[];transform(s){return this.visitor(s),s}visitor(s){this.visit(s),PG(s)?s.children.forEach(u=>{this.visitor(u)}):xyt(s)?s.children.forEach(u=>{this.visitor(u)}):KP(s)&&this.visitor(s.value)}},$bt=t((a,s,u)=>p=>{if(!KP(p)||!pj(p.value)||typeof p.value.value!="string")return;if(!a.some(b=>O4(p,b))){h_e.test(p.value.value)&&s.push(new tA("An $env() statement is not expected at this location.",u,p.location,p.value.value));return}let y=new RegExp(h_e).exec(p.value.value);if(y?.length===2&&y[0]===p.value.value){let b={type:vc.FunctionBody,parent:null,value:`environment["${y[1]}"]`};p.value=b}else{let b=p.value.value.replaceAll(new RegExp(h_e),(k,A)=>`\${environment["${A}"] ? environment["${A}"] : ""}`);b!==p.value.value&&(p.value=IT.createTemplateString(b,p))}},"getEnvStatementTransformer");var uK="config/routes.json",xwr=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*","corsPolicies/[]/{}/*"],Ewr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Jbt=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],Cwr="handler/{}/options/{}/rewritePattern",kwr="handler/{}/options/{}/baseUrl",y_e=class extends g_e{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(s){this.addedImports.has(s)||this.addedImports.set(s,`__import${this.importCount++}`);let u=this.addedImports.get(s);if(!u)throw new Error("Import name is undefined. This should not happen.");return u}getImports(){let s=[];return this.addedImports.forEach((u,p)=>{s.push({name:u,path:p})}),s}visit(s){this.rewriteHandlerFunction(s),this.rewriteForwardFunction(s),this.replaceImportStatements(s),this.replaceEnvStatements(s)}rewriteHandlerFunction(s){if(!(!KP(s)||!pj(s.value)||typeof s.value.value!="string")&&O4(s,Cwr)){if(!s.parent||!PG(s.parent)){this.errors.push(new tA("Invalid node, expected object",uK,s.parent?s.parent.location:s.location,void 0));return}let u=s.value.value,p={type:vc.FunctionBody,parent:null,value:qbt(u)},y=IT.createProperty("__rewriteFunction",p,s);s.parent.children.push(y)}}rewriteForwardFunction(s){if(!(!KP(s)||!pj(s.value)||typeof s.value.value!="string")&&O4(s,kwr)){if(!s.parent||!PG(s.parent)){this.errors.push(new tA("Invalid node, expected object",uK,s.parent?s.parent.location:s.location,void 0));return}let u=s.value.value,p={type:vc.FunctionBody,parent:null,value:qbt(u)},y=IT.createProperty("__rewriteFunction",p,s);s.parent.children.push(y)}}replaceImportStatements(s){if(!KP(s)||!pj(s.value))return;let u=s.value.value;if(typeof u!="string")return;if(!Ewr.some(A=>O4(s,A))&&!Jbt.some(A=>O4(s,A))){if(pFe.test(u)){if(s.name.value==="$ref")return;this.errors.push(new tA("An $import() statement is not expected at this location.",uK,s.location,u))}return}let p=pFe.exec(u);if(Jbt.some(A=>O4(s,A))&&!p)return;if(!p){this.errors.push(new tA("Invalid $import() statement",uK,s.location,u));return}let y=p[1];y.startsWith(".")&&(y=Twr.join("..",y));let b=this.getImportName(y),k={type:vc.Identifier,parent:s.parent,value:b};s.value=k}replaceEnvStatements=$bt(xwr,this.errors,uK)};function qbt(a){return`(request, context) => {
711
711
  const { params, url, query, method, headers } = request;
712
712
  const { host, hostname, origin, pathname, port, search } = new URL(url);
713
713
  const e = encodeURIComponent;
package/index.minified.js CHANGED
@@ -706,7 +706,7 @@ export default {
706
706
  `),pluginName:EO,helpUrl:"https://zuplo.com/docs/articles/tsconfig"}),{warnings:Sr,errors:[]}}catch(b){a.error(b);let k={message:`Error validating tsconfig.json : ${b.message}`,severity:"error",pluginName:EO};return{warnings:[],errors:[k]}}})},"validateTSConfig");import{parse as dir}from"@swc/core";import pir from"vm";var{hasOwnProperty:Qv}=Object.prototype;function CO(s,a){return s=s.slice(),s.push(a),s}t(CO,"push");function iNe(s,a){return a=a.slice(),a.unshift(s),a}t(iNe,"unshift");var sNe=class extends Error{static{t(this,"NewError")}constructor(a){super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'),this.avoidNew=!0,this.value=a,this.name="NewError"}};function s_(s,a,u,p,g){if(!(this instanceof s_))try{return new s_(s,a,u,p,g)}catch(k){if(!k.avoidNew)throw k;return k.value}typeof s=="string"&&(g=p,p=u,u=a,a=s,s=null);let b=s&&typeof s=="object";if(s=s||{},this.json=s.json||u,this.path=s.path||a,this.resultType=s.resultType||"value",this.flatten=s.flatten||!1,this.wrap=Qv.call(s,"wrap")?s.wrap:!0,this.sandbox=s.sandbox||{},this.preventEval=s.preventEval||!1,this.parent=s.parent||null,this.parentProperty=s.parentProperty||null,this.callback=s.callback||p||null,this.otherTypeCallback=s.otherTypeCallback||g||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},s.autostart!==!1){let k={path:b?s.path:a};b?"json"in s&&(k.json=s.json):k.json=u;let A=this.evaluate(k);if(!A||typeof A!="object")throw new sNe(A);return A}}t(s_,"JSONPath");s_.prototype.evaluate=function(s,a,u,p){let g=this.parent,b=this.parentProperty,{flatten:k,wrap:A}=this;if(this.currResultType=this.resultType,this.currPreventEval=this.preventEval,this.currSandbox=this.sandbox,u=u||this.callback,this.currOtherTypeCallback=p||this.otherTypeCallback,a=a||this.json,s=s||this.path,s&&typeof s=="object"&&!Array.isArray(s)){if(!s.path&&s.path!=="")throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!Qv.call(s,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');({json:a}=s),k=Qv.call(s,"flatten")?s.flatten:k,this.currResultType=Qv.call(s,"resultType")?s.resultType:this.currResultType,this.currSandbox=Qv.call(s,"sandbox")?s.sandbox:this.currSandbox,A=Qv.call(s,"wrap")?s.wrap:A,this.currPreventEval=Qv.call(s,"preventEval")?s.preventEval:this.currPreventEval,u=Qv.call(s,"callback")?s.callback:u,this.currOtherTypeCallback=Qv.call(s,"otherTypeCallback")?s.otherTypeCallback:this.currOtherTypeCallback,g=Qv.call(s,"parent")?s.parent:g,b=Qv.call(s,"parentProperty")?s.parentProperty:b,s=s.path}if(g=g||null,b=b||null,Array.isArray(s)&&(s=s_.toPathString(s)),!s&&s!==""||!a)return;let M=s_.toPathArray(s);M[0]==="$"&&M.length>1&&M.shift(),this._hasParentSelector=null;let U=this._trace(M,a,["$"],g,b,u).filter(function(re){return re&&!re.isParentSelector});return U.length?!A&&U.length===1&&!U[0].hasArrExpr?this._getPreferredOutput(U[0]):U.reduce((re,Z)=>{let G=this._getPreferredOutput(Z);return k&&Array.isArray(G)?re=re.concat(G):re.push(G),re},[]):A?[]:void 0};s_.prototype._getPreferredOutput=function(s){let a=this.currResultType;switch(a){case"all":{let u=Array.isArray(s.path)?s.path:s_.toPathArray(s.path);return s.pointer=s_.toPointer(u),s.path=typeof s.path=="string"?s.path:s_.toPathString(s.path),s}case"value":case"parent":case"parentProperty":return s[a];case"path":return s_.toPathString(s[a]);case"pointer":return s_.toPointer(s.path);default:throw new TypeError("Unknown result type")}};s_.prototype._handleCallback=function(s,a,u){if(a){let p=this._getPreferredOutput(s);s.path=typeof s.path=="string"?s.path:s_.toPathString(s.path),a(p,u,s)}};s_.prototype._trace=function(s,a,u,p,g,b,k,A){let M;if(!s.length)return M={path:u,value:a,parent:p,parentProperty:g,hasArrExpr:k},this._handleCallback(M,b,"value"),M;let U=s[0],re=s.slice(1),Z=[];function G(Te){Array.isArray(Te)?Te.forEach(ge=>{Z.push(ge)}):Z.push(Te)}if(t(G,"addRet"),(typeof U!="string"||A)&&a&&Qv.call(a,U))G(this._trace(re,a[U],CO(u,U),a,U,b,k));else if(U==="*")this._walk(a,Te=>{G(this._trace(re,a[Te],CO(u,Te),a,Te,b,!0,!0))});else if(U==="..")G(this._trace(re,a,u,p,g,b,k)),this._walk(a,Te=>{typeof a[Te]=="object"&&G(this._trace(s.slice(),a[Te],CO(u,Te),a,Te,b,!0))});else{if(U==="^")return this._hasParentSelector=!0,{path:u.slice(0,-1),expr:re,isParentSelector:!0};if(U==="~")return M={path:CO(u,U),value:g,parent:p,parentProperty:null},this._handleCallback(M,b,"property"),M;if(U==="$")G(this._trace(re,a,u,null,null,b,k));else if(/^(-?\d*):(-?\d*):?(\d*)$/u.test(U))G(this._slice(U,re,a,u,p,g,b));else if(U.indexOf("?(")===0){if(this.currPreventEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");let Te=U.replace(/^\?\((.*?)\)$/u,"$1");this._walk(a,ge=>{this._eval(Te,a[ge],ge,u,p,g)&&G(this._trace(re,a[ge],CO(u,ge),a,ge,b,!0))})}else if(U[0]==="("){if(this.currPreventEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");G(this._trace(iNe(this._eval(U,a,u[u.length-1],u.slice(0,-1),p,g),re),a,u,p,g,b,k))}else if(U[0]==="@"){let Te=!1,ge=U.slice(1,-2);switch(ge){case"scalar":(!a||!["object","function"].includes(typeof a))&&(Te=!0);break;case"boolean":case"string":case"undefined":case"function":typeof a===ge&&(Te=!0);break;case"integer":Number.isFinite(a)&&!(a%1)&&(Te=!0);break;case"number":Number.isFinite(a)&&(Te=!0);break;case"nonFinite":typeof a=="number"&&!Number.isFinite(a)&&(Te=!0);break;case"object":a&&typeof a===ge&&(Te=!0);break;case"array":Array.isArray(a)&&(Te=!0);break;case"other":Te=this.currOtherTypeCallback(a,u,p,g);break;case"null":a===null&&(Te=!0);break;default:throw new TypeError("Unknown value type "+ge)}if(Te)return M={path:u,value:a,parent:p,parentProperty:g},this._handleCallback(M,b,"value"),M}else if(U[0]==="`"&&a&&Qv.call(a,U.slice(1))){let Te=U.slice(1);G(this._trace(re,a[Te],CO(u,Te),a,Te,b,k,!0))}else if(U.includes(",")){let Te=U.split(",");for(let ge of Te)G(this._trace(iNe(ge,re),a,u,p,g,b,!0))}else!A&&a&&Qv.call(a,U)&&G(this._trace(re,a[U],CO(u,U),a,U,b,k,!0))}if(this._hasParentSelector)for(let Te=0;Te<Z.length;Te++){let ge=Z[Te];if(ge&&ge.isParentSelector){let ve=this._trace(ge.expr,a,ge.path,p,g,b,k);if(Array.isArray(ve)){Z[Te]=ve[0];let dt=ve.length;for(let _t=1;_t<dt;_t++)Te++,Z.splice(Te,0,ve[_t])}else Z[Te]=ve}}return Z};s_.prototype._walk=function(s,a){if(Array.isArray(s)){let u=s.length;for(let p=0;p<u;p++)a(p)}else s&&typeof s=="object"&&Object.keys(s).forEach(u=>{a(u)})};s_.prototype._slice=function(s,a,u,p,g,b,k){if(!Array.isArray(u))return;let A=u.length,M=s.split(":"),U=M[2]&&Number.parseInt(M[2])||1,re=M[0]&&Number.parseInt(M[0])||0,Z=M[1]&&Number.parseInt(M[1])||A;re=re<0?Math.max(0,re+A):Math.min(A,re),Z=Z<0?Math.max(0,Z+A):Math.min(A,Z);let G=[];for(let Te=re;Te<Z;Te+=U)this._trace(iNe(Te,a),u,p,g,b,k,!0).forEach(ve=>{G.push(ve)});return G};s_.prototype._eval=function(s,a,u,p,g,b){this.currSandbox._$_parentProperty=b,this.currSandbox._$_parent=g,this.currSandbox._$_property=u,this.currSandbox._$_root=this.json,this.currSandbox._$_v=a;let k=s.includes("@path");k&&(this.currSandbox._$_path=s_.toPathString(p.concat([u])));let A="script:"+s;if(!s_.cache[A]){let M=s.replace(/@parentProperty/gu,"_$_parentProperty").replace(/@parent/gu,"_$_parent").replace(/@property/gu,"_$_property").replace(/@root/gu,"_$_root").replace(/@([.\s)[])/gu,"_$_v$1");k&&(M=M.replace(/@path/gu,"_$_path")),s_.cache[A]=new this.vm.Script(M)}try{return s_.cache[A].runInNewContext(this.currSandbox)}catch(M){throw new Error("jsonPath: "+M.message+": "+s)}};s_.cache={};s_.toPathString=function(s){let a=s,u=a.length,p="$";for(let g=1;g<u;g++)/^(~|\^|@.*?\(\))$/u.test(a[g])||(p+=/^[0-9*]+$/u.test(a[g])?"["+a[g]+"]":"['"+a[g]+"']");return p};s_.toPointer=function(s){let a=s,u=a.length,p="";for(let g=1;g<u;g++)/^(~|\^|@.*?\(\))$/u.test(a[g])||(p+="/"+a[g].toString().replace(/~/gu,"~0").replace(/\//gu,"~1"));return p};s_.toPathArray=function(s){let{cache:a}=s_;if(a[s])return a[s].concat();let u=[],g=s.replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu,";$&;").replace(/[['](\??\(.*?\))[\]']/gu,function(b,k){return"[#"+(u.push(k)-1)+"]"}).replace(/\[['"]([^'\]]*)['"]\]/gu,function(b,k){return"['"+k.replace(/\./gu,"%@%").replace(/~/gu,"%%@@%%")+"']"}).replace(/~/gu,";~;").replace(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu,";").replace(/%@%/gu,".").replace(/%%@@%%/gu,"~").replace(/(?:;)?(\^+)(?:;)?/gu,function(b,k){return";"+k.split("").join(";")+";"}).replace(/;;;|;;/gu,";..;").replace(/;$|'?\]|'$/gu,"").split(";").map(function(b){let k=b.match(/#(\d+)/u);return!k||!k[1]?b:u[k[1]]});return a[s]=g,a[s].concat()};s_.prototype.vm=pir;import mir from"fs/promises";import hir from"path";var tlt=t(async function({outputDirectory:s,logger:a}){return Lu.timeFn("Verify Worker output",async()=>{a.debug("Verify Worker output");let u=hir.join(s,"worker.js");try{if(await hc.fileExists(u)){let p=await mir.readFile(u,"utf-8"),g=await dir(p,{syntax:"ecmascript"}),b=s_({path:"$..callee[?(@property === 'value' && (@ === 'Function'|| @ === 'eval'))]^",json:g.body});if(b&&b.length>0)return{warnings:[{message:"We do not support the use of 'eval' or 'new Function(...)'",severity:"warning",pluginName:"verify-worker-output"}],errors:[]}}}catch(p){a.error(p);let g={message:`Error validating build output : ${p.message}`,severity:"error",pluginName:"verify-worker-output"};return{warnings:[],errors:[g]}}return{warnings:[],errors:[]}})},"verifyWorkerOutput");import*as syt from"esbuild";import{randomUUID as gir}from"crypto";var nI=class{static{t(this,"CompilerResult")}buildId;buildTime;buildTimeMs;errors;warnings;status;assets;metafile;constructor(a,u){this.buildId=u?.buildId??gir(),this.buildTime=u?.startBuildTime.toISOString(),this.buildTimeMs=u?.endBuildTime.getTime()-u?.startBuildTime.getTime(),this.errors=a.errors.map(p=>({message:p.text,severity:GW,...p})),this.warnings=a.warnings.map(p=>({message:p.text,severity:HW,...p})),a.metafile&&(this.metafile=a.metafile),this.status=lO,this.warnings&&this.warnings.length>0&&(this.status=B9),this.errors&&this.errors.length>0&&(this.status=Kv)}};var yir=!1;function uM(s,a){return{open:`\x1B[${s.join(";")}m`,close:`\x1B[${a}m`,regexp:new RegExp(`\\x1b\\[${a}m`,"g")}}t(uM,"code");function fM(s,a){return yir?`${a.open}${s.replace(a.regexp,a.open)}${a.close}`:s}t(fM,"run");function vir(s){return fM(s,uM([31],39))}t(vir,"red");function bir(s){return fM(s,uM([32],39))}t(bir,"green");function Sir(s){return fM(s,uM([33],39))}t(Sir,"yellow");function Tir(s){return fM(s,uM([34],39))}t(Tir,"blue");function xir(s){return fM(s,uM([35],39))}t(xir,"magenta");function Eir(s){return fM(s,uM([36],39))}t(Eir,"cyan");var eFr=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var rlt=[vir,bir,Sir,Tir,xir,Eir];function Cir(s){let a=0,u=s.length,p=0;if(u>0)for(;p<u;)a=(a<<5)-a+s.charCodeAt(p++)|0;return a}t(Cir,"hashCode");function nlt(s){let a=Math.abs(Cir(s));return rlt[a%rlt.length]}t(nlt,"generateColor");import{inspect as kir}from"util";function ilt(s,a,...u){let p=0,g=u.length,b=String(a).replace(/%[sdjoO%]/g,k=>{if(k==="%%")return"%";if(p>=g)return k;switch(k){case"%s":return String(u[p++]);case"%d":return Number(u[p++]).toString();case"%o":return s(u[p++]).split(`
707
707
  `).map(A=>A.trim()).join(" ");case"%O":return s(u[p++]);case"%j":try{return JSON.stringify(u[p++])}catch{return"[Circular]"}default:return k}});for(let k of u.splice(p))k===null||!(typeof k=="object"&&k!==null)?b+=" "+k:b+=" "+s(k);return b}t(ilt,"format");var slt=t((s,...a)=>ilt(kir,s,a),"format");var aNe=class{static{t(this,"Debugger")}manager;ns;color;last;enabled;constructor(a,u){this.manager=a,this.ns=u,this.color=nlt(u),this.last=0,this.enabled=a.enabled.some(p=>p.test(u))}log(...a){if(!this.enabled)return;let u,p=a[0];typeof p=="function"?u=p():u=String(p);let g=Date.now()-(this.last||Date.now());u=slt(u,...a);let b=`${this.color(this.ns)} ${u} ${this.color(`+${g}ms`)}`;console.log(b),this.last=Date.now()}},oNe=class{static{t(this,"DebugManager")}debuggers;enabled;constructor(a){this.debuggers=new Map,this.enabled=a??[]}};function wir(s){return!s||s.length===0?[]:(s=s.replace(/\s/g,"").replace(/\*/g,".+"),s.split(",").map(a=>new RegExp(`^${a}$`)))}t(wir,"extract");var jce;function alt(s){jce||(jce=new oNe(wir(process.env.DEBUG)));let a=new aNe(jce,s);return jce.debuggers.set(s,a),Object.assign(a.log.bind(a),{self:a})}t(alt,"debug");import dfe,{dirname as ryt}from"path";import{fileURLToPath as nyt}from"url";var cNe="no-remote-module";function olt({logger:s}){return{name:cNe,async setup(a){a.onResolve({filter:/^https?:\/\//},u=>(s.error(u,"User attempted to load a remote module"),{errors:[{text:`Remote modules are not supported. Attempted to load module ${u.path}`,detail:"InvalidRemoteModule",pluginName:cNe,location:{line:0,column:0,file:""}}],pluginName:cNe}))}}}t(olt,"blockRemoteModulePlugin");import clt from"fs/promises";import Bce from"path";import Dir from"prettier";var llt="/docs",Pir="/__zuplo/dev-portal";function Air(s){let a=s.trim().toLowerCase();return a.endsWith("/")&&(a=a.slice(0,-1)),a}t(Air,"normalizePathname");function Nir(s){let a={sitePathname:s?.sitePathname===Pir?llt:s?.sitePathname?Air(s.sitePathname):llt,enabled:s?s.enabled??!0:!1};return`const devPortal = ${JSON.stringify(a)};
708
708
  export default devPortal;`}t(Nir,"generateSource");function ult(s){return{name:"dev-portal-config",setup(a){a.onResolve({filter:/dev-portal.json$/},u=>({namespace:"dev-portal-json",path:Bce.isAbsolute(u.path)?u.path:Bce.join(u.resolveDir,u.path),pluginName:"dev-portal"})),a.onLoad({filter:/.*/,namespace:"dev-portal-json"},async u=>Lu.timeFn("Generating dev-portal.json data",async()=>{let p,g,b=[];if(await hc.fileExists(u.path)){g=await clt.readFile(u.path,"utf-8");try{p=JSON.parse(g)}catch{b.push({id:"dev-portal-build-error",text:"Could not parse dev-portal.json. Ensure that the file is valid JSON.",location:{file:"dev-portal.json",namespace:"dev-portal-json",line:1,column:0,length:0,lineText:"",suggestion:""},detail:"DevPortalValidationError",pluginName:"dev-portal",notes:[{text:"Could not parse dev-portal.json. Ensure that the file is valid JSON.",location:null}]})}}if(b&&b.length>0)throw b;let k;try{if(k=Nir(p),zm.DEBUG_BUILD_MODE&&k&&await hc.dirExists(s.sourceDirectory)){let A=await Dir.format(k,{parser:"babel"});await clt.writeFile(Bce.join(s.sourceDirectory,BN,"dev-portal.js"),A)}if(b&&b.length>0)throw b}catch(A){A.length>0?A.forEach(M=>{let U={id:"dev-portal-build-error",text:M.message,location:{file:"dev-portal.json",namespace:"dev-portal-json",line:1,column:0,length:0,lineText:"issue",suggestion:""},detail:"DevPortalValidationError",pluginName:"dev-portal",notes:[{text:M.message,location:null}]};b.push(U)}):b.push({id:"dev-portal-build-error",text:A.message,location:{file:"dev-portal.json",namespace:"dev-portal-json",line:1,column:0,length:0,lineText:"issue",suggestion:""},detail:"DevPortalValidationError",pluginName:"dev-portal",notes:[{text:A.message,location:null}]})}return{contents:k,errors:b,pluginName:"dev-portal",loader:"js",resolveDir:Bce.dirname(u.path),watchFiles:[u.path]}}))}}}t(ult,"devPortalConfigPlugin");import flt from"path";var _lt="legacy-environment",plt="legacy-environment",Iir=`import { environment } from "@zuplo/runtime";
709
- export default environment;`;function dlt(s){return{name:"environment",setup(a){a.onResolve({filter:/@app\/environment$/},()=>({namespace:plt,pluginName:_lt,path:flt.join(s.sourceDirectory,BN,"environment.js")})),a.onLoad({filter:/.*/,namespace:plt},async u=>({contents:Iir,loader:"ts",resolveDir:flt.dirname(u.path),pluginName:_lt}))}}}t(dlt,"environmentPlugin");var D_t=Rp(QIe(),1),P_t=Rp(Kft(),1),A_t=Rp(x4e(),1),N_t=Rp(E4e(),1);import w_t from"fs/promises";import BS from"path";import Ffr from"prettier";var Hk="schemas",Tle="json-schema";function I_t(s){return{name:Hk,async setup(a){let u=new A_t.Ajv2020({code:{source:!0},allErrors:!0,strict:!1,verbose:!0,meta:!0});(0,P_t.default)(u,{mode:"fast"}),u.opts.code.formats=D_t._`require("ajv-formats/dist/formats").fastFormats`;let p=BS.join(s.sourceDirectory,MN),g,b=[],k=[];if(await hc.dirExists(p)&&(u.addKeyword("faker"),g=await hc.listFolderContents(p,MN),await Promise.all(g.map(async A=>{try{let M=hc.safePath(s.sourceDirectory).resolve(p,A);if(!M.startsWith(p))throw new Error("All schemas must be in the schemas directory");let U=await w_t.readFile(M,"utf-8");if(U===""||U===void 0)throw new Error(`Schema 'schemas/${A}' is empty and will be ignored.`);let re=JSON.parse(U);if(re.$schema&&re.$schema!=="https://json-schema.org/draft/2020-12/schema")throw new Error(`Error in ${A}: All JSON schemas must use version 2020-12. See release notes for changes: https://json-schema.org/draft/2020-12/release-notes.html`);if(u.$dataMetaSchema,u.addSchema(re,A),u.errors?.length){let Z=u.errors[0];b.push({id:"json-schema-validation-error",pluginName:Hk,text:`Error: ${Z.message}`,location:{file:BS.join(MN,A)},detail:{params:Z.params,propertyName:Z.propertyName,schemaPath:Z.schemaPath,data:Z.data}})}}catch(M){if(M.message.endsWith("is empty and will be ignored.")){k.push({id:"empty-json-schema-file",pluginName:Hk,text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."},detail:"EmptyJSONSchemaFile",notes:[{text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."}}]});return}let U=await w6e(A,s.sourceDirectory,M.message);b.push({id:"json-schema-add-error",pluginName:Hk,text:`Error: ${M.message}`,location:U,detail:"InvalidAddSchemaError",notes:[{text:M.message}]})}})),await Promise.all(g.map(async A=>{try{let M=u.getSchema(A);M&&u.compile(M.schema).errors?.forEach(re=>{b.push({text:`Failed to compile ${A}: ${re.message}`})})}catch(M){let U=await w6e(A,s.sourceDirectory,M.message);b.push({id:"json-schema-compile-error",pluginName:Hk,text:`The schema file '${A}' is not valid. Error: ${M.message}`,location:U,detail:"InvalidSchemaError",notes:[{text:M.message}]})}})),zm.DEBUG_BUILD_MODE)){let A=BS.resolve(s.outputDirectory,MN);await hc.mkdirIfNotExists(A)}a.onStart(async()=>{if(g)return{errors:b,warnings:k}}),a.onResolve({filter:/schemas\/.*\.json$/},async A=>{let M=BS.isAbsolute(A.path)?A.path:BS.join(A.resolveDir,A.path);if(A.importer&&A.importer!==BS.join(s.sourceDirectory,"config/routes.json"))return{path:M};if(!await hc.fileExists(M)){let U="policies.json";return{errors:[{id:"json-schema-build-error",text:`Unable to resolve reference to '${A.path}' from ${U}`,location:{file:BS.join(A.resolveDir,U),namespace:Tle,line:1,column:0,length:0,lineText:`Invalid JSON schema reference in ${U}`,suggestion:""},detail:"RouteReferenceError",pluginName:Hk,notes:[{text:`Unable to resolve reference to '${A.path}' from ${U}`,location:null}]}],namespace:Tle,path:M,pluginName:Hk}}return{path:M,namespace:Tle,pluginName:Hk}}),a.onLoad({filter:/.*/,namespace:Tle},async A=>Lu.timeFn(`Generating json schema data: ${BS.basename(A.path)}`,async()=>{let M=[],U;try{let re=BS.relative(p,A.path),Z=u.getSchema(re);if(!Z)throw new Error(`Could not load schema at ${A.path}`);U=Z.source?.validateCode;let G=u.compile(Z.schema);U=(0,N_t.default)(u,G)}catch(re){M.push({pluginName:Hk,text:`Cannot parse project's schemas/${BS.basename(A.path)} file. Error: ${re.message}`,location:null,notes:[{text:re.message,location:null}],detail:re})}if(zm.DEBUG_BUILD_MODE&&U){let re=BS.resolve(s.outputDirectory,MN),Z=BS.relative(p,A.path),G=await Ffr.format(U,{parser:"babel"}),Te=hc.safePath(s.sourceDirectory).resolve(re,`${Z}.js`);await hc.mkdirForFilePathIfNotExits(Te),await w_t.writeFile(Te,G,"utf-8")}return{contents:U,errors:M,pluginName:Hk,resolveDir:BS.dirname(A.path),watchFiles:[A.path]}}))}}}t(I_t,"jsonSchemaPlugin");import{relative as Lfr,resolve as Rfr}from"path";import{dirname as Mfr}from"path";import{fileURLToPath as jfr}from"url";var O_t=["node:assert","node:async_hooks","node:buffer","node:crypto","node:diagnostics_channel","node:events","node:path","node:process","node:stream","node:string_decoder","node:util"],Bfr="nodejs-compat-plugin";function F_t({nodeCompatEnabled:s,sourceDirectory:a}){return{name:Bfr,setup(u){let p=new Set;u.onStart(()=>{p.clear()}),u.onResolve({filter:/node:.*/},async({path:g,kind:b,resolveDir:k,...A})=>{let M=`${g}:${b}:${k}:${A.importer}`;if(p.has(M))return;if(p.add(M),!s&&g==="node:async_hooks")return{path:Rfr(Mfr(jfr(import.meta.url)),"../../../polyfills/async_hooks.js")};let U=await u.resolve(g,{kind:b,resolveDir:k,importer:A.importer});return U.errors.length>0?s&&O_t.includes(g)||g.includes("/")&&O_t.includes(g.split("/")[0])?{external:!0}:{external:!0,warnings:U.errors.map(Z=>({...Z,location:{file:Lfr(a,A.importer),line:0,column:0,namespace:"",length:0,lineText:"",suggestion:"Remove the imported node module"},detail:`The package "${g}" wasn't found on the file system but is built into node. If this code is executed it will fail.`}))}:U})}}}t(F_t,"nodejsCompatPlugin");function Ufr(s){if(s.length>=255)throw new TypeError("Alphabet too long");let a=new Uint8Array(256);for(let U=0;U<a.length;U++)a[U]=255;for(let U=0;U<s.length;U++){let re=s.charAt(U),Z=re.charCodeAt(0);if(a[Z]!==255)throw new TypeError(re+" is ambiguous");a[Z]=U}let u=s.length,p=s.charAt(0),g=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function k(U){if(U instanceof Uint8Array||(ArrayBuffer.isView(U)?U=new Uint8Array(U.buffer,U.byteOffset,U.byteLength):Array.isArray(U)&&(U=Uint8Array.from(U))),!(U instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(U.length===0)return"";let re=0,Z=0,G=0,Te=U.length;for(;G!==Te&&U[G]===0;)G++,re++;let ge=(Te-G)*b+1>>>0,ve=new Uint8Array(ge);for(;G!==Te;){let Vt=U[G],hr=0;for(let Sr=ge-1;(Vt!==0||hr<Z)&&Sr!==-1;Sr--,hr++)Vt+=256*ve[Sr]>>>0,ve[Sr]=Vt%u>>>0,Vt=Vt/u>>>0;if(Vt!==0)throw new Error("Non-zero carry");Z=hr,G++}let dt=ge-Z;for(;dt!==ge&&ve[dt]===0;)dt++;let _t=p.repeat(re);for(;dt<ge;++dt)_t+=s.charAt(ve[dt]);return _t}t(k,"encode");function A(U){if(typeof U!="string")throw new TypeError("Expected String");if(U.length===0)return new Uint8Array;let re=0,Z=0,G=0;for(;U[re]===p;)Z++,re++;let Te=(U.length-re)*g+1>>>0,ge=new Uint8Array(Te);for(;U[re];){let Vt=a[U.charCodeAt(re)];if(Vt===255)return;let hr=0;for(let Sr=Te-1;(Vt!==0||hr<G)&&Sr!==-1;Sr--,hr++)Vt+=u*ge[Sr]>>>0,ge[Sr]=Vt%256>>>0,Vt=Vt/256>>>0;if(Vt!==0)throw new Error("Non-zero carry");G=hr,re++}let ve=Te-G;for(;ve!==Te&&ge[ve]===0;)ve++;let dt=new Uint8Array(Z+(Te-ve)),_t=Z;for(;ve!==Te;)dt[_t++]=ge[ve++];return dt}t(A,"decodeUnsafe");function M(U){let re=A(U);if(re)return re;throw new Error("Non-base"+u+" character")}return t(M,"decode"),{encode:k,decodeUnsafe:A,decode:M}}t(Ufr,"base");var L_t=Ufr;var $fr="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",xle=L_t($fr);var C4e="2024-09-02",R_t=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function M_t(){return new ET({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:C4e,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:R_t[C4e]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}t(M_t,"getMockEnvironment");var ET=class s{static{t(this,"Environment")}config;static#t;static#r=!1;static initialize(a){this.#t||(this.#t=new s(a),this.#r=!0)}static get instance(){return this.#r||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#t=M_t()),this.#t}constructor({build:a,runtime:u}){let p;try{if(u.__ZUPLO_CONFIG){let g=atob(u.__ZUPLO_CONFIG);p=JSON.parse(g)}if(u.ZUPLO_SYSTEM_CONFIGURATIONS){let g=new TextDecoder().decode(xle.decode(u.ZUPLO_SYSTEM_CONFIGURATIONS)),b=JSON.parse(g);for(let k of Object.keys(b))u[k]=b[k]}}catch(g){console.error("Failed to parse runtime configuration",g)}this.config=p??{},this.build=a,this.runtime=u,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get enableRuntimeUserLogs(){return this.config.runtime_user_logs==="true"}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Jfr=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function j_t(s){return s.startsWith("__ZUPLO")||s.startsWith("ZUPLO_")?!Jfr.includes(s)&&!s.startsWith("ZUPLO_PUBLIC_"):!1}t(j_t,"isRestrictedEnvVariableName");function B_t(s){return!!s.startsWith("ZUPLO_")}t(B_t,"isZuploReadableEnvVariableName");var ZRr=new Proxy({},{get(s,a){let u=String(a);switch(u){case"ZUPLO_ENVIRONMENT_TYPE":return ET.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return ET.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return ET.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return ET.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return ET.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return ET.instance.build.BUILD_ID}if(!(j_t(u)&&!B_t(u)))return ET.instance.runtime[u]}});function nH(s,a,u){return`_${qP(s+"_"+a+"_"+u)}`}t(nH,"getRawOperationDataIdentifierName");function k4e(s,a,u,p){return`_${qP(s.toLowerCase())}_`+a.toLowerCase()+"_"+u.toLowerCase()+`_${p.toLowerCase()}`}t(k4e,"getIdForParameterSchema");function w4e(s,a,u){return`_${qP(s.toLowerCase())}_`+a.toLowerCase()+`_rb_${qP(u.toLowerCase())}`}t(w4e,"getIdForRequestBodySchema");function iH(s,a){return`_${qP(s)}__${qP(a)}`}t(iH,"getIdForRefSchema");function qP(s){let a=[];for(let u=0;u<s.length;u++){let p=s.charCodeAt(u);p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122?a.push(s.charAt(u)):a.push("_")}return a.join("")}t(qP,"sanitizedIdentifierName");var zgt=Rp(adt(),1);import{findNodeAtLocation as eK,getNodeValue as que,printParseErrorCode as nbr}from"jsonc-parser";import POe from"path";var gH=class{static{t(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(s,a,u,p,g,b){this.type=s,this.name=a,this.prefix=u,this.value=p,this.suffix=g,this.modifier=b}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},mdr=/[$_\p{ID_Start}]/u,hdr=/[$_\u200C\u200D\p{ID_Continue}]/u,o3e=".*";function gdr(s,a){return(a?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(s)}t(gdr,"Re");function ldt(s,a=!1){let u=[],p=0;for(;p<s.length;){let g=s[p],b=t(function(k){if(!a)throw new TypeError(k);u.push({type:"INVALID_CHAR",index:p,value:s[p++]})},"c");if(g==="*"){u.push({type:"ASTERISK",index:p,value:s[p++]});continue}if(g==="+"||g==="?"){u.push({type:"OTHER_MODIFIER",index:p,value:s[p++]});continue}if(g==="\\"){u.push({type:"ESCAPED_CHAR",index:p++,value:s[p++]});continue}if(g==="{"){u.push({type:"OPEN",index:p,value:s[p++]});continue}if(g==="}"){u.push({type:"CLOSE",index:p,value:s[p++]});continue}if(g===":"){let k="",A=p+1;for(;A<s.length;){let M=s.substr(A,1);if(A===p+1&&mdr.test(M)||A!==p+1&&hdr.test(M)){k+=s[A++];continue}break}if(!k){b(`Missing parameter name at ${p}`);continue}u.push({type:"NAME",index:p,value:k}),p=A;continue}if(g==="("){let k=1,A="",M=p+1,U=!1;if(s[M]==="?"){b(`Pattern cannot start with "?" at ${M}`);continue}for(;M<s.length;){if(!gdr(s[M],!1)){b(`Invalid character '${s[M]}' at ${M}.`),U=!0;break}if(s[M]==="\\"){A+=s[M++]+s[M++];continue}if(s[M]===")"){if(k--,k===0){M++;break}}else if(s[M]==="("&&(k++,s[M+1]!=="?")){b(`Capturing groups are not allowed at ${M}`),U=!0;break}A+=s[M++]}if(U)continue;if(k){b(`Unbalanced pattern at ${p}`);continue}if(!A){b(`Missing pattern at ${p}`);continue}u.push({type:"REGEX",index:p,value:A}),p=M;continue}u.push({type:"CHAR",index:p,value:s[p++]})}return u.push({type:"END",index:p,value:""}),u}t(ldt,"v");function udt(s,a={}){let u=ldt(s);a.delimiter??="/#?",a.prefixes??="./";let p=`[^${wT(a.delimiter)}]+?`,g=[],b=0,k=0,A="",M=new Set,U=t(hr=>{if(k<u.length&&u[k].type===hr)return u[k++].value},"a"),re=t(()=>U("OTHER_MODIFIER")??U("ASTERISK"),"f"),Z=t(hr=>{let Sr=U(hr);if(Sr!==void 0)return Sr;let{type:Zt,index:lr}=u[k];throw new TypeError(`Unexpected ${Zt} at ${lr}, expected ${hr}`)},"d"),G=t(()=>{let hr="",Sr;for(;Sr=U("CHAR")??U("ESCAPED_CHAR");)hr+=Sr;return hr},"T"),Te=t(hr=>hr,"Se"),ge=a.encodePart||Te,ve="",dt=t(hr=>{ve+=hr},"U"),_t=t(()=>{ve.length&&(g.push(new gH(3,"","",ge(ve),"",3)),ve="")},"$"),Vt=t((hr,Sr,Zt,lr,Xt)=>{let ei=3;switch(Xt){case"?":ei=1;break;case"*":ei=0;break;case"+":ei=2;break}if(!Sr&&!Zt&&ei===3){dt(hr);return}if(_t(),!Sr&&!Zt){if(!hr)return;g.push(new gH(3,"","",ge(hr),"",ei));return}let fr;Zt?Zt==="*"?fr=o3e:fr=Zt:fr=p;let wi=2;fr===p?(wi=1,fr=""):fr===o3e&&(wi=0,fr="");let un;if(Sr?un=Sr:Zt&&(un=b++),M.has(un))throw new TypeError(`Duplicate name '${un}'.`);M.add(un),g.push(new gH(wi,un,ge(hr),fr,ge(lr),ei))},"V");for(;k<u.length;){let hr=U("CHAR"),Sr=U("NAME"),Zt=U("REGEX");if(!Sr&&!Zt&&(Zt=U("ASTERISK")),Sr||Zt){let Xt=hr??"";a.prefixes.indexOf(Xt)===-1&&(dt(Xt),Xt=""),_t();let ei=re();Vt(Xt,Sr,Zt,"",ei);continue}let lr=hr??U("ESCAPED_CHAR");if(lr){dt(lr);continue}if(U("OPEN")){let Xt=G(),ei=U("NAME"),fr=U("REGEX");!ei&&!fr&&(fr=U("ASTERISK"));let wi=G();Z("CLOSE");let un=re();Vt(Xt,ei,fr,wi,un);continue}_t(),Z("END")}return g}t(udt,"D");function wT(s){return s.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(wT,"S");function odt(s){return s&&s.ignoreCase?"ui":"u"}t(odt,"X");function ydr(s,a,u){return fdt(udt(s,u),a,u)}t(ydr,"Z");function MM(s){switch(s){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}t(MM,"k");function fdt(s,a,u={}){u.delimiter??="/#?",u.prefixes??="./",u.sensitive??=!1,u.strict??=!1,u.end??=!0,u.start??=!0,u.endsWith="";let p=u.start?"^":"";for(let A of s){if(A.type===3){A.modifier===3?p+=wT(A.value):p+=`(?:${wT(A.value)})${MM(A.modifier)}`;continue}a&&a.push(A.name);let M=`[^${wT(u.delimiter)}]+?`,U=A.value;if(A.type===1?U=M:A.type===0&&(U=o3e),!A.prefix.length&&!A.suffix.length){A.modifier===3||A.modifier===1?p+=`(${U})${MM(A.modifier)}`:p+=`((?:${U})${MM(A.modifier)})`;continue}if(A.modifier===3||A.modifier===1){p+=`(?:${wT(A.prefix)}(${U})${wT(A.suffix)})`,p+=MM(A.modifier);continue}p+=`(?:${wT(A.prefix)}`,p+=`((?:${U})(?:`,p+=wT(A.suffix),p+=wT(A.prefix),p+=`(?:${U}))*)${wT(A.suffix)})`,A.modifier===0&&(p+="?")}let g=`[${wT(u.endsWith)}]|$`,b=`[${wT(u.delimiter)}]`;if(u.end)return u.strict||(p+=`${b}?`),u.endsWith.length?p+=`(?=${g})`:p+="$",new RegExp(p,odt(u));u.strict||(p+=`(?:${b}(?=${g}))?`);let k=!1;if(s.length){let A=s[s.length-1];A.type===3&&A.modifier===3&&(k=u.delimiter.indexOf(A)>-1)}return k||(p+=`(?=${b}|${g})`),new RegExp(p,odt(u))}t(fdt,"F");var hI={delimiter:"",prefixes:"",sensitive:!0,strict:!0},vdr={delimiter:".",prefixes:"",sensitive:!0,strict:!0},bdr={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function Sdr(s,a){return s.length?s[0]==="/"?!0:!a||s.length<2?!1:(s[0]=="\\"||s[0]=="{")&&s[1]=="/":!1}t(Sdr,"J");function _dt(s,a){return s.startsWith(a)?s.substring(a.length,s.length):s}t(_dt,"Q");function Tdr(s,a){return s.endsWith(a)?s.substr(0,s.length-a.length):s}t(Tdr,"Ee");function pdt(s){return!s||s.length<2?!1:s[0]==="["||(s[0]==="\\"||s[0]==="{")&&s[1]==="["}t(pdt,"W");var ddt=["ftp","file","http","https","ws","wss"];function mdt(s){if(!s)return!0;for(let a of ddt)if(s.test(a))return!0;return!1}t(mdt,"N");function xdr(s,a){if(s=_dt(s,"#"),a||s==="")return s;let u=new URL("https://example.com");return u.hash=s,u.hash?u.hash.substring(1,u.hash.length):""}t(xdr,"te");function Edr(s,a){if(s=_dt(s,"?"),a||s==="")return s;let u=new URL("https://example.com");return u.search=s,u.search?u.search.substring(1,u.search.length):""}t(Edr,"re");function Cdr(s,a){return a||s===""?s:pdt(s)?ydt(s):gdt(s)}t(Cdr,"ne");function kdr(s,a){if(a||s==="")return s;let u=new URL("https://example.com");return u.password=s,u.password}t(kdr,"se");function wdr(s,a){if(a||s==="")return s;let u=new URL("https://example.com");return u.username=s,u.username}t(wdr,"ie");function Ddr(s,a,u){if(u||s==="")return s;if(a&&!ddt.includes(a))return new URL(`${a}:${s}`).pathname;let p=s[0]=="/";return s=new URL(p?s:"/-"+s,"https://example.com").pathname,p||(s=s.substring(2,s.length)),s}t(Ddr,"ae");function Pdr(s,a,u){return hdt(a)===s&&(s=""),u||s===""?s:vdt(s)}t(Pdr,"oe");function Adr(s,a){return s=Tdr(s,":"),a||s===""?s:c3e(s)}t(Adr,"ce");function hdt(s){switch(s){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}t(hdt,"_");function c3e(s){if(s==="")return s;if(/^[-+.A-Za-z0-9]*$/.test(s))return s.toLowerCase();throw new TypeError(`Invalid protocol '${s}'.`)}t(c3e,"y");function Ndr(s){if(s==="")return s;let a=new URL("https://example.com");return a.username=s,a.username}t(Ndr,"le");function Idr(s){if(s==="")return s;let a=new URL("https://example.com");return a.password=s,a.password}t(Idr,"fe");function gdt(s){if(s==="")return s;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(s))throw new TypeError(`Invalid hostname '${s}'`);let a=new URL("https://example.com");return a.hostname=s,a.hostname}t(gdt,"z");function ydt(s){if(s==="")return s;if(/[^0-9a-fA-F[\]:]/g.test(s))throw new TypeError(`Invalid IPv6 hostname '${s}'`);return s.toLowerCase()}t(ydt,"j");function vdt(s){if(s===""||/^[0-9]*$/.test(s)&&parseInt(s)<=65535)return s;throw new TypeError(`Invalid port '${s}'.`)}t(vdt,"K");function Odr(s){if(s==="")return s;let a=new URL("https://example.com");return a.pathname=s[0]!=="/"?"/-"+s:s,s[0]!=="/"?a.pathname.substring(2,a.pathname.length):a.pathname}t(Odr,"he");function Fdr(s){return s===""?s:new URL(`data:${s}`).pathname}t(Fdr,"ue");function Ldr(s){if(s==="")return s;let a=new URL("https://example.com");return a.search=s,a.search.substring(1,a.search.length)}t(Ldr,"de");function Rdr(s){if(s==="")return s;let a=new URL("https://example.com");return a.hash=s,a.hash.substring(1,a.hash.length)}t(Rdr,"pe");var Mdr=class{static{t(this,"H")}#t;#r=[];#i={};#e=0;#a=1;#m=0;#o=0;#u=0;#c=0;#l=!1;constructor(s){this.#t=s}get result(){return this.#i}parse(){for(this.#r=ldt(this.#t,!0);this.#e<this.#r.length;this.#e+=this.#a){if(this.#a=1,this.#r[this.#e].type==="END"){if(this.#o===0){this.#y(),this.#E()?this.#n(9,1):this.#_()?this.#n(8,1):this.#n(7,0);continue}else if(this.#o===2){this.#p(5);continue}this.#n(10,0);break}if(this.#u>0)if(this.#s())this.#u-=1;else continue;if(this.#D()){this.#u+=1;continue}switch(this.#o){case 0:this.#g()&&this.#p(1);break;case 1:if(this.#g()){this.#I();let s=7,a=1;this.#w()?(s=2,a=3):this.#l&&(s=2),this.#n(s,a)}break;case 2:this.#C()?this.#p(3):(this.#x()||this.#_()||this.#E())&&this.#p(5);break;case 3:this.#T()?this.#n(4,1):this.#C()&&this.#n(5,1);break;case 4:this.#C()&&this.#n(5,1);break;case 5:this.#N()?this.#c+=1:this.#b()&&(this.#c-=1),this.#k()&&!this.#c?this.#n(6,1):this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 6:this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 7:this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 8:this.#E()&&this.#n(9,1);break;case 9:break;case 10:break}}this.#i.hostname!==void 0&&this.#i.port===void 0&&(this.#i.port="")}#n(s,a){switch(this.#o){case 0:break;case 1:this.#i.protocol=this.#S();break;case 2:break;case 3:this.#i.username=this.#S();break;case 4:this.#i.password=this.#S();break;case 5:this.#i.hostname=this.#S();break;case 6:this.#i.port=this.#S();break;case 7:this.#i.pathname=this.#S();break;case 8:this.#i.search=this.#S();break;case 9:this.#i.hash=this.#S();break;case 10:break}this.#o!==0&&s!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(s)&&(this.#i.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(s)&&(this.#i.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&s===9&&(this.#i.search??="")),this.#v(s,a)}#v(s,a){this.#o=s,this.#m=this.#e+a,this.#e+=a,this.#a=0}#y(){this.#e=this.#m,this.#a=0}#p(s){this.#y(),this.#o=s}#d(s){return s<0&&(s=this.#r.length-s),s<this.#r.length?this.#r[s]:this.#r[this.#r.length-1]}#h(s,a){let u=this.#d(s);return u.value===a&&(u.type==="CHAR"||u.type==="ESCAPED_CHAR"||u.type==="INVALID_CHAR")}#g(){return this.#h(this.#e,":")}#w(){return this.#h(this.#e+1,"/")&&this.#h(this.#e+2,"/")}#C(){return this.#h(this.#e,"@")}#T(){return this.#h(this.#e,":")}#k(){return this.#h(this.#e,":")}#x(){return this.#h(this.#e,"/")}#_(){if(this.#h(this.#e,"?"))return!0;if(this.#r[this.#e].value!=="?")return!1;let s=this.#d(this.#e-1);return s.type!=="NAME"&&s.type!=="REGEX"&&s.type!=="CLOSE"&&s.type!=="ASTERISK"}#E(){return this.#h(this.#e,"#")}#D(){return this.#r[this.#e].type=="OPEN"}#s(){return this.#r[this.#e].type=="CLOSE"}#N(){return this.#h(this.#e,"[")}#b(){return this.#h(this.#e,"]")}#S(){let s=this.#r[this.#e],a=this.#d(this.#m).index;return this.#t.substring(a,s.index)}#I(){let s={};Object.assign(s,hI),s.encodePart=c3e;let a=ydr(this.#S(),void 0,s);this.#l=mdt(a)}},a3e=["protocol","username","password","hostname","port","pathname","search","hash"],mI="*";function cdt(s,a){if(typeof s!="string")throw new TypeError("parameter 1 is not of type 'string'.");let u=new URL(s,a);return{protocol:u.protocol.substring(0,u.protocol.length-1),username:u.username,password:u.password,hostname:u.hostname,port:u.port,pathname:u.pathname,search:u.search!==""?u.search.substring(1,u.search.length):void 0,hash:u.hash!==""?u.hash.substring(1,u.hash.length):void 0}}t(cdt,"ge");function GP(s,a){return a?hH(s):s}t(GP,"b");function mH(s,a,u){let p;if(typeof a.baseURL=="string")try{p=new URL(a.baseURL),a.protocol===void 0&&(s.protocol=GP(p.protocol.substring(0,p.protocol.length-1),u)),!u&&a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.username===void 0&&(s.username=GP(p.username,u)),!u&&a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.username===void 0&&a.password===void 0&&(s.password=GP(p.password,u)),a.protocol===void 0&&a.hostname===void 0&&(s.hostname=GP(p.hostname,u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&(s.port=GP(p.port,u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.pathname===void 0&&(s.pathname=GP(p.pathname,u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.pathname===void 0&&a.search===void 0&&(s.search=GP(p.search.substring(1,p.search.length),u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.pathname===void 0&&a.search===void 0&&a.hash===void 0&&(s.hash=GP(p.hash.substring(1,p.hash.length),u))}catch{throw new TypeError(`invalid baseURL '${a.baseURL}'.`)}if(typeof a.protocol=="string"&&(s.protocol=Adr(a.protocol,u)),typeof a.username=="string"&&(s.username=wdr(a.username,u)),typeof a.password=="string"&&(s.password=kdr(a.password,u)),typeof a.hostname=="string"&&(s.hostname=Cdr(a.hostname,u)),typeof a.port=="string"&&(s.port=Pdr(a.port,s.protocol,u)),typeof a.pathname=="string"){if(s.pathname=a.pathname,p&&!Sdr(s.pathname,u)){let g=p.pathname.lastIndexOf("/");g>=0&&(s.pathname=GP(p.pathname.substring(0,g+1),u)+s.pathname)}s.pathname=Ddr(s.pathname,s.protocol,u)}return typeof a.search=="string"&&(s.search=Edr(a.search,u)),typeof a.hash=="string"&&(s.hash=xdr(a.hash,u)),s}t(mH,"w");function hH(s){return s.replace(/([+*?:{}()\\])/g,"\\$1")}t(hH,"C");function jdr(s){return s.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(jdr,"Oe");function Bdr(s,a){a.delimiter??="/#?",a.prefixes??="./",a.sensitive??=!1,a.strict??=!1,a.end??=!0,a.start??=!0,a.endsWith="";let u=".*",p=`[^${jdr(a.delimiter)}]+?`,g=/[$_\u200C\u200D\p{ID_Continue}]/u,b="";for(let k=0;k<s.length;++k){let A=s[k];if(A.type===3){if(A.modifier===3){b+=hH(A.value);continue}b+=`{${hH(A.value)}}${MM(A.modifier)}`;continue}let M=A.hasCustomName(),U=!!A.suffix.length||!!A.prefix.length&&(A.prefix.length!==1||!a.prefixes.includes(A.prefix)),re=k>0?s[k-1]:null,Z=k<s.length-1?s[k+1]:null;if(!U&&M&&A.type===1&&A.modifier===3&&Z&&!Z.prefix.length&&!Z.suffix.length)if(Z.type===3){let G=Z.value.length>0?Z.value[0]:"";U=g.test(G)}else U=!Z.hasCustomName();if(!U&&!A.prefix.length&&re&&re.type===3){let G=re.value[re.value.length-1];U=a.prefixes.includes(G)}U&&(b+="{"),b+=hH(A.prefix),M&&(b+=`:${A.name}`),A.type===2?b+=`(${A.value})`:A.type===1?M||(b+=`(${p})`):A.type===0&&(!M&&(!re||re.type===3||re.modifier!==3||U||A.prefix!=="")?b+="*":b+=`(${u})`),A.type===1&&M&&A.suffix.length&&g.test(A.suffix[0])&&(b+="\\"),b+=hH(A.suffix),U&&(b+="}"),A.modifier!==3&&(b+=MM(A.modifier))}return b}t(Bdr,"ke");var bdt=class{static{t(this,"me")}#t;#r={};#i={};#e={};#a={};#m=!1;constructor(s={},a,u){try{let p;if(typeof a=="string"?p=a:u=a,typeof s=="string"){let A=new Mdr(s);if(A.parse(),s=A.result,p===void 0&&typeof s.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");s.baseURL=p}else{if(!s||typeof s!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(p)throw new TypeError("parameter 1 is not of type 'string'.")}typeof u>"u"&&(u={ignoreCase:!1});let g={ignoreCase:u.ignoreCase===!0},b={pathname:mI,protocol:mI,username:mI,password:mI,hostname:mI,port:mI,search:mI,hash:mI};this.#t=mH(b,s,!0),hdt(this.#t.protocol)===this.#t.port&&(this.#t.port="");let k;for(k of a3e){if(!(k in this.#t))continue;let A={},M=this.#t[k];switch(this.#i[k]=[],k){case"protocol":Object.assign(A,hI),A.encodePart=c3e;break;case"username":Object.assign(A,hI),A.encodePart=Ndr;break;case"password":Object.assign(A,hI),A.encodePart=Idr;break;case"hostname":Object.assign(A,vdr),pdt(M)?A.encodePart=ydt:A.encodePart=gdt;break;case"port":Object.assign(A,hI),A.encodePart=vdt;break;case"pathname":mdt(this.#r.protocol)?(Object.assign(A,bdr,g),A.encodePart=Odr):(Object.assign(A,hI,g),A.encodePart=Fdr);break;case"search":Object.assign(A,hI,g),A.encodePart=Ldr;break;case"hash":Object.assign(A,hI,g),A.encodePart=Rdr;break}try{this.#a[k]=udt(M,A),this.#r[k]=fdt(this.#a[k],this.#i[k],A),this.#e[k]=Bdr(this.#a[k],A),this.#m=this.#m||this.#a[k].some(U=>U.type===2)}catch{throw new TypeError(`invalid ${k} pattern '${this.#t[k]}'.`)}}}catch(p){throw new TypeError(`Failed to construct 'URLPattern': ${p.message}`)}}test(s={},a){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof s!="string"&&a)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof s>"u")return!1;try{typeof s=="object"?u=mH(u,s,!1):u=mH(u,cdt(s,a),!1)}catch{return!1}let p;for(p of a3e)if(!this.#r[p].exec(u[p]))return!1;return!0}exec(s={},a){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof s!="string"&&a)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof s>"u")return;try{typeof s=="object"?u=mH(u,s,!1):u=mH(u,cdt(s,a),!1)}catch{return null}let p={};a?p.inputs=[s,a]:p.inputs=[s];let g;for(g of a3e){let b=this.#r[g].exec(u[g]);if(!b)return null;let k={};for(let[A,M]of this.#i[g].entries())if(typeof M=="string"||typeof M=="number"){let U=b[A+1];k[M]=U}p[g]={input:u[g]??"",groups:k}}return p}static compareComponent(s,a,u){let p=t((A,M)=>{for(let U of["type","modifier","prefix","value","suffix"]){if(A[U]<M[U])return-1;if(A[U]!==M[U])return 1}return 0},"o"),g=new gH(3,"","","","",3),b=new gH(0,"","","","",3),k=t((A,M)=>{let U=0;for(;U<Math.min(A.length,M.length);++U){let re=p(A[U],M[U]);if(re)return re}return A.length===M.length?0:p(A[U]??g,M[U]??g)},"s");return!a.#e[s]&&!u.#e[s]?0:a.#e[s]&&!u.#e[s]?k(a.#a[s],[b]):!a.#e[s]&&u.#e[s]?k([b],u.#a[s]):k(a.#a[s],u.#a[s])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#m}};globalThis.URLPattern||(globalThis.URLPattern=bdt);import{AssertionError as Udr}from"assert";function $O(s,a){if(s===!1)throw new Udr({message:a})}t($O,"assert");var bc;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.FunctionBody="FunctionBody"})(bc||(bc={}));function yH(s){return s.type===bc.Object}t(yH,"isAstObject");function HP(s){return s.type===bc.Property}t(HP,"isAstProperty");function Sdt(s){return s.type===bc.Array}t(Sdt,"isAstArray");function jM(s){return s.type===bc.Literal}t(jM,"isAstLiteral");import{visit as $dr}from"jsonc-parser";var Jdr={DEFAULT:{allowTrailingComma:!1}};function vH(s,a=[],u=Jdr.DEFAULT){let p={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function g(M){p.type==="property"&&(p.length=M-p.offset,p=p.parent)}t(g,"ensurePropertyComplete");function b(M){return p.children?.push(M),M}t(b,"onValue"),$dr(s,{onObjectBegin:t((M,U,re)=>{p=b({type:"object",offset:M,length:-1,line:U+1,column:re+1,parent:p,children:[]})},"onObjectBegin"),onObjectProperty:t((M,U,re,Z,G)=>{p=b({type:"property",offset:U,length:-1,line:Z+1,column:G+1,parent:p,children:[]}),p.children?.push({type:"string",value:M,offset:U,length:re,line:Z,column:G,parent:p})},"onObjectProperty"),onObjectEnd:t((M,U)=>{g(M+U),p.length=M+U-p.offset,p=p.parent,g(M+U)},"onObjectEnd"),onArrayBegin:t((M,U,re,Z)=>{p=b({type:"array",offset:M,length:-1,line:re+1,column:Z+1,parent:p,children:[]})},"onArrayBegin"),onArrayEnd:t((M,U)=>{p.length=M+U-p.offset,p=p.parent,g(M+U)},"onArrayEnd"),onLiteralValue:t((M,U,re,Z,G)=>{b({type:qdr(M),offset:U,length:re,line:Z+1,column:G+1,parent:p,value:M}),g(U+re)},"onLiteralValue"),onSeparator:t((M,U)=>{p.type==="property"&&(M===":"?p.colonOffset=U:M===","&&g(U))},"onSeparator"),onError:t((M,U,re,Z,G)=>{a.push({error:M,offset:U,length:re,line:Z+1,column:G+1})},"onError")},u);let A=p.children[0];return A&&delete A.parent,A}t(vH,"parse");function qdr(s){switch(typeof s){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(s){if(Array.isArray(s))return"array"}else return"null";return"object"}default:return"null"}}t(qdr,"getNodeType");var bH=class{static{t(this,"AstAdapter")}parse(a){let p=vH(a,[]);if(p)return this.parseNode(p,void 0);throw new Error("Failed to parse JSON")}convert(a){return this.parseNode(a,void 0)}parseNode(a,u){switch(a.type){case"object":return this.createObject(a,u);case"array":return this.createArray(a,u);case"property":return this.createProperty(a,u);case"string":return this.createLiteral(a,u);case"number":return this.createLiteral(a,u);case"boolean":return this.createLiteral(a,u);case"null":return this.createLiteral(a,u)}}createLiteral(a,u){return{type:bc.Literal,location:{line:a.line,column:a.column},parent:u,value:a.type==="null"?null:a.value}}createObject(a,u){let p={type:bc.Object,children:[],parent:u,location:{line:a.line,column:a.column}};return a.children?.forEach(g=>{p.children.push(this.parseNode(g,p))}),p}createProperty(a,u){$O(a.children?.length===2,"Invalid property node");let p={type:bc.Property,location:{line:a.line,column:a.column},parent:u,name:null,value:null};return p.name={value:a.children[0].value,location:{line:a.line,column:a.column},type:bc.Identifier,parent:p},p.value=this.parseNode(a.children[1],p),p}createArray(a,u){let p={type:bc.Array,location:{line:a.line,column:a.column},parent:u,children:[]};return a.children?.forEach(g=>p.children.push(this.parseNode(g,p))),p}};var DT={createLiteral:t((s,a)=>({type:bc.Literal,parent:a,value:s}),"createLiteral"),createTemplateString:t((s,a)=>({type:bc.TemplateString,parent:a,value:s}),"createTemplateString"),createIdentifier:t((s,a)=>({type:bc.Identifier,value:s,parent:a}),"createIdentifier"),createProperty:t((s,a,u)=>{let p={type:bc.Property,parent:u,name:null,value:a};return p.name={value:s,type:bc.Identifier,parent:p},p.value.parent=p,p},"createProperty"),createArrayOfLiterals:t((s,a)=>{let u={type:bc.Array,parent:a,children:[]};for(let p of s)u.children.push(DT.createLiteral(p,u));return u},"createArrayOfLiterals")};var SH=class{static{t(this,"SourceGenerator")}generate(a){let u=[];return this.generateSource(u,a),u.join("")}generateSource(a,u){switch(u.type){case bc.Array:return this.generateArray(a,u);case bc.Object:return this.generateObject(a,u);case bc.Property:return this.generateProperty(a,u);case bc.Literal:return this.generateLiteral(a,u);case bc.FunctionCall:return this.generateFunctionCall(a,u);case bc.Identifier:return this.generateIdentifier(a,u);case bc.FunctionBody:return this.generateFunctionBody(a,u);case bc.TemplateString:return this.generateTemplateString(a,u)}}generateArray(a,u){a.push("["),u.children.map(p=>{this.generateSource(a,p),a.push(",")}),a.push("]")}generateObject(a,u){a.push("{"),u.children.forEach(p=>{this.generateSource(a,p),a.push(",")}),a.push("}")}generateProperty(a,u){let p=u.name.value,g=p.search(/(\/|\\|-|\+|@|#|%|\^|&|\*|:|\.)/g)<0?p:`'${p}'`;a.push(g),a.push(":"),this.generateSource(a,u.value)}generateFunctionCall(a,u){a.push(u.name.value),a.push("("),u.children.forEach((p,g,b)=>{this.generateSource(a,p),g<b.length&&a.push(",")}),a.push(")")}generateFunctionBody(a,u){a.push(u.value)}generateTemplateString(a,u){a.push("`"),a.push(u.value.replaceAll("`","\\`")),a.push("`")}generateLiteral(a,u){if(u.value===null)return a.push("null");switch(typeof u.value){case"number":case"boolean":return a.push(`${u.value}`);case"string":{let p=u.value,g=JSON.stringify(p);return a.push(`${g}`)}}}generateIdentifier(a,u){a.push(u.value)}};import{parse as zdr}from"@swc/core";import Vdr from"fs/promises";var Tdt=t(async s=>{let a=new Set;try{let u=await Vdr.readFile(s,"utf-8");(await zdr(u,{syntax:"typescript"})).body.forEach(g=>{g.type==="ExportDefaultDeclaration"||g.type==="ExportDefaultExpression"?a.add("default"):g.type==="ExportDeclaration"&&g.declaration.type==="FunctionDeclaration"?a.add(g.declaration.identifier.value):g.type==="ExportDeclaration"&&g.declaration.type==="VariableDeclaration"&&g.declaration.declarations[0].id.type==="Identifier"&&a.add(g.declaration.declarations[0].id.value)})}catch{return null}return a},"getJSFileExports");var xdt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var l3e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var Edt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var u3e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var f3e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler","version"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},version:{type:"string",pattern:"^[0-9a-z-]+$"},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var Cdt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/routes.schema.json",title:"Route Config File",type:"object",additionalProperties:!1,required:["routes","versions"],$defs:{info:{type:"object",required:["title","version"],properties:{title:{type:"string"},summary:{type:"string"},description:{type:"string"},termsOfService:{type:"string",format:"uri"},version:{type:"string"}}},versionData:{type:"object",required:["name","pathPrefix"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},pathPrefix:{type:"string",pattern:"(^$|^/[^\\s]*$)"},info:{$ref:"#/$defs/info"},openApiFile:{description:"The project relative path to the OpenAPI spec.",type:"string"},excludeFromOpenApi:{type:"boolean",description:"If false, OpenAPI documentation will not be generated for this version. If openApiFile is set this setting is ignored."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."}}}},properties:{$schema:{type:"string"},versions:{type:"array",minItems:1,items:{$ref:"#/$defs/versionData"}},routes:{type:"array",minItems:0,items:{$ref:"route-configuration.schema.json"}},policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}},requestErrorHandler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"}}};var Rgt=Rp(sgt(),1),Mgt=Rp(Lgt(),1);var Lue=class s{static{t(this,"JsonValidator")}static#t=new s;static get instance(){return s.#t}ajv;constructor(){this.ajv=new Mgt.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Rgt.default)(this.ajv,{mode:"fast"})}addSchema(a,u){this.ajv.addSchema(a,u)}compile(a){let u=this.ajv.compile(a);return t(g=>({isValid:u(g),errors:this.toSimpleErrors(u.errors,g),warnings:[]}),"validator")}toSimpleErrors(a,u){let p=[];return a?.forEach(g=>{g.keyword==="enum"&&g.params.allowedValues&&Array.isArray(g.params.allowedValues)&&(g.message+=`; ${g.params.allowedValues.join(", ")}`),g.instancePath&&(g.instancePath=g.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let b={details:{}},k=g.instancePath.split("/");if(k.length>2){let M=k[1],U=k[2]?parseInt(k[2]):0,re=k[3],Z=isNaN(U)?void 0:u[M][U][re];b={details:{property:M,index:U,field:re,fieldValue:Z}}}if(g.keyword==="required"&&g.params.missingProperty&&g.instancePath&&(g.message=`A 'path' is missing required property '${g.params.missingProperty}'`),g.keyword==="additionalProperties"&&g.params.additionalProperty&&g.instancePath&&(g.message=`A 'path' should NOT include property '${g.params.additionalProperty}'`),g.keyword==="type"&&g.params.type&&g.instancePath){let M=g.instancePath.split("/"),U=M[M.length-1];g.message=`Value of property '${U}' must be '${g.params.type}'`}let A=Object.assign(g,b);p.push(A)}),p}};var ZP=Lue.instance;ZP.addSchema(Cdt,"routes.schema.json");ZP.addSchema(f3e,"route-configuration.schema.json");ZP.addSchema(Edt,"policy-configuration.schema.json");ZP.addSchema(l3e,"policies.schema.json");ZP.addSchema(u3e,"open-api-route-configuration.schema.json");ZP.addSchema(xdt,"fragments.schema.json");var Yvr=ZP.compile(f3e),jgt=ZP.compile(u3e),COe=ZP.compile(l3e);var Rue=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(a){return this.results=COe(a),this.results}};var Mue=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(a){return this.results=jgt(a),this.results}};import Qvr from"path";var kOe=/\$import\((.*)\)/,jue=/\$env\((.*?)\)/g;var eA=class extends Error{static{t(this,"CodeGenError")}location;constructor(a,u,p,g){super(a),this.location={file:u,namespace:"",line:p?p.line:0,column:p?p.column:0,length:0,lineText:g??"",suggestion:""}}},Xvr=t(s=>{let a=[],u=s;for(;u.parent;)a.push(u),u=u.parent;return a.reverse()},"invertTree"),CI=t((s,a)=>{if(!s)return!1;let u=Xvr(s);return a.split("/").every((b,k)=>{let A=u[k];return A?b==="*"||HP(A)&&A.name.value===b?!0:b==="{}"?A.type===bc.Object:b==="[]"?A.type===bc.Array:!1:!1})},"testPosition");var Bue=class{static{t(this,"AstTransformer")}errors=[];transform(a){return this.visitor(a),a}visitor(a){this.visit(a),yH(a)?a.children.forEach(u=>{this.visitor(u)}):Sdt(a)?a.children.forEach(u=>{this.visitor(u)}):HP(a)&&this.visitor(a.value)}},Bgt=t((s,a,u)=>p=>{if(!HP(p)||!jM(p.value)||typeof p.value.value!="string")return;if(!s.some(b=>CI(p,b))){jue.test(p.value.value)&&a.push(new eA("An $env() statement is not expected at this location.",u,p.location,p.value.value));return}let g=new RegExp(jue).exec(p.value.value);if(g?.length===2&&g[0]===p.value.value){let b={type:bc.FunctionBody,parent:null,value:`environment["${g[1]}"]`};p.value=b}else{let b=p.value.value.replaceAll(new RegExp(jue),(k,A)=>`\${environment["${A}"] ? environment["${A}"] : ""}`);b!==p.value.value&&(p.value=DT.createTemplateString(b,p))}},"getEnvStatementTransformer");var ZH="config/routes.json",Zvr=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*","corsPolicies/[]/{}/*"],ebr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Ugt=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],tbr="handler/{}/options/{}/rewritePattern",rbr="handler/{}/options/{}/baseUrl",Uue=class extends Bue{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(a){this.addedImports.has(a)||this.addedImports.set(a,`__import${this.importCount++}`);let u=this.addedImports.get(a);if(!u)throw new Error("Import name is undefined. This should not happen.");return u}getImports(){let a=[];return this.addedImports.forEach((u,p)=>{a.push({name:u,path:p})}),a}visit(a){this.rewriteHandlerFunction(a),this.rewriteForwardFunction(a),this.replaceImportStatements(a),this.replaceEnvStatements(a)}rewriteHandlerFunction(a){if(!(!HP(a)||!jM(a.value)||typeof a.value.value!="string")&&CI(a,tbr)){if(!a.parent||!yH(a.parent)){this.errors.push(new eA("Invalid node, expected object",ZH,a.parent?a.parent.location:a.location,void 0));return}let u=a.value.value,p={type:bc.FunctionBody,parent:null,value:$gt(u)},g=DT.createProperty("__rewriteFunction",p,a);a.parent.children.push(g)}}rewriteForwardFunction(a){if(!(!HP(a)||!jM(a.value)||typeof a.value.value!="string")&&CI(a,rbr)){if(!a.parent||!yH(a.parent)){this.errors.push(new eA("Invalid node, expected object",ZH,a.parent?a.parent.location:a.location,void 0));return}let u=a.value.value,p={type:bc.FunctionBody,parent:null,value:$gt(u)},g=DT.createProperty("__rewriteFunction",p,a);a.parent.children.push(g)}}replaceImportStatements(a){if(!HP(a)||!jM(a.value))return;let u=a.value.value;if(typeof u!="string")return;if(!ebr.some(A=>CI(a,A))&&!Ugt.some(A=>CI(a,A))){if(kOe.test(u)){if(a.name.value==="$ref")return;this.errors.push(new eA("An $import() statement is not expected at this location.",ZH,a.location,u))}return}let p=kOe.exec(u);if(Ugt.some(A=>CI(a,A))&&!p)return;if(!p){this.errors.push(new eA("Invalid $import() statement",ZH,a.location,u));return}let g=p[1];g.startsWith(".")&&(g=Qvr.join("..",g));let b=this.getImportName(g),k={type:bc.Identifier,parent:a.parent,value:b};a.value=k}replaceEnvStatements=Bgt(Zvr,this.errors,ZH)};function $gt(s){return`(request, context) => {
709
+ export default environment;`;function dlt(s){return{name:"environment",setup(a){a.onResolve({filter:/@app\/environment$/},()=>({namespace:plt,pluginName:_lt,path:flt.join(s.sourceDirectory,BN,"environment.js")})),a.onLoad({filter:/.*/,namespace:plt},async u=>({contents:Iir,loader:"ts",resolveDir:flt.dirname(u.path),pluginName:_lt}))}}}t(dlt,"environmentPlugin");var D_t=Rp(QIe(),1),P_t=Rp(Kft(),1),A_t=Rp(x4e(),1),N_t=Rp(E4e(),1);import w_t from"fs/promises";import BS from"path";import Ffr from"prettier";var Hk="schemas",Tle="json-schema";function I_t(s){return{name:Hk,async setup(a){let u=new A_t.Ajv2020({code:{source:!0},allErrors:!0,strict:!1,verbose:!0,meta:!0});(0,P_t.default)(u,{mode:"fast"}),u.opts.code.formats=D_t._`require("ajv-formats/dist/formats").fastFormats`;let p=BS.join(s.sourceDirectory,MN),g,b=[],k=[];if(await hc.dirExists(p)&&(u.addKeyword("faker"),g=await hc.listFolderContents(p,MN),await Promise.all(g.map(async A=>{try{let M=hc.safePath(s.sourceDirectory).resolve(p,A);if(!M.startsWith(p))throw new Error("All schemas must be in the schemas directory");let U=await w_t.readFile(M,"utf-8");if(U===""||U===void 0)throw new Error(`Schema 'schemas/${A}' is empty and will be ignored.`);let re=JSON.parse(U);if(re.$schema&&re.$schema!=="https://json-schema.org/draft/2020-12/schema")throw new Error(`Error in ${A}: All JSON schemas must use version 2020-12. See release notes for changes: https://json-schema.org/draft/2020-12/release-notes.html`);if(u.$dataMetaSchema,u.addSchema(re,A),u.errors?.length){let Z=u.errors[0];b.push({id:"json-schema-validation-error",pluginName:Hk,text:`Error: ${Z.message}`,location:{file:BS.join(MN,A)},detail:{params:Z.params,propertyName:Z.propertyName,schemaPath:Z.schemaPath,data:Z.data}})}}catch(M){if(M.message.endsWith("is empty and will be ignored.")){k.push({id:"empty-json-schema-file",pluginName:Hk,text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."},detail:"EmptyJSONSchemaFile",notes:[{text:`Schema 'schemas/${A}' is empty and will be ignored.`,location:{file:`schemas/${A}`,suggestion:"Add schema details or remove the file from the project."}}]});return}let U=await w6e(A,s.sourceDirectory,M.message);b.push({id:"json-schema-add-error",pluginName:Hk,text:`Error: ${M.message}`,location:U,detail:"InvalidAddSchemaError",notes:[{text:M.message}]})}})),await Promise.all(g.map(async A=>{try{let M=u.getSchema(A);M&&u.compile(M.schema).errors?.forEach(re=>{b.push({text:`Failed to compile ${A}: ${re.message}`})})}catch(M){let U=await w6e(A,s.sourceDirectory,M.message);b.push({id:"json-schema-compile-error",pluginName:Hk,text:`The schema file '${A}' is not valid. Error: ${M.message}`,location:U,detail:"InvalidSchemaError",notes:[{text:M.message}]})}})),zm.DEBUG_BUILD_MODE)){let A=BS.resolve(s.outputDirectory,MN);await hc.mkdirIfNotExists(A)}a.onStart(async()=>{if(g)return{errors:b,warnings:k}}),a.onResolve({filter:/schemas\/.*\.json$/},async A=>{let M=BS.isAbsolute(A.path)?A.path:BS.join(A.resolveDir,A.path);if(A.importer&&A.importer!==BS.join(s.sourceDirectory,"config/routes.json"))return{path:M};if(!await hc.fileExists(M)){let U="policies.json";return{errors:[{id:"json-schema-build-error",text:`Unable to resolve reference to '${A.path}' from ${U}`,location:{file:BS.join(A.resolveDir,U),namespace:Tle,line:1,column:0,length:0,lineText:`Invalid JSON schema reference in ${U}`,suggestion:""},detail:"RouteReferenceError",pluginName:Hk,notes:[{text:`Unable to resolve reference to '${A.path}' from ${U}`,location:null}]}],namespace:Tle,path:M,pluginName:Hk}}return{path:M,namespace:Tle,pluginName:Hk}}),a.onLoad({filter:/.*/,namespace:Tle},async A=>Lu.timeFn(`Generating json schema data: ${BS.basename(A.path)}`,async()=>{let M=[],U;try{let re=BS.relative(p,A.path),Z=u.getSchema(re);if(!Z)throw new Error(`Could not load schema at ${A.path}`);U=Z.source?.validateCode;let G=u.compile(Z.schema);U=(0,N_t.default)(u,G)}catch(re){M.push({pluginName:Hk,text:`Cannot parse project's schemas/${BS.basename(A.path)} file. Error: ${re.message}`,location:null,notes:[{text:re.message,location:null}],detail:re})}if(zm.DEBUG_BUILD_MODE&&U){let re=BS.resolve(s.outputDirectory,MN),Z=BS.relative(p,A.path),G=await Ffr.format(U,{parser:"babel"}),Te=hc.safePath(s.sourceDirectory).resolve(re,`${Z}.js`);await hc.mkdirForFilePathIfNotExits(Te),await w_t.writeFile(Te,G,"utf-8")}return{contents:U,errors:M,pluginName:Hk,resolveDir:BS.dirname(A.path),watchFiles:[A.path]}}))}}}t(I_t,"jsonSchemaPlugin");import{relative as Lfr,resolve as Rfr}from"path";import{dirname as Mfr}from"path";import{fileURLToPath as jfr}from"url";var O_t=["node:assert","node:async_hooks","node:buffer","node:crypto","node:diagnostics_channel","node:events","node:path","node:process","node:stream","node:string_decoder","node:util"],Bfr="nodejs-compat-plugin";function F_t({nodeCompatEnabled:s,sourceDirectory:a}){return{name:Bfr,setup(u){let p=new Set;u.onStart(()=>{p.clear()}),u.onResolve({filter:/node:.*/},async({path:g,kind:b,resolveDir:k,...A})=>{let M=`${g}:${b}:${k}:${A.importer}`;if(p.has(M))return;if(p.add(M),!s&&g==="node:async_hooks")return{path:Rfr(Mfr(jfr(import.meta.url)),"../../../polyfills/async_hooks.js")};let U=await u.resolve(g,{kind:b,resolveDir:k,importer:A.importer});return U.errors.length>0?s&&O_t.includes(g)||g.includes("/")&&O_t.includes(g.split("/")[0])?{external:!0}:{external:!0,warnings:U.errors.map(Z=>({...Z,location:{file:Lfr(a,A.importer),line:0,column:0,namespace:"",length:0,lineText:"",suggestion:"Remove the imported node module"},detail:`The package "${g}" wasn't found on the file system but is built into node. If this code is executed it will fail.`}))}:U})}}}t(F_t,"nodejsCompatPlugin");function Ufr(s){if(s.length>=255)throw new TypeError("Alphabet too long");let a=new Uint8Array(256);for(let U=0;U<a.length;U++)a[U]=255;for(let U=0;U<s.length;U++){let re=s.charAt(U),Z=re.charCodeAt(0);if(a[Z]!==255)throw new TypeError(re+" is ambiguous");a[Z]=U}let u=s.length,p=s.charAt(0),g=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function k(U){if(U instanceof Uint8Array||(ArrayBuffer.isView(U)?U=new Uint8Array(U.buffer,U.byteOffset,U.byteLength):Array.isArray(U)&&(U=Uint8Array.from(U))),!(U instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(U.length===0)return"";let re=0,Z=0,G=0,Te=U.length;for(;G!==Te&&U[G]===0;)G++,re++;let ge=(Te-G)*b+1>>>0,ve=new Uint8Array(ge);for(;G!==Te;){let Vt=U[G],hr=0;for(let Sr=ge-1;(Vt!==0||hr<Z)&&Sr!==-1;Sr--,hr++)Vt+=256*ve[Sr]>>>0,ve[Sr]=Vt%u>>>0,Vt=Vt/u>>>0;if(Vt!==0)throw new Error("Non-zero carry");Z=hr,G++}let dt=ge-Z;for(;dt!==ge&&ve[dt]===0;)dt++;let _t=p.repeat(re);for(;dt<ge;++dt)_t+=s.charAt(ve[dt]);return _t}t(k,"encode");function A(U){if(typeof U!="string")throw new TypeError("Expected String");if(U.length===0)return new Uint8Array;let re=0,Z=0,G=0;for(;U[re]===p;)Z++,re++;let Te=(U.length-re)*g+1>>>0,ge=new Uint8Array(Te);for(;U[re];){let Vt=a[U.charCodeAt(re)];if(Vt===255)return;let hr=0;for(let Sr=Te-1;(Vt!==0||hr<G)&&Sr!==-1;Sr--,hr++)Vt+=u*ge[Sr]>>>0,ge[Sr]=Vt%256>>>0,Vt=Vt/256>>>0;if(Vt!==0)throw new Error("Non-zero carry");G=hr,re++}let ve=Te-G;for(;ve!==Te&&ge[ve]===0;)ve++;let dt=new Uint8Array(Z+(Te-ve)),_t=Z;for(;ve!==Te;)dt[_t++]=ge[ve++];return dt}t(A,"decodeUnsafe");function M(U){let re=A(U);if(re)return re;throw new Error("Non-base"+u+" character")}return t(M,"decode"),{encode:k,decodeUnsafe:A,decode:M}}t(Ufr,"base");var L_t=Ufr;var $fr="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",xle=L_t($fr);var C4e="2024-09-02",R_t=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0}});function M_t(){return new ET({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:C4e,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:R_t[C4e]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}t(M_t,"getMockEnvironment");var ET=class s{static{t(this,"Environment")}config;static#t;static#r=!1;static initialize(a){this.#t||(this.#t=new s(a),this.#r=!0)}static get instance(){return this.#r||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#t=M_t()),this.#t}constructor({build:a,runtime:u}){let p;try{if(u.__ZUPLO_CONFIG){let g=atob(u.__ZUPLO_CONFIG);p=JSON.parse(g)}if(u.ZUPLO_SYSTEM_CONFIGURATIONS){let g=new TextDecoder().decode(xle.decode(u.ZUPLO_SYSTEM_CONFIGURATIONS)),b=JSON.parse(g);for(let k of Object.keys(b))u[k]=b[k]}}catch(g){console.error("Failed to parse runtime configuration",g)}this.config=p??{},this.build=a,this.runtime=u,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Jfr=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function j_t(s){return s.startsWith("__ZUPLO")||s.startsWith("ZUPLO_")?!Jfr.includes(s)&&!s.startsWith("ZUPLO_PUBLIC_"):!1}t(j_t,"isRestrictedEnvVariableName");function B_t(s){return!!s.startsWith("ZUPLO_")}t(B_t,"isZuploReadableEnvVariableName");var ZRr=new Proxy({},{get(s,a){let u=String(a);switch(u){case"ZUPLO_ENVIRONMENT_TYPE":return ET.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return ET.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return ET.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return ET.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return ET.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return ET.instance.build.BUILD_ID}if(!(j_t(u)&&!B_t(u)))return ET.instance.runtime[u]}});function nH(s,a,u){return`_${qP(s+"_"+a+"_"+u)}`}t(nH,"getRawOperationDataIdentifierName");function k4e(s,a,u,p){return`_${qP(s.toLowerCase())}_`+a.toLowerCase()+"_"+u.toLowerCase()+`_${p.toLowerCase()}`}t(k4e,"getIdForParameterSchema");function w4e(s,a,u){return`_${qP(s.toLowerCase())}_`+a.toLowerCase()+`_rb_${qP(u.toLowerCase())}`}t(w4e,"getIdForRequestBodySchema");function iH(s,a){return`_${qP(s)}__${qP(a)}`}t(iH,"getIdForRefSchema");function qP(s){let a=[];for(let u=0;u<s.length;u++){let p=s.charCodeAt(u);p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122?a.push(s.charAt(u)):a.push("_")}return a.join("")}t(qP,"sanitizedIdentifierName");var zgt=Rp(adt(),1);import{findNodeAtLocation as eK,getNodeValue as que,printParseErrorCode as nbr}from"jsonc-parser";import POe from"path";var gH=class{static{t(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(s,a,u,p,g,b){this.type=s,this.name=a,this.prefix=u,this.value=p,this.suffix=g,this.modifier=b}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},mdr=/[$_\p{ID_Start}]/u,hdr=/[$_\u200C\u200D\p{ID_Continue}]/u,o3e=".*";function gdr(s,a){return(a?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(s)}t(gdr,"Re");function ldt(s,a=!1){let u=[],p=0;for(;p<s.length;){let g=s[p],b=t(function(k){if(!a)throw new TypeError(k);u.push({type:"INVALID_CHAR",index:p,value:s[p++]})},"c");if(g==="*"){u.push({type:"ASTERISK",index:p,value:s[p++]});continue}if(g==="+"||g==="?"){u.push({type:"OTHER_MODIFIER",index:p,value:s[p++]});continue}if(g==="\\"){u.push({type:"ESCAPED_CHAR",index:p++,value:s[p++]});continue}if(g==="{"){u.push({type:"OPEN",index:p,value:s[p++]});continue}if(g==="}"){u.push({type:"CLOSE",index:p,value:s[p++]});continue}if(g===":"){let k="",A=p+1;for(;A<s.length;){let M=s.substr(A,1);if(A===p+1&&mdr.test(M)||A!==p+1&&hdr.test(M)){k+=s[A++];continue}break}if(!k){b(`Missing parameter name at ${p}`);continue}u.push({type:"NAME",index:p,value:k}),p=A;continue}if(g==="("){let k=1,A="",M=p+1,U=!1;if(s[M]==="?"){b(`Pattern cannot start with "?" at ${M}`);continue}for(;M<s.length;){if(!gdr(s[M],!1)){b(`Invalid character '${s[M]}' at ${M}.`),U=!0;break}if(s[M]==="\\"){A+=s[M++]+s[M++];continue}if(s[M]===")"){if(k--,k===0){M++;break}}else if(s[M]==="("&&(k++,s[M+1]!=="?")){b(`Capturing groups are not allowed at ${M}`),U=!0;break}A+=s[M++]}if(U)continue;if(k){b(`Unbalanced pattern at ${p}`);continue}if(!A){b(`Missing pattern at ${p}`);continue}u.push({type:"REGEX",index:p,value:A}),p=M;continue}u.push({type:"CHAR",index:p,value:s[p++]})}return u.push({type:"END",index:p,value:""}),u}t(ldt,"v");function udt(s,a={}){let u=ldt(s);a.delimiter??="/#?",a.prefixes??="./";let p=`[^${wT(a.delimiter)}]+?`,g=[],b=0,k=0,A="",M=new Set,U=t(hr=>{if(k<u.length&&u[k].type===hr)return u[k++].value},"a"),re=t(()=>U("OTHER_MODIFIER")??U("ASTERISK"),"f"),Z=t(hr=>{let Sr=U(hr);if(Sr!==void 0)return Sr;let{type:Zt,index:lr}=u[k];throw new TypeError(`Unexpected ${Zt} at ${lr}, expected ${hr}`)},"d"),G=t(()=>{let hr="",Sr;for(;Sr=U("CHAR")??U("ESCAPED_CHAR");)hr+=Sr;return hr},"T"),Te=t(hr=>hr,"Se"),ge=a.encodePart||Te,ve="",dt=t(hr=>{ve+=hr},"U"),_t=t(()=>{ve.length&&(g.push(new gH(3,"","",ge(ve),"",3)),ve="")},"$"),Vt=t((hr,Sr,Zt,lr,Xt)=>{let ei=3;switch(Xt){case"?":ei=1;break;case"*":ei=0;break;case"+":ei=2;break}if(!Sr&&!Zt&&ei===3){dt(hr);return}if(_t(),!Sr&&!Zt){if(!hr)return;g.push(new gH(3,"","",ge(hr),"",ei));return}let fr;Zt?Zt==="*"?fr=o3e:fr=Zt:fr=p;let wi=2;fr===p?(wi=1,fr=""):fr===o3e&&(wi=0,fr="");let un;if(Sr?un=Sr:Zt&&(un=b++),M.has(un))throw new TypeError(`Duplicate name '${un}'.`);M.add(un),g.push(new gH(wi,un,ge(hr),fr,ge(lr),ei))},"V");for(;k<u.length;){let hr=U("CHAR"),Sr=U("NAME"),Zt=U("REGEX");if(!Sr&&!Zt&&(Zt=U("ASTERISK")),Sr||Zt){let Xt=hr??"";a.prefixes.indexOf(Xt)===-1&&(dt(Xt),Xt=""),_t();let ei=re();Vt(Xt,Sr,Zt,"",ei);continue}let lr=hr??U("ESCAPED_CHAR");if(lr){dt(lr);continue}if(U("OPEN")){let Xt=G(),ei=U("NAME"),fr=U("REGEX");!ei&&!fr&&(fr=U("ASTERISK"));let wi=G();Z("CLOSE");let un=re();Vt(Xt,ei,fr,wi,un);continue}_t(),Z("END")}return g}t(udt,"D");function wT(s){return s.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(wT,"S");function odt(s){return s&&s.ignoreCase?"ui":"u"}t(odt,"X");function ydr(s,a,u){return fdt(udt(s,u),a,u)}t(ydr,"Z");function MM(s){switch(s){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}t(MM,"k");function fdt(s,a,u={}){u.delimiter??="/#?",u.prefixes??="./",u.sensitive??=!1,u.strict??=!1,u.end??=!0,u.start??=!0,u.endsWith="";let p=u.start?"^":"";for(let A of s){if(A.type===3){A.modifier===3?p+=wT(A.value):p+=`(?:${wT(A.value)})${MM(A.modifier)}`;continue}a&&a.push(A.name);let M=`[^${wT(u.delimiter)}]+?`,U=A.value;if(A.type===1?U=M:A.type===0&&(U=o3e),!A.prefix.length&&!A.suffix.length){A.modifier===3||A.modifier===1?p+=`(${U})${MM(A.modifier)}`:p+=`((?:${U})${MM(A.modifier)})`;continue}if(A.modifier===3||A.modifier===1){p+=`(?:${wT(A.prefix)}(${U})${wT(A.suffix)})`,p+=MM(A.modifier);continue}p+=`(?:${wT(A.prefix)}`,p+=`((?:${U})(?:`,p+=wT(A.suffix),p+=wT(A.prefix),p+=`(?:${U}))*)${wT(A.suffix)})`,A.modifier===0&&(p+="?")}let g=`[${wT(u.endsWith)}]|$`,b=`[${wT(u.delimiter)}]`;if(u.end)return u.strict||(p+=`${b}?`),u.endsWith.length?p+=`(?=${g})`:p+="$",new RegExp(p,odt(u));u.strict||(p+=`(?:${b}(?=${g}))?`);let k=!1;if(s.length){let A=s[s.length-1];A.type===3&&A.modifier===3&&(k=u.delimiter.indexOf(A)>-1)}return k||(p+=`(?=${b}|${g})`),new RegExp(p,odt(u))}t(fdt,"F");var hI={delimiter:"",prefixes:"",sensitive:!0,strict:!0},vdr={delimiter:".",prefixes:"",sensitive:!0,strict:!0},bdr={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function Sdr(s,a){return s.length?s[0]==="/"?!0:!a||s.length<2?!1:(s[0]=="\\"||s[0]=="{")&&s[1]=="/":!1}t(Sdr,"J");function _dt(s,a){return s.startsWith(a)?s.substring(a.length,s.length):s}t(_dt,"Q");function Tdr(s,a){return s.endsWith(a)?s.substr(0,s.length-a.length):s}t(Tdr,"Ee");function pdt(s){return!s||s.length<2?!1:s[0]==="["||(s[0]==="\\"||s[0]==="{")&&s[1]==="["}t(pdt,"W");var ddt=["ftp","file","http","https","ws","wss"];function mdt(s){if(!s)return!0;for(let a of ddt)if(s.test(a))return!0;return!1}t(mdt,"N");function xdr(s,a){if(s=_dt(s,"#"),a||s==="")return s;let u=new URL("https://example.com");return u.hash=s,u.hash?u.hash.substring(1,u.hash.length):""}t(xdr,"te");function Edr(s,a){if(s=_dt(s,"?"),a||s==="")return s;let u=new URL("https://example.com");return u.search=s,u.search?u.search.substring(1,u.search.length):""}t(Edr,"re");function Cdr(s,a){return a||s===""?s:pdt(s)?ydt(s):gdt(s)}t(Cdr,"ne");function kdr(s,a){if(a||s==="")return s;let u=new URL("https://example.com");return u.password=s,u.password}t(kdr,"se");function wdr(s,a){if(a||s==="")return s;let u=new URL("https://example.com");return u.username=s,u.username}t(wdr,"ie");function Ddr(s,a,u){if(u||s==="")return s;if(a&&!ddt.includes(a))return new URL(`${a}:${s}`).pathname;let p=s[0]=="/";return s=new URL(p?s:"/-"+s,"https://example.com").pathname,p||(s=s.substring(2,s.length)),s}t(Ddr,"ae");function Pdr(s,a,u){return hdt(a)===s&&(s=""),u||s===""?s:vdt(s)}t(Pdr,"oe");function Adr(s,a){return s=Tdr(s,":"),a||s===""?s:c3e(s)}t(Adr,"ce");function hdt(s){switch(s){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}t(hdt,"_");function c3e(s){if(s==="")return s;if(/^[-+.A-Za-z0-9]*$/.test(s))return s.toLowerCase();throw new TypeError(`Invalid protocol '${s}'.`)}t(c3e,"y");function Ndr(s){if(s==="")return s;let a=new URL("https://example.com");return a.username=s,a.username}t(Ndr,"le");function Idr(s){if(s==="")return s;let a=new URL("https://example.com");return a.password=s,a.password}t(Idr,"fe");function gdt(s){if(s==="")return s;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(s))throw new TypeError(`Invalid hostname '${s}'`);let a=new URL("https://example.com");return a.hostname=s,a.hostname}t(gdt,"z");function ydt(s){if(s==="")return s;if(/[^0-9a-fA-F[\]:]/g.test(s))throw new TypeError(`Invalid IPv6 hostname '${s}'`);return s.toLowerCase()}t(ydt,"j");function vdt(s){if(s===""||/^[0-9]*$/.test(s)&&parseInt(s)<=65535)return s;throw new TypeError(`Invalid port '${s}'.`)}t(vdt,"K");function Odr(s){if(s==="")return s;let a=new URL("https://example.com");return a.pathname=s[0]!=="/"?"/-"+s:s,s[0]!=="/"?a.pathname.substring(2,a.pathname.length):a.pathname}t(Odr,"he");function Fdr(s){return s===""?s:new URL(`data:${s}`).pathname}t(Fdr,"ue");function Ldr(s){if(s==="")return s;let a=new URL("https://example.com");return a.search=s,a.search.substring(1,a.search.length)}t(Ldr,"de");function Rdr(s){if(s==="")return s;let a=new URL("https://example.com");return a.hash=s,a.hash.substring(1,a.hash.length)}t(Rdr,"pe");var Mdr=class{static{t(this,"H")}#t;#r=[];#i={};#e=0;#a=1;#m=0;#o=0;#u=0;#c=0;#l=!1;constructor(s){this.#t=s}get result(){return this.#i}parse(){for(this.#r=ldt(this.#t,!0);this.#e<this.#r.length;this.#e+=this.#a){if(this.#a=1,this.#r[this.#e].type==="END"){if(this.#o===0){this.#y(),this.#E()?this.#n(9,1):this.#_()?this.#n(8,1):this.#n(7,0);continue}else if(this.#o===2){this.#p(5);continue}this.#n(10,0);break}if(this.#u>0)if(this.#s())this.#u-=1;else continue;if(this.#D()){this.#u+=1;continue}switch(this.#o){case 0:this.#g()&&this.#p(1);break;case 1:if(this.#g()){this.#I();let s=7,a=1;this.#w()?(s=2,a=3):this.#l&&(s=2),this.#n(s,a)}break;case 2:this.#C()?this.#p(3):(this.#x()||this.#_()||this.#E())&&this.#p(5);break;case 3:this.#T()?this.#n(4,1):this.#C()&&this.#n(5,1);break;case 4:this.#C()&&this.#n(5,1);break;case 5:this.#N()?this.#c+=1:this.#b()&&(this.#c-=1),this.#k()&&!this.#c?this.#n(6,1):this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 6:this.#x()?this.#n(7,0):this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 7:this.#_()?this.#n(8,1):this.#E()&&this.#n(9,1);break;case 8:this.#E()&&this.#n(9,1);break;case 9:break;case 10:break}}this.#i.hostname!==void 0&&this.#i.port===void 0&&(this.#i.port="")}#n(s,a){switch(this.#o){case 0:break;case 1:this.#i.protocol=this.#S();break;case 2:break;case 3:this.#i.username=this.#S();break;case 4:this.#i.password=this.#S();break;case 5:this.#i.hostname=this.#S();break;case 6:this.#i.port=this.#S();break;case 7:this.#i.pathname=this.#S();break;case 8:this.#i.search=this.#S();break;case 9:this.#i.hash=this.#S();break;case 10:break}this.#o!==0&&s!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(s)&&(this.#i.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(s)&&(this.#i.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&s===9&&(this.#i.search??="")),this.#v(s,a)}#v(s,a){this.#o=s,this.#m=this.#e+a,this.#e+=a,this.#a=0}#y(){this.#e=this.#m,this.#a=0}#p(s){this.#y(),this.#o=s}#d(s){return s<0&&(s=this.#r.length-s),s<this.#r.length?this.#r[s]:this.#r[this.#r.length-1]}#h(s,a){let u=this.#d(s);return u.value===a&&(u.type==="CHAR"||u.type==="ESCAPED_CHAR"||u.type==="INVALID_CHAR")}#g(){return this.#h(this.#e,":")}#w(){return this.#h(this.#e+1,"/")&&this.#h(this.#e+2,"/")}#C(){return this.#h(this.#e,"@")}#T(){return this.#h(this.#e,":")}#k(){return this.#h(this.#e,":")}#x(){return this.#h(this.#e,"/")}#_(){if(this.#h(this.#e,"?"))return!0;if(this.#r[this.#e].value!=="?")return!1;let s=this.#d(this.#e-1);return s.type!=="NAME"&&s.type!=="REGEX"&&s.type!=="CLOSE"&&s.type!=="ASTERISK"}#E(){return this.#h(this.#e,"#")}#D(){return this.#r[this.#e].type=="OPEN"}#s(){return this.#r[this.#e].type=="CLOSE"}#N(){return this.#h(this.#e,"[")}#b(){return this.#h(this.#e,"]")}#S(){let s=this.#r[this.#e],a=this.#d(this.#m).index;return this.#t.substring(a,s.index)}#I(){let s={};Object.assign(s,hI),s.encodePart=c3e;let a=ydr(this.#S(),void 0,s);this.#l=mdt(a)}},a3e=["protocol","username","password","hostname","port","pathname","search","hash"],mI="*";function cdt(s,a){if(typeof s!="string")throw new TypeError("parameter 1 is not of type 'string'.");let u=new URL(s,a);return{protocol:u.protocol.substring(0,u.protocol.length-1),username:u.username,password:u.password,hostname:u.hostname,port:u.port,pathname:u.pathname,search:u.search!==""?u.search.substring(1,u.search.length):void 0,hash:u.hash!==""?u.hash.substring(1,u.hash.length):void 0}}t(cdt,"ge");function GP(s,a){return a?hH(s):s}t(GP,"b");function mH(s,a,u){let p;if(typeof a.baseURL=="string")try{p=new URL(a.baseURL),a.protocol===void 0&&(s.protocol=GP(p.protocol.substring(0,p.protocol.length-1),u)),!u&&a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.username===void 0&&(s.username=GP(p.username,u)),!u&&a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.username===void 0&&a.password===void 0&&(s.password=GP(p.password,u)),a.protocol===void 0&&a.hostname===void 0&&(s.hostname=GP(p.hostname,u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&(s.port=GP(p.port,u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.pathname===void 0&&(s.pathname=GP(p.pathname,u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.pathname===void 0&&a.search===void 0&&(s.search=GP(p.search.substring(1,p.search.length),u)),a.protocol===void 0&&a.hostname===void 0&&a.port===void 0&&a.pathname===void 0&&a.search===void 0&&a.hash===void 0&&(s.hash=GP(p.hash.substring(1,p.hash.length),u))}catch{throw new TypeError(`invalid baseURL '${a.baseURL}'.`)}if(typeof a.protocol=="string"&&(s.protocol=Adr(a.protocol,u)),typeof a.username=="string"&&(s.username=wdr(a.username,u)),typeof a.password=="string"&&(s.password=kdr(a.password,u)),typeof a.hostname=="string"&&(s.hostname=Cdr(a.hostname,u)),typeof a.port=="string"&&(s.port=Pdr(a.port,s.protocol,u)),typeof a.pathname=="string"){if(s.pathname=a.pathname,p&&!Sdr(s.pathname,u)){let g=p.pathname.lastIndexOf("/");g>=0&&(s.pathname=GP(p.pathname.substring(0,g+1),u)+s.pathname)}s.pathname=Ddr(s.pathname,s.protocol,u)}return typeof a.search=="string"&&(s.search=Edr(a.search,u)),typeof a.hash=="string"&&(s.hash=xdr(a.hash,u)),s}t(mH,"w");function hH(s){return s.replace(/([+*?:{}()\\])/g,"\\$1")}t(hH,"C");function jdr(s){return s.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}t(jdr,"Oe");function Bdr(s,a){a.delimiter??="/#?",a.prefixes??="./",a.sensitive??=!1,a.strict??=!1,a.end??=!0,a.start??=!0,a.endsWith="";let u=".*",p=`[^${jdr(a.delimiter)}]+?`,g=/[$_\u200C\u200D\p{ID_Continue}]/u,b="";for(let k=0;k<s.length;++k){let A=s[k];if(A.type===3){if(A.modifier===3){b+=hH(A.value);continue}b+=`{${hH(A.value)}}${MM(A.modifier)}`;continue}let M=A.hasCustomName(),U=!!A.suffix.length||!!A.prefix.length&&(A.prefix.length!==1||!a.prefixes.includes(A.prefix)),re=k>0?s[k-1]:null,Z=k<s.length-1?s[k+1]:null;if(!U&&M&&A.type===1&&A.modifier===3&&Z&&!Z.prefix.length&&!Z.suffix.length)if(Z.type===3){let G=Z.value.length>0?Z.value[0]:"";U=g.test(G)}else U=!Z.hasCustomName();if(!U&&!A.prefix.length&&re&&re.type===3){let G=re.value[re.value.length-1];U=a.prefixes.includes(G)}U&&(b+="{"),b+=hH(A.prefix),M&&(b+=`:${A.name}`),A.type===2?b+=`(${A.value})`:A.type===1?M||(b+=`(${p})`):A.type===0&&(!M&&(!re||re.type===3||re.modifier!==3||U||A.prefix!=="")?b+="*":b+=`(${u})`),A.type===1&&M&&A.suffix.length&&g.test(A.suffix[0])&&(b+="\\"),b+=hH(A.suffix),U&&(b+="}"),A.modifier!==3&&(b+=MM(A.modifier))}return b}t(Bdr,"ke");var bdt=class{static{t(this,"me")}#t;#r={};#i={};#e={};#a={};#m=!1;constructor(s={},a,u){try{let p;if(typeof a=="string"?p=a:u=a,typeof s=="string"){let A=new Mdr(s);if(A.parse(),s=A.result,p===void 0&&typeof s.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");s.baseURL=p}else{if(!s||typeof s!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(p)throw new TypeError("parameter 1 is not of type 'string'.")}typeof u>"u"&&(u={ignoreCase:!1});let g={ignoreCase:u.ignoreCase===!0},b={pathname:mI,protocol:mI,username:mI,password:mI,hostname:mI,port:mI,search:mI,hash:mI};this.#t=mH(b,s,!0),hdt(this.#t.protocol)===this.#t.port&&(this.#t.port="");let k;for(k of a3e){if(!(k in this.#t))continue;let A={},M=this.#t[k];switch(this.#i[k]=[],k){case"protocol":Object.assign(A,hI),A.encodePart=c3e;break;case"username":Object.assign(A,hI),A.encodePart=Ndr;break;case"password":Object.assign(A,hI),A.encodePart=Idr;break;case"hostname":Object.assign(A,vdr),pdt(M)?A.encodePart=ydt:A.encodePart=gdt;break;case"port":Object.assign(A,hI),A.encodePart=vdt;break;case"pathname":mdt(this.#r.protocol)?(Object.assign(A,bdr,g),A.encodePart=Odr):(Object.assign(A,hI,g),A.encodePart=Fdr);break;case"search":Object.assign(A,hI,g),A.encodePart=Ldr;break;case"hash":Object.assign(A,hI,g),A.encodePart=Rdr;break}try{this.#a[k]=udt(M,A),this.#r[k]=fdt(this.#a[k],this.#i[k],A),this.#e[k]=Bdr(this.#a[k],A),this.#m=this.#m||this.#a[k].some(U=>U.type===2)}catch{throw new TypeError(`invalid ${k} pattern '${this.#t[k]}'.`)}}}catch(p){throw new TypeError(`Failed to construct 'URLPattern': ${p.message}`)}}test(s={},a){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof s!="string"&&a)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof s>"u")return!1;try{typeof s=="object"?u=mH(u,s,!1):u=mH(u,cdt(s,a),!1)}catch{return!1}let p;for(p of a3e)if(!this.#r[p].exec(u[p]))return!1;return!0}exec(s={},a){let u={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof s!="string"&&a)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof s>"u")return;try{typeof s=="object"?u=mH(u,s,!1):u=mH(u,cdt(s,a),!1)}catch{return null}let p={};a?p.inputs=[s,a]:p.inputs=[s];let g;for(g of a3e){let b=this.#r[g].exec(u[g]);if(!b)return null;let k={};for(let[A,M]of this.#i[g].entries())if(typeof M=="string"||typeof M=="number"){let U=b[A+1];k[M]=U}p[g]={input:u[g]??"",groups:k}}return p}static compareComponent(s,a,u){let p=t((A,M)=>{for(let U of["type","modifier","prefix","value","suffix"]){if(A[U]<M[U])return-1;if(A[U]!==M[U])return 1}return 0},"o"),g=new gH(3,"","","","",3),b=new gH(0,"","","","",3),k=t((A,M)=>{let U=0;for(;U<Math.min(A.length,M.length);++U){let re=p(A[U],M[U]);if(re)return re}return A.length===M.length?0:p(A[U]??g,M[U]??g)},"s");return!a.#e[s]&&!u.#e[s]?0:a.#e[s]&&!u.#e[s]?k(a.#a[s],[b]):!a.#e[s]&&u.#e[s]?k([b],u.#a[s]):k(a.#a[s],u.#a[s])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#m}};globalThis.URLPattern||(globalThis.URLPattern=bdt);import{AssertionError as Udr}from"assert";function $O(s,a){if(s===!1)throw new Udr({message:a})}t($O,"assert");var bc;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.FunctionBody="FunctionBody"})(bc||(bc={}));function yH(s){return s.type===bc.Object}t(yH,"isAstObject");function HP(s){return s.type===bc.Property}t(HP,"isAstProperty");function Sdt(s){return s.type===bc.Array}t(Sdt,"isAstArray");function jM(s){return s.type===bc.Literal}t(jM,"isAstLiteral");import{visit as $dr}from"jsonc-parser";var Jdr={DEFAULT:{allowTrailingComma:!1}};function vH(s,a=[],u=Jdr.DEFAULT){let p={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function g(M){p.type==="property"&&(p.length=M-p.offset,p=p.parent)}t(g,"ensurePropertyComplete");function b(M){return p.children?.push(M),M}t(b,"onValue"),$dr(s,{onObjectBegin:t((M,U,re)=>{p=b({type:"object",offset:M,length:-1,line:U+1,column:re+1,parent:p,children:[]})},"onObjectBegin"),onObjectProperty:t((M,U,re,Z,G)=>{p=b({type:"property",offset:U,length:-1,line:Z+1,column:G+1,parent:p,children:[]}),p.children?.push({type:"string",value:M,offset:U,length:re,line:Z,column:G,parent:p})},"onObjectProperty"),onObjectEnd:t((M,U)=>{g(M+U),p.length=M+U-p.offset,p=p.parent,g(M+U)},"onObjectEnd"),onArrayBegin:t((M,U,re,Z)=>{p=b({type:"array",offset:M,length:-1,line:re+1,column:Z+1,parent:p,children:[]})},"onArrayBegin"),onArrayEnd:t((M,U)=>{p.length=M+U-p.offset,p=p.parent,g(M+U)},"onArrayEnd"),onLiteralValue:t((M,U,re,Z,G)=>{b({type:qdr(M),offset:U,length:re,line:Z+1,column:G+1,parent:p,value:M}),g(U+re)},"onLiteralValue"),onSeparator:t((M,U)=>{p.type==="property"&&(M===":"?p.colonOffset=U:M===","&&g(U))},"onSeparator"),onError:t((M,U,re,Z,G)=>{a.push({error:M,offset:U,length:re,line:Z+1,column:G+1})},"onError")},u);let A=p.children[0];return A&&delete A.parent,A}t(vH,"parse");function qdr(s){switch(typeof s){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(s){if(Array.isArray(s))return"array"}else return"null";return"object"}default:return"null"}}t(qdr,"getNodeType");var bH=class{static{t(this,"AstAdapter")}parse(a){let p=vH(a,[]);if(p)return this.parseNode(p,void 0);throw new Error("Failed to parse JSON")}convert(a){return this.parseNode(a,void 0)}parseNode(a,u){switch(a.type){case"object":return this.createObject(a,u);case"array":return this.createArray(a,u);case"property":return this.createProperty(a,u);case"string":return this.createLiteral(a,u);case"number":return this.createLiteral(a,u);case"boolean":return this.createLiteral(a,u);case"null":return this.createLiteral(a,u)}}createLiteral(a,u){return{type:bc.Literal,location:{line:a.line,column:a.column},parent:u,value:a.type==="null"?null:a.value}}createObject(a,u){let p={type:bc.Object,children:[],parent:u,location:{line:a.line,column:a.column}};return a.children?.forEach(g=>{p.children.push(this.parseNode(g,p))}),p}createProperty(a,u){$O(a.children?.length===2,"Invalid property node");let p={type:bc.Property,location:{line:a.line,column:a.column},parent:u,name:null,value:null};return p.name={value:a.children[0].value,location:{line:a.line,column:a.column},type:bc.Identifier,parent:p},p.value=this.parseNode(a.children[1],p),p}createArray(a,u){let p={type:bc.Array,location:{line:a.line,column:a.column},parent:u,children:[]};return a.children?.forEach(g=>p.children.push(this.parseNode(g,p))),p}};var DT={createLiteral:t((s,a)=>({type:bc.Literal,parent:a,value:s}),"createLiteral"),createTemplateString:t((s,a)=>({type:bc.TemplateString,parent:a,value:s}),"createTemplateString"),createIdentifier:t((s,a)=>({type:bc.Identifier,value:s,parent:a}),"createIdentifier"),createProperty:t((s,a,u)=>{let p={type:bc.Property,parent:u,name:null,value:a};return p.name={value:s,type:bc.Identifier,parent:p},p.value.parent=p,p},"createProperty"),createArrayOfLiterals:t((s,a)=>{let u={type:bc.Array,parent:a,children:[]};for(let p of s)u.children.push(DT.createLiteral(p,u));return u},"createArrayOfLiterals")};var SH=class{static{t(this,"SourceGenerator")}generate(a){let u=[];return this.generateSource(u,a),u.join("")}generateSource(a,u){switch(u.type){case bc.Array:return this.generateArray(a,u);case bc.Object:return this.generateObject(a,u);case bc.Property:return this.generateProperty(a,u);case bc.Literal:return this.generateLiteral(a,u);case bc.FunctionCall:return this.generateFunctionCall(a,u);case bc.Identifier:return this.generateIdentifier(a,u);case bc.FunctionBody:return this.generateFunctionBody(a,u);case bc.TemplateString:return this.generateTemplateString(a,u)}}generateArray(a,u){a.push("["),u.children.map(p=>{this.generateSource(a,p),a.push(",")}),a.push("]")}generateObject(a,u){a.push("{"),u.children.forEach(p=>{this.generateSource(a,p),a.push(",")}),a.push("}")}generateProperty(a,u){let p=u.name.value,g=p.search(/(\/|\\|-|\+|@|#|%|\^|&|\*|:|\.)/g)<0?p:`'${p}'`;a.push(g),a.push(":"),this.generateSource(a,u.value)}generateFunctionCall(a,u){a.push(u.name.value),a.push("("),u.children.forEach((p,g,b)=>{this.generateSource(a,p),g<b.length&&a.push(",")}),a.push(")")}generateFunctionBody(a,u){a.push(u.value)}generateTemplateString(a,u){a.push("`"),a.push(u.value.replaceAll("`","\\`")),a.push("`")}generateLiteral(a,u){if(u.value===null)return a.push("null");switch(typeof u.value){case"number":case"boolean":return a.push(`${u.value}`);case"string":{let p=u.value,g=JSON.stringify(p);return a.push(`${g}`)}}}generateIdentifier(a,u){a.push(u.value)}};import{parse as zdr}from"@swc/core";import Vdr from"fs/promises";var Tdt=t(async s=>{let a=new Set;try{let u=await Vdr.readFile(s,"utf-8");(await zdr(u,{syntax:"typescript"})).body.forEach(g=>{g.type==="ExportDefaultDeclaration"||g.type==="ExportDefaultExpression"?a.add("default"):g.type==="ExportDeclaration"&&g.declaration.type==="FunctionDeclaration"?a.add(g.declaration.identifier.value):g.type==="ExportDeclaration"&&g.declaration.type==="VariableDeclaration"&&g.declaration.declarations[0].id.type==="Identifier"&&a.add(g.declaration.declarations[0].id.value)})}catch{return null}return a},"getJSFileExports");var xdt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var l3e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var Edt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var u3e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var f3e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler","version"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},version:{type:"string",pattern:"^[0-9a-z-]+$"},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var Cdt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/routes.schema.json",title:"Route Config File",type:"object",additionalProperties:!1,required:["routes","versions"],$defs:{info:{type:"object",required:["title","version"],properties:{title:{type:"string"},summary:{type:"string"},description:{type:"string"},termsOfService:{type:"string",format:"uri"},version:{type:"string"}}},versionData:{type:"object",required:["name","pathPrefix"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},pathPrefix:{type:"string",pattern:"(^$|^/[^\\s]*$)"},info:{$ref:"#/$defs/info"},openApiFile:{description:"The project relative path to the OpenAPI spec.",type:"string"},excludeFromOpenApi:{type:"boolean",description:"If false, OpenAPI documentation will not be generated for this version. If openApiFile is set this setting is ignored."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."}}}},properties:{$schema:{type:"string"},versions:{type:"array",minItems:1,items:{$ref:"#/$defs/versionData"}},routes:{type:"array",minItems:0,items:{$ref:"route-configuration.schema.json"}},policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}},requestErrorHandler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"}}};var Rgt=Rp(sgt(),1),Mgt=Rp(Lgt(),1);var Lue=class s{static{t(this,"JsonValidator")}static#t=new s;static get instance(){return s.#t}ajv;constructor(){this.ajv=new Mgt.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Rgt.default)(this.ajv,{mode:"fast"})}addSchema(a,u){this.ajv.addSchema(a,u)}compile(a){let u=this.ajv.compile(a);return t(g=>({isValid:u(g),errors:this.toSimpleErrors(u.errors,g),warnings:[]}),"validator")}toSimpleErrors(a,u){let p=[];return a?.forEach(g=>{g.keyword==="enum"&&g.params.allowedValues&&Array.isArray(g.params.allowedValues)&&(g.message+=`; ${g.params.allowedValues.join(", ")}`),g.instancePath&&(g.instancePath=g.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let b={details:{}},k=g.instancePath.split("/");if(k.length>2){let M=k[1],U=k[2]?parseInt(k[2]):0,re=k[3],Z=isNaN(U)?void 0:u[M][U][re];b={details:{property:M,index:U,field:re,fieldValue:Z}}}if(g.keyword==="required"&&g.params.missingProperty&&g.instancePath&&(g.message=`A 'path' is missing required property '${g.params.missingProperty}'`),g.keyword==="additionalProperties"&&g.params.additionalProperty&&g.instancePath&&(g.message=`A 'path' should NOT include property '${g.params.additionalProperty}'`),g.keyword==="type"&&g.params.type&&g.instancePath){let M=g.instancePath.split("/"),U=M[M.length-1];g.message=`Value of property '${U}' must be '${g.params.type}'`}let A=Object.assign(g,b);p.push(A)}),p}};var ZP=Lue.instance;ZP.addSchema(Cdt,"routes.schema.json");ZP.addSchema(f3e,"route-configuration.schema.json");ZP.addSchema(Edt,"policy-configuration.schema.json");ZP.addSchema(l3e,"policies.schema.json");ZP.addSchema(u3e,"open-api-route-configuration.schema.json");ZP.addSchema(xdt,"fragments.schema.json");var Yvr=ZP.compile(f3e),jgt=ZP.compile(u3e),COe=ZP.compile(l3e);var Rue=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(a){return this.results=COe(a),this.results}};var Mue=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(a){return this.results=jgt(a),this.results}};import Qvr from"path";var kOe=/\$import\((.*)\)/,jue=/\$env\((.*?)\)/g;var eA=class extends Error{static{t(this,"CodeGenError")}location;constructor(a,u,p,g){super(a),this.location={file:u,namespace:"",line:p?p.line:0,column:p?p.column:0,length:0,lineText:g??"",suggestion:""}}},Xvr=t(s=>{let a=[],u=s;for(;u.parent;)a.push(u),u=u.parent;return a.reverse()},"invertTree"),CI=t((s,a)=>{if(!s)return!1;let u=Xvr(s);return a.split("/").every((b,k)=>{let A=u[k];return A?b==="*"||HP(A)&&A.name.value===b?!0:b==="{}"?A.type===bc.Object:b==="[]"?A.type===bc.Array:!1:!1})},"testPosition");var Bue=class{static{t(this,"AstTransformer")}errors=[];transform(a){return this.visitor(a),a}visitor(a){this.visit(a),yH(a)?a.children.forEach(u=>{this.visitor(u)}):Sdt(a)?a.children.forEach(u=>{this.visitor(u)}):HP(a)&&this.visitor(a.value)}},Bgt=t((s,a,u)=>p=>{if(!HP(p)||!jM(p.value)||typeof p.value.value!="string")return;if(!s.some(b=>CI(p,b))){jue.test(p.value.value)&&a.push(new eA("An $env() statement is not expected at this location.",u,p.location,p.value.value));return}let g=new RegExp(jue).exec(p.value.value);if(g?.length===2&&g[0]===p.value.value){let b={type:bc.FunctionBody,parent:null,value:`environment["${g[1]}"]`};p.value=b}else{let b=p.value.value.replaceAll(new RegExp(jue),(k,A)=>`\${environment["${A}"] ? environment["${A}"] : ""}`);b!==p.value.value&&(p.value=DT.createTemplateString(b,p))}},"getEnvStatementTransformer");var ZH="config/routes.json",Zvr=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*","corsPolicies/[]/{}/*"],ebr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Ugt=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],tbr="handler/{}/options/{}/rewritePattern",rbr="handler/{}/options/{}/baseUrl",Uue=class extends Bue{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(a){this.addedImports.has(a)||this.addedImports.set(a,`__import${this.importCount++}`);let u=this.addedImports.get(a);if(!u)throw new Error("Import name is undefined. This should not happen.");return u}getImports(){let a=[];return this.addedImports.forEach((u,p)=>{a.push({name:u,path:p})}),a}visit(a){this.rewriteHandlerFunction(a),this.rewriteForwardFunction(a),this.replaceImportStatements(a),this.replaceEnvStatements(a)}rewriteHandlerFunction(a){if(!(!HP(a)||!jM(a.value)||typeof a.value.value!="string")&&CI(a,tbr)){if(!a.parent||!yH(a.parent)){this.errors.push(new eA("Invalid node, expected object",ZH,a.parent?a.parent.location:a.location,void 0));return}let u=a.value.value,p={type:bc.FunctionBody,parent:null,value:$gt(u)},g=DT.createProperty("__rewriteFunction",p,a);a.parent.children.push(g)}}rewriteForwardFunction(a){if(!(!HP(a)||!jM(a.value)||typeof a.value.value!="string")&&CI(a,rbr)){if(!a.parent||!yH(a.parent)){this.errors.push(new eA("Invalid node, expected object",ZH,a.parent?a.parent.location:a.location,void 0));return}let u=a.value.value,p={type:bc.FunctionBody,parent:null,value:$gt(u)},g=DT.createProperty("__rewriteFunction",p,a);a.parent.children.push(g)}}replaceImportStatements(a){if(!HP(a)||!jM(a.value))return;let u=a.value.value;if(typeof u!="string")return;if(!ebr.some(A=>CI(a,A))&&!Ugt.some(A=>CI(a,A))){if(kOe.test(u)){if(a.name.value==="$ref")return;this.errors.push(new eA("An $import() statement is not expected at this location.",ZH,a.location,u))}return}let p=kOe.exec(u);if(Ugt.some(A=>CI(a,A))&&!p)return;if(!p){this.errors.push(new eA("Invalid $import() statement",ZH,a.location,u));return}let g=p[1];g.startsWith(".")&&(g=Qvr.join("..",g));let b=this.getImportName(g),k={type:bc.Identifier,parent:a.parent,value:b};a.value=k}replaceEnvStatements=Bgt(Zvr,this.errors,ZH)};function $gt(s){return`(request, context) => {
710
710
  const { params, url, query, method, headers } = request;
711
711
  const { host, hostname, origin, pathname, port, search } = new URL(url);
712
712
  const e = encodeURIComponent;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/core",
3
- "version": "6.2.18",
3
+ "version": "6.2.21",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "type": "module",
@@ -44,8 +44,8 @@
44
44
  "prettier": "^3.3.3"
45
45
  },
46
46
  "peerDependencies": {
47
- "@zuplo/graphql": "6.2.18",
48
- "@zuplo/otel": "6.2.18",
49
- "@zuplo/runtime": "6.2.18"
47
+ "@zuplo/graphql": "6.2.21",
48
+ "@zuplo/otel": "6.2.21",
49
+ "@zuplo/runtime": "6.2.21"
50
50
  }
51
51
  }