@asaidimu/anansi 1.6.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/index.cjs +33 -48
  2. package/index.d.cts +250 -27
  3. package/index.d.ts +250 -27
  4. package/index.js +42 -57
  5. package/package.json +1 -1
package/index.cjs CHANGED
@@ -1,80 +1,65 @@
1
- "use strict";var He=Object.create;var W=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Ye=(t,e)=>{for(var n in e)W(t,n,{get:e[n],enumerable:!0})},xe=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Be(e))!We.call(t,a)&&a!==n&&W(t,a,{get:()=>e[a],enumerable:!(i=ze(e,a))||i.enumerable});return t};var J=(t,e,n)=>(n=t!=null?He(Ke(t)):{},xe(e||!t||!t.__esModule?W(n,"default",{value:t,enumerable:!0}):n,t)),Qe=t=>xe(W({},"__esModule",{value:!0}),t);var Dt={};Ye(Dt,{JsonPatchError:()=>A,MigrationEngine:()=>we,MigrationError:()=>C,MigrationErrorCode:()=>Ne,SchemaRegistry:()=>B,applyPatch:()=>ee,calculateNextVersion:()=>$e,compareSemanticVersions:()=>F,createGitSchemaRegistry:()=>Et,createPatch:()=>et,createSchemaMigrationHelper:()=>qe,createStandardSchemaValidator:()=>De,deepMerge:()=>fe,docgen:()=>Ct,extractInputFieldGroups:()=>kt,formResolver:()=>st,generateSHA256Hash:()=>V,generateValidationInterface:()=>Tt,normalizePath:()=>Te,schemaChangeToPatch:()=>de,schemaToTypes:()=>xt,serializeParams:()=>H,sortSemanticVars:()=>St,validate:()=>ut,validateMigration:()=>ye,validateSchemaChange:()=>ge,validateSchemaDefinition:()=>_});module.exports=Qe(Dt);var vt=require("@asaidimu/events");var bt=require("@asaidimu/events"),ne=require("@asaidimu/query");var A=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function Z(t){let e=Te(t);return e===""?[]:e.substring(1).split("/").map(Ze)}function Te(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(Q).join("/"):"/"+t.split(".").map(Q).join("/")}function Q(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Ze(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function X(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new A(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let a=i==="-"?n.length:parseInt(i);if(isNaN(a)||a<0||a>n.length)throw new A(`Invalid array index: ${i}`);n=n[a]}else{if(!n.hasOwnProperty(i))throw new A(`Property ${i} not found`);n=n[i]}}return n}function re(t,e){let n=M.get(e)||Z(e);if(M.set(e,n),n.length===0)return t;let i=X(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);if(isNaN(r)||r<0||r>=i.length)throw new A(`Invalid array index: ${a}`);return i[r]}return i[a]}function Xe(t,e,n){let i=M.get(e)||Z(e);M.set(e,i);let a=X(t,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(s=>s!==n)):a[r]===n&&delete a[r],t}function Y(t,e,n){let i=M.get(e)||Z(e);if(M.set(e,i),i.length===0)return n;let a=i.slice(0,-1),r=i[i.length-1],s=X(t,a);if(Array.isArray(s))if(r==="-")s.push(n);else{let o=parseInt(r);if(o<0||o>s.length)throw new A(`Invalid array index: ${r}`);s.splice(o,0,n)}else s[r]=n;return t}function oe(t,e){let n=M.get(e)||Z(e);if(M.set(e,n),n.length===0)return;let i=X(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);i.splice(r,1)}else delete i[a];return t}function ee(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=Y(n,i.path,i.value);break;case"remove":n=oe(n,i.path);break;case"removeValue":n=Xe(n,i.path,i.value);break;case"replace":n=Y(oe(n,i.path),i.path,i.value);break;case"copy":{let a=re(n,i.from);n=Y(n,i.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=re(n,i.from);n=Y(n,i.path,a),n=oe(n,i.from);break}case"test":{let a=re(n,i.path);if(JSON.stringify(a)!==JSON.stringify(i.value))throw new A("Test operation failed");break}default:throw new A(`Unsupported operation: ${i.op}`)}}catch(a){throw a instanceof A&&(a.operation=i),a}return n}function et(t,e){let n=[];return ce(t,e,"",n),n}function ce(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?tt(t,e,n,i):nt(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function tt(t,e,n,i){let a=Math.max(t.length,e.length);for(let r=0;r<a;r++){let s=`${n}/${r}`;r>=t.length?i.push({op:"add",path:`${n}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:s}):ce(t[r],e[r],s,i)}}function nt(t,e,n,i){let a=new Set,r=Object.keys(t),s=Object.keys(e);for(let o of r){let c=Q(o),u=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ce(t[o],e[o],u,i),a.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!a.has(o)){let c=Q(o),u=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function de(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([a,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?n.push({op:"replace",path:`${i}/${a}`,value:r}):n.push({op:"replace",path:`${i}/${a}`,value:r})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`/indexes/${i}/${a}`,value:r})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(a=>Array.isArray(a)?a.some(r=>r.name===t.name):a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=it(e,t.name);i&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`${i}/${a}`,value:r})});break}}return n}function it(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(Ce(i)){let a=ke(i.rules,e);if(a)return`/constraints/${n}${a}`}}return null}function Ce(t){return t&&"operator"in t&&"rules"in t}function ke(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(Ce(i)){let a=ke(i.rules,e);if(a)return`/rules/${n}${a}`}}return null}function fe(t,e){let n={...t};return ue(t)&&ue(e)&&Object.keys(e).forEach(i=>{ue(e[i])?i in t?n[i]=fe(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function ue(t){return t&&typeof t=="object"&&!Array.isArray(t)}function H(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function De(t,e){let n=o=>({value:o}),i=o=>({issues:o}),a=(o,c,u,l)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:u}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:u}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:u}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:u}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:u}]:[];case"enum":return l?.values?l.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(l.values)}, got ${o}`,path:u}]:[{message:"Enum type requires 'values' definition",path:u}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:u}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:u}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:u}]}};function r(o,c,u,l,x){let S=[],v=o.rules.map((g,k)=>{let $=[...l,`rules[${k}]`];if("rules"in g){if(x.has(g.name))return!0;x.add(g.name);let h=r(g,c,u,$,x);return S.push(...h),h.length===0}else{let h=u[g.predicate];if(!h)return S.push({message:`Predicate '${g.predicate}' not found`,path:$}),!1;let y=h({data:c,field:g.field,arguments:g.parameters});if(!y){let T=g.field?` for field '${g.field}'`:"";S.push({message:g.errorMessage||`Constraint '${g.name}' failed${T} with params ${H(g.parameters)}`,path:$})}return y}});return(()=>{switch(o.operator){case"and":return v.every(g=>g);case"or":return v.some(g=>g);case"not":return!v.every(g=>g);case"nor":return!v.some(g=>g);case"xor":return v.filter(g=>g).length===1}})()||S.push({message:`Constraint group '${o.name}' failed`,path:l}),S}function s(o,c,u,l,x,S=new Set,v){let m=[],g;if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))g=c.fields;else{let h=c.fields.find(y=>!y.when||v&&v[y.when.field]!==void 0&&v[y.when.field]===y.when.value);if(!h)return m.push({message:"No matching field set found for discriminated schema",path:l}),m;g=h.fields}else g=c.fields;let k=new Set(Object.values(g).map($=>$.name));Object.entries(g).forEach(([$,h])=>{let y=[...l,h.name],T=Object.hasOwnProperty.call(o,h.name)?o[h.name]:void 0;if(h.required&&T==null){m.push({message:`Field '${h.name}' is required`,path:y});return}if(T!==void 0){if(m.push(...a(T,h.type,y,h)),h.type==="array"||h.type==="set"){h.itemsType&&Array.isArray(T)&&T.forEach((f,d)=>m.push(...a(f,h.itemsType,[...y,d.toString()])));let b=h.schema||h.nestedSchema;if(b&&!Array.isArray(b)){let f=x[b.id];f?T.forEach((d,p)=>{typeof d=="object"&&d!==null&&(S.has(b.id)?m.push({message:`Circular reference detected at '${b.id}'`,path:[...y,p.toString()]}):(S.add(b.id),m.push(...s(d,f,u,[...y,p.toString()],x,S,o)),S.delete(b.id)))}):m.push({message:`Nested schema '${b.id}' not found`,path:y})}}if(h.type==="object"){let b=h.schema||h.nestedSchema;if(b&&!Array.isArray(b)){let f=x[b.id];f?typeof T=="object"&&T!==null&&(S.has(b.id)?m.push({message:`Circular reference detected at '${b.id}'`,path:y}):(S.add(b.id),m.push(...s(T,f,u,y,x,S,o)),b.constraints?.forEach((d,p)=>{if("rules"in d)m.push(...r(d,T,u,[...y,`constraints[${p}]`],S));else{let w=u[d.predicate];w?w({data:T,field:void 0,arguments:d.parameters})||m.push({message:d.errorMessage||`Constraint '${d.name}' failed with params ${H(d.parameters)}`,path:[...y,`constraints[${p}]`]}):m.push({message:`Predicate '${d.predicate}' not found`,path:[...y,`constraints[${p}]`]})}}),S.delete(b.id))):m.push({message:`Nested schema '${b.id}' not found`,path:y})}}if(h.type==="union"){let b=h.schema;!b||!Array.isArray(b)?m.push({message:"Union type requires an array of schema references",path:y}):b.some(d=>{let p=x[d.id];return p?s(T,p,u,y,x,new Set(S),o).length===0:(m.push({message:`Nested schema '${d.id}' not found`,path:y}),!1)})||m.push({message:"Value does not match any union schema",path:y})}h.constraints?.forEach((b,f)=>{if("rules"in b)m.push(...r(b,o,u,[...y,`constraints[${f}]`],S));else{let d=u[b.predicate];d?d({data:o,field:h.name,arguments:b.parameters})||m.push({message:b.errorMessage||`Constraint '${b.name}' failed for field '${h.name}' with params ${H(b.parameters)}`,path:[...y,`constraints[${f}]`]}):m.push({message:`Predicate '${b.predicate}' not found`,path:[...y,`constraints[${f}]`]})}})}});for(let $ in o)Object.hasOwnProperty.call(o,$)&&!k.has($)&&m.push({message:`Unexpected field '${$}'`,path:[...l,$]});return c.constraints?.forEach(($,h)=>{if("rules"in $)m.push(...r($,o,u,[...l,`constraints[${h}]`],S));else{let y=u[$.predicate];if(!y)m.push({message:`Predicate '${$.predicate}' not found`,path:[...l,`constraints[${h}]`]});else if(!y({data:o,field:$.field,arguments:$.parameters})){let b=$.field?` for field '${$.field}'`:"";m.push({message:$.errorMessage||`Constraint '${$.name}' failed${b} with params ${H($.parameters)}`,path:[...l,`constraints[${h}]`]})}}}),m}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,t,e,[],t.nestedSchemas||{});return u.length>0?i(u):n(c)},types:{input:{},output:{}}}}}function st(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(a=>{if(!a.path)return;let r=a.path,s=i;for(let o=0;o<r.length;o++){let c=r[o];o===r.length-1?s[c]={type:"validation",message:a.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var q=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var me=t=>({value:t}),L=t=>({issues:t}),E=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Ie=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},at=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Re=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},z=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],rt=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string")||t instanceof RegExp||typeof t=="object"&&t!==null&&"field"in t&&typeof t.field=="string")return[];break;case"number":if(typeof t=="number"||Array.isArray(t)&&t.every(i=>typeof i=="number")||typeof t=="object"&&t!==null&&"precision"in t&&typeof t.precision=="number")return[];break;case"boolean":if(typeof t=="boolean")return[];break;case"array":case"set":if(typeof t=="number"||typeof t=="object"&&t!==null&&"minItems"in t&&typeof t.minItems=="number")return[];break;case"enum":if(Array.isArray(t)&&t.length>0&&t.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"union":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[n]}]},he=(t,e)=>{let n=[],i=["predicate","name"],a=["type","predicate","field","parameters","name","description","errorMessage"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),n.push(...E(t.predicate,`${e}.predicate`)),t.type!==void 0&&t.type!=="schema"&&n.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),t.field!==void 0&&typeof t.field!="string"&&n.push({message:"Field must be a string",path:[`${e}.field`]}),t.parameters!==void 0&&(!t.type||t.type!=="schema")&&n.push(...rt(t.parameters,"dynamic",`${e}.parameters`)),n.push(...E(t.description,`${e}.description`,!1)),n.push(...E(t.errorMessage,`${e}.errorMessage`,!1)),n},pe=(t,e)=>{let n=[],i=["name","operator","rules"],a=["name","operator","rules"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),n.push(...Re(t.operator,`${e}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?n.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):t.rules.forEach((s,o)=>{"rules"in s?n.push(...pe(s,`${e}.rules[${o}]`)):n.push(...he(s,`${e}.rules[${o}]`))}),n},j=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,a)=>{"rules"in i?n.push(...pe(i,`${e}[${a}]`)):n.push(...he(i,`${e}[${a}]`))}),n},Ae=(t,e)=>{let n=[],i=["operator","field"],a=["operator","field","value","conditions"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Re(t.operator,`${e}.operator`)),n.push(...E(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...Ae(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},Pe=(t,e)=>{let n=[],i=["fields","type","name"],a=["fields","type","unique","partial","description","order","name"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),n.push(...at(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...z(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...Ae(t.partial,`${e}.partial`)),n.push(...E(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},U=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,a)=>n.push(...Pe(i,`${e}[${a}]`))),n},ot=(t,e,n,i,a)=>{let r=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&r.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;r.push(...E(s.id,`${c}.id`)),i.includes(s.id)||r.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&r.push(...j(s.constraints,`${c}.constraints`)),s.indexes&&r.push(...U(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&a==="object")&&!Array.isArray(t)?(r.push(...E(t.id,`${e}.id`)),i.includes(t.id)||r.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&r.push(...j(t.constraints,`${e}.constraints`)),t.indexes&&r.push(...U(t.indexes,`${e}.indexes`))):r.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),r)},te=(t,e,n)=>{let i=[],a=["name","type"],r=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=t;if(a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...E(t.name,`${e}.name`)),i.push(...Ie(t.type,`${e}.type`)),i.push(...z(t.required,`${e}.required`,!1)),t.constraints&&i.push(...j(t.constraints,`${e}.constraints`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...ot(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...Ie(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],u=t.nestedSchema;o.forEach(l=>{u[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.nestedSchema.${l}`]})}),Object.keys(u).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${l}`]})}),i.push(...E(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...j(t.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...U(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...z(t.deprecated,`${e}.deprecated`,!1)),t.reference){let o=["schema","field"],c=["schema","field"],u=t.reference;o.forEach(l=>{u[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.reference.${l}`]})}),Object.keys(u).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.reference.${l}`]})}),i.push(...E(t.reference.schema,`${e}.reference.schema`)),i.push(...E(t.reference.field,`${e}.reference.field`))}return i.push(...E(t.description,`${e}.description`,!1)),i.push(...z(t.unique,`${e}.unique`,!1)),i},Fe=(t,e,n)=>{let i=[],a=["name","fields"],r=["name","description","concrete","fields","indexes","constraints","metadata"],s=t;return a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...E(t.name,`${e}.name`)),i.push(...z(t.concrete,`${e}.concrete`,!1)),Array.isArray(t.fields)?(t.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),t.fields.forEach((o,c)=>{let u=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[u]});else{let l=o.fields;typeof l!="object"||l===null?i.push({message:"Fields must be a non-empty object",path:[`${u}.fields`]}):Object.entries(l).forEach(([x,S])=>{i.push(...te(S,`${u}.fields.${x}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${u}.when`]})}})):typeof t.fields=="object"&&t.fields!==null?Object.entries(t.fields).forEach(([o,c])=>{i.push(...te(c,`${e}.fields.${o}`,n))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...E(t.description,`${e}.description`,!1)),t.indexes&&i.push(...U(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...j(t.constraints,`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},ct=t=>{if(typeof t!="object"||t===null)return L([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields","nestedSchemas"],a=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[s]})}),n.push(...E(e.name,"name")),n.push(...E(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...te(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(...Fe(c,`nestedSchemas.${o}`,s)))}return n.push(...E(e.description,"description",!1)),e.indexes&&n.push(...U(e.indexes,"indexes")),e.constraints&&n.push(...j(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...Me(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),n.length>0?L(n):me(e)},le=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),n.push(...te(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],a=["type","id","changes","nestedSchemaChanges"],r=t;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...E(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...j(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...U(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Pe(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...pe(t.constraint,`${e}.constraint`)):n.push(...he(t.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),n.push(...Fe(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...E(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},dt=(t,e)=>{let n=[],i=["forward","backward"],a=i,r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},Me=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],a=[...i,"rollback","dependencies"],r=t;i.forEach(o=>{r[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{a.includes(o)||n.push({message:"Unknown property",path:[`${e}.${o}`]})}),n.push(...E(t.id,`${e}.id`)),n.push(...E(t.schemaVersion,`${e}.schemaVersion`)),n.push(...E(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>n.push(...le(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...le(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...E(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...dt(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...E(t.createdAt,`${e}.createdAt`)),t.dependencies!==void 0&&(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),n.push(...E(t.checksum,`${e}.checksum`)),n},Oe={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:ct,types:{input:{},output:{}}}};var je={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return L([{message:"Migration must be an object",path:[]}]);let e=t,n=Me(e,"");return n.length>0?L(n):me(e)},types:{input:{},output:{}}}},Ve={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return L([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,a)=>n.push(...le(i,`[${a}]`))),n.length>0?L(n):me(e)},types:{input:[],output:[]}}};function ye(t){try{return!je["~standard"].validate(t).issues}catch(e){throw new q("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function ge(t){try{return!Ve["~standard"].validate(t).issues}catch(e){throw new q("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function _(t){try{return!Oe["~standard"].validate(t).issues}catch(e){throw new q("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var ut=_;var V=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function ft(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function lt(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function mt(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function ht(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function pt(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function yt(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return pt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=lt(e,n);return i?ht(e.parameters,t.parameters,i):!0}return!1}function gt(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return mt(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return yt(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function $t(t){let e=new Set,n=new Set,i=new Set,a=new Set;for(let r of t)switch(r.type){case"addField":if(n.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);n.add(r.id);break;case"modifyField":if(n.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(n.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);a.add(r.id);break}}function wt(t){let e=new Set,n=new Set,i=new Set;for(let a of t)switch(a.type){case"addConstraint":let r=a.constraint,s=("name"in r,r.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(e.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);n.add(a.name);break;case"modifyConstraint":if(n.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(i.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);e.add(a.name);break}}function $e(t,e,n){if(e.length===0)throw new Error("No changes provided");$t(e),wt(e);let i=ft(t),a="patch";for(let r of e){let s=gt(r,n);if(s==="major"){a="major";break}else s==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function F(t,e){let n=u=>u.split(".").map(l=>parseInt(l,10)||0),[i,a,r]=n(t),[s,o,c]=n(e);return i-s||a-o||r-c}function St(t){return t.sort(F)}var C=class extends Error{constructor(n,i,a,r){super(n);this.code=i;this.migrationId=a;this.cause=r;this.name="MigrationError"}},Ne=(S=>(S.INVALID_SCHEMA="INVALID_SCHEMA",S.INVALID_MIGRATION="INVALID_MIGRATION",S.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",S.TIMEOUT="TIMEOUT",S.MEMORY_LIMIT="MEMORY_LIMIT",S.CONCURRENT_OPERATION="CONCURRENT_OPERATION",S.TRANSFORM_ERROR="TRANSFORM_ERROR",S.VERSION_NOT_FOUND="VERSION_NOT_FOUND",S.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",S.STREAM_ERROR="STREAM_ERROR",S.ROLLBACK_ERROR="ROLLBACK_ERROR",S.MISSING_TRANSFORM="MISSING_TRANSFORM",S))(Ne||{}),we=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!_(e))throw new C("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(a=>ye(a)))throw new C("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((a,r)=>F(a.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((a,r)=>F(a.version,r.version)))}catch(a){throw a instanceof C?a:new C("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,a)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await V(n)}catch(n){throw new C("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new C("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>ge(i))}catch(i){throw new C("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},r=this.getRelevantMigrations(n,i),s=r.reduce((c,u)=>{let l=n==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,l,u.id)},a),o=await t.processMigrationList(e,n,r);return{newSchema:s,dataPreview:o}}catch(a){throw a instanceof C?a:new C("Dry run failed","INVALID_SCHEMA",void 0,a)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let a=e==="forward"?"pending":"applied",r=n?F(i.schemaVersion,n)>=0:!0;return i.status===a&&r}).sort((i,a)=>e==="forward"?i.id.localeCompare(a.id):a.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let a=$e(e.version,n);return n.map(s=>{try{return de(s,e)}catch(o){throw new C("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ee(s,o)}catch(c){throw new C("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:a})}catch(a){throw a instanceof C?a:new C("Schema update failed","INVALID_SCHEMA",i,a)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new C("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let a=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return n;for(let o=0;o<r;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",a);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new C(`Failed to resolve transform for migration ${s.id}`,"TRANSFORM_ERROR",s.id,o)}}))).filter(s=>!!s.transform).reduce((s,{migration:o,transform:c})=>s.pipeThrough(new TransformStream({async transform(u,l){try{let x=await c(u);l.enqueue(x)}catch(x){l.error(new C(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,x))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new C(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let a=await i.text();if(typeof window<"u"){let r=new Blob([a],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[n]}else{let{runInNewContext:r}=await import("vm"),s={module:{exports:{}},console};return r(a,s,e),s.module.exports[n]}}catch(i){throw new C(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new C(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,a)=>this.applySchemaChanges(i,[a]),this.currentSchema)}catch(n){throw n instanceof C?n:new C("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var qe=t=>{let e=[],n=[];return{addField:(i,a)=>{e.push({type:"addField",id:i,definition:a}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let a=t.fields[i];a&&n.push({type:"addField",id:i,definition:a})},modifyField:(i,a)=>{e.push({type:"modifyField",id:i,changes:a});let r=t.fields[i];r&&n.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let a=t.indexes?.find(r=>r.name===i);a&&n.push({type:"addIndex",definition:a})},modifyIndex:(i,a)=>{e.push({type:"modifyIndex",name:i,changes:a});let r=t.indexes?.find(s=>s.name===i);r&&n.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let a=t.constraints?.find(r=>"name"in r&&r.name===i);a&&n.push({type:"addConstraint",constraint:a})},modifyConstraint:(i,a)=>{e.push({type:"modifyConstraint",name:i,changes:a});let r=t.constraints?.find(s=>"name"in s&&s.name===i);r&&n.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,a)=>{e.push({type:"addNestedSchema",id:i,definition:a}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let a=t.nestedSchemas[i];a&&n.push({type:"addNestedSchema",id:i,definition:a})},modifyNestedSchema:(i,a)=>{e.push({type:"modifyNestedSchema",id:i,changes:a});let r=t.nestedSchemas[i];r&&n.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:n})}};var ln=require("@isomorphic-git/lightning-fs"),I=J(require("isomorphic-git"),1),K=J(require("isomorphic-git/http/web"),1);var _e=J(require("@isomorphic-git/lightning-fs"),1);function Le(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function Ue(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function Se(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),a=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,s;return n?(r=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(r=i[1],s=i[2].trim()):a?(r=a[2],s=a[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:s,type:n?"arrow":i?"function":a?"method":"unknown"})}function be(t){let{params:e,body:n,type:i}=JSON.parse(t),a=new Function(e,n);return i==="arrow"&&Object.defineProperty(a,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),a}var Ge=require("buffer");window.Buffer=Ge.Buffer;var B=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new _e.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!_(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,a=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let s=await V(r);await this.updateIndex(i,e,s,a,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let a=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(a))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(a,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(r.migrations=await this.migrations({name:e,version:n})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let a=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await V(a)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),a=n||i.version,r=[];for(let[s,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let u=JSON.parse(String(await this.fsp.readFile(c,"utf8")));F(u.schemaVersion,a)<=0&&r.push(this.deserializeMigration(u))}}return r.sort((s,o)=>F(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async a=>({...i,version:a.version,description:a.description,migrations:await this.migrations({name:e,version:a.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let a={...i};if(i.transform?.forward){let o=i.transform;a.transform={forward:Se(o.forward),backward:Se(o.backward||(c=>c))}}let r=JSON.stringify(a),s=await V(r);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,r,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Le(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ue(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:be(e.transform.forward),backward:be(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,a,r){let s=`${e}/index.json`,o=r==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(r==="create"?"Initial version":"Updated version"),migrations:a.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,a.forEach(({id:c,hash:u,checksum:l})=>{o.migrations[c]={hash:u,checksum:l}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let a=`${e}/${i}`;(await this.fsp.stat(a)).isDirectory()?await this.rmdirRecursive(a):await this.fsp.unlink(a)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let a of i){let r=`${e}/${a}`;(await this.fsp.stat(r)).isDirectory()?n.push(...await this.listFilesRecursive(r)):n.push(r)}return n}};var ve=class{locks=new Map;async acquire(e){let n,i=new Promise(r=>{n=r}),a=this.locks.get(e)||Promise.resolve();return this.locks.set(e,a.then(()=>i)),await a,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},Ee=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function ie(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function se(t,e,n,i,a){await i.init(),await I.default.init({fs:t,dir:e,defaultBranch:n}),await I.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await I.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await I.default.add({fs:t,dir:e,filepath:"."}),await I.default.commit({fs:t,dir:e,message:"chore: initial commit",author:a})}async function Et(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,a=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new B(t),u=c.fs,l=t.startsWith("/")?t:`/${t}`,x=new ve,S=new Ee(e.cacheTtl);async function v(f,d){let p=o;do{let w=s[o];try{return await f(w)}catch(D){if(console.warn(`Failed with proxy ${w}: ${D.message}`),o=(o+1)%s.length,o===p)throw new Error(`${d}: All CORS proxies failed`)}}while(!0)}async function m(f,d="."){return ie(async()=>(await I.default.add({fs:u,dir:l,filepath:d}),(await I.default.statusMatrix({fs:u,dir:l})).some(([w,D,R])=>D!==R)?await I.default.commit({fs:u,dir:l,message:f,author:r}):null),"Failed to commit changes")}async function g(f,d,p){return ie(async()=>{if(await k(f))throw new Error(`Tag ${f} already exists`);await I.default.annotatedTag({fs:u,dir:l,ref:f,message:d,tagger:r,object:p})},`Failed to create tag ${f}`)}async function k(f){try{return(await I.default.listTags({fs:u,dir:l})).includes(f)}catch{return!1}}async function $(f){return(await I.default.listTags({fs:u,dir:l})).filter(w=>w.startsWith(f))}async function h(f){return ie(async()=>{let p=(await I.default.listTags({fs:u,dir:l})).filter(w=>w.startsWith(f));for(let w of p)await I.default.deleteTag({fs:u,dir:l,ref:w});return p},`Failed to delete tags with prefix ${f}`)}async function y(f){return ie(async()=>{await I.default.checkout({fs:u,dir:l,ref:f})},`Failed to checkout ${f}`)}async function T(f,{delete:d=!1,force:p=!1}={}){i&&await v(async w=>{await I.default.push({fs:u,http:K.default,dir:l,ref:f,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,delete:d,force:p})},`Failed to push ${f}`)}async function b(f,d=!0){i&&await v(async p=>{try{await I.default.pull({fs:u,http:K.default,dir:l,ref:f,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:p,fastForwardOnly:!0})}catch(w){if(!d)console.warn(`Fast-forward pull failed for ${f}, attempting regular pull`),await I.default.pull({fs:u,http:K.default,dir:l,ref:f,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:p,fastForwardOnly:!1});else throw w}},`Failed to pull ${f}`)}if(i&&!await c.fileExists(l)){let f=l.slice(1);if(await i.exists({name:f}).catch(()=>!1))await v(async p=>{await I.default.clone({fs:u,http:K.default,dir:l,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:p})},"Failed to clone repository");else if(a)try{i=await i.create({name:f,private:!0}),await se(u,l,n,c,r),await I.default.addRemote({fs:u,dir:l,remote:"origin",url:i.url()}),await T(n)}catch(p){console.error("Failed to create and push to remote repository:",p),await se(u,l,n,c,r)}else await se(u,l,n,c,r)}else await se(u,l,n,c,r);return{async init(){return x.withLock("init",()=>c.init())},async create(f){let{name:d,version:p}=f.schema;return x.withLock(`schema:${d}`,async()=>{await y(n),await c.create(f);let w=await m(`feat: create schema ${d}`);w&&await g(`${d}-${p}`,`Version ${p}`,w),S.invalidate(d)})},async update(f){let{name:d,version:p}=f.schema;return x.withLock(`schema:${d}`,async()=>{await y(n),await c.update(f);let w=await m(`fix: update schema ${d}`);w&&await g(`${d}-${p}`,`Version ${p}`,w),S.invalidate(d)})},async delete(f){let{name:d}=f;return x.withLock(`schema:${d}`,async()=>{await y(n),await I.default.remove({fs:u,dir:l,filepath:d}),await c.delete(f);let p=await m(`chore: delete schema ${d}`),w=await $(`${d}-`);if(i&&p){await T(n);for(let D of w)await T(D,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${D}: ${R.message}`))}await h(`${d}-`),S.invalidate(d)})},async list(){return x.withLock("list",()=>c.list())},async schema(f){let{name:d,version:p}=f,w=`${d}-${p||"latest"}-${f.migrations||!1}`,D=S.get(w);return D||x.withLock(`schema:${d}`,async()=>{if(p){let O=`${d}-${p}`;if(await k(O))await y(O);else throw new Error(`Version ${p} of schema ${d} not found`)}else await y(n);let R=await c.schema(f);return S.set(w,R),R})},async stats(f){return x.withLock("stats",()=>c.stats(f))},async sync(){return x.withLock("sync",async()=>{if(await y(n),await c.sync(),await m("chore: sync local changes"),i){await b(n,!1),await T(n);let f=await I.default.listTags({fs:u,dir:l});for(let p of f)await T(p,{force:!0});let d=await I.default.listTags({fs:u,dir:l});for(let p of d)f.includes(p)||await T(p,{delete:!0})}S.invalidate()})},async migrations(f){let{name:d,version:p}=f,w=`migrations-${d}-${p||"latest"}`,D=S.get(w);return D||x.withLock(`migrations:${d}`,async()=>{if(p){let O=`${d}-${p}`;if(await k(O))await y(O);else throw new Error(`Version ${p} of schema ${d} not found`)}else await y(n);let R=await c.migrations(f);return S.set(w,R),R})},async history(f){let{name:d}=f,p=`history-${d}`,w=S.get(p);return w||x.withLock(`history:${d}`,async()=>{await y(n);let D=await c.history(f);return S.set(p,D),D})}}}function P(t){return"predicate"in t}function xt(t,e=!0,n=!0){let i="",a=n?"export ":"",r=new Map,s=new Map,o=(v,m=[])=>{if(!e||!v&&!m.length)return"";let g=v?[v]:[];return m.forEach(k=>g.push(k)),`/**
2
- * ${g.join(`
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})},De=(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)):{},De(e||!t||!t.__esModule?Z(n,"default",{value:t,enumerable:!0}):n,t)),it=t=>De(Z({},"__esModule",{value:!0}),t);var Mt={};nt(Mt,{JsonPatchError:()=>F,MigrationEngine:()=>Ee,MigrationError:()=>C,MigrationErrorCode:()=>Ge,SchemaRegistry:()=>Y,applyPatch:()=>ie,calculateNextVersion:()=>ve,compareSemanticVersions:()=>M,createGitSchemaRegistry:()=>Pt,createPatch:()=>at,createSchemaMigrationHelper:()=>Je,createStandardSchemaValidator:()=>Fe,deepMerge:()=>pe,docgen:()=>Ot,extractInputFieldGroups:()=>Dt,formResolver:()=>ut,generateSHA256Hash:()=>U,normalizePath:()=>Ae,schemaChangeToPatch:()=>me,schemaDefaults:()=>At,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=Ae(t);return e===""?[]:e.substring(1).split("/").map(st)}function Ae(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,l)=>{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 l?.values?l.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(l.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,l,v){let $=[],P=o.rules.map((m,T)=>{let E=[...l,`rules[${T}]`];if("rules"in m){if(v.has(m.name))return!0;v.add(m.name);let p=a(m,c,d,E,v);return $.push(...p),p.length===0}else{let p=d[m.predicate];if(!p)return $.push({message:`Predicate '${m.predicate}' not found`,path:E}),!1;let g=p({data:c,field:m.field,arguments:m.parameters});if(!g){let S=m.field?` for field '${m.field}'`:"";$.push({message:m.errorMessage||`Constraint '${m.name}' failed${S} with params ${K(m.parameters)}`,path:E})}return g}});return(()=>{switch(o.operator){case"and":return P.every(m=>m);case"or":return P.some(m=>m);case"not":return!P.every(m=>m);case"nor":return!P.some(m=>m);case"xor":return P.filter(m=>m).length===1}})()||$.push({message:`Constraint group '${o.name}' failed`,path:l}),$}function s(o,c,d,l,v,$=new Set,P){let y=[],m={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))m=c.fields;else{let E=c.fields,p=E.find(S=>!S.when);p&&Object.assign(m,p.fields);let g=E.find(S=>S.when&&o[S.when.field]!==void 0&&o[S.when.field]===S.when.value);if(g)Object.assign(m,g.fields);else if(!p)return y.push({message:"No matching field set found for discriminated schema",path:l}),y}else m=c.fields;let T=new Set(Object.values(m).map(E=>E.name));Object.entries(m).forEach(([E,p])=>{let g=[...l,p.name],S=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&S==null){y.push({message:`Field '${p.name}' is required`,path:g});return}if(S!==void 0){if(y.push(...r(S,p.type,g,p)),p.type==="array"||p.type==="set"){p.itemsType&&Array.isArray(S)&&S.forEach((u,f)=>y.push(...r(u,p.itemsType,[...g,f.toString()])));let w=p.schema||p.nestedSchema;if(w&&!Array.isArray(w)){let u=v[w.id];u?S.forEach((f,h)=>{typeof f=="object"&&f!==null&&($.has(w.id)?y.push({message:`Circular reference detected at '${w.id}'`,path:[...g,h.toString()]}):($.add(w.id),y.push(...s(f,u,d,[...g,h.toString()],v,$,o)),$.delete(w.id)))}):y.push({message:`Nested schema '${w.id}' not found`,path:g})}}if(p.type==="object"){let w=p.schema||p.nestedSchema;if(w&&!Array.isArray(w)){let u=v[w.id];u?typeof S=="object"&&S!==null&&($.has(w.id)?y.push({message:`Circular reference detected at '${w.id}'`,path:g}):($.add(w.id),y.push(...s(S,u,d,g,v,$,o)),w.constraints?.forEach((f,h)=>{if("rules"in f)y.push(...a(f,S,d,[...g,`constraints[${h}]`],$));else{let b=d[f.predicate];b?b({data:S,field:void 0,arguments:f.parameters})||y.push({message:f.errorMessage||`Constraint '${f.name}' failed with params ${K(f.parameters)}`,path:[...g,`constraints[${h}]`]}):y.push({message:`Predicate '${f.predicate}' not found`,path:[...g,`constraints[${h}]`]})}}),$.delete(w.id))):y.push({message:`Nested schema '${w.id}' not found`,path:g})}}if(p.type==="union"){let w=p.schema;!w||!Array.isArray(w)?y.push({message:"Union type requires an array of schema references",path:g}):w.some(f=>{let h=v[f.id];return h?s(S,h,d,g,v,new Set($),o).length===0:(y.push({message:`Nested schema '${f.id}' not found`,path:g}),!1)})||y.push({message:"Value does not match any union schema",path:g})}p.constraints?.forEach((w,u)=>{if("rules"in w)y.push(...a(w,o,d,[...g,`constraints[${u}]`],$));else{let f=d[w.predicate];f?f({data:o,field:p.name,arguments:w.parameters})||y.push({message:w.errorMessage||`Constraint '${w.name}' failed for field '${p.name}' with params ${K(w.parameters)}`,path:[...g,`constraints[${u}]`]}):y.push({message:`Predicate '${w.predicate}' not found`,path:[...g,`constraints[${u}]`]})}})}});for(let E in o)Object.hasOwnProperty.call(o,E)&&!T.has(E)&&y.push({message:`Unexpected field '${E}'`,path:[...l,E]});return c.constraints?.forEach((E,p)=>{if("rules"in E)y.push(...a(E,o,d,[...l,`constraints[${p}]`],$));else{let g=d[E.predicate];if(!g)y.push({message:`Predicate '${E.predicate}' not found`,path:[...l,`constraints[${p}]`]});else if(!g({data:o,field:E.field,arguments:E.parameters})){let w=E.field?` for field '${E.field}'`:"";y.push({message:E.errorMessage||`Constraint '${E.name}' failed${w} with params ${K(E.parameters)}`,path:[...l,`constraints[${p}]`]})}}}),y}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(l=>{d[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.nestedSchema.${l}`]})}),Object.keys(d).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${l}`]})}),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(l=>{d[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.reference.${l}`]})}),Object.keys(d).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.reference.${l}`]})}),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 l=o.fields;typeof l!="object"||l===null?i.push({message:"Fields must be a non-empty object",path:[`${d}.fields`]}):Object.entries(l).forEach(([v,$])=>{i.push(...se($,`${d}.fields.${v}`,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(l=>parseInt(l,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 C=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 C("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(r=>Se(r)))throw new C("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 C?r:new C("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 C("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new C("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>be(i))}catch(i){throw new C("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(n,i),s=a.reduce((c,d)=>{let l=n==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,l,d.id)},r),o=await t.processMigrationList(e,n,a);return{newSchema:s,dataPreview:o}}catch(r){throw r instanceof C?r:new C("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 C("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ie(s,o)}catch(c){throw new C("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:r})}catch(r){throw r instanceof C?r:new C("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 C("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new C("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let 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 C(`Failed to resolve transform for migration ${s.id}`,"TRANSFORM_ERROR",s.id,o)}}))).filter(s=>!!s.transform).reduce((s,{migration:o,transform:c})=>s.pipeThrough(new TransformStream({async transform(d,l){try{let v=await c(d);l.enqueue(v)}catch(v){l.error(new C(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,v))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new C(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let 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 C(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new C(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,r)=>this.applySchemaChanges(i,[r]),this.currentSchema)}catch(n){throw n instanceof C?n:new C("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 Dt(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 At(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[v,$]of Object.entries(o.fields))i[v]=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:l})=>{o.migrations[c]={hash:d,checksum:l}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let 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,l=t.startsWith("/")?t:`/${t}`,v=new ke,$=new Re(e.cacheTtl);async function P(u,f){let h=o;do{let b=s[o];try{return await u(b)}catch(R){if(console.warn(`Failed with proxy ${b}: ${R.message}`),o=(o+1)%s.length,o===h)throw new Error(`${f}: All CORS proxies failed`)}}while(!0)}async function y(u,f="."){return oe(async()=>(await D.default.add({fs:d,dir:l,filepath:f}),(await D.default.statusMatrix({fs:d,dir:l})).some(([b,R,k])=>R!==k)?await D.default.commit({fs:d,dir:l,message:u,author:a}):null),"Failed to commit changes")}async function m(u,f,h){return oe(async()=>{if(await T(u))throw new Error(`Tag ${u} already exists`);await D.default.annotatedTag({fs:d,dir:l,ref:u,message:f,tagger:a,object:h})},`Failed to create tag ${u}`)}async function T(u){try{return(await D.default.listTags({fs:d,dir:l})).includes(u)}catch{return!1}}async function E(u){return(await D.default.listTags({fs:d,dir:l})).filter(b=>b.startsWith(u))}async function p(u){return oe(async()=>{let h=(await D.default.listTags({fs:d,dir:l})).filter(b=>b.startsWith(u));for(let b of h)await D.default.deleteTag({fs:d,dir:l,ref:b});return h},`Failed to delete tags with prefix ${u}`)}async function g(u){return oe(async()=>{await D.default.checkout({fs:d,dir:l,ref:u})},`Failed to checkout ${u}`)}async function S(u,{delete:f=!1,force:h=!1}={}){i&&await P(async b=>{await D.default.push({fs:d,http:Q.default,dir:l,ref:u,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:f,force:h})},`Failed to push ${u}`)}async function w(u,f=!0){i&&await P(async h=>{try{await D.default.pull({fs:d,http:Q.default,dir:l,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:h,fastForwardOnly:!0})}catch(b){if(!f)console.warn(`Fast-forward pull failed for ${u}, attempting regular pull`),await D.default.pull({fs:d,http:Q.default,dir:l,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:h,fastForwardOnly:!1});else throw b}},`Failed to pull ${u}`)}if(i&&!await c.fileExists(l)){let u=l.slice(1);if(await i.exists({name:u}).catch(()=>!1))await P(async h=>{await D.default.clone({fs:d,http:Q.default,dir:l,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:h})},"Failed to clone repository");else if(r)try{i=await i.create({name:u,private:!0}),await ce(d,l,n,c,a),await D.default.addRemote({fs:d,dir:l,remote:"origin",url:i.url()}),await S(n)}catch(h){console.error("Failed to create and push to remote repository:",h),await ce(d,l,n,c,a)}else await ce(d,l,n,c,a)}else await ce(d,l,n,c,a);return{async init(){return v.withLock("init",()=>c.init())},async create(u){let{name:f,version:h}=u.schema;return v.withLock(`schema:${f}`,async()=>{await g(n),await c.create(u);let b=await y(`feat: create schema ${f}`);b&&await m(`${f}-${h}`,`Version ${h}`,b),$.invalidate(f)})},async update(u){let{name:f,version:h}=u.schema;return v.withLock(`schema:${f}`,async()=>{await g(n),await c.update(u);let b=await y(`fix: update schema ${f}`);b&&await m(`${f}-${h}`,`Version ${h}`,b),$.invalidate(f)})},async delete(u){let{name:f}=u;return v.withLock(`schema:${f}`,async()=>{await g(n),await D.default.remove({fs:d,dir:l,filepath:f}),await c.delete(u);let h=await y(`chore: delete schema ${f}`),b=await E(`${f}-`);if(i&&h){await S(n);for(let R of b)await S(R,{delete:!0,force:!0}).catch(k=>console.warn(`Failed to delete remote tag ${R}: ${k.message}`))}await p(`${f}-`),$.invalidate(f)})},async list(){return v.withLock("list",()=>c.list())},async schema(u){let{name:f,version:h}=u,b=`${f}-${h||"latest"}-${u.migrations||!1}`,R=$.get(b);return R||v.withLock(`schema:${f}`,async()=>{if(h){let A=`${f}-${h}`;if(await T(A))await g(A);else throw new Error(`Version ${h} of schema ${f} not found`)}else await g(n);let k=await c.schema(u);return $.set(b,k),k})},async stats(u){return v.withLock("stats",()=>c.stats(u))},async sync(){return v.withLock("sync",async()=>{if(await g(n),await c.sync(),await y("chore: sync local changes"),i){await w(n,!1),await S(n);let u=await D.default.listTags({fs:d,dir:l});for(let h of u)await S(h,{force:!0});let f=await D.default.listTags({fs:d,dir:l});for(let h of f)u.includes(h)||await S(h,{delete:!0})}$.invalidate()})},async migrations(u){let{name:f,version:h}=u,b=`migrations-${f}-${h||"latest"}`,R=$.get(b);return R||v.withLock(`migrations:${f}`,async()=>{if(h){let A=`${f}-${h}`;if(await T(A))await g(A);else throw new Error(`Version ${h} of schema ${f} not found`)}else await g(n);let k=await c.migrations(u);return $.set(b,k),k})},async history(u){let{name:f}=u,h=`history-${f}`,b=$.get(h);return b||v.withLock(`history:${f}`,async()=>{await g(n);let R=await c.history(u);return $.set(h,R),R})}}}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=(y,m=[])=>{if(!e||!y&&!m.length)return"";let T=y?[y]:[];return m.forEach(E=>T.push(E)),`/**
2
+ * ${T.join(`
3
3
  * `)}
4
4
  */
5
- `},c=v=>v.charAt(0).toUpperCase()+v.slice(1),u=(v,m)=>{for(let[g,k]of Object.entries(v))if(k.type==="enum"&&Array.isArray(k.values)){let $=`${m}${c(k.name)}`,h=k.values.map(y=>String(y));r.set($,h)}else if(k.type==="string"&&k.constraints){let $=k.constraints.find(h=>P(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if($&&P($)&&Array.isArray($.parameters)){let h=`${m}${c(k.name)}`,y=$.parameters.map(T=>String(T));r.set(h,y)}}else if(k.type==="record"){let $=`${m}${c(k.name)}`;s.set(k.name,$)}};u(t.fields,t.name);for(let[v,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(g=>u(g.fields,c(m.name))):u(m.fields,c(m.name));for(let[v,m]of r){i+=o(`Union type for ${v.toLowerCase()} field values`);let g=m.map(k=>`"${k}"`).join(" | ");i+=`${a}type ${v} = ${g};
5
+ `},c=y=>y.charAt(0).toUpperCase()+y.slice(1),d=(y,m)=>{let T=s.get(m)||new Map;for(let[E,p]of Object.entries(y))if(p.type==="enum"&&Array.isArray(p.values)){let g=`${m}${c(p.name)}`,S=p.values.map(w=>String(w));a.set(g,S)}else if(p.type==="string"&&p.constraints){let g=p.constraints.find(S=>O(S)&&(S.predicate==="enum"||S.predicate==="oneOf"));if(g&&O(g)&&Array.isArray(g.parameters)){let S=`${m}${c(p.name)}`,w=g.parameters.map(u=>String(u));a.set(S,w)}}else if(p.type==="record"){let g=`${m}${c(p.name)}`;T.set(p.name,g)}T.size>0&&s.set(m,T)};d(t.fields,t.name);for(let[y,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(T=>d(T.fields,c(m.name))):d(m.fields,c(m.name));for(let[y,m]of a){i+=o(`Union type for ${y.toLowerCase()} field values`);let T=m.map(E=>`"${E}"`).join(" | ");i+=`${r}type ${y} = ${T};
6
6
 
7
- `}for(let[v,m]of Object.entries(t.nestedSchemas||{})){let g=c(m.name),k=m.constraints?.map($=>P($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];if(m.concrete&&k.push("@concrete Indicates a concrete schema"),i+=o(m.description,k),Array.isArray(m.fields)){let $=m.fields.filter(b=>!b.when),h=m.fields.filter(b=>b.when),y="";if($.length>0){y+=`{
8
- `;for(let b of $)for(let[f,d]of Object.entries(b.fields)){let p=d.constraints?.map(R=>P(R)?`@constraint ${R.name}: ${R.description||R.predicate}`:`@constraint ${R.name}`)||[];d.unique&&p.push("@unique Ensures unique values"),d.default!==void 0&&p.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?y+=o(d.description,p):p.length&&(y+=o(void 0,p)),d.deprecated&&(y+=` /** @deprecated */
9
- `);let w=ae(d,t,g,s),D=d.required===!1?"?":"";y+=` ${d.name}${D}: ${w};
10
- `}y+="}"}let T="";h.length>0&&(T=h.map(f=>{let d="";d+=`{
11
- `;for(let[p,w]of Object.entries(f.fields)){let D=w.constraints?.map(G=>P(G)?`@constraint ${G.name}: ${G.description||G.predicate}`:`@constraint ${G.name}`)||[];w.unique&&D.push("@unique Ensures unique values"),w.default!==void 0&&D.push(`@default ${JSON.stringify(w.default)}`),e&&w.description?d+=o(w.description,D):D.length&&(d+=o(void 0,D)),w.deprecated&&(d+=` /** @deprecated */
12
- `);let R=ae(w,t,g,s),O=w.required===!1?"?":"";d+=` ${w.name}${O}: ${R};
13
- `}if(f.when)for(let[p,w]of Object.entries(f.when))d+=` ${p}: "${w}";
14
- `;return d+="}",d}).join(" | ")),y&&T?i+=`${a}type ${g} = ${y} & (${T});
7
+ `}for(let[y,m]of Object.entries(t.nestedSchemas||{})){let T=c(m.name),E=m.constraints?.map(w=>O(w)?`@constraint ${w.name}: ${w.description||w.predicate}`:`@constraint ${w.name}`)||[];m.concrete&&E.push("@concrete Indicates a concrete schema"),i+=o(m.description,E);let p=s.get(T)||new Map,g=Array.from(p.entries()).map(([w,u])=>`${u} extends Record<string, any> = Record<string, any>`).join(", "),S=p.size>0?`<${g}>`:"";if(Array.isArray(m.fields)){let w=m.fields.filter(b=>!b.when),u=m.fields.filter(b=>b.when),f="";if(w.length>0){f+=`{
8
+ `;for(let b of w)for(let[R,k]of Object.entries(b.fields)){let A=k.constraints?.map(V=>O(V)?`@constraint ${V.name}: ${V.description||V.predicate}`:`@constraint ${V.name}`)||[];k.unique&&A.push("@unique Ensures unique values"),k.default!==void 0&&A.push(`@default ${JSON.stringify(k.default)}`),e&&k.description?f+=o(k.description,A):A.length&&(f+=o(void 0,A)),k.deprecated&&(f+=` /** @deprecated */
9
+ `);let I=de(k,t,T,p),N=k.required===!1?"?":"";f+=` ${k.name}${N}: ${I};
10
+ `}f+="}"}let h="";u.length>0&&(h=u.map(R=>{let k=`{
11
+ `;for(let[A,I]of Object.entries(R.fields)){let N=I.constraints?.map(z=>O(z)?`@constraint ${z.name}: ${z.description||z.predicate}`:`@constraint ${z.name}`)||[];I.unique&&N.push("@unique Ensures unique values"),I.default!==void 0&&N.push(`@default ${JSON.stringify(I.default)}`),e&&I.description?k+=o(I.description,N):N.length&&(k+=o(void 0,N)),I.deprecated&&(k+=` /** @deprecated */
12
+ `);let V=de(I,t,T,p),Ye=I.required===!1?"?":"";k+=` ${I.name}${Ye}: ${V};
13
+ `}if(R.when)for(let[A,I]of Object.entries(R.when))k+=` ${A}: "${I}";
14
+ `;return k+="}",k}).join(" | ")),f&&h?i+=`${r}type ${T}${S} = ${f} & (${h});
15
15
 
16
- `:y?i+=`${a}type ${g} = ${y};
16
+ `:f?i+=`${r}type ${T}${S} = ${f};
17
17
 
18
- `:T&&(i+=`${a}type ${g} = ${T};
18
+ `:h&&(i+=`${r}type ${T}${S} = ${h};
19
19
 
20
- `)}else{i+=`${a}type ${g} = {
21
- `;for(let[$,h]of Object.entries(m.fields)){let y=h.constraints?.map(f=>P(f)?`@constraint ${f.name}: ${f.description||f.predicate}`:`@constraint ${f.name}`)||[];h.unique&&y.push("@unique Ensures unique values"),h.default!==void 0&&y.push(`@default ${JSON.stringify(h.default)}`),e&&h.description?i+=o(h.description,y):y.length&&(i+=o(void 0,y)),h.deprecated&&(i+=` /** @deprecated */
22
- `);let T=ae(h,t,g,s),b=h.required===!1?"?":"";i+=` ${h.name}${b}: ${T};
20
+ `)}else{i+=`${r}type ${T}${S} = {
21
+ `;for(let[w,u]of Object.entries(m.fields)){let f=u.constraints?.map(R=>O(R)?`@constraint ${R.name}: ${R.description||R.predicate}`:`@constraint ${R.name}`)||[];u.unique&&f.push("@unique Ensures unique values"),u.default!==void 0&&f.push(`@default ${JSON.stringify(u.default)}`),e&&u.description?i+=o(u.description,f):f.length&&(i+=o(void 0,f)),u.deprecated&&(i+=` /** @deprecated */
22
+ `);let h=de(u,t,T,p),b=u.required===!1?"?":"";i+=` ${u.name}${b}: ${h};
23
23
  `}m.metadata&&(i+=` metadata: Record<string, any>;
24
24
  `),i+=`};
25
25
 
26
- `}if(m.indexes?.length){i+=o(`Available indexes for ${g}`),i+=`${a}enum ${g}IndexNames {
27
- `;for(let $ of m.indexes)i+=` ${$.name} = "${$.name}",
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${T}`),i+=`${r}enum ${T}IndexNames {
27
+ `;for(let w of m.indexes)i+=` ${w.name} = "${w.name}",
28
28
  `;i+=`}
29
29
 
30
- `}}let l=t.constraints?.map(v=>P(v)?`@constraint ${v.name}: ${v.description||v.predicate}`:`@constraint ${v.name}`)||[];i+=o(t.description,l);let x=Array.from(s.entries()).map(([v,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),S=s.size>0?`<${x}>`:"";i+=`${a}type ${t.name}${S} = {
31
- `;for(let[v,m]of Object.entries(t.fields)){let g=m.constraints?.map(h=>P(h)?`@constraint ${h.name}: ${h.description||h.predicate}`:`@constraint ${h.name}`)||[];m.unique&&g.push("@unique Ensures unique values"),m.default!==void 0&&g.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,g):g.length&&(i+=o(void 0,g)),m.deprecated&&(i+=` /** @deprecated */
32
- `);let k=ae(m,t,t.name,s),$=m.required===!1?"?":"";i+=` ${m.name}${$}: ${k};
30
+ `}}let l=t.constraints?.map(y=>O(y)?`@constraint ${y.name}: ${y.description||y.predicate}`:`@constraint ${y.name}`)||[];i+=o(t.description,l);let v=s.get(t.name)||new Map,$=Array.from(v.entries()).map(([y,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),P=v.size>0?`<${$}>`:"";i+=`${r}type ${t.name}${P} = {
31
+ `;for(let[y,m]of Object.entries(t.fields)){let T=m.constraints?.map(g=>O(g)?`@constraint ${g.name}: ${g.description||g.predicate}`:`@constraint ${g.name}`)||[];m.unique&&T.push("@unique Ensures unique values"),m.default!==void 0&&T.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,T):T.length&&(i+=o(void 0,T)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let E=de(m,t,t.name,v),p=m.required===!1?"?":"";i+=` ${m.name}${p}: ${E};
33
33
  `}if(t.metadata&&(i+=` metadata: Record<string, any>;
34
34
  `),i+=`};
35
35
 
36
- `,t.indexes?.length){i+=o(`Available indexes for ${t.name}`),i+=`${a}enum ${t.name}IndexNames {
37
- `;for(let v of t.indexes)i+=` ${v.name} = "${v.name}",
36
+ `,t.indexes?.length){i+=o(`Available indexes for ${t.name}`),i+=`${r}enum ${t.name}IndexNames {
37
+ `;for(let y of t.indexes)i+=` ${y.name} = "${y.name}",
38
38
  `;i+=`}
39
- `}return i.trim()}function ae(t,e,n,i){switch(t.type){case"string":if(t.constraints){let a=t.constraints.find(r=>P(r)&&(r.predicate==="enum"||r.predicate==="oneOf"));if(a&&P(a)&&Array.isArray(a.parameters))return`${n}${N(t.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`${N(a.name)}[]`}return`${t.itemsType}[]`}return"any[]";case"set":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`Set<${N(a.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${N(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return N(a.name)}if(t.nestedSchema){let a=e.nestedSchemas[t.nestedSchema.id];return N(a.name)}return t.reference?`${t.reference.schema}${t.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(t.name)||"Record<string, any>";case"union":return t.schema&&Array.isArray(t.schema)?t.schema.map(r=>{let s=e.nestedSchemas[r.id];return N(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function N(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Tt(t,e=!0){let i=`${e?"export ":""}interface ${t.name}Validator {
40
- `;return i+=` /**
41
- * Validates a ${t.name} object against all schema constraints
42
- * @param data The data to validate
43
- * @returns Validation result with any errors
44
- */
45
- `,i+=` validate(data: ${t.name}): { valid: boolean; errors: Array<{ field: string; message: string }> };
46
-
47
- `,i+=` /**
48
- * Checks if the given object conforms to the ${t.name} type structure
49
- * @param data The object to check
50
- * @returns Whether the object matches the expected structure
51
- */
52
- `,i+=` isType(data: any): data is ${t.name};
53
- `,i+=`}
54
- `,i}function Ct(t,e){let n=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,a=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
55
- ${s.conditions.map(c=>` ${a(c)}`).join(`
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
+ ${s.conditions.map(c=>` ${r(c)}`).join(`
56
41
  `)}
57
- ]`),o},r=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,l])=>{let x=`${c} ${u} (${l.type})
42
+ ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([d,l])=>{let v=`${c} ${d} (${l.type})
58
43
 
59
- `;return x+=`**Required:** ${l.required?"Yes":"No"}
44
+ `;return v+=`**Required:** ${l.required?"Yes":"No"}
60
45
 
61
- `,l.description&&(x+=`**Description:** ${l.description}
46
+ `,l.description&&(v+=`**Description:** ${l.description}
62
47
 
63
- `),l.itemsType&&(x+=`**Item Type:** ${l.itemsType}
48
+ `),l.itemsType&&(v+=`**Item Type:** ${l.itemsType}
64
49
 
65
- `),l.nestedSchema&&(x+=r(l.nestedSchema,o+1)),x}).join(`
50
+ `),l.nestedSchema&&(v+=a(l.nestedSchema,o+1)),v}).join(`
66
51
  `)};n.push(`# ${t.name} Schema (Version ${t.version})`),t.description&&n.push(`
67
52
  ${t.description}
68
53
  `),n.push("## Metadata"),n.push(`- **Dependencies:** ${t.dependencies?.join(", ")||"None"}`),n.push(`- **Created:** ${new Date().toISOString()}
69
54
  `),n.push(`## Fields
70
55
  `),n.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),n.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,o]of Object.entries(t.fields))n.push([s,o.type,o.required?"Yes":"No",i(o.default),o.description?.replace(/\n/g," ")||"",o.deprecated?"Yes":"No",o.unique?"Yes":"No",o.constraints?.length||0].join("|"));Object.entries(t.fields).forEach(([s,o])=>{o.nestedSchema&&(n.push(`
71
56
  ### Nested Schema: ${s}
72
- `),n.push(r(o.nestedSchema)))}),n.push(`
57
+ `),n.push(a(o.nestedSchema)))}),n.push(`
73
58
  ## Indexes
74
- `),n.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),n.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of t.indexes||[])n.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?a(s.partial):"None",s.description||""].join("|"));n.push(`
59
+ `),n.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),n.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of t.indexes||[])n.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?r(s.partial):"None",s.description||""].join("|"));n.push(`
75
60
  ## Constraints
76
61
  `),t.constraints&&n.push("### Schema-level Constraints"),n.push(`
77
62
  ## Migrations
78
63
  `),n.push("| ID | Description | Status | Changes |"),n.push("|----|-------------|--------|---------|");for(let s of t.migrations||[])n.push([s.id,s.description,s.status,s.changes.length].join("|"));if(t.mock&&e?.faker)try{let s=t.mock(e.faker).next().value;n.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{n.push(`
79
64
  <!-- Error generating mock data -->`)}return n.join(`
80
- `)}function kt(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(a=>{n[a.name]={label:a.label,description:a.description}}),Je(t.fields,"",t.nestedSchemas||{},e);let i=[];for(let[a,r]of Object.entries(e)){let s=a!=="ungrouped"?n[a]:void 0;i.push({name:a!=="ungrouped"?a:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:r})}return i}function Je(t,e,n,i){for(let[a,r]of Object.entries(t)){let s=e?`${e}.${r.name}`:r.name,o={...r,name:s};if(!r.hint?.input?.ignore){if(r.type!=="object"){let c=r.hint?.input?.group||"ungrouped";i[c]||(i[c]=[]),i[c].push(o)}if(r.nestedSchema?.id&&n[r.nestedSchema.id]){let c=n[r.nestedSchema.id];Je(c.fields,s,n,i)}}}}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,formResolver,generateSHA256Hash,generateValidationInterface,normalizePath,schemaChangeToPatch,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
65
+ `)}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,formResolver,generateSHA256Hash,normalizePath,schemaChangeToPatch,schemaDefaults,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});