@zuplo/core 7.4.7 → 7.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -572,7 +572,7 @@ globstar while`,s,pe,o,ae,rt),this.matchOne(s.slice(pe),o.slice(ae),f))return th
572
572
  `),stderr:E.join(`
573
573
  `),exitCode:A},"Tar process logs")}}t(LXt,"tarFolder");async function RXt({tarFilePath:s,outputDir:o,logger:f}){let d=[],y=[],E;try{await new Promise((A,R)=>{let q=tit("sh",["-c",`tar -xvf ${s} -C ${o};`]);q.stdout.on("data",K=>{let ve=K.toString().trim();ve.length>0&&d.push(ve.trim())}),q.stderr.on("data",K=>{let ve=K.toString().trim();ve.length>0&&y.push(ve.trim())}),q.on("close",K=>{E=K,K===0?A():R(new Error(`tar process exited with code ${K}`))}),q.on("error",K=>{R(K)})})}catch(A){throw new Error("Failed to untar file",{cause:A})}finally{f.info({stdout:d.join(`
574
574
  `),stderr:y.join(`
575
- `),exitCode:E},"Untar process logs")}}t(RXt,"untarFile");async function MXt(s){if(await XPe(s))return await qN.rm(s,{recursive:!0})}t(MXt,"deleteFolder");var nu=ZPe;var Yct=wp(Est(),1);import{AssertionError as uer}from"node:assert";function UP(s,o){if(s===!1)throw new uer({message:o})}t(UP,"assert");var qo;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.Raw="Raw"})(qo||(qo={}));function H9(s){return s.type===qo.Object}t(H9,"isAstObject");function zP(s){return s.type===qo.Property}t(zP,"isAstProperty");function IAe(s){return s.type===qo.Array}t(IAe,"isAstArray");function fO(s){return s.type===qo.Literal}t(fO,"isAstLiteral");function GN(s){if(s===void 0)throw new Error("Node is undefined");if(!H9(s))throw new Error("Node is not object")}t(GN,"assertAstObject");import{findNodeAtLocation as fer,getNodeValue as _er,printParseErrorCode as per,visit as der}from"jsonc-parser";var mer={DEFAULT:{allowTrailingComma:!1}};function UV(s,o=[],f=mer.DEFAULT){let d={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(q){d.type==="property"&&(d.length=q-d.offset,d=d.parent)}t(y,"ensurePropertyComplete");function E(q){return d.children?.push(q),q}t(E,"onValue"),der(s,{onObjectBegin:t((q,K,ve,pe)=>{d=E({type:"object",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onObjectBegin"),onObjectProperty:t((q,K,ve,pe,ae)=>{d=E({type:"property",offset:K,length:-1,line:pe+1,column:ae+1,parent:d,children:[]}),d.children?.push({type:"string",value:q,offset:K,length:ve,line:pe,column:ae,parent:d})},"onObjectProperty"),onObjectEnd:t((q,K)=>{y(q+K),d.length=q+K-d.offset,d=d.parent,y(q+K)},"onObjectEnd"),onArrayBegin:t((q,K,ve,pe)=>{d=E({type:"array",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onArrayBegin"),onArrayEnd:t((q,K)=>{d.length=q+K-d.offset,d=d.parent,y(q+K)},"onArrayEnd"),onLiteralValue:t((q,K,ve,pe,ae)=>{E({type:her(q),offset:K,length:ve,line:pe+1,column:ae+1,parent:d,value:q}),y(K+ve)},"onLiteralValue"),onSeparator:t((q,K)=>{d.type==="property"&&(q===":"?d.colonOffset=K:q===","&&y(K))},"onSeparator"),onError:t((q,K,ve,pe,ae)=>{o.push({error:q,offset:K,length:ve,line:pe+1,column:ae+1})},"onError")},f);let R=d.children?.[0];return R&&delete R.parent,R}t(UV,"parse");function her(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(her,"getNodeType");function G9(s,o){return fer(s,o)}t(G9,"findNodeAtLocation");function zV(s){return _er(s)}t(zV,"getNodeValue");function Cst(s){return per(s)}t(Cst,"printParseErrorCode");var JV=class{static{t(this,"AstAdapter")}parse(o){let d=UV(o,[]);if(d)return this.parseNode(d,void 0);throw new Error("Failed to parse JSON")}convert(o){return this.parseNode(o,void 0)}parseNode(o,f){switch(o.type){case"object":return this.createObject(o,f);case"array":return this.createArray(o,f);case"property":return this.createProperty(o,f);case"string":return this.createLiteral(o,f);case"number":return this.createLiteral(o,f);case"boolean":return this.createLiteral(o,f);case"null":return this.createLiteral(o,f)}}createLiteral(o,f){return{type:qo.Literal,location:{line:o.line,column:o.column},parent:f,value:o.type==="null"?null:o.value}}createObject(o,f){let d={type:qo.Object,children:[],parent:f,location:{line:o.line,column:o.column}};return o.children?.forEach(y=>{d.children.push(this.parseNode(y,d))}),d}createProperty(o,f){UP(o.children?.length===2,"Invalid property node");let d={type:qo.Property,location:{line:o.line,column:o.column},parent:f,name:null,value:null};return d.name={value:o.children[0].value,location:{line:o.line,column:o.column},type:qo.Identifier,parent:d},d.value=this.parseNode(o.children[1],d),d}createArray(o,f){let d={type:qo.Array,location:{line:o.line,column:o.column},parent:f,children:[]};return o.children?.forEach(y=>d.children.push(this.parseNode(y,d))),d}};var PS={createLiteral:t((s,o)=>({type:qo.Literal,parent:o,value:s}),"createLiteral"),createTemplateString:t((s,o)=>({type:qo.TemplateString,parent:o,value:s}),"createTemplateString"),createIdentifier:t((s,o)=>({type:qo.Identifier,value:s,parent:o}),"createIdentifier"),createProperty:t((s,o,f)=>{let d={type:qo.Property,parent:f,name:null,value:o};return d.name={value:s,type:qo.Identifier,parent:d},d.value.parent=d,d},"createProperty"),createArrayOfLiterals:t((s,o)=>{let f={type:qo.Array,parent:o,children:[]};for(let d of s)f.children.push(PS.createLiteral(d,f));return f},"createArrayOfLiterals")};var ger=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,$V=class{static{t(this,"SourceGenerator")}generate(o){let f=[];return this.generateSource(f,o),f.join("")}generateSource(o,f){switch(f.type){case qo.Array:return this.generateArray(o,f);case qo.Object:return this.generateObject(o,f);case qo.Property:return this.generateProperty(o,f);case qo.Literal:return this.generateLiteral(o,f);case qo.FunctionCall:return this.generateFunctionCall(o,f);case qo.Identifier:return this.generateIdentifier(o,f);case qo.Raw:return this.generateRaw(o,f);case qo.TemplateString:return this.generateTemplateString(o,f)}}generateArray(o,f){o.push("["),f.children.map(d=>{this.generateSource(o,d),o.push(",")}),o.push("]")}generateObject(o,f){o.push("{"),f.children.forEach(d=>{this.generateSource(o,d),o.push(",")}),o.push("}")}generateProperty(o,f){this.generateIdentifier(o,f.name),o.push(":"),this.generateSource(o,f.value)}generateFunctionCall(o,f){o.push(f.name.value),o.push("("),f.children.forEach((d,y,E)=>{this.generateSource(o,d),y<E.length&&o.push(",")}),o.push(")")}generateRaw(o,f){o.push(f.value)}generateTemplateString(o,f){o.push("`"),o.push(f.value.replaceAll("`","\\`")),o.push("`")}generateLiteral(o,f){if(f.value===null)return o.push("null");switch(typeof f.value){case"number":case"boolean":return o.push(`${f.value}`);case"string":{let d=f.value,y=JSON.stringify(d);return o.push(`${y}`)}}}generateIdentifier(o,f){let d=ger.test(f.value)?f.value:`'${f.value}'`;o.push(d)}};import yer from"node:fs/promises";import{parse as ver}from"@swc/core";var kst=t(async s=>{let o=new Set;try{let f=await yer.readFile(s,"utf-8");(await ver(f,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?o.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?o.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&o.add(y.declaration.declarations[0].id.value)})}catch{return null}return o},"getJSFileExports");var wst=["ai-gateway-auth-v2","ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2","ai-gateway-dlp","ai-gateway-fallback-model-v2","ai-gateway-metering-v2","ai-gateway-model-filtering-v2","ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2","akamai-ai-firewall","akamai-ai-firewall-v2","akamai-firewall-for-ai","comet-opik-tracing-v2","galileo-tracing-v2","prompt-injection","semantic-cache"],Dst={"ai-gateway-auth-v2-inbound":"ai-gateway-auth-v2","ai-gateway-configuration-executor-v2-inbound":"ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2-inbound":"ai-gateway-configuration-loader-v2","ai-gateway-dlp-inbound":"ai-gateway-dlp","ai-gateway-fallback-model-v2-inbound":"ai-gateway-fallback-model-v2","ai-gateway-metering-v2-inbound":"ai-gateway-metering-v2","ai-gateway-model-filtering-v2-inbound":"ai-gateway-model-filtering-v2","ai-gateway-semantic-cache-inbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-outbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2-inbound":"ai-gateway-semantic-cache-v2","akamai-ai-firewall-v2-inbound":"akamai-ai-firewall-v2","akamai-firewall-for-ai-inbound":"akamai-firewall-for-ai","akamai-firewall-for-ai-outbound":"akamai-firewall-for-ai","comet-opik-tracing-v2-inbound":"comet-opik-tracing-v2","galileo-tracing-v2-inbound":"galileo-tracing-v2","prompt-injection-outbound":"prompt-injection","semantic-cache-inbound":"semantic-cache"};var Pst={$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 OAe={$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 Ast={$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 FAe={$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"],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:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},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 LAe={$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:{},mcp:{oneOf:[{type:"object",additionalProperties:!1,properties:{type:{const:"tool"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"},includeOutputSchema:{type:"boolean"},includeStructuredContent:{type:"boolean"},annotations:{type:"object",additionalProperties:!1,properties:{title:{type:"string"},readOnlyHint:{type:"boolean"},destructiveHint:{type:"boolean"},idempotentHint:{type:"boolean"},openWorldHint:{type:"boolean"}}},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"prompt"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"resource"},name:{type:"string"},description:{type:"string"},uri:{type:"string"},mimeType:{type:"string"},enabled:{type:"boolean"},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"graphql"},enabled:{type:"boolean"},introspectionTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}},executeTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}}},required:["type"]}]},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 Bct=wp(Hce(),1),Uct=wp(Xce(),1);var Zce=class s{static{t(this,"JsonValidator")}static#e=new s;static get instance(){return s.#e}ajv;constructor(){this.ajv=new Bct.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Uct.default)(this.ajv,{mode:"fast"})}addSchema(o,f){this.ajv.addSchema(o,f)}compile(o){let f=this.ajv.compile(o);return t(y=>({isValid:f(y),errors:this.toSimpleErrors(f.errors,y),warnings:[]}),"validator")}toSimpleErrors(o,f){let d=[];return o?.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 E={details:{}},A=y.instancePath.split("/");if(A.length>2){let q=A[1],K=A[2]?parseInt(A[2],10):0,ve=A[3],pe=Number.isNaN(K)?void 0:f[q][K][ve];E={details:{property:q,index:K,field:ve,fieldValue:pe}}}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 q=y.instancePath.split("/"),K=q[q.length-1];y.message=`Value of property '${K}' must be '${y.params.type}'`}let R=Object.assign(y,E);d.push(R)}),d}};var iI=Zce.instance;iI.addSchema(FAe,"route-configuration.schema.json");iI.addSchema(Ast,"policy-configuration.schema.json");iI.addSchema(OAe,"policies.schema.json");iI.addSchema(LAe,"open-api-route-configuration.schema.json");iI.addSchema(Pst,"fragments.schema.json");var HAr=iI.compile(FAe),zct=iI.compile(LAe),XNe=iI.compile(OAe);var Qce=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(o){return this.results=XNe(o),this.results}};var ele=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(o){return this.results=zct(o),this.results}};import Wor from"node:path";var ZNe=/\$import\((.*)\)/,bH=/\$env\((.*?)\)/g;var jk=class extends Error{static{t(this,"CodeGenError")}location;constructor(o,f,d,y){super(o),this.location={file:f,namespace:"",line:d?d.line:0,column:d?d.column:0,length:0,lineText:y??"",suggestion:""}}},$or=t(s=>{let o=[],f=s;for(;f.parent;)o.push(f),f=f.parent;return o.reverse()},"invertTree"),qP=t((s,o)=>{if(!s)return!1;let f=$or(s);return o.split("/").every((E,A)=>{let R=f[A];return R?E==="*"||zP(R)&&R.name.value===E?!0:E==="{}"?R.type===qo.Object:E==="[]"?R.type===qo.Array:!1:!1})},"testPosition");var tle=class{static{t(this,"AstTransformer")}errors=[];transform(o){return this.visitor(o),o}visitor(o){this.visit(o),H9(o)?o.children.forEach(f=>{this.visitor(f)}):IAe(o)?o.children.forEach(f=>{this.visitor(f)}):zP(o)&&this.visitor(o.value)}},Jct=t(s=>{let o=new RegExp(bH).exec(s);if(o?.length===2&&o[0]===s)return{type:"raw",value:`environment["${o[1]}"]`};{let f=s.replaceAll(new RegExp(bH),(d,y)=>`\${environment["${y}"] ? environment["${y}"] : ""}`);if(f!==s)return{type:"template",value:f}}return null},"replaceEnvInString"),$ct=t((s,o,f)=>d=>{if(fO(d)&&typeof d.value=="string"&&d.parent&&IAe(d.parent)){if(!s.some(A=>qP(d.parent,A))){bH.test(d.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value));return}let E=Jct(d.value);if(E){let A=d.parent,R=A.children.indexOf(d);if(R!==-1)if(E.type==="raw"){let q={type:qo.Raw,parent:A,value:E.value};A.children[R]=q}else A.children[R]=PS.createTemplateString(E.value,d)}return}if(!zP(d)||!fO(d.value)||typeof d.value.value!="string")return;if(!s.some(E=>qP(d,E))){bH.test(d.value.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value.value));return}let y=Jct(d.value.value);if(y)if(y.type==="raw"){let E={type:qo.Raw,parent:null,value:y.value};d.value=E}else d.value=PS.createTemplateString(y.value,d)},"getEnvStatementTransformer");var SH="config/routes.json",qor=["handler/{}/options/*","handler/{}/options/*/[]","policies/[]/{}/handler/{}/options/*","policies/[]/{}/handler/{}/options/*/[]","corsPolicies/[]/{}/*","corsPolicies/[]/{}/*/[]"],Vor=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","handler/{}/options/{}/onOpen/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Wct=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],Hor="handler/{}/options/{}/rewritePattern",Gor="handler/{}/options/{}/baseUrl",rle=class extends tle{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(o){this.addedImports.has(o)||this.addedImports.set(o,`__import${this.importCount++}`);let f=this.addedImports.get(o);if(!f)throw new Error("Import name is undefined. This should not happen.");return f}getImports(){let o=[];return this.addedImports.forEach((f,d)=>{o.push({name:f,path:d})}),o}visit(o){this.rewriteHandlerFunction(o),this.rewriteForwardFunction(o),this.replaceImportStatements(o),this.replaceEnvStatements(o)}rewriteHandlerFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,Hor)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",SH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:qct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}rewriteForwardFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,Gor)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",SH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:qct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}replaceImportStatements(o){if(!zP(o)||!fO(o.value))return;let f=o.value.value;if(typeof f!="string")return;if(!Vor.some(R=>qP(o,R))&&!Wct.some(R=>qP(o,R))){if(ZNe.test(f)){if(o.name.value==="$ref")return;this.errors.push(new jk("An $import() statement is not expected at this location.",SH,o.location,f))}return}let d=ZNe.exec(f);if(Wct.some(R=>qP(o,R))&&!d)return;if(!d){this.errors.push(new jk("Invalid $import() statement",SH,o.location,f));return}let y=d[1];y=y.replace(/\\/g,"/"),y.startsWith(".")&&(y=Wor.posix.join("..",y));let E=this.getImportName(y),A={type:qo.Identifier,parent:o.parent,value:E};o.value=A}replaceEnvStatements=$ct(qor,this.errors,SH)};function qct(s){return`(request, context) => {
575
+ `),exitCode:E},"Untar process logs")}}t(RXt,"untarFile");async function MXt(s){if(await XPe(s))return await qN.rm(s,{recursive:!0})}t(MXt,"deleteFolder");var nu=ZPe;var Yct=wp(Est(),1);import{AssertionError as uer}from"node:assert";function UP(s,o){if(s===!1)throw new uer({message:o})}t(UP,"assert");var qo;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.Raw="Raw"})(qo||(qo={}));function H9(s){return s.type===qo.Object}t(H9,"isAstObject");function zP(s){return s.type===qo.Property}t(zP,"isAstProperty");function IAe(s){return s.type===qo.Array}t(IAe,"isAstArray");function fO(s){return s.type===qo.Literal}t(fO,"isAstLiteral");function GN(s){if(s===void 0)throw new Error("Node is undefined");if(!H9(s))throw new Error("Node is not object")}t(GN,"assertAstObject");import{findNodeAtLocation as fer,getNodeValue as _er,printParseErrorCode as per,visit as der}from"jsonc-parser";var mer={DEFAULT:{allowTrailingComma:!1}};function UV(s,o=[],f=mer.DEFAULT){let d={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(q){d.type==="property"&&(d.length=q-d.offset,d=d.parent)}t(y,"ensurePropertyComplete");function E(q){return d.children?.push(q),q}t(E,"onValue"),der(s,{onObjectBegin:t((q,K,ve,pe)=>{d=E({type:"object",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onObjectBegin"),onObjectProperty:t((q,K,ve,pe,ae)=>{d=E({type:"property",offset:K,length:-1,line:pe+1,column:ae+1,parent:d,children:[]}),d.children?.push({type:"string",value:q,offset:K,length:ve,line:pe,column:ae,parent:d})},"onObjectProperty"),onObjectEnd:t((q,K)=>{y(q+K),d.length=q+K-d.offset,d=d.parent,y(q+K)},"onObjectEnd"),onArrayBegin:t((q,K,ve,pe)=>{d=E({type:"array",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onArrayBegin"),onArrayEnd:t((q,K)=>{d.length=q+K-d.offset,d=d.parent,y(q+K)},"onArrayEnd"),onLiteralValue:t((q,K,ve,pe,ae)=>{E({type:her(q),offset:K,length:ve,line:pe+1,column:ae+1,parent:d,value:q}),y(K+ve)},"onLiteralValue"),onSeparator:t((q,K)=>{d.type==="property"&&(q===":"?d.colonOffset=K:q===","&&y(K))},"onSeparator"),onError:t((q,K,ve,pe,ae)=>{o.push({error:q,offset:K,length:ve,line:pe+1,column:ae+1})},"onError")},f);let R=d.children?.[0];return R&&delete R.parent,R}t(UV,"parse");function her(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(her,"getNodeType");function G9(s,o){return fer(s,o)}t(G9,"findNodeAtLocation");function zV(s){return _er(s)}t(zV,"getNodeValue");function Cst(s){return per(s)}t(Cst,"printParseErrorCode");var JV=class{static{t(this,"AstAdapter")}parse(o){let d=UV(o,[]);if(d)return this.parseNode(d,void 0);throw new Error("Failed to parse JSON")}convert(o){return this.parseNode(o,void 0)}parseNode(o,f){switch(o.type){case"object":return this.createObject(o,f);case"array":return this.createArray(o,f);case"property":return this.createProperty(o,f);case"string":return this.createLiteral(o,f);case"number":return this.createLiteral(o,f);case"boolean":return this.createLiteral(o,f);case"null":return this.createLiteral(o,f)}}createLiteral(o,f){return{type:qo.Literal,location:{line:o.line,column:o.column},parent:f,value:o.type==="null"?null:o.value}}createObject(o,f){let d={type:qo.Object,children:[],parent:f,location:{line:o.line,column:o.column}};return o.children?.forEach(y=>{d.children.push(this.parseNode(y,d))}),d}createProperty(o,f){UP(o.children?.length===2,"Invalid property node");let d={type:qo.Property,location:{line:o.line,column:o.column},parent:f,name:null,value:null};return d.name={value:o.children[0].value,location:{line:o.line,column:o.column},type:qo.Identifier,parent:d},d.value=this.parseNode(o.children[1],d),d}createArray(o,f){let d={type:qo.Array,location:{line:o.line,column:o.column},parent:f,children:[]};return o.children?.forEach(y=>d.children.push(this.parseNode(y,d))),d}};var PS={createLiteral:t((s,o)=>({type:qo.Literal,parent:o,value:s}),"createLiteral"),createTemplateString:t((s,o)=>({type:qo.TemplateString,parent:o,value:s}),"createTemplateString"),createIdentifier:t((s,o)=>({type:qo.Identifier,value:s,parent:o}),"createIdentifier"),createProperty:t((s,o,f)=>{let d={type:qo.Property,parent:f,name:null,value:o};return d.name={value:s,type:qo.Identifier,parent:d},d.value.parent=d,d},"createProperty"),createArrayOfLiterals:t((s,o)=>{let f={type:qo.Array,parent:o,children:[]};for(let d of s)f.children.push(PS.createLiteral(d,f));return f},"createArrayOfLiterals")};var ger=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,$V=class{static{t(this,"SourceGenerator")}generate(o){let f=[];return this.generateSource(f,o),f.join("")}generateSource(o,f){switch(f.type){case qo.Array:return this.generateArray(o,f);case qo.Object:return this.generateObject(o,f);case qo.Property:return this.generateProperty(o,f);case qo.Literal:return this.generateLiteral(o,f);case qo.FunctionCall:return this.generateFunctionCall(o,f);case qo.Identifier:return this.generateIdentifier(o,f);case qo.Raw:return this.generateRaw(o,f);case qo.TemplateString:return this.generateTemplateString(o,f)}}generateArray(o,f){o.push("["),f.children.map(d=>{this.generateSource(o,d),o.push(",")}),o.push("]")}generateObject(o,f){o.push("{"),f.children.forEach(d=>{this.generateSource(o,d),o.push(",")}),o.push("}")}generateProperty(o,f){this.generateIdentifier(o,f.name),o.push(":"),this.generateSource(o,f.value)}generateFunctionCall(o,f){o.push(f.name.value),o.push("("),f.children.forEach((d,y,E)=>{this.generateSource(o,d),y<E.length&&o.push(",")}),o.push(")")}generateRaw(o,f){o.push(f.value)}generateTemplateString(o,f){o.push("`"),o.push(f.value.replaceAll("`","\\`")),o.push("`")}generateLiteral(o,f){if(f.value===null)return o.push("null");switch(typeof f.value){case"number":case"boolean":return o.push(`${f.value}`);case"string":{let d=f.value,y=JSON.stringify(d);return o.push(`${y}`)}}}generateIdentifier(o,f){let d=ger.test(f.value)?f.value:`'${f.value}'`;o.push(d)}};import yer from"node:fs/promises";import{parse as ver}from"@swc/core";var kst=t(async s=>{let o=new Set;try{let f=await yer.readFile(s,"utf-8");(await ver(f,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?o.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?o.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&o.add(y.declaration.declarations[0].id.value)})}catch{return null}return o},"getJSFileExports");var wst=["ai-gateway-auth-v2","ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2","ai-gateway-dlp","ai-gateway-fallback-model-v2","ai-gateway-metering-v2","ai-gateway-model-filtering-v2","ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2","ai-gateway-smart-router","akamai-ai-firewall","akamai-ai-firewall-v2","akamai-firewall-for-ai","comet-opik-tracing-v2","galileo-tracing-v2","prompt-injection","semantic-cache"],Dst={"ai-gateway-auth-v2-inbound":"ai-gateway-auth-v2","ai-gateway-configuration-executor-v2-inbound":"ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2-inbound":"ai-gateway-configuration-loader-v2","ai-gateway-dlp-inbound":"ai-gateway-dlp","ai-gateway-fallback-model-v2-inbound":"ai-gateway-fallback-model-v2","ai-gateway-metering-v2-inbound":"ai-gateway-metering-v2","ai-gateway-model-filtering-v2-inbound":"ai-gateway-model-filtering-v2","ai-gateway-semantic-cache-inbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-outbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2-inbound":"ai-gateway-semantic-cache-v2","ai-gateway-smart-router-inbound":"ai-gateway-smart-router","akamai-ai-firewall-v2-inbound":"akamai-ai-firewall-v2","akamai-firewall-for-ai-inbound":"akamai-firewall-for-ai","akamai-firewall-for-ai-outbound":"akamai-firewall-for-ai","comet-opik-tracing-v2-inbound":"comet-opik-tracing-v2","galileo-tracing-v2-inbound":"galileo-tracing-v2","prompt-injection-outbound":"prompt-injection","semantic-cache-inbound":"semantic-cache"};var Pst={$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 OAe={$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 Ast={$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 FAe={$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"],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:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},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 LAe={$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:{},mcp:{oneOf:[{type:"object",additionalProperties:!1,properties:{type:{const:"tool"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"},includeOutputSchema:{type:"boolean"},includeStructuredContent:{type:"boolean"},annotations:{type:"object",additionalProperties:!1,properties:{title:{type:"string"},readOnlyHint:{type:"boolean"},destructiveHint:{type:"boolean"},idempotentHint:{type:"boolean"},openWorldHint:{type:"boolean"}}},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"prompt"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"resource"},name:{type:"string"},description:{type:"string"},uri:{type:"string"},mimeType:{type:"string"},enabled:{type:"boolean"},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"graphql"},enabled:{type:"boolean"},introspectionTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}},executeTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}}},required:["type"]}]},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 Bct=wp(Hce(),1),Uct=wp(Xce(),1);var Zce=class s{static{t(this,"JsonValidator")}static#e=new s;static get instance(){return s.#e}ajv;constructor(){this.ajv=new Bct.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Uct.default)(this.ajv,{mode:"fast"})}addSchema(o,f){this.ajv.addSchema(o,f)}compile(o){let f=this.ajv.compile(o);return t(y=>({isValid:f(y),errors:this.toSimpleErrors(f.errors,y),warnings:[]}),"validator")}toSimpleErrors(o,f){let d=[];return o?.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 E={details:{}},A=y.instancePath.split("/");if(A.length>2){let q=A[1],K=A[2]?parseInt(A[2],10):0,ve=A[3],pe=Number.isNaN(K)?void 0:f[q][K][ve];E={details:{property:q,index:K,field:ve,fieldValue:pe}}}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 q=y.instancePath.split("/"),K=q[q.length-1];y.message=`Value of property '${K}' must be '${y.params.type}'`}let R=Object.assign(y,E);d.push(R)}),d}};var iI=Zce.instance;iI.addSchema(FAe,"route-configuration.schema.json");iI.addSchema(Ast,"policy-configuration.schema.json");iI.addSchema(OAe,"policies.schema.json");iI.addSchema(LAe,"open-api-route-configuration.schema.json");iI.addSchema(Pst,"fragments.schema.json");var HAr=iI.compile(FAe),zct=iI.compile(LAe),XNe=iI.compile(OAe);var Qce=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(o){return this.results=XNe(o),this.results}};var ele=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(o){return this.results=zct(o),this.results}};import Wor from"node:path";var ZNe=/\$import\((.*)\)/,bH=/\$env\((.*?)\)/g;var jk=class extends Error{static{t(this,"CodeGenError")}location;constructor(o,f,d,y){super(o),this.location={file:f,namespace:"",line:d?d.line:0,column:d?d.column:0,length:0,lineText:y??"",suggestion:""}}},$or=t(s=>{let o=[],f=s;for(;f.parent;)o.push(f),f=f.parent;return o.reverse()},"invertTree"),qP=t((s,o)=>{if(!s)return!1;let f=$or(s);return o.split("/").every((E,A)=>{let R=f[A];return R?E==="*"||zP(R)&&R.name.value===E?!0:E==="{}"?R.type===qo.Object:E==="[]"?R.type===qo.Array:!1:!1})},"testPosition");var tle=class{static{t(this,"AstTransformer")}errors=[];transform(o){return this.visitor(o),o}visitor(o){this.visit(o),H9(o)?o.children.forEach(f=>{this.visitor(f)}):IAe(o)?o.children.forEach(f=>{this.visitor(f)}):zP(o)&&this.visitor(o.value)}},Jct=t(s=>{let o=new RegExp(bH).exec(s);if(o?.length===2&&o[0]===s)return{type:"raw",value:`environment["${o[1]}"]`};{let f=s.replaceAll(new RegExp(bH),(d,y)=>`\${environment["${y}"] ? environment["${y}"] : ""}`);if(f!==s)return{type:"template",value:f}}return null},"replaceEnvInString"),$ct=t((s,o,f)=>d=>{if(fO(d)&&typeof d.value=="string"&&d.parent&&IAe(d.parent)){if(!s.some(A=>qP(d.parent,A))){bH.test(d.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value));return}let E=Jct(d.value);if(E){let A=d.parent,R=A.children.indexOf(d);if(R!==-1)if(E.type==="raw"){let q={type:qo.Raw,parent:A,value:E.value};A.children[R]=q}else A.children[R]=PS.createTemplateString(E.value,d)}return}if(!zP(d)||!fO(d.value)||typeof d.value.value!="string")return;if(!s.some(E=>qP(d,E))){bH.test(d.value.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value.value));return}let y=Jct(d.value.value);if(y)if(y.type==="raw"){let E={type:qo.Raw,parent:null,value:y.value};d.value=E}else d.value=PS.createTemplateString(y.value,d)},"getEnvStatementTransformer");var SH="config/routes.json",qor=["handler/{}/options/*","handler/{}/options/*/[]","policies/[]/{}/handler/{}/options/*","policies/[]/{}/handler/{}/options/*/[]","corsPolicies/[]/{}/*","corsPolicies/[]/{}/*/[]"],Vor=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","handler/{}/options/{}/onOpen/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Wct=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],Hor="handler/{}/options/{}/rewritePattern",Gor="handler/{}/options/{}/baseUrl",rle=class extends tle{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(o){this.addedImports.has(o)||this.addedImports.set(o,`__import${this.importCount++}`);let f=this.addedImports.get(o);if(!f)throw new Error("Import name is undefined. This should not happen.");return f}getImports(){let o=[];return this.addedImports.forEach((f,d)=>{o.push({name:f,path:d})}),o}visit(o){this.rewriteHandlerFunction(o),this.rewriteForwardFunction(o),this.replaceImportStatements(o),this.replaceEnvStatements(o)}rewriteHandlerFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,Hor)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",SH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:qct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}rewriteForwardFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,Gor)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",SH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:qct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}replaceImportStatements(o){if(!zP(o)||!fO(o.value))return;let f=o.value.value;if(typeof f!="string")return;if(!Vor.some(R=>qP(o,R))&&!Wct.some(R=>qP(o,R))){if(ZNe.test(f)){if(o.name.value==="$ref")return;this.errors.push(new jk("An $import() statement is not expected at this location.",SH,o.location,f))}return}let d=ZNe.exec(f);if(Wct.some(R=>qP(o,R))&&!d)return;if(!d){this.errors.push(new jk("Invalid $import() statement",SH,o.location,f));return}let y=d[1];y=y.replace(/\\/g,"/"),y.startsWith(".")&&(y=Wor.posix.join("..",y));let E=this.getImportName(y),A={type:qo.Identifier,parent:o.parent,value:E};o.value=A}replaceEnvStatements=$ct(qor,this.errors,SH)};function qct(s){return`(request, context) => {
576
576
  const { params, url, query, method, headers } = request;
577
577
  const { host, hostname, origin, pathname, port, search } = new URL(url);
578
578
  const e = encodeURIComponent;
@@ -596,7 +596,7 @@ globstar while`,s,pe,o,ae,rt),this.matchOne(s.slice(pe),o.slice(ae),f))return th
596
596
  };
597
597
  }
598
598
  export default routes;
599
- `),Xor=["2023-03-14","2024-01-15","2024-03-14","2024-09-02"];function Kct(s){return!s||Xor.includes(s)}t(Kct,"isLegacyPathBehavior");function Zor(s){let o=globalThis.URLPattern;if(!o)throw new Error("Native URLPattern is unavailable. Run the build with Node.js 24 or later.");return new o({pathname:s})}t(Zor,"createNativeURLPattern");function tIe(s){let o="",f=0,d=!1;for(let y=0;y<s.length;y++){let E=s[y];if(E==="\\"){o+=E,y+1<s.length&&(o+=s[++y]);continue}!d&&E==="("?f++:!d&&E===")"&&f>0?f--:f>0&&E==="["?d=!0:d&&E==="]"&&(d=!1),E==="/"&&f>0&&(o+="\\"),o+=E}return o}t(tIe,"normalizeUrlPatternForNative");async function rIe(s){try{let{content:o,warnings:f}=await Qor(s);return{content:o,errors:[],warnings:f}}catch(o){if(o instanceof Cy)return o.toBuildResult();throw o}}t(rIe,"compileRoutes");async function Qor({sourceDirectory:s,policiesContent:o,oasContent:f,compatibilityDate:d,allowDuplicateRoutes:y,isAiEnabled:E}){let A=[],R=[],q=new rle,K=new $V,{policiesNode:ve,policiesData:pe}=ncr(o);E===!1&&rcr(pe);let{generatedPolicies:ae,policyNames:rt}=icr(q,K,ve,pe),{generatedCorsPolicies:ze,corsPoliciesNames:je}=scr(q,K,ve,pe),Bt=acr(s,f),Ut=[],Or=new Map,Jn=new Map;for(let br of Bt){let{node:js,oas:Ni,oasProjectRelativePath:jo}=br,ji=G9(js,["paths"]);if(!ji)continue;let Op=sle.basename(Ni.fileName,".oas.json"),ed,Ln=t(()=>(ed??=mcr(js),ed),"getDefaultRewriteServer");for(let Fh of ji.children??[])if(Fh.children){let cl=_cr(Fh),wr=cl[Vct]?.pathMode;if(wr){if(wr!==nle&&wr!==eIe)throw new Cy({text:`Unknown path mode ${wr}`,location:{line:0,column:0,file:jo}})}else wr=nle;for(let[UE,gl]of Object.entries(cl)){if(!ile(UE))continue;let M_=UE,va=M_.split(/,/).map(Lh=>Lh.trim().toUpperCase()),PT=gl,ob=PT[QNe];if(ob){let Oi=new ele().validate(ob);if(Oi.isValid){let Fp=Hct(Fh);if(!Or.has(Fp)&&(Or.set(Fp,new Set),Kct(d)))try{Zor(tIe(Fp))}catch{R.push({text:`Path '${Fp}' contains invalid characters. The value must be a valid URLPattern.`,location:{line:Fh.line,column:Fh.column,file:jo}})}if(!y){let d7=Or.get(Fp);va.forEach(Tt=>{d7.has(Tt)?R.push({text:`Cannot have duplicate routes declared. Route '${Tt.toUpperCase()} ${Fp}' declared more than once.`,location:{line:Fh.line,column:Fh.column,file:jo}}):d7.add(Tt)})}let OS=pcr(Fh,[Fp,M_,QNe]),Ug=dcr(OS),iA=await ycr(OS,Ug,Ni,Jn);if(!iA.valid)throw new Cy({text:iA.errorMsg??`Unknown error on handler for path '${Fp}'`,location:{line:iA.line??0,column:iA.column??0,file:jo}});let tw=bcr(OS,Ug,jo);if(!tw.valid)throw new Cy(tw.errors);tw.warnings&&A.push(...tw.warnings),Ut.push({path:Fp,pathPattern:Fp,pathMode:wr,httpMethods:va,rawOperation:M_,rawOpenAPI:PT,oasFileName:Op,oasProjectRelativePath:jo,config:OS})}else throw new Cy({text:JSON.stringify(Oi.errors),location:{line:0,column:0,file:jo}})}else{let Lh=Hct(Fh),Oi={corsPolicy:"none",handler:hcr(Lh,Ln())};Ut.push({path:Lh,pathPattern:Lh,pathMode:nle,rawOpenAPI:PT,oasFileName:Op,oasProjectRelativePath:jo,httpMethods:va,rawOperation:M_,config:UV(JSON.stringify(Oi))})}if(ob&&"policies"in ob){let Lh=ob.policies;Lh.inbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}),Lh.outbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})})}if(R.length>0)throw new Cy(R);let wj=["none","anything-goes"];if(ob&&"corsPolicy"in ob){let Lh=ob.corsPolicy;if(wj.includes(Lh))continue;je.includes(Lh)||R.push({text:`Cors policy '${Lh}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}}}if(R.length>0)throw new Cy(R)}let _n=[];for(let br of Ut){let js=new JV().convert(br.config);ocr(js,br),ccr(js,br,d),lcr(js,br),ucr(js,br),fcr(js,br);let Ni=q.transform(js),jo=q.errors;if(jo.length>0)throw new Cy({text:JSON.stringify(jo),location:{line:0,column:0,file:br.oasProjectRelativePath}});let Op=new $V().generate(Ni);_n.push(Op)}if(UP(Bt.length===f.length,"Tree length should match OAS file length"),UP(Ut.length===_n.length,`The number of validated nodes should match the number of generated fragments. There were ${Ut.length} validated nodes and ${_n.length} generated fragments.`),R.length>0)throw new Cy(R);let Wn={routes:_n,imports:q.getImports(),policies:ae,corsPolicies:ze};return{content:Kor(Wn),warnings:A}}t(Qor,"generateSourceCode");var ecr=0,tcr=1;function rcr(s){let o=new Set([...wst,...Object.keys(Dst)]),f=(s.policies??[]).filter(y=>y?.policyType&&o.has(y.policyType)).map(y=>`'${y.name}' (policyType: ${y.policyType})`);if(f.length===0)return;let d=f.join(", ");throw new Cy({text:`AI capabilities are disabled for this account, so AI-powered policies cannot be used. Remove ${d} from policies.json or ask an account admin to enable AI capabilities in account settings.`,location:{line:0,column:0,file:"/config/policies.json"}})}t(rcr,"assertNoAiPoliciesUsed");function ncr(s){let o=new Qce,f=JSON.parse(s.content),d=o.validate(f);if(!d.isValid)throw new Cy({text:JSON.stringify(d.errors),location:{line:0,column:0,file:"/config/policies.json"}});let y=new JV().parse(JSON.stringify(f));return{policiesData:f,policiesNode:y}}t(ncr,"getPolicyData");function icr(s,o,f,d){let y=[],E;GN(f);let A=f.children.find(R=>R.name.value==="policies");if(A){let R=s.transform(A);E=o.generate(R),y=d.policies.map(({name:q})=>q)}else E="policies: []";return{generatedPolicies:E,policyNames:y}}t(icr,"generatePolicies");function scr(s,o,f,d){let y,E;GN(f);let A=f.children.find(R=>R.name.value==="corsPolicies");if(A){let R=s.transform(A);E=o.generate(R),y=d.corsPolicies.map(({name:q})=>q)}else E="corsPolicies: []",y=[];return{generatedCorsPolicies:E,corsPoliciesNames:y}}t(scr,"generateCorsPolicies");function acr(s,o){let f=[];for(let d of o){let y=[],E=UV(d.content,y),A=`./${sle.posix.relative(s.replace(/\\/g,"/"),d.fileName.replace(/\\/g,"/"))}`;if(y.length>0)throw new Cy(y.map(R=>({text:Cst(R.error),location:{file:A,line:R.line,column:R.column}})));if(!E)throw new Cy({text:"Error parsing the OpenAPI file. Check the contents of the file.",location:{file:A,line:0,column:0}});f.push({node:E,oas:d,oasProjectRelativePath:A})}return f}t(acr,"getOasTrees");function ocr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"path",type:qo.Identifier,parent:f},f.value=PS.createLiteral(o.path,f),GN(s),s.children.unshift(f)}t(ocr,"embellishWithPath");function ccr(s,o,f){let d={type:qo.Property,parent:s,name:null,value:null};if(d.name={value:"pathPattern",type:qo.Identifier,parent:d},o.pathMode===eIe)d.value=PS.createLiteral(tIe(o.path),d);else{let y=/{(\S+?)}/gm,A=Kct(f)?o.path:o.path.replace(/([*+?()[\].|^$\\:])/g,"\\$1");A=A.replace(y,":$1"),A=tIe(A),o.path.endsWith("/")||(A=`${A}{/}?`),d.value=PS.createLiteral(A,d)}GN(s),s.children.unshift(d)}t(ccr,"embellishWithPathPattern");function lcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"methods",type:qo.Identifier,parent:f},f.value=PS.createArrayOfLiterals(o.httpMethods,f),GN(s),s.children.unshift(f)}t(lcr,"embellishWithMethods");function ucr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"raw",type:qo.Identifier,parent:s};let d=wV(o.oasFileName,o.path,o.rawOperation);f.value={type:qo.Raw,parent:f,value:`() => {return rawRouteData.${d};}`},GN(s),s.children.unshift(f)}t(ucr,"embellishWithRawOpenApi");function fcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"metadata",type:qo.Identifier,parent:s};let d={type:qo.Property,parent:f,name:null,value:null};d.name={value:"filepath",type:qo.Identifier,parent:d},d.value=PS.createLiteral(o.oasProjectRelativePath,d),f.value={type:qo.Object,parent:f,children:[d]},GN(s),s.children.unshift(f)}t(fcr,"embellishWithMetadata");function _cr(s){return UP(s.type==="property"),UP(Array.isArray(s.children)),zV(s.children[tcr])}t(_cr,"evaluatePathItem");function Hct(s){return UP(s.type==="property"),UP(Array.isArray(s.children)),zV(s.children[ecr])}t(Hct,"evaluatePath");function pcr(s,o){return G9(s.parent,o)}t(pcr,"extractZuploRouteNode");function dcr(s){return zV(s)}t(dcr,"evaluateZuploRouteNode");function mcr(s){let o;if(s.type==="object")for(let d of s.children??[]){let y=d.children?.[1];y&&d.children?.[0]?.value==="servers"&&(o=y)}let f=o?zV(o):void 0;return`${f&&f.length>0?f[0].url:"http://example.com"}`}t(mcr,"resolveDefaultRewriteServer");function hcr(s,o){let f=/{(\S+?)}/gm,y=s.replace(f,"${params.$1}");return{export:"urlRewriteHandler",module:"$import(@zuplo/runtime)",options:{rewritePattern:`${o}${y}`,forwardSearch:!0}}}t(hcr,"addDefaultUrlRewriteHandler");async function gcr(s,o){if(o.has(s))return o.get(s);let f=await kst(s);return o.set(s,f),f}t(gcr,"getJSFileExportsCached");async function ycr(s,o,f,d){let y=o.handler.module.replace(/^\$import\(/,"").replace(/\)$/,""),E=sle.join(sle.dirname(f.fileName),"..",`${y}.ts`),A=o.handler.export;if(y==="@zuplo/runtime"||y.startsWith("@zuplo/runtime/"))return{valid:!0};if(await nu.fileExists(E)){let R=await gcr(E,d);if(R===null)return{valid:!1,errorMsg:`Could not find any export due to a compile error in '${nu.getParentDirFilename(E)}'`};if(!R.has(A)){let q=`Could not find export "${A}" in '${nu.getParentDirFilename(E)}'`,K=0,ve=0;if(s.children)for(let pe of s.children)pe.children&&pe.children.forEach(ae=>{ae.value==="handler"&&(K=ae.line,ve=ae.column)});return{valid:!1,errorMsg:q,line:K,column:ve}}return{valid:!0}}else return{valid:!1,errorMsg:`Could not find module '${y}'`}}t(ycr,"checkModuleIsValid");var Gct=t((s,o)=>{let f=G9(s,["handler","options",o])??G9(s,["handler","options"])??G9(s,["handler"]);return f?{line:f.line,column:f.column-1}:{line:0,column:0}},"getHandlerOptionLocation"),vcr="$env(";function bcr(s,o,f){let d=o.handler.export;if(d!=="urlForwardHandler"&&d!=="urlRewriteHandler")return{valid:!0};let y="rewritePattern";d==="urlForwardHandler"&&(y="baseUrl");let E=o.handler.options?.[y];if(!E){let A=Gct(s,y);return{valid:!1,errors:[{text:`Invalid request handler configuration. handler.options.${y} is required but was not provided.`,location:{file:f,line:A.line,column:A.column}}]}}if(E.includes(vcr)){let A=Gct(s,y);return{valid:!0,warnings:[{text:`Invalid environment variable access syntax detected. Use \${env.VAR_NAME} instead of $env(VAR_NAME) for handler.options.${y}.`,location:{file:f,line:A.line,column:A.column}}]}}return{valid:!0}}t(bcr,"checkHandlerIsValid");var BH=wp(g4e(),1);import{readFile as cpr}from"node:fs/promises";var ST=wp(g4e(),1);var NO=class extends Error{static{t(this,"CustomResolveError")}},uI=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(o,f){this.sourceDirectory=o,this.logger=f}dereference(o,f){return BH.$RefParser.dereference(o,{resolve:{json:!0,file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:f?.onDereference}})}bundle(o){return BH.$RefParser.bundle(o,{resolve:{file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(o){return BH.$RefParser.parse(o,{resolve:{file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(o){return BH.$RefParser.resolve(o,{resolve:{file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function Ile(s,o){return{order:100,canRead(f){let d=_pr(f.url);if(!(d===void 0||d==="file"))return!1;let E;try{E=kft(f.url)}catch(A){throw new NO(`Malformed URI: ${f.url}`,{cause:A})}try{nu.safePath(s).resolve(E)}catch(A){return o?.warn(A),!1}return!0},async read(f){let d;try{d=kft(f.url)}catch(y){throw new NO(`Malformed URI: ${f.url}`,{cause:y})}try{return await cpr(d)}catch(y){throw new NO(`Error opening file "${d}"`,{cause:y})}}}}t(Ile,"customResolver");var lpr=/\//g,upr=/^(\w{2,}):\/\//i;function fpr(){return/^win/.test(globalThis.process?globalThis.process.platform:"")}t(fpr,"isWindowsPlatform");var y4e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function _pr(s){let o=upr.exec(s);if(o)return o[1].toLowerCase()}t(_pr,"getProtocol");function kft(s,o){let f=fpr();s=decodeURI(s);for(let y=0;y<y4e.length;y+=2)s=s.replace(y4e[y],y4e[y+1]);let d=s.substr(0,7).toLowerCase()==="file://";if(d&&(s=s[7]==="/"?s.substr(8):s.substr(7),f&&s[1]==="/"&&(s=`${s[0]}:${s.substr(1)}`),o?s=`file:///${s}`:(d=!1,s=f?s:`/${s}`)),!d){let y=s.split(f?"\\":"/"),E=[];for(let A of y)A===".."?E.length&&E[E.length-1]!==""&&E.pop():(A!==""||E.length===0)&&E.push(A);s=E.join(f?"\\":"/"),!f&&E[0]===""&&(s=`/${s.substring(1)}`)}return f&&!d&&(s=s.replace(lpr,"\\"),s.substr(1,2)===":\\"&&(s=s[0].toUpperCase()+s.substr(1))),s}t(kft,"toFileSystemPath");var wft="YOUR_KEY_HERE";async function Dft(s){let f=await new uI(s.sourceDirectory,s.logger).bundle(s.openApiDocPath),d=s.openApiDocPath.replace(s.sourceDirectory,"");return ppr({...s,relativeOpenApiPath:d},f)}t(Dft,"buildPublicOpenApiFile");async function ppr(s,o){gpr({relativeOpenApiPath:s.relativeOpenApiPath},o);let f=o;return f=mpr(f),dpr(f,s.urls?.api?.defaultUrl),f=hpr(f,s),Pft(f,"x-zuplo"),f}t(ppr,"buildRawOpenApiFile");function dpr(s,o){o?s.servers=[{url:o}]:s.servers=[]}t(dpr,"addServerHost");function mpr(s){if(!s.paths)return s;let{components:o}=s,f=o?{...o}:void 0,d=[];f&&f.parameters&&(d=Object.entries(f.parameters).reduce((E,[A,R])=>(I9 in R&&Gae(R[I9])&&(E.push(A),f.parameters&&delete f.parameters[A]),E),[]));let y=Object.entries(s.paths).reduce((E,[A,R])=>{if(!R)return E;let q={...R},K=["delete","get","head","patch","post","put","trace","options"];return K.forEach(ve=>{let pe=R[ve];if(!pe)return;if(Gae(pe[I9])){delete q[ve];return}let{parameters:ae}=pe;if(!ae)return;let rt=ae.filter(ze=>{if(I9 in ze&&Gae(ze[I9]))return!1;if("$ref"in ze){let je=ze.$ref.split("/").pop();return je?!d.includes(je):!0}return!0});q[ve]={...pe,parameters:rt}}),K.some(ve=>!!q[ve])&&(E[A]=q),E},{});return{...s,paths:y,components:f}}t(mpr,"removeHiddenRoutesAndParams");function hpr(s,{policiesConfig:o}){if(!s.paths)return s;let f=Object.entries(s.paths).reduce((d,[y,E])=>{if(!E)return d;let A={...E};return[A.delete,A.get,A.head,A.patch,A.post,A.put,A.trace,A.options].forEach(R=>{if(!R)return;let q=R["x-zuplo-route"]?.policies?.inbound?.reduce((pe,ae)=>{let rt=o.policies?.find(({name:Bt})=>Bt===ae);if(!rt)return pe;if(!(rt.handler.export==="CompositeInboundPolicy"))return pe.concat(ae);let je=rt.handler.options?.policies;return je?pe.concat(je):pe},[]),K=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="ApiAuthKeyInboundPolicy"||ae.handler.export==="ApiKeyInboundPolicy")&&!ae.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&K.push(ae)})}),K.length>0){let pe=K.length>0&&K[0].handler&&K[0].handler.options&&K[0].handler.options.authHeader?K[0].handler.options.authHeader:"Authorization",ae=K.length>0&&K[0].handler&&K[0].handler.options&&(K[0].handler.options.authScheme||K[0].handler.options.authScheme==="")?K[0].handler.options.authScheme:"Bearer",rt=ae!==""?`${ae} ${wft}`:wft,ze={name:pe,in:"header",required:!0,example:rt,schema:{type:"string"},description:`The \`${pe}\` header is used to authenticate with the API using your API key. Value is of the format \`${rt}\`.`};R.parameters?R.parameters.some(Or=>"name"in Or&&Or.name===ze.name)||R.parameters.unshift(ze):R.parameters=[ze];let je={type:"http",scheme:ae.toLowerCase()},Bt="api_key";s.components?.securitySchemes?Object.values(s.components?.securitySchemes).some(Or=>"name"in Or&&Or.type==="apiKey"||"type"in Or&&Or.type==="http"&&Or.scheme===ae)||(s.components.securitySchemes={...s.components.securitySchemes,[Bt]:je}):(s.components||(s.components={}),s.components.securitySchemes={[Bt]:je});let Ut={[Bt]:[]};R.security?R.security.some(Or=>Or[Bt]!==void 0)||R.security.unshift(Ut):R.security=[Ut]}let ve=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="RateLimitInboundPolicy"||ae.handler.export==="ComplexRateLimitInboundPolicy")&&ve.push(ae)})}),ve.length>0){let pe={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},ae={...pe,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};s.components?.responses||s.components||(s.components={}),s.components.responses={...s.components.responses,RateLimitNoRetryAfter:pe,RateLimitWithRetryAfter:ae},R.responses||(R.responses={});let rt=ve.some(ze=>ze.handler.options?.headerMode!=="none");R.responses[429]||(R.responses[429]={$ref:rt?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),d[y]=A,d},{});return{...s,paths:f}}t(hpr,"enrichSpecWithZuploData");function Pft(s,o){for(let f in s)f.startsWith(o)?delete s[f]:typeof s[f]=="object"&&Pft(s[f],o)}t(Pft,"removePropertiesByPrefix");function gpr({relativeOpenApiPath:s},o){if(!o||typeof o!="object")throw new w1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in o)||typeof o.info!="object"||!o.info)throw new w1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in o.info)||typeof o.info.title!="string")throw new w1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(gpr,"assertIsZuploOpenApiSpec");import Epr from"node:fs/promises";import Cpr from"node:path";var{stringify:ypr}=JSON;if(!String.prototype.repeat)throw new Error("String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation");if(!String.prototype.endsWith)throw new Error("String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation");var Ole={"||":2,"??":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},LE=17,vpr={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:LE,ClassExpression:LE,FunctionExpression:LE,ObjectExpression:LE,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function NM(s,o){let{generator:f}=s;if(s.write("("),o!=null&&o.length>0){f[o[0].type](o[0],s);let{length:d}=o;for(let y=1;y<d;y++){let E=o[y];s.write(", "),f[E.type](E,s)}}s.write(")")}t(NM,"formatSequence");function Rft(s,o,f,d){let y=s.expressionsPrecedence[o.type];if(y===LE)return!0;let E=s.expressionsPrecedence[f.type];return y!==E?!d&&y===15&&E===14&&f.operator==="**"||y<E:y!==13&&y!==14?!1:o.operator==="**"&&f.operator==="**"?!d:y===13&&E===13&&(o.operator==="??"||f.operator==="??")?!0:d?Ole[o.operator]<=Ole[f.operator]:Ole[o.operator]<Ole[f.operator]}t(Rft,"expressionNeedsParenthesis");function Fle(s,o,f,d){let{generator:y}=s;Rft(s,o,f,d)?(s.write("("),y[o.type](o,s),s.write(")")):y[o.type](o,s)}t(Fle,"formatExpression");function bpr(s,o,f,d){let y=o.split(`
599
+ `),Xor=["2023-03-14","2024-01-15","2024-03-14","2024-09-02"];function Kct(s){return!s||Xor.includes(s)}t(Kct,"isLegacyPathBehavior");function Zor(s){let o=globalThis.URLPattern;if(typeof o!="function")throw new Error("Native URLPattern is unavailable. Run the build with Node.js 24 or later.");return new o({pathname:s})}t(Zor,"createNativeURLPattern");function tIe(s){let o="",f=0,d=!1;for(let y=0;y<s.length;y++){let E=s[y];if(E==="\\"){o+=E,y+1<s.length&&(o+=s[++y]);continue}!d&&E==="("?f++:!d&&E===")"&&f>0?f--:f>0&&E==="["?d=!0:d&&E==="]"&&(d=!1),E==="/"&&f>0&&(o+="\\"),o+=E}return o}t(tIe,"normalizeUrlPatternForNative");async function rIe(s){try{let{content:o,warnings:f}=await Qor(s);return{content:o,errors:[],warnings:f}}catch(o){if(o instanceof Cy)return o.toBuildResult();throw o}}t(rIe,"compileRoutes");async function Qor({sourceDirectory:s,policiesContent:o,oasContent:f,compatibilityDate:d,allowDuplicateRoutes:y,isAiEnabled:E}){let A=[],R=[],q=new rle,K=new $V,{policiesNode:ve,policiesData:pe}=ncr(o);E===!1&&rcr(pe);let{generatedPolicies:ae,policyNames:rt}=icr(q,K,ve,pe),{generatedCorsPolicies:ze,corsPoliciesNames:je}=scr(q,K,ve,pe),Bt=acr(s,f),Ut=[],Or=new Map,Jn=new Map;for(let br of Bt){let{node:js,oas:Ni,oasProjectRelativePath:jo}=br,ji=G9(js,["paths"]);if(!ji)continue;let Op=sle.basename(Ni.fileName,".oas.json"),ed,Ln=t(()=>(ed??=mcr(js),ed),"getDefaultRewriteServer");for(let Fh of ji.children??[])if(Fh.children){let cl=_cr(Fh),wr=cl[Vct]?.pathMode;if(wr){if(wr!==nle&&wr!==eIe)throw new Cy({text:`Unknown path mode ${wr}`,location:{line:0,column:0,file:jo}})}else wr=nle;for(let[UE,gl]of Object.entries(cl)){if(!ile(UE))continue;let M_=UE,va=M_.split(/,/).map(Lh=>Lh.trim().toUpperCase()),PT=gl,ob=PT[QNe];if(ob){let Oi=new ele().validate(ob);if(Oi.isValid){let Fp=Hct(Fh);if(!Or.has(Fp)&&(Or.set(Fp,new Set),Kct(d)))try{Zor(tIe(Fp))}catch{R.push({text:`Path '${Fp}' contains invalid characters. The value must be a valid URLPattern.`,location:{line:Fh.line,column:Fh.column,file:jo}})}if(!y){let d7=Or.get(Fp);va.forEach(Tt=>{d7.has(Tt)?R.push({text:`Cannot have duplicate routes declared. Route '${Tt.toUpperCase()} ${Fp}' declared more than once.`,location:{line:Fh.line,column:Fh.column,file:jo}}):d7.add(Tt)})}let OS=pcr(Fh,[Fp,M_,QNe]),Ug=dcr(OS),iA=await ycr(OS,Ug,Ni,Jn);if(!iA.valid)throw new Cy({text:iA.errorMsg??`Unknown error on handler for path '${Fp}'`,location:{line:iA.line??0,column:iA.column??0,file:jo}});let tw=bcr(OS,Ug,jo);if(!tw.valid)throw new Cy(tw.errors);tw.warnings&&A.push(...tw.warnings),Ut.push({path:Fp,pathPattern:Fp,pathMode:wr,httpMethods:va,rawOperation:M_,rawOpenAPI:PT,oasFileName:Op,oasProjectRelativePath:jo,config:OS})}else throw new Cy({text:JSON.stringify(Oi.errors),location:{line:0,column:0,file:jo}})}else{let Lh=Hct(Fh),Oi={corsPolicy:"none",handler:hcr(Lh,Ln())};Ut.push({path:Lh,pathPattern:Lh,pathMode:nle,rawOpenAPI:PT,oasFileName:Op,oasProjectRelativePath:jo,httpMethods:va,rawOperation:M_,config:UV(JSON.stringify(Oi))})}if(ob&&"policies"in ob){let Lh=ob.policies;Lh.inbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}),Lh.outbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})})}if(R.length>0)throw new Cy(R);let wj=["none","anything-goes"];if(ob&&"corsPolicy"in ob){let Lh=ob.corsPolicy;if(wj.includes(Lh))continue;je.includes(Lh)||R.push({text:`Cors policy '${Lh}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}}}if(R.length>0)throw new Cy(R)}let _n=[];for(let br of Ut){let js=new JV().convert(br.config);ocr(js,br),ccr(js,br,d),lcr(js,br),ucr(js,br),fcr(js,br);let Ni=q.transform(js),jo=q.errors;if(jo.length>0)throw new Cy({text:JSON.stringify(jo),location:{line:0,column:0,file:br.oasProjectRelativePath}});let Op=new $V().generate(Ni);_n.push(Op)}if(UP(Bt.length===f.length,"Tree length should match OAS file length"),UP(Ut.length===_n.length,`The number of validated nodes should match the number of generated fragments. There were ${Ut.length} validated nodes and ${_n.length} generated fragments.`),R.length>0)throw new Cy(R);let Wn={routes:_n,imports:q.getImports(),policies:ae,corsPolicies:ze};return{content:Kor(Wn),warnings:A}}t(Qor,"generateSourceCode");var ecr=0,tcr=1;function rcr(s){let o=new Set([...wst,...Object.keys(Dst)]),f=(s.policies??[]).filter(y=>y?.policyType&&o.has(y.policyType)).map(y=>`'${y.name}' (policyType: ${y.policyType})`);if(f.length===0)return;let d=f.join(", ");throw new Cy({text:`AI capabilities are disabled for this account, so AI-powered policies cannot be used. Remove ${d} from policies.json or ask an account admin to enable AI capabilities in account settings.`,location:{line:0,column:0,file:"/config/policies.json"}})}t(rcr,"assertNoAiPoliciesUsed");function ncr(s){let o=new Qce,f=JSON.parse(s.content),d=o.validate(f);if(!d.isValid)throw new Cy({text:JSON.stringify(d.errors),location:{line:0,column:0,file:"/config/policies.json"}});let y=new JV().parse(JSON.stringify(f));return{policiesData:f,policiesNode:y}}t(ncr,"getPolicyData");function icr(s,o,f,d){let y=[],E;GN(f);let A=f.children.find(R=>R.name.value==="policies");if(A){let R=s.transform(A);E=o.generate(R),y=d.policies.map(({name:q})=>q)}else E="policies: []";return{generatedPolicies:E,policyNames:y}}t(icr,"generatePolicies");function scr(s,o,f,d){let y,E;GN(f);let A=f.children.find(R=>R.name.value==="corsPolicies");if(A){let R=s.transform(A);E=o.generate(R),y=d.corsPolicies.map(({name:q})=>q)}else E="corsPolicies: []",y=[];return{generatedCorsPolicies:E,corsPoliciesNames:y}}t(scr,"generateCorsPolicies");function acr(s,o){let f=[];for(let d of o){let y=[],E=UV(d.content,y),A=`./${sle.posix.relative(s.replace(/\\/g,"/"),d.fileName.replace(/\\/g,"/"))}`;if(y.length>0)throw new Cy(y.map(R=>({text:Cst(R.error),location:{file:A,line:R.line,column:R.column}})));if(!E)throw new Cy({text:"Error parsing the OpenAPI file. Check the contents of the file.",location:{file:A,line:0,column:0}});f.push({node:E,oas:d,oasProjectRelativePath:A})}return f}t(acr,"getOasTrees");function ocr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"path",type:qo.Identifier,parent:f},f.value=PS.createLiteral(o.path,f),GN(s),s.children.unshift(f)}t(ocr,"embellishWithPath");function ccr(s,o,f){let d={type:qo.Property,parent:s,name:null,value:null};if(d.name={value:"pathPattern",type:qo.Identifier,parent:d},o.pathMode===eIe)d.value=PS.createLiteral(tIe(o.path),d);else{let y=/{(\S+?)}/gm,A=Kct(f)?o.path:o.path.replace(/([*+?()[\].|^$\\:])/g,"\\$1");A=A.replace(y,":$1"),A=tIe(A),o.path.endsWith("/")||(A=`${A}{/}?`),d.value=PS.createLiteral(A,d)}GN(s),s.children.unshift(d)}t(ccr,"embellishWithPathPattern");function lcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"methods",type:qo.Identifier,parent:f},f.value=PS.createArrayOfLiterals(o.httpMethods,f),GN(s),s.children.unshift(f)}t(lcr,"embellishWithMethods");function ucr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"raw",type:qo.Identifier,parent:s};let d=wV(o.oasFileName,o.path,o.rawOperation);f.value={type:qo.Raw,parent:f,value:`() => {return rawRouteData.${d};}`},GN(s),s.children.unshift(f)}t(ucr,"embellishWithRawOpenApi");function fcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"metadata",type:qo.Identifier,parent:s};let d={type:qo.Property,parent:f,name:null,value:null};d.name={value:"filepath",type:qo.Identifier,parent:d},d.value=PS.createLiteral(o.oasProjectRelativePath,d),f.value={type:qo.Object,parent:f,children:[d]},GN(s),s.children.unshift(f)}t(fcr,"embellishWithMetadata");function _cr(s){return UP(s.type==="property"),UP(Array.isArray(s.children)),zV(s.children[tcr])}t(_cr,"evaluatePathItem");function Hct(s){return UP(s.type==="property"),UP(Array.isArray(s.children)),zV(s.children[ecr])}t(Hct,"evaluatePath");function pcr(s,o){return G9(s.parent,o)}t(pcr,"extractZuploRouteNode");function dcr(s){return zV(s)}t(dcr,"evaluateZuploRouteNode");function mcr(s){let o;if(s.type==="object")for(let d of s.children??[]){let y=d.children?.[1];y&&d.children?.[0]?.value==="servers"&&(o=y)}let f=o?zV(o):void 0;return`${f&&f.length>0?f[0].url:"http://example.com"}`}t(mcr,"resolveDefaultRewriteServer");function hcr(s,o){let f=/{(\S+?)}/gm,y=s.replace(f,"${params.$1}");return{export:"urlRewriteHandler",module:"$import(@zuplo/runtime)",options:{rewritePattern:`${o}${y}`,forwardSearch:!0}}}t(hcr,"addDefaultUrlRewriteHandler");async function gcr(s,o){if(o.has(s))return o.get(s);let f=await kst(s);return o.set(s,f),f}t(gcr,"getJSFileExportsCached");async function ycr(s,o,f,d){let y=o.handler.module.replace(/^\$import\(/,"").replace(/\)$/,""),E=sle.join(sle.dirname(f.fileName),"..",`${y}.ts`),A=o.handler.export;if(y==="@zuplo/runtime"||y.startsWith("@zuplo/runtime/"))return{valid:!0};if(await nu.fileExists(E)){let R=await gcr(E,d);if(R===null)return{valid:!1,errorMsg:`Could not find any export due to a compile error in '${nu.getParentDirFilename(E)}'`};if(!R.has(A)){let q=`Could not find export "${A}" in '${nu.getParentDirFilename(E)}'`,K=0,ve=0;if(s.children)for(let pe of s.children)pe.children&&pe.children.forEach(ae=>{ae.value==="handler"&&(K=ae.line,ve=ae.column)});return{valid:!1,errorMsg:q,line:K,column:ve}}return{valid:!0}}else return{valid:!1,errorMsg:`Could not find module '${y}'`}}t(ycr,"checkModuleIsValid");var Gct=t((s,o)=>{let f=G9(s,["handler","options",o])??G9(s,["handler","options"])??G9(s,["handler"]);return f?{line:f.line,column:f.column-1}:{line:0,column:0}},"getHandlerOptionLocation"),vcr="$env(";function bcr(s,o,f){let d=o.handler.export;if(d!=="urlForwardHandler"&&d!=="urlRewriteHandler")return{valid:!0};let y="rewritePattern";d==="urlForwardHandler"&&(y="baseUrl");let E=o.handler.options?.[y];if(!E){let A=Gct(s,y);return{valid:!1,errors:[{text:`Invalid request handler configuration. handler.options.${y} is required but was not provided.`,location:{file:f,line:A.line,column:A.column}}]}}if(E.includes(vcr)){let A=Gct(s,y);return{valid:!0,warnings:[{text:`Invalid environment variable access syntax detected. Use \${env.VAR_NAME} instead of $env(VAR_NAME) for handler.options.${y}.`,location:{file:f,line:A.line,column:A.column}}]}}return{valid:!0}}t(bcr,"checkHandlerIsValid");var BH=wp(g4e(),1);import{readFile as cpr}from"node:fs/promises";var ST=wp(g4e(),1);var NO=class extends Error{static{t(this,"CustomResolveError")}},uI=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(o,f){this.sourceDirectory=o,this.logger=f}dereference(o,f){return BH.$RefParser.dereference(o,{resolve:{json:!0,file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:f?.onDereference}})}bundle(o){return BH.$RefParser.bundle(o,{resolve:{file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(o){return BH.$RefParser.parse(o,{resolve:{file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(o){return BH.$RefParser.resolve(o,{resolve:{file:Ile(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function Ile(s,o){return{order:100,canRead(f){let d=_pr(f.url);if(!(d===void 0||d==="file"))return!1;let E;try{E=kft(f.url)}catch(A){throw new NO(`Malformed URI: ${f.url}`,{cause:A})}try{nu.safePath(s).resolve(E)}catch(A){return o?.warn(A),!1}return!0},async read(f){let d;try{d=kft(f.url)}catch(y){throw new NO(`Malformed URI: ${f.url}`,{cause:y})}try{return await cpr(d)}catch(y){throw new NO(`Error opening file "${d}"`,{cause:y})}}}}t(Ile,"customResolver");var lpr=/\//g,upr=/^(\w{2,}):\/\//i;function fpr(){return/^win/.test(globalThis.process?globalThis.process.platform:"")}t(fpr,"isWindowsPlatform");var y4e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function _pr(s){let o=upr.exec(s);if(o)return o[1].toLowerCase()}t(_pr,"getProtocol");function kft(s,o){let f=fpr();s=decodeURI(s);for(let y=0;y<y4e.length;y+=2)s=s.replace(y4e[y],y4e[y+1]);let d=s.substr(0,7).toLowerCase()==="file://";if(d&&(s=s[7]==="/"?s.substr(8):s.substr(7),f&&s[1]==="/"&&(s=`${s[0]}:${s.substr(1)}`),o?s=`file:///${s}`:(d=!1,s=f?s:`/${s}`)),!d){let y=s.split(f?"\\":"/"),E=[];for(let A of y)A===".."?E.length&&E[E.length-1]!==""&&E.pop():(A!==""||E.length===0)&&E.push(A);s=E.join(f?"\\":"/"),!f&&E[0]===""&&(s=`/${s.substring(1)}`)}return f&&!d&&(s=s.replace(lpr,"\\"),s.substr(1,2)===":\\"&&(s=s[0].toUpperCase()+s.substr(1))),s}t(kft,"toFileSystemPath");var wft="YOUR_KEY_HERE";async function Dft(s){let f=await new uI(s.sourceDirectory,s.logger).bundle(s.openApiDocPath),d=s.openApiDocPath.replace(s.sourceDirectory,"");return ppr({...s,relativeOpenApiPath:d},f)}t(Dft,"buildPublicOpenApiFile");async function ppr(s,o){gpr({relativeOpenApiPath:s.relativeOpenApiPath},o);let f=o;return f=mpr(f),dpr(f,s.urls?.api?.defaultUrl),f=hpr(f,s),Pft(f,"x-zuplo"),f}t(ppr,"buildRawOpenApiFile");function dpr(s,o){o?s.servers=[{url:o}]:s.servers=[]}t(dpr,"addServerHost");function mpr(s){if(!s.paths)return s;let{components:o}=s,f=o?{...o}:void 0,d=[];f&&f.parameters&&(d=Object.entries(f.parameters).reduce((E,[A,R])=>(I9 in R&&Gae(R[I9])&&(E.push(A),f.parameters&&delete f.parameters[A]),E),[]));let y=Object.entries(s.paths).reduce((E,[A,R])=>{if(!R)return E;let q={...R},K=["delete","get","head","patch","post","put","trace","options"];return K.forEach(ve=>{let pe=R[ve];if(!pe)return;if(Gae(pe[I9])){delete q[ve];return}let{parameters:ae}=pe;if(!ae)return;let rt=ae.filter(ze=>{if(I9 in ze&&Gae(ze[I9]))return!1;if("$ref"in ze){let je=ze.$ref.split("/").pop();return je?!d.includes(je):!0}return!0});q[ve]={...pe,parameters:rt}}),K.some(ve=>!!q[ve])&&(E[A]=q),E},{});return{...s,paths:y,components:f}}t(mpr,"removeHiddenRoutesAndParams");function hpr(s,{policiesConfig:o}){if(!s.paths)return s;let f=Object.entries(s.paths).reduce((d,[y,E])=>{if(!E)return d;let A={...E};return[A.delete,A.get,A.head,A.patch,A.post,A.put,A.trace,A.options].forEach(R=>{if(!R)return;let q=R["x-zuplo-route"]?.policies?.inbound?.reduce((pe,ae)=>{let rt=o.policies?.find(({name:Bt})=>Bt===ae);if(!rt)return pe;if(!(rt.handler.export==="CompositeInboundPolicy"))return pe.concat(ae);let je=rt.handler.options?.policies;return je?pe.concat(je):pe},[]),K=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="ApiAuthKeyInboundPolicy"||ae.handler.export==="ApiKeyInboundPolicy")&&!ae.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&K.push(ae)})}),K.length>0){let pe=K.length>0&&K[0].handler&&K[0].handler.options&&K[0].handler.options.authHeader?K[0].handler.options.authHeader:"Authorization",ae=K.length>0&&K[0].handler&&K[0].handler.options&&(K[0].handler.options.authScheme||K[0].handler.options.authScheme==="")?K[0].handler.options.authScheme:"Bearer",rt=ae!==""?`${ae} ${wft}`:wft,ze={name:pe,in:"header",required:!0,example:rt,schema:{type:"string"},description:`The \`${pe}\` header is used to authenticate with the API using your API key. Value is of the format \`${rt}\`.`};R.parameters?R.parameters.some(Or=>"name"in Or&&Or.name===ze.name)||R.parameters.unshift(ze):R.parameters=[ze];let je={type:"http",scheme:ae.toLowerCase()},Bt="api_key";s.components?.securitySchemes?Object.values(s.components?.securitySchemes).some(Or=>"name"in Or&&Or.type==="apiKey"||"type"in Or&&Or.type==="http"&&Or.scheme===ae)||(s.components.securitySchemes={...s.components.securitySchemes,[Bt]:je}):(s.components||(s.components={}),s.components.securitySchemes={[Bt]:je});let Ut={[Bt]:[]};R.security?R.security.some(Or=>Or[Bt]!==void 0)||R.security.unshift(Ut):R.security=[Ut]}let ve=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="RateLimitInboundPolicy"||ae.handler.export==="ComplexRateLimitInboundPolicy")&&ve.push(ae)})}),ve.length>0){let pe={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},ae={...pe,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};s.components?.responses||s.components||(s.components={}),s.components.responses={...s.components.responses,RateLimitNoRetryAfter:pe,RateLimitWithRetryAfter:ae},R.responses||(R.responses={});let rt=ve.some(ze=>ze.handler.options?.headerMode!=="none");R.responses[429]||(R.responses[429]={$ref:rt?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),d[y]=A,d},{});return{...s,paths:f}}t(hpr,"enrichSpecWithZuploData");function Pft(s,o){for(let f in s)f.startsWith(o)?delete s[f]:typeof s[f]=="object"&&Pft(s[f],o)}t(Pft,"removePropertiesByPrefix");function gpr({relativeOpenApiPath:s},o){if(!o||typeof o!="object")throw new w1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in o)||typeof o.info!="object"||!o.info)throw new w1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in o.info)||typeof o.info.title!="string")throw new w1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(gpr,"assertIsZuploOpenApiSpec");import Epr from"node:fs/promises";import Cpr from"node:path";var{stringify:ypr}=JSON;if(!String.prototype.repeat)throw new Error("String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation");if(!String.prototype.endsWith)throw new Error("String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation");var Ole={"||":2,"??":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},LE=17,vpr={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:LE,ClassExpression:LE,FunctionExpression:LE,ObjectExpression:LE,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function NM(s,o){let{generator:f}=s;if(s.write("("),o!=null&&o.length>0){f[o[0].type](o[0],s);let{length:d}=o;for(let y=1;y<d;y++){let E=o[y];s.write(", "),f[E.type](E,s)}}s.write(")")}t(NM,"formatSequence");function Rft(s,o,f,d){let y=s.expressionsPrecedence[o.type];if(y===LE)return!0;let E=s.expressionsPrecedence[f.type];return y!==E?!d&&y===15&&E===14&&f.operator==="**"||y<E:y!==13&&y!==14?!1:o.operator==="**"&&f.operator==="**"?!d:y===13&&E===13&&(o.operator==="??"||f.operator==="??")?!0:d?Ole[o.operator]<=Ole[f.operator]:Ole[o.operator]<Ole[f.operator]}t(Rft,"expressionNeedsParenthesis");function Fle(s,o,f,d){let{generator:y}=s;Rft(s,o,f,d)?(s.write("("),y[o.type](o,s),s.write(")")):y[o.type](o,s)}t(Fle,"formatExpression");function bpr(s,o,f,d){let y=o.split(`
600
600
  `),E=y.length-1;if(s.write(y[0].trim()),E>0){s.write(d);for(let A=1;A<E;A++)s.write(f+y[A].trim()+d);s.write(f+y[E].trim())}}t(bpr,"reindent");function M1(s,o,f,d){let{length:y}=o;for(let E=0;E<y;E++){let A=o[E];s.write(f),A.type[0]==="L"?s.write("// "+A.value.trim()+`
601
601
  `,A):(s.write("/*"),bpr(s,A.value,f,d),s.write("*/"+d))}}t(M1,"formatComments");function Spr(s){let o=s;for(;o!=null;){let{type:f}=o;if(f[0]==="C"&&f[1]==="a")return!0;if(f[0]==="M"&&f[1]==="e"&&f[2]==="m")o=o.object;else return!1}}t(Spr,"hasCallExpression");function v4e(s,o){let{generator:f}=s,{declarations:d}=o;s.write(o.kind+" ");let{length:y}=d;if(y>0){f.VariableDeclarator(d[0],s);for(let E=1;E<y;E++)s.write(", "),f.VariableDeclarator(d[E],s)}}t(v4e,"formatVariableDeclaration");var Aft,Nft,Ift,Oft,Fft,Lft,Tpr={Program(s,o){let f=o.indent.repeat(o.indentLevel),{lineEnd:d,writeComments:y}=o;y&&s.comments!=null&&M1(o,s.comments,f,d);let E=s.body,{length:A}=E;for(let R=0;R<A;R++){let q=E[R];y&&q.comments!=null&&M1(o,q.comments,f,d),o.write(f),this[q.type](q,o),o.write(d)}y&&s.trailingComments!=null&&M1(o,s.trailingComments,f,d)},BlockStatement:Lft=t(function(s,o){let f=o.indent.repeat(o.indentLevel++),{lineEnd:d,writeComments:y}=o,E=f+o.indent;o.write("{");let A=s.body;if(A!=null&&A.length>0){o.write(d),y&&s.comments!=null&&M1(o,s.comments,E,d);let{length:R}=A;for(let q=0;q<R;q++){let K=A[q];y&&K.comments!=null&&M1(o,K.comments,E,d),o.write(E),this[K.type](K,o),o.write(d)}o.write(f)}else y&&s.comments!=null&&(o.write(d),M1(o,s.comments,E,d),o.write(f));y&&s.trailingComments!=null&&M1(o,s.trailingComments,E,d),o.write("}"),o.indentLevel--},"BlockStatement"),ClassBody:Lft,StaticBlock(s,o){o.write("static "),this.BlockStatement(s,o)},EmptyStatement(s,o){o.write(";")},ExpressionStatement(s,o){let f=o.expressionsPrecedence[s.expression.type];f===LE||f===3&&s.expression.left.type[0]==="O"?(o.write("("),this[s.expression.type](s.expression,o),o.write(")")):this[s.expression.type](s.expression,o),o.write(";")},IfStatement(s,o){o.write("if ("),this[s.test.type](s.test,o),o.write(") "),this[s.consequent.type](s.consequent,o),s.alternate!=null&&(o.write(" else "),this[s.alternate.type](s.alternate,o))},LabeledStatement(s,o){this[s.label.type](s.label,o),o.write(": "),this[s.body.type](s.body,o)},BreakStatement(s,o){o.write("break"),s.label!=null&&(o.write(" "),this[s.label.type](s.label,o)),o.write(";")},ContinueStatement(s,o){o.write("continue"),s.label!=null&&(o.write(" "),this[s.label.type](s.label,o)),o.write(";")},WithStatement(s,o){o.write("with ("),this[s.object.type](s.object,o),o.write(") "),this[s.body.type](s.body,o)},SwitchStatement(s,o){let f=o.indent.repeat(o.indentLevel++),{lineEnd:d,writeComments:y}=o;o.indentLevel++;let E=f+o.indent,A=E+o.indent;o.write("switch ("),this[s.discriminant.type](s.discriminant,o),o.write(") {"+d);let{cases:R}=s,{length:q}=R;for(let K=0;K<q;K++){let ve=R[K];y&&ve.comments!=null&&M1(o,ve.comments,E,d),ve.test?(o.write(E+"case "),this[ve.test.type](ve.test,o),o.write(":"+d)):o.write(E+"default:"+d);let{consequent:pe}=ve,{length:ae}=pe;for(let rt=0;rt<ae;rt++){let ze=pe[rt];y&&ze.comments!=null&&M1(o,ze.comments,A,d),o.write(A),this[ze.type](ze,o),o.write(d)}}o.indentLevel-=2,o.write(f+"}")},ReturnStatement(s,o){o.write("return"),s.argument&&(o.write(" "),this[s.argument.type](s.argument,o)),o.write(";")},ThrowStatement(s,o){o.write("throw "),this[s.argument.type](s.argument,o),o.write(";")},TryStatement(s,o){if(o.write("try "),this[s.block.type](s.block,o),s.handler){let{handler:f}=s;f.param==null?o.write(" catch "):(o.write(" catch ("),this[f.param.type](f.param,o),o.write(") ")),this[f.body.type](f.body,o)}s.finalizer&&(o.write(" finally "),this[s.finalizer.type](s.finalizer,o))},WhileStatement(s,o){o.write("while ("),this[s.test.type](s.test,o),o.write(") "),this[s.body.type](s.body,o)},DoWhileStatement(s,o){o.write("do "),this[s.body.type](s.body,o),o.write(" while ("),this[s.test.type](s.test,o),o.write(");")},ForStatement(s,o){if(o.write("for ("),s.init!=null){let{init:f}=s;f.type[0]==="V"?v4e(o,f):this[f.type](f,o)}o.write("; "),s.test&&this[s.test.type](s.test,o),o.write("; "),s.update&&this[s.update.type](s.update,o),o.write(") "),this[s.body.type](s.body,o)},ForInStatement:Aft=t(function(s,o){o.write(`for ${s.await?"await ":""}(`);let{left:f}=s;f.type[0]==="V"?v4e(o,f):this[f.type](f,o),o.write(s.type[3]==="I"?" in ":" of "),this[s.right.type](s.right,o),o.write(") "),this[s.body.type](s.body,o)},"ForInStatement"),ForOfStatement:Aft,DebuggerStatement(s,o){o.write("debugger;",s)},FunctionDeclaration:Nft=t(function(s,o){o.write((s.async?"async ":"")+(s.generator?"function* ":"function ")+(s.id?s.id.name:""),s),NM(o,s.params),o.write(" "),this[s.body.type](s.body,o)},"FunctionDeclaration"),FunctionExpression:Nft,VariableDeclaration(s,o){v4e(o,s),o.write(";")},VariableDeclarator(s,o){this[s.id.type](s.id,o),s.init!=null&&(o.write(" = "),this[s.init.type](s.init,o))},ClassDeclaration(s,o){if(o.write("class "+(s.id?`${s.id.name} `:""),s),s.superClass){o.write("extends ");let{superClass:f}=s,{type:d}=f,y=o.expressionsPrecedence[d];(d[0]!=="C"||d[1]!=="l"||d[5]!=="E")&&(y===LE||y<o.expressionsPrecedence.ClassExpression)?(o.write("("),this[s.superClass.type](f,o),o.write(")")):this[f.type](f,o),o.write(" ")}this.ClassBody(s.body,o)},ImportDeclaration(s,o){o.write("import ");let{specifiers:f,attributes:d}=s,{length:y}=f,E=0;if(y>0){for(;E<y;){E>0&&o.write(", ");let A=f[E],R=A.type[6];if(R==="D")o.write(A.local.name,A),E++;else if(R==="N")o.write("* as "+A.local.name,A),E++;else break}if(E<y){for(o.write("{");;){let A=f[E],{name:R}=A.imported;if(o.write(R,A),R!==A.local.name&&o.write(" as "+A.local.name),++E<y)o.write(", ");else break}o.write("}")}o.write(" from ")}if(this.Literal(s.source,o),d&&d.length>0){o.write(" with { ");for(let A=0;A<d.length;A++)this.ImportAttribute(d[A],o),A<d.length-1&&o.write(", ");o.write(" }")}o.write(";")},ImportAttribute(s,o){this.Identifier(s.key,o),o.write(": "),this.Literal(s.value,o)},ImportExpression(s,o){o.write("import("),this[s.source.type](s.source,o),o.write(")")},ExportDefaultDeclaration(s,o){o.write("export default "),this[s.declaration.type](s.declaration,o),o.expressionsPrecedence[s.declaration.type]!=null&&s.declaration.type[0]!=="F"&&o.write(";")},ExportNamedDeclaration(s,o){if(o.write("export "),s.declaration)this[s.declaration.type](s.declaration,o);else{o.write("{");let{specifiers:f}=s,{length:d}=f;if(d>0)for(let y=0;;){let E=f[y],{name:A}=E.local;if(o.write(A,E),A!==E.exported.name&&o.write(" as "+E.exported.name),++y<d)o.write(", ");else break}if(o.write("}"),s.source&&(o.write(" from "),this.Literal(s.source,o)),s.attributes&&s.attributes.length>0){o.write(" with { ");for(let y=0;y<s.attributes.length;y++)this.ImportAttribute(s.attributes[y],o),y<s.attributes.length-1&&o.write(", ");o.write(" }")}o.write(";")}},ExportAllDeclaration(s,o){if(s.exported!=null?o.write("export * as "+s.exported.name+" from "):o.write("export * from "),this.Literal(s.source,o),s.attributes&&s.attributes.length>0){o.write(" with { ");for(let f=0;f<s.attributes.length;f++)this.ImportAttribute(s.attributes[f],o),f<s.attributes.length-1&&o.write(", ");o.write(" }")}o.write(";")},MethodDefinition(s,o){s.static&&o.write("static ");let f=s.kind[0];(f==="g"||f==="s")&&o.write(s.kind+" "),s.value.async&&o.write("async "),s.value.generator&&o.write("*"),s.computed?(o.write("["),this[s.key.type](s.key,o),o.write("]")):this[s.key.type](s.key,o),NM(o,s.value.params),o.write(" "),this[s.value.body.type](s.value.body,o)},ClassExpression(s,o){this.ClassDeclaration(s,o)},ArrowFunctionExpression(s,o){o.write(s.async?"async ":"",s);let{params:f}=s;f!=null&&(f.length===1&&f[0].type[0]==="I"?o.write(f[0].name,f[0]):NM(o,s.params)),o.write(" => "),s.body.type[0]==="O"?(o.write("("),this.ObjectExpression(s.body,o),o.write(")")):this[s.body.type](s.body,o)},ThisExpression(s,o){o.write("this",s)},Super(s,o){o.write("super",s)},RestElement:Ift=t(function(s,o){o.write("..."),this[s.argument.type](s.argument,o)},"RestElement"),SpreadElement:Ift,YieldExpression(s,o){o.write(s.delegate?"yield*":"yield"),s.argument&&(o.write(" "),this[s.argument.type](s.argument,o))},AwaitExpression(s,o){o.write("await ",s),Fle(o,s.argument,s)},TemplateLiteral(s,o){let{quasis:f,expressions:d}=s;o.write("`");let{length:y}=d;for(let A=0;A<y;A++){let R=d[A],q=f[A];o.write(q.value.raw,q),o.write("${"),this[R.type](R,o),o.write("}")}let E=f[f.length-1];o.write(E.value.raw,E),o.write("`")},TemplateElement(s,o){o.write(s.value.raw,s)},TaggedTemplateExpression(s,o){Fle(o,s.tag,s),this[s.quasi.type](s.quasi,o)},ArrayExpression:Fft=t(function(s,o){if(o.write("["),s.elements.length>0){let{elements:f}=s,{length:d}=f;for(let y=0;;){let E=f[y];if(E!=null&&this[E.type](E,o),++y<d)o.write(", ");else{E==null&&o.write(", ");break}}}o.write("]")},"ArrayExpression"),ArrayPattern:Fft,ObjectExpression(s,o){let f=o.indent.repeat(o.indentLevel++),{lineEnd:d,writeComments:y}=o,E=f+o.indent;if(o.write("{"),s.properties.length>0){o.write(d),y&&s.comments!=null&&M1(o,s.comments,E,d);let A=","+d,{properties:R}=s,{length:q}=R;for(let K=0;;){let ve=R[K];if(y&&ve.comments!=null&&M1(o,ve.comments,E,d),o.write(E),this[ve.type](ve,o),++K<q)o.write(A);else break}o.write(d),y&&s.trailingComments!=null&&M1(o,s.trailingComments,E,d),o.write(f+"}")}else y?s.comments!=null?(o.write(d),M1(o,s.comments,E,d),s.trailingComments!=null&&M1(o,s.trailingComments,E,d),o.write(f+"}")):s.trailingComments!=null?(o.write(d),M1(o,s.trailingComments,E,d),o.write(f+"}")):o.write("}"):o.write("}");o.indentLevel--},Property(s,o){s.method||s.kind[0]!=="i"?this.MethodDefinition(s,o):(s.shorthand||(s.computed?(o.write("["),this[s.key.type](s.key,o),o.write("]")):this[s.key.type](s.key,o),o.write(": ")),this[s.value.type](s.value,o))},PropertyDefinition(s,o){if(s.static&&o.write("static "),s.computed&&o.write("["),this[s.key.type](s.key,o),s.computed&&o.write("]"),s.value==null){s.key.type[0]!=="F"&&o.write(";");return}o.write(" = "),this[s.value.type](s.value,o),o.write(";")},ObjectPattern(s,o){if(o.write("{"),s.properties.length>0){let{properties:f}=s,{length:d}=f;for(let y=0;this[f[y].type](f[y],o),++y<d;)o.write(", ")}o.write("}")},SequenceExpression(s,o){NM(o,s.expressions)},UnaryExpression(s,o){if(s.prefix){let{operator:f,argument:d,argument:{type:y}}=s;o.write(f);let E=Rft(o,d,s);!E&&(f.length>1||y[0]==="U"&&(y[1]==="n"||y[1]==="p")&&d.prefix&&d.operator[0]===f&&(f==="+"||f==="-"))&&o.write(" "),E?(o.write(f.length>1?" (":"("),this[y](d,o),o.write(")")):this[y](d,o)}else this[s.argument.type](s.argument,o),o.write(s.operator)},UpdateExpression(s,o){s.prefix?(o.write(s.operator),this[s.argument.type](s.argument,o)):(this[s.argument.type](s.argument,o),o.write(s.operator))},AssignmentExpression(s,o){this[s.left.type](s.left,o),o.write(" "+s.operator+" "),this[s.right.type](s.right,o)},AssignmentPattern(s,o){this[s.left.type](s.left,o),o.write(" = "),this[s.right.type](s.right,o)},BinaryExpression:Oft=t(function(s,o){let f=s.operator==="in";f&&o.write("("),Fle(o,s.left,s,!1),o.write(" "+s.operator+" "),Fle(o,s.right,s,!0),f&&o.write(")")},"BinaryExpression"),LogicalExpression:Oft,ConditionalExpression(s,o){let{test:f}=s,d=o.expressionsPrecedence[f.type];d===LE||d<=o.expressionsPrecedence.ConditionalExpression?(o.write("("),this[f.type](f,o),o.write(")")):this[f.type](f,o),o.write(" ? "),this[s.consequent.type](s.consequent,o),o.write(" : "),this[s.alternate.type](s.alternate,o)},NewExpression(s,o){o.write("new ");let f=o.expressionsPrecedence[s.callee.type];f===LE||f<o.expressionsPrecedence.CallExpression||Spr(s.callee)?(o.write("("),this[s.callee.type](s.callee,o),o.write(")")):this[s.callee.type](s.callee,o),NM(o,s.arguments)},CallExpression(s,o){let f=o.expressionsPrecedence[s.callee.type];f===LE||f<o.expressionsPrecedence.CallExpression?(o.write("("),this[s.callee.type](s.callee,o),o.write(")")):this[s.callee.type](s.callee,o),s.optional&&o.write("?."),NM(o,s.arguments)},ChainExpression(s,o){this[s.expression.type](s.expression,o)},MemberExpression(s,o){let f=o.expressionsPrecedence[s.object.type];f===LE||f<o.expressionsPrecedence.MemberExpression?(o.write("("),this[s.object.type](s.object,o),o.write(")")):this[s.object.type](s.object,o),s.computed?(s.optional&&o.write("?."),o.write("["),this[s.property.type](s.property,o),o.write("]")):(s.optional?o.write("?."):o.write("."),this[s.property.type](s.property,o))},MetaProperty(s,o){o.write(s.meta.name+"."+s.property.name,s)},Identifier(s,o){o.write(s.name,s)},PrivateIdentifier(s,o){o.write(`#${s.name}`,s)},Literal(s,o){s.raw!=null?o.write(s.raw,s):s.regex!=null?this.RegExpLiteral(s,o):s.bigint!=null?o.write(s.bigint+"n",s):o.write(ypr(s.value),s)},RegExpLiteral(s,o){let{regex:f}=s;o.write(`/${f.pattern}/${f.flags}`,s)}},xpr={};var b4e=class{static{t(this,"State")}constructor(o){let f=o??xpr;this.output="",f.output!=null?(this.output=f.output,this.write=this.writeToStream):this.output="",this.generator=f.generator!=null?f.generator:Tpr,this.expressionsPrecedence=f.expressionsPrecedence!=null?f.expressionsPrecedence:vpr,this.indent=f.indent!=null?f.indent:" ",this.lineEnd=f.lineEnd!=null?f.lineEnd:`
602
602
  `,this.indentLevel=f.startingIndentLevel!=null?f.startingIndentLevel:0,this.writeComments=f.comments?f.comments:!1,f.sourceMap!=null&&(this.write=f.output==null?this.writeAndMap:this.writeToStreamAndMap,this.sourceMap=f.sourceMap,this.line=1,this.column=0,this.lineEndSize=this.lineEnd.split(`
package/index.minified.js CHANGED
@@ -572,7 +572,7 @@ globstar while`,s,pe,o,ae,rt),this.matchOne(s.slice(pe),o.slice(ae),f))return th
572
572
  `),stderr:E.join(`
573
573
  `),exitCode:A},"Tar process logs")}}t(sZt,"tarFolder");async function aZt({tarFilePath:s,outputDir:o,logger:f}){let d=[],y=[],E;try{await new Promise((A,R)=>{let q=cit("sh",["-c",`tar -xvf ${s} -C ${o};`]);q.stdout.on("data",K=>{let ve=K.toString().trim();ve.length>0&&d.push(ve.trim())}),q.stderr.on("data",K=>{let ve=K.toString().trim();ve.length>0&&y.push(ve.trim())}),q.on("close",K=>{E=K,K===0?A():R(new Error(`tar process exited with code ${K}`))}),q.on("error",K=>{R(K)})})}catch(A){throw new Error("Failed to untar file",{cause:A})}finally{f.info({stdout:d.join(`
574
574
  `),stderr:y.join(`
575
- `),exitCode:E},"Untar process logs")}}t(aZt,"untarFile");async function oZt(s){if(await nAe(s))return await GN.rm(s,{recursive:!0})}t(oZt,"deleteFolder");var nu=iAe;var rlt=R_(Nst(),1);import{AssertionError as Fer}from"node:assert";function $P(s,o){if(s===!1)throw new Fer({message:o})}t($P,"assert");var qo;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.Raw="Raw"})(qo||(qo={}));function H9(s){return s.type===qo.Object}t(H9,"isAstObject");function WP(s){return s.type===qo.Property}t(WP,"isAstProperty");function jAe(s){return s.type===qo.Array}t(jAe,"isAstArray");function pO(s){return s.type===qo.Literal}t(pO,"isAstLiteral");function XN(s){if(s===void 0)throw new Error("Node is undefined");if(!H9(s))throw new Error("Node is not object")}t(XN,"assertAstObject");import{findNodeAtLocation as Ler,getNodeValue as Rer,printParseErrorCode as Mer,visit as jer}from"jsonc-parser";var Ber={DEFAULT:{allowTrailingComma:!1}};function zV(s,o=[],f=Ber.DEFAULT){let d={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(q){d.type==="property"&&(d.length=q-d.offset,d=d.parent)}t(y,"ensurePropertyComplete");function E(q){return d.children?.push(q),q}t(E,"onValue"),jer(s,{onObjectBegin:t((q,K,ve,pe)=>{d=E({type:"object",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onObjectBegin"),onObjectProperty:t((q,K,ve,pe,ae)=>{d=E({type:"property",offset:K,length:-1,line:pe+1,column:ae+1,parent:d,children:[]}),d.children?.push({type:"string",value:q,offset:K,length:ve,line:pe,column:ae,parent:d})},"onObjectProperty"),onObjectEnd:t((q,K)=>{y(q+K),d.length=q+K-d.offset,d=d.parent,y(q+K)},"onObjectEnd"),onArrayBegin:t((q,K,ve,pe)=>{d=E({type:"array",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onArrayBegin"),onArrayEnd:t((q,K)=>{d.length=q+K-d.offset,d=d.parent,y(q+K)},"onArrayEnd"),onLiteralValue:t((q,K,ve,pe,ae)=>{E({type:Uer(q),offset:K,length:ve,line:pe+1,column:ae+1,parent:d,value:q}),y(K+ve)},"onLiteralValue"),onSeparator:t((q,K)=>{d.type==="property"&&(q===":"?d.colonOffset=K:q===","&&y(K))},"onSeparator"),onError:t((q,K,ve,pe,ae)=>{o.push({error:q,offset:K,length:ve,line:pe+1,column:ae+1})},"onError")},f);let R=d.children?.[0];return R&&delete R.parent,R}t(zV,"parse");function Uer(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(Uer,"getNodeType");function G9(s,o){return Ler(s,o)}t(G9,"findNodeAtLocation");function JV(s){return Rer(s)}t(JV,"getNodeValue");function Ist(s){return Mer(s)}t(Ist,"printParseErrorCode");var $V=class{static{t(this,"AstAdapter")}parse(o){let d=zV(o,[]);if(d)return this.parseNode(d,void 0);throw new Error("Failed to parse JSON")}convert(o){return this.parseNode(o,void 0)}parseNode(o,f){switch(o.type){case"object":return this.createObject(o,f);case"array":return this.createArray(o,f);case"property":return this.createProperty(o,f);case"string":return this.createLiteral(o,f);case"number":return this.createLiteral(o,f);case"boolean":return this.createLiteral(o,f);case"null":return this.createLiteral(o,f)}}createLiteral(o,f){return{type:qo.Literal,location:{line:o.line,column:o.column},parent:f,value:o.type==="null"?null:o.value}}createObject(o,f){let d={type:qo.Object,children:[],parent:f,location:{line:o.line,column:o.column}};return o.children?.forEach(y=>{d.children.push(this.parseNode(y,d))}),d}createProperty(o,f){$P(o.children?.length===2,"Invalid property node");let d={type:qo.Property,location:{line:o.line,column:o.column},parent:f,name:null,value:null};return d.name={value:o.children[0].value,location:{line:o.line,column:o.column},type:qo.Identifier,parent:d},d.value=this.parseNode(o.children[1],d),d}createArray(o,f){let d={type:qo.Array,location:{line:o.line,column:o.column},parent:f,children:[]};return o.children?.forEach(y=>d.children.push(this.parseNode(y,d))),d}};var PS={createLiteral:t((s,o)=>({type:qo.Literal,parent:o,value:s}),"createLiteral"),createTemplateString:t((s,o)=>({type:qo.TemplateString,parent:o,value:s}),"createTemplateString"),createIdentifier:t((s,o)=>({type:qo.Identifier,value:s,parent:o}),"createIdentifier"),createProperty:t((s,o,f)=>{let d={type:qo.Property,parent:f,name:null,value:o};return d.name={value:s,type:qo.Identifier,parent:d},d.value.parent=d,d},"createProperty"),createArrayOfLiterals:t((s,o)=>{let f={type:qo.Array,parent:o,children:[]};for(let d of s)f.children.push(PS.createLiteral(d,f));return f},"createArrayOfLiterals")};var zer=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,WV=class{static{t(this,"SourceGenerator")}generate(o){let f=[];return this.generateSource(f,o),f.join("")}generateSource(o,f){switch(f.type){case qo.Array:return this.generateArray(o,f);case qo.Object:return this.generateObject(o,f);case qo.Property:return this.generateProperty(o,f);case qo.Literal:return this.generateLiteral(o,f);case qo.FunctionCall:return this.generateFunctionCall(o,f);case qo.Identifier:return this.generateIdentifier(o,f);case qo.Raw:return this.generateRaw(o,f);case qo.TemplateString:return this.generateTemplateString(o,f)}}generateArray(o,f){o.push("["),f.children.map(d=>{this.generateSource(o,d),o.push(",")}),o.push("]")}generateObject(o,f){o.push("{"),f.children.forEach(d=>{this.generateSource(o,d),o.push(",")}),o.push("}")}generateProperty(o,f){this.generateIdentifier(o,f.name),o.push(":"),this.generateSource(o,f.value)}generateFunctionCall(o,f){o.push(f.name.value),o.push("("),f.children.forEach((d,y,E)=>{this.generateSource(o,d),y<E.length&&o.push(",")}),o.push(")")}generateRaw(o,f){o.push(f.value)}generateTemplateString(o,f){o.push("`"),o.push(f.value.replaceAll("`","\\`")),o.push("`")}generateLiteral(o,f){if(f.value===null)return o.push("null");switch(typeof f.value){case"number":case"boolean":return o.push(`${f.value}`);case"string":{let d=f.value,y=JSON.stringify(d);return o.push(`${y}`)}}}generateIdentifier(o,f){let d=zer.test(f.value)?f.value:`'${f.value}'`;o.push(d)}};import Jer from"node:fs/promises";import{parse as $er}from"@swc/core";var Ost=t(async s=>{let o=new Set;try{let f=await Jer.readFile(s,"utf-8");(await $er(f,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?o.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?o.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&o.add(y.declaration.declarations[0].id.value)})}catch{return null}return o},"getJSFileExports");var Fst=["ai-gateway-auth-v2","ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2","ai-gateway-dlp","ai-gateway-fallback-model-v2","ai-gateway-metering-v2","ai-gateway-model-filtering-v2","ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2","akamai-ai-firewall","akamai-ai-firewall-v2","akamai-firewall-for-ai","comet-opik-tracing-v2","galileo-tracing-v2","prompt-injection","semantic-cache"],Lst={"ai-gateway-auth-v2-inbound":"ai-gateway-auth-v2","ai-gateway-configuration-executor-v2-inbound":"ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2-inbound":"ai-gateway-configuration-loader-v2","ai-gateway-dlp-inbound":"ai-gateway-dlp","ai-gateway-fallback-model-v2-inbound":"ai-gateway-fallback-model-v2","ai-gateway-metering-v2-inbound":"ai-gateway-metering-v2","ai-gateway-model-filtering-v2-inbound":"ai-gateway-model-filtering-v2","ai-gateway-semantic-cache-inbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-outbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2-inbound":"ai-gateway-semantic-cache-v2","akamai-ai-firewall-v2-inbound":"akamai-ai-firewall-v2","akamai-firewall-for-ai-inbound":"akamai-firewall-for-ai","akamai-firewall-for-ai-outbound":"akamai-firewall-for-ai","comet-opik-tracing-v2-inbound":"comet-opik-tracing-v2","galileo-tracing-v2-inbound":"galileo-tracing-v2","prompt-injection-outbound":"prompt-injection","semantic-cache-inbound":"semantic-cache"};var Rst={$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 BAe={$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 Mst={$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 UAe={$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"],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:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},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 zAe={$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:{},mcp:{oneOf:[{type:"object",additionalProperties:!1,properties:{type:{const:"tool"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"},includeOutputSchema:{type:"boolean"},includeStructuredContent:{type:"boolean"},annotations:{type:"object",additionalProperties:!1,properties:{title:{type:"string"},readOnlyHint:{type:"boolean"},destructiveHint:{type:"boolean"},idempotentHint:{type:"boolean"},openWorldHint:{type:"boolean"}}},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"prompt"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"resource"},name:{type:"string"},description:{type:"string"},uri:{type:"string"},mimeType:{type:"string"},enabled:{type:"boolean"},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"graphql"},enabled:{type:"boolean"},introspectionTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}},executeTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}}},required:["type"]}]},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 Vct=R_(Gce(),1),Hct=R_(Zce(),1);var Qce=class s{static{t(this,"JsonValidator")}static#e=new s;static get instance(){return s.#e}ajv;constructor(){this.ajv=new Vct.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Hct.default)(this.ajv,{mode:"fast"})}addSchema(o,f){this.ajv.addSchema(o,f)}compile(o){let f=this.ajv.compile(o);return t(y=>({isValid:f(y),errors:this.toSimpleErrors(f.errors,y),warnings:[]}),"validator")}toSimpleErrors(o,f){let d=[];return o?.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 E={details:{}},A=y.instancePath.split("/");if(A.length>2){let q=A[1],K=A[2]?parseInt(A[2],10):0,ve=A[3],pe=Number.isNaN(K)?void 0:f[q][K][ve];E={details:{property:q,index:K,field:ve,fieldValue:pe}}}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 q=y.instancePath.split("/"),K=q[q.length-1];y.message=`Value of property '${K}' must be '${y.params.type}'`}let R=Object.assign(y,E);d.push(R)}),d}};var oI=Qce.instance;oI.addSchema(UAe,"route-configuration.schema.json");oI.addSchema(Mst,"policy-configuration.schema.json");oI.addSchema(BAe,"policies.schema.json");oI.addSchema(zAe,"open-api-route-configuration.schema.json");oI.addSchema(Rst,"fragments.schema.json");var y6r=oI.compile(UAe),Gct=oI.compile(zAe),nIe=oI.compile(BAe);var ele=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(o){return this.results=nIe(o),this.results}};var tle=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(o){return this.results=Gct(o),this.results}};import dcr from"node:path";var iIe=/\$import\((.*)\)/,SH=/\$env\((.*?)\)/g;var Uk=class extends Error{static{t(this,"CodeGenError")}location;constructor(o,f,d,y){super(o),this.location={file:f,namespace:"",line:d?d.line:0,column:d?d.column:0,length:0,lineText:y??"",suggestion:""}}},pcr=t(s=>{let o=[],f=s;for(;f.parent;)o.push(f),f=f.parent;return o.reverse()},"invertTree"),GP=t((s,o)=>{if(!s)return!1;let f=pcr(s);return o.split("/").every((E,A)=>{let R=f[A];return R?E==="*"||WP(R)&&R.name.value===E?!0:E==="{}"?R.type===qo.Object:E==="[]"?R.type===qo.Array:!1:!1})},"testPosition");var rle=class{static{t(this,"AstTransformer")}errors=[];transform(o){return this.visitor(o),o}visitor(o){this.visit(o),H9(o)?o.children.forEach(f=>{this.visitor(f)}):jAe(o)?o.children.forEach(f=>{this.visitor(f)}):WP(o)&&this.visitor(o.value)}},Yct=t(s=>{let o=new RegExp(SH).exec(s);if(o?.length===2&&o[0]===s)return{type:"raw",value:`environment["${o[1]}"]`};{let f=s.replaceAll(new RegExp(SH),(d,y)=>`\${environment["${y}"] ? environment["${y}"] : ""}`);if(f!==s)return{type:"template",value:f}}return null},"replaceEnvInString"),Kct=t((s,o,f)=>d=>{if(pO(d)&&typeof d.value=="string"&&d.parent&&jAe(d.parent)){if(!s.some(A=>GP(d.parent,A))){SH.test(d.value)&&o.push(new Uk("An $env() statement is not expected at this location.",f,d.location,d.value));return}let E=Yct(d.value);if(E){let A=d.parent,R=A.children.indexOf(d);if(R!==-1)if(E.type==="raw"){let q={type:qo.Raw,parent:A,value:E.value};A.children[R]=q}else A.children[R]=PS.createTemplateString(E.value,d)}return}if(!WP(d)||!pO(d.value)||typeof d.value.value!="string")return;if(!s.some(E=>GP(d,E))){SH.test(d.value.value)&&o.push(new Uk("An $env() statement is not expected at this location.",f,d.location,d.value.value));return}let y=Yct(d.value.value);if(y)if(y.type==="raw"){let E={type:qo.Raw,parent:null,value:y.value};d.value=E}else d.value=PS.createTemplateString(y.value,d)},"getEnvStatementTransformer");var TH="config/routes.json",mcr=["handler/{}/options/*","handler/{}/options/*/[]","policies/[]/{}/handler/{}/options/*","policies/[]/{}/handler/{}/options/*/[]","corsPolicies/[]/{}/*","corsPolicies/[]/{}/*/[]"],hcr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","handler/{}/options/{}/onOpen/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Xct=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],gcr="handler/{}/options/{}/rewritePattern",ycr="handler/{}/options/{}/baseUrl",nle=class extends rle{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(o){this.addedImports.has(o)||this.addedImports.set(o,`__import${this.importCount++}`);let f=this.addedImports.get(o);if(!f)throw new Error("Import name is undefined. This should not happen.");return f}getImports(){let o=[];return this.addedImports.forEach((f,d)=>{o.push({name:f,path:d})}),o}visit(o){this.rewriteHandlerFunction(o),this.rewriteForwardFunction(o),this.replaceImportStatements(o),this.replaceEnvStatements(o)}rewriteHandlerFunction(o){if(!(!WP(o)||!pO(o.value)||typeof o.value.value!="string")&&GP(o,gcr)){if(!o.parent||!H9(o.parent)){this.errors.push(new Uk("Invalid node, expected object",TH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Zct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}rewriteForwardFunction(o){if(!(!WP(o)||!pO(o.value)||typeof o.value.value!="string")&&GP(o,ycr)){if(!o.parent||!H9(o.parent)){this.errors.push(new Uk("Invalid node, expected object",TH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Zct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}replaceImportStatements(o){if(!WP(o)||!pO(o.value))return;let f=o.value.value;if(typeof f!="string")return;if(!hcr.some(R=>GP(o,R))&&!Xct.some(R=>GP(o,R))){if(iIe.test(f)){if(o.name.value==="$ref")return;this.errors.push(new Uk("An $import() statement is not expected at this location.",TH,o.location,f))}return}let d=iIe.exec(f);if(Xct.some(R=>GP(o,R))&&!d)return;if(!d){this.errors.push(new Uk("Invalid $import() statement",TH,o.location,f));return}let y=d[1];y=y.replace(/\\/g,"/"),y.startsWith(".")&&(y=dcr.posix.join("..",y));let E=this.getImportName(y),A={type:qo.Identifier,parent:o.parent,value:E};o.value=A}replaceEnvStatements=Kct(mcr,this.errors,TH)};function Zct(s){return`(request, context) => {
575
+ `),exitCode:E},"Untar process logs")}}t(aZt,"untarFile");async function oZt(s){if(await nAe(s))return await GN.rm(s,{recursive:!0})}t(oZt,"deleteFolder");var nu=iAe;var rlt=R_(Nst(),1);import{AssertionError as Fer}from"node:assert";function $P(s,o){if(s===!1)throw new Fer({message:o})}t($P,"assert");var qo;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.Raw="Raw"})(qo||(qo={}));function H9(s){return s.type===qo.Object}t(H9,"isAstObject");function WP(s){return s.type===qo.Property}t(WP,"isAstProperty");function jAe(s){return s.type===qo.Array}t(jAe,"isAstArray");function pO(s){return s.type===qo.Literal}t(pO,"isAstLiteral");function XN(s){if(s===void 0)throw new Error("Node is undefined");if(!H9(s))throw new Error("Node is not object")}t(XN,"assertAstObject");import{findNodeAtLocation as Ler,getNodeValue as Rer,printParseErrorCode as Mer,visit as jer}from"jsonc-parser";var Ber={DEFAULT:{allowTrailingComma:!1}};function zV(s,o=[],f=Ber.DEFAULT){let d={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(q){d.type==="property"&&(d.length=q-d.offset,d=d.parent)}t(y,"ensurePropertyComplete");function E(q){return d.children?.push(q),q}t(E,"onValue"),jer(s,{onObjectBegin:t((q,K,ve,pe)=>{d=E({type:"object",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onObjectBegin"),onObjectProperty:t((q,K,ve,pe,ae)=>{d=E({type:"property",offset:K,length:-1,line:pe+1,column:ae+1,parent:d,children:[]}),d.children?.push({type:"string",value:q,offset:K,length:ve,line:pe,column:ae,parent:d})},"onObjectProperty"),onObjectEnd:t((q,K)=>{y(q+K),d.length=q+K-d.offset,d=d.parent,y(q+K)},"onObjectEnd"),onArrayBegin:t((q,K,ve,pe)=>{d=E({type:"array",offset:q,length:-1,line:ve+1,column:pe+1,parent:d,children:[]})},"onArrayBegin"),onArrayEnd:t((q,K)=>{d.length=q+K-d.offset,d=d.parent,y(q+K)},"onArrayEnd"),onLiteralValue:t((q,K,ve,pe,ae)=>{E({type:Uer(q),offset:K,length:ve,line:pe+1,column:ae+1,parent:d,value:q}),y(K+ve)},"onLiteralValue"),onSeparator:t((q,K)=>{d.type==="property"&&(q===":"?d.colonOffset=K:q===","&&y(K))},"onSeparator"),onError:t((q,K,ve,pe,ae)=>{o.push({error:q,offset:K,length:ve,line:pe+1,column:ae+1})},"onError")},f);let R=d.children?.[0];return R&&delete R.parent,R}t(zV,"parse");function Uer(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(Uer,"getNodeType");function G9(s,o){return Ler(s,o)}t(G9,"findNodeAtLocation");function JV(s){return Rer(s)}t(JV,"getNodeValue");function Ist(s){return Mer(s)}t(Ist,"printParseErrorCode");var $V=class{static{t(this,"AstAdapter")}parse(o){let d=zV(o,[]);if(d)return this.parseNode(d,void 0);throw new Error("Failed to parse JSON")}convert(o){return this.parseNode(o,void 0)}parseNode(o,f){switch(o.type){case"object":return this.createObject(o,f);case"array":return this.createArray(o,f);case"property":return this.createProperty(o,f);case"string":return this.createLiteral(o,f);case"number":return this.createLiteral(o,f);case"boolean":return this.createLiteral(o,f);case"null":return this.createLiteral(o,f)}}createLiteral(o,f){return{type:qo.Literal,location:{line:o.line,column:o.column},parent:f,value:o.type==="null"?null:o.value}}createObject(o,f){let d={type:qo.Object,children:[],parent:f,location:{line:o.line,column:o.column}};return o.children?.forEach(y=>{d.children.push(this.parseNode(y,d))}),d}createProperty(o,f){$P(o.children?.length===2,"Invalid property node");let d={type:qo.Property,location:{line:o.line,column:o.column},parent:f,name:null,value:null};return d.name={value:o.children[0].value,location:{line:o.line,column:o.column},type:qo.Identifier,parent:d},d.value=this.parseNode(o.children[1],d),d}createArray(o,f){let d={type:qo.Array,location:{line:o.line,column:o.column},parent:f,children:[]};return o.children?.forEach(y=>d.children.push(this.parseNode(y,d))),d}};var PS={createLiteral:t((s,o)=>({type:qo.Literal,parent:o,value:s}),"createLiteral"),createTemplateString:t((s,o)=>({type:qo.TemplateString,parent:o,value:s}),"createTemplateString"),createIdentifier:t((s,o)=>({type:qo.Identifier,value:s,parent:o}),"createIdentifier"),createProperty:t((s,o,f)=>{let d={type:qo.Property,parent:f,name:null,value:o};return d.name={value:s,type:qo.Identifier,parent:d},d.value.parent=d,d},"createProperty"),createArrayOfLiterals:t((s,o)=>{let f={type:qo.Array,parent:o,children:[]};for(let d of s)f.children.push(PS.createLiteral(d,f));return f},"createArrayOfLiterals")};var zer=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,WV=class{static{t(this,"SourceGenerator")}generate(o){let f=[];return this.generateSource(f,o),f.join("")}generateSource(o,f){switch(f.type){case qo.Array:return this.generateArray(o,f);case qo.Object:return this.generateObject(o,f);case qo.Property:return this.generateProperty(o,f);case qo.Literal:return this.generateLiteral(o,f);case qo.FunctionCall:return this.generateFunctionCall(o,f);case qo.Identifier:return this.generateIdentifier(o,f);case qo.Raw:return this.generateRaw(o,f);case qo.TemplateString:return this.generateTemplateString(o,f)}}generateArray(o,f){o.push("["),f.children.map(d=>{this.generateSource(o,d),o.push(",")}),o.push("]")}generateObject(o,f){o.push("{"),f.children.forEach(d=>{this.generateSource(o,d),o.push(",")}),o.push("}")}generateProperty(o,f){this.generateIdentifier(o,f.name),o.push(":"),this.generateSource(o,f.value)}generateFunctionCall(o,f){o.push(f.name.value),o.push("("),f.children.forEach((d,y,E)=>{this.generateSource(o,d),y<E.length&&o.push(",")}),o.push(")")}generateRaw(o,f){o.push(f.value)}generateTemplateString(o,f){o.push("`"),o.push(f.value.replaceAll("`","\\`")),o.push("`")}generateLiteral(o,f){if(f.value===null)return o.push("null");switch(typeof f.value){case"number":case"boolean":return o.push(`${f.value}`);case"string":{let d=f.value,y=JSON.stringify(d);return o.push(`${y}`)}}}generateIdentifier(o,f){let d=zer.test(f.value)?f.value:`'${f.value}'`;o.push(d)}};import Jer from"node:fs/promises";import{parse as $er}from"@swc/core";var Ost=t(async s=>{let o=new Set;try{let f=await Jer.readFile(s,"utf-8");(await $er(f,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?o.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?o.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&o.add(y.declaration.declarations[0].id.value)})}catch{return null}return o},"getJSFileExports");var Fst=["ai-gateway-auth-v2","ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2","ai-gateway-dlp","ai-gateway-fallback-model-v2","ai-gateway-metering-v2","ai-gateway-model-filtering-v2","ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2","ai-gateway-smart-router","akamai-ai-firewall","akamai-ai-firewall-v2","akamai-firewall-for-ai","comet-opik-tracing-v2","galileo-tracing-v2","prompt-injection","semantic-cache"],Lst={"ai-gateway-auth-v2-inbound":"ai-gateway-auth-v2","ai-gateway-configuration-executor-v2-inbound":"ai-gateway-configuration-executor-v2","ai-gateway-configuration-loader-v2-inbound":"ai-gateway-configuration-loader-v2","ai-gateway-dlp-inbound":"ai-gateway-dlp","ai-gateway-fallback-model-v2-inbound":"ai-gateway-fallback-model-v2","ai-gateway-metering-v2-inbound":"ai-gateway-metering-v2","ai-gateway-model-filtering-v2-inbound":"ai-gateway-model-filtering-v2","ai-gateway-semantic-cache-inbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-outbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2-inbound":"ai-gateway-semantic-cache-v2","ai-gateway-smart-router-inbound":"ai-gateway-smart-router","akamai-ai-firewall-v2-inbound":"akamai-ai-firewall-v2","akamai-firewall-for-ai-inbound":"akamai-firewall-for-ai","akamai-firewall-for-ai-outbound":"akamai-firewall-for-ai","comet-opik-tracing-v2-inbound":"comet-opik-tracing-v2","galileo-tracing-v2-inbound":"galileo-tracing-v2","prompt-injection-outbound":"prompt-injection","semantic-cache-inbound":"semantic-cache"};var Rst={$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 BAe={$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 Mst={$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 UAe={$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"],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:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},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 zAe={$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:{},mcp:{oneOf:[{type:"object",additionalProperties:!1,properties:{type:{const:"tool"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"},includeOutputSchema:{type:"boolean"},includeStructuredContent:{type:"boolean"},annotations:{type:"object",additionalProperties:!1,properties:{title:{type:"string"},readOnlyHint:{type:"boolean"},destructiveHint:{type:"boolean"},idempotentHint:{type:"boolean"},openWorldHint:{type:"boolean"}}},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"prompt"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"resource"},name:{type:"string"},description:{type:"string"},uri:{type:"string"},mimeType:{type:"string"},enabled:{type:"boolean"},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"graphql"},enabled:{type:"boolean"},introspectionTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}},executeTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}}},required:["type"]}]},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 Vct=R_(Gce(),1),Hct=R_(Zce(),1);var Qce=class s{static{t(this,"JsonValidator")}static#e=new s;static get instance(){return s.#e}ajv;constructor(){this.ajv=new Vct.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Hct.default)(this.ajv,{mode:"fast"})}addSchema(o,f){this.ajv.addSchema(o,f)}compile(o){let f=this.ajv.compile(o);return t(y=>({isValid:f(y),errors:this.toSimpleErrors(f.errors,y),warnings:[]}),"validator")}toSimpleErrors(o,f){let d=[];return o?.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 E={details:{}},A=y.instancePath.split("/");if(A.length>2){let q=A[1],K=A[2]?parseInt(A[2],10):0,ve=A[3],pe=Number.isNaN(K)?void 0:f[q][K][ve];E={details:{property:q,index:K,field:ve,fieldValue:pe}}}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 q=y.instancePath.split("/"),K=q[q.length-1];y.message=`Value of property '${K}' must be '${y.params.type}'`}let R=Object.assign(y,E);d.push(R)}),d}};var oI=Qce.instance;oI.addSchema(UAe,"route-configuration.schema.json");oI.addSchema(Mst,"policy-configuration.schema.json");oI.addSchema(BAe,"policies.schema.json");oI.addSchema(zAe,"open-api-route-configuration.schema.json");oI.addSchema(Rst,"fragments.schema.json");var y6r=oI.compile(UAe),Gct=oI.compile(zAe),nIe=oI.compile(BAe);var ele=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(o){return this.results=nIe(o),this.results}};var tle=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(o){return this.results=Gct(o),this.results}};import dcr from"node:path";var iIe=/\$import\((.*)\)/,SH=/\$env\((.*?)\)/g;var Uk=class extends Error{static{t(this,"CodeGenError")}location;constructor(o,f,d,y){super(o),this.location={file:f,namespace:"",line:d?d.line:0,column:d?d.column:0,length:0,lineText:y??"",suggestion:""}}},pcr=t(s=>{let o=[],f=s;for(;f.parent;)o.push(f),f=f.parent;return o.reverse()},"invertTree"),GP=t((s,o)=>{if(!s)return!1;let f=pcr(s);return o.split("/").every((E,A)=>{let R=f[A];return R?E==="*"||WP(R)&&R.name.value===E?!0:E==="{}"?R.type===qo.Object:E==="[]"?R.type===qo.Array:!1:!1})},"testPosition");var rle=class{static{t(this,"AstTransformer")}errors=[];transform(o){return this.visitor(o),o}visitor(o){this.visit(o),H9(o)?o.children.forEach(f=>{this.visitor(f)}):jAe(o)?o.children.forEach(f=>{this.visitor(f)}):WP(o)&&this.visitor(o.value)}},Yct=t(s=>{let o=new RegExp(SH).exec(s);if(o?.length===2&&o[0]===s)return{type:"raw",value:`environment["${o[1]}"]`};{let f=s.replaceAll(new RegExp(SH),(d,y)=>`\${environment["${y}"] ? environment["${y}"] : ""}`);if(f!==s)return{type:"template",value:f}}return null},"replaceEnvInString"),Kct=t((s,o,f)=>d=>{if(pO(d)&&typeof d.value=="string"&&d.parent&&jAe(d.parent)){if(!s.some(A=>GP(d.parent,A))){SH.test(d.value)&&o.push(new Uk("An $env() statement is not expected at this location.",f,d.location,d.value));return}let E=Yct(d.value);if(E){let A=d.parent,R=A.children.indexOf(d);if(R!==-1)if(E.type==="raw"){let q={type:qo.Raw,parent:A,value:E.value};A.children[R]=q}else A.children[R]=PS.createTemplateString(E.value,d)}return}if(!WP(d)||!pO(d.value)||typeof d.value.value!="string")return;if(!s.some(E=>GP(d,E))){SH.test(d.value.value)&&o.push(new Uk("An $env() statement is not expected at this location.",f,d.location,d.value.value));return}let y=Yct(d.value.value);if(y)if(y.type==="raw"){let E={type:qo.Raw,parent:null,value:y.value};d.value=E}else d.value=PS.createTemplateString(y.value,d)},"getEnvStatementTransformer");var TH="config/routes.json",mcr=["handler/{}/options/*","handler/{}/options/*/[]","policies/[]/{}/handler/{}/options/*","policies/[]/{}/handler/{}/options/*/[]","corsPolicies/[]/{}/*","corsPolicies/[]/{}/*/[]"],hcr=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","handler/{}/options/{}/onOpen/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Xct=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],gcr="handler/{}/options/{}/rewritePattern",ycr="handler/{}/options/{}/baseUrl",nle=class extends rle{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(o){this.addedImports.has(o)||this.addedImports.set(o,`__import${this.importCount++}`);let f=this.addedImports.get(o);if(!f)throw new Error("Import name is undefined. This should not happen.");return f}getImports(){let o=[];return this.addedImports.forEach((f,d)=>{o.push({name:f,path:d})}),o}visit(o){this.rewriteHandlerFunction(o),this.rewriteForwardFunction(o),this.replaceImportStatements(o),this.replaceEnvStatements(o)}rewriteHandlerFunction(o){if(!(!WP(o)||!pO(o.value)||typeof o.value.value!="string")&&GP(o,gcr)){if(!o.parent||!H9(o.parent)){this.errors.push(new Uk("Invalid node, expected object",TH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Zct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}rewriteForwardFunction(o){if(!(!WP(o)||!pO(o.value)||typeof o.value.value!="string")&&GP(o,ycr)){if(!o.parent||!H9(o.parent)){this.errors.push(new Uk("Invalid node, expected object",TH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Zct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}replaceImportStatements(o){if(!WP(o)||!pO(o.value))return;let f=o.value.value;if(typeof f!="string")return;if(!hcr.some(R=>GP(o,R))&&!Xct.some(R=>GP(o,R))){if(iIe.test(f)){if(o.name.value==="$ref")return;this.errors.push(new Uk("An $import() statement is not expected at this location.",TH,o.location,f))}return}let d=iIe.exec(f);if(Xct.some(R=>GP(o,R))&&!d)return;if(!d){this.errors.push(new Uk("Invalid $import() statement",TH,o.location,f));return}let y=d[1];y=y.replace(/\\/g,"/"),y.startsWith(".")&&(y=dcr.posix.join("..",y));let E=this.getImportName(y),A={type:qo.Identifier,parent:o.parent,value:E};o.value=A}replaceEnvStatements=Kct(mcr,this.errors,TH)};function Zct(s){return`(request, context) => {
576
576
  const { params, url, query, method, headers } = request;
577
577
  const { host, hostname, origin, pathname, port, search } = new URL(url);
578
578
  const e = encodeURIComponent;
@@ -596,7 +596,7 @@ globstar while`,s,pe,o,ae,rt),this.matchOne(s.slice(pe),o.slice(ae),f))return th
596
596
  };
597
597
  }
598
598
  export default routes;
599
- `),Scr=["2023-03-14","2024-01-15","2024-03-14","2024-09-02"];function nlt(s){return!s||Scr.includes(s)}t(nlt,"isLegacyPathBehavior");function Tcr(s){let o=globalThis.URLPattern;if(!o)throw new Error("Native URLPattern is unavailable. Run the build with Node.js 24 or later.");return new o({pathname:s})}t(Tcr,"createNativeURLPattern");function oIe(s){let o="",f=0,d=!1;for(let y=0;y<s.length;y++){let E=s[y];if(E==="\\"){o+=E,y+1<s.length&&(o+=s[++y]);continue}!d&&E==="("?f++:!d&&E===")"&&f>0?f--:f>0&&E==="["?d=!0:d&&E==="]"&&(d=!1),E==="/"&&f>0&&(o+="\\"),o+=E}return o}t(oIe,"normalizeUrlPatternForNative");async function cIe(s){try{let{content:o,warnings:f}=await xcr(s);return{content:o,errors:[],warnings:f}}catch(o){if(o instanceof ky)return o.toBuildResult();throw o}}t(cIe,"compileRoutes");async function xcr({sourceDirectory:s,policiesContent:o,oasContent:f,compatibilityDate:d,allowDuplicateRoutes:y,isAiEnabled:E}){let A=[],R=[],q=new nle,K=new WV,{policiesNode:ve,policiesData:pe}=wcr(o);E===!1&&kcr(pe);let{generatedPolicies:ae,policyNames:rt}=Dcr(q,K,ve,pe),{generatedCorsPolicies:ze,corsPoliciesNames:je}=Pcr(q,K,ve,pe),Bt=Acr(s,f),Ut=[],Or=new Map,Jn=new Map;for(let br of Bt){let{node:js,oas:Ni,oasProjectRelativePath:jo}=br,ji=G9(js,["paths"]);if(!ji)continue;let Op=ale.basename(Ni.fileName,".oas.json"),ed,Ln=t(()=>(ed??=Bcr(js),ed),"getDefaultRewriteServer");for(let Fh of ji.children??[])if(Fh.children){let cl=Rcr(Fh),wr=cl[Qct]?.pathMode;if(wr){if(wr!==ile&&wr!==aIe)throw new ky({text:`Unknown path mode ${wr}`,location:{line:0,column:0,file:jo}})}else wr=ile;for(let[JE,gl]of Object.entries(cl)){if(!sle(JE))continue;let j_=JE,va=j_.split(/,/).map(Lh=>Lh.trim().toUpperCase()),NT=gl,ob=NT[sIe];if(ob){let Oi=new tle().validate(ob);if(Oi.isValid){let Fp=elt(Fh);if(!Or.has(Fp)&&(Or.set(Fp,new Set),nlt(d)))try{Tcr(oIe(Fp))}catch{R.push({text:`Path '${Fp}' contains invalid characters. The value must be a valid URLPattern.`,location:{line:Fh.line,column:Fh.column,file:jo}})}if(!y){let m7=Or.get(Fp);va.forEach(Tt=>{m7.has(Tt)?R.push({text:`Cannot have duplicate routes declared. Route '${Tt.toUpperCase()} ${Fp}' declared more than once.`,location:{line:Fh.line,column:Fh.column,file:jo}}):m7.add(Tt)})}let FS=Mcr(Fh,[Fp,j_,sIe]),Ug=jcr(FS),oA=await Jcr(FS,Ug,Ni,Jn);if(!oA.valid)throw new ky({text:oA.errorMsg??`Unknown error on handler for path '${Fp}'`,location:{line:oA.line??0,column:oA.column??0,file:jo}});let nw=Wcr(FS,Ug,jo);if(!nw.valid)throw new ky(nw.errors);nw.warnings&&A.push(...nw.warnings),Ut.push({path:Fp,pathPattern:Fp,pathMode:wr,httpMethods:va,rawOperation:j_,rawOpenAPI:NT,oasFileName:Op,oasProjectRelativePath:jo,config:FS})}else throw new ky({text:JSON.stringify(Oi.errors),location:{line:0,column:0,file:jo}})}else{let Lh=elt(Fh),Oi={corsPolicy:"none",handler:Ucr(Lh,Ln())};Ut.push({path:Lh,pathPattern:Lh,pathMode:ile,rawOpenAPI:NT,oasFileName:Op,oasProjectRelativePath:jo,httpMethods:va,rawOperation:j_,config:zV(JSON.stringify(Oi))})}if(ob&&"policies"in ob){let Lh=ob.policies;Lh.inbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}),Lh.outbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})})}if(R.length>0)throw new ky(R);let wj=["none","anything-goes"];if(ob&&"corsPolicy"in ob){let Lh=ob.corsPolicy;if(wj.includes(Lh))continue;je.includes(Lh)||R.push({text:`Cors policy '${Lh}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}}}if(R.length>0)throw new ky(R)}let _n=[];for(let br of Ut){let js=new $V().convert(br.config);Ncr(js,br),Icr(js,br,d),Ocr(js,br),Fcr(js,br),Lcr(js,br);let Ni=q.transform(js),jo=q.errors;if(jo.length>0)throw new ky({text:JSON.stringify(jo),location:{line:0,column:0,file:br.oasProjectRelativePath}});let Op=new WV().generate(Ni);_n.push(Op)}if($P(Bt.length===f.length,"Tree length should match OAS file length"),$P(Ut.length===_n.length,`The number of validated nodes should match the number of generated fragments. There were ${Ut.length} validated nodes and ${_n.length} generated fragments.`),R.length>0)throw new ky(R);let Wn={routes:_n,imports:q.getImports(),policies:ae,corsPolicies:ze};return{content:bcr(Wn),warnings:A}}t(xcr,"generateSourceCode");var Ecr=0,Ccr=1;function kcr(s){let o=new Set([...Fst,...Object.keys(Lst)]),f=(s.policies??[]).filter(y=>y?.policyType&&o.has(y.policyType)).map(y=>`'${y.name}' (policyType: ${y.policyType})`);if(f.length===0)return;let d=f.join(", ");throw new ky({text:`AI capabilities are disabled for this account, so AI-powered policies cannot be used. Remove ${d} from policies.json or ask an account admin to enable AI capabilities in account settings.`,location:{line:0,column:0,file:"/config/policies.json"}})}t(kcr,"assertNoAiPoliciesUsed");function wcr(s){let o=new ele,f=JSON.parse(s.content),d=o.validate(f);if(!d.isValid)throw new ky({text:JSON.stringify(d.errors),location:{line:0,column:0,file:"/config/policies.json"}});let y=new $V().parse(JSON.stringify(f));return{policiesData:f,policiesNode:y}}t(wcr,"getPolicyData");function Dcr(s,o,f,d){let y=[],E;XN(f);let A=f.children.find(R=>R.name.value==="policies");if(A){let R=s.transform(A);E=o.generate(R),y=d.policies.map(({name:q})=>q)}else E="policies: []";return{generatedPolicies:E,policyNames:y}}t(Dcr,"generatePolicies");function Pcr(s,o,f,d){let y,E;XN(f);let A=f.children.find(R=>R.name.value==="corsPolicies");if(A){let R=s.transform(A);E=o.generate(R),y=d.corsPolicies.map(({name:q})=>q)}else E="corsPolicies: []",y=[];return{generatedCorsPolicies:E,corsPoliciesNames:y}}t(Pcr,"generateCorsPolicies");function Acr(s,o){let f=[];for(let d of o){let y=[],E=zV(d.content,y),A=`./${ale.posix.relative(s.replace(/\\/g,"/"),d.fileName.replace(/\\/g,"/"))}`;if(y.length>0)throw new ky(y.map(R=>({text:Ist(R.error),location:{file:A,line:R.line,column:R.column}})));if(!E)throw new ky({text:"Error parsing the OpenAPI file. Check the contents of the file.",location:{file:A,line:0,column:0}});f.push({node:E,oas:d,oasProjectRelativePath:A})}return f}t(Acr,"getOasTrees");function Ncr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"path",type:qo.Identifier,parent:f},f.value=PS.createLiteral(o.path,f),XN(s),s.children.unshift(f)}t(Ncr,"embellishWithPath");function Icr(s,o,f){let d={type:qo.Property,parent:s,name:null,value:null};if(d.name={value:"pathPattern",type:qo.Identifier,parent:d},o.pathMode===aIe)d.value=PS.createLiteral(oIe(o.path),d);else{let y=/{(\S+?)}/gm,A=nlt(f)?o.path:o.path.replace(/([*+?()[\].|^$\\:])/g,"\\$1");A=A.replace(y,":$1"),A=oIe(A),o.path.endsWith("/")||(A=`${A}{/}?`),d.value=PS.createLiteral(A,d)}XN(s),s.children.unshift(d)}t(Icr,"embellishWithPathPattern");function Ocr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"methods",type:qo.Identifier,parent:f},f.value=PS.createArrayOfLiterals(o.httpMethods,f),XN(s),s.children.unshift(f)}t(Ocr,"embellishWithMethods");function Fcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"raw",type:qo.Identifier,parent:s};let d=DV(o.oasFileName,o.path,o.rawOperation);f.value={type:qo.Raw,parent:f,value:`() => {return rawRouteData.${d};}`},XN(s),s.children.unshift(f)}t(Fcr,"embellishWithRawOpenApi");function Lcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"metadata",type:qo.Identifier,parent:s};let d={type:qo.Property,parent:f,name:null,value:null};d.name={value:"filepath",type:qo.Identifier,parent:d},d.value=PS.createLiteral(o.oasProjectRelativePath,d),f.value={type:qo.Object,parent:f,children:[d]},XN(s),s.children.unshift(f)}t(Lcr,"embellishWithMetadata");function Rcr(s){return $P(s.type==="property"),$P(Array.isArray(s.children)),JV(s.children[Ccr])}t(Rcr,"evaluatePathItem");function elt(s){return $P(s.type==="property"),$P(Array.isArray(s.children)),JV(s.children[Ecr])}t(elt,"evaluatePath");function Mcr(s,o){return G9(s.parent,o)}t(Mcr,"extractZuploRouteNode");function jcr(s){return JV(s)}t(jcr,"evaluateZuploRouteNode");function Bcr(s){let o;if(s.type==="object")for(let d of s.children??[]){let y=d.children?.[1];y&&d.children?.[0]?.value==="servers"&&(o=y)}let f=o?JV(o):void 0;return`${f&&f.length>0?f[0].url:"http://example.com"}`}t(Bcr,"resolveDefaultRewriteServer");function Ucr(s,o){let f=/{(\S+?)}/gm,y=s.replace(f,"${params.$1}");return{export:"urlRewriteHandler",module:"$import(@zuplo/runtime)",options:{rewritePattern:`${o}${y}`,forwardSearch:!0}}}t(Ucr,"addDefaultUrlRewriteHandler");async function zcr(s,o){if(o.has(s))return o.get(s);let f=await Ost(s);return o.set(s,f),f}t(zcr,"getJSFileExportsCached");async function Jcr(s,o,f,d){let y=o.handler.module.replace(/^\$import\(/,"").replace(/\)$/,""),E=ale.join(ale.dirname(f.fileName),"..",`${y}.ts`),A=o.handler.export;if(y==="@zuplo/runtime"||y.startsWith("@zuplo/runtime/"))return{valid:!0};if(await nu.fileExists(E)){let R=await zcr(E,d);if(R===null)return{valid:!1,errorMsg:`Could not find any export due to a compile error in '${nu.getParentDirFilename(E)}'`};if(!R.has(A)){let q=`Could not find export "${A}" in '${nu.getParentDirFilename(E)}'`,K=0,ve=0;if(s.children)for(let pe of s.children)pe.children&&pe.children.forEach(ae=>{ae.value==="handler"&&(K=ae.line,ve=ae.column)});return{valid:!1,errorMsg:q,line:K,column:ve}}return{valid:!0}}else return{valid:!1,errorMsg:`Could not find module '${y}'`}}t(Jcr,"checkModuleIsValid");var tlt=t((s,o)=>{let f=G9(s,["handler","options",o])??G9(s,["handler","options"])??G9(s,["handler"]);return f?{line:f.line,column:f.column-1}:{line:0,column:0}},"getHandlerOptionLocation"),$cr="$env(";function Wcr(s,o,f){let d=o.handler.export;if(d!=="urlForwardHandler"&&d!=="urlRewriteHandler")return{valid:!0};let y="rewritePattern";d==="urlForwardHandler"&&(y="baseUrl");let E=o.handler.options?.[y];if(!E){let A=tlt(s,y);return{valid:!1,errors:[{text:`Invalid request handler configuration. handler.options.${y} is required but was not provided.`,location:{file:f,line:A.line,column:A.column}}]}}if(E.includes($cr)){let A=tlt(s,y);return{valid:!0,warnings:[{text:`Invalid environment variable access syntax detected. Use \${env.VAR_NAME} instead of $env(VAR_NAME) for handler.options.${y}.`,location:{file:f,line:A.line,column:A.column}}]}}return{valid:!0}}t(Wcr,"checkHandlerIsValid");var UH=R_(x4e(),1);import{readFile as Ipr}from"node:fs/promises";var TT=R_(x4e(),1);var OO=class extends Error{static{t(this,"CustomResolveError")}},pI=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(o,f){this.sourceDirectory=o,this.logger=f}dereference(o,f){return UH.$RefParser.dereference(o,{resolve:{json:!0,file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:f?.onDereference}})}bundle(o){return UH.$RefParser.bundle(o,{resolve:{file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(o){return UH.$RefParser.parse(o,{resolve:{file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(o){return UH.$RefParser.resolve(o,{resolve:{file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function Ole(s,o){return{order:100,canRead(f){let d=Rpr(f.url);if(!(d===void 0||d==="file"))return!1;let E;try{E=Oft(f.url)}catch(A){throw new OO(`Malformed URI: ${f.url}`,{cause:A})}try{nu.safePath(s).resolve(E)}catch(A){return o?.warn(A),!1}return!0},async read(f){let d;try{d=Oft(f.url)}catch(y){throw new OO(`Malformed URI: ${f.url}`,{cause:y})}try{return await Ipr(d)}catch(y){throw new OO(`Error opening file "${d}"`,{cause:y})}}}}t(Ole,"customResolver");var Opr=/\//g,Fpr=/^(\w{2,}):\/\//i;function Lpr(){return/^win/.test(globalThis.process?globalThis.process.platform:"")}t(Lpr,"isWindowsPlatform");var E4e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function Rpr(s){let o=Fpr.exec(s);if(o)return o[1].toLowerCase()}t(Rpr,"getProtocol");function Oft(s,o){let f=Lpr();s=decodeURI(s);for(let y=0;y<E4e.length;y+=2)s=s.replace(E4e[y],E4e[y+1]);let d=s.substr(0,7).toLowerCase()==="file://";if(d&&(s=s[7]==="/"?s.substr(8):s.substr(7),f&&s[1]==="/"&&(s=`${s[0]}:${s.substr(1)}`),o?s=`file:///${s}`:(d=!1,s=f?s:`/${s}`)),!d){let y=s.split(f?"\\":"/"),E=[];for(let A of y)A===".."?E.length&&E[E.length-1]!==""&&E.pop():(A!==""||E.length===0)&&E.push(A);s=E.join(f?"\\":"/"),!f&&E[0]===""&&(s=`/${s.substring(1)}`)}return f&&!d&&(s=s.replace(Opr,"\\"),s.substr(1,2)===":\\"&&(s=s[0].toUpperCase()+s.substr(1))),s}t(Oft,"toFileSystemPath");var Fft="YOUR_KEY_HERE";async function Lft(s){let f=await new pI(s.sourceDirectory,s.logger).bundle(s.openApiDocPath),d=s.openApiDocPath.replace(s.sourceDirectory,"");return Mpr({...s,relativeOpenApiPath:d},f)}t(Lft,"buildPublicOpenApiFile");async function Mpr(s,o){zpr({relativeOpenApiPath:s.relativeOpenApiPath},o);let f=o;return f=Bpr(f),jpr(f,s.urls?.api?.defaultUrl),f=Upr(f,s),Rft(f,"x-zuplo"),f}t(Mpr,"buildRawOpenApiFile");function jpr(s,o){o?s.servers=[{url:o}]:s.servers=[]}t(jpr,"addServerHost");function Bpr(s){if(!s.paths)return s;let{components:o}=s,f=o?{...o}:void 0,d=[];f&&f.parameters&&(d=Object.entries(f.parameters).reduce((E,[A,R])=>(O9 in R&&Yae(R[O9])&&(E.push(A),f.parameters&&delete f.parameters[A]),E),[]));let y=Object.entries(s.paths).reduce((E,[A,R])=>{if(!R)return E;let q={...R},K=["delete","get","head","patch","post","put","trace","options"];return K.forEach(ve=>{let pe=R[ve];if(!pe)return;if(Yae(pe[O9])){delete q[ve];return}let{parameters:ae}=pe;if(!ae)return;let rt=ae.filter(ze=>{if(O9 in ze&&Yae(ze[O9]))return!1;if("$ref"in ze){let je=ze.$ref.split("/").pop();return je?!d.includes(je):!0}return!0});q[ve]={...pe,parameters:rt}}),K.some(ve=>!!q[ve])&&(E[A]=q),E},{});return{...s,paths:y,components:f}}t(Bpr,"removeHiddenRoutesAndParams");function Upr(s,{policiesConfig:o}){if(!s.paths)return s;let f=Object.entries(s.paths).reduce((d,[y,E])=>{if(!E)return d;let A={...E};return[A.delete,A.get,A.head,A.patch,A.post,A.put,A.trace,A.options].forEach(R=>{if(!R)return;let q=R["x-zuplo-route"]?.policies?.inbound?.reduce((pe,ae)=>{let rt=o.policies?.find(({name:Bt})=>Bt===ae);if(!rt)return pe;if(!(rt.handler.export==="CompositeInboundPolicy"))return pe.concat(ae);let je=rt.handler.options?.policies;return je?pe.concat(je):pe},[]),K=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="ApiAuthKeyInboundPolicy"||ae.handler.export==="ApiKeyInboundPolicy")&&!ae.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&K.push(ae)})}),K.length>0){let pe=K.length>0&&K[0].handler&&K[0].handler.options&&K[0].handler.options.authHeader?K[0].handler.options.authHeader:"Authorization",ae=K.length>0&&K[0].handler&&K[0].handler.options&&(K[0].handler.options.authScheme||K[0].handler.options.authScheme==="")?K[0].handler.options.authScheme:"Bearer",rt=ae!==""?`${ae} ${Fft}`:Fft,ze={name:pe,in:"header",required:!0,example:rt,schema:{type:"string"},description:`The \`${pe}\` header is used to authenticate with the API using your API key. Value is of the format \`${rt}\`.`};R.parameters?R.parameters.some(Or=>"name"in Or&&Or.name===ze.name)||R.parameters.unshift(ze):R.parameters=[ze];let je={type:"http",scheme:ae.toLowerCase()},Bt="api_key";s.components?.securitySchemes?Object.values(s.components?.securitySchemes).some(Or=>"name"in Or&&Or.type==="apiKey"||"type"in Or&&Or.type==="http"&&Or.scheme===ae)||(s.components.securitySchemes={...s.components.securitySchemes,[Bt]:je}):(s.components||(s.components={}),s.components.securitySchemes={[Bt]:je});let Ut={[Bt]:[]};R.security?R.security.some(Or=>Or[Bt]!==void 0)||R.security.unshift(Ut):R.security=[Ut]}let ve=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="RateLimitInboundPolicy"||ae.handler.export==="ComplexRateLimitInboundPolicy")&&ve.push(ae)})}),ve.length>0){let pe={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},ae={...pe,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};s.components?.responses||s.components||(s.components={}),s.components.responses={...s.components.responses,RateLimitNoRetryAfter:pe,RateLimitWithRetryAfter:ae},R.responses||(R.responses={});let rt=ve.some(ze=>ze.handler.options?.headerMode!=="none");R.responses[429]||(R.responses[429]={$ref:rt?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),d[y]=A,d},{});return{...s,paths:f}}t(Upr,"enrichSpecWithZuploData");function Rft(s,o){for(let f in s)f.startsWith(o)?delete s[f]:typeof s[f]=="object"&&Rft(s[f],o)}t(Rft,"removePropertiesByPrefix");function zpr({relativeOpenApiPath:s},o){if(!o||typeof o!="object")throw new D1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in o)||typeof o.info!="object"||!o.info)throw new D1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in o.info)||typeof o.info.title!="string")throw new D1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(zpr,"assertIsZuploOpenApiSpec");import Gpr from"node:fs/promises";import Ypr from"node:path";var{stringify:Jpr}=JSON;if(!String.prototype.repeat)throw new Error("String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation");if(!String.prototype.endsWith)throw new Error("String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation");var Fle={"||":2,"??":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},ME=17,$pr={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:ME,ClassExpression:ME,FunctionExpression:ME,ObjectExpression:ME,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function NM(s,o){let{generator:f}=s;if(s.write("("),o!=null&&o.length>0){f[o[0].type](o[0],s);let{length:d}=o;for(let y=1;y<d;y++){let E=o[y];s.write(", "),f[E.type](E,s)}}s.write(")")}t(NM,"formatSequence");function $ft(s,o,f,d){let y=s.expressionsPrecedence[o.type];if(y===ME)return!0;let E=s.expressionsPrecedence[f.type];return y!==E?!d&&y===15&&E===14&&f.operator==="**"||y<E:y!==13&&y!==14?!1:o.operator==="**"&&f.operator==="**"?!d:y===13&&E===13&&(o.operator==="??"||f.operator==="??")?!0:d?Fle[o.operator]<=Fle[f.operator]:Fle[o.operator]<Fle[f.operator]}t($ft,"expressionNeedsParenthesis");function Lle(s,o,f,d){let{generator:y}=s;$ft(s,o,f,d)?(s.write("("),y[o.type](o,s),s.write(")")):y[o.type](o,s)}t(Lle,"formatExpression");function Wpr(s,o,f,d){let y=o.split(`
599
+ `),Scr=["2023-03-14","2024-01-15","2024-03-14","2024-09-02"];function nlt(s){return!s||Scr.includes(s)}t(nlt,"isLegacyPathBehavior");function Tcr(s){let o=globalThis.URLPattern;if(typeof o!="function")throw new Error("Native URLPattern is unavailable. Run the build with Node.js 24 or later.");return new o({pathname:s})}t(Tcr,"createNativeURLPattern");function oIe(s){let o="",f=0,d=!1;for(let y=0;y<s.length;y++){let E=s[y];if(E==="\\"){o+=E,y+1<s.length&&(o+=s[++y]);continue}!d&&E==="("?f++:!d&&E===")"&&f>0?f--:f>0&&E==="["?d=!0:d&&E==="]"&&(d=!1),E==="/"&&f>0&&(o+="\\"),o+=E}return o}t(oIe,"normalizeUrlPatternForNative");async function cIe(s){try{let{content:o,warnings:f}=await xcr(s);return{content:o,errors:[],warnings:f}}catch(o){if(o instanceof ky)return o.toBuildResult();throw o}}t(cIe,"compileRoutes");async function xcr({sourceDirectory:s,policiesContent:o,oasContent:f,compatibilityDate:d,allowDuplicateRoutes:y,isAiEnabled:E}){let A=[],R=[],q=new nle,K=new WV,{policiesNode:ve,policiesData:pe}=wcr(o);E===!1&&kcr(pe);let{generatedPolicies:ae,policyNames:rt}=Dcr(q,K,ve,pe),{generatedCorsPolicies:ze,corsPoliciesNames:je}=Pcr(q,K,ve,pe),Bt=Acr(s,f),Ut=[],Or=new Map,Jn=new Map;for(let br of Bt){let{node:js,oas:Ni,oasProjectRelativePath:jo}=br,ji=G9(js,["paths"]);if(!ji)continue;let Op=ale.basename(Ni.fileName,".oas.json"),ed,Ln=t(()=>(ed??=Bcr(js),ed),"getDefaultRewriteServer");for(let Fh of ji.children??[])if(Fh.children){let cl=Rcr(Fh),wr=cl[Qct]?.pathMode;if(wr){if(wr!==ile&&wr!==aIe)throw new ky({text:`Unknown path mode ${wr}`,location:{line:0,column:0,file:jo}})}else wr=ile;for(let[JE,gl]of Object.entries(cl)){if(!sle(JE))continue;let j_=JE,va=j_.split(/,/).map(Lh=>Lh.trim().toUpperCase()),NT=gl,ob=NT[sIe];if(ob){let Oi=new tle().validate(ob);if(Oi.isValid){let Fp=elt(Fh);if(!Or.has(Fp)&&(Or.set(Fp,new Set),nlt(d)))try{Tcr(oIe(Fp))}catch{R.push({text:`Path '${Fp}' contains invalid characters. The value must be a valid URLPattern.`,location:{line:Fh.line,column:Fh.column,file:jo}})}if(!y){let m7=Or.get(Fp);va.forEach(Tt=>{m7.has(Tt)?R.push({text:`Cannot have duplicate routes declared. Route '${Tt.toUpperCase()} ${Fp}' declared more than once.`,location:{line:Fh.line,column:Fh.column,file:jo}}):m7.add(Tt)})}let FS=Mcr(Fh,[Fp,j_,sIe]),Ug=jcr(FS),oA=await Jcr(FS,Ug,Ni,Jn);if(!oA.valid)throw new ky({text:oA.errorMsg??`Unknown error on handler for path '${Fp}'`,location:{line:oA.line??0,column:oA.column??0,file:jo}});let nw=Wcr(FS,Ug,jo);if(!nw.valid)throw new ky(nw.errors);nw.warnings&&A.push(...nw.warnings),Ut.push({path:Fp,pathPattern:Fp,pathMode:wr,httpMethods:va,rawOperation:j_,rawOpenAPI:NT,oasFileName:Op,oasProjectRelativePath:jo,config:FS})}else throw new ky({text:JSON.stringify(Oi.errors),location:{line:0,column:0,file:jo}})}else{let Lh=elt(Fh),Oi={corsPolicy:"none",handler:Ucr(Lh,Ln())};Ut.push({path:Lh,pathPattern:Lh,pathMode:ile,rawOpenAPI:NT,oasFileName:Op,oasProjectRelativePath:jo,httpMethods:va,rawOperation:j_,config:zV(JSON.stringify(Oi))})}if(ob&&"policies"in ob){let Lh=ob.policies;Lh.inbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}),Lh.outbound?.forEach(Oi=>{rt.includes(Oi)||R.push({text:`Policy '${Oi}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})})}if(R.length>0)throw new ky(R);let wj=["none","anything-goes"];if(ob&&"corsPolicy"in ob){let Lh=ob.corsPolicy;if(wj.includes(Lh))continue;je.includes(Lh)||R.push({text:`Cors policy '${Lh}' does not exist in policies.json. Please add it and rebuild.`,location:{line:cl.line,column:cl.column,file:jo}})}}}if(R.length>0)throw new ky(R)}let _n=[];for(let br of Ut){let js=new $V().convert(br.config);Ncr(js,br),Icr(js,br,d),Ocr(js,br),Fcr(js,br),Lcr(js,br);let Ni=q.transform(js),jo=q.errors;if(jo.length>0)throw new ky({text:JSON.stringify(jo),location:{line:0,column:0,file:br.oasProjectRelativePath}});let Op=new WV().generate(Ni);_n.push(Op)}if($P(Bt.length===f.length,"Tree length should match OAS file length"),$P(Ut.length===_n.length,`The number of validated nodes should match the number of generated fragments. There were ${Ut.length} validated nodes and ${_n.length} generated fragments.`),R.length>0)throw new ky(R);let Wn={routes:_n,imports:q.getImports(),policies:ae,corsPolicies:ze};return{content:bcr(Wn),warnings:A}}t(xcr,"generateSourceCode");var Ecr=0,Ccr=1;function kcr(s){let o=new Set([...Fst,...Object.keys(Lst)]),f=(s.policies??[]).filter(y=>y?.policyType&&o.has(y.policyType)).map(y=>`'${y.name}' (policyType: ${y.policyType})`);if(f.length===0)return;let d=f.join(", ");throw new ky({text:`AI capabilities are disabled for this account, so AI-powered policies cannot be used. Remove ${d} from policies.json or ask an account admin to enable AI capabilities in account settings.`,location:{line:0,column:0,file:"/config/policies.json"}})}t(kcr,"assertNoAiPoliciesUsed");function wcr(s){let o=new ele,f=JSON.parse(s.content),d=o.validate(f);if(!d.isValid)throw new ky({text:JSON.stringify(d.errors),location:{line:0,column:0,file:"/config/policies.json"}});let y=new $V().parse(JSON.stringify(f));return{policiesData:f,policiesNode:y}}t(wcr,"getPolicyData");function Dcr(s,o,f,d){let y=[],E;XN(f);let A=f.children.find(R=>R.name.value==="policies");if(A){let R=s.transform(A);E=o.generate(R),y=d.policies.map(({name:q})=>q)}else E="policies: []";return{generatedPolicies:E,policyNames:y}}t(Dcr,"generatePolicies");function Pcr(s,o,f,d){let y,E;XN(f);let A=f.children.find(R=>R.name.value==="corsPolicies");if(A){let R=s.transform(A);E=o.generate(R),y=d.corsPolicies.map(({name:q})=>q)}else E="corsPolicies: []",y=[];return{generatedCorsPolicies:E,corsPoliciesNames:y}}t(Pcr,"generateCorsPolicies");function Acr(s,o){let f=[];for(let d of o){let y=[],E=zV(d.content,y),A=`./${ale.posix.relative(s.replace(/\\/g,"/"),d.fileName.replace(/\\/g,"/"))}`;if(y.length>0)throw new ky(y.map(R=>({text:Ist(R.error),location:{file:A,line:R.line,column:R.column}})));if(!E)throw new ky({text:"Error parsing the OpenAPI file. Check the contents of the file.",location:{file:A,line:0,column:0}});f.push({node:E,oas:d,oasProjectRelativePath:A})}return f}t(Acr,"getOasTrees");function Ncr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"path",type:qo.Identifier,parent:f},f.value=PS.createLiteral(o.path,f),XN(s),s.children.unshift(f)}t(Ncr,"embellishWithPath");function Icr(s,o,f){let d={type:qo.Property,parent:s,name:null,value:null};if(d.name={value:"pathPattern",type:qo.Identifier,parent:d},o.pathMode===aIe)d.value=PS.createLiteral(oIe(o.path),d);else{let y=/{(\S+?)}/gm,A=nlt(f)?o.path:o.path.replace(/([*+?()[\].|^$\\:])/g,"\\$1");A=A.replace(y,":$1"),A=oIe(A),o.path.endsWith("/")||(A=`${A}{/}?`),d.value=PS.createLiteral(A,d)}XN(s),s.children.unshift(d)}t(Icr,"embellishWithPathPattern");function Ocr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"methods",type:qo.Identifier,parent:f},f.value=PS.createArrayOfLiterals(o.httpMethods,f),XN(s),s.children.unshift(f)}t(Ocr,"embellishWithMethods");function Fcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"raw",type:qo.Identifier,parent:s};let d=DV(o.oasFileName,o.path,o.rawOperation);f.value={type:qo.Raw,parent:f,value:`() => {return rawRouteData.${d};}`},XN(s),s.children.unshift(f)}t(Fcr,"embellishWithRawOpenApi");function Lcr(s,o){let f={type:qo.Property,parent:s,name:null,value:null};f.name={value:"metadata",type:qo.Identifier,parent:s};let d={type:qo.Property,parent:f,name:null,value:null};d.name={value:"filepath",type:qo.Identifier,parent:d},d.value=PS.createLiteral(o.oasProjectRelativePath,d),f.value={type:qo.Object,parent:f,children:[d]},XN(s),s.children.unshift(f)}t(Lcr,"embellishWithMetadata");function Rcr(s){return $P(s.type==="property"),$P(Array.isArray(s.children)),JV(s.children[Ccr])}t(Rcr,"evaluatePathItem");function elt(s){return $P(s.type==="property"),$P(Array.isArray(s.children)),JV(s.children[Ecr])}t(elt,"evaluatePath");function Mcr(s,o){return G9(s.parent,o)}t(Mcr,"extractZuploRouteNode");function jcr(s){return JV(s)}t(jcr,"evaluateZuploRouteNode");function Bcr(s){let o;if(s.type==="object")for(let d of s.children??[]){let y=d.children?.[1];y&&d.children?.[0]?.value==="servers"&&(o=y)}let f=o?JV(o):void 0;return`${f&&f.length>0?f[0].url:"http://example.com"}`}t(Bcr,"resolveDefaultRewriteServer");function Ucr(s,o){let f=/{(\S+?)}/gm,y=s.replace(f,"${params.$1}");return{export:"urlRewriteHandler",module:"$import(@zuplo/runtime)",options:{rewritePattern:`${o}${y}`,forwardSearch:!0}}}t(Ucr,"addDefaultUrlRewriteHandler");async function zcr(s,o){if(o.has(s))return o.get(s);let f=await Ost(s);return o.set(s,f),f}t(zcr,"getJSFileExportsCached");async function Jcr(s,o,f,d){let y=o.handler.module.replace(/^\$import\(/,"").replace(/\)$/,""),E=ale.join(ale.dirname(f.fileName),"..",`${y}.ts`),A=o.handler.export;if(y==="@zuplo/runtime"||y.startsWith("@zuplo/runtime/"))return{valid:!0};if(await nu.fileExists(E)){let R=await zcr(E,d);if(R===null)return{valid:!1,errorMsg:`Could not find any export due to a compile error in '${nu.getParentDirFilename(E)}'`};if(!R.has(A)){let q=`Could not find export "${A}" in '${nu.getParentDirFilename(E)}'`,K=0,ve=0;if(s.children)for(let pe of s.children)pe.children&&pe.children.forEach(ae=>{ae.value==="handler"&&(K=ae.line,ve=ae.column)});return{valid:!1,errorMsg:q,line:K,column:ve}}return{valid:!0}}else return{valid:!1,errorMsg:`Could not find module '${y}'`}}t(Jcr,"checkModuleIsValid");var tlt=t((s,o)=>{let f=G9(s,["handler","options",o])??G9(s,["handler","options"])??G9(s,["handler"]);return f?{line:f.line,column:f.column-1}:{line:0,column:0}},"getHandlerOptionLocation"),$cr="$env(";function Wcr(s,o,f){let d=o.handler.export;if(d!=="urlForwardHandler"&&d!=="urlRewriteHandler")return{valid:!0};let y="rewritePattern";d==="urlForwardHandler"&&(y="baseUrl");let E=o.handler.options?.[y];if(!E){let A=tlt(s,y);return{valid:!1,errors:[{text:`Invalid request handler configuration. handler.options.${y} is required but was not provided.`,location:{file:f,line:A.line,column:A.column}}]}}if(E.includes($cr)){let A=tlt(s,y);return{valid:!0,warnings:[{text:`Invalid environment variable access syntax detected. Use \${env.VAR_NAME} instead of $env(VAR_NAME) for handler.options.${y}.`,location:{file:f,line:A.line,column:A.column}}]}}return{valid:!0}}t(Wcr,"checkHandlerIsValid");var UH=R_(x4e(),1);import{readFile as Ipr}from"node:fs/promises";var TT=R_(x4e(),1);var OO=class extends Error{static{t(this,"CustomResolveError")}},pI=class{static{t(this,"RefParser")}sourceDirectory;logger;constructor(o,f){this.sourceDirectory=o,this.logger=f}dereference(o,f){return UH.$RefParser.dereference(o,{resolve:{json:!0,file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1},dereference:{circular:"ignore",onDereference:f?.onDereference}})}bundle(o){return UH.$RefParser.bundle(o,{resolve:{file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1}})}parse(o){return UH.$RefParser.parse(o,{resolve:{file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1}})}resolve(o){return UH.$RefParser.resolve(o,{resolve:{file:Ole(this.sourceDirectory,this.logger),external:!0,http:!1}})}};function Ole(s,o){return{order:100,canRead(f){let d=Rpr(f.url);if(!(d===void 0||d==="file"))return!1;let E;try{E=Oft(f.url)}catch(A){throw new OO(`Malformed URI: ${f.url}`,{cause:A})}try{nu.safePath(s).resolve(E)}catch(A){return o?.warn(A),!1}return!0},async read(f){let d;try{d=Oft(f.url)}catch(y){throw new OO(`Malformed URI: ${f.url}`,{cause:y})}try{return await Ipr(d)}catch(y){throw new OO(`Error opening file "${d}"`,{cause:y})}}}}t(Ole,"customResolver");var Opr=/\//g,Fpr=/^(\w{2,}):\/\//i;function Lpr(){return/^win/.test(globalThis.process?globalThis.process.platform:"")}t(Lpr,"isWindowsPlatform");var E4e=[/%23/g,"#",/%24/g,"$",/%26/g,"&",/%2C/g,",",/%40/g,"@"];function Rpr(s){let o=Fpr.exec(s);if(o)return o[1].toLowerCase()}t(Rpr,"getProtocol");function Oft(s,o){let f=Lpr();s=decodeURI(s);for(let y=0;y<E4e.length;y+=2)s=s.replace(E4e[y],E4e[y+1]);let d=s.substr(0,7).toLowerCase()==="file://";if(d&&(s=s[7]==="/"?s.substr(8):s.substr(7),f&&s[1]==="/"&&(s=`${s[0]}:${s.substr(1)}`),o?s=`file:///${s}`:(d=!1,s=f?s:`/${s}`)),!d){let y=s.split(f?"\\":"/"),E=[];for(let A of y)A===".."?E.length&&E[E.length-1]!==""&&E.pop():(A!==""||E.length===0)&&E.push(A);s=E.join(f?"\\":"/"),!f&&E[0]===""&&(s=`/${s.substring(1)}`)}return f&&!d&&(s=s.replace(Opr,"\\"),s.substr(1,2)===":\\"&&(s=s[0].toUpperCase()+s.substr(1))),s}t(Oft,"toFileSystemPath");var Fft="YOUR_KEY_HERE";async function Lft(s){let f=await new pI(s.sourceDirectory,s.logger).bundle(s.openApiDocPath),d=s.openApiDocPath.replace(s.sourceDirectory,"");return Mpr({...s,relativeOpenApiPath:d},f)}t(Lft,"buildPublicOpenApiFile");async function Mpr(s,o){zpr({relativeOpenApiPath:s.relativeOpenApiPath},o);let f=o;return f=Bpr(f),jpr(f,s.urls?.api?.defaultUrl),f=Upr(f,s),Rft(f,"x-zuplo"),f}t(Mpr,"buildRawOpenApiFile");function jpr(s,o){o?s.servers=[{url:o}]:s.servers=[]}t(jpr,"addServerHost");function Bpr(s){if(!s.paths)return s;let{components:o}=s,f=o?{...o}:void 0,d=[];f&&f.parameters&&(d=Object.entries(f.parameters).reduce((E,[A,R])=>(O9 in R&&Yae(R[O9])&&(E.push(A),f.parameters&&delete f.parameters[A]),E),[]));let y=Object.entries(s.paths).reduce((E,[A,R])=>{if(!R)return E;let q={...R},K=["delete","get","head","patch","post","put","trace","options"];return K.forEach(ve=>{let pe=R[ve];if(!pe)return;if(Yae(pe[O9])){delete q[ve];return}let{parameters:ae}=pe;if(!ae)return;let rt=ae.filter(ze=>{if(O9 in ze&&Yae(ze[O9]))return!1;if("$ref"in ze){let je=ze.$ref.split("/").pop();return je?!d.includes(je):!0}return!0});q[ve]={...pe,parameters:rt}}),K.some(ve=>!!q[ve])&&(E[A]=q),E},{});return{...s,paths:y,components:f}}t(Bpr,"removeHiddenRoutesAndParams");function Upr(s,{policiesConfig:o}){if(!s.paths)return s;let f=Object.entries(s.paths).reduce((d,[y,E])=>{if(!E)return d;let A={...E};return[A.delete,A.get,A.head,A.patch,A.post,A.put,A.trace,A.options].forEach(R=>{if(!R)return;let q=R["x-zuplo-route"]?.policies?.inbound?.reduce((pe,ae)=>{let rt=o.policies?.find(({name:Bt})=>Bt===ae);if(!rt)return pe;if(!(rt.handler.export==="CompositeInboundPolicy"))return pe.concat(ae);let je=rt.handler.options?.policies;return je?pe.concat(je):pe},[]),K=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="ApiAuthKeyInboundPolicy"||ae.handler.export==="ApiKeyInboundPolicy")&&!ae.handler.options?.disableAutomaticallyAddingKeyHeaderToOpenApi&&K.push(ae)})}),K.length>0){let pe=K.length>0&&K[0].handler&&K[0].handler.options&&K[0].handler.options.authHeader?K[0].handler.options.authHeader:"Authorization",ae=K.length>0&&K[0].handler&&K[0].handler.options&&(K[0].handler.options.authScheme||K[0].handler.options.authScheme==="")?K[0].handler.options.authScheme:"Bearer",rt=ae!==""?`${ae} ${Fft}`:Fft,ze={name:pe,in:"header",required:!0,example:rt,schema:{type:"string"},description:`The \`${pe}\` header is used to authenticate with the API using your API key. Value is of the format \`${rt}\`.`};R.parameters?R.parameters.some(Or=>"name"in Or&&Or.name===ze.name)||R.parameters.unshift(ze):R.parameters=[ze];let je={type:"http",scheme:ae.toLowerCase()},Bt="api_key";s.components?.securitySchemes?Object.values(s.components?.securitySchemes).some(Or=>"name"in Or&&Or.type==="apiKey"||"type"in Or&&Or.type==="http"&&Or.scheme===ae)||(s.components.securitySchemes={...s.components.securitySchemes,[Bt]:je}):(s.components||(s.components={}),s.components.securitySchemes={[Bt]:je});let Ut={[Bt]:[]};R.security?R.security.some(Or=>Or[Bt]!==void 0)||R.security.unshift(Ut):R.security=[Ut]}let ve=[];if(q&&q.forEach(pe=>{o.policies?.forEach(ae=>{ae.name===pe&&(ae.handler.export==="RateLimitInboundPolicy"||ae.handler.export==="ComplexRateLimitInboundPolicy")&&ve.push(ae)})}),ve.length>0){let pe={description:"Rate Limiting Response",content:{"application/json":{schema:{type:"object",required:["type","title","status"],examples:[{type:"https://httpproblems.com/http-status/429",title:"Too Many Requests",status:429,instance:"/foo/bar"}],properties:{type:{type:"string",example:"https://httpproblems.com/http-status/429",description:"A URI reference that identifies the problem."},title:{type:"string",example:"Too Many Requests",description:"A short, human-readable summary of the problem."},status:{type:"number",example:429,description:"The HTTP status code."},instance:{type:"string",example:"/foo/bar"}}}}}},ae={...pe,headers:{"retry-after":{description:"The number of seconds to wait before making a new request.",schema:{type:"integer",example:60}}}};s.components?.responses||s.components||(s.components={}),s.components.responses={...s.components.responses,RateLimitNoRetryAfter:pe,RateLimitWithRetryAfter:ae},R.responses||(R.responses={});let rt=ve.some(ze=>ze.handler.options?.headerMode!=="none");R.responses[429]||(R.responses[429]={$ref:rt?"#/components/responses/RateLimitWithRetryAfter":"#/components/responses/RateLimitNoRetryAfter"})}}),d[y]=A,d},{});return{...s,paths:f}}t(Upr,"enrichSpecWithZuploData");function Rft(s,o){for(let f in s)f.startsWith(o)?delete s[f]:typeof s[f]=="object"&&Rft(s[f],o)}t(Rft,"removePropertiesByPrefix");function zpr({relativeOpenApiPath:s},o){if(!o||typeof o!="object")throw new D1({message:"The OpenAPI Document could not be parsed.",severity:"error"});if(!("info"in o)||typeof o.info!="object"||!o.info)throw new D1({message:"The OpenAPI document does not have the required 'info' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"});if(!("title"in o.info)||typeof o.info.title!="string")throw new D1({message:"The OpenAPI document does not have the required 'info.title' property.",location:{file:s,column:0,length:0,line:0,lineText:"",namespace:"",suggestion:"Add the required 'info.title' property. https://spec.openapis.org/oas/v3.1.0#info-object"},severity:"error"})}t(zpr,"assertIsZuploOpenApiSpec");import Gpr from"node:fs/promises";import Ypr from"node:path";var{stringify:Jpr}=JSON;if(!String.prototype.repeat)throw new Error("String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation");if(!String.prototype.endsWith)throw new Error("String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation");var Fle={"||":2,"??":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},ME=17,$pr={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:ME,ClassExpression:ME,FunctionExpression:ME,ObjectExpression:ME,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function NM(s,o){let{generator:f}=s;if(s.write("("),o!=null&&o.length>0){f[o[0].type](o[0],s);let{length:d}=o;for(let y=1;y<d;y++){let E=o[y];s.write(", "),f[E.type](E,s)}}s.write(")")}t(NM,"formatSequence");function $ft(s,o,f,d){let y=s.expressionsPrecedence[o.type];if(y===ME)return!0;let E=s.expressionsPrecedence[f.type];return y!==E?!d&&y===15&&E===14&&f.operator==="**"||y<E:y!==13&&y!==14?!1:o.operator==="**"&&f.operator==="**"?!d:y===13&&E===13&&(o.operator==="??"||f.operator==="??")?!0:d?Fle[o.operator]<=Fle[f.operator]:Fle[o.operator]<Fle[f.operator]}t($ft,"expressionNeedsParenthesis");function Lle(s,o,f,d){let{generator:y}=s;$ft(s,o,f,d)?(s.write("("),y[o.type](o,s),s.write(")")):y[o.type](o,s)}t(Lle,"formatExpression");function Wpr(s,o,f,d){let y=o.split(`
600
600
  `),E=y.length-1;if(s.write(y[0].trim()),E>0){s.write(d);for(let A=1;A<E;A++)s.write(f+y[A].trim()+d);s.write(f+y[E].trim())}}t(Wpr,"reindent");function M1(s,o,f,d){let{length:y}=o;for(let E=0;E<y;E++){let A=o[E];s.write(f),A.type[0]==="L"?s.write("// "+A.value.trim()+`
601
601
  `,A):(s.write("/*"),Wpr(s,A.value,f,d),s.write("*/"+d))}}t(M1,"formatComments");function qpr(s){let o=s;for(;o!=null;){let{type:f}=o;if(f[0]==="C"&&f[1]==="a")return!0;if(f[0]==="M"&&f[1]==="e"&&f[2]==="m")o=o.object;else return!1}}t(qpr,"hasCallExpression");function C4e(s,o){let{generator:f}=s,{declarations:d}=o;s.write(o.kind+" ");let{length:y}=d;if(y>0){f.VariableDeclarator(d[0],s);for(let E=1;E<y;E++)s.write(", "),f.VariableDeclarator(d[E],s)}}t(C4e,"formatVariableDeclaration");var Mft,jft,Bft,Uft,zft,Jft,Vpr={Program(s,o){let f=o.indent.repeat(o.indentLevel),{lineEnd:d,writeComments:y}=o;y&&s.comments!=null&&M1(o,s.comments,f,d);let E=s.body,{length:A}=E;for(let R=0;R<A;R++){let q=E[R];y&&q.comments!=null&&M1(o,q.comments,f,d),o.write(f),this[q.type](q,o),o.write(d)}y&&s.trailingComments!=null&&M1(o,s.trailingComments,f,d)},BlockStatement:Jft=t(function(s,o){let f=o.indent.repeat(o.indentLevel++),{lineEnd:d,writeComments:y}=o,E=f+o.indent;o.write("{");let A=s.body;if(A!=null&&A.length>0){o.write(d),y&&s.comments!=null&&M1(o,s.comments,E,d);let{length:R}=A;for(let q=0;q<R;q++){let K=A[q];y&&K.comments!=null&&M1(o,K.comments,E,d),o.write(E),this[K.type](K,o),o.write(d)}o.write(f)}else y&&s.comments!=null&&(o.write(d),M1(o,s.comments,E,d),o.write(f));y&&s.trailingComments!=null&&M1(o,s.trailingComments,E,d),o.write("}"),o.indentLevel--},"BlockStatement"),ClassBody:Jft,StaticBlock(s,o){o.write("static "),this.BlockStatement(s,o)},EmptyStatement(s,o){o.write(";")},ExpressionStatement(s,o){let f=o.expressionsPrecedence[s.expression.type];f===ME||f===3&&s.expression.left.type[0]==="O"?(o.write("("),this[s.expression.type](s.expression,o),o.write(")")):this[s.expression.type](s.expression,o),o.write(";")},IfStatement(s,o){o.write("if ("),this[s.test.type](s.test,o),o.write(") "),this[s.consequent.type](s.consequent,o),s.alternate!=null&&(o.write(" else "),this[s.alternate.type](s.alternate,o))},LabeledStatement(s,o){this[s.label.type](s.label,o),o.write(": "),this[s.body.type](s.body,o)},BreakStatement(s,o){o.write("break"),s.label!=null&&(o.write(" "),this[s.label.type](s.label,o)),o.write(";")},ContinueStatement(s,o){o.write("continue"),s.label!=null&&(o.write(" "),this[s.label.type](s.label,o)),o.write(";")},WithStatement(s,o){o.write("with ("),this[s.object.type](s.object,o),o.write(") "),this[s.body.type](s.body,o)},SwitchStatement(s,o){let f=o.indent.repeat(o.indentLevel++),{lineEnd:d,writeComments:y}=o;o.indentLevel++;let E=f+o.indent,A=E+o.indent;o.write("switch ("),this[s.discriminant.type](s.discriminant,o),o.write(") {"+d);let{cases:R}=s,{length:q}=R;for(let K=0;K<q;K++){let ve=R[K];y&&ve.comments!=null&&M1(o,ve.comments,E,d),ve.test?(o.write(E+"case "),this[ve.test.type](ve.test,o),o.write(":"+d)):o.write(E+"default:"+d);let{consequent:pe}=ve,{length:ae}=pe;for(let rt=0;rt<ae;rt++){let ze=pe[rt];y&&ze.comments!=null&&M1(o,ze.comments,A,d),o.write(A),this[ze.type](ze,o),o.write(d)}}o.indentLevel-=2,o.write(f+"}")},ReturnStatement(s,o){o.write("return"),s.argument&&(o.write(" "),this[s.argument.type](s.argument,o)),o.write(";")},ThrowStatement(s,o){o.write("throw "),this[s.argument.type](s.argument,o),o.write(";")},TryStatement(s,o){if(o.write("try "),this[s.block.type](s.block,o),s.handler){let{handler:f}=s;f.param==null?o.write(" catch "):(o.write(" catch ("),this[f.param.type](f.param,o),o.write(") ")),this[f.body.type](f.body,o)}s.finalizer&&(o.write(" finally "),this[s.finalizer.type](s.finalizer,o))},WhileStatement(s,o){o.write("while ("),this[s.test.type](s.test,o),o.write(") "),this[s.body.type](s.body,o)},DoWhileStatement(s,o){o.write("do "),this[s.body.type](s.body,o),o.write(" while ("),this[s.test.type](s.test,o),o.write(");")},ForStatement(s,o){if(o.write("for ("),s.init!=null){let{init:f}=s;f.type[0]==="V"?C4e(o,f):this[f.type](f,o)}o.write("; "),s.test&&this[s.test.type](s.test,o),o.write("; "),s.update&&this[s.update.type](s.update,o),o.write(") "),this[s.body.type](s.body,o)},ForInStatement:Mft=t(function(s,o){o.write(`for ${s.await?"await ":""}(`);let{left:f}=s;f.type[0]==="V"?C4e(o,f):this[f.type](f,o),o.write(s.type[3]==="I"?" in ":" of "),this[s.right.type](s.right,o),o.write(") "),this[s.body.type](s.body,o)},"ForInStatement"),ForOfStatement:Mft,DebuggerStatement(s,o){o.write("debugger;",s)},FunctionDeclaration:jft=t(function(s,o){o.write((s.async?"async ":"")+(s.generator?"function* ":"function ")+(s.id?s.id.name:""),s),NM(o,s.params),o.write(" "),this[s.body.type](s.body,o)},"FunctionDeclaration"),FunctionExpression:jft,VariableDeclaration(s,o){C4e(o,s),o.write(";")},VariableDeclarator(s,o){this[s.id.type](s.id,o),s.init!=null&&(o.write(" = "),this[s.init.type](s.init,o))},ClassDeclaration(s,o){if(o.write("class "+(s.id?`${s.id.name} `:""),s),s.superClass){o.write("extends ");let{superClass:f}=s,{type:d}=f,y=o.expressionsPrecedence[d];(d[0]!=="C"||d[1]!=="l"||d[5]!=="E")&&(y===ME||y<o.expressionsPrecedence.ClassExpression)?(o.write("("),this[s.superClass.type](f,o),o.write(")")):this[f.type](f,o),o.write(" ")}this.ClassBody(s.body,o)},ImportDeclaration(s,o){o.write("import ");let{specifiers:f,attributes:d}=s,{length:y}=f,E=0;if(y>0){for(;E<y;){E>0&&o.write(", ");let A=f[E],R=A.type[6];if(R==="D")o.write(A.local.name,A),E++;else if(R==="N")o.write("* as "+A.local.name,A),E++;else break}if(E<y){for(o.write("{");;){let A=f[E],{name:R}=A.imported;if(o.write(R,A),R!==A.local.name&&o.write(" as "+A.local.name),++E<y)o.write(", ");else break}o.write("}")}o.write(" from ")}if(this.Literal(s.source,o),d&&d.length>0){o.write(" with { ");for(let A=0;A<d.length;A++)this.ImportAttribute(d[A],o),A<d.length-1&&o.write(", ");o.write(" }")}o.write(";")},ImportAttribute(s,o){this.Identifier(s.key,o),o.write(": "),this.Literal(s.value,o)},ImportExpression(s,o){o.write("import("),this[s.source.type](s.source,o),o.write(")")},ExportDefaultDeclaration(s,o){o.write("export default "),this[s.declaration.type](s.declaration,o),o.expressionsPrecedence[s.declaration.type]!=null&&s.declaration.type[0]!=="F"&&o.write(";")},ExportNamedDeclaration(s,o){if(o.write("export "),s.declaration)this[s.declaration.type](s.declaration,o);else{o.write("{");let{specifiers:f}=s,{length:d}=f;if(d>0)for(let y=0;;){let E=f[y],{name:A}=E.local;if(o.write(A,E),A!==E.exported.name&&o.write(" as "+E.exported.name),++y<d)o.write(", ");else break}if(o.write("}"),s.source&&(o.write(" from "),this.Literal(s.source,o)),s.attributes&&s.attributes.length>0){o.write(" with { ");for(let y=0;y<s.attributes.length;y++)this.ImportAttribute(s.attributes[y],o),y<s.attributes.length-1&&o.write(", ");o.write(" }")}o.write(";")}},ExportAllDeclaration(s,o){if(s.exported!=null?o.write("export * as "+s.exported.name+" from "):o.write("export * from "),this.Literal(s.source,o),s.attributes&&s.attributes.length>0){o.write(" with { ");for(let f=0;f<s.attributes.length;f++)this.ImportAttribute(s.attributes[f],o),f<s.attributes.length-1&&o.write(", ");o.write(" }")}o.write(";")},MethodDefinition(s,o){s.static&&o.write("static ");let f=s.kind[0];(f==="g"||f==="s")&&o.write(s.kind+" "),s.value.async&&o.write("async "),s.value.generator&&o.write("*"),s.computed?(o.write("["),this[s.key.type](s.key,o),o.write("]")):this[s.key.type](s.key,o),NM(o,s.value.params),o.write(" "),this[s.value.body.type](s.value.body,o)},ClassExpression(s,o){this.ClassDeclaration(s,o)},ArrowFunctionExpression(s,o){o.write(s.async?"async ":"",s);let{params:f}=s;f!=null&&(f.length===1&&f[0].type[0]==="I"?o.write(f[0].name,f[0]):NM(o,s.params)),o.write(" => "),s.body.type[0]==="O"?(o.write("("),this.ObjectExpression(s.body,o),o.write(")")):this[s.body.type](s.body,o)},ThisExpression(s,o){o.write("this",s)},Super(s,o){o.write("super",s)},RestElement:Bft=t(function(s,o){o.write("..."),this[s.argument.type](s.argument,o)},"RestElement"),SpreadElement:Bft,YieldExpression(s,o){o.write(s.delegate?"yield*":"yield"),s.argument&&(o.write(" "),this[s.argument.type](s.argument,o))},AwaitExpression(s,o){o.write("await ",s),Lle(o,s.argument,s)},TemplateLiteral(s,o){let{quasis:f,expressions:d}=s;o.write("`");let{length:y}=d;for(let A=0;A<y;A++){let R=d[A],q=f[A];o.write(q.value.raw,q),o.write("${"),this[R.type](R,o),o.write("}")}let E=f[f.length-1];o.write(E.value.raw,E),o.write("`")},TemplateElement(s,o){o.write(s.value.raw,s)},TaggedTemplateExpression(s,o){Lle(o,s.tag,s),this[s.quasi.type](s.quasi,o)},ArrayExpression:zft=t(function(s,o){if(o.write("["),s.elements.length>0){let{elements:f}=s,{length:d}=f;for(let y=0;;){let E=f[y];if(E!=null&&this[E.type](E,o),++y<d)o.write(", ");else{E==null&&o.write(", ");break}}}o.write("]")},"ArrayExpression"),ArrayPattern:zft,ObjectExpression(s,o){let f=o.indent.repeat(o.indentLevel++),{lineEnd:d,writeComments:y}=o,E=f+o.indent;if(o.write("{"),s.properties.length>0){o.write(d),y&&s.comments!=null&&M1(o,s.comments,E,d);let A=","+d,{properties:R}=s,{length:q}=R;for(let K=0;;){let ve=R[K];if(y&&ve.comments!=null&&M1(o,ve.comments,E,d),o.write(E),this[ve.type](ve,o),++K<q)o.write(A);else break}o.write(d),y&&s.trailingComments!=null&&M1(o,s.trailingComments,E,d),o.write(f+"}")}else y?s.comments!=null?(o.write(d),M1(o,s.comments,E,d),s.trailingComments!=null&&M1(o,s.trailingComments,E,d),o.write(f+"}")):s.trailingComments!=null?(o.write(d),M1(o,s.trailingComments,E,d),o.write(f+"}")):o.write("}"):o.write("}");o.indentLevel--},Property(s,o){s.method||s.kind[0]!=="i"?this.MethodDefinition(s,o):(s.shorthand||(s.computed?(o.write("["),this[s.key.type](s.key,o),o.write("]")):this[s.key.type](s.key,o),o.write(": ")),this[s.value.type](s.value,o))},PropertyDefinition(s,o){if(s.static&&o.write("static "),s.computed&&o.write("["),this[s.key.type](s.key,o),s.computed&&o.write("]"),s.value==null){s.key.type[0]!=="F"&&o.write(";");return}o.write(" = "),this[s.value.type](s.value,o),o.write(";")},ObjectPattern(s,o){if(o.write("{"),s.properties.length>0){let{properties:f}=s,{length:d}=f;for(let y=0;this[f[y].type](f[y],o),++y<d;)o.write(", ")}o.write("}")},SequenceExpression(s,o){NM(o,s.expressions)},UnaryExpression(s,o){if(s.prefix){let{operator:f,argument:d,argument:{type:y}}=s;o.write(f);let E=$ft(o,d,s);!E&&(f.length>1||y[0]==="U"&&(y[1]==="n"||y[1]==="p")&&d.prefix&&d.operator[0]===f&&(f==="+"||f==="-"))&&o.write(" "),E?(o.write(f.length>1?" (":"("),this[y](d,o),o.write(")")):this[y](d,o)}else this[s.argument.type](s.argument,o),o.write(s.operator)},UpdateExpression(s,o){s.prefix?(o.write(s.operator),this[s.argument.type](s.argument,o)):(this[s.argument.type](s.argument,o),o.write(s.operator))},AssignmentExpression(s,o){this[s.left.type](s.left,o),o.write(" "+s.operator+" "),this[s.right.type](s.right,o)},AssignmentPattern(s,o){this[s.left.type](s.left,o),o.write(" = "),this[s.right.type](s.right,o)},BinaryExpression:Uft=t(function(s,o){let f=s.operator==="in";f&&o.write("("),Lle(o,s.left,s,!1),o.write(" "+s.operator+" "),Lle(o,s.right,s,!0),f&&o.write(")")},"BinaryExpression"),LogicalExpression:Uft,ConditionalExpression(s,o){let{test:f}=s,d=o.expressionsPrecedence[f.type];d===ME||d<=o.expressionsPrecedence.ConditionalExpression?(o.write("("),this[f.type](f,o),o.write(")")):this[f.type](f,o),o.write(" ? "),this[s.consequent.type](s.consequent,o),o.write(" : "),this[s.alternate.type](s.alternate,o)},NewExpression(s,o){o.write("new ");let f=o.expressionsPrecedence[s.callee.type];f===ME||f<o.expressionsPrecedence.CallExpression||qpr(s.callee)?(o.write("("),this[s.callee.type](s.callee,o),o.write(")")):this[s.callee.type](s.callee,o),NM(o,s.arguments)},CallExpression(s,o){let f=o.expressionsPrecedence[s.callee.type];f===ME||f<o.expressionsPrecedence.CallExpression?(o.write("("),this[s.callee.type](s.callee,o),o.write(")")):this[s.callee.type](s.callee,o),s.optional&&o.write("?."),NM(o,s.arguments)},ChainExpression(s,o){this[s.expression.type](s.expression,o)},MemberExpression(s,o){let f=o.expressionsPrecedence[s.object.type];f===ME||f<o.expressionsPrecedence.MemberExpression?(o.write("("),this[s.object.type](s.object,o),o.write(")")):this[s.object.type](s.object,o),s.computed?(s.optional&&o.write("?."),o.write("["),this[s.property.type](s.property,o),o.write("]")):(s.optional?o.write("?."):o.write("."),this[s.property.type](s.property,o))},MetaProperty(s,o){o.write(s.meta.name+"."+s.property.name,s)},Identifier(s,o){o.write(s.name,s)},PrivateIdentifier(s,o){o.write(`#${s.name}`,s)},Literal(s,o){s.raw!=null?o.write(s.raw,s):s.regex!=null?this.RegExpLiteral(s,o):s.bigint!=null?o.write(s.bigint+"n",s):o.write(Jpr(s.value),s)},RegExpLiteral(s,o){let{regex:f}=s;o.write(`/${f.pattern}/${f.flags}`,s)}},Hpr={};var k4e=class{static{t(this,"State")}constructor(o){let f=o??Hpr;this.output="",f.output!=null?(this.output=f.output,this.write=this.writeToStream):this.output="",this.generator=f.generator!=null?f.generator:Vpr,this.expressionsPrecedence=f.expressionsPrecedence!=null?f.expressionsPrecedence:$pr,this.indent=f.indent!=null?f.indent:" ",this.lineEnd=f.lineEnd!=null?f.lineEnd:`
602
602
  `,this.indentLevel=f.startingIndentLevel!=null?f.startingIndentLevel:0,this.writeComments=f.comments?f.comments:!1,f.sourceMap!=null&&(this.write=f.output==null?this.writeAndMap:this.writeToStreamAndMap,this.sourceMap=f.sourceMap,this.line=1,this.column=0,this.lineEndSize=this.lineEnd.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/core",
3
- "version": "7.4.7",
3
+ "version": "7.5.1",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "type": "module",
@@ -40,9 +40,9 @@
40
40
  "source-map": "^0.7.4"
41
41
  },
42
42
  "peerDependencies": {
43
- "@zuplo/graphql": "7.4.7",
44
- "@zuplo/otel": "7.4.7",
45
- "@zuplo/runtime": "7.4.7",
43
+ "@zuplo/graphql": "7.5.1",
44
+ "@zuplo/otel": "7.5.1",
45
+ "@zuplo/runtime": "7.5.1",
46
46
  "deno": "2.3.1"
47
47
  }
48
48
  }