@luminix/core 0.3.5 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core.js +1 -1
- package/package.json +2 -2
- package/dist/core.cjs +0 -4
package/dist/core.js
CHANGED
package/package.json
CHANGED
package/dist/core.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty;var re=(a,t,e)=>t in a?se(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var p=(a,t,e)=>re(a,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("@luminix/support");class ie{constructor(t,e,i){p(this,"_user");this.config=t,this.model=e,this.route=i}attempt(t,e=!1,i){const s=document.createElement("form");s.method="post",s.action=this.route.url("login"),s.style.display="none";const d=this.config.get("auth.csrf");if(typeof d=="string"){const l=document.createElement("input");l.type="hidden",l.name="_token",l.value=d,s.appendChild(l)}const y=document.createElement("input");y.type="email",y.name="email",y.value=t.email,s.appendChild(y);const c=document.createElement("input");if(c.type="password",c.name="password",c.value=t.password,s.appendChild(c),e){const l=document.createElement("input");l.type="checkbox",l.name="remember",l.value="1",l.checked=!0,s.appendChild(l)}i&&s.addEventListener("submit",i),document.body.appendChild(s),s.submit()}check(){return!!this.config.get("auth.user")}logout(t){const e=document.createElement("form");e.method="post",e.action=this.route.url("logout"),e.style.display="none";const i=this.config.get("auth.csrf");if(typeof i=="string"){const s=document.createElement("input");s.type="hidden",s.name="_token",s.value=i,e.appendChild(s)}document.body.appendChild(e),t&&e.addEventListener("submit",t),e.submit()}user(){if(!this._user){const t=this.model.make("user"),e=this.config.get("auth.user");if(!e)return;this._user=new t(e)}return this._user}id(){var t;return((t=this.user())==null?void 0:t.getKey())||null}}class ne{constructor(){p(this,"bags");const t={};document.querySelectorAll('#luminix-embed [id^="luminix-error"]').forEach(i=>{const d=i.id.replace("luminix-error::","");t[d]=n.reader(d,"error")}),this.bags={default:new n.PropertyBag(t)}}bag(t="default"){return this.bags[t]||(this.bags[t]=new n.PropertyBag({})),this.bags[t]}add(t,e,i="default"){this.bag(i).set(t,e)}set(t,e="default"){this.bag(e).set(".",t)}all(t="default"){return this.bag(t).all()}get(t,e="default"){return this.bag(e).get(t,null)}clear(t="default"){this.bag(t).set(".",{})}}class oe{constructor(t){this._debug=t}emergency(...t){this._debug&&console.error(...t)}alert(...t){this._debug&&console.error(...t)}critical(...t){this._debug&&console.error(...t)}error(...t){this._debug&&console.error(...t)}warning(...t){this._debug&&console.warn(...t)}notice(...t){this._debug&&console.info(...t)}info(...t){this._debug&&console.info(...t)}debug(...t){this._debug&&console.debug(...t)}}var R,j;class ae extends(j=Error,R=Symbol.toStringTag,j){constructor(e){super(`[Luminix] Model "${e}" does not have a primary key`);p(this,R,"ModelWithoutPrimaryKeyException")}}class ue extends n.EventSource{constructor(e,i,s={}){super();p(this,"bag");this.services=e,this.abstract=i,this.bag=new n.PropertyBag(s),this.bag.on("change",()=>{this.emit("change",{data:this.bag,source:this})})}lock(e){this.bag.lock(e)}whereBetween(e,i){return this.where(e,"between",i)}whereNotBetween(e,i){return this.where(e,"notBetween",i)}whereNull(e){return this.where(e,"null",null)}whereNotNull(e){return this.where(e,"notNull",null)}limit(e){return this.bag.set("per_page",e),this}where(e,i,s){if(this.bag.has("where")||this.bag.set("where",{}),typeof e=="function")return e(this)||this;if(typeof s>"u")return this.bag.set(`where.${e}`,i),this;if(typeof i!="string")throw new Error(`Invalid operator ${i} provided for where clause.`);const y={"=":"","!=":"notEquals",">":"greaterThan",">=":"greaterThanOrEquals","<":"lessThan","<=":"lessThanOrEquals"}[i]||i;return this.bag.set(`where.${e}:${y}`,s),this}with(e){const i=this.bag.get("with",[]);return(Array.isArray(e)?e:[e]).forEach(d=>{i.includes(d)||i.push(d)}),this.bag.set("with",i),this}withOnly(e){return this.bag.set("with",Array.isArray(e)?e:[e]),this}without(e){const i=this.bag.get("with",[]);return(Array.isArray(e)?e:[e]).forEach(d=>{i.includes(d)&&i.splice(i.indexOf(d),1)}),this.bag.set("with",i),this}orderBy(e,i="asc"){return this.bag.set("order_by",`${e}:${i}`),this}searchBy(e){return this.bag.set("q",e),this}minified(){return this.bag.set("minified",!0),this}unset(e){return this.bag.delete(e),this}include(e){for(const[i,s]of e.entries())this.bag.set(i,s);return this}async exec(e=1,i){try{this.bag.set("page",e),this.emit("submit",{data:this.bag,source:this});const s=await this.services.route.call(`luminix.${this.abstract}.index`,c=>c.withQueryParameters(this.bag.all())),d=this.services.model.make(this.abstract),y=new n.Collection(s.json("data").map(c=>{const l=new d(c);return l.exists=!0,this.services.model.emit("fetch",{class:this.abstract,model:l,source:this.services.model}),l}));if(i){const[c]=i.split("?");return{...s.json(),data:y,links:{first:`${c}?${n.Query.merge(i,s.json("links").first).toString()}`,last:`${c}?${n.Query.merge(i,s.json("links").last).toString()}`,next:s.json("links").next&&`${c}?${n.Query.merge(i,s.json("links").next??"").toString()}`,prev:s.json("links").prev&&`${c}?${n.Query.merge(i,s.json("links").prev??"").toString()}`},meta:{...s.json("meta"),links:s.json("meta").links.map(l=>({...l,url:l.url&&`${c}?${n.Query.merge(i,l.url).toString()}`}))}}}return{...s.json(),data:y}}catch(s){throw this.emit("error",{error:s,source:this}),s}}async get(e=1,i){const s=await this.exec(e,i);return this.emit("success",{response:s,items:s.data,source:this}),s}async first(){const e=await this.limit(1).exec(1);return this.emit("success",{response:e,items:e.data.first(),source:this}),e.data.first()}async find(e){const i=this.services.model.schema(this.abstract).primaryKey;if(!i)throw new ae(this.abstract);const s=await this.where(i,e).limit(1).exec(1);return this.emit("success",{response:s,items:s.data.sole(),source:this}),s.data.sole()}async all(){const e=this.services.config.get("luminix.backend.api.max_per_page",150),i=await this.limit(e).exec(1),s=i.meta.last_page;if(s===1)return i.data;const d=Array.from({length:s-1},(l,r)=>r+2),y=await Promise.all(d.map(l=>this.limit(e).exec(l))),c=new n.Collection(y.reduce((l,r)=>(l.push(...r.data),l),i.data).all());return this.emit("success",{response:{...i,data:c},items:c,source:this}),c}}var O,A;class m extends(A=TypeError,O=Symbol.toStringTag,A){constructor(e,i="Model"){super(`[Luminix] "${e}" expects ${i}`);p(this,O,"NotModelException")}}var N,k;class le extends(k=Error,N=Symbol.toStringTag,k){constructor(e,i,s,d){super(`[Luminix] Could not determine inverse relation for "${i}" in model "${e}". Please specify a relation in model "${s}" of type ${d} that points back to "${e}".`);p(this,N,"NoInverseRelationException")}}var q,K;class he extends(K=Error,q=Symbol.toStringTag,K){constructor(e){super(`[Luminix] Relation "${e}" is not supported`);p(this,q,"UnsupportedRelationException")}}class S{constructor(t,e,i,s=null){p(this,"unsubscribeQuery",null);if(this.services=t,this.meta=e,this.parent=i,this.items=s,s!==null&&!n.Obj.isModel(s)&&!(s instanceof n.Collection&&s.every(n.Obj.isModel)))throw new m("Relation.constructor()","Model, Collection<Model> or null")}make(t){const e=this.getRelated();if(t===null||typeof t>"u"){this.set(null);return}if(this.isSingle()){if(typeof t!="object"||Array.isArray(t))throw new TypeError("Relation.make() expects an object");this.set(new e(t))}if(this.isMultiple()){if(!Array.isArray(t))throw new TypeError("Relation.make() expects an array");this.set(new n.Collection(t.map(i=>new e(i))))}}guessInverseRelation(){const{relations:t}=this.getRelated().getSchema(),e=this.getType(),i=this.services.model.guessInverseRelation({HasOne:["BelongsTo"],HasMany:["BelongsTo"],BelongsTo:["HasOne","HasMany"],BelongsToMany:["BelongsToMany"],MorphTo:["MorphMany","MorphOne"],MorphOne:["MorphTo"],MorphMany:["MorphTo"],MorphToMany:["MorphToMany"]},this.parent,e,this.getRelated());if(!(e in i))throw new he(e);for(const s in t){const d=t[s];if((d.model===this.parent.getType()||["MorphOne","MorphMany"].includes(e))&&i[e].includes(d.type))return s}throw new le(this.parent.getType(),e,this.getRelated().getSchemaName(),i[e].join(" or "))}set(t){if(t!==null&&!n.Obj.isModel(t)&&!(t instanceof n.Collection&&t.every(n.Obj.isModel)))throw new m("Relation.set()","Model, Collection<Model> or null");!this.items||n.Obj.isModel(this.items)?this.items=t:t instanceof n.Collection&&this.items.splice(0,this.items.count(),...t)}getForeignKey(){return this.meta.foreignKey}getName(){return this.meta.name}getType(){return this.meta.type}getModel(){return this.meta.model}getRelated(){return this.services.model.make(this.meta.model)}query(){const t=this.getRelated().query();return this.unsubscribeQuery&&this.unsubscribeQuery(),this.unsubscribeQuery=t.on("success",e=>{this.items=e.items}),t}isLoaded(){return this.items!==null}getLoadedItems(){return this.items}isSingle(){return n.Obj.isModel(this.items)}isMultiple(){return this.items instanceof n.Collection}getParent(){return this.parent}where(...t){return this.query().where(...t)}whereNull(t){return this.query().whereNull(t)}whereNotNull(t){return this.query().whereNotNull(t)}whereBetween(t,e){return this.query().whereBetween(t,e)}whereNotBetween(t,e){return this.query().whereNotBetween(t,e)}orderBy(t,e="asc"){return this.query().orderBy(t,e)}searchBy(t){return this.query().searchBy(t)}minified(){return this.query().minified()}limit(t){return this.query().limit(t)}}var C,B;class M extends(B=Error,C=Symbol.toStringTag,B){constructor(e){super(`[Luminix] Expected ${e} to be reducible.`);p(this,C,"NotReducibleException")}}var P,Q;class ce extends(Q=Error,P=Symbol.toStringTag,Q){constructor(){super("[Luminix] Method not implemented.");p(this,P,"MethodNotImplementedException")}}var I,D;class Y extends(D=Error,I=Symbol.toStringTag,D){constructor(e,i){super(`[Luminix] Model "${e}" must be persisted before calling "${i}"`);p(this,I,"ModelNotPersistedException")}}function de(a,t,e,i,s){var d,y,c;return c=class extends(y=n.EventSource,d=Symbol.toStringTag,y){constructor(r={}){super();p(this,"_attributes",new n.PropertyBag({}));p(this,"_original",{});p(this,"_relations",{});p(this,"_changedKeys",[]);p(this,"exists",!1);p(this,"wasRecentlyCreated",!1);p(this,d,n.Str.studly(s));this.makeRelations(),this.makeAttributes(r)}cast(r,o){return r==null||!o?r:["boolean","bool"].includes(o)?!!r:["date","datetime","immutable_date","immutable_datetime"].includes(o)&&typeof r=="string"?new Date(r):["float","double","integer","int"].includes(o)||o.startsWith("decimal:")?Number(r):r}mutate(r,o){return r==null||!o?r:["boolean","bool"].includes(o)?!!r:["date","datetime","immutable_date","immutable_datetime"].includes(o)&&r instanceof Date?r.toISOString():["float","double","integer","int"].includes(o)||o.startsWith("decimal:")?Number(r):r}makeRelations(){const{relations:r}=e.schema(s);if(this._relations={},!r)return;const o=e.getRelationConstructors(s);Object.entries(r).forEach(([u,h])=>{const{type:g}=h,f=g in o?o[g]:S;this._relations[u]=new f({model:e,route:i},{name:u,...h},this,null)})}makeAttributes(r){const{relations:o}=e.schema(s),u=Object.keys(o||{}),h=n.Obj.omit(r,...u);if(this.fillable.filter(g=>!(g in h)).forEach(g=>{h[g]=null}),o&&Object.keys(o).forEach(g=>{this.relation(n.Str.camel(g)).make(r[g])}),!this.validateJsonObject(h)){if(a.get("app.env","production")==="production")throw new TypeError(`[Luminix] Invalid attributes for model "${s}"`);t.warning(`Invalid attributes for model "${s}".
|
|
2
|
-
This will throw an error in production.`,{attributes:r,abstract:s})}this._attributes.set(".",h),this._original=h,this._changedKeys.splice(0,this._changedKeys.length)}makePrimaryKeyReplacer(){return{[this.getKeyName()]:this.getKey()}}dispatchChangeEvent(r){this.emit("change",{value:r,source:this})}dispatchCreateEvent(r){this.emit("create",{value:r,source:this}),e.emit("create",{class:s,model:this,source:e})}dispatchUpdateEvent(r){this.emit("update",{value:r,source:this}),e.emit("update",{class:s,model:this,source:e})}dispatchSaveEvent(){this.emit("save",{value:this.diff(),source:this}),e.emit("save",{class:s,model:this,source:e})}dispatchDeleteEvent(r=!1){this.emit("delete",{force:r,[this.getKeyName()]:this.getKey(),source:this}),e.emit("delete",{class:s,model:this,source:e,force:r})}dispatchRestoreEvent(){this.emit("restore",{value:this.attributes,source:this}),e.emit("restore",{class:s,model:this,source:e})}dispatchErrorEvent(r,o){this.emit("error",{error:r,operation:o,source:this}),e.emit("error",{class:s,model:this,source:e,error:r,operation:o})}updateChangedKeys(r){const o=(u,h)=>typeof u=="object"&&u!==null?n.Obj.isEqual(u,h):u==h;!this._changedKeys.includes(r)&&!o(n.Obj.get(this._original,r),this._attributes.get(r))?this._changedKeys.push(r):this._changedKeys.includes(r)&&o(n.Obj.get(this._original,r),this._attributes.get(r))&&this._changedKeys.splice(this._changedKeys.indexOf(r),1)}validateJsonObject(r){return typeof r!="object"||r===null?!1:Object.entries(r).every(([,o])=>["boolean","number","string"].includes(typeof o)||o===null||this.validateJsonObject(o)||Array.isArray(o)&&o.every(u=>this.validateJsonObject(u)))}get attributes(){return this._attributes.all()}get original(){return this._original}get relations(){return this._relations}get fillable(){return e.schema(s).fillable}get primaryKey(){return e.schema(s).primaryKey}get timestamps(){return e.schema(s).timestamps}get casts(){return{...e.schema(s).casts,...this.timestamps?{created_at:"datetime",updated_at:"datetime"}:{}}}get isDirty(){return this._changedKeys.length>0}getAttribute(r){let o=this._attributes.get(r,null);r in this.casts&&(o=this.cast(o,this.casts[r]));const u=e[`model${n.Str.studly(s)}Get${n.Str.studly(r)}Attribute`];if(typeof u!="function")throw new M("ModelFacade");return u.bind(e)(o,this)}setAttribute(r,o){const u=e[`model${n.Str.studly(s)}Set${n.Str.studly(r)}Attribute`];if(typeof u!="function")throw new M("ModelFacade");const h=u.bind(e)(this.mutate(o,this.casts[r]),this);if(!this.validateJsonObject({[r]:h})){if(a.get("app.env","production")==="production")throw new TypeError(`[Luminix] Attribute "${r}" in model "${s}" must be a boolean, number, string or null`);t.warning(`Invalid type for attribute "${r}" in model "${s}" after mutation.
|
|
3
|
-
This will throw an error in production.`,{key:r,value:o,mutated:h,cast:this.casts[r],item:this.toJson()});return}this._attributes.set(r,h),this.updateChangedKeys(r),this.dispatchChangeEvent({[r]:h})}getKey(){return this.getAttribute(this.primaryKey)}getKeyName(){return this.primaryKey}fill(r){const o=n.Obj.pick(r,...this.fillable),u=Object.entries(o).reduce((h,[g,f])=>{const w=e[`model${n.Str.studly(s)}Set${n.Str.studly(g)}Attribute`];if(typeof w!="function")throw new M("ModelFacade");return h[g]=w.bind(e)(this.mutate(f,this.casts[g]),this),h},{});if(!this.validateJsonObject(u)){if(a.get("app.env","production")==="production")throw new TypeError(`[Luminix] Invalid attributes for model "${s}"`);t.warning(`Invalid attributes for model "${s}" after mutation.
|
|
4
|
-
This will throw an error in production.`,{attributes:r,mutatedAttributes:u,item:this.toJson(),casts:this.casts});return}this._attributes.merge(".",u),Object.keys(u).forEach(h=>this.updateChangedKeys(h)),this.dispatchChangeEvent(u)}dump(){t.info({...this.toJson(),[Symbol.toStringTag]:n.Str.studly(s)})}toJson(){const r=Object.entries(this.relations).reduce((u,[h,g])=>(g.isLoaded()&&(g.isSingle()?u[n.Str.snake(h)]=g.getLoadedItems().toJson():g.isMultiple()&&(u[n.Str.snake(h)]=g.getLoadedItems().map(f=>f.toJson()).all())),u),{}),o=e[`model${n.Str.studly(s)}Json`];if(typeof o!="function")throw new M("ModelFacade");return o.bind(e)({...this.attributes,...r},this)}diff(){return this._changedKeys.reduce((r,o)=>(r[o]=this._attributes.get(o),r),{})}getType(){return s}relation(r){if(r===n.Str.camel(r))return this.relations[n.Str.snake(r)]}getErrorBag(r){return`${this.exists?`${s}[${this.getKey()}].`:`${s}.`}${r}`}getRouteForSave(){return this.exists?[`luminix.${s}.update`,this.makePrimaryKeyReplacer()]:`luminix.${s}.store`}getRouteForUpdate(){return[`luminix.${s}.update`,this.makePrimaryKeyReplacer()]}getRouteForDelete(){return[`luminix.${s}.destroy`,this.makePrimaryKeyReplacer()]}getRouteForRefresh(){return[`luminix.${s}.show`,this.makePrimaryKeyReplacer()]}getLabel(){const{labeledBy:r}=e.schema(s);return this.getAttribute(r)}async refresh(r){if(!this.exists)throw new Y(s,"refresh");const o=await i.call(this.getRouteForRefresh(),r,this.getErrorBag("fetch"));this.makeAttributes(o.json())}async save(r={},o){try{const{additionalPayload:u={},sendsOnlyModifiedFields:h=!0}=r,g=this.exists,f={...n.Obj.pick(h&&g?this.diff():this.attributes,...this.fillable),...u};if(n.Obj.isEmpty(f))return;const w=await i.call(this.getRouteForSave(),T=>o?o(T.withData(f)):T.withData(f),this.getErrorBag(g?"update":"store"));if(w.successful())return this.makeAttributes(w.json()),this.exists=!0,this.dispatchSaveEvent(),g?this.dispatchUpdateEvent(w.json()):(this.wasRecentlyCreated=!0,this.dispatchCreateEvent(w.json())),w;throw w}catch(u){throw this.dispatchErrorEvent(u,"save"),u}}async push(){throw new ce}async delete(){try{const r=await i.call(this.getRouteForDelete(),void 0,this.getErrorBag("delete"));if(r.noContent())return this.dispatchDeleteEvent(),r;throw r}catch(r){throw this.dispatchErrorEvent(r,"delete"),r}}async update(r,o){try{const u=await i.call(this.getRouteForUpdate(),h=>o?o(h.withData(r)):h.withData(r),this.getErrorBag("update"));if(u.ok()){this.makeAttributes(u.json()),this.dispatchUpdateEvent(u.json());return}throw u}catch(u){throw this.dispatchErrorEvent(u,"save"),u}}async forceDelete(){try{const r=await i.call(this.getRouteForDelete(),o=>o.withQueryParameters({force:!0}),this.getErrorBag("forceDelete"));if(r.noContent())return this.dispatchDeleteEvent(!0),r;throw r}catch(r){throw this.dispatchErrorEvent(r,"forceDelete"),r}}async restore(){try{const r=await i.call(this.getRouteForUpdate(),o=>o.withQueryParameters({restore:!0}),this.getErrorBag("restore"));if(r.ok())return this.dispatchRestoreEvent(),r;throw r}catch(r){throw this.dispatchErrorEvent(r,"restore"),r}}static getSchemaName(){return s}static getSchema(){return e.schema(s)}static query(){return new ue({config:a,route:i,model:e},s)}static where(...r){return this.query().where(...r)}static whereNull(r){return this.query().whereNull(r)}static whereNotNull(r){return this.query().whereNotNull(r)}static whereBetween(r,o){return this.query().whereBetween(r,o)}static whereNotBetween(r,o){return this.query().whereNotBetween(r,o)}static orderBy(r,o="asc"){return this.query().orderBy(r,o)}static searchBy(r){return this.query().searchBy(r)}static minified(){return this.query().minified()}static limit(r){return this.query().limit(r)}static get(r=1,o){return this.query().get(r,o)}static find(r){return this.query().find(r)}static first(){return this.query().first()}static async create(r){const o=e.make(s),u=new o;return u.fill(r),await u.save(),u}static async update(r,o){const u=e.make(s),h=new u({id:r});return h.fill(o),h.exists=!0,await h.save(),h}static delete(r){if(Array.isArray(r))return i.call(`luminix.${s}.destroyMany`,h=>h.withQueryParameters({ids:r}),`${s}.deleteMany`);const o=e.make(s);return new o({id:r}).delete()}static async restore(r){if(Array.isArray(r))return i.call(`luminix.${s}.restoreMany`,h=>h.withData({ids:r}),`${s}.restoreMany`);const o=e.make(s);return new o({id:r}).restore()}static forceDelete(r){if(Array.isArray(r))return i.call(`luminix.${s}.destroyMany`,h=>h.withQueryParameters({ids:r,force:!0}),`${s}.forceDeleteMany`);const o=e.make(s);return new o({id:r}).forceDelete()}static singular(){return e.schema(s).displayName.singular}static plural(){return e.schema(s).displayName.plural}},p(c,"name",n.Str.studly(s)),c}function pe(a,t,e){var i,s;return class extends(s=e,i=Symbol.toStringTag,s){constructor(y={}){super(y);p(this,i,n.Str.studly(t));return new Proxy(this,{get:(c,l)=>{if(l==="__isModel")return!0;if(Reflect.has(c,l)||typeof l!="string")return Reflect.get(c,l);if(Object.keys(c.attributes).includes(l))return c.getAttribute(l);if(Object.keys(c.relations).includes(l))return c.relations[l].getLoadedItems();if(l.endsWith("Relation")&&Object.keys(c.relations).includes(n.Str.snake(l.slice(0,-8))))return()=>c.relation(l.slice(0,-8));if(a.hasReducer(`model${n.Str.studly(c.getType())}Get${n.Str.studly(l)}Attribute`)){const r=a[`model${n.Str.studly(c.getType())}Get${n.Str.studly(l)}Attribute`];if(typeof r!="function")throw new M("ModelFacade");return r.bind(a)(void 0,c)}return Reflect.get(c,l)},set:(c,l,r)=>l in c&&typeof c[l]!="function"?Reflect.set(c,l,r):(c.setAttribute(n.Str.snake(l),r),!0)})}}}var H,L;class _ extends(L=Error,H=Symbol.toStringTag,L){constructor(e){super(`[Luminix] Model "${e}" not found`);p(this,H,"ModelNotFoundException")}}var F,J;class x extends(J=TypeError,F=Symbol.toStringTag,J){constructor(e,i,s){super(`[Luminix] "${e}" expects a related model of type "${i}". Received "${s}" instead.`);p(this,F,"ModelInvalidRelatedTypeException")}}class Z extends S{constructor(t,e,i,s=null){if(!n.Obj.isModel(s)&&s!==null)throw new m("BelongsTo.constructor()","Model or null");super(t,e,i,s),this.services=t,this.meta=e,this.parent=i,this.items=s}isSingle(){return!0}isMultiple(){return!1}query(){const t=super.query(),e=this.guessInverseRelation();return t.where(e,this.parent.getKey()),t.lock(`where.${e}`),t}get(){return this.query().first()}async associate(t){if(!n.Obj.isModel(t))throw new m("BelongsTo.associate()");if(t.getType()!==this.getRelated().getSchemaName())throw new x("BelongsTo.associate()",this.getRelated().getSchemaName(),t.getType());if(!t.exists)throw new Y(this.getRelated().getSchemaName(),"save");return this.parent.update({[this.getForeignKey()]:t.getKey()})}dissociate(){return this.parent.update({[this.getForeignKey()]:null})}}class ee extends S{constructor(t,e,i,s=null){if(s!==null&&!(s instanceof n.Collection&&s.every(n.Obj.isModel)))throw new m("BelongsToMany.constructor()","Collection<Model> or null");super(t,e,i,s),this.services=t,this.meta=e,this.parent=i,this.items=s}isSingle(){return!1}isMultiple(){return!0}query(){const t=super.query(),e=this.guessInverseRelation();return t.where(e,this.parent.getKey()),t.lock(`where.${e}`),t}get(t=1,e){return this.query().get(t,e)}all(){return this.query().all()}first(){return this.query().first()}find(t){return this.query().find(t)}attachQuietly(t,e={}){return this.services.route.call([`luminix.${this.parent.getType()}.${this.getName()}:attach`,{[this.parent.getKeyName()]:this.parent.getKey(),itemId:t}],i=>i.withData(e))}async attach(t,e={}){if(await this.attachQuietly(t,e),this.items){const i=this.items.search(d=>d.getKey()===t),s=await this.getRelated().find(t);if(!s)return;i!==!1?this.items.put(i,s):this.items.push(s)}else this.items=await this.all()}async detachQuietly(t){await this.services.route.call([`luminix.${this.parent.getType()}.${this.getName()}:detach`,{[this.parent.getKeyName()]:this.parent.getKey(),itemId:t}])}async detach(t){if(await this.detachQuietly(t),this.items){const e=this.items.search(i=>i.getKey()===t);e!==!1&&this.items.pull(e)}}async syncQuietly(t){await this.services.route.call([`luminix.${this.parent.getType()}.${this.getName()}:sync`,{[this.parent.getKeyName()]:this.parent.getKey()}],e=>e.withData(t))}async syncWithPivotValuesQuietly(t,e){await this.services.route.call([`luminix.${this.parent.getType()}.${this.getName()}:sync`,{[this.parent.getKeyName()]:this.parent.getKey()}],i=>i.withData(t.map(s=>({[this.getRelated().getSchema().primaryKey]:s,...e}))))}async sync(t){await this.syncQuietly(t);const e=await this.all();this.items?this.items.splice(0,this.items.count(),...e):this.items=e}async syncWithPivotValues(t,e){await this.syncWithPivotValuesQuietly(t,e);const i=await this.all();this.items?this.items.splice(0,this.items.count(),...i):this.items=i}}class $ extends S{query(){const t=super.query(),e=this.guessInverseRelation();return t.where(e,this.parent.getKey()),t.lock(`where.${e}`),t}async saveQuietly(t){if(!n.Obj.isModel(t))throw new m("HasOneOrMany.saveQuietly()");if(t.getType()!==this.getRelated().getSchemaName())throw new x("HasOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),t.getType());t.setAttribute(this.getForeignKey(),this.parent.getKey()),await t.save()}}class ge extends ${constructor(t,e,i,s=null){if(!n.Obj.isModel(s)&&s!==null)throw new m("HasOne.constructor()","Model or null");super(t,e,i,s),this.services=t,this.meta=e,this.parent=i,this.items=s}isSingle(){return!0}isMultiple(){return!1}get(){return this.query().first()}async save(t){await this.saveQuietly(t),this.items=t}}function E(a){return new n.Collection(a)}class ye extends ${constructor(t,e,i,s=null){if(s!==null&&!(s instanceof n.Collection&&s.every(n.Obj.isModel)))throw new m("HasMany.constructor()","Collection<Model> or null");super(t,e,i,s),this.services=t,this.meta=e,this.parent=i,this.items=s}isSingle(){return!1}isMultiple(){return!0}get(t=1,e){return this.query().get(t,e)}all(){return this.query().all()}first(){return this.query().first()}find(t){return this.query().find(t)}async saveManyQuietly(t){if(!Array.isArray(t)||!t.every(n.Obj.isModel))throw new m("HasMany.saveManyQuietly()","Model[]");if(!t.every(e=>e.getType()===this.getRelated().getSchemaName()))throw new x("HasMany.saveManyQuietly()",this.getRelated().getSchemaName(),t.map(e=>e.getType()).join(", "));await Promise.all(t.map(e=>(e.setAttribute(this.getForeignKey(),this.parent.getKey()),e.save())))}async saveMany(t){await this.saveManyQuietly(t),this.items?this.items.splice(0,this.items.count(),...t):this.items=E(t)}async save(t){await this.saveQuietly(t),this.items===null?this.items=E([t]):this.items.push(t)}}class te extends ${query(){const t=this.getRelated().query();t.once("success",i=>{this.items=i.items});const e=this.guessInverseRelation();return t.where(e+"_id",this.parent.getKey()),t.where(e+"_type",this.getRelated().getSchemaName()),t.lock(`where.${e}_id`),t.lock(`where.${e}_type`),t}async saveQuietly(t){if(!n.Obj.isModel(t))throw new m("MorphOneOrMany.saveQuietly()");if(t.getType()!==this.getRelated().getSchemaName())throw new x("MorphOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),t.getType());const e=this.guessInverseRelation();t.setAttribute(e+"_id",this.parent.getKey()),t.setAttribute(e+"_type",this.parent.getType()),await t.save()}}class me extends te{constructor(t,e,i,s=null){if(s!==null&&!(s instanceof n.Collection&&s.every(n.Obj.isModel)))throw new m("MorphMany.constructor()","Collection<Model> or null");super(t,e,i,s),this.services=t,this.meta=e,this.parent=i,this.items=s}isSingle(){return!1}isMultiple(){return!0}get(t=1,e){return this.query().get(t,e)}all(){return this.query().all()}first(){return this.query().first()}find(t){return this.query().find(t)}async saveManyQuietly(t){if(!Array.isArray(t)||!t.every(n.Obj.isModel))throw new m("MorphMany.saveManyQuietly()");if(!t.every(e=>e.getType()===this.getRelated().getSchemaName()))throw new x("MorphMany.saveManyQuietly()",this.getRelated().getSchemaName(),t.map(e=>e.getType()).join(", "));await Promise.all(t.map(e=>(e.setAttribute(this.getName()+"_id",this.parent.getKey()),e.setAttribute(this.getName()+"_type",this.parent.getType()),e.save())))}async save(t){await this.saveQuietly(t),this.items?this.items.push(t):this.items=await this.all()}async saveMany(t){await this.saveManyQuietly(t);const e=await this.all();this.items?this.items.splice(0,this.items.count(),...e):this.items=e}}class fe extends te{constructor(t,e,i,s=null){if(super(t,e,i,s),this.services=t,this.meta=e,this.parent=i,this.items=s,s!==null&&!n.Obj.isModel(s))throw new m("MorphOne.constructor()","Model or null")}isSingle(){return!0}isMultiple(){return!1}get(){return this.query().first()}async save(t){await this.saveQuietly(t),this.items=t}}class we extends Z{getRelated(){return this.services.model.make(this.parent.getAttribute(this.getName()+"_type"))}async associate(t){if(!n.Obj.isModel(t))throw new m("MorphTo.associate()");return t.exists||await t.save(),this.parent.update({[this.getName()+"_id"]:t.getKey(),[this.getName()+"_type"]:t.getType()})}dissociate(){return this.parent.update({[this.getName()+"_id"]:null,[this.getName()+"_type"]:null})}}class be extends ee{query(){const t=super.query(),e=this.guessInverseRelation();return t.where(e+"_id",this.parent.getKey()),t.where(e+"_type",this.parent.getType()),t.lock(`where.${e}_id`),t.lock(`where.${e}_type`),t}}var U,G;class ve extends(G=n.EventSource,U=Symbol.toStringTag,G){constructor(e){super();p(this,"_models",{});p(this,U,"ModelService");this._schema=e}boot(e){this._schema&&Object.keys(this._schema).forEach(i=>{const s=this[`model${n.Str.studly(i)}`],d=this.model(de(e.make("config"),e.make("log"),e.make("model"),e.make("route"),i),i),y=s(d);this._models[i]=pe(e.make("model"),i,y)})}schema(e){if(!this._schema||e&&!this._schema[e])throw new _(e||"undefined");return e?this._schema[e]:this._schema}make(e){if(e&&!this._models[e])throw new _(e);return e?this._models[e]:this._models}getRelationConstructors(e){return this.relationMap({BelongsTo:Z,BelongsToMany:ee,HasOne:ge,HasMany:ye,MorphMany:me,MorphOne:fe,MorphTo:we,MorphToMany:be},e)}toString(){return"model"}}const Me=n.Reducible(ve);var V,W;class xe extends(W=Error,V=Symbol.toStringTag,W){constructor(e){super(`[Luminix] Route "${e}" not found`);p(this,V,"RouteNotFoundException")}}class Se{constructor(t,e,i,s=""){this.routes=t,this.error=e,this.http=i,this.appUrl=s}isRouteTuple(t){if(!Array.isArray(t)||t.length<2)return!1;const[e,...i]=t;if(typeof e!="string")return!1;const s=["get","post","put","patch","delete"];return!!i.every(d=>s.includes(d))}extractGenerator(t){let e,i=!1;return Array.isArray(t)?[e,i]=t:e=t,[e,i]}get(t){if(!this.exists(t))throw new xe(t);return n.Obj.get(this.routes,t)}url(t){return this.appUrl+this.path(t)}path(t){const[e,i]=this.extractGenerator(t),s=this.get(e)[0].replace(/^\/|\/$/g,""),d=/{([^}]+)}/g;if(i===!1){if(typeof this.replaceRouteParams!="function")throw new M("RouteFacade");return this.replaceRouteParams(`/${s}`)}const y=s.match(d),c=y?y.map(h=>h.slice(1,-1)):[],l=Object.keys(i),r=c.filter(h=>!l.includes(h)),o=l.filter(h=>!c.includes(h));if(r.length>0)throw new TypeError(`Missing values for parameter(s): ${r.join(", ")}`);if(o.length>0)throw new TypeError(`Unexpected parameters: ${o.join(", ")}`);return`/${c.reduce((h,g)=>h.replace(`{${g}}`,`${i[g]}`),s)}`}methods(t){const[e]=this.extractGenerator(t);return this.get(e).slice(1)}exists(t){return n.Obj.has(this.routes,t)&&this.isRouteTuple(n.Obj.get(this.routes,t))}async call(t,e=s=>s,i="default"){if(typeof this.clientOptions!="function"||typeof this.clientError!="function")throw new M("RouteFacade");const[s,d]=this.extractGenerator(t),[,...y]=this.get(s),c=this.url(d?[s,d]:s),l=e(this.http()),r=this.clientOptions({},s);n.Obj.isEmpty(r)||l.withOptions(r);const o=y[0]??r.method;this.error.clear(i);const u=await l[o](c);if(n.isValidationError(u)){const h=u.json("errors");this.error.set(Object.entries(h).reduce((g,[f,w])=>(g[f]=w.join(" "),g),{}),i)}else u.failed()&&this.error.set(this.clientError({axios:u.json("message")},{response:u,name:s,replace:d,client:l}),i);return u}toString(){return"route"}}const Ee=n.Reducible(Se);class $e{getClient(){return new n.Client}baseUrl(t){return this.getClient().baseUrl(t)}asForm(){return this.getClient().asForm()}accept(t){return this.getClient().accept(t)}acceptJson(){return this.getClient().acceptJson()}withHeaders(t){return this.getClient().withHeaders(t)}withOptions(t){return this.getClient().withOptions(t)}withData(t){return this.getClient().withData(t)}withQueryParameters(t){return this.getClient().withQueryParameters(t)}withBasicAuth(t,e){return this.getClient().withBasicAuth(t,e)}withToken(t){return this.getClient().withToken(t)}get(t,e){return this.getClient().get(t,e)}post(t,e){return this.getClient().post(t,e)}put(t,e){return this.getClient().put(t,e)}patch(t,e){return this.getClient().patch(t,e)}delete(t,e){return this.getClient().delete(t,e)}}const Te=n.Macroable($e);var z,X;class _e extends(X=n.ServiceProvider,z=Symbol.toStringTag,X){constructor(){super(...arguments);p(this,z,"LuminixServiceProvider")}register(){this.registerServices(),this.registerMacros(),this.app.on("ready",()=>{this.app.dump("[Luminix] App boot completed")})}boot(){this.app.make("model").boot(this.app)}registerServices(){this.app.singleton("auth",()=>new ie(this.app.make("config"),this.app.make("model"),this.app.make("route"))),this.app.singleton("config",()=>{const e=new n.PropertyBag(n.Obj.omit(this.app.configuration,"manifest"));return e.has("auth.user")||e.set("auth.user",null),e.lock("auth.user"),e}),this.app.singleton("error",()=>new ne),this.app.singleton("http",()=>new Te),this.app.singleton("log",()=>{var e;return new oe(((e=this.app.configuration.app)==null?void 0:e.debug)??!1)}),this.app.singleton("model",()=>{var e;return new Me(((e=this.app.configuration.manifest)==null?void 0:e.models)??{})}),this.app.singleton("route",()=>{var e,i;return new Ee(((e=this.app.configuration.manifest)==null?void 0:e.routes)??{},this.app.make("error"),()=>this.app.make("http"),(i=this.app.configuration.app)==null?void 0:i.url)})}registerMacros(){this.app.macro("environment",(...e)=>e.length>0?e.includes(this.app.make("config").get("app.env","production")):this.app.make("config").get("app.env","production")),this.app.macro("getLocale",()=>this.app.make("config").get("app.locale","en")),this.app.macro("hasDebugModeEnabled",()=>this.app.make("config").get("app.debug",!1)),this.app.macro("isLocal",()=>this.app.make("config").get("app.env","production")==="local"),this.app.macro("isProduction",()=>this.app.make("config").get("app.env","production")==="production"),n.Obj.macro("isModel",function(e){return typeof e=="object"&&e!==null&&e.__isModel===!0})}}class Re{constructor(){p(this,"app")}getFacadeAccessor(){return this.app||(this.app=new(n.Macroable(n.Application))([_e])),this.app}down(){this.app&&(this.app.flush(),delete this.app)}setInstance(t){this.down(),this.app=t}}const b=n.MakeFacade(Re);function v(a=void 0){return typeof a!="string"?b:b.make(a)}function je(){return v("auth")}function Oe(a,t){const e=v("config");return typeof a>"u"?e:e.get(a,t)}function Ae(a,t="default"){return a?v().make("error").get(a,t):v().make("error")}function Ne(...a){const t=v("log");return a.length?t.debug(...a):t}function ke(a){const t=v("model");return a?t.make(a):t}function qe(a,t=!1){const e=v("route");return a?t?e.url([a,t]):e.url(a):e}class Ke{getFacadeAccessor(){return"auth"}}const Ce=n.MakeFacade(Ke,b);class Be{getFacadeAccessor(){return"config"}}const Pe=n.MakeFacade(Be,b),Qe=a=>a instanceof n.Response&&a.unprocessableEntity()&&typeof a.json("message")=="string"&&typeof a.json("errors")=="object"&&a.json("errors")!==null&&Object.values(a.json("errors")).every(t=>Array.isArray(t)&&t.every(e=>typeof e=="string"));class Ie{getFacadeAccessor(){return"error"}}const De=n.MakeFacade(Ie,b);class He{getFacadeAccessor(){return"http"}}const Le=n.MakeFacade(He,b);class Fe{getFacadeAccessor(){return"log"}}const Je=n.MakeFacade(Fe,b);class Ue{getFacadeAccessor(){return"model"}}const Ge=n.MakeFacade(Ue,b);class Ve{getFacadeAccessor(){return"route"}}const We=n.MakeFacade(Ve,b);class ze{constructor(){p(this,"name");p(this,"version")}register(t){}boot(t){}}exports.App=b;exports.Auth=Ce;exports.Config=Pe;exports.Error=De;exports.Http=Le;exports.Log=Je;exports.Model=Ge;exports.Plugin=ze;exports.Route=We;exports.app=v;exports.auth=je;exports.collect=E;exports.config=Oe;exports.error=Ae;exports.isValidationError=Qe;exports.log=Ne;exports.model=ke;exports.route=qe;
|