@asaidimu/anansi 1.6.3 → 1.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1,35 +1,35 @@
1
- "use strict";var Qe=Object.create;var Z=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(t,e)=>{for(var n in e)Z(t,n,{get:e[n],enumerable:!0})},Ae=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xe(e))!tt.call(t,r)&&r!==n&&Z(t,r,{get:()=>e[r],enumerable:!(i=Ze(e,r))||i.enumerable});return t};var B=(t,e,n)=>(n=t!=null?Qe(et(t)):{},Ae(e||!t||!t.__esModule?Z(n,"default",{value:t,enumerable:!0}):n,t)),it=t=>Ae(Z({},"__esModule",{value:!0}),t);var Mt={};nt(Mt,{JsonPatchError:()=>F,MigrationEngine:()=>Ee,MigrationError:()=>k,MigrationErrorCode:()=>Ge,SchemaRegistry:()=>Y,applyPatch:()=>ie,calculateNextVersion:()=>ve,compareSemanticVersions:()=>M,createGitSchemaRegistry:()=>Pt,createPatch:()=>at,createSchemaMigrationHelper:()=>Je,createStandardSchemaValidator:()=>Fe,deepMerge:()=>pe,docgen:()=>Ot,extractInputFieldGroups:()=>At,formResolver:()=>ut,generateSHA256Hash:()=>U,normalizePath:()=>De,schemaChangeToPatch:()=>me,schemaDefaults:()=>Dt,schemaToTypes:()=>Ft,serializeParams:()=>K,sortSemanticVars:()=>Ct,validate:()=>yt,validateMigration:()=>Se,validateSchemaChange:()=>be,validateSchemaDefinition:()=>H});module.exports=it(Mt);var Rt=require("@asaidimu/events");var kt=require("@asaidimu/events"),re=require("@asaidimu/query");var F=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function te(t){let e=De(t);return e===""?[]:e.substring(1).split("/").map(st)}function De(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(ee).join("/"):"/"+t.split(".").map(ee).join("/")}function ee(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function st(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var j=new Map;function ne(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new F(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let r=i==="-"?n.length:parseInt(i);if(isNaN(r)||r<0||r>n.length)throw new F(`Invalid array index: ${i}`);n=n[r]}else{if(!n.hasOwnProperty(i))throw new F(`Property ${i} not found`);n=n[i]}}return n}function ue(t,e){let n=j.get(e)||te(e);if(j.set(e,n),n.length===0)return t;let i=ne(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);if(isNaN(a)||a<0||a>=i.length)throw new F(`Invalid array index: ${r}`);return i[a]}return i[r]}function rt(t,e,n){let i=j.get(e)||te(e);j.set(e,i);let r=ne(t,i.slice(0,-1)),a=i[i.length-1];return Array.isArray(r)?r.splice(0,r.length,...r.filter(s=>s!==n)):r[a]===n&&delete r[a],t}function X(t,e,n){let i=j.get(e)||te(e);if(j.set(e,i),i.length===0)return n;let r=i.slice(0,-1),a=i[i.length-1],s=ne(t,r);if(Array.isArray(s))if(a==="-")s.push(n);else{let o=parseInt(a);if(o<0||o>s.length)throw new F(`Invalid array index: ${a}`);s.splice(o,0,n)}else s[a]=n;return t}function fe(t,e){let n=j.get(e)||te(e);if(j.set(e,n),n.length===0)return;let i=ne(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);i.splice(a,1)}else delete i[r];return t}function ie(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=X(n,i.path,i.value);break;case"remove":n=fe(n,i.path);break;case"removeValue":n=rt(n,i.path,i.value);break;case"replace":n=X(fe(n,i.path),i.path,i.value);break;case"copy":{let r=ue(n,i.from);n=X(n,i.path,JSON.parse(JSON.stringify(r)));break}case"move":{let r=ue(n,i.from);n=X(n,i.path,r),n=fe(n,i.from);break}case"test":{let r=ue(n,i.path);if(JSON.stringify(r)!==JSON.stringify(i.value))throw new F("Test operation failed");break}default:throw new F(`Unsupported operation: ${i.op}`)}}catch(r){throw r instanceof F&&(r.operation=i),r}return n}function at(t,e){let n=[];return le(t,e,"",n),n}function le(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?ot(t,e,n,i):ct(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function ot(t,e,n,i){let r=Math.max(t.length,e.length);for(let a=0;a<r;a++){let s=`${n}/${a}`;a>=t.length?i.push({op:"add",path:`${n}/-`,value:e[a]}):a>=e.length?i.push({op:"remove",path:s}):le(t[a],e[a],s,i)}}function ct(t,e,n,i){let r=new Set,a=Object.keys(t),s=Object.keys(e);for(let o of a){let c=ee(o),d=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(le(t[o],e[o],d,i),r.add(o)):i.push({op:"remove",path:d})}for(let o of s)if(!r.has(o)){let c=ee(o),d=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function me(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([r,a])=>{typeof a=="object"&&a!==null&&!Array.isArray(a)?n.push({op:"replace",path:`${i}/${r}`,value:a}):n.push({op:"replace",path:`${i}/${r}`,value:a})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`/indexes/${i}/${r}`,value:a})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(r=>Array.isArray(r)?r.some(a=>a.name===t.name):r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=dt(e,t.name);i&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`${i}/${r}`,value:a})});break}}return n}function dt(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(Ie(i)){let r=Pe(i.rules,e);if(r)return`/constraints/${n}${r}`}}return null}function Ie(t){return t&&"operator"in t&&"rules"in t}function Pe(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(Ie(i)){let r=Pe(i.rules,e);if(r)return`/rules/${n}${r}`}}return null}function pe(t,e){let n={...t};return he(t)&&he(e)&&Object.keys(e).forEach(i=>{he(e[i])?i in t?n[i]=pe(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function he(t){return t&&typeof t=="object"&&!Array.isArray(t)}function K(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function Fe(t,e){let n=o=>({value:o}),i=o=>({issues:o}),r=(o,c,d,f)=>{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"enum":return f?.values?f.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(f.values)}, got ${o}`,path:d}]:[{message:"Enum type requires 'values' definition",path:d}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:d}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function a(o,c,d,f,b){let $=[],E=o.rules.map((m,p)=>{let S=[...f,`rules[${p}]`];if("rules"in m){if(b.has(m.name))return!0;b.add(m.name);let y=a(m,c,d,S,b);return $.push(...y),y.length===0}else{let y=d[m.predicate];if(!y)return $.push({message:`Predicate '${m.predicate}' not found`,path:S}),!1;let w=y({data:c,field:m.field,arguments:m.parameters});if(!w){let h=m.field?` for field '${m.field}'`:"";$.push({message:m.errorMessage||`Constraint '${m.name}' failed${h} with params ${K(m.parameters)}`,path:S})}return w}});return(()=>{switch(o.operator){case"and":return E.every(m=>m);case"or":return E.some(m=>m);case"not":return!E.every(m=>m);case"nor":return!E.some(m=>m);case"xor":return E.filter(m=>m).length===1}})()||$.push({message:`Constraint group '${o.name}' failed`,path:f}),$}function s(o,c,d,f,b,$=new Set){let E=[],T={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))T=c.fields;else{let p=c.fields,S=p.find(w=>!w.when);S&&Object.assign(T,S.fields);let y=p.find(w=>w.when&&o[w.when.field]!==void 0&&o[w.when.field]===w.when.value);if(y)Object.assign(T,y.fields);else if(!S)return E.push({message:"No matching field set found for discriminated schema",path:f}),E}else T=c.fields;let m=new Set(Object.values(T).map(p=>p.name));Object.entries(T).forEach(([p,S])=>{let y=[...f,S.name],w=Object.hasOwnProperty.call(o,S.name)?o[S.name]:void 0;if(S.required&&w==null){E.push({message:`Field '${S.name}' is required`,path:y});let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C&&E.push(...s({},C,d,y,b,$))}else S.type==="union"&&Array.isArray(S.schema)&&S.schema.forEach(C=>{let u=b[C.id];u&&E.push(...s({},u,d,y,b,$))});return}if(w!==void 0){if(E.push(...r(w,S.type,y,S)),S.type==="array"||S.type==="set"){S.itemsType&&Array.isArray(w)&&w.forEach((C,u)=>E.push(...r(C,S.itemsType,[...y,u.toString()])));let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?w.forEach((u,l)=>{typeof u=="object"&&u!==null&&($.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:[...y,l.toString()]}):($.add(h.id),E.push(...s(u,C,d,[...y,l.toString()],b,$)),$.delete(h.id)))}):E.push({message:`Nested schema '${h.id}' not found`,path:y})}}if(S.type==="object"){let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?typeof w=="object"&&w!==null&&($.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:y}):($.add(h.id),E.push(...s(w,C,d,y,b,$)),h.constraints?.forEach((u,l)=>{if("rules"in u)E.push(...a(u,w,d,[...y,`constraints[${l}]`],$));else{let g=d[u.predicate];g?g({data:w,field:void 0,arguments:u.parameters})||E.push({message:u.errorMessage||`Constraint '${u.name}' failed with params ${K(u.parameters)}`,path:[...y,`constraints[${l}]`]}):E.push({message:`Predicate '${u.predicate}' not found`,path:[...y,`constraints[${l}]`]})}}),$.delete(h.id))):E.push({message:`Nested schema '${h.id}' not found`,path:y})}}if(S.type==="union"){let h=S.schema;!h||!Array.isArray(h)?E.push({message:"Union type requires an array of schema references",path:y}):h.some(u=>{let l=b[u.id];return l?s(w,l,d,y,b,new Set($)).length===0:(E.push({message:`Nested schema '${u.id}' not found`,path:y}),!1)})||E.push({message:"Value does not match any union schema",path:y})}S.constraints?.forEach((h,C)=>{if("rules"in h)E.push(...a(h,o,d,[...y,`constraints[${C}]`],$));else{let u=d[h.predicate];u?u({data:o,field:S.name,arguments:h.parameters})||E.push({message:h.errorMessage||`Constraint '${h.name}' failed for field '${S.name}' with params ${K(h.parameters)}`,path:[...y,`constraints[${C}]`]}):E.push({message:`Predicate '${h.predicate}' not found`,path:[...y,`constraints[${C}]`]})}})}});for(let p in o)Object.hasOwnProperty.call(o,p)&&!m.has(p)&&E.push({message:`Unexpected field '${p}'`,path:[...f,p]});return c.constraints?.forEach((p,S)=>{if("rules"in p)E.push(...a(p,o,d,[...f,`constraints[${S}]`],$));else{let y=d[p.predicate];if(!y)E.push({message:`Predicate '${p.predicate}' not found`,path:[...f,`constraints[${S}]`]});else if(!y({data:o,field:p.field,arguments:p.parameters})){let h=p.field?` for field '${p.field}'`:"";E.push({message:p.errorMessage||`Constraint '${p.name}' failed${h} with params ${K(p.parameters)}`,path:[...f,`constraints[${S}]`]})}}}),E}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=s(c,t,e,[],t.nestedSchemas||{});return d.length>0?i(d):n(c)},types:{input:{},output:{}}}}}function ut(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(r=>{if(!r.path)return;let a=r.path,s=i;for(let o=0;o<a.length;o++){let c=a[o];o===a.length-1?s[c]={type:"validation",message:r.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var _=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var ge=t=>({value:t}),G=t=>({issues:t}),x=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Oe=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},ft=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Me=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},W=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],lt=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string")||t instanceof RegExp||typeof t=="object"&&t!==null&&"field"in t&&typeof t.field=="string")return[];break;case"number":if(typeof t=="number"||Array.isArray(t)&&t.every(i=>typeof i=="number")||typeof t=="object"&&t!==null&&"precision"in t&&typeof t.precision=="number")return[];break;case"boolean":if(typeof t=="boolean")return[];break;case"array":case"set":if(typeof t=="number"||typeof t=="object"&&t!==null&&"minItems"in t&&typeof t.minItems=="number")return[];break;case"enum":if(Array.isArray(t)&&t.length>0&&t.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"union":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[n]}]},we=(t,e)=>{let n=[],i=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...x(t.predicate,`${e}.predicate`)),t.type!==void 0&&t.type!=="schema"&&n.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),t.field!==void 0&&typeof t.field!="string"&&n.push({message:"Field must be a string",path:[`${e}.field`]}),t.parameters!==void 0&&(!t.type||t.type!=="schema")&&n.push(...lt(t.parameters,"dynamic",`${e}.parameters`)),n.push(...x(t.description,`${e}.description`,!1)),n.push(...x(t.errorMessage,`${e}.errorMessage`,!1)),n},$e=(t,e)=>{let n=[],i=["name","operator","rules"],r=["name","operator","rules"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...Me(t.operator,`${e}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?n.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):t.rules.forEach((s,o)=>{"rules"in s?n.push(...$e(s,`${e}.rules[${o}]`)):n.push(...we(s,`${e}.rules[${o}]`))}),n},q=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>{"rules"in i?n.push(...$e(i,`${e}[${r}]`)):n.push(...we(i,`${e}[${r}]`))}),n},je=(t,e)=>{let n=[],i=["operator","field"],r=["operator","field","value","conditions"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Me(t.operator,`${e}.operator`)),n.push(...x(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...je(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},Ne=(t,e)=>{let n=[],i=["fields","type","name"],r=["fields","type","unique","partial","description","order","name"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...ft(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...W(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...je(t.partial,`${e}.partial`)),n.push(...x(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},J=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>n.push(...Ne(i,`${e}[${r}]`))),n},mt=(t,e,n,i,r)=>{let a=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&a.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;a.push(...x(s.id,`${c}.id`)),i.includes(s.id)||a.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&a.push(...q(s.constraints,`${c}.constraints`)),s.indexes&&a.push(...J(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&r==="object")&&!Array.isArray(t)?(a.push(...x(t.id,`${e}.id`)),i.includes(t.id)||a.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&a.push(...q(t.constraints,`${e}.constraints`)),t.indexes&&a.push(...J(t.indexes,`${e}.indexes`))):a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),a)},se=(t,e,n)=>{let i=[],r=["name","type"],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=t;if(r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...Oe(t.type,`${e}.type`)),i.push(...W(t.required,`${e}.required`,!1)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...mt(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...Oe(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],d=t.nestedSchema;o.forEach(f=>{d[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.nestedSchema.${f}`]})}),Object.keys(d).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${f}`]})}),i.push(...x(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...q(t.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...J(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...W(t.deprecated,`${e}.deprecated`,!1)),t.reference){let o=["schema","field"],c=["schema","field"],d=t.reference;o.forEach(f=>{d[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.reference.${f}`]})}),Object.keys(d).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.reference.${f}`]})}),i.push(...x(t.reference.schema,`${e}.reference.schema`)),i.push(...x(t.reference.field,`${e}.reference.field`))}return i.push(...x(t.description,`${e}.description`,!1)),i.push(...W(t.unique,`${e}.unique`,!1)),i},Ve=(t,e,n)=>{let i=[],r=["name","fields"],a=["name","description","concrete","fields","indexes","constraints","metadata"],s=t;return r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...W(t.concrete,`${e}.concrete`,!1)),Array.isArray(t.fields)?(t.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),t.fields.forEach((o,c)=>{let d=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[d]});else{let f=o.fields;typeof f!="object"||f===null?i.push({message:"Fields must be a non-empty object",path:[`${d}.fields`]}):Object.entries(f).forEach(([b,$])=>{i.push(...se($,`${d}.fields.${b}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${d}.when`]})}})):typeof t.fields=="object"&&t.fields!==null?Object.entries(t.fields).forEach(([o,c])=>{i.push(...se(c,`${e}.fields.${o}`,n))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...x(t.description,`${e}.description`,!1)),t.indexes&&i.push(...J(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},ht=t=>{if(typeof t!="object"||t===null)return G([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields","nestedSchemas"],r=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],a=e;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[s]})}),n.push(...x(e.name,"name")),n.push(...x(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...se(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(...Ve(c,`nestedSchemas.${o}`,s)))}return n.push(...x(e.description,"description",!1)),e.indexes&&n.push(...J(e.indexes,"indexes")),e.constraints&&n.push(...q(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...qe(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),n.length>0?G(n):ge(e)},ye=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...se(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],r=["type","id","changes","nestedSchemaChanges"],a=t;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...x(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...q(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...J(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Ne(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...$e(t.constraint,`${e}.constraint`)):n.push(...we(t.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...Ve(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},pt=(t,e)=>{let n=[],i=["forward","backward"],r=i,a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},qe=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],r=[...i,"rollback","dependencies"],a=t;i.forEach(o=>{a[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(a).forEach(o=>{r.includes(o)||n.push({message:"Unknown property",path:[`${e}.${o}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...x(t.schemaVersion,`${e}.schemaVersion`)),n.push(...x(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>n.push(...ye(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...ye(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...x(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...pt(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...x(t.createdAt,`${e}.createdAt`)),t.dependencies!==void 0&&(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),n.push(...x(t.checksum,`${e}.checksum`)),n},Ue={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:ht,types:{input:{},output:{}}}};var Le={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return G([{message:"Migration must be an object",path:[]}]);let e=t,n=qe(e,"");return n.length>0?G(n):ge(e)},types:{input:{},output:{}}}},_e={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return G([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,r)=>n.push(...ye(i,`[${r}]`))),n.length>0?G(n):ge(e)},types:{input:[],output:[]}}};function Se(t){try{return!Le["~standard"].validate(t).issues}catch(e){throw new _("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function be(t){try{return!_e["~standard"].validate(t).issues}catch(e){throw new _("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function H(t){try{return!Ue["~standard"].validate(t).issues}catch(e){throw new _("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var yt=H;var U=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function gt(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function wt(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function $t(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function St(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function bt(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function vt(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return bt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=wt(e,n);return i?St(e.parameters,t.parameters,i):!0}return!1}function Et(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return $t(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return vt(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function xt(t){let e=new Set,n=new Set,i=new Set,r=new Set;for(let a of t)switch(a.type){case"addField":if(n.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);i.add(a.id);break;case"removeField":if(i.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case"modifyField":if(n.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);e.add(a.id);break;case"deprecateField":if(n.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);r.add(a.id);break}}function Tt(t){let e=new Set,n=new Set,i=new Set;for(let r of t)switch(r.type){case"addConstraint":let a=r.constraint,s=("name"in a,a.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(r.name))throw new Error(`Cannot remove newly added constraint: ${r.name}`);if(e.has(r.name))throw new Error(`Cannot remove modified constraint: ${r.name}`);n.add(r.name);break;case"modifyConstraint":if(n.has(r.name))throw new Error(`Cannot modify removed constraint: ${r.name}`);if(i.has(r.name))throw new Error(`Cannot modify newly added constraint: ${r.name}`);e.add(r.name);break}}function ve(t,e,n){if(e.length===0)throw new Error("No changes provided");xt(e),Tt(e);let i=gt(t),r="patch";for(let a of e){let s=Et(a,n);if(s==="major"){r="major";break}else s==="minor"&&r==="patch"&&(r="minor")}switch(r){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(t,e){let n=d=>d.split(".").map(f=>parseInt(f,10)||0),[i,r,a]=n(t),[s,o,c]=n(e);return i-s||r-o||a-c}function Ct(t){return t.sort(M)}var k=class extends Error{constructor(n,i,r,a){super(n);this.code=i;this.migrationId=r;this.cause=a;this.name="MigrationError"}},Ge=($=>($.INVALID_SCHEMA="INVALID_SCHEMA",$.INVALID_MIGRATION="INVALID_MIGRATION",$.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",$.TIMEOUT="TIMEOUT",$.MEMORY_LIMIT="MEMORY_LIMIT",$.CONCURRENT_OPERATION="CONCURRENT_OPERATION",$.TRANSFORM_ERROR="TRANSFORM_ERROR",$.VERSION_NOT_FOUND="VERSION_NOT_FOUND",$.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",$.STREAM_ERROR="STREAM_ERROR",$.ROLLBACK_ERROR="ROLLBACK_ERROR",$.MISSING_TRANSFORM="MISSING_TRANSFORM",$))(Ge||{}),Ee=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!H(e))throw new k("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(r=>Se(r)))throw new k("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((r,a)=>M(r.schemaVersion,a.schemaVersion))}i&&(this.history=i.sort((r,a)=>M(r.version,a.version)))}catch(r){throw r instanceof k?r:new k("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,r)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await U(n)}catch(n){throw new k("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}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=>be(i))}catch(i){throw new k("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(n,i),s=a.reduce((c,d)=>{let f=n==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,f,d.id)},r),o=await t.processMigrationList(e,n,a);return{newSchema:s,dataPreview:o}}catch(r){throw r instanceof k?r:new k("Dry run failed","INVALID_SCHEMA",void 0,r)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let r=e==="forward"?"pending":"applied",a=n?M(i.schemaVersion,n)>=0:!0;return i.status===r&&a}).sort((i,r)=>e==="forward"?i.id.localeCompare(r.id):r.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let r=ve(e.version,n);return n.map(s=>{try{return me(s,e)}catch(o){throw new k("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ie(s,o)}catch(c){throw new k("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:r})}catch(r){throw r instanceof k?r:new k("Schema update failed","INVALID_SCHEMA",i,r)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new k("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new 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,n){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 r=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),a=this.history.length-i;if(a<0)return n;for(let o=0;o<a;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",r);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new 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(d,f){try{let b=await c(d);f.enqueue(b)}catch(b){f.error(new k(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,b))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new k(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let r=await i.text();if(typeof window<"u"){let a=new Blob([r],{type:"application/javascript"});return(await import(URL.createObjectURL(a))).default[n]}else{let{runInNewContext:a}=await import("vm"),s={module:{exports:{}},console};return a(r,s,e),s.module.exports[n]}}catch(i){throw new k(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new 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 n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,r)=>this.applySchemaChanges(i,[r]),this.currentSchema)}catch(n){throw n instanceof k?n:new k("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var Je=t=>{let e=[],n=[];return{addField:(i,r)=>{e.push({type:"addField",id:i,definition:r}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let r=t.fields[i];r&&n.push({type:"addField",id:i,definition:r})},modifyField:(i,r)=>{e.push({type:"modifyField",id:i,changes:r});let a=t.fields[i];a&&n.push({type:"modifyField",id:i,changes:a})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let r=t.indexes?.find(a=>a.name===i);r&&n.push({type:"addIndex",definition:r})},modifyIndex:(i,r)=>{e.push({type:"modifyIndex",name:i,changes:r});let a=t.indexes?.find(s=>s.name===i);a&&n.push({type:"modifyIndex",name:i,changes:a})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let r=t.constraints?.find(a=>"name"in a&&a.name===i);r&&n.push({type:"addConstraint",constraint:r})},modifyConstraint:(i,r)=>{e.push({type:"modifyConstraint",name:i,changes:r});let a=t.constraints?.find(s=>"name"in s&&s.name===i);a&&n.push({type:"modifyConstraint",name:i,changes:a})},addNestedSchema:(i,r)=>{e.push({type:"addNestedSchema",id:i,definition:r}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let r=t.nestedSchemas[i];r&&n.push({type:"addNestedSchema",id:i,definition:r})},modifyNestedSchema:(i,r)=>{e.push({type:"modifyNestedSchema",id:i,changes:r});let a=t.nestedSchemas[i];a&&n.push({type:"modifyNestedSchema",id:i,changes:a})},changes:()=>({migrate:e,rollback:n})}};var bn=require("@isomorphic-git/lightning-fs"),D=B(require("isomorphic-git"),1),Q=B(require("isomorphic-git/http/web"),1);var Ke=B(require("@isomorphic-git/lightning-fs"),1);function He(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function ze(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function xe(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),r=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),a,s;return n?(a=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(a=i[1],s=i[2].trim()):r?(a=r[2],s=r[3].trim()):(a=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:a,body:s,type:n?"arrow":i?"function":r?"method":"unknown"})}function Te(t){let{params:e,body:n,type:i}=JSON.parse(t),r=new Function(e,n);return i==="arrow"&&Object.defineProperty(r,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),r}function At(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(r=>{n[r.name]={label:r.label,description:r.description}}),Ce(t.fields,"",t.nestedSchemas||{},e);let i=[];for(let[r,a]of Object.entries(e)){let s=r!=="ungrouped"?n[r]:void 0;i.push({name:r!=="ungrouped"?r:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:a})}return i}function Ce(t,e,n,i,r){if(Array.isArray(t))t.forEach(a=>{let s=a.when?e?`${e}.${a.when?.field}`:a.when?.field:void 0;Ce(a.fields,e,n,i,s?{[s]:a.when?.value}:void 0)});else for(let[a,s]of Object.entries(t)){if(s.hint?.input.ignore)continue;let o=e?`${e}.${s.name}`:s.name,c={...s,name:o};if(s.type!=="object"){let d=s.hint?.input?.group||"ungrouped";i[d]||(i[d]=[]),i[d].push(c)}if(r&&(c.when=r),s.schema&&"id"in s.schema&&n[s.schema.id]){let d=n[s.schema.id];Ce(d.fields,o,n,i,r)}}}function Dt(t,e){let n={},i=t.nestedSchemas||{};for(let[r,a]of Object.entries(t.fields))n[r]=ae(a,i,e);return n}function ae(t,e,n){if("default"in t&&t.default!==void 0)return t.default;if(n?.resolver){let i=n.resolver(t);if(i!==void 0)return i}switch(t.type){case"string":return"";case"number":return 0;case"boolean":return!1;case"array":return[];case"set":return[];case"enum":if(!t.values||t.values.length===0)throw new Error(`Enum field "${t.name}" requires non-empty values array`);return t.values[0];case"object":if(!t.schema||!("id"in t.schema)||!e[t.schema.id])throw new Error(`Object field "${t.name}" references invalid nested schema`);return Be(e[t.schema.id],e,n);case"record":return{};case"union":if(!t.schema||!Array.isArray(t.schema)||t.schema.length===0)throw new Error(`Union field "${t.name}" requires non-empty schema array`);let i=n?.discriminator?.[t.name],r=t.schema[0];if(i!==void 0)for(let a of t.schema){let o=e[a.id].fields;if(It(o,i)){r=a;break}}return Be(e[r.id],e,n);case"dynamic":return{};default:throw new Error(`Unsupported field type "${t.type}" for field "${t.name}"`)}}function It(t,e){if(Array.isArray(t)){for(let n of t)for(let i of Object.values(n.fields))if(i.type==="enum"&&i.values?.includes(e)||i.default===e)return i}else for(let n of Object.values(t))if(n.type==="enum"&&n.values?.includes(e)||n.default===e)return n}function Be(t,e,n){let i={},r=n?.discriminator||{};if(Array.isArray(t.fields)){let a=t.fields.filter(o=>!o.when);for(let o of a)for(let[c,d]of Object.entries(o.fields))i[c]=ae(d,e,n);let s=t.fields.filter(o=>o.when);for(let o of s){let c=o.when.field,d=o.when.value;if(r[c]===d)for(let[b,$]of Object.entries(o.fields))i[b]=ae($,e,n)}}else for(let[a,s]of Object.entries(t.fields))i[a]=ae(s,e,n);return i}var We=require("buffer");window.Buffer=We.Buffer;var Y=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new Ke.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!H(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,r=await this.processAndStoreMigrations(i,e),a=this.serializeSchema(e);await this.writeSchemaFile(i,a);let s=await U(a);await this.updateIndex(i,e,s,r,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let r=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(r))return null;let a=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(r,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(a.migrations=await this.migrations({name:e,version:n})),a)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let r=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await U(r)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),r=n||i.version,a=[];for(let[s,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,r)<=0&&a.push(this.deserializeMigration(d))}}return a.sort((s,o)=>M(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async r=>({...i,version:r.version,description:r.description,migrations:await this.migrations({name:e,version:r.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let r={...i};if(i.transform?.forward){let o=i.transform;r.transform={forward:xe(o.forward),backward:xe(o.backward||(c=>c))}}let a=JSON.stringify(r),s=await U(a);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,a,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?He(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=ze(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:Te(e.transform.forward),backward:Te(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,r,a){let s=`${e}/index.json`,o=a==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(a==="create"?"Initial version":"Updated version"),migrations:r.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,r.forEach(({id:c,hash:d,checksum:f})=>{o.migrations[c]={hash:d,checksum:f}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let r=`${e}/${i}`;(await this.fsp.stat(r)).isDirectory()?await this.rmdirRecursive(r):await this.fsp.unlink(r)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let r of i){let a=`${e}/${r}`;(await this.fsp.stat(a)).isDirectory()?n.push(...await this.listFilesRecursive(a)):n.push(a)}return n}};var ke=class{locks=new Map;async acquire(e){let n,i=new Promise(a=>{n=a}),r=this.locks.get(e)||Promise.resolve();return this.locks.set(e,r.then(()=>i)),await r,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},Re=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function oe(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function ce(t,e,n,i,r){await i.init(),await D.default.init({fs:t,dir:e,defaultBranch:n}),await D.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await D.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await D.default.add({fs:t,dir:e,filepath:"."}),await D.default.commit({fs:t,dir:e,message:"chore: initial commit",author:r})}async function Pt(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,r=e.createRemote??!1,a=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new Y(t),d=c.fs,f=t.startsWith("/")?t:`/${t}`,b=new ke,$=new Re(e.cacheTtl);async function E(u,l){let g=o;do{let v=s[o];try{return await u(v)}catch(A){if(console.warn(`Failed with proxy ${v}: ${A.message}`),o=(o+1)%s.length,o===g)throw new Error(`${l}: All CORS proxies failed`)}}while(!0)}async function T(u,l="."){return oe(async()=>(await D.default.add({fs:d,dir:f,filepath:l}),(await D.default.statusMatrix({fs:d,dir:f})).some(([v,A,R])=>A!==R)?await D.default.commit({fs:d,dir:f,message:u,author:a}):null),"Failed to commit changes")}async function m(u,l,g){return oe(async()=>{if(await p(u))throw new Error(`Tag ${u} already exists`);await D.default.annotatedTag({fs:d,dir:f,ref:u,message:l,tagger:a,object:g})},`Failed to create tag ${u}`)}async function p(u){try{return(await D.default.listTags({fs:d,dir:f})).includes(u)}catch{return!1}}async function S(u){return(await D.default.listTags({fs:d,dir:f})).filter(v=>v.startsWith(u))}async function y(u){return oe(async()=>{let g=(await D.default.listTags({fs:d,dir:f})).filter(v=>v.startsWith(u));for(let v of g)await D.default.deleteTag({fs:d,dir:f,ref:v});return g},`Failed to delete tags with prefix ${u}`)}async function w(u){return oe(async()=>{await D.default.checkout({fs:d,dir:f,ref:u})},`Failed to checkout ${u}`)}async function h(u,{delete:l=!1,force:g=!1}={}){i&&await E(async v=>{await D.default.push({fs:d,http:Q.default,dir:f,ref:u,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:v,delete:l,force:g})},`Failed to push ${u}`)}async function C(u,l=!0){i&&await E(async g=>{try{await D.default.pull({fs:d,http:Q.default,dir:f,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:g,fastForwardOnly:!0})}catch(v){if(!l)console.warn(`Fast-forward pull failed for ${u}, attempting regular pull`),await D.default.pull({fs:d,http:Q.default,dir:f,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:g,fastForwardOnly:!1});else throw v}},`Failed to pull ${u}`)}if(i&&!await c.fileExists(f)){let u=f.slice(1);if(await i.exists({name:u}).catch(()=>!1))await E(async g=>{await D.default.clone({fs:d,http:Q.default,dir:f,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:g})},"Failed to clone repository");else if(r)try{i=await i.create({name:u,private:!0}),await ce(d,f,n,c,a),await D.default.addRemote({fs:d,dir:f,remote:"origin",url:i.url()}),await h(n)}catch(g){console.error("Failed to create and push to remote repository:",g),await ce(d,f,n,c,a)}else await ce(d,f,n,c,a)}else await ce(d,f,n,c,a);return{async init(){return b.withLock("init",()=>c.init())},async create(u){let{name:l,version:g}=u.schema;return b.withLock(`schema:${l}`,async()=>{await w(n),await c.create(u);let v=await T(`feat: create schema ${l}`);v&&await m(`${l}-${g}`,`Version ${g}`,v),$.invalidate(l)})},async update(u){let{name:l,version:g}=u.schema;return b.withLock(`schema:${l}`,async()=>{await w(n),await c.update(u);let v=await T(`fix: update schema ${l}`);v&&await m(`${l}-${g}`,`Version ${g}`,v),$.invalidate(l)})},async delete(u){let{name:l}=u;return b.withLock(`schema:${l}`,async()=>{await w(n),await D.default.remove({fs:d,dir:f,filepath:l}),await c.delete(u);let g=await T(`chore: delete schema ${l}`),v=await S(`${l}-`);if(i&&g){await h(n);for(let A of v)await h(A,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${A}: ${R.message}`))}await y(`${l}-`),$.invalidate(l)})},async list(){return b.withLock("list",()=>c.list())},async schema(u){let{name:l,version:g}=u,v=`${l}-${g||"latest"}-${u.migrations||!1}`,A=$.get(v);return A||b.withLock(`schema:${l}`,async()=>{if(g){let I=`${l}-${g}`;if(await p(I))await w(I);else throw new Error(`Version ${g} of schema ${l} not found`)}else await w(n);let R=await c.schema(u);return $.set(v,R),R})},async stats(u){return b.withLock("stats",()=>c.stats(u))},async sync(){return b.withLock("sync",async()=>{if(await w(n),await c.sync(),await T("chore: sync local changes"),i){await C(n,!1),await h(n);let u=await D.default.listTags({fs:d,dir:f});for(let g of u)await h(g,{force:!0});let l=await D.default.listTags({fs:d,dir:f});for(let g of l)u.includes(g)||await h(g,{delete:!0})}$.invalidate()})},async migrations(u){let{name:l,version:g}=u,v=`migrations-${l}-${g||"latest"}`,A=$.get(v);return A||b.withLock(`migrations:${l}`,async()=>{if(g){let I=`${l}-${g}`;if(await p(I))await w(I);else throw new Error(`Version ${g} of schema ${l} not found`)}else await w(n);let R=await c.migrations(u);return $.set(v,R),R})},async history(u){let{name:l}=u,g=`history-${l}`,v=$.get(g);return v||b.withLock(`history:${l}`,async()=>{await w(n);let A=await c.history(u);return $.set(g,A),A})}}}function O(t){return"predicate"in t}function Ft(t,e=!0,n=!0){let i="",r=n?"export ":"",a=new Map,s=new Map,o=(T,m=[])=>{if(!e||!T&&!m.length)return"";let p=T?[T]:[];return m.forEach(S=>p.push(S)),`/**
2
- * ${p.join(`
1
+ "use strict";var Qe=Object.create;var Z=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(t,e)=>{for(var n in e)Z(t,n,{get:e[n],enumerable:!0})},Ae=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xe(e))!tt.call(t,r)&&r!==n&&Z(t,r,{get:()=>e[r],enumerable:!(i=Ze(e,r))||i.enumerable});return t};var B=(t,e,n)=>(n=t!=null?Qe(et(t)):{},Ae(e||!t||!t.__esModule?Z(n,"default",{value:t,enumerable:!0}):n,t)),it=t=>Ae(Z({},"__esModule",{value:!0}),t);var Mt={};nt(Mt,{JsonPatchError:()=>F,MigrationEngine:()=>Ee,MigrationError:()=>k,MigrationErrorCode:()=>Ge,SchemaRegistry:()=>Y,applyPatch:()=>ie,calculateNextVersion:()=>ve,compareSemanticVersions:()=>M,createGitSchemaRegistry:()=>Pt,createPatch:()=>at,createSchemaMigrationHelper:()=>Je,createStandardSchemaValidator:()=>Fe,deepMerge:()=>pe,docgen:()=>Ot,extractInputFieldGroups:()=>At,formResolver:()=>ut,generateSHA256Hash:()=>U,normalizePath:()=>De,schemaChangeToPatch:()=>me,schemaDefaults:()=>Dt,schemaToTypes:()=>Ft,serializeParams:()=>K,sortSemanticVars:()=>Ct,validate:()=>yt,validateMigration:()=>Se,validateSchemaChange:()=>be,validateSchemaDefinition:()=>H});module.exports=it(Mt);var Rt=require("@asaidimu/events");var kt=require("@asaidimu/events"),re=require("@asaidimu/query");var F=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function te(t){let e=De(t);return e===""?[]:e.substring(1).split("/").map(st)}function De(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(ee).join("/"):"/"+t.split(".").map(ee).join("/")}function ee(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function st(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var j=new Map;function ne(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new F(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let r=i==="-"?n.length:parseInt(i);if(isNaN(r)||r<0||r>n.length)throw new F(`Invalid array index: ${i}`);n=n[r]}else{if(!n.hasOwnProperty(i))throw new F(`Property ${i} not found`);n=n[i]}}return n}function ue(t,e){let n=j.get(e)||te(e);if(j.set(e,n),n.length===0)return t;let i=ne(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);if(isNaN(a)||a<0||a>=i.length)throw new F(`Invalid array index: ${r}`);return i[a]}return i[r]}function rt(t,e,n){let i=j.get(e)||te(e);j.set(e,i);let r=ne(t,i.slice(0,-1)),a=i[i.length-1];return Array.isArray(r)?r.splice(0,r.length,...r.filter(s=>s!==n)):r[a]===n&&delete r[a],t}function X(t,e,n){let i=j.get(e)||te(e);if(j.set(e,i),i.length===0)return n;let r=i.slice(0,-1),a=i[i.length-1],s=ne(t,r);if(Array.isArray(s))if(a==="-")s.push(n);else{let o=parseInt(a);if(o<0||o>s.length)throw new F(`Invalid array index: ${a}`);s.splice(o,0,n)}else s[a]=n;return t}function fe(t,e){let n=j.get(e)||te(e);if(j.set(e,n),n.length===0)return;let i=ne(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);i.splice(a,1)}else delete i[r];return t}function ie(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=X(n,i.path,i.value);break;case"remove":n=fe(n,i.path);break;case"removeValue":n=rt(n,i.path,i.value);break;case"replace":n=X(fe(n,i.path),i.path,i.value);break;case"copy":{let r=ue(n,i.from);n=X(n,i.path,JSON.parse(JSON.stringify(r)));break}case"move":{let r=ue(n,i.from);n=X(n,i.path,r),n=fe(n,i.from);break}case"test":{let r=ue(n,i.path);if(JSON.stringify(r)!==JSON.stringify(i.value))throw new F("Test operation failed");break}default:throw new F(`Unsupported operation: ${i.op}`)}}catch(r){throw r instanceof F&&(r.operation=i),r}return n}function at(t,e){let n=[];return le(t,e,"",n),n}function le(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?ot(t,e,n,i):ct(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function ot(t,e,n,i){let r=Math.max(t.length,e.length);for(let a=0;a<r;a++){let s=`${n}/${a}`;a>=t.length?i.push({op:"add",path:`${n}/-`,value:e[a]}):a>=e.length?i.push({op:"remove",path:s}):le(t[a],e[a],s,i)}}function ct(t,e,n,i){let r=new Set,a=Object.keys(t),s=Object.keys(e);for(let o of a){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(le(t[o],e[o],u,i),r.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!r.has(o)){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function me(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([r,a])=>{typeof a=="object"&&a!==null&&!Array.isArray(a)?n.push({op:"replace",path:`${i}/${r}`,value:a}):n.push({op:"replace",path:`${i}/${r}`,value:a})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`/indexes/${i}/${r}`,value:a})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(r=>Array.isArray(r)?r.some(a=>a.name===t.name):r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=dt(e,t.name);i&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`${i}/${r}`,value:a})});break}}return n}function dt(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(Ie(i)){let r=Pe(i.rules,e);if(r)return`/constraints/${n}${r}`}}return null}function Ie(t){return t&&"operator"in t&&"rules"in t}function Pe(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(Ie(i)){let r=Pe(i.rules,e);if(r)return`/rules/${n}${r}`}}return null}function pe(t,e){let n={...t};return he(t)&&he(e)&&Object.keys(e).forEach(i=>{he(e[i])?i in t?n[i]=pe(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function he(t){return t&&typeof t=="object"&&!Array.isArray(t)}function K(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function Fe(t,e){let n=o=>({value:o}),i=o=>({issues:o}),r=(o,c,u,f)=>{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 f?.values?f.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(f.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 a(o,c,u,f,b){let p=[],E=o.rules.map((m,y)=>{let S=[...f,`rules[${y}]`];if("rules"in m){if(b.has(m.name))return!0;b.add(m.name);let g=a(m,c,u,S,b);return p.push(...g),g.length===0}else{let g=u[m.predicate];if(!g)return p.push({message:`Predicate '${m.predicate}' not found`,path:S}),!1;let $=g({data:c,field:m.field,arguments:m.parameters});if(!$){let h=m.field?` for field '${m.field}'`:"";p.push({message:m.errorMessage||`Constraint '${m.name}' failed${h} with params ${K(m.parameters)}`,path:S})}return $}});return(()=>{switch(o.operator){case"and":return E.every(m=>m);case"or":return E.some(m=>m);case"not":return!E.every(m=>m);case"nor":return!E.some(m=>m);case"xor":return E.filter(m=>m).length===1}})()||p.push({message:`Constraint group '${o.name}' failed`,path:f}),p}function s(o,c,u,f,b,p=new Set){let E=[],T={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))T=c.fields;else{let y=c.fields,S=y.find($=>!$.when);S&&Object.assign(T,S.fields);let g=y.find($=>$.when&&o[$.when.field]!==void 0&&o[$.when.field]===$.when.value);if(g)Object.assign(T,g.fields);else if(!S)return E.push({message:"No matching field set found for discriminated schema",path:f}),E}else T=c.fields;let m=new Set(Object.values(T).map(y=>y.name));Object.entries(T).forEach(([y,S])=>{let g=[...f,S.name],$=Object.hasOwnProperty.call(o,S.name)?o[S.name]:void 0;if(S.required&&$==null){E.push({message:`Field '${S.name}' is required`,path:g});let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C&&E.push(...s({},C,u,g,b,p))}else S.type==="union"&&Array.isArray(S.schema)&&S.schema.forEach(C=>{let d=b[C.id];d&&E.push(...s({},d,u,g,b,p))});return}if($!==void 0){if(E.push(...r($,S.type,g,S)),S.type==="array"||S.type==="set"){S.itemsType&&Array.isArray($)&&$.forEach((C,d)=>E.push(...r(C,S.itemsType,[...g,d.toString()])));let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?$.forEach((d,l)=>{typeof d=="object"&&d!==null&&(p.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:[...g,l.toString()]}):(p.add(h.id),E.push(...s(d,C,u,[...g,l.toString()],b,p)),p.delete(h.id)))}):E.push({message:`Nested schema '${h.id}' not found`,path:g})}}if(S.type==="object"){let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?typeof $=="object"&&$!==null&&(p.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:g}):(p.add(h.id),E.push(...s($,C,u,g,b,p)),h.constraints?.forEach((d,l)=>{if("rules"in d)E.push(...a(d,$,u,[...g,`constraints[${l}]`],p));else{let w=u[d.predicate];w?w({data:$,field:void 0,arguments:d.parameters})||E.push({message:d.errorMessage||`Constraint '${d.name}' failed with params ${K(d.parameters)}`,path:[...g,`constraints[${l}]`]}):E.push({message:`Predicate '${d.predicate}' not found`,path:[...g,`constraints[${l}]`]})}}),p.delete(h.id))):E.push({message:`Nested schema '${h.id}' not found`,path:g})}}if(S.type==="union"){let h=S.schema;!h||!Array.isArray(h)?E.push({message:"Union type requires an array of schema references",path:g}):h.some(d=>{let l=b[d.id];return l?s($,l,u,g,b,new Set(p)).length===0:(E.push({message:`Nested schema '${d.id}' not found`,path:g}),!1)})||E.push({message:"Value does not match any union schema",path:g})}S.constraints?.forEach((h,C)=>{if("rules"in h)E.push(...a(h,o,u,[...g,`constraints[${C}]`],p));else{let d=u[h.predicate];d?d({data:o,field:S.name,arguments:h.parameters})||E.push({message:h.errorMessage||`Constraint '${h.name}' failed for field '${S.name}' with params ${K(h.parameters)}`,path:[...g,`constraints[${C}]`]}):E.push({message:`Predicate '${h.predicate}' not found`,path:[...g,`constraints[${C}]`]})}})}});for(let y in o)Object.hasOwnProperty.call(o,y)&&!m.has(y)&&E.push({message:`Unexpected field '${y}'`,path:[...f,y]});return c.constraints?.forEach((y,S)=>{if("rules"in y)E.push(...a(y,o,u,[...f,`constraints[${S}]`],p));else{let g=u[y.predicate];if(!g)E.push({message:`Predicate '${y.predicate}' not found`,path:[...f,`constraints[${S}]`]});else if(!g({data:o,field:y.field,arguments:y.parameters})){let h=y.field?` for field '${y.field}'`:"";E.push({message:y.errorMessage||`Constraint '${y.name}' failed${h} with params ${K(y.parameters)}`,path:[...f,`constraints[${S}]`]})}}}),E}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,t,e,[],t.nestedSchemas||{});return u.length>0?i(u):n(c)},types:{input:{},output:{}}}}}function ut(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(r=>{if(!r.path)return;let a=r.path,s=i;for(let o=0;o<a.length;o++){let c=a[o];o===a.length-1?s[c]={type:"validation",message:r.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var _=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var ge=t=>({value:t}),G=t=>({issues:t}),x=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Oe=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},ft=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Me=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},W=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],lt=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string")||t instanceof RegExp||typeof t=="object"&&t!==null&&"field"in t&&typeof t.field=="string")return[];break;case"number":if(typeof t=="number"||Array.isArray(t)&&t.every(i=>typeof i=="number")||typeof t=="object"&&t!==null&&"precision"in t&&typeof t.precision=="number")return[];break;case"boolean":if(typeof t=="boolean")return[];break;case"array":case"set":if(typeof t=="number"||typeof t=="object"&&t!==null&&"minItems"in t&&typeof t.minItems=="number")return[];break;case"enum":if(Array.isArray(t)&&t.length>0&&t.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"union":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[n]}]},we=(t,e)=>{let n=[],i=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...x(t.predicate,`${e}.predicate`)),t.type!==void 0&&t.type!=="schema"&&n.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),t.field!==void 0&&typeof t.field!="string"&&n.push({message:"Field must be a string",path:[`${e}.field`]}),t.parameters!==void 0&&(!t.type||t.type!=="schema")&&n.push(...lt(t.parameters,"dynamic",`${e}.parameters`)),n.push(...x(t.description,`${e}.description`,!1)),n.push(...x(t.errorMessage,`${e}.errorMessage`,!1)),n},$e=(t,e)=>{let n=[],i=["name","operator","rules"],r=["name","operator","rules"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...Me(t.operator,`${e}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?n.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):t.rules.forEach((s,o)=>{"rules"in s?n.push(...$e(s,`${e}.rules[${o}]`)):n.push(...we(s,`${e}.rules[${o}]`))}),n},q=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>{"rules"in i?n.push(...$e(i,`${e}[${r}]`)):n.push(...we(i,`${e}[${r}]`))}),n},je=(t,e)=>{let n=[],i=["operator","field"],r=["operator","field","value","conditions"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Me(t.operator,`${e}.operator`)),n.push(...x(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...je(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},Ne=(t,e)=>{let n=[],i=["fields","type","name"],r=["fields","type","unique","partial","description","order","name"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...ft(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...W(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...je(t.partial,`${e}.partial`)),n.push(...x(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},J=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>n.push(...Ne(i,`${e}[${r}]`))),n},mt=(t,e,n,i,r)=>{let a=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&a.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;a.push(...x(s.id,`${c}.id`)),i.includes(s.id)||a.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&a.push(...q(s.constraints,`${c}.constraints`)),s.indexes&&a.push(...J(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&r==="object")&&!Array.isArray(t)?(a.push(...x(t.id,`${e}.id`)),i.includes(t.id)||a.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&a.push(...q(t.constraints,`${e}.constraints`)),t.indexes&&a.push(...J(t.indexes,`${e}.indexes`))):a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),a)},se=(t,e,n)=>{let i=[],r=["name","type"],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=t;if(r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...Oe(t.type,`${e}.type`)),i.push(...W(t.required,`${e}.required`,!1)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...mt(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...Oe(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],u=t.nestedSchema;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.nestedSchema.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${f}`]})}),i.push(...x(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...q(t.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...J(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...W(t.deprecated,`${e}.deprecated`,!1)),t.reference){let o=["schema","field"],c=["schema","field"],u=t.reference;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.reference.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.reference.${f}`]})}),i.push(...x(t.reference.schema,`${e}.reference.schema`)),i.push(...x(t.reference.field,`${e}.reference.field`))}return i.push(...x(t.description,`${e}.description`,!1)),i.push(...W(t.unique,`${e}.unique`,!1)),i},Ve=(t,e,n)=>{let i=[],r=["name","fields"],a=["name","description","concrete","fields","indexes","constraints","metadata"],s=t;return r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...W(t.concrete,`${e}.concrete`,!1)),Array.isArray(t.fields)?(t.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),t.fields.forEach((o,c)=>{let u=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[u]});else{let f=o.fields;typeof f!="object"||f===null?i.push({message:"Fields must be a non-empty object",path:[`${u}.fields`]}):Object.entries(f).forEach(([b,p])=>{i.push(...se(p,`${u}.fields.${b}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${u}.when`]})}})):typeof t.fields=="object"&&t.fields!==null?Object.entries(t.fields).forEach(([o,c])=>{i.push(...se(c,`${e}.fields.${o}`,n))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...x(t.description,`${e}.description`,!1)),t.indexes&&i.push(...J(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},ht=t=>{if(typeof t!="object"||t===null)return G([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields","nestedSchemas"],r=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],a=e;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[s]})}),n.push(...x(e.name,"name")),n.push(...x(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...se(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(...Ve(c,`nestedSchemas.${o}`,s)))}return n.push(...x(e.description,"description",!1)),e.indexes&&n.push(...J(e.indexes,"indexes")),e.constraints&&n.push(...q(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...qe(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),n.length>0?G(n):ge(e)},ye=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...se(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],r=["type","id","changes","nestedSchemaChanges"],a=t;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...x(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...q(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...J(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Ne(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...$e(t.constraint,`${e}.constraint`)):n.push(...we(t.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...Ve(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},pt=(t,e)=>{let n=[],i=["forward","backward"],r=i,a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},qe=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],r=[...i,"rollback","dependencies"],a=t;i.forEach(o=>{a[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(a).forEach(o=>{r.includes(o)||n.push({message:"Unknown property",path:[`${e}.${o}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...x(t.schemaVersion,`${e}.schemaVersion`)),n.push(...x(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>n.push(...ye(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...ye(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...x(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...pt(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...x(t.createdAt,`${e}.createdAt`)),t.dependencies!==void 0&&(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),n.push(...x(t.checksum,`${e}.checksum`)),n},Ue={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:ht,types:{input:{},output:{}}}};var Le={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return G([{message:"Migration must be an object",path:[]}]);let e=t,n=qe(e,"");return n.length>0?G(n):ge(e)},types:{input:{},output:{}}}},_e={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return G([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,r)=>n.push(...ye(i,`[${r}]`))),n.length>0?G(n):ge(e)},types:{input:[],output:[]}}};function Se(t){try{return!Le["~standard"].validate(t).issues}catch(e){throw new _("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function be(t){try{return!_e["~standard"].validate(t).issues}catch(e){throw new _("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function H(t){try{return!Ue["~standard"].validate(t).issues}catch(e){throw new _("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var yt=H;var U=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function gt(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function wt(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function $t(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function St(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function bt(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function vt(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return bt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=wt(e,n);return i?St(e.parameters,t.parameters,i):!0}return!1}function Et(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return $t(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return vt(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function xt(t){let e=new Set,n=new Set,i=new Set,r=new Set;for(let a of t)switch(a.type){case"addField":if(n.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);i.add(a.id);break;case"removeField":if(i.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case"modifyField":if(n.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);e.add(a.id);break;case"deprecateField":if(n.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);r.add(a.id);break}}function Tt(t){let e=new Set,n=new Set,i=new Set;for(let r of t)switch(r.type){case"addConstraint":let a=r.constraint,s=("name"in a,a.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(r.name))throw new Error(`Cannot remove newly added constraint: ${r.name}`);if(e.has(r.name))throw new Error(`Cannot remove modified constraint: ${r.name}`);n.add(r.name);break;case"modifyConstraint":if(n.has(r.name))throw new Error(`Cannot modify removed constraint: ${r.name}`);if(i.has(r.name))throw new Error(`Cannot modify newly added constraint: ${r.name}`);e.add(r.name);break}}function ve(t,e,n){if(e.length===0)throw new Error("No changes provided");xt(e),Tt(e);let i=gt(t),r="patch";for(let a of e){let s=Et(a,n);if(s==="major"){r="major";break}else s==="minor"&&r==="patch"&&(r="minor")}switch(r){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(t,e){let n=u=>u.split(".").map(f=>parseInt(f,10)||0),[i,r,a]=n(t),[s,o,c]=n(e);return i-s||r-o||a-c}function Ct(t){return t.sort(M)}var k=class extends Error{constructor(n,i,r,a){super(n);this.code=i;this.migrationId=r;this.cause=a;this.name="MigrationError"}},Ge=(p=>(p.INVALID_SCHEMA="INVALID_SCHEMA",p.INVALID_MIGRATION="INVALID_MIGRATION",p.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",p.TIMEOUT="TIMEOUT",p.MEMORY_LIMIT="MEMORY_LIMIT",p.CONCURRENT_OPERATION="CONCURRENT_OPERATION",p.TRANSFORM_ERROR="TRANSFORM_ERROR",p.VERSION_NOT_FOUND="VERSION_NOT_FOUND",p.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",p.STREAM_ERROR="STREAM_ERROR",p.ROLLBACK_ERROR="ROLLBACK_ERROR",p.MISSING_TRANSFORM="MISSING_TRANSFORM",p))(Ge||{}),Ee=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!H(e))throw new k("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(r=>Se(r)))throw new k("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((r,a)=>M(r.schemaVersion,a.schemaVersion))}i&&(this.history=i.sort((r,a)=>M(r.version,a.version)))}catch(r){throw r instanceof k?r:new k("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,r)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await U(n)}catch(n){throw new k("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}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=>be(i))}catch(i){throw new k("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(n,i),s=a.reduce((c,u)=>{let f=n==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,f,u.id)},r),o=await t.processMigrationList(e,n,a);return{newSchema:s,dataPreview:o}}catch(r){throw r instanceof k?r:new k("Dry run failed","INVALID_SCHEMA",void 0,r)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let r=e==="forward"?"pending":"applied",a=n?M(i.schemaVersion,n)>=0:!0;return i.status===r&&a}).sort((i,r)=>e==="forward"?i.id.localeCompare(r.id):r.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let r=ve(e.version,n);return n.map(s=>{try{return me(s,e)}catch(o){throw new k("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ie(s,o)}catch(c){throw new k("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:r})}catch(r){throw r instanceof k?r:new k("Schema update failed","INVALID_SCHEMA",i,r)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new k("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new 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,n){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 r=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),a=this.history.length-i;if(a<0)return n;for(let o=0;o<a;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",r);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new 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,f){try{let b=await c(u);f.enqueue(b)}catch(b){f.error(new k(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,b))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new k(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let r=await i.text();if(typeof window<"u"){let a=new Blob([r],{type:"application/javascript"});return(await import(URL.createObjectURL(a))).default[n]}else{let{runInNewContext:a}=await import("vm"),s={module:{exports:{}},console};return a(r,s,e),s.module.exports[n]}}catch(i){throw new k(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new 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 n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,r)=>this.applySchemaChanges(i,[r]),this.currentSchema)}catch(n){throw n instanceof k?n:new k("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var Je=t=>{let e=[],n=[];return{addField:(i,r)=>{e.push({type:"addField",id:i,definition:r}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let r=t.fields[i];r&&n.push({type:"addField",id:i,definition:r})},modifyField:(i,r)=>{e.push({type:"modifyField",id:i,changes:r});let a=t.fields[i];a&&n.push({type:"modifyField",id:i,changes:a})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let r=t.indexes?.find(a=>a.name===i);r&&n.push({type:"addIndex",definition:r})},modifyIndex:(i,r)=>{e.push({type:"modifyIndex",name:i,changes:r});let a=t.indexes?.find(s=>s.name===i);a&&n.push({type:"modifyIndex",name:i,changes:a})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let r=t.constraints?.find(a=>"name"in a&&a.name===i);r&&n.push({type:"addConstraint",constraint:r})},modifyConstraint:(i,r)=>{e.push({type:"modifyConstraint",name:i,changes:r});let a=t.constraints?.find(s=>"name"in s&&s.name===i);a&&n.push({type:"modifyConstraint",name:i,changes:a})},addNestedSchema:(i,r)=>{e.push({type:"addNestedSchema",id:i,definition:r}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let r=t.nestedSchemas[i];r&&n.push({type:"addNestedSchema",id:i,definition:r})},modifyNestedSchema:(i,r)=>{e.push({type:"modifyNestedSchema",id:i,changes:r});let a=t.nestedSchemas[i];a&&n.push({type:"modifyNestedSchema",id:i,changes:a})},changes:()=>({migrate:e,rollback:n})}};var bn=require("@isomorphic-git/lightning-fs"),D=B(require("isomorphic-git"),1),Q=B(require("isomorphic-git/http/web"),1);var Ke=B(require("@isomorphic-git/lightning-fs"),1);function He(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function ze(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function xe(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),r=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),a,s;return n?(a=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(a=i[1],s=i[2].trim()):r?(a=r[2],s=r[3].trim()):(a=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:a,body:s,type:n?"arrow":i?"function":r?"method":"unknown"})}function Te(t){let{params:e,body:n,type:i}=JSON.parse(t),r=new Function(e,n);return i==="arrow"&&Object.defineProperty(r,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),r}function At(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(r=>{n[r.name]={label:r.label,description:r.description}}),Ce(t.fields,"",t.nestedSchemas||{},e,!0);let i=[];for(let[r,a]of Object.entries(e)){let s=r!=="ungrouped"?n[r]:void 0;i.push({name:r!=="ungrouped"?r:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:a})}return i}function Ce(t,e,n,i,r,a){if(Array.isArray(t))t.forEach(s=>{let o=s.when?e?`${e}.${s.when?.field}`:s.when?.field:void 0;Ce(s.fields,e,n,i,r,o?{[o]:s.when?.value}:void 0)});else for(let[s,o]of Object.entries(t)){if(o.hint?.input.ignore)continue;let c=e?`${e}.${o.name}`:o.name,f=o.required===!0&&r,b={...o,name:c,required:f};if(a&&(b.when=a),o.type!=="object"){let p=o.hint?.input?.group||"ungrouped";i[p]||(i[p]=[]),i[p].push(b)}if(o.schema&&"id"in o.schema&&n[o.schema.id]){let p=n[o.schema.id];Ce(p.fields,c,n,i,f,a)}}}function Dt(t,e){let n={},i=t.nestedSchemas||{};for(let[r,a]of Object.entries(t.fields))n[r]=ae(a,i,e);return n}function ae(t,e,n){if("default"in t&&t.default!==void 0)return t.default;if(n?.resolver){let i=n.resolver(t);if(i!==void 0)return i}switch(t.type){case"string":return"";case"number":return 0;case"boolean":return!1;case"array":return[];case"set":return[];case"enum":if(!t.values||t.values.length===0)throw new Error(`Enum field "${t.name}" requires non-empty values array`);return t.values[0];case"object":if(!t.schema||!("id"in t.schema)||!e[t.schema.id])throw new Error(`Object field "${t.name}" references invalid nested schema`);return Be(e[t.schema.id],e,n);case"record":return{};case"union":if(!t.schema||!Array.isArray(t.schema)||t.schema.length===0)throw new Error(`Union field "${t.name}" requires non-empty schema array`);let i=n?.discriminator?.[t.name],r=t.schema[0];if(i!==void 0)for(let a of t.schema){let o=e[a.id].fields;if(It(o,i)){r=a;break}}return Be(e[r.id],e,n);case"dynamic":return{};default:throw new Error(`Unsupported field type "${t.type}" for field "${t.name}"`)}}function It(t,e){if(Array.isArray(t)){for(let n of t)for(let i of Object.values(n.fields))if(i.type==="enum"&&i.values?.includes(e)||i.default===e)return i}else for(let n of Object.values(t))if(n.type==="enum"&&n.values?.includes(e)||n.default===e)return n}function Be(t,e,n){let i={},r=n?.discriminator||{};if(Array.isArray(t.fields)){let a=t.fields.filter(o=>!o.when);for(let o of a)for(let[c,u]of Object.entries(o.fields))i[c]=ae(u,e,n);let s=t.fields.filter(o=>o.when);for(let o of s){let c=o.when.field,u=o.when.value;if(r[c]===u)for(let[b,p]of Object.entries(o.fields))i[b]=ae(p,e,n)}}else for(let[a,s]of Object.entries(t.fields))i[a]=ae(s,e,n);return i}var We=require("buffer");window.Buffer=We.Buffer;var Y=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new Ke.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!H(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,r=await this.processAndStoreMigrations(i,e),a=this.serializeSchema(e);await this.writeSchemaFile(i,a);let s=await U(a);await this.updateIndex(i,e,s,r,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let r=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(r))return null;let a=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(r,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(a.migrations=await this.migrations({name:e,version:n})),a)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let r=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await U(r)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),r=n||i.version,a=[];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,r)<=0&&a.push(this.deserializeMigration(u))}}return a.sort((s,o)=>M(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async r=>({...i,version:r.version,description:r.description,migrations:await this.migrations({name:e,version:r.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let r={...i};if(i.transform?.forward){let o=i.transform;r.transform={forward:xe(o.forward),backward:xe(o.backward||(c=>c))}}let a=JSON.stringify(r),s=await U(a);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,a,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?He(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=ze(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:Te(e.transform.forward),backward:Te(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,r,a){let s=`${e}/index.json`,o=a==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(a==="create"?"Initial version":"Updated version"),migrations:r.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,r.forEach(({id:c,hash:u,checksum:f})=>{o.migrations[c]={hash:u,checksum:f}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let r=`${e}/${i}`;(await this.fsp.stat(r)).isDirectory()?await this.rmdirRecursive(r):await this.fsp.unlink(r)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let r of i){let a=`${e}/${r}`;(await this.fsp.stat(a)).isDirectory()?n.push(...await this.listFilesRecursive(a)):n.push(a)}return n}};var ke=class{locks=new Map;async acquire(e){let n,i=new Promise(a=>{n=a}),r=this.locks.get(e)||Promise.resolve();return this.locks.set(e,r.then(()=>i)),await r,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},Re=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function oe(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function ce(t,e,n,i,r){await i.init(),await D.default.init({fs:t,dir:e,defaultBranch:n}),await D.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await D.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await D.default.add({fs:t,dir:e,filepath:"."}),await D.default.commit({fs:t,dir:e,message:"chore: initial commit",author:r})}async function Pt(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,r=e.createRemote??!1,a=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new Y(t),u=c.fs,f=t.startsWith("/")?t:`/${t}`,b=new ke,p=new Re(e.cacheTtl);async function E(d,l){let w=o;do{let v=s[o];try{return await d(v)}catch(A){if(console.warn(`Failed with proxy ${v}: ${A.message}`),o=(o+1)%s.length,o===w)throw new Error(`${l}: All CORS proxies failed`)}}while(!0)}async function T(d,l="."){return oe(async()=>(await D.default.add({fs:u,dir:f,filepath:l}),(await D.default.statusMatrix({fs:u,dir:f})).some(([v,A,R])=>A!==R)?await D.default.commit({fs:u,dir:f,message:d,author:a}):null),"Failed to commit changes")}async function m(d,l,w){return oe(async()=>{if(await y(d))throw new Error(`Tag ${d} already exists`);await D.default.annotatedTag({fs:u,dir:f,ref:d,message:l,tagger:a,object:w})},`Failed to create tag ${d}`)}async function y(d){try{return(await D.default.listTags({fs:u,dir:f})).includes(d)}catch{return!1}}async function S(d){return(await D.default.listTags({fs:u,dir:f})).filter(v=>v.startsWith(d))}async function g(d){return oe(async()=>{let w=(await D.default.listTags({fs:u,dir:f})).filter(v=>v.startsWith(d));for(let v of w)await D.default.deleteTag({fs:u,dir:f,ref:v});return w},`Failed to delete tags with prefix ${d}`)}async function $(d){return oe(async()=>{await D.default.checkout({fs:u,dir:f,ref:d})},`Failed to checkout ${d}`)}async function h(d,{delete:l=!1,force:w=!1}={}){i&&await E(async v=>{await D.default.push({fs:u,http:Q.default,dir:f,ref:d,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:v,delete:l,force:w})},`Failed to push ${d}`)}async function C(d,l=!0){i&&await E(async w=>{try{await D.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(v){if(!l)console.warn(`Fast-forward pull failed for ${d}, attempting regular pull`),await D.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw v}},`Failed to pull ${d}`)}if(i&&!await c.fileExists(f)){let d=f.slice(1);if(await i.exists({name:d}).catch(()=>!1))await E(async w=>{await D.default.clone({fs:u,http:Q.default,dir:f,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(r)try{i=await i.create({name:d,private:!0}),await ce(u,f,n,c,a),await D.default.addRemote({fs:u,dir:f,remote:"origin",url:i.url()}),await h(n)}catch(w){console.error("Failed to create and push to remote repository:",w),await ce(u,f,n,c,a)}else await ce(u,f,n,c,a)}else await ce(u,f,n,c,a);return{async init(){return b.withLock("init",()=>c.init())},async create(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await $(n),await c.create(d);let v=await T(`feat: create schema ${l}`);v&&await m(`${l}-${w}`,`Version ${w}`,v),p.invalidate(l)})},async update(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await $(n),await c.update(d);let v=await T(`fix: update schema ${l}`);v&&await m(`${l}-${w}`,`Version ${w}`,v),p.invalidate(l)})},async delete(d){let{name:l}=d;return b.withLock(`schema:${l}`,async()=>{await $(n),await D.default.remove({fs:u,dir:f,filepath:l}),await c.delete(d);let w=await T(`chore: delete schema ${l}`),v=await S(`${l}-`);if(i&&w){await h(n);for(let A of v)await h(A,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${A}: ${R.message}`))}await g(`${l}-`),p.invalidate(l)})},async list(){return b.withLock("list",()=>c.list())},async schema(d){let{name:l,version:w}=d,v=`${l}-${w||"latest"}-${d.migrations||!1}`,A=p.get(v);return A||b.withLock(`schema:${l}`,async()=>{if(w){let I=`${l}-${w}`;if(await y(I))await $(I);else throw new Error(`Version ${w} of schema ${l} not found`)}else await $(n);let R=await c.schema(d);return p.set(v,R),R})},async stats(d){return b.withLock("stats",()=>c.stats(d))},async sync(){return b.withLock("sync",async()=>{if(await $(n),await c.sync(),await T("chore: sync local changes"),i){await C(n,!1),await h(n);let d=await D.default.listTags({fs:u,dir:f});for(let w of d)await h(w,{force:!0});let l=await D.default.listTags({fs:u,dir:f});for(let w of l)d.includes(w)||await h(w,{delete:!0})}p.invalidate()})},async migrations(d){let{name:l,version:w}=d,v=`migrations-${l}-${w||"latest"}`,A=p.get(v);return A||b.withLock(`migrations:${l}`,async()=>{if(w){let I=`${l}-${w}`;if(await y(I))await $(I);else throw new Error(`Version ${w} of schema ${l} not found`)}else await $(n);let R=await c.migrations(d);return p.set(v,R),R})},async history(d){let{name:l}=d,w=`history-${l}`,v=p.get(w);return v||b.withLock(`history:${l}`,async()=>{await $(n);let A=await c.history(d);return p.set(w,A),A})}}}function O(t){return"predicate"in t}function Ft(t,e=!0,n=!0){let i="",r=n?"export ":"",a=new Map,s=new Map,o=(T,m=[])=>{if(!e||!T&&!m.length)return"";let y=T?[T]:[];return m.forEach(S=>y.push(S)),`/**
2
+ * ${y.join(`
3
3
  * `)}
4
4
  */
5
- `},c=T=>T.charAt(0).toUpperCase()+T.slice(1),d=(T,m)=>{let p=s.get(m)||new Map;for(let[S,y]of Object.entries(T))if(y.type==="enum"&&Array.isArray(y.values)){let w=`${m}${c(y.name)}`,h=y.values.map(C=>String(C));a.set(w,h)}else if(y.type==="string"&&y.constraints){let w=y.constraints.find(h=>O(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if(w&&O(w)&&Array.isArray(w.parameters)){let h=`${m}${c(y.name)}`,C=w.parameters.map(u=>String(u));a.set(h,C)}}else if(y.type==="record"){let w=`${m}${c(y.name)}`;p.set(y.name,w)}p.size>0&&s.set(m,p)};d(t.fields,t.name);for(let[T,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(p=>d(p.fields,c(m.name))):d(m.fields,c(m.name));for(let[T,m]of a){i+=o(`Union type for ${T.toLowerCase()} field values`);let p=m.map(S=>`"${S}"`).join(" | ");i+=`${r}type ${T} = ${p};
5
+ `},c=T=>T.charAt(0).toUpperCase()+T.slice(1),u=(T,m)=>{let y=s.get(m)||new Map;for(let[S,g]of Object.entries(T))if(g.type==="enum"&&Array.isArray(g.values)){let $=`${m}${c(g.name)}`,h=g.values.map(C=>String(C));a.set($,h)}else if(g.type==="string"&&g.constraints){let $=g.constraints.find(h=>O(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if($&&O($)&&Array.isArray($.parameters)){let h=`${m}${c(g.name)}`,C=$.parameters.map(d=>String(d));a.set(h,C)}}else if(g.type==="record"){let $=`${m}${c(g.name)}`;y.set(g.name,$)}y.size>0&&s.set(m,y)};u(t.fields,t.name);for(let[T,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(y=>u(y.fields,c(m.name))):u(m.fields,c(m.name));for(let[T,m]of a){i+=o(`Union type for ${T.toLowerCase()} field values`);let y=m.map(S=>`"${S}"`).join(" | ");i+=`${r}type ${T} = ${y};
6
6
 
7
- `}for(let[T,m]of Object.entries(t.nestedSchemas||{})){let p=c(m.name),S=m.constraints?.map(C=>O(C)?`@constraint ${C.name}: ${C.description||C.predicate}`:`@constraint ${C.name}`)||[];m.concrete&&S.push("@concrete Indicates a concrete schema"),i+=o(m.description,S);let y=s.get(p)||new Map,w=Array.from(y.entries()).map(([C,u])=>`${u} extends Record<string, any> = Record<string, any>`).join(", "),h=y.size>0?`<${w}>`:"";if(Array.isArray(m.fields)){let C=m.fields.filter(v=>!v.when),u=m.fields.filter(v=>v.when),l="";if(C.length>0){l+=`{
7
+ `}for(let[T,m]of Object.entries(t.nestedSchemas||{})){let y=c(m.name),S=m.constraints?.map(C=>O(C)?`@constraint ${C.name}: ${C.description||C.predicate}`:`@constraint ${C.name}`)||[];m.concrete&&S.push("@concrete Indicates a concrete schema"),i+=o(m.description,S);let g=s.get(y)||new Map,$=Array.from(g.entries()).map(([C,d])=>`${d} extends Record<string, any> = Record<string, any>`).join(", "),h=g.size>0?`<${$}>`:"";if(Array.isArray(m.fields)){let C=m.fields.filter(v=>!v.when),d=m.fields.filter(v=>v.when),l="";if(C.length>0){l+=`{
8
8
  `;for(let v of C)for(let[A,R]of Object.entries(v.fields)){let I=R.constraints?.map(V=>O(V)?`@constraint ${V.name}: ${V.description||V.predicate}`:`@constraint ${V.name}`)||[];R.unique&&I.push("@unique Ensures unique values"),R.default!==void 0&&I.push(`@default ${JSON.stringify(R.default)}`),e&&R.description?l+=o(R.description,I):I.length&&(l+=o(void 0,I)),R.deprecated&&(l+=` /** @deprecated */
9
- `);let P=de(R,t,p,y),N=R.required===!1?"?":"";l+=` ${R.name}${N}: ${P};
10
- `}l+="}"}let g="";u.length>0&&(g=u.map(A=>{let R=`{
9
+ `);let P=de(R,t,y,g),N=R.required===!1?"?":"";l+=` ${R.name}${N}: ${P};
10
+ `}l+="}"}let w="";d.length>0&&(w=d.map(A=>{let R=`{
11
11
  `;for(let[I,P]of Object.entries(A.fields)){let N=P.constraints?.map(z=>O(z)?`@constraint ${z.name}: ${z.description||z.predicate}`:`@constraint ${z.name}`)||[];P.unique&&N.push("@unique Ensures unique values"),P.default!==void 0&&N.push(`@default ${JSON.stringify(P.default)}`),e&&P.description?R+=o(P.description,N):N.length&&(R+=o(void 0,N)),P.deprecated&&(R+=` /** @deprecated */
12
- `);let V=de(P,t,p,y),Ye=P.required===!1?"?":"";R+=` ${P.name}${Ye}: ${V};
12
+ `);let V=de(P,t,y,g),Ye=P.required===!1?"?":"";R+=` ${P.name}${Ye}: ${V};
13
13
  `}if(A.when)for(let[I,P]of Object.entries(A.when))R+=` ${I}: "${P}";
14
- `;return R+="}",R}).join(" | ")),l&&g?i+=`${r}type ${p}${h} = ${l} & (${g});
14
+ `;return R+="}",R}).join(" | ")),l&&w?i+=`${r}type ${y}${h} = ${l} & (${w});
15
15
 
16
- `:l?i+=`${r}type ${p}${h} = ${l};
16
+ `:l?i+=`${r}type ${y}${h} = ${l};
17
17
 
18
- `:g&&(i+=`${r}type ${p}${h} = ${g};
18
+ `:w&&(i+=`${r}type ${y}${h} = ${w};
19
19
 
20
- `)}else{i+=`${r}type ${p}${h} = {
21
- `;for(let[C,u]of Object.entries(m.fields)){let l=u.constraints?.map(A=>O(A)?`@constraint ${A.name}: ${A.description||A.predicate}`:`@constraint ${A.name}`)||[];u.unique&&l.push("@unique Ensures unique values"),u.default!==void 0&&l.push(`@default ${JSON.stringify(u.default)}`),e&&u.description?i+=o(u.description,l):l.length&&(i+=o(void 0,l)),u.deprecated&&(i+=` /** @deprecated */
22
- `);let g=de(u,t,p,y),v=u.required===!1?"?":"";i+=` ${u.name}${v}: ${g};
20
+ `)}else{i+=`${r}type ${y}${h} = {
21
+ `;for(let[C,d]of Object.entries(m.fields)){let l=d.constraints?.map(A=>O(A)?`@constraint ${A.name}: ${A.description||A.predicate}`:`@constraint ${A.name}`)||[];d.unique&&l.push("@unique Ensures unique values"),d.default!==void 0&&l.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?i+=o(d.description,l):l.length&&(i+=o(void 0,l)),d.deprecated&&(i+=` /** @deprecated */
22
+ `);let w=de(d,t,y,g),v=d.required===!1?"?":"";i+=` ${d.name}${v}: ${w};
23
23
  `}m.metadata&&(i+=` metadata: Record<string, any>;
24
24
  `),i+=`};
25
25
 
26
- `}if(m.indexes?.length){i+=o(`Available indexes for ${p}`),i+=`${r}enum ${p}IndexNames {
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${y}`),i+=`${r}enum ${y}IndexNames {
27
27
  `;for(let C of m.indexes)i+=` ${C.name} = "${C.name}",
28
28
  `;i+=`}
29
29
 
30
- `}}let f=t.constraints?.map(T=>O(T)?`@constraint ${T.name}: ${T.description||T.predicate}`:`@constraint ${T.name}`)||[];i+=o(t.description,f);let b=s.get(t.name)||new Map,$=Array.from(b.entries()).map(([T,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),E=b.size>0?`<${$}>`:"";i+=`${r}type ${t.name}${E} = {
31
- `;for(let[T,m]of Object.entries(t.fields)){let p=m.constraints?.map(w=>O(w)?`@constraint ${w.name}: ${w.description||w.predicate}`:`@constraint ${w.name}`)||[];m.unique&&p.push("@unique Ensures unique values"),m.default!==void 0&&p.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,p):p.length&&(i+=o(void 0,p)),m.deprecated&&(i+=` /** @deprecated */
32
- `);let S=de(m,t,t.name,b),y=m.required===!1?"?":"";i+=` ${m.name}${y}: ${S};
30
+ `}}let f=t.constraints?.map(T=>O(T)?`@constraint ${T.name}: ${T.description||T.predicate}`:`@constraint ${T.name}`)||[];i+=o(t.description,f);let b=s.get(t.name)||new Map,p=Array.from(b.entries()).map(([T,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),E=b.size>0?`<${p}>`:"";i+=`${r}type ${t.name}${E} = {
31
+ `;for(let[T,m]of Object.entries(t.fields)){let y=m.constraints?.map($=>O($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];m.unique&&y.push("@unique Ensures unique values"),m.default!==void 0&&y.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,y):y.length&&(i+=o(void 0,y)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let S=de(m,t,t.name,b),g=m.required===!1?"?":"";i+=` ${m.name}${g}: ${S};
33
33
  `}if(t.metadata&&(i+=` metadata: Record<string, any>;
34
34
  `),i+=`};
35
35
 
@@ -39,7 +39,7 @@
39
39
  `}return i.trim()}function de(t,e,n,i){switch(t.type){case"string":if(t.constraints){let r=t.constraints.find(a=>O(a)&&(a.predicate==="enum"||a.predicate==="oneOf"));if(r&&O(r)&&Array.isArray(r.parameters))return`${n}${L(t.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id];return`${L(r.name)}[]`}return`${t.itemsType}[]`}return"any[]";case"set":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id];return`Set<${L(r.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${L(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id],a=L(r.name);return r.concrete?`string | ${a}`:a}if(t.nestedSchema){let r=e.nestedSchemas[t.nestedSchema.id],a=L(r.name);return r.concrete?`string | ${a}`:a}return t.reference?`${t.reference.schema}${t.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(t.name)||"Record<string, any>";case"union":return t.schema&&Array.isArray(t.schema)?t.schema.map(a=>{let s=e.nestedSchemas[a.id];return L(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function L(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Ot(t,e){let n=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,r=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
40
40
  ${s.conditions.map(c=>` ${r(c)}`).join(`
41
41
  `)}
42
- ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([d,f])=>{let b=`${c} ${d} (${f.type})
42
+ ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,f])=>{let b=`${c} ${u} (${f.type})
43
43
 
44
44
  `;return b+=`**Required:** ${f.required?"Yes":"No"}
45
45
 
package/index.d.cts CHANGED
@@ -1761,6 +1761,8 @@ interface FieldGroup {
1761
1761
  /**
1762
1762
  * Extracts all field definitions from a schema, organized into groups based on hint.input.group,
1763
1763
  * including those in nested schemas, with proper path prefixing to represent the field hierarchy.
1764
+ * The 'required' property of each field is adjusted to be true only if the field and all its parent
1765
+ * fields are required, ensuring alignment with validation behavior.
1764
1766
  *
1765
1767
  * @param schema - The schema definition to extract fields from
1766
1768
  * @returns Array of field groups, each containing grouped field definitions
@@ -1773,7 +1775,7 @@ declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[]
1773
1775
  *
1774
1776
  * @param schema - The schema definition to generate defaults from
1775
1777
  * @param options - Optional configuration for custom defaults and discriminators
1776
- * @returns A fully populated default object conforming to the schema's structure
1778
+ * @returns A fully populated default object conforming to the schemas structure
1777
1779
  */
1778
1780
  declare function schemaDefaults<T>(schema: SchemaDefinition, options?: {
1779
1781
  resolver?: (field: FieldDefinition<any>) => any;
package/index.d.ts CHANGED
@@ -1761,6 +1761,8 @@ interface FieldGroup {
1761
1761
  /**
1762
1762
  * Extracts all field definitions from a schema, organized into groups based on hint.input.group,
1763
1763
  * including those in nested schemas, with proper path prefixing to represent the field hierarchy.
1764
+ * The 'required' property of each field is adjusted to be true only if the field and all its parent
1765
+ * fields are required, ensuring alignment with validation behavior.
1764
1766
  *
1765
1767
  * @param schema - The schema definition to extract fields from
1766
1768
  * @returns Array of field groups, each containing grouped field definitions
@@ -1773,7 +1775,7 @@ declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[]
1773
1775
  *
1774
1776
  * @param schema - The schema definition to generate defaults from
1775
1777
  * @param options - Optional configuration for custom defaults and discriminators
1776
- * @returns A fully populated default object conforming to the schema's structure
1778
+ * @returns A fully populated default object conforming to the schemas structure
1777
1779
  */
1778
1780
  declare function schemaDefaults<T>(schema: SchemaDefinition, options?: {
1779
1781
  resolver?: (field: FieldDefinition<any>) => any;
package/index.js CHANGED
@@ -1,35 +1,35 @@
1
- import{createEventBus as Wt}from"@asaidimu/events";import{createEventBus as Mt}from"@asaidimu/events";import{createMatcher as Nt,createPaginator as Vt,createProjector as qt,createSorter as Ut}from"@asaidimu/query";var F=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function Y(t){let e=Le(t);return e===""?[]:e.substring(1).split("/").map(_e)}function Le(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(W).join("/"):"/"+t.split(".").map(W).join("/")}function W(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function _e(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function Q(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new F(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let r=i==="-"?n.length:parseInt(i);if(isNaN(r)||r<0||r>n.length)throw new F(`Invalid array index: ${i}`);n=n[r]}else{if(!n.hasOwnProperty(i))throw new F(`Property ${i} not found`);n=n[i]}}return n}function ae(t,e){let n=M.get(e)||Y(e);if(M.set(e,n),n.length===0)return t;let i=Q(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);if(isNaN(a)||a<0||a>=i.length)throw new F(`Invalid array index: ${r}`);return i[a]}return i[r]}function Ge(t,e,n){let i=M.get(e)||Y(e);M.set(e,i);let r=Q(t,i.slice(0,-1)),a=i[i.length-1];return Array.isArray(r)?r.splice(0,r.length,...r.filter(s=>s!==n)):r[a]===n&&delete r[a],t}function K(t,e,n){let i=M.get(e)||Y(e);if(M.set(e,i),i.length===0)return n;let r=i.slice(0,-1),a=i[i.length-1],s=Q(t,r);if(Array.isArray(s))if(a==="-")s.push(n);else{let o=parseInt(a);if(o<0||o>s.length)throw new F(`Invalid array index: ${a}`);s.splice(o,0,n)}else s[a]=n;return t}function oe(t,e){let n=M.get(e)||Y(e);if(M.set(e,n),n.length===0)return;let i=Q(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);i.splice(a,1)}else delete i[r];return t}function ce(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=K(n,i.path,i.value);break;case"remove":n=oe(n,i.path);break;case"removeValue":n=Ge(n,i.path,i.value);break;case"replace":n=K(oe(n,i.path),i.path,i.value);break;case"copy":{let r=ae(n,i.from);n=K(n,i.path,JSON.parse(JSON.stringify(r)));break}case"move":{let r=ae(n,i.from);n=K(n,i.path,r),n=oe(n,i.from);break}case"test":{let r=ae(n,i.path);if(JSON.stringify(r)!==JSON.stringify(i.value))throw new F("Test operation failed");break}default:throw new F(`Unsupported operation: ${i.op}`)}}catch(r){throw r instanceof F&&(r.operation=i),r}return n}function mt(t,e){let n=[];return de(t,e,"",n),n}function de(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?Je(t,e,n,i):He(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function Je(t,e,n,i){let r=Math.max(t.length,e.length);for(let a=0;a<r;a++){let s=`${n}/${a}`;a>=t.length?i.push({op:"add",path:`${n}/-`,value:e[a]}):a>=e.length?i.push({op:"remove",path:s}):de(t[a],e[a],s,i)}}function He(t,e,n,i){let r=new Set,a=Object.keys(t),s=Object.keys(e);for(let o of a){let c=W(o),d=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(de(t[o],e[o],d,i),r.add(o)):i.push({op:"remove",path:d})}for(let o of s)if(!r.has(o)){let c=W(o),d=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function Se(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([r,a])=>{typeof a=="object"&&a!==null&&!Array.isArray(a)?n.push({op:"replace",path:`${i}/${r}`,value:a}):n.push({op:"replace",path:`${i}/${r}`,value:a})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`/indexes/${i}/${r}`,value:a})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(r=>Array.isArray(r)?r.some(a=>a.name===t.name):r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=ze(e,t.name);i&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`${i}/${r}`,value:a})});break}}return n}function ze(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(be(i)){let r=ve(i.rules,e);if(r)return`/constraints/${n}${r}`}}return null}function be(t){return t&&"operator"in t&&"rules"in t}function ve(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(be(i)){let r=ve(i.rules,e);if(r)return`/rules/${n}${r}`}}return null}function Ee(t,e){let n={...t};return ue(t)&&ue(e)&&Object.keys(e).forEach(i=>{ue(e[i])?i in t?n[i]=Ee(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function ue(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Z(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function Be(t,e){let n=o=>({value:o}),i=o=>({issues:o}),r=(o,c,d,f)=>{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"enum":return f?.values?f.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(f.values)}, got ${o}`,path:d}]:[{message:"Enum type requires 'values' definition",path:d}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:d}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function a(o,c,d,f,b){let $=[],E=o.rules.map((m,p)=>{let S=[...f,`rules[${p}]`];if("rules"in m){if(b.has(m.name))return!0;b.add(m.name);let y=a(m,c,d,S,b);return $.push(...y),y.length===0}else{let y=d[m.predicate];if(!y)return $.push({message:`Predicate '${m.predicate}' not found`,path:S}),!1;let w=y({data:c,field:m.field,arguments:m.parameters});if(!w){let h=m.field?` for field '${m.field}'`:"";$.push({message:m.errorMessage||`Constraint '${m.name}' failed${h} with params ${Z(m.parameters)}`,path:S})}return w}});return(()=>{switch(o.operator){case"and":return E.every(m=>m);case"or":return E.some(m=>m);case"not":return!E.every(m=>m);case"nor":return!E.some(m=>m);case"xor":return E.filter(m=>m).length===1}})()||$.push({message:`Constraint group '${o.name}' failed`,path:f}),$}function s(o,c,d,f,b,$=new Set){let E=[],T={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))T=c.fields;else{let p=c.fields,S=p.find(w=>!w.when);S&&Object.assign(T,S.fields);let y=p.find(w=>w.when&&o[w.when.field]!==void 0&&o[w.when.field]===w.when.value);if(y)Object.assign(T,y.fields);else if(!S)return E.push({message:"No matching field set found for discriminated schema",path:f}),E}else T=c.fields;let m=new Set(Object.values(T).map(p=>p.name));Object.entries(T).forEach(([p,S])=>{let y=[...f,S.name],w=Object.hasOwnProperty.call(o,S.name)?o[S.name]:void 0;if(S.required&&w==null){E.push({message:`Field '${S.name}' is required`,path:y});let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C&&E.push(...s({},C,d,y,b,$))}else S.type==="union"&&Array.isArray(S.schema)&&S.schema.forEach(C=>{let u=b[C.id];u&&E.push(...s({},u,d,y,b,$))});return}if(w!==void 0){if(E.push(...r(w,S.type,y,S)),S.type==="array"||S.type==="set"){S.itemsType&&Array.isArray(w)&&w.forEach((C,u)=>E.push(...r(C,S.itemsType,[...y,u.toString()])));let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?w.forEach((u,l)=>{typeof u=="object"&&u!==null&&($.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:[...y,l.toString()]}):($.add(h.id),E.push(...s(u,C,d,[...y,l.toString()],b,$)),$.delete(h.id)))}):E.push({message:`Nested schema '${h.id}' not found`,path:y})}}if(S.type==="object"){let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?typeof w=="object"&&w!==null&&($.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:y}):($.add(h.id),E.push(...s(w,C,d,y,b,$)),h.constraints?.forEach((u,l)=>{if("rules"in u)E.push(...a(u,w,d,[...y,`constraints[${l}]`],$));else{let g=d[u.predicate];g?g({data:w,field:void 0,arguments:u.parameters})||E.push({message:u.errorMessage||`Constraint '${u.name}' failed with params ${Z(u.parameters)}`,path:[...y,`constraints[${l}]`]}):E.push({message:`Predicate '${u.predicate}' not found`,path:[...y,`constraints[${l}]`]})}}),$.delete(h.id))):E.push({message:`Nested schema '${h.id}' not found`,path:y})}}if(S.type==="union"){let h=S.schema;!h||!Array.isArray(h)?E.push({message:"Union type requires an array of schema references",path:y}):h.some(u=>{let l=b[u.id];return l?s(w,l,d,y,b,new Set($)).length===0:(E.push({message:`Nested schema '${u.id}' not found`,path:y}),!1)})||E.push({message:"Value does not match any union schema",path:y})}S.constraints?.forEach((h,C)=>{if("rules"in h)E.push(...a(h,o,d,[...y,`constraints[${C}]`],$));else{let u=d[h.predicate];u?u({data:o,field:S.name,arguments:h.parameters})||E.push({message:h.errorMessage||`Constraint '${h.name}' failed for field '${S.name}' with params ${Z(h.parameters)}`,path:[...y,`constraints[${C}]`]}):E.push({message:`Predicate '${h.predicate}' not found`,path:[...y,`constraints[${C}]`]})}})}});for(let p in o)Object.hasOwnProperty.call(o,p)&&!m.has(p)&&E.push({message:`Unexpected field '${p}'`,path:[...f,p]});return c.constraints?.forEach((p,S)=>{if("rules"in p)E.push(...a(p,o,d,[...f,`constraints[${S}]`],$));else{let y=d[p.predicate];if(!y)E.push({message:`Predicate '${p.predicate}' not found`,path:[...f,`constraints[${S}]`]});else if(!y({data:o,field:p.field,arguments:p.parameters})){let h=p.field?` for field '${p.field}'`:"";E.push({message:p.errorMessage||`Constraint '${p.name}' failed${h} with params ${Z(p.parameters)}`,path:[...f,`constraints[${S}]`]})}}}),E}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=s(c,t,e,[],t.nestedSchemas||{});return d.length>0?i(d):n(c)},types:{input:{},output:{}}}}}function yt(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(r=>{if(!r.path)return;let a=r.path,s=i;for(let o=0;o<a.length;o++){let c=a[o];o===a.length-1?s[c]={type:"validation",message:r.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var L=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var le=t=>({value:t}),_=t=>({issues:t}),x=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],xe=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Ke=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Te=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},z=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],We=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string")||t instanceof RegExp||typeof t=="object"&&t!==null&&"field"in t&&typeof t.field=="string")return[];break;case"number":if(typeof t=="number"||Array.isArray(t)&&t.every(i=>typeof i=="number")||typeof t=="object"&&t!==null&&"precision"in t&&typeof t.precision=="number")return[];break;case"boolean":if(typeof t=="boolean")return[];break;case"array":case"set":if(typeof t=="number"||typeof t=="object"&&t!==null&&"minItems"in t&&typeof t.minItems=="number")return[];break;case"enum":if(Array.isArray(t)&&t.length>0&&t.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"union":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[n]}]},me=(t,e)=>{let n=[],i=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...x(t.predicate,`${e}.predicate`)),t.type!==void 0&&t.type!=="schema"&&n.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),t.field!==void 0&&typeof t.field!="string"&&n.push({message:"Field must be a string",path:[`${e}.field`]}),t.parameters!==void 0&&(!t.type||t.type!=="schema")&&n.push(...We(t.parameters,"dynamic",`${e}.parameters`)),n.push(...x(t.description,`${e}.description`,!1)),n.push(...x(t.errorMessage,`${e}.errorMessage`,!1)),n},he=(t,e)=>{let n=[],i=["name","operator","rules"],r=["name","operator","rules"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...Te(t.operator,`${e}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?n.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):t.rules.forEach((s,o)=>{"rules"in s?n.push(...he(s,`${e}.rules[${o}]`)):n.push(...me(s,`${e}.rules[${o}]`))}),n},q=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>{"rules"in i?n.push(...he(i,`${e}[${r}]`)):n.push(...me(i,`${e}[${r}]`))}),n},Ce=(t,e)=>{let n=[],i=["operator","field"],r=["operator","field","value","conditions"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Te(t.operator,`${e}.operator`)),n.push(...x(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...Ce(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},ke=(t,e)=>{let n=[],i=["fields","type","name"],r=["fields","type","unique","partial","description","order","name"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...Ke(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...z(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...Ce(t.partial,`${e}.partial`)),n.push(...x(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},G=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>n.push(...ke(i,`${e}[${r}]`))),n},Ye=(t,e,n,i,r)=>{let a=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&a.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;a.push(...x(s.id,`${c}.id`)),i.includes(s.id)||a.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&a.push(...q(s.constraints,`${c}.constraints`)),s.indexes&&a.push(...G(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&r==="object")&&!Array.isArray(t)?(a.push(...x(t.id,`${e}.id`)),i.includes(t.id)||a.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&a.push(...q(t.constraints,`${e}.constraints`)),t.indexes&&a.push(...G(t.indexes,`${e}.indexes`))):a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),a)},X=(t,e,n)=>{let i=[],r=["name","type"],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=t;if(r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...xe(t.type,`${e}.type`)),i.push(...z(t.required,`${e}.required`,!1)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...Ye(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...xe(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],d=t.nestedSchema;o.forEach(f=>{d[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.nestedSchema.${f}`]})}),Object.keys(d).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${f}`]})}),i.push(...x(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...q(t.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...G(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...z(t.deprecated,`${e}.deprecated`,!1)),t.reference){let o=["schema","field"],c=["schema","field"],d=t.reference;o.forEach(f=>{d[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.reference.${f}`]})}),Object.keys(d).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.reference.${f}`]})}),i.push(...x(t.reference.schema,`${e}.reference.schema`)),i.push(...x(t.reference.field,`${e}.reference.field`))}return i.push(...x(t.description,`${e}.description`,!1)),i.push(...z(t.unique,`${e}.unique`,!1)),i},Re=(t,e,n)=>{let i=[],r=["name","fields"],a=["name","description","concrete","fields","indexes","constraints","metadata"],s=t;return r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...z(t.concrete,`${e}.concrete`,!1)),Array.isArray(t.fields)?(t.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),t.fields.forEach((o,c)=>{let d=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[d]});else{let f=o.fields;typeof f!="object"||f===null?i.push({message:"Fields must be a non-empty object",path:[`${d}.fields`]}):Object.entries(f).forEach(([b,$])=>{i.push(...X($,`${d}.fields.${b}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${d}.when`]})}})):typeof t.fields=="object"&&t.fields!==null?Object.entries(t.fields).forEach(([o,c])=>{i.push(...X(c,`${e}.fields.${o}`,n))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...x(t.description,`${e}.description`,!1)),t.indexes&&i.push(...G(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},Qe=t=>{if(typeof t!="object"||t===null)return _([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields","nestedSchemas"],r=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],a=e;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[s]})}),n.push(...x(e.name,"name")),n.push(...x(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...X(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(...Re(c,`nestedSchemas.${o}`,s)))}return n.push(...x(e.description,"description",!1)),e.indexes&&n.push(...G(e.indexes,"indexes")),e.constraints&&n.push(...q(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...Ae(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),n.length>0?_(n):le(e)},fe=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...X(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],r=["type","id","changes","nestedSchemaChanges"],a=t;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...x(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...q(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...G(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...ke(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...he(t.constraint,`${e}.constraint`)):n.push(...me(t.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...Re(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},Ze=(t,e)=>{let n=[],i=["forward","backward"],r=i,a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},Ae=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],r=[...i,"rollback","dependencies"],a=t;i.forEach(o=>{a[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(a).forEach(o=>{r.includes(o)||n.push({message:"Unknown property",path:[`${e}.${o}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...x(t.schemaVersion,`${e}.schemaVersion`)),n.push(...x(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>n.push(...fe(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...fe(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...x(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...Ze(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...x(t.createdAt,`${e}.createdAt`)),t.dependencies!==void 0&&(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),n.push(...x(t.checksum,`${e}.checksum`)),n},De={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:Qe,types:{input:{},output:{}}}};var Ie={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return _([{message:"Migration must be an object",path:[]}]);let e=t,n=Ae(e,"");return n.length>0?_(n):le(e)},types:{input:{},output:{}}}},Pe={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return _([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,r)=>n.push(...fe(i,`[${r}]`))),n.length>0?_(n):le(e)},types:{input:[],output:[]}}};function Fe(t){try{return!Ie["~standard"].validate(t).issues}catch(e){throw new L("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function Oe(t){try{return!Pe["~standard"].validate(t).issues}catch(e){throw new L("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function B(t){try{return!De["~standard"].validate(t).issues}catch(e){throw new L("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var vt=B;var J=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function Xe(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function et(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function tt(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function nt(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function it(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function st(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return it(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=et(e,n);return i?nt(e.parameters,t.parameters,i):!0}return!1}function rt(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return tt(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return st(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function at(t){let e=new Set,n=new Set,i=new Set,r=new Set;for(let a of t)switch(a.type){case"addField":if(n.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);i.add(a.id);break;case"removeField":if(i.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case"modifyField":if(n.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);e.add(a.id);break;case"deprecateField":if(n.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);r.add(a.id);break}}function ot(t){let e=new Set,n=new Set,i=new Set;for(let r of t)switch(r.type){case"addConstraint":let a=r.constraint,s=("name"in a,a.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(r.name))throw new Error(`Cannot remove newly added constraint: ${r.name}`);if(e.has(r.name))throw new Error(`Cannot remove modified constraint: ${r.name}`);n.add(r.name);break;case"modifyConstraint":if(n.has(r.name))throw new Error(`Cannot modify removed constraint: ${r.name}`);if(i.has(r.name))throw new Error(`Cannot modify newly added constraint: ${r.name}`);e.add(r.name);break}}function Me(t,e,n){if(e.length===0)throw new Error("No changes provided");at(e),ot(e);let i=Xe(t),r="patch";for(let a of e){let s=rt(a,n);if(s==="major"){r="major";break}else s==="minor"&&r==="patch"&&(r="minor")}switch(r){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 j(t,e){let n=d=>d.split(".").map(f=>parseInt(f,10)||0),[i,r,a]=n(t),[s,o,c]=n(e);return i-s||r-o||a-c}function Tt(t){return t.sort(j)}var R=class extends Error{constructor(n,i,r,a){super(n);this.code=i;this.migrationId=r;this.cause=a;this.name="MigrationError"}},ct=($=>($.INVALID_SCHEMA="INVALID_SCHEMA",$.INVALID_MIGRATION="INVALID_MIGRATION",$.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",$.TIMEOUT="TIMEOUT",$.MEMORY_LIMIT="MEMORY_LIMIT",$.CONCURRENT_OPERATION="CONCURRENT_OPERATION",$.TRANSFORM_ERROR="TRANSFORM_ERROR",$.VERSION_NOT_FOUND="VERSION_NOT_FOUND",$.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",$.STREAM_ERROR="STREAM_ERROR",$.ROLLBACK_ERROR="ROLLBACK_ERROR",$.MISSING_TRANSFORM="MISSING_TRANSFORM",$))(ct||{}),je=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!B(e))throw new R("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(r=>Fe(r)))throw new R("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((r,a)=>j(r.schemaVersion,a.schemaVersion))}i&&(this.history=i.sort((r,a)=>j(r.version,a.version)))}catch(r){throw r instanceof R?r:new R("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,r)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await J(n)}catch(n){throw new R("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new R("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Oe(i))}catch(i){throw new R("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(n,i),s=a.reduce((c,d)=>{let f=n==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,f,d.id)},r),o=await t.processMigrationList(e,n,a);return{newSchema:s,dataPreview:o}}catch(r){throw r instanceof R?r:new R("Dry run failed","INVALID_SCHEMA",void 0,r)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let r=e==="forward"?"pending":"applied",a=n?j(i.schemaVersion,n)>=0:!0;return i.status===r&&a}).sort((i,r)=>e==="forward"?i.id.localeCompare(r.id):r.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let r=Me(e.version,n);return n.map(s=>{try{return Se(s,e)}catch(o){throw new R("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ce(s,o)}catch(c){throw new R("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:r})}catch(r){throw r instanceof R?r:new R("Schema update failed","INVALID_SCHEMA",i,r)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new R("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new R("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 r=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),a=this.history.length-i;if(a<0)return n;for(let o=0;o<a;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",r);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new R(`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(d,f){try{let b=await c(d);f.enqueue(b)}catch(b){f.error(new R(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,b))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new R(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let r=await i.text();if(typeof window<"u"){let a=new Blob([r],{type:"application/javascript"});return(await import(URL.createObjectURL(a))).default[n]}else{let{runInNewContext:a}=await import("vm"),s={module:{exports:{}},console};return a(r,s,e),s.module.exports[n]}}catch(i){throw new R(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new R(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,r)=>this.applySchemaChanges(i,[r]),this.currentSchema)}catch(n){throw n instanceof R?n:new R("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var dt=t=>{let e=[],n=[];return{addField:(i,r)=>{e.push({type:"addField",id:i,definition:r}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let r=t.fields[i];r&&n.push({type:"addField",id:i,definition:r})},modifyField:(i,r)=>{e.push({type:"modifyField",id:i,changes:r});let a=t.fields[i];a&&n.push({type:"modifyField",id:i,changes:a})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let r=t.indexes?.find(a=>a.name===i);r&&n.push({type:"addIndex",definition:r})},modifyIndex:(i,r)=>{e.push({type:"modifyIndex",name:i,changes:r});let a=t.indexes?.find(s=>s.name===i);a&&n.push({type:"modifyIndex",name:i,changes:a})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let r=t.constraints?.find(a=>"name"in a&&a.name===i);r&&n.push({type:"addConstraint",constraint:r})},modifyConstraint:(i,r)=>{e.push({type:"modifyConstraint",name:i,changes:r});let a=t.constraints?.find(s=>"name"in s&&s.name===i);a&&n.push({type:"modifyConstraint",name:i,changes:a})},addNestedSchema:(i,r)=>{e.push({type:"addNestedSchema",id:i,definition:r}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let r=t.nestedSchemas[i];r&&n.push({type:"addNestedSchema",id:i,definition:r})},modifyNestedSchema:(i,r)=>{e.push({type:"modifyNestedSchema",id:i,changes:r});let a=t.nestedSchemas[i];a&&n.push({type:"modifyNestedSchema",id:i,changes:a})},changes:()=>({migrate:e,rollback:n})}};import"@isomorphic-git/lightning-fs";import D from"isomorphic-git";import ne from"isomorphic-git/http/web";import ft from"@isomorphic-git/lightning-fs";function Ne(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function Ve(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function pe(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),r=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),a,s;return n?(a=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(a=i[1],s=i[2].trim()):r?(a=r[2],s=r[3].trim()):(a=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:a,body:s,type:n?"arrow":i?"function":r?"method":"unknown"})}function ye(t){let{params:e,body:n,type:i}=JSON.parse(t),r=new Function(e,n);return i==="arrow"&&Object.defineProperty(r,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),r}function Xt(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(r=>{n[r.name]={label:r.label,description:r.description}}),ge(t.fields,"",t.nestedSchemas||{},e);let i=[];for(let[r,a]of Object.entries(e)){let s=r!=="ungrouped"?n[r]:void 0;i.push({name:r!=="ungrouped"?r:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:a})}return i}function ge(t,e,n,i,r){if(Array.isArray(t))t.forEach(a=>{let s=a.when?e?`${e}.${a.when?.field}`:a.when?.field:void 0;ge(a.fields,e,n,i,s?{[s]:a.when?.value}:void 0)});else for(let[a,s]of Object.entries(t)){if(s.hint?.input.ignore)continue;let o=e?`${e}.${s.name}`:s.name,c={...s,name:o};if(s.type!=="object"){let d=s.hint?.input?.group||"ungrouped";i[d]||(i[d]=[]),i[d].push(c)}if(r&&(c.when=r),s.schema&&"id"in s.schema&&n[s.schema.id]){let d=n[s.schema.id];ge(d.fields,o,n,i,r)}}}function en(t,e){let n={},i=t.nestedSchemas||{};for(let[r,a]of Object.entries(t.fields))n[r]=ee(a,i,e);return n}function ee(t,e,n){if("default"in t&&t.default!==void 0)return t.default;if(n?.resolver){let i=n.resolver(t);if(i!==void 0)return i}switch(t.type){case"string":return"";case"number":return 0;case"boolean":return!1;case"array":return[];case"set":return[];case"enum":if(!t.values||t.values.length===0)throw new Error(`Enum field "${t.name}" requires non-empty values array`);return t.values[0];case"object":if(!t.schema||!("id"in t.schema)||!e[t.schema.id])throw new Error(`Object field "${t.name}" references invalid nested schema`);return qe(e[t.schema.id],e,n);case"record":return{};case"union":if(!t.schema||!Array.isArray(t.schema)||t.schema.length===0)throw new Error(`Union field "${t.name}" requires non-empty schema array`);let i=n?.discriminator?.[t.name],r=t.schema[0];if(i!==void 0)for(let a of t.schema){let o=e[a.id].fields;if(ut(o,i)){r=a;break}}return qe(e[r.id],e,n);case"dynamic":return{};default:throw new Error(`Unsupported field type "${t.type}" for field "${t.name}"`)}}function ut(t,e){if(Array.isArray(t)){for(let n of t)for(let i of Object.values(n.fields))if(i.type==="enum"&&i.values?.includes(e)||i.default===e)return i}else for(let n of Object.values(t))if(n.type==="enum"&&n.values?.includes(e)||n.default===e)return n}function qe(t,e,n){let i={},r=n?.discriminator||{};if(Array.isArray(t.fields)){let a=t.fields.filter(o=>!o.when);for(let o of a)for(let[c,d]of Object.entries(o.fields))i[c]=ee(d,e,n);let s=t.fields.filter(o=>o.when);for(let o of s){let c=o.when.field,d=o.when.value;if(r[c]===d)for(let[b,$]of Object.entries(o.fields))i[b]=ee($,e,n)}}else for(let[a,s]of Object.entries(t.fields))i[a]=ee(s,e,n);return i}import{Buffer as lt}from"buffer";window.Buffer=lt;var te=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new ft(`${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||!B(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,r=await this.processAndStoreMigrations(i,e),a=this.serializeSchema(e);await this.writeSchemaFile(i,a);let s=await J(a);await this.updateIndex(i,e,s,r,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let r=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(r))return null;let a=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(r,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(a.migrations=await this.migrations({name:e,version:n})),a)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let r=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await J(r)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),r=n||i.version,a=[];for(let[s,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")));j(d.schemaVersion,r)<=0&&a.push(this.deserializeMigration(d))}}return a.sort((s,o)=>j(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async r=>({...i,version:r.version,description:r.description,migrations:await this.migrations({name:e,version:r.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let r={...i};if(i.transform?.forward){let o=i.transform;r.transform={forward:pe(o.forward),backward:pe(o.backward||(c=>c))}}let a=JSON.stringify(r),s=await J(a);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,a,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ne(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ve(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ye(e.transform.forward),backward:ye(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,r,a){let s=`${e}/index.json`,o=a==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(a==="create"?"Initial version":"Updated version"),migrations:r.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,r.forEach(({id:c,hash:d,checksum:f})=>{o.migrations[c]={hash:d,checksum:f}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let r=`${e}/${i}`;(await this.fsp.stat(r)).isDirectory()?await this.rmdirRecursive(r):await this.fsp.unlink(r)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let r of i){let a=`${e}/${r}`;(await this.fsp.stat(a)).isDirectory()?n.push(...await this.listFilesRecursive(a)):n.push(a)}return n}};var we=class{locks=new Map;async acquire(e){let n,i=new Promise(a=>{n=a}),r=this.locks.get(e)||Promise.resolve();return this.locks.set(e,r.then(()=>i)),await r,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},$e=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function ie(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function se(t,e,n,i,r){await i.init(),await D.init({fs:t,dir:e,defaultBranch:n}),await D.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await D.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await D.add({fs:t,dir:e,filepath:"."}),await D.commit({fs:t,dir:e,message:"chore: initial commit",author:r})}async function $n(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,r=e.createRemote??!1,a=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new te(t),d=c.fs,f=t.startsWith("/")?t:`/${t}`,b=new we,$=new $e(e.cacheTtl);async function E(u,l){let g=o;do{let v=s[o];try{return await u(v)}catch(A){if(console.warn(`Failed with proxy ${v}: ${A.message}`),o=(o+1)%s.length,o===g)throw new Error(`${l}: All CORS proxies failed`)}}while(!0)}async function T(u,l="."){return ie(async()=>(await D.add({fs:d,dir:f,filepath:l}),(await D.statusMatrix({fs:d,dir:f})).some(([v,A,k])=>A!==k)?await D.commit({fs:d,dir:f,message:u,author:a}):null),"Failed to commit changes")}async function m(u,l,g){return ie(async()=>{if(await p(u))throw new Error(`Tag ${u} already exists`);await D.annotatedTag({fs:d,dir:f,ref:u,message:l,tagger:a,object:g})},`Failed to create tag ${u}`)}async function p(u){try{return(await D.listTags({fs:d,dir:f})).includes(u)}catch{return!1}}async function S(u){return(await D.listTags({fs:d,dir:f})).filter(v=>v.startsWith(u))}async function y(u){return ie(async()=>{let g=(await D.listTags({fs:d,dir:f})).filter(v=>v.startsWith(u));for(let v of g)await D.deleteTag({fs:d,dir:f,ref:v});return g},`Failed to delete tags with prefix ${u}`)}async function w(u){return ie(async()=>{await D.checkout({fs:d,dir:f,ref:u})},`Failed to checkout ${u}`)}async function h(u,{delete:l=!1,force:g=!1}={}){i&&await E(async v=>{await D.push({fs:d,http:ne,dir:f,ref:u,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:v,delete:l,force:g})},`Failed to push ${u}`)}async function C(u,l=!0){i&&await E(async g=>{try{await D.pull({fs:d,http:ne,dir:f,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:g,fastForwardOnly:!0})}catch(v){if(!l)console.warn(`Fast-forward pull failed for ${u}, attempting regular pull`),await D.pull({fs:d,http:ne,dir:f,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:g,fastForwardOnly:!1});else throw v}},`Failed to pull ${u}`)}if(i&&!await c.fileExists(f)){let u=f.slice(1);if(await i.exists({name:u}).catch(()=>!1))await E(async g=>{await D.clone({fs:d,http:ne,dir:f,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:g})},"Failed to clone repository");else if(r)try{i=await i.create({name:u,private:!0}),await se(d,f,n,c,a),await D.addRemote({fs:d,dir:f,remote:"origin",url:i.url()}),await h(n)}catch(g){console.error("Failed to create and push to remote repository:",g),await se(d,f,n,c,a)}else await se(d,f,n,c,a)}else await se(d,f,n,c,a);return{async init(){return b.withLock("init",()=>c.init())},async create(u){let{name:l,version:g}=u.schema;return b.withLock(`schema:${l}`,async()=>{await w(n),await c.create(u);let v=await T(`feat: create schema ${l}`);v&&await m(`${l}-${g}`,`Version ${g}`,v),$.invalidate(l)})},async update(u){let{name:l,version:g}=u.schema;return b.withLock(`schema:${l}`,async()=>{await w(n),await c.update(u);let v=await T(`fix: update schema ${l}`);v&&await m(`${l}-${g}`,`Version ${g}`,v),$.invalidate(l)})},async delete(u){let{name:l}=u;return b.withLock(`schema:${l}`,async()=>{await w(n),await D.remove({fs:d,dir:f,filepath:l}),await c.delete(u);let g=await T(`chore: delete schema ${l}`),v=await S(`${l}-`);if(i&&g){await h(n);for(let A of v)await h(A,{delete:!0,force:!0}).catch(k=>console.warn(`Failed to delete remote tag ${A}: ${k.message}`))}await y(`${l}-`),$.invalidate(l)})},async list(){return b.withLock("list",()=>c.list())},async schema(u){let{name:l,version:g}=u,v=`${l}-${g||"latest"}-${u.migrations||!1}`,A=$.get(v);return A||b.withLock(`schema:${l}`,async()=>{if(g){let I=`${l}-${g}`;if(await p(I))await w(I);else throw new Error(`Version ${g} of schema ${l} not found`)}else await w(n);let k=await c.schema(u);return $.set(v,k),k})},async stats(u){return b.withLock("stats",()=>c.stats(u))},async sync(){return b.withLock("sync",async()=>{if(await w(n),await c.sync(),await T("chore: sync local changes"),i){await C(n,!1),await h(n);let u=await D.listTags({fs:d,dir:f});for(let g of u)await h(g,{force:!0});let l=await D.listTags({fs:d,dir:f});for(let g of l)u.includes(g)||await h(g,{delete:!0})}$.invalidate()})},async migrations(u){let{name:l,version:g}=u,v=`migrations-${l}-${g||"latest"}`,A=$.get(v);return A||b.withLock(`migrations:${l}`,async()=>{if(g){let I=`${l}-${g}`;if(await p(I))await w(I);else throw new Error(`Version ${g} of schema ${l} not found`)}else await w(n);let k=await c.migrations(u);return $.set(v,k),k})},async history(u){let{name:l}=u,g=`history-${l}`,v=$.get(g);return v||b.withLock(`history:${l}`,async()=>{await w(n);let A=await c.history(u);return $.set(g,A),A})}}}function O(t){return"predicate"in t}function Tn(t,e=!0,n=!0){let i="",r=n?"export ":"",a=new Map,s=new Map,o=(T,m=[])=>{if(!e||!T&&!m.length)return"";let p=T?[T]:[];return m.forEach(S=>p.push(S)),`/**
2
- * ${p.join(`
1
+ import{createEventBus as Wt}from"@asaidimu/events";import{createEventBus as Mt}from"@asaidimu/events";import{createMatcher as Nt,createPaginator as Vt,createProjector as qt,createSorter as Ut}from"@asaidimu/query";var F=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function Y(t){let e=Le(t);return e===""?[]:e.substring(1).split("/").map(_e)}function Le(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(W).join("/"):"/"+t.split(".").map(W).join("/")}function W(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function _e(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function Q(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new F(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let r=i==="-"?n.length:parseInt(i);if(isNaN(r)||r<0||r>n.length)throw new F(`Invalid array index: ${i}`);n=n[r]}else{if(!n.hasOwnProperty(i))throw new F(`Property ${i} not found`);n=n[i]}}return n}function ae(t,e){let n=M.get(e)||Y(e);if(M.set(e,n),n.length===0)return t;let i=Q(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);if(isNaN(a)||a<0||a>=i.length)throw new F(`Invalid array index: ${r}`);return i[a]}return i[r]}function Ge(t,e,n){let i=M.get(e)||Y(e);M.set(e,i);let r=Q(t,i.slice(0,-1)),a=i[i.length-1];return Array.isArray(r)?r.splice(0,r.length,...r.filter(s=>s!==n)):r[a]===n&&delete r[a],t}function K(t,e,n){let i=M.get(e)||Y(e);if(M.set(e,i),i.length===0)return n;let r=i.slice(0,-1),a=i[i.length-1],s=Q(t,r);if(Array.isArray(s))if(a==="-")s.push(n);else{let o=parseInt(a);if(o<0||o>s.length)throw new F(`Invalid array index: ${a}`);s.splice(o,0,n)}else s[a]=n;return t}function oe(t,e){let n=M.get(e)||Y(e);if(M.set(e,n),n.length===0)return;let i=Q(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);i.splice(a,1)}else delete i[r];return t}function ce(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=K(n,i.path,i.value);break;case"remove":n=oe(n,i.path);break;case"removeValue":n=Ge(n,i.path,i.value);break;case"replace":n=K(oe(n,i.path),i.path,i.value);break;case"copy":{let r=ae(n,i.from);n=K(n,i.path,JSON.parse(JSON.stringify(r)));break}case"move":{let r=ae(n,i.from);n=K(n,i.path,r),n=oe(n,i.from);break}case"test":{let r=ae(n,i.path);if(JSON.stringify(r)!==JSON.stringify(i.value))throw new F("Test operation failed");break}default:throw new F(`Unsupported operation: ${i.op}`)}}catch(r){throw r instanceof F&&(r.operation=i),r}return n}function mt(t,e){let n=[];return de(t,e,"",n),n}function de(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?Je(t,e,n,i):He(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function Je(t,e,n,i){let r=Math.max(t.length,e.length);for(let a=0;a<r;a++){let s=`${n}/${a}`;a>=t.length?i.push({op:"add",path:`${n}/-`,value:e[a]}):a>=e.length?i.push({op:"remove",path:s}):de(t[a],e[a],s,i)}}function He(t,e,n,i){let r=new Set,a=Object.keys(t),s=Object.keys(e);for(let o of a){let c=W(o),u=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(de(t[o],e[o],u,i),r.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!r.has(o)){let c=W(o),u=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function Se(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([r,a])=>{typeof a=="object"&&a!==null&&!Array.isArray(a)?n.push({op:"replace",path:`${i}/${r}`,value:a}):n.push({op:"replace",path:`${i}/${r}`,value:a})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`/indexes/${i}/${r}`,value:a})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(r=>Array.isArray(r)?r.some(a=>a.name===t.name):r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=ze(e,t.name);i&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`${i}/${r}`,value:a})});break}}return n}function ze(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(be(i)){let r=ve(i.rules,e);if(r)return`/constraints/${n}${r}`}}return null}function be(t){return t&&"operator"in t&&"rules"in t}function ve(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(be(i)){let r=ve(i.rules,e);if(r)return`/rules/${n}${r}`}}return null}function Ee(t,e){let n={...t};return ue(t)&&ue(e)&&Object.keys(e).forEach(i=>{ue(e[i])?i in t?n[i]=Ee(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function ue(t){return t&&typeof t=="object"&&!Array.isArray(t)}function Z(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function Be(t,e){let n=o=>({value:o}),i=o=>({issues:o}),r=(o,c,u,f)=>{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 f?.values?f.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(f.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 a(o,c,u,f,b){let p=[],E=o.rules.map((m,y)=>{let S=[...f,`rules[${y}]`];if("rules"in m){if(b.has(m.name))return!0;b.add(m.name);let g=a(m,c,u,S,b);return p.push(...g),g.length===0}else{let g=u[m.predicate];if(!g)return p.push({message:`Predicate '${m.predicate}' not found`,path:S}),!1;let $=g({data:c,field:m.field,arguments:m.parameters});if(!$){let h=m.field?` for field '${m.field}'`:"";p.push({message:m.errorMessage||`Constraint '${m.name}' failed${h} with params ${Z(m.parameters)}`,path:S})}return $}});return(()=>{switch(o.operator){case"and":return E.every(m=>m);case"or":return E.some(m=>m);case"not":return!E.every(m=>m);case"nor":return!E.some(m=>m);case"xor":return E.filter(m=>m).length===1}})()||p.push({message:`Constraint group '${o.name}' failed`,path:f}),p}function s(o,c,u,f,b,p=new Set){let E=[],T={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))T=c.fields;else{let y=c.fields,S=y.find($=>!$.when);S&&Object.assign(T,S.fields);let g=y.find($=>$.when&&o[$.when.field]!==void 0&&o[$.when.field]===$.when.value);if(g)Object.assign(T,g.fields);else if(!S)return E.push({message:"No matching field set found for discriminated schema",path:f}),E}else T=c.fields;let m=new Set(Object.values(T).map(y=>y.name));Object.entries(T).forEach(([y,S])=>{let g=[...f,S.name],$=Object.hasOwnProperty.call(o,S.name)?o[S.name]:void 0;if(S.required&&$==null){E.push({message:`Field '${S.name}' is required`,path:g});let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C&&E.push(...s({},C,u,g,b,p))}else S.type==="union"&&Array.isArray(S.schema)&&S.schema.forEach(C=>{let d=b[C.id];d&&E.push(...s({},d,u,g,b,p))});return}if($!==void 0){if(E.push(...r($,S.type,g,S)),S.type==="array"||S.type==="set"){S.itemsType&&Array.isArray($)&&$.forEach((C,d)=>E.push(...r(C,S.itemsType,[...g,d.toString()])));let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?$.forEach((d,l)=>{typeof d=="object"&&d!==null&&(p.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:[...g,l.toString()]}):(p.add(h.id),E.push(...s(d,C,u,[...g,l.toString()],b,p)),p.delete(h.id)))}):E.push({message:`Nested schema '${h.id}' not found`,path:g})}}if(S.type==="object"){let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?typeof $=="object"&&$!==null&&(p.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:g}):(p.add(h.id),E.push(...s($,C,u,g,b,p)),h.constraints?.forEach((d,l)=>{if("rules"in d)E.push(...a(d,$,u,[...g,`constraints[${l}]`],p));else{let w=u[d.predicate];w?w({data:$,field:void 0,arguments:d.parameters})||E.push({message:d.errorMessage||`Constraint '${d.name}' failed with params ${Z(d.parameters)}`,path:[...g,`constraints[${l}]`]}):E.push({message:`Predicate '${d.predicate}' not found`,path:[...g,`constraints[${l}]`]})}}),p.delete(h.id))):E.push({message:`Nested schema '${h.id}' not found`,path:g})}}if(S.type==="union"){let h=S.schema;!h||!Array.isArray(h)?E.push({message:"Union type requires an array of schema references",path:g}):h.some(d=>{let l=b[d.id];return l?s($,l,u,g,b,new Set(p)).length===0:(E.push({message:`Nested schema '${d.id}' not found`,path:g}),!1)})||E.push({message:"Value does not match any union schema",path:g})}S.constraints?.forEach((h,C)=>{if("rules"in h)E.push(...a(h,o,u,[...g,`constraints[${C}]`],p));else{let d=u[h.predicate];d?d({data:o,field:S.name,arguments:h.parameters})||E.push({message:h.errorMessage||`Constraint '${h.name}' failed for field '${S.name}' with params ${Z(h.parameters)}`,path:[...g,`constraints[${C}]`]}):E.push({message:`Predicate '${h.predicate}' not found`,path:[...g,`constraints[${C}]`]})}})}});for(let y in o)Object.hasOwnProperty.call(o,y)&&!m.has(y)&&E.push({message:`Unexpected field '${y}'`,path:[...f,y]});return c.constraints?.forEach((y,S)=>{if("rules"in y)E.push(...a(y,o,u,[...f,`constraints[${S}]`],p));else{let g=u[y.predicate];if(!g)E.push({message:`Predicate '${y.predicate}' not found`,path:[...f,`constraints[${S}]`]});else if(!g({data:o,field:y.field,arguments:y.parameters})){let h=y.field?` for field '${y.field}'`:"";E.push({message:y.errorMessage||`Constraint '${y.name}' failed${h} with params ${Z(y.parameters)}`,path:[...f,`constraints[${S}]`]})}}}),E}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,t,e,[],t.nestedSchemas||{});return u.length>0?i(u):n(c)},types:{input:{},output:{}}}}}function yt(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(r=>{if(!r.path)return;let a=r.path,s=i;for(let o=0;o<a.length;o++){let c=a[o];o===a.length-1?s[c]={type:"validation",message:r.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var L=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var le=t=>({value:t}),_=t=>({issues:t}),x=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],xe=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Ke=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Te=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},z=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],We=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string")||t instanceof RegExp||typeof t=="object"&&t!==null&&"field"in t&&typeof t.field=="string")return[];break;case"number":if(typeof t=="number"||Array.isArray(t)&&t.every(i=>typeof i=="number")||typeof t=="object"&&t!==null&&"precision"in t&&typeof t.precision=="number")return[];break;case"boolean":if(typeof t=="boolean")return[];break;case"array":case"set":if(typeof t=="number"||typeof t=="object"&&t!==null&&"minItems"in t&&typeof t.minItems=="number")return[];break;case"enum":if(Array.isArray(t)&&t.length>0&&t.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"union":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[n]}]},me=(t,e)=>{let n=[],i=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...x(t.predicate,`${e}.predicate`)),t.type!==void 0&&t.type!=="schema"&&n.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),t.field!==void 0&&typeof t.field!="string"&&n.push({message:"Field must be a string",path:[`${e}.field`]}),t.parameters!==void 0&&(!t.type||t.type!=="schema")&&n.push(...We(t.parameters,"dynamic",`${e}.parameters`)),n.push(...x(t.description,`${e}.description`,!1)),n.push(...x(t.errorMessage,`${e}.errorMessage`,!1)),n},he=(t,e)=>{let n=[],i=["name","operator","rules"],r=["name","operator","rules"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...Te(t.operator,`${e}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?n.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):t.rules.forEach((s,o)=>{"rules"in s?n.push(...he(s,`${e}.rules[${o}]`)):n.push(...me(s,`${e}.rules[${o}]`))}),n},q=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>{"rules"in i?n.push(...he(i,`${e}[${r}]`)):n.push(...me(i,`${e}[${r}]`))}),n},Ce=(t,e)=>{let n=[],i=["operator","field"],r=["operator","field","value","conditions"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Te(t.operator,`${e}.operator`)),n.push(...x(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...Ce(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},ke=(t,e)=>{let n=[],i=["fields","type","name"],r=["fields","type","unique","partial","description","order","name"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...Ke(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...z(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...Ce(t.partial,`${e}.partial`)),n.push(...x(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},G=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>n.push(...ke(i,`${e}[${r}]`))),n},Ye=(t,e,n,i,r)=>{let a=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&a.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;a.push(...x(s.id,`${c}.id`)),i.includes(s.id)||a.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&a.push(...q(s.constraints,`${c}.constraints`)),s.indexes&&a.push(...G(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&r==="object")&&!Array.isArray(t)?(a.push(...x(t.id,`${e}.id`)),i.includes(t.id)||a.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&a.push(...q(t.constraints,`${e}.constraints`)),t.indexes&&a.push(...G(t.indexes,`${e}.indexes`))):a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),a)},X=(t,e,n)=>{let i=[],r=["name","type"],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=t;if(r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...xe(t.type,`${e}.type`)),i.push(...z(t.required,`${e}.required`,!1)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...Ye(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...xe(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],u=t.nestedSchema;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.nestedSchema.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${f}`]})}),i.push(...x(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...q(t.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...G(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...z(t.deprecated,`${e}.deprecated`,!1)),t.reference){let o=["schema","field"],c=["schema","field"],u=t.reference;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.reference.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.reference.${f}`]})}),i.push(...x(t.reference.schema,`${e}.reference.schema`)),i.push(...x(t.reference.field,`${e}.reference.field`))}return i.push(...x(t.description,`${e}.description`,!1)),i.push(...z(t.unique,`${e}.unique`,!1)),i},Re=(t,e,n)=>{let i=[],r=["name","fields"],a=["name","description","concrete","fields","indexes","constraints","metadata"],s=t;return r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...z(t.concrete,`${e}.concrete`,!1)),Array.isArray(t.fields)?(t.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),t.fields.forEach((o,c)=>{let u=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[u]});else{let f=o.fields;typeof f!="object"||f===null?i.push({message:"Fields must be a non-empty object",path:[`${u}.fields`]}):Object.entries(f).forEach(([b,p])=>{i.push(...X(p,`${u}.fields.${b}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${u}.when`]})}})):typeof t.fields=="object"&&t.fields!==null?Object.entries(t.fields).forEach(([o,c])=>{i.push(...X(c,`${e}.fields.${o}`,n))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...x(t.description,`${e}.description`,!1)),t.indexes&&i.push(...G(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},Qe=t=>{if(typeof t!="object"||t===null)return _([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields","nestedSchemas"],r=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],a=e;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[s]})}),n.push(...x(e.name,"name")),n.push(...x(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...X(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(...Re(c,`nestedSchemas.${o}`,s)))}return n.push(...x(e.description,"description",!1)),e.indexes&&n.push(...G(e.indexes,"indexes")),e.constraints&&n.push(...q(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...Ae(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),n.length>0?_(n):le(e)},fe=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...X(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],r=["type","id","changes","nestedSchemaChanges"],a=t;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...x(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...q(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...G(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...ke(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...he(t.constraint,`${e}.constraint`)):n.push(...me(t.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...Re(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},Ze=(t,e)=>{let n=[],i=["forward","backward"],r=i,a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},Ae=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],r=[...i,"rollback","dependencies"],a=t;i.forEach(o=>{a[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(a).forEach(o=>{r.includes(o)||n.push({message:"Unknown property",path:[`${e}.${o}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...x(t.schemaVersion,`${e}.schemaVersion`)),n.push(...x(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>n.push(...fe(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...fe(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...x(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...Ze(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...x(t.createdAt,`${e}.createdAt`)),t.dependencies!==void 0&&(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),n.push(...x(t.checksum,`${e}.checksum`)),n},De={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:Qe,types:{input:{},output:{}}}};var Ie={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return _([{message:"Migration must be an object",path:[]}]);let e=t,n=Ae(e,"");return n.length>0?_(n):le(e)},types:{input:{},output:{}}}},Pe={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return _([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,r)=>n.push(...fe(i,`[${r}]`))),n.length>0?_(n):le(e)},types:{input:[],output:[]}}};function Fe(t){try{return!Ie["~standard"].validate(t).issues}catch(e){throw new L("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function Oe(t){try{return!Pe["~standard"].validate(t).issues}catch(e){throw new L("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function B(t){try{return!De["~standard"].validate(t).issues}catch(e){throw new L("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var vt=B;var J=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function Xe(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function et(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function tt(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function nt(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function it(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function st(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return it(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=et(e,n);return i?nt(e.parameters,t.parameters,i):!0}return!1}function rt(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return tt(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return st(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function at(t){let e=new Set,n=new Set,i=new Set,r=new Set;for(let a of t)switch(a.type){case"addField":if(n.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);i.add(a.id);break;case"removeField":if(i.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case"modifyField":if(n.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);e.add(a.id);break;case"deprecateField":if(n.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);r.add(a.id);break}}function ot(t){let e=new Set,n=new Set,i=new Set;for(let r of t)switch(r.type){case"addConstraint":let a=r.constraint,s=("name"in a,a.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(r.name))throw new Error(`Cannot remove newly added constraint: ${r.name}`);if(e.has(r.name))throw new Error(`Cannot remove modified constraint: ${r.name}`);n.add(r.name);break;case"modifyConstraint":if(n.has(r.name))throw new Error(`Cannot modify removed constraint: ${r.name}`);if(i.has(r.name))throw new Error(`Cannot modify newly added constraint: ${r.name}`);e.add(r.name);break}}function Me(t,e,n){if(e.length===0)throw new Error("No changes provided");at(e),ot(e);let i=Xe(t),r="patch";for(let a of e){let s=rt(a,n);if(s==="major"){r="major";break}else s==="minor"&&r==="patch"&&(r="minor")}switch(r){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 j(t,e){let n=u=>u.split(".").map(f=>parseInt(f,10)||0),[i,r,a]=n(t),[s,o,c]=n(e);return i-s||r-o||a-c}function Tt(t){return t.sort(j)}var R=class extends Error{constructor(n,i,r,a){super(n);this.code=i;this.migrationId=r;this.cause=a;this.name="MigrationError"}},ct=(p=>(p.INVALID_SCHEMA="INVALID_SCHEMA",p.INVALID_MIGRATION="INVALID_MIGRATION",p.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",p.TIMEOUT="TIMEOUT",p.MEMORY_LIMIT="MEMORY_LIMIT",p.CONCURRENT_OPERATION="CONCURRENT_OPERATION",p.TRANSFORM_ERROR="TRANSFORM_ERROR",p.VERSION_NOT_FOUND="VERSION_NOT_FOUND",p.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",p.STREAM_ERROR="STREAM_ERROR",p.ROLLBACK_ERROR="ROLLBACK_ERROR",p.MISSING_TRANSFORM="MISSING_TRANSFORM",p))(ct||{}),je=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!B(e))throw new R("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(r=>Fe(r)))throw new R("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((r,a)=>j(r.schemaVersion,a.schemaVersion))}i&&(this.history=i.sort((r,a)=>j(r.version,a.version)))}catch(r){throw r instanceof R?r:new R("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,r)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await J(n)}catch(n){throw new R("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new R("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Oe(i))}catch(i){throw new R("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(n,i),s=a.reduce((c,u)=>{let f=n==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,f,u.id)},r),o=await t.processMigrationList(e,n,a);return{newSchema:s,dataPreview:o}}catch(r){throw r instanceof R?r:new R("Dry run failed","INVALID_SCHEMA",void 0,r)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let r=e==="forward"?"pending":"applied",a=n?j(i.schemaVersion,n)>=0:!0;return i.status===r&&a}).sort((i,r)=>e==="forward"?i.id.localeCompare(r.id):r.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let r=Me(e.version,n);return n.map(s=>{try{return Se(s,e)}catch(o){throw new R("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ce(s,o)}catch(c){throw new R("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:r})}catch(r){throw r instanceof R?r:new R("Schema update failed","INVALID_SCHEMA",i,r)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new R("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new R("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new R("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 r=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),a=this.history.length-i;if(a<0)return n;for(let o=0;o<a;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",r);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new R(`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,f){try{let b=await c(u);f.enqueue(b)}catch(b){f.error(new R(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,b))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new R(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let r=await i.text();if(typeof window<"u"){let a=new Blob([r],{type:"application/javascript"});return(await import(URL.createObjectURL(a))).default[n]}else{let{runInNewContext:a}=await import("vm"),s={module:{exports:{}},console};return a(r,s,e),s.module.exports[n]}}catch(i){throw new R(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new R(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,r)=>this.applySchemaChanges(i,[r]),this.currentSchema)}catch(n){throw n instanceof R?n:new R("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var dt=t=>{let e=[],n=[];return{addField:(i,r)=>{e.push({type:"addField",id:i,definition:r}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let r=t.fields[i];r&&n.push({type:"addField",id:i,definition:r})},modifyField:(i,r)=>{e.push({type:"modifyField",id:i,changes:r});let a=t.fields[i];a&&n.push({type:"modifyField",id:i,changes:a})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let r=t.indexes?.find(a=>a.name===i);r&&n.push({type:"addIndex",definition:r})},modifyIndex:(i,r)=>{e.push({type:"modifyIndex",name:i,changes:r});let a=t.indexes?.find(s=>s.name===i);a&&n.push({type:"modifyIndex",name:i,changes:a})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let r=t.constraints?.find(a=>"name"in a&&a.name===i);r&&n.push({type:"addConstraint",constraint:r})},modifyConstraint:(i,r)=>{e.push({type:"modifyConstraint",name:i,changes:r});let a=t.constraints?.find(s=>"name"in s&&s.name===i);a&&n.push({type:"modifyConstraint",name:i,changes:a})},addNestedSchema:(i,r)=>{e.push({type:"addNestedSchema",id:i,definition:r}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let r=t.nestedSchemas[i];r&&n.push({type:"addNestedSchema",id:i,definition:r})},modifyNestedSchema:(i,r)=>{e.push({type:"modifyNestedSchema",id:i,changes:r});let a=t.nestedSchemas[i];a&&n.push({type:"modifyNestedSchema",id:i,changes:a})},changes:()=>({migrate:e,rollback:n})}};import"@isomorphic-git/lightning-fs";import D from"isomorphic-git";import ne from"isomorphic-git/http/web";import ft from"@isomorphic-git/lightning-fs";function Ne(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function Ve(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function pe(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),r=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),a,s;return n?(a=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(a=i[1],s=i[2].trim()):r?(a=r[2],s=r[3].trim()):(a=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:a,body:s,type:n?"arrow":i?"function":r?"method":"unknown"})}function ye(t){let{params:e,body:n,type:i}=JSON.parse(t),r=new Function(e,n);return i==="arrow"&&Object.defineProperty(r,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),r}function Xt(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(r=>{n[r.name]={label:r.label,description:r.description}}),ge(t.fields,"",t.nestedSchemas||{},e,!0);let i=[];for(let[r,a]of Object.entries(e)){let s=r!=="ungrouped"?n[r]:void 0;i.push({name:r!=="ungrouped"?r:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:a})}return i}function ge(t,e,n,i,r,a){if(Array.isArray(t))t.forEach(s=>{let o=s.when?e?`${e}.${s.when?.field}`:s.when?.field:void 0;ge(s.fields,e,n,i,r,o?{[o]:s.when?.value}:void 0)});else for(let[s,o]of Object.entries(t)){if(o.hint?.input.ignore)continue;let c=e?`${e}.${o.name}`:o.name,f=o.required===!0&&r,b={...o,name:c,required:f};if(a&&(b.when=a),o.type!=="object"){let p=o.hint?.input?.group||"ungrouped";i[p]||(i[p]=[]),i[p].push(b)}if(o.schema&&"id"in o.schema&&n[o.schema.id]){let p=n[o.schema.id];ge(p.fields,c,n,i,f,a)}}}function en(t,e){let n={},i=t.nestedSchemas||{};for(let[r,a]of Object.entries(t.fields))n[r]=ee(a,i,e);return n}function ee(t,e,n){if("default"in t&&t.default!==void 0)return t.default;if(n?.resolver){let i=n.resolver(t);if(i!==void 0)return i}switch(t.type){case"string":return"";case"number":return 0;case"boolean":return!1;case"array":return[];case"set":return[];case"enum":if(!t.values||t.values.length===0)throw new Error(`Enum field "${t.name}" requires non-empty values array`);return t.values[0];case"object":if(!t.schema||!("id"in t.schema)||!e[t.schema.id])throw new Error(`Object field "${t.name}" references invalid nested schema`);return qe(e[t.schema.id],e,n);case"record":return{};case"union":if(!t.schema||!Array.isArray(t.schema)||t.schema.length===0)throw new Error(`Union field "${t.name}" requires non-empty schema array`);let i=n?.discriminator?.[t.name],r=t.schema[0];if(i!==void 0)for(let a of t.schema){let o=e[a.id].fields;if(ut(o,i)){r=a;break}}return qe(e[r.id],e,n);case"dynamic":return{};default:throw new Error(`Unsupported field type "${t.type}" for field "${t.name}"`)}}function ut(t,e){if(Array.isArray(t)){for(let n of t)for(let i of Object.values(n.fields))if(i.type==="enum"&&i.values?.includes(e)||i.default===e)return i}else for(let n of Object.values(t))if(n.type==="enum"&&n.values?.includes(e)||n.default===e)return n}function qe(t,e,n){let i={},r=n?.discriminator||{};if(Array.isArray(t.fields)){let a=t.fields.filter(o=>!o.when);for(let o of a)for(let[c,u]of Object.entries(o.fields))i[c]=ee(u,e,n);let s=t.fields.filter(o=>o.when);for(let o of s){let c=o.when.field,u=o.when.value;if(r[c]===u)for(let[b,p]of Object.entries(o.fields))i[b]=ee(p,e,n)}}else for(let[a,s]of Object.entries(t.fields))i[a]=ee(s,e,n);return i}import{Buffer as lt}from"buffer";window.Buffer=lt;var te=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new ft(`${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||!B(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,r=await this.processAndStoreMigrations(i,e),a=this.serializeSchema(e);await this.writeSchemaFile(i,a);let s=await J(a);await this.updateIndex(i,e,s,r,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let r=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(r))return null;let a=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(r,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(a.migrations=await this.migrations({name:e,version:n})),a)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let r=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await J(r)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),r=n||i.version,a=[];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")));j(u.schemaVersion,r)<=0&&a.push(this.deserializeMigration(u))}}return a.sort((s,o)=>j(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async r=>({...i,version:r.version,description:r.description,migrations:await this.migrations({name:e,version:r.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let r={...i};if(i.transform?.forward){let o=i.transform;r.transform={forward:pe(o.forward),backward:pe(o.backward||(c=>c))}}let a=JSON.stringify(r),s=await J(a);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,a,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ne(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ve(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ye(e.transform.forward),backward:ye(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,r,a){let s=`${e}/index.json`,o=a==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(a==="create"?"Initial version":"Updated version"),migrations:r.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,r.forEach(({id:c,hash:u,checksum:f})=>{o.migrations[c]={hash:u,checksum:f}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let r=`${e}/${i}`;(await this.fsp.stat(r)).isDirectory()?await this.rmdirRecursive(r):await this.fsp.unlink(r)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let r of i){let a=`${e}/${r}`;(await this.fsp.stat(a)).isDirectory()?n.push(...await this.listFilesRecursive(a)):n.push(a)}return n}};var we=class{locks=new Map;async acquire(e){let n,i=new Promise(a=>{n=a}),r=this.locks.get(e)||Promise.resolve();return this.locks.set(e,r.then(()=>i)),await r,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},$e=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function ie(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function se(t,e,n,i,r){await i.init(),await D.init({fs:t,dir:e,defaultBranch:n}),await D.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await D.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await D.add({fs:t,dir:e,filepath:"."}),await D.commit({fs:t,dir:e,message:"chore: initial commit",author:r})}async function $n(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,r=e.createRemote??!1,a=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new te(t),u=c.fs,f=t.startsWith("/")?t:`/${t}`,b=new we,p=new $e(e.cacheTtl);async function E(d,l){let w=o;do{let v=s[o];try{return await d(v)}catch(A){if(console.warn(`Failed with proxy ${v}: ${A.message}`),o=(o+1)%s.length,o===w)throw new Error(`${l}: All CORS proxies failed`)}}while(!0)}async function T(d,l="."){return ie(async()=>(await D.add({fs:u,dir:f,filepath:l}),(await D.statusMatrix({fs:u,dir:f})).some(([v,A,k])=>A!==k)?await D.commit({fs:u,dir:f,message:d,author:a}):null),"Failed to commit changes")}async function m(d,l,w){return ie(async()=>{if(await y(d))throw new Error(`Tag ${d} already exists`);await D.annotatedTag({fs:u,dir:f,ref:d,message:l,tagger:a,object:w})},`Failed to create tag ${d}`)}async function y(d){try{return(await D.listTags({fs:u,dir:f})).includes(d)}catch{return!1}}async function S(d){return(await D.listTags({fs:u,dir:f})).filter(v=>v.startsWith(d))}async function g(d){return ie(async()=>{let w=(await D.listTags({fs:u,dir:f})).filter(v=>v.startsWith(d));for(let v of w)await D.deleteTag({fs:u,dir:f,ref:v});return w},`Failed to delete tags with prefix ${d}`)}async function $(d){return ie(async()=>{await D.checkout({fs:u,dir:f,ref:d})},`Failed to checkout ${d}`)}async function h(d,{delete:l=!1,force:w=!1}={}){i&&await E(async v=>{await D.push({fs:u,http:ne,dir:f,ref:d,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:v,delete:l,force:w})},`Failed to push ${d}`)}async function C(d,l=!0){i&&await E(async w=>{try{await D.pull({fs:u,http:ne,dir:f,ref:d,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(v){if(!l)console.warn(`Fast-forward pull failed for ${d}, attempting regular pull`),await D.pull({fs:u,http:ne,dir:f,ref:d,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw v}},`Failed to pull ${d}`)}if(i&&!await c.fileExists(f)){let d=f.slice(1);if(await i.exists({name:d}).catch(()=>!1))await E(async w=>{await D.clone({fs:u,http:ne,dir:f,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(r)try{i=await i.create({name:d,private:!0}),await se(u,f,n,c,a),await D.addRemote({fs:u,dir:f,remote:"origin",url:i.url()}),await h(n)}catch(w){console.error("Failed to create and push to remote repository:",w),await se(u,f,n,c,a)}else await se(u,f,n,c,a)}else await se(u,f,n,c,a);return{async init(){return b.withLock("init",()=>c.init())},async create(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await $(n),await c.create(d);let v=await T(`feat: create schema ${l}`);v&&await m(`${l}-${w}`,`Version ${w}`,v),p.invalidate(l)})},async update(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await $(n),await c.update(d);let v=await T(`fix: update schema ${l}`);v&&await m(`${l}-${w}`,`Version ${w}`,v),p.invalidate(l)})},async delete(d){let{name:l}=d;return b.withLock(`schema:${l}`,async()=>{await $(n),await D.remove({fs:u,dir:f,filepath:l}),await c.delete(d);let w=await T(`chore: delete schema ${l}`),v=await S(`${l}-`);if(i&&w){await h(n);for(let A of v)await h(A,{delete:!0,force:!0}).catch(k=>console.warn(`Failed to delete remote tag ${A}: ${k.message}`))}await g(`${l}-`),p.invalidate(l)})},async list(){return b.withLock("list",()=>c.list())},async schema(d){let{name:l,version:w}=d,v=`${l}-${w||"latest"}-${d.migrations||!1}`,A=p.get(v);return A||b.withLock(`schema:${l}`,async()=>{if(w){let I=`${l}-${w}`;if(await y(I))await $(I);else throw new Error(`Version ${w} of schema ${l} not found`)}else await $(n);let k=await c.schema(d);return p.set(v,k),k})},async stats(d){return b.withLock("stats",()=>c.stats(d))},async sync(){return b.withLock("sync",async()=>{if(await $(n),await c.sync(),await T("chore: sync local changes"),i){await C(n,!1),await h(n);let d=await D.listTags({fs:u,dir:f});for(let w of d)await h(w,{force:!0});let l=await D.listTags({fs:u,dir:f});for(let w of l)d.includes(w)||await h(w,{delete:!0})}p.invalidate()})},async migrations(d){let{name:l,version:w}=d,v=`migrations-${l}-${w||"latest"}`,A=p.get(v);return A||b.withLock(`migrations:${l}`,async()=>{if(w){let I=`${l}-${w}`;if(await y(I))await $(I);else throw new Error(`Version ${w} of schema ${l} not found`)}else await $(n);let k=await c.migrations(d);return p.set(v,k),k})},async history(d){let{name:l}=d,w=`history-${l}`,v=p.get(w);return v||b.withLock(`history:${l}`,async()=>{await $(n);let A=await c.history(d);return p.set(w,A),A})}}}function O(t){return"predicate"in t}function Tn(t,e=!0,n=!0){let i="",r=n?"export ":"",a=new Map,s=new Map,o=(T,m=[])=>{if(!e||!T&&!m.length)return"";let y=T?[T]:[];return m.forEach(S=>y.push(S)),`/**
2
+ * ${y.join(`
3
3
  * `)}
4
4
  */
5
- `},c=T=>T.charAt(0).toUpperCase()+T.slice(1),d=(T,m)=>{let p=s.get(m)||new Map;for(let[S,y]of Object.entries(T))if(y.type==="enum"&&Array.isArray(y.values)){let w=`${m}${c(y.name)}`,h=y.values.map(C=>String(C));a.set(w,h)}else if(y.type==="string"&&y.constraints){let w=y.constraints.find(h=>O(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if(w&&O(w)&&Array.isArray(w.parameters)){let h=`${m}${c(y.name)}`,C=w.parameters.map(u=>String(u));a.set(h,C)}}else if(y.type==="record"){let w=`${m}${c(y.name)}`;p.set(y.name,w)}p.size>0&&s.set(m,p)};d(t.fields,t.name);for(let[T,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(p=>d(p.fields,c(m.name))):d(m.fields,c(m.name));for(let[T,m]of a){i+=o(`Union type for ${T.toLowerCase()} field values`);let p=m.map(S=>`"${S}"`).join(" | ");i+=`${r}type ${T} = ${p};
5
+ `},c=T=>T.charAt(0).toUpperCase()+T.slice(1),u=(T,m)=>{let y=s.get(m)||new Map;for(let[S,g]of Object.entries(T))if(g.type==="enum"&&Array.isArray(g.values)){let $=`${m}${c(g.name)}`,h=g.values.map(C=>String(C));a.set($,h)}else if(g.type==="string"&&g.constraints){let $=g.constraints.find(h=>O(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if($&&O($)&&Array.isArray($.parameters)){let h=`${m}${c(g.name)}`,C=$.parameters.map(d=>String(d));a.set(h,C)}}else if(g.type==="record"){let $=`${m}${c(g.name)}`;y.set(g.name,$)}y.size>0&&s.set(m,y)};u(t.fields,t.name);for(let[T,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(y=>u(y.fields,c(m.name))):u(m.fields,c(m.name));for(let[T,m]of a){i+=o(`Union type for ${T.toLowerCase()} field values`);let y=m.map(S=>`"${S}"`).join(" | ");i+=`${r}type ${T} = ${y};
6
6
 
7
- `}for(let[T,m]of Object.entries(t.nestedSchemas||{})){let p=c(m.name),S=m.constraints?.map(C=>O(C)?`@constraint ${C.name}: ${C.description||C.predicate}`:`@constraint ${C.name}`)||[];m.concrete&&S.push("@concrete Indicates a concrete schema"),i+=o(m.description,S);let y=s.get(p)||new Map,w=Array.from(y.entries()).map(([C,u])=>`${u} extends Record<string, any> = Record<string, any>`).join(", "),h=y.size>0?`<${w}>`:"";if(Array.isArray(m.fields)){let C=m.fields.filter(v=>!v.when),u=m.fields.filter(v=>v.when),l="";if(C.length>0){l+=`{
7
+ `}for(let[T,m]of Object.entries(t.nestedSchemas||{})){let y=c(m.name),S=m.constraints?.map(C=>O(C)?`@constraint ${C.name}: ${C.description||C.predicate}`:`@constraint ${C.name}`)||[];m.concrete&&S.push("@concrete Indicates a concrete schema"),i+=o(m.description,S);let g=s.get(y)||new Map,$=Array.from(g.entries()).map(([C,d])=>`${d} extends Record<string, any> = Record<string, any>`).join(", "),h=g.size>0?`<${$}>`:"";if(Array.isArray(m.fields)){let C=m.fields.filter(v=>!v.when),d=m.fields.filter(v=>v.when),l="";if(C.length>0){l+=`{
8
8
  `;for(let v of C)for(let[A,k]of Object.entries(v.fields)){let I=k.constraints?.map(V=>O(V)?`@constraint ${V.name}: ${V.description||V.predicate}`:`@constraint ${V.name}`)||[];k.unique&&I.push("@unique Ensures unique values"),k.default!==void 0&&I.push(`@default ${JSON.stringify(k.default)}`),e&&k.description?l+=o(k.description,I):I.length&&(l+=o(void 0,I)),k.deprecated&&(l+=` /** @deprecated */
9
- `);let P=re(k,t,p,y),N=k.required===!1?"?":"";l+=` ${k.name}${N}: ${P};
10
- `}l+="}"}let g="";u.length>0&&(g=u.map(A=>{let k=`{
9
+ `);let P=re(k,t,y,g),N=k.required===!1?"?":"";l+=` ${k.name}${N}: ${P};
10
+ `}l+="}"}let w="";d.length>0&&(w=d.map(A=>{let k=`{
11
11
  `;for(let[I,P]of Object.entries(A.fields)){let N=P.constraints?.map(H=>O(H)?`@constraint ${H.name}: ${H.description||H.predicate}`:`@constraint ${H.name}`)||[];P.unique&&N.push("@unique Ensures unique values"),P.default!==void 0&&N.push(`@default ${JSON.stringify(P.default)}`),e&&P.description?k+=o(P.description,N):N.length&&(k+=o(void 0,N)),P.deprecated&&(k+=` /** @deprecated */
12
- `);let V=re(P,t,p,y),Ue=P.required===!1?"?":"";k+=` ${P.name}${Ue}: ${V};
12
+ `);let V=re(P,t,y,g),Ue=P.required===!1?"?":"";k+=` ${P.name}${Ue}: ${V};
13
13
  `}if(A.when)for(let[I,P]of Object.entries(A.when))k+=` ${I}: "${P}";
14
- `;return k+="}",k}).join(" | ")),l&&g?i+=`${r}type ${p}${h} = ${l} & (${g});
14
+ `;return k+="}",k}).join(" | ")),l&&w?i+=`${r}type ${y}${h} = ${l} & (${w});
15
15
 
16
- `:l?i+=`${r}type ${p}${h} = ${l};
16
+ `:l?i+=`${r}type ${y}${h} = ${l};
17
17
 
18
- `:g&&(i+=`${r}type ${p}${h} = ${g};
18
+ `:w&&(i+=`${r}type ${y}${h} = ${w};
19
19
 
20
- `)}else{i+=`${r}type ${p}${h} = {
21
- `;for(let[C,u]of Object.entries(m.fields)){let l=u.constraints?.map(A=>O(A)?`@constraint ${A.name}: ${A.description||A.predicate}`:`@constraint ${A.name}`)||[];u.unique&&l.push("@unique Ensures unique values"),u.default!==void 0&&l.push(`@default ${JSON.stringify(u.default)}`),e&&u.description?i+=o(u.description,l):l.length&&(i+=o(void 0,l)),u.deprecated&&(i+=` /** @deprecated */
22
- `);let g=re(u,t,p,y),v=u.required===!1?"?":"";i+=` ${u.name}${v}: ${g};
20
+ `)}else{i+=`${r}type ${y}${h} = {
21
+ `;for(let[C,d]of Object.entries(m.fields)){let l=d.constraints?.map(A=>O(A)?`@constraint ${A.name}: ${A.description||A.predicate}`:`@constraint ${A.name}`)||[];d.unique&&l.push("@unique Ensures unique values"),d.default!==void 0&&l.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?i+=o(d.description,l):l.length&&(i+=o(void 0,l)),d.deprecated&&(i+=` /** @deprecated */
22
+ `);let w=re(d,t,y,g),v=d.required===!1?"?":"";i+=` ${d.name}${v}: ${w};
23
23
  `}m.metadata&&(i+=` metadata: Record<string, any>;
24
24
  `),i+=`};
25
25
 
26
- `}if(m.indexes?.length){i+=o(`Available indexes for ${p}`),i+=`${r}enum ${p}IndexNames {
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${y}`),i+=`${r}enum ${y}IndexNames {
27
27
  `;for(let C of m.indexes)i+=` ${C.name} = "${C.name}",
28
28
  `;i+=`}
29
29
 
30
- `}}let f=t.constraints?.map(T=>O(T)?`@constraint ${T.name}: ${T.description||T.predicate}`:`@constraint ${T.name}`)||[];i+=o(t.description,f);let b=s.get(t.name)||new Map,$=Array.from(b.entries()).map(([T,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),E=b.size>0?`<${$}>`:"";i+=`${r}type ${t.name}${E} = {
31
- `;for(let[T,m]of Object.entries(t.fields)){let p=m.constraints?.map(w=>O(w)?`@constraint ${w.name}: ${w.description||w.predicate}`:`@constraint ${w.name}`)||[];m.unique&&p.push("@unique Ensures unique values"),m.default!==void 0&&p.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,p):p.length&&(i+=o(void 0,p)),m.deprecated&&(i+=` /** @deprecated */
32
- `);let S=re(m,t,t.name,b),y=m.required===!1?"?":"";i+=` ${m.name}${y}: ${S};
30
+ `}}let f=t.constraints?.map(T=>O(T)?`@constraint ${T.name}: ${T.description||T.predicate}`:`@constraint ${T.name}`)||[];i+=o(t.description,f);let b=s.get(t.name)||new Map,p=Array.from(b.entries()).map(([T,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),E=b.size>0?`<${p}>`:"";i+=`${r}type ${t.name}${E} = {
31
+ `;for(let[T,m]of Object.entries(t.fields)){let y=m.constraints?.map($=>O($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];m.unique&&y.push("@unique Ensures unique values"),m.default!==void 0&&y.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,y):y.length&&(i+=o(void 0,y)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let S=re(m,t,t.name,b),g=m.required===!1?"?":"";i+=` ${m.name}${g}: ${S};
33
33
  `}if(t.metadata&&(i+=` metadata: Record<string, any>;
34
34
  `),i+=`};
35
35
 
@@ -39,7 +39,7 @@ import{createEventBus as Wt}from"@asaidimu/events";import{createEventBus as Mt}f
39
39
  `}return i.trim()}function re(t,e,n,i){switch(t.type){case"string":if(t.constraints){let r=t.constraints.find(a=>O(a)&&(a.predicate==="enum"||a.predicate==="oneOf"));if(r&&O(r)&&Array.isArray(r.parameters))return`${n}${U(t.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id];return`${U(r.name)}[]`}return`${t.itemsType}[]`}return"any[]";case"set":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id];return`Set<${U(r.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${U(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id],a=U(r.name);return r.concrete?`string | ${a}`:a}if(t.nestedSchema){let r=e.nestedSchemas[t.nestedSchema.id],a=U(r.name);return r.concrete?`string | ${a}`:a}return t.reference?`${t.reference.schema}${t.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(t.name)||"Record<string, any>";case"union":return t.schema&&Array.isArray(t.schema)?t.schema.map(a=>{let s=e.nestedSchemas[a.id];return U(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function U(t){return t.charAt(0).toUpperCase()+t.slice(1)}function kn(t,e){let n=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,r=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
40
40
  ${s.conditions.map(c=>` ${r(c)}`).join(`
41
41
  `)}
42
- ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([d,f])=>{let b=`${c} ${d} (${f.type})
42
+ ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,f])=>{let b=`${c} ${u} (${f.type})
43
43
 
44
44
  `;return b+=`**Required:** ${f.required?"Yes":"No"}
45
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/anansi",
3
- "version": "1.6.3",
3
+ "version": "1.6.4",
4
4
  "description": "A toolkit for advanced data modelling",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",