@asaidimu/anansi 1.5.2 → 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.
Files changed (5) hide show
  1. package/index.cjs +52 -39
  2. package/index.d.cts +105 -35
  3. package/index.d.ts +105 -35
  4. package/index.js +40 -27
  5. package/package.json +2 -1
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)){if(r.hint?.input?.ignore)continue;let a=e?`${e}.${r.name}`:r.name,o={...r,name:a},c=r.hint?.input?.group||"ungrouped";if(i[c]||(i[c]=[]),i[c].push(o),r.nestedSchema?.id&&t[r.nestedSchema.id]){let d=t[r.nestedSchema.id];Me(d.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.2",
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",