@blue-labs/language 4.0.0-rc.0 → 4.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("big.js"),u=require("@blue-labs/shared-utils"),h=require("zod"),Dr=require("bs58"),K=require("radash"),B=require("@blue-labs/repository-contract"),_r=require("js-sha256"),Lr=require("crypto"),jr=require("base32.js"),fe=require("js-yaml"),Ft=i=>i&&i.__esModule?i:{default:i},Oe=Ft(Dr),it=Ft(Lr);class D extends G{constructor(e){super(e)}}class O extends G{constructor(e){super(e)}}const ae="name",ce="description",U="type",Ne="itemType",Pe="keyType",Se="valueType",J="value",Y="items",V="blueId",_e="blue",Tt=[ae,ce,U,Ne,Pe,Se,J,Y,V,_e],zt="Text",Ut="Double",Kt="Integer",kt="Boolean",Ht="List",Yt="Dictionary",Ge=[zt,Ut,Kt,kt],vt=[...Ge,Ht,Yt],re="DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",se="7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",ie="5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",ne="4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",Ze="6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",Bt="G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",bt=[re,se,ie,ne],ye=[...bt,Ze,Bt],Wt=Object.fromEntries(vt.map((i,e)=>[i,ye[e]])),qe=Object.fromEntries(ye.map((i,e)=>[i,vt[e]])),$r=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:Ge,BASIC_TYPE_BLUE_IDS:bt,BOOLEAN_TYPE:kt,BOOLEAN_TYPE_BLUE_ID:ne,CORE_TYPES:vt,CORE_TYPE_BLUE_IDS:ye,CORE_TYPE_BLUE_ID_TO_NAME_MAP:qe,CORE_TYPE_NAME_TO_BLUE_ID_MAP:Wt,DICTIONARY_TYPE:Yt,DICTIONARY_TYPE_BLUE_ID:Bt,DOUBLE_TYPE:Ut,DOUBLE_TYPE_BLUE_ID:se,INTEGER_TYPE:Kt,INTEGER_TYPE_BLUE_ID:ie,LIST_TYPE:Ht,LIST_TYPE_BLUE_ID:Ze,OBJECT_BLUE:_e,OBJECT_BLUE_ID:V,OBJECT_CONTRACTS:B.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:ce,OBJECT_ITEMS:Y,OBJECT_ITEM_TYPE:Ne,OBJECT_KEY_TYPE:Pe,OBJECT_MERGE_POLICY:B.OBJECT_MERGE_POLICY,OBJECT_NAME:ae,OBJECT_SCHEMA:B.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:Tt,OBJECT_TYPE:U,OBJECT_VALUE:J,OBJECT_VALUE_TYPE:Se,TEXT_TYPE:zt,TEXT_TYPE_BLUE_ID:re},Symbol.toStringTag,{value:"Module"}));class xr{static get(e,t,r,s=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return s&&o!==void 0?o:e}const n=t.substring(1).split("/");return this.getRecursive(e,n,0,r,s)}static getRecursive(e,t,r,s,n){if(r===t.length-1&&!n)return this.getNodeForSegment(e,t[r],s,!1);if(r===t.length){const a=e.getValue();return n&&a!==void 0?a:e}const o=t[r],l=this.getNodeForSegment(e,o,s,!0);if(l)return this.getRecursive(l,t,r+1,s,n)}static getNodeForSegment(e,t,r,s){let n;const o=e.getProperties();if(o&&t in o)n=o[t];else switch(t){case"name":{const l=e.getName();n=new d().setValue(l??null);break}case"description":{const l=e.getDescription();n=new d().setValue(l??null);break}case"type":n=e.getType();break;case"itemType":n=e.getItemType();break;case"keyType":n=e.getKeyType();break;case"valueType":n=e.getValueType();break;case"value":{const l=e.getValue();n=new d().setValue(l??null);break}case"blueId":{const l=e.getBlueId();n=new d().setValue(l??null);break}case"blue":n=e.getBlue();break;case"items":{const l=e.getItems();n=new d().setItems(l);break}case"properties":{const l=e.getProperties();n=new d().setProperties(l);break}case B.OBJECT_CONTRACTS:{const l=e.getContracts();n=new d().setContracts(l);break}default:{if(/^\d+$/.test(t)){const l=parseInt(t,10),a=e.getItems();a&&l>=0&&l<a.length?n=a[l]:n=void 0}else n=void 0;break}}if(n)return s&&r?this.link(n,r):n}static link(e,t){const r=t(e);return u.isNonNullable(r)?r:e}}class d{static INTEGER=new d("Integer");name;description;type;itemType;keyType;valueType;value;items;properties;blueId;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 d().setValue(e).setInlineValue(!0):this.type=e,this}getItemType(){return this.itemType}setItemType(e){return typeof e=="string"?this.itemType=new d().setValue(e).setInlineValue(!0):this.itemType=e,this}getKeyType(){return this.keyType}setKeyType(e){return typeof e=="string"?this.keyType=new d().setValue(e).setInlineValue(!0):this.keyType=e,this}getValueType(){return this.valueType}setValueType(e){return typeof e=="string"?this.valueType=new d().setValue(e).setInlineValue(!0):this.valueType=e,this}getValue(){const e=this.type?.getBlueId();if(u.isNonNullable(e)&&u.isNonNullable(this.value)){if(e===ie&&typeof this.value=="string")return new O(this.value);if(e===se&&typeof this.value=="string"){const t=new D(this.value),r=parseFloat(t.toString());return new D(r.toString())}else if(e===ne&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new O(e.toString()):this.value=new D(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}addProperty(e,t){return this.properties||(this.properties={}),this.properties[e]=t,this}removeProperty(e){return this.properties&&delete this.properties[e],this}getContractsProperty(){return this.properties?.[B.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}setContracts(e){return u.isNullable(e)?this.removeProperty(B.OBJECT_CONTRACTS):this.addProperty(B.OBJECT_CONTRACTS,new d().setProperties(e)),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(B.OBJECT_CONTRACTS,new d().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(B.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)}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 xr.get(this,e,t)}getAsNode(e){const t=this.get(e);if(t instanceof d)return t;throw new Error(`Value at path ${e} is not a BlueNode: ${t}`)}getAsInteger(e){const t=this.get(e);if(t instanceof O||t instanceof D)return t.toNumber();throw new Error(`Value at path ${e} is not a BigInteger or BigDecimal: ${t}`)}clone(){const e=new d(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()]))),e.blueId=this.blueId,e.blue=this.blue?.clone(),e.inlineValue=this.inlineValue,e}cloneShallow(){const e=new d(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.blueId=this.blueId,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 Te{static MIN_BLUE_ID_LENGTH=41;static MAX_BLUE_ID_LENGTH=45;static BLUE_ID_PATTERN=/^[1-9A-HJ-NP-Za-km-z]{41,45}(?:#\d+)?$/;static isPotentialBlueId(e){if(!e||e.length===0||!this.BLUE_ID_PATTERN.test(e))return!1;const t=e.split("#"),r=t[0],s=r.length;if(s<this.MIN_BLUE_ID_LENGTH||s>this.MAX_BLUE_ID_LENGTH)return!1;try{if(Oe.default.decode(r).length!==32)return!1}catch{return!1}if(t.length>1)try{if(Number(t[1])<0)return!1}catch{return!1}return!0}}const Fr=h.z.string().max(Te.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(Te.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(i=>{try{return Oe.default.decode(i),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),ve=h.z.lazy(()=>h.z.record(h.z.unknown()).and(h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:ve.optional(),value:h.z.union([h.z.string(),h.z.number(),h.z.boolean()]).optional().nullable(),items:h.z.array(ve).optional()}))),Le=h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:ve.optional()}),zr=Le.extend({value:h.z.string().optional()}),Ur=Le.extend({value:h.z.number().optional()}),Kr=Le.extend({value:h.z.boolean().optional()}),kr=Le.extend({items:h.z.array(h.z.string()).optional()}),Hr=i=>ve.safeParse(i).success,Jt=i=>u.isNonNullable(i)&&"blueId"in i&&u.isNonNullable(i.blueId),Yr=i=>u.isNonNullable(i)&&"name"in i&&u.isNonNullable(i.name),Gt=i=>u.isNonNullable(i)&&"items"in i&&u.isNonNullable(i.items),Zt=i=>u.isNonNullable(i)&&"type"in i&&u.isNonNullable(i.type),qt=i=>u.isNonNullable(i)&&"value"in i&&u.isNonNullable(i.value),Wr=(i,e)=>i.required({type:!0}).safeParse(e).success,w=i=>i instanceof G,ee=i=>w(i)&&i instanceof O,Ue=i=>w(i)&&i instanceof D,Jr=h.z.lazy(()=>h.z.record(Ve)),Gr=h.z.lazy(()=>h.z.union([h.z.array(Ve),h.z.array(Ve).readonly()])),Ve=h.z.lazy(()=>h.z.union([u.jsonPrimitiveSchema,Jr,Gr,h.z.instanceof(G)])),Nt=i=>K.isObject(i)&&!K.isArray(i)&&!u.isReadonlyArray(i)&&!w(i),Pt=i=>K.isArray(i)||u.isReadonlyArray(i),Zr=i=>Pt(i)||Nt(i)||w(i)||u.isJsonPrimitive(i);class m{static deserialize(e){return m.handleNode(e)}static handleNode(e){if(e===void 0)throw new Error("This is not a valid JSON-like value. Found 'undefined' as a value.");if(Nt(e)){const t=new d,r={};return Object.entries(e).forEach(([s,n])=>{switch(s){case ae:if(n==null)t.setName(void 0);else{if(typeof n!="string")throw new Error(`The ${ae} field must be a string.`);t.setName(n)}break;case ce:if(n==null)t.setDescription(void 0);else{if(typeof n!="string")throw new Error(`The ${ce} field must be a string.`);t.setDescription(n)}break;case U:t.setType(m.handleNode(n));break;case Ne:t.setItemType(m.handleNode(n));break;case Pe:t.setKeyType(m.handleNode(n));break;case Se:t.setValueType(m.handleNode(n));break;case J:t.setValue(m.handleValue(n));break;case V:if(typeof n!="string")throw new Error(`The ${V} field must be a string.`);t.setBlueId(n);break;case Y:t.setItems(m.handleArray(n));break;case _e:t.setBlue(m.handleNode(n));break;default:r[s]=m.handleNode(n);break}}),Object.keys(r).length>0&&t.setProperties(r),t}else{if(Pt(e))return new d().setItems(m.handleArray(e));{const t=e;return new d().setValue(m.handleValue(t)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||w(e))if(ee(e)||Number.isSafeInteger(e)){const t=new O(e.toString()),r=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER;return t.lt(r)?new O(r.toString()):t.gt(s)?new O(s.toString()):t}else{const t=parseFloat(e.toString());return new D(t.toString())}else if(typeof e=="boolean")return e;throw new Error(`Can't handle node: ${JSON.stringify(e)}`)}static handleArray(e){if(e!=null){if(K.isObject(e)&&!Array.isArray(e))return[m.handleNode(e)];if(Array.isArray(e))return e.map(m.handleNode);throw new Error("Expected an array node")}}}function qr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var nt,Dt;function Xr(){return Dt||(Dt=1,nt=function i(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?i(e.toJSON()):Array.isArray(e)?`[${e.reduce((s,n,o)=>`${s}${o===0?"":","}${i(n===void 0||typeof n=="symbol"?null:n)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,s)=>{if(e[s]===void 0||typeof e[s]=="symbol")return r;const n=r.length===0?"":",";return`${r}${n}${i(s)}:${i(e[s])}`},"")}}`}),nt}var Qr=Xr();const es=qr(Qr);class Ke{static canonicalize(e){return es(e)}}const ot=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class St{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new St),this.instance}initBrowserCrypto(){return ot?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return ot&&!!it.default&&typeof it.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return ot?it.default:null}}class Xt{cryptoEnv=St.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return Oe.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return Oe.default.encode(r)}canonicalizeInput(e){const t=Ke.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(_r.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 s=new TextEncoder().encode(e),n=await t.subtle.digest("SHA-256",s);return new Uint8Array(n)}}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 E{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(),s=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(s)}static textNode(e){return new d().setType(new d().setBlueId(re)).setValue(e)}static integerNode(e){const t=e instanceof O?e:new O(e.toString());return new d().setType(new d().setBlueId(ie)).setValue(t)}static doubleNode(e){const t=e instanceof D?e:new D(e.toString());return new d().setType(new d().setBlueId(se)).setValue(t)}static booleanNode(e){return new d().setType(new d().setBlueId(ne)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const s of Object.values(S)){const n=u.isNonNullable(this.getFieldValue(e,s));if(t.has(s)){if(!n)return!1}else if(!r.has(s)){if(n)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 me="$previous",de="$pos",dt="$empty";class v{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.getProperties()?.[B.OBJECT_MERGE_POLICY]?.getValue();if(t==="append-only"||t==="positional")return t}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 Object.prototype.hasOwnProperty.call(e.getProperties()??{},me)}static hasPositionProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},de)}static hasEmptyProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},dt)}static isEmptyItem(e){const t=e.getProperties(),r=t?.[dt];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&E.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&E.hasFieldsAndMayHaveFields(r,new Set([S.VALUE]),new Set([S.TYPE]))&&r.getValue()===!0}static isPreviousItem(e){const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&E.hasFieldsAndMayHaveFields(e,new Set([S.PROPERTIES]))&&E.hasBlueIdOnly(t[me])}static getPreviousBlueId(e){if(this.isPreviousItem(e))return e.getProperties()?.[me]?.getBlueId()}static createPreviousItem(e){return new d().setProperties({[me]:new d().setBlueId(e)})}static readPosition(e){const t=e.getProperties()?.[de];if(t===void 0)return;if(!E.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(),s=r instanceof O?r.toNumber():typeof r=="number"?r:void 0;if(s===void 0||!Number.isInteger(s)||s<0)throw new Error("$pos must be a non-negative integer value.");return s}static createPositionedItem(e,t){const r=t.clone();return r.addProperty(de,new d().setValue(e)),r}static withoutPosition(e){const t=e.clone(),r=t.getProperties();return r!==void 0&&(delete r[de],Object.keys(r).length===0&&t.setProperties(void 0)),t}static hasPayloadAfterRemovingPosition(e){return!E.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)}}const ts=new Set([ae,ce,J]),rs={$list:"empty"},ss="$listCons",is="prev",ns="elem";class os{constructor(e){this.hashProvider=e}calculate(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!1)}calculateSync(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!0)}calculateInternal(e,t){return this.isScalar(e)?this.applyHash(this.toJsonScalar(e),t):Array.isArray(e)?this.calculateList(e,t):this.isPureReference(e)?e[V]:this.isScalarWrapper(e)?this.calculateInternal(e[J],t):this.isBasicTypedScalarWrapper(e)?this.calculateInternal(e[J],t):this.isListWrapper(e)?this.calculateInternal(e[Y],t):this.isBasicTypedListWrapper(e)?this.calculateInternal(e[Y],t):this.calculateMap(e,t)}calculateMap(e,t){const s=Object.entries(e).sort(([o],[l])=>o.localeCompare(l)).map(([o,l])=>{if(ts.has(o))return t?[o,l]:Promise.resolve([o,l]);const a=this.calculateInternal(l,t);return t?[o,{[V]:a}]:Promise.resolve(a).then(c=>[o,{[V]:c}])}),n=o=>{const l={};for(const[a,c]of o)l[a]=c;return this.applyHash(l,t)};return t?n(s):Promise.all(s).then(n)}calculateList(e,t){let r=0,s;const n=e[0];if(n!==void 0&&this.hasPreviousControlKey(n)){const o=this.getPreviousControlBlueId(n);if(o===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");s=t?o:Promise.resolve(o),r=1}else s=this.applyHash(rs,t);for(let o=r;o<e.length;o++){const l=e[o];if(this.hasPreviousControlKey(l))throw new Error("$previous list control is allowed only first.");if(this.hasPositionControlKey(l))throw new Error("$pos list controls must be consumed before raw BlueId hashing.");const a=s,c=this.calculateInternal(l,t);t?s=this.applyHash(this.createListFoldInput(a,c),!0):s=Promise.all([a,c]).then(([p,f])=>this.applyHash(this.createListFoldInput(p,f),!1))}return s}createListFoldInput(e,t){return{[ss]:{[is]:{[V]:e},[ns]:{[V]:t}}}}getPreviousControlBlueId(e){if(typeof e!="object"||e===null||Array.isArray(e)||w(e))return;const t=Object.entries(e);if(t.length!==1||t[0][0]!==me)return;const r=t[0][1];if(!(typeof r!="object"||r===null||Array.isArray(r)||w(r)||!this.isPureReference(r)))return r[V]}hasPreviousControlKey(e){return this.hasControlKey(e,me)}hasPositionControlKey(e){return this.hasControlKey(e,de)}hasControlKey(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!w(e)&&Object.prototype.hasOwnProperty.call(e,t)}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}toHashValue(e){return e instanceof d?this.nodeToHashValue(e):Array.isArray(e)?e.map(t=>this.toHashValue(t)).filter(t=>t!==void 0):this.jsonToHashValue(e)}nodeToHashValue(e){const t={};this.setIfPresent(t,ae,e.getName()),this.setIfPresent(t,ce,e.getDescription()),this.setIfPresent(t,U,e.getType()),this.setIfPresent(t,Ne,e.getItemType()),this.setIfPresent(t,Pe,e.getKeyType()),this.setIfPresent(t,Se,e.getValueType());const r=e.getValue();r!==void 0&&(t[J]=this.scalarToHashValue(r));const s=e.getItems();s!==void 0&&(t[Y]=s.map(o=>this.nodeToHashValue(o))),this.setIfPresent(t,V,e.getReferenceBlueId()),this.setIfPresent(t,_e,e.getBlue());const n=e.getProperties();if(n!==void 0)for(const[o,l]of Object.entries(n))t[o]=this.nodeToHashValue(l);return t}jsonToHashValue(e){if(e!=null){if(this.isScalar(e)||w(e))return this.scalarToHashValue(e);if(Array.isArray(e))return e.map(t=>this.jsonToHashValue(t)).filter(t=>t!==void 0);if(typeof e=="object"){const t={};for(const[r,s]of Object.entries(e))t[r]=this.jsonToHashValue(s);return t}return e}}setIfPresent(e,t,r){r!==void 0&&(e[t]=r instanceof d?this.nodeToHashValue(r):r)}clean(e){if(e==null)return;if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.clean(r)).filter(r=>r!==void 0);const t={};for(const[r,s]of Object.entries(e)){const n=this.clean(s);n!==void 0&&(t[r]=n)}return Object.keys(t).length===0?void 0:t}isPureReference(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===V&&typeof t[0]?.[1]=="string"}isScalarWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===J}isBasicTypedScalarWrapper(e){return this.hasOnlyKeys(e,[U,J])&&this.isBasicScalarTypeReference(e[U])}isListWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===Y&&Array.isArray(t[0]?.[1])}isBasicTypedListWrapper(e){return this.hasOnlyKeys(e,[U,Y])&&this.isTypeReference(e[U],Ze)&&Array.isArray(e[Y])}hasOnlyKeys(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.prototype.hasOwnProperty.call(e,s))}isBasicScalarTypeReference(e){return this.isTypeReference(e,re)||this.isTypeReference(e,ie)||this.isTypeReference(e,se)||this.isTypeReference(e,ne)}isTypeReference(e,t){return typeof e!="object"||e===null||Array.isArray(e)||w(e)?!1:this.isPureReference(e)&&e[V]===t}isScalar(e){return u.isJsonPrimitive(e)&&e!==null||w(e)}scalarToHashValue(e){if(e instanceof O||ee(e)){const t=new G(Number.MIN_SAFE_INTEGER.toString()),r=new G(Number.MAX_SAFE_INTEGER.toString());return e.lt(t)||e.gt(r)?e.toString():e.toNumber()}return e instanceof D||w(e)?e.toNumber():e}toJsonScalar(e){return w(e)?this.scalarToHashValue(e):e}}class A{static INSTANCE=new A(new Xt);hasher;constructor(e){this.hasher=new os(e)}static calculateBlueId(e){return A.INSTANCE.calculate(e)}static calculateBlueIdSync(e){return A.INSTANCE.calculateSync(e)}calculate(e){return this.hasher.calculate(e)}calculateSync(e){return this.hasher.calculateSync(e)}}class W{constructor(e={emitListControls:!0}){this.options=e}reverse(e){const t=new d;return this.reverseNode(t,e,e.getType(),!0),t}static calculateHashMinimalBlueId(e){return A.calculateBlueIdSync(this.toHashMinimalNode(e))}static calculateHashMinimalListBlueId(e){return A.calculateBlueIdSync(e.map(t=>this.toHashMinimalNode(t)))}static toHashMinimalNode(e){return new W({emitListControls:!1}).reverse(e)}reverseNode(e,t,r,s){!s&&this.isIdenticalToType(t,r)||(this.reverseBasicProperties(e,t,r,s),this.reverseTypeReferences(e,t,r),this.reverseItems(e,t,r),this.reverseProperties(e,t,r))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r,s){const n=t.getValue();u.isNonNullable(n)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(n),u.isNonNullable(t.getName())&&(s||u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(s||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){const s=(n,o)=>{const l=n(t),a=r?n(r):void 0,c=l?.getBlueId();u.isNonNullable(c)&&(u.isNullable(a?.getBlueId())||c!==a.getBlueId())&&o(e,new d().setBlueId(c))};s(n=>n.getType(),(n,o)=>n.setType(o)),s(n=>n.getItemType(),(n,o)=>n.setItemType(o)),s(n=>n.getKeyType(),(n,o)=>n.setKeyType(o)),s(n=>n.getValueType(),(n,o)=>n.setValueType(o))}reverseItems(e,t,r){const s=t.getItems();if(u.isNullable(s))return;const n=r?.getItems();if(s.length===0){(u.isNullable(n)||n.length>0)&&e.setItems([]);return}if(u.isNonNullable(n)&&s.length===n.length&&s.every((l,a)=>W.calculateHashMinimalBlueId(l)===W.calculateHashMinimalBlueId(n[a])))return;const o=this.options.emitListControls!==!1&&u.isNonNullable(n)&&n.length>0?this.reverseInheritedItems(t,r):this.reverseFullItems(s);o.length>0&&e.setItems(o)}reverseInheritedItems(e,t){const r=e.getItems()??[],s=t.getItems()??[];if(r.length<s.length)throw new Error(`Resolved list has fewer items (${r.length}) than inherited list (${s.length}).`);const n=v.getMergePolicy(e,t),o=[];for(let c=0;c<s.length;c++)W.calculateHashMinimalBlueId(r[c])!==W.calculateHashMinimalBlueId(s[c])&&o.push(c);if(o.length>0&&n==="append-only")throw new Error("append-only list cannot be minimized as a non-prefix mutation.");const l=W.calculateHashMinimalListBlueId(s),a=[v.createPreviousItem(l)];for(const c of o){const p=new d;this.reverseNode(p,r[c],s[c],!1);const f=E.isEmptyNode(p)?r[c].clone():p;a.push(v.createPositionedItem(c,f))}for(let c=s.length;c<r.length;c++){const p=new d;this.reverseNode(p,r[c],void 0,!1),a.push(p)}return a.length===1?[]:a}reverseFullItems(e){const t=[];for(let r=0;r<e.length;r++){const s=new d;this.reverseNode(s,e[r],void 0,!1),t.push(s)}return t}reverseProperties(e,t,r){const s=t.getProperties();if(u.isNullable(s))return;const n={};for(const[o,l]of Object.entries(s)){const a=this.getInheritedProperty(o,t,r),c=new d;this.reverseNode(c,l,a,!1),E.isEmptyNode(c)||(n[o]=c)}Object.keys(n).length>0&&e.setProperties(n)}getInheritedProperty(e,t,r){const s=r?.getProperties()?.[e],n=t.getType()?.getProperties()?.[e];if(!(u.isNullable(s)&&u.isNullable(n)))return u.isNullable(s)?n:u.isNullable(n)?s:this.mergeNodes(s,n)}mergeNodes(e,t){const r=e.clone(),s=t.getValue();u.isNonNullable(s)&&r.setValue(s);const n=t.getType();u.isNonNullable(n)&&r.setType(n.clone());const o=t.getItemType();u.isNonNullable(o)&&r.setItemType(o.clone());const l=t.getKeyType();u.isNonNullable(l)&&r.setKeyType(l.clone());const a=t.getValueType();u.isNonNullable(a)&&r.setValueType(a.clone());const c=t.getProperties();if(u.isNonNullable(c)){const f=r.getProperties()||{};for(const[y,g]of Object.entries(c))f[y]=g.clone();r.setProperties(f)}const p=t.getItems();return u.isNonNullable(p)&&r.setItems(p.map(f=>f.clone())),r}}class ht{mergeReverser=new W;hashMergeReverser=new W({emitListControls:!1});minimize(e){return this.minimizeResolved(e)}minimizeResolved(e){return this.mergeReverser.reverse(e)}minimizeResolvedForHash(e){return this.hashMergeReverser.reverse(e)}}class pe extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r&&r.length>0?r:[],this.name="BlueError"}}const $={AMBIGUOUS_BLUE_ID_PAYLOAD:"AMBIGUOUS_BLUE_ID_PAYLOAD",BLUE_ID_MISMATCH:"BLUE_ID_MISMATCH",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 q{static RESERVED_PROPERTY_KEYS=new Set([B.OBJECT_SCHEMA,B.OBJECT_MERGE_POLICY,B.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((n,o)=>{this.validateListControlNode(n,[...t,"items",String(o)],o)});const s=e.getProperties();if(s!==void 0)for(const[n,o]of Object.entries(s))this.validateListControlNode(o,[...t,n])}static validateNode(e,t,r){r.insideItems&&this.validateListControlItem(e,t,r.itemIndex??0);const s=e.getReferenceBlueId();if(s!==void 0&&!E.hasBlueIdOnly(e))if(r.insideItems&&v.hasPositionProperty(e)&&E.hasBlueIdOnly(v.withoutPosition(e)))v.readPosition(e);else{const f=this.toPointer(t);throw new pe($.AMBIGUOUS_BLUE_ID_PAYLOAD,`Ambiguous blueId plus payload at ${f}. Use exact { blueId } for references or remove blueId from payload content.`,[{code:$.AMBIGUOUS_BLUE_ID_PAYLOAD,message:"A storage or authoring node cannot combine blueId with payload.",locationPath:t,context:{blueId:s}}])}const n=this.getChildProperties(e,t,r),o=e.getValue()!==void 0,l=e.getItems()!==void 0,a=Object.keys(n).length>0;o&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value and items payloads."),o&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value payload with object child fields."),l&&a&&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((p,f)=>{this.validateNode(p,[...t,"items",String(f)],{insideItems:!0,itemIndex:f})});const c=e.getProperties();if(c!==void 0)for(const[p,f]of Object.entries(c))this.validateNode(f,[...t,p],{insideItems:!1})}static validateListControlItem(e,t,r){if(v.hasEmptyProperty(e)&&(v.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $previous."),v.hasPositionProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $pos."),v.isEmptyItem(e)||this.throwInvalidStorageShape(t,"$empty list content must be exactly { $empty: true }.")),v.hasPreviousProperty(e)&&(r!==0&&this.throwInvalidStorageShape(t,"$previous list control is allowed only as the first item."),v.isPreviousItem(e)||this.throwInvalidStorageShape(t,"$previous list control must be exactly { $previous: { blueId: <id> } }.")),v.hasPositionProperty(e)){v.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$pos cannot be combined with $previous.");try{v.readPosition(e)}catch(s){this.throwInvalidStorageShape([...t,de],s instanceof Error?s.message:"$pos must be a non-negative integer value.")}v.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 s=e.getProperties()??{};return Object.prototype.hasOwnProperty.call(s,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(s).filter(([n])=>!this.RESERVED_PROPERTY_KEYS.has(n)&&!(r.insideItems&&(n===de||n===dt))))}static throwInvalidStorageShape(e,t){const r=this.toPointer(e);throw new pe($.INVALID_STORAGE_SHAPE,`${t} at ${r}`,[{code:$.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 ls{static convert(e){const t=Oe.default.decode(e),r=new Uint8Array(2+t.length);r[0]=18,r[1]=32,r.set(t,2);const s=new Uint8Array(2+r.length);return s[0]=1,s[1]=85,s.set(r,2),"b"+new jr.Encoder({type:"rfc4648",lc:!0}).write(s).finalize().replace(/=/g,"")}}class T{static get(e,t="official"){const{strategy:r}=this.normalizeOptions(t),s=e.getValue(),n=this.handleValue(s);if(n!==void 0&&r==="simple")return n;const o=e.getItems()?.map(F=>T.get(F,r));if(o!==void 0&&r==="simple")return o;const l=e.getName(),a=e.getDescription();if(r==="original"&&l===void 0&&a===void 0){if(n!==void 0)return n;if(o!==void 0)return o}const c={};l!==void 0&&(c[ae]=l),a!==void 0&&(c[ce]=a);const p=e.getType();if(r==="official"&&s!==void 0&&p===void 0){const F=this.inferTypeBlueId(s);F!==null&&(c[U]={[V]:F})}else p!==void 0&&(c[U]=T.get(p,r));const f=e.getItemType();f!==void 0&&(c[Ne]=T.get(f,r));const y=e.getKeyType();y!==void 0&&(c[Pe]=T.get(y,r));const g=e.getValueType();g!==void 0&&(c[Se]=T.get(g,r)),n!==void 0&&(c[J]=n),o!==void 0&&(c[Y]=o);const I=e.getBlueId();I!==void 0&&(c[V]=I);const _=e.getBlue();_!==void 0&&(c[_e]=_);const N=e.getProperties();return N!==void 0&&Object.entries(N).forEach(([F,b])=>{c[F]=T.get(b,r)}),c}static handleValue(e){if(w(e)){if(ee(e)){const t=new G(Number.MIN_SAFE_INTEGER.toString()),r=new G(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"?re:w(e)?ee(e)?ie:se:typeof e=="boolean"?ne: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()),s=r.getType();s!==void 0&&r.setType(M.transform(s,t));const n=r.getItemType();n!==void 0&&r.setItemType(M.transform(n,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(M.transform(o,t));const l=r.getValueType();l!==void 0&&r.setValueType(M.transform(l,t));const a=r.getItems();if(a!==void 0){const p=a.map(f=>M.transform(f,t));r.setItems(p)}const c=r.getProperties();if(c!==void 0){const p=Object.keys(c).reduce((f,y)=>(f[y]=M.transform(c[y],t),f),{});r.setProperties(p)}return r}}const ue=i=>!!i&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof d),Q=i=>i instanceof O||i instanceof D,as=i=>i.replace(/~1/g,"/").replace(/~0/g,"~");function we(i){if(i==="/")return[];if(!i.startsWith("/"))throw new Error(`Path must start with '/': ${i}`);return i.split("/").slice(1).map(as)}function Be(i){if(i==="-")return-1;const e=typeof i=="number"?i:parseInt(i,10);if(isNaN(e))throw new Error(`Invalid array index (NaN) from '${i}'`);if(!Number.isFinite(e))throw new Error(`Invalid array index '${i}' results in non-finite number ${e}`);return e}function Qt(i,e,t,r=!0){switch(e){case"name":return t?r?i.getName()??null:i:i.getName();case"description":return t?r?i.getDescription():i:i.getDescription();case"type":return i.getType();case"itemType":return i.getItemType();case"keyType":return i.getKeyType();case"valueType":return i.getValueType();case"value":return t?r?i.getValue()??null:i:i.getValue();case"blueId":return t?r?i.getBlueId()??null:i:i.getBlueId();case"blue":return i.getBlue();case"items":return i.getItems();case"properties":return i.getProperties();case B.OBJECT_CONTRACTS:return i.getContracts();default:return}}function _t(i,e,t=!0){if(i instanceof d){const r=Qt(i,e,!0,t);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",B.OBJECT_CONTRACTS].includes(e))return r;if(/^-?\d+$/.test(e)&&e!=="-"){const n=i.getItems(),o=parseInt(e,10);return n&&o>=0&&o<n.length?n[o]:void 0}const s=i.getProperties();return s&&e in s?s[e]:void 0}if(Array.isArray(i)){if(e==="-")return;const r=Be(e);return r>=0&&r<i.length?i[r]:void 0}if(ue(i))return i[e]}function Ee(i,e){if(e.length===0)return{parent:i,key:"value",actualTarget:i.getValue()??i};let t=i;for(let s=0;s<e.length-1;++s){const n=e[s],o=_t(t,n);if(o===void 0)throw new Error(`Cannot resolve '/${e.slice(0,s+1).join("/")}'`);t=o}const r=e[e.length-1];if(t instanceof d){const s=_t(t,r,!1);if((typeof s!="object"||s===null||Q(s))&&!(s instanceof d)&&!Array.isArray(s)&&["name","description","value","blueId"].includes(r))return{parent:t,key:r,actualTarget:s}}return Array.isArray(t)&&r==="-"?{parent:t,key:"-"}:t instanceof d&&t.getItems()&&r==="-"?{parent:t,key:"-"}:{parent:t,key:Array.isArray(t)?Be(r):r}}function wt(i,e){if(i instanceof d){const t=e,r=Qt(i,t,!1);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",B.OBJECT_CONTRACTS].includes(t))return r;if(typeof e=="number"||typeof e=="string"&&/^\d+$/.test(e)){const s=i.getItems(),n=typeof e=="number"?e:parseInt(e,10);if(s&&n>=0&&n<s.length)return s[n]}return i.getProperties()?.[t]}return Array.isArray(i)||ue(i)?i[e]:i}function L(i){if(i instanceof d)return i;if(i===null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||Q(i))return m.deserialize(i);const e=pt(i);return m.deserialize(e)}function pt(i){if(i===void 0)return null;if(i===null||typeof i!="object")return i;if(Array.isArray(i))return i.map(pt);const e={};for(const[t,r]of Object.entries(i))e[t]=pt(r);return e}function Et(i,e,t){if(i instanceof d){const r=e;switch(r){case"name":i.setName(t);return;case"description":i.setDescription(t);return;case"type":i.setType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"itemType":i.setItemType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"keyType":i.setKeyType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"valueType":i.setValueType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"value":{const s=t;i.setValue(s===void 0?null:s);return}case"blueId":i.setBlueId(t);return;case"blue":i.setBlue(t instanceof d||t===void 0?t:L(t));return;case"items":i.setItems(t);return;case"properties":i.setProperties(t);return;case B.OBJECT_CONTRACTS:i.setContracts(t);return;default:{if(t===void 0){const s=i.getProperties();s&&r in s&&delete s[r]}else i.getProperties()||i.setProperties({}),i.addProperty(r,t instanceof d?t:L(t));return}}}Array.isArray(i)?i.splice(Be(e),1):ue(i)&&(t===void 0?delete i[e]:i[e]=t)}function cs(i,e,t,r){let s=-1;if(e!=="-"&&(s=typeof e=="number"?e:parseInt(e,10),isNaN(s)))throw new Error(`Invalid numeric key for BlueNode item operation: ${e}`);if(s<-1)throw new Error(`Invalid array index for BlueNode items: ${s}`);let n=i.getItems();if(n||(n=[],i.setItems(n)),!r&&s!==-1&&s>n.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${n.length}.`);if(e==="-")n.push(t);else if(r){if(s>=0)if(s<n.length)n[s]=t;else{for(let o=n.length;o<s;o++)n.push(m.deserialize(null));n.push(t)}}else n.splice(s,0,t)}function ke(i,e,t,r){if(Array.isArray(i)){const s=e==="-"?i.length:Be(e);if(!r&&s>i.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${i.length}. Path involving key '${e}'.`);if(s<0&&e!=="-")throw new Error(`Invalid negative array index: ${e}`);const n=L(t);if(r){if(s>=0&&s<i.length)i[s]=n;else if(s>=i.length){for(let o=i.length;o<s;o++)i.push(m.deserialize(null));i.push(n)}}else i.splice(s,0,n);return}if(i instanceof d){e==="-"||typeof e=="number"&&!isNaN(e)||typeof e=="string"&&/^\d+$/.test(e)?cs(i,e,L(t),r):Et(i,e,t);return}if(ue(i)){i[e]=L(t);return}throw new Error(`Cannot insert into parent of type ${typeof i}`)}function us(i,e){if(Array.isArray(i)){const t=Be(e);t===-1&&e==="-"?i.length>0&&i.pop():t>=0&&t<i.length&&i.splice(t,1);return}if(i instanceof d){if(typeof e=="number"||typeof e=="string"&&/^-?\d+$/.test(e)){const t=i.getItems();if(t){const r=Be(e);r===-1&&e==="-"?t.length>0&&t.pop():r>=0&&r<t.length&&t.splice(r,1),t.length===0&&i.setItems(void 0);return}}Et(i,e,void 0)}else ue(i)&&delete i[e]}function ft(i){if(i instanceof d)return i.clone();if(Array.isArray(i))return i.map(t=>ft(t));if(ue(i)){const e={};return Object.keys(i).forEach(t=>{e[t]=ft(i[t])}),e}return i}function he(i,e){if(i===e||i instanceof d&&(i.isInlineValue()||i.getValue()!==void 0)&&he(i.getValue()??null,e)||e instanceof d&&(e.isInlineValue()||e.getValue()!==void 0)&&he(i,e.getValue()??null))return!0;if(i instanceof d&&e instanceof d||Q(i)&&Q(e)||Q(i)&&typeof e=="number"||typeof i=="number"&&Q(e))return i.toString()===e.toString();if(Array.isArray(i)&&Array.isArray(e))return i.length===e.length&&i.every((t,r)=>he(t,e[r]));if(ue(i)&&ue(e)){const t=Object.keys(i),r=Object.keys(e);return t.length===r.length&&t.every(s=>he(i[s],e[s]))}return!1}function er(i,e){const{parent:t,key:r}=Ee(i,we(e));return wt(t,r)}function tr(i,e,t){const r=we(e);if(r.length===0&&e==="/"){const o=L(t);i.setValue(o.getValue()??null),o.getItems()?i.setItems(o.getItems()):i.setItems(void 0);return}const{parent:s,key:n}=Ee(i,r);ke(s,n,t,!0)}function ds(i,e,t){const r=we(e);if(r.length===0&&e==="/"){if(i.getItems()&&Array.isArray(t)){const o=L(t);o.getItems()?(i.setItems(o.getItems()),i.setValue(null)):(i.setValue(o.getValue()??null),i.setItems(void 0))}else{const o=L(t);i.setValue(o.getValue()??null),o.getItems()&&i.setItems(o.getItems())}return!0}const{parent:s,key:n}=Ee(i,r);return ke(s,n,t,!1),!0}function hs(i,e,t){const r=we(e);if(r.length===0&&e==="/"){const l=L(t);return i.setValue(l.getValue()??null),l.getItems()?i.setItems(l.getItems()):i.setItems(void 0),!0}const{parent:s,key:n,actualTarget:o}=Ee(i,r);if(o!==void 0&&s instanceof d)Et(s,n,t);else{const l=wt(s,n),a=Array.isArray(s)||s instanceof d&&s.getItems()&&(typeof n=="number"||typeof n=="string"&&/^\d+$/.test(n));if(l===void 0){if(a)throw new Error(`REPLACE failed: Target array index '${n.toString()}' is out of bounds or does not exist at path '${e}'.`);ke(s,n,t,!0)}else ke(s,n,t,!0)}return!0}function rr(i,e){const t=we(e);if(t.length===0&&e==="/")return i.setValue(null),i.setItems(void 0),i.setProperties(void 0),!0;const{parent:r,key:s}=Ee(i,t);return us(r,s),!0}function ps(i,e,t){const r=ft(er(i,e));return tr(i,t,r),!0}function fs(i,e,t){const r=we(e),{parent:s,key:n}=Ee(i,r),o=wt(s,n);if(o===void 0)throw new Error(`MOVE failed: 'from' location '${e}' does not exist.`);return rr(i,e)?(tr(i,t,o),!0):!1}function ys(i,e,t){const r=er(i,e);let s=t;if(r instanceof d)if((t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||Q(t))&&(r.isInlineValue()||r.getValue()!==void 0)){if(!he(r.getValue()??null,t))throw new Error(`TEST failed at '${e}': Expected ${JSON.stringify(t)}, got ${JSON.stringify(r.getValue()??null)}`);return!0}else typeof t=="object"&&!(t instanceof d)&&(s=L(t));else if(Q(r)&&typeof t=="number")r instanceof O?s=new O(t.toString()):r instanceof D&&(s=new D(t.toString()));else if((r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&Q(t)){const n=t;!he(r,n.toString())&&(typeof r=="number"&&parseFloat(n.toString()))}if(!he(r,s)){const n=r instanceof d?r.toString():JSON.stringify(r),o=s instanceof d?s.toString():JSON.stringify(s);throw new Error(`TEST failed at '${e}': Expected ${o}, got ${n}`)}return!0}function gs(i,e){switch(e.op){case"add":return ds(i,e.path,e.val);case"replace":return hs(i,e.path,e.val);case"remove":return rr(i,e.path);case"copy":return ps(i,e.from,e.path);case"move":return fs(i,e.from,e.path);case"test":return ys(i,e.path,e.val)}}function ms(i,e,t=!1){const r=t?i:i.clone();return gs(r,e),r}const lt=Symbol.for("zod-schema-annotations");function Is(){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 sr(){const i=Is();return lt in i||(i[lt]=new WeakMap),i[lt]}function je(i,e){const t=sr(),r=t.get(i)||{};return t.set(i,{...r,...e}),i}const Z=i=>sr().get(i),ir=i=>e=>{const t=Z(e);return je(e,{...t,blueDescription:i})},nr=i=>{const e=Z(i);return u.isNonNullable(e)&&K.isString(e.blueDescription)?e.blueDescription:null},Ts=i=>ir(i)(h.z.string().optional()),vs=h.z.union([h.z.string(),h.z.boolean()]),or=i=>e=>{const t=Z(e);return je(e,{...t,blueId:i})},lr=i=>{const e=Z(i),t=vs.safeParse(e?.blueId);return t.success?t.data:null},Bs=i=>or(i??!0)(h.z.string()),ar=i=>e=>{const t=Z(e);return je(e,{...t,blueName:i})},cr=i=>{const e=Z(i);return u.isNonNullable(e)&&K.isString(e.blueName)?e.blueName:null},bs=i=>{const e=h.z.string().optional();return ar(i)(e)},ur=()=>i=>{const e=Z(i);return je(i,{...e,blueNode:!0})},dr=i=>{const e=Z(i);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},Ct=i=>!!dr(i),Ns=()=>{const i=h.z.instanceof(d);return ur()(i)},Ps=h.z.object({value:h.z.array(h.z.string()).optional(),defaultValue:h.z.string().optional()}),hr=i=>{const e=Z(i),t=Ps.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},pr=i=>e=>{const t=Z(e),r=typeof i=="string"?{value:[i]}:i;return je(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class Me{static resolveBlueId(e){const t=hr(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const s=t.value?.[0];return u.isNonNullable(s)?s:Me.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}class z{static isTypeOf(e,t,r){const s=Me.resolveBlueId(t),n=e.getType()?.getBlueId();if(u.isNullable(s)||u.isNullable(n))return!1;const o=r?.blueIdMapper?.toCurrentBlueId(s)??s,l=r?.blueIdMapper?.toCurrentBlueId(n)??n;if(o===l)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const a=r.typeSchemaResolver.resolveSchema(e);return z.checkSchemaExtension(a,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const s=z.unwrapSchema(e),n=z.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(s,n):!1}static isWrapperType(e){return e instanceof h.ZodOptional||e instanceof h.ZodNullable||e instanceof h.ZodReadonly||e instanceof h.ZodBranded||e instanceof h.ZodEffects||e instanceof h.ZodLazy}static unwrapSchema(e){return Ct(e)?e:z.isWrapperType(e)?e instanceof h.ZodEffects?z.unwrapSchema(e.innerType()):e instanceof h.ZodLazy?z.unwrapSchema(e.schema):z.unwrapSchema(e.unwrap()):e}}const fr=Symbol("blue.subtypeCache");function Ss(i,e){return i[fr]=e,i}function Lt(i,e){const t=i.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(ye.includes(r)){const n=qe[r];return new d().setBlueId(r).setName(n)}const s=e.fetchByBlueId(r);if(!s||s.length===0)return;if(s.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return s[0].cloneShallow().setBlueId(r)}return t}function C(i,e,t){const r=He(i),s=He(e),n=t[fr],o=`${r}|${s}`,l=n?.get(o);if(l!==void 0)return l;const a=ws(i,e,t,r,s);return n?.set(o,a),a}function He(i){const e=i.getReferenceBlueId();return e!==void 0?e:A.calculateBlueIdSync(oe(i))}function oe(i){if(!yr(i))return i;const e=i.cloneShallow();e.getReferenceBlueId()!==void 0&&!E.hasBlueIdOnly(e)&&e.setReferenceBlueId(void 0);const t=e.getType();t!==void 0&&e.setType(oe(t));const r=e.getItemType();r!==void 0&&e.setItemType(oe(r));const s=e.getKeyType();s!==void 0&&e.setKeyType(oe(s));const n=e.getValueType();n!==void 0&&e.setValueType(oe(n));const o=e.getBlue();o!==void 0&&e.setBlue(oe(o));const l=e.getItems();l!==void 0&&e.setItems(l.map(c=>oe(c)));const a=e.getProperties();return a!==void 0&&e.setProperties(Object.fromEntries(Object.entries(a).map(([c,p])=>[c,oe(p)]))),e}function yr(i){return i.getReferenceBlueId()!==void 0&&!E.hasBlueIdOnly(i)?!0:[i.getType(),i.getItemType(),i.getKeyType(),i.getValueType(),i.getBlue(),...i.getItems()??[],...Object.values(i.getProperties()??{})].some(t=>t!==void 0&&yr(t))}function ws(i,e,t,r,s){if(r===s)return!0;if(r&&ye.includes(r)){let a=e;for(;a!==void 0;){if(He(a)===r)return!0;a=Lt(a,t)}return!1}let n=i;const o=i.getBlueId();if(o){const a=t.fetchByBlueId(o);a&&a.length===1&&(n=a[0])}let l=n;for(;l!==void 0;){if(He(l)===s)return!0;l=Lt(l,t)}return!1}function Es(i,e){return bt.some(t=>{const r=new d().setBlueId(t);return C(i,r,e)})}function Cs(i,e){const t=new d().setBlueId(re);return C(i,t,e)}function Rs(i,e){const t=new d().setBlueId(ie);return C(i,t,e)}function As(i,e){const t=new d().setBlueId(se);return C(i,t,e)}function Os(i,e){const t=new d().setBlueId(ne);return C(i,t,e)}function Fe(i,e){const t=new d().setBlueId(Ze);return C(i,t,e)}function ze(i,e){const t=new d().setBlueId(Bt);return C(i,t,e)}function Vs(i,e){return Ge.some(t=>{const r=new d().setName(t);return C(i,r,e)})}function Ms(i,e){for(const t of Ge){const r=new d().setName(t);if(C(i,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${i.getName()||"unknown"}".`)}class gr{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=Me.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),s=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(s))return!1;if(r===s)return!0;if(u.isNonNullable(this.nodeProvider))try{const n=new d().setBlueId(r),o=new d().setBlueId(s);if(C(n,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=Me.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,s]of this.blueIdMap)if(s===e||s._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)?A.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}class Xe{}class Ce{static convert(e){const t=new yt;return Ce.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const s=e.getProperties(),n=e.getItems(),o=s!==void 0&&Object.keys(s).length>0,l=n!==void 0&&n.length>0;if(!o&&!l){r.addPath(t===""?"/":t);return}if(s)for(const[a,c]of Object.entries(s)){const p=`${t}/${a}`;Ce.traverseNode(c,p,r)}if(n)for(let a=0;a<n.length;a++){const c=`${t}/${a}`;Ce.traverseNode(n[a],c,r)}}}function jt(i,e){const t=i.split(e),r=[...t].reverse().findIndex(n=>n!==""),s=r===-1?0:t.length-r;return t.slice(0,s)}class Qe extends Xe{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=jt(e,"/"),s=jt(t,"/");if(s.length>r.length)return!1;for(let n=1;n<s.length;n++)if(r[n]!=="*"&&r[n]!==s[n])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 yt().setMaxDepth(e);for(let r=1;r<=e;r++){const s="/"+Array(r).fill("*").join("/");t.addPath(s)}return t.build()}static withSinglePath(e){return new yt().addPath(e).build()}static fromNode(e){return Ce.convert(e)}}class yt{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 Qe(this.allowedPaths,this.maxDepth)}}class H extends Xe{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class et extends Xe{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 et(e)}}const x=new H;class k extends d{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 d().setReferenceBlueId(this.sourceSemanticBlueId);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return new ht().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 ht().minimizeResolvedForHash(this);return A.calculateBlueIdSync(t)}clone(){const e=super.clone();return new k(e,this.getMetadata())}cloneShallow(){const e=super.cloneShallow();return new k(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(!Te.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()).setBlueId(e.getBlueId()).setBlue(e.getBlue()).setInlineValue(e.isInlineValue());const t=e.getValue();t!==void 0&&this.setValue(t)}}class Ds{blue;constructor(e){this.blue=e}matchesType(e,t,r=x){const s=Qe.fromNode(t),n=et.of(r,s),o=this.extendAndResolve(e,n),l=this.blue.resolve(t,n),a=this.expandSchemaOwnedTypeReferences(t);return this.recursiveValueComparison(o,l,a,n)?this.verifyMatch(o,t,n)||t.getType()===void 0:!1}extendAndResolve(e,t){const r=e.clone(),s=r.clone();this.blue.extend(s,t);const n=this.blue.resolve(s,t);return this.restoreMissingStructure(n,r),n}restoreMissingStructure(e,t){const r=t.getItems(),s=e.getItems();if(r&&r.length>0)if(!s||s.length===0)e.setItems(r.map(a=>a.clone()));else for(let a=0;a<Math.min(s.length,r.length);a++)this.restoreMissingStructure(s[a],r[a]);const n=t.getProperties();if(n){let a=e.getProperties();a||(a={},e.setProperties(a));for(const[c,p]of Object.entries(n)){const f=a[c];f===void 0?a[c]=p.clone():this.restoreMissingStructure(f,p)}}const o=t.getBlueId();e.getBlueId()===void 0&&o!==void 0&&e.setBlueId(o);const l=t.getValue();e.getValue()===void 0&&l!==void 0&&e.setValue(l)}verifyMatch(e,t,r){const s=t.getType();if(this.matchesImplicitStructure(e,s))return!0;const n=e.clone().setType(t.clone());try{this.blue.resolve(n,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,s=x){const n=t.getType(),o=this.matchesImplicitStructure(e,n)||this.matchesImplicitCoreCollectionType(e,t);if(e.getType()===void 0&&this.isCoreCollectionType(t)&&!o)return!1;if(n&&!o){const b=e.getType();if(!b||!C(b,n,this.blue.getNodeProvider()))return!1}const l=t.getBlueId();if(!o&&l!==void 0)if(this.isExplicitBlueIdMatcher(r)){if(e.getBlueId()!==l&&!this.matchesCalculatedBlueId(e,l))return!1}else{const b=e.getBlueId(),P=e.getType();if(P===void 0&&b!==void 0&&b!==l||P&&!C(P,t,this.blue.getNodeProvider()))return!1}const a=e.getBlueId();if(!o&&l===void 0&&a!==void 0&&e.getType()===void 0&&t.getItems()===void 0&&this.hasMatcherShape(t)&&!this.matchesCalculatedBlueId(t,a))return!1;const c=t.getValue();if(c!==void 0){const b=e.getValue();if(b===void 0)return!1;if(w(b)&&w(c)){if(!b.eq(c))return!1}else if(b!==c)return!1}const p=t.getItems(),f=r.getItems();if(p!==void 0){const b=e.getItems()??[];for(let P=0;P<p.length;P++)if(P<b.length){if(!this.recursiveValueComparison(b[P],p[P],f?.[P]??p[P],s))return!1}else if(this.hasValueInNestedStructure(p[P]))return!1}const y=t.getItemType(),g=r.getItemType();if(y!==void 0){const b=e.getItems()??[];for(const P of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(P,y,g??y,s),y,g??y,s))return!1}const I=t.getProperties(),_=r.getProperties();if(I!==void 0){const b=e.getProperties()??{};for(const[P,st]of Object.entries(I))if(P in b){if(!this.recursiveValueComparison(b[P],st,_?.[P]??st,s))return!1}else if(this.hasValueInNestedStructure(st))return!1}const N=t.getValueType(),F=r.getValueType();if(N!==void 0){const b=Object.values(e.getProperties()??{});for(const P of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(P,N,F??N,s),N,F??N,s))return!1}return!0}resolveUntypedNodeAgainstMatcherType(e,t,r,s){return e.getType()!==void 0||this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,s)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const s of t)if(this.hasValueInNestedStructure(s))return!0}const r=e.getProperties();if(r!==void 0){for(const s of Object.values(r))if(this.hasValueInNestedStructure(s))return!0}return!1}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}matchesCalculatedBlueId(e,t){if(e instanceof k&&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}}}toPlainBlueNode(e){const t=new d(e.getName());t.setDescription(e.getDescription()).setReferenceBlueId(e.getReferenceBlueId()).setInlineValue(e.isInlineValue());const r=e.getValue();r!==void 0&&t.setValue(r);const s=e.getType();s!==void 0&&t.setType(this.toPlainBlueNode(s));const n=e.getItemType();n!==void 0&&t.setItemType(this.toPlainBlueNode(n));const o=e.getKeyType();o!==void 0&&t.setKeyType(this.toPlainBlueNode(o));const l=e.getValueType();l!==void 0&&t.setValueType(this.toPlainBlueNode(l));const a=e.getItems();a!==void 0&&t.setItems(a.map(f=>this.toPlainBlueNode(f)));const c=e.getProperties();c!==void 0&&t.setProperties(Object.fromEntries(Object.entries(c).map(([f,y])=>[f,this.toPlainBlueNode(y)])));const p=e.getBlue();return p!==void 0&&t.setBlue(this.toPlainBlueNode(p)),t}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:Fe(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):ze(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:Fe(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):ze(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return Fe(e,this.blue.getNodeProvider())||ze(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.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}isExplicitBlueIdMatcher(e){return this.isBareBlueIdReference(e)}resolveAgainstTargetType(e,t,r){try{const s=e.clone(),n=s.clone().setType(t.clone()),o=this.blue.resolve(n,r);return this.restoreMissingStructure(o,s),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()),s=e.getType();s&&e.setType(this.expandReferencedTypeNode(s,r));const n=e.getItemType();n&&e.setItemType(this.expandReferencedTypeNode(n,r));const o=e.getKeyType();o&&e.setKeyType(this.expandReferencedTypeNode(o,r));const l=e.getValueType();l&&e.setValueType(this.expandReferencedTypeNode(l,r));const a=e.getItems();a&&e.setItems(a.map(p=>this.expandSchemaTypeReferences(p,r)));const c=e.getProperties();return c&&e.setProperties(Object.fromEntries(Object.entries(c).map(([p,f])=>[p,this.expandSchemaTypeReferences(f,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 s=this.blue.getNodeProvider().fetchByBlueId(r);return!s||s.length!==1?e.clone():this.expandSchemaTypeReferences(s[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}class j{static ZERO_BLUE_ID="0".repeat(44);static THIS_INDEX_REFERENCE_PATTERN=/^this#(\d+)$/;prepareDocument;calculateBlueId;constructor(e={}){this.prepareDocument=e.prepareDocument??(t=>t),this.calculateBlueId=e.calculateBlueId??A.calculateBlueIdSync}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((l,a)=>{const c=this.prepareDocument(this.replaceIndexedThisReferences(l,()=>j.ZERO_BLUE_ID));return{originalIndex:a,preliminaryBlueId:this.calculateBlueId(c),node:l}});this.validateUniquePreliminaryBlueIds(t);const r=[...t].sort(this.comparePreliminaryDocuments),s=[];r.forEach(({originalIndex:l},a)=>{s[l]=a});const n=r.map(({node:l})=>this.prepareDocument(this.replaceIndexedThisReferences(l,a=>`this#${s[a]}`))),o=this.calculateBlueId(n);return{blueId:o,nodes:n,documentBlueIds:n.map((l,a)=>`${o}#${a}`),originalToSortedIndexes:s}}comparePreliminaryDocuments(e,t){return e.preliminaryBlueId<t.preliminaryBlueId?-1:e.preliminaryBlueId>t.preliminaryBlueId?1:0}validateUniquePreliminaryBlueIds(e){const t=new Map;for(const r of e){const s=t.get(r.preliminaryBlueId);if(s!==void 0)throw new Error(`Direct cyclic document set has ambiguous canonical ordering: documents ${s} and ${r.originalIndex} share preliminary BlueId '${r.preliminaryBlueId}'.`);t.set(r.preliminaryBlueId,r.originalIndex)}}validateCyclicSet(e){if(e.length===0)throw new Error("Cyclic document set cannot be empty.");this.visitReferences(e,(t,r)=>{if(r==="this")throw new Error("Direct cyclic document sets must use indexed references such as 'this#0'; unindexed 'this' is not supported.");if(r.startsWith("this#")&&!j.THIS_INDEX_REFERENCE_PATTERN.test(r))throw new Error(`Malformed direct cyclic reference '${r}'. Expected 'this#<non-negative-integer>'.`);const s=this.readIndexedThisReference(r);if(s!==void 0&&s>=e.length)throw new Error(`Direct cyclic reference '${r}' points outside the ${e.length}-document set.`)})}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 s=this.readIndexedThisReference(r);s!==void 0&&e.setReferenceBlueId(t(s))}this.childrenOf(e).forEach(s=>this.rewriteIndexedThisReferences(s,t))}static nodeHasThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{(s==="this"||s.startsWith("this#"))&&(t=!0)}),t}static nodeHasIndexedThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{j.THIS_INDEX_REFERENCE_PATTERN.test(s)&&(t=!0)}),t}visitReferences(e,t){e.forEach(r=>j.visitNodeReferences(r,t))}static visitNodeReferences(e,t){const r=e.getReferenceBlueId();r!==void 0&&t(e,r),this.childrenOf(e).forEach(s=>this.visitNodeReferences(s,t))}readIndexedThisReference(e){const t=e.match(j.THIS_INDEX_REFERENCE_PATTERN);if(t!==null)return Number(t[1])}childrenOf(e){return j.childrenOf(e)}static childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}class ge{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function tt(i){return new class extends ge{fetchByBlueId(e){return i(e)}}}class mr{resolveWithoutLimits(e){return this.resolve(e,x)}}class Ir extends ge{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 at=fe.types.float.options,_s={...at,construct:i=>{const e=i.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new D(e);if(at.construct)return at.construct(i)}},Ls=new fe.Type("tag:yaml.org,2002:float",_s),ct=fe.types.int.options,js={...ct,construct:i=>{let e=i;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new O(e);if(ct.construct)return ct.construct(i)}},$s=new fe.Type("tag:yaml.org,2002:int",js),Tr=fe.CORE_SCHEMA.extend({implicit:[Ls,$s]}),te=i=>{const e=fe.load(i,{schema:Tr});return e===void 0?void 0:e},vr=i=>fe.dump(i,{schema:Tr,replacer:(e,t)=>{if(w(t)){if(ee(t)){const r=new G(Number.MIN_SAFE_INTEGER.toString()),s=new G(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(s))return t.toString()}return t.toNumber()}return t}}),Br=`- type:
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Z=require("big.js"),u=require("@blue-labs/shared-utils"),h=require("zod"),Lr=require("bs58"),H=require("radash"),B=require("@blue-labs/repository-contract"),jr=require("js-sha256"),xr=require("crypto"),$r=require("base32.js"),pe=require("js-yaml"),Ft=i=>i&&i.__esModule?i:{default:i},Oe=Ft(Lr),it=Ft(xr);class _ extends Z{constructor(e){super(e)}}class O extends Z{constructor(e){super(e)}}const le="name",ae="description",K="type",Ne="itemType",Pe="keyType",Se="valueType",J="value",W="items",V="blueId",Le="blue",vt=[le,ae,K,Ne,Pe,Se,J,W,V,Le],zt="Text",Ut="Double",Kt="Integer",Ht="Boolean",kt="List",Yt="Dictionary",Ge=[zt,Ut,Kt,Ht],Bt=[...Ge,kt,Yt],te="DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",re="7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",se="5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",ie="4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",qe="6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",bt="G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",Nt=[te,re,se,ie],fe=[...Nt,qe,bt],Wt=Object.fromEntries(Bt.map((i,e)=>[i,fe[e]])),Xe=Object.fromEntries(fe.map((i,e)=>[i,Bt[e]])),Fr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:Ge,BASIC_TYPE_BLUE_IDS:Nt,BOOLEAN_TYPE:Ht,BOOLEAN_TYPE_BLUE_ID:ie,CORE_TYPES:Bt,CORE_TYPE_BLUE_IDS:fe,CORE_TYPE_BLUE_ID_TO_NAME_MAP:Xe,CORE_TYPE_NAME_TO_BLUE_ID_MAP:Wt,DICTIONARY_TYPE:Yt,DICTIONARY_TYPE_BLUE_ID:bt,DOUBLE_TYPE:Ut,DOUBLE_TYPE_BLUE_ID:re,INTEGER_TYPE:Kt,INTEGER_TYPE_BLUE_ID:se,LIST_TYPE:kt,LIST_TYPE_BLUE_ID:qe,OBJECT_BLUE:Le,OBJECT_BLUE_ID:V,OBJECT_CONTRACTS:B.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:ae,OBJECT_ITEMS:W,OBJECT_ITEM_TYPE:Ne,OBJECT_KEY_TYPE:Pe,OBJECT_MERGE_POLICY:B.OBJECT_MERGE_POLICY,OBJECT_NAME:le,OBJECT_SCHEMA:B.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:vt,OBJECT_TYPE:K,OBJECT_VALUE:J,OBJECT_VALUE_TYPE:Se,TEXT_TYPE:zt,TEXT_TYPE_BLUE_ID:te},Symbol.toStringTag,{value:"Module"}));class zr{static get(e,t,r,s=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return s&&o!==void 0?o:e}const n=t.substring(1).split("/");return this.getRecursive(e,n,0,r,s)}static getRecursive(e,t,r,s,n){if(r===t.length-1&&!n)return this.getNodeForSegment(e,t[r],s,!1);if(r===t.length){const a=e.getValue();return n&&a!==void 0?a:e}const o=t[r],l=this.getNodeForSegment(e,o,s,!0);if(l)return this.getRecursive(l,t,r+1,s,n)}static getNodeForSegment(e,t,r,s){let n;const o=e.getProperties();if(o&&t in o)n=o[t];else switch(t){case"name":{const l=e.getName();n=new d().setValue(l??null);break}case"description":{const l=e.getDescription();n=new d().setValue(l??null);break}case"type":n=e.getType();break;case"itemType":n=e.getItemType();break;case"keyType":n=e.getKeyType();break;case"valueType":n=e.getValueType();break;case"value":{const l=e.getValue();n=new d().setValue(l??null);break}case"blueId":{const l=e.getBlueId();n=new d().setValue(l??null);break}case"blue":n=e.getBlue();break;case"items":{const l=e.getItems();n=new d().setItems(l);break}case"properties":{const l=e.getProperties();n=new d().setProperties(l);break}case B.OBJECT_CONTRACTS:{const l=e.getContracts();n=new d().setContracts(l);break}default:{if(/^\d+$/.test(t)){const l=parseInt(t,10),a=e.getItems();a&&l>=0&&l<a.length?n=a[l]:n=void 0}else n=void 0;break}}if(n)return s&&r?this.link(n,r):n}static link(e,t){const r=t(e);return u.isNonNullable(r)?r:e}}class d{static INTEGER=new d("Integer");name;description;type;itemType;keyType;valueType;value;items;properties;blueId;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 d().setValue(e).setInlineValue(!0):this.type=e,this}getItemType(){return this.itemType}setItemType(e){return typeof e=="string"?this.itemType=new d().setValue(e).setInlineValue(!0):this.itemType=e,this}getKeyType(){return this.keyType}setKeyType(e){return typeof e=="string"?this.keyType=new d().setValue(e).setInlineValue(!0):this.keyType=e,this}getValueType(){return this.valueType}setValueType(e){return typeof e=="string"?this.valueType=new d().setValue(e).setInlineValue(!0):this.valueType=e,this}getValue(){const e=this.type?.getBlueId();if(u.isNonNullable(e)&&u.isNonNullable(this.value)){if(e===se&&typeof this.value=="string")return new O(this.value);if(e===re&&typeof this.value=="string"){const t=new _(this.value),r=parseFloat(t.toString());return new _(r.toString())}else if(e===ie&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new O(e.toString()):this.value=new _(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}addProperty(e,t){return this.properties||(this.properties={}),this.properties[e]=t,this}removeProperty(e){return this.properties&&delete this.properties[e],this}getContractsProperty(){return this.properties?.[B.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}setContracts(e){return u.isNullable(e)?this.removeProperty(B.OBJECT_CONTRACTS):this.addProperty(B.OBJECT_CONTRACTS,new d().setProperties(e)),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(B.OBJECT_CONTRACTS,new d().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(B.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)}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 zr.get(this,e,t)}getAsNode(e){const t=this.get(e);if(t instanceof d)return t;throw new Error(`Value at path ${e} is not a BlueNode: ${t}`)}getAsInteger(e){const t=this.get(e);if(t instanceof O||t instanceof _)return t.toNumber();throw new Error(`Value at path ${e} is not a BigInteger or BigDecimal: ${t}`)}clone(){const e=new d(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()]))),e.blueId=this.blueId,e.blue=this.blue?.clone(),e.inlineValue=this.inlineValue,e}cloneShallow(){const e=new d(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.blueId=this.blueId,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 Te{static MIN_BLUE_ID_LENGTH=41;static MAX_BLUE_ID_LENGTH=45;static BLUE_ID_PATTERN=/^[1-9A-HJ-NP-Za-km-z]{41,45}(?:#\d+)?$/;static isPotentialBlueId(e){if(!e||e.length===0||!this.BLUE_ID_PATTERN.test(e))return!1;const t=e.split("#"),r=t[0],s=r.length;if(s<this.MIN_BLUE_ID_LENGTH||s>this.MAX_BLUE_ID_LENGTH)return!1;try{if(Oe.default.decode(r).length!==32)return!1}catch{return!1}if(t.length>1)try{if(Number(t[1])<0)return!1}catch{return!1}return!0}}const Ur=h.z.string().max(Te.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(Te.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(i=>{try{return Oe.default.decode(i),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),ve=h.z.lazy(()=>h.z.record(h.z.unknown()).and(h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:ve.optional(),value:h.z.union([h.z.string(),h.z.number(),h.z.boolean()]).optional().nullable(),items:h.z.array(ve).optional()}))),je=h.z.object({blueId:h.z.string().optional(),name:h.z.string().optional(),description:h.z.string().optional(),type:ve.optional()}),Kr=je.extend({value:h.z.string().optional()}),Hr=je.extend({value:h.z.number().optional()}),kr=je.extend({value:h.z.boolean().optional()}),Yr=je.extend({items:h.z.array(h.z.string()).optional()}),Wr=i=>ve.safeParse(i).success,Jt=i=>u.isNonNullable(i)&&"blueId"in i&&u.isNonNullable(i.blueId),Jr=i=>u.isNonNullable(i)&&"name"in i&&u.isNonNullable(i.name),Zt=i=>u.isNonNullable(i)&&"items"in i&&u.isNonNullable(i.items),Gt=i=>u.isNonNullable(i)&&"type"in i&&u.isNonNullable(i.type),qt=i=>u.isNonNullable(i)&&"value"in i&&u.isNonNullable(i.value),Zr=(i,e)=>i.required({type:!0}).safeParse(e).success,E=i=>i instanceof Z,Q=i=>E(i)&&i instanceof O,He=i=>E(i)&&i instanceof _,Gr=h.z.lazy(()=>h.z.record(Ve)),qr=h.z.lazy(()=>h.z.union([h.z.array(Ve),h.z.array(Ve).readonly()])),Ve=h.z.lazy(()=>h.z.union([u.jsonPrimitiveSchema,Gr,qr,h.z.instanceof(Z)])),Pt=i=>H.isObject(i)&&!H.isArray(i)&&!u.isReadonlyArray(i)&&!E(i),St=i=>H.isArray(i)||u.isReadonlyArray(i),Xr=i=>St(i)||Pt(i)||E(i)||u.isJsonPrimitive(i);class m{static deserialize(e){return m.handleNode(e)}static handleNode(e){if(e===void 0)throw new Error("This is not a valid JSON-like value. Found 'undefined' as a value.");if(Pt(e)){const t=new d,r={};return Object.entries(e).forEach(([s,n])=>{switch(s){case le:if(n==null)t.setName(void 0);else{if(typeof n!="string")throw new Error(`The ${le} field must be a string.`);t.setName(n)}break;case ae:if(n==null)t.setDescription(void 0);else{if(typeof n!="string")throw new Error(`The ${ae} field must be a string.`);t.setDescription(n)}break;case K:t.setType(m.handleNode(n));break;case Ne:t.setItemType(m.handleNode(n));break;case Pe:t.setKeyType(m.handleNode(n));break;case Se:t.setValueType(m.handleNode(n));break;case J:t.setValue(m.handleValue(n));break;case V:if(typeof n!="string")throw new Error(`The ${V} field must be a string.`);t.setBlueId(n);break;case W:t.setItems(m.handleArray(n));break;case Le:t.setBlue(m.handleNode(n));break;default:r[s]=m.handleNode(n);break}}),Object.keys(r).length>0&&t.setProperties(r),t}else{if(St(e))return new d().setItems(m.handleArray(e));{const t=e;return new d().setValue(m.handleValue(t)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||E(e))if(Q(e)||Number.isSafeInteger(e)){const t=new O(e.toString()),r=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER;return t.lt(r)?new O(r.toString()):t.gt(s)?new O(s.toString()):t}else{const t=parseFloat(e.toString());return new _(t.toString())}else if(typeof e=="boolean")return e;throw new Error(`Can't handle node: ${JSON.stringify(e)}`)}static handleArray(e){if(e!=null){if(H.isObject(e)&&!Array.isArray(e))return[m.handleNode(e)];if(Array.isArray(e))return e.map(m.handleNode);throw new Error("Expected an array node")}}}function Qr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var nt,_t;function es(){return _t||(_t=1,nt=function i(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?i(e.toJSON()):Array.isArray(e)?`[${e.reduce((s,n,o)=>`${s}${o===0?"":","}${i(n===void 0||typeof n=="symbol"?null:n)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,s)=>{if(e[s]===void 0||typeof e[s]=="symbol")return r;const n=r.length===0?"":",";return`${r}${n}${i(s)}:${i(e[s])}`},"")}}`}),nt}var ts=es();const rs=Qr(ts);class ke{static canonicalize(e){return rs(e)}}const ot=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class wt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new wt),this.instance}initBrowserCrypto(){return ot?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return ot&&!!it.default&&typeof it.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return ot?it.default:null}}class Xt{cryptoEnv=wt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return Oe.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return Oe.default.encode(r)}canonicalizeInput(e){const t=ke.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(jr.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 s=new TextEncoder().encode(e),n=await t.subtle.digest("SHA-256",s);return new Uint8Array(n)}}const w={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 P{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([w.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([w.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),s=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(s)}static textNode(e){return new d().setType(new d().setBlueId(te)).setValue(e)}static integerNode(e){const t=e instanceof O?e:new O(e.toString());return new d().setType(new d().setBlueId(se)).setValue(t)}static doubleNode(e){const t=e instanceof _?e:new _(e.toString());return new d().setType(new d().setBlueId(re)).setValue(t)}static booleanNode(e){return new d().setType(new d().setBlueId(ie)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const s of Object.values(w)){const n=u.isNonNullable(this.getFieldValue(e,s));if(t.has(s)){if(!n)return!1}else if(!r.has(s)){if(n)return!1}}return!0}static getFieldValue(e,t){switch(t){case w.NAME:return e.getName();case w.TYPE:return e.getType();case w.VALUE:return e.getValue();case w.DESCRIPTION:return e.getDescription();case w.PROPERTIES:return e.getProperties();case w.BLUE:return e.getBlue();case w.ITEMS:return e.getItems();case w.KEY_TYPE:return e.getKeyType();case w.VALUE_TYPE:return e.getValueType();case w.ITEM_TYPE:return e.getItemType();case w.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}const ge="$previous",ue="$pos",dt="$empty";class T{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.getProperties()?.[B.OBJECT_MERGE_POLICY]?.getValue();if(t==="append-only"||t==="positional")return t}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 Object.prototype.hasOwnProperty.call(e.getProperties()??{},ge)}static hasPositionProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},ue)}static hasEmptyProperty(e){return Object.prototype.hasOwnProperty.call(e.getProperties()??{},dt)}static isEmptyItem(e){const t=e.getProperties(),r=t?.[dt];return t!==void 0&&Object.keys(t).length===1&&r!==void 0&&P.hasFieldsAndMayHaveFields(e,new Set([w.PROPERTIES]))&&P.hasFieldsAndMayHaveFields(r,new Set([w.VALUE]),new Set([w.TYPE]))&&r.getValue()===!0}static isPreviousItem(e){const t=e.getProperties();return t!==void 0&&Object.keys(t).length===1&&P.hasFieldsAndMayHaveFields(e,new Set([w.PROPERTIES]))&&P.hasBlueIdOnly(t[ge])}static getPreviousBlueId(e){if(this.isPreviousItem(e))return e.getProperties()?.[ge]?.getBlueId()}static createPreviousItem(e){return new d().setProperties({[ge]:new d().setBlueId(e)})}static readPosition(e){const t=e.getProperties()?.[ue];if(t===void 0)return;if(!P.hasFieldsAndMayHaveFields(t,new Set([w.VALUE]),new Set([w.TYPE])))throw new Error("$pos must be a non-negative integer value.");const r=t.getValue(),s=r instanceof O?r.toNumber():typeof r=="number"?r:void 0;if(s===void 0||!Number.isInteger(s)||s<0)throw new Error("$pos must be a non-negative integer value.");return s}static createPositionedItem(e,t){const r=t.clone();return r.addProperty(ue,new d().setValue(e)),r}static withoutPosition(e){const t=e.clone(),r=t.getProperties();return r!==void 0&&(delete r[ue],Object.keys(r).length===0&&t.setProperties(void 0)),t}static hasPayloadAfterRemovingPosition(e){return!P.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)}}const ss=new Set([le,ae,J]),is={$list:"empty"},ns="$listCons",os="prev",ls="elem";class as{constructor(e){this.hashProvider=e}calculate(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!1)}calculateSync(e){const t=this.clean(this.toHashValue(e));if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.calculateInternal(t,!0)}calculateInternal(e,t){return this.isScalar(e)?this.applyHash(this.toJsonScalar(e),t):Array.isArray(e)?this.calculateList(e,t):this.isPureReference(e)?e[V]:this.isScalarWrapper(e)?this.calculateInternal(e[J],t):this.isBasicTypedScalarWrapper(e)?this.calculateInternal(e[J],t):this.isListWrapper(e)?this.calculateInternal(e[W],t):this.isBasicTypedListWrapper(e)?this.calculateInternal(e[W],t):this.calculateMap(e,t)}calculateMap(e,t){const s=Object.entries(e).sort(([o],[l])=>o.localeCompare(l)).map(([o,l])=>{if(ss.has(o))return t?[o,l]:Promise.resolve([o,l]);const a=this.calculateInternal(l,t);return t?[o,{[V]:a}]:Promise.resolve(a).then(c=>[o,{[V]:c}])}),n=o=>{const l={};for(const[a,c]of o)l[a]=c;return this.applyHash(l,t)};return t?n(s):Promise.all(s).then(n)}calculateList(e,t){let r=0,s;const n=e[0];if(n!==void 0&&this.hasPreviousControlKey(n)){const o=this.getPreviousControlBlueId(n);if(o===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");s=t?o:Promise.resolve(o),r=1}else s=this.applyHash(is,t);for(let o=r;o<e.length;o++){const l=e[o];if(this.hasPreviousControlKey(l))throw new Error("$previous list control is allowed only first.");if(this.hasPositionControlKey(l))throw new Error("$pos list controls must be consumed before raw BlueId hashing.");const a=s,c=this.calculateInternal(l,t);t?s=this.applyHash(this.createListFoldInput(a,c),!0):s=Promise.all([a,c]).then(([p,f])=>this.applyHash(this.createListFoldInput(p,f),!1))}return s}createListFoldInput(e,t){return{[ns]:{[os]:{[V]:e},[ls]:{[V]:t}}}}getPreviousControlBlueId(e){if(typeof e!="object"||e===null||Array.isArray(e)||E(e))return;const t=Object.entries(e);if(t.length!==1||t[0][0]!==ge)return;const r=t[0][1];if(!(typeof r!="object"||r===null||Array.isArray(r)||E(r)||!this.isPureReference(r)))return r[V]}hasPreviousControlKey(e){return this.hasControlKey(e,ge)}hasPositionControlKey(e){return this.hasControlKey(e,ue)}hasControlKey(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!E(e)&&Object.prototype.hasOwnProperty.call(e,t)}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}toHashValue(e){return e instanceof d?this.nodeToHashValue(e):Array.isArray(e)?e.map(t=>this.toHashValue(t)).filter(t=>t!==void 0):this.jsonToHashValue(e)}nodeToHashValue(e){const t={};this.setIfPresent(t,le,e.getName()),this.setIfPresent(t,ae,e.getDescription()),this.setIfPresent(t,K,e.getType()),this.setIfPresent(t,Ne,e.getItemType()),this.setIfPresent(t,Pe,e.getKeyType()),this.setIfPresent(t,Se,e.getValueType());const r=e.getValue();r!==void 0&&(t[J]=this.scalarToHashValue(r));const s=e.getItems();s!==void 0&&(t[W]=s.map(o=>this.nodeToHashValue(o))),this.setIfPresent(t,V,e.getReferenceBlueId()),this.setIfPresent(t,Le,e.getBlue());const n=e.getProperties();if(n!==void 0)for(const[o,l]of Object.entries(n))t[o]=this.nodeToHashValue(l);return t}jsonToHashValue(e){if(e!=null){if(this.isScalar(e)||E(e))return this.scalarToHashValue(e);if(Array.isArray(e))return e.map(t=>this.jsonToHashValue(t)).filter(t=>t!==void 0);if(typeof e=="object"){const t={};for(const[r,s]of Object.entries(e))t[r]=this.jsonToHashValue(s);return t}return e}}setIfPresent(e,t,r){r!==void 0&&(e[t]=r instanceof d?this.nodeToHashValue(r):r)}clean(e){if(e==null)return;if(this.isScalar(e))return e;if(Array.isArray(e))return e.map(r=>this.clean(r)).filter(r=>r!==void 0);const t={};for(const[r,s]of Object.entries(e)){const n=this.clean(s);n!==void 0&&(t[r]=n)}return Object.keys(t).length===0?void 0:t}isPureReference(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===V&&typeof t[0]?.[1]=="string"}isScalarWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===J}isBasicTypedScalarWrapper(e){return this.hasOnlyKeys(e,[K,J])&&this.isBasicScalarTypeReference(e[K])}isListWrapper(e){const t=Object.entries(e);return t.length===1&&t[0]?.[0]===W&&Array.isArray(t[0]?.[1])}isBasicTypedListWrapper(e){return this.hasOnlyKeys(e,[K,W])&&this.isTypeReference(e[K],qe)&&Array.isArray(e[W])}hasOnlyKeys(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.prototype.hasOwnProperty.call(e,s))}isBasicScalarTypeReference(e){return this.isTypeReference(e,te)||this.isTypeReference(e,se)||this.isTypeReference(e,re)||this.isTypeReference(e,ie)}isTypeReference(e,t){return typeof e!="object"||e===null||Array.isArray(e)||E(e)?!1:this.isPureReference(e)&&e[V]===t}isScalar(e){return u.isJsonPrimitive(e)&&e!==null||E(e)}scalarToHashValue(e){if(e instanceof O||Q(e)){const t=new Z(Number.MIN_SAFE_INTEGER.toString()),r=new Z(Number.MAX_SAFE_INTEGER.toString());return e.lt(t)||e.gt(r)?e.toString():e.toNumber()}return e instanceof _||E(e)?e.toNumber():e}toJsonScalar(e){return E(e)?this.scalarToHashValue(e):e}}class A{static INSTANCE=new A(new Xt);hasher;constructor(e){this.hasher=new as(e)}static calculateBlueId(e){return A.INSTANCE.calculate(e)}static calculateBlueIdSync(e){return A.INSTANCE.calculateSync(e)}calculate(e){return this.hasher.calculate(e)}calculateSync(e){return this.hasher.calculateSync(e)}}class z{constructor(e={emitListControls:!0}){this.options=e}reverse(e){const t=new d;return this.reverseNode(t,e,void 0,!0),t}static calculateHashMinimalBlueId(e){return A.calculateBlueIdSync(this.toHashMinimalNode(e))}static calculateHashMinimalListBlueId(e){return A.calculateBlueIdSync(e.map(t=>this.toHashMinimalNode(t)))}static toHashMinimalNode(e){return new z({emitListControls:!1}).reverse(e)}reverseNode(e,t,r,s){const n=this.getEffectiveFromType(r,t);!s&&this.isIdenticalToType(t,n)||(this.reverseBasicProperties(e,t,n,s),this.reverseTypeReferences(e,t,r,n),this.reverseItems(e,t,n),this.reverseProperties(e,t,n))}isIdenticalToType(e,t){return u.isNonNullable(e.getBlueId())&&u.isNonNullable(t?.getBlueId())&&e.getBlueId()===t.getBlueId()}reverseBasicProperties(e,t,r,s){const n=t.getValue();u.isNonNullable(n)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(n),u.isNonNullable(t.getName())&&(s||u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(s||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,s){const n=(o,l,a)=>{const c=o(t),p=a?o(a):void 0;u.isNonNullable(c)&&!this.areTypeReferencesEquivalent(c,p)&&l(e,this.toMinimalTypeReference(c))};n(o=>o.getType(),(o,l)=>o.setType(l),r),n(o=>o.getItemType(),(o,l)=>o.setItemType(l),s),n(o=>o.getKeyType(),(o,l)=>o.setKeyType(l),s),n(o=>o.getValueType(),(o,l)=>o.setValueType(l),s)}areTypeReferencesEquivalent(e,t){if(u.isNullable(t))return!1;const r=e.getBlueId(),s=t.getBlueId();return u.isNonNullable(r)||u.isNonNullable(s)?u.isNonNullable(r)&&u.isNonNullable(s)&&r===s:z.calculateHashMinimalBlueId(e)===z.calculateHashMinimalBlueId(t)}toMinimalTypeReference(e){const t=e.getBlueId();if(u.isNonNullable(t))return new d().setBlueId(t);const r=new d;return this.reverseNode(r,e,void 0,!0),P.isEmptyNode(r)?e.clone():r}reverseItems(e,t,r){const s=t.getItems();if(u.isNullable(s))return;const n=r?.getItems();if(s.length===0){(u.isNullable(n)||n.length>0)&&e.setItems([]);return}if(u.isNonNullable(n)&&s.length===n.length&&s.every((l,a)=>z.calculateHashMinimalBlueId(l)===z.calculateHashMinimalBlueId(n[a])))return;const o=this.options.emitListControls!==!1&&u.isNonNullable(n)&&n.length>0?this.reverseInheritedItems(t,r):this.reverseFullItems(s);o.length>0&&e.setItems(o)}reverseInheritedItems(e,t){const r=e.getItems()??[],s=t.getItems()??[];if(r.length<s.length)throw new Error(`Resolved list has fewer items (${r.length}) than inherited list (${s.length}).`);const n=T.getMergePolicy(e,t),o=[];for(let c=0;c<s.length;c++)z.calculateHashMinimalBlueId(r[c])!==z.calculateHashMinimalBlueId(s[c])&&o.push(c);if(o.length>0&&n==="append-only")throw new Error("append-only list cannot be minimized as a non-prefix mutation.");const l=z.calculateHashMinimalListBlueId(s),a=[T.createPreviousItem(l)];for(const c of o){const p=new d;this.reverseNode(p,r[c],s[c],!1);const f=P.isEmptyNode(p)?r[c].clone():p;a.push(T.createPositionedItem(c,f))}for(let c=s.length;c<r.length;c++){const p=new d;this.reverseNode(p,r[c],void 0,!1),a.push(p)}return a.length===1?[]:a}reverseFullItems(e){const t=[];for(let r=0;r<e.length;r++){const s=new d;this.reverseNode(s,e[r],void 0,!1),t.push(s)}return t}reverseProperties(e,t,r){const s=t.getProperties();if(u.isNullable(s))return;const n={};for(const[o,l]of Object.entries(s)){const a=this.getInheritedProperty(o,r),c=new d;this.reverseNode(c,l,a,!1),P.isEmptyNode(c)||(n[o]=c)}Object.keys(n).length>0&&e.setProperties(n)}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(!P.isEmptyNode(t))return t}mergeNodes(e,t){const r=e.clone(),s=t.getValue();u.isNonNullable(s)&&r.setValue(s);const n=t.getType();u.isNonNullable(n)&&r.setType(n.clone());const o=t.getItemType();u.isNonNullable(o)&&r.setItemType(o.clone());const l=t.getKeyType();u.isNonNullable(l)&&r.setKeyType(l.clone());const a=t.getValueType();u.isNonNullable(a)&&r.setValueType(a.clone());const c=t.getProperties();if(u.isNonNullable(c)){const f=r.getProperties()||{};for(const[y,g]of Object.entries(c)){const I=f[y];f[y]=I===void 0?g.clone():this.mergeNodes(I,g)}r.setProperties(f)}const p=t.getItems();return u.isNonNullable(p)&&r.setItems(p.map(f=>f.clone())),r}}class ht{mergeReverser=new z;hashMergeReverser=new z({emitListControls:!1});minimize(e){return this.minimizeResolved(e)}minimizeResolved(e){return this.mergeReverser.reverse(e)}minimizeResolvedForHash(e){return this.hashMergeReverser.reverse(e)}}class he extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r&&r.length>0?r:[],this.name="BlueError"}}const x={AMBIGUOUS_BLUE_ID_PAYLOAD:"AMBIGUOUS_BLUE_ID_PAYLOAD",BLUE_ID_MISMATCH:"BLUE_ID_MISMATCH",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 q{static RESERVED_PROPERTY_KEYS=new Set([B.OBJECT_SCHEMA,B.OBJECT_MERGE_POLICY,B.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((n,o)=>{this.validateListControlNode(n,[...t,"items",String(o)],o)});const s=e.getProperties();if(s!==void 0)for(const[n,o]of Object.entries(s))this.validateListControlNode(o,[...t,n])}static validateNode(e,t,r){r.insideItems&&this.validateListControlItem(e,t,r.itemIndex??0);const s=e.getReferenceBlueId();if(s!==void 0&&!P.hasBlueIdOnly(e))if(r.insideItems&&T.hasPositionProperty(e)&&P.hasBlueIdOnly(T.withoutPosition(e)))T.readPosition(e);else{const f=this.toPointer(t);throw new he(x.AMBIGUOUS_BLUE_ID_PAYLOAD,`Ambiguous blueId plus payload at ${f}. Use exact { blueId } for references or remove blueId from payload content.`,[{code:x.AMBIGUOUS_BLUE_ID_PAYLOAD,message:"A storage or authoring node cannot combine blueId with payload.",locationPath:t,context:{blueId:s}}])}const n=this.getChildProperties(e,t,r),o=e.getValue()!==void 0,l=e.getItems()!==void 0,a=Object.keys(n).length>0;o&&l&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value and items payloads."),o&&a&&this.throwInvalidStorageShape(t,"A storage or authoring node cannot combine value payload with object child fields."),l&&a&&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((p,f)=>{this.validateNode(p,[...t,"items",String(f)],{insideItems:!0,itemIndex:f})});const c=e.getProperties();if(c!==void 0)for(const[p,f]of Object.entries(c))this.validateNode(f,[...t,p],{insideItems:!1})}static validateListControlItem(e,t,r){if(T.hasEmptyProperty(e)&&(T.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $previous."),T.hasPositionProperty(e)&&this.throwInvalidStorageShape(t,"$empty cannot be combined with $pos."),T.isEmptyItem(e)||this.throwInvalidStorageShape(t,"$empty list content must be exactly { $empty: true }.")),T.hasPreviousProperty(e)&&(r!==0&&this.throwInvalidStorageShape(t,"$previous list control is allowed only as the first item."),T.isPreviousItem(e)||this.throwInvalidStorageShape(t,"$previous list control must be exactly { $previous: { blueId: <id> } }.")),T.hasPositionProperty(e)){T.hasPreviousProperty(e)&&this.throwInvalidStorageShape(t,"$pos cannot be combined with $previous.");try{T.readPosition(e)}catch(s){this.throwInvalidStorageShape([...t,ue],s instanceof Error?s.message:"$pos must be a non-negative integer value.")}T.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 s=e.getProperties()??{};return Object.prototype.hasOwnProperty.call(s,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(s).filter(([n])=>!this.RESERVED_PROPERTY_KEYS.has(n)&&!(r.insideItems&&(n===ue||n===dt))))}static throwInvalidStorageShape(e,t){const r=this.toPointer(e);throw new he(x.INVALID_STORAGE_SHAPE,`${t} at ${r}`,[{code:x.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 cs{static convert(e){const t=Oe.default.decode(e),r=new Uint8Array(2+t.length);r[0]=18,r[1]=32,r.set(t,2);const s=new Uint8Array(2+r.length);return s[0]=1,s[1]=85,s.set(r,2),"b"+new $r.Encoder({type:"rfc4648",lc:!0}).write(s).finalize().replace(/=/g,"")}}class v{static get(e,t="official"){const{strategy:r}=this.normalizeOptions(t),s=e.getValue(),n=this.handleValue(s);if(n!==void 0&&r==="simple")return n;const o=e.getItems()?.map(F=>v.get(F,r));if(o!==void 0&&r==="simple")return o;const l=e.getName(),a=e.getDescription();if(r==="original"&&l===void 0&&a===void 0){if(n!==void 0)return n;if(o!==void 0)return o}const c={};l!==void 0&&(c[le]=l),a!==void 0&&(c[ae]=a);const p=e.getType();if(r==="official"&&s!==void 0&&p===void 0){const F=this.inferTypeBlueId(s);F!==null&&(c[K]={[V]:F})}else p!==void 0&&(c[K]=v.get(p,r));const f=e.getItemType();f!==void 0&&(c[Ne]=v.get(f,r));const y=e.getKeyType();y!==void 0&&(c[Pe]=v.get(y,r));const g=e.getValueType();g!==void 0&&(c[Se]=v.get(g,r)),n!==void 0&&(c[J]=n),o!==void 0&&(c[W]=o);const I=e.getBlueId();I!==void 0&&(c[V]=I);const D=e.getBlue();D!==void 0&&(c[Le]=D);const N=e.getProperties();return N!==void 0&&Object.entries(N).forEach(([F,b])=>{c[F]=v.get(b,r)}),c}static handleValue(e){if(E(e)){if(Q(e)){const t=new Z(Number.MIN_SAFE_INTEGER.toString()),r=new Z(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"?te:E(e)?Q(e)?se:re:typeof e=="boolean"?ie: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()),s=r.getType();s!==void 0&&r.setType(M.transform(s,t));const n=r.getItemType();n!==void 0&&r.setItemType(M.transform(n,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(M.transform(o,t));const l=r.getValueType();l!==void 0&&r.setValueType(M.transform(l,t));const a=r.getItems();if(a!==void 0){const p=a.map(f=>M.transform(f,t));r.setItems(p)}const c=r.getProperties();if(c!==void 0){const p=Object.keys(c).reduce((f,y)=>(f[y]=M.transform(c[y],t),f),{});r.setProperties(p)}return r}}const ce=i=>!!i&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof d),X=i=>i instanceof O||i instanceof _,us=i=>i.replace(/~1/g,"/").replace(/~0/g,"~");function we(i){if(i==="/")return[];if(!i.startsWith("/"))throw new Error(`Path must start with '/': ${i}`);return i.split("/").slice(1).map(us)}function Be(i){if(i==="-")return-1;const e=typeof i=="number"?i:parseInt(i,10);if(isNaN(e))throw new Error(`Invalid array index (NaN) from '${i}'`);if(!Number.isFinite(e))throw new Error(`Invalid array index '${i}' results in non-finite number ${e}`);return e}function Qt(i,e,t,r=!0){switch(e){case"name":return t?r?i.getName()??null:i:i.getName();case"description":return t?r?i.getDescription():i:i.getDescription();case"type":return i.getType();case"itemType":return i.getItemType();case"keyType":return i.getKeyType();case"valueType":return i.getValueType();case"value":return t?r?i.getValue()??null:i:i.getValue();case"blueId":return t?r?i.getBlueId()??null:i:i.getBlueId();case"blue":return i.getBlue();case"items":return i.getItems();case"properties":return i.getProperties();case B.OBJECT_CONTRACTS:return i.getContracts();default:return}}function Dt(i,e,t=!0){if(i instanceof d){const r=Qt(i,e,!0,t);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",B.OBJECT_CONTRACTS].includes(e))return r;if(/^-?\d+$/.test(e)&&e!=="-"){const n=i.getItems(),o=parseInt(e,10);return n&&o>=0&&o<n.length?n[o]:void 0}const s=i.getProperties();return s&&e in s?s[e]:void 0}if(Array.isArray(i)){if(e==="-")return;const r=Be(e);return r>=0&&r<i.length?i[r]:void 0}if(ce(i))return i[e]}function Ee(i,e){if(e.length===0)return{parent:i,key:"value",actualTarget:i.getValue()??i};let t=i;for(let s=0;s<e.length-1;++s){const n=e[s],o=Dt(t,n);if(o===void 0)throw new Error(`Cannot resolve '/${e.slice(0,s+1).join("/")}'`);t=o}const r=e[e.length-1];if(t instanceof d){const s=Dt(t,r,!1);if((typeof s!="object"||s===null||X(s))&&!(s instanceof d)&&!Array.isArray(s)&&["name","description","value","blueId"].includes(r))return{parent:t,key:r,actualTarget:s}}return Array.isArray(t)&&r==="-"?{parent:t,key:"-"}:t instanceof d&&t.getItems()&&r==="-"?{parent:t,key:"-"}:{parent:t,key:Array.isArray(t)?Be(r):r}}function Et(i,e){if(i instanceof d){const t=e,r=Qt(i,t,!1);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",B.OBJECT_CONTRACTS].includes(t))return r;if(typeof e=="number"||typeof e=="string"&&/^\d+$/.test(e)){const s=i.getItems(),n=typeof e=="number"?e:parseInt(e,10);if(s&&n>=0&&n<s.length)return s[n]}return i.getProperties()?.[t]}return Array.isArray(i)||ce(i)?i[e]:i}function L(i){if(i instanceof d)return i;if(i===null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"||X(i))return m.deserialize(i);const e=pt(i);return m.deserialize(e)}function pt(i){if(i===void 0)return null;if(i===null||typeof i!="object")return i;if(Array.isArray(i))return i.map(pt);const e={};for(const[t,r]of Object.entries(i))e[t]=pt(r);return e}function Ct(i,e,t){if(i instanceof d){const r=e;switch(r){case"name":i.setName(t);return;case"description":i.setDescription(t);return;case"type":i.setType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"itemType":i.setItemType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"keyType":i.setKeyType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"valueType":i.setValueType(t instanceof d||typeof t=="string"||t===void 0?t:L(t));return;case"value":{const s=t;i.setValue(s===void 0?null:s);return}case"blueId":i.setBlueId(t);return;case"blue":i.setBlue(t instanceof d||t===void 0?t:L(t));return;case"items":i.setItems(t);return;case"properties":i.setProperties(t);return;case B.OBJECT_CONTRACTS:i.setContracts(t);return;default:{if(t===void 0){const s=i.getProperties();s&&r in s&&delete s[r]}else i.getProperties()||i.setProperties({}),i.addProperty(r,t instanceof d?t:L(t));return}}}Array.isArray(i)?i.splice(Be(e),1):ce(i)&&(t===void 0?delete i[e]:i[e]=t)}function ds(i,e,t,r){let s=-1;if(e!=="-"&&(s=typeof e=="number"?e:parseInt(e,10),isNaN(s)))throw new Error(`Invalid numeric key for BlueNode item operation: ${e}`);if(s<-1)throw new Error(`Invalid array index for BlueNode items: ${s}`);let n=i.getItems();if(n||(n=[],i.setItems(n)),!r&&s!==-1&&s>n.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${n.length}.`);if(e==="-")n.push(t);else if(r){if(s>=0)if(s<n.length)n[s]=t;else{for(let o=n.length;o<s;o++)n.push(m.deserialize(null));n.push(t)}}else n.splice(s,0,t)}function Ye(i,e,t,r){if(Array.isArray(i)){const s=e==="-"?i.length:Be(e);if(!r&&s>i.length)throw new Error(`ADD operation failed: Target array index '${s}' is greater than array length ${i.length}. Path involving key '${e}'.`);if(s<0&&e!=="-")throw new Error(`Invalid negative array index: ${e}`);const n=L(t);if(r){if(s>=0&&s<i.length)i[s]=n;else if(s>=i.length){for(let o=i.length;o<s;o++)i.push(m.deserialize(null));i.push(n)}}else i.splice(s,0,n);return}if(i instanceof d){e==="-"||typeof e=="number"&&!isNaN(e)||typeof e=="string"&&/^\d+$/.test(e)?ds(i,e,L(t),r):Ct(i,e,t);return}if(ce(i)){i[e]=L(t);return}throw new Error(`Cannot insert into parent of type ${typeof i}`)}function hs(i,e){if(Array.isArray(i)){const t=Be(e);t===-1&&e==="-"?i.length>0&&i.pop():t>=0&&t<i.length&&i.splice(t,1);return}if(i instanceof d){if(typeof e=="number"||typeof e=="string"&&/^-?\d+$/.test(e)){const t=i.getItems();if(t){const r=Be(e);r===-1&&e==="-"?t.length>0&&t.pop():r>=0&&r<t.length&&t.splice(r,1),t.length===0&&i.setItems(void 0);return}}Ct(i,e,void 0)}else ce(i)&&delete i[e]}function ft(i){if(i instanceof d)return i.clone();if(Array.isArray(i))return i.map(t=>ft(t));if(ce(i)){const e={};return Object.keys(i).forEach(t=>{e[t]=ft(i[t])}),e}return i}function de(i,e){if(i===e||i instanceof d&&(i.isInlineValue()||i.getValue()!==void 0)&&de(i.getValue()??null,e)||e instanceof d&&(e.isInlineValue()||e.getValue()!==void 0)&&de(i,e.getValue()??null))return!0;if(i instanceof d&&e instanceof d||X(i)&&X(e)||X(i)&&typeof e=="number"||typeof i=="number"&&X(e))return i.toString()===e.toString();if(Array.isArray(i)&&Array.isArray(e))return i.length===e.length&&i.every((t,r)=>de(t,e[r]));if(ce(i)&&ce(e)){const t=Object.keys(i),r=Object.keys(e);return t.length===r.length&&t.every(s=>de(i[s],e[s]))}return!1}function er(i,e){const{parent:t,key:r}=Ee(i,we(e));return Et(t,r)}function tr(i,e,t){const r=we(e);if(r.length===0&&e==="/"){const o=L(t);i.setValue(o.getValue()??null),o.getItems()?i.setItems(o.getItems()):i.setItems(void 0);return}const{parent:s,key:n}=Ee(i,r);Ye(s,n,t,!0)}function ps(i,e,t){const r=we(e);if(r.length===0&&e==="/"){if(i.getItems()&&Array.isArray(t)){const o=L(t);o.getItems()?(i.setItems(o.getItems()),i.setValue(null)):(i.setValue(o.getValue()??null),i.setItems(void 0))}else{const o=L(t);i.setValue(o.getValue()??null),o.getItems()&&i.setItems(o.getItems())}return!0}const{parent:s,key:n}=Ee(i,r);return Ye(s,n,t,!1),!0}function fs(i,e,t){const r=we(e);if(r.length===0&&e==="/"){const l=L(t);return i.setValue(l.getValue()??null),l.getItems()?i.setItems(l.getItems()):i.setItems(void 0),!0}const{parent:s,key:n,actualTarget:o}=Ee(i,r);if(o!==void 0&&s instanceof d)Ct(s,n,t);else{const l=Et(s,n),a=Array.isArray(s)||s instanceof d&&s.getItems()&&(typeof n=="number"||typeof n=="string"&&/^\d+$/.test(n));if(l===void 0){if(a)throw new Error(`REPLACE failed: Target array index '${n.toString()}' is out of bounds or does not exist at path '${e}'.`);Ye(s,n,t,!0)}else Ye(s,n,t,!0)}return!0}function rr(i,e){const t=we(e);if(t.length===0&&e==="/")return i.setValue(null),i.setItems(void 0),i.setProperties(void 0),!0;const{parent:r,key:s}=Ee(i,t);return hs(r,s),!0}function ys(i,e,t){const r=ft(er(i,e));return tr(i,t,r),!0}function gs(i,e,t){const r=we(e),{parent:s,key:n}=Ee(i,r),o=Et(s,n);if(o===void 0)throw new Error(`MOVE failed: 'from' location '${e}' does not exist.`);return rr(i,e)?(tr(i,t,o),!0):!1}function ms(i,e,t){const r=er(i,e);let s=t;if(r instanceof d)if((t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||X(t))&&(r.isInlineValue()||r.getValue()!==void 0)){if(!de(r.getValue()??null,t))throw new Error(`TEST failed at '${e}': Expected ${JSON.stringify(t)}, got ${JSON.stringify(r.getValue()??null)}`);return!0}else typeof t=="object"&&!(t instanceof d)&&(s=L(t));else if(X(r)&&typeof t=="number")r instanceof O?s=new O(t.toString()):r instanceof _&&(s=new _(t.toString()));else if((r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&X(t)){const n=t;!de(r,n.toString())&&(typeof r=="number"&&parseFloat(n.toString()))}if(!de(r,s)){const n=r instanceof d?r.toString():JSON.stringify(r),o=s instanceof d?s.toString():JSON.stringify(s);throw new Error(`TEST failed at '${e}': Expected ${o}, got ${n}`)}return!0}function Is(i,e){switch(e.op){case"add":return ps(i,e.path,e.val);case"replace":return fs(i,e.path,e.val);case"remove":return rr(i,e.path);case"copy":return ys(i,e.from,e.path);case"move":return gs(i,e.from,e.path);case"test":return ms(i,e.path,e.val)}}function Ts(i,e,t=!1){const r=t?i:i.clone();return Is(r,e),r}const lt=Symbol.for("zod-schema-annotations");function vs(){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 sr(){const i=vs();return lt in i||(i[lt]=new WeakMap),i[lt]}function xe(i,e){const t=sr(),r=t.get(i)||{};return t.set(i,{...r,...e}),i}const G=i=>sr().get(i),ir=i=>e=>{const t=G(e);return xe(e,{...t,blueDescription:i})},nr=i=>{const e=G(i);return u.isNonNullable(e)&&H.isString(e.blueDescription)?e.blueDescription:null},Bs=i=>ir(i)(h.z.string().optional()),bs=h.z.union([h.z.string(),h.z.boolean()]),or=i=>e=>{const t=G(e);return xe(e,{...t,blueId:i})},lr=i=>{const e=G(i),t=bs.safeParse(e?.blueId);return t.success?t.data:null},Ns=i=>or(i??!0)(h.z.string()),ar=i=>e=>{const t=G(e);return xe(e,{...t,blueName:i})},cr=i=>{const e=G(i);return u.isNonNullable(e)&&H.isString(e.blueName)?e.blueName:null},Ps=i=>{const e=h.z.string().optional();return ar(i)(e)},ur=()=>i=>{const e=G(i);return xe(i,{...e,blueNode:!0})},dr=i=>{const e=G(i);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},Rt=i=>!!dr(i),Ss=()=>{const i=h.z.instanceof(d);return ur()(i)},ws=h.z.object({value:h.z.array(h.z.string()).optional(),defaultValue:h.z.string().optional()}),hr=i=>{const e=G(i),t=ws.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},pr=i=>e=>{const t=G(e),r=typeof i=="string"?{value:[i]}:i;return xe(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class Me{static resolveBlueId(e){const t=hr(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const s=t.value?.[0];return u.isNonNullable(s)?s:Me.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}class U{static isTypeOf(e,t,r){const s=Me.resolveBlueId(t),n=e.getType()?.getBlueId();if(u.isNullable(s)||u.isNullable(n))return!1;const o=r?.blueIdMapper?.toCurrentBlueId(s)??s,l=r?.blueIdMapper?.toCurrentBlueId(n)??n;if(o===l)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const a=r.typeSchemaResolver.resolveSchema(e);return U.checkSchemaExtension(a,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const s=U.unwrapSchema(e),n=U.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(s,n):!1}static isWrapperType(e){return e instanceof h.ZodOptional||e instanceof h.ZodNullable||e instanceof h.ZodReadonly||e instanceof h.ZodBranded||e instanceof h.ZodEffects||e instanceof h.ZodLazy}static unwrapSchema(e){return Rt(e)?e:U.isWrapperType(e)?e instanceof h.ZodEffects?U.unwrapSchema(e.innerType()):e instanceof h.ZodLazy?U.unwrapSchema(e.schema):U.unwrapSchema(e.unwrap()):e}}const fr=Symbol("blue.subtypeCache");function Es(i,e){return i[fr]=e,i}function Lt(i,e){const t=i.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(fe.includes(r)){const n=Xe[r];return new d().setBlueId(r).setName(n)}const s=e.fetchByBlueId(r);if(!s||s.length===0)return;if(s.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return s[0].cloneShallow().setBlueId(r)}return t}function C(i,e,t){const r=We(i),s=We(e),n=t[fr],o=`${r}|${s}`,l=n?.get(o);if(l!==void 0)return l;const a=Cs(i,e,t,r,s);return n?.set(o,a),a}function We(i){const e=i.getReferenceBlueId();return e!==void 0?e:A.calculateBlueIdSync(ne(i))}function ne(i){if(!yr(i))return i;const e=i.cloneShallow();e.getReferenceBlueId()!==void 0&&!P.hasBlueIdOnly(e)&&e.setReferenceBlueId(void 0);const t=e.getType();t!==void 0&&e.setType(ne(t));const r=e.getItemType();r!==void 0&&e.setItemType(ne(r));const s=e.getKeyType();s!==void 0&&e.setKeyType(ne(s));const n=e.getValueType();n!==void 0&&e.setValueType(ne(n));const o=e.getBlue();o!==void 0&&e.setBlue(ne(o));const l=e.getItems();l!==void 0&&e.setItems(l.map(c=>ne(c)));const a=e.getProperties();return a!==void 0&&e.setProperties(Object.fromEntries(Object.entries(a).map(([c,p])=>[c,ne(p)]))),e}function yr(i){return i.getReferenceBlueId()!==void 0&&!P.hasBlueIdOnly(i)?!0:[i.getType(),i.getItemType(),i.getKeyType(),i.getValueType(),i.getBlue(),...i.getItems()??[],...Object.values(i.getProperties()??{})].some(t=>t!==void 0&&yr(t))}function Cs(i,e,t,r,s){if(r===s)return!0;if(r&&fe.includes(r)){let a=e;for(;a!==void 0;){if(We(a)===r)return!0;a=Lt(a,t)}return!1}let n=i;const o=i.getBlueId();if(o){const a=t.fetchByBlueId(o);a&&a.length===1&&(n=a[0])}let l=n;for(;l!==void 0;){if(We(l)===s)return!0;l=Lt(l,t)}return!1}function Rs(i,e){return Nt.some(t=>{const r=new d().setBlueId(t);return C(i,r,e)})}function As(i,e){const t=new d().setBlueId(te);return C(i,t,e)}function Os(i,e){const t=new d().setBlueId(se);return C(i,t,e)}function Vs(i,e){const t=new d().setBlueId(re);return C(i,t,e)}function Ms(i,e){const t=new d().setBlueId(ie);return C(i,t,e)}function Ue(i,e){const t=new d().setBlueId(qe);return C(i,t,e)}function Ke(i,e){const t=new d().setBlueId(bt);return C(i,t,e)}function _s(i,e){return Ge.some(t=>{const r=new d().setName(t);return C(i,r,e)})}function Ds(i,e){for(const t of Ge){const r=new d().setName(t);if(C(i,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${i.getName()||"unknown"}".`)}class gr{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=Me.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),s=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(s))return!1;if(r===s)return!0;if(u.isNonNullable(this.nodeProvider))try{const n=new d().setBlueId(r),o=new d().setBlueId(s);if(C(n,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=Me.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,s]of this.blueIdMap)if(s===e||s._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)?A.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}class Qe{}class Ce{static convert(e){const t=new yt;return Ce.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const s=e.getProperties(),n=e.getItems(),o=s!==void 0&&Object.keys(s).length>0,l=n!==void 0&&n.length>0;if(!o&&!l){r.addPath(t===""?"/":t);return}if(s)for(const[a,c]of Object.entries(s)){const p=`${t}/${a}`;Ce.traverseNode(c,p,r)}if(n)for(let a=0;a<n.length;a++){const c=`${t}/${a}`;Ce.traverseNode(n[a],c,r)}}}function jt(i,e){const t=i.split(e),r=[...t].reverse().findIndex(n=>n!==""),s=r===-1?0:t.length-r;return t.slice(0,s)}class et extends Qe{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=jt(e,"/"),s=jt(t,"/");if(s.length>r.length)return!1;for(let n=1;n<s.length;n++)if(r[n]!=="*"&&r[n]!==s[n])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 yt().setMaxDepth(e);for(let r=1;r<=e;r++){const s="/"+Array(r).fill("*").join("/");t.addPath(s)}return t.build()}static withSinglePath(e){return new yt().addPath(e).build()}static fromNode(e){return Ce.convert(e)}}class yt{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 et(this.allowedPaths,this.maxDepth)}}class Y extends Qe{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class tt extends Qe{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 tt(e)}}const $=new Y;class k extends d{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 d().setReferenceBlueId(this.sourceSemanticBlueId);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return new ht().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 ht().minimizeResolvedForHash(this);return A.calculateBlueIdSync(t)}clone(){const e=super.clone();return new k(e,this.getMetadata())}cloneShallow(){const e=super.cloneShallow();return new k(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(!Te.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()).setBlueId(e.getBlueId()).setBlue(e.getBlue()).setInlineValue(e.isInlineValue());const t=e.getValue();t!==void 0&&this.setValue(t)}}class Ls{blue;constructor(e){this.blue=e}matchesType(e,t,r=$){const s=et.fromNode(t),n=tt.of(r,s),o=this.extendAndResolve(e,n),l=this.blue.resolve(t,n),a=this.expandSchemaOwnedTypeReferences(t);return this.recursiveValueComparison(o,l,a,n)?this.verifyMatch(o,t,n)||t.getType()===void 0:!1}extendAndResolve(e,t){const r=e.clone(),s=r.clone();this.blue.extend(s,t);const n=this.blue.resolve(s,t);return this.restoreMissingStructure(n,r),n}restoreMissingStructure(e,t){const r=t.getItems(),s=e.getItems();if(r&&r.length>0)if(!s||s.length===0)e.setItems(r.map(a=>a.clone()));else for(let a=0;a<Math.min(s.length,r.length);a++)this.restoreMissingStructure(s[a],r[a]);const n=t.getProperties();if(n){let a=e.getProperties();a||(a={},e.setProperties(a));for(const[c,p]of Object.entries(n)){const f=a[c];f===void 0?a[c]=p.clone():this.restoreMissingStructure(f,p)}}const o=t.getBlueId();e.getBlueId()===void 0&&o!==void 0&&e.setBlueId(o);const l=t.getValue();e.getValue()===void 0&&l!==void 0&&e.setValue(l)}verifyMatch(e,t,r){const s=t.getType();if(this.matchesImplicitStructure(e,s))return!0;const n=e.clone().setType(t.clone());try{this.blue.resolve(n,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,s=$){const n=t.getType(),o=this.matchesImplicitStructure(e,n)||this.matchesImplicitCoreCollectionType(e,t);if(e.getType()===void 0&&this.isCoreCollectionType(t)&&!o)return!1;if(n&&!o){const b=e.getType();if(!b||!C(b,n,this.blue.getNodeProvider()))return!1}const l=t.getBlueId();if(!o&&l!==void 0)if(this.isExplicitBlueIdMatcher(r)){if(e.getBlueId()!==l&&!this.matchesCalculatedBlueId(e,l))return!1}else{const b=e.getBlueId(),S=e.getType();if(S===void 0&&b!==void 0&&b!==l||S&&!C(S,t,this.blue.getNodeProvider()))return!1}const a=e.getBlueId();if(!o&&l===void 0&&a!==void 0&&e.getType()===void 0&&t.getItems()===void 0&&this.hasMatcherShape(t)&&!this.matchesCalculatedBlueId(t,a))return!1;const c=t.getValue();if(c!==void 0){const b=e.getValue();if(b===void 0)return!1;if(E(b)&&E(c)){if(!b.eq(c))return!1}else if(b!==c)return!1}const p=t.getItems(),f=r.getItems();if(p!==void 0){const b=e.getItems()??[];for(let S=0;S<p.length;S++)if(S<b.length){if(!this.recursiveValueComparison(b[S],p[S],f?.[S]??p[S],s))return!1}else if(this.hasValueInNestedStructure(p[S]))return!1}const y=t.getItemType(),g=r.getItemType();if(y!==void 0){const b=e.getItems()??[];for(const S of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(S,y,g??y,s),y,g??y,s))return!1}const I=t.getProperties(),D=r.getProperties();if(I!==void 0){const b=e.getProperties()??{};for(const[S,st]of Object.entries(I))if(S in b){if(!this.recursiveValueComparison(b[S],st,D?.[S]??st,s))return!1}else if(this.hasValueInNestedStructure(st))return!1}const N=t.getValueType(),F=r.getValueType();if(N!==void 0){const b=Object.values(e.getProperties()??{});for(const S of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(S,N,F??N,s),N,F??N,s))return!1}return!0}resolveUntypedNodeAgainstMatcherType(e,t,r,s){return e.getType()!==void 0||this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,s)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const s of t)if(this.hasValueInNestedStructure(s))return!0}const r=e.getProperties();if(r!==void 0){for(const s of Object.values(r))if(this.hasValueInNestedStructure(s))return!0}return!1}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}matchesCalculatedBlueId(e,t){if(e instanceof k&&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}}}toPlainBlueNode(e){const t=new d(e.getName());t.setDescription(e.getDescription()).setReferenceBlueId(e.getReferenceBlueId()).setInlineValue(e.isInlineValue());const r=e.getValue();r!==void 0&&t.setValue(r);const s=e.getType();s!==void 0&&t.setType(this.toPlainBlueNode(s));const n=e.getItemType();n!==void 0&&t.setItemType(this.toPlainBlueNode(n));const o=e.getKeyType();o!==void 0&&t.setKeyType(this.toPlainBlueNode(o));const l=e.getValueType();l!==void 0&&t.setValueType(this.toPlainBlueNode(l));const a=e.getItems();a!==void 0&&t.setItems(a.map(f=>this.toPlainBlueNode(f)));const c=e.getProperties();c!==void 0&&t.setProperties(Object.fromEntries(Object.entries(c).map(([f,y])=>[f,this.toPlainBlueNode(y)])));const p=e.getBlue();return p!==void 0&&t.setBlue(this.toPlainBlueNode(p)),t}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:Ue(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ke(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:Ue(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ke(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return Ue(e,this.blue.getNodeProvider())||Ke(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.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}isExplicitBlueIdMatcher(e){return this.isBareBlueIdReference(e)}resolveAgainstTargetType(e,t,r){try{const s=e.clone(),n=s.clone().setType(t.clone()),o=this.blue.resolve(n,r);return this.restoreMissingStructure(o,s),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()),s=e.getType();s&&e.setType(this.expandReferencedTypeNode(s,r));const n=e.getItemType();n&&e.setItemType(this.expandReferencedTypeNode(n,r));const o=e.getKeyType();o&&e.setKeyType(this.expandReferencedTypeNode(o,r));const l=e.getValueType();l&&e.setValueType(this.expandReferencedTypeNode(l,r));const a=e.getItems();a&&e.setItems(a.map(p=>this.expandSchemaTypeReferences(p,r)));const c=e.getProperties();return c&&e.setProperties(Object.fromEntries(Object.entries(c).map(([p,f])=>[p,this.expandSchemaTypeReferences(f,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 s=this.blue.getNodeProvider().fetchByBlueId(r);return!s||s.length!==1?e.clone():this.expandSchemaTypeReferences(s[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}class j{static ZERO_BLUE_ID="0".repeat(44);static THIS_INDEX_REFERENCE_PATTERN=/^this#(\d+)$/;prepareDocument;calculateBlueId;constructor(e={}){this.prepareDocument=e.prepareDocument??(t=>t),this.calculateBlueId=e.calculateBlueId??A.calculateBlueIdSync}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((l,a)=>{const c=this.prepareDocument(this.replaceIndexedThisReferences(l,()=>j.ZERO_BLUE_ID));return{originalIndex:a,preliminaryBlueId:this.calculateBlueId(c),node:l}});this.validateUniquePreliminaryBlueIds(t);const r=[...t].sort(this.comparePreliminaryDocuments),s=[];r.forEach(({originalIndex:l},a)=>{s[l]=a});const n=r.map(({node:l})=>this.prepareDocument(this.replaceIndexedThisReferences(l,a=>`this#${s[a]}`))),o=this.calculateBlueId(n);return{blueId:o,nodes:n,documentBlueIds:n.map((l,a)=>`${o}#${a}`),originalToSortedIndexes:s}}comparePreliminaryDocuments(e,t){return e.preliminaryBlueId<t.preliminaryBlueId?-1:e.preliminaryBlueId>t.preliminaryBlueId?1:0}validateUniquePreliminaryBlueIds(e){const t=new Map;for(const r of e){const s=t.get(r.preliminaryBlueId);if(s!==void 0)throw new Error(`Direct cyclic document set has ambiguous canonical ordering: documents ${s} and ${r.originalIndex} share preliminary BlueId '${r.preliminaryBlueId}'.`);t.set(r.preliminaryBlueId,r.originalIndex)}}validateCyclicSet(e){if(e.length===0)throw new Error("Cyclic document set cannot be empty.");this.visitReferences(e,(t,r)=>{if(r==="this")throw new Error("Direct cyclic document sets must use indexed references such as 'this#0'; unindexed 'this' is not supported.");if(r.startsWith("this#")&&!j.THIS_INDEX_REFERENCE_PATTERN.test(r))throw new Error(`Malformed direct cyclic reference '${r}'. Expected 'this#<non-negative-integer>'.`);const s=this.readIndexedThisReference(r);if(s!==void 0&&s>=e.length)throw new Error(`Direct cyclic reference '${r}' points outside the ${e.length}-document set.`)})}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 s=this.readIndexedThisReference(r);s!==void 0&&e.setReferenceBlueId(t(s))}this.childrenOf(e).forEach(s=>this.rewriteIndexedThisReferences(s,t))}static nodeHasThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{(s==="this"||s.startsWith("this#"))&&(t=!0)}),t}static nodeHasIndexedThisReference(e){let t=!1;return this.visitNodeReferences(e,(r,s)=>{j.THIS_INDEX_REFERENCE_PATTERN.test(s)&&(t=!0)}),t}visitReferences(e,t){e.forEach(r=>j.visitNodeReferences(r,t))}static visitNodeReferences(e,t){const r=e.getReferenceBlueId();r!==void 0&&t(e,r),this.childrenOf(e).forEach(s=>this.visitNodeReferences(s,t))}readIndexedThisReference(e){const t=e.match(j.THIS_INDEX_REFERENCE_PATTERN);if(t!==null)return Number(t[1])}childrenOf(e){return j.childrenOf(e)}static childrenOf(e){return[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].filter(t=>t!==void 0)}}class ye{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function rt(i){return new class extends ye{fetchByBlueId(e){return i(e)}}}class mr{resolveWithoutLimits(e){return this.resolve(e,$)}}class Ir extends ye{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 at=pe.types.float.options,js={...at,construct:i=>{const e=i.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new _(e);if(at.construct)return at.construct(i)}},xs=new pe.Type("tag:yaml.org,2002:float",js),ct=pe.types.int.options,$s={...ct,construct:i=>{let e=i;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new O(e);if(ct.construct)return ct.construct(i)}},Fs=new pe.Type("tag:yaml.org,2002:int",$s),Tr=pe.CORE_SCHEMA.extend({implicit:[xs,Fs]}),ee=i=>{const e=pe.load(i,{schema:Tr});return e===void 0?void 0:e},vr=i=>pe.dump(i,{schema:Tr,replacer:(e,t)=>{if(E(t)){if(Q(t)){const r=new Z(Number.MIN_SAFE_INTEGER.toString()),s=new Z(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(s))return t.toString()}return t.toNumber()}return t}}),Br=`- type:
2
2
  blueId: 27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo
3
3
  mappings:
4
4
  Text: DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K
@@ -9,19 +9,19 @@
9
9
  Dictionary: G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj
10
10
  - type:
11
11
  blueId: FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4
12
- `,xs=`name: Transformation
13
- description: TODO`,Fs=`name: Infer Basic Types For Untyped Values
12
+ `,zs=`name: Transformation
13
+ description: TODO`,Us=`name: Infer Basic Types For Untyped Values
14
14
  type:
15
15
  blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
16
- description: This transformation infers type details for Text, Integer, Number and Boolean.`,zs=`name: Replace Inline Types with BlueIds
16
+ description: This transformation infers type details for Text, Integer, Number and Boolean.`,Ks=`name: Replace Inline Types with BlueIds
17
17
  type:
18
18
  blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
19
- description: This transformation replaces`,Us=[Br,xs,Fs,zs];class Ks extends ge{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of Us){const t=te(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(n=>m.deserialize(n)),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,r)}else{const r=m.deserialize(t),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,[r])}}}}class Rt extends ge{static INSTANCE=new Rt;nodeProvider;constructor(){super(),this.nodeProvider=new Ks}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class De{static wrap(e){const t=[Rt.INSTANCE];return t.push(e),new Ir(t)}}class At{nodeProvider;strategy;constructor(e,t){this.nodeProvider=De.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,s=!1){if(!s){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const n=e.getBlueId();if(n&&E.hasBlueIdOnly(e)&&!ye.includes(n)){const y=this.fetchNode(e);if(y&&y.length>0){const g=this.shouldPreserveReferenceBlueId(r,s);if(y.length===1){const I=y[0];this.mergeNodes(e,I,g)}else{const I=y.map(N=>N.clone()),_=new d().setItems(I);this.mergeNodes(e,_,g)}}}const o=e.getType();o&&this.extendNode(o,t,"type",!0);const l=e.getItemType();l&&this.extendNode(l,t,"itemType",!0);const a=e.getKeyType();a&&this.extendNode(a,t,"keyType",!0);const c=e.getValueType();c&&this.extendNode(c,t,"valueType",!0);const p=e.getProperties();p&&Object.entries(p).forEach(([y,g])=>{this.extendNode(g,t,y,!1)});const f=e.getItems();if(f&&f.length>0)for(let y=0;y<f.length;y++)this.extendNode(f[y],t,String(y),!1)}finally{s||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 s=t.getValue();u.isNonNullable(s)&&e.setValue(s),e.setItems(t.getItems()?.map(o=>o.clone()));const n=t.getProperties();e.setProperties(n===void 0?void 0:Object.fromEntries(Object.entries(n).map(([o,l])=>[o,l.clone()]))),e.setBlue(t.getBlue()?.clone())}}class le extends mr{mergingProcessor;nodeProvider;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProvider=De.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 s=e;const n=t.getType();if(u.isNonNullable(n)){const o=this.resolveTypeNode(n,r),l=this.getTypeOverlay(n,o,r);s=this.mergeObject(s,l,r);const a=t.cloneShallow().setType(o.clone());return this.mergeObject(s,a,r)}return this.mergeObject(s,t,r)}mergeObject(e,t,r){const s=e.cloneShallow();let n=this.mergingProcessor.process(s,t,r.nodeProvider);const o=t.getItems();u.isNonNullable(o)&&(n=this.mergeChildren(n,t,r));const l=t.getProperties();return u.isNonNullable(l)&&(n=this.mergeProperties(n,t,l,r)),u.isNonNullable(t.getBlueId())&&(n=n.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(n=this.mergingProcessor.postProcess(n,t,r.nodeProvider)),n}mergeChildren(e,t,r){const s=t.getItems()??[];return v.hasListControlItems(s)?this.mergeChildrenWithListControls(e,t,r):this.mergeChildrenWithoutListControls(e,s,r)}mergeChildrenWithoutListControls(e,t,r){const s=e.getItems();if(u.isNullable(s)){const o=[];for(let l=0;l<t.length;l++){const a=t[l];if(r.limits.shouldMergePathSegment(String(l),a)){this.enterPathSegment(r,String(l),a);try{const c=this.materializeForCurrentContext(a,r);o.push(c)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(o)}if(t.length<s.length)throw new Error(`Subtype of element must not have more items (${s.length}) than the element itself (${t.length}).`);const n=[...s];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>=n.length){const p=this.materializeForCurrentContext(t[o],r);n.push(p);continue}const l=r.limits instanceof H?t[o]:this.materializeForCurrentContext(t[o],r),a=this.calculateNodeBlueId(l,r),c=this.calculateNodeBlueId(n[o],r);if(a!==c)throw new Error(`Mismatched items at index ${o}: source item has blueId '${a}', but target item has blueId '${c}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(n)}mergeChildrenWithListControls(e,t,r){const s=t.getItems()??[],n=e.getItems()??[],o=v.getMergePolicy(t,e),l=[...n];let a=0,c=!1;const p=s[0];if(p!==void 0&&v.hasPreviousProperty(p)){if(v.getPreviousBlueId(p)===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");c=!0,a=1}const f=c&&n.length===0&&!(r.limits instanceof H),y=new Set;for(;a<s.length;a++){const g=s[a];if(v.hasPreviousProperty(g))throw new Error("$previous list control is allowed only as the first item.");const I=v.readPosition(g);if(I!==void 0){if(o==="append-only")throw new Error("$pos is not allowed in append-only lists.");if(I>=n.length)throw new Error(`$pos ${I} is out of range for inherited list length ${n.length}.`);if(y.has(I))throw new Error(`Duplicate $pos list overlay for index ${I}.`);y.add(I);const N=v.withoutPosition(g);if(!v.hasPayloadAfterRemovingPosition(g))throw new Error("$pos list control must include an item payload.");if(!r.limits.shouldMergePathSegment(String(I),N))continue;this.enterPathSegment(r,String(I),N);try{const F=l[I];l[I]=F===void 0||v.isReplacementPayload(N)?this.materializeForCurrentContext(N,r):this.mergeWithContext(F,N,r)}finally{this.exitPathSegment(r)}continue}const _=l.length;if(!(!f&&!r.limits.shouldMergePathSegment(String(_),g))){if(f){l.push(this.materializeWithoutLimits(g,r));continue}this.enterPathSegment(r,String(_),g);try{const N=this.materializeForCurrentContext(g,r);l.push(N)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}materializeWithoutLimits(e,t){return new le(this.mergingProcessor,t.nodeProvider).resolve(e,x)}mergeProperties(e,t,r,s){const n=e.getProperties()??{};let o=n,l=!1;for(const[a,c]of Object.entries(r))if(s.limits.shouldMergePathSegment(a,c)){this.enterPathSegment(s,a,c);try{const p=o[a],f=this.getPathLimitedListControlTarget(p,t,a,c,s),y=f??p,I=this.shouldMergePropertyWithoutPreResolve(y,c,s)?this.mergeExistingProperty(y,c,s):(()=>{const N=this.materializeForCurrentContext(c,s);return y===void 0?N:this.mergeObject(y,N,s)})(),_=f===void 0?I:this.projectListNodeToCurrentLimits(I,s);_!==p&&(l||(o={...n},l=!0),o[a]=_)}finally{this.exitPathSegment(s)}}return l?e.cloneShallow().setProperties(o):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof H?u.isNonNullable(e)&&v.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 d,n=this.mergeWithContext(r,e,t).cloneShallow().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new k(n,{completeness:t.limits instanceof H?"full":"path-limited"})}createResolutionContext(e){const t=new Map,r=new Map,s=Ss(this.createResolutionNodeProvider(this.nodeProvider,t),r);return{limits:e,nodeProvider:s,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 s=this.createResolvedTypeCacheKey(r,t),n=t.resolvedTypeCache.get(s);if(u.isNonNullable(n)&&!t.resolvingTypeKeys.has(s))return n;if(t.resolvingTypeBlueIds.has(r))return n??this.createCyclicTypeReference(r,t);const o=this.createCyclicTypeReference(r,t);t.resolvedTypeCache.set(s,o),t.resolvingTypeKeys.add(s),t.resolvingTypeBlueIds.add(r);try{const l=this.resolveAndExtendTypeNode(e,t);return l.setReferenceBlueId(r),t.resolvedTypeCache.set(s,l),l}catch(l){throw t.resolvedTypeCache.delete(s),l}finally{t.resolvingTypeKeys.delete(s),t.resolvingTypeBlueIds.delete(r)}}return this.resolveAndExtendTypeNode(e,t)}createCyclicTypeReference(e,t){return new k(new d().setReferenceBlueId(e),{completeness:t.limits instanceof H?"full":"path-limited"})}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new At(t.nodeProvider).extend(r,Qe.withSinglePath("/")),this.resolveWithContext(r,t)}getTypeOverlay(e,t,r){const s=e.getBlueId();if(u.isNullable(s))return this.createTypeOverlay(t);const n=this.createResolvedTypeCacheKey(s,r),o=r.typeOverlayCache.get(n);if(u.isNonNullable(o))return o;const l=this.createTypeOverlay(t);return r.resolvingTypeBlueIds.has(s)||r.typeOverlayCache.set(n,l),l}createTypeOverlay(e){return e.cloneShallow().setType(void 0).setBlueId(void 0)}createResolvedTypeCacheKey(e,t){return t.limits instanceof H?e:`${e}|${this.getCurrentPointer(t)}`}materializeForCurrentContext(e,t){return e.isResolved()&&this.canReuseResolvedSubtree(t)?e.clone():this.resolveWithContext(e,t)}canReuseResolvedSubtree(e){return e.limits instanceof H}calculateNodeBlueId(e,t){const r=t.nodeHashCache.get(e);if(u.isNonNullable(r))return r;const s=W.calculateHashMinimalBlueId(e);return t.nodeHashCache.set(e,s),s}getPathLimitedListControlTarget(e,t,r,s,n){if(!(e===void 0||n.limits instanceof H||!v.hasListControlItems(s.getItems())))return this.resolveFullInheritedProperty(t,r,n)}resolveFullInheritedProperty(e,t,r){const s=e.getType();if(s===void 0)return;const n=s.getBlueId();if(u.isNonNullable(n)){const a=r.nodeProvider.fetchByBlueId(n)?.[0];return a===void 0?void 0:new le(this.mergingProcessor,r.nodeProvider).resolve(a,x).getProperties()?.[t]?.clone()}return new le(this.mergingProcessor,r.nodeProvider).resolve(s,x).getProperties()?.[t]?.clone()}projectListNodeToCurrentLimits(e,t){const r=e.getItems();return r===void 0?e:e.cloneShallow().setItems(r.filter((s,n)=>t.limits.shouldMergePathSegment(String(n),s)))}createResolutionNodeProvider(e,t){return new class extends ge{fetchByBlueId(r){if(t.has(r))return t.get(r)??null;const s=e.fetchByBlueId(r);return t.set(r,s),s}}}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 br{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.process(s,t,r),e)}postProcess(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.postProcess?n.postProcess(s,t,r):s,e)}}class Nr{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const s=e.getValue();if(u.isNullable(s))return e.cloneShallow().setValue(r);if(!ks(r,s))throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${s}`)}return e}}const ks=(i,e)=>ee(i)&&ee(e)||Ue(i)&&Ue(e)?i.eq(e):i===e;class Pr{process(e,t,r){const s=e.getType(),n=t.getType();let o=e;if(s===void 0)o=e.cloneShallow().setType(n);else if(n!==void 0){if(!C(n,s,r)){const a=T.get(n),c=T.get(s);throw new Error(`The source type '${JSON.stringify(a)}' is not a subtype of the target type '${JSON.stringify(c)}'.`)}o=e.cloneShallow().setType(n)}return o}}class Sr{process(e,t,r){const s=t.getItemType(),n=t.getType();if(s!==void 0&&n!==void 0&&!Fe(n,r))throw new Error("Source node with itemType must have a List type");const o=e.getItemType();let l=e;if(o===void 0)s!==void 0&&(l=e.cloneShallow().setItemType(s));else if(s!==void 0){if(!C(s,o,r)){const f=T.get(s),y=T.get(o);throw new Error(`The source item type '${JSON.stringify(f)}' is not a subtype of the target item type '${JSON.stringify(y)}'.`)}l=e.cloneShallow().setItemType(s)}const a=l.getItemType(),c=t.getItems();if(a!==void 0&&c!==void 0)for(const p of c){const f=p.getType();if(f!==void 0&&!C(f,a,r)){const y=T.get(f),g=T.get(a);throw new Error(`Item of type '${JSON.stringify(y)}' is not a subtype of the list's item type '${JSON.stringify(g)}'.`)}}return l}}class wr{process(e,t,r){const s=t.getKeyType(),n=t.getValueType(),o=t.getType();if((s!==void 0||n!==void 0)&&o!==void 0&&!ze(o,r))throw new Error("Source node with keyType or valueType must have a Dictionary type");let l=this.processKeyType(e,t,r);l=this.processValueType(l,t,r);const a=l.getKeyType(),c=l.getValueType(),p=t.getProperties();return(a!==void 0||c!==void 0)&&p!==void 0&&Object.entries(p).forEach(([f,y])=>{a!==void 0&&this.validateKeyType(f,a,r),c!==void 0&&this.validateValueType(y,c,r)}),l}processKeyType(e,t,r){const s=e.getKeyType(),n=t.getKeyType();if(s===void 0){if(n!==void 0)return this.validateBasicKeyType(n,r),e.cloneShallow().setKeyType(n)}else if(n!==void 0){if(this.validateBasicKeyType(n,r),!C(n,s,r)){const l=T.get(n),a=T.get(s);throw new Error(`The source key type '${JSON.stringify(l)}' is not a subtype of the target key type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setKeyType(n)}return e}processValueType(e,t,r){const s=e.getValueType(),n=t.getValueType();if(s===void 0){if(n!==void 0)return e.cloneShallow().setValueType(n)}else if(n!==void 0){if(!C(n,s,r)){const l=T.get(n),a=T.get(s);throw new Error(`The source value type '${JSON.stringify(l)}' is not a subtype of the target value type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setValueType(n)}return e}validateBasicKeyType(e,t){if(!Es(e,t))throw new Error("Dictionary key type must be a basic type")}validateKeyType(e,t,r){if(!Cs(t,r))if(Rs(t,r)){const s=Number.parseInt(e,10);if(Number.isNaN(s)||s.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(As(t,r)){const s=Number.parseFloat(e);if(Number.isNaN(s))throw new Error(`Key '${e}' is not a valid Number.`)}else if(Os(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 s=e.getType();if(s!==void 0&&!C(s,t,r)){const n=T.get(s),o=T.get(t);throw new Error(`Value of type '${JSON.stringify(n)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}class Er{process(e){return e}postProcess(e,t,r){const s=e.getType();if(s!==void 0&&Vs(s,r)){const n=e.getItems(),o=e.getProperties();if(n!==void 0&&n.length>0||o!==void 0&&Object.keys(o).length>0){const l=Ms(s,r),a=s.getName()||"unknown";throw new Error(`Node of type "${a}" (which extends basic type "${l}") must not have items, properties or contracts.`)}}return e}}class Cr{process(e,t){let r=e;const s=t.getName();s!==void 0&&s!==e.getName()&&(r=r.cloneShallow().setName(s));const n=t.getDescription();return n!==void 0&&n!==r.getDescription()&&(r=r.cloneShallow().setDescription(n)),r}}const Hs=Object.freeze(Object.defineProperty({__proto__:null,BasicTypesVerifier:Er,DictionaryProcessor:wr,ListProcessor:Sr,MetadataPropagator:Cr,SequentialMergingProcessor:br,TypeAssigner:Pr,ValuePropagator:Nr},Symbol.toStringTag,{value:"Module"}));function rt(){return new br([new Nr,new Pr,new Sr,new wr,new Cr,new Er])}class Re{nodeProvider;mergingProcessor;minimizer=new ht;cyclicSetIdentity;constructor(e={}){this.nodeProvider=e.nodeProvider??tt(()=>[]),this.mergingProcessor=e.mergingProcessor??rt(),this.cyclicSetIdentity=this.createCyclicSetIdentityService()}createCyclicSetIdentityService(){return new j({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 k&&e.getCompleteness()==="path-limited"){const t=e.getSourceSemanticBlueId();if(t!==void 0)return new d().setReferenceBlueId(t);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return E.hasBlueIdOnly(e)?e.clone():e.isResolved()?this.minimizeResolved(e):this.minimizeAuthoring(e)}minimizeResolved(e){if(e instanceof k&&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 le(this.mergingProcessor,t).resolve(e,x);return this.minimizeResolved(r)}hashMinimalTrusted(e){return this.hashMinimalTrustedWithProvider(e,this.nodeProvider)}hashMinimalTrustedWithProvider(e,t){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t))):(q.validateStorageShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t)))}hashMinimalTrustedAsync(e){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueId(this.toHashableMinimalTrusted(e))):(q.validateStorageShape(e),A.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(!v.hasPositionControl(e))return e;const r=new le(this.mergingProcessor,t).resolve(e,x);return this.minimizer.minimizeResolvedForHash(r)}prepareCyclicDocument(e){return this.minimizeAuthoringWithProvider(e,this.createCyclicReferenceNodeProvider())}hashCyclicPrepared(e){return this.hashMinimalTrustedWithProvider(e,this.createCyclicReferenceNodeProvider())}createCyclicReferenceNodeProvider(){const e=this.nodeProvider;return new class extends ge{fetchByBlueId(t){return t===j.ZERO_BLUE_ID||j.isIndexedThisReference(t)?[new d().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)&&j.hasThisReference([e]))throw new Error("Direct cyclic references using 'this#k' are supported only in a top-level document set.");return}if(j.hasThisReference(t))return this.cyclicSetIdentity.calculate(t).blueId}getTopLevelSetItems(e){if(Array.isArray(e))return e;if(E.hasItemsOnly(e))return e.getItems()??[]}toMinimalListIdentityInput(e){q.validateListControlShape(e);const t=new d().setItems(e);return this.minimizeAuthoring(t).getItems()??[]}}class Rr{semanticIdentity;cyclicSetIdentity;constructor(e={}){const t=e.nodeProvider??tt(()=>[]),r=e.mergingProcessor??rt();this.semanticIdentity=new Re({nodeProvider:t,mergingProcessor:r}),this.cyclicSetIdentity=this.semanticIdentity.createCyclicSetIdentityService()}prepareStorageNode(e,t){const r=this.preprocessForStorage(e,t);if(this.hasThisReference(r))throw new Error("Self-references using this or this#k are not supported in single-document provider storage ingest.");return this.preparePreprocessedStorageNode(r)}prepareStorageNodeList(e,t){if(e.length===0)throw new Error("List of nodes cannot be null or empty");const r=e.map(o=>this.preprocessForStorage(o,t));if(j.hasThisReference(r)){const o=this.cyclicSetIdentity.calculate(r);return o.nodes.forEach(l=>q.validateStorageShape(l)),{blueId:o.blueId,nodes:o.nodes,documentBlueIds:o.documentBlueIds,isCyclicSet:!0}}const s=r.map(o=>this.preparePreprocessedStorageNode(o).node);return{blueId:this.semanticIdentity.hashMinimalTrusted(s),nodes:s}}preprocessForStorage(e,t){q.validateStorageShape(e);const r=t(e);return q.validateStorageShape(r),r}preparePreprocessedStorageNode(e){const t=this.prepareSemanticStorage(e);return q.validateStorageShape(t.node),t}prepareSemanticStorage(e){const t=this.semanticIdentity.minimizeAuthoring(e);return{blueId:this.semanticIdentity.hashMinimalTrusted(t),node:t}}hasThisReference(e){const t=e.getReferenceBlueId();return t!==void 0&&(t==="this"||t.startsWith("this#"))?!0:[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].some(s=>s!==void 0&&this.hasThisReference(s))}}const Ys=i=>i instanceof h.ZodOptional||i instanceof h.ZodNullable||i instanceof h.ZodReadonly||i instanceof h.ZodBranded||i instanceof h.ZodEffects||i instanceof h.ZodLazy,Ws=i=>i instanceof h.ZodString||i instanceof h.ZodNumber||i instanceof h.ZodBoolean||i instanceof h.ZodBigInt;class Ar{static convertValue(e,t){const r=e.getType()?.getBlueId(),s=e.getValue();return u.isNullable(s)?Ws(t)&&E.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):s:re===r?this.convertFromString(String(s),t):se===r||s instanceof D?this.convertFromBigDecimal(new D(s?.toString()),t):ie===r||s instanceof O?this.convertFromBigInteger(new O(s?.toString()),t):ne===r||typeof s=="boolean"?this.convertFromBoolean(!!s,t):this.convertFromString(String(s),t)}static convertFromString(e,t){if(!t||t instanceof h.ZodString||t instanceof h.ZodEnum||t instanceof h.ZodNativeEnum)return e;if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBoolean)return e.toLowerCase()==="true";if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodBigInt)return BigInt(e.toString());if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t||t instanceof h.ZodBoolean)return e;if(t instanceof h.ZodString)return e.toString();if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;if(e instanceof h.ZodNumber)return 0;if(e instanceof h.ZodBoolean)return!1;if(e instanceof h.ZodString)return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}class Js{convert(e,t){return Ar.convertValue(e,t)}}class Gs{constructor(e,t){this.nodeToObjectConverter=e,this.calculateBlueId=t}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(t instanceof h.ZodIntersection){const r=t._def.left,s=t._def.right,n=this.convert(e,r),o=this.convert(e,s);return{...n,...o}}if(t instanceof h.ZodUnion)throw new Error("Union not supported");if(t instanceof h.ZodObject)return Object.keys(t.shape).reduce((s,n)=>{const o=e.getProperties(),l=t.shape[n],a=lr(l);if(u.isNonNullable(a)){const g=K.isString(a)?a:n,I=o?.[g],_=I?this.calculateBlueId(I):void 0;return s[n]=_,s}const c=cr(l);if(u.isNonNullable(c)){const g=o?.[c];return s[n]=g?.getName(),s}const p=nr(l);if(u.isNonNullable(p)){const g=o?.[p];return s[n]=g?.getDescription(),s}if(n==="name"){const g=e.getName();return s[n]=g,s}if(n==="description"){const g=e.getDescription();return s[n]=g,s}const f=o?.[n];if(u.isNullable(f))return s;const y=this.nodeToObjectConverter.convert(f,l);return s[n]=y,s},{});throw new Error("Unknown schema type, "+t._def.typeName)}}class Zs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.element;return r.map(o=>this.nodeToObjectConverter.convert(o,s))}}class qs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t._def.valueType,n=r.map(o=>this.nodeToObjectConverter.convert(o,s));return new Set(n)}}class Xs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,s=t.valueSchema,n=new Map,o=e.getName();u.isNonNullable(o)&&n.set(ae,o);const l=e.getDescription();u.isNonNullable(l)&&n.set(ce,l);const a=e.getProperties();return u.isNonNullable(a)&&Object.entries(a).forEach(([c,p])=>{const f=new d().setValue(c);f.setType(new d().setBlueId(re));const y=Ar.convertValue(f,r),g=this.nodeToObjectConverter.convert(p,s);n.set(y,g)}),t instanceof h.ZodRecord?Object.fromEntries(n):n}}class Qs{convert(e){return T.get(e)}}class ei{convert(e){return T.get(e)}}class ti{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.items;return r.map((o,l)=>this.nodeToObjectConverter.convert(o,s[l]))}}const ri=h.z.union([h.z.literal("ZodString"),h.z.literal("ZodNumber"),h.z.literal("ZodBoolean"),h.z.literal("ZodBigInt"),h.z.literal("ZodArray"),h.z.literal("ZodSet"),h.z.literal("ZodMap"),h.z.literal("ZodRecord"),h.z.literal("ZodObject"),h.z.literal("ZodEnum"),h.z.literal("ZodNativeEnum"),h.z.literal("ZodUnknown"),h.z.literal("ZodAny"),h.z.literal("ZodTuple")]);class si{constructor(e,t){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new Gs(this.nodeToObjectConverter,t)}converters=new Map;complexObjectConverter;registerConverters(){const e=new Js,t=new Zs(this.nodeToObjectConverter),r=new ti(this.nodeToObjectConverter),s=new qs(this.nodeToObjectConverter),n=new Xs(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 Qs),this.converters.set("ZodAny",new ei),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",s),this.converters.set("ZodMap",n),this.converters.set("ZodRecord",n),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){if(Ys(e))return e instanceof h.ZodEffects?this.getSchemaTypeName(e.innerType()):e instanceof h.ZodLazy?this.getSchemaTypeName(e.schema):this.getSchemaTypeName(e.unwrap());const t=e._def.typeName;try{return ri.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class ii{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 si(this,this.calculateBlueId)}converterFactory;calculateBlueId;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),s=z.unwrapSchema(t);if(Ct(s))return e;let n=s;return z.checkSchemaExtension(r,s,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(n=r),this.convertWithType(e,n)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class ni{static get(e,t={}){const{strategy:r="official"}=t,s=T.get(e,r);return vr(s)}}const gt=async i=>{if(Jt(i))return i;try{const e=Ve.parse(i),{Blue:t}=await Promise.resolve().then(()=>zi),r=await new t().calculateBlueId(e);return{...i,blueId:r}}catch(e){throw new Error(`Failed enriching object with Blue ID: ${e}`)}},oi=i=>i?.items,li=i=>i?.value,ai=i=>u.isNullable(i)?{}:K.omit(i,Tt),ci=i=>Zt(i)?i.type.name??null:qt(i)?K.pascal(typeof i.value):Gt(i)?"List":null,Or=i=>u.isNonNullable(i)&&Object.keys(K.omit(i,["blueId"])).length>0,ui=i=>{try{const e=m.deserialize(i),t=T.get(e);return ve.parse(t)}catch(e){throw new Error(`Failed transforming JSON-like value to BlueObject: ${e}`)}},mt=async i=>{const{resolveFunction:e,signal:t=new AbortController().signal,omitItems:r}=i,s=i.count??i.items.length;let n=await K.map(i.items,async l=>await gt(l));const o=Math.max(n?.length-s,0);for(let l=n.length-1;l>=o;l--)if(!Or(n[l])){const a=await e(n[l],{signal:t});if(Array.isArray(a))return mt({...i,items:[...n.slice(0,l),...a,...n.slice(l+1)]});const c=await gt(a);if(r?.includes(c.blueId))return mt({...i,items:[...n.slice(0,l),...n.slice(l+1)]});n=[...n.slice(0,l),c,...n.slice(l+1)]}return n};function Ae(i){try{const e=new URL(i);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class di{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 d().setBlueId(re)):typeof r=="bigint"||ee(r)?e.setType(new d().setBlueId(ie)):Ue(r)?e.setType(new d().setBlueId(se)):typeof r=="boolean"&&e.setType(new d().setBlueId(ne))),e}}class Ye{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof d){const r=e.getProperties();if(r&&r[Ye.MAPPINGS]){const n=r[Ye.MAPPINGS].getProperties();n&&Object.entries(n).forEach(([o,l])=>{const a=l.getValue();typeof a=="string"&&this.mappings.set(o,a)})}}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 s=this.mappings.get(r);if(s){const n=new d().setBlueId(s);t===e.getType()?e.setType(n):t===e.getItemType()?e.setItemType(n):t===e.getKeyType()?e.setKeyType(n):t===e.getValueType()&&e.setValueType(n)}}}}}class hi{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 s=String(t.getValue());throw new Error(`Unknown type "${s}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class Ot{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const s of this.blueIdsCollections)Object.assign(t,s);const r=Object.entries(t).map(([s,n])=>` ${s}: ${n}`).join(`
19
+ description: This transformation replaces`,Hs=[Br,zs,Us,Ks];class ks extends ye{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of Hs){const t=ee(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(n=>m.deserialize(n)),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,r)}else{const r=m.deserialize(t),s=A.calculateBlueIdSync(r);this.blueIdToNodesMap.set(s,[r])}}}}class At extends ye{static INSTANCE=new At;nodeProvider;constructor(){super(),this.nodeProvider=new ks}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class _e{static wrap(e){const t=[At.INSTANCE];return t.push(e),new Ir(t)}}class Ot{nodeProvider;strategy;constructor(e,t){this.nodeProvider=_e.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,s=!1){if(!s){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const n=e.getBlueId();if(n&&P.hasBlueIdOnly(e)&&!fe.includes(n)){const y=this.fetchNode(e);if(y&&y.length>0){const g=this.shouldPreserveReferenceBlueId(r,s);if(y.length===1){const I=y[0];this.mergeNodes(e,I,g)}else{const I=y.map(N=>N.clone()),D=new d().setItems(I);this.mergeNodes(e,D,g)}}}const o=e.getType();o&&this.extendNode(o,t,"type",!0);const l=e.getItemType();l&&this.extendNode(l,t,"itemType",!0);const a=e.getKeyType();a&&this.extendNode(a,t,"keyType",!0);const c=e.getValueType();c&&this.extendNode(c,t,"valueType",!0);const p=e.getProperties();p&&Object.entries(p).forEach(([y,g])=>{this.extendNode(g,t,y,!1)});const f=e.getItems();if(f&&f.length>0)for(let y=0;y<f.length;y++)this.extendNode(f[y],t,String(y),!1)}finally{s||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 s=t.getValue();u.isNonNullable(s)&&e.setValue(s),e.setItems(t.getItems()?.map(o=>o.clone()));const n=t.getProperties();e.setProperties(n===void 0?void 0:Object.fromEntries(Object.entries(n).map(([o,l])=>[o,l.clone()]))),e.setBlue(t.getBlue()?.clone())}}class oe extends mr{mergingProcessor;nodeProvider;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProvider=_e.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 s=e;const n=t.getType();if(u.isNonNullable(n)){const o=this.resolveTypeNode(n,r),l=this.getTypeOverlay(n,o,r);s=this.mergeObject(s,l,r);const a=t.cloneShallow().setType(o.clone());return this.mergeObject(s,a,r)}return this.mergeObject(s,t,r)}mergeObject(e,t,r){const s=e.cloneShallow();let n=this.mergingProcessor.process(s,t,r.nodeProvider);const o=t.getItems();u.isNonNullable(o)&&(n=this.mergeChildren(n,t,r));const l=t.getProperties();return u.isNonNullable(l)&&(n=this.mergeProperties(n,t,l,r)),u.isNonNullable(t.getBlueId())&&(n=n.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(n=this.mergingProcessor.postProcess(n,t,r.nodeProvider)),n}mergeChildren(e,t,r){const s=t.getItems()??[];return T.hasListControlItems(s)?this.mergeChildrenWithListControls(e,t,r):this.mergeChildrenWithoutListControls(e,s,r)}mergeChildrenWithoutListControls(e,t,r){const s=e.getItems();if(u.isNullable(s)){const o=[];for(let l=0;l<t.length;l++){const a=t[l];if(r.limits.shouldMergePathSegment(String(l),a)){this.enterPathSegment(r,String(l),a);try{const c=this.materializeForCurrentContext(a,r);o.push(c)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(o)}if(t.length<s.length)throw new Error(`Subtype of element must not have more items (${s.length}) than the element itself (${t.length}).`);const n=[...s];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>=n.length){const p=this.materializeForCurrentContext(t[o],r);n.push(p);continue}const l=r.limits instanceof Y?t[o]:this.materializeForCurrentContext(t[o],r),a=this.calculateNodeBlueId(l,r),c=this.calculateNodeBlueId(n[o],r);if(a!==c)throw new Error(`Mismatched items at index ${o}: source item has blueId '${a}', but target item has blueId '${c}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(n)}mergeChildrenWithListControls(e,t,r){const s=t.getItems()??[],n=e.getItems()??[],o=T.getMergePolicy(t,e),l=[...n];let a=0,c=!1;const p=s[0];if(p!==void 0&&T.hasPreviousProperty(p)){if(T.getPreviousBlueId(p)===void 0)throw new Error("$previous list control must be exactly { $previous: { blueId: <id> } }.");c=!0,a=1}const f=c&&n.length===0&&!(r.limits instanceof Y),y=new Set;for(;a<s.length;a++){const g=s[a];if(T.hasPreviousProperty(g))throw new Error("$previous list control is allowed only as the first item.");const I=T.readPosition(g);if(I!==void 0){if(o==="append-only")throw new Error("$pos is not allowed in append-only lists.");if(I>=n.length)throw new Error(`$pos ${I} is out of range for inherited list length ${n.length}.`);if(y.has(I))throw new Error(`Duplicate $pos list overlay for index ${I}.`);y.add(I);const N=T.withoutPosition(g);if(!T.hasPayloadAfterRemovingPosition(g))throw new Error("$pos list control must include an item payload.");if(!r.limits.shouldMergePathSegment(String(I),N))continue;this.enterPathSegment(r,String(I),N);try{const F=l[I];l[I]=F===void 0||T.isReplacementPayload(N)?this.materializeForCurrentContext(N,r):this.mergeWithContext(F,N,r)}finally{this.exitPathSegment(r)}continue}const D=l.length;if(!(!f&&!r.limits.shouldMergePathSegment(String(D),g))){if(f){l.push(this.materializeWithoutLimits(g,r));continue}this.enterPathSegment(r,String(D),g);try{const N=this.materializeForCurrentContext(g,r);l.push(N)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}materializeWithoutLimits(e,t){return new oe(this.mergingProcessor,t.nodeProvider).resolve(e,$)}mergeProperties(e,t,r,s){const n=e.getProperties()??{};let o=n,l=!1;for(const[a,c]of Object.entries(r))if(s.limits.shouldMergePathSegment(a,c)){this.enterPathSegment(s,a,c);try{const p=o[a],f=this.getPathLimitedListControlTarget(p,t,a,c,s),y=f??p,I=this.shouldMergePropertyWithoutPreResolve(y,c,s)?this.mergeExistingProperty(y,c,s):(()=>{const N=this.materializeForCurrentContext(c,s);return y===void 0?N:this.mergeObject(y,N,s)})(),D=f===void 0?I:this.projectListNodeToCurrentLimits(I,s);D!==p&&(l||(o={...n},l=!0),o[a]=D)}finally{this.exitPathSegment(s)}}return l?e.cloneShallow().setProperties(o):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof Y?u.isNonNullable(e)&&T.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 d,n=this.mergeWithContext(r,e,t).cloneShallow().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new k(n,{completeness:t.limits instanceof Y?"full":"path-limited"})}createResolutionContext(e){const t=new Map,r=new Map,s=Es(this.createResolutionNodeProvider(this.nodeProvider,t),r);return{limits:e,nodeProvider:s,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 s=this.createResolvedTypeCacheKey(r,t),n=t.resolvedTypeCache.get(s);if(u.isNonNullable(n)&&!t.resolvingTypeKeys.has(s))return n;if(t.resolvingTypeBlueIds.has(r))return n??this.createCyclicTypeReference(r,t);const o=this.createCyclicTypeReference(r,t);t.resolvedTypeCache.set(s,o),t.resolvingTypeKeys.add(s),t.resolvingTypeBlueIds.add(r);try{const l=this.resolveAndExtendTypeNode(e,t);return l.setReferenceBlueId(r),t.resolvedTypeCache.set(s,l),l}catch(l){throw t.resolvedTypeCache.delete(s),l}finally{t.resolvingTypeKeys.delete(s),t.resolvingTypeBlueIds.delete(r)}}return this.resolveAndExtendTypeNode(e,t)}createCyclicTypeReference(e,t){return new k(new d().setReferenceBlueId(e),{completeness:t.limits instanceof Y?"full":"path-limited"})}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new Ot(t.nodeProvider).extend(r,et.withSinglePath("/")),this.resolveWithContext(r,t)}getTypeOverlay(e,t,r){const s=e.getBlueId();if(u.isNullable(s))return this.createTypeOverlay(t);const n=this.createResolvedTypeCacheKey(s,r),o=r.typeOverlayCache.get(n);if(u.isNonNullable(o))return o;const l=this.createTypeOverlay(t);return r.resolvingTypeBlueIds.has(s)||r.typeOverlayCache.set(n,l),l}createTypeOverlay(e){return e.cloneShallow().setType(void 0).setBlueId(void 0)}createResolvedTypeCacheKey(e,t){return t.limits instanceof Y?e:`${e}|${this.getCurrentPointer(t)}`}materializeForCurrentContext(e,t){return e.isResolved()&&this.canReuseResolvedSubtree(t)?e.clone():this.resolveWithContext(e,t)}canReuseResolvedSubtree(e){return e.limits instanceof Y}calculateNodeBlueId(e,t){const r=t.nodeHashCache.get(e);if(u.isNonNullable(r))return r;const s=z.calculateHashMinimalBlueId(e);return t.nodeHashCache.set(e,s),s}getPathLimitedListControlTarget(e,t,r,s,n){if(!(e===void 0||n.limits instanceof Y||!T.hasListControlItems(s.getItems())))return this.resolveFullInheritedProperty(t,r,n)}resolveFullInheritedProperty(e,t,r){const s=e.getType();if(s===void 0)return;const n=s.getBlueId();if(u.isNonNullable(n)){const a=r.nodeProvider.fetchByBlueId(n)?.[0];return a===void 0?void 0:new oe(this.mergingProcessor,r.nodeProvider).resolve(a,$).getProperties()?.[t]?.clone()}return new oe(this.mergingProcessor,r.nodeProvider).resolve(s,$).getProperties()?.[t]?.clone()}projectListNodeToCurrentLimits(e,t){const r=e.getItems();return r===void 0?e:e.cloneShallow().setItems(r.filter((s,n)=>t.limits.shouldMergePathSegment(String(n),s)))}createResolutionNodeProvider(e,t){return new class extends ye{fetchByBlueId(r){if(t.has(r))return t.get(r)??null;const s=e.fetchByBlueId(r);return t.set(r,s),s}}}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 br{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.process(s,t,r),e)}postProcess(e,t,r){return this.mergingProcessors.reduce((s,n)=>n.postProcess?n.postProcess(s,t,r):s,e)}}class Nr{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const s=e.getValue();if(u.isNullable(s))return e.cloneShallow().setValue(r);if(!Ys(r,s))throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${s}`)}return e}}const Ys=(i,e)=>Q(i)&&Q(e)||He(i)&&He(e)?i.eq(e):i===e;class Pr{process(e,t,r){const s=e.getType(),n=t.getType();let o=e;if(s===void 0)o=e.cloneShallow().setType(n);else if(n!==void 0){if(!C(n,s,r)){const a=v.get(n),c=v.get(s);throw new Error(`The source type '${JSON.stringify(a)}' is not a subtype of the target type '${JSON.stringify(c)}'.`)}o=e.cloneShallow().setType(n)}return o}}class Sr{process(e,t,r){const s=t.getItemType(),n=t.getType();if(s!==void 0&&n!==void 0&&!Ue(n,r))throw new Error("Source node with itemType must have a List type");const o=e.getItemType();let l=e;if(o===void 0)s!==void 0&&(l=e.cloneShallow().setItemType(s));else if(s!==void 0){if(!C(s,o,r)){const f=v.get(s),y=v.get(o);throw new Error(`The source item type '${JSON.stringify(f)}' is not a subtype of the target item type '${JSON.stringify(y)}'.`)}l=e.cloneShallow().setItemType(s)}const a=l.getItemType(),c=t.getItems();if(a!==void 0&&c!==void 0)for(const p of c){const f=p.getType();if(f!==void 0&&!C(f,a,r)){const y=v.get(f),g=v.get(a);throw new Error(`Item of type '${JSON.stringify(y)}' is not a subtype of the list's item type '${JSON.stringify(g)}'.`)}}return l}}class wr{process(e,t,r){const s=t.getKeyType(),n=t.getValueType(),o=t.getType();if((s!==void 0||n!==void 0)&&o!==void 0&&!Ke(o,r))throw new Error("Source node with keyType or valueType must have a Dictionary type");let l=this.processKeyType(e,t,r);l=this.processValueType(l,t,r);const a=l.getKeyType(),c=l.getValueType(),p=t.getProperties();return(a!==void 0||c!==void 0)&&p!==void 0&&Object.entries(p).forEach(([f,y])=>{a!==void 0&&this.validateKeyType(f,a,r),c!==void 0&&this.validateValueType(y,c,r)}),l}processKeyType(e,t,r){const s=e.getKeyType(),n=t.getKeyType();if(s===void 0){if(n!==void 0)return this.validateBasicKeyType(n,r),e.cloneShallow().setKeyType(n)}else if(n!==void 0){if(this.validateBasicKeyType(n,r),!C(n,s,r)){const l=v.get(n),a=v.get(s);throw new Error(`The source key type '${JSON.stringify(l)}' is not a subtype of the target key type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setKeyType(n)}return e}processValueType(e,t,r){const s=e.getValueType(),n=t.getValueType();if(s===void 0){if(n!==void 0)return e.cloneShallow().setValueType(n)}else if(n!==void 0){if(!C(n,s,r)){const l=v.get(n),a=v.get(s);throw new Error(`The source value type '${JSON.stringify(l)}' is not a subtype of the target value type '${JSON.stringify(a)}'.`)}return e.cloneShallow().setValueType(n)}return e}validateBasicKeyType(e,t){if(!Rs(e,t))throw new Error("Dictionary key type must be a basic type")}validateKeyType(e,t,r){if(!As(t,r))if(Os(t,r)){const s=Number.parseInt(e,10);if(Number.isNaN(s)||s.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(Vs(t,r)){const s=Number.parseFloat(e);if(Number.isNaN(s))throw new Error(`Key '${e}' is not a valid Number.`)}else if(Ms(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 s=e.getType();if(s!==void 0&&!C(s,t,r)){const n=v.get(s),o=v.get(t);throw new Error(`Value of type '${JSON.stringify(n)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}class Er{process(e){return e}postProcess(e,t,r){const s=e.getType();if(s!==void 0&&_s(s,r)){const n=e.getItems(),o=e.getProperties();if(n!==void 0&&n.length>0||o!==void 0&&Object.keys(o).length>0){const l=Ds(s,r),a=s.getName()||"unknown";throw new Error(`Node of type "${a}" (which extends basic type "${l}") must not have items, properties or contracts.`)}}return e}}class Cr{process(e,t){let r=e;const s=t.getName();s!==void 0&&s!==e.getName()&&(r=r.cloneShallow().setName(s));const n=t.getDescription();return n!==void 0&&n!==r.getDescription()&&(r=r.cloneShallow().setDescription(n)),r}}const Ws=Object.freeze(Object.defineProperty({__proto__:null,BasicTypesVerifier:Er,DictionaryProcessor:wr,ListProcessor:Sr,MetadataPropagator:Cr,SequentialMergingProcessor:br,TypeAssigner:Pr,ValuePropagator:Nr},Symbol.toStringTag,{value:"Module"}));function $e(){return new br([new Nr,new Pr,new Sr,new wr,new Cr,new Er])}class Re{nodeProvider;mergingProcessor;minimizer=new ht;cyclicSetIdentity;constructor(e={}){this.nodeProvider=e.nodeProvider??rt(()=>[]),this.mergingProcessor=e.mergingProcessor??$e(),this.cyclicSetIdentity=this.createCyclicSetIdentityService()}createCyclicSetIdentityService(){return new j({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 k&&e.getCompleteness()==="path-limited"){const t=e.getSourceSemanticBlueId();if(t!==void 0)return new d().setReferenceBlueId(t);throw new Error("Cannot minimize a path-limited resolved node without a source semantic BlueId.")}return P.hasBlueIdOnly(e)?e.clone():e.isResolved()?this.minimizeResolved(e):this.minimizeAuthoring(e)}minimizeResolved(e){if(e instanceof k&&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 oe(this.mergingProcessor,t).resolve(e,$);return this.minimizeResolved(r)}hashMinimalTrusted(e){return this.hashMinimalTrustedWithProvider(e,this.nodeProvider)}hashMinimalTrustedWithProvider(e,t){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t))):(q.validateStorageShape(e),A.calculateBlueIdSync(this.toHashableMinimalTrusted(e,t)))}hashMinimalTrustedAsync(e){return Array.isArray(e)?(q.validateStorageListShape(e),A.calculateBlueId(this.toHashableMinimalTrusted(e))):(q.validateStorageShape(e),A.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(!T.hasPositionControl(e))return e;const r=new oe(this.mergingProcessor,t).resolve(e,$);return this.minimizer.minimizeResolvedForHash(r)}prepareCyclicDocument(e){return this.minimizeAuthoringWithProvider(e,this.createCyclicReferenceNodeProvider())}hashCyclicPrepared(e){return this.hashMinimalTrustedWithProvider(e,this.createCyclicReferenceNodeProvider())}createCyclicReferenceNodeProvider(){const e=this.nodeProvider;return new class extends ye{fetchByBlueId(t){return t===j.ZERO_BLUE_ID||j.isIndexedThisReference(t)?[new d().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)&&j.hasThisReference([e]))throw new Error("Direct cyclic references using 'this#k' are supported only in a top-level document set.");return}if(j.hasThisReference(t))return this.cyclicSetIdentity.calculate(t).blueId}getTopLevelSetItems(e){if(Array.isArray(e))return e;if(P.hasItemsOnly(e))return e.getItems()??[]}toMinimalListIdentityInput(e){q.validateListControlShape(e);const t=new d().setItems(e);return this.minimizeAuthoring(t).getItems()??[]}}class Js{semanticIdentity;cyclicSetIdentity;constructor(e={}){const t=e.nodeProvider??rt(()=>[]),r=e.mergingProcessor??$e();this.semanticIdentity=new Re({nodeProvider:t,mergingProcessor:r}),this.cyclicSetIdentity=this.semanticIdentity.createCyclicSetIdentityService()}prepareStorageNode(e,t){const r=this.preprocessForStorage(e,t);if(this.hasThisReference(r))throw new Error("Self-references using this or this#k are not supported in single-document provider storage ingest.");return this.preparePreprocessedStorageNode(r)}prepareStorageNodeList(e,t){if(e.length===0)throw new Error("List of nodes cannot be null or empty");const r=e.map(o=>this.preprocessForStorage(o,t));if(j.hasThisReference(r)){const o=this.cyclicSetIdentity.calculate(r);return o.nodes.forEach(l=>q.validateStorageShape(l)),{blueId:o.blueId,nodes:o.nodes,documentBlueIds:o.documentBlueIds,isCyclicSet:!0}}const s=r.map(o=>this.preparePreprocessedStorageNode(o).node);return{blueId:this.semanticIdentity.hashMinimalTrusted(s),nodes:s}}preprocessForStorage(e,t){q.validateStorageShape(e);const r=t(e);return q.validateStorageShape(r),r}preparePreprocessedStorageNode(e){const t=this.prepareSemanticStorage(e);return q.validateStorageShape(t.node),t}prepareSemanticStorage(e){const t=this.semanticIdentity.minimizeAuthoring(e);return{blueId:this.semanticIdentity.hashMinimalTrusted(t),node:t}}hasThisReference(e){const t=e.getReferenceBlueId();return t!==void 0&&(t==="this"||t.startsWith("this#"))?!0:[e.getType(),e.getItemType(),e.getKeyType(),e.getValueType(),e.getBlue(),...e.getItems()??[],...Object.values(e.getProperties()??{})].some(s=>s!==void 0&&this.hasThisReference(s))}}const Zs=i=>i instanceof h.ZodOptional||i instanceof h.ZodNullable||i instanceof h.ZodReadonly||i instanceof h.ZodBranded||i instanceof h.ZodEffects||i instanceof h.ZodLazy,Gs=i=>i instanceof h.ZodString||i instanceof h.ZodNumber||i instanceof h.ZodBoolean||i instanceof h.ZodBigInt;class Rr{static convertValue(e,t){const r=e.getType()?.getBlueId(),s=e.getValue();return u.isNullable(s)?Gs(t)&&P.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):s:te===r?this.convertFromString(String(s),t):re===r||s instanceof _?this.convertFromBigDecimal(new _(s?.toString()),t):se===r||s instanceof O?this.convertFromBigInteger(new O(s?.toString()),t):ie===r||typeof s=="boolean"?this.convertFromBoolean(!!s,t):this.convertFromString(String(s),t)}static convertFromString(e,t){if(!t||t instanceof h.ZodString||t instanceof h.ZodEnum||t instanceof h.ZodNativeEnum)return e;if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBoolean)return e.toLowerCase()==="true";if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){if(t instanceof h.ZodNumber)return e.toNumber();if(t instanceof h.ZodBigInt)return BigInt(e.toString());if(t instanceof h.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t||t instanceof h.ZodBoolean)return e;if(t instanceof h.ZodString)return e.toString();if(t instanceof h.ZodNumber)return Number(e);if(t instanceof h.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;if(e instanceof h.ZodNumber)return 0;if(e instanceof h.ZodBoolean)return!1;if(e instanceof h.ZodString)return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}class qs{convert(e,t){return Rr.convertValue(e,t)}}class Xs{constructor(e,t){this.nodeToObjectConverter=e,this.calculateBlueId=t}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(t instanceof h.ZodIntersection){const r=t._def.left,s=t._def.right,n=this.convert(e,r),o=this.convert(e,s);return{...n,...o}}if(t instanceof h.ZodUnion)throw new Error("Union not supported");if(t instanceof h.ZodObject)return Object.keys(t.shape).reduce((s,n)=>{const o=e.getProperties(),l=t.shape[n],a=lr(l);if(u.isNonNullable(a)){const g=H.isString(a)?a:n,I=o?.[g],D=I?this.calculateBlueId(I):void 0;return s[n]=D,s}const c=cr(l);if(u.isNonNullable(c)){const g=o?.[c];return s[n]=g?.getName(),s}const p=nr(l);if(u.isNonNullable(p)){const g=o?.[p];return s[n]=g?.getDescription(),s}if(n==="name"){const g=e.getName();return s[n]=g,s}if(n==="description"){const g=e.getDescription();return s[n]=g,s}const f=o?.[n];if(u.isNullable(f))return s;const y=this.nodeToObjectConverter.convert(f,l);return s[n]=y,s},{});throw new Error("Unknown schema type, "+t._def.typeName)}}class Qs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.element;return r.map(o=>this.nodeToObjectConverter.convert(o,s))}}class ei{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t._def.valueType,n=r.map(o=>this.nodeToObjectConverter.convert(o,s));return new Set(n)}}class ti{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,s=t.valueSchema,n=new Map,o=e.getName();u.isNonNullable(o)&&n.set(le,o);const l=e.getDescription();u.isNonNullable(l)&&n.set(ae,l);const a=e.getProperties();return u.isNonNullable(a)&&Object.entries(a).forEach(([c,p])=>{const f=new d().setValue(c);f.setType(new d().setBlueId(te));const y=Rr.convertValue(f,r),g=this.nodeToObjectConverter.convert(p,s);n.set(y,g)}),t instanceof h.ZodRecord?Object.fromEntries(n):n}}class ri{convert(e){return v.get(e)}}class si{convert(e){return v.get(e)}}class ii{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const s=t.items;return r.map((o,l)=>this.nodeToObjectConverter.convert(o,s[l]))}}const ni=h.z.union([h.z.literal("ZodString"),h.z.literal("ZodNumber"),h.z.literal("ZodBoolean"),h.z.literal("ZodBigInt"),h.z.literal("ZodArray"),h.z.literal("ZodSet"),h.z.literal("ZodMap"),h.z.literal("ZodRecord"),h.z.literal("ZodObject"),h.z.literal("ZodEnum"),h.z.literal("ZodNativeEnum"),h.z.literal("ZodUnknown"),h.z.literal("ZodAny"),h.z.literal("ZodTuple")]);class oi{constructor(e,t){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new Xs(this.nodeToObjectConverter,t)}converters=new Map;complexObjectConverter;registerConverters(){const e=new qs,t=new Qs(this.nodeToObjectConverter),r=new ii(this.nodeToObjectConverter),s=new ei(this.nodeToObjectConverter),n=new ti(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 ri),this.converters.set("ZodAny",new si),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",s),this.converters.set("ZodMap",n),this.converters.set("ZodRecord",n),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){if(Zs(e))return e instanceof h.ZodEffects?this.getSchemaTypeName(e.innerType()):e instanceof h.ZodLazy?this.getSchemaTypeName(e.schema):this.getSchemaTypeName(e.unwrap());const t=e._def.typeName;try{return ni.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class li{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 oi(this,this.calculateBlueId)}converterFactory;calculateBlueId;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),s=U.unwrapSchema(t);if(Rt(s))return e;let n=s;return U.checkSchemaExtension(r,s,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(n=r),this.convertWithType(e,n)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class ai{static get(e,t={}){const{strategy:r="official"}=t,s=v.get(e,r);return vr(s)}}const gt=async i=>{if(Jt(i))return i;try{const e=Ve.parse(i),{Blue:t}=await Promise.resolve().then(()=>Hi),r=await new t().calculateBlueId(e);return{...i,blueId:r}}catch(e){throw new Error(`Failed enriching object with Blue ID: ${e}`)}},ci=i=>i?.items,ui=i=>i?.value,di=i=>u.isNullable(i)?{}:H.omit(i,vt),hi=i=>Gt(i)?i.type.name??null:qt(i)?H.pascal(typeof i.value):Zt(i)?"List":null,Ar=i=>u.isNonNullable(i)&&Object.keys(H.omit(i,["blueId"])).length>0,pi=i=>{try{const e=m.deserialize(i),t=v.get(e);return ve.parse(t)}catch(e){throw new Error(`Failed transforming JSON-like value to BlueObject: ${e}`)}},mt=async i=>{const{resolveFunction:e,signal:t=new AbortController().signal,omitItems:r}=i,s=i.count??i.items.length;let n=await H.map(i.items,async l=>await gt(l));const o=Math.max(n?.length-s,0);for(let l=n.length-1;l>=o;l--)if(!Ar(n[l])){const a=await e(n[l],{signal:t});if(Array.isArray(a))return mt({...i,items:[...n.slice(0,l),...a,...n.slice(l+1)]});const c=await gt(a);if(r?.includes(c.blueId))return mt({...i,items:[...n.slice(0,l),...n.slice(l+1)]});n=[...n.slice(0,l),c,...n.slice(l+1)]}return n};function Ae(i){try{const e=new URL(i);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class fi{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 d().setBlueId(te)):typeof r=="bigint"||Q(r)?e.setType(new d().setBlueId(se)):He(r)?e.setType(new d().setBlueId(re)):typeof r=="boolean"&&e.setType(new d().setBlueId(ie))),e}}class Je{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof d){const r=e.getProperties();if(r&&r[Je.MAPPINGS]){const n=r[Je.MAPPINGS].getProperties();n&&Object.entries(n).forEach(([o,l])=>{const a=l.getValue();typeof a=="string"&&this.mappings.set(o,a)})}}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 s=this.mappings.get(r);if(s){const n=new d().setBlueId(s);t===e.getType()?e.setType(n):t===e.getItemType()?e.setItemType(n):t===e.getKeyType()?e.setKeyType(n):t===e.getValueType()&&e.setValueType(n)}}}}}class yi{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 s=String(t.getValue());throw new Error(`Unknown type "${s}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class Or{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const s of this.blueIdsCollections)Object.assign(t,s);const r=Object.entries(t).map(([s,n])=>` ${s}: ${n}`).join(`
20
20
  `);return`- type:
21
21
  blueId: ${e}
22
22
  mappings:
23
- ${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 be{static DEFAULT_BLUE_BLUE_ID="BF4xn5LN3HzQJSmqcXRyUq4tZEtkj2eBZ8UPCDJMnhG9";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:s}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=De.wrap(t),this.processorProvider=r||be.getStandardProvider(),this.blueIdsMappingGenerator=s||new Ot,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=e.clone(),s=r.getBlue();if(!s&&t&&(s=t.clone()),s){new At(this.nodeProvider).extend(s,Qe.withSinglePath("/*"));const n=this.flattenTransformationItems(s.getItems());if(n&&n.length>0){for(const o of n){const l=this.processorProvider.getProcessor(o);if(l)r=l.process(r);else throw new Error(`No processor found for transformation: ${o}`)}r.setBlue(void 0)}r=new hi().process(r)}return r}flattenTransformationItems(e){if(e!==void 0)return e.flatMap(t=>t.getItems()??[t])}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",s=e.getType()?.getBlueId();if(t===s)return new Ye(e);if(r===s)return new di}}}enrichDefaultBlue(e){if(this.blueIdsMappingGenerator.getTotalBlueIdCount()===0)return e;const t=this.blueIdsMappingGenerator.generateMappingsYaml();return`
23
+ ${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 De{static DEFAULT_BLUE_BLUE_ID="BF4xn5LN3HzQJSmqcXRyUq4tZEtkj2eBZ8UPCDJMnhG9";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:s}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=_e.wrap(t),this.processorProvider=r||De.getStandardProvider(),this.blueIdsMappingGenerator=s||new Or,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=e.clone(),s=r.getBlue();if(!s&&t&&(s=t.clone()),s){new Ot(this.nodeProvider).extend(s,et.withSinglePath("/*"));const n=this.flattenTransformationItems(s.getItems());if(n&&n.length>0){for(const o of n){const l=this.processorProvider.getProcessor(o);if(l)r=l.process(r);else throw new Error(`No processor found for transformation: ${o}`)}r.setBlue(void 0)}r=new yi().process(r)}return r}flattenTransformationItems(e){if(e!==void 0)return e.flatMap(t=>t.getItems()??[t])}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",s=e.getType()?.getBlueId();if(t===s)return new Je(e);if(r===s)return new fi}}}enrichDefaultBlue(e){if(this.blueIdsMappingGenerator.getTotalBlueIdCount()===0)return e;const t=this.blueIdsMappingGenerator.generateMappingsYaml();return`
24
24
  ${e}
25
25
  ${t}
26
- `}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(Br),t=te(e);if(t)this.defaultSimpleBlue=m.deserialize(t);else throw new Error("Failed to parse default Blue content")}catch(e){throw new Error(`Error loading default Blue: ${e}`)}}}class pi{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(Te.isPotentialBlueId(t))return this.handleBlueId(r,t);throw Ae(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(Te.isPotentialBlueId(t))return this.handleBlueId(r,t);if(Ae(t)&&this.urlContentFetcher)try{const s=await this.fetchFromUrl(t);return s&&r.setBlue(new d().setItems(s)),r}catch(s){throw s instanceof Error?new Error(`Failed to fetch from URL '${t}'.
27
- ${s.message}`):s}else throw Ae(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 d().setBlueId(this.preprocessingAliases.get(t))),e}handleBlueId(e,t){return e.setBlue(new d().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 fi={fetchUrl:async i=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${i}`)}};class yi{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||fi}validateUrl(e){if(!Ae(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(l){throw new Error(`Error fetching from URL: ${e}`,{cause:l})}const{data:r,contentType:s}=t;let n;if(s.includes("application/json")||s.includes("text/yaml")||s.includes("application/yaml")||s.includes("text/plain"))n=te(r);else throw new Error(`Unsupported content type from URL: ${s}`);if(n===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(n)?o=n.map(l=>m.deserialize(l)):o=[m.deserialize(n)],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 $e{constructor(e,t,r,s=[],n=!1){this.blueId=e,this.content=t,this.isMultipleDocuments=r,this.documentBlueIds=s,this.isCyclicSet=n}}class X{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t,r){let s;try{const a=te(e);if(a===void 0)throw new Error;s=a}catch{throw new Error("Failed to parse content as YAML or JSON")}let n,o;const l=Array.isArray(s);if(l){const a=s.map(p=>m.deserialize(p)),c=r.prepareStorageNodeList(a,t);return n=c.blueId,o=c.nodes.map(p=>T.get(p)),new $e(n,o,!0,c.documentBlueIds,c.isCyclicSet??!1)}else{const a=m.deserialize(s),c=r.prepareStorageNode(a,t);n=c.blueId,o=T.get(c.node)}return new $e(n,o,l)}static parseAndCalculateBlueIdForNode(e,t,r){const s=r.prepareStorageNode(e,t),n=T.get(s.node);return new $e(s.blueId,n,!1)}static parseAndCalculateBlueIdForNodeList(e,t,r){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const s=r.prepareStorageNodeList(e,t),n=s.nodes.map(l=>T.get(l)),o=!0;return new $e(s.blueId,n,o,s.documentBlueIds,s.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 s={};for(const[n,o]of Object.entries(e))typeof o=="string"?n===V&&this.THIS_REFERENCE_PATTERN.test(o)?s[n]=this.resolveThisReference(o,t,r):s[n]=o:o&&typeof o=="object"?s[n]=this.resolveThisReferencesRecursive(o,t,r):s[n]=o;return s}else if(Array.isArray(e))return e.map(s=>s&&typeof s=="object"?this.resolveThisReferencesRecursive(s,t,r):s);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 gi extends ge{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const s=Array.isArray(r),n=X.resolveThisReferences(r,t,s);if(e.includes("#")){const o=e.split("#");if(o.length>1){const l=parseInt(o[1]);if(Array.isArray(n)&&l<n.length){const a=n[l];return[m.deserialize(a)]}else return l===0?[m.deserialize(n)]:null}}return Array.isArray(n)?n.map(o=>m.deserialize(o)):[m.deserialize(n)]}}class Vr extends gi{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 s of t){const n=this.fetchByBlueId(s);n&&r.push(...n)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}class Vt extends Vr{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;aliasBlueIdMap=new Map;bootstrapBlueIdToContentMap=new Map;bootstrapBlueIdToMultipleDocumentsMap=new Map;preprocessor;storageService;constructor(e,t={}){super();const r=new Ot,s=Vt.collectAliasMappings(e);this.aliasBlueIdMap=new Map(Object.entries(s)),Object.keys(s).length>0&&r.registerBlueIds(s);const n=new be({nodeProvider:this,blueIdsMappingGenerator:r});this.preprocessor=o=>n.preprocessWithDefaultBlue(o),this.storageService=new Rr({nodeProvider:this,mergingProcessor:t.mergingProcessor}),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const s of Object.values(r.packages))for(const[n,o]of Object.entries(s.aliases)){const l=t[n];if(l&&l!==o)throw new Error(`Conflicting alias mapping for ${n}`);t[n]=o}return t}loadRepositories(e){for(const t of e)Object.values(t.packages).forEach(r=>{for(const[s,n]of Object.entries(r.contents))this.seedPreprocessedContent(s,n)});for(const t of e)Object.values(t.packages).forEach(r=>{for(const[s,n]of Object.entries(r.contents))this.processContent(n,s)});this.bootstrapBlueIdToContentMap.clear(),this.bootstrapBlueIdToMultipleDocumentsMap.clear()}seedPreprocessedContent(e,t){if(Array.isArray(t)){const s=t.map(n=>T.get(this.preprocessor(m.deserialize(n))));this.bootstrapBlueIdToContentMap.set(e,s),this.bootstrapBlueIdToMultipleDocumentsMap.set(e,!0);return}const r=this.preprocessor(m.deserialize(t));this.bootstrapBlueIdToContentMap.set(e,T.get(r)),this.bootstrapBlueIdToMultipleDocumentsMap.set(e,!1)}processContent(e,t){Array.isArray(e)?this.processMultipleDocuments(e,t):this.processSingleDocument(e,t)}processSingleDocument(e,t){const r=m.deserialize(e),s=X.parseAndCalculateBlueIdForNode(r,this.preprocessor,this.storageService);this.assertProvidedBlueId(s.blueId,t),this.storeContent(s.blueId,s.content,!1);const n=r.getName();n&&this.addToNameMap(n,s.blueId)}processMultipleDocuments(e,t){const r=e.map(n=>{const o=m.deserialize(n);return this.preprocessor(o)}),s=X.parseAndCalculateBlueIdForNodeList(r,n=>n,this.storageService);if(this.assertProvidedBlueId(s.blueId,t),this.storeContent(s.blueId,s.content,s.isMultipleDocuments),s.isCyclicSet){this.addListItemNames(s.blueId,s.content);return}r.forEach((n,o)=>{const l=`${s.blueId}#${o}`,a=X.parseAndCalculateBlueIdForNode(n,p=>p,this.storageService);this.blueIdToContentMap.set(a.blueId,a.content),this.blueIdToMultipleDocumentsMap.set(a.blueId,!1);const c=n.getName();c&&this.addToNameMap(c,l)})}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);if(t!==void 0&&r!==void 0)return X.resolveThisReferences(t,e,r);const s=this.bootstrapBlueIdToContentMap.get(e),n=this.bootstrapBlueIdToMultipleDocumentsMap.get(e);return s!==void 0&&n!==void 0?X.resolveThisReferences(s,e,n):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:s}=this.getBaseBlueIdAndSuffix(e);if(s===void 0)return e;const n=this.aliasBlueIdMap.get(r);if(n===void 0)return e;if(this.getBaseBlueIdAndSuffix(n).suffix===void 0)return`${n}${s}`}getBaseBlueIdAndSuffix(e){const t=e.indexOf("#");return t===-1?{baseBlueId:e}:{baseBlueId:e.slice(0,t),suffix:e.slice(t)}}assertProvidedBlueId(e,t){if(t!==void 0&&t!==e)throw new pe($.BLUE_ID_MISMATCH,`Repository content key '${t}' does not match semantic BlueId '${e}'.`,[{code:$.BLUE_ID_MISMATCH,message:"Repository contents must be keyed by the semantic BlueId of their minimal storage form.",context:{providedBlueId:t,computedBlueId:e}}])}}class mi{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(qe).forEach(([n,o])=>{this.blueIdToInlineValue.set(n,o)});const s=r.getAllBlueIds();Object.entries(s).forEach(([n,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,n)})}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 s=t();if(!s||s.isInlineValue()&&s.getValue()!==void 0)return;const n=s.getBlueId();if(!n)return;const o=this.resolveInlineValue(n,s);if(!o)return;const l=new d().setValue(o).setInlineValue(!0);r(l)}resolveInlineValue(e,t){const r=this.blueIdToInlineValue.get(e);if(r)return r;const s=t.getName();if(s)return this.blueIdToInlineValue.set(e,s),s;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Ii{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Ti(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)Ai(this.contents,r.contents,r.name),Ri(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]??Wt[e]??e;for(const r of this.runtimes){const s=r.toCurrentBlueIdIndex[t];if(s)return s}return t}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=qe[t];if(r)return r;for(const s of this.runtimes){const n=s.typeAliasByCurrentBlueId[t];if(n)return n}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const s=r.types[t];if(s)return{runtime:r,currentBlueId:t,typeMeta:s,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Ti(i){const e=vi(i);return Object.values(i.packages).forEach(t=>{Bi(e,i,t)}),{name:i.name,repositoryVersions:i.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 vi(i){const e=Object.fromEntries(i.repositoryVersions.map((r,s)=>[r,s])),t=i.repositoryVersions[i.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Bi(i,e,t){if(i.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);i.packageNames.add(t.name),bi(i,t),Ni(i,e,t),Pi(i,t),Si(i,t)}function bi(i,e){Object.entries(e.aliases).forEach(([t,r])=>{if(i.aliases[t]&&i.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);i.aliases[t]=r})}function Ni(i,e,t){Object.entries(t.typesMeta).forEach(([r,s])=>{if(i.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const n=wi(s,e,r,t.name);if(i.types[r]=n,i.typePackageByCurrentBlueId[r]=t.name,i.typeAliasByCurrentBlueId[r]=`${t.name}/${s.name}`,n.status===B.BLUE_REPOSITORY_STATUS_STABLE&&!i.toCurrentBlueIdIndex[r]&&(i.toCurrentBlueIdIndex[r]=r),n.status===B.BLUE_REPOSITORY_STATUS_STABLE)for(const o of n.versions){const l=i.toCurrentBlueIdIndex[o.typeBlueId];if(l&&l!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);i.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function Pi(i,e){Object.entries(e.contents).forEach(([t,r])=>{i.contents[t]=r})}function Si(i,e){i.schemas.push(...Object.values(e.schemas))}function wi(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV)return Ei(i,e,t,r),{...i,versions:i.versions?[...i.versions]:i.versions};const s=[...i.versions??[]].sort((o,l)=>o.repositoryVersionIndex-l.repositoryVersionIndex);if(s.length===0)throw new Error(`Stable type ${r}/${i.name} (${t}) must have at least one version entry`);const n=new Set;return s.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);if(n.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);n.add(o.repositoryVersionIndex);for(const l of o.attributesAdded??[])Ci(l,e.name,t,o.repositoryVersionIndex)}),{...i,versions:s}}function Ei(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV){if(i.versions&&i.versions.length>1)throw new Error(`Dev type ${r}/${i.name} (${t}) must not declare multiple versions`);if(i.versions&&i.versions.length===1){const s=i.versions[0];if(s.repositoryVersionIndex<0||s.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${s.repositoryVersionIndex} for dev type ${r}/${i.name}`)}}}function Ci(i,e,t,r){try{B.validateAttributesAddedPointer(i)}catch(s){const n=s instanceof Error?s.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${i}' for type ${t} in repository ${e} at index ${r}: ${n}`)}}function Ri(i,e,t){for(const[r,s]of Object.entries(e)){const n=i[r];if(n&&n!==s)throw new Error(`Conflicting alias '${r}' across repositories: '${n}' vs '${s}' (from ${t})`);i[r]=s}}function Ai(i,e,t){for(const[r,s]of Object.entries(e)){if(r in i){const n=i[r];if(!Oi(n,s))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}i[r]=s}}function Oi(i,e){if(i===e)return!0;if(i===null||e===null||typeof i!="object"||typeof e!="object")return!1;const t=Ke.canonicalize(i),r=Ke.canonicalize(e);return t!==void 0&&t===r}const Vi=new Set(["__proto__","constructor","prototype"]);function $t(i){const e=i.at(0),t=i.at(-1);return!e||!t?i:e==="'"&&t==="'"||e==='"'&&t==='"'?i.slice(1,-1):i}function Mi(i,e){const t=i.indexOf("=");if(t===-1)throw Ie(e,`Missing '=' in segment '${i.trim()}'`);if(i.indexOf("=",t+1)!==-1)throw Ie(e,`Unexpected '=' in segment '${i.trim()}'`);const r=$t(i.slice(0,t).trim()),s=$t(i.slice(t+1).trim());if(!r)throw Ie(e,"Repository name is empty");if(!s)throw Ie(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:s}}function Di(i){if(i.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of i.split(",")){const r=t.trim();if(!r)throw Ie(i,"Empty repository segment");const{name:s,value:n}=Mi(r,i);Li(s,i),e[s]=n}return e}function _i(i){return typeof i=="string"?Di(i):i}function Ie(i,e){return new pe($.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:$.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:i,reason:e}}])}function Li(i,e){if(Vi.has(i))throw Ie(e,`Forbidden repository name '${i}'`)}function ji(i,e){const t=i.filter(s=>s.repositoryVersionIndex>e).sort((s,n)=>n.repositoryVersionIndex-s.repositoryVersionIndex),r=[];for(const s of t){const n=[...s.attributesAdded].sort((o,l)=>xt(l)-xt(o));r.push(...n)}return r}function xt(i){return B.parsePointer(i).length}const $i=new Set([...Tt]),R={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class xi{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(),s=r?.getBlueId();if(!r||!s)return;const n=this.resolveType(s);switch(n.kind){case R.core:{r.setBlueId(n.blueId);return}case R.representable:{this.applyDropPointers([r],n.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,n.dropPointers),r.setBlueId(n.targetBlueId);return}case R.noRuntime:case R.noTargetContext:case R.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,s);return}throw n.kind===R.unrepresentable?n.error:this.unrepresentableError(s,n.kind===R.noTargetContext?`Repository '${n.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",n.kind===R.noTargetContext?n.runtime:void 0,n.kind===R.noTargetContext?n.meta:void 0,void 0,n.kind===R.noTargetContext?n.typeAlias:void 0)}}}resolveType(e){if(ye.includes(e))return{kind:R.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),s=this.registry.findRuntimeByBlueId(t);if(!s||!s.typeMeta)return{kind:R.noRuntime};const n=this.targetRepoVersionIndexes[s.runtime.name];if(n===void 0)return{kind:R.noTargetContext,currentBlueId:t,runtimeName:s.runtime.name,runtime:s.runtime,meta:s.typeMeta,typeAlias:r};const o=s.typeMeta;if(o.status===B.BLUE_REPOSITORY_STATUS_DEV){const f=s.runtime.repositoryVersions.length-1;if(n!==f)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${n}.`,s.runtime,o,n,r)};const y=o.versions?.[0];return{kind:R.representable,currentBlueId:t,targetBlueId:y?.typeBlueId??t,dropPointers:[]}}const l=o.versions||[];if(l.length===0)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,s.runtime,o,n,r)};const a=l[0].repositoryVersionIndex;if(n<a)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${n}.`,s.runtime,o,n,r)};let c=l[0].typeBlueId;for(const f of l)f.repositoryVersionIndex<=n&&(c=f.typeBlueId);const p=o.status===B.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,n):[];return{kind:R.representable,currentBlueId:t,targetBlueId:c,dropPointers:p}}getDropPointers(e,t){return e.status!==B.BLUE_REPOSITORY_STATUS_STABLE?[]:ji(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const s=r.rootIsSchema??!1;for(const n of t)for(const o of e)this.deletePropertyAtPointer(o,n,s)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,s])=>s instanceof d&&!$i.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let s;try{s=B.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,s,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[s,...n]=t;if(s===U){const a=e.getType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Ne){const a=e.getItemType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Pe){const a=e.getKeyType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Se){const a=e.getValueType();a&&this.applyPointerSegments(a,n,!0);return}const o=e.getProperties();if(!o)return;if(n.length===0){if(!r||!(s in o))return;const a={...o};delete a[s],e.setProperties(a);return}const l=o[s];l instanceof d&&this.applyPointerSegments(l,n,r)}inlineDefinition(e,t,r){const s=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(s))throw this.unrepresentableError(s,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(s)});const n=this.registry.getContents()[s];if(!n)throw this.unrepresentableError(s,`Missing definition to inline for BlueId ${s}.`);this.inliningStack.add(s);try{const o=m.deserialize(n);o.setBlueId(void 0);const l=M.transform(o,a=>this.transformNode(a));return t(l),e}finally{this.inliningStack.delete(s)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new pe($.INVALID_REPOSITORY_POINTER,t,[{code:$.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,s,n,o,l){const a={currentTypeBlueId:e,targetRepoVersionIndex:n,typeAlias:o,...l};if(r&&(n!==void 0&&(a.requestedRepoBlueId=r.repositoryVersions[n]),a.serverRepoBlueId=r.currentRepoBlueId),s&&s.status===B.BLUE_REPOSITORY_STATUS_STABLE){const p=s.versions?.[0]?.repositoryVersionIndex;p!==void 0&&(a.typeIntroducedInRepoBlueId=r?.repositoryVersions[p])}const c={code:$.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[U],context:a};return new pe($.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[c])}}function It(i,e){return e?M.transform(i,t=>(xe(()=>t.getType(),r=>t.setType(r),e),xe(()=>t.getItemType(),r=>t.setItemType(r),e),xe(()=>t.getKeyType(),r=>t.setKeyType(r),e),xe(()=>t.getValueType(),r=>t.setValueType(r),e),t)):i}function xe(i,e,t){const r=i();if(!r||r.isInlineValue())return;const s=r.getBlueId();if(!s)return;const n=t.toCurrentBlueId(s);n!==s&&e(r.clone().setBlueId(n))}class Fi{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 s=It(e,this.blueIdMapper);return new xi({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(s)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?_i(e.repositories):e.repositories;for(const[s,n]of Object.entries(r)){const o=this.registry.findRuntimeByName(s);if(!o)continue;const l=o.repoVersionIndexById[n];if(l===void 0)throw this.unknownRepoBlueIdError(s,n,o.currentRepoBlueId);t[s]=l}return t}unknownRepoBlueIdError(e,t,r){const s=`Unknown RepoBlueId '${t}' for repository '${e}'.`,n={code:$.REPO_UNKNOWN_REPO_BLUE_ID,message:s,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new pe($.REPO_UNKNOWN_REPO_BLUE_ID,s,[n])}}class We{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=x;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:s,repositories:n,mergingProcessor:o}=e;this.repositories=n,this.repositoryRegistry=new Ii(n??[]),this.blueContextResolver=new Fi({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry}),this.mergingProcessor=o??rt();const l=tt(()=>[]);this.nodeProvider=this.wrapNodeProviderWithRepositories(t||l,n),this.typeSchemaResolver=r??new gr([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.urlContentFetcher=new yi(s),this.blueDirectivePreprocessor=new pi(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new Ot,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const a=this.repositoryRegistry.getRuntimes().flatMap(c=>c.schemas);a.length>0&&this.typeSchemaResolver?.registerSchemas(a)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return T.get(s,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return ni.get(s,{strategy:r.format})}nodeToSchemaOutput(e,t){return new ii(this.typeSchemaResolver,{calculateBlueId:s=>this.calculateBlueIdSync(s)}).convert(e,t)}resolve(e,t=x){const r=this.combineWithGlobalLimits(t),n=new le(this.mergingProcessor,this.nodeProvider).resolve(e,r);if(!(r instanceof H)){const o=this.getExactReferenceBlueId(e);o!==void 0&&n.setSourceSemanticBlueId(o)}return n}createResolvedNode(e){return e instanceof k?e:new k(e)}reverse(e){return this.minimize(e)}minimize(e){return new Re({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).minimize(e)}restoreInlineTypes(e){return new mi({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new At(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(m.deserialize(e));return It(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(m.deserialize(e));return It(t,this.repositoryRegistry)}yamlToNode(e){const t=te(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}async yamlToNodeAsync(e){const t=te(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeAsync(t)}prepareForBlueIdCalculation=async e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?await Promise.all(e.map(r=>this.jsonValueToNodeAsync(r))):this.jsonValueToNodeAsync(e);calculateBlueId=async e=>{const t=await this.prepareForBlueIdCalculation(e);return new Re({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).calculateBlueId(t)};prepareForBlueIdCalculationSync=e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?e.map(t=>this.jsonValueToNode(t)):this.jsonValueToNode(e);calculateBlueIdSync(e){const t=this.prepareForBlueIdCalculationSync(e);return new Re({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 be({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new be({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(!E.hasBlueIdOnly(e))return;const t=e.getReferenceBlueId();return t!==void 0&&Te.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()}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 z.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 s=e.getType();if(!s)return!1;const n=new d().setReferenceBlueId(r);return C(s,n,this.nodeProvider)}isTypeOfNode(e,t){return new Ds(this).matchesType(e,t,this.globalLimits)}setGlobalLimits(e){return this.globalLimits=e??x,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?De.wrap(new Ir([new Vt(t,{mergingProcessor:this.mergingProcessor}),e])):De.wrap(e)}combineWithGlobalLimits(e){return this.globalLimits==x?e:e==x?this.globalLimits:et.of(this.globalLimits,e)}}const zi=Object.freeze(Object.defineProperty({__proto__:null,Blue:We},Symbol.toStringTag,{value:"Module"})),ut=new WeakMap,Ui=10;function Ki(i,e={}){const t=e.mergingProcessor===void 0;if(t){const a=ut.get(i);if(a)return a}const r=Hi(i);if(r.length===0)return t&&ut.set(i,i),i;const s=Yi(i),n=e.mergingProcessor??rt();let o=Object.fromEntries(r.map(({oldBlueId:a})=>[a,a]));const l=ki(r.length);for(let a=0;a<l;a++){const c=Wi(r,s,o,n);if(qi(o,c)){const p=Ji(i,o);return t&&ut.set(i,p),p}o=c}throw new Error(`Repository semantic reindexing did not converge after ${l} passes for ${r.length} entries.`)}function ki(i){return Math.max(Ui,i+1)}function Hi(i){const e=[];for(const[t,r]of Object.entries(i.packages))for(const[s,n]of Object.entries(r.contents))e.push({packageName:t,oldBlueId:s,content:n});return e}function Yi(i){const e={};for(const t of Object.values(i.packages))for(const[r,s]of Object.entries(t.aliases))e[r]=s;return e}function Wi(i,e,t,r){const s=new Map(i.map(({oldBlueId:c,content:p})=>[c,Je(p,t)])),n=new Map;for(const{oldBlueId:c}of i)n.set(c,c),n.set(t[c],c);const o=new We,l={fetchByBlueId(c){const[p,f]=c.split("#"),y=n.get(p);if(!y)return[];const g=s.get(y);if(g===void 0)return[];if(Array.isArray(g)){if(f!==void 0){const I=g[Number(f)];return I===void 0?[]:[o.jsonValueToNode(I)]}return g.map(I=>o.jsonValueToNode(I))}return f!==void 0&&f!=="0"?[]:[o.jsonValueToNode(g)]},fetchFirstByBlueId(c){return this.fetchByBlueId(c)[0]??null}},a=new We({nodeProvider:l,mergingProcessor:r});return a.registerBlueIds(Mr(e,t)),Object.fromEntries(i.map(({packageName:c,oldBlueId:p})=>{const f=s.get(p);if(f===void 0)throw new Error(`Missing repository content for ${p}.`);try{const y=a.jsonValueToNode(f);return[p,a.calculateBlueIdSync(y)]}catch(y){const g=y instanceof Error?y.message:String(y);throw new Error(`Failed to calculate semantic BlueId for ${c}/${p}: ${g}`)}}))}function Ji(i,e){return{name:i.name,repositoryVersions:i.repositoryVersions,packages:Object.fromEntries(Object.entries(i.packages).map(([t,r])=>[t,Gi(r,e)]))}}function Gi(i,e){return{name:i.name,aliases:Mr(i.aliases,e),typesMeta:Object.fromEntries(Object.entries(i.typesMeta).map(([t,r])=>[e[t]??t,Zi(r,e)])),contents:Object.fromEntries(Object.entries(i.contents).map(([t,r])=>[e[t]??t,Je(r,e)])),schemas:Object.fromEntries(Object.entries(i.schemas).map(([t,r])=>{const s=e[t]??t;return[s,pr(s)(r)]}))}}function Zi(i,e){return{...i,versions:i.versions.map(t=>({...t,typeBlueId:Mt(t.typeBlueId,e)}))}}function qi(i,e){const t=Object.keys(i);return t.length!==Object.keys(e).length?!1:t.every(r=>i[r]===e[r])}function Mr(i,e){return Object.fromEntries(Object.entries(i).map(([t,r])=>[t,Mt(r,e)]))}function Je(i,e){return Array.isArray(i)?i.map(t=>Je(t,e)):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([t,r])=>[t,t==="blueId"&&typeof r=="string"?Mt(r,e):Je(r,e)])):i}function Mt(i,e){const t=e[i];if(t!==void 0)return t;const r=/^(.*)(#\d+)$/.exec(i);if(!r)return i;const[,s,n]=r;return`${e[s]??s}${n}`}class Xi extends Vr{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;storageService;constructor(e=[]){super();const t=new be({nodeProvider:this});this.preprocessor=r=>t.preprocessWithDefaultBlue(r),this.storageService=new Rr({nodeProvider:this}),e.forEach(r=>this.processNode(r))}processNode(e){E.hasItemsOnly(e)?this.processNodeWithItems(e):this.processSingleNode(e)}processSingleNode(e){const t=X.parseAndCalculateBlueIdForNode(e,this.preprocessor,this.storageService);this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,t.isMultipleDocuments);const r=e.getName();r&&this.addToNameMap(r,t.blueId)}processNodeWithItems(e){const t=e.getItems();if(!t)return;const r=this.storeNodeList(t);this.addListItemNames(r.blueId,r.content)}processNodeList(e){this.storeNodeList(e)}storeNodeList(e){const t=X.parseAndCalculateBlueIdForNodeList(e,this.preprocessor,this.storageService);return this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,!0),t}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?X.resolveThisReferences(t,e,r):null}addSingleNodes(...e){e.forEach(t=>this.processNode(t))}addSingleDocs(...e){e.forEach(t=>{const r=te(t);if(r!==void 0){const s=m.deserialize(r);this.processNode(s)}})}getBlueIdByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t||t.length===0)throw new Error(`No node with name "${e}"`);return t[0]}getNodeByName(e){const t=this.findNodeByName(e);if(!t)throw new Error(`No node with name "${e}"`);return t}addListAndItsItemsFromNodes(e){const t=this.storeNodeList(e);if(j.hasThisReference(e)){this.addListItemNames(t.blueId,t.content);return}e.forEach(r=>this.processNode(r))}addListAndItsItemsFromDoc(e){const t=te(e);if(t!==void 0){const s=m.deserialize(t).getItems();s&&this.addListAndItsItems(s)}}addListAndItsItems(e){Array.isArray(e)?this.addListAndItsItemsFromNodes(e):this.addListAndItsItemsFromDoc(e)}addList(e){this.processNodeList(e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}}exports.Base58Sha256Provider=Xt;exports.BasicNodeProvider=Xi;exports.Blue=We;exports.BlueIdCalculator=A;exports.BlueIdToCid=ls;exports.BlueNode=d;exports.BlueNodeTypeSchema=z;exports.JsonCanonicalizer=Ke;exports.Limits=Xe;exports.Merger=le;exports.MergingProcessors=Hs;exports.NodeResolver=mr;exports.Nodes=E;exports.Properties=$r;exports.ResolvedBlueNode=k;exports.SemanticIdentityService=Re;exports.TypeSchemaResolver=gr;exports.applyBlueNodePatch=ms;exports.baseBlueObjectSchema=Le;exports.blueDescriptionField=Ts;exports.blueIdField=Bs;exports.blueIdSchema=Fr;exports.blueNameField=bs;exports.blueNodeField=Ns;exports.blueObjectBooleanValueSchema=Kr;exports.blueObjectNumberValueSchema=Ur;exports.blueObjectSchema=ve;exports.blueObjectStringListItemsSchema=kr;exports.blueObjectStringValueSchema=zr;exports.createNodeProvider=tt;exports.enrichWithBlueId=gt;exports.getBlueDescriptionAnnotation=nr;exports.getBlueIdAnnotation=lr;exports.getBlueNameAnnotation=cr;exports.getBlueNodeAnnotation=dr;exports.getBlueObjectItems=oi;exports.getBlueObjectProperties=ai;exports.getBlueObjectTypeLabel=ci;exports.getBlueObjectValue=li;exports.getTypeBlueIdAnnotation=hr;exports.hasBlueObjectBlueIdDefined=Jt;exports.hasBlueObjectItemsDefined=Gt;exports.hasBlueObjectNameDefined=Yr;exports.hasBlueObjectTypeDefined=Zt;exports.hasBlueObjectValueDefined=qt;exports.isBigDecimalNumber=Ue;exports.isBigIntegerNumber=ee;exports.isBigNumber=w;exports.isBlueNodeSchema=Ct;exports.isBlueObject=Hr;exports.isBlueObjectResolved=Or;exports.isGivenBlueObjectTypeSchema=Wr;exports.isJsonBlueArray=Pt;exports.isJsonBlueObject=Nt;exports.isJsonBlueValue=Zr;exports.isUrl=Ae;exports.jsonBlueValueSchema=Ve;exports.normalizeToBlueObject=ui;exports.reindexRepositoryForSemanticStorage=Ki;exports.resolveBlueObjectItems=mt;exports.withBlueDescription=ir;exports.withBlueId=or;exports.withBlueName=ar;exports.withBlueNode=ur;exports.withTypeBlueId=pr;exports.yamlBlueDump=vr;exports.yamlBlueParse=te;
26
+ `}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(Br),t=ee(e);if(t)this.defaultSimpleBlue=m.deserialize(t);else throw new Error("Failed to parse default Blue content")}catch(e){throw new Error(`Error loading default Blue: ${e}`)}}}class gi{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(Te.isPotentialBlueId(t))return this.handleBlueId(r,t);throw Ae(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(Te.isPotentialBlueId(t))return this.handleBlueId(r,t);if(Ae(t)&&this.urlContentFetcher)try{const s=await this.fetchFromUrl(t);return s&&r.setBlue(new d().setItems(s)),r}catch(s){throw s instanceof Error?new Error(`Failed to fetch from URL '${t}'.
27
+ ${s.message}`):s}else throw Ae(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 d().setBlueId(this.preprocessingAliases.get(t))),e}handleBlueId(e,t){return e.setBlue(new d().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 mi={fetchUrl:async i=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${i}`)}};class Ii{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||mi}validateUrl(e){if(!Ae(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(l){throw new Error(`Error fetching from URL: ${e}`,{cause:l})}const{data:r,contentType:s}=t;let n;if(s.includes("application/json")||s.includes("text/yaml")||s.includes("application/yaml")||s.includes("text/plain"))n=ee(r);else throw new Error(`Unsupported content type from URL: ${s}`);if(n===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(n)?o=n.map(l=>m.deserialize(l)):o=[m.deserialize(n)],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 Fe{constructor(e,t,r,s=[],n=!1){this.blueId=e,this.content=t,this.isMultipleDocuments=r,this.documentBlueIds=s,this.isCyclicSet=n}}class Ie{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t,r){let s;try{const a=ee(e);if(a===void 0)throw new Error;s=a}catch{throw new Error("Failed to parse content as YAML or JSON")}let n,o;const l=Array.isArray(s);if(l){const a=s.map(p=>m.deserialize(p)),c=r.prepareStorageNodeList(a,t);return n=c.blueId,o=c.nodes.map(p=>v.get(p)),new Fe(n,o,!0,c.documentBlueIds,c.isCyclicSet??!1)}else{const a=m.deserialize(s),c=r.prepareStorageNode(a,t);n=c.blueId,o=v.get(c.node)}return new Fe(n,o,l)}static parseAndCalculateBlueIdForNode(e,t,r){const s=r.prepareStorageNode(e,t),n=v.get(s.node);return new Fe(s.blueId,n,!1)}static parseAndCalculateBlueIdForNodeList(e,t,r){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const s=r.prepareStorageNodeList(e,t),n=s.nodes.map(l=>v.get(l)),o=!0;return new Fe(s.blueId,n,o,s.documentBlueIds,s.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 s={};for(const[n,o]of Object.entries(e))typeof o=="string"?n===V&&this.THIS_REFERENCE_PATTERN.test(o)?s[n]=this.resolveThisReference(o,t,r):s[n]=o:o&&typeof o=="object"?s[n]=this.resolveThisReferencesRecursive(o,t,r):s[n]=o;return s}else if(Array.isArray(e))return e.map(s=>s&&typeof s=="object"?this.resolveThisReferencesRecursive(s,t,r):s);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 Ti extends ye{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const s=Array.isArray(r),n=Ie.resolveThisReferences(r,t,s);if(e.includes("#")){const o=e.split("#");if(o.length>1){const l=parseInt(o[1]);if(Array.isArray(n)&&l<n.length){const a=n[l];return[m.deserialize(a)]}else return l===0?[m.deserialize(n)]:null}}return Array.isArray(n)?n.map(o=>m.deserialize(o)):[m.deserialize(n)]}}class Vr extends Ti{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 s of t){const n=this.fetchByBlueId(s);n&&r.push(...n)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}class Vt extends Vr{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;aliasBlueIdMap=new Map;constructor(e,t={}){super();const r=Vt.collectAliasMappings(e);this.aliasBlueIdMap=new Map(Object.entries(r)),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const s of Object.values(r.packages))for(const[n,o]of Object.entries(s.aliases)){const l=t[n];if(l&&l!==o)throw new Error(`Conflicting alias mapping for ${n}`);t[n]=o}return t}loadRepositories(e){for(const t of e)Object.values(t.packages).forEach(r=>{for(const[s,n]of Object.entries(r.contents))this.storeContent(s,n,Array.isArray(n)),this.addContentNames(s,n)})}addContentNames(e,t){if(Array.isArray(t)){this.addListItemNames(e,t);return}const s=m.deserialize(t).getName();s&&this.addToNameMap(s,e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Ie.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:s}=this.getBaseBlueIdAndSuffix(e);if(s===void 0)return e;const n=this.aliasBlueIdMap.get(r);if(n===void 0)return e;if(this.getBaseBlueIdAndSuffix(n).suffix===void 0)return`${n}${s}`}getBaseBlueIdAndSuffix(e){const t=e.indexOf("#");return t===-1?{baseBlueId:e}:{baseBlueId:e.slice(0,t),suffix:e.slice(t)}}}class vi{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(Xe).forEach(([n,o])=>{this.blueIdToInlineValue.set(n,o)});const s=r.getAllBlueIds();Object.entries(s).forEach(([n,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,n)})}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 s=t();if(!s||s.isInlineValue()&&s.getValue()!==void 0)return;const n=s.getBlueId();if(!n)return;const o=this.resolveInlineValue(n,s);if(!o)return;const l=new d().setValue(o).setInlineValue(!0);r(l)}resolveInlineValue(e,t){const r=this.blueIdToInlineValue.get(e);if(r)return r;const s=t.getName();if(s)return this.blueIdToInlineValue.set(e,s),s;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Bi{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(bi(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)Mi(this.contents,r.contents,r.name),Vi(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]??Wt[e]??e;for(const r of this.runtimes){const s=r.toCurrentBlueIdIndex[t];if(s)return s}return t}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=Xe[t];if(r)return r;for(const s of this.runtimes){const n=s.typeAliasByCurrentBlueId[t];if(n)return n}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const s=r.types[t];if(s)return{runtime:r,currentBlueId:t,typeMeta:s,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function bi(i){const e=Ni(i);return Object.values(i.packages).forEach(t=>{Pi(e,i,t)}),{name:i.name,repositoryVersions:i.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 Ni(i){const e=Object.fromEntries(i.repositoryVersions.map((r,s)=>[r,s])),t=i.repositoryVersions[i.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Pi(i,e,t){if(i.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);i.packageNames.add(t.name),Si(i,t),wi(i,e,t),Ei(i,t),Ci(i,t)}function Si(i,e){Object.entries(e.aliases).forEach(([t,r])=>{if(i.aliases[t]&&i.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);i.aliases[t]=r})}function wi(i,e,t){Object.entries(t.typesMeta).forEach(([r,s])=>{if(i.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const n=Ri(s,e,r,t.name);if(i.types[r]=n,i.typePackageByCurrentBlueId[r]=t.name,i.typeAliasByCurrentBlueId[r]=`${t.name}/${s.name}`,n.status===B.BLUE_REPOSITORY_STATUS_STABLE&&!i.toCurrentBlueIdIndex[r]&&(i.toCurrentBlueIdIndex[r]=r),n.status===B.BLUE_REPOSITORY_STATUS_STABLE)for(const o of n.versions){const l=i.toCurrentBlueIdIndex[o.typeBlueId];if(l&&l!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);i.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function Ei(i,e){Object.entries(e.contents).forEach(([t,r])=>{i.contents[t]=r})}function Ci(i,e){i.schemas.push(...Object.values(e.schemas))}function Ri(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV)return Ai(i,e,t,r),{...i,versions:i.versions?[...i.versions]:i.versions};const s=[...i.versions??[]].sort((o,l)=>o.repositoryVersionIndex-l.repositoryVersionIndex);if(s.length===0)throw new Error(`Stable type ${r}/${i.name} (${t}) must have at least one version entry`);const n=new Set;return s.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);if(n.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${i.name}`);n.add(o.repositoryVersionIndex);for(const l of o.attributesAdded??[])Oi(l,e.name,t,o.repositoryVersionIndex)}),{...i,versions:s}}function Ai(i,e,t,r){if(i.status===B.BLUE_REPOSITORY_STATUS_DEV){if(i.versions&&i.versions.length>1)throw new Error(`Dev type ${r}/${i.name} (${t}) must not declare multiple versions`);if(i.versions&&i.versions.length===1){const s=i.versions[0];if(s.repositoryVersionIndex<0||s.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${s.repositoryVersionIndex} for dev type ${r}/${i.name}`)}}}function Oi(i,e,t,r){try{B.validateAttributesAddedPointer(i)}catch(s){const n=s instanceof Error?s.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${i}' for type ${t} in repository ${e} at index ${r}: ${n}`)}}function Vi(i,e,t){for(const[r,s]of Object.entries(e)){const n=i[r];if(n&&n!==s)throw new Error(`Conflicting alias '${r}' across repositories: '${n}' vs '${s}' (from ${t})`);i[r]=s}}function Mi(i,e,t){for(const[r,s]of Object.entries(e)){if(r in i){const n=i[r];if(!_i(n,s))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}i[r]=s}}function _i(i,e){if(i===e)return!0;if(i===null||e===null||typeof i!="object"||typeof e!="object")return!1;const t=ke.canonicalize(i),r=ke.canonicalize(e);return t!==void 0&&t===r}const Di=new Set(["__proto__","constructor","prototype"]);function xt(i){const e=i.at(0),t=i.at(-1);return!e||!t?i:e==="'"&&t==="'"||e==='"'&&t==='"'?i.slice(1,-1):i}function Li(i,e){const t=i.indexOf("=");if(t===-1)throw me(e,`Missing '=' in segment '${i.trim()}'`);if(i.indexOf("=",t+1)!==-1)throw me(e,`Unexpected '=' in segment '${i.trim()}'`);const r=xt(i.slice(0,t).trim()),s=xt(i.slice(t+1).trim());if(!r)throw me(e,"Repository name is empty");if(!s)throw me(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:s}}function ji(i){if(i.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of i.split(",")){const r=t.trim();if(!r)throw me(i,"Empty repository segment");const{name:s,value:n}=Li(r,i);$i(s,i),e[s]=n}return e}function xi(i){return typeof i=="string"?ji(i):i}function me(i,e){return new he(x.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:x.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:i,reason:e}}])}function $i(i,e){if(Di.has(i))throw me(e,`Forbidden repository name '${i}'`)}function Fi(i,e){const t=i.filter(s=>s.repositoryVersionIndex>e).sort((s,n)=>n.repositoryVersionIndex-s.repositoryVersionIndex),r=[];for(const s of t){const n=[...s.attributesAdded].sort((o,l)=>$t(l)-$t(o));r.push(...n)}return r}function $t(i){return B.parsePointer(i).length}const zi=new Set([...vt]),R={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class Ui{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(),s=r?.getBlueId();if(!r||!s)return;const n=this.resolveType(s);switch(n.kind){case R.core:{r.setBlueId(n.blueId);return}case R.representable:{this.applyDropPointers([r],n.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,n.dropPointers),r.setBlueId(n.targetBlueId);return}case R.noRuntime:case R.noTargetContext:case R.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,s);return}throw n.kind===R.unrepresentable?n.error:this.unrepresentableError(s,n.kind===R.noTargetContext?`Repository '${n.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",n.kind===R.noTargetContext?n.runtime:void 0,n.kind===R.noTargetContext?n.meta:void 0,void 0,n.kind===R.noTargetContext?n.typeAlias:void 0)}}}resolveType(e){if(fe.includes(e))return{kind:R.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),s=this.registry.findRuntimeByBlueId(t);if(!s||!s.typeMeta)return{kind:R.noRuntime};const n=this.targetRepoVersionIndexes[s.runtime.name];if(n===void 0)return{kind:R.noTargetContext,currentBlueId:t,runtimeName:s.runtime.name,runtime:s.runtime,meta:s.typeMeta,typeAlias:r};const o=s.typeMeta;if(o.status===B.BLUE_REPOSITORY_STATUS_DEV){const f=s.runtime.repositoryVersions.length-1;if(n!==f)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${n}.`,s.runtime,o,n,r)};const y=o.versions?.[0];return{kind:R.representable,currentBlueId:t,targetBlueId:y?.typeBlueId??t,dropPointers:[]}}const l=o.versions||[];if(l.length===0)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,s.runtime,o,n,r)};const a=l[0].repositoryVersionIndex;if(n<a)return{kind:R.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${n}.`,s.runtime,o,n,r)};let c=l[0].typeBlueId;for(const f of l)f.repositoryVersionIndex<=n&&(c=f.typeBlueId);const p=o.status===B.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,n):[];return{kind:R.representable,currentBlueId:t,targetBlueId:c,dropPointers:p}}getDropPointers(e,t){return e.status!==B.BLUE_REPOSITORY_STATUS_STABLE?[]:Fi(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const s=r.rootIsSchema??!1;for(const n of t)for(const o of e)this.deletePropertyAtPointer(o,n,s)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,s])=>s instanceof d&&!zi.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let s;try{s=B.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,s,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[s,...n]=t;if(s===K){const a=e.getType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Ne){const a=e.getItemType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Pe){const a=e.getKeyType();a&&this.applyPointerSegments(a,n,!0);return}if(s===Se){const a=e.getValueType();a&&this.applyPointerSegments(a,n,!0);return}const o=e.getProperties();if(!o)return;if(n.length===0){if(!r||!(s in o))return;const a={...o};delete a[s],e.setProperties(a);return}const l=o[s];l instanceof d&&this.applyPointerSegments(l,n,r)}inlineDefinition(e,t,r){const s=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(s))throw this.unrepresentableError(s,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(s)});const n=this.registry.getContents()[s];if(!n)throw this.unrepresentableError(s,`Missing definition to inline for BlueId ${s}.`);this.inliningStack.add(s);try{const o=m.deserialize(n);o.setBlueId(void 0);const l=M.transform(o,a=>this.transformNode(a));return t(l),e}finally{this.inliningStack.delete(s)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new he(x.INVALID_REPOSITORY_POINTER,t,[{code:x.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,s,n,o,l){const a={currentTypeBlueId:e,targetRepoVersionIndex:n,typeAlias:o,...l};if(r&&(n!==void 0&&(a.requestedRepoBlueId=r.repositoryVersions[n]),a.serverRepoBlueId=r.currentRepoBlueId),s&&s.status===B.BLUE_REPOSITORY_STATUS_STABLE){const p=s.versions?.[0]?.repositoryVersionIndex;p!==void 0&&(a.typeIntroducedInRepoBlueId=r?.repositoryVersions[p])}const c={code:x.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[K],context:a};return new he(x.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[c])}}function It(i,e){return e?M.transform(i,t=>(ze(()=>t.getType(),r=>t.setType(r),e),ze(()=>t.getItemType(),r=>t.setItemType(r),e),ze(()=>t.getKeyType(),r=>t.setKeyType(r),e),ze(()=>t.getValueType(),r=>t.setValueType(r),e),t)):i}function ze(i,e,t){const r=i();if(!r||r.isInlineValue())return;const s=r.getBlueId();if(!s)return;const n=t.toCurrentBlueId(s);n!==s&&e(r.clone().setBlueId(n))}class Ki{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 s=It(e,this.blueIdMapper);return new Ui({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(s)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?xi(e.repositories):e.repositories;for(const[s,n]of Object.entries(r)){const o=this.registry.findRuntimeByName(s);if(!o)continue;const l=o.repoVersionIndexById[n];if(l===void 0)throw this.unknownRepoBlueIdError(s,n,o.currentRepoBlueId);t[s]=l}return t}unknownRepoBlueIdError(e,t,r){const s=`Unknown RepoBlueId '${t}' for repository '${e}'.`,n={code:x.REPO_UNKNOWN_REPO_BLUE_ID,message:s,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new he(x.REPO_UNKNOWN_REPO_BLUE_ID,s,[n])}}class be{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=$;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:s,repositories:n,mergingProcessor:o}=e;this.repositories=n,this.repositoryRegistry=new Bi(n??[]),this.blueContextResolver=new Ki({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry}),this.mergingProcessor=o??$e();const l=rt(()=>[]);this.nodeProvider=this.wrapNodeProviderWithRepositories(t||l,n),this.typeSchemaResolver=r??new gr([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.urlContentFetcher=new Ii(s),this.blueDirectivePreprocessor=new gi(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new Or,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const a=this.repositoryRegistry.getRuntimes().flatMap(c=>c.schemas);a.length>0&&this.typeSchemaResolver?.registerSchemas(a)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return v.get(s,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),s=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return ai.get(s,{strategy:r.format})}nodeToSchemaOutput(e,t){return new li(this.typeSchemaResolver,{calculateBlueId:s=>this.calculateBlueIdSync(s)}).convert(e,t)}resolve(e,t=$){const r=this.combineWithGlobalLimits(t),n=new oe(this.mergingProcessor,this.nodeProvider).resolve(e,r);if(!(r instanceof Y)){const o=this.getExactReferenceBlueId(e);o!==void 0&&n.setSourceSemanticBlueId(o)}return n}createResolvedNode(e){return e instanceof k?e:new k(e)}reverse(e){return this.minimize(e)}minimize(e){return new Re({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).minimize(e)}restoreInlineTypes(e){return new vi({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new Ot(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(m.deserialize(e));return It(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(m.deserialize(e));return It(t,this.repositoryRegistry)}yamlToNode(e){const t=ee(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}async yamlToNodeAsync(e){const t=ee(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNodeAsync(t)}prepareForBlueIdCalculation=async e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?await Promise.all(e.map(r=>this.jsonValueToNodeAsync(r))):this.jsonValueToNodeAsync(e);calculateBlueId=async e=>{const t=await this.prepareForBlueIdCalculation(e);return new Re({nodeProvider:this.nodeProvider,mergingProcessor:this.mergingProcessor}).calculateBlueId(t)};prepareForBlueIdCalculationSync=e=>e instanceof d||Array.isArray(e)&&e.every(t=>t instanceof d)?e:Array.isArray(e)?e.map(t=>this.jsonValueToNode(t)):this.jsonValueToNode(e);calculateBlueIdSync(e){const t=this.prepareForBlueIdCalculationSync(e);return new Re({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 De({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new De({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(!P.hasBlueIdOnly(e))return;const t=e.getReferenceBlueId();return t!==void 0&&Te.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()}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 U.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 s=e.getType();if(!s)return!1;const n=new d().setReferenceBlueId(r);return C(s,n,this.nodeProvider)}isTypeOfNode(e,t){return new Ls(this).matchesType(e,t,this.globalLimits)}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?_e.wrap(new Ir([new Vt(t,{mergingProcessor:this.mergingProcessor}),e])):_e.wrap(e)}combineWithGlobalLimits(e){return this.globalLimits==$?e:e==$?this.globalLimits:tt.of(this.globalLimits,e)}}const Hi=Object.freeze(Object.defineProperty({__proto__:null,Blue:be},Symbol.toStringTag,{value:"Module"})),ut=new WeakMap,ki=10;function Yi(i,e={}){const t=e.mergingProcessor===void 0;if(t){const a=ut.get(i);if(a)return a}const r=Mr(i);if(r.length===0)return t&&ut.set(i,i),i;const s=_r(i),n=e.mergingProcessor??$e();let o=Object.fromEntries(r.map(({oldBlueId:a})=>[a,a]));const l=Ji(r.length);for(let a=0;a<l;a++){const c=qi(r,s,o,n);if(tn(o,c)){const p=Xi(i,o);return t&&ut.set(i,p),p}o=c}throw new Error(`Repository semantic reindexing did not converge after ${l} passes for ${r.length} entries.`)}function Wi(i,e={}){const t=Mr(i);if(t.length===0)return;const r=_r(i),s=e.mergingProcessor??$e(),n=new be({nodeProvider:Zi(t,r),mergingProcessor:s});n.registerBlueIds(r);for(const{packageName:o,oldBlueId:l,content:a}of t){const c=Array.isArray(a)?a.map(f=>n.jsonValueToNode(f)):n.jsonValueToNode(a),p=n.calculateBlueIdSync(c);if(p!==l)throw new he(x.BLUE_ID_MISMATCH,`Repository content key '${l}' does not match semantic BlueId '${p}'.`,[{code:x.BLUE_ID_MISMATCH,message:"Repository contents must be keyed by the semantic BlueId of their minimal storage form.",context:{packageName:o,providedBlueId:l,computedBlueId:p}}])}}function Ji(i){return Math.max(ki,i+1)}function Mr(i){const e=[];for(const[t,r]of Object.entries(i.packages))for(const[s,n]of Object.entries(r.contents))e.push({packageName:t,oldBlueId:s,content:n});return e}function _r(i){const e={};for(const t of Object.values(i.packages))for(const[r,s]of Object.entries(t.aliases))e[r]=s;return e}function Zi(i,e){const t=new Map(i.map(({oldBlueId:n,content:o})=>[n,o])),r=new Map(Object.entries(e)),s=new be;return{fetchByBlueId(n){const o=Gi(n,r);if(o===void 0)return[];const{baseBlueId:l,suffix:a}=Tt(o),c=t.get(l);if(c===void 0)return[];const p=Array.isArray(c),f=Ie.resolveThisReferences(c,l,p);if(a!==void 0){const y=Number(a.slice(1));if(Array.isArray(f)){const g=f[y];return g===void 0?[]:[s.jsonValueToNode(g)]}return y===0?[s.jsonValueToNode(f)]:[]}return Array.isArray(f)?f.map(y=>s.jsonValueToNode(y)):[s.jsonValueToNode(f)]},fetchFirstByBlueId(n){return this.fetchByBlueId(n)[0]??null}}}function Gi(i,e){const t=e.get(i);if(t!==void 0)return t;const{baseBlueId:r,suffix:s}=Tt(i);if(s===void 0)return i;const n=e.get(r);if(n===void 0)return i;if(Tt(n).suffix===void 0)return`${n}${s}`}function Tt(i){const e=i.indexOf("#");return e===-1?{baseBlueId:i}:{baseBlueId:i.slice(0,e),suffix:i.slice(e)}}function qi(i,e,t,r){const s=new Map(i.map(({oldBlueId:c,content:p})=>[c,Ze(p,t)])),n=new Map;for(const{oldBlueId:c}of i)n.set(c,c),n.set(t[c],c);const o=new be,l={fetchByBlueId(c){const[p,f]=c.split("#"),y=n.get(p);if(!y)return[];const g=s.get(y);if(g===void 0)return[];if(Array.isArray(g)){if(f!==void 0){const I=g[Number(f)];return I===void 0?[]:[o.jsonValueToNode(I)]}return g.map(I=>o.jsonValueToNode(I))}return f!==void 0&&f!=="0"?[]:[o.jsonValueToNode(g)]},fetchFirstByBlueId(c){return this.fetchByBlueId(c)[0]??null}},a=new be({nodeProvider:l,mergingProcessor:r});return a.registerBlueIds(Dr(e,t)),Object.fromEntries(i.map(({packageName:c,oldBlueId:p})=>{const f=s.get(p);if(f===void 0)throw new Error(`Missing repository content for ${p}.`);try{const y=a.jsonValueToNode(f);return[p,a.calculateBlueIdSync(y)]}catch(y){const g=y instanceof Error?y.message:String(y);throw new Error(`Failed to calculate semantic BlueId for ${c}/${p}: ${g}`)}}))}function Xi(i,e){return{name:i.name,repositoryVersions:i.repositoryVersions,packages:Object.fromEntries(Object.entries(i.packages).map(([t,r])=>[t,Qi(r,e)]))}}function Qi(i,e){return{name:i.name,aliases:Dr(i.aliases,e),typesMeta:Object.fromEntries(Object.entries(i.typesMeta).map(([t,r])=>[e[t]??t,en(r,e)])),contents:Object.fromEntries(Object.entries(i.contents).map(([t,r])=>[e[t]??t,Ze(r,e)])),schemas:Object.fromEntries(Object.entries(i.schemas).map(([t,r])=>{const s=e[t]??t;return[s,pr(s)(r)]}))}}function en(i,e){return{...i,versions:i.versions.map(t=>({...t,typeBlueId:Mt(t.typeBlueId,e)}))}}function tn(i,e){const t=Object.keys(i);return t.length!==Object.keys(e).length?!1:t.every(r=>i[r]===e[r])}function Dr(i,e){return Object.fromEntries(Object.entries(i).map(([t,r])=>[t,Mt(r,e)]))}function Ze(i,e){return Array.isArray(i)?i.map(t=>Ze(t,e)):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([t,r])=>[t,t==="blueId"&&typeof r=="string"?Mt(r,e):Ze(r,e)])):i}function Mt(i,e){const t=e[i];if(t!==void 0)return t;const r=/^(.*)(#\d+)$/.exec(i);if(!r)return i;const[,s,n]=r;return`${e[s]??s}${n}`}class rn extends Vr{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;storageService;constructor(e=[]){super();const t=new De({nodeProvider:this});this.preprocessor=r=>t.preprocessWithDefaultBlue(r),this.storageService=new Js({nodeProvider:this}),e.forEach(r=>this.processNode(r))}processNode(e){P.hasItemsOnly(e)?this.processNodeWithItems(e):this.processSingleNode(e)}processSingleNode(e){const t=Ie.parseAndCalculateBlueIdForNode(e,this.preprocessor,this.storageService);this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,t.isMultipleDocuments);const r=e.getName();r&&this.addToNameMap(r,t.blueId)}processNodeWithItems(e){const t=e.getItems();if(!t)return;const r=this.storeNodeList(t);this.addListItemNames(r.blueId,r.content)}processNodeList(e){this.storeNodeList(e)}storeNodeList(e){const t=Ie.parseAndCalculateBlueIdForNodeList(e,this.preprocessor,this.storageService);return this.blueIdToContentMap.set(t.blueId,t.content),this.blueIdToMultipleDocumentsMap.set(t.blueId,!0),t}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?Ie.resolveThisReferences(t,e,r):null}addSingleNodes(...e){e.forEach(t=>this.processNode(t))}addSingleDocs(...e){e.forEach(t=>{const r=ee(t);if(r!==void 0){const s=m.deserialize(r);this.processNode(s)}})}getBlueIdByName(e){const t=this.nameToBlueIdsMap.get(e);if(!t||t.length===0)throw new Error(`No node with name "${e}"`);return t[0]}getNodeByName(e){const t=this.findNodeByName(e);if(!t)throw new Error(`No node with name "${e}"`);return t}addListAndItsItemsFromNodes(e){const t=this.storeNodeList(e);if(j.hasThisReference(e)){this.addListItemNames(t.blueId,t.content);return}e.forEach(r=>this.processNode(r))}addListAndItsItemsFromDoc(e){const t=ee(e);if(t!==void 0){const s=m.deserialize(t).getItems();s&&this.addListAndItsItems(s)}}addListAndItsItems(e){Array.isArray(e)?this.addListAndItsItemsFromNodes(e):this.addListAndItsItemsFromDoc(e)}addList(e){this.processNodeList(e)}addListItemNames(e,t){Array.isArray(t)&&t.forEach((r,s)=>{const o=m.deserialize(r).getName();o&&this.addToNameMap(o,`${e}#${s}`)})}}exports.Base58Sha256Provider=Xt;exports.BasicNodeProvider=rn;exports.Blue=be;exports.BlueIdCalculator=A;exports.BlueIdToCid=cs;exports.BlueNode=d;exports.BlueNodeTypeSchema=U;exports.JsonCanonicalizer=ke;exports.Limits=Qe;exports.Merger=oe;exports.MergingProcessors=Ws;exports.NodeResolver=mr;exports.Nodes=P;exports.Properties=Fr;exports.ResolvedBlueNode=k;exports.SemanticIdentityService=Re;exports.TypeSchemaResolver=gr;exports.applyBlueNodePatch=Ts;exports.baseBlueObjectSchema=je;exports.blueDescriptionField=Bs;exports.blueIdField=Ns;exports.blueIdSchema=Ur;exports.blueNameField=Ps;exports.blueNodeField=Ss;exports.blueObjectBooleanValueSchema=kr;exports.blueObjectNumberValueSchema=Hr;exports.blueObjectSchema=ve;exports.blueObjectStringListItemsSchema=Yr;exports.blueObjectStringValueSchema=Kr;exports.createNodeProvider=rt;exports.enrichWithBlueId=gt;exports.getBlueDescriptionAnnotation=nr;exports.getBlueIdAnnotation=lr;exports.getBlueNameAnnotation=cr;exports.getBlueNodeAnnotation=dr;exports.getBlueObjectItems=ci;exports.getBlueObjectProperties=di;exports.getBlueObjectTypeLabel=hi;exports.getBlueObjectValue=ui;exports.getTypeBlueIdAnnotation=hr;exports.hasBlueObjectBlueIdDefined=Jt;exports.hasBlueObjectItemsDefined=Zt;exports.hasBlueObjectNameDefined=Jr;exports.hasBlueObjectTypeDefined=Gt;exports.hasBlueObjectValueDefined=qt;exports.isBigDecimalNumber=He;exports.isBigIntegerNumber=Q;exports.isBigNumber=E;exports.isBlueNodeSchema=Rt;exports.isBlueObject=Wr;exports.isBlueObjectResolved=Ar;exports.isGivenBlueObjectTypeSchema=Zr;exports.isJsonBlueArray=St;exports.isJsonBlueObject=Pt;exports.isJsonBlueValue=Xr;exports.isUrl=Ae;exports.jsonBlueValueSchema=Ve;exports.normalizeToBlueObject=pi;exports.reindexRepositoryForSemanticStorage=Yi;exports.resolveBlueObjectItems=mt;exports.validateRepositorySemanticStorage=Wi;exports.withBlueDescription=ir;exports.withBlueId=or;exports.withBlueName=ar;exports.withBlueNode=ur;exports.withTypeBlueId=pr;exports.yamlBlueDump=vr;exports.yamlBlueParse=ee;