@rilaykit/core 0.1.1-alpha.1 → 0.1.2
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/LICENSE +21 -0
- package/README.md +182 -0
- package/dist/index.d.mts +1256 -431
- package/dist/index.d.ts +1256 -431
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +26 -9
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var zod=require('zod');var y=class o{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new o}addComponent(e,r){let t=r.id||`${r.type}-${e}-${Date.now()}`,n={id:t,subType:e,...r};return this.components.set(t,n),this}setRowRenderer(e){return this.formRenderConfig={...this.formRenderConfig,rowRenderer:e},this}setBodyRenderer(e){return this.formRenderConfig={...this.formRenderConfig,bodyRenderer:e},this}setSubmitButtonRenderer(e){return this.formRenderConfig={...this.formRenderConfig,submitButtonRenderer:e},this}setFormRenderConfig(e){return this.formRenderConfig=e,this}getFormRenderConfig(){return {...this.formRenderConfig}}setStepperRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,stepperRenderer:e},this}setWorkflowNavigationRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,navigationRenderer:e},this}setWorkflowRenderConfig(e){return this.workflowRenderConfig=e,this}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}setRenderConfig(e){return this.setFormRenderConfig(e)}getComponent(e){return this.components.get(e)}getComponentsByType(e){return Array.from(this.components.values()).filter(r=>r.type===e)}getComponentsBySubType(e){return Array.from(this.components.values()).filter(r=>r.subType===e)}getComponentsByCategory(e){return Array.from(this.components.values()).filter(r=>r.category===e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){return this.components.delete(e)}clear(){this.components.clear();}export(){return Object.fromEntries(this.components)}import(e){for(let[r,t]of Object.entries(e))this.components.set(r,t);return this}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),{}),bySubType:e.reduce((r,t)=>(r[t.subType]=(r[t.subType]||0)+1,r),{}),byCategory:e.reduce((r,t)=>{let n=t.category||"uncategorized";return r[n]=(r[n]||0)+1,r},{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNavigation:!!this.workflowRenderConfig.navigationRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(s=>s.id),n=t.filter((s,i)=>t.indexOf(s)!==i);n.length>0&&e.push(`Duplicate component IDs found: ${n.join(", ")}`);let a=r.filter(s=>!s.renderer);return a.length>0&&e.push(`Components without renderer: ${a.map(s=>s.id).join(", ")}`),e}};var m=o=>async e=>{try{return await o.parseAsync(e),{isValid:!0,errors:[]}}catch(r){return r&&typeof r=="object"&&"errors"in r&&Array.isArray(r.errors)?{isValid:false,errors:r.errors.map(t=>({code:t.code,message:t.message,path:t.path?t.path.map(String):[]}))}:{isValid:false,errors:[{code:"unknown",message:r instanceof Error?r.message:"Unknown validation error"}]}}},w=o=>async(e,r,t)=>{try{let n=await o(e,r);return n===!0?{isValid:!0,errors:[]}:n===!1?{isValid:!1,errors:[{code:"validation_failed",message:"Validation failed"}]}:{isValid:!1,errors:[{code:"validation_failed",message:String(n)}]}}catch(n){return {isValid:false,errors:[{code:"validation_error",message:n instanceof Error?n.message:"Validation error"}]}}},b=(o,e="all")=>async(r,t,n)=>{let a=await Promise.all(o.map(l=>l(r,t,n)));if(e==="all"){let l=a.flatMap(u=>u.errors),c=a.flatMap(u=>u.warnings||[]);return {isValid:a.every(u=>u.isValid),errors:l,warnings:c.length>0?c:void 0}}if(a.some(l=>l.isValid)){let l=a.flatMap(c=>c.warnings||[]);return {isValid:true,errors:[],warnings:l.length>0?l:void 0}}return {isValid:false,errors:a.flatMap(l=>l.errors)}},v=(o,e)=>async(r,t,n)=>o(r,t)?e(r,t,n):{isValid:true,errors:[]},P={required:(o="This field is required")=>w(e=>e==null||e===""?o:!0),email:(o="Invalid email format")=>m(zod.z.string().email(o)),minLength:(o,e)=>m(zod.z.string().min(o,e||`Minimum ${o} characters required`)),maxLength:(o,e)=>m(zod.z.string().max(o,e||`Maximum ${o} characters allowed`)),pattern:(o,e="Invalid format")=>m(zod.z.string().regex(o,e)),numberRange:(o,e,r)=>{let t=zod.z.number();return o!==void 0&&(t=t.min(o,r||`Value must be at least ${o}`)),e!==void 0&&(t=t.max(e,r||`Value must be at most ${e}`)),m(t)},url:(o="Invalid URL format")=>m(zod.z.string().url(o)),phoneNumber:(o="Invalid phone number format")=>m(zod.z.string().regex(/^\+?[\d\s\-\(\)]+$/,o)),asyncValidation:(o,e=300)=>{let r=new Map;return (t,n,a)=>new Promise(s=>{let i=`${n.fieldId}-${JSON.stringify(t)}`;r.has(i)&&clearTimeout(r.get(i));let l=setTimeout(async()=>{try{let c=await o(t,n);s(c===!0?{isValid:!0,errors:[]}:{isValid:!1,errors:[{code:"async_validation_failed",message:typeof c=="string"?c:"Async validation failed"}]});}catch(c){s({isValid:false,errors:[{code:"async_validation_error",message:c instanceof Error?c.message:"Async validation error"}]});}finally{r.delete(i);}},e);r.set(i,l);})}},k=(o,e=[],r)=>({isValid:o,errors:e,warnings:r}),V=(o,e,r)=>({code:o,message:e,path:r});var g=class{constructor(){this.name="localStorage";}async save(e,r){try{localStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to localStorage: ${t}`)}}async load(e){try{let r=localStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from localStorage: ${r}`)}}async remove(e){try{localStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from localStorage: ${r}`)}}async exists(e){return localStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},p=class{constructor(){this.name="sessionStorage";}async save(e,r){try{sessionStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to sessionStorage: ${t}`)}}async load(e){try{let r=sessionStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from sessionStorage: ${r}`)}}async remove(e){try{sessionStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from sessionStorage: ${r}`)}}async exists(e){return sessionStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},f=class{constructor(){this.name="memory";this.storage=new Map;}async save(e,r){this.storage.set(e,{...r});}async load(e){let r=this.storage.get(e);return r?{...r}:null}async remove(e){this.storage.delete(e);}async exists(e){return this.storage.has(e)}async list(e){let r=Array.from(this.storage.keys());return e?r.filter(t=>t.includes(e)):r}clear(){this.storage.clear();}},h=class{constructor(e,r=[]){this.primary=e;this.fallbacks=r;this.name="composite";}async save(e,r){let t=[this.primary,...this.fallbacks];for(let n of t)try{await n.save(e,r);return}catch(a){console.warn(`Failed to save with ${n.name}:`,a);}throw new Error("All persistence adapters failed to save")}async load(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{let n=await t.load(e);if(n)return n}catch(n){console.warn(`Failed to load with ${t.name}:`,n);}return null}async remove(e){let r=[this.primary,...this.fallbacks],t=[];for(let n of r)try{await n.remove(e);}catch(a){t.push(a);}if(t.length===r.length)throw new Error(`All adapters failed to remove: ${t.map(n=>n.message).join(", ")}`)}async exists(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{if(await t.exists(e))return !0}catch(n){console.warn(`Failed to check existence with ${t.name}:`,n);}return false}async list(e){try{return await this.primary.list?.(e)||[]}catch(r){console.warn("Failed to list with primary adapter:",r);for(let t of this.fallbacks)try{return await t.list?.(e)||[]}catch(n){console.warn(`Failed to list with fallback ${t.name}:`,n);}return []}}};var E={localStorage(o={}){return {adapter:new g,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},sessionStorage(o={}){return {adapter:new p,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},memory(o={}){return {adapter:new f,debounceMs:0,autoSave:true,saveOnStepChange:true,...o}},custom(o,e={}){return {adapter:o,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...e}}};function T(o,e,r={}){let t=e||new f;return {adapter:{name:`resilient-${o.name}`,async save(a,s){try{await o.save(a,s);}catch(i){console.warn("Primary persistence failed, using fallback:",i),await t.save(a,s);}},async load(a){try{let s=await o.load(a);if(s)return s}catch(s){console.warn("Primary persistence load failed, trying fallback:",s);}return await t.load(a)},async remove(a){let s=[];try{await o.remove(a);}catch(i){s.push(i);}try{await t.remove(a);}catch(i){s.push(i);}if(s.length===2)throw new Error(`Both adapters failed: ${s.map(i=>i.message).join(", ")}`)},async exists(a){try{if(await o.exists(a))return !0}catch(s){console.warn("Primary persistence exists check failed:",s);}try{return await t.exists(a)}catch(s){return console.warn("Fallback persistence exists check failed:",s),false}},async list(a){try{return await o.list?.(a)||[]}catch(s){console.warn("Primary persistence list failed:",s);try{return await t.list?.(a)||[]}catch(i){return console.warn("Fallback persistence list failed:",i),[]}}}},debounceMs:1e3,autoSave:true,saveOnStepChange:true,maxRetries:3,retryDelayMs:1e3,...r}}exports.CompositeAdapter=h;exports.LocalStorageAdapter=g;exports.MemoryAdapter=f;exports.SessionStorageAdapter=p;exports.combineValidators=b;exports.commonValidators=P;exports.createConditionalValidator=v;exports.createCustomValidator=w;exports.createResilientPersistence=T;exports.createValidationError=V;exports.createValidationResult=k;exports.createZodValidator=m;exports.persistence=E;exports.ril=y;
|
|
1
|
+
'use strict';function P(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:P(n,o)};return r(a)}function ge(n,e){return {...n,...e}}function F(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 ye(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 E=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 he(n){return Array.isArray(n)?n:[n]}function V(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=>V(r));let e={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=V(n[r]));return e}function ve(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","repeatableRenderer","repeatableItemRenderer"],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,repeatable:!!this.formRenderConfig.repeatableRenderer,repeatableItem:!!this.formRenderConfig.repeatableItemRenderer,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{F(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","repeatableRenderer","repeatableItemRenderer"],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 R(n){return n==null?true:typeof n=="string"?n.trim().length===0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.keys(n).length===0:false}function C(n,e=[]){return {isValid:n,errors:[...e]}}function W(){return C(true,[])}function O(n,e,r){return C(false,[{message:n,code:e,path:r}])}function N(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="This field is required"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>R(e)?{issues:[{message:n,path:void 0}]}:{value:e}}}}function L(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 q(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 U(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 _(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 K(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 j(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 Q(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 H(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 J(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 G(...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 b(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:X(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 X(n){if(!(!n||n.length===0))return n.map(e=>typeof e=="object"&&"key"in e?String(e.key):String(e)).join(".")}function Y(n){if(!c(n))throw new Error("Invalid Standard Schema");return {vendor:n["~standard"].vendor,version:n["~standard"].version,hasTypes:!!n["~standard"].types}}function Z(n){return c(n)&&!!n["~standard"].types}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 b(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 re(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 b(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 ne(n){return !!n.validate}function te(...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 oe(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 ie(n){return Array.isArray(n)?n.every(c):c(n)}function ae(n){return n?Array.isArray(n)?n:[n]:[]}var se=0,M=()=>`event_${Date.now()}_${++se}`,de=()=>`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:de(),environment:"production",userAgent:typeof window<"u"?window.navigator?.userAgent:void 0,url:typeof window<"u"?window.location?.href:void 0,...r},this.profiler=new x,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);}}},x=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}},p=null;function Me(n,e){return p&&p.destroy(),p=new w(n,e),p}function Be(){return p}async function Ie(){p&&(await p.destroy(),p=null);}var S=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))}},I=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 S("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 T=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 f(r.visible))t.add(o);if(r.disabled)for(let o of f(r.disabled))t.add(o);if(r.required)for(let o of f(r.required))t.add(o);if(r.readonly)for(let o of f(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 k=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 D(this,e)}};function Ne(n){return new k(n)}function D(n,e){if(n.conditions&&n.conditions.length>0){let t=n.conditions.map(o=>D(o,e));return n.logicalOperator==="or"?t.some(o=>o):t.every(o=>o)}let r=le(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 le(n,e){if(e in n)return 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 f(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 $e(n){let e=new Set;for(let r of Object.values(n))if(r){let t=f(r);for(let o of t)e.add(o);}return Array.from(e)}exports.ComponentRendererWrapper=fe;exports.ConditionDependencyGraph=T;exports.ConsoleAdapter=S;exports.DevelopmentAdapter=A;exports.IdGenerator=E;exports.LocalStorageAdapter=I;exports.RemoteAdapter=B;exports.RilayMonitor=w;exports.async=J;exports.combine=G;exports.combineSchemas=te;exports.configureObject=ve;exports.createErrorResult=O;exports.createStandardValidator=oe;exports.createSuccessResult=W;exports.createValidationContext=N;exports.createValidationResult=C;exports.custom=H;exports.deepClone=V;exports.destroyGlobalMonitoring=Ie;exports.email=L;exports.ensureUnique=F;exports.evaluateCondition=D;exports.extractAllDependencies=$e;exports.extractConditionDependencies=f;exports.getGlobalMonitor=Be;exports.getSchemaInfo=Y;exports.hasSchemaTypes=Z;exports.hasUnifiedValidation=ne;exports.initializeMonitoring=Me;exports.isEmptyValue=R;exports.isStandardSchema=c;exports.isValidationRule=ie;exports.max=Q;exports.maxLength=z;exports.mergeInto=ge;exports.min=j;exports.minLength=U;exports.normalizeToArray=he;exports.normalizeValidationRules=ae;exports.number=K;exports.pattern=_;exports.required=$;exports.resolveRendererChildren=P;exports.ril=v;exports.url=q;exports.validateFormWithUnifiedConfig=re;exports.validateRequired=ye;exports.validateWithStandardSchema=b;exports.validateWithUnifiedConfig=ee;exports.when=Ne;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {z}from'zod';var y=class o{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new o}addComponent(e,r){let t=r.id||`${r.type}-${e}-${Date.now()}`,n={id:t,subType:e,...r};return this.components.set(t,n),this}setRowRenderer(e){return this.formRenderConfig={...this.formRenderConfig,rowRenderer:e},this}setBodyRenderer(e){return this.formRenderConfig={...this.formRenderConfig,bodyRenderer:e},this}setSubmitButtonRenderer(e){return this.formRenderConfig={...this.formRenderConfig,submitButtonRenderer:e},this}setFormRenderConfig(e){return this.formRenderConfig=e,this}getFormRenderConfig(){return {...this.formRenderConfig}}setStepperRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,stepperRenderer:e},this}setWorkflowNavigationRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,navigationRenderer:e},this}setWorkflowRenderConfig(e){return this.workflowRenderConfig=e,this}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}setRenderConfig(e){return this.setFormRenderConfig(e)}getComponent(e){return this.components.get(e)}getComponentsByType(e){return Array.from(this.components.values()).filter(r=>r.type===e)}getComponentsBySubType(e){return Array.from(this.components.values()).filter(r=>r.subType===e)}getComponentsByCategory(e){return Array.from(this.components.values()).filter(r=>r.category===e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){return this.components.delete(e)}clear(){this.components.clear();}export(){return Object.fromEntries(this.components)}import(e){for(let[r,t]of Object.entries(e))this.components.set(r,t);return this}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),{}),bySubType:e.reduce((r,t)=>(r[t.subType]=(r[t.subType]||0)+1,r),{}),byCategory:e.reduce((r,t)=>{let n=t.category||"uncategorized";return r[n]=(r[n]||0)+1,r},{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNavigation:!!this.workflowRenderConfig.navigationRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(s=>s.id),n=t.filter((s,i)=>t.indexOf(s)!==i);n.length>0&&e.push(`Duplicate component IDs found: ${n.join(", ")}`);let a=r.filter(s=>!s.renderer);return a.length>0&&e.push(`Components without renderer: ${a.map(s=>s.id).join(", ")}`),e}};var m=o=>async e=>{try{return await o.parseAsync(e),{isValid:!0,errors:[]}}catch(r){return r&&typeof r=="object"&&"errors"in r&&Array.isArray(r.errors)?{isValid:false,errors:r.errors.map(t=>({code:t.code,message:t.message,path:t.path?t.path.map(String):[]}))}:{isValid:false,errors:[{code:"unknown",message:r instanceof Error?r.message:"Unknown validation error"}]}}},w=o=>async(e,r,t)=>{try{let n=await o(e,r);return n===!0?{isValid:!0,errors:[]}:n===!1?{isValid:!1,errors:[{code:"validation_failed",message:"Validation failed"}]}:{isValid:!1,errors:[{code:"validation_failed",message:String(n)}]}}catch(n){return {isValid:false,errors:[{code:"validation_error",message:n instanceof Error?n.message:"Validation error"}]}}},b=(o,e="all")=>async(r,t,n)=>{let a=await Promise.all(o.map(l=>l(r,t,n)));if(e==="all"){let l=a.flatMap(u=>u.errors),c=a.flatMap(u=>u.warnings||[]);return {isValid:a.every(u=>u.isValid),errors:l,warnings:c.length>0?c:void 0}}if(a.some(l=>l.isValid)){let l=a.flatMap(c=>c.warnings||[]);return {isValid:true,errors:[],warnings:l.length>0?l:void 0}}return {isValid:false,errors:a.flatMap(l=>l.errors)}},v=(o,e)=>async(r,t,n)=>o(r,t)?e(r,t,n):{isValid:true,errors:[]},P={required:(o="This field is required")=>w(e=>e==null||e===""?o:!0),email:(o="Invalid email format")=>m(z.string().email(o)),minLength:(o,e)=>m(z.string().min(o,e||`Minimum ${o} characters required`)),maxLength:(o,e)=>m(z.string().max(o,e||`Maximum ${o} characters allowed`)),pattern:(o,e="Invalid format")=>m(z.string().regex(o,e)),numberRange:(o,e,r)=>{let t=z.number();return o!==void 0&&(t=t.min(o,r||`Value must be at least ${o}`)),e!==void 0&&(t=t.max(e,r||`Value must be at most ${e}`)),m(t)},url:(o="Invalid URL format")=>m(z.string().url(o)),phoneNumber:(o="Invalid phone number format")=>m(z.string().regex(/^\+?[\d\s\-\(\)]+$/,o)),asyncValidation:(o,e=300)=>{let r=new Map;return (t,n,a)=>new Promise(s=>{let i=`${n.fieldId}-${JSON.stringify(t)}`;r.has(i)&&clearTimeout(r.get(i));let l=setTimeout(async()=>{try{let c=await o(t,n);s(c===!0?{isValid:!0,errors:[]}:{isValid:!1,errors:[{code:"async_validation_failed",message:typeof c=="string"?c:"Async validation failed"}]});}catch(c){s({isValid:false,errors:[{code:"async_validation_error",message:c instanceof Error?c.message:"Async validation error"}]});}finally{r.delete(i);}},e);r.set(i,l);})}},k=(o,e=[],r)=>({isValid:o,errors:e,warnings:r}),V=(o,e,r)=>({code:o,message:e,path:r});var g=class{constructor(){this.name="localStorage";}async save(e,r){try{localStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to localStorage: ${t}`)}}async load(e){try{let r=localStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from localStorage: ${r}`)}}async remove(e){try{localStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from localStorage: ${r}`)}}async exists(e){return localStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},p=class{constructor(){this.name="sessionStorage";}async save(e,r){try{sessionStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to sessionStorage: ${t}`)}}async load(e){try{let r=sessionStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from sessionStorage: ${r}`)}}async remove(e){try{sessionStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from sessionStorage: ${r}`)}}async exists(e){return sessionStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},f=class{constructor(){this.name="memory";this.storage=new Map;}async save(e,r){this.storage.set(e,{...r});}async load(e){let r=this.storage.get(e);return r?{...r}:null}async remove(e){this.storage.delete(e);}async exists(e){return this.storage.has(e)}async list(e){let r=Array.from(this.storage.keys());return e?r.filter(t=>t.includes(e)):r}clear(){this.storage.clear();}},h=class{constructor(e,r=[]){this.primary=e;this.fallbacks=r;this.name="composite";}async save(e,r){let t=[this.primary,...this.fallbacks];for(let n of t)try{await n.save(e,r);return}catch(a){console.warn(`Failed to save with ${n.name}:`,a);}throw new Error("All persistence adapters failed to save")}async load(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{let n=await t.load(e);if(n)return n}catch(n){console.warn(`Failed to load with ${t.name}:`,n);}return null}async remove(e){let r=[this.primary,...this.fallbacks],t=[];for(let n of r)try{await n.remove(e);}catch(a){t.push(a);}if(t.length===r.length)throw new Error(`All adapters failed to remove: ${t.map(n=>n.message).join(", ")}`)}async exists(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{if(await t.exists(e))return !0}catch(n){console.warn(`Failed to check existence with ${t.name}:`,n);}return false}async list(e){try{return await this.primary.list?.(e)||[]}catch(r){console.warn("Failed to list with primary adapter:",r);for(let t of this.fallbacks)try{return await t.list?.(e)||[]}catch(n){console.warn(`Failed to list with fallback ${t.name}:`,n);}return []}}};var E={localStorage(o={}){return {adapter:new g,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},sessionStorage(o={}){return {adapter:new p,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},memory(o={}){return {adapter:new f,debounceMs:0,autoSave:true,saveOnStepChange:true,...o}},custom(o,e={}){return {adapter:o,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...e}}};function T(o,e,r={}){let t=e||new f;return {adapter:{name:`resilient-${o.name}`,async save(a,s){try{await o.save(a,s);}catch(i){console.warn("Primary persistence failed, using fallback:",i),await t.save(a,s);}},async load(a){try{let s=await o.load(a);if(s)return s}catch(s){console.warn("Primary persistence load failed, trying fallback:",s);}return await t.load(a)},async remove(a){let s=[];try{await o.remove(a);}catch(i){s.push(i);}try{await t.remove(a);}catch(i){s.push(i);}if(s.length===2)throw new Error(`Both adapters failed: ${s.map(i=>i.message).join(", ")}`)},async exists(a){try{if(await o.exists(a))return !0}catch(s){console.warn("Primary persistence exists check failed:",s);}try{return await t.exists(a)}catch(s){return console.warn("Fallback persistence exists check failed:",s),false}},async list(a){try{return await o.list?.(a)||[]}catch(s){console.warn("Primary persistence list failed:",s);try{return await t.list?.(a)||[]}catch(i){return console.warn("Fallback persistence list failed:",i),[]}}}},debounceMs:1e3,autoSave:true,saveOnStepChange:true,maxRetries:3,retryDelayMs:1e3,...r}}export{h as CompositeAdapter,g as LocalStorageAdapter,f as MemoryAdapter,p as SessionStorageAdapter,b as combineValidators,P as commonValidators,v as createConditionalValidator,w as createCustomValidator,T as createResilientPersistence,V as createValidationError,k as createValidationResult,m as createZodValidator,E as persistence,y as ril};
|
|
1
|
+
function P(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:P(n,o)};return r(a)}function ge(n,e){return {...n,...e}}function F(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 ye(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 E=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 he(n){return Array.isArray(n)?n:[n]}function V(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=>V(r));let e={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=V(n[r]));return e}function ve(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","repeatableRenderer","repeatableItemRenderer"],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,repeatable:!!this.formRenderConfig.repeatableRenderer,repeatableItem:!!this.formRenderConfig.repeatableItemRenderer,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{F(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","repeatableRenderer","repeatableItemRenderer"],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 R(n){return n==null?true:typeof n=="string"?n.trim().length===0:Array.isArray(n)?n.length===0:typeof n=="object"?Object.keys(n).length===0:false}function C(n,e=[]){return {isValid:n,errors:[...e]}}function W(){return C(true,[])}function O(n,e,r){return C(false,[{message:n,code:e,path:r}])}function N(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="This field is required"){return {"~standard":{version:1,vendor:"rilaykit",validate:e=>R(e)?{issues:[{message:n,path:void 0}]}:{value:e}}}}function L(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 q(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 U(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 _(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 K(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 j(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 Q(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 H(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 J(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 G(...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 b(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:X(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 X(n){if(!(!n||n.length===0))return n.map(e=>typeof e=="object"&&"key"in e?String(e.key):String(e)).join(".")}function Y(n){if(!c(n))throw new Error("Invalid Standard Schema");return {vendor:n["~standard"].vendor,version:n["~standard"].version,hasTypes:!!n["~standard"].types}}function Z(n){return c(n)&&!!n["~standard"].types}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 b(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 re(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 b(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 ne(n){return !!n.validate}function te(...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 oe(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 ie(n){return Array.isArray(n)?n.every(c):c(n)}function ae(n){return n?Array.isArray(n)?n:[n]:[]}var se=0,M=()=>`event_${Date.now()}_${++se}`,de=()=>`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:de(),environment:"production",userAgent:typeof window<"u"?window.navigator?.userAgent:void 0,url:typeof window<"u"?window.location?.href:void 0,...r},this.profiler=new x,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);}}},x=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}},p=null;function Me(n,e){return p&&p.destroy(),p=new w(n,e),p}function Be(){return p}async function Ie(){p&&(await p.destroy(),p=null);}var S=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))}},I=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 S("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 T=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 f(r.visible))t.add(o);if(r.disabled)for(let o of f(r.disabled))t.add(o);if(r.required)for(let o of f(r.required))t.add(o);if(r.readonly)for(let o of f(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 k=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 D(this,e)}};function Ne(n){return new k(n)}function D(n,e){if(n.conditions&&n.conditions.length>0){let t=n.conditions.map(o=>D(o,e));return n.logicalOperator==="or"?t.some(o=>o):t.every(o=>o)}let r=le(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 le(n,e){if(e in n)return 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 f(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 $e(n){let e=new Set;for(let r of Object.values(n))if(r){let t=f(r);for(let o of t)e.add(o);}return Array.from(e)}export{fe as ComponentRendererWrapper,T as ConditionDependencyGraph,S as ConsoleAdapter,A as DevelopmentAdapter,E as IdGenerator,I as LocalStorageAdapter,B as RemoteAdapter,w as RilayMonitor,J as async,G as combine,te as combineSchemas,ve as configureObject,O as createErrorResult,oe as createStandardValidator,W as createSuccessResult,N as createValidationContext,C as createValidationResult,H as custom,V as deepClone,Ie as destroyGlobalMonitoring,L as email,F as ensureUnique,D as evaluateCondition,$e as extractAllDependencies,f as extractConditionDependencies,Be as getGlobalMonitor,Y as getSchemaInfo,Z as hasSchemaTypes,ne as hasUnifiedValidation,Me as initializeMonitoring,R as isEmptyValue,c as isStandardSchema,ie as isValidationRule,Q as max,z as maxLength,ge as mergeInto,j as min,U as minLength,he as normalizeToArray,ae as normalizeValidationRules,K as number,_ as pattern,$ as required,P as resolveRendererChildren,v as ril,q as url,re as validateFormWithUnifiedConfig,ye as validateRequired,b as validateWithStandardSchema,ee as validateWithUnifiedConfig,Ne as when};
|
package/package.json
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rilaykit/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"private": false,
|
|
4
5
|
"description": "Core types, configurations, and utilities for the RilayKit form library",
|
|
5
6
|
"main": "dist/index.js",
|
|
7
|
+
"module": "dist/index.mjs",
|
|
6
8
|
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.mjs",
|
|
13
|
+
"require": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
7
16
|
"files": [
|
|
8
17
|
"dist"
|
|
9
18
|
],
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"provenance": true
|
|
21
|
+
},
|
|
10
22
|
"keywords": [
|
|
11
23
|
"react",
|
|
12
24
|
"forms",
|
|
@@ -14,22 +26,27 @@
|
|
|
14
26
|
"validation",
|
|
15
27
|
"builder-pattern"
|
|
16
28
|
],
|
|
17
|
-
"author": "
|
|
29
|
+
"author": "AND YOU CREATE <contact@andyoucreate.com>",
|
|
18
30
|
"license": "MIT",
|
|
31
|
+
"homepage": "https://rilay.dev",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "https://github.com/andyoucreate/rilaykit.git"
|
|
35
|
+
},
|
|
36
|
+
"bugs": {
|
|
37
|
+
"url": "https://github.com/andyoucreate/rilaykit/issues"
|
|
38
|
+
},
|
|
19
39
|
"peerDependencies": {
|
|
20
40
|
"react": ">=18.0.0",
|
|
21
41
|
"typescript": ">=5.0.0"
|
|
22
42
|
},
|
|
23
43
|
"devDependencies": {
|
|
24
|
-
"@types/react": "^
|
|
25
|
-
"react": "^19.
|
|
26
|
-
"typescript": "^5.3
|
|
44
|
+
"@types/react": "^19.0.0",
|
|
45
|
+
"react": "^19.0.0",
|
|
46
|
+
"typescript": "^5.8.3"
|
|
27
47
|
},
|
|
28
48
|
"dependencies": {
|
|
29
|
-
"
|
|
30
|
-
},
|
|
31
|
-
"publishConfig": {
|
|
32
|
-
"access": "public"
|
|
49
|
+
"@standard-schema/spec": "^1.0.0"
|
|
33
50
|
},
|
|
34
51
|
"scripts": {
|
|
35
52
|
"build": "tsup",
|