UNPKG

bknd

Version:

Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.

3 lines 251 kB
var qc=Object.defineProperty;var et=(r,e)=>{for(var t in e)qc(r,t,{get:e[t],enumerable:!0})};import{$console as vt,McpClient as Pd}from"bknd/utils";var E=class{_returning;static slug="untitled-event";params;returned=!1;validate(e){throw new Ai(this,e)}clone(e){let t=new this.constructor(e);return t.returned=!0,t}constructor(e){this.params=e}};var ue=class extends Error{constructor(e,t){super(`Expected "${e}", got "${t}"`)}},Ai=class extends Error{constructor(t,n){super(`Event "${t.constructor.slug}" returned without validation`);this.data=n}};var Wn=class{mode="async";event;handler;once=!1;id;constructor(e,t,n="async",i){this.event=e,this.handler=t,this.mode=n,this.id=i}};import{$console as Gn}from"bknd/utils";var B=class{constructor(e,t){this.options=t;e&&this.registerEvents(e),t?.listeners?.forEach(n=>this.addListener(n))}events=[];listeners=[];enabled=!0;asyncs=[];enable(){return this.enabled=!0,this}disable(){return this.enabled=!1,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(n=>n.slug===t)})}eventExists(e){let t;return typeof e=="string"?t=e:t=e.constructor?.slug??e.slug,!!this.events.find(n=>t===n.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=!1){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(n=>this.registerEvent(n,!0)),this}addListener(e){return this.throwIfEventNotRegistered(e.event),e.id&&this.listeners.find(n=>n.id===e.id)?(Gn.debug(`Listener with id "${e.id}" already exists.`),this):(this.listeners.push(e),this)}createEventListener(e,t,n="async"){let i=typeof e=="string"?this.events.find(a=>a.slug===e):e,s=typeof n=="string"?{mode:n}:n,o=new Wn(i,t,s.mode);s.once&&(o.once=!0),s.id&&(o.id=`${i.slug}-${s.id}`),this.addListener(o)}onEvent(e,t,n){this.createEventListener(e,t,n)}on(e,t,n){this.createEventListener(e,t,n)}onAny(e,t){this.events.forEach(n=>this.onEvent(n,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(n=>n()))}async emit(e){let t=e.constructor.slug;if(!this.enabled)return Gn.debug("EventManager disabled, not emitting",t),e;if(!this.eventExists(e))throw new Error(`Event "${t}" not registered`);let n=[],i=[];this.listeners=this.listeners.filter(o=>o.event.slug!==t?!0:(o.mode==="sync"?n.push(o):i.push(async()=>{try{await o.handler(e,o.event.slug)}catch(a){this.options?.onError?this.options.onError(e,a):Gn.error("Error executing async listener",o,a)}}),!o.once)),this.collectAsyncs(i);let s=e;for(let o of n)try{let a=await o.handler(s,o.event.slug);if(typeof a<"u"){let c=s.validate(a);if(c&&c.constructor.slug===t){if(!c.returned)throw new Error(`Returned event ${c.constructor.slug} must be marked as returned.`);s=c}}}catch(a){if(a instanceof ue)this.options?.onInvalidReturn?.(s,a),Gn.warn(`Invalid return of event listener for "${t}": ${a.message}`);else if(this.options?.onError)this.options.onError(s,a);else throw a}return s}};import{sql as Ic}from"kysely";var tt=class{plugins;constructor(e=[]){this.plugins=new Set(e)}async transformResultRows(e){let t=e;for(let n of this.plugins)t=(await n.transformResult({queryId:"1",result:{rows:t}})).rows;return t}};var So=["text","integer","real","blob","date","datetime","timestamp","boolean","json"],vo=Symbol.for("bknd:connection"),H=class{constructor(e,t={},n=[]){this.fn=t;this.plugins=n;this.kysely=e,this[vo]=!0,this.pluginRunner=new tt(n)}initialized=!1;pluginRunner;supported={batching:!1,softscans:!0};kysely;client;async init(){this.initialized=!0}static isConnection(e){return e?e[vo]===!0:!1}getIntrospector(){return this.kysely.introspection}supports(e){return this.supported[e]??!1}async ping(){return(await Ic`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 n=>{let i=t??"rows",{[i]:s,...o}=n;return{...o,rows:await this.transformResultRows(s)}}))}validateFieldSpecType(e){if(!So.includes(e))throw new Error(`Invalid field type "${e}". Allowed types are: ${So.join(", ")}`);return!0}toDriver(e,t){return e}fromDriver(e,t){return e}async close(){}};function ve(r,e,t={}){return{create(...n){return new class extends r{createIntrospector(i){return new e(i,t)}}(...n)}}}import{objectEach as Up,transformObject as $n,McpServer as Lp,SecretSchema as Qp,setPath as Xa,mark as Jp}from"bknd/utils";var Vn=class{_context=[];_enabled=!0;id=Math.random().toString(36).substr(2,9);last=0;constructor(e=!0){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(),n=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,n,...e),this.last=t,this}};var T=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}}},pe=class r extends Error{constructor(t,n,i){super(t);this.details=n;this.type=i}static with(t,n,i){throw new r(t,n,i)}toJSON(){return{type:this.type??"unknown",message:this.message,details:this.details}}};import{$console as Ee,mergeObject as qi}from"bknd/utils";import{HttpStatus as Uc}from"bknd/utils";import{getPath as Eo,invariant as Ot,isPlainObject as To}from"bknd/utils";function Z(r){return["string","number","boolean"].includes(typeof r)}function Oo(r){return[!0,!1,0,1].includes(r)}var Fi=class{constructor(e,t,n){this.key=e;this.valid=t;this.validate=n}expect};function R(r,e,t){return Ot(typeof r=="string","key must be a string"),Ot(r[0]==="$","key must start with '$'"),Ot(typeof e=="function","valid must be a function"),Ot(typeof t=="function","validate must be a function"),new Fi(r,e,t)}function _o(r,e){let t=r.find(n=>n.key===e);if(!t)throw new Error(`Expression does not exist: "${e}"`);return t}var Ro="$or";function Mi(r,e,t=[]){Ot(typeof r=="object","$query must be an object");let n=e.map(c=>c.key),i=Object.keys(r??{}),s=[Ro],o={};if(i.some(c=>c.startsWith("$")&&!s.includes(c)))throw new Error(`Invalid key '${i}'. Keys must not start with '$'.`);if(t.length>0&&i.some(c=>s.includes(c)))throw new Error(`Operand ${Ro} can only appear at the top level.`);function a(c,l,u=[]){if(_o(e,c).valid(l)===!1)throw new Error(`Given value at "${[...u,c].join(".")}" is invalid, got "${JSON.stringify(l)}"`)}for(let[c,l]of Object.entries(r))if(l!==void 0)if(c==="$or")Ot(To(l),"$or must be an object"),o.$or=Mi(l,e,[...t,c]);else if(Z(l))a("$eq",l,t),o[c]={$eq:l};else if(To(l)){let u=Object.keys(l).filter(p=>!n.includes(p));if(u.length===0){o[c]={};for(let[p,d]of Object.entries(l))a(p,d,[...t,c]),o[c][p]=d}else throw new Error(`Invalid key(s) at "${c}": ${u.join(", ")}. Expected expression key: ${n.join(", ")}.`)}else throw new Error(`Invalid value at "${[...t,c].join(".")}", got "${JSON.stringify(l)}"`);return o}function Co(r,e,t){let n=t.convert?Mi(r,e):r,i={$and:[],$or:[],keys:new Set},{$or:s,...o}=n;function a(c,l,u,p=[]){let d=_o(e,c);if(!d)throw new Error(`Expression does not exist: "${c}"`);if(!d.valid(l))throw new Error(`Invalid value at "${[...p,c].join(".")}", got "${JSON.stringify(l)}"`);return d.validate(l,u,t.exp_ctx)}for(let[c,l]of Object.entries(o))if(l!==void 0)for(let[u,p]of Object.entries(l)){let d=t.value_is_kv?c:Eo(t.object,c);i.$and.push(a(u,p,d,[c])),i.keys.add(c)}for(let[c,l]of Object.entries(s??{})){let u=t.value_is_kv?c:Eo(t.object,c);for(let[p,d]of Object.entries(l))i.$or.push(a(p,d,u,[c])),i.keys.add(c)}return i}function $c(r){let e={$and:void 0,$or:void 0};return e.$and=r.$and.every(t=>!!t),e.$or=r.$or.some(t=>!!t),!!e.$and||!!e.$or}function Yn(r){if(!r.some(e=>e.key==="$eq"))throw new Error("'$eq' expression is required");return{convert:e=>Mi(e,r),build:(e,t)=>Co(e,r,t),validate:(e,t)=>{let n=Co(e,r,t);return $c(n)},expressions:r,expressionKeys:r.map(e=>e.key)}}var Bc=[R("$eq",r=>Z(r),(r,e)=>r===e),R("$ne",r=>Z(r),(r,e)=>r!==e),R("$like",r=>Z(r),(r,e)=>{switch(typeof e){case"string":return e.includes(r);case"number":return e===Number(r);case"boolean":return e===!!r;default:return!1}}),R("$regex",r=>r instanceof RegExp?!0:typeof r=="string",(r,e)=>r instanceof RegExp?r.test(e):typeof r=="string"?new RegExp(r).test(e):!1),R("$isnull",r=>!0,(r,e)=>r?e===null:e!==null),R("$notnull",r=>!0,(r,e)=>r?e!==null:e===null),R("$in",r=>Array.isArray(r),(r,e)=>r.includes(e)),R("$notin",r=>Array.isArray(r),(r,e)=>!r.includes(e)),R("$gt",r=>typeof r=="number",(r,e)=>e>r),R("$gte",r=>typeof r=="number",(r,e)=>e>=r),R("$lt",r=>typeof r=="number",(r,e)=>e<r),R("$lte",r=>typeof r=="number",(r,e)=>e<=r),R("$between",r=>Array.isArray(r)&&r.length===2&&r.every(e=>typeof e=="number"),(r,e)=>r[0]<=e&&e<=r[1])],Po=Yn(Bc),ji=r=>Po.convert(r),Di=(r,e)=>Po.validate(r,{object:e,convert:!0});var Te=class extends T{constructor(t,n,i){super(`Permission "${t.name}" not granted`);this.permission=t;this.policy=n;this.description=i}name="PermissionsException";code=Uc.FORBIDDEN;toJSON(){return{...super.toJSON(),description:this.description,permission:this.permission.name,policy:this.policy?.toJSON()}}},Xn=class{constructor(e=[],t=[],n){this.permissions=e;this.roles=t;this.config=n;this.permissions=e,this.roles=t,this.config=n}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 n of t)this.registerPermission(n);return this}getUserRole(e){if(e&&typeof e.role=="string"){let t=this.roles?.find(n=>n.name===e?.role);if(t)return Ee.debug(`guard: role "${e.role}" found`),t}return Ee.debug("guard: role not found",{user:e}),this.getDefaultRole()}getDefaultRole(){return this.roles?.find(e=>e.is_default)}isEnabled(){return this.config?.enabled===!0}collect(e,t,n){let i=t&&"get"in t?t.get("auth")?.user:t,s={...n??{},...this.config?.context,user:i},o=this.permissionExists(e.name),a=this.getUserRole(i),c=a?.permissions.find(l=>l.permission.name===e.name);return{ctx:s,user:i,exists:o,role:a,rolePermission:c}}granted(e,t,n){if(!this.isEnabled())return;let{ctx:i,exists:s,role:o,rolePermission:a}=this.collect(e,t,n),c=Object.assign({},i);if(e.context&&(c=e.parseContext(c)),Ee.debug("guard: checking permission",{name:e.name,context:c}),!s)throw new Te(e,void 0,`Permission ${e.name} does not exist`);if(!o)throw new Te(e,void 0,"User has no role");if(!a){if(o.implicit_allow===!0){Ee.debug(`guard: role "${o.name}" has implicit allow, allowing`);return}throw new Te(e,void 0,`Role "${o.name}" does not have required permission`)}if(a?.policies.length>0){Ee.debug("guard: rolePermission has policies, checking");let l=a.effect==="allow";for(let u of a.policies){if(Ee.debug("guard: checking policy",{policy:u.toJSON(),ctx:c}),u.content.effect==="filter")continue;if(u.meetsCondition(c))if(Ee.debug("guard: policy meets condition"),u.content.effect==="deny"){Ee.debug("guard: policy is deny, setting allowed to false"),l=!1;break}else u.content.effect==="allow"&&(l=!0);else Ee.debug("guard: policy does not meet condition")}if(!l)throw new Te(e,void 0,"Policy condition unmet")}Ee.debug("guard allowing",{permission:e.name,role:o.name})}filters(e,t,n){if(!e.isFilterable())throw new Te(e,void 0,"Permission is not filterable");let{ctx:i,exists:s,role:o,user:a,rolePermission:c}=this.collect(e,t,n),l=Object.assign({user:a},i);e.context&&(l=e.parseContext(l,{coerceDropUnknown:!1}));let u=[],p=[];if(s&&o&&c&&c.policies.length>0)for(let m of c.policies)m.content.effect==="filter"&&m.meetsCondition(l)&&(p.push(m),u.push(m.getReplacedFilter(l)));let d=u.length>0?qi({},...u):void 0;return{filters:u,filter:d,policies:p,merge:m=>Lc(m??{},d??{}),matches:(m,y)=>{let v=Array.isArray(m)?m:[m];if(p.length>0){for(let w of p)for(let F of v)if(!w.meetsFilter(F,l)){if(y?.throwOnError)throw new Te(e,w,"Policy filter not met");return!1}}return!0}}}};function Lc(r,e){let t=ji(r),n=ji(e),i=qi(t,n);if("$or"in t&&t.$or){let s=t.$or,o=Object.keys(n);for(let a of o)a in s&&(i.$or[a]=qi(s[a],n[a]))}return i}var Ii=(r,e)=>typeof r=="string"?[1,"1","true"].includes(r):!!(r||e);function k(){try{return Ii(0)}catch{return!1}}function ln(){try{return"0.20.0"}catch{return"0.0.0"}}var Qc={cli_log_level:{key:"BKND_CLI_LOG_LEVEL",validate:r=>{if(typeof r=="string"&&["log","info","warn","error","debug"].includes(r.toLowerCase()))return r.toLowerCase()}},cli_create_ref:{key:"BKND_CLI_CREATE_REF",validate:r=>typeof r=="string"?r:void 0},cli_telemetry:{key:"BKND_CLI_TELEMETRY",validate:r=>{if(!(typeof r>"u"))return Ii(r,!0)}},modules_debug:{key:"BKND_MODULES_DEBUG",validate:Ii}},$i=(r,e,t)=>{try{let n=t?.source??process.env,i=Qc[r],s=n[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};import{$console as wl}from"bknd/utils";import{sql as Sl}from"kysely";import{HttpStatus as nt}from"bknd/utils";var Zn=class extends T{name="UnableToConnectException";code=nt.INTERNAL_SERVER_ERROR},W=class extends T{name="InvalidSearchParamsException";code=nt.UNPROCESSABLE_ENTITY},er=class extends T{name="TransformRetrieveFailedException";code=nt.UNPROCESSABLE_ENTITY},_=class r extends T{name="TransformPersistFailedException";code=nt.UNPROCESSABLE_ENTITY;static invalidType(e,t,n){let i=typeof n=="object"?JSON.stringify(n):n,s=`Property "${e}" must be of type "${t}", "${i}" of type "${typeof n}" given.`;return new r(s)}static required(e){return new r(`Property "${e}" is required`)}},tr=class extends T{constructor(t,n,i){console.error("InvalidFieldConfigException",{given:n,error:i.first()});super(`Invalid Field config given for field "${t.name}": ${i.firstToString()}`);this.given=n}name="InvalidFieldConfigException";code=nt.BAD_REQUEST},nr=class extends T{name="EntityNotDefinedException";code=nt.BAD_REQUEST;constructor(e){e?super(`Entity "${typeof e!="string"?e.name:e}" not defined`):super("Cannot find an entity that is undefined")}},ko=class extends T{name="EntityNotFoundException";code=nt.NOT_FOUND;constructor(e,t){super(`Entity "${typeof e!="string"?e.name:e}" with id "${t}" not found`)}};import{$console as Ao}from"bknd/utils";var Bi=class extends E{static slug="mutator-insert-before";validate(e){let{entity:t}=this.params;if(!t.isValidData(e,"create"))throw Ao.warn("MutatorInsertBefore.validate: invalid",{entity:t.name,data:e}),new ue("EntityData","invalid");return this.clone({entity:t,data:e})}},Ni=class extends E{static slug="mutator-insert-after"},Ui=class extends E{static slug="mutator-update-before";validate(e){let{entity:t,entityId:n}=this.params;if(!t.isValidData(e,"update"))throw Ao.warn("MutatorUpdateBefore.validate: invalid",{entity:t.name,entityId:n,data:e}),new ue("EntityData","invalid");return this.clone({entityId:n,entity:t,data:e})}},Li=class extends E{static slug="mutator-update-after"},Qi=class extends E{static slug="mutator-delete-before"},un=class extends E{static slug="mutator-delete-after"},_e={MutatorInsertBefore:Bi,MutatorInsertAfter:Ni,MutatorUpdateBefore:Ui,MutatorUpdateAfter:Li,MutatorDeleteBefore:Qi,MutatorDeleteAfter:un},Ji=class extends E{static slug="repository-find-one-before"},Ki=class extends E{static slug="repository-find-one-after"},zi=class extends E{static slug="repository-find-many-before";static another="one"},Hi=class extends E{static slug="repository-find-many-after"},_t={RepositoryFindOneBefore:Ji,RepositoryFindOneAfter:Ki,RepositoryFindManyBefore:zi,RepositoryFindManyAfter:Hi};var rr=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(n=>n.target.entity.name===e.name&&n.source.reference===t||n.source.entity.name===e.name&&n.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)}};import{omitKeys as Vc,s as Wi}from"bknd/utils";import{s as U,parse as Kc,InvalidSchemaError as zc,snakeToPascalWithSpaces as Hc}from"bknd/utils";var Wc=["create","read","update","delete"],Qy=["form","table","read","submit"],Gc=["create","read","update","delete","form","table","submit"];var Fo=!0,Mo=!1,P=U.strictObject({label:U.string(),description:U.string(),required:U.boolean({default:!1}),fillable:U.anyOf([U.boolean({title:"Boolean"}),U.array(U.string({enum:Wc}),{title:"Context",uniqueItems:!0})]),hidden:U.anyOf([U.boolean({title:"Boolean"}),U.array(U.string({enum:Gc}),{title:"Context",uniqueItems:!0})]),virtual:U.boolean(),default_value:U.any()}).partial(),C=class{_required;_type;name;type="field";config;constructor(e,t){this.name=e,this._type,this._required;try{this.config=Kc(this.getSchema(),t||{})}catch(n){throw n instanceof zc?new tr(this,t,n):n}}getType(){return this.type}schema(){return Object.freeze({name:this.name,type:"text",nullable:!0,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):Fo:this.config.fillable??Fo}isHidden(e){return Array.isArray(this.config.hidden)?e?this.config.hidden.includes(e):Mo:this.config.hidden??Mo}isRequired(){return this.config?.required??!1}isVirtual(){return this.config.virtual??!1}getLabel(e){return this.config.label?this.config.label:e?.fallback!==!1?Hc(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():!0}transformRetrieve(e){return e}async transformPersist(e,t,n){if(this.nullish(e)){if(this.isRequired()&&!this.hasDefault())throw _.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(U.any())}toType(){return{required:this.isRequired(),comment:this.getDescription(),type:"any"}}toJSON(){return{type:this.type,config:this.config}}};var Gi=Wi.strictObject({default_value:Wi.boolean(),...Vc(P.properties,["default_value"])}).partial(),Pt=class extends C{type="boolean";getSchema(){return Gi}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()?!1:this.hasDefault()?this.getDefault():null:typeof e=="string"?e==="1":!!e}async transformPersist(e,t,n){let i=await super.transformPersist(e,t,n);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 _.invalidType(this.name,"boolean",i);return i}toJsonSchema(){return this.toSchemaWrapIfRequired(Wi.boolean({default:this.getDefault()}))}toType(){return{...super.toType(),type:"boolean"}}};import{dayjs as jo,$console as Do,s as kt}from"bknd/utils";var Vi=kt.strictObject({type:kt.string({enum:["date","datetime","week"],default:"date"}),timezone:kt.string(),min_date:kt.string(),max_date:kt.string(),...P.properties}).partial(),rt=class extends C{type="date";getSchema(){return Vi}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,n]=e.split("-W").map(i=>Number.parseInt(i,10));return jo().year(t).week(n).toDate()}return new Date(e)}getValue(e,t){if(e===null||!e)return;let n=this.parseDateFromString(e);if(t==="submit")try{return n.toISOString()}catch{return}if(this.config.type==="week")try{return`${n.getFullYear()}-W${jo(n).week()}`}catch(i){Do.warn("DateField.getValue:week error",e,String(i));return}try{let s=new Date().getTimezoneOffset(),o=new Date(n.getTime()-s*6e4);return this.formatDate(o)}catch(i){Do.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,n){let i=await super.transformPersist(e,t,n);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(kt.string({default:this.getDefault()}))}toType(){return{...super.toType(),type:"Date | string"}}};import{omitKeys as Yc}from"bknd/utils";import{s as G}from"bknd/utils";var Yi=G.strictObject({default_value:G.string(),options:G.anyOf([G.object({type:G.literal("strings"),values:G.array(G.string())}),G.object({type:G.literal("objects"),values:G.array(G.object({label:G.string(),value:G.string()}))})]),...Yc(P.properties,["default_value"])}).partial(),At=class extends C{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 Yi}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(n=>n.value).includes(e)}getValue(e,t){if(!this.isValidValue(e))return this.hasDefault()?this.getDefault():null;switch(t){case"table":return this.getOptions().find(n=>n.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,n){let i=await super.transformPersist(e,t,n);if(this.nullish(i))return i;if(!this.isValidValue(i))throw new _(`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??{type:"strings",values:[]}).values?.map(n=>typeof n=="string"?n:n.value)??[];return this.toSchemaWrapIfRequired(G.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"}}};import{omitKeys as Xc}from"bknd/utils";import{s as qo}from"bknd/utils";var Xi=qo.strictObject({default_value:qo.any(),...Xc(P.properties,["default_value"])}).partial(),Ft=class extends C{type="json";getSchema(){return Xi}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!1}isSerialized(e){try{if(typeof e=="string")return e===JSON.stringify(JSON.parse(e))}catch{}return!1}isValid(e){return this.isSerializable(e)}getValue(e,t){switch(t){case"table":return e===null?null:JSON.stringify(e);case"submit":if(!e||typeof e=="string"&&e.length===0)return null;if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return e}}return e}async transformPersist(e,t,n){let i=await super.transformPersist(e,t,n);if(this.nullish(i))return i;if(!this.isSerializable(i))throw new _(`Field "${this.name}" must be serializable to JSON.`);return this.isSerialized(i)?i:JSON.stringify(i)}toType(){return{...super.toType(),type:"any"}}};import{Validator as Zc}from"@cfworker/json-schema";import{objectToJsLiteral as el}from"bknd/utils";import{s as Mt}from"bknd/utils";var Zi=Mt.strictObject({schema:Mt.any({type:"object"}),ui_schema:Mt.any({type:"object"}),default_from_schema:Mt.boolean(),...P.properties}).partial(),jt=class extends C{type="jsonschema";validator;constructor(e,t){super(e,t);let n=this.getJsonSchema();this.validator=new Zc(typeof n=="object"?JSON.parse(JSON.stringify(n)):{})}getSchema(){return Zi}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")?!0:this.validator.validate(e).valid:!1}getValue(e,t){switch(t){case"form":return e===null?"":e;case"table":return e===null?null:JSON.stringify(e);case"submit":break}return e}transformRetrieve(e){let t=super.transformRetrieve(e);if(t===null){if(this.config.default_from_schema)try{return Mt.fromSchema(this.getJsonSchema()).template()}catch{return null}else if(this.hasDefault())return this.getDefault()}return t}async transformPersist(e,t,n){let i=await super.transformPersist(e,t,n);if(this.nullish(i))return i;if(!this.isValid(i))throw new _(this.name,i);return!i||typeof i!="object"?this.getDefault():JSON.stringify(i)}toJsonSchema(){let e=this.getJsonSchema()??{type:"object"};return this.toSchemaWrapIfRequired(Mt.fromSchema({default:this.getDefault(),...e}))}toType(){return{...super.toType(),import:[{package:"json-schema-to-ts",name:"FromSchema"}],type:`FromSchema<${el(this.getJsonSchema(),2,1)}>`}}};import{s as Ue,omitKeys as tl}from"bknd/utils";var es=Ue.strictObject({default_value:Ue.number(),minimum:Ue.number(),maximum:Ue.number(),exclusiveMinimum:Ue.number(),exclusiveMaximum:Ue.number(),multipleOf:Ue.number(),...tl(P.properties,["default_value"])}).partial(),Dt=class extends C{type="number";getSchema(){return es}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,10)}return e}async transformPersist(e,t,n){let i=await super.transformPersist(e,t,n);if(!this.nullish(i)&&typeof i!="number")throw _.invalidType(this.name,"number",i);if(this.config.maximum&&i>this.config.maximum)throw new _(`Field "${this.name}" cannot be greater than ${this.config.maximum}`);if(this.config.minimum&&i<this.config.minimum)throw new _(`Field "${this.name}" cannot be less than ${this.config.minimum}`);return i}toJsonSchema(){return this.toSchemaWrapIfRequired(Ue.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 it={server:{default_port:1337,assets_path:"/"},data:{default_primary_field:"id"}};import{omitKeys as nl,uuidv7 as rl,s as pn}from"bknd/utils";var dn=["integer","uuid"],ts=pn.strictObject({format:pn.string({enum:dn,default:"integer"}),required:pn.boolean({default:!1}),...nl(P.properties,["required"])}).partial(),de=class extends C{type="primary";constructor(e=it.data.default_primary_field,t){super(e,{...t,fillable:!1,required:!1})}isRequired(){return!1}getSchema(){return ts}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:!0,nullable:!1})}getNewValue(){if(this.format==="uuid")return rl()}async transformPersist(e){throw new Error("PrimaryField: This function should not be called")}toJsonSchema(){return this.toSchemaWrapIfRequired(this.format==="integer"?pn.number({writeOnly:void 0}):pn.string({writeOnly:void 0}))}toType(){let e=this.format==="integer"?"number":"string";return{...super.toType(),required:!0,import:[{package:"kysely",name:"Generated"}],type:`Generated<${e}>`}}};import{omitKeys as il,s as oe}from"bknd/utils";var ns=oe.strictObject({default_value:oe.string(),minLength:oe.number(),maxLength:oe.number(),pattern:oe.string(),html_config:oe.partialObject({element:oe.string(),props:oe.record(oe.anyOf([oe.string({title:"String"}),oe.number({title:"Number"})]))}),...il(P.properties,["default_value"])}).partial(),Pe=class extends C{type="text";getSchema(){return ns}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,n){let i=await super.transformPersist(e,t,n);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 _(`Field "${this.name}" must be at most ${this.config.maxLength} character(s)`);if(this.config.minLength&&i?.length<this.config.minLength)throw new _(`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 _(`Field "${this.name}" must match the pattern ${this.config.pattern}`);return i}toJsonSchema(){return this.toSchemaWrapIfRequired(oe.string({default:this.getDefault(),minLength:this.config?.minLength,maxLength:this.config?.maxLength,pattern:this.config?.pattern}))}toType(){return{...super.toType(),type:"string"}}};var qt=class{constructor(e,t,n=!1,i){this.entity=e;this.fields=t;this.unique=n;this.name=i;if(t.length===0)throw new Error("Indices must contain at least one field");if(t.some(s=>!(s instanceof C)))throw new Error("All fields must be instances of Field");i||(this.name=[n?"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 Io={primary:{schema:ts,field:de},text:{schema:ns,field:Pe},number:{schema:es,field:Dt},boolean:{schema:Gi,field:Pt},date:{schema:Vi,field:rt},enum:{schema:Yi,field:At},json:{schema:Xi,field:Ft},jsonschema:{schema:Zi,field:jt}};import{$console as sl}from"bknd/utils";var ir=class r{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:!1}),t=await this.getIntrospector().getIndices(),n=[];for(let i of e)r.EXCLUDE_TABLES.includes(i.name)||i.name&&n.push({...i,indices:t.filter(s=>s.table===i.name)});return n}getIntrospectionFromEntity(e){let t=e.getFields(!1),n=this.em.getIndicesOf(e);return{name:e.name,isView:!1,columns:t.map(i=>({name:i.name,dataType:"TEXT",isNullable:!0,isAutoIncrementing:i instanceof de,hasDefaultValue:!1,comment:void 0})),indices:n.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)),n=[],i=s=>s.name;e.filter(s=>/bknd/.test(s.name)||s.isView?!1:!t.map(o=>o.name).includes(s.name)).forEach(s=>{n.push({name:s.name,isDrop:!0,isNew:!1,columns:{add:[],drop:[],change:[]},indices:{add:[],drop:[]}})});for(let s of t){let o=e.find(a=>a.name===s.name);if(!o)n.push({name:s.name,isNew:!0,columns:{add:s.columns.map(i),drop:[],change:[]},indices:{add:s.indices.map(i),drop:[]}});else{let a=s.columns.filter(m=>!o.columns.map(i).includes(m.name)),c=o.columns.filter(m=>!s.columns.map(i).includes(m.name)),l=[];for(let m of s.columns){let y=o.columns.find(w=>w.name===m.name),v=[];for(let[w,F]of Object.entries(m))y&&y[w]!==F&&v.push({attribute:w,prev:y[w],next:F});Object.keys(v).length>0&&l.push({name:m.name,changes:v})}let u=s.indices.filter(m=>!o.indices.map(y=>y.name).includes(m.name)),p=o.indices.filter(m=>!s.indices.map(y=>y.name).includes(m.name));[a,c,u,p].some(m=>m.length>0)&&n.push({name:s.name,isNew:!1,columns:{add:a.map(i),drop:c.map(i),change:[]},indices:{add:u.map(i),drop:p.map(i)}})}}return n}collectFieldSchemas(e,t){let n=[];if(t.length===0)return n;for(let i of t){let o=this.em.entity(e).getField(i).schema();o&&n.push(this.em.connection.getFieldSchema(o))}return n}async sync(e={force:!1,drop:!1}){let t=await this.getDiff(),n=[],i=this.em.connection.kysely.schema,s=[];for(let o of t){let a=this.collectFieldSchemas(o.name,o.columns.add),c=o.columns.drop,l=o.indices.drop;if(o.isDrop)e.drop&&s.push(i.dropTable(o.name));else if(o.isNew){let u=i.createTable(o.name);for(let p of a)u=u.addColumn(...p);s.push(u)}else{if(a.length>0)for(let u of a)s.push(i.alterTable(o.name).addColumn(...u));if(e.drop&&c.length>0)for(let u of c)s.push(i.alterTable(o.name).dropColumn(u))}for(let u of o.indices.add){let d=this.em.getIndicesOf(o.name).find(y=>y.name===u),m=i.createIndex(u).on(o.name).columns(d.fields.map(y=>y.name));d.unique&&(m=m.unique()),s.push(m)}if(e.drop)for(let u of l)s.push(i.dropIndex(u))}if(s.length>0){n.push(...s.map(o=>{let{sql:a,parameters:c}=o.compile();return{sql:a,parameters:c}})),sl.debug("[SchemaManager]",`${s.length} statements ${n.map(o=>o.sql).join(`; `)}`);try{await this.em.connection.executeQueries(...s)}catch(o){throw new Error(`Failed to execute batch: ${String(o)}`)}}return n}};import{snakeToPascalWithSpaces as ol,transformObject as al,$console as $o,s as st,parse as cl}from"bknd/utils";var sr=st.strictObject({name:st.string(),name_singular:st.string(),description:st.string(),sort_field:st.string({default:it.data.default_primary_field}),sort_dir:st.string({enum:["asc","desc"],default:"asc"}),primary_format:st.string({enum:dn})},{default:{}}).partial(),It=["regular","system","generated"],Bo=Symbol.for("bknd:entity"),V=class r{#e;#t;name;fields;config;data;type="regular";constructor(e,t,n,i){if(typeof e!="string"||e.length===0)throw new Error("Entity name must be a non-empty string");this.name=e,this.config=cl(sr,n||{});let s=t?.filter(o=>o instanceof de).length??0;if(s>1)throw new Error(`Entity "${e}" has more than one primary field`);this.fields=s===1?[]:[new de(void 0,{format:this.config.primary_format})],t&&t.forEach(o=>this.addField(o)),i&&(this.type=i),this[Bo]=!0}static isEntity(e){return e?e[Bo]===!0:!1}static create(e){return new r(e.name,e.fields,e.config,e.type)}getType(){return this.type}getSelect(e,t){return this.getFields().filter(n=>!n.isHidden(t??"read")).map(n=>e?`${e}.${n.name} as ${n.name}`:n.name)}getDefaultSort(){return{by:this.config.sort_field??"id",dir:this.config.sort_dir??"asc"}}getAliasedSelectFrom(e,t,n){let i=t??this.name;return this.getFields().filter(s=>!s.isVirtual()&&!s.isHidden(n??"read")&&e.includes(s.name)).map(s=>i?`${i}.${s.name} as ${s.name}`:s.name)}getFillableFields(e,t){return this.getFields(t).filter(n=>n.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 n=this.fields.findIndex(i=>i.name===e);if(n===-1)throw new Error(`Field "${e}" not found on entity "${this.name}"`);this.fields[n]=t}getPrimaryField(){return this.fields[0]}id(){return this.getPrimaryField()}get label(){return this.config.name??ol(this.name)}field(e){return this.getField(e)}hasField(e){let t=typeof e=="string"?e:e.name;return this.fields.findIndex(n=>n.name===t)!==-1}getFields(e=!1){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)){$o.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,n){if(typeof e!="object"&&n?.explain)throw new Error(`Entity "${this.name}" data must be an object`);let i=this.getFillableFields(t,!1);if(n?.ignoreUnknown!==!0){let s=i.map(c=>c.name),a=Object.keys(e).filter(c=>!s.includes(c));if(a.length>0&&n?.explain)throw new Error(`Entity "${this.name}" data must only contain known keys, unknown: "${a}"`)}for(let s of i)if(!s.isValid(e?.[s.name],t)){if($o.warn("invalid data given for",this.name,t,s.name,e[s.name]),n?.explain)throw new Error(`Field "${s.name}" has invalid data: "${e[s.name]}"`);return!1}return!0}toSchema(e){let t;switch(e?.context){case"create":case"update":t=this.getFillableFields(e.context);break;default:t=this.getFields(!0)}let n=Object.fromEntries(t.map(s=>[s.name,s])),i={type:"object",additionalProperties:!1,properties:al(n,s=>{let o=s.isFillable(e?.context);return{title:s.config.label,$comment:s.config.description,$field:s.type,readOnly:o?void 0:!0,...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 me(r){if(typeof r!="string")throw new Error(`Invalid key: ${r}`);return r}var ll=[R("$eq",r=>Z(r),(r,e,t)=>t(me(e),"=",r)),R("$ne",r=>Z(r),(r,e,t)=>t(me(e),"!=",r)),R("$gt",r=>Z(r),(r,e,t)=>t(me(e),">",r)),R("$gte",r=>Z(r),(r,e,t)=>t(me(e),">=",r)),R("$lt",r=>Z(r),(r,e,t)=>t(me(e),"<",r)),R("$lte",r=>Z(r),(r,e,t)=>t(me(e),"<=",r)),R("$isnull",r=>Oo(r),(r,e,t)=>t(me(e),r?"is":"is not",null)),R("$in",r=>Array.isArray(r),(r,e,t)=>t(me(e),"in",r)),R("$notin",r=>Array.isArray(r),(r,e,t)=>t(me(e),"not in",r)),R("$between",r=>Array.isArray(r)&&r.length===2,(r,e,t)=>t.between(me(e),r[0],r[1])),R("$like",r=>Z(r),(r,e,t)=>t(me(e),"like",String(r).replace(/\*/g,"%")))],or=Yn(ll),Yf=or.expressionKeys,ee=class{static addClause(e,t){return Object.keys(t).length===0?e:e.where(n=>{let i=or.build(t,{value_is_kv:!0,exp_ctx:n,convert:!0});return i.$or.length>0&&i.$and.length>0?n.and(i.$and).or(n.and(i.$or)):i.$or.length>0?n.or(i.$or):n.and(i.$and)})}static convert(e){return or.convert(e)}static getPropertyNames(e){let{keys:t}=or.build(e,{value_is_kv:!0,exp_ctx:()=>null,convert:!0});return Array.from(t)}};import{s as ar,parse as ul}from"bknd/utils";var ye=class{config;source;target;directions=["source","target"];static schema=ar.strictObject({mappedBy:ar.string().optional(),inversedBy:ar.string().optional(),required:ar.boolean().optional()});constructor(e,t,n={}){this.source=e,this.target=t;let i=this.constructor.schema;this.config=ul(i,n)}getReferenceQuery(e,t,n){return{}}helper(e){return new cr(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,n){let i=typeof e=="string"?e:e.name,s=this.ref(i),o=n.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,n){throw new Error("$set is not allowed")}async $create(e,t,n){throw new Error("$create is not allowed")}async $attach(e,t,n){throw new Error("$attach is not allowed")}async $detach(e,t,n){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,n){this.entity=e,this.cardinality=n,this.reference=t}toJSON(){return{entity:this.entity.name,cardinality:this.cardinality,name:this.reference}}};import{s as ot}from"bknd/utils";var pl=["cascade","set null","set default","restrict","no action"],rs=ot.strictObject({reference:ot.string(),target:ot.string(),target_field:ot.string({default:"id"}).optional(),target_field_type:ot.string({enum:["text","integer"],default:"integer"}).optional(),on_delete:ot.string({enum:pl,default:"set null"}).optional(),...P.properties}),M=class r extends C{type="relation";getSchema(){return rs}static create(e,t,n){let i=[t.reference??t.entity.name,t.entity.getPrimaryField().name].join("_");return new r(i,{...n,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(ot.number({$ref:`${this.config?.target}#/properties/${this.config?.target_field}`}))}toType(){let e=this.config.target_field_type==="integer"?"number":"string";return{...super.toType(),type:e}}};var j={OneToOne:"1:1",ManyToOne:"n:1",ManyToMany:"m:n",Polymorphic:"poly"};import{s as is}from"bknd/utils";var te=class r extends ye{connectionEntity;additionalFields=[];connectionTableMappedName;em;static schema=is.strictObject({connectionTable:is.string().optional(),connectionTableMappedName:is.string().optional(),...ye.schema.properties});constructor(e,t,n,i){let s=n?.connectionTable||r.defaultConnectionTable(e,t),o=new fe(e,e.name),a=new fe(t,t.name);super(o,a,n),this.connectionEntity=new V(s,i,void 0,"generated"),this.connectionTableMappedName=n?.connectionTableMappedName||s,this.additionalFields=i||[]}static defaultConnectionTable(e,t){return`${e.name}_${t.name}`}type(){return j.ManyToMany}isListableFor(){return!0}getField(e){let t=this.connectionEntity,n=t.fields.find(i=>i instanceof M&&i.target()===e.name);if(!n||!(n instanceof M))throw new Error(`Connection entity "${t.name}" does not have a relation to "${e.name}"`);return n}getQueryInfo(e){let t=this.other(e),n=this.connectionEntity,i=this.getField(e),s=this.getField(t.entity),o=`${e.name}.${e.getPrimaryField().name}`,a=`${n.name}.${i.name}`,c=`${n.name}.${s.name}`,l=[n.name,`${t.entity.name}.${t.entity.getPrimaryField().name}`,c],u=`${e.name}.${e.getPrimaryField().name}`;return{other:t,join:l,entityRef:o,selfRef:a,otherRef:c,groupBy:u}}getReferenceQuery(e,t){let{other:n,otherRef:i}=this.getQueryInfo(e);return{where:{[i]:t},join:[n.reference]}}buildJoin(e,t){let{other:n,join:i,entityRef:s,selfRef:o,groupBy:a}=this.getQueryInfo(e);return t.innerJoin(n.entity.name,s,o).innerJoin(...i).groupBy(a)}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 n=5,{other:i,join:s,entityRef:o,selfRef:a}=this.getQueryInfo(e),c=this.connectionEntity.fields.filter(l=>!(l instanceof M||l instanceof de));return l=>l.selectFrom(i.entity.name).select(u=>{let p=[];if(c.length>0){let d=this.connectionEntity.name;p.push(t(Object.fromEntries(c.map(m=>[m.name,u.ref(`${d}.${m.name}`)]))).as(this.connectionTableMappedName))}return p}).whereRef(o,"=",a).innerJoin(...s).limit(n)}initialize(e){this.em=e;let t=M.create(this,this.source),n=M.create(this,this.target);e.hasEntity(this.connectionEntity)?(this.connectionEntity.hasField(t)||this.connectionEntity.addField(t),this.connectionEntity.hasField(n)||this.connectionEntity.addField(n)):(this.connectionEntity.addField(t),this.connectionEntity.addField(n),e.addEntity(this.connectionEntity))}getName(){return[...Array.from(new Set([this.type().replace(":",""),this.connectionEntity.name,this.connectionTableMappedName].filter(Boolean)))].join("_")}};import{snakeToPascalWithSpaces as dl,s as mn}from"bknd/utils";var he=class r extends ye{fieldConfig;static DEFAULTS={with_limit:5};static schema=mn.strictObject({sourceCardinality:mn.number().optional(),with_limit:mn.number({default:r.DEFAULTS.with_limit}).optional(),fieldConfig:mn.object({label:mn.string()}).optional(),...ye.schema.properties});constructor(e,t,n={}){let i=n.mappedBy||t.name,s=n.inversedBy||e.name,o=typeof n.sourceCardinality=="number"&&n.sourceCardinality>0?n.sourceCardinality:void 0,a=new fe(e,s,o),c=new fe(t,i,1);super(a,c,n),this.fieldConfig=n.fieldConfig??{}}type(){return j.ManyToOne}initialize(e){let t=dl(this.target.reference),n=M.create(this,this.target,{label:t,...this.fieldConfig});this.source.entity.field(n.name)||this.source.entity.addField(M.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 M))throw new Error(`Field "${this.target.reference}_${e}" not found on entity "${this.source.entity.name}"`);return t}queryInfo(e,t){let n=this.source.reference===t?"source":"target",i=this[n],s=this[n==="source"?"target":"source"],o,a,c;n==="source"?(o=this.source.reference,a=`${o}.${this.getField().name}`,c=`${e.name}.${i.entity.getPrimaryField().name}`):(o=this.target.reference,a=`${o}.${e.getPrimaryField().name}`,c=`${e.name}.${this.getField().name}`);let l=`${e.name}.${e.getPrimaryField().name}`;return{other:s,self:i,relationRef:o,entityRef:a,otherRef:c,groupBy:l}}getReferenceQuery(e,t,n){let i=this.source.reference===n?"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,n){let{self:i,entityRef:s,otherRef:o,groupBy:a}=this.queryInfo(e,n);return t.innerJoin(i.entity.name,s,o).groupBy(a)}buildWith(e,t){let{self:n,entityRef:i,otherRef:s,relationRef:o}=this.queryInfo(e,t);return a=>a.selectFrom(`${n.entity.name} as ${o}`).whereRef(i,"=",s).$if(n.cardinality===1,c=>c.limit(1))}async $set(e,t,n){if(typeof n!="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 a=o.local_field,c=this.getField(),l=n[Object.keys(n)[0]];if(!a||!(c instanceof M))throw new Error(`Cannot perform $set for relation "${t}"`);if(l===null&&!c.isRequired())return[a,null];if(!(await e.repository(c.target()).exists({[c.targetField()]:l})).data.exists){let p=c.targetField();throw new Error(`Cannot connect "${i.name}.${t}" to "${c.target()}.${p}" = "${l}": not found.`)}return[a,l]}};var at=class extends he{constructor(e,t,n){let{mappedBy:i,inversedBy:s,required:o}=n||{};super(e,t,{mappedBy:i,inversedBy:s,sourceCardinality:1,required:o,with_limit:1})}type(){return j.OneToOne}isListableFor(){return!1}async $set(e,t,n){throw new Error("$set is not allowed")}async $create(e,t,n){if(n===null||typeof n!="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(),a=o.primary,c=o.local_field;if(!o.$create||!a||!c)throw new Error(`Cannot perform $create for relation "${t}"`);try{let{data:l}=await e.mutator(i).insertOne(n),u=l[a];return[c,u]}catch{throw new Error(`Error performing $create on "${i.name}".`)}}};import{s as No}from"bknd/utils";var Le=class extends ye{static schema=No.strictObject({targetCardinality:No.number().optional(),...ye.schema.properties});constructor(e,t,n={}){let i=n.mappedBy||t.name,s=n.inversedBy||e.name,o=typeof n.targetC