@luminix/core 0.0.1-beta.20 → 0.0.1-beta.21
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/dist/core.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/core.js
CHANGED
|
@@ -2435,7 +2435,7 @@ class ct {
|
|
|
2435
2435
|
} = e;
|
|
2436
2436
|
this.bind("config", new v(u)), this.facades.config.has("auth.user") || this.facades.config.set("auth.user", null), this.facades.config.lock("auth.user");
|
|
2437
2437
|
const l = new URL(((F = e.app) == null ? void 0 : F.url) ?? "http://localhost"), a = ((N = e.app) == null ? void 0 : N.port) ?? "";
|
|
2438
|
-
a && (l.port = `${a}`), this.bind("error", new ht()), this.bind("route", new lt(i, this.facades.error, l.toString())), this.bind("model", new it(s)), this.bind("auth", new Qe(this)), this.emit("booting");
|
|
2438
|
+
a && (l.port = `${a}`), this.bind("error", new ht()), this.bind("route", new lt(i, this.facades.error, d.trim(l.toString(), "/"))), this.bind("model", new it(s)), this.bind("auth", new Qe(this)), this.emit("booting");
|
|
2439
2439
|
for (const y of Object.values(this.facades))
|
|
2440
2440
|
typeof y == "object" && y !== null && "boot" in y && typeof y.boot == "function" && y.boot(this);
|
|
2441
2441
|
for (const y of this._plugins)
|
package/dist/core.umd.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
(function(m,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("lodash"),require("immer"),require("axios")):typeof define=="function"&&define.amd?define(["exports","lodash","immer","axios"],c):(m=typeof globalThis<"u"?globalThis:m||self,c(m.LuminixCore={},m._,m.immer,m.axios))})(this,function(m,c,w,_){"use strict";var wt=Object.defineProperty;var Ie=m=>{throw TypeError(m)};var bt=(m,c,w)=>c in m?wt(m,c,{enumerable:!0,configurable:!0,writable:!0,value:w}):m[c]=w;var p=(m,c,w)=>bt(m,typeof c!="symbol"?c+"":c,w),D=(m,c,w)=>c.has(m)||Ie("Cannot "+w);var o=(m,c,w)=>(D(m,c,"read from private field"),w?w.call(m):c.get(m)),J=(m,c,w)=>c.has(m)?Ie("Cannot add the same private member more than once"):c instanceof WeakSet?c.add(m):c.set(m,w),je=(m,c,w,_)=>(D(m,c,"write to private field"),_?_.call(m,w):c.set(m,w),w),Fe=(m,c,w)=>(D(m,c,"access private method"),w);var re,se,ie,ne,oe,he,n,ue,ae,le,ce,de,fe,me,pe,ge,ye,we,be,Ee,xe,Me,Te,$e,Se,Ae,Re,ve,Ne,_e,Be,qe;class Pe extends(se=Error,re=Symbol.toStringTag,se){constructor(t){super(`[Luminix] Facade "${t}" not found`);p(this,re,"FacadeNotFoundException")}}class Le{constructor(e){p(this,"_user");this.app=e}attempt(e,t=!1,r){const i=document.createElement("form");i.method="post",i.action=this.app.make("route").url("login"),i.style.display="none";const s=this.app.make("config").get("auth.csrf");if(typeof s=="string"){const a=document.createElement("input");a.type="hidden",a.name="_token",a.value=s,i.appendChild(a)}const u=document.createElement("input");u.type="email",u.name="email",u.value=e.email,i.appendChild(u);const l=document.createElement("input");if(l.type="password",l.name="password",l.value=e.password,i.appendChild(l),t){const a=document.createElement("input");a.type="checkbox",a.name="remember",a.value="1",a.checked=!0,i.appendChild(a)}r&&i.addEventListener("submit",r),document.body.appendChild(i),i.submit()}check(){return!!this.app.make("config").get("auth.user")}logout(e){const t=document.createElement("form");t.method="post",t.action=this.app.make("route").url("logout"),t.style.display="none";const r=this.app.make("config").get("auth.csrf");if(typeof r=="string"){const i=document.createElement("input");i.type="hidden",i.name="_token",i.value=r,t.appendChild(i)}document.body.appendChild(t),e&&t.addEventListener("submit",e),t.submit()}user(){if(!this._user){const{model:e,config:t}=this.app.make(),r=e.make("user"),i=t.get("auth.user");if(!i)return null;this._user=new r(i)}return this._user}id(){var e;return((e=this.user())==null?void 0:e.getKey())||null}}class ke{constructor(e){this._debug=e}emergency(...e){this._debug&&console.error(...e)}alert(...e){this._debug&&console.error(...e)}critical(...e){this._debug&&console.error(...e)}error(...e){this._debug&&console.error(...e)}warning(...e){this._debug&&console.warn(...e)}notice(...e){this._debug&&console.info(...e)}info(...e){this._debug&&console.info(...e)}debug(...e){this._debug&&console.debug(...e)}}class q{constructor(e){p(this,"locked",[]);this.bag=e,Object.freeze(this.bag)}get(e,t){return c.get(this.bag,e,t)}set(e,t){if(this.locked.some(r=>e.startsWith(r)))throw new Error(`Cannot set a locked path "${e}"`);if(typeof t=="object"&&t!==null&&this.locked.some(r=>c.has(t,r.slice(e.length+1))))throw new Error(`Cannot set a path "${e}" that would override a locked path`);if(e==="."){if(this.locked.length)throw new Error("Cannot set the root path when there are locked paths");if(typeof t!="object"||t===null)throw new TypeError("Value must be an object");this.bag=w.produce(this.bag,()=>t),this.emit("change",{path:e,value:t,type:"set"});return}this.bag=w.produce(this.bag,r=>{c.set(r,e,t)}),this.emit("change",{path:e,value:t,type:"set"})}merge(e,t){if(typeof t!="object"||t===null)throw new TypeError("Value must be an object");if(e==="."){if(this.locked.some(i=>c.has(t,i)))throw new Error(`Cannot merge a path "${e}" that would override a locked path`);this.bag=w.produce(this.bag,i=>({...i,...t})),this.emit("change",{path:e,value:t,type:"merge"});return}const r=this.get(e);if(typeof r=="object"&&r!==null)return this.set(e,{...r,...t});if(r===null||typeof r>"u")return this.set(e,t);throw new Error(`Cannot merge a non-object path "${e}"`)}has(e){return c.has(this.bag,e)}delete(e){if(this.locked.some(t=>e.startsWith(t)))throw new Error(`Cannot delete a locked path "${e}"`);this.bag=w.produce(this.bag,t=>{c.unset(t,e)}),this.emit("change",{path:e,value:null,type:"delete"})}lock(e){if(!this.has(e))throw new Error(`Cannot lock a non-existing path "${e}"`);this.locked.push(e)}clone(){return new q(this.bag)}all(){return this.bag}isEmpty(){return c.isEmpty(this.bag)}on(e,t){return()=>null}once(e,t){}emit(e,t){}}function A(h){var e,t,r,Ke,s;return s=class extends(t=h,e=Symbol.toStringTag,t){constructor(...a){super(...a);J(this,r);p(this,"emitter");p(this,e,h.name);this.emitter=Fe(this,r,Ke).call(this)}on(a,f){if(typeof a!="string")throw new TypeError("event must be a string");if(typeof f!="function")throw new TypeError("callback must be a function");return this.emitter.on(a,f)}once(a,f){if(typeof a!="string")throw new TypeError("event must be a string");if(typeof f!="function")throw new TypeError("callback must be a function");const g=this.emitter.on(a,M=>{g(),f(M)})}emit(a,f={}){if(typeof a!="string")throw new TypeError("event must be a string");if(typeof f!="object")throw new TypeError("data must be an object");this.emitter.emit(a,{...f,source:this})}},r=new WeakSet,Ke=function(){return{emit(a,f){for(let g=0,M=this.events[a]||[],T=M.length;g<T;g++)M[g](f)},events:{},on(a,f){var g;return((g=this.events)[a]||(g[a]=[])).push(f),()=>{var M;this.events[a]=(M=this.events[a])==null?void 0:M.filter(T=>f!==T)}}}},s}function H(...h){return h.reduce((e,t)=>e.flatMap(r=>t.map(i=>[r,i].flat())))}function R(h){return!(typeof h!="object"||h===null||!Reflect.has(h,"constructor")||Reflect.get(h.constructor,"name")!=="Collection")}class E extends(ne=Error,ie=Symbol.toStringTag,ne){constructor(){super("[Luminix] Method not implemented.");p(this,ie,"MethodNotImplementedException")}}function d(h=[],e=k){if(!Array.isArray(h))throw new TypeError("collect() expects an array");return new(A(e))([...h])}const v=h=>{h.emit("change",{items:h.all()})},K=(h,e)=>Array.isArray(h)?h[e]??null:h.get(e);class k{constructor(e=[]){J(this,n);p(this,oe,"Collection");je(this,n,e)}get items(){return[...o(this,n)]}[(he=Symbol.iterator,oe=Symbol.toStringTag,he)](){return o(this,n)[Symbol.iterator]()}all(){return[...o(this,n)]}average(e){return typeof e=="string"?this.avg(e):this.avg()}avg(e){return typeof e=="string"?this.sum(e)/o(this,n).length:this.sum()/o(this,n).length}chunk(e){const t=[];for(let r=0;r<o(this,n).length;r+=e)t.push(o(this,n).slice(r,r+e));return d(t.map(r=>d(r)))}chunkWhile(e){const t=[];let r=d();for(let i=0;i<o(this,n).length;i++)e(o(this,n)[i],i,r)?r.push(o(this,n)[i]):(t.push(r),r=d());return r.count()>0&&t.push(r),d(t)}collapse(){return d(o(this,n).flat())}collect(){return d(o(this,n))}combine(e){const t={};return o(this,n).forEach((r,i)=>{if(typeof r!="string")throw new TypeError("The `combine` method expects the keys to be strings");t[r]=K(e,i)}),t}concat(e){return Array.isArray(e)?d([...o(this,n),...e]):d([...o(this,n),...e.all()])}contains(e,t){return typeof e=="function"?o(this,n).some((r,i)=>e(r,i,this)):o(this,n).some(r=>{if(typeof t>"u")return r==e;if(typeof e!="string")throw new TypeError("The key must be a string");return r[e]==t})}containsOneItem(){return o(this,n).length===1}containsStrict(e,t){return typeof e=="function"?o(this,n).some((r,i)=>e(r,i,this)):o(this,n).some(r=>{if(typeof t>"u")return r===e;if(typeof e!="string")throw new TypeError("The key must be a string");return r[e]===t})}count(){return o(this,n).length}countBy(e){return typeof e=="function"?o(this,n).reduce((t,r,i)=>{const s=e(r,i,this);return t[s]=t[s]?t[s]+1:1,t},{}):o(this,n).reduce((t,r)=>{if(!["string","number"].includes(typeof r))throw new TypeError("The countBy method expects the items to be strings or numbers");return t[String(r)]=t[String(r)]?t[String(r)]+1:1,t},{})}crossJoin(...e){return d(H(o(this,n),...e.map(t=>Array.isArray(t)?t:t.all())))}diff(e){return Array.isArray(e)?d(o(this,n).filter(t=>!e.includes(t))):d(o(this,n).filter(t=>!e.contains(t)))}doesntContain(e,t){return typeof e=="function"?o(this,n).every((r,i)=>!e(r,i,this)):o(this,n).every(r=>{if(typeof t>"u")return r!=e;if(typeof e!="string")throw new TypeError("The key must be a string");return r[e]!=t})}dump(){console.log(this.toArray())}duplicates(e){return d(typeof e=="string"?o(this,n).reduce((t,r,i)=>(o(this,n).slice(i+1).some(s=>s[e]==r[e])&&t.push(r[e]),t),[]):o(this,n).reduce((t,r,i)=>(o(this,n).slice(i+1).some(s=>s==r)&&t.push(r),t),[]))}duplicatesStrict(e){return d(typeof e=="string"?o(this,n).reduce((t,r,i)=>(o(this,n).slice(i+1).some(s=>s[e]===r[e])&&t.push(r[e]),t),[]):o(this,n).reduce((t,r,i)=>(o(this,n).slice(i+1).some(s=>s===r)&&t.push(r),t),[]))}each(e){let t=0;for(const r of this){if(e(r,t,this)===!1)break;t++}return this}eachSpread(e){for(const t of this){if(!Array.isArray(t)&&!R(t))throw new TypeError("The items in the collection must be arrays or collections");const r=Array.isArray(t)?t:t.all();if(e(...r)===!1)break}return this}ensure(e){const t=Array.isArray(e)?e:[e];return o(this,n).forEach((r,i)=>{if(!t.some(s=>typeof s=="string"?typeof r===s:r instanceof s))throw new TypeError(`The item at index ${i} is not of the expected type`)}),this}every(e){return o(this,n).every((t,r)=>e(t,r,this))}except(e){return d(o(this,n).filter((t,r)=>!e.includes(r)))}filter(e){return d(o(this,n).filter((t,r)=>typeof e!="function"?!!t:e(t,r,this)))}first(e){return typeof e=="function"?o(this,n).find((t,r)=>e(t,r,this))??null:o(this,n)[0]??null}firstOrFail(e){const t=this.first(e);if(t===null)throw new Error("No matching item found");return t}firstWhere(e,t,r){if(typeof e!="string")throw new TypeError("The key must be a string");if(typeof t>"u")return this.first(i=>!!i[e]);if(typeof r>"u")return o(this,n).find(i=>i[e]==t)??null;if(typeof t!="string")throw new TypeError("The operator must be a string");return r===null?o(this,n).find(i=>i[e]===null)??null:o(this,n).find(i=>{switch(t){case"=":return i[e]==r;case"!=":return i[e]!=r;case">":return i[e]>r;case"<":return i[e]<r;case">=":return i[e]>=r;case"<=":return i[e]<=r;default:throw new Error("Unsupported operator")}})??null}flatMap(e){return d(o(this,n).flatMap((t,r)=>e(t,r,this)))}forget(e){return o(this,n).splice(e,1),v(this),this}forPage(e,t){return d(o(this,n).slice((e-1)*t,e*t))}get(e,t){if(typeof e!="number")throw new TypeError("The key must be a number");return typeof t>"u"?o(this,n)[e]??null:typeof t=="function"?o(this,n)[e]??t():o(this,n)[e]??t}groupBy(e){const t=Array.isArray(e)?e:[e];return o(this,n).reduce((r,i,s)=>{const u=t.map(a=>{if(typeof a=="function"){const f=a(i,s,this);return Array.isArray(f)?f:[f]}return[String(i[a])]});return H(...u).forEach(a=>{const f=Array.isArray(a)?a.join("."):a;c.set(r,f,[...c.get(r,f,[]),i])}),r},{})}has(e){return o(this,n).length>e}hasAny(e){return e.some(t=>this.has(t))}implode(e,t){if(typeof t>"u"){if(typeof e!="string")throw new TypeError("The glue must be a string");if(!o(this,n).every(r=>["string","number"].includes(typeof r)))throw new TypeError("The items must be strings or numbers");return o(this,n).join(e)}if(typeof e=="function")return o(this,n).map((r,i)=>e(r,i,this)).join(t);if(typeof e!="string")throw new TypeError("The key must be a string");if(!o(this,n).every(r=>typeof r=="object"))throw new TypeError("The items must be objects");return o(this,n).map(r=>r[e]).join(t)}intersect(e){return Array.isArray(e)?d(o(this,n).filter(t=>e.includes(t))):d(o(this,n).filter(t=>e.contains(t)))}isEmpty(){return o(this,n).length===0}isNotEmpty(){return!this.isEmpty()}join(e,t){return typeof t>"u"?o(this,n).join(e):o(this,n).slice(0,-1).join(e)+t+o(this,n)[o(this,n).length-1]}keyBy(e){if(typeof e=="function")return o(this,n).reduce((t,r,i)=>(t[e(r,i,this)]=r,t),{});if(typeof e!="string")throw new TypeError("The key must be a string");return o(this,n).reduce((t,r)=>(t[String(r[e])]=r,t),{})}last(e){return typeof e=="function"?o(this,n).toReversed().find((t,r)=>e(t,r,this))??null:o(this,n)[o(this,n).length-1]??null}map(e){return d(o(this,n).map((t,r)=>e(t,r,this)))}mapInto(e){return d(o(this,n).map(t=>new e(t)))}mapSpread(e){return d(o(this,n).map(t=>{if(!Array.isArray(t)&&!R(t))throw new TypeError("The items in the collection must be arrays or collections");const r=Array.isArray(t)?t:t.all();return e(...r)}))}mapToGroups(e){return o(this,n).reduce((t,r,i)=>{const s=e(r,i,this);return Object.entries(s).forEach(([u,l])=>{t[u]=t[u]??[],t[u].push(l)}),t},{})}mapWithKeys(e){return o(this,n).reduce((t,r,i)=>{const s=e(r,i,this);return Object.entries(s).forEach(([u,l])=>{t[u]=l}),t},{})}max(e){return typeof e=="string"?o(this,n).reduce((t,r)=>r[e]>t?r[e]:t,o(this,n)[0][e]):o(this,n).reduce((t,r)=>r>t?r:t,o(this,n)[0])}median(e){if(typeof e=="string"){const i=this.pluck(e).sort(),s=Math.floor(i.count()/2);return i.count()%2===0?d([K(i,s-1),K(i,s)]).avg():K(i,s)}const t=o(this,n).toSorted(),r=Math.floor(t.length/2);return t.length%2===0?d([t[r-1],t[r]]).avg():t[r]??null}merge(e){return Array.isArray(e)?d([...o(this,n),...e]):d([...o(this,n),...e.all()])}min(e){return typeof e=="string"?o(this,n).reduce((t,r)=>r[e]<t?r[e]:t,o(this,n)[0][e]):o(this,n).reduce((t,r)=>r<t?r:t,o(this,n)[0])}mode(e){const t=typeof e=="string"?this.filter(i=>["number","string"].includes(typeof i[e])).countBy(i=>i[e]):this.countBy(),r=Math.max(...Object.values(t));return Object.entries(t).filter(([,i])=>i===r).map(([i])=>i)}nth(e,t=0){return this.chunk(e).filter(r=>r.count()>t).map(r=>r.get(t))}only(e){return d(o(this,n).filter((t,r)=>e.includes(r)))}pad(e,t=null){const r=o(this,n).slice();for(;r.length<Math.abs(e);)e>0?r.push(t):r.unshift(t);return d(r)}partition(e){return[this.filter(e),this.reject(e)]}percentage(e,t=2){return Math.round(100*(10^t)*this.filter(e).count()/o(this,n).length)/(10^t)}pipe(e){return e(this)}pipeInto(e){return new e(this)}pipeThrough(e){return e.reduce((t,r)=>{if(!R(t)&&!Array.isArray(t))throw new TypeError("The pipeline expects the carry to be a collection or an array");return r(R(t)?t:d(t))},this)}pluck(e){return this.map(t=>t[e])}pop(e=1){const t=o(this,n).splice(o(this,n).length-e,e);return v(this),e===1?t[0]??null:d(t)}prepend(e){const t=o(this,n).unshift(e);return v(this),t}pull(e){const t=o(this,n).splice(e,1)[0]??null;return v(this),t}push(...e){const t=o(this,n).push(...e);return v(this),t}put(e,t){return o(this,n).splice(e,1,t),v(this),this}random(e=1){if(o(this,n).length<e)throw new Error("The collection has fewer items than the requested amount");const t=d(c.sampleSize(o(this,n),e));return e===1?t.first():t}reduce(e,t=null){return o(this,n).reduce((r,i,s)=>e(r,i,s,this),t)}reject(e){return this.filter((t,r)=>!e(t,r,this))}replace(e){const t=o(this,n).slice();return Object.entries(e).forEach(([r,i])=>{t[parseInt(r)]=i}),d(t)}reverse(){return d(o(this,n).toReversed())}search(e,t=!1){if(typeof e!="function"||o(this,n).every(i=>typeof i=="function")){const i=o(this,n).findIndex(s=>t?s===e:s==e);return i===-1?!1:i}const r=o(this,n).findIndex((i,s)=>e(i,s,this));return r===-1?!1:r}select(e){return this.map(t=>e.reduce((r,i)=>(r[i]=t[i],r),{}))}shift(e=1){const t=o(this,n).splice(0,e);return v(this),e===1?t[0]??null:d(t)}shuffle(){return d(c.shuffle(o(this,n)))}skip(e){return d(o(this,n).slice(e))}skipUntil(e){return typeof e=="function"?this.skip(o(this,n).findIndex((t,r)=>e(t,r,this))):this.skip(o(this,n).findIndex(t=>t==e))}skipWhile(e){return typeof e=="function"?this.skip(o(this,n).findIndex((t,r)=>!e(t,r,this))):this.skip(o(this,n).findIndex(t=>t!=e))}slice(e,t){return d(typeof t>"u"?o(this,n).slice(e):typeof e>"u"?o(this,n).slice(0,t):o(this,n).slice(e,e+t))}sliding(e,t=1){const r=[];for(let i=0;i<o(this,n).length&&!(i+e>o(this,n).length);i+=t)r.push(o(this,n).slice(i,i+e));return d(r.map(i=>d(i)))}sole(e,t){if(typeof e=="function"){const r=this.filter(e);return r.count()===1?r.first():null}if(typeof e=="string"){const r=this.where(e,t);return r.count()===1?r.first():null}return o(this,n).length===1?this.first():null}some(...e){return this.contains(...e)}sort(e){return d(o(this,n).toSorted(e))}sortBy(e,t="asc"){if(typeof e=="function"){let r=-1;return d(o(this,n).toSorted((i,s)=>(r++,e(i,r,this)-e(s,r,this))))}if(Array.isArray(e))return e.every(r=>Array.isArray(r))?d(o(this,n).toSorted((r,i)=>{for(const[s,u]of e){const l=r[s]??-1/0,a=i[s]??-1/0;if(l>a)return u==="asc"?1:-1;if(l<a)return u==="asc"?-1:1}return 0})):d(o(this,n).toSorted((r,i)=>{for(const s of e){const u=s(r,i);if(u!==0)return u}return 0}));if(typeof e!="string")throw new TypeError("The key must be a string");return d(o(this,n).toSorted((r,i)=>{const s=r[e]??-1/0,u=i[e]??-1/0;return s>u?t==="asc"?1:-1:s<u?t==="asc"?-1:1:0}))}sortDesc(){return this.sort((e,t)=>e>t?-1:e<t?1:0)}splice(e,t,...r){const i=t===void 0?o(this,n).length:t,s=o(this,n).splice(e,i,...r);return v(this),d(s)}split(e){const t=[];for(let r=0;r<e;r++){const i=o(this,n).slice(t.flat().length,t.flat().length+Math.min(Math.ceil((o(this,n).length-t.flat().length)/(e-r)),o(this,n).length-t.flat().length));t.push(d(i))}return d(t)}splitIn(e){const t=Math.ceil(o(this,n).length/e);return this.chunk(t)}sum(e){return typeof e=="string"?o(this,n).reduce((t,r)=>{const i=r[e];if(typeof i!="number")throw new TypeError("The items must be numbers");return t+i},0):o(this,n).reduce((t,r)=>{if(typeof r!="number")throw new TypeError("The items must be numbers");return t+r},0)}take(e){return d(o(this,n).slice(0,e))}takeUntil(e){return typeof e=="function"?this.take(o(this,n).findIndex((t,r)=>e(t,r,this))):this.take(o(this,n).findIndex(t=>t==e))}takeWhile(e){return typeof e=="function"?this.take(o(this,n).findIndex((t,r)=>!e(t,r,this))):this.take(o(this,n).findIndex(t=>t!=e))}tap(e){return e(this),this}toArray(){const e=t=>typeof t!="object"?t:Array.isArray(t)?t.map(e):t&&"toArray"in t&&typeof t.toArray=="function"?t.toArray():t&&"toJson"in t&&typeof t.toJson=="function"?t.toJson():t;return o(this,n).map(e)}toJson(){return JSON.stringify(o(this,n))}transform(e){for(const[t,r]of o(this,n).entries())o(this,n).splice(t,1,e(r,t,this));return v(this),this}unique(e){return d(typeof e=="string"?[...new Set(o(this,n).map(t=>t[e]))].map(t=>o(this,n).find(r=>r[e]==t)):[...new Set(o(this,n))])}uniqueStrict(e){return d(typeof e=="string"?[...new Set(o(this,n).map(t=>t[e]))].map(t=>o(this,n).find(r=>r[e]===t)):[...new Set(o(this,n))])}unless(e,t,r){return e?typeof r=="function"&&r(this):t(this),this}unlessEmpty(e,t){return this.whenNotEmpty(e,t)}unlessNotEmpty(e,t){return this.whenEmpty(e,t)}value(e){return o(this,n).length===0?null:o(this,n)[0][e]}when(e,t,r){return e?t(this):typeof r=="function"&&r(this),this}whenEmpty(e,t){return this.isEmpty()?e(this):typeof t=="function"&&t(this),this}whenNotEmpty(e,t){return this.isNotEmpty()?e(this):typeof t=="function"&&t(this),this}where(e,t,r){if(typeof r>"u")return d(o(this,n).filter(s=>s[e]==t));if(typeof t!="string")throw new TypeError("The operator must be a string");if(r===null)return d(o(this,n).filter(s=>s[e]===null));const i={"=":s=>s[e]==r,"!=":s=>s[e]!=r,">":s=>s[e]>r,"<":s=>s[e]<r,">=":s=>s[e]>=r,"<=":s=>s[e]<=r};if(!(t in i))throw new Error("Unsupported operator");return d(o(this,n).filter((s,u)=>i[t](s,u,this)))}whereStrict(e,t,r){if(typeof r>"u")return d(o(this,n).filter(s=>s[e]===t));if(typeof t!="string")throw new TypeError("The operator must be a string");if(r===null)return d(o(this,n).filter(s=>s[e]===null));const i={"=":s=>s[e]===r,"!=":s=>s[e]!==r,">":s=>s[e]>r,"<":s=>s[e]<r,">=":s=>s[e]>=r,"<=":s=>s[e]<=r};if(!(t in i))throw new Error("Unsupported operator");return d(o(this,n).filter((s,u)=>i[t](s,u,this)))}whereBetween(e,[t,r]){return d(o(this,n).filter(i=>i[e]>=t&&i[e]<=r))}whereIn(e,t){return d(o(this,n).filter(r=>t.includes(r[e])))}whereInstanceOf(e){return d(o(this,n).filter(t=>t instanceof e))}whereNotBetween(e,[t,r]){return d(o(this,n).filter(i=>i[e]<t||i[e]>r))}whereNotIn(e,t){return d(o(this,n).filter(r=>!t.includes(r[e])))}whereNotNull(e){return d(o(this,n).filter(t=>t[e]!==null))}whereNull(e){return d(o(this,n).filter(t=>t[e]===null))}zip(e){return Array.isArray(e)?d(o(this,n).map((t,r)=>[t,e[r]??null])):d(o(this,n).map((t,r)=>[t,e.get(r)]))}on(e,t){throw new E}once(e,t){throw new E}emit(e,t){throw new E}}n=new WeakMap;const C=A(k);class W extends(ae=k,ue=Symbol.toStringTag,ae){constructor(){super(...arguments);p(this,ue,"Collection")}intersect(t){return this.filter(r=>t.some(i=>i.getKey()===r.getKey()))}}const I=(...h)=>{const e=new URLSearchParams;return h.forEach(t=>{const[,...r]=t.split("?");new URLSearchParams(r.join("")).forEach((s,u)=>{e.set(u,s)})}),e};class Ce extends(ce=Error,le=Symbol.toStringTag,ce){constructor(t){super(`[Luminix] Model "${t}" does not have a primary key`);p(this,le,"ModelWithoutPrimaryKeyException")}}const Qe=A(q);class Ue{constructor(e,t,r={}){p(this,"bag");this.facades=e,this.abstract=t,this.query=r,this.bag=new Qe(r),this.bag.on("change",()=>{this.emit("change",{data:this.bag})})}on(e,t){throw new E}once(e,t){throw new E}emit(e,t){throw new E}lock(e){this.bag.lock(e)}whereBetween(e,t){return this.bag.has("where")||this.bag.set("where",{}),this.bag.set(`where.${c.camelCase(e)}Between`,t),this}whereNotBetween(e,t){return this.bag.has("where")||this.bag.set("where",{}),this.bag.set(`where.${c.camelCase(e)}NotBetween`,t),this}whereNull(e){return this.bag.has("where")||this.bag.set("where",{}),this.bag.set(`where.${c.camelCase(e)}Null`,!0),this}whereNotNull(e){return this.bag.has("where")||this.bag.set("where",{}),this.bag.set(`where.${c.camelCase(e)}NotNull`,!0),this}limit(e){return this.bag.set("per_page",e),this}where(e,t,r){if(this.bag.has("where")||this.bag.set("where",{}),typeof e=="function")return e(this)||this;if(typeof r>"u")return this.bag.set(`where.${c.camelCase(e)}`,t),this;if(typeof t!="string")throw new Error(`Invalid operator ${t} provided for where clause.`);const s={"=":"","!=":"NotEquals",">":"GreaterThan",">=":"GreaterThanOrEquals","<":"LessThan","<=":"LessThanOrEquals"}[t]||c.upperFirst(c.camelCase(t));return this.bag.set(`where.${c.camelCase(e)}${s}`,r),this}with(e){const t=this.bag.get("with",[]);return(Array.isArray(e)?e:[e]).forEach(i=>{t.includes(i)||t.push(i)}),this.bag.set("with",t),this}withOnly(e){return this.bag.set("with",Array.isArray(e)?e:[e]),this}without(e){const t=this.bag.get("with",[]);return(Array.isArray(e)?e:[e]).forEach(i=>{t.includes(i)&&t.splice(t.indexOf(i),1)}),this.bag.set("with",t),this}orderBy(e,t="asc"){return this.bag.set("order_by",`${e}:${t}`),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[t,r]of e.entries())this.bag.set(t,r);return this}async exec(e=1,t){try{this.bag.set("page",e),this.emit("submit",{data:this.bag});const{data:r}=await this.facades.route.call(`luminix.${this.abstract}.index`,{params:this.bag.all(),errorBag:`${this.abstract}.fetch`}),i=this.facades.model.make(this.abstract),s=d(r.data.map(u=>{const l=new i(u);return l.exists=!0,this.facades.model.emit("fetch",{class:this.abstract,model:l}),l}),W);if(t){const[u]=t.split("?");return{...r,data:s,links:{first:`${u}?${I(t,r.links.first).toString()}`,last:`${u}?${I(t,r.links.last).toString()}`,next:r.links.next&&`${u}?${I(t,r.links.next).toString()}`,prev:r.links.prev&&`${u}?${I(t,r.links.prev).toString()}`},meta:{...r.meta,links:r.meta.links.map(l=>({...l,url:l.url&&`${u}?${I(t,l.url).toString()}`}))}}}return{...r,data:s}}catch(r){throw this.emit("error",{error:r}),r}}async get(e=1,t){const r=await this.exec(e,t);return this.emit("success",{response:r,items:r.data}),r}async first(){const e=await this.limit(1).exec(1);return this.emit("success",{response:e,items:e.data.first()}),e.data.first()}async find(e){const t=this.facades.model.schema(this.abstract).primaryKey;if(!t)throw new Ce(this.abstract);const r=await this.where(t,e).limit(1).exec(1);return this.emit("success",{response:r,items:r.data.sole()}),r.data.sole()}async all(){const e=this.facades.config.get("luminix.backend.api.max_per_page",150),t=await this.limit(e).exec(1),r=t.meta.last_page;if(r===1)return t.data;const i=Array.from({length:r-1},(l,a)=>a+2),s=await Promise.all(i.map(l=>this.limit(e).exec(l))),u=d(s.reduce((l,a)=>(l.push(...a.data),l),t.data).all(),W);return this.emit("success",{response:{...t,data:u},items:u}),u}}const De=A(Ue);class N extends(fe=Error,de=Symbol.toStringTag,fe){constructor(t){super(`[Luminix] Expected ${t} to be reducible.`);p(this,de,"NotReducibleException")}}class $ extends(pe=TypeError,me=Symbol.toStringTag,pe){constructor(t,r="Model"){super(`[Luminix] "${t}" expects ${r}`);p(this,me,"NotModelException")}}class Je extends(ye=Error,ge=Symbol.toStringTag,ye){constructor(t,r,i,s){super(`[Luminix] Could not determine inverse relation for "${r}" in model "${t}". Please specify a relation in model "${i}" of type ${s} that points back to "${t}".`);p(this,ge,"NoInverseRelationException")}}class He extends(be=Error,we=Symbol.toStringTag,be){constructor(t){super(`[Luminix] Relation "${t}" is not supported`);p(this,we,"UnsupportedRelationException")}}function x(h){return typeof h=="object"&&h!==null&&h.__isModel===!0}class P{constructor(e,t,r,i=null){p(this,"unsubscribeQuery",null);if(this.meta=e,this.facades=t,this.parent=r,this.items=i,i!==null&&!x(i)&&!(R(i)&&i.every(x)))throw new $("Relation.constructor()","Model, Collection<Model> or null")}make(e){const t=this.getRelated();if(e===null||typeof e>"u"){this.set(null);return}if(this.isSingle()){if(typeof e!="object"||Array.isArray(e))throw new TypeError("Relation.make() expects an object");this.set(new t(e))}if(this.isMultiple()){if(!Array.isArray(e))throw new TypeError("Relation.make() expects an array");this.set(d(e.map(r=>new t(r))))}}guessInverseRelation(){const{relations:e}=this.getRelated().getSchema();if(typeof this.facades.model.guessInverseRelation!="function")throw new N("ModelFacade");const t=this.getType(),r=this.facades.model.guessInverseRelation({HasOne:["BelongsTo"],HasMany:["BelongsTo"],BelongsTo:["HasOne","HasMany"],BelongsToMany:["BelongsToMany"],MorphTo:["MorphMany","MorphOne"],MorphOne:["MorphTo"],MorphMany:["MorphTo"],MorphToMany:["MorphToMany"]},this.parent,t,this.getRelated());if(!(t in r))throw new He(t);for(const i in e){const s=e[i];if((s.model===this.parent.getType()||["MorphOne","MorphMany"].includes(t))&&r[t].includes(s.type))return i}throw new Je(this.parent.getType(),t,this.getRelated().getSchemaName(),r[t].join(" or "))}set(e){if(e!==null&&!x(e)&&!(R(e)&&e.every(x)))throw new $("Relation.set()","Model, Collection<Model> or null");!this.items||x(this.items)?this.items=e:R(e)&&this.items.splice(0,this.items.count(),...e)}getForeignKey(){return this.meta.foreignKey}getName(){return this.meta.name}getType(){return this.meta.type}getModel(){return this.meta.model}getRelated(){return this.facades.model.make(this.meta.model)}query(){const e=this.getRelated().query();return this.unsubscribeQuery&&this.unsubscribeQuery(),this.unsubscribeQuery=e.on("success",t=>{this.items=t.items}),e}isLoaded(){return this.items!==null}getLoadedItems(){return this.items}isSingle(){return x(this.items)}isMultiple(){return R(this.items)}getParent(){return this.parent}where(...e){return this.query().where(...e)}whereNull(e){return this.query().whereNull(e)}whereNotNull(e){return this.query().whereNotNull(e)}whereBetween(e,t){return this.query().whereBetween(e,t)}whereNotBetween(e,t){return this.query().whereNotBetween(e,t)}orderBy(e,t="asc"){return this.query().orderBy(e,t)}searchBy(e){return this.query().searchBy(e)}minified(){return this.query().minified()}limit(e){return this.query().limit(e)}}class G extends(xe=Error,Ee=Symbol.toStringTag,xe){constructor(t,r){super(`[Luminix] Model "${t}" must be persisted before calling "${r}"`);p(this,Ee,"ModelNotPersistedException")}}function We(h,e){var r;r=Symbol.toStringTag;class t{constructor(s={}){p(this,"_attributes",new q({}));p(this,"_original",{});p(this,"_relations",{});p(this,"_changedKeys",[]);p(this,"exists",!1);p(this,"wasRecentlyCreated",!1);p(this,r,c.upperFirst(c.camelCase(e)));this.makeRelations(),this.makeAttributes(s)}cast(s,u){return s==null||!u?s:["boolean","bool"].includes(u)?!!s:["date","datetime","immutable_date","immutable_datetime"].includes(u)&&typeof s=="string"?new Date(s):["float","double","integer","int"].includes(u)||u.startsWith("decimal:")?Number(s):s}mutate(s,u){return s==null||!u?s:["boolean","bool"].includes(u)?!!s:["date","datetime","immutable_date","immutable_datetime"].includes(u)&&s instanceof Date?s.toISOString():["float","double","integer","int"].includes(u)||u.startsWith("decimal:")?Number(s):s}makeRelations(){const{relations:s}=h.make("model").schema(e);if(this._relations={},!s)return;const u=h.make("model").relationMap({},e);Object.entries(s).forEach(([l,a])=>{const{type:f}=a,g=f in u?u[f]:P;this._relations[l]=new g({name:l,...a},h.make(),this,null)})}makeAttributes(s){const{relations:u}=h.make("model").schema(e),l=Object.keys(u||{}),a=c.omit(s,l);if(this.fillable.filter(f=>!(f in a)).forEach(f=>{a[f]=null}),u&&Object.keys(u).forEach(f=>{this.relation(c.camelCase(f)).make(s[f])}),!this.validateJsonObject(a)){if(h.isProduction())throw new TypeError(`[Luminix] Invalid attributes for model "${e}"`);h.make("log").warning(`Invalid attributes for model "${e}".
|
|
2
2
|
This will throw an error in production.`,{attributes:s,abstract:e})}this._attributes.set(".",a),this._original=a,this._changedKeys.splice(0,this._changedKeys.length)}makePrimaryKeyReplacer(){return{[this.getKeyName()]:this.getKey()}}dispatchChangeEvent(s){this.emit("change",{value:s})}dispatchCreateEvent(s){this.emit("create",{value:s}),h.make("model").emit("create",{class:e,model:this})}dispatchUpdateEvent(s){this.emit("update",{value:s}),h.make("model").emit("update",{class:e,model:this})}dispatchSaveEvent(){this.emit("save",{value:this.diff()}),h.make("model").emit("save",{class:e,model:this})}dispatchDeleteEvent(s=!1){this.emit("delete",{force:s,[this.getKeyName()]:this.getKey()}),h.make("model").emit("delete",{class:e,model:this,force:s})}dispatchRestoreEvent(){this.emit("restore",{value:this.attributes}),h.make("model").emit("restore",{class:e,model:this})}dispatchErrorEvent(s,u){this.emit("error",{error:s,operation:u}),h.make("model").emit("error",{class:e,model:this,error:s,operation:u})}updateChangedKeys(s){const u=(l,a)=>typeof l=="object"&&l!==null?c.isEqual(l,a):l==a;!this._changedKeys.includes(s)&&!u(c.get(this._original,s),this._attributes.get(s))?this._changedKeys.push(s):this._changedKeys.includes(s)&&u(c.get(this._original,s),this._attributes.get(s))&&this._changedKeys.splice(this._changedKeys.indexOf(s),1)}validateJsonObject(s){return typeof s!="object"||s===null?!1:Object.entries(s).every(([,u])=>["boolean","number","string"].includes(typeof u)||u===null||this.validateJsonObject(u)||Array.isArray(u)&&u.every(l=>this.validateJsonObject(l)))}get attributes(){return this._attributes.all()}get original(){return this._original}get relations(){return this._relations}get fillable(){return h.make("model").schema(e).fillable}get primaryKey(){return h.make("model").schema(e).primaryKey}get timestamps(){return h.make("model").schema(e).timestamps}get casts(){return{...h.make("model").schema(e).casts,...this.timestamps?{created_at:"datetime",updated_at:"datetime"}:{}}}get isDirty(){return this._changedKeys.length>0}getAttribute(s){let u=this._attributes.get(s,null);s in this.casts&&(u=this.cast(u,this.casts[s]));const l=h.make("model")[`model${c.upperFirst(c.camelCase(e))}Get${c.upperFirst(c.camelCase(s))}Attribute`];if(typeof l!="function")throw new N("ModelFacade");return l.bind(h.make("model"))(u,this)}setAttribute(s,u){const l=h.make("model")[`model${c.upperFirst(c.camelCase(e))}Set${c.upperFirst(c.camelCase(s))}Attribute`];if(typeof l!="function")throw new N("ModelFacade");const a=l.bind(h.make("model"))(this.mutate(u,this.casts[s]),this);if(!this.validateJsonObject({[s]:a})){if(h.isProduction())throw new TypeError(`[Luminix] Attribute "${s}" in model "${e}" must be a boolean, number, string or null`);h.make("log").warning(`Invalid type for attribute "${s}" in model "${e}" after mutation.
|
|
3
3
|
This will throw an error in production.`,{key:s,value:u,mutated:a,cast:this.casts[s],item:this.toJson()});return}this._attributes.set(s,a),this.updateChangedKeys(s),this.dispatchChangeEvent({[s]:a})}getKey(){return this.getAttribute(this.primaryKey)}getKeyName(){return this.primaryKey}fill(s){const u=c.pick(s,this.fillable),l=Object.entries(u).reduce((a,[f,g])=>{const M=h.make("model")[`model${c.upperFirst(c.camelCase(e))}Set${c.upperFirst(c.camelCase(f))}Attribute`];if(typeof M!="function")throw new N("ModelFacade");return a[f]=M.bind(h.make("model"))(this.mutate(g,this.casts[f]),this),a},{});if(!this.validateJsonObject(l)){if(h.isProduction())throw new TypeError(`[Luminix] Invalid attributes for model "${e}"`);h.make("log").warning(`Invalid attributes for model "${e}" after mutation.
|
|
4
|
-
This will throw an error in production.`,{attributes:s,mutatedAttributes:l,item:this.toJson(),casts:this.casts});return}this._attributes.merge(".",l),Object.keys(l).forEach(a=>this.updateChangedKeys(a)),this.dispatchChangeEvent(l)}dump(){h.make("log").info({...this.toJson(),[Symbol.toStringTag]:c.upperFirst(c.camelCase(e))})}toJson(){const s=Object.entries(this.relations).reduce((l,[a,f])=>(f.isLoaded()&&(f.isSingle()?l[c.snakeCase(a)]=f.getLoadedItems().toJson():f.isMultiple()&&(l[c.snakeCase(a)]=f.getLoadedItems().map(g=>g.toJson()).all())),l),{}),u=h.make("model")[`model${c.upperFirst(c.camelCase(e))}Json`];if(typeof u!="function")throw new N("ModelFacade");return u.bind(h.make("model"))({...this.attributes,...s},this)}diff(){return this._changedKeys.reduce((s,u)=>(s[u]=this._attributes.get(u),s),{})}getType(){return e}relation(s){if(s===c.camelCase(s))return this.relations[c.snakeCase(s)]}getErrorBag(s){return`${this.exists?`${e}[${this.getKey()}].`:`${e}.`}${s}`}getRouteForSave(){return this.exists?[`luminix.${e}.update`,this.makePrimaryKeyReplacer()]:`luminix.${e}.store`}getRouteForUpdate(){return[`luminix.${e}.update`,this.makePrimaryKeyReplacer()]}getRouteForDelete(){return[`luminix.${e}.destroy`,this.makePrimaryKeyReplacer()]}getRouteForRefresh(){return[`luminix.${e}.show`,this.makePrimaryKeyReplacer()]}getLabel(){const{labeledBy:s}=h.make("model").schema(e);return this.getAttribute(s)}async refresh(){if(!this.exists)throw new G(e,"refresh");const{data:s}=await h.make("route").call(this.getRouteForRefresh(),{errorBag:this.getErrorBag("fetch")});this.makeAttributes(s)}async save(s={}){try{const{additionalPayload:u={},sendsOnlyModifiedFields:l=!0}=s,a=this.exists,f={...c.pick(l&&a?this.diff():this.attributes,this.fillable),...u};if(c.isEmpty(f))return;const g=await h.make("route").call(this.getRouteForSave(),{data:f,errorBag:this.getErrorBag(a?"update":"store")});if([200,201].includes(g.status))return this.makeAttributes(g.data),this.exists=!0,this.dispatchSaveEvent(),a?this.dispatchUpdateEvent(g.data):(this.wasRecentlyCreated=!0,this.dispatchCreateEvent(g.data)),g;throw g}catch(u){throw this.dispatchErrorEvent(u,"save"),u}}async push(){throw new E}async delete(){try{const s=await h.make("route").call(this.getRouteForDelete(),{errorBag:this.getErrorBag("delete")});if(s.status===204)return this.dispatchDeleteEvent(),s;throw s}catch(s){throw this.dispatchErrorEvent(s,"delete"),s}}async update(s){try{const u=await h.make("route").call(this.getRouteForUpdate(),{data:s,errorBag:this.getErrorBag("update")});if(u.status===200){this.makeAttributes(u.data),this.dispatchUpdateEvent(u.data);return}throw u}catch(u){throw this.dispatchErrorEvent(u,"save"),u}}async forceDelete(){try{const s=await h.make("route").call(this.getRouteForDelete(),{params:{force:!0},errorBag:this.getErrorBag("forceDelete")});if(s.status===204)return this.dispatchDeleteEvent(!0),s;throw s}catch(s){throw this.dispatchErrorEvent(s,"forceDelete"),s}}async restore(){try{const s=await h.make("route").call(this.getRouteForUpdate(),{params:{restore:!0},errorBag:this.getErrorBag("restore")});if(s.status===200)return this.dispatchRestoreEvent(),s;throw s}catch(s){throw this.dispatchErrorEvent(s,"restore"),s}}static getSchemaName(){return e}static getSchema(){return h.make("model").schema(e)}static query(){return new De(h.make(),e)}static where(...s){return this.query().where(...s)}static whereNull(s){return this.query().whereNull(s)}static whereNotNull(s){return this.query().whereNotNull(s)}static whereBetween(s,u){return this.query().whereBetween(s,u)}static whereNotBetween(s,u){return this.query().whereNotBetween(s,u)}static orderBy(s,u="asc"){return this.query().orderBy(s,u)}static searchBy(s){return this.query().searchBy(s)}static minified(){return this.query().minified()}static limit(s){return this.query().limit(s)}static get(s=1,u){return this.query().get(s,u)}static find(s){return this.query().find(s)}static first(){return this.query().first()}static async create(s){const u=h.make("model").make(e),l=new u;return l.fill(s),await l.save(),l}static async update(s,u){const l=h.make("model").make(e),a=new l({id:s});return a.fill(u),a.exists=!0,await a.save(),a}static delete(s){if(Array.isArray(s))return h.make("route").call(`luminix.${e}.destroyMany`,{params:{ids:s},errorBag:`${e}.deleteMany`});const u=h.make("model").make(e);return new u({id:s}).delete()}static async restore(s){if(Array.isArray(s))return h.make("route").call(`luminix.${e}.restoreMany`,{data:{ids:s},errorBag:`${e}.restoreMany`});const u=h.make("model").make(e);return new u({id:s}).restore()}static forceDelete(s){if(Array.isArray(s))return h.make("route").call(`luminix.${e}.destroyMany`,{params:{ids:s,force:!0},errorBag:`${e}.forceDeleteMany`});const u=h.make("model").make(e);return new u({id:s}).forceDelete()}static singular(){return h.make("model").schema(e).displayName.singular}static plural(){return h.make("model").schema(e).displayName.plural}on(s,u){throw new E}once(s,u){throw new E}emit(s,u){throw new E}}return p(t,"name",c.upperFirst(c.camelCase(e))),A(t)}function Ge(h,e,t){var r,i;return class extends(i=t,r=Symbol.toStringTag,i){constructor(u={}){super(u);p(this,r,c.upperFirst(c.camelCase(e)));return new Proxy(this,{get:(l,a)=>{if(a==="__isModel")return!0;if(a in l)return Reflect.get(l,a);if(a!==c.camelCase(a))return;const f=c.snakeCase(a);if(Object.keys(l.attributes).includes(f))return l.getAttribute(f);if(Object.keys(l.relations).includes(f))return l.relations[f].getLoadedItems();if(a.endsWith("Relation")&&Object.keys(l.relations).includes(c.snakeCase(a.slice(0,-8))))return()=>l.relation(a.slice(0,-8));if(h.model.hasReducer(`model${l.constructor.name}Get${c.upperFirst(a)}Attribute`)){const g=h.model[`model${l.constructor.name}Get${c.upperFirst(a)}Attribute`];if(typeof g!="function")throw new N("ModelFacade");return g.bind(h.model)(void 0,l)}return Reflect.get(l,a)},set:(l,a,f)=>a in l&&typeof l[a]!="function"?Reflect.set(l,a,f):(l.setAttribute(c.snakeCase(a),f),!0)})}}}class Ve extends(Te=Error,Me=Symbol.toStringTag,Te){constructor(t,r){super(`[Luminix] Cannot create reducer '${t}' on '${r}' as it is a reserved property`);p(this,Me,"ReducerOverrideException")}}function Q(h){return class extends h{constructor(...t){super(...t);p(this,"reducers",{});return new Proxy(this,{get(r,i,s){return typeof i=="symbol"||i in r?Reflect.get(r,i,s):(u,...l)=>{const{[i]:a=d()}=r.reducers;return w.isDraftable(u)?w.produce(u,f=>a.sortBy("priority").reduce((g,M)=>M.callback(g,...l),f)):a.sortBy("priority").reduce((f,g)=>g.callback(f,...l),u)}}})}reducer(t,r,i=10){if(t in this)throw new Ve(t,this);return this.reducers[t]||(this.reducers[t]=d()),this.reducers[t].push({callback:r,priority:i}),()=>this.removeReducer(t,r)}removeReducer(t,r){const i=this.reducers[t].search(s=>s.callback===r);i!==!1&&this.reducers[t].pull(i)}getReducer(t){return this.reducers[t]||(this.reducers[t]=d()),this.reducers[t]}hasReducer(t){return!!this.reducers[t]&&this.reducers[t].count()>0}clearReducer(t){this.reducers[t].splice(0,this.reducers[t].count())}flushReducers(){Object.values(this.reducers).forEach(t=>t.splice(0,t.count()))}}}class V extends(Se=Error,$e=Symbol.toStringTag,Se){constructor(t){super(`[Luminix] Model "${t}" not found`);p(this,$e,"ModelNotFoundException")}}class j extends(Re=TypeError,Ae=Symbol.toStringTag,Re){constructor(t,r,i){super(`[Luminix] "${t}" expects a related model of type "${r}". Received "${i}" instead.`);p(this,Ae,"ModelInvalidRelatedTypeException")}}class X extends P{constructor(e,t,r,i=null){if(!x(i)&&i!==null)throw new $("BelongsTo.constructor()","Model or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!0}isMultiple(){return!1}query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t,this.parent.getKey()),e.lock(`where.${t}`),e}get(){return this.query().first()}async associate(e){if(!x(e))throw new $("BelongsTo.associate()");if(e.getType()!==this.getRelated().getSchemaName())throw new j("BelongsTo.associate()",this.getRelated().getSchemaName(),e.getType());if(!e.exists)throw new G(this.getRelated().getSchemaName(),"save");return this.parent.update({[this.getForeignKey()]:e.getKey()})}dissociate(){return this.parent.update({[this.getForeignKey()]:null})}}class Y extends P{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof C&&i.every(x)))throw new $("BelongsToMany.constructor()","Collection<Model> or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!1}isMultiple(){return!0}query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t,this.parent.getKey()),e.lock(`where.${t}`),e}get(e=1,t){return this.query().get(e,t)}all(){return this.query().all()}first(){return this.query().first()}find(e){return this.query().find(e)}attachQuietly(e,t={}){return this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:attach`,{[this.parent.getKeyName()]:this.parent.getKey(),itemId:e}],{data:t,errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:attach`})}async attach(e,t={}){if(await this.attachQuietly(e,t),this.items){const r=this.items.search(s=>s.getKey()===e),i=await this.getRelated().find(e);if(!i)return;r!==!1?this.items.put(r,i):this.items.push(i)}else this.items=await this.all()}async detachQuietly(e){await this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:detach`,{[this.parent.getKeyName()]:this.parent.getKey(),itemId:e}],{errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:detach`})}async detach(e){if(await this.detachQuietly(e),this.items){const t=this.items.search(r=>r.getKey()===e);t!==!1&&this.items.pull(t)}}async syncQuietly(e){await this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:sync`,{[this.parent.getKeyName()]:this.parent.getKey()}],{data:e,errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:sync`})}async syncWithPivotValuesQuietly(e,t){await this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:sync`,{[this.parent.getKeyName()]:this.parent.getKey()}],{data:e.map(r=>({[this.getRelated().getSchema().primaryKey]:r,...t})),errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:sync`})}async sync(e){await this.syncQuietly(e);const t=await this.all();this.items?this.items.splice(0,this.items.count(),...t):this.items=t}async syncWithPivotValues(e,t){await this.syncWithPivotValuesQuietly(e,t);const r=await this.all();this.items?this.items.splice(0,this.items.count(),...r):this.items=r}}class U extends P{query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t,this.parent.getKey()),e.lock(`where.${t}`),e}async saveQuietly(e){if(!x(e))throw new $("HasOneOrMany.saveQuietly()");if(e.getType()!==this.getRelated().getSchemaName())throw new j("HasOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),e.getType());e.setAttribute(this.getForeignKey(),this.parent.getKey()),await e.save()}}class Xe extends U{constructor(e,t,r,i=null){if(!x(i)&&i!==null)throw new $("HasOne.constructor()","Model or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!0}isMultiple(){return!1}get(){return this.query().first()}async save(e){await this.saveQuietly(e),this.items=e}}class Ye extends U{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof C&&i.every(x)))throw new $("HasMany.constructor()","Collection<Model> or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!1}isMultiple(){return!0}get(e=1,t){return this.query().get(e,t)}all(){return this.query().all()}first(){return this.query().first()}find(e){return this.query().find(e)}async saveManyQuietly(e){if(!Array.isArray(e)||!e.every(x))throw new $("HasMany.saveManyQuietly()","Model[]");if(!e.every(t=>t.getType()===this.getRelated().getSchemaName()))throw new j("HasMany.saveManyQuietly()",this.getRelated().getSchemaName(),e.map(t=>t.getType()).join(", "));await Promise.all(e.map(t=>(t.setAttribute(this.getForeignKey(),this.parent.getKey()),t.save())))}async saveMany(e){await this.saveManyQuietly(e);const t=await this.all();this.items?this.items.splice(0,this.items.count(),...t):this.items=t}async save(e){await this.saveQuietly(e),this.items===null?this.items=await this.all():this.items.push(e)}}class Z extends U{query(){const e=this.getRelated().query();e.once("success",r=>{this.items=r.items});const t=this.guessInverseRelation();return e.where(t+"_id",this.parent.getKey()),e.where(t+"_type",this.getRelated().getSchemaName()),e.lock(`where.${t}_id`),e.lock(`where.${t}_type`),e}async saveQuietly(e){if(!x(e))throw new $("MorphOneOrMany.saveQuietly()");if(e.getType()!==this.getRelated().getSchemaName())throw new j("MorphOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),e.getType());const t=this.guessInverseRelation();e.setAttribute(t+"_id",this.parent.getKey()),e.setAttribute(t+"_type",this.parent.getType()),await e.save()}}class Ze extends Z{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof C&&i.every(x)))throw new $("MorphMany.constructor()","Collection<Model> or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!1}isMultiple(){return!0}get(e=1,t){return this.query().get(e,t)}all(){return this.query().all()}first(){return this.query().first()}find(e){return this.query().find(e)}async saveManyQuietly(e){if(!Array.isArray(e)||!e.every(x))throw new $("MorphMany.saveManyQuietly()");if(!e.every(t=>t.getType()===this.getRelated().getSchemaName()))throw new j("MorphMany.saveManyQuietly()",this.getRelated().getSchemaName(),e.map(t=>t.getType()).join(", "));await Promise.all(e.map(t=>(t.setAttribute(this.getName()+"_id",this.parent.getKey()),t.setAttribute(this.getName()+"_type",this.parent.getType()),t.save())))}async save(e){await this.saveQuietly(e),this.items?this.items.push(e):this.items=await this.all()}async saveMany(e){await this.saveManyQuietly(e);const t=await this.all();this.items?this.items.splice(0,this.items.count(),...t):this.items=t}}class ze extends Z{constructor(e,t,r,i=null){if(super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i,i!==null&&!x(i))throw new $("MorphOne.constructor()","Model or null")}isSingle(){return!0}isMultiple(){return!1}get(){return this.query().first()}async save(e){await this.saveQuietly(e),this.items=e}}class Oe extends X{getRelated(){return this.facades.model.make(this.parent.getAttribute(this.getName()+"_type"))}async associate(e){if(!x(e))throw new $("MorphTo.associate()");return e.exists||await e.save(),this.parent.update({[this.getName()+"_id"]:e.getKey(),[this.getName()+"_type"]:e.getType()})}dissociate(){return this.parent.update({[this.getName()+"_id"]:null,[this.getName()+"_type"]:null})}}class et extends Y{constructor(e,t,r,i=null){super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t+"_id",this.parent.getKey()),e.where(t+"_type",this.parent.getType()),e.lock(`where.${t}_id`),e.lock(`where.${t}_type`),e}}ve=Symbol.toStringTag;class tt{constructor(e){p(this,"_models",{});p(this,ve,"ModelFacade");this._schema=e}boot(e){this._schema&&(Object.keys(this._schema).forEach(t=>{const r=this[`model${c.upperFirst(c.camelCase(t))}`];if(typeof this.model!="function"||typeof r!="function")throw new N("ModelFacade");const i=this.model(We(e,t),t),s=r(i);this._models[t]=Ge(e.make(),t,s)}),this.reducer("relationMap",()=>({BelongsTo:X,BelongsToMany:Y,HasOne:Xe,HasMany:Ye,MorphMany:Ze,MorphOne:ze,MorphTo:Oe,MorphToMany:et}),0))}schema(e){if(!this._schema||e&&!this._schema[e])throw new V(e||"undefined");return e?this._schema[e]:this._schema}make(e){if(e&&!this._models[e])throw new V(e);return e?this._models[e]:this._models}toString(){return"model"}on(e,t){throw new E}once(e,t){throw new E}emit(e,t){throw new E}reducer(e,t,r){throw new E}removeReducer(e){throw new E}getReducer(e){throw new E}hasReducer(e){throw new E}clearReducer(e){throw new E}flushReducers(){throw new E}}const rt=A(Q(tt));class st extends(_e=Error,Ne=Symbol.toStringTag,_e){constructor(){super("[Luminix] Embed element not found. Make sure to include the `@luminixEmbed()` directive in your Blade template.");p(this,Ne,"NoEmbedException")}}const z=(h,e="data")=>{if(!document.querySelector("#luminix-embed"))throw new st;const t=document.getElementById(`luminix-${e}::`+h);return t?t.dataset.json&&t.dataset.value?JSON.parse(t.dataset.value):t.dataset.value:null},O=A(q),ee=h=>_.isAxiosError(h)&&h.response!==void 0&&h.response.data!==null&&"message"in h.response.data&&typeof h.response.data.message=="string"&&"errors"in h.response.data&&typeof h.response.data.errors=="object"&&h.response.data.errors!==null&&Object.values(h.response.data.errors).every(e=>Array.isArray(e)&&e.every(t=>typeof t=="string"))&&h.response.status===422;let it=class{constructor(){p(this,"bags");const e={};document.querySelectorAll('#luminix-embed [id^="luminix-error"]').forEach(r=>{const s=r.id.replace("luminix-error::","");e[s]=z(s,"error")}),this.bags={default:new O(e)}}bag(e="default"){return this.bags[e]||(this.bags[e]=new O({})),this.bags[e]}add(e,t,r="default"){this.bag(r).set(e,t)}set(e,t="default"){this.bag(t).set(".",e)}all(e="default"){return this.bag(e).all()}get(e,t="default"){return this.bag(t).get(e,null)}clear(e="default"){this.bag(e).set(".",{})}};class nt extends(qe=Error,Be=Symbol.toStringTag,qe){constructor(t){super(`[Luminix] Route "${t}" not found`);p(this,Be,"RouteNotFoundException")}}class ot{constructor(e,t,r=""){this.routes=e,this.error=t,this.appUrl=r}isRouteTuple(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,...r]=e;if(typeof t!="string")return!1;const i=["get","post","put","patch","delete"];return!!r.every(s=>i.includes(s))}extractGenerator(e){let t,r=!1;return Array.isArray(e)?[t,r]=e:t=e,[t,r]}get(e){if(!this.exists(e))throw new nt(e);return c.get(this.routes,e)}url(e){const[t,r]=this.extractGenerator(e),i=this.get(t)[0].replace(/^\/|\/$/g,""),s=/{([^}]+)}/g;if(r===!1){if(typeof this.replaceRouteParams!="function")throw new N("RouteFacade");return this.appUrl+this.replaceRouteParams(`/${i}`)}const u=i.match(s),l=u?u.map(T=>T.slice(1,-1)):[],a=Object.keys(r),f=l.filter(T=>!a.includes(T)),g=a.filter(T=>!l.includes(T));if(f.length>0)throw new TypeError(`Missing values for parameter(s): ${f.join(", ")}`);if(g.length>0)throw new TypeError(`Unexpected parameters: ${g.join(", ")}`);const M=l.reduce((T,S)=>T.replace(`{${S}}`,`${r[S]}`),i);return this.appUrl+`/${M}`}methods(e){const[t]=this.extractGenerator(e);return this.get(t).slice(1)}exists(e){return c.has(this.routes,e)&&this.isRouteTuple(c.get(this.routes,e))}async call(e,t={}){if(typeof this.axiosOptions!="function"||typeof this.axiosError!="function")throw new N("RouteFacade");const[r,i]=this.extractGenerator(e),[,...s]=this.get(r),u=this.url(i?[r,i]:r),l=this.axiosOptions(t,r),{method:a=s[0],errorBag:f="default",...g}=l,{data:M,...T}=g;this.error.clear(f);try{return["get","delete"].includes(a)?await _[a](u,g):await _[a](u,M,T)}catch(S){if(ee(S)){const{errors:L}=S.response.data;this.error.set(Object.entries(L).reduce((F,[b,yt])=>(F[b]=yt.join(" "),F),{}),f)}else _.isAxiosError(S)&&this.error.set(this.axiosError({axios:S.message},{error:S,name:r,replace:i,config:t}),f);throw S}}toString(){return"route"}}const ht=Q(ot);class ut{constructor(){p(this,"facades",{});p(this,"booted",!1);p(this,"_plugins",[])}make(e=void 0){if(!e)return this.facades;if(e in this.facades)return this.facades[e]}has(e){return!!this.facades[e]}bind(e,t){this.facades[e]||(this.facades[e]=t)}plugins(){return this._plugins}async boot(e={}){var f,g,M,T,S,L,F;if(this.booted)throw new window.Error("[Luminix] App already booted");this.booted=!0,(f=e.app)!=null&&f.debug&&console.log("[Luminix] Booting started..."),this.emit("init",{register:b=>{this._plugins.push(b),typeof b.register=="function"&&b.register(this)}});const t=(((g=e.app)==null?void 0:g.url)??"")+(((M=e.app)==null?void 0:M.bootUrl)??"/luminix-api/init");if(document.getElementById("luminix-data::config")){if(document.getElementById("luminix-data::config")){const b=z("config");b&&typeof b=="object"&&c.merge(e,b)}}else try{const{data:b}=await _.get(t);b&&typeof b=="object"&&c.merge(e,b)}catch(b){(T=e.app)!=null&&T.debug&&console.error(b)}this.bind("log",new ke(!!((S=e.app)!=null&&S.debug)));const{log:r}=this.facades,{manifest:{routes:i={},models:s={}}={},...u}=e;this.bind("config",new q(u)),this.facades.config.has("auth.user")||this.facades.config.set("auth.user",null),this.facades.config.lock("auth.user");const l=new URL(((L=e.app)==null?void 0:L.url)??"http://localhost"),a=((F=e.app)==null?void 0:F.port)??"";a&&(l.port=`${a}`),this.bind("error",new it),this.bind("route",new ht(i,this.facades.error,l.toString())),this.bind("model",new rt(s)),this.bind("auth",new Le(this)),this.emit("booting");for(const b of Object.values(this.facades))typeof b=="object"&&b!==null&&"boot"in b&&typeof b.boot=="function"&&b.boot(this);for(const b of this._plugins)typeof b.boot=="function"&&b.boot(this.facades);return r.info("[Luminix] App boot completed",{config:this.facades.config.all(),plugins:this._plugins,manifest:{routes:i,models:s}}),this.emit("booted"),this.facades}environment(...e){return e.length>0?e.includes(this.facades.config.get("app.env","production")):this.facades.config.get("app.env","production")}getLocale(){return this.facades.config.get("app.locale","en")}getPlugin(e){for(const t of this._plugins)if(t instanceof e)return t}hasDebugModeEnabled(){return this.facades.config.get("app.debug",!1)}isLocal(){return this.facades.config.get("app.env","production")==="local"}isProduction(){return this.facades.config.get("app.env","production")==="production"}on(e,t){throw new window.Error("Method not implemented.")}once(e,t){throw new window.Error("Method not implemented.")}emit(e,t){throw new window.Error("Method not implemented.")}}const te=A(ut);let y;function B(h=void 0){if(y||(y=new te),typeof h!="string")return{boot:y.boot.bind(y),make:y.make.bind(y),plugins:y.plugins.bind(y),on:y.once.bind(y),environment:y.environment.bind(y),getLocale:y.getLocale.bind(y),getPlugin:y.getPlugin.bind(y),hasDebugModeEnabled:y.hasDebugModeEnabled.bind(y),isLocal:y.isLocal.bind(y),isProduction:y.isProduction.bind(y),setInstance:e=>y=e};if(!y.has(h))throw new Pe(h);return y.make(h)}function at(){return B("auth")}function lt(h){return d(h)}function ct(h,e){const t=B("config");return typeof h>"u"?t:t.get(h,e)}function dt(h,e="default"){return h?B().make("error").get(h,e):B().make("error")}function ft(...h){const e=B("log");return h.length?e.debug(...h):e}function mt(h){const e=B("model");return h?e.make(h):e}function pt(h,e=!1){const t=B("route");return h?e?t.url([h,e]):t.url(h):t}class gt{constructor(){p(this,"name");p(this,"version")}register(e){}boot(e){}}m.App=te,m.HasEvents=A,m.Plugin=gt,m.PropertyBag=q,m.Reducible=Q,m.app=B,m.auth=at,m.collect=lt,m.config=ct,m.error=dt,m.isCollection=R,m.isModel=x,m.isValidationError=ee,m.log=ft,m.model=mt,m.route=pt,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|
|
4
|
+
This will throw an error in production.`,{attributes:s,mutatedAttributes:l,item:this.toJson(),casts:this.casts});return}this._attributes.merge(".",l),Object.keys(l).forEach(a=>this.updateChangedKeys(a)),this.dispatchChangeEvent(l)}dump(){h.make("log").info({...this.toJson(),[Symbol.toStringTag]:c.upperFirst(c.camelCase(e))})}toJson(){const s=Object.entries(this.relations).reduce((l,[a,f])=>(f.isLoaded()&&(f.isSingle()?l[c.snakeCase(a)]=f.getLoadedItems().toJson():f.isMultiple()&&(l[c.snakeCase(a)]=f.getLoadedItems().map(g=>g.toJson()).all())),l),{}),u=h.make("model")[`model${c.upperFirst(c.camelCase(e))}Json`];if(typeof u!="function")throw new N("ModelFacade");return u.bind(h.make("model"))({...this.attributes,...s},this)}diff(){return this._changedKeys.reduce((s,u)=>(s[u]=this._attributes.get(u),s),{})}getType(){return e}relation(s){if(s===c.camelCase(s))return this.relations[c.snakeCase(s)]}getErrorBag(s){return`${this.exists?`${e}[${this.getKey()}].`:`${e}.`}${s}`}getRouteForSave(){return this.exists?[`luminix.${e}.update`,this.makePrimaryKeyReplacer()]:`luminix.${e}.store`}getRouteForUpdate(){return[`luminix.${e}.update`,this.makePrimaryKeyReplacer()]}getRouteForDelete(){return[`luminix.${e}.destroy`,this.makePrimaryKeyReplacer()]}getRouteForRefresh(){return[`luminix.${e}.show`,this.makePrimaryKeyReplacer()]}getLabel(){const{labeledBy:s}=h.make("model").schema(e);return this.getAttribute(s)}async refresh(){if(!this.exists)throw new G(e,"refresh");const{data:s}=await h.make("route").call(this.getRouteForRefresh(),{errorBag:this.getErrorBag("fetch")});this.makeAttributes(s)}async save(s={}){try{const{additionalPayload:u={},sendsOnlyModifiedFields:l=!0}=s,a=this.exists,f={...c.pick(l&&a?this.diff():this.attributes,this.fillable),...u};if(c.isEmpty(f))return;const g=await h.make("route").call(this.getRouteForSave(),{data:f,errorBag:this.getErrorBag(a?"update":"store")});if([200,201].includes(g.status))return this.makeAttributes(g.data),this.exists=!0,this.dispatchSaveEvent(),a?this.dispatchUpdateEvent(g.data):(this.wasRecentlyCreated=!0,this.dispatchCreateEvent(g.data)),g;throw g}catch(u){throw this.dispatchErrorEvent(u,"save"),u}}async push(){throw new E}async delete(){try{const s=await h.make("route").call(this.getRouteForDelete(),{errorBag:this.getErrorBag("delete")});if(s.status===204)return this.dispatchDeleteEvent(),s;throw s}catch(s){throw this.dispatchErrorEvent(s,"delete"),s}}async update(s){try{const u=await h.make("route").call(this.getRouteForUpdate(),{data:s,errorBag:this.getErrorBag("update")});if(u.status===200){this.makeAttributes(u.data),this.dispatchUpdateEvent(u.data);return}throw u}catch(u){throw this.dispatchErrorEvent(u,"save"),u}}async forceDelete(){try{const s=await h.make("route").call(this.getRouteForDelete(),{params:{force:!0},errorBag:this.getErrorBag("forceDelete")});if(s.status===204)return this.dispatchDeleteEvent(!0),s;throw s}catch(s){throw this.dispatchErrorEvent(s,"forceDelete"),s}}async restore(){try{const s=await h.make("route").call(this.getRouteForUpdate(),{params:{restore:!0},errorBag:this.getErrorBag("restore")});if(s.status===200)return this.dispatchRestoreEvent(),s;throw s}catch(s){throw this.dispatchErrorEvent(s,"restore"),s}}static getSchemaName(){return e}static getSchema(){return h.make("model").schema(e)}static query(){return new De(h.make(),e)}static where(...s){return this.query().where(...s)}static whereNull(s){return this.query().whereNull(s)}static whereNotNull(s){return this.query().whereNotNull(s)}static whereBetween(s,u){return this.query().whereBetween(s,u)}static whereNotBetween(s,u){return this.query().whereNotBetween(s,u)}static orderBy(s,u="asc"){return this.query().orderBy(s,u)}static searchBy(s){return this.query().searchBy(s)}static minified(){return this.query().minified()}static limit(s){return this.query().limit(s)}static get(s=1,u){return this.query().get(s,u)}static find(s){return this.query().find(s)}static first(){return this.query().first()}static async create(s){const u=h.make("model").make(e),l=new u;return l.fill(s),await l.save(),l}static async update(s,u){const l=h.make("model").make(e),a=new l({id:s});return a.fill(u),a.exists=!0,await a.save(),a}static delete(s){if(Array.isArray(s))return h.make("route").call(`luminix.${e}.destroyMany`,{params:{ids:s},errorBag:`${e}.deleteMany`});const u=h.make("model").make(e);return new u({id:s}).delete()}static async restore(s){if(Array.isArray(s))return h.make("route").call(`luminix.${e}.restoreMany`,{data:{ids:s},errorBag:`${e}.restoreMany`});const u=h.make("model").make(e);return new u({id:s}).restore()}static forceDelete(s){if(Array.isArray(s))return h.make("route").call(`luminix.${e}.destroyMany`,{params:{ids:s,force:!0},errorBag:`${e}.forceDeleteMany`});const u=h.make("model").make(e);return new u({id:s}).forceDelete()}static singular(){return h.make("model").schema(e).displayName.singular}static plural(){return h.make("model").schema(e).displayName.plural}on(s,u){throw new E}once(s,u){throw new E}emit(s,u){throw new E}}return p(t,"name",c.upperFirst(c.camelCase(e))),A(t)}function Ge(h,e,t){var r,i;return class extends(i=t,r=Symbol.toStringTag,i){constructor(u={}){super(u);p(this,r,c.upperFirst(c.camelCase(e)));return new Proxy(this,{get:(l,a)=>{if(a==="__isModel")return!0;if(a in l)return Reflect.get(l,a);if(a!==c.camelCase(a))return;const f=c.snakeCase(a);if(Object.keys(l.attributes).includes(f))return l.getAttribute(f);if(Object.keys(l.relations).includes(f))return l.relations[f].getLoadedItems();if(a.endsWith("Relation")&&Object.keys(l.relations).includes(c.snakeCase(a.slice(0,-8))))return()=>l.relation(a.slice(0,-8));if(h.model.hasReducer(`model${l.constructor.name}Get${c.upperFirst(a)}Attribute`)){const g=h.model[`model${l.constructor.name}Get${c.upperFirst(a)}Attribute`];if(typeof g!="function")throw new N("ModelFacade");return g.bind(h.model)(void 0,l)}return Reflect.get(l,a)},set:(l,a,f)=>a in l&&typeof l[a]!="function"?Reflect.set(l,a,f):(l.setAttribute(c.snakeCase(a),f),!0)})}}}class Ve extends(Te=Error,Me=Symbol.toStringTag,Te){constructor(t,r){super(`[Luminix] Cannot create reducer '${t}' on '${r}' as it is a reserved property`);p(this,Me,"ReducerOverrideException")}}function Q(h){return class extends h{constructor(...t){super(...t);p(this,"reducers",{});return new Proxy(this,{get(r,i,s){return typeof i=="symbol"||i in r?Reflect.get(r,i,s):(u,...l)=>{const{[i]:a=d()}=r.reducers;return w.isDraftable(u)?w.produce(u,f=>a.sortBy("priority").reduce((g,M)=>M.callback(g,...l),f)):a.sortBy("priority").reduce((f,g)=>g.callback(f,...l),u)}}})}reducer(t,r,i=10){if(t in this)throw new Ve(t,this);return this.reducers[t]||(this.reducers[t]=d()),this.reducers[t].push({callback:r,priority:i}),()=>this.removeReducer(t,r)}removeReducer(t,r){const i=this.reducers[t].search(s=>s.callback===r);i!==!1&&this.reducers[t].pull(i)}getReducer(t){return this.reducers[t]||(this.reducers[t]=d()),this.reducers[t]}hasReducer(t){return!!this.reducers[t]&&this.reducers[t].count()>0}clearReducer(t){this.reducers[t].splice(0,this.reducers[t].count())}flushReducers(){Object.values(this.reducers).forEach(t=>t.splice(0,t.count()))}}}class V extends(Se=Error,$e=Symbol.toStringTag,Se){constructor(t){super(`[Luminix] Model "${t}" not found`);p(this,$e,"ModelNotFoundException")}}class j extends(Re=TypeError,Ae=Symbol.toStringTag,Re){constructor(t,r,i){super(`[Luminix] "${t}" expects a related model of type "${r}". Received "${i}" instead.`);p(this,Ae,"ModelInvalidRelatedTypeException")}}class X extends P{constructor(e,t,r,i=null){if(!x(i)&&i!==null)throw new $("BelongsTo.constructor()","Model or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!0}isMultiple(){return!1}query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t,this.parent.getKey()),e.lock(`where.${t}`),e}get(){return this.query().first()}async associate(e){if(!x(e))throw new $("BelongsTo.associate()");if(e.getType()!==this.getRelated().getSchemaName())throw new j("BelongsTo.associate()",this.getRelated().getSchemaName(),e.getType());if(!e.exists)throw new G(this.getRelated().getSchemaName(),"save");return this.parent.update({[this.getForeignKey()]:e.getKey()})}dissociate(){return this.parent.update({[this.getForeignKey()]:null})}}class Y extends P{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof C&&i.every(x)))throw new $("BelongsToMany.constructor()","Collection<Model> or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!1}isMultiple(){return!0}query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t,this.parent.getKey()),e.lock(`where.${t}`),e}get(e=1,t){return this.query().get(e,t)}all(){return this.query().all()}first(){return this.query().first()}find(e){return this.query().find(e)}attachQuietly(e,t={}){return this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:attach`,{[this.parent.getKeyName()]:this.parent.getKey(),itemId:e}],{data:t,errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:attach`})}async attach(e,t={}){if(await this.attachQuietly(e,t),this.items){const r=this.items.search(s=>s.getKey()===e),i=await this.getRelated().find(e);if(!i)return;r!==!1?this.items.put(r,i):this.items.push(i)}else this.items=await this.all()}async detachQuietly(e){await this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:detach`,{[this.parent.getKeyName()]:this.parent.getKey(),itemId:e}],{errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:detach`})}async detach(e){if(await this.detachQuietly(e),this.items){const t=this.items.search(r=>r.getKey()===e);t!==!1&&this.items.pull(t)}}async syncQuietly(e){await this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:sync`,{[this.parent.getKeyName()]:this.parent.getKey()}],{data:e,errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:sync`})}async syncWithPivotValuesQuietly(e,t){await this.facades.route.call([`luminix.${this.parent.getType()}.${this.getName()}:sync`,{[this.parent.getKeyName()]:this.parent.getKey()}],{data:e.map(r=>({[this.getRelated().getSchema().primaryKey]:r,...t})),errorBag:`${this.parent.getType()}[${this.parent.getKey()}].${this.getName()}:sync`})}async sync(e){await this.syncQuietly(e);const t=await this.all();this.items?this.items.splice(0,this.items.count(),...t):this.items=t}async syncWithPivotValues(e,t){await this.syncWithPivotValuesQuietly(e,t);const r=await this.all();this.items?this.items.splice(0,this.items.count(),...r):this.items=r}}class U extends P{query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t,this.parent.getKey()),e.lock(`where.${t}`),e}async saveQuietly(e){if(!x(e))throw new $("HasOneOrMany.saveQuietly()");if(e.getType()!==this.getRelated().getSchemaName())throw new j("HasOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),e.getType());e.setAttribute(this.getForeignKey(),this.parent.getKey()),await e.save()}}class Xe extends U{constructor(e,t,r,i=null){if(!x(i)&&i!==null)throw new $("HasOne.constructor()","Model or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!0}isMultiple(){return!1}get(){return this.query().first()}async save(e){await this.saveQuietly(e),this.items=e}}class Ye extends U{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof C&&i.every(x)))throw new $("HasMany.constructor()","Collection<Model> or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!1}isMultiple(){return!0}get(e=1,t){return this.query().get(e,t)}all(){return this.query().all()}first(){return this.query().first()}find(e){return this.query().find(e)}async saveManyQuietly(e){if(!Array.isArray(e)||!e.every(x))throw new $("HasMany.saveManyQuietly()","Model[]");if(!e.every(t=>t.getType()===this.getRelated().getSchemaName()))throw new j("HasMany.saveManyQuietly()",this.getRelated().getSchemaName(),e.map(t=>t.getType()).join(", "));await Promise.all(e.map(t=>(t.setAttribute(this.getForeignKey(),this.parent.getKey()),t.save())))}async saveMany(e){await this.saveManyQuietly(e);const t=await this.all();this.items?this.items.splice(0,this.items.count(),...t):this.items=t}async save(e){await this.saveQuietly(e),this.items===null?this.items=await this.all():this.items.push(e)}}class Z extends U{query(){const e=this.getRelated().query();e.once("success",r=>{this.items=r.items});const t=this.guessInverseRelation();return e.where(t+"_id",this.parent.getKey()),e.where(t+"_type",this.getRelated().getSchemaName()),e.lock(`where.${t}_id`),e.lock(`where.${t}_type`),e}async saveQuietly(e){if(!x(e))throw new $("MorphOneOrMany.saveQuietly()");if(e.getType()!==this.getRelated().getSchemaName())throw new j("MorphOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),e.getType());const t=this.guessInverseRelation();e.setAttribute(t+"_id",this.parent.getKey()),e.setAttribute(t+"_type",this.parent.getType()),await e.save()}}class Ze extends Z{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof C&&i.every(x)))throw new $("MorphMany.constructor()","Collection<Model> or null");super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}isSingle(){return!1}isMultiple(){return!0}get(e=1,t){return this.query().get(e,t)}all(){return this.query().all()}first(){return this.query().first()}find(e){return this.query().find(e)}async saveManyQuietly(e){if(!Array.isArray(e)||!e.every(x))throw new $("MorphMany.saveManyQuietly()");if(!e.every(t=>t.getType()===this.getRelated().getSchemaName()))throw new j("MorphMany.saveManyQuietly()",this.getRelated().getSchemaName(),e.map(t=>t.getType()).join(", "));await Promise.all(e.map(t=>(t.setAttribute(this.getName()+"_id",this.parent.getKey()),t.setAttribute(this.getName()+"_type",this.parent.getType()),t.save())))}async save(e){await this.saveQuietly(e),this.items?this.items.push(e):this.items=await this.all()}async saveMany(e){await this.saveManyQuietly(e);const t=await this.all();this.items?this.items.splice(0,this.items.count(),...t):this.items=t}}class ze extends Z{constructor(e,t,r,i=null){if(super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i,i!==null&&!x(i))throw new $("MorphOne.constructor()","Model or null")}isSingle(){return!0}isMultiple(){return!1}get(){return this.query().first()}async save(e){await this.saveQuietly(e),this.items=e}}class Oe extends X{getRelated(){return this.facades.model.make(this.parent.getAttribute(this.getName()+"_type"))}async associate(e){if(!x(e))throw new $("MorphTo.associate()");return e.exists||await e.save(),this.parent.update({[this.getName()+"_id"]:e.getKey(),[this.getName()+"_type"]:e.getType()})}dissociate(){return this.parent.update({[this.getName()+"_id"]:null,[this.getName()+"_type"]:null})}}class et extends Y{constructor(e,t,r,i=null){super(e,t,r,i),this.meta=e,this.facades=t,this.parent=r,this.items=i}query(){const e=super.query(),t=this.guessInverseRelation();return e.where(t+"_id",this.parent.getKey()),e.where(t+"_type",this.parent.getType()),e.lock(`where.${t}_id`),e.lock(`where.${t}_type`),e}}ve=Symbol.toStringTag;class tt{constructor(e){p(this,"_models",{});p(this,ve,"ModelFacade");this._schema=e}boot(e){this._schema&&(Object.keys(this._schema).forEach(t=>{const r=this[`model${c.upperFirst(c.camelCase(t))}`];if(typeof this.model!="function"||typeof r!="function")throw new N("ModelFacade");const i=this.model(We(e,t),t),s=r(i);this._models[t]=Ge(e.make(),t,s)}),this.reducer("relationMap",()=>({BelongsTo:X,BelongsToMany:Y,HasOne:Xe,HasMany:Ye,MorphMany:Ze,MorphOne:ze,MorphTo:Oe,MorphToMany:et}),0))}schema(e){if(!this._schema||e&&!this._schema[e])throw new V(e||"undefined");return e?this._schema[e]:this._schema}make(e){if(e&&!this._models[e])throw new V(e);return e?this._models[e]:this._models}toString(){return"model"}on(e,t){throw new E}once(e,t){throw new E}emit(e,t){throw new E}reducer(e,t,r){throw new E}removeReducer(e){throw new E}getReducer(e){throw new E}hasReducer(e){throw new E}clearReducer(e){throw new E}flushReducers(){throw new E}}const rt=A(Q(tt));class st extends(_e=Error,Ne=Symbol.toStringTag,_e){constructor(){super("[Luminix] Embed element not found. Make sure to include the `@luminixEmbed()` directive in your Blade template.");p(this,Ne,"NoEmbedException")}}const z=(h,e="data")=>{if(!document.querySelector("#luminix-embed"))throw new st;const t=document.getElementById(`luminix-${e}::`+h);return t?t.dataset.json&&t.dataset.value?JSON.parse(t.dataset.value):t.dataset.value:null},O=A(q),ee=h=>_.isAxiosError(h)&&h.response!==void 0&&h.response.data!==null&&"message"in h.response.data&&typeof h.response.data.message=="string"&&"errors"in h.response.data&&typeof h.response.data.errors=="object"&&h.response.data.errors!==null&&Object.values(h.response.data.errors).every(e=>Array.isArray(e)&&e.every(t=>typeof t=="string"))&&h.response.status===422;let it=class{constructor(){p(this,"bags");const e={};document.querySelectorAll('#luminix-embed [id^="luminix-error"]').forEach(r=>{const s=r.id.replace("luminix-error::","");e[s]=z(s,"error")}),this.bags={default:new O(e)}}bag(e="default"){return this.bags[e]||(this.bags[e]=new O({})),this.bags[e]}add(e,t,r="default"){this.bag(r).set(e,t)}set(e,t="default"){this.bag(t).set(".",e)}all(e="default"){return this.bag(e).all()}get(e,t="default"){return this.bag(t).get(e,null)}clear(e="default"){this.bag(e).set(".",{})}};class nt extends(qe=Error,Be=Symbol.toStringTag,qe){constructor(t){super(`[Luminix] Route "${t}" not found`);p(this,Be,"RouteNotFoundException")}}class ot{constructor(e,t,r=""){this.routes=e,this.error=t,this.appUrl=r}isRouteTuple(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,...r]=e;if(typeof t!="string")return!1;const i=["get","post","put","patch","delete"];return!!r.every(s=>i.includes(s))}extractGenerator(e){let t,r=!1;return Array.isArray(e)?[t,r]=e:t=e,[t,r]}get(e){if(!this.exists(e))throw new nt(e);return c.get(this.routes,e)}url(e){const[t,r]=this.extractGenerator(e),i=this.get(t)[0].replace(/^\/|\/$/g,""),s=/{([^}]+)}/g;if(r===!1){if(typeof this.replaceRouteParams!="function")throw new N("RouteFacade");return this.appUrl+this.replaceRouteParams(`/${i}`)}const u=i.match(s),l=u?u.map(T=>T.slice(1,-1)):[],a=Object.keys(r),f=l.filter(T=>!a.includes(T)),g=a.filter(T=>!l.includes(T));if(f.length>0)throw new TypeError(`Missing values for parameter(s): ${f.join(", ")}`);if(g.length>0)throw new TypeError(`Unexpected parameters: ${g.join(", ")}`);const M=l.reduce((T,S)=>T.replace(`{${S}}`,`${r[S]}`),i);return this.appUrl+`/${M}`}methods(e){const[t]=this.extractGenerator(e);return this.get(t).slice(1)}exists(e){return c.has(this.routes,e)&&this.isRouteTuple(c.get(this.routes,e))}async call(e,t={}){if(typeof this.axiosOptions!="function"||typeof this.axiosError!="function")throw new N("RouteFacade");const[r,i]=this.extractGenerator(e),[,...s]=this.get(r),u=this.url(i?[r,i]:r),l=this.axiosOptions(t,r),{method:a=s[0],errorBag:f="default",...g}=l,{data:M,...T}=g;this.error.clear(f);try{return["get","delete"].includes(a)?await _[a](u,g):await _[a](u,M,T)}catch(S){if(ee(S)){const{errors:L}=S.response.data;this.error.set(Object.entries(L).reduce((F,[b,yt])=>(F[b]=yt.join(" "),F),{}),f)}else _.isAxiosError(S)&&this.error.set(this.axiosError({axios:S.message},{error:S,name:r,replace:i,config:t}),f);throw S}}toString(){return"route"}}const ht=Q(ot);class ut{constructor(){p(this,"facades",{});p(this,"booted",!1);p(this,"_plugins",[])}make(e=void 0){if(!e)return this.facades;if(e in this.facades)return this.facades[e]}has(e){return!!this.facades[e]}bind(e,t){this.facades[e]||(this.facades[e]=t)}plugins(){return this._plugins}async boot(e={}){var f,g,M,T,S,L,F;if(this.booted)throw new window.Error("[Luminix] App already booted");this.booted=!0,(f=e.app)!=null&&f.debug&&console.log("[Luminix] Booting started..."),this.emit("init",{register:b=>{this._plugins.push(b),typeof b.register=="function"&&b.register(this)}});const t=(((g=e.app)==null?void 0:g.url)??"")+(((M=e.app)==null?void 0:M.bootUrl)??"/luminix-api/init");if(document.getElementById("luminix-data::config")){if(document.getElementById("luminix-data::config")){const b=z("config");b&&typeof b=="object"&&c.merge(e,b)}}else try{const{data:b}=await _.get(t);b&&typeof b=="object"&&c.merge(e,b)}catch(b){(T=e.app)!=null&&T.debug&&console.error(b)}this.bind("log",new ke(!!((S=e.app)!=null&&S.debug)));const{log:r}=this.facades,{manifest:{routes:i={},models:s={}}={},...u}=e;this.bind("config",new q(u)),this.facades.config.has("auth.user")||this.facades.config.set("auth.user",null),this.facades.config.lock("auth.user");const l=new URL(((L=e.app)==null?void 0:L.url)??"http://localhost"),a=((F=e.app)==null?void 0:F.port)??"";a&&(l.port=`${a}`),this.bind("error",new it),this.bind("route",new ht(i,this.facades.error,c.trim(l.toString(),"/"))),this.bind("model",new rt(s)),this.bind("auth",new Le(this)),this.emit("booting");for(const b of Object.values(this.facades))typeof b=="object"&&b!==null&&"boot"in b&&typeof b.boot=="function"&&b.boot(this);for(const b of this._plugins)typeof b.boot=="function"&&b.boot(this.facades);return r.info("[Luminix] App boot completed",{config:this.facades.config.all(),plugins:this._plugins,manifest:{routes:i,models:s}}),this.emit("booted"),this.facades}environment(...e){return e.length>0?e.includes(this.facades.config.get("app.env","production")):this.facades.config.get("app.env","production")}getLocale(){return this.facades.config.get("app.locale","en")}getPlugin(e){for(const t of this._plugins)if(t instanceof e)return t}hasDebugModeEnabled(){return this.facades.config.get("app.debug",!1)}isLocal(){return this.facades.config.get("app.env","production")==="local"}isProduction(){return this.facades.config.get("app.env","production")==="production"}on(e,t){throw new window.Error("Method not implemented.")}once(e,t){throw new window.Error("Method not implemented.")}emit(e,t){throw new window.Error("Method not implemented.")}}const te=A(ut);let y;function B(h=void 0){if(y||(y=new te),typeof h!="string")return{boot:y.boot.bind(y),make:y.make.bind(y),plugins:y.plugins.bind(y),on:y.once.bind(y),environment:y.environment.bind(y),getLocale:y.getLocale.bind(y),getPlugin:y.getPlugin.bind(y),hasDebugModeEnabled:y.hasDebugModeEnabled.bind(y),isLocal:y.isLocal.bind(y),isProduction:y.isProduction.bind(y),setInstance:e=>y=e};if(!y.has(h))throw new Pe(h);return y.make(h)}function at(){return B("auth")}function lt(h){return d(h)}function ct(h,e){const t=B("config");return typeof h>"u"?t:t.get(h,e)}function dt(h,e="default"){return h?B().make("error").get(h,e):B().make("error")}function ft(...h){const e=B("log");return h.length?e.debug(...h):e}function mt(h){const e=B("model");return h?e.make(h):e}function pt(h,e=!1){const t=B("route");return h?e?t.url([h,e]):t.url(h):t}class gt{constructor(){p(this,"name");p(this,"version")}register(e){}boot(e){}}m.App=te,m.HasEvents=A,m.Plugin=gt,m.PropertyBag=q,m.Reducible=Q,m.app=B,m.auth=at,m.collect=lt,m.config=ct,m.error=dt,m.isCollection=R,m.isModel=x,m.isValidationError=ee,m.log=ft,m.model=mt,m.route=pt,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|