@asaidimu/anansi 1.5.3 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1,67 +1,80 @@
1
- "use strict";var Je=Object.create;var J=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var We=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},be=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ze(e))!Ke.call(n,s)&&s!==t&&J(n,s,{get:()=>e[s],enumerable:!(i=He(e,s))||i.enumerable});return n};var q=(n,e,t)=>(t=n!=null?Je(Be(n)):{},be(e||!n||!n.__esModule?J(t,"default",{value:n,enumerable:!0}):t,n)),Ye=n=>be(J({},"__esModule",{value:!0}),n);var Ct={};We(Ct,{JsonPatchError:()=>P,MigrationEngine:()=>pe,MigrationError:()=>v,MigrationErrorCode:()=>Fe,SchemaRegistry:()=>_,applyPatch:()=>W,calculateNextVersion:()=>le,compareSemanticVersions:()=>A,createGitSchemaRegistry:()=>$t,createPatch:()=>Xe,createSchemaMigrationHelper:()=>je,createStandardSchemaValidator:()=>Ce,deepMerge:()=>re,docgen:()=>xt,extractInputFieldGroups:()=>Et,generateSHA256Hash:()=>O,generateValidationInterface:()=>vt,normalizePath:()=>ve,schemaChangeToPatch:()=>ae,schemaToTypes:()=>bt,serializeParams:()=>U,sortSemanticVars:()=>gt,validate:()=>ot,validateMigration:()=>me,validateSchemaChange:()=>he,validateSchemaDefinition:()=>N});module.exports=Ye(Ct);var St=require("@asaidimu/events");var wt=require("@asaidimu/events"),Z=require("@asaidimu/query");var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function B(n){let e=ve(n);return e===""?[]:e.substring(1).split("/").map(Qe)}function ve(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(z).join("/"):"/"+n.split(".").map(z).join("/")}function z(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Qe(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function K(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function te(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return n;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function Ze(n,e,t){let i=M.get(e)||B(e);M.set(e,i);let s=K(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function H(n,e,t){let i=M.get(e)||B(e);if(M.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=K(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function ne(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function W(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=H(t,i.path,i.value);break;case"remove":t=ne(t,i.path);break;case"removeValue":t=Ze(t,i.path,i.value);break;case"replace":t=H(ne(t,i.path),i.path,i.value);break;case"copy":{let s=te(t,i.from);t=H(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=te(t,i.from);t=H(t,i.path,s),t=ne(t,i.from);break}case"test":{let s=te(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function Xe(n,e){let t=[];return ie(n,e,"",t),t}function ie(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?et(n,e,t,i):tt(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function et(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ie(n[r],e[r],a,i)}}function tt(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=z(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ie(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=z(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function ae(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=nt(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function nt(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function xe(n){return n&&"operator"in n&&"rules"in n}function Ee(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function re(n,e){let t={...n};return se(n)&&se(e)&&Object.keys(e).forEach(i=>{se(e[i])?i in n?t[i]=re(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function se(n){return n&&typeof n=="object"&&!Array.isArray(n)}function U(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ce(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let x=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,x,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:x}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${U(f.parameters)}`,path:x})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],D=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let x=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:x});return}if(C!==void 0){if(g.push(...s(C,p.type,x)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...x,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,I)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...x,I.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...x,I.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:x}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,x,m,h)),p.nestedSchema.constraints?.forEach((E,I)=>{if("rules"in E)g.push(...r(E,C,d,[...x,`constraints[${I}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${U(E.parameters)}`,path:[...x,`constraints[${I}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...x,`constraints[${I}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...x,`constraints[${E}]`],h));else{let I=d[$.predicate];I?I({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${U($.parameters)}`,path:[...x,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...x,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!D.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let x=d[f.predicate];if(!x)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!x({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${U(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var F=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ce=n=>({value:n}),j=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Te=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},it=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},De=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Y=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],at=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},de=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(...at(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},ue=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...De(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...ue(a,`${e}.rules[${o}]`)):t.push(...de(a,`${e}.rules[${o}]`))}),t},L=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...ue(i,`${e}[${s}]`)):t.push(...de(i,`${e}[${s}]`))}),t},ke=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...De(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...ke(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Ie=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...it(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...Y(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...ke(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},Q=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...Ie(i,`${e}[${s}]`))),t},fe=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Te(n.type,`${e}.type`)),t.push(...Y(n.required,`${e}.required`,!1)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...Te(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...L(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...Q(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...Y(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...Y(n.unique,`${e}.unique`,!1)),t},Pe=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...fe(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...Q(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},st=n=>{if(typeof n!="object"||n===null)return j([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...fe(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...Pe(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...Q(e.indexes,"indexes")),e.constraints&&t.push(...L(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...Re(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?j(t):ce(e)},oe=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...fe(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...L(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...Q(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...Ie(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...ue(n.constraint,`${e}.constraint`)):t.push(...de(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...Pe(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},rt=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},Re=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...oe(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...oe(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...rt(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},Ae={"~standard":{version:1,vendor:"xAI",validate:st,types:{input:{},output:{}}}};var Me={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return j([{message:"Migration must be an object",path:[]}]);let e=n,t=Re(e,"");return t.length>0?j(t):ce(e)},types:{input:{},output:{}}}},Oe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return j([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...oe(i,`[${s}]`))),t.length>0?j(t):ce(e)},types:{input:[],output:[]}}};function me(n){try{return!Me["~standard"].validate(n).issues}catch(e){throw new F("Invalid migration definition",e)}}function he(n){try{return!Oe["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}function N(n){try{return!Ae["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}var ot=N;var O=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(n).digest("hex")}};function ct(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function dt(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function ut(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function ft(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function mt(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function ht(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return mt(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=dt(e,t);return i?ft(e.parameters,n.parameters,i):!0}return!1}function lt(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return ut(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return ht(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function pt(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);s.add(r.id);break}}function yt(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function le(n,e,t){if(e.length===0)throw new Error("No changes provided");pt(e),yt(e);let i=ct(n),s="patch";for(let r of e){let a=lt(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function A(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function gt(n){return n.sort(A)}var v=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},Fe=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(Fe||{}),pe=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!N(e))throw new v("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>me(s)))throw new v("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>A(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>A(s.version,r.version)))}catch(s){throw s instanceof v?s:new v("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await O(t)}catch(t){throw new v("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new v("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>he(i))}catch(i){throw new v("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof v?s:new v("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?A(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=le(e.version,t);return t.map(a=>{try{return ae(a,e)}catch(o){throw new v("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return W(a,o)}catch(c){throw new v("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof v?s:new v("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new v("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,t){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let s=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new v(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new v(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new v(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new v(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new v(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof v?t:new v("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var je=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};var dn=require("@isomorphic-git/lightning-fs"),T=q(require("isomorphic-git"),1),G=q(require("isomorphic-git/http/web"),1);var qe=q(require("@isomorphic-git/lightning-fs"),1);function Ne(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Ve(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function ye(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ge(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}var Ue=require("buffer");window.Buffer=Ue.Buffer;var _=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new qe.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!N(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await O(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await O(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));A(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>A(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:ye(o.forward),backward:ye(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await O(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ne(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ve(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ge(e.transform.forward),backward:ge(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var we=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},Se=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function X(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function ee(n,e,t,i,s){await i.init(),await T.default.init({fs:n,dir:e,defaultBranch:t}),await T.default.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.default.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.default.add({fs:n,dir:e,filepath:"."}),await T.default.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function $t(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new _(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new we,h=new Se(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(k){if(console.warn(`Failed with proxy ${b}: ${k.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function D(l,y="."){return X(async()=>(await T.default.add({fs:d,dir:u,filepath:y}),(await T.default.statusMatrix({fs:d,dir:u})).some(([b,k,R])=>k!==R)?await T.default.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return X(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.default.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.default.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function x(l){return(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return X(async()=>{let w=(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.default.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return X(async()=>{await T.default.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.default.push({fs:d,http:G.default,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function I(l,y=!0){i&&await g(async w=>{try{await T.default.pull({fs:d,http:G.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.default.pull({fs:d,http:G.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.default.clone({fs:d,http:G.default,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await ee(d,u,t,c,r),await T.default.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await ee(d,u,t,c,r)}else await ee(d,u,t,c,r)}else await ee(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await D(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await D(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.default.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await D(`chore: delete schema ${y}`),b=await x(`${y}-`);if(i&&w){await E(t);for(let k of b)await E(k,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${k}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,k=h.get(b);return k||m.withLock(`schema:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await D("chore: sync local changes"),i){await I(t,!1),await E(t);let l=await T.default.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.default.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,k=h.get(b);return k||m.withLock(`migrations:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let k=await c.history(l);return h.set(w,k),k})}}}function bt(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
2
- * ${h.join(`
1
+ "use strict";var He=Object.create;var W=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Ye=(t,e)=>{for(var n in e)W(t,n,{get:e[n],enumerable:!0})},xe=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Be(e))!We.call(t,a)&&a!==n&&W(t,a,{get:()=>e[a],enumerable:!(i=ze(e,a))||i.enumerable});return t};var J=(t,e,n)=>(n=t!=null?He(Ke(t)):{},xe(e||!t||!t.__esModule?W(n,"default",{value:t,enumerable:!0}):n,t)),Qe=t=>xe(W({},"__esModule",{value:!0}),t);var Dt={};Ye(Dt,{JsonPatchError:()=>A,MigrationEngine:()=>we,MigrationError:()=>C,MigrationErrorCode:()=>Ne,SchemaRegistry:()=>B,applyPatch:()=>ee,calculateNextVersion:()=>$e,compareSemanticVersions:()=>F,createGitSchemaRegistry:()=>Et,createPatch:()=>et,createSchemaMigrationHelper:()=>qe,createStandardSchemaValidator:()=>De,deepMerge:()=>fe,docgen:()=>Ct,extractInputFieldGroups:()=>kt,formResolver:()=>st,generateSHA256Hash:()=>V,generateValidationInterface:()=>Tt,normalizePath:()=>Te,schemaChangeToPatch:()=>de,schemaToTypes:()=>xt,serializeParams:()=>H,sortSemanticVars:()=>St,validate:()=>ut,validateMigration:()=>ye,validateSchemaChange:()=>ge,validateSchemaDefinition:()=>_});module.exports=Qe(Dt);var vt=require("@asaidimu/events");var bt=require("@asaidimu/events"),ne=require("@asaidimu/query");var A=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function Z(t){let e=Te(t);return e===""?[]:e.substring(1).split("/").map(Ze)}function Te(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(Q).join("/"):"/"+t.split(".").map(Q).join("/")}function Q(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Ze(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function X(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new A(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let a=i==="-"?n.length:parseInt(i);if(isNaN(a)||a<0||a>n.length)throw new A(`Invalid array index: ${i}`);n=n[a]}else{if(!n.hasOwnProperty(i))throw new A(`Property ${i} not found`);n=n[i]}}return n}function re(t,e){let n=M.get(e)||Z(e);if(M.set(e,n),n.length===0)return t;let i=X(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);if(isNaN(r)||r<0||r>=i.length)throw new A(`Invalid array index: ${a}`);return i[r]}return i[a]}function Xe(t,e,n){let i=M.get(e)||Z(e);M.set(e,i);let a=X(t,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(s=>s!==n)):a[r]===n&&delete a[r],t}function Y(t,e,n){let i=M.get(e)||Z(e);if(M.set(e,i),i.length===0)return n;let a=i.slice(0,-1),r=i[i.length-1],s=X(t,a);if(Array.isArray(s))if(r==="-")s.push(n);else{let o=parseInt(r);if(o<0||o>s.length)throw new A(`Invalid array index: ${r}`);s.splice(o,0,n)}else s[r]=n;return t}function oe(t,e){let n=M.get(e)||Z(e);if(M.set(e,n),n.length===0)return;let i=X(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);i.splice(r,1)}else delete i[a];return t}function ee(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=Y(n,i.path,i.value);break;case"remove":n=oe(n,i.path);break;case"removeValue":n=Xe(n,i.path,i.value);break;case"replace":n=Y(oe(n,i.path),i.path,i.value);break;case"copy":{let a=re(n,i.from);n=Y(n,i.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=re(n,i.from);n=Y(n,i.path,a),n=oe(n,i.from);break}case"test":{let a=re(n,i.path);if(JSON.stringify(a)!==JSON.stringify(i.value))throw new A("Test operation failed");break}default:throw new A(`Unsupported operation: ${i.op}`)}}catch(a){throw a instanceof A&&(a.operation=i),a}return n}function et(t,e){let n=[];return ce(t,e,"",n),n}function ce(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?tt(t,e,n,i):nt(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function tt(t,e,n,i){let a=Math.max(t.length,e.length);for(let r=0;r<a;r++){let s=`${n}/${r}`;r>=t.length?i.push({op:"add",path:`${n}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:s}):ce(t[r],e[r],s,i)}}function nt(t,e,n,i){let a=new Set,r=Object.keys(t),s=Object.keys(e);for(let o of r){let c=Q(o),u=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ce(t[o],e[o],u,i),a.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!a.has(o)){let c=Q(o),u=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function de(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([a,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?n.push({op:"replace",path:`${i}/${a}`,value:r}):n.push({op:"replace",path:`${i}/${a}`,value:r})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`/indexes/${i}/${a}`,value:r})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(a=>Array.isArray(a)?a.some(r=>r.name===t.name):a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=it(e,t.name);i&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`${i}/${a}`,value:r})});break}}return n}function it(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(Ce(i)){let a=ke(i.rules,e);if(a)return`/constraints/${n}${a}`}}return null}function Ce(t){return t&&"operator"in t&&"rules"in t}function ke(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(Ce(i)){let a=ke(i.rules,e);if(a)return`/rules/${n}${a}`}}return null}function fe(t,e){let n={...t};return ue(t)&&ue(e)&&Object.keys(e).forEach(i=>{ue(e[i])?i in t?n[i]=fe(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function ue(t){return t&&typeof t=="object"&&!Array.isArray(t)}function H(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function De(t,e){let n=o=>({value:o}),i=o=>({issues:o}),a=(o,c,u,l)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:u}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:u}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:u}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:u}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:u}]:[];case"enum":return l?.values?l.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(l.values)}, got ${o}`,path:u}]:[{message:"Enum type requires 'values' definition",path:u}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:u}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:u}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:u}]}};function r(o,c,u,l,x){let S=[],v=o.rules.map((g,k)=>{let $=[...l,`rules[${k}]`];if("rules"in g){if(x.has(g.name))return!0;x.add(g.name);let h=r(g,c,u,$,x);return S.push(...h),h.length===0}else{let h=u[g.predicate];if(!h)return S.push({message:`Predicate '${g.predicate}' not found`,path:$}),!1;let y=h({data:c,field:g.field,arguments:g.parameters});if(!y){let T=g.field?` for field '${g.field}'`:"";S.push({message:g.errorMessage||`Constraint '${g.name}' failed${T} with params ${H(g.parameters)}`,path:$})}return y}});return(()=>{switch(o.operator){case"and":return v.every(g=>g);case"or":return v.some(g=>g);case"not":return!v.every(g=>g);case"nor":return!v.some(g=>g);case"xor":return v.filter(g=>g).length===1}})()||S.push({message:`Constraint group '${o.name}' failed`,path:l}),S}function s(o,c,u,l,x,S=new Set,v){let m=[],g;if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))g=c.fields;else{let h=c.fields.find(y=>!y.when||v&&v[y.when.field]!==void 0&&v[y.when.field]===y.when.value);if(!h)return m.push({message:"No matching field set found for discriminated schema",path:l}),m;g=h.fields}else g=c.fields;let k=new Set(Object.values(g).map($=>$.name));Object.entries(g).forEach(([$,h])=>{let y=[...l,h.name],T=Object.hasOwnProperty.call(o,h.name)?o[h.name]:void 0;if(h.required&&T==null){m.push({message:`Field '${h.name}' is required`,path:y});return}if(T!==void 0){if(m.push(...a(T,h.type,y,h)),h.type==="array"||h.type==="set"){h.itemsType&&Array.isArray(T)&&T.forEach((f,d)=>m.push(...a(f,h.itemsType,[...y,d.toString()])));let b=h.schema||h.nestedSchema;if(b&&!Array.isArray(b)){let f=x[b.id];f?T.forEach((d,p)=>{typeof d=="object"&&d!==null&&(S.has(b.id)?m.push({message:`Circular reference detected at '${b.id}'`,path:[...y,p.toString()]}):(S.add(b.id),m.push(...s(d,f,u,[...y,p.toString()],x,S,o)),S.delete(b.id)))}):m.push({message:`Nested schema '${b.id}' not found`,path:y})}}if(h.type==="object"){let b=h.schema||h.nestedSchema;if(b&&!Array.isArray(b)){let f=x[b.id];f?typeof T=="object"&&T!==null&&(S.has(b.id)?m.push({message:`Circular reference detected at '${b.id}'`,path:y}):(S.add(b.id),m.push(...s(T,f,u,y,x,S,o)),b.constraints?.forEach((d,p)=>{if("rules"in d)m.push(...r(d,T,u,[...y,`constraints[${p}]`],S));else{let w=u[d.predicate];w?w({data:T,field:void 0,arguments:d.parameters})||m.push({message:d.errorMessage||`Constraint '${d.name}' failed with params ${H(d.parameters)}`,path:[...y,`constraints[${p}]`]}):m.push({message:`Predicate '${d.predicate}' not found`,path:[...y,`constraints[${p}]`]})}}),S.delete(b.id))):m.push({message:`Nested schema '${b.id}' not found`,path:y})}}if(h.type==="union"){let b=h.schema;!b||!Array.isArray(b)?m.push({message:"Union type requires an array of schema references",path:y}):b.some(d=>{let p=x[d.id];return p?s(T,p,u,y,x,new Set(S),o).length===0:(m.push({message:`Nested schema '${d.id}' not found`,path:y}),!1)})||m.push({message:"Value does not match any union schema",path:y})}h.constraints?.forEach((b,f)=>{if("rules"in b)m.push(...r(b,o,u,[...y,`constraints[${f}]`],S));else{let d=u[b.predicate];d?d({data:o,field:h.name,arguments:b.parameters})||m.push({message:b.errorMessage||`Constraint '${b.name}' failed for field '${h.name}' with params ${H(b.parameters)}`,path:[...y,`constraints[${f}]`]}):m.push({message:`Predicate '${b.predicate}' not found`,path:[...y,`constraints[${f}]`]})}})}});for(let $ in o)Object.hasOwnProperty.call(o,$)&&!k.has($)&&m.push({message:`Unexpected field '${$}'`,path:[...l,$]});return c.constraints?.forEach(($,h)=>{if("rules"in $)m.push(...r($,o,u,[...l,`constraints[${h}]`],S));else{let y=u[$.predicate];if(!y)m.push({message:`Predicate '${$.predicate}' not found`,path:[...l,`constraints[${h}]`]});else if(!y({data:o,field:$.field,arguments:$.parameters})){let b=$.field?` for field '${$.field}'`:"";m.push({message:$.errorMessage||`Constraint '${$.name}' failed${b} with params ${H($.parameters)}`,path:[...l,`constraints[${h}]`]})}}}),m}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,t,e,[],t.nestedSchemas||{});return u.length>0?i(u):n(c)},types:{input:{},output:{}}}}}function st(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(a=>{if(!a.path)return;let r=a.path,s=i;for(let o=0;o<r.length;o++){let c=r[o];o===r.length-1?s[c]={type:"validation",message:a.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var q=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var me=t=>({value:t}),L=t=>({issues:t}),E=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Ie=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},at=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Re=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},z=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],rt=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string")||t instanceof RegExp||typeof t=="object"&&t!==null&&"field"in t&&typeof t.field=="string")return[];break;case"number":if(typeof t=="number"||Array.isArray(t)&&t.every(i=>typeof i=="number")||typeof t=="object"&&t!==null&&"precision"in t&&typeof t.precision=="number")return[];break;case"boolean":if(typeof t=="boolean")return[];break;case"array":case"set":if(typeof t=="number"||typeof t=="object"&&t!==null&&"minItems"in t&&typeof t.minItems=="number")return[];break;case"enum":if(Array.isArray(t)&&t.length>0&&t.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"union":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[n]}]},he=(t,e)=>{let n=[],i=["predicate","name"],a=["type","predicate","field","parameters","name","description","errorMessage"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),n.push(...E(t.predicate,`${e}.predicate`)),t.type!==void 0&&t.type!=="schema"&&n.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),t.field!==void 0&&typeof t.field!="string"&&n.push({message:"Field must be a string",path:[`${e}.field`]}),t.parameters!==void 0&&(!t.type||t.type!=="schema")&&n.push(...rt(t.parameters,"dynamic",`${e}.parameters`)),n.push(...E(t.description,`${e}.description`,!1)),n.push(...E(t.errorMessage,`${e}.errorMessage`,!1)),n},pe=(t,e)=>{let n=[],i=["name","operator","rules"],a=["name","operator","rules"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),n.push(...Re(t.operator,`${e}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?n.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):t.rules.forEach((s,o)=>{"rules"in s?n.push(...pe(s,`${e}.rules[${o}]`)):n.push(...he(s,`${e}.rules[${o}]`))}),n},j=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,a)=>{"rules"in i?n.push(...pe(i,`${e}[${a}]`)):n.push(...he(i,`${e}[${a}]`))}),n},Ae=(t,e)=>{let n=[],i=["operator","field"],a=["operator","field","value","conditions"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Re(t.operator,`${e}.operator`)),n.push(...E(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...Ae(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},Pe=(t,e)=>{let n=[],i=["fields","type","name"],a=["fields","type","unique","partial","description","order","name"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),n.push(...at(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...z(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...Ae(t.partial,`${e}.partial`)),n.push(...E(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},U=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,a)=>n.push(...Pe(i,`${e}[${a}]`))),n},ot=(t,e,n,i,a)=>{let r=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&r.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;r.push(...E(s.id,`${c}.id`)),i.includes(s.id)||r.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&r.push(...j(s.constraints,`${c}.constraints`)),s.indexes&&r.push(...U(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&a==="object")&&!Array.isArray(t)?(r.push(...E(t.id,`${e}.id`)),i.includes(t.id)||r.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&r.push(...j(t.constraints,`${e}.constraints`)),t.indexes&&r.push(...U(t.indexes,`${e}.indexes`))):r.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),r)},te=(t,e,n)=>{let i=[],a=["name","type"],r=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=t;if(a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...E(t.name,`${e}.name`)),i.push(...Ie(t.type,`${e}.type`)),i.push(...z(t.required,`${e}.required`,!1)),t.constraints&&i.push(...j(t.constraints,`${e}.constraints`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...ot(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...Ie(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],u=t.nestedSchema;o.forEach(l=>{u[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.nestedSchema.${l}`]})}),Object.keys(u).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${l}`]})}),i.push(...E(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...j(t.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...U(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...z(t.deprecated,`${e}.deprecated`,!1)),t.reference){let o=["schema","field"],c=["schema","field"],u=t.reference;o.forEach(l=>{u[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.reference.${l}`]})}),Object.keys(u).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.reference.${l}`]})}),i.push(...E(t.reference.schema,`${e}.reference.schema`)),i.push(...E(t.reference.field,`${e}.reference.field`))}return i.push(...E(t.description,`${e}.description`,!1)),i.push(...z(t.unique,`${e}.unique`,!1)),i},Fe=(t,e,n)=>{let i=[],a=["name","fields"],r=["name","description","concrete","fields","indexes","constraints","metadata"],s=t;return a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...E(t.name,`${e}.name`)),i.push(...z(t.concrete,`${e}.concrete`,!1)),Array.isArray(t.fields)?(t.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),t.fields.forEach((o,c)=>{let u=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[u]});else{let l=o.fields;typeof l!="object"||l===null?i.push({message:"Fields must be a non-empty object",path:[`${u}.fields`]}):Object.entries(l).forEach(([x,S])=>{i.push(...te(S,`${u}.fields.${x}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${u}.when`]})}})):typeof t.fields=="object"&&t.fields!==null?Object.entries(t.fields).forEach(([o,c])=>{i.push(...te(c,`${e}.fields.${o}`,n))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...E(t.description,`${e}.description`,!1)),t.indexes&&i.push(...U(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...j(t.constraints,`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},ct=t=>{if(typeof t!="object"||t===null)return L([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields","nestedSchemas"],a=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[s]})}),n.push(...E(e.name,"name")),n.push(...E(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...te(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(...Fe(c,`nestedSchemas.${o}`,s)))}return n.push(...E(e.description,"description",!1)),e.indexes&&n.push(...U(e.indexes,"indexes")),e.constraints&&n.push(...j(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...Me(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),n.length>0?L(n):me(e)},le=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),n.push(...te(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],a=["type","id","changes","nestedSchemaChanges"],r=t;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...E(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...j(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...U(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Pe(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...pe(t.constraint,`${e}.constraint`)):n.push(...he(t.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),n.push(...Fe(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},dt=(t,e)=>{let n=[],i=["forward","backward"],a=i,r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},Me=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],a=[...i,"rollback","dependencies"],r=t;i.forEach(o=>{r[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{a.includes(o)||n.push({message:"Unknown property",path:[`${e}.${o}`]})}),n.push(...E(t.id,`${e}.id`)),n.push(...E(t.schemaVersion,`${e}.schemaVersion`)),n.push(...E(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>n.push(...le(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...le(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...E(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...dt(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...E(t.createdAt,`${e}.createdAt`)),t.dependencies!==void 0&&(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),n.push(...E(t.checksum,`${e}.checksum`)),n},Oe={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:ct,types:{input:{},output:{}}}};var je={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return L([{message:"Migration must be an object",path:[]}]);let e=t,n=Me(e,"");return n.length>0?L(n):me(e)},types:{input:{},output:{}}}},Ve={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return L([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,a)=>n.push(...le(i,`[${a}]`))),n.length>0?L(n):me(e)},types:{input:[],output:[]}}};function ye(t){try{return!je["~standard"].validate(t).issues}catch(e){throw new q("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function ge(t){try{return!Ve["~standard"].validate(t).issues}catch(e){throw new q("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function _(t){try{return!Oe["~standard"].validate(t).issues}catch(e){throw new q("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var ut=_;var V=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function ft(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function lt(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function mt(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function ht(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function pt(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function yt(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return pt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=lt(e,n);return i?ht(e.parameters,t.parameters,i):!0}return!1}function gt(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return mt(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return yt(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function $t(t){let e=new Set,n=new Set,i=new Set,a=new Set;for(let r of t)switch(r.type){case"addField":if(n.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);n.add(r.id);break;case"modifyField":if(n.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(n.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);a.add(r.id);break}}function wt(t){let e=new Set,n=new Set,i=new Set;for(let a of t)switch(a.type){case"addConstraint":let r=a.constraint,s=("name"in r,r.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(e.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);n.add(a.name);break;case"modifyConstraint":if(n.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(i.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);e.add(a.name);break}}function $e(t,e,n){if(e.length===0)throw new Error("No changes provided");$t(e),wt(e);let i=ft(t),a="patch";for(let r of e){let s=gt(r,n);if(s==="major"){a="major";break}else s==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function F(t,e){let n=u=>u.split(".").map(l=>parseInt(l,10)||0),[i,a,r]=n(t),[s,o,c]=n(e);return i-s||a-o||r-c}function St(t){return t.sort(F)}var C=class extends Error{constructor(n,i,a,r){super(n);this.code=i;this.migrationId=a;this.cause=r;this.name="MigrationError"}},Ne=(S=>(S.INVALID_SCHEMA="INVALID_SCHEMA",S.INVALID_MIGRATION="INVALID_MIGRATION",S.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",S.TIMEOUT="TIMEOUT",S.MEMORY_LIMIT="MEMORY_LIMIT",S.CONCURRENT_OPERATION="CONCURRENT_OPERATION",S.TRANSFORM_ERROR="TRANSFORM_ERROR",S.VERSION_NOT_FOUND="VERSION_NOT_FOUND",S.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",S.STREAM_ERROR="STREAM_ERROR",S.ROLLBACK_ERROR="ROLLBACK_ERROR",S.MISSING_TRANSFORM="MISSING_TRANSFORM",S))(Ne||{}),we=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!_(e))throw new C("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(a=>ye(a)))throw new C("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((a,r)=>F(a.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((a,r)=>F(a.version,r.version)))}catch(a){throw a instanceof C?a:new C("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,a)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await V(n)}catch(n){throw new C("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new C("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>ge(i))}catch(i){throw new C("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},r=this.getRelevantMigrations(n,i),s=r.reduce((c,u)=>{let l=n==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,l,u.id)},a),o=await t.processMigrationList(e,n,r);return{newSchema:s,dataPreview:o}}catch(a){throw a instanceof C?a:new C("Dry run failed","INVALID_SCHEMA",void 0,a)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let a=e==="forward"?"pending":"applied",r=n?F(i.schemaVersion,n)>=0:!0;return i.status===a&&r}).sort((i,a)=>e==="forward"?i.id.localeCompare(a.id):a.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let a=$e(e.version,n);return n.map(s=>{try{return de(s,e)}catch(o){throw new C("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ee(s,o)}catch(c){throw new C("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:a})}catch(a){throw a instanceof C?a:new C("Schema update failed","INVALID_SCHEMA",i,a)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new C("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let a=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return n;for(let o=0;o<r;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",a);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new C(`Failed to resolve transform for migration ${s.id}`,"TRANSFORM_ERROR",s.id,o)}}))).filter(s=>!!s.transform).reduce((s,{migration:o,transform:c})=>s.pipeThrough(new TransformStream({async transform(u,l){try{let x=await c(u);l.enqueue(x)}catch(x){l.error(new C(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,x))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new C(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let a=await i.text();if(typeof window<"u"){let r=new Blob([a],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[n]}else{let{runInNewContext:r}=await import("vm"),s={module:{exports:{}},console};return r(a,s,e),s.module.exports[n]}}catch(i){throw new C(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new C(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,a)=>this.applySchemaChanges(i,[a]),this.currentSchema)}catch(n){throw n instanceof C?n:new C("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var qe=t=>{let e=[],n=[];return{addField:(i,a)=>{e.push({type:"addField",id:i,definition:a}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let a=t.fields[i];a&&n.push({type:"addField",id:i,definition:a})},modifyField:(i,a)=>{e.push({type:"modifyField",id:i,changes:a});let r=t.fields[i];r&&n.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let a=t.indexes?.find(r=>r.name===i);a&&n.push({type:"addIndex",definition:a})},modifyIndex:(i,a)=>{e.push({type:"modifyIndex",name:i,changes:a});let r=t.indexes?.find(s=>s.name===i);r&&n.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let a=t.constraints?.find(r=>"name"in r&&r.name===i);a&&n.push({type:"addConstraint",constraint:a})},modifyConstraint:(i,a)=>{e.push({type:"modifyConstraint",name:i,changes:a});let r=t.constraints?.find(s=>"name"in s&&s.name===i);r&&n.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,a)=>{e.push({type:"addNestedSchema",id:i,definition:a}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let a=t.nestedSchemas[i];a&&n.push({type:"addNestedSchema",id:i,definition:a})},modifyNestedSchema:(i,a)=>{e.push({type:"modifyNestedSchema",id:i,changes:a});let r=t.nestedSchemas[i];r&&n.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:n})}};var ln=require("@isomorphic-git/lightning-fs"),I=J(require("isomorphic-git"),1),K=J(require("isomorphic-git/http/web"),1);var _e=J(require("@isomorphic-git/lightning-fs"),1);function Le(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function Ue(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function Se(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),a=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,s;return n?(r=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(r=i[1],s=i[2].trim()):a?(r=a[2],s=a[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:s,type:n?"arrow":i?"function":a?"method":"unknown"})}function be(t){let{params:e,body:n,type:i}=JSON.parse(t),a=new Function(e,n);return i==="arrow"&&Object.defineProperty(a,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),a}var Ge=require("buffer");window.Buffer=Ge.Buffer;var B=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new _e.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!_(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,a=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let s=await V(r);await this.updateIndex(i,e,s,a,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let a=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(a))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(a,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(r.migrations=await this.migrations({name:e,version:n})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let a=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await V(a)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),a=n||i.version,r=[];for(let[s,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let u=JSON.parse(String(await this.fsp.readFile(c,"utf8")));F(u.schemaVersion,a)<=0&&r.push(this.deserializeMigration(u))}}return r.sort((s,o)=>F(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async a=>({...i,version:a.version,description:a.description,migrations:await this.migrations({name:e,version:a.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let a={...i};if(i.transform?.forward){let o=i.transform;a.transform={forward:Se(o.forward),backward:Se(o.backward||(c=>c))}}let r=JSON.stringify(a),s=await V(r);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,r,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Le(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ue(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:be(e.transform.forward),backward:be(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,a,r){let s=`${e}/index.json`,o=r==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(r==="create"?"Initial version":"Updated version"),migrations:a.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,a.forEach(({id:c,hash:u,checksum:l})=>{o.migrations[c]={hash:u,checksum:l}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let a=`${e}/${i}`;(await this.fsp.stat(a)).isDirectory()?await this.rmdirRecursive(a):await this.fsp.unlink(a)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let a of i){let r=`${e}/${a}`;(await this.fsp.stat(r)).isDirectory()?n.push(...await this.listFilesRecursive(r)):n.push(r)}return n}};var ve=class{locks=new Map;async acquire(e){let n,i=new Promise(r=>{n=r}),a=this.locks.get(e)||Promise.resolve();return this.locks.set(e,a.then(()=>i)),await a,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},Ee=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function ie(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function se(t,e,n,i,a){await i.init(),await I.default.init({fs:t,dir:e,defaultBranch:n}),await I.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await I.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await I.default.add({fs:t,dir:e,filepath:"."}),await I.default.commit({fs:t,dir:e,message:"chore: initial commit",author:a})}async function Et(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,a=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new B(t),u=c.fs,l=t.startsWith("/")?t:`/${t}`,x=new ve,S=new Ee(e.cacheTtl);async function v(f,d){let p=o;do{let w=s[o];try{return await f(w)}catch(D){if(console.warn(`Failed with proxy ${w}: ${D.message}`),o=(o+1)%s.length,o===p)throw new Error(`${d}: All CORS proxies failed`)}}while(!0)}async function m(f,d="."){return ie(async()=>(await I.default.add({fs:u,dir:l,filepath:d}),(await I.default.statusMatrix({fs:u,dir:l})).some(([w,D,R])=>D!==R)?await I.default.commit({fs:u,dir:l,message:f,author:r}):null),"Failed to commit changes")}async function g(f,d,p){return ie(async()=>{if(await k(f))throw new Error(`Tag ${f} already exists`);await I.default.annotatedTag({fs:u,dir:l,ref:f,message:d,tagger:r,object:p})},`Failed to create tag ${f}`)}async function k(f){try{return(await I.default.listTags({fs:u,dir:l})).includes(f)}catch{return!1}}async function $(f){return(await I.default.listTags({fs:u,dir:l})).filter(w=>w.startsWith(f))}async function h(f){return ie(async()=>{let p=(await I.default.listTags({fs:u,dir:l})).filter(w=>w.startsWith(f));for(let w of p)await I.default.deleteTag({fs:u,dir:l,ref:w});return p},`Failed to delete tags with prefix ${f}`)}async function y(f){return ie(async()=>{await I.default.checkout({fs:u,dir:l,ref:f})},`Failed to checkout ${f}`)}async function T(f,{delete:d=!1,force:p=!1}={}){i&&await v(async w=>{await I.default.push({fs:u,http:K.default,dir:l,ref:f,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,delete:d,force:p})},`Failed to push ${f}`)}async function b(f,d=!0){i&&await v(async p=>{try{await I.default.pull({fs:u,http:K.default,dir:l,ref:f,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:p,fastForwardOnly:!0})}catch(w){if(!d)console.warn(`Fast-forward pull failed for ${f}, attempting regular pull`),await I.default.pull({fs:u,http:K.default,dir:l,ref:f,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:p,fastForwardOnly:!1});else throw w}},`Failed to pull ${f}`)}if(i&&!await c.fileExists(l)){let f=l.slice(1);if(await i.exists({name:f}).catch(()=>!1))await v(async p=>{await I.default.clone({fs:u,http:K.default,dir:l,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:p})},"Failed to clone repository");else if(a)try{i=await i.create({name:f,private:!0}),await se(u,l,n,c,r),await I.default.addRemote({fs:u,dir:l,remote:"origin",url:i.url()}),await T(n)}catch(p){console.error("Failed to create and push to remote repository:",p),await se(u,l,n,c,r)}else await se(u,l,n,c,r)}else await se(u,l,n,c,r);return{async init(){return x.withLock("init",()=>c.init())},async create(f){let{name:d,version:p}=f.schema;return x.withLock(`schema:${d}`,async()=>{await y(n),await c.create(f);let w=await m(`feat: create schema ${d}`);w&&await g(`${d}-${p}`,`Version ${p}`,w),S.invalidate(d)})},async update(f){let{name:d,version:p}=f.schema;return x.withLock(`schema:${d}`,async()=>{await y(n),await c.update(f);let w=await m(`fix: update schema ${d}`);w&&await g(`${d}-${p}`,`Version ${p}`,w),S.invalidate(d)})},async delete(f){let{name:d}=f;return x.withLock(`schema:${d}`,async()=>{await y(n),await I.default.remove({fs:u,dir:l,filepath:d}),await c.delete(f);let p=await m(`chore: delete schema ${d}`),w=await $(`${d}-`);if(i&&p){await T(n);for(let D of w)await T(D,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${D}: ${R.message}`))}await h(`${d}-`),S.invalidate(d)})},async list(){return x.withLock("list",()=>c.list())},async schema(f){let{name:d,version:p}=f,w=`${d}-${p||"latest"}-${f.migrations||!1}`,D=S.get(w);return D||x.withLock(`schema:${d}`,async()=>{if(p){let O=`${d}-${p}`;if(await k(O))await y(O);else throw new Error(`Version ${p} of schema ${d} not found`)}else await y(n);let R=await c.schema(f);return S.set(w,R),R})},async stats(f){return x.withLock("stats",()=>c.stats(f))},async sync(){return x.withLock("sync",async()=>{if(await y(n),await c.sync(),await m("chore: sync local changes"),i){await b(n,!1),await T(n);let f=await I.default.listTags({fs:u,dir:l});for(let p of f)await T(p,{force:!0});let d=await I.default.listTags({fs:u,dir:l});for(let p of d)f.includes(p)||await T(p,{delete:!0})}S.invalidate()})},async migrations(f){let{name:d,version:p}=f,w=`migrations-${d}-${p||"latest"}`,D=S.get(w);return D||x.withLock(`migrations:${d}`,async()=>{if(p){let O=`${d}-${p}`;if(await k(O))await y(O);else throw new Error(`Version ${p} of schema ${d} not found`)}else await y(n);let R=await c.migrations(f);return S.set(w,R),R})},async history(f){let{name:d}=f,p=`history-${d}`,w=S.get(p);return w||x.withLock(`history:${d}`,async()=>{await y(n);let D=await c.history(f);return S.set(p,D),D})}}}function P(t){return"predicate"in t}function xt(t,e=!0,n=!0){let i="",a=n?"export ":"",r=new Map,s=new Map,o=(v,m=[])=>{if(!e||!v&&!m.length)return"";let g=v?[v]:[];return m.forEach(k=>g.push(k)),`/**
2
+ * ${g.join(`
3
3
  * `)}
4
4
  */
5
- `},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let D=g.constraints.find(f=>f.predicate==="enum"||f.predicate==="oneOf");if(D&&Array.isArray(D.parameters)){let f=`${m}${_e(g.name)}`,p=D.parameters.map(x=>String(x));r.set(f,p)}}};c(n.fields,n.name);for(let[u,m]of Object.entries(n.nestedSchemas))c(m.fields,o(m.name));for(let[u,m]of r){i+=a(`Union type for ${u.toLowerCase()} field values`);let h=m.map(g=>`"${g}"`).join(" | ");i+=`${s}type ${u} = ${h};
5
+ `},c=v=>v.charAt(0).toUpperCase()+v.slice(1),u=(v,m)=>{for(let[g,k]of Object.entries(v))if(k.type==="enum"&&Array.isArray(k.values)){let $=`${m}${c(k.name)}`,h=k.values.map(y=>String(y));r.set($,h)}else if(k.type==="string"&&k.constraints){let $=k.constraints.find(h=>P(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if($&&P($)&&Array.isArray($.parameters)){let h=`${m}${c(k.name)}`,y=$.parameters.map(T=>String(T));r.set(h,y)}}else if(k.type==="record"){let $=`${m}${c(k.name)}`;s.set(k.name,$)}};u(t.fields,t.name);for(let[v,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(g=>u(g.fields,c(m.name))):u(m.fields,c(m.name));for(let[v,m]of r){i+=o(`Union type for ${v.toLowerCase()} field values`);let g=m.map(k=>`"${k}"`).join(" | ");i+=`${a}type ${v} = ${g};
6
6
 
7
- `}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(D=>`@constraint ${D.name}: ${D.description||D.predicate}`)||[];i+=a(m.description,g),i+=`${s}type ${h} = {
8
- `;for(let[D,f]of Object.entries(m.fields)){let p=f.constraints?.map($=>`@constraint ${$.name}: ${$.description||$.predicate}`)||[];f.unique&&p.push("@unique Ensures unique values"),f.default!==void 0&&p.push(`@default ${JSON.stringify(f.default)}`),e&&f.description?i+=a(f.description,p):p.length&&(i+=a(void 0,p)),f.deprecated&&(i+=` /** @deprecated */
9
- `);let x=Le(f,n,h),C=f.required===!1?"?":"";i+=` ${f.name}${C}: ${x};
10
- `}if(m.metadata&&(i+=` metadata: Record<string, any>;
7
+ `}for(let[v,m]of Object.entries(t.nestedSchemas||{})){let g=c(m.name),k=m.constraints?.map($=>P($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];if(m.concrete&&k.push("@concrete Indicates a concrete schema"),i+=o(m.description,k),Array.isArray(m.fields)){let $=m.fields.filter(b=>!b.when),h=m.fields.filter(b=>b.when),y="";if($.length>0){y+=`{
8
+ `;for(let b of $)for(let[f,d]of Object.entries(b.fields)){let p=d.constraints?.map(R=>P(R)?`@constraint ${R.name}: ${R.description||R.predicate}`:`@constraint ${R.name}`)||[];d.unique&&p.push("@unique Ensures unique values"),d.default!==void 0&&p.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?y+=o(d.description,p):p.length&&(y+=o(void 0,p)),d.deprecated&&(y+=` /** @deprecated */
9
+ `);let w=ae(d,t,g,s),D=d.required===!1?"?":"";y+=` ${d.name}${D}: ${w};
10
+ `}y+="}"}let T="";h.length>0&&(T=h.map(f=>{let d="";d+=`{
11
+ `;for(let[p,w]of Object.entries(f.fields)){let D=w.constraints?.map(G=>P(G)?`@constraint ${G.name}: ${G.description||G.predicate}`:`@constraint ${G.name}`)||[];w.unique&&D.push("@unique Ensures unique values"),w.default!==void 0&&D.push(`@default ${JSON.stringify(w.default)}`),e&&w.description?d+=o(w.description,D):D.length&&(d+=o(void 0,D)),w.deprecated&&(d+=` /** @deprecated */
12
+ `);let R=ae(w,t,g,s),O=w.required===!1?"?":"";d+=` ${w.name}${O}: ${R};
13
+ `}if(f.when)for(let[p,w]of Object.entries(f.when))d+=` ${p}: "${w}";
14
+ `;return d+="}",d}).join(" | ")),y&&T?i+=`${a}type ${g} = ${y} & (${T});
15
+
16
+ `:y?i+=`${a}type ${g} = ${y};
17
+
18
+ `:T&&(i+=`${a}type ${g} = ${T};
19
+
20
+ `)}else{i+=`${a}type ${g} = {
21
+ `;for(let[$,h]of Object.entries(m.fields)){let y=h.constraints?.map(f=>P(f)?`@constraint ${f.name}: ${f.description||f.predicate}`:`@constraint ${f.name}`)||[];h.unique&&y.push("@unique Ensures unique values"),h.default!==void 0&&y.push(`@default ${JSON.stringify(h.default)}`),e&&h.description?i+=o(h.description,y):y.length&&(i+=o(void 0,y)),h.deprecated&&(i+=` /** @deprecated */
22
+ `);let T=ae(h,t,g,s),b=h.required===!1?"?":"";i+=` ${h.name}${b}: ${T};
23
+ `}m.metadata&&(i+=` metadata: Record<string, any>;
11
24
  `),i+=`};
12
25
 
13
- `,m.indexes?.length){i+=a(`Available indexes for ${h}`),i+=`${s}enum ${h}IndexNames {
14
- `;for(let D of m.indexes)i+=` ${D.name} = "${D.name}",
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${g}`),i+=`${a}enum ${g}IndexNames {
27
+ `;for(let $ of m.indexes)i+=` ${$.name} = "${$.name}",
15
28
  `;i+=`}
16
29
 
17
- `}}let d=n.constraints?.map(u=>`@constraint ${u.name}: ${u.description||u.predicate}`)||[];i+=a(n.description,d),i+=`${s}type ${n.name} = {
18
- `;for(let[u,m]of Object.entries(n.fields)){let h=m.constraints?.map(f=>`@constraint ${f.name}: ${f.description||f.predicate}`)||[];m.unique&&h.push("@unique Ensures unique values"),m.default!==void 0&&h.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=a(m.description,h):h.length&&(i+=a(void 0,h)),m.deprecated&&(i+=` /** @deprecated */
19
- `);let g=Le(m,n,n.name),D=m.required===!1?"?":"";i+=` ${m.name}${D}: ${g};
20
- `}if(n.metadata&&(i+=` metadata: Record<string, any>;
30
+ `}}let l=t.constraints?.map(v=>P(v)?`@constraint ${v.name}: ${v.description||v.predicate}`:`@constraint ${v.name}`)||[];i+=o(t.description,l);let x=Array.from(s.entries()).map(([v,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),S=s.size>0?`<${x}>`:"";i+=`${a}type ${t.name}${S} = {
31
+ `;for(let[v,m]of Object.entries(t.fields)){let g=m.constraints?.map(h=>P(h)?`@constraint ${h.name}: ${h.description||h.predicate}`:`@constraint ${h.name}`)||[];m.unique&&g.push("@unique Ensures unique values"),m.default!==void 0&&g.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,g):g.length&&(i+=o(void 0,g)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let k=ae(m,t,t.name,s),$=m.required===!1?"?":"";i+=` ${m.name}${$}: ${k};
33
+ `}if(t.metadata&&(i+=` metadata: Record<string, any>;
21
34
  `),i+=`};
22
35
 
23
- `,n.indexes?.length){i+=a(`Available indexes for ${n.name}`),i+=`${s}enum ${n.name}IndexNames {
24
- `;for(let u of n.indexes)i+=` ${u.name} = "${u.name}",
36
+ `,t.indexes?.length){i+=o(`Available indexes for ${t.name}`),i+=`${a}enum ${t.name}IndexNames {
37
+ `;for(let v of t.indexes)i+=` ${v.name} = "${v.name}",
25
38
  `;i+=`}
26
- `}return i}function Le(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${_e(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${$e(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${$e(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return $e(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function _e(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function $e(n){return n.charAt(0).toUpperCase()+n.slice(1)}function vt(n,e=!0){let i=`${e?"export ":""}interface ${n.name}Validator {
39
+ `}return i.trim()}function ae(t,e,n,i){switch(t.type){case"string":if(t.constraints){let a=t.constraints.find(r=>P(r)&&(r.predicate==="enum"||r.predicate==="oneOf"));if(a&&P(a)&&Array.isArray(a.parameters))return`${n}${N(t.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`${N(a.name)}[]`}return`${t.itemsType}[]`}return"any[]";case"set":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`Set<${N(a.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${N(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return N(a.name)}if(t.nestedSchema){let a=e.nestedSchemas[t.nestedSchema.id];return N(a.name)}return t.reference?`${t.reference.schema}${t.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(t.name)||"Record<string, any>";case"union":return t.schema&&Array.isArray(t.schema)?t.schema.map(r=>{let s=e.nestedSchemas[r.id];return N(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function N(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Tt(t,e=!0){let i=`${e?"export ":""}interface ${t.name}Validator {
27
40
  `;return i+=` /**
28
- * Validates a ${n.name} object against all schema constraints
41
+ * Validates a ${t.name} object against all schema constraints
29
42
  * @param data The data to validate
30
43
  * @returns Validation result with any errors
31
44
  */
32
- `,i+=` validate(data: ${n.name}): { valid: boolean; errors: Array<{ field: string; message: string }> };
45
+ `,i+=` validate(data: ${t.name}): { valid: boolean; errors: Array<{ field: string; message: string }> };
33
46
 
34
47
  `,i+=` /**
35
- * Checks if the given object conforms to the ${n.name} type structure
48
+ * Checks if the given object conforms to the ${t.name} type structure
36
49
  * @param data The object to check
37
50
  * @returns Whether the object matches the expected structure
38
51
  */
39
- `,i+=` isType(data: any): data is ${n.name};
52
+ `,i+=` isType(data: any): data is ${t.name};
40
53
  `,i+=`}
41
- `,i}function xt(n,e){let t=[],i=a=>a===void 0?"`None`":`\`${JSON.stringify(a,null,2)}\``,s=a=>{let o=`**${a.field}** ${a.operator}`;return a.value!==void 0&&(o+=` ${JSON.stringify(a.value)}`),a.conditions&&(o+=` [
42
- ${a.conditions.map(c=>` ${s(c)}`).join(`
54
+ `,i}function Ct(t,e){let n=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,a=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
55
+ ${s.conditions.map(c=>` ${a(c)}`).join(`
43
56
  `)}
44
- ]`),o},r=(a,o=1)=>{let c="#".repeat(o+2);return Object.entries(a).map(([d,u])=>{let m=`${c} ${d} (${u.type})
57
+ ]`),o},r=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,l])=>{let x=`${c} ${u} (${l.type})
45
58
 
46
- `;return m+=`**Required:** ${u.required?"Yes":"No"}
59
+ `;return x+=`**Required:** ${l.required?"Yes":"No"}
47
60
 
48
- `,u.description&&(m+=`**Description:** ${u.description}
61
+ `,l.description&&(x+=`**Description:** ${l.description}
49
62
 
50
- `),u.itemsType&&(m+=`**Item Type:** ${u.itemsType}
63
+ `),l.itemsType&&(x+=`**Item Type:** ${l.itemsType}
51
64
 
52
- `),u.nestedSchema&&(m+=r(u.nestedSchema,o+1)),m}).join(`
53
- `)};t.push(`# ${n.name} Schema (Version ${n.version})`),n.description&&t.push(`
54
- ${n.description}
55
- `),t.push("## Metadata"),t.push(`- **Dependencies:** ${n.dependencies?.join(", ")||"None"}`),t.push(`- **Created:** ${new Date().toISOString()}
56
- `),t.push(`## Fields
57
- `),t.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),t.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[a,o]of Object.entries(n.fields))t.push([a,o.type,o.required?"Yes":"No",i(o.default),o.description?.replace(/\n/g," ")||"",o.deprecated?"Yes":"No",o.unique?"Yes":"No",o.constraints?.length||0].join("|"));Object.entries(n.fields).forEach(([a,o])=>{o.nestedSchema&&(t.push(`
58
- ### Nested Schema: ${a}
59
- `),t.push(r(o.nestedSchema)))}),t.push(`
65
+ `),l.nestedSchema&&(x+=r(l.nestedSchema,o+1)),x}).join(`
66
+ `)};n.push(`# ${t.name} Schema (Version ${t.version})`),t.description&&n.push(`
67
+ ${t.description}
68
+ `),n.push("## Metadata"),n.push(`- **Dependencies:** ${t.dependencies?.join(", ")||"None"}`),n.push(`- **Created:** ${new Date().toISOString()}
69
+ `),n.push(`## Fields
70
+ `),n.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),n.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,o]of Object.entries(t.fields))n.push([s,o.type,o.required?"Yes":"No",i(o.default),o.description?.replace(/\n/g," ")||"",o.deprecated?"Yes":"No",o.unique?"Yes":"No",o.constraints?.length||0].join("|"));Object.entries(t.fields).forEach(([s,o])=>{o.nestedSchema&&(n.push(`
71
+ ### Nested Schema: ${s}
72
+ `),n.push(r(o.nestedSchema)))}),n.push(`
60
73
  ## Indexes
61
- `),t.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),t.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let a of n.indexes||[])t.push([a.name,a.type,a.fields.join(", "),a.unique?"Yes":"No",a.order||"asc",a.partial?s(a.partial):"None",a.description||""].join("|"));t.push(`
74
+ `),n.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),n.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of t.indexes||[])n.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?a(s.partial):"None",s.description||""].join("|"));n.push(`
62
75
  ## Constraints
63
- `),n.constraints&&t.push("### Schema-level Constraints"),t.push(`
76
+ `),t.constraints&&n.push("### Schema-level Constraints"),n.push(`
64
77
  ## Migrations
65
- `),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let a of n.migrations||[])t.push([a.id,a.description,a.status,a.changes.length].join("|"));if(n.mock&&e?.faker)try{let a=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(a,null,2)+"\n```")}catch{t.push(`
66
- <!-- Error generating mock data -->`)}return t.join(`
67
- `)}function Et(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(s=>{t[s.name]={label:s.label,description:s.description}}),Ge(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[s,r]of Object.entries(e)){let a=s!=="ungrouped"?t[s]:void 0;i.push({name:s!=="ungrouped"?s:"ungrouped",label:a?.label||"Ungrouped",description:a?.description,fields:r})}return i}function Ge(n,e,t,i){for(let[s,r]of Object.entries(n)){let a=e?`${e}.${r.name}`:r.name,o={...r,name:a};if(!r.hint?.input?.ignore){if(r.type!=="object"){let c=r.hint?.input?.group||"ungrouped";i[c]||(i[c]=[]),i[c].push(o)}if(r.nestedSchema?.id&&t[r.nestedSchema.id]){let c=t[r.nestedSchema.id];Ge(c.fields,a,t,i)}}}}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,generateSHA256Hash,generateValidationInterface,normalizePath,schemaChangeToPatch,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
78
+ `),n.push("| ID | Description | Status | Changes |"),n.push("|----|-------------|--------|---------|");for(let s of t.migrations||[])n.push([s.id,s.description,s.status,s.changes.length].join("|"));if(t.mock&&e?.faker)try{let s=t.mock(e.faker).next().value;n.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{n.push(`
79
+ <!-- Error generating mock data -->`)}return n.join(`
80
+ `)}function kt(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(a=>{n[a.name]={label:a.label,description:a.description}}),Je(t.fields,"",t.nestedSchemas||{},e);let i=[];for(let[a,r]of Object.entries(e)){let s=a!=="ungrouped"?n[a]:void 0;i.push({name:a!=="ungrouped"?a:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:r})}return i}function Je(t,e,n,i){for(let[a,r]of Object.entries(t)){let s=e?`${e}.${r.name}`:r.name,o={...r,name:s};if(!r.hint?.input?.ignore){if(r.type!=="object"){let c=r.hint?.input?.group||"ungrouped";i[c]||(i[c]=[]),i[c].push(o)}if(r.nestedSchema?.id&&n[r.nestedSchema.id]){let c=n[r.nestedSchema.id];Je(c.fields,s,n,i)}}}}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,formResolver,generateSHA256Hash,generateValidationInterface,normalizePath,schemaChangeToPatch,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
package/index.d.cts CHANGED
@@ -3,6 +3,7 @@ import { Faker } from '@faker-js/faker';
3
3
  import { QueryDSL, QueryFilter } from '@asaidimu/query';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
5
5
  import LightningFS from '@isomorphic-git/lightning-fs';
6
+ import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
6
7
 
7
8
  /**
8
9
  * hints.ts
@@ -129,10 +130,22 @@ type DynamicHint = {
129
130
  group?: string;
130
131
  ignore?: boolean;
131
132
  };
133
+ /**
134
+ * Hints for generating a date input control.
135
+ */
136
+ type DateHint = {
137
+ type: "date" | "datetime" | "time";
138
+ label?: string;
139
+ placeholder?: string;
140
+ min?: string;
141
+ max?: string;
142
+ group?: string;
143
+ ignore?: boolean;
144
+ };
132
145
  /**
133
146
  * Union type for all possible input hints.
134
147
  */
135
- type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint;
148
+ type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint | DateHint;
136
149
  /**
137
150
  * Defines metadata for a group of inputs at the schema level.
138
151
  */
@@ -239,7 +252,7 @@ interface FieldDefinition<T> {
239
252
  name: string;
240
253
  type: FieldType;
241
254
  required?: boolean;
242
- constraints?: Constraint<any>[];
255
+ constraints?: Array<Constraint<any> | ConstraintGroup<any>>;
243
256
  default?: T;
244
257
  /** For type 'enum', specifies the allowed values. */
245
258
  values?: Array<string | number>;
@@ -1495,9 +1508,32 @@ declare class MigrationEngine {
1495
1508
  */
1496
1509
  declare const createSchemaMigrationHelper: <T>(schema: Readonly<SchemaDefinition>) => SchemaMigrationHelper;
1497
1510
 
1498
- declare function validateMigration<T>(change: any): change is Migration<T>;
1499
- declare function validateSchemaChange<T>(change: any): change is SchemaChange<T>;
1500
- declare function validateSchemaDefinition(schema: any): schema is SchemaDefinition;
1511
+ /**
1512
+ * Validates a migration object against the standard schema.
1513
+ * @template T The expected type of the migration data.
1514
+ * @param change The object to validate.
1515
+ * @returns A type guard indicating whether the object conforms to Migration<T>.
1516
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1517
+ */
1518
+ declare function validateMigration<T>(change: unknown): change is Migration<T>;
1519
+ /**
1520
+ * Validates a schema change object against the standard schema.
1521
+ * @template T The expected type of the schema change data.
1522
+ * @param change The object to validate.
1523
+ * @returns A type guard indicating whether the object conforms to SchemaChange<T>.
1524
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1525
+ */
1526
+ declare function validateSchemaChange<T>(change: unknown): change is SchemaChange<T>;
1527
+ /**
1528
+ * Validates a schema definition object against the standard schema.
1529
+ * @param schema The object to validate.
1530
+ * @returns A type guard indicating whether the object conforms to SchemaDefinition.
1531
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1532
+ */
1533
+ declare function validateSchemaDefinition(schema: unknown): schema is SchemaDefinition;
1534
+ /**
1535
+ * Alias for validateSchemaDefinition, provided for convenience.
1536
+ */
1501
1537
  declare const validate: typeof validateSchemaDefinition;
1502
1538
 
1503
1539
  /**
@@ -1520,9 +1556,10 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1520
1556
  * Converts a SchemaDefinition to TypeScript type definitions
1521
1557
  *
1522
1558
  * Analyzes a schema definition and generates TypeScript type declarations for the main schema,
1523
- * nested schemas, and union types for enum-like constraints. Uses capitalized field.name for field names,
1524
- * capitalized nestedSchema.name for type names, and ignores UUID keys. Handles required/optional fields,
1525
- * union types, primitives, arrays, sets, references, and nested structures with strict type safety.
1559
+ * nested schemas, and union types for enum fields and constraints. Uses field.name as-is for field names,
1560
+ * capitalized nestedSchema.name for type names, and handles required/optional fields, new types (enum,
1561
+ * record, union), discriminated unions with common fields, primitives, arrays, sets, references, and nested
1562
+ * structures with strict type safety. Introduces unique generics for each record field.
1526
1563
  *
1527
1564
  * @param schema - The schema definition to convert
1528
1565
  * @param includeComments - Whether to include JSDoc comments (default: true)
@@ -1541,22 +1578,14 @@ declare function generateValidationInterface(schema: SchemaDefinition, exportTyp
1541
1578
  declare function serializeParams(params: any): string;
1542
1579
  /**
1543
1580
  * Creates a Standard Schema validator that conforms to the StandardSchemaV1 interface.
1544
- * The validator uses a closure pattern to maintain internal state and avoid prop drilling.
1545
- * Instead of only returning a boolean, the validator collects detailed error issues if validation fails.
1546
- *
1547
- * @template T - The type of the data object to validate
1548
- * @param {SchemaDefinition} schema - The schema definition containing field and constraint rules
1549
- * @param {PredicateMap} constraintsMap - A map of constraint names to predicate functions
1550
- * @returns {StandardSchemaV1<T, T>} An object conforming to the StandardSchemaV1 interface
1551
- *
1552
- * @example
1553
- * const validator = createStandardSchemaValidator(mySchema, myConstraints);
1554
- * const result = validator["~standard"].validate(data);
1555
- * if ('issues' in result) {
1556
- * console.log('Validation failed:', result.issues);
1557
- * }
1558
1581
  */
1559
1582
  declare function createStandardSchemaValidator<T extends Record<string, any>>(schema: SchemaDefinition, constraintsMap: PredicateMap): StandardSchemaV1<T, T>;
1583
+ /**
1584
+ * Adapts a StandardSchemaV1 validator to React Hook Form's resolver interface.
1585
+ * @param validator - The StandardSchemaV1 validator instance.
1586
+ * @returns A resolver function compatible with React Hook Form.
1587
+ */
1588
+ declare function formResolver<TFieldValues extends FieldValues>(validator: ReturnType<typeof createStandardSchemaValidator>["~standard"]): (values: TFieldValues, context: unknown, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
1560
1589
 
1561
1590
  /**
1562
1591
  * Calculates the next version number based on schema changes.
@@ -1604,4 +1633,4 @@ interface FieldGroup {
1604
1633
  */
1605
1634
  declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
1606
1635
 
1607
- export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldGroup, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
1636
+ export { type ArrayHint, type BooleanHint, type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type DateHint, type DynamicHint, type EnumHint, type FieldDefinition, type FieldGroup, type FieldSchema, type FieldType, type FileHint, type FunctionMap, type GroupDefinition, type IndexDefinition, type IndexType, type InputHint, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type NumberHint, type ObjectHint, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaHint, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type SecretHint, type SetHint, type TextHint, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, formResolver, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
package/index.d.ts CHANGED
@@ -3,6 +3,7 @@ import { Faker } from '@faker-js/faker';
3
3
  import { QueryDSL, QueryFilter } from '@asaidimu/query';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
5
5
  import LightningFS from '@isomorphic-git/lightning-fs';
6
+ import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
6
7
 
7
8
  /**
8
9
  * hints.ts
@@ -129,10 +130,22 @@ type DynamicHint = {
129
130
  group?: string;
130
131
  ignore?: boolean;
131
132
  };
133
+ /**
134
+ * Hints for generating a date input control.
135
+ */
136
+ type DateHint = {
137
+ type: "date" | "datetime" | "time";
138
+ label?: string;
139
+ placeholder?: string;
140
+ min?: string;
141
+ max?: string;
142
+ group?: string;
143
+ ignore?: boolean;
144
+ };
132
145
  /**
133
146
  * Union type for all possible input hints.
134
147
  */
135
- type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint;
148
+ type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint | DateHint;
136
149
  /**
137
150
  * Defines metadata for a group of inputs at the schema level.
138
151
  */
@@ -239,7 +252,7 @@ interface FieldDefinition<T> {
239
252
  name: string;
240
253
  type: FieldType;
241
254
  required?: boolean;
242
- constraints?: Constraint<any>[];
255
+ constraints?: Array<Constraint<any> | ConstraintGroup<any>>;
243
256
  default?: T;
244
257
  /** For type 'enum', specifies the allowed values. */
245
258
  values?: Array<string | number>;
@@ -1495,9 +1508,32 @@ declare class MigrationEngine {
1495
1508
  */
1496
1509
  declare const createSchemaMigrationHelper: <T>(schema: Readonly<SchemaDefinition>) => SchemaMigrationHelper;
1497
1510
 
1498
- declare function validateMigration<T>(change: any): change is Migration<T>;
1499
- declare function validateSchemaChange<T>(change: any): change is SchemaChange<T>;
1500
- declare function validateSchemaDefinition(schema: any): schema is SchemaDefinition;
1511
+ /**
1512
+ * Validates a migration object against the standard schema.
1513
+ * @template T The expected type of the migration data.
1514
+ * @param change The object to validate.
1515
+ * @returns A type guard indicating whether the object conforms to Migration<T>.
1516
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1517
+ */
1518
+ declare function validateMigration<T>(change: unknown): change is Migration<T>;
1519
+ /**
1520
+ * Validates a schema change object against the standard schema.
1521
+ * @template T The expected type of the schema change data.
1522
+ * @param change The object to validate.
1523
+ * @returns A type guard indicating whether the object conforms to SchemaChange<T>.
1524
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1525
+ */
1526
+ declare function validateSchemaChange<T>(change: unknown): change is SchemaChange<T>;
1527
+ /**
1528
+ * Validates a schema definition object against the standard schema.
1529
+ * @param schema The object to validate.
1530
+ * @returns A type guard indicating whether the object conforms to SchemaDefinition.
1531
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1532
+ */
1533
+ declare function validateSchemaDefinition(schema: unknown): schema is SchemaDefinition;
1534
+ /**
1535
+ * Alias for validateSchemaDefinition, provided for convenience.
1536
+ */
1501
1537
  declare const validate: typeof validateSchemaDefinition;
1502
1538
 
1503
1539
  /**
@@ -1520,9 +1556,10 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1520
1556
  * Converts a SchemaDefinition to TypeScript type definitions
1521
1557
  *
1522
1558
  * Analyzes a schema definition and generates TypeScript type declarations for the main schema,
1523
- * nested schemas, and union types for enum-like constraints. Uses capitalized field.name for field names,
1524
- * capitalized nestedSchema.name for type names, and ignores UUID keys. Handles required/optional fields,
1525
- * union types, primitives, arrays, sets, references, and nested structures with strict type safety.
1559
+ * nested schemas, and union types for enum fields and constraints. Uses field.name as-is for field names,
1560
+ * capitalized nestedSchema.name for type names, and handles required/optional fields, new types (enum,
1561
+ * record, union), discriminated unions with common fields, primitives, arrays, sets, references, and nested
1562
+ * structures with strict type safety. Introduces unique generics for each record field.
1526
1563
  *
1527
1564
  * @param schema - The schema definition to convert
1528
1565
  * @param includeComments - Whether to include JSDoc comments (default: true)
@@ -1541,22 +1578,14 @@ declare function generateValidationInterface(schema: SchemaDefinition, exportTyp
1541
1578
  declare function serializeParams(params: any): string;
1542
1579
  /**
1543
1580
  * Creates a Standard Schema validator that conforms to the StandardSchemaV1 interface.
1544
- * The validator uses a closure pattern to maintain internal state and avoid prop drilling.
1545
- * Instead of only returning a boolean, the validator collects detailed error issues if validation fails.
1546
- *
1547
- * @template T - The type of the data object to validate
1548
- * @param {SchemaDefinition} schema - The schema definition containing field and constraint rules
1549
- * @param {PredicateMap} constraintsMap - A map of constraint names to predicate functions
1550
- * @returns {StandardSchemaV1<T, T>} An object conforming to the StandardSchemaV1 interface
1551
- *
1552
- * @example
1553
- * const validator = createStandardSchemaValidator(mySchema, myConstraints);
1554
- * const result = validator["~standard"].validate(data);
1555
- * if ('issues' in result) {
1556
- * console.log('Validation failed:', result.issues);
1557
- * }
1558
1581
  */
1559
1582
  declare function createStandardSchemaValidator<T extends Record<string, any>>(schema: SchemaDefinition, constraintsMap: PredicateMap): StandardSchemaV1<T, T>;
1583
+ /**
1584
+ * Adapts a StandardSchemaV1 validator to React Hook Form's resolver interface.
1585
+ * @param validator - The StandardSchemaV1 validator instance.
1586
+ * @returns A resolver function compatible with React Hook Form.
1587
+ */
1588
+ declare function formResolver<TFieldValues extends FieldValues>(validator: ReturnType<typeof createStandardSchemaValidator>["~standard"]): (values: TFieldValues, context: unknown, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
1560
1589
 
1561
1590
  /**
1562
1591
  * Calculates the next version number based on schema changes.
@@ -1604,4 +1633,4 @@ interface FieldGroup {
1604
1633
  */
1605
1634
  declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
1606
1635
 
1607
- export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldGroup, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
1636
+ export { type ArrayHint, type BooleanHint, type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type DateHint, type DynamicHint, type EnumHint, type FieldDefinition, type FieldGroup, type FieldSchema, type FieldType, type FileHint, type FunctionMap, type GroupDefinition, type IndexDefinition, type IndexType, type InputHint, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type NumberHint, type ObjectHint, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaHint, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type SecretHint, type SetHint, type TextHint, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, formResolver, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
package/index.js CHANGED
@@ -1,29 +1,42 @@
1
- import{createEventBus as qt}from"@asaidimu/events";import{createEventBus as Ct}from"@asaidimu/events";import{createMatcher as Dt,createPaginator as kt,createProjector as It,createSorter as Pt}from"@asaidimu/query";var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function _(n){let e=Oe(n);return e===""?[]:e.substring(1).split("/").map(Fe)}function Oe(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(L).join("/"):"/"+n.split(".").map(L).join("/")}function L(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Fe(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var A=new Map;function G(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function Q(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return n;let i=G(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function je(n,e,t){let i=A.get(e)||_(e);A.set(e,i);let s=G(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function U(n,e,t){let i=A.get(e)||_(e);if(A.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=G(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function Z(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return;let i=G(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function X(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=U(t,i.path,i.value);break;case"remove":t=Z(t,i.path);break;case"removeValue":t=je(t,i.path,i.value);break;case"replace":t=U(Z(t,i.path),i.path,i.value);break;case"copy":{let s=Q(t,i.from);t=U(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=Q(t,i.from);t=U(t,i.path,s),t=Z(t,i.from);break}case"test":{let s=Q(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function at(n,e){let t=[];return ee(n,e,"",t),t}function ee(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?Ne(n,e,t,i):Ve(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function Ne(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ee(n[r],e[r],a,i)}}function Ve(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=L(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ee(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=L(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function me(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=qe(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function qe(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function he(n){return n&&"operator"in n&&"rules"in n}function le(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function pe(n,e){let t={...n};return te(n)&&te(e)&&Object.keys(e).forEach(i=>{te(e[i])?i in n?t[i]=pe(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function te(n){return n&&typeof n=="object"&&!Array.isArray(n)}function J(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ue(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let v=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,v,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:v}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${J(f.parameters)}`,path:v})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],D=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let v=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:v});return}if(C!==void 0){if(g.push(...s(C,p.type,v)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...v,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,I)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...v,I.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...v,I.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:v}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,v,m,h)),p.nestedSchema.constraints?.forEach((E,I)=>{if("rules"in E)g.push(...r(E,C,d,[...v,`constraints[${I}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${J(E.parameters)}`,path:[...v,`constraints[${I}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...v,`constraints[${I}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...v,`constraints[${E}]`],h));else{let I=d[$.predicate];I?I({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${J($.parameters)}`,path:[...v,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...v,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!D.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let v=d[f.predicate];if(!v)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!v({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${J(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var O=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ie=n=>({value:n}),F=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],ye=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Le=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},ge=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},H=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],_e=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},ae=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(..._e(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},se=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ge(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...se(a,`${e}.rules[${o}]`)):t.push(...ae(a,`${e}.rules[${o}]`))}),t},V=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...se(i,`${e}[${s}]`)):t.push(...ae(i,`${e}[${s}]`))}),t},we=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...ge(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...we(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Se=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Le(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...H(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...we(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},z=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...Se(i,`${e}[${s}]`))),t},re=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ye(n.type,`${e}.type`)),t.push(...H(n.required,`${e}.required`,!1)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...ye(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...V(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...z(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...H(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...H(n.unique,`${e}.unique`,!1)),t},$e=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...re(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...z(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},Ge=n=>{if(typeof n!="object"||n===null)return F([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...re(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...$e(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...z(e.indexes,"indexes")),e.constraints&&t.push(...V(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...be(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?F(t):ie(e)},ne=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...re(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...V(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...z(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...Se(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...se(n.constraint,`${e}.constraint`)):t.push(...ae(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...$e(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},Je=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},be=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...ne(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...ne(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...Je(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},ve={"~standard":{version:1,vendor:"xAI",validate:Ge,types:{input:{},output:{}}}};var xe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return F([{message:"Migration must be an object",path:[]}]);let e=n,t=be(e,"");return t.length>0?F(t):ie(e)},types:{input:{},output:{}}}},Ee={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return F([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...ne(i,`[${s}]`))),t.length>0?F(t):ie(e)},types:{input:[],output:[]}}};function Ce(n){try{return!xe["~standard"].validate(n).issues}catch(e){throw new O("Invalid migration definition",e)}}function Te(n){try{return!Ee["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}function q(n){try{return!ve["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}var mt=q;var j=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(n).digest("hex")}};function He(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function ze(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function Be(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function Ke(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function We(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function Ye(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return We(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=ze(e,t);return i?Ke(e.parameters,n.parameters,i):!0}return!1}function Qe(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return Be(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return Ye(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function Ze(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);s.add(r.id);break}}function Xe(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function De(n,e,t){if(e.length===0)throw new Error("No changes provided");Ze(e),Xe(e);let i=He(n),s="patch";for(let r of e){let a=Qe(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function M(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function pt(n){return n.sort(M)}var x=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},et=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(et||{}),ke=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!q(e))throw new x("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>Ce(s)))throw new x("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>M(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>M(s.version,r.version)))}catch(s){throw s instanceof x?s:new x("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await j(t)}catch(t){throw new x("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new x("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Te(i))}catch(i){throw new x("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof x?s:new x("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?M(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=De(e.version,t);return t.map(a=>{try{return me(a,e)}catch(o){throw new x("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return X(a,o)}catch(c){throw new x("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof x?s:new x("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new x("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,t){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let s=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new x(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new x(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new x(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new x(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new x(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof x?t:new x("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var tt=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};import"@isomorphic-git/lightning-fs";import T from"isomorphic-git";import K from"isomorphic-git/http/web";import nt from"@isomorphic-git/lightning-fs";function Ie(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Pe(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function oe(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ce(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}import{Buffer as it}from"buffer";window.Buffer=it;var B=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new nt(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!q(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await j(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await j(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));M(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>M(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:oe(o.forward),backward:oe(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await j(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ie(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Pe(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ce(e.transform.forward),backward:ce(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var de=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},ue=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function W(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function Y(n,e,t,i,s){await i.init(),await T.init({fs:n,dir:e,defaultBranch:t}),await T.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.add({fs:n,dir:e,filepath:"."}),await T.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function sn(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new B(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new de,h=new ue(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(k){if(console.warn(`Failed with proxy ${b}: ${k.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function D(l,y="."){return W(async()=>(await T.add({fs:d,dir:u,filepath:y}),(await T.statusMatrix({fs:d,dir:u})).some(([b,k,R])=>k!==R)?await T.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return W(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function v(l){return(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return W(async()=>{let w=(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return W(async()=>{await T.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.push({fs:d,http:K,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function I(l,y=!0){i&&await g(async w=>{try{await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.clone({fs:d,http:K,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await Y(d,u,t,c,r),await T.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await Y(d,u,t,c,r)}else await Y(d,u,t,c,r)}else await Y(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await D(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await D(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await D(`chore: delete schema ${y}`),b=await v(`${y}-`);if(i&&w){await E(t);for(let k of b)await E(k,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${k}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,k=h.get(b);return k||m.withLock(`schema:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await D("chore: sync local changes"),i){await I(t,!1),await E(t);let l=await T.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,k=h.get(b);return k||m.withLock(`migrations:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let k=await c.history(l);return h.set(w,k),k})}}}function fn(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
2
- * ${h.join(`
1
+ import{createEventBus as _t}from"@asaidimu/events";import{createEventBus as Dt}from"@asaidimu/events";import{createMatcher as Rt,createPaginator as At,createProjector as Pt,createSorter as Ft}from"@asaidimu/query";var A=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function B(n){let e=Oe(n);return e===""?[]:e.substring(1).split("/").map(je)}function Oe(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(z).join("/"):"/"+n.split(".").map(z).join("/")}function z(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function je(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var F=new Map;function K(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new A(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let a=i==="-"?t.length:parseInt(i);if(isNaN(a)||a<0||a>t.length)throw new A(`Invalid array index: ${i}`);t=t[a]}else{if(!t.hasOwnProperty(i))throw new A(`Property ${i} not found`);t=t[i]}}return t}function ne(n,e){let t=F.get(e)||B(e);if(F.set(e,t),t.length===0)return n;let i=K(n,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(i)){let r=parseInt(a);if(isNaN(r)||r<0||r>=i.length)throw new A(`Invalid array index: ${a}`);return i[r]}return i[a]}function Ve(n,e,t){let i=F.get(e)||B(e);F.set(e,i);let a=K(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(s=>s!==t)):a[r]===t&&delete a[r],n}function H(n,e,t){let i=F.get(e)||B(e);if(F.set(e,i),i.length===0)return t;let a=i.slice(0,-1),r=i[i.length-1],s=K(n,a);if(Array.isArray(s))if(r==="-")s.push(t);else{let o=parseInt(r);if(o<0||o>s.length)throw new A(`Invalid array index: ${r}`);s.splice(o,0,t)}else s[r]=t;return n}function ie(n,e){let t=F.get(e)||B(e);if(F.set(e,t),t.length===0)return;let i=K(n,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(i)){let r=parseInt(a);i.splice(r,1)}else delete i[a];return n}function se(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=H(t,i.path,i.value);break;case"remove":t=ie(t,i.path);break;case"removeValue":t=Ve(t,i.path,i.value);break;case"replace":t=H(ie(t,i.path),i.path,i.value);break;case"copy":{let a=ne(t,i.from);t=H(t,i.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=ne(t,i.from);t=H(t,i.path,a),t=ie(t,i.from);break}case"test":{let a=ne(t,i.path);if(JSON.stringify(a)!==JSON.stringify(i.value))throw new A("Test operation failed");break}default:throw new A(`Unsupported operation: ${i.op}`)}}catch(a){throw a instanceof A&&(a.operation=i),a}return t}function rt(n,e){let t=[];return ae(n,e,"",t),t}function ae(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?Ne(n,e,t,i):qe(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function Ne(n,e,t,i){let a=Math.max(n.length,e.length);for(let r=0;r<a;r++){let s=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:s}):ae(n[r],e[r],s,i)}}function qe(n,e,t,i){let a=new Set,r=Object.keys(n),s=Object.keys(e);for(let o of r){let c=z(o),u=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ae(n[o],e[o],u,i),a.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!a.has(o)){let c=z(o),u=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function pe(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([a,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${a}`,value:r}):t.push({op:"replace",path:`${i}/${a}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(a=>a.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(a=>a.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([a,r])=>{t.push({op:"replace",path:`/indexes/${i}/${a}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(a=>Array.isArray(a)?a.some(r=>r.name===n.name):a.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=Le(e,n.name);i&&Object.entries(n.changes).forEach(([a,r])=>{t.push({op:"replace",path:`${i}/${a}`,value:r})});break}}return t}function Le(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(ye(i)){let a=ge(i.rules,e);if(a)return`/constraints/${t}${a}`}}return null}function ye(n){return n&&"operator"in n&&"rules"in n}function ge(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(ye(i)){let a=ge(i.rules,e);if(a)return`/rules/${t}${a}`}}return null}function $e(n,e){let t={...n};return re(n)&&re(e)&&Object.keys(e).forEach(i=>{re(e[i])?i in n?t[i]=$e(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function re(n){return n&&typeof n=="object"&&!Array.isArray(n)}function W(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ue(n,e){let t=o=>({value:o}),i=o=>({issues:o}),a=(o,c,u,l)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:u}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:u}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:u}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:u}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:u}]:[];case"enum":return l?.values?l.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(l.values)}, got ${o}`,path:u}]:[{message:"Enum type requires 'values' definition",path:u}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:u}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:u}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:u}]}};function r(o,c,u,l,x){let S=[],v=o.rules.map((g,C)=>{let $=[...l,`rules[${C}]`];if("rules"in g){if(x.has(g.name))return!0;x.add(g.name);let h=r(g,c,u,$,x);return S.push(...h),h.length===0}else{let h=u[g.predicate];if(!h)return S.push({message:`Predicate '${g.predicate}' not found`,path:$}),!1;let y=h({data:c,field:g.field,arguments:g.parameters});if(!y){let T=g.field?` for field '${g.field}'`:"";S.push({message:g.errorMessage||`Constraint '${g.name}' failed${T} with params ${W(g.parameters)}`,path:$})}return y}});return(()=>{switch(o.operator){case"and":return v.every(g=>g);case"or":return v.some(g=>g);case"not":return!v.every(g=>g);case"nor":return!v.some(g=>g);case"xor":return v.filter(g=>g).length===1}})()||S.push({message:`Constraint group '${o.name}' failed`,path:l}),S}function s(o,c,u,l,x,S=new Set,v){let m=[],g;if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))g=c.fields;else{let h=c.fields.find(y=>!y.when||v&&v[y.when.field]!==void 0&&v[y.when.field]===y.when.value);if(!h)return m.push({message:"No matching field set found for discriminated schema",path:l}),m;g=h.fields}else g=c.fields;let C=new Set(Object.values(g).map($=>$.name));Object.entries(g).forEach(([$,h])=>{let y=[...l,h.name],T=Object.hasOwnProperty.call(o,h.name)?o[h.name]:void 0;if(h.required&&T==null){m.push({message:`Field '${h.name}' is required`,path:y});return}if(T!==void 0){if(m.push(...a(T,h.type,y,h)),h.type==="array"||h.type==="set"){h.itemsType&&Array.isArray(T)&&T.forEach((f,d)=>m.push(...a(f,h.itemsType,[...y,d.toString()])));let b=h.schema||h.nestedSchema;if(b&&!Array.isArray(b)){let f=x[b.id];f?T.forEach((d,p)=>{typeof d=="object"&&d!==null&&(S.has(b.id)?m.push({message:`Circular reference detected at '${b.id}'`,path:[...y,p.toString()]}):(S.add(b.id),m.push(...s(d,f,u,[...y,p.toString()],x,S,o)),S.delete(b.id)))}):m.push({message:`Nested schema '${b.id}' not found`,path:y})}}if(h.type==="object"){let b=h.schema||h.nestedSchema;if(b&&!Array.isArray(b)){let f=x[b.id];f?typeof T=="object"&&T!==null&&(S.has(b.id)?m.push({message:`Circular reference detected at '${b.id}'`,path:y}):(S.add(b.id),m.push(...s(T,f,u,y,x,S,o)),b.constraints?.forEach((d,p)=>{if("rules"in d)m.push(...r(d,T,u,[...y,`constraints[${p}]`],S));else{let w=u[d.predicate];w?w({data:T,field:void 0,arguments:d.parameters})||m.push({message:d.errorMessage||`Constraint '${d.name}' failed with params ${W(d.parameters)}`,path:[...y,`constraints[${p}]`]}):m.push({message:`Predicate '${d.predicate}' not found`,path:[...y,`constraints[${p}]`]})}}),S.delete(b.id))):m.push({message:`Nested schema '${b.id}' not found`,path:y})}}if(h.type==="union"){let b=h.schema;!b||!Array.isArray(b)?m.push({message:"Union type requires an array of schema references",path:y}):b.some(d=>{let p=x[d.id];return p?s(T,p,u,y,x,new Set(S),o).length===0:(m.push({message:`Nested schema '${d.id}' not found`,path:y}),!1)})||m.push({message:"Value does not match any union schema",path:y})}h.constraints?.forEach((b,f)=>{if("rules"in b)m.push(...r(b,o,u,[...y,`constraints[${f}]`],S));else{let d=u[b.predicate];d?d({data:o,field:h.name,arguments:b.parameters})||m.push({message:b.errorMessage||`Constraint '${b.name}' failed for field '${h.name}' with params ${W(b.parameters)}`,path:[...y,`constraints[${f}]`]}):m.push({message:`Predicate '${b.predicate}' not found`,path:[...y,`constraints[${f}]`]})}})}});for(let $ in o)Object.hasOwnProperty.call(o,$)&&!C.has($)&&m.push({message:`Unexpected field '${$}'`,path:[...l,$]});return c.constraints?.forEach(($,h)=>{if("rules"in $)m.push(...r($,o,u,[...l,`constraints[${h}]`],S));else{let y=u[$.predicate];if(!y)m.push({message:`Predicate '${$.predicate}' not found`,path:[...l,`constraints[${h}]`]});else if(!y({data:o,field:$.field,arguments:$.parameters})){let b=$.field?` for field '${$.field}'`:"";m.push({message:$.errorMessage||`Constraint '${$.name}' failed${b} with params ${W($.parameters)}`,path:[...l,`constraints[${h}]`]})}}}),m}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,n,e,[],n.nestedSchemas||{});return u.length>0?i(u):t(c)},types:{input:{},output:{}}}}}function dt(n){return async e=>{let t=n.validate(e);if(t instanceof Promise&&(t=await t),"value"in t)return{values:t.value,errors:{}};let i={};return t.issues.forEach(a=>{if(!a.path)return;let r=a.path,s=i;for(let o=0;o<r.length;o++){let c=r[o];o===r.length-1?s[c]={type:"validation",message:a.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var N=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ce=n=>({value:n}),q=n=>({issues:n}),E=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],we=(n,e)=>{let t=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},_e=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Se=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},G=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],Ge=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"enum":if(Array.isArray(n)&&n.length>0&&n.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"union":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},de=(n,e)=>{let t=[],i=["predicate","name"],a=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),t.push(...E(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(...Ge(n.parameters,"dynamic",`${e}.parameters`)),t.push(...E(n.description,`${e}.description`,!1)),t.push(...E(n.errorMessage,`${e}.errorMessage`,!1)),t},ue=(n,e)=>{let t=[],i=["name","operator","rules"],a=["name","operator","rules"],r=n;return i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),t.push(...Se(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((s,o)=>{"rules"in s?t.push(...ue(s,`${e}.rules[${o}]`)):t.push(...de(s,`${e}.rules[${o}]`))}),t},j=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,a)=>{"rules"in i?t.push(...ue(i,`${e}[${a}]`)):t.push(...de(i,`${e}[${a}]`))}),t},be=(n,e)=>{let t=[],i=["operator","field"],a=["operator","field","value","conditions"],r=n;return i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...Se(n.operator,`${e}.operator`)),t.push(...E(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((s,o)=>t.push(...be(s,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},ve=(n,e)=>{let t=[],i=["fields","type","name"],a=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),t.push(..._e(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(s=>typeof s=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...G(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...be(n.partial,`${e}.partial`)),t.push(...E(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},L=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,a)=>t.push(...ve(i,`${e}[${a}]`))),t},Je=(n,e,t,i,a)=>{let r=[];return n===void 0?[]:(t==="union"&&Array.isArray(n)?(n.length===0&&r.push({message:"Schema array must not be empty for union type",path:[e]}),n.forEach((s,o)=>{let c=`${e}[${o}]`;r.push(...E(s.id,`${c}.id`)),i.includes(s.id)||r.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&r.push(...j(s.constraints,`${c}.constraints`)),s.indexes&&r.push(...L(s.indexes,`${c}.indexes`))})):(t==="object"||t==="array"&&a==="object")&&!Array.isArray(n)?(r.push(...E(n.id,`${e}.id`)),i.includes(n.id)||r.push({message:`Schema ID '${n.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),n.constraints&&r.push(...j(n.constraints,`${e}.constraints`)),n.indexes&&r.push(...L(n.indexes,`${e}.indexes`))):r.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),r)},Y=(n,e,t)=>{let i=[],a=["name","type"],r=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=n;if(a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...E(n.name,`${e}.name`)),i.push(...we(n.type,`${e}.type`)),i.push(...G(n.required,`${e}.required`,!1)),n.constraints&&i.push(...j(n.constraints,`${e}.constraints`)),n.values!==void 0&&(n.type==="enum"?(!Array.isArray(n.values)||n.values.length===0||!n.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),n.schema!==void 0&&i.push(...Je(n.schema,`${e}.schema`,n.type,t,n.itemsType)),n.itemsType&&i.push(...we(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let o=["id"],c=["id","constraints","indexes"],u=n.nestedSchema;o.forEach(l=>{u[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.nestedSchema.${l}`]})}),Object.keys(u).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${l}`]})}),i.push(...E(n.nestedSchema.id,`${e}.nestedSchema.id`)),t.includes(n.nestedSchema.id)||i.push({message:`nestedSchema.id '${n.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),n.nestedSchema.constraints&&i.push(...j(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&i.push(...L(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...G(n.deprecated,`${e}.deprecated`,!1)),n.reference){let o=["schema","field"],c=["schema","field"],u=n.reference;o.forEach(l=>{u[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.reference.${l}`]})}),Object.keys(u).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.reference.${l}`]})}),i.push(...E(n.reference.schema,`${e}.reference.schema`)),i.push(...E(n.reference.field,`${e}.reference.field`))}return i.push(...E(n.description,`${e}.description`,!1)),i.push(...G(n.unique,`${e}.unique`,!1)),i},Ee=(n,e,t)=>{let i=[],a=["name","fields"],r=["name","description","concrete","fields","indexes","constraints","metadata"],s=n;return a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...E(n.name,`${e}.name`)),i.push(...G(n.concrete,`${e}.concrete`,!1)),Array.isArray(n.fields)?(n.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),n.fields.forEach((o,c)=>{let u=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[u]});else{let l=o.fields;typeof l!="object"||l===null?i.push({message:"Fields must be a non-empty object",path:[`${u}.fields`]}):Object.entries(l).forEach(([x,S])=>{i.push(...Y(S,`${u}.fields.${x}`,t))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${u}.when`]})}})):typeof n.fields=="object"&&n.fields!==null?Object.entries(n.fields).forEach(([o,c])=>{i.push(...Y(c,`${e}.fields.${o}`,t))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...E(n.description,`${e}.description`,!1)),n.indexes&&i.push(...L(n.indexes,`${e}.indexes`)),n.constraints&&i.push(...j(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},He=n=>{if(typeof n!="object"||n===null)return q([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],a=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[s]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[s]})}),t.push(...E(e.name,"name")),t.push(...E(e.version,"version")),typeof e.fields!="object"||e.fields===null)t.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{t.push(...Y(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...Ee(c,`nestedSchemas.${o}`,s)))}return t.push(...E(e.description,"description",!1)),e.indexes&&t.push(...L(e.indexes,"indexes")),e.constraints&&t.push(...j(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>t.push(...xe(s,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?q(t):ce(e)},oe=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),t.push(...Y(n.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],a=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let s=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...E(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...j(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...L(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...ve(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in n.constraint?t.push(...ue(n.constraint,`${e}.constraint`)):t.push(...de(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),t.push(...Ee(n.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],a=i,r=n;i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},ze=(n,e)=>{let t=[],i=["forward","backward"],a=i,r=n;return i.forEach(s=>{r[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},xe=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],a=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{a.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...E(n.id,`${e}.id`)),t.push(...E(n.schemaVersion,`${e}.schemaVersion`)),t.push(...E(n.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(n.status)||t.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...oe(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...oe(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...E(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...ze(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...E(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...E(n.checksum,`${e}.checksum`)),t},Te={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:He,types:{input:{},output:{}}}};var Ce={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:n=>{if(typeof n!="object"||n===null)return q([{message:"Migration must be an object",path:[]}]);let e=n,t=xe(e,"");return t.length>0?q(t):ce(e)},types:{input:{},output:{}}}},ke={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:n=>{if(!Array.isArray(n))return q([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,a)=>t.push(...oe(i,`[${a}]`))),t.length>0?q(t):ce(e)},types:{input:[],output:[]}}};function De(n){try{return!Ce["~standard"].validate(n).issues}catch(e){throw new N("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function Ie(n){try{return!ke["~standard"].validate(n).issues}catch(e){throw new N("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function J(n){try{return!Te["~standard"].validate(n).issues}catch(e){throw new N("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var pt=J;var U=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(n).digest("hex")}};function Be(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function Ke(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function We(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function Ye(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function Qe(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function Ze(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return Qe(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=Ke(e,t);return i?Ye(e.parameters,n.parameters,i):!0}return!1}function Xe(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return We(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return Ze(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function et(n){let e=new Set,t=new Set,i=new Set,a=new Set;for(let r of n)switch(r.type){case"addField":if(t.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);a.add(r.id);break}}function tt(n){let e=new Set,t=new Set,i=new Set;for(let a of n)switch(a.type){case"addConstraint":let r=a.constraint,s=("name"in r,r.name);if(t.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(e.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);t.add(a.name);break;case"modifyConstraint":if(t.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(i.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);e.add(a.name);break}}function Re(n,e,t){if(e.length===0)throw new Error("No changes provided");et(e),tt(e);let i=Be(n),a="patch";for(let r of e){let s=Xe(r,t);if(s==="major"){a="major";break}else s==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function M(n,e){let t=u=>u.split(".").map(l=>parseInt(l,10)||0),[i,a,r]=t(n),[s,o,c]=t(e);return i-s||a-o||r-c}function $t(n){return n.sort(M)}var k=class extends Error{constructor(t,i,a,r){super(t);this.code=i;this.migrationId=a;this.cause=r;this.name="MigrationError"}},nt=(S=>(S.INVALID_SCHEMA="INVALID_SCHEMA",S.INVALID_MIGRATION="INVALID_MIGRATION",S.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",S.TIMEOUT="TIMEOUT",S.MEMORY_LIMIT="MEMORY_LIMIT",S.CONCURRENT_OPERATION="CONCURRENT_OPERATION",S.TRANSFORM_ERROR="TRANSFORM_ERROR",S.VERSION_NOT_FOUND="VERSION_NOT_FOUND",S.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",S.STREAM_ERROR="STREAM_ERROR",S.ROLLBACK_ERROR="ROLLBACK_ERROR",S.MISSING_TRANSFORM="MISSING_TRANSFORM",S))(nt||{}),Ae=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!J(e))throw new k("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(a=>De(a)))throw new k("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((a,r)=>M(a.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((a,r)=>M(a.version,r.version)))}catch(a){throw a instanceof k?a:new k("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,a)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await U(t)}catch(t){throw new k("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new k("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Ie(i))}catch(i){throw new k("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},r=this.getRelevantMigrations(t,i),s=r.reduce((c,u)=>{let l=t==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,l,u.id)},a),o=await n.processMigrationList(e,t,r);return{newSchema:s,dataPreview:o}}catch(a){throw a instanceof k?a:new k("Dry run failed","INVALID_SCHEMA",void 0,a)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let a=e==="forward"?"pending":"applied",r=t?M(i.schemaVersion,t)>=0:!0;return i.status===a&&r}).sort((i,a)=>e==="forward"?i.id.localeCompare(a.id):a.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let a=Re(e.version,t);return t.map(s=>{try{return pe(s,e)}catch(o){throw new k("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return se(s,o)}catch(c){throw new k("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:a})}catch(a){throw a instanceof k?a:new k("Schema update failed","INVALID_SCHEMA",i,a)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new k("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,t){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let a=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return t;for(let o=0;o<r;o++)this.transformSchema("backward");let s=await n.processMigrationList(t,"backward",a);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,t);return{migration:s,transform:o}}catch(o){throw new k(`Failed to resolve transform for migration ${s.id}`,"TRANSFORM_ERROR",s.id,o)}}))).filter(s=>!!s.transform).reduce((s,{migration:o,transform:c})=>s.pipeThrough(new TransformStream({async transform(u,l){try{let x=await c(u);l.enqueue(x)}catch(x){l.error(new k(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,x))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new k(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let a=await i.text();if(typeof window<"u"){let r=new Blob([a],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),s={module:{exports:{}},console};return r(a,s,e),s.module.exports[t]}}catch(i){throw new k(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new k(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,a)=>this.applySchemaChanges(i,[a]),this.currentSchema)}catch(t){throw t instanceof k?t:new k("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var it=n=>{let e=[],t=[];return{addField:(i,a)=>{e.push({type:"addField",id:i,definition:a}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let a=n.fields[i];a&&t.push({type:"addField",id:i,definition:a})},modifyField:(i,a)=>{e.push({type:"modifyField",id:i,changes:a});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let a=n.indexes?.find(r=>r.name===i);a&&t.push({type:"addIndex",definition:a})},modifyIndex:(i,a)=>{e.push({type:"modifyIndex",name:i,changes:a});let r=n.indexes?.find(s=>s.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let a=n.constraints?.find(r=>"name"in r&&r.name===i);a&&t.push({type:"addConstraint",constraint:a})},modifyConstraint:(i,a)=>{e.push({type:"modifyConstraint",name:i,changes:a});let r=n.constraints?.find(s=>"name"in s&&s.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,a)=>{e.push({type:"addNestedSchema",id:i,definition:a}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let a=n.nestedSchemas[i];a&&t.push({type:"addNestedSchema",id:i,definition:a})},modifyNestedSchema:(i,a)=>{e.push({type:"modifyNestedSchema",id:i,changes:a});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};import"@isomorphic-git/lightning-fs";import I from"isomorphic-git";import Z from"isomorphic-git/http/web";import st from"@isomorphic-git/lightning-fs";function Pe(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Fe(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function fe(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),a=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,s;return t?(r=t[1],s=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],s=i[2].trim()):a?(r=a[2],s=a[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:s,type:t?"arrow":i?"function":a?"method":"unknown"})}function le(n){let{params:e,body:t,type:i}=JSON.parse(n),a=new Function(e,t);return i==="arrow"&&Object.defineProperty(a,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),a}import{Buffer as at}from"buffer";window.Buffer=at;var Q=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new st(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!J(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,a=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let s=await U(r);await this.updateIndex(i,e,s,a,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let a=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(a))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(a,"utf8")))),s=await this.readSchemaIndex(e);return t&&t!==s.version&&!s.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let a=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await U(a)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),a=t||i.version,r=[];for(let[s,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let u=JSON.parse(String(await this.fsp.readFile(c,"utf8")));M(u.schemaVersion,a)<=0&&r.push(this.deserializeMigration(u))}}return r.sort((s,o)=>M(s.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async a=>({...i,version:a.version,description:a.description,migrations:await this.migrations({name:e,version:a.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let a={...i};if(i.transform?.forward){let o=i.transform;a.transform={forward:fe(o.forward),backward:fe(o.backward||(c=>c))}}let r=JSON.stringify(a),s=await U(r);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,r,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Pe(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Fe(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:le(e.transform.forward),backward:le(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,a,r){let s=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:a.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,a.forEach(({id:c,hash:u,checksum:l})=>{o.migrations[c]={hash:u,checksum:l}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let a=`${e}/${i}`;(await this.fsp.stat(a)).isDirectory()?await this.rmdirRecursive(a):await this.fsp.unlink(a)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let a of i){let r=`${e}/${a}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var me=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),a=this.locks.get(e)||Promise.resolve();return this.locks.set(e,a.then(()=>i)),await a,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},he=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function X(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function ee(n,e,t,i,a){await i.init(),await I.init({fs:n,dir:e,defaultBranch:t}),await I.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await I.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await I.add({fs:n,dir:e,filepath:"."}),await I.commit({fs:n,dir:e,message:"chore: initial commit",author:a})}async function cn(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,a=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new Q(n),u=c.fs,l=n.startsWith("/")?n:`/${n}`,x=new me,S=new he(e.cacheTtl);async function v(f,d){let p=o;do{let w=s[o];try{return await f(w)}catch(D){if(console.warn(`Failed with proxy ${w}: ${D.message}`),o=(o+1)%s.length,o===p)throw new Error(`${d}: All CORS proxies failed`)}}while(!0)}async function m(f,d="."){return X(async()=>(await I.add({fs:u,dir:l,filepath:d}),(await I.statusMatrix({fs:u,dir:l})).some(([w,D,R])=>D!==R)?await I.commit({fs:u,dir:l,message:f,author:r}):null),"Failed to commit changes")}async function g(f,d,p){return X(async()=>{if(await C(f))throw new Error(`Tag ${f} already exists`);await I.annotatedTag({fs:u,dir:l,ref:f,message:d,tagger:r,object:p})},`Failed to create tag ${f}`)}async function C(f){try{return(await I.listTags({fs:u,dir:l})).includes(f)}catch{return!1}}async function $(f){return(await I.listTags({fs:u,dir:l})).filter(w=>w.startsWith(f))}async function h(f){return X(async()=>{let p=(await I.listTags({fs:u,dir:l})).filter(w=>w.startsWith(f));for(let w of p)await I.deleteTag({fs:u,dir:l,ref:w});return p},`Failed to delete tags with prefix ${f}`)}async function y(f){return X(async()=>{await I.checkout({fs:u,dir:l,ref:f})},`Failed to checkout ${f}`)}async function T(f,{delete:d=!1,force:p=!1}={}){i&&await v(async w=>{await I.push({fs:u,http:Z,dir:l,ref:f,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,delete:d,force:p})},`Failed to push ${f}`)}async function b(f,d=!0){i&&await v(async p=>{try{await I.pull({fs:u,http:Z,dir:l,ref:f,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:p,fastForwardOnly:!0})}catch(w){if(!d)console.warn(`Fast-forward pull failed for ${f}, attempting regular pull`),await I.pull({fs:u,http:Z,dir:l,ref:f,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:p,fastForwardOnly:!1});else throw w}},`Failed to pull ${f}`)}if(i&&!await c.fileExists(l)){let f=l.slice(1);if(await i.exists({name:f}).catch(()=>!1))await v(async p=>{await I.clone({fs:u,http:Z,dir:l,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:p})},"Failed to clone repository");else if(a)try{i=await i.create({name:f,private:!0}),await ee(u,l,t,c,r),await I.addRemote({fs:u,dir:l,remote:"origin",url:i.url()}),await T(t)}catch(p){console.error("Failed to create and push to remote repository:",p),await ee(u,l,t,c,r)}else await ee(u,l,t,c,r)}else await ee(u,l,t,c,r);return{async init(){return x.withLock("init",()=>c.init())},async create(f){let{name:d,version:p}=f.schema;return x.withLock(`schema:${d}`,async()=>{await y(t),await c.create(f);let w=await m(`feat: create schema ${d}`);w&&await g(`${d}-${p}`,`Version ${p}`,w),S.invalidate(d)})},async update(f){let{name:d,version:p}=f.schema;return x.withLock(`schema:${d}`,async()=>{await y(t),await c.update(f);let w=await m(`fix: update schema ${d}`);w&&await g(`${d}-${p}`,`Version ${p}`,w),S.invalidate(d)})},async delete(f){let{name:d}=f;return x.withLock(`schema:${d}`,async()=>{await y(t),await I.remove({fs:u,dir:l,filepath:d}),await c.delete(f);let p=await m(`chore: delete schema ${d}`),w=await $(`${d}-`);if(i&&p){await T(t);for(let D of w)await T(D,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${D}: ${R.message}`))}await h(`${d}-`),S.invalidate(d)})},async list(){return x.withLock("list",()=>c.list())},async schema(f){let{name:d,version:p}=f,w=`${d}-${p||"latest"}-${f.migrations||!1}`,D=S.get(w);return D||x.withLock(`schema:${d}`,async()=>{if(p){let O=`${d}-${p}`;if(await C(O))await y(O);else throw new Error(`Version ${p} of schema ${d} not found`)}else await y(t);let R=await c.schema(f);return S.set(w,R),R})},async stats(f){return x.withLock("stats",()=>c.stats(f))},async sync(){return x.withLock("sync",async()=>{if(await y(t),await c.sync(),await m("chore: sync local changes"),i){await b(t,!1),await T(t);let f=await I.listTags({fs:u,dir:l});for(let p of f)await T(p,{force:!0});let d=await I.listTags({fs:u,dir:l});for(let p of d)f.includes(p)||await T(p,{delete:!0})}S.invalidate()})},async migrations(f){let{name:d,version:p}=f,w=`migrations-${d}-${p||"latest"}`,D=S.get(w);return D||x.withLock(`migrations:${d}`,async()=>{if(p){let O=`${d}-${p}`;if(await C(O))await y(O);else throw new Error(`Version ${p} of schema ${d} not found`)}else await y(t);let R=await c.migrations(f);return S.set(w,R),R})},async history(f){let{name:d}=f,p=`history-${d}`,w=S.get(p);return w||x.withLock(`history:${d}`,async()=>{await y(t);let D=await c.history(f);return S.set(p,D),D})}}}function P(n){return"predicate"in n}function hn(n,e=!0,t=!0){let i="",a=t?"export ":"",r=new Map,s=new Map,o=(v,m=[])=>{if(!e||!v&&!m.length)return"";let g=v?[v]:[];return m.forEach(C=>g.push(C)),`/**
2
+ * ${g.join(`
3
3
  * `)}
4
4
  */
5
- `},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let D=g.constraints.find(f=>f.predicate==="enum"||f.predicate==="oneOf");if(D&&Array.isArray(D.parameters)){let f=`${m}${Ae(g.name)}`,p=D.parameters.map(v=>String(v));r.set(f,p)}}};c(n.fields,n.name);for(let[u,m]of Object.entries(n.nestedSchemas))c(m.fields,o(m.name));for(let[u,m]of r){i+=a(`Union type for ${u.toLowerCase()} field values`);let h=m.map(g=>`"${g}"`).join(" | ");i+=`${s}type ${u} = ${h};
5
+ `},c=v=>v.charAt(0).toUpperCase()+v.slice(1),u=(v,m)=>{for(let[g,C]of Object.entries(v))if(C.type==="enum"&&Array.isArray(C.values)){let $=`${m}${c(C.name)}`,h=C.values.map(y=>String(y));r.set($,h)}else if(C.type==="string"&&C.constraints){let $=C.constraints.find(h=>P(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if($&&P($)&&Array.isArray($.parameters)){let h=`${m}${c(C.name)}`,y=$.parameters.map(T=>String(T));r.set(h,y)}}else if(C.type==="record"){let $=`${m}${c(C.name)}`;s.set(C.name,$)}};u(n.fields,n.name);for(let[v,m]of Object.entries(n.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(g=>u(g.fields,c(m.name))):u(m.fields,c(m.name));for(let[v,m]of r){i+=o(`Union type for ${v.toLowerCase()} field values`);let g=m.map(C=>`"${C}"`).join(" | ");i+=`${a}type ${v} = ${g};
6
6
 
7
- `}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(D=>`@constraint ${D.name}: ${D.description||D.predicate}`)||[];i+=a(m.description,g),i+=`${s}type ${h} = {
8
- `;for(let[D,f]of Object.entries(m.fields)){let p=f.constraints?.map($=>`@constraint ${$.name}: ${$.description||$.predicate}`)||[];f.unique&&p.push("@unique Ensures unique values"),f.default!==void 0&&p.push(`@default ${JSON.stringify(f.default)}`),e&&f.description?i+=a(f.description,p):p.length&&(i+=a(void 0,p)),f.deprecated&&(i+=` /** @deprecated */
9
- `);let v=Re(f,n,h),C=f.required===!1?"?":"";i+=` ${f.name}${C}: ${v};
10
- `}if(m.metadata&&(i+=` metadata: Record<string, any>;
7
+ `}for(let[v,m]of Object.entries(n.nestedSchemas||{})){let g=c(m.name),C=m.constraints?.map($=>P($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];if(m.concrete&&C.push("@concrete Indicates a concrete schema"),i+=o(m.description,C),Array.isArray(m.fields)){let $=m.fields.filter(b=>!b.when),h=m.fields.filter(b=>b.when),y="";if($.length>0){y+=`{
8
+ `;for(let b of $)for(let[f,d]of Object.entries(b.fields)){let p=d.constraints?.map(R=>P(R)?`@constraint ${R.name}: ${R.description||R.predicate}`:`@constraint ${R.name}`)||[];d.unique&&p.push("@unique Ensures unique values"),d.default!==void 0&&p.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?y+=o(d.description,p):p.length&&(y+=o(void 0,p)),d.deprecated&&(y+=` /** @deprecated */
9
+ `);let w=te(d,n,g,s),D=d.required===!1?"?":"";y+=` ${d.name}${D}: ${w};
10
+ `}y+="}"}let T="";h.length>0&&(T=h.map(f=>{let d="";d+=`{
11
+ `;for(let[p,w]of Object.entries(f.fields)){let D=w.constraints?.map(_=>P(_)?`@constraint ${_.name}: ${_.description||_.predicate}`:`@constraint ${_.name}`)||[];w.unique&&D.push("@unique Ensures unique values"),w.default!==void 0&&D.push(`@default ${JSON.stringify(w.default)}`),e&&w.description?d+=o(w.description,D):D.length&&(d+=o(void 0,D)),w.deprecated&&(d+=` /** @deprecated */
12
+ `);let R=te(w,n,g,s),O=w.required===!1?"?":"";d+=` ${w.name}${O}: ${R};
13
+ `}if(f.when)for(let[p,w]of Object.entries(f.when))d+=` ${p}: "${w}";
14
+ `;return d+="}",d}).join(" | ")),y&&T?i+=`${a}type ${g} = ${y} & (${T});
15
+
16
+ `:y?i+=`${a}type ${g} = ${y};
17
+
18
+ `:T&&(i+=`${a}type ${g} = ${T};
19
+
20
+ `)}else{i+=`${a}type ${g} = {
21
+ `;for(let[$,h]of Object.entries(m.fields)){let y=h.constraints?.map(f=>P(f)?`@constraint ${f.name}: ${f.description||f.predicate}`:`@constraint ${f.name}`)||[];h.unique&&y.push("@unique Ensures unique values"),h.default!==void 0&&y.push(`@default ${JSON.stringify(h.default)}`),e&&h.description?i+=o(h.description,y):y.length&&(i+=o(void 0,y)),h.deprecated&&(i+=` /** @deprecated */
22
+ `);let T=te(h,n,g,s),b=h.required===!1?"?":"";i+=` ${h.name}${b}: ${T};
23
+ `}m.metadata&&(i+=` metadata: Record<string, any>;
11
24
  `),i+=`};
12
25
 
13
- `,m.indexes?.length){i+=a(`Available indexes for ${h}`),i+=`${s}enum ${h}IndexNames {
14
- `;for(let D of m.indexes)i+=` ${D.name} = "${D.name}",
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${g}`),i+=`${a}enum ${g}IndexNames {
27
+ `;for(let $ of m.indexes)i+=` ${$.name} = "${$.name}",
15
28
  `;i+=`}
16
29
 
17
- `}}let d=n.constraints?.map(u=>`@constraint ${u.name}: ${u.description||u.predicate}`)||[];i+=a(n.description,d),i+=`${s}type ${n.name} = {
18
- `;for(let[u,m]of Object.entries(n.fields)){let h=m.constraints?.map(f=>`@constraint ${f.name}: ${f.description||f.predicate}`)||[];m.unique&&h.push("@unique Ensures unique values"),m.default!==void 0&&h.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=a(m.description,h):h.length&&(i+=a(void 0,h)),m.deprecated&&(i+=` /** @deprecated */
19
- `);let g=Re(m,n,n.name),D=m.required===!1?"?":"";i+=` ${m.name}${D}: ${g};
30
+ `}}let l=n.constraints?.map(v=>P(v)?`@constraint ${v.name}: ${v.description||v.predicate}`:`@constraint ${v.name}`)||[];i+=o(n.description,l);let x=Array.from(s.entries()).map(([v,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),S=s.size>0?`<${x}>`:"";i+=`${a}type ${n.name}${S} = {
31
+ `;for(let[v,m]of Object.entries(n.fields)){let g=m.constraints?.map(h=>P(h)?`@constraint ${h.name}: ${h.description||h.predicate}`:`@constraint ${h.name}`)||[];m.unique&&g.push("@unique Ensures unique values"),m.default!==void 0&&g.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,g):g.length&&(i+=o(void 0,g)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let C=te(m,n,n.name,s),$=m.required===!1?"?":"";i+=` ${m.name}${$}: ${C};
20
33
  `}if(n.metadata&&(i+=` metadata: Record<string, any>;
21
34
  `),i+=`};
22
35
 
23
- `,n.indexes?.length){i+=a(`Available indexes for ${n.name}`),i+=`${s}enum ${n.name}IndexNames {
24
- `;for(let u of n.indexes)i+=` ${u.name} = "${u.name}",
36
+ `,n.indexes?.length){i+=o(`Available indexes for ${n.name}`),i+=`${a}enum ${n.name}IndexNames {
37
+ `;for(let v of n.indexes)i+=` ${v.name} = "${v.name}",
25
38
  `;i+=`}
26
- `}return i}function Re(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${Ae(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${fe(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${fe(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return fe(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function Ae(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function fe(n){return n.charAt(0).toUpperCase()+n.slice(1)}function mn(n,e=!0){let i=`${e?"export ":""}interface ${n.name}Validator {
39
+ `}return i.trim()}function te(n,e,t,i){switch(n.type){case"string":if(n.constraints){let a=n.constraints.find(r=>P(r)&&(r.predicate==="enum"||r.predicate==="oneOf"));if(a&&P(a)&&Array.isArray(a.parameters))return`${t}${V(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.schema&&!Array.isArray(n.schema)){let a=e.nestedSchemas[n.schema.id];return`${V(a.name)}[]`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.schema&&!Array.isArray(n.schema)){let a=e.nestedSchemas[n.schema.id];return`Set<${V(a.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"enum":return n.values?`${t}${V(n.name)}`:"string";case"object":if(n.schema&&!Array.isArray(n.schema)){let a=e.nestedSchemas[n.schema.id];return V(a.name)}if(n.nestedSchema){let a=e.nestedSchemas[n.nestedSchema.id];return V(a.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(n.name)||"Record<string, any>";case"union":return n.schema&&Array.isArray(n.schema)?n.schema.map(r=>{let s=e.nestedSchemas[r.id];return V(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function V(n){return n.charAt(0).toUpperCase()+n.slice(1)}function pn(n,e=!0){let i=`${e?"export ":""}interface ${n.name}Validator {
27
40
  `;return i+=` /**
28
41
  * Validates a ${n.name} object against all schema constraints
29
42
  * @param data The data to validate
@@ -38,30 +51,30 @@ import{createEventBus as qt}from"@asaidimu/events";import{createEventBus as Ct}f
38
51
  */
39
52
  `,i+=` isType(data: any): data is ${n.name};
40
53
  `,i+=`}
41
- `,i}function ln(n,e){let t=[],i=a=>a===void 0?"`None`":`\`${JSON.stringify(a,null,2)}\``,s=a=>{let o=`**${a.field}** ${a.operator}`;return a.value!==void 0&&(o+=` ${JSON.stringify(a.value)}`),a.conditions&&(o+=` [
42
- ${a.conditions.map(c=>` ${s(c)}`).join(`
54
+ `,i}function gn(n,e){let t=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,a=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
55
+ ${s.conditions.map(c=>` ${a(c)}`).join(`
43
56
  `)}
44
- ]`),o},r=(a,o=1)=>{let c="#".repeat(o+2);return Object.entries(a).map(([d,u])=>{let m=`${c} ${d} (${u.type})
57
+ ]`),o},r=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,l])=>{let x=`${c} ${u} (${l.type})
45
58
 
46
- `;return m+=`**Required:** ${u.required?"Yes":"No"}
59
+ `;return x+=`**Required:** ${l.required?"Yes":"No"}
47
60
 
48
- `,u.description&&(m+=`**Description:** ${u.description}
61
+ `,l.description&&(x+=`**Description:** ${l.description}
49
62
 
50
- `),u.itemsType&&(m+=`**Item Type:** ${u.itemsType}
63
+ `),l.itemsType&&(x+=`**Item Type:** ${l.itemsType}
51
64
 
52
- `),u.nestedSchema&&(m+=r(u.nestedSchema,o+1)),m}).join(`
65
+ `),l.nestedSchema&&(x+=r(l.nestedSchema,o+1)),x}).join(`
53
66
  `)};t.push(`# ${n.name} Schema (Version ${n.version})`),n.description&&t.push(`
54
67
  ${n.description}
55
68
  `),t.push("## Metadata"),t.push(`- **Dependencies:** ${n.dependencies?.join(", ")||"None"}`),t.push(`- **Created:** ${new Date().toISOString()}
56
69
  `),t.push(`## Fields
57
- `),t.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),t.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[a,o]of Object.entries(n.fields))t.push([a,o.type,o.required?"Yes":"No",i(o.default),o.description?.replace(/\n/g," ")||"",o.deprecated?"Yes":"No",o.unique?"Yes":"No",o.constraints?.length||0].join("|"));Object.entries(n.fields).forEach(([a,o])=>{o.nestedSchema&&(t.push(`
58
- ### Nested Schema: ${a}
70
+ `),t.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),t.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,o]of Object.entries(n.fields))t.push([s,o.type,o.required?"Yes":"No",i(o.default),o.description?.replace(/\n/g," ")||"",o.deprecated?"Yes":"No",o.unique?"Yes":"No",o.constraints?.length||0].join("|"));Object.entries(n.fields).forEach(([s,o])=>{o.nestedSchema&&(t.push(`
71
+ ### Nested Schema: ${s}
59
72
  `),t.push(r(o.nestedSchema)))}),t.push(`
60
73
  ## Indexes
61
- `),t.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),t.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let a of n.indexes||[])t.push([a.name,a.type,a.fields.join(", "),a.unique?"Yes":"No",a.order||"asc",a.partial?s(a.partial):"None",a.description||""].join("|"));t.push(`
74
+ `),t.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),t.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of n.indexes||[])t.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?a(s.partial):"None",s.description||""].join("|"));t.push(`
62
75
  ## Constraints
63
76
  `),n.constraints&&t.push("### Schema-level Constraints"),t.push(`
64
77
  ## Migrations
65
- `),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let a of n.migrations||[])t.push([a.id,a.description,a.status,a.changes.length].join("|"));if(n.mock&&e?.faker)try{let a=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(a,null,2)+"\n```")}catch{t.push(`
78
+ `),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let s of n.migrations||[])t.push([s.id,s.description,s.status,s.changes.length].join("|"));if(n.mock&&e?.faker)try{let s=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{t.push(`
66
79
  <!-- Error generating mock data -->`)}return t.join(`
67
- `)}function yn(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(s=>{t[s.name]={label:s.label,description:s.description}}),Me(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[s,r]of Object.entries(e)){let a=s!=="ungrouped"?t[s]:void 0;i.push({name:s!=="ungrouped"?s:"ungrouped",label:a?.label||"Ungrouped",description:a?.description,fields:r})}return i}function Me(n,e,t,i){for(let[s,r]of Object.entries(n)){let a=e?`${e}.${r.name}`:r.name,o={...r,name:a};if(!r.hint?.input?.ignore){if(r.type!=="object"){let c=r.hint?.input?.group||"ungrouped";i[c]||(i[c]=[]),i[c].push(o)}if(r.nestedSchema?.id&&t[r.nestedSchema.id]){let c=t[r.nestedSchema.id];Me(c.fields,a,t,i)}}}}export{P as JsonPatchError,ke as MigrationEngine,x as MigrationError,et as MigrationErrorCode,B as SchemaRegistry,X as applyPatch,De as calculateNextVersion,M as compareSemanticVersions,sn as createGitSchemaRegistry,at as createPatch,tt as createSchemaMigrationHelper,Ue as createStandardSchemaValidator,pe as deepMerge,ln as docgen,yn as extractInputFieldGroups,j as generateSHA256Hash,mn as generateValidationInterface,Oe as normalizePath,me as schemaChangeToPatch,fn as schemaToTypes,J as serializeParams,pt as sortSemanticVars,mt as validate,Ce as validateMigration,Te as validateSchemaChange,q as validateSchemaDefinition};
80
+ `)}function wn(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(a=>{t[a.name]={label:a.label,description:a.description}}),Me(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[a,r]of Object.entries(e)){let s=a!=="ungrouped"?t[a]:void 0;i.push({name:a!=="ungrouped"?a:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:r})}return i}function Me(n,e,t,i){for(let[a,r]of Object.entries(n)){let s=e?`${e}.${r.name}`:r.name,o={...r,name:s};if(!r.hint?.input?.ignore){if(r.type!=="object"){let c=r.hint?.input?.group||"ungrouped";i[c]||(i[c]=[]),i[c].push(o)}if(r.nestedSchema?.id&&t[r.nestedSchema.id]){let c=t[r.nestedSchema.id];Me(c.fields,s,t,i)}}}}export{A as JsonPatchError,Ae as MigrationEngine,k as MigrationError,nt as MigrationErrorCode,Q as SchemaRegistry,se as applyPatch,Re as calculateNextVersion,M as compareSemanticVersions,cn as createGitSchemaRegistry,rt as createPatch,it as createSchemaMigrationHelper,Ue as createStandardSchemaValidator,$e as deepMerge,gn as docgen,wn as extractInputFieldGroups,dt as formResolver,U as generateSHA256Hash,pn as generateValidationInterface,Oe as normalizePath,pe as schemaChangeToPatch,hn as schemaToTypes,W as serializeParams,$t as sortSemanticVars,pt as validate,De as validateMigration,Ie as validateSchemaChange,J as validateSchemaDefinition};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/anansi",
3
- "version": "1.5.3",
3
+ "version": "1.6.0",
4
4
  "description": "A toolkit for advanced data modelling",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -49,6 +49,7 @@
49
49
  "fake-indexeddb": "^6.0.0",
50
50
  "happy-dom": "^17.0.4",
51
51
  "playwright": "^1.50.1",
52
+ "react-hook-form": "^7.55.0",
52
53
  "tailwindcss": "^4.0.6",
53
54
  "tsup": "^8.3.6",
54
55
  "typescript": "^5.7.3",