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