@blue-labs/language 5.0.0-rc.1 → 5.0.0-rc.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.
@@ -1,98 +0,0 @@
1
- "use strict";const fe=require("big.js"),u=require("@blue-labs/shared-utils"),m=require("zod"),$r=require("bs58"),ve=require("radash"),y=require("@blue-labs/repository-contract"),kr=require("js-sha256"),qr=require("crypto");require("base32.js");const Be=require("js-yaml"),Yt=n=>n&&n.__esModule?n:{default:n},De=Yt($r),ft=Yt(qr);class V extends fe{constructor(e){super(e)}}class R extends fe{constructor(e){super(e)}}const ae="name",le="description",F="type",me="itemType",ye="keyType",ge="valueType",ee="value",Te="items",N="blueId",rt="blue",wt="constraints",St="properties",Kr="positional",Gr="append-only",ce="$previous",it="$pos",st="$replace",Ie="$empty",Ct=[ae,le,F,me,ye,ge,ee,Te,N,rt,y.OBJECT_SCHEMA,y.OBJECT_MERGE_POLICY,y.OBJECT_CONTRACTS,wt,St,ce,it,st,Ie],Wt="Text",Zt="Double",Jt="Integer",Xt="Boolean",Qt="List",er="Dictionary",nt=[Wt,Zt,Jt,Xt],Rt=[...nt,Qt,er],k="GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC",q="9eWaHYz2vKrFofdHTHAizNNu8xP6QE3WQ5y7DGrGZvyJ",H="E2LM6qgzWG9ttagq2xTmiZkgYEAgkYedFCmU9v7NnVEq",Y="AwvXD961fmnmqcSQhjMA7r15HpVh39cefb6ZTyUz2Fm2",ot="8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF",at="Efkz9D1ARMM7rU43w3rDNVqat1naS6qXKCqP4eHin3yG",At=[k,q,H,Y],ie=[...At,ot,at],lt=Object.fromEntries(Rt.map((n,e)=>[n,ie[e]])),ct=Object.fromEntries(ie.map((n,e)=>[n,Rt[e]])),X={Contract:"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF","Json Patch Entry":"61W96XosAp3DrEC7PuqLYtmF2A6ETpqH6qF2DgYwDq4c","Contract Execution Result":"AMtAXPmvumgz1GxKUU9uv3ncXiKMENvqq8AaLvD5LXhv",Channel:"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5",Handler:"7X46P3Q6FJrogqKrBXTALpqzkieyyiQeatnqLvWzAPXE",Marker:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy","Process Embedded":"8FVc8MPz6DcTMgcY3RXU6EBpGa9arWPJ141K2H86yi8Q","Processing Initialized Marker":"6JjyUKoK7uJxA5NY9YhMaKJbXC6c9iHyx1khv4gaAq4Q","Processing Terminated Marker":"GBDBthfshBFr4GQKUU1fmy4GnPL7q2y3as4deUWpuBtu","Channel Event Checkpoint":"9GEC24YbFG9hj4banjYh2oEnDpAob1wAPmhjuykJp8T1","Type Generalization Policy":"Fbenow6tanFHkWzKiDD8fGxminQswQ1FecMRakaCx2WX","Type Generalization Rule":"7Vnmk8StjwY7e9mBNpACrn8oh3KZ7yQBjnXe5bLDWn4D","Document Update Channel":"Ac9LC5T7pHVa1TtkhMBjBRtxecShzvbe7ugUdXT1Mu2o","Triggered Event Channel":"5HwxfbwRBCxG8xYpowWkCPC9akqUSKV7So2M4QHEmLsZ","Lifecycle Event Channel":"2DXGQUiQBQ6CT89jwAsTAXaEPhLgiSXhKCGh9Q7Hv3MQ","Embedded Node Channel":"H6iUJp3GcLypsJDimMSVoxQQdxxuD8j6eqEUWWqCZ6i","Document Update":"7HEaG1SpBdsbVHsrwRTZSZGmpJUWHfFoEzecYWpjo1vm","Document Processing Initiated":"Ht1o66MTLKf7JmnEiR27rRLSwdz8FUTgf2mGPNuLSDUL","Document Processing Terminated":"4HWncQEQsdpk8zcXxYxgdtoXo5nKHxFPWeJfTscCbmeK","Document Processing Fatal Error":"AMZbj5tNGxjPrvaNyw56sfqcLSW2j1XmkncEYUVtgmVC"},Ot={...lt,...X},tr=Object.fromEntries(Object.entries(X).map(([n,e])=>[e,n])),rr={...ct,...tr},Hr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:nt,BASIC_TYPE_BLUE_IDS:At,BLUE_CONTRACTS_RUNTIME_TYPE_BLUE_ID_TO_NAME_MAP:tr,BLUE_CONTRACTS_RUNTIME_TYPE_NAME_TO_BLUE_ID_MAP:X,BOOLEAN_TYPE:Xt,BOOLEAN_TYPE_BLUE_ID:Y,CORE_TYPES:Rt,CORE_TYPE_BLUE_IDS:ie,CORE_TYPE_BLUE_ID_TO_NAME_MAP:ct,CORE_TYPE_NAME_TO_BLUE_ID_MAP:lt,DEFAULT_BLUE_TYPE_BLUE_ID_TO_NAME_MAP:rr,DEFAULT_BLUE_TYPE_NAME_TO_BLUE_ID_MAP:Ot,DICTIONARY_TYPE:er,DICTIONARY_TYPE_BLUE_ID:at,DOUBLE_TYPE:Zt,DOUBLE_TYPE_BLUE_ID:q,INTEGER_TYPE:Jt,INTEGER_TYPE_BLUE_ID:H,LIST_CONTROL_EMPTY:Ie,LIST_CONTROL_POS:it,LIST_CONTROL_PREVIOUS:ce,LIST_CONTROL_REPLACE:st,LIST_MERGE_POLICY_APPEND_ONLY:Gr,LIST_MERGE_POLICY_POSITIONAL:Kr,LIST_TYPE:Qt,LIST_TYPE_BLUE_ID:ot,OBJECT_BLUE:rt,OBJECT_BLUE_ID:N,OBJECT_CONSTRAINTS:wt,OBJECT_CONTRACTS:y.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:le,OBJECT_ITEMS:Te,OBJECT_ITEM_TYPE:me,OBJECT_KEY_TYPE:ye,OBJECT_MERGE_POLICY:y.OBJECT_MERGE_POLICY,OBJECT_NAME:ae,OBJECT_PROPERTIES:St,OBJECT_SCHEMA:y.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:Ct,OBJECT_TYPE:F,OBJECT_VALUE:ee,OBJECT_VALUE_TYPE:ge,TEXT_TYPE:Wt,TEXT_TYPE_BLUE_ID:k},Symbol.toStringTag,{value:"Module"}));class Yr{static get(e,t,r,i=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return i&&o!==void 0?o:e}const s=t.substring(1).split("/");return this.getRecursive(e,s,0,r,i)}static getRecursive(e,t,r,i,s){if(r===t.length-1&&!s)return this.getNodeForSegment(e,t[r],i,!1);if(r===t.length){const l=e.getValue();return s&&l!==void 0?l:e}const o=t[r],a=this.getNodeForSegment(e,o,i,!0);if(a)return this.getRecursive(a,t,r+1,i,s)}static getNodeForSegment(e,t,r,i){let s;const o=e.getProperties();if(o&&t in o)s=o[t];else switch(t){case"name":{const a=e.getName();s=new h().setValue(a??null);break}case"description":{const a=e.getDescription();s=new h().setValue(a??null);break}case"type":s=e.getType();break;case"itemType":s=e.getItemType();break;case"keyType":s=e.getKeyType();break;case"valueType":s=e.getValueType();break;case"value":{const a=e.getValue();s=new h().setValue(a??null);break}case"blueId":{const a=e.getBlueId();s=new h().setValue(a??null);break}case"blue":s=e.getBlue();break;case"items":{const a=e.getItems();s=new h().setItems(a);break}case"properties":{const a=e.getProperties();s=new h().setProperties(a);break}case y.OBJECT_CONTRACTS:{const a=e.getContracts();s=new h().setContracts(a);break}default:{if(/^\d+$/.test(t)){const a=parseInt(t,10),l=e.getItems();l&&a>=0&&a<l.length?s=l[a]:s=void 0}else s=void 0;break}}if(s)return i&&r?this.link(s,r):s}static link(e,t){const r=t(e);return u.isNonNullable(r)?r:e}}class h{static INTEGER=new h("Integer");name;description;type;itemType;keyType;valueType;value;items;properties;contracts;blueId;schema;mergePolicy;previousBlueId;position;blue;inlineValue=!1;constructor(e){this.name=e}getName(){return this.name}setName(e){return this.name=e,this}getDescription(){return this.description}setDescription(e){return this.description=e,this}getType(){return this.type}setType(e){return typeof e=="string"?this.type=new h().setValue(e).setInlineValue(!0):this.type=e,this}getItemType(){return this.itemType}setItemType(e){return typeof e=="string"?this.itemType=new h().setValue(e).setInlineValue(!0):this.itemType=e,this}getKeyType(){return this.keyType}setKeyType(e){return typeof e=="string"?this.keyType=new h().setValue(e).setInlineValue(!0):this.keyType=e,this}getValueType(){return this.valueType}setValueType(e){return typeof e=="string"?this.valueType=new h().setValue(e).setInlineValue(!0):this.valueType=e,this}getValue(){const e=this.type?.getBlueId();if(u.isNonNullable(e)&&u.isNonNullable(this.value)){if(e===H&&typeof this.value=="string")return new R(this.value);if(e===q&&typeof this.value=="string"){const t=new V(this.value),r=parseFloat(t.toString());return new V(r.toString())}else if(e===Y&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}getRawValue(){return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new R(e.toString()):this.value=new V(e.toString()):this.value=e,this}getItems(){return this.items}setItems(e){return this.items=e,this}addItems(...e){return this.items||(this.items=[]),this.items.push(...e),this}getProperties(){return this.properties}setProperties(e){return this.properties=e,this.contracts=e?.[y.OBJECT_CONTRACTS],this}addProperty(e,t){return this.properties||(this.properties={}),this.properties[e]=t,e===y.OBJECT_CONTRACTS&&(this.contracts=t),this}removeProperty(e){return this.properties&&delete this.properties[e],e===y.OBJECT_CONTRACTS&&(this.contracts=void 0),this}getContractsProperty(){return this.contracts??this.properties?.[y.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}getContractsNode(){return this.contracts??this.properties?.[y.OBJECT_CONTRACTS]}setContracts(e){return u.isNullable(e)?(this.contracts=void 0,this.removeProperty(y.OBJECT_CONTRACTS)):(this.contracts=new h().setProperties(e),this.addProperty(y.OBJECT_CONTRACTS,this.contracts)),this}setContractsNode(e){return this.contracts=e,e===void 0?this.removeProperty(y.OBJECT_CONTRACTS):this.addProperty(y.OBJECT_CONTRACTS,e),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(y.OBJECT_CONTRACTS,new h().addProperty(e,t)):r.addProperty(e,t),this}removeContract(e){const t=this.getContractsProperty();if(t){t.removeProperty(e);const r=t.getProperties();r&&Object.keys(r).length===0&&this.removeProperty(y.OBJECT_CONTRACTS)}return this}getReferenceBlueId(){return this.blueId}setReferenceBlueId(e){return this.blueId=e,this}getBlueId(){return this.getReferenceBlueId()}setBlueId(e){return this.setReferenceBlueId(e)}getSchema(){return this.schema}setSchema(e){return this.schema=e,this}getMergePolicy(){return this.mergePolicy}setMergePolicy(e){return this.mergePolicy=e,this}getPreviousBlueId(){return this.previousBlueId}setPreviousBlueId(e){return this.previousBlueId=e,this}getPosition(){return this.position}setPosition(e){return this.position=e,this}getBlue(){return this.blue}setBlue(e){return this.blue=e,this}isInlineValue(){return this.inlineValue}setInlineValue(e){return this.inlineValue=e,this}isResolved(){return!1}get(e,t){return Yr.get(this,e,t)}getAsNode(e){const t=this.get(e);if(t instanceof h)return t;throw new Error(`Value at path ${e} is not a BlueNode: ${t}`)}getAsInteger(e){const t=this.get(e);if(t instanceof R||t instanceof V)return t.toNumber();throw new Error(`Value at path ${e} is not a BigInteger or BigDecimal: ${t}`)}clone(){const e=new h(this.name);return e.description=this.description,e.type=this.type?.clone(),e.itemType=this.itemType?.clone(),e.keyType=this.keyType?.clone(),e.valueType=this.valueType?.clone(),e.value=this.value,e.items=this.items?.map(t=>t.clone()),this.properties&&(e.properties=Object.fromEntries(Object.entries(this.properties).map(([t,r])=>[t,r.clone()]))),this.contracts&&(e.contracts=e.properties?.[y.OBJECT_CONTRACTS]??this.contracts.clone()),e.blueId=this.blueId,e.schema=this.schema?.clone(),e.mergePolicy=this.mergePolicy,e.previousBlueId=this.previousBlueId,e.position=this.position,e.blue=this.blue?.clone(),e.inlineValue=this.inlineValue,e}cloneShallow(){const e=new h(this.name);return e.description=this.description,e.type=this.type,e.itemType=this.itemType,e.keyType=this.keyType,e.valueType=this.valueType,e.value=this.value,e.items=this.items?[...this.items]:void 0,e.properties=this.properties?{...this.properties}:void 0,e.contracts=e.properties?.[y.OBJECT_CONTRACTS]??this.contracts,e.blueId=this.blueId,e.schema=this.schema,e.mergePolicy=this.mergePolicy,e.previousBlueId=this.previousBlueId,e.position=this.position,e.blue=this.blue,e.inlineValue=this.inlineValue,e}toString(){return`BlueNode{name='${this.name}', description='${this.description}', type=${this.type}, itemType=${this.itemType}, keyType=${this.keyType}, valueType=${this.valueType}, value=${this.value}, items=${this.items}, properties=${this.properties}, blueId='${this.blueId}', blue=${this.blue}, inlineValue=${this.inlineValue}}`}}class K{static MIN_BLUE_ID_LENGTH=41;static MAX_BLUE_ID_LENGTH=45;static ZERO_BLUE_ID="0".repeat(44);static PLAIN_BLUE_ID_PATTERN=/^[1-9A-HJ-NP-Za-km-z]+$/;static CYCLIC_MEMBER_PATTERN=/^([1-9A-HJ-NP-Za-km-z]+)#(0|[1-9]\d*)$/;static THIS_MEMBER_PATTERN=/^this#(0|[1-9]\d*)$/;static ZERO_PLACEHOLDER_PATTERN=/^0{44}$/;static isPotentialBlueId(e){try{return this.requireBlueIdOrCyclicMember(e,"blueId"),!0}catch{return!1}}static requirePlainBlueId(e,t){if(e===void 0||e.length===0||!this.PLAIN_BLUE_ID_PATTERN.test(e))throw new Error(`Expected canonical Base58 SHA-256 BlueId at ${t}.`);try{const r=De.default.decode(e);if(r.length!==32||De.default.encode(r)!==e)throw new Error}catch{throw new Error(`Expected canonical Base58 SHA-256 BlueId at ${t}.`)}return e}static requireBlueIdOrCyclicMember(e,t){if(e===void 0)throw new Error(`Expected BlueId at ${t}.`);const r=e.match(this.CYCLIC_MEMBER_PATTERN);if(r!==null)return this.requirePlainBlueId(r[1],t),e;if(e.includes("#"))throw new Error(`Invalid cyclic BlueId member syntax at ${t}.`);return this.requirePlainBlueId(e,t)}static requireNoThisPlaceholderOutsideCyclicApi(e,t){if(e!==void 0&&(e==="this"||this.THIS_MEMBER_PATTERN.test(e)))throw new Error(`"this" BlueId placeholders are valid only inside cyclic BlueId calculation APIs. Path: ${t}`);return e}static isCyclicCalculationPlaceholder(e){return e!==void 0&&(e==="this"||this.THIS_MEMBER_PATTERN.test(e)||this.ZERO_PLACEHOLDER_PATTERN.test(e))}}const Wr=m.z.string().max(K.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(K.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(n=>{try{return De.default.decode(n),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),Ze=m.z.lazy(()=>m.z.record(m.z.unknown()).and(m.z.object({blueId:m.z.string().optional(),name:m.z.string().optional(),description:m.z.string().optional(),type:Ze.optional(),value:m.z.union([m.z.string(),m.z.number(),m.z.boolean()]).optional().nullable(),items:m.z.array(Ze).optional()}))),ze=m.z.object({blueId:m.z.string().optional(),name:m.z.string().optional(),description:m.z.string().optional(),type:Ze.optional()}),Zr=ze.extend({value:m.z.string().optional()}),Jr=ze.extend({value:m.z.number().optional()}),Xr=ze.extend({value:m.z.boolean().optional()}),Qr=ze.extend({items:m.z.array(m.z.string()).optional()}),x=n=>n instanceof fe,W=n=>x(n)&&n instanceof R,Je=n=>x(n)&&n instanceof V,ei=m.z.lazy(()=>m.z.record(Xe)),ti=m.z.lazy(()=>m.z.union([m.z.array(Xe),m.z.array(Xe).readonly()])),Xe=m.z.lazy(()=>m.z.union([u.jsonPrimitiveSchema,ei,ti,m.z.instanceof(fe)])),$=n=>ve.isObject(n)&&!ve.isArray(n)&&!u.isReadonlyArray(n)&&!x(n),Mt=n=>ve.isArray(n)||u.isReadonlyArray(n),ri=n=>Mt(n)||$(n)||x(n)||u.isJsonPrimitive(n),ut=["required","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minItems","maxItems","uniqueItems","minFields","maxFields"];class je{fields={};enumValues;get(e){return this.fields[e]}set(e,t){return t===void 0?delete this.fields[e]:this.fields[e]=t,this}getEnum(){return this.enumValues}setEnum(e){return this.enumValues=e,this}entries(){return ut.flatMap(e=>{const t=this.fields[e];return t===void 0?[]:[[e,t]]})}clone(){const e=new je;for(const[t,r]of this.entries())e.set(t,r.clone());return e.setEnum(this.enumValues?.map(t=>t.clone())),e}}const ii=new R(Number.MIN_SAFE_INTEGER.toString()),si=new R(Number.MAX_SAFE_INTEGER.toString());class g{static deserialize(e){return g.handleNode(e,{root:!0,strictReferenceOnly:!0})}static deserializeUnchecked(e){return g.handleNode(e,{root:!1,strictReferenceOnly:!1})}static handleNode(e,t={root:!1,strictReferenceOnly:!0}){if(e===void 0)throw new Error("This is not a valid JSON-like value. Found 'undefined' as a value.");if(e===null&&t.root)throw new Error("Root null is not a valid Blue document.");if($(e)){const r=new h,i={};return Object.entries(e).forEach(([s,o])=>{switch(s){case ae:if(o==null)r.setName(void 0);else{if(typeof o!="string")throw new Error(`The ${ae} field must be a string.`);r.setName(o)}break;case le:if(o==null)r.setDescription(void 0);else{if(typeof o!="string")throw new Error(`The ${le} field must be a string.`);r.setDescription(o)}break;case F:r.setType(g.handleNode(o,{...t,root:!1}));break;case me:r.setItemType(g.handleNode(o,{...t,root:!1}));break;case ye:r.setKeyType(g.handleNode(o,{...t,root:!1}));break;case ge:r.setValueType(g.handleNode(o,{...t,root:!1}));break;case y.OBJECT_MERGE_POLICY:if(o!=="positional"&&o!=="append-only"&&o!==void 0)throw new Error('The mergePolicy field must be "positional" or "append-only".');r.setMergePolicy(o);break;case ee:r.setValue(g.handleValue(o));break;case N:if(t.strictReferenceOnly&&Object.keys(e).length!==1)throw new Error("blueId nodes must be reference-only and cannot contain sibling fields.");if(typeof o!="string")throw new Error(`The ${N} field must be a string.`);r.setBlueId(o);break;case Te:r.setItems(g.handleArray(o,t));break;case rt:r.setBlue(g.handleNode(o,{...t,root:!1}));break;case ce:if(Object.keys(e).length!==1)throw new Error("$previous list anchors must be single-key list items.");r.setPreviousBlueId(g.handlePreviousBlueId(o));break;case it:r.setPosition(g.handlePosition(o));break;case y.OBJECT_SCHEMA:r.setSchema(g.handleSchema(o,t));break;case y.OBJECT_CONTRACTS:i[s]=g.handleNode(o,{...t,root:!1});break;case wt:throw new Error("constraints is not part of the Blue Language 1.0 top-level vocabulary.");case St:throw new Error("properties is an internal field and must not appear in Blue documents.");default:i[s]=g.handleNode(o,{...t,root:!1});break}}),Object.keys(i).length>0&&r.setProperties(i),r}else{if(Mt(e))return new h().setItems(g.handleArray(e,t));{const r=e;return new h().setValue(g.handleValue(r)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||x(e)){if(typeof e=="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error("Unquoted integers outside [-9007199254740991, 9007199254740991] must be quoted and explicitly typed as Integer.");if(W(e)||Number.isSafeInteger(e)){const t=new R(e.toString());if(t.lt(ii)||t.gt(si))throw new Error("Unquoted integers outside [-9007199254740991, 9007199254740991] must be quoted and explicitly typed as Integer.");return t}else{const t=parseFloat(e.toString());return new V(t.toString())}}else if(typeof e=="boolean")return e;throw new Error(`Can't handle node: ${JSON.stringify(e)}`)}static handleArray(e,t){if(e!=null){if(ve.isObject(e)&&!Array.isArray(e))return[g.handleNode(e,{...t,root:!1})];if(Array.isArray(e))return e.map(r=>g.handleNode(r,{...t,root:!1}));throw new Error("Expected an array node")}}static handlePreviousBlueId(e){if(!$(e)||Object.keys(e).length!==1)throw new Error("$previous must have shape { blueId: <PrevListBlueId> }.");const t=e[N];if(typeof t!="string")throw new Error("$previous.blueId must be a string.");return t}static handlePosition(e){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("$pos must be a non-negative integer.");return e}static handleSchema(e,t){if(!$(e))throw new Error("schema must be an object.");const r=new je;for(const i of Object.keys(e)){if(i==="enum"){const s=e[i];if(!Array.isArray(s))throw new Error("schema.enum must be a list.");r.setEnum(s.map(o=>g.handleNode(o,{...t,root:!1})));continue}if(!ut.includes(i))throw new Error(`schema.${i} is not part of the Blue language core.`);g.validateSchemaKeywordShape(i,e[i],t),r.set(i,g.handleNode(e[i],{...t,root:!1}))}return r}static validateSchemaKeywordShape(e,t,r){if(e==="required"||e==="uniqueItems"){if(typeof t!="boolean")throw new Error(`schema.${e} must be a boolean.`);return}if(["minLength","maxLength","minItems","maxItems","minFields","maxFields"].includes(e)){if(typeof t!="number"||!Number.isInteger(t)||t<0||!Number.isSafeInteger(t))throw new Error(`schema.${e} must be a non-negative integer in the interoperable range.`);return}if($(t)){const i=g.handleNode(t,{...r,root:!1});if(i.getValue()!==void 0&&i.getValue()!==null)return;throw new Error(`schema.${e} must be numeric or an explicit numeric scalar node.`)}if(typeof t!="number"&&!x(t))throw new Error(`schema.${e} must be numeric or an explicit numeric scalar node.`)}}function ni(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var mt,Ut;function oi(){return Ut||(Ut=1,mt=function n(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?n(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,s,o)=>`${i}${o===0?"":","}${n(s===void 0||typeof s=="symbol"?null:s)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return r;const s=r.length===0?"":",";return`${r}${s}${n(i)}:${n(e[i])}`},"")}}`}),mt}var ai=oi();const li=ni(ai);class Qe{static canonicalize(e){return li(e)}}const yt=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class Vt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new Vt),this.instance}initBrowserCrypto(){return yt?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return yt&&!!ft.default&&typeof ft.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return yt?ft.default:null}}class ir{cryptoEnv=Vt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return De.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return De.default.encode(r)}canonicalizeInput(e){const t=Qe.canonicalize(e);if(typeof t!="string")throw new Error("Canonized value must be a string");return t}sha256Sync(e){const t=this.cryptoEnv.getNodeCrypto();if(!t)throw new Error("Synchronous SHA-256 is not available in this environment");const r=t.createHash("sha256").update(e).digest();return new Uint8Array(r)}sha256SyncBrowser(e){return new Uint8Array(kr.sha256.arrayBuffer(e))}async sha256Async(e){if(this.cryptoEnv.hasNodeCrypto())return Promise.resolve(this.sha256Sync(e));const t=this.cryptoEnv.getBrowserCrypto();if(!t)throw new Error("crypto is not available in this environment");const i=new TextEncoder().encode(e),s=await t.subtle.digest("SHA-256",i);return new Uint8Array(s)}}class sr{static toCanonicalDoubleValue(e){const t=e instanceof V||e instanceof R?e.toNumber():typeof e=="number"?e:typeof e=="string"?Number(e):Number.NaN;if(!Number.isFinite(t))throw new Error("Double value must be finite.");return new V(t.toString())}static isExactBinary64Multiple(e,t){const r=Ee.fromNumber(this.toFiniteNumber(e)),i=Ee.fromNumber(this.toFiniteNumber(t));return r.dividedByIsInteger(i)}static toFiniteNumber(e){const t=e instanceof V||e instanceof R?e.toNumber():typeof e=="number"?e:Number.NaN;if(!Number.isFinite(t))throw new Error("Double value must be finite.");return t}}class Ee{constructor(e,t){if(this.numerator=e,this.denominator=t,t<=0n)throw new Error("denominator must be positive");const r=ci(zt(e),t);this.numerator=e/r,this.denominator=t/r}static fromNumber(e){if(!Number.isFinite(e))throw new Error("Double value must be finite.");if(Object.is(e,0)||Object.is(e,-0))return new Ee(0n,1n);const t=new ArrayBuffer(8),r=new DataView(t);r.setFloat64(0,e,!1);const i=r.getBigUint64(0,!1),s=(i&1n<<63n)!==0n,o=Number(i>>52n&0x7ffn),a=i&0x000fffffffffffffn;let l,c;return o===0?(l=a,c=-1074):(l=1n<<52n|a,c=o-1023-52),s&&(l=-l),c>=0?new Ee(l<<BigInt(c),1n):new Ee(l,1n<<BigInt(-c))}dividedByIsInteger(e){if(e.numerator===0n)throw new Error("Division by zero rational.");const t=this.numerator*e.denominator,r=this.denominator*zt(e.numerator);return t%r===0n}}function ci(n,e){let t=n,r=e;for(;r!==0n;){const i=t%r;t=r,r=i}return t===0n?1n:t}function zt(n){return n<0n?-n:n}const ui=new R(Number.MIN_SAFE_INTEGER.toString()),di=new R(Number.MAX_SAFE_INTEGER.toString());class ne{static get(e){return this.getNode(e,"/","root",-1,!1)}static getAllowingCyclicPlaceholders(e){return this.getNode(e,"/","root",-1,!0)}static getWithResolvedBlueIdMetadata(e){return this.getNode(this.stripResolvedBlueIdMetadata(e.clone()),"/","root",-1,!1)}static stripResolvedBlueIdMetadata(e){e.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(e)&&e.setReferenceBlueId(void 0),this.stripResolvedBlueIdMetadataChild(e.getType()),this.stripResolvedBlueIdMetadataChild(e.getItemType()),this.stripResolvedBlueIdMetadataChild(e.getKeyType()),this.stripResolvedBlueIdMetadataChild(e.getValueType()),this.stripResolvedBlueIdMetadataChild(e.getBlue()),this.stripResolvedBlueIdMetadataChild(e.getContractsNode()),e.getItems()?.forEach(r=>this.stripResolvedBlueIdMetadata(r)),Object.values(e.getProperties()??{}).forEach(r=>this.stripResolvedBlueIdMetadata(r));const t=e.getSchema();return t?.entries().forEach(([,r])=>this.stripResolvedBlueIdMetadata(r)),t?.getEnum()?.forEach(r=>this.stripResolvedBlueIdMetadata(r)),e}static stripResolvedBlueIdMetadataChild(e){e!==void 0&&this.stripResolvedBlueIdMetadata(e)}static getListElement(e,t){return this.getNode(e,`/${t}`,"list-element",t,!1)}static getListElementAllowingCyclicPlaceholders(e,t){return this.getNode(e,`/${t}`,"list-element",t,!0)}static getNode(e,t,r,i,s){if(this.validateBlueIdInput(e,t,r,i),r==="list-element"&&this.isEmptyPlaceholder(e))return{[Ie]:!0};if(this.isReferenceOnly(e)){const f=this.validateReferenceBlueId(e.getReferenceBlueId(),this.appendPath(t,N),s);return{[N]:f}}if(e.getPreviousBlueId()!==void 0){const f=K.requirePlainBlueId(e.getPreviousBlueId(),this.appendPath(this.appendPath(t,ce),N));return{[ce]:{[N]:f}}}const o=e.getValue(),a=e.getItems(),l=a===void 0?void 0:a.map((f,I)=>this.getNode(f,this.appendPath(this.appendPath(t,Te),String(I)),"list-element",I,s));if(l!==void 0&&this.isPayloadOnlyList(e))return l;const c={};this.setString(c,ae,e.getName()),this.setString(c,le,e.getDescription());let d;o!=null&&e.getType()===void 0?(d=this.inferTypeBlueId(o),d!==void 0&&(c[F]={[N]:d})):e.getType()!==void 0&&(d=e.getType()?.getReferenceBlueId(),c[F]=this.getNode(e.getType(),this.appendPath(t,F),"metadata",-1,s)),this.setNode(c,me,e.getItemType(),t,s),this.setNode(c,ye,e.getKeyType(),t,s),this.setNode(c,ge,e.getValueType(),t,s),e.getMergePolicy()!==void 0&&(c[y.OBJECT_MERGE_POLICY]=e.getMergePolicy()),o!=null&&(c[ee]=this.handleValue(o,d)),l!==void 0&&(c[Te]=l);const p=e.getSchema();p!==void 0&&(c[y.OBJECT_SCHEMA]=this.schemaToInput(p,this.appendPath(t,y.OBJECT_SCHEMA),s)),e.getContractsNode()!==void 0&&(c[y.OBJECT_CONTRACTS]=this.getNode(e.getContractsNode(),this.appendPath(t,y.OBJECT_CONTRACTS),"metadata",-1,s));for(const[f,I]of Object.entries(e.getProperties()??{}))f!==y.OBJECT_CONTRACTS&&(c[f]=this.getNode(I,this.appendPath(t,f),"object-field",-1,s));return c}static schemaToInput(e,t,r){const i={};for(const[o,a]of e.entries())i[o]=this.getNode(a,this.appendPath(t,o),"metadata",-1,r);const s=e.getEnum();return s!==void 0&&(i.enum=this.canonicalizeSchemaEnumValues(s,this.appendPath(t,"enum"),r).map((o,a)=>this.getNode(o,this.appendPath(this.appendPath(t,"enum"),String(a)),"metadata",-1,r))),i}static canonicalizeSchemaEnumValues(e,t,r){const i=new Map;for(const s of e){const o=s.clone();o.setSchema(void 0),i.set(JSON.stringify(this.getNode(o,t,"metadata",-1,r)),s)}return[...i.entries()].sort(([s],[o])=>s.localeCompare(o)).map(([,s])=>s)}static validateReferenceBlueId(e,t,r){return r&&K.isCyclicCalculationPlaceholder(e)?e:K.requireBlueIdOrCyclicMember(K.requireNoThisPlaceholderOutsideCyclicApi(e,t),t)}static validateBlueIdInput(e,t,r,i){if(e===void 0)throw new Error(`BlueId input must not contain null nodes. Path: ${t}`);if(r==="metadata"&&this.isTypePosition(t)&&e.isInlineValue())throw new Error(`Direct BlueId input must not contain unresolved type aliases. Path: ${t}`);if(e.getBlue()!==void 0)throw new Error(`"blue" is a preprocessing directive and must not be present in BlueId input. Call preprocess/canonicalize/calculateSemanticBlueId first. Path: ${t}`);if(e.getPosition()!==void 0)throw new Error(`"$pos" overlays are not valid direct BlueId input. Path: ${t}`);if(e.getProperties()?.[st]!==void 0)throw new Error(`"$replace" overlays are not valid direct BlueId input. Path: ${t}`);if(r==="list-element"){if(this.isEmptyNode(e))throw new Error(`Direct BlueId input must use { "$empty": true } for empty list placeholders. Path: ${t}`);if(e.getProperties()?.[Ie]!==void 0&&this.validateEmptyPlaceholder(e,t),e.getPreviousBlueId()!==void 0&&i!==0)throw new Error(`"$previous" must appear only as the first list item. Path: ${t}`)}else if(e.getPreviousBlueId()!==void 0)throw new Error(`"$previous" is valid only as the first list item in direct BlueId input. Path: ${t}`);this.validatePayloadKind(e,t)}static validatePayloadKind(e,t){const r=this.ordinaryPropertyKeys(e),i=[e.getValue()!==void 0&&e.getValue()!==null,e.getItems()!==void 0,r.length>0].filter(Boolean).length;if(i>1)throw new Error(`A Blue node may contain only one payload kind: value, items, or object fields. Path: ${t}`);if(e.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(e))throw new Error(`"blueId" nodes must be reference-only and cannot contain sibling fields. Path: ${t}`);if(e.getPreviousBlueId()!==void 0&&(i>0||e.getName()!==void 0||e.getDescription()!==void 0||e.getType()!==void 0||e.getItemType()!==void 0||e.getKeyType()!==void 0||e.getValueType()!==void 0||e.getSchema()!==void 0||e.getMergePolicy()!==void 0||e.getPosition()!==void 0||e.getContractsNode()!==void 0||e.getReferenceBlueId()!==void 0))throw new Error(`"$previous" list anchors must be single-key list items. Path: ${t}`)}static handleValue(e,t){if(t===q)return sr.toCanonicalDoubleValue(e).toNumber();if(e instanceof R||W(e))return e.lt(ui)||e.gt(di)?e.toString():e.toNumber();const r=e;if(r instanceof V||x(r))return r.toNumber();if(typeof e=="string"||typeof e=="boolean")return e;throw new Error(`Unsupported Blue scalar value: ${String(e)}`)}static inferTypeBlueId(e){if(typeof e=="string")return k;if(e instanceof R||W(e))return H;if(e instanceof V||x(e))return q;if(typeof e=="boolean")return Y}static setString(e,t,r){r!==void 0&&(e[t]=r)}static setNode(e,t,r,i,s){r!==void 0&&(e[t]=this.getNode(r,this.appendPath(i,t),"metadata",-1,s))}static isReferenceOnly(e){return e.getReferenceBlueId()!==void 0&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&(e.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isPayloadOnlyList(e){return e.getItems()!==void 0&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&(e.getValue()===void 0||e.getValue()===null)&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isEmptyNode(e){return e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&(e.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&this.ordinaryPropertyKeys(e).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}static isEmptyPlaceholder(e){const t=e.getProperties(),r=t?.[Ie];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&r.getValue()===!0&&r.getItems()===void 0&&Object.keys(r.getProperties()??{}).length===0}static validateEmptyPlaceholder(e,t){if(!this.isEmptyPlaceholder(e))throw new Error(`"$empty" list placeholder must have exact shape { "$empty": true }. Path: ${t}`)}static isTypePosition(e){return e.endsWith(`/${F}`)||e.endsWith(`/${me}`)||e.endsWith(`/${ye}`)||e.endsWith(`/${ge}`)}static appendPath(e,t){const r=t.replace(/~/g,"~0").replace(/\//g,"~1");return e==="/"?`/${r}`:`${e}/${r}`}static ordinaryPropertyKeys(e){return Object.keys(e.getProperties()??{}).filter(t=>t!==y.OBJECT_CONTRACTS)}}const hi=new Set([ae,le,ee]);class E{constructor(e){this.hashProvider=e}static INSTANCE=new E(new ir);static calculateBlueId(e){return E.INSTANCE.calculate(e)}static calculateBlueIdSync(e){return E.INSTANCE.calculateSync(e)}static calculateBlueIdAllowingCyclicPlaceholdersSync(e){return E.INSTANCE.calculateAllowingCyclicPlaceholdersSync(e)}static calculateBlueIdWithResolvedBlueIdMetadataSync(e){return E.INSTANCE.calculateInput(ne.getWithResolvedBlueIdMetadata(e),!0)}static calculateBlueIdInputSync(e){return E.INSTANCE.calculateInput(e,!0)}calculate(e){return this.calculateInput(this.prepareInput(e),!1)}calculateSync(e){return this.calculateInput(this.prepareInput(e),!0)}calculateAllowingCyclicPlaceholdersSync(e){return this.calculateInput(this.prepareInputAllowingCyclicPlaceholders(e),!0)}prepareInput(e){return e instanceof h?ne.get(e):Array.isArray(e)&&e.every(t=>t instanceof h)?e.map((t,r)=>ne.getListElement(t,r)):ne.get(g.deserialize(e))}prepareInputAllowingCyclicPlaceholders(e){return e instanceof h?ne.getAllowingCyclicPlaceholders(e):Array.isArray(e)&&e.every(t=>t instanceof h)?e.map((t,r)=>ne.getListElementAllowingCyclicPlaceholders(t,r)):ne.getAllowingCyclicPlaceholders(g.deserialize(e))}calculateInput(e,t){return this.calculateCleaned(this.cleanRoot(e),t)}calculateCleaned(e,t){return this.isScalar(e)?this.applyHash(e,t):Array.isArray(e)?this.calculateList(e,t):this.calculateMap(e,t)}calculateMap(e,t){if(Object.keys(e).length===1&&typeof e[N]=="string")return e[N];const r=Object.keys(e).sort().map(i=>{const s=e[i];if(hi.has(i))return[i,s];const o=this.calculateCleaned(s,t);return t?[i,{[N]:o}]:Promise.resolve(o).then(a=>[i,{[N]:a}])});return t?this.applyHash(Object.fromEntries(r),!0):Promise.all(r).then(i=>this.applyHash(Object.fromEntries(i),!1))}calculateList(e,t){let r,i=0;e.length>0&&this.isPreviousControl(e[0])?(r=this.previousBlueId(e[0]),i=1):r=this.applyHash({$list:"empty"},t);for(let s=i;s<e.length;s+=1){const o=r,a=this.calculateCleaned(e[s],t);t?r=this.applyHash(this.listCons(o,a),!0):r=Promise.all([o,a]).then(([l,c])=>this.applyHash(this.listCons(l,c),!1))}return r}listCons(e,t){return{$listCons:{elem:{[N]:t},prev:{[N]:e}}}}cleanRoot(e){if(e==null)throw new Error("Root null is not valid BlueId input.");if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.cleanRoot(r));const t={};for(const[r,i]of Object.entries(e)){const s=this.cleanObjectField(i);s!==void 0&&(t[r]=s)}return t}cleanObjectField(e){if(e==null)return;if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.cleanRoot(r));const t={};for(const[r,i]of Object.entries(e)){const s=this.cleanObjectField(i);s!==void 0&&(t[r]=s)}return Object.keys(t).length===0?void 0:t}isPreviousControl(e){if(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length!==1)return!1;const t=e[ce];return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length===1&&typeof t[N]=="string"}previousBlueId(e){return e[ce][N]}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}isScalar(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}}const S={NAME:"name",DESCRIPTION:"description",TYPE:"type",BLUE_ID:"blue_id",KEY_TYPE:"key_type",VALUE_TYPE:"value_type",ITEM_TYPE:"item_type",VALUE:"value",PROPERTIES:"properties",BLUE:"blue",ITEMS:"items"};class C{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([S.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([S.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),i=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(i)}static textNode(e){return new h().setType(new h().setBlueId(k)).setValue(e)}static integerNode(e){const t=e instanceof R?e:new R(e.toString());return new h().setType(new h().setBlueId(H)).setValue(t)}static doubleNode(e){const t=e instanceof V?e:new V(e.toString());return new h().setType(new h().setBlueId(q)).setValue(t)}static booleanNode(e){return new h().setType(new h().setBlueId(Y)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const i of Object.values(S)){const s=u.isNonNullable(this.getFieldValue(e,i));if(t.has(i)){if(!s)return!1}else if(!r.has(i)){if(s)return!1}}return!0}static getFieldValue(e,t){switch(t){case S.NAME:return e.getName();case S.TYPE:return e.getType();case S.VALUE:return e.getValue();case S.DESCRIPTION:return e.getDescription();case S.PROPERTIES:return e.getProperties();case S.BLUE:return e.getBlue();case S.ITEMS:return e.getItems();case S.KEY_TYPE:return e.getKeyType();case S.VALUE_TYPE:return e.getValueType();case S.ITEM_TYPE:return e.getItemType();case S.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}const gt="$previous",Re="$pos",bt="$empty";class b{static getMergePolicy(e,t){const r=this.getMergePolicyValue(e);return r!==void 0?r:(t===void 0?void 0:this.getMergePolicyValue(t))??"positional"}static getMergePolicyValue(e){const t=e.getMergePolicy();if(t==="append-only"||t==="positional")return t;const r=e.getProperties()?.[y.OBJECT_MERGE_POLICY]?.getValue();if(r==="append-only"||r==="positional")return r}static hasListControlItems(e){return e?.some(t=>this.hasPreviousProperty(t)||this.hasPositionProperty(t))??!1}static hasAnyListControl(e){const t=e.getItems();return this.hasListControlItems(t)||t?.some(r=>this.hasAnyListControl(r))?!0:Object.values(e.getProperties()??{}).some(r=>this.hasAnyListControl(r))||this.hasAnyListControlChild(e.getType())||this.hasAnyListControlChild(e.getItemType())||this.hasAnyListControlChild(e.getKeyType())||this.hasAnyListControlChild(e.getValueType())||this.hasAnyListControlChild(e.getBlue())}static hasPositionControl(e){const t=e.getItems();return t?.some(r=>this.hasPositionProperty(r))||t?.some(r=>this.hasPositionControl(r))?!0:Object.values(e.getProperties()??{}).some(r=>this.hasPositionControl(r))||this.hasPositionControlChild(e.getType())||this.hasPositionControlChild(e.getItemType())||this.hasPositionControlChild(e.getKeyType())||this.hasPositionControlChild(e.getValueType())||this.hasPositionControlChild(e.getBlue())}static hasPreviousProperty(e){return e.getPreviousBlueId()!==void 0||Object.prototype.hasOwnProperty.call(e.getProperties()??{},gt)}static hasPositionProperty(e){return e.getPosition()!==void 0||Object.prototype.hasOwnProperty.call(e.getProperties()??{},Re)}static hasEmptyProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},bt)}static isEmptyItem(e){const t=e.getProperties(),r=t?.[bt];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&C.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&C.hasFieldsAndMayHaveFields(r,new Set([S.VALUE]),new Set([S.TYPE]))&&r.getValue()===!0}static isPreviousItem(e){if(e.getPreviousBlueId()!==void 0)return e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0;const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&C.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&C.hasBlueIdOnly(t[gt])}static getPreviousBlueId(e){if(e.getPreviousBlueId()!==void 0)return e.getPreviousBlueId();if(this.isPreviousItem(e))return e.getProperties()?.[gt]?.getBlueId()}static createPreviousItem(e){return new h().setPreviousBlueId(e)}static readPosition(e){if(e.getPosition()!==void 0)return e.getPosition();const t=e.getProperties()?.[Re];if(t===void 0)return;if(!C.hasFieldsAndMayHaveFields(t,new Set([S.VALUE]),new Set([S.TYPE])))throw new Error("$pos must be a non-negative integer value.");const r=t.getValue(),i=r instanceof R?r.toNumber():typeof r=="number"?r:void 0;if(i===void 0||!Number.isInteger(i)||i<0)throw new Error("$pos must be a non-negative integer value.");return i}static createPositionedItem(e,t){return t.clone().setPosition(e)}static withoutPosition(e){const t=e.clone();t.setPosition(void 0);const r=t.getProperties();return r!==void 0&&(delete r[Re],Object.keys(r).length===0&&t.setProperties(void 0)),t}static hasPayloadAfterRemovingPosition(e){return!C.isEmptyNode(this.withoutPosition(e))}static isReplacementPayload(e){return u.isNonNullable(e.getValue())||u.isNonNullable(e.getItems())||u.isNonNullable(e.getBlueId())}static hasAnyListControlChild(e){return e!==void 0&&this.hasAnyListControl(e)}static hasPositionControlChild(e){return e!==void 0&&this.hasPositionControl(e)}}class j{constructor(e={emitListControls:!0}){this.options=e}reverse(e){const t=new h;return this.reverseNode(t,e,void 0,!0),t}reverseToCanonicalOverlay(e){const t=new h;return this.reverseCanonicalNode(t,e,e.getType()),t}static calculateHashMinimalBlueId(e){return E.calculateBlueIdSync(this.toHashMinimalNode(e))}static calculateHashMinimalListBlueId(e){return E.calculateBlueIdSync(e.map(t=>this.toHashMinimalNode(t)))}static toHashMinimalNode(e){return new j({emitListControls:!1}).reverse(e)}reverseCanonicalNode(e,t,r){if(t.getReferenceBlueId()!==void 0&&r?.getReferenceBlueId()===t.getReferenceBlueId())return;const i=t.getValue();i!=null&&(r===void 0||r.getValue()===void 0||r.getValue()===null||!this.sameScalarValue(i,r.getValue()))&&e.setValue(i),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getType(),(l,c)=>l.setType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getItemType(),(l,c)=>l.setItemType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getKeyType(),(l,c)=>l.setKeyType(c)),this.setCanonicalTypeIfDifferent(t,r,e,l=>l.getValueType(),(l,c)=>l.setValueType(c)),this.preserveCanonicalPayloadTypeForMetadataOverride(t,e),t.getName()!==void 0&&(r===void 0||t.getName()!==r.getName())&&e.setName(t.getName()),t.getDescription()!==void 0&&(r===void 0||t.getDescription()!==r.getDescription())&&e.setDescription(t.getDescription()),this.isReferenceOnly(t)&&(r===void 0||t.getReferenceBlueId()!==r.getReferenceBlueId())&&e.setReferenceBlueId(t.getReferenceBlueId()),t.getMergePolicy()!==void 0&&(r===void 0||t.getMergePolicy()!==r.getMergePolicy())&&e.setMergePolicy(t.getMergePolicy()),t.getSchema()!==void 0&&!this.sameSchema(t.getSchema(),r?.getSchema())&&e.setSchema(t.getSchema()?.clone());const s=t.getContractsNode();if(s!==void 0){const l=r?.getContractsNode();if(!this.sameNodeBlueId(s,l)){const c=new h;this.reverseCanonicalNode(c,s,l),this.isCanonicalEmptyNode(c)||e.setContractsNode(c)}}const o=t.getItems();o!==void 0&&e.setItems(o.map(l=>{const c=new h;return this.reverseCanonicalNode(c,l,void 0),this.isCanonicalEmptyNode(c)?this.emptyPlaceholder():c}));const a=t.getProperties();if(a!==void 0){const l={};for(const[c,d]of Object.entries(a)){if(c===y.OBJECT_CONTRACTS)continue;const p=r?.getProperties()?.[c];if(this.sameNodeBlueId(d,p))continue;const f=new h;this.reverseCanonicalNode(f,d,p),this.isCanonicalEmptyNode(f)||(l[c]=f)}Object.keys(l).length>0&&e.setProperties(l)}}setCanonicalTypeIfDifferent(e,t,r,i,s){const o=i(e),a=t===void 0?void 0:i(t);o!==void 0&&(a===void 0||a.getReferenceBlueId()!==o.getReferenceBlueId())&&s(r,new h().setReferenceBlueId(o.getReferenceBlueId()))}preserveCanonicalPayloadTypeForMetadataOverride(e,t){if(t.getType()!==void 0||e.getType()===void 0||t.getItemType()===void 0&&t.getKeyType()===void 0&&t.getValueType()===void 0)return;const r=e.getType(),i=r?.getReferenceBlueId();t.setType(i===void 0?r?.clone():new h().setReferenceBlueId(i))}sameSchema(e,t){return e===t?!0:e===void 0||t===void 0?!1:E.calculateBlueIdSync(new h().setSchema(e))===E.calculateBlueIdSync(new h().setSchema(t))}sameNodeBlueId(e,t){return e===t?!0:e===void 0||t===void 0?!1:E.calculateBlueIdWithResolvedBlueIdMetadataSync(e)===E.calculateBlueIdWithResolvedBlueIdMetadataSync(t)}sameScalarValue(e,t){return e!==null&&t!==null&&typeof e=="object"&&typeof t=="object"&&"eq"in e&&typeof e.eq=="function"?!!e.eq(t):e===t}emptyPlaceholder(){return new h().addProperty("$empty",new h().setValue(!0))}isReferenceOnly(e){return e.getReferenceBlueId()!==void 0&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}isCanonicalEmptyNode(e){return e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&(e.getValue()===void 0||e.getValue()===null)&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}reverseNode(e,t,r,i){const s=this.getEffectiveFromType(r,t);!i&&this.isIdenticalToType(t,s)||(this.reverseBasicProperties(e,t,s,i),this.reverseTypeReferences(e,t,r,s),this.reverseItems(e,t,s),this.reverseProperties(e,t,s))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r,i){const s=t.getValue();u.isNonNullable(s)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(s),u.isNonNullable(t.getName())&&(i||u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(i||u.isNullable(r)||t.getDescription()!==r.getDescription())&&e.setDescription(t.getDescription()),u.isNonNullable(t.getBlueId())&&(u.isNullable(r)||t.getBlueId()!==r.getBlueId())&&e.setBlueId(t.getBlueId())}reverseTypeReferences(e,t,r,i){const s=(o,a,l)=>{const c=o(t),d=l?o(l):void 0;u.isNonNullable(c)&&!this.areTypeReferencesEquivalent(c,d)&&a(e,this.toMinimalTypeReference(c))};s(o=>o.getType(),(o,a)=>o.setType(a),r),s(o=>o.getItemType(),(o,a)=>o.setItemType(a),i),s(o=>o.getKeyType(),(o,a)=>o.setKeyType(a),i),s(o=>o.getValueType(),(o,a)=>o.setValueType(a),i)}areTypeReferencesEquivalent(e,t){if(u.isNullable(t))return!1;const r=e.getBlueId(),i=t.getBlueId();return u.isNonNullable(r)||u.isNonNullable(i)?u.isNonNullable(r)&&u.isNonNullable(i)&&r===i:j.calculateHashMinimalBlueId(e)===j.calculateHashMinimalBlueId(t)}toMinimalTypeReference(e){const t=e.getBlueId();if(u.isNonNullable(t))return new h().setBlueId(t);const r=new h;return this.reverseNode(r,e,void 0,!0),C.isEmptyNode(r)?e.clone():r}reverseItems(e,t,r){const i=t.getItems();if(u.isNullable(i))return;const s=r?.getItems();if(i.length===0){(u.isNullable(s)||s.length>0)&&e.setItems([]);return}if(u.isNonNullable(s)&&i.length===s.length&&i.every((a,l)=>j.calculateHashMinimalBlueId(a)===j.calculateHashMinimalBlueId(s[l])))return;const o=this.options.emitListControls!==!1&&u.isNonNullable(s)&&s.length>0?this.reverseInheritedItems(t,r):this.reverseFullItems(i);o.length>0&&e.setItems(o)}reverseInheritedItems(e,t){const r=e.getItems()??[],i=t.getItems()??[];if(r.length<i.length)throw new Error(`Resolved list has fewer items (${r.length}) than inherited list (${i.length}).`);const s=b.getMergePolicy(e,t),o=[];for(let c=0;c<i.length;c++)j.calculateHashMinimalBlueId(r[c])!==j.calculateHashMinimalBlueId(i[c])&&o.push(c);if(o.length>0&&s==="append-only")throw new Error("append-only list cannot be minimized as a non-prefix mutation.");const a=j.calculateHashMinimalListBlueId(i),l=[b.createPreviousItem(a)];for(const c of o){const d=new h;this.reverseNode(d,r[c],i[c],!1);const p=C.isEmptyNode(d)?r[c].clone():d;l.push(b.createPositionedItem(c,p))}for(let c=i.length;c<r.length;c++){const d=new h;this.reverseNode(d,r[c],void 0,!1),l.push(d)}return l.length===1?[]:l}reverseFullItems(e){const t=[];for(let r=0;r<e.length;r++){const i=new h;this.reverseNode(i,e[r],void 0,!1),t.push(i)}return t}reverseProperties(e,t,r){const i=t.getProperties();if(u.isNullable(i))return;const s={};for(const[o,a]of Object.entries(i)){const l=this.getInheritedProperty(o,r),c=new h;this.reverseNode(c,a,l,!1),C.isEmptyNode(c)||(s[o]=c)}Object.keys(s).length>0&&e.setProperties(s)}getInheritedProperty(e,t){return t?.getProperties()?.[e]}getEffectiveFromType(e,t){const r=this.createOwnTypeOverlay(t.getType());return u.isNullable(e)?r:u.isNullable(r)?e:this.mergeNodes(e,r)}createOwnTypeOverlay(e){if(u.isNullable(e))return;const t=e.cloneShallow().setName(void 0).setDescription(void 0).setType(void 0).setBlueId(void 0);if(!C.isEmptyNode(t))return t}mergeNodes(e,t){const r=e.clone(),i=t.getValue();u.isNonNullable(i)&&r.setValue(i);const s=t.getType();u.isNonNullable(s)&&r.setType(s.clone());const o=t.getItemType();u.isNonNullable(o)&&r.setItemType(o.clone());const a=t.getKeyType();u.isNonNullable(a)&&r.setKeyType(a.clone());const l=t.getValueType();u.isNonNullable(l)&&r.setValueType(l.clone());const c=t.getProperties();if(u.isNonNullable(c)){const p=r.getProperties()||{};for(const[f,I]of Object.entries(c)){const v=p[f];p[f]=v===void 0?I.clone():this.mergeNodes(v,I)}r.setProperties(p)}const d=t.getItems();return u.isNonNullable(d)&&r.setItems(d.map(p=>p.clone())),r}}class Et{mergeReverser=new j;hashMergeReverser=new j({emitListControls:!1});minimize(e){return this.minimizeResolved(e)}minimizeResolved(e){return this.mergeReverser.reverse(e)}minimizeResolvedForHash(e){return this.hashMergeReverser.reverse(e)}}class Ne extends Error{code;category;details;constructor(e,t,r,i){super(t),this.code=e,this.category=i,this.details=r&&r.length>0?r:[],this.name="BlueError"}}function pi(n){return fi(n)?n.category:void 0}function fi(n){return typeof n=="object"&&n!==null&&typeof n.category=="string"}const G={AMBIGUOUS_BLUE_ID_PAYLOAD:"AMBIGUOUS_BLUE_ID_PAYLOAD",INVALID_STORAGE_SHAPE:"INVALID_STORAGE_SHAPE",REPO_UNKNOWN_REPO_BLUE_ID:"REPO_UNKNOWN_REPO_BLUE_ID",REPO_UNREPRESENTABLE_IN_TARGET_VERSION:"REPO_UNREPRESENTABLE_IN_TARGET_VERSION",INVALID_BLUE_CONTEXT_REPOSITORIES:"INVALID_BLUE_CONTEXT_REPOSITORIES",INVALID_REPOSITORY_POINTER:"INVALID_REPOSITORY_POINTER"};class Pe{static RESERVED_PROPERTY_KEYS=new Set([y.OBJECT_SCHEMA,y.OBJECT_MERGE_POLICY,y.OBJECT_CONTRACTS]);static INTERNAL_PROPERTIES_KEY="properties";static validateStorageShape(e){this.validateNode(e,[],{insideItems:!1})}static validateStorageListShape(e){e.forEach((t,r)=>{this.validateNode(t,[String(r)],{insideItems:!0,itemIndex:r})})}static validateListControlShape(e){e.forEach((t,r)=>{this.validateListControlNode(t,[String(r)],r)})}static validateListControlNode(e,t,r){r!==void 0&&this.validateListControlItem(e,t,r),this.validateListControlChild(e.getType(),[...t,"type"]),this.validateListControlChild(e.getItemType(),[...t,"itemType"]),this.validateListControlChild(e.getKeyType(),[...t,"keyType"]),this.validateListControlChild(e.getValueType(),[...t,"valueType"]),this.validateListControlChild(e.getBlue(),[...t,"blue"]),e.getItems()?.forEach((s,o)=>{this.validateListControlNode(s,[...t,"items",String(o)],o)});const i=e.getProperties();if(i!==void 0)for(const[s,o]of Object.entries(i))this.validateListControlNode(o,[...t,s])}static validateNode(e,t,r){r.insideItems&&this.validateListControlItem(e,t,r.itemIndex??0);const i=e.getReferenceBlueId();if(i!==void 0&&!C.hasBlueIdOnly(e))if(r.insideItems&&b.hasPositionProperty(e)&&C.hasBlueIdOnly(b.withoutPosition(e)))b.readPosition(e);else{const p=this.toPointer(t);throw new Ne(G.AMBIGUOUS_BLUE_ID_PAYLOAD,`Ambiguous blueId plus payload at ${p}. Use exact { blueId } for references or remove blueId from payload content.`,[{code:G.AMBIGUOUS_BLUE_ID_PAYLOAD,message:"A storage or authoring node cannot combine blueId with payload.",locationPath:t,context:{blueId:i}}])}const s=this.getChildProperties(e,t,r),o=e.getValue()!==void 0,a=e.getItems()!==void 0,l=Object.keys(s).length>0;o&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value and items payloads."),o&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value payload with object child fields."),a&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine items payload with object child fields."),this.validateChild(e.getType(),[...t,"type"]),this.validateChild(e.getItemType(),[...t,"itemType"]),this.validateChild(e.getKeyType(),[...t,"keyType"]),this.validateChild(e.getValueType(),[...t,"valueType"]),this.validateChild(e.getBlue(),[...t,"blue"]),e.getItems()?.forEach((d,p)=>{this.validateNode(d,[...t,"items",String(p)],{insideItems:!0,itemIndex:p})});const c=e.getProperties();if(c!==void 0)for(const[d,p]of Object.entries(c))this.validateNode(p,[...t,d],{insideItems:!1})}static validateListControlItem(e,t,r){if(b.hasEmptyProperty(e)&&(b.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $previous."),b.hasPositionProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $pos."),b.isEmptyItem(e)||this.throwInvalidStorageShape(t,"$empty list content must be exactly { $empty: true }.")),b.hasPreviousProperty(e)&&(r!==0&&this.throwInvalidStorageShape(t,"$previous list control is allowed only as the first item."),b.isPreviousItem(e)||this.throwInvalidStorageShape(t,"$previous list control must be exactly { $previous: { blueId: <id> } }.")),b.hasPositionProperty(e)){b.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$pos cannot be combined with $previous.");try{b.readPosition(e)}catch(i){this.throwInvalidStorageShape([...t,Re],i instanceof Error?i.message:"$pos must be a non-negative integer value.")}b.hasPayloadAfterRemovingPosition(e)||this.throwInvalidStorageShape(t,"$pos list control must include an item payload.")}}static validateChild(e,t){e!==void 0&&this.validateNode(e,t,{insideItems:!1})}static validateListControlChild(e,t){e!==void 0&&this.validateListControlNode(e,t)}static getChildProperties(e,t,r){const i=e.getProperties()??{};return Object.prototype.hasOwnProperty.call(i,this.INTERNAL_PROPERTIES_KEY)&&this.throwInvalidStorageShape([...t,this.INTERNAL_PROPERTIES_KEY],"The document-level properties key is not part of the Blue language."),Object.fromEntries(Object.entries(i).filter(([s])=>!this.RESERVED_PROPERTY_KEYS.has(s)&&!(r.insideItems&&(s===Re||s===bt))))}static throwInvalidStorageShape(e,t){const r=this.toPointer(e);throw new Ne(G.INVALID_STORAGE_SHAPE,`${t} at ${r}`,[{code:G.INVALID_STORAGE_SHAPE,message:t,locationPath:e}])}static toPointer(e){return e.length===0?"/":`/${e.map(t=>t.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`}}class B{static get(e,t="official"){const{strategy:r}=this.normalizeOptions(t),i=e.getValue(),s=this.handleValue(i);if(s!==void 0&&r==="simple")return s;const o=e.getItems()?.map(T=>B.get(T,r));if(o!==void 0&&r==="simple")return o;const a=e.getName(),l=e.getDescription();if(r==="original"&&a===void 0&&l===void 0){if(s!==void 0)return s;if(o!==void 0)return o}const c={};a!==void 0&&(c[ae]=a),l!==void 0&&(c[le]=l);const d=e.getType();if(r==="official"&&i!==void 0&&d===void 0){const T=this.inferTypeBlueId(i);T!==null&&(c[F]={[N]:T})}else d!==void 0&&(c[F]=B.get(d,r));const p=e.getItemType();p!==void 0&&(c[me]=B.get(p,r));const f=e.getKeyType();f!==void 0&&(c[ye]=B.get(f,r));const I=e.getValueType();I!==void 0&&(c[ge]=B.get(I,r));const v=e.getMergePolicy();v!==void 0&&(c[y.OBJECT_MERGE_POLICY]=v),s!==void 0&&(c[ee]=s),o!==void 0&&(c[Te]=o);const P=e.getBlueId();P!==void 0&&(c[N]=P);const D=e.getBlue();D!==void 0&&(c[rt]=B.get(D,r));const U=e.getPreviousBlueId();U!==void 0&&(c[ce]={[N]:U});const Z=e.getPosition();Z!==void 0&&(c[it]=Z);const J=e.getSchema();if(J!==void 0){const T={};for(const[pt,jr]of J.entries())T[pt]=B.get(jr,r);const z=J.getEnum();z!==void 0&&(T.enum=z.map(pt=>B.get(pt,r))),c[y.OBJECT_SCHEMA]=T}const we=e.getContractsNode();we!==void 0&&(c[y.OBJECT_CONTRACTS]=B.get(we,r));const w=e.getProperties();return w!==void 0&&Object.entries(w).forEach(([T,z])=>{c[T]=B.get(z,r)}),c}static handleValue(e){if(x(e)){if(W(e)){const t=new fe(Number.MIN_SAFE_INTEGER.toString()),r=new fe(Number.MAX_SAFE_INTEGER.toString());if(e.lt(t)||e.gt(r))return e.toString()}return e.toNumber()}return e}static inferTypeBlueId(e){return typeof e=="string"?k:x(e)?W(e)?H:q:typeof e=="boolean"?Y:null}static normalizeOptions(e){return typeof e=="string"?{strategy:e}:{strategy:e.strategy??"official"}}}class M{static transform(e,t){const r=t(e.clone()),i=r.getType();i!==void 0&&r.setType(M.transform(i,t));const s=r.getItemType();s!==void 0&&r.setItemType(M.transform(s,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(M.transform(o,t));const a=r.getValueType();a!==void 0&&r.setValueType(M.transform(a,t));const l=r.getSchema();if(l!==void 0){const p=l.clone();for(const[I,v]of p.entries())p.set(I,M.transform(v,t));const f=p.getEnum();f!==void 0&&p.setEnum(f.map(I=>M.transform(I,t))),r.setSchema(p)}const c=r.getItems();if(c!==void 0){const p=c.map(f=>M.transform(f,t));r.setItems(p)}const d=r.getProperties();if(d!==void 0){const p=Object.keys(d).reduce((f,I)=>(f[I]=M.transform(d[I],t),f),{});r.setProperties(p)}return r}}const It=Symbol.for("zod-schema-annotations");function mi(){if(typeof globalThis<"u")return globalThis;if(typeof global<"u")return global;if(typeof window<"u")return window;if(typeof self<"u")return self;throw new Error("Unable to locate global object")}function nr(){const n=mi();return It in n||(n[It]=new WeakMap),n[It]}function $e(n,e){const t=nr(),r=t.get(n)||{};return t.set(n,{...r,...e}),n}const se=n=>nr().get(n),or=n=>e=>{const t=se(e);return $e(e,{...t,blueDescription:n})},ar=n=>{const e=se(n);return u.isNonNullable(e)&&ve.isString(e.blueDescription)?e.blueDescription:null},yi=n=>or(n)(m.z.string().optional()),gi=m.z.union([m.z.string(),m.z.boolean()]),lr=n=>e=>{const t=se(e);return $e(e,{...t,blueId:n})},cr=n=>{const e=se(n),t=gi.safeParse(e?.blueId);return t.success?t.data:null},Ii=n=>lr(n??!0)(m.z.string()),ur=n=>e=>{const t=se(e);return $e(e,{...t,blueName:n})},dr=n=>{const e=se(n);return u.isNonNullable(e)&&ve.isString(e.blueName)?e.blueName:null},vi=n=>{const e=m.z.string().optional();return ur(n)(e)},hr=()=>n=>{const e=se(n);return $e(n,{...e,blueNode:!0})},pr=n=>{const e=se(n);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},Dt=n=>!!pr(n),Ti=()=>{const n=m.z.instanceof(h);return hr()(n)},Bi=m.z.object({value:m.z.array(m.z.string()).optional(),defaultValue:m.z.string().optional()}),fr=n=>{const e=se(n),t=Bi.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},Pi=n=>e=>{const t=se(e),r=typeof n=="string"?{value:[n]}:n;return $e(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class Le{static resolveBlueId(e){const t=fr(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const i=t.value?.[0];return u.isNonNullable(i)?i:Le.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}const mr=n=>{const e=String(n._def.typeName);return e==="ZodOptional"||e==="ZodNullable"||e==="ZodReadonly"||e==="ZodBranded"||e==="ZodEffects"||e==="ZodLazy"},bi=n=>{const e=String(n._def.typeName);return e==="ZodString"||e==="ZodNumber"||e==="ZodBoolean"||e==="ZodBigInt"};class Q{static isTypeOf(e,t,r){const i=Le.resolveBlueId(t),s=e.getType()?.getBlueId();if(u.isNullable(i)||u.isNullable(s))return!1;const o=r?.blueIdMapper?.toCurrentBlueId(i)??i,a=r?.blueIdMapper?.toCurrentBlueId(s)??s;if(o===a)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const l=r.typeSchemaResolver.resolveSchema(e);return Q.checkSchemaExtension(l,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const i=Q.unwrapSchema(e),s=Q.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(i,s):!1}static unwrapSchema(e){if(Dt(e))return e;const t=String(e._def.typeName);return t==="ZodEffects"?Q.unwrapSchema(e.innerType()):t==="ZodLazy"?Q.unwrapSchema(e.schema):mr(e)?Q.unwrapSchema(e.unwrap()):e}}const yr=Symbol("blue.subtypeCache");function Ei(n,e){return n[yr]=e,n}function jt(n,e){const t=n.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(ie.includes(r)){const s=ct[r];return new h().setBlueId(r).setName(s)}const i=e.fetchByBlueId(r);if(!i||i.length===0)return;if(i.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return i[0].cloneShallow().setBlueId(r)}return t}function A(n,e,t){const r=xe(n),i=xe(e),s=t[yr],o=`${r}|${i}`,a=s?.get(o);if(a!==void 0)return a;const l=Ni(n,e,t,r,i);return s?.set(o,l),l}function xe(n){const e=n.getReferenceBlueId();return e!==void 0?e:E.calculateBlueIdSync(de(n))}function de(n){if(!gr(n))return n;const e=n.cloneShallow();e.getReferenceBlueId()!==void 0&&!C.hasBlueIdOnly(e)&&e.setReferenceBlueId(void 0);const t=e.getType();t!==void 0&&e.setType(de(t));const r=e.getItemType();r!==void 0&&e.setItemType(de(r));const i=e.getKeyType();i!==void 0&&e.setKeyType(de(i));const s=e.getValueType();s!==void 0&&e.setValueType(de(s));const o=e.getBlue();o!==void 0&&e.setBlue(de(o));const a=e.getItems();a!==void 0&&e.setItems(a.map(c=>de(c)));const l=e.getProperties();return l!==void 0&&e.setProperties(Object.fromEntries(Object.entries(l).map(([c,d])=>[c,de(d)]))),e}function gr(n){return n.getReferenceBlueId()!==void 0&&!C.hasBlueIdOnly(n)?!0:[n.getType(),n.getItemType(),n.getKeyType(),n.getValueType(),n.getBlue(),...n.getItems()??[],...Object.values(n.getProperties()??{})].some(t=>t!==void 0&&gr(t))}function Ni(n,e,t,r,i){if(r===i)return!0;if(wi(e,i)&&Ir(n))return!1;if(r&&ie.includes(r)){let l=e;for(;l!==void 0;){if(xe(l)===r)return!0;l=jt(l,t)}return!1}let s=n;const o=n.getBlueId();if(o){const l=t.fetchByBlueId(o);l&&l.length===1&&(s=l[0].cloneShallow().setBlueId(o))}let a=s;for(;a!==void 0;){if(xe(a)===i)return!0;a=jt(a,t)}return!1}function wi(n,e){return ie.includes(e)||Si(n)}function Ir(n){const e=n.getType();return n.getName()===void 0&&n.getDescription()===void 0&&n.getReferenceBlueId()===void 0&&e!==void 0&&n.getItemType()===void 0&&n.getKeyType()===void 0&&n.getValueType()===void 0&&n.getValue()===void 0&&n.getItems()===void 0&&n.getProperties()===void 0&&n.getContractsNode()===void 0&&n.getSchema()===void 0&&n.getMergePolicy()===void 0&&n.getPreviousBlueId()===void 0&&n.getPosition()===void 0&&n.getBlue()===void 0&&ie.includes(xe(e))}function Si(n){const e=n.getName();return e!==void 0&&Object.prototype.hasOwnProperty.call(lt,e)&&n.getDescription()===void 0&&n.getType()===void 0&&n.getItemType()===void 0&&n.getKeyType()===void 0&&n.getValueType()===void 0&&n.getValue()===void 0&&n.getItems()===void 0&&n.getProperties()===void 0&&n.getContractsNode()===void 0&&n.getReferenceBlueId()===void 0&&n.getSchema()===void 0&&n.getMergePolicy()===void 0&&n.getPreviousBlueId()===void 0&&n.getPosition()===void 0&&n.getBlue()===void 0}function Ci(n,e){return At.some(t=>{const r=new h().setBlueId(t);return A(n,r,e)})}function Ri(n,e){const t=new h().setBlueId(k);return A(n,t,e)}function Ai(n,e){const t=new h().setBlueId(H);return A(n,t,e)}function Oi(n,e){const t=new h().setBlueId(q);return A(n,t,e)}function Mi(n,e){const t=new h().setBlueId(Y);return A(n,t,e)}function Ge(n,e){const t=new h().setBlueId(ot);return A(n,t,e)}function He(n,e){const t=new h().setBlueId(at);return A(n,t,e)}function Vi(n,e){return nt.some(t=>{const r=new h().setName(t);return A(n,r,e)})}function Di(n,e){for(const t of nt){const r=new h().setName(t);if(A(n,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${n.getName()||"unknown"}".`)}class vr{blueIdMap=new Map;nodeProvider;constructor(e=[],t){this.nodeProvider=t?.nodeProvider??null,this.registerSchemas(e)}registerSchemas(e){for(const t of e)this.registerSchema(t)}registerSchema(e){const t=Le.resolveBlueId(e);if(u.isNonNullable(t)){if(this.blueIdMap.has(t))throw new Error(`Duplicate BlueId value: ${t}`);this.blueIdMap.set(t,e)}}setNodeProvider(e){this.nodeProvider=e}resolveSchema(e){const t=this.getEffectiveBlueId(e);return u.isNullable(t)?null:this.blueIdMap.get(t)}isSchemaExtendedFrom(e,t){if(u.isNullable(e))return!1;const r=this.getBlueIdForSchema(e),i=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(i))return!1;if(r===i)return!0;if(u.isNonNullable(this.nodeProvider))try{const s=new h().setBlueId(r),o=new h().setBlueId(i);if(A(s,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=Le.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,i]of this.blueIdMap)if(i===e||i._def===e._def)return r;return null}getEffectiveBlueId(e){const t=e.getType();return u.isNonNullable(t)&&u.isNonNullable(t.getBlueId())?t.getBlueId():u.isNonNullable(t)?E.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}class ue{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function Lt(n){return new class extends ue{fetchByBlueId(e){return n(e)}}}class Ce extends ue{nodeProviders;constructor(e){super(),this.nodeProviders=e}fetchByBlueId(e){for(const t of this.nodeProviders){const r=t.fetchByBlueId(e);if(r&&r.length>0)return r}return[]}fetchFirstByBlueId(e){for(const t of this.nodeProviders){const r=t.fetchFirstByBlueId(e);if(r)return r}return null}getNodeProviders(){return this.nodeProviders}}const vt=Be.types.float.options,Li={...vt,construct:n=>{const e=n.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new V(e);if(vt.construct)return vt.construct(n)}},xi=new Be.Type("tag:yaml.org,2002:float",Li),Tt=Be.types.int.options,_i={...Tt,construct:n=>{let e=n;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new R(e);if(Tt.construct)return Tt.construct(n)}},Fi=new Be.Type("tag:yaml.org,2002:int",_i),Tr=Be.CORE_SCHEMA.extend({implicit:[xi,Fi]}),he=n=>{const e=Be.load(n,{schema:Tr});return e===void 0?void 0:e},Br=n=>Be.dump(n,{schema:Tr,replacer:(e,t)=>{if(x(t)){if(W(t)){const r=new fe(Number.MIN_SAFE_INTEGER.toString()),i=new fe(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(i))return t.toString()}return t.toNumber()}return t}}),Pr=`- type:
2
- blueId: 27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo
3
- mappings:
4
- Text: GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC
5
- Double: 9eWaHYz2vKrFofdHTHAizNNu8xP6QE3WQ5y7DGrGZvyJ
6
- Integer: E2LM6qgzWG9ttagq2xTmiZkgYEAgkYedFCmU9v7NnVEq
7
- Boolean: AwvXD961fmnmqcSQhjMA7r15HpVh39cefb6ZTyUz2Fm2
8
- List: 8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF
9
- Dictionary: Efkz9D1ARMM7rU43w3rDNVqat1naS6qXKCqP4eHin3yG
10
- Contract: 6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF
11
- Json Patch Entry: 61W96XosAp3DrEC7PuqLYtmF2A6ETpqH6qF2DgYwDq4c
12
- Contract Execution Result: AMtAXPmvumgz1GxKUU9uv3ncXiKMENvqq8AaLvD5LXhv
13
- Channel: 4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5
14
- Handler: 7X46P3Q6FJrogqKrBXTALpqzkieyyiQeatnqLvWzAPXE
15
- Marker: 6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy
16
- Process Embedded: 8FVc8MPz6DcTMgcY3RXU6EBpGa9arWPJ141K2H86yi8Q
17
- Processing Initialized Marker: 6JjyUKoK7uJxA5NY9YhMaKJbXC6c9iHyx1khv4gaAq4Q
18
- Processing Terminated Marker: GBDBthfshBFr4GQKUU1fmy4GnPL7q2y3as4deUWpuBtu
19
- Channel Event Checkpoint: 9GEC24YbFG9hj4banjYh2oEnDpAob1wAPmhjuykJp8T1
20
- Type Generalization Policy: Fbenow6tanFHkWzKiDD8fGxminQswQ1FecMRakaCx2WX
21
- Type Generalization Rule: 7Vnmk8StjwY7e9mBNpACrn8oh3KZ7yQBjnXe5bLDWn4D
22
- Document Update Channel: Ac9LC5T7pHVa1TtkhMBjBRtxecShzvbe7ugUdXT1Mu2o
23
- Triggered Event Channel: 5HwxfbwRBCxG8xYpowWkCPC9akqUSKV7So2M4QHEmLsZ
24
- Lifecycle Event Channel: 2DXGQUiQBQ6CT89jwAsTAXaEPhLgiSXhKCGh9Q7Hv3MQ
25
- Embedded Node Channel: H6iUJp3GcLypsJDimMSVoxQQdxxuD8j6eqEUWWqCZ6i
26
- Document Update: 7HEaG1SpBdsbVHsrwRTZSZGmpJUWHfFoEzecYWpjo1vm
27
- Document Processing Initiated: Ht1o66MTLKf7JmnEiR27rRLSwdz8FUTgf2mGPNuLSDUL
28
- Document Processing Terminated: 4HWncQEQsdpk8zcXxYxgdtoXo5nKHxFPWeJfTscCbmeK
29
- Document Processing Fatal Error: AMZbj5tNGxjPrvaNyw56sfqcLSW2j1XmkncEYUVtgmVC
30
- - type:
31
- blueId: FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4
32
- `,Ui=`name: Transformation
33
- description: TODO`,zi=`name: Infer Basic Types For Untyped Values
34
- type:
35
- blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
36
- description: This transformation infers type details for Text, Integer, Number and Boolean.`,ji=`name: Replace Inline Types with BlueIds
37
- type:
38
- blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
39
- description: This transformation replaces`,$i=[Pr,Ui,zi,ji];class ki extends ue{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of $i){const t=he(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(s=>g.deserialize(s)),i=E.calculateBlueIdSync(r);this.blueIdToNodesMap.set(i,r)}else{const r=g.deserialize(t),i=E.calculateBlueIdSync(r);this.blueIdToNodesMap.set(i,[r])}}}}class Ae extends ue{static INSTANCE=new Ae;nodeProvider;constructor(){super(),this.nodeProvider=new ki}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class $t extends ue{constructor(e){super(),this.delegate=e}fetchByBlueId(e){let t;try{t=K.requireBlueIdOrCyclicMember(e,"provider.fetchByBlueId")}catch{return this.delegate.fetchByBlueId(e)}const r=this.delegate.fetchByBlueId(e);if(r===null||r.length===0||t.includes("#"))return r;const i=r.length===1?E.calculateBlueIdSync(this.contentWithoutRootIdentity(r[0])):E.calculateBlueIdSync(r.map(s=>this.contentWithoutRootIdentity(s)));if(i!==t){if(this.verifyCyclicSetContent(t,r))return r;throw new Error(`Provider returned content with BlueId ${i} for requested BlueId ${t}.`)}return r}contentWithoutRootIdentity(e){const t=e.clone();return t.getReferenceBlueId()!==void 0&&!this.isReferenceOnly(t)&&t.setReferenceBlueId(void 0),t}isReferenceOnly(e){return e.getReferenceBlueId()!==void 0&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&Object.keys(e.getProperties()??{}).length===0&&e.getContractsNode()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}verifyCyclicSetContent(e,t){if(t.length===0)return!1;const r=t.map(s=>{const o=s.clone();return this.rewriteCyclicMemberReferences(o,e),o});if(!r.some(s=>this.hasThisReference(s)))return!1;try{return E.calculateBlueIdAllowingCyclicPlaceholdersSync(r)===e}catch{return!1}}rewriteCyclicMemberReferences(e,t){const r=e.getReferenceBlueId();r?.startsWith(`${t}#`)&&e.setReferenceBlueId(`this#${r.slice(t.length+1)}`),this.childrenOf(e).forEach(i=>this.rewriteCyclicMemberReferences(i,t))}hasThisReference(e){return e.getReferenceBlueId()?.startsWith("this#")?!0:this.childrenOf(e).some(r=>this.hasThisReference(r))}childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),e.getContractsNode(),...e.getSchema()?.entries().map(([,t])=>t)??[],...e.getSchema()?.getEnum()??[],...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}const br=Symbol.for("blue.repositoryBasedNodeProvider");class oe{static wrap(e){if(this.isAlreadyWrapped(e))return e;if(this.isUnverified(e))return new Ce([Ae.INSTANCE,e]);const t=[Ae.INSTANCE,new $t(e)];return new Ce(t)}static unverified(e){return new Bt(e)}static isUnverified(e){return e instanceof Bt||e[br]===!0?!0:e instanceof Ce&&e.getNodeProviders().some(t=>this.isUnverified(t))}static isAlreadyWrapped(e){return e instanceof Ce?e.getNodeProviders().some(t=>t===Ae.INSTANCE||t instanceof $t||t instanceof Bt):!1}}class Bt extends ue{constructor(e){super(),this.delegate=e}fetchByBlueId(e){return this.delegate.fetchByBlueId(e)}}class dt{}class Oe{static convert(e){const t=new et;return Oe.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const i=e.getProperties(),s=e.getItems(),o=i!==void 0&&Object.keys(i).length>0,a=s!==void 0&&s.length>0;if(!o&&!a){r.addPath(t===""?"/":t);return}if(i)for(const[l,c]of Object.entries(i)){const d=`${t}/${l}`;Oe.traverseNode(c,d,r)}if(s)for(let l=0;l<s.length;l++){const c=`${t}/${l}`;Oe.traverseNode(s[l],c,r)}}}function kt(n,e){const t=n.split(e),r=[...t].reverse().findIndex(s=>s!==""),i=r===-1?0:t.length-r;return t.slice(0,i)}class ke extends dt{allowedPaths;maxDepth;currentPath=[];constructor(e,t){super(),this.allowedPaths=e,this.maxDepth=t}shouldExtendPathSegment(e){if(this.currentPath.length>=this.maxDepth)return!1;const t=this.normalizePath(this.getCurrentFullPath()+"/"+e);return this.isAllowedPath(t)}shouldMergePathSegment(e){return this.shouldExtendPathSegment(e)}isAllowedPath(e){for(const t of this.allowedPaths)if(this.matchesAllowedPath(t,e))return!0;return!1}matchesAllowedPath(e,t){const r=kt(e,"/"),i=kt(t,"/");if(i.length>r.length)return!1;for(let s=1;s<i.length;s++)if(r[s]!=="*"&&r[s]!==i[s])return!1;return!0}enterPathSegment(e){this.currentPath.push(e)}exitPathSegment(){this.currentPath.length>0&&this.currentPath.pop()}getCurrentFullPath(){return"/"+this.currentPath.join("/")}normalizePath(e){return"/"+e.split("/").filter(t=>t!=="").join("/")}static withMaxDepth(e){const t=new et().setMaxDepth(e);for(let r=1;r<=e;r++){const i="/"+Array(r).fill("*").join("/");t.addPath(i)}return t.build()}static withSinglePath(e){return new et().addPath(e).build()}static fromNode(e){return Oe.convert(e)}}class et{allowedPaths=new Set;maxDepth=Number.MAX_SAFE_INTEGER;addPath(e){return this.allowedPaths.add(e),this}setMaxDepth(e){return this.maxDepth=e,this}build(){return new ke(this.allowedPaths,this.maxDepth)}}class re extends dt{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class _e extends dt{limits;constructor(e){super(),this.limits=e}shouldExtendPathSegment(e,t){return this.limits.every(r=>r.shouldExtendPathSegment(e,t))}shouldMergePathSegment(e,t){return this.limits.every(r=>r.shouldMergePathSegment(e,t))}enterPathSegment(e,t){this.limits.forEach(r=>{r.enterPathSegment(e,t)})}exitPathSegment(){this.limits.forEach(e=>{e.exitPathSegment()})}static of(...e){return new _e(e)}}const _=new re;class te extends h{completeness;sourceSemanticBlueId;constructor(e,t={}){super(e.getName()),this.completeness=t.completeness??"full",this.sourceSemanticBlueId=this.validateSourceSemanticBlueId(t.sourceSemanticBlueId),this.createFrom(e)}isResolved(){return!0}getMinimalNode(){if(this.completeness==="path-limited"){if(this.sourceSemanticBlueId!==void 0)return new h().setReferenceBlueId(this.sourceSemanticBlueId);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return new Et().minimizeResolved(this)}getMinimalBlueId(){if(this.completeness==="path-limited"){if(this.sourceSemanticBlueId!==void 0)return this.sourceSemanticBlueId;throw new Error("Cannot calculate minimal BlueId for a path-limited resolved node without a source semantic BlueId.")}const t=new Et().minimizeResolvedForHash(this);return E.calculateBlueIdSync(t)}clone(){const e=super.clone();return new te(e,this.getMetadata())}cloneShallow(){const e=super.cloneShallow();return new te(e,this.getMetadata())}getCompleteness(){return this.completeness}getSourceSemanticBlueId(){return this.sourceSemanticBlueId}setSourceSemanticBlueId(e){return this.sourceSemanticBlueId=this.validateSourceSemanticBlueId(e),this}validateSourceSemanticBlueId(e){if(e!==void 0){if(!K.isPotentialBlueId(e))throw new Error("sourceSemanticBlueId must be a valid BlueId.");return e}}getMetadata(){return{completeness:this.completeness,sourceSemanticBlueId:this.sourceSemanticBlueId}}createFrom(e){e.getName()!==this.getName()&&this.setName(e.getName()),this.setDescription(e.getDescription()).setType(e.getType()).setItemType(e.getItemType()).setKeyType(e.getKeyType()).setValueType(e.getValueType()).setItems(e.getItems()).setProperties(e.getProperties()).setContractsNode(e.getContractsNode()).setBlueId(e.getBlueId()).setSchema(e.getSchema()).setMergePolicy(e.getMergePolicy()).setPreviousBlueId(e.getPreviousBlueId()).setPosition(e.getPosition()).setBlue(e.getBlue()).setInlineValue(e.isInlineValue());const t=e.getValue();t!==void 0&&this.setValue(t)}}class qi{blue;constructor(e){this.blue=e}matchesType(e,t,r=_,i={}){if(this.isTypeOnlyMatcher(t)&&this.targetTypeReferenceHasNoDefinition(t)&&this.matchesUnresolvedExactTypeOnly(e,t))return!0;try{const s=ke.fromNode(t),o=i.limits===void 0?r:_e.of(r,i.limits),a=_e.of(o,s),l=this.extendAndResolve(e,a),c=this.blue.resolve(t,a),d=this.expandSchemaOwnedTypeReferences(t);return this.recursiveValueComparison(l,c,d,a,{},this.normalizeMatcherPointer(i.pointer),i.memo)?this.isTypeOnlyMatcher(t)?!0:this.verifyMatch(l,t,a)||t.getType()===void 0:!1}catch{return this.matchesUnresolvedExactTypeOnly(e,t)}}extendAndResolve(e,t){const r=e.clone(),i=r.clone();this.blue.extend(i,t);const s=this.blue.resolve(i,t);return this.restoreMissingStructure(s,r),s}restoreMissingStructure(e,t){const r=t.getItems(),i=e.getItems();if(r&&r.length>0)if(!i||i.length===0)e.setItems(r.map(l=>l.clone()));else for(let l=0;l<Math.min(i.length,r.length);l++)this.restoreMissingStructure(i[l],r[l]);const s=t.getProperties();if(s){let l=e.getProperties();l||(l={},e.setProperties(l));for(const[c,d]of Object.entries(s)){const p=l[c];p===void 0?l[c]=d.clone():this.restoreMissingStructure(p,d)}}const o=t.getBlueId();e.getBlueId()===void 0&&o!==void 0&&e.setBlueId(o);const a=t.getValue();e.getValue()===void 0&&a!==void 0&&e.setValue(a)}verifyMatch(e,t,r){const i=t.getType();if(this.matchesImplicitStructure(e,i))return!0;const s=e.clone().setType(t.clone());try{this.blue.resolve(s,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,i=_,s={},o,a){const l=this.expectedTypeBlueIdForMemo(t,r);if(a&&o&&l){const c=a.get(o,l);if(c!==void 0)return c;const d=this.recursiveValueComparisonUncached(e,t,r,i,s,o,a);return a.set(o,l,d),d}return this.recursiveValueComparisonUncached(e,t,r,i,s,o,a)}recursiveValueComparisonUncached(e,t,r=t,i=_,s={},o,a){const l=t.getType(),c=this.matchesImplicitStructure(e,l)||this.matchesImplicitCoreCollectionType(e,t);if(this.requiresSemanticPresence(t)&&!this.isRootMatcherPointer(o)&&this.isMetadataOnlyNode(e)||!this.matchesSchemaCardinality(e,t)||e.getType()===void 0&&this.isCoreCollectionType(t)&&!c)return!1;if(l&&!c){const w=e.getType();if(w){if(!A(w,l,this.blue.getNodeProvider())&&!this.matchesExactTypeReference(w,l))return!1}else if(!this.matchesImplicitPrimitiveType(e,l))return!1}const d=t.getBlueId();if(!c&&d!==void 0)if(this.isExplicitBlueIdMatcher(r)){if(s.bareBlueIdMatcherMode==="type-reference"){if(!this.matchesBareBlueIdTypeReference(e,t,d))return!1}else if(!this.matchesBareBlueIdIdentity(e,d))return!1}else{const w=e.getBlueId(),T=e.getType();if(T===void 0&&w!==void 0&&w!==d||T&&!A(T,t,this.blue.getNodeProvider())&&!this.matchesExactTypeReference(T,t))return!1}const p=e.getBlueId();if(!c&&d===void 0&&p!==void 0&&e.getType()===void 0&&t.getItems()===void 0&&this.hasMatcherShape(t)&&!this.matchesCalculatedBlueId(t,p))return!1;const f=t.getValue();if(f!==void 0){const w=e.getValue();if(w===void 0)return!1;if(x(w)&&x(f)){if(!w.eq(f))return!1}else if(w!==f)return!1}const I=t.getItems(),v=r.getItems();if(I!==void 0){const w=e.getItems()??[];for(let T=0;T<I.length;T++)if(T<w.length){if(!this.recursiveValueComparison(w[T],I[T],v?.[T]??I[T],i,{},this.childMatcherPointer(o,String(T)),a))return!1}else if(this.requiresSemanticPresence(I[T])||this.hasValueInNestedStructure(I[T]))return!1}const P=t.getItemType(),D=r.getItemType();if(P!==void 0){const w=e.getItems()??[];for(let T=0;T<w.length;T++){const z=w[T];if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(z,P,D??P,i,"type-reference"),P,D??P,i,{bareBlueIdMatcherMode:"type-reference"},this.childMatcherPointer(o,String(T)),a))return!1}}const U=t.getProperties(),Z=r.getProperties();if(U!==void 0){const w=e.getProperties()??{};for(const[T,z]of Object.entries(U))if(T in w){if(!this.recursiveValueComparison(w[T],z,Z?.[T]??z,i,{},this.childMatcherPointer(o,T),a))return!1}else if(this.requiresSemanticPresence(z)||this.hasValueInNestedStructure(z))return!1}const J=t.getValueType(),we=r.getValueType();if(J!==void 0){const w=Object.entries(e.getProperties()??{});for(const[T,z]of w)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(z,J,we??J,i,"type-reference"),J,we??J,i,{bareBlueIdMatcherMode:"type-reference"},this.childMatcherPointer(o,T),a))return!1}return!0}expectedTypeBlueIdForMemo(e,t){return this.blueIdOrReference(t)??this.blueIdOrReference(e)??this.blueIdOrReference(t.getType())??this.blueIdOrReference(e.getType())}blueIdOrReference(e){return e?.getBlueId()??e?.getReferenceBlueId()}normalizeMatcherPointer(e){if(e===void 0)return;const t=e.trim();return t.length===0||t==="/"?"/":t.startsWith("/")?t:`/${t}`}childMatcherPointer(e,t){if(e===void 0)return;const r=t.replace(/~/g,"~0").replace(/\//g,"~1");return e==="/"?`/${r}`:`${e}/${r}`}resolveUntypedNodeAgainstMatcherType(e,t,r,i,s="identity"){return e.getType()!==void 0||e.getBlueId()!==void 0||s==="identity"&&this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,i)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const i of t)if(this.hasValueInNestedStructure(i))return!0}const r=e.getProperties();if(r!==void 0){for(const i of Object.values(r))if(this.hasValueInNestedStructure(i))return!0}return!1}requiresSemanticPresence(e){return e.getSchema()?.get("required")?.getValue()===!0}matchesSchemaCardinality(e,t){const r=t.getSchema();if(!r)return!0;const i=this.schemaInteger(r,"minItems");if(i!==void 0&&(e.getItems()?.length??0)<i)return!1;const s=this.schemaInteger(r,"maxItems");if(s!==void 0&&(e.getItems()?.length??0)>s)return!1;const o=Object.keys(e.getProperties()??{}).length,a=this.schemaInteger(r,"minFields");if(a!==void 0&&o<a)return!1;const l=this.schemaInteger(r,"maxFields");return!(l!==void 0&&o>l)}schemaInteger(e,t){const r=e.get(t)?.getValue();if(typeof r=="number"&&Number.isInteger(r))return r;if(W(r))return Number(r.toString())}isRootMatcherPointer(e){return e===void 0||e==="/"}isMetadataOnlyNode(e){return e.getValue()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0&&e.getBlueId()===void 0&&e.getReferenceBlueId()===void 0&&this.hasMetadata(e)}hasMetadata(e){return e.getName()!==void 0||e.getDescription()!==void 0||e.getType()!==void 0||e.getItemType()!==void 0||e.getKeyType()!==void 0||e.getValueType()!==void 0||e.getSchema()!==void 0||e.getMergePolicy()!==void 0||e.getBlue()!==void 0}hasMatcherShape(e){return e.getValue()!==void 0||e.getType()!==void 0||e.getItemType()!==void 0||e.getKeyType()!==void 0||e.getValueType()!==void 0||e.getItems()!==void 0||e.getProperties()!==void 0}isTypeOnlyMatcher(e){return e.getType()!==void 0&&e.getBlueId()===void 0&&e.getReferenceBlueId()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getProperties()===void 0&&e.getName()===void 0&&e.getDescription()===void 0}matchesUnresolvedExactTypeOnly(e,t){if(!this.isTypeOnlyMatcher(t))return!1;const r=e.getType(),i=t.getType();return r!==void 0&&i!==void 0&&this.matchesExactTypeReference(r,i)}targetTypeReferenceHasNoDefinition(e){const t=this.blueIdOrReference(e.getType());if(t===void 0)return!1;const r=this.blue.getNodeProvider().fetchByBlueId(t);return r==null||r.length===0}matchesImplicitPrimitiveType(e,t){const r=e.getValue();switch(this.blueIdOrReference(t)??this.primitiveAliasBlueId(t.getValue())){case k:return typeof r=="string";case H:return typeof r=="number"&&Number.isInteger(r)&&Number.isSafeInteger(r)||W(r);case q:return typeof r=="number"||x(r);case Y:return typeof r=="boolean";default:return!1}}primitiveAliasBlueId(e){switch(e){case"Text":return k;case"Integer":return H;case"Double":return q;case"Boolean":return Y;default:return}}matchesCalculatedBlueId(e,t){if(e instanceof te&&e.getCompleteness()==="path-limited"&&e.getSourceSemanticBlueId()!==void 0)return e.getSourceSemanticBlueId()===t;try{return this.blue.calculateBlueIdSync(e)===t}catch{try{return this.blue.calculateBlueIdSync(this.toPlainBlueNode(e))===t}catch{return!1}}}matchesBareBlueIdIdentity(e,t){return e.getBlueId()===t||this.matchesCalculatedBlueId(e,t)}matchesBareBlueIdTypeReference(e,t,r){const i=e.getType();return i?A(i,t,this.blue.getNodeProvider()):e.getBlueId()!==void 0?this.matchesBareBlueIdIdentity(e,r):!1}matchesExactTypeReference(e,t){const r=this.blueIdOrReference(e),i=this.blueIdOrReference(t);return r!==void 0&&i!==void 0&&r===i}toPlainBlueNode(e){const t=new h(e.getName());t.setDescription(e.getDescription()).setReferenceBlueId(e.getReferenceBlueId()).setInlineValue(e.isInlineValue());const r=e.getValue();r!==void 0&&t.setValue(r);const i=e.getType();i!==void 0&&t.setType(this.toPlainBlueNode(i));const s=e.getItemType();s!==void 0&&t.setItemType(this.toPlainBlueNode(s));const o=e.getKeyType();o!==void 0&&t.setKeyType(this.toPlainBlueNode(o));const a=e.getValueType();a!==void 0&&t.setValueType(this.toPlainBlueNode(a));const l=e.getItems();l!==void 0&&t.setItems(l.map(p=>this.toPlainBlueNode(p)));const c=e.getProperties();c!==void 0&&t.setProperties(Object.fromEntries(Object.entries(c).map(([p,f])=>[p,this.toPlainBlueNode(f)])));const d=e.getBlue();return d!==void 0&&t.setBlue(this.toPlainBlueNode(d)),t}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:Ge(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):He(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:Ge(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):He(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return Ge(e,this.blue.getNodeProvider())||He(e,this.blue.getNodeProvider())}isImplicitListStructure(e){return e.getItems()!==void 0&&e.getValue()===void 0}isImplicitDictionaryStructure(e){return e.getProperties()!==void 0&&e.getValue()===void 0}isBareBlueIdReference(e){return e.getBlueId()!==void 0&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getProperties()===void 0&&e.getValueType()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0&&e.getPreviousBlueId()===void 0&&e.getPosition()===void 0&&e.getBlue()===void 0}isExplicitBlueIdMatcher(e){return this.isBareBlueIdReference(e)}resolveAgainstTargetType(e,t,r){try{const i=e.clone(),s=i.clone().setType(t.clone()),o=this.blue.resolve(s,r);return this.restoreMissingStructure(o,i),o}catch{return null}}expandSchemaOwnedTypeReferences(e){return this.isSchemaDefinitionNode(e)?this.expandSchemaTypeReferences(e.clone()):e}isSchemaDefinitionNode(e){return e.getBlueId()!==void 0&&(e.getName()!==void 0||e.getDescription()!==void 0||e.getType()!==void 0||e.getItemType()!==void 0||e.getKeyType()!==void 0||e.getValueType()!==void 0||e.getItems()!==void 0||e.getProperties()!==void 0)}expandSchemaTypeReferences(e,t=new Set){const r=this.withVisitedBlueId(t,e.getBlueId()),i=e.getType();i&&e.setType(this.expandReferencedTypeNode(i,r));const s=e.getItemType();s&&e.setItemType(this.expandReferencedTypeNode(s,r));const o=e.getKeyType();o&&e.setKeyType(this.expandReferencedTypeNode(o,r));const a=e.getValueType();a&&e.setValueType(this.expandReferencedTypeNode(a,r));const l=e.getItems();l&&e.setItems(l.map(d=>this.expandSchemaTypeReferences(d,r)));const c=e.getProperties();return c&&e.setProperties(Object.fromEntries(Object.entries(c).map(([d,p])=>[d,this.expandSchemaTypeReferences(p,r)]))),e}expandReferencedTypeNode(e,t){if(!this.isBareBlueIdReference(e))return this.expandSchemaTypeReferences(e.clone(),t);const r=e.getBlueId();if(!r||t.has(r))return e.clone();const i=this.blue.getNodeProvider().fetchByBlueId(r);return!i||i.length!==1?e.clone():this.expandSchemaTypeReferences(i[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}class L{static ZERO_BLUE_ID="0".repeat(44);static THIS_INDEX_REFERENCE_PATTERN=/^this#(0|[1-9]\d*)$/;prepareDocument;calculateBlueId;constructor(e={}){this.prepareDocument=e.prepareDocument??(t=>t),this.calculateBlueId=e.calculateBlueId??E.calculateBlueIdAllowingCyclicPlaceholdersSync}static hasThisReference(e){return e.some(t=>this.nodeHasThisReference(t))}static hasIndexedThisReference(e){return e.some(t=>this.nodeHasIndexedThisReference(t))}static isIndexedThisReference(e){return this.THIS_INDEX_REFERENCE_PATTERN.test(e)}calculate(e){this.validateCyclicSet(e);const t=e.map((a,l)=>{const c=this.prepareDocument(this.replaceIndexedThisReferences(a,()=>L.ZERO_BLUE_ID));return{originalIndex:l,preliminaryBlueId:this.calculateBlueId(c),node:a}});this.rejectDuplicatePreliminaryInputs(t);const r=[...t].sort(this.comparePreliminaryDocuments),i=[];r.forEach(({originalIndex:a},l)=>{i[a]=l});const s=r.map(({node:a})=>this.prepareDocument(this.replaceIndexedThisReferences(a,l=>`this#${i[l]}`))),o=this.calculateBlueId(s);return{blueId:o,nodes:s,documentBlueIds:e.map((a,l)=>`${o}#${i[l]}`),originalToSortedIndexes:i}}comparePreliminaryDocuments(e,t){return e.preliminaryBlueId<t.preliminaryBlueId?-1:e.preliminaryBlueId>t.preliminaryBlueId?1:e.originalIndex-t.originalIndex}rejectDuplicatePreliminaryInputs(e){const t=new Map;e.forEach(({preliminaryBlueId:r,originalIndex:i})=>{const s=t.get(r);if(s!==void 0)throw new Error(`Duplicate preliminary cyclic BlueId input for members ${s} and ${i}.`);t.set(r,i)})}validateCyclicSet(e){if(e.length===0)throw new Error("Cyclic document set cannot be empty.");let t=!1;if(this.visitReferences(e,(r,i)=>{if((i==="this"||i.startsWith("this#"))&&(t=!0),i==="this")throw new Error("Direct cyclic document sets must use indexed references such as 'this#0'; unindexed 'this' is not supported.");if(i.startsWith("this#")&&!L.THIS_INDEX_REFERENCE_PATTERN.test(i))throw new Error(`Malformed direct cyclic reference '${i}'. Expected 'this#<non-negative-integer>'.`);const s=this.readIndexedThisReference(i);if(s!==void 0&&s>=e.length)throw new Error(`Direct cyclic reference '${i}' points outside the ${e.length}-document set.`)}),!t)throw new Error("Circular BlueId calculation requires at least one internal this reference.")}replaceIndexedThisReferences(e,t){const r=e.clone();return this.rewriteIndexedThisReferences(r,t),r}rewriteIndexedThisReferences(e,t){const r=e.getReferenceBlueId();if(r!==void 0){const i=this.readIndexedThisReference(r);i!==void 0&&e.setReferenceBlueId(t(i))}this.childrenOf(e).forEach(i=>this.rewriteIndexedThisReferences(i,t))}static nodeHasThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,i)=>{(i==="this"||i.startsWith("this#"))&&(t=!0)}),t}static nodeHasIndexedThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,i)=>{L.THIS_INDEX_REFERENCE_PATTERN.test(i)&&(t=!0)}),t}visitReferences(e,t){e.forEach(r=>L.visitNodeReferences(r,t))}static visitNodeReferences(e,t){const r=e.getReferenceBlueId();r!==void 0&&t(e,r),this.childrenOf(e).forEach(i=>this.visitNodeReferences(i,t))}readIndexedThisReference(e){const t=e.match(L.THIS_INDEX_REFERENCE_PATTERN);if(t!==null)return Number(t[1])}childrenOf(e){return L.childrenOf(e)}static childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),e.getContractsNode(),...e.getSchema()?.entries().map(([,t])=>t)??[],...e.getSchema()?.getEnum()??[],...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}class Er{resolveWithoutLimits(e){return this.resolve(e,_)}}class xt{nodeProvider;strategy;constructor(e,t){this.nodeProvider=oe.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,i=!1){if(!i){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const s=e.getBlueId();if(s&&C.hasBlueIdOnly(e)&&!ie.includes(s)){const f=this.fetchNode(e);if(f&&f.length>0){const I=this.shouldPreserveReferenceBlueId(r,i);if(f.length===1){const v=f[0];this.mergeNodes(e,v,I)}else{const v=f.map(D=>D.clone()),P=new h().setItems(v);this.mergeNodes(e,P,I)}}}const o=e.getType();o&&this.extendNode(o,t,"type",!0);const a=e.getItemType();a&&this.extendNode(a,t,"itemType",!0);const l=e.getKeyType();l&&this.extendNode(l,t,"keyType",!0);const c=e.getValueType();c&&this.extendNode(c,t,"valueType",!0);const d=e.getProperties();d&&Object.entries(d).forEach(([f,I])=>{this.extendNode(I,t,f,!1)});const p=e.getItems();if(p&&p.length>0)for(let f=0;f<p.length;f++)this.extendNode(p[f],t,String(f),!1)}finally{i||t.exitPathSegment()}}fetchNode(e){const t=e.getBlueId();if(!t){if(this.strategy==="RETURN_EMPTY")return null;throw new Error(`No blueId found for node: ${e.getName()}`)}const r=this.nodeProvider.fetchByBlueId(t);if(!r||r.length===0){if(this.strategy==="RETURN_EMPTY")return null;throw new Error(`No content found for blueId: ${e.getBlueId()}`)}return r}shouldPreserveReferenceBlueId(e,t){return t&&["type","itemType","keyType","valueType"].includes(e)}mergeNodes(e,t,r){r||e.setReferenceBlueId(void 0),e.setName(t.getName()),e.setDescription(t.getDescription()),e.setType(t.getType()?.clone()),e.setItemType(t.getItemType()?.clone()),e.setKeyType(t.getKeyType()?.clone()),e.setValueType(t.getValueType()?.clone());const i=t.getValue();u.isNonNullable(i)&&e.setValue(i),e.setItems(t.getItems()?.map(o=>o.clone()));const s=t.getProperties();e.setProperties(s===void 0?void 0:Object.fromEntries(Object.entries(s).map(([o,a])=>[o,a.clone()]))),e.setBlue(t.getBlue()?.clone())}}class pe extends Er{mergingProcessor;nodeProvider;nodeProviderIsUnverified;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProviderIsUnverified=oe.isUnverified(t),this.nodeProvider=oe.wrap(t)}merge(e,t,r){return this.mergeWithContext(e,t,this.createResolutionContext(r))}mergeWithContext(e,t,r){if(u.isNonNullable(t.getBlue()))throw new Error('Document contains "blue" attribute. Preprocess document before merging.');let i=e;const s=t.getType();if(u.isNonNullable(s)){const o=this.resolveTypeNode(s,r),a=this.getTypeOverlay(s,o,r);i=this.mergeObject(i,a,r);const l=t.cloneShallow().setType(o.clone());return this.mergeObject(i,l,r)}return this.mergeObject(i,t,r)}mergeObject(e,t,r){const i=e.cloneShallow(),s=this.mergingProcessor.preserveSource?.(i,t,r.nodeProvider);if(s!==void 0)return this.mergingProcessor.postProcess?this.mergingProcessor.postProcess(s,t,r.nodeProvider):s;let o=this.mergingProcessor.process(i,t,r.nodeProvider);if(this.mergingProcessor.shouldPreserveSource?.(t,r.nodeProvider))return this.mergingProcessor.postProcess&&(o=this.mergingProcessor.postProcess(o,t,r.nodeProvider)),o;const a=t.getItems();u.isNonNullable(a)&&(o=this.mergeChildren(o,t,r));const l=t.getProperties();return u.isNonNullable(l)&&(o=this.mergeProperties(o,t,l,r)),u.isNonNullable(t.getBlueId())&&(o=o.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(o=this.mergingProcessor.postProcess(o,t,r.nodeProvider)),o}mergeChildren(e,t,r){const i=t.getItems()??[];for(let s=0;s<i.length;s+=1)if(s!==0&&b.hasPreviousProperty(i[s]))throw new Error("$previous list control is allowed only as the first item.");return b.hasListControlItems(i)?this.mergeChildrenWithListControls(e,t,r):this.mergeChildrenWithoutListControls(e,i,r)}mergeChildrenWithoutListControls(e,t,r){const i=e.getItems();if(u.isNullable(i)){const o=[];for(let a=0;a<t.length;a++){const l=t[a];if(r.limits.shouldMergePathSegment(String(a),l)){this.enterPathSegment(r,String(a),l);try{const c=this.materializeForCurrentContextWithItemType(l,r,e.getItemType());o.push(c)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(o)}if(t.length<i.length)throw new Error(`Subtype of element must not have more items (${i.length}) than the element itself (${t.length}).`);const s=[...i];for(let o=0;o<t.length;o++)if(r.limits.shouldMergePathSegment(String(o),t[o])){this.enterPathSegment(r,String(o),t[o]);try{if(o>=s.length){const d=this.materializeForCurrentContextWithItemType(t[o],r,e.getItemType());s.push(d);continue}const a=r.limits instanceof re?this.applyItemType(t[o],e.getItemType()):this.materializeForCurrentContextWithItemType(t[o],r,e.getItemType()),l=this.calculateNodeBlueId(a,r),c=this.calculateNodeBlueId(s[o],r);if(l!==c)throw new Error(`Mismatched items at index ${o}: source item has blueId '${l}', but target item has blueId '${c}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(s)}mergeChildrenWithListControls(e,t,r){const i=t.getItems()??[],s=e.getItems()!==void 0,o=e.getItems()??[],a=b.getMergePolicy(t,e),l=[...o];let c=0,d=!1;const p=i[0];if(p!==void 0&&b.hasPreviousProperty(p)){if(b.getPreviousBlueId(p)===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");d=!0,c=1}const f=d&&o.length===0&&!(r.limits instanceof re),I=new Set;for(;c<i.length;c++){const v=i[c];if(b.hasPreviousProperty(v))throw new Error("$previous list control is allowed only as the first item.");const P=b.readPosition(v);if(P!==void 0){if(a==="append-only")throw new Error("$pos is not allowed in append-only lists.");if(!s){if(P!==l.length)throw new Error("$pos is out of range for a list without inherited items.");const Z=b.withoutPosition(v);if(!b.hasPayloadAfterRemovingPosition(v))throw new Error("$pos list control must include an item payload.");this.enterPathSegment(r,String(P),Z);try{l.push(this.materializeForCurrentContextWithItemType(Z,r,e.getItemType()))}finally{this.exitPathSegment(r)}continue}if(P>=o.length)throw new Error(`$pos ${P} is out of range for inherited list length ${o.length}.`);if(I.has(P))throw new Error(`Duplicate $pos list overlay for index ${P}.`);I.add(P);const U=b.withoutPosition(v);if(!b.hasPayloadAfterRemovingPosition(v))throw new Error("$pos list control must include an item payload.");if(!r.limits.shouldMergePathSegment(String(P),U))continue;this.enterPathSegment(r,String(P),U);try{const Z=l[P],J=Z?.getType()??e.getItemType();l[P]=Z===void 0||b.isReplacementPayload(U)?this.materializeForCurrentContextWithItemType(U,r,J):this.mergeWithContext(Z,U,r)}finally{this.exitPathSegment(r)}continue}const D=l.length;if(!(!f&&!r.limits.shouldMergePathSegment(String(D),v))){if(f){l.push(this.materializeWithoutLimits(this.applyItemType(v,e.getItemType()),r));continue}this.enterPathSegment(r,String(D),v);try{const U=this.materializeForCurrentContextWithItemType(v,r,e.getItemType());l.push(U)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}materializeWithoutLimits(e,t){return new pe(this.mergingProcessor,t.nodeProvider).resolve(e,_)}mergeProperties(e,t,r,i){const s=e.getProperties()??{};let o=s,a=!1;for(const[l,c]of Object.entries(r))if(i.limits.shouldMergePathSegment(l,c)){this.enterPathSegment(i,l,c);try{const d=o[l],p=this.getPathLimitedListControlTarget(d,t,l,c,i),f=p??d,v=this.shouldMergePropertyWithoutPreResolve(f,c,i)?this.mergeExistingProperty(f,c,i):(()=>{const D=this.materializeForCurrentContext(c,i);return f===void 0?D:this.mergeObject(f,D,i)})(),P=p===void 0?v:this.projectListNodeToCurrentLimits(v,i);P!==d&&(a||(o={...s},a=!0),o[l]=P)}finally{this.exitPathSegment(i)}}return a?e.cloneShallow().setProperties(o):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof re?u.isNonNullable(e)&&b.hasListControlItems(t.getItems()):u.isNonNullable(t.getItems())||u.isNonNullable(e.getItems())}mergeExistingProperty(e,t,r){if(e===void 0)throw new Error("Cannot merge property without an existing target.");return this.mergeWithContext(e,t,r)}resolve(e,t){return this.resolveWithContext(e,this.createResolutionContext(t))}resolveWithContext(e,t){const r=new h,s=this.mergeWithContext(r,e,t).cloneShallow().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new te(s,{completeness:t.limits instanceof re?"full":"path-limited"})}createResolutionContext(e){const t=new Map,r=new Map,i=Ei(this.createResolutionNodeProvider(this.nodeProvider,t),r);return{limits:e,nodeProvider:i,resolvedTypeCache:new Map,resolvingTypeKeys:new Set,resolvingTypeBlueIds:new Set,typeOverlayCache:new Map,nodeHashCache:new WeakMap,providerFetchCache:t,subtypeCache:r,pathStack:[]}}resolveTypeNode(e,t){const r=e.getBlueId();if(u.isNonNullable(r)){const i=this.createResolvedTypeCacheKey(r,t),s=t.resolvedTypeCache.get(i);if(u.isNonNullable(s)&&!t.resolvingTypeKeys.has(i))return s;if(t.resolvingTypeBlueIds.has(r))return s??this.createCyclicTypeReference(r,t);const o=this.createCyclicTypeReference(r,t);t.resolvedTypeCache.set(i,o),t.resolvingTypeKeys.add(i),t.resolvingTypeBlueIds.add(r);try{const a=this.resolveAndExtendTypeNode(e,t);return a.setReferenceBlueId(r),t.resolvedTypeCache.set(i,a),a}catch(a){throw t.resolvedTypeCache.delete(i),a}finally{t.resolvingTypeKeys.delete(i),t.resolvingTypeBlueIds.delete(r)}}return this.resolveAndExtendTypeNode(e,t)}createCyclicTypeReference(e,t){return new te(new h().setReferenceBlueId(e),{completeness:t.limits instanceof re?"full":"path-limited"})}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new xt(t.nodeProvider).extend(r,ke.withSinglePath("/")),this.resolveWithContext(r,t)}getTypeOverlay(e,t,r){const i=e.getBlueId();if(u.isNullable(i))return this.createTypeOverlay(t);const s=this.createResolvedTypeCacheKey(i,r),o=r.typeOverlayCache.get(s);if(u.isNonNullable(o))return o;const a=this.createTypeOverlay(t);return r.resolvingTypeBlueIds.has(i)||r.typeOverlayCache.set(s,a),a}createTypeOverlay(e){return e.cloneShallow().setType(void 0).setBlueId(void 0)}createResolvedTypeCacheKey(e,t){return t.limits instanceof re?e:`${e}|${this.getCurrentPointer(t)}`}materializeForCurrentContext(e,t){return e.isResolved()&&this.canReuseResolvedSubtree(t)?e.clone():this.resolveWithContext(e,t)}materializeForCurrentContextWithItemType(e,t,r){return this.materializeForCurrentContext(this.applyItemType(e,r),t)}applyItemType(e,t){return e.getType()!==void 0||e.getReferenceBlueId()!==void 0||t===void 0?e:e.clone().setType(this.itemTypeReference(t))}itemTypeReference(e){const t=e.getReferenceBlueId();return t===void 0?e.clone():new h().setReferenceBlueId(t)}canReuseResolvedSubtree(e){return e.limits instanceof re}calculateNodeBlueId(e,t){const r=t.nodeHashCache.get(e);if(u.isNonNullable(r))return r;const i=j.calculateHashMinimalBlueId(e);return t.nodeHashCache.set(e,i),i}getPathLimitedListControlTarget(e,t,r,i,s){if(!(e===void 0||s.limits instanceof re||!b.hasListControlItems(i.getItems())))return this.resolveFullInheritedProperty(t,r,s)}resolveFullInheritedProperty(e,t,r){const i=e.getType();if(i===void 0)return;const s=i.getBlueId();if(u.isNonNullable(s)){const l=r.nodeProvider.fetchByBlueId(s)?.[0];return l===void 0?void 0:new pe(this.mergingProcessor,r.nodeProvider).resolve(l,_).getProperties()?.[t]?.clone()}return new pe(this.mergingProcessor,r.nodeProvider).resolve(i,_).getProperties()?.[t]?.clone()}projectListNodeToCurrentLimits(e,t){const r=e.getItems();return r===void 0?e:e.cloneShallow().setItems(r.filter((i,s)=>t.limits.shouldMergePathSegment(String(s),i)))}createResolutionNodeProvider(e,t){const r=new class extends ue{fetchByBlueId(i){if(t.has(i))return t.get(i)??null;const s=e.fetchByBlueId(i);return t.set(i,s),s}};return this.nodeProviderIsUnverified?oe.unverified(r):r}getCurrentPointer(e){return e.pathStack.length===0?"/":`/${e.pathStack.join("/")}`}enterPathSegment(e,t,r){e.pathStack.push(t),e.limits.enterPathSegment(t,r)}exitPathSegment(e){e.pathStack.pop(),e.limits.exitPathSegment()}}class Nr{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((i,s)=>s.process(i,t,r),e)}preserveSource(e,t,r){for(const i of this.mergingProcessors){const s=i.preserveSource?.(e,t,r);if(s!==void 0)return s}}shouldPreserveSource(e,t){return this.mergingProcessors.some(r=>r.shouldPreserveSource?.(e,t))}postProcess(e,t,r){return this.mergingProcessors.reduce((i,s)=>s.postProcess?s.postProcess(i,t,r):i,e)}}class wr{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const i=e.getValue();if(u.isNullable(i))return e.cloneShallow().setValue(r);if(!Ki(r,i)){if(Gi(e))return e.cloneShallow().setValue(r);throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${i}`)}}return e}}const Ki=(n,e)=>W(n)&&W(e)||Je(n)&&Je(e)?n.eq(e):n===e,Gi=n=>u.isNonNullable(n.getType())||u.isNonNullable(n.getItemType())||u.isNonNullable(n.getKeyType())||u.isNonNullable(n.getValueType())||u.isNonNullable(n.getSchema())||u.isNonNullable(n.getDescription());class Sr{process(e,t,r){const i=e.getType(),s=t.getType();let o=e;if(i===void 0){if(s!==void 0&&t.getValue()!==void 0&&Ir(s)){const a=B.get(s);throw new Error(`Anonymous core type alias '${JSON.stringify(a)}' is not interchangeable with its registry core type.`)}o=e.cloneShallow().setType(s)}else if(s!==void 0){if(!A(s,i,r)){const l=B.get(s),c=B.get(i);throw new Error(`The source type '${JSON.stringify(l)}' is not a subtype of the target type '${JSON.stringify(c)}'.`)}o=e.cloneShallow().setType(s)}return o}}class Cr{process(e,t,r){let i=this.processMergePolicy(e,t);const s=t.getItemType(),o=t.getType();if(s!==void 0&&o!==void 0&&!Ge(o,r))throw new Error("Source node with itemType must have a List type");const a=i.getItemType();if(a===void 0)s!==void 0&&(i=i.cloneShallow().setItemType(s));else if(s!==void 0){if(!A(s,a,r)){const p=B.get(s),f=B.get(a);throw new Error(`The source item type '${JSON.stringify(p)}' is not a subtype of the target item type '${JSON.stringify(f)}'.`)}i=i.cloneShallow().setItemType(s)}const l=i.getItemType(),c=t.getItems();if(l!==void 0&&c!==void 0)for(const d of c){const p=d.getType();if(p!==void 0&&!A(p,l,r)){const f=B.get(p),I=B.get(l);throw new Error(`Item of type '${JSON.stringify(f)}' is not a subtype of the list's item type '${JSON.stringify(I)}'.`)}}return i}processMergePolicy(e,t){const r=t.getMergePolicy(),i=e.getMergePolicy();if(this.validateMergePolicy(r),this.validateMergePolicy(i),i===void 0)return r===void 0?e:e.cloneShallow().setMergePolicy(r);if(r!==void 0&&r!==i)throw new Error(`Conflicting list mergePolicy values: target is "${i}" but source is "${r}".`);return e}validateMergePolicy(e){if(e!==void 0&&e!=="positional"&&e!=="append-only")throw new Error('mergePolicy must be either "positional" or "append-only".')}}class Rr{process(e,t,r){const i=t.getKeyType(),s=t.getValueType(),o=t.getType();if((i!==void 0||s!==void 0)&&o!==void 0&&!He(o,r))throw new Error("Source node with keyType or valueType must have a Dictionary type");let a=this.processKeyType(e,t,r);a=this.processValueType(a,t,r);const l=a.getKeyType(),c=a.getValueType(),d=t.getProperties();return(l!==void 0||c!==void 0)&&d!==void 0&&Object.entries(d).forEach(([p,f])=>{l!==void 0&&this.validateKeyType(p,l,r),c!==void 0&&this.validateValueType(f,c,r)}),a}processKeyType(e,t,r){const i=e.getKeyType(),s=t.getKeyType();if(i===void 0){if(s!==void 0)return this.validateBasicKeyType(s,r),e.cloneShallow().setKeyType(s)}else if(s!==void 0){if(this.validateBasicKeyType(s,r),!A(s,i,r)){const a=B.get(s),l=B.get(i);throw new Error(`The source key type '${JSON.stringify(a)}' is not a subtype of the target key type '${JSON.stringify(l)}'.`)}return e.cloneShallow().setKeyType(s)}return e}processValueType(e,t,r){const i=e.getValueType(),s=t.getValueType();if(i===void 0){if(s!==void 0)return e.cloneShallow().setValueType(s)}else if(s!==void 0){if(!A(s,i,r)){const a=B.get(s),l=B.get(i);throw new Error(`The source value type '${JSON.stringify(a)}' is not a subtype of the target value type '${JSON.stringify(l)}'.`)}return e.cloneShallow().setValueType(s)}return e}validateBasicKeyType(e,t){if(!Ci(e,t))throw new Error(`Dictionary key type must be a basic type: ${JSON.stringify(B.get(e))}`)}validateKeyType(e,t,r){if(!Ri(t,r))if(Ai(t,r)){const i=Number.parseInt(e,10);if(Number.isNaN(i)||i.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(Oi(t,r)){const i=Number.parseFloat(e);if(Number.isNaN(i))throw new Error(`Key '${e}' is not a valid Number.`)}else if(Mi(t,r)){if(e.toLowerCase()!=="true"&&e.toLowerCase()!=="false")throw new Error(`Key '${e}' is not a valid Boolean.`)}else throw new Error(`Unsupported key type: ${t.getName()||"unknown"}`)}validateValueType(e,t,r){const i=e.getType();if(i!==void 0&&!A(i,t,r)){const s=B.get(i),o=B.get(t);throw new Error(`Value of type '${JSON.stringify(s)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}const Hi=new Set(["minLength","minimum","exclusiveMinimum","minItems","minFields"]),Yi=new Set(["maxLength","maximum","exclusiveMaximum","maxItems","maxFields"]),Wi=new Set(["required","uniqueItems"]);class Ar{process(e,t){const r=t.getSchema();if(r===void 0)return e;const i=e.getSchema()?.clone()??new je;for(const s of ut){const o=r.get(s);if(o===void 0)continue;const a=i.get(s);i.set(s,this.propagateField(s,a,o))}return i.setEnum(this.propagateEnum(i.getEnum(),r.getEnum())),e.cloneShallow().setSchema(i)}propagateField(e,t,r){return t===void 0?r.clone():Wi.has(e)?r.getValue()===!0?r.clone():t.clone():e==="multipleOf"?this.multipleOf(t,r):Hi.has(e)?this.numericValue(r)>this.numericValue(t)?r.clone():t.clone():Yi.has(e)?this.numericValue(r)<this.numericValue(t)?r.clone():t.clone():r.clone()}multipleOf(e,t){const r=this.numericValue(e),i=this.numericValue(t);return Number.isInteger(r)&&Number.isInteger(i)?new h().setValue(Number(Ji(BigInt(r),BigInt(i)))):i>r?t.clone():e.clone()}propagateEnum(e,t){if(t===void 0)return e?.map(i=>i.clone());if(e===void 0)return this.canonicalizeEnum(t);const r=new Map(e.map(i=>[this.enumComparableBlueId(i),i]));return this.canonicalizeEnum(t.flatMap(i=>{const s=r.get(this.enumComparableBlueId(i));return s===void 0?[]:[s]}))}canonicalizeEnum(e){const t=new Map;for(const r of e)t.set(this.enumComparableBlueId(r),r.clone());return[...t.values()].sort((r,i)=>this.enumCanonicalKey(r).localeCompare(this.enumCanonicalKey(i)))}enumComparableBlueId(e){const t=e.clone();return t.setSchema(void 0),E.calculateBlueIdSync(t)}enumCanonicalKey(e){const t=e.clone();return t.setSchema(void 0),JSON.stringify(ne.get(t))}numericValue(e){const t=e.getValue();if(typeof t=="number")return t;if(t!=null&&"toString"in Object(t))return Number(t.toString());throw new Error("Schema keyword value must be numeric.")}}function Zi(n,e){let t=n<0n?-n:n,r=e<0n?-e:e;for(;r!==0n;){const i=t%r;t=r,r=i}return t}function Ji(n,e){return n===0n||e===0n?0n:n/Zi(n,e)*e}class Or{process(e){return e}postProcess(e){const t=e.getSchema();return t===void 0||(this.verifyMultipleOfKeyword(t),this.verifyTextLength("minLength",t.get("minLength"),e),this.verifyTextLength("maxLength",t.get("maxLength"),e),this.verifyMultipleOf(t.get("multipleOf"),e),this.verifyEnum(t.getEnum(),e)),e}verifyMultipleOfKeyword(e){const t=e.get("multipleOf");if(t!==void 0&&this.numericValue(t)<=0)throw new Error('Schema keyword "multipleOf" must be greater than zero.')}verifyTextLength(e,t,r){if(t===void 0)return;const i=r.getValue();if(i==null){if(!this.hasPayload(r))return;throw this.wrongKind(e,"Text scalar")}if(typeof i!="string")throw this.wrongKind(e,"Text scalar");const s=Array.from(i).length,o=this.numericValue(t);if(e==="minLength"&&s<o)throw new Error(`Value "${i}" is shorter than the minimum length of ${o}.`);if(e==="maxLength"&&s>o)throw new Error(`Value "${i}" is longer than the maximum length of ${o}.`)}verifyMultipleOf(e,t){if(e===void 0)return;const r=t.getValue();if(r==null){if(!this.hasPayload(t))return;throw this.wrongKind("multipleOf","numeric scalar")}if(!this.isNumeric(r))throw this.wrongKind("multipleOf","numeric scalar");if(!sr.isExactBinary64Multiple(r,e.getValue()))throw new Error(`Value ${String(r)} is not a multiple of ${String(e.getValue())}.`)}verifyEnum(e,t){if(e===void 0||t.getValue()===void 0)return;const r=this.comparableBlueId(t);if(!e.some(i=>this.comparableBlueId(i)===r))throw new Error("Node value is not one of the allowed enum values.")}comparableBlueId(e){const t=e.clone();return t.setName(void 0),t.setDescription(void 0),t.setSchema(void 0),E.calculateBlueIdSync(t)}hasPayload(e){return e.getValue()!==void 0&&e.getValue()!==null||e.getItems()!==void 0||Object.keys(e.getProperties()??{}).length>0}isNumeric(e){return typeof e=="number"||e!=null&&"toString"in Object(e)}numericValue(e){const t=e.getValue();if(!this.isNumeric(t))throw this.wrongKind("schema","numeric scalar");return Number(t?.toString())}wrongKind(e,t){return new Error(`Schema keyword "${e}" applies to wrong kind; expected ${t}.`)}}class Mr{process(e){return e}postProcess(e,t,r){const i=e.getType();if(i!==void 0&&Vi(i,r)){const s=e.getItems(),o=e.getProperties();if(s!==void 0&&s.length>0||o!==void 0&&Object.keys(o).length>0){const a=Di(i,r),l=i.getName()||"unknown";throw new Error(`Node of type "${l}" (which extends basic type "${a}") must not have items, properties or contracts.`)}}return e}}class Vr{process(e,t){let r=e;const i=t.getName();i!==void 0&&i!==e.getName()&&(r=r.cloneShallow().setName(i));const s=t.getDescription();return s!==void 0&&s!==r.getDescription()&&(r=r.cloneShallow().setDescription(s)),r}}function _t(){return new Nr([new wr,new Sr,new Cr,new Rr,new Ar,new Or,new Vr,new Mr])}class Ye{nodeProvider;mergingProcessor;minimizer=new Et;cyclicSetIdentity;constructor(e={}){this.nodeProvider=e.nodeProvider??Lt(()=>[]),this.mergingProcessor=e.mergingProcessor??_t(),this.cyclicSetIdentity=this.createCyclicSetIdentityService()}createCyclicSetIdentityService(){return new L({prepareDocument:e=>this.prepareCyclicDocument(e),calculateBlueId:e=>this.hashCyclicPrepared(e)})}calculateBlueId(e){const t=this.tryCalculateCyclicSetBlueId(e);if(t!==void 0)return Promise.resolve(t);const r=this.toMinimalIdentityInput(e);return this.hashMinimalTrustedAsync(r)}calculateBlueIdSync(e){const t=this.tryCalculateCyclicSetBlueId(e);if(t!==void 0)return t;const r=this.toMinimalIdentityInput(e);return this.hashMinimalTrusted(r)}minimize(e){if(e instanceof te&&e.getCompleteness()==="path-limited"){const t=e.getSourceSemanticBlueId();if(t!==void 0)return new h().setReferenceBlueId(t);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return C.hasBlueIdOnly(e)?e.clone():e.isResolved()?this.minimizeResolved(e):this.minimizeAuthoring(e)}minimizeResolved(e){if(e instanceof te&&e.getCompleteness()==="path-limited")throw new Error("Cannot minimize a path-limited resolved node as a full resolved tree.");return this.minimizer.minimizeResolved(e)}minimizeAuthoring(e){return this.minimizeAuthoringWithProvider(e,this.nodeProvider)}minimizeAuthoringWithProvider(e,t){const r=new pe(this.mergingProcessor,t).resolve(e,_);return this.minimizeResolved(r)}hashMinimalTrusted(e){return this.hashMinimalTrustedWithProvider(e,this.nodeProvider)}hashMinimalTrustedWithProvider(e,t){return Array.isArray(e)?(Pe.validateStorageListShape(e),E.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t))):(Pe.validateStorageShape(e),E.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t)))}hashMinimalTrustedAsync(e){return Array.isArray(e)?(Pe.validateStorageListShape(e),E.calculateBlueId(this.toHashableMinimalTrusted(e))):(Pe.validateStorageShape(e),E.calculateBlueId(this.toHashableMinimalTrusted(e)))}toHashableMinimalTrusted(e,t=this.nodeProvider){return Array.isArray(e)?e.map(r=>this.toHashableMinimalTrustedNode(r,t)):this.toHashableMinimalTrustedNode(e,t)}toHashableMinimalTrustedNode(e,t=this.nodeProvider){if(!b.hasPositionControl(e))return e;const r=new pe(this.mergingProcessor,t).resolve(e,_);return this.minimizer.minimizeResolvedForHash(r)}prepareCyclicDocument(e){return this.minimizeAuthoringWithProvider(e,this.createCyclicReferenceNodeProvider())}hashCyclicPrepared(e){return E.calculateBlueIdAllowingCyclicPlaceholdersSync(this.toHashableMinimalTrusted(e,this.createCyclicReferenceNodeProvider()))}createCyclicReferenceNodeProvider(){const e=this.nodeProvider;return oe.unverified(new class extends ue{fetchByBlueId(t){return t===L.ZERO_BLUE_ID||L.isIndexedThisReference(t)?[new h().setReferenceBlueId(t)]:e.fetchByBlueId(t)}})}toMinimalIdentityInput(e){return Array.isArray(e)?this.toMinimalListIdentityInput(e):this.minimize(e)}tryCalculateCyclicSetBlueId(e){const t=this.getTopLevelSetItems(e);if(t===void 0){if(!Array.isArray(e)&&L.hasThisReference([e]))throw new Error("Direct cyclic references using 'this#k' are supported only in a top-level document set.");return}if(L.hasThisReference(t))return this.cyclicSetIdentity.calculate(t).blueId}getTopLevelSetItems(e){if(Array.isArray(e))return e;if(C.hasItemsOnly(e))return e.getItems()??[]}toMinimalListIdentityInput(e){if(Pe.validateListControlShape(e),e[0]!==void 0&&b.isPreviousItem(e[0]))return e.map(i=>i.clone());const t=new h().setItems(e);return this.minimizeAuthoring(t).getItems()??[]}}class Dr{static convertValue(e,t){const r=e.getType()?.getBlueId(),i=e.getValue();return u.isNullable(i)?bi(t)&&C.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):i:k===r?this.convertFromString(String(i),t):q===r||i instanceof V?this.convertFromBigDecimal(new V(i?.toString()),t):H===r||i instanceof R?this.convertFromBigInteger(new R(i?.toString()),t):Y===r||typeof i=="boolean"?this.convertFromBoolean(!!i,t):this.convertFromString(String(i),t)}static convertFromString(e,t){if(!t)return e;const r=Se(t);if(r==="ZodString"||r==="ZodEnum"||r==="ZodNativeEnum")return e;if(r==="ZodNumber")return Number(e);if(r==="ZodBoolean")return e.toLowerCase()==="true";if(r==="ZodBigInt")return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){const r=Se(t);if(r==="ZodNumber")return e.toNumber();if(r==="ZodString")return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){const r=Se(t);if(r==="ZodNumber")return e.toNumber();if(r==="ZodBigInt")return BigInt(e.toString());if(r==="ZodString")return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t)return e;const r=Se(t);if(r==="ZodBoolean")return e;if(r==="ZodString")return e.toString();if(r==="ZodNumber")return Number(e);if(r==="ZodBigInt")return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;const t=Se(e);if(t==="ZodNumber")return 0;if(t==="ZodBoolean")return!1;if(t==="ZodString")return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}function Se(n){return String(n._def.typeName)}class Xi{convert(e,t){return Dr.convertValue(e,t)}}class Qi{constructor(e,t){this.nodeToObjectConverter=e,this.calculateBlueId=t}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(Pt(t)==="ZodIntersection"){const r=t,i=r._def.left,s=r._def.right,o=this.convert(e,i),a=this.convert(e,s);return{...o,...a}}if(Pt(t)==="ZodUnion")throw new Error("Union not supported");if(Pt(t)==="ZodObject"){const r=t;return Object.keys(r.shape).reduce((s,o)=>{const a=e.getProperties(),l=r.shape[o],c=cr(l);if(u.isNonNullable(c)){const v=ve.isString(c)?c:o,P=a?.[v],D=P?this.calculateBlueId(P):void 0;return s[o]=D,s}const d=dr(l);if(u.isNonNullable(d)){const v=a?.[d];return s[o]=v?.getName(),s}const p=ar(l);if(u.isNonNullable(p)){const v=a?.[p];return s[o]=v?.getDescription(),s}if(o==="name"){const v=e.getName();return s[o]=v,s}if(o==="description"){const v=e.getDescription();return s[o]=v,s}const f=a?.[o];if(u.isNullable(f))return s;const I=this.nodeToObjectConverter.convert(f,l);return s[o]=I,s},{})}throw new Error("Unknown schema type, "+t._def.typeName)}}function Pt(n){return String(n._def.typeName)}class es{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t.element??t._def.type;return r.map(o=>this.nodeToObjectConverter.convert(o,i))}}class ts{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t._def.valueType,s=r.map(o=>this.nodeToObjectConverter.convert(o,i));return new Set(s)}}class rs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,i=t.valueSchema,s=new Map,o=e.getName();u.isNonNullable(o)&&s.set(ae,o);const a=e.getDescription();u.isNonNullable(a)&&s.set(le,a);const l=e.getProperties();return u.isNonNullable(l)&&Object.entries(l).forEach(([c,d])=>{const p=new h().setValue(c);p.setType(new h().setBlueId(k));const f=Dr.convertValue(p,r),I=this.nodeToObjectConverter.convert(d,i);s.set(f,I)}),t instanceof m.ZodRecord?Object.fromEntries(s):s}}class is{convert(e){return B.get(e)}}class ss{convert(e){return B.get(e)}}class ns{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const i=t.items;return r.map((o,a)=>this.nodeToObjectConverter.convert(o,i[a]))}}const os=m.z.union([m.z.literal("ZodString"),m.z.literal("ZodNumber"),m.z.literal("ZodBoolean"),m.z.literal("ZodBigInt"),m.z.literal("ZodArray"),m.z.literal("ZodSet"),m.z.literal("ZodMap"),m.z.literal("ZodRecord"),m.z.literal("ZodObject"),m.z.literal("ZodEnum"),m.z.literal("ZodNativeEnum"),m.z.literal("ZodUnknown"),m.z.literal("ZodAny"),m.z.literal("ZodTuple")]);class as{constructor(e,t){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new Qi(this.nodeToObjectConverter,t)}converters=new Map;complexObjectConverter;registerConverters(){const e=new Xi,t=new es(this.nodeToObjectConverter),r=new ns(this.nodeToObjectConverter),i=new ts(this.nodeToObjectConverter),s=new rs(this.nodeToObjectConverter);this.converters.set("ZodString",e),this.converters.set("ZodNumber",e),this.converters.set("ZodBoolean",e),this.converters.set("ZodBigInt",e),this.converters.set("ZodEnum",e),this.converters.set("ZodNativeEnum",e),this.converters.set("ZodUnknown",new is),this.converters.set("ZodAny",new ss),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",i),this.converters.set("ZodMap",s),this.converters.set("ZodRecord",s),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){const t=String(e._def.typeName);if(t==="ZodEffects")return this.getSchemaTypeName(e.innerType());if(t==="ZodLazy")return this.getSchemaTypeName(e.schema);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodReadonly"||t==="ZodBranded"||mr(e))return this.getSchemaTypeName(e.unwrap());try{return os.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class Lr{constructor(e,t){if(this.typeSchemaResolver=e,!t?.calculateBlueId)throw new Error("NodeToObjectConverter requires a semantic calculateBlueId option.");this.calculateBlueId=t.calculateBlueId,this.converterFactory=new as(this,this.calculateBlueId)}converterFactory;calculateBlueId;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),i=Q.unwrapSchema(t);if(Dt(i))return e;let s=i;return Q.checkSchemaExtension(r,i,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(s=r),this.convertWithType(e,s)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class ls{static get(e,t={}){const{strategy:r="official"}=t,i=B.get(e,r);return Br(i)}}function Me(n){try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class cs{process(e){return M.transform(e,this.inferType.bind(this))}inferType(e){const t=e.getType(),r=e.getValue();return u.isNullable(t)&&u.isNonNullable(r)&&(typeof r=="string"?e.setType(new h().setBlueId(k)):typeof r=="bigint"||W(r)?e.setType(new h().setBlueId(H)):Je(r)?e.setType(new h().setBlueId(q)):typeof r=="boolean"&&e.setType(new h().setBlueId(Y))),e}}class Fe{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof h){const r=e.getProperties();if(r&&r[Fe.MAPPINGS]){const s=r[Fe.MAPPINGS].getProperties();s&&Object.entries(s).forEach(([o,a])=>{const l=a.getValue();typeof l=="string"&&this.mappings.set(o,l)})}}else this.mappings=e}process(e){return M.transform(e,this.transformNode.bind(this))}transformNode(e){const t=e.clone();return this.transformTypeField(t,t.getType()),this.transformTypeField(t,t.getItemType()),this.transformTypeField(t,t.getKeyType()),this.transformTypeField(t,t.getValueType()),t}transformTypeField(e,t){if(t&&t.isInlineValue()&&t.getValue()!==void 0){const r=String(t.getValue());if(this.mappings.has(r)){const i=this.mappings.get(r);if(i){const s=new h().setBlueId(i);t===e.getType()?e.setType(s):t===e.getItemType()?e.setItemType(s):t===e.getKeyType()?e.setKeyType(s):t===e.getValueType()&&e.setValueType(s)}}}}}class us{process(e){return M.transform(e,this.validateNode.bind(this)),e}validateNode(e){return this.validateTypeField(e,e.getType(),"type"),this.validateTypeField(e,e.getItemType(),"itemType"),this.validateTypeField(e,e.getKeyType(),"keyType"),this.validateTypeField(e,e.getValueType(),"valueType"),e}validateTypeField(e,t,r){if(t&&t.isInlineValue()&&t.getValue()!==void 0){const i=String(t.getValue());throw new Error(`Unknown type "${i}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class xr{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const i of this.blueIdsCollections)Object.assign(t,i);const r=Object.entries(t).map(([i,s])=>` ${i}: ${s}`).join(`
40
- `);return`- type:
41
- blueId: ${e}
42
- mappings:
43
- ${r}`}getAllBlueIds(){const e={};for(const t of this.blueIdsCollections)Object.assign(e,t);return e}getAllBlueIdNames(){return Object.keys(this.getAllBlueIds())}clear(){this.blueIdsCollections=[]}getCollectionCount(){return this.blueIdsCollections.length}getTotalBlueIdCount(){return Object.keys(this.getAllBlueIds()).length}}class Ue{static DEFAULT_BLUE_BLUE_ID="EsyNgNY4ZZeCvWiGLQM52WPJ7HF5kz3DyCoxdDDaauc6";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:i}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=oe.wrap(t),this.processorProvider=r||Ue.getStandardProvider(),this.blueIdsMappingGenerator=i||new xr,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=this.applyPortableImports(this.normalizeListPlaceholders(e.clone(),!1)),i=r.getBlue();if(!i&&t&&(i=t.clone()),i){new xt(this.nodeProvider).extend(i,ke.withSinglePath("/*"));const s=this.flattenTransformationItems(i.getItems());if(s&&s.length>0){for(const o of s){const a=this.processorProvider.getProcessor(o);if(a)r=a.process(r);else throw new Error(`No processor found for transformation: ${o}`)}r.setBlue(void 0)}r=new us().process(r)}return r}applyPortableImports(e){const r=e.getBlue()?.getProperties()?.imports;if(r===void 0)return e;const i=r.getProperties();if(i===void 0||r.getValue()!==void 0||r.getItems()!==void 0||r.getReferenceBlueId()!==void 0)throw new Error("blue.imports must be an object mapping aliases to pure references.");const s=new Map;for(const[l,c]of Object.entries(i)){if(!this.isReferenceOnly(c))throw new Error(`blue.imports.${l} must be a pure reference.`);const d=K.requirePlainBlueId(c.getReferenceBlueId(),`blue.imports.${l}`),p=Ot[l];if(p!==void 0&&p!==d)throw new Error(`blue.imports cannot redefine default Blue alias "${l}".`);s.set(l,d)}const o=new Fe(s).process(e),a=o.getBlue();return a!==void 0&&(a.removeProperty("imports"),this.isEmptyNode(a)&&o.setBlue(void 0)),o}normalizeListPlaceholders(e,t){if(t&&this.isEmptyPlaceholder(e))return e.clone();if(t&&(this.isNullNode(e)||this.isEmptyNode(e)))return this.emptyPlaceholder();const r=e.clone(),i=r.getType();i!==void 0&&r.setType(this.normalizeListPlaceholders(i,!1));const s=r.getItemType();s!==void 0&&r.setItemType(this.normalizeListPlaceholders(s,!1));const o=r.getKeyType();o!==void 0&&r.setKeyType(this.normalizeListPlaceholders(o,!1));const a=r.getValueType();a!==void 0&&r.setValueType(this.normalizeListPlaceholders(a,!1));const l=r.getBlue();l!==void 0&&r.setBlue(this.normalizeListPlaceholders(l,!1));const c=r.getContractsNode();c!==void 0&&r.setContractsNode(this.normalizeListPlaceholders(c,!1));const d=r.getItems();d!==void 0&&r.setItems(d.map(f=>this.normalizeListPlaceholders(f,!0)));const p=r.getProperties();if(p!==void 0){const f=Object.fromEntries(Object.entries(p).flatMap(([I,v])=>{const P=this.normalizeListPlaceholders(v,!1);return this.isEmptyNode(P)||this.isNullNode(P)?[]:[[I,P]]}));r.setProperties(Object.keys(f).length===0?void 0:f)}return t&&this.isEmptyNode(r)?this.emptyPlaceholder():r}emptyPlaceholder(){return new h().addProperty(Ie,new h().setValue(!0))}isEmptyPlaceholder(e){const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&t[Ie]?.getValue()===!0}isNullNode(e){return e.getValue()===null&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0}isReferenceOnly(e){return e.getReferenceBlueId()!==void 0&&e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&e.getProperties()===void 0}isEmptyNode(e){return e.getName()===void 0&&e.getDescription()===void 0&&e.getType()===void 0&&e.getItemType()===void 0&&e.getKeyType()===void 0&&e.getValueType()===void 0&&e.getValue()===void 0&&e.getItems()===void 0&&(e.getProperties()===void 0||Object.keys(e.getProperties()??{}).length===0)&&e.getContractsNode()===void 0&&e.getReferenceBlueId()===void 0&&e.getSchema()===void 0&&e.getMergePolicy()===void 0}flattenTransformationItems(e){if(e!==void 0)return e.flatMap(t=>t.getItems()??[t])}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",i=e.getType()?.getBlueId();if(t===i)return new Fe(e);if(r===i)return new cs}}}enrichDefaultBlue(e){if(this.blueIdsMappingGenerator.getTotalBlueIdCount()===0)return e;const t=this.blueIdsMappingGenerator.generateMappingsYaml();return`
44
- ${e}
45
- ${t}
46
- `}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(Pr),t=he(e);if(t)this.defaultSimpleBlue=g.deserialize(t);else throw new Error("Failed to parse default Blue content")}catch(e){throw new Error(`Error loading default Blue: ${e}`)}}}class ds{preprocessingAliases=new Map;urlContentFetcher;constructor(e,t){e&&(this.preprocessingAliases=new Map(e)),this.urlContentFetcher=t}process(e){const t=this.getBlueNodeValue(e);if(t){const r=e.clone();if(this.preprocessingAliases.has(t))return this.handleAliasValue(r,t);if(K.isPotentialBlueId(t))return this.handleBlueId(r,t);throw Me(t)?new Error(`URL '${t}' detected. Use the async version of this method to fetch the content.`):new Error(`Invalid blue value: ${t}`)}return e}async processAsync(e){const t=this.getBlueNodeValue(e);if(t){const r=e.clone();if(this.preprocessingAliases.has(t))return this.handleAliasValue(r,t);if(K.isPotentialBlueId(t))return this.handleBlueId(r,t);if(Me(t)&&this.urlContentFetcher)try{const i=await this.fetchFromUrl(t);return i&&r.setBlue(new h().setItems(i)),r}catch(i){throw i instanceof Error?new Error(`Failed to fetch from URL '${t}'.
47
- ${i.message}`):i}else throw Me(t)?new Error(`UrlContentFetcher not provided for URL: ${t}`):new Error(`Invalid blue value: ${t}`)}return e}getBlueNodeValue(e){const r=e.getBlue()?.getValue();return r&&typeof r=="string"?r:null}handleAliasValue(e,t){return e.setBlue(new h().setBlueId(this.preprocessingAliases.get(t))),e}handleBlueId(e,t){return e.setBlue(new h().setBlueId(t)),e}async fetchFromUrl(e){if(!this.urlContentFetcher)throw new Error(`UrlContentFetcher not provided for URL: ${e}`);return await this.urlContentFetcher.fetchAndCache(e)}getPreprocessingAliases(){return new Map(this.preprocessingAliases)}setPreprocessingAliases(e){return this.preprocessingAliases=new Map(e),this}addPreprocessingAliases(e){return e.forEach((t,r)=>{this.preprocessingAliases.set(r,t)}),this}setUrlContentFetcher(e){return this.urlContentFetcher=e,this}getUrlContentFetcher(){return this.urlContentFetcher}}const hs={fetchUrl:async n=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${n}`)}};class ps{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||hs}validateUrl(e){if(!Me(e))throw new Error(`Invalid URL: ${e}`);return!0}isDomainAllowed(e){if(this.allowedDomains.length===0)return!0;try{const t=new URL(e);return this.allowedDomains.some(r=>t.hostname===r||t.hostname.endsWith(`.${r}`))}catch{return!1}}getFromCache(e){try{return this.validateUrl(e),this.cache.get(e)||[]}catch{return[]}}async fetchAndCache(e){if(this.validateUrl(e),!this.enabled)throw new Error("URL fetching is disabled. Enable it using the enableFetching method.");if(!this.isDomainAllowed(e))throw new Error(`Domain not allowed for URL: ${e}.`);let t;try{t=await this.fetchStrategy.fetchUrl(e)}catch(a){throw new Error(`Error fetching from URL: ${e}`,{cause:a})}const{data:r,contentType:i}=t;let s;if(i.includes("application/json")||i.includes("text/yaml")||i.includes("application/yaml")||i.includes("text/plain"))s=he(r);else throw new Error(`Unsupported content type from URL: ${i}`);if(s===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(s)?o=s.map(a=>g.deserialize(a)):o=[g.deserialize(s)],this.cache.set(e,o),o}prefetchUrl(e,t){try{this.validateUrl(e),this.cache.set(e,t)}catch{}}clearCache(){this.cache.clear()}setFetchStrategy(e){return this.fetchStrategy=e,this}getFetchStrategy(){return this.fetchStrategy}enableFetching(){return this.enabled=!0,this.allowedDomains=[],this}enableFetchingForDomains(e){return this.enabled=!0,this.allowedDomains=[...e],this}disableFetching(){return this.enabled=!1,this}isFetchingEnabled(){return this.enabled}getAllowedDomains(){return[...this.allowedDomains]}allowDomain(e){return this.allowedDomains.includes(e)||this.allowedDomains.push(e),this}disallowDomain(e){return this.allowedDomains=this.allowedDomains.filter(t=>t!==e),this}clearAllowedDomains(){return this.allowedDomains=[],this}}class qe{constructor(e,t,r,i=[],s=!1){this.blueId=e,this.content=t,this.isMultipleDocuments=r,this.documentBlueIds=i,this.isCyclicSet=s}}class Ft{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t,r){let i;try{const l=he(e);if(l===void 0)throw new Error;i=l}catch{throw new Error("Failed to parse content as YAML or JSON")}let s,o;const a=Array.isArray(i);if(a){const l=i.map(d=>g.deserialize(d)),c=r.prepareStorageNodeList(l,t);return s=c.blueId,o=c.nodes.map(d=>B.get(d)),new qe(s,o,!0,c.documentBlueIds,c.isCyclicSet??!1)}else{const l=g.deserialize(i),c=r.prepareStorageNode(l,t);s=c.blueId,o=B.get(c.node)}return new qe(s,o,a)}static parseAndCalculateBlueIdForNode(e,t,r){const i=r.prepareStorageNode(e,t),s=B.get(i.node);return new qe(i.blueId,s,!1)}static parseAndCalculateBlueIdForNodeList(e,t,r){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const i=r.prepareStorageNodeList(e,t),s=i.nodes.map(a=>B.get(a)),o=!0;return new qe(i.blueId,s,o,i.documentBlueIds,i.isCyclicSet??!1)}static resolveThisReferences(e,t,r){return this.resolveThisReferencesRecursive(e,t,r)}static resolveThisReferencesRecursive(e,t,r){if(e&&typeof e=="object"&&!Array.isArray(e)){const i={};for(const[s,o]of Object.entries(e))typeof o=="string"?s===N&&this.THIS_REFERENCE_PATTERN.test(o)?i[s]=this.resolveThisReference(o,t,r):i[s]=o:o&&typeof o=="object"?i[s]=this.resolveThisReferencesRecursive(o,t,r):i[s]=o;return i}else if(Array.isArray(e))return e.map(i=>i&&typeof i=="object"?this.resolveThisReferencesRecursive(i,t,r):i);return e}static resolveThisReference(e,t,r){if(r){if(!e.startsWith("this#"))throw new Error("For multiple documents, 'this' references must include an index (e.g., 'this#0')");return t+e.substring(4)}else{if(e==="this")return t;throw new Error("For a single document, only 'this' is allowed as a reference, not 'this#<id>'")}}}class fs extends ue{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const i=Array.isArray(r),s=Ft.resolveThisReferences(r,t,i);if(e.includes("#")){const o=e.split("#");if(o.length>1){const a=parseInt(o[1]);if(Array.isArray(s)&&a<s.length){const l=s[a];return[g.deserialize(l)]}else return a===0?[g.deserialize(s)]:null}}return Array.isArray(s)?s.map(o=>g.deserialize(o)):[g.deserialize(s)]}}class _r extends fs{nameToBlueIdsMap=new Map;findNodeByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t)return;if(t.length>1)throw new Error(`Multiple nodes found with name: ${e}`);const r=this.fetchByBlueId(t[0]);return r&&r.length>0?r[0]:void 0}findAllNodesByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t)return[];const r=[];for(const i of t){const s=this.fetchByBlueId(i);s&&r.push(...s)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}const ms=new Set(["required","uniqueItems"]),ys=new Set(["minLength","maxLength","minItems","maxItems","minFields","maxFields"]),gs=[F,me,ye,ge],Is=new Map([["DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",k],["7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",q],["5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",H],["4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",Y],["6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",ot],["G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",at]]),vs=new Map([["AERp8BWnuUsjoPciAeNXuUWS9fmqPNMdWbxmKn3tcitx",X.Contract],["Bz49DbfqKC1yJeCfv5RYPZUKTfb7rtZnmreCaz4RsXn5",X["Json Patch Entry"]],["DcoJyCh7XXxy1nR5xjy7qfkUgQ1GiZnKKSxh8DJusBSr",X.Channel],["9ZE5pGjtSGJgWJG7iAVz4iPEz5CatceX3yb3qp5MpAKJ",X.Handler],["7QACj919YMRvFCTELCf6jfQTp41RVhtHdE6bPazLUZQ6",X.Marker],["BrpmpNt5JkapeUvPqYcxgXZrHNZX3R757dRwuXXdfNM2",X["Document Processing Initiated"]],["C77W4kVGcxL7Mkx9WL9QESPEFFL2GzWAe647s1Efprt",X["Triggered Event Channel"]],["H2aCCTUcLMTJozWkn7HPUjyFBFxamraw1q8DyWk87zxr",X["Lifecycle Event Channel"]]]),Fr=new Map([...Is,...vs]);function Nt(n){const e=tt(n);return Array.isArray(e)?Ts(e):e}function Ts(n){const e=n.map(t=>g.deserialize(t));return L.hasIndexedThisReference(e)?Bs(e):n}function Bs(n){return new L().calculate(n).nodes.map(t=>tt(B.get(t)))}function tt(n){if(Array.isArray(n))return n.map(s=>tt(s));if(!$(n))return n;const e=Object.fromEntries(Object.entries(n).map(([s,o])=>[s,tt(o)])),t=e[N];typeof t=="string"&&(e[N]=Fr.get(t)??t);for(const s of gs){const o=e[s];o!==void 0&&(e[s]=Ss(o))}const r=Ps(e);if(r!==void 0)return r;const i=e[y.OBJECT_SCHEMA];return $(i)&&(e[y.OBJECT_SCHEMA]=Ns(i)),e}function Ps(n){if(!bs(n))return;const e=n[ee];return typeof e=="string"?Es(e):void 0}function bs(n){const e=n[F];return $(e)&&e[N]===k&&typeof n[ee]=="string"}function Es(n){const t=n.trim().match(/^\$\{\s*(.*)\s*\}$/u);if(!t)return;const r=t[1].trim(),i=r.match(/^document\(['"]([^'"]+)['"]\)$/u);if(i)return{$document:Ur(i[1])};if(r==="event")return{$event:"/"};if(r.startsWith("event."))return{$event:qt(r.slice(6))};if(r==="currentContract")return{$currentContract:"/"};if(r.startsWith("currentContract."))return{$currentContract:qt(r.slice(16))};if(r.startsWith("steps."))return{$steps:r.slice(6)}}function Ur(n){return n.startsWith("/")?n:`/${n}`}function qt(n){return Ur(n.split(".").map(e=>e.replace(/~/gu,"~0").replace(/\//gu,"~1")).join("/"))}function Ns(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,ws(e,t)]))}function ws(n,e){if(n==="enum"&&$(e)){const t=e[Te];if(Array.isArray(t))return t}return(ms.has(n)||ys.has(n))&&$(e)&&Object.prototype.hasOwnProperty.call(e,ee)?e[ee]:e}function Ss(n){if(!$(n)||Object.keys(n).length!==1)return n;const t=n[F];if(!$(t))return n;const r=t[N];if(typeof r!="string")return n;const i=Fr.get(r)??r;return ie.includes(i)?{[N]:i}:n}class Ve extends _r{[br]=!0;blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;aliasBlueIdMap=new Map;constructor(e,t={}){super();const r=Ve.collectAliasMappings(e);this.aliasBlueIdMap=new Map(Object.entries(r)),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const i of Object.values(r.packages))for(const[s,o]of Object.entries(i.aliases)){const a=t[s];if(a&&a!==o)throw new Error(`Conflicting alias mapping for ${s}`);t[s]=o}return t}loadRepositories(e){const t=[],r=new Map;for(const i of e)Object.values(i.packages).forEach(s=>{for(const[o,a]of Object.entries(s.contents)){const l=Ve.parseCyclicBlueId(o);if(!l){t.push({providedBlueId:o,content:a});continue}const c=r.get(l.baseBlueId)??[];c.push({index:l.index,content:a}),r.set(l.baseBlueId,c)}});t.forEach(({content:i,providedBlueId:s})=>{const o=Nt(i);this.storeContent(s,o,Array.isArray(o)),this.addContentNames(s,o)});for(const[i,s]of r){const o=Ve.toDenseCyclicContent(i,s),a=Nt(o);this.storeContent(i,a,!0),this.addContentNames(i,a)}}static parseCyclicBlueId(e){const t=/^(.*)#(\d+)$/.exec(e);return!t?.[1]||t[2]===void 0?null:{baseBlueId:t[1],index:Number.parseInt(t[2],10)}}static toDenseCyclicContent(e,t){return[...t].sort((i,s)=>i.index-s.index).map((i,s)=>{if(i.index!==s)throw new Error(`Cyclic repository content for ${e} is missing index ${s}.`);return i.content})}addContentNames(e,t){if(Array.isArray(t)){this.addListItemNames(e,t);return}const i=g.deserialize(t).getName();i&&this.addToNameMap(i,e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,i)=>{const o=g.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${i}`)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Ft.resolveThisReferences(t,e,r):null}fetchByBlueId(e){const t=this.resolveAliasBlueId(e);return t===void 0?null:super.fetchByBlueId(t)}storeContent(e,t,r){this.blueIdToContentMap.set(e,t),this.blueIdToMultipleDocumentsMap.set(e,r)}getBlueIds(){return Array.from(this.blueIdToContentMap.keys())}hasBlueId(e){const t=this.resolveAliasBlueId(e);return t===void 0?!1:this.blueIdToContentMap.has(this.getBaseBlueIdAndSuffix(t).baseBlueId)}resolveAliasBlueId(e){const t=this.aliasBlueIdMap.get(e);if(t!==void 0)return t;const{baseBlueId:r,suffix:i}=this.getBaseBlueIdAndSuffix(e);if(i===void 0)return e;const s=this.aliasBlueIdMap.get(r);if(s===void 0)return e;if(this.getBaseBlueIdAndSuffix(s).suffix===void 0)return`${s}${i}`}getBaseBlueIdAndSuffix(e){const t=e.indexOf("#");return t===-1?{baseBlueId:e}:{baseBlueId:e.slice(0,t),suffix:e.slice(t)}}}class Cs{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(ct).forEach(([s,o])=>{this.blueIdToInlineValue.set(s,o)});const i=r.getAllBlueIds();Object.entries(i).forEach(([s,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,s)})}restore(e){return M.transform(e,t=>this.restoreNode(t))}restoreNode(e){return this.restoreTypeField(e,()=>e.getType(),t=>e.setType(t)),this.restoreTypeField(e,()=>e.getItemType(),t=>e.setItemType(t)),this.restoreTypeField(e,()=>e.getKeyType(),t=>e.setKeyType(t)),this.restoreTypeField(e,()=>e.getValueType(),t=>e.setValueType(t)),e}restoreTypeField(e,t,r){const i=t();if(!i||i.isInlineValue()&&i.getValue()!==void 0)return;const s=i.getBlueId();if(!s)return;const o=this.resolveInlineValue(s,i);if(!o)return;const a=new h().setValue(o).setInlineValue(!0);r(a)}resolveInlineValue(e,t){const r=this.blueIdToInlineValue.get(e);if(r)return r;const i=t.getName();if(i)return this.blueIdToInlineValue.set(e,i),i;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Rs{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(As(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)js(this.contents,r.contents,r.name),zs(this.aliases,r.aliases,r.name)}getRuntimes(){return this.runtimes}getAliases(){return this.aliases}getContents(){return this.contents}findRuntimeByName(e){return this.runtimes.find(t=>t.name===e)}toCurrentBlueId(e){const t=this.aliases[e]??Ot[e]??e;for(const r of this.runtimes){const i=r.toCurrentBlueIdIndex[t];if(i)return i}return t}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=rr[t];if(r)return r;for(const i of this.runtimes){const s=i.typeAliasByCurrentBlueId[t];if(s)return s}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const i=r.types[t];if(i)return{runtime:r,currentBlueId:t,typeMeta:i,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function As(n){const e=Os(n);return Object.values(n.packages).forEach(t=>{Ms(e,n,t)}),{name:n.name,repositoryVersions:n.repositoryVersions,repoVersionIndexById:e.repoVersionIndexById,aliases:e.aliases,types:e.types,toCurrentBlueIdIndex:e.toCurrentBlueIdIndex,contents:e.contents,schemas:e.schemas,currentRepoBlueId:e.currentRepoBlueId,typeAliasByCurrentBlueId:e.typeAliasByCurrentBlueId,typePackageByCurrentBlueId:e.typePackageByCurrentBlueId}}function Os(n){const e=Object.fromEntries(n.repositoryVersions.map((r,i)=>[r,i])),t=n.repositoryVersions[n.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Ms(n,e,t){if(n.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);n.packageNames.add(t.name),Vs(n,t),Ds(n,e,t),Ls(n,t),xs(n,t)}function Vs(n,e){Object.entries(e.aliases).forEach(([t,r])=>{if(n.aliases[t]&&n.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);n.aliases[t]=r})}function Ds(n,e,t){Object.entries(t.typesMeta).forEach(([r,i])=>{if(n.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const s=_s(i,e,r,t.name);if(n.types[r]=s,n.typePackageByCurrentBlueId[r]=t.name,n.typeAliasByCurrentBlueId[r]=`${t.name}/${i.name}`,s.status===y.BLUE_REPOSITORY_STATUS_STABLE&&!n.toCurrentBlueIdIndex[r]&&(n.toCurrentBlueIdIndex[r]=r),s.status===y.BLUE_REPOSITORY_STATUS_STABLE)for(const o of s.versions){const a=n.toCurrentBlueIdIndex[o.typeBlueId];if(a&&a!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);n.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function Ls(n,e){Object.entries(e.contents).forEach(([t,r])=>{n.contents[t]=r})}function xs(n,e){n.schemas.push(...Object.values(e.schemas))}function _s(n,e,t,r){if(n.status===y.BLUE_REPOSITORY_STATUS_DEV)return Fs(n,e,t,r),{...n,versions:n.versions?[...n.versions]:n.versions};const i=[...n.versions??[]].sort((o,a)=>o.repositoryVersionIndex-a.repositoryVersionIndex);if(i.length===0)throw new Error(`Stable type ${r}/${n.name} (${t}) must have at least one version entry`);const s=new Set;return i.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${n.name}`);if(s.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${n.name}`);s.add(o.repositoryVersionIndex);for(const a of o.attributesAdded??[])Us(a,e.name,t,o.repositoryVersionIndex)}),{...n,versions:i}}function Fs(n,e,t,r){if(n.status===y.BLUE_REPOSITORY_STATUS_DEV){if(n.versions&&n.versions.length>1)throw new Error(`Dev type ${r}/${n.name} (${t}) must not declare multiple versions`);if(n.versions&&n.versions.length===1){const i=n.versions[0];if(i.repositoryVersionIndex<0||i.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${i.repositoryVersionIndex} for dev type ${r}/${n.name}`)}}}function Us(n,e,t,r){try{y.validateAttributesAddedPointer(n)}catch(i){const s=i instanceof Error?i.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${n}' for type ${t} in repository ${e} at index ${r}: ${s}`)}}function zs(n,e,t){for(const[r,i]of Object.entries(e)){const s=n[r];if(s&&s!==i)throw new Error(`Conflicting alias '${r}' across repositories: '${s}' vs '${i}' (from ${t})`);n[r]=i}}function js(n,e,t){for(const[r,i]of Object.entries(e)){if(r in n){const s=n[r];if(!$s(s,i))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}n[r]=i}}function $s(n,e){if(n===e)return!0;if(n===null||e===null||typeof n!="object"||typeof e!="object")return!1;const t=Qe.canonicalize(n),r=Qe.canonicalize(e);return t!==void 0&&t===r}const ks=new Set(["__proto__","constructor","prototype"]);function Kt(n){const e=n.at(0),t=n.at(-1);return!e||!t?n:e==="'"&&t==="'"||e==='"'&&t==='"'?n.slice(1,-1):n}function qs(n,e){const t=n.indexOf("=");if(t===-1)throw be(e,`Missing '=' in segment '${n.trim()}'`);if(n.indexOf("=",t+1)!==-1)throw be(e,`Unexpected '=' in segment '${n.trim()}'`);const r=Kt(n.slice(0,t).trim()),i=Kt(n.slice(t+1).trim());if(!r)throw be(e,"Repository name is empty");if(!i)throw be(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:i}}function Ks(n){if(n.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of n.split(",")){const r=t.trim();if(!r)throw be(n,"Empty repository segment");const{name:i,value:s}=qs(r,n);Hs(i,n),e[i]=s}return e}function Gs(n){return typeof n=="string"?Ks(n):n}function be(n,e){return new Ne(G.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:G.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:n,reason:e}}])}function Hs(n,e){if(ks.has(n))throw be(e,`Forbidden repository name '${n}'`)}function Ys(n,e){const t=n.filter(i=>i.repositoryVersionIndex>e).sort((i,s)=>s.repositoryVersionIndex-i.repositoryVersionIndex),r=[];for(const i of t){const s=[...i.attributesAdded].sort((o,a)=>Gt(a)-Gt(o));r.push(...s)}return r}function Gt(n){return y.parsePointer(n).length}const Ws=new Set([...Ct]),O={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class Zs{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return M.transform(e,t=>this.transformNode(t))}transformNode(e){return this.processTypeReference(e,{getter:()=>e.getType(),setter:t=>e.setType(t),schemaTraversalTargets:[e]}),this.processTypeReference(e,{getter:()=>e.getItemType(),setter:t=>e.setItemType(t),schemaTraversalTargets:e.getItems()??[]}),this.processTypeReference(e,{getter:()=>e.getKeyType(),setter:t=>e.setKeyType(t),schemaTraversalTargets:[]}),this.processTypeReference(e,{getter:()=>e.getValueType(),setter:t=>e.setValueType(t),schemaTraversalTargets:this.getDictionaryValueTargets(e)}),e}processTypeReference(e,t){const r=t.getter(),i=r?.getBlueId();if(!r||!i)return;const s=this.resolveType(i);switch(s.kind){case O.core:{r.setBlueId(s.blueId);return}case O.representable:{this.applyDropPointers([r],s.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,s.dropPointers),r.setBlueId(s.targetBlueId);return}case O.noRuntime:case O.noTargetContext:case O.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,i);return}throw s.kind===O.unrepresentable?s.error:this.unrepresentableError(i,s.kind===O.noTargetContext?`Repository '${s.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",s.kind===O.noTargetContext?s.runtime:void 0,s.kind===O.noTargetContext?s.meta:void 0,void 0,s.kind===O.noTargetContext?s.typeAlias:void 0)}}}resolveType(e){if(ie.includes(e))return{kind:O.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),i=this.registry.findRuntimeByBlueId(t);if(!i||!i.typeMeta)return{kind:O.noRuntime};const s=this.targetRepoVersionIndexes[i.runtime.name];if(s===void 0)return{kind:O.noTargetContext,currentBlueId:t,runtimeName:i.runtime.name,runtime:i.runtime,meta:i.typeMeta,typeAlias:r};const o=i.typeMeta;if(o.status===y.BLUE_REPOSITORY_STATUS_DEV){const p=i.runtime.repositoryVersions.length-1;if(s!==p)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${s}.`,i.runtime,o,s,r)};const f=o.versions?.[0];return{kind:O.representable,currentBlueId:t,targetBlueId:f?.typeBlueId??t,dropPointers:[]}}const a=o.versions||[];if(a.length===0)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,i.runtime,o,s,r)};const l=a[0].repositoryVersionIndex;if(s<l)return{kind:O.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${s}.`,i.runtime,o,s,r)};let c=a[0].typeBlueId;for(const p of a)p.repositoryVersionIndex<=s&&(c=p.typeBlueId);const d=o.status===y.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,s):[];return{kind:O.representable,currentBlueId:t,targetBlueId:c,dropPointers:d}}getDropPointers(e,t){return e.status!==y.BLUE_REPOSITORY_STATUS_STABLE?[]:Ys(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const i=r.rootIsSchema??!1;for(const s of t)for(const o of e)this.deletePropertyAtPointer(o,s,i)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,i])=>i instanceof h&&!Ws.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let i;try{i=y.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,i,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[i,...s]=t;if(i===F){const l=e.getType();l&&this.applyPointerSegments(l,s,!0);return}if(i===me){const l=e.getItemType();l&&this.applyPointerSegments(l,s,!0);return}if(i===ye){const l=e.getKeyType();l&&this.applyPointerSegments(l,s,!0);return}if(i===ge){const l=e.getValueType();l&&this.applyPointerSegments(l,s,!0);return}const o=e.getProperties();if(!o)return;if(s.length===0){if(!r||!(i in o))return;const l={...o};delete l[i],e.setProperties(l);return}const a=o[i];a instanceof h&&this.applyPointerSegments(a,s,r)}inlineDefinition(e,t,r){const i=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(i))throw this.unrepresentableError(i,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(i)});const s=this.registry.getContents()[i];if(!s)throw this.unrepresentableError(i,`Missing definition to inline for BlueId ${i}.`);this.inliningStack.add(i);try{const o=g.deserialize(s);o.setBlueId(void 0);const a=M.transform(o,l=>this.transformNode(l));return t(a),e}finally{this.inliningStack.delete(i)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new Ne(G.INVALID_REPOSITORY_POINTER,t,[{code:G.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,i,s,o,a){const l={currentTypeBlueId:e,targetRepoVersionIndex:s,typeAlias:o,...a};if(r&&(s!==void 0&&(l.requestedRepoBlueId=r.repositoryVersions[s]),l.serverRepoBlueId=r.currentRepoBlueId),i&&i.status===y.BLUE_REPOSITORY_STATUS_STABLE){const d=i.versions?.[0]?.repositoryVersionIndex;d!==void 0&&(l.typeIntroducedInRepoBlueId=r?.repositoryVersions[d])}const c={code:G.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[F],context:l};return new Ne(G.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[c])}}function We(n,e){return e?M.transform(n,t=>(Ke(()=>t.getType(),r=>t.setType(r),e),Ke(()=>t.getItemType(),r=>t.setItemType(r),e),Ke(()=>t.getKeyType(),r=>t.setKeyType(r),e),Ke(()=>t.getValueType(),r=>t.setValueType(r),e),t)):n}function Ke(n,e,t){const r=n();if(!r||r.isInlineValue())return;const i=r.getBlueId();if(!i)return;const s=t.toCurrentBlueId(i);s!==i&&e(r.clone().setBlueId(s))}class Js{registry;blueIdMapper;constructor(e){this.registry=e.registry,this.blueIdMapper=e.blueIdMapper}transform(e,t){const r=this.computeTargetRepoVersionIndexes(t);if(Object.keys(r).length===0)return e;const i=We(e,this.blueIdMapper);return new Zs({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(i)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?Gs(e.repositories):e.repositories;for(const[i,s]of Object.entries(r)){const o=this.registry.findRuntimeByName(i);if(!o)continue;const a=o.repoVersionIndexById[s];if(a===void 0)throw this.unknownRepoBlueIdError(i,s,o.currentRepoBlueId);t[i]=a}return t}unknownRepoBlueIdError(e,t,r){const i=`Unknown RepoBlueId '${t}' for repository '${e}'.`,s={code:G.REPO_UNKNOWN_REPO_BLUE_ID,message:i,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new Ne(G.REPO_UNKNOWN_REPO_BLUE_ID,i,[s])}}const ht={"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF":{name:"Contract",description:`Base Blue Contracts and Processor 1.0 runtime type for executable or processor-interpreted declarations under an active scope's contracts map. A Contract is scope-local, identity-bearing Blue content. The processor discovers materialized contract entries in the selected document, resolves each entry far enough to identify its effective runtime type BlueId, and either executes supported behavior or applies must-understand and fatal rules. Contract entries are sorted by effective order and contract-map key when ordering is required. A Contract by itself has no executable behavior; concrete subtypes define Channel, Handler, Marker, or extension semantics.
48
- `,order:{type:{blueId:"E2LM6qgzWG9ttagq2xTmiZkgYEAgkYedFCmU9v7NnVEq"},description:`Optional deterministic sort key within a scope. Missing order is treated as 0. Ordering compares order first, ascending, then contract-map key in lexicographic Unicode code-point order.
49
- `}},"61W96XosAp3DrEC7PuqLYtmF2A6ETpqH6qF2DgYwDq4c":{name:"Json Patch Entry",description:`Blue Contracts and Processor 1.0 runtime patch request produced by handlers. A Json Patch Entry describes one deterministic mutation request against the selected document. Only add, replace, and remove are supported. The path is a Blue Runtime Pointer and must not target the document root. Despite its historical name, Json Patch Entry is not full RFC 6902; it uses Blue-specific upsert, auto-materialization, runtime insertion normalization, and post-patch type-soundness rules. The val field is required for add and replace and must be absent for remove. Patches are applied in result order; each successful patch triggers its full Document Update cascade before the next patch is applied. Field is named val, not value, because value is Blue's scalar payload wrapper.
50
- `,op:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required patch operation. Allowed values are add, replace, and remove.
51
- `,schema:{required:!0,enum:["add","replace","remove"]}},path:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required absolute Blue Runtime Pointer identifying the mutation target. The empty string is invalid. The root pointer / is not a valid runtime patch target for handlers or channels.
52
- `,schema:{required:!0}},val:{description:`Patch payload for add and replace. It may be any valid Blue node. It must be absent for remove.
53
- `}},AMtAXPmvumgz1GxKUU9uv3ncXiKMENvqq8AaLvD5LXhv:{name:"Contract Execution Result",description:`Abstract processor result shape used to normalize effects returned by a supported handler or by a supported channel type that explicitly permits channel results. In Blue Contracts 1.0 core, patches and Triggered emissions are handler effects. External channels must not return patches or Triggered events unless a supported extension explicitly grants that capability. When a result is applied, the processor applies explicit gas first, then patches in order with immediate cascades, then emitted events in order, then a requested termination. Invalid present result fields cause runtime fatal termination before any effects from that result are applied, except for overhead already charged.
54
- `,patches:{type:{blueId:"8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF"},itemType:{type:{blueId:"61W96XosAp3DrEC7PuqLYtmF2A6ETpqH6qF2DgYwDq4c"}},description:`Optional list of patch entries. Missing is equivalent to an empty list. Patches are applied in list order. Each successful patch triggers its Document Update cascade before the next patch.
55
- `},triggeredEvents:{type:{blueId:"8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF"},description:`Optional list of Blue event nodes to record and enqueue as Triggered events after all patches from the same result are applied. Missing is equivalent to an empty list.
56
- `},gasConsumed:{type:{blueId:"E2LM6qgzWG9ttagq2xTmiZkgYEAgkYedFCmU9v7NnVEq"},description:`Optional non-negative explicit gas consumed by the contract. Missing is equivalent to 0. Negative gas is invalid and causes runtime fatal termination.
57
- `},termination:{description:`Optional termination request. If present, it requests graceful or fatal termination after gas, patches, and emitted events from the same result have been processed in the required order.
58
- `}},"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5":{name:"Channel",type:{blueId:"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF"},description:`Runtime contract role for event entry points within a scope. A Channel evaluates an incoming event or processor-managed delivery and either rejects it or accepts it by producing one channelized payload for same-scope handlers bound to that channel key. A Channel may consume gas and may request termination only through processor-defined interfaces. A Channel must not directly mutate the selected document. Processor-managed channel subtypes are fed only by the processor and are never directly entered by external events.
59
- `,event:{description:`Optional channel-specific matcher or matcher configuration. The meaning is defined by the concrete channel type.
60
- `}},"7X46P3Q6FJrogqKrBXTALpqzkieyyiQeatnqLvWzAPXE":{name:"Handler",type:{blueId:"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF"},description:`Runtime contract role for deterministic logic bound to exactly one channel in the same scope. A Handler is eligible only for deliveries produced by the same-scope channel named by its channel field. A Handler may request patches, emit Blue event nodes, consume non-negative gas, or request termination. It has no other permitted observable side effects. For a given document snapshot, channelized payload, handler contract content, and allowed context, a Handler must produce deterministic results.
61
- `,channel:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required same-scope contract-map key of the channel this handler binds to. Handlers do not bind to channels in parent, child, embedded, or referenced nodes.
62
- `,schema:{required:!0}},event:{description:`Optional handler-specific matcher for the channelized payload. The meaning is defined by the concrete handler type or extension runtime.
63
- `}},"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy":{name:"Marker",type:{blueId:"6WrVQoSpKHUUg5HPrwjkVV6pxe4sdkyGnakMs8ayEGeF"},description:`Runtime contract role for processor-observed state or policy. Markers do not run contract logic. The processor obeys supported marker semantics when a supported marker appears at the correct reserved key. Unsupported marker types in an active scope are subject to must-understand rules. Required processor-managed markers have reserved keys under contracts and must not appear under other keys.
64
- `},"8FVc8MPz6DcTMgcY3RXU6EBpGa9arWPJ141K2H86yi8Q":{name:"Process Embedded",type:{blueId:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy"},description:`Required processor-managed marker at contracts/embedded. It declares embedded child scopes beneath the current scope. The processor reads paths dynamically during embedded traversal, re-reads after each processed child, processes each normalized child path at most once per parent invocation, and rejects malformed, duplicate, self-root, or non-object embedded scope paths according to the processor rules. Missing child paths are skipped and marked processed for the current invocation.
65
- `,paths:{type:{blueId:"8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF"},itemType:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"}},description:`Required list of scope-relative Blue Runtime Pointers identifying embedded child roots. Each path must begin with /, must not be /, and must resolve inside the current scope's pointer domain. Duplicate resolved child paths are invalid.
66
- `,schema:{required:!0,uniqueItems:!0}}},"6JjyUKoK7uJxA5NY9YhMaKJbXC6c9iHyx1khv4gaAq4Q":{name:"Processing Initialized Marker",type:{blueId:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy"},description:`Required processor-managed marker at contracts/initialized. It records that a scope has completed first-run initialization. The processor publishes the Document Processing Initiated lifecycle event before writing this marker. The marker is written by a processor-managed patch that triggers the normal Document Update cascade. The marker stores the pre-initialization Content BlueId of the scope subtree as documentId.
67
- `,documentId:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required BlueId string for the pre-initialization Content BlueId of the scope subtree. The value must be a valid Blue Language BlueId string.
68
- `,schema:{required:!0}}},GBDBthfshBFr4GQKUU1fmy4GnPL7q2y3as4deUWpuBtu:{name:"Processing Terminated Marker",type:{blueId:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy"},description:`Required processor-managed marker at contracts/terminated. It records final runtime state for a scope. A scope with a valid pre-existing terminated marker is inactive for processing: it incurs scope-entry gas when entered, but it is not initialized, matched, bridged, drained, checkpointed, or run. Termination markers are written by processor Direct Write and do not emit Document Update cascades. An ancestor may replace or remove an embedded child root containing this marker as a whole.
69
- `,cause:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required termination cause. fatal means deterministic runtime fatal termination. graceful means contract-requested non-error termination.
70
- `,schema:{required:!0,enum:["fatal","graceful"]}},reason:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Optional human-readable deterministic reason supplied by the processor or contract. It is content in the selected document and in emitted lifecycle events when present.
71
- `}},"9GEC24YbFG9hj4banjYh2oEnDpAob1wAPmhjuykJp8T1":{name:"Channel Event Checkpoint",type:{blueId:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy"},description:`Required processor-managed marker at contracts/checkpoint. It stores idempotency state for external channel deliveries. Checkpoints are never used for processor-managed Document Update, Triggered Event, Lifecycle Event, or Embedded Node channels. The processor creates this marker lazily when an external channel accepts an event and no checkpoint exists. It updates lastEvents by Direct Write after successful external channel processing. Checkpoint Direct Writes do not emit Document Update cascades. By default, lastEvents stores the normalized checkpoint subject for each external channel's raw contract-map key, and newness is determined by the channel's effective checkpointIdentityMode. Pointer escaping is used only when writing the member by Direct Write; it is not part of the stored key.
72
- `,lastEvents:{type:{blueId:"Efkz9D1ARMM7rU43w3rDNVqat1naS6qXKCqP4eHin3yG"},keyType:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"}},description:`Required dictionary keyed by raw external-channel contract-map key. Each value is the previous normalized checkpoint subject for that external channel. The default subject is the preprocessed incoming event node.
73
- `,schema:{required:!0}}},Fbenow6tanFHkWzKiDD8fGxminQswQ1FecMRakaCx2WX:{name:"Type Generalization Policy",type:{blueId:"6zqbYGDGrMv5ReuEsjyzyyjjuqVnqDZxtY7RsPXdBTNy"},description:`Optional processor-managed marker at contracts/generalization. It controls whether post-patch type soundness may be restored by dynamic type generalization in the current scope. If absent, the processor uses defaultMode nearest-valid with no rules. Handlers and channels must not patch this marker or its descendants in Blue Contracts and Processor 1.0.
74
- `,defaultMode:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Optional default generalization mode for paths not governed by a more specific rule. Missing means nearest-valid. nearest-valid permits the processor to choose the nearest valid permitted ancestor type. reject makes a patch fatal when restoring soundness would require generalization.
75
- `,schema:{enum:["nearest-valid","reject"]}},rules:{type:{blueId:"8DSFoWG9MqRSUhStqoPLrwVQiYByRh18NWbDEarN8MKF"},itemType:{type:{blueId:"7Vnmk8StjwY7e9mBNpACrn8oh3KZ7yQBjnXe5bLDWn4D"}},description:`Optional ordered list of path-specific generalization rules. The most specific matching path wins; if two rules normalize to the same path, the later rule in list order wins.
76
- `}},"7Vnmk8StjwY7e9mBNpACrn8oh3KZ7yQBjnXe5bLDWn4D":{name:"Type Generalization Rule",description:`Rule entry used by Type Generalization Policy. It governs a scope-relative subtree path and can reject dynamic generalization or require the generated type to remain equal to or a subtype of a declared floor type.
77
- `,path:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required scope-relative Blue Runtime Pointer identifying the governed subtree. The pointer is normalized against the scope containing the policy marker before rule selection.
78
- `,schema:{required:!0}},mode:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Optional mode for this path. Missing means the policy defaultMode. reject forbids generalization at the governed path. nearest-valid permits the nearest valid permitted ancestor type.
79
- `,schema:{enum:["nearest-valid","reject"]}},mustRemainSubtypeOf:{description:`Optional type reference floor. If present, any generated type selected for the governed path must be equal to or a subtype of this type.
80
- `}},Ac9LC5T7pHVa1TtkhMBjBRtxecShzvbe7ugUdXT1Mu2o:{name:"Document Update Channel",type:{blueId:"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5"},description:`Processor-managed channel fed after each successful runtime patch. For every successful patch, the processor discovers matching Document Update Channels from the post-patch selected document and delivers one Document Update payload per participating scope, from the patch origin scope toward root. A Document Update Channel matches when the absolute changed path is descendant-or-equal to the channel path resolved against the receiving scope. The channel is never checkpoint-gated and is never entered directly by external events. Triggered FIFO is not drained during Document Update cascades.
81
- `,path:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required scope-relative Blue Runtime Pointer watched by this channel. The channel matches patches whose absolute changed path is descendant-or-equal to ABS(scope, path).
82
- `,schema:{required:!0}}},"5HwxfbwRBCxG8xYpowWkCPC9akqUSKV7So2M4QHEmLsZ":{name:"Triggered Event Channel",type:{blueId:"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5"},description:`Processor-managed channel that drains events emitted into a scope's Triggered FIFO. A scope drains its Triggered FIFO at most once per PROCESS invocation, during the scope's FIFO phase. Triggered FIFO delivery does not occur during Document Update cascades. If a scope has no Triggered Event Channel, emitted events are still recorded and may be bridged to a parent, but they are not locally delivered.
83
- `},"2DXGQUiQBQ6CT89jwAsTAXaEPhLgiSXhKCGh9Q7Hv3MQ":{name:"Lifecycle Event Channel",type:{blueId:"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5"},description:`Processor-managed channel for lifecycle events emitted by the processor at a scope. Lifecycle events include Document Processing Initiated and Document Processing Terminated. Lifecycle events are delivered through Lifecycle Event Channels, recorded as bridgeable emissions for parent Embedded Node Channels, and, at root, appended to the root outbox. Lifecycle events are not enqueued into the Triggered FIFO unless a lifecycle handler explicitly emits a Triggered event.
84
- `},H6iUJp3GcLypsJDimMSVoxQQdxxuD8j6eqEUWWqCZ6i:{name:"Embedded Node Channel",type:{blueId:"4FAZ94JPExNM4pn2ZhtdHa4CVP7uASmLNVrBy7aCG1p5"},description:`Processor-managed channel in a parent scope that bridges recorded emissions from a processed embedded child scope. Bridging occurs after the parent has handled the external event and before the parent drains its Triggered FIFO. Child emissions are delivered in the order recorded by the child, and child scopes are bridged in the parent invocation's processed-path insertion order. Bridge gas is charged only when an emission is actually delivered to at least one matching Embedded Node Channel.
85
- `,childPath:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required scope-relative Blue Runtime Pointer identifying the embedded child root whose emissions this channel receives. The resolved child path is compared with the processed child scope path.
86
- `,schema:{required:!0}}},"7HEaG1SpBdsbVHsrwRTZSZGmpJUWHfFoEzecYWpjo1vm":{name:"Document Update",description:`Processor-emitted event delivered through Document Update Channels after each successful runtime patch. One Document Update payload is created per participating receiving scope for that patch. The path is relative to the receiving scope. before and after are immutable snapshots of the changed path before and after the patch, using null when the changed path was absent or removed. All handlers at the same receiving scope for the same patch see the same immutable payload object.
87
- `,op:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required operation that caused the update: add, replace, or remove.
88
- `,schema:{required:!0,enum:["add","replace","remove"]}},path:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required path of the changed node, relative to the receiving scope. / means the receiving scope root itself.
89
- `,schema:{required:!0}},before:{description:`Snapshot at the changed path before the patch, or null when absent.
90
- `},after:{description:`Snapshot at the changed path after the patch, or null when removed.
91
- `}},Ht1o66MTLKf7JmnEiR27rRLSwdz8FUTgf2mGPNuLSDUL:{name:"Document Processing Initiated",description:`Processor-emitted lifecycle event published at a scope before the Processing Initialized Marker is written. It represents first-run initialization of that scope for the current selected document state. At root, this event is also recorded in the root outbox. At non-root scopes, it is bridgeable to a parent Embedded Node Channel. The documentId field is the pre-initialization Content BlueId of the scope subtree.
92
- `,documentId:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required BlueId string for the pre-initialization Content BlueId of the scope subtree.
93
- `,schema:{required:!0}}},"4HWncQEQsdpk8zcXxYxgdtoXo5nKHxFPWeJfTscCbmeK":{name:"Document Processing Terminated",description:`Processor-emitted lifecycle event published at a scope when that scope terminates gracefully or fatally. It is delivered through Lifecycle Event Channels, recorded as bridgeable for parent Embedded Node Channels, and, at root, included in the root outbox. For a root fatal termination, this event appears before Document Processing Fatal Error.
94
- `,cause:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Required termination cause: fatal or graceful.
95
- `,schema:{required:!0,enum:["fatal","graceful"]}},reason:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Optional deterministic reason for termination.
96
- `}},AMZbj5tNGxjPrvaNyw56sfqcLSW2j1XmkncEYUVtgmVC:{name:"Document Processing Fatal Error",description:`Processor-emitted root outbox event appended when root processing terminates fatally. It is appended after Document Processing Terminated for the same root termination sequence. It is outbox-only: it is not delivered to Lifecycle Event Channels, is not recorded as bridgeable, and is not placed in the Triggered FIFO.
97
- `,reason:{type:{blueId:"GX7CFUmSDrE2MzptunLCCdZwnuwwrenRQqEnHL4x3uoC"},description:`Optional deterministic fatal error reason.
98
- `}}},Xs=Object.fromEntries(Object.entries(ht).map(([n,e])=>[e.name,n])),Qs=Object.fromEntries(Object.entries(ht).map(([n,e])=>[n,{status:"stable",name:e.name,versions:[{repositoryVersionIndex:0,typeBlueId:n,attributesAdded:[]}]}])),Ht={name:"blue.builtin-runtime-types",repositoryVersions:["blue.builtin-runtime-types/v1"],packages:{builtinRuntimeTypes:{name:"builtinRuntimeTypes",aliases:{},typesMeta:Qs,contents:ht,schemas:{}}}};class zr{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=_;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:i,repositories:s,mergingProcessor:o}=e,a=this.includeBuiltinRuntimeTypesRepository(s);this.repositories=a,this.repositoryRegistry=new Rs(a),this.blueContextResolver=new Js({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry}),this.mergingProcessor=o??_t();const l=Lt(()=>[]);this.nodeProvider=this.wrapNodeProviderWithRepositories(t||l,a),this.typeSchemaResolver=r??new vr([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.urlContentFetcher=new ps(i),this.blueDirectivePreprocessor=new ds(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new xr,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const c=this.repositoryRegistry.getRuntimes().flatMap(d=>d.schemas);c.length>0&&this.typeSchemaResolver?.registerSchemas(c)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),i=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return B.get(i,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),i=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return ls.get(i,{strategy:r.format})}nodeToSchemaOutput(e,t){return new Lr(this.typeSchemaResolver,{calculateBlueId:i=>this.calculateBlueIdSync(i)}).convert(e,t)}resolve(e,t=_){const r=this.combineWithGlobalLimits(t),s=new pe(this.mergingProcessor,this.nodeProvider).resolve(e,r);if(!(r instanceof re)){const o=this.getExactReferenceBlueId(e);o!==void 0&&s.setSourceSemanticBlueId(o)}return s}createResolvedNode(e){return e instanceof te?e:new te(e)}reverse(e){return this.minimize(e)}minimize(e){return new Ye({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).minimize(e)}restoreInlineTypes(e){return new Cs({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new xt(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(g.deserialize(e));return We(t,this.repositoryRegistry)}jsonValueToNodeUnchecked(e){const t=this.preprocess(g.deserializeUnchecked(e));return We(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(g.deserialize(e));return We(t,this.repositoryRegistry)}yamlToNode(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}yamlToNodeUnchecked(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeUnchecked(t)}async yamlToNodeAsync(e){const t=he(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeAsync(t)}prepareForBlueIdCalculation=async e=>e instanceof h||Array.isArray(e)&&e.every(t=>t instanceof h)?e:this.jsonValueToNodeAsync(e);calculateBlueId=async e=>{const t=await this.prepareForBlueIdCalculation(e);return new Ye({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).calculateBlueId(t)};prepareForBlueIdCalculationSync=e=>e instanceof h||Array.isArray(e)&&e.every(t=>t instanceof h)?e:this.jsonValueToNode(e);calculateBlueIdSync(e){const t=this.prepareForBlueIdCalculationSync(e);return new Ye({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).calculateBlueIdSync(t)}getTypeAliasByBlueId(e){const t=e?.trim();if(t)return this.repositoryRegistry.getTypeAlias(t)}addPreprocessingAliases(e){this.blueDirectivePreprocessor.addPreprocessingAliases(e)}preprocess(e){const t=this.blueDirectivePreprocessor.process(e);return new Ue({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new Ue({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return M.transform(e,t)}getNodeProvider(){return this.nodeProvider}setNodeProvider(e){return this.nodeProvider=this.wrapNodeProviderWithRepositories(e,this.repositories),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getExactReferenceBlueId(e){if(!C.hasBlueIdOnly(e))return;const t=e.getReferenceBlueId();return t!==void 0&&K.isPotentialBlueId(t)?t:void 0}getTypeSchemaResolver(){return this.typeSchemaResolver}setTypeSchemaResolver(e){return this.typeSchemaResolver=e,this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}getUrlContentFetcher(){return this.urlContentFetcher}setUrlFetchStrategy(e){return this.urlContentFetcher.setFetchStrategy(e),this}enablePreprocessingDirectivesFetchForUrls(){return this.urlContentFetcher.enableFetching(),this}enablePreprocessingDirectivesFetchForDomains(e){return this.urlContentFetcher.enableFetchingForDomains(e),this}allowUrlFetchingForDomain(e){return this.urlContentFetcher.allowDomain(e),this}disallowUrlFetchingForDomain(e){return this.urlContentFetcher.disallowDomain(e),this}getAllowedUrlFetchingDomains(){return this.urlContentFetcher.getAllowedDomains()}disablePreprocessingDirectivesFetchForUrls(){return this.urlContentFetcher.disableFetching(),this}isPreprocessingDirectivesFetchForUrlsEnabled(){return this.urlContentFetcher.isFetchingEnabled()}includeBuiltinRuntimeTypesRepository(e){const t=e??[];return t.some(r=>r.name===Ht.name)?t:[Ht,...t]}getPreprocessingAliases(){return this.blueDirectivePreprocessor.getPreprocessingAliases()}setPreprocessingAliases(e){return this.blueDirectivePreprocessor.setPreprocessingAliases(e),this}registerBlueIds(...e){return this.blueIdsMappingGenerator.registerBlueIds(...e),this}getAllRegisteredBlueIds(){return this.blueIdsMappingGenerator.getAllBlueIds()}getAllBlueIdNames(){return this.blueIdsMappingGenerator.getAllBlueIdNames()}getBlueIdsMappingGenerator(){return this.blueIdsMappingGenerator}isTypeOf(e,t,r){return Q.isTypeOf(e,t,{checkSchemaExtensions:r?.checkSchemaExtensions,typeSchemaResolver:this.typeSchemaResolver,blueIdMapper:this.repositoryRegistry})}isTypeOfBlueId(e,t){const r=this.repositoryRegistry.toCurrentBlueId(t.trim());if(r.length===0)return!1;const i=e.getType();if(!i)return!1;const s=new h().setReferenceBlueId(r);return A(i,s,this.nodeProvider)}isTypeOfNode(e,t,r={}){return new qi(this).matchesType(e,t,this.globalLimits,r)}setGlobalLimits(e){return this.globalLimits=e??_,this}getGlobalLimits(){return this.globalLimits}normalizeNodeToJsonOptions(e){return typeof e=="string"?{format:e,blueContext:void 0}:{format:e?.format??"official",blueContext:e?.blueContext}}wrapNodeProviderWithRepositories(e,t){return t&&t.length>0?new Ce([new Ve(t,{mergingProcessor:this.mergingProcessor}),oe.wrap(e)]):oe.wrap(e)}combineWithGlobalLimits(e){return this.globalLimits==_?e:e==_?this.globalLimits:_e.of(this.globalLimits,e)}}const en=Object.freeze(Object.defineProperty({__proto__:null,Blue:zr},Symbol.toStringTag,{value:"Module"}));exports.BUILTIN_RUNTIME_TYPE_CONTENT_BY_BLUE_ID=ht;exports.BUILTIN_RUNTIME_TYPE_NAME_TO_BLUE_ID_MAP=Xs;exports.Base58Sha256Provider=ir;exports.BasicTypesVerifier=Mr;exports.BigDecimalNumber=V;exports.BigIntegerNumber=R;exports.Blue=zr;exports.Blue$1=en;exports.BlueIdCalculator=E;exports.BlueNode=h;exports.BlueNodeTypeSchema=Q;exports.CORE_TYPE_NAME_TO_BLUE_ID_MAP=lt;exports.CyclicSetIdentityService=L;exports.DictionaryProcessor=Rr;exports.JsonCanonicalizer=Qe;exports.LIST_CONTROL_PREVIOUS=ce;exports.LIST_CONTROL_REPLACE=st;exports.Limits=dt;exports.ListProcessor=Cr;exports.MergeReverser=j;exports.Merger=pe;exports.MetadataPropagator=Vr;exports.NodeContentHandler=Ft;exports.NodeDeserializer=g;exports.NodeProviderWrapper=oe;exports.NodeResolver=Er;exports.NodeToBlueIdInput=ne;exports.NodeToMapListOrValue=B;exports.NodeToObjectConverter=Lr;exports.Nodes=C;exports.OBJECT_BLUE_ID=N;exports.OBJECT_DESCRIPTION=le;exports.OBJECT_NAME=ae;exports.OBJECT_SPECIFIC_KEYS=Ct;exports.OBJECT_VALUE=ee;exports.PathLimits=ke;exports.PathLimitsBuilder=et;exports.PreloadedNodeProvider=_r;exports.Preprocessor=Ue;exports.Properties=Hr;exports.ResolvedBlueNode=te;exports.SCHEMA_FIELDS=ut;exports.Schema=je;exports.SchemaPropagator=Ar;exports.SchemaVerifier=Or;exports.SemanticIdentityService=Ye;exports.SequentialMergingProcessor=Nr;exports.StorageShapeValidator=Pe;exports.TypeAssigner=Sr;exports.TypeSchemaResolver=vr;exports.ValuePropagator=wr;exports.baseBlueObjectSchema=ze;exports.blueDescriptionField=yi;exports.blueIdField=Ii;exports.blueIdSchema=Wr;exports.blueLanguageErrorCategory=pi;exports.blueNameField=vi;exports.blueNodeField=Ti;exports.blueObjectBooleanValueSchema=Xr;exports.blueObjectNumberValueSchema=Jr;exports.blueObjectSchema=Ze;exports.blueObjectStringListItemsSchema=Qr;exports.blueObjectStringValueSchema=Zr;exports.canonicalizeRepositoryContent=Nt;exports.createDefaultMergingProcessor=_t;exports.createNodeProvider=Lt;exports.getBlueDescriptionAnnotation=ar;exports.getBlueIdAnnotation=cr;exports.getBlueNameAnnotation=dr;exports.getBlueNodeAnnotation=pr;exports.getTypeBlueIdAnnotation=fr;exports.isBigDecimalNumber=Je;exports.isBigIntegerNumber=W;exports.isBigNumber=x;exports.isBlueNodeSchema=Dt;exports.isJsonBlueArray=Mt;exports.isJsonBlueObject=$;exports.isJsonBlueValue=ri;exports.isUrl=Me;exports.jsonBlueValueSchema=Xe;exports.withBlueDescription=or;exports.withBlueId=lr;exports.withBlueName=ur;exports.withBlueNode=hr;exports.withTypeBlueId=Pi;exports.yamlBlueDump=Br;exports.yamlBlueParse=he;