@rilaykit/workflow 9.0.1 → 11.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 CHANGED
@@ -14,6 +14,10 @@ interface WorkflowState {
14
14
  }
15
15
  interface UseWorkflowStateProps {
16
16
  defaultValues?: Record<string, any>;
17
+ defaultStepIndex?: number;
18
+ workflowSteps?: Array<{
19
+ id: string;
20
+ }>;
17
21
  persistence?: {
18
22
  workflowId: string;
19
23
  adapter?: WorkflowPersistenceAdapter;
@@ -22,7 +26,7 @@ interface UseWorkflowStateProps {
22
26
  autoLoad?: boolean;
23
27
  };
24
28
  }
25
- declare function useWorkflowState({ defaultValues, persistence }: UseWorkflowStateProps): {
29
+ declare function useWorkflowState({ defaultValues, defaultStepIndex, workflowSteps, persistence, }: UseWorkflowStateProps): {
26
30
  workflowState: WorkflowState;
27
31
  setCurrentStep: (stepIndex: number) => void;
28
32
  setStepData: (data: Record<string, any>, stepId: string) => void;
@@ -965,11 +969,12 @@ interface WorkflowProviderProps {
965
969
  children: React$1.ReactNode;
966
970
  workflowConfig: WorkflowConfig;
967
971
  defaultValues?: Record<string, any>;
972
+ defaultStep?: string;
968
973
  onStepChange?: (fromStep: number, toStep: number, context: WorkflowContext) => void;
969
974
  onWorkflowComplete?: (data: Record<string, any>) => void | Promise<void>;
970
975
  className?: string;
971
976
  }
972
- declare function WorkflowProvider({ children, workflowConfig, defaultValues, onStepChange, onWorkflowComplete, className, }: WorkflowProviderProps): react_jsx_runtime.JSX.Element;
977
+ declare function WorkflowProvider({ children, workflowConfig, defaultValues, defaultStep, onStepChange, onWorkflowComplete, className, }: WorkflowProviderProps): react_jsx_runtime.JSX.Element;
973
978
  declare function useWorkflowContext(): WorkflowContextValue;
974
979
 
975
980
  type WorkflowProps = Omit<WorkflowProviderProps, 'children' | 'workflowConfig'> & {
@@ -1212,4 +1217,39 @@ declare class RilayLicenseManager {
1212
1217
  }>;
1213
1218
  }
1214
1219
 
1215
- export { type LicensePayload, type LicensePlan, type LicenseResult, LocalStorageAdapter, type LocalStorageAdapterConfig, type PersistedWorkflowData, type PersistenceOptions, RilayLicenseManager, type StepDefinition, type UsePersistenceProps, type UsePersistenceReturn, Workflow, WorkflowBody, type WorkflowContextValue, WorkflowNextButton, type WorkflowPersistenceAdapter, WorkflowPersistenceError, WorkflowPreviousButton, WorkflowProvider, WorkflowSkipButton, WorkflowStepper, debounce, flow, generateStorageKey, mergePersistedState, persistedToWorkflowState, useConditionEvaluation, usePersistence, useStepMetadata, useWorkflowAnalytics, useWorkflowConditions, useWorkflowContext, useWorkflowNavigation, useWorkflowState, useWorkflowSubmission, validatePersistedData, workflowStateToPersisted };
1220
+ /**
1221
+ * Utility functions for handling nested data structures in workflows
1222
+ * and making them compatible with condition evaluation
1223
+ */
1224
+ /**
1225
+ * Flattens a nested object into a flat object with dot-notation keys
1226
+ *
1227
+ * @param obj - The nested object to flatten
1228
+ * @param prefix - The prefix to use for keys (used internally for recursion)
1229
+ * @returns A flattened object with dot-notation keys
1230
+ *
1231
+ * @example
1232
+ * ```typescript
1233
+ * const nested = {
1234
+ * products: { requestedProducts: ['health'] },
1235
+ * user: { profile: { name: 'John' } }
1236
+ * };
1237
+ *
1238
+ * const flat = flattenObject(nested);
1239
+ * // Result: {
1240
+ * // 'products.requestedProducts': ['health'],
1241
+ * // 'user.profile.name': 'John'
1242
+ * // }
1243
+ * ```
1244
+ */
1245
+ declare function flattenObject(obj: Record<string, any>, prefix?: string): Record<string, any>;
1246
+ /**
1247
+ * Combines workflow data from different sources and flattens them for condition evaluation
1248
+ *
1249
+ * @param allData - Global workflow data (usually from defaultValues)
1250
+ * @param stepData - Step-specific data
1251
+ * @returns Combined and flattened data ready for condition evaluation
1252
+ */
1253
+ declare function combineWorkflowDataForConditions(allData: Record<string, any>, stepData: Record<string, any>): Record<string, any>;
1254
+
1255
+ export { type LicensePayload, type LicensePlan, type LicenseResult, LocalStorageAdapter, type LocalStorageAdapterConfig, type PersistedWorkflowData, type PersistenceOptions, RilayLicenseManager, type StepDefinition, type UsePersistenceProps, type UsePersistenceReturn, Workflow, WorkflowBody, type WorkflowContextValue, WorkflowNextButton, type WorkflowPersistenceAdapter, WorkflowPersistenceError, WorkflowPreviousButton, WorkflowProvider, WorkflowSkipButton, WorkflowStepper, combineWorkflowDataForConditions, debounce, flattenObject, flow, generateStorageKey, mergePersistedState, persistedToWorkflowState, useConditionEvaluation, usePersistence, useStepMetadata, useWorkflowAnalytics, useWorkflowConditions, useWorkflowContext, useWorkflowNavigation, useWorkflowState, useWorkflowSubmission, validatePersistedData, workflowStateToPersisted };
package/dist/index.d.ts CHANGED
@@ -14,6 +14,10 @@ interface WorkflowState {
14
14
  }
15
15
  interface UseWorkflowStateProps {
16
16
  defaultValues?: Record<string, any>;
17
+ defaultStepIndex?: number;
18
+ workflowSteps?: Array<{
19
+ id: string;
20
+ }>;
17
21
  persistence?: {
18
22
  workflowId: string;
19
23
  adapter?: WorkflowPersistenceAdapter;
@@ -22,7 +26,7 @@ interface UseWorkflowStateProps {
22
26
  autoLoad?: boolean;
23
27
  };
24
28
  }
25
- declare function useWorkflowState({ defaultValues, persistence }: UseWorkflowStateProps): {
29
+ declare function useWorkflowState({ defaultValues, defaultStepIndex, workflowSteps, persistence, }: UseWorkflowStateProps): {
26
30
  workflowState: WorkflowState;
27
31
  setCurrentStep: (stepIndex: number) => void;
28
32
  setStepData: (data: Record<string, any>, stepId: string) => void;
@@ -965,11 +969,12 @@ interface WorkflowProviderProps {
965
969
  children: React$1.ReactNode;
966
970
  workflowConfig: WorkflowConfig;
967
971
  defaultValues?: Record<string, any>;
972
+ defaultStep?: string;
968
973
  onStepChange?: (fromStep: number, toStep: number, context: WorkflowContext) => void;
969
974
  onWorkflowComplete?: (data: Record<string, any>) => void | Promise<void>;
970
975
  className?: string;
971
976
  }
972
- declare function WorkflowProvider({ children, workflowConfig, defaultValues, onStepChange, onWorkflowComplete, className, }: WorkflowProviderProps): react_jsx_runtime.JSX.Element;
977
+ declare function WorkflowProvider({ children, workflowConfig, defaultValues, defaultStep, onStepChange, onWorkflowComplete, className, }: WorkflowProviderProps): react_jsx_runtime.JSX.Element;
973
978
  declare function useWorkflowContext(): WorkflowContextValue;
974
979
 
975
980
  type WorkflowProps = Omit<WorkflowProviderProps, 'children' | 'workflowConfig'> & {
@@ -1212,4 +1217,39 @@ declare class RilayLicenseManager {
1212
1217
  }>;
1213
1218
  }
1214
1219
 
1215
- export { type LicensePayload, type LicensePlan, type LicenseResult, LocalStorageAdapter, type LocalStorageAdapterConfig, type PersistedWorkflowData, type PersistenceOptions, RilayLicenseManager, type StepDefinition, type UsePersistenceProps, type UsePersistenceReturn, Workflow, WorkflowBody, type WorkflowContextValue, WorkflowNextButton, type WorkflowPersistenceAdapter, WorkflowPersistenceError, WorkflowPreviousButton, WorkflowProvider, WorkflowSkipButton, WorkflowStepper, debounce, flow, generateStorageKey, mergePersistedState, persistedToWorkflowState, useConditionEvaluation, usePersistence, useStepMetadata, useWorkflowAnalytics, useWorkflowConditions, useWorkflowContext, useWorkflowNavigation, useWorkflowState, useWorkflowSubmission, validatePersistedData, workflowStateToPersisted };
1220
+ /**
1221
+ * Utility functions for handling nested data structures in workflows
1222
+ * and making them compatible with condition evaluation
1223
+ */
1224
+ /**
1225
+ * Flattens a nested object into a flat object with dot-notation keys
1226
+ *
1227
+ * @param obj - The nested object to flatten
1228
+ * @param prefix - The prefix to use for keys (used internally for recursion)
1229
+ * @returns A flattened object with dot-notation keys
1230
+ *
1231
+ * @example
1232
+ * ```typescript
1233
+ * const nested = {
1234
+ * products: { requestedProducts: ['health'] },
1235
+ * user: { profile: { name: 'John' } }
1236
+ * };
1237
+ *
1238
+ * const flat = flattenObject(nested);
1239
+ * // Result: {
1240
+ * // 'products.requestedProducts': ['health'],
1241
+ * // 'user.profile.name': 'John'
1242
+ * // }
1243
+ * ```
1244
+ */
1245
+ declare function flattenObject(obj: Record<string, any>, prefix?: string): Record<string, any>;
1246
+ /**
1247
+ * Combines workflow data from different sources and flattens them for condition evaluation
1248
+ *
1249
+ * @param allData - Global workflow data (usually from defaultValues)
1250
+ * @param stepData - Step-specific data
1251
+ * @returns Combined and flattened data ready for condition evaluation
1252
+ */
1253
+ declare function combineWorkflowDataForConditions(allData: Record<string, any>, stepData: Record<string, any>): Record<string, any>;
1254
+
1255
+ export { type LicensePayload, type LicensePlan, type LicenseResult, LocalStorageAdapter, type LocalStorageAdapterConfig, type PersistedWorkflowData, type PersistenceOptions, RilayLicenseManager, type StepDefinition, type UsePersistenceProps, type UsePersistenceReturn, Workflow, WorkflowBody, type WorkflowContextValue, WorkflowNextButton, type WorkflowPersistenceAdapter, WorkflowPersistenceError, WorkflowPreviousButton, WorkflowProvider, WorkflowSkipButton, WorkflowStepper, combineWorkflowDataForConditions, debounce, flattenObject, flow, generateStorageKey, mergePersistedState, persistedToWorkflowState, useConditionEvaluation, usePersistence, useStepMetadata, useWorkflowAnalytics, useWorkflowConditions, useWorkflowContext, useWorkflowNavigation, useWorkflowState, useWorkflowSubmission, validatePersistedData, workflowStateToPersisted };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var core=require('@rilaykit/core'),forms=require('@rilaykit/forms'),mt=require('react'),Pe=require('@noble/ed25519'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var mt__default=/*#__PURE__*/_interopDefault(mt);var Pe__namespace=/*#__PURE__*/_interopNamespace(Pe);var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new core.IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof forms.form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=core.normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=core.deepClone(this.steps),n.analytics=this.analytics?core.deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?core.deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{core.ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(o=>o.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var He=1751361139160,Ze="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,o]=n,a=`${i}.${s}`,c=new TextEncoder().encode(a),l=o.match(/.{2}/g);if(!l)return {valid:!1,error:"INVALID"};let p=new Uint8Array(l.map(W=>Number.parseInt(W,16))),m=k.hexToBytes(Ze);if(!await Pe__namespace.verify(p,c,m))return {valid:!1,error:"SIGNATURE_INVALID"};let S=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(S),u=Math.floor(Date.now()/1e3);return d.e<u?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:He>d.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let o=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),p=o<<18|a<<12|c<<6|l;n+=String.fromCharCode(p>>16&255),c!==64&&(n+=String.fromCharCode(p>>8&255)),l!==64&&(n+=String.fromCharCode(p&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var _=k;function j(t,e={},r={}){return mt.useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,core.evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function We(t,e={}){return mt.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=o=>{try{return o&&typeof o=="object"&&"build"in o?core.evaluateCondition(o.build(),e):core.evaluateCondition(o,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function De(t,e={}){return mt.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let o=a=>{try{return a&&typeof a=="object"&&"build"in a?core.evaluateCondition(a.build(),e):core.evaluateCondition(a,e)}catch(c){return console.warn(`Error evaluating condition for step ${s}:`,c),false}};r[s]={visible:i.visible?o(i.visible):true,disabled:i.disabled?o(i.disabled):false,required:i.required?o(i.required):false,readonly:i.readonly?o(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function ee(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Ee(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function Ye(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function te(t,e){return e?`${e}:${t}`:t}function re(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function Qe(t,e,r="persist"){let n=Ee(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function J({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,o]=mt.useState(false),[a,c]=mt.useState(null),[l,p]=mt.useState(false),m=mt.useRef(r),g=mt.useRef(n),S=mt.useRef({hasPendingChanges:false});mt.useEffect(()=>{m.current=r,g.current=n;},[r,n]);let d=te(g.current.storageKey||t,i),u=mt.useCallback(()=>{c(null);},[]),h=mt.useCallback((b,P)=>{let C=b instanceof D?b:new D(`${P} failed: ${b.message}`,"OPERATION_FAILED",b);c(C),console.error("[WorkflowPersistence]",C);},[]),W=mt.useCallback(async b=>{u(),o(true);try{let P=ee(t,b,g.current.metadata);await m.current.save(d,P),S.current.lastSavedState={...b},S.current.hasPendingChanges=!1;}catch(P){throw h(P,"Save"),P}finally{o(false);}},[t,d,u,h]),y=mt.useRef(re(async b=>{try{await W(b);}catch(P){console.debug("[WorkflowPersistence] Auto-save failed:",P);}},n.debounceMs||500)),x=mt.useCallback((b,P)=>P?b.currentStepIndex!==P.currentStepIndex||JSON.stringify(b.allData)!==JSON.stringify(P.allData)||JSON.stringify(b.stepData)!==JSON.stringify(P.stepData)||b.visitedSteps.size!==P.visitedSteps.size||!Array.from(b.visitedSteps).every(C=>P.visitedSteps.has(C)):true,[]),I=mt.useCallback(async()=>{u(),p(true);try{let b=await m.current.load(d);return b&&(S.current.lastSavedState={currentStepIndex:b.currentStepIndex,allData:b.allData,stepData:b.stepData,visitedSteps:new Set(b.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},S.current.hasPendingChanges=!1),b}catch(b){return h(b,"Load"),null}finally{setTimeout(()=>p(false),100);}},[d,u,h]),E=mt.useCallback(async()=>{u();try{await m.current.remove(d),S.current.lastSavedState=void 0,S.current.hasPendingChanges=!1;}catch(b){throw h(b,"Clear"),b}},[d,u,h]),f=mt.useCallback(async()=>{try{return await m.current.exists(d)}catch(b){return h(b,"Exists check"),false}},[d,h]);mt.useEffect(()=>{g.current.autoPersist&&(s||l||e.isInitializing||e.isSubmitting||e.isTransitioning||x(e,S.current.lastSavedState)&&(S.current.hasPendingChanges=true,y.current(e)));},[e,s,l,x]);let v=mt.useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:I,clearPersistedData:E,hasPersistedData:f}}function je(){let{workflowConfig:t,currentStep:e}=T(),r=mt.useMemo(()=>e?.metadata,[e?.metadata]),n=mt.useMemo(()=>l=>t.steps.find(m=>m.id===l)?.metadata,[t.steps]),i=mt.useMemo(()=>l=>t.steps[l]?.metadata,[t.steps]),s=mt.useMemo(()=>l=>r?l in r:false,[r]),o=mt.useMemo(()=>(l,p)=>r&&l in r?r[l]:p,[r]),a=mt.useMemo(()=>()=>t.steps.map((l,p)=>({id:l.id,title:l.title,index:p,metadata:l.metadata})),[t.steps]),c=mt.useMemo(()=>l=>t.steps.map((p,m)=>({step:p,index:m})).filter(({step:p,index:m})=>l(p.metadata,p.id,m)).map(({step:p})=>p.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:o,getAllStepsMetadata:a,findStepsByMetadata:c}}function ie({workflowConfig:t,workflowState:e,workflowContext:r}){let n=mt.useRef(Date.now()),i=mt.useRef(new Map),s=mt.useRef(false),o=mt.useRef(null),a=core.getGlobalMonitor();mt.useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),mt.useEffect(()=>{let g=t.steps[e.currentStepIndex];if(g&&o.current!==g.id){if(o.current&&t.analytics?.onStepComplete){let S=i.current.get(o.current);if(S){let d=Date.now()-S;t.analytics.onStepComplete(o.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:o.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}o.current=g.id,i.current.set(g.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(g.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:g.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let c=mt.useCallback((g,S)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(g,S,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:g,reason:S},void 0,"medium");},[t.analytics,r,a,t.id]),l=mt.useCallback(g=>{t.analytics?.onError&&t.analytics.onError(g,r),a&&a.trackError(g,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),p=mt.useCallback((g,S,d)=>{if(!a)return;let u={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:S,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:g,toStep:S,direction:S>g?"forward":"backward"},u,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),m=mt.useCallback((g,S)=>{if(!a)return;let d={timestamp:Date.now(),duration:g,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:g};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:S,currentStepIndex:e.currentStepIndex},d,g>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:c,trackError:l,trackNavigation:p,trackConditionEvaluation:m}}function Te(t,e){return {visible:t.visible,skippable:e===true||t.required}}function se({workflowConfig:t,workflowState:e,currentStep:r}){let n=mt.useMemo(()=>({...e.allData,...e.stepData}),[e.allData,e.stepData]),i=mt.useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=j(i,n,{visible:true,disabled:false,required:false,readonly:false}),o=mt.useMemo(()=>Te(s,r?.allowSkip),[s,r?.allowSkip]),a=mt.useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{x.conditions&&(y[I]={visible:x.conditions.visible,required:x.conditions.skippable});}),y},[t.steps]),c=De(a,n),l=mt.useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{let E=c[I];E?y[I]=Te(E,x.allowSkip):y[I]={visible:true,skippable:x.allowSkip===true};}),y},[t.steps,c]),p=mt.useMemo(()=>{if(!r?.formConfig?.allFields)return {};let y={};for(let x of r.formConfig.allFields)x.conditions&&(y[x.id]=x.conditions);return y},[r?.formConfig?.allFields]),m=We(p,n),g=mt.useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.visible??true,[l,t.steps.length]),S=mt.useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.skippable??false,[l,t.steps.length]),d=mt.useCallback(y=>m[y]?.visible??true,[m]),u=mt.useCallback(y=>m[y]?.disabled??false,[m]),h=mt.useCallback(y=>m[y]?.required??false,[m]),W=mt.useCallback(y=>m[y]?.readonly??false,[m]);return {stepConditions:o,fieldConditions:m,allStepConditions:l,isStepVisible:g,isStepSkippable:S,isFieldVisible:d,isFieldDisabled:u,isFieldRequired:h,isFieldReadonly:W}}function oe({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:o,setStepData:a,onStepChange:c}){let l=mt.useRef(c);l.current=c;let p=t.steps[e.currentStepIndex],m=mt.useCallback(()=>({setStepData:(f,v)=>{a(v,f);},setStepFields:(f,v)=>{let P={...e.allData[f]||{},...v};a(P,f);},getStepData:f=>e.allData[f]||{},setNextStepField:(f,v)=>{let b=e.currentStepIndex+1;if(b<t.steps.length){let P=t.steps[b].id,K={...e.allData[P]||{},[f]:v};a(K,P);}},setNextStepFields:f=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let b=t.steps[v].id,C={...e.allData[b]||{},...f};a(C,b);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),g=mt.useCallback(async f=>{if(f<0||f>=t.steps.length||!n.isStepVisible(f))return false;s(true);try{return l.current&&l.current(e.currentStepIndex,f,r),i(f),o(f,t.steps[f].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,o]),S=mt.useCallback(f=>{for(let v=f+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=mt.useCallback(f=>{for(let v=f-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),u=mt.useCallback(async()=>{if(p?.onAfterValidation)try{let v=m();await p.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let f=S(e.currentStepIndex);return f===null?false:g(f)},[p,m,e.stepData,r,t.analytics,e.currentStepIndex,S,g]),h=mt.useCallback(async()=>{let f=d(e.currentStepIndex);return f===null?false:g(f)},[e.currentStepIndex,d,g]),W=mt.useCallback(async()=>!p?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(p.id,"user_skip",r),u()),[p,n,e.currentStepIndex,t.analytics,r,u]),y=mt.useCallback(f=>f<0||f>=t.steps.length?false:n.isStepVisible(f),[t.steps.length,n]),x=mt.useCallback(()=>{let f=S(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,S,y]),I=mt.useCallback(()=>{let f=d(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,d,y]),E=mt.useCallback(()=>p?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[p?.allowSkip,n,e.currentStepIndex]);return {goToStep:g,goNext:u,goPrevious:h,skipStep:W,canGoToStep:y,canGoNext:x,canGoPrevious:I,canSkipCurrentStep:E}}function nt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function ae({defaultValues:t={},persistence:e}){let r={currentStepIndex:0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[n,i]=mt.useReducer(nt,r),s=e?.adapter?J({workflowId:e.workflowId,workflowState:n,adapter:e.adapter,options:e.options,userId:e.userId}):null,o=mt.useCallback(u=>{i({type:"SET_CURRENT_STEP",stepIndex:u});},[]),a=mt.useCallback((u,h)=>{i({type:"SET_STEP_DATA",data:u,stepId:h});},[]),c=mt.useCallback((u,h,W)=>{i({type:"SET_FIELD_VALUE",fieldId:u,value:h,stepId:W});},[]),l=mt.useCallback(u=>{i({type:"SET_SUBMITTING",isSubmitting:u});},[]),p=mt.useCallback(u=>{i({type:"SET_TRANSITIONING",isTransitioning:u});},[]),m=mt.useCallback((u,h)=>{i({type:"MARK_STEP_VISITED",stepIndex:u,stepId:h});},[]),g=mt.useCallback(()=>{i({type:"RESET_WORKFLOW"});},[]),S=mt.useCallback(()=>{i({type:"SET_INITIALIZATION_COMPLETE"});},[]),d=mt.useCallback(async()=>{if(!s)return S(),false;try{let u=await s.loadPersistedData();if(u){let h={currentStepIndex:u.currentStepIndex,allData:u.allData,stepData:u.stepData,visitedSteps:new Set(u.visitedSteps)};return i({type:"LOAD_PERSISTED_STATE",state:h}),S(),!0}}catch(u){console.error("Failed to load persisted state:",u);}return S(),false},[s,S]);return {workflowState:n,setCurrentStep:o,setStepData:a,setFieldValue:c,setSubmitting:l,setTransitioning:p,markStepVisited:m,resetWorkflow:g,loadPersistedState:d,persistence:s?{isPersisting:s.isPersisting,persistenceError:s.persistenceError,persistNow:s.persistNow,clearPersistedData:s.clearPersistedData,hasPersistedData:s.hasPersistedData}:null}}function le({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let o=mt.useRef(i);o.current=i;let a=mt.useCallback(async()=>{n(true);try{if(o.current&&await o.current(e.allData),t.analytics?.onWorkflowComplete){let l=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,l,e.allData);}}catch(l){throw console.error("Workflow submission failed:",l),t.analytics?.onError&&t.analytics.onError(l,r),l}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),c=mt.useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:c()}}var Me=mt.createContext(null);function ce({children:t,workflowConfig:e,defaultValues:r={},onStepChange:n,onWorkflowComplete:i,className:s}){let o=mt.useRef(n),a=mt.useRef(i);o.current=n,a.current=i;let{workflowState:c,setCurrentStep:l,setStepData:p,setFieldValue:m,setSubmitting:g,setTransitioning:S,markStepVisited:d,resetWorkflow:u,loadPersistedState:h,persistence:W}=ae({defaultValues:r,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});mt.useEffect(()=>{e.persistence&&h&&h();},[]);let y=mt.useMemo(()=>({isPersisting:W?.isPersisting??false,persistenceError:W?.persistenceError??null,persistNow:W?.persistNow}),[W?.isPersisting,W?.persistenceError,W?.persistNow]),x=mt.useMemo(()=>({workflowId:e.id,currentStepIndex:c.currentStepIndex,totalSteps:e.steps.length,allData:c.allData,stepData:c.stepData,visitedSteps:c.visitedSteps}),[e.id,e.steps.length,c.currentStepIndex,c.allData,c.stepData,c.visitedSteps]),I=mt.useMemo(()=>e.steps[c.currentStepIndex],[e.steps,c.currentStepIndex]),E=mt.useMemo(()=>I?.formConfig,[I?.formConfig]),f=se({workflowConfig:e,workflowState:c,currentStep:I}),v=mt.useMemo(()=>{let w=-1;for(let A=0;A<e.steps.length;A++)if(f.isStepVisible(A)){w=A;break}let R=-1;for(let A=e.steps.length-1;A>=0;A--)if(f.isStepVisible(A)){R=A;break}return {...x,isFirstStep:c.currentStepIndex===w,isLastStep:c.currentStepIndex===R}},[x,c.currentStepIndex,f,e.steps.length]),{analyticsStartTime:b}=ie({workflowConfig:e,workflowState:c,workflowContext:v}),{goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}=oe({workflowConfig:e,workflowState:c,workflowContext:v,conditionsHelpers:f,setCurrentStep:l,setTransitioning:S,markStepVisited:d,setStepData:p,onStepChange:o.current});mt.useEffect(()=>{if(!f.isStepVisible(c.currentStepIndex)){for(let R=0;R<e.steps.length;R++)if(f.isStepVisible(R)){l(R),d(R,e.steps[R].id);break}}},[f,c.currentStepIndex,e.steps,l,d]);let{submitWorkflow:$,isSubmitting:be,canSubmit:ve}=le({workflowConfig:e,workflowState:c,workflowContext:v,setSubmitting:g,onWorkflowComplete:a.current,analyticsStartTime:b}),Z=mt.useCallback((w,R)=>{m(w,R,I?.id||"");},[m,I?.id]),he=mt.useCallback(w=>{p(w,I?.id||"");},[p,I?.id]),Oe=mt.useCallback(async w=>{I?.id&&w&&p(w,I.id),v.isLastStep?await $():await C();},[v.isLastStep,$,C,I?.id,p]),xe=mt.useMemo(()=>({goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}),[P,C,K,fe,me,Se,ge,ye]),ke=mt.useMemo(()=>({setValue:Z,setStepData:he,resetWorkflow:u}),[Z,he,u]),Ie=mt.useMemo(()=>({submitWorkflow:$,isSubmitting:be,canSubmit:ve}),[$,be,ve]),Ue=mt.useMemo(()=>({workflowState:c,workflowConfig:e,currentStep:I,context:v,formConfig:E,conditionsHelpers:f,currentStepMetadata:I?.metadata,...xe,...ke,...Ie,persistNow:y.persistNow,isPersisting:y.isPersisting,persistenceError:y.persistenceError}),[c,e,I,v,E,f,xe,ke,Ie,y]),Ge=mt.useMemo(()=>{if(!I?.id)return {};let w=c?.allData[I.id]||{};if(!E?.allFields)return w;let R=new Set(E.allFields.map(q=>q.id)),A={};for(let[q,$e]of Object.entries(w))R.has(q)&&(A[q]=$e);return A},[c?.allData,I?.id,E?.allFields]),Ke=mt.useMemo(()=>c.isInitializing.toString(),[c.isInitializing]);return jsxRuntime.jsx(Me.Provider,{value:Ue,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:E,defaultValues:Ge,onFieldChange:Z,"data-workflow-id":e.id,className:s,onSubmit:Oe,children:t},Ke)})}function T(){let t=mt.useContext(Me);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function dt({children:t,workflowConfig:e,...r}){let[n,i]=mt.useState(),s=mt.useMemo(()=>e instanceof U?e.build():e,[e]);return mt.useEffect(()=>{if(typeof window<"u"&&_.shouldDisplayWatermark()){let a=_.getWatermarkMessage();i(a);}},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(ce,{...r,workflowConfig:s,children:t}),n&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var St=mt__default.default.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsxRuntime.jsx(forms.FormBody,{}):null});var xt=mt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:o,currentStep:a}=T(),{submit:c,formState:l}=forms.useFormContext(),p=mt.useMemo(()=>{let S=l.isSubmitting||s.isSubmitting,d=r??S,u=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:u}},[l.isSubmitting,s.isSubmitting,s.isTransitioning,r]),m=mt.useCallback(async S=>{S?.preventDefault(),p.canGoNext&&await c(S);},[p.canGoNext,c]),g=mt.useMemo(()=>({isLastStep:i.isLastStep,canGoNext:p.canGoNext,isSubmitting:p.finalIsSubmitting,onSubmit:m,className:e,currentStep:a,stepData:l.values||{},allData:i.allData,context:i}),[i.isLastStep,p.canGoNext,p.finalIsSubmitting,m,e,a,l.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:o.renderConfig?.nextButtonRenderer,props:g,...n})});var Et=mt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:o,workflowConfig:a,currentStep:c}=T(),{formState:l}=forms.useFormContext(),p=mt.useMemo(()=>{let S=l.isSubmitting||o.isSubmitting,d=r??S,u=i.currentStepIndex>0&&!o.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:u}},[l.isSubmitting,o.isSubmitting,o.isTransitioning,i.currentStepIndex,r]),m=mt.useCallback(async S=>{S?.preventDefault(),p.canGoPrevious&&await s();},[p.canGoPrevious,s]),g=mt.useMemo(()=>({canGoPrevious:p.canGoPrevious,isSubmitting:p.finalIsSubmitting,onPrevious:m,className:e,currentStep:c,stepData:l.values||{},allData:i.allData,context:i}),[p.canGoPrevious,p.finalIsSubmitting,m,e,c,l.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:g,...n})});var Nt=mt__default.default.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:o,workflowConfig:a,context:c,conditionsHelpers:l}=T(),{formState:p}=forms.useFormContext(),m=mt.useMemo(()=>{let d=p.isSubmitting||o.isSubmitting,u=r??d,h=(!!i?.allowSkip||l.isStepSkippable(o.currentStepIndex))&&!o.isTransitioning&&!u;return {finalIsSubmitting:u,canSkip:h}},[p.isSubmitting,o.isSubmitting,o.isTransitioning,o.currentStepIndex,i?.allowSkip,l.isStepSkippable,r]),g=mt.useCallback(async d=>{d?.preventDefault(),m.canSkip&&await s();},[m.canSkip,s]),S=mt.useMemo(()=>({canSkip:m.canSkip,isSubmitting:m.finalIsSubmitting,onSkip:g,className:e,currentStep:i,stepData:p.values||{},allData:c.allData,context:c}),[m.canSkip,m.finalIsSubmitting,g,e,i,p.values,c.allData,c]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:S,...n})});var _t=mt__default.default.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:o,conditionsHelpers:a}=T(),{visibleSteps:c,visibleToOriginalIndexMap:l,originalToVisibleIndexMap:p}=mt.useMemo(()=>{let d=[],u=new Map,h=new Map;return i.steps.forEach((W,y)=>{if(a.isStepVisible(y)){let x=d.length;d.push(W),u.set(x,y),h.set(y,x);}}),{visibleSteps:d,visibleToOriginalIndexMap:u,originalToVisibleIndexMap:h}},[i.steps,a]),m=mt.useCallback(d=>{let u=l.get(d);u!==void 0&&(e?e(u):o(u));},[l,e,o]),g=mt.useMemo(()=>p.get(s.currentStepIndex)??-1,[p,s.currentStepIndex]),S=mt.useMemo(()=>({steps:c,currentStepIndex:g,visitedSteps:s.visitedSteps,onStepClick:m,className:r}),[c,g,s.visitedSteps,m,r]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:S,...n})});var ue=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),o=this.compress?this.compressData(s):s;localStorage.setItem(n,o);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},o=JSON.stringify(s),a=this.compress?this.compressData(o):o;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,o=JSON.parse(s);o.expiresAt&&Date.now()>o.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
2
- exports.LocalStorageAdapter=ue;exports.RilayLicenseManager=_;exports.Workflow=dt;exports.WorkflowBody=St;exports.WorkflowNextButton=xt;exports.WorkflowPersistenceError=D;exports.WorkflowPreviousButton=Et;exports.WorkflowProvider=ce;exports.WorkflowSkipButton=Nt;exports.WorkflowStepper=_t;exports.debounce=re;exports.flow=U;exports.generateStorageKey=te;exports.mergePersistedState=Qe;exports.persistedToWorkflowState=Ee;exports.useConditionEvaluation=j;exports.usePersistence=J;exports.useStepMetadata=je;exports.useWorkflowAnalytics=ie;exports.useWorkflowConditions=se;exports.useWorkflowContext=T;exports.useWorkflowNavigation=oe;exports.useWorkflowState=ae;exports.useWorkflowSubmission=le;exports.validatePersistedData=Ye;exports.workflowStateToPersisted=ee;
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 mt,{createContext,useMemo,useCallback,useContext,useState,useRef,useEffect,useReducer}from'react';import*as Pe from'@noble/ed25519';import {jsx,jsxs}from'react/jsx-runtime';var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=deepClone(this.steps),n.analytics=this.analytics?deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(o=>o.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var He=1751361139160,Ze="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,o]=n,a=`${i}.${s}`,c=new TextEncoder().encode(a),l=o.match(/.{2}/g);if(!l)return {valid:!1,error:"INVALID"};let p=new Uint8Array(l.map(W=>Number.parseInt(W,16))),m=k.hexToBytes(Ze);if(!await Pe.verify(p,c,m))return {valid:!1,error:"SIGNATURE_INVALID"};let S=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(S),u=Math.floor(Date.now()/1e3);return d.e<u?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:He>d.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let o=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),l=r.indexOf(s.charAt(i++)),p=o<<18|a<<12|c<<6|l;n+=String.fromCharCode(p>>16&255),c!==64&&(n+=String.fromCharCode(p>>8&255)),l!==64&&(n+=String.fromCharCode(p&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var _=k;function j(t,e={},r={}){return useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function We(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=o=>{try{return o&&typeof o=="object"&&"build"in o?evaluateCondition(o.build(),e):evaluateCondition(o,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function De(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let o=a=>{try{return a&&typeof a=="object"&&"build"in a?evaluateCondition(a.build(),e):evaluateCondition(a,e)}catch(c){return console.warn(`Error evaluating condition for step ${s}:`,c),false}};r[s]={visible:i.visible?o(i.visible):true,disabled:i.disabled?o(i.disabled):false,required:i.required?o(i.required):false,readonly:i.readonly?o(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function ee(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Ee(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function Ye(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function te(t,e){return e?`${e}:${t}`:t}function re(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function Qe(t,e,r="persist"){let n=Ee(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function J({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,o]=useState(false),[a,c]=useState(null),[l,p]=useState(false),m=useRef(r),g=useRef(n),S=useRef({hasPendingChanges:false});useEffect(()=>{m.current=r,g.current=n;},[r,n]);let d=te(g.current.storageKey||t,i),u=useCallback(()=>{c(null);},[]),h=useCallback((b,P)=>{let C=b instanceof D?b:new D(`${P} failed: ${b.message}`,"OPERATION_FAILED",b);c(C),console.error("[WorkflowPersistence]",C);},[]),W=useCallback(async b=>{u(),o(true);try{let P=ee(t,b,g.current.metadata);await m.current.save(d,P),S.current.lastSavedState={...b},S.current.hasPendingChanges=!1;}catch(P){throw h(P,"Save"),P}finally{o(false);}},[t,d,u,h]),y=useRef(re(async b=>{try{await W(b);}catch(P){console.debug("[WorkflowPersistence] Auto-save failed:",P);}},n.debounceMs||500)),x=useCallback((b,P)=>P?b.currentStepIndex!==P.currentStepIndex||JSON.stringify(b.allData)!==JSON.stringify(P.allData)||JSON.stringify(b.stepData)!==JSON.stringify(P.stepData)||b.visitedSteps.size!==P.visitedSteps.size||!Array.from(b.visitedSteps).every(C=>P.visitedSteps.has(C)):true,[]),I=useCallback(async()=>{u(),p(true);try{let b=await m.current.load(d);return b&&(S.current.lastSavedState={currentStepIndex:b.currentStepIndex,allData:b.allData,stepData:b.stepData,visitedSteps:new Set(b.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},S.current.hasPendingChanges=!1),b}catch(b){return h(b,"Load"),null}finally{setTimeout(()=>p(false),100);}},[d,u,h]),E=useCallback(async()=>{u();try{await m.current.remove(d),S.current.lastSavedState=void 0,S.current.hasPendingChanges=!1;}catch(b){throw h(b,"Clear"),b}},[d,u,h]),f=useCallback(async()=>{try{return await m.current.exists(d)}catch(b){return h(b,"Exists check"),false}},[d,h]);useEffect(()=>{g.current.autoPersist&&(s||l||e.isInitializing||e.isSubmitting||e.isTransitioning||x(e,S.current.lastSavedState)&&(S.current.hasPendingChanges=true,y.current(e)));},[e,s,l,x]);let v=useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:I,clearPersistedData:E,hasPersistedData:f}}function je(){let{workflowConfig:t,currentStep:e}=T(),r=useMemo(()=>e?.metadata,[e?.metadata]),n=useMemo(()=>l=>t.steps.find(m=>m.id===l)?.metadata,[t.steps]),i=useMemo(()=>l=>t.steps[l]?.metadata,[t.steps]),s=useMemo(()=>l=>r?l in r:false,[r]),o=useMemo(()=>(l,p)=>r&&l in r?r[l]:p,[r]),a=useMemo(()=>()=>t.steps.map((l,p)=>({id:l.id,title:l.title,index:p,metadata:l.metadata})),[t.steps]),c=useMemo(()=>l=>t.steps.map((p,m)=>({step:p,index:m})).filter(({step:p,index:m})=>l(p.metadata,p.id,m)).map(({step:p})=>p.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:o,getAllStepsMetadata:a,findStepsByMetadata:c}}function ie({workflowConfig:t,workflowState:e,workflowContext:r}){let n=useRef(Date.now()),i=useRef(new Map),s=useRef(false),o=useRef(null),a=getGlobalMonitor();useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),useEffect(()=>{let g=t.steps[e.currentStepIndex];if(g&&o.current!==g.id){if(o.current&&t.analytics?.onStepComplete){let S=i.current.get(o.current);if(S){let d=Date.now()-S;t.analytics.onStepComplete(o.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:o.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}o.current=g.id,i.current.set(g.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(g.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:g.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let c=useCallback((g,S)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(g,S,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:g,reason:S},void 0,"medium");},[t.analytics,r,a,t.id]),l=useCallback(g=>{t.analytics?.onError&&t.analytics.onError(g,r),a&&a.trackError(g,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),p=useCallback((g,S,d)=>{if(!a)return;let u={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:S,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:g,toStep:S,direction:S>g?"forward":"backward"},u,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),m=useCallback((g,S)=>{if(!a)return;let d={timestamp:Date.now(),duration:g,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:g};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:S,currentStepIndex:e.currentStepIndex},d,g>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:c,trackError:l,trackNavigation:p,trackConditionEvaluation:m}}function Te(t,e){return {visible:t.visible,skippable:e===true||t.required}}function se({workflowConfig:t,workflowState:e,currentStep:r}){let n=useMemo(()=>({...e.allData,...e.stepData}),[e.allData,e.stepData]),i=useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=j(i,n,{visible:true,disabled:false,required:false,readonly:false}),o=useMemo(()=>Te(s,r?.allowSkip),[s,r?.allowSkip]),a=useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{x.conditions&&(y[I]={visible:x.conditions.visible,required:x.conditions.skippable});}),y},[t.steps]),c=De(a,n),l=useMemo(()=>{let y={};return t.steps.forEach((x,I)=>{let E=c[I];E?y[I]=Te(E,x.allowSkip):y[I]={visible:true,skippable:x.allowSkip===true};}),y},[t.steps,c]),p=useMemo(()=>{if(!r?.formConfig?.allFields)return {};let y={};for(let x of r.formConfig.allFields)x.conditions&&(y[x.id]=x.conditions);return y},[r?.formConfig?.allFields]),m=We(p,n),g=useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.visible??true,[l,t.steps.length]),S=useCallback(y=>y<0||y>=t.steps.length?false:l[y]?.skippable??false,[l,t.steps.length]),d=useCallback(y=>m[y]?.visible??true,[m]),u=useCallback(y=>m[y]?.disabled??false,[m]),h=useCallback(y=>m[y]?.required??false,[m]),W=useCallback(y=>m[y]?.readonly??false,[m]);return {stepConditions:o,fieldConditions:m,allStepConditions:l,isStepVisible:g,isStepSkippable:S,isFieldVisible:d,isFieldDisabled:u,isFieldRequired:h,isFieldReadonly:W}}function oe({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:o,setStepData:a,onStepChange:c}){let l=useRef(c);l.current=c;let p=t.steps[e.currentStepIndex],m=useCallback(()=>({setStepData:(f,v)=>{a(v,f);},setStepFields:(f,v)=>{let P={...e.allData[f]||{},...v};a(P,f);},getStepData:f=>e.allData[f]||{},setNextStepField:(f,v)=>{let b=e.currentStepIndex+1;if(b<t.steps.length){let P=t.steps[b].id,K={...e.allData[P]||{},[f]:v};a(K,P);}},setNextStepFields:f=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let b=t.steps[v].id,C={...e.allData[b]||{},...f};a(C,b);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),g=useCallback(async f=>{if(f<0||f>=t.steps.length||!n.isStepVisible(f))return false;s(true);try{return l.current&&l.current(e.currentStepIndex,f,r),i(f),o(f,t.steps[f].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,o]),S=useCallback(f=>{for(let v=f+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=useCallback(f=>{for(let v=f-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),u=useCallback(async()=>{if(p?.onAfterValidation)try{let v=m();await p.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let f=S(e.currentStepIndex);return f===null?false:g(f)},[p,m,e.stepData,r,t.analytics,e.currentStepIndex,S,g]),h=useCallback(async()=>{let f=d(e.currentStepIndex);return f===null?false:g(f)},[e.currentStepIndex,d,g]),W=useCallback(async()=>!p?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(p.id,"user_skip",r),u()),[p,n,e.currentStepIndex,t.analytics,r,u]),y=useCallback(f=>f<0||f>=t.steps.length?false:n.isStepVisible(f),[t.steps.length,n]),x=useCallback(()=>{let f=S(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,S,y]),I=useCallback(()=>{let f=d(e.currentStepIndex);return f!==null&&y(f)},[e.currentStepIndex,d,y]),E=useCallback(()=>p?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[p?.allowSkip,n,e.currentStepIndex]);return {goToStep:g,goNext:u,goPrevious:h,skipStep:W,canGoToStep:y,canGoNext:x,canGoPrevious:I,canSkipCurrentStep:E}}function nt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function ae({defaultValues:t={},persistence:e}){let r={currentStepIndex:0,allData:t,stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:true},[n,i]=useReducer(nt,r),s=e?.adapter?J({workflowId:e.workflowId,workflowState:n,adapter:e.adapter,options:e.options,userId:e.userId}):null,o=useCallback(u=>{i({type:"SET_CURRENT_STEP",stepIndex:u});},[]),a=useCallback((u,h)=>{i({type:"SET_STEP_DATA",data:u,stepId:h});},[]),c=useCallback((u,h,W)=>{i({type:"SET_FIELD_VALUE",fieldId:u,value:h,stepId:W});},[]),l=useCallback(u=>{i({type:"SET_SUBMITTING",isSubmitting:u});},[]),p=useCallback(u=>{i({type:"SET_TRANSITIONING",isTransitioning:u});},[]),m=useCallback((u,h)=>{i({type:"MARK_STEP_VISITED",stepIndex:u,stepId:h});},[]),g=useCallback(()=>{i({type:"RESET_WORKFLOW"});},[]),S=useCallback(()=>{i({type:"SET_INITIALIZATION_COMPLETE"});},[]),d=useCallback(async()=>{if(!s)return S(),false;try{let u=await s.loadPersistedData();if(u){let h={currentStepIndex:u.currentStepIndex,allData:u.allData,stepData:u.stepData,visitedSteps:new Set(u.visitedSteps)};return i({type:"LOAD_PERSISTED_STATE",state:h}),S(),!0}}catch(u){console.error("Failed to load persisted state:",u);}return S(),false},[s,S]);return {workflowState:n,setCurrentStep:o,setStepData:a,setFieldValue:c,setSubmitting:l,setTransitioning:p,markStepVisited:m,resetWorkflow:g,loadPersistedState:d,persistence:s?{isPersisting:s.isPersisting,persistenceError:s.persistenceError,persistNow:s.persistNow,clearPersistedData:s.clearPersistedData,hasPersistedData:s.hasPersistedData}:null}}function le({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let o=useRef(i);o.current=i;let a=useCallback(async()=>{n(true);try{if(o.current&&await o.current(e.allData),t.analytics?.onWorkflowComplete){let l=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,l,e.allData);}}catch(l){throw console.error("Workflow submission failed:",l),t.analytics?.onError&&t.analytics.onError(l,r),l}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),c=useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:c()}}var Me=createContext(null);function ce({children:t,workflowConfig:e,defaultValues:r={},onStepChange:n,onWorkflowComplete:i,className:s}){let o=useRef(n),a=useRef(i);o.current=n,a.current=i;let{workflowState:c,setCurrentStep:l,setStepData:p,setFieldValue:m,setSubmitting:g,setTransitioning:S,markStepVisited:d,resetWorkflow:u,loadPersistedState:h,persistence:W}=ae({defaultValues:r,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});useEffect(()=>{e.persistence&&h&&h();},[]);let y=useMemo(()=>({isPersisting:W?.isPersisting??false,persistenceError:W?.persistenceError??null,persistNow:W?.persistNow}),[W?.isPersisting,W?.persistenceError,W?.persistNow]),x=useMemo(()=>({workflowId:e.id,currentStepIndex:c.currentStepIndex,totalSteps:e.steps.length,allData:c.allData,stepData:c.stepData,visitedSteps:c.visitedSteps}),[e.id,e.steps.length,c.currentStepIndex,c.allData,c.stepData,c.visitedSteps]),I=useMemo(()=>e.steps[c.currentStepIndex],[e.steps,c.currentStepIndex]),E=useMemo(()=>I?.formConfig,[I?.formConfig]),f=se({workflowConfig:e,workflowState:c,currentStep:I}),v=useMemo(()=>{let w=-1;for(let A=0;A<e.steps.length;A++)if(f.isStepVisible(A)){w=A;break}let R=-1;for(let A=e.steps.length-1;A>=0;A--)if(f.isStepVisible(A)){R=A;break}return {...x,isFirstStep:c.currentStepIndex===w,isLastStep:c.currentStepIndex===R}},[x,c.currentStepIndex,f,e.steps.length]),{analyticsStartTime:b}=ie({workflowConfig:e,workflowState:c,workflowContext:v}),{goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}=oe({workflowConfig:e,workflowState:c,workflowContext:v,conditionsHelpers:f,setCurrentStep:l,setTransitioning:S,markStepVisited:d,setStepData:p,onStepChange:o.current});useEffect(()=>{if(!f.isStepVisible(c.currentStepIndex)){for(let R=0;R<e.steps.length;R++)if(f.isStepVisible(R)){l(R),d(R,e.steps[R].id);break}}},[f,c.currentStepIndex,e.steps,l,d]);let{submitWorkflow:$,isSubmitting:be,canSubmit:ve}=le({workflowConfig:e,workflowState:c,workflowContext:v,setSubmitting:g,onWorkflowComplete:a.current,analyticsStartTime:b}),Z=useCallback((w,R)=>{m(w,R,I?.id||"");},[m,I?.id]),he=useCallback(w=>{p(w,I?.id||"");},[p,I?.id]),Oe=useCallback(async w=>{I?.id&&w&&p(w,I.id),v.isLastStep?await $():await C();},[v.isLastStep,$,C,I?.id,p]),xe=useMemo(()=>({goToStep:P,goNext:C,goPrevious:K,skipStep:fe,canGoToStep:me,canGoNext:Se,canGoPrevious:ge,canSkipCurrentStep:ye}),[P,C,K,fe,me,Se,ge,ye]),ke=useMemo(()=>({setValue:Z,setStepData:he,resetWorkflow:u}),[Z,he,u]),Ie=useMemo(()=>({submitWorkflow:$,isSubmitting:be,canSubmit:ve}),[$,be,ve]),Ue=useMemo(()=>({workflowState:c,workflowConfig:e,currentStep:I,context:v,formConfig:E,conditionsHelpers:f,currentStepMetadata:I?.metadata,...xe,...ke,...Ie,persistNow:y.persistNow,isPersisting:y.isPersisting,persistenceError:y.persistenceError}),[c,e,I,v,E,f,xe,ke,Ie,y]),Ge=useMemo(()=>{if(!I?.id)return {};let w=c?.allData[I.id]||{};if(!E?.allFields)return w;let R=new Set(E.allFields.map(q=>q.id)),A={};for(let[q,$e]of Object.entries(w))R.has(q)&&(A[q]=$e);return A},[c?.allData,I?.id,E?.allFields]),Ke=useMemo(()=>c.isInitializing.toString(),[c.isInitializing]);return jsx(Me.Provider,{value:Ue,children:jsx(FormProvider,{formConfig:E,defaultValues:Ge,onFieldChange:Z,"data-workflow-id":e.id,className:s,onSubmit:Oe,children:t},Ke)})}function T(){let t=useContext(Me);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function dt({children:t,workflowConfig:e,...r}){let[n,i]=useState(),s=useMemo(()=>e instanceof U?e.build():e,[e]);return useEffect(()=>{if(typeof window<"u"&&_.shouldDisplayWatermark()){let a=_.getWatermarkMessage();i(a);}},[]),jsxs("div",{style:{position:"relative"},children:[jsx(ce,{...r,workflowConfig:s,children:t}),n&&jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var St=mt.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsx(FormBody,{}):null});var xt=mt.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:o,currentStep:a}=T(),{submit:c,formState:l}=useFormContext(),p=useMemo(()=>{let S=l.isSubmitting||s.isSubmitting,d=r??S,u=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:u}},[l.isSubmitting,s.isSubmitting,s.isTransitioning,r]),m=useCallback(async S=>{S?.preventDefault(),p.canGoNext&&await c(S);},[p.canGoNext,c]),g=useMemo(()=>({isLastStep:i.isLastStep,canGoNext:p.canGoNext,isSubmitting:p.finalIsSubmitting,onSubmit:m,className:e,currentStep:a,stepData:l.values||{},allData:i.allData,context:i}),[i.isLastStep,p.canGoNext,p.finalIsSubmitting,m,e,a,l.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:o.renderConfig?.nextButtonRenderer,props:g,...n})});var Et=mt.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:o,workflowConfig:a,currentStep:c}=T(),{formState:l}=useFormContext(),p=useMemo(()=>{let S=l.isSubmitting||o.isSubmitting,d=r??S,u=i.currentStepIndex>0&&!o.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:u}},[l.isSubmitting,o.isSubmitting,o.isTransitioning,i.currentStepIndex,r]),m=useCallback(async S=>{S?.preventDefault(),p.canGoPrevious&&await s();},[p.canGoPrevious,s]),g=useMemo(()=>({canGoPrevious:p.canGoPrevious,isSubmitting:p.finalIsSubmitting,onPrevious:m,className:e,currentStep:c,stepData:l.values||{},allData:i.allData,context:i}),[p.canGoPrevious,p.finalIsSubmitting,m,e,c,l.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:g,...n})});var Nt=mt.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:o,workflowConfig:a,context:c,conditionsHelpers:l}=T(),{formState:p}=useFormContext(),m=useMemo(()=>{let d=p.isSubmitting||o.isSubmitting,u=r??d,h=(!!i?.allowSkip||l.isStepSkippable(o.currentStepIndex))&&!o.isTransitioning&&!u;return {finalIsSubmitting:u,canSkip:h}},[p.isSubmitting,o.isSubmitting,o.isTransitioning,o.currentStepIndex,i?.allowSkip,l.isStepSkippable,r]),g=useCallback(async d=>{d?.preventDefault(),m.canSkip&&await s();},[m.canSkip,s]),S=useMemo(()=>({canSkip:m.canSkip,isSubmitting:m.finalIsSubmitting,onSkip:g,className:e,currentStep:i,stepData:p.values||{},allData:c.allData,context:c}),[m.canSkip,m.finalIsSubmitting,g,e,i,p.values,c.allData,c]);return jsx(ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:S,...n})});var _t=mt.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:o,conditionsHelpers:a}=T(),{visibleSteps:c,visibleToOriginalIndexMap:l,originalToVisibleIndexMap:p}=useMemo(()=>{let d=[],u=new Map,h=new Map;return i.steps.forEach((W,y)=>{if(a.isStepVisible(y)){let x=d.length;d.push(W),u.set(x,y),h.set(y,x);}}),{visibleSteps:d,visibleToOriginalIndexMap:u,originalToVisibleIndexMap:h}},[i.steps,a]),m=useCallback(d=>{let u=l.get(d);u!==void 0&&(e?e(u):o(u));},[l,e,o]),g=useMemo(()=>p.get(s.currentStepIndex)??-1,[p,s.currentStepIndex]),S=useMemo(()=>({steps:c,currentStepIndex:g,visitedSteps:s.visitedSteps,onStepClick:m,className:r}),[c,g,s.visitedSteps,m,r]);return jsx(ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:S,...n})});var ue=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),o=this.compress?this.compressData(s):s;localStorage.setItem(n,o);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},o=JSON.stringify(s),a=this.compress?this.compressData(o):o;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,o=JSON.parse(s);o.expiresAt&&Date.now()>o.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
2
- export{ue as LocalStorageAdapter,_ as RilayLicenseManager,dt as Workflow,St as WorkflowBody,xt as WorkflowNextButton,D as WorkflowPersistenceError,Et as WorkflowPreviousButton,ce as WorkflowProvider,Nt as WorkflowSkipButton,_t as WorkflowStepper,re as debounce,U as flow,te as generateStorageKey,Qe as mergePersistedState,Ee as persistedToWorkflowState,j as useConditionEvaluation,J as usePersistence,je as useStepMetadata,ie as useWorkflowAnalytics,se as useWorkflowConditions,T as useWorkflowContext,oe as useWorkflowNavigation,ae as useWorkflowState,le as useWorkflowSubmission,Ye as validatePersistedData,ee as workflowStateToPersisted};
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": "9.0.1",
3
+ "version": "11.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/core": "9.0.1",
38
- "@rilaykit/forms": "9.0.1"
37
+ "@rilaykit/core": "10.0.0",
38
+ "@rilaykit/forms": "10.0.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "react": ">=18.0.0",