@luminix/core 0.0.1-beta.17 → 0.0.1-beta.18
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 +2 -1
- package/dist/core.umd.cjs +2 -2
- package/dist/types/App.d.ts +2 -1
- package/package.json +1 -1
package/dist/core.js
CHANGED
|
@@ -2494,7 +2494,8 @@ function A(n = void 0) {
|
|
|
2494
2494
|
getPlugin: y.getPlugin.bind(y),
|
|
2495
2495
|
hasDebugModeEnabled: y.hasDebugModeEnabled.bind(y),
|
|
2496
2496
|
isLocal: y.isLocal.bind(y),
|
|
2497
|
-
isProduction: y.isProduction.bind(y)
|
|
2497
|
+
isProduction: y.isProduction.bind(y),
|
|
2498
|
+
setInstance: (e) => y = e
|
|
2498
2499
|
};
|
|
2499
2500
|
if (!y.has(n))
|
|
2500
2501
|
throw new ke(n);
|
package/dist/core.umd.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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,N){"use strict";var wt=Object.defineProperty;var Be=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),C=(m,c,w)=>c.has(m)||Be("Cannot "+w);var o=(m,c,w)=>(C(m,c,"read from private field"),w?w.call(m):c.get(m)),Q=(m,c,w)=>c.has(m)?Be("Cannot add the same private member more than once"):c instanceof WeakSet?c.add(m):c.set(m,w),qe=(m,c,w,N)=>(C(m,c,"write to private field"),N?N.call(m,w):c.set(m,w),w),Ie=(m,c,w)=>(C(m,c,"access private method"),w);var z,ee,te,re,se,ie,n,ne,oe,he,ue,ae,le,ce,de,fe,me,pe,ge,ye,we,be,Ee,xe,Me,Te,$e,Se,Ae,Re,ve,Ne;class Fe extends(ee=Error,z=Symbol.toStringTag,ee){constructor(t){super(`[Luminix] Facade "${t}" not found`);p(this,z,"FacadeNotFoundException")}}class Ke{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 Pe{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 B{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 B(this.bag)}all(){return this.bag}isEmpty(){return c.isEmpty(this.bag)}on(e,t){return()=>null}once(e,t){}emit(e,t){}}function S(h){var e,t,r,je,s;return s=class extends(t=h,e=Symbol.toStringTag,t){constructor(...a){super(...a);Q(this,r);p(this,"emitter");p(this,e,h.name);this.emitter=Ie(this,r,je).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,je=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 D(...h){return h.reduce((e,t)=>e.flatMap(r=>t.map(i=>[r,i].flat())))}function A(h){return!(typeof h!="object"||h===null||!Reflect.has(h,"constructor")||Reflect.get(h.constructor,"name")!=="Collection")}class E extends(re=Error,te=Symbol.toStringTag,re){constructor(){super("[Luminix] Method not implemented.");p(this,te,"MethodNotImplementedException")}}function d(h=[],e=K){if(!Array.isArray(h))throw new TypeError("collect() expects an array");return new(S(e))([...h])}const R=h=>{h.emit("change",{items:h.all()})},j=(h,e)=>Array.isArray(h)?h[e]??null:h.get(e);class K{constructor(e=[]){Q(this,n);p(this,se,"Collection");qe(this,n,e)}get items(){return[...o(this,n)]}[(ie=Symbol.iterator,se=Symbol.toStringTag,ie)](){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]=j(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(D(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)&&!A(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),R(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 D(...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)&&!A(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([j(i,s-1),j(i,s)]).avg():j(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(!A(t)&&!Array.isArray(t))throw new TypeError("The pipeline expects the carry to be a collection or an array");return r(A(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 R(this),e===1?t[0]??null:d(t)}prepend(e){const t=o(this,n).unshift(e);return R(this),t}pull(e){const t=o(this,n).splice(e,1)[0]??null;return R(this),t}push(...e){const t=o(this,n).push(...e);return R(this),t}put(e,t){return o(this,n).splice(e,1,t),R(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 R(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 R(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 R(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 P=S(K);class U extends(oe=K,ne=Symbol.toStringTag,oe){constructor(){super(...arguments);p(this,ne,"Collection")}intersect(t){return this.filter(r=>t.some(i=>i.getKey()===r.getKey()))}}const q=(...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 Le extends(ue=Error,he=Symbol.toStringTag,ue){constructor(t){super(`[Luminix] Model "${t}" does not have a primary key`);p(this,he,"ModelWithoutPrimaryKeyException")}}const ke=S(B);class Ce{constructor(e,t,r={}){p(this,"bag");this.facades=e,this.abstract=t,this.query=r,this.bag=new ke(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}),U);if(t){const[u]=t.split("?");return{...r,data:s,links:{first:`${u}?${q(t,r.links.first).toString()}`,last:`${u}?${q(t,r.links.last).toString()}`,next:r.links.next&&`${u}?${q(t,r.links.next).toString()}`,prev:r.links.prev&&`${u}?${q(t,r.links.prev).toString()}`},meta:{...r.meta,links:r.meta.links.map(l=>({...l,url:l.url&&`${u}?${q(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 Le(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(),U);return this.emit("success",{response:{...t,data:u},items:u}),u}}const Qe=S(Ce);class v extends(le=Error,ae=Symbol.toStringTag,le){constructor(t){super(`[Luminix] Expected ${t} to be reducible.`);p(this,ae,"NotReducibleException")}}class $ extends(de=TypeError,ce=Symbol.toStringTag,de){constructor(t,r="Model"){super(`[Luminix] "${t}" expects ${r}`);p(this,ce,"NotModelException")}}class De extends(me=Error,fe=Symbol.toStringTag,me){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,fe,"NoInverseRelationException")}}class Ue extends(ge=Error,pe=Symbol.toStringTag,ge){constructor(t){super(`[Luminix] Relation "${t}" is not supported`);p(this,pe,"UnsupportedRelationException")}}function x(h){return typeof h=="object"&&h!==null&&h.__isModel===!0}class F{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)&&!(A(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 v("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 Ue(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 De(this.parent.getType(),t,this.getRelated().getSchemaName(),r[t].join(" or "))}set(e){if(e!==null&&!x(e)&&!(A(e)&&e.every(x)))throw new $("Relation.set()","Model, Collection<Model> or null");!this.items||x(this.items)?this.items=e:A(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 A(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 J extends(we=Error,ye=Symbol.toStringTag,we){constructor(t,r){super(`[Luminix] Model "${t}" must be persisted before calling "${r}"`);p(this,ye,"ModelNotPersistedException")}}function Je(h,e){var r;r=Symbol.toStringTag;class t{constructor(s={}){p(this,"_attributes",new B({}));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]:F;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}".
|
|
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,b,N){"use strict";var wt=Object.defineProperty;var Be=m=>{throw TypeError(m)};var bt=(m,c,b)=>c in m?wt(m,c,{enumerable:!0,configurable:!0,writable:!0,value:b}):m[c]=b;var p=(m,c,b)=>bt(m,typeof c!="symbol"?c+"":c,b),C=(m,c,b)=>c.has(m)||Be("Cannot "+b);var o=(m,c,b)=>(C(m,c,"read from private field"),b?b.call(m):c.get(m)),Q=(m,c,b)=>c.has(m)?Be("Cannot add the same private member more than once"):c instanceof WeakSet?c.add(m):c.set(m,b),qe=(m,c,b,N)=>(C(m,c,"write to private field"),N?N.call(m,b):c.set(m,b),b),Ie=(m,c,b)=>(C(m,c,"access private method"),b);var z,ee,te,re,se,ie,n,ne,oe,he,ue,ae,le,ce,de,fe,me,pe,ge,ye,we,be,Ee,xe,Me,Te,$e,Se,Ae,Re,ve,Ne;class Fe extends(ee=Error,z=Symbol.toStringTag,ee){constructor(t){super(`[Luminix] Facade "${t}" not found`);p(this,z,"FacadeNotFoundException")}}class Ke{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 Pe{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 B{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=b.produce(this.bag,()=>t),this.emit("change",{path:e,value:t,type:"set"});return}this.bag=b.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=b.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=b.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 B(this.bag)}all(){return this.bag}isEmpty(){return c.isEmpty(this.bag)}on(e,t){return()=>null}once(e,t){}emit(e,t){}}function S(h){var e,t,r,je,s;return s=class extends(t=h,e=Symbol.toStringTag,t){constructor(...a){super(...a);Q(this,r);p(this,"emitter");p(this,e,h.name);this.emitter=Ie(this,r,je).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,je=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 D(...h){return h.reduce((e,t)=>e.flatMap(r=>t.map(i=>[r,i].flat())))}function A(h){return!(typeof h!="object"||h===null||!Reflect.has(h,"constructor")||Reflect.get(h.constructor,"name")!=="Collection")}class E extends(re=Error,te=Symbol.toStringTag,re){constructor(){super("[Luminix] Method not implemented.");p(this,te,"MethodNotImplementedException")}}function d(h=[],e=K){if(!Array.isArray(h))throw new TypeError("collect() expects an array");return new(S(e))([...h])}const R=h=>{h.emit("change",{items:h.all()})},j=(h,e)=>Array.isArray(h)?h[e]??null:h.get(e);class K{constructor(e=[]){Q(this,n);p(this,se,"Collection");qe(this,n,e)}get items(){return[...o(this,n)]}[(ie=Symbol.iterator,se=Symbol.toStringTag,ie)](){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]=j(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(D(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)&&!A(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),R(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 D(...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)&&!A(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([j(i,s-1),j(i,s)]).avg():j(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(!A(t)&&!Array.isArray(t))throw new TypeError("The pipeline expects the carry to be a collection or an array");return r(A(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 R(this),e===1?t[0]??null:d(t)}prepend(e){const t=o(this,n).unshift(e);return R(this),t}pull(e){const t=o(this,n).splice(e,1)[0]??null;return R(this),t}push(...e){const t=o(this,n).push(...e);return R(this),t}put(e,t){return o(this,n).splice(e,1,t),R(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 R(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 R(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 R(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 P=S(K);class U extends(oe=K,ne=Symbol.toStringTag,oe){constructor(){super(...arguments);p(this,ne,"Collection")}intersect(t){return this.filter(r=>t.some(i=>i.getKey()===r.getKey()))}}const q=(...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 Le extends(ue=Error,he=Symbol.toStringTag,ue){constructor(t){super(`[Luminix] Model "${t}" does not have a primary key`);p(this,he,"ModelWithoutPrimaryKeyException")}}const ke=S(B);class Ce{constructor(e,t,r={}){p(this,"bag");this.facades=e,this.abstract=t,this.query=r,this.bag=new ke(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}),U);if(t){const[u]=t.split("?");return{...r,data:s,links:{first:`${u}?${q(t,r.links.first).toString()}`,last:`${u}?${q(t,r.links.last).toString()}`,next:r.links.next&&`${u}?${q(t,r.links.next).toString()}`,prev:r.links.prev&&`${u}?${q(t,r.links.prev).toString()}`},meta:{...r.meta,links:r.meta.links.map(l=>({...l,url:l.url&&`${u}?${q(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 Le(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(),U);return this.emit("success",{response:{...t,data:u},items:u}),u}}const Qe=S(Ce);class v extends(le=Error,ae=Symbol.toStringTag,le){constructor(t){super(`[Luminix] Expected ${t} to be reducible.`);p(this,ae,"NotReducibleException")}}class $ extends(de=TypeError,ce=Symbol.toStringTag,de){constructor(t,r="Model"){super(`[Luminix] "${t}" expects ${r}`);p(this,ce,"NotModelException")}}class De extends(me=Error,fe=Symbol.toStringTag,me){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,fe,"NoInverseRelationException")}}class Ue extends(ge=Error,pe=Symbol.toStringTag,ge){constructor(t){super(`[Luminix] Relation "${t}" is not supported`);p(this,pe,"UnsupportedRelationException")}}function x(h){return typeof h=="object"&&h!==null&&h.__isModel===!0}class F{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)&&!(A(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 v("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 Ue(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 De(this.parent.getType(),t,this.getRelated().getSchemaName(),r[t].join(" or "))}set(e){if(e!==null&&!x(e)&&!(A(e)&&e.every(x)))throw new $("Relation.set()","Model, Collection<Model> or null");!this.items||x(this.items)?this.items=e:A(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 A(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 J extends(we=Error,ye=Symbol.toStringTag,we){constructor(t,r){super(`[Luminix] Model "${t}" must be persisted before calling "${r}"`);p(this,ye,"ModelNotPersistedException")}}function Je(h,e){var r;r=Symbol.toStringTag;class t{constructor(s={}){p(this,"_attributes",new B({}));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]:F;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 v("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 v("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 v("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 v("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 J(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 Qe(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))),S(t)}function He(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 v("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 We extends(Ee=Error,be=Symbol.toStringTag,Ee){constructor(t,r){super(`[Luminix] Cannot create reducer '${t}' on '${r}' as it is a reserved property`);p(this,be,"ReducerOverrideException")}}function L(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 We(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 H extends(Me=Error,xe=Symbol.toStringTag,Me){constructor(t){super(`[Luminix] Model "${t}" not found`);p(this,xe,"ModelNotFoundException")}}class I extends($e=TypeError,Te=Symbol.toStringTag,$e){constructor(t,r,i){super(`[Luminix] "${t}" expects a related model of type "${r}". Received "${i}" instead.`);p(this,Te,"ModelInvalidRelatedTypeException")}}class W extends F{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 I("BelongsTo.associate()",this.getRelated().getSchemaName(),e.getType());if(!e.exists)throw new J(this.getRelated().getSchemaName(),"save");return this.parent.update({[this.getForeignKey()]:e.getKey()})}dissociate(){return this.parent.update({[this.getForeignKey()]:null})}}class G extends F{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof P&&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 k extends F{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 I("HasOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),e.getType());e.setAttribute(this.getForeignKey(),this.parent.getKey()),await e.save()}}class Ge extends k{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 Ve extends k{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof P&&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 I("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 V extends k{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 I("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 Oe extends V{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof P&&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 I("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 Xe extends V{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 Ye extends W{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 Ze extends G{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}}Se=Symbol.toStringTag;class ze{constructor(e){p(this,"_models",{});p(this,Se,"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 v("ModelFacade");const i=this.model(Je(e,t),t),s=r(i);this._models[t]=He(e.make(),t,s)}),this.reducer("relationMap",()=>({BelongsTo:W,BelongsToMany:G,HasOne:Ge,HasMany:Ve,MorphMany:Oe,MorphOne:Xe,MorphTo:Ye,MorphToMany:Ze}),0))}schema(e){if(!this._schema||e&&!this._schema[e])throw new H(e||"undefined");return e?this._schema[e]:this._schema}make(e){if(e&&!this._models[e])throw new H(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 et=S(L(ze));class tt extends(Re=Error,Ae=Symbol.toStringTag,Re){constructor(){super("[Luminix] Embed element not found. Make sure to include the `@luminixEmbed()` directive in your Blade template.");p(this,Ae,"NoEmbedException")}}const O=(h,e="data")=>{if(!document.querySelector("#luminix-embed"))throw new tt;const t=document.getElementById(`luminix-${e}::`+h);return t?t.dataset.json&&t.dataset.value?JSON.parse(t.dataset.value):t.dataset.value:null},X=S(B),Y=h=>N.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 rt=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]=O(s,"error")}),this.bags={default:new X(e)}}bag(e="default"){return this.bags[e]||(this.bags[e]=new X({})),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 st extends(Ne=Error,ve=Symbol.toStringTag,Ne){constructor(t){super(`[Luminix] Route "${t}" not found`);p(this,ve,"RouteNotFoundException")}}class it{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 st(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 v("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,y)=>T.replace(`{${y}}`,`${r[y]}`),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 v("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 N[a](u,g):await N[a](u,M,T)}catch(y){if(Y(y)){const{errors:pt}=y.response.data;this.error.set(Object.entries(pt).reduce((_e,[gt,yt])=>(_e[gt]=yt.join(" "),_e),{}),f)}else N.isAxiosError(y)&&this.error.set(this.axiosError({axios:y.message},{error:y,name:r,replace:i,config:t}),f);throw y}}toString(){return"route"}}const nt=L(it);class ot{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 l,a,f,g,M,T;if(this.booted)throw new window.Error("[Luminix] App already booted");this.booted=!0,(l=e.app)!=null&&l.debug&&console.log("[Luminix] Booting started..."),this.emit("init",{register:y=>{this._plugins.push(y),typeof y.register=="function"&&y.register(this)}});const t=(((a=e.app)==null?void 0:a.url)??"")+(((f=e.app)==null?void 0:f.bootUrl)??"/luminix-api/init");if(document.getElementById("luminix-data::config")){if(document.getElementById("luminix-data::config")){const y=O("config");y&&typeof y=="object"&&c.merge(e,y)}}else try{const{data:y}=await N.get(t);y&&typeof y=="object"&&c.merge(e,y)}catch(y){(g=e.app)!=null&&g.debug&&console.error(y)}this.bind("log",new Pe(!!((M=e.app)!=null&&M.debug)));const{log:r}=this.facades,{manifest:{routes:i={},models:s={}}={},...u}=e;this.bind("config",new B(u)),this.facades.config.has("auth.user")||this.facades.config.set("auth.user",null),this.facades.config.lock("auth.user"),this.bind("error",new rt),this.bind("route",new nt(i,this.facades.error,((T=e.app)==null?void 0:T.url)??"")),this.bind("model",new et(s)),this.bind("auth",new Ke(this)),this.emit("booting");for(const y of Object.values(this.facades))typeof y=="object"&&y!==null&&"boot"in y&&typeof y.boot=="function"&&y.boot(this);for(const y of this._plugins)typeof y.boot=="function"&&y.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 Z=S(ot);let b;function _(h=void 0){if(b||(b=new Z),typeof h!="string")return{boot:b.boot.bind(b),make:b.make.bind(b),plugins:b.plugins.bind(b),on:b.once.bind(b),environment:b.environment.bind(b),getLocale:b.getLocale.bind(b),getPlugin:b.getPlugin.bind(b),hasDebugModeEnabled:b.hasDebugModeEnabled.bind(b),isLocal:b.isLocal.bind(b),isProduction:b.isProduction.bind(b)};if(!b.has(h))throw new Fe(h);return b.make(h)}function ht(){return _("auth")}function ut(h){return d(h)}function at(h,e){const t=_("config");return typeof h>"u"?t:t.get(h,e)}function lt(h,e="default"){return h?_().make("error").get(h,e):_().make("error")}function ct(...h){const e=_("log");return h.length?e.debug(...h):e}function dt(h){const e=_("model");return h?e.make(h):e}function ft(h,e=!1){const t=_("route");return h?e?t.url([h,e]):t.url(h):t}class mt{constructor(){p(this,"name");p(this,"version")}register(e){}boot(e){}}m.App=Z,m.HasEvents=S,m.Plugin=mt,m.PropertyBag=B,m.Reducible=L,m.app=_,m.auth=ht,m.collect=ut,m.config=at,m.error=lt,m.isCollection=A,m.isModel=x,m.isValidationError=Y,m.log=ct,m.model=dt,m.route=ft,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 v("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 J(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 Qe(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))),S(t)}function He(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 v("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 We extends(Ee=Error,be=Symbol.toStringTag,Ee){constructor(t,r){super(`[Luminix] Cannot create reducer '${t}' on '${r}' as it is a reserved property`);p(this,be,"ReducerOverrideException")}}function L(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 b.isDraftable(u)?b.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 We(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 H extends(Me=Error,xe=Symbol.toStringTag,Me){constructor(t){super(`[Luminix] Model "${t}" not found`);p(this,xe,"ModelNotFoundException")}}class I extends($e=TypeError,Te=Symbol.toStringTag,$e){constructor(t,r,i){super(`[Luminix] "${t}" expects a related model of type "${r}". Received "${i}" instead.`);p(this,Te,"ModelInvalidRelatedTypeException")}}class W extends F{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 I("BelongsTo.associate()",this.getRelated().getSchemaName(),e.getType());if(!e.exists)throw new J(this.getRelated().getSchemaName(),"save");return this.parent.update({[this.getForeignKey()]:e.getKey()})}dissociate(){return this.parent.update({[this.getForeignKey()]:null})}}class G extends F{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof P&&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 k extends F{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 I("HasOneOrMany.saveQuietly()",this.getRelated().getSchemaName(),e.getType());e.setAttribute(this.getForeignKey(),this.parent.getKey()),await e.save()}}class Ge extends k{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 Ve extends k{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof P&&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 I("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 V extends k{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 I("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 Oe extends V{constructor(e,t,r,i=null){if(i!==null&&!(i instanceof P&&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 I("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 Xe extends V{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 Ye extends W{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 Ze extends G{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}}Se=Symbol.toStringTag;class ze{constructor(e){p(this,"_models",{});p(this,Se,"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 v("ModelFacade");const i=this.model(Je(e,t),t),s=r(i);this._models[t]=He(e.make(),t,s)}),this.reducer("relationMap",()=>({BelongsTo:W,BelongsToMany:G,HasOne:Ge,HasMany:Ve,MorphMany:Oe,MorphOne:Xe,MorphTo:Ye,MorphToMany:Ze}),0))}schema(e){if(!this._schema||e&&!this._schema[e])throw new H(e||"undefined");return e?this._schema[e]:this._schema}make(e){if(e&&!this._models[e])throw new H(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 et=S(L(ze));class tt extends(Re=Error,Ae=Symbol.toStringTag,Re){constructor(){super("[Luminix] Embed element not found. Make sure to include the `@luminixEmbed()` directive in your Blade template.");p(this,Ae,"NoEmbedException")}}const O=(h,e="data")=>{if(!document.querySelector("#luminix-embed"))throw new tt;const t=document.getElementById(`luminix-${e}::`+h);return t?t.dataset.json&&t.dataset.value?JSON.parse(t.dataset.value):t.dataset.value:null},X=S(B),Y=h=>N.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 rt=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]=O(s,"error")}),this.bags={default:new X(e)}}bag(e="default"){return this.bags[e]||(this.bags[e]=new X({})),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 st extends(Ne=Error,ve=Symbol.toStringTag,Ne){constructor(t){super(`[Luminix] Route "${t}" not found`);p(this,ve,"RouteNotFoundException")}}class it{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 st(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 v("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,y)=>T.replace(`{${y}}`,`${r[y]}`),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 v("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 N[a](u,g):await N[a](u,M,T)}catch(y){if(Y(y)){const{errors:pt}=y.response.data;this.error.set(Object.entries(pt).reduce((_e,[gt,yt])=>(_e[gt]=yt.join(" "),_e),{}),f)}else N.isAxiosError(y)&&this.error.set(this.axiosError({axios:y.message},{error:y,name:r,replace:i,config:t}),f);throw y}}toString(){return"route"}}const nt=L(it);class ot{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 l,a,f,g,M,T;if(this.booted)throw new window.Error("[Luminix] App already booted");this.booted=!0,(l=e.app)!=null&&l.debug&&console.log("[Luminix] Booting started..."),this.emit("init",{register:y=>{this._plugins.push(y),typeof y.register=="function"&&y.register(this)}});const t=(((a=e.app)==null?void 0:a.url)??"")+(((f=e.app)==null?void 0:f.bootUrl)??"/luminix-api/init");if(document.getElementById("luminix-data::config")){if(document.getElementById("luminix-data::config")){const y=O("config");y&&typeof y=="object"&&c.merge(e,y)}}else try{const{data:y}=await N.get(t);y&&typeof y=="object"&&c.merge(e,y)}catch(y){(g=e.app)!=null&&g.debug&&console.error(y)}this.bind("log",new Pe(!!((M=e.app)!=null&&M.debug)));const{log:r}=this.facades,{manifest:{routes:i={},models:s={}}={},...u}=e;this.bind("config",new B(u)),this.facades.config.has("auth.user")||this.facades.config.set("auth.user",null),this.facades.config.lock("auth.user"),this.bind("error",new rt),this.bind("route",new nt(i,this.facades.error,((T=e.app)==null?void 0:T.url)??"")),this.bind("model",new et(s)),this.bind("auth",new Ke(this)),this.emit("booting");for(const y of Object.values(this.facades))typeof y=="object"&&y!==null&&"boot"in y&&typeof y.boot=="function"&&y.boot(this);for(const y of this._plugins)typeof y.boot=="function"&&y.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 Z=S(ot);let w;function _(h=void 0){if(w||(w=new Z),typeof h!="string")return{boot:w.boot.bind(w),make:w.make.bind(w),plugins:w.plugins.bind(w),on:w.once.bind(w),environment:w.environment.bind(w),getLocale:w.getLocale.bind(w),getPlugin:w.getPlugin.bind(w),hasDebugModeEnabled:w.hasDebugModeEnabled.bind(w),isLocal:w.isLocal.bind(w),isProduction:w.isProduction.bind(w),setInstance:e=>w=e};if(!w.has(h))throw new Fe(h);return w.make(h)}function ht(){return _("auth")}function ut(h){return d(h)}function at(h,e){const t=_("config");return typeof h>"u"?t:t.get(h,e)}function lt(h,e="default"){return h?_().make("error").get(h,e):_().make("error")}function ct(...h){const e=_("log");return h.length?e.debug(...h):e}function dt(h){const e=_("model");return h?e.make(h):e}function ft(h,e=!1){const t=_("route");return h?e?t.url([h,e]):t.url(h):t}class mt{constructor(){p(this,"name");p(this,"version")}register(e){}boot(e){}}m.App=Z,m.HasEvents=S,m.Plugin=mt,m.PropertyBag=B,m.Reducible=L,m.app=_,m.auth=ht,m.collect=ut,m.config=at,m.error=lt,m.isCollection=A,m.isModel=x,m.isValidationError=Y,m.log=ct,m.model=dt,m.route=ft,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|
package/dist/types/App.d.ts
CHANGED
|
@@ -56,8 +56,9 @@ export type AppExternal = {
|
|
|
56
56
|
hasDebugModeEnabled(): boolean;
|
|
57
57
|
isLocal(): boolean;
|
|
58
58
|
isProduction(): boolean;
|
|
59
|
+
setInstance(app: AppFacade): void;
|
|
59
60
|
};
|
|
60
|
-
export type AppFacade = AppExternal & {
|
|
61
|
+
export type AppFacade = Omit<AppExternal, 'setInstance'> & {
|
|
61
62
|
has(key: string): boolean;
|
|
62
63
|
bind<T extends keyof AppFacades>(key: T, facade: AppFacades[T]): void;
|
|
63
64
|
emit: EventSource<AppEvents>['emit'];
|