@rilaykit/workflow 9.0.0 → 9.0.1
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/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var core=require('@rilaykit/core'),forms=require('@rilaykit/forms'),ft=require('react'),Pe=require('@noble/ed25519'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ft__default=/*#__PURE__*/_interopDefault(ft);var Pe__namespace=/*#__PURE__*/_interopNamespace(Pe);var V=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new core.IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof forms.form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=core.normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=core.deepClone(this.steps),n.analytics=this.analytics?core.deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?core.deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{core.ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(o=>o.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var Xe=1751361139160,He="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",x=class x{static async setLicenseKey(e){x.licenseKey=e||"",x.licenseKey?x.licenseResult=await x.validateLicense():x.licenseResult={valid:false,error:"MISSING"},x.isInitialized=true;}static async validateLicense(){if(!x.licenseKey)return {valid:false,error:"MISSING"};try{if(!x.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=x.licenseKey.slice(4),n=x.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,o]=n,a=`${i}.${s}`,c=new TextEncoder().encode(a),l=o.match(/.{2}/g);if(!l)return {valid:!1,error:"INVALID"};let p=new Uint8Array(l.map(W=>Number.parseInt(W,16))),f=x.hexToBytes(He);if(!await Pe__namespace.verify(p,c,f))return {valid:!1,error:"SIGNATURE_INVALID"};let m=x.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(m),u=Math.floor(Date.now()/1e3);return d.e<u?{valid:!1,error:"EXPIRED",data:x.decompressPayload(d)}:Xe>d.e*1e3?{valid:!1,error:"EXPIRED",data:x.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:x.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let o=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),p=o<<18|a<<12|c<<6|l;n+=String.fromCharCode(p>>16&255),c!==64&&(n+=String.fromCharCode(p>>8&255)),l!==64&&(n+=String.fromCharCode(p&255));}return n}static getLicenseResult(){return x.isInitialized?x.licenseResult?x.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!x.getLicenseResult().valid}static getWatermarkMessage(){let e=x.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=x.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=x.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};x.licenseKey="",x.licenseResult=null,x.isInitialized=false;var F=x;function Q(t,e={},r={}){return ft.useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,core.evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function Ie(t,e={}){return ft.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=o=>{try{return o&&typeof o=="object"&&"build"in o?core.evaluateCondition(o.build(),e):core.evaluateCondition(o,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function We(t,e={}){return ft.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let o=a=>{try{return a&&typeof a=="object"&&"build"in a?core.evaluateCondition(a.build(),e):core.evaluateCondition(a,e)}catch(c){return console.warn(`Error evaluating condition for step ${s}:`,c),false}};r[s]={visible:i.visible?o(i.visible):true,disabled:i.disabled?o(i.disabled):false,required:i.required?o(i.required):false,readonly:i.readonly?o(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function j(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function De(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function Ze(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function ee(t,e){return e?`${e}:${t}`:t}function te(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function Ye(t,e,r="persist"){let n=De(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function z({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,o]=ft.useState(false),[a,c]=ft.useState(null),[l,p]=ft.useState(false),f=ft.useRef(r),S=ft.useRef(n),m=ft.useRef({hasPendingChanges:false});ft.useEffect(()=>{f.current=r,S.current=n;},[r,n]);let d=ee(S.current.storageKey||t,i),u=ft.useCallback(()=>{c(null);},[]),k=ft.useCallback((b,I)=>{let T=b instanceof D?b:new D(`${I} failed: ${b.message}`,"OPERATION_FAILED",b);c(T),console.error("[WorkflowPersistence]",T);},[]),W=ft.useCallback(async b=>{u(),o(true);try{let I=j(t,b,S.current.metadata);await f.current.save(d,I),m.current.lastSavedState={...b},m.current.hasPendingChanges=!1;}catch(I){throw k(I,"Save"),I}finally{o(false);}},[t,d,u,k]),g=ft.useRef(te(async b=>{try{await W(b);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),h=ft.useCallback((b,I)=>I?b.currentStepIndex!==I.currentStepIndex||JSON.stringify(b.allData)!==JSON.stringify(I.allData)||JSON.stringify(b.stepData)!==JSON.stringify(I.stepData)||b.visitedSteps.size!==I.visitedSteps.size||!Array.from(b.visitedSteps).every(T=>I.visitedSteps.has(T)):true,[]),P=ft.useCallback(async()=>{u(),p(true);try{let b=await f.current.load(d);return b&&(m.current.lastSavedState={currentStepIndex:b.currentStepIndex,allData:b.allData,stepData:b.stepData,visitedSteps:new Set(b.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},m.current.hasPendingChanges=!1),b}catch(b){return k(b,"Load"),null}finally{setTimeout(()=>p(false),100);}},[d,u,k]),w=ft.useCallback(async()=>{u();try{await f.current.remove(d),m.current.lastSavedState=void 0,m.current.hasPendingChanges=!1;}catch(b){throw k(b,"Clear"),b}},[d,u,k]),y=ft.useCallback(async()=>{try{return await f.current.exists(d)}catch(b){return k(b,"Exists check"),false}},[d,k]);ft.useEffect(()=>{S.current.autoPersist&&(s||l||e.isInitializing||e.isSubmitting||e.isTransitioning||h(e,m.current.lastSavedState)&&(m.current.hasPendingChanges=true,g.current(e)));},[e,s,l,h]);let v=ft.useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:P,clearPersistedData:w,hasPersistedData:y}}function Qe(){let{workflowConfig:t,currentStep:e}=E(),r=ft.useMemo(()=>e?.metadata,[e?.metadata]),n=ft.useMemo(()=>l=>t.steps.find(f=>f.id===l)?.metadata,[t.steps]),i=ft.useMemo(()=>l=>t.steps[l]?.metadata,[t.steps]),s=ft.useMemo(()=>l=>r?l in r:false,[r]),o=ft.useMemo(()=>(l,p)=>r&&l in r?r[l]:p,[r]),a=ft.useMemo(()=>()=>t.steps.map((l,p)=>({id:l.id,title:l.title,index:p,metadata:l.metadata})),[t.steps]),c=ft.useMemo(()=>l=>t.steps.map((p,f)=>({step:p,index:f})).filter(({step:p,index:f})=>l(p.metadata,p.id,f)).map(({step:p})=>p.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:o,getAllStepsMetadata:a,findStepsByMetadata:c}}function ne({workflowConfig:t,workflowState:e,workflowContext:r}){let n=ft.useRef(Date.now()),i=ft.useRef(new Map),s=ft.useRef(false),o=ft.useRef(null),a=core.getGlobalMonitor();ft.useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),ft.useEffect(()=>{let S=t.steps[e.currentStepIndex];if(S&&o.current!==S.id){if(o.current&&t.analytics?.onStepComplete){let m=i.current.get(o.current);if(m){let d=Date.now()-m;t.analytics.onStepComplete(o.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:o.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}o.current=S.id,i.current.set(S.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(S.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:S.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let c=ft.useCallback((S,m)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(S,m,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:S,reason:m},void 0,"medium");},[t.analytics,r,a,t.id]),l=ft.useCallback(S=>{t.analytics?.onError&&t.analytics.onError(S,r),a&&a.trackError(S,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),p=ft.useCallback((S,m,d)=>{if(!a)return;let u={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:m,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:S,toStep:m,direction:m>S?"forward":"backward"},u,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=ft.useCallback((S,m)=>{if(!a)return;let d={timestamp:Date.now(),duration:S,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:S};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:m,currentStepIndex:e.currentStepIndex},d,S>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:c,trackError:l,trackNavigation:p,trackConditionEvaluation:f}}function Re(t,e){return {visible:t.visible,skippable:e===true||t.required}}function ie({workflowConfig:t,workflowState:e,currentStep:r}){let n=ft.useMemo(()=>({...e.allData,...e.stepData}),[e.allData,e.stepData]),i=ft.useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=Q(i,n,{visible:true,disabled:false,required:false,readonly:false}),o=ft.useMemo(()=>Re(s,r?.allowSkip),[s,r?.allowSkip]),a=ft.useMemo(()=>{let g={};return t.steps.forEach((h,P)=>{h.conditions&&(g[P]={visible:h.conditions.visible,required:h.conditions.skippable});}),g},[t.steps]),c=We(a,n),l=ft.useMemo(()=>{let g={};return t.steps.forEach((h,P)=>{let w=c[P];w?g[P]=Re(w,h.allowSkip):g[P]={visible:true,skippable:h.allowSkip===true};}),g},[t.steps,c]),p=ft.useMemo(()=>{if(!r?.formConfig?.allFields)return {};let g={};for(let h of r.formConfig.allFields)h.conditions&&(g[h.id]=h.conditions);return g},[r?.formConfig?.allFields]),f=Ie(p,n),S=ft.useCallback(g=>g<0||g>=t.steps.length?false:l[g]?.visible??true,[l,t.steps.length]),m=ft.useCallback(g=>g<0||g>=t.steps.length?false:l[g]?.skippable??false,[l,t.steps.length]),d=ft.useCallback(g=>f[g]?.visible??true,[f]),u=ft.useCallback(g=>f[g]?.disabled??false,[f]),k=ft.useCallback(g=>f[g]?.required??false,[f]),W=ft.useCallback(g=>f[g]?.readonly??false,[f]);return {stepConditions:o,fieldConditions:f,allStepConditions:l,isStepVisible:S,isStepSkippable:m,isFieldVisible:d,isFieldDisabled:u,isFieldRequired:k,isFieldReadonly:W}}function se({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:o,setStepData:a,onStepChange:c}){let l=ft.useRef(c);l.current=c;let p=t.steps[e.currentStepIndex],f=ft.useCallback(()=>({setStepData:(y,v)=>{a(v,y);},setStepFields:(y,v)=>{let I={...e.allData[y]||{},...v};a(I,y);},getStepData:y=>e.allData[y]||{},setNextStepField:(y,v)=>{let b=e.currentStepIndex+1;if(b<t.steps.length){let I=t.steps[b].id,G={...e.allData[I]||{},[y]:v};a(G,I);}},setNextStepFields:y=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let b=t.steps[v].id,T={...e.allData[b]||{},...y};a(T,b);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),S=ft.useCallback(async y=>{if(y<0||y>=t.steps.length||!n.isStepVisible(y))return false;s(true);try{return l.current&&l.current(e.currentStepIndex,y,r),i(y),o(y,t.steps[y].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,o]),m=ft.useCallback(y=>{for(let v=y+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=ft.useCallback(y=>{for(let v=y-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),u=ft.useCallback(async()=>{if(p?.onAfterValidation)try{let v=f();await p.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let y=m(e.currentStepIndex);return y===null?false:S(y)},[p,f,e.stepData,r,t.analytics,e.currentStepIndex,m,S]),k=ft.useCallback(async()=>{let y=d(e.currentStepIndex);return y===null?false:S(y)},[e.currentStepIndex,d,S]),W=ft.useCallback(async()=>!p?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(p.id,"user_skip",r),u()),[p,n,e.currentStepIndex,t.analytics,r,u]),g=ft.useCallback(y=>y<0||y>=t.steps.length?false:n.isStepVisible(y),[t.steps.length,n]),h=ft.useCallback(()=>{let y=m(e.currentStepIndex);return y!==null&&g(y)},[e.currentStepIndex,m,g]),P=ft.useCallback(()=>{let y=d(e.currentStepIndex);return y!==null&&g(y)},[e.currentStepIndex,d,g]),w=ft.useCallback(()=>p?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[p?.allowSkip,n,e.currentStepIndex]);return {goToStep:S,goNext:u,goPrevious:k,skipStep:W,canGoToStep:g,canGoNext:h,canGoPrevious:P,canSkipCurrentStep:w}}function rt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function oe({defaultValues:t={},persistence:e}){let r={currentStepIndex:0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[n,i]=ft.useReducer(rt,r),s=e?.adapter?z({workflowId:e.workflowId,workflowState:n,adapter:e.adapter,options:e.options,userId:e.userId}):null,o=ft.useCallback(u=>{i({type:"SET_CURRENT_STEP",stepIndex:u});},[]),a=ft.useCallback((u,k)=>{i({type:"SET_STEP_DATA",data:u,stepId:k});},[]),c=ft.useCallback((u,k,W)=>{i({type:"SET_FIELD_VALUE",fieldId:u,value:k,stepId:W});},[]),l=ft.useCallback(u=>{i({type:"SET_SUBMITTING",isSubmitting:u});},[]),p=ft.useCallback(u=>{i({type:"SET_TRANSITIONING",isTransitioning:u});},[]),f=ft.useCallback((u,k)=>{i({type:"MARK_STEP_VISITED",stepIndex:u,stepId:k});},[]),S=ft.useCallback(()=>{i({type:"RESET_WORKFLOW"});},[]),m=ft.useCallback(()=>{i({type:"SET_INITIALIZATION_COMPLETE"});},[]),d=ft.useCallback(async()=>{if(!s)return m(),false;try{let u=await s.loadPersistedData();if(u){let k={currentStepIndex:u.currentStepIndex,allData:u.allData,stepData:u.stepData,visitedSteps:new Set(u.visitedSteps)};return i({type:"LOAD_PERSISTED_STATE",state:k}),m(),!0}}catch(u){console.error("Failed to load persisted state:",u);}return m(),false},[s,m]);return {workflowState:n,setCurrentStep:o,setStepData:a,setFieldValue:c,setSubmitting:l,setTransitioning:p,markStepVisited:f,resetWorkflow:S,loadPersistedState:d,persistence:s?{isPersisting:s.isPersisting,persistenceError:s.persistenceError,persistNow:s.persistNow,clearPersistedData:s.clearPersistedData,hasPersistedData:s.hasPersistedData}:null}}function ae({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let o=ft.useRef(i);o.current=i;let a=ft.useCallback(async()=>{n(true);try{if(o.current&&await o.current(e.allData),t.analytics?.onWorkflowComplete){let l=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,l,e.allData);}}catch(l){throw console.error("Workflow submission failed:",l),t.analytics?.onError&&t.analytics.onError(l,r),l}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),c=ft.useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:c()}}var Le=ft.createContext(null);function pe({children:t,workflowConfig:e,defaultValues:r={},onStepChange:n,onWorkflowComplete:i,className:s}){let o=ft.useRef(n),a=ft.useRef(i);o.current=n,a.current=i;let{workflowState:c,setCurrentStep:l,setStepData:p,setFieldValue:f,setSubmitting:S,setTransitioning:m,markStepVisited:d,resetWorkflow:u,loadPersistedState:k,persistence:W}=oe({defaultValues:r,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});ft.useEffect(()=>{e.persistence&&k&&k();},[]);let g=ft.useMemo(()=>({isPersisting:W?.isPersisting??false,persistenceError:W?.persistenceError??null,persistNow:W?.persistNow}),[W?.isPersisting,W?.persistenceError,W?.persistNow]),h=ft.useMemo(()=>({workflowId:e.id,currentStepIndex:c.currentStepIndex,totalSteps:e.steps.length,allData:c.allData,stepData:c.stepData,isFirstStep:c.currentStepIndex===0,isLastStep:c.currentStepIndex===e.steps.length-1,visitedSteps:c.visitedSteps}),[e.id,e.steps.length,c.currentStepIndex,c.allData,c.stepData,c.visitedSteps]),P=ft.useMemo(()=>e.steps[c.currentStepIndex],[e.steps,c.currentStepIndex]),w=ft.useMemo(()=>P?.formConfig,[P?.formConfig]),{analyticsStartTime:y}=ne({workflowConfig:e,workflowState:c,workflowContext:h}),v=ie({workflowConfig:e,workflowState:c,currentStep:P}),{goToStep:b,goNext:I,goPrevious:T,skipStep:G,canGoToStep:ue,canGoNext:fe,canGoPrevious:me,canSkipCurrentStep:Se}=se({workflowConfig:e,workflowState:c,workflowContext:h,conditionsHelpers:v,setCurrentStep:l,setTransitioning:m,markStepVisited:d,setStepData:p,onStepChange:o.current});ft.useEffect(()=>{if(!v.isStepVisible(c.currentStepIndex)){for(let A=0;A<e.steps.length;A++)if(v.isStepVisible(A)){l(A),d(A,e.steps[A].id);break}}},[v,c.currentStepIndex,e.steps,l,d]);let{submitWorkflow:K,isSubmitting:ge,canSubmit:ye}=ae({workflowConfig:e,workflowState:c,workflowContext:h,setSubmitting:S,onWorkflowComplete:a.current,analyticsStartTime:y}),H=ft.useCallback((C,A)=>{f(C,A,P?.id||"");},[f,P?.id]),be=ft.useCallback(C=>{p(C,P?.id||"");},[p,P?.id]),Oe=ft.useCallback(async C=>{P?.id&&C&&p(C,P.id),h.isLastStep?await K():await I();},[h.isLastStep,K,I,P?.id,p]),ve=ft.useMemo(()=>({goToStep:b,goNext:I,goPrevious:T,skipStep:G,canGoToStep:ue,canGoNext:fe,canGoPrevious:me,canSkipCurrentStep:Se}),[b,I,T,G,ue,fe,me,Se]),he=ft.useMemo(()=>({setValue:H,setStepData:be,resetWorkflow:u}),[H,be,u]),ke=ft.useMemo(()=>({submitWorkflow:K,isSubmitting:ge,canSubmit:ye}),[K,ge,ye]),Ve=ft.useMemo(()=>({workflowState:c,workflowConfig:e,currentStep:P,context:h,formConfig:w,conditionsHelpers:v,currentStepMetadata:P?.metadata,...ve,...he,...ke,persistNow:g.persistNow,isPersisting:g.isPersisting,persistenceError:g.persistenceError}),[c,e,P,h,w,v,ve,he,ke,g]),Ue=ft.useMemo(()=>{if(!P?.id)return {};let C=c?.allData[P.id]||{};if(!w?.allFields)return C;let A=new Set(w.allFields.map($=>$.id)),xe={};for(let[$,Ke]of Object.entries(C))A.has($)&&(xe[$]=Ke);return xe},[c?.allData,P?.id,w?.allFields]),Ge=ft.useMemo(()=>c.isInitializing.toString(),[c.isInitializing]);return jsxRuntime.jsx(Le.Provider,{value:Ve,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:w,defaultValues:Ue,onFieldChange:H,"data-workflow-id":e.id,className:s,onSubmit:Oe,children:t},Ge)})}function E(){let t=ft.useContext(Le);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function ct({children:t,workflowConfig:e,...r}){let[n,i]=ft.useState(),s=ft.useMemo(()=>e instanceof V?e.build():e,[e]);return ft.useEffect(()=>{if(typeof window<"u"&&F.shouldDisplayWatermark()){let a=F.getWatermarkMessage();i(a);}},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(pe,{...r,workflowConfig:s,children:t}),n&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var mt=ft__default.default.memo(function({stepId:e,children:r}){let{currentStep:n}=E();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsxRuntime.jsx(forms.FormBody,{}):null});var ht=ft__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:o,currentStep:a}=E(),{submit:c,formState:l}=forms.useFormContext(),p=ft.useMemo(()=>{let m=l.isSubmitting||s.isSubmitting,d=r??m,u=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:u}},[l.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=ft.useCallback(async m=>{m?.preventDefault(),p.canGoNext&&await c(m);},[p.canGoNext,c]),S=ft.useMemo(()=>({isLastStep:i.isLastStep,canGoNext:p.canGoNext,isSubmitting:p.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:l.values||{},allData:i.allData,context:i}),[i.isLastStep,p.canGoNext,p.finalIsSubmitting,f,e,a,l.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:o.renderConfig?.nextButtonRenderer,props:S,...n})});var Dt=ft__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:o,workflowConfig:a,currentStep:c}=E(),{formState:l}=forms.useFormContext(),p=ft.useMemo(()=>{let m=l.isSubmitting||o.isSubmitting,d=r??m,u=i.currentStepIndex>0&&!o.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:u}},[l.isSubmitting,o.isSubmitting,o.isTransitioning,i.currentStepIndex,r]),f=ft.useCallback(async m=>{m?.preventDefault(),p.canGoPrevious&&await s();},[p.canGoPrevious,s]),S=ft.useMemo(()=>({canGoPrevious:p.canGoPrevious,isSubmitting:p.finalIsSubmitting,onPrevious:f,className:e,currentStep:c,stepData:l.values||{},allData:i.allData,context:i}),[p.canGoPrevious,p.finalIsSubmitting,f,e,c,l.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:S,...n})});var At=ft__default.default.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:o,workflowConfig:a,context:c,conditionsHelpers:l}=E(),{formState:p}=forms.useFormContext(),f=ft.useMemo(()=>{let d=p.isSubmitting||o.isSubmitting,u=r??d,k=(!!i?.allowSkip||l.isStepSkippable(o.currentStepIndex))&&!o.isTransitioning&&!u;return {finalIsSubmitting:u,canSkip:k}},[p.isSubmitting,o.isSubmitting,o.isTransitioning,o.currentStepIndex,i?.allowSkip,l.isStepSkippable,r]),S=ft.useCallback(async d=>{d?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),m=ft.useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:S,className:e,currentStep:i,stepData:p.values||{},allData:c.allData,context:c}),[f.canSkip,f.finalIsSubmitting,S,e,i,p.values,c.allData,c]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:m,...n})});var Ft=ft__default.default.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:o,conditionsHelpers:a}=E(),{visibleSteps:c,visibleToOriginalIndexMap:l,originalToVisibleIndexMap:p}=ft.useMemo(()=>{let d=[],u=new Map,k=new Map;return i.steps.forEach((W,g)=>{if(a.isStepVisible(g)){let h=d.length;d.push(W),u.set(h,g),k.set(g,h);}}),{visibleSteps:d,visibleToOriginalIndexMap:u,originalToVisibleIndexMap:k}},[i.steps,a]),f=ft.useCallback(d=>{let u=l.get(d);u!==void 0&&(e?e(u):o(u));},[l,e,o]),S=ft.useMemo(()=>p.get(s.currentStepIndex)??-1,[p,s.currentStepIndex]),m=ft.useMemo(()=>({steps:c,currentStepIndex:S,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[c,S,s.visitedSteps,f,r]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:m,...n})});var de=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),o=this.compress?this.compressData(s):s;localStorage.setItem(n,o);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},o=JSON.stringify(s),a=this.compress?this.compressData(o):o;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,o=JSON.parse(s);o.expiresAt&&Date.now()>o.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
|
|
2
|
-
exports.LocalStorageAdapter=
|
|
1
|
+
'use strict';var core=require('@rilaykit/core'),forms=require('@rilaykit/forms'),mt=require('react'),Pe=require('@noble/ed25519'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var mt__default=/*#__PURE__*/_interopDefault(mt);var Pe__namespace=/*#__PURE__*/_interopNamespace(Pe);var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new core.IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof forms.form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=core.normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=core.deepClone(this.steps),n.analytics=this.analytics?core.deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?core.deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{core.ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(o=>o.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var He=1751361139160,Ze="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,o]=n,a=`${i}.${s}`,c=new TextEncoder().encode(a),l=o.match(/.{2}/g);if(!l)return {valid:!1,error:"INVALID"};let p=new Uint8Array(l.map(W=>Number.parseInt(W,16))),m=k.hexToBytes(Ze);if(!await Pe__namespace.verify(p,c,m))return {valid:!1,error:"SIGNATURE_INVALID"};let S=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(S),u=Math.floor(Date.now()/1e3);return d.e<u?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:He>d.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let o=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),p=o<<18|a<<12|c<<6|l;n+=String.fromCharCode(p>>16&255),c!==64&&(n+=String.fromCharCode(p>>8&255)),l!==64&&(n+=String.fromCharCode(p&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var _=k;function j(t,e={},r={}){return mt.useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,core.evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function We(t,e={}){return mt.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=o=>{try{return o&&typeof o=="object"&&"build"in o?core.evaluateCondition(o.build(),e):core.evaluateCondition(o,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function De(t,e={}){return mt.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let o=a=>{try{return a&&typeof a=="object"&&"build"in a?core.evaluateCondition(a.build(),e):core.evaluateCondition(a,e)}catch(c){return console.warn(`Error evaluating condition for step ${s}:`,c),false}};r[s]={visible:i.visible?o(i.visible):true,disabled:i.disabled?o(i.disabled):false,required:i.required?o(i.required):false,readonly:i.readonly?o(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function ee(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Ee(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function Ye(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function te(t,e){return e?`${e}:${t}`:t}function re(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function Qe(t,e,r="persist"){let n=Ee(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function J({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,o]=mt.useState(false),[a,c]=mt.useState(null),[l,p]=mt.useState(false),m=mt.useRef(r),g=mt.useRef(n),S=mt.useRef({hasPendingChanges:false});mt.useEffect(()=>{m.current=r,g.current=n;},[r,n]);let d=te(g.current.storageKey||t,i),u=mt.useCallback(()=>{c(null);},[]),h=mt.useCallback((b,P)=>{let C=b instanceof D?b:new D(`${P} failed: ${b.message}`,"OPERATION_FAILED",b);c(C),console.error("[WorkflowPersistence]",C);},[]),W=mt.useCallback(async b=>{u(),o(true);try{let P=ee(t,b,g.current.metadata);await m.current.save(d,P),S.current.lastSavedState={...b},S.current.hasPendingChanges=!1;}catch(P){throw h(P,"Save"),P}finally{o(false);}},[t,d,u,h]),y=mt.useRef(re(async b=>{try{await W(b);}catch(P){console.debug("[WorkflowPersistence] Auto-save failed:",P);}},n.debounceMs||500)),x=mt.useCallback((b,P)=>P?b.currentStepIndex!==P.currentStepIndex||JSON.stringify(b.allData)!==JSON.stringify(P.allData)||JSON.stringify(b.stepData)!==JSON.stringify(P.stepData)||b.visitedSteps.size!==P.visitedSteps.size||!Array.from(b.visitedSteps).every(C=>P.visitedSteps.has(C)):true,[]),I=mt.useCallback(async()=>{u(),p(true);try{let b=await m.current.load(d);return b&&(S.current.lastSavedState={currentStepIndex:b.currentStepIndex,allData:b.allData,stepData:b.stepData,visitedSteps:new Set(b.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},S.current.hasPendingChanges=!1),b}catch(b){return h(b,"Load"),null}finally{setTimeout(()=>p(false),100);}},[d,u,h]),E=mt.useCallback(async()=>{u();try{await m.current.remove(d),S.current.lastSavedState=void 0,S.current.hasPendingChanges=!1;}catch(b){throw h(b,"Clear"),b}},[d,u,h]),f=mt.useCallback(async()=>{try{return await m.current.exists(d)}catch(b){return h(b,"Exists check"),false}},[d,h]);mt.useEffect(()=>{g.current.autoPersist&&(s||l||e.isInitializing||e.isSubmitting||e.isTransitioning||x(e,S.current.lastSavedState)&&(S.current.hasPendingChanges=true,y.current(e)));},[e,s,l,x]);let v=mt.useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:I,clearPersistedData:E,hasPersistedData:f}}function je(){let{workflowConfig:t,currentStep:e}=T(),r=mt.useMemo(()=>e?.metadata,[e?.metadata]),n=mt.useMemo(()=>l=>t.steps.find(m=>m.id===l)?.metadata,[t.steps]),i=mt.useMemo(()=>l=>t.steps[l]?.metadata,[t.steps]),s=mt.useMemo(()=>l=>r?l in r:false,[r]),o=mt.useMemo(()=>(l,p)=>r&&l in r?r[l]:p,[r]),a=mt.useMemo(()=>()=>t.steps.map((l,p)=>({id:l.id,title:l.title,index:p,metadata:l.metadata})),[t.steps]),c=mt.useMemo(()=>l=>t.steps.map((p,m)=>({step:p,index:m})).filter(({step:p,index:m})=>l(p.metadata,p.id,m)).map(({step:p})=>p.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:o,getAllStepsMetadata:a,findStepsByMetadata:c}}function ie({workflowConfig:t,workflowState:e,workflowContext:r}){let n=mt.useRef(Date.now()),i=mt.useRef(new Map),s=mt.useRef(false),o=mt.useRef(null),a=core.getGlobalMonitor();mt.useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),mt.useEffect(()=>{let g=t.steps[e.currentStepIndex];if(g&&o.current!==g.id){if(o.current&&t.analytics?.onStepComplete){let S=i.current.get(o.current);if(S){let d=Date.now()-S;t.analytics.onStepComplete(o.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:o.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}o.current=g.id,i.current.set(g.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(g.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:g.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let c=mt.useCallback((g,S)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(g,S,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:g,reason:S},void 0,"medium");},[t.analytics,r,a,t.id]),l=mt.useCallback(g=>{t.analytics?.onError&&t.analytics.onError(g,r),a&&a.trackError(g,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),p=mt.useCallback((g,S,d)=>{if(!a)return;let u={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:S,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:g,toStep:S,direction:S>g?"forward":"backward"},u,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),m=mt.useCallback((g,S)=>{if(!a)return;let d={timestamp:Date.now(),duration:g,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:g};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:S,currentStepIndex:e.currentStepIndex},d,g>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:c,trackError:l,trackNavigation:p,trackConditionEvaluation:m}}function Te(t,e){return {visible:t.visible,skippable:e===true||t.required}}function se({workflowConfig:t,workflowState:e,currentStep:r}){let n=mt.useMemo(()=>({...e.allData,...e.stepData}),[e.allData,e.stepData]),i=mt.useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=j(i,n,{visible:true,disabled:false,required:false,readonly:false}),o=mt.useMemo(()=>Te(s,r?.allowSkip),[s,r?.allowSkip]),a=mt.useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{x.conditions&&(y[I]={visible:x.conditions.visible,required:x.conditions.skippable});}),y},[t.steps]),c=De(a,n),l=mt.useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{let E=c[I];E?y[I]=Te(E,x.allowSkip):y[I]={visible:true,skippable:x.allowSkip===true};}),y},[t.steps,c]),p=mt.useMemo(()=>{if(!r?.formConfig?.allFields)return {};let y={};for(let x of r.formConfig.allFields)x.conditions&&(y[x.id]=x.conditions);return y},[r?.formConfig?.allFields]),m=We(p,n),g=mt.useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.visible??true,[l,t.steps.length]),S=mt.useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.skippable??false,[l,t.steps.length]),d=mt.useCallback(y=>m[y]?.visible??true,[m]),u=mt.useCallback(y=>m[y]?.disabled??false,[m]),h=mt.useCallback(y=>m[y]?.required??false,[m]),W=mt.useCallback(y=>m[y]?.readonly??false,[m]);return {stepConditions:o,fieldConditions:m,allStepConditions:l,isStepVisible:g,isStepSkippable:S,isFieldVisible:d,isFieldDisabled:u,isFieldRequired:h,isFieldReadonly:W}}function oe({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:o,setStepData:a,onStepChange:c}){let l=mt.useRef(c);l.current=c;let p=t.steps[e.currentStepIndex],m=mt.useCallback(()=>({setStepData:(f,v)=>{a(v,f);},setStepFields:(f,v)=>{let P={...e.allData[f]||{},...v};a(P,f);},getStepData:f=>e.allData[f]||{},setNextStepField:(f,v)=>{let b=e.currentStepIndex+1;if(b<t.steps.length){let P=t.steps[b].id,K={...e.allData[P]||{},[f]:v};a(K,P);}},setNextStepFields:f=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let b=t.steps[v].id,C={...e.allData[b]||{},...f};a(C,b);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),g=mt.useCallback(async f=>{if(f<0||f>=t.steps.length||!n.isStepVisible(f))return false;s(true);try{return l.current&&l.current(e.currentStepIndex,f,r),i(f),o(f,t.steps[f].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,o]),S=mt.useCallback(f=>{for(let v=f+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=mt.useCallback(f=>{for(let v=f-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),u=mt.useCallback(async()=>{if(p?.onAfterValidation)try{let v=m();await p.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let f=S(e.currentStepIndex);return f===null?false:g(f)},[p,m,e.stepData,r,t.analytics,e.currentStepIndex,S,g]),h=mt.useCallback(async()=>{let f=d(e.currentStepIndex);return f===null?false:g(f)},[e.currentStepIndex,d,g]),W=mt.useCallback(async()=>!p?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(p.id,"user_skip",r),u()),[p,n,e.currentStepIndex,t.analytics,r,u]),y=mt.useCallback(f=>f<0||f>=t.steps.length?false:n.isStepVisible(f),[t.steps.length,n]),x=mt.useCallback(()=>{let f=S(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,S,y]),I=mt.useCallback(()=>{let f=d(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,d,y]),E=mt.useCallback(()=>p?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[p?.allowSkip,n,e.currentStepIndex]);return {goToStep:g,goNext:u,goPrevious:h,skipStep:W,canGoToStep:y,canGoNext:x,canGoPrevious:I,canSkipCurrentStep:E}}function nt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function ae({defaultValues:t={},persistence:e}){let r={currentStepIndex:0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[n,i]=mt.useReducer(nt,r),s=e?.adapter?J({workflowId:e.workflowId,workflowState:n,adapter:e.adapter,options:e.options,userId:e.userId}):null,o=mt.useCallback(u=>{i({type:"SET_CURRENT_STEP",stepIndex:u});},[]),a=mt.useCallback((u,h)=>{i({type:"SET_STEP_DATA",data:u,stepId:h});},[]),c=mt.useCallback((u,h,W)=>{i({type:"SET_FIELD_VALUE",fieldId:u,value:h,stepId:W});},[]),l=mt.useCallback(u=>{i({type:"SET_SUBMITTING",isSubmitting:u});},[]),p=mt.useCallback(u=>{i({type:"SET_TRANSITIONING",isTransitioning:u});},[]),m=mt.useCallback((u,h)=>{i({type:"MARK_STEP_VISITED",stepIndex:u,stepId:h});},[]),g=mt.useCallback(()=>{i({type:"RESET_WORKFLOW"});},[]),S=mt.useCallback(()=>{i({type:"SET_INITIALIZATION_COMPLETE"});},[]),d=mt.useCallback(async()=>{if(!s)return S(),false;try{let u=await s.loadPersistedData();if(u){let h={currentStepIndex:u.currentStepIndex,allData:u.allData,stepData:u.stepData,visitedSteps:new Set(u.visitedSteps)};return i({type:"LOAD_PERSISTED_STATE",state:h}),S(),!0}}catch(u){console.error("Failed to load persisted state:",u);}return S(),false},[s,S]);return {workflowState:n,setCurrentStep:o,setStepData:a,setFieldValue:c,setSubmitting:l,setTransitioning:p,markStepVisited:m,resetWorkflow:g,loadPersistedState:d,persistence:s?{isPersisting:s.isPersisting,persistenceError:s.persistenceError,persistNow:s.persistNow,clearPersistedData:s.clearPersistedData,hasPersistedData:s.hasPersistedData}:null}}function le({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let o=mt.useRef(i);o.current=i;let a=mt.useCallback(async()=>{n(true);try{if(o.current&&await o.current(e.allData),t.analytics?.onWorkflowComplete){let l=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,l,e.allData);}}catch(l){throw console.error("Workflow submission failed:",l),t.analytics?.onError&&t.analytics.onError(l,r),l}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),c=mt.useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:c()}}var Me=mt.createContext(null);function ce({children:t,workflowConfig:e,defaultValues:r={},onStepChange:n,onWorkflowComplete:i,className:s}){let o=mt.useRef(n),a=mt.useRef(i);o.current=n,a.current=i;let{workflowState:c,setCurrentStep:l,setStepData:p,setFieldValue:m,setSubmitting:g,setTransitioning:S,markStepVisited:d,resetWorkflow:u,loadPersistedState:h,persistence:W}=ae({defaultValues:r,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});mt.useEffect(()=>{e.persistence&&h&&h();},[]);let y=mt.useMemo(()=>({isPersisting:W?.isPersisting??false,persistenceError:W?.persistenceError??null,persistNow:W?.persistNow}),[W?.isPersisting,W?.persistenceError,W?.persistNow]),x=mt.useMemo(()=>({workflowId:e.id,currentStepIndex:c.currentStepIndex,totalSteps:e.steps.length,allData:c.allData,stepData:c.stepData,visitedSteps:c.visitedSteps}),[e.id,e.steps.length,c.currentStepIndex,c.allData,c.stepData,c.visitedSteps]),I=mt.useMemo(()=>e.steps[c.currentStepIndex],[e.steps,c.currentStepIndex]),E=mt.useMemo(()=>I?.formConfig,[I?.formConfig]),f=se({workflowConfig:e,workflowState:c,currentStep:I}),v=mt.useMemo(()=>{let w=-1;for(let A=0;A<e.steps.length;A++)if(f.isStepVisible(A)){w=A;break}let R=-1;for(let A=e.steps.length-1;A>=0;A--)if(f.isStepVisible(A)){R=A;break}return {...x,isFirstStep:c.currentStepIndex===w,isLastStep:c.currentStepIndex===R}},[x,c.currentStepIndex,f,e.steps.length]),{analyticsStartTime:b}=ie({workflowConfig:e,workflowState:c,workflowContext:v}),{goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}=oe({workflowConfig:e,workflowState:c,workflowContext:v,conditionsHelpers:f,setCurrentStep:l,setTransitioning:S,markStepVisited:d,setStepData:p,onStepChange:o.current});mt.useEffect(()=>{if(!f.isStepVisible(c.currentStepIndex)){for(let R=0;R<e.steps.length;R++)if(f.isStepVisible(R)){l(R),d(R,e.steps[R].id);break}}},[f,c.currentStepIndex,e.steps,l,d]);let{submitWorkflow:$,isSubmitting:be,canSubmit:ve}=le({workflowConfig:e,workflowState:c,workflowContext:v,setSubmitting:g,onWorkflowComplete:a.current,analyticsStartTime:b}),Z=mt.useCallback((w,R)=>{m(w,R,I?.id||"");},[m,I?.id]),he=mt.useCallback(w=>{p(w,I?.id||"");},[p,I?.id]),Oe=mt.useCallback(async w=>{I?.id&&w&&p(w,I.id),v.isLastStep?await $():await C();},[v.isLastStep,$,C,I?.id,p]),xe=mt.useMemo(()=>({goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}),[P,C,K,fe,me,Se,ge,ye]),ke=mt.useMemo(()=>({setValue:Z,setStepData:he,resetWorkflow:u}),[Z,he,u]),Ie=mt.useMemo(()=>({submitWorkflow:$,isSubmitting:be,canSubmit:ve}),[$,be,ve]),Ue=mt.useMemo(()=>({workflowState:c,workflowConfig:e,currentStep:I,context:v,formConfig:E,conditionsHelpers:f,currentStepMetadata:I?.metadata,...xe,...ke,...Ie,persistNow:y.persistNow,isPersisting:y.isPersisting,persistenceError:y.persistenceError}),[c,e,I,v,E,f,xe,ke,Ie,y]),Ge=mt.useMemo(()=>{if(!I?.id)return {};let w=c?.allData[I.id]||{};if(!E?.allFields)return w;let R=new Set(E.allFields.map(q=>q.id)),A={};for(let[q,$e]of Object.entries(w))R.has(q)&&(A[q]=$e);return A},[c?.allData,I?.id,E?.allFields]),Ke=mt.useMemo(()=>c.isInitializing.toString(),[c.isInitializing]);return jsxRuntime.jsx(Me.Provider,{value:Ue,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:E,defaultValues:Ge,onFieldChange:Z,"data-workflow-id":e.id,className:s,onSubmit:Oe,children:t},Ke)})}function T(){let t=mt.useContext(Me);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function dt({children:t,workflowConfig:e,...r}){let[n,i]=mt.useState(),s=mt.useMemo(()=>e instanceof U?e.build():e,[e]);return mt.useEffect(()=>{if(typeof window<"u"&&_.shouldDisplayWatermark()){let a=_.getWatermarkMessage();i(a);}},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(ce,{...r,workflowConfig:s,children:t}),n&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var St=mt__default.default.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsxRuntime.jsx(forms.FormBody,{}):null});var xt=mt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:o,currentStep:a}=T(),{submit:c,formState:l}=forms.useFormContext(),p=mt.useMemo(()=>{let S=l.isSubmitting||s.isSubmitting,d=r??S,u=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:u}},[l.isSubmitting,s.isSubmitting,s.isTransitioning,r]),m=mt.useCallback(async S=>{S?.preventDefault(),p.canGoNext&&await c(S);},[p.canGoNext,c]),g=mt.useMemo(()=>({isLastStep:i.isLastStep,canGoNext:p.canGoNext,isSubmitting:p.finalIsSubmitting,onSubmit:m,className:e,currentStep:a,stepData:l.values||{},allData:i.allData,context:i}),[i.isLastStep,p.canGoNext,p.finalIsSubmitting,m,e,a,l.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:o.renderConfig?.nextButtonRenderer,props:g,...n})});var Et=mt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:o,workflowConfig:a,currentStep:c}=T(),{formState:l}=forms.useFormContext(),p=mt.useMemo(()=>{let S=l.isSubmitting||o.isSubmitting,d=r??S,u=i.currentStepIndex>0&&!o.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:u}},[l.isSubmitting,o.isSubmitting,o.isTransitioning,i.currentStepIndex,r]),m=mt.useCallback(async S=>{S?.preventDefault(),p.canGoPrevious&&await s();},[p.canGoPrevious,s]),g=mt.useMemo(()=>({canGoPrevious:p.canGoPrevious,isSubmitting:p.finalIsSubmitting,onPrevious:m,className:e,currentStep:c,stepData:l.values||{},allData:i.allData,context:i}),[p.canGoPrevious,p.finalIsSubmitting,m,e,c,l.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:g,...n})});var Nt=mt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:o,workflowConfig:a,context:c,conditionsHelpers:l}=T(),{formState:p}=forms.useFormContext(),m=mt.useMemo(()=>{let d=p.isSubmitting||o.isSubmitting,u=r??d,h=(!!i?.allowSkip||l.isStepSkippable(o.currentStepIndex))&&!o.isTransitioning&&!u;return {finalIsSubmitting:u,canSkip:h}},[p.isSubmitting,o.isSubmitting,o.isTransitioning,o.currentStepIndex,i?.allowSkip,l.isStepSkippable,r]),g=mt.useCallback(async d=>{d?.preventDefault(),m.canSkip&&await s();},[m.canSkip,s]),S=mt.useMemo(()=>({canSkip:m.canSkip,isSubmitting:m.finalIsSubmitting,onSkip:g,className:e,currentStep:i,stepData:p.values||{},allData:c.allData,context:c}),[m.canSkip,m.finalIsSubmitting,g,e,i,p.values,c.allData,c]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:S,...n})});var _t=mt__default.default.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:o,conditionsHelpers:a}=T(),{visibleSteps:c,visibleToOriginalIndexMap:l,originalToVisibleIndexMap:p}=mt.useMemo(()=>{let d=[],u=new Map,h=new Map;return i.steps.forEach((W,y)=>{if(a.isStepVisible(y)){let x=d.length;d.push(W),u.set(x,y),h.set(y,x);}}),{visibleSteps:d,visibleToOriginalIndexMap:u,originalToVisibleIndexMap:h}},[i.steps,a]),m=mt.useCallback(d=>{let u=l.get(d);u!==void 0&&(e?e(u):o(u));},[l,e,o]),g=mt.useMemo(()=>p.get(s.currentStepIndex)??-1,[p,s.currentStepIndex]),S=mt.useMemo(()=>({steps:c,currentStepIndex:g,visitedSteps:s.visitedSteps,onStepClick:m,className:r}),[c,g,s.visitedSteps,m,r]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:S,...n})});var ue=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),o=this.compress?this.compressData(s):s;localStorage.setItem(n,o);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},o=JSON.stringify(s),a=this.compress?this.compressData(o):o;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,o=JSON.parse(s);o.expiresAt&&Date.now()>o.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
|
|
2
|
+
exports.LocalStorageAdapter=ue;exports.RilayLicenseManager=_;exports.Workflow=dt;exports.WorkflowBody=St;exports.WorkflowNextButton=xt;exports.WorkflowPersistenceError=D;exports.WorkflowPreviousButton=Et;exports.WorkflowProvider=ce;exports.WorkflowSkipButton=Nt;exports.WorkflowStepper=_t;exports.debounce=re;exports.flow=U;exports.generateStorageKey=te;exports.mergePersistedState=Qe;exports.persistedToWorkflowState=Ee;exports.useConditionEvaluation=j;exports.usePersistence=J;exports.useStepMetadata=je;exports.useWorkflowAnalytics=ie;exports.useWorkflowConditions=se;exports.useWorkflowContext=T;exports.useWorkflowNavigation=oe;exports.useWorkflowState=ae;exports.useWorkflowSubmission=le;exports.validatePersistedData=Ye;exports.workflowStateToPersisted=ee;
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {ComponentRendererWrapper,IdGenerator,normalizeToArray,deepClone,ensureUnique,getGlobalMonitor,evaluateCondition}from'@rilaykit/core';import {FormBody,useFormContext,form,FormProvider}from'@rilaykit/forms';import ft,{createContext,useMemo,useCallback,useContext,useState,useRef,useEffect,useReducer}from'react';import*as Pe from'@noble/ed25519';import {jsx,jsxs}from'react/jsx-runtime';var V=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=deepClone(this.steps),n.analytics=this.analytics?deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(o=>o.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var Xe=1751361139160,He="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",x=class x{static async setLicenseKey(e){x.licenseKey=e||"",x.licenseKey?x.licenseResult=await x.validateLicense():x.licenseResult={valid:false,error:"MISSING"},x.isInitialized=true;}static async validateLicense(){if(!x.licenseKey)return {valid:false,error:"MISSING"};try{if(!x.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=x.licenseKey.slice(4),n=x.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,o]=n,a=`${i}.${s}`,c=new TextEncoder().encode(a),l=o.match(/.{2}/g);if(!l)return {valid:!1,error:"INVALID"};let p=new Uint8Array(l.map(W=>Number.parseInt(W,16))),f=x.hexToBytes(He);if(!await Pe.verify(p,c,f))return {valid:!1,error:"SIGNATURE_INVALID"};let m=x.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(m),u=Math.floor(Date.now()/1e3);return d.e<u?{valid:!1,error:"EXPIRED",data:x.decompressPayload(d)}:Xe>d.e*1e3?{valid:!1,error:"EXPIRED",data:x.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:x.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let o=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),p=o<<18|a<<12|c<<6|l;n+=String.fromCharCode(p>>16&255),c!==64&&(n+=String.fromCharCode(p>>8&255)),l!==64&&(n+=String.fromCharCode(p&255));}return n}static getLicenseResult(){return x.isInitialized?x.licenseResult?x.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!x.getLicenseResult().valid}static getWatermarkMessage(){let e=x.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=x.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=x.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};x.licenseKey="",x.licenseResult=null,x.isInitialized=false;var F=x;function Q(t,e={},r={}){return useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function Ie(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=o=>{try{return o&&typeof o=="object"&&"build"in o?evaluateCondition(o.build(),e):evaluateCondition(o,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function We(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let o=a=>{try{return a&&typeof a=="object"&&"build"in a?evaluateCondition(a.build(),e):evaluateCondition(a,e)}catch(c){return console.warn(`Error evaluating condition for step ${s}:`,c),false}};r[s]={visible:i.visible?o(i.visible):true,disabled:i.disabled?o(i.disabled):false,required:i.required?o(i.required):false,readonly:i.readonly?o(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function j(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function De(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function Ze(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function ee(t,e){return e?`${e}:${t}`:t}function te(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function Ye(t,e,r="persist"){let n=De(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function z({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,o]=useState(false),[a,c]=useState(null),[l,p]=useState(false),f=useRef(r),S=useRef(n),m=useRef({hasPendingChanges:false});useEffect(()=>{f.current=r,S.current=n;},[r,n]);let d=ee(S.current.storageKey||t,i),u=useCallback(()=>{c(null);},[]),k=useCallback((b,I)=>{let T=b instanceof D?b:new D(`${I} failed: ${b.message}`,"OPERATION_FAILED",b);c(T),console.error("[WorkflowPersistence]",T);},[]),W=useCallback(async b=>{u(),o(true);try{let I=j(t,b,S.current.metadata);await f.current.save(d,I),m.current.lastSavedState={...b},m.current.hasPendingChanges=!1;}catch(I){throw k(I,"Save"),I}finally{o(false);}},[t,d,u,k]),g=useRef(te(async b=>{try{await W(b);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),h=useCallback((b,I)=>I?b.currentStepIndex!==I.currentStepIndex||JSON.stringify(b.allData)!==JSON.stringify(I.allData)||JSON.stringify(b.stepData)!==JSON.stringify(I.stepData)||b.visitedSteps.size!==I.visitedSteps.size||!Array.from(b.visitedSteps).every(T=>I.visitedSteps.has(T)):true,[]),P=useCallback(async()=>{u(),p(true);try{let b=await f.current.load(d);return b&&(m.current.lastSavedState={currentStepIndex:b.currentStepIndex,allData:b.allData,stepData:b.stepData,visitedSteps:new Set(b.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},m.current.hasPendingChanges=!1),b}catch(b){return k(b,"Load"),null}finally{setTimeout(()=>p(false),100);}},[d,u,k]),w=useCallback(async()=>{u();try{await f.current.remove(d),m.current.lastSavedState=void 0,m.current.hasPendingChanges=!1;}catch(b){throw k(b,"Clear"),b}},[d,u,k]),y=useCallback(async()=>{try{return await f.current.exists(d)}catch(b){return k(b,"Exists check"),false}},[d,k]);useEffect(()=>{S.current.autoPersist&&(s||l||e.isInitializing||e.isSubmitting||e.isTransitioning||h(e,m.current.lastSavedState)&&(m.current.hasPendingChanges=true,g.current(e)));},[e,s,l,h]);let v=useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:P,clearPersistedData:w,hasPersistedData:y}}function Qe(){let{workflowConfig:t,currentStep:e}=E(),r=useMemo(()=>e?.metadata,[e?.metadata]),n=useMemo(()=>l=>t.steps.find(f=>f.id===l)?.metadata,[t.steps]),i=useMemo(()=>l=>t.steps[l]?.metadata,[t.steps]),s=useMemo(()=>l=>r?l in r:false,[r]),o=useMemo(()=>(l,p)=>r&&l in r?r[l]:p,[r]),a=useMemo(()=>()=>t.steps.map((l,p)=>({id:l.id,title:l.title,index:p,metadata:l.metadata})),[t.steps]),c=useMemo(()=>l=>t.steps.map((p,f)=>({step:p,index:f})).filter(({step:p,index:f})=>l(p.metadata,p.id,f)).map(({step:p})=>p.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:o,getAllStepsMetadata:a,findStepsByMetadata:c}}function ne({workflowConfig:t,workflowState:e,workflowContext:r}){let n=useRef(Date.now()),i=useRef(new Map),s=useRef(false),o=useRef(null),a=getGlobalMonitor();useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),useEffect(()=>{let S=t.steps[e.currentStepIndex];if(S&&o.current!==S.id){if(o.current&&t.analytics?.onStepComplete){let m=i.current.get(o.current);if(m){let d=Date.now()-m;t.analytics.onStepComplete(o.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:o.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}o.current=S.id,i.current.set(S.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(S.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:S.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let c=useCallback((S,m)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(S,m,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:S,reason:m},void 0,"medium");},[t.analytics,r,a,t.id]),l=useCallback(S=>{t.analytics?.onError&&t.analytics.onError(S,r),a&&a.trackError(S,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),p=useCallback((S,m,d)=>{if(!a)return;let u={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:m,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:S,toStep:m,direction:m>S?"forward":"backward"},u,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=useCallback((S,m)=>{if(!a)return;let d={timestamp:Date.now(),duration:S,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:S};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:m,currentStepIndex:e.currentStepIndex},d,S>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:c,trackError:l,trackNavigation:p,trackConditionEvaluation:f}}function Re(t,e){return {visible:t.visible,skippable:e===true||t.required}}function ie({workflowConfig:t,workflowState:e,currentStep:r}){let n=useMemo(()=>({...e.allData,...e.stepData}),[e.allData,e.stepData]),i=useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=Q(i,n,{visible:true,disabled:false,required:false,readonly:false}),o=useMemo(()=>Re(s,r?.allowSkip),[s,r?.allowSkip]),a=useMemo(()=>{let g={};return t.steps.forEach((h,P)=>{h.conditions&&(g[P]={visible:h.conditions.visible,required:h.conditions.skippable});}),g},[t.steps]),c=We(a,n),l=useMemo(()=>{let g={};return t.steps.forEach((h,P)=>{let w=c[P];w?g[P]=Re(w,h.allowSkip):g[P]={visible:true,skippable:h.allowSkip===true};}),g},[t.steps,c]),p=useMemo(()=>{if(!r?.formConfig?.allFields)return {};let g={};for(let h of r.formConfig.allFields)h.conditions&&(g[h.id]=h.conditions);return g},[r?.formConfig?.allFields]),f=Ie(p,n),S=useCallback(g=>g<0||g>=t.steps.length?false:l[g]?.visible??true,[l,t.steps.length]),m=useCallback(g=>g<0||g>=t.steps.length?false:l[g]?.skippable??false,[l,t.steps.length]),d=useCallback(g=>f[g]?.visible??true,[f]),u=useCallback(g=>f[g]?.disabled??false,[f]),k=useCallback(g=>f[g]?.required??false,[f]),W=useCallback(g=>f[g]?.readonly??false,[f]);return {stepConditions:o,fieldConditions:f,allStepConditions:l,isStepVisible:S,isStepSkippable:m,isFieldVisible:d,isFieldDisabled:u,isFieldRequired:k,isFieldReadonly:W}}function se({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:o,setStepData:a,onStepChange:c}){let l=useRef(c);l.current=c;let p=t.steps[e.currentStepIndex],f=useCallback(()=>({setStepData:(y,v)=>{a(v,y);},setStepFields:(y,v)=>{let I={...e.allData[y]||{},...v};a(I,y);},getStepData:y=>e.allData[y]||{},setNextStepField:(y,v)=>{let b=e.currentStepIndex+1;if(b<t.steps.length){let I=t.steps[b].id,G={...e.allData[I]||{},[y]:v};a(G,I);}},setNextStepFields:y=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let b=t.steps[v].id,T={...e.allData[b]||{},...y};a(T,b);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),S=useCallback(async y=>{if(y<0||y>=t.steps.length||!n.isStepVisible(y))return false;s(true);try{return l.current&&l.current(e.currentStepIndex,y,r),i(y),o(y,t.steps[y].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,o]),m=useCallback(y=>{for(let v=y+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=useCallback(y=>{for(let v=y-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),u=useCallback(async()=>{if(p?.onAfterValidation)try{let v=f();await p.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let y=m(e.currentStepIndex);return y===null?false:S(y)},[p,f,e.stepData,r,t.analytics,e.currentStepIndex,m,S]),k=useCallback(async()=>{let y=d(e.currentStepIndex);return y===null?false:S(y)},[e.currentStepIndex,d,S]),W=useCallback(async()=>!p?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(p.id,"user_skip",r),u()),[p,n,e.currentStepIndex,t.analytics,r,u]),g=useCallback(y=>y<0||y>=t.steps.length?false:n.isStepVisible(y),[t.steps.length,n]),h=useCallback(()=>{let y=m(e.currentStepIndex);return y!==null&&g(y)},[e.currentStepIndex,m,g]),P=useCallback(()=>{let y=d(e.currentStepIndex);return y!==null&&g(y)},[e.currentStepIndex,d,g]),w=useCallback(()=>p?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[p?.allowSkip,n,e.currentStepIndex]);return {goToStep:S,goNext:u,goPrevious:k,skipStep:W,canGoToStep:g,canGoNext:h,canGoPrevious:P,canSkipCurrentStep:w}}function rt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function oe({defaultValues:t={},persistence:e}){let r={currentStepIndex:0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[n,i]=useReducer(rt,r),s=e?.adapter?z({workflowId:e.workflowId,workflowState:n,adapter:e.adapter,options:e.options,userId:e.userId}):null,o=useCallback(u=>{i({type:"SET_CURRENT_STEP",stepIndex:u});},[]),a=useCallback((u,k)=>{i({type:"SET_STEP_DATA",data:u,stepId:k});},[]),c=useCallback((u,k,W)=>{i({type:"SET_FIELD_VALUE",fieldId:u,value:k,stepId:W});},[]),l=useCallback(u=>{i({type:"SET_SUBMITTING",isSubmitting:u});},[]),p=useCallback(u=>{i({type:"SET_TRANSITIONING",isTransitioning:u});},[]),f=useCallback((u,k)=>{i({type:"MARK_STEP_VISITED",stepIndex:u,stepId:k});},[]),S=useCallback(()=>{i({type:"RESET_WORKFLOW"});},[]),m=useCallback(()=>{i({type:"SET_INITIALIZATION_COMPLETE"});},[]),d=useCallback(async()=>{if(!s)return m(),false;try{let u=await s.loadPersistedData();if(u){let k={currentStepIndex:u.currentStepIndex,allData:u.allData,stepData:u.stepData,visitedSteps:new Set(u.visitedSteps)};return i({type:"LOAD_PERSISTED_STATE",state:k}),m(),!0}}catch(u){console.error("Failed to load persisted state:",u);}return m(),false},[s,m]);return {workflowState:n,setCurrentStep:o,setStepData:a,setFieldValue:c,setSubmitting:l,setTransitioning:p,markStepVisited:f,resetWorkflow:S,loadPersistedState:d,persistence:s?{isPersisting:s.isPersisting,persistenceError:s.persistenceError,persistNow:s.persistNow,clearPersistedData:s.clearPersistedData,hasPersistedData:s.hasPersistedData}:null}}function ae({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let o=useRef(i);o.current=i;let a=useCallback(async()=>{n(true);try{if(o.current&&await o.current(e.allData),t.analytics?.onWorkflowComplete){let l=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,l,e.allData);}}catch(l){throw console.error("Workflow submission failed:",l),t.analytics?.onError&&t.analytics.onError(l,r),l}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),c=useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:c()}}var Le=createContext(null);function pe({children:t,workflowConfig:e,defaultValues:r={},onStepChange:n,onWorkflowComplete:i,className:s}){let o=useRef(n),a=useRef(i);o.current=n,a.current=i;let{workflowState:c,setCurrentStep:l,setStepData:p,setFieldValue:f,setSubmitting:S,setTransitioning:m,markStepVisited:d,resetWorkflow:u,loadPersistedState:k,persistence:W}=oe({defaultValues:r,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});useEffect(()=>{e.persistence&&k&&k();},[]);let g=useMemo(()=>({isPersisting:W?.isPersisting??false,persistenceError:W?.persistenceError??null,persistNow:W?.persistNow}),[W?.isPersisting,W?.persistenceError,W?.persistNow]),h=useMemo(()=>({workflowId:e.id,currentStepIndex:c.currentStepIndex,totalSteps:e.steps.length,allData:c.allData,stepData:c.stepData,isFirstStep:c.currentStepIndex===0,isLastStep:c.currentStepIndex===e.steps.length-1,visitedSteps:c.visitedSteps}),[e.id,e.steps.length,c.currentStepIndex,c.allData,c.stepData,c.visitedSteps]),P=useMemo(()=>e.steps[c.currentStepIndex],[e.steps,c.currentStepIndex]),w=useMemo(()=>P?.formConfig,[P?.formConfig]),{analyticsStartTime:y}=ne({workflowConfig:e,workflowState:c,workflowContext:h}),v=ie({workflowConfig:e,workflowState:c,currentStep:P}),{goToStep:b,goNext:I,goPrevious:T,skipStep:G,canGoToStep:ue,canGoNext:fe,canGoPrevious:me,canSkipCurrentStep:Se}=se({workflowConfig:e,workflowState:c,workflowContext:h,conditionsHelpers:v,setCurrentStep:l,setTransitioning:m,markStepVisited:d,setStepData:p,onStepChange:o.current});useEffect(()=>{if(!v.isStepVisible(c.currentStepIndex)){for(let A=0;A<e.steps.length;A++)if(v.isStepVisible(A)){l(A),d(A,e.steps[A].id);break}}},[v,c.currentStepIndex,e.steps,l,d]);let{submitWorkflow:K,isSubmitting:ge,canSubmit:ye}=ae({workflowConfig:e,workflowState:c,workflowContext:h,setSubmitting:S,onWorkflowComplete:a.current,analyticsStartTime:y}),H=useCallback((C,A)=>{f(C,A,P?.id||"");},[f,P?.id]),be=useCallback(C=>{p(C,P?.id||"");},[p,P?.id]),Oe=useCallback(async C=>{P?.id&&C&&p(C,P.id),h.isLastStep?await K():await I();},[h.isLastStep,K,I,P?.id,p]),ve=useMemo(()=>({goToStep:b,goNext:I,goPrevious:T,skipStep:G,canGoToStep:ue,canGoNext:fe,canGoPrevious:me,canSkipCurrentStep:Se}),[b,I,T,G,ue,fe,me,Se]),he=useMemo(()=>({setValue:H,setStepData:be,resetWorkflow:u}),[H,be,u]),ke=useMemo(()=>({submitWorkflow:K,isSubmitting:ge,canSubmit:ye}),[K,ge,ye]),Ve=useMemo(()=>({workflowState:c,workflowConfig:e,currentStep:P,context:h,formConfig:w,conditionsHelpers:v,currentStepMetadata:P?.metadata,...ve,...he,...ke,persistNow:g.persistNow,isPersisting:g.isPersisting,persistenceError:g.persistenceError}),[c,e,P,h,w,v,ve,he,ke,g]),Ue=useMemo(()=>{if(!P?.id)return {};let C=c?.allData[P.id]||{};if(!w?.allFields)return C;let A=new Set(w.allFields.map($=>$.id)),xe={};for(let[$,Ke]of Object.entries(C))A.has($)&&(xe[$]=Ke);return xe},[c?.allData,P?.id,w?.allFields]),Ge=useMemo(()=>c.isInitializing.toString(),[c.isInitializing]);return jsx(Le.Provider,{value:Ve,children:jsx(FormProvider,{formConfig:w,defaultValues:Ue,onFieldChange:H,"data-workflow-id":e.id,className:s,onSubmit:Oe,children:t},Ge)})}function E(){let t=useContext(Le);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function ct({children:t,workflowConfig:e,...r}){let[n,i]=useState(),s=useMemo(()=>e instanceof V?e.build():e,[e]);return useEffect(()=>{if(typeof window<"u"&&F.shouldDisplayWatermark()){let a=F.getWatermarkMessage();i(a);}},[]),jsxs("div",{style:{position:"relative"},children:[jsx(pe,{...r,workflowConfig:s,children:t}),n&&jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var mt=ft.memo(function({stepId:e,children:r}){let{currentStep:n}=E();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsx(FormBody,{}):null});var ht=ft.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:o,currentStep:a}=E(),{submit:c,formState:l}=useFormContext(),p=useMemo(()=>{let m=l.isSubmitting||s.isSubmitting,d=r??m,u=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:u}},[l.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=useCallback(async m=>{m?.preventDefault(),p.canGoNext&&await c(m);},[p.canGoNext,c]),S=useMemo(()=>({isLastStep:i.isLastStep,canGoNext:p.canGoNext,isSubmitting:p.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:l.values||{},allData:i.allData,context:i}),[i.isLastStep,p.canGoNext,p.finalIsSubmitting,f,e,a,l.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:o.renderConfig?.nextButtonRenderer,props:S,...n})});var Dt=ft.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:o,workflowConfig:a,currentStep:c}=E(),{formState:l}=useFormContext(),p=useMemo(()=>{let m=l.isSubmitting||o.isSubmitting,d=r??m,u=i.currentStepIndex>0&&!o.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:u}},[l.isSubmitting,o.isSubmitting,o.isTransitioning,i.currentStepIndex,r]),f=useCallback(async m=>{m?.preventDefault(),p.canGoPrevious&&await s();},[p.canGoPrevious,s]),S=useMemo(()=>({canGoPrevious:p.canGoPrevious,isSubmitting:p.finalIsSubmitting,onPrevious:f,className:e,currentStep:c,stepData:l.values||{},allData:i.allData,context:i}),[p.canGoPrevious,p.finalIsSubmitting,f,e,c,l.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:S,...n})});var At=ft.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:o,workflowConfig:a,context:c,conditionsHelpers:l}=E(),{formState:p}=useFormContext(),f=useMemo(()=>{let d=p.isSubmitting||o.isSubmitting,u=r??d,k=(!!i?.allowSkip||l.isStepSkippable(o.currentStepIndex))&&!o.isTransitioning&&!u;return {finalIsSubmitting:u,canSkip:k}},[p.isSubmitting,o.isSubmitting,o.isTransitioning,o.currentStepIndex,i?.allowSkip,l.isStepSkippable,r]),S=useCallback(async d=>{d?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),m=useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:S,className:e,currentStep:i,stepData:p.values||{},allData:c.allData,context:c}),[f.canSkip,f.finalIsSubmitting,S,e,i,p.values,c.allData,c]);return jsx(ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:m,...n})});var Ft=ft.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:o,conditionsHelpers:a}=E(),{visibleSteps:c,visibleToOriginalIndexMap:l,originalToVisibleIndexMap:p}=useMemo(()=>{let d=[],u=new Map,k=new Map;return i.steps.forEach((W,g)=>{if(a.isStepVisible(g)){let h=d.length;d.push(W),u.set(h,g),k.set(g,h);}}),{visibleSteps:d,visibleToOriginalIndexMap:u,originalToVisibleIndexMap:k}},[i.steps,a]),f=useCallback(d=>{let u=l.get(d);u!==void 0&&(e?e(u):o(u));},[l,e,o]),S=useMemo(()=>p.get(s.currentStepIndex)??-1,[p,s.currentStepIndex]),m=useMemo(()=>({steps:c,currentStepIndex:S,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[c,S,s.visitedSteps,f,r]);return jsx(ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:m,...n})});var de=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),o=this.compress?this.compressData(s):s;localStorage.setItem(n,o);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},o=JSON.stringify(s),a=this.compress?this.compressData(o):o;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,o=JSON.parse(s);o.expiresAt&&Date.now()>o.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
|
|
2
|
-
export{
|
|
1
|
+
import {ComponentRendererWrapper,IdGenerator,normalizeToArray,deepClone,ensureUnique,getGlobalMonitor,evaluateCondition}from'@rilaykit/core';import {FormBody,useFormContext,form,FormProvider}from'@rilaykit/forms';import mt,{createContext,useMemo,useCallback,useContext,useState,useRef,useEffect,useReducer}from'react';import*as Pe from'@noble/ed25519';import {jsx,jsxs}from'react/jsx-runtime';var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=deepClone(this.steps),n.analytics=this.analytics?deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(o=>o.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var He=1751361139160,Ze="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,o]=n,a=`${i}.${s}`,c=new TextEncoder().encode(a),l=o.match(/.{2}/g);if(!l)return {valid:!1,error:"INVALID"};let p=new Uint8Array(l.map(W=>Number.parseInt(W,16))),m=k.hexToBytes(Ze);if(!await Pe.verify(p,c,m))return {valid:!1,error:"SIGNATURE_INVALID"};let S=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(S),u=Math.floor(Date.now()/1e3);return d.e<u?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:He>d.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let o=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),p=o<<18|a<<12|c<<6|l;n+=String.fromCharCode(p>>16&255),c!==64&&(n+=String.fromCharCode(p>>8&255)),l!==64&&(n+=String.fromCharCode(p&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var _=k;function j(t,e={},r={}){return useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function We(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=o=>{try{return o&&typeof o=="object"&&"build"in o?evaluateCondition(o.build(),e):evaluateCondition(o,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function De(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let o=a=>{try{return a&&typeof a=="object"&&"build"in a?evaluateCondition(a.build(),e):evaluateCondition(a,e)}catch(c){return console.warn(`Error evaluating condition for step ${s}:`,c),false}};r[s]={visible:i.visible?o(i.visible):true,disabled:i.disabled?o(i.disabled):false,required:i.required?o(i.required):false,readonly:i.readonly?o(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function ee(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Ee(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function Ye(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function te(t,e){return e?`${e}:${t}`:t}function re(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function Qe(t,e,r="persist"){let n=Ee(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function J({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,o]=useState(false),[a,c]=useState(null),[l,p]=useState(false),m=useRef(r),g=useRef(n),S=useRef({hasPendingChanges:false});useEffect(()=>{m.current=r,g.current=n;},[r,n]);let d=te(g.current.storageKey||t,i),u=useCallback(()=>{c(null);},[]),h=useCallback((b,P)=>{let C=b instanceof D?b:new D(`${P} failed: ${b.message}`,"OPERATION_FAILED",b);c(C),console.error("[WorkflowPersistence]",C);},[]),W=useCallback(async b=>{u(),o(true);try{let P=ee(t,b,g.current.metadata);await m.current.save(d,P),S.current.lastSavedState={...b},S.current.hasPendingChanges=!1;}catch(P){throw h(P,"Save"),P}finally{o(false);}},[t,d,u,h]),y=useRef(re(async b=>{try{await W(b);}catch(P){console.debug("[WorkflowPersistence] Auto-save failed:",P);}},n.debounceMs||500)),x=useCallback((b,P)=>P?b.currentStepIndex!==P.currentStepIndex||JSON.stringify(b.allData)!==JSON.stringify(P.allData)||JSON.stringify(b.stepData)!==JSON.stringify(P.stepData)||b.visitedSteps.size!==P.visitedSteps.size||!Array.from(b.visitedSteps).every(C=>P.visitedSteps.has(C)):true,[]),I=useCallback(async()=>{u(),p(true);try{let b=await m.current.load(d);return b&&(S.current.lastSavedState={currentStepIndex:b.currentStepIndex,allData:b.allData,stepData:b.stepData,visitedSteps:new Set(b.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},S.current.hasPendingChanges=!1),b}catch(b){return h(b,"Load"),null}finally{setTimeout(()=>p(false),100);}},[d,u,h]),E=useCallback(async()=>{u();try{await m.current.remove(d),S.current.lastSavedState=void 0,S.current.hasPendingChanges=!1;}catch(b){throw h(b,"Clear"),b}},[d,u,h]),f=useCallback(async()=>{try{return await m.current.exists(d)}catch(b){return h(b,"Exists check"),false}},[d,h]);useEffect(()=>{g.current.autoPersist&&(s||l||e.isInitializing||e.isSubmitting||e.isTransitioning||x(e,S.current.lastSavedState)&&(S.current.hasPendingChanges=true,y.current(e)));},[e,s,l,x]);let v=useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:I,clearPersistedData:E,hasPersistedData:f}}function je(){let{workflowConfig:t,currentStep:e}=T(),r=useMemo(()=>e?.metadata,[e?.metadata]),n=useMemo(()=>l=>t.steps.find(m=>m.id===l)?.metadata,[t.steps]),i=useMemo(()=>l=>t.steps[l]?.metadata,[t.steps]),s=useMemo(()=>l=>r?l in r:false,[r]),o=useMemo(()=>(l,p)=>r&&l in r?r[l]:p,[r]),a=useMemo(()=>()=>t.steps.map((l,p)=>({id:l.id,title:l.title,index:p,metadata:l.metadata})),[t.steps]),c=useMemo(()=>l=>t.steps.map((p,m)=>({step:p,index:m})).filter(({step:p,index:m})=>l(p.metadata,p.id,m)).map(({step:p})=>p.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:o,getAllStepsMetadata:a,findStepsByMetadata:c}}function ie({workflowConfig:t,workflowState:e,workflowContext:r}){let n=useRef(Date.now()),i=useRef(new Map),s=useRef(false),o=useRef(null),a=getGlobalMonitor();useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),useEffect(()=>{let g=t.steps[e.currentStepIndex];if(g&&o.current!==g.id){if(o.current&&t.analytics?.onStepComplete){let S=i.current.get(o.current);if(S){let d=Date.now()-S;t.analytics.onStepComplete(o.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:o.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}o.current=g.id,i.current.set(g.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(g.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:g.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let c=useCallback((g,S)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(g,S,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:g,reason:S},void 0,"medium");},[t.analytics,r,a,t.id]),l=useCallback(g=>{t.analytics?.onError&&t.analytics.onError(g,r),a&&a.trackError(g,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),p=useCallback((g,S,d)=>{if(!a)return;let u={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:S,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:g,toStep:S,direction:S>g?"forward":"backward"},u,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),m=useCallback((g,S)=>{if(!a)return;let d={timestamp:Date.now(),duration:g,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:g};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:S,currentStepIndex:e.currentStepIndex},d,g>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:c,trackError:l,trackNavigation:p,trackConditionEvaluation:m}}function Te(t,e){return {visible:t.visible,skippable:e===true||t.required}}function se({workflowConfig:t,workflowState:e,currentStep:r}){let n=useMemo(()=>({...e.allData,...e.stepData}),[e.allData,e.stepData]),i=useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=j(i,n,{visible:true,disabled:false,required:false,readonly:false}),o=useMemo(()=>Te(s,r?.allowSkip),[s,r?.allowSkip]),a=useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{x.conditions&&(y[I]={visible:x.conditions.visible,required:x.conditions.skippable});}),y},[t.steps]),c=De(a,n),l=useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{let E=c[I];E?y[I]=Te(E,x.allowSkip):y[I]={visible:true,skippable:x.allowSkip===true};}),y},[t.steps,c]),p=useMemo(()=>{if(!r?.formConfig?.allFields)return {};let y={};for(let x of r.formConfig.allFields)x.conditions&&(y[x.id]=x.conditions);return y},[r?.formConfig?.allFields]),m=We(p,n),g=useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.visible??true,[l,t.steps.length]),S=useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.skippable??false,[l,t.steps.length]),d=useCallback(y=>m[y]?.visible??true,[m]),u=useCallback(y=>m[y]?.disabled??false,[m]),h=useCallback(y=>m[y]?.required??false,[m]),W=useCallback(y=>m[y]?.readonly??false,[m]);return {stepConditions:o,fieldConditions:m,allStepConditions:l,isStepVisible:g,isStepSkippable:S,isFieldVisible:d,isFieldDisabled:u,isFieldRequired:h,isFieldReadonly:W}}function oe({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:o,setStepData:a,onStepChange:c}){let l=useRef(c);l.current=c;let p=t.steps[e.currentStepIndex],m=useCallback(()=>({setStepData:(f,v)=>{a(v,f);},setStepFields:(f,v)=>{let P={...e.allData[f]||{},...v};a(P,f);},getStepData:f=>e.allData[f]||{},setNextStepField:(f,v)=>{let b=e.currentStepIndex+1;if(b<t.steps.length){let P=t.steps[b].id,K={...e.allData[P]||{},[f]:v};a(K,P);}},setNextStepFields:f=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let b=t.steps[v].id,C={...e.allData[b]||{},...f};a(C,b);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),g=useCallback(async f=>{if(f<0||f>=t.steps.length||!n.isStepVisible(f))return false;s(true);try{return l.current&&l.current(e.currentStepIndex,f,r),i(f),o(f,t.steps[f].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,o]),S=useCallback(f=>{for(let v=f+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=useCallback(f=>{for(let v=f-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),u=useCallback(async()=>{if(p?.onAfterValidation)try{let v=m();await p.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let f=S(e.currentStepIndex);return f===null?false:g(f)},[p,m,e.stepData,r,t.analytics,e.currentStepIndex,S,g]),h=useCallback(async()=>{let f=d(e.currentStepIndex);return f===null?false:g(f)},[e.currentStepIndex,d,g]),W=useCallback(async()=>!p?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(p.id,"user_skip",r),u()),[p,n,e.currentStepIndex,t.analytics,r,u]),y=useCallback(f=>f<0||f>=t.steps.length?false:n.isStepVisible(f),[t.steps.length,n]),x=useCallback(()=>{let f=S(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,S,y]),I=useCallback(()=>{let f=d(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,d,y]),E=useCallback(()=>p?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[p?.allowSkip,n,e.currentStepIndex]);return {goToStep:g,goNext:u,goPrevious:h,skipStep:W,canGoToStep:y,canGoNext:x,canGoPrevious:I,canSkipCurrentStep:E}}function nt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function ae({defaultValues:t={},persistence:e}){let r={currentStepIndex:0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[n,i]=useReducer(nt,r),s=e?.adapter?J({workflowId:e.workflowId,workflowState:n,adapter:e.adapter,options:e.options,userId:e.userId}):null,o=useCallback(u=>{i({type:"SET_CURRENT_STEP",stepIndex:u});},[]),a=useCallback((u,h)=>{i({type:"SET_STEP_DATA",data:u,stepId:h});},[]),c=useCallback((u,h,W)=>{i({type:"SET_FIELD_VALUE",fieldId:u,value:h,stepId:W});},[]),l=useCallback(u=>{i({type:"SET_SUBMITTING",isSubmitting:u});},[]),p=useCallback(u=>{i({type:"SET_TRANSITIONING",isTransitioning:u});},[]),m=useCallback((u,h)=>{i({type:"MARK_STEP_VISITED",stepIndex:u,stepId:h});},[]),g=useCallback(()=>{i({type:"RESET_WORKFLOW"});},[]),S=useCallback(()=>{i({type:"SET_INITIALIZATION_COMPLETE"});},[]),d=useCallback(async()=>{if(!s)return S(),false;try{let u=await s.loadPersistedData();if(u){let h={currentStepIndex:u.currentStepIndex,allData:u.allData,stepData:u.stepData,visitedSteps:new Set(u.visitedSteps)};return i({type:"LOAD_PERSISTED_STATE",state:h}),S(),!0}}catch(u){console.error("Failed to load persisted state:",u);}return S(),false},[s,S]);return {workflowState:n,setCurrentStep:o,setStepData:a,setFieldValue:c,setSubmitting:l,setTransitioning:p,markStepVisited:m,resetWorkflow:g,loadPersistedState:d,persistence:s?{isPersisting:s.isPersisting,persistenceError:s.persistenceError,persistNow:s.persistNow,clearPersistedData:s.clearPersistedData,hasPersistedData:s.hasPersistedData}:null}}function le({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let o=useRef(i);o.current=i;let a=useCallback(async()=>{n(true);try{if(o.current&&await o.current(e.allData),t.analytics?.onWorkflowComplete){let l=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,l,e.allData);}}catch(l){throw console.error("Workflow submission failed:",l),t.analytics?.onError&&t.analytics.onError(l,r),l}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),c=useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:c()}}var Me=createContext(null);function ce({children:t,workflowConfig:e,defaultValues:r={},onStepChange:n,onWorkflowComplete:i,className:s}){let o=useRef(n),a=useRef(i);o.current=n,a.current=i;let{workflowState:c,setCurrentStep:l,setStepData:p,setFieldValue:m,setSubmitting:g,setTransitioning:S,markStepVisited:d,resetWorkflow:u,loadPersistedState:h,persistence:W}=ae({defaultValues:r,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});useEffect(()=>{e.persistence&&h&&h();},[]);let y=useMemo(()=>({isPersisting:W?.isPersisting??false,persistenceError:W?.persistenceError??null,persistNow:W?.persistNow}),[W?.isPersisting,W?.persistenceError,W?.persistNow]),x=useMemo(()=>({workflowId:e.id,currentStepIndex:c.currentStepIndex,totalSteps:e.steps.length,allData:c.allData,stepData:c.stepData,visitedSteps:c.visitedSteps}),[e.id,e.steps.length,c.currentStepIndex,c.allData,c.stepData,c.visitedSteps]),I=useMemo(()=>e.steps[c.currentStepIndex],[e.steps,c.currentStepIndex]),E=useMemo(()=>I?.formConfig,[I?.formConfig]),f=se({workflowConfig:e,workflowState:c,currentStep:I}),v=useMemo(()=>{let w=-1;for(let A=0;A<e.steps.length;A++)if(f.isStepVisible(A)){w=A;break}let R=-1;for(let A=e.steps.length-1;A>=0;A--)if(f.isStepVisible(A)){R=A;break}return {...x,isFirstStep:c.currentStepIndex===w,isLastStep:c.currentStepIndex===R}},[x,c.currentStepIndex,f,e.steps.length]),{analyticsStartTime:b}=ie({workflowConfig:e,workflowState:c,workflowContext:v}),{goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}=oe({workflowConfig:e,workflowState:c,workflowContext:v,conditionsHelpers:f,setCurrentStep:l,setTransitioning:S,markStepVisited:d,setStepData:p,onStepChange:o.current});useEffect(()=>{if(!f.isStepVisible(c.currentStepIndex)){for(let R=0;R<e.steps.length;R++)if(f.isStepVisible(R)){l(R),d(R,e.steps[R].id);break}}},[f,c.currentStepIndex,e.steps,l,d]);let{submitWorkflow:$,isSubmitting:be,canSubmit:ve}=le({workflowConfig:e,workflowState:c,workflowContext:v,setSubmitting:g,onWorkflowComplete:a.current,analyticsStartTime:b}),Z=useCallback((w,R)=>{m(w,R,I?.id||"");},[m,I?.id]),he=useCallback(w=>{p(w,I?.id||"");},[p,I?.id]),Oe=useCallback(async w=>{I?.id&&w&&p(w,I.id),v.isLastStep?await $():await C();},[v.isLastStep,$,C,I?.id,p]),xe=useMemo(()=>({goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}),[P,C,K,fe,me,Se,ge,ye]),ke=useMemo(()=>({setValue:Z,setStepData:he,resetWorkflow:u}),[Z,he,u]),Ie=useMemo(()=>({submitWorkflow:$,isSubmitting:be,canSubmit:ve}),[$,be,ve]),Ue=useMemo(()=>({workflowState:c,workflowConfig:e,currentStep:I,context:v,formConfig:E,conditionsHelpers:f,currentStepMetadata:I?.metadata,...xe,...ke,...Ie,persistNow:y.persistNow,isPersisting:y.isPersisting,persistenceError:y.persistenceError}),[c,e,I,v,E,f,xe,ke,Ie,y]),Ge=useMemo(()=>{if(!I?.id)return {};let w=c?.allData[I.id]||{};if(!E?.allFields)return w;let R=new Set(E.allFields.map(q=>q.id)),A={};for(let[q,$e]of Object.entries(w))R.has(q)&&(A[q]=$e);return A},[c?.allData,I?.id,E?.allFields]),Ke=useMemo(()=>c.isInitializing.toString(),[c.isInitializing]);return jsx(Me.Provider,{value:Ue,children:jsx(FormProvider,{formConfig:E,defaultValues:Ge,onFieldChange:Z,"data-workflow-id":e.id,className:s,onSubmit:Oe,children:t},Ke)})}function T(){let t=useContext(Me);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function dt({children:t,workflowConfig:e,...r}){let[n,i]=useState(),s=useMemo(()=>e instanceof U?e.build():e,[e]);return useEffect(()=>{if(typeof window<"u"&&_.shouldDisplayWatermark()){let a=_.getWatermarkMessage();i(a);}},[]),jsxs("div",{style:{position:"relative"},children:[jsx(ce,{...r,workflowConfig:s,children:t}),n&&jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var St=mt.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsx(FormBody,{}):null});var xt=mt.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:o,currentStep:a}=T(),{submit:c,formState:l}=useFormContext(),p=useMemo(()=>{let S=l.isSubmitting||s.isSubmitting,d=r??S,u=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:u}},[l.isSubmitting,s.isSubmitting,s.isTransitioning,r]),m=useCallback(async S=>{S?.preventDefault(),p.canGoNext&&await c(S);},[p.canGoNext,c]),g=useMemo(()=>({isLastStep:i.isLastStep,canGoNext:p.canGoNext,isSubmitting:p.finalIsSubmitting,onSubmit:m,className:e,currentStep:a,stepData:l.values||{},allData:i.allData,context:i}),[i.isLastStep,p.canGoNext,p.finalIsSubmitting,m,e,a,l.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:o.renderConfig?.nextButtonRenderer,props:g,...n})});var Et=mt.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:o,workflowConfig:a,currentStep:c}=T(),{formState:l}=useFormContext(),p=useMemo(()=>{let S=l.isSubmitting||o.isSubmitting,d=r??S,u=i.currentStepIndex>0&&!o.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:u}},[l.isSubmitting,o.isSubmitting,o.isTransitioning,i.currentStepIndex,r]),m=useCallback(async S=>{S?.preventDefault(),p.canGoPrevious&&await s();},[p.canGoPrevious,s]),g=useMemo(()=>({canGoPrevious:p.canGoPrevious,isSubmitting:p.finalIsSubmitting,onPrevious:m,className:e,currentStep:c,stepData:l.values||{},allData:i.allData,context:i}),[p.canGoPrevious,p.finalIsSubmitting,m,e,c,l.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:g,...n})});var Nt=mt.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:o,workflowConfig:a,context:c,conditionsHelpers:l}=T(),{formState:p}=useFormContext(),m=useMemo(()=>{let d=p.isSubmitting||o.isSubmitting,u=r??d,h=(!!i?.allowSkip||l.isStepSkippable(o.currentStepIndex))&&!o.isTransitioning&&!u;return {finalIsSubmitting:u,canSkip:h}},[p.isSubmitting,o.isSubmitting,o.isTransitioning,o.currentStepIndex,i?.allowSkip,l.isStepSkippable,r]),g=useCallback(async d=>{d?.preventDefault(),m.canSkip&&await s();},[m.canSkip,s]),S=useMemo(()=>({canSkip:m.canSkip,isSubmitting:m.finalIsSubmitting,onSkip:g,className:e,currentStep:i,stepData:p.values||{},allData:c.allData,context:c}),[m.canSkip,m.finalIsSubmitting,g,e,i,p.values,c.allData,c]);return jsx(ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:S,...n})});var _t=mt.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:o,conditionsHelpers:a}=T(),{visibleSteps:c,visibleToOriginalIndexMap:l,originalToVisibleIndexMap:p}=useMemo(()=>{let d=[],u=new Map,h=new Map;return i.steps.forEach((W,y)=>{if(a.isStepVisible(y)){let x=d.length;d.push(W),u.set(x,y),h.set(y,x);}}),{visibleSteps:d,visibleToOriginalIndexMap:u,originalToVisibleIndexMap:h}},[i.steps,a]),m=useCallback(d=>{let u=l.get(d);u!==void 0&&(e?e(u):o(u));},[l,e,o]),g=useMemo(()=>p.get(s.currentStepIndex)??-1,[p,s.currentStepIndex]),S=useMemo(()=>({steps:c,currentStepIndex:g,visitedSteps:s.visitedSteps,onStepClick:m,className:r}),[c,g,s.visitedSteps,m,r]);return jsx(ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:S,...n})});var ue=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),o=this.compress?this.compressData(s):s;localStorage.setItem(n,o);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},o=JSON.stringify(s),a=this.compress?this.compressData(o):o;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,o=JSON.parse(s);o.expiresAt&&Date.now()>o.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
|
|
2
|
+
export{ue as LocalStorageAdapter,_ as RilayLicenseManager,dt as Workflow,St as WorkflowBody,xt as WorkflowNextButton,D as WorkflowPersistenceError,Et as WorkflowPreviousButton,ce as WorkflowProvider,Nt as WorkflowSkipButton,_t as WorkflowStepper,re as debounce,U as flow,te as generateStorageKey,Qe as mergePersistedState,Ee as persistedToWorkflowState,j as useConditionEvaluation,J as usePersistence,je as useStepMetadata,ie as useWorkflowAnalytics,se as useWorkflowConditions,T as useWorkflowContext,oe as useWorkflowNavigation,ae as useWorkflowState,le as useWorkflowSubmission,Ye as validatePersistedData,ee as workflowStateToPersisted};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rilaykit/workflow",
|
|
3
|
-
"version": "9.0.
|
|
3
|
+
"version": "9.0.1",
|
|
4
4
|
"description": "Commercial workflow and multi-step form utilities for RilayKit - License required for all use",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"@noble/ed25519": "^1.7.1",
|
|
37
|
-
"@rilaykit/core": "9.0.
|
|
38
|
-
"@rilaykit/forms": "9.0.
|
|
37
|
+
"@rilaykit/core": "9.0.1",
|
|
38
|
+
"@rilaykit/forms": "9.0.1"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"react": ">=18.0.0",
|