@rilaykit/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';function k(n,e){return typeof n=="function"?n(e):n}function fe({children:n,renderAs:e,renderer:r,name:t,props:o}){if(e==="children"||e===true){if(typeof n!="function")throw new Error(`When renderAs="children" is used, children must be a function that returns React elements for ${t}`);return n(o)}if(!r)throw new Error(`No renderer provided for ${t}`);if(typeof r!="function")throw new Error(`Renderer must be a function for ${t}`);let a={...o,children:k(n,o)};return r(a)}function me(n,e){return {...n,...e}}function V(n,e){let r=n.filter((t,o)=>n.indexOf(t)!==o);if(r.length>0)throw new Error(`Duplicate ${e} IDs: ${r.join(", ")}`)}function ge(n,e,r){if(n.filter(o=>e.some(i=>!o[i])).length>0)throw new Error(`Missing required fields in ${r}: ${e.join(", ")}`)}var P=class{constructor(){this.counters=new Map;}next(e){let r=this.counters.get(e)||0;return this.counters.set(e,r+1),`${e}-${r+1}`}reset(e){e?this.counters.delete(e):this.counters.clear();}};function ye(n){return Array.isArray(n)?n:[n]}function E(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n))return n.map(r=>E(r));let e={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=E(n[r]));return e}function he(n,e,r){let t={...n};for(let o in e)r&&!r.includes(o)||e[o]!==void 0&&(t[o]=e[o]);return t}var h=class extends Error{constructor(r,t,o){super(r);this.code=t;this.meta=o;this.name="RilayError";}},g=class extends h{constructor(e,r){super(e,"VALIDATION_ERROR",r),this.name="ValidationError";}};function m(n,e){let r={...n};for(let t in e){let o=e[t],i=r[t];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?r[t]=m(i,o):r[t]=o;}return r}var v=class n{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new n}addComponent(e,r){let t={id:e,type:e,...r},o=new n;return o.components=new Map(this.components),o.formRenderConfig={...this.formRenderConfig},o.workflowRenderConfig={...this.workflowRenderConfig},o.components.set(e,t),o}configure(e){let r=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],t=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],o={},i={};for(let[s,u]of Object.entries(e))r.includes(s)?o[s]=u:t.includes(s)&&(i[s]=u);let a=new n;return a.components=new Map(this.components),a.formRenderConfig=m(this.formRenderConfig,o),a.workflowRenderConfig=m(this.workflowRenderConfig,i),a}getFormRenderConfig(){return {...this.formRenderConfig}}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}getComponent(e){return this.components.get(e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){let r=new n;return r.components=new Map(this.components),r.formRenderConfig={...this.formRenderConfig},r.workflowRenderConfig={...this.workflowRenderConfig},r.components.delete(e),r}clear(){let e=new n;return e.formRenderConfig={...this.formRenderConfig},e.workflowRenderConfig={...this.workflowRenderConfig},e}clone(){let e=new n;return e.components=new Map(this.components),e.formRenderConfig=m({},this.formRenderConfig),e.workflowRenderConfig=m({},this.workflowRenderConfig),e}getStats(){let e=Array.from(this.components.values());return {total:e.length,byType:e.reduce((r,t)=>(r[t.type]=(r[t.type]||0)+1,r),{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,field:!!this.formRenderConfig.fieldRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNextButton:!!this.workflowRenderConfig.nextButtonRenderer,workflowPreviousButton:!!this.workflowRenderConfig.previousButtonRenderer,workflowSkipButton:!!this.workflowRenderConfig.skipButtonRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(l=>l.id);try{V(t,"component");}catch(l){e.push(l instanceof Error?l.message:String(l));}let o=r.filter(l=>!l.renderer);o.length>0&&e.push(`Components without renderer: ${o.map(l=>l.id).join(", ")}`);let i=Object.keys(this.formRenderConfig),a=Object.keys(this.workflowRenderConfig),s=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],u=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],d=i.filter(l=>!s.includes(l)),y=a.filter(l=>!u.includes(l));return d.length>0&&e.push(`Invalid form renderer keys: ${d.join(", ")}`),y.length>0&&e.push(`Invalid workflow renderer keys: ${y.join(", ")}`),e}async validateAsync(){let e=[],r=[],t=Array.from(this.components.values());try{let o=this.validate();e.push(...o);let i=t.map(async d=>d.renderer&&typeof d.renderer!="function"&&typeof d.renderer!="object"?`Component "${d.id}" has invalid renderer type: ${typeof d.renderer}`:((d.id.includes(" ")||d.id.includes("-"))&&r.push(`Component "${d.id}" uses non-standard naming (contains spaces or dashes)`),null)),s=(await Promise.all(i)).filter(d=>d!==null);e.push(...s),t.length>50&&r.push("Large number of components detected. Consider splitting configuration.");let u={isValid:e.length===0,errors:e,warnings:r.length>0?r:void 0};if(!u.isValid)throw new g("Ril configuration validation failed",{errors:e,warnings:r,componentCount:t.length});return u}catch(o){throw o instanceof g?o:new g("Unexpected error during async validation",{originalError:o instanceof Error?o.message:String(o)})}}};function C(n,e=[]){return {isValid:n,errors:[...e]}}function D(){return C(true,[])}function W(n,e,r){return C(false,[{message:n,code:e,path:r}])}function O(n={}){return {fieldId:n.fieldId,formId:n.formId,stepId:n.stepId,workflowId:n.workflowId,allFormData:n.allFormData||{},stepData:n.stepData||{},workflowData:n.workflowData||{}}}function N(n="This field is required"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>e===""||e==null||Array.isArray(e)&&e.length===0||typeof e=="object"&&Object.keys(e).length===0?{issues:[{message:n,path:void 0}]}:{value:e}}}}function $(n="Please enter a valid email address"){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Email must be a string"}]}:e.test(r)?{value:r}:{issues:[{message:n}]},types:{input:"",output:""}}}}function L(n="Please enter a valid URL"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{if(typeof e!="string")return {issues:[{message:"URL must be a string"}]};try{return new URL(e),{value:e}}catch{return {issues:[{message:n}]}}},types:{input:"",output:""}}}}function q(n,e){let r=`Must be at least ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length>=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function z(n,e){let r=`Must be no more than ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length<=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function U(n,e="Value does not match required pattern"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Value must be a string"}]}:n.test(r)?{value:r}:{issues:[{message:e}]},types:{input:"",output:""}}}}function _(n="Must be a valid number"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{let r=typeof e=="string"?Number(e):e;return typeof r!="number"||Number.isNaN(r)?{issues:[{message:n}]}:{value:r}},types:{input:0,output:0}}}}function K(n,e){let r=`Must be at least ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o>=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function j(n,e){let r=`Must be no more than ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o<=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function Q(n,e="Validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>{try{return n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function H(n,e="Async validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:async r=>{try{return await n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function J(...n){return {"~standard":{version:1,vendor:"rilaykit",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function c(n){return n!=null&&typeof n=="object"&&"~standard"in n&&n["~standard"]!==null&&typeof n["~standard"]=="object"&&n["~standard"].version===1&&typeof n["~standard"].vendor=="string"&&typeof n["~standard"].validate=="function"}async function R(n,e){if(!c(n))throw new Error("Invalid Standard Schema: missing ~standard property or invalid structure");try{let r=n["~standard"].validate(e);return r instanceof Promise&&(r=await r),r.issues?{isValid:!1,errors:r.issues.map(o=>({message:o.message,code:"VALIDATION_ERROR",path:G(o.path)}))}:{isValid:!0,errors:[],value:r.value}}catch(r){return {isValid:false,errors:[{message:r instanceof Error?r.message:"Validation failed",code:"VALIDATION_ERROR"}]}}}function G(n){if(!(!n||n.length===0))return n.map(e=>typeof e=="object"&&"key"in e?String(e.key):String(e)).join(".")}function X(n){if(!c(n))throw new Error("Invalid Standard Schema");return {vendor:n["~standard"].vendor,version:n["~standard"].version,hasTypes:!!n["~standard"].types}}function Y(n){return c(n)&&!!n["~standard"].types}async function Z(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Validation error",code:"VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}async function ee(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Form validation error",code:"FORM_VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}function re(n){return !!n.validate}function ne(...n){return {"~standard":{version:1,vendor:"rilaykit-combined",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function te(n,e="rilaykit"){return {"~standard":{version:1,vendor:e,validate:async r=>{try{let t=await n(r,{});return t.isValid?{value:r}:{issues:t.errors.map(i=>({message:i.message,path:i.path?[i.path]:void 0}))}}catch(t){return {issues:[{message:t instanceof Error?t.message:"Validation failed"}]}}}}}}function oe(n){return Array.isArray(n)?n.every(c):c(n)}function ie(n){return n?Array.isArray(n)?n:[n]:[]}var ae=0,M=()=>`event_${Date.now()}_${++ae}`,se=()=>`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,w=class{constructor(e,r){this.adapters=[];this.eventBuffer=[];this.config={bufferSize:100,flushInterval:5e3,sampleRate:1,enablePerformanceTracking:true,enableErrorTracking:true,enableMemoryTracking:false,...e},this.context={sessionId:se(),environment:"production",userAgent:typeof window<"u"?window.navigator?.userAgent:void 0,url:typeof window<"u"?window.location?.href:void 0,...r},this.profiler=new b,this.config.enabled&&this.startFlushTimer();}addAdapter(e){this.adapters.push(e);}removeAdapter(e){this.adapters=this.adapters.filter(r=>r.name!==e);}track(e,r,t,o,i="low"){if(!this.config.enabled||Math.random()>(this.config.sampleRate||1))return;let a={id:M(),type:e,timestamp:Date.now(),source:r,data:{...t,context:this.context},metrics:o,severity:i};if(o&&this.config.performanceThresholds&&this.checkPerformanceThresholds(a,o),this.eventBuffer.push(a),this.config.onEvent)try{this.config.onEvent(a);}catch(s){console.error("Error in monitoring event callback:",s);}this.eventBuffer.length>=(this.config.bufferSize||100)&&this.flush();}trackError(e,r,t){this.track("error",r,{message:e.message,name:e.name,stack:e.stack,context:t},void 0,"high");}getProfiler(){return this.profiler}updateContext(e){this.context={...this.context,...e};}async flush(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];if(this.eventBuffer=[],this.config.onBatch)try{this.config.onBatch(e);}catch(r){console.error("Error in monitoring batch callback:",r);}await Promise.all(this.adapters.map(async r=>{try{await r.send(e);}catch(t){console.error(`Error sending events to adapter ${r.name}:`,t),this.config.onError&&this.config.onError(t);}}));}async destroy(){this.flushTimer&&clearInterval(this.flushTimer),await this.flush(),await Promise.all(this.adapters.map(async e=>{if(e.flush)try{await e.flush();}catch(r){console.error(`Error flushing adapter ${e.name}:`,r);}}));}startFlushTimer(){this.config.flushInterval&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval));}checkPerformanceThresholds(e,r){let t=this.config.performanceThresholds;t.componentRenderTime&&e.type==="component_render"&&r.duration>t.componentRenderTime&&this.createPerformanceWarning("Component render time exceeded threshold",t.componentRenderTime,r.duration,"Consider memoizing component or optimizing render logic"),t.formValidationTime&&e.type==="form_validation"&&r.duration>t.formValidationTime&&this.createPerformanceWarning("Form validation time exceeded threshold",t.formValidationTime,r.duration,"Consider debouncing validation or optimizing validators"),t.workflowNavigationTime&&e.type==="workflow_navigation"&&r.duration>t.workflowNavigationTime&&this.createPerformanceWarning("Workflow navigation time exceeded threshold",t.workflowNavigationTime,r.duration,"Consider optimizing step transitions or condition evaluation"),t.memoryUsage&&r.memoryUsage&&r.memoryUsage>t.memoryUsage&&this.createPerformanceWarning("Memory usage exceeded threshold",t.memoryUsage,r.memoryUsage,"Check for memory leaks or optimize data structures"),t.reRenderCount&&r.reRenderCount&&r.reRenderCount>t.reRenderCount&&this.createPerformanceWarning("Component re-render count exceeded threshold",t.reRenderCount,r.reRenderCount,"Consider using React.memo or optimizing dependencies");}createPerformanceWarning(e,r,t,o){let i={id:M(),type:"performance_warning",timestamp:Date.now(),source:"rilay_monitor",data:{message:e,context:this.context},threshold:r,actualValue:t,recommendation:o,severity:"medium"};if(this.eventBuffer.push(i),this.config.onEvent)try{this.config.onEvent(i);}catch(a){console.error("Error in performance warning callback:",a);}}},b=class{constructor(){this.metrics=new Map;this.startTimes=new Map;}start(e,r={}){this.startTimes.set(e,performance.now()),this.metrics.set(e,{timestamp:Date.now(),duration:0,renderCount:r.renderCount||0,reRenderCount:r.reRenderCount||0,memoryUsage:this.getMemoryUsage()});}end(e){let r=this.startTimes.get(e);if(!r)return null;let t=performance.now()-r,o=this.metrics.get(e);if(!o)return null;let i={...o,duration:t,memoryUsage:this.getMemoryUsage()};return this.metrics.set(e,i),this.startTimes.delete(e),i}mark(e){typeof performance<"u"&&performance.mark&&performance.mark(e);}measure(e,r,t){if(typeof performance<"u"&&performance.measure){performance.measure(e,r,t);let o=performance.getEntriesByName(e,"measure");return o.length>0?o[o.length-1].duration:0}return 0}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){let e={};return this.metrics.forEach((r,t)=>{e[t]=r;}),e}clear(e){e?(this.metrics.delete(e),this.startTimes.delete(e)):(this.metrics.clear(),this.startTimes.clear());}getMemoryUsage(){if(typeof performance<"u"&&performance.memory)return performance.memory.usedJSHeapSize}},f=null;function Ve(n,e){return f&&f.destroy(),f=new w(n,e),f}function Me(){return f}async function Be(){f&&(await f.destroy(),f=null);}var x=class{constructor(e="info"){this.name="console";this.logLevel=e;}async send(e){for(let r of e)this.logEvent(r);}logEvent(e){let r={id:e.id,type:e.type,timestamp:new Date(e.timestamp).toISOString(),source:e.source,severity:e.severity,data:e.data,metrics:e.metrics};switch(e.severity){case "critical":case "high":this.shouldLog("error")&&console.error(`[Rilay Monitor] ${e.type}:`,r);break;case "medium":this.shouldLog("warn")&&console.warn(`[Rilay Monitor] ${e.type}:`,r);break;default:this.shouldLog("info")&&console.info(`[Rilay Monitor] ${e.type}:`,r);break}if(e.type==="performance_warning"&&this.shouldLog("warn")){let t=e;console.warn(`[Rilay Performance Warning] ${t.data.message}`,{threshold:t.threshold,actual:t.actualValue,recommendation:t.recommendation});}}shouldLog(e){let r=["debug","info","warn","error"],t=r.indexOf(this.logLevel);return r.indexOf(e)>=t}},B=class{constructor(e){this.name="remote";this.eventQueue=[];this.isProcessing=false;this.endpoint=e.endpoint,this.apiKey=e.apiKey,this.headers={"Content-Type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},...e.headers},this.batchSize=e.batchSize||50,this.retryAttempts=e.retryAttempts||3;}async send(e){this.eventQueue.push(...e),this.isProcessing||await this.processQueue();}async flush(){await this.processQueue();}configure(e){e.headers&&Object.assign(this.headers,e.headers);}async processQueue(){if(!(this.isProcessing||this.eventQueue.length===0)){this.isProcessing=true;try{for(;this.eventQueue.length>0;){let e=this.eventQueue.splice(0,this.batchSize);await this.sendBatch(e);}}finally{this.isProcessing=false;}}}async sendBatch(e){let r={events:e,timestamp:Date.now(),source:"rilay-monitoring"},t=null;for(let o=1;o<=this.retryAttempts;o++)try{let i=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(r)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return}catch(i){if(t=i,i instanceof Error&&i.message.includes("HTTP 4"))break;o<this.retryAttempts&&await this.delay(2**o*1e3);}throw console.error("Failed to send monitoring events to remote endpoint:",t),t}delay(e){return new Promise(r=>setTimeout(r,e))}},F=class{constructor(e=1e3){this.name="localStorage";this.storageKey="rilay_monitoring_events";this.maxEvents=e;}async send(e){try{let o=[...this.getStoredEvents(),...e].slice(-this.maxEvents);localStorage.setItem(this.storageKey,JSON.stringify(o));}catch(r){console.error("Failed to store monitoring events:",r);}}async flush(){}getStoredEvents(){try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return console.error("Failed to retrieve stored monitoring events:",e),[]}}clearStoredEvents(){localStorage.removeItem(this.storageKey);}getEventCount(){return this.getStoredEvents().length}},A=class{constructor(){this.name="development";this.console=new x("debug");}async send(e){await this.console.send(e),this.logPerformanceSummary(e),this.logErrorSummary(e);}logPerformanceSummary(e){let r=e.filter(a=>a.metrics);if(r.length===0)return;console.group("[Rilay Performance Summary]");let t=r.reduce((a,s)=>a+(s.metrics?.duration||0),0)/r.length,o=Math.max(...r.map(a=>a.metrics?.duration||0));console.info(`Average duration: ${t.toFixed(2)}ms`),console.info(`Max duration: ${o.toFixed(2)}ms`);let i={};for(let a of r)i[a.type]||(i[a.type]=[]),i[a.type].push(a);for(let[a,s]of Object.entries(i)){let u=s.reduce((d,y)=>d+(y.metrics?.duration||0),0)/s.length;console.info(`${a}: ${u.toFixed(2)}ms avg (${s.length} events)`);}console.groupEnd();}logErrorSummary(e){let r=e.filter(o=>o.type==="error");if(r.length===0)return;console.group("[Rilay Error Summary]"),console.error(`${r.length} errors detected`);let t={};for(let o of r)t[o.source]=(t[o.source]||0)+1;for(let[o,i]of Object.entries(t))console.error(`${o}: ${i} errors`);console.groupEnd();}};var S=class{constructor(){this.fieldDependencies=new Map;this.reverseDependencies=new Map;}addField(e,r){if(!r){this.fieldDependencies.set(e,new Set);return}let t=new Set;if(r.visible)for(let o of p(r.visible))t.add(o);if(r.disabled)for(let o of p(r.disabled))t.add(o);if(r.required)for(let o of p(r.required))t.add(o);if(r.readonly)for(let o of p(r.readonly))t.add(o);this.fieldDependencies.set(e,t);for(let o of t)this.reverseDependencies.has(o)||this.reverseDependencies.set(o,new Set),this.reverseDependencies.get(o).add(e);}removeField(e){let r=this.fieldDependencies.get(e);if(r)for(let t of r){let o=this.reverseDependencies.get(t);o&&(o.delete(e),o.size===0&&this.reverseDependencies.delete(t));}this.fieldDependencies.delete(e);}getAffectedFields(e){let r=this.reverseDependencies.get(e);return r?Array.from(r):[]}getAffectedFieldsMultiple(e){let r=new Set;for(let t of e){let o=this.reverseDependencies.get(t);if(o)for(let i of o)r.add(i);}return Array.from(r)}getDependencies(e){let r=this.fieldDependencies.get(e);return r?Array.from(r):[]}hasDependencies(e){let r=this.fieldDependencies.get(e);return r!==void 0&&r.size>0}getAllFields(){return Array.from(this.fieldDependencies.keys())}getAllDependencyPaths(){return Array.from(this.reverseDependencies.keys())}clear(){this.fieldDependencies.clear(),this.reverseDependencies.clear();}get size(){return this.fieldDependencies.size}toDebugObject(){let e={},r={};for(let[t,o]of this.fieldDependencies)e[t]=Array.from(o);for(let[t,o]of this.reverseDependencies)r[t]=Array.from(o);return {fields:e,reverseDeps:r}}};var T=class{constructor(e){this.field=e,this.operator="exists",this.conditions=[];}equals(e){return this.operator="equals",this.value=e,this}notEquals(e){return this.operator="notEquals",this.value=e,this}greaterThan(e){return this.operator="greaterThan",this.value=e,this}lessThan(e){return this.operator="lessThan",this.value=e,this}greaterThanOrEqual(e){return this.operator="greaterThanOrEqual",this.value=e,this}lessThanOrEqual(e){return this.operator="lessThanOrEqual",this.value=e,this}contains(e){return this.operator="contains",this.value=e,this}notContains(e){return this.operator="notContains",this.value=e,this}in(e){return this.operator="in",this.value=e,this}notIn(e){return this.operator="notIn",this.value=e,this}matches(e){return this.operator="matches",this.value=e instanceof RegExp?e.source:e,this}exists(){return this.operator="exists",this.value=void 0,this}notExists(){return this.operator="notExists",this.value=void 0,this}and(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="and",this}or(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="or",this}build(){return {field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator}}evaluate(e){return I(this,e)}};function We(n){return new T(n)}function I(n,e){if(n.conditions&&n.conditions.length>0){let t=n.conditions.map(o=>I(o,e));return n.logicalOperator==="or"?t.some(o=>o):t.every(o=>o)}let r=de(e,n.field);switch(n.operator){case "equals":return r===n.value;case "notEquals":return r!==n.value;case "greaterThan":return typeof r=="number"&&typeof n.value=="number"&&r>n.value;case "lessThan":return typeof r=="number"&&typeof n.value=="number"&&r<n.value;case "greaterThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r>=n.value;case "lessThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r<=n.value;case "contains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?r.includes(n.value):false;case "notContains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?!r.includes(n.value):false;case "in":return Array.isArray(n.value)&&n.value.includes(r);case "notIn":return Array.isArray(n.value)&&!n.value.includes(r);case "matches":return typeof r!="string"||typeof n.value!="string"?false:new RegExp(n.value).test(r);case "exists":return r!=null;case "notExists":return r==null;default:return false}}function de(n,e){let r=e.split("."),t=n;for(let o of r)if(t&&typeof t=="object"&&o in t)t=t[o];else return;return t}function p(n){if(!n)return [];let e="build"in n?n.build():n,r=new Set;function t(o){if(o.field&&o.field.trim()!==""&&r.add(o.field),o.conditions&&o.conditions.length>0)for(let i of o.conditions)t(i);}return t(e),Array.from(r)}function Oe(n){let e=new Set;for(let r of Object.values(n))if(r){let t=p(r);for(let o of t)e.add(o);}return Array.from(e)}exports.ComponentRendererWrapper=fe;exports.ConditionDependencyGraph=S;exports.ConsoleAdapter=x;exports.DevelopmentAdapter=A;exports.IdGenerator=P;exports.LocalStorageAdapter=F;exports.RemoteAdapter=B;exports.RilayMonitor=w;exports.async=H;exports.combine=J;exports.combineSchemas=ne;exports.configureObject=he;exports.createErrorResult=W;exports.createStandardValidator=te;exports.createSuccessResult=D;exports.createValidationContext=O;exports.createValidationResult=C;exports.custom=Q;exports.deepClone=E;exports.destroyGlobalMonitoring=Be;exports.email=$;exports.ensureUnique=V;exports.evaluateCondition=I;exports.extractAllDependencies=Oe;exports.extractConditionDependencies=p;exports.getGlobalMonitor=Me;exports.getSchemaInfo=X;exports.hasSchemaTypes=Y;exports.hasUnifiedValidation=re;exports.initializeMonitoring=Ve;exports.isStandardSchema=c;exports.isValidationRule=oe;exports.max=j;exports.maxLength=z;exports.mergeInto=me;exports.min=K;exports.minLength=q;exports.normalizeToArray=ye;exports.normalizeValidationRules=ie;exports.number=_;exports.pattern=U;exports.required=N;exports.resolveRendererChildren=k;exports.ril=v;exports.url=L;exports.validateFormWithUnifiedConfig=ee;exports.validateRequired=ge;exports.validateWithStandardSchema=R;exports.validateWithUnifiedConfig=Z;exports.when=We;
1
+ 'use strict';function k(n,e){return typeof n=="function"?n(e):n}function fe({children:n,renderAs:e,renderer:r,name:t,props:o}){if(e==="children"||e===true){if(typeof n!="function")throw new Error(`When renderAs="children" is used, children must be a function that returns React elements for ${t}`);return n(o)}if(!r)throw new Error(`No renderer provided for ${t}`);if(typeof r!="function")throw new Error(`Renderer must be a function for ${t}`);let a={...o,children:k(n,o)};return r(a)}function me(n,e){return {...n,...e}}function V(n,e){let r=n.filter((t,o)=>n.indexOf(t)!==o);if(r.length>0)throw new Error(`Duplicate ${e} IDs: ${r.join(", ")}`)}function ge(n,e,r){if(n.filter(o=>e.some(i=>!o[i])).length>0)throw new Error(`Missing required fields in ${r}: ${e.join(", ")}`)}var P=class{constructor(){this.counters=new Map;}next(e){let r=this.counters.get(e)||0;return this.counters.set(e,r+1),`${e}-${r+1}`}reset(e){e?this.counters.delete(e):this.counters.clear();}};function ye(n){return Array.isArray(n)?n:[n]}function E(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n))return n.map(r=>E(r));let e={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=E(n[r]));return e}function he(n,e,r){let t={...n};for(let o in e)r&&!r.includes(o)||e[o]!==void 0&&(t[o]=e[o]);return t}var h=class extends Error{constructor(r,t,o){super(r);this.code=t;this.meta=o;this.name="RilayError";}},g=class extends h{constructor(e,r){super(e,"VALIDATION_ERROR",r),this.name="ValidationError";}};function m(n,e){let r={...n};for(let t in e){let o=e[t],i=r[t];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?r[t]=m(i,o):r[t]=o;}return r}var v=class n{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new n}addComponent(e,r){let t={id:e,type:e,...r},o=new n;return o.components=new Map(this.components),o.formRenderConfig={...this.formRenderConfig},o.workflowRenderConfig={...this.workflowRenderConfig},o.components.set(e,t),o}configure(e){let r=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],t=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],o={},i={};for(let[s,u]of Object.entries(e))r.includes(s)?o[s]=u:t.includes(s)&&(i[s]=u);let a=new n;return a.components=new Map(this.components),a.formRenderConfig=m(this.formRenderConfig,o),a.workflowRenderConfig=m(this.workflowRenderConfig,i),a}getFormRenderConfig(){return {...this.formRenderConfig}}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}getComponent(e){return this.components.get(e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){let r=new n;return r.components=new Map(this.components),r.formRenderConfig={...this.formRenderConfig},r.workflowRenderConfig={...this.workflowRenderConfig},r.components.delete(e),r}clear(){let e=new n;return e.formRenderConfig={...this.formRenderConfig},e.workflowRenderConfig={...this.workflowRenderConfig},e}clone(){let e=new n;return e.components=new Map(this.components),e.formRenderConfig=m({},this.formRenderConfig),e.workflowRenderConfig=m({},this.workflowRenderConfig),e}getStats(){let e=Array.from(this.components.values());return {total:e.length,byType:e.reduce((r,t)=>(r[t.type]=(r[t.type]||0)+1,r),{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,field:!!this.formRenderConfig.fieldRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNextButton:!!this.workflowRenderConfig.nextButtonRenderer,workflowPreviousButton:!!this.workflowRenderConfig.previousButtonRenderer,workflowSkipButton:!!this.workflowRenderConfig.skipButtonRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(l=>l.id);try{V(t,"component");}catch(l){e.push(l instanceof Error?l.message:String(l));}let o=r.filter(l=>!l.renderer);o.length>0&&e.push(`Components without renderer: ${o.map(l=>l.id).join(", ")}`);let i=Object.keys(this.formRenderConfig),a=Object.keys(this.workflowRenderConfig),s=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],u=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],d=i.filter(l=>!s.includes(l)),y=a.filter(l=>!u.includes(l));return d.length>0&&e.push(`Invalid form renderer keys: ${d.join(", ")}`),y.length>0&&e.push(`Invalid workflow renderer keys: ${y.join(", ")}`),e}async validateAsync(){let e=[],r=[],t=Array.from(this.components.values());try{let o=this.validate();e.push(...o);let i=t.map(async d=>d.renderer&&typeof d.renderer!="function"&&typeof d.renderer!="object"?`Component "${d.id}" has invalid renderer type: ${typeof d.renderer}`:((d.id.includes(" ")||d.id.includes("-"))&&r.push(`Component "${d.id}" uses non-standard naming (contains spaces or dashes)`),null)),s=(await Promise.all(i)).filter(d=>d!==null);e.push(...s),t.length>50&&r.push("Large number of components detected. Consider splitting configuration.");let u={isValid:e.length===0,errors:e,warnings:r.length>0?r:void 0};if(!u.isValid)throw new g("Ril configuration validation failed",{errors:e,warnings:r,componentCount:t.length});return u}catch(o){throw o instanceof g?o:new g("Unexpected error during async validation",{originalError:o instanceof Error?o.message:String(o)})}}};function C(n,e=[]){return {isValid:n,errors:[...e]}}function D(){return C(true,[])}function W(n,e,r){return C(false,[{message:n,code:e,path:r}])}function O(n={}){return {fieldId:n.fieldId,formId:n.formId,stepId:n.stepId,workflowId:n.workflowId,allFormData:n.allFormData||{},stepData:n.stepData||{},workflowData:n.workflowData||{}}}function N(n="This field is required"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>e===""||e==null||Array.isArray(e)&&e.length===0||typeof e=="object"&&Object.keys(e).length===0?{issues:[{message:n,path:void 0}]}:{value:e}}}}function $(n="Please enter a valid email address"){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Email must be a string"}]}:e.test(r)?{value:r}:{issues:[{message:n}]},types:{input:"",output:""}}}}function L(n="Please enter a valid URL"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{if(typeof e!="string")return {issues:[{message:"URL must be a string"}]};try{return new URL(e),{value:e}}catch{return {issues:[{message:n}]}}},types:{input:"",output:""}}}}function q(n,e){let r=`Must be at least ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length>=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function z(n,e){let r=`Must be no more than ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length<=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function U(n,e="Value does not match required pattern"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Value must be a string"}]}:n.test(r)?{value:r}:{issues:[{message:e}]},types:{input:"",output:""}}}}function _(n="Must be a valid number"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{let r=typeof e=="string"?Number(e):e;return typeof r!="number"||Number.isNaN(r)?{issues:[{message:n}]}:{value:r}},types:{input:0,output:0}}}}function K(n,e){let r=`Must be at least ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o>=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function j(n,e){let r=`Must be no more than ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o<=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function Q(n,e="Validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>{try{return n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function H(n,e="Async validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:async r=>{try{return await n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function J(...n){return {"~standard":{version:1,vendor:"rilaykit",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function c(n){return n!=null&&typeof n=="object"&&"~standard"in n&&n["~standard"]!==null&&typeof n["~standard"]=="object"&&n["~standard"].version===1&&typeof n["~standard"].vendor=="string"&&typeof n["~standard"].validate=="function"}async function R(n,e){if(!c(n))throw new Error("Invalid Standard Schema: missing ~standard property or invalid structure");try{let r=n["~standard"].validate(e);return r instanceof Promise&&(r=await r),r.issues?{isValid:!1,errors:r.issues.map(o=>({message:o.message,code:"VALIDATION_ERROR",path:G(o.path)}))}:{isValid:!0,errors:[],value:r.value}}catch(r){return {isValid:false,errors:[{message:r instanceof Error?r.message:"Validation failed",code:"VALIDATION_ERROR"}]}}}function G(n){if(!(!n||n.length===0))return n.map(e=>typeof e=="object"&&"key"in e?String(e.key):String(e)).join(".")}function X(n){if(!c(n))throw new Error("Invalid Standard Schema");return {vendor:n["~standard"].vendor,version:n["~standard"].version,hasTypes:!!n["~standard"].types}}function Y(n){return c(n)&&!!n["~standard"].types}async function Z(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Validation error",code:"VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}async function ee(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Form validation error",code:"FORM_VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}function re(n){return !!n.validate}function ne(...n){return {"~standard":{version:1,vendor:"rilaykit-combined",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function te(n,e="rilaykit"){return {"~standard":{version:1,vendor:e,validate:async r=>{try{let t=await n(r,{});return t.isValid?{value:r}:{issues:t.errors.map(i=>({message:i.message,path:i.path?[i.path]:void 0}))}}catch(t){return {issues:[{message:t instanceof Error?t.message:"Validation failed"}]}}}}}}function oe(n){return Array.isArray(n)?n.every(c):c(n)}function ie(n){return n?Array.isArray(n)?n:[n]:[]}var ae=0,M=()=>`event_${Date.now()}_${++ae}`,se=()=>`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,w=class{constructor(e,r){this.adapters=[];this.eventBuffer=[];this.config={bufferSize:100,flushInterval:5e3,sampleRate:1,enablePerformanceTracking:true,enableErrorTracking:true,enableMemoryTracking:false,...e},this.context={sessionId:se(),environment:"production",userAgent:typeof window<"u"?window.navigator?.userAgent:void 0,url:typeof window<"u"?window.location?.href:void 0,...r},this.profiler=new b,this.config.enabled&&this.startFlushTimer();}addAdapter(e){this.adapters.push(e);}removeAdapter(e){this.adapters=this.adapters.filter(r=>r.name!==e);}track(e,r,t,o,i="low"){if(!this.config.enabled||Math.random()>(this.config.sampleRate||1))return;let a={id:M(),type:e,timestamp:Date.now(),source:r,data:{...t,context:this.context},metrics:o,severity:i};if(o&&this.config.performanceThresholds&&this.checkPerformanceThresholds(a,o),this.eventBuffer.push(a),this.config.onEvent)try{this.config.onEvent(a);}catch(s){console.error("Error in monitoring event callback:",s);}this.eventBuffer.length>=(this.config.bufferSize||100)&&this.flush();}trackError(e,r,t){this.track("error",r,{message:e.message,name:e.name,stack:e.stack,context:t},void 0,"high");}getProfiler(){return this.profiler}updateContext(e){this.context={...this.context,...e};}async flush(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];if(this.eventBuffer=[],this.config.onBatch)try{this.config.onBatch(e);}catch(r){console.error("Error in monitoring batch callback:",r);}await Promise.all(this.adapters.map(async r=>{try{await r.send(e);}catch(t){console.error(`Error sending events to adapter ${r.name}:`,t),this.config.onError&&this.config.onError(t);}}));}async destroy(){this.flushTimer&&clearInterval(this.flushTimer),await this.flush(),await Promise.all(this.adapters.map(async e=>{if(e.flush)try{await e.flush();}catch(r){console.error(`Error flushing adapter ${e.name}:`,r);}}));}startFlushTimer(){this.config.flushInterval&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval));}checkPerformanceThresholds(e,r){let t=this.config.performanceThresholds;t.componentRenderTime&&e.type==="component_render"&&r.duration>t.componentRenderTime&&this.createPerformanceWarning("Component render time exceeded threshold",t.componentRenderTime,r.duration,"Consider memoizing component or optimizing render logic"),t.formValidationTime&&e.type==="form_validation"&&r.duration>t.formValidationTime&&this.createPerformanceWarning("Form validation time exceeded threshold",t.formValidationTime,r.duration,"Consider debouncing validation or optimizing validators"),t.workflowNavigationTime&&e.type==="workflow_navigation"&&r.duration>t.workflowNavigationTime&&this.createPerformanceWarning("Workflow navigation time exceeded threshold",t.workflowNavigationTime,r.duration,"Consider optimizing step transitions or condition evaluation"),t.memoryUsage&&r.memoryUsage&&r.memoryUsage>t.memoryUsage&&this.createPerformanceWarning("Memory usage exceeded threshold",t.memoryUsage,r.memoryUsage,"Check for memory leaks or optimize data structures"),t.reRenderCount&&r.reRenderCount&&r.reRenderCount>t.reRenderCount&&this.createPerformanceWarning("Component re-render count exceeded threshold",t.reRenderCount,r.reRenderCount,"Consider using React.memo or optimizing dependencies");}createPerformanceWarning(e,r,t,o){let i={id:M(),type:"performance_warning",timestamp:Date.now(),source:"rilay_monitor",data:{message:e,context:this.context},threshold:r,actualValue:t,recommendation:o,severity:"medium"};if(this.eventBuffer.push(i),this.config.onEvent)try{this.config.onEvent(i);}catch(a){console.error("Error in performance warning callback:",a);}}},b=class{constructor(){this.metrics=new Map;this.startTimes=new Map;}start(e,r={}){this.startTimes.set(e,performance.now()),this.metrics.set(e,{timestamp:Date.now(),duration:0,renderCount:r.renderCount||0,reRenderCount:r.reRenderCount||0,memoryUsage:this.getMemoryUsage()});}end(e){let r=this.startTimes.get(e);if(!r)return null;let t=performance.now()-r,o=this.metrics.get(e);if(!o)return null;let i={...o,duration:t,memoryUsage:this.getMemoryUsage()};return this.metrics.set(e,i),this.startTimes.delete(e),i}mark(e){typeof performance<"u"&&performance.mark&&performance.mark(e);}measure(e,r,t){if(typeof performance<"u"&&performance.measure){performance.measure(e,r,t);let o=performance.getEntriesByName(e,"measure");return o.length>0?o[o.length-1].duration:0}return 0}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){let e={};return this.metrics.forEach((r,t)=>{e[t]=r;}),e}clear(e){e?(this.metrics.delete(e),this.startTimes.delete(e)):(this.metrics.clear(),this.startTimes.clear());}getMemoryUsage(){if(typeof performance<"u"&&performance.memory)return performance.memory.usedJSHeapSize}},f=null;function Ve(n,e){return f&&f.destroy(),f=new w(n,e),f}function Me(){return f}async function Be(){f&&(await f.destroy(),f=null);}var x=class{constructor(e="info"){this.name="console";this.logLevel=e;}async send(e){for(let r of e)this.logEvent(r);}logEvent(e){let r={id:e.id,type:e.type,timestamp:new Date(e.timestamp).toISOString(),source:e.source,severity:e.severity,data:e.data,metrics:e.metrics};switch(e.severity){case "critical":case "high":this.shouldLog("error")&&console.error(`[Rilay Monitor] ${e.type}:`,r);break;case "medium":this.shouldLog("warn")&&console.warn(`[Rilay Monitor] ${e.type}:`,r);break;default:this.shouldLog("info")&&console.info(`[Rilay Monitor] ${e.type}:`,r);break}if(e.type==="performance_warning"&&this.shouldLog("warn")){let t=e;console.warn(`[Rilay Performance Warning] ${t.data.message}`,{threshold:t.threshold,actual:t.actualValue,recommendation:t.recommendation});}}shouldLog(e){let r=["debug","info","warn","error"],t=r.indexOf(this.logLevel);return r.indexOf(e)>=t}},B=class{constructor(e){this.name="remote";this.eventQueue=[];this.isProcessing=false;this.endpoint=e.endpoint,this.apiKey=e.apiKey,this.headers={"Content-Type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},...e.headers},this.batchSize=e.batchSize||50,this.retryAttempts=e.retryAttempts||3;}async send(e){this.eventQueue.push(...e),this.isProcessing||await this.processQueue();}async flush(){await this.processQueue();}configure(e){e.headers&&Object.assign(this.headers,e.headers);}async processQueue(){if(!(this.isProcessing||this.eventQueue.length===0)){this.isProcessing=true;try{for(;this.eventQueue.length>0;){let e=this.eventQueue.splice(0,this.batchSize);await this.sendBatch(e);}}finally{this.isProcessing=false;}}}async sendBatch(e){let r={events:e,timestamp:Date.now(),source:"rilay-monitoring"},t=null;for(let o=1;o<=this.retryAttempts;o++)try{let i=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(r)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return}catch(i){if(t=i,i instanceof Error&&i.message.includes("HTTP 4"))break;o<this.retryAttempts&&await this.delay(Math.pow(2,o)*1e3);}throw console.error("Failed to send monitoring events to remote endpoint:",t),t}delay(e){return new Promise(r=>setTimeout(r,e))}},F=class{constructor(e=1e3){this.name="localStorage";this.storageKey="rilay_monitoring_events";this.maxEvents=e;}async send(e){try{let o=[...this.getStoredEvents(),...e].slice(-this.maxEvents);localStorage.setItem(this.storageKey,JSON.stringify(o));}catch(r){console.error("Failed to store monitoring events:",r);}}async flush(){}getStoredEvents(){try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return console.error("Failed to retrieve stored monitoring events:",e),[]}}clearStoredEvents(){localStorage.removeItem(this.storageKey);}getEventCount(){return this.getStoredEvents().length}},A=class{constructor(){this.name="development";this.console=new x("debug");}async send(e){await this.console.send(e),this.logPerformanceSummary(e),this.logErrorSummary(e);}logPerformanceSummary(e){let r=e.filter(a=>a.metrics);if(r.length===0)return;console.group("[Rilay Performance Summary]");let t=r.reduce((a,s)=>a+(s.metrics?.duration||0),0)/r.length,o=Math.max(...r.map(a=>a.metrics?.duration||0));console.info(`Average duration: ${t.toFixed(2)}ms`),console.info(`Max duration: ${o.toFixed(2)}ms`);let i={};for(let a of r)i[a.type]||(i[a.type]=[]),i[a.type].push(a);for(let[a,s]of Object.entries(i)){let u=s.reduce((d,y)=>d+(y.metrics?.duration||0),0)/s.length;console.info(`${a}: ${u.toFixed(2)}ms avg (${s.length} events)`);}console.groupEnd();}logErrorSummary(e){let r=e.filter(o=>o.type==="error");if(r.length===0)return;console.group("[Rilay Error Summary]"),console.error(`${r.length} errors detected`);let t={};for(let o of r)t[o.source]=(t[o.source]||0)+1;for(let[o,i]of Object.entries(t))console.error(`${o}: ${i} errors`);console.groupEnd();}};var S=class{constructor(){this.fieldDependencies=new Map;this.reverseDependencies=new Map;}addField(e,r){if(!r){this.fieldDependencies.set(e,new Set);return}let t=new Set;if(r.visible)for(let o of p(r.visible))t.add(o);if(r.disabled)for(let o of p(r.disabled))t.add(o);if(r.required)for(let o of p(r.required))t.add(o);if(r.readonly)for(let o of p(r.readonly))t.add(o);this.fieldDependencies.set(e,t);for(let o of t)this.reverseDependencies.has(o)||this.reverseDependencies.set(o,new Set),this.reverseDependencies.get(o).add(e);}removeField(e){let r=this.fieldDependencies.get(e);if(r)for(let t of r){let o=this.reverseDependencies.get(t);o&&(o.delete(e),o.size===0&&this.reverseDependencies.delete(t));}this.fieldDependencies.delete(e);}getAffectedFields(e){let r=this.reverseDependencies.get(e);return r?Array.from(r):[]}getAffectedFieldsMultiple(e){let r=new Set;for(let t of e){let o=this.reverseDependencies.get(t);if(o)for(let i of o)r.add(i);}return Array.from(r)}getDependencies(e){let r=this.fieldDependencies.get(e);return r?Array.from(r):[]}hasDependencies(e){let r=this.fieldDependencies.get(e);return r!==void 0&&r.size>0}getAllFields(){return Array.from(this.fieldDependencies.keys())}getAllDependencyPaths(){return Array.from(this.reverseDependencies.keys())}clear(){this.fieldDependencies.clear(),this.reverseDependencies.clear();}get size(){return this.fieldDependencies.size}toDebugObject(){let e={},r={};for(let[t,o]of this.fieldDependencies)e[t]=Array.from(o);for(let[t,o]of this.reverseDependencies)r[t]=Array.from(o);return {fields:e,reverseDeps:r}}};var T=class{constructor(e){this.field=e,this.operator="exists",this.conditions=[];}equals(e){return this.operator="equals",this.value=e,this}notEquals(e){return this.operator="notEquals",this.value=e,this}greaterThan(e){return this.operator="greaterThan",this.value=e,this}lessThan(e){return this.operator="lessThan",this.value=e,this}greaterThanOrEqual(e){return this.operator="greaterThanOrEqual",this.value=e,this}lessThanOrEqual(e){return this.operator="lessThanOrEqual",this.value=e,this}contains(e){return this.operator="contains",this.value=e,this}notContains(e){return this.operator="notContains",this.value=e,this}in(e){return this.operator="in",this.value=e,this}notIn(e){return this.operator="notIn",this.value=e,this}matches(e){return this.operator="matches",this.value=e instanceof RegExp?e.source:e,this}exists(){return this.operator="exists",this.value=void 0,this}notExists(){return this.operator="notExists",this.value=void 0,this}and(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="and",this}or(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="or",this}build(){return {field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator}}evaluate(e){return I(this,e)}};function We(n){return new T(n)}function I(n,e){if(n.conditions&&n.conditions.length>0){let t=n.conditions.map(o=>I(o,e));return n.logicalOperator==="or"?t.some(o=>o):t.every(o=>o)}let r=de(e,n.field);switch(n.operator){case "equals":return r===n.value;case "notEquals":return r!==n.value;case "greaterThan":return typeof r=="number"&&typeof n.value=="number"&&r>n.value;case "lessThan":return typeof r=="number"&&typeof n.value=="number"&&r<n.value;case "greaterThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r>=n.value;case "lessThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r<=n.value;case "contains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?r.includes(n.value):false;case "notContains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?!r.includes(n.value):false;case "in":return Array.isArray(n.value)&&n.value.includes(r);case "notIn":return Array.isArray(n.value)&&!n.value.includes(r);case "matches":return typeof r!="string"||typeof n.value!="string"?false:new RegExp(n.value).test(r);case "exists":return r!=null;case "notExists":return r==null;default:return false}}function de(n,e){let r=e.split("."),t=n;for(let o of r)if(t&&typeof t=="object"&&o in t)t=t[o];else return;return t}function p(n){if(!n)return [];let e="build"in n?n.build():n,r=new Set;function t(o){if(o.field&&o.field.trim()!==""&&r.add(o.field),o.conditions&&o.conditions.length>0)for(let i of o.conditions)t(i);}return t(e),Array.from(r)}function Oe(n){let e=new Set;for(let r of Object.values(n))if(r){let t=p(r);for(let o of t)e.add(o);}return Array.from(e)}exports.ComponentRendererWrapper=fe;exports.ConditionDependencyGraph=S;exports.ConsoleAdapter=x;exports.DevelopmentAdapter=A;exports.IdGenerator=P;exports.LocalStorageAdapter=F;exports.RemoteAdapter=B;exports.RilayMonitor=w;exports.async=H;exports.combine=J;exports.combineSchemas=ne;exports.configureObject=he;exports.createErrorResult=W;exports.createStandardValidator=te;exports.createSuccessResult=D;exports.createValidationContext=O;exports.createValidationResult=C;exports.custom=Q;exports.deepClone=E;exports.destroyGlobalMonitoring=Be;exports.email=$;exports.ensureUnique=V;exports.evaluateCondition=I;exports.extractAllDependencies=Oe;exports.extractConditionDependencies=p;exports.getGlobalMonitor=Me;exports.getSchemaInfo=X;exports.hasSchemaTypes=Y;exports.hasUnifiedValidation=re;exports.initializeMonitoring=Ve;exports.isStandardSchema=c;exports.isValidationRule=oe;exports.max=j;exports.maxLength=z;exports.mergeInto=me;exports.min=K;exports.minLength=q;exports.normalizeToArray=ye;exports.normalizeValidationRules=ie;exports.number=_;exports.pattern=U;exports.required=N;exports.resolveRendererChildren=k;exports.ril=v;exports.url=L;exports.validateFormWithUnifiedConfig=ee;exports.validateRequired=ge;exports.validateWithStandardSchema=R;exports.validateWithUnifiedConfig=Z;exports.when=We;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- function k(n,e){return typeof n=="function"?n(e):n}function fe({children:n,renderAs:e,renderer:r,name:t,props:o}){if(e==="children"||e===true){if(typeof n!="function")throw new Error(`When renderAs="children" is used, children must be a function that returns React elements for ${t}`);return n(o)}if(!r)throw new Error(`No renderer provided for ${t}`);if(typeof r!="function")throw new Error(`Renderer must be a function for ${t}`);let a={...o,children:k(n,o)};return r(a)}function me(n,e){return {...n,...e}}function V(n,e){let r=n.filter((t,o)=>n.indexOf(t)!==o);if(r.length>0)throw new Error(`Duplicate ${e} IDs: ${r.join(", ")}`)}function ge(n,e,r){if(n.filter(o=>e.some(i=>!o[i])).length>0)throw new Error(`Missing required fields in ${r}: ${e.join(", ")}`)}var P=class{constructor(){this.counters=new Map;}next(e){let r=this.counters.get(e)||0;return this.counters.set(e,r+1),`${e}-${r+1}`}reset(e){e?this.counters.delete(e):this.counters.clear();}};function ye(n){return Array.isArray(n)?n:[n]}function E(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n))return n.map(r=>E(r));let e={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=E(n[r]));return e}function he(n,e,r){let t={...n};for(let o in e)r&&!r.includes(o)||e[o]!==void 0&&(t[o]=e[o]);return t}var h=class extends Error{constructor(r,t,o){super(r);this.code=t;this.meta=o;this.name="RilayError";}},g=class extends h{constructor(e,r){super(e,"VALIDATION_ERROR",r),this.name="ValidationError";}};function m(n,e){let r={...n};for(let t in e){let o=e[t],i=r[t];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?r[t]=m(i,o):r[t]=o;}return r}var v=class n{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new n}addComponent(e,r){let t={id:e,type:e,...r},o=new n;return o.components=new Map(this.components),o.formRenderConfig={...this.formRenderConfig},o.workflowRenderConfig={...this.workflowRenderConfig},o.components.set(e,t),o}configure(e){let r=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],t=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],o={},i={};for(let[s,u]of Object.entries(e))r.includes(s)?o[s]=u:t.includes(s)&&(i[s]=u);let a=new n;return a.components=new Map(this.components),a.formRenderConfig=m(this.formRenderConfig,o),a.workflowRenderConfig=m(this.workflowRenderConfig,i),a}getFormRenderConfig(){return {...this.formRenderConfig}}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}getComponent(e){return this.components.get(e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){let r=new n;return r.components=new Map(this.components),r.formRenderConfig={...this.formRenderConfig},r.workflowRenderConfig={...this.workflowRenderConfig},r.components.delete(e),r}clear(){let e=new n;return e.formRenderConfig={...this.formRenderConfig},e.workflowRenderConfig={...this.workflowRenderConfig},e}clone(){let e=new n;return e.components=new Map(this.components),e.formRenderConfig=m({},this.formRenderConfig),e.workflowRenderConfig=m({},this.workflowRenderConfig),e}getStats(){let e=Array.from(this.components.values());return {total:e.length,byType:e.reduce((r,t)=>(r[t.type]=(r[t.type]||0)+1,r),{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,field:!!this.formRenderConfig.fieldRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNextButton:!!this.workflowRenderConfig.nextButtonRenderer,workflowPreviousButton:!!this.workflowRenderConfig.previousButtonRenderer,workflowSkipButton:!!this.workflowRenderConfig.skipButtonRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(l=>l.id);try{V(t,"component");}catch(l){e.push(l instanceof Error?l.message:String(l));}let o=r.filter(l=>!l.renderer);o.length>0&&e.push(`Components without renderer: ${o.map(l=>l.id).join(", ")}`);let i=Object.keys(this.formRenderConfig),a=Object.keys(this.workflowRenderConfig),s=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],u=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],d=i.filter(l=>!s.includes(l)),y=a.filter(l=>!u.includes(l));return d.length>0&&e.push(`Invalid form renderer keys: ${d.join(", ")}`),y.length>0&&e.push(`Invalid workflow renderer keys: ${y.join(", ")}`),e}async validateAsync(){let e=[],r=[],t=Array.from(this.components.values());try{let o=this.validate();e.push(...o);let i=t.map(async d=>d.renderer&&typeof d.renderer!="function"&&typeof d.renderer!="object"?`Component "${d.id}" has invalid renderer type: ${typeof d.renderer}`:((d.id.includes(" ")||d.id.includes("-"))&&r.push(`Component "${d.id}" uses non-standard naming (contains spaces or dashes)`),null)),s=(await Promise.all(i)).filter(d=>d!==null);e.push(...s),t.length>50&&r.push("Large number of components detected. Consider splitting configuration.");let u={isValid:e.length===0,errors:e,warnings:r.length>0?r:void 0};if(!u.isValid)throw new g("Ril configuration validation failed",{errors:e,warnings:r,componentCount:t.length});return u}catch(o){throw o instanceof g?o:new g("Unexpected error during async validation",{originalError:o instanceof Error?o.message:String(o)})}}};function C(n,e=[]){return {isValid:n,errors:[...e]}}function D(){return C(true,[])}function W(n,e,r){return C(false,[{message:n,code:e,path:r}])}function O(n={}){return {fieldId:n.fieldId,formId:n.formId,stepId:n.stepId,workflowId:n.workflowId,allFormData:n.allFormData||{},stepData:n.stepData||{},workflowData:n.workflowData||{}}}function N(n="This field is required"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>e===""||e==null||Array.isArray(e)&&e.length===0||typeof e=="object"&&Object.keys(e).length===0?{issues:[{message:n,path:void 0}]}:{value:e}}}}function $(n="Please enter a valid email address"){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Email must be a string"}]}:e.test(r)?{value:r}:{issues:[{message:n}]},types:{input:"",output:""}}}}function L(n="Please enter a valid URL"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{if(typeof e!="string")return {issues:[{message:"URL must be a string"}]};try{return new URL(e),{value:e}}catch{return {issues:[{message:n}]}}},types:{input:"",output:""}}}}function q(n,e){let r=`Must be at least ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length>=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function z(n,e){let r=`Must be no more than ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length<=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function U(n,e="Value does not match required pattern"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Value must be a string"}]}:n.test(r)?{value:r}:{issues:[{message:e}]},types:{input:"",output:""}}}}function _(n="Must be a valid number"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{let r=typeof e=="string"?Number(e):e;return typeof r!="number"||Number.isNaN(r)?{issues:[{message:n}]}:{value:r}},types:{input:0,output:0}}}}function K(n,e){let r=`Must be at least ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o>=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function j(n,e){let r=`Must be no more than ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o<=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function Q(n,e="Validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>{try{return n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function H(n,e="Async validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:async r=>{try{return await n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function J(...n){return {"~standard":{version:1,vendor:"rilaykit",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function c(n){return n!=null&&typeof n=="object"&&"~standard"in n&&n["~standard"]!==null&&typeof n["~standard"]=="object"&&n["~standard"].version===1&&typeof n["~standard"].vendor=="string"&&typeof n["~standard"].validate=="function"}async function R(n,e){if(!c(n))throw new Error("Invalid Standard Schema: missing ~standard property or invalid structure");try{let r=n["~standard"].validate(e);return r instanceof Promise&&(r=await r),r.issues?{isValid:!1,errors:r.issues.map(o=>({message:o.message,code:"VALIDATION_ERROR",path:G(o.path)}))}:{isValid:!0,errors:[],value:r.value}}catch(r){return {isValid:false,errors:[{message:r instanceof Error?r.message:"Validation failed",code:"VALIDATION_ERROR"}]}}}function G(n){if(!(!n||n.length===0))return n.map(e=>typeof e=="object"&&"key"in e?String(e.key):String(e)).join(".")}function X(n){if(!c(n))throw new Error("Invalid Standard Schema");return {vendor:n["~standard"].vendor,version:n["~standard"].version,hasTypes:!!n["~standard"].types}}function Y(n){return c(n)&&!!n["~standard"].types}async function Z(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Validation error",code:"VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}async function ee(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Form validation error",code:"FORM_VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}function re(n){return !!n.validate}function ne(...n){return {"~standard":{version:1,vendor:"rilaykit-combined",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function te(n,e="rilaykit"){return {"~standard":{version:1,vendor:e,validate:async r=>{try{let t=await n(r,{});return t.isValid?{value:r}:{issues:t.errors.map(i=>({message:i.message,path:i.path?[i.path]:void 0}))}}catch(t){return {issues:[{message:t instanceof Error?t.message:"Validation failed"}]}}}}}}function oe(n){return Array.isArray(n)?n.every(c):c(n)}function ie(n){return n?Array.isArray(n)?n:[n]:[]}var ae=0,M=()=>`event_${Date.now()}_${++ae}`,se=()=>`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,w=class{constructor(e,r){this.adapters=[];this.eventBuffer=[];this.config={bufferSize:100,flushInterval:5e3,sampleRate:1,enablePerformanceTracking:true,enableErrorTracking:true,enableMemoryTracking:false,...e},this.context={sessionId:se(),environment:"production",userAgent:typeof window<"u"?window.navigator?.userAgent:void 0,url:typeof window<"u"?window.location?.href:void 0,...r},this.profiler=new b,this.config.enabled&&this.startFlushTimer();}addAdapter(e){this.adapters.push(e);}removeAdapter(e){this.adapters=this.adapters.filter(r=>r.name!==e);}track(e,r,t,o,i="low"){if(!this.config.enabled||Math.random()>(this.config.sampleRate||1))return;let a={id:M(),type:e,timestamp:Date.now(),source:r,data:{...t,context:this.context},metrics:o,severity:i};if(o&&this.config.performanceThresholds&&this.checkPerformanceThresholds(a,o),this.eventBuffer.push(a),this.config.onEvent)try{this.config.onEvent(a);}catch(s){console.error("Error in monitoring event callback:",s);}this.eventBuffer.length>=(this.config.bufferSize||100)&&this.flush();}trackError(e,r,t){this.track("error",r,{message:e.message,name:e.name,stack:e.stack,context:t},void 0,"high");}getProfiler(){return this.profiler}updateContext(e){this.context={...this.context,...e};}async flush(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];if(this.eventBuffer=[],this.config.onBatch)try{this.config.onBatch(e);}catch(r){console.error("Error in monitoring batch callback:",r);}await Promise.all(this.adapters.map(async r=>{try{await r.send(e);}catch(t){console.error(`Error sending events to adapter ${r.name}:`,t),this.config.onError&&this.config.onError(t);}}));}async destroy(){this.flushTimer&&clearInterval(this.flushTimer),await this.flush(),await Promise.all(this.adapters.map(async e=>{if(e.flush)try{await e.flush();}catch(r){console.error(`Error flushing adapter ${e.name}:`,r);}}));}startFlushTimer(){this.config.flushInterval&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval));}checkPerformanceThresholds(e,r){let t=this.config.performanceThresholds;t.componentRenderTime&&e.type==="component_render"&&r.duration>t.componentRenderTime&&this.createPerformanceWarning("Component render time exceeded threshold",t.componentRenderTime,r.duration,"Consider memoizing component or optimizing render logic"),t.formValidationTime&&e.type==="form_validation"&&r.duration>t.formValidationTime&&this.createPerformanceWarning("Form validation time exceeded threshold",t.formValidationTime,r.duration,"Consider debouncing validation or optimizing validators"),t.workflowNavigationTime&&e.type==="workflow_navigation"&&r.duration>t.workflowNavigationTime&&this.createPerformanceWarning("Workflow navigation time exceeded threshold",t.workflowNavigationTime,r.duration,"Consider optimizing step transitions or condition evaluation"),t.memoryUsage&&r.memoryUsage&&r.memoryUsage>t.memoryUsage&&this.createPerformanceWarning("Memory usage exceeded threshold",t.memoryUsage,r.memoryUsage,"Check for memory leaks or optimize data structures"),t.reRenderCount&&r.reRenderCount&&r.reRenderCount>t.reRenderCount&&this.createPerformanceWarning("Component re-render count exceeded threshold",t.reRenderCount,r.reRenderCount,"Consider using React.memo or optimizing dependencies");}createPerformanceWarning(e,r,t,o){let i={id:M(),type:"performance_warning",timestamp:Date.now(),source:"rilay_monitor",data:{message:e,context:this.context},threshold:r,actualValue:t,recommendation:o,severity:"medium"};if(this.eventBuffer.push(i),this.config.onEvent)try{this.config.onEvent(i);}catch(a){console.error("Error in performance warning callback:",a);}}},b=class{constructor(){this.metrics=new Map;this.startTimes=new Map;}start(e,r={}){this.startTimes.set(e,performance.now()),this.metrics.set(e,{timestamp:Date.now(),duration:0,renderCount:r.renderCount||0,reRenderCount:r.reRenderCount||0,memoryUsage:this.getMemoryUsage()});}end(e){let r=this.startTimes.get(e);if(!r)return null;let t=performance.now()-r,o=this.metrics.get(e);if(!o)return null;let i={...o,duration:t,memoryUsage:this.getMemoryUsage()};return this.metrics.set(e,i),this.startTimes.delete(e),i}mark(e){typeof performance<"u"&&performance.mark&&performance.mark(e);}measure(e,r,t){if(typeof performance<"u"&&performance.measure){performance.measure(e,r,t);let o=performance.getEntriesByName(e,"measure");return o.length>0?o[o.length-1].duration:0}return 0}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){let e={};return this.metrics.forEach((r,t)=>{e[t]=r;}),e}clear(e){e?(this.metrics.delete(e),this.startTimes.delete(e)):(this.metrics.clear(),this.startTimes.clear());}getMemoryUsage(){if(typeof performance<"u"&&performance.memory)return performance.memory.usedJSHeapSize}},f=null;function Ve(n,e){return f&&f.destroy(),f=new w(n,e),f}function Me(){return f}async function Be(){f&&(await f.destroy(),f=null);}var x=class{constructor(e="info"){this.name="console";this.logLevel=e;}async send(e){for(let r of e)this.logEvent(r);}logEvent(e){let r={id:e.id,type:e.type,timestamp:new Date(e.timestamp).toISOString(),source:e.source,severity:e.severity,data:e.data,metrics:e.metrics};switch(e.severity){case "critical":case "high":this.shouldLog("error")&&console.error(`[Rilay Monitor] ${e.type}:`,r);break;case "medium":this.shouldLog("warn")&&console.warn(`[Rilay Monitor] ${e.type}:`,r);break;default:this.shouldLog("info")&&console.info(`[Rilay Monitor] ${e.type}:`,r);break}if(e.type==="performance_warning"&&this.shouldLog("warn")){let t=e;console.warn(`[Rilay Performance Warning] ${t.data.message}`,{threshold:t.threshold,actual:t.actualValue,recommendation:t.recommendation});}}shouldLog(e){let r=["debug","info","warn","error"],t=r.indexOf(this.logLevel);return r.indexOf(e)>=t}},B=class{constructor(e){this.name="remote";this.eventQueue=[];this.isProcessing=false;this.endpoint=e.endpoint,this.apiKey=e.apiKey,this.headers={"Content-Type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},...e.headers},this.batchSize=e.batchSize||50,this.retryAttempts=e.retryAttempts||3;}async send(e){this.eventQueue.push(...e),this.isProcessing||await this.processQueue();}async flush(){await this.processQueue();}configure(e){e.headers&&Object.assign(this.headers,e.headers);}async processQueue(){if(!(this.isProcessing||this.eventQueue.length===0)){this.isProcessing=true;try{for(;this.eventQueue.length>0;){let e=this.eventQueue.splice(0,this.batchSize);await this.sendBatch(e);}}finally{this.isProcessing=false;}}}async sendBatch(e){let r={events:e,timestamp:Date.now(),source:"rilay-monitoring"},t=null;for(let o=1;o<=this.retryAttempts;o++)try{let i=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(r)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return}catch(i){if(t=i,i instanceof Error&&i.message.includes("HTTP 4"))break;o<this.retryAttempts&&await this.delay(2**o*1e3);}throw console.error("Failed to send monitoring events to remote endpoint:",t),t}delay(e){return new Promise(r=>setTimeout(r,e))}},F=class{constructor(e=1e3){this.name="localStorage";this.storageKey="rilay_monitoring_events";this.maxEvents=e;}async send(e){try{let o=[...this.getStoredEvents(),...e].slice(-this.maxEvents);localStorage.setItem(this.storageKey,JSON.stringify(o));}catch(r){console.error("Failed to store monitoring events:",r);}}async flush(){}getStoredEvents(){try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return console.error("Failed to retrieve stored monitoring events:",e),[]}}clearStoredEvents(){localStorage.removeItem(this.storageKey);}getEventCount(){return this.getStoredEvents().length}},A=class{constructor(){this.name="development";this.console=new x("debug");}async send(e){await this.console.send(e),this.logPerformanceSummary(e),this.logErrorSummary(e);}logPerformanceSummary(e){let r=e.filter(a=>a.metrics);if(r.length===0)return;console.group("[Rilay Performance Summary]");let t=r.reduce((a,s)=>a+(s.metrics?.duration||0),0)/r.length,o=Math.max(...r.map(a=>a.metrics?.duration||0));console.info(`Average duration: ${t.toFixed(2)}ms`),console.info(`Max duration: ${o.toFixed(2)}ms`);let i={};for(let a of r)i[a.type]||(i[a.type]=[]),i[a.type].push(a);for(let[a,s]of Object.entries(i)){let u=s.reduce((d,y)=>d+(y.metrics?.duration||0),0)/s.length;console.info(`${a}: ${u.toFixed(2)}ms avg (${s.length} events)`);}console.groupEnd();}logErrorSummary(e){let r=e.filter(o=>o.type==="error");if(r.length===0)return;console.group("[Rilay Error Summary]"),console.error(`${r.length} errors detected`);let t={};for(let o of r)t[o.source]=(t[o.source]||0)+1;for(let[o,i]of Object.entries(t))console.error(`${o}: ${i} errors`);console.groupEnd();}};var S=class{constructor(){this.fieldDependencies=new Map;this.reverseDependencies=new Map;}addField(e,r){if(!r){this.fieldDependencies.set(e,new Set);return}let t=new Set;if(r.visible)for(let o of p(r.visible))t.add(o);if(r.disabled)for(let o of p(r.disabled))t.add(o);if(r.required)for(let o of p(r.required))t.add(o);if(r.readonly)for(let o of p(r.readonly))t.add(o);this.fieldDependencies.set(e,t);for(let o of t)this.reverseDependencies.has(o)||this.reverseDependencies.set(o,new Set),this.reverseDependencies.get(o).add(e);}removeField(e){let r=this.fieldDependencies.get(e);if(r)for(let t of r){let o=this.reverseDependencies.get(t);o&&(o.delete(e),o.size===0&&this.reverseDependencies.delete(t));}this.fieldDependencies.delete(e);}getAffectedFields(e){let r=this.reverseDependencies.get(e);return r?Array.from(r):[]}getAffectedFieldsMultiple(e){let r=new Set;for(let t of e){let o=this.reverseDependencies.get(t);if(o)for(let i of o)r.add(i);}return Array.from(r)}getDependencies(e){let r=this.fieldDependencies.get(e);return r?Array.from(r):[]}hasDependencies(e){let r=this.fieldDependencies.get(e);return r!==void 0&&r.size>0}getAllFields(){return Array.from(this.fieldDependencies.keys())}getAllDependencyPaths(){return Array.from(this.reverseDependencies.keys())}clear(){this.fieldDependencies.clear(),this.reverseDependencies.clear();}get size(){return this.fieldDependencies.size}toDebugObject(){let e={},r={};for(let[t,o]of this.fieldDependencies)e[t]=Array.from(o);for(let[t,o]of this.reverseDependencies)r[t]=Array.from(o);return {fields:e,reverseDeps:r}}};var T=class{constructor(e){this.field=e,this.operator="exists",this.conditions=[];}equals(e){return this.operator="equals",this.value=e,this}notEquals(e){return this.operator="notEquals",this.value=e,this}greaterThan(e){return this.operator="greaterThan",this.value=e,this}lessThan(e){return this.operator="lessThan",this.value=e,this}greaterThanOrEqual(e){return this.operator="greaterThanOrEqual",this.value=e,this}lessThanOrEqual(e){return this.operator="lessThanOrEqual",this.value=e,this}contains(e){return this.operator="contains",this.value=e,this}notContains(e){return this.operator="notContains",this.value=e,this}in(e){return this.operator="in",this.value=e,this}notIn(e){return this.operator="notIn",this.value=e,this}matches(e){return this.operator="matches",this.value=e instanceof RegExp?e.source:e,this}exists(){return this.operator="exists",this.value=void 0,this}notExists(){return this.operator="notExists",this.value=void 0,this}and(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="and",this}or(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="or",this}build(){return {field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator}}evaluate(e){return I(this,e)}};function We(n){return new T(n)}function I(n,e){if(n.conditions&&n.conditions.length>0){let t=n.conditions.map(o=>I(o,e));return n.logicalOperator==="or"?t.some(o=>o):t.every(o=>o)}let r=de(e,n.field);switch(n.operator){case "equals":return r===n.value;case "notEquals":return r!==n.value;case "greaterThan":return typeof r=="number"&&typeof n.value=="number"&&r>n.value;case "lessThan":return typeof r=="number"&&typeof n.value=="number"&&r<n.value;case "greaterThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r>=n.value;case "lessThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r<=n.value;case "contains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?r.includes(n.value):false;case "notContains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?!r.includes(n.value):false;case "in":return Array.isArray(n.value)&&n.value.includes(r);case "notIn":return Array.isArray(n.value)&&!n.value.includes(r);case "matches":return typeof r!="string"||typeof n.value!="string"?false:new RegExp(n.value).test(r);case "exists":return r!=null;case "notExists":return r==null;default:return false}}function de(n,e){let r=e.split("."),t=n;for(let o of r)if(t&&typeof t=="object"&&o in t)t=t[o];else return;return t}function p(n){if(!n)return [];let e="build"in n?n.build():n,r=new Set;function t(o){if(o.field&&o.field.trim()!==""&&r.add(o.field),o.conditions&&o.conditions.length>0)for(let i of o.conditions)t(i);}return t(e),Array.from(r)}function Oe(n){let e=new Set;for(let r of Object.values(n))if(r){let t=p(r);for(let o of t)e.add(o);}return Array.from(e)}export{fe as ComponentRendererWrapper,S as ConditionDependencyGraph,x as ConsoleAdapter,A as DevelopmentAdapter,P as IdGenerator,F as LocalStorageAdapter,B as RemoteAdapter,w as RilayMonitor,H as async,J as combine,ne as combineSchemas,he as configureObject,W as createErrorResult,te as createStandardValidator,D as createSuccessResult,O as createValidationContext,C as createValidationResult,Q as custom,E as deepClone,Be as destroyGlobalMonitoring,$ as email,V as ensureUnique,I as evaluateCondition,Oe as extractAllDependencies,p as extractConditionDependencies,Me as getGlobalMonitor,X as getSchemaInfo,Y as hasSchemaTypes,re as hasUnifiedValidation,Ve as initializeMonitoring,c as isStandardSchema,oe as isValidationRule,j as max,z as maxLength,me as mergeInto,K as min,q as minLength,ye as normalizeToArray,ie as normalizeValidationRules,_ as number,U as pattern,N as required,k as resolveRendererChildren,v as ril,L as url,ee as validateFormWithUnifiedConfig,ge as validateRequired,R as validateWithStandardSchema,Z as validateWithUnifiedConfig,We as when};
1
+ function k(n,e){return typeof n=="function"?n(e):n}function fe({children:n,renderAs:e,renderer:r,name:t,props:o}){if(e==="children"||e===true){if(typeof n!="function")throw new Error(`When renderAs="children" is used, children must be a function that returns React elements for ${t}`);return n(o)}if(!r)throw new Error(`No renderer provided for ${t}`);if(typeof r!="function")throw new Error(`Renderer must be a function for ${t}`);let a={...o,children:k(n,o)};return r(a)}function me(n,e){return {...n,...e}}function V(n,e){let r=n.filter((t,o)=>n.indexOf(t)!==o);if(r.length>0)throw new Error(`Duplicate ${e} IDs: ${r.join(", ")}`)}function ge(n,e,r){if(n.filter(o=>e.some(i=>!o[i])).length>0)throw new Error(`Missing required fields in ${r}: ${e.join(", ")}`)}var P=class{constructor(){this.counters=new Map;}next(e){let r=this.counters.get(e)||0;return this.counters.set(e,r+1),`${e}-${r+1}`}reset(e){e?this.counters.delete(e):this.counters.clear();}};function ye(n){return Array.isArray(n)?n:[n]}function E(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n))return n.map(r=>E(r));let e={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=E(n[r]));return e}function he(n,e,r){let t={...n};for(let o in e)r&&!r.includes(o)||e[o]!==void 0&&(t[o]=e[o]);return t}var h=class extends Error{constructor(r,t,o){super(r);this.code=t;this.meta=o;this.name="RilayError";}},g=class extends h{constructor(e,r){super(e,"VALIDATION_ERROR",r),this.name="ValidationError";}};function m(n,e){let r={...n};for(let t in e){let o=e[t],i=r[t];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?r[t]=m(i,o):r[t]=o;}return r}var v=class n{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new n}addComponent(e,r){let t={id:e,type:e,...r},o=new n;return o.components=new Map(this.components),o.formRenderConfig={...this.formRenderConfig},o.workflowRenderConfig={...this.workflowRenderConfig},o.components.set(e,t),o}configure(e){let r=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],t=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],o={},i={};for(let[s,u]of Object.entries(e))r.includes(s)?o[s]=u:t.includes(s)&&(i[s]=u);let a=new n;return a.components=new Map(this.components),a.formRenderConfig=m(this.formRenderConfig,o),a.workflowRenderConfig=m(this.workflowRenderConfig,i),a}getFormRenderConfig(){return {...this.formRenderConfig}}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}getComponent(e){return this.components.get(e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){let r=new n;return r.components=new Map(this.components),r.formRenderConfig={...this.formRenderConfig},r.workflowRenderConfig={...this.workflowRenderConfig},r.components.delete(e),r}clear(){let e=new n;return e.formRenderConfig={...this.formRenderConfig},e.workflowRenderConfig={...this.workflowRenderConfig},e}clone(){let e=new n;return e.components=new Map(this.components),e.formRenderConfig=m({},this.formRenderConfig),e.workflowRenderConfig=m({},this.workflowRenderConfig),e}getStats(){let e=Array.from(this.components.values());return {total:e.length,byType:e.reduce((r,t)=>(r[t.type]=(r[t.type]||0)+1,r),{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,field:!!this.formRenderConfig.fieldRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNextButton:!!this.workflowRenderConfig.nextButtonRenderer,workflowPreviousButton:!!this.workflowRenderConfig.previousButtonRenderer,workflowSkipButton:!!this.workflowRenderConfig.skipButtonRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(l=>l.id);try{V(t,"component");}catch(l){e.push(l instanceof Error?l.message:String(l));}let o=r.filter(l=>!l.renderer);o.length>0&&e.push(`Components without renderer: ${o.map(l=>l.id).join(", ")}`);let i=Object.keys(this.formRenderConfig),a=Object.keys(this.workflowRenderConfig),s=["rowRenderer","bodyRenderer","submitButtonRenderer","fieldRenderer"],u=["stepperRenderer","nextButtonRenderer","previousButtonRenderer","skipButtonRenderer"],d=i.filter(l=>!s.includes(l)),y=a.filter(l=>!u.includes(l));return d.length>0&&e.push(`Invalid form renderer keys: ${d.join(", ")}`),y.length>0&&e.push(`Invalid workflow renderer keys: ${y.join(", ")}`),e}async validateAsync(){let e=[],r=[],t=Array.from(this.components.values());try{let o=this.validate();e.push(...o);let i=t.map(async d=>d.renderer&&typeof d.renderer!="function"&&typeof d.renderer!="object"?`Component "${d.id}" has invalid renderer type: ${typeof d.renderer}`:((d.id.includes(" ")||d.id.includes("-"))&&r.push(`Component "${d.id}" uses non-standard naming (contains spaces or dashes)`),null)),s=(await Promise.all(i)).filter(d=>d!==null);e.push(...s),t.length>50&&r.push("Large number of components detected. Consider splitting configuration.");let u={isValid:e.length===0,errors:e,warnings:r.length>0?r:void 0};if(!u.isValid)throw new g("Ril configuration validation failed",{errors:e,warnings:r,componentCount:t.length});return u}catch(o){throw o instanceof g?o:new g("Unexpected error during async validation",{originalError:o instanceof Error?o.message:String(o)})}}};function C(n,e=[]){return {isValid:n,errors:[...e]}}function D(){return C(true,[])}function W(n,e,r){return C(false,[{message:n,code:e,path:r}])}function O(n={}){return {fieldId:n.fieldId,formId:n.formId,stepId:n.stepId,workflowId:n.workflowId,allFormData:n.allFormData||{},stepData:n.stepData||{},workflowData:n.workflowData||{}}}function N(n="This field is required"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>e===""||e==null||Array.isArray(e)&&e.length===0||typeof e=="object"&&Object.keys(e).length===0?{issues:[{message:n,path:void 0}]}:{value:e}}}}function $(n="Please enter a valid email address"){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Email must be a string"}]}:e.test(r)?{value:r}:{issues:[{message:n}]},types:{input:"",output:""}}}}function L(n="Please enter a valid URL"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{if(typeof e!="string")return {issues:[{message:"URL must be a string"}]};try{return new URL(e),{value:e}}catch{return {issues:[{message:n}]}}},types:{input:"",output:""}}}}function q(n,e){let r=`Must be at least ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length>=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function z(n,e){let r=`Must be no more than ${n} characters long`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>typeof t!="string"?{issues:[{message:"Value must be a string"}]}:t.length<=n?{value:t}:{issues:[{message:e||r}]},types:{input:"",output:""}}}}function U(n,e="Value does not match required pattern"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>typeof r!="string"?{issues:[{message:"Value must be a string"}]}:n.test(r)?{value:r}:{issues:[{message:e}]},types:{input:"",output:""}}}}function _(n="Must be a valid number"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>{let r=typeof e=="string"?Number(e):e;return typeof r!="number"||Number.isNaN(r)?{issues:[{message:n}]}:{value:r}},types:{input:0,output:0}}}}function K(n,e){let r=`Must be at least ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o>=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function j(n,e){let r=`Must be no more than ${n}`;return {"~standard":{version:1,vendor:"rilaykit",validate:t=>{let o=typeof t=="string"?Number(t):t;return typeof o!="number"||Number.isNaN(o)?{issues:[{message:"Value must be a number"}]}:o<=n?{value:o}:{issues:[{message:e||r}]}},types:{input:0,output:0}}}}function Q(n,e="Validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:r=>{try{return n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function H(n,e="Async validation failed"){return {"~standard":{version:1,vendor:"rilaykit",validate:async r=>{try{return await n(r)?{value:r}:{issues:[{message:e}]}}catch(t){return {issues:[{message:t instanceof Error?t.message:e}]}}}}}}function J(...n){return {"~standard":{version:1,vendor:"rilaykit",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function c(n){return n!=null&&typeof n=="object"&&"~standard"in n&&n["~standard"]!==null&&typeof n["~standard"]=="object"&&n["~standard"].version===1&&typeof n["~standard"].vendor=="string"&&typeof n["~standard"].validate=="function"}async function R(n,e){if(!c(n))throw new Error("Invalid Standard Schema: missing ~standard property or invalid structure");try{let r=n["~standard"].validate(e);return r instanceof Promise&&(r=await r),r.issues?{isValid:!1,errors:r.issues.map(o=>({message:o.message,code:"VALIDATION_ERROR",path:G(o.path)}))}:{isValid:!0,errors:[],value:r.value}}catch(r){return {isValid:false,errors:[{message:r instanceof Error?r.message:"Validation failed",code:"VALIDATION_ERROR"}]}}}function G(n){if(!(!n||n.length===0))return n.map(e=>typeof e=="object"&&"key"in e?String(e.key):String(e)).join(".")}function X(n){if(!c(n))throw new Error("Invalid Standard Schema");return {vendor:n["~standard"].vendor,version:n["~standard"].version,hasTypes:!!n["~standard"].types}}function Y(n){return c(n)&&!!n["~standard"].types}async function Z(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Validation error",code:"VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}async function ee(n,e,r){if(!n.validate)return {isValid:true,errors:[]};let t=Array.isArray(n.validate)?n.validate:[n.validate],o=[];for(let i of t){if(!c(i)){o.push({message:"Invalid validation rule: must implement Standard Schema interface",code:"INVALID_SCHEMA"});continue}try{let a=await R(i,e);a.isValid||o.push(...a.errors);}catch(a){o.push({message:a instanceof Error?a.message:"Form validation error",code:"FORM_VALIDATION_ERROR"});}}return {isValid:o.length===0,errors:o}}function re(n){return !!n.validate}function ne(...n){return {"~standard":{version:1,vendor:"rilaykit-combined",validate:async e=>{let r=[],t=e;for(let o of n){let i=o["~standard"].validate(e);i instanceof Promise&&(i=await i),i.issues?r.push(...i.issues):t=i.value;}return r.length>0?{issues:r}:{value:t}}}}}function te(n,e="rilaykit"){return {"~standard":{version:1,vendor:e,validate:async r=>{try{let t=await n(r,{});return t.isValid?{value:r}:{issues:t.errors.map(i=>({message:i.message,path:i.path?[i.path]:void 0}))}}catch(t){return {issues:[{message:t instanceof Error?t.message:"Validation failed"}]}}}}}}function oe(n){return Array.isArray(n)?n.every(c):c(n)}function ie(n){return n?Array.isArray(n)?n:[n]:[]}var ae=0,M=()=>`event_${Date.now()}_${++ae}`,se=()=>`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,w=class{constructor(e,r){this.adapters=[];this.eventBuffer=[];this.config={bufferSize:100,flushInterval:5e3,sampleRate:1,enablePerformanceTracking:true,enableErrorTracking:true,enableMemoryTracking:false,...e},this.context={sessionId:se(),environment:"production",userAgent:typeof window<"u"?window.navigator?.userAgent:void 0,url:typeof window<"u"?window.location?.href:void 0,...r},this.profiler=new b,this.config.enabled&&this.startFlushTimer();}addAdapter(e){this.adapters.push(e);}removeAdapter(e){this.adapters=this.adapters.filter(r=>r.name!==e);}track(e,r,t,o,i="low"){if(!this.config.enabled||Math.random()>(this.config.sampleRate||1))return;let a={id:M(),type:e,timestamp:Date.now(),source:r,data:{...t,context:this.context},metrics:o,severity:i};if(o&&this.config.performanceThresholds&&this.checkPerformanceThresholds(a,o),this.eventBuffer.push(a),this.config.onEvent)try{this.config.onEvent(a);}catch(s){console.error("Error in monitoring event callback:",s);}this.eventBuffer.length>=(this.config.bufferSize||100)&&this.flush();}trackError(e,r,t){this.track("error",r,{message:e.message,name:e.name,stack:e.stack,context:t},void 0,"high");}getProfiler(){return this.profiler}updateContext(e){this.context={...this.context,...e};}async flush(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];if(this.eventBuffer=[],this.config.onBatch)try{this.config.onBatch(e);}catch(r){console.error("Error in monitoring batch callback:",r);}await Promise.all(this.adapters.map(async r=>{try{await r.send(e);}catch(t){console.error(`Error sending events to adapter ${r.name}:`,t),this.config.onError&&this.config.onError(t);}}));}async destroy(){this.flushTimer&&clearInterval(this.flushTimer),await this.flush(),await Promise.all(this.adapters.map(async e=>{if(e.flush)try{await e.flush();}catch(r){console.error(`Error flushing adapter ${e.name}:`,r);}}));}startFlushTimer(){this.config.flushInterval&&this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flush();},this.config.flushInterval));}checkPerformanceThresholds(e,r){let t=this.config.performanceThresholds;t.componentRenderTime&&e.type==="component_render"&&r.duration>t.componentRenderTime&&this.createPerformanceWarning("Component render time exceeded threshold",t.componentRenderTime,r.duration,"Consider memoizing component or optimizing render logic"),t.formValidationTime&&e.type==="form_validation"&&r.duration>t.formValidationTime&&this.createPerformanceWarning("Form validation time exceeded threshold",t.formValidationTime,r.duration,"Consider debouncing validation or optimizing validators"),t.workflowNavigationTime&&e.type==="workflow_navigation"&&r.duration>t.workflowNavigationTime&&this.createPerformanceWarning("Workflow navigation time exceeded threshold",t.workflowNavigationTime,r.duration,"Consider optimizing step transitions or condition evaluation"),t.memoryUsage&&r.memoryUsage&&r.memoryUsage>t.memoryUsage&&this.createPerformanceWarning("Memory usage exceeded threshold",t.memoryUsage,r.memoryUsage,"Check for memory leaks or optimize data structures"),t.reRenderCount&&r.reRenderCount&&r.reRenderCount>t.reRenderCount&&this.createPerformanceWarning("Component re-render count exceeded threshold",t.reRenderCount,r.reRenderCount,"Consider using React.memo or optimizing dependencies");}createPerformanceWarning(e,r,t,o){let i={id:M(),type:"performance_warning",timestamp:Date.now(),source:"rilay_monitor",data:{message:e,context:this.context},threshold:r,actualValue:t,recommendation:o,severity:"medium"};if(this.eventBuffer.push(i),this.config.onEvent)try{this.config.onEvent(i);}catch(a){console.error("Error in performance warning callback:",a);}}},b=class{constructor(){this.metrics=new Map;this.startTimes=new Map;}start(e,r={}){this.startTimes.set(e,performance.now()),this.metrics.set(e,{timestamp:Date.now(),duration:0,renderCount:r.renderCount||0,reRenderCount:r.reRenderCount||0,memoryUsage:this.getMemoryUsage()});}end(e){let r=this.startTimes.get(e);if(!r)return null;let t=performance.now()-r,o=this.metrics.get(e);if(!o)return null;let i={...o,duration:t,memoryUsage:this.getMemoryUsage()};return this.metrics.set(e,i),this.startTimes.delete(e),i}mark(e){typeof performance<"u"&&performance.mark&&performance.mark(e);}measure(e,r,t){if(typeof performance<"u"&&performance.measure){performance.measure(e,r,t);let o=performance.getEntriesByName(e,"measure");return o.length>0?o[o.length-1].duration:0}return 0}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){let e={};return this.metrics.forEach((r,t)=>{e[t]=r;}),e}clear(e){e?(this.metrics.delete(e),this.startTimes.delete(e)):(this.metrics.clear(),this.startTimes.clear());}getMemoryUsage(){if(typeof performance<"u"&&performance.memory)return performance.memory.usedJSHeapSize}},f=null;function Ve(n,e){return f&&f.destroy(),f=new w(n,e),f}function Me(){return f}async function Be(){f&&(await f.destroy(),f=null);}var x=class{constructor(e="info"){this.name="console";this.logLevel=e;}async send(e){for(let r of e)this.logEvent(r);}logEvent(e){let r={id:e.id,type:e.type,timestamp:new Date(e.timestamp).toISOString(),source:e.source,severity:e.severity,data:e.data,metrics:e.metrics};switch(e.severity){case "critical":case "high":this.shouldLog("error")&&console.error(`[Rilay Monitor] ${e.type}:`,r);break;case "medium":this.shouldLog("warn")&&console.warn(`[Rilay Monitor] ${e.type}:`,r);break;default:this.shouldLog("info")&&console.info(`[Rilay Monitor] ${e.type}:`,r);break}if(e.type==="performance_warning"&&this.shouldLog("warn")){let t=e;console.warn(`[Rilay Performance Warning] ${t.data.message}`,{threshold:t.threshold,actual:t.actualValue,recommendation:t.recommendation});}}shouldLog(e){let r=["debug","info","warn","error"],t=r.indexOf(this.logLevel);return r.indexOf(e)>=t}},B=class{constructor(e){this.name="remote";this.eventQueue=[];this.isProcessing=false;this.endpoint=e.endpoint,this.apiKey=e.apiKey,this.headers={"Content-Type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},...e.headers},this.batchSize=e.batchSize||50,this.retryAttempts=e.retryAttempts||3;}async send(e){this.eventQueue.push(...e),this.isProcessing||await this.processQueue();}async flush(){await this.processQueue();}configure(e){e.headers&&Object.assign(this.headers,e.headers);}async processQueue(){if(!(this.isProcessing||this.eventQueue.length===0)){this.isProcessing=true;try{for(;this.eventQueue.length>0;){let e=this.eventQueue.splice(0,this.batchSize);await this.sendBatch(e);}}finally{this.isProcessing=false;}}}async sendBatch(e){let r={events:e,timestamp:Date.now(),source:"rilay-monitoring"},t=null;for(let o=1;o<=this.retryAttempts;o++)try{let i=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(r)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return}catch(i){if(t=i,i instanceof Error&&i.message.includes("HTTP 4"))break;o<this.retryAttempts&&await this.delay(Math.pow(2,o)*1e3);}throw console.error("Failed to send monitoring events to remote endpoint:",t),t}delay(e){return new Promise(r=>setTimeout(r,e))}},F=class{constructor(e=1e3){this.name="localStorage";this.storageKey="rilay_monitoring_events";this.maxEvents=e;}async send(e){try{let o=[...this.getStoredEvents(),...e].slice(-this.maxEvents);localStorage.setItem(this.storageKey,JSON.stringify(o));}catch(r){console.error("Failed to store monitoring events:",r);}}async flush(){}getStoredEvents(){try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return console.error("Failed to retrieve stored monitoring events:",e),[]}}clearStoredEvents(){localStorage.removeItem(this.storageKey);}getEventCount(){return this.getStoredEvents().length}},A=class{constructor(){this.name="development";this.console=new x("debug");}async send(e){await this.console.send(e),this.logPerformanceSummary(e),this.logErrorSummary(e);}logPerformanceSummary(e){let r=e.filter(a=>a.metrics);if(r.length===0)return;console.group("[Rilay Performance Summary]");let t=r.reduce((a,s)=>a+(s.metrics?.duration||0),0)/r.length,o=Math.max(...r.map(a=>a.metrics?.duration||0));console.info(`Average duration: ${t.toFixed(2)}ms`),console.info(`Max duration: ${o.toFixed(2)}ms`);let i={};for(let a of r)i[a.type]||(i[a.type]=[]),i[a.type].push(a);for(let[a,s]of Object.entries(i)){let u=s.reduce((d,y)=>d+(y.metrics?.duration||0),0)/s.length;console.info(`${a}: ${u.toFixed(2)}ms avg (${s.length} events)`);}console.groupEnd();}logErrorSummary(e){let r=e.filter(o=>o.type==="error");if(r.length===0)return;console.group("[Rilay Error Summary]"),console.error(`${r.length} errors detected`);let t={};for(let o of r)t[o.source]=(t[o.source]||0)+1;for(let[o,i]of Object.entries(t))console.error(`${o}: ${i} errors`);console.groupEnd();}};var S=class{constructor(){this.fieldDependencies=new Map;this.reverseDependencies=new Map;}addField(e,r){if(!r){this.fieldDependencies.set(e,new Set);return}let t=new Set;if(r.visible)for(let o of p(r.visible))t.add(o);if(r.disabled)for(let o of p(r.disabled))t.add(o);if(r.required)for(let o of p(r.required))t.add(o);if(r.readonly)for(let o of p(r.readonly))t.add(o);this.fieldDependencies.set(e,t);for(let o of t)this.reverseDependencies.has(o)||this.reverseDependencies.set(o,new Set),this.reverseDependencies.get(o).add(e);}removeField(e){let r=this.fieldDependencies.get(e);if(r)for(let t of r){let o=this.reverseDependencies.get(t);o&&(o.delete(e),o.size===0&&this.reverseDependencies.delete(t));}this.fieldDependencies.delete(e);}getAffectedFields(e){let r=this.reverseDependencies.get(e);return r?Array.from(r):[]}getAffectedFieldsMultiple(e){let r=new Set;for(let t of e){let o=this.reverseDependencies.get(t);if(o)for(let i of o)r.add(i);}return Array.from(r)}getDependencies(e){let r=this.fieldDependencies.get(e);return r?Array.from(r):[]}hasDependencies(e){let r=this.fieldDependencies.get(e);return r!==void 0&&r.size>0}getAllFields(){return Array.from(this.fieldDependencies.keys())}getAllDependencyPaths(){return Array.from(this.reverseDependencies.keys())}clear(){this.fieldDependencies.clear(),this.reverseDependencies.clear();}get size(){return this.fieldDependencies.size}toDebugObject(){let e={},r={};for(let[t,o]of this.fieldDependencies)e[t]=Array.from(o);for(let[t,o]of this.reverseDependencies)r[t]=Array.from(o);return {fields:e,reverseDeps:r}}};var T=class{constructor(e){this.field=e,this.operator="exists",this.conditions=[];}equals(e){return this.operator="equals",this.value=e,this}notEquals(e){return this.operator="notEquals",this.value=e,this}greaterThan(e){return this.operator="greaterThan",this.value=e,this}lessThan(e){return this.operator="lessThan",this.value=e,this}greaterThanOrEqual(e){return this.operator="greaterThanOrEqual",this.value=e,this}lessThanOrEqual(e){return this.operator="lessThanOrEqual",this.value=e,this}contains(e){return this.operator="contains",this.value=e,this}notContains(e){return this.operator="notContains",this.value=e,this}in(e){return this.operator="in",this.value=e,this}notIn(e){return this.operator="notIn",this.value=e,this}matches(e){return this.operator="matches",this.value=e instanceof RegExp?e.source:e,this}exists(){return this.operator="exists",this.value=void 0,this}notExists(){return this.operator="notExists",this.value=void 0,this}and(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="and",this}or(e){let r="build"in e?e.build():e,t={field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator};return this.field="",this.operator="exists",this.value=void 0,this.conditions=[t,r],this.logicalOperator="or",this}build(){return {field:this.field,operator:this.operator,value:this.value,conditions:this.conditions,logicalOperator:this.logicalOperator}}evaluate(e){return I(this,e)}};function We(n){return new T(n)}function I(n,e){if(n.conditions&&n.conditions.length>0){let t=n.conditions.map(o=>I(o,e));return n.logicalOperator==="or"?t.some(o=>o):t.every(o=>o)}let r=de(e,n.field);switch(n.operator){case "equals":return r===n.value;case "notEquals":return r!==n.value;case "greaterThan":return typeof r=="number"&&typeof n.value=="number"&&r>n.value;case "lessThan":return typeof r=="number"&&typeof n.value=="number"&&r<n.value;case "greaterThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r>=n.value;case "lessThanOrEqual":return typeof r=="number"&&typeof n.value=="number"&&r<=n.value;case "contains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?r.includes(n.value):false;case "notContains":return typeof r=="string"&&typeof n.value=="string"||Array.isArray(r)?!r.includes(n.value):false;case "in":return Array.isArray(n.value)&&n.value.includes(r);case "notIn":return Array.isArray(n.value)&&!n.value.includes(r);case "matches":return typeof r!="string"||typeof n.value!="string"?false:new RegExp(n.value).test(r);case "exists":return r!=null;case "notExists":return r==null;default:return false}}function de(n,e){let r=e.split("."),t=n;for(let o of r)if(t&&typeof t=="object"&&o in t)t=t[o];else return;return t}function p(n){if(!n)return [];let e="build"in n?n.build():n,r=new Set;function t(o){if(o.field&&o.field.trim()!==""&&r.add(o.field),o.conditions&&o.conditions.length>0)for(let i of o.conditions)t(i);}return t(e),Array.from(r)}function Oe(n){let e=new Set;for(let r of Object.values(n))if(r){let t=p(r);for(let o of t)e.add(o);}return Array.from(e)}export{fe as ComponentRendererWrapper,S as ConditionDependencyGraph,x as ConsoleAdapter,A as DevelopmentAdapter,P as IdGenerator,F as LocalStorageAdapter,B as RemoteAdapter,w as RilayMonitor,H as async,J as combine,ne as combineSchemas,he as configureObject,W as createErrorResult,te as createStandardValidator,D as createSuccessResult,O as createValidationContext,C as createValidationResult,Q as custom,E as deepClone,Be as destroyGlobalMonitoring,$ as email,V as ensureUnique,I as evaluateCondition,Oe as extractAllDependencies,p as extractConditionDependencies,Me as getGlobalMonitor,X as getSchemaInfo,Y as hasSchemaTypes,re as hasUnifiedValidation,Ve as initializeMonitoring,c as isStandardSchema,oe as isValidationRule,j as max,z as maxLength,me as mergeInto,K as min,q as minLength,ye as normalizeToArray,ie as normalizeValidationRules,_ as number,U as pattern,N as required,k as resolveRendererChildren,v as ril,L as url,ee as validateFormWithUnifiedConfig,ge as validateRequired,R as validateWithStandardSchema,Z as validateWithUnifiedConfig,We as when};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rilaykit/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "private": false,
5
5
  "description": "Core types, configurations, and utilities for the RilayKit form library",
6
6
  "main": "dist/index.js",