bknd
Version:
Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.
81 lines • 220 kB
JavaScript
import Lt from'dayjs';import ac from'dayjs/plugin/weekOfYear.js';import'hono/adapter';import {XMLParser}from'fast-xml-parser';import'hono/validator';import {sql,ParseJSONResultsPlugin,DEFAULT_MIGRATION_TABLE,DEFAULT_MIGRATION_LOCK_TABLE,Kysely,SqliteDialect,SqliteQueryCompiler,SqliteAdapter,SqliteIntrospector,CompiledQuery,SelectQueryNode,RawNode,IdentifierNode}from'kysely';import {s,omitKeys,parse,snakeToPascalWithSpaces,secret,objectTransform,transformObject,$console,uuidv7,filterKeys,jsc,isFile,pickHeaders2,InvalidSchemaError,HttpStatus,describeRoute,getFileFromContext,truncate,runtimeSupports,schemaToSpec,deepFreeze,stripMark,mergeObjectWith,getFullPathKeys,randomString,patternMatch,objectEach,mark,datetimeStringUTC,datetimeStringLocal,getTimezoneOffset,getTimezone,getRuntimeKey,SecretSchema,encodeSearch,isPlainObject}from'bknd/utils';import {Validator}from'@cfworker/json-schema';import {Hono}from'hono';import {set,get,transform,pick,has,omit,mergeWith,isEqual}from'lodash-es';import {cors}from'hono/cors';import {createMiddleware}from'hono/factory';import {setSignedCookie,getSignedCookie,deleteCookie,setCookie}from'hono/cookie';import {sign,verify,decode}from'hono/jwt';import {serializeSigned}from'hono/utils/cookie';import*as b from'oauth4webapi';import {genSalt,hash,compare}from'bcryptjs';import {AwsClient}from'aws4fetch';import {html}from'hono/html';import {Fragment}from'hono/jsx';import {css,Style}from'hono/css';import {jsxs,jsx}from'hono/jsx/jsx-runtime';import {swaggerUI}from'@hono/swagger-ui';import {jsonBuildObject,jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/sqlite';var Za=Object.create;var oi=Object.defineProperty;var ec=Object.getOwnPropertyDescriptor;var tc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,nc=Object.prototype.hasOwnProperty;var ic=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Be=(n,e)=>{for(var t in e)oi(n,t,{get:e[t],enumerable:true});},sc=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of tc(e))!nc.call(n,i)&&i!==t&&oi(n,i,{get:()=>e[i],enumerable:!(r=ec(e,i))||r.enumerable});return n};var oc=(n,e,t)=>(t=n!=null?Za(rc(n)):{},sc(oi(t,"default",{value:n,enumerable:true}),n));var Xs=ic((hd,ai)=>{var y=String,Ys=function(){return {isColorSupported:false,reset:y,bold:y,dim:y,italic:y,underline:y,inverse:y,hidden:y,strikethrough:y,black:y,red:y,green:y,yellow:y,blue:y,magenta:y,cyan:y,white:y,gray:y,bgBlack:y,bgRed:y,bgGreen:y,bgYellow:y,bgBlue:y,bgMagenta:y,bgCyan:y,bgWhite:y,blackBright:y,redBright:y,greenBright:y,yellowBright:y,blueBright:y,magentaBright:y,cyanBright:y,whiteBright:y,bgBlackBright:y,bgRedBright:y,bgGreenBright:y,bgYellowBright:y,bgBlueBright:y,bgMagentaBright:y,bgCyanBright:y,bgWhiteBright:y}};ai.exports=Ys();ai.exports.createColors=Ys;});Lt.extend(ac);function Hs(n){return Lt(n).format("YYYY-MM-DD HH:mm:ss")}var W=oc(Xs());var ci=(n,e)=>typeof n=="string"?[1,"1","true"].includes(n):!!(n||e);function A(){try{return ci(0)}catch{return false}}function Zs(){try{return "0.16.0"}catch{return "0.0.0"}}var cc={cli_log_level:{key:"BKND_CLI_LOG_LEVEL",validate:n=>{if(typeof n=="string"&&["log","info","warn","error","debug"].includes(n.toLowerCase()))return n.toLowerCase()}},cli_create_ref:{key:"BKND_CLI_CREATE_REF",validate:n=>typeof n=="string"?n:void 0},cli_telemetry:{key:"BKND_CLI_TELEMETRY",validate:n=>{if(!(typeof n>"u"))return ci(n,true)}},modules_debug:{key:"BKND_MODULES_DEBUG",validate:ci}},Qt=(n,e,t)=>{try{let r=t?.source??process.env,i=cc[n],s=r[i.key],o=i.validate(s);if(typeof o<"u")return t?.onValid?.(o),o;t?.onFallback?.(s);}catch{t?.onFallback?.(void 0);}return e};function lc(){try{let n=process||{},e=n.argv||[],t=n.env||{};return !(t.NO_COLOR||e.includes("--no-color"))&&(!!t.FORCE_COLOR||e.includes("--color")||n.platform==="win32"||(n.stdout||{}).isTTY&&t.TERM!=="dumb"||!!t.CI)}catch{return false}}var li={critical:{prefix:"CRT",color:W.default.red,args_color:W.default.red,original:console.error},error:{prefix:"ERR",color:W.default.red,args_color:W.default.red,original:console.error},warn:{prefix:"WRN",color:W.default.yellow,args_color:W.default.yellow,original:console.warn},info:{prefix:"INF",color:W.default.cyan,original:console.info},log:{prefix:"LOG",color:W.default.dim,args_color:W.default.dim,original:console.log},debug:{prefix:"DBG",color:W.default.yellow,args_color:W.default.dim,original:console.debug}};function uc(n,e){let t=lc(),r=li[n],i=r.color(`[${r.prefix}]`),s=e.map(o=>"args_color"in r&&t&&typeof o=="string"?r.args_color(o):o);return r.original(i,W.default.gray(Hs()),...s)}var to=Qt("cli_log_level","log"),Tr=globalThis.__consoleConfig??={level:to},eo=Object.keys(li),f=new Proxy(Tr,{get:(n,e)=>{switch(e){case "original":return console;case "setLevel":return i=>{Tr.level=i;};case "resetLevel":return ()=>{Tr.level=to;}}let t=eo.indexOf(Tr.level),r=eo.indexOf(e);return e in li&&r<=t?(...i)=>uc(e,i):()=>null}});function pi(n){return !n||n.length===0?n:n.charAt(0).toUpperCase()+n.slice(1)}function ro(n){return !n||n.length===0?n:n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function Rr(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function pc(n){return /^[a-z]+(_[a-z]+)*$/.test(n)?"snake_case":/^[A-Z][a-zA-Z]*$/.test(n)?"PascalCase":/^[a-z][a-zA-Z]*$/.test(n)?"camelCase":/^[a-z]+(-[a-z]+)*$/.test(n)?"kebab-case":/^[A-Z]+(_[A-Z]+)*$/.test(n)?"SCREAMING_SNAKE_CASE":"unknown"}function dc(n){switch(pc(n)){case "snake_case":return ro(n);case "PascalCase":return ui(Rr(n));case "camelCase":return pi(ui(Rr(n)));case "kebab-case":return ui(n);case "SCREAMING_SNAKE_CASE":return ro(n.toLowerCase());case "unknown":return pi(n)}}function no(n){return dc(n)}function ui(n){return n.split("-").map(pi).join(" ")}function mc(n){return Object.prototype.toString.call(n)==="[object Object]"}function $e(n){return n!==null&&typeof n=="object"}function ee(n,e){let t=new Set(e),r={};for(let[i,s]of Object.entries(n))t.has(i)||(r[i]=s);return r}function Cr(n,e=[]){return n===null||typeof n!="object"?n:Array.isArray(n)?n.map(t=>Cr(t,e)):Object.keys(n).reduce((t,r)=>{let i=e.includes(r)?r:Rr(r);return t[i]=Cr(n[r],e),t},{})}function P(n,e){let t={};for(let[r,i]of Object.entries(n)){let s=e(i,r);typeof s<"u"&&(t[r]=s);}return t}var Ar=P;function Or(n){return n&&Object.entries(n).reduce((e,[t,r])=>{if(r&&Array.isArray(r)&&r.some(i=>typeof i=="object")){let i=r.map(Or);i.length>0&&(e[t]=i);}else if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Or(r);Object.keys(i).length>0&&(e[t]=i);}else r!==""&&r!==null&&r!==void 0&&(e[t]=r);return e},{})}function di(n,...e){for(let t of e)for(let[r,i]of Object.entries(t))i!==void 0&&(!mc(i)&&!Array.isArray(i)||Array.isArray(i)&&!Array.isArray(n[r])?n[r]=i:$e(n[r])?di(n[r],i):n[r]=i);return n}function _r(n,e=0,t=0){let r=e?`
`:"",i=a=>e?" ".repeat(e*a):"",s=i(t+1),o=i(t);if(n===null)return "null";if(n===void 0)return "undefined";let c=typeof n;if(c==="string")return JSON.stringify(n);if(c==="number"||c==="boolean")return String(n);if(Array.isArray(n)){let a=n.map(l=>_r(l,e,t+1)).join(", "+(e?r+s:""));return "["+(e&&n.length?r+s:"")+a+(e&&n.length?r+o:"")+"]"}if(c==="object"){let a=Object.entries(n).map(([u,p])=>(/^[A-Za-z_$][\w$]*$/.test(u)?u:JSON.stringify(u))+": "+_r(p,e,t+1)),l=a.join(", "+(e?r+s:""));return "{"+(e&&a.length?r+s:"")+l+(e&&a.length?r+o:"")+"}"}throw new TypeError(`Unsupported data type: ${c}`)}function io(n,e){return e.reduce((t,r)=>(r in n&&(t[r]=n[r]),t),{})}var mi={video:["mp4","webm"],audio:["ogg"],image:["jpeg","png","gif","webp","bmp","tiff","avif","heic","heif"],text:["html","css","mdx","yaml","vcard","csv","vtt"],application:["zip","xml","toml","json","json5"],font:["woff","woff2","ttf","otf"]},g={vnd:"vnd.openxmlformats-officedocument",z:"application/x-7z-compressed",t:(n="plain")=>`text/${n}`,a:(n="octet-stream")=>`application/${n}`,i:n=>`image/${n}`,v:n=>`video/${n}`},fi=new Map([["7z",g.z],["7zip",g.z],["ai",g.a("pdf")],["apk",g.a("vnd.android.package-archive")],["doc",g.a("msword")],["docx",`${g.vnd}.wordprocessingml.document`],["eps",g.a("postscript")],["epub",g.a("epub+zip")],["ini",g.t()],["ico",g.i("vnd.microsoft.icon")],["jar",g.a("java-archive")],["jsonld",g.a("ld+json")],["jpg",g.i("jpeg")],["js",g.t("javascript")],["log",g.t()],["m3u",g.t()],["m3u8",g.a("vnd.apple.mpegurl")],["manifest",g.t("cache-manifest")],["md",g.t("markdown")],["mkv",g.v("x-matroska")],["mp3",g.a("mpeg")],["mobi",g.a("x-mobipocket-ebook")],["ppt",g.a("powerpoint")],["pptx",`${g.vnd}.presentationml.presentation`],["qt",g.v("quicktime")],["svg",g.i("svg+xml")],["tif",g.i("tiff")],["tsv",g.t("tab-separated-values")],["tgz",g.a("x-tar")],["txt",g.t()],["text",g.t()],["vcd",g.a("x-cdlink")],["vcs",g.t("x-vcalendar")],["wav",g.a("x-wav")],["webmanifest",g.a("manifest+json")],["xls",g.a("vnd.ms-excel")],["xlsx",`${g.vnd}.spreadsheetml.sheet`],["yml",g.t("yaml")]]);function fc(n){try{let e=n.split(".").pop();if(!e)return g.a();for(let[t,r]of Object.entries(mi))if(r.includes(e))return `${t}/${e}`;return fi.get(e)}catch{return g.a()}}function so(n,e=[]){let t=n.toLowerCase();if(e.includes(t))return false;if(Object.entries(mi).flatMap(([r,i])=>i.map(s=>`${r}/${s}`)).includes(t))return true;for(let[r,i]of fi.entries())if(i===t&&!e.includes(r))return true;return false}function oo(n){let e=n.toLowerCase();for(let[t,r]of Object.entries(mi))for(let i of r)if(e===`${t}/${i}`)return i;for(let[t,r]of fi.entries())if(r===e)return t;return ""}function yi(n,e){if(!n)throw new Error(e)}function yc(n){return typeof n=="object"&&n!==null&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"}function hi(n){return yc(n)&&typeof n.name=="string"&&typeof n.lastModified=="number"}async function ao(n,e){let t=hi(n),r=t?n.type:e;yi(r&&typeof r=="string"&&r.startsWith("image/"),"type must be image/*");let i=t?await n.arrayBuffer():n;yi(i.byteLength>=128,"Buffer must be at least 128 bytes");let s=new DataView(i);if(r==="image/jpeg"){let o=2;for(;o<s.byteLength;){let c=s.getUint16(o);if(o+=2,c===65472||c===65474)return {width:s.getUint16(o+5),height:s.getUint16(o+3)};o+=s.getUint16(o);}}else {if(r==="image/png")return {width:s.getUint32(16),height:s.getUint32(20)};if(r==="image/gif")return {width:s.getUint16(6),height:s.getUint16(8)};if(r==="image/tiff"){let o=s.getUint16(0)===18761,c=s.getUint32(4,o),a=s.getUint32(c+18,o),l=s.getUint32(c+10,o);return {width:a,height:l}}}throw new Error("Unsupported image format")}function hc(n){return n?{...Object.fromEntries(n.entries())}:{}}function co(n,e){let t=hc(n),r={};for(let i of e)t[i]&&(r[i]=t[i]);return r}function lo(n){return new XMLParser().parse(n)}var bc=["SHA-1","SHA-256","SHA-384","SHA-512"];async function uo(n,e,t,r){if(!bc.includes(n))throw new Error(`Invalid hash algorithm: ${n}`);let i=new TextEncoder().encode((t??"")+e+(r??"")),s=await crypto.subtle.digest(n,i);return Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join("")}var kr={sha256:async(n,e,t)=>uo("SHA-256",n,e,t),sha1:async(n,e,t)=>uo("SHA-1",n,e,t)};function po(n){let e=new Uint8Array(n);return crypto.getRandomValues(e),Array.from(e,t=>String.fromCharCode(33+t%94)).join("")}var j=[];for(let n=0;n<256;++n)j.push((n+256).toString(16).slice(1));function mo(n,e=0){return (j[n[e+0]]+j[n[e+1]]+j[n[e+2]]+j[n[e+3]]+"-"+j[n[e+4]]+j[n[e+5]]+"-"+j[n[e+6]]+j[n[e+7]]+"-"+j[n[e+8]]+j[n[e+9]]+"-"+j[n[e+10]]+j[n[e+11]]+j[n[e+12]]+j[n[e+13]]+j[n[e+14]]+j[n[e+15]]).toLowerCase()}var gi,wc=new Uint8Array(16);function bi(){if(!gi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");gi=crypto.getRandomValues.bind(crypto);}return gi(wc)}var xc=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),wi={randomUUID:xc};function Ec(n,e,t){if(wi.randomUUID&&!e&&!n)return wi.randomUUID();n=n||{};let r=n.random??n.rng?.()??bi();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[t+i]=r[i];return e}return mo(r)}var xi=Ec;function fo(){return xi()}function Ei(n){return n==null?0:typeof n=="number"?n:Number.parseInt(n,10)}var yo=Symbol.for("jsonv");function vc(n){return Object.prototype.toString.call(n)==="[object Object]"}function Sc(n){return n!==null&&typeof n=="object"}function Si(n,...e){for(let t of e)for(let[r,i]of Object.entries(t))i!==void 0&&(!vc(i)&&!Array.isArray(i)||Array.isArray(i)&&!Array.isArray(n[r])?n[r]=i:Sc(n[r])?Si(n[r],i):n[r]=i);return n}var Tc={query:"query",param:"path",header:"header",cookie:"cookie"},Rc={json:{type:"application/json"},form:{type:"multipart/form-data"}};function Cc(n,e){let t=Tc[e],r=Rc[e];return t?{parameters:Object.entries(n.properties).map(([i,s])=>({name:i,in:t,required:n.required?.includes(i)||void 0,description:s?.description||void 0,schema:structuredClone(s.toJSON())}))}:r?{requestBody:{content:{[r.type]:{schema:structuredClone(n.toJSON()),example:n.examples?.[0]??n.template({},{withOptional:true,withExtendedOptional:true})}}}}:{}}var Oc=n=>n.split("/").map(e=>{let t=e;if(t.startsWith(":")){let r=t.match(/^:([^{?]+)(?:{(.+)})?(\?)?$/);r?t=`{${r[1]}}`:(t=t.slice(1,t.length),t.endsWith("?")&&(t=t.slice(0,-1)),t=`{${t}}`);}return t}).join("/"),ho=n=>n.charAt(0).toUpperCase()+n.slice(1),vi=new Map,_c=(n,e)=>{let t=`${n}:${e}`;if(vi.has(t))return vi.get(t);let r=n;if(e==="/")return `${r}Index`;for(let i of e.split("/"))i.charCodeAt(0)===123?r+=`By${ho(i.slice(1,-1))}`:r+=ho(i);return vi.set(t,r),r},go=(n,e={})=>{let t=false;return async r=>{if(!t){t=true,e.paths=e.paths??{};for(let i of n.routes)if(yo in i.handler){let s=i.method.toLowerCase(),o=Oc(i.path),{type:c,value:a}=i.handler[yo];e.paths[o]||(e.paths[o]={}),e.paths[o][s]||(e.paths[o][s]={responses:{},operationId:_c(s,o)});let l=e.paths[o][s];switch(c){case "parameters":let{parameters:u,requestBody:p}=Cc(a.schema,a.target);u&&(l.parameters||(l.parameters=[]),l.parameters.push(...u.filter(d=>{try{return !l.parameters.some(m=>m.name===d.name&&m.in===d.in)}catch{return true}}))),p&&(l.requestBody||(l.requestBody={}),Si(l.requestBody,p));break;case "route-doc":Si(e.paths[o][s],a);break}}}return r.json({openapi:"3.1.0",info:{title:"API",...e.info},...e})}};var v=class{_returning;static slug="untitled-event";params;returned=false;validate(e){throw new Ti(this,e)}clone(e){let t=new this.constructor(e);return t.returned=true,t}constructor(e){this.params=e;}};var le=class extends Error{constructor(e,t){super(`Expected "${e}", got "${t}"`);}},Ti=class extends Error{constructor(t,r){super(`Event "${t.constructor.slug}" returned without validation`);this.data=r;}};var Fr=class{mode="async";event;handler;once=false;id;constructor(e,t,r="async",i){this.event=e,this.handler=t,this.mode=r,this.id=i;}};var $=class{constructor(e,t){this.options=t;e&&this.registerEvents(e),t?.listeners?.forEach(r=>this.addListener(r));}events=[];listeners=[];enabled=true;asyncs=[];enable(){return this.enabled=true,this}disable(){return this.enabled=false,this}clearEvents(){return this.events=[],this}clearAll(){return this.clearEvents(),this.listeners=[],this}getListeners(){return [...this.listeners]}get Events(){return new Proxy(this,{get:(e,t)=>this.events.find(r=>r.slug===t)})}eventExists(e){let t;return typeof e=="string"?t=e:t=e.constructor?.slug??e.slug,!!this.events.find(r=>t===r.slug)}throwIfEventNotRegistered(e){if(!this.eventExists(e)){let t=e.constructor?.slug??e.slug??e;throw new Error(`Event "${t}" not registered`)}}registerEvent(e,t=false){if(this.eventExists(e)){if(t)return this;throw new Error(`Event "${e.name}" already registered.`)}return this.events.push(e),this}registerEvents(e){return (typeof e=="object"?Object.values(e):e).forEach(r=>this.registerEvent(r,true)),this}addListener(e){return this.throwIfEventNotRegistered(e.event),e.id&&this.listeners.find(r=>r.id===e.id)?(f.debug(`Listener with id "${e.id}" already exists.`),this):(this.listeners.push(e),this)}createEventListener(e,t,r="async"){let i=typeof e=="string"?this.events.find(c=>c.slug===e):e,s=typeof r=="string"?{mode:r}:r,o=new Fr(i,t,s.mode);s.once&&(o.once=true),s.id&&(o.id=`${i.slug}-${s.id}`),this.addListener(o);}onEvent(e,t,r){this.createEventListener(e,t,r);}on(e,t,r){this.createEventListener(e,t,r);}onAny(e,t){this.events.forEach(r=>this.onEvent(r,e,t));}collectAsyncs(e){this.asyncs.push(...e);}async executeAsyncs(e=t=>Promise.all(t)){if(this.asyncs.length===0)return;let t=[...this.asyncs];this.asyncs=[],await e(t.map(r=>r()));}async emit(e){let t=e.constructor.slug;if(!this.enabled)return f.debug("EventManager disabled, not emitting",t),e;if(!this.eventExists(e))throw new Error(`Event "${t}" not registered`);let r=[],i=[];this.listeners=this.listeners.filter(o=>o.event.slug!==t?true:(o.mode==="sync"?r.push(o):i.push(async()=>await o.handler(e,o.event.slug)),!o.once)),this.collectAsyncs(i);let s=e;for(let o of r)try{let c=await o.handler(s,o.event.slug);if(typeof c<"u"){let a=s.validate(c);if(a&&a.constructor.slug===t){if(!a.returned)throw new Error(`Returned event ${a.constructor.slug} must be marked as returned.`);s=a;}}}catch(c){if(c instanceof le)this.options?.onInvalidReturn?.(s,c),f.warn(`Invalid return of event listener for "${t}": ${c.message}`);else if(this.options?.onError)this.options.onError(s,c);else throw c}return s}};var Ne=class{plugins;constructor(e=[]){this.plugins=new Set(e);}async transformResultRows(e){let t=e;for(let r of this.plugins)t=(await r.transformResult({queryId:"1",result:{rows:t}})).rows;return t}};var bo=["text","integer","real","blob","date","datetime","timestamp","boolean","json"],wo=Symbol.for("bknd:connection"),te=class{constructor(e,t={},r=[]){this.fn=t;this.plugins=r;this.kysely=e,this[wo]=true,this.pluginRunner=new Ne(r);}initialized=false;pluginRunner;supported={batching:false,softscans:true};kysely;client;async init(){this.initialized=true;}static isConnection(e){return e?e[wo]===true:false}getIntrospector(){return this.kysely.introspection}supports(e){return this.supported[e]??false}async ping(){return (await sql`SELECT 1`.execute(this.kysely)).rows.length>0}async transformResultRows(e){return await this.pluginRunner.transformResultRows(e)}async executeQueries(...e){return Promise.all(e.map(async t=>await this.kysely.executeQuery(t)))}async executeQuery(e){return (await this.executeQueries(e))[0]}getCompiled(...e){return e.map(t=>"compile"in t?t.compile():t)}async withTransformedRows(e,t){return await Promise.all(e.map(async r=>{let i=t??"rows",{[i]:s,...o}=r;return {...o,rows:await this.transformResultRows(s)}}))}validateFieldSpecType(e){if(!bo.includes(e))throw new Error(`Invalid field type "${e}". Allowed types are: ${bo.join(", ")}`);return true}toDriver(e,t){return e}fromDriver(e,t){return e}async close(){}};function Pr(n,e,t={}){return {create(...r){return new class extends n{createIntrospector(i){return new e(i,t)}}(...r)}}}var C=class extends Error{code=400;name="Exception";_context=void 0;constructor(e,t){super(e),t&&(this.code=t);}context(e){return this._context=e,this}toJSON(){return {error:this.message,type:this.name,context:this._context}}},ue=class n extends Error{constructor(t,r,i){super(t);this.details=r;this.type=i;}static with(t,r,i){throw new n(t,r,i)}toJSON(){return {type:this.type??"unknown",message:this.message,details:this.details}}};var x=class{constructor(e){this.name=e;this.name=e;}toJSON(){return {name:this.name}}};var Mr=class{constructor(e,t){this.permission=e;this.config=t;}},pt=class n{constructor(e,t=[],r=false,i=false){this.name=e;this.permissions=t;this.is_default=r;this.implicit_allow=i;}static createWithPermissionNames(e,t,r=false,i=false){return new n(e,t.map(s=>new Mr(new x(s))),r,i)}static create(e){return new n(e.name,e.permissions?.map(t=>new Mr(new x(t)))??[],e.is_default,e.implicit_allow)}};var jr=class n{permissions;roles;config;constructor(e=[],t=[],r){this.permissions=e,this.roles=t,this.config=r;}static create(e,t,r){let i=t?Ar(t,({permissions:o=[],is_default:c,implicit_allow:a},l)=>pt.createWithPermissionNames(l,o,c,a)):{},s=e.map(o=>new x(o));return new n(s,Object.values(i),r)}getPermissionNames(){return this.permissions.map(e=>e.name)}getPermissions(){return this.permissions}permissionExists(e){return !!this.permissions.find(t=>t.name===e)}setRoles(e){return this.roles=e,this}getRoles(){return this.roles}setConfig(e){return this.config={...this.config,...e},this}registerPermission(e){if(this.permissions.find(t=>t.name===e.name))throw new Error(`Permission ${e.name} already exists`);return this.permissions.push(e),this}registerPermissions(e){let t=Array.isArray(e)?e:Object.values(e);for(let r of t)this.registerPermission(r);return this}getUserRole(e){if(e&&typeof e.role=="string"){let t=this.roles?.find(r=>r.name===e?.role);if(t)return f.debug(`guard: role "${e.role}" found`),t}return f.debug("guard: role not found",{user:e}),this.getDefaultRole()}getDefaultRole(){return this.roles?.find(e=>e.is_default)}isEnabled(){return this.config?.enabled===true}hasPermission(e,t){if(!this.isEnabled())return true;let r=typeof e=="string"?e:e.name;if(f.debug("guard: checking permission",{name:r,user:{id:t?.id,role:t?.role}}),!this.permissionExists(r))throw new Error(`Permission ${r} does not exist`);let s=this.getUserRole(t);if(s){if(s.implicit_allow===true)return f.debug(`guard: role "${s.name}" has implicit allow, allowing`),true}else return f.debug("guard: user has no role, denying"),false;let o=s.permissions.find(c=>c.permission.name===r);return f.debug("guard: rolePermission, allowing?",{permission:r,role:s.name,allowing:!!o}),!!o}granted(e,t){let r=t&&"get"in t?t.get("auth")?.user:t;return this.hasPermission(e,r)}throwUnlessGranted(e,t){if(!this.granted(e,t))throw new C(`Permission "${typeof e=="string"?e:e.name}" not granted`,403)}};var Dr=class{_context=[];_enabled=true;id=Math.random().toString(36).substr(2,9);last=0;constructor(e=true){this._enabled=e;}context(e){return this._context.push(e),this}clear(){return this._context.pop(),this}reset(){return this.last=0,this}log(...e){if(!this._enabled)return this;let t=performance.now(),r=this.last===0?0:Number.parseInt(String(t-this.last)),i=" ".repeat(Math.max(this._context.length-1,0)),s=this._context.length>0?`[${this._context[this._context.length-1]}]`:"";return console.log(i,s,r,...e),this.last=t,this}};function Ri(n){return n!==null&&n.constructor.name==="Object"}function xo(n){try{return n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||Array.isArray(n)||Ri(n)}catch{return false}}function Eo(n,e){let t=[];function r(i,s,o){if(!xo(i)||!xo(s))throw new Error("Diff: Only primitive types are supported");if(i!==s)if(typeof i!=typeof s)t.push({t:"e",p:o,o:i,n:s});else if(Array.isArray(i)&&Array.isArray(s)){let c=Math.max(i.length,s.length);for(let a=0;a<c;a++)a>=i.length?t.push({t:"a",p:[...o,a],o:void 0,n:s[a]}):a>=s.length?t.push({t:"r",p:[...o,a],o:i[a],n:void 0}):r(i[a],s[a],[...o,a]);}else if(Ri(i)&&Ri(s)){let c=Object.keys(i),a=Object.keys(s),l=new Set([...c,...a]);for(let u of l)u in i?u in s?r(i[u],s[u],[...o,u]):t.push({t:"r",p:[...o,u],o:i[u],n:void 0}):t.push({t:"a",p:[...o,u],o:void 0,n:s[u]});}else t.push({t:"e",p:o,o:i,n:s});}return r(n,e,[]),t}function vo(n,e){let t=dt(n);for(let r of e)kc(t,r);return t}function kc(n,e){let{p:t,t:r,n:i}=e,s=Fc(n,t.slice(0,-1)),o=t[t.length-1];r==="a"||r==="e"?s[o]=i:r==="r"&&(Array.isArray(s)?s.splice(o,1):delete s[o]);}function Fc(n,e){let t=n;for(let r of e)t[r]===void 0&&(t[r]=typeof r=="number"?[]:{}),t=t[r];return t}function dt(n){return JSON.parse(JSON.stringify(n))}var Ir=class extends C{name="UnableToConnectException";code=HttpStatus.INTERNAL_SERVER_ERROR},V=class extends C{name="InvalidSearchParamsException";code=HttpStatus.UNPROCESSABLE_ENTITY},qr=class extends C{name="TransformRetrieveFailedException";code=HttpStatus.UNPROCESSABLE_ENTITY},O=class n extends C{name="TransformPersistFailedException";code=HttpStatus.UNPROCESSABLE_ENTITY;static invalidType(e,t,r){let i=typeof r=="object"?JSON.stringify(r):r,s=`Property "${e}" must be of type "${t}", "${i}" of type "${typeof r}" given.`;return new n(s)}static required(e){return new n(`Property "${e}" is required`)}},Br=class extends C{constructor(t,r,i){console.error("InvalidFieldConfigException",{given:r,error:i.first()});super(`Invalid Field config given for field "${t.name}": ${i.firstToString()}`);this.given=r;}name="InvalidFieldConfigException";code=HttpStatus.BAD_REQUEST},$r=class extends C{name="EntityNotDefinedException";code=HttpStatus.BAD_REQUEST;constructor(e){e?super(`Entity "${typeof e!="string"?e.name:e}" not defined`):super("Cannot find an entity that is undefined");}},So=class extends C{name="EntityNotFoundException";code=HttpStatus.NOT_FOUND;constructor(e,t){super(`Entity "${typeof e!="string"?e.name:e}" with id "${t}" not found`);}};var Ci=class extends v{static slug="mutator-insert-before";validate(e){let{entity:t}=this.params;if(!t.isValidData(e,"create"))throw $console.warn("MutatorInsertBefore.validate: invalid",{entity:t.name,data:e}),new le("EntityData","invalid");return this.clone({entity:t,data:e})}},Oi=class extends v{static slug="mutator-insert-after"},_i=class extends v{static slug="mutator-update-before";validate(e){let{entity:t,entityId:r}=this.params;if(!t.isValidData(e,"update"))throw $console.warn("MutatorUpdateBefore.validate: invalid",{entity:t.name,entityId:r,data:e}),new le("EntityData","invalid");return this.clone({entityId:r,entity:t,data:e})}},Ai=class extends v{static slug="mutator-update-after"},ki=class extends v{static slug="mutator-delete-before"},Fi=class extends v{static slug="mutator-delete-after"},ve={MutatorInsertBefore:Ci,MutatorInsertAfter:Oi,MutatorUpdateBefore:_i,MutatorUpdateAfter:Ai,MutatorDeleteBefore:ki,MutatorDeleteAfter:Fi},Pi=class extends v{static slug="repository-find-one-before"},Mi=class extends v{static slug="repository-find-one-after"},ji=class extends v{static slug="repository-find-many-before";static another="one"},Di=class extends v{static slug="repository-find-many-after"},mt={RepositoryFindOneBefore:Pi,RepositoryFindOneAfter:Mi,RepositoryFindManyBefore:ji,RepositoryFindManyAfter:Di};var Nr=class{_relations=[];constructor(e){this._relations=e;}get all(){return this._relations}exists(e){return this._relations.some(t=>t.source.entity.name===e.source.entity.name&&t.target.entity.name===e.target.entity.name&&t.type===e.type)}relationsOf(e){return this._relations.filter(t=>t.visibleFrom("source")&&t.source.entity.name===e.name||t.visibleFrom("target")&&t.target.entity.name===e.name)}sourceRelationsOf(e){return this._relations.filter(t=>t.source.entity.name===e.name)}targetRelationsOf(e){return this._relations.filter(t=>t.visibleFrom("target")&&t.target.entity.name===e.name)}listableRelationsOf(e){return this.relationsOf(e).filter(t=>t.isListableFor(e))}relationOf(e,t){return this.relationsOf(e).find(r=>r.target.entity.name===e.name&&r.source.reference===t||r.source.entity.name===e.name&&r.target.reference===t)}hasRelations(e){return this.relationsOf(e).length>0}relatedEntitiesOf(e){return this.relationsOf(e).map(t=>t.other(e).entity)}relationReferencesOf(e){return this.relationsOf(e).map(t=>t.other(e).reference)}};var Ic=["create","read","update","delete"],km=["form","table","read","submit"],qc=["create","read","update","delete","form","table","submit"];var Ro=true,Co=false,k=s.strictObject({label:s.string(),description:s.string(),required:s.boolean({default:false}),fillable:s.anyOf([s.boolean({title:"Boolean"}),s.array(s.string({enum:Ic}),{title:"Context",uniqueItems:true})]),hidden:s.anyOf([s.boolean({title:"Boolean"}),s.array(s.string({enum:qc}),{title:"Context",uniqueItems:true})]),virtual:s.boolean(),default_value:s.any()}).partial(),S=class{_required;_type;name;type="field";config;constructor(e,t){this.name=e,this._type,this._required;try{this.config=parse(this.getSchema(),t||{});}catch(r){throw r instanceof InvalidSchemaError?new Br(this,t,r):r}}getType(){return this.type}schema(){return Object.freeze({name:this.name,type:"text",nullable:true,dflt:void 0})}hasDefault(){return this.config.default_value!==void 0}getDefault(){return this.config?.default_value}isFillable(e){return Array.isArray(this.config.fillable)?e?this.config.fillable.includes(e):Ro:this.config.fillable??Ro}isHidden(e){return Array.isArray(this.config.hidden)?e?this.config.hidden.includes(e):Co:this.config.hidden??Co}isRequired(){return this.config?.required??false}isVirtual(){return this.config.virtual??false}getLabel(e){return this.config.label?this.config.label:e?.fallback!==false?snakeToPascalWithSpaces(this.name):void 0}getDescription(){return this.config.description}getValue(e,t){return e}getHtmlConfig(){return {element:"input",props:{type:"text"}}}isValid(e,t){return typeof e<"u"?this.isFillable(t):t==="create"?!this.isRequired():true}transformRetrieve(e){return e}async transformPersist(e,t,r){if(this.nullish(e)){if(this.isRequired()&&!this.hasDefault())throw O.required(this.name);return this.getDefault()}return e}toSchemaWrapIfRequired(e){return this.isRequired()?e:e.optional()}nullish(e){return e==null}toJsonSchema(){return this.toSchemaWrapIfRequired(s.any())}toType(){return {required:this.isRequired(),comment:this.getDescription(),type:"any"}}toJSON(){return {type:this.type,config:this.config}}};var qi=s.strictObject({default_value:s.boolean(),...ee(k.properties,["default_value"])}).partial(),ft=class extends S{type="boolean";getSchema(){return qi}getValue(e,t){switch(t){case "table":return e?"Yes":"No";default:return e}}schema(){return Object.freeze({...super.schema(),type:"boolean"})}getHtmlConfig(){return {...super.getHtmlConfig(),element:"boolean"}}transformRetrieve(e){return typeof e>"u"||e===null?this.isRequired()?false:this.hasDefault()?this.getDefault():null:typeof e=="string"?e==="1":!!e}async transformPersist(e,t,r){let i=await super.transformPersist(e,t,r);if(this.nullish(i))return this.isRequired()?!!this.config.default_value:void 0;if(typeof i=="number")return i!==0;if(typeof i!="boolean")throw O.invalidType(this.name,"boolean",i);return i}toJsonSchema(){return this.toSchemaWrapIfRequired(s.boolean({default:this.getDefault()}))}toType(){return {...super.toType(),type:"boolean"}}};var Bi=s.strictObject({type:s.string({enum:["date","datetime","week"],default:"date"}),timezone:s.string(),min_date:s.string(),max_date:s.string(),...k.properties}).partial(),Le=class extends S{type="date";getSchema(){return Bi}schema(){return Object.freeze({...super.schema(),type:this.config.type==="datetime"?"datetime":"date"})}getHtmlConfig(){let e=this.config.type==="datetime"?"datetime-local":this.config.type;return {...super.getHtmlConfig(),element:"date",props:{type:e}}}parseDateFromString(e){if(this.config.type==="week"&&e.includes("-W")){let[t,r]=e.split("-W").map(i=>Number.parseInt(i,10));return Lt().year(t).week(r).toDate()}return new Date(e)}getValue(e,t){if(e===null||!e)return;let r=this.parseDateFromString(e);if(t==="submit")try{return r.toISOString()}catch{return}if(this.config.type==="week")try{return `${r.getFullYear()}-W${Lt(r).week()}`}catch(i){f.warn("DateField.getValue:week error",e,String(i));return}try{let s=new Date().getTimezoneOffset(),o=new Date(r.getTime()-s*6e4);return this.formatDate(o)}catch(i){f.warn("DateField.getValue error",this.config.type,e,String(i));return}}formatDate(e){switch(this.config.type){case "datetime":return e.toISOString().split(".")[0].replace("T"," ");default:return e.toISOString().split("T")[0]}}transformRetrieve(e){let t=super.transformRetrieve(e);if(t===null)return null;try{return new Date(t)}catch{return null}}async transformPersist(e,t,r){let i=await super.transformPersist(e,t,r);if(this.nullish(i))return i;switch(this.config.type){case "date":case "week":return new Date(i).toISOString().split("T")[0];default:return new Date(i).toISOString()}}toJsonSchema(){return this.toSchemaWrapIfRequired(s.string({default:this.getDefault()}))}toType(){return {...super.toType(),type:"Date | string"}}};var $i=s.strictObject({default_value:s.string(),options:s.anyOf([s.object({type:s.literal("strings"),values:s.array(s.string())}),s.object({type:s.literal("objects"),values:s.array(s.object({label:s.string(),value:s.string()}))})]),...ee(k.properties,["default_value"])}).partial(),ht=class extends S{type="enum";constructor(e,t){if(super(e,t),this.config.default_value&&!this.isValidValue(this.config.default_value))throw new Error(`Default value "${this.config.default_value}" is not a valid option`)}getSchema(){return $i}getOptions(){let e=this.config?.options??{type:"strings",values:[]};return e.type==="strings"?e.values?.map(t=>({label:t,value:t})):e?.values}isValidValue(e){return this.getOptions().map(r=>r.value).includes(e)}getValue(e,t){if(!this.isValidValue(e))return this.hasDefault()?this.getDefault():null;switch(t){case "table":return this.getOptions().find(r=>r.value===e)?.label??e}return e}transformRetrieve(e){let t=super.transformRetrieve(e);return t===null&&this.hasDefault()?this.getDefault():this.isValidValue(t)?t:this.hasDefault()?this.getDefault():null}async transformPersist(e,t,r){let i=await super.transformPersist(e,t,r);if(this.nullish(i))return i;if(!this.isValidValue(i))throw new O(`Field "${this.name}" must be one of the following values: ${this.getOptions().map(s=>s.value).join(", ")}`);return i}toJsonSchema(){let t=(this.config?.options??{values:[]}).values?.map(r=>typeof r=="string"?r:r.value)??[];return this.toSchemaWrapIfRequired(s.string({enum:t,default:this.getDefault()}))}toType(){let e=this.getOptions().map(({value:t})=>typeof t=="string"?`"${t}"`:t);return {...super.toType(),type:e.length>0?e.join(" | "):"string"}}};var Ni=s.strictObject({default_value:s.any(),...ee(k.properties,["default_value"])}).partial(),gt=class extends S{type="json";getSchema(){return Ni}transformRetrieve(e){let t=super.transformRetrieve(e);return t===null&&this.hasDefault()?this.getDefault():this.isSerialized(t)?JSON.parse(t):t}isSerializable(e){try{let t=JSON.stringify(e);if(t===JSON.stringify(JSON.parse(t)))return !0}catch{}return false}isSerialized(e){try{if(typeof e=="string")return e===JSON.stringify(JSON.parse(e))}catch{}return false}getValue(e,t){switch(t){case "form":return e===null?"":JSON.stringify(e,null,2);case "table":return e===null?null:JSON.stringify(e);case "submit":return typeof e=="string"&&e.length===0?null:JSON.parse(e)}return e}async transformPersist(e,t,r){let i=await super.transformPersist(e,t,r);if(this.nullish(i))return i;if(!this.isSerializable(i))throw new O(`Field "${this.name}" must be serializable to JSON.`);return this.isSerialized(i)?i:JSON.stringify(i)}toType(){return {...super.toType(),type:"any"}}};var Ui=s.strictObject({schema:s.any({type:"object"}),ui_schema:s.any({type:"object"}),default_from_schema:s.boolean(),...k.properties}).partial(),wt=class extends S{type="jsonschema";validator;constructor(e,t){super(e,t),this.validator=new Validator({...this.getJsonSchema()});}getSchema(){return Ui}getJsonSchema(){return this.config?.schema}getJsonUiSchema(){return this.config.ui_schema??{}}isValid(e,t="update"){return super.isValid(e,t)?!this.isRequired()&&(!e||typeof e!="object")?true:this.validator.validate(e).valid:false}getValue(e,t){switch(t){case "form":return e===null?"":e;case "table":return e===null?null:JSON.stringify(e);}return e}transformRetrieve(e){let t=super.transformRetrieve(e);if(t===null){if(this.config.default_from_schema)try{return s.fromSchema(this.getJsonSchema()).template()}catch{return null}else if(this.hasDefault())return this.getDefault()}return t}async transformPersist(e,t,r){let i=await super.transformPersist(e,t,r);if(this.nullish(i))return i;if(!this.isValid(i))throw new O(this.name,i);return !i||typeof i!="object"?this.getDefault():JSON.stringify(i)}toJsonSchema(){let e=this.getJsonSchema()??{type:"object"};return this.toSchemaWrapIfRequired(s.fromSchema({default:this.getDefault(),...e}))}toType(){return {...super.toType(),import:[{package:"json-schema-to-ts",name:"FromSchema"}],type:`FromSchema<${_r(this.getJsonSchema(),2,1)}>`}}};var Li=s.strictObject({default_value:s.number(),minimum:s.number(),maximum:s.number(),exclusiveMinimum:s.number(),exclusiveMaximum:s.number(),multipleOf:s.number(),...ee(k.properties,["default_value"])}).partial(),ke=class extends S{type="number";getSchema(){return Li}getHtmlConfig(){return {element:"input",props:{type:"number",pattern:"d*",inputMode:"numeric"}}}schema(){return Object.freeze({...super.schema(),type:"integer"})}getValue(e,t){if(typeof e>"u"||e===null)return null;switch(t){case "submit":return Number.parseInt(e)}return e}async transformPersist(e,t,r){let i=await super.transformPersist(e,t,r);if(!this.nullish(i)&&typeof i!="number")throw O.invalidType(this.name,"number",i);if(this.config.maximum&&i>this.config.maximum)throw new O(`Field "${this.name}" cannot be greater than ${this.config.maximum}`);if(this.config.minimum&&i<this.config.minimum)throw new O(`Field "${this.name}" cannot be less than ${this.config.minimum}`);return i}toJsonSchema(){return this.toSchemaWrapIfRequired(s.number({default:this.getDefault(),minimum:this.config?.minimum,maximum:this.config?.maximum,exclusiveMinimum:this.config?.exclusiveMinimum,exclusiveMaximum:this.config?.exclusiveMaximum,multipleOf:this.config?.multipleOf}))}toType(){return {...super.toType(),type:"number"}}};var Qe={server:{default_port:1337,assets_path:"/"},data:{default_primary_field:"id"}};var Jt=["integer","uuid"],Qi=s.strictObject({format:s.string({enum:Jt,default:"integer"}),required:s.boolean({default:false}),...omitKeys(k.properties,["required"])}).partial(),pe=class extends S{type="primary";constructor(e=Qe.data.default_primary_field,t){super(e,{...t,fillable:false,required:false});}isRequired(){return false}getSchema(){return Qi}get format(){return this.config.format??"integer"}get fieldType(){return this.format==="integer"?"integer":"text"}schema(){return Object.freeze({type:this.fieldType,name:this.name,primary:true,nullable:false})}getNewValue(){if(this.format==="uuid")return uuidv7()}async transformPersist(e){throw new Error("PrimaryField: This function should not be called")}toJsonSchema(){return this.toSchemaWrapIfRequired(this.format==="integer"?s.number({writeOnly:void 0}):s.string({writeOnly:void 0}))}toType(){let e=this.format==="integer"?"number":"string";return {...super.toType(),required:true,import:[{package:"kysely",name:"Generated"}],type:`Generated<${e}>`}}};var Ki=s.strictObject({default_value:s.string(),minLength:s.number(),maxLength:s.number(),pattern:s.string(),html_config:s.partialObject({element:s.string(),props:s.record(s.anyOf([s.string({title:"String"}),s.number({title:"Number"})]))}),...ee(k.properties,["default_value"])}).partial(),Fe=class extends S{type="text";getSchema(){return Ki}getHtmlConfig(){return this.config.html_config?this.config.html_config:super.getHtmlConfig()}transformRetrieve(e){let t=super.transformRetrieve(e);return this.config.maxLength?t.substring(0,this.config.maxLength):this.isRequired()?t?t.toString():"":t}async transformPersist(e,t,r){let i=await super.transformPersist(e,t,r);if(this.nullish(i))return i;if(i!==null&&typeof i!="string"&&(i=String(i)),this.config.maxLength&&i?.length>this.config.maxLength)throw new O(`Field "${this.name}" must be at most ${this.config.maxLength} character(s)`);if(this.config.minLength&&i?.length<this.config.minLength)throw new O(`Field "${this.name}" must be at least ${this.config.minLength} character(s)`);if(this.config.pattern&&i&&!new RegExp(this.config.pattern).test(i))throw new O(`Field "${this.name}" must match the pattern ${this.config.pattern}`);return i}toJsonSchema(){return this.toSchemaWrapIfRequired(s.string({default:this.getDefault(),minLength:this.config?.minLength,maxLength:this.config?.maxLength,pattern:this.config?.pattern}))}toType(){return {...super.toType(),type:"string"}}};var xt=class{constructor(e,t,r=false,i){this.entity=e;this.fields=t;this.unique=r;this.name=i;if(t.length===0)throw new Error("Indices must contain at least one field");if(t.some(s=>!(s instanceof S)))throw new Error("All fields must be instances of Field");if(r&&!t[0]?.isRequired())throw new Error(`Unique indices must have first field as required: ${t.map(o=>o.name).join(", ")}`);i||(this.name=[r?"idx_unique":"idx",e.name,...t.map(s=>s.name)].join("_"));}toJSON(){return {entity:this.entity.name,fields:this.fields.map(e=>e.name),unique:this.unique}}};var _o={primary:{schema:Qi,field:pe},text:{schema:Ki,field:Fe},number:{schema:Li,field:ke},boolean:{schema:qi,field:ft},date:{schema:Bi,field:Le},enum:{schema:$i,field:ht},json:{schema:Ni,field:gt},jsonschema:{schema:Ui,field:wt}};var Ur=class n{constructor(e){this.em=e;}static EXCLUDE_TABLES=["libsql_wasm_func_table","sqlite_sequence","_cf_KV"];getIntrospector(){return this.em.connection.getIntrospector()}async introspect(){let e=await this.getIntrospector().getTables({withInternalKyselyTables:false}),t=await this.getIntrospector().getIndices(),r=[];for(let i of e)n.EXCLUDE_TABLES.includes(i.name)||r.push({...i,indices:t.filter(s=>s.table===i.name)});return r}getIntrospectionFromEntity(e){let t=e.getFields(false),r=this.em.getIndicesOf(e);return {name:e.name,isView:false,columns:t.map(i=>({name:i.name,dataType:"TEXT",isNullable:true,isAutoIncrementing:i instanceof pe,hasDefaultValue:false,comment:void 0})),indices:r.map(i=>({name:i.name,table:e.name,isUnique:i.unique,columns:i.fields.map(s=>({name:s.name,order:0}))}))}}async getDiff(){let e=await this.introspect(),t=this.em.entities.map(s=>this.getIntrospectionFromEntity(s)),r=[],i=s=>s.name;e.filter(s=>/bknd/.test(s.name)||s.isView?false:!t.map(o=>o.name).includes(s.name)).forEach(s=>{r.push({name:s.name,isDrop:true,isNew:false,columns:{add:[],drop:[],change:[]},indices:{add:[],drop:[]}});});for(let s of t){let o=e.find(c=>c.name===s.name);if(!o)r.push({name:s.name,isNew:true,columns:{add:s.columns.map(i),drop:[],change:[]},indices:{add:s.indices.map(i),drop:[]}});else {let c=s.columns.filter(m=>!o.columns.map(i).includes(m.name)),a=o.columns.filter(m=>!s.columns.map(i).includes(m.name)),l=[];for(let m of s.columns){let h=o.columns.find(_=>_.name===m.name),F=[];for(let[_,ce]of Object.entries(m))h&&h[_]!==ce&&F.push({attribute:_,prev:h[_],next:ce});Object.keys(F).length>0&&l.push({name:m.name,changes:F});}let u=s.indices.filter(m=>!o.indices.map(h=>h.name).includes(m.name)),p=o.indices.filter(m=>!s.indices.map(h=>h.name).includes(m.name));[c,a,u,p].some(m=>m.length>0)&&r.push({name:s.name,isNew:false,columns:{add:c.map(i),drop:a.map(i),change:[]},indices:{add:u.map(i),drop:p.map(i)}});}}return r}collectFieldSchemas(e,t){let r=[];if(t.length===0)return r;for(let i of t){let o=this.em.entity(e).getField(i).schema();o&&r.push(this.em.connection.getFieldSchema(o));}return r}async sync(e={force:false,drop:false}){let t=await this.getDiff(),i=[],s=this.em.connection.kysely.schema;for(let o of t){let c=[],a=0,l=this.collectFieldSchemas(o.name,o.columns.add),u=o.columns.drop,p=o.indices.drop;if(o.isDrop)a++,e.drop&&c.push(s.dropTable(o.name));else if(o.isNew){let d=s.createTable(o.name);for(let m of l)a++,d=d.addColumn(...m);c.push(d);}else {if(l.length>0)for(let d of l)a++,c.push(s.alterTable(o.name).addColumn(...d));if(e.drop&&u.length>0)for(let d of u)a++,c.push(s.alterTable(o.name).dropColumn(d));}for(let d of o.indices.add){let h=this.em.getIndicesOf(o.name).find(_=>_.name===d),F=s.createIndex(d).on(o.name).columns(h.fields.map(_=>_.name));h.unique&&(F=F.unique()),c.push(F),a++;}if(e.drop)for(let d of p)c.push(s.dropIndex(d)),a++;if(a!==0)for(let d of c){let{sql:m,parameters:h}=d.compile();if(i.push({sql:m,parameters:h}),e.force)try{$console.debug("[SchemaManager]",m),await d.execute();}catch(F){throw new Error(`Failed to execute query: ${m}: ${F.message}`)}}}return i}};var Ji=s.strictObject({name:s.string(),name_singular:s.string(),description:s.string(),sort_field:s.string({default:Qe.data.default_primary_field}),sort_dir:s.string({enum:["asc","desc"],default:"asc"}),primary_format:s.string({enum:Jt})}).partial(),zt=["regular","system","generated"],ko=Symbol.for("bknd:entity"),z=class n{#e;#t;name;fields;config;data;type="regular";constructor(e,t,r,i){if(typeof e!="string"||e.length===0)throw new Error("Entity name must be a non-empty string");this.name=e,this.config=parse(Ji,r||{});let s=t?.filter(o=>o instanceof pe).length??0;if(s>1)throw new Error(`Entity "${e}" has more than one primary field`);this.fields=s===1?[]:[new pe(void 0,{format:this.config.primary_format})],t&&t.forEach(o=>this.addField(o)),i&&(this.type=i),this[ko]=true;}static isEntity(e){return e?e[ko]===true:false}static create(e){return new n(e.name,e.fields,e.config,e.type)}getType(){return this.type}getSelect(e,t){return this.getFields().filter(r=>!r.isHidden(t??"read")).map(r=>e?`${e}.${r.name} as ${r.name}`:r.name)}getDefaultSort(){return {by:this.config.sort_field??"id",dir:this.config.sort_dir??"asc"}}getAliasedSelectFrom(e,t,r){let i=t??this.name;return this.getFields().filter(s=>!s.isVirtual()&&!s.isHidden(r??"read")&&e.includes(s.name)).map(s=>i?`${i}.${s.name} as ${s.name}`:s.name)}getFillableFields(e,t){return this.getFields(t).filter(r=>r.isFillable(e))}getRequiredFields(){return this.getFields().filter(e=>e.isRequired())}getDefaultObject(){return this.getFields().reduce((e,t)=>(t.hasDefault()&&(e[t.name]=t.getDefault()),e),{})}getField(e){return this.fields.find(t=>t.name===e)}__replaceField(e,t){let r=this.fields.findIndex(i=>i.name===e);if(r===-1)throw new Error(`Field "${e}" not found on entity "${this.name}"`);this.fields[r]=t;}getPrimaryField(){return this.fields[0]}id(){return this.getPrimaryField()}get label(){return this.config.name??snakeToPascalWithSpaces(this.name)}field(e){return this.getField(e)}hasField(e){let t=typeof e=="string"?e:e.name;return this.fields.findIndex(r=>r.name===t)!==-1}getFields(e=false){return e?this.fields:this.fields.filter(t=>!t.isVirtual())}addField(e){let t=this.getField(e.name);if(t){if(JSON.stringify(t)===JSON.stringify(e)){$console.warn(`Field "${e.name}" already exists on entity "${this.name}", but it's the same, so skipping.`);return}throw new Error(`Field "${e.name}" already exists on entity "${this.name}"`)}this.fields.push(e);}__setData(e){this.data=e;}isValidData(e,t,r){if(typeof e!="object"&&r?.explain)throw new Error(`Entity "${this.name}" data must be an object`);let i=this.getFillableFields(t,false);if(r?.ignoreUnknown!==true){let s=i.map(a=>a.name),c=Object.keys(e).filter(a=>!s.includes(a));if(c.length>0&&r?.explain)throw new Error(`Entity "${this.name}" data must only contain known keys, unknown: "${c}"`)}for(let s of i)if(!s.isValid(e?.[s.name],t)){if($console.warn("invalid data given for",this.name,t,s.name,e[s.name]),r?.explain)throw new Error(`Field "${s.name}" has invalid data: "${e[s.name]}"`);return false}return true}toSchema(e){let t;switch(e?.context){case "create":case "update":t=this.getFillableFields(e.context);break;default:t=this.getFields(true);}let r=Object.fromEntries(t.map(s=>[s.name,s])),i={type:"object",additionalProperties:false,properties:transformObject(r,s=>{let o=s.isFillable(e?.context);return {title:s.config.label,$comment:s.config.description,$field:s.type,readOnly:o?void 0:true,...s.toJsonSchema()}})};return e?.clean?JSON.parse(JSON.stringify(i)):i}toTypes(){return {name:this.name,type:this.type,comment:this.config.description,fields:Object.fromEntries(this.getFields().map(e=>[e.name,e.toType()]))}}toJSON(){return {type:this.type,fields:Object.fromEntries(this.fields.map(e=>[e.name,e.toJSON()])),config:this.config}}};function Se(n){return ["string","number","boolean"].includes(typeof n)}function Mo(n){return [true,false,0,1].includes(n)}var zi=class{constructor(e,t,r){this.key=e;this.valid=t;this.validate=r;}expect};function ne(n,e,t){return new zi(n,e,t)}function jo(n,e){let t=n.find(r=>r.key===e);if(!t)throw new Error(`Expression does not exist: "${e}"`);return t}var Fo="$or";function Gi(n,e,t=[]){let r=e.map(a=>a.key),i=Object.keys(n),s=[Fo],o={};if(i.some(a=>a.startsWith("$")&&!s.includes(a)))throw new Error(`Invalid key '${i}'. Keys must not start with '$'.`);if(t.length>0&&i.some(a=>s.includes(a)))throw new Error(`Operand ${Fo} can only appear at the top level.`);function c(a,l,u=[]){if(jo(e,a).valid(l)===false)throw new Error(`Invalid value at "${[...u,a].join(".")}": ${l}`)}for(let[a,l]of Object.entries(n))if(a==="$or")o.$or=Gi(l,e,[...t,a]);else if(Se(l))c("$eq",l,t),o[a]={$eq:l};else if(typeof l=="object"){let u=Object.keys(l).filter(p=>!r.includes(p));if(u.length===0){o[a]={};for(let[p,d]of Object.entries(l))c(p,d,[...t,a]),o[a][p]=d;}else throw new Error(`Invalid key(s) at "${a}": ${u.join(", ")}. Expected expressions.`)}return o}function Po(n,e,t){let r=t.convert?Gi(n,e):n,i={$and:[],$or:[],keys:new Set},{$or:s,...o}=r;function c(a,l,u,p=[]){let d=jo(e,a);if(!d)throw new Error(`Expression does not exist: "${a}"`);if(!d.valid(l))throw new Error(`Invalid expected value at "${[...p,a].join(".")}": ${l}`);return d.validate(l,u,t.exp_ctx)}for(let[a,l]of Object.entries(o))for(let[u,p]of Object.entries(l)){let d=t.value_is_kv?a:t.object[a];i.$and.push(c(u,p,d,[a])),i.keys.add(a);}for(let[a,l]of Object.entries(s??{})){let u=t.value_is_kv?a:t.object[a];for(let[p,d]of Object.entries(l))i.$or.push(c(p,d,u,[a])),i.keys.add(a);}return i}function Jc(n){let e={$and:void 0,$or:void 0};return e.$and=n.$and.every(t=>!!t),e.$or=n.$or.some(t=>!!t),!!e.$and||!!e.$or}function Do(n){return {convert:e=>Gi(e,n),build:(e,t)=>Po(e,n,t),validate:(e,t)=>{let r=Po(e,n,t);return Jc(r)},expressions:n,expressionKeys:n.map(e=>e.key)}}function de(n){if(typeof n!="string")throw new Error(`Invalid key: ${n}`);return n}var zc=[ne("$eq",n=>Se(n),(n,e,t)=>t(de(e),"=",n)),ne("$ne",n=>Se(n),(n,e,t)=>t(de(e),"!=",n)),ne("$gt",n=>Se(n),(n,e,t)=>t(de(e),">",n)),ne("$gte",n=>Se(n),(n,e,t)=>t(de(e),">=",n)),ne("$lt",n=>Se(n),(n,e,t)=>t(de(e),"<",n)),ne("$lte",n=>Se(n),(n,e,t)=>t(de(e),"<=",n)),ne("$isnull",n=>Mo(n),(n,e,t)=>t(de(e),n?"is":"is not",null)),ne("$in",n=>Array.isArray(n),(n,e,t)=>t(de(e),"in",n)),ne("$notin",n=>Array.isArray(n),(n,e,t)=>t(de(e),"not in",n)),ne("$between",n=>Array.isArray(n)&&n.length===2,(n,e,t)=>t.between(de(e),n[0],n[1])),ne("$like",n=>Se(n),(n,e,t)=>t(de(e),"like",String(n).replace(/\*/g,"%")))],Lr=Do(zc),H=class{static addClause(e,t){return Object.keys(t).length===0?e:e.where(r=>{let i=Lr.build(t,{value_is_kv:true,exp_ctx:r,convert:true});return i.$or.length>0&&i.$and.length>0?r.and(i.$and).or(r.and(i.$or)):i.$or.length>0?r.or(i.$or):r.and(i.$and)})}static convert(e){return Lr.convert(e)}static getPropertyNames(e){let{keys:t}=Lr.build(e,{value_is_kv:true,exp_ctx:()=>null,convert:true});return Array.from(t)}};var me=class{config;source;target;directions=["source","target"];static schema=s.strictObject({mappedBy:s.string().optional(),inversedBy:s.string().optional(),required:s.boolean().optional()});constructor(e,t,r={}){this.source=e,this.target=t;let i=this.constructor.schema;this.config=parse(i,r);}getReferenceQuery(e,t,r){return {}}helper(e){return new Kr(this,e)}other(e){let t=typeof e=="string"?e:e.name;if(this.source.entity.name===this.target.entity.name)return this.source.cardinality===1?this.target:this.source;if(this.source.entity.name===t)return this.target;if(this.target.entity.name===t)return this.source;throw new Error(`Entity "${t}" is not part of the relation "${this.source.entity.name} <-> ${this.target.entity.name}"`)}self(e){return this.other(e).entity.name===this.source.entity.name?this.target:this.source}ref(e){return this.source.reference===e?this.source:this.target}otherRef(e){return this.source.reference===e?this.target:this.source}visibleFrom(e){return this.directions.includes(e)}hydrate(e,t,r){let i=typeof e=="string"?e:e.name,s=this.ref(i),o=r.hydrate(s.entity.name,t);if(s.cardinality===1){if(Array.isArray(o)&&o.length>1)throw new Error(`Failed to hydrate "${s.entity.name}" with value: ${JSON.stringify(t)} (cardinality: 1)`);return o[0]}if(!o)throw new Error(`Failed to hydrate "${s.entity.name}" with value: ${JSON.stringify(t)} (cardinality: -)`);return o}isListableFor(e){return this.target.entity.name===e.name}get required(){return !!this.config.required}async $set(e,t,r){throw new Error("$set is not allowed")}async $create(e,t,r){throw new Error("$create is not allowed")}async $attach(e,t,r){throw new Error("$attach is not allowed")}async $detach(e,t,r){throw new Error("$detach is not allowed")}getName(){return [this.type().replace(":",""),this.source.entity.name,this.target.entity.name,this.config.mappedBy,this.config.inversedBy].filter(Boolean).join("_")}toJSON(){return {type:this.type(),source:this.source.entity.name,target:this.target.entity.name,config:this.config}}};var fe=class{entity;cardinality;reference;constructor(e,t,r){this.entity=e,this.cardinality=r,this.reference=t;}toJSON(){return {entity:this.entity.name,cardinality:this.cardinality,name:this.reference}}};var Wc=["cascade","set null","set default","restrict","no action"],Wi=s.strictObject({reference:s.string(),target:s.string(),target_field:s.string({default:"id"}).optional(),target_field_type:s.string({enum:["text","integer"],default:"integer"}).optional(),on_delete:s.string({enum:Wc,default:"set null"}).optional(),...k.properties}),D=class n extends S{type="relation";getSchema(){return Wi}static create(e,t,r){let i=[t.reference??t.entity.name,t.entity.getPrimaryField().name].join("_");return new n(i,{...r,required:e.required,reference:t.reference,target:t.entity.name,target_field:t.entity.getPrimaryField().name,target_field_type:t.entity.getPrimaryField().fieldType})}reference(){return this.config.reference}target(){return this.config.target}targetField(){return this.config.target_field}schema(){return Object.freeze({...super.schema(),type:this.config.target_field_type??"integer",references:`${this.config.target}.${this.config.target_field}`,onDelete:this.config.on_delete??"set null"})}transformRetrieve(e){return e}async transformPersist(e,t){throw new Error("RelationField: This function should not be called")}toJsonSchema(){return this.toSchemaWrapIfRequired(s.number({$ref:`${this.config?.target}#/properties/${this.config?.target_field}`}))}toType(){return {...super.toType(),type:"number"}}};var I={OneToOne:"1:1",ManyToOne:"n:1",ManyToMany:"m:n",Polymorphic:"poly"};var Y=class n extends me{connectionEntity;additionalFields=[];connectionTableMappedName;em;static schema=s.strictObject({connectionTable:s.string().optional(),connectionTableMappedName:s.string().optional(),...me.schema.properties});constructor(e,t,r,i){let s=r?.connectionTable||n.defaultConnectionTable(e,t),o=new fe(e,e.name),c=new fe(t,t.name);super(o,c,r),this.connectionEntity=new z(s,i,void 0,"generated"),this.connectionTableMappedName=r?.connectionTableMappedName||s,this.additionalFields=i||[];}static defaultConnectionTable(e,t){return `${e.name}_${t.name}`}type(){return I.ManyToMany}isListableFor(){return true}getField(e){let t=this.connectionEntity,r=t.fields.find(i=>i instanceof D&&i.target()===e.name);if(!r||!(r instanceof D))throw new Error(`Connection entity "${t.name}" does not have a relation to "${e.name}"`);return r}getQueryInfo(e){let t=this.other(e),r=this.connectionEntity,i=this.getField(e),s=this.getField(t.entity),o=`${e.name}.${e.getPrimaryField().name}`,c=`${r.name}.${i.name}`,a=`${r.name}.${s.name}`,l=[r.name,`${t.entity.name}.${t.entity.getPrimaryField().name}`,a],u=`${e.name}.${e.getPrimaryField().name}`;return {other:t,join:l,entityRef:o,selfRef:c,otherRef:a,groupBy:u}}getReferenceQuery(e,t){let{other:r,otherRef:i}=this.getQueryInfo(e);return {where:{[i]:t},join:[r.reference]}}buildJoin(e,t){let{other:r,join:i,entityRef:s,selfRef:o,groupBy:c}=this.getQueryInfo(e);return t.innerJoin(r.entity.name,s,o).innerJoin(...i).groupBy(c)}buildWith(e){if(!this.em)throw new Error("EntityManager not set, can't build");let t=this.em.connection.fn.jsonBuildObject;if(!t)throw new Error("Connection does not support jsonBuildObject");let r=5,{other:i,join:s,entityRef:o,selfRef:c}=this.getQueryInfo(e),a=this.connectionEntity.fields.filter(l=>!(l instanceof D||l instanceof pe));return l=>l.selectFrom(i.entity.name).select(u=>{let p=[];if(a.length>0){let d=this.connectionEntity.name;p.push(t(Object.fromEntries(a.map(m=>[m.name,u.ref(`${d}.${m.name}`)]))).as(this.connectionTableMappedName));}return p}).whereRef(o,"=",c).innerJoin(...s).limit(r)}initialize(e){this.em=e;let t=D.create(this,this.source),r=D.create(this,this.target);e.hasEntity(this.connectionEntity)?(this.connectionEntity.hasField(t)||this.connectionEntity.addField(t),this.connectionEntity.hasField(r)||this.connectionEntity.addField(r)):(this.connectionEntity.addField(t),this.connectionEntity.addField(r),e.addEntity(this.connectionEntity));}getName(){return [super.getName(),[this.connectionEntity.name,this.connectionTableMappedName].filter(Boolean)].join("_")}};var ye=class n extends me{fieldConfig;static DEFAULTS={with_limit:5};static schema=s.strictObject({sourceCardinality:s.number().optional(),with_limit:s.number({default:n.DEFAULTS.with_limit}).optional(),fieldConfig:s.object({label:s.string()}).optional(),...me.schema.properties});constructor(e,t,r={}){let i=r.mappedBy||t.name,s=r.inversedBy||e.name,o=typeof r.sourceCardinality=="number"&&r.sourceCardinality>0?r.sourceCardinality:void 0,c=new fe(e,s,o),a=new fe(t,i,1);super(c,a,r),this.fieldConfig=r.fieldConfig??{};}type(){return I.ManyToOne}initialize(e){let t=snakeToPascalWithSpaces(this.target.reference),r=D.create(this,this.target,{label:t,...this.fieldConfig});this.source.entity.field(r.name)||this.source.entity.addField(D.create(this,this.target,{label:t,...this.fieldConfig}));}getField(){let e=this.target.entity.getPrimaryField().name,t=this.source.entity.getField(`${this.target.reference}_${e}`);if(!(t instanceof D))throw new Error(`Field "${this.target.reference}_${e}" not found on entity "${this.source.entity.name}"`);return t}queryInfo(e,t){let r=this.source.reference===t?"source":"target",i=this[r],s=this[r==="source"?"target":"source"],o,c,a;r==="source"?(o=this.source.reference,c=`${o}.${this.getField().name}`,a=`${e.name}.${i.entity.getPrimaryField().name}`):(o=this.target.reference,c=`${o}.${e.getPrimaryField().name}`,a=`${e.name}.${this.getField().name}`);let l=`${e.name}.${e.getPrimaryField().name}`;return {other:s,self:i,relationRef:o,entityRef:c,otherRef:a,groupBy:l}}getReferenceQuery(e,t,r){let i=this.source.reference===r?"source":"target",s=this[i],o=this[i==="source"?"target":"source"];return {where:{[`${o.reference}_${o.entity.getPrimaryField().name}`]:t},join:o.entity.name===s.entity.name?[]:[o.entity.name]}}buildJoin(e,t,r){let{self:i,entityRef:s,otherRef:o,groupBy:c}=this.queryInfo(e,r);return t.innerJoin(i.entity.name,s,o).groupBy(c)}buildWith(e,t){let{self:r,entityRef:i,otherRef:s,relationRef:o}=this.queryInfo(e,t);return c=>c.selectFrom(`${r.entity.name} as ${o}`).whereRef(i,"=",s).$if(r.cardinality===1,a=>a.limit(1))}async $set(e,t,r){if(typeof r!="object")throw new Error(`Invalid value for relation field "${t}" given, expected object.`);let i=this.source.entity,o=this.helper(i.name).getMutationInfo();if(!o.$set)throw new Error(`Cannot perform $set for relation "${t}"`);let c=o.local_field,a=this.getField(),l=r[Object.keys(r)[0]];if(!c||!(a instanceof D))throw new Error(`Cannot perform $set for relation "${t}"`);if(l===null&&!a.isRequired())return [c,null];if(!(await e.repository(a.target()).exists({[a.targetField()]:l})).data.exists){let p=a.targetField();throw new Error(`Cannot connect "${i.name}.${t}" to "${a.target()}.${p}" = "${l}": not found.`)}return [c,l]}};var ze=class extends ye{constructor(e,t,r){let{mappedBy:i,inversedBy:s,required:o}=r||{};super(e,t,{mappedBy:i,inversedBy:s,sourceCardinality:1,required:o});}type(){return I.OneToOne}isListableFor(){return false}async $set(e,t,r){throw new Error("$set is not allowed")}async $create(e,t,r){if(r===null||typeof r!="object")throw new Error(`Invalid value for relation field "${t}" given, expected object.`);let i=this.other(this.source.entity).entity,o=this.helper(this.source.entity.name).getMutationInfo(),c=o.primary,a=o.local_field;if(!o.$create||!c||!a)throw new Error(`Cannot perform $create for relation "${t}"`);try{let{data:l}=await e.mutator(i).insertOne(r),u=l[c];return [a,u]}catch{throw new Error(`Error performing $create on "${i.name}".`)}}};var Pe=class extends me{static schema=s.strictObject({targetCardinality:s.number().optional(),...me.schema.properties});constructor(e,t,r={}){let i=r.mappedBy||t.name,s=r.inversedBy||e.name,o=typeof r.targetCardinality=="number"&&r.targetCardinality>0?r.targetCardinality:void 0,c=new fe(e,s,1),a=new fe(t,i,o);super(c,a,r),this.directions=["source"];}type(){return I.Polymorphic}queryInfo(e){let t=this.other(e),r=`${t.entity.name}.${this.getReferenceField().name}`,i=`${e.name}.${this.config.mappedBy}`,s=`${t.entity.name}.${this.config.mappedBy}`,o=`${e.name}.${e.getPrimaryField().name}`,c=`${t.entity.name}.${this.getEntityIdField().name}`,a=`${e.name}.${e.getPrimaryField().name}`;return {other:t,whereLhs:r,reference:i,reference_other:s,entityRef:o,otherRef:c,groupBy:a}}buildJoin(e,t){let{other:r,whereLhs:i,reference:s,entityRef:o,otherRef:c,groupBy:a}=this.queryInfo(e);return t.innerJoin(r.entity.name,l=>l.onRef(o,"=",c).on(i,"=",s)).groupBy(a)}getReferenceQuery(e,t){let r=this.queryInfo(e);return {where:{[this.getReferenceField().name]:r.reference_other,[this.getEntityIdField().name]:t}}}buildWith(e){let{other:t,whereLhs:r,reference:i,entityRef:s,otherRef:o}=this.queryInfo(e);return c=>c.selectFrom(t.entity.name).where(r,"=",i).whereRef(s,"=",o).$if(t.cardinality===1,a=>a.limit(1))}isListableFor(e){return this.source.entity.name===e.name&&this.target.cardinality!==1}getReferenceField(){return new Fe("reference",{hidden:true,fillable:["create"]})}getEntityIdField(){return new ke("entity_id",{hidden:true,fillable:["create"]})}initialize(e){let t=this.getReferenceField(),r=this.getEntityIdField();this.target.entity.field(t.name)||this.target.entity.addField(t),this.target.entity.field(r.name)||this.target.entity.addField(r);}};var Hi=["$set","$create","$attach","$detach"],Kr=class{relation;access;self;other;constructor(e,t){if(this.relation=e,e.source.entity.name===t)this.access="source",this.self=e.source,this.other=e.target;else if(e.target.entity.name===t)this.access="target",this.self=e.target,this.other=e.source;else throw new Error(`Entity "${t}" is not part of the relation "${e.source.entity.name} <-> ${e.target.entity.name}"`)}getMutationInfo(){let e={$set:false,$create:false,$attach:false,$detach:false},t,r;switch(this.relation.type()){case I.ManyToOne:typeof this.self.cardinality>"u"&&this.other.cardinality===1&&(e.$set=true,t=this.relation.getField()?.name,r=this.other.entity.getPrimaryField().name);break;case I.OneToOne:this.access==="source"&&(e.$create=true,e.$set=true,t=this.relation.getField()?.name,r=this.other.entity.getPrimaryField().name);break;case I.ManyToMany:this.access==="source"&&(e.$attach=true,e.$detach=true,r=this.other.entity.getPrimaryField().name);break}return {reference:this.other.reference,local_field:t,...e,primary:r,cardinality:this.other.cardinality,relation_type:this.relation.type()}}};var Jr=class{constructor(e,t){this.entity=e;this.em=t;}getRelationalKeys(){let e=[];return this.entity.type==="generated"&&this.em.relations.all.find(r=>r instanceof Y&&r.connectionEntity.name===this.entity.name)instanceof Y&&e.push(...this.entity.fields.filter(r=>r.type==="relation").map(r=>r.name)),this.em.relationsOf(this.entity.name).map(t=>{let r=t.helper(this.entity.name).getMutationInfo();e.push(r.reference),r.local_field&&e.push(r.local_field);}),e}async persistRelationField(e,t,r){if(r===null&&!e.isRequired())return [t,r];if(typeof r=="object")throw new Error(`Invalid value for relation field "${t}" given, expected primitive.`);if(!(await this.em.repository(e.target()).exists({[e.targetField()]:r})).data.exists){let s=e.targetField();throw new Error(`Cannot connect "${this.entity.name}.${t}" to "${e.target()}.${s}" = "${r}": not found.`)}return [t,r]}async persistReference(e,t,r){if(typeof r!="object"||r===null||typeof r>"u")throw new Error(`Invalid value for relation "${t}" given, expected object to persist reference. Like '{$set: {id: 1}}'.`);let i=Object.keys(r)[0];if(!Hi.includes(i))throw new Error(`Invalid operation "${i}" for relation "${t}". Allowed: ${Hi.join(", ")}`);let s=r[i];return await e[i](this.em,t,s)}async persistRelation(e,t){let r=this.entity.getField(e);if(r instanceof D)return this.persistRelationField(r,e,t);let i=this.em.relationOf(this.entity.name,e);if(i)return this.persistReference(i,e,t);throw new Error(`Relation "${e}" failed to resolve on entity "${this.entity.name}": Unable to resolve relation origin.`)}};var Yi={[I.OneToOne]:{schema:ze.schema,cls:ze},[I.ManyToOne]:{schema:ye.schema,cls:ye},[I.ManyToMany]:{schema:Y.schema,cls:Y},[I.Polymorphic]:{schema:Pe.schema,cls:Pe}},qo={relation:{schema:Wi,field:D}};var Et=class{constructor(e,t={}){this.conn=e;this.options=t;}results=[];time=0;get(){if(!this.results)throw new Error("Result not executed");return Array.isArray(this.results)?this.results??[]:this.results[0]}first(){let e=this.get();return (Array.isArray(e)?e[0]:e)??{}}get sql(){return this.first().sql}get parameters(){return this.first().parameters}get data(){return this.options.single?this.first().data?.[0]:this.first().data??[]}async execute(e){let t=Array.isArray(e)?e:[e];for(let r of t){let i=r.compile();await this.options.beforeExecute?.(i);try{let s=performance.now(),o=await this.conn.executeQuery(i);this.time=Number.parseFloat((performance.now()-s).toFixed(2)),this.results.push({...o,data:this.options.hydrator?.(o.rows),items:o.rows.length,time:this.time,sql:i.sql,parameters:[...i.parameters]});}catch(s){if(this.options.onError)await this.options.onError(s);else throw s}}return this}additionalMetaKeys(){return []}toJSON(){let{rows:e,data:t,...r}=this.first(),i=A()?["items","time","sql","parameters"]:["items","time"],s=io(r,[...i,...this.additionalMetaKeys()]);return {data:this.data,meta:s}}};var zr=class extends Et{constructor(t,r,i){let s=i?.logParams===void 0?A():i.logParams;super(t.connection,{hydrator:o=>t.hydrate(r.name,o),beforeExecute:o=>{i?.silent||f.debug(`[Mutation]
${o.sql}
`,s?o.parameters:void 0);},onError:o=>{if(!i?.silent)throw f.error("[ERROR] Mutator:",o.message),o},...i});this.em=t;this.entity=r;}};var Gr=class n{constructor(e,t,r){this.em=e;this.entity=t;this.options=r;this.emgr=r?.emgr??new $(ve);}static Events=ve;emgr;__unstable_disable_system_entity_creation=true;__unstable_toggleSystemEntityCreation(e){this.__unstable_disable_system_entity_creation=e;}get conn(){return this.em.connection.kysely}async getValidatedData(e,t){let r=this.entity;if(!t)throw new Error("Context must be provided for validation");let i=Object.keys(e),s={},o=new Jr(r,this.em),c=o.getRelationalKeys();for(let a of i){if(c.includes(a)){let u=await o.persistRelation(a,e[a]);if(Array.isArray(u)){let[p,d]=u;s[p]=d;}continue}let l=r.getField(a);if(!l)throw new Error(`Field "${a}" not found on entity "${r.name}". Fields: ${r.getFillableFields().map(u=>u.name).join(", ")}`);if(!l.isFillable(t))throw new Error(`Field "${a}" is not fillable on entity "${r.name}"`);s[a]=await l.transformPersist(e[a],this.em,t),s[a]=this.em.connection.toDriver(s[a],l);}if(Object.keys(s).length===0)throw new Error(`No data left to update "${r.name}"`);return s}async performQuery(e,t){return await new zr(this.em,this.entity,{silent:false,...t}).execute(e)}async insertOne(e){let t=this.entity;if(t.type==="system"&&this.__unstable_disable_system_entity_creation)throw new Error(`Creation of system entity "${t.name}" is disabled`);let r=await this.emgr.emit(new n.Events.MutatorInsertBefore({entity:t,data:e})),i=r.returned?r.params.data:e,s=await this.getValidatedData({...t.getDefaultObject(),...i},"create"),o=t.getRequiredFields();for(let p of o)if(typeof s[p.name]>"u"||s[p.name]===null)throw new Error(`Field "${p.name}" is required`);let c=t.getPrimaryField(),a=c.getNewValue();a&&(s={[c.name]:a,...s});let l=this.conn.insertInto(t.name).values(s).returning(t.getSelect()),u=await this.performQuery(l,{single:true});return await this.emgr.emit(new n.Events.MutatorInsertAfter({entity:t,data:u.data,changed:s})),u}async updateOne(e,t){let r=this.entity;if(!e)throw new Error("ID must be provided for update");let i=await this.emgr.emit(new n.Events.MutatorUpdateBefore({entity:r,entityId:e,data:t})),s=i.returned?i.params.data:t,o=await this.getValidatedData(s,"update"),c=this.conn.updateTable(r.name).set(o).where(r.id().name,"=",e).returning(r.getSelect()),a=await this.performQuery(c,{single:true});return await this.emgr.emit(new n.Events.MutatorUpdateAfter({entity:r,entityId:e,data:a.data,changed:o})),a}async deleteOne(e){let t=this.entity;if(!e)throw new Error("ID must be provided for deletion");await this.emgr.emit(new n.Events.MutatorDeleteBefore({entity:t,entityId:e}));let r=this.conn.deleteFrom(t.name).where(t.id().name,"=",e).returning(t.getSelect()),i=await this.performQuery(r,{single:true});return await this.emgr.emit(new n.Events.MutatorDeleteAfter({entity:t,entityId:e,data:i.data})),i}getValidOptions(e){let t=this.entity,r={};if(e?.where){let i=H.getPropertyNames(e.where).filter(s=>typeof t.getField(s)>"u");if(i.length>0)throw new V(`Invalid where field(s): ${i.join(", ")}`);r.where=e.where;}return r}appendWhere(e,t){let r=this.entity;r.name;if(t){let o=H.getPropertyNames(t).filter(c=>typeof r.getField(c)>"u");if(o.length>0)throw new V(`Invalid where field(s): ${o.join(", ")}`);return H.addClause(e,t)}return e}async deleteWhere(e){let t=this.entity;if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error("Where clause must be provided for mass deletion");let r=this.appendWhere(this.conn.deleteFrom(t.name),e).returning(t.getSelect());return await this.performQuery(r)}async updateWhere(e,t){let r=this.entity,i=await this.getValidatedData(e,"update");if(!t||typeof t!="object"||Object.keys(t).length===0)throw new Error("Where clause must be provided for mass update");let s=this.appendWhere(this.conn.updateTable(r.name),t).set(i).returning(r.getSelect());return await this.performQuery(s)}async insertMany(e){let t=this.entity;if(t.type==="system"&&this.__unstable_disable_system_entity_creation)throw new Error(`Creation of system entity "${t.name}" is disabled`);let r=[];for(let s of e){let o={...t.getDefaultObject(),...await this.getValidatedData(s,"create")},c=t.getRequiredFields();for(let a of c)if(typeof o[a.name]>"u"||o[a.name]===null)throw new Error(`Field "${a.name}" is required`);r.push(o);}let i=this.conn.insertInto(t.name).values(r).returning(t.getSelect());return await this.performQuery(i)}};var Vr=s.string({pattern:"^(?:[a-zA-Z_$][\\w$]*)(?:,[a-zA-Z_$][\\w$]*)*$"}),Bo=s.anyOf([Vr,s.array(Vr,{uniqueItems:true})],{default:[],coerce:n=>Array.isArray(n)?n:typeof n=="string"?n.includes(",")?n.split(","):[n]:[]}),Wr={by:"id",dir:"asc"},Hc=s.object({by:s.string(),dir:s.string({enum:["asc","desc"]}).optional()}).strict(),Yc=s.anyOf([s.string(),Hc],{default:Wr,coerce:n=>{if(typeof n=="string"){if(/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(n)){let e=n[0]==="-"?"desc":"asc";return {by:e==="desc"?n.slice(1):n,dir:e}}else if(/^{.*}$/.test(n))return {...Wr,...JSON.parse(n)};return f.warn(`Invalid sort given: '${JSON.stringify(n)}'`),Wr}else if($e(n))return {...Wr,...n};return n}}),Xc=s.anyOf([s.string(),s.object({})],{default:{},examples:[{attribute:{$eq:1}}],coerce:n=>{let e=typeof n=="string"?JSON.parse(n):n;return H.convert(e)}}),Zc=n=>s.anyOf([Vr,s.array(Vr),n],{coerce:function(e,t={}){let r=e;if(typeof r=="string"&&(r.match(/^\{/)||r.match(/^\[/)?r=JSON.parse(r):r.includes(",")?r=r.split(","):r=[r]),Array.isArray(r)&&(r=r.reduce((i,s)=>(i[s]={},i),{})),$e(r))for(let i in r)r[i]=n.coerce(r[i],t);return r}}),ie=s.recursive(n=>s.object({limit:s.number({default:10}),offset:s.number({default:0}),sort:Yc,where:Xc,select:Bo,join:Bo,with:Zc(n)}).partial()),$o=()=>ie.template({},{withOptional:true});var Wt=class n{static buildClause(e,t,r,i){let s=e.relationOf(r.name,i);if(!s)throw new Error(`Relation "${i}" not found`);return s.buildJoin(r,t,i)}static getJoinedEntityNames(e,t,r){return r.flatMap(i=>{let s=e.relationOf(t.name,i);if(!s)throw new Error(`Relation "${i}" not found`);let o=s.other(t);return s instanceof ye?[o.entity.name]:s instanceof Y?[o.entity.name,s.connectionEntity.name]:[]})}static addClause(e,t,r,i){if(i.length===0)return t;let s=t;for(let o of i)s=n.buildClause(e,s,r,o);return s}};var Hr=class extends Et{constructor(t,r,i){super(t.connection,{hydrator:s=>t.hydrate(r.name,s),beforeExecute:s=>{i?.silent||f.debug(`Query:
${s.sql}
`,s.parameters);},onError:s=>{if(i?.silent!==true)throw f.error("Repository:",String(s)),s},...i});this.em=t;this.entity=r;}shouldIncludeCounts(t){return t===void 0?this.conn.supports("softscans"):t}async execute(t,r){if(this.shouldIncludeCounts(r?.includeCounts)){let s=(l="count")=>this.conn.kysely.fn.countAll().as(l),o=t.clearSelect().select(s()).clearLimit().clearOffset().clearGroupBy().clearOrderBy(),c=this.conn.kysely.selectFrom(this.entity.name).select(s()),a=t.compile();this.options.beforeExecute?.(a);try{let l=performance.now(),[u,p,d]=await this.em.connection.executeQueries(a,o,c);this.time=Number.parseFloat((performance.now()-l).toFixed(2)),this.results.push({...u,data:this.options.hydrator?.(u.rows),items:u.rows.length,count:Ei(p.rows[0]?.count??0),total:Ei(d.rows[0]?.count??0),time:this.time,sql:a.sql,parameters:[...a.parameters]});}catch(l){if(this.options.onError)await this.options.onError(l);else throw l}return this}return await super.execute(t)}get count(){return this.first().count}get total(){return this.first().total}additionalMetaKeys(){return ["count","total"]}};var Yr=class n{constructor(e,t,r={}){this.em=e;this.entity=t;this.options=r;this.emgr=r?.emgr??new $(ve);}static Events=mt;emgr;cloneFor(e,t={}){return new n(this.em,this.em.entity(e),{...this.options,...t,emgr:this.emgr})}get conn(){return this.em.connection.kysely}checkIndex(e,t,r){!this.em.getIndexedFields(e).map(s=>s.name).includes(t)&&this.options?.silent!==true&&f.warn(`Field "${e}.${t}" used in "${r}" is not indexed`);}getValidOptions(e){let t=this.entity,r={...structuredClone($o()),sort:t.getDefaultSort(),select:t.getSelect()};if(!e)return r;if(e.sort){if(!r.select.includes(e.sort.by))throw new V(`Invalid sort field "${e.sort.by}"`);if(!["asc","desc"].includes(e.sort.dir))throw new V(`Invalid sort direction "${e.sort.dir}"`);this.checkIndex(t.name,e.sort.by,"sort"),r.sort={dir:e.sort.dir??"asc",by:e.sort.by};}if(e.select&&e.select.length>0){let i=e.select.filter(s=>!r.select.includes(s));if(i.length>0)throw new V(`Invalid select field(s): ${i.join(", ")}`).context({entity:t.name,valid:r.select});r.select=e.select;}if(e.with){Vt.validateWiths(this.em,t.name,e.with);r.with=e.with;}if(e.join&&e.join.length>0)for(let i of e.join){if(!this.em.relationOf(t.name,i))throw new V(`JOIN: "${i}" is not a relation of "${t.name}"`);r.join.push(i);}if(e.where){let i=[t.name];r.join?.length>0&&i.push(...Wt.getJoinedEntityNames(this.em,t,r.join));let s=H.getPropertyNames(e.where).filter(o=>{if(o.includes(".")){let[c,a]=o.split(".");return i.includes(c)?(this.checkIndex(c,a,"where"),!this.em.entity(c).getField(a)):true}return this.checkIndex(t.name,o,"where"),typeof t.getField(o)>"u"});if(s.length>0)throw new V(`Invalid where field(s): ${s.join(", ")}`).context({aliases:i,entity:t.name});r.where=e.where;}return e.limit&&(r.limit=e.limit),e.offset&&(r.offset=e.offset),r}async performQuery(e,t,r){return await new Hr(this.em,this.entity,{silent:this.options.silent,...t}).execute(e,{includeCounts:r?.includeCounts??this.options.includeCounts})}async triggerFindBefore(e,t){let r=t.limit===1?n.Events.RepositoryFindOneBefore:n.Events.RepositoryFindManyBefore;await this.emgr.emit(new r({entity:e,options:t}));}async triggerFindAfter(e,t,r){t.limit===1?await this.emgr.emit(new n.Events.RepositoryFindOneAfter({entity:e,options:t,data:r})):await this.emgr.emit(new n.Events.RepositoryFindManyAfter({entity:e,options:t,data:r}));}async single(e,t){await this.triggerFindBefore(this.entity,t);let r=await this.performQuery(e,{single:true});return await this.triggerFindAfter(this.entity,t,r.data),r}addOptionsToQueryBuilder(e,t,r){let i=this.entity,s=e??this.conn.selectFrom(i.name),o=r?.validate!==false?this.getValidOptions(t):t;if(!o)return s;let c=r?.alias??i.name,a=p=>`${c}.${p}`,l=r?.ignore??[],u={limit:10,offset:0,...r?.defaults};return !l.includes("select")&&o.select&&(s=s.select(i.getAliasedSelectFrom(o.select,c))),!l.includes("with")&&o.with&&(s=Vt.addClause(this.em,s,i,o.with)),!l.includes("join")&&o.join&&(s=Wt.addClause(this.em,s,i,o.join)),!l.includes("where")&&o.where&&(s=H.addClause(s,o.where)),l.includes("limit")||(s=s.limit(o.limit??u.limit),l.includes("offset")||(s=s.offset(o.offset??u.offset))),l.includes("sort")||(s=s.orderBy(a(o.sort?.by??"id"),o.sort?.dir??"asc")),s}buildQuery(e,t=[]){let r=this.entity,i=this.getValidOptions(e);return {qb:this.addOptionsToQueryBuilder(void 0,i,{ignore:t,alias:r.name,validate:false}),options:i}}async findId(e,t){let{qb:r,options:i}=this.buildQuery({...t,where:{[this.entity.getPrimaryField().name]:e},limit:1},["offset","sort"]);return this.single(r,i)}async findOne(e,t){let{qb:r,options:i}=this.buildQuery({...t,where:e,limit:1});return await this.single(r,i)}async findMany(e){let{qb:t,options:r}=this.buildQuery(e);await this.triggerFindBefore(this.entity,r);let i=await this.performQuery(t);return await this.triggerFindAfter(this.entity,r,i.data),i}async findManyByReference(e,t,r){let i=this.entity,o=this.em.relations.listableRelationsOf(i).find(u=>u.ref(t).reference===t);if(!o)throw new Error(`Relation "${t}" not found or not listable on entity "${i.name}"`);let c=o.other(i).entity,a=o.getReferenceQuery(c,e,t);if(!("where"in a)||Object.keys(a.where).length===0)throw new Error(`Invalid reference query for "${t}" on entity "${c.name}"`);let l={...r,...a,where:{...a.where,...r?.where??{}}};return this.cloneFor(c).findMany(l)}async count(e){let t=this.entity,r=this.getValidOptions({where:e}),i=this.conn.fn.count(sql`*`).as("count"),s=this.conn.selectFrom(t.name).select(i);return r.where&&(s=H.addClause(s,r.where)),await this.performQuery(s,{hydrator:o=>({count:o[0]?.count??0})},{includeCounts:false})}async exists(e){let t=this.entity,r=this.getValidOptions({where:e}),i=this.conn.fn.count(sql`*`).as("count"),s=this.conn.selectFrom(t.name).select(i);return s=H.addClause(s,r.where).limit(1),await this.performQuery(s,{hydrator:o=>({exists:o[0]?.count>0})})}};var Vt=class n{static addClause(e,t,r,i){if(!i||!$e(i))return console.warn(`'withs' undefined or invalid, given: ${JSON.stringify(i)}`),t;let s=e.connection.fn,o=t;for(let[c,a]of Object.entries(i)){let l=e.relationOf(r.name,c);if(!l)throw new Error(`Relation "${r.name}<>${c}" not found`);let u=l.ref(c).cardinality,p=u===1?s.jsonObjectFrom:s.jsonArrayFrom;if(!p)throw new Error("Connection does not support jsonObjectFrom/jsonArrayFrom");let d=l.other(r);o=o.select(m=>{let h=l.buildWith(r,c)(m);return a&&(h=e.repo(d.entity).addOptionsToQueryBuilder(h,a,{ignore:["with","join",u===1?"limit":void 0].filter(Boolean)})),a.with&&(h=n.addClause(e,h,d.entity,a.with)),p(h).as(d.reference)});}return o}static validateWiths(e,t,r){let i=0;if(!r||!$e(r))return r&&console.warn(`'withs' invalid, given: ${JSON.stringify(r)}`),i;let s=[];for(let[o,c]of Object.entries(r)){if(!e.relationOf(t,o))throw new V(`WITH: "${o}" is not a relation of "${t}"`);i++,"with"in c&&s.push(n.validateWiths(e,o,c.with));}return s.length>0&&(i+=Math.max(...s)),i}};var Me=class n{connection;_entities=[];_relations=[];_indices=[];_schema;emgr;static Events={...ve,...mt};constructor(e,t,r=[],i=[],s){if(e.forEach(o=>this.addEntity(o)),r.forEach(o=>this.addRelation(o)),i.forEach(o=>this.addIndex(o)),!te.isConnection(t))throw new Ir("");this.connection=t,this.emgr=s??new $,this.emgr.registerEvents(n.Events);}fork(){return new n(this._entities,this.connection,this._relations,this._indices)}clear(){return this._entities=[],this._relations=[],this._indices=[],this}get entities(){return this._entities}get relations(){return new Nr(this._relations)}get indices(){return this._indices}async ping(){return (await sql`SELECT 1`.execute(this.connection.kysely)).rows.length>0}addEntity(e){let t=this.entities.find(r=>r.name===e.name);if(t){if(JSON.stringify(t)===JSON.stringify(e)){$console.warn(`Entity "${e.name}" already exists, but it's the same, skipping adding it.`);return}throw new Error(`Entity "${e.name}" already exists`)}this.entities.push(e);}__replaceEntity(e,t=e.name){let r=this._entities.findIndex(i=>i.name===t);if(r===-1)throw new Error(`Entity "${t}" not found and cannot be replaced`);this._entities[r]=e;}entity(e,t){let r=this.entities.find(i=>z.isEntity(e)?i.name===e.name:i.name===e);if(!r){if(t===true)return;throw new $r(z.isEntity(e)?e.name:e)}return r}hasEntity(e){let t=typeof e=="string"?e:e.name;return this.entities.some(r=>r.name===t)}hasIndex(e){let t=typeof e=="string"?e:e.name;return this.indices.some(r=>r.name===t)}getIndexedFields(e){let t=this.entity(e),r=this.getIndicesOf(t),i=t.fields.filter(o=>o.type==="relation"),s=r.map(o=>o.fields[0]);return [t.getPrimaryField(),...i,...s].filter(Boolean)}addRelation(e){if(!this.entity(e.source.entity.name)||!this.entity(e.target.entity.name))throw new Error("Relation source or target entity not found");if(this._relations.find(r=>{let i=r.source.entity.name===e.source.entity.name&&r.target.entity.name===e.target.entity.name,s=r.source.reference===e.source.reference&&r.target.reference===e.target.reference;return i&&s}))throw new Error(`Relation "${e.type}" between "${e.source.entity.name}" and "${e.target.entity.name}" already exists`);this._relations.push(e),e.initialize(this);}relationsOf(e){return this.relations.relationsOf(this.entity(e))}relationOf(e,t){return this.relations.relationOf(this.entity(e),t)}hasRelations(e){return this.relations.hasRelations(this.entity(e))}relatedEntitiesOf(e){return this.relations.relatedEntitiesOf(this.entity(e))}relationReferencesOf(e){return this.relations.relationReferencesOf(this.entity(e))}repository(e,t={}){return this.repo(e,t)}repo(e,t={}){return new Yr(this,this.entity(e),{...t,emgr:this.emgr})}mutator(e){return new Gr(this,this.entity(e),{emgr:this.emgr})}addIndex(e,t=false){if(this.indices.find(r=>r.name===e.name)){if(t)throw new Error(`Index "${e.name}" already exists`);return}this._indices.push(e);}getIndicesOf(e){let t=z.isEntity(e)?e:this.entity(e);return this.indices.filter(r=>r.entity.name===t.name)}schema(){return this._schema||(this._schema=new Ur(this)),this._schema}hydrate(e,t){let r=this.entity(e),i=[];for(let s of t){for(let[o,c]of Object.entries(s)){let a=r.getField(o);if(!a||a.isVirtual()){let l=this.relationOf(e,o);if(l){if(!c)continue;c=l.hydrate(o,Array.isArray(c)?c:[c],this),s[o]=c;continue}else if(a?.isVirtual())continue;throw new Error(`Field "${o}" not found on entity "${r.name}"`)}try{c===null&&a.hasDefault()&&(s[o]=a.getDefault()),c=this.connection.fromDriver(c,a),s[o]=a.transformRetrieve(c);}catch(l){throw new qr(`"${a.type}" field "${o}" on entity "${r.name}": ${l.message}`)}}i.push(s);}return i}toJSON(){return {entities:Object.fromEntries(this.entities.map(e=>[e.name,e.toJSON()])),relations:Object.fromEntries(this.relations.all.map(e=>[e.getName(),e.toJSON()])),indices:Object.fromEntries(this.indices.map(e=>[e.name,e.toJSON()]))}}};var Xr=class extends te{name="dummy";supported={batching:true};constructor(){super(void 0);}getFieldSchema(e,t){throw new Error("Method not implemented.")}};var Xi=s.strictObject({entity:s.string(),min_items:s.number(),max_items:s.number(),mime_types:s.array(s.string()),...k.properties}).partial(),Te=class extends S{type="media";constructor(e,t){super(e,{...t,fillable:["update"],virtual:true});}getSchema(){return Xi}getMaxItems(){return this.config.max_items}getMinItems(){return this.config.min_items}schema(){}toJsonSchema(){let e="../schema.json#/properties/media",t=this.config?.min_items,r=this.config?.max_items;return r===1?{$ref:e}:{type:"array",items:{$ref:e},minItems:t,maxItems:r}}};var Zr={text:n=>new Fe(n.field_name,{...n.config,required:n.is_required}),number:n=>new ke(n.field_name,{...n.config,required:n.is_required}),date:n=>new Le(n.field_name,{...n.config,required:n.is_required}),datetime:n=>new Le(n.field_name,{...n.config,required:n.is_required}),boolean:n=>new ft(n.field_name,{...n.config,required:n.is_required}),enumm:n=>new ht(n.field_name,{...n.config,required:n.is_required}),json:n=>new gt(n.field_name,{...n.config,required:n.is_required}),jsonSchema:n=>new wt(n.field_name,{...n.config,required:n.is_required}),media:n=>new Te(n.field_name,{...n.config,entity:n.entity.name,required:n.is_required}),medium:n=>new Te(n.field_name,{...n.config,entity:n.entity.name,required:n.is_required})},N=class{constructor(e,t,r){this.type=e;this.config=t;this.is_required=r;}required(){return this.is_required=true,this}getField(e){if(!Zr[this.type])throw new Error(`Unknown field type: ${this.type}`);try{return Zr[this.type](e)}catch(t){throw new Error(`Faild to construct field "${this.type}": ${t}`)}}make(e){if(!Zr[this.type])throw new Error(`Unknown field type: ${this.type}`);try{return Zr[this.type]({entity:{name:"unknown",fields:{}},field_name:e,config:this.config,is_required:this.is_required})}catch(t){throw new Error(`Faild to construct field "${this.type}": ${t}`)}}};function se(n){return new N("text",n,false)}function St(n){return new N("number",n,false)}function rl(n){return new N("date",{...n,type:"date"},false)}function Tt(n){return new N("date",{...n,type:"datetime"},false)}function nl(n){return new N("date",{...n,type:"week"},false)}function es(n){return new N("boolean",n,false)}function Rt(n){let t={options:{type:typeof n?.enum?.[0]!="string"?"objects":"strings",values:n?.enum??[]}};return new N("enumm",t,false)}function ts(n){return new N("json",n,false)}function rs(n){return new N("jsonSchema",n,false)}function il(n){return new N("media",n,false)}function sl(n){return new N("media",{...n,max_items:1},false)}function ns(n,e){if(e instanceof N)return e.make(n);throw new Error("Invalid field")}function Ge(n,e,t,r){let i=[];for(let[s,o]of Object.entries(e)){let c=o,a={entity:{name:n,fields:e},field_name:s,config:c.config,is_required:c.is_required};i.push(c.getField(a));}return new z(n,i,t,r)}function Uo(n){return {manyToOne:(e,t)=>new ye(n,e,t),oneToOne:(e,t)=>new ze(n,e,t),manyToMany:(e,t,r)=>{let i=[];if(r){let s=r,o=[],c=t?.connectionTable??Y.defaultConnectionTable(n,e);for(let[a,l]of Object.entries(r)){let u=l,p={entity:{name:c,fields:s},field_name:a,config:u.config,is_required:u.is_required};o.push(u.getField(p));}i.push(o);}return new Y(n,e,t,i)},polyToOne:(e,t)=>new Pe(n,e,{...t,targetCardinality:1}),polyToMany:(e,t)=>new Pe(n,e,t)}}function Lo(n){return {on:(e,t)=>{let r=e.map(i=>{let s=n.field(i);if(!s)throw new Error(`Field "${String(i)}" not found on entity "${n.name}"`);return s});return new xt(n,r,t)}}}var Zi=class extends Me{constructor(t,r=[],i=[]){super(Object.values(t),new Xr,r,i);this.__entities=t;}withConnection(t){return new Me(this.entities,t,this.relations.all,this.indices)}};function Ht(n,e){let t=[],r=[],i=c=>new Proxy(Uo(c),{get(a,l){return (...u)=>(t.push(a[l](...u)),i(c))}}),s=c=>new Proxy(Lo(c),{get(a,l){return (...u)=>(r.push(a[l](...u)),s(c))}});e&&e({relation:i,index:s},n);let o=new Zi(n,t,r);return {DB:o.__entities,entities:o.__entities,relations:t,indices:r,proto:o,toJSON:()=>o.toJSON()}}var is=[{version:1,up:async n=>n},{version:2,up:async(n,{db:e})=>n},{version:3,up:async n=>n},{version:4,up:async(n,{db:e})=>({...n,auth:{...n.auth,basepath:"/api/auth2"}})},{version:5,up:async(n,{db:e})=>{let t=n.server.cors?.allow_methods??[];return set(n.server,"cors.allow_methods",[...new Set([...t,"PATCH"])]),n}},{version:6,up:async(n,{db:e})=>n},{version:7,up:async(n,{db:e})=>{let{expiresIn:t,...r}=n.auth.jwt;return {...n,auth:{...n.auth,jwt:r}}}},{version:8,up:async n=>{let e=P(n.auth.strategies,t=>({...t,enabled:true}));return {...n,auth:{...n.auth,strategies:e}}}},{version:9,up:async n=>{let{admin:e,...t}=n.server;return {...n,server:t}}}],Ct=is[is.length-1]?.version??0,Qo="__bknd";async function cl(n,e,t,r){let i=is.filter(a=>a.version>n&&a.version<=e),s=Object.assign({},t),o=0,c=n;for(let a of i)try{s=await a.up(s,r),c=a.version,o++;}catch(l){throw console.error(l),new Error(`Migration ${a.version} failed: ${l.message}`)}return [c,s]}async function Ko(n,e,t){return cl(n,Ct,e,t)}var Xt=class{constructor(e,t,r){this._schema=e;this.options=r;this._default=deepFreeze(e.template({},{withOptional:true})),this._value=deepFreeze(parse(e,structuredClone(t??{}),{withDefaults:true,forceParse:this.isForceParse(),skipMark:this.isForceParse()})),this._config=deepFreeze(this._value);}_default;_value;_config;_restriction_bypass=false;isForceParse(){return this.options?.forceParse??true}default(){return this._default}async onBeforeUpdate(e,t){return this.options?.onBeforeUpdate?this.options.onBeforeUpdate(e,t):t}get(e){return e?.stripMark?stripMark(this._config):this._config}clone(){return structuredClone(this._config)}async set(e,t){let r=parse(this._schema,structuredClone(e),{coerce:false,forceParse:true,skipMark:this.isForceParse()}),i=await this.onBeforeUpdate(this._config,r);return this._value=deepFreeze(i),this._config=deepFreeze(i),t!==true&&await this.options?.onUpdate?.(this._config),this._config}bypass(){return this._restriction_bypass=true,this}throwIfRestricted(e){if(this._restriction_bypass){this._restriction_bypass=false;return}let t=this.options?.restrictPaths??[];if(Array.isArray(t)&&t.length>0){for(let r of t)if(typeof e=="string"?e.startsWith(r):has(e,r))throw new Error(`Path "${r}" is restricted`)}}async patch(e,t){let r=this.clone(),i=e.length>0?set({},e,t):t;this.throwIfRestricted(i);let s=mergeObjectWith(r,i,(c,a)=>{if(Array.isArray(c)&&Array.isArray(a))return a});if(this.options?.overwritePaths){let a=getFullPathKeys(t).map(l=>e.length>0?e+"."+l:l).filter(l=>this.options?.overwritePaths?.some(u=>typeof u=="string"?l===u:u.test(l)));if(a.length>0){let l=a.length>1?a.filter(u=>a.some(p=>p!==u&&p.startsWith(u))):a;for(let u of l)set(s,u,get(i,u));}}let o=await this.set(s);return [i,o]}async overwrite(e,t){let r=this.clone(),i=e.length>0?set({},e,t):t;this.throwIfRestricted(i);let s=set(r,e,t),o=await this.set(s);return [i,o]}has(e){let t=e.split(".");if(t.length>1){let r=t.slice(0,-1).join(".");if(!has(this._config,r))throw new Error(`Parent path "${r}" does not exist`)}return has(this._config,e)}async remove(e){if(this.throwIfRestricted(e),!this.has(e))throw new Error(`Path "${e}" does not exist`);let t=this.clone(),r=get(t,e),i=omit(t,e),s=await this.set(i);return [r,s]}};var Q=class{constructor(e,t){this._ctx=t;this._schema=new Xt(this.getSchema(),e,{forceParse:this.useForceParse(),onUpdate:async r=>{await this._listener(r);},restrictPaths:this.getRestrictedPaths(),overwritePaths:this.getOverwritePaths(),onBeforeUpdate:this.onBeforeUpdate.bind(this)});}_built=false;_schema;_listener=()=>null;static ctx_flags={sync_required:false,ctx_reload_required:false};onBeforeUpdate(e,t){return t}setListener(e){return this._listener=e,this}useForceParse(){return false}getRestrictedPaths(){}getOverwritePaths(){}get configDefault(){return this._schema.default()}get config(){return this._schema.get()}setContext(e){return this._ctx=e,this}schema(){return this._schema}onServerInit(e){}get ctx(){if(!this._ctx)throw new Error("Context not set");return this._ctx}async build(){throw new Error("Not implemented")}setBuilt(){this._built=true,this._schema=new Xt(this.getSchema(),this.toJSON(true),{onUpdate:async e=>{await this._listener(e);},forceParse:this.useForceParse(),restrictPaths:this.getRestrictedPaths(),overwritePaths:this.getOverwritePaths(),onBeforeUpdate:this.onBeforeUpdate.bind(this)});}isBuilt(){return this._built}throwIfNotBuilt(){if(!this._built)throw new Error("Config not built: "+this.constructor.name)}toJSON(e){return this.config}};var Re=class extends C{getSafeErrorAndCode(){return {error:"Invalid credentials",code:HttpStatus.UNAUTHORIZED}}toJSON(){return A()?super.toJSON():{error:this.getSafeErrorAndCode().error,type:"AuthException"}}},os=class extends Re{name="UserExistsException";code=HttpStatus.UNPROCESSABLE_ENTITY;constructor(){super("User already exists");}},Zt=class extends Re{name="UserNotFoundException";code=HttpStatus.NOT_FOUND;constructor(){super("User not found");}},We=class extends Re{name="InvalidCredentialsException";code=HttpStatus.UNAUTHORIZED;constructor(){super("Invalid credentials");}},tn=class extends Re{name="UnableToCreateUserException";code=HttpStatus.INTERNAL_SERVER_ERROR;constructor(){super("Unable to create user");}},oe=class extends Re{code=HttpStatus.UNPROCESSABLE_ENTITY;constructor(e){super(e??"Invalid conditions");}};var Go=["GET","POST","PATCH","PUT","DELETE"],yl=s.strictObject({cors:s.strictObject({origin:s.string({default:"*"}),allow_methods:s.array(s.string({enum:Go}),{default:Go,uniqueItems:true}),allow_headers:s.array(s.string(),{default:["Content-Type","Content-Length","Authorization","Accept"]}),allow_credentials:s.boolean({default:true})})}),rn=class extends Q{getRestrictedPaths(){return []}get client(){return this.ctx.server}getSchema(){return yl}async build(){let e=this.config.cors.origin??"";this.client.use("*",cors({origin:e.includes(",")?e.split(",").map(t=>t.trim()):e,allowMethods:this.config.cors.allow_methods,allowHeaders:this.config.cors.allow_headers,credentials:this.config.cors.allow_credentials})),this.client.use("/",async(t,r)=>{await r(),(!t.finalized||t.res.status===404)&&new URL(t.req.url).pathname==="/"&&(t.res=void 0,t.res=Response.json({bknd:"hello world!"}));}),this.client.onError((t,r)=>($console.error("[AppServer:onError]",t),t instanceof Response?t:t instanceof Re?r.json(t.toJSON(),t.getSafeErrorAndCode().code):t instanceof C?r.json(t.toJSON(),t.code):t instanceof Error&&A()?r.json({error:t.message,stack:t.stack},500):r.json({error:t.message},500))),this.setBuilt();}toJSON(e){return this.config}};var er={};Be(er,{createUser:()=>as});var as=new x("auth.user.create");var He={};Be(He,{databaseSync:()=>cs,entityCreate:()=>Ve,entityDelete:()=>sn,entityRead:()=>he,entityUpdate:()=>nn,rawMutate:()=>gl,rawQuery:()=>hl});var he=new x("data.entity.read"),Ve=new x("data.entity.create"),nn=new x("data.entity.update"),sn=new x("data.entity.delete"),cs=new x("data.database.sync"),hl=new x("data.raw.query"),gl=new x("data.raw.mutate");var on={};Be(on,{auth:()=>Ho,permission:()=>Yo});function ls(n){let e=n instanceof Request?n:n.req.raw;return new URL(e.url).pathname}function wl(n,e){let t=n.get("auth");if(!t)throw new Error("auth ctx not found");if(t.skip)return true;let r=n.req.raw;if(!e)return false;let i=ls(r),s=e.some(o=>patternMatch(i,o));return t.skip=s,s}var Ho=n=>createMiddleware(async(e,t)=>{e.get("auth")||e.set("auth",{registered:false,resolved:false,skip:false,user:void 0});let r=e.get("app"),i=e.get("auth"),s=r?.module.auth.authenticator,o=wl(e,n?.skip)||!r?.module.auth.enabled;i.registered?(o=true,$console.warn(`auth middleware already registered for ${ls(e)}`)):(i.registered=true,!o&&!i.resolved&&r?.module.auth.enabled&&(i.user=await s?.resolveAuthFromRequest(e),i.resolved=true)),await t(),i.skip=false,i.resolved=false,i.user=void 0;}),Yo=(n,e)=>createMiddleware(async(t,r)=>{let i=t.get("app"),s=t.get("auth");if(!s)throw new Error("auth ctx not found");if(!s.registered||!i){let o=`auth middleware not registered, cannot check permissions for ${ls(t)}`;if(i?.module.auth.enabled)throw new Error(o);$console.warn(o);}else if(!s.skip){let o=i.modules.ctx().guard,c=Array.isArray(n)?n:[n];if(e?.onGranted||e?.onDenied){let a;if(c.every(l=>o.granted(l,t))?a=await e?.onGranted?.(t):a=await e?.onDenied?.(t),a instanceof Response)return a}else c.some(a=>o.throwUnlessGranted(a,t));}await r();});var ae=class n{middlewares=on;create(){return n.createServer()}static createServer(){return new Hono}getController(){return this.create()}isJsonRequest(e){return e.req.header("Content-Type")==="application/json"||e.req.header("Accept")==="application/json"}notFound(e){return this.isJsonRequest(e)?e.json({error:"Not found"},404):e.notFound()}getEntitiesEnum(e){let t=e.entities.map(r=>r.name);return t.length>0?s.anyOf([s.string({enum:t}),s.string()]):s.string()}};var cn=class extends ae{constructor(t){super();this.auth=t;}get guard(){return this.auth.ctx.guard}get em(){return this.auth.ctx.em}get userRepo(){let t=this.auth.config.entity_name;return this.em.repo(t)}registerStrategyActions(t,r){if(!this.auth.isStrategyEnabled(t))return;let i=t.getActions?.();if(!i)return;let{auth:s,permission:o}=this.middlewares,c=this.create().use(s()),a=t.getName(),{create:l,change:u}=i,p=this.auth.em;l&&(c.post("/create",o([as,Ve]),describeRoute({summary:"Create a new user",tags:["auth"]}),async d=>{try{let m=await this.auth.authenticator.getBody(d),h=parse(l.schema,m,{}),F=await l.preprocess?.(h)??h,_=p.mutator(this.auth.config.entity_name);_.__unstable_toggleSystemEntityCreation(!1);let{data:ce}=await _.insertOne({...F,strategy:a});return _.__unstable_toggleSystemEntityCreation(!0),d.json({success:!0,action:"create",strategy:a,data:ce})}catch(m){if(m instanceof InvalidSchemaError)return d.json({success:false,errors:m.errors},400);throw m}}),c.get("create/schema.json",describeRoute({summary:"Get the schema for creating a user",tags:["auth"]}),async d=>d.json(l.schema))),r.route(`/${a}/actions`,c);}getController(){let{auth:t}=this.middlewares,r=this.create();r.get("/me",describeRoute({summary:"Get the current user",tags:["auth"]}),t(),async s=>{let o=s.get("auth")?.user;if(o){let{data:c}=await this.userRepo.findId(o.id);return await this.auth.authenticator?.requestCookieRefresh(s),s.json({user:c})}return s.json({user:null},403)}),r.get("/logout",describeRoute({summary:"Logout the current user",tags:["auth"]}),t(),async s=>{if(await this.auth.authenticator.logout(s),this.auth.authenticator.isJsonRequest(s))return s.json({ok:true});let o=s.req.header("referer");return o?s.redirect(o):s.redirect("/")}),r.get("/strategies",describeRoute({summary:"Get the available authentication strategies",tags:["auth"]}),jsc("query",s.object({include_disabled:s.boolean().optional()})),async s=>{let{include_disabled:o}=s.req.valid("query"),{strategies:c,basepath:a}=this.auth.toJSON(false);return o?s.json({strategies:c,basepath:a}):s.json({strategies:transformObject(c??{},(l,u)=>this.auth.isStrategyEnabled(u)?l:void 0),basepath:a})});let i=this.auth.authenticator.getStrategies();for(let[s,o]of Object.entries(i))this.auth.isStrategyEnabled(o)&&(r.route(`/${s}`,o.getController(this.auth.authenticator)),this.registerStrategyActions(o,r));return r}};var us="__bknd_flash";function _t(n,e,t="info"){n.req.header("Accept")?.includes("text/html")&&setCookie(n,us,JSON.stringify({type:t,message:e}),{path:"/"});}function Cl(n){let e=document.cookie.split("; ");for(let t of e){let[r,i]=t.split("=");if(r===n)try{return decodeURIComponent(i)}catch{return null}}return null}function Ol(n=true){let e=Cl(us);return e&&n&&(document.cookie=`${us}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`),e?JSON.parse(e):void 0}var ea=60*60*24*7,ps=s.object({path:s.string({default:"/"}),sameSite:s.string({enum:["strict","lax","none"],default:"lax"}),secure:s.boolean({default:true}),httpOnly:s.boolean({default:true}),expires:s.number({default:ea}),partitioned:s.boolean({default:false}),renew:s.boolean({default:true}),pathSuccess:s.string({default:"/"}),pathLoggedOut:s.string({default:"/"})}).partial().strict(),ds=s.object({secret:secret({default:""}),alg:s.string({enum:["HS256","HS384","HS512"],default:"HS256"}).optional(),expires:s.number().optional(),issuer:s.string().optional(),fields:s.array(s.string(),{default:["id","email","role"]})},{default:{}}).strict(),Bl=s.object({jwt:ds,cookie:ps}),ln=class{constructor(e,t,r){this.strategies=e;this.userPool=t;this.config=parse(Bl,r??{});}config;async resolveLogin(e,t,r,i,s){try{let o=s?.identifier||"email";if(typeof o!="string"||o.length===0)throw new oe("Identifier must be a string");if(!(o in r))throw new oe(`Profile must have identifier "${o}"`);let c=await this.userPool.findBy(t.getName(),o,r[o]);if(c.strategy_value){if(c.strategy!==t.getName())throw new oe("User signed up with a different strategy")}else throw new oe("User must have a strategy value");await i(c);let a=await this.safeAuthResponse(c);return this.respondWithUser(e,a,s)}catch(o){return this.respondWithError(e,o,s)}}async resolveRegister(e,t,r,i,s){try{let o=s?.identifier||"email";if(typeof o!="string"||o.length===0)throw new oe("Identifier must be a string");if(!(o in r))throw new oe(`Profile must have identifier "${o}"`);if(!("strategy_value"in r))throw new oe("Profile must have a strategy value");let c=await this.userPool.create(t.getName(),{...r,strategy_value:r.strategy_value});await i(c);let a=await this.safeAuthResponse(c);return this.respondWithUser(e,a,s)}catch(o){return this.respondWithError(e,o,s)}}async respondWithUser(e,t,r){let i=this.getSafeUrl(e,r?.redirect??this.config.cookie.pathSuccess??"/");if("token"in t)return await this.setAuthCookie(e,t.token),this.isJsonRequest(e)||r?.forceJsonResponse?e.json(t):e.redirect(i);throw new C("Invalid response")}async respondWithError(e,t,r){if($console.error("respondWithError",t),this.isJsonRequest(e)||r?.forceJsonResponse)throw t;await _t(e,String(t),"error");let i=this.getSafeUrl(e,e.req.header("Referer")??"/");return e.redirect(i)}getStrategies(){return this.strategies}strategy(e){try{return this.strategies[e]}catch{throw new Error(`Strategy "${String(e)}" not found`)}}async jwt(e){let r={...pick(e,this.config.jwt.fields),iat:Math.floor(Date.now()/1e3)};this.config.jwt?.issuer&&(r.iss=this.config.jwt.issuer),this.config.jwt?.expires&&(r.exp=Math.floor(Date.now()/1e3)+this.config.jwt.expires);let i=this.config.jwt.secret;if(!i||i.length===0)throw new Error("Cannot sign JWT without a secret");return sign(r,i,this.config.jwt?.alg??"HS256")}async safeAuthResponse(e){let t=pick(e,this.config.jwt.fields);return {user:t,token:await this.jwt(t)}}async verify(e){try{let t=await verify(e,this.config.jwt?.secret??"",this.config.jwt?.alg??"HS256");if(this.config.jwt?.issuer&&t.iss!==this.config.jwt.issuer)throw new C("Invalid issuer",403);return t}catch{}}get cookieOptions(){let{expires:e=ea,renew:t,...r}=this.config.cookie;return {...r,expires:new Date(Date.now()+e*1e3)}}async getAuthCookie(e){try{let t=this.config.jwt.secret,r=await getSignedCookie(e,t,"auth");return typeof r!="string"?void 0:r}catch(t){t instanceof Error&&$console.error("[getAuthCookie]",t.message);return}}async requestCookieRefresh(e){if(this.config.cookie.renew&&e.get("auth")?.user){let t=await this.getAuthCookie(e);t&&await this.setAuthCookie(e,t);}}async setAuthCookie(e,t){$console.debug("setting auth cookie",truncate(t));let r=this.config.jwt.secret;await setSignedCookie(e,"auth",t,r,this.cookieOptions);}async unsafeGetAuthCookie(e){return serializeSigned("auth",e,this.config.jwt.secret,this.cookieOptions)}deleteAuthCookie(e){$console.debug("deleting auth cookie"),deleteCookie(e,"auth",this.cookieOptions);}async logout(e){$console.info("Logging out"),e.set("auth",void 0),await this.getAuthCookie(e)&&_t(e,"Signed out","info"),this.deleteAuthCookie(e);}isJsonRequest(e){return e.req.header("Content-Type")==="application/json"}async getBody(e){return this.isJsonRequest(e)?await e.req.json():Object.fromEntries((await e.req.formData()).entries())}getSafeUrl(e,t){let r=t.replace(/\/+$/,"/");return runtimeSupports("redirects_non_fq")?r:new URL(e.req.url).origin+r}async resolveAuthFromRequest(e){let t;if(e.req.raw.headers.has("Authorization")?t=String(e.req.header("Authorization")).replace("Bearer ",""):t=await this.getAuthCookie(e),t)return await this.verify(t)}toJSON(e){return {...this.config,jwt:e?this.config.jwt:void 0}}};var nr={};Be(nr,{github:()=>ra,google:()=>ta});var ta={type:"oidc",client:{token_endpoint_auth_method:"client_secret_basic"},as:{issuer:"https://accounts.google.com"},profile:async n=>({...n,sub:n.sub,email:n.email})};var ra={type:"oauth2",client:{token_endpoint_auth_method:"client_secret_basic"},as:{code_challenge_methods_supported:["S256"],issuer:"https://github.com",scopes_supported:["read:user","user:email"],scope_separator:" ",authorization_endpoint:"https://github.com/login/oauth/authorize",token_endpoint:"https://github.com/login/oauth/access_token",userinfo_endpoint:"https://api.github.com/user"},profile:async(n,e,t)=>{try{let s=(await(await fetch("https://api.github.com/user/emails",{headers:{"User-Agent":"bknd",Accept:"application/json",Authorization:`Bearer ${t.access_token}`}})).json()).find(o=>o.primary)?.email;if(!s)throw new Error("No primary email found");return {...n,sub:String(n.id),email:s}}catch{throw new Error("Couldn't retrive github email")}}};var Ye=class{constructor(e,t,r,i){this.config=e;this.type=t;this.name=r;this.mode=i;this.config=parse(this.getSchema(),e??{});}actions={};registerAction(e,t,r){this.actions[e]={schema:t,preprocess:r};}getType(){return this.type}getMode(){return this.mode}getName(){return this.name}toJSON(e){return {type:this.getType(),config:e?this.config:void 0}}getActions(){return this.actions}};var Kl=s.object({name:s.string({enum:Object.keys(nr)}),type:s.string({enum:["oidc","oauth2"],default:"oauth2"}),client:s.object({client_id:s.string(),client_secret:s.string()}).strict()},{title:"OAuth"}),De=class extends C{constructor(t,r){super("OAuthCallbackException on "+r);this.error=t;this.step=r;}name="OAuthCallbackException"},Ie=class extends Ye{constructor(e){super(e,"oauth",e.name,"external");}getSchema(){return Kl}getIssuerConfig(){return nr[this.config.name]}async getConfig(){let e=this.getIssuerConfig();if(e.type==="oidc"){let t=new URL(e.as.issuer),r=await b.discoveryRequest(t);e.as=await b.processDiscoveryResponse(t,r);}return {...e,type:e.type,client:{...e.client,...this.config.client}}}async getCodeChallenge(e,t,r="S256"){let i=e.code_challenge_methods_supported?.includes(r),s,o;return i&&(s=await b.calculatePKCECodeChallenge(t),o=r),{challenge_supported:i,challenge:s,challenge_method:o}}async request(e){let{client:t,as:r}=await this.getConfig(),{challenge_supported:i,challenge:s,challenge_method:o}=await this.getCodeChallenge(r,e.state);if(!r.authorization_endpoint)throw new Error("authorization_endpoint is not provided");let c=e.scopes??r.scopes_supported;if(!Array.isArray(c)||c.length===0)throw new Error("No scopes provided");if(c.every(u=>!r.scopes_supported?.includes(u)))throw new Error("Invalid scopes provided");let a=r.authorization_endpoint,l={client_id:t.client_id,redirect_uri:e.redirect_uri,response_type:"code",scope:c.join(r.scope_separator??" ")};return i?(l.code_challenge=s,l.code_challenge_method=o):l.nonce=e.state,{url:new URL(a)+"?"+new URLSearchParams(l).toString(),endpoint:a,params:l}}async oidc(e,t){let r=await this.getConfig(),{client:i,as:s,type:o}=r,c=b.validateAuthResponse(s,i,e,b.expectNoState);if(b.isOAuth2Error(c))throw new De(c,"validateAuthResponse");let a=await b.authorizationCodeGrantRequest(s,i,c,t.redirect_uri,t.state),l=b.parseWwwAuthenticateChallenges(a);if(l)throw new De(l,"www-authenticate");let{challenge_supported:u,challenge:p}=await this.getCodeChallenge(s,t.state),m=await b.processAuthorizationCodeOpenIDResponse(s,i,a,u?void 0:p);if(b.isOAuth2Error(m))throw new De(m,"processAuthorizationCodeOpenIDResponse");let h=b.getValidatedIdTokenClaims(m),F=await b.userInfoRequest(s,i,m.access_token),_=await b.processUserInfoResponse(s,i,h.sub,F);return await r.profile(_,r,h)}async oauth2(e,t){let r=await this.getConfig(),{client:i,type:s,as:o,profile:c}=r,a=b.validateAuthResponse(o,i,e,b.expectNoState);if(b.isOAuth2Error(a))throw new De(a,"validateAuthResponse");let l=await b.authorizationCodeGrantRequest(o,i,a,t.redirect_uri,t.state),u=b.parseWwwAuthenticateChallenges(l);if(u)throw new De(u,"www-authenticate");let p=l.clone(),d={};try{if(d=await b.processAuthorizationCodeOAuth2Response(o,i,l),b.isOAuth2Error(d))throw new Error}catch{d=await p.json();}let h=await(await b.userInfoRequest(o,i,d.access_token)).json();return await r.profile(h,r,d)}async callback(e,t){switch(this.getIssuerConfig().type){case "oidc":return await this.oidc(e,t);case "oauth2":return await this.oauth2(e,t);default:throw new Error("Unsupported type")}}getController(e){let t=new Hono,r="secret",i="_challenge",s=async(c,a)=>{await setSignedCookie(c,i,JSON.stringify(a),r,{secure:true,httpOnly:true,sameSite:"Lax",maxAge:60*5});},o=async c=>{if(c.req.header("X-State-Challenge"))return {state:c.req.header("X-State-Challenge"),action:c.req.header("X-State-Action"),mode:"token"};let a=await getSignedCookie(c,r,i);try{return JSON.parse(a)}catch{throw new Error("Invalid state")}};return t.get("/callback",async c=>{let a=new URL(c.req.url),l=new URLSearchParams(a.search),u=await o(c),p=u.mode==="cookie"?a.origin+a.pathname:a.origin+a.pathname.replace("/callback","/token"),d=await this.callback(l,{redirect_uri:p,state:u.state}),m={email:d.email,strategy_value:d.sub},h=async _=>{if(_.strategy_value!==d.sub)throw new C("Invalid credentials")},F={redirect:u.redirect,forceJsonResponse:u.mode!=="cookie"};switch(u.action){case "login":return e.resolveLogin(c,this,m,h,F);case "register":return e.resolveRegister(c,this,m,h,F);default:throw new Error("Invalid action")}}),t.get("/token",async c=>{let a=new URL(c.req.url),l=new URLSearchParams(a.search);return c.json({code:l.get("code")??null})}),t.post("/:action",async c=>{let a=c.req.param("action");if(!["login","register"].includes(a))return c.notFound();let l=new URL(c.req.url),u=l.pathname.replace(`/${a}`,""),p=l.origin+u+"/callback",d=new URL(c.req.header("Referer")??"/"),m=b.generateRandomCodeVerifier(),h=await this.request({redirect_uri:p,state:m});return await s(c,{state:m,action:a,redirect:d.toString(),mode:"cookie"}),c.redirect(h.url)}),t.get("/:action",async c=>{let a=c.req.param("action");if(!["login","register"].includes(a))return c.notFound();let l=new URL(c.req.url),u=l.pathname.replace(`/${a}`,""),p=l.origin+u+"/token",d=b.generateRandomCodeVerifier(),m=await this.request({redirect_uri:p,state:d});return A()?c.json({url:m.url,redirect_uri:p,challenge:d,action:a,params:m.params}):c.json({url:m.url,challenge:d,action:a})}),t}toJSON(e){let t=e?this.config:filterKeys(this.config,["secret","client_id"]);return {...super.toJSON(e),config:{...t,type:this.getIssuerConfig().type}}}};var ms=s.string({pattern:"^(https?|wss?)://[^\\s/$.?#].[^\\s]*$"}),Jl=s.strictObject({type:s.string({enum:["oidc","oauth2"],default:"oidc"}),name:s.string(),client:s.object({client_id:s.string(),client_secret:s.string(),token_endpoint_auth_method:s.string({enum:["client_secret_basic"]})}),as:s.strictObject({issuer:s.string(),code_challenge_methods_supported:s.string({enum:["S256"]}).optional(),scopes_supported:s.array(s.string()).optional(),scope_separator:s.string({default:" "}).optional(),authorization_endpoint:ms.optional(),token_endpoint:ms.optional(),userinfo_endpoint:ms.optional()})},{title:"Custom OAuth"}),kt=class extends Ie{constructor(e){super(e),this.type="custom_oauth";}getIssuerConfig(){return {...this.config,profile:async e=>e}}getSchema(){return Jl}};var Hl=s.object({hashing:s.string({enum:["plain","sha256","bcrypt"],default:"sha256"}),rounds:s.number({minimum:1,maximum:10}).optional()}).strict(),Ft=class extends Ye{constructor(e={}){super(e,"password","password","form"),this.registerAction("create",this.getPayloadSchema(),async({password:t,...r})=>({...r,strategy_value:await this.hash(t)}));}getSchema(){return Hl}getPayloadSchema(){return s.object({email:s.string({format:"email"}),password:s.string({minLength:8})})}async hash(e){switch(this.config.hashing){case "sha256":return kr.sha256(e);case "bcrypt":{let t=await genSalt(this.config.rounds??4);return hash(e,t)}default:return e}}async compare(e,t){switch(this.config.hashing){case "sha256":{let r=await this.hash(t);return e===r}case "bcrypt":return await compare(t,e)}return false}verify(e){return async t=>{if(await this.compare(t?.strategy_value,e)!==true)throw new We}}getController(e){let t=new Hono,r=s.object({redirect:s.string().optional()}),i=this.getPayloadSchema();return t.post("/login",jsc("query",r),async s=>{try{let o=parse(i,await e.getBody(s),{onError:a=>{throw f.error("Invalid login payload",[...a]),new We}}),{redirect:c}=s.req.valid("query");return await e.resolveLogin(s,this,o,this.verify(o.password),{redirect:c})}catch(o){return e.respondWithError(s,o)}}),t.post("/register",jsc("query",r),async s=>{try{let{redirect:o}=s.req.valid("query"),{password:c,email:a,...l}=parse(i,await e.getBody(s),{onError:p=>{f.error("Invalid register payload",[...p]),new We;}}),u={...l,email:a,strategy_value:await this.hash(c)};return await e.resolveRegister(s,this,u,async()=>{},{redirect:o})}catch(o){return e.respondWithError(s,o)}}),t}};var Xl={password:{cls:Ft,schema:Ft.prototype.getSchema()},oauth:{cls:Ie,schema:Ie.prototype.getSchema()},custom_oauth:{cls:kt,schema:kt.prototype.getSchema()}},fs=Xl,Zl=objectTransform(fs,(n,e)=>s.strictObject({enabled:s.boolean({default:true}).optional(),type:s.literal(e),config:n.schema},{title:e})),eu=s.anyOf(Object.values(Zl)),tu=s.object({enabled:s.boolean({default:false}).optional()}),ru=s.strictObject({permissions:s.array(s.string()).optional(),is_default:s.boolean().optional(),implicit_allow:s.boolean().optional()}),ys=s.strictObject({enabled:s.boolean({default:false}),basepath:s.string({default:"/api/auth"}),entity_name:s.string({default:"users"}),allow_register:s.boolean({default:true}).optional(),jwt:ds,cookie:ps,strategies:s.record(eu,{title:"Strategies",default:{password:{type:"password",enabled:true,config:{hashing:"sha256"}}}}),guard:tu.optional(),roles:s.record(ru,{default:{}}).optional()},{title:"Authentication"});var un=class{constructor(e){this.appAuth=e;}get em(){return this.appAuth.em}get users(){return this.appAuth.getUsersEntity()}async findBy(e,t,r){f.debug("[AppUserPool:findBy]",{strategy:e,prop:t,value:r}),this.toggleStrategyValueVisibility(true);let i=await this.em.repo(this.users).findOne({[t]:r,strategy:e});if(this.toggleStrategyValueVisibility(false),!i.data)throw f.debug("[AppUserPool]: User not found"),new Zt;return i.data}async create(e,t){if(f.debug("[AppUserPool:create]",{strategy:e,payload:t}),!("strategy_value"in t))throw new oe("Profile must have a strategy_value value");let r=this.users.getSelect(void 0,"create"),s={...pick(t,r),strategy:e},o=this.em.mutator(this.users);o.__unstable_toggleSystemEntityCreation(false),this.toggleStrategyValueVisibility(true);let c=await o.insertOne(s);if(o.__unstable_toggleSystemEntityCreation(true),this.toggleStrategyValueVisibility(false),!c.data)throw new tn;return f.debug("[AppUserPool]: User created",c.data),c.data}toggleStrategyValueVisibility(e){let t=(r,i)=>{let s=this.users.field(r);if(i)s.config.hidden=false,s.config.fillable=true;else {let o=Pt.usersFields.strategy_value.config;s.config.hidden=o.hidden,s.config.fillable=o.fillable;}};t("strategy_value",e),t("strategy",e);}};var pn={email:se().required(),strategy:se({fillable:["create"],hidden:["update","form"]}).required(),strategy_value:se({fillable:["create"],hidden:["read","table","update","form"]}).required(),role:se()};var Pt=class n extends Q{_authenticator;cache={};_controller;async onBeforeUpdate(e,t){let r=ys.properties.jwt.properties.secret.default;return !e.enabled&&t.enabled&&t.jwt.secret===r&&(f.warn("No JWT secret provided, generating a random one"),t.jwt.secret=po(64)),t.strategies?.password?.enabled||(f.warn("Password strategy cannot be disabled."),t.strategies.password.enabled=true),t}get enabled(){return this.config.enabled}async build(){if(!this.enabled){this.setBuilt();return}let e=P(this.config.roles??{},(r,i)=>pt.create({name:i,...r}));this.ctx.guard.setRoles(Object.values(e)),this.ctx.guard.setConfig(this.config.guard??{});let t=P(this.config.strategies??{},(r,i)=>{try{return new fs[r.type].cls(r.config)}catch{throw new Error(`Could not build strategy ${String(i)} with config ${JSON.stringify(r.config)}`)}});this._authenticator=new ln(t,new un(this),{jwt:this.config.jwt,cookie:this.config.cookie}),this.registerEntities(),super.setBuilt(),this._controller=new cn(this),this.ctx.server.route(this.config.basepath,this._controller.getController()),this.ctx.guard.registerPermissions(er);}isStrategyEnabled(e){let t=typeof e=="string"?e:e.getName();return t==="password"?true:this.config.strategies?.[t]?.enabled??false}get controller(){if(!this.isBuilt())throw new Error("Can't access controller, AppAuth not built yet");return this._controller}getSchema(){return ys}get authenticator(){return this.throwIfNotBuilt(),this._authenticator}get em(){return this.ctx.em}getUsersEntity(e){let t=this.config.entity_name;return e||!this.em.hasEntity(t)?Ge(t,n.usersFields,void 0,"system"):this.em.entity(t)}static usersFields=pn;registerEntities(){let e=this.getUsersEntity(true);this.ctx.helper.ensureSchema(Ht({[e.name]:e},({index:t},{users:r})=>{t(r).on(["email"],true).on(["strategy"]).on(["strategy_value"]);}));try{let t=Object.keys(this.config.roles??{});this.ctx.helper.replaceEntityField(e,"role",Rt({enum:t}));}catch{}try{let t=Object.keys(this.config.strategies??{});this.ctx.helper.replaceEntityField(e,"strategy",Rt({enum:t}));}catch{}}async createUser({email:e,password:t,...r}){if(!this.enabled)throw new Error("Cannot create user, auth not enabled");let i="password",o=await this.authenticator.strategy(i).hash(t),c=this.em.mutator(this.config.entity_name);c.__unstable_toggleSystemEntityCreation(false);let{data:a}=await c.insertOne({...r,email:e,strategy:i,strategy_value:o});return c.__unstable_toggleSystemEntityCreation(true),a}toJSON(e){if(!this.config.enabled)return this.configDefault;let t=this.authenticator.getStrategies();return {...this.config,...this.authenticator.toJSON(e),strategies:P(t,r=>({enabled:this.isStrategyEnabled(r),...r.toJSON(e)}))}}};var jt={};Be(jt,{accessAdmin:()=>dn,accessApi:()=>hs,build:()=>gs,configRead:()=>mn,configReadSecrets:()=>ir,configWrite:()=>Xe,schemaRead:()=>Mt});var dn=new x("system.access.admin"),hs=new x("system.access.api"),mn=new x("system.config.read"),ir=new x("system.config.read.secrets"),Xe=new x("system.config.write"),Mt=new x("system.schema.read"),gs=new x("system.build");var fn=class extends ae{constructor(t,r){super();this.ctx=t;this.config=r;}get em(){return this.ctx.em}get guard(){return this.ctx.guard}entityExists(t){try{return !!this.em.entity(t)}catch{return false}}getController(){let{permission:t,auth:r}=this.middlewares,i=this.create().use(r(),t(hs)),s$1=this.getEntitiesEnum(this.em);function o(c,a){let l=a;return l.description=c,l}return i.get("/",describeRoute({summary:"Retrieve data configuration",tags:["data"]}),o("data info",c=>c.json(this.em.toJSON()))),i.get("/sync",t(cs),describeRoute({summary:"Sync database schema",tags:["data"]}),jsc("query",s.object({force:s.boolean(),drop:s.boolean()}).partial()),async c=>{let{force:a,drop:l}=c.req.valid("query"),u=await this.em.schema().introspect(),p=await this.em.schema().sync({force:a,drop:l});return c.json({tables:u.map(d=>d.name),changes:p})}),i.get("/schema.json",t(he),describeRoute({summary:"Retrieve data schema",tags:["data"]}),async c=>{let a=`${this.config.basepath}/schema.json`,l=Object.fromEntries(this.em.entities.map(u=>[u.name,{$ref:`${this.config.basepath}/schemas/${u.name}`}]));return c.json({$schema:"https://json-schema.org/draft/2020-12/schema",$id:a,properties:l})}),i.get("/schemas/:entity/:context?",t(he),describeRoute({summary:"Retrieve entity schema",tags:["data"]}),jsc("param",s.object({entity:s$1,context:s.string({enum:["create","update"],default:"create"}).optional()})),async c=>{let{entity:a,context:l}=c.req.param();if(!this.entityExists(a))return this.notFound(c);let u=this.em.entity(a),p=u.toSchema({context:l}),m=`${new URL(c.req.url).origin}${this.config.basepath}`,h=`${this.config.basepath}/schemas/${a}`;return c.json({$schema:`${m}/schema.json`,$id:h,title:u.label,$comment:u.config.description,...p})}),i.route("/entity",this.getEntityRoutes()),i.get("/info/:entity",t(he),describeRoute({summary:"Retrieve entity info",tags:["data"]}),jsc("param",s.object({entity:s$1})),async c=>{let{entity:a}=c.req.param();if(!this.entityExists(a))return this.notFound(c);let l=this.em.entity(a),u=l.fields.map(d=>d.name),p=d=>d.map(m=>({entity:m.other(l).entity.name,ref:m.other(l).reference}));return c.json({name:l.name,fields:u,relations:{all:p(this.em.relations.relationsOf(l)),listable:p(this.em.relations.listableRelationsOf(l)),source:p(this.em.relations.sourceRelationsOf(l)),target:p(this.em.relations.targetRelationsOf(l))}})}),i}getEntityRoutes(){let{permission:t}=this.middlewares,r=this.create(),i=this.getEntitiesEnum(this.em),s$1=s.anyOf([s.number(),s.string()],{coerce:l=>l});r.post("/:entity/fn/count",t(he),describeRoute({summary:"Count entities",tags:["data"]}),jsc("param",s.object({entity:i})),jsc("json",ie.properties.where),async l=>{let{entity:u}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let p=l.req.valid("json"),d=await this.em.repository(u).count(p);return l.json({entity:u,...d.data})}),r.post("/:entity/fn/exists",t(he),describeRoute({summary:"Check if entity exists",tags:["data"]}),jsc("param",s.object({entity:i})),jsc("json",ie.properties.where),async l=>{let{entity:u}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let p=l.req.valid("json"),d=await this.em.repository(u).exists(p);return l.json({entity:u,...d.data})});let o=s.object({...omitKeys(ie.properties,["with"]),sort:s.string({default:"id"}),select:s.array(s.string()),join:s.array(s.string())}).partial(),c=(l=Object.keys(ie.properties))=>[...schemaToSpec(o,"query").parameters?.filter(u=>l.includes(u.name))];r.get("/:entity",describeRoute({summary:"Read many",parameters:c(["limit","offset","sort","select","join"]),tags:["data"]}),t(he),jsc("param",s.object({entity:i})),jsc("query",ie,{skipOpenAPI:true}),async l=>{let{entity:u}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let p=l.req.valid("query"),d=await this.em.repository(u).findMany(p);return l.json(d,{status:d.data?200:404})}),r.get("/:entity/:id",describeRoute({summary:"Read one",parameters:c(["offset","sort","select"]),tags:["data"]}),t(he),jsc("param",s.object({entity:i,id:s$1})),jsc("query",ie,{skipOpenAPI:true}),async l=>{let{entity:u,id:p}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let d=l.req.valid("query"),m=await this.em.repository(u).findId(p,d);return l.json(m,{status:m.data?200:404})}),r.get("/:entity/:id/:reference",describeRoute({summary:"Read many by reference",parameters:c(),tags:["data"]}),t(he),jsc("param",s.object({entity:i,id:s$1,reference:s.string()})),jsc("query",ie,{skipOpenAPI:true}),async l=>{let{entity:u,id:p,reference:d}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let m=l.req.valid("query"),h=await this.em.repository(u).findManyByReference(p,d,m);return l.json(h,{status:h.data?200:404})});let a=s.object({...o.properties,with:s.object({})}).partial();return r.post("/:entity/query",describeRoute({summary:"Query entities",requestBody:{content:{"application/json":{schema:a.toJSON(),example:a.template({withOptional:true})}}},tags:["data"]}),t(he),jsc("param",s.object({entity:i})),jsc("json",ie,{skipOpenAPI:true}),async l=>{let{entity:u}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let p=l.req.valid("json"),d=await this.em.repository(u).findMany(p);return l.json(d,{status:d.data?200:404})}),r.post("/:entity",describeRoute({summary:"Insert one or many",tags:["data"]}),t(Ve),jsc("param",s.object({entity:i})),jsc("json",s.anyOf([s.object({}),s.array(s.object({}))])),async l=>{let{entity:u}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let p=await l.req.json();if(Array.isArray(p)){let m=await this.em.mutator(u).insertMany(p);return l.json(m,201)}let d=await this.em.mutator(u).insertOne(p);return l.json(d,201)}),r.patch("/:entity",describeRoute({summary:"Update many",tags:["data"]}),t(nn),jsc("param",s.object({entity:i})),jsc("json",s.object({update:s.object({}),where:ie.properties.where})),async l=>{let{entity:u}=l.req.param();if(!this.entityExists(u))return this.notFound(l);let{update:p,where:d}=await l.req.json(),m=await this.em.mutator(u).updateWhere(p,d);return l.json(m)}),r.patch("/:entity/:id",describeRoute({summary:"Update one",tags:["data"]}),t(nn),jsc("param",s.object({entity:i,id:s$1})),jsc("json",s.object({})),async l=>{let{entity:u,id:p}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let d=await l.req.json(),m=await this.em.mutator(u).updateOne(p,d);return l.json(m)}),r.delete("/:entity/:id",describeRoute({summary:"Delete one",tags:["data"]}),t(sn),jsc("param",s.object({entity:i,id:s$1})),async l=>{let{entity:u,id:p}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let d=await this.em.mutator(u).deleteOne(p);return l.json(d)}),r.delete("/:entity",describeRoute({summary:"Delete many",tags:["data"]}),t(sn),jsc("param",s.object({entity:i})),jsc("json",ie.properties.where),async l=>{let{entity:u}=l.req.valid("param");if(!this.entityExists(u))return this.notFound(l);let p=await l.req.json(),d=await this.em.mutator(u).deleteWhere(p);return l.json(d)}),r}};var yn={..._o,...qo,media:{schema:Xi,field:Te}},sa=Yi,ou=Ar(yn,(n,e)=>s.strictObject({name:s.string().optional(),type:s.literal(e),config:n.schema.optional()},{title:e})),au=s.anyOf(Object.values(ou)),cu=s.record(au),lu=s.strictObject({name:s.string().optional(),type:s.string({enum:zt,default:"regular"}),config:Ji,fields:cu}),uu=Object.entries(Yi).map(([n,e])=>s.strictObject({type:s.literal(n),source:s.string(),target:s.string(),config:e.schema.optional()},{title:n})),pu=s.strictObject({entity:s.string(),fields:s.array(s.string(),{minItems:1}),unique:s.boolean({default:false}).optional()}),oa=s.strictObject({basepath:s.string({default:"/api/data"}).optional(),default_primary_format:s.string({enum:Jt,default:"integer"}).optional(),entities:s.record(lu,{default:{}}).optional(),relations:s.record(s.anyOf(uu),{default:{}}).optional(),indices:s.record(pu,{default:{}}).optional()});function aa(n,e){let t=P(e.fields??{},(r,i)=>{let{type:s}=r;if(!(s in yn))throw new Error(`Field type "${s}" not found`);let{field:o}=yn[s];return new o(i,r.config)});return new z(n,Object.values(t),e.config,e.type)}function ca(n,e){return new sa[n.type].cls(e(n.source),e(n.target),n.config)}var hn=class extends Q{async build(){let{entities:e={},relations:t={},indices:r={}}=this.config,i=P(e,(a,l)=>aa(l,a)),s=a=>{let l=typeof a=="string"?a:a.name,u=i[l];if(u)return u;throw new Error(`[AppData] Entity "${l}" not found`)},o=P(t,a=>ca(a,s)),c=P(r,(a,l)=>{let u=s(a.entity),p=a.fields.map(d=>u.field(d));return new xt(u,p,a.unique,l)});for(let a of Object.values(i))this.ctx.em.addEntity(a);for(let a of Object.values(o))this.ctx.em.addRelation(a);for(let a of Object.values(c))this.ctx.em.addIndex(a);this.ctx.server.route(this.basepath,new fn(this.ctx,this.config).getController()),this.ctx.guard.registerPermissions(Object.values(He)),this.setBuilt();}async onBeforeUpdate(e,t){let r={from:Object.keys(e.entities??{}),to:Object.keys(t.entities??{})};if(r.from.length-r.to.length>1)throw new Error("Cannot remove more than one entity at a time");return t}getSchema(){return oa}get em(){return this.throwIfNotBuilt(),this.ctx.em}get basepath(){return this.config.basepath??"/api/data"}getOverwritePaths(){return [/^entities\..*\.config$/,/^entities\..*\.fields\..*\.config$/]}toJSON(e){return {...this.config,...this.em.toJSON()}}};var sr=class{constructor(e={},t={}){this.variables=e;this.options=t;}another(){return 1}static hasMarkup(e){let t="";if(Array.isArray(e)||typeof e=="object"){if(!["Array","Object"].includes(e.constructor.name))return false;t=JSON.stringify(e);}else t=String(e);return ["{{"].some(i=>t.includes(i))}async render(e){if(typeof e>"u"||e===null)return e;if(typeof e=="string")return await this.renderString(e);if(Array.isArray(e))return await Promise.all(e.map(t=>this.render(t)));if(typeof e=="object")return await this.renderObject(e);throw new Error("Invalid template type")}async renderString(e){return e.replace(/{{\s*([^{}]+?)\s*}}/g,(t,r)=>{let i=get(this.variables,r.trim());return i==null?"":String(i)})}async renderObject(e){let t={};for(let[r,i]of Object.entries(e)){let s=r;this.options.renderKeys&&(s=await this.renderString(r)),t[s]=await this.render(i);}return t}};var Ze=(n,e)=>n,we=class n{name;static schema=s.any();_params;constructor(e,t){if(typeof e!="string")throw new Error(`Task name must be a string, got ${typeof e}`);this.name=e;let r=this.constructor.schema;if(r===n.schema&&typeof t<"u"&&Object.keys(t||{}).length>0)throw new Error(`Task "${e}" has no schema defined but params passed: ${JSON.stringify(t)}`);this._params=parse(r,t||{});}get params(){return this._params}clone(e,t){return new this.constructor(e,t)}static async resolveParams(e,t,r={}){let i={},s=new sr(r,{renderKeys:true});for(let[o,c]of Object.entries(t)){if(c&&sr.hasMarkup(c)){try{i[o]=await s.render(c);}catch(a){throw a instanceof ue?a:new ue("Failed to resolve param",{key:o,value:c,error:a.message},"resolve-params")}continue}i[o]=c;}return e.coerce(i)}async cloneWithResolvedParams(e){let t=Object.fromEntries(e.entries()),r=await n.resolveParams(this.constructor.schema,this._params,t);return this.clone(this.name,r)}async run(e=new Map){let t=new Date,r,i,s,o,a=performance.now();try{let l=await this.cloneWithResolvedParams(e);o=l.params,r=await l.execute(e),s=!0;}catch(l){s=false,l instanceof ue?i=l.toJSON():i={type:"unknown",message:l.message};}return {start:t,output:r,error:i,success:s,params:o,time:performance.now()-a}}error(e,t){return new ue(e,t,"runtime")}get label(){return this.name}toJSON(){return {type:this.type,params:this.params}}};var bs=["GET","POST","PUT","PATCH","DELETE"],gn=class extends we{type="fetch";static schema=s.strictObject({url:s.string({pattern:"^(http|https)://"}),method:Ze(s.string({enum:bs,default:"GET"})).optional(),headers:Ze(s.array(s.strictObject({key:s.string(),value:s.string()}))).optional(),body:Ze(s.string()).optional(),normal:Ze(s.number()).optional()});getBody(){let e=this.params.body;if(e){if(typeof e=="string")return e;if(typeof e=="object")return JSON.stringify(e);throw new Error(`Invalid body type: ${typeof e}`)}}async execute(){if(!bs.includes(this.params.method??"GET"))throw this.error("Invalid method",{given:this.params.method,valid:bs});let e=this.getBody(),t=new Headers(this.params.headers?.map(s=>[s.key,s.value])),r=await fetch(this.params.url,{method:this.params.method??"GET",headers:t,body:e});if(!r.ok)throw this.error("Failed to fetch",{status:r.status,statusText:r.statusText});return await r.json()}};var bn=class extends we{type="log";static schema=s.strictObject({delay:s.number({default:10})});async execute(){return await new Promise(e=>setTimeout(e,this.params.delay)),f.log(`[DONE] LogTask: ${this.name}`),true}};var wn=class extends we{type="render";static schema=s.strictObject({render:s.string()});async execute(){return this.params.render}};var Dt=class{source;target;config;id;constructor(e,t,r,i){this.source=e,this.target=t,this.config=r??{},this.config.condition instanceof It||(this.config.condition=It.default()),this.id=i??fo();}get condition(){return this.config.condition}get max_retries(){return this.config.max_retries??0}toJSON(){return Or({source:this.source.name,target:this.target.name,config:{...this.config,condition:this.config.condition?.toJSON()}})}},It=class n{constructor(e,t="",r=void 0){this.type=e;this.path=t;this.value=r;}static default(){return n.success()}static success(){return new n("success")}static error(){return new n("error")}static matches(e,t){if(typeof e!="string"||e.length===0)throw new Error("Invalid path");return new n("matches",e,t)}isMet(e){switch(this.type){case "success":return e.success;case "error":return e.success===false;case "matches":return get(e.output,this.path)===this.value}}sameAs(e=n.default()){return this.type===e.type&&this.path===e.path&&this.value===e.value}toJSON(){return {type:this.type,path:this.path.length===0?void 0:this.path,value:this.value}}static fromObject(e){return new n(e.type,e.path,e.value)}};var or=class extends v{static slug="flow-execution-event";task(){return this.params.task}getState(){return this.succeeded()?"success":this.failed()?"failed":this.isStart()?"running":"idle"}isStart(){return this.params.end===void 0}isEnd(){return !this.isStart()}succeeded(){return this.isEnd()&&this.params.result?.success}failed(){return this.isEnd()&&!this.params.result?.success}},ar=class extends v{static slug="flow-execution-state"},xn=class n{flow;started_at;finished_at;logs=[];inputs=new Map;queue=[];emgr;static Events={ExecutionEvent:or,ExecutionState:ar};constructor(e){this.flow=e,this.logs=[],this.queue=[this.flow.startTask],this.emgr=new $(n.Events);}subscribe(e){this.emgr.onAny(e);}async onDone(e,t){let r=new Date;if(this.logs.push({...t,task:e,end:r}),this.inputs.set(e.name,t),this.flow.respondingTask===e){this.queue=[];return}this.queue=this.queue.filter(s=>s!==e);let i=this.flow.task(e).getOutConnections(t).filter(s=>{let o=s.target,c=this.logs.filter(l=>l.task===o&&l.success).length,a=this.flow.task(o).getInConnections().find(l=>l.source===e)?.max_retries??0;if(c>a)throw new Error(`Task "${o.name}" reached max retries (${c}/${a})`);return this.flow.task(o).getInTasks(true).every(l=>this.logs.some(u=>u.task===l&&u.end!==void 0))}).map(s=>s.target);this.queue.push(...i);}__getLastTaskLog(e){for(let t=this.logs.length-1;t>=0;t--)if(this.logs[t]?.task===e)return this.logs[t];return null}async run(){let e=this.queue;if(e.length===0)return;let t=e.map(async r=>{await this.emgr.emit(new or({task:r}));let i=await r.run(this.inputs);return await this.emgr.emit(new or({task:r,result:i,end:new Date})),await this.onDone(r,i),i});try{return await Promise.all(t),this.run()}catch(r){throw f.error("RuntimeExecutor: error",r),r}}async start(e){await this.emgr.emit(new ar({execution:this,state:"started"})),this.inputs.set("flow",{start:new Date,output:e,error:void 0,success:true,params:e}),this.started_at=new Date,await this.run(),this.finished_at=new Date,await this.emgr.emit(new ar({execution:this,state:"ended"}));}finished(){return this.finished_at!==void 0}errorCount(){return this.logs.filter(e=>!e.success).length}hasErrors(){return this.errorCount()>0}getErrorLogs(){return this.logs.filter(e=>!e.success)}getErrors(){return this.getErrorLogs().map(e=>e.error)}getResponse(){let e=this.flow.respondingTask;e||(e=this.flow.tasks[this.flow.tasks.length-1]);let t=this.__getLastTaskLog(e);if(t)return t.output}};var En=class n{flow;source;constructor(e,t){this.flow=e,this.source=t;}task(e){return new n(this.flow,e)}asInputFor(e,t,r){let i=this.getDepth(),s=this.getOutConnections(),o=s.map(a=>a.condition),c=s.some(a=>this.task(a.target).getDepth()<=i);if(o.length>0&&c&&this.getOutConnections().some(a=>a.condition.sameAs(t)))throw new Error("Task cannot be connected to a deeper task with the same condition");this.flow.addConnection(new Dt(this.source,e,{condition:t,max_retries:r}));}asOutputFor(e,t){this.task(e).asInputFor(this.source,t);}getNext(){return this.flow.connections.filter(e=>e.source===this.source).map(e=>e.target)}getDepth(){return this.flow.getSequence().findIndex(e=>e.includes(this.source))}getInConnections(e=false){if(e){let t=this.getDepth();return this.getInConnections().filter(r=>r.target===this.source&&this.task(r.source).getDepth()<t)}return this.flow.connections.filter(t=>t.target===this.source)}getInTasks(e=false){if(e){let t=this.getDepth();return this.getInConnections().map(r=>r.source).filter(r=>this.task(r).getDepth()<t)}return this.getInConnections().map(t=>t.source)}getOutConnections(e){return e?this.flow.connections.filter(t=>t.source===this.source&&t.condition.isMet(e)):this.flow.connections.filter(t=>t.source===this.source)}getOutTasks(e){return this.getOutConnections(e).map(t=>t.target)}};var X=class{executions=[];type="manual";config;static schema=s.strictObject({mode:s.string({enum:["sync","async"],default:"async"})});constructor(e){let t=this.constructor.schema;this.config=parse(t,e??{});}async register(e,...t){this.executions.push(await e.start());}toJSON(){return {type:this.type,config:this.config}}};var et=class n{name;trigger;tasks=[];connections=[];respondingTask;startTask;sequence;constructor(e,t,r,i){this.name=e,this.trigger=i??new X,t.map(s=>this.addTask(s)),this.connections=r||[],this.startTask=t[0],this.sequence=this.getSequence();}setStartTask(e){return this.startTask=e,this.sequence=this.getSequence(),this}getSequence(e=[]){if(e.length===0)return e.push([this.startTask]),this.getSequence(e);let t=e[e.length-1],r=[];return t?.forEach(i=>{this.task(i).getOutTasks().forEach(o=>{e.some(c=>c.includes(o))||r.push(o);});}),r.length===0?e:(e.push(r),this.getSequence(e))}addTask(e){if(this.tasks.includes(e))throw new Error("Task already defined");if(this.tasks.some(t=>t.name===e.name))throw new Error(`Task with name "${e.name}" already defined. Use a unique name.`);return this.tasks.push(e),this}setRespondingTask(e){if(!this.tasks.includes(e))throw new Error(`Cannot set task "${e.name}" as responding, not registered.`);return this.respondingTask=e,this}addConnection(e){if(this.connections.some(r=>r.source===e.source&&r.target===e.target&&r.condition[0]===e.condition[0]&&r.condition[1]===e.condition[1]))throw new Error("Connection already defined");return this.connections.push(e),this}task(e){return new En(this,e)}createExecution(){return this.sequence=this.getSequence(),new xn(this)}async start(e=void 0){let t=this.createExecution();return await t.start(e),t}toJSON(){return {trigger:this.trigger.toJSON(),tasks:Object.fromEntries(this.tasks.map(e=>[e.name,e.toJSON()])),connections:Object.fromEntries(this.connections.map(e=>[e.id,e.toJSON()])),start_task:this.startTask?.name,responding_task:this.respondingTask?.name}}static fromObject(e,t,r){let i=P(t.tasks??{},(a,l)=>{let u=r[a.type];if(!u)throw new Error(`Task ${l} not found in taskMap`);try{let p=u.cls;return new p(l,a.params)}catch(p){throw f.error("Error creating task",l,a.type,a,u),new Error(`Error creating task ${a.type}: ${p.message}`)}}),s=P(t.connections??{},(a,l)=>{let u=a.config.condition?It.fromObject(a.config.condition):void 0;return new Dt(i[a.source],i[a.target],{...a.config,condition:u},l)}),o;if(t.trigger){let a=cr[t.trigger.type]?.cls;a&&(o=new a(t.trigger.config));}let c=new n(e,Object.values(i),Object.values(s),o);return c.startTask=t.start_task?i[t.start_task]:null,t.responding_task&&(c.respondingTask=i[t.responding_task]),c}};var Sn=class extends we{type="subflow";static schema=s.strictObject({flow:s.any(),input:Ze(s.any()).optional(),loop:s.boolean().optional()});async execute(){let e=this.params.flow;if(!(e instanceof et))throw new Error("Invalid flow provided");if(this.params.loop){let r=Array.isArray(this.params.input)?this.params.input:[this.params.input],i=[];for(let s of r){let o=e.createExecution();await o.start(s),i.push(await o.getResponse());}return i}let t=e.createExecution();return await t.start(this.params.input),t.getResponse()}};var lr=class extends X{type="event";static schema=s.strictObject({event:s.string(),...X.schema.properties});async register(e,t){if(!t.eventExists(this.config.event))throw new Error(`Event ${this.config.event} is not registered.`);t.on(this.config.event,async r=>{let i=e.createExecution();this.executions.push(i);try{await i.start(r.params);}catch(s){f.error(s);}},this.config.mode);}};var gu=["GET","POST","PUT","PATCH","DELETE"],tt=class extends X{type="http";static schema=s.strictObject({path:s.string({pattern:"^/.*$"}),method:s.string({enum:gu,default:"GET"}),response_type:s.string({enum:["json","text","html"],default:"json"}),...X.schema.properties});async register(e,t){let r=this.config.method.toLowerCase();t[r](this.config.path,async i=>{let s=i.req.raw,o=i[this.config.response_type],c=e.createExecution();if(this.executions.push(c),this.config.mode==="sync"){await c.start(s);let a=c.getResponse(),l=c.getErrors();return l.length>0?i.json({success:false,errors:l}):o(a)}return c.start(s),i.json({success:true})});}};var cr={manual:{cls:X},event:{cls:lr},http:{cls:tt}};var ma={fetch:{cls:gn},log:{cls:bn},render:{cls:wn},subflow:{cls:Sn}};var ws={...ma},bu=cr,fa=P(ws,(n,e)=>s.strictObject({type:s.literal(e),params:n.cls.schema},{title:String(e)}));s.anyOf(Object.values(fa));var ya=P(bu,(n,e)=>s.strictObject({type:s.literal(e),config:n.cls.schema.optional()},{title:String(e)}));s.anyOf(Object.values(ya));var wu=s.strictObject({source:s.string(),target:s.string(),config:s.strictObject({condition:s.anyOf([s.strictObject({type:s.literal("success")},{title:"success"}),s.strictObject({type:s.literal("error")},{title:"error"}),s.strictObject({type:s.literal("matches"),path:s.string(),value:s.string()},{title:"matches"})]),max_retries:s.number()}).partial()}),xu=s.strictObject({trigger:s.anyOf(Object.values(ya)),tasks:s.record(s.anyOf(Object.values(fa))).optional(),connections:s.record(wu).optional(),start_task:s.string().optional(),responding_task:s.string().optional()}),ha=s.strictObject({basepath:s.string({default:"/api/flows"}),flows:s.record(xu,{default:{}})});var Rn=class extends Q{flows={};getSchema(){return ha}getFlowInfo(e){return {...e.toJSON(),tasks:e.tasks.length,connections:e.connections}}async build(){let e=transformObject(this.config.flows,(r,i)=>et.fromObject(i,r,ws));this.flows=e;let t=new Hono;t.get("/",async r=>{let i=transformObject(this.flows,s=>this.getFlowInfo(s));return r.json(i)}),t.get("/flow/:name",async r=>{let i=r.req.param("name");return r.json(this.flows[i]?.toJSON())}),t.get("/flow/:name/run",async r=>{let i=r.req.param("name"),s=this.flows[i],o=s.createExecution(),c=performance.now();await o.start();let a=performance.now()-c,l=o.getErrors();return r.json({success:l.length===0,time:a,errors:l,response:o.getResponse(),flow:this.getFlowInfo(s),logs:o.logs})}),t.all("*",r=>r.notFound()),this.ctx.server.route(this.config.basepath,t);for(let[r,i]of Object.entries(this.flows)){let s=i.trigger;switch(true){case s instanceof tt:await s.register(i,this.ctx.server);break}}this.setBuilt();}toJSON(){return {...this.config,flows:transformObject(this.flows,e=>e.toJSON())}}};var qt={};Be(qt,{FileAccessEvent:()=>dr,FileDeletedEvent:()=>pr,FileUploadedEvent:()=>ur});var ur=class extends v{static slug="file-uploaded";validate(e){if(typeof e!="object")throw new le("object",typeof e);return this.clone({...e,...this.params})}},pr=class extends v{static slug="file-deleted"},dr=class extends v{static slug="file-access"};var rt=class n{#e;static Events=qt;emgr;config;constructor(e,t={},r){this.#e=e,this.config={...t,body_max_size:t.body_max_size&&t.body_max_size>0?t.body_max_size:void 0},this.emgr=r??new $,this.emgr.registerEvents(n.Events);}getAdapter(){return this.#e}async objectMetadata(e){return await this.#e.getObjectMeta(e)}getConfig(){return this.config}async uploadFile(e,t,r){let i=await this.#e.putObject(t,e);if(typeof i>"u")throw new Error("Failed to upload file");let s={name:t,meta:{size:0,type:"application/octet-stream"},etag:typeof i=="string"?i:""};if(typeof i=="object"?s=i:hi(e)&&(s.meta.size=e.size,s.meta.type=e.type),!so(s.meta.type,["application/octet-stream","application/json"])){let c=await this.#e.getObjectMeta(t);if(!c)throw new Error("Failed to get object meta");s.meta=c;}if(s.meta.type.startsWith("image")&&(!s.meta.width||!s.meta.height))try{let c=await ao(e);s.meta={...s.meta,...c};}catch(c){f.warn("Failed to get image dimensions",c);}let o={file:e,...s,state:{name:s.name,path:s.name}};if(!r){let c=await this.emgr.emit(new ur(o));if(c.returned)return c.params}return o}async deleteFile(e){await this.#e.deleteObject(e),await this.emgr.emit(new pr({name:e}));}async fileExists(e){return await this.#e.objectExists(e)}};var mr={};Be(mr,{deleteFile:()=>Ss,listFiles:()=>vs,readFile:()=>Es,uploadFile:()=>Cn});var Es=new x("media.file.read"),vs=new x("media.file.list"),Cn=new x("media.file.upload"),Ss=new x("media.file.delete");function ga(n){if(!n.includes("."))return;let e=n.split(".");return e[e.length-1]?.toLowerCase()}function On(n,e=16){let t=typeof n=="string"?n:n.name;if(typeof t!="string")throw console.error("Couldn't extract filename from",n),new Error("Invalid file name");let r=ga(t);if(!r&&isFile(n)&&n.type){let i=oo(n.type);i.length>0&&(r=i);}return [randomString(e),r].filter(Boolean).join(".")}var _n=class extends ae{constructor(t){super();this.media=t;}getStorageAdapter(){return this.getStorage().getAdapter()}getStorage(){return this.media.storage}getController(){let{auth:t,permission:r}=this.middlewares,i=this.create().use(t()),s$1=this.getEntitiesEnum(this.media.em);i.get("/files",describeRoute({summary:"Get the list of files",tags:["media"]}),r(vs),async a=>{let l=await this.getStorageAdapter().listObjects();return a.json(l)}),i.get("/file/:filename",describeRoute({summary:"Get a file by name",tags:["media"]}),r(Es),async a=>{let{filename:l}=a.req.param();if(!l)throw new Error("No file name provided");await this.getStorage().emgr.emit(new dr({name:l}));let u=await this.getStorageAdapter().getObject(l,a.req.raw.headers),p=new Headers(u.headers);return p.set("Cache-Control","public, max-age=31536000, immutable"),new Response(u.body,{status:u.status,statusText:u.statusText,headers:p})}),i.delete("/file/:filename",describeRoute({summary:"Delete a file by name",tags:["media"]}),r(Ss),async a=>{let{filename:l}=a.req.param();if(!l)throw new Error("No file name provided");return await this.getStorage().deleteFile(l),a.json({message:"File deleted"})});let o=this.getStorage().getConfig().body_max_size??Number.POSITIVE_INFINITY;A()&&i.post("/inspect",describeRoute({summary:"Inspect a file",tags:["media"]}),async a=>{let l=await getFileFromContext(a);return a.json({type:l?.type,name:l?.name,size:l?.size})});let c={content:{"multipart/form-data":{schema:{type:"object",properties:{file:{type:"string",format:"binary"}},required:["file"]}},"application/octet-stream":{schema:{type:"string",format:"binary"}}}};return i.post("/upload/:filename?",describeRoute({summary:"Upload a file",tags:["media"],requestBody:c}),jsc("param",s.object({filename:s.string().optional()})),r(Cn),async a=>{let l=a.req.param("filename"),u=await getFileFromContext(a);if(!u)return a.json({error:"No file provided"},HttpStatus.BAD_REQUEST);if(u.size>o)return a.json({error:`Max size (${o} bytes) exceeded`},HttpStatus.PAYLOAD_TOO_LARGE);let p=l??On(u),d=await this.getStorage().uploadFile(u,p);return a.json(d,HttpStatus.CREATED)}),i.post("/entity/:entity/:id/:field",describeRoute({summary:"Add a file to an entity",tags:["media"],requestBody:c}),jsc("param",s.object({entity:s$1,id:s.number(),field:s.string()})),jsc("query",s.object({overwrite:s.boolean().optional()})),r([Ve,Cn]),async a=>{let l=a.req.param("entity"),u=a.req.param("field"),p=Number.parseInt(a.req.param("id")),d=this.media.em.entity(l);if(!d)return a.json({error:`Entity "${l}" not found`},HttpStatus.NOT_FOUND);let m=d.field(u);if(!m||!(m instanceof Te))return a.json({error:`Invalid field "${u}"`},HttpStatus.BAD_REQUEST);let h=this.media.getMediaEntity().name,F=`${l}.${u}`,_={scope:u,reference:F,entity_id:p},ce=m.getMaxItems(),ri=[];if(ce){let{overwrite:ii}=a.req.valid("query"),{data:{count:Sr}}=await this.media.em.repository(h).count(_);if(Sr>=ce){if(!ii)return a.json({error:`Max items (${ce}) reached`},HttpStatus.BAD_REQUEST);if(Sr>ce)return a.json({error:`Max items (${ce}) exceeded already with ${Sr} items.`},HttpStatus.UNPROCESSABLE_ENTITY);let si=await this.media.em.repo(h).findMany({select:["path"],where:_,sort:{by:"id",dir:"asc"},limit:Sr-ce+1});si.data&&si.data.length>0&&si.data.map(Xa=>ri.push(Xa.path));}}let{data:{exists:Va}}=await this.media.em.repository(d).exists({id:p});if(!Va)return a.json({error:`Entity "${l}" with ID "${p}" doesn't exist found`},HttpStatus.NOT_FOUND);let vr=await getFileFromContext(a);if(!vr)return a.json({error:"No file provided"},HttpStatus.BAD_REQUEST);if(vr.size>o)return a.json({error:`Max size (${o} bytes) exceeded`},HttpStatus.PAYLOAD_TOO_LARGE);let Ha=On(vr),Vs=await this.getStorage().uploadFile(vr,Ha,true),ni=this.media.em.mutator(h);ni.__unstable_toggleSystemEntityCreation(false);let Ya=await ni.insertOne({...this.media.uploadedEventDataToMediaPayload(Vs),..._});if(ni.__unstable_toggleSystemEntityCreation(true),ri.length>0)for(let ii of ri)await this.getStorage().deleteFile(ii);return a.json({ok:true,result:Ya.data,...Vs},HttpStatus.CREATED)}),i}};var An=class{constructor(e){this.registerFn=e;}is_set=false;items={};set(e){if(this.is_set)throw new Error("Registry is already set");return this.items=e,this.is_set=true,this}add(e,t){return this.items[e]=t,this}register(e,t){if(this.registerFn){let r=this.registerFn(t);return this.items[e]=r,this}return this.add(e,t)}get(e){return this.items[e]}has(e){return e in this.items}all(){return this.items}};var kn=class extends AwsClient{#e;constructor(e,t){super(e),this.#e=t??{responseType:"json"};}convertParams(e){switch(this.#e.convertParams){case "pascalToKebab":return Cr(e);default:return e}}getUrl(e="/",t={}){let r=new URL(e),i=this.convertParams(t);return Object.entries(i).forEach(([s,o])=>{r.searchParams.append(s,o);}),r.toString()}updateKeysRecursively(e,t){return e==null?e:Array.isArray(e)?e.map(r=>this.updateKeysRecursively(r,t)):typeof e=="object"?Object.keys(e).reduce((r,i)=>{let s=i;return i.indexOf(" ")===-1&&(s=i.charAt(0)[t]()+i.slice(1)),r[s]=this.updateKeysRecursively(e[i],t),r},{}):e}async fetchJson(e,t){let r=await this.fetch(e,t);if(this.#e.responseType==="xml"){if(!r.ok){let o=await r.text();throw new Error(o)}let s=await r.text();return lo(s)}if(!r.ok){let s=await r.json();throw new Error(s.message)}let i=await r.json();return this.#e.responseKeysToUpper?this.updateKeysRecursively(i,"toUpperCase"):i}};var ba=Symbol.for("bknd:storage"),it=class{constructor(){this[ba]=true;}static isAdapter(e){return e?e[ba]===true:false}};var wa=s.object({access_key:s.string(),secret_access_key:s.string(),url:s.string({pattern:"^https?://(?:.*)?[^/.]+$",description:"URL to S3 compatible endpoint without trailing slash",examples:["https://{account_id}.r2.cloudflarestorage.com/{bucket}","https://{bucket}.s3.{region}.amazonaws.com"]})},{title:"AWS S3",description:"AWS S3 or compatible storage"}),st=class extends it{#e;client;constructor(e){super(),this.client=new kn({accessKeyId:e.access_key,secretAccessKey:e.secret_access_key,retries:A()?0:10},{convertParams:"pascalToKebab",responseType:"xml"}),this.#e=parse(wa,e);}getName(){return "s3"}getSchema(){return wa}getUrl(e="",t={}){let r=this.getObjectUrl("").slice(0,-1);return e.length>0&&(r+=`/${e}`),this.client.getUrl(r,t)}getObjectUrl(e){return `${this.#e.url}/${e}`}async listObjects(e=""){let t={ListType:2,Prefix:e},r=this.getUrl("",t),i=await this.client.fetchJson(r,{method:"GET"}),{Contents:s}=i.ListBucketResult,o=s?Array.isArray(s)?s:[s]:[];return transform(o,(a,l)=>{l.Key&&l.LastModified&&l.Size&&a.push({key:l.Key,last_modified:l.LastModified,size:l.Size});},[])}async putObject(e,t,r={}){let i=this.getUrl(e,{}),s=await this.client.fetch(i,{method:"PUT",body:t,headers:isFile(t)?{"Content-Length":String(t.size)}:{}});if(!s.ok)throw new Error(`Failed to upload object: ${s.status} ${s.statusText}`);return String(s.headers.get("etag"))}async headObject(e,t={}){let r=this.getUrl(e,{});return await this.client.fetch(r,{method:"HEAD",headers:{Range:"bytes=0-1"}})}async getObjectMeta(e){let t=await this.headObject(e),r=String(t.headers.get("content-type")),i=Number(String(t.headers.get("content-range")?.split("/")[1]));return {type:r,size:i}}async objectExists(e,t={}){return (await this.headObject(e)).ok}async getObject(e,t){let r=this.getUrl(e),i=await this.client.fetch(r,{method:"GET",headers:pickHeaders2(t,["if-none-match","accept-encoding","accept","if-modified-since"])});return new Response(i.body,{status:i.status,statusText:i.statusText,headers:i.headers})}async deleteObject(e,t={}){let r=this.getUrl(e,t);await this.client.fetch(r,{method:"DELETE"});}toJSON(e){return {type:this.getName(),config:e?this.#e:void 0}}};var xa=s.object({cloud_name:s.string(),api_key:s.string(),api_secret:s.string(),upload_preset:s.string().optional()},{title:"Cloudinary",description:"Cloudinary media storage"}),ot=class extends it{config;constructor(e){super(),this.config=parse(xa,e);}getSchema(){return xa}getMimeType(e){switch(true){case(e.format==="jpeg"||e.format==="jpg"):return "image/jpeg"}return `${e.resource_type}/${e.format}`}getName(){return "cloudinary"}getAuthorizationHeader(){return {Authorization:`Basic ${btoa(`${this.config.api_key}:${this.config.api_secret}`)}`}}async putObject(e,t){let r=e.replace(/\.[a-z0-9]{2,5}$/,""),i=new FormData;i.append("file",t),i.append("public_id",r),i.append("api_key",this.config.api_key),this.config.upload_preset&&i.append("upload_preset",this.config.upload_preset);let s=await fetch(`https://api.cloudinary.com/v1_1/${this.config.cloud_name}/auto/upload`,{method:"POST",headers:{Accept:"application/json"},body:i});if(!s.ok)return;let o=await s.json();return {name:o.public_id+"."+o.format,etag:o.etag,meta:{type:this.getMimeType(o),size:o.bytes}}}async listObjects(e){let t=await fetch(`https://api.cloudinary.com/v1_1/${this.config.cloud_name}/resources/search`,{method:"GET",headers:{Accept:"application/json","Cache-Control":"no-cache",...this.getAuthorizationHeader()}});if(!t.ok)throw new Error("Failed to list objects");return (await t.json()).resources.map(s=>({key:s.public_id,last_modified:new Date(s.uploaded_at),size:s.bytes}))}async headObject(e){let t=this.getObjectUrl(e);return await fetch(t,{method:"HEAD",headers:{"Cache-Control":"no-cache, no-store, must-revalidate",Pragma:"no-cache",Expires:"0",Range:"bytes=0-1"}})}async objectExists(e){return (await this.headObject(e)).ok}async getObjectMeta(e){let t=await this.headObject(e);if(t.ok){let r=t.headers.get("content-type"),i=Number(t.headers.get("content-range")?.split("/")[1]);return {type:r,size:i}}throw new Error("Cannot get object meta")}guessType(e){let t={image:["jpg","jpeg","png","gif","webp","svg"],video:["mp4","webm","ogg"]},r=e.split(".").pop();return Object.keys(t).find(i=>t[i].includes(r))}getObjectUrl(e){let t=this.guessType(e)??"image";return `https://res.cloudinary.com/${this.config.cloud_name}/${t}/upload/${e}`}async generateSignature(e,t){let r=e.timestamp??Math.floor(Date.now()/1e3),i=Object.entries({...e,timestamp:r}).sort(([o],[c])=>o.localeCompare(c)).map(([o,c])=>`${o}=${c}`).join("&");return {signature:await kr.sha1(i+(t??this.config.api_secret)),timestamp:r}}filenameToPublicId(e){return e.split(".").slice(0,-1).join(".")}async getObject(e,t){let r=await fetch(this.getObjectUrl(e),{method:"GET",headers:co(t,["range"])});return new Response(r.body,{status:r.status,statusText:r.statusText,headers:r.headers})}async deleteObject(e){let t=this.guessType(e)??"image",r=this.filenameToPublicId(e),{timestamp:i,signature:s}=await this.generateSignature({public_id:r}),o=new FormData;o.append("public_id",r),o.append("timestamp",String(i)),o.append("signature",s),o.append("api_key",this.config.api_key);let c=`https://api.cloudinary.com/v1_1/${this.config.cloud_name}/${t}/destroy`,a=await fetch(c,{headers:{Accept:"application/json","Cache-Control":"no-cache",...this.getAuthorizationHeader()},method:"POST",body:o});if(!a.ok)throw new Error(`Failed to delete object: ${a.status} ${a.statusText}`)}toJSON(e){return {type:"cloudinary",config:e?this.config:{cloud_name:this.config.cloud_name}}}};var Ea=new An(n=>({cls:n,schema:n.prototype.getSchema()})).register("s3",st).register("cloudinary",ot);({s3:{schema:st.prototype.getSchema()},cloudinary:{schema:ot.prototype.getSchema()}});var Cs={media:Ea};var Os=Cs.media;function _s(){let n=objectTransform(Os.all(),(e,t)=>s.strictObject({type:s.literal(t),config:e.schema},{title:e.schema?.title??t,description:e.schema?.description}));return s.strictObject({enabled:s.boolean({default:false}),basepath:s.string({default:"/api/media"}),entity_name:s.string({default:"media"}),storage:s.strictObject({body_max_size:s.number({description:"Max size of the body in bytes. Leave blank for unlimited."}).optional()},{default:{}}),adapter:s.anyOf(Object.values(n)).optional()},{default:{}})}_s();var Pn={path:se().required(),folder:es({default_value:false,hidden:true,fillable:["create"]}),mime_type:se(),size:St(),scope:se({hidden:true,fillable:["create"]}),etag:se(),modified_at:Tt(),reference:se(),entity_id:St(),metadata:ts()};var Mn=class n extends Q{_storage;async build(){if(!this.config.enabled){this.setBuilt();return}if(!this.config.adapter){console.info("No storage adapter provided, skip building media.");return}let e;try{let{type:t,config:r}=this.config.adapter,i=Os.get(t).cls;e=new i(r),this._storage=new rt(e,this.config.storage,this.ctx.emgr),this.setBuilt(),this.setupListeners(),this.ctx.guard.registerPermissions(mr),this.ctx.server.route(this.basepath,new _n(this).getController());let s=this.getMediaEntity(!0);this.ctx.helper.ensureSchema(Ht({[s.name]:s},({index:o},{media:c})=>{o(c).on(["path"],!0).on(["reference"]).on(["entity_id"]);}));}catch(t){throw console.error(t),new Error(`Could not build adapter with config ${JSON.stringify(this.config.adapter)}`)}}getSchema(){return _s()}get basepath(){return this.config.basepath}get storage(){return this.throwIfNotBuilt(),this._storage}uploadedEventDataToMediaPayload(e){let t={};return e.meta.width&&e.meta.height&&(t.width=e.meta.width,t.height=e.meta.height),{path:e.name,mime_type:e.meta.type,size:e.meta.size,etag:e.etag,modified_at:new Date,metadata:t}}static mediaFields=Pn;getMediaEntity(e){let t=this.config.entity_name;return e||!this.em.hasEntity(t)?Ge(t,n.mediaFields,void 0,"system"):this.em.entity(t)}get em(){return this.ctx.em}setupListeners(){let{emgr:e,em:t}=this.ctx,r=this.getMediaEntity().name;e.onEvent(rt.Events.FileUploadedEvent,async i=>{let s=t.mutator(r);s.__unstable_toggleSystemEntityCreation(false);let o=this.uploadedEventDataToMediaPayload(i.params),{data:c}=await s.insertOne(o);return s.__unstable_toggleSystemEntityCreation(true),{data:c}},{mode:"sync",id:"add-data-media"}),e.onEvent(rt.Events.FileDeletedEvent,async i=>{let{data:s}=await t.repo(r).findOne({path:i.params.name});s&&await t.mutator(r).deleteOne(s.id),f.log("App:storage:file deleted",i.params);},{mode:"sync",id:"delete-data-media"});}getOverwritePaths(){return [/^\.?adapter$/]}toJSON(e){return !this.isBuilt()||!this.config.enabled?this.configDefault:{...this.config,adapter:this.storage.getAdapter().toJSON(e)}}};var jn=class{constructor(e){this.ctx=e;}get em(){return this.ctx.em}get flags(){return this.ctx.flags}ensureEntity(e){let t=this.em.entity(e.name,true);if(!t){this.em.addEntity(e),this.flags.sync_required=true;return}for(let r of e.fields){let i=t.field(r.name);i?this.setEntityFieldConfigs(r,i)>0&&(this.flags.sync_required=true):(t.addField(r),this.flags.sync_required=true);}if(t.type!==e.type){let r=zt.indexOf(t.type),s=zt.indexOf(e.type)>r?e.type:t.type;this.em.__replaceEntity(new z(t.name,t.fields,t.config,s));}}ensureIndex(e){this.em.hasIndex(e)||(this.em.addIndex(e),this.flags.sync_required=true);}ensureRelation(e){try{this.em.addRelation(e),this.flags.sync_required=!0;}catch{}this.em.relations.exists(e);}ensureSchema(e){return Object.values(e.entities??{}).forEach(this.ensureEntity.bind(this)),e.indices?.forEach(this.ensureIndex.bind(this)),e.relations?.forEach(this.ensureRelation.bind(this)),e}setEntityFieldConfigs(e,t,r=["hidden","fillable","required"]){let i=0;for(let s of r)isEqual(t.config[s],e.config[s])||(t.config[s]=e.config[s],i++);return i}replaceEntityField(e,t,r){let i=this.em.entity(e),s=typeof t=="string"?t:t.name,o=r instanceof N?ns(s,r):r;this.setEntityFieldConfigs(i.field(s),o),i.__replaceField(s,o);}};var hr={server:rn,data:hn,auth:Pt,media:Mn,flows:Rn},Ta=Object.keys(hr);var Iu=s.anyOf([Ra(),s.array(s.strictObject({t:s.string({enum:["a","r","e"]}),p:s.array(s.anyOf([s.string(),s.number()])),o:s.any().optional(),n:s.any().optional()}))]),As=Ge(Qo,{version:St().required(),type:Rt({enum:["config","diff","backup"]}).required(),json:rs({schema:Iu.toJSON()}).required(),created_at:Tt(),updated_at:Tt()}),qu=Qt("modules_debug"),ks=class extends v{},Dn=class extends ks{static slug="mm-config-update"},Fs={ModuleManagerConfigUpdateEvent:Dn},In=class{constructor(e,t){this.connection=e;this.options=t;this.__em=new Me([As],this.connection),this.modules={},this.emgr=new $({...Fs}),this.logger=new Dr(qu);let r={};if(t?.initial)if("version"in t.initial){let{version:i,...s}=t.initial;this._version=i,r=stripMark(s),this._booted_with="provided";}else r=mergeWith(Ca(),t.initial),this._booted_with="partial";this.logger.log("booted with",this._booted_with),this.createModules(r);}static Events=Fs;modules;__em;em;server;emgr;guard;_version=0;_built=false;_booted_with;_stable_configs;logger;createModules(e){this.logger.context("createModules").log("creating modules");try{let t=this.ctx(!0);for(let r in hr){let i=e&&r in e?e[r]:{},s=new hr[r](i,t);s.setListener(async o=>{await this.onModuleConfigUpdated(r,o);}),this.modules[r]=s;}this.logger.log("modules created");}catch(t){throw this.logger.log("failed to create modules",t),t}this.logger.clear();}get verbosity(){return this.options?.verbosity??0}isBuilt(){return this._built}async onModuleConfigUpdated(e,t){this.options?.onUpdated?await this.options.onUpdated(e,t):await this.buildModules();}repo(){return this.__em.repo(As,{silent:true,includeCounts:false})}mutator(){return this.__em.mutator(As)}get db(){return this.connection.kysely}async syncConfigTable(){this.logger.context("sync").log("start");let e=await this.__em.schema().sync({force:true});return this.logger.log("done").clear(),e}rebuildServer(){this.server=new Hono,this.options?.basePath&&(this.server=this.server.basePath(this.options.basePath)),this.options?.onServerInit&&this.options.onServerInit(this.server),objectEach(this.modules,e=>{e.onServerInit(this.server);});}ctx(e){e&&(this.rebuildServer(),this.em=this.em?this.em.clear():new Me([],this.connection,[],[],this.emgr),this.guard=new jr);let t={connection:this.connection,server:this.server,em:this.em,emgr:this.emgr,guard:this.guard,flags:Q.ctx_flags,logger:this.logger};return {...t,helper:new jn(t)}}async fetch(){this.logger.context("fetch").log("fetching");let e=performance.now(),{data:t}=await this.repo().findOne({type:"config"},{sort:{by:"version",dir:"desc"}});if(!t){this.logger.log("error fetching").clear();return}return this.logger.log("took",performance.now()-e,"ms",{version:t.version,id:t.id}).clear(),t}async save(){this.logger.context("save").log("saving version",this.version());let e=this.configs(),t=this.version();try{let r=await this.fetch();if(!r)throw new ue("no config found");if(this.logger.log("fetched version",r.version),r.version!==t)this.logger.log("version conflict, storing new version",r.version,t),await this.mutator().insertOne({version:r.version,type:"backup",json:e}),await this.mutator().insertOne({version:t,type:"config",json:e});else {this.logger.log("version matches",r.version);let i=Eo(r.json,dt(e));if(this.logger.log("checking diff",[i.length]),i.length>0){this.validateDiffs(i);let s=new Date;await this.mutator().insertOne({version:t,type:"diff",json:dt(i),created_at:s,updated_at:s}),await this.mutator().updateWhere({version:t,json:e,updated_at:s},{type:"config",version:t});}else this.logger.log("no diff, not saving");}}catch(r){if(r instanceof ue&&r.message==="no config found")this.logger.log("no config, just save fresh"),await this.mutator().insertOne({type:"config",version:t,json:e,created_at:new Date,updated_at:new Date});else throw r instanceof O?($console.error("ModuleManager: Cannot save invalid config"),this.revertModules(),r):($console.error("ModuleManager: Aborting"),this.revertModules(),r)}return this.setConfigs(e),this.logger.clear(),this}revertModules(){this._stable_configs?($console.warn("ModuleManager: Reverting modules"),this.setConfigs(this._stable_configs)):$console.error("ModuleManager: No stable configs to revert to");}validateDiffs(e){let t=[...new Set(e.map(r=>r.p[0]))];if(t.length!==0)for(let r of t){let i=r,s=this.get(i);if(!s){let o="validateDiffs: module not registered";throw $console.error(o,JSON.stringify({module:i,diffs:e},null,2)),new Error(o)}if(this._stable_configs?.[i]){let o=dt(this._stable_configs?.[i]),c=vo({[i]:o},e)[i];s.onBeforeUpdate(o,c);}}}setConfigs(e){this.logger.log("setting configs"),objectEach(e,(t,r)=>{try{this.modules[r].schema().set(t,!0);}catch(i){throw console.error(i),new Error(`Failed to set config for module ${r}: ${JSON.stringify(t,null,2)}`)}});}async build(e){if(this.logger.context("build").log("version",this.version()),await this.ctx().connection.init(),this.version()===0||e?.fetch===true){e?.fetch&&this.logger.log("force fetch");let t=await this.fetch();if(!t)this.logger.log("nothing in database, go initial"),await this.setupInitial();else if(this.logger.log("db has",t.version),this._version=t.version,this.options?.trustFetched===true&&(this.logger.log("trusting fetched config (mark)"),mark(t.json)),this.version()!==Ct){this.logger.log("now migrating"),await this.syncConfigTable();let r=this.version(),[i,s]=await Ko(r,t.json,{db:this.db});this._version=i,this.ctx().flags.sync_required=true,this.logger.log("migrated to",i),$console.log("Migrated config from",r,"to",this.version()),this.createModules(s),await this.buildModules();}else this.logger.log("version is current",this.version()),this.createModules(t.json),await this.buildModules();}else {if(this.version()!==Ct)throw new Error(`Given version (${this.version()}) and current version (${Ct}) do not match.`);this.logger.log("current version is up to date",this.version()),await this.buildModules();}return this.logger.log("done"),this.logger.clear(),this}async buildModules(e){let t={built:false,modules:[],synced:false,saved:false,reloaded:false};if(this.logger.context("buildModules").log("triggered",e,this._built),e?.graceful&&this._built)return this.logger.log("skipping build (graceful)"),t;this.logger.log("building");let r=this.ctx(true);for(let i in this.modules)await this.modules[i].setContext(r).build(),this.logger.log("built",i),t.modules.push(i);return this._built=t.built=true,this.logger.log("modules built",r.flags),this.options?.onModulesBuilt&&await this.options.onModulesBuilt(r),e?.ignoreFlags!==true&&(r.flags.sync_required&&(r.flags.sync_required=false,this.logger.log("db sync requested"),await r.em.schema().sync({force:true}),t.synced=true,await this.save(),t.saved=true),r.flags.ctx_reload_required&&(r.flags.ctx_reload_required=false,this.logger.log("ctx reload requested"),this.ctx(true),t.reloaded=true)),this.logger.log("resetting flags"),r.flags=Q.ctx_flags,this._stable_configs=dt(this.configs()),this.logger.clear(),t}async setupInitial(){this.logger.context("initial").log("start"),this._version=Ct,await this.syncConfigTable(),(await this.buildModules()).saved||await this.save();let t={...this.ctx(),em:this.ctx().em.fork()};await t.em.schema().sync({force:true}),await this.options?.seed?.(t),await this.options?.onFirstBoot?.(),this.logger.clear();}mutateConfigSafe(e){let t=this.modules[e];return new Proxy(t.schema(),{get:(r,i)=>{if(!["set","patch","overwrite","remove"].includes(i))throw new Error(`Method ${i} is not allowed`);return async(...s)=>{$console.log("[Safe Mutate]",e);try{t.setListener(async()=>{await this.emgr.emit(new Dn({ctx:this.ctx(),module:e,config:t.config})),await this.buildModules();});let o=await r[i](...s);return t.setListener(async c=>{await this.onModuleConfigUpdated(e,c);}),this.options?.onUpdated&&await this.options.onUpdated(e,t.config),o}catch(o){throw $console.error(`[Safe Mutate] failed "${e}":`,o),this.revertModules(),await this.onModuleConfigUpdated(e,t.config),$console.warn(`[Safe Mutate] reverted "${e}":`),o}}}})}get(e){if(!(e in this.modules))throw new Error(`Module "${e}" doesn't exist, cannot get`);return this.modules[e]}version(){return this._version}built(){return this._built}configs(){return transformObject(this.modules,e=>e.toJSON(true))}getSchema(){let e=transformObject(this.modules,t=>t.getSchema());return {version:this.version(),...e}}toJSON(e){let t=transformObject(this.modules,r=>{if(this._built)return r.isBuilt()?r.toJSON(e):r.configDefault});return {version:this.version(),...t}}};function Ra(){return {type:"object",...transformObject(hr,e=>e.prototype.getSchema())}}function Ca(){let n=transformObject(hr,e=>e.prototype.getSchema().template({},{withOptional:true,withExtendedOptional:true}));return structuredClone(n)}var Ms="<!-- BKND_CONTEXT -->",Bn=class extends ae{constructor(t,r={}){super();this.app=t;this._options=r;}get ctx(){return this.app.modules.ctx()}get options(){return {...this._options,basepath:this._options.basepath??"/",adminBasepath:this._options.adminBasepath??"",assetsPath:this._options.assetsPath??Qe.server.assets_path,logo_return_path:this._options.logoReturnPath??"/"}}get basepath(){return this.withAdminBasePath()}withBasePath(t=""){return (this.options.basepath+t).replace(/(?<!:)\/+/g,"/")}withAdminBasePath(t=""){return this.withBasePath(this.options.adminBasepath+t)}getController(){let{auth:t,permission:r}=this.middlewares,i=this.create().use(t({})),s=this.app.module.auth,o=this.app.modules.configs(),c=o.auth.enabled,a={success:o.auth.cookie.pathSuccess??this.withAdminBasePath("/"),loggedOut:o.auth.cookie.pathLoggedOut??this.withAdminBasePath("/"),login:this.withAdminBasePath("/auth/login"),register:this.withAdminBasePath("/auth/register"),logout:"/api/auth/logout"},l=["/","/data/*","/auth/*","/media/*","/flows/*","/settings/*"];A()&&l.push("/test/*");for(let u of l)i.get(u,r(dn,{onDenied:async p=>{if(!u.startsWith("/auth"))return _t(p,"You are not authorized to access the Admin UI","error"),$console.log("redirecting",a.login),p.redirect(a.login)}}),r(Mt,{onDenied:async p=>{_t(p,"You not allowed to read the schema","warning");}}),async p=>{let d={user:p.get("auth")?.user,logout_route:a.logout,admin_basepath:this.options.adminBasepath,theme:this.options.theme,logo_return_path:this.options.logoReturnPath},m=await this.getHtml(d);return m?(await s.authenticator?.requestCookieRefresh(p),p.html(m)):(console.warn("Couldn't generate HTML for admin UI"),p.notFound())});if(c){let u=[r([dn,Mt],{onGranted:async p=>{if(p.get("auth")?.user)return $console.log("redirecting to success"),p.redirect(a.success)}}),async p=>p.html(p.get("html"))];i.get(a.login,...u),i.get(a.register,...u),i.get(a.logout,async p=>(await s.authenticator?.logout(p),p.redirect(a.loggedOut)));}return i}async getHtml(t){let r=`window.__BKND__ = JSON.parse('${JSON.stringify(t)}');`;if(this.options.html)return this.options.html.includes(Ms)?this.options.html.replace(Ms,"<script>"+r+"<\/script>"):($console.warn(`Custom HTML needs to include '${Ms}' to inject BKND context`),this.options.html);let i=!A()&&!this.options.forceDev,s=typeof this.options.forceDev=="object"&&"mainPath"in this.options.forceDev?this.options.forceDev.mainPath:"/src/ui/main.tsx",o={js:"main.js",css:"styles.css"};if(i){let a;this.options.assetsPath.startsWith("http")?a=await fetch(this.options.assetsPath+".vite/manifest.json",{headers:{Accept:"application/json"}}).then(l=>l.json()):a=await import('bknd/dist/manifest.json').then(l=>l.default);try{o.js=a["src/ui/main.tsx"].file,o.css=a["src/ui/main.tsx"].css[0];}catch(l){$console.warn("Couldn't find assets in manifest",l);}}let c=i?this.options.assetsPath+"favicon.ico":"/favicon.ico";return jsxs(Fragment,{children:[html`<!DOCTYPE html>`,jsxs("html",{lang:"en",children:[jsxs("head",{children:[jsx("meta",{charset:"UTF-8"}),jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),jsx("link",{rel:"icon",href:c,type:"image/x-icon"}),jsx("title",{children:"BKND"}),this.options.debugRerenders&&jsx("script",{crossOrigin:"anonymous",src:"//unpkg.com/react-scan/dist/auto.global.js"}),i?jsxs(Fragment,{children:[jsx("script",{type:"module",src:this.options.assetsPath+o?.js}),jsx("link",{rel:"stylesheet",href:this.options.assetsPath+o?.css})]}):jsxs(Fragment,{children:[jsx("script",{type:"module",dangerouslySetInnerHTML:{__html:`import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true`}}),jsx("script",{type:"module",src:"/@vite/client"})]}),jsx("style",{dangerouslySetInnerHTML:{__html:"body { margin: 0; padding: 0; }"}})]}),jsxs("body",{children:[jsxs("div",{id:"root",children:[jsx(Style,{}),jsx("div",{id:"loading",className:Nu,children:jsx("span",{className:Uu,children:"Initializing..."})})]}),jsx("script",{dangerouslySetInnerHTML:{__html:r}}),!i&&jsx("script",{type:"module",src:s})]})]})]})}},Nu=css`
margin: 0;
padding: 0;
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: rgb(9,9,11);
background-color: rgb(250,250,250);
@media (prefers-color-scheme: dark) {
color: rgb(250,250,250);
background-color: rgb(30,31,34);
}
`,Uu=css`
opacity: 0.3;
font-size: 14px;
font-family: monospace;
`;var $n=class extends ae{constructor(t){super();this.app=t;}get ctx(){return this.app.modules.ctx()}registerConfigController(t){let{permission:r}=this.middlewares,i=this.create();i.use(r(mn)),i.get("/raw",describeRoute({summary:"Get the raw config",tags:["system"]}),r([ir]),async o=>o.json(await this.app.modules.fetch())),i.get("/:module?",describeRoute({summary:"Get the config for a module",tags:["system"]}),jsc("param",s.object({module:s.string({enum:Ta}).optional()})),jsc("query",s.object({secrets:s.boolean().optional()})),async o=>{let{secrets:c}=o.req.valid("query"),{module:a}=o.req.valid("param");c&&this.ctx.guard.throwUnlessGranted(ir,o);let l=this.app.toJSON(c);return o.json(a?{version:this.app.version(),module:a,config:l[a]}:l)});async function s$1(o,c){try{return o.json(await c(),{status:202})}catch(a){return $console.error("config update error",a),a instanceof InvalidSchemaError?o.json({success:false,type:"type-invalid",errors:a.errors},{status:400}):a instanceof Error?o.json({success:false,type:"error",error:a.message},{status:500}):o.json({success:false,type:"unknown"},{status:500})}}i.post("/set/:module",r(Xe),jsc("query",s.object({force:s.boolean().optional()}),{skipOpenAPI:true}),async o=>{let c=o.req.param("module"),{force:a}=o.req.valid("query"),l=await o.req.json();return await s$1(o,async()=>{if(a===true){let u={...this.app.module[c].config,...l};await this.app.mutateConfig(c).set(u);}else await this.app.mutateConfig(c).patch("",l);return {success:true,module:c,config:this.app.module[c].config}})}),i.post("/add/:module/:path",r(Xe),async o=>{let c=o.req.param("module"),a=await o.req.json(),l=o.req.param("path");return this.app.modules.get(c).schema().has(l)?o.json({success:false,path:l,error:"Path already exists"},{status:400}):await s$1(o,async()=>(await this.app.mutateConfig(c).patch(l,a),{success:true,module:c,config:this.app.module[c].config}))}),i.patch("/patch/:module/:path",r(Xe),async o=>{let c=o.req.param("module"),a=await o.req.json(),l=o.req.param("path");return await s$1(o,async()=>(await this.app.mutateConfig(c).patch(l,a),{success:true,module:c,config:this.app.module[c].config}))}),i.put("/overwrite/:module/:path",r(Xe),async o=>{let c=o.req.param("module"),a=await o.req.json(),l=o.req.param("path");return await s$1(o,async()=>(await this.app.mutateConfig(c).overwrite(l,a),{success:true,module:c,config:this.app.module[c].config}))}),i.delete("/remove/:module/:path",r(Xe),async o=>{let c=o.req.param("module"),a=o.req.param("path");return await s$1(o,async()=>(await this.app.mutateConfig(c).remove(a),{success:true,module:c,config:this.app.module[c].config}))}),t.route("/config",i);}getController(){let{permission:t,auth:r}=this.middlewares,i=this.create().use(r());return this.registerConfigController(i),i.get("/schema/:module?",describeRoute({summary:"Get the schema for a module",tags:["system"]}),t(Mt),jsc("query",s.object({config:s.boolean(),secrets:s.boolean(),fresh:s.boolean()}).partial()),async s=>{let o=s.req.param("module"),{config:c,secrets:a,fresh:l}=s.req.valid("query");c&&this.ctx.guard.throwUnlessGranted(mn,s),a&&this.ctx.guard.throwUnlessGranted(ir,s);let{version:u,...p}=this.app.getSchema();return l&&await this.app.build({fetch:true}),o?s.json({module:o,version:u,schema:p[o],config:c?this.app.module[o].toJSON(a):void 0}):s.json({module:o,version:u,schema:p,config:c?this.app.toJSON(a):void 0,permissions:this.app.modules.ctx().guard.getPermissionNames()})}),i.post("/build",describeRoute({summary:"Build the app",tags:["system"]}),jsc("query",s.object({sync:s.boolean().optional(),fetch:s.boolean().optional()})),async s=>{let o=s.req.valid("query");return this.ctx.guard.throwUnlessGranted(gs,s),await this.app.build(o),s.json({success:true,options:o})}),i.get("/ping",describeRoute({summary:"Ping the server",tags:["system"]}),s=>s.json({pong:true})),i.get("/info",describeRoute({summary:"Get the server info",tags:["system"]}),s=>s.json({version:s.get("app")?.version(),runtime:getRuntimeKey(),connection:{name:this.app.em.connection.name,supports:this.app.em.connection.supported},timezone:{name:getTimezone(),offset:getTimezoneOffset(),local:datetimeStringLocal(),utc:datetimeStringUTC()},origin:new URL(s.req.raw.url).origin,plugins:Array.from(this.app.plugins.keys()),walk:{auth:[...s.get("app").getSchema().auth.walk({data:s.get("app").toJSON(true).auth})].filter(o=>o.schema instanceof SecretSchema).map(o=>({...o,schema:o.schema.constructor.name}))}})),i.get("/openapi.json",go(this.ctx.server,{info:{title:"bknd API",version:Zs()}})),i.get("/swagger",swaggerUI({url:"/api/system/openapi.json"})),i}};var be=class{constructor(e={},t){this._options=e;this.fetcher=t??fetch;}fetcher;getDefaultOptions(){return {}}get options(){return {host:"http://localhost",token:void 0,...this.getDefaultOptions(),...this._options}}key(){return this.options.basepath??""}getUrl(e){let t=this.options.basepath??"";return this.options.host+(t+"/"+e).replace(/\/{2,}/g,"/").replace(/\/$/,"")}request(e,t,r){let i=r?.method??"GET",s=Array.isArray(e)?e.join("/"):e,o=this.getUrl(s);t instanceof URLSearchParams?o+="?"+t.toString():typeof t=="object"&&Object.keys(t).length>0&&(o+="?"+encodeSearch(t));let c=new Headers(this.options.headers??{});for(let[u,p]of Object.entries(r?.headers??{}))c.set(u,p);c.has("Accept")||c.set("Accept","application/json"),this.options.token&&this.options.token_transport==="header"&&c.set("Authorization",`Bearer ${this.options.token}`);let a=r?.body;if(r&&"body"in r&&["POST","PATCH","PUT"].includes(i)){let u=c.get("Content-Type")??void 0;(!u||u.startsWith("application/json")||isPlainObject(a))&&(a=JSON.stringify(r.body),c.set("Content-Type","application/json"));}let l=new Request(o,{...r,method:i,body:a,headers:c});return new js(l,{fetcher:this.fetcher,verbose:this.options.verbose})}get(e,t,r){return this.request(e,t,{...r,method:"GET"})}post(e,t,r){return this.request(e,void 0,{...r,body:t,method:"POST"})}patch(e,t,r){return this.request(e,void 0,{...r,body:t,method:"PATCH"})}put(e,t,r){return this.request(e,void 0,{...r,body:t,method:"PUT"})}delete(e,t,r){return this.request(e,void 0,{...r,body:t,method:"DELETE"})}};function Zu(n,e,t){let r=typeof t<"u"?t:e,i=["raw","body","ok","status","res","data","toJSON"];return typeof r!="object"&&(r={}),new Proxy(r,{get(s,o,c){return o==="raw"||o==="res"?n:o==="body"?e:o==="data"?t:o==="ok"?n.ok:o==="status"?n.status:o==="toJSON"?()=>s:Reflect.get(s,o,c)},has(s,o){return i.includes(o)?true:Reflect.has(s,o)},ownKeys(s){return Array.from(new Set([...Reflect.ownKeys(s),...i]))},getOwnPropertyDescriptor(s,o){return i.includes(o)?{configurable:true,enumerable:true,value:Reflect.get({raw:n,body:e,ok:n.ok,status:n.status},o)}:Reflect.getOwnPropertyDescriptor(s,o)}})}var js=class n{constructor(e,t,r){this.request=e;this.options=t;this.refineData=r;}[Symbol.toStringTag];get verbose(){return this.options?.verbose??false}refine(e){return new n(this.request,this.options,e)}async execute(){A()&&await new Promise(o=>setTimeout(o,200));let e=this.options?.fetcher??fetch;this.verbose&&$console.debug("[FetchPromise] Request",{method:this.request.method,url:this.request.url});let t=await e(this.request);this.verbose&&$console.debug("[FetchPromise] Response",{res:t,ok:t.ok,status:t.status});let r,i,s=t.headers.get("Content-Type")??"";if(s.startsWith("application/json")?(r=await t.json(),typeof r=="object"&&(i="data"in r?r.data:r)):s.startsWith("text")?r=await t.text():r=t.body,this.refineData)try{i=this.refineData(i);}catch(o){console.warn("[FetchPromise] Error in refineData",o),i=void 0;}return Zu(t,r,i)}then(e,t){return this.execute().then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}path(){return new URL(this.request.url).pathname}key(e){let t=new URL(this.request.url);return e?.search!==false?this.path()+t.search:this.path()}keyArray(e){let t=new URL(this.request.url),r=this.path().split("/");return (e?.search!==false?[...r,t.searchParams.toString()]:r).filter(Boolean)}toString(){return this.key({search:true})}toJSON(){return {url:this.request.url,method:this.request.method}}};var Nn=class extends be{getDefaultOptions(){return {basepath:"/api/auth",credentials:"include"}}async login(e,t){let r=await this.post([e,"login"],t,{credentials:this.options.credentials});return r.ok&&r.body.token&&await this.options.onTokenUpdate?.(r.body.token),r}async register(e,t){let r=await this.post([e,"register"],t,{credentials:this.options.credentials});return r.ok&&r.body.token&&await this.options.onTokenUpdate?.(r.body.token),r}async actionSchema(e,t){return this.get([e,"actions",t,"schema.json"])}async action(e,t,r){return this.post([e,"actions",t],r)}async loginWithPassword(e){return this.login("password",e)}async registerWithPassword(e){return this.register("password",e)}me(){return this.get(["me"])}strategies(){return this.get(["strategies"])}async logout(){await this.options.onTokenUpdate?.(void 0);}};var Un=class extends be{getDefaultOptions(){return {basepath:"/api/data",queryLengthLimit:1e3,defaultQuery:{limit:10}}}requireObjectSet(e,t){if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error(t??"object is required")}readOne(e,t,r={}){return this.get(["entity",e,t],r)}readOneBy(e,t={}){return this.readMany(e,{...t,limit:1,offset:0}).refine(r=>r[0])}readMany(e,t={}){let r=t??this.options.defaultQuery,i=this.get(["entity",e],r);return i.request.url.length<=this.options.queryLengthLimit?i:this.post(["entity",e,"query"],r)}readManyByReference(e,t,r,i={}){return this.get(["entity",e,t,r],i??this.options.defaultQuery)}createOne(e,t){return this.post(["entity",e],t)}createMany(e,t){if(!t||!Array.isArray(t)||t.length===0)throw new Error("input is required");return this.post(["entity",e],t)}updateOne(e,t,r){if(!t)throw new Error("ID is required");return this.patch(["entity",e,t],r)}updateMany(e,t,r){return this.requireObjectSet(t),this.patch(["entity",e],{update:r,where:t})}deleteOne(e,t){if(!t)throw new Error("ID is required");return this.delete(["entity",e,t])}deleteMany(e,t){return this.requireObjectSet(t),this.delete(["entity",e],t)}count(e,t={}){return this.post(["entity",e,"fn","count"],t)}exists(e,t={}){return this.post(["entity",e,"fn","exists"],t)}};var Ln=class extends be{getDefaultOptions(){return {basepath:"/api/media",upload_fetcher:fetch,init:{}}}listFiles(){return this.get(["files"])}getFile(e){return this.get(["file",e],void 0,{headers:{Accept:"*/*"}})}async getFileStream(e){let{res:t}=await this.getFile(e);if(!t.ok||!t.body)throw new Error("Failed to fetch file");return t.body}async download(e){let{res:t}=await this.getFile(e);if(!t.ok||!t.body)throw new Error("Failed to fetch file");return await t.blob()}getFileUploadUrl(e){return e?this.getUrl(`/upload/${e.path}`):this.getUrl("/upload")}getEntityUploadUrl(e,t,r){return this.getUrl(`/entity/${e}/${t}/${r}`)}getUploadHeaders(){return this.options.token_transport==="header"&&this.options.token?new Headers({Authorization:`Bearer ${this.options.token}`}):new Headers}uploadFile(e,t){let r={"Content-Type":"application/octet-stream",...t?._init?.headers||{}},i=t?.filename||"";try{typeof e.type<"u"&&(r["Content-Type"]=e.type),t?.filename||(i=e.name);}catch{}i&&i.length>0&&i.includes("/")&&(i=i.split("/").pop()||"");let s={...this.options.init,...t?._init||{},headers:r};if(t?.path)return this.post(t.path,e,s);if(!i||i.length===0)throw new Error("Invalid filename");return this.post(t?.path??["upload",i],e,s)}async upload(e,t={}){if(e instanceof Request||typeof e=="string"){let i=await(t.fetcher??this.options.upload_fetcher)(e);if(!i.ok||!i.body)throw new Error("Failed to fetch file");return this.uploadFile(i.body,t)}else if(e instanceof Response){if(!e.body)throw new Error("Invalid response");return this.uploadFile(e.body,{...t??{},_init:{...t._init??{},headers:{...t._init?.headers??{},"Content-Type":e.headers.get("Content-Type")||"application/octet-stream"}}})}return this.uploadFile(e,t)}async uploadToEntity(e,t,r,i,s){return this.upload(i,{...s,path:["entity",e,t,r]})}deleteFile(e){return this.delete(["file",e])}};var Qn=class extends be{getDefaultOptions(){return {basepath:"/api/system"}}readConfig(){return this.get("config")}readSchema(e){return this.get("schema",{config:e?.config?1:0,secrets:e?.secrets?1:0,fresh:e?.fresh?1:0})}setConfig(e,t,r){return this.post(["config","set",e].join("/")+`?force=${r?1:0}`,t)}addConfig(e,t,r){return this.post(["config","add",e,t],r)}patchConfig(e,t,r){return this.patch(["config","patch",e,t],r)}overwriteConfig(e,t,r){return this.put(["config","overwrite",e,t],r)}removeConfig(e,t){return this.delete(["config","remove",e,t])}};var br=class{constructor(e={}){this.options=e;this.verified=e.verified===true,"request"in e&&e.request?(this.options.host=e.host??new URL(e.request.url).origin,this.options.headers=e.headers??e.request.headers,this.extractToken()):"token"in e&&e.token?(this.token_transport="header",this.updateToken(e.token,{trigger:false})):"user"in e&&e.user?(this.token_transport="none",this.user=e.user,this.verified=e.verified!==false):this.extractToken(),this.buildApis();}token;user;verified=false;token_transport="header";system;data;auth;media;get fetcher(){return this.options.fetcher??fetch}get baseUrl(){return this.options.host??"http://localhost"}get tokenKey(){return this.options.key??"auth"}extractToken(){if(this.verified=false,this.options.headers){let e=tp(this.options.headers.get("cookie"),"auth");if(e){this.token_transport="cookie",this.updateToken(e);return}let t=this.options.headers.get("authorization")?.replace("Bearer ","");if(t){this.token_transport="header",this.updateToken(t);return}}else this.storage&&this.storage.getItem(this.tokenKey).then(e=>{this.token_transport="header",this.updateToken(e?String(e):void 0);});}get storage(){return this.options.storage?{getItem:async e=>await this.options.storage.getItem(e),setItem:async(e,t)=>await this.options.storage.setItem(e,t),removeItem:async e=>await this.options.storage.removeItem(e)}:null}updateToken(e,t){if(this.token=e,this.verified=false,e?this.user=ee(decode(e).payload,["iat","iss","exp"]):this.user=void 0,this.storage){let r=this.tokenKey;e?this.storage.setItem(r,e).then(()=>{this.options.onAuthStateChange?.(this.getAuthState());}):this.storage.removeItem(r).then(()=>{this.options.onAuthStateChange?.(this.getAuthState());});}else t?.trigger!==false&&this.options.onAuthStateChange?.(this.getAuthState());t?.rebuild&&this.buildApis();}markAuthVerified(e){return this.verified=e,this}isAuthVerified(){return this.verified}getAuthState(){return {token:this.token,user:this.user,verified:this.verified}}isAuthenticated(){let{token:e,user:t}=this.getAuthState();return !!e&&!!t}async getVerifiedAuthState(){return await this.verifyAuth(),this.getAuthState()}async verifyAuth(){if(!this.token){this.markAuthVerified(false);return}try{let{ok:e,data:t}=await this.auth.me(),r=t?.user;if(!e||!r)throw new Error;this.user=r,this.markAuthVerified(!0);}catch{this.markAuthVerified(false),this.updateToken(void 0);}}getUser(){return this.user||null}getParams(){return Object.freeze({host:this.baseUrl,token:this.token,headers:this.options.headers,token_transport:this.token_transport,verbose:this.options.verbose})}buildApis(){let e=this.getParams(),t=this.options.fetcher;this.system=new Qn(e,t),this.data=new Un({...e,...this.options.data},t),this.auth=new Nn({...e,credentials:this.options.storage?"omit":"include",...this.options.auth,onTokenUpdate:r=>{this.updateToken(r,{rebuild:true}),this.options.auth?.onTokenUpdate?.(r);}},t),this.media=new Ln({...e,...this.options.media},t);}};function tp(n,e){if(!n)return null;for(let t of n.split("; ")){let[r,i]=t.split("=");if(r===e&&i)return decodeURIComponent(i)}return null}var ct=class extends v{},Kn=class extends ct{static slug="app-config-updated"},Jn=class extends ct{static slug="app-built"},zn=class extends ct{static slug="app-first-boot"},Gn=class extends ct{static slug="app-request"},Wn=class extends ct{static slug="app-before-response"},Ds={AppConfigUpdatedEvent:Kn,AppBuiltEvent:Jn,AppFirstBoot:zn,AppRequest:Gn,AppBeforeResponse:Wn},Vn=class{constructor(e,t,r){this.connection=e;this.options=r;this.drivers=r?.drivers??{};for(let i of r?.plugins??[]){let s=i(this);if(this.plugins.has(s.name))throw new Error(`Plugin ${s.name} already registered`);this.plugins.set(s.name,s);}this.runPlugins("onBoot"),this.modules=new In(e,{...r?.manager??{},initial:t,onUpdated:this.onUpdated.bind(this),onFirstBoot:this.onFirstBoot.bind(this),onServerInit:this.onServerInit.bind(this),onModulesBuilt:this.onModulesBuilt.bind(this)}),this.modules.ctx().emgr.registerEvents(Ds);}static Events=Ds;modules;adminController;_id=crypto.randomUUID();plugins=new Map;drivers={};trigger_first_boot=false;_building=false;get emgr(){return this.modules.ctx().emgr}async runPlugins(e,...t){let r=[];for(let[i,s]of this.plugins)try{if(e in s&&s[e]){let o=s[e];if(o&&typeof o=="function"){f.debug(`[Plugin:${i}] ${e}`);let c=await o(...t);r.push({name:i,result:c});}}}catch(o){f.warn(`[Plugin:${i}] error running "${e}"`,String(o));}return r}async build(e){if(this._building){for(;this._building;)await new Promise(i=>setTimeout(i,10));if(!e?.forceBuild)return}await this.runPlugins("beforeBuild"),this._building=true,e?.sync&&(this.modules.ctx().flags.sync_required=true),await this.modules.build({fetch:e?.fetch});let{guard:t,server:r}=this.modules.ctx();t.registerPermissions(Object.values(jt)),r.route("/api/system",new $n(this).getController()),f.log("App built"),await this.emgr.emit(new Jn({app:this})),await this.runPlugins("onBuilt"),this.trigger_first_boot&&(this.trigger_first_boot=false,await this.emgr.emit(new zn({app:this})),await this.options?.seed?.({...this.modules.ctx(),app:this})),this._building=false;}mutateConfig(e){return this.modules.mutateConfigSafe(e)}get server(){return this.modules.server}get em(){return this.modules.ctx().em}get fetch(){return this.server.fetch}get module(){return new Proxy({},{get:(e,t)=>this.modules.get(t)})}getSchema(){return this.modules.getSchema()}version(){return this.modules.version()}isBuilt(){return this.modules.isBuilt()}registerAdminController(e){return this.adminController=new Bn(this,e),this.modules.server.route(this.adminController.basepath,this.adminController.getController()),this}toJSON(e){return this.modules.toJSON(e)}static create(e){return Aa(e)}async createUser(e){return this.module.auth.createUser(e)}getApi(e){let t=this.server.request;return e&&e instanceof Request?new br({request:e,headers:e.headers,fetcher:t}):new br({host:"http://localhost",...e??{},fetcher:t})}async onUpdated(e,t){if(!this.emgr.enabled){f.warn("App config updated, but event manager is disabled, skip.");return}f.log("App config updated",e),await this.build({sync:true}),await this.emgr.emit(new Kn({app:this,module:e,config:t}));}async onFirstBoot(){f.log("App first boot"),this.trigger_first_boot=true,await this.runPlugins("onFirstBoot");}async onServerInit(e){e.use(async(t,r)=>{t.set("app",this),await this.emgr.emit(new Gn({app:this,request:t.req.raw})),await r();try{t.res.headers.set("X-bknd-id",this._id);}catch{}switch(await this.emgr.emit(new Wn({app:this,request:t.req.raw,response:t.res})),this.options?.asyncEventsMode??"async"){case "sync":await this.emgr.executeAsyncs();break;case "async":this.emgr.executeAsyncs();break}}),this.options?.manager?.onServerInit&&this.options.manager.onServerInit(e),await this.runPlugins("onServerInit",e);}async onModulesBuilt(e){let t=await this.runPlugins("schema");if(t.length>0)for(let{name:r,result:i}of t)i&&(f.log(`[Plugin:${r}] schema`),e.helper.ensureSchema(i));}};function Aa(n={}){if(!n.connection||!te.isConnection(n.connection))throw new Error("Invalid connection");return new Vn(n.connection,n.initialConfig,n.options)}function ka(n){return new TextEncoder().encode(n).length}var Is=class{cache;maxSize;defaultTTL;currentSize;constructor(e={}){this.maxSize=e.maxSize??1024*1024*10,this.defaultTTL=e.defaultTTL??60*60,this.cache=new Map,this.currentSize=0;}now(){return Date.now()}isExpired(e){return e.expiresAt!==null&&e.expiresAt<=this.now()}setEntry(e,t){let r=this.cache.get(e),i=r?r.size:0,s=this.currentSize-i+t.size;if(t.size>this.maxSize)throw new Error(`InMemoryCacheDriver: entry too large (entry: ${t.size}, max: ${this.maxSize})`);for(;s>this.maxSize&&this.cache.size>0;){let o=this.cache.keys().next().value;if(typeof o=="string"){let c=this.cache.get(o);c&&(this.currentSize-=c.size),this.cache.delete(o),s=this.currentSize-i+t.size;}else break}if(s>this.maxSize)throw new Error(`InMemoryCacheDriver: maxSize exceeded after eviction (attempted: ${s}, max: ${this.maxSize})`);r&&(this.currentSize-=i),this.cache.delete(e),this.cache.set(e,t),this.currentSize+=t.size;}async get(e){let t=this.cache.get(e);if(t){if(this.isExpired(t)){this.cache.delete(e),this.currentSize-=t.size;return}return this.cache.delete(e),this.cache.set(e,t),t.value}}async set(e,t,r){let i=r===void 0?this.defaultTTL>0?this.now()+this.defaultTTL*1e3:null:r>0?this.now()+r*1e3:null,s=ka(e)+ka(t);this.setEntry(e,{value:t,expiresAt:i,size:s});}async del(e){let t=this.cache.get(e);t&&(this.currentSize-=t.size,this.cache.delete(e));}},rp=n=>new Is(n);var np=n=>{let e=n.host??"https://api.resend.com/emails",t=n.from??"Acme <onboarding@resend.dev>";return {send:async(r,i,s,o)=>{let c={from:t,to:r,subject:i};typeof s=="string"?c.html=s:(c.html=s.html,c.text=s.text);let a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.apiKey}`},body:JSON.stringify({...c,...o})});if(!a.ok)throw new Error(await a.text());return await a.json()}}};var sp=n=>{let e=`https://email.${n.region}.amazonaws.com/v2/email/outbound-emails`,t=n.from,r=new AwsClient({accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,service:"ses",region:n.region});return {send:async(i,s,o,c)=>{let a={FromEmailAddress:t,Destination:{ToAddresses:[i]},Content:{Simple:{Subject:{Data:s,Charset:"UTF-8"},Body:{}}}};typeof o=="string"?a.Content.Simple.Body.Html={Data:o,Charset:"UTF-8"}:(o.html&&(a.Content.Simple.Body.Html={Data:o.html,Charset:"UTF-8"}),o.text&&(a.Content.Simple.Body.Text={Data:o.text,Charset:"UTF-8"})),c?.cc&&c.cc.length>0&&(a.Destination.CcAddresses=c.cc),c?.bcc&&c.bcc.length>0&&(a.Destination.BccAddresses=c.bcc),c?.replyTo&&c.replyTo.length>0&&(a.ReplyToAddresses=c.replyTo);let l=await r.fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a)}),u=await l.text();if(!l.ok){let d=u;try{let m=JSON.parse(u);d=m.message||m.Message||u;}catch{}throw new Error(`SES SendEmail failed: ${d}`)}let p="";try{p=JSON.parse(u).MessageId;}catch{}return {MessageId:p,status:l.status,body:u}}}};var op=n=>{let e=n.host??"https://api.mailchannels.net/tx/v1/send",t=n.from??{email:"onboarding@mailchannels.net",name:"Mailchannels"};return {send:async(r,i,s,o)=>{let c=di({from:t,subject:i,content:typeof s=="string"?[{type:"text/html",value:s}]:[{type:"text/plain",value:s.text},{type:"text/html",value:s.html}],personalizations:[{to:[{email:r}]}]},o??{}),a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","X-Api-Key":n.apiKey},body:JSON.stringify(c)}),l=await a.json();if(l?.results.length===0||l.results?.[0]?.status!=="sent")throw new Error(l.results?.[0]?.reason??"Unknown error");return await a.json()}}};async function Fa(n){let e=await(n.conf.fetch??globalThis.fetch)(`${n.conf.url}/v3/pipeline`,{method:"POST",headers:n.conf.authToken?{Authorization:"Bearer "+n.conf.authToken}:void 0,body:JSON.stringify(n.req_json)});return e.ok?{isOk:true,val:await e.json()}:{isOk:false,err:{kind:"LIBSQL_SERVER_ERROR",server_message:await(async()=>{try{return await e.text()}catch{return null}})(),http_status_code:e.status}}}async function Pa(n,e){let t=await Fa({conf:n,req_json:{baton:null,requests:[{type:"execute",stmt:e},{type:"close"}]}});if(t.isOk){let r=t.val.results[0];return r.type=="ok"?{isOk:true,val:r.response.result}:{isOk:false,err:{kind:"LIBSQL_RESPONSE_ERROR",data:r.error}}}else return t}async function Hn(n,e){let t=await Fa({conf:n,req_json:{baton:null,requests:[{type:"batch",batch:{steps:e}},{type:"close"}]}});if(t.isOk){let r=t.val.results[0];return r.type=="ok"?{isOk:true,val:r.response.result}:{isOk:false,err:{kind:"LIBSQL_RESPONSE_ERROR",data:r.error}}}else return t}async function Ma(n){return (await(n.fetch??globalThis.fetch)(`${n.url}/v3`,{method:"GET"})).ok?{isOk:true,val:null}:{isOk:false,err:null}}var ap=Object.defineProperty,cp=(n,e,t)=>e in n?ap(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t,Nt=(n,e,t)=>(cp(n,typeof e!="symbol"?e+"":e,t),t),Ee=class extends Error{constructor(n,e,t,r){e!==void 0&&(n=`${e}: ${n}`),super(n,{cause:r}),Nt(this,"code"),Nt(this,"rawCode"),this.code=e,this.rawCode=t,this.name="LibsqlError";}},lp=class extends Ee{constructor(n){super(n,"HRANA_PROTO_ERROR"),this.name="ProtoError";}},Ba=class extends Ee{constructor(n,e){super(n,e??"UNKNOWN"),this.name="ResponseError",this.stack=void 0;}},up=class extends Ee{constructor(n,e){super(`HTTP code ${n}: ${e??"No error message from server."}`,"SERVER_ERROR"),Nt(this,"http_status_code"),this.http_status_code=n,this.name="HttpServerError";}},qs=class extends Ee{constructor(n){super(n,"UNKNOWN"),this.name="MisuseError";}},Zn=typeof Buffer=="function",pp=typeof btoa=="function",dp=typeof atob=="function",mp=n=>atob(n),fp=n=>btoa(n),yp=n=>Buffer.from(n).toString("base64"),hp=n=>Buffer.from(n,"binary").toString("base64"),gp=n=>Buffer.from(n,"base64"),bp=n=>Buffer.from(n,"base64").toString("binary"),wp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",wr=Array.prototype.slice.call(wp),Yn=(n=>{let e={};return n.forEach((t,r)=>e[t]=r),e})(wr),xp=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Ep=n=>{let e,t,r,i,s="",o=n.length%3;for(let c=0;c<n.length;){if((t=n.charCodeAt(c++))>255||(r=n.charCodeAt(c++))>255||(i=n.charCodeAt(c++))>255)throw new Ee("Invalid character found while polyfilling btoa","BTOA_POLYFILL_INVALID_CHAR");e=t<<16|r<<8|i,s+=wr[e>>18&63]+wr[e>>12&63]+wr[e>>6&63]+wr[e&63];}return o?s.slice(0,o-3)+"===".substring(o):s},vp=pp?n=>fp(n):Zn?n=>hp(n):Ep,Xn=String.fromCharCode.bind(String),ja=Zn?n=>yp(n):n=>{let e=[];for(let t=0,r=n.length;t<r;t+=4096){let i=[];n.subarray(t,t+4096).forEach(s=>i.push(s.valueOf())),e.push(Xn.apply(null,i));}return vp(e.join(""))},$a=n=>n.replace(/[^A-Za-z0-9\+\/]/g,""),Sp=n=>{if(n=n.replace(/\s+/g,""),!xp.test(n))throw new Ee("Malformed base64 while polyfilling atob","MALFORMED_BASE64_FOR_ATOB");n+="==".slice(2-(n.length&3));let e,t="",r,i;for(let s=0;s<n.length;)e=Yn[n.charAt(s++)]<<18|Yn[n.charAt(s++)]<<12|(r=Yn[n.charAt(s++)])<<6|(i=Yn[n.charAt(s++)]),t+=r===64?Xn(e>>16&255):i===64?Xn(e>>16&255,e>>8&255):Xn(e>>16&255,e>>8&255,e&255);return t},Tp=dp?n=>mp($a(n)):Zn?n=>bp(n):Sp,Da=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):n=>new Uint8Array(Array.prototype.slice.call(n,0)),Rp=Zn?n=>Da(gp(n)):n=>Da(Tp(n).split("").map(e=>e.charCodeAt(0))),Cp=n=>$a(n.replace(/[-_]/g,e=>e=="-"?"+":"/")),Op=n=>Rp(Cp(n));function Ia(n){if(n===null)return {type:"null"};if(typeof n=="string")return {type:"text",value:n};if(typeof n=="number"){if(!Number.isFinite(n))throw new RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return {type:"float",value:n}}if(typeof n=="bigint"){if(n<-9223372036854775808n||n>9223372036854775807n)throw new RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return {type:"integer",value:""+n}}if(typeof n=="boolean")return {type:"integer",value:""+(n?1n:0n)};if(n instanceof ArrayBuffer)return {type:"blob",base64:ja(new Uint8Array(n))};if(n instanceof Uint8Array)return {type:"blob",base64:ja(n)};if(n instanceof Date)return {type:"float",value:+n.valueOf()};throw new qs("Invalid type of input. Cannot build request to server.")}function qa(n){if(n===void 0)return {};if(Object.prototype.toString.call(n)==="[object Array]")return {args:n.map(e=>Ia(e))};{let e=[],t=n;for(let r in t)e.push({name:r,value:Ia(t[r])});return {named_args:e}}}function Bs(n,e,t){if(typeof n=="string"){let r=qa(e);return {sql:n,args:r.args,named_args:r.named_args,want_rows:t}}else {let r=qa(n.args);return {sql:n.sql,args:r.args,named_args:r.named_args,want_rows:n.want_rows}}}var xr={ok:n=>({type:"ok",step:n}),error:n=>({type:"error",step:n}),not:n=>({type:"not",cond:n}),and:n=>({type:"and",conds:n}),or:n=>({type:"or",conds:n}),is_autocommit:()=>({type:"is_autocommit"})};function _p(n,e){return n.map((t,r)=>({stmt:Bs(t),condition:e[r]??void 0}))}function Ap(n){if(n==="write")return {stmt:{sql:"BEGIN IMMEDIATE"}};if(n==="read")return {stmt:{sql:"BEGIN TRANSACTION READONLY"}};if(n==="deferred")return {stmt:{sql:"BEGIN DEFERRED"}};throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}function kp(n){return [{stmt:{sql:"COMMIT"},condition:{type:"ok",step:n}},{stmt:{sql:"ROLLBACK"},condition:{type:"not",cond:{type:"ok",step:n+1}}}]}function Fp(n,e){let t=n.map((r,i)=>({stmt:Bs(r),condition:xr.and([xr.ok(i),xr.not(xr.is_autocommit())])}));return [Ap(e)].concat(t).concat(kp(t.length))}function Pp(n,e="number"){switch(n.type){case "null":return null;case "integer":switch(e){case "number":{let t=Number(n.value);if(!Number.isSafeInteger(t))throw new RangeError("Received integer which is too large to be safely represented as a JavaScript number");return t}case "bigint":return BigInt(n.value);case "string":return n.value;default:throw new qs('Invalid value for "intMode".')}case "float":return n.value;case "text":return n.value;case "blob":return Op(n.base64).slice().buffer;default:throw new lp("Invalid data type from server. Cannot parse.")}}function Na(n,e){let t=[];for(let i=0;i<n.rows.length;i++){let s={};Object.defineProperty(s,"length",{value:n.rows[i].length});for(let o=0;o<n.rows[i].length;o++){let c=Pp(n.rows[i][o],e);Object.defineProperty(s,o,{value:c});let a=n.cols[o].name;a!==void 0&&!Object.hasOwn(s,a)&&Object.defineProperty(s,a,{value:c,enumerable:true,configurable:true,writable:true});}t.push(s);}let r={rows:t,columns:n.cols.map(i=>i.name??""),columnTypes:n.cols.map(i=>i.decltype??""),rowsAffected:n.affected_row_count,lastInsertRowid:n.last_insert_rowid?BigInt(n.last_insert_rowid):void 0,rowsRead:n.rows_read,rowsWritten:n.rows_written,queryDurationMS:n.query_duration_ms};return {...r,toJSON:()=>r}}function Ua(n,e){return n.step_results.map((t,r)=>{var i,s;if(t)return Na(t,e);if(n.step_errors[r])throw new Ba((i=n.step_errors[r])==null?void 0:i.message,(s=n.step_errors[r])==null?void 0:s.code);return null})}function Mp(n,e){let t=Ua(n,e);return t.slice(1,t.length-2).filter(r=>r!==null)}function ei(n){return n.kind==="LIBSQL_SERVER_ERROR"?new up(n.http_status_code,n.server_message):new Ba(n.data.message,n.data.code)}async function jp(n,e,t,r){let i=await Pa(n,Bs(e,t,r));if(i.isOk)return Na(i.val,n.intMode);throw ei(i.err)}async function Dp(n,e,t){let r=await Hn(n,_p(e,t));if(r.isOk)return Ua(r.val,n.intMode);throw ei(r.err)}async function Ip(n){return (await Ma(n)).isOk}async function La(n,e,t="deferred"){let r=await Hn(n,Fp(e,t));if(r.isOk)return Mp(r.val,n.intMode);throw ei(r.err)}async function qp(n,e){return La(n,["PRAGMA foreign_keys=off"].concat(e).concat("PRAGMA foreign_keys=on"),"deferred")}async function Bp(n,e){let t=e.split(";").filter(i=>i.trim()!=="").map((i,s)=>({stmt:{sql:i},condition:xr.ok(s-1)}));t[0].condition=void 0;let r=await Hn(n,t);if(!r.isOk)throw ei(r.err)}var $p=typeof console.error=="function",Np=typeof URL=="function",Up=n=>console.error(n),Lp=n=>new URL(n);function Qp(n){try{if(!Ip(n))throw new Ee("Server incompatible. Please upgrade your libSQL server.","OUT_OF_DATE_SERVER")}catch{throw new Ee("The fetch function is non functional.","FETCH_FUCKED")}}function lt(n){$p&&Up(n);}function Kp(n){if((()=>{if(Np)try{let e=Lp(n);return !(e.protocol==="https:"||e.protocol==="http:")}catch(e){throw new Ee(e.message,"ERR_INVALID_URL",void 0,e)}else if(n.startsWith("https://")||n.startsWith("http://"))return false;return true})())throw new Ee('This is a HTTP client and only supports "https:" and "http:" URLs. For modern libsql DBs simply changing "libsql://" to "https://" should resolve this.',"URL_SCHEME_NOT_SUPPORTED")}function Jp(n){n.encryptionKey&<("'encryptionKey' config unsupported."),n.syncUrl&<("'syncUrl' config unsupported because 'url' is the remote url. (embedded replicas unsupported)"),n.syncInterval&<("'syncInterval' config unsupported because nothing to sync. (embedded replicas unsupported)"),n.tls&<("'tls' config unsupported. Change url scheme to 'http' for no tls and 'https' for tls."),n.concurrency&<("'concurrency' config unsupported. You may use a custom fetch to specify concurrency.");}function Qa(n){return new zp(n)}var zp=class{constructor(n){Nt(this,"conf"),Nt(this,"closed"),Nt(this,"protocol"),n.disableCriticalChecks||(Kp(n.url),Qp(n),Jp(n)),this.conf=n,this.closed=false,this.protocol="http";}async execute(n,e,t){return await jp(this.conf,n,e,t)}async batch(n,e){return await La(this.conf,n,e)}async batchWithoutTransaction(n,e){return await Dp(this.conf,n,e)}async migrate(n){return await qp(this.conf,n)}async transaction(n){throw new qs("'libsql-stateless' is stateless and does not support interactive transactions. Use this.batch() instead.")}async executeMultiple(n){return await Bp(this.conf,n)}async sync(){lt("'libsql-stateless' is remote only so nothing to sync.");}close(){lt("'libsql-stateless' is stateless therefore no connection to close.");}};var ti=class{transformQuery(e){return e.node}transformResult(e){return Promise.resolve({...e.result,rows:e.result.rows.map(t=>{let r={};for(let i in t)Number.isNaN(+i)&&(r[i]=t[i]);return r})})}};var Us=class{constructor(n){this.createDriver=n;}createDriver;createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(n){return new SqliteIntrospector(n)}},Yp=class{promise;resolve;async lock(){for(;this.promise;)await this.promise;this.promise=new Promise(n=>{this.resolve=n;});}unlock(){let n=this.resolve;this.promise=void 0,this.resolve=void 0,n?.();}};async function Ns(n,e,t,r,i){await t.executeQuery(i(RawNode.createWithChildren([RawNode.createWithSql(`${n} `),IdentifierNode.create(r)]),e()));}var Ls=class{mutex=new Yp;conn;savepoint;releaseSavepoint;rollbackToSavepoint;init;constructor(n){this.init=()=>import('kysely').then(({createQueryId:e})=>{e&&(this.savepoint=Ns.bind(null,"savepoint",e),this.releaseSavepoint=Ns.bind(null,"release",e),this.rollbackToSavepoint=Ns.bind(null,"rollback to",e));}).then(n);}async acquireConnection(){return await this.mutex.lock(),this.conn}async beginTransaction(n){await n.executeQuery(CompiledQuery.raw("begin"));}async commitTransaction(n){await n.executeQuery(CompiledQuery.raw("commit"));}async rollbackTransaction(n){await n.executeQuery(CompiledQuery.raw("rollback"));}async releaseConnection(){this.mutex.unlock();}};function Qs(n){return async(e,t,r)=>{let i=await n.all(t,r);return e||i.length?{rows:i}:{rows:[],...await n.run("select 1")}}}function Ks(n){return n==null?void 0:BigInt(n)}var Xp=class extends Ls{db;constructor(n,e){super(async()=>{this.db=await n(),this.conn=new Zp(this.db),await e?.(this.conn);});}async destroy(){await this.db?.close();}},Zp=class{constructor(n){this.db=n;}async*streamQuery({parameters:n,query:e,sql:t}){if(!this.db.iterator)throw new Error("streamQuery() is not supported.");let r=this.db.iterator(SelectQueryNode.is(e),t,n);for await(let i of r)yield {rows:[i]};}async executeQuery({parameters:n,query:e,sql:t}){return await this.db.query(SelectQueryNode.is(e),t,n)}},za=class extends Us{constructor(n,e){super(()=>new Xp(n,e));}};var Ut=class{constructor(e,t={}){this.db=e;this._excludeTables=t.excludeTables??[],this._plugins=t.plugins??[new ParseJSONResultsPlugin];}_excludeTables=[];_plugins;getExcludedTableNames(){return [...this._excludeTables,DEFAULT_MIGRATION_TABLE,DEFAULT_MIGRATION_LOCK_TABLE]}async executeWithPlugins(e){let t=await e.execute(this.db);return await new Ne(this._plugins??[]).transformResultRows(t.rows)}async getMetadata(e){return {tables:await this.getTables(e)}}async getIndices(e){return (await this.getSchemaSpec()).flatMap(r=>r.indices).filter(r=>!e||r.table===e)}async getTables(e={withInternalKyselyTables:false}){return (await this.getSchemaSpec()).map(r=>({name:r.name,isView:r.isView,columns:r.columns}))}};var Er=class extends Ut{async getSchemas(){return []}async getSchemaSpec(){let e=this.getExcludedTableNames().map(i=>`'${i}'`).join(", "),t=sql`
SELECT m.name, m.type, m.sql,
(SELECT json_group_array(
json_object(
'name', p.name,
'type', p.type,
'notnull', p."notnull",
'default', p.dflt_value,
'primary_key', p.pk
)) FROM pragma_table_info(m.name) p) AS columns,
(SELECT json_group_array(
json_object(
'name', i.name,
'origin', i.origin,
'partial', i.partial,
'sql', im.sql,
'columns', (SELECT json_group_array(
json_object(
'name', ii.name,
'seqno', ii.seqno
)) FROM pragma_index_info(i.name) ii)
)) FROM pragma_index_list(m.name) i
LEFT JOIN sqlite_master im ON im.name = i.name
AND im.type = 'index'
) AS indices
FROM sqlite_master m
WHERE m.type IN ('table', 'view')
and m.name not like 'sqlite_%'
and m.name not in (${sql.raw(e)})
`;return (await this.executeWithPlugins(t)).map(i=>({name:i.name,isView:i.type==="view",columns:i.columns?.map(s=>{let o=i.sql?.split(/[\(\),]/)?.find(c=>c.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,"");return {name:s.name,dataType:s.type,isNullable:!s.notnull,isAutoIncrementing:s.name===o,hasDefaultValue:s.dflt_value!=null,comment:void 0}})??[],indices:i.indices?.map(s=>({name:s.name,table:i.name,isUnique:s.sql?.match(/unique/i)!=null,columns:s.columns.map(o=>({name:o.name,order:o.seqno}))}))??[]}))}};var ut=class extends te{name="sqlite";constructor(e){let{excludeTables:t,dialect:r,dialectArgs:i=[],additionalPlugins:s}=e,o=[new ParseJSONResultsPlugin,...s??[]],c=new Kysely({dialect:Pr(r,Er,{excludeTables:t,plugins:o}).create(...i),plugins:o});super(c,{jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonBuildObject:jsonBuildObject,...e.customFn??{}},o);}getFieldSchema(e){this.validateFieldSpecType(e.type);let t=e.type;switch(e.type){case "json":t="text";break}return [e.name,t,r=>{if(e.primary)return e.type==="integer"?r.primaryKey().notNull().autoIncrement():r.primaryKey().notNull();if(e.references){let i=r.references(e.references);return e.onDelete&&(i=i.onDelete(e.onDelete)),e.onUpdate&&(i=i.onUpdate(e.onUpdate)),i}return r}]}toDriver(e,t){return t.type==="boolean"?e?1:0:typeof e>"u"?null:e}fromDriver(e,t){return t.type==="boolean"&&typeof e=="number"?e===1:e}};var Js=class extends ut{constructor(t,r,i){super({dialect:za,dialectArgs:[r,i?.onCreateConnection],additionalPlugins:i?.additionalPlugins,excludeTables:i?.excludeTables});this.db=t;this.executor=r;if(this.client=t,i?.name&&(this.name=i.name),i?.supports)for(let[s,o]of Object.entries(i.supports))o!==void 0&&(this.supported[s]=o);}name="generic-sqlite";#e;async getExecutor(){return this.#e||(this.#e=await this.executor()),this.#e}async executeQueries(...t){let r=await this.getExecutor();if(!r.batch)return super.executeQueries(...t);let s=this.getCompiled(...t).map(c=>({sql:c.sql,parameters:c.parameters})),o=await r.batch(s);return this.withTransformedRows(o)}};function zs(n,e,t,r){return new Js(e,()=>t(Wa),{name:n,...r})}var Wa={parseBigInt:Ks,buildQueryFn:Qs};function cd(n){if(n&&"url"in n){let{url:e,authToken:t}=n;return Qa({url:e,authToken:t})}return n}function ld(n){let e=cd(n);return zs("libsql",e,t=>{let r=s=>({insertId:s.lastInsertRowid,numAffectedRows:BigInt(s.rowsAffected),rows:s.rows}),i=async(s,o)=>{let c=await e.execute({sql:s,args:[...o||[]]});return r(c)};return {db:e,batch:async s=>(await e.batch(s.map(({sql:c,parameters:a})=>({sql:c,args:a})))).map(r),query:t.buildQueryFn({all:async(s,o)=>(await i(s,o)).rows,run:i}),close:()=>e.close()}},{supports:{batching:true,softscans:true},additionalPlugins:[new ti],excludeTables:["libsql_wasm_func_table"]})}var ud={users:pn,media:Pn},Gs=class{constructor(e,t={}){this.em=e;this._options=t;}get options(){return {...this._options,indentWidth:2,indentChar:" ",entityCommentMultiline:true,fieldCommentMultiline:false}}toTypes(){return this.em.entities.map(e=>e.toTypes())}getTab(e=1){return this.options.indentChar.repeat(this.options.indentWidth).repeat(e)}collectImports(e,t={}){for(let[,r]of Object.entries(e.fields))for(let i of r.import??[]){let s=i.name,o=i.package;t[o]||(t[o]=[]),t[o].includes(s)||t[o].push(s);}return t}typeName(e){return no(e)}fieldTypesToString(e,t){let r="",i=this.options.fieldCommentMultiline,s=t?.indent??1;for(let[o,c]of Object.entries(e.fields)){if(t?.ignore_fields?.includes(o))continue;let a="";a+=this.commentString(c.comment,s,i),a+=`${this.getTab(s)}${o}${c.required?"":"?"}: `,a+=c.type+";",a+=`
`,r+=a;}return r}relationToFieldType(e,t){let r=e.other(t),i=e.isListableFor(t),o=this.typeName(r.entity.name);return r.entity.type==="system"&&(o=`DB["${r.entity.name}"]`),{fields:{[r.reference]:{required:false,type:`${o}${i?"[]":""}`}}}}importsToString(e){let t=[];for(let[r,i]of Object.entries(e))t.push(`import type { ${i.join(", ")} } from "${r}";`);return t}commentString(e,t=0,r=true){if(!e)return "";let i=this.getTab(t);return r?`${i}/**
${i} * ${e}
${i} */
`:`${i}// ${e}
`}entityToTypeString(e,t){let r=e.toTypes(),i=this.typeName(r.name),s=t?.indent??1,o=Math.max(0,s-1),c=this.commentString(r.comment,o,this.options.entityCommentMultiline);c+=`${t?.export?"export ":""}interface ${i} {
`,c+=this.fieldTypesToString(r,t);let l=this.em.relations.relationsOf(e).map(u=>this.relationToFieldType(u,e));for(let u of l)c+=this.fieldTypesToString(u,{indent:s});return c+=`${this.getTab(o)}}`,c}toString(){let e=[],t={},r={bknd:["DB"],kysely:["Insertable","Selectable","Updateable","Generated"]},i=`declare global {
`;i+=`${this.getTab(1)}type BkndEntity<T extends keyof DB> = Selectable<DB[T]>;
`,i+=`${this.getTab(1)}type BkndEntityCreate<T extends keyof DB> = Insertable<DB[T]>;
`,i+=`${this.getTab(1)}type BkndEntityUpdate<T extends keyof DB> = Updateable<DB[T]>;
`,i+="}",e.push(i);let s=this.em.entities.filter(l=>l.type==="system");for(let l of this.em.entities){if(s.includes(l))continue;let u=l.toTypes();if(!u)continue;this.collectImports(u,r),t[u.name]=this.typeName(u.name);let p=this.entityToTypeString(l,{export:true});e.push(p);}let o=`interface Database {
`;for(let[l,u]of Object.entries(t))o+=`${this.getTab(1)}${l}: ${u};
`;o+="}",e.push(o);let c=`declare module "bknd" {
`;for(let l of s){let u=Object.keys(ud[l.name]);l.fields.filter(d=>!u.includes(d.name)&&d.type!=="primary").map(d=>d.name).length!==0&&(c+=`${this.getTab(1)}${this.entityToTypeString(l,{ignore_fields:["id",...u],indent:2})}
`);}return c+=`${this.getTab(1)}interface DB extends Database {}
}`,e.push(c),[this.importsToString(r).join(`
`),e.join(`
`)].join(`
`)}};var Ws=class extends ut{name="sqlite-local";constructor(e){super({dialect:SqliteDialect,dialectArgs:[{database:e}]}),this.client=e;}};try{let{emitWarning:n}=process;process.emitWarning=(e,...t)=>{if(!e.includes("SQLite is an experimental feature"))return n(e,...t)};}catch{}var FS={...qt},MS={...ve,...mt};export{Ic as ActionContext,Vn as App,Ds as AppEvents,er as AuthPermissions,Ye as AuthStrategy,Ut as BaseIntrospector,ue as BkndError,te as Connection,He as DataPermissions,MS as DatabaseEvents,$r as EntityNotDefinedException,So as EntityNotFoundException,Gs as EntityTypescript,v as Event,$ as EventManager,C as Exception,S as Field,We as InvalidCredentialsException,le as InvalidEventReturn,Br as InvalidFieldConfigException,V as InvalidSearchParamsException,Ne as KyselyPluginRunner,FS as MediaEvents,mr as MediaPermissions,Fs as ModuleManagerEvents,x as Permission,km as RenderContext,ut as SqliteConnection,Er as SqliteIntrospector,Ws as SqliteLocalConnection,rt as Storage,it as StorageAdapter,ot as StorageCloudinaryAdapter,st as StorageS3Adapter,O as TransformPersistFailedException,qr as TransformRetrieveFailedException,Ir as UnableToConnectException,os as UserExistsException,Zt as UserNotFoundException,k as baseFieldConfigSchema,es as boolean,Qe as config,Aa as createApp,Pr as customIntrospector,rl as date,Tt as datetime,Ht as em,Ge as entity,Rt as enumm,Qt as env,zs as genericSqlite,Wa as genericSqliteUtils,Ca as getDefaultConfig,Ra as getDefaultSchema,ga as getExtensionFromName,Ol as getFlashMessage,On as getRandomizedFilename,fc as guessMimeType,Lo as index,A as isDebug,ts as json,rs as jsonSchema,ld as libsql,op as mailchannelsEmail,ns as make,il as media,sl as medium,rp as memoryCache,on as middlewares,St as number,Cs as registries,Uo as relation,np as resendEmail,sp as sesEmail,se as text,nl as week};