@stonecrop/stonecrop 0.7.9 → 0.8.0
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/src/composable.d.ts +8 -0
- package/dist/src/composable.d.ts.map +1 -1
- package/dist/src/composable.js +129 -0
- package/dist/src/registry.d.ts +59 -0
- package/dist/src/registry.d.ts.map +1 -1
- package/dist/src/registry.js +166 -0
- package/dist/src/stonecrop.d.ts.map +1 -1
- package/dist/src/stonecrop.js +6 -3
- package/dist/src/stores/hst.d.ts +5 -0
- package/dist/src/stores/hst.d.ts.map +1 -1
- package/dist/src/stores/hst.js +10 -3
- package/dist/stonecrop.d.ts +163 -1
- package/dist/stonecrop.js +917 -729
- package/dist/stonecrop.js.map +1 -1
- package/dist/stonecrop.umd.cjs +3 -3
- package/dist/stonecrop.umd.cjs.map +1 -1
- package/package.json +3 -3
- package/src/composable.ts +166 -0
- package/src/registry.ts +189 -0
- package/src/stonecrop.ts +6 -3
- package/src/stores/hst.ts +13 -3
package/dist/stonecrop.umd.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(I,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],a):(I=typeof globalThis<"u"?globalThis:I||self,a(I["@stonecrop/stonecrop"]={},I.Vue))})(this,(function(I,a){"use strict";const Y=typeof window<"u";let J;const ae=n=>J=n;process.env.NODE_ENV;const de=process.env.NODE_ENV!=="production"?Symbol("pinia"):Symbol();function G(n){return n&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"&&typeof n.toJSON!="function"}var oe;(function(n){n.direct="direct",n.patchObject="patch object",n.patchFunction="patch function"})(oe||(oe={}));function we(n,e){for(const t in e){const r=e[t];if(!(t in n))continue;const o=n[t];G(o)&&G(r)&&!a.isRef(r)&&!a.isReactive(r)?n[t]=we(o,r):n[t]=r}return n}const Ee=()=>{};function Re(n,e,t,r=Ee){n.add(e);const o=()=>{n.delete(e)&&r()};return!t&&a.getCurrentScope()&&a.onScopeDispose(o),o}function X(n,...e){n.forEach(t=>{t(...e)})}const Fe=n=>n(),Oe=Symbol(),pe=Symbol();function he(n,e){n instanceof Map&&e instanceof Map?e.forEach((t,r)=>n.set(r,t)):n instanceof Set&&e instanceof Set&&e.forEach(n.add,n);for(const t in e){if(!e.hasOwnProperty(t))continue;const r=e[t],o=n[t];G(o)&&G(r)&&n.hasOwnProperty(t)&&!a.isRef(r)&&!a.isReactive(r)?n[t]=he(o,r):n[t]=r}return n}const xe=process.env.NODE_ENV!=="production"?Symbol("pinia:skipHydration"):Symbol();function je(n){return!G(n)||!Object.prototype.hasOwnProperty.call(n,xe)}const{assign:H}=Object;function Ae(n){return!!(a.isRef(n)&&n.effect)}function Pe(n,e,t,r){const{state:o,actions:s,getters:i}=e,c=t.state.value[n];let l;function d(){!c&&(process.env.NODE_ENV==="production"||!r)&&(t.state.value[n]=o?o():{});const m=process.env.NODE_ENV!=="production"&&r?a.toRefs(a.ref(o?o():{}).value):a.toRefs(t.state.value[n]);return H(m,s,Object.keys(i||{}).reduce((w,P)=>(process.env.NODE_ENV!=="production"&&P in m&&console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${P}" in store "${n}".`),w[P]=a.markRaw(a.computed(()=>{ae(t);const $=t._s.get(n);return i[P].call($,$)})),w),{}))}return l=ge(n,d,e,t,r,!0),l}function ge(n,e,t={},r,o,s){let i;const c=H({actions:{}},t);if(process.env.NODE_ENV!=="production"&&!r._e.active)throw new Error("Pinia destroyed");const l={deep:!0};process.env.NODE_ENV!=="production"&&(l.onTrigger=p=>{d?$=p:d==!1&&!y._hotUpdating&&(Array.isArray($)?$.push(p):console.error("🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug."))});let d,m,w=new Set,P=new Set,$;const L=r.state.value[n];!s&&!L&&(process.env.NODE_ENV==="production"||!o)&&(r.state.value[n]={});const x=a.ref({});let _;function D(p){let h;d=m=!1,process.env.NODE_ENV!=="production"&&($=[]),typeof p=="function"?(p(r.state.value[n]),h={type:oe.patchFunction,storeId:n,events:$}):(he(r.state.value[n],p),h={type:oe.patchObject,payload:p,storeId:n,events:$});const A=_=Symbol();a.nextTick().then(()=>{_===A&&(d=!0)}),m=!0,X(w,h,r.state.value[n])}const N=s?function(){const{state:h}=t,A=h?h():{};this.$patch(B=>{H(B,A)})}:process.env.NODE_ENV!=="production"?()=>{throw new Error(`🍍: Store "${n}" is built using the setup syntax and does not implement $reset().`)}:Ee;function b(){i.stop(),w.clear(),P.clear(),r._s.delete(n)}const V=(p,h="")=>{if(Oe in p)return p[pe]=h,p;const A=function(){ae(r);const B=Array.from(arguments),E=new Set,C=new Set;function M(S){E.add(S)}function v(S){C.add(S)}X(P,{args:B,name:A[pe],store:y,after:M,onError:v});let R;try{R=p.apply(this&&this.$id===n?this:y,B)}catch(S){throw X(C,S),S}return R instanceof Promise?R.then(S=>(X(E,S),S)).catch(S=>(X(C,S),Promise.reject(S))):(X(E,R),R)};return A[Oe]=!0,A[pe]=h,A},O=a.markRaw({actions:{},getters:{},state:[],hotState:x}),T={_p:r,$id:n,$onAction:Re.bind(null,P),$patch:D,$reset:N,$subscribe(p,h={}){const A=Re(w,p,h.detached,()=>B()),B=i.run(()=>a.watch(()=>r.state.value[n],E=>{(h.flush==="sync"?m:d)&&p({storeId:n,type:oe.direct,events:$},E)},H({},l,h)));return A},$dispose:b},y=a.reactive(process.env.NODE_ENV!=="production"||process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="test"&&Y?H({_hmrPayload:O,_customProperties:a.markRaw(new Set)},T):T);r._s.set(n,y);const j=(r._a&&r._a.runWithContext||Fe)(()=>r._e.run(()=>(i=a.effectScope()).run(()=>e({action:V}))));for(const p in j){const h=j[p];if(a.isRef(h)&&!Ae(h)||a.isReactive(h))process.env.NODE_ENV!=="production"&&o?x.value[p]=a.toRef(j,p):s||(L&&je(h)&&(a.isRef(h)?h.value=L[p]:he(h,L[p])),r.state.value[n][p]=h),process.env.NODE_ENV!=="production"&&O.state.push(p);else if(typeof h=="function"){const A=process.env.NODE_ENV!=="production"&&o?h:V(h,p);j[p]=A,process.env.NODE_ENV!=="production"&&(O.actions[p]=h),c.actions[p]=h}else process.env.NODE_ENV!=="production"&&Ae(h)&&(O.getters[p]=s?t.getters[p]:h,Y&&(j._getters||(j._getters=a.markRaw([]))).push(p))}if(H(y,j),H(a.toRaw(y),j),Object.defineProperty(y,"$state",{get:()=>process.env.NODE_ENV!=="production"&&o?x.value:r.state.value[n],set:p=>{if(process.env.NODE_ENV!=="production"&&o)throw new Error("cannot set hotState");D(h=>{H(h,p)})}}),process.env.NODE_ENV!=="production"&&(y._hotUpdate=a.markRaw(p=>{y._hotUpdating=!0,p._hmrPayload.state.forEach(h=>{if(h in y.$state){const A=p.$state[h],B=y.$state[h];typeof A=="object"&&G(A)&&G(B)?we(A,B):p.$state[h]=B}y[h]=a.toRef(p.$state,h)}),Object.keys(y.$state).forEach(h=>{h in p.$state||delete y[h]}),d=!1,m=!1,r.state.value[n]=a.toRef(p._hmrPayload,"hotState"),m=!0,a.nextTick().then(()=>{d=!0});for(const h in p._hmrPayload.actions){const A=p[h];y[h]=V(A,h)}for(const h in p._hmrPayload.getters){const A=p._hmrPayload.getters[h],B=s?a.computed(()=>(ae(r),A.call(y,y))):A;y[h]=B}Object.keys(y._hmrPayload.getters).forEach(h=>{h in p._hmrPayload.getters||delete y[h]}),Object.keys(y._hmrPayload.actions).forEach(h=>{h in p._hmrPayload.actions||delete y[h]}),y._hmrPayload=p._hmrPayload,y._getters=p._getters,y._hotUpdating=!1})),process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="test"&&Y){const p={writable:!0,configurable:!0,enumerable:!1};["_p","_hmrPayload","_getters","_customProperties"].forEach(h=>{Object.defineProperty(y,h,H({value:y[h]},p))})}return r._p.forEach(p=>{if(process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="test"&&Y){const h=i.run(()=>p({store:y,app:r._a,pinia:r,options:c}));Object.keys(h||{}).forEach(A=>y._customProperties.add(A)),H(y,h)}else H(y,i.run(()=>p({store:y,app:r._a,pinia:r,options:c})))}),process.env.NODE_ENV!=="production"&&y.$state&&typeof y.$state=="object"&&typeof y.$state.constructor=="function"&&!y.$state.constructor.toString().includes("[native code]")&&console.warn(`[🍍]: The "state" must be a plain object. It cannot be
|
|
2
2
|
state: () => new MyClass()
|
|
3
|
-
Found in store "${
|
|
3
|
+
Found in store "${y.$id}".`),L&&s&&t.hydrate&&t.hydrate(y.$state,L),d=!0,m=!0,y}function Be(n,e,t){let r;const o=typeof e=="function";r=o?t:e;function s(i,c){const l=a.hasInjectionContext();if(i=(process.env.NODE_ENV==="test"&&J&&J._testing?null:i)||(l?a.inject(de,null):null),i&&ae(i),process.env.NODE_ENV!=="production"&&!J)throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
|
|
4
4
|
See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.
|
|
5
|
-
This will fail in production.`);s=q,s._s.has(n)||(o?pe(n,e,r,s):Re(n,r,s),process.env.NODE_ENV!=="production"&&(i._pinia=s));const g=s._s.get(n);if(process.env.NODE_ENV!=="production"&&c){const y="__hot:"+n,E=o?pe(y,e,r,s,!0):Re(y,W({},r),s,!0);c._hotUpdate(E),delete s.state.value[y],s._s.delete(y)}if(process.env.NODE_ENV!=="production"&&Z){const y=a.getCurrentInstance();if(y&&y.proxy&&!c){const E=y.proxy,P="_pStores"in E?E._pStores:E._pStores={};P[n]=g}}return g}return i.$id=n,i}function Oe(n){const e=a.toRaw(n),t={};for(const r in e){const o=e[r];o.effect?t[r]=a.computed({get:()=>n[r],set(i){n[r]=i}}):(a.isRef(o)||a.isReactive(o))&&(t[r]=a.toRef(n,r))}return t}const Me=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const xe=Object.prototype.toString,je=n=>xe.call(n)==="[object Object]",Pe=()=>{};function Be(...n){if(n.length!==1)return a.toRef(...n);const e=n[0];return typeof e=="function"?a.readonly(a.customRef(()=>({get:e,set:Pe}))):a.ref(e)}function We(n,e){function t(...r){return new Promise((o,i)=>{Promise.resolve(n(()=>e.apply(this,r),{fn:e,thisArg:this,args:r})).then(o).catch(i)})}return t}const Ne=n=>n();function Ue(n=Ne,e={}){const{initialState:t="active"}=e,r=Be(t==="active");function o(){r.value=!1}function i(){r.value=!0}const s=(...c)=>{r.value&&n(...c)};return{isActive:a.readonly(r),pause:o,resume:i,eventFilter:s}}function he(n){return Array.isArray(n)?n:[n]}function ze(n){return a.getCurrentInstance()}function He(n,e,t={}){const{eventFilter:r=Ne,...o}=t;return a.watch(n,We(r,e),o)}function qe(n,e,t={}){const{eventFilter:r,initialState:o="active",...i}=t,{eventFilter:s,pause:c,resume:l,isActive:g}=Ue(r,{initialState:o});return{stop:He(n,e,{...i,eventFilter:s}),pause:c,resume:l,isActive:g}}const Je=qe;function Ge(n,e=!0,t){ze()?a.onMounted(n,t):e?n():a.nextTick(n)}function Ke(n,e,t){return a.watch(n,e,{...t,immediate:!0})}function re(n,e,t){return a.watch(n,(o,i,s)=>{o&&e(o,i,s)},{...t,once:!1})}const G=Me?window:void 0;function Ze(n){var e;const t=a.toValue(n);return(e=t?.$el)!==null&&e!==void 0?e:t}function Q(...n){const e=(r,o,i,s)=>(r.addEventListener(o,i,s),()=>r.removeEventListener(o,i,s)),t=a.computed(()=>{const r=he(a.toValue(n[0])).filter(o=>o!=null);return r.every(o=>typeof o!="string")?r:void 0});return Ke(()=>{var r,o;return[(r=(o=t.value)===null||o===void 0?void 0:o.map(i=>Ze(i)))!==null&&r!==void 0?r:[G].filter(i=>i!=null),he(a.toValue(t.value?n[1]:n[0])),he(a.unref(t.value?n[2]:n[1])),a.toValue(t.value?n[3]:n[2])]},([r,o,i,s],c,l)=>{if(!r?.length||!o?.length||!i?.length)return;const g=je(s)?{...s}:s,y=r.flatMap(E=>o.flatMap(P=>i.map(T=>e(E,P,T,g))));l(()=>{y.forEach(E=>E())})},{flush:"post"})}const ie=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},se="__vueuse_ssr_handlers__",Ye=Qe();function Qe(){return se in ie||(ie[se]=ie[se]||{}),ie[se]}function Xe(n,e){return Ye[n]||e}function et(n){return n==null?"any":n instanceof Set?"set":n instanceof Map?"map":n instanceof Date?"date":typeof n=="boolean"?"boolean":typeof n=="string"?"string":typeof n=="object"?"object":Number.isNaN(n)?"any":"number"}const tt={boolean:{read:n=>n==="true",write:n=>String(n)},object:{read:n=>JSON.parse(n),write:n=>JSON.stringify(n)},number:{read:n=>Number.parseFloat(n),write:n=>String(n)},any:{read:n=>n,write:n=>String(n)},string:{read:n=>n,write:n=>String(n)},map:{read:n=>new Map(JSON.parse(n)),write:n=>JSON.stringify(Array.from(n.entries()))},set:{read:n=>new Set(JSON.parse(n)),write:n=>JSON.stringify(Array.from(n))},date:{read:n=>new Date(n),write:n=>n.toISOString()}},_e="vueuse-storage";function rt(n,e,t,r={}){var o;const{flush:i="pre",deep:s=!0,listenToStorageChanges:c=!0,writeDefaults:l=!0,mergeDefaults:g=!1,shallow:y,window:E=G,eventFilter:P,onError:T=d=>{console.error(d)},initOnMounted:k}=r,M=(y?a.shallowRef:a.ref)(e),_=a.computed(()=>a.toValue(n));if(!t)try{t=Xe("getDefaultStorage",()=>G?.localStorage)()}catch(d){T(d)}if(!t)return M;const $=a.toValue(e),N=et($),w=(o=r.serializer)!==null&&o!==void 0?o:tt[N],{pause:C,resume:R}=Je(M,d=>u(d),{flush:i,deep:s,eventFilter:P});a.watch(_,()=>O(),{flush:i});let A=!1;const m=d=>{k&&!A||O(d)},j=d=>{k&&!A||S(d)};E&&c&&(t instanceof Storage?Q(E,"storage",m,{passive:!0}):Q(E,_e,j)),k?Ge(()=>{A=!0,O()}):O();function x(d,b){if(E){const I={key:_.value,oldValue:d,newValue:b,storageArea:t};E.dispatchEvent(t instanceof Storage?new StorageEvent("storage",I):new CustomEvent(_e,{detail:I}))}}function u(d){try{const b=t.getItem(_.value);if(d==null)x(b,null),t.removeItem(_.value);else{const I=w.write(d);b!==I&&(t.setItem(_.value,I),x(b,I))}}catch(b){T(b)}}function f(d){const b=d?d.newValue:t.getItem(_.value);if(b==null)return l&&$!=null&&t.setItem(_.value,w.write($)),$;if(!d&&g){const I=w.read(b);return typeof g=="function"?g(I,$):N==="object"&&!Array.isArray(I)?{...$,...I}:I}else return typeof b!="string"?b:w.read(b)}function O(d){if(!(d&&d.storageArea!==t)){if(d&&d.key==null){M.value=$;return}if(!(d&&d.key!==_.value)){C();try{const b=w.write(M.value);(d===void 0||d?.newValue!==b)&&(M.value=f(d))}catch(b){T(b)}finally{d?a.nextTick(R):R()}}}}function S(d){O(d.detail)}return M}function nt(n,e,t={}){const{window:r=G}=t;return rt(n,e,r?.localStorage,t)}const ot={ctrl:"control",command:"meta",cmd:"meta",option:"alt",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright"};function it(n={}){const{reactive:e=!1,target:t=G,aliasMap:r=ot,passive:o=!0,onEventFired:i=Pe}=n,s=a.reactive(new Set),c={toJSON(){return{}},current:s},l=e?a.reactive(c):c,g=new Set,y=new Map([["Meta",g],["Shift",new Set],["Alt",new Set]]),E=new Set;function P(N,w){N in l&&(e?l[N]=w:l[N].value=w)}function T(){s.clear();for(const N of E)P(N,!1)}function k(N,w,C){if(!(!N||typeof w.getModifierState!="function")){for(const[R,A]of y)if(w.getModifierState(R)){C.forEach(m=>A.add(m));break}}}function M(N,w){if(N)return;const C=`${w[0].toUpperCase()}${w.slice(1)}`,R=y.get(C);if(!["shift","alt"].includes(w)||!R)return;const A=Array.from(R),m=A.indexOf(w);A.forEach((j,x)=>{x>=m&&(s.delete(j),P(j,!1))}),R.clear()}function _(N,w){var C,R;const A=(C=N.key)===null||C===void 0?void 0:C.toLowerCase(),m=[(R=N.code)===null||R===void 0?void 0:R.toLowerCase(),A].filter(Boolean);if(A!==""){A&&(w?s.add(A):s.delete(A));for(const j of m)E.add(j),P(j,w);k(w,N,[...s,...m]),M(w,A),A==="meta"&&!w&&(g.forEach(j=>{s.delete(j),P(j,!1)}),g.clear())}}Q(t,"keydown",N=>(_(N,!0),i(N)),{passive:o}),Q(t,"keyup",N=>(_(N,!1),i(N)),{passive:o}),Q("blur",T,{passive:o}),Q("focus",T,{passive:o});const $=new Proxy(l,{get(N,w,C){if(typeof w!="string")return Reflect.get(N,w,C);if(w=w.toLowerCase(),w in r&&(w=r[w]),!(w in l))if(/[+_-]/.test(w)){const A=w.split(/[+_-]/g).map(m=>m.trim());l[w]=a.computed(()=>A.map(m=>a.toValue($[m])).every(Boolean))}else l[w]=a.shallowRef(!1);const R=Reflect.get(N,w,C);return e?a.toValue(R):R}});return $}function ge(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function ae(n){const e={type:n.type,clientId:n.clientId,timestamp:n.timestamp.toISOString()};return n.operation&&(e.operation={...n.operation,timestamp:n.operation.timestamp.toISOString()}),n.operations&&(e.operations=n.operations.map(t=>({...t,timestamp:t.timestamp.toISOString()}))),e}function st(n){const e={type:n.type,clientId:n.clientId,timestamp:new Date(n.timestamp)};return n.operation&&(e.operation={...n.operation,timestamp:new Date(n.operation.timestamp)}),n.operations&&(e.operations=n.operations.map(t=>({...t,timestamp:new Date(t.timestamp)}))),e}const X=Le("hst-operation-log",()=>{const n=a.ref({maxOperations:100,enableCrossTabSync:!0,autoSyncInterval:3e4,enablePersistence:!1,persistenceKeyPrefix:"stonecrop-ops"}),e=a.ref([]),t=a.ref(-1),r=a.ref(ge()),o=a.ref(!1),i=a.ref([]),s=a.ref(null),c=a.computed(()=>t.value<0?!1:e.value[t.value]?.reversible??!1),l=a.computed(()=>t.value<e.value.length-1),g=a.computed(()=>{let p=0;for(let h=t.value;h>=0&&e.value[h]?.reversible;h--)p++;return p}),y=a.computed(()=>e.value.length-1-t.value),E=a.computed(()=>({canUndo:c.value,canRedo:l.value,undoCount:g.value,redoCount:y.value,currentIndex:t.value}));function P(p){n.value={...n.value,...p},n.value.enablePersistence&&(V(),F()),n.value.enableCrossTabSync&&f()}function T(p,h="user"){const v={...p,id:ge(),timestamp:new Date,source:h,userId:n.value.userId};if(n.value.operationFilter&&!n.value.operationFilter(v))return v.id;if(o.value)return i.value.push(v),v.id;if(t.value<e.value.length-1&&(e.value=e.value.slice(0,t.value+1)),e.value.push(v),t.value++,n.value.maxOperations&&e.value.length>n.value.maxOperations){const L=e.value.length-n.value.maxOperations;e.value=e.value.slice(L),t.value-=L}return n.value.enableCrossTabSync&&O(v),v.id}function k(){o.value=!0,i.value=[],s.value=ge()}function M(p){if(!o.value||i.value.length===0)return o.value=!1,i.value=[],s.value=null,null;const h=s.value,v=i.value.every(U=>U.reversible),L={id:h,type:"batch",path:"",fieldname:"",beforeValue:null,afterValue:null,doctype:i.value[0]?.doctype||"",timestamp:new Date,source:"user",reversible:v,irreversibleReason:v?void 0:"Contains irreversible operations",childOperationIds:i.value.map(U=>U.id),metadata:{description:p}};i.value.forEach(U=>{U.parentOperationId=h}),e.value.push(...i.value,L),t.value=e.value.length-1,n.value.enableCrossTabSync&&S(i.value,L);const z=h;return o.value=!1,i.value=[],s.value=null,z}function _(){o.value=!1,i.value=[],s.value=null}function $(p){if(!c.value)return!1;const h=e.value[t.value];if(!h.reversible)return typeof console<"u"&&h.irreversibleReason&&console.warn("Cannot undo irreversible operation:",h.irreversibleReason),!1;try{if(h.type==="batch"&&h.childOperationIds)for(let v=h.childOperationIds.length-1;v>=0;v--){const L=h.childOperationIds[v],z=e.value.find(U=>U.id===L);z&&w(z,p)}else w(h,p);return t.value--,n.value.enableCrossTabSync&&d(h),!0}catch(v){return typeof console<"u"&&console.error("Undo failed:",v),!1}}function N(p){if(!l.value)return!1;const h=e.value[t.value+1];try{if(h.type==="batch"&&h.childOperationIds)for(const v of h.childOperationIds){const L=e.value.find(z=>z.id===v);L&&C(L,p)}else C(h,p);return t.value++,n.value.enableCrossTabSync&&b(h),!0}catch(v){return typeof console<"u"&&console.error("Redo failed:",v),!1}}function w(p,h){(p.type==="set"||p.type==="delete")&&h&&typeof h.set=="function"&&h.set(p.path,p.beforeValue,"undo")}function C(p,h){(p.type==="set"||p.type==="delete")&&h&&typeof h.set=="function"&&h.set(p.path,p.afterValue,"redo")}function R(){const p=e.value.filter(v=>v.reversible).length,h=e.value.map(v=>v.timestamp);return{operations:[...e.value],currentIndex:t.value,totalOperations:e.value.length,reversibleOperations:p,irreversibleOperations:e.value.length-p,oldestOperation:h.length>0?new Date(Math.min(...h.map(v=>v.getTime()))):void 0,newestOperation:h.length>0?new Date(Math.max(...h.map(v=>v.getTime()))):void 0}}function A(){e.value=[],t.value=-1}function m(p,h){return e.value.filter(v=>v.doctype===p&&(h===void 0||v.recordId===h))}function j(p,h){const v=e.value.find(L=>L.id===p);v&&(v.reversible=!1,v.irreversibleReason=h)}function x(p,h,v,L="success",z){const U={type:"action",path:v&&v.length>0?`${p}.${v[0]}`:p,fieldname:"",beforeValue:null,afterValue:null,doctype:p,recordId:v&&v.length>0?v[0]:void 0,reversible:!1,actionName:h,actionRecordIds:v,actionResult:L,actionError:z};return T(U)}let u=null;function f(){typeof window>"u"||!window.BroadcastChannel||(u=new BroadcastChannel("stonecrop-operation-log"),u.addEventListener("message",p=>{const h=p.data;if(!h||typeof h!="object")return;const v=st(h);v.clientId!==r.value&&(v.type==="operation"&&v.operation?(e.value.push({...v.operation,source:"sync"}),t.value=e.value.length-1):v.type==="operation"&&v.operations&&(e.value.push(...v.operations.map(L=>({...L,source:"sync"}))),t.value=e.value.length-1))}))}function O(p){if(!u)return;const h={type:"operation",operation:p,clientId:r.value,timestamp:new Date};u.postMessage(ae(h))}function S(p,h){if(!u)return;const v={type:"operation",operations:[...p,h],clientId:r.value,timestamp:new Date};u.postMessage(ae(v))}function d(p){if(!u)return;const h={type:"undo",operation:p,clientId:r.value,timestamp:new Date};u.postMessage(ae(h))}function b(p){if(!u)return;const h={type:"redo",operation:p,clientId:r.value,timestamp:new Date};u.postMessage(ae(h))}const I=nt("stonecrop-ops-operations",null,{serializer:{read:p=>{try{return JSON.parse(p)}catch{return null}},write:p=>p?JSON.stringify(p):""}});function V(){if(!(typeof window>"u"))try{const p=I.value;p&&Array.isArray(p.operations)&&(e.value=p.operations.map(h=>({...h,timestamp:new Date(h.timestamp)})),t.value=p.currentIndex??-1)}catch(p){typeof console<"u"&&console.error("Failed to load operations from persistence:",p)}}function B(){if(!(typeof window>"u"))try{I.value={operations:e.value.map(p=>({...p,timestamp:p.timestamp.toISOString()})),currentIndex:t.value}}catch(p){typeof console<"u"&&console.error("Failed to save operations to persistence:",p)}}function F(){a.watch([e,t],()=>{n.value.enablePersistence&&B()},{deep:!0})}return{operations:e,currentIndex:t,config:n,clientId:r,undoRedoState:E,canUndo:c,canRedo:l,undoCount:g,redoCount:y,configure:P,addOperation:T,startBatch:k,commitBatch:M,cancelBatch:_,undo:$,redo:N,clear:A,getOperationsFor:m,getSnapshot:R,markIrreversible:j,logAction:x}});class ne{static _root;options;doctypeActions=new Map;doctypeTransitions=new Map;fieldRollbackConfig=new Map;globalActions=new Map;globalTransitionActions=new Map;constructor(e={}){if(ne._root)return ne._root;ne._root=this,this.options={defaultTimeout:e.defaultTimeout??5e3,debug:e.debug??!1,enableRollback:e.enableRollback??!0,errorHandler:e.errorHandler}}registerAction(e,t){this.globalActions.set(e,t)}registerTransitionAction(e,t){this.globalTransitionActions.set(e,t)}setFieldRollback(e,t,r){this.fieldRollbackConfig.has(e)||this.fieldRollbackConfig.set(e,new Map),this.fieldRollbackConfig.get(e).set(t,r)}getFieldRollback(e,t){return this.fieldRollbackConfig.get(e)?.get(t)}registerDoctypeActions(e,t){if(!t)return;const r=new Map,o=new Map;if(typeof t.entrySeq=="function")t.entrySeq().forEach(([i,s])=>{this.categorizeAction(i,s,r,o)});else if(t instanceof Map)for(const[i,s]of t)this.categorizeAction(i,s,r,o);else t&&typeof t=="object"&&Object.entries(t).forEach(([i,s])=>{this.categorizeAction(i,s,r,o)});this.doctypeActions.set(e,r),this.doctypeTransitions.set(e,o)}categorizeAction(e,t,r,o){this.isTransitionKey(e)?o.set(e,t):r.set(e,t)}isTransitionKey(e){return/^[A-Z0-9_]+$/.test(e)&&e.length>0}async executeFieldTriggers(e,t={}){const{doctype:r,fieldname:o}=e,i=this.findFieldTriggers(r,o);if(i.length===0)return{path:e.path,actionResults:[],totalExecutionTime:0,allSucceeded:!0,stoppedOnError:!1,rolledBack:!1};const s=performance.now(),c=[];let l=!1,g=!1,y;const E=this.getFieldRollback(r,o),P=t.enableRollback??E??this.options.enableRollback;P&&e.store&&(y=this.captureSnapshot(e));for(const _ of i)try{const $=await this.executeAction(_,e,t.timeout);if(c.push($),!$.success){l=!0;break}}catch($){const w={success:!1,error:$ instanceof Error?$:new Error(String($)),executionTime:0,action:_};c.push(w),l=!0;break}if(P&&l&&y&&e.store)try{this.restoreSnapshot(e,y),g=!0}catch(_){console.error("[FieldTriggers] Rollback failed:",_)}const T=performance.now()-s,k=c.filter(_=>!_.success);if(k.length>0&&this.options.errorHandler)for(const _ of k)try{this.options.errorHandler(_.error,e,_.action)}catch($){console.error("[FieldTriggers] Error in global error handler:",$)}return{path:e.path,actionResults:c,totalExecutionTime:T,allSucceeded:c.every(_=>_.success),stoppedOnError:l,rolledBack:g,snapshot:this.options.debug&&P?y:void 0}}async executeTransitionActions(e,t={}){const{doctype:r,transition:o}=e,i=this.findTransitionActions(r,o);if(i.length===0)return[];const s=[];for(const l of i)try{const g=await this.executeTransitionAction(l,e,t.timeout);if(s.push(g),!g.success)break}catch(g){const E={success:!1,error:g instanceof Error?g:new Error(String(g)),executionTime:0,action:l,transition:o};s.push(E);break}const c=s.filter(l=>!l.success);if(c.length>0&&this.options.errorHandler)for(const l of c)try{this.options.errorHandler(l.error,e,l.action)}catch(g){console.error("[FieldTriggers] Error in global error handler:",g)}return s}findTransitionActions(e,t){const r=this.doctypeTransitions.get(e);return r?r.get(t)||[]:[]}async executeTransitionAction(e,t,r){const o=performance.now(),i=r??this.options.defaultTimeout;try{let s=this.globalTransitionActions.get(e);if(!s){const l=this.globalActions.get(e);l&&(s=l)}if(!s)throw new Error(`Transition action "${e}" not found in registry`);return await this.executeWithTimeout(s,t,i),{success:!0,executionTime:performance.now()-o,action:e,transition:t.transition}}catch(s){const c=performance.now()-o;return{success:!1,error:s instanceof Error?s:new Error(String(s)),executionTime:c,action:e,transition:t.transition}}}findFieldTriggers(e,t){const r=this.doctypeActions.get(e);if(!r)return[];const o=[];for(const[i,s]of r)this.isFieldTriggerKey(i,t)&&o.push(...s);return o}isFieldTriggerKey(e,t){return e===t?!0:e.includes(".")?this.matchFieldPattern(e,t):e.includes("*")?this.matchFieldPattern(e,t):!1}matchFieldPattern(e,t){const r=e.split("."),o=t.split(".");if(r.length!==o.length)return!1;for(let i=0;i<r.length;i++){const s=r[i],c=o[i];if(s!=="*"&&s!==c)return!1}return!0}async executeAction(e,t,r){const o=performance.now(),i=r??this.options.defaultTimeout;try{const s=this.globalActions.get(e);if(!s)throw new Error(`Action "${e}" not found in registry`);return await this.executeWithTimeout(s,t,i),{success:!0,executionTime:performance.now()-o,action:e}}catch(s){const c=performance.now()-o;return{success:!1,error:s instanceof Error?s:new Error(String(s)),executionTime:c,action:e}}}async executeWithTimeout(e,t,r){return new Promise((o,i)=>{const s=setTimeout(()=>{i(new Error(`Action timeout after ${r}ms`))},r);Promise.resolve(e(t)).then(c=>{clearTimeout(s),o(c)}).catch(c=>{clearTimeout(s),i(c)})})}captureSnapshot(e){if(!(!e.store||!e.doctype||!e.recordId))try{const t=`${e.doctype}.${e.recordId}`,r=e.store.get(t);return!r||typeof r!="object"?void 0:JSON.parse(JSON.stringify(r))}catch(t){this.options.debug&&console.warn("[FieldTriggers] Failed to capture snapshot:",t);return}}restoreSnapshot(e,t){if(!(!e.store||!e.doctype||!e.recordId||!t))try{const r=`${e.doctype}.${e.recordId}`;e.store.set(r,t),this.options.debug&&console.log(`[FieldTriggers] Rolled back ${r} to previous state`)}catch(r){throw console.error("[FieldTriggers] Failed to restore snapshot:",r),r}}}function H(n){return new ne(n)}function at(n,e){H().registerAction(n,e)}function ct(n,e){H().registerTransitionAction(n,e)}function lt(n,e,t){H().setFieldRollback(n,e,t)}async function ut(n,e,t){const r=H(),o={path:t?.path||(t?.recordId?`${n}.${t.recordId}`:n),fieldname:"",beforeValue:void 0,afterValue:void 0,operation:"set",doctype:n,recordId:t?.recordId,timestamp:new Date,transition:e,currentState:t?.currentState,targetState:t?.targetState,fsmContext:t?.fsmContext};return await r.executeTransitionActions(o)}function ft(n,e){if(n)try{X().markIrreversible(n,e)}catch{}}function Ae(){try{return X()}catch{return null}}class K{static instance;static getInstance(){return K.instance||(K.instance=new K),K.instance}getRegistry(){if(typeof globalThis<"u"){const e=globalThis.Registry?._root;if(e)return e}if(typeof window<"u"){const e=window.Registry?._root;if(e)return e}if(typeof global<"u"&&global){const e=global.Registry?._root;if(e)return e}}getDoctypeMeta(e){const t=this.getRegistry();if(t&&typeof t=="object"&&"registry"in t)return t.registry[e]}}class ce{target;parentPath;rootNode;doctype;parentDoctype;hst;constructor(e,t,r="",o=null,i){return this.target=e,this.parentPath=r,this.rootNode=o||this,this.doctype=t,this.parentDoctype=i,this.hst=K.getInstance(),new Proxy(this,{get(s,c){if(c in s)return s[c];const l=String(c);return s.getNode(l)},set(s,c,l){const g=String(c);return s.set(g,l),!0}})}get(e){return this.resolveValue(e)}getNode(e){const t=this.resolvePath(e),r=this.resolveValue(e),o=t.split(".");let i=this.doctype;return this.doctype==="StonecropStore"&&o.length>=1&&(i=o[0]),typeof r=="object"&&r!==null&&!this.isPrimitive(r)?new ce(r,i,t,this.rootNode,this.parentDoctype):new ce(r,i,t,this.rootNode,this.parentDoctype)}set(e,t,r="user"){const o=this.resolvePath(e),i=this.has(e)?this.get(e):void 0;if(r!=="undo"&&r!=="redo"){const s=Ae();if(s&&typeof s.addOperation=="function"){const c=o.split("."),l=this.doctype==="StonecropStore"&&c.length>=1?c[0]:this.doctype,g=c.length>=2?c[1]:void 0,y=c.slice(2).join(".")||c[c.length-1],P=t===void 0&&i!==void 0?"delete":"set";s.addOperation({type:P,path:o,fieldname:y,beforeValue:i,afterValue:t,doctype:l,recordId:g,reversible:!0},r)}}this.updateValue(e,t),this.triggerFieldActions(o,i,t)}has(e){try{if(e==="")return!0;const t=this.parsePath(e);let r=this.target;for(let o=0;o<t.length;o++){const i=t[o];if(r==null)return!1;if(o===t.length-1)return this.isImmutable(r)?r.has(i):this.isPiniaStore(r)&&r.$state&&i in r.$state||i in r;r=this.getProperty(r,i)}return!1}catch{return!1}}getParent(){if(!this.parentPath)return null;const t=this.parentPath.split(".").slice(0,-1).join(".");return t===""?this.rootNode:this.rootNode.getNode(t)}getRoot(){return this.rootNode}getPath(){return this.parentPath}getDepth(){return this.parentPath?this.parentPath.split(".").length:0}getBreadcrumbs(){return this.parentPath?this.parentPath.split("."):[]}async triggerTransition(e,t){const r=H(),o=this.parentPath.split(".");let i=this.doctype,s;this.doctype==="StonecropStore"&&o.length>=1&&(i=o[0]),o.length>=2&&(s=o[1]);const c={path:this.parentPath,fieldname:"",beforeValue:void 0,afterValue:void 0,operation:"set",doctype:i,recordId:s,timestamp:new Date,store:this.rootNode||void 0,transition:e,currentState:t?.currentState,targetState:t?.targetState,fsmContext:t?.fsmContext},l=Ae();return l&&typeof l.addOperation=="function"&&l.addOperation({type:"transition",path:this.parentPath,fieldname:e,beforeValue:t?.currentState,afterValue:t?.targetState,doctype:i,recordId:s,reversible:!1,metadata:{transition:e,currentState:t?.currentState,targetState:t?.targetState,fsmContext:t?.fsmContext}},"user"),await r.executeTransitionActions(c)}resolvePath(e){return e===""?this.parentPath:this.parentPath?`${this.parentPath}.${e}`:e}resolveValue(e){if(e==="")return this.target;const t=this.parsePath(e);let r=this.target;for(const o of t){if(r==null)return;r=this.getProperty(r,o)}return r}updateValue(e,t){if(e==="")throw new Error("Cannot set value on empty path");const r=this.parsePath(e),o=r.pop();let i=this.target;for(const s of r)if(i=this.getProperty(i,s),i==null)throw new Error(`Cannot set property on null/undefined path: ${e}`);this.setProperty(i,o,t)}getProperty(e,t){return this.isImmutable(e)?e.get(t):this.isVueReactive(e)?e[t]:this.isPiniaStore(e)?e.$state?.[t]??e[t]:e[t]}setProperty(e,t,r){if(this.isImmutable(e))throw new Error("Cannot directly mutate immutable objects. Use immutable update methods instead.");if(this.isPiniaStore(e)){e.$patch?e.$patch({[t]:r}):e[t]=r;return}e[t]=r}async triggerFieldActions(e,t,r){try{if(!e||typeof e!="string")return;const o=e.split(".");if(o.length<3)return;const i=H(),s=o.slice(2).join(".")||o[o.length-1];let c=this.doctype;this.doctype==="StonecropStore"&&o.length>=1&&(c=o[0]);let l;o.length>=2&&(l=o[1]);const g={path:e,fieldname:s,beforeValue:t,afterValue:r,operation:"set",doctype:c,recordId:l,timestamp:new Date,store:this.rootNode||void 0};await i.executeFieldTriggers(g)}catch(o){o instanceof Error&&console.warn("Field trigger error:",o.message)}}isVueReactive(e){return e&&typeof e=="object"&&"__v_isReactive"in e&&e.__v_isReactive===!0}isPiniaStore(e){return e&&typeof e=="object"&&("$state"in e||"$patch"in e||"$id"in e)}isImmutable(e){if(!e||typeof e!="object")return!1;const t="get"in e&&typeof e.get=="function",r="set"in e&&typeof e.set=="function",o="has"in e&&typeof e.has=="function",i="__ownerID"in e||"_map"in e||"_list"in e||"_origin"in e||"_capacity"in e||"_defaultValues"in e||"_tail"in e||"_root"in e||"size"in e&&t&&r;let s;try{const l=e;if("constructor"in l&&l.constructor&&typeof l.constructor=="object"&&"name"in l.constructor){const g=l.constructor.name;s=typeof g=="string"?g:void 0}}catch{s=void 0}const c=s&&(s.includes("Map")||s.includes("List")||s.includes("Set")||s.includes("Stack")||s.includes("Seq"))&&(t||r);return!!(t&&r&&o&&i||t&&r&&c)}isPrimitive(e){return e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="function"||typeof e=="symbol"||typeof e=="bigint"}parsePath(e){return e?e.split(".").filter(t=>t.length>0):[]}}function Ie(n,e,t){return new ce(n,e,"",null,t)}class ye{hstStore;_operationLogStore;_operationLogConfig;registry;constructor(e,t){this.registry=e,this._operationLogConfig=t,this.initializeHSTStore(),this.setupRegistrySync()}getOperationLogStore(){return this._operationLogStore||(this._operationLogStore=X(),this._operationLogConfig&&this._operationLogStore.configure(this._operationLogConfig)),this._operationLogStore}initializeHSTStore(){const e={};Object.keys(this.registry.registry).forEach(t=>{e[t]={}}),this.hstStore=Ie(e,"StonecropStore")}setupRegistrySync(){const e=this.registry.addDoctype.bind(this.registry);this.registry.addDoctype=t=>{e(t),this.hstStore.has(t.slug)||this.hstStore.set(t.slug,{})}}records(e){const t=typeof e=="string"?e:e.slug;return this.ensureDoctypeExists(t),this.hstStore.getNode(t)}addRecord(e,t,r){const o=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(o),this.hstStore.set(`${o}.${t}`,r)}getRecordById(e,t){const r=typeof e=="string"?e:e.slug;if(this.ensureDoctypeExists(r),!(!this.hstStore.has(`${r}.${t}`)||this.hstStore.get(`${r}.${t}`)===void 0))return this.hstStore.getNode(`${r}.${t}`)}removeRecord(e,t){const r=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(r),this.hstStore.has(`${r}.${t}`)&&this.hstStore.set(`${r}.${t}`,void 0)}getRecordIds(e){const t=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(t);const r=this.hstStore.get(t);return!r||typeof r!="object"?[]:Object.keys(r).filter(o=>r[o]!==void 0)}clearRecords(e){const t=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(t),this.getRecordIds(t).forEach(o=>{this.hstStore.set(`${t}.${o}`,void 0)})}setup(e){this.ensureDoctypeExists(e.slug)}runAction(e,t,r){const i=this.registry.registry[e.slug]?.actions?.get(t),s=Array.isArray(r)?r.filter(y=>typeof y=="string"):void 0,c=this.getOperationLogStore();let l="success",g;try{i&&i.length>0&&i.forEach(y=>{try{new Function("args",y)(r)}catch(E){throw l="failure",g=E instanceof Error?E.message:"Unknown error",E}})}catch{}finally{c.logAction(e.doctype,t,s,l,g)}}async getRecords(e){(await(await fetch(`/${e.slug}`)).json()).forEach(o=>{o.id&&this.addRecord(e,o.id,o)})}async getRecord(e,t){const o=await(await fetch(`/${e.slug}/${t}`)).json();this.addRecord(e,t,o)}ensureDoctypeExists(e){this.hstStore.has(e)||this.hstStore.set(e,{})}async getMeta(e){if(!this.registry.getMeta)throw new Error("No getMeta function provided to Registry");return await this.registry.getMeta(e)}getStore(){return this.hstStore}}function dt(n){n||(n={});const e=n.registry||a.inject("$registry"),t=a.inject("$stonecrop"),r=a.ref(),o=a.ref(),i=a.ref({}),s=a.ref(),c=a.ref(),l=a.ref([]),g=a.ref(-1),y=a.computed(()=>r.value?.getOperationLogStore().canUndo??!1),E=a.computed(()=>r.value?.getOperationLogStore().canRedo??!1),P=a.computed(()=>r.value?.getOperationLogStore().undoCount??0),T=a.computed(()=>r.value?.getOperationLogStore().redoCount??0),k=a.computed(()=>r.value?.getOperationLogStore().undoRedoState??{canUndo:!1,canRedo:!1,undoCount:0,redoCount:0,currentIndex:-1}),M=S=>r.value?.getOperationLogStore().undo(S)??!1,_=S=>r.value?.getOperationLogStore().redo(S)??!1,$=()=>{r.value?.getOperationLogStore().startBatch()},N=S=>r.value?.getOperationLogStore().commitBatch(S)??null,w=()=>{r.value?.getOperationLogStore().cancelBatch()},C=()=>{r.value?.getOperationLogStore().clear()},R=(S,d)=>r.value?.getOperationLogStore().getOperationsFor(S,d)??[],A=()=>r.value?.getOperationLogStore().getSnapshot()??{operations:[],currentIndex:-1,totalOperations:0,reversibleOperations:0,irreversibleOperations:0},m=(S,d)=>{r.value?.getOperationLogStore().markIrreversible(S,d)},j=(S,d,b,I="success",V)=>r.value?.getOperationLogStore().logAction(S,d,b,I,V)??"",x=S=>{r.value?.getOperationLogStore().configure(S)};a.onMounted(async()=>{if(e){r.value=t||new ye(e);try{const S=r.value.getOperationLogStore(),d=Oe(S);l.value=d.operations.value,g.value=d.currentIndex.value,a.watch(()=>d.operations.value,b=>{l.value=b}),a.watch(()=>d.currentIndex.value,b=>{g.value=b})}catch{}if(!n.doctype&&e.router){const S=e.router.currentRoute.value;if(!S.path)return;const d=S.path.split("/").filter(I=>I.length>0),b=d[1]?.toLowerCase();if(d.length>0){const I={path:S.path,segments:d},V=await e.getMeta?.(I);if(V){if(e.addDoctype(V),r.value.setup(V),s.value=V,c.value=b,o.value=r.value.getStore(),b&&b!=="new"){const B=r.value.getRecordById(V,b);if(B)i.value=B.get("")||{};else try{await r.value.getRecord(V,b);const F=r.value.getRecordById(V,b);F&&(i.value=F.get("")||{})}catch{i.value=le(V)}}else i.value=le(V);o.value&&Te(V,b||"new",i,o.value),r.value.runAction(V,"load",b?[b]:void 0)}}}if(n.doctype){o.value=r.value.getStore();const S=n.doctype,d=n.recordId;if(d&&d!=="new"){const b=r.value.getRecordById(S,d);if(b)i.value=b.get("")||{};else try{await r.value.getRecord(S,d);const I=r.value.getRecordById(S,d);I&&(i.value=I.get("")||{})}catch{i.value=le(S)}}else i.value=le(S);o.value&&Te(S,d||"new",i,o.value)}}});const u=(S,d)=>{const b=n.doctype||s.value;if(!b)return"";const I=d||n.recordId||c.value||"new";return`${b.slug}.${I}.${S}`},f=S=>{const d=n.doctype||s.value;if(!(!o.value||!r.value||!d))try{const b=S.path.split(".");if(b.length>=2){const B=b[0],F=b[1];if(o.value.has(`${B}.${F}`)||r.value.addRecord(d,F,{...i.value}),b.length>3){const p=`${B}.${F}`,h=b.slice(2);let v=p;for(let L=0;L<h.length-1;L++)if(v+=`.${h[L]}`,!o.value.has(v)){const z=h[L+1],U=!isNaN(Number(z));o.value.set(v,U?[]:{})}}}o.value.set(S.path,S.value);const I=S.fieldname.split("."),V={...i.value};I.length===1?V[I[0]]=S.value:pt(V,I,S.value),i.value=V}catch{}};(n.doctype||e?.router)&&(a.provide("hstPathProvider",u),a.provide("hstChangeHandler",f));const O={operations:l,currentIndex:g,undoRedoState:k,canUndo:y,canRedo:E,undoCount:P,redoCount:T,undo:M,redo:_,startBatch:$,commitBatch:N,cancelBatch:w,clear:C,getOperationsFor:R,getSnapshot:A,markIrreversible:m,logAction:j,configure:x};return n.doctype?{stonecrop:r,operationLog:O,provideHSTPath:u,handleHSTChange:f,hstStore:o,formData:i}:!n.doctype&&e?.router?{stonecrop:r,operationLog:O,provideHSTPath:u,handleHSTChange:f,hstStore:o,formData:i}:{stonecrop:r,operationLog:O}}function le(n){const e={};return n.schema&&n.schema.forEach(t=>{switch("fieldtype"in t?t.fieldtype:"Data"){case"Data":case"Text":e[t.fieldname]="";break;case"Check":e[t.fieldname]=!1;break;case"Int":case"Float":e[t.fieldname]=0;break;case"Table":e[t.fieldname]=[];break;case"JSON":e[t.fieldname]={};break;default:e[t.fieldname]=null}}),e}function Te(n,e,t,r){a.watch(t,o=>{const i=`${n.slug}.${e}`;Object.keys(o).forEach(s=>{const c=`${i}.${s}`;try{r.set(c,o[s])}catch{}})},{deep:!0})}function pt(n,e,t){let r=n;for(let i=0;i<e.length-1;i++){const s=e[i];(!(s in r)||typeof r[s]!="object")&&(r[s]=isNaN(Number(e[i+1]))?{}:[]),r=r[s]}const o=e[e.length-1];r[o]=t}function me(n){const t=a.inject("$operationLogStore",void 0)||X();n&&t.configure(n);const{operations:r,currentIndex:o,undoRedoState:i,canUndo:s,canRedo:c,undoCount:l,redoCount:g}=Oe(t);function y(R){return t.undo(R)}function E(R){return t.redo(R)}function P(){t.startBatch()}function T(R){return t.commitBatch(R)}function k(){t.cancelBatch()}function M(){t.clear()}function _(R,A){return t.getOperationsFor(R,A)}function $(){return t.getSnapshot()}function N(R,A){t.markIrreversible(R,A)}function w(R,A,m,j="success",x){return t.logAction(R,A,m,j,x)}function C(R){t.configure(R)}return{operations:r,currentIndex:o,undoRedoState:i,canUndo:s,canRedo:c,undoCount:l,redoCount:g,undo:y,redo:E,startBatch:P,commitBatch:T,cancelBatch:k,clear:M,getOperationsFor:_,getSnapshot:$,markIrreversible:N,logAction:w,configure:C}}function ht(n,e=!0){if(!e)return;const{undo:t,redo:r,canUndo:o,canRedo:i}=me(),s=it();re(s["Ctrl+Z"],()=>{o.value&&t(n)}),re(s["Meta+Z"],()=>{o.value&&t(n)}),re(s["Ctrl+Shift+Z"],()=>{i.value&&r(n)}),re(s["Meta+Shift+Z"],()=>{i.value&&r(n)}),re(s["Ctrl+Y"],()=>{i.value&&r(n)})}async function gt(n,e){const{startBatch:t,commitBatch:r,cancelBatch:o}=me();t();try{return await n(),r(e)}catch(i){throw o(),i}}class yt{doctype;schema;workflow;actions;component;constructor(e,t,r,o,i){this.doctype=e,this.schema=t,this.workflow=r,this.actions=o,this.component=i}get slug(){return this.doctype.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}}class ee{static _root;name;registry;router;constructor(e,t){if(ee._root)return ee._root;ee._root=this,this.name="Registry",this.registry={},this.router=e,this.getMeta=t}getMeta;addDoctype(e){e.doctype in Object.keys(this.registry)||(this.registry[e.slug]=e);const t=H();t.registerDoctypeActions(e.doctype,e.actions),e.slug!==e.doctype&&t.registerDoctypeActions(e.slug,e.actions),e.component&&this.router&&!this.router.hasRoute(e.doctype)&&this.router.addRoute({path:`/${e.slug}`,name:e.slug,component:e.component})}}async function mt(n,e,t){await a.nextTick();try{await t(n,e)}catch{}}const vt={install:(n,e)=>{const t=n.config.globalProperties.$router,r=e?.router,o=t||r;!t&&r&&n.use(r);const i=new ee(o,e?.getMeta);n.provide("$registry",i),n.config.globalProperties.$registry=i;const s=new ye(i);n.provide("$stonecrop",s),n.config.globalProperties.$stonecrop=s;try{const c=n.config.globalProperties.$pinia;if(c){const l=X(c);n.provide("$operationLogStore",l),n.config.globalProperties.$operationLogStore=l}}catch(c){console.warn("Pinia not available - operation log features will be disabled:",c)}if(e?.components)for(const[c,l]of Object.entries(e.components))n.component(c,l);e?.autoInitializeRouter&&e.onRouterInitialized&&mt(i,s,e.onRouterInitialized)}};var $e=(n=>(n.ERROR="error",n.WARNING="warning",n.INFO="info",n))($e||{});class De{options;constructor(e={}){this.options={registry:e.registry||null,validateLinkTargets:e.validateLinkTargets??!0,validateActions:e.validateActions??!0,validateWorkflows:e.validateWorkflows??!0,validateRequiredProperties:e.validateRequiredProperties??!0}}validate(e,t,r,o){const i=[],s=t?Array.isArray(t)?t:t.toArray():[];if(this.options.validateRequiredProperties&&i.push(...this.validateRequiredProperties(e,s)),this.options.validateLinkTargets&&this.options.registry&&i.push(...this.validateLinkFields(e,s,this.options.registry)),this.options.validateWorkflows&&r&&i.push(...this.validateWorkflow(e,r)),this.options.validateActions&&o){const y=o instanceof Map?o:o.toObject();i.push(...this.validateActionRegistration(e,y))}const c=i.filter(y=>y.severity==="error").length,l=i.filter(y=>y.severity==="warning").length,g=i.filter(y=>y.severity==="info").length;return{valid:c===0,issues:i,errorCount:c,warningCount:l,infoCount:g}}validateRequiredProperties(e,t){const r=[];for(const o of t){if(!o.fieldname){r.push({severity:"error",rule:"required-fieldname",message:"Field is missing required property: fieldname",doctype:e,context:{field:o}});continue}if(!o.component&&!("fieldtype"in o)&&r.push({severity:"error",rule:"required-component-or-fieldtype",message:`Field "${o.fieldname}" must have either component or fieldtype property`,doctype:e,fieldname:o.fieldname}),"schema"in o){const i=o.schema,s=Array.isArray(i)?i:i.toArray?.()||[];r.push(...this.validateRequiredProperties(e,s))}}return r}validateLinkFields(e,t,r){const o=[];for(const i of t){if(("fieldtype"in i?i.fieldtype:void 0)==="Link"){const c="options"in i?i.options:void 0;if(!c){o.push({severity:"error",rule:"link-missing-options",message:`Link field "${i.fieldname}" is missing options property (target doctype)`,doctype:e,fieldname:i.fieldname});continue}const l=typeof c=="string"?c:"";if(!l){o.push({severity:"error",rule:"link-invalid-options",message:`Link field "${i.fieldname}" has invalid options format (expected string doctype name)`,doctype:e,fieldname:i.fieldname});continue}r.registry[l]||r.registry[l.toLowerCase()]||o.push({severity:"error",rule:"link-invalid-target",message:`Link field "${i.fieldname}" references non-existent doctype: "${l}"`,doctype:e,fieldname:i.fieldname,context:{targetDoctype:l}})}if("schema"in i){const c=i.schema,l=Array.isArray(c)?c:c.toArray?.()||[];o.push(...this.validateLinkFields(e,l,r))}}return o}validateWorkflow(e,t){const r=[];if(!t.initial&&!t.type&&r.push({severity:"warning",rule:"workflow-missing-initial",message:"Workflow is missing initial state property",doctype:e}),!t.states||Object.keys(t.states).length===0)return r.push({severity:"warning",rule:"workflow-no-states",message:"Workflow has no states defined",doctype:e}),r;t.initial&&typeof t.initial=="string"&&!t.states[t.initial]&&r.push({severity:"error",rule:"workflow-invalid-initial",message:`Workflow initial state "${t.initial}" does not exist in states`,doctype:e,context:{initialState:t.initial}});const o=Object.keys(t.states),i=new Set;t.initial&&typeof t.initial=="string"&&i.add(t.initial);for(const[s,c]of Object.entries(t.states)){const l=c;if(l.on){for(const[g,y]of Object.entries(l.on))if(typeof y=="string")i.add(y);else if(y&&typeof y=="object"){const E="target"in y?y.target:void 0;typeof E=="string"?i.add(E):Array.isArray(E)&&E.forEach(P=>{typeof P=="string"&&i.add(P)})}}}for(const s of o)i.has(s)||r.push({severity:"warning",rule:"workflow-unreachable-state",message:`Workflow state "${s}" may not be reachable`,doctype:e,context:{stateName:s}});return r}validateActionRegistration(e,t){const r=[],o=H();for(const[i,s]of Object.entries(t)){if(!Array.isArray(s)){r.push({severity:"error",rule:"action-invalid-format",message:`Action configuration for "${i}" must be an array`,doctype:e,context:{triggerName:i,actionNames:s}});continue}for(const c of s){const l=o;l.globalActions?.has(c)||l.globalTransitionActions?.has(c)||r.push({severity:"warning",rule:"action-not-registered",message:`Action "${c}" referenced in "${i}" is not registered in FieldTriggerEngine`,doctype:e,context:{triggerName:i,actionName:c}})}}return r}}function Ce(n,e){return new De({registry:n,...e})}function St(n,e,t,r,o){return Ce(t).validate(n,e,r,o)}D.DoctypeMeta=yt,D.HST=K,D.Registry=ee,D.SchemaValidator=De,D.Stonecrop=ye,D.ValidationSeverity=$e,D.createHST=Ie,D.createValidator=Ce,D.default=vt,D.getGlobalTriggerEngine=H,D.markOperationIrreversible=ft,D.registerGlobalAction=at,D.registerTransitionAction=ct,D.setFieldRollback=lt,D.triggerTransition=ut,D.useOperationLog=me,D.useOperationLogStore=X,D.useStonecrop=dt,D.useUndoRedoShortcuts=ht,D.validateSchema=St,D.withBatch=gt,Object.defineProperties(D,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
5
|
+
This will fail in production.`);i=J,i._s.has(n)||(o?ge(n,e,r,i):Pe(n,r,i),process.env.NODE_ENV!=="production"&&(s._pinia=i));const d=i._s.get(n);if(process.env.NODE_ENV!=="production"&&c){const m="__hot:"+n,w=o?ge(m,e,r,i,!0):Pe(m,H({},r),i,!0);c._hotUpdate(w),delete i.state.value[m],i._s.delete(m)}if(process.env.NODE_ENV!=="production"&&Y){const m=a.getCurrentInstance();if(m&&m.proxy&&!c){const w=m.proxy,P="_pStores"in w?w._pStores:w._pStores={};P[n]=d}}return d}return s.$id=n,s}function Ne(n){const e=a.toRaw(n),t={};for(const r in e){const o=e[r];o.effect?t[r]=a.computed({get:()=>n[r],set(s){n[r]=s}}):(a.isRef(o)||a.isReactive(o))&&(t[r]=a.toRef(n,r))}return t}const We=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const He=Object.prototype.toString,Ue=n=>He.call(n)==="[object Object]",_e=()=>{};function ze(...n){if(n.length!==1)return a.toRef(...n);const e=n[0];return typeof e=="function"?a.readonly(a.customRef(()=>({get:e,set:_e}))):a.ref(e)}function qe(n,e){function t(...r){return new Promise((o,s)=>{Promise.resolve(n(()=>e.apply(this,r),{fn:e,thisArg:this,args:r})).then(o).catch(s)})}return t}const Te=n=>n();function Je(n=Te,e={}){const{initialState:t="active"}=e,r=ze(t==="active");function o(){r.value=!1}function s(){r.value=!0}const i=(...c)=>{r.value&&n(...c)};return{isActive:a.readonly(r),pause:o,resume:s,eventFilter:i}}function me(n){return Array.isArray(n)?n:[n]}function Ge(n){return a.getCurrentInstance()}function Ke(n,e,t={}){const{eventFilter:r=Te,...o}=t;return a.watch(n,qe(r,e),o)}function Ze(n,e,t={}){const{eventFilter:r,initialState:o="active",...s}=t,{eventFilter:i,pause:c,resume:l,isActive:d}=Je(r,{initialState:o});return{stop:Ke(n,e,{...s,eventFilter:i}),pause:c,resume:l,isActive:d}}const Qe=Ze;function Ye(n,e=!0,t){Ge()?a.onMounted(n,t):e?n():a.nextTick(n)}function Xe(n,e,t){return a.watch(n,e,{...t,immediate:!0})}function se(n,e,t){return a.watch(n,(o,s,i)=>{o&&e(o,s,i)},{...t,once:!1})}const K=We?window:void 0;function et(n){var e;const t=a.toValue(n);return(e=t?.$el)!==null&&e!==void 0?e:t}function ee(...n){const e=(r,o,s,i)=>(r.addEventListener(o,s,i),()=>r.removeEventListener(o,s,i)),t=a.computed(()=>{const r=me(a.toValue(n[0])).filter(o=>o!=null);return r.every(o=>typeof o!="string")?r:void 0});return Xe(()=>{var r,o;return[(r=(o=t.value)===null||o===void 0?void 0:o.map(s=>et(s)))!==null&&r!==void 0?r:[K].filter(s=>s!=null),me(a.toValue(t.value?n[1]:n[0])),me(a.unref(t.value?n[2]:n[1])),a.toValue(t.value?n[3]:n[2])]},([r,o,s,i],c,l)=>{if(!r?.length||!o?.length||!s?.length)return;const d=Ue(i)?{...i}:i,m=r.flatMap(w=>o.flatMap(P=>s.map($=>e(w,P,$,d))));l(()=>{m.forEach(w=>w())})},{flush:"post"})}const ce=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},le="__vueuse_ssr_handlers__",tt=rt();function rt(){return le in ce||(ce[le]=ce[le]||{}),ce[le]}function nt(n,e){return tt[n]||e}function ot(n){return n==null?"any":n instanceof Set?"set":n instanceof Map?"map":n instanceof Date?"date":typeof n=="boolean"?"boolean":typeof n=="string"?"string":typeof n=="object"?"object":Number.isNaN(n)?"any":"number"}const st={boolean:{read:n=>n==="true",write:n=>String(n)},object:{read:n=>JSON.parse(n),write:n=>JSON.stringify(n)},number:{read:n=>Number.parseFloat(n),write:n=>String(n)},any:{read:n=>n,write:n=>String(n)},string:{read:n=>n,write:n=>String(n)},map:{read:n=>new Map(JSON.parse(n)),write:n=>JSON.stringify(Array.from(n.entries()))},set:{read:n=>new Set(JSON.parse(n)),write:n=>JSON.stringify(Array.from(n))},date:{read:n=>new Date(n),write:n=>n.toISOString()}},$e="vueuse-storage";function it(n,e,t,r={}){var o;const{flush:s="pre",deep:i=!0,listenToStorageChanges:c=!0,writeDefaults:l=!0,mergeDefaults:d=!1,shallow:m,window:w=K,eventFilter:P,onError:$=E=>{console.error(E)},initOnMounted:L}=r,x=(m?a.shallowRef:a.ref)(e),_=a.computed(()=>a.toValue(n));if(!t)try{t=nt("getDefaultStorage",()=>K?.localStorage)()}catch(E){$(E)}if(!t)return x;const D=a.toValue(e),N=ot(D),b=(o=r.serializer)!==null&&o!==void 0?o:st[N],{pause:V,resume:O}=Qe(x,E=>p(E),{flush:s,deep:i,eventFilter:P});a.watch(_,()=>A(),{flush:s});let T=!1;const y=E=>{L&&!T||A(E)},W=E=>{L&&!T||B(E)};w&&c&&(t instanceof Storage?ee(w,"storage",y,{passive:!0}):ee(w,$e,W)),L?Ye(()=>{T=!0,A()}):A();function j(E,C){if(w){const M={key:_.value,oldValue:E,newValue:C,storageArea:t};w.dispatchEvent(t instanceof Storage?new StorageEvent("storage",M):new CustomEvent($e,{detail:M}))}}function p(E){try{const C=t.getItem(_.value);if(E==null)j(C,null),t.removeItem(_.value);else{const M=b.write(E);C!==M&&(t.setItem(_.value,M),j(C,M))}}catch(C){$(C)}}function h(E){const C=E?E.newValue:t.getItem(_.value);if(C==null)return l&&D!=null&&t.setItem(_.value,b.write(D)),D;if(!E&&d){const M=b.read(C);return typeof d=="function"?d(M,D):N==="object"&&!Array.isArray(M)?{...D,...M}:M}else return typeof C!="string"?C:b.read(C)}function A(E){if(!(E&&E.storageArea!==t)){if(E&&E.key==null){x.value=D;return}if(!(E&&E.key!==_.value)){V();try{const C=b.write(x.value);(E===void 0||E?.newValue!==C)&&(x.value=h(E))}catch(C){$(C)}finally{E?a.nextTick(O):O()}}}}function B(E){A(E.detail)}return x}function at(n,e,t={}){const{window:r=K}=t;return it(n,e,r?.localStorage,t)}const ct={ctrl:"control",command:"meta",cmd:"meta",option:"alt",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright"};function lt(n={}){const{reactive:e=!1,target:t=K,aliasMap:r=ct,passive:o=!0,onEventFired:s=_e}=n,i=a.reactive(new Set),c={toJSON(){return{}},current:i},l=e?a.reactive(c):c,d=new Set,m=new Map([["Meta",d],["Shift",new Set],["Alt",new Set]]),w=new Set;function P(N,b){N in l&&(e?l[N]=b:l[N].value=b)}function $(){i.clear();for(const N of w)P(N,!1)}function L(N,b,V){if(!(!N||typeof b.getModifierState!="function")){for(const[O,T]of m)if(b.getModifierState(O)){V.forEach(y=>T.add(y));break}}}function x(N,b){if(N)return;const V=`${b[0].toUpperCase()}${b.slice(1)}`,O=m.get(V);if(!["shift","alt"].includes(b)||!O)return;const T=Array.from(O),y=T.indexOf(b);T.forEach((W,j)=>{j>=y&&(i.delete(W),P(W,!1))}),O.clear()}function _(N,b){var V,O;const T=(V=N.key)===null||V===void 0?void 0:V.toLowerCase(),y=[(O=N.code)===null||O===void 0?void 0:O.toLowerCase(),T].filter(Boolean);if(T!==""){T&&(b?i.add(T):i.delete(T));for(const W of y)w.add(W),P(W,b);L(b,N,[...i,...y]),x(b,T),T==="meta"&&!b&&(d.forEach(W=>{i.delete(W),P(W,!1)}),d.clear())}}ee(t,"keydown",N=>(_(N,!0),s(N)),{passive:o}),ee(t,"keyup",N=>(_(N,!1),s(N)),{passive:o}),ee("blur",$,{passive:o}),ee("focus",$,{passive:o});const D=new Proxy(l,{get(N,b,V){if(typeof b!="string")return Reflect.get(N,b,V);if(b=b.toLowerCase(),b in r&&(b=r[b]),!(b in l))if(/[+_-]/.test(b)){const T=b.split(/[+_-]/g).map(y=>y.trim());l[b]=a.computed(()=>T.map(y=>a.toValue(D[y])).every(Boolean))}else l[b]=a.shallowRef(!1);const O=Reflect.get(N,b,V);return e?a.toValue(O):O}});return D}function ye(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function ue(n){const e={type:n.type,clientId:n.clientId,timestamp:n.timestamp.toISOString()};return n.operation&&(e.operation={...n.operation,timestamp:n.operation.timestamp.toISOString()}),n.operations&&(e.operations=n.operations.map(t=>({...t,timestamp:t.timestamp.toISOString()}))),e}function ut(n){const e={type:n.type,clientId:n.clientId,timestamp:new Date(n.timestamp)};return n.operation&&(e.operation={...n.operation,timestamp:new Date(n.operation.timestamp)}),n.operations&&(e.operations=n.operations.map(t=>({...t,timestamp:new Date(t.timestamp)}))),e}const te=Be("hst-operation-log",()=>{const n=a.ref({maxOperations:100,enableCrossTabSync:!0,autoSyncInterval:3e4,enablePersistence:!1,persistenceKeyPrefix:"stonecrop-ops"}),e=a.ref([]),t=a.ref(-1),r=a.ref(ye()),o=a.ref(!1),s=a.ref([]),i=a.ref(null),c=a.computed(()=>t.value<0?!1:e.value[t.value]?.reversible??!1),l=a.computed(()=>t.value<e.value.length-1),d=a.computed(()=>{let f=0;for(let u=t.value;u>=0&&e.value[u]?.reversible;u--)f++;return f}),m=a.computed(()=>e.value.length-1-t.value),w=a.computed(()=>({canUndo:c.value,canRedo:l.value,undoCount:d.value,redoCount:m.value,currentIndex:t.value}));function P(f){n.value={...n.value,...f},n.value.enablePersistence&&(v(),S()),n.value.enableCrossTabSync&&h()}function $(f,u="user"){const g={...f,id:ye(),timestamp:new Date,source:u,userId:n.value.userId};if(n.value.operationFilter&&!n.value.operationFilter(g))return g.id;if(o.value)return s.value.push(g),g.id;if(t.value<e.value.length-1&&(e.value=e.value.slice(0,t.value+1)),e.value.push(g),t.value++,n.value.maxOperations&&e.value.length>n.value.maxOperations){const k=e.value.length-n.value.maxOperations;e.value=e.value.slice(k),t.value-=k}return n.value.enableCrossTabSync&&A(g),g.id}function L(){o.value=!0,s.value=[],i.value=ye()}function x(f){if(!o.value||s.value.length===0)return o.value=!1,s.value=[],i.value=null,null;const u=i.value,g=s.value.every(F=>F.reversible),k={id:u,type:"batch",path:"",fieldname:"",beforeValue:null,afterValue:null,doctype:s.value[0]?.doctype||"",timestamp:new Date,source:"user",reversible:g,irreversibleReason:g?void 0:"Contains irreversible operations",childOperationIds:s.value.map(F=>F.id),metadata:{description:f}};s.value.forEach(F=>{F.parentOperationId=u}),e.value.push(...s.value,k),t.value=e.value.length-1,n.value.enableCrossTabSync&&B(s.value,k);const U=u;return o.value=!1,s.value=[],i.value=null,U}function _(){o.value=!1,s.value=[],i.value=null}function D(f){if(!c.value)return!1;const u=e.value[t.value];if(!u.reversible)return typeof console<"u"&&u.irreversibleReason&&console.warn("Cannot undo irreversible operation:",u.irreversibleReason),!1;try{if(u.type==="batch"&&u.childOperationIds)for(let g=u.childOperationIds.length-1;g>=0;g--){const k=u.childOperationIds[g],U=e.value.find(F=>F.id===k);U&&b(U,f)}else b(u,f);return t.value--,n.value.enableCrossTabSync&&E(u),!0}catch(g){return typeof console<"u"&&console.error("Undo failed:",g),!1}}function N(f){if(!l.value)return!1;const u=e.value[t.value+1];try{if(u.type==="batch"&&u.childOperationIds)for(const g of u.childOperationIds){const k=e.value.find(U=>U.id===g);k&&V(k,f)}else V(u,f);return t.value++,n.value.enableCrossTabSync&&C(u),!0}catch(g){return typeof console<"u"&&console.error("Redo failed:",g),!1}}function b(f,u){(f.type==="set"||f.type==="delete")&&u&&typeof u.set=="function"&&u.set(f.path,f.beforeValue,"undo")}function V(f,u){(f.type==="set"||f.type==="delete")&&u&&typeof u.set=="function"&&u.set(f.path,f.afterValue,"redo")}function O(){const f=e.value.filter(g=>g.reversible).length,u=e.value.map(g=>g.timestamp);return{operations:[...e.value],currentIndex:t.value,totalOperations:e.value.length,reversibleOperations:f,irreversibleOperations:e.value.length-f,oldestOperation:u.length>0?new Date(Math.min(...u.map(g=>g.getTime()))):void 0,newestOperation:u.length>0?new Date(Math.max(...u.map(g=>g.getTime()))):void 0}}function T(){e.value=[],t.value=-1}function y(f,u){return e.value.filter(g=>g.doctype===f&&(u===void 0||g.recordId===u))}function W(f,u){const g=e.value.find(k=>k.id===f);g&&(g.reversible=!1,g.irreversibleReason=u)}function j(f,u,g,k="success",U){const F={type:"action",path:g&&g.length>0?`${f}.${g[0]}`:f,fieldname:"",beforeValue:null,afterValue:null,doctype:f,recordId:g&&g.length>0?g[0]:void 0,reversible:!1,actionName:u,actionRecordIds:g,actionResult:k,actionError:U};return $(F)}let p=null;function h(){typeof window>"u"||!window.BroadcastChannel||(p=new BroadcastChannel("stonecrop-operation-log"),p.addEventListener("message",f=>{const u=f.data;if(!u||typeof u!="object")return;const g=ut(u);g.clientId!==r.value&&(g.type==="operation"&&g.operation?(e.value.push({...g.operation,source:"sync"}),t.value=e.value.length-1):g.type==="operation"&&g.operations&&(e.value.push(...g.operations.map(k=>({...k,source:"sync"}))),t.value=e.value.length-1))}))}function A(f){if(!p)return;const u={type:"operation",operation:f,clientId:r.value,timestamp:new Date};p.postMessage(ue(u))}function B(f,u){if(!p)return;const g={type:"operation",operations:[...f,u],clientId:r.value,timestamp:new Date};p.postMessage(ue(g))}function E(f){if(!p)return;const u={type:"undo",operation:f,clientId:r.value,timestamp:new Date};p.postMessage(ue(u))}function C(f){if(!p)return;const u={type:"redo",operation:f,clientId:r.value,timestamp:new Date};p.postMessage(ue(u))}const M=at("stonecrop-ops-operations",null,{serializer:{read:f=>{try{return JSON.parse(f)}catch{return null}},write:f=>f?JSON.stringify(f):""}});function v(){if(!(typeof window>"u"))try{const f=M.value;f&&Array.isArray(f.operations)&&(e.value=f.operations.map(u=>({...u,timestamp:new Date(u.timestamp)})),t.value=f.currentIndex??-1)}catch(f){typeof console<"u"&&console.error("Failed to load operations from persistence:",f)}}function R(){if(!(typeof window>"u"))try{M.value={operations:e.value.map(f=>({...f,timestamp:f.timestamp.toISOString()})),currentIndex:t.value}}catch(f){typeof console<"u"&&console.error("Failed to save operations to persistence:",f)}}function S(){a.watch([e,t],()=>{n.value.enablePersistence&&R()},{deep:!0})}return{operations:e,currentIndex:t,config:n,clientId:r,undoRedoState:w,canUndo:c,canRedo:l,undoCount:d,redoCount:m,configure:P,addOperation:$,startBatch:L,commitBatch:x,cancelBatch:_,undo:D,redo:N,clear:T,getOperationsFor:y,getSnapshot:O,markIrreversible:W,logAction:j}});class ie{static _root;options;doctypeActions=new Map;doctypeTransitions=new Map;fieldRollbackConfig=new Map;globalActions=new Map;globalTransitionActions=new Map;constructor(e={}){if(ie._root)return ie._root;ie._root=this,this.options={defaultTimeout:e.defaultTimeout??5e3,debug:e.debug??!1,enableRollback:e.enableRollback??!0,errorHandler:e.errorHandler}}registerAction(e,t){this.globalActions.set(e,t)}registerTransitionAction(e,t){this.globalTransitionActions.set(e,t)}setFieldRollback(e,t,r){this.fieldRollbackConfig.has(e)||this.fieldRollbackConfig.set(e,new Map),this.fieldRollbackConfig.get(e).set(t,r)}getFieldRollback(e,t){return this.fieldRollbackConfig.get(e)?.get(t)}registerDoctypeActions(e,t){if(!t)return;const r=new Map,o=new Map;if(typeof t.entrySeq=="function")t.entrySeq().forEach(([s,i])=>{this.categorizeAction(s,i,r,o)});else if(t instanceof Map)for(const[s,i]of t)this.categorizeAction(s,i,r,o);else t&&typeof t=="object"&&Object.entries(t).forEach(([s,i])=>{this.categorizeAction(s,i,r,o)});this.doctypeActions.set(e,r),this.doctypeTransitions.set(e,o)}categorizeAction(e,t,r,o){this.isTransitionKey(e)?o.set(e,t):r.set(e,t)}isTransitionKey(e){return/^[A-Z0-9_]+$/.test(e)&&e.length>0}async executeFieldTriggers(e,t={}){const{doctype:r,fieldname:o}=e,s=this.findFieldTriggers(r,o);if(s.length===0)return{path:e.path,actionResults:[],totalExecutionTime:0,allSucceeded:!0,stoppedOnError:!1,rolledBack:!1};const i=performance.now(),c=[];let l=!1,d=!1,m;const w=this.getFieldRollback(r,o),P=t.enableRollback??w??this.options.enableRollback;P&&e.store&&(m=this.captureSnapshot(e));for(const _ of s)try{const D=await this.executeAction(_,e,t.timeout);if(c.push(D),!D.success){l=!0;break}}catch(D){const b={success:!1,error:D instanceof Error?D:new Error(String(D)),executionTime:0,action:_};c.push(b),l=!0;break}if(P&&l&&m&&e.store)try{this.restoreSnapshot(e,m),d=!0}catch(_){console.error("[FieldTriggers] Rollback failed:",_)}const $=performance.now()-i,L=c.filter(_=>!_.success);if(L.length>0&&this.options.errorHandler)for(const _ of L)try{this.options.errorHandler(_.error,e,_.action)}catch(D){console.error("[FieldTriggers] Error in global error handler:",D)}return{path:e.path,actionResults:c,totalExecutionTime:$,allSucceeded:c.every(_=>_.success),stoppedOnError:l,rolledBack:d,snapshot:this.options.debug&&P?m:void 0}}async executeTransitionActions(e,t={}){const{doctype:r,transition:o}=e,s=this.findTransitionActions(r,o);if(s.length===0)return[];const i=[];for(const l of s)try{const d=await this.executeTransitionAction(l,e,t.timeout);if(i.push(d),!d.success)break}catch(d){const w={success:!1,error:d instanceof Error?d:new Error(String(d)),executionTime:0,action:l,transition:o};i.push(w);break}const c=i.filter(l=>!l.success);if(c.length>0&&this.options.errorHandler)for(const l of c)try{this.options.errorHandler(l.error,e,l.action)}catch(d){console.error("[FieldTriggers] Error in global error handler:",d)}return i}findTransitionActions(e,t){const r=this.doctypeTransitions.get(e);return r?r.get(t)||[]:[]}async executeTransitionAction(e,t,r){const o=performance.now(),s=r??this.options.defaultTimeout;try{let i=this.globalTransitionActions.get(e);if(!i){const l=this.globalActions.get(e);l&&(i=l)}if(!i)throw new Error(`Transition action "${e}" not found in registry`);return await this.executeWithTimeout(i,t,s),{success:!0,executionTime:performance.now()-o,action:e,transition:t.transition}}catch(i){const c=performance.now()-o;return{success:!1,error:i instanceof Error?i:new Error(String(i)),executionTime:c,action:e,transition:t.transition}}}findFieldTriggers(e,t){const r=this.doctypeActions.get(e);if(!r)return[];const o=[];for(const[s,i]of r)this.isFieldTriggerKey(s,t)&&o.push(...i);return o}isFieldTriggerKey(e,t){return e===t?!0:e.includes(".")?this.matchFieldPattern(e,t):e.includes("*")?this.matchFieldPattern(e,t):!1}matchFieldPattern(e,t){const r=e.split("."),o=t.split(".");if(r.length!==o.length)return!1;for(let s=0;s<r.length;s++){const i=r[s],c=o[s];if(i!=="*"&&i!==c)return!1}return!0}async executeAction(e,t,r){const o=performance.now(),s=r??this.options.defaultTimeout;try{const i=this.globalActions.get(e);if(!i)throw new Error(`Action "${e}" not found in registry`);return await this.executeWithTimeout(i,t,s),{success:!0,executionTime:performance.now()-o,action:e}}catch(i){const c=performance.now()-o;return{success:!1,error:i instanceof Error?i:new Error(String(i)),executionTime:c,action:e}}}async executeWithTimeout(e,t,r){return new Promise((o,s)=>{const i=setTimeout(()=>{s(new Error(`Action timeout after ${r}ms`))},r);Promise.resolve(e(t)).then(c=>{clearTimeout(i),o(c)}).catch(c=>{clearTimeout(i),s(c)})})}captureSnapshot(e){if(!(!e.store||!e.doctype||!e.recordId))try{const t=`${e.doctype}.${e.recordId}`,r=e.store.get(t);return!r||typeof r!="object"?void 0:JSON.parse(JSON.stringify(r))}catch(t){this.options.debug&&console.warn("[FieldTriggers] Failed to capture snapshot:",t);return}}restoreSnapshot(e,t){if(!(!e.store||!e.doctype||!e.recordId||!t))try{const r=`${e.doctype}.${e.recordId}`;e.store.set(r,t),this.options.debug&&console.log(`[FieldTriggers] Rolled back ${r} to previous state`)}catch(r){throw console.error("[FieldTriggers] Failed to restore snapshot:",r),r}}}function z(n){return new ie(n)}function ft(n,e){z().registerAction(n,e)}function dt(n,e){z().registerTransitionAction(n,e)}function pt(n,e,t){z().setFieldRollback(n,e,t)}async function ht(n,e,t){const r=z(),o={path:t?.path||(t?.recordId?`${n}.${t.recordId}`:n),fieldname:"",beforeValue:void 0,afterValue:void 0,operation:"set",doctype:n,recordId:t?.recordId,timestamp:new Date,transition:e,currentState:t?.currentState,targetState:t?.targetState,fsmContext:t?.fsmContext};return await r.executeTransitionActions(o)}function gt(n,e){if(n)try{te().markIrreversible(n,e)}catch{}}function De(){try{return te()}catch{return null}}class Z{static instance;static getInstance(){return Z.instance||(Z.instance=new Z),Z.instance}getRegistry(){if(typeof globalThis<"u"){const e=globalThis.Registry?._root;if(e)return e}if(typeof window<"u"){const e=window.Registry?._root;if(e)return e}if(typeof global<"u"&&global){const e=global.Registry?._root;if(e)return e}}getDoctypeMeta(e){const t=this.getRegistry();if(t&&typeof t=="object"&&"registry"in t)return t.registry[e]}}class fe{target;parentPath;rootNode;doctype;parentDoctype;hst;constructor(e,t,r="",o=null,s){return this.target=e,this.parentPath=r,this.rootNode=o||this,this.doctype=t,this.parentDoctype=s,this.hst=Z.getInstance(),new Proxy(this,{get(i,c){if(c in i)return i[c];const l=String(c);return i.getNode(l)},set(i,c,l){const d=String(c);return i.set(d,l),!0}})}get(e){return this.resolveValue(e)}getNode(e){const t=this.resolvePath(e),r=this.resolveValue(e),o=t.split(".");let s=this.doctype;return this.doctype==="StonecropStore"&&o.length>=1&&(s=o[0]),typeof r=="object"&&r!==null&&!this.isPrimitive(r)?new fe(r,s,t,this.rootNode,this.parentDoctype):new fe(r,s,t,this.rootNode,this.parentDoctype)}set(e,t,r="user"){const o=this.resolvePath(e),s=this.has(e)?this.get(e):void 0;if(r!=="undo"&&r!=="redo"){const i=De();if(i&&typeof i.addOperation=="function"){const c=o.split("."),l=this.doctype==="StonecropStore"&&c.length>=1?c[0]:this.doctype,d=c.length>=2?c[1]:void 0,m=c.slice(2).join(".")||c[c.length-1],P=t===void 0&&s!==void 0?"delete":"set";i.addOperation({type:P,path:o,fieldname:m,beforeValue:s,afterValue:t,doctype:l,recordId:d,reversible:!0},r)}}this.updateValue(e,t),this.triggerFieldActions(o,s,t)}has(e){try{if(e==="")return!0;const t=this.parsePath(e);let r=this.target;for(let o=0;o<t.length;o++){const s=t[o];if(r==null)return!1;if(o===t.length-1)return this.isImmutable(r)?r.has(s):this.isPiniaStore(r)&&r.$state&&s in r.$state||s in r;r=this.getProperty(r,s)}return!1}catch{return!1}}getParent(){if(!this.parentPath)return null;const t=this.parentPath.split(".").slice(0,-1).join(".");return t===""?this.rootNode:this.rootNode.getNode(t)}getRoot(){return this.rootNode}getPath(){return this.parentPath}getDepth(){return this.parentPath?this.parentPath.split(".").length:0}getBreadcrumbs(){return this.parentPath?this.parentPath.split("."):[]}async triggerTransition(e,t){const r=z(),o=this.parentPath.split(".");let s=this.doctype,i;this.doctype==="StonecropStore"&&o.length>=1&&(s=o[0]),o.length>=2&&(i=o[1]);const c={path:this.parentPath,fieldname:"",beforeValue:void 0,afterValue:void 0,operation:"set",doctype:s,recordId:i,timestamp:new Date,store:this.rootNode||void 0,transition:e,currentState:t?.currentState,targetState:t?.targetState,fsmContext:t?.fsmContext},l=De();return l&&typeof l.addOperation=="function"&&l.addOperation({type:"transition",path:this.parentPath,fieldname:e,beforeValue:t?.currentState,afterValue:t?.targetState,doctype:s,recordId:i,reversible:!1,metadata:{transition:e,currentState:t?.currentState,targetState:t?.targetState,fsmContext:t?.fsmContext}},"user"),await r.executeTransitionActions(c)}resolvePath(e){return e===""?this.parentPath:this.parentPath?`${this.parentPath}.${e}`:e}resolveValue(e){if(e==="")return this.target;const t=this.parsePath(e);let r=this.target;for(const o of t){if(r==null)return;r=this.getProperty(r,o)}return r}updateValue(e,t){if(e==="")throw new Error("Cannot set value on empty path");const r=this.parsePath(e),o=r.pop();let s=this.target;for(const i of r)if(s=this.getProperty(s,i),s==null)throw new Error(`Cannot set property on null/undefined path: ${e}`);this.setProperty(s,o,t)}getProperty(e,t){return this.isImmutable(e)?e.get(t):this.isVueReactive(e)?e[t]:this.isPiniaStore(e)?e.$state?.[t]??e[t]:e[t]}setProperty(e,t,r){if(this.isImmutable(e))throw new Error("Cannot directly mutate immutable objects. Use immutable update methods instead.");if(this.isPiniaStore(e)){e.$patch?e.$patch({[t]:r}):e[t]=r;return}e[t]=r}async triggerFieldActions(e,t,r){try{if(!e||typeof e!="string")return;const o=e.split(".");if(o.length<3)return;const s=z(),i=o.slice(2).join(".")||o[o.length-1];let c=this.doctype;this.doctype==="StonecropStore"&&o.length>=1&&(c=o[0]);let l;o.length>=2&&(l=o[1]);const d={path:e,fieldname:i,beforeValue:t,afterValue:r,operation:"set",doctype:c,recordId:l,timestamp:new Date,store:this.rootNode||void 0};await s.executeFieldTriggers(d)}catch(o){o instanceof Error&&console.warn("Field trigger error:",o.message)}}isVueReactive(e){return e&&typeof e=="object"&&"__v_isReactive"in e&&e.__v_isReactive===!0}isPiniaStore(e){return e&&typeof e=="object"&&("$state"in e||"$patch"in e||"$id"in e)}isImmutable(e){if(!e||typeof e!="object")return!1;const t="get"in e&&typeof e.get=="function",r="set"in e&&typeof e.set=="function",o="has"in e&&typeof e.has=="function",s="__ownerID"in e||"_map"in e||"_list"in e||"_origin"in e||"_capacity"in e||"_defaultValues"in e||"_tail"in e||"_root"in e||"size"in e&&t&&r;let i;try{const l=e;if("constructor"in l&&l.constructor&&typeof l.constructor=="object"&&"name"in l.constructor){const d=l.constructor.name;i=typeof d=="string"?d:void 0}}catch{i=void 0}const c=i&&(i.includes("Map")||i.includes("List")||i.includes("Set")||i.includes("Stack")||i.includes("Seq"))&&(t||r);return!!(t&&r&&o&&s||t&&r&&c)}isPrimitive(e){return e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="function"||typeof e=="symbol"||typeof e=="bigint"}parsePath(e){return e?e.replace(/\[(\d+)\]/g,".$1").split(".").filter(r=>r.length>0):[]}}function Ie(n,e,t){return new fe(n,e,"",null,t)}class ve{hstStore;_operationLogStore;_operationLogConfig;registry;constructor(e,t){this.registry=e,this._operationLogConfig=t,this.initializeHSTStore(),this.setupRegistrySync()}getOperationLogStore(){return this._operationLogStore||(this._operationLogStore=te(),this._operationLogConfig&&this._operationLogStore.configure(this._operationLogConfig)),this._operationLogStore}initializeHSTStore(){const e={};Object.keys(this.registry.registry).forEach(t=>{e[t]={}}),this.hstStore=Ie(a.reactive(e),"StonecropStore")}setupRegistrySync(){const e=this.registry.addDoctype.bind(this.registry);this.registry.addDoctype=t=>{e(t),this.hstStore.has(t.slug)||this.hstStore.set(t.slug,{})}}records(e){const t=typeof e=="string"?e:e.slug;return this.ensureDoctypeExists(t),this.hstStore.getNode(t)}addRecord(e,t,r){const o=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(o),this.hstStore.set(`${o}.${t}`,r)}getRecordById(e,t){const r=typeof e=="string"?e:e.slug;if(this.ensureDoctypeExists(r),!(!this.hstStore.has(`${r}.${t}`)||this.hstStore.get(`${r}.${t}`)===void 0))return this.hstStore.getNode(`${r}.${t}`)}removeRecord(e,t){const r=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(r),this.hstStore.has(`${r}.${t}`)&&this.hstStore.set(`${r}.${t}`,void 0)}getRecordIds(e){const t=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(t);const r=this.hstStore.get(t);return!r||typeof r!="object"?[]:Object.keys(r).filter(o=>r[o]!==void 0)}clearRecords(e){const t=typeof e=="string"?e:e.slug;this.ensureDoctypeExists(t),this.getRecordIds(t).forEach(o=>{this.hstStore.set(`${t}.${o}`,void 0)})}setup(e){this.ensureDoctypeExists(e.slug)}runAction(e,t,r){const s=this.registry.registry[e.slug]?.actions?.get(t),i=Array.isArray(r)?r.filter(m=>typeof m=="string"):void 0,c=this.getOperationLogStore();let l="success",d;try{s&&s.length>0&&s.forEach(m=>{try{new Function("args",m)(r)}catch(w){throw l="failure",d=w instanceof Error?w.message:"Unknown error",w}})}catch{}finally{c.logAction(e.doctype,t,i,l,d)}}async getRecords(e){(await(await fetch(`/${e.slug}`)).json()).forEach(o=>{o.id&&this.addRecord(e,o.id,o)})}async getRecord(e,t){const o=await(await fetch(`/${e.slug}/${t}`)).json();this.addRecord(e,t,o)}ensureDoctypeExists(e){this.hstStore.has(e)||this.hstStore.set(e,{})}async getMeta(e){if(!this.registry.getMeta)throw new Error("No getMeta function provided to Registry");return await this.registry.getMeta(e)}getStore(){return this.hstStore}}function mt(n){n||(n={});const e=n.registry||a.inject("$registry"),t=a.inject("$stonecrop"),r=a.ref(),o=a.ref(),s=a.ref({}),i=a.ref(),c=a.ref(),l=a.ref([]);if(n.doctype&&e){const v=n.doctype.schema?Array.isArray(n.doctype.schema)?n.doctype.schema:Array.from(n.doctype.schema):[];l.value=e.resolveSchema(v)}const d=a.ref([]),m=a.ref(-1),w=a.computed(()=>r.value?.getOperationLogStore().canUndo??!1),P=a.computed(()=>r.value?.getOperationLogStore().canRedo??!1),$=a.computed(()=>r.value?.getOperationLogStore().undoCount??0),L=a.computed(()=>r.value?.getOperationLogStore().redoCount??0),x=a.computed(()=>r.value?.getOperationLogStore().undoRedoState??{canUndo:!1,canRedo:!1,undoCount:0,redoCount:0,currentIndex:-1}),_=v=>r.value?.getOperationLogStore().undo(v)??!1,D=v=>r.value?.getOperationLogStore().redo(v)??!1,N=()=>{r.value?.getOperationLogStore().startBatch()},b=v=>r.value?.getOperationLogStore().commitBatch(v)??null,V=()=>{r.value?.getOperationLogStore().cancelBatch()},O=()=>{r.value?.getOperationLogStore().clear()},T=(v,R)=>r.value?.getOperationLogStore().getOperationsFor(v,R)??[],y=()=>r.value?.getOperationLogStore().getSnapshot()??{operations:[],currentIndex:-1,totalOperations:0,reversibleOperations:0,irreversibleOperations:0},W=(v,R)=>{r.value?.getOperationLogStore().markIrreversible(v,R)},j=(v,R,S,f="success",u)=>r.value?.getOperationLogStore().logAction(v,R,S,f,u)??"",p=v=>{r.value?.getOperationLogStore().configure(v)};a.onMounted(async()=>{if(e){r.value=t||new ve(e);try{const v=r.value.getOperationLogStore(),R=Ne(v);d.value=R.operations.value,m.value=R.currentIndex.value,a.watch(()=>R.operations.value,S=>{d.value=S}),a.watch(()=>R.currentIndex.value,S=>{m.value=S})}catch{}if(!n.doctype&&e.router){const v=e.router.currentRoute.value;if(!v.path)return;const R=v.path.split("/").filter(f=>f.length>0),S=R[1]?.toLowerCase();if(R.length>0){const f={path:v.path,segments:R},u=await e.getMeta?.(f);if(u){if(e.addDoctype(u),r.value.setup(u),i.value=u,c.value=S,o.value=r.value.getStore(),e){const g=u.schema?Array.isArray(u.schema)?u.schema:Array.from(u.schema):[];l.value=e.resolveSchema(g)}if(S&&S!=="new"){const g=r.value.getRecordById(u,S);if(g)s.value=g.get("")||{};else try{await r.value.getRecord(u,S);const k=r.value.getRecordById(u,S);k&&(s.value=k.get("")||{})}catch{s.value=q(u)}}else s.value=q(u);o.value&&Ce(u,S||"new",s,o.value),r.value.runAction(u,"load",S?[S]:void 0)}}}if(n.doctype){o.value=r.value.getStore();const v=n.doctype,R=n.recordId;if(R&&R!=="new"){const S=r.value.getRecordById(v,R);if(S)s.value=S.get("")||{};else try{await r.value.getRecord(v,R);const f=r.value.getRecordById(v,R);f&&(s.value=f.get("")||{})}catch{s.value=q(v)}}else s.value=q(v);o.value&&Ce(v,R||"new",s,o.value)}}});const h=(v,R)=>{const S=n.doctype||i.value;if(!S)return"";const f=R||n.recordId||c.value||"new";return`${S.slug}.${f}.${v}`},A=v=>{const R=n.doctype||i.value;if(!(!o.value||!r.value||!R))try{const S=v.path.split(".");if(S.length>=2){const g=S[0],k=S[1];if(o.value.has(`${g}.${k}`)||r.value.addRecord(R,k,{...s.value}),S.length>3){const U=`${g}.${k}`,F=S.slice(2);let Q=U;for(let ne=0;ne<F.length-1;ne++)if(Q+=`.${F[ne]}`,!o.value.has(Q)){const be=F[ne+1],Ot=!isNaN(Number(be));o.value.set(Q,Ot?[]:{})}}}o.value.set(v.path,v.value);const f=v.fieldname.split("."),u={...s.value};f.length===1?u[f[0]]=v.value:yt(u,f,v.value),s.value=u}catch{}};(n.doctype||e?.router)&&(a.provide("hstPathProvider",h),a.provide("hstChangeHandler",A));const B=(v,R,S)=>{if(!r.value)return q(R);if(S)try{const f=o.value?.get(v);return f&&typeof f=="object"?f:q(R)}catch{return q(R)}return q(R)},E=async(v,R)=>{if(!o.value||!r.value)throw new Error("HST store not initialized");const S=`${v.slug}.${R}`,u={...o.value.get(S)||{}},g=v.schema?Array.isArray(v.schema)?v.schema:Array.from(v.schema):[],U=(e?e.resolveSchema(g):g).filter(F=>"fieldtype"in F&&F.fieldtype==="Doctype"&&"schema"in F&&Array.isArray(F.schema));for(const F of U){const Q=F,ne=`${S}.${Q.fieldname}`,be=ke(Q.schema,ne,o.value);u[Q.fieldname]=be}return u},C=(v,R)=>({provideHSTPath:u=>`${v}.${u}`,handleHSTChange:u=>{const g=u.path.startsWith(v)?u.path:`${v}.${u.fieldname}`;A({...u,path:g})}}),M={operations:d,currentIndex:m,undoRedoState:x,canUndo:w,canRedo:P,undoCount:$,redoCount:L,undo:_,redo:D,startBatch:N,commitBatch:b,cancelBatch:V,clear:O,getOperationsFor:T,getSnapshot:y,markIrreversible:W,logAction:j,configure:p};return n.doctype?{stonecrop:r,operationLog:M,provideHSTPath:h,handleHSTChange:A,hstStore:o,formData:s,resolvedSchema:l,loadNestedData:B,saveRecursive:E,createNestedContext:C}:!n.doctype&&e?.router?{stonecrop:r,operationLog:M,provideHSTPath:h,handleHSTChange:A,hstStore:o,formData:s,resolvedSchema:l,loadNestedData:B,saveRecursive:E,createNestedContext:C}:{stonecrop:r,operationLog:M}}function q(n){const e={};return n.schema&&n.schema.forEach(t=>{switch("fieldtype"in t?t.fieldtype:"Data"){case"Data":case"Text":e[t.fieldname]="";break;case"Check":e[t.fieldname]=!1;break;case"Int":case"Float":e[t.fieldname]=0;break;case"Table":e[t.fieldname]=[];break;case"JSON":e[t.fieldname]={};break;default:e[t.fieldname]=null}}),e}function Ce(n,e,t,r){a.watch(t,o=>{const s=`${n.slug}.${e}`;Object.keys(o).forEach(i=>{const c=`${s}.${i}`;try{r.set(c,o[i])}catch{}})},{deep:!0})}function yt(n,e,t){let r=n;for(let s=0;s<e.length-1;s++){const i=e[s];(!(i in r)||typeof r[i]!="object")&&(r[i]=isNaN(Number(e[s+1]))?{}:[]),r=r[i]}const o=e[e.length-1];r[o]=t}function ke(n,e,t){const o={...t.get(e)||{}},s=n.filter(i=>"fieldtype"in i&&i.fieldtype==="Doctype"&&"schema"in i&&Array.isArray(i.schema));for(const i of s){const c=i,l=`${e}.${c.fieldname}`,d=ke(c.schema,l,t);o[c.fieldname]=d}return o}function Se(n){const t=a.inject("$operationLogStore",void 0)||te();n&&t.configure(n);const{operations:r,currentIndex:o,undoRedoState:s,canUndo:i,canRedo:c,undoCount:l,redoCount:d}=Ne(t);function m(O){return t.undo(O)}function w(O){return t.redo(O)}function P(){t.startBatch()}function $(O){return t.commitBatch(O)}function L(){t.cancelBatch()}function x(){t.clear()}function _(O,T){return t.getOperationsFor(O,T)}function D(){return t.getSnapshot()}function N(O,T){t.markIrreversible(O,T)}function b(O,T,y,W="success",j){return t.logAction(O,T,y,W,j)}function V(O){t.configure(O)}return{operations:r,currentIndex:o,undoRedoState:s,canUndo:i,canRedo:c,undoCount:l,redoCount:d,undo:m,redo:w,startBatch:P,commitBatch:$,cancelBatch:L,clear:x,getOperationsFor:_,getSnapshot:D,markIrreversible:N,logAction:b,configure:V}}function vt(n,e=!0){if(!e)return;const{undo:t,redo:r,canUndo:o,canRedo:s}=Se(),i=lt();se(i["Ctrl+Z"],()=>{o.value&&t(n)}),se(i["Meta+Z"],()=>{o.value&&t(n)}),se(i["Ctrl+Shift+Z"],()=>{s.value&&r(n)}),se(i["Meta+Shift+Z"],()=>{s.value&&r(n)}),se(i["Ctrl+Y"],()=>{s.value&&r(n)})}async function St(n,e){const{startBatch:t,commitBatch:r,cancelBatch:o}=Se();t();try{return await n(),r(e)}catch(s){throw o(),s}}class bt{doctype;schema;workflow;actions;component;constructor(e,t,r,o,s){this.doctype=e,this.schema=t,this.workflow=r,this.actions=o,this.component=s}get slug(){return this.doctype.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}}class re{static _root;name;registry;router;constructor(e,t){if(re._root)return re._root;re._root=this,this.name="Registry",this.registry={},this.router=e,this.getMeta=t}getMeta;addDoctype(e){e.doctype in Object.keys(this.registry)||(this.registry[e.slug]=e);const t=z();t.registerDoctypeActions(e.doctype,e.actions),e.slug!==e.doctype&&t.registerDoctypeActions(e.slug,e.actions),e.component&&this.router&&!this.router.hasRoute(e.doctype)&&this.router.addRoute({path:`/${e.slug}`,name:e.slug,component:e.component})}resolveSchema(e,t){const r=t||new Set;return e.map(o=>{if("fieldtype"in o&&o.fieldtype==="Doctype"&&"options"in o&&typeof o.options=="string"){const s=o.options;if(r.has(s))return{...o};const i=this.registry[s];if(i&&i.schema){const c=Array.isArray(i.schema)?i.schema:Array.from(i.schema);r.add(s);const l=this.resolveSchema(c,r);return r.delete(s),{...o,schema:l}}}if("fieldtype"in o&&o.fieldtype==="Table"&&"options"in o&&typeof o.options=="string"){const s=o.options;if(r.has(s))return{...o};const i=this.registry[s];if(i&&i.schema){const c=Array.isArray(i.schema)?i.schema:Array.from(i.schema),l={...o};return(!("columns"in o)||!o.columns)&&(l.columns=c.map(d=>({name:d.fieldname,fieldname:d.fieldname,label:"label"in d&&d.label||d.fieldname,fieldtype:"fieldtype"in d?d.fieldtype:"Data",align:"align"in d&&d.align||"left",edit:"edit"in d?d.edit:!0,width:"width"in d&&d.width||"20ch"}))),l.component||(l.component="ATable"),(!("config"in o)||!o.config)&&(l.config={view:"list"}),(!("rows"in o)||!o.rows)&&(l.rows=[]),l}}return{...o}})}initializeRecord(e){const t={};return e.forEach(r=>{switch("fieldtype"in r?r.fieldtype:"Data"){case"Data":case"Text":case"Code":t[r.fieldname]="";break;case"Check":t[r.fieldname]=!1;break;case"Int":case"Float":case"Decimal":case"Currency":case"Quantity":t[r.fieldname]=0;break;case"Table":t[r.fieldname]=[];break;case"JSON":t[r.fieldname]={};break;case"Doctype":"schema"in r&&Array.isArray(r.schema)?t[r.fieldname]=this.initializeRecord(r.schema):t[r.fieldname]={};break;default:t[r.fieldname]=null}}),t}}async function wt(n,e,t){await a.nextTick();try{await t(n,e)}catch{}}const Et={install:(n,e)=>{const t=n.config.globalProperties.$router,r=e?.router,o=t||r;!t&&r&&n.use(r);const s=new re(o,e?.getMeta);n.provide("$registry",s),n.config.globalProperties.$registry=s;const i=new ve(s);n.provide("$stonecrop",i),n.config.globalProperties.$stonecrop=i;try{const c=n.config.globalProperties.$pinia;if(c){const l=te(c);n.provide("$operationLogStore",l),n.config.globalProperties.$operationLogStore=l}}catch(c){console.warn("Pinia not available - operation log features will be disabled:",c)}if(e?.components)for(const[c,l]of Object.entries(e.components))n.component(c,l);e?.autoInitializeRouter&&e.onRouterInitialized&&wt(s,i,e.onRouterInitialized)}};var Ve=(n=>(n.ERROR="error",n.WARNING="warning",n.INFO="info",n))(Ve||{});class Le{options;constructor(e={}){this.options={registry:e.registry||null,validateLinkTargets:e.validateLinkTargets??!0,validateActions:e.validateActions??!0,validateWorkflows:e.validateWorkflows??!0,validateRequiredProperties:e.validateRequiredProperties??!0}}validate(e,t,r,o){const s=[],i=t?Array.isArray(t)?t:t.toArray():[];if(this.options.validateRequiredProperties&&s.push(...this.validateRequiredProperties(e,i)),this.options.validateLinkTargets&&this.options.registry&&s.push(...this.validateLinkFields(e,i,this.options.registry)),this.options.validateWorkflows&&r&&s.push(...this.validateWorkflow(e,r)),this.options.validateActions&&o){const m=o instanceof Map?o:o.toObject();s.push(...this.validateActionRegistration(e,m))}const c=s.filter(m=>m.severity==="error").length,l=s.filter(m=>m.severity==="warning").length,d=s.filter(m=>m.severity==="info").length;return{valid:c===0,issues:s,errorCount:c,warningCount:l,infoCount:d}}validateRequiredProperties(e,t){const r=[];for(const o of t){if(!o.fieldname){r.push({severity:"error",rule:"required-fieldname",message:"Field is missing required property: fieldname",doctype:e,context:{field:o}});continue}if(!o.component&&!("fieldtype"in o)&&r.push({severity:"error",rule:"required-component-or-fieldtype",message:`Field "${o.fieldname}" must have either component or fieldtype property`,doctype:e,fieldname:o.fieldname}),"schema"in o){const s=o.schema,i=Array.isArray(s)?s:s.toArray?.()||[];r.push(...this.validateRequiredProperties(e,i))}}return r}validateLinkFields(e,t,r){const o=[];for(const s of t){if(("fieldtype"in s?s.fieldtype:void 0)==="Link"){const c="options"in s?s.options:void 0;if(!c){o.push({severity:"error",rule:"link-missing-options",message:`Link field "${s.fieldname}" is missing options property (target doctype)`,doctype:e,fieldname:s.fieldname});continue}const l=typeof c=="string"?c:"";if(!l){o.push({severity:"error",rule:"link-invalid-options",message:`Link field "${s.fieldname}" has invalid options format (expected string doctype name)`,doctype:e,fieldname:s.fieldname});continue}r.registry[l]||r.registry[l.toLowerCase()]||o.push({severity:"error",rule:"link-invalid-target",message:`Link field "${s.fieldname}" references non-existent doctype: "${l}"`,doctype:e,fieldname:s.fieldname,context:{targetDoctype:l}})}if("schema"in s){const c=s.schema,l=Array.isArray(c)?c:c.toArray?.()||[];o.push(...this.validateLinkFields(e,l,r))}}return o}validateWorkflow(e,t){const r=[];if(!t.initial&&!t.type&&r.push({severity:"warning",rule:"workflow-missing-initial",message:"Workflow is missing initial state property",doctype:e}),!t.states||Object.keys(t.states).length===0)return r.push({severity:"warning",rule:"workflow-no-states",message:"Workflow has no states defined",doctype:e}),r;t.initial&&typeof t.initial=="string"&&!t.states[t.initial]&&r.push({severity:"error",rule:"workflow-invalid-initial",message:`Workflow initial state "${t.initial}" does not exist in states`,doctype:e,context:{initialState:t.initial}});const o=Object.keys(t.states),s=new Set;t.initial&&typeof t.initial=="string"&&s.add(t.initial);for(const[i,c]of Object.entries(t.states)){const l=c;if(l.on){for(const[d,m]of Object.entries(l.on))if(typeof m=="string")s.add(m);else if(m&&typeof m=="object"){const w="target"in m?m.target:void 0;typeof w=="string"?s.add(w):Array.isArray(w)&&w.forEach(P=>{typeof P=="string"&&s.add(P)})}}}for(const i of o)s.has(i)||r.push({severity:"warning",rule:"workflow-unreachable-state",message:`Workflow state "${i}" may not be reachable`,doctype:e,context:{stateName:i}});return r}validateActionRegistration(e,t){const r=[],o=z();for(const[s,i]of Object.entries(t)){if(!Array.isArray(i)){r.push({severity:"error",rule:"action-invalid-format",message:`Action configuration for "${s}" must be an array`,doctype:e,context:{triggerName:s,actionNames:i}});continue}for(const c of i){const l=o;l.globalActions?.has(c)||l.globalTransitionActions?.has(c)||r.push({severity:"warning",rule:"action-not-registered",message:`Action "${c}" referenced in "${s}" is not registered in FieldTriggerEngine`,doctype:e,context:{triggerName:s,actionName:c}})}}return r}}function Me(n,e){return new Le({registry:n,...e})}function Rt(n,e,t,r,o){return Me(t).validate(n,e,r,o)}I.DoctypeMeta=bt,I.HST=Z,I.Registry=re,I.SchemaValidator=Le,I.Stonecrop=ve,I.ValidationSeverity=Ve,I.createHST=Ie,I.createValidator=Me,I.default=Et,I.getGlobalTriggerEngine=z,I.markOperationIrreversible=gt,I.registerGlobalAction=ft,I.registerTransitionAction=dt,I.setFieldRollback=pt,I.triggerTransition=ht,I.useOperationLog=Se,I.useOperationLogStore=te,I.useStonecrop=mt,I.useUndoRedoShortcuts=vt,I.validateSchema=Rt,I.withBatch=St,Object.defineProperties(I,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
6
6
|
//# sourceMappingURL=stonecrop.umd.cjs.map
|