@asaidimu/anansi 4.0.2 → 8.6.3
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/README.md +204 -685
- package/index.cjs +1 -65
- package/index.d.cts +926 -2192
- package/index.d.mts +1081 -0
- package/index.mjs +1 -0
- package/package.json +31 -37
- package/LICENSE.md +0 -21
- package/index.d.ts +0 -2347
- package/index.js +0 -65
package/index.cjs
CHANGED
|
@@ -1,65 +1 @@
|
|
|
1
|
-
"use strict";var tt=Object.create;var Z=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var rt=(t,e)=>{for(var n in e)Z(t,n,{get:e[n],enumerable:!0})},Ie=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of it(e))!at.call(t,a)&&a!==n&&Z(t,a,{get:()=>e[a],enumerable:!(i=nt(e,a))||i.enumerable});return t};var K=(t,e,n)=>(n=t!=null?tt(st(t)):{},Ie(e||!t||!t.__esModule?Z(n,"default",{value:t,enumerable:!0}):n,t)),ot=t=>Ie(Z({},"__esModule",{value:!0}),t);var Vt={};rt(Vt,{JsonPatchError:()=>M,MigrationEngine:()=>xe,MigrationError:()=>A,MigrationErrorCode:()=>Be,SchemaRegistry:()=>Y,applyPatch:()=>ie,calculateNextVersion:()=>Te,compareSemanticVersions:()=>j,createGitSchemaRegistry:()=>Ot,createPatch:()=>ut,createSchemaMigrationHelper:()=>Ke,createStandardSchemaValidator:()=>Oe,deepMerge:()=>ye,docgen:()=>Nt,extractInputFieldGroups:()=>Ft,formResolver:()=>ht,generateSHA256Hash:()=>L,normalizePath:()=>Fe,schemaChangeToPatch:()=>he,schemaDefaults:()=>Pt,schemaToTypes:()=>jt,serializeParams:()=>U,sortSemanticVars:()=>At,validate:()=>wt,validateMigration:()=>ve,validateSchemaChange:()=>Ee,validateSchemaDefinition:()=>z});module.exports=ot(Vt);var It=require("@asaidimu/events");var Rt=require("@asaidimu/events"),re=require("@asaidimu/query");var M=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function te(t){let e=Fe(t);return e===""?[]:e.substring(1).split("/").map(ct)}function Fe(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(ee).join("/"):"/"+t.split(".").map(ee).join("/")}function ee(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function ct(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var N=new Map;function ne(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new M(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let a=i==="-"?n.length:parseInt(i);if(isNaN(a)||a<0||a>n.length)throw new M(`Invalid array index: ${i}`);n=n[a]}else{if(!n.hasOwnProperty(i))throw new M(`Property ${i} not found`);n=n[i]}}return n}function fe(t,e){let n=N.get(e)||te(e);if(N.set(e,n),n.length===0)return t;let i=ne(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);if(isNaN(r)||r<0||r>=i.length)throw new M(`Invalid array index: ${a}`);return i[r]}return i[a]}function dt(t,e,n){let i=N.get(e)||te(e);N.set(e,i);let a=ne(t,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(s=>s!==n)):a[r]===n&&delete a[r],t}function X(t,e,n){let i=N.get(e)||te(e);if(N.set(e,i),i.length===0)return n;let a=i.slice(0,-1),r=i[i.length-1],s=ne(t,a);if(Array.isArray(s))if(r==="-")s.push(n);else{let o=parseInt(r);if(o<0||o>s.length)throw new M(`Invalid array index: ${r}`);s.splice(o,0,n)}else s[r]=n;return t}function le(t,e){let n=N.get(e)||te(e);if(N.set(e,n),n.length===0)return;let i=ne(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);i.splice(r,1)}else delete i[a];return t}function ie(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=X(n,i.path,i.value);break;case"remove":n=le(n,i.path);break;case"removeValue":n=dt(n,i.path,i.value);break;case"replace":n=X(le(n,i.path),i.path,i.value);break;case"copy":{let a=fe(n,i.from);n=X(n,i.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=fe(n,i.from);n=X(n,i.path,a),n=le(n,i.from);break}case"test":{let a=fe(n,i.path);if(JSON.stringify(a)!==JSON.stringify(i.value))throw new M("Test operation failed");break}default:throw new M(`Unsupported operation: ${i.op}`)}}catch(a){throw a instanceof M&&(a.operation=i),a}return n}function ut(t,e){let n=[];return me(t,e,"",n),n}function me(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?ft(t,e,n,i):lt(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function ft(t,e,n,i){let a=Math.max(t.length,e.length);for(let r=0;r<a;r++){let s=`${n}/${r}`;r>=t.length?i.push({op:"add",path:`${n}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:s}):me(t[r],e[r],s,i)}}function lt(t,e,n,i){let a=new Set,r=Object.keys(t),s=Object.keys(e);for(let o of r){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(me(t[o],e[o],u,i),a.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!a.has(o)){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function he(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([a,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?n.push({op:"replace",path:`${i}/${a}`,value:r}):n.push({op:"replace",path:`${i}/${a}`,value:r})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`/indexes/${i}/${a}`,value:r})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(a=>Array.isArray(a)?a.some(r=>r.name===t.name):a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=mt(e,t.name);i&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`${i}/${a}`,value:r})});break}}return n}function mt(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(Pe(i)){let a=Me(i.rules,e);if(a)return`/constraints/${n}${a}`}}return null}function Pe(t){return t&&"operator"in t&&"rules"in t}function Me(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(Pe(i)){let a=Me(i.rules,e);if(a)return`/rules/${n}${a}`}}return null}function ye(t,e){let n={...t};return pe(t)&&pe(e)&&Object.keys(e).forEach(i=>{pe(e[i])?i in t?n[i]=ye(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function pe(t){return t&&typeof t=="object"&&!Array.isArray(t)}var ge=new Map;function U(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function Oe(t,e){let n=o=>({value:o}),i=o=>({issues:o}),a=(o,c,u,f)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:u}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:u}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:u}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:u}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:u}]:[];case"enum":return f?.values?f.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(f.values)}, got ${o}`,path:u}]:[{message:"Enum type requires 'values' definition",path:u}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:u}]:[];case"record":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];case"union":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected union (object), got ${typeof o}`,path:u}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];default:return[{message:`Unknown type '${c}'`,path:u}]}};function r(o,c,u,f,b){let p=[],v=o.rules.map((m,g)=>{let y=[...f,`rules[${g}]`],$=`${m.name}@${y.join(".")}`;if("rules"in m){if(b.has($))return!0;b.add($);let h=r(m,c,u,y,b);return p.push(...h),b.delete($),h.length===0}else{let h=u[m.predicate];if(!h)return p.push({message:`Predicate '${m.predicate}' not found`,path:y}),!1;let E=`${m.predicate}:${JSON.stringify(m.parameters)}:${JSON.stringify(c[m.field])}`;if(ge.has(E)){let d=ge.get(E);return d||p.push({message:m.errorMessage||`Constraint '${m.name}' failed with params ${U(m.parameters)}`,path:y}),d}let S=h({data:c,field:m.field,arguments:m.parameters});return ge.set(E,S),S||p.push({message:m.errorMessage||`Constraint '${m.name}' failed with params ${U(m.parameters)}`,path:y}),S}});return(()=>{switch(o.operator){case"and":return v.every(m=>m);case"or":return v.some(m=>m);case"not":return!v.every(m=>m);case"nor":return!v.some(m=>m);case"xor":return v.filter(m=>m).length===1}})()||p.push({message:`Constraint group '${o.name}' failed`,path:f}),p}function s(o,c,u,f,b,p=new Set){let v=[];if("type"in c&&!("fields"in c)){let g=f.length>0?o[f[f.length-1]]:o;return v.push(...a(g,c.type,f,{values:c.values})),c.constraints&&c.constraints.forEach((y,$)=>{if("rules"in y)v.push(...r(y,{value:g},u,[...f,`constraints[${$}]`],p));else{let h=u[y.predicate];h?h({data:{value:g},field:"value",arguments:y.parameters})||v.push({message:y.errorMessage||`Constraint '${y.name}' failed with params ${U(y.parameters)}`,path:[...f,`constraints[${$}]`]}):v.push({message:`Predicate '${y.predicate}' not found`,path:[...f,`constraints[${$}]`]})}}),v}let C={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))C=c.fields;else{let g=c.fields,y=g.find(h=>!h.when);y&&Object.assign(C,y.fields);let $=g.find(h=>h.when&&o[h.when.field]!==void 0&&o[h.when.field]===h.when.value);if($)Object.assign(C,$.fields);else if(!y)return v.push({message:"No matching field set found for discriminated schema",path:f}),v}else C=c.fields;let m=new Set(Object.values(C).map(g=>g.name));Object.entries(C).forEach(([g,y])=>{let $=[...f,y.name],h=Object.hasOwnProperty.call(o,y.name)?o[y.name]:y.default!==void 0?y.default:void 0;y.required&&h==null&&v.push({message:`Field '${y.name}' is required`,path:$});let E=y.schema||y.nestedSchema;if(y.type==="object"&&E&&!Array.isArray(E)){let S=b[E.id];if(S)if(p.has(E.id))v.push({message:`Circular reference detected at '${E.id}'`,path:$});else{p.add(E.id);let d=h&&typeof h=="object"&&!Array.isArray(h)?h:{};v.push(...s(d,S,u,$,b,p)),E.constraints?.forEach((l,w)=>{if("rules"in l)v.push(...r(l,d,u,[...$,`constraints[${w}]`],p));else{let T=u[l.predicate];T?T({data:d,field:void 0,arguments:l.parameters})||v.push({message:l.errorMessage||`Constraint '${l.name}' failed with params ${U(l.parameters)}`,path:[...$,`constraints[${w}]`]}):v.push({message:`Predicate '${l.predicate}' not found`,path:[...$,`constraints[${w}]`]})}}),p.delete(E.id)}else v.push({message:`Nested schema '${E.id}' not found`,path:$})}if(y.type==="union"&&E&&Array.isArray(E)){let S=!1,d=[];E.forEach((l,w)=>{let T=b[l.id];if(T)if(p.has(l.id))d.push({message:`Circular reference detected at '${l.id}'`,path:[...$,w.toString()]});else{p.add(l.id);let D=h&&typeof h=="object"&&!Array.isArray(h)?h:{},k=s(D,T,u,$,b,new Set(p));k.length===0&&h!==void 0?(S=!0,l.constraints?.forEach((R,F)=>{if("rules"in R){let P=r(R,D,u,[...$,`constraints[${F}]`],p);P.length>0&&(S=!1,d.push(...P))}else{let P=u[R.predicate];P&&!P({data:D,field:void 0,arguments:R.parameters})&&(S=!1,d.push({message:R.errorMessage||`Constraint '${R.name}' failed`,path:[...$,`constraints[${F}]`]}))}})):h===void 0&&d.push(...k.filter(R=>R.message.includes("is required"))),p.delete(l.id)}else d.push({message:`Nested schema '${l.id}' not found`,path:[...$,w.toString()]})}),!S&&h!==void 0?(v.push({message:"Value does not match any union schema",path:$}),v.push(...d)):h===void 0&&v.push(...d)}h!==void 0&&(v.push(...a(h,y.type,$,{values:y.values})),(y.type==="array"||y.type==="set")&&Array.isArray(h)&&(y.constraints?.forEach((S,d)=>{let l=u[S.predicate];l&&!l({data:{[y.name]:h},field:y.name,arguments:S.parameters})&&v.push({message:S.errorMessage||`Constraint '${S.name}' failed for field '${y.name}'`,path:[...$,`constraints[${d}]`]})}),y.itemsType&&h.forEach((S,d)=>v.push(...a(S,y.itemsType,[...$,d.toString()]))),E&&!Array.isArray(E)&&(b[E.id]?h.forEach((S,d)=>{typeof S=="object"&&S!==null&&(p.has(E.id)?v.push({message:`Circular reference detected at '${E.id}'`,path:[...$,d.toString()]}):(p.add(E.id),v.push(...s(S,b[E.id],u,[...$,d.toString()],b,p)),p.delete(E.id)))}):v.push({message:`Nested schema '${E.id}' not found`,path:$}))),y.constraints?.forEach((S,d)=>{if("rules"in S)v.push(...r(S,o,u,[...$,`constraints[${d}]`],p));else{let l=u[S.predicate];l?l({data:o,field:y.name,arguments:S.parameters})||v.push({message:S.errorMessage||`Constraint '${S.name}' failed for field '${y.name}' with params ${U(S.parameters)}`,path:[...$,`constraints[${d}]`]}):v.push({message:`Predicate '${S.predicate}' not found`,path:[...$,`constraints[${d}]`]})}}))});for(let g in o)Object.hasOwnProperty.call(o,g)&&!m.has(g)&&v.push({message:`Unexpected field '${g}'`,path:[...f,g]});return c.constraints?.forEach((g,y)=>{if("rules"in g)v.push(...r(g,o,u,[...f,`constraints[${y}]`],p));else{let $=u[g.predicate];$?$({data:o,field:g.field,arguments:g.parameters})||v.push({message:g.errorMessage||`Constraint '${g.name}' failed with params ${U(g.parameters)}`,path:[...f,`constraints[${y}]`]}):v.push({message:`Predicate '${g.predicate}' not found`,path:[...f,`constraints[${y}]`]})}}),v}return t.version!=="1.0.0"&&console.warn(`Schema version '${t.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,t,e,[],t.nestedSchemas||{});return u.length>0?i(u):n(c)},types:{input:{},output:{}}}}}function ht(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(a=>{if(!a.path)return;let r=a.path.filter(o=>!o.includes("constraints")),s=i;for(let o=0;o<r.length;o++){let c=r[o];o===r.length-1?s[c]={type:"validation",message:a.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var H=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var we=t=>({value:t}),J=t=>({issues:t}),x=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],se=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:t==="dynamic"?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[e]}]:[]},pt=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},je=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},W=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],yt=(t,e,n)=>t===void 0?[]:[],Se=(t,e,n)=>{let i=[],a=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],s=t;return a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${n}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:`Unknown property ${o}`,path:[`${n}.${o}`]})}),i.push(...x(t.name,`${n}.name`)),i.push(...x(t.predicate,`${n}.predicate`)),t.field!==void 0&&typeof t.field!="string"&&i.push({message:"Field must be a string",path:[`${n}.field`]}),t.parameters!==void 0&&i.push(...yt(t.parameters,e,`${n}.parameters`)),i.push(...x(t.description,`${n}.description`,!1)),i.push(...x(t.errorMessage,`${n}.errorMessage`,!1)),i},be=(t,e,n)=>{let i=[],a=["name","operator","rules"],r=a,s=t;return a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${n}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:`Unknown property ${o}`,path:[`${n}.${o}`]})}),i.push(...x(t.name,`${n}.name`)),i.push(...je(t.operator,`${n}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?i.push({message:"Rules must be a non-empty array",path:[`${n}.rules`]}):t.rules.forEach((o,c)=>{"rules"in o?i.push(...be(o,e,`${n}.rules[${c}]`)):i.push(...Se(o,e,`${n}.rules[${c}]`))}),i},V=(t,e,n)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[n]}];let i=[];return t.forEach((a,r)=>{"rules"in a?i.push(...be(a,e,`${n}[${r}]`)):i.push(...Se(a,e,`${n}[${r}]`))}),i},Ne=(t,e)=>{let n=[],i=["operator","field"],a=["operator","field","value","conditions"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...je(t.operator,`${e}.operator`)),n.push(...x(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...Ne(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},Ve=(t,e)=>{let n=[],i=["fields","type","name"],a=["fields","type","unique","partial","description","order","name"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...pt(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...W(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...Ne(t.partial,`${e}.partial`)),n.push(...x(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},G=(t,e)=>{if(t===void 0)return[];if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,a)=>n.push(...Ve(i,`${e}[${a}]`))),n},qe=(t,e,n,i,a)=>{let r=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&r.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;r.push(...x(s.id,`${c}.id`)),i.includes(s.id)||r.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&r.push(...V(s.constraints,"dynamic",`${c}.constraints`)),s.indexes&&r.push(...G(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&a==="object")&&!Array.isArray(t)?(r.push(...x(t.id,`${e}.id`)),i.includes(t.id)||r.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&r.push(...V(t.constraints,"dynamic",`${e}.constraints`)),t.indexes&&r.push(...G(t.indexes,`${e}.indexes`))):r.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),r)},Ue=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t!="string")return[{message:"Default must be a string",path:[n]}];break;case"number":if(typeof t!="number")return[{message:"Default must be a number",path:[n]}];break;case"boolean":if(typeof t!="boolean")return[{message:"Default must be a boolean",path:[n]}];break;case"array":case"set":if(!Array.isArray(t))return[{message:"Default must be an array",path:[n]}];break;case"enum":if(!Array.isArray(t)||!t.every(i=>typeof i=="string"||typeof i=="number"))return[{message:"Default must be an array of strings or numbers",path:[n]}];break;case"object":case"record":if(typeof t!="object"||t===null)return[{message:"Default must be an object",path:[n]}];break;case"union":case"dynamic":return[]}return[]},Le=(t,e)=>t===void 0?[]:typeof t!="object"||t===null?[{message:"Hint must be an object",path:[e]}]:"input"in t&&typeof t.input!="object"?[{message:"Hint.input must be an object",path:[`${e}.input`]}]:[],ae=(t,e,n)=>{let i=[],a=["name","type"],r=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],s=t;if(a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:`Unknown property ${o}`,path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...se(t.type,`${e}.type`)),i.push(...W(t.required,`${e}.required`,!1)),t.constraints&&i.push(...V(t.constraints,t.type,`${e}.constraints`)),i.push(...Ue(t.default,t.type,`${e}.default`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...qe(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...se(t.itemsType,`${e}.itemsType`)),t.nestedSchema){i.push({message:"nestedSchema is deprecated; use schema instead",path:[`${e}.nestedSchema`]});let o=["id"],c=["id","constraints","indexes"],u=t.nestedSchema;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.nestedSchema.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:`Unknown property ${f}`,path:[`${e}.nestedSchema.${f}`]})}),i.push(...x(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...V(t.nestedSchema.constraints,"dynamic",`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...G(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...W(t.deprecated,`${e}.deprecated`,!1)),t.reference){i.push({message:"reference is deprecated",path:[`${e}.reference`]});let o=["schema","field"],c=["schema","field"],u=t.reference;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.reference.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:`Unknown property ${f}`,path:[`${e}.reference.${f}`]})}),i.push(...x(t.reference.schema,`${e}.reference.schema`)),i.push(...x(t.reference.field,`${e}.reference.field`))}return i.push(...x(t.description,`${e}.description`,!1)),i.push(...W(t.unique,`${e}.unique`,!1)),t.hint&&i.push(...Le(t.hint,`${e}.hint`)),i},_e=(t,e,n)=>{let i=[];if("type"in t&&["string","number","boolean","array","set","enum","record"].includes(t.type)){let r=["name","type"],s=["name","type","default","schema","itemsType","constraints","description","metadata"],o=t;r.forEach(c=>{o[c]===void 0&&i.push({message:`${c} is required`,path:[`${e}.${c}`]})}),Object.keys(o).forEach(c=>{s.includes(c)||i.push({message:`Unknown property ${c}`,path:[`${e}.${c}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...se(t.type,`${e}.type`)),i.push(...Ue(t.default,t.type,`${e}.default`)),t.schema&&i.push(...qe(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...se(t.itemsType,`${e}.itemsType`)),t.constraints&&i.push(...V(t.constraints,t.type,`${e}.constraints`)),i.push(...x(t.description,`${e}.description`,!1)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]})}else{let r=["name"],s=["name","description","concrete","fields","indexes","constraints","metadata"],o=t;r.forEach(c=>{o[c]===void 0&&i.push({message:`${c} is required`,path:[`${e}.${c}`]})}),Object.keys(o).forEach(c=>{s.includes(c)||i.push({message:`Unknown property ${c}`,path:[`${e}.${c}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...W(o.concrete,`${e}.concrete`,!1)),o.concrete&&Array.isArray(o.fields)&&i.push({message:"Fields must be an object when concrete is true",path:[`${e}.fields`]}),Array.isArray(o.fields)?(o.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),o.fields.forEach((c,u)=>{let f=`${e}.fields[${u}]`;if(typeof c!="object"||c===null||!("fields"in c))i.push({message:"Each variant must have a 'fields' property",path:[f]});else{let b=c.fields;typeof b!="object"||b===null?i.push({message:"Fields must be a non-empty object",path:[`${f}.fields`]}):Object.entries(b).forEach(([p,v])=>{i.push(...ae(v,`${f}.fields.${p}`,n))}),c.when!==void 0&&(typeof c.when!="object"||c.when===null?i.push({message:"When must be an object",path:[`${f}.when`]}):i.push(...x(c.when.field,`${f}.when.field`)))}})):o.fields!==void 0&&(typeof o.fields!="object"||o.fields===null?i.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(o.fields).forEach(([c,u])=>{i.push(...ae(u,`${e}.fields.${c}`,n))})),i.push(...x(t.description,`${e}.description`,!1)),t.indexes&&i.push(...G(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...V(o.constraints,"dynamic",`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]})}return i},gt=t=>{if(typeof t!="object"||t===null)return J([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields"],a=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],r=e;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[s]})}),n.push(...x(e.name,"name")),n.push(...x(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...ae(c,`fields.${o}`,s))})}if(e.nestedSchemas!==void 0)if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(..._e(c,`nestedSchemas.${o}`,s)))}return n.push(...x(e.description,"description",!1)),e.indexes&&n.push(...G(e.indexes,"indexes")),e.constraints&&n.push(...V(e.constraints,"dynamic","constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(n.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...He(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),e.hint&&n.push(...Le(e.hint,"hint")),n.length>0?J(n):we(e)},$e=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...ae(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],a=["type","id","changes","nestedSchemaChanges"],r=t;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:`Unknown property ${c}`,path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...x(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...V(o.constraints,"dynamic",`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...G(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...Ve(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...be(t.constraint,"dynamic",`${e}.constraint`)):n.push(...Se(t.constraint,"dynamic",`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(..._e(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},$t=(t,e)=>{let n=[],i=["forward","backward"],a=i,r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},He=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],a=[...i,"rollback","dependencies"],r=t;i.forEach(o=>{r[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{a.includes(o)||n.push({message:`Unknown property ${o}`,path:[`${e}.${o}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...x(t.schemaVersion,`${e}.schemaVersion`)),n.push(...x(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>{n.push(...$e(o,`${e}.changes[${c}]`))}),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...$e(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...x(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...$t(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...x(t.createdAt,`${e}.createdAt`)),n.push(...x(t.checksum,`${e}.checksum`)),t.dependencies!==void 0&&(n.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${e}.dependencies`]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]})),n},Je={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:gt,types:{input:{},output:{}}}};var Ge={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return J([{message:"Migration must be an object",path:[]}]);let e=t,n=He(e,"");return n.length>0?J(n):we(e)},types:{input:{},output:{}}}},ze={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return J([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,a)=>n.push(...$e(i,`[${a}]`))),n.length>0?J(n):we(e)},types:{input:[],output:[]}}};function ve(t){try{return!Ge["~standard"].validate(t).issues}catch(e){throw new H("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function Ee(t){try{return!ze["~standard"].validate(t).issues}catch(e){throw new H("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function z(t){try{return!Je["~standard"].validate(t).issues}catch(e){throw new H("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var wt=z;var L=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function St(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function bt(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function vt(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function Et(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function Tt(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function xt(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return Tt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=bt(e,n);return i?Et(e.parameters,t.parameters,i):!0}return!1}function Ct(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return vt(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return xt(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function kt(t){let e=new Set,n=new Set,i=new Set,a=new Set;for(let r of t)switch(r.type){case"addField":if(n.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);n.add(r.id);break;case"modifyField":if(n.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(n.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);a.add(r.id);break}}function Dt(t){let e=new Set,n=new Set,i=new Set;for(let a of t)switch(a.type){case"addConstraint":let r=a.constraint,s=("name"in r,r.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(e.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);n.add(a.name);break;case"modifyConstraint":if(n.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(i.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);e.add(a.name);break}}function Te(t,e,n){if(e.length===0)throw new Error("No changes provided");kt(e),Dt(e);let i=St(t),a="patch";for(let r of e){let s=Ct(r,n);if(s==="major"){a="major";break}else s==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function j(t,e){let n=u=>u.split(".").map(f=>parseInt(f,10)||0),[i,a,r]=n(t),[s,o,c]=n(e);return i-s||a-o||r-c}function At(t){return t.sort(j)}var A=class extends Error{constructor(n,i,a,r){super(n);this.code=i;this.migrationId=a;this.cause=r;this.name="MigrationError"}},Be=(p=>(p.INVALID_SCHEMA="INVALID_SCHEMA",p.INVALID_MIGRATION="INVALID_MIGRATION",p.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",p.TIMEOUT="TIMEOUT",p.MEMORY_LIMIT="MEMORY_LIMIT",p.CONCURRENT_OPERATION="CONCURRENT_OPERATION",p.TRANSFORM_ERROR="TRANSFORM_ERROR",p.VERSION_NOT_FOUND="VERSION_NOT_FOUND",p.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",p.STREAM_ERROR="STREAM_ERROR",p.ROLLBACK_ERROR="ROLLBACK_ERROR",p.MISSING_TRANSFORM="MISSING_TRANSFORM",p))(Be||{}),xe=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!z(e))throw new A("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(a=>ve(a)))throw new A("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((a,r)=>j(a.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((a,r)=>j(a.version,r.version)))}catch(a){throw a instanceof A?a:new A("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,a)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await L(n)}catch(n){throw new A("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new A("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Ee(i))}catch(i){throw new A("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},r=this.getRelevantMigrations(n,i),s=r.reduce((c,u)=>{let f=n==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,f,u.id)},a),o=await t.processMigrationList(e,n,r);return{newSchema:s,dataPreview:o}}catch(a){throw a instanceof A?a:new A("Dry run failed","INVALID_SCHEMA",void 0,a)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let a=e==="forward"?"pending":"applied",r=n?j(i.schemaVersion,n)>=0:!0;return i.status===a&&r}).sort((i,a)=>e==="forward"?i.id.localeCompare(a.id):a.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let a=Te(e.version,n);return n.map(s=>{try{return he(s,e)}catch(o){throw new A("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ie(s,o)}catch(c){throw new A("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:a})}catch(a){throw a instanceof A?a:new A("Schema update failed","INVALID_SCHEMA",i,a)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new A("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let a=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return n;for(let o=0;o<r;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",a);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new A(`Failed to resolve transform for migration ${s.id}`,"TRANSFORM_ERROR",s.id,o)}}))).filter(s=>!!s.transform).reduce((s,{migration:o,transform:c})=>s.pipeThrough(new TransformStream({async transform(u,f){try{let b=await c(u);f.enqueue(b)}catch(b){f.error(new A(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,b))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new A(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let a=await i.text();if(typeof window<"u"){let r=new Blob([a],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[n]}else{let{runInNewContext:r}=await import("vm"),s={module:{exports:{}},console};return r(a,s,e),s.module.exports[n]}}catch(i){throw new A(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new A(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,a)=>this.applySchemaChanges(i,[a]),this.currentSchema)}catch(n){throw n instanceof A?n:new A("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var Ke=t=>{let e=[],n=[];return{addField:(i,a)=>{e.push({type:"addField",id:i,definition:a}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let a=t.fields[i];a&&n.push({type:"addField",id:i,definition:a})},modifyField:(i,a)=>{e.push({type:"modifyField",id:i,changes:a});let r=t.fields[i];r&&n.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let a=t.indexes?.find(r=>r.name===i);a&&n.push({type:"addIndex",definition:a})},modifyIndex:(i,a)=>{e.push({type:"modifyIndex",name:i,changes:a});let r=t.indexes?.find(s=>s.name===i);r&&n.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let a=t.constraints?.find(r=>"name"in r&&r.name===i);a&&n.push({type:"addConstraint",constraint:a})},modifyConstraint:(i,a)=>{e.push({type:"modifyConstraint",name:i,changes:a});let r=t.constraints?.find(s=>"name"in s&&s.name===i);r&&n.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,a)=>{e.push({type:"addNestedSchema",id:i,definition:a}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{if(e.push({type:"removeNestedSchema",id:i}),!t.nestedSchemas)return;let a=t.nestedSchemas[i];a&&n.push({type:"addNestedSchema",id:i,definition:a})},modifyNestedSchema:(i,a)=>{if(e.push({type:"modifyNestedSchema",id:i,changes:a}),!t.nestedSchemas)return;let r=t.nestedSchemas[i];r&&n.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:n})}};var Tn=require("@isomorphic-git/lightning-fs"),I=K(require("isomorphic-git"),1),Q=K(require("isomorphic-git/http/web"),1);var Ze=K(require("@isomorphic-git/lightning-fs"),1);function We(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function Ye(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function Ce(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),a=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,s;return n?(r=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(r=i[1],s=i[2].trim()):a?(r=a[2],s=a[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:s,type:n?"arrow":i?"function":a?"method":"unknown"})}function ke(t){let{params:e,body:n,type:i}=JSON.parse(t),a=new Function(e,n);return i==="arrow"&&Object.defineProperty(a,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),a}function Ft(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(a=>{n[a.name]={label:a.label,description:a.description}}),De(t.fields,"",t.nestedSchemas||{},e,!0);let i=[];for(let[a,r]of Object.entries(e)){let s=a!=="ungrouped"?n[a]:void 0;i.push({name:a!=="ungrouped"?a:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:r})}return i}function De(t,e,n,i,a,r){if(Array.isArray(t))t.forEach(s=>{let o=s.when?e?`${e}.${s.when?.field}`:s.when?.field:void 0;De(s.fields,e,n,i,a,o?{[o]:s.when?.value}:void 0)});else for(let[s,o]of Object.entries(t)){if(o.hint?.input.ignore)continue;let c=e?`${e}.${o.name}`:o.name,f=o.required===!0&&a,b={...o,name:c,required:f};if(r&&(b.when=r),o.type!=="object"){let p=o.hint?.input?.group||"ungrouped";i[p]||(i[p]=[]),i[p].push(b)}if(o.schema&&"id"in o.schema&&n[o.schema.id]){let p=n[o.schema.id];De(p.fields,c,n,i,f,r)}}}function Pt(t,e){let n={},i=t.nestedSchemas||{};for(let[a,r]of Object.entries(t.fields))n[a]=oe(r,i,e);return n}function oe(t,e,n){if("default"in t&&t.default!==void 0)return t.default;if(n?.resolver){let i=n.resolver(t);if(i!==void 0)return i}switch(t.type){case"string":return;case"number":return;case"boolean":return!1;case"array":return[];case"set":return[];case"enum":if(!t.values||t.values.length===0)throw new Error(`Enum field "${t.name}" requires non-empty values array`);return t.values[0];case"object":if(!t.schema||!("id"in t.schema)||!e[t.schema.id])throw new Error(`Object field "${t.name}" references invalid nested schema`);return Qe(e[t.schema.id],e,n);case"record":return{};case"union":if(!t.schema||!Array.isArray(t.schema)||t.schema.length===0)throw new Error(`Union field "${t.name}" requires non-empty schema array`);let i=n?.discriminator?.[t.name],a=t.schema[0];if(i!==void 0)for(let r of t.schema){let o=e[r.id].fields;if(Mt(o,i)){a=r;break}}return Qe(e[a.id],e,n);case"dynamic":return{};default:throw new Error(`Unsupported field type "${t.type}" for field "${t.name}"`)}}function Mt(t,e){if(Array.isArray(t)){for(let n of t)for(let i of Object.values(n.fields))if(i.type==="enum"&&i.values?.includes(e)||i.default===e)return i}else for(let n of Object.values(t))if(n.type==="enum"&&n.values?.includes(e)||n.default===e)return n}function Qe(t,e,n){let i={},a=n?.discriminator||{};if(Array.isArray(t.fields)){let r=t.fields.filter(o=>!o.when);for(let o of r)for(let[c,u]of Object.entries(o.fields))i[c]=oe(u,e,n);let s=t.fields.filter(o=>o.when);for(let o of s){let c=o.when.field,u=o.when.value;if(a[c]===u)for(let[b,p]of Object.entries(o.fields))i[b]=oe(p,e,n)}}else for(let[r,s]of Object.entries(t.fields))i[r]=oe(s,e,n);return i}var Xe=require("buffer");typeof window<"u"&&(window.Buffer=Xe.Buffer);var Y=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new Ze.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!z(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,a=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let s=await L(r);await this.updateIndex(i,e,s,a,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let a=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(a))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(a,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(r.migrations=await this.migrations({name:e,version:n})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let a=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await L(a)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),a=n||i.version,r=[];for(let[s,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let u=JSON.parse(String(await this.fsp.readFile(c,"utf8")));j(u.schemaVersion,a)<=0&&r.push(this.deserializeMigration(u))}}return r.sort((s,o)=>j(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async a=>({...i,version:a.version,description:a.description,migrations:await this.migrations({name:e,version:a.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let a={...i};if(i.transform?.forward){let o=i.transform;a.transform={forward:Ce(o.forward),backward:Ce(o.backward||(c=>c))}}let r=JSON.stringify(a),s=await L(r);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,r,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?We(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ye(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ke(e.transform.forward),backward:ke(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,a,r){let s=`${e}/index.json`,o=r==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(r==="create"?"Initial version":"Updated version"),migrations:a.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,a.forEach(({id:c,hash:u,checksum:f})=>{o.migrations[c]={hash:u,checksum:f}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let a=`${e}/${i}`;(await this.fsp.stat(a)).isDirectory()?await this.rmdirRecursive(a):await this.fsp.unlink(a)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let a of i){let r=`${e}/${a}`;(await this.fsp.stat(r)).isDirectory()?n.push(...await this.listFilesRecursive(r)):n.push(r)}return n}};var Ae=class{locks=new Map;async acquire(e){let n,i=new Promise(r=>{n=r}),a=this.locks.get(e)||Promise.resolve();return this.locks.set(e,a.then(()=>i)),await a,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},Re=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function ce(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function de(t,e,n,i,a){await i.init(),await I.default.init({fs:t,dir:e,defaultBranch:n}),await I.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await I.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await I.default.add({fs:t,dir:e,filepath:"."}),await I.default.commit({fs:t,dir:e,message:"chore: initial commit",author:a})}async function Ot(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,a=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new Y(t),u=c.fs,f=t.startsWith("/")?t:`/${t}`,b=new Ae,p=new Re(e.cacheTtl);async function v(d,l){let w=o;do{let T=s[o];try{return await d(T)}catch(D){if(console.warn(`Failed with proxy ${T}: ${D.message}`),o=(o+1)%s.length,o===w)throw new Error(`${l}: All CORS proxies failed`)}}while(!0)}async function C(d,l="."){return ce(async()=>(await I.default.add({fs:u,dir:f,filepath:l}),(await I.default.statusMatrix({fs:u,dir:f})).some(([T,D,k])=>D!==k)?await I.default.commit({fs:u,dir:f,message:d,author:r}):null),"Failed to commit changes")}async function m(d,l,w){return ce(async()=>{if(await g(d))throw new Error(`Tag ${d} already exists`);await I.default.annotatedTag({fs:u,dir:f,ref:d,message:l,tagger:r,object:w})},`Failed to create tag ${d}`)}async function g(d){try{return(await I.default.listTags({fs:u,dir:f})).includes(d)}catch{return!1}}async function y(d){return(await I.default.listTags({fs:u,dir:f})).filter(T=>T.startsWith(d))}async function $(d){return ce(async()=>{let w=(await I.default.listTags({fs:u,dir:f})).filter(T=>T.startsWith(d));for(let T of w)await I.default.deleteTag({fs:u,dir:f,ref:T});return w},`Failed to delete tags with prefix ${d}`)}async function h(d){return ce(async()=>{await I.default.checkout({fs:u,dir:f,ref:d})},`Failed to checkout ${d}`)}async function E(d,{delete:l=!1,force:w=!1}={}){i&&await v(async T=>{await I.default.push({fs:u,http:Q.default,dir:f,ref:d,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:T,delete:l,force:w})},`Failed to push ${d}`)}async function S(d,l=!0){i&&await v(async w=>{try{await I.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(T){if(!l)console.warn(`Fast-forward pull failed for ${d}, attempting regular pull`),await I.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw T}},`Failed to pull ${d}`)}if(i&&!await c.fileExists(f)){let d=f.slice(1);if(await i.exists({name:d}).catch(()=>!1))await v(async w=>{await I.default.clone({fs:u,http:Q.default,dir:f,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(a)try{i=await i.create({name:d,private:!0}),await de(u,f,n,c,r),await I.default.addRemote({fs:u,dir:f,remote:"origin",url:i.url()}),await E(n)}catch(w){console.error("Failed to create and push to remote repository:",w),await de(u,f,n,c,r)}else await de(u,f,n,c,r)}else await de(u,f,n,c,r);return{async init(){return b.withLock("init",()=>c.init())},async create(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await h(n),await c.create(d);let T=await C(`feat: create schema ${l}`);T&&await m(`${l}-${w}`,`Version ${w}`,T),p.invalidate(l)})},async update(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await h(n),await c.update(d);let T=await C(`fix: update schema ${l}`);T&&await m(`${l}-${w}`,`Version ${w}`,T),p.invalidate(l)})},async delete(d){let{name:l}=d;return b.withLock(`schema:${l}`,async()=>{await h(n),await I.default.remove({fs:u,dir:f,filepath:l}),await c.delete(d);let w=await C(`chore: delete schema ${l}`),T=await y(`${l}-`);if(i&&w){await E(n);for(let D of T)await E(D,{delete:!0,force:!0}).catch(k=>console.warn(`Failed to delete remote tag ${D}: ${k.message}`))}await $(`${l}-`),p.invalidate(l)})},async list(){return b.withLock("list",()=>c.list())},async schema(d){let{name:l,version:w}=d,T=`${l}-${w||"latest"}-${d.migrations||!1}`,D=p.get(T);return D||b.withLock(`schema:${l}`,async()=>{if(w){let R=`${l}-${w}`;if(await g(R))await h(R);else throw new Error(`Version ${w} of schema ${l} not found`)}else await h(n);let k=await c.schema(d);return p.set(T,k),k})},async stats(d){return b.withLock("stats",()=>c.stats(d))},async sync(){return b.withLock("sync",async()=>{if(await h(n),await c.sync(),await C("chore: sync local changes"),i){await S(n,!1),await E(n);let d=await I.default.listTags({fs:u,dir:f});for(let w of d)await E(w,{force:!0});let l=await I.default.listTags({fs:u,dir:f});for(let w of l)d.includes(w)||await E(w,{delete:!0})}p.invalidate()})},async migrations(d){let{name:l,version:w}=d,T=`migrations-${l}-${w||"latest"}`,D=p.get(T);return D||b.withLock(`migrations:${l}`,async()=>{if(w){let R=`${l}-${w}`;if(await g(R))await h(R);else throw new Error(`Version ${w} of schema ${l} not found`)}else await h(n);let k=await c.migrations(d);return p.set(T,k),k})},async history(d){let{name:l}=d,w=`history-${l}`,T=p.get(w);return T||b.withLock(`history:${l}`,async()=>{await h(n);let D=await c.history(d);return p.set(w,D),D})}}}function O(t){return"predicate"in t}function jt(t,e=!0,n=!0){let i="",a=n?"export ":"",r=new Map,s=new Map,o=(C,m=[])=>{if(!e||!C&&!m.length)return"";let g=C?[C]:[];return m.forEach(y=>g.push(y)),`/**
|
|
2
|
-
* ${g.join(`
|
|
3
|
-
* `)}
|
|
4
|
-
*/
|
|
5
|
-
`},c=C=>C.charAt(0).toUpperCase()+C.slice(1),u=(C,m)=>{let g=s.get(m)||new Map;for(let[y,$]of Object.entries(C))if($.type==="enum"&&Array.isArray($.values)){let h=`${m}${c($.name)}`,E=$.values.map(S=>String(S));r.set(h,E)}else if($.type==="string"&&$.constraints){let h=$.constraints.find(E=>O(E)&&(E.predicate==="enum"||E.predicate==="oneOf"));if(h&&O(h)&&Array.isArray(h.parameters)){let E=`${m}${c($.name)}`,S=h.parameters.map(d=>String(d));r.set(E,S)}}else if($.type==="record"){let h=`${m}${c($.name)}`;g.set($.name,h)}g.size>0&&s.set(m,g)};u(t.fields,t.name);for(let[C,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(g=>u(g.fields,c(m.name))):u(m.fields,c(m.name));for(let[C,m]of r){i+=o(`Union type for ${C.toLowerCase()} field values`);let g=m.map(y=>`"${y}"`).join(" | ");i+=`${a}type ${C} = ${g};
|
|
6
|
-
|
|
7
|
-
`}for(let[C,m]of Object.entries(t.nestedSchemas||{})){let g=c(m.name),y=m.constraints?.map(S=>O(S)?`@constraint ${S.name}: ${S.description||S.predicate}`:`@constraint ${S.name}`)||[];m.concrete&&y.push("@concrete Indicates a concrete schema"),i+=o(m.description,y);let $=s.get(g)||new Map,h=Array.from($.entries()).map(([S,d])=>`${d} extends Record<string, any> = Record<string, any>`).join(", "),E=$.size>0?`<${h}>`:"";if(Array.isArray(m.fields)){let S=m.fields.filter(T=>!T.when),d=m.fields.filter(T=>T.when),l="";if(S.length>0){l+=`{
|
|
8
|
-
`;for(let T of S)for(let[D,k]of Object.entries(T.fields)){let R=k.constraints?.map(q=>O(q)?`@constraint ${q.name}: ${q.description||q.predicate}`:`@constraint ${q.name}`)||[];k.unique&&R.push("@unique Ensures unique values"),k.default!==void 0&&R.push(`@default ${JSON.stringify(k.default)}`),e&&k.description?l+=o(k.description,R):R.length&&(l+=o(void 0,R)),k.deprecated&&(l+=` /** @deprecated */
|
|
9
|
-
`);let F=ue(k,t,g,$),P=k.required===!1?"?":"";l+=` ${k.name}${P}: ${F};
|
|
10
|
-
`}l+="}"}let w="";d.length>0&&(w=d.map(D=>{let k=`{
|
|
11
|
-
`;for(let[R,F]of Object.entries(D.fields)){let P=F.constraints?.map(B=>O(B)?`@constraint ${B.name}: ${B.description||B.predicate}`:`@constraint ${B.name}`)||[];F.unique&&P.push("@unique Ensures unique values"),F.default!==void 0&&P.push(`@default ${JSON.stringify(F.default)}`),e&&F.description?k+=o(F.description,P):P.length&&(k+=o(void 0,P)),F.deprecated&&(k+=` /** @deprecated */
|
|
12
|
-
`);let q=ue(F,t,g,$),et=F.required===!1?"?":"";k+=` ${F.name}${et}: ${q};
|
|
13
|
-
`}if(D.when)for(let[R,F]of Object.entries(D.when))k+=` ${R}: "${F}";
|
|
14
|
-
`;return k+="}",k}).join(" | ")),l&&w?i+=`${a}type ${g}${E} = ${l} & (${w});
|
|
15
|
-
|
|
16
|
-
`:l?i+=`${a}type ${g}${E} = ${l};
|
|
17
|
-
|
|
18
|
-
`:w&&(i+=`${a}type ${g}${E} = ${w};
|
|
19
|
-
|
|
20
|
-
`)}else{i+=`${a}type ${g}${E} = {
|
|
21
|
-
`;for(let[S,d]of Object.entries(m.fields)){let l=d.constraints?.map(D=>O(D)?`@constraint ${D.name}: ${D.description||D.predicate}`:`@constraint ${D.name}`)||[];d.unique&&l.push("@unique Ensures unique values"),d.default!==void 0&&l.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?i+=o(d.description,l):l.length&&(i+=o(void 0,l)),d.deprecated&&(i+=` /** @deprecated */
|
|
22
|
-
`);let w=ue(d,t,g,$),T=d.required===!1?"?":"";i+=` ${d.name}${T}: ${w};
|
|
23
|
-
`}m.metadata&&(i+=` metadata: Record<string, any>;
|
|
24
|
-
`),i+=`};
|
|
25
|
-
|
|
26
|
-
`}if(m.indexes?.length){i+=o(`Available indexes for ${g}`),i+=`${a}enum ${g}IndexNames {
|
|
27
|
-
`;for(let S of m.indexes)i+=` ${S.name} = "${S.name}",
|
|
28
|
-
`;i+=`}
|
|
29
|
-
|
|
30
|
-
`}}let f=t.constraints?.map(C=>O(C)?`@constraint ${C.name}: ${C.description||C.predicate}`:`@constraint ${C.name}`)||[];i+=o(t.description,f);let b=s.get(t.name)||new Map,p=Array.from(b.entries()).map(([C,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),v=b.size>0?`<${p}>`:"";i+=`${a}type ${t.name}${v} = {
|
|
31
|
-
`;for(let[C,m]of Object.entries(t.fields)){let g=m.constraints?.map(h=>O(h)?`@constraint ${h.name}: ${h.description||h.predicate}`:`@constraint ${h.name}`)||[];m.unique&&g.push("@unique Ensures unique values"),m.default!==void 0&&g.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,g):g.length&&(i+=o(void 0,g)),m.deprecated&&(i+=` /** @deprecated */
|
|
32
|
-
`);let y=ue(m,t,t.name,b),$=m.required===!1?"?":"";i+=` ${m.name}${$}: ${y};
|
|
33
|
-
`}if(t.metadata&&(i+=` metadata: Record<string, any>;
|
|
34
|
-
`),i+=`};
|
|
35
|
-
|
|
36
|
-
`,t.indexes?.length){i+=o(`Available indexes for ${t.name}`),i+=`${a}enum ${t.name}IndexNames {
|
|
37
|
-
`;for(let C of t.indexes)i+=` ${C.name} = "${C.name}",
|
|
38
|
-
`;i+=`}
|
|
39
|
-
`}return i.trim()}function ue(t,e,n,i){switch(t.type){case"string":if(t.constraints){let a=t.constraints.find(r=>O(r)&&(r.predicate==="enum"||r.predicate==="oneOf"));if(a&&O(a)&&Array.isArray(a.parameters))return`${n}${_(t.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`${_(a.name)}[]`}return`${t.itemsType}[]`}return"any[]";case"set":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`Set<${_(a.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${_(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id],r=_(a.name);return a.concrete?`string | ${r}`:r}if(t.nestedSchema){let a=e.nestedSchemas[t.nestedSchema.id],r=_(a.name);return a.concrete?`string | ${r}`:r}return t.reference?`${t.reference.schema}${t.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(t.name)||"Record<string, any>";case"union":return t.schema&&Array.isArray(t.schema)?t.schema.map(r=>{let s=e.nestedSchemas[r.id];return _(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function _(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Nt(t,e){let n=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,a=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
|
|
40
|
-
${s.conditions.map(c=>` ${a(c)}`).join(`
|
|
41
|
-
`)}
|
|
42
|
-
]`),o},r=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,f])=>{let b=`${c} ${u} (${f.type})
|
|
43
|
-
|
|
44
|
-
`;return b+=`**Required:** ${f.required?"Yes":"No"}
|
|
45
|
-
|
|
46
|
-
`,f.description&&(b+=`**Description:** ${f.description}
|
|
47
|
-
|
|
48
|
-
`),f.itemsType&&(b+=`**Item Type:** ${f.itemsType}
|
|
49
|
-
|
|
50
|
-
`),f.nestedSchema&&(b+=r(f.nestedSchema,o+1)),b}).join(`
|
|
51
|
-
`)};n.push(`# ${t.name} Schema (Version ${t.version})`),t.description&&n.push(`
|
|
52
|
-
${t.description}
|
|
53
|
-
`),n.push("## Metadata"),n.push(`- **Dependencies:** ${t.dependencies?.join(", ")||"None"}`),n.push(`- **Created:** ${new Date().toISOString()}
|
|
54
|
-
`),n.push(`## Fields
|
|
55
|
-
`),n.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),n.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,o]of Object.entries(t.fields))n.push([s,o.type,o.required?"Yes":"No",i(o.default),o.description?.replace(/\n/g," ")||"",o.deprecated?"Yes":"No",o.unique?"Yes":"No",o.constraints?.length||0].join("|"));Object.entries(t.fields).forEach(([s,o])=>{o.nestedSchema&&(n.push(`
|
|
56
|
-
### Nested Schema: ${s}
|
|
57
|
-
`),n.push(r(o.nestedSchema)))}),n.push(`
|
|
58
|
-
## Indexes
|
|
59
|
-
`),n.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),n.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of t.indexes||[])n.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?a(s.partial):"None",s.description||""].join("|"));n.push(`
|
|
60
|
-
## Constraints
|
|
61
|
-
`),t.constraints&&n.push("### Schema-level Constraints"),n.push(`
|
|
62
|
-
## Migrations
|
|
63
|
-
`),n.push("| ID | Description | Status | Changes |"),n.push("|----|-------------|--------|---------|");for(let s of t.migrations||[])n.push([s.id,s.description,s.status,s.changes.length].join("|"));if(t.mock&&e?.faker)try{let s=t.mock(e.faker).next().value;n.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{n.push(`
|
|
64
|
-
<!-- Error generating mock data -->`)}return n.join(`
|
|
65
|
-
`)}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,formResolver,generateSHA256Hash,normalizePath,schemaChangeToPatch,schemaDefaults,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("hash-wasm"),t=require("fzstd");var n=class e{kind;value;constructor(e,t){this.kind=e,this.value=t}isZero(){return this.kind===`zero`}isNull(){return this.kind===`null`}static fromJSON(t){if(t===void 0)return new e(`zero`,void 0);if(t===null)return new e(`null`,void 0);if(typeof t==`string`)return new e(`string`,t);if(typeof t==`boolean`)return new e(`boolean`,t);if(typeof t==`number`)return Number.isInteger(t)?new e(`integer`,t):new e(`float`,t);if(Array.isArray(t))return new e(`array`,t);if(typeof t==`object`)return new e(`object`,t);throw Error(`anansi: unsupported literal ${typeof t}`)}};function r(e){let t=typeof e==`string`?JSON.parse(e):e;if(!t.name)throw Error(`anansi: schema requires a name`);return t}function i(e){return!!e&&!Array.isArray(e)&&typeof e.id==`string`}function a(e){return Array.isArray(e)}function o(e){return!!e&&!Array.isArray(e)&&typeof e.id!=`string`}function s(e,t){return e?`${e}.${t}`:t}var c=class{source;nested=new Map;building=new Set;constructor(e){this.source=e}compile(){for(let e of Object.keys(this.source.schemas??{}))this.compileNested(e);return{root:this.compileFields(this.source.fields??{},[],``),schemas:this.nested}}compileNested(e){let t=this.nested.get(e);if(t)return t;if(this.building.has(e))return null;let n=(this.source.schemas??{})[e];if(!n)throw Error(`anansi: schema '${e}' not found`);this.building.add(e);try{let t=n.values&&n.values.length>0?`enum`:n.type??`unknown`,r={id:e,name:n.name,effectiveType:t,fields:[],isRecursive:!1,values:n.values,enumDef:t===`enum`?l(n.values??[],n.type):void 0};return this.nested.set(e,r),n.fields&&(r.fields=this.compileFields(n.fields,[e],``)),r.isRecursive=r.fields.some(e=>e.kind.tag===`recursive`),r}finally{this.building.delete(e)}}compileFields(e,t,n){let r=[];for(let[i,a]of Object.entries(e))r.push(this.compileField(i,a,t,n));return r}compileField(e,t,r,c){let u=t.type??`unknown`,d={id:e,name:t.name,path:s(c,t.name),type:u,required:!!t.required,deprecated:!!t.deprecated,unique:!!t.unique,nullable:t.nullable!==!1,hasDefault:!n.fromJSON(t.default).isZero(),kind:{tag:`scalar`}},f=t.schema;switch(u){case`geometry`:break;case`record`:d.kind=i(f)?{tag:`container`,c:{itemSchema:this.resolve(f.id)??void 0,record:!0}}:{tag:`container`,c:{record:!0}};break;case`array`:if(a(f))throw Error(`anansi: ${d.path}: array cannot reference multiple schemas`);if(i(f))d.kind={tag:`container`,c:{itemSchema:this.require(f.id,d.path),record:!1}};else if(o(f)){let e=f.type??`unknown`,t={itemType:e,record:!1};(f.values?.length??0)>0&&(t.itemEnum=l(f.values,e)),d.kind={tag:`container`,c:t}}else d.kind={tag:`container`,c:{record:!1}};break;case`object`:d.kind=i(f)?{tag:`object`,schema:this.require(f.id,d.path)}:o(f)?{tag:`object`,schema:this.synthesizeInline(f,e,r)}:{tag:`scalar`};break;case`union`:if(a(f)){let e=[];for(let t of f)e.push(this.require(t.id,d.path));d.kind={tag:`union`,variants:e}}else d.kind=i(f)?{tag:`object`,schema:this.require(f.id,d.path)}:{tag:`scalar`};break;case`composite`:if(a(f)){let e=[];for(let t of f)e.push(this.require(t.id,d.path));d.kind={tag:`composite`,parts:e}}else d.kind={tag:`scalar`};break;case`enum`:if((t.values?.length??0)>0)d.kind={tag:`enum`,enumDef:l(t.values,u)};else if(o(f)&&(f.values?.length??0)>0)d.kind={tag:`enum`,enumDef:l(f.values,f.type??`string`)};else if(i(f)){let e=this.resolve(f.id);d.kind=e&&e.enumDef?{tag:`enum`,enumDef:e.enumDef}:{tag:`scalar`}}else d.kind={tag:`scalar`};break;default:if(i(f)){let e=this.resolve(f.id);d.kind=e===null?{tag:`recursive`,schemaId:f.id}:e.enumDef?{tag:`enum`,enumDef:e.enumDef}:{tag:`scalar`}}}return d}resolve(e){return this.nested.has(e)?this.nested.get(e):this.building.has(e)?null:this.compileNested(e)}require(e,t){let n=this.resolve(e);if(!n)throw Error(`anansi: ${t}: unresolvable schema reference '${e}'`);return n}synthesizeInline(e,t,n){let r=`inline:${[...n,t].join(`/`)}`,i=this.nested.get(r);if(i)return i;let a={id:r,name:r,effectiveType:e.type??`object`,fields:[],isRecursive:!1};this.nested.set(r,a);let o=e.fields??{};return a.fields=this.compileFields(o,[...n,r],``),a}};function l(e,t){let n=new Map,r=[];for(let t of e)t===null||[`string`,`number`,`boolean`].includes(typeof t)?n.set(JSON.stringify(t),t):r.push(t);return{lookup:n,complex:r,expectNumeric:t===`integer`||t===`number`}}const u={TypeUnknown:0,TypeInt:1,TypeFloat:2,TypeString:3,TypeBool:4,TypeBytes:5,TypeGeometry:6,TypeRecord:7,TypeArrayUnknown:8,TypeArrayInt:9,TypeArrayFloat:10,TypeArrayString:11,TypeArrayBool:12,TypeArrayBytes:13,TypeArrayObject:14,TypeArrayGeometry:15},d={[u.TypeUnknown]:`unknown`,[u.TypeInt]:`int`,[u.TypeFloat]:`float`,[u.TypeString]:`string`,[u.TypeBool]:`bool`,[u.TypeBytes]:`bytes`,[u.TypeGeometry]:`geometry`,[u.TypeRecord]:`record`,[u.TypeArrayUnknown]:`array_unknown`,[u.TypeArrayInt]:`array_int`,[u.TypeArrayFloat]:`array_float`,[u.TypeArrayString]:`array_string`,[u.TypeArrayBool]:`array_bool`,[u.TypeArrayBytes]:`array_bytes`,[u.TypeArrayObject]:`array_object`,[u.TypeArrayGeometry]:`array_geometry`},f=16384;function p(e){return(e.raw&4294967264|(e.raw>>>28&15)<<1)>>>0}function ee(e,t,n,r,i){let a=0;return a|=(e&15)<<28,a|=(n&63)<<22,a|=(r&127)<<15,a|=(i.child&63)<<9,a|=(t&3)<<7,i.required&&(a|=64),i.hasDefault&&(a|=32),i.deprecated&&(a|=16),i.unique&&(a|=8),i.terminal&&(a|=4),i.nullable&&(a|=2),i.recursive&&(a|=1),m(a>>>0)}function m(e){return{raw:e,dt:e>>>28&15,schemaIdx:e>>>22&63,fieldIdx:e>>>15&127,childSchemaIdx:e>>>9&63,kind:e>>>7&3,required:!!(e&64),hasDefault:!!(e&32),deprecated:!!(e&16),unique:!!(e&8),terminal:!!(e&4),nullable:!!(e&2),recursive:!!(e&1)}}function te(e){switch(e){case`string`:return u.TypeString;case`number`:return u.TypeFloat;case`decimal`:return u.TypeString;case`integer`:return u.TypeInt;case`boolean`:return u.TypeBool;case`bytes`:return u.TypeBytes;default:return u.TypeUnknown}}function h(e){return e?.expectNumeric?u.TypeInt:u.TypeString}function ne(e,t){if(e)return u.TypeArrayObject;switch(t){case`string`:return u.TypeArrayString;case`number`:return u.TypeArrayFloat;case`decimal`:return u.TypeArrayString;case`integer`:return u.TypeArrayInt;case`boolean`:return u.TypeArrayBool;case`bytes`:return u.TypeArrayBytes;case`geometry`:return u.TypeArrayGeometry;case`unknown`:return u.TypeArrayUnknown;default:return u.TypeUnknown}}function re(e){let t=e.kind;if(e.type===`geometry`)return[u.TypeGeometry,0,!0];if(t.tag===`scalar`)return[te(e.type),0,!0];if(t.tag===`enum`)return[h(t.enumDef),0,!0];if(t.tag===`recursive`)return[u.TypeUnknown,1,!0];if(t.tag===`object`)return[u.TypeUnknown,1,!1];if(t.tag===`container`){let e=!t.c.itemSchema;return t.c.record?[u.TypeRecord,1,e]:[ne(t.c.itemSchema,t.c.itemType),2,e]}return t.tag===`union`?[u.TypeUnknown,3,!1]:[u.TypeUnknown,1,!1]}var ie=class{slots=[];descriptors=[];metas=[];localOffsets=[];fieldTypes=[];linkedSlots=[];assignSlot(e){if(this.slots.length>=63)throw Error(`anansi: exceeds maximum of 63 nested schemas while assigning '${e.name}'`);let t=this.slots.length;return this.slots.push({fieldStart:-1,fieldCount:-1,footprint:-1}),this.linkedSlots.push({idx:t,slot:this.slots[t],fields:[]}),t}childSlotForField(e,t){let n=e.kind;return n.tag===`recursive`?{idx:t,kindTag:n}:n.tag===`object`?{idx:this.assignSlot(n.schema),kindTag:n}:n.tag===`composite`?{idx:this.assignSlot({id:`composite:${e.path}`,name:`composite:${e.name}`,effectiveType:`object`,fields:ae(n.parts),isRecursive:!1}),kindTag:n}:n.tag===`container`&&n.c.itemSchema?{idx:this.assignSlot(n.c.itemSchema),kindTag:n}:null}linkFields(e,t){let n=this.linkedSlots[t],r=[];for(let i=0;i<e.length;i++){if(e.length>128)throw Error(`anansi: slot ${t} exceeds 128 fields`);let a=e[i],[o,s,c]=re(a),l=this.childSlotForField(a,t),u=l?l.idx:63,d=a.kind.tag===`recursive`,f=ee(o,s,t,i,{required:a.required,hasDefault:a.hasDefault,deprecated:a.deprecated,unique:a.unique,terminal:c,nullable:a.nullable,recursive:d,child:u}),p=this.descriptors.length;this.descriptors.push(f),this.fieldTypes.push(a.type);let m={meta:{name:a.name,path:a.path},fd:f,dp:0,abs:p};n.fields.push(m),this.metas.push(m.meta),!c&&u!==63&&r.push({rf:a,fd:f,childIdx:u})}for(let e of r){let t=e.rf.kind;if(t.tag===`object`||t.tag===`composite`){let n=t.tag===`object`?t.schema.fields:ae(t.parts),r=this.linkFields(n,e.childIdx);this.setSlot(e.childIdx,r.count)}else if(t.tag===`container`&&t.c.itemSchema){let n=this.linkFields(t.c.itemSchema.fields,e.childIdx);this.setSlot(e.childIdx,n.count)}let r=n.fields.find(t=>t.fd===e.fd);r.child=this.linkedSlots[e.childIdx]}return{count:e.length,slot:n}}setSlot(e,t){let n=this.slots[e];n.fieldStart===-1&&(n.fieldStart=this.descriptors.length-t),n.fieldCount=t}};function ae(e){let t=[];for(let n of e)t.push(...n.fields);return t}function oe(e){for(let t=e.slots.length-1;t>=0;t--){let n=e.slots[t];n.fieldCount<0&&(n.fieldStart=0,n.fieldCount=0);let r=0;for(let t=0;t<n.fieldCount;t++){let i=n.fieldStart+t,a=e.descriptors[i];a.terminal?r+=1:a.childSchemaIdx!==63&&(r+=e.slots[a.childSchemaIdx].footprint)}n.footprint=r}for(let t of e.slots){let n=0;for(let r=0;r<t.fieldCount;r++){let i=t.fieldStart+r,a=e.descriptors[i];e.localOffsets[i]=n,a.terminal?n+=1:a.childSchemaIdx!==63&&(n+=e.slots[a.childSchemaIdx].footprint)}}}function se(e,t,n,r){if(r.length===0)return 0;if(r.length===1){let[n,i]=r[0],a=e[n].fieldStart+i;return t[a].terminal?a+1>>>0:0}let i=f;for(let a=0;a<r.length;a++){let[o,s]=r[a],c=e[o].fieldStart+s,l=t[c];if(i+=n[c],a===r.length-1)return l.terminal?i>>>0:0;if(l.terminal)return 0}return i>>>0}function ce(e,t){return(t<<5|e<<1)>>>0}function le(e){let{root:t,schemas:n}=new c(e).compile(),r=new ie;r.slots.push({fieldStart:-1,fieldCount:-1,footprint:-1}),r.linkedSlots.push({idx:0,slot:r.slots[0],fields:[]});let i=r.linkFields(t,0);return r.slots[0].fieldStart=0,r.slots[0].fieldCount=i.count,oe(r),de(r,r.linkedSlots[0],[]),{slots:r.slots,metas:r.metas,descriptors:r.descriptors,localOffsets:r.localOffsets,fieldTypes:r.fieldTypes,root:r.linkedSlots[0],childrenByPath:ue(r.linkedSlots[0])}}function ue(e){let t=new Map;for(let n of e.fields)n.child&&t.set(n.meta.path,n.child);return t}function de(e,t,n){for(let r=0;r<t.slot.fieldCount;r++){let i=t.slot.fieldStart+r,a=e.descriptors[i],o=t.fields[r],s=[...n,[t.idx,r]],c=se(e.slots,e.descriptors,e.localOffsets,s);o.dp=c===0?p(a):ce(a.dt,c),!a.terminal&&o.child&&de(e,o.child,s)}}function fe(e){let t=(e,n,r)=>{let i=[];for(let a=0;a<e.slot.fieldCount;a++){let o=e.fields[a],s=o.fd,c=[...n,[e.idx,a]],l=r?`${r}.${o.meta.name}`:o.meta.name,f={name:o.meta.name,path:l,t:d[s.dt],dp:o.dp};if(!s.terminal&&o.child){s.dt===u.TypeArrayObject?(f.child=t(o.child,c,l),i.push(f)):i.push(...t(o.child,c,l));continue}i.push(f)}return i};return t(e.root,[],``)}function g(e,t){for(t>>>=0;t>=128;)e.push(t&127|128),t>>>=7;e.push(t)}function pe(e,t){if(!Number.isSafeInteger(t))throw Error(`anansi: integer ${t} exceeds Number.MAX_SAFE_INTEGER`);he(e,BigInt(t))}function me(e,t){for(;t>=128n;)e.push(Number(t&127n)|128),t>>=7n;e.push(Number(t))}function he(e,t){me(e,t<<1n^t>>63n)}var _=class{data;pos;constructor(e,t=0){this.data=e,this.pos=t}eof(){return this.pos>=this.data.length}remaining(){return this.data.length-this.pos}byte(){if(this.eof())throw Error(`anansi: unexpected end of buffer`);return this.data[this.pos++]}take(e){if(e<0||this.pos+e>this.data.length)throw Error(`anansi: unexpected end of buffer (need ${e}, have ${this.remaining()})`);let t=this.data.subarray(this.pos,this.pos+e);return this.pos+=e,t}uvarint(){let e=0,t=0;for(let n=0;n<10;n++){let r=this.byte();if(r<128){if(n===9&&r>1)throw Error(`anansi: varint overflow`);return(e|r<<t)>>>0}e|=(r&127)<<t,t+=7}throw Error(`anansi: varint overflow`)}uvarintBig(){let e=0n,t=0n,n=0;for(;n<10;){let r=this.byte();if(e|=BigInt(r&127)<<t,r<128)return e;t+=7n,n++}throw Error(`anansi: varint overflow`)}varint(){let e=this.uvarintBig(),t=e>>1n^-(e&1n),n=Number(t);if(!Number.isSafeInteger(n))throw Error(`anansi: decoded integer ${n} exceeds Number.MAX_SAFE_INTEGER`);return n}};const v={Unknown:0,Int:1,Float:2,String:3,Bool:4,Bytes:5,Geometry:6,Record:7,ArrayUnknown:8,ArrayInt:9,ArrayFloat:10,ArrayString:11,ArrayBool:12,ArrayBytes:13,ArrayObject:14,ArrayGeometry:15},ge=new TextEncoder,_e=new TextDecoder;function ve(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function ye(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function y(e,t){pe(e,t)}function be(e){return e.varint()}function b(e,t){let n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t,!0);for(let t=0;t<8;t++)e.push(n.getUint8(t))}function x(e){let t=e.take(8);return new DataView(t.buffer,t.byteOffset,8).getFloat64(0,!0)}function S(e,t){let n=ge.encode(t);g(e,n.length);for(let t of n)e.push(t)}function C(e){let t=e.uvarint();return _e.decode(e.take(t))}function xe(e,t){e.push(+!!t)}function Se(e){return e.byte()!==0}function w(e,t){let n=new Uint8Array(t.length+7>>3);t.forEach((e,t)=>{e&&(n[t>>3]|=1<<(t&7))});for(let t of n)e.push(t)}function T(e,t){let n=e.take(t+7>>3),r=[];for(let e=0;e<t;e++)r.push(!!(n[e>>3]&1<<(e&7)));return r}function Ce(e,t){let n=ye(t);g(e,n.length);for(let t of n)e.push(t)}function we(e){let t=e.uvarint();return ve(e.take(t))}function Te(e,t){g(e,t.length);for(let n of t){g(e,n.length/2);for(let t=0;t<n.length;t+=2)b(e,n[t]),b(e,n[t+1])}}function Ee(e){let t=e.uvarint(),n=[];for(let r=0;r<t;r++){let t=e.uvarint(),r=[];for(let n=0;n<t;n++)r.push(x(e),x(e));n.push(r)}return n}const E={Null:0,Int:v.Int,Float:v.Float,String:v.String,Bool:v.Bool,Bytes:v.Bytes,Geometry:v.Geometry,Record:v.Record,ArrUnknown:v.ArrayUnknown,ArrInt:v.ArrayInt,ArrFloat:v.ArrayFloat,ArrString:v.ArrayString,ArrBool:v.ArrayBool,ArrBytes:v.ArrayBytes};function De(e){return e.length>0&&Array.isArray(e[0])&&Array.isArray(e[0][0])}function Oe(e,t){if(t==null){e.push(E.Null);return}switch(typeof t){case`boolean`:e.push(E.Bool),xe(e,t);return;case`string`:e.push(E.String),S(e,t);return;case`number`:Number.isSafeInteger(t)?(e.push(E.Int),y(e,t)):(e.push(E.Float),b(e,t));return;case`object`:if(Array.isArray(t)){if(De(t)){e.push(E.Geometry),Te(e,t);return}if(t.every(e=>typeof e==`string`)){e.push(E.ArrString),g(e,t.length);for(let n of t)S(e,n);return}if(t.every(e=>Number.isSafeInteger(e))){e.push(E.ArrInt),g(e,t.length);for(let n of t)y(e,n);return}if(t.every(e=>typeof e==`number`)){e.push(E.ArrFloat),g(e,t.length);for(let n of t)b(e,n);return}if(t.every(e=>typeof e==`boolean`)){e.push(E.ArrBool);let n=t;g(e,n.length),w(e,n);return}e.push(E.ArrUnknown),g(e,t.length);for(let n of t)Oe(e,n);return}e.push(E.Record),Ae(e,t);return;default:throw Error(`anansi: unsupported any value ${typeof t}`)}}function ke(e){let t=e.byte();switch(t){case E.Null:return null;case E.Bool:return Se(e);case E.String:return C(e);case E.Int:return be(e);case E.Float:return x(e);case E.Bytes:return we(e);case E.Geometry:return Ee(e);case E.Record:return je(e);case E.ArrInt:{let t=e.uvarint();return Array.from({length:t},()=>be(e))}case E.ArrFloat:{let t=e.uvarint();return Array.from({length:t},()=>x(e))}case E.ArrString:{let t=e.uvarint();return Array.from({length:t},()=>C(e))}case E.ArrBool:return T(e,e.uvarint());case E.ArrUnknown:{let t=e.uvarint();return Array.from({length:t},()=>ke(e))}default:throw Error(`anansi: unknown any tag ${t}`)}}function Ae(e,t){let n=Object.keys(t).sort();g(e,n.length);for(let r of n)S(e,r),Oe(e,t[r])}function je(e){let t=e.uvarint(),n={};for(let r=0;r<t;r++){let t=C(e);n[t]=ke(e)}return n}function Me(e,t){g(e,t.length);for(let n of t)y(e,n)}function Ne(e){let t=e.uvarint();return Array.from({length:t},()=>be(e))}function Pe(e,t){g(e,t.length);for(let n of t)b(e,n)}function Fe(e){let t=e.uvarint();return Array.from({length:t},()=>x(e))}function Ie(e,t){g(e,t.length);for(let n of t)S(e,n)}function Le(e){let t=e.uvarint();return Array.from({length:t},()=>C(e))}function Re(e,t){g(e,t.length),w(e,t)}function ze(e){return T(e,e.uvarint())}function Be(e,t){g(e,t.length);for(let n of t)Ce(e,n)}function Ve(e){let t=e.uvarint();return Array.from({length:t},()=>we(e))}function He(e,t){g(e,t.length);for(let n of t)Te(e,n)}function Ue(e){let t=e.uvarint();return Array.from({length:t},()=>Ee(e))}function We(e,t){g(e,t.length);for(let n of t)Oe(e,n)}function Ge(e){let t=e.uvarint();return Array.from({length:t},()=>ke(e))}const D={Dense:0,Sparse:1,Batch:2,Stream:3};function O(e,t){let n=t.split(`.`),r=e;for(let e=0;e<n.length;e++){if(typeof r!=`object`||!r)return[!1,void 0];let t=r;if(!(n[e]in t))return[!1,void 0];r=t[n[e]]}return r===void 0?[!1,void 0]:[!0,r]}function k(e,t){let[n,r]=O(e,t.path);return!n||r===void 0?`notSet`:r===null?`null`:`value`}function Ke(e,t){let n=t.length+1;return{...e,path:e.path.slice(n)}}function qe(e,t){return e.map(e=>Ke(e,t))}function Je(e,t,n){switch(t.t){case`int`:y(e,n);break;case`float`:b(e,n);break;case`string`:S(e,n);break;case`bool`:xe(e,n);break;case`bytes`:Ce(e,n);break;case`geometry`:Te(e,n);break;case`record`:Ae(e,n);break;case`unknown`:Oe(e,n);break;case`array_int`:Me(e,n);break;case`array_float`:Pe(e,n);break;case`array_string`:Ie(e,n);break;case`array_bool`:Re(e,n);break;case`array_bytes`:Be(e,n);break;case`array_geometry`:He(e,n);break;case`array_unknown`:We(e,n);break;default:throw Error(`anansi: cannot write value for type ${t.t} field ${t.path}`)}}function Ye(e,t){switch(t.t){case`int`:return e.varint();case`float`:return x(e);case`string`:return C(e);case`bool`:return Se(e);case`bytes`:return we(e);case`geometry`:return Ee(e);case`record`:return je(e);case`unknown`:return ke(e);case`array_int`:return Ne(e);case`array_float`:return Fe(e);case`array_string`:return Le(e);case`array_bool`:return ze(e);case`array_bytes`:return Ve(e);case`array_geometry`:return Ue(e);case`array_unknown`:return Ge(e);default:throw Error(`anansi: cannot read value for type ${t.t} field ${t.path}`)}}function Xe(e,t,n,r,i){let a=qe(t,n);g(e,r.length);for(let t of r){let n=0;for(let e of a)k(t,e)!==`notSet`&&n++;let r=a.length>0?n/a.length:1,o=!(a.length<=64||r>.25),s=o?D.Sparse:D.Dense,c=(i.flags&-200|s)>>>0,l=[],u={flags:i.flags&-4|s,version:i.version};o?M(l,a,t,u):A(l,a,t,u);let d=[c,i.version,...l];g(e,d.length);for(let t of d)e.push(t)}}function Ze(e,t,n,r,i){let a=e.uvarint();for(let o=0;o<a;o++){let a=e.uvarint(),o=new _(e.take(a)),s=o.byte();o.byte();let c=i?i():{},l=s&3;if(l===D.Dense)j(o,t,c,n);else if(l===D.Sparse)N(o,t,c,n);else throw Error(`anansi: unsupported nested packet type ${l}`);r.push(c)}}const Qe={flags:D.Dense,version:0};function A(e,t,n,r=Qe){let i=2*t.length,a=new Uint8Array(i+7>>3);t.forEach((e,t)=>{let r=k(n,e)===`notSet`?0:k(n,e)===`null`?1:2;a[t>>2]|=r<<((t&3)<<1)});for(let t of a)e.push(t);let o=F(t);for(let t=0;t<=15;t++){let i=o[t];if(!(!i||i.length===0)){if(t===v.Bool){let t=[];for(let e of i)k(n,e)===`value`&&t.push(O(n,e.path)[1]);w(e,t);continue}for(let t of i)if(k(n,t)===`value`){if(t.t===`array_object`){Xe(e,t.child,t.name,O(n,t.path)[1]??[],r);continue}Je(e,t,O(n,t.path)[1])}}}}function j(e,t,n,r){let i=[],a=2*t.length,o=e.take(a+7>>3);for(let e=0;e<t.length;e++)i.push(o[e>>2]>>((e&3)<<1)&3);let s=F(t);for(let a=0;a<=15;a++){let o=s[a];if(o){if(a===v.Bool){let a=o.filter((e,n)=>i[t.indexOf(o[n])]===2).length,s=T(e,a),c=0;o.forEach(e=>{let a=t.indexOf(e);i[a]===2&&P(n,e.path,r,s[c++])});continue}for(let a of o){let o=i[t.indexOf(a)];if(o!==0){if(o===1){P(n,a.path,r,null);continue}if(a.t===`array_object`){let t=[];Ze(e,a.child,a.name,t),P(n,a.path,r,t);continue}P(n,a.path,r,Ye(e,a))}}}}}function M(e,t,n,r={flags:D.Sparse,version:0}){let i=t.filter(e=>k(n,e)!==`notSet`);g(e,i.length);for(let t of i){let i=k(n,t),a=t.dp;i===`null`?a|=1:a&=4294967294,g(e,a),i===`value`&&(t.t===`array_object`?Xe(e,t.child,t.name,O(n,t.path)[1]??[],r):Je(e,t,O(n,t.path)[1]))}}function N(e,t,n,r){let i=new Map;for(let e of t)i.set(e.dp&4294967294,e);let a=e.uvarint();for(let t=0;t<a;t++){let t=e.uvarint(),a=!!(t&1),o=i.get(t&4294967294);if(!o)throw Error(`anansi: sparse packet references unknown data point ${t}`);if(a){P(n,o.path,r,null);continue}if(o.t===`array_object`){let t=[];Ze(e,o.child,o.name,t),P(n,o.path,r,t);continue}P(n,o.path,r,Ye(e,o))}}function P(e,t,n,r){let i=t;if(n&&i.startsWith(n+`.`)){i=i.slice(n.length+1),$e(e,i.split(`.`),r);return}$e(e,i.split(`.`),r)}function $e(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];(typeof r[n]!=`object`||r[n]===null)&&(r[n]={}),r=r[n]}r[t[t.length-1]]=n}function F(e){let t=[];for(let n of e){let e=et[n.t]??v.Unknown;(t[e]??=[]).push(n)}return t}const et=Object.fromEntries(Object.entries({unknown:v.Unknown,int:v.Int,float:v.Float,string:v.String,bool:v.Bool,bytes:v.Bytes,geometry:v.Geometry,record:v.Record,array_unknown:v.ArrayUnknown,array_int:v.ArrayInt,array_float:v.ArrayFloat,array_string:v.ArrayString,array_bool:v.ArrayBool,array_bytes:v.ArrayBytes,array_object:v.ArrayObject,array_geometry:v.ArrayGeometry}));function I(e){if(e<0||e>1023)throw Error(`anansi: schema version ${e} exceeds maximum of 1023`);return{flags:e>>8<<4,version:e&255}}function L(e,t){return(e>>4&3)<<8|t}function tt(e,t,n=0,r=`auto`){let i=I(n),a=0;for(let n of e)k(t,n)!==`notSet`&&a++;let o=e.length?a/e.length:1,s=r===`sparse`||r===`auto`&&!(e.length<=64||o>.25),c=i.flags|(s?D.Sparse:D.Dense),l=[c,i.version],u={flags:c,version:i.version},d=[];return s?M(d,e,t,u):A(d,e,t,u),new Uint8Array([...l,...d])}function nt(e,t){let n=new _(e),r=n.byte(),i=n.byte();if((r>>4&3)===D.Stream)throw Error(`anansi: stream packets unsupported`);if(r&196)throw Error(`anansi: compressed/encrypted/hashed packets require transform support not enabled in this build`);let a=r&3,o={};if(a===D.Dense)j(n,t,o);else if(a===D.Sparse)N(n,t,o);else throw Error(`anansi: use batch API for packet type ${a}`);return{version:L(r,i),doc:o}}function rt(e,t,n=0){let r=I(n),i=0,a=0;for(let n of t){for(let t of e)k(n,t)!==`notSet`&&i++;a+=e.length}let o=a?i/a:1,s=e.length>64&&o<=.25,c=[r.flags|D.Batch,r.version],l=[];g(l,t.length),l.push(s?2:0);let u={flags:r.flags|D.Batch,version:r.version};for(let n of t)s?M(l,e,n,u):A(l,e,n,u);return new Uint8Array([...c,...l])}function it(e,t,n=0){let r=I(n),i=[r.flags|D.Batch|8,r.version],a=at(e,t,{flags:i[0],version:r.version});return new Uint8Array([...i,...a])}function at(e,t,n){let r=[];g(r,t.length),r.push(1);let i=F(e);for(let e=0;e<=15;e++){let a=i[e];if(!a||a.length===0)continue;let o=2*a.length*t.length,s=new Uint8Array(o+7>>3),c=0;for(let e of a)for(let n of t){let t=k(n,e),r=t===`notSet`?0:t===`null`?1:2;s[c>>3]|=r<<(c&7),c+=2}for(let e of s)r.push(e);if(e===v.Bool){for(let e of a){let n=[];for(let r of t)k(r,e)===`value`&&n.push(O(r,e.path)[1]);w(r,n)}continue}for(let e of a)for(let i of t)if(k(i,e)===`value`){if(e.t===`array_object`){Xe(r,e.child,e.name,O(i,e.path)[1]??[],n);continue}Je(r,e,O(i,e.path)[1])}}return r}function ot(e,t){let n=new _(e),r=n.byte(),i=n.byte();if((r&3)!==D.Batch)throw Error(`anansi: not a batch packet`);if(r&196)throw Error(`anansi: transformed batch packets unsupported in this build`);let a=n.uvarint(),o=n.byte(),s=Array.from({length:a},()=>({}));if(o&1||r&8)st(n,t,s);else{let e=!!(o&2);for(let r of s)e?N(n,t,r):j(n,t,r)}return{version:L(r,i),docs:s}}function st(e,t,n){let r=F(t);for(let t=0;t<=15;t++){let i=r[t];if(!i||i.length===0)continue;let a=2*i.length*n.length,o=e.take(a+7>>3),s=[],c=0;for(let e=0;e<i.length;e++){let e=[];for(let t=0;t<n.length;t++)e.push(o[c>>3]>>(c&7)&3),c+=2;s.push(e)}if(t===v.Bool){i.forEach((t,r)=>{let i=s[r].filter(e=>e===2).length,a=T(e,i),o=0;s[r].forEach((e,r)=>{if(e!==0){if(e===1){P(n[r],t.path,void 0,null);return}P(n[r],t.path,void 0,a[o++])}})});continue}i.forEach((t,r)=>{s[r].forEach((r,i)=>{if(r!==0){if(r===1){P(n[i],t.path,void 0,null);return}if(t.t===`array_object`){let r=[];Ze(e,t.child,t.name,r),P(n[i],t.path,void 0,r);return}P(n[i],t.path,void 0,Ye(e,t))}})})}}const ct=e=>e&3;let lt,ut=!1;function dt(){if(!ut){ut=!0;try{lt=globalThis.process?.getBuiltinModule?.(`node:zlib`)??void 0}catch{lt=void 0}}return lt}function ft(e){let t=dt()?.zstdCompressSync?.(e);if(!t)throw Error(`anansi: zstd compression is unavailable in this runtime (no node:zlib). Send plain packets, or provide a WASM compressor.`);return t}function pt(e,n){return dt()?.zstdDecompressSync?.(e)||(0,t.decompress)(e)}async function mt(t){let n=await(0,e.blake3)(t,128),r=new Uint8Array(16);for(let e=0;e<16;e++)r[e]=parseInt(n.slice(e*2,e*2+2),16);return r}async function ht(e){if(e.length!==32)throw Error(`anansi: AES-256-GCM requires a 32-byte key, got ${e.length}`);return crypto.subtle.importKey(`raw`,e,`AES-GCM`,!1,[`encrypt`,`decrypt`])}async function gt(e,t,n,r){let i=e;r.integrity&&(i|=128),r.compression&&(i|=4),r.encryptionKey&&(i|=64);let a=[i,t];if(r.integrity)for(let e of await mt(n))a.push(e);let o=[];if(r.compression){g(o,n.length);for(let e of ft(n))o.push(e)}else for(let e of n)o.push(e);if(!r.encryptionKey)return new Uint8Array([...a,...o]);let s=await ht(r.encryptionKey),c=crypto.getRandomValues(new Uint8Array(12)),l=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:c},s,new Uint8Array(o))),u=new Uint8Array(a.length+12+l.length);return u.set(Uint8Array.from(a),0),u.set(c,a.length),u.set(l,a.length+12),u}async function _t(e,t,n){let r;t&128&&(r=e.take(16));let i=e.data.subarray(e.pos);if(t&64){if(!n.decryptionKey)throw Error(`anansi: encrypted packet but no decryption key provided`);if(i.length<12)throw Error(`anansi: truncated nonce`);let e=i.subarray(0,12);i=i.subarray(12);let t=await ht(n.decryptionKey),r=await crypto.subtle.decrypt({name:`AES-GCM`,iv:e},t,i);i=new Uint8Array(r)}let a=i.length,o=new _(i);if(t&4){if(a=o.uvarint(),a>536870912)throw Error(`anansi: declared uncompressed size ${a} exceeds limit`);let e=pt(i.subarray(o.pos),a);if(e.length!==a)throw Error(`anansi: decompressed ${e.length} bytes, header declared ${a}`);i=e}if(r){let e=await mt(i);for(let t=0;t<16;t++)if(r[t]!==e[t])throw Error(`anansi: integrity check failed (packet digest mismatch)`)}return new _(i)}function vt(e,t){let n=0;for(let r of e){let[e,i]=yt(t,r.path);e&&i!=null&&n++}return e.length<=64||e.length===0||n/e.length>.25?`dense`:`sparse`}function yt(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return[!1,void 0];let t=n;if(!(e in t))return[!1,void 0];n=t[e]}return[n!==void 0,n]}function bt(e,t,n){let r=n===`sparse`||n===`auto`&&vt(e,t)===`sparse`,i=[];return r?M(i,e,t):A(i,e,t),new Uint8Array(i)}async function xt(e,t,n=0,r={}){let i=I(n),a=r.kind??`auto`,o=a===`sparse`||a===`auto`&&vt(e,t)===`sparse`,s=i.flags|(o?D.Sparse:D.Dense),c=bt(e,t,o?`sparse`:`dense`);return gt(s,i.version,c,r)}async function St(e,t,n={}){let r=new _(e),i=r.byte(),a=r.byte();if(i&64&&!n.decryptionKey)throw Error(`anansi: encrypted packet but no decryption key provided`);let o=await _t(r,i,n),s={},c=ct(i);if(c===D.Dense)j(o,t,s);else if(c===D.Sparse)N(o,t,s);else throw Error(`anansi: use batch API for packet type ${c}`);return{version:L(i,a),doc:s}}function Ct(e,t){let n=0,r=0;for(let i of t)for(let t of e){let[e,a]=yt(i,t.path);e&&a!=null&&n++,r++}let i=r>0?n/r:1,a=e.length>64&&i<=.25,o=[];g(o,t.length),o.push(a?2:0);for(let n of t)a?M(o,e,n):A(o,e,n);return{body:new Uint8Array(o),sparse:a}}async function wt(e,t,n=0,r={}){let i=I(n),{body:a,sparse:o}=Ct(e,t);return gt(i.flags|D.Batch|(o?2:0),i.version,a,r)}async function Tt(e,t,n=0,r={}){let i=I(n),a=i.flags|D.Batch|8,o=new Uint8Array(at(e,t,{flags:a,version:i.version}));return gt(a,i.version,o,r)}async function Et(e,t,n={}){let r=new _(e),i=r.byte(),a=r.byte();if(ct(i)!==D.Batch)throw Error(`anansi: not a batch packet`);let o=await _t(r,i,n),s=o.uvarint(),c=o.byte(),l=Array.from({length:s},()=>({}));if(c&1||i&8)st(o,t,l);else for(let e of l)c&2?N(o,t,e):j(o,t,e);return{version:L(i,a),docs:l}}var Dt=class e{linked;fields;fullVersion;kind;enc;dec;constructor(e,t,n,r,i,a){this.linked=e,this.fields=t,this.fullVersion=n,this.kind=r,this.enc=i,this.dec=a}static async create(t,n={}){let i=le(r(t));return new e(i,fe(i),n.fullVersion??0,n.kind??`auto`,{compression:n.compression,integrity:n.integrity,encryptionKey:n.encryptionKey},{decryptionKey:n.decryptionKey})}async encode(e){return this.enc.compression||this.enc.integrity||this.enc.encryptionKey?xt(this.fields,e,this.fullVersion,{...this.enc,kind:this.kind}):tt(this.fields,e,this.fullVersion,this.kind)}async decode(e){return St(e,this.fields,this.dec)}async encodeBatch(e){return this.enc.compression||this.enc.integrity||this.enc.encryptionKey?wt(this.fields,e,this.fullVersion,this.enc):rt(this.fields,e,this.fullVersion)}async decodeBatch(e){return Et(e,this.fields,this.dec)}async encodeColumnar(e){return this.enc.compression||this.enc.integrity||this.enc.encryptionKey?Tt(this.fields,e,this.fullVersion,this.enc):Tt(this.fields,e,this.fullVersion,{})}};function Ot(){return{maxDepth:20,mode:`strict`}}var R=class e{raw;constructor(e){this.raw=e}static zero(){return new e({kind:`zero`})}static fromSingle(t){return new e({kind:`single`,value:t})}static fromMultiple(t){return new e({kind:`multiple`,value:t})}static fromInline(t){return new e({kind:`inline`,value:t})}static fromFieldSchema(t){if(t==null)return e.zero();if(Array.isArray(t))return e.fromMultiple(t);let n=t;return`id`in n&&typeof n.id==`string`?e.fromSingle(t):`type`in n?e.fromInline(t):e.zero()}isZero(){return this.raw.kind===`zero`}isSingle(){return this.raw.kind===`single`}isMultiple(){return this.raw.kind===`multiple`}isInline(){return this.raw.kind===`inline`}asSingle(){if(this.raw.kind!==`single`)throw Error(`FieldSchemaReference is '${this.raw.kind}', not 'single'`);return this.raw.value}asMultiple(){if(this.raw.kind!==`multiple`)throw Error(`FieldSchemaReference is '${this.raw.kind}', not 'multiple'`);return this.raw.value}asInline(){if(this.raw.kind!==`inline`)throw Error(`FieldSchemaReference is '${this.raw.kind}', not 'inline'`);return this.raw.value}};function kt(e){let t=e;if(`predicate`in t&&typeof t.predicate==`string`){let t=e;return{kind:`rule`,name:t.name,description:t.description??void 0,predicate:t.predicate,parameters:t.parameters??void 0,fields:t.fields??[]}}let n=e;return{kind:`group`,name:n.name,description:n.description??void 0,operator:n.operator,rules:(n.rules??[]).map(e=>kt(e))}}function z(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e))t[n]=kt(r);return t}const B={issues:[],success:!0,skipped:!1},V={issues:[],success:!0,skipped:!0};function H(e){return{issues:e,success:!1,skipped:!1}}function U(e,t,n){return{code:e,message:t,path:n}}function W(e,t){return e===``?t:`${e}.${t}`}function At(e,t,n){return e===``?[n,[n]]:[`${e}.${n}`,[...t,n]]}function jt(e){return e===``?[]:e.split(`.`)}function G(e){let t=e.length;for(let n of e)for(let e of n)e===`[`&&t++;return t}function Mt(e,t,n){let r=[],i=[];for(let a of n){let n=jt(a);e===``?(r.push(a),i.push(n)):(r.push(W(e,a)),i.push([...t,...n]))}return[r,i]}function Nt(e,t){if(t.length===0)return[e,!0];let n=e;for(let e of t){if(n==null)return[void 0,!1];let t=e.indexOf(`[`);if(t===-1){if(typeof n!=`object`||Array.isArray(n))return[void 0,!1];let t=n;if(!(e in t))return[void 0,!1];n=t[e]}else{let r=e.slice(0,t);if(r!==``){if(typeof n!=`object`||Array.isArray(n))return[void 0,!1];let e=n;if(!(r in e))return[void 0,!1];n=e[r]}let i=e.slice(t).matchAll(/\[(\d+)\]/g);for(let e of i){let t=e[1];if(t===void 0)return[void 0,!1];let r=parseInt(t,10);if(!Array.isArray(n)||r>=n.length)return[void 0,!1];n=n[r]}}}return[n,!0]}function K(e,t){return Nt(e.rootData,t)}function q(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Pt(e){if(e==null)return!0;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===`bigint`||t===`symbol`}function J(e,t,n=!1){if(e===t)return!0;if(e===null||t===null||e===void 0||t===void 0)return e===t;let r=typeof e,i=typeof t;if(r===`string`&&i===`string`||r===`boolean`&&i===`boolean`||r===`number`&&i===`number`||n&&r===`number`&&i===`number`)return e===t;if(r!==`object`||i!==`object`)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!J(e[r],t[r],n))return!1;return!0}if(Array.isArray(e)!==Array.isArray(t))return!1;let a=e,o=t,s=Object.keys(a),c=Object.keys(o);if(s.length!==c.length)return!1;for(let e of s)if(!(e in o)||!J(a[e],o[e],n))return!1;return!0}function Ft(e){return typeof e==`number`&&Number.isInteger(e)}function It(e){return typeof e==`number`&&!Number.isInteger(e)}function Y(e){return typeof e==`number`}var X=class{id;path;pathParts;deps;constructor(e,t,n,r=[]){this.id=e,this.path=t,this.pathParts=n,this.deps=r}getID(){return this.id}getPath(){return this.path}getPathParts(){return this.pathParts}getDependencies(){return this.deps}},Lt=class extends X{expectedFields;constructor(e,t,n,r,i=[]){super(e,t,n,i),this.expectedFields=r}async execute(e){let[t,n]=K(e,this.pathParts);if(!n)return B;let r=q(t);if(!r)return H([U(`TYPE_MISMATCH`,`Expected object for unexpected field check`,this.path)]);let i=[];for(let e of Object.keys(r))this.expectedFields.has(e)||i.push(U(`UNEXPECTED_FIELD`,`Unexpected field '${e}'`,W(this.path,e)));return i.length>0?H(i):B}},Rt=class extends X{fieldName;parentPath;parentPathParts;constructor(e,t,n,r,i,a,o=[]){super(e,t,n,o),this.fieldName=r,this.parentPath=i,this.parentPathParts=a}async execute(e){let[t,n]=K(e,this.parentPathParts);if(!n&&this.parentPath!==``)return B;if(t==null)return V;let r=q(t);return r?this.fieldName in r?B:H([U(`REQUIRED_FIELD_MISSING`,`Required field '${this.fieldName}' is missing`,this.path)]):H([U(`INVALID_DATA_STRUCTURE`,`Cannot check for required fields on non-object parent`,this.parentPath)])}},zt=class extends X{expected;constructor(e,t,n,r,i=[]){super(e,t,n,i),this.expected=r}async execute(e){let[t,n]=K(e,this.pathParts);if(!n||t===void 0)return B;switch(this.expected){case`string`:if(typeof t==`string`)return B;break;case`boolean`:if(typeof t==`boolean`)return B;break;case`number`:if(Y(t))return B;break;case`integer`:if(Ft(t))return B;break;case`decimal`:if(It(t))return B;break;case`bytes`:if(t instanceof Uint8Array||Array.isArray(t)&&t.every(e=>typeof e==`number`))return B;break;case`unknown`:return B;default:return B}return H([U(`TYPE_MISMATCH`,`Expected ${this.expected}, got ${typeof t} (${JSON.stringify(t)})`,this.path)])}},Bt=class extends X{lookup;complex;expectNumeric;constructor(e,t,n,r,i,a,o=[]){super(e,t,n,o),this.lookup=r,this.complex=i,this.expectNumeric=a}async execute(e){let[t,n]=K(e,this.pathParts);if(!n||t===void 0)return B;if(typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`)return H([U(`TYPE_MISMATCH`,`Expected scalar for enum, got ${typeof t}`,this.path)]);if(this.lookup.has(t))return B;for(let e of this.complex)if(J(t,e,this.expectNumeric))return B;return H([U(`ENUM_VIOLATION`,`Value ${JSON.stringify(t)} is not in the allowed list`,this.path)])}},Vt=class extends X{graph;constructor(e,t,n,r,i=[]){super(e,t,n,i),this.graph=r}async execute(e){let[t,n]=K(e,this.pathParts);if(!n||t===void 0)return B;if(!Array.isArray(t))return H([U(`ARRAY_TYPE_MISMATCH`,`Expected array`,this.path)]);let r=G(this.pathParts);if(r>=e.maxDepth)return H([U(`MAX_DEPTH_EXCEEDED`,`Maximum nesting depth of ${e.maxDepth} exceeded`,this.path)]);if(!this.graph)return B;let i=[],a=e.maxDepth-r;for(let n=0;n<t.length;n++){let r=t[n],o=`${this.path}[${n}]`,s=await this.graph.traverse(e.functionMap,{item:r},e.mode,a,e.originalRoot);for(let e of s)i.push({...e,path:e.path.startsWith(`item`)?e.path.replace(`item`,o):e.path})}return i.length>0?H(i):B}},Ht=class extends X{graph;constructor(e,t,n,r,i=[]){super(e,t,n,i),this.graph=r}async execute(e){let[t,n]=K(e,this.pathParts);if(!n||t===void 0)return B;let r=q(t);if(!r)return H([U(`OBJECT_TYPE_MISMATCH`,`Expected object for record, got ${typeof t}`,this.path)]);let i=G(this.pathParts);if(i>=e.maxDepth)return H([U(`MAX_DEPTH_EXCEEDED`,`Maximum nesting depth of ${e.maxDepth} exceeded`,this.path)]);if(!this.graph)return B;let a=[],o=e.maxDepth-i;for(let[t,n]of Object.entries(r)){let r=W(this.path,t),i=await this.graph.traverse(e.functionMap,{item:n},e.mode,o,e.originalRoot);for(let e of i)a.push({...e,path:e.path.startsWith(`item`)?e.path.replace(`item`,r):e.path})}return a.length>0?H(a):B}},Ut=class extends X{itemGraph;constructor(e,t,n,r,i=[]){super(e,t,n,i),this.itemGraph=r}async execute(e){let[t,n]=K(e,this.pathParts);if(!n||t===void 0)return B;if(!Array.isArray(t))return H([U(`SET_TYPE_MISMATCH`,`Expected array for set validation`,this.path)]);if(this.itemGraph){let n=G(this.pathParts);if(n>=e.maxDepth)return H([U(`MAX_DEPTH_EXCEEDED`,`Maximum nesting depth of ${e.maxDepth} exceeded`,this.path)]);let r=e.maxDepth-n,i=[];for(let n=0;n<t.length;n++){let a=`${this.path}[${n}]`,o=await this.itemGraph.traverse(e.functionMap,{item:t[n]},e.mode,r,e.originalRoot);for(let e of o)i.push({...e,path:e.path.startsWith(`item`)?e.path.replace(`item`,a):e.path})}if(i.length>0)return H(i)}if(t.length<=1)return B;let r=new Map,i=[];for(let e=0;e<t.length;e++){let n=t[e];if(Pt(n)){let t=r.get(n);if(t!==void 0)return H([U(`SET_DUPLICATE`,`Duplicate value at index ${e} (first seen at index ${t})`,this.path)]);r.set(n,e)}else{let t=i.find(e=>J(n,e.val,!1));if(t)return H([U(`SET_DUPLICATE`,`Duplicate value at index ${e} (first seen at index ${t.index})`,this.path)]);i.push({val:n,index:e})}}return B}},Wt=class extends X{constructor(e,t,n,r=[]){super(e,t,n,r)}async execute(e){let[t,n]=K(e,this.pathParts);if(!n)return B;if(!Array.isArray(t))return H([U(`GEOMETRY_TYPE_MISMATCH`,`Geometry must be an array of coordinate arrays`,this.path)]);for(let e=0;e<t.length;e++){let n=t[e];if(!Array.isArray(n))return H([U(`GEOMETRY_TYPE_MISMATCH`,`Geometry inner element at index ${e} must be an array`,`${this.path}[${e}]`)]);for(let t=0;t<n.length;t++)if(!Y(n[t]))return H([U(`GEOMETRY_TYPE_MISMATCH`,`Geometry element at [${e}][${t}] is not a valid number`,`${this.path}[${e}][${t}]`)])}return B}},Gt=class extends X{constructor(e,t,n,r=[]){super(e,t,n,r)}async execute(e){return B}},Kt=class extends X{validationGraph;schemaName;constructor(e,t,n,r,i,a=[]){super(e,t,n,a),this.validationGraph=r,this.schemaName=i}async execute(e){let[t,n]=K(e,this.pathParts);if(!n||t===void 0)return B;let r=q(t);if(!r)return H([U(`TYPE_MISMATCH`,`Expected object for recursive schema ${this.schemaName}, got ${typeof t}`,this.path)]);if(G(this.pathParts)>=e.maxDepth)return H([U(`MAX_DEPTH_EXCEEDED`,`Recursive schema '${this.schemaName}' exceeds maximum depth of ${e.maxDepth}`,this.path)]);let i=(await this.validationGraph.traverse(e.functionMap,r,e.mode,e.maxDepth,e.originalRoot)).map(e=>({...e,path:e.path===``?this.path:W(this.path,e.path)}));return i.length>0?H(i):B}},qt=class extends X{graphs;constructor(e,t,n,r,i=[]){super(e,t,n,i),this.graphs=r}async execute(e){let[t,n]=K(e,this.pathParts);if(!n||t===void 0)return B;if(G(this.pathParts)>=e.maxDepth)return H([U(`MAX_DEPTH_EXCEEDED`,`Maximum nesting depth of ${e.maxDepth} exceeded`,this.path)]);let r=await Promise.all(this.graphs.map(async(n,r)=>{let i={root:t},a=(await n.traverse(e.functionMap,i,e.mode,e.maxDepth,e.originalRoot)).map(e=>({...e,path:e.path.startsWith(`root`)?e.path.replace(`root`,this.path):e.path,message:`[variant ${r}] ${e.message}`})),o=a.length===0;return!o&&a.length===0&&a.push(U(`INTERNAL_ERROR`,`Variant ${r} failed without reporting any issues`,this.path)),{ok:o,issues:a}}));return r.some(e=>e.ok)?B:H([U(`UNION_MISMATCH`,`Value at '${this.path}' did not match any variant of the union`,this.path),...r.flatMap(e=>e.issues)])}},Jt=class extends X{constraint;fieldPaths;fieldPathParts;constraintPath;constraintPathParts;scope;constructor(e,t,n,r,i,a,o,s,c,l=[]){super(e,t,n,l),this.constraint=r,this.fieldPaths=i,this.fieldPathParts=a,this.constraintPath=o,this.constraintPathParts=s,this.scope=c}async execute(e){if(this.constraint.kind!==`rule`)return H([U(`INTERNAL_ERROR`,`ConstraintNode '${this.constraint.name}': expected a rule, got a group`,this.constraintPath)]);switch(this.scope){case`global`:return this.executeGlobalConstraint(e,this.constraint);case`recursive`:return this.executeRecursiveConstraint(e,this.constraint)}}executeGlobalConstraint(e,t){return Qt(e,t.name,this.constraintPath,this.fieldPaths,this.fieldPathParts,()=>$t({...e,data:e.rootData},t,this.constraintPath))}executeRecursiveConstraint(e,t){let[n,r]=K(e,this.constraintPathParts);if(!r)return Promise.resolve(V);let i=this.fieldPaths.map(e=>this.constraintPath!==``&&e.startsWith(this.constraintPath+`.`)?e.slice(this.constraintPath.length+1):e),a=this.fieldPathParts.map((e,t)=>{let n=this.fieldPaths[t]??``;return this.constraintPath!==``&&n.startsWith(this.constraintPath+`.`)?e.slice(this.constraintPathParts.length):e});return Qt(e,t.name,this.constraintPath,i,a,()=>$t({...e,data:n},t,this.constraintPath))}},Yt=class extends X{group;name;constructor(e,t,n,r,i,a,o=[]){super(e,t,n,o),this.group=r,this.name=i}async execute(e){let{allPaths:t,allParts:n}=Zt(this.group,this.path,this.pathParts);return Qt(e,this.name,this.path,t,n,()=>this.executeGroup(e,this.group,this.path,this.name))}async executeGroup(e,t,n,r){let i=[],a=[];for(let o of t.rules){let t;if(o.kind===`rule`)t=await $t(e,o,n);else if(o.kind===`group`)t=await this.executeGroup(e,o,n,o.name);else return H([U(`INTERNAL_ERROR`,`Unknown constraint kind in group '${r}'`,n)]);i.push(t.success),t.success||a.push(...t.issues)}return Xt(t.operator,i)?B:H([U(`CONSTRAINT_GROUP_VIOLATION`,`Constraint group '${r}' failed`,n),...a])}};function Xt(e,t){switch(e){case`and`:return t.every(Boolean);case`or`:return t.some(Boolean);case`not`:return t.length===1&&!t[0];case`nor`:return t.every(e=>!e);case`xor`:return t.filter(Boolean).length===1;case`nand`:return!t.every(Boolean);case`xnor`:return t.filter(Boolean).length!==1;default:return!1}}function Zt(e,t,n){let r=new Map;function i(e){for(let a of e.rules)if(a.kind===`rule`){let[e,i]=Mt(t,n,a.fields);for(let t=0;t<e.length;t++){let n=e[t],a=i[t];r.set(n,a)}}else a.kind===`group`&&i(a)}i(e);let a=Array.from(r.keys());return{allPaths:a,allParts:a.map(e=>r.get(e))}}async function Qt(e,t,n,r,i,a){let o=[],s=[];for(let t=0;t<r.length;t++){let n=i[t]??[],a=r[t]??``,[,c]=K(e,n);c?o.push(a):s.push(a)}if(s.length===0)return a();if(o.length===0)switch(e.mode){case`strict`:return H([U(`CONSTRAINT_INCOMPLETE`,`Constraint '${t}' cannot be evaluated: missing required fields ${JSON.stringify(s)}`,n)]);case`partialStrict`:case`loose`:return V}switch(e.mode){case`strict`:return H([U(`CONSTRAINT_INCOMPLETE`,`Constraint '${t}' cannot be evaluated: missing required fields ${JSON.stringify(s)}`,n)]);case`partialStrict`:return H([U(`CONSTRAINT_PARTIAL_UPDATE`,`Constraint '${t}' couples fields ${JSON.stringify(r)}. Cannot update only ${JSON.stringify(o)} - all coupled fields must be updated together`,n)]);case`loose`:return V}}async function $t(e,t,n){let r=e.functionMap[t.predicate];if(!r)return H([U(`MISSING_PREDICATE`,`Predicate '${t.predicate}' not found`,n)]);let i=await r({root:e.originalRoot,data:e.data,keys:t.fields,parameters:t.parameters});return i.length>0?H(i.map(e=>({...e,path:e.path===``?n:W(n,e.path)}))):B}var en=class{constraints=new Map;add(e,t,n,r,i){let a=this.constraints.get(e);(!a||n>=a.specificity)&&this.constraints.set(e,{constraint:t,specificity:n,basePath:r,scope:i})}getEffective(){return Array.from(this.constraints.values())}};function tn(){return new en}var nn=class{buildingSchemas=new Map;recursiveGraphCache=new Map;isRecursive(e){return(this.buildingSchemas.get(e)??0)>0}markBuilding(e){this.buildingSchemas.set(e,(this.buildingSchemas.get(e)??0)+1)}unmarkBuilding(e){let t=(this.buildingSchemas.get(e)??0)-1;t<=0?this.buildingSchemas.delete(e):this.buildingSchemas.set(e,t)}makeGraphCacheKey(e,t){let n=Object.keys(t).sort();return n.length===0?e:`${e}:${n.join(`,`)}`}async getOrBuildRecursiveGraph(e,t,n,r){let i=this.makeGraphCacheKey(e,n),a=this.recursiveGraphCache.get(i);if(a)return a;let o=new dn;this.recursiveGraphCache.set(i,o),this.markBuilding(e);try{let e=rn(t,r);await o.buildFromSchema(e,``,[],new Map,t,n,r,this,!1,!1),o.finalize()}catch(e){throw this.recursiveGraphCache.delete(i),e}finally{this.unmarkBuilding(e)}return o}};function rn(e,t){let n=`fields`in e?e.fields:{},r=e.constraints??{},i={name:e.name,version:`0`,fields:n,constraints:r};return e.description!==void 0&&(i.description=e.description),t.schemas!==void 0&&(i.schemas=t.schemas),i}function Z(e){return`type`in e&&e.type?e.type:`fields`in e&&e.fields&&Object.keys(e.fields).length>0?`object`:`unknown`}function an(e){switch(e){case`object`:case`array`:case`set`:case`record`:case`union`:case`composite`:case`enum`:case`geometry`:return!0;default:return!1}}function on(e){let t=[];for(let n of e.rules)n.kind===`rule`?t.push(...n.fields):n.kind===`group`&&t.push(...on(n));return t}function sn(e,t){let n={},r=e.constraints??{},i=e=>e===t||e.startsWith(t+`.`);for(let[e,t]of Object.entries(r)){let r=kt(t);r.kind===`rule`?r.fields.some(i)&&(n[e]=r):r.kind===`group`&&on(r).some(i)&&(n[e]=r)}return n}function cn(e,t,n,r){let i=tn(),a=r===``?`global`:`recursive`;for(let[,t]of Object.entries(e))i.add(t.name,t,1,r,a);for(let[,e]of Object.entries(t))i.add(e.name,e,2,r,a);for(let[,e]of Object.entries(n))i.add(e.name,e,3,r,a);return i.getEffective()}function ln(e){let t=new Map,n=[];for(let r of e)r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`?t.set(r,!0):n.push(r));return{lookup:t,complex:n}}function un(e,t){let n=new Set;function r(e){let i=Z(e);if(i===`object`||i===`unknown`){if(`fields`in e&&e.fields)for(let t of Object.values(e.fields))n.add(t.name)}else if(i===`union`||i===`composite`){if(!(`schema`in e)||!e.schema)return;let n=R.fromFieldSchema(e.schema);if(!n.isMultiple())return;for(let e of n.asMultiple()){let n=t.schemas?.[e.id];n&&r(n)}}}for(let n of e){let e=t.schemas?.[n.id];e&&r(e)}return n}var dn=class e{nodes=new Map;dependencies=new Map;visitedState=new Map;executionOrder=[];nextNodeID=1;nullablePaths=new Set;buildNodeID(){return this.nextNodeID++}addNode(e){let t=e.getID();this.nodes.has(t)||(this.nodes.set(t,e),this.dependencies.set(t,e.getDependencies()))}createUnexpectedFieldsNode(e,t,n,r=[]){return new Lt(this.buildNodeID(),e,t,n,r)}createRequiredFieldNode(e,t,n,r,i,a=[]){return new Rt(this.buildNodeID(),e,t,n,r,i,a)}createTypeCheckNode(e,t,n,r=[]){return new zt(this.buildNodeID(),e,t,n,r)}createCompletionNode(e,t,n){return new Gt(this.buildNodeID(),e,t,n)}finalize(){this.visitedState=new Map;let e=[],t=!1,n=r=>{if(t)return;let i=this.visitedState.get(r)??0;if(i===1){t=!0;return}if(i!==2){this.visitedState.set(r,1);for(let e of this.dependencies.get(r)??[])n(e);this.visitedState.set(r,2),e.push(r)}};for(let e of this.nodes.keys())if((this.visitedState.get(e)??0)===0&&(n(e),t))throw Error(`Circular dependency detected in validation graph at node ${e}`);this.executionOrder=e}async traverse(e,t,n,r,i){let a={originalRoot:i,rootData:t,data:t,functionMap:e,maxDepth:r,mode:n,visited:new Map,issues:[]};for(let e of this.executionOrder){let t=this.nodes.get(e),r=this.dependencies.get(e)??[],i=!1;for(let t of r){let n=a.visited.get(t);if(n!==void 0&&!n){a.visited.set(e,!0),i=!0;break}}if(i)continue;let o=t.getPathParts(),s=t.getPath(),[c,l]=K(a,o),u=t instanceof Rt,d=this.nullablePaths.has(s);if((!l||c===void 0)&&!u){a.visited.set(e,!0);continue}if(c===null){if(u)continue;if(d){a.visited.set(e,!0);continue}}let f=await t.execute(a);if(a.visited.set(e,f.success),f&&!f.skipped&&f.issues.length>0)for(let e of f.issues)switch(n){case`strict`:a.issues.push(e);break;case`partialStrict`:e.code!==`REQUIRED_FIELD_MISSING`&&a.issues.push(e);break;case`loose`:e.code!==`REQUIRED_FIELD_MISSING`&&e.code!==`UNEXPECTED_FIELD`&&a.issues.push(e)}}return a.issues}async buildFromSchema(e,t,n,r,i,a,o,s,c,l){let u=[],d=i&&`fields`in i&&i.fields?i.fields:e.fields,f=null;if(!c){let e=new Set(Object.values(d).map(e=>e.name));f=this.createUnexpectedFieldsNode(t,n,e),this.addNode(f),u.push({id:f.getID(),deps:[]})}let p=[],ee=[];for(let i of Object.values(d)){let a=await this.buildFieldNodes(i,t,n,p,e,r,o,s,l);ee.push(...a)}let m=cn(z(i?i.constraints:e.constraints),a,o&&t!==``?sn(o,t):{},t),te=ee.map(e=>e.id),h=this.buildFromEffectiveConstraints(m,n,te,r);if(h.length>0){let e=this.createCompletionNode(t,n,h);this.addNode(e),u.push({id:e.getID(),deps:h})}return u}async buildFieldNodes(e,t,n,r,i,a,o,s,c){let[l,u]=At(t,n,e.name);e.nullable!==!1&&this.nullablePaths.add(l);let d=r,f=[];if(e.required){let r=this.createRequiredFieldNode(l,u,e.name,t,n,d);this.addNode(r),d=[r.getID()],f.push({id:r.getID(),deps:d})}if(!an(e.type)){let t=this.createTypeCheckNode(l,u,e.type,d);this.addNode(t),d=[t.getID()],f.push({id:t.getID(),deps:d})}let p=await this.buildFieldTypeNodes(e,l,u,d,i,a,o,s,c);return f.push(...p),f}async buildFieldTypeNodes(e,t,n,r,i,a,o,s,c){let l=[],u=null;switch(e.type){case`enum`:u=await this.buildEnumNode(e,t,n,r,o);break;case`array`:u=await this.buildContainerNode(e,t,n,r,o,s,`array`,`array items`);break;case`set`:{let i=await this.buildContainerNode(e,t,n,r,o,s,`array`,`set elements`),a=i instanceof Vt?i.graph:null;u=new Ut(this.buildNodeID(),t,n,a,r);break}case`record`:u=await this.buildContainerNode(e,t,n,r,o,s,`record`,`record items`);break;case`union`:u=await this.buildUnionNode(e,t,n,r,o,s);break;case`composite`:{let i=await this.buildCompositeNode(e,t,n,r,o,s);return l.push(...i),l}case`geometry`:u=new Wt(this.buildNodeID(),t,n,r);break;case`object`:{let r=await this.buildObjectFieldNodes(e,t,n,i,a,o,s,c);return l.push(...r),l}default:return l}return u&&(this.addNode(u),l.push({id:u.getID(),deps:u.getDependencies()})),l}async buildObjectFieldNodes(e,t,n,r,i,a,o,s){let c=[],l=R.fromFieldSchema(e.schema);if(l.isZero())throw Error(`FieldSchemaReference is zero/uninitialized at path '${t}'`);if(!l.isSingle())throw Error(`Object field must use a single schema reference at path '${t}'`);let u=l.asSingle(),d=a.schemas?.[u.id];if(!d)throw Error(`Nested schema '${u.id}' not found for field '${e.name}' at path '${t}'`);if(o.isRecursive(u.id)){let e=z(u.constraints),r=await o.getOrBuildRecursiveGraph(u.id,d,e,a),i=new Kt(this.buildNodeID(),t,n,r,u.id);return this.addNode(i),c.push({id:i.getID(),deps:[]}),c}let f=rn(d,a);o.markBuilding(u.id);try{let e=await this.buildFromSchema(f,t,n,i,d,z(u.constraints),a,o,s,!1),r=new Gt(this.buildNodeID(),t,n,e.map(e=>e.id));this.addNode(r),c.push({id:r.getID(),deps:e.map(e=>e.id)})}finally{o.unmarkBuilding(u.id)}return c}async buildContainerNode(t,n,r,i,a,o,s,c){let l=e=>s===`array`?new Vt(this.buildNodeID(),n,r,e,i):new Ht(this.buildNodeID(),n,r,e,i),u=R.fromFieldSchema(t.schema);if(u.isZero())return l(null);if(u.isSingle()){let e=u.asSingle();if(e.id!==``){let t=a.schemas?.[e.id];if(!t)throw Error(`Nested schema '${e.id}' not found for ${c} at path '${n}'`);let r=Z(t),i=r===`composite`||r===`union`,s;s=r===`object`?R.fromSingle({id:e.id}):`schema`in t&&t.schema?R.fromFieldSchema(t.schema):R.zero();let u=s.isZero()?void 0:s.isSingle()?s.asSingle():s.isMultiple()?s.asMultiple():s.asInline(),d={name:`item`,type:r};u!==void 0&&(d.schema=u);let f=`default`in t?t.default:void 0;return f!==void 0&&(d.default=f),l(await this.createSubGraph(`item`,d,n,a,o,i,!1))}}if(u.isInline()){let t=u.asInline();if(!t.type)throw Error(`Inline descriptor missing 'type' field at path '${n}'`);let r=new e,i=new Map,s=t.type;if(s===`record`){let e={name:`__inline_record`,version:`0`,fields:{}};a.schemas!==void 0&&(e.schemas=a.schemas),await r.buildFromSchema(e,``,[],i,null,{},a,o,!0,!1)}else{let e=r.createTypeCheckNode(`item`,[`item`],s);r.addNode(e)}return r.finalize(),l(r)}throw Error(`Invalid schema reference for ${c} at path '${n}'`)}async buildEnumNode(e,t,n,r,i){let a=R.fromFieldSchema(e.schema);if(a.isZero())throw Error(`Enum field must have schema reference at path '${t}'`);let o=a.isSingle()?[a.asSingle()]:a.isMultiple()?a.asMultiple():[];if(o.length===0&&!a.isInline())throw Error(`Enum schema reference must be single, multiple, or inline at path '${t}'`);if(a.isInline()){let e=a.asInline();if(!e.type)throw Error(`Inline enum descriptor missing 'type' at path '${t}'`);if(!e.values||e.values.length===0)throw Error(`Inline enum descriptor missing 'values' at path '${t}'`);let{lookup:i,complex:o}=ln(e.values),s=e.type===`number`||e.type===`integer`||e.type===`decimal`;return new Bt(this.buildNodeID(),t,n,i,o,s,r)}let s=new Map,c=[],l=null;for(let e of o){let n,r,a;if(e.id!==``){let o=i.schemas?.[e.id];if(!o)throw Error(`Enum schema '${e.id}' not found at path '${t}'`);if(!(`values`in o)||!o.values?.length)throw Error(`Enum schema '${e.id}' has no values defined at path '${t}'`);a=o.type,{lookup:n,complex:r}=ln(o.values)}else throw Error(`Inline descriptor in named-reference array is not permitted at path '${t}'`);for(let[e]of n)s.set(e,!0);c=c.concat(r),l||=a}let u=l===`number`||l===`integer`||l===`decimal`;return new Bt(this.buildNodeID(),t,n,s,c,u,r)}async buildUnionNode(e,t,n,r,i,a){let o=R.fromFieldSchema(e.schema);if(o.isZero()||!o.isMultiple())throw Error(`Union field must reference multiple schemas at path '${t}'`);let s=o.asMultiple(),c=[];for(let e of s){let n=i.schemas?.[e.id];if(!n)throw Error(`Nested schema '${e.id}' not found for union at path '${t}'`);let r;r=`fields`in n&&n.fields&&Object.keys(n.fields).length>0?{name:`root`,type:`object`,schema:{id:e.id}}:{name:`root`,type:Z(n),schema:`schema`in n?n.schema:void 0};let o=await this.createSubGraph(`root`,r,t,i,a,!0,!1);c.push(o)}return new qt(this.buildNodeID(),t,n,c,r)}async buildCompositeNode(e,t,n,r,i,a){let o=R.fromFieldSchema(e.schema);if(o.isZero()||!o.isMultiple())throw Error(`Composite field must reference multiple schemas at path '${t}'`);let s=o.asMultiple(),c=un(s,i),l=this.createUnexpectedFieldsNode(t,n,c);this.addNode(l);let u=[l.getID()],d=[];for(let e of s){let r=i.schemas?.[e.id];if(!r)throw Error(`Nested schema '${e.id}' not found for composite at path '${t}'`);let o=Z(r);if(o===`object`||o===`unknown`){let o=rn(r,i);a.markBuilding(e.id);let s;try{s=await this.buildFromSchema(o,t,n,new Map,r,z(e.constraints),i,a,!0,!0)}finally{a.unmarkBuilding(e.id)}for(let e of s)e.deps.includes(l.getID())||(e.deps=[l.getID(),...e.deps],this.dependencies.set(e.id,e.deps));d.push(...s)}else if(o===`union`){if(!(`schema`in r)||!r.schema)throw Error(`Union part '${e.id}' in composite must reference multiple schemas at path '${t}'`);let o=R.fromFieldSchema(r.schema);if(!o.isMultiple())throw Error(`Union part '${e.id}' in composite must reference multiple schemas at path '${t}'`);let s=o.asMultiple(),c=[];for(let e of s){let n=i.schemas?.[e.id];if(!n)throw Error(`Union variant schema '${e.id}' not found at path '${t}'`);let r;r=`fields`in n&&n.fields&&Object.keys(n.fields).length>0?{name:`root`,type:`object`,schema:{id:e.id}}:{name:`root`,type:Z(n),schema:`schema`in n?n.schema:void 0};let o=await this.createSubGraph(`root`,r,t,i,a,!0,!0);c.push(o)}let l=new qt(this.buildNodeID(),t,n,c,u);this.addNode(l),d.push({id:l.getID(),deps:u})}else throw Error(`Composite part '${e.id}' has unsupported effective type '${o}'; composite parts must be object or union schemas at path '${t}'`)}return[{id:l.getID(),deps:[]},...d]}buildFromEffectiveConstraints(e,t,n,r){let i=[];for(let a of e){let e=this.buildFromConstraintRuleWithScope(a.constraint,a.basePath,t,n,r,a.scope);i.push(...e)}return i}buildFromConstraintRuleWithScope(e,t,n,r,i,a){let o=`${t}:${e.name}`;if(i.get(o))return[];if(i.set(o,!0),e.kind===`rule`){let[i,o]=Mt(t,n,e.fields),s=new Jt(this.buildNodeID(),t,n,e,i,o,t,n,a,r);return this.addNode(s),[s.getID()]}if(e.kind===`group`){let i=new Yt(this.buildNodeID(),t,n,e,e.name,a,r);return this.addNode(i),[i.getID()]}return[]}async createSubGraph(t,n,r,i,a,o,s){let c={name:`subgraph_${r}`,version:`0`,fields:{[t]:n}};i.schemas!==void 0&&(c.schemas=i.schemas);let l=new e,u=new Map;return await l.buildFromSchema(c,``,[],u,null,{},i,a,o,s),l.finalize(),l}},fn=class e{fmap;graph;config;constructor(e,t,n){this.graph=e,this.fmap=t,this.config=n}async validate(e){return this.graph.traverse(this.fmap,e,`strict`,this.config.maxDepth,e)}async validatePartial(e){return this.graph.traverse(this.fmap,e,`partialStrict`,this.config.maxDepth,e)}async validateLoose(e){return this.graph.traverse(this.fmap,e,`loose`,this.config.maxDepth,e)}static async create(t,n,r=Ot()){let i=new dn,a=new nn,o=new Map;return await i.buildFromSchema(t,``,[],o,null,{},t,a,!1,!1),i.finalize(),new e(i,n,r)}},pn={version:`1.0.0`,name:`Schema`,description:`Meta-schema defining the structure of schema definitions`,fields:{"019d7775-6565-7755-904d-2d0cdf0e1b86":{name:`fields`,type:`record`,schema:{id:`019d7775-6565-7f15-b0f4-27a4f40cbf5c`}},"019d7775-6565-73d6-a7be-130b3c1e93c8":{name:`indexes`,type:`record`,schema:{id:`019d7775-6565-74f6-9c72-9e35d3d16b0a`}},"019d7775-6565-722f-9a5a-2810f537a61c":{name:`constraints`,type:`record`,schema:{id:`019d7775-6565-7ab6-9c65-ab60632aeca8`}},"019d7775-6565-7fe8-86f6-57a8a305a314":{name:`schemas`,type:`record`,schema:{id:`019d7775-6565-7db3-9bb0-be9fc50550bd`}},"019d7775-6565-7c1f-a6f7-aeb5c4eb35e4":{name:`name`,required:!0,type:`string`},"019d7775-6565-7545-9e25-fc471f57bcfb":{name:`description`,type:`string`},"019d7775-6565-7bdc-a9d4-776b1f163346":{name:`version`,required:!0,type:`string`},"019d7775-6565-74ed-8a52-12027f3c577d":{name:`metadata`,type:`record`}},schemas:{"019d7775-6566-7da1-b24a-67bd81dd2b0e":{name:`Unknown`,type:`unknown`},"019d7775-6565-7db3-9bb0-be9fc50550bd":{name:`NestedSchema`,fields:{"019d7775-6566-77a1-9b36-bbd57f927d11":{name:`fields`,type:`record`,schema:{id:`019d7775-6565-7f15-b0f4-27a4f40cbf5c`}},"019d7775-6567-7931-b2d6-fb52039c28b5":{name:`type`,type:`enum`,schema:{id:`019d7775-6566-765a-b142-157d1d6367b7`}},"019d7775-6567-7742-90ae-a96178ae505d":{name:`values`,type:`array`,schema:{id:`019d7775-6566-7da1-b24a-67bd81dd2b0e`}},"019d7775-6567-7709-a7e3-ed75f833da15":{name:`schema`,type:`union`,schema:[{id:`019d7775-6565-7f2a-956b-35b40caa8ec7`},{id:`019d7775-6565-71bc-84f3-044dc089d50c`},{id:`019d7775-6566-7786-8769-c13eb5a883d9`}]},"019d7775-6566-748e-b099-50c76a5b79c2":{name:`name`,required:!0,type:`string`},"019d7775-6566-74df-a8df-038cc26af034":{name:`description`,type:`string`},"019d7775-6567-748e-bcad-76068cc4739f":{name:`metadata`,type:`record`},"019d7775-6567-7022-b7fb-3975ccae2b72":{name:`concrete`,type:`boolean`},"019d7775-6567-7f25-b7e2-acc72435964f":{name:`indexes`,type:`record`,schema:{id:`019d7775-6565-74f6-9c72-9e35d3d16b0a`}},"019d7775-6567-750b-a618-5bcdc4e5d04a":{name:`constraints`,type:`record`,schema:{id:`019d7775-6565-7ab6-9c65-ab60632aeca8`}},"019d7775-6567-75c4-b399-eb4764617462":{name:`default`,type:`unknown`}},constraints:{"019d7775-6563-7554-bfae-d6ad7774d5ac":{name:`nested_schema_mode_exclusive`,predicate:`nested_schema_exclusive_mode`}}},"019d7775-6565-71ef-a08f-cdcdb116f947":{name:`IndexCondition`,fields:{"019d7775-6567-75ef-8e82-347da30f06fd":{name:`operator`,required:!0,type:`enum`,schema:{id:`019d7775-6566-7a70-8b56-e55704397fc2`}},"019d7775-6567-7466-a873-e7866e9d031f":{name:`field`,required:!0,type:`string`},"019d7775-6567-7526-9704-d19fb4eb8d8d":{name:`value`,required:!0,type:`unknown`},"a2f03bc4-e620-4b7f-a2ad-8271471ac1e4":{name:`description`,type:`string`},"8782f46d-5f1f-4102-9c3c-917752d8c9d1":{name:`metadata`,type:`record`}},constraints:{"019d7775-6563-713e-8355-df812c6bb8c9":{name:`index_condition_exclusive_type`,predicate:`index_condition_type_exclusive`},"019d7775-6564-712b-8c53-9fa93809f219":{name:`index_condition_value_type_match`,predicate:`index_condition_value_matches_field_type`}}},"019d7775-6565-7d6a-a531-47e7ea838bc4":{name:`IndexConditionGroup`,fields:{"019d7775-6567-7b4e-893f-ee7afb0c4be1":{name:`operator`,required:!0,type:`enum`,schema:{id:`019d7775-6566-7e3b-860a-c4aa4adf5d6d`}},"019d7775-6567-7af2-817f-bc5b8732c198":{name:`conditions`,required:!0,type:`array`,schema:{id:`019d7775-6565-74a3-a6e0-881a0148fc59`}},"670ebd05-3bce-4da7-a39b-20cf9ba67abe":{name:`description`,type:`string`},"8e60fb23-0e3f-4ae5-bfff-fd20da1da756":{name:`metadata`,type:`record`}}},"019d7775-6565-794d-8aba-bdc5e3cbe97e":{name:`ConstraintUnion`,type:`union`,schema:[{id:`019d7775-6565-703f-95cf-e7511d33c91b`},{id:`019d7775-6565-7ea4-a820-e8bcdbc690bc`}]},"019d7775-6566-7786-8769-c13eb5a883d9":{name:`InlineTypeDescriptor`,fields:{"019d7775-6568-713f-867f-93dde123ccfd":{name:`type`,required:!0,type:`enum`,schema:{id:`019d7775-6566-7e05-ab1b-6f768f459927`}},"019d7775-6568-7ae5-95b7-56c97722c732":{name:`values`,type:`array`,schema:{id:`019d7775-6566-7da1-b24a-67bd81dd2b0e`}},"347a2348-014b-41a7-80ad-a4e8d364ef5d":{name:`description`,type:`string`},"7d0f2347-3dfe-4e37-8235-1f9122e045dc":{name:`metadata`,type:`record`}}},"019d7775-6566-7e3b-860a-c4aa4adf5d6d":{name:`LogicalOperatorEnum`,type:`string`,values:[`and`,`or`,`not`,`nor`,`xor`,`nand`,`xnor`]},"019d7775-6566-7f2f-a009-0af144502aac":{name:`IndexOrderEnum`,type:`string`,values:[`asc`,`desc`]},"019d7775-6565-7f15-b0f4-27a4f40cbf5c":{name:`Field`,fields:{"019d7775-6566-727e-b4ff-4e6e8b800808":{name:`type`,required:!0,type:`enum`,schema:{id:`019d7775-6566-765a-b142-157d1d6367b7`}},"019d7775-6566-79e9-a60b-1c15e2154580":{name:`schema`,type:`union`,schema:[{id:`019d7775-6565-7f2a-956b-35b40caa8ec7`},{id:`019d7775-6565-71bc-84f3-044dc089d50c`},{id:`019d7775-6566-7786-8769-c13eb5a883d9`}]},"019d7775-6566-7a4c-877d-262c18adb028":{name:`name`,required:!0,type:`string`},"019d7775-6566-7b93-aa4c-b1e3869512d8":{name:`description`,type:`string`},"019d7775-6566-7ed5-9fb3-33a67b90dbbe":{name:`default`,type:`unknown`},"019d7775-6566-722b-8132-d5d8c4c9b2b6":{name:`required`,type:`boolean`},"a1000000-0000-0000-0000-000000000001":{name:`nullable`,type:`boolean`},"019d7775-6566-7367-9664-adb25994bf41":{name:`deprecated`,type:`boolean`},"019d7775-6566-7fc8-82c6-735838cdfe21":{name:`unique`,type:`boolean`},"95ab0d3b-352c-4aff-a43a-81ab889aaa42":{name:`metadata`,type:`record`}},constraints:{"019d7775-6563-7605-8bfb-c27365b73581":{name:`enum_fields_valid`,predicate:`enum_fields_valid`},"019d7775-6563-74fe-a5ae-4eef62a128d9":{name:`arrays_require_schema`,predicate:`collection_requires_schema`},"019d7775-6563-7080-ae67-bad5cd864f07":{name:`objects_require_schema`,predicate:`object_requires_schema`},"019d7775-6563-7e83-92c4-0258a8fc0d3a":{name:`unions_require_multiple_schemas`,predicate:`union_requires_multiple_schemas`},"019d7775-6564-7c60-9f9f-aeeabe05c1b5":{name:`default_value_type_match`,predicate:`default_matches_type`},"019d7775-6564-77ca-94bc-30a07da76c3d":{name:`records_allow_optional_schema`,predicate:`record_schema_cardinality`},"019d7775-6564-7768-8995-72c282cfe69f":{name:`inline_type_descriptor_valid`,predicate:`inline_type_descriptor_valid`},"019d7775-6563-7c55-a6f3-ac8f087d89d1":{name:`primitives_no_schema`,predicate:`primitives_prohibit_schema`},"019d7775-6563-73ce-aef1-86943b54a1ca":{name:`composites_require_multiple_schemas`,predicate:`composite_requires_multiple_schemas`},"019d7775-6564-719d-9948-67dd885e7632":{name:`object_referenced_schema_has_fields`,predicate:`object_referenced_schema_has_fields`},"019d7775-6564-75ce-a807-02396e0b8394":{name:`composite_referenced_schemas_must_be_objects`,predicate:`composite_referenced_schemas_must_be_objects`},"019d7775-6564-75bc-abf5-6ddd81b7d2d4":{name:`schema_reference_form_correct`,predicate:`schema_reference_form_correct`}}},"019d7775-6565-7ab6-9c65-ab60632aeca8":{name:`Constraint`,type:`composite`,schema:[{id:`019d7775-6565-7068-9cb9-28460e0368f0`},{id:`019d7775-6565-794d-8aba-bdc5e3cbe97e`}]},"019d7775-6566-765a-b142-157d1d6367b7":{name:`FieldTypeEnum`,type:`string`,values:[`unknown`,`string`,`number`,`integer`,`decimal`,`boolean`,`array`,`set`,`enum`,`object`,`record`,`union`,`composite`,`geometry`,`bytes`]},"019d7775-6566-7a70-8b56-e55704397fc2":{name:`ComparisonOperatorEnum`,type:`string`,values:[`eq`,`neq`,`lt`,`lte`,`gt`,`gte`,`in`,`nin`,`contains`,`ncontains`,`exists`,`nexists`]},"019d7775-6565-74a3-a6e0-881a0148fc59":{name:`IndexConditionUnion`,type:`union`,schema:[{id:`019d7775-6565-71ef-a08f-cdcdb116f947`},{id:`019d7775-6565-7d6a-a531-47e7ea838bc4`}]},"019d7775-6565-7068-9cb9-28460e0368f0":{name:`ConstraintMetadata`,fields:{"019d7775-6567-7017-9068-5bfcd1f9fef0":{name:`name`,required:!0,type:`string`},"019d7775-6568-7b0d-ad28-391874b5e3de":{name:`description`,type:`string`},"ee8ea6de-95f9-48e5-a047-4744b39e1c8f":{name:`metadata`,type:`record`}}},"019d7775-6565-703f-95cf-e7511d33c91b":{name:`ConstraintRule`,fields:{"019d7775-6568-7ad6-9e45-7fdbdef3fc7e":{name:`predicate`,required:!0,type:`string`},"019d7775-6568-7221-a4de-7e82d6c9f6bc":{name:`parameters`,type:`unknown`},"019d7775-6568-7d8b-a230-328fe5d352e8":{name:`fields`,type:`array`,schema:{id:`019d7775-6566-7a63-9e10-5d11c8eb607c`}}},constraints:{"019d7775-6563-7028-b96f-bc6e0abefc15":{name:`constraint_type_exclusive`,predicate:`constraint_type_exclusive`},"019d7775-6563-752b-bf9d-bf8936472250":{name:`constraint_rule_requires_predicate`,predicate:`constraint_rule_requires_predicate`},"019d7775-6564-7fc2-bbdb-0fc59e567f2b":{name:`constraint_fields_exist`,predicate:`constraint_fields_exist`}}},"019d7775-6565-7ea4-a820-e8bcdbc690bc":{name:`ConstraintGroup`,fields:{"019d7775-6568-7ebf-a1c3-829de95d9216":{name:`operator`,required:!0,type:`enum`,schema:{id:`019d7775-6566-7e3b-860a-c4aa4adf5d6d`}},"019d7775-6568-76d9-a21c-fb289c36cc70":{name:`rules`,required:!0,type:`array`,schema:{id:`019d7775-6565-794d-8aba-bdc5e3cbe97e`}}},constraints:{"019d7775-6563-7028-b96f-bc6e0abefc15":{name:`constraint_type_exclusive`,predicate:`constraint_type_exclusive`}}},"019d7775-6565-7f2a-956b-35b40caa8ec7":{name:`SchemaReference`,fields:{"019d7775-6568-762c-932e-89b85f08a951":{name:`id`,required:!0,type:`string`},"019d7775-6568-77eb-bd9d-d874a2354fd5":{name:`indexes`,type:`record`,schema:{id:`019d7775-6565-74f6-9c72-9e35d3d16b0a`}},"019d7775-6568-7ed9-99b3-90cca439ee2e":{name:`constraints`,type:`record`,schema:{id:`019d7775-6565-7ab6-9c65-ab60632aeca8`}},"abb42217-0f28-4501-ab12-c54bfe5d1492":{name:`description`,type:`string`},"ed9a369c-1c98-4bc7-845b-92fa81be31f8":{name:`metadata`,type:`record`}},constraints:{"019d7775-6564-79f2-9d64-d6b8c2696deb":{name:`schema_reference_id_required`,predicate:`schema_reference_id_required`}}},"019d7775-6565-71bc-84f3-044dc089d50c":{name:`SchemaReferenceArray`,type:`array`,schema:{id:`019d7775-6565-7f2a-956b-35b40caa8ec7`}},"019d7775-6566-7e05-ab1b-6f768f459927":{name:`InlineTypeEnum`,type:`string`,values:[`string`,`number`,`integer`,`decimal`,`boolean`,`bytes`,`unknown`,`record`]},"019d7775-6566-7df4-bc09-67956251c4a2":{name:`IndexTypeEnum`,type:`string`,values:[`normal`,`unique`,`primary`,`spatial`,`fulltext`]},"019d7775-6566-7a63-9e10-5d11c8eb607c":{name:`String`,type:`string`},"019d7775-6565-74f6-9c72-9e35d3d16b0a":{name:`Index`,fields:{"019d7775-6567-7390-96c6-8154ccc6d1ad":{name:`name`,required:!0,type:`string`},"019d7775-6567-7568-98c8-76d64b745bc7":{name:`description`,type:`string`},"019d7775-6567-7a3d-b154-1199406b7851":{name:`unique`,type:`boolean`},"019d7775-6567-7e59-a2f4-ffc431e24fdd":{name:`type`,required:!0,type:`enum`,schema:{id:`019d7775-6566-7df4-bc09-67956251c4a2`}},"019d7775-6567-787d-921c-fa28f53cedcd":{name:`fields`,required:!0,type:`array`,schema:{id:`019d7775-6566-7a63-9e10-5d11c8eb607c`}},"019d7775-6567-76c9-869a-c4e25c154583":{name:`order`,type:`enum`,schema:{id:`019d7775-6566-7f2f-a009-0af144502aac`}},"019d7775-6567-7bc2-b870-6e1ae4faa558":{name:`condition`,type:`union`,schema:[{id:`019d7775-6565-71ef-a08f-cdcdb116f947`},{id:`019d7775-6565-7d6a-a531-47e7ea838bc4`}]},"75f044b7-253c-4f48-93b7-692b9626c0ea":{name:`metadata`,type:`record`}},constraints:{"019d7775-6564-7c2d-b06d-82971c0b1fa9":{name:`index_fields_exist`,predicate:`index_fields_reference_valid`},"019d7775-6564-7660-adc8-3f1ab037d695":{name:`spatial_index_on_geometry_field`,predicate:`spatial_index_on_geometry_field`},"019d7775-6564-712b-8c53-9fa93809f219":{name:`index_condition_value_type_match`,predicate:`index_condition_value_matches_field_type`},"019d7775-6564-7285-a734-f7eed15d25e4":{name:`index_fields_not_empty`,predicate:`index_fields_not_empty`}}}},constraints:{"019d7775-6563-7554-bfae-d6ad7774d5ac":{name:`nested_schema_mode_exclusive`,predicate:`nested_schema_exclusive_mode`},"019d7775-6564-7565-b53c-49667d23c237":{name:`global_field_id_uniqueness`,predicate:`global_field_id_uniqueness`},"019d7775-6564-7a5d-bb7e-d2e9e804123f":{name:`schema_reference_integrity`,predicate:`schema_reference_exists`},"019d7775-6563-7f89-8368-395733efec86":{name:`schema_name_required`,predicate:`schema_name_required`}}};const mn=new Set([`string`,`number`,`integer`,`decimal`,`boolean`,`geometry`,`bytes`,`unknown`]),hn=new Set([`array`,`set`]),gn=[`fields`],_n=[`type`,`default`,`values`,`schema`],vn=new Set([`number`,`integer`,`decimal`,`string`]);function Q(e){let t=e.type;return t==null?[``,!1]:[String(t),!0]}function yn(e){return mn.has(e)}function $(e){return vn.has(e)}function bn(e){return hn.has(e)}function xn(e,t){let n=e.schemas;return n&&n[t]||null}function Sn(e){if(e.fields){let t=e.fields;if(Object.keys(t).length>0)return!0}let t=e.type;return t===`object`||t===`record`}function Cn(e){let t=e.schema;return t==null?[[],!1]:Array.isArray(t)?[t,!0]:[[t],!1]}function wn(e,t,n){let r=xn(e,t);if(!r)return[U(`ENUM_NAMED_SCHEMA_NOT_FOUND`,`Enum referenced schema '${t}' does not exist`,n)];let i=[],a=r.type;if(a==null)return i.push(U(`ENUM_NAMED_SCHEMA_NO_TYPE`,`Enum referenced schema '${t}' must have a 'type' (string or numeric)`,n)),i;let o=String(a);if(!(o===`string`||$(o)))return i.push(U(`ENUM_NAMED_SCHEMA_INVALID_TYPE`,`Enum referenced schema '${t}' type must be string or numeric, got '${a}'`,n)),i;let s=r.values;if(s==null)return i.push(U(`ENUM_NAMED_SCHEMA_MISSING_VALUES`,`Enum schema '${t}' must have a 'values' array`,n)),i;let c=s;if(!Array.isArray(c)||c.length===0)return i.push(U(`ENUM_NAMED_SCHEMA_EMPTY_VALUES`,`Enum schema '${t}' 'values' must be a non-empty array`,n)),i;let l=o===`string`;return c.forEach((e,r)=>{e!=null&&(l?typeof e!=`string`&&i.push(U(`ENUM_NAMED_VALUE_TYPE_MISMATCH`,`Enum schema '${t}': value at index ${r} must be string, got ${typeof e}`,`${n} (values[${r}])`)):$(o)&&(Y(e)||i.push(U(`ENUM_NAMED_VALUE_TYPE_MISMATCH`,`Enum schema '${t}': value at index ${r} must be numeric (type '${o}'), got ${typeof e}`,`${n} (values[${r}])`))))}),gn.forEach(e=>{let a=r[e];a!=null&&Object.keys(a).length>0&&i.push(U(`ENUM_NAMED_SCHEMA_HAS_FIELDS`,`Enum referenced schema '${t}' must not have '${e}' (must be a simple value schema)`,n))}),i}function Tn(e,t){let n=[],r=e.type;if(r==null)return n.push(U(`ENUM_INLINE_NO_TYPE`,`Inline enum descriptor must have a 'type' (string or numeric)`,t)),n;let i=String(r);if(!(i===`string`||$(i)))return n.push(U(`ENUM_INLINE_INVALID_TYPE`,`Inline enum descriptor type must be string or numeric, got '${r}'`,t)),n;let a=e.values;if(a==null)return n.push(U(`ENUM_INLINE_MISSING_VALUES`,`Inline enum descriptor must have a 'values' array`,t)),n;let o=a;if(!Array.isArray(o)||o.length===0)return n.push(U(`ENUM_INLINE_EMPTY_VALUES`,`Inline enum descriptor 'values' must be a non-empty array`,t)),n;let s=i===`string`;return o.forEach((e,r)=>{e!=null&&(s?typeof e!=`string`&&n.push(U(`ENUM_INLINE_VALUE_TYPE_MISMATCH`,`Inline enum value at index ${r} must be string, got ${typeof e}`,`${t}.values[${r}]`)):$(i)&&(Y(e)||n.push(U(`ENUM_INLINE_VALUE_TYPE_MISMATCH`,`Inline enum value at index ${r} must be numeric (type '${i}'), got ${typeof e}`,`${t}.values[${r}]`))))}),n}function En(e,t,n){if(typeof e!=`object`||!e)return[U(`ENUM_REF_INVALID`,`Enum schema reference must be an object`,t)];let r=e,i=`id`in r,a=`type`in r;if(i&&a)return[U(`ENUM_REF_AMBIGUOUS`,`Enum schema reference cannot have both 'id' (named) and 'type' (inline)`,t)];if(i){let e=r.id;return e==null||e===``?[U(`ENUM_NAMED_REF_INVALID_ID`,`Named enum reference 'id' must be a non-empty string`,t)]:wn(n,String(e),t)}return a?Tn(r,t):[U(`ENUM_REF_NO_ID_OR_TYPE`,`Enum schema reference must have either 'id' (named) or 'type' (inline)`,t)]}function Dn(e,t){let n=t.split(`.`),r=e.fields&&typeof e.fields==`object`?e.fields:null,i=null;for(let t=0;t<n.length;t++){if(!r)return null;let a=null;for(let e of Object.values(r))if(e&&typeof e==`object`&&e.name===n[t]){a=e;break}if(!a)return null;if(i=a,t<n.length-1){let t=a.schema;if(t&&typeof t==`object`&&!Array.isArray(t)){if(typeof t.id==`string`){let n=t.id,i=e.schemas?.[n];r=i&&typeof i==`object`?i.fields??null:null}else r=t.fields?t.fields:null}else r=null}}return i?{def:i}:null}const On={primitives_prohibit_schema:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t),i=t.schema;return r&&yn(n)&&i!=null?[U(`PRIMITIVE_HAS_SCHEMA`,`Primitive type '${n}' cannot have a schema reference`,``)]:[]},enum_fields_valid:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t);if(!r||n!==`enum`)return[];if(t.schema==null)return[U(`ENUM_MISSING_SCHEMA`,`Enum field must have a schema reference`,``)];let[i,a]=Cn(t);if(i.length===0)return[U(`ENUM_NO_VALID_REFS`,`Enum field has no valid schema references`,``)];let o=[];return i.forEach((t,n)=>{let r=a?`schema[${n}]`:`schema`;o.push(...En(t,r,e.root))}),o},composite_requires_multiple_schemas:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t),i=t.schema;if(r&&n===`composite`){if(i==null)return[U(`COMPOSITE_MISSING_SCHEMA`,`Composite type must have schema references`,``)];if(Array.isArray(i)){if(i.length<2)return[U(`COMPOSITE_INSUFFICIENT_SCHEMAS`,`Composite must have at least 2 schema references`,``)]}else return[U(`COMPOSITE_SCHEMA_NOT_ARRAY`,`Composite 'schema' must be an array of references`,``)]}return[]},composite_referenced_schemas_must_be_objects:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t);if(!r||n!==`composite`)return[];let i=t.schema;if(!Array.isArray(i)||i.length===0)return[];let a=[],o=e.root,s=(e,t)=>{let n=xn(o,e);if(!n)return[];let r=[],i=n.type;if(i!=null){let e=String(i);if(e===`composite`)return[];if(e===`union`){let e=n.schema;return Array.isArray(e)&&e.forEach((e,n)=>{typeof e==`object`&&e&&`id`in e&&r.push(...s(String(e.id),`${t}.schema[${n}]`))}),r}}return Sn(n)||r.push(U(`COMPOSITE_REF_NOT_OBJECT`,`Composite schema '${e}' must effectively represent an object type (has fields, or type 'object'/'record')`,t)),r};return i.forEach((e,t)=>{typeof e==`object`&&e&&`id`in e&&a.push(...s(String(e.id),`schema[${t}]`))}),a},object_requires_schema:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t),i=t.schema;return r&&n===`object`&&i==null?[U(`OBJECT_MISSING_SCHEMA`,`Object type must have a schema reference`,``)]:[]},object_referenced_schema_has_fields:e=>{let t=e.root,n=e.data;if(typeof n!=`object`||!n)return[];let[r,i]=Q(n);if(!i||r!==`object`)return[];let a=n.schema;if(typeof a!=`object`||!a||Array.isArray(a))return[];let o=a.id;if(!o)return[];let s=xn(t,String(o));if(!s)return[];let c=s.fields;return c==null?[U(`OBJECT_REF_NO_FIELDS`,`Object field references schema '${o}' which has no 'fields' (must be Schema mode)`,``)]:typeof c!=`object`||Object.keys(c).length===0?[U(`OBJECT_REF_EMPTY_FIELDS`,`Object field references schema '${o}' which has empty fields`,``)]:[]},spatial_index_on_geometry_field:e=>{let t=e.root,n=e.data;if(typeof n!=`object`||!n||n.type!==`spatial`)return[];let r=n.fields;if(!Array.isArray(r))return[];for(let e of r){let n=String(e),r=Dn(t,n);if(!r)continue;let i=r.def.type;if(i!==`geometry`)return[U(`SPATIAL_INDEX_NON_GEOMETRY`,`Spatial index can only reference geometry fields, but field '${n}' has type '${i}'`,``)]}return[]},index_condition_value_matches_field_type:e=>{let t=e.root,n=e.data;if(typeof n!=`object`||!n)return[];let r=n.field;if(r==null)return[];let i=n.value,a=Dn(t,String(r));if(!a)return[];let o=a.def.type,s=!0;switch(o){case`string`:typeof i!=`string`&&i!==null&&(s=!1);break;case`boolean`:typeof i!=`boolean`&&i!==null&&(s=!1);break;case`integer`:!Ft(i)&&i!==null&&(s=!1);break;case`number`:case`decimal`:!Y(i)&&i!==null&&(s=!1)}return s?[]:[U(`INDEX_CONDITION_VALUE_TYPE_MISMATCH`,`Value for field '${r}' must be ${o}`,``)]},schema_reference_exists:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.schemas||{},r=[],i=(e,t)=>{if(e&&typeof e==`object`&&`id`in e){let i=e.id;typeof i==`string`&&!n[i]&&r.push(U(`SCHEMA_REFERENCE_NOT_FOUND`,`Referenced schema '${i}' does not exist`,t))}},a=(e,t)=>{if(!(typeof e!=`object`||!e)){if(e.hasOwnProperty(`schema`)){let n=e.schema;Array.isArray(n)?n.forEach((e,n)=>i(e,`${t}.schema[${n}]`)):i(n,`${t}.schema`)}for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&a(r,t?`${t}.${n}`:n)}};return a(t,``),r},default_matches_type:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.type,r=t.default;if(n===void 0||r==null)return[];let i=String(n),a=``;switch(i){case`string`:typeof r!=`string`&&(a=`must be string`);break;case`boolean`:typeof r!=`boolean`&&(a=`must be boolean`);break;case`integer`:Ft(r)||(a=`must be integer`);break;case`number`:case`decimal`:Y(r)||(a=`must be numeric`);break;case`array`:case`set`:Array.isArray(r)||(a=`must be array`);break;case`object`:case`record`:(typeof r!=`object`||Array.isArray(r))&&(a=`must be object`);break;case`geometry`:Array.isArray(r)||(a=`must be array of coordinate arrays`)}return a?[U(`DEFAULT_VALUE_TYPE_MISMATCH`,`Default value ${JSON.stringify(r)} ${a} for type ${i}`,``)]:[]},global_field_id_uniqueness:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=new Map,r=[],i=(e,t)=>{if(!(typeof e!=`object`||!e))for(let i of Object.keys(e)){let e=n.get(i);e?r.push(U(`DUPLICATE_FIELD_ID`,`Field ID '${i}' is not unique; already used at ${e}`,`${t}.${i}`)):n.set(i,`${t}.${i}`)}};t.fields&&i(t.fields,`fields`);let a=t.schemas;if(a&&typeof a==`object`){for(let[e,t]of Object.entries(a))if(typeof t==`object`&&t){let n=t;n.fields&&i(n.fields,`schemas.${e}.fields`)}}return r},constraint_fields_exist:e=>{let t=e.root,n=[],r=(e,n)=>{let r=e.split(`.`),i=n;for(let e=0;e<r.length;e++){let n=r[e],a=i[n];if(a===void 0)return!1;if(e===r.length-1)return!0;let o=a;if(o.type===`object`){let e=o.schema;if(e&&e.id){let n=xn(t,String(e.id));if(n&&n.fields){i=n.fields;continue}}}return!1}return!1},i=(e,t,i)=>{for(let[a,o]of Object.entries(e)){if(typeof o!=`object`||!o)continue;let e=o;if(e.predicate&&e.fields){let o=e.fields;Array.isArray(o)&&o.forEach((e,o)=>{typeof e==`string`&&(r(e,t)||n.push(U(`CONSTRAINT_FIELD_NOT_FOUND`,`Constraint '${a}' references non-existent field path '${e}'`,`${i}constraints.${a}.fields[${o}]`)))})}}},a=t.fields,o=t.constraints;o&&a&&i(o,a,``);let s=t.schemas;if(s){for(let[e,t]of Object.entries(s))if(typeof t==`object`&&t){let n=t,r=n.constraints,a=n.fields;r&&a&&i(r,a,`schemas.${e}.`)}}return n},inline_type_descriptor_valid:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.schema;if(!n||typeof n!=`object`||Array.isArray(n))return[];let r=t.type,i=n.type;if(r===void 0||i===void 0)return[];let a=new Set([`record`,`array`,`set`,`enum`]),o=String(r);if(!a.has(o))return[U(`INLINE_DESCRIPTOR_NOT_ALLOWED_FOR_FIELD_TYPE`,`Inline type descriptors are only allowed for fields of type record, array, set, or enum, but got '${o}'`,``)];let s=String(i);if(!new Set([`string`,`number`,`integer`,`decimal`,`boolean`,`bytes`,`unknown`,`record`]).has(s))return[U(`INLINE_DESCRIPTOR_INVALID_TYPE`,`Inline descriptor type '${s}' is not allowed (only primitives and 'record')`,``)];let c=n.values;if(c!=null){if(s!==`string`&&!$(s))return[U(`INLINE_DESCRIPTOR_VALUES_WITHOUT_ENUM`,`'values' can only be used with string or numeric inline types`,``)];if(!Array.isArray(c)||c.length===0)return[U(`INLINE_DESCRIPTOR_VALUES_NOT_ARRAY`,`'values' must be a non‑empty array`,``)]}return[]},schema_reference_form_correct:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t);if(!r)return[];let i=t.schema;if(i==null)return[];let a=e=>({isNamed:`id`in e,isInline:`type`in e});if(Array.isArray(i)){if(i.length===0)return[U(`SCHEMA_REF_FORM_INVALID`,`Field type '${n}' requires at least one reference`,``)];if(n!==`union`&&n!==`composite`&&n!==`enum`)return[U(`SCHEMA_REF_FORM_INVALID`,`Field type '${n}' cannot use an array of references`,``)];for(let e=0;e<i.length;e++){let t=i[e];if(typeof t!=`object`||!t)return[U(`SCHEMA_REF_FORM_INVALID`,`Element ${e} of schema array is not an object`,``)];let{isNamed:r,isInline:o}=a(t);if(n===`enum`){if(!r&&!o)return[U(`SCHEMA_REF_FORM_INVALID`,`Enum array element ${e} must be a named reference or inline descriptor`,``)]}else if(!r)return[U(`SCHEMA_REF_FORM_INVALID`,`Field type '${n}' array element ${e} must be a named schema reference (with 'id')`,``)]}}else if(typeof i==`object`){let{isNamed:e,isInline:t}=a(i);switch(n){case`array`:case`set`:case`record`:case`enum`:if(!e&&!t)return[U(`SCHEMA_REF_FORM_INVALID`,`Field type '${n}' requires a single named reference or an inline descriptor`,``)];break;case`object`:if(!e)return[U(`SCHEMA_REF_FORM_INVALID`,`Object field requires a single named schema reference`,``)];break;case`union`:case`composite`:return[U(`SCHEMA_REF_FORM_INVALID`,`Field type '${n}' requires an array of references`,``)]}}return[]},collection_requires_schema:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t);if(!r)return[];let i=t.schema;return bn(n)&&i==null?[U(`COLLECTION_MISSING_SCHEMA`,`Collection type '${n}' must have a schema reference`,``)]:[]},union_requires_multiple_schemas:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t);if(!r||n!==`union`)return[];let i=t.schema;return i==null?[U(`UNION_MISSING_SCHEMA`,`Union type must have schema references`,``)]:Array.isArray(i)?i.length<2?[U(`UNION_INSUFFICIENT_SCHEMAS`,`Union type must have at least 2 schema references, got ${i.length}`,``)]:[]:[U(`UNION_SCHEMA_NOT_ARRAY`,`Union type schema must be an array of schema references`,``)]},record_schema_cardinality:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let[n,r]=Q(t);if(!r||n!==`record`)return[];let i=t.schema;return Array.isArray(i)?[U(`RECORD_SCHEMA_ARRAY`,`Record type must have zero or one schema reference, not an array`,``)]:[]},nested_schema_exclusive_mode:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=!1;for(let e of gn){let r=t[e];if(typeof r==`object`&&r&&Object.keys(r).length>0){n=!0;break}}let r=!1;for(let e of _n)if(t[e]!=null){r=!0;break}return n&&r?[U(`NESTED_SCHEMA_MIXED_MODE`,`NestedSchema cannot mix BaseSchema fields (fields/indexes/constraints) with FieldProperties (type/values/schema)`,``)]:!n&&!r?[U(`NESTED_SCHEMA_NO_MODE`,`NestedSchema must have either BaseSchema fields or FieldProperties, not neither`,``)]:[]},constraint_type_exclusive:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=String(t.name||`UNNAMED`),r=!!(t.predicate&&String(t.predicate)!==``),i=!!(t.operator&&Array.isArray(t.rules)&&t.rules.length>0);return r&&i?[U(`CONSTRAINT_MIXED_TYPE`,`Constraint cannot have both predicate (rule) and operator+rules (group)`,n)]:!r&&!i?[U(`CONSTRAINT_NO_TYPE`,`Constraint must have either predicate (rule) or operator+rules (group)`,n)]:[]},constraint_rule_requires_predicate:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.predicate;return n===void 0?[U(`REQUIRED_FIELD_MISSING`,`Required field 'predicate' is missing`,`predicate`)]:n===null?[U(`REQUIRED_FIELD_NULL`,`Required field 'predicate' cannot be null`,`predicate`)]:typeof n==`string`?n.trim()===``?[U(`REQUIRED_FIELD_EMPTY`,`Required field 'predicate' cannot be empty`,`predicate`)]:[]:[U(`REQUIRED_FIELD_WRONG_TYPE`,`Required field 'predicate' must be a string`,`predicate`)]},index_condition_type_exclusive:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=!!(t.field&&t.operator&&t.value!==void 0),r=!!(t.operator&&Array.isArray(t.conditions)&&t.conditions.length>0);return n&&r?[U(`INDEX_CONDITION_MIXED_TYPE`,`IndexCondition cannot have both single condition fields and group fields`,``)]:!n&&!r?[U(`INDEX_CONDITION_NO_TYPE`,`IndexCondition must be either a single condition or a group`,``)]:[]},schema_name_required:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.name;return n==null||String(n).trim()===``?[U(`SCHEMA_NAME_MISSING`,`Schema name is required`,`name`)]:[]},field_name_required:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.name;return n==null||String(n).trim()===``?[U(`FIELD_NAME_MISSING`,`Field name is required`,`name`)]:[]},index_fields_not_empty:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.fields;return!Array.isArray(n)||n.length===0?[U(`INDEX_FIELDS_EMPTY`,`Index must reference at least one field`,`fields`)]:[]},schema_reference_id_required:e=>{let t=e.data;if(typeof t!=`object`||!t)return[];let n=t.id;return n==null||String(n).trim()===``?[U(`SCHEMA_REFERENCE_ID_MISSING`,`SchemaReference ID is required`,`id`)]:[]},index_fields_reference_valid:e=>[]};var kn=class{static validator=null;static async validate(e){return this.validator||=await fn.create(pn,On),await this.validator.validate(e)}};exports.AnansiCodec=Dt,exports.Compiler=c,exports.DataTypes=u,exports.DocumentValidator=fn,exports.FD_NO_CHILD=63,exports.FLAG_COMPRESSED=4,exports.FLAG_ENCRYPTED=64,exports.FLAG_HASH_PRESENT=128,exports.Literal=n,exports.MAX_SCHEMA_SLOTS=63,exports.MULTI_STEP_BASE=f,exports.SchemaValidator=kn,exports.addressForSteps=se,exports.buildEnum=l,exports.buildManifest=fe,exports.decodeAnansiBatch=Et,exports.decodeAnansiPacket=St,exports.decodeBatch=ot,exports.decodeDocument=nt,exports.defaultValidationConfig=Ot,exports.encodeAnansiBatchColumnar=Tt,exports.encodeAnansiBatchRows=wt,exports.encodeAnansiPacket=xt,exports.encodeBatchColumnar=it,exports.encodeBatchRows=rt,exports.encodeDocument=tt,exports.internalDP=p,exports.link=le,exports.makeDescriptor=ee,exports.metaSchemaPredicateMap=On,exports.parseSchema=r,exports.unpackDescriptor=m,exports.userDataDP=ce;
|