@rilaykit/workflow 1.1.0 → 2.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 +178 -258
- package/dist/index.d.ts +178 -258
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,127 @@
|
|
|
1
|
-
import
|
|
2
|
-
import * as react from 'react';
|
|
3
|
-
import react__default from 'react';
|
|
4
|
-
import { WorkflowConfig, WorkflowContext, ValidationError, StepConfig, FormConfiguration, ValidationResult, ril, StepLifecycleHooks, StepPermissions, CustomStepRenderer, DynamicStepConfig, ConditionalBranch, NavigationConfig, PersistenceConfig, WorkflowAnalytics, WorkflowOptimizations, WorkflowVersion, CompletionConfig, WorkflowPlugin } from '@rilaykit/core';
|
|
1
|
+
import { ril, FormConfiguration, StepLifecycleHooks, StepPermissions, CustomStepRenderer, DynamicStepConfig, NavigationConfig, PersistenceConfig, WorkflowAnalytics, CompletionConfig, WorkflowPlugin, StepConfig, WorkflowConfig, WorkflowContext, ValidationError, ValidationResult, RendererChildrenFunction, WorkflowNextButtonRendererProps, WorkflowPreviousButtonRendererProps, WorkflowSkipButtonRendererProps, WorkflowStepperRendererProps } from '@rilaykit/core';
|
|
5
2
|
export * from '@rilaykit/core';
|
|
6
3
|
export { createZodValidator, ril } from '@rilaykit/core';
|
|
4
|
+
import { form } from '@rilaykit/forms';
|
|
7
5
|
export { form } from '@rilaykit/forms';
|
|
6
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
7
|
+
import * as react from 'react';
|
|
8
|
+
import react__default from 'react';
|
|
9
|
+
|
|
10
|
+
interface StepDefinition {
|
|
11
|
+
id: string;
|
|
12
|
+
title: string;
|
|
13
|
+
description?: string;
|
|
14
|
+
formConfig: FormConfiguration | form;
|
|
15
|
+
allowSkip?: boolean;
|
|
16
|
+
requiredToComplete?: boolean;
|
|
17
|
+
hooks?: StepLifecycleHooks;
|
|
18
|
+
permissions?: StepPermissions;
|
|
19
|
+
renderer?: CustomStepRenderer;
|
|
20
|
+
dynamicConfig?: DynamicStepConfig;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Workflow builder class for creating complex multi-step workflows
|
|
24
|
+
* Simplified API with auto-build capability
|
|
25
|
+
*/
|
|
26
|
+
declare class flow {
|
|
27
|
+
private config;
|
|
28
|
+
private workflowId;
|
|
29
|
+
private workflowName;
|
|
30
|
+
private workflowDescription?;
|
|
31
|
+
private steps;
|
|
32
|
+
private navigation;
|
|
33
|
+
private persistence?;
|
|
34
|
+
private completion?;
|
|
35
|
+
private analytics?;
|
|
36
|
+
private plugins;
|
|
37
|
+
constructor(config: ril, workflowId: string, workflowName: string, description?: string);
|
|
38
|
+
static create(config: ril, workflowId: string, workflowName: string, description?: string): flow;
|
|
39
|
+
/**
|
|
40
|
+
* Helper method to create a step configuration from StepDefinition
|
|
41
|
+
*/
|
|
42
|
+
private createStepFromDefinition;
|
|
43
|
+
/**
|
|
44
|
+
* Add a step using simplified StepDefinition object
|
|
45
|
+
*/
|
|
46
|
+
addStep(stepDefinition: StepDefinition): this;
|
|
47
|
+
/**
|
|
48
|
+
* Add a dynamic step using StepDefinition with dynamicConfig
|
|
49
|
+
*/
|
|
50
|
+
addDynamicStep(stepDefinition: StepDefinition & {
|
|
51
|
+
dynamicConfig: DynamicStepConfig;
|
|
52
|
+
}): this;
|
|
53
|
+
/**
|
|
54
|
+
* Add multiple steps at once
|
|
55
|
+
*/
|
|
56
|
+
addSteps(stepDefinitions: StepDefinition[]): this;
|
|
57
|
+
/**
|
|
58
|
+
* Configuration setters with fluent interface
|
|
59
|
+
*/
|
|
60
|
+
setNavigation(navigation: NavigationConfig): this;
|
|
61
|
+
enableBackNavigation(enabled?: boolean): this;
|
|
62
|
+
enableStepSkipping(enabled?: boolean): this;
|
|
63
|
+
setPersistence(persistence: PersistenceConfig): this;
|
|
64
|
+
setAnalytics(analytics: WorkflowAnalytics): this;
|
|
65
|
+
setCompletion(completion: CompletionConfig): this;
|
|
66
|
+
/**
|
|
67
|
+
* Plugin management
|
|
68
|
+
*/
|
|
69
|
+
use(plugin: WorkflowPlugin): this;
|
|
70
|
+
private validatePluginDependencies;
|
|
71
|
+
removePlugin(pluginName: string): this;
|
|
72
|
+
/**
|
|
73
|
+
* Step management
|
|
74
|
+
*/
|
|
75
|
+
updateStep(stepId: string, updates: Partial<Omit<StepConfig, 'id'>>): this;
|
|
76
|
+
removeStep(stepId: string): this;
|
|
77
|
+
getStep(stepId: string): StepConfig | undefined;
|
|
78
|
+
getSteps(): StepConfig[];
|
|
79
|
+
clearSteps(): this;
|
|
80
|
+
/**
|
|
81
|
+
* Clone the workflow builder
|
|
82
|
+
*/
|
|
83
|
+
clone(newWorkflowId?: string, newWorkflowName?: string): flow;
|
|
84
|
+
/**
|
|
85
|
+
* Validate the workflow configuration
|
|
86
|
+
*/
|
|
87
|
+
validate(): string[];
|
|
88
|
+
/**
|
|
89
|
+
* Get workflow statistics
|
|
90
|
+
*/
|
|
91
|
+
getStats(): {
|
|
92
|
+
totalSteps: number;
|
|
93
|
+
dynamicSteps: number;
|
|
94
|
+
pluginsInstalled: number;
|
|
95
|
+
estimatedFields: number;
|
|
96
|
+
hasPersistence: boolean;
|
|
97
|
+
hasAnalytics: boolean;
|
|
98
|
+
allowBackNavigation: boolean;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Build the final workflow configuration
|
|
102
|
+
*/
|
|
103
|
+
build(): WorkflowConfig;
|
|
104
|
+
/**
|
|
105
|
+
* Export/Import functionality
|
|
106
|
+
*/
|
|
107
|
+
toJSON(): any;
|
|
108
|
+
fromJSON(json: any): this;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Factory function to create a workflow builder directly
|
|
112
|
+
*/
|
|
113
|
+
declare function createFlow(config: ril, workflowId: string, workflowName: string, description?: string): flow;
|
|
114
|
+
declare module '@rilaykit/core' {
|
|
115
|
+
interface ril {
|
|
116
|
+
createFlow(workflowId: string, workflowName: string, description?: string): flow;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
8
119
|
|
|
9
120
|
interface WorkflowState {
|
|
10
121
|
currentStepIndex: number;
|
|
11
122
|
allData: Record<string, any>;
|
|
12
123
|
stepData: Record<string, any>;
|
|
13
124
|
errors: Record<string, ValidationError[]>;
|
|
14
|
-
warnings: Record<string, ValidationError[]>;
|
|
15
125
|
touched: Set<string>;
|
|
16
126
|
isValidating: Set<string>;
|
|
17
127
|
visitedSteps: Set<string>;
|
|
@@ -48,16 +158,20 @@ interface WorkflowProviderProps {
|
|
|
48
158
|
className?: string;
|
|
49
159
|
user?: any;
|
|
50
160
|
}
|
|
161
|
+
declare function WorkflowProvider({ children, workflowConfig, defaultValues, onStepChange, onWorkflowComplete, className, user, }: WorkflowProviderProps): react_jsx_runtime.JSX.Element;
|
|
162
|
+
declare function useWorkflowContext(): WorkflowContextValue;
|
|
51
163
|
|
|
52
|
-
type WorkflowProps = Omit<WorkflowProviderProps, 'children'> & {
|
|
164
|
+
type WorkflowProps = Omit<WorkflowProviderProps, 'children' | 'workflowConfig'> & {
|
|
53
165
|
children: react__default.ReactNode;
|
|
166
|
+
workflowConfig: WorkflowConfig | flow;
|
|
54
167
|
};
|
|
55
168
|
/**
|
|
56
169
|
* A wrapper component for the Rilay workflow system.
|
|
57
170
|
* It simplifies the API by wrapping the WorkflowProvider and providing a clean,
|
|
58
171
|
* component-based interface for building workflows.
|
|
172
|
+
* Accepts both WorkflowConfig and flow builder instances.
|
|
59
173
|
*/
|
|
60
|
-
declare function Workflow({ children, ...props }: WorkflowProps): react_jsx_runtime.JSX.Element;
|
|
174
|
+
declare function Workflow({ children, workflowConfig, ...props }: WorkflowProps): react_jsx_runtime.JSX.Element;
|
|
61
175
|
|
|
62
176
|
/**
|
|
63
177
|
* Renders the main content of the current workflow step.
|
|
@@ -65,232 +179,101 @@ declare function Workflow({ children, ...props }: WorkflowProps): react_jsx_runt
|
|
|
65
179
|
*/
|
|
66
180
|
declare function WorkflowBody(): react_jsx_runtime.JSX.Element | null;
|
|
67
181
|
|
|
68
|
-
interface WorkflowNavigationProps {
|
|
69
|
-
className?: string;
|
|
70
|
-
}
|
|
71
|
-
declare function WorkflowNavigation({ className }: WorkflowNavigationProps): react_jsx_runtime.JSX.Element;
|
|
72
|
-
|
|
73
182
|
interface WorkflowNextButtonProps {
|
|
74
183
|
className?: string;
|
|
75
|
-
children?: React.ReactNode
|
|
184
|
+
children?: React.ReactNode | RendererChildrenFunction<WorkflowNextButtonRendererProps>;
|
|
185
|
+
renderAs?: 'default' | 'children' | boolean;
|
|
76
186
|
}
|
|
77
|
-
declare function WorkflowNextButton({ className, children }: WorkflowNextButtonProps): react.
|
|
187
|
+
declare function WorkflowNextButton({ className, children, renderAs }: WorkflowNextButtonProps): react.ReactNode;
|
|
78
188
|
|
|
79
189
|
interface WorkflowPreviousButtonProps {
|
|
80
190
|
className?: string;
|
|
81
|
-
children?: React.ReactNode
|
|
191
|
+
children?: React.ReactNode | RendererChildrenFunction<WorkflowPreviousButtonRendererProps>;
|
|
192
|
+
renderAs?: 'default' | 'children' | boolean;
|
|
82
193
|
}
|
|
83
|
-
declare function WorkflowPreviousButton({ className, children }: WorkflowPreviousButtonProps): react.
|
|
194
|
+
declare function WorkflowPreviousButton({ className, children, renderAs, }: WorkflowPreviousButtonProps): react.ReactNode;
|
|
84
195
|
|
|
85
196
|
interface WorkflowSkipButtonProps {
|
|
86
197
|
className?: string;
|
|
87
|
-
children?: React.ReactNode
|
|
198
|
+
children?: React.ReactNode | RendererChildrenFunction<WorkflowSkipButtonRendererProps>;
|
|
199
|
+
renderAs?: 'default' | 'children' | boolean;
|
|
88
200
|
}
|
|
89
|
-
declare function WorkflowSkipButton({ className, children }: WorkflowSkipButtonProps): react.
|
|
201
|
+
declare function WorkflowSkipButton({ className, children, renderAs }: WorkflowSkipButtonProps): react.ReactNode;
|
|
90
202
|
|
|
91
203
|
interface WorkflowStepperProps {
|
|
92
204
|
onStepClick?: (stepIndex: number) => void;
|
|
93
205
|
className?: string;
|
|
206
|
+
children?: React.ReactNode | RendererChildrenFunction<WorkflowStepperRendererProps>;
|
|
207
|
+
renderAs?: 'default' | 'children' | boolean;
|
|
208
|
+
}
|
|
209
|
+
declare function WorkflowStepper({ onStepClick, className, children, renderAs, }: WorkflowStepperProps): react.ReactNode;
|
|
210
|
+
|
|
211
|
+
interface LicensePayload {
|
|
212
|
+
plan: 'ARCHITECT' | 'FOUNDRY';
|
|
213
|
+
company: string;
|
|
214
|
+
customerId: string;
|
|
215
|
+
expiry: number;
|
|
216
|
+
iat: number;
|
|
217
|
+
}
|
|
218
|
+
interface LicenseResult {
|
|
219
|
+
valid: boolean;
|
|
220
|
+
data?: LicensePayload;
|
|
221
|
+
error?: 'EXPIRED' | 'INVALID' | 'MISSING' | 'FORMAT_INVALID' | 'SIGNATURE_INVALID';
|
|
94
222
|
}
|
|
95
|
-
|
|
223
|
+
type LicensePlan = 'ARCHITECT' | 'FOUNDRY';
|
|
96
224
|
|
|
97
225
|
/**
|
|
98
|
-
*
|
|
99
|
-
*
|
|
226
|
+
* Enhanced Rilay License Manager with Ed25519 cryptographic validation
|
|
227
|
+
* Uses @noble/ed25519 for secure and fast signature verification
|
|
100
228
|
*/
|
|
101
|
-
declare class
|
|
102
|
-
private
|
|
103
|
-
private
|
|
104
|
-
private
|
|
105
|
-
private workflowDescription?;
|
|
106
|
-
private steps;
|
|
107
|
-
private branches;
|
|
108
|
-
private navigation;
|
|
109
|
-
private persistence?;
|
|
110
|
-
private completion?;
|
|
111
|
-
private analytics?;
|
|
112
|
-
private optimizations?;
|
|
113
|
-
private version?;
|
|
114
|
-
private plugins;
|
|
115
|
-
constructor(config: ril, workflowId: string, workflowName: string, description?: string);
|
|
116
|
-
static create(config: ril, workflowId: string, workflowName: string, description?: string): flow;
|
|
117
|
-
/**
|
|
118
|
-
* Add a standard step to the workflow
|
|
119
|
-
* @param stepId - Unique step identifier
|
|
120
|
-
* @param title - Step title
|
|
121
|
-
* @param formConfig - Complete form configuration for this step
|
|
122
|
-
* @param options - Additional step options
|
|
123
|
-
* @returns flow instance for chaining
|
|
124
|
-
*/
|
|
125
|
-
addStep(stepId: string, title: string, formConfig: FormConfiguration, options?: {
|
|
126
|
-
description?: string;
|
|
127
|
-
allowSkip?: boolean;
|
|
128
|
-
requiredToComplete?: boolean;
|
|
129
|
-
hooks?: StepLifecycleHooks;
|
|
130
|
-
permissions?: StepPermissions;
|
|
131
|
-
renderer?: CustomStepRenderer;
|
|
132
|
-
}): this;
|
|
133
|
-
/**
|
|
134
|
-
* Add a dynamic step that resolves form config based on previous data
|
|
135
|
-
* @param stepId - Unique step identifier
|
|
136
|
-
* @param title - Step title
|
|
137
|
-
* @param dynamicConfig - Configuration for dynamic step resolution
|
|
138
|
-
* @param fallbackFormConfig - Fallback form configuration if dynamic resolution fails
|
|
139
|
-
* @param options - Additional step options
|
|
140
|
-
* @returns flow instance for chaining
|
|
141
|
-
*/
|
|
142
|
-
addDynamicStep(stepId: string, title: string, dynamicConfig: DynamicStepConfig, fallbackFormConfig: FormConfiguration, options?: {
|
|
143
|
-
description?: string;
|
|
144
|
-
allowSkip?: boolean;
|
|
145
|
-
requiredToComplete?: boolean;
|
|
146
|
-
hooks?: StepLifecycleHooks;
|
|
147
|
-
permissions?: StepPermissions;
|
|
148
|
-
}): this;
|
|
149
|
-
/**
|
|
150
|
-
* Add multiple steps at once
|
|
151
|
-
* @param stepConfigs - Array of step configurations
|
|
152
|
-
* @returns flow instance for chaining
|
|
153
|
-
*/
|
|
154
|
-
addSteps(stepConfigs: Array<{
|
|
155
|
-
stepId: string;
|
|
156
|
-
title: string;
|
|
157
|
-
formConfig: FormConfiguration;
|
|
158
|
-
description?: string;
|
|
159
|
-
allowSkip?: boolean;
|
|
160
|
-
requiredToComplete?: boolean;
|
|
161
|
-
hooks?: StepLifecycleHooks;
|
|
162
|
-
permissions?: StepPermissions;
|
|
163
|
-
}>): this;
|
|
164
|
-
/**
|
|
165
|
-
* Add a conditional branch to the workflow
|
|
166
|
-
* @param branch - Conditional branch configuration
|
|
167
|
-
* @returns flow instance for chaining
|
|
168
|
-
*/
|
|
169
|
-
addConditionalBranch(branch: ConditionalBranch): this;
|
|
170
|
-
/**
|
|
171
|
-
* Add multiple conditional branches
|
|
172
|
-
* @param branches - Array of conditional branches
|
|
173
|
-
* @returns flow instance for chaining
|
|
174
|
-
*/
|
|
175
|
-
addConditionalBranches(branches: ConditionalBranch[]): this;
|
|
176
|
-
/**
|
|
177
|
-
* Set navigation configuration
|
|
178
|
-
* @param navigation - Navigation configuration
|
|
179
|
-
* @returns flow instance for chaining
|
|
180
|
-
*/
|
|
181
|
-
setNavigation(navigation: NavigationConfig): this;
|
|
182
|
-
/**
|
|
183
|
-
* Set persistence strategy
|
|
184
|
-
* @param persistence - Persistence configuration
|
|
185
|
-
* @returns flow instance for chaining
|
|
186
|
-
*/
|
|
187
|
-
setPersistence(persistence: PersistenceConfig): this;
|
|
188
|
-
/**
|
|
189
|
-
* Set analytics configuration
|
|
190
|
-
* @param analytics - Analytics configuration
|
|
191
|
-
* @returns flow instance for chaining
|
|
192
|
-
*/
|
|
193
|
-
setAnalytics(analytics: WorkflowAnalytics): this;
|
|
194
|
-
/**
|
|
195
|
-
* Set performance optimizations
|
|
196
|
-
* @param optimizations - Optimization configuration
|
|
197
|
-
* @returns flow instance for chaining
|
|
198
|
-
*/
|
|
199
|
-
setOptimizations(optimizations: WorkflowOptimizations): this;
|
|
200
|
-
/**
|
|
201
|
-
* Set workflow version
|
|
202
|
-
* @param version - Version configuration
|
|
203
|
-
* @returns flow instance for chaining
|
|
204
|
-
*/
|
|
205
|
-
setVersion(version: WorkflowVersion): this;
|
|
206
|
-
/**
|
|
207
|
-
* Set completion configuration
|
|
208
|
-
* @param completion - Completion configuration
|
|
209
|
-
* @returns flow instance for chaining
|
|
210
|
-
*/
|
|
211
|
-
setCompletion(completion: CompletionConfig): this;
|
|
212
|
-
/**
|
|
213
|
-
* Add a plugin to the workflow
|
|
214
|
-
* @param plugin - Plugin to add
|
|
215
|
-
* @returns flow instance for chaining
|
|
216
|
-
*/
|
|
217
|
-
use(plugin: WorkflowPlugin): this;
|
|
218
|
-
/**
|
|
219
|
-
* Remove a plugin from the workflow
|
|
220
|
-
* @param pluginName - Name of the plugin to remove
|
|
221
|
-
* @returns flow instance for chaining
|
|
222
|
-
*/
|
|
223
|
-
removePlugin(pluginName: string): this;
|
|
224
|
-
/**
|
|
225
|
-
* Update step configuration
|
|
226
|
-
* @param stepId - Step identifier
|
|
227
|
-
* @param updates - Updates to apply
|
|
228
|
-
* @returns flow instance for chaining
|
|
229
|
-
*/
|
|
230
|
-
updateStep(stepId: string, updates: Partial<Omit<StepConfig, 'id'>>): this;
|
|
229
|
+
declare class RilayLicenseManager {
|
|
230
|
+
private static licenseKey;
|
|
231
|
+
private static licenseResult;
|
|
232
|
+
private static isInitialized;
|
|
231
233
|
/**
|
|
232
|
-
*
|
|
233
|
-
* @param stepId - Step identifier
|
|
234
|
-
* @returns flow instance for chaining
|
|
234
|
+
* Initialize with a license key and Ed25519 public key
|
|
235
235
|
*/
|
|
236
|
-
|
|
236
|
+
static setLicenseKey(licenseKey?: string): Promise<void>;
|
|
237
237
|
/**
|
|
238
|
-
*
|
|
239
|
-
* @param stepId - Step identifier
|
|
240
|
-
* @returns Step configuration or undefined
|
|
238
|
+
* Validate license using Ed25519 signature verification
|
|
241
239
|
*/
|
|
242
|
-
|
|
240
|
+
private static validateLicense;
|
|
243
241
|
/**
|
|
244
|
-
*
|
|
245
|
-
* @returns Array of step configurations
|
|
242
|
+
* Convert compressed payload to full payload
|
|
246
243
|
*/
|
|
247
|
-
|
|
244
|
+
private static decompressPayload;
|
|
248
245
|
/**
|
|
249
|
-
*
|
|
250
|
-
* @returns flow instance for chaining
|
|
246
|
+
* Convert hex string to Uint8Array
|
|
251
247
|
*/
|
|
252
|
-
|
|
248
|
+
private static hexToBytes;
|
|
253
249
|
/**
|
|
254
|
-
*
|
|
255
|
-
* @param newWorkflowId - ID for the cloned workflow
|
|
256
|
-
* @param newWorkflowName - Name for the cloned workflow
|
|
257
|
-
* @returns New flow instance
|
|
250
|
+
* Convert base64 string to text (browser-compatible)
|
|
258
251
|
*/
|
|
259
|
-
|
|
252
|
+
private static base64ToString;
|
|
260
253
|
/**
|
|
261
|
-
*
|
|
262
|
-
* @returns Array of validation errors
|
|
254
|
+
* Get license validation result
|
|
263
255
|
*/
|
|
264
|
-
|
|
256
|
+
static getLicenseResult(): LicenseResult;
|
|
265
257
|
/**
|
|
266
|
-
*
|
|
267
|
-
* @returns Object with workflow statistics
|
|
258
|
+
* Check if watermark should be displayed
|
|
268
259
|
*/
|
|
269
|
-
|
|
270
|
-
totalSteps: number;
|
|
271
|
-
dynamicSteps: number;
|
|
272
|
-
conditionalBranches: number;
|
|
273
|
-
pluginsInstalled: number;
|
|
274
|
-
estimatedFields: number;
|
|
275
|
-
hasPersistence: boolean;
|
|
276
|
-
hasAnalytics: boolean;
|
|
277
|
-
};
|
|
260
|
+
static shouldDisplayWatermark(): boolean;
|
|
278
261
|
/**
|
|
279
|
-
*
|
|
280
|
-
* @returns Complete workflow configuration
|
|
262
|
+
* Get watermark message
|
|
281
263
|
*/
|
|
282
|
-
|
|
264
|
+
static getWatermarkMessage(): string;
|
|
283
265
|
/**
|
|
284
|
-
*
|
|
285
|
-
* @returns JSON representation of the workflow
|
|
266
|
+
* Display license status in console
|
|
286
267
|
*/
|
|
287
|
-
|
|
268
|
+
static logLicenseStatus(): void;
|
|
288
269
|
/**
|
|
289
|
-
*
|
|
290
|
-
* @param json - JSON representation of the workflow
|
|
291
|
-
* @returns flow instance for chaining
|
|
270
|
+
* Get license info
|
|
292
271
|
*/
|
|
293
|
-
|
|
272
|
+
static getLicenseInfo(): Promise<{
|
|
273
|
+
plan?: string;
|
|
274
|
+
company?: string;
|
|
275
|
+
expiryDate?: string;
|
|
276
|
+
}>;
|
|
294
277
|
}
|
|
295
278
|
|
|
296
279
|
interface AnalyticsPluginConfig {
|
|
@@ -382,67 +365,4 @@ declare class ValidationPlugin implements WorkflowPlugin {
|
|
|
382
365
|
private validateAsync;
|
|
383
366
|
}
|
|
384
367
|
|
|
385
|
-
|
|
386
|
-
plan: 'ARCHITECT' | 'FOUNDRY';
|
|
387
|
-
company: string;
|
|
388
|
-
customerId: string;
|
|
389
|
-
expiry: number;
|
|
390
|
-
iat: number;
|
|
391
|
-
}
|
|
392
|
-
interface LicenseResult {
|
|
393
|
-
valid: boolean;
|
|
394
|
-
data?: LicensePayload;
|
|
395
|
-
error?: 'EXPIRED' | 'INVALID' | 'MISSING' | 'FORMAT_INVALID' | 'SIGNATURE_INVALID';
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
/**
|
|
399
|
-
* Enhanced Rilay License Manager with Ed25519 cryptographic validation
|
|
400
|
-
* Uses @noble/ed25519 for secure and fast signature verification
|
|
401
|
-
*/
|
|
402
|
-
declare class RilayLicenseManager {
|
|
403
|
-
private static licenseKey;
|
|
404
|
-
private static licenseResult;
|
|
405
|
-
private static isInitialized;
|
|
406
|
-
/**
|
|
407
|
-
* Initialize with a license key and Ed25519 public key
|
|
408
|
-
*/
|
|
409
|
-
static setLicenseKey(licenseKey?: string): Promise<void>;
|
|
410
|
-
/**
|
|
411
|
-
* Validate license using Ed25519 signature verification
|
|
412
|
-
*/
|
|
413
|
-
private static validateLicense;
|
|
414
|
-
/**
|
|
415
|
-
* Convert compressed payload to full payload
|
|
416
|
-
*/
|
|
417
|
-
private static decompressPayload;
|
|
418
|
-
/**
|
|
419
|
-
* Convert hex string to Uint8Array
|
|
420
|
-
*/
|
|
421
|
-
private static hexToBytes;
|
|
422
|
-
/**
|
|
423
|
-
* Get license validation result
|
|
424
|
-
*/
|
|
425
|
-
static getLicenseResult(): LicenseResult;
|
|
426
|
-
/**
|
|
427
|
-
* Check if watermark should be displayed
|
|
428
|
-
*/
|
|
429
|
-
static shouldDisplayWatermark(): boolean;
|
|
430
|
-
/**
|
|
431
|
-
* Get watermark message
|
|
432
|
-
*/
|
|
433
|
-
static getWatermarkMessage(): string;
|
|
434
|
-
/**
|
|
435
|
-
* Display license status in console
|
|
436
|
-
*/
|
|
437
|
-
static logLicenseStatus(): void;
|
|
438
|
-
/**
|
|
439
|
-
* Get license info
|
|
440
|
-
*/
|
|
441
|
-
static getLicenseInfo(): Promise<{
|
|
442
|
-
plan?: string;
|
|
443
|
-
company?: string;
|
|
444
|
-
expiryDate?: string;
|
|
445
|
-
}>;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
export { AnalyticsPlugin, RilayLicenseManager, ValidationPlugin, Workflow, WorkflowBody, flow as WorkflowBuilder, type WorkflowContextValue, WorkflowNavigation, type WorkflowNavigationProps, WorkflowNextButton, type WorkflowNextButtonProps, WorkflowPreviousButton, type WorkflowPreviousButtonProps, type WorkflowProviderProps, WorkflowSkipButton, type WorkflowSkipButtonProps, WorkflowStepper, type WorkflowStepperProps, flow };
|
|
368
|
+
export { AnalyticsPlugin, type LicensePayload, type LicensePlan, type LicenseResult, RilayLicenseManager, type StepDefinition, ValidationPlugin, Workflow, WorkflowBody, type WorkflowContextValue, WorkflowNextButton, type WorkflowNextButtonProps, WorkflowPreviousButton, type WorkflowPreviousButtonProps, WorkflowProvider, type WorkflowProviderProps, WorkflowSkipButton, type WorkflowSkipButtonProps, WorkflowStepper, type WorkflowStepperProps, createFlow, flow, useWorkflowContext };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var react=require('react'),X=require('@noble/ed25519'),forms=require('@rilaykit/forms'),jsxRuntime=require('react/jsx-runtime'),core=require('@rilaykit/core');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 X__namespace=/*#__PURE__*/_interopNamespace(X);var ie=1751361139160,ne="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",f=class f{static async setLicenseKey(e){f.licenseKey=e||"",f.licenseKey?f.licenseResult=await f.validateLicense():f.licenseResult={valid:false,error:"MISSING"},f.isInitialized=true;}static async validateLicense(){if(!f.licenseKey)return {valid:false,error:"MISSING"};try{if(!f.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=f.licenseKey.slice(4),t=Buffer.from(e,"base64").toString().split(".");if(t.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[r,n,l]=t,i=`${r}.${n}`,p=new TextEncoder().encode(i),m=l.match(/.{2}/g);if(!m)return {valid:!1,error:"INVALID"};let h=new Uint8Array(m.map(u=>Number.parseInt(u,16))),E=f.hexToBytes(ne);if(!await X__namespace.verify(h,p,E))return {valid:!1,error:"SIGNATURE_INVALID"};let v=Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString(),w=JSON.parse(v),C=Math.floor(Date.now()/1e3);return w.e<C?{valid:!1,error:"EXPIRED",data:f.decompressPayload(w)}:ie>w.e*1e3?{valid:!1,error:"EXPIRED",data:f.decompressPayload(w)}:w.p===void 0||!w.c||!w.i||!w.e||!w.t?{valid:!1,error:"INVALID"}:{valid:!0,data:f.decompressPayload(w)}}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 o=new Uint8Array(e.length/2);for(let t=0;t<e.length;t+=2)o[t/2]=Number.parseInt(e.substring(t,t+2),16);return o}static getLicenseResult(){return f.isInitialized?f.licenseResult?f.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!f.getLicenseResult().valid}static getWatermarkMessage(){let e=f.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=f.getLicenseResult();if(e.valid)return;let t={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${t}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=f.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};f.licenseKey="",f.licenseResult=null,f.isInitialized=false;var x=f;function pe(a,e){switch(e.type){case "SET_CURRENT_STEP":return {...a,currentStepIndex:e.stepIndex,stepData:a.allData[a.resolvedSteps[e.stepIndex]?.id]||{}};case "SET_STEP_DATA":{let o=a.resolvedSteps[a.currentStepIndex]?.id;return {...a,stepData:e.data,allData:{...a.allData,[o]:e.data}}}case "SET_ALL_DATA":return {...a,allData:e.data};case "SET_FIELD_VALUE":{let o=a.resolvedSteps[a.currentStepIndex]?.id,t={...a.stepData,[e.fieldId]:e.value};return {...a,stepData:t,allData:{...a.allData,[o]:t}}}case "SET_ERROR":return {...a,errors:{...a.errors,[e.fieldId]:e.errors}};case "SET_WARNING":return {...a,warnings:{...a.warnings,[e.fieldId]:e.warnings}};case "CLEAR_ERROR":{let o={...a.errors};return delete o[e.fieldId],{...a,errors:o}}case "CLEAR_WARNING":{let o={...a.warnings};return delete o[e.fieldId],{...a,warnings:o}}case "MARK_TOUCHED":return {...a,touched:new Set([...a.touched,e.fieldId])};case "SET_VALIDATING":{let o=new Set(a.isValidating);return e.isValidating?o.add(e.fieldId):o.delete(e.fieldId),{...a,isValidating:o}}case "SET_SUBMITTING":return {...a,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...a,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...a,visitedSteps:new Set([...a.visitedSteps,a.resolvedSteps[e.stepIndex]?.id])};case "SET_PERSISTED_DATA":return {...a,persistedData:e.data};case "SET_RESOLVED_STEPS":return {...a,resolvedSteps:e.steps};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},errors:{},warnings:{},touched:new Set,isValidating:new Set,visitedSteps:new Set,isSubmitting:false,isTransitioning:false,resolvedSteps:a.resolvedSteps};default:return a}}var Z=react.createContext(null);function j({children:a,workflowConfig:e,defaultValues:o={},onStepChange:t,onWorkflowComplete:r,className:n,user:l}){let[i,p]=react.useReducer(pe,{currentStepIndex:0,allData:o,stepData:{},errors:{},warnings:{},touched:new Set,isValidating:new Set,visitedSteps:new Set,isSubmitting:false,isTransitioning:false,resolvedSteps:e.steps}),m=react.useRef(null),h=react.useRef(Date.now()),E=react.useRef(new Map),k=react.useRef(false),v=react.useRef(null),w=react.useRef(t),C=react.useRef(r);w.current=t,C.current=r;let s=react.useMemo(()=>e,[e]),u=react.useMemo(()=>({workflowId:s.id,currentStepIndex:i.currentStepIndex,totalSteps:i.resolvedSteps.length,allData:i.allData,stepData:i.stepData,isFirstStep:i.currentStepIndex===0,isLastStep:i.currentStepIndex===i.resolvedSteps.length-1,visitedSteps:i.visitedSteps,user:l}),[s.id,i.currentStepIndex,i.resolvedSteps.length,i.allData,i.stepData,i.visitedSteps,l]);react.useEffect(()=>{(async()=>{let d=[];for(let g of s.steps)if(g.isDynamic&&g.dynamicConfig)try{let V=await g.dynamicConfig.resolver(i.allData,u);d.push(...V);}catch(V){console.error(`Failed to resolve dynamic step "${g.id}":`,V),d.push({...g,isDynamic:false});}else d.push(g);p({type:"SET_RESOLVED_STEPS",steps:d});})();},[s.steps,i.allData,u]),react.useEffect(()=>{s.analytics?.onWorkflowStart&&!k.current&&(k.current=true,s.analytics.onWorkflowStart(s.id,u));},[s.id,s.analytics,u]),react.useEffect(()=>{let c=i.resolvedSteps[i.currentStepIndex];if(c&&v.current!==c.id){if(v.current&&s.analytics?.onStepComplete){let d=E.current.get(v.current);d&&s.analytics.onStepComplete(v.current,Date.now()-d,i.stepData,u);}v.current=c.id,E.current.set(c.id,Date.now()),s.analytics?.onStepStart&&s.analytics.onStepStart(c.id,Date.now(),u);}},[i.currentStepIndex,i.resolvedSteps,s.analytics,u]);let S=react.useCallback(async()=>{if(s.persistence)try{let c={workflowId:s.id,currentStepIndex:i.currentStepIndex,allData:i.allData,metadata:{timestamp:Date.now(),version:"1.0.0",userId:l?.id,sessionId:crypto.randomUUID()}},d=s.persistence.key||`workflow-${s.id}`;await s.persistence.adapter.save(d,c),s.persistence.onSave&&await s.persistence.onSave(c);}catch(c){console.error("Failed to save workflow draft:",c),s.persistence.onError&&await s.persistence.onError(c,"save");}},[s,i.currentStepIndex,i.allData,l]),G=react.useCallback(async()=>{if(s.persistence)try{let c=s.persistence.key||`workflow-${s.id}`,d=await s.persistence.adapter.load(c);d&&d.workflowId===s.id&&(p({type:"SET_ALL_DATA",data:d.allData}),p({type:"SET_CURRENT_STEP",stepIndex:d.currentStepIndex}),p({type:"SET_PERSISTED_DATA",data:d}),s.persistence.onLoad&&await s.persistence.onLoad(d));}catch(c){console.error("Failed to load workflow draft:",c),s.persistence.onError&&await s.persistence.onError(c,"load");}},[s]),b=react.useCallback(async()=>{if(s.persistence)try{let c=s.persistence.key||`workflow-${s.id}`;await s.persistence.adapter.remove(c);}catch(c){console.error("Failed to clear workflow draft:",c),s.persistence.onError&&await s.persistence.onError(c,"remove");}},[s]);react.useEffect(()=>{s.persistence&&(async()=>{try{let d=s.persistence.key||`workflow-${s.id}`,g=await s.persistence.adapter.load(d);g&&g.workflowId===s.id&&(p({type:"SET_ALL_DATA",data:g.allData}),p({type:"SET_CURRENT_STEP",stepIndex:g.currentStepIndex}),p({type:"SET_PERSISTED_DATA",data:g}),s.persistence.onLoad&&await s.persistence.onLoad(g),console.log("Workflow data loaded from persistence:",g));}catch(d){console.error("Failed to load workflow draft on mount:",d),s.persistence.onError&&await s.persistence.onError(d,"load");}})();},[s.id]),react.useEffect(()=>{if(s.persistence?.saveOnStepChange)return m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{S();},s.persistence.debounceMs||1e3),()=>{m.current&&clearTimeout(m.current);}},[i.allData,S,s.persistence]);let R=react.useMemo(()=>i.resolvedSteps[i.currentStepIndex],[i.resolvedSteps,i.currentStepIndex]),U=react.useMemo(()=>R?.formConfig,[R]),P=react.useCallback(async c=>{if(c<0||c>=i.resolvedSteps.length)return false;let d=i.resolvedSteps[c];if(d.permissions)try{if(!(d.permissions.customGuard?await d.permissions.customGuard(l,u):!0))return console.warn(`Access denied to step "${d.id}"`),!1}catch(g){return console.error(`Permission check failed for step "${d.id}":`,g),false}if(d.hooks?.onBeforeEnter)try{await d.hooks.onBeforeEnter(i.stepData,i.allData,u);}catch(g){return console.error(`onBeforeEnter hook failed for step "${d.id}":`,g),s.analytics?.onError&&s.analytics.onError(g,u),false}p({type:"SET_TRANSITIONING",isTransitioning:true});try{return w.current&&w.current(i.currentStepIndex,c,u),p({type:"SET_CURRENT_STEP",stepIndex:c}),p({type:"MARK_STEP_VISITED",stepIndex:c}),!0}catch(g){return console.error("Step transition failed:",g),s.analytics?.onError&&s.analytics.onError(g,u),false}finally{p({type:"SET_TRANSITIONING",isTransitioning:false});}},[i.resolvedSteps,i.currentStepIndex,i.stepData,i.allData,l,u,s.analytics]),_=react.useCallback((c,d)=>{p({type:"SET_FIELD_VALUE",fieldId:c,value:d});},[]),z=react.useCallback(c=>{p({type:"SET_STEP_DATA",data:c});},[]),K=react.useCallback(async()=>R?{isValid:true,errors:[]}:{isValid:true,errors:[]},[R]),N=react.useCallback(async()=>P(i.currentStepIndex+1),[P,i.currentStepIndex]),H=react.useCallback(async()=>s.navigation?.allowBackNavigation?P(i.currentStepIndex-1):false,[s.navigation,i.currentStepIndex,P]),q=react.useCallback(async()=>!R?.allowSkip||!s.navigation?.allowStepSkipping?false:(s.analytics?.onStepSkip&&s.analytics.onStepSkip(R.id,"user_skip",u),P(i.currentStepIndex+1)),[R,s.navigation,s.analytics,u,P,i.currentStepIndex]),J=react.useCallback(async()=>{p({type:"SET_SUBMITTING",isSubmitting:true});try{if(C.current&&await C.current(i.allData),await b(),s.analytics?.onWorkflowComplete){let c=Date.now()-h.current;s.analytics.onWorkflowComplete(s.id,c,i.allData);}}catch(c){throw console.error("Workflow submission failed:",c),s.analytics?.onError&&s.analytics.onError(c,u),c}finally{p({type:"SET_SUBMITTING",isSubmitting:false});}},[i.allData,C,b,s.analytics,u]),Y=react.useCallback(()=>{p({type:"RESET_WORKFLOW"});},[]),re=react.useMemo(()=>({workflowState:i,workflowConfig:s,currentStep:R,context:u,formConfig:U,goToStep:P,goNext:N,goPrevious:H,skipStep:q,setValue:_,setStepData:z,validateCurrentStep:K,submitWorkflow:J,resetWorkflow:Y,saveDraft:S,loadDraft:G,clearDraft:b}),[i,s,R,u,U,P,N,H,q,_,z,K,J,Y,S,G,b]),oe=react.useCallback(async()=>{await N();},[N]);return jsxRuntime.jsx(Z.Provider,{value:re,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:R?.formConfig,defaultValues:i?.allData[R?.id]||{},onFieldChange:_,"data-workflow-id":s.id,className:n,onSubmit:oe,children:a},R?.id)})}function I(){let a=react.useContext(Z);if(!a)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return a}function ue({children:a,...e}){let[o,t]=react.useState(false),r=x.shouldDisplayWatermark(),n=x.getWatermarkMessage();return react.useEffect(()=>{t(true);},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(j,{...e,children:a}),o&&r&&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})]})}function we(){let{currentStep:a}=I();if(!a)return null;let{formConfig:e,renderer:o}=a;return e?o?o(a):jsxRuntime.jsx(forms.FormBody,{}):null}function L({className:a,children:e}){let{context:o,submitWorkflow:t,workflowState:r,workflowConfig:n}=I(),{submit:l}=forms.useFormContext(),i=n.renderConfig?.nextButtonRenderer;if(!i)throw new Error(`No nextButtonRenderer configured for workflow "${n.id}". Please configure a nextButtonRenderer using config.setWorkflowNextButtonRenderer() or config.setWorkflowRenderConfig().`);let p=!r.isTransitioning&&!r.isSubmitting,m=async k=>{k?.preventDefault(),p&&await l(k);},h=async k=>{k?.preventDefault(),p&&await t();},E={isLastStep:o.isLastStep,canGoNext:p,isSubmitting:r.isSubmitting,onNext:m,onSubmit:h,className:a,children:e};return i(E)}function B({className:a,children:e}){let{workflowConfig:o,context:t,goPrevious:r,workflowState:n}=I(),l=o.renderConfig?.previousButtonRenderer;if(!l)throw new Error(`No previousButtonRenderer configured for workflow "${o.id}". Please configure a previousButtonRenderer using config.setWorkflowPreviousButtonRenderer() or config.setWorkflowRenderConfig().`);let i=t.currentStepIndex>0&&o.navigation?.allowBackNavigation!==false&&!n.isTransitioning&&!n.isSubmitting;return l({canGoPrevious:i,onPrevious:async h=>{h?.preventDefault(),i&&await r();},className:a,children:e})}function O({className:a,children:e}){let{workflowConfig:o,currentStep:t,skipStep:r,workflowState:n}=I(),l=o.renderConfig?.skipButtonRenderer;if(!l)throw new Error(`No skipButtonRenderer configured for workflow "${o.id}". Please configure a skipButtonRenderer using config.setWorkflowSkipButtonRenderer() or config.setWorkflowRenderConfig().`);let i=!!t?.allowSkip&&o.navigation?.allowStepSkipping!==false&&!n.isTransitioning&&!n.isSubmitting;return l({canSkip:i,onSkip:async h=>{h?.preventDefault(),i&&await r();},className:a,children:e})}function ye({className:a}){let{workflowConfig:e,currentStep:o,context:t,goPrevious:r,skipStep:n,submitWorkflow:l,workflowState:i}=I(),{submit:p}=forms.useFormContext(),m=e.renderConfig?.navigationRenderer;if(m){let h=!i.isTransitioning&&!i.isSubmitting,E=t.currentStepIndex>0&&e.navigation?.allowBackNavigation!==false&&!i.isTransitioning&&!i.isSubmitting,k=!!o?.allowSkip&&e.navigation?.allowStepSkipping!==false&&!i.isTransitioning&&!i.isSubmitting,v=async S=>{S?.preventDefault(),h&&await p(S);},w=async S=>{S?.preventDefault(),E&&await r();},C=async S=>{S?.preventDefault(),k&&await n();},s=async S=>{S?.preventDefault(),h&&await l();},u={currentStep:o,context:t,canGoNext:h,canGoPrevious:E,canSkip:k,isSubmitting:i.isSubmitting,onNext:v,onPrevious:w,onSkip:k?C:S=>S?.preventDefault(),onSubmit:s,className:a};return m(u)}return jsxRuntime.jsxs("div",{className:`flex justify-between items-center ${a||""}`,children:[jsxRuntime.jsx(B,{}),jsxRuntime.jsxs("div",{className:"flex gap-2",children:[jsxRuntime.jsx(O,{}),jsxRuntime.jsx(L,{})]})]})}function ve({onStepClick:a,className:e}){let{workflowConfig:o,workflowState:t,goToStep:r}=I(),n=o.renderConfig?.stepperRenderer;if(!n)throw new Error(`No stepperRenderer configured for workflow "${o.id}". Please configure a stepperRenderer using config.setStepperRenderer() or config.setWorkflowRenderConfig().`);let l=p=>{a?a(p):r(p);},i={steps:t.resolvedSteps,currentStepIndex:t.currentStepIndex,visitedSteps:t.visitedSteps,onStepClick:l,className:e};return n(i)}var A=class a{constructor(e,o,t,r){this.steps=[];this.branches=[];this.navigation={};this.plugins=[];this.config=e,this.workflowId=o,this.workflowName=t,this.workflowDescription=r,x.logLicenseStatus();}static create(e,o,t,r){return new a(e,o,t,r)}addStep(e,o,t,r){let n={id:e,title:o,description:r?.description,formConfig:t,allowSkip:r?.allowSkip||false,requiredToComplete:r?.requiredToComplete!==false,hooks:r?.hooks,permissions:r?.permissions,isDynamic:false,renderer:r?.renderer};return this.steps.push(n),this}addDynamicStep(e,o,t,r,n){let l={id:e,title:o,description:n?.description,formConfig:r,allowSkip:n?.allowSkip||false,requiredToComplete:n?.requiredToComplete!==false,hooks:n?.hooks,permissions:n?.permissions,isDynamic:true,dynamicConfig:t};return this.steps.push(l),this}addSteps(e){for(let o of e)this.addStep(o.stepId,o.title,o.formConfig,{description:o.description,allowSkip:o.allowSkip,requiredToComplete:o.requiredToComplete,hooks:o.hooks,permissions:o.permissions});return this}addConditionalBranch(e){return this.branches.push(e),this}addConditionalBranches(e){return this.branches.push(...e),this}setNavigation(e){return this.navigation=e,this}setPersistence(e){return this.persistence=e,this}setAnalytics(e){return this.analytics=e,this}setOptimizations(e){return this.optimizations=e,this}setVersion(e){return this.version=e,this}setCompletion(e){return this.completion=e,this}use(e){if(e.dependencies){let o=e.dependencies.filter(t=>!this.plugins.some(r=>r.name===t));if(o.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${o.join(", ")}`)}this.plugins.push(e);try{e.install(this);}catch(o){throw new Error(`Failed to install plugin "${e.name}": ${o instanceof Error?o.message:String(o)}`)}return this}removePlugin(e){return this.plugins=this.plugins.filter(o=>o.name!==e),this}updateStep(e,o){let t=this.steps.findIndex(r=>r.id===e);if(t===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[t]={...this.steps[t],...o},this}removeStep(e){return this.steps=this.steps.filter(o=>o.id!==e),this}getStep(e){return this.steps.find(o=>o.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this}clone(e,o){let t=new a(this.config,e||`${this.workflowId}-clone`,o||`${this.workflowName} (Copy)`,this.workflowDescription);return t.steps=this.steps.map(r=>({...r})),t.branches=this.branches.map(r=>({...r})),t.navigation={...this.navigation},t.persistence=this.persistence?{...this.persistence}:void 0,t.completion=this.completion?{...this.completion}:void 0,t.analytics=this.analytics?{...this.analytics}:void 0,t.optimizations=this.optimizations?{...this.optimizations}:void 0,t.version=this.version?{...this.version}:void 0,t.plugins=[...this.plugins],t}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let o=this.steps.map(r=>r.id),t=o.filter((r,n)=>o.indexOf(r)!==n);t.length>0&&e.push(`Duplicate step IDs: ${t.join(", ")}`);for(let r of this.plugins)if(r.dependencies){let n=r.dependencies.filter(l=>!this.plugins.some(i=>i.name===l));n.length>0&&e.push(`Plugin "${r.name}" requires missing dependencies: ${n.join(", ")}`);}return e}getStats(){return {totalSteps:this.steps.length,dynamicSteps:this.steps.filter(e=>e.isDynamic).length,conditionalBranches:this.branches.length,pluginsInstalled:this.plugins.length,estimatedFields:this.steps.reduce((e,o)=>e+o.formConfig.allFields.length,0),hasPersistence:!!this.persistence,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],branches:[...this.branches],navigation:this.navigation,persistence:this.persistence,completion:this.completion,analytics:this.analytics,optimizations:this.optimizations,version:this.version,plugins:[...this.plugins],renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,branches:this.branches,navigation:this.navigation,persistence:this.persistence,completion:this.completion,analytics:this.analytics,optimizations:this.optimizations,version:this.version,plugins:this.plugins.map(e=>({name:e.name,version:e.version,dependencies:e.dependencies}))}}fromJSON(e){return e.id&&(this.workflowId=e.id),e.name&&(this.workflowName=e.name),e.description&&(this.workflowDescription=e.description),e.steps&&(this.steps=e.steps),e.branches&&(this.branches=e.branches),e.navigation&&(this.navigation=e.navigation),e.persistence&&(this.persistence=e.persistence),e.completion&&(this.completion=e.completion),e.analytics&&(this.analytics=e.analytics),e.optimizations&&(this.optimizations=e.optimizations),e.version&&(this.version=e.version),this}};var M=class{constructor(e){this.name="analytics";this.version="1.0.0";this.performanceData=new Map;this.config=e;}install(e){let o={onWorkflowStart:(t,r)=>{this.track("workflow_start",{workflow_id:t,total_steps:r.totalSteps,...this.getContextData(r)}),this.config.enablePerformanceTracking&&this.performanceData.set(`workflow_${t}`,Date.now());},onWorkflowComplete:(t,r,n)=>{this.track("workflow_complete",{workflow_id:t,duration_ms:r,form_data_keys:this.config.includeFormData?Object.keys(n):void 0,...this.config.includeFormData?{form_data:n}:{}});},onWorkflowAbandon:(t,r,n)=>{this.track("workflow_abandon",{workflow_id:t,abandoned_at_step:r,completion_percentage:this.calculateCompletionPercentage(n)});},onStepStart:(t,r,n)=>{this.track("step_start",{step_id:t,step_index:n.currentStepIndex,workflow_id:n.workflowId,...this.getContextData(n)}),this.config.enablePerformanceTracking&&this.performanceData.set(`step_${t}`,r);},onStepComplete:(t,r,n,l)=>{this.track("step_complete",{step_id:t,step_index:l.currentStepIndex,workflow_id:l.workflowId,duration_ms:r,field_count:Object.keys(n).length,...this.getContextData(l)});},onStepSkip:(t,r,n)=>{this.track("step_skip",{step_id:t,step_index:n.currentStepIndex,workflow_id:n.workflowId,skip_reason:r,...this.getContextData(n)});},onValidationError:(t,r,n)=>{this.track("validation_error",{step_id:t,step_index:n.currentStepIndex,workflow_id:n.workflowId,error_count:r.length,error_codes:r.map(l=>l.code),...this.getContextData(n)});},onError:(t,r)=>{this.track("workflow_error",{workflow_id:r.workflowId,step_id:r.currentStepIndex,error_message:t.message,error_name:t.name,...this.getContextData(r)});}};e.setAnalytics(o);}track(e,o){let t=this.config.eventMapping?.[e]||e,r={...o,timestamp:Date.now(),plugin_version:this.version};for(let[n,l]of Object.entries(this.config.providers))switch(n){case "googleAnalytics":this.trackGoogleAnalytics(t,r,l);break;case "mixpanel":this.trackMixpanel(t,r);break;case "amplitude":this.trackAmplitude(t,r);break;case "custom":this.trackCustom(t,r,l);break}}trackGoogleAnalytics(e,o,t){typeof window<"u"&&window.gtag&&window.gtag("event",e,{...o,custom_map:t.customDimensions});}trackMixpanel(e,o){typeof window<"u"&&window.mixpanel&&window.mixpanel.track(e,o);}trackAmplitude(e,o){typeof window<"u"&&window.amplitude&&window.amplitude.getInstance().logEvent(e,o);}async trackCustom(e,o,t){try{await fetch(t.endpoint,{method:"POST",headers:{"Content-Type":"application/json",...t.headers},body:JSON.stringify({event:e,properties:o})});}catch(r){console.error("Custom analytics tracking failed:",r);}}getContextData(e){return this.config.includeUserContext?{user_id:e.user?.id,is_first_step:e.isFirstStep,is_last_step:e.isLastStep,visited_steps_count:e.visitedSteps.size,browser_info:typeof window<"u"?{user_agent:navigator.userAgent,language:navigator.language,platform:navigator.platform}:void 0}:{}}calculateCompletionPercentage(e){let o=Object.keys(e).length,t=Object.values(e).filter(r=>r!=null&&r!=="").length;return o>0?t/o*100:0}};var $=class{constructor(e){this.name="validation";this.version="1.0.0";this.dependencies=[];this.debounceTimers=new Map;this.config=e;}install(e){let o=e.getSteps();for(let t of o){let r=t.hooks||{};e.updateStep(t.id,{hooks:{...r,onValidate:async(n,l)=>{let i=await this.validateStep(n,l);return this.config.onValidationComplete&&this.config.onValidationComplete(i,l),i}}});}}async validateStep(e,o){let t=[];try{if(this.config.schema){let n=await this.validateWithSchema(e,o);t.push(...n.errors);}let r=await this.validateWithRules(e,o);if(t.push(...r.errors),this.config.crossFieldValidation){let n=await this.validateCrossField(o.allData,o);t.push(...n.errors);}if(this.config.asyncRules){let n=await this.validateAsync(e,o);t.push(...n.errors);}return {isValid:t.length===0,errors:t}}catch(r){return {isValid:false,errors:[{code:"VALIDATION_ERROR",message:`Validation failed: ${r instanceof Error?r.message:String(r)}`}]}}}async validateWithSchema(e,o){if(!this.config.schema?.schema)return {isValid:true,errors:[]};try{switch(this.config.schema.type){case "zod":{let t=this.config.schema.schema.safeParse(e);if(!t.success)return {isValid:!1,errors:t.error.errors.map(r=>({code:r.code,message:r.message,path:r.path}))};break}case "yup":try{await this.config.schema.schema.validate(e,{abortEarly:!1});}catch(t){return {isValid:!1,errors:t.inner?.map(r=>({code:"YUP_VALIDATION_ERROR",message:r.message,path:r.path?[r.path]:void 0}))||[{code:"YUP_VALIDATION_ERROR",message:t.message}]}}break;case "custom":{let t=await this.config.schema.schema(e,o);if(!t.isValid)return t;break}}return {isValid:!0,errors:[]}}catch(t){return {isValid:false,errors:[{code:"SCHEMA_VALIDATION_ERROR",message:`Schema validation failed: ${t instanceof Error?t.message:String(t)}`}]}}}async validateWithRules(e,o){let t=[];if(this.config.rules.required)for(let r of this.config.rules.required)(!e[r]||typeof e[r]=="string"&&e[r].trim()==="")&&t.push({code:"REQUIRED",message:`${r} is required`,path:[r]});if(this.config.rules.email){let r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;for(let n of this.config.rules.email)e[n]&&!r.test(e[n])&&t.push({code:"INVALID_EMAIL",message:`${n} must be a valid email address`,path:[n]});}if(this.config.rules.phone){let r=/^[\+]?[1-9][\d]{0,15}$/;for(let n of this.config.rules.phone)e[n]&&!r.test(e[n].replace(/\s/g,""))&&t.push({code:"INVALID_PHONE",message:`${n} must be a valid phone number`,path:[n]});}if(this.config.rules.minLength)for(let[r,n]of Object.entries(this.config.rules.minLength))e[r]&&e[r].length<n&&t.push({code:"MIN_LENGTH",message:`${r} must be at least ${n} characters long`,path:[r]});if(this.config.rules.maxLength)for(let[r,n]of Object.entries(this.config.rules.maxLength))e[r]&&e[r].length>n&&t.push({code:"MAX_LENGTH",message:`${r} must be no more than ${n} characters long`,path:[r]});if(this.config.rules.pattern)for(let[r,n]of Object.entries(this.config.rules.pattern))e[r]&&!n.test(e[r])&&t.push({code:"PATTERN_MISMATCH",message:`${r} format is invalid`,path:[r]});if(this.config.rules.custom){for(let[r,n]of Object.entries(this.config.rules.custom))if(e[r]){let l=await n(e[r],o);l.isValid||t.push(...l.errors.map(i=>({...i,path:[r]})));}}return {isValid:t.length===0,errors:t}}async validateCrossField(e,o){let t=[];if(!this.config.crossFieldValidation)return {isValid:true,errors:[]};for(let r of this.config.crossFieldValidation){let n={},l=true;for(let i of r.fields)if(e[i]!==void 0)n[i]=e[i];else {l=false;break}l&&((await r.validator(n,o)).isValid||t.push({code:"CROSS_FIELD_VALIDATION",message:r.message,path:r.fields}));}return {isValid:t.length===0,errors:t}}async validateAsync(e,o){let t=[];if(!this.config.asyncRules)return {isValid:true,errors:[]};let r=Object.entries(this.config.asyncRules).map(async([l,i])=>{if(!e[l])return null;let p=`${l}_${o.workflowId}`;return this.debounceTimers.has(p)&&clearTimeout(this.debounceTimers.get(p)),new Promise(m=>{let h=setTimeout(async()=>{try{let E=i.method==="GET"?`${i.url}?value=${encodeURIComponent(e[l])}`:i.url,v=await(await fetch(E,{method:i.method||"POST",headers:{"Content-Type":"application/json",...i.headers},body:i.method!=="GET"?JSON.stringify({value:e[l]}):void 0})).json();v.isValid?m(null):m({code:"ASYNC_VALIDATION_ERROR",message:v.message||`${l} validation failed`,path:[l]});}catch{m({code:"ASYNC_VALIDATION_ERROR",message:`Async validation failed for ${l}`,path:[l]});}},i.debounceMs||500);this.debounceTimers.set(p,h);})}),n=await Promise.all(r);return t.push(...n.filter(l=>l!==null)),{isValid:t.length===0,errors:t}}};
|
|
2
|
-
Object.defineProperty(exports,"
|
|
1
|
+
'use strict';var core=require('@rilaykit/core'),forms=require('@rilaykit/forms'),q=require('@noble/ed25519'),react=require('react'),jsxRuntime=require('react/jsx-runtime');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 q__namespace=/*#__PURE__*/_interopNamespace(q);var j=1751361139160,ee="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",f=class f{static async setLicenseKey(e){f.licenseKey=e||"",f.licenseKey?f.licenseResult=await f.validateLicense():f.licenseResult={valid:false,error:"MISSING"},f.isInitialized=true;}static async validateLicense(){if(!f.licenseKey)return {valid:false,error:"MISSING"};try{if(!f.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=f.licenseKey.slice(4),t=f.base64ToString(e).split(".");if(t.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[r,i,l]=t,n=`${r}.${i}`,d=new TextEncoder().encode(n),u=l.match(/.{2}/g);if(!u)return {valid:!1,error:"INVALID"};let S=new Uint8Array(u.map(g=>Number.parseInt(g,16))),y=f.hexToBytes(ee);if(!await q__namespace.verify(S,d,y))return {valid:!1,error:"SIGNATURE_INVALID"};let w=f.base64ToString(i.replace(/-/g,"+").replace(/_/g,"/")),h=JSON.parse(w),k=Math.floor(Date.now()/1e3);return h.e<k?{valid:!1,error:"EXPIRED",data:f.decompressPayload(h)}:j>h.e*1e3?{valid:!1,error:"EXPIRED",data:f.decompressPayload(h)}:h.p===void 0||!h.c||!h.i||!h.e||!h.t?{valid:!1,error:"INVALID"}:{valid:!0,data:f.decompressPayload(h)}}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 o=new Uint8Array(e.length/2);for(let t=0;t<e.length;t+=2)o[t/2]=Number.parseInt(e.substring(t,t+2),16);return o}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="",r=0,i=e.replace(/[^A-Za-z0-9+/]/g,"");for(;r<i.length;){let l=o.indexOf(i.charAt(r++)),n=o.indexOf(i.charAt(r++)),d=o.indexOf(i.charAt(r++)),u=o.indexOf(i.charAt(r++)),S=l<<18|n<<12|d<<6|u;t+=String.fromCharCode(S>>16&255),d!==64&&(t+=String.fromCharCode(S>>8&255)),u!==64&&(t+=String.fromCharCode(S&255));}return t}static getLicenseResult(){return f.isInitialized?f.licenseResult?f.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!f.getLicenseResult().valid}static getWatermarkMessage(){let e=f.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=f.getLicenseResult();if(e.valid)return;let t={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${t}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=f.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};f.licenseKey="",f.licenseResult=null,f.isInitialized=false;var x=f;var D=class a{constructor(e,o,t,r){this.steps=[];this.navigation={allowBackNavigation:true};this.plugins=[];this.config=e,this.workflowId=o,this.workflowName=t,this.workflowDescription=r,x.logLicenseStatus();}static create(e,o,t,r){return new a(e,o,t,r)}createStepFromDefinition(e){return {id:e.id,title:e.title,description:e.description,formConfig:e.formConfig instanceof forms.form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,requiredToComplete:e.requiredToComplete!==false,hooks:e.hooks,permissions:e.permissions,isDynamic:!!e.dynamicConfig,dynamicConfig:e.dynamicConfig,renderer:e.renderer}}addStep(e){let o=this.createStepFromDefinition(e);return this.steps.push(o),this}addDynamicStep(e){return this.addStep(e)}addSteps(e){for(let o of e)this.addStep(o);return this}setNavigation(e){return this.navigation={...this.navigation,...e},this}enableBackNavigation(e=true){return this.navigation={...this.navigation,allowBackNavigation:e},this}enableStepSkipping(e=true){return this.navigation={...this.navigation,allowStepSkipping:e},this}setPersistence(e){return this.persistence=e,this}setAnalytics(e){return this.analytics=e,this}setCompletion(e){return this.completion=e,this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(o){throw new Error(`Failed to install plugin "${e.name}": ${o instanceof Error?o.message:String(o)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let o=e.dependencies.filter(t=>!this.plugins.some(r=>r.name===t));if(o.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${o.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(o=>o.name!==e),this}updateStep(e,o){let t=this.steps.findIndex(r=>r.id===e);if(t===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[t]={...this.steps[t],...o},this}removeStep(e){return this.steps=this.steps.filter(o=>o.id!==e),this}getStep(e){return this.steps.find(o=>o.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this}clone(e,o){let t=new a(this.config,e||`${this.workflowId}-clone`,o||`${this.workflowName} (Copy)`,this.workflowDescription);return t.steps=this.steps.map(r=>({...r})),t.navigation={...this.navigation},t.persistence=this.persistence?{...this.persistence}:void 0,t.completion=this.completion?{...this.completion}:void 0,t.analytics=this.analytics?{...this.analytics}:void 0,t.plugins=[...this.plugins],t}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let o=this.steps.map(r=>r.id),t=o.filter((r,i)=>o.indexOf(r)!==i);t.length>0&&e.push(`Duplicate step IDs: ${t.join(", ")}`);for(let r of this.plugins)if(r.dependencies){let i=r.dependencies.filter(l=>!this.plugins.some(n=>n.name===l));i.length>0&&e.push(`Plugin "${r.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){return {totalSteps:this.steps.length,dynamicSteps:this.steps.filter(e=>e.isDynamic).length,pluginsInstalled:this.plugins.length,estimatedFields:this.steps.reduce((e,o)=>e+o.formConfig.allFields.length,0),hasPersistence:!!this.persistence,hasAnalytics:!!this.analytics,allowBackNavigation:this.navigation.allowBackNavigation!==false}}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],navigation:this.navigation,persistence:this.persistence,completion:this.completion,analytics:this.analytics,plugins:[...this.plugins],renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,navigation:this.navigation,persistence:this.persistence,completion:this.completion,analytics:this.analytics,plugins:this.plugins.map(e=>({name:e.name,version:e.version,dependencies:e.dependencies}))}}fromJSON(e){return e.id&&(this.workflowId=e.id),e.name&&(this.workflowName=e.name),e.description&&(this.workflowDescription=e.description),e.steps&&(this.steps=e.steps),e.navigation&&(this.navigation=e.navigation),e.persistence&&(this.persistence=e.persistence),e.completion&&(this.completion=e.completion),e.analytics&&(this.analytics=e.analytics),this}};function oe(a,e,o,t){return D.create(a,e,o,t)}core.ril.prototype.createFlow=function(a,e,o){return D.create(this,a,e,o)};function le(a,e){switch(e.type){case "SET_CURRENT_STEP":return {...a,currentStepIndex:e.stepIndex,stepData:a.allData[a.resolvedSteps[e.stepIndex]?.id]||{}};case "SET_STEP_DATA":{let o=a.resolvedSteps[a.currentStepIndex]?.id;return {...a,stepData:e.data,allData:{...a.allData,[o]:e.data}}}case "SET_ALL_DATA":return {...a,allData:e.data};case "SET_FIELD_VALUE":{let o=a.resolvedSteps[a.currentStepIndex]?.id,t={...a.stepData,[e.fieldId]:e.value};return {...a,stepData:t,allData:{...a.allData,[o]:t}}}case "SET_ERROR":return {...a,errors:{...a.errors,[e.fieldId]:e.errors}};case "CLEAR_ERROR":{let o={...a.errors};return delete o[e.fieldId],{...a,errors:o}}case "MARK_TOUCHED":return {...a,touched:new Set([...a.touched,e.fieldId])};case "SET_VALIDATING":{let o=new Set(a.isValidating);return e.isValidating?o.add(e.fieldId):o.delete(e.fieldId),{...a,isValidating:o}}case "SET_SUBMITTING":return {...a,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...a,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...a,visitedSteps:new Set([...a.visitedSteps,a.resolvedSteps[e.stepIndex]?.id])};case "SET_PERSISTED_DATA":return {...a,persistedData:e.data};case "SET_RESOLVED_STEPS":return {...a,resolvedSteps:e.steps};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},errors:{},touched:new Set,isValidating:new Set,visitedSteps:new Set,isSubmitting:false,isTransitioning:false,resolvedSteps:a.resolvedSteps};default:return a}}var Y=react.createContext(null);function L({children:a,workflowConfig:e,defaultValues:o={},onStepChange:t,onWorkflowComplete:r,className:i,user:l}){let[n,d]=react.useReducer(le,{currentStepIndex:0,allData:o,stepData:{},errors:{},touched:new Set,isValidating:new Set,visitedSteps:new Set,isSubmitting:false,isTransitioning:false,resolvedSteps:e.steps}),u=react.useRef(null),S=react.useRef(Date.now()),y=react.useRef(new Map),C=react.useRef(false),w=react.useRef(null),h=react.useRef(t),k=react.useRef(r);h.current=t,k.current=r;let s=react.useMemo(()=>e,[e]),g=react.useMemo(()=>({workflowId:s.id,currentStepIndex:n.currentStepIndex,totalSteps:n.resolvedSteps.length,allData:n.allData,stepData:n.stepData,isFirstStep:n.currentStepIndex===0,isLastStep:n.currentStepIndex===n.resolvedSteps.length-1,visitedSteps:n.visitedSteps,user:l}),[s.id,n.currentStepIndex,n.resolvedSteps.length,n.allData,n.stepData,n.visitedSteps,l]);react.useEffect(()=>{(async()=>{let p=[];for(let m of s.steps)if(m.isDynamic&&m.dynamicConfig)try{let V=await m.dynamicConfig.resolver(n.allData,g);p.push(...V);}catch(V){console.error(`Failed to resolve dynamic step "${m.id}":`,V),p.push({...m,isDynamic:false});}else p.push(m);d({type:"SET_RESOLVED_STEPS",steps:p});})();},[s.steps,n.allData,g]),react.useEffect(()=>{s.analytics?.onWorkflowStart&&!C.current&&(C.current=true,s.analytics.onWorkflowStart(s.id,g));},[s.id,s.analytics,g]),react.useEffect(()=>{let c=n.resolvedSteps[n.currentStepIndex];if(c&&w.current!==c.id){if(w.current&&s.analytics?.onStepComplete){let p=y.current.get(w.current);p&&s.analytics.onStepComplete(w.current,Date.now()-p,n.stepData,g);}w.current=c.id,y.current.set(c.id,Date.now()),s.analytics?.onStepStart&&s.analytics.onStepStart(c.id,Date.now(),g);}},[n.currentStepIndex,n.resolvedSteps,s.analytics,g]);let E=react.useCallback(async()=>{if(s.persistence)try{let c={workflowId:s.id,currentStepIndex:n.currentStepIndex,allData:n.allData,metadata:{timestamp:Date.now(),version:"1.0.0",userId:l?.id,sessionId:crypto.randomUUID()}},p=s.persistence.key||`workflow-${s.id}`;await s.persistence.adapter.save(p,c),s.persistence.onSave&&await s.persistence.onSave(c);}catch(c){console.error("Failed to save workflow draft:",c),s.persistence.onError&&await s.persistence.onError(c,"save");}},[s,n.currentStepIndex,n.allData,l]),O=react.useCallback(async()=>{if(s.persistence)try{let c=s.persistence.key||`workflow-${s.id}`,p=await s.persistence.adapter.load(c);p&&p.workflowId===s.id&&(d({type:"SET_ALL_DATA",data:p.allData}),d({type:"SET_CURRENT_STEP",stepIndex:p.currentStepIndex}),d({type:"SET_PERSISTED_DATA",data:p}),s.persistence.onLoad&&await s.persistence.onLoad(p));}catch(c){console.error("Failed to load workflow draft:",c),s.persistence.onError&&await s.persistence.onError(c,"load");}},[s]),A=react.useCallback(async()=>{if(s.persistence)try{let c=s.persistence.key||`workflow-${s.id}`;await s.persistence.adapter.remove(c);}catch(c){console.error("Failed to clear workflow draft:",c),s.persistence.onError&&await s.persistence.onError(c,"remove");}},[s]);react.useEffect(()=>{s.persistence&&(async()=>{try{let p=s.persistence.key||`workflow-${s.id}`,m=await s.persistence.adapter.load(p);m&&m.workflowId===s.id&&(d({type:"SET_ALL_DATA",data:m.allData}),d({type:"SET_CURRENT_STEP",stepIndex:m.currentStepIndex}),d({type:"SET_PERSISTED_DATA",data:m}),s.persistence.onLoad&&await s.persistence.onLoad(m),console.log("Workflow data loaded from persistence:",m));}catch(p){console.error("Failed to load workflow draft on mount:",p),s.persistence.onError&&await s.persistence.onError(p,"load");}})();},[s.id]),react.useEffect(()=>{if(s.persistence?.saveOnStepChange)return u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{E();},s.persistence.debounceMs||1e3),()=>{u.current&&clearTimeout(u.current);}},[n.allData,E,s.persistence]);let R=react.useMemo(()=>n.resolvedSteps[n.currentStepIndex],[n.resolvedSteps,n.currentStepIndex]),M=react.useMemo(()=>R?.formConfig,[R]),P=react.useCallback(async c=>{if(c<0||c>=n.resolvedSteps.length)return false;let p=n.resolvedSteps[c];if(p.permissions)try{if(!(p.permissions.customGuard?await p.permissions.customGuard(l,g):!0))return console.warn(`Access denied to step "${p.id}"`),!1}catch(m){return console.error(`Permission check failed for step "${p.id}":`,m),false}if(p.hooks?.onBeforeEnter)try{await p.hooks.onBeforeEnter(n.stepData,n.allData,g);}catch(m){return console.error(`onBeforeEnter hook failed for step "${p.id}":`,m),s.analytics?.onError&&s.analytics.onError(m,g),false}d({type:"SET_TRANSITIONING",isTransitioning:true});try{return h.current&&h.current(n.currentStepIndex,c,g),d({type:"SET_CURRENT_STEP",stepIndex:c}),d({type:"MARK_STEP_VISITED",stepIndex:c}),!0}catch(m){return console.error("Step transition failed:",m),s.analytics?.onError&&s.analytics.onError(m,g),false}finally{d({type:"SET_TRANSITIONING",isTransitioning:false});}},[n.resolvedSteps,n.currentStepIndex,n.stepData,n.allData,l,g,s.analytics]),N=react.useCallback((c,p)=>{d({type:"SET_FIELD_VALUE",fieldId:c,value:p});},[]),$=react.useCallback(c=>{d({type:"SET_STEP_DATA",data:c});},[]),U=react.useCallback(async()=>R?{isValid:true,errors:[]}:{isValid:true,errors:[]},[R]),_=react.useCallback(async()=>P(n.currentStepIndex+1),[P,n.currentStepIndex]),G=react.useCallback(async()=>s.navigation?.allowBackNavigation?P(n.currentStepIndex-1):false,[s.navigation,n.currentStepIndex,P]),K=react.useCallback(async()=>!R?.allowSkip||!s.navigation?.allowStepSkipping?false:(s.analytics?.onStepSkip&&s.analytics.onStepSkip(R.id,"user_skip",g),P(n.currentStepIndex+1)),[R,s.navigation,s.analytics,g,P,n.currentStepIndex]),H=react.useCallback(async()=>{d({type:"SET_SUBMITTING",isSubmitting:true});try{if(k.current&&await k.current(n.allData),await A(),s.analytics?.onWorkflowComplete){let c=Date.now()-S.current;s.analytics.onWorkflowComplete(s.id,c,n.allData);}}catch(c){throw console.error("Workflow submission failed:",c),s.analytics?.onError&&s.analytics.onError(c,g),c}finally{d({type:"SET_SUBMITTING",isSubmitting:false});}},[n.allData,k,A,s.analytics,g]),z=react.useCallback(()=>{d({type:"RESET_WORKFLOW"});},[]),Z=react.useMemo(()=>({workflowState:n,workflowConfig:s,currentStep:R,context:g,formConfig:M,goToStep:P,goNext:_,goPrevious:G,skipStep:K,setValue:N,setStepData:$,validateCurrentStep:U,submitWorkflow:H,resetWorkflow:z,saveDraft:E,loadDraft:O,clearDraft:A}),[n,s,R,g,M,P,_,G,K,N,$,U,H,z,E,O,A]),Q=react.useCallback(async()=>{await _();},[_]);return jsxRuntime.jsx(Y.Provider,{value:Z,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:R?.formConfig,defaultValues:n?.allData[R?.id]||{},onFieldChange:N,"data-workflow-id":s.id,className:i,onSubmit:Q,children:a},R?.id)})}function I(){let a=react.useContext(Y);if(!a)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return a}function pe({children:a,workflowConfig:e,...o}){let[t,r]=react.useState(false),i=x.shouldDisplayWatermark(),l=x.getWatermarkMessage(),n=e instanceof D?e.build():e;return react.useEffect(()=>{r(true);},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(L,{...o,workflowConfig:n,children:a}),t&&i&&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:l})]})}function ge(){let{currentStep:a}=I();if(!a)return null;let{formConfig:e,renderer:o}=a;return e?o?o(a):jsxRuntime.jsx(forms.FormBody,{}):null}function Se({className:a,children:e,renderAs:o}){let{context:t,submitWorkflow:r,workflowState:i,workflowConfig:l,currentStep:n}=I(),{submit:d,formState:u}=forms.useFormContext(),S=!i.isTransitioning&&!i.isSubmitting,y=async E=>{E?.preventDefault(),S&&await d(E);},C=async E=>{E?.preventDefault(),S&&await r();},w={isLastStep:t.isLastStep,canGoNext:S,isSubmitting:i.isSubmitting,onNext:y,onSubmit:C,className:a,currentStep:n,stepData:u.values||{},allData:t.allData,context:t};if(o==="children"||o===true){if(typeof e!="function")throw new Error('When renderAs="children" is used, children must be a function that returns React elements');return e(w)}let k=l.renderConfig?.nextButtonRenderer;if(!k)throw new Error(`No nextButtonRenderer configured for workflow "${l.id}". Please configure a nextButtonRenderer using config.setWorkflowNextButtonRenderer() or config.setWorkflowRenderConfig().`);let s=core.resolveRendererChildren(e,w),g={...w,children:s};return k(g)}function ve({className:a,children:e,renderAs:o}){let{context:t,goPrevious:r,workflowState:i,workflowConfig:l,currentStep:n}=I(),{formState:d}=forms.useFormContext(),u=t.currentStepIndex>0&&l.navigation?.allowBackNavigation!==false&&!i.isTransitioning&&!i.isSubmitting;if(l.navigation?.allowBackNavigation===false)throw new Error(`WorkflowPreviousButton is rendered but allowBackNavigation is disabled in workflow "${l.id}". Either enable back navigation or remove the WorkflowPreviousButton component.`);let y={canGoPrevious:u,onPrevious:async s=>{s?.preventDefault(),u&&await r();},className:a,currentStep:n,stepData:d.values||{},allData:t.allData,context:t};if(o==="children"||o===true){if(typeof e!="function")throw new Error('When renderAs="children" is used, children must be a function that returns React elements');return e(y)}let w=l.renderConfig?.previousButtonRenderer;if(!w)throw new Error(`No previousButtonRenderer configured for workflow "${l.id}". Please configure a previousButtonRenderer using config.setWorkflowPreviousButtonRenderer() or config.setWorkflowRenderConfig().`);let h=core.resolveRendererChildren(e,y),k={...y,children:h};return w(k)}function Ie({className:a,children:e,renderAs:o}){let{currentStep:t,skipStep:r,workflowState:i,workflowConfig:l,context:n}=I(),{formState:d}=forms.useFormContext(),u=!!t?.allowSkip&&l.navigation?.allowStepSkipping!==false&&!i.isTransitioning&&!i.isSubmitting,y={canSkip:u,onSkip:async s=>{s?.preventDefault(),u&&await r();},className:a,currentStep:t,stepData:d.values||{},allData:n.allData,context:n};if(o==="children"||o===true){if(typeof e!="function")throw new Error('When renderAs="children" is used, children must be a function that returns React elements');return e(y)}let w=l.renderConfig?.skipButtonRenderer;if(!w)throw new Error(`No skipButtonRenderer configured for workflow "${l.id}". Please configure a skipButtonRenderer using config.setWorkflowSkipButtonRenderer() or config.setWorkflowRenderConfig().`);let h=core.resolveRendererChildren(e,y),k={...y,children:h};return w(k)}function Ee({onStepClick:a,className:e,children:o,renderAs:t}){let{workflowConfig:r,workflowState:i,goToStep:l}=I(),n=C=>{a?a(C):l(C);},d={steps:i.resolvedSteps,currentStepIndex:i.currentStepIndex,visitedSteps:i.visitedSteps,onStepClick:n,className:e};if(t==="children"||t===true){if(typeof o!="function")throw new Error('When renderAs="children" is used, children must be a function that returns React elements');return o(d)}let S=r.renderConfig?.stepperRenderer;if(!S)throw new Error(`No stepperRenderer configured for workflow "${r.id}". Please configure a stepperRenderer using config.setStepperRenderer() or config.setWorkflowRenderConfig().`);return S(d)}var B=class{constructor(e){this.name="analytics";this.version="1.0.0";this.performanceData=new Map;this.config=e;}install(e){let o={onWorkflowStart:(t,r)=>{this.track("workflow_start",{workflow_id:t,total_steps:r.totalSteps,...this.getContextData(r)}),this.config.enablePerformanceTracking&&this.performanceData.set(`workflow_${t}`,Date.now());},onWorkflowComplete:(t,r,i)=>{this.track("workflow_complete",{workflow_id:t,duration_ms:r,form_data_keys:this.config.includeFormData?Object.keys(i):void 0,...this.config.includeFormData?{form_data:i}:{}});},onWorkflowAbandon:(t,r,i)=>{this.track("workflow_abandon",{workflow_id:t,abandoned_at_step:r,completion_percentage:this.calculateCompletionPercentage(i)});},onStepStart:(t,r,i)=>{this.track("step_start",{step_id:t,step_index:i.currentStepIndex,workflow_id:i.workflowId,...this.getContextData(i)}),this.config.enablePerformanceTracking&&this.performanceData.set(`step_${t}`,r);},onStepComplete:(t,r,i,l)=>{this.track("step_complete",{step_id:t,step_index:l.currentStepIndex,workflow_id:l.workflowId,duration_ms:r,field_count:Object.keys(i).length,...this.getContextData(l)});},onStepSkip:(t,r,i)=>{this.track("step_skip",{step_id:t,step_index:i.currentStepIndex,workflow_id:i.workflowId,skip_reason:r,...this.getContextData(i)});},onValidationError:(t,r,i)=>{this.track("validation_error",{step_id:t,step_index:i.currentStepIndex,workflow_id:i.workflowId,error_count:r.length,error_codes:r.map(l=>l.code),...this.getContextData(i)});},onError:(t,r)=>{this.track("workflow_error",{workflow_id:r.workflowId,step_id:r.currentStepIndex,error_message:t.message,error_name:t.name,...this.getContextData(r)});}};e.setAnalytics(o);}track(e,o){let t=this.config.eventMapping?.[e]||e,r={...o,timestamp:Date.now(),plugin_version:this.version};for(let[i,l]of Object.entries(this.config.providers))switch(i){case "googleAnalytics":this.trackGoogleAnalytics(t,r,l);break;case "mixpanel":this.trackMixpanel(t,r);break;case "amplitude":this.trackAmplitude(t,r);break;case "custom":this.trackCustom(t,r,l);break}}trackGoogleAnalytics(e,o,t){typeof window<"u"&&window.gtag&&window.gtag("event",e,{...o,custom_map:t.customDimensions});}trackMixpanel(e,o){typeof window<"u"&&window.mixpanel&&window.mixpanel.track(e,o);}trackAmplitude(e,o){typeof window<"u"&&window.amplitude&&window.amplitude.getInstance().logEvent(e,o);}async trackCustom(e,o,t){try{await fetch(t.endpoint,{method:"POST",headers:{"Content-Type":"application/json",...t.headers},body:JSON.stringify({event:e,properties:o})});}catch(r){console.error("Custom analytics tracking failed:",r);}}getContextData(e){return this.config.includeUserContext?{user_id:e.user?.id,is_first_step:e.isFirstStep,is_last_step:e.isLastStep,visited_steps_count:e.visitedSteps.size,browser_info:typeof window<"u"?{user_agent:navigator.userAgent,language:navigator.language,platform:navigator.platform}:void 0}:{}}calculateCompletionPercentage(e){let o=Object.keys(e).length,t=Object.values(e).filter(r=>r!=null&&r!=="").length;return o>0?t/o*100:0}};var F=class{constructor(e){this.name="validation";this.version="1.0.0";this.dependencies=[];this.debounceTimers=new Map;this.config=e;}install(e){let o=e.getSteps();for(let t of o){let r=t.hooks||{};e.updateStep(t.id,{hooks:{...r,onValidate:async(i,l)=>{let n=await this.validateStep(i,l);return this.config.onValidationComplete&&this.config.onValidationComplete(n,l),n}}});}}async validateStep(e,o){let t=[];try{if(this.config.schema){let i=await this.validateWithSchema(e,o);t.push(...i.errors);}let r=await this.validateWithRules(e,o);if(t.push(...r.errors),this.config.crossFieldValidation){let i=await this.validateCrossField(o.allData,o);t.push(...i.errors);}if(this.config.asyncRules){let i=await this.validateAsync(e,o);t.push(...i.errors);}return {isValid:t.length===0,errors:t}}catch(r){return {isValid:false,errors:[{code:"VALIDATION_ERROR",message:`Validation failed: ${r instanceof Error?r.message:String(r)}`}]}}}async validateWithSchema(e,o){if(!this.config.schema?.schema)return {isValid:true,errors:[]};try{switch(this.config.schema.type){case "zod":{let t=this.config.schema.schema.safeParse(e);if(!t.success)return {isValid:!1,errors:t.error.errors.map(r=>({code:r.code,message:r.message,path:r.path}))};break}case "yup":try{await this.config.schema.schema.validate(e,{abortEarly:!1});}catch(t){return {isValid:!1,errors:t.inner?.map(r=>({code:"YUP_VALIDATION_ERROR",message:r.message,path:r.path?[r.path]:void 0}))||[{code:"YUP_VALIDATION_ERROR",message:t.message}]}}break;case "custom":{let t=await this.config.schema.schema(e,o);if(!t.isValid)return t;break}}return {isValid:!0,errors:[]}}catch(t){return {isValid:false,errors:[{code:"SCHEMA_VALIDATION_ERROR",message:`Schema validation failed: ${t instanceof Error?t.message:String(t)}`}]}}}async validateWithRules(e,o){let t=[];if(this.config.rules.required)for(let r of this.config.rules.required)(!e[r]||typeof e[r]=="string"&&e[r].trim()==="")&&t.push({code:"REQUIRED",message:`${r} is required`,path:[r]});if(this.config.rules.email){let r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;for(let i of this.config.rules.email)e[i]&&!r.test(e[i])&&t.push({code:"INVALID_EMAIL",message:`${i} must be a valid email address`,path:[i]});}if(this.config.rules.phone){let r=/^[\+]?[1-9][\d]{0,15}$/;for(let i of this.config.rules.phone)e[i]&&!r.test(e[i].replace(/\s/g,""))&&t.push({code:"INVALID_PHONE",message:`${i} must be a valid phone number`,path:[i]});}if(this.config.rules.minLength)for(let[r,i]of Object.entries(this.config.rules.minLength))e[r]&&e[r].length<i&&t.push({code:"MIN_LENGTH",message:`${r} must be at least ${i} characters long`,path:[r]});if(this.config.rules.maxLength)for(let[r,i]of Object.entries(this.config.rules.maxLength))e[r]&&e[r].length>i&&t.push({code:"MAX_LENGTH",message:`${r} must be no more than ${i} characters long`,path:[r]});if(this.config.rules.pattern)for(let[r,i]of Object.entries(this.config.rules.pattern))e[r]&&!i.test(e[r])&&t.push({code:"PATTERN_MISMATCH",message:`${r} format is invalid`,path:[r]});if(this.config.rules.custom){for(let[r,i]of Object.entries(this.config.rules.custom))if(e[r]){let l=await i(e[r],o);l.isValid||t.push(...l.errors.map(n=>({...n,path:[r]})));}}return {isValid:t.length===0,errors:t}}async validateCrossField(e,o){let t=[];if(!this.config.crossFieldValidation)return {isValid:true,errors:[]};for(let r of this.config.crossFieldValidation){let i={},l=true;for(let n of r.fields)if(e[n]!==void 0)i[n]=e[n];else {l=false;break}l&&((await r.validator(i,o)).isValid||t.push({code:"CROSS_FIELD_VALIDATION",message:r.message,path:r.fields}));}return {isValid:t.length===0,errors:t}}async validateAsync(e,o){let t=[];if(!this.config.asyncRules)return {isValid:true,errors:[]};let r=Object.entries(this.config.asyncRules).map(async([l,n])=>{if(!e[l])return null;let d=`${l}_${o.workflowId}`;return this.debounceTimers.has(d)&&clearTimeout(this.debounceTimers.get(d)),new Promise(u=>{let S=setTimeout(async()=>{try{let y=n.method==="GET"?`${n.url}?value=${encodeURIComponent(e[l])}`:n.url,w=await(await fetch(y,{method:n.method||"POST",headers:{"Content-Type":"application/json",...n.headers},body:n.method!=="GET"?JSON.stringify({value:e[l]}):void 0})).json();w.isValid?u(null):u({code:"ASYNC_VALIDATION_ERROR",message:w.message||`${l} validation failed`,path:[l]});}catch{u({code:"ASYNC_VALIDATION_ERROR",message:`Async validation failed for ${l}`,path:[l]});}},n.debounceMs||500);this.debounceTimers.set(d,S);})}),i=await Promise.all(r);return t.push(...i.filter(l=>l!==null)),{isValid:t.length===0,errors:t}}};
|
|
2
|
+
Object.defineProperty(exports,"createZodValidator",{enumerable:true,get:function(){return core.createZodValidator}});Object.defineProperty(exports,"ril",{enumerable:true,get:function(){return core.ril}});Object.defineProperty(exports,"form",{enumerable:true,get:function(){return forms.form}});exports.AnalyticsPlugin=B;exports.RilayLicenseManager=x;exports.ValidationPlugin=F;exports.Workflow=pe;exports.WorkflowBody=ge;exports.WorkflowNextButton=Se;exports.WorkflowPreviousButton=ve;exports.WorkflowProvider=L;exports.WorkflowSkipButton=Ie;exports.WorkflowStepper=Ee;exports.createFlow=oe;exports.flow=D;exports.useWorkflowContext=I;
|