@rilaykit/workflow 10.0.0 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +3 -3
package/dist/index.d.mts
CHANGED
|
@@ -15,6 +15,9 @@ interface WorkflowState {
|
|
|
15
15
|
interface UseWorkflowStateProps {
|
|
16
16
|
defaultValues?: Record<string, any>;
|
|
17
17
|
defaultStepIndex?: number;
|
|
18
|
+
workflowSteps?: Array<{
|
|
19
|
+
id: string;
|
|
20
|
+
}>;
|
|
18
21
|
persistence?: {
|
|
19
22
|
workflowId: string;
|
|
20
23
|
adapter?: WorkflowPersistenceAdapter;
|
|
@@ -23,7 +26,7 @@ interface UseWorkflowStateProps {
|
|
|
23
26
|
autoLoad?: boolean;
|
|
24
27
|
};
|
|
25
28
|
}
|
|
26
|
-
declare function useWorkflowState({ defaultValues, defaultStepIndex, persistence, }: UseWorkflowStateProps): {
|
|
29
|
+
declare function useWorkflowState({ defaultValues, defaultStepIndex, workflowSteps, persistence, }: UseWorkflowStateProps): {
|
|
27
30
|
workflowState: WorkflowState;
|
|
28
31
|
setCurrentStep: (stepIndex: number) => void;
|
|
29
32
|
setStepData: (data: Record<string, any>, stepId: string) => void;
|
package/dist/index.d.ts
CHANGED
|
@@ -15,6 +15,9 @@ interface WorkflowState {
|
|
|
15
15
|
interface UseWorkflowStateProps {
|
|
16
16
|
defaultValues?: Record<string, any>;
|
|
17
17
|
defaultStepIndex?: number;
|
|
18
|
+
workflowSteps?: Array<{
|
|
19
|
+
id: string;
|
|
20
|
+
}>;
|
|
18
21
|
persistence?: {
|
|
19
22
|
workflowId: string;
|
|
20
23
|
adapter?: WorkflowPersistenceAdapter;
|
|
@@ -23,7 +26,7 @@ interface UseWorkflowStateProps {
|
|
|
23
26
|
autoLoad?: boolean;
|
|
24
27
|
};
|
|
25
28
|
}
|
|
26
|
-
declare function useWorkflowState({ defaultValues, defaultStepIndex, persistence, }: UseWorkflowStateProps): {
|
|
29
|
+
declare function useWorkflowState({ defaultValues, defaultStepIndex, workflowSteps, persistence, }: UseWorkflowStateProps): {
|
|
27
30
|
workflowState: WorkflowState;
|
|
28
31
|
setCurrentStep: (stepIndex: number) => void;
|
|
29
32
|
setStepData: (data: Record<string, any>, stepId: string) => void;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var core=require('@rilaykit/core'),forms=require('@rilaykit/forms'),bt=require('react'),Ee=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 bt__default=/*#__PURE__*/_interopDefault(bt);var Ee__namespace=/*#__PURE__*/_interopNamespace(Ee);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(a=>a.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 Qe=1751361139160,et="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",I=class I{static async setLicenseKey(e){I.licenseKey=e||"",I.licenseKey?I.licenseResult=await I.validateLicense():I.licenseResult={valid:false,error:"MISSING"},I.isInitialized=true;}static async validateLicense(){if(!I.licenseKey)return {valid:false,error:"MISSING"};try{if(!I.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=I.licenseKey.slice(4),n=I.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,a]=n,l=`${i}.${s}`,b=new TextEncoder().encode(l),p=a.match(/.{2}/g);if(!p)return {valid:!1,error:"INVALID"};let o=new Uint8Array(p.map(P=>Number.parseInt(P,16))),f=I.hexToBytes(et);if(!await Ee__namespace.verify(o,b,f))return {valid:!1,error:"SIGNATURE_INVALID"};let m=I.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),c=JSON.parse(m),h=Math.floor(Date.now()/1e3);return c.e<h?{valid:!1,error:"EXPIRED",data:I.decompressPayload(c)}:Qe>c.e*1e3?{valid:!1,error:"EXPIRED",data:I.decompressPayload(c)}:c.p===void 0||!c.c||!c.i||!c.e||!c.t?{valid:!1,error:"INVALID"}:{valid:!0,data:I.decompressPayload(c)}}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 a=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),b=r.indexOf(s.charAt(i++)),p=r.indexOf(s.charAt(i++)),o=a<<18|l<<12|b<<6|p;n+=String.fromCharCode(o>>16&255),b!==64&&(n+=String.fromCharCode(o>>8&255)),p!==64&&(n+=String.fromCharCode(o&255));}return n}static getLicenseResult(){return I.isInitialized?I.licenseResult?I.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!I.getLicenseResult().valid}static getWatermarkMessage(){let e=I.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=I.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=I.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};I.licenseKey="",I.licenseResult=null,I.isInitialized=false;var _=I;function ee(t,e={},r={}){return bt.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 bt.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=a=>{try{return a&&typeof a=="object"&&"build"in a?core.evaluateCondition(a.build(),e):core.evaluateCondition(a,e)}catch(l){return console.warn(`Error evaluating condition for field ${n}:`,l),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 Te(t,e={}){return bt.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 a=l=>{try{return l&&typeof l=="object"&&"build"in l?core.evaluateCondition(l.build(),e):core.evaluateCondition(l,e)}catch(b){return console.warn(`Error evaluating condition for step ${s}:`,b),false}};r[s]={visible:i.visible?a(i.visible):true,disabled:i.disabled?a(i.disabled):false,required:i.required?a(i.required):false,readonly:i.readonly?a(i.readonly):false};}}return r},[t,e])}var W=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function te(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 Ce(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function tt(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 re(t,e){return e?`${e}:${t}`:t}function ne(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function rt(t,e,r="persist"){let n=Ce(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 X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,a]=bt.useState(false),[l,b]=bt.useState(null),[p,o]=bt.useState(false),f=bt.useRef(r),u=bt.useRef(n),m=bt.useRef({hasPendingChanges:false});bt.useEffect(()=>{f.current=r,u.current=n;},[r,n]);let c=re(u.current.storageKey||t,i),h=bt.useCallback(()=>{b(null);},[]),g=bt.useCallback((S,k)=>{let L=S instanceof W?S:new W(`${k} failed: ${S.message}`,"OPERATION_FAILED",S);b(L),console.error("[WorkflowPersistence]",L);},[]),P=bt.useCallback(async S=>{h(),a(true);try{let k=te(t,S,u.current.metadata);await f.current.save(c,k),m.current.lastSavedState={...S},m.current.hasPendingChanges=!1;}catch(k){throw g(k,"Save"),k}finally{a(false);}},[t,c,h,g]),y=bt.useRef(ne(async S=>{try{await P(S);}catch(k){console.debug("[WorkflowPersistence] Auto-save failed:",k);}},n.debounceMs||500)),x=bt.useCallback((S,k)=>k?S.currentStepIndex!==k.currentStepIndex||JSON.stringify(S.allData)!==JSON.stringify(k.allData)||JSON.stringify(S.stepData)!==JSON.stringify(k.stepData)||S.visitedSteps.size!==k.visitedSteps.size||!Array.from(S.visitedSteps).every(L=>k.visitedSteps.has(L)):true,[]),E=bt.useCallback(async()=>{h(),o(true);try{let S=await f.current.load(c);return S&&(m.current.lastSavedState={currentStepIndex:S.currentStepIndex,allData:S.allData,stepData:S.stepData,visitedSteps:new Set(S.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},m.current.hasPendingChanges=!1),S}catch(S){return g(S,"Load"),null}finally{setTimeout(()=>o(false),100);}},[c,h,g]),N=bt.useCallback(async()=>{h();try{await f.current.remove(c),m.current.lastSavedState=void 0,m.current.hasPendingChanges=!1;}catch(S){throw g(S,"Clear"),S}},[c,h,g]),d=bt.useCallback(async()=>{try{return await f.current.exists(c)}catch(S){return g(S,"Exists check"),false}},[c,g]);bt.useEffect(()=>{u.current.autoPersist&&(s||p||e.isInitializing||e.isSubmitting||e.isTransitioning||x(e,m.current.lastSavedState)&&(m.current.hasPendingChanges=true,y.current(e)));},[e,s,p,x]);let v=bt.useCallback(async()=>{await P(e);},[P,e]);return {isPersisting:s,persistenceError:l,persistNow:v,loadPersistedData:E,clearPersistedData:N,hasPersistedData:d}}function nt(){let{workflowConfig:t,currentStep:e}=w(),r=bt.useMemo(()=>e?.metadata,[e?.metadata]),n=bt.useMemo(()=>p=>t.steps.find(f=>f.id===p)?.metadata,[t.steps]),i=bt.useMemo(()=>p=>t.steps[p]?.metadata,[t.steps]),s=bt.useMemo(()=>p=>r?p in r:false,[r]),a=bt.useMemo(()=>(p,o)=>r&&p in r?r[p]:o,[r]),l=bt.useMemo(()=>()=>t.steps.map((p,o)=>({id:p.id,title:p.title,index:o,metadata:p.metadata})),[t.steps]),b=bt.useMemo(()=>p=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>p(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:a,getAllStepsMetadata:l,findStepsByMetadata:b}}function se({workflowConfig:t,workflowState:e,workflowContext:r}){let n=bt.useRef(Date.now()),i=bt.useRef(new Map),s=bt.useRef(false),a=bt.useRef(null),l=core.getGlobalMonitor();bt.useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),l&&l.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,l,t.steps.length]),bt.useEffect(()=>{let u=t.steps[e.currentStepIndex];if(u&&a.current!==u.id){if(a.current&&t.analytics?.onStepComplete){let m=i.current.get(a.current);if(m){let c=Date.now()-m;t.analytics.onStepComplete(a.current,c,e.stepData,r),l&&l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:a.current,duration:c},{timestamp:Date.now(),duration:c,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:c,conditionEvaluationDuration:0},"low");}}a.current=u.id,i.current.set(u.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(u.id,Date.now(),r),l&&l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:u.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,l,t.id]);let b=bt.useCallback((u,m)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(u,m,r),l&&l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:u,reason:m},void 0,"medium");},[t.analytics,r,l,t.id]),p=bt.useCallback(u=>{t.analytics?.onError&&t.analytics.onError(u,r),l&&l.trackError(u,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,l,t.id,e.currentStepIndex,t.steps]),o=bt.useCallback((u,m,c)=>{if(!l)return;let h={timestamp:Date.now(),duration:c,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:m,navigationDuration:c,conditionEvaluationDuration:0};l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:u,toStep:m,direction:m>u?"forward":"backward"},h,c>1e3?"medium":"low");},[l,t.id,t.steps.length]),f=bt.useCallback((u,m)=>{if(!l)return;let c={timestamp:Date.now(),duration:u,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:u};l.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:m,currentStepIndex:e.currentStepIndex},c,u>100?"medium":"low");},[l,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:b,trackError:p,trackNavigation:o,trackConditionEvaluation:f}}function oe(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,oe(i,s)):r[s]=i;}return r}function ae(t,e){let r={...t,...e},n=oe(r);return {...r,...n}}function Le(t,e){return {visible:t.visible,skippable:e===true||t.required}}function le({workflowConfig:t,workflowState:e,currentStep:r}){let n=bt.useMemo(()=>ae(e.allData,e.stepData),[e.allData,e.stepData]),i=bt.useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=ee(i,n,{visible:true,disabled:false,required:false,readonly:false}),a=bt.useMemo(()=>Le(s,r?.allowSkip),[s,r?.allowSkip]),l=bt.useMemo(()=>{let y={};return t.steps.forEach((x,E)=>{x.conditions&&(y[E]={visible:x.conditions.visible,required:x.conditions.skippable});}),y},[t.steps]),b=Te(l,n),p=bt.useMemo(()=>{let y={};return t.steps.forEach((x,E)=>{let N=b[E];N?y[E]=Le(N,x.allowSkip):y[E]={visible:true,skippable:x.allowSkip===true};}),y},[t.steps,b]),o=bt.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]),f=we(o,n),u=bt.useCallback(y=>y<0||y>=t.steps.length?false:p[y]?.visible??true,[p,t.steps.length]),m=bt.useCallback(y=>y<0||y>=t.steps.length?false:p[y]?.skippable??false,[p,t.steps.length]),c=bt.useCallback(y=>f[y]?.visible??true,[f]),h=bt.useCallback(y=>f[y]?.disabled??false,[f]),g=bt.useCallback(y=>f[y]?.required??false,[f]),P=bt.useCallback(y=>f[y]?.readonly??false,[f]);return {stepConditions:a,fieldConditions:f,allStepConditions:p,isStepVisible:u,isStepSkippable:m,isFieldVisible:c,isFieldDisabled:h,isFieldRequired:g,isFieldReadonly:P}}function pe({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:a,setStepData:l,onStepChange:b}){let p=bt.useRef(b);p.current=b;let o=t.steps[e.currentStepIndex],f=bt.useCallback(()=>({setStepData:(d,v)=>{l(v,d);},setStepFields:(d,v)=>{let k={...e.allData[d]||{},...v};l(k,d);},getStepData:d=>e.allData[d]||{},setNextStepField:(d,v)=>{let S=e.currentStepIndex+1;if(S<t.steps.length){let k=t.steps[S].id,K={...e.allData[k]||{},[d]:v};l(K,k);}},setNextStepFields:d=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let S=t.steps[v].id,L={...e.allData[S]||{},...d};l(L,S);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,l]),u=bt.useCallback(async d=>{if(d<0||d>=t.steps.length||!n.isStepVisible(d))return false;s(true);try{return p.current&&p.current(e.currentStepIndex,d,r),i(d),a(d,t.steps[d].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,a]),m=bt.useCallback(d=>{for(let v=d+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),c=bt.useCallback(d=>{for(let v=d-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),h=bt.useCallback(async()=>{if(o?.onAfterValidation)try{let v=f();await o.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let d=m(e.currentStepIndex);return d===null?false:u(d)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,m,u]),g=bt.useCallback(async()=>{let d=c(e.currentStepIndex);return d===null?false:u(d)},[e.currentStepIndex,c,u]),P=bt.useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),y=bt.useCallback(d=>d<0||d>=t.steps.length?false:n.isStepVisible(d),[t.steps.length,n]),x=bt.useCallback(()=>{let d=m(e.currentStepIndex);return d!==null&&y(d)},[e.currentStepIndex,m,y]),E=bt.useCallback(()=>{let d=c(e.currentStepIndex);return d!==null&&y(d)},[e.currentStepIndex,c,y]),N=bt.useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:u,goNext:h,goPrevious:g,skipStep:P,canGoToStep:y,canGoNext:x,canGoPrevious:E,canSkipCurrentStep:N}}function at(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 ce({defaultValues:t={},defaultStepIndex:e,persistence:r}){let n={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[i,s]=bt.useReducer(at,n),a=r?.adapter?X({workflowId:r.workflowId,workflowState:i,adapter:r.adapter,options:r.options,userId:r.userId}):null,l=bt.useCallback(g=>{s({type:"SET_CURRENT_STEP",stepIndex:g});},[]),b=bt.useCallback((g,P)=>{s({type:"SET_STEP_DATA",data:g,stepId:P});},[]),p=bt.useCallback((g,P,y)=>{s({type:"SET_FIELD_VALUE",fieldId:g,value:P,stepId:y});},[]),o=bt.useCallback(g=>{s({type:"SET_SUBMITTING",isSubmitting:g});},[]),f=bt.useCallback(g=>{s({type:"SET_TRANSITIONING",isTransitioning:g});},[]),u=bt.useCallback((g,P)=>{s({type:"MARK_STEP_VISITED",stepIndex:g,stepId:P});},[]),m=bt.useCallback(()=>{s({type:"RESET_WORKFLOW"});},[]),c=bt.useCallback(()=>{s({type:"SET_INITIALIZATION_COMPLETE"});},[]),h=bt.useCallback(async()=>{if(!a)return c(),false;try{let g=await a.loadPersistedData();if(g){let P={currentStepIndex:g.currentStepIndex,allData:g.allData,stepData:g.stepData,visitedSteps:new Set(g.visitedSteps)};return s({type:"LOAD_PERSISTED_STATE",state:P}),c(),!0}}catch(g){console.error("Failed to load persisted state:",g);}return c(),false},[a,c]);return {workflowState:i,setCurrentStep:l,setStepData:b,setFieldValue:p,setSubmitting:o,setTransitioning:f,markStepVisited:u,resetWorkflow:m,loadPersistedState:h,persistence:a?{isPersisting:a.isPersisting,persistenceError:a.persistenceError,persistNow:a.persistNow,clearPersistedData:a.clearPersistedData,hasPersistedData:a.hasPersistedData}:null}}function de({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let a=bt.useRef(i);a.current=i;let l=bt.useCallback(async()=>{n(true);try{if(a.current&&await a.current(e.allData),t.analytics?.onWorkflowComplete){let p=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,p,e.allData);}}catch(p){throw console.error("Workflow submission failed:",p),t.analytics?.onError&&t.analytics.onError(p,r),p}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),b=bt.useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:l,isSubmitting:e.isSubmitting,canSubmit:b()}}var Oe=bt.createContext(null);function fe({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:a}){let l=bt.useRef(i),b=bt.useRef(s);l.current=i,b.current=s;let p=bt.useMemo(()=>{if(!n)return 0;let D=e.steps.findIndex(R=>R.id===n);return D===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):D},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:u,setFieldValue:m,setSubmitting:c,setTransitioning:h,markStepVisited:g,resetWorkflow:P,loadPersistedState:y,persistence:x}=ce({defaultValues:r,defaultStepIndex:p,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});bt.useEffect(()=>{e.persistence&&y&&y();},[]);let E=bt.useMemo(()=>({isPersisting:x?.isPersisting??false,persistenceError:x?.persistenceError??null,persistNow:x?.persistNow}),[x?.isPersisting,x?.persistenceError,x?.persistNow]),N=bt.useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),d=bt.useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),v=bt.useMemo(()=>d?.formConfig,[d?.formConfig]),S=le({workflowConfig:e,workflowState:o,currentStep:d}),k=bt.useMemo(()=>{let D=-1;for(let T=0;T<e.steps.length;T++)if(S.isStepVisible(T)){D=T;break}let R=-1;for(let T=e.steps.length-1;T>=0;T--)if(S.isStepVisible(T)){R=T;break}return {...N,isFirstStep:o.currentStepIndex===D,isLastStep:o.currentStepIndex===R}},[N,o.currentStepIndex,S,e.steps.length]),{analyticsStartTime:L}=se({workflowConfig:e,workflowState:o,workflowContext:k}),{goToStep:K,goNext:$,goPrevious:ge,skipStep:ye,canGoToStep:be,canGoNext:ve,canGoPrevious:he,canSkipCurrentStep:xe}=pe({workflowConfig:e,workflowState:o,workflowContext:k,conditionsHelpers:S,setCurrentStep:f,setTransitioning:h,markStepVisited:g,setStepData:u,onStepChange:l.current});bt.useEffect(()=>{if(!S.isStepVisible(o.currentStepIndex)){for(let R=0;R<e.steps.length;R++)if(S.isStepVisible(R)){f(R),g(R,e.steps[R].id);break}}},[S,o.currentStepIndex,e.steps,f,g]);let{submitWorkflow:q,isSubmitting:ke,canSubmit:Ie}=de({workflowConfig:e,workflowState:o,workflowContext:k,setSubmitting:c,onWorkflowComplete:b.current,analyticsStartTime:L}),j=bt.useCallback((D,R)=>{m(D,R,d?.id||"");},[m,d?.id]),Pe=bt.useCallback(D=>{u(D,d?.id||"");},[u,d?.id]),$e=bt.useCallback(async D=>{d?.id&&D&&u(D,d.id),k.isLastStep?await q():await $();},[k.isLastStep,q,$,d?.id,u]),We=bt.useMemo(()=>({goToStep:K,goNext:$,goPrevious:ge,skipStep:ye,canGoToStep:be,canGoNext:ve,canGoPrevious:he,canSkipCurrentStep:xe}),[K,$,ge,ye,be,ve,he,xe]),De=bt.useMemo(()=>({setValue:j,setStepData:Pe,resetWorkflow:P}),[j,Pe,P]),Re=bt.useMemo(()=>({submitWorkflow:q,isSubmitting:ke,canSubmit:Ie}),[q,ke,Ie]),qe=bt.useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:d,context:k,formConfig:v,conditionsHelpers:S,currentStepMetadata:d?.metadata,...We,...De,...Re,persistNow:E.persistNow,isPersisting:E.isPersisting,persistenceError:E.persistenceError}),[o,e,d,k,v,S,We,De,Re,E]),ze=bt.useMemo(()=>{if(!d?.id)return {};let D=o?.allData[d.id]||{};if(!v?.allFields)return D;let R=new Set(v.allFields.map(z=>z.id)),T={};for(let[z,Xe]of Object.entries(D))R.has(z)&&(T[z]=Xe);return T},[o?.allData,d?.id,v?.allFields]),Je=bt.useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsxRuntime.jsx(Oe.Provider,{value:qe,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:v,defaultValues:ze,onFieldChange:j,"data-workflow-id":e.id,className:a,onSubmit:$e,children:t},Je)})}function w(){let t=bt.useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function St({children:t,workflowConfig:e,...r}){let[n,i]=bt.useState(),s=bt.useMemo(()=>e instanceof U?e.build():e,[e]);return bt.useEffect(()=>{if(typeof window<"u"&&_.shouldDisplayWatermark()){let l=_.getWatermarkMessage();i(l);}},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(fe,{...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 vt=bt__default.default.memo(function({stepId:e,children:r}){let{currentStep:n}=w();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 Wt=bt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:a,currentStep:l}=w(),{submit:b,formState:p}=forms.useFormContext(),o=bt.useMemo(()=>{let m=p.isSubmitting||s.isSubmitting,c=r??m,h=!s.isTransitioning&&!c;return {finalIsSubmitting:c,canGoNext:h}},[p.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=bt.useCallback(async m=>{m?.preventDefault(),o.canGoNext&&await b(m);},[o.canGoNext,b]),u=bt.useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:l,stepData:p.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,l,p.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:a.renderConfig?.nextButtonRenderer,props:u,...n})});var Ct=bt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:a,workflowConfig:l,currentStep:b}=w(),{formState:p}=forms.useFormContext(),o=bt.useMemo(()=>{let m=p.isSubmitting||a.isSubmitting,c=r??m,h=i.currentStepIndex>0&&!a.isTransitioning&&!c;return {finalIsSubmitting:c,canGoPrevious:h}},[p.isSubmitting,a.isSubmitting,a.isTransitioning,i.currentStepIndex,r]),f=bt.useCallback(async m=>{m?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),u=bt.useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:b,stepData:p.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,b,p.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:l.renderConfig?.previousButtonRenderer,props:u,...n})});var Bt=bt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:a,workflowConfig:l,context:b,conditionsHelpers:p}=w(),{formState:o}=forms.useFormContext(),f=bt.useMemo(()=>{let c=o.isSubmitting||a.isSubmitting,h=r??c,g=(!!i?.allowSkip||p.isStepSkippable(a.currentStepIndex))&&!a.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:g}},[o.isSubmitting,a.isSubmitting,a.isTransitioning,a.currentStepIndex,i?.allowSkip,p.isStepSkippable,r]),u=bt.useCallback(async c=>{c?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),m=bt.useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:u,className:e,currentStep:i,stepData:o.values||{},allData:b.allData,context:b}),[f.canSkip,f.finalIsSubmitting,u,e,i,o.values,b.allData,b]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:l.renderConfig?.skipButtonRenderer,props:m,...n})});var Gt=bt__default.default.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:a,conditionsHelpers:l}=w(),{visibleSteps:b,visibleToOriginalIndexMap:p,originalToVisibleIndexMap:o}=bt.useMemo(()=>{let c=[],h=new Map,g=new Map;return i.steps.forEach((P,y)=>{if(l.isStepVisible(y)){let x=c.length;c.push(P),h.set(x,y),g.set(y,x);}}),{visibleSteps:c,visibleToOriginalIndexMap:h,originalToVisibleIndexMap:g}},[i.steps,l]),f=bt.useCallback(c=>{let h=p.get(c);h!==void 0&&(e?e(h):a(h));},[p,e,a]),u=bt.useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),m=bt.useMemo(()=>({steps:b,currentStepIndex:u,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[b,u,s.visitedSteps,f,r]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:m,...n})});var Se=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),a=this.compress?this.compressData(s):s;localStorage.setItem(n,a);}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},a=JSON.stringify(s),l=this.compress?this.compressData(a):a;localStorage.setItem(i,l);}catch(i){throw new W("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new W(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new W("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 W(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new W("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 W(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new W("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 W(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new W("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 W(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new W("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,a=JSON.parse(s);a.expiresAt&&Date.now()>a.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'),ht=require('react'),Ce=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 ht__default=/*#__PURE__*/_interopDefault(ht);var Ce__namespace=/*#__PURE__*/_interopNamespace(Ce);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(l=>l.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 et=1751361139160,tt="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,l]=n,a=`${i}.${s}`,g=new TextEncoder().encode(a),c=l.match(/.{2}/g);if(!c)return {valid:!1,error:"INVALID"};let o=new Uint8Array(c.map(E=>Number.parseInt(E,16))),f=k.hexToBytes(tt);if(!await Ce__namespace.verify(o,g,f))return {valid:!1,error:"SIGNATURE_INVALID"};let y=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(y),h=Math.floor(Date.now()/1e3);return d.e<h?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:et>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 l=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),g=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),o=l<<18|a<<12|g<<6|c;n+=String.fromCharCode(o>>16&255),g!==64&&(n+=String.fromCharCode(o>>8&255)),c!==64&&(n+=String.fromCharCode(o&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 B=k;function te(t,e={},r={}){return ht.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 Ae(t,e={}){return ht.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=l=>{try{return l&&typeof l=="object"&&"build"in l?core.evaluateCondition(l.build(),e):core.evaluateCondition(l,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 Ne(t,e={}){return ht.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 l=a=>{try{return a&&typeof a=="object"&&"build"in a?core.evaluateCondition(a.build(),e):core.evaluateCondition(a,e)}catch(g){return console.warn(`Error evaluating condition for step ${s}:`,g),false}};r[s]={visible:i.visible?l(i.visible):true,disabled:i.disabled?l(i.disabled):false,required:i.required?l(i.required):false,readonly:i.readonly?l(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 re(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 Le(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function rt(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 ne(t,e){return e?`${e}:${t}`:t}function ie(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function nt(t,e,r="persist"){let n=Le(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 X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,l]=ht.useState(false),[a,g]=ht.useState(null),[c,o]=ht.useState(false),f=ht.useRef(r),m=ht.useRef(n),y=ht.useRef({hasPendingChanges:false});ht.useEffect(()=>{f.current=r,m.current=n;},[r,n]);let d=ne(m.current.storageKey||t,i),h=ht.useCallback(()=>{g(null);},[]),x=ht.useCallback((S,I)=>{let L=S instanceof D?S:new D(`${I} failed: ${S.message}`,"OPERATION_FAILED",S);g(L),console.error("[WorkflowPersistence]",L);},[]),E=ht.useCallback(async S=>{h(),l(true);try{let I=re(t,S,m.current.metadata);await f.current.save(d,I),y.current.lastSavedState={...S},y.current.hasPendingChanges=!1;}catch(I){throw x(I,"Save"),I}finally{l(false);}},[t,d,h,x]),p=ht.useRef(ie(async S=>{try{await E(S);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),b=ht.useCallback((S,I)=>I?S.currentStepIndex!==I.currentStepIndex||JSON.stringify(S.allData)!==JSON.stringify(I.allData)||JSON.stringify(S.stepData)!==JSON.stringify(I.stepData)||S.visitedSteps.size!==I.visitedSteps.size||!Array.from(S.visitedSteps).every(L=>I.visitedSteps.has(L)):true,[]),w=ht.useCallback(async()=>{h(),o(true);try{let S=await f.current.load(d);return S&&(y.current.lastSavedState={currentStepIndex:S.currentStepIndex,allData:S.allData,stepData:S.stepData,visitedSteps:new Set(S.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},y.current.hasPendingChanges=!1),S}catch(S){return x(S,"Load"),null}finally{setTimeout(()=>o(false),100);}},[d,h,x]),N=ht.useCallback(async()=>{h();try{await f.current.remove(d),y.current.lastSavedState=void 0,y.current.hasPendingChanges=!1;}catch(S){throw x(S,"Clear"),S}},[d,h,x]),u=ht.useCallback(async()=>{try{return await f.current.exists(d)}catch(S){return x(S,"Exists check"),false}},[d,x]);ht.useEffect(()=>{m.current.autoPersist&&(s||c||e.isInitializing||e.isSubmitting||e.isTransitioning||b(e,y.current.lastSavedState)&&(y.current.hasPendingChanges=true,p.current(e)));},[e,s,c,b]);let v=ht.useCallback(async()=>{await E(e);},[E,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:w,clearPersistedData:N,hasPersistedData:u}}function it(){let{workflowConfig:t,currentStep:e}=T(),r=ht.useMemo(()=>e?.metadata,[e?.metadata]),n=ht.useMemo(()=>c=>t.steps.find(f=>f.id===c)?.metadata,[t.steps]),i=ht.useMemo(()=>c=>t.steps[c]?.metadata,[t.steps]),s=ht.useMemo(()=>c=>r?c in r:false,[r]),l=ht.useMemo(()=>(c,o)=>r&&c in r?r[c]:o,[r]),a=ht.useMemo(()=>()=>t.steps.map((c,o)=>({id:c.id,title:c.title,index:o,metadata:c.metadata})),[t.steps]),g=ht.useMemo(()=>c=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>c(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:l,getAllStepsMetadata:a,findStepsByMetadata:g}}function oe({workflowConfig:t,workflowState:e,workflowContext:r}){let n=ht.useRef(Date.now()),i=ht.useRef(new Map),s=ht.useRef(false),l=ht.useRef(null),a=core.getGlobalMonitor();ht.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]),ht.useEffect(()=>{let m=t.steps[e.currentStepIndex];if(m&&l.current!==m.id){if(l.current&&t.analytics?.onStepComplete){let y=i.current.get(l.current);if(y){let d=Date.now()-y;t.analytics.onStepComplete(l.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:l.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}l.current=m.id,i.current.set(m.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(m.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:m.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 g=ht.useCallback((m,y)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(m,y,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:m,reason:y},void 0,"medium");},[t.analytics,r,a,t.id]),c=ht.useCallback(m=>{t.analytics?.onError&&t.analytics.onError(m,r),a&&a.trackError(m,`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]),o=ht.useCallback((m,y,d)=>{if(!a)return;let h={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:y,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:m,toStep:y,direction:y>m?"forward":"backward"},h,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=ht.useCallback((m,y)=>{if(!a)return;let d={timestamp:Date.now(),duration:m,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:m};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:y,currentStepIndex:e.currentStepIndex},d,m>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:g,trackError:c,trackNavigation:o,trackConditionEvaluation:f}}function ae(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,ae(i,s)):r[s]=i;}return r}function le(t,e){let r={...t,...e},n=ae(r);return {...r,...n}}function Ve(t,e){return {visible:t.visible,skippable:e===true||t.required}}function pe({workflowConfig:t,workflowState:e,currentStep:r}){let n=ht.useMemo(()=>le(e.allData,e.stepData),[e.allData,e.stepData]),i=ht.useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=te(i,n,{visible:true,disabled:false,required:false,readonly:false}),l=ht.useMemo(()=>Ve(s,r?.allowSkip),[s,r?.allowSkip]),a=ht.useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{b.conditions&&(p[w]={visible:b.conditions.visible,required:b.conditions.skippable});}),p},[t.steps]),g=Ne(a,n),c=ht.useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{let N=g[w];N?p[w]=Ve(N,b.allowSkip):p[w]={visible:true,skippable:b.allowSkip===true};}),p},[t.steps,g]),o=ht.useMemo(()=>{if(!r?.formConfig?.allFields)return {};let p={};for(let b of r.formConfig.allFields)b.conditions&&(p[b.id]=b.conditions);return p},[r?.formConfig?.allFields]),f=Ae(o,n),m=ht.useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.visible??true,[c,t.steps.length]),y=ht.useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.skippable??false,[c,t.steps.length]),d=ht.useCallback(p=>f[p]?.visible??true,[f]),h=ht.useCallback(p=>f[p]?.disabled??false,[f]),x=ht.useCallback(p=>f[p]?.required??false,[f]),E=ht.useCallback(p=>f[p]?.readonly??false,[f]);return {stepConditions:l,fieldConditions:f,allStepConditions:c,isStepVisible:m,isStepSkippable:y,isFieldVisible:d,isFieldDisabled:h,isFieldRequired:x,isFieldReadonly:E}}function ce({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:l,setStepData:a,onStepChange:g}){let c=ht.useRef(g);c.current=g;let o=t.steps[e.currentStepIndex],f=ht.useCallback(()=>({setStepData:(u,v)=>{a(v,u);},setStepFields:(u,v)=>{let I={...e.allData[u]||{},...v};a(I,u);},getStepData:u=>e.allData[u]||{},setNextStepField:(u,v)=>{let S=e.currentStepIndex+1;if(S<t.steps.length){let I=t.steps[S].id,K={...e.allData[I]||{},[u]:v};a(K,I);}},setNextStepFields:u=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let S=t.steps[v].id,L={...e.allData[S]||{},...u};a(L,S);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),m=ht.useCallback(async u=>{if(u<0||u>=t.steps.length||!n.isStepVisible(u))return false;s(true);try{return c.current&&c.current(e.currentStepIndex,u,r),i(u),l(u,t.steps[u].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,l]),y=ht.useCallback(u=>{for(let v=u+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=ht.useCallback(u=>{for(let v=u-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),h=ht.useCallback(async()=>{if(o?.onAfterValidation)try{let v=f();await o.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let u=y(e.currentStepIndex);return u===null?false:m(u)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,y,m]),x=ht.useCallback(async()=>{let u=d(e.currentStepIndex);return u===null?false:m(u)},[e.currentStepIndex,d,m]),E=ht.useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),p=ht.useCallback(u=>u<0||u>=t.steps.length?false:n.isStepVisible(u),[t.steps.length,n]),b=ht.useCallback(()=>{let u=y(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,y,p]),w=ht.useCallback(()=>{let u=d(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,d,p]),N=ht.useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:m,goNext:h,goPrevious:x,skipStep:E,canGoToStep:p,canGoNext:b,canGoPrevious:w,canSkipCurrentStep:N}}function pt(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 de({defaultValues:t={},defaultStepIndex:e,workflowSteps:r,persistence:n}){let i=ht.useMemo(()=>{let p=new Set;if(e&&e>0&&r)for(let b=0;b<e;b++)r[b]&&p.add(r[b].id);return p},[e,r]),s={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:i,isSubmitting:false,isTransitioning:false,isInitializing:true},[l,a]=ht.useReducer(pt,s),g=n?.adapter?X({workflowId:n.workflowId,workflowState:l,adapter:n.adapter,options:n.options,userId:n.userId}):null,c=ht.useCallback(p=>{a({type:"SET_CURRENT_STEP",stepIndex:p});},[]),o=ht.useCallback((p,b)=>{a({type:"SET_STEP_DATA",data:p,stepId:b});},[]),f=ht.useCallback((p,b,w)=>{a({type:"SET_FIELD_VALUE",fieldId:p,value:b,stepId:w});},[]),m=ht.useCallback(p=>{a({type:"SET_SUBMITTING",isSubmitting:p});},[]),y=ht.useCallback(p=>{a({type:"SET_TRANSITIONING",isTransitioning:p});},[]),d=ht.useCallback((p,b)=>{a({type:"MARK_STEP_VISITED",stepIndex:p,stepId:b});},[]),h=ht.useCallback(()=>{a({type:"RESET_WORKFLOW"});},[]),x=ht.useCallback(()=>{a({type:"SET_INITIALIZATION_COMPLETE"});},[]),E=ht.useCallback(async()=>{if(!g)return x(),false;try{let p=await g.loadPersistedData();if(p){let b={currentStepIndex:p.currentStepIndex,allData:p.allData,stepData:p.stepData,visitedSteps:new Set(p.visitedSteps)};return a({type:"LOAD_PERSISTED_STATE",state:b}),x(),!0}}catch(p){console.error("Failed to load persisted state:",p);}return x(),false},[g,x]);return {workflowState:l,setCurrentStep:c,setStepData:o,setFieldValue:f,setSubmitting:m,setTransitioning:y,markStepVisited:d,resetWorkflow:h,loadPersistedState:E,persistence:g?{isPersisting:g.isPersisting,persistenceError:g.persistenceError,persistNow:g.persistNow,clearPersistedData:g.clearPersistedData,hasPersistedData:g.hasPersistedData}:null}}function ue({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let l=ht.useRef(i);l.current=i;let a=ht.useCallback(async()=>{n(true);try{if(l.current&&await l.current(e.allData),t.analytics?.onWorkflowComplete){let c=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,c,e.allData);}}catch(c){throw console.error("Workflow submission failed:",c),t.analytics?.onError&&t.analytics.onError(c,r),c}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),g=ht.useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:g()}}var Oe=ht.createContext(null);function ge({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:l}){let a=ht.useRef(i),g=ht.useRef(s);a.current=i,g.current=s;let c=ht.useMemo(()=>{if(!n)return 0;let R=e.steps.findIndex(P=>P.id===n);return R===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):R},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:m,setFieldValue:y,setSubmitting:d,setTransitioning:h,markStepVisited:x,resetWorkflow:E,loadPersistedState:p,persistence:b}=de({defaultValues:r,defaultStepIndex:c,workflowSteps:e.steps,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});ht.useEffect(()=>{e.persistence&&p&&p();},[]);let w=ht.useMemo(()=>({isPersisting:b?.isPersisting??false,persistenceError:b?.persistenceError??null,persistNow:b?.persistNow}),[b?.isPersisting,b?.persistenceError,b?.persistNow]),N=ht.useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),u=ht.useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),v=ht.useMemo(()=>u?.formConfig,[u?.formConfig]),S=pe({workflowConfig:e,workflowState:o,currentStep:u}),I=ht.useMemo(()=>{let R=-1;for(let W=0;W<e.steps.length;W++)if(S.isStepVisible(W)){R=W;break}let P=-1;for(let W=e.steps.length-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}return {...N,isFirstStep:o.currentStepIndex===R,isLastStep:o.currentStepIndex===P}},[N,o.currentStepIndex,S,e.steps.length]),{analyticsStartTime:L}=oe({workflowConfig:e,workflowState:o,workflowContext:I}),{goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}=ce({workflowConfig:e,workflowState:o,workflowContext:I,conditionsHelpers:S,setCurrentStep:f,setTransitioning:h,markStepVisited:x,setStepData:m,onStepChange:a.current}),j=ht.useRef(false);ht.useEffect(()=>{if(j.current)return;if(!S.isStepVisible(o.currentStepIndex)){for(let P=0;P<e.steps.length;P++)if(S.isStepVisible(P)){f(P),x(P,e.steps[P].id);break}}j.current=true;},[o.currentStepIndex,e.steps,f,x]),ht.useEffect(()=>{if(!j.current)return;if(!S.isStepVisible(o.currentStepIndex)){let P=null;for(let W=o.currentStepIndex+1;W<e.steps.length;W++)if(S.isStepVisible(W)){P=W;break}if(P===null){for(let W=o.currentStepIndex-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}}P!==null&&(f(P),x(P,e.steps[P].id));}},[S,o.currentStepIndex,e.steps,f,x]);let{submitWorkflow:q,isSubmitting:We,canSubmit:De}=ue({workflowConfig:e,workflowState:o,workflowContext:I,setSubmitting:d,onWorkflowComplete:g.current,analyticsStartTime:L}),Y=ht.useCallback((R,P)=>{y(R,P,u?.id||"");},[y,u?.id]),Re=ht.useCallback(R=>{m(R,u?.id||"");},[m,u?.id]),qe=ht.useCallback(async R=>{u?.id&&R&&m(R,u.id),I.isLastStep?await q():await $();},[I.isLastStep,q,$,u?.id,m]),Ee=ht.useMemo(()=>({goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}),[K,$,ve,he,xe,Ie,ke,Pe]),we=ht.useMemo(()=>({setValue:Y,setStepData:Re,resetWorkflow:E}),[Y,Re,E]),Te=ht.useMemo(()=>({submitWorkflow:q,isSubmitting:We,canSubmit:De}),[q,We,De]),ze=ht.useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:u,context:I,formConfig:v,conditionsHelpers:S,currentStepMetadata:u?.metadata,...Ee,...we,...Te,persistNow:w.persistNow,isPersisting:w.isPersisting,persistenceError:w.persistenceError}),[o,e,u,I,v,S,Ee,we,Te,w]),Je=ht.useMemo(()=>{if(!u?.id)return {};let R=o?.allData[u.id]||{};if(!v?.allFields)return R;let P=new Set(v.allFields.map(z=>z.id)),W={};for(let[z,He]of Object.entries(R))P.has(z)&&(W[z]=He);return W},[o?.allData,u?.id,v?.allFields]),Xe=ht.useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsxRuntime.jsx(Oe.Provider,{value:ze,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:v,defaultValues:Je,onFieldChange:Y,"data-workflow-id":e.id,className:l,onSubmit:qe,children:t},Xe)})}function T(){let t=ht.useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function yt({children:t,workflowConfig:e,...r}){let[n,i]=ht.useState(),s=ht.useMemo(()=>e instanceof U?e.build():e,[e]);return ht.useEffect(()=>{if(typeof window<"u"&&B.shouldDisplayWatermark()){let a=B.getWatermarkMessage();i(a);}},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(ge,{...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 xt=ht__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 Rt=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:l,currentStep:a}=T(),{submit:g,formState:c}=forms.useFormContext(),o=ht.useMemo(()=>{let y=c.isSubmitting||s.isSubmitting,d=r??y,h=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:h}},[c.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=ht.useCallback(async y=>{y?.preventDefault(),o.canGoNext&&await g(y);},[o.canGoNext,g]),m=ht.useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:c.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,a,c.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:l.renderConfig?.nextButtonRenderer,props:m,...n})});var Nt=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:l,workflowConfig:a,currentStep:g}=T(),{formState:c}=forms.useFormContext(),o=ht.useMemo(()=>{let y=c.isSubmitting||l.isSubmitting,d=r??y,h=i.currentStepIndex>0&&!l.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:h}},[c.isSubmitting,l.isSubmitting,l.isTransitioning,i.currentStepIndex,r]),f=ht.useCallback(async y=>{y?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),m=ht.useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:g,stepData:c.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,g,c.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:m,...n})});var _t=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:l,workflowConfig:a,context:g,conditionsHelpers:c}=T(),{formState:o}=forms.useFormContext(),f=ht.useMemo(()=>{let d=o.isSubmitting||l.isSubmitting,h=r??d,x=(!!i?.allowSkip||c.isStepSkippable(l.currentStepIndex))&&!l.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:x}},[o.isSubmitting,l.isSubmitting,l.isTransitioning,l.currentStepIndex,i?.allowSkip,c.isStepSkippable,r]),m=ht.useCallback(async d=>{d?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),y=ht.useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:m,className:e,currentStep:i,stepData:o.values||{},allData:g.allData,context:g}),[f.canSkip,f.finalIsSubmitting,m,e,i,o.values,g.allData,g]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:y,...n})});var $t=ht__default.default.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:l,conditionsHelpers:a}=T(),{visibleSteps:g,visibleToOriginalIndexMap:c,originalToVisibleIndexMap:o}=ht.useMemo(()=>{let d=[],h=new Map,x=new Map;return i.steps.forEach((E,p)=>{if(a.isStepVisible(p)){let b=d.length;d.push(E),h.set(b,p),x.set(p,b);}}),{visibleSteps:d,visibleToOriginalIndexMap:h,originalToVisibleIndexMap:x}},[i.steps,a]),f=ht.useCallback(d=>{let h=c.get(d);h!==void 0&&(e?e(h):l(h));},[c,e,l]),m=ht.useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),y=ht.useMemo(()=>({steps:g,currentStepIndex:m,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[g,m,s.visitedSteps,f,r]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:y,...n})});var be=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),l=this.compress?this.compressData(s):s;localStorage.setItem(n,l);}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},l=JSON.stringify(s),a=this.compress?this.compressData(l):l;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,l=JSON.parse(s);l.expiresAt&&Date.now()>l.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
|
|
2
|
+
exports.LocalStorageAdapter=be;exports.RilayLicenseManager=B;exports.Workflow=yt;exports.WorkflowBody=xt;exports.WorkflowNextButton=Rt;exports.WorkflowPersistenceError=D;exports.WorkflowPreviousButton=Nt;exports.WorkflowProvider=ge;exports.WorkflowSkipButton=_t;exports.WorkflowStepper=$t;exports.combineWorkflowDataForConditions=le;exports.debounce=ie;exports.flattenObject=ae;exports.flow=U;exports.generateStorageKey=ne;exports.mergePersistedState=nt;exports.persistedToWorkflowState=Le;exports.useConditionEvaluation=te;exports.usePersistence=X;exports.useStepMetadata=it;exports.useWorkflowAnalytics=oe;exports.useWorkflowConditions=pe;exports.useWorkflowContext=T;exports.useWorkflowNavigation=ce;exports.useWorkflowState=de;exports.useWorkflowSubmission=ue;exports.validatePersistedData=rt;exports.workflowStateToPersisted=re;
|
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 bt,{createContext,useMemo,useCallback,useContext,useState,useRef,useEffect,useReducer}from'react';import*as Ee 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(a=>a.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 Qe=1751361139160,et="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",I=class I{static async setLicenseKey(e){I.licenseKey=e||"",I.licenseKey?I.licenseResult=await I.validateLicense():I.licenseResult={valid:false,error:"MISSING"},I.isInitialized=true;}static async validateLicense(){if(!I.licenseKey)return {valid:false,error:"MISSING"};try{if(!I.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=I.licenseKey.slice(4),n=I.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,a]=n,l=`${i}.${s}`,b=new TextEncoder().encode(l),p=a.match(/.{2}/g);if(!p)return {valid:!1,error:"INVALID"};let o=new Uint8Array(p.map(P=>Number.parseInt(P,16))),f=I.hexToBytes(et);if(!await Ee.verify(o,b,f))return {valid:!1,error:"SIGNATURE_INVALID"};let m=I.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),c=JSON.parse(m),h=Math.floor(Date.now()/1e3);return c.e<h?{valid:!1,error:"EXPIRED",data:I.decompressPayload(c)}:Qe>c.e*1e3?{valid:!1,error:"EXPIRED",data:I.decompressPayload(c)}:c.p===void 0||!c.c||!c.i||!c.e||!c.t?{valid:!1,error:"INVALID"}:{valid:!0,data:I.decompressPayload(c)}}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 a=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),b=r.indexOf(s.charAt(i++)),p=r.indexOf(s.charAt(i++)),o=a<<18|l<<12|b<<6|p;n+=String.fromCharCode(o>>16&255),b!==64&&(n+=String.fromCharCode(o>>8&255)),p!==64&&(n+=String.fromCharCode(o&255));}return n}static getLicenseResult(){return I.isInitialized?I.licenseResult?I.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!I.getLicenseResult().valid}static getWatermarkMessage(){let e=I.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=I.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=I.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};I.licenseKey="",I.licenseResult=null,I.isInitialized=false;var _=I;function ee(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=a=>{try{return a&&typeof a=="object"&&"build"in a?evaluateCondition(a.build(),e):evaluateCondition(a,e)}catch(l){return console.warn(`Error evaluating condition for field ${n}:`,l),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 Te(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 a=l=>{try{return l&&typeof l=="object"&&"build"in l?evaluateCondition(l.build(),e):evaluateCondition(l,e)}catch(b){return console.warn(`Error evaluating condition for step ${s}:`,b),false}};r[s]={visible:i.visible?a(i.visible):true,disabled:i.disabled?a(i.disabled):false,required:i.required?a(i.required):false,readonly:i.readonly?a(i.readonly):false};}}return r},[t,e])}var W=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function te(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 Ce(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function tt(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 re(t,e){return e?`${e}:${t}`:t}function ne(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function rt(t,e,r="persist"){let n=Ce(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 X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,a]=useState(false),[l,b]=useState(null),[p,o]=useState(false),f=useRef(r),u=useRef(n),m=useRef({hasPendingChanges:false});useEffect(()=>{f.current=r,u.current=n;},[r,n]);let c=re(u.current.storageKey||t,i),h=useCallback(()=>{b(null);},[]),g=useCallback((S,k)=>{let L=S instanceof W?S:new W(`${k} failed: ${S.message}`,"OPERATION_FAILED",S);b(L),console.error("[WorkflowPersistence]",L);},[]),P=useCallback(async S=>{h(),a(true);try{let k=te(t,S,u.current.metadata);await f.current.save(c,k),m.current.lastSavedState={...S},m.current.hasPendingChanges=!1;}catch(k){throw g(k,"Save"),k}finally{a(false);}},[t,c,h,g]),y=useRef(ne(async S=>{try{await P(S);}catch(k){console.debug("[WorkflowPersistence] Auto-save failed:",k);}},n.debounceMs||500)),x=useCallback((S,k)=>k?S.currentStepIndex!==k.currentStepIndex||JSON.stringify(S.allData)!==JSON.stringify(k.allData)||JSON.stringify(S.stepData)!==JSON.stringify(k.stepData)||S.visitedSteps.size!==k.visitedSteps.size||!Array.from(S.visitedSteps).every(L=>k.visitedSteps.has(L)):true,[]),E=useCallback(async()=>{h(),o(true);try{let S=await f.current.load(c);return S&&(m.current.lastSavedState={currentStepIndex:S.currentStepIndex,allData:S.allData,stepData:S.stepData,visitedSteps:new Set(S.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},m.current.hasPendingChanges=!1),S}catch(S){return g(S,"Load"),null}finally{setTimeout(()=>o(false),100);}},[c,h,g]),N=useCallback(async()=>{h();try{await f.current.remove(c),m.current.lastSavedState=void 0,m.current.hasPendingChanges=!1;}catch(S){throw g(S,"Clear"),S}},[c,h,g]),d=useCallback(async()=>{try{return await f.current.exists(c)}catch(S){return g(S,"Exists check"),false}},[c,g]);useEffect(()=>{u.current.autoPersist&&(s||p||e.isInitializing||e.isSubmitting||e.isTransitioning||x(e,m.current.lastSavedState)&&(m.current.hasPendingChanges=true,y.current(e)));},[e,s,p,x]);let v=useCallback(async()=>{await P(e);},[P,e]);return {isPersisting:s,persistenceError:l,persistNow:v,loadPersistedData:E,clearPersistedData:N,hasPersistedData:d}}function nt(){let{workflowConfig:t,currentStep:e}=w(),r=useMemo(()=>e?.metadata,[e?.metadata]),n=useMemo(()=>p=>t.steps.find(f=>f.id===p)?.metadata,[t.steps]),i=useMemo(()=>p=>t.steps[p]?.metadata,[t.steps]),s=useMemo(()=>p=>r?p in r:false,[r]),a=useMemo(()=>(p,o)=>r&&p in r?r[p]:o,[r]),l=useMemo(()=>()=>t.steps.map((p,o)=>({id:p.id,title:p.title,index:o,metadata:p.metadata})),[t.steps]),b=useMemo(()=>p=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>p(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:a,getAllStepsMetadata:l,findStepsByMetadata:b}}function se({workflowConfig:t,workflowState:e,workflowContext:r}){let n=useRef(Date.now()),i=useRef(new Map),s=useRef(false),a=useRef(null),l=getGlobalMonitor();useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),l&&l.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,l,t.steps.length]),useEffect(()=>{let u=t.steps[e.currentStepIndex];if(u&&a.current!==u.id){if(a.current&&t.analytics?.onStepComplete){let m=i.current.get(a.current);if(m){let c=Date.now()-m;t.analytics.onStepComplete(a.current,c,e.stepData,r),l&&l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:a.current,duration:c},{timestamp:Date.now(),duration:c,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:c,conditionEvaluationDuration:0},"low");}}a.current=u.id,i.current.set(u.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(u.id,Date.now(),r),l&&l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:u.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,l,t.id]);let b=useCallback((u,m)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(u,m,r),l&&l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:u,reason:m},void 0,"medium");},[t.analytics,r,l,t.id]),p=useCallback(u=>{t.analytics?.onError&&t.analytics.onError(u,r),l&&l.trackError(u,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,l,t.id,e.currentStepIndex,t.steps]),o=useCallback((u,m,c)=>{if(!l)return;let h={timestamp:Date.now(),duration:c,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:m,navigationDuration:c,conditionEvaluationDuration:0};l.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:u,toStep:m,direction:m>u?"forward":"backward"},h,c>1e3?"medium":"low");},[l,t.id,t.steps.length]),f=useCallback((u,m)=>{if(!l)return;let c={timestamp:Date.now(),duration:u,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:u};l.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:m,currentStepIndex:e.currentStepIndex},c,u>100?"medium":"low");},[l,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:b,trackError:p,trackNavigation:o,trackConditionEvaluation:f}}function oe(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,oe(i,s)):r[s]=i;}return r}function ae(t,e){let r={...t,...e},n=oe(r);return {...r,...n}}function Le(t,e){return {visible:t.visible,skippable:e===true||t.required}}function le({workflowConfig:t,workflowState:e,currentStep:r}){let n=useMemo(()=>ae(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=ee(i,n,{visible:true,disabled:false,required:false,readonly:false}),a=useMemo(()=>Le(s,r?.allowSkip),[s,r?.allowSkip]),l=useMemo(()=>{let y={};return t.steps.forEach((x,E)=>{x.conditions&&(y[E]={visible:x.conditions.visible,required:x.conditions.skippable});}),y},[t.steps]),b=Te(l,n),p=useMemo(()=>{let y={};return t.steps.forEach((x,E)=>{let N=b[E];N?y[E]=Le(N,x.allowSkip):y[E]={visible:true,skippable:x.allowSkip===true};}),y},[t.steps,b]),o=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]),f=we(o,n),u=useCallback(y=>y<0||y>=t.steps.length?false:p[y]?.visible??true,[p,t.steps.length]),m=useCallback(y=>y<0||y>=t.steps.length?false:p[y]?.skippable??false,[p,t.steps.length]),c=useCallback(y=>f[y]?.visible??true,[f]),h=useCallback(y=>f[y]?.disabled??false,[f]),g=useCallback(y=>f[y]?.required??false,[f]),P=useCallback(y=>f[y]?.readonly??false,[f]);return {stepConditions:a,fieldConditions:f,allStepConditions:p,isStepVisible:u,isStepSkippable:m,isFieldVisible:c,isFieldDisabled:h,isFieldRequired:g,isFieldReadonly:P}}function pe({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:a,setStepData:l,onStepChange:b}){let p=useRef(b);p.current=b;let o=t.steps[e.currentStepIndex],f=useCallback(()=>({setStepData:(d,v)=>{l(v,d);},setStepFields:(d,v)=>{let k={...e.allData[d]||{},...v};l(k,d);},getStepData:d=>e.allData[d]||{},setNextStepField:(d,v)=>{let S=e.currentStepIndex+1;if(S<t.steps.length){let k=t.steps[S].id,K={...e.allData[k]||{},[d]:v};l(K,k);}},setNextStepFields:d=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let S=t.steps[v].id,L={...e.allData[S]||{},...d};l(L,S);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,l]),u=useCallback(async d=>{if(d<0||d>=t.steps.length||!n.isStepVisible(d))return false;s(true);try{return p.current&&p.current(e.currentStepIndex,d,r),i(d),a(d,t.steps[d].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,a]),m=useCallback(d=>{for(let v=d+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),c=useCallback(d=>{for(let v=d-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),h=useCallback(async()=>{if(o?.onAfterValidation)try{let v=f();await o.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let d=m(e.currentStepIndex);return d===null?false:u(d)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,m,u]),g=useCallback(async()=>{let d=c(e.currentStepIndex);return d===null?false:u(d)},[e.currentStepIndex,c,u]),P=useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),y=useCallback(d=>d<0||d>=t.steps.length?false:n.isStepVisible(d),[t.steps.length,n]),x=useCallback(()=>{let d=m(e.currentStepIndex);return d!==null&&y(d)},[e.currentStepIndex,m,y]),E=useCallback(()=>{let d=c(e.currentStepIndex);return d!==null&&y(d)},[e.currentStepIndex,c,y]),N=useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:u,goNext:h,goPrevious:g,skipStep:P,canGoToStep:y,canGoNext:x,canGoPrevious:E,canSkipCurrentStep:N}}function at(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 ce({defaultValues:t={},defaultStepIndex:e,persistence:r}){let n={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[i,s]=useReducer(at,n),a=r?.adapter?X({workflowId:r.workflowId,workflowState:i,adapter:r.adapter,options:r.options,userId:r.userId}):null,l=useCallback(g=>{s({type:"SET_CURRENT_STEP",stepIndex:g});},[]),b=useCallback((g,P)=>{s({type:"SET_STEP_DATA",data:g,stepId:P});},[]),p=useCallback((g,P,y)=>{s({type:"SET_FIELD_VALUE",fieldId:g,value:P,stepId:y});},[]),o=useCallback(g=>{s({type:"SET_SUBMITTING",isSubmitting:g});},[]),f=useCallback(g=>{s({type:"SET_TRANSITIONING",isTransitioning:g});},[]),u=useCallback((g,P)=>{s({type:"MARK_STEP_VISITED",stepIndex:g,stepId:P});},[]),m=useCallback(()=>{s({type:"RESET_WORKFLOW"});},[]),c=useCallback(()=>{s({type:"SET_INITIALIZATION_COMPLETE"});},[]),h=useCallback(async()=>{if(!a)return c(),false;try{let g=await a.loadPersistedData();if(g){let P={currentStepIndex:g.currentStepIndex,allData:g.allData,stepData:g.stepData,visitedSteps:new Set(g.visitedSteps)};return s({type:"LOAD_PERSISTED_STATE",state:P}),c(),!0}}catch(g){console.error("Failed to load persisted state:",g);}return c(),false},[a,c]);return {workflowState:i,setCurrentStep:l,setStepData:b,setFieldValue:p,setSubmitting:o,setTransitioning:f,markStepVisited:u,resetWorkflow:m,loadPersistedState:h,persistence:a?{isPersisting:a.isPersisting,persistenceError:a.persistenceError,persistNow:a.persistNow,clearPersistedData:a.clearPersistedData,hasPersistedData:a.hasPersistedData}:null}}function de({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let a=useRef(i);a.current=i;let l=useCallback(async()=>{n(true);try{if(a.current&&await a.current(e.allData),t.analytics?.onWorkflowComplete){let p=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,p,e.allData);}}catch(p){throw console.error("Workflow submission failed:",p),t.analytics?.onError&&t.analytics.onError(p,r),p}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),b=useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:l,isSubmitting:e.isSubmitting,canSubmit:b()}}var Oe=createContext(null);function fe({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:a}){let l=useRef(i),b=useRef(s);l.current=i,b.current=s;let p=useMemo(()=>{if(!n)return 0;let D=e.steps.findIndex(R=>R.id===n);return D===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):D},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:u,setFieldValue:m,setSubmitting:c,setTransitioning:h,markStepVisited:g,resetWorkflow:P,loadPersistedState:y,persistence:x}=ce({defaultValues:r,defaultStepIndex:p,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});useEffect(()=>{e.persistence&&y&&y();},[]);let E=useMemo(()=>({isPersisting:x?.isPersisting??false,persistenceError:x?.persistenceError??null,persistNow:x?.persistNow}),[x?.isPersisting,x?.persistenceError,x?.persistNow]),N=useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),d=useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),v=useMemo(()=>d?.formConfig,[d?.formConfig]),S=le({workflowConfig:e,workflowState:o,currentStep:d}),k=useMemo(()=>{let D=-1;for(let T=0;T<e.steps.length;T++)if(S.isStepVisible(T)){D=T;break}let R=-1;for(let T=e.steps.length-1;T>=0;T--)if(S.isStepVisible(T)){R=T;break}return {...N,isFirstStep:o.currentStepIndex===D,isLastStep:o.currentStepIndex===R}},[N,o.currentStepIndex,S,e.steps.length]),{analyticsStartTime:L}=se({workflowConfig:e,workflowState:o,workflowContext:k}),{goToStep:K,goNext:$,goPrevious:ge,skipStep:ye,canGoToStep:be,canGoNext:ve,canGoPrevious:he,canSkipCurrentStep:xe}=pe({workflowConfig:e,workflowState:o,workflowContext:k,conditionsHelpers:S,setCurrentStep:f,setTransitioning:h,markStepVisited:g,setStepData:u,onStepChange:l.current});useEffect(()=>{if(!S.isStepVisible(o.currentStepIndex)){for(let R=0;R<e.steps.length;R++)if(S.isStepVisible(R)){f(R),g(R,e.steps[R].id);break}}},[S,o.currentStepIndex,e.steps,f,g]);let{submitWorkflow:q,isSubmitting:ke,canSubmit:Ie}=de({workflowConfig:e,workflowState:o,workflowContext:k,setSubmitting:c,onWorkflowComplete:b.current,analyticsStartTime:L}),j=useCallback((D,R)=>{m(D,R,d?.id||"");},[m,d?.id]),Pe=useCallback(D=>{u(D,d?.id||"");},[u,d?.id]),$e=useCallback(async D=>{d?.id&&D&&u(D,d.id),k.isLastStep?await q():await $();},[k.isLastStep,q,$,d?.id,u]),We=useMemo(()=>({goToStep:K,goNext:$,goPrevious:ge,skipStep:ye,canGoToStep:be,canGoNext:ve,canGoPrevious:he,canSkipCurrentStep:xe}),[K,$,ge,ye,be,ve,he,xe]),De=useMemo(()=>({setValue:j,setStepData:Pe,resetWorkflow:P}),[j,Pe,P]),Re=useMemo(()=>({submitWorkflow:q,isSubmitting:ke,canSubmit:Ie}),[q,ke,Ie]),qe=useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:d,context:k,formConfig:v,conditionsHelpers:S,currentStepMetadata:d?.metadata,...We,...De,...Re,persistNow:E.persistNow,isPersisting:E.isPersisting,persistenceError:E.persistenceError}),[o,e,d,k,v,S,We,De,Re,E]),ze=useMemo(()=>{if(!d?.id)return {};let D=o?.allData[d.id]||{};if(!v?.allFields)return D;let R=new Set(v.allFields.map(z=>z.id)),T={};for(let[z,Xe]of Object.entries(D))R.has(z)&&(T[z]=Xe);return T},[o?.allData,d?.id,v?.allFields]),Je=useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsx(Oe.Provider,{value:qe,children:jsx(FormProvider,{formConfig:v,defaultValues:ze,onFieldChange:j,"data-workflow-id":e.id,className:a,onSubmit:$e,children:t},Je)})}function w(){let t=useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function St({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 l=_.getWatermarkMessage();i(l);}},[]),jsxs("div",{style:{position:"relative"},children:[jsx(fe,{...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 vt=bt.memo(function({stepId:e,children:r}){let{currentStep:n}=w();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsx(FormBody,{}):null});var Wt=bt.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:a,currentStep:l}=w(),{submit:b,formState:p}=useFormContext(),o=useMemo(()=>{let m=p.isSubmitting||s.isSubmitting,c=r??m,h=!s.isTransitioning&&!c;return {finalIsSubmitting:c,canGoNext:h}},[p.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=useCallback(async m=>{m?.preventDefault(),o.canGoNext&&await b(m);},[o.canGoNext,b]),u=useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:l,stepData:p.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,l,p.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:a.renderConfig?.nextButtonRenderer,props:u,...n})});var Ct=bt.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:a,workflowConfig:l,currentStep:b}=w(),{formState:p}=useFormContext(),o=useMemo(()=>{let m=p.isSubmitting||a.isSubmitting,c=r??m,h=i.currentStepIndex>0&&!a.isTransitioning&&!c;return {finalIsSubmitting:c,canGoPrevious:h}},[p.isSubmitting,a.isSubmitting,a.isTransitioning,i.currentStepIndex,r]),f=useCallback(async m=>{m?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),u=useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:b,stepData:p.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,b,p.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:l.renderConfig?.previousButtonRenderer,props:u,...n})});var Bt=bt.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:a,workflowConfig:l,context:b,conditionsHelpers:p}=w(),{formState:o}=useFormContext(),f=useMemo(()=>{let c=o.isSubmitting||a.isSubmitting,h=r??c,g=(!!i?.allowSkip||p.isStepSkippable(a.currentStepIndex))&&!a.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:g}},[o.isSubmitting,a.isSubmitting,a.isTransitioning,a.currentStepIndex,i?.allowSkip,p.isStepSkippable,r]),u=useCallback(async c=>{c?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),m=useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:u,className:e,currentStep:i,stepData:o.values||{},allData:b.allData,context:b}),[f.canSkip,f.finalIsSubmitting,u,e,i,o.values,b.allData,b]);return jsx(ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:l.renderConfig?.skipButtonRenderer,props:m,...n})});var Gt=bt.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:a,conditionsHelpers:l}=w(),{visibleSteps:b,visibleToOriginalIndexMap:p,originalToVisibleIndexMap:o}=useMemo(()=>{let c=[],h=new Map,g=new Map;return i.steps.forEach((P,y)=>{if(l.isStepVisible(y)){let x=c.length;c.push(P),h.set(x,y),g.set(y,x);}}),{visibleSteps:c,visibleToOriginalIndexMap:h,originalToVisibleIndexMap:g}},[i.steps,l]),f=useCallback(c=>{let h=p.get(c);h!==void 0&&(e?e(h):a(h));},[p,e,a]),u=useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),m=useMemo(()=>({steps:b,currentStepIndex:u,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[b,u,s.visitedSteps,f,r]);return jsx(ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:m,...n})});var Se=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),a=this.compress?this.compressData(s):s;localStorage.setItem(n,a);}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},a=JSON.stringify(s),l=this.compress?this.compressData(a):a;localStorage.setItem(i,l);}catch(i){throw new W("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new W(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new W("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 W(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new W("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 W(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new W("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 W(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new W("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 W(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new W("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,a=JSON.parse(s);a.expiresAt&&Date.now()>a.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 ht,{createContext,useMemo,useCallback,useContext,useState,useRef,useEffect,useReducer}from'react';import*as Ce 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(l=>l.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 et=1751361139160,tt="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,l]=n,a=`${i}.${s}`,g=new TextEncoder().encode(a),c=l.match(/.{2}/g);if(!c)return {valid:!1,error:"INVALID"};let o=new Uint8Array(c.map(E=>Number.parseInt(E,16))),f=k.hexToBytes(tt);if(!await Ce.verify(o,g,f))return {valid:!1,error:"SIGNATURE_INVALID"};let y=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(y),h=Math.floor(Date.now()/1e3);return d.e<h?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:et>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 l=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),g=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),o=l<<18|a<<12|g<<6|c;n+=String.fromCharCode(o>>16&255),g!==64&&(n+=String.fromCharCode(o>>8&255)),c!==64&&(n+=String.fromCharCode(o&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 B=k;function te(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 Ae(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=l=>{try{return l&&typeof l=="object"&&"build"in l?evaluateCondition(l.build(),e):evaluateCondition(l,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 Ne(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 l=a=>{try{return a&&typeof a=="object"&&"build"in a?evaluateCondition(a.build(),e):evaluateCondition(a,e)}catch(g){return console.warn(`Error evaluating condition for step ${s}:`,g),false}};r[s]={visible:i.visible?l(i.visible):true,disabled:i.disabled?l(i.disabled):false,required:i.required?l(i.required):false,readonly:i.readonly?l(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 re(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 Le(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function rt(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 ne(t,e){return e?`${e}:${t}`:t}function ie(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function nt(t,e,r="persist"){let n=Le(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 X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,l]=useState(false),[a,g]=useState(null),[c,o]=useState(false),f=useRef(r),m=useRef(n),y=useRef({hasPendingChanges:false});useEffect(()=>{f.current=r,m.current=n;},[r,n]);let d=ne(m.current.storageKey||t,i),h=useCallback(()=>{g(null);},[]),x=useCallback((S,I)=>{let L=S instanceof D?S:new D(`${I} failed: ${S.message}`,"OPERATION_FAILED",S);g(L),console.error("[WorkflowPersistence]",L);},[]),E=useCallback(async S=>{h(),l(true);try{let I=re(t,S,m.current.metadata);await f.current.save(d,I),y.current.lastSavedState={...S},y.current.hasPendingChanges=!1;}catch(I){throw x(I,"Save"),I}finally{l(false);}},[t,d,h,x]),p=useRef(ie(async S=>{try{await E(S);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),b=useCallback((S,I)=>I?S.currentStepIndex!==I.currentStepIndex||JSON.stringify(S.allData)!==JSON.stringify(I.allData)||JSON.stringify(S.stepData)!==JSON.stringify(I.stepData)||S.visitedSteps.size!==I.visitedSteps.size||!Array.from(S.visitedSteps).every(L=>I.visitedSteps.has(L)):true,[]),w=useCallback(async()=>{h(),o(true);try{let S=await f.current.load(d);return S&&(y.current.lastSavedState={currentStepIndex:S.currentStepIndex,allData:S.allData,stepData:S.stepData,visitedSteps:new Set(S.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},y.current.hasPendingChanges=!1),S}catch(S){return x(S,"Load"),null}finally{setTimeout(()=>o(false),100);}},[d,h,x]),N=useCallback(async()=>{h();try{await f.current.remove(d),y.current.lastSavedState=void 0,y.current.hasPendingChanges=!1;}catch(S){throw x(S,"Clear"),S}},[d,h,x]),u=useCallback(async()=>{try{return await f.current.exists(d)}catch(S){return x(S,"Exists check"),false}},[d,x]);useEffect(()=>{m.current.autoPersist&&(s||c||e.isInitializing||e.isSubmitting||e.isTransitioning||b(e,y.current.lastSavedState)&&(y.current.hasPendingChanges=true,p.current(e)));},[e,s,c,b]);let v=useCallback(async()=>{await E(e);},[E,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:w,clearPersistedData:N,hasPersistedData:u}}function it(){let{workflowConfig:t,currentStep:e}=T(),r=useMemo(()=>e?.metadata,[e?.metadata]),n=useMemo(()=>c=>t.steps.find(f=>f.id===c)?.metadata,[t.steps]),i=useMemo(()=>c=>t.steps[c]?.metadata,[t.steps]),s=useMemo(()=>c=>r?c in r:false,[r]),l=useMemo(()=>(c,o)=>r&&c in r?r[c]:o,[r]),a=useMemo(()=>()=>t.steps.map((c,o)=>({id:c.id,title:c.title,index:o,metadata:c.metadata})),[t.steps]),g=useMemo(()=>c=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>c(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:l,getAllStepsMetadata:a,findStepsByMetadata:g}}function oe({workflowConfig:t,workflowState:e,workflowContext:r}){let n=useRef(Date.now()),i=useRef(new Map),s=useRef(false),l=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 m=t.steps[e.currentStepIndex];if(m&&l.current!==m.id){if(l.current&&t.analytics?.onStepComplete){let y=i.current.get(l.current);if(y){let d=Date.now()-y;t.analytics.onStepComplete(l.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:l.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}l.current=m.id,i.current.set(m.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(m.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:m.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 g=useCallback((m,y)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(m,y,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:m,reason:y},void 0,"medium");},[t.analytics,r,a,t.id]),c=useCallback(m=>{t.analytics?.onError&&t.analytics.onError(m,r),a&&a.trackError(m,`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]),o=useCallback((m,y,d)=>{if(!a)return;let h={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:y,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:m,toStep:y,direction:y>m?"forward":"backward"},h,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=useCallback((m,y)=>{if(!a)return;let d={timestamp:Date.now(),duration:m,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:m};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:y,currentStepIndex:e.currentStepIndex},d,m>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:g,trackError:c,trackNavigation:o,trackConditionEvaluation:f}}function ae(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,ae(i,s)):r[s]=i;}return r}function le(t,e){let r={...t,...e},n=ae(r);return {...r,...n}}function Ve(t,e){return {visible:t.visible,skippable:e===true||t.required}}function pe({workflowConfig:t,workflowState:e,currentStep:r}){let n=useMemo(()=>le(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=te(i,n,{visible:true,disabled:false,required:false,readonly:false}),l=useMemo(()=>Ve(s,r?.allowSkip),[s,r?.allowSkip]),a=useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{b.conditions&&(p[w]={visible:b.conditions.visible,required:b.conditions.skippable});}),p},[t.steps]),g=Ne(a,n),c=useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{let N=g[w];N?p[w]=Ve(N,b.allowSkip):p[w]={visible:true,skippable:b.allowSkip===true};}),p},[t.steps,g]),o=useMemo(()=>{if(!r?.formConfig?.allFields)return {};let p={};for(let b of r.formConfig.allFields)b.conditions&&(p[b.id]=b.conditions);return p},[r?.formConfig?.allFields]),f=Ae(o,n),m=useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.visible??true,[c,t.steps.length]),y=useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.skippable??false,[c,t.steps.length]),d=useCallback(p=>f[p]?.visible??true,[f]),h=useCallback(p=>f[p]?.disabled??false,[f]),x=useCallback(p=>f[p]?.required??false,[f]),E=useCallback(p=>f[p]?.readonly??false,[f]);return {stepConditions:l,fieldConditions:f,allStepConditions:c,isStepVisible:m,isStepSkippable:y,isFieldVisible:d,isFieldDisabled:h,isFieldRequired:x,isFieldReadonly:E}}function ce({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:l,setStepData:a,onStepChange:g}){let c=useRef(g);c.current=g;let o=t.steps[e.currentStepIndex],f=useCallback(()=>({setStepData:(u,v)=>{a(v,u);},setStepFields:(u,v)=>{let I={...e.allData[u]||{},...v};a(I,u);},getStepData:u=>e.allData[u]||{},setNextStepField:(u,v)=>{let S=e.currentStepIndex+1;if(S<t.steps.length){let I=t.steps[S].id,K={...e.allData[I]||{},[u]:v};a(K,I);}},setNextStepFields:u=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let S=t.steps[v].id,L={...e.allData[S]||{},...u};a(L,S);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),m=useCallback(async u=>{if(u<0||u>=t.steps.length||!n.isStepVisible(u))return false;s(true);try{return c.current&&c.current(e.currentStepIndex,u,r),i(u),l(u,t.steps[u].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,l]),y=useCallback(u=>{for(let v=u+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=useCallback(u=>{for(let v=u-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),h=useCallback(async()=>{if(o?.onAfterValidation)try{let v=f();await o.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let u=y(e.currentStepIndex);return u===null?false:m(u)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,y,m]),x=useCallback(async()=>{let u=d(e.currentStepIndex);return u===null?false:m(u)},[e.currentStepIndex,d,m]),E=useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),p=useCallback(u=>u<0||u>=t.steps.length?false:n.isStepVisible(u),[t.steps.length,n]),b=useCallback(()=>{let u=y(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,y,p]),w=useCallback(()=>{let u=d(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,d,p]),N=useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:m,goNext:h,goPrevious:x,skipStep:E,canGoToStep:p,canGoNext:b,canGoPrevious:w,canSkipCurrentStep:N}}function pt(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 de({defaultValues:t={},defaultStepIndex:e,workflowSteps:r,persistence:n}){let i=useMemo(()=>{let p=new Set;if(e&&e>0&&r)for(let b=0;b<e;b++)r[b]&&p.add(r[b].id);return p},[e,r]),s={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:i,isSubmitting:false,isTransitioning:false,isInitializing:true},[l,a]=useReducer(pt,s),g=n?.adapter?X({workflowId:n.workflowId,workflowState:l,adapter:n.adapter,options:n.options,userId:n.userId}):null,c=useCallback(p=>{a({type:"SET_CURRENT_STEP",stepIndex:p});},[]),o=useCallback((p,b)=>{a({type:"SET_STEP_DATA",data:p,stepId:b});},[]),f=useCallback((p,b,w)=>{a({type:"SET_FIELD_VALUE",fieldId:p,value:b,stepId:w});},[]),m=useCallback(p=>{a({type:"SET_SUBMITTING",isSubmitting:p});},[]),y=useCallback(p=>{a({type:"SET_TRANSITIONING",isTransitioning:p});},[]),d=useCallback((p,b)=>{a({type:"MARK_STEP_VISITED",stepIndex:p,stepId:b});},[]),h=useCallback(()=>{a({type:"RESET_WORKFLOW"});},[]),x=useCallback(()=>{a({type:"SET_INITIALIZATION_COMPLETE"});},[]),E=useCallback(async()=>{if(!g)return x(),false;try{let p=await g.loadPersistedData();if(p){let b={currentStepIndex:p.currentStepIndex,allData:p.allData,stepData:p.stepData,visitedSteps:new Set(p.visitedSteps)};return a({type:"LOAD_PERSISTED_STATE",state:b}),x(),!0}}catch(p){console.error("Failed to load persisted state:",p);}return x(),false},[g,x]);return {workflowState:l,setCurrentStep:c,setStepData:o,setFieldValue:f,setSubmitting:m,setTransitioning:y,markStepVisited:d,resetWorkflow:h,loadPersistedState:E,persistence:g?{isPersisting:g.isPersisting,persistenceError:g.persistenceError,persistNow:g.persistNow,clearPersistedData:g.clearPersistedData,hasPersistedData:g.hasPersistedData}:null}}function ue({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let l=useRef(i);l.current=i;let a=useCallback(async()=>{n(true);try{if(l.current&&await l.current(e.allData),t.analytics?.onWorkflowComplete){let c=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,c,e.allData);}}catch(c){throw console.error("Workflow submission failed:",c),t.analytics?.onError&&t.analytics.onError(c,r),c}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),g=useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:g()}}var Oe=createContext(null);function ge({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:l}){let a=useRef(i),g=useRef(s);a.current=i,g.current=s;let c=useMemo(()=>{if(!n)return 0;let R=e.steps.findIndex(P=>P.id===n);return R===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):R},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:m,setFieldValue:y,setSubmitting:d,setTransitioning:h,markStepVisited:x,resetWorkflow:E,loadPersistedState:p,persistence:b}=de({defaultValues:r,defaultStepIndex:c,workflowSteps:e.steps,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});useEffect(()=>{e.persistence&&p&&p();},[]);let w=useMemo(()=>({isPersisting:b?.isPersisting??false,persistenceError:b?.persistenceError??null,persistNow:b?.persistNow}),[b?.isPersisting,b?.persistenceError,b?.persistNow]),N=useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),u=useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),v=useMemo(()=>u?.formConfig,[u?.formConfig]),S=pe({workflowConfig:e,workflowState:o,currentStep:u}),I=useMemo(()=>{let R=-1;for(let W=0;W<e.steps.length;W++)if(S.isStepVisible(W)){R=W;break}let P=-1;for(let W=e.steps.length-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}return {...N,isFirstStep:o.currentStepIndex===R,isLastStep:o.currentStepIndex===P}},[N,o.currentStepIndex,S,e.steps.length]),{analyticsStartTime:L}=oe({workflowConfig:e,workflowState:o,workflowContext:I}),{goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}=ce({workflowConfig:e,workflowState:o,workflowContext:I,conditionsHelpers:S,setCurrentStep:f,setTransitioning:h,markStepVisited:x,setStepData:m,onStepChange:a.current}),j=useRef(false);useEffect(()=>{if(j.current)return;if(!S.isStepVisible(o.currentStepIndex)){for(let P=0;P<e.steps.length;P++)if(S.isStepVisible(P)){f(P),x(P,e.steps[P].id);break}}j.current=true;},[o.currentStepIndex,e.steps,f,x]),useEffect(()=>{if(!j.current)return;if(!S.isStepVisible(o.currentStepIndex)){let P=null;for(let W=o.currentStepIndex+1;W<e.steps.length;W++)if(S.isStepVisible(W)){P=W;break}if(P===null){for(let W=o.currentStepIndex-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}}P!==null&&(f(P),x(P,e.steps[P].id));}},[S,o.currentStepIndex,e.steps,f,x]);let{submitWorkflow:q,isSubmitting:We,canSubmit:De}=ue({workflowConfig:e,workflowState:o,workflowContext:I,setSubmitting:d,onWorkflowComplete:g.current,analyticsStartTime:L}),Y=useCallback((R,P)=>{y(R,P,u?.id||"");},[y,u?.id]),Re=useCallback(R=>{m(R,u?.id||"");},[m,u?.id]),qe=useCallback(async R=>{u?.id&&R&&m(R,u.id),I.isLastStep?await q():await $();},[I.isLastStep,q,$,u?.id,m]),Ee=useMemo(()=>({goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}),[K,$,ve,he,xe,Ie,ke,Pe]),we=useMemo(()=>({setValue:Y,setStepData:Re,resetWorkflow:E}),[Y,Re,E]),Te=useMemo(()=>({submitWorkflow:q,isSubmitting:We,canSubmit:De}),[q,We,De]),ze=useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:u,context:I,formConfig:v,conditionsHelpers:S,currentStepMetadata:u?.metadata,...Ee,...we,...Te,persistNow:w.persistNow,isPersisting:w.isPersisting,persistenceError:w.persistenceError}),[o,e,u,I,v,S,Ee,we,Te,w]),Je=useMemo(()=>{if(!u?.id)return {};let R=o?.allData[u.id]||{};if(!v?.allFields)return R;let P=new Set(v.allFields.map(z=>z.id)),W={};for(let[z,He]of Object.entries(R))P.has(z)&&(W[z]=He);return W},[o?.allData,u?.id,v?.allFields]),Xe=useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsx(Oe.Provider,{value:ze,children:jsx(FormProvider,{formConfig:v,defaultValues:Je,onFieldChange:Y,"data-workflow-id":e.id,className:l,onSubmit:qe,children:t},Xe)})}function T(){let t=useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function yt({children:t,workflowConfig:e,...r}){let[n,i]=useState(),s=useMemo(()=>e instanceof U?e.build():e,[e]);return useEffect(()=>{if(typeof window<"u"&&B.shouldDisplayWatermark()){let a=B.getWatermarkMessage();i(a);}},[]),jsxs("div",{style:{position:"relative"},children:[jsx(ge,{...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 xt=ht.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 Rt=ht.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:l,currentStep:a}=T(),{submit:g,formState:c}=useFormContext(),o=useMemo(()=>{let y=c.isSubmitting||s.isSubmitting,d=r??y,h=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:h}},[c.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=useCallback(async y=>{y?.preventDefault(),o.canGoNext&&await g(y);},[o.canGoNext,g]),m=useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:c.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,a,c.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:l.renderConfig?.nextButtonRenderer,props:m,...n})});var Nt=ht.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:l,workflowConfig:a,currentStep:g}=T(),{formState:c}=useFormContext(),o=useMemo(()=>{let y=c.isSubmitting||l.isSubmitting,d=r??y,h=i.currentStepIndex>0&&!l.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:h}},[c.isSubmitting,l.isSubmitting,l.isTransitioning,i.currentStepIndex,r]),f=useCallback(async y=>{y?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),m=useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:g,stepData:c.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,g,c.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:m,...n})});var _t=ht.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:l,workflowConfig:a,context:g,conditionsHelpers:c}=T(),{formState:o}=useFormContext(),f=useMemo(()=>{let d=o.isSubmitting||l.isSubmitting,h=r??d,x=(!!i?.allowSkip||c.isStepSkippable(l.currentStepIndex))&&!l.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:x}},[o.isSubmitting,l.isSubmitting,l.isTransitioning,l.currentStepIndex,i?.allowSkip,c.isStepSkippable,r]),m=useCallback(async d=>{d?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),y=useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:m,className:e,currentStep:i,stepData:o.values||{},allData:g.allData,context:g}),[f.canSkip,f.finalIsSubmitting,m,e,i,o.values,g.allData,g]);return jsx(ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:y,...n})});var $t=ht.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:l,conditionsHelpers:a}=T(),{visibleSteps:g,visibleToOriginalIndexMap:c,originalToVisibleIndexMap:o}=useMemo(()=>{let d=[],h=new Map,x=new Map;return i.steps.forEach((E,p)=>{if(a.isStepVisible(p)){let b=d.length;d.push(E),h.set(b,p),x.set(p,b);}}),{visibleSteps:d,visibleToOriginalIndexMap:h,originalToVisibleIndexMap:x}},[i.steps,a]),f=useCallback(d=>{let h=c.get(d);h!==void 0&&(e?e(h):l(h));},[c,e,l]),m=useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),y=useMemo(()=>({steps:g,currentStepIndex:m,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[g,m,s.visitedSteps,f,r]);return jsx(ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:y,...n})});var be=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),l=this.compress?this.compressData(s):s;localStorage.setItem(n,l);}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},l=JSON.stringify(s),a=this.compress?this.compressData(l):l;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,l=JSON.parse(s);l.expiresAt&&Date.now()>l.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
|
|
2
|
+
export{be as LocalStorageAdapter,B as RilayLicenseManager,yt as Workflow,xt as WorkflowBody,Rt as WorkflowNextButton,D as WorkflowPersistenceError,Nt as WorkflowPreviousButton,ge as WorkflowProvider,_t as WorkflowSkipButton,$t as WorkflowStepper,le as combineWorkflowDataForConditions,ie as debounce,ae as flattenObject,U as flow,ne as generateStorageKey,nt as mergePersistedState,Le as persistedToWorkflowState,te as useConditionEvaluation,X as usePersistence,it as useStepMetadata,oe as useWorkflowAnalytics,pe as useWorkflowConditions,T as useWorkflowContext,ce as useWorkflowNavigation,de as useWorkflowState,ue as useWorkflowSubmission,rt as validatePersistedData,re as workflowStateToPersisted};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rilaykit/workflow",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "12.0.0",
|
|
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/
|
|
38
|
-
"@rilaykit/
|
|
37
|
+
"@rilaykit/core": "11.0.0",
|
|
38
|
+
"@rilaykit/forms": "11.0.0"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"react": ">=18.0.0",
|