bknd
Version:
Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.
4 lines • 812 kB
JavaScript
"use client";
import*as nt from'react';import nt__default,{createContext,forwardRef,useImperativeHandle,useState,useEffect,memo,lazy,cloneElement,createElement,isValidElement,useContext,Children,Suspense,Component,useId,useRef,Fragment as Fragment$1,use,useMemo,useCallback,createRef,useReducer,useDebugValue,startTransition,useLayoutEffect,useTransition,useSyncExternalStore as useSyncExternalStore$1}from'react';import {useDisclosure,useFocusTrap,useClickOutside,useClipboard,useDebouncedCallback,randomId,useHotkeys,useForceUpdate,useReducedMotion,useDidUpdate,useViewportSize,useListState,useToggle,getHotkeyHandler,useInViewport}from'@mantine/hooks';import Ds from'react-dom';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {createUseExternalEvents,Modal,Tooltip,TextInput,Tabs,Textarea,Switch,Select,NumberInput,Input,SegmentedControl,Popover,Radio,MantineProvider,getDefaultZIndex,createVarsResolver,rem,factory,useProps,useMantineTheme,useStyles,OptionalPortal,Box,RemoveScroll,Button,RadioGroup,createTheme,Menu,TagsInput,Notification,useMantineColorScheme,Group,Slider}from'@mantine/core';import {s,stringIdentifier,ucFirstAllSnakeToPascalWithSpaces,pickKeys,omitKeys,formatNumber,objectTransform,objectCleanEmpty,$console,isObject,transformObject,getBrowser,snakeToPascalWithSpaces,parse,isEqual,ensureInt,dayjs,objectToJsLiteral,uuidv7,InvalidSchemaError,Tool,getPath,limitObjectDepth,autoFormatString,mcpLogLevels,invariant,uuid,HttpStatus,isPlainObject,secret,hash as hash$1,describeRoute,jsc,filterKeys,isFile,pickHeaders2,pickHeaders,pick,clampNumber,threw,isFileAccepted,encodeSearch,ucFirst,mergeObject,decodeSearch,patternMatch,secureRandomString,deepFreeze,stripMark,mergeObjectWith,getFullPathKeys,mcpTool,truncate,runtimeSupports,schemaToSpec,convertNumberedObjectToArray,detectImageDimensions,getFileFromContext,randomString,recursivelyReplacePlaceholders}from'bknd/utils';import {sql}from'kysely';import {Validator}from'@cfworker/json-schema';import {mergeWith,get,omit,isEmpty,transform,throttle,cloneDeep,isEqual as isEqual$1,pick as pick$1,has,set}from'lodash-es';import {cors}from'hono/cors';import {createMiddleware}from'hono/factory';import {Hono}from'hono';import {setSignedCookie,getSignedCookie,deleteCookie,setCookie}from'hono/cookie';import {sign,verify}from'hono/jwt';import {serializeSigned}from'hono/utils/cookie';import*as jt from'oauth4webapi';import {genSalt,hash,compare}from'bcryptjs';import {XMLParser}from'fast-xml-parser';import {AwsClient}from'aws4fetch';import {useSyncExternalStore}from'use-sync-external-store/shim/index.js';import {useEntityQuery,ClientProvider,useBkndWindowContext,useApi,useInvalidate,useApiInfiniteQuery,useApiQuery,useAuth,useEntityMutate,mountOnce}from'bknd/client';import {create,useStore,createStore}from'zustand';import {combine,persist}from'zustand/middleware';import CB from'dayjs';import frt from'dayjs/plugin/weekOfYear.js';import fo from'picocolors';import'hono/adapter';import*as F4 from'jsonv-ts';import'jsonv-ts/hono';import {McpClient}from'jsonv-ts/mcp';import {ScrollArea,Switch as Switch$1}from'radix-ui';import f8t,{EditorView}from'@uiw/react-codemirror';import {json}from'@codemirror/lang-json';import {html}from'@codemirror/lang-html';import {Draft2019}from'json-schema-library';import*as R5 from'object-path-immutable';import {Handle,Position,MarkerType,ReactFlowProvider,useNodesState,useEdgesState,useReactFlow,addEdge,ReactFlow,Background,BackgroundVariant,MiniMap,useViewport,Panel}from'@xyflow/react';import tIt,{mutate}from'swr';import {Draggable,DragDropContext,Droppable}from'@hello-pangea/dnd';import {useSyncExternalStoreWithSelector}from'use-sync-external-store/shim/with-selector.js';import {useForm}from'@tanstack/react-form';var MQ=Object.create;var Ig=Object.defineProperty;var xQ=Object.getOwnPropertyDescriptor;var kQ=Object.getOwnPropertyNames;var bQ=Object.getPrototypeOf,yQ=Object.prototype.hasOwnProperty;var v=(t,a)=>()=>(t&&(a=t(t=0)),a);var y=(t,a)=>()=>(a||t((a={exports:{}}).exports,a),a.exports),fe=(t,a)=>{for(var r in a)Ig(t,r,{get:a[r],enumerable:true});},LQ=(t,a,r,e)=>{if(a&&typeof a=="object"||typeof a=="function")for(let o of kQ(a))!yQ.call(t,o)&&o!==r&&Ig(t,o,{get:()=>a[o],enumerable:!(e=xQ(a,o))||e.enumerable});return t};var V=(t,a,r)=>(r=t!=null?MQ(bQ(t)):{},LQ(a||!t||!t.__esModule?Ig(r,"default",{value:t,enumerable:true}):r,t));function Sg(t){let a=t,r=false,e=new Set;return {getState(){return a},updateState(o){a=typeof o=="function"?o(a):o;},setState(o){this.updateState(o),e.forEach(n=>n(a));},initialize(o){r||(a=o,r=true);},subscribe(o){return e.add(o),()=>e.delete(o)}}}function jg(t){return useSyncExternalStore$1(t.subscribe,()=>t.getState(),()=>t.getState())}var rb=v(()=>{"use client";});var eb=v(()=>{rb();});function TQ(t,a,r){let e=[],o=[],n={};for(let i of t){let l=i.position||a;n[l]=n[l]||0,n[l]+=1,n[l]<=r?o.push(i):e.push(i);}return {notifications:o,queue:e}}function Un(t,a){let r=t.getState(),e=a([...r.notifications,...r.queue]),o=TQ(e,r.defaultPosition,r.limit);t.setState({notifications:o.notifications,queue:o.queue,limit:r.limit,defaultPosition:r.defaultPosition});}function nb(t,a=O1){let r=t.id||randomId();return Un(a,e=>t.id&&e.some(o=>o.id===t.id)?e:[...e,{...t,id:r}]),r}function zs(t,a=O1){return Un(a,r=>r.filter(e=>e.id===t?(e.onClose?.(e),false):true)),t}function ib(t,a=O1){return Un(a,r=>r.map(e=>e.id===t.id?{...e,...t}:e)),t.id}function lb(t=O1){Un(t,()=>[]);}function db(t=O1){Un(t,a=>a.slice(0,t.getState().limit));}var ob,O1,Wg,hr,Fg=v(()=>{"use client";eb();ob=()=>Sg({notifications:[],queue:[],defaultPosition:"bottom-right",limit:5}),O1=ob(),Wg=(t=O1)=>jg(t);hr={show:nb,hide:zs,update:ib,clean:lb,cleanQueue:db,updateState:Un};});function Es(){return Es=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var r=arguments[a];for(var e in r)({}).hasOwnProperty.call(r,e)&&(t[e]=r[e]);}return t},Es.apply(null,arguments)}var cb=v(()=>{});function Ps(t,a){if(t==null)return {};var r={};for(var e in t)if({}.hasOwnProperty.call(t,e)){if(a.indexOf(e)!==-1)continue;r[e]=t[e];}return r}var zg=v(()=>{});function Os(t,a){return Os=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,e){return r.__proto__=e,r},Os(t,a)}var hb=v(()=>{});function As(t,a){t.prototype=Object.create(a.prototype),t.prototype.constructor=t,Os(t,a);}var Eg=v(()=>{hb();});var Pg,sb=v(()=>{Pg={disabled:false};});var el,Og=v(()=>{el=nt__default.createContext(null);});var pb,ub=v(()=>{pb=function(a){return a.scrollTop};});function ol(){}var qd,Hn,Vn,nl,Ag,A1,Rg,gb=v(()=>{zg();Eg();sb();Og();ub();qd="unmounted",Hn="exited",Vn="entering",nl="entered",Ag="exiting",A1=function(t){As(a,t);function a(e,o){var n;n=t.call(this,e,o)||this;var i=o,l=i&&!i.isMounting?e.enter:e.appear,d;return n.appearStatus=null,e.in?l?(d=Hn,n.appearStatus=Vn):d=nl:e.unmountOnExit||e.mountOnEnter?d=qd:d=Hn,n.state={status:d},n.nextCallback=null,n}a.getDerivedStateFromProps=function(o,n){var i=o.in;return i&&n.status===qd?{status:Hn}:null};var r=a.prototype;return r.componentDidMount=function(){this.updateStatus(true,this.appearStatus);},r.componentDidUpdate=function(o){var n=null;if(o!==this.props){var i=this.state.status;this.props.in?i!==Vn&&i!==nl&&(n=Vn):(i===Vn||i===nl)&&(n=Ag);}this.updateStatus(false,n);},r.componentWillUnmount=function(){this.cancelNextCallback();},r.getTimeouts=function(){var o=this.props.timeout,n,i,l;return n=i=l=o,o!=null&&typeof o!="number"&&(n=o.exit,i=o.enter,l=o.appear!==void 0?o.appear:i),{exit:n,enter:i,appear:l}},r.updateStatus=function(o,n){if(o===void 0&&(o=false),n!==null)if(this.cancelNextCallback(),n===Vn){if(this.props.unmountOnExit||this.props.mountOnEnter){var i=this.props.nodeRef?this.props.nodeRef.current:Ds.findDOMNode(this);i&&pb(i);}this.performEnter(o);}else this.performExit();else this.props.unmountOnExit&&this.state.status===Hn&&this.setState({status:qd});},r.performEnter=function(o){var n=this,i=this.props.enter,l=this.context?this.context.isMounting:o,d=this.props.nodeRef?[l]:[Ds.findDOMNode(this),l],c=d[0],h=d[1],p=this.getTimeouts(),s=l?p.appear:p.enter;if(!o&&!i||Pg.disabled){this.safeSetState({status:nl},function(){n.props.onEntered(c);});return}this.props.onEnter(c,h),this.safeSetState({status:Vn},function(){n.props.onEntering(c,h),n.onTransitionEnd(s,function(){n.safeSetState({status:nl},function(){n.props.onEntered(c,h);});});});},r.performExit=function(){var o=this,n=this.props.exit,i=this.getTimeouts(),l=this.props.nodeRef?void 0:Ds.findDOMNode(this);if(!n||Pg.disabled){this.safeSetState({status:Hn},function(){o.props.onExited(l);});return}this.props.onExit(l),this.safeSetState({status:Ag},function(){o.props.onExiting(l),o.onTransitionEnd(i.exit,function(){o.safeSetState({status:Hn},function(){o.props.onExited(l);});});});},r.cancelNextCallback=function(){this.nextCallback!==null&&(this.nextCallback.cancel(),this.nextCallback=null);},r.safeSetState=function(o,n){n=this.setNextCallback(n),this.setState(o,n);},r.setNextCallback=function(o){var n=this,i=true;return this.nextCallback=function(l){i&&(i=false,n.nextCallback=null,o(l));},this.nextCallback.cancel=function(){i=false;},this.nextCallback},r.onTransitionEnd=function(o,n){this.setNextCallback(n);var i=this.props.nodeRef?this.props.nodeRef.current:Ds.findDOMNode(this),l=o==null&&!this.props.addEndListener;if(!i||l){setTimeout(this.nextCallback,0);return}if(this.props.addEndListener){var d=this.props.nodeRef?[this.nextCallback]:[i,this.nextCallback],c=d[0],h=d[1];this.props.addEndListener(c,h);}o!=null&&setTimeout(this.nextCallback,o);},r.render=function(){var o=this.state.status;if(o===qd)return null;var n=this.props,i=n.children;n.in;n.mountOnEnter;n.unmountOnExit;n.appear;n.enter;n.exit;n.timeout;n.addEndListener;n.onEnter;n.onEntering;n.onEntered;n.onExit;n.onExiting;n.onExited;n.nodeRef;var C=Ps(n,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]);return nt__default.createElement(el.Provider,{value:null},typeof i=="function"?i(o,C):nt__default.cloneElement(nt__default.Children.only(i),C))},a}(nt__default.Component);A1.contextType=el;A1.propTypes={};A1.defaultProps={in:false,mountOnEnter:false,unmountOnExit:false,appear:false,enter:true,exit:true,onEnter:ol,onEntering:ol,onEntered:ol,onExit:ol,onExiting:ol,onExited:ol};A1.UNMOUNTED=qd;A1.EXITED=Hn;A1.ENTERING=Vn;A1.ENTERED=nl;A1.EXITING=Ag;Rg=A1;});function fb(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var vb=v(()=>{});function qs(t,a){var r=function(n){return a&&isValidElement(n)?a(n):n},e=Object.create(null);return t&&Children.map(t,function(o){return o}).forEach(function(o){e[o.key]=r(o);}),e}function SQ(t,a){t=t||{},a=a||{};function r(h){return h in a?a[h]:t[h]}var e=Object.create(null),o=[];for(var n in t)n in a?o.length&&(e[n]=o,o=[]):o.push(n);var i,l={};for(var d in a){if(e[d])for(i=0;i<e[d].length;i++){var c=e[d][i];l[e[d][i]]=r(c);}l[d]=r(d);}for(i=0;i<o.length;i++)l[o[i]]=r(o[i]);return l}function $n(t,a,r){return r[a]!=null?r[a]:t.props[a]}function mb(t,a){return qs(t.children,function(r){return cloneElement(r,{onExited:a.bind(null,r),in:true,appear:$n(r,"appear",t),enter:$n(r,"enter",t),exit:$n(r,"exit",t)})})}function Mb(t,a,r){var e=qs(t.children),o=SQ(a,e);return Object.keys(o).forEach(function(n){var i=o[n];if(isValidElement(i)){var l=n in a,d=n in e,c=a[n],h=isValidElement(c)&&!c.props.in;d&&(!l||h)?o[n]=cloneElement(i,{onExited:r.bind(null,i),in:true,exit:$n(i,"exit",t),enter:$n(i,"enter",t)}):!d&&l&&!h?o[n]=cloneElement(i,{in:false}):d&&l&&isValidElement(c)&&(o[n]=cloneElement(i,{onExited:r.bind(null,i),in:c.props.in,exit:$n(i,"exit",t),enter:$n(i,"enter",t)}));}}),o}var xb=v(()=>{});var jQ,WQ,Dg,j0,kb=v(()=>{zg();cb();vb();Eg();Og();xb();jQ=Object.values||function(t){return Object.keys(t).map(function(a){return t[a]})},WQ={component:"div",childFactory:function(a){return a}},Dg=function(t){As(a,t);function a(e,o){var n;n=t.call(this,e,o)||this;var i=n.handleExited.bind(fb(n));return n.state={contextValue:{isMounting:true},handleExited:i,firstRender:true},n}var r=a.prototype;return r.componentDidMount=function(){this.mounted=true,this.setState({contextValue:{isMounting:false}});},r.componentWillUnmount=function(){this.mounted=false;},a.getDerivedStateFromProps=function(o,n){var i=n.children,l=n.handleExited,d=n.firstRender;return {children:d?mb(o,l):Mb(o,i,l),firstRender:false}},r.handleExited=function(o,n){var i=qs(this.props.children);o.key in i||(o.props.onExited&&o.props.onExited(n),this.mounted&&this.setState(function(l){var d=Es({},l.children);return delete d[o.key],{children:d}}));},r.render=function(){var o=this.props,n=o.component,i=o.childFactory,l=Ps(o,["component","childFactory"]),d=this.state.contextValue,c=jQ(this.state.children).map(i);return delete l.appear,delete l.enter,delete l.exit,n===null?nt__default.createElement(el.Provider,{value:d},c):nt__default.createElement(el.Provider,{value:d},nt__default.createElement(n,l,c))},a}(nt__default.Component);Dg.propTypes={};Dg.defaultProps=WQ;j0=Dg;});var bb=v(()=>{kb();gb();});function yb(t,a){return t.reduce((r,e)=>(r[e.position||a].push(e),r),Ng.reduce((r,e)=>(r[e]=[],r),{}))}var Ng,Lb=v(()=>{"use client";Ng=["bottom-center","bottom-left","bottom-right","top-center","top-left","top-right"];});function wb({state:t,maxHeight:a,position:r,transitionDuration:e}){let[o,n]=r.split("-"),i=n==="center"?`${o}-center`:n,l={opacity:0,maxHeight:a,transform:Cb[i],transitionDuration:`${e}ms, ${e}ms, ${e}ms`,transitionTimingFunction:"cubic-bezier(.51,.3,0,1.21), cubic-bezier(.51,.3,0,1.21), linear",transitionProperty:"opacity, transform, max-height"},d={opacity:1,transform:FQ[i]},c={opacity:0,maxHeight:0,transform:Cb[i]};return {...l,...{entering:d,entered:d,exiting:c,exited:c}[t]}}var Cb,FQ,Tb=v(()=>{"use client";Cb={left:"translateX(-100%)",right:"translateX(100%)","top-center":"translateY(-100%)","bottom-center":"translateY(100%)"},FQ={left:"translateX(0)",right:"translateX(0)","top-center":"translateY(0)","bottom-center":"translateY(0)"};});function Bb(t,a){return typeof a=="number"?a:a===false||t===false?false:t}var Ib=v(()=>{"use client";});var _g,jb=v(()=>{"use client";Ib();_g=forwardRef(({data:t,onHide:a,autoClose:r,...e},o)=>{let{autoClose:n,message:i,...l}=t,d=Bb(r,t.autoClose),c=useRef(-1),h=()=>window.clearTimeout(c.current),p=()=>{a(t.id),h();},s=()=>{typeof d=="number"&&(c.current=window.setTimeout(p,d));};return useEffect(()=>{t.onOpen?.(t);},[]),useEffect(()=>(s(),h),[d]),jsx(Notification,{...e,...l,onClose:p,ref:o,onMouseEnter:h,onMouseLeave:s,children:i})});_g.displayName="@mantine/notifications/NotificationContainer";});var qg,Wb=v(()=>{"use client";qg={root:"m_b37d9ac7",notification:"m_5ed0edd0"};});var QQ,YQ,XQ,Ae,Eb=v(()=>{"use client";bb();Lb();Tb();jb();Fg();Wb();QQ=Rg,YQ={position:"bottom-right",autoClose:4e3,transitionDuration:250,containerWidth:440,notificationMaxHeight:200,limit:5,zIndex:getDefaultZIndex("overlay"),store:O1,withinPortal:true},XQ=createVarsResolver((t,{zIndex:a,containerWidth:r})=>({root:{"--notifications-z-index":a?.toString(),"--notifications-container-width":rem(r)}})),Ae=factory((t,a)=>{let r=useProps("Notifications",YQ,t),{classNames:e,className:o,style:n,styles:i,unstyled:l,vars:d,position:c,autoClose:h,transitionDuration:p,containerWidth:s,notificationMaxHeight:u,limit:g,zIndex:f,store:m,portalProps:M,withinPortal:x,...b}=r,k=useMantineTheme(),L=Wg(m),C=useForceUpdate(),w=useReducedMotion(),B=useRef({}),F=useRef(0),z=(k.respectReducedMotion?w:false)?1:p,S=useStyles({name:"Notifications",classes:qg,props:r,className:o,style:n,classNames:e,styles:i,unstyled:l,vars:d,varsResolver:XQ});useEffect(()=>{m?.updateState(A=>({...A,limit:g||5,defaultPosition:c}));},[g,c]),useDidUpdate(()=>{L.notifications.length>F.current&&setTimeout(()=>C(),0),F.current=L.notifications.length;},[L.notifications]);let W=yb(L.notifications,c),O=Ng.reduce((A,$)=>(A[$]=W[$].map(({style:gt,...D})=>jsx(QQ,{timeout:z,onEnter:()=>B.current[D.id].offsetHeight,nodeRef:{current:B.current[D.id]},children:Q=>jsx(_g,{ref:ut=>{B.current[D.id]=ut;},data:D,onHide:ut=>zs(ut,m),autoClose:h,...S("notification",{style:{...wb({state:Q,position:$,transitionDuration:z,maxHeight:u}),...gt}})})},D.id)),A),{});return jsxs(OptionalPortal,{withinPortal:x,...M,children:[jsx(Box,{...S("root"),"data-position":"top-center",ref:a,...b,children:jsx(j0,{children:O["top-center"]})}),jsx(Box,{...S("root"),"data-position":"top-left",...b,children:jsx(j0,{children:O["top-left"]})}),jsx(Box,{...S("root",{className:RemoveScroll.classNames.fullWidth}),"data-position":"top-right",...b,children:jsx(j0,{children:O["top-right"]})}),jsx(Box,{...S("root",{className:RemoveScroll.classNames.fullWidth}),"data-position":"bottom-right",...b,children:jsx(j0,{children:O["bottom-right"]})}),jsx(Box,{...S("root"),"data-position":"bottom-left",...b,children:jsx(j0,{children:O["bottom-left"]})}),jsx(Box,{...S("root"),"data-position":"bottom-center",...b,children:jsx(j0,{children:O["bottom-center"]})})]})});Ae.classes=qg;Ae.displayName="@mantine/notifications/Notifications";Ae.show=hr.show;Ae.hide=hr.hide;Ae.update=hr.update;Ae.clean=hr.clean;Ae.cleanQueue=hr.cleanQueue;Ae.updateState=hr.updateState;});var Gn=v(()=>{Fg();Eb();});var Pb=v(()=>{});var _a,Jn,W0=v(()=>{_a=class extends Error{code=400;name="Exception";_context=void 0;constructor(a,r){super(a),r&&(this.code=r);}context(a){return this._context=a,this}toJSON(){return {error:this.message,type:this.name,context:this._context}}},Jn=class t extends Error{constructor(r,e,o){super(r);this.details=e;this.type=o;}static with(r,e,o){throw new t(r,e,o)}toJSON(){return {type:this.type??"unknown",message:this.message,details:this.details}}};});function Re(t){return ["string","number","boolean"].includes(typeof t)}function Nb(t){return [true,false,0,1].includes(t)}function Ma(t,a,r){return invariant(typeof t=="string","key must be a string"),invariant(t[0]==="$","key must start with '$'"),invariant(typeof a=="function","valid must be a function"),invariant(typeof r=="function","validate must be a function"),new Ug(t,a,r)}function _b(t,a){let r=t.find(e=>e.key===a);if(!r)throw new Error(`Expression does not exist: "${a}"`);return r}function Hg(t,a,r=[]){invariant(typeof t=="object","$query must be an object");let e=a.map(d=>d.key),o=Object.keys(t??{}),n=[Rb],i={};if(o.some(d=>d.startsWith("$")&&!n.includes(d)))throw new Error(`Invalid key '${o}'. Keys must not start with '$'.`);if(r.length>0&&o.some(d=>n.includes(d)))throw new Error(`Operand ${Rb} can only appear at the top level.`);function l(d,c,h=[]){if(_b(a,d).valid(c)===false)throw new Error(`Given value at "${[...h,d].join(".")}" is invalid, got "${JSON.stringify(c)}"`)}for(let[d,c]of Object.entries(t))if(c!==void 0)if(d==="$or")invariant(isPlainObject(c),"$or must be an object"),i.$or=Hg(c,a,[...r,d]);else if(Re(c))l("$eq",c,r),i[d]={$eq:c};else if(isPlainObject(c)){let h=Object.keys(c).filter(p=>!e.includes(p));if(h.length===0){i[d]={};for(let[p,s]of Object.entries(c))l(p,s,[...r,d]),i[d][p]=s;}else throw new Error(`Invalid key(s) at "${d}": ${h.join(", ")}. Expected expression key: ${e.join(", ")}.`)}else throw new Error(`Invalid value at "${[...r,d].join(".")}", got "${JSON.stringify(c)}"`);return i}function Db(t,a,r){let e=r.convert?Hg(t,a):t,o={$and:[],$or:[],keys:new Set},{$or:n,...i}=e;function l(d,c,h,p=[]){let s=_b(a,d);if(!s)throw new Error(`Expression does not exist: "${d}"`);if(!s.valid(c))throw new Error(`Invalid value at "${[...p,d].join(".")}", got "${JSON.stringify(c)}"`);return s.validate(c,h,r.exp_ctx)}for(let[d,c]of Object.entries(i))if(c!==void 0)for(let[h,p]of Object.entries(c)){let s=r.value_is_kv?d:getPath(r.object,d);o.$and.push(l(h,p,s,[d])),o.keys.add(d);}for(let[d,c]of Object.entries(n??{})){let h=r.value_is_kv?d:getPath(r.object,d);for(let[p,s]of Object.entries(c))o.$or.push(l(p,s,h,[d])),o.keys.add(d);}return o}function ZQ(t){let a={$and:void 0,$or:void 0};return a.$and=t.$and.every(r=>!!r),a.$or=t.$or.some(r=>!!r),!!a.$and||!!a.$or}function Hs(t){if(!t.some(a=>a.key==="$eq"))throw new Error("'$eq' expression is required");return {convert:a=>Hg(a,t),build:(a,r)=>Db(a,t,r),validate:(a,r)=>{let e=Db(a,t,r);return ZQ(e)},expressions:t,expressionKeys:t.map(a=>a.key)}}var Ug,Rb,Vg=v(()=>{Ug=class{constructor(a,r,e){this.key=a;this.valid=r;this.validate=e;}expect};Rb="$or";});var tY,aY,$g,qb=v(()=>{Vg();tY=[Ma("$eq",t=>Re(t),(t,a)=>t===a),Ma("$ne",t=>Re(t),(t,a)=>t!==a),Ma("$like",t=>Re(t),(t,a)=>{switch(typeof a){case "string":return a.includes(t);case "number":return a===Number(t);case "boolean":return a===!!t;default:return false}}),Ma("$regex",t=>t instanceof RegExp?true:typeof t=="string",(t,a)=>t instanceof RegExp?t.test(a):typeof t=="string"?new RegExp(t).test(a):false),Ma("$isnull",t=>true,(t,a)=>t?a===null:a!==null),Ma("$notnull",t=>true,(t,a)=>t?a!==null:a===null),Ma("$in",t=>Array.isArray(t),(t,a)=>t.includes(a)),Ma("$notin",t=>Array.isArray(t),(t,a)=>!t.includes(a)),Ma("$gt",t=>typeof t=="number",(t,a)=>a>t),Ma("$gte",t=>typeof t=="number",(t,a)=>a>=t),Ma("$lt",t=>typeof t=="number",(t,a)=>a<t),Ma("$lte",t=>typeof t=="number",(t,a)=>a<=t),Ma("$between",t=>Array.isArray(t)&&t.length===2&&t.every(a=>typeof a=="number"),(t,a)=>t[0]<=a&&a<=t[1])],aY=Hs(tY),$g=(t,a)=>aY.validate(t,{object:a,convert:true});});var Vs,Ub=v(()=>{W0();Vs=class extends _a{constructor(r,e,o){super(`Permission "${r.name}" not granted`);this.permission=r;this.policy=e;this.description=o;}name="PermissionsException";code=HttpStatus.FORBIDDEN;toJSON(){return {...super.toJSON(),description:this.description,permission:this.permission.name,policy:this.policy?.toJSON()}}};});function Yt(){try{return Gg(0)}catch{return false}}function Hb(){try{return "0.20.0"}catch{return "0.0.0"}}var Gg,oY,$s,yr=v(()=>{Gg=(t,a)=>typeof t=="string"?[1,"1","true"].includes(t):!!(t||a);oY={cli_log_level:{key:"BKND_CLI_LOG_LEVEL",validate:t=>{if(typeof t=="string"&&["log","info","warn","error","debug"].includes(t.toLowerCase()))return t.toLowerCase()}},cli_create_ref:{key:"BKND_CLI_CREATE_REF",validate:t=>typeof t=="string"?t:void 0},cli_telemetry:{key:"BKND_CLI_TELEMETRY",validate:t=>{if(!(typeof t>"u"))return Gg(t,true)}},modules_debug:{key:"BKND_MODULES_DEBUG",validate:Gg}},$s=(t,a,r)=>{try{let e=r?.source??process.env,o=oY[t],n=e[o.key],i=o.validate(n);if(typeof i<"u")return r?.onValid?.(i),i;r?.onFallback?.(n);}catch{r?.onFallback?.(void 0);}return a};});var Ga,d1,Jg,Kg=v(()=>{Ga=class{_returning;static slug="untitled-event";params;returned=false;validate(a){throw new Jg(this,a)}clone(a){let r=new this.constructor(a);return r.returned=true,r}constructor(a){this.params=a;}},d1=class extends Error{constructor(a,r){super(`Expected "${a}", got "${r}"`);}},Jg=class extends Error{constructor(r,e){super(`Event "${r.constructor.slug}" returned without validation`);this.data=e;}};});var Gs,Vb=v(()=>{Gs=class{mode="async";event;handler;once=false;id;constructor(a,r,e="async",o){this.event=a,this.handler=r,this.mode=e,this.id=o;}};});var De,$b=v(()=>{Kg();Vb();De=class{constructor(a,r){this.options=r;a&&this.registerEvents(a),r?.listeners?.forEach(e=>this.addListener(e));}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:(a,r)=>this.events.find(e=>e.slug===r)})}eventExists(a){let r;return typeof a=="string"?r=a:r=a.constructor?.slug??a.slug,!!this.events.find(e=>r===e.slug)}throwIfEventNotRegistered(a){if(!this.eventExists(a)){let r=a.constructor?.slug??a.slug??a;throw new Error(`Event "${r}" not registered`)}}registerEvent(a,r=false){if(this.eventExists(a)){if(r)return this;throw new Error(`Event "${a.name}" already registered.`)}return this.events.push(a),this}registerEvents(a){return (typeof a=="object"?Object.values(a):a).forEach(e=>this.registerEvent(e,true)),this}addListener(a){return this.throwIfEventNotRegistered(a.event),a.id&&this.listeners.find(e=>e.id===a.id)?($console.debug(`Listener with id "${a.id}" already exists.`),this):(this.listeners.push(a),this)}createEventListener(a,r,e="async"){let o=typeof a=="string"?this.events.find(l=>l.slug===a):a,n=typeof e=="string"?{mode:e}:e,i=new Gs(o,r,n.mode);n.once&&(i.once=true),n.id&&(i.id=`${o.slug}-${n.id}`),this.addListener(i);}onEvent(a,r,e){this.createEventListener(a,r,e);}on(a,r,e){this.createEventListener(a,r,e);}onAny(a,r){this.events.forEach(e=>this.onEvent(e,a,r));}collectAsyncs(a){this.asyncs.push(...a);}async executeAsyncs(a=r=>Promise.all(r)){if(this.asyncs.length===0)return;let r=[...this.asyncs];this.asyncs=[],await a(r.map(e=>e()));}async emit(a){let r=a.constructor.slug;if(!this.enabled)return $console.debug("EventManager disabled, not emitting",r),a;if(!this.eventExists(a))throw new Error(`Event "${r}" not registered`);let e=[],o=[];this.listeners=this.listeners.filter(i=>i.event.slug!==r?true:(i.mode==="sync"?e.push(i):o.push(async()=>{try{await i.handler(a,i.event.slug);}catch(l){this.options?.onError?this.options.onError(a,l):$console.error("Error executing async listener",i,l);}}),!i.once)),this.collectAsyncs(o);let n=a;for(let i of e)try{let l=await i.handler(n,i.event.slug);if(typeof l<"u"){let d=n.validate(l);if(d&&d.constructor.slug===r){if(!d.returned)throw new Error(`Returned event ${d.constructor.slug} must be marked as returned.`);n=d;}}}catch(l){if(l instanceof d1)this.options?.onInvalidReturn?.(n,l),$console.warn(`Invalid return of event listener for "${r}": ${l.message}`);else if(this.options?.onError)this.options.onError(n,l);else throw l}return n}};});var F0=v(()=>{Kg();$b();});var Ks,Gb=v(()=>{Ks=class{plugins;constructor(a=[]){this.plugins=new Set(a);}async transformResultRows(a){let r=a;for(let e of this.plugins)r=(await e.transformResult({queryId:"1",result:{rows:r}})).rows;return r}};});var Jb,Kb,dl,Qg=v(()=>{Gb();Jb=["text","integer","real","blob","date","datetime","timestamp","boolean","json"],Kb=Symbol.for("bknd:connection"),dl=class{constructor(a,r={},e=[]){this.fn=r;this.plugins=e;this.kysely=a,this[Kb]=true,this.pluginRunner=new Ks(e);}initialized=false;pluginRunner;supported={batching:false,softscans:true};kysely;client;async init(){this.initialized=true;}static isConnection(a){return a?a[Kb]===true:false}getIntrospector(){return this.kysely.introspection}supports(a){return this.supported[a]??false}async ping(){return (await sql`SELECT 1`.execute(this.kysely)).rows.length>0}async transformResultRows(a){return await this.pluginRunner.transformResultRows(a)}async executeQueries(...a){return Promise.all(a.map(async r=>await this.kysely.executeQuery(r)))}async executeQuery(a){return (await this.executeQueries(a))[0]}getCompiled(...a){return a.map(r=>"compile"in r?r.compile():r)}async withTransformedRows(a,r){return await Promise.all(a.map(async e=>{let o=r??"rows",{[o]:n,...i}=e;return {...i,rows:await this.transformResultRows(n)}}))}validateFieldSpecType(a){if(!Jb.includes(a))throw new Error(`Invalid field type "${a}". Allowed types are: ${Jb.join(", ")}`);return true}toDriver(a,r){return a}fromDriver(a,r){return a}async close(){}};});var Qs,me,Ys,ar,Xs,Zs,ro=v(()=>{W0();Qs=class extends _a{name="UnableToConnectException";code=HttpStatus.INTERNAL_SERVER_ERROR},me=class extends _a{name="InvalidSearchParamsException";code=HttpStatus.UNPROCESSABLE_ENTITY},Ys=class extends _a{name="TransformRetrieveFailedException";code=HttpStatus.UNPROCESSABLE_ENTITY},ar=class t extends _a{name="TransformPersistFailedException";code=HttpStatus.UNPROCESSABLE_ENTITY;static invalidType(a,r,e){let o=typeof e=="object"?JSON.stringify(e):e,n=`Property "${a}" must be of type "${r}", "${o}" of type "${typeof e}" given.`;return new t(n)}static required(a){return new t(`Property "${a}" is required`)}},Xs=class extends _a{constructor(r,e,o){console.error("InvalidFieldConfigException",{given:e,error:o.first()});super(`Invalid Field config given for field "${r.name}": ${o.firstToString()}`);this.given=e;}name="InvalidFieldConfigException";code=HttpStatus.BAD_REQUEST},Zs=class extends _a{name="EntityNotDefinedException";code=HttpStatus.BAD_REQUEST;constructor(a){a?super(`Entity "${typeof a!="string"?a.name:a}" not defined`):super("Cannot find an entity that is undefined");}};});var Yg,Xg,Zg,tf,af,Ud,Kn,rf,ef,of,nf,tp,Hd=v(()=>{F0();Yg=class extends Ga{static slug="mutator-insert-before";validate(a){let{entity:r}=this.params;if(!r.isValidData(a,"create"))throw $console.warn("MutatorInsertBefore.validate: invalid",{entity:r.name,data:a}),new d1("EntityData","invalid");return this.clone({entity:r,data:a})}},Xg=class extends Ga{static slug="mutator-insert-after"},Zg=class extends Ga{static slug="mutator-update-before";validate(a){let{entity:r,entityId:e}=this.params;if(!r.isValidData(a,"update"))throw $console.warn("MutatorUpdateBefore.validate: invalid",{entity:r.name,entityId:e,data:a}),new d1("EntityData","invalid");return this.clone({entityId:e,entity:r,data:a})}},tf=class extends Ga{static slug="mutator-update-after"},af=class extends Ga{static slug="mutator-delete-before"},Ud=class extends Ga{static slug="mutator-delete-after"},Kn={MutatorInsertBefore:Yg,MutatorInsertAfter:Xg,MutatorUpdateBefore:Zg,MutatorUpdateAfter:tf,MutatorDeleteBefore:af,MutatorDeleteAfter:Ud},rf=class extends Ga{static slug="repository-find-one-before"},ef=class extends Ga{static slug="repository-find-one-after"},of=class extends Ga{static slug="repository-find-many-before";static another="one"},nf=class extends Ga{static slug="repository-find-many-after"},tp={RepositoryFindOneBefore:rf,RepositoryFindOneAfter:ef,RepositoryFindManyBefore:of,RepositoryFindManyAfter:nf};});var hl,ap=v(()=>{hl=class{_relations=[];constructor(a){this._relations=a;}get all(){return this._relations}exists(a){return this._relations.some(r=>r.source.entity.name===a.source.entity.name&&r.target.entity.name===a.target.entity.name&&r.type===a.type)}relationsOf(a){return this._relations.filter(r=>r.visibleFrom("source")&&r.source.entity.name===a.name||r.visibleFrom("target")&&r.target.entity.name===a.name)}sourceRelationsOf(a){return this._relations.filter(r=>r.source.entity.name===a.name)}targetRelationsOf(a){return this._relations.filter(r=>r.visibleFrom("target")&&r.target.entity.name===a.name)}listableRelationsOf(a){return this.relationsOf(a).filter(r=>r.isListableFor(a))}relationOf(a,r){return this.relationsOf(a).find(e=>e.target.entity.name===a.name&&e.source.reference===r||e.source.entity.name===a.name&&e.target.reference===r)}hasRelations(a){return this.relationsOf(a).length>0}relatedEntitiesOf(a){return this.relationsOf(a).map(r=>r.other(a).entity)}relationReferencesOf(a){return this.relationsOf(a).map(r=>r.other(a).reference)}};});var hY,sY,Yb,Xb,za,La,eo=v(()=>{ro();hY=["create","read","update","delete"],sY=["create","read","update","delete","form","table","submit"],Yb=true,Xb=false,za=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:hY}),{title:"Context",uniqueItems:true})]),hidden:s.anyOf([s.boolean({title:"Boolean"}),s.array(s.string({enum:sY}),{title:"Context",uniqueItems:true})]),virtual:s.boolean(),default_value:s.any()}).partial(),La=class{_required;_type;name;type="field";config;constructor(a,r){this.name=a,this._type,this._required;try{this.config=parse(this.getSchema(),r||{});}catch(e){throw e instanceof InvalidSchemaError?new Xs(this,r,e):e}}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(a){return Array.isArray(this.config.fillable)?a?this.config.fillable.includes(a):Yb:this.config.fillable??Yb}isHidden(a){return Array.isArray(this.config.hidden)?a?this.config.hidden.includes(a):Xb:this.config.hidden??Xb}isRequired(){return this.config?.required??false}isVirtual(){return this.config.virtual??false}getLabel(a){return this.config.label?this.config.label:a?.fallback!==false?snakeToPascalWithSpaces(this.name):void 0}getDescription(){return this.config.description}getValue(a,r){return a}getHtmlConfig(){return {element:"input",props:{type:"text"}}}isValid(a,r){return typeof a<"u"?this.isFillable(r):r==="create"?!this.isRequired():true}transformRetrieve(a){return a}async transformPersist(a,r,e){if(this.nullish(a)){if(this.isRequired()&&!this.hasDefault())throw ar.required(this.name);return this.getDefault()}return a}toSchemaWrapIfRequired(a){return this.isRequired()?a:a.optional()}nullish(a){return a==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 df,sl,Zb=v(()=>{ro();eo();df=s.strictObject({default_value:s.boolean(),...omitKeys(za.properties,["default_value"])}).partial(),sl=class extends La{type="boolean";getSchema(){return df}getValue(a,r){switch(r){case "table":return a?"Yes":"No";default:return a}}schema(){return Object.freeze({...super.schema(),type:"boolean"})}getHtmlConfig(){return {...super.getHtmlConfig(),element:"boolean"}}transformRetrieve(a){return typeof a>"u"||a===null?this.isRequired()?false:this.hasDefault()?this.getDefault():null:typeof a=="string"?a==="1":!!a}async transformPersist(a,r,e){let o=await super.transformPersist(a,r,e);if(this.nullish(o))return this.isRequired()?!!this.config.default_value:void 0;if(typeof o=="number")return o!==0;if(typeof o!="boolean")throw ar.invalidType(this.name,"boolean",o);return o}toJsonSchema(){return this.toSchemaWrapIfRequired(s.boolean({default:this.getDefault()}))}toType(){return {...super.toType(),type:"boolean"}}};});var cf,Qn,ry=v(()=>{eo();cf=s.strictObject({type:s.string({enum:["date","datetime","week"],default:"date"}),timezone:s.string(),min_date:s.string(),max_date:s.string(),...za.properties}).partial(),Qn=class extends La{type="date";getSchema(){return cf}schema(){return Object.freeze({...super.schema(),type:this.config.type==="datetime"?"datetime":"date"})}getHtmlConfig(){let a=this.config.type==="datetime"?"datetime-local":this.config.type;return {...super.getHtmlConfig(),element:"date",props:{type:a}}}parseDateFromString(a){if(this.config.type==="week"&&a.includes("-W")){let[r,e]=a.split("-W").map(o=>Number.parseInt(o,10));return dayjs().year(r).week(e).toDate()}return new Date(a)}getValue(a,r){if(a===null||!a)return;let e=this.parseDateFromString(a);if(r==="submit")try{return e.toISOString()}catch{return}if(this.config.type==="week")try{return `${e.getFullYear()}-W${dayjs(e).week()}`}catch(o){$console.warn("DateField.getValue:week error",a,String(o));return}try{let n=new Date().getTimezoneOffset(),i=new Date(e.getTime()-n*6e4);return this.formatDate(i)}catch(o){$console.warn("DateField.getValue error",this.config.type,a,String(o));return}}formatDate(a){switch(this.config.type){case "datetime":return a.toISOString().split(".")[0].replace("T"," ");default:return a.toISOString().split("T")[0]}}transformRetrieve(a){let r=super.transformRetrieve(a);if(r===null)return null;try{return new Date(r)}catch{return null}}async transformPersist(a,r,e){let o=await super.transformPersist(a,r,e);if(this.nullish(o))return o;switch(this.config.type){case "date":case "week":return new Date(o).toISOString().split("T")[0];default:return new Date(o).toISOString()}}toJsonSchema(){return this.toSchemaWrapIfRequired(s.string({default:this.getDefault()}))}toType(){return {...super.toType(),type:"Date | string"}}};});var hf,ul,ey=v(()=>{ro();eo();hf=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()}))})]),...omitKeys(za.properties,["default_value"])}).partial(),ul=class extends La{type="enum";constructor(a,r){if(super(a,r),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 hf}getOptions(){let a=this.config?.options??{type:"strings",values:[]};return a.type==="strings"?a.values?.map(r=>({label:r,value:r})):a?.values}isValidValue(a){return this.getOptions().map(e=>e.value).includes(a)}getValue(a,r){if(!this.isValidValue(a))return this.hasDefault()?this.getDefault():null;switch(r){case "table":return this.getOptions().find(e=>e.value===a)?.label??a}return a}transformRetrieve(a){let r=super.transformRetrieve(a);return r===null&&this.hasDefault()?this.getDefault():this.isValidValue(r)?r:this.hasDefault()?this.getDefault():null}async transformPersist(a,r,e){let o=await super.transformPersist(a,r,e);if(this.nullish(o))return o;if(!this.isValidValue(o))throw new ar(`Field "${this.name}" must be one of the following values: ${this.getOptions().map(n=>n.value).join(", ")}`);return o}toJsonSchema(){let r=(this.config?.options??{values:[]}).values?.map(e=>typeof e=="string"?e:e.value)??[];return this.toSchemaWrapIfRequired(s.string({enum:r,default:this.getDefault()}))}toType(){let a=this.getOptions().map(({value:r})=>typeof r=="string"?`"${r}"`:r);return {...super.toType(),type:a.length>0?a.join(" | "):"string"}}};});var sf,gl,ny=v(()=>{ro();eo();sf=s.strictObject({default_value:s.any(),...omitKeys(za.properties,["default_value"])}).partial(),gl=class extends La{type="json";getSchema(){return sf}transformRetrieve(a){let r=super.transformRetrieve(a);return r===null&&this.hasDefault()?this.getDefault():this.isSerialized(r)?JSON.parse(r):r}isSerializable(a){try{let r=JSON.stringify(a);if(r===JSON.stringify(JSON.parse(r)))return !0}catch{}return false}isSerialized(a){try{if(typeof a=="string")return a===JSON.stringify(JSON.parse(a))}catch{}return false}isValid(a){return this.isSerializable(a)}getValue(a,r){switch(r){case "table":return a===null?null:JSON.stringify(a);case "submit":if(!a||typeof a=="string"&&a.length===0)return null;if(typeof a=="object")return a;try{return JSON.parse(a)}catch{return a}}return a}async transformPersist(a,r,e){let o=await super.transformPersist(a,r,e);if(this.nullish(o))return o;if(!this.isSerializable(o))throw new ar(`Field "${this.name}" must be serializable to JSON.`);return this.isSerialized(o)?o:JSON.stringify(o)}toType(){return {...super.toType(),type:"any"}}};});var pf,vl,iy=v(()=>{ro();eo();pf=s.strictObject({schema:s.any({type:"object"}),ui_schema:s.any({type:"object"}),default_from_schema:s.boolean(),...za.properties}).partial(),vl=class extends La{type="jsonschema";validator;constructor(a,r){super(a,r);let e=this.getJsonSchema();this.validator=new Validator(typeof e=="object"?JSON.parse(JSON.stringify(e)):{});}getSchema(){return pf}getJsonSchema(){return this.config?.schema}getJsonUiSchema(){return this.config.ui_schema??{}}isValid(a,r="update"){return super.isValid(a,r)?!this.isRequired()&&(!a||typeof a!="object")?true:this.validator.validate(a).valid:false}getValue(a,r){switch(r){case "form":return a===null?"":a;case "table":return a===null?null:JSON.stringify(a);}return a}transformRetrieve(a){let r=super.transformRetrieve(a);if(r===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 r}async transformPersist(a,r,e){let o=await super.transformPersist(a,r,e);if(this.nullish(o))return o;if(!this.isValid(o))throw new ar(this.name,o);return !o||typeof o!="object"?this.getDefault():JSON.stringify(o)}toJsonSchema(){let a=this.getJsonSchema()??{type:"object"};return this.toSchemaWrapIfRequired(s.fromSchema({default:this.getDefault(),...a}))}toType(){return {...super.toType(),import:[{package:"json-schema-to-ts",name:"FromSchema"}],type:`FromSchema<${objectToJsLiteral(this.getJsonSchema(),2,1)}>`}}};});var uf,ml,ly=v(()=>{ro();eo();uf=s.strictObject({default_value:s.number(),minimum:s.number(),maximum:s.number(),exclusiveMinimum:s.number(),exclusiveMaximum:s.number(),multipleOf:s.number(),...omitKeys(za.properties,["default_value"])}).partial(),ml=class extends La{type="number";getSchema(){return uf}getHtmlConfig(){return {element:"input",props:{type:"number",pattern:"d*",inputMode:"numeric"}}}schema(){return Object.freeze({...super.schema(),type:"integer"})}getValue(a,r){if(typeof a>"u"||a===null)return null;switch(r){case "submit":return Number.parseInt(a,10)}return a}async transformPersist(a,r,e){let o=await super.transformPersist(a,r,e);if(!this.nullish(o)&&typeof o!="number")throw ar.invalidType(this.name,"number",o);if(this.config.maximum&&o>this.config.maximum)throw new ar(`Field "${this.name}" cannot be greater than ${this.config.maximum}`);if(this.config.minimum&&o<this.config.minimum)throw new ar(`Field "${this.name}" cannot be less than ${this.config.minimum}`);return o}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 rp,gf=v(()=>{rp={server:{default_port:1337,assets_path:"/"},data:{default_primary_field:"id"}};});var $d,ff,zo,vf=v(()=>{gf();eo();$d=["integer","uuid"],ff=s.strictObject({format:s.string({enum:$d,default:"integer"}),required:s.boolean({default:false}),...omitKeys(za.properties,["required"])}).partial(),zo=class extends La{type="primary";constructor(a=rp.data.default_primary_field,r){super(a,{...r,fillable:false,required:false});}isRequired(){return false}getSchema(){return ff}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(a){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 a=this.format==="integer"?"number":"string";return {...super.toType(),required:true,import:[{package:"kysely",name:"Generated"}],type:`Generated<${a}>`}}};});var mf,R1,dy=v(()=>{ro();eo();mf=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"})]))}),...omitKeys(za.properties,["default_value"])}).partial(),R1=class extends La{type="text";getSchema(){return mf}getHtmlConfig(){return this.config.html_config?this.config.html_config:super.getHtmlConfig()}transformRetrieve(a){let r=super.transformRetrieve(a);return this.config.maxLength?r.substring(0,this.config.maxLength):this.isRequired()?r?r.toString():"":r}async transformPersist(a,r,e){let o=await super.transformPersist(a,r,e);if(this.nullish(o))return o;if(o!==null&&typeof o!="string"&&(o=String(o)),this.config.maxLength&&o?.length>this.config.maxLength)throw new ar(`Field "${this.name}" must be at most ${this.config.maxLength} character(s)`);if(this.config.minLength&&o?.length<this.config.minLength)throw new ar(`Field "${this.name}" must be at least ${this.config.minLength} character(s)`);if(this.config.pattern&&o&&!new RegExp(this.config.pattern).test(o))throw new ar(`Field "${this.name}" must match the pattern ${this.config.pattern}`);return o}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 cy=v(()=>{eo();s.strictObject({...za.properties}).partial();});var Ml,hy=v(()=>{eo();Ml=class{constructor(a,r,e=false,o){this.entity=a;this.fields=r;this.unique=e;this.name=o;if(r.length===0)throw new Error("Indices must contain at least one field");if(r.some(n=>!(n instanceof La)))throw new Error("All fields must be instances of Field");o||(this.name=[e?"idx_unique":"idx",a.name,...r.map(n=>n.name)].join("_"));}toJSON(){return {entity:this.entity.name,fields:this.fields.map(a=>a.name),unique:this.unique}}};});var sy,Eo=v(()=>{Zb();ry();ey();ny();iy();ly();vf();dy();eo();vf();cy();hy();sy={primary:{schema:ff,field:zo},text:{schema:mf,field:R1},number:{schema:uf,field:ml},boolean:{schema:df,field:sl},date:{schema:cf,field:Qn},enum:{schema:hf,field:ul},json:{schema:sf,field:gl},jsonschema:{schema:pf,field:vl}};});var ep,py=v(()=>{Eo();ep=class t{constructor(a){this.em=a;}static EXCLUDE_TABLES=["libsql_wasm_func_table","sqlite_sequence","_cf_KV"];getIntrospector(){return this.em.connection.getIntrospector()}async introspect(){let a=await this.getIntrospector().getTables({withInternalKyselyTables:false}),r=await this.getIntrospector().getIndices(),e=[];for(let o of a)t.EXCLUDE_TABLES.includes(o.name)||o.name&&e.push({...o,indices:r.filter(n=>n.table===o.name)});return e}getIntrospectionFromEntity(a){let r=a.getFields(false),e=this.em.getIndicesOf(a);return {name:a.name,isView:false,columns:r.map(o=>({name:o.name,dataType:"TEXT",isNullable:true,isAutoIncrementing:o instanceof zo,hasDefaultValue:false,comment:void 0})),indices:e.map(o=>({name:o.name,table:a.name,isUnique:o.unique,columns:o.fields.map(n=>({name:n.name,order:0}))}))}}async getDiff(){let a=await this.introspect(),r=this.em.entities.map(n=>this.getIntrospectionFromEntity(n)),e=[],o=n=>n.name;a.filter(n=>/bknd/.test(n.name)||n.isView?false:!r.map(i=>i.name).includes(n.name)).forEach(n=>{e.push({name:n.name,isDrop:true,isNew:false,columns:{add:[],drop:[],change:[]},indices:{add:[],drop:[]}});});for(let n of r){let i=a.find(l=>l.name===n.name);if(!i)e.push({name:n.name,isNew:true,columns:{add:n.columns.map(o),drop:[],change:[]},indices:{add:n.indices.map(o),drop:[]}});else {let l=n.columns.filter(u=>!i.columns.map(o).includes(u.name)),d=i.columns.filter(u=>!n.columns.map(o).includes(u.name)),c=[];for(let u of n.columns){let g=i.columns.find(m=>m.name===u.name),f=[];for(let[m,M]of Object.entries(u))g&&g[m]!==M&&f.push({attribute:m,prev:g[m],next:M});Object.keys(f).length>0&&c.push({name:u.name,changes:f});}let h=n.indices.filter(u=>!i.indices.map(g=>g.name).includes(u.name)),p=i.indices.filter(u=>!n.indices.map(g=>g.name).includes(u.name));[l,d,h,p].some(u=>u.length>0)&&e.push({name:n.name,isNew:false,columns:{add:l.map(o),drop:d.map(o),change:[]},indices:{add:h.map(o),drop:p.map(o)}});}}return e}collectFieldSchemas(a,r){let e=[];if(r.length===0)return e;for(let o of r){let i=this.em.entity(a).getField(o).schema();i&&e.push(this.em.connection.getFieldSchema(i));}return e}async sync(a={force:false,drop:false}){let r=await this.getDiff(),e=[],o=this.em.connection.kysely.schema,n=[];for(let i of r){let l=this.collectFieldSchemas(i.name,i.columns.add),d=i.columns.drop,c=i.indices.drop;if(i.isDrop)a.drop&&n.push(o.dropTable(i.name));else if(i.isNew){let h=o.createTable(i.name);for(let p of l)h=h.addColumn(...p);n.push(h);}else {if(l.length>0)for(let h of l)n.push(o.alterTable(i.name).addColumn(...h));if(a.drop&&d.length>0)for(let h of d)n.push(o.alterTable(i.name).dropColumn(h));}for(let h of i.indices.add){let s=this.em.getIndicesOf(i.name).find(g=>g.name===h),u=o.createIndex(h).on(i.name).columns(s.fields.map(g=>g.name));s.unique&&(u=u.unique()),n.push(u);}if(a.drop)for(let h of c)n.push(o.dropIndex(h));}if(n.length>0){e.push(...n.map(i=>{let{sql:l,parameters:d}=i.compile();return {sql:l,parameters:d}})),$console.debug("[SchemaManager]",`${n.length} statements
${e.map(i=>i.sql).join(`;
`)}`);try{await this.em.connection.executeQueries(...n);}catch(i){throw new Error(`Failed to execute batch: ${String(i)}`)}}return e}};});var op,Mf,gy,no,xf=v(()=>{gf();Eo();op=s.strictObject({name:s.string(),name_singular:s.string(),description:s.string(),sort_field:s.string({default:rp.data.default_primary_field}),sort_dir:s.string({enum:["asc","desc"],default:"asc"}),primary_format:s.string({enum:$d})},{default:{}}).partial(),Mf=["regular","system","generated"],gy=Symbol.for("bknd:entity"),no=class t{#t;#a;name;fields;config;data;type="regular";constructor(a,r,e,o){if(typeof a!="string"||a.length===0)throw new Error("Entity name must be a non-empty string");this.name=a,this.config=parse(op,e||{});let n=r?.filter(i=>i instanceof zo).length??0;if(n>1)throw new Error(`Entity "${a}" has more than one primary field`);this.fields=n===1?[]:[new zo(void 0,{format:this.config.primary_format})],r&&r.forEach(i=>this.addField(i)),o&&(this.type=o),this[gy]=true;}static isEntity(a){return a?a[gy]===true:false}static create(a){return new t(a.name,a.fields,a.config,a.type)}getType(){return this.type}getSelect(a,r){return this.getFields().filter(e=>!e.isHidden(r??"read")).map(e=>a?`${a}.${e.name} as ${e.name}`:e.name)}getDefaultSort(){return {by:this.config.sort_field??"id",dir:this.config.sort_dir??"asc"}}getAliasedSelectFrom(a,r,e){let o=r??this.name;return this.getFields().filter(n=>!n.isVirtual()&&!n.isHidden(e??"read")&&a.includes(n.name)).map(n=>o?`${o}.${n.name} as ${n.name}`:n.name)}getFillableFields(a,r){return this.getFields(r).filter(e=>e.isFillable(a))}getRequiredFields(){return this.getFields().filter(a=>a.isRequired())}getDefaultObject(){return this.getFields().reduce((a,r)=>(r.hasDefault()&&(a[r.name]=r.getDefault()),a),{})}getField(a){return this.fields.find(r=>r.name===a)}__replaceField(a,r){let e=this.fields.findIndex(o=>o.name===a);if(e===-1)throw new Error(`Field "${a}" not found on entity "${this.na