@asaidimu/anansi 1.2.2 → 1.2.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/index.cjs +33 -33
- package/index.d.cts +185 -1
- package/index.d.ts +185 -1
- package/index.js +33 -33
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
"use strict";var se=Object.create;var v=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var le=(e,r)=>{for(var t in r)v(e,t,{get:r[t],enumerable:!0})},B=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of pe(r))!de.call(e,a)&&a!==t&&v(e,a,{get:()=>r[a],enumerable:!(n=ce(r,a))||n.enumerable});return e};var C=(e,r,t)=>(t=e!=null?se(me(e)):{},B(r||!e||!e.__esModule?v(t,"default",{value:e,enumerable:!0}):t,e)),fe=e=>B(v({},"__esModule",{value:!0}),e);var Ge={};le(Ge,{JsonPatchError:()=>y,MigrationError:()=>L,MigrationErrorCode:()=>ae,MigrationSchema:()=>ee,applyPatch:()=>M,calculateNextVersion:()=>re,compareSemanticVersions:()=>R,createPatch:()=>ye,createSchemaMigrationHelper:()=>ie,createStandardSchemaValidator:()=>Q,deepMerge:()=>A,docgen:()=>He,generateSHA256Hash:()=>_,normalizePath:()=>z,schemaChangeToPatch:()=>q,schemaToTypes:()=>Le,sortSemanticVars:()=>Fe,validate:()=>Te,validateMigration:()=>te,validateSchemaChange:()=>ne,validateSchemaDefinition:()=>J});module.exports=fe(Ge);var Ne=require("@asaidimu/events");var Ae=require("@asaidimu/events"),k=require("@asaidimu/query");var y=class extends Error{constructor(t,n){super(t);this.operation=n;this.name="JsonPatchError"}};function x(e){let r=z(e);return r===""?[]:r.substring(1).split("/").map(ue)}function z(e){return e===""||e==="/"?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(T).join("/"):"/"+e.split(".").map(T).join("/")}function T(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ue(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var w=new Map;function E(e,r){let t=e;for(let n of r){if(t===null||typeof t!="object")throw new y(`Invalid path - parent not found at ${n}`);if(Array.isArray(t)){let a=n==="-"?t.length:parseInt(n);if(isNaN(a)||a<0||a>t.length)throw new y(`Invalid array index: ${n}`);t=t[a]}else{if(!t.hasOwnProperty(n))throw new y(`Property ${n} not found`);t=t[n]}}return t}function D(e,r){let t=w.get(r)||x(r);if(w.set(r,t),t.length===0)return e;let n=E(e,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(n)){let i=parseInt(a);if(isNaN(i)||i<0||i>=n.length)throw new y(`Invalid array index: ${a}`);return n[i]}return n[a]}function he(e,r,t){let n=w.get(r)||x(r);w.set(r,n);let a=E(e,n.slice(0,-1)),i=n[n.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(m=>m!==t)):a[i]===t&&delete a[i],e}function $(e,r,t){let n=w.get(r)||x(r);if(w.set(r,n),n.length===0)return t;let a=n.slice(0,-1),i=n[n.length-1],m=E(e,a);if(Array.isArray(m))if(i==="-")m.push(t);else{let c=parseInt(i);if(c<0||c>m.length)throw new y(`Invalid array index: ${i}`);m.splice(c,0,t)}else m[i]=t;return e}function O(e,r){let t=w.get(r)||x(r);if(w.set(r,t),t.length===0)return;let n=E(e,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(n)){let i=parseInt(a);n.splice(i,1)}else delete n[a];return e}function M(e,r){let t=JSON.parse(JSON.stringify(e));for(let n of r)try{switch(n.op){case"add":t=$(t,n.path,n.value);break;case"remove":t=O(t,n.path);break;case"removeValue":t=he(t,n.path,n.value);break;case"replace":t=$(O(t,n.path),n.path,n.value);break;case"copy":{let a=D(t,n.from);t=$(t,n.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=D(t,n.from);t=$(t,n.path,a),t=O(t,n.from);break}case"test":{let a=D(t,n.path);if(JSON.stringify(a)!==JSON.stringify(n.value))throw new y("Test operation failed");break}default:throw new y(`Unsupported operation: ${n.op}`)}}catch(a){throw a instanceof y&&(a.operation=n),a}return t}function ye(e,r){let t=[];return P(e,r,"",t),t}function P(e,r,t,n){if(e!==r){if(typeof e!=typeof r||Array.isArray(e)!==Array.isArray(r)){n.push({op:"replace",path:t,value:r});return}typeof e=="object"&&e!==null?Array.isArray(e)?ge(e,r,t,n):we(e,r,t,n):e!==r&&n.push({op:"replace",path:t,value:r})}}function ge(e,r,t,n){let a=Math.max(e.length,r.length);for(let i=0;i<a;i++){let m=`${t}/${i}`;i>=e.length?n.push({op:"add",path:`${t}/-`,value:r[i]}):i>=r.length?n.push({op:"remove",path:m}):P(e[i],r[i],m,n)}}function we(e,r,t,n){let a=new Set,i=Object.keys(e),m=Object.keys(r);for(let c of i){let d=T(c),s=t?`${t}/${d}`:`/${d}`;r.hasOwnProperty(c)?(P(e[c],r[c],s,n),a.add(c)):n.push({op:"remove",path:s})}for(let c of m)if(!a.has(c)){let d=T(c),s=t?`${t}/${d}`:`/${d}`;n.push({op:"add",path:s,value:r[c]})}}function q(e,r){let t=[];switch(e.type){case"addField":t.push({op:"add",path:`/fields/${e.name}`,value:e.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${e.name}`});break;case"modifyField":{let n=`/fields/${e.name}`;Object.entries(e.changes).forEach(([a,i])=>{typeof i=="object"&&i!==null&&!Array.isArray(i)?t.push({op:"replace",path:`${n}/${a}`,value:i}):t.push({op:"replace",path:`${n}/${a}`,value:i})});break}case"deprecateField":t.push({op:"add",path:`/fields/${e.name}/deprecated`,value:!0});break;case"addIndex":r.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let n=r.indexes?.findIndex(a=>a.name===e.name);n!==void 0&&n>=0&&t.push({op:"remove",path:`/indexes/${n}`});break}case"modifyIndex":{let n=r.indexes?.findIndex(a=>a.name===e.name);n!==void 0&&n>=0&&Object.entries(e.changes).forEach(([a,i])=>{t.push({op:"replace",path:`/indexes/${n}/${a}`,value:i})});break}case"addConstraint":r.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(n=>{t.push({op:"add",path:"/constraints/-",value:n})}):t.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let n=r.constraints?.findIndex(a=>Array.isArray(a)?a.some(i=>i.name===e.name):a.name===e.name);n!==void 0&&n>=0&&t.push({op:"remove",path:`/constraints/${n}`});break}case"modifyConstraint":{let n=Se(r,e.name);n&&Object.entries(e.changes).forEach(([a,i])=>{t.push({op:"replace",path:`${n}/${a}`,value:i})});break}}return t}function Se(e,r){if(!e.constraints)return null;for(let t=0;t<e.constraints.length;t++){let n=e.constraints[t];if(n.name===r)return`/constraints/${t}`;if(K(n)){let a=Y(n.rules,r);if(a)return`/constraints/${t}${a}`}}return null}function K(e){return e&&"operator"in e&&"rules"in e}function Y(e,r){for(let t=0;t<e.length;t++){let n=e[t];if("name"in n&&n.name===r)return`/rules/${t}`;if(K(n)){let a=Y(n.rules,r);if(a)return`/rules/${t}${a}`}}return null}function A(e,r){let t={...e};return F(e)&&F(r)&&Object.keys(r).forEach(n=>{F(r[n])?n in e?t[n]=A(e[n],r[n]):Object.assign(t,{[n]:r[n]}):Object.assign(t,{[n]:r[n]})}),t}function F(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Q(e,r){let t=(s,l,u,p)=>{let f=[];switch(u.type){case"string":typeof s!="string"&&f.push({message:`Expected type string but received ${typeof s}.`,path:p});break;case"number":typeof s!="number"&&f.push({message:`Expected type number but received ${typeof s}.`,path:p});break;case"boolean":typeof s!="boolean"&&f.push({message:`Expected type boolean but received ${typeof s}.`,path:p});break;case"array":Array.isArray(s)?u.itemsType?s.forEach((h,g)=>{f.push(...t(h,`Array: ${l}`,{type:u.itemsType,nestedSchema:u.nestedSchema},[...p,g]))}):f.push({message:`Expected itemsType for array ${l}`,path:p}):f.push({message:`Expected an array but received ${typeof s}.`,path:p});break;case"object":if(typeof s!="object"||s===null)f.push({message:`Expected an object but received ${s===null?"null":typeof s}.`,path:p});else if(u.nestedSchema){let h={name:u.description?`${u.description}-schema`:"nested-schema",version:"1.0",fields:u.nestedSchema};f.push(...d(h,s,p))}break;case"dynamic":break;default:f.push({message:`Unknown field type: ${u.type}`,path:p});break}return f},n=(s,l,u,p)=>{let f=[];return l.constraints&&l.constraints.forEach(h=>{let g=r[h.predicate];g?(h.type==="schema"?g({data:u,arguments:h.parameters}):g({data:u,field:s,arguments:h.parameters}))||f.push({message:`Constraint '${h.name}' failed for field '${s}'.`,path:p}):f.push({message:`Missing predicate for constraint: ${h.name}`,path:p})}),f},a=(s,l,u,p,f)=>[...t(u,s,l,f),...n(s,l,p,f)],i=(s,l,u)=>{if("operator"in s)return m(s.operator,s.rules.map(f=>i(f,l,u)));let p=r[s.predicate];return p?s.type==="schema"?p({data:l,field:s.field,arguments:s.parameters}):p({data:l,field:u,arguments:s.parameters}):!1},m=(s,l)=>{switch(s){case"and":return l.every(Boolean);case"or":return l.some(Boolean);case"not":return l.length===1?!l[0]:!1;case"nor":return!l.some(Boolean);case"xor":return l.filter(Boolean).length===1;default:return console.error(`Unknown logical operator: ${s}`),!1}},c=s=>"operator"in s?`(${s.rules.map(c).join(` ${s.operator} `)})`:s.name,d=(s,l,u=[])=>{let p=[];for(let[f,h]of Object.entries(s.fields))h.required&&l[f]===void 0&&p.push({message:`Field '${f}' is required.`,path:[...u,f]});for(let[f,h]of Object.entries(s.fields)){let g=l[f];g!==void 0&&p.push(...a(f,h,g,l,[...u,f]))}return s.constraints&&s.constraints.forEach(f=>{i(f,l)||p.push({message:`Schema constraint failed: ${c(f)}`,path:u})}),p};return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if(typeof s!="object"||s===null)return{issues:[{message:"Value must be a non-null object",path:[]}]};let l=d(e,s);return l.length===0?{value:s}:{issues:l}}}}}var o=require("zod");var S=class extends Error{constructor(t,n){super(t);this.errors=n;this.name="SchemaValidationError"}};var Z=o.z.enum(["and","or","not","nor","xor"]),W=o.z.enum(["string","number","boolean","array","object","dynamic"]),be=o.z.enum(["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"]),ve=o.z.custom(()=>!0),b=o.z.object({type:o.z.string().optional(),name:o.z.string(),predicate:o.z.string().optional(),parameters:ve.optional(),description:o.z.string().optional(),field:o.z.string().optional(),errorMessage:o.z.string().optional()}),V=o.z.object({operator:Z,rules:o.z.array(o.z.union([b,o.z.lazy(()=>V)]))}),I=o.z.object({type:W,required:o.z.boolean().optional(),constraints:o.z.array(b).optional(),default:o.z.any().optional(),itemsType:W.optional(),nestedSchema:o.z.record(o.z.lazy(()=>I)).optional(),deprecated:o.z.boolean().optional(),reference:o.z.object({schema:o.z.string(),field:o.z.string()}).optional(),description:o.z.string().optional(),unique:o.z.boolean().optional()}),X=o.z.object({operator:Z,field:o.z.string(),value:o.z.any().optional(),conditions:o.z.array(o.z.lazy(()=>X)).optional()}),N=o.z.object({fields:o.z.array(o.z.string()),type:be,unique:o.z.boolean().optional(),partial:X.optional(),description:o.z.string().optional(),order:o.z.enum(["asc","desc"]).optional(),name:o.z.string().optional()}),Ce=o.z.array(o.z.union([b,V])),$e=o.z.object({name:o.z.string(),version:o.z.string(),description:o.z.string().optional(),fields:o.z.record(I),indexes:o.z.array(N).optional(),constraints:Ce.optional(),metadata:o.z.record(o.z.any()).optional(),dependencies:o.z.array(o.z.string()).optional(),migrations:o.z.array(o.z.any()).optional()}),j=o.z.union([o.z.object({type:o.z.literal("addField"),name:o.z.string(),definition:I}),o.z.object({type:o.z.literal("removeField"),name:o.z.string()}),o.z.object({type:o.z.literal("modifyField"),name:o.z.string(),changes:I.partial()}),o.z.object({type:o.z.literal("addIndex"),definition:N}),o.z.object({type:o.z.literal("removeIndex"),name:o.z.string()}),o.z.object({type:o.z.literal("modifyIndex"),name:o.z.string(),changes:N.partial()}),o.z.object({type:o.z.literal("addConstraint"),constraint:o.z.union([b,V])}),o.z.object({type:o.z.literal("removeConstraint"),name:o.z.string()}),o.z.object({type:o.z.literal("modifyConstraint"),name:o.z.string(),changes:b.partial()}),o.z.object({type:o.z.literal("deprecateField"),name:o.z.string()})]),ee=o.z.object({id:o.z.string(),schemaVersion:o.z.string(),changes:o.z.array(j),description:o.z.string(),status:o.z.enum(["pending","applied","failed"]),rollback:o.z.array(j).optional(),transform:o.z.unknown(),createdAt:o.z.string(),checksum:o.z.string().optional()});function te(e){try{return ee.parse(e),!0}catch(r){throw new S("Invalid migration definition",r)}}function ne(e){try{return j.parse(e),!0}catch(r){throw new S("Invalid schema definition",r)}}function J(e){try{return $e.parse(e),!0}catch(r){throw new S("Invalid schema definition",r)}}var Te=J;var _=async e=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}else{let{createHash:r}=await import("crypto");return r("sha256").update(e).digest("hex")}};function xe(e){let r=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!r)throw new Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(r[1],10),minor:parseInt(r[2],10),patch:parseInt(r[3],10)}}function Ee(e,r){if(r&&"field"in e&&e.field){let t=r.fields[e.field];if(t)return t.type}if("parameters"in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function Ie(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function Re(e,r,t){switch(t){case"string":if(e instanceof RegExp&&r instanceof RegExp)return e.source!==r.source;if(Array.isArray(e)&&Array.isArray(r))return r.length<e.length||!e.every(n=>r.includes(n));break;case"number":if(typeof e=="object"&&typeof r=="object"&&"precision"in e&&"precision"in r)return r.precision<e.precision||(r.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(r))return r.length<e.length||!e.every(n=>r.includes(n));break;case"array":if(typeof e=="object"&&typeof r=="object"&&"minItems"in e&&"maxItems"in e&&"minItems"in r&&"maxItems"in r)return r.minItems>e.minItems||r.maxItems<e.maxItems;break;case"object":if(typeof e=="object"&&typeof r=="object"&&"schema"in e&&"schema"in r)return Object.keys(r.schema).length>Object.keys(e.schema).length;break}return!1}function ke(e,r){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(r.operator&&t[r.operator]>t[e.operator]||r.rules&&r.rules.length>e.rules.length)}function De(e,r,t){if(!r)return!0;if("rules"in r&&"rules"in e)return ke(r,e);if("predicate"in e&&e.predicate!==void 0)return!0;if("parameters"in e&&e.parameters!==void 0){let n=Ee(r,t);return n?Re(r.parameters,e.parameters,n):!0}return!1}function Oe(e,r){switch(e.type){case"removeField":case"removeIndex":return"major";case"modifyField":return Ie(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return e.changes.unique!==void 0||e.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=r?.constraints?.find(n=>"name"in n&&n.name===e.name);return De(e.changes,t,r)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Me(e){let r=new Set,t=new Set,n=new Set,a=new Set;for(let i of e)switch(i.type){case"addField":if(t.has(i.name))throw new Error(`Cannot add previously removed field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot add already modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot add deprecated field: ${i.name}`);n.add(i.name);break;case"removeField":if(n.has(i.name))throw new Error(`Cannot remove newly added field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot remove modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot remove field that is being deprecated: ${i.name}`);t.add(i.name);break;case"modifyField":if(t.has(i.name))throw new Error(`Cannot modify removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot modify newly added field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot modify field that is being deprecated: ${i.name}`);r.add(i.name);break;case"deprecateField":if(t.has(i.name))throw new Error(`Cannot deprecate removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot deprecate newly added field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot deprecate modified field: ${i.name}`);a.add(i.name);break}}function Pe(e){let r=new Set,t=new Set,n=new Set;for(let a of e)switch(a.type){case"addConstraint":let i=a.constraint,m=("name"in i,i.name);if(t.has(m))throw new Error(`Cannot add previously removed constraint: ${m}`);if(r.has(m))throw new Error(`Cannot add already modified constraint: ${m}`);n.add(m);break;case"removeConstraint":if(n.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(r.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);t.add(a.name);break;case"modifyConstraint":if(t.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(n.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);r.add(a.name);break}}function re(e,r,t){if(r.length===0)throw new Error("No changes provided");Me(r),Pe(r);let n=xe(e),a="patch";for(let i of r){let m=Oe(i,t);if(m==="major"){a="major";break}else m==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${n.major+1}.0.0`;case"minor":return`${n.major}.${n.minor+1}.0`;case"patch":return`${n.major}.${n.minor}.${n.patch+1}`}}function R(e,r){let t=s=>s.split(".").map(l=>parseInt(l,10)||0),[n,a,i]=t(e),[m,c,d]=t(r);return n-m||a-c||i-d}function Fe(e){return e.sort(R)}var L=class extends Error{constructor(t,n,a,i){super(t);this.code=n;this.migrationId=a;this.cause=i;this.name="MigrationError"}},ae=(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))(ae||{});var ie=e=>{let r=[],t=[];return{addField:(n,a)=>{r.push({type:"addField",name:n,definition:a}),t.push({type:"removeField",name:n})},removeField:n=>{r.push({type:"removeField",name:n});let a=e.fields[n];a&&t.push({type:"addField",name:n,definition:a})},modifyField:(n,a)=>{r.push({type:"modifyField",name:n,changes:a});let i=e.fields[n];t.push({type:"modifyField",name:n,changes:i})},deprecateField:n=>{r.push({type:"deprecateField",name:n}),t.push({type:"modifyField",name:n,changes:{deprecated:!1}})},addIndex:n=>{r.push({type:"addIndex",definition:n}),t.push({type:"removeIndex",name:n.name})},removeIndex:n=>{r.push({type:"removeIndex",name:n});let a=e.indexes?.find(i=>i.name===n);a&&t.push({type:"addIndex",definition:a})},modifyIndex:(n,a)=>{r.push({type:"modifyIndex",name:n,changes:a});let i=e.indexes?.find(m=>m.name===n);i&&t.push({type:"modifyIndex",name:n,changes:i})},addConstraint:n=>{r.push({type:"addConstraint",constraint:n}),t.push({type:"removeConstraint",name:n.name})},removeConstraint:n=>{r.push({type:"removeConstraint",name:n});let a=e.constraints?.find(i=>"name"in i&&i.name===n);a&&t.push({type:"addConstraint",constraint:a})},modifyConstraint:(n,a)=>{r.push({type:"modifyConstraint",name:n,changes:a});let i=e.constraints?.find(m=>"name"in m&&m.name===n);i&&t.push({type:"modifyConstraint",name:n,changes:i})},changes:()=>({migrate:r,rollback:t})}};var je=C(require("@isomorphic-git/lightning-fs"),1),oe=require("buffer"),Ve=C(require("isomorphic-git"),1),Je=C(require("isomorphic-git/http/web"),1);window.Buffer=oe.Buffer;function _e(e,r,t){switch(e.type){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return e.itemsType?e.itemsType==="object"&&e.nestedSchema?`${`${r}ItemsItem`}[]`:`${e.itemsType}[]`:"any[]";case"object":return e.nestedSchema?`${r}${U(t)}`:"Record<string, any>";case"dynamic":return"any";default:return"any"}}function H(e,r){let t="";for(let[n,a]of Object.entries(e))if(a.type==="object"&&a.nestedSchema){let i=`${r}${U(n)}`;t+=`
|
|
1
|
+
"use strict";var ce=Object.create;var T=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty;var fe=(r,t)=>{for(var e in t)T(r,e,{get:t[e],enumerable:!0})},Q=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of me(t))!le.call(r,a)&&a!==e&&T(r,a,{get:()=>t[a],enumerable:!(n=pe(t,a))||n.enumerable});return r};var C=(r,t,e)=>(e=r!=null?ce(de(r)):{},Q(t||!r||!r.__esModule?T(e,"default",{value:r,enumerable:!0}):e,r)),ue=r=>Q(T({},"__esModule",{value:!0}),r);var Ue={};fe(Ue,{JsonPatchError:()=>g,MigrationEngine:()=>z,MigrationError:()=>h,MigrationErrorCode:()=>ie,MigrationSchema:()=>ae,applyPatch:()=>k,calculateNextVersion:()=>B,compareSemanticVersions:()=>b,createPatch:()=>ge,createSchemaMigrationHelper:()=>oe,createStandardSchemaValidator:()=>ee,deepMerge:()=>J,docgen:()=>Ge,generateSHA256Hash:()=>M,normalizePath:()=>W,schemaChangeToPatch:()=>j,schemaToTypes:()=>He,sortSemanticVars:()=>Ae,validate:()=>xe,validateMigration:()=>G,validateSchemaChange:()=>U,validateSchemaDefinition:()=>O});module.exports=ue(Ue);var je=require("@asaidimu/events");var Ne=require("@asaidimu/events"),P=require("@asaidimu/query");var g=class extends Error{constructor(e,n){super(e);this.operation=n;this.name="JsonPatchError"}};function I(r){let t=W(r);return t===""?[]:t.substring(1).split("/").map(he)}function W(r){return r===""||r==="/"?"":r.startsWith("/")?"/"+r.substring(1).split("/").map(E).join("/"):"/"+r.split(".").map(E).join("/")}function E(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}function he(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}var S=new Map;function R(r,t){let e=r;for(let n of t){if(e===null||typeof e!="object")throw new g(`Invalid path - parent not found at ${n}`);if(Array.isArray(e)){let a=n==="-"?e.length:parseInt(n);if(isNaN(a)||a<0||a>e.length)throw new g(`Invalid array index: ${n}`);e=e[a]}else{if(!e.hasOwnProperty(n))throw new g(`Property ${n} not found`);e=e[n]}}return e}function F(r,t){let e=S.get(t)||I(t);if(S.set(t,e),e.length===0)return r;let n=R(r,e.slice(0,-1)),a=e[e.length-1];if(Array.isArray(n)){let i=parseInt(a);if(isNaN(i)||i<0||i>=n.length)throw new g(`Invalid array index: ${a}`);return n[i]}return n[a]}function ye(r,t,e){let n=S.get(t)||I(t);S.set(t,n);let a=R(r,n.slice(0,-1)),i=n[n.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(p=>p!==e)):a[i]===e&&delete a[i],r}function x(r,t,e){let n=S.get(t)||I(t);if(S.set(t,n),n.length===0)return e;let a=n.slice(0,-1),i=n[n.length-1],p=R(r,a);if(Array.isArray(p))if(i==="-")p.push(e);else{let s=parseInt(i);if(s<0||s>p.length)throw new g(`Invalid array index: ${i}`);p.splice(s,0,e)}else p[i]=e;return r}function A(r,t){let e=S.get(t)||I(t);if(S.set(t,e),e.length===0)return;let n=R(r,e.slice(0,-1)),a=e[e.length-1];if(Array.isArray(n)){let i=parseInt(a);n.splice(i,1)}else delete n[a];return r}function k(r,t){let e=JSON.parse(JSON.stringify(r));for(let n of t)try{switch(n.op){case"add":e=x(e,n.path,n.value);break;case"remove":e=A(e,n.path);break;case"removeValue":e=ye(e,n.path,n.value);break;case"replace":e=x(A(e,n.path),n.path,n.value);break;case"copy":{let a=F(e,n.from);e=x(e,n.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=F(e,n.from);e=x(e,n.path,a),e=A(e,n.from);break}case"test":{let a=F(e,n.path);if(JSON.stringify(a)!==JSON.stringify(n.value))throw new g("Test operation failed");break}default:throw new g(`Unsupported operation: ${n.op}`)}}catch(a){throw a instanceof g&&(a.operation=n),a}return e}function ge(r,t){let e=[];return N(r,t,"",e),e}function N(r,t,e,n){if(r!==t){if(typeof r!=typeof t||Array.isArray(r)!==Array.isArray(t)){n.push({op:"replace",path:e,value:t});return}typeof r=="object"&&r!==null?Array.isArray(r)?we(r,t,e,n):Se(r,t,e,n):r!==t&&n.push({op:"replace",path:e,value:t})}}function we(r,t,e,n){let a=Math.max(r.length,t.length);for(let i=0;i<a;i++){let p=`${e}/${i}`;i>=r.length?n.push({op:"add",path:`${e}/-`,value:t[i]}):i>=t.length?n.push({op:"remove",path:p}):N(r[i],t[i],p,n)}}function Se(r,t,e,n){let a=new Set,i=Object.keys(r),p=Object.keys(t);for(let s of i){let d=E(s),c=e?`${e}/${d}`:`/${d}`;t.hasOwnProperty(s)?(N(r[s],t[s],c,n),a.add(s)):n.push({op:"remove",path:c})}for(let s of p)if(!a.has(s)){let d=E(s),c=e?`${e}/${d}`:`/${d}`;n.push({op:"add",path:c,value:t[s]})}}function j(r,t){let e=[];switch(r.type){case"addField":e.push({op:"add",path:`/fields/${r.name}`,value:r.definition});break;case"removeField":e.push({op:"remove",path:`/fields/${r.name}`});break;case"modifyField":{let n=`/fields/${r.name}`;Object.entries(r.changes).forEach(([a,i])=>{typeof i=="object"&&i!==null&&!Array.isArray(i)?e.push({op:"replace",path:`${n}/${a}`,value:i}):e.push({op:"replace",path:`${n}/${a}`,value:i})});break}case"deprecateField":e.push({op:"add",path:`/fields/${r.name}/deprecated`,value:!0});break;case"addIndex":t.indexes||e.push({op:"add",path:"/indexes",value:[]}),e.push({op:"add",path:"/indexes/-",value:r.definition});break;case"removeIndex":{let n=t.indexes?.findIndex(a=>a.name===r.name);n!==void 0&&n>=0&&e.push({op:"remove",path:`/indexes/${n}`});break}case"modifyIndex":{let n=t.indexes?.findIndex(a=>a.name===r.name);n!==void 0&&n>=0&&Object.entries(r.changes).forEach(([a,i])=>{e.push({op:"replace",path:`/indexes/${n}/${a}`,value:i})});break}case"addConstraint":t.constraints||e.push({op:"add",path:"/constraints",value:[]}),Array.isArray(r.constraint)?r.constraint.forEach(n=>{e.push({op:"add",path:"/constraints/-",value:n})}):e.push({op:"add",path:"/constraints/-",value:r.constraint});break;case"removeConstraint":{let n=t.constraints?.findIndex(a=>Array.isArray(a)?a.some(i=>i.name===r.name):a.name===r.name);n!==void 0&&n>=0&&e.push({op:"remove",path:`/constraints/${n}`});break}case"modifyConstraint":{let n=be(t,r.name);n&&Object.entries(r.changes).forEach(([a,i])=>{e.push({op:"replace",path:`${n}/${a}`,value:i})});break}}return e}function be(r,t){if(!r.constraints)return null;for(let e=0;e<r.constraints.length;e++){let n=r.constraints[e];if(n.name===t)return`/constraints/${e}`;if(Z(n)){let a=X(n.rules,t);if(a)return`/constraints/${e}${a}`}}return null}function Z(r){return r&&"operator"in r&&"rules"in r}function X(r,t){for(let e=0;e<r.length;e++){let n=r[e];if("name"in n&&n.name===t)return`/rules/${e}`;if(Z(n)){let a=X(n.rules,t);if(a)return`/rules/${e}${a}`}}return null}function J(r,t){let e={...r};return V(r)&&V(t)&&Object.keys(t).forEach(n=>{V(t[n])?n in r?e[n]=J(r[n],t[n]):Object.assign(e,{[n]:t[n]}):Object.assign(e,{[n]:t[n]})}),e}function V(r){return r&&typeof r=="object"&&!Array.isArray(r)}function ee(r,t){let e=(c,l,f,m)=>{let u=[];switch(f.type){case"string":typeof c!="string"&&u.push({message:`Expected type string but received ${typeof c}.`,path:m});break;case"number":typeof c!="number"&&u.push({message:`Expected type number but received ${typeof c}.`,path:m});break;case"boolean":typeof c!="boolean"&&u.push({message:`Expected type boolean but received ${typeof c}.`,path:m});break;case"array":Array.isArray(c)?f.itemsType?c.forEach((y,w)=>{u.push(...e(y,`Array: ${l}`,{type:f.itemsType,nestedSchema:f.nestedSchema},[...m,w]))}):u.push({message:`Expected itemsType for array ${l}`,path:m}):u.push({message:`Expected an array but received ${typeof c}.`,path:m});break;case"object":if(typeof c!="object"||c===null)u.push({message:`Expected an object but received ${c===null?"null":typeof c}.`,path:m});else if(f.nestedSchema){let y={name:f.description?`${f.description}-schema`:"nested-schema",version:"1.0",fields:f.nestedSchema};u.push(...d(y,c,m))}break;case"dynamic":break;default:u.push({message:`Unknown field type: ${f.type}`,path:m});break}return u},n=(c,l,f,m)=>{let u=[];return l.constraints&&l.constraints.forEach(y=>{let w=t[y.predicate];w?(y.type==="schema"?w({data:f,arguments:y.parameters}):w({data:f,field:c,arguments:y.parameters}))||u.push({message:`Constraint '${y.name}' failed for field '${c}'.`,path:m}):u.push({message:`Missing predicate for constraint: ${y.name}`,path:m})}),u},a=(c,l,f,m,u)=>[...e(f,c,l,u),...n(c,l,m,u)],i=(c,l,f)=>{if("operator"in c)return p(c.operator,c.rules.map(u=>i(u,l,f)));let m=t[c.predicate];return m?c.type==="schema"?m({data:l,field:c.field,arguments:c.parameters}):m({data:l,field:f,arguments:c.parameters}):!1},p=(c,l)=>{switch(c){case"and":return l.every(Boolean);case"or":return l.some(Boolean);case"not":return l.length===1?!l[0]:!1;case"nor":return!l.some(Boolean);case"xor":return l.filter(Boolean).length===1;default:return console.error(`Unknown logical operator: ${c}`),!1}},s=c=>"operator"in c?`(${c.rules.map(s).join(` ${c.operator} `)})`:c.name,d=(c,l,f=[])=>{let m=[];for(let[u,y]of Object.entries(c.fields))y.required&&l[u]===void 0&&m.push({message:`Field '${u}' is required.`,path:[...f,u]});for(let[u,y]of Object.entries(c.fields)){let w=l[u];w!==void 0&&m.push(...a(u,y,w,l,[...f,u]))}return c.constraints&&c.constraints.forEach(u=>{i(u,l)||m.push({message:`Schema constraint failed: ${s(u)}`,path:f})}),m};return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:c=>{if(typeof c!="object"||c===null)return{issues:[{message:"Value must be a non-null object",path:[]}]};let l=d(r,c);return l.length===0?{value:c}:{issues:l}}}}}var o=require("zod");var v=class extends Error{constructor(e,n){super(e);this.errors=n;this.name="SchemaValidationError"}};var ne=o.z.enum(["and","or","not","nor","xor"]),te=o.z.enum(["string","number","boolean","array","object","dynamic"]),ve=o.z.enum(["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"]),Ce=o.z.custom(()=>!0),$=o.z.object({type:o.z.string().optional(),name:o.z.string(),predicate:o.z.string().optional(),parameters:Ce.optional(),description:o.z.string().optional(),field:o.z.string().optional(),errorMessage:o.z.string().optional()}),H=o.z.object({operator:ne,rules:o.z.array(o.z.union([$,o.z.lazy(()=>H)]))}),D=o.z.object({type:te,required:o.z.boolean().optional(),constraints:o.z.array($).optional(),default:o.z.any().optional(),itemsType:te.optional(),nestedSchema:o.z.record(o.z.lazy(()=>D)).optional(),deprecated:o.z.boolean().optional(),reference:o.z.object({schema:o.z.string(),field:o.z.string()}).optional(),description:o.z.string().optional(),unique:o.z.boolean().optional()}),re=o.z.object({operator:ne,field:o.z.string(),value:o.z.any().optional(),conditions:o.z.array(o.z.lazy(()=>re)).optional()}),_=o.z.object({fields:o.z.array(o.z.string()),type:ve,unique:o.z.boolean().optional(),partial:re.optional(),description:o.z.string().optional(),order:o.z.enum(["asc","desc"]).optional(),name:o.z.string().optional()}),$e=o.z.array(o.z.union([$,H])),Te=o.z.object({name:o.z.string(),version:o.z.string(),description:o.z.string().optional(),fields:o.z.record(D),indexes:o.z.array(_).optional(),constraints:$e.optional(),metadata:o.z.record(o.z.any()).optional(),dependencies:o.z.array(o.z.string()).optional(),migrations:o.z.array(o.z.any()).optional()}),L=o.z.union([o.z.object({type:o.z.literal("addField"),name:o.z.string(),definition:D}),o.z.object({type:o.z.literal("removeField"),name:o.z.string()}),o.z.object({type:o.z.literal("modifyField"),name:o.z.string(),changes:D.partial()}),o.z.object({type:o.z.literal("addIndex"),definition:_}),o.z.object({type:o.z.literal("removeIndex"),name:o.z.string()}),o.z.object({type:o.z.literal("modifyIndex"),name:o.z.string(),changes:_.partial()}),o.z.object({type:o.z.literal("addConstraint"),constraint:o.z.union([$,H])}),o.z.object({type:o.z.literal("removeConstraint"),name:o.z.string()}),o.z.object({type:o.z.literal("modifyConstraint"),name:o.z.string(),changes:$.partial()}),o.z.object({type:o.z.literal("deprecateField"),name:o.z.string()})]),ae=o.z.object({id:o.z.string(),schemaVersion:o.z.string(),changes:o.z.array(L),description:o.z.string(),status:o.z.enum(["pending","applied","failed"]),rollback:o.z.array(L).optional(),transform:o.z.unknown(),createdAt:o.z.string(),checksum:o.z.string().optional()});function G(r){try{return ae.parse(r),!0}catch(t){throw new v("Invalid migration definition",t)}}function U(r){try{return L.parse(r),!0}catch(t){throw new v("Invalid schema definition",t)}}function O(r){try{return Te.parse(r),!0}catch(t){throw new v("Invalid schema definition",t)}}var xe=O;var M=async r=>{if(typeof window<"u"&&crypto.subtle){let e=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}else{let{createHash:t}=await import("crypto");return t("sha256").update(r).digest("hex")}};function Ee(r){let t=r.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new Error(`Invalid version format: ${r}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}function Ie(r,t){if(t&&"field"in r&&r.field){let e=t.fields[r.field];if(e)return e.type}if("parameters"in r){let e=r.parameters;if(e instanceof RegExp||Array.isArray(e)&&typeof e[0]=="string")return"string";if(typeof e=="number"||Array.isArray(e)&&typeof e[0]=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="object"&&e!==null){if("minItems"in e||"maxItems"in e)return"array";if("schema"in e)return"object"}}}function Re(r){return r.required===!0||r.type!==void 0||r.itemsType!==void 0||r.nestedSchema!==void 0||r.reference!==void 0||r.unique===!0}function ke(r,t,e){switch(e){case"string":if(r instanceof RegExp&&t instanceof RegExp)return r.source!==t.source;if(Array.isArray(r)&&Array.isArray(t))return t.length<r.length||!r.every(n=>t.includes(n));break;case"number":if(typeof r=="object"&&typeof t=="object"&&"precision"in r&&"precision"in t)return t.precision<r.precision||(t.scale??0)<(r.scale??0);if(Array.isArray(r)&&Array.isArray(t))return t.length<r.length||!r.every(n=>t.includes(n));break;case"array":if(typeof r=="object"&&typeof t=="object"&&"minItems"in r&&"maxItems"in r&&"minItems"in t&&"maxItems"in t)return t.minItems>r.minItems||t.maxItems<r.maxItems;break;case"object":if(typeof r=="object"&&typeof t=="object"&&"schema"in r&&"schema"in t)return Object.keys(t.schema).length>Object.keys(r.schema).length;break}return!1}function De(r,t){let e={or:1,xor:2,and:3,not:4,nor:4};return!!(t.operator&&e[t.operator]>e[r.operator]||t.rules&&t.rules.length>r.rules.length)}function Oe(r,t,e){if(!t)return!0;if("rules"in t&&"rules"in r)return De(t,r);if("predicate"in r&&r.predicate!==void 0)return!0;if("parameters"in r&&r.parameters!==void 0){let n=Ie(t,e);return n?ke(t.parameters,r.parameters,n):!0}return!1}function Me(r,t){switch(r.type){case"removeField":case"removeIndex":return"major";case"modifyField":return Re(r.changes)?"major":r.changes.deprecated?"minor":"patch";case"modifyIndex":return r.changes.unique!==void 0||r.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let e=t?.constraints?.find(n=>"name"in n&&n.name===r.name);return Oe(r.changes,e,t)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(r)}`)}}function Pe(r){let t=new Set,e=new Set,n=new Set,a=new Set;for(let i of r)switch(i.type){case"addField":if(e.has(i.name))throw new Error(`Cannot add previously removed field: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot add already modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot add deprecated field: ${i.name}`);n.add(i.name);break;case"removeField":if(n.has(i.name))throw new Error(`Cannot remove newly added field: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot remove modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot remove field that is being deprecated: ${i.name}`);e.add(i.name);break;case"modifyField":if(e.has(i.name))throw new Error(`Cannot modify removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot modify newly added field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot modify field that is being deprecated: ${i.name}`);t.add(i.name);break;case"deprecateField":if(e.has(i.name))throw new Error(`Cannot deprecate removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot deprecate newly added field: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot deprecate modified field: ${i.name}`);a.add(i.name);break}}function Fe(r){let t=new Set,e=new Set,n=new Set;for(let a of r)switch(a.type){case"addConstraint":let i=a.constraint,p=("name"in i,i.name);if(e.has(p))throw new Error(`Cannot add previously removed constraint: ${p}`);if(t.has(p))throw new Error(`Cannot add already modified constraint: ${p}`);n.add(p);break;case"removeConstraint":if(n.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(t.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);e.add(a.name);break;case"modifyConstraint":if(e.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(n.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);t.add(a.name);break}}function B(r,t,e){if(t.length===0)throw new Error("No changes provided");Pe(t),Fe(t);let n=Ee(r),a="patch";for(let i of t){let p=Me(i,e);if(p==="major"){a="major";break}else p==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${n.major+1}.0.0`;case"minor":return`${n.major}.${n.minor+1}.0`;case"patch":return`${n.major}.${n.minor}.${n.patch+1}`}}function b(r,t){let e=c=>c.split(".").map(l=>parseInt(l,10)||0),[n,a,i]=e(r),[p,s,d]=e(t);return n-p||a-s||i-d}function Ae(r){return r.sort(b)}var h=class extends Error{constructor(e,n,a,i){super(e);this.code=n;this.migrationId=a;this.cause=i;this.name="MigrationError"}},ie=(m=>(m.INVALID_SCHEMA="INVALID_SCHEMA",m.INVALID_MIGRATION="INVALID_MIGRATION",m.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",m.TIMEOUT="TIMEOUT",m.MEMORY_LIMIT="MEMORY_LIMIT",m.CONCURRENT_OPERATION="CONCURRENT_OPERATION",m.TRANSFORM_ERROR="TRANSFORM_ERROR",m.VERSION_NOT_FOUND="VERSION_NOT_FOUND",m.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",m.STREAM_ERROR="STREAM_ERROR",m.ROLLBACK_ERROR="ROLLBACK_ERROR",m.MISSING_TRANSFORM="MISSING_TRANSFORM",m))(ie||{}),z=class r{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(t,e,n){try{if(!O(t))throw new h("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=t,e){if(!e.every(a=>G(a)))throw new h("Invalid migration configuration","INVALID_MIGRATION");this.migrations=e.sort((a,i)=>b(a.schemaVersion,i.schemaVersion))}n&&(this.history=n.sort((a,i)=>b(a.version,i.version)))}catch(a){throw a instanceof h?a:new h("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,a)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(t){try{let e=JSON.stringify({id:t.id,schemaVersion:t.schemaVersion,changes:t.changes,description:t.description,rollback:t.rollback,createdAt:t.createdAt});return await M(e)}catch(e){throw new h("Checksum generation failed","CHECKSUM_MISMATCH",t.id,e)}}async add(t){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");if(!t.changes?.length)throw new h("Migration must include changes","INVALID_MIGRATION");try{t.changes.forEach(n=>U(n))}catch(n){throw new h("Invalid schema changes","INVALID_MIGRATION",void 0,n)}let e={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:t.changes,description:t.description,status:"pending",rollback:t.rollback,transform:t.transform,createdAt:new Date().toISOString(),checksum:""};e.checksum=await this.generateChecksum(e),this.migrations.push(e)}async dryRun(t,e,n){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},i=this.getRelevantMigrations(e,n),p=i.reduce((d,c)=>{let l=e==="forward"?c.changes:c.rollback||[];return this.applySchemaChanges(d,l,c.id)},a),s=await r.processMigrationList(t,e,i);return{newSchema:p,dataPreview:s}}catch(a){throw a instanceof h?a:new h("Dry run failed","INVALID_SCHEMA",void 0,a)}finally{this.isProcessing=!1}}getRelevantMigrations(t,e){return[...this.migrations].filter(n=>{let a=t==="forward"?"pending":"applied",i=e?b(n.schemaVersion,e)>=0:!0;return n.status===a&&i}).sort((n,a)=>t==="forward"?n.id.localeCompare(a.id):a.id.localeCompare(n.id))}applySchemaChanges(t,e,n){try{let a=B(t.version,e);return e.map(p=>{try{return j(p,t)}catch(s){throw new h("Invalid schema change","INVALID_SCHEMA",n,s)}}).reduce((p,s)=>{try{return k(p,s)}catch(d){throw new h("Failed to apply patch","INVALID_SCHEMA",n,d)}},{...t,version:a})}catch(a){throw a instanceof h?a:new h("Schema update failed","INVALID_SCHEMA",n,a)}}async prepareMigration(){let t=this.migrations.filter(e=>e.status==="pending");return await this.validateMigrations(t),t}async migrate(t){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");let e=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let n=await r.processMigrationList(t,"forward",e);return this.markMigrationsApplied(e),n}finally{this.isProcessing=!1}}async validateMigrations(t){await Promise.all(t.map(async e=>{let n=await this.generateChecksum(e);if(e.checksum!==n)throw new h("Checksum mismatch","CHECKSUM_MISMATCH",e.id)}))}markMigrationsApplied(t){this.migrations=this.migrations.map(e=>t.some(n=>n.id===e.id)?{...e,status:"applied"}:e)}async rollback(t){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(n=>n.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,t):t}async rollbackToVersion(t,e){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");try{let n=this.history.findIndex(s=>s.version===t);if(n===-1)throw new Error(`Version ${t} not found in history`);let a=this.migrations.filter(s=>s.schemaVersion===t&&s.status==="applied").sort((s,d)=>d.id.localeCompare(s.id)),i=this.history.length-n;if(i<0)return e;for(let s=0;s<i;s++)this.transformSchema("backward");let p=await r.processMigrationList(e,"backward",a);return this.migrations=this.migrations.map(s=>s.schemaVersion===t&&s.status==="applied"?{...s,status:"pending"}:s),p}finally{this.isProcessing=!1}}static async processMigrationList(t,e,n){return(await Promise.all(n.map(async p=>{try{let s=await this.resolveTransform(p,e);return{migration:p,transform:s}}catch(s){throw new h(`Failed to resolve transform for migration ${p.id}`,"TRANSFORM_ERROR",p.id,s)}}))).filter(p=>!!p.transform).reduce((p,{migration:s,transform:d})=>p.pipeThrough(new TransformStream({async transform(c,l){try{let f=await d(c);l.enqueue(f)}catch(f){l.error(new h(`Data transformation failed for migration ${s.id}`,"TRANSFORM_ERROR",s.id,f))}}})),t)}static async resolveTransform(t,e){return t.transform?typeof t.transform=="string"?t.transform.startsWith("http://")||t.transform.startsWith("https://")?this.resolveRemoteTransform(t.transform,e):this.resolveLocalTransform(t.transform,e):t.transform[e]:null}static async resolveRemoteTransform(t,e){try{let n=await fetch(t);if(!n.ok)throw new h(`Failed to fetch transform module: ${t}`,"TRANSFORM_ERROR",void 0);let a=await n.text();if(typeof window<"u"){let i=new Blob([a],{type:"application/javascript"});return(await import(URL.createObjectURL(i))).default[e]}else{let{runInNewContext:i}=await import("vm"),p={module:{exports:{}},console};return i(a,p,t),p.module.exports[e]}}catch(n){throw new h(`Failed to load remote transform module: ${t}`,"TRANSFORM_ERROR",void 0,n)}}static async resolveLocalTransform(t,e){try{return(await import(t)).default[e]}catch(n){throw new h(`Failed to import local transform module: ${t}`,"TRANSFORM_ERROR",void 0,n)}}transformSchema(t){try{if(t==="backward"){let n=this.history.pop();if(!n)throw new Error("No previous version");this.currentSchema=n;return}let e=this.migrations.filter(n=>n.status==="pending").flatMap(n=>n.changes);if(!e.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=e.reduce((n,a)=>this.applySchemaChanges(n,[a]),this.currentSchema)}catch(e){throw e instanceof h?e:new h("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};var oe=r=>{let t=[],e=[];return{addField:(n,a)=>{t.push({type:"addField",name:n,definition:a}),e.push({type:"removeField",name:n})},removeField:n=>{t.push({type:"removeField",name:n});let a=r.fields[n];a&&e.push({type:"addField",name:n,definition:a})},modifyField:(n,a)=>{t.push({type:"modifyField",name:n,changes:a});let i=r.fields[n];e.push({type:"modifyField",name:n,changes:i})},deprecateField:n=>{t.push({type:"deprecateField",name:n}),e.push({type:"modifyField",name:n,changes:{deprecated:!1}})},addIndex:n=>{t.push({type:"addIndex",definition:n}),e.push({type:"removeIndex",name:n.name})},removeIndex:n=>{t.push({type:"removeIndex",name:n});let a=r.indexes?.find(i=>i.name===n);a&&e.push({type:"addIndex",definition:a})},modifyIndex:(n,a)=>{t.push({type:"modifyIndex",name:n,changes:a});let i=r.indexes?.find(p=>p.name===n);i&&e.push({type:"modifyIndex",name:n,changes:i})},addConstraint:n=>{t.push({type:"addConstraint",constraint:n}),e.push({type:"removeConstraint",name:n.name})},removeConstraint:n=>{t.push({type:"removeConstraint",name:n});let a=r.constraints?.find(i=>"name"in i&&i.name===n);a&&e.push({type:"addConstraint",constraint:a})},modifyConstraint:(n,a)=>{t.push({type:"modifyConstraint",name:n,changes:a});let i=r.constraints?.find(p=>"name"in p&&p.name===n);i&&e.push({type:"modifyConstraint",name:n,changes:i})},changes:()=>({migrate:t,rollback:e})}};var Ve=C(require("@isomorphic-git/lightning-fs"),1),se=require("buffer"),Je=C(require("isomorphic-git"),1),_e=C(require("isomorphic-git/http/web"),1);window.Buffer=se.Buffer;function Le(r,t,e){switch(r.type){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return r.itemsType?r.itemsType==="object"&&r.nestedSchema?`${`${t}ItemsItem`}[]`:`${r.itemsType}[]`:"any[]";case"object":return r.nestedSchema?`${t}${Y(e)}`:"Record<string, any>";case"dynamic":return"any";default:return"any"}}function q(r,t){let e="";for(let[n,a]of Object.entries(r))if(a.type==="object"&&a.nestedSchema){let i=`${t}${Y(n)}`;e+=`
|
|
2
2
|
export interface ${i} {
|
|
3
|
-
${
|
|
4
|
-
}`;let
|
|
5
|
-
${
|
|
3
|
+
${K(a.nestedSchema,i)}
|
|
4
|
+
}`;let p=q(a.nestedSchema,i);p&&(e+=`
|
|
5
|
+
${p}`)}else if(a.type==="array"&&a.itemsType==="object"&&a.nestedSchema){let i=`${t}ItemsItem`;e+=`
|
|
6
6
|
export interface ${i} {
|
|
7
|
-
${
|
|
8
|
-
}`;let
|
|
9
|
-
${
|
|
7
|
+
${K(a.nestedSchema,i)}
|
|
8
|
+
}`;let p=q(a.nestedSchema,i);p&&(e+=`
|
|
9
|
+
${p}`)}return e}function K(r,t){return Object.entries(r).map(([e,n])=>{let a=[];n.description&&a.push(` /** ${n.description} */`),n.deprecated&&a.push(" /** @deprecated */");let i=n.required?"":"?",p=Le(n,t,e);return a.push(` ${e}${i}: ${p};`),a.join(`
|
|
10
10
|
`)}).join(`
|
|
11
|
-
`)}function
|
|
12
|
-
`;
|
|
13
|
-
`),
|
|
14
|
-
${
|
|
15
|
-
}`;let n=
|
|
16
|
-
${n}`),
|
|
17
|
-
`,
|
|
11
|
+
`)}function Y(r){return r.charAt(0).toUpperCase()+r.slice(1)}function He(r){let t=Y(r.name),e=`// Generated from schema version ${r.version}
|
|
12
|
+
`;r.description&&(e+=`/** ${r.description} */
|
|
13
|
+
`),e+=`export interface ${t} {
|
|
14
|
+
${K(r.fields,t)}
|
|
15
|
+
}`;let n=q(r.fields,t);return n&&(e+=`
|
|
16
|
+
${n}`),e+=`
|
|
17
|
+
`,e}function Ge(r,t){let e=[],n=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,a=(s=[])=>s.map(d=>`- **${d.name}**: ${d.description||""}
|
|
18
18
|
- Parameters: ${JSON.stringify(d.parameters)}
|
|
19
19
|
- Error: ${d.errorMessage||"None"}`).join(`
|
|
20
|
-
`),i=
|
|
21
|
-
${
|
|
20
|
+
`),i=s=>{let d=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(d+=` ${JSON.stringify(s.value)}`),s.conditions&&(d+=` [
|
|
21
|
+
${s.conditions.map(c=>` ${i(c)}`).join(`
|
|
22
22
|
`)}
|
|
23
|
-
]`),d},
|
|
23
|
+
]`),d},p=(s,d=1)=>{let c="#".repeat(d+2);return Object.entries(s).map(([l,f])=>{let m=`${c} ${l} (${f.type})
|
|
24
24
|
|
|
25
|
-
`;return
|
|
25
|
+
`;return m+=`**Required:** ${f.required?"Yes":"No"}
|
|
26
26
|
|
|
27
|
-
`,
|
|
27
|
+
`,f.description&&(m+=`**Description:** ${f.description}
|
|
28
28
|
|
|
29
|
-
`),
|
|
29
|
+
`),f.itemsType&&(m+=`**Item Type:** ${f.itemsType}
|
|
30
30
|
|
|
31
|
-
`),
|
|
32
|
-
`)};
|
|
33
|
-
${
|
|
34
|
-
`),
|
|
35
|
-
`),
|
|
36
|
-
`),
|
|
37
|
-
### Nested Schema: ${
|
|
38
|
-
`),
|
|
31
|
+
`),f.nestedSchema&&(m+=p(f.nestedSchema,d+1)),m}).join(`
|
|
32
|
+
`)};e.push(`# ${r.name} Schema (Version ${r.version})`),r.description&&e.push(`
|
|
33
|
+
${r.description}
|
|
34
|
+
`),e.push("## Metadata"),e.push(`- **Dependencies:** ${r.dependencies?.join(", ")||"None"}`),e.push(`- **Created:** ${new Date().toISOString()}
|
|
35
|
+
`),e.push(`## Fields
|
|
36
|
+
`),e.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),e.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,d]of Object.entries(r.fields))e.push([s,d.type,d.required?"Yes":"No",n(d.default),d.description?.replace(/\n/g," ")||"",d.deprecated?"Yes":"No",d.unique?"Yes":"No",d.constraints?.length||0].join("|"));Object.entries(r.fields).forEach(([s,d])=>{d.nestedSchema&&(e.push(`
|
|
37
|
+
### Nested Schema: ${s}
|
|
38
|
+
`),e.push(p(d.nestedSchema)))}),e.push(`
|
|
39
39
|
## Indexes
|
|
40
|
-
`),
|
|
40
|
+
`),e.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),e.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of r.indexes||[])e.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?i(s.partial):"None",s.description||""].join("|"));e.push(`
|
|
41
41
|
## Constraints
|
|
42
|
-
`),
|
|
42
|
+
`),r.constraints&&e.push("### Schema-level Constraints"),e.push(`
|
|
43
43
|
## Migrations
|
|
44
|
-
`),
|
|
45
|
-
<!-- Error generating mock data -->`)}return
|
|
46
|
-
`)}0&&(module.exports={JsonPatchError,MigrationError,MigrationErrorCode,MigrationSchema,applyPatch,calculateNextVersion,compareSemanticVersions,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,generateSHA256Hash,normalizePath,schemaChangeToPatch,schemaToTypes,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
|
|
44
|
+
`),e.push("| ID | Description | Status | Changes |"),e.push("|----|-------------|--------|---------|");for(let s of r.migrations||[])e.push([s.id,s.description,s.status,s.changes.length].join("|"));if(r.mock&&t?.faker)try{let s=r.mock(t.faker).next().value;e.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{e.push(`
|
|
45
|
+
<!-- Error generating mock data -->`)}return e.join(`
|
|
46
|
+
`)}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,MigrationSchema,applyPatch,calculateNextVersion,compareSemanticVersions,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,generateSHA256Hash,normalizePath,schemaChangeToPatch,schemaToTypes,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
|
package/index.d.cts
CHANGED
|
@@ -857,6 +857,190 @@ declare enum MigrationErrorCode {
|
|
|
857
857
|
ROLLBACK_ERROR = "ROLLBACK_ERROR",
|
|
858
858
|
MISSING_TRANSFORM = "MISSING_TRANSFORM"
|
|
859
859
|
}
|
|
860
|
+
/**
|
|
861
|
+
* @class MigrationEngine
|
|
862
|
+
* @param {SchemaDefinition} currentSchema - The current schema definition
|
|
863
|
+
* @param {Array<Migration<any>>} [migrations] - Optional array of migrations
|
|
864
|
+
* @throws {MigrationError} If the initial schema or migrations are invalid
|
|
865
|
+
*/
|
|
866
|
+
declare class MigrationEngine {
|
|
867
|
+
private currentSchema;
|
|
868
|
+
private history;
|
|
869
|
+
private migrations;
|
|
870
|
+
private isProcessing;
|
|
871
|
+
/**
|
|
872
|
+
* @constructor
|
|
873
|
+
* @param {SchemaDefinition} currentSchema - The current schema definition
|
|
874
|
+
* @param {Array<Migration<any>>} [migrations] - Optional array of migrations
|
|
875
|
+
*/
|
|
876
|
+
constructor(currentSchema: SchemaDefinition, migrations?: Array<Migration<any>>, history?: Array<SchemaDefinition>);
|
|
877
|
+
/**
|
|
878
|
+
* Gets the current state of the migration helper
|
|
879
|
+
* @returns {Object} Current state containing schema, history, and migrations
|
|
880
|
+
* @example
|
|
881
|
+
* ```javascript
|
|
882
|
+
* const state = migrationEngine.data();
|
|
883
|
+
* // state contains currentSchema, history, and migrations
|
|
884
|
+
* ```
|
|
885
|
+
*/
|
|
886
|
+
data(): {
|
|
887
|
+
schema: SchemaDefinition;
|
|
888
|
+
history: SchemaDefinition[];
|
|
889
|
+
migrations: Migration<any>[];
|
|
890
|
+
};
|
|
891
|
+
/**
|
|
892
|
+
* Generates a SHA-256 checksum for a migration
|
|
893
|
+
* @private
|
|
894
|
+
* @param {Omit<Migration<any>, "checksum">} migration - The migration object
|
|
895
|
+
* @returns {Promise<string>} The generated checksum
|
|
896
|
+
* @throws {MigrationError} If checksum generation fails
|
|
897
|
+
*/
|
|
898
|
+
private generateChecksum;
|
|
899
|
+
/**
|
|
900
|
+
* Adds a new migration to the engine
|
|
901
|
+
* @async
|
|
902
|
+
* @param {Object} opts - Options for the new migration
|
|
903
|
+
* @param {SchemaChange<any>[]} opts.changes - Array of schema changes
|
|
904
|
+
* @param {string} opts.description - Description of the migration
|
|
905
|
+
* @param {SchemaChange<any>[]} [opts.rollback] - Optional rollback changes
|
|
906
|
+
* @param {DataTransform<any, any>} [opts.transform] - Optional data transform
|
|
907
|
+
* @throws {MigrationError} If adding the migration fails
|
|
908
|
+
*/
|
|
909
|
+
add(opts: {
|
|
910
|
+
changes: SchemaChange<any>[];
|
|
911
|
+
description: string;
|
|
912
|
+
rollback?: SchemaChange<any>[];
|
|
913
|
+
transform?: string | DataTransform<any, any>;
|
|
914
|
+
}): Promise<void>;
|
|
915
|
+
/**
|
|
916
|
+
* Performs a dry run of the migration
|
|
917
|
+
* @async
|
|
918
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
919
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
920
|
+
* @param {version} version - Version to rollback to
|
|
921
|
+
* @returns {Promise<Object>} Object containing newSchema and dataPreview
|
|
922
|
+
* @throws {MigrationError} If dry run fails
|
|
923
|
+
*/
|
|
924
|
+
dryRun(input: ReadableStream<any>, direction: "forward" | "backward", version?: string): Promise<{
|
|
925
|
+
newSchema: SchemaDefinition;
|
|
926
|
+
dataPreview: ReadableStream<any>;
|
|
927
|
+
}>;
|
|
928
|
+
/**
|
|
929
|
+
* Gets relevant migrations based on direction
|
|
930
|
+
* @private
|
|
931
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
932
|
+
* @returns {Array<Migration<any>>} Relevant migrations
|
|
933
|
+
*/
|
|
934
|
+
private getRelevantMigrations;
|
|
935
|
+
/**
|
|
936
|
+
* Applies schema changes to a given schema
|
|
937
|
+
* @private
|
|
938
|
+
* @param {SchemaDefinition} schema - The schema to modify
|
|
939
|
+
* @param {SchemaChange<any>[]} changes - Array of schema changes
|
|
940
|
+
* @param {string} [migrationId] - ID of the migration
|
|
941
|
+
* @returns {SchemaDefinition} Modified schema
|
|
942
|
+
* @throws {MigrationError} If applying changes fails
|
|
943
|
+
*/
|
|
944
|
+
private applySchemaChanges;
|
|
945
|
+
/**
|
|
946
|
+
* Prepares the list of pending migrations for application
|
|
947
|
+
* @async
|
|
948
|
+
* @returns {Promise<Array<Migration<any>>} List of pending migrations
|
|
949
|
+
* @throws {MigrationError} If preparation fails
|
|
950
|
+
*/
|
|
951
|
+
prepareMigration(): Promise<Array<Migration<any>>>;
|
|
952
|
+
/**
|
|
953
|
+
* Applies pending migrations
|
|
954
|
+
* @async
|
|
955
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
956
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
957
|
+
* @throws {MigrationError} If migration fails
|
|
958
|
+
*/
|
|
959
|
+
migrate(input: ReadableStream<any>): Promise<ReadableStream<any>>;
|
|
960
|
+
/**
|
|
961
|
+
* Validates migrations by checking their checksums
|
|
962
|
+
* @private
|
|
963
|
+
* @async
|
|
964
|
+
* @param {Array<Migration<any>>} migrations - Migrations to validate
|
|
965
|
+
* @throws {MigrationError} If validation fails
|
|
966
|
+
*/
|
|
967
|
+
private validateMigrations;
|
|
968
|
+
/**
|
|
969
|
+
* Marks migrations as applied
|
|
970
|
+
* @private
|
|
971
|
+
* @param {Array<Migration<any>>} migrations - Migrations to mark as applied
|
|
972
|
+
*/
|
|
973
|
+
private markMigrationsApplied;
|
|
974
|
+
/**
|
|
975
|
+
* Rolls back the last applied migration
|
|
976
|
+
* @async
|
|
977
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
978
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
979
|
+
*/
|
|
980
|
+
rollback(input: ReadableStream<any>): Promise<ReadableStream<any>>;
|
|
981
|
+
/**
|
|
982
|
+
* Rolls back to a specific schema version
|
|
983
|
+
* @async
|
|
984
|
+
* @param {string} targetVersion - Target schema version
|
|
985
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
986
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
987
|
+
* @throws {Error} If target version is not found
|
|
988
|
+
*/
|
|
989
|
+
rollbackToVersion(targetVersion: string, input: ReadableStream<any>): Promise<ReadableStream<any>>;
|
|
990
|
+
/**
|
|
991
|
+
* Processes a list of migrations on a data stream, applying transformations
|
|
992
|
+
* in the specified direction (forward or backward).
|
|
993
|
+
*
|
|
994
|
+
* @static
|
|
995
|
+
* @async
|
|
996
|
+
* @param {ReadableStream<any>} input - The input data stream to process
|
|
997
|
+
* @param {"forward" | "backward"} direction - Direction of migration (either "forward" or "backward")
|
|
998
|
+
* @param {Array<Migration<any>>} migrations - Array of Migration objects to process
|
|
999
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
1000
|
+
* @throws {MigrationError} If any migration processing fails
|
|
1001
|
+
*/
|
|
1002
|
+
static processMigrationList(input: ReadableStream<any>, direction: "forward" | "backward", migrations: Migration<any>[]): Promise<ReadableStream<any>>;
|
|
1003
|
+
/**
|
|
1004
|
+
* Resolves the transform function for a given migration in the specified direction.
|
|
1005
|
+
*
|
|
1006
|
+
* @private
|
|
1007
|
+
* @async
|
|
1008
|
+
* @param {Migration<any>} migration - The migration to resolve the transform for
|
|
1009
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
1010
|
+
* @returns {Promise<TransformFunction<any, any>>} Resolved transform function
|
|
1011
|
+
* @throws {MigrationError} If transform resolution fails
|
|
1012
|
+
*/
|
|
1013
|
+
private static resolveTransform;
|
|
1014
|
+
/**
|
|
1015
|
+
* Resolves a transform function from a remote URL.
|
|
1016
|
+
*
|
|
1017
|
+
* @private
|
|
1018
|
+
* @async
|
|
1019
|
+
* @param {string} url - URL of the transform module
|
|
1020
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
1021
|
+
* @returns {Promise<TransformFunction<any, any>>} Resolved transform function
|
|
1022
|
+
* @throws {MigrationError} If resolution fails
|
|
1023
|
+
*/
|
|
1024
|
+
private static resolveRemoteTransform;
|
|
1025
|
+
/**
|
|
1026
|
+
* Resolves a transform function from a local module path.
|
|
1027
|
+
*
|
|
1028
|
+
* @private
|
|
1029
|
+
* @async
|
|
1030
|
+
* @param {string} path - Local module path
|
|
1031
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
1032
|
+
* @returns {Promise<TransformFunction<any, any>>} Resolved transform function
|
|
1033
|
+
* @throws {MigrationError} If resolution fails
|
|
1034
|
+
*/
|
|
1035
|
+
private static resolveLocalTransform;
|
|
1036
|
+
/**
|
|
1037
|
+
* Transforms the schema either forward or backward
|
|
1038
|
+
* @private
|
|
1039
|
+
* @param {"forward" | "backward"} direction - Direction of transformation
|
|
1040
|
+
* @throws {Error} If transformation fails
|
|
1041
|
+
*/
|
|
1042
|
+
private transformSchema;
|
|
1043
|
+
}
|
|
860
1044
|
|
|
861
1045
|
/**
|
|
862
1046
|
* Helper for building schema migrations with forward and rollback changes.
|
|
@@ -1696,4 +1880,4 @@ declare function docgen(schema: SchemaDefinition, options?: {
|
|
|
1696
1880
|
faker?: Faker;
|
|
1697
1881
|
}): string;
|
|
1698
1882
|
|
|
1699
|
-
export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, MigrationSchema, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, type SchemaRegistry, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaToTypes, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
|
|
1883
|
+
export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, MigrationSchema, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, type SchemaRegistry, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaToTypes, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
|
package/index.d.ts
CHANGED
|
@@ -857,6 +857,190 @@ declare enum MigrationErrorCode {
|
|
|
857
857
|
ROLLBACK_ERROR = "ROLLBACK_ERROR",
|
|
858
858
|
MISSING_TRANSFORM = "MISSING_TRANSFORM"
|
|
859
859
|
}
|
|
860
|
+
/**
|
|
861
|
+
* @class MigrationEngine
|
|
862
|
+
* @param {SchemaDefinition} currentSchema - The current schema definition
|
|
863
|
+
* @param {Array<Migration<any>>} [migrations] - Optional array of migrations
|
|
864
|
+
* @throws {MigrationError} If the initial schema or migrations are invalid
|
|
865
|
+
*/
|
|
866
|
+
declare class MigrationEngine {
|
|
867
|
+
private currentSchema;
|
|
868
|
+
private history;
|
|
869
|
+
private migrations;
|
|
870
|
+
private isProcessing;
|
|
871
|
+
/**
|
|
872
|
+
* @constructor
|
|
873
|
+
* @param {SchemaDefinition} currentSchema - The current schema definition
|
|
874
|
+
* @param {Array<Migration<any>>} [migrations] - Optional array of migrations
|
|
875
|
+
*/
|
|
876
|
+
constructor(currentSchema: SchemaDefinition, migrations?: Array<Migration<any>>, history?: Array<SchemaDefinition>);
|
|
877
|
+
/**
|
|
878
|
+
* Gets the current state of the migration helper
|
|
879
|
+
* @returns {Object} Current state containing schema, history, and migrations
|
|
880
|
+
* @example
|
|
881
|
+
* ```javascript
|
|
882
|
+
* const state = migrationEngine.data();
|
|
883
|
+
* // state contains currentSchema, history, and migrations
|
|
884
|
+
* ```
|
|
885
|
+
*/
|
|
886
|
+
data(): {
|
|
887
|
+
schema: SchemaDefinition;
|
|
888
|
+
history: SchemaDefinition[];
|
|
889
|
+
migrations: Migration<any>[];
|
|
890
|
+
};
|
|
891
|
+
/**
|
|
892
|
+
* Generates a SHA-256 checksum for a migration
|
|
893
|
+
* @private
|
|
894
|
+
* @param {Omit<Migration<any>, "checksum">} migration - The migration object
|
|
895
|
+
* @returns {Promise<string>} The generated checksum
|
|
896
|
+
* @throws {MigrationError} If checksum generation fails
|
|
897
|
+
*/
|
|
898
|
+
private generateChecksum;
|
|
899
|
+
/**
|
|
900
|
+
* Adds a new migration to the engine
|
|
901
|
+
* @async
|
|
902
|
+
* @param {Object} opts - Options for the new migration
|
|
903
|
+
* @param {SchemaChange<any>[]} opts.changes - Array of schema changes
|
|
904
|
+
* @param {string} opts.description - Description of the migration
|
|
905
|
+
* @param {SchemaChange<any>[]} [opts.rollback] - Optional rollback changes
|
|
906
|
+
* @param {DataTransform<any, any>} [opts.transform] - Optional data transform
|
|
907
|
+
* @throws {MigrationError} If adding the migration fails
|
|
908
|
+
*/
|
|
909
|
+
add(opts: {
|
|
910
|
+
changes: SchemaChange<any>[];
|
|
911
|
+
description: string;
|
|
912
|
+
rollback?: SchemaChange<any>[];
|
|
913
|
+
transform?: string | DataTransform<any, any>;
|
|
914
|
+
}): Promise<void>;
|
|
915
|
+
/**
|
|
916
|
+
* Performs a dry run of the migration
|
|
917
|
+
* @async
|
|
918
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
919
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
920
|
+
* @param {version} version - Version to rollback to
|
|
921
|
+
* @returns {Promise<Object>} Object containing newSchema and dataPreview
|
|
922
|
+
* @throws {MigrationError} If dry run fails
|
|
923
|
+
*/
|
|
924
|
+
dryRun(input: ReadableStream<any>, direction: "forward" | "backward", version?: string): Promise<{
|
|
925
|
+
newSchema: SchemaDefinition;
|
|
926
|
+
dataPreview: ReadableStream<any>;
|
|
927
|
+
}>;
|
|
928
|
+
/**
|
|
929
|
+
* Gets relevant migrations based on direction
|
|
930
|
+
* @private
|
|
931
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
932
|
+
* @returns {Array<Migration<any>>} Relevant migrations
|
|
933
|
+
*/
|
|
934
|
+
private getRelevantMigrations;
|
|
935
|
+
/**
|
|
936
|
+
* Applies schema changes to a given schema
|
|
937
|
+
* @private
|
|
938
|
+
* @param {SchemaDefinition} schema - The schema to modify
|
|
939
|
+
* @param {SchemaChange<any>[]} changes - Array of schema changes
|
|
940
|
+
* @param {string} [migrationId] - ID of the migration
|
|
941
|
+
* @returns {SchemaDefinition} Modified schema
|
|
942
|
+
* @throws {MigrationError} If applying changes fails
|
|
943
|
+
*/
|
|
944
|
+
private applySchemaChanges;
|
|
945
|
+
/**
|
|
946
|
+
* Prepares the list of pending migrations for application
|
|
947
|
+
* @async
|
|
948
|
+
* @returns {Promise<Array<Migration<any>>} List of pending migrations
|
|
949
|
+
* @throws {MigrationError} If preparation fails
|
|
950
|
+
*/
|
|
951
|
+
prepareMigration(): Promise<Array<Migration<any>>>;
|
|
952
|
+
/**
|
|
953
|
+
* Applies pending migrations
|
|
954
|
+
* @async
|
|
955
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
956
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
957
|
+
* @throws {MigrationError} If migration fails
|
|
958
|
+
*/
|
|
959
|
+
migrate(input: ReadableStream<any>): Promise<ReadableStream<any>>;
|
|
960
|
+
/**
|
|
961
|
+
* Validates migrations by checking their checksums
|
|
962
|
+
* @private
|
|
963
|
+
* @async
|
|
964
|
+
* @param {Array<Migration<any>>} migrations - Migrations to validate
|
|
965
|
+
* @throws {MigrationError} If validation fails
|
|
966
|
+
*/
|
|
967
|
+
private validateMigrations;
|
|
968
|
+
/**
|
|
969
|
+
* Marks migrations as applied
|
|
970
|
+
* @private
|
|
971
|
+
* @param {Array<Migration<any>>} migrations - Migrations to mark as applied
|
|
972
|
+
*/
|
|
973
|
+
private markMigrationsApplied;
|
|
974
|
+
/**
|
|
975
|
+
* Rolls back the last applied migration
|
|
976
|
+
* @async
|
|
977
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
978
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
979
|
+
*/
|
|
980
|
+
rollback(input: ReadableStream<any>): Promise<ReadableStream<any>>;
|
|
981
|
+
/**
|
|
982
|
+
* Rolls back to a specific schema version
|
|
983
|
+
* @async
|
|
984
|
+
* @param {string} targetVersion - Target schema version
|
|
985
|
+
* @param {ReadableStream<any>} input - Input data stream
|
|
986
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
987
|
+
* @throws {Error} If target version is not found
|
|
988
|
+
*/
|
|
989
|
+
rollbackToVersion(targetVersion: string, input: ReadableStream<any>): Promise<ReadableStream<any>>;
|
|
990
|
+
/**
|
|
991
|
+
* Processes a list of migrations on a data stream, applying transformations
|
|
992
|
+
* in the specified direction (forward or backward).
|
|
993
|
+
*
|
|
994
|
+
* @static
|
|
995
|
+
* @async
|
|
996
|
+
* @param {ReadableStream<any>} input - The input data stream to process
|
|
997
|
+
* @param {"forward" | "backward"} direction - Direction of migration (either "forward" or "backward")
|
|
998
|
+
* @param {Array<Migration<any>>} migrations - Array of Migration objects to process
|
|
999
|
+
* @returns {Promise<ReadableStream<any>>} Transformed data stream
|
|
1000
|
+
* @throws {MigrationError} If any migration processing fails
|
|
1001
|
+
*/
|
|
1002
|
+
static processMigrationList(input: ReadableStream<any>, direction: "forward" | "backward", migrations: Migration<any>[]): Promise<ReadableStream<any>>;
|
|
1003
|
+
/**
|
|
1004
|
+
* Resolves the transform function for a given migration in the specified direction.
|
|
1005
|
+
*
|
|
1006
|
+
* @private
|
|
1007
|
+
* @async
|
|
1008
|
+
* @param {Migration<any>} migration - The migration to resolve the transform for
|
|
1009
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
1010
|
+
* @returns {Promise<TransformFunction<any, any>>} Resolved transform function
|
|
1011
|
+
* @throws {MigrationError} If transform resolution fails
|
|
1012
|
+
*/
|
|
1013
|
+
private static resolveTransform;
|
|
1014
|
+
/**
|
|
1015
|
+
* Resolves a transform function from a remote URL.
|
|
1016
|
+
*
|
|
1017
|
+
* @private
|
|
1018
|
+
* @async
|
|
1019
|
+
* @param {string} url - URL of the transform module
|
|
1020
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
1021
|
+
* @returns {Promise<TransformFunction<any, any>>} Resolved transform function
|
|
1022
|
+
* @throws {MigrationError} If resolution fails
|
|
1023
|
+
*/
|
|
1024
|
+
private static resolveRemoteTransform;
|
|
1025
|
+
/**
|
|
1026
|
+
* Resolves a transform function from a local module path.
|
|
1027
|
+
*
|
|
1028
|
+
* @private
|
|
1029
|
+
* @async
|
|
1030
|
+
* @param {string} path - Local module path
|
|
1031
|
+
* @param {"forward" | "backward"} direction - Direction of migration
|
|
1032
|
+
* @returns {Promise<TransformFunction<any, any>>} Resolved transform function
|
|
1033
|
+
* @throws {MigrationError} If resolution fails
|
|
1034
|
+
*/
|
|
1035
|
+
private static resolveLocalTransform;
|
|
1036
|
+
/**
|
|
1037
|
+
* Transforms the schema either forward or backward
|
|
1038
|
+
* @private
|
|
1039
|
+
* @param {"forward" | "backward"} direction - Direction of transformation
|
|
1040
|
+
* @throws {Error} If transformation fails
|
|
1041
|
+
*/
|
|
1042
|
+
private transformSchema;
|
|
1043
|
+
}
|
|
860
1044
|
|
|
861
1045
|
/**
|
|
862
1046
|
* Helper for building schema migrations with forward and rollback changes.
|
|
@@ -1696,4 +1880,4 @@ declare function docgen(schema: SchemaDefinition, options?: {
|
|
|
1696
1880
|
faker?: Faker;
|
|
1697
1881
|
}): string;
|
|
1698
1882
|
|
|
1699
|
-
export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, MigrationSchema, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, type SchemaRegistry, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaToTypes, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
|
|
1883
|
+
export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, MigrationSchema, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, type SchemaRegistry, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaToTypes, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
|
package/index.js
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
import{createEventBus as at}from"@asaidimu/events";import{createEventBus as Ue}from"@asaidimu/events";import{createMatcher as ze,createPaginator as qe,createProjector as Ke,createSorter as Ye}from"@asaidimu/query";var y=class extends Error{constructor(t,n){super(t);this.operation=n;this.name="JsonPatchError"}};function $(e){let r=q(e);return r===""?[]:r.substring(1).split("/").map(K)}function q(e){return e===""||e==="/"?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(C).join("/"):"/"+e.split(".").map(C).join("/")}function C(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function K(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var w=new Map;function T(e,r){let t=e;for(let n of r){if(t===null||typeof t!="object")throw new y(`Invalid path - parent not found at ${n}`);if(Array.isArray(t)){let a=n==="-"?t.length:parseInt(n);if(isNaN(a)||a<0||a>t.length)throw new y(`Invalid array index: ${n}`);t=t[a]}else{if(!t.hasOwnProperty(n))throw new y(`Property ${n} not found`);t=t[n]}}return t}function E(e,r){let t=w.get(r)||$(r);if(w.set(r,t),t.length===0)return e;let n=T(e,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(n)){let i=parseInt(a);if(isNaN(i)||i<0||i>=n.length)throw new y(`Invalid array index: ${a}`);return n[i]}return n[a]}function Y(e,r,t){let n=w.get(r)||$(r);w.set(r,n);let a=T(e,n.slice(0,-1)),i=n[n.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(m=>m!==t)):a[i]===t&&delete a[i],e}function v(e,r,t){let n=w.get(r)||$(r);if(w.set(r,n),n.length===0)return t;let a=n.slice(0,-1),i=n[n.length-1],m=T(e,a);if(Array.isArray(m))if(i==="-")m.push(t);else{let c=parseInt(i);if(c<0||c>m.length)throw new y(`Invalid array index: ${i}`);m.splice(c,0,t)}else m[i]=t;return e}function I(e,r){let t=w.get(r)||$(r);if(w.set(r,t),t.length===0)return;let n=T(e,t.slice(0,-1)),a=t[t.length-1];if(Array.isArray(n)){let i=parseInt(a);n.splice(i,1)}else delete n[a];return e}function j(e,r){let t=JSON.parse(JSON.stringify(e));for(let n of r)try{switch(n.op){case"add":t=v(t,n.path,n.value);break;case"remove":t=I(t,n.path);break;case"removeValue":t=Y(t,n.path,n.value);break;case"replace":t=v(I(t,n.path),n.path,n.value);break;case"copy":{let a=E(t,n.from);t=v(t,n.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=E(t,n.from);t=v(t,n.path,a),t=I(t,n.from);break}case"test":{let a=E(t,n.path);if(JSON.stringify(a)!==JSON.stringify(n.value))throw new y("Test operation failed");break}default:throw new y(`Unsupported operation: ${n.op}`)}}catch(a){throw a instanceof y&&(a.operation=n),a}return t}function $e(e,r){let t=[];return R(e,r,"",t),t}function R(e,r,t,n){if(e!==r){if(typeof e!=typeof r||Array.isArray(e)!==Array.isArray(r)){n.push({op:"replace",path:t,value:r});return}typeof e=="object"&&e!==null?Array.isArray(e)?Q(e,r,t,n):W(e,r,t,n):e!==r&&n.push({op:"replace",path:t,value:r})}}function Q(e,r,t,n){let a=Math.max(e.length,r.length);for(let i=0;i<a;i++){let m=`${t}/${i}`;i>=e.length?n.push({op:"add",path:`${t}/-`,value:r[i]}):i>=r.length?n.push({op:"remove",path:m}):R(e[i],r[i],m,n)}}function W(e,r,t,n){let a=new Set,i=Object.keys(e),m=Object.keys(r);for(let c of i){let d=C(c),s=t?`${t}/${d}`:`/${d}`;r.hasOwnProperty(c)?(R(e[c],r[c],s,n),a.add(c)):n.push({op:"remove",path:s})}for(let c of m)if(!a.has(c)){let d=C(c),s=t?`${t}/${d}`:`/${d}`;n.push({op:"add",path:s,value:r[c]})}}function Z(e,r){let t=[];switch(e.type){case"addField":t.push({op:"add",path:`/fields/${e.name}`,value:e.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${e.name}`});break;case"modifyField":{let n=`/fields/${e.name}`;Object.entries(e.changes).forEach(([a,i])=>{typeof i=="object"&&i!==null&&!Array.isArray(i)?t.push({op:"replace",path:`${n}/${a}`,value:i}):t.push({op:"replace",path:`${n}/${a}`,value:i})});break}case"deprecateField":t.push({op:"add",path:`/fields/${e.name}/deprecated`,value:!0});break;case"addIndex":r.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let n=r.indexes?.findIndex(a=>a.name===e.name);n!==void 0&&n>=0&&t.push({op:"remove",path:`/indexes/${n}`});break}case"modifyIndex":{let n=r.indexes?.findIndex(a=>a.name===e.name);n!==void 0&&n>=0&&Object.entries(e.changes).forEach(([a,i])=>{t.push({op:"replace",path:`/indexes/${n}/${a}`,value:i})});break}case"addConstraint":r.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(n=>{t.push({op:"add",path:"/constraints/-",value:n})}):t.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let n=r.constraints?.findIndex(a=>Array.isArray(a)?a.some(i=>i.name===e.name):a.name===e.name);n!==void 0&&n>=0&&t.push({op:"remove",path:`/constraints/${n}`});break}case"modifyConstraint":{let n=X(r,e.name);n&&Object.entries(e.changes).forEach(([a,i])=>{t.push({op:"replace",path:`${n}/${a}`,value:i})});break}}return t}function X(e,r){if(!e.constraints)return null;for(let t=0;t<e.constraints.length;t++){let n=e.constraints[t];if(n.name===r)return`/constraints/${t}`;if(V(n)){let a=J(n.rules,r);if(a)return`/constraints/${t}${a}`}}return null}function V(e){return e&&"operator"in e&&"rules"in e}function J(e,r){for(let t=0;t<e.length;t++){let n=e[t];if("name"in n&&n.name===r)return`/rules/${t}`;if(V(n)){let a=J(n.rules,r);if(a)return`/rules/${t}${a}`}}return null}function _(e,r){let t={...e};return k(e)&&k(r)&&Object.keys(r).forEach(n=>{k(r[n])?n in e?t[n]=_(e[n],r[n]):Object.assign(t,{[n]:r[n]}):Object.assign(t,{[n]:r[n]})}),t}function k(e){return e&&typeof e=="object"&&!Array.isArray(e)}function ee(e,r){let t=(s,l,u,p)=>{let f=[];switch(u.type){case"string":typeof s!="string"&&f.push({message:`Expected type string but received ${typeof s}.`,path:p});break;case"number":typeof s!="number"&&f.push({message:`Expected type number but received ${typeof s}.`,path:p});break;case"boolean":typeof s!="boolean"&&f.push({message:`Expected type boolean but received ${typeof s}.`,path:p});break;case"array":Array.isArray(s)?u.itemsType?s.forEach((h,g)=>{f.push(...t(h,`Array: ${l}`,{type:u.itemsType,nestedSchema:u.nestedSchema},[...p,g]))}):f.push({message:`Expected itemsType for array ${l}`,path:p}):f.push({message:`Expected an array but received ${typeof s}.`,path:p});break;case"object":if(typeof s!="object"||s===null)f.push({message:`Expected an object but received ${s===null?"null":typeof s}.`,path:p});else if(u.nestedSchema){let h={name:u.description?`${u.description}-schema`:"nested-schema",version:"1.0",fields:u.nestedSchema};f.push(...d(h,s,p))}break;case"dynamic":break;default:f.push({message:`Unknown field type: ${u.type}`,path:p});break}return f},n=(s,l,u,p)=>{let f=[];return l.constraints&&l.constraints.forEach(h=>{let g=r[h.predicate];g?(h.type==="schema"?g({data:u,arguments:h.parameters}):g({data:u,field:s,arguments:h.parameters}))||f.push({message:`Constraint '${h.name}' failed for field '${s}'.`,path:p}):f.push({message:`Missing predicate for constraint: ${h.name}`,path:p})}),f},a=(s,l,u,p,f)=>[...t(u,s,l,f),...n(s,l,p,f)],i=(s,l,u)=>{if("operator"in s)return m(s.operator,s.rules.map(f=>i(f,l,u)));let p=r[s.predicate];return p?s.type==="schema"?p({data:l,field:s.field,arguments:s.parameters}):p({data:l,field:u,arguments:s.parameters}):!1},m=(s,l)=>{switch(s){case"and":return l.every(Boolean);case"or":return l.some(Boolean);case"not":return l.length===1?!l[0]:!1;case"nor":return!l.some(Boolean);case"xor":return l.filter(Boolean).length===1;default:return console.error(`Unknown logical operator: ${s}`),!1}},c=s=>"operator"in s?`(${s.rules.map(c).join(` ${s.operator} `)})`:s.name,d=(s,l,u=[])=>{let p=[];for(let[f,h]of Object.entries(s.fields))h.required&&l[f]===void 0&&p.push({message:`Field '${f}' is required.`,path:[...u,f]});for(let[f,h]of Object.entries(s.fields)){let g=l[f];g!==void 0&&p.push(...a(f,h,g,l,[...u,f]))}return s.constraints&&s.constraints.forEach(f=>{i(f,l)||p.push({message:`Schema constraint failed: ${c(f)}`,path:u})}),p};return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if(typeof s!="object"||s===null)return{issues:[{message:"Value must be a non-null object",path:[]}]};let l=d(e,s);return l.length===0?{value:s}:{issues:l}}}}}import{z as o}from"zod";var S=class extends Error{constructor(t,n){super(t);this.errors=n;this.name="SchemaValidationError"}};var H=o.enum(["and","or","not","nor","xor"]),L=o.enum(["string","number","boolean","array","object","dynamic"]),te=o.enum(["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"]),ne=o.custom(()=>!0),b=o.object({type:o.string().optional(),name:o.string(),predicate:o.string().optional(),parameters:ne.optional(),description:o.string().optional(),field:o.string().optional(),errorMessage:o.string().optional()}),M=o.object({operator:H,rules:o.array(o.union([b,o.lazy(()=>M)]))}),x=o.object({type:L,required:o.boolean().optional(),constraints:o.array(b).optional(),default:o.any().optional(),itemsType:L.optional(),nestedSchema:o.record(o.lazy(()=>x)).optional(),deprecated:o.boolean().optional(),reference:o.object({schema:o.string(),field:o.string()}).optional(),description:o.string().optional(),unique:o.boolean().optional()}),G=o.object({operator:H,field:o.string(),value:o.any().optional(),conditions:o.array(o.lazy(()=>G)).optional()}),D=o.object({fields:o.array(o.string()),type:te,unique:o.boolean().optional(),partial:G.optional(),description:o.string().optional(),order:o.enum(["asc","desc"]).optional(),name:o.string().optional()}),re=o.array(o.union([b,M])),ae=o.object({name:o.string(),version:o.string(),description:o.string().optional(),fields:o.record(x),indexes:o.array(D).optional(),constraints:re.optional(),metadata:o.record(o.any()).optional(),dependencies:o.array(o.string()).optional(),migrations:o.array(o.any()).optional()}),O=o.union([o.object({type:o.literal("addField"),name:o.string(),definition:x}),o.object({type:o.literal("removeField"),name:o.string()}),o.object({type:o.literal("modifyField"),name:o.string(),changes:x.partial()}),o.object({type:o.literal("addIndex"),definition:D}),o.object({type:o.literal("removeIndex"),name:o.string()}),o.object({type:o.literal("modifyIndex"),name:o.string(),changes:D.partial()}),o.object({type:o.literal("addConstraint"),constraint:o.union([b,M])}),o.object({type:o.literal("removeConstraint"),name:o.string()}),o.object({type:o.literal("modifyConstraint"),name:o.string(),changes:b.partial()}),o.object({type:o.literal("deprecateField"),name:o.string()})]),ie=o.object({id:o.string(),schemaVersion:o.string(),changes:o.array(O),description:o.string(),status:o.enum(["pending","applied","failed"]),rollback:o.array(O).optional(),transform:o.unknown(),createdAt:o.string(),checksum:o.string().optional()});function oe(e){try{return ie.parse(e),!0}catch(r){throw new S("Invalid migration definition",r)}}function se(e){try{return O.parse(e),!0}catch(r){throw new S("Invalid schema definition",r)}}function U(e){try{return ae.parse(e),!0}catch(r){throw new S("Invalid schema definition",r)}}var Oe=U;var B=async e=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}else{let{createHash:r}=await import("crypto");return r("sha256").update(e).digest("hex")}};function ce(e){let r=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!r)throw new Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(r[1],10),minor:parseInt(r[2],10),patch:parseInt(r[3],10)}}function pe(e,r){if(r&&"field"in e&&e.field){let t=r.fields[e.field];if(t)return t.type}if("parameters"in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function me(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function de(e,r,t){switch(t){case"string":if(e instanceof RegExp&&r instanceof RegExp)return e.source!==r.source;if(Array.isArray(e)&&Array.isArray(r))return r.length<e.length||!e.every(n=>r.includes(n));break;case"number":if(typeof e=="object"&&typeof r=="object"&&"precision"in e&&"precision"in r)return r.precision<e.precision||(r.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(r))return r.length<e.length||!e.every(n=>r.includes(n));break;case"array":if(typeof e=="object"&&typeof r=="object"&&"minItems"in e&&"maxItems"in e&&"minItems"in r&&"maxItems"in r)return r.minItems>e.minItems||r.maxItems<e.maxItems;break;case"object":if(typeof e=="object"&&typeof r=="object"&&"schema"in e&&"schema"in r)return Object.keys(r.schema).length>Object.keys(e.schema).length;break}return!1}function le(e,r){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(r.operator&&t[r.operator]>t[e.operator]||r.rules&&r.rules.length>e.rules.length)}function fe(e,r,t){if(!r)return!0;if("rules"in r&&"rules"in e)return le(r,e);if("predicate"in e&&e.predicate!==void 0)return!0;if("parameters"in e&&e.parameters!==void 0){let n=pe(r,t);return n?de(r.parameters,e.parameters,n):!0}return!1}function ue(e,r){switch(e.type){case"removeField":case"removeIndex":return"major";case"modifyField":return me(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return e.changes.unique!==void 0||e.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=r?.constraints?.find(n=>"name"in n&&n.name===e.name);return fe(e.changes,t,r)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function he(e){let r=new Set,t=new Set,n=new Set,a=new Set;for(let i of e)switch(i.type){case"addField":if(t.has(i.name))throw new Error(`Cannot add previously removed field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot add already modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot add deprecated field: ${i.name}`);n.add(i.name);break;case"removeField":if(n.has(i.name))throw new Error(`Cannot remove newly added field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot remove modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot remove field that is being deprecated: ${i.name}`);t.add(i.name);break;case"modifyField":if(t.has(i.name))throw new Error(`Cannot modify removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot modify newly added field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot modify field that is being deprecated: ${i.name}`);r.add(i.name);break;case"deprecateField":if(t.has(i.name))throw new Error(`Cannot deprecate removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot deprecate newly added field: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot deprecate modified field: ${i.name}`);a.add(i.name);break}}function ye(e){let r=new Set,t=new Set,n=new Set;for(let a of e)switch(a.type){case"addConstraint":let i=a.constraint,m=("name"in i,i.name);if(t.has(m))throw new Error(`Cannot add previously removed constraint: ${m}`);if(r.has(m))throw new Error(`Cannot add already modified constraint: ${m}`);n.add(m);break;case"removeConstraint":if(n.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(r.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);t.add(a.name);break;case"modifyConstraint":if(t.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(n.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);r.add(a.name);break}}function ge(e,r,t){if(r.length===0)throw new Error("No changes provided");he(r),ye(r);let n=ce(e),a="patch";for(let i of r){let m=ue(i,t);if(m==="major"){a="major";break}else m==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${n.major+1}.0.0`;case"minor":return`${n.major}.${n.minor+1}.0`;case"patch":return`${n.major}.${n.minor}.${n.patch+1}`}}function P(e,r){let t=s=>s.split(".").map(l=>parseInt(l,10)||0),[n,a,i]=t(e),[m,c,d]=t(r);return n-m||a-c||i-d}function Fe(e){return e.sort(P)}var z=class extends Error{constructor(t,n,a,i){super(t);this.code=n;this.migrationId=a;this.cause=i;this.name="MigrationError"}},we=(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))(we||{});var Se=e=>{let r=[],t=[];return{addField:(n,a)=>{r.push({type:"addField",name:n,definition:a}),t.push({type:"removeField",name:n})},removeField:n=>{r.push({type:"removeField",name:n});let a=e.fields[n];a&&t.push({type:"addField",name:n,definition:a})},modifyField:(n,a)=>{r.push({type:"modifyField",name:n,changes:a});let i=e.fields[n];t.push({type:"modifyField",name:n,changes:i})},deprecateField:n=>{r.push({type:"deprecateField",name:n}),t.push({type:"modifyField",name:n,changes:{deprecated:!1}})},addIndex:n=>{r.push({type:"addIndex",definition:n}),t.push({type:"removeIndex",name:n.name})},removeIndex:n=>{r.push({type:"removeIndex",name:n});let a=e.indexes?.find(i=>i.name===n);a&&t.push({type:"addIndex",definition:a})},modifyIndex:(n,a)=>{r.push({type:"modifyIndex",name:n,changes:a});let i=e.indexes?.find(m=>m.name===n);i&&t.push({type:"modifyIndex",name:n,changes:i})},addConstraint:n=>{r.push({type:"addConstraint",constraint:n}),t.push({type:"removeConstraint",name:n.name})},removeConstraint:n=>{r.push({type:"removeConstraint",name:n});let a=e.constraints?.find(i=>"name"in i&&i.name===n);a&&t.push({type:"addConstraint",constraint:a})},modifyConstraint:(n,a)=>{r.push({type:"modifyConstraint",name:n,changes:a});let i=e.constraints?.find(m=>"name"in m&&m.name===n);i&&t.push({type:"modifyConstraint",name:n,changes:i})},changes:()=>({migrate:r,rollback:t})}};import wt from"@isomorphic-git/lightning-fs";import{Buffer as be}from"buffer";import vt from"isomorphic-git";import $t from"isomorphic-git/http/web";window.Buffer=be;function ve(e,r,t){switch(e.type){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return e.itemsType?e.itemsType==="object"&&e.nestedSchema?`${`${r}ItemsItem`}[]`:`${e.itemsType}[]`:"any[]";case"object":return e.nestedSchema?`${r}${N(t)}`:"Record<string, any>";case"dynamic":return"any";default:return"any"}}function F(e,r){let t="";for(let[n,a]of Object.entries(e))if(a.type==="object"&&a.nestedSchema){let i=`${r}${N(n)}`;t+=`
|
|
1
|
+
import{createEventBus as it}from"@asaidimu/events";import{createEventBus as Be}from"@asaidimu/events";import{createMatcher as qe,createPaginator as Ke,createProjector as Ye,createSorter as Qe}from"@asaidimu/query";var g=class extends Error{constructor(e,t){super(e);this.operation=t;this.name="JsonPatchError"}};function x(r){let n=Z(r);return n===""?[]:n.substring(1).split("/").map(X)}function Z(r){return r===""||r==="/"?"":r.startsWith("/")?"/"+r.substring(1).split("/").map(T).join("/"):"/"+r.split(".").map(T).join("/")}function T(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}function X(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}var S=new Map;function E(r,n){let e=r;for(let t of n){if(e===null||typeof e!="object")throw new g(`Invalid path - parent not found at ${t}`);if(Array.isArray(e)){let a=t==="-"?e.length:parseInt(t);if(isNaN(a)||a<0||a>e.length)throw new g(`Invalid array index: ${t}`);e=e[a]}else{if(!e.hasOwnProperty(t))throw new g(`Property ${t} not found`);e=e[t]}}return e}function R(r,n){let e=S.get(n)||x(n);if(S.set(n,e),e.length===0)return r;let t=E(r,e.slice(0,-1)),a=e[e.length-1];if(Array.isArray(t)){let i=parseInt(a);if(isNaN(i)||i<0||i>=t.length)throw new g(`Invalid array index: ${a}`);return t[i]}return t[a]}function ee(r,n,e){let t=S.get(n)||x(n);S.set(n,t);let a=E(r,t.slice(0,-1)),i=t[t.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(p=>p!==e)):a[i]===e&&delete a[i],r}function $(r,n,e){let t=S.get(n)||x(n);if(S.set(n,t),t.length===0)return e;let a=t.slice(0,-1),i=t[t.length-1],p=E(r,a);if(Array.isArray(p))if(i==="-")p.push(e);else{let s=parseInt(i);if(s<0||s>p.length)throw new g(`Invalid array index: ${i}`);p.splice(s,0,e)}else p[i]=e;return r}function k(r,n){let e=S.get(n)||x(n);if(S.set(n,e),e.length===0)return;let t=E(r,e.slice(0,-1)),a=e[e.length-1];if(Array.isArray(t)){let i=parseInt(a);t.splice(i,1)}else delete t[a];return r}function D(r,n){let e=JSON.parse(JSON.stringify(r));for(let t of n)try{switch(t.op){case"add":e=$(e,t.path,t.value);break;case"remove":e=k(e,t.path);break;case"removeValue":e=ee(e,t.path,t.value);break;case"replace":e=$(k(e,t.path),t.path,t.value);break;case"copy":{let a=R(e,t.from);e=$(e,t.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=R(e,t.from);e=$(e,t.path,a),e=k(e,t.from);break}case"test":{let a=R(e,t.path);if(JSON.stringify(a)!==JSON.stringify(t.value))throw new g("Test operation failed");break}default:throw new g(`Unsupported operation: ${t.op}`)}}catch(a){throw a instanceof g&&(a.operation=t),a}return e}function Te(r,n){let e=[];return O(r,n,"",e),e}function O(r,n,e,t){if(r!==n){if(typeof r!=typeof n||Array.isArray(r)!==Array.isArray(n)){t.push({op:"replace",path:e,value:n});return}typeof r=="object"&&r!==null?Array.isArray(r)?te(r,n,e,t):ne(r,n,e,t):r!==n&&t.push({op:"replace",path:e,value:n})}}function te(r,n,e,t){let a=Math.max(r.length,n.length);for(let i=0;i<a;i++){let p=`${e}/${i}`;i>=r.length?t.push({op:"add",path:`${e}/-`,value:n[i]}):i>=n.length?t.push({op:"remove",path:p}):O(r[i],n[i],p,t)}}function ne(r,n,e,t){let a=new Set,i=Object.keys(r),p=Object.keys(n);for(let s of i){let d=T(s),c=e?`${e}/${d}`:`/${d}`;n.hasOwnProperty(s)?(O(r[s],n[s],c,t),a.add(s)):t.push({op:"remove",path:c})}for(let s of p)if(!a.has(s)){let d=T(s),c=e?`${e}/${d}`:`/${d}`;t.push({op:"add",path:c,value:n[s]})}}function L(r,n){let e=[];switch(r.type){case"addField":e.push({op:"add",path:`/fields/${r.name}`,value:r.definition});break;case"removeField":e.push({op:"remove",path:`/fields/${r.name}`});break;case"modifyField":{let t=`/fields/${r.name}`;Object.entries(r.changes).forEach(([a,i])=>{typeof i=="object"&&i!==null&&!Array.isArray(i)?e.push({op:"replace",path:`${t}/${a}`,value:i}):e.push({op:"replace",path:`${t}/${a}`,value:i})});break}case"deprecateField":e.push({op:"add",path:`/fields/${r.name}/deprecated`,value:!0});break;case"addIndex":n.indexes||e.push({op:"add",path:"/indexes",value:[]}),e.push({op:"add",path:"/indexes/-",value:r.definition});break;case"removeIndex":{let t=n.indexes?.findIndex(a=>a.name===r.name);t!==void 0&&t>=0&&e.push({op:"remove",path:`/indexes/${t}`});break}case"modifyIndex":{let t=n.indexes?.findIndex(a=>a.name===r.name);t!==void 0&&t>=0&&Object.entries(r.changes).forEach(([a,i])=>{e.push({op:"replace",path:`/indexes/${t}/${a}`,value:i})});break}case"addConstraint":n.constraints||e.push({op:"add",path:"/constraints",value:[]}),Array.isArray(r.constraint)?r.constraint.forEach(t=>{e.push({op:"add",path:"/constraints/-",value:t})}):e.push({op:"add",path:"/constraints/-",value:r.constraint});break;case"removeConstraint":{let t=n.constraints?.findIndex(a=>Array.isArray(a)?a.some(i=>i.name===r.name):a.name===r.name);t!==void 0&&t>=0&&e.push({op:"remove",path:`/constraints/${t}`});break}case"modifyConstraint":{let t=re(n,r.name);t&&Object.entries(r.changes).forEach(([a,i])=>{e.push({op:"replace",path:`${t}/${a}`,value:i})});break}}return e}function re(r,n){if(!r.constraints)return null;for(let e=0;e<r.constraints.length;e++){let t=r.constraints[e];if(t.name===n)return`/constraints/${e}`;if(H(t)){let a=G(t.rules,n);if(a)return`/constraints/${e}${a}`}}return null}function H(r){return r&&"operator"in r&&"rules"in r}function G(r,n){for(let e=0;e<r.length;e++){let t=r[e];if("name"in t&&t.name===n)return`/rules/${e}`;if(H(t)){let a=G(t.rules,n);if(a)return`/rules/${e}${a}`}}return null}function U(r,n){let e={...r};return M(r)&&M(n)&&Object.keys(n).forEach(t=>{M(n[t])?t in r?e[t]=U(r[t],n[t]):Object.assign(e,{[t]:n[t]}):Object.assign(e,{[t]:n[t]})}),e}function M(r){return r&&typeof r=="object"&&!Array.isArray(r)}function ae(r,n){let e=(c,l,f,m)=>{let u=[];switch(f.type){case"string":typeof c!="string"&&u.push({message:`Expected type string but received ${typeof c}.`,path:m});break;case"number":typeof c!="number"&&u.push({message:`Expected type number but received ${typeof c}.`,path:m});break;case"boolean":typeof c!="boolean"&&u.push({message:`Expected type boolean but received ${typeof c}.`,path:m});break;case"array":Array.isArray(c)?f.itemsType?c.forEach((y,w)=>{u.push(...e(y,`Array: ${l}`,{type:f.itemsType,nestedSchema:f.nestedSchema},[...m,w]))}):u.push({message:`Expected itemsType for array ${l}`,path:m}):u.push({message:`Expected an array but received ${typeof c}.`,path:m});break;case"object":if(typeof c!="object"||c===null)u.push({message:`Expected an object but received ${c===null?"null":typeof c}.`,path:m});else if(f.nestedSchema){let y={name:f.description?`${f.description}-schema`:"nested-schema",version:"1.0",fields:f.nestedSchema};u.push(...d(y,c,m))}break;case"dynamic":break;default:u.push({message:`Unknown field type: ${f.type}`,path:m});break}return u},t=(c,l,f,m)=>{let u=[];return l.constraints&&l.constraints.forEach(y=>{let w=n[y.predicate];w?(y.type==="schema"?w({data:f,arguments:y.parameters}):w({data:f,field:c,arguments:y.parameters}))||u.push({message:`Constraint '${y.name}' failed for field '${c}'.`,path:m}):u.push({message:`Missing predicate for constraint: ${y.name}`,path:m})}),u},a=(c,l,f,m,u)=>[...e(f,c,l,u),...t(c,l,m,u)],i=(c,l,f)=>{if("operator"in c)return p(c.operator,c.rules.map(u=>i(u,l,f)));let m=n[c.predicate];return m?c.type==="schema"?m({data:l,field:c.field,arguments:c.parameters}):m({data:l,field:f,arguments:c.parameters}):!1},p=(c,l)=>{switch(c){case"and":return l.every(Boolean);case"or":return l.some(Boolean);case"not":return l.length===1?!l[0]:!1;case"nor":return!l.some(Boolean);case"xor":return l.filter(Boolean).length===1;default:return console.error(`Unknown logical operator: ${c}`),!1}},s=c=>"operator"in c?`(${c.rules.map(s).join(` ${c.operator} `)})`:c.name,d=(c,l,f=[])=>{let m=[];for(let[u,y]of Object.entries(c.fields))y.required&&l[u]===void 0&&m.push({message:`Field '${u}' is required.`,path:[...f,u]});for(let[u,y]of Object.entries(c.fields)){let w=l[u];w!==void 0&&m.push(...a(u,y,w,l,[...f,u]))}return c.constraints&&c.constraints.forEach(u=>{i(u,l)||m.push({message:`Schema constraint failed: ${s(u)}`,path:f})}),m};return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:c=>{if(typeof c!="object"||c===null)return{issues:[{message:"Value must be a non-null object",path:[]}]};let l=d(r,c);return l.length===0?{value:c}:{issues:l}}}}}import{z as o}from"zod";var b=class extends Error{constructor(e,t){super(e);this.errors=t;this.name="SchemaValidationError"}};var z=o.enum(["and","or","not","nor","xor"]),B=o.enum(["string","number","boolean","array","object","dynamic"]),ie=o.enum(["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"]),oe=o.custom(()=>!0),C=o.object({type:o.string().optional(),name:o.string(),predicate:o.string().optional(),parameters:oe.optional(),description:o.string().optional(),field:o.string().optional(),errorMessage:o.string().optional()}),A=o.object({operator:z,rules:o.array(o.union([C,o.lazy(()=>A)]))}),I=o.object({type:B,required:o.boolean().optional(),constraints:o.array(C).optional(),default:o.any().optional(),itemsType:B.optional(),nestedSchema:o.record(o.lazy(()=>I)).optional(),deprecated:o.boolean().optional(),reference:o.object({schema:o.string(),field:o.string()}).optional(),description:o.string().optional(),unique:o.boolean().optional()}),q=o.object({operator:z,field:o.string(),value:o.any().optional(),conditions:o.array(o.lazy(()=>q)).optional()}),P=o.object({fields:o.array(o.string()),type:ie,unique:o.boolean().optional(),partial:q.optional(),description:o.string().optional(),order:o.enum(["asc","desc"]).optional(),name:o.string().optional()}),se=o.array(o.union([C,A])),ce=o.object({name:o.string(),version:o.string(),description:o.string().optional(),fields:o.record(I),indexes:o.array(P).optional(),constraints:se.optional(),metadata:o.record(o.any()).optional(),dependencies:o.array(o.string()).optional(),migrations:o.array(o.any()).optional()}),F=o.union([o.object({type:o.literal("addField"),name:o.string(),definition:I}),o.object({type:o.literal("removeField"),name:o.string()}),o.object({type:o.literal("modifyField"),name:o.string(),changes:I.partial()}),o.object({type:o.literal("addIndex"),definition:P}),o.object({type:o.literal("removeIndex"),name:o.string()}),o.object({type:o.literal("modifyIndex"),name:o.string(),changes:P.partial()}),o.object({type:o.literal("addConstraint"),constraint:o.union([C,A])}),o.object({type:o.literal("removeConstraint"),name:o.string()}),o.object({type:o.literal("modifyConstraint"),name:o.string(),changes:C.partial()}),o.object({type:o.literal("deprecateField"),name:o.string()})]),pe=o.object({id:o.string(),schemaVersion:o.string(),changes:o.array(F),description:o.string(),status:o.enum(["pending","applied","failed"]),rollback:o.array(F).optional(),transform:o.unknown(),createdAt:o.string(),checksum:o.string().optional()});function K(r){try{return pe.parse(r),!0}catch(n){throw new b("Invalid migration definition",n)}}function Y(r){try{return F.parse(r),!0}catch(n){throw new b("Invalid schema definition",n)}}function N(r){try{return ce.parse(r),!0}catch(n){throw new b("Invalid schema definition",n)}}var Me=N;var j=async r=>{if(typeof window<"u"&&crypto.subtle){let e=new TextEncoder().encode(r),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}else{let{createHash:n}=await import("crypto");return n("sha256").update(r).digest("hex")}};function me(r){let n=r.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!n)throw new Error(`Invalid version format: ${r}. Expected format: major.minor.patch`);return{major:parseInt(n[1],10),minor:parseInt(n[2],10),patch:parseInt(n[3],10)}}function de(r,n){if(n&&"field"in r&&r.field){let e=n.fields[r.field];if(e)return e.type}if("parameters"in r){let e=r.parameters;if(e instanceof RegExp||Array.isArray(e)&&typeof e[0]=="string")return"string";if(typeof e=="number"||Array.isArray(e)&&typeof e[0]=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="object"&&e!==null){if("minItems"in e||"maxItems"in e)return"array";if("schema"in e)return"object"}}}function le(r){return r.required===!0||r.type!==void 0||r.itemsType!==void 0||r.nestedSchema!==void 0||r.reference!==void 0||r.unique===!0}function fe(r,n,e){switch(e){case"string":if(r instanceof RegExp&&n instanceof RegExp)return r.source!==n.source;if(Array.isArray(r)&&Array.isArray(n))return n.length<r.length||!r.every(t=>n.includes(t));break;case"number":if(typeof r=="object"&&typeof n=="object"&&"precision"in r&&"precision"in n)return n.precision<r.precision||(n.scale??0)<(r.scale??0);if(Array.isArray(r)&&Array.isArray(n))return n.length<r.length||!r.every(t=>n.includes(t));break;case"array":if(typeof r=="object"&&typeof n=="object"&&"minItems"in r&&"maxItems"in r&&"minItems"in n&&"maxItems"in n)return n.minItems>r.minItems||n.maxItems<r.maxItems;break;case"object":if(typeof r=="object"&&typeof n=="object"&&"schema"in r&&"schema"in n)return Object.keys(n.schema).length>Object.keys(r.schema).length;break}return!1}function ue(r,n){let e={or:1,xor:2,and:3,not:4,nor:4};return!!(n.operator&&e[n.operator]>e[r.operator]||n.rules&&n.rules.length>r.rules.length)}function he(r,n,e){if(!n)return!0;if("rules"in n&&"rules"in r)return ue(n,r);if("predicate"in r&&r.predicate!==void 0)return!0;if("parameters"in r&&r.parameters!==void 0){let t=de(n,e);return t?fe(n.parameters,r.parameters,t):!0}return!1}function ye(r,n){switch(r.type){case"removeField":case"removeIndex":return"major";case"modifyField":return le(r.changes)?"major":r.changes.deprecated?"minor":"patch";case"modifyIndex":return r.changes.unique!==void 0||r.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let e=n?.constraints?.find(t=>"name"in t&&t.name===r.name);return he(r.changes,e,n)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(r)}`)}}function ge(r){let n=new Set,e=new Set,t=new Set,a=new Set;for(let i of r)switch(i.type){case"addField":if(e.has(i.name))throw new Error(`Cannot add previously removed field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot add already modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot add deprecated field: ${i.name}`);t.add(i.name);break;case"removeField":if(t.has(i.name))throw new Error(`Cannot remove newly added field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot remove modified field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot remove field that is being deprecated: ${i.name}`);e.add(i.name);break;case"modifyField":if(e.has(i.name))throw new Error(`Cannot modify removed field: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot modify newly added field: ${i.name}`);if(a.has(i.name))throw new Error(`Cannot modify field that is being deprecated: ${i.name}`);n.add(i.name);break;case"deprecateField":if(e.has(i.name))throw new Error(`Cannot deprecate removed field: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot deprecate newly added field: ${i.name}`);if(n.has(i.name))throw new Error(`Cannot deprecate modified field: ${i.name}`);a.add(i.name);break}}function we(r){let n=new Set,e=new Set,t=new Set;for(let a of r)switch(a.type){case"addConstraint":let i=a.constraint,p=("name"in i,i.name);if(e.has(p))throw new Error(`Cannot add previously removed constraint: ${p}`);if(n.has(p))throw new Error(`Cannot add already modified constraint: ${p}`);t.add(p);break;case"removeConstraint":if(t.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(n.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);e.add(a.name);break;case"modifyConstraint":if(e.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(t.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);n.add(a.name);break}}function Q(r,n,e){if(n.length===0)throw new Error("No changes provided");ge(n),we(n);let t=me(r),a="patch";for(let i of n){let p=ye(i,e);if(p==="major"){a="major";break}else p==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${t.major+1}.0.0`;case"minor":return`${t.major}.${t.minor+1}.0`;case"patch":return`${t.major}.${t.minor}.${t.patch+1}`}}function v(r,n){let e=c=>c.split(".").map(l=>parseInt(l,10)||0),[t,a,i]=e(r),[p,s,d]=e(n);return t-p||a-s||i-d}function Ae(r){return r.sort(v)}var h=class extends Error{constructor(e,t,a,i){super(e);this.code=t;this.migrationId=a;this.cause=i;this.name="MigrationError"}},Se=(m=>(m.INVALID_SCHEMA="INVALID_SCHEMA",m.INVALID_MIGRATION="INVALID_MIGRATION",m.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",m.TIMEOUT="TIMEOUT",m.MEMORY_LIMIT="MEMORY_LIMIT",m.CONCURRENT_OPERATION="CONCURRENT_OPERATION",m.TRANSFORM_ERROR="TRANSFORM_ERROR",m.VERSION_NOT_FOUND="VERSION_NOT_FOUND",m.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",m.STREAM_ERROR="STREAM_ERROR",m.ROLLBACK_ERROR="ROLLBACK_ERROR",m.MISSING_TRANSFORM="MISSING_TRANSFORM",m))(Se||{}),W=class r{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(n,e,t){try{if(!N(n))throw new h("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=n,e){if(!e.every(a=>K(a)))throw new h("Invalid migration configuration","INVALID_MIGRATION");this.migrations=e.sort((a,i)=>v(a.schemaVersion,i.schemaVersion))}t&&(this.history=t.sort((a,i)=>v(a.version,i.version)))}catch(a){throw a instanceof h?a:new h("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,a)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(n){try{let e=JSON.stringify({id:n.id,schemaVersion:n.schemaVersion,changes:n.changes,description:n.description,rollback:n.rollback,createdAt:n.createdAt});return await j(e)}catch(e){throw new h("Checksum generation failed","CHECKSUM_MISMATCH",n.id,e)}}async add(n){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");if(!n.changes?.length)throw new h("Migration must include changes","INVALID_MIGRATION");try{n.changes.forEach(t=>Y(t))}catch(t){throw new h("Invalid schema changes","INVALID_MIGRATION",void 0,t)}let e={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:n.changes,description:n.description,status:"pending",rollback:n.rollback,transform:n.transform,createdAt:new Date().toISOString(),checksum:""};e.checksum=await this.generateChecksum(e),this.migrations.push(e)}async dryRun(n,e,t){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},i=this.getRelevantMigrations(e,t),p=i.reduce((d,c)=>{let l=e==="forward"?c.changes:c.rollback||[];return this.applySchemaChanges(d,l,c.id)},a),s=await r.processMigrationList(n,e,i);return{newSchema:p,dataPreview:s}}catch(a){throw a instanceof h?a:new h("Dry run failed","INVALID_SCHEMA",void 0,a)}finally{this.isProcessing=!1}}getRelevantMigrations(n,e){return[...this.migrations].filter(t=>{let a=n==="forward"?"pending":"applied",i=e?v(t.schemaVersion,e)>=0:!0;return t.status===a&&i}).sort((t,a)=>n==="forward"?t.id.localeCompare(a.id):a.id.localeCompare(t.id))}applySchemaChanges(n,e,t){try{let a=Q(n.version,e);return e.map(p=>{try{return L(p,n)}catch(s){throw new h("Invalid schema change","INVALID_SCHEMA",t,s)}}).reduce((p,s)=>{try{return D(p,s)}catch(d){throw new h("Failed to apply patch","INVALID_SCHEMA",t,d)}},{...n,version:a})}catch(a){throw a instanceof h?a:new h("Schema update failed","INVALID_SCHEMA",t,a)}}async prepareMigration(){let n=this.migrations.filter(e=>e.status==="pending");return await this.validateMigrations(n),n}async migrate(n){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");let e=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let t=await r.processMigrationList(n,"forward",e);return this.markMigrationsApplied(e),t}finally{this.isProcessing=!1}}async validateMigrations(n){await Promise.all(n.map(async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new h("Checksum mismatch","CHECKSUM_MISMATCH",e.id)}))}markMigrationsApplied(n){this.migrations=this.migrations.map(e=>n.some(t=>t.id===e.id)?{...e,status:"applied"}:e)}async rollback(n){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(t=>t.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,n):n}async rollbackToVersion(n,e){if(this.isProcessing)throw new h("Concurrent operation","CONCURRENT_OPERATION");try{let t=this.history.findIndex(s=>s.version===n);if(t===-1)throw new Error(`Version ${n} not found in history`);let a=this.migrations.filter(s=>s.schemaVersion===n&&s.status==="applied").sort((s,d)=>d.id.localeCompare(s.id)),i=this.history.length-t;if(i<0)return e;for(let s=0;s<i;s++)this.transformSchema("backward");let p=await r.processMigrationList(e,"backward",a);return this.migrations=this.migrations.map(s=>s.schemaVersion===n&&s.status==="applied"?{...s,status:"pending"}:s),p}finally{this.isProcessing=!1}}static async processMigrationList(n,e,t){return(await Promise.all(t.map(async p=>{try{let s=await this.resolveTransform(p,e);return{migration:p,transform:s}}catch(s){throw new h(`Failed to resolve transform for migration ${p.id}`,"TRANSFORM_ERROR",p.id,s)}}))).filter(p=>!!p.transform).reduce((p,{migration:s,transform:d})=>p.pipeThrough(new TransformStream({async transform(c,l){try{let f=await d(c);l.enqueue(f)}catch(f){l.error(new h(`Data transformation failed for migration ${s.id}`,"TRANSFORM_ERROR",s.id,f))}}})),n)}static async resolveTransform(n,e){return n.transform?typeof n.transform=="string"?n.transform.startsWith("http://")||n.transform.startsWith("https://")?this.resolveRemoteTransform(n.transform,e):this.resolveLocalTransform(n.transform,e):n.transform[e]:null}static async resolveRemoteTransform(n,e){try{let t=await fetch(n);if(!t.ok)throw new h(`Failed to fetch transform module: ${n}`,"TRANSFORM_ERROR",void 0);let a=await t.text();if(typeof window<"u"){let i=new Blob([a],{type:"application/javascript"});return(await import(URL.createObjectURL(i))).default[e]}else{let{runInNewContext:i}=await import("vm"),p={module:{exports:{}},console};return i(a,p,n),p.module.exports[e]}}catch(t){throw new h(`Failed to load remote transform module: ${n}`,"TRANSFORM_ERROR",void 0,t)}}static async resolveLocalTransform(n,e){try{return(await import(n)).default[e]}catch(t){throw new h(`Failed to import local transform module: ${n}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(n){try{if(n==="backward"){let t=this.history.pop();if(!t)throw new Error("No previous version");this.currentSchema=t;return}let e=this.migrations.filter(t=>t.status==="pending").flatMap(t=>t.changes);if(!e.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=e.reduce((t,a)=>this.applySchemaChanges(t,[a]),this.currentSchema)}catch(e){throw e instanceof h?e:new h("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};var be=r=>{let n=[],e=[];return{addField:(t,a)=>{n.push({type:"addField",name:t,definition:a}),e.push({type:"removeField",name:t})},removeField:t=>{n.push({type:"removeField",name:t});let a=r.fields[t];a&&e.push({type:"addField",name:t,definition:a})},modifyField:(t,a)=>{n.push({type:"modifyField",name:t,changes:a});let i=r.fields[t];e.push({type:"modifyField",name:t,changes:i})},deprecateField:t=>{n.push({type:"deprecateField",name:t}),e.push({type:"modifyField",name:t,changes:{deprecated:!1}})},addIndex:t=>{n.push({type:"addIndex",definition:t}),e.push({type:"removeIndex",name:t.name})},removeIndex:t=>{n.push({type:"removeIndex",name:t});let a=r.indexes?.find(i=>i.name===t);a&&e.push({type:"addIndex",definition:a})},modifyIndex:(t,a)=>{n.push({type:"modifyIndex",name:t,changes:a});let i=r.indexes?.find(p=>p.name===t);i&&e.push({type:"modifyIndex",name:t,changes:i})},addConstraint:t=>{n.push({type:"addConstraint",constraint:t}),e.push({type:"removeConstraint",name:t.name})},removeConstraint:t=>{n.push({type:"removeConstraint",name:t});let a=r.constraints?.find(i=>"name"in i&&i.name===t);a&&e.push({type:"addConstraint",constraint:a})},modifyConstraint:(t,a)=>{n.push({type:"modifyConstraint",name:t,changes:a});let i=r.constraints?.find(p=>"name"in p&&p.name===t);i&&e.push({type:"modifyConstraint",name:t,changes:i})},changes:()=>({migrate:n,rollback:e})}};import St from"@isomorphic-git/lightning-fs";import{Buffer as ve}from"buffer";import Ct from"isomorphic-git";import Tt from"isomorphic-git/http/web";window.Buffer=ve;function Ce(r,n,e){switch(r.type){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return r.itemsType?r.itemsType==="object"&&r.nestedSchema?`${`${n}ItemsItem`}[]`:`${r.itemsType}[]`:"any[]";case"object":return r.nestedSchema?`${n}${_(e)}`:"Record<string, any>";case"dynamic":return"any";default:return"any"}}function V(r,n){let e="";for(let[t,a]of Object.entries(r))if(a.type==="object"&&a.nestedSchema){let i=`${n}${_(t)}`;e+=`
|
|
2
2
|
export interface ${i} {
|
|
3
|
-
${
|
|
4
|
-
}`;let
|
|
5
|
-
${
|
|
3
|
+
${J(a.nestedSchema,i)}
|
|
4
|
+
}`;let p=V(a.nestedSchema,i);p&&(e+=`
|
|
5
|
+
${p}`)}else if(a.type==="array"&&a.itemsType==="object"&&a.nestedSchema){let i=`${n}ItemsItem`;e+=`
|
|
6
6
|
export interface ${i} {
|
|
7
|
-
${
|
|
8
|
-
}`;let
|
|
9
|
-
${
|
|
7
|
+
${J(a.nestedSchema,i)}
|
|
8
|
+
}`;let p=V(a.nestedSchema,i);p&&(e+=`
|
|
9
|
+
${p}`)}return e}function J(r,n){return Object.entries(r).map(([e,t])=>{let a=[];t.description&&a.push(` /** ${t.description} */`),t.deprecated&&a.push(" /** @deprecated */");let i=t.required?"":"?",p=Ce(t,n,e);return a.push(` ${e}${i}: ${p};`),a.join(`
|
|
10
10
|
`)}).join(`
|
|
11
|
-
`)}function
|
|
12
|
-
`;
|
|
13
|
-
`),
|
|
14
|
-
${
|
|
15
|
-
}`;let
|
|
16
|
-
${
|
|
17
|
-
`,
|
|
11
|
+
`)}function _(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Ot(r){let n=_(r.name),e=`// Generated from schema version ${r.version}
|
|
12
|
+
`;r.description&&(e+=`/** ${r.description} */
|
|
13
|
+
`),e+=`export interface ${n} {
|
|
14
|
+
${J(r.fields,n)}
|
|
15
|
+
}`;let t=V(r.fields,n);return t&&(e+=`
|
|
16
|
+
${t}`),e+=`
|
|
17
|
+
`,e}function Pt(r,n){let e=[],t=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,a=(s=[])=>s.map(d=>`- **${d.name}**: ${d.description||""}
|
|
18
18
|
- Parameters: ${JSON.stringify(d.parameters)}
|
|
19
19
|
- Error: ${d.errorMessage||"None"}`).join(`
|
|
20
|
-
`),i=
|
|
21
|
-
${
|
|
20
|
+
`),i=s=>{let d=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(d+=` ${JSON.stringify(s.value)}`),s.conditions&&(d+=` [
|
|
21
|
+
${s.conditions.map(c=>` ${i(c)}`).join(`
|
|
22
22
|
`)}
|
|
23
|
-
]`),d},
|
|
23
|
+
]`),d},p=(s,d=1)=>{let c="#".repeat(d+2);return Object.entries(s).map(([l,f])=>{let m=`${c} ${l} (${f.type})
|
|
24
24
|
|
|
25
|
-
`;return
|
|
25
|
+
`;return m+=`**Required:** ${f.required?"Yes":"No"}
|
|
26
26
|
|
|
27
|
-
`,
|
|
27
|
+
`,f.description&&(m+=`**Description:** ${f.description}
|
|
28
28
|
|
|
29
|
-
`),
|
|
29
|
+
`),f.itemsType&&(m+=`**Item Type:** ${f.itemsType}
|
|
30
30
|
|
|
31
|
-
`),
|
|
32
|
-
`)};
|
|
33
|
-
${
|
|
34
|
-
`),
|
|
35
|
-
`),
|
|
36
|
-
`),
|
|
37
|
-
### Nested Schema: ${
|
|
38
|
-
`),
|
|
31
|
+
`),f.nestedSchema&&(m+=p(f.nestedSchema,d+1)),m}).join(`
|
|
32
|
+
`)};e.push(`# ${r.name} Schema (Version ${r.version})`),r.description&&e.push(`
|
|
33
|
+
${r.description}
|
|
34
|
+
`),e.push("## Metadata"),e.push(`- **Dependencies:** ${r.dependencies?.join(", ")||"None"}`),e.push(`- **Created:** ${new Date().toISOString()}
|
|
35
|
+
`),e.push(`## Fields
|
|
36
|
+
`),e.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),e.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,d]of Object.entries(r.fields))e.push([s,d.type,d.required?"Yes":"No",t(d.default),d.description?.replace(/\n/g," ")||"",d.deprecated?"Yes":"No",d.unique?"Yes":"No",d.constraints?.length||0].join("|"));Object.entries(r.fields).forEach(([s,d])=>{d.nestedSchema&&(e.push(`
|
|
37
|
+
### Nested Schema: ${s}
|
|
38
|
+
`),e.push(p(d.nestedSchema)))}),e.push(`
|
|
39
39
|
## Indexes
|
|
40
|
-
`),
|
|
40
|
+
`),e.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),e.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of r.indexes||[])e.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?i(s.partial):"None",s.description||""].join("|"));e.push(`
|
|
41
41
|
## Constraints
|
|
42
|
-
`),
|
|
42
|
+
`),r.constraints&&e.push("### Schema-level Constraints"),e.push(`
|
|
43
43
|
## Migrations
|
|
44
|
-
`),
|
|
45
|
-
<!-- Error generating mock data -->`)}return
|
|
46
|
-
`)}export{
|
|
44
|
+
`),e.push("| ID | Description | Status | Changes |"),e.push("|----|-------------|--------|---------|");for(let s of r.migrations||[])e.push([s.id,s.description,s.status,s.changes.length].join("|"));if(r.mock&&n?.faker)try{let s=r.mock(n.faker).next().value;e.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{e.push(`
|
|
45
|
+
<!-- Error generating mock data -->`)}return e.join(`
|
|
46
|
+
`)}export{g as JsonPatchError,W as MigrationEngine,h as MigrationError,Se as MigrationErrorCode,pe as MigrationSchema,D as applyPatch,Q as calculateNextVersion,v as compareSemanticVersions,Te as createPatch,be as createSchemaMigrationHelper,ae as createStandardSchemaValidator,U as deepMerge,Pt as docgen,j as generateSHA256Hash,Z as normalizePath,L as schemaChangeToPatch,Ot as schemaToTypes,Ae as sortSemanticVars,Me as validate,K as validateMigration,Y as validateSchemaChange,N as validateSchemaDefinition};
|