@stonecrop/stonecrop 0.8.3 → 0.8.5

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.
@@ -2,5 +2,5 @@
2
2
  state: () => new MyClass()
3
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.`);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"}})}));
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}}function Qe(n,e=!0,t){Ge()?a.onMounted(n,t):e?n():a.nextTick(n)}function Ye(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 Xe(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 Ye(()=>{var r,o;return[(r=(o=t.value)===null||o===void 0?void 0:o.map(s=>Xe(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__",et=tt();function tt(){return le in ce||(ce[le]=ce[le]||{}),ce[le]}function rt(n,e){return et[n]||e}function nt(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 ot={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 st(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=rt("getDefaultStorage",()=>K?.localStorage)()}catch(E){$(E)}if(!t)return x;const D=a.toValue(e),N=nt(D),b=(o=r.serializer)!==null&&o!==void 0?o:ot[N],{pause:V,resume:O}=Ze(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?Qe(()=>{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 it(n,e,t={}){const{window:r=K}=t;return st(n,e,r?.localStorage,t)}const at={ctrl:"control",command:"meta",cmd:"meta",option:"alt",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright"};function ct(n={}){const{reactive:e=!1,target:t=K,aliasMap:r=at,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 lt(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=lt(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=it("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 ut(n,e){z().registerAction(n,e)}function ft(n,e){z().registerTransitionAction(n,e)}function dt(n,e,t){z().setFieldRollback(n,e,t)}async function pt(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 ht(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 gt(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],Rt=!isNaN(Number(be));o.value.set(Q,Rt?[]:{})}}}o.value.set(v.path,v.value);const f=v.fieldname.split("."),u={...s.value};f.length===1?u[f[0]]=v.value:mt(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 mt(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 yt(n,e=!0){if(!e)return;const{undo:t,redo:r,canUndo:o,canRedo:s}=Se(),i=ct();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 vt(n,e){const{startBatch:t,commitBatch:r,cancelBatch:o}=Se();t();try{return await n(),r(e)}catch(s){throw o(),s}}class St{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 bt(n,e,t){await a.nextTick();try{await t(n,e)}catch{}}const wt={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&&bt(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 Et(n,e,t,r,o){return Me(t).validate(n,e,r,o)}I.DoctypeMeta=St,I.HST=Z,I.Registry=re,I.SchemaValidator=Le,I.Stonecrop=ve,I.ValidationSeverity=Ve,I.createHST=Ie,I.createValidator=Me,I.default=wt,I.getGlobalTriggerEngine=z,I.markOperationIrreversible=ht,I.registerGlobalAction=ut,I.registerTransitionAction=ft,I.setFieldRollback=dt,I.triggerTransition=pt,I.useOperationLog=Se,I.useOperationLogStore=te,I.useStonecrop=gt,I.useUndoRedoShortcuts=yt,I.validateSchema=Et,I.withBatch=vt,Object.defineProperties(I,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
6
6
  //# sourceMappingURL=stonecrop.umd.cjs.map