@asaidimu/anansi 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +9 -9
- package/index.d.cts +165 -16
- package/index.d.ts +165 -16
- package/index.js +9 -9
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
"use strict";var Je=Object.create;var G=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var Ke=(n,e)=>{for(var t in e)G(n,t,{get:e[t],enumerable:!0})},be=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of He(e))!Be.call(n,s)&&s!==t&&G(n,s,{get:()=>e[s],enumerable:!(i=Ge(e,s))||i.enumerable});return n};var q=(n,e,t)=>(t=n!=null?Je(ze(n)):{},be(e||!n||!n.__esModule?G(t,"default",{value:n,enumerable:!0}):t,n)),We=n=>be(G({},"__esModule",{value:!0}),n);var xt={};Ke(xt,{JsonPatchError:()=>P,MigrationEngine:()=>pe,MigrationError:()=>v,MigrationErrorCode:()=>Fe,SchemaRegistry:()=>_,applyPatch:()=>W,calculateNextVersion:()=>le,compareSemanticVersions:()=>A,createGitSchemaRegistry:()=>St,createPatch:()=>Ze,createSchemaMigrationHelper:()=>je,createStandardSchemaValidator:()=>Ce,deepMerge:()=>re,docgen:()=>vt,generateSHA256Hash:()=>O,generateValidationInterface:()=>bt,normalizePath:()=>ve,schemaChangeToPatch:()=>ae,schemaToTypes:()=>$t,serializeParams:()=>U,sortSemanticVars:()=>yt,validate:()=>rt,validateMigration:()=>me,validateSchemaChange:()=>he,validateSchemaDefinition:()=>N});module.exports=We(xt);var wt=require("@asaidimu/events");var gt=require("@asaidimu/events"),Z=require("@asaidimu/query");var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function B(n){let e=ve(n);return e===""?[]:e.substring(1).split("/").map(Ye)}function ve(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(z).join("/"):"/"+n.split(".").map(z).join("/")}function z(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Ye(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function K(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function te(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return n;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function Qe(n,e,t){let i=M.get(e)||B(e);M.set(e,i);let s=K(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function H(n,e,t){let i=M.get(e)||B(e);if(M.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=K(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function ne(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function W(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=H(t,i.path,i.value);break;case"remove":t=ne(t,i.path);break;case"removeValue":t=Qe(t,i.path,i.value);break;case"replace":t=H(ne(t,i.path),i.path,i.value);break;case"copy":{let s=te(t,i.from);t=H(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=te(t,i.from);t=H(t,i.path,s),t=ne(t,i.from);break}case"test":{let s=te(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function Ze(n,e){let t=[];return ie(n,e,"",t),t}function ie(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?Xe(n,e,t,i):et(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function Xe(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ie(n[r],e[r],a,i)}}function et(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=z(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ie(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=z(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function ae(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=tt(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function tt(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function xe(n){return n&&"operator"in n&&"rules"in n}function Ee(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function re(n,e){let t={...n};return se(n)&&se(e)&&Object.keys(e).forEach(i=>{se(e[i])?i in n?t[i]=re(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function se(n){return n&&typeof n=="object"&&!Array.isArray(n)}function U(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ce(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let x=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,x,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:x}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${U(f.parameters)}`,path:x})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],k=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let x=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:x});return}if(C!==void 0){if(g.push(...s(C,p.type,x)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...x,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,D)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...x,D.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...x,D.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:x}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,x,m,h)),p.nestedSchema.constraints?.forEach((E,D)=>{if("rules"in E)g.push(...r(E,C,d,[...x,`constraints[${D}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${U(E.parameters)}`,path:[...x,`constraints[${D}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...x,`constraints[${D}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...x,`constraints[${E}]`],h));else{let D=d[$.predicate];D?D({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${U($.parameters)}`,path:[...x,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...x,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!k.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let x=d[f.predicate];if(!x)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!x({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${U(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var F=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ce=n=>({value:n}),j=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Te=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},nt=(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]}]:[]},ke=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Y=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],it=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},de=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(...it(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},ue=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ke(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...ue(a,`${e}.rules[${o}]`)):t.push(...de(a,`${e}.rules[${o}]`))}),t},L=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...ue(i,`${e}[${s}]`)):t.push(...de(i,`${e}[${s}]`))}),t},Ie=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...ke(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...Ie(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},De=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...nt(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...Y(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...Ie(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},Q=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...De(i,`${e}[${s}]`))),t},fe=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Te(n.type,`${e}.type`)),t.push(...Y(n.required,`${e}.required`,!1)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...Te(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...L(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...Q(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...Y(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...Y(n.unique,`${e}.unique`,!1)),t},Pe=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...fe(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...Q(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},at=n=>{if(typeof n!="object"||n===null)return j([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...fe(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...Pe(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...Q(e.indexes,"indexes")),e.constraints&&t.push(...L(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...Re(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?j(t):ce(e)},oe=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...fe(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...L(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...Q(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...De(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...ue(n.constraint,`${e}.constraint`)):t.push(...de(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...Pe(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},st=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},Re=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...oe(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...oe(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...st(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},Ae={"~standard":{version:1,vendor:"xAI",validate:at,types:{input:{},output:{}}}};var Me={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return j([{message:"Migration must be an object",path:[]}]);let e=n,t=Re(e,"");return t.length>0?j(t):ce(e)},types:{input:{},output:{}}}},Oe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return j([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...oe(i,`[${s}]`))),t.length>0?j(t):ce(e)},types:{input:[],output:[]}}};function me(n){try{return!Me["~standard"].validate(n).issues}catch(e){throw new F("Invalid migration definition",e)}}function he(n){try{return!Oe["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}function N(n){try{return!Ae["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}var rt=N;var O=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(n).digest("hex")}};function ot(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 ct(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 dt(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 ut(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 ft(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 mt(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return ft(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=ct(e,t);return i?ut(e.parameters,n.parameters,i):!0}return!1}function ht(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return dt(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 mt(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 lt(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);s.add(r.id);break}}function pt(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function le(n,e,t){if(e.length===0)throw new Error("No changes provided");lt(e),pt(e);let i=ot(n),s="patch";for(let r of e){let a=ht(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function A(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function yt(n){return n.sort(A)}var v=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},Fe=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(Fe||{}),pe=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!N(e))throw new v("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>me(s)))throw new v("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>A(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>A(s.version,r.version)))}catch(s){throw s instanceof v?s:new v("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await O(t)}catch(t){throw new v("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new v("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>he(i))}catch(i){throw new v("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof v?s:new v("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?A(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=le(e.version,t);return t.map(a=>{try{return ae(a,e)}catch(o){throw new v("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return W(a,o)}catch(c){throw new v("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof v?s:new v("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new v("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,t){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let s=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new v(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new v(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new v(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new v(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new v(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof v?t:new v("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var je=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};var on=require("@isomorphic-git/lightning-fs"),T=q(require("isomorphic-git"),1),J=q(require("isomorphic-git/http/web"),1);var qe=q(require("@isomorphic-git/lightning-fs"),1);function Ne(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Ve(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function ye(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ge(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}var Ue=require("buffer");window.Buffer=Ue.Buffer;var _=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new qe.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!N(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await O(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await O(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));A(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>A(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:ye(o.forward),backward:ye(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await O(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ne(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ve(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ge(e.transform.forward),backward:ge(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var we=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},Se=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function X(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function ee(n,e,t,i,s){await i.init(),await T.default.init({fs:n,dir:e,defaultBranch:t}),await T.default.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.default.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.default.add({fs:n,dir:e,filepath:"."}),await T.default.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function St(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new _(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new we,h=new Se(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(I){if(console.warn(`Failed with proxy ${b}: ${I.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function k(l,y="."){return X(async()=>(await T.default.add({fs:d,dir:u,filepath:y}),(await T.default.statusMatrix({fs:d,dir:u})).some(([b,I,R])=>I!==R)?await T.default.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return X(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.default.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.default.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function x(l){return(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return X(async()=>{let w=(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.default.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return X(async()=>{await T.default.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.default.push({fs:d,http:J.default,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function D(l,y=!0){i&&await g(async w=>{try{await T.default.pull({fs:d,http:J.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.default.pull({fs:d,http:J.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.default.clone({fs:d,http:J.default,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await ee(d,u,t,c,r),await T.default.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await ee(d,u,t,c,r)}else await ee(d,u,t,c,r)}else await ee(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await k(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await k(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.default.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await k(`chore: delete schema ${y}`),b=await x(`${y}-`);if(i&&w){await E(t);for(let I of b)await E(I,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${I}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,I=h.get(b);return I||m.withLock(`schema:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await k("chore: sync local changes"),i){await D(t,!1),await E(t);let l=await T.default.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.default.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,I=h.get(b);return I||m.withLock(`migrations:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let I=await c.history(l);return h.set(w,I),I})}}}function $t(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
|
|
1
|
+
"use strict";var Je=Object.create;var J=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var We=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},be=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ze(e))!Ke.call(n,s)&&s!==t&&J(n,s,{get:()=>e[s],enumerable:!(i=He(e,s))||i.enumerable});return n};var q=(n,e,t)=>(t=n!=null?Je(Be(n)):{},be(e||!n||!n.__esModule?J(t,"default",{value:n,enumerable:!0}):t,n)),Ye=n=>be(J({},"__esModule",{value:!0}),n);var Ct={};We(Ct,{JsonPatchError:()=>P,MigrationEngine:()=>pe,MigrationError:()=>v,MigrationErrorCode:()=>Fe,SchemaRegistry:()=>_,applyPatch:()=>W,calculateNextVersion:()=>le,compareSemanticVersions:()=>A,createGitSchemaRegistry:()=>$t,createPatch:()=>Xe,createSchemaMigrationHelper:()=>je,createStandardSchemaValidator:()=>Ce,deepMerge:()=>re,docgen:()=>xt,extractInputFieldGroups:()=>Et,generateSHA256Hash:()=>O,generateValidationInterface:()=>vt,normalizePath:()=>ve,schemaChangeToPatch:()=>ae,schemaToTypes:()=>bt,serializeParams:()=>U,sortSemanticVars:()=>gt,validate:()=>ot,validateMigration:()=>me,validateSchemaChange:()=>he,validateSchemaDefinition:()=>N});module.exports=Ye(Ct);var St=require("@asaidimu/events");var wt=require("@asaidimu/events"),Z=require("@asaidimu/query");var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function B(n){let e=ve(n);return e===""?[]:e.substring(1).split("/").map(Qe)}function ve(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(z).join("/"):"/"+n.split(".").map(z).join("/")}function z(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Qe(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function K(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function te(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return n;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function Ze(n,e,t){let i=M.get(e)||B(e);M.set(e,i);let s=K(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function H(n,e,t){let i=M.get(e)||B(e);if(M.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=K(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function ne(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function W(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=H(t,i.path,i.value);break;case"remove":t=ne(t,i.path);break;case"removeValue":t=Ze(t,i.path,i.value);break;case"replace":t=H(ne(t,i.path),i.path,i.value);break;case"copy":{let s=te(t,i.from);t=H(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=te(t,i.from);t=H(t,i.path,s),t=ne(t,i.from);break}case"test":{let s=te(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function Xe(n,e){let t=[];return ie(n,e,"",t),t}function ie(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?et(n,e,t,i):tt(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function et(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ie(n[r],e[r],a,i)}}function tt(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=z(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ie(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=z(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function ae(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=nt(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function nt(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function xe(n){return n&&"operator"in n&&"rules"in n}function Ee(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function re(n,e){let t={...n};return se(n)&&se(e)&&Object.keys(e).forEach(i=>{se(e[i])?i in n?t[i]=re(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function se(n){return n&&typeof n=="object"&&!Array.isArray(n)}function U(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ce(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let x=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,x,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:x}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${U(f.parameters)}`,path:x})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],D=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let x=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:x});return}if(C!==void 0){if(g.push(...s(C,p.type,x)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...x,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,I)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...x,I.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...x,I.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:x}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,x,m,h)),p.nestedSchema.constraints?.forEach((E,I)=>{if("rules"in E)g.push(...r(E,C,d,[...x,`constraints[${I}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${U(E.parameters)}`,path:[...x,`constraints[${I}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...x,`constraints[${I}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...x,`constraints[${E}]`],h));else{let I=d[$.predicate];I?I({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${U($.parameters)}`,path:[...x,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...x,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!D.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let x=d[f.predicate];if(!x)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!x({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${U(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var F=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ce=n=>({value:n}),j=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Te=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},it=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},De=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Y=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],at=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},de=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(...at(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},ue=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...De(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...ue(a,`${e}.rules[${o}]`)):t.push(...de(a,`${e}.rules[${o}]`))}),t},L=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...ue(i,`${e}[${s}]`)):t.push(...de(i,`${e}[${s}]`))}),t},ke=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...De(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...ke(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Ie=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...it(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...Y(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...ke(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},Q=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...Ie(i,`${e}[${s}]`))),t},fe=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Te(n.type,`${e}.type`)),t.push(...Y(n.required,`${e}.required`,!1)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...Te(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...L(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...Q(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...Y(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...Y(n.unique,`${e}.unique`,!1)),t},Pe=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...fe(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...Q(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},st=n=>{if(typeof n!="object"||n===null)return j([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...fe(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...Pe(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...Q(e.indexes,"indexes")),e.constraints&&t.push(...L(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...Re(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?j(t):ce(e)},oe=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...fe(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...L(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...Q(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...Ie(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...ue(n.constraint,`${e}.constraint`)):t.push(...de(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...Pe(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},rt=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},Re=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...oe(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...oe(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...rt(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},Ae={"~standard":{version:1,vendor:"xAI",validate:st,types:{input:{},output:{}}}};var Me={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return j([{message:"Migration must be an object",path:[]}]);let e=n,t=Re(e,"");return t.length>0?j(t):ce(e)},types:{input:{},output:{}}}},Oe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return j([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...oe(i,`[${s}]`))),t.length>0?j(t):ce(e)},types:{input:[],output:[]}}};function me(n){try{return!Me["~standard"].validate(n).issues}catch(e){throw new F("Invalid migration definition",e)}}function he(n){try{return!Oe["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}function N(n){try{return!Ae["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}var ot=N;var O=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(n).digest("hex")}};function ct(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function dt(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function ut(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function ft(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function mt(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function ht(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return mt(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=dt(e,t);return i?ft(e.parameters,n.parameters,i):!0}return!1}function lt(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return ut(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return ht(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function pt(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);s.add(r.id);break}}function yt(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function le(n,e,t){if(e.length===0)throw new Error("No changes provided");pt(e),yt(e);let i=ct(n),s="patch";for(let r of e){let a=lt(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function A(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function gt(n){return n.sort(A)}var v=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},Fe=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(Fe||{}),pe=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!N(e))throw new v("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>me(s)))throw new v("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>A(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>A(s.version,r.version)))}catch(s){throw s instanceof v?s:new v("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await O(t)}catch(t){throw new v("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new v("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>he(i))}catch(i){throw new v("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof v?s:new v("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?A(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=le(e.version,t);return t.map(a=>{try{return ae(a,e)}catch(o){throw new v("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return W(a,o)}catch(c){throw new v("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof v?s:new v("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new v("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,t){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let s=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new v(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new v(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new v(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new v(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new v(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof v?t:new v("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var je=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};var dn=require("@isomorphic-git/lightning-fs"),T=q(require("isomorphic-git"),1),G=q(require("isomorphic-git/http/web"),1);var qe=q(require("@isomorphic-git/lightning-fs"),1);function Ne(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Ve(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function ye(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ge(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}var Ue=require("buffer");window.Buffer=Ue.Buffer;var _=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new qe.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!N(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await O(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await O(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));A(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>A(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:ye(o.forward),backward:ye(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await O(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ne(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ve(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ge(e.transform.forward),backward:ge(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var we=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},Se=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function X(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function ee(n,e,t,i,s){await i.init(),await T.default.init({fs:n,dir:e,defaultBranch:t}),await T.default.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.default.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.default.add({fs:n,dir:e,filepath:"."}),await T.default.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function $t(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new _(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new we,h=new Se(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(k){if(console.warn(`Failed with proxy ${b}: ${k.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function D(l,y="."){return X(async()=>(await T.default.add({fs:d,dir:u,filepath:y}),(await T.default.statusMatrix({fs:d,dir:u})).some(([b,k,R])=>k!==R)?await T.default.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return X(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.default.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.default.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function x(l){return(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return X(async()=>{let w=(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.default.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return X(async()=>{await T.default.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.default.push({fs:d,http:G.default,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function I(l,y=!0){i&&await g(async w=>{try{await T.default.pull({fs:d,http:G.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.default.pull({fs:d,http:G.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.default.clone({fs:d,http:G.default,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await ee(d,u,t,c,r),await T.default.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await ee(d,u,t,c,r)}else await ee(d,u,t,c,r)}else await ee(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await D(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await D(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.default.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await D(`chore: delete schema ${y}`),b=await x(`${y}-`);if(i&&w){await E(t);for(let k of b)await E(k,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${k}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,k=h.get(b);return k||m.withLock(`schema:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await D("chore: sync local changes"),i){await I(t,!1),await E(t);let l=await T.default.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.default.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,k=h.get(b);return k||m.withLock(`migrations:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let k=await c.history(l);return h.set(w,k),k})}}}function bt(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
|
|
2
2
|
* ${h.join(`
|
|
3
3
|
* `)}
|
|
4
4
|
*/
|
|
5
|
-
`},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let
|
|
5
|
+
`},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let D=g.constraints.find(f=>f.predicate==="enum"||f.predicate==="oneOf");if(D&&Array.isArray(D.parameters)){let f=`${m}${_e(g.name)}`,p=D.parameters.map(x=>String(x));r.set(f,p)}}};c(n.fields,n.name);for(let[u,m]of Object.entries(n.nestedSchemas))c(m.fields,o(m.name));for(let[u,m]of r){i+=a(`Union type for ${u.toLowerCase()} field values`);let h=m.map(g=>`"${g}"`).join(" | ");i+=`${s}type ${u} = ${h};
|
|
6
6
|
|
|
7
|
-
`}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(
|
|
8
|
-
`;for(let[
|
|
7
|
+
`}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(D=>`@constraint ${D.name}: ${D.description||D.predicate}`)||[];i+=a(m.description,g),i+=`${s}type ${h} = {
|
|
8
|
+
`;for(let[D,f]of Object.entries(m.fields)){let p=f.constraints?.map($=>`@constraint ${$.name}: ${$.description||$.predicate}`)||[];f.unique&&p.push("@unique Ensures unique values"),f.default!==void 0&&p.push(`@default ${JSON.stringify(f.default)}`),e&&f.description?i+=a(f.description,p):p.length&&(i+=a(void 0,p)),f.deprecated&&(i+=` /** @deprecated */
|
|
9
9
|
`);let x=Le(f,n,h),C=f.required===!1?"?":"";i+=` ${f.name}${C}: ${x};
|
|
10
10
|
`}if(m.metadata&&(i+=` metadata: Record<string, any>;
|
|
11
11
|
`),i+=`};
|
|
12
12
|
|
|
13
13
|
`,m.indexes?.length){i+=a(`Available indexes for ${h}`),i+=`${s}enum ${h}IndexNames {
|
|
14
|
-
`;for(let
|
|
14
|
+
`;for(let D of m.indexes)i+=` ${D.name} = "${D.name}",
|
|
15
15
|
`;i+=`}
|
|
16
16
|
|
|
17
17
|
`}}let d=n.constraints?.map(u=>`@constraint ${u.name}: ${u.description||u.predicate}`)||[];i+=a(n.description,d),i+=`${s}type ${n.name} = {
|
|
18
18
|
`;for(let[u,m]of Object.entries(n.fields)){let h=m.constraints?.map(f=>`@constraint ${f.name}: ${f.description||f.predicate}`)||[];m.unique&&h.push("@unique Ensures unique values"),m.default!==void 0&&h.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=a(m.description,h):h.length&&(i+=a(void 0,h)),m.deprecated&&(i+=` /** @deprecated */
|
|
19
|
-
`);let g=Le(m,n,n.name),
|
|
19
|
+
`);let g=Le(m,n,n.name),D=m.required===!1?"?":"";i+=` ${m.name}${D}: ${g};
|
|
20
20
|
`}if(n.metadata&&(i+=` metadata: Record<string, any>;
|
|
21
21
|
`),i+=`};
|
|
22
22
|
|
|
23
23
|
`,n.indexes?.length){i+=a(`Available indexes for ${n.name}`),i+=`${s}enum ${n.name}IndexNames {
|
|
24
24
|
`;for(let u of n.indexes)i+=` ${u.name} = "${u.name}",
|
|
25
25
|
`;i+=`}
|
|
26
|
-
`}return i}function Le(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${_e(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${$e(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${$e(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return $e(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function _e(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function $e(n){return n.charAt(0).toUpperCase()+n.slice(1)}function
|
|
26
|
+
`}return i}function Le(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${_e(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${$e(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${$e(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return $e(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function _e(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function $e(n){return n.charAt(0).toUpperCase()+n.slice(1)}function vt(n,e=!0){let i=`${e?"export ":""}interface ${n.name}Validator {
|
|
27
27
|
`;return i+=` /**
|
|
28
28
|
* Validates a ${n.name} object against all schema constraints
|
|
29
29
|
* @param data The data to validate
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
*/
|
|
39
39
|
`,i+=` isType(data: any): data is ${n.name};
|
|
40
40
|
`,i+=`}
|
|
41
|
-
`,i}function
|
|
41
|
+
`,i}function xt(n,e){let t=[],i=a=>a===void 0?"`None`":`\`${JSON.stringify(a,null,2)}\``,s=a=>{let o=`**${a.field}** ${a.operator}`;return a.value!==void 0&&(o+=` ${JSON.stringify(a.value)}`),a.conditions&&(o+=` [
|
|
42
42
|
${a.conditions.map(c=>` ${s(c)}`).join(`
|
|
43
43
|
`)}
|
|
44
44
|
]`),o},r=(a,o=1)=>{let c="#".repeat(o+2);return Object.entries(a).map(([d,u])=>{let m=`${c} ${d} (${u.type})
|
|
@@ -64,4 +64,4 @@ ${n.description}
|
|
|
64
64
|
## Migrations
|
|
65
65
|
`),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let a of n.migrations||[])t.push([a.id,a.description,a.status,a.changes.length].join("|"));if(n.mock&&e?.faker)try{let a=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(a,null,2)+"\n```")}catch{t.push(`
|
|
66
66
|
<!-- Error generating mock data -->`)}return t.join(`
|
|
67
|
-
`)}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,generateSHA256Hash,generateValidationInterface,normalizePath,schemaChangeToPatch,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
|
|
67
|
+
`)}function Et(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(s=>{t[s.name]={label:s.label,description:s.description}}),Ge(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[s,r]of Object.entries(e)){let a=s!=="ungrouped"?t[s]:void 0;i.push({name:s!=="ungrouped"?s:"ungrouped",label:a?.label||"Ungrouped",description:a?.description,fields:r})}return i}function Ge(n,e,t,i){for(let[s,r]of Object.entries(n)){if(r.hint?.input?.ignore)continue;let a=e?`${e}.${r.name}`:r.name,o={...r,name:a},c=r.hint?.input?.group||"ungrouped";if(i[c]||(i[c]=[]),i[c].push(o),r.nestedSchema?.id&&t[r.nestedSchema.id]){let d=t[r.nestedSchema.id];Ge(d.fields,a,t,i)}}}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,generateSHA256Hash,generateValidationInterface,normalizePath,schemaChangeToPatch,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
|
package/index.d.cts
CHANGED
|
@@ -5,21 +5,145 @@ import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
|
5
5
|
import LightningFS from '@isomorphic-git/lightning-fs';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
8
|
+
* hints.ts
|
|
9
9
|
*
|
|
10
|
-
* Defines
|
|
11
|
-
*
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
*
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
10
|
+
* Defines type hints for generating form input controls based on schema field definitions.
|
|
11
|
+
* Each hint type corresponds to a specific input control, providing metadata for code generation.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Hints for generating a file input control.
|
|
15
|
+
*/
|
|
16
|
+
type FileHint = {
|
|
17
|
+
type: "file";
|
|
18
|
+
label?: string;
|
|
19
|
+
embed?: boolean;
|
|
20
|
+
mimes?: string | string[];
|
|
21
|
+
size?: {
|
|
22
|
+
max?: number;
|
|
23
|
+
min?: number;
|
|
24
|
+
};
|
|
25
|
+
dimensions?: {
|
|
26
|
+
width: number;
|
|
27
|
+
height: number;
|
|
28
|
+
};
|
|
29
|
+
group?: string;
|
|
30
|
+
ignore?: boolean;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Hints for generating a text-based input control.
|
|
34
|
+
*/
|
|
35
|
+
type TextHint = {
|
|
36
|
+
type: "text" | "email" | "tel" | "url" | "textarea";
|
|
37
|
+
label?: string;
|
|
38
|
+
placeholder?: string;
|
|
39
|
+
group?: string;
|
|
40
|
+
ignore?: boolean;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Hints for generating a secret input control (e.g., passwords, API keys).
|
|
44
|
+
*/
|
|
45
|
+
type SecretHint = {
|
|
46
|
+
type: "secret";
|
|
47
|
+
label?: string;
|
|
48
|
+
placeholder?: string;
|
|
49
|
+
password?: boolean;
|
|
50
|
+
group?: string;
|
|
51
|
+
ignore?: boolean;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Hints for generating a number-based input control.
|
|
55
|
+
*/
|
|
56
|
+
type NumberHint = {
|
|
57
|
+
type: "number" | "range";
|
|
58
|
+
label?: string;
|
|
59
|
+
step?: number;
|
|
60
|
+
group?: string;
|
|
61
|
+
ignore?: boolean;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Hints for generating a boolean input control.
|
|
65
|
+
*/
|
|
66
|
+
type BooleanHint = {
|
|
67
|
+
type: "checkbox" | "radio";
|
|
68
|
+
label?: string;
|
|
69
|
+
radioLabels?: {
|
|
70
|
+
true: string;
|
|
71
|
+
false: string;
|
|
72
|
+
};
|
|
73
|
+
group?: string;
|
|
74
|
+
ignore?: boolean;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Hints for generating an enum input control.
|
|
78
|
+
*/
|
|
79
|
+
type EnumHint = {
|
|
80
|
+
type: "select" | "radio";
|
|
81
|
+
label?: string;
|
|
82
|
+
group?: string;
|
|
83
|
+
ignore?: boolean;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Hints for generating an array input control.
|
|
87
|
+
*/
|
|
88
|
+
type ArrayHint = {
|
|
89
|
+
type: "list";
|
|
90
|
+
label?: string;
|
|
91
|
+
itemHint?: {
|
|
92
|
+
type: string;
|
|
93
|
+
};
|
|
94
|
+
group?: string;
|
|
95
|
+
ignore?: boolean;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Hints for generating a set input control.
|
|
99
|
+
*/
|
|
100
|
+
type SetHint = {
|
|
101
|
+
type: "tags";
|
|
102
|
+
label?: string;
|
|
103
|
+
itemHint?: {
|
|
104
|
+
type: string;
|
|
105
|
+
};
|
|
106
|
+
group?: string;
|
|
107
|
+
ignore?: boolean;
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Hints for generating an object input control.
|
|
111
|
+
*/
|
|
112
|
+
type ObjectHint = {
|
|
113
|
+
type: "group";
|
|
114
|
+
label?: string;
|
|
115
|
+
collapsible?: boolean;
|
|
116
|
+
group?: string;
|
|
117
|
+
ignore?: boolean;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Hints for generating a dynamic input control.
|
|
121
|
+
*/
|
|
122
|
+
type DynamicHint = {
|
|
123
|
+
type: "text";
|
|
124
|
+
label?: string;
|
|
125
|
+
group?: string;
|
|
126
|
+
ignore?: boolean;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Union type for all possible input hints.
|
|
130
|
+
*/
|
|
131
|
+
type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint;
|
|
132
|
+
/**
|
|
133
|
+
* Defines metadata for a group of inputs at the schema level.
|
|
134
|
+
*/
|
|
135
|
+
type GroupDefinition = {
|
|
136
|
+
name: string;
|
|
137
|
+
label?: string;
|
|
138
|
+
description?: string;
|
|
139
|
+
};
|
|
140
|
+
/**
|
|
141
|
+
* Defines hints at the schema level, including group metadata.
|
|
22
142
|
*/
|
|
143
|
+
type SchemaHint = {
|
|
144
|
+
groups?: GroupDefinition[];
|
|
145
|
+
};
|
|
146
|
+
|
|
23
147
|
/**
|
|
24
148
|
* Logical operators for combining constraints or index conditions.
|
|
25
149
|
*/
|
|
@@ -27,7 +151,7 @@ type LogicalOperator = "and" | "or" | "not" | "nor" | "xor";
|
|
|
27
151
|
/**
|
|
28
152
|
* Basic field types supported by the schema system.
|
|
29
153
|
*/
|
|
30
|
-
type FieldType = "string" | "number" | "boolean" | "array" | "set" | "enum" | "object" | "dynamic";
|
|
154
|
+
type FieldType = "string" | "number" | "boolean" | "array" | "set" | "enum" | "object" | "record" | "dynamic";
|
|
31
155
|
/**
|
|
32
156
|
* Index types for optimizing different query patterns.
|
|
33
157
|
*/
|
|
@@ -54,6 +178,9 @@ type ConstraintsMap = Record<string, Predicate>;
|
|
|
54
178
|
* Names of supported predicates, derived from a PredicateMap.
|
|
55
179
|
*/
|
|
56
180
|
type PredicateName<T extends PredicateMap = any> = keyof T;
|
|
181
|
+
/**
|
|
182
|
+
* Parameters for predicates, tailored to each field type.
|
|
183
|
+
*/
|
|
57
184
|
/**
|
|
58
185
|
* Parameters for predicates, tailored to each field type.
|
|
59
186
|
*/
|
|
@@ -69,7 +196,7 @@ type PredicateParameters<T extends FieldType> = T extends "string" ? string | st
|
|
|
69
196
|
maxItems: number;
|
|
70
197
|
} : T extends "object" ? {
|
|
71
198
|
schema: Record<string, unknown>;
|
|
72
|
-
} : T extends "dynamic" ? any : never;
|
|
199
|
+
} : T extends "record" ? Record<string, unknown> : T extends "dynamic" ? any : never;
|
|
73
200
|
/** @deprecated Use PredicateParameters instead. */
|
|
74
201
|
type ConstraintParameters<T extends FieldType> = PredicateParameters<T>;
|
|
75
202
|
/**
|
|
@@ -120,6 +247,9 @@ interface FieldDefinition<T> {
|
|
|
120
247
|
};
|
|
121
248
|
description?: string;
|
|
122
249
|
unique?: boolean;
|
|
250
|
+
hint?: {
|
|
251
|
+
input: InputHint;
|
|
252
|
+
};
|
|
123
253
|
}
|
|
124
254
|
/**
|
|
125
255
|
* Condition for partial indexes, allowing conditional indexing based on field values.
|
|
@@ -170,6 +300,7 @@ interface SchemaDefinition {
|
|
|
170
300
|
/** @deprecated Use dependencies in DomainModel instead. */
|
|
171
301
|
dependencies?: string[];
|
|
172
302
|
migrations?: Array<Migration<any>>;
|
|
303
|
+
hint?: SchemaHint;
|
|
173
304
|
mock?: <T>(faker: typeof _faker_js_faker) => Generator<T, void, unknown>;
|
|
174
305
|
}
|
|
175
306
|
/**
|
|
@@ -1411,4 +1542,22 @@ declare function docgen(schema: SchemaDefinition, options?: {
|
|
|
1411
1542
|
faker?: Faker;
|
|
1412
1543
|
}): string;
|
|
1413
1544
|
|
|
1414
|
-
|
|
1545
|
+
/**
|
|
1546
|
+
* Represents a group of field definitions with optional metadata.
|
|
1547
|
+
*/
|
|
1548
|
+
interface FieldGroup {
|
|
1549
|
+
name: string;
|
|
1550
|
+
label: string;
|
|
1551
|
+
description?: string;
|
|
1552
|
+
fields: FieldDefinition<any>[];
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Extracts all field definitions from a schema, organized into groups based on hint.input.group,
|
|
1556
|
+
* including those in nested schemas, with proper path prefixing to represent the field hierarchy.
|
|
1557
|
+
*
|
|
1558
|
+
* @param schema - The schema definition to extract fields from
|
|
1559
|
+
* @returns Array of field groups, each containing grouped field definitions
|
|
1560
|
+
*/
|
|
1561
|
+
declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
|
|
1562
|
+
|
|
1563
|
+
export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldGroup, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
|
package/index.d.ts
CHANGED
|
@@ -5,21 +5,145 @@ import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
|
5
5
|
import LightningFS from '@isomorphic-git/lightning-fs';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
8
|
+
* hints.ts
|
|
9
9
|
*
|
|
10
|
-
* Defines
|
|
11
|
-
*
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
*
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
10
|
+
* Defines type hints for generating form input controls based on schema field definitions.
|
|
11
|
+
* Each hint type corresponds to a specific input control, providing metadata for code generation.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Hints for generating a file input control.
|
|
15
|
+
*/
|
|
16
|
+
type FileHint = {
|
|
17
|
+
type: "file";
|
|
18
|
+
label?: string;
|
|
19
|
+
embed?: boolean;
|
|
20
|
+
mimes?: string | string[];
|
|
21
|
+
size?: {
|
|
22
|
+
max?: number;
|
|
23
|
+
min?: number;
|
|
24
|
+
};
|
|
25
|
+
dimensions?: {
|
|
26
|
+
width: number;
|
|
27
|
+
height: number;
|
|
28
|
+
};
|
|
29
|
+
group?: string;
|
|
30
|
+
ignore?: boolean;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Hints for generating a text-based input control.
|
|
34
|
+
*/
|
|
35
|
+
type TextHint = {
|
|
36
|
+
type: "text" | "email" | "tel" | "url" | "textarea";
|
|
37
|
+
label?: string;
|
|
38
|
+
placeholder?: string;
|
|
39
|
+
group?: string;
|
|
40
|
+
ignore?: boolean;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Hints for generating a secret input control (e.g., passwords, API keys).
|
|
44
|
+
*/
|
|
45
|
+
type SecretHint = {
|
|
46
|
+
type: "secret";
|
|
47
|
+
label?: string;
|
|
48
|
+
placeholder?: string;
|
|
49
|
+
password?: boolean;
|
|
50
|
+
group?: string;
|
|
51
|
+
ignore?: boolean;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Hints for generating a number-based input control.
|
|
55
|
+
*/
|
|
56
|
+
type NumberHint = {
|
|
57
|
+
type: "number" | "range";
|
|
58
|
+
label?: string;
|
|
59
|
+
step?: number;
|
|
60
|
+
group?: string;
|
|
61
|
+
ignore?: boolean;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Hints for generating a boolean input control.
|
|
65
|
+
*/
|
|
66
|
+
type BooleanHint = {
|
|
67
|
+
type: "checkbox" | "radio";
|
|
68
|
+
label?: string;
|
|
69
|
+
radioLabels?: {
|
|
70
|
+
true: string;
|
|
71
|
+
false: string;
|
|
72
|
+
};
|
|
73
|
+
group?: string;
|
|
74
|
+
ignore?: boolean;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Hints for generating an enum input control.
|
|
78
|
+
*/
|
|
79
|
+
type EnumHint = {
|
|
80
|
+
type: "select" | "radio";
|
|
81
|
+
label?: string;
|
|
82
|
+
group?: string;
|
|
83
|
+
ignore?: boolean;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Hints for generating an array input control.
|
|
87
|
+
*/
|
|
88
|
+
type ArrayHint = {
|
|
89
|
+
type: "list";
|
|
90
|
+
label?: string;
|
|
91
|
+
itemHint?: {
|
|
92
|
+
type: string;
|
|
93
|
+
};
|
|
94
|
+
group?: string;
|
|
95
|
+
ignore?: boolean;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Hints for generating a set input control.
|
|
99
|
+
*/
|
|
100
|
+
type SetHint = {
|
|
101
|
+
type: "tags";
|
|
102
|
+
label?: string;
|
|
103
|
+
itemHint?: {
|
|
104
|
+
type: string;
|
|
105
|
+
};
|
|
106
|
+
group?: string;
|
|
107
|
+
ignore?: boolean;
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Hints for generating an object input control.
|
|
111
|
+
*/
|
|
112
|
+
type ObjectHint = {
|
|
113
|
+
type: "group";
|
|
114
|
+
label?: string;
|
|
115
|
+
collapsible?: boolean;
|
|
116
|
+
group?: string;
|
|
117
|
+
ignore?: boolean;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Hints for generating a dynamic input control.
|
|
121
|
+
*/
|
|
122
|
+
type DynamicHint = {
|
|
123
|
+
type: "text";
|
|
124
|
+
label?: string;
|
|
125
|
+
group?: string;
|
|
126
|
+
ignore?: boolean;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Union type for all possible input hints.
|
|
130
|
+
*/
|
|
131
|
+
type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint;
|
|
132
|
+
/**
|
|
133
|
+
* Defines metadata for a group of inputs at the schema level.
|
|
134
|
+
*/
|
|
135
|
+
type GroupDefinition = {
|
|
136
|
+
name: string;
|
|
137
|
+
label?: string;
|
|
138
|
+
description?: string;
|
|
139
|
+
};
|
|
140
|
+
/**
|
|
141
|
+
* Defines hints at the schema level, including group metadata.
|
|
22
142
|
*/
|
|
143
|
+
type SchemaHint = {
|
|
144
|
+
groups?: GroupDefinition[];
|
|
145
|
+
};
|
|
146
|
+
|
|
23
147
|
/**
|
|
24
148
|
* Logical operators for combining constraints or index conditions.
|
|
25
149
|
*/
|
|
@@ -27,7 +151,7 @@ type LogicalOperator = "and" | "or" | "not" | "nor" | "xor";
|
|
|
27
151
|
/**
|
|
28
152
|
* Basic field types supported by the schema system.
|
|
29
153
|
*/
|
|
30
|
-
type FieldType = "string" | "number" | "boolean" | "array" | "set" | "enum" | "object" | "dynamic";
|
|
154
|
+
type FieldType = "string" | "number" | "boolean" | "array" | "set" | "enum" | "object" | "record" | "dynamic";
|
|
31
155
|
/**
|
|
32
156
|
* Index types for optimizing different query patterns.
|
|
33
157
|
*/
|
|
@@ -54,6 +178,9 @@ type ConstraintsMap = Record<string, Predicate>;
|
|
|
54
178
|
* Names of supported predicates, derived from a PredicateMap.
|
|
55
179
|
*/
|
|
56
180
|
type PredicateName<T extends PredicateMap = any> = keyof T;
|
|
181
|
+
/**
|
|
182
|
+
* Parameters for predicates, tailored to each field type.
|
|
183
|
+
*/
|
|
57
184
|
/**
|
|
58
185
|
* Parameters for predicates, tailored to each field type.
|
|
59
186
|
*/
|
|
@@ -69,7 +196,7 @@ type PredicateParameters<T extends FieldType> = T extends "string" ? string | st
|
|
|
69
196
|
maxItems: number;
|
|
70
197
|
} : T extends "object" ? {
|
|
71
198
|
schema: Record<string, unknown>;
|
|
72
|
-
} : T extends "dynamic" ? any : never;
|
|
199
|
+
} : T extends "record" ? Record<string, unknown> : T extends "dynamic" ? any : never;
|
|
73
200
|
/** @deprecated Use PredicateParameters instead. */
|
|
74
201
|
type ConstraintParameters<T extends FieldType> = PredicateParameters<T>;
|
|
75
202
|
/**
|
|
@@ -120,6 +247,9 @@ interface FieldDefinition<T> {
|
|
|
120
247
|
};
|
|
121
248
|
description?: string;
|
|
122
249
|
unique?: boolean;
|
|
250
|
+
hint?: {
|
|
251
|
+
input: InputHint;
|
|
252
|
+
};
|
|
123
253
|
}
|
|
124
254
|
/**
|
|
125
255
|
* Condition for partial indexes, allowing conditional indexing based on field values.
|
|
@@ -170,6 +300,7 @@ interface SchemaDefinition {
|
|
|
170
300
|
/** @deprecated Use dependencies in DomainModel instead. */
|
|
171
301
|
dependencies?: string[];
|
|
172
302
|
migrations?: Array<Migration<any>>;
|
|
303
|
+
hint?: SchemaHint;
|
|
173
304
|
mock?: <T>(faker: typeof _faker_js_faker) => Generator<T, void, unknown>;
|
|
174
305
|
}
|
|
175
306
|
/**
|
|
@@ -1411,4 +1542,22 @@ declare function docgen(schema: SchemaDefinition, options?: {
|
|
|
1411
1542
|
faker?: Faker;
|
|
1412
1543
|
}): string;
|
|
1413
1544
|
|
|
1414
|
-
|
|
1545
|
+
/**
|
|
1546
|
+
* Represents a group of field definitions with optional metadata.
|
|
1547
|
+
*/
|
|
1548
|
+
interface FieldGroup {
|
|
1549
|
+
name: string;
|
|
1550
|
+
label: string;
|
|
1551
|
+
description?: string;
|
|
1552
|
+
fields: FieldDefinition<any>[];
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Extracts all field definitions from a schema, organized into groups based on hint.input.group,
|
|
1556
|
+
* including those in nested schemas, with proper path prefixing to represent the field hierarchy.
|
|
1557
|
+
*
|
|
1558
|
+
* @param schema - The schema definition to extract fields from
|
|
1559
|
+
* @returns Array of field groups, each containing grouped field definitions
|
|
1560
|
+
*/
|
|
1561
|
+
declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
|
|
1562
|
+
|
|
1563
|
+
export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldGroup, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
|
package/index.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import{createEventBus as Vt}from"@asaidimu/events";import{createEventBus as Et}from"@asaidimu/events";import{createMatcher as Tt,createPaginator as kt,createProjector as It,createSorter as Dt}from"@asaidimu/query";var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function _(n){let e=Me(n);return e===""?[]:e.substring(1).split("/").map(Oe)}function Me(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(L).join("/"):"/"+n.split(".").map(L).join("/")}function L(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Oe(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var A=new Map;function J(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function Q(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return n;let i=J(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function Fe(n,e,t){let i=A.get(e)||_(e);A.set(e,i);let s=J(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function U(n,e,t){let i=A.get(e)||_(e);if(A.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=J(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function Z(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return;let i=J(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function X(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=U(t,i.path,i.value);break;case"remove":t=Z(t,i.path);break;case"removeValue":t=Fe(t,i.path,i.value);break;case"replace":t=U(Z(t,i.path),i.path,i.value);break;case"copy":{let s=Q(t,i.from);t=U(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=Q(t,i.from);t=U(t,i.path,s),t=Z(t,i.from);break}case"test":{let s=Q(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function it(n,e){let t=[];return ee(n,e,"",t),t}function ee(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?je(n,e,t,i):Ne(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function je(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ee(n[r],e[r],a,i)}}function Ne(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=L(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ee(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=L(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function me(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=Ve(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function Ve(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function he(n){return n&&"operator"in n&&"rules"in n}function le(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function pe(n,e){let t={...n};return te(n)&&te(e)&&Object.keys(e).forEach(i=>{te(e[i])?i in n?t[i]=pe(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function te(n){return n&&typeof n=="object"&&!Array.isArray(n)}function G(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function qe(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let v=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,v,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:v}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${G(f.parameters)}`,path:v})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],k=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let v=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:v});return}if(C!==void 0){if(g.push(...s(C,p.type,v)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...v,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,D)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...v,D.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...v,D.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:v}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,v,m,h)),p.nestedSchema.constraints?.forEach((E,D)=>{if("rules"in E)g.push(...r(E,C,d,[...v,`constraints[${D}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${G(E.parameters)}`,path:[...v,`constraints[${D}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...v,`constraints[${D}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...v,`constraints[${E}]`],h));else{let D=d[$.predicate];D?D({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${G($.parameters)}`,path:[...v,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...v,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!k.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let v=d[f.predicate];if(!v)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!v({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${G(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var O=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ie=n=>({value:n}),F=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],ye=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Ue=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},ge=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},H=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],Le=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},ae=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(...Le(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},se=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ge(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...se(a,`${e}.rules[${o}]`)):t.push(...ae(a,`${e}.rules[${o}]`))}),t},V=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...se(i,`${e}[${s}]`)):t.push(...ae(i,`${e}[${s}]`))}),t},we=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...ge(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...we(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Se=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Ue(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...H(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...we(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},z=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...Se(i,`${e}[${s}]`))),t},re=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ye(n.type,`${e}.type`)),t.push(...H(n.required,`${e}.required`,!1)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...ye(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...V(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...z(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...H(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...H(n.unique,`${e}.unique`,!1)),t},$e=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...re(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...z(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},_e=n=>{if(typeof n!="object"||n===null)return F([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...re(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...$e(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...z(e.indexes,"indexes")),e.constraints&&t.push(...V(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...be(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?F(t):ie(e)},ne=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...re(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...V(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...z(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...Se(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...se(n.constraint,`${e}.constraint`)):t.push(...ae(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...$e(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},Je=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},be=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...ne(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...ne(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...Je(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},ve={"~standard":{version:1,vendor:"xAI",validate:_e,types:{input:{},output:{}}}};var xe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return F([{message:"Migration must be an object",path:[]}]);let e=n,t=be(e,"");return t.length>0?F(t):ie(e)},types:{input:{},output:{}}}},Ee={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return F([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...ne(i,`[${s}]`))),t.length>0?F(t):ie(e)},types:{input:[],output:[]}}};function Ce(n){try{return!xe["~standard"].validate(n).issues}catch(e){throw new O("Invalid migration definition",e)}}function Te(n){try{return!Ee["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}function q(n){try{return!ve["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}var ft=q;var j=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(n).digest("hex")}};function Ge(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 He(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 ze(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 Be(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 Ke(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 We(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return Ke(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=He(e,t);return i?Be(e.parameters,n.parameters,i):!0}return!1}function Ye(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return ze(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 We(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 Qe(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);s.add(r.id);break}}function Ze(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function ke(n,e,t){if(e.length===0)throw new Error("No changes provided");Qe(e),Ze(e);let i=Ge(n),s="patch";for(let r of e){let a=Ye(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function M(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function lt(n){return n.sort(M)}var x=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},Xe=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(Xe||{}),Ie=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!q(e))throw new x("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>Ce(s)))throw new x("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>M(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>M(s.version,r.version)))}catch(s){throw s instanceof x?s:new x("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await j(t)}catch(t){throw new x("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new x("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Te(i))}catch(i){throw new x("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof x?s:new x("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?M(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=ke(e.version,t);return t.map(a=>{try{return me(a,e)}catch(o){throw new x("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return X(a,o)}catch(c){throw new x("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof x?s:new x("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new x("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,t){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let s=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new x(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new x(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new x(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new x(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new x(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof x?t:new x("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var et=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};import"@isomorphic-git/lightning-fs";import T from"isomorphic-git";import K from"isomorphic-git/http/web";import tt from"@isomorphic-git/lightning-fs";function De(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Pe(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function oe(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ce(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}import{Buffer as nt}from"buffer";window.Buffer=nt;var B=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new tt(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!q(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await j(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await j(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));M(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>M(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:oe(o.forward),backward:oe(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await j(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?De(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Pe(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ce(e.transform.forward),backward:ce(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var de=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},ue=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function W(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function Y(n,e,t,i,s){await i.init(),await T.init({fs:n,dir:e,defaultBranch:t}),await T.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.add({fs:n,dir:e,filepath:"."}),await T.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function an(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new B(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new de,h=new ue(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(I){if(console.warn(`Failed with proxy ${b}: ${I.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function k(l,y="."){return W(async()=>(await T.add({fs:d,dir:u,filepath:y}),(await T.statusMatrix({fs:d,dir:u})).some(([b,I,R])=>I!==R)?await T.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return W(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function v(l){return(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return W(async()=>{let w=(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return W(async()=>{await T.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.push({fs:d,http:K,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function D(l,y=!0){i&&await g(async w=>{try{await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.clone({fs:d,http:K,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await Y(d,u,t,c,r),await T.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await Y(d,u,t,c,r)}else await Y(d,u,t,c,r)}else await Y(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await k(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await k(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await k(`chore: delete schema ${y}`),b=await v(`${y}-`);if(i&&w){await E(t);for(let I of b)await E(I,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${I}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,I=h.get(b);return I||m.withLock(`schema:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await k("chore: sync local changes"),i){await D(t,!1),await E(t);let l=await T.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,I=h.get(b);return I||m.withLock(`migrations:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let I=await c.history(l);return h.set(w,I),I})}}}function un(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
|
|
1
|
+
import{createEventBus as qt}from"@asaidimu/events";import{createEventBus as Ct}from"@asaidimu/events";import{createMatcher as Dt,createPaginator as kt,createProjector as It,createSorter as Pt}from"@asaidimu/query";var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function _(n){let e=Oe(n);return e===""?[]:e.substring(1).split("/").map(Fe)}function Oe(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(L).join("/"):"/"+n.split(".").map(L).join("/")}function L(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Fe(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var A=new Map;function G(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function Q(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return n;let i=G(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function je(n,e,t){let i=A.get(e)||_(e);A.set(e,i);let s=G(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function U(n,e,t){let i=A.get(e)||_(e);if(A.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=G(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function Z(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return;let i=G(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function X(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=U(t,i.path,i.value);break;case"remove":t=Z(t,i.path);break;case"removeValue":t=je(t,i.path,i.value);break;case"replace":t=U(Z(t,i.path),i.path,i.value);break;case"copy":{let s=Q(t,i.from);t=U(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=Q(t,i.from);t=U(t,i.path,s),t=Z(t,i.from);break}case"test":{let s=Q(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function at(n,e){let t=[];return ee(n,e,"",t),t}function ee(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?Ne(n,e,t,i):Ve(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function Ne(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ee(n[r],e[r],a,i)}}function Ve(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=L(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ee(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=L(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function me(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=qe(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function qe(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function he(n){return n&&"operator"in n&&"rules"in n}function le(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function pe(n,e){let t={...n};return te(n)&&te(e)&&Object.keys(e).forEach(i=>{te(e[i])?i in n?t[i]=pe(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function te(n){return n&&typeof n=="object"&&!Array.isArray(n)}function J(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ue(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let v=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,v,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:v}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${J(f.parameters)}`,path:v})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],D=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let v=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:v});return}if(C!==void 0){if(g.push(...s(C,p.type,v)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...v,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,I)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...v,I.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...v,I.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:v}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,v,m,h)),p.nestedSchema.constraints?.forEach((E,I)=>{if("rules"in E)g.push(...r(E,C,d,[...v,`constraints[${I}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${J(E.parameters)}`,path:[...v,`constraints[${I}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...v,`constraints[${I}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...v,`constraints[${E}]`],h));else{let I=d[$.predicate];I?I({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${J($.parameters)}`,path:[...v,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...v,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!D.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let v=d[f.predicate];if(!v)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!v({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${J(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var O=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ie=n=>({value:n}),F=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],ye=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Le=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},ge=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},H=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],_e=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},ae=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(..._e(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},se=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ge(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...se(a,`${e}.rules[${o}]`)):t.push(...ae(a,`${e}.rules[${o}]`))}),t},V=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...se(i,`${e}[${s}]`)):t.push(...ae(i,`${e}[${s}]`))}),t},we=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...ge(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...we(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Se=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Le(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...H(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...we(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},z=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...Se(i,`${e}[${s}]`))),t},re=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ye(n.type,`${e}.type`)),t.push(...H(n.required,`${e}.required`,!1)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...ye(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...V(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...z(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...H(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...H(n.unique,`${e}.unique`,!1)),t},$e=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...re(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...z(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},Ge=n=>{if(typeof n!="object"||n===null)return F([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...re(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...$e(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...z(e.indexes,"indexes")),e.constraints&&t.push(...V(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...be(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?F(t):ie(e)},ne=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...re(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...V(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...z(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...Se(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...se(n.constraint,`${e}.constraint`)):t.push(...ae(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...$e(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},Je=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},be=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...ne(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...ne(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...Je(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},ve={"~standard":{version:1,vendor:"xAI",validate:Ge,types:{input:{},output:{}}}};var xe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return F([{message:"Migration must be an object",path:[]}]);let e=n,t=be(e,"");return t.length>0?F(t):ie(e)},types:{input:{},output:{}}}},Ee={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return F([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...ne(i,`[${s}]`))),t.length>0?F(t):ie(e)},types:{input:[],output:[]}}};function Ce(n){try{return!xe["~standard"].validate(n).issues}catch(e){throw new O("Invalid migration definition",e)}}function Te(n){try{return!Ee["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}function q(n){try{return!ve["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}var mt=q;var j=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(n).digest("hex")}};function He(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function ze(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function Be(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function Ke(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function We(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function Ye(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return We(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=ze(e,t);return i?Ke(e.parameters,n.parameters,i):!0}return!1}function Qe(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return Be(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return Ye(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function Ze(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);s.add(r.id);break}}function Xe(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function De(n,e,t){if(e.length===0)throw new Error("No changes provided");Ze(e),Xe(e);let i=He(n),s="patch";for(let r of e){let a=Qe(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function M(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function pt(n){return n.sort(M)}var x=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},et=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(et||{}),ke=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!q(e))throw new x("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>Ce(s)))throw new x("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>M(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>M(s.version,r.version)))}catch(s){throw s instanceof x?s:new x("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await j(t)}catch(t){throw new x("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new x("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Te(i))}catch(i){throw new x("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof x?s:new x("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?M(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=De(e.version,t);return t.map(a=>{try{return me(a,e)}catch(o){throw new x("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return X(a,o)}catch(c){throw new x("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof x?s:new x("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new x("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,t){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let s=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new x(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new x(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new x(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new x(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new x(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof x?t:new x("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var tt=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};import"@isomorphic-git/lightning-fs";import T from"isomorphic-git";import K from"isomorphic-git/http/web";import nt from"@isomorphic-git/lightning-fs";function Ie(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Pe(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function oe(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ce(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}import{Buffer as it}from"buffer";window.Buffer=it;var B=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new nt(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!q(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await j(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await j(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));M(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>M(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:oe(o.forward),backward:oe(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await j(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ie(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Pe(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ce(e.transform.forward),backward:ce(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var de=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},ue=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function W(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function Y(n,e,t,i,s){await i.init(),await T.init({fs:n,dir:e,defaultBranch:t}),await T.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.add({fs:n,dir:e,filepath:"."}),await T.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function sn(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new B(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new de,h=new ue(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(k){if(console.warn(`Failed with proxy ${b}: ${k.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function D(l,y="."){return W(async()=>(await T.add({fs:d,dir:u,filepath:y}),(await T.statusMatrix({fs:d,dir:u})).some(([b,k,R])=>k!==R)?await T.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return W(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function v(l){return(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return W(async()=>{let w=(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return W(async()=>{await T.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.push({fs:d,http:K,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function I(l,y=!0){i&&await g(async w=>{try{await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.clone({fs:d,http:K,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await Y(d,u,t,c,r),await T.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await Y(d,u,t,c,r)}else await Y(d,u,t,c,r)}else await Y(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await D(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await D(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await D(`chore: delete schema ${y}`),b=await v(`${y}-`);if(i&&w){await E(t);for(let k of b)await E(k,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${k}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,k=h.get(b);return k||m.withLock(`schema:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await D("chore: sync local changes"),i){await I(t,!1),await E(t);let l=await T.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,k=h.get(b);return k||m.withLock(`migrations:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let k=await c.history(l);return h.set(w,k),k})}}}function fn(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
|
|
2
2
|
* ${h.join(`
|
|
3
3
|
* `)}
|
|
4
4
|
*/
|
|
5
|
-
`},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let
|
|
5
|
+
`},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let D=g.constraints.find(f=>f.predicate==="enum"||f.predicate==="oneOf");if(D&&Array.isArray(D.parameters)){let f=`${m}${Ae(g.name)}`,p=D.parameters.map(v=>String(v));r.set(f,p)}}};c(n.fields,n.name);for(let[u,m]of Object.entries(n.nestedSchemas))c(m.fields,o(m.name));for(let[u,m]of r){i+=a(`Union type for ${u.toLowerCase()} field values`);let h=m.map(g=>`"${g}"`).join(" | ");i+=`${s}type ${u} = ${h};
|
|
6
6
|
|
|
7
|
-
`}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(
|
|
8
|
-
`;for(let[
|
|
7
|
+
`}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(D=>`@constraint ${D.name}: ${D.description||D.predicate}`)||[];i+=a(m.description,g),i+=`${s}type ${h} = {
|
|
8
|
+
`;for(let[D,f]of Object.entries(m.fields)){let p=f.constraints?.map($=>`@constraint ${$.name}: ${$.description||$.predicate}`)||[];f.unique&&p.push("@unique Ensures unique values"),f.default!==void 0&&p.push(`@default ${JSON.stringify(f.default)}`),e&&f.description?i+=a(f.description,p):p.length&&(i+=a(void 0,p)),f.deprecated&&(i+=` /** @deprecated */
|
|
9
9
|
`);let v=Re(f,n,h),C=f.required===!1?"?":"";i+=` ${f.name}${C}: ${v};
|
|
10
10
|
`}if(m.metadata&&(i+=` metadata: Record<string, any>;
|
|
11
11
|
`),i+=`};
|
|
12
12
|
|
|
13
13
|
`,m.indexes?.length){i+=a(`Available indexes for ${h}`),i+=`${s}enum ${h}IndexNames {
|
|
14
|
-
`;for(let
|
|
14
|
+
`;for(let D of m.indexes)i+=` ${D.name} = "${D.name}",
|
|
15
15
|
`;i+=`}
|
|
16
16
|
|
|
17
17
|
`}}let d=n.constraints?.map(u=>`@constraint ${u.name}: ${u.description||u.predicate}`)||[];i+=a(n.description,d),i+=`${s}type ${n.name} = {
|
|
18
18
|
`;for(let[u,m]of Object.entries(n.fields)){let h=m.constraints?.map(f=>`@constraint ${f.name}: ${f.description||f.predicate}`)||[];m.unique&&h.push("@unique Ensures unique values"),m.default!==void 0&&h.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=a(m.description,h):h.length&&(i+=a(void 0,h)),m.deprecated&&(i+=` /** @deprecated */
|
|
19
|
-
`);let g=Re(m,n,n.name),
|
|
19
|
+
`);let g=Re(m,n,n.name),D=m.required===!1?"?":"";i+=` ${m.name}${D}: ${g};
|
|
20
20
|
`}if(n.metadata&&(i+=` metadata: Record<string, any>;
|
|
21
21
|
`),i+=`};
|
|
22
22
|
|
|
23
23
|
`,n.indexes?.length){i+=a(`Available indexes for ${n.name}`),i+=`${s}enum ${n.name}IndexNames {
|
|
24
24
|
`;for(let u of n.indexes)i+=` ${u.name} = "${u.name}",
|
|
25
25
|
`;i+=`}
|
|
26
|
-
`}return i}function Re(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${Ae(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${fe(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${fe(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return fe(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function Ae(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function fe(n){return n.charAt(0).toUpperCase()+n.slice(1)}function
|
|
26
|
+
`}return i}function Re(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${Ae(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${fe(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${fe(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return fe(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function Ae(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function fe(n){return n.charAt(0).toUpperCase()+n.slice(1)}function mn(n,e=!0){let i=`${e?"export ":""}interface ${n.name}Validator {
|
|
27
27
|
`;return i+=` /**
|
|
28
28
|
* Validates a ${n.name} object against all schema constraints
|
|
29
29
|
* @param data The data to validate
|
|
@@ -38,7 +38,7 @@ import{createEventBus as Vt}from"@asaidimu/events";import{createEventBus as Et}f
|
|
|
38
38
|
*/
|
|
39
39
|
`,i+=` isType(data: any): data is ${n.name};
|
|
40
40
|
`,i+=`}
|
|
41
|
-
`,i}function
|
|
41
|
+
`,i}function ln(n,e){let t=[],i=a=>a===void 0?"`None`":`\`${JSON.stringify(a,null,2)}\``,s=a=>{let o=`**${a.field}** ${a.operator}`;return a.value!==void 0&&(o+=` ${JSON.stringify(a.value)}`),a.conditions&&(o+=` [
|
|
42
42
|
${a.conditions.map(c=>` ${s(c)}`).join(`
|
|
43
43
|
`)}
|
|
44
44
|
]`),o},r=(a,o=1)=>{let c="#".repeat(o+2);return Object.entries(a).map(([d,u])=>{let m=`${c} ${d} (${u.type})
|
|
@@ -64,4 +64,4 @@ ${n.description}
|
|
|
64
64
|
## Migrations
|
|
65
65
|
`),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let a of n.migrations||[])t.push([a.id,a.description,a.status,a.changes.length].join("|"));if(n.mock&&e?.faker)try{let a=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(a,null,2)+"\n```")}catch{t.push(`
|
|
66
66
|
<!-- Error generating mock data -->`)}return t.join(`
|
|
67
|
-
`)}export{P as JsonPatchError,
|
|
67
|
+
`)}function yn(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(s=>{t[s.name]={label:s.label,description:s.description}}),Me(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[s,r]of Object.entries(e)){let a=s!=="ungrouped"?t[s]:void 0;i.push({name:s!=="ungrouped"?s:"ungrouped",label:a?.label||"Ungrouped",description:a?.description,fields:r})}return i}function Me(n,e,t,i){for(let[s,r]of Object.entries(n)){if(r.hint?.input?.ignore)continue;let a=e?`${e}.${r.name}`:r.name,o={...r,name:a},c=r.hint?.input?.group||"ungrouped";if(i[c]||(i[c]=[]),i[c].push(o),r.nestedSchema?.id&&t[r.nestedSchema.id]){let d=t[r.nestedSchema.id];Me(d.fields,a,t,i)}}}export{P as JsonPatchError,ke as MigrationEngine,x as MigrationError,et as MigrationErrorCode,B as SchemaRegistry,X as applyPatch,De as calculateNextVersion,M as compareSemanticVersions,sn as createGitSchemaRegistry,at as createPatch,tt as createSchemaMigrationHelper,Ue as createStandardSchemaValidator,pe as deepMerge,ln as docgen,yn as extractInputFieldGroups,j as generateSHA256Hash,mn as generateValidationInterface,Oe as normalizePath,me as schemaChangeToPatch,fn as schemaToTypes,J as serializeParams,pt as sortSemanticVars,mt as validate,Ce as validateMigration,Te as validateSchemaChange,q as validateSchemaDefinition};
|