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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +27 -6
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +8 -8
  5. package/dist/index.mjs +4736 -3268
  6. package/dist/lib/Blue.d.ts +14 -4
  7. package/dist/lib/Blue.d.ts.map +1 -1
  8. package/dist/lib/errors/BlueError.d.ts +3 -0
  9. package/dist/lib/errors/BlueError.d.ts.map +1 -1
  10. package/dist/lib/identity/BlueIdHasher.d.ts +39 -0
  11. package/dist/lib/identity/BlueIdHasher.d.ts.map +1 -0
  12. package/dist/lib/identity/CyclicSetIdentityService.d.ts +35 -0
  13. package/dist/lib/identity/CyclicSetIdentityService.d.ts.map +1 -0
  14. package/dist/lib/identity/SemanticIdentityService.d.ts +40 -0
  15. package/dist/lib/identity/SemanticIdentityService.d.ts.map +1 -0
  16. package/dist/lib/identity/SemanticStorageService.d.ts +29 -0
  17. package/dist/lib/identity/SemanticStorageService.d.ts.map +1 -0
  18. package/dist/lib/identity/index.d.ts +5 -0
  19. package/dist/lib/identity/index.d.ts.map +1 -0
  20. package/dist/lib/index.d.ts +2 -0
  21. package/dist/lib/index.d.ts.map +1 -1
  22. package/dist/lib/mapping/ComplexObjectConverter.d.ts +2 -1
  23. package/dist/lib/mapping/ComplexObjectConverter.d.ts.map +1 -1
  24. package/dist/lib/mapping/ConverterFactory.d.ts +2 -1
  25. package/dist/lib/mapping/ConverterFactory.d.ts.map +1 -1
  26. package/dist/lib/mapping/NodeToObjectConverter.d.ts +6 -2
  27. package/dist/lib/mapping/NodeToObjectConverter.d.ts.map +1 -1
  28. package/dist/lib/merge/Merger.d.ts +13 -10
  29. package/dist/lib/merge/Merger.d.ts.map +1 -1
  30. package/dist/lib/model/Node.d.ts +10 -0
  31. package/dist/lib/model/Node.d.ts.map +1 -1
  32. package/dist/lib/model/ResolvedNode.d.ts +17 -1
  33. package/dist/lib/model/ResolvedNode.d.ts.map +1 -1
  34. package/dist/lib/preprocess/Preprocessor.d.ts +7 -1
  35. package/dist/lib/preprocess/Preprocessor.d.ts.map +1 -1
  36. package/dist/lib/provider/AbstractNodeProvider.d.ts.map +1 -1
  37. package/dist/lib/provider/BasicNodeProvider.d.ts +3 -0
  38. package/dist/lib/provider/BasicNodeProvider.d.ts.map +1 -1
  39. package/dist/lib/provider/InMemoryNodeProvider.d.ts +6 -0
  40. package/dist/lib/provider/InMemoryNodeProvider.d.ts.map +1 -1
  41. package/dist/lib/provider/NodeContentHandler.d.ts +18 -4
  42. package/dist/lib/provider/NodeContentHandler.d.ts.map +1 -1
  43. package/dist/lib/provider/RepositoryBasedNodeProvider.d.ts +16 -1
  44. package/dist/lib/provider/RepositoryBasedNodeProvider.d.ts.map +1 -1
  45. package/dist/lib/repository/RepositoryRuntime.d.ts.map +1 -1
  46. package/dist/lib/repository/SemanticRepositoryReindexer.d.ts +11 -0
  47. package/dist/lib/repository/SemanticRepositoryReindexer.d.ts.map +1 -0
  48. package/dist/lib/utils/BlueIdCalculator.d.ts +4 -9
  49. package/dist/lib/utils/BlueIdCalculator.d.ts.map +1 -1
  50. package/dist/lib/utils/ListControls.d.ts +27 -0
  51. package/dist/lib/utils/ListControls.d.ts.map +1 -0
  52. package/dist/lib/utils/MergeReverser.d.ts +30 -0
  53. package/dist/lib/utils/MergeReverser.d.ts.map +1 -1
  54. package/dist/lib/utils/Minimizer.d.ts +18 -0
  55. package/dist/lib/utils/Minimizer.d.ts.map +1 -0
  56. package/dist/lib/utils/NodeExtender.d.ts +1 -1
  57. package/dist/lib/utils/NodeExtender.d.ts.map +1 -1
  58. package/dist/lib/utils/NodeProviderWrapper.d.ts +3 -5
  59. package/dist/lib/utils/NodeProviderWrapper.d.ts.map +1 -1
  60. package/dist/lib/utils/NodeToMapListOrValue.d.ts +5 -1
  61. package/dist/lib/utils/NodeToMapListOrValue.d.ts.map +1 -1
  62. package/dist/lib/utils/NodeTypeMatcher.d.ts +3 -0
  63. package/dist/lib/utils/NodeTypeMatcher.d.ts.map +1 -1
  64. package/dist/lib/utils/NodeTypes.d.ts +6 -0
  65. package/dist/lib/utils/NodeTypes.d.ts.map +1 -1
  66. package/dist/lib/utils/StorageShapeValidator.d.ts +17 -0
  67. package/dist/lib/utils/StorageShapeValidator.d.ts.map +1 -0
  68. package/dist/lib/utils/TypeSchema.d.ts +2 -0
  69. package/dist/lib/utils/TypeSchema.d.ts.map +1 -1
  70. package/dist/lib/utils/index.d.ts +2 -0
  71. package/dist/lib/utils/index.d.ts.map +1 -1
  72. package/dist/utils/blueObject/enrichWithBlueId.d.ts.map +1 -1
  73. package/dist/utils/index.d.ts +0 -1
  74. package/dist/utils/index.d.ts.map +1 -1
  75. package/package.json +3 -3
  76. package/dist/utils/blueId/calculateBlueId.d.ts +0 -15
  77. package/dist/utils/blueId/calculateBlueId.d.ts.map +0 -1
  78. package/dist/utils/blueId/index.d.ts +0 -2
  79. package/dist/utils/blueId/index.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("big.js"),u=require("@blue-labs/shared-utils"),c=require("zod"),pr=require("bs58"),M=require("radash"),v=require("@blue-labs/repository-contract"),hr=require("js-sha256"),fr=require("crypto"),yr=require("base32.js"),te=require("js-yaml"),vt=s=>s&&s.__esModule?s:{default:s},de=vt(pr),Ue=vt(fr);class A extends U{constructor(e){super(e)}}class S extends U{constructor(e){super(e)}}const q="name",X="description",Q="type",ye="itemType",ge="keyType",me="valueType",Ie="value",Me="items",z="blueId",De="blue",et=[q,X,Q,ye,ge,me,Ie,Me,z,De],Nt="Text",Bt="Double",wt="Integer",Et="Boolean",St="List",Pt="Dictionary",xe=[Nt,Bt,wt,Et],tt=[...xe,St,Pt],Y="DLRQwz7MQeCrzjy9bohPNwtCxKEBbKaMK65KBrwjfG6K",J="7pwXmXYCJtWnd348c2JQGBkm9C4renmZRwxbfaypsx5y",Z="5WNMiV9Knz63B4dVY5JtMyh3FB4FSGqv7ceScvuapdE1",G="4EzhSubEimSQD3zrYHRtobfPPWntUuhEz8YcdxHsi12u",rt="6aehfNAxHLC1PHHoDr3tYtFH3RWNbiWdFancJ1bypXEY",st="G7fBT9PSod1RfHLHkpafAGBDVAJMrMhAMY51ERcyXNrj",nt=[Y,J,Z,G],re=[...nt,rt,st],gr=Object.fromEntries(tt.map((s,e)=>[s,re[e]])),_e=Object.fromEntries(re.map((s,e)=>[s,tt[e]])),mr=Object.freeze(Object.defineProperty({__proto__:null,BASIC_TYPES:xe,BASIC_TYPE_BLUE_IDS:nt,BOOLEAN_TYPE:Et,BOOLEAN_TYPE_BLUE_ID:G,CORE_TYPES:tt,CORE_TYPE_BLUE_IDS:re,CORE_TYPE_BLUE_ID_TO_NAME_MAP:_e,CORE_TYPE_NAME_TO_BLUE_ID_MAP:gr,DICTIONARY_TYPE:Pt,DICTIONARY_TYPE_BLUE_ID:st,DOUBLE_TYPE:Bt,DOUBLE_TYPE_BLUE_ID:J,INTEGER_TYPE:wt,INTEGER_TYPE_BLUE_ID:Z,LIST_TYPE:St,LIST_TYPE_BLUE_ID:rt,OBJECT_BLUE:De,OBJECT_BLUE_ID:z,OBJECT_CONTRACTS:v.OBJECT_CONTRACTS,OBJECT_DESCRIPTION:X,OBJECT_ITEMS:Me,OBJECT_ITEM_TYPE:ye,OBJECT_KEY_TYPE:ge,OBJECT_MERGE_POLICY:v.OBJECT_MERGE_POLICY,OBJECT_NAME:q,OBJECT_SCHEMA:v.OBJECT_SCHEMA,OBJECT_SPECIFIC_KEYS:et,OBJECT_TYPE:Q,OBJECT_VALUE:Ie,OBJECT_VALUE_TYPE:me,TEXT_TYPE:Nt,TEXT_TYPE_BLUE_ID:Y},Symbol.toStringTag,{value:"Module"}));class Ir{static get(e,t,r,n=!0){if(u.isNullable(t)||!t.startsWith("/"))throw new Error(`Invalid path: ${t}`);if(t==="/"){const o=e.getValue();return n&&o!==void 0?o:e}const i=t.substring(1).split("/");return this.getRecursive(e,i,0,r,n)}static getRecursive(e,t,r,n,i){if(r===t.length-1&&!i)return this.getNodeForSegment(e,t[r],n,!1);if(r===t.length){const a=e.getValue();return i&&a!==void 0?a:e}const o=t[r],l=this.getNodeForSegment(e,o,n,!0);if(l)return this.getRecursive(l,t,r+1,n,i)}static getNodeForSegment(e,t,r,n){let i;const o=e.getProperties();if(o&&t in o)i=o[t];else switch(t){case"name":{const l=e.getName();i=new d().setValue(l??null);break}case"description":{const l=e.getDescription();i=new d().setValue(l??null);break}case"type":i=e.getType();break;case"itemType":i=e.getItemType();break;case"keyType":i=e.getKeyType();break;case"valueType":i=e.getValueType();break;case"value":{const l=e.getValue();i=new d().setValue(l??null);break}case"blueId":{const l=e.getBlueId();i=new d().setValue(l??null);break}case"blue":i=e.getBlue();break;case"items":{const l=e.getItems();i=new d().setItems(l);break}case"properties":{const l=e.getProperties();i=new d().setProperties(l);break}case v.OBJECT_CONTRACTS:{const l=e.getContracts();i=new d().setContracts(l);break}default:{if(/^\d+$/.test(t)){const l=parseInt(t,10),a=e.getItems();a&&l>=0&&l<a.length?i=a[l]:i=void 0}else i=void 0;break}}if(i)return n&&r?this.link(i,r):i}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===Z&&typeof this.value=="string")return new S(this.value);if(e===J&&typeof this.value=="string"){const t=new A(this.value),r=parseFloat(t.toString());return new A(r.toString())}else if(e===G&&typeof this.value=="string")return this.value.toLowerCase()==="true"}return this.value}setValue(e){return typeof e=="number"?e%1===0?this.value=new S(e.toString()):this.value=new A(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?.[v.OBJECT_CONTRACTS]}getContracts(){return this.getContractsProperty()?.getProperties()}setContracts(e){return u.isNullable(e)?this.removeProperty(v.OBJECT_CONTRACTS):this.addProperty(v.OBJECT_CONTRACTS,new d().setProperties(e)),this}addContract(e,t){const r=this.getContractsProperty();return u.isNullable(r)?this.addProperty(v.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(v.OBJECT_CONTRACTS)}return this}getBlueId(){return this.blueId}setBlueId(e){return this.blueId=e,this}getBlue(){return this.blue}setBlue(e){return this.blue=e,this}isInlineValue(){return this.inlineValue}setInlineValue(e){return this.inlineValue=e,this}isResolved(){return!1}get(e,t){return Ir.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 S||t instanceof A)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 Pe{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],n=r.length;if(n<this.MIN_BLUE_ID_LENGTH||n>this.MAX_BLUE_ID_LENGTH)return!1;try{if(de.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 Tr=c.z.string().max(Pe.MAX_BLUE_ID_LENGTH,{message:"Blue Id has a maximum length of 45 characters"}).min(Pe.MIN_BLUE_ID_LENGTH,{message:"Blue Id has a minimum length of 41 characters"}).refine(s=>{try{return de.default.decode(s),!0}catch{return!1}},{message:"Blue Id must be a valid Base58 string"}),ne=c.z.lazy(()=>c.z.record(c.z.unknown()).and(c.z.object({blueId:c.z.string().optional(),name:c.z.string().optional(),description:c.z.string().optional(),type:ne.optional(),value:c.z.union([c.z.string(),c.z.number(),c.z.boolean()]).optional().nullable(),items:c.z.array(ne).optional()}))),Te=c.z.object({blueId:c.z.string().optional(),name:c.z.string().optional(),description:c.z.string().optional(),type:ne.optional()}),br=Te.extend({value:c.z.string().optional()}),vr=Te.extend({value:c.z.number().optional()}),Nr=Te.extend({value:c.z.boolean().optional()}),Br=Te.extend({items:c.z.array(c.z.string()).optional()}),wr=s=>ne.safeParse(s).success,Ct=s=>u.isNonNullable(s)&&"blueId"in s&&u.isNonNullable(s.blueId),Er=s=>u.isNonNullable(s)&&"name"in s&&u.isNonNullable(s.name),At=s=>u.isNonNullable(s)&&"items"in s&&u.isNonNullable(s.items),Rt=s=>u.isNonNullable(s)&&"type"in s&&u.isNonNullable(s.type),Vt=s=>u.isNonNullable(s)&&"value"in s&&u.isNonNullable(s.value),Sr=(s,e)=>s.required({type:!0}).safeParse(e).success,R=s=>s instanceof U,k=s=>R(s)&&s instanceof S,Ce=s=>R(s)&&s instanceof A,Pr=c.z.lazy(()=>c.z.record(pe)),Cr=c.z.lazy(()=>c.z.union([c.z.array(pe),c.z.array(pe).readonly()])),pe=c.z.lazy(()=>c.z.union([u.jsonPrimitiveSchema,Pr,Cr,c.z.instanceof(U)])),it=s=>M.isObject(s)&&!M.isArray(s)&&!u.isReadonlyArray(s)&&!R(s),ot=s=>M.isArray(s)||u.isReadonlyArray(s),Ar=s=>ot(s)||it(s)||R(s)||u.isJsonPrimitive(s);class y{static deserialize(e){return y.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(it(e)){const t=new d,r={};return Object.entries(e).forEach(([n,i])=>{switch(n){case q:if(i==null)t.setName(void 0);else{if(typeof i!="string")throw new Error(`The ${q} field must be a string.`);t.setName(i)}break;case X:if(i==null)t.setDescription(void 0);else{if(typeof i!="string")throw new Error(`The ${X} field must be a string.`);t.setDescription(i)}break;case Q:t.setType(y.handleNode(i));break;case ye:t.setItemType(y.handleNode(i));break;case ge:t.setKeyType(y.handleNode(i));break;case me:t.setValueType(y.handleNode(i));break;case Ie:t.setValue(y.handleValue(i));break;case z:if(typeof i!="string")throw new Error(`The ${z} field must be a string.`);t.setBlueId(i);break;case Me:t.setItems(y.handleArray(i));break;case De:t.setBlue(y.handleNode(i));break;default:r[n]=y.handleNode(i);break}}),Object.keys(r).length>0&&t.setProperties(r),t}else{if(ot(e))return new d().setItems(y.handleArray(e));{const t=e;return new d().setValue(y.handleValue(t)).setInlineValue(!0)}}}static handleValue(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||R(e))if(k(e)||Number.isSafeInteger(e)){const t=new S(e.toString()),r=Number.MIN_SAFE_INTEGER,n=Number.MAX_SAFE_INTEGER;return t.lt(r)?new S(r.toString()):t.gt(n)?new S(n.toString()):t}else{const t=parseFloat(e.toString());return new A(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(M.isObject(e)&&!Array.isArray(e))return[y.handleNode(e)];if(Array.isArray(e))return e.map(y.handleNode);throw new Error("Expected an array node")}}}function Rr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var ze,yt;function Vr(){return yt||(yt=1,ze=function s(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?s(e.toJSON()):Array.isArray(e)?`[${e.reduce((n,i,o)=>`${n}${o===0?"":","}${s(i===void 0||typeof i=="symbol"?null:i)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,n)=>{if(e[n]===void 0||typeof e[n]=="symbol")return r;const i=r.length===0?"":",";return`${r}${i}${s(n)}:${s(e[n])}`},"")}}`}),ze}var Or=Vr();const Mr=Rr(Or);class Ae{static canonicalize(e){return Mr(e)}}const ke=typeof process<"u"&&process.versions!=null&&process.versions.node!=null;class lt{static instance;browserCrypto;constructor(){this.browserCrypto=this.initBrowserCrypto()}static getInstance(){return this.instance||(this.instance=new lt),this.instance}initBrowserCrypto(){return ke?null:"crypto"in globalThis?globalThis.crypto:null}hasNodeCrypto(){return ke&&!!Ue.default&&typeof Ue.default.createHash=="function"}getBrowserCrypto(){return this.browserCrypto}getNodeCrypto(){return ke?Ue.default:null}}class Ot{cryptoEnv=lt.getInstance();applySync(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):this.sha256SyncBrowser(t);return de.default.encode(r)}async apply(e){const t=this.canonicalizeInput(e),r=this.cryptoEnv.hasNodeCrypto()?this.sha256Sync(t):await this.sha256Async(t);return de.default.encode(r)}canonicalizeInput(e){const t=Ae.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(hr.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 n=new TextEncoder().encode(e),i=await t.subtle.digest("SHA-256",n);return new Uint8Array(i)}}class m{static get(e,t="official"){const r=e.getValue(),n=this.handleValue(r);if(n!==void 0&&t==="simple")return n;const i=e.getItems()?.map(_=>m.get(_,t));if(i!==void 0&&t==="simple")return i;const o=e.getName(),l=e.getDescription();if(t==="original"&&o===void 0&&l===void 0){if(n!==void 0)return n;if(i!==void 0)return i}const a={};o!==void 0&&(a[q]=o),l!==void 0&&(a[X]=l);const p=e.getType();if(t==="official"&&r!==void 0&&p===void 0){const _=this.inferTypeBlueId(r);_!==null&&(a[Q]={[z]:_})}else p!==void 0&&(a[Q]=m.get(p,t));const f=e.getItemType();f!==void 0&&(a[ye]=m.get(f,t));const h=e.getKeyType();h!==void 0&&(a[ge]=m.get(h,t));const g=e.getValueType();g!==void 0&&(a[me]=m.get(g,t)),n!==void 0&&(a[Ie]=n),i!==void 0&&(a[Me]=i);const T=e.getBlueId();T!==void 0&&(a[z]=T);const x=e.getBlue();x!==void 0&&(a[De]=x);const V=e.getProperties();return V!==void 0&&Object.entries(V).forEach(([_,b])=>{a[_]=m.get(b,t)}),a}static handleValue(e){if(R(e)){if(k(e)){const t=new U(Number.MIN_SAFE_INTEGER.toString()),r=new U(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"?Y:R(e)?k(e)?Z:J:typeof e=="boolean"?G:null}}const Dr=s=>u.isJsonPrimitive(s)&&u.isNonNullable(s);class I{static INSTANCE=new I(new Ot);hashProvider;constructor(e){this.hashProvider=e}static calculateBlueId(e){if(Array.isArray(e)){const r=e.map(n=>m.get(n));return I.INSTANCE.calculate(r)}const t=m.get(e);return I.INSTANCE.calculate(t)}static calculateBlueIdSync(e){if(Array.isArray(e)){const r=e.map(n=>m.get(n));return I.INSTANCE.calculateSync(r)}const t=m.get(e);return I.INSTANCE.calculateSync(t)}calculate(e){const t=this.cleanStructure(e);if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.internalCalculate(t,!1)}calculateSync(e){const t=this.cleanStructure(e);if(t===void 0)throw new Error("Object after cleaning cannot be null or undefined.");return this.internalCalculate(t,!0)}internalCalculate(e,t){return Dr(e)||R(e)?this.applyHash(e.toString(),t):Array.isArray(e)||u.isReadonlyArray(e)?this.calculateList(e,t):this.calculateMap(e,t)}calculateMap(e,t){if(e[z]!==void 0)return e[z];const n=Object.keys(e).map(o=>{const l=e[o];if([q,Ie,X].includes(o))return t?[o,l]:Promise.resolve([o,l]);{const a=this.internalCalculate(l,t);return t?[o,{blueId:a}]:Promise.resolve(a).then(p=>[o,{blueId:p}])}}),i=o=>{const l={};for(const[a,p]of o)l[a]=p;return this.applyHash(l,t)};return t?i(n):Promise.all(n).then(i)}calculateList(e,t){if(e.length===0)throw new Error("Cannot calculate BlueId for an empty list.");let r=this.internalCalculate(e[0],t);const n=(i,o)=>t?this.applyHash([{blueId:i},{blueId:o}],!0):Promise.all([i,o]).then(([l,a])=>this.applyHash([{blueId:l},{blueId:a}],!1));for(let i=1;i<e.length;i++){const o=this.internalCalculate(e[i],t);r=n(r,o)}return r}applyHash(e,t){return t?this.hashProvider.applySync(e):this.hashProvider.apply(e)}cleanStructure(e){if(e!=null){if(u.isJsonPrimitive(e)||R(e))return e;if(Array.isArray(e)||u.isReadonlyArray(e)){const t=e.map(r=>this.cleanStructure(r)).filter(u.isNonNullable);return t.length>0?t:void 0}else if(typeof e=="object"){const t={};for(const r in e){const n=this.cleanStructure(e[r]);n!=null&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}else return e}}}class xr{static convert(e){const t=de.default.decode(e),r=new Uint8Array(2+t.length);r[0]=18,r[1]=32,r.set(t,2);const n=new Uint8Array(2+r.length);return n[0]=1,n[1]=85,n.set(r,2),"b"+new yr.Encoder({type:"rfc4648",lc:!0}).write(n).finalize().replace(/=/g,"")}}class E{static transform(e,t){const r=t(e.clone()),n=r.getType();n!==void 0&&r.setType(E.transform(n,t));const i=r.getItemType();i!==void 0&&r.setItemType(E.transform(i,t));const o=r.getKeyType();o!==void 0&&r.setKeyType(E.transform(o,t));const l=r.getValueType();l!==void 0&&r.setValueType(E.transform(l,t));const a=r.getItems();if(a!==void 0){const f=a.map(h=>E.transform(h,t));r.setItems(f)}const p=r.getProperties();if(p!==void 0){const f=Object.keys(p).reduce((h,g)=>(h[g]=E.transform(p[g],t),h),{});r.setProperties(f)}return r}}const K=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof d),F=s=>s instanceof S||s instanceof A,_r=s=>s.replace(/~1/g,"/").replace(/~0/g,"~");function le(s){if(s==="/")return[];if(!s.startsWith("/"))throw new Error(`Path must start with '/': ${s}`);return s.split("/").slice(1).map(_r)}function ie(s){if(s==="-")return-1;const e=typeof s=="number"?s:parseInt(s,10);if(isNaN(e))throw new Error(`Invalid array index (NaN) from '${s}'`);if(!Number.isFinite(e))throw new Error(`Invalid array index '${s}' results in non-finite number ${e}`);return e}function Mt(s,e,t,r=!0){switch(e){case"name":return t?r?s.getName()??null:s:s.getName();case"description":return t?r?s.getDescription():s:s.getDescription();case"type":return s.getType();case"itemType":return s.getItemType();case"keyType":return s.getKeyType();case"valueType":return s.getValueType();case"value":return t?r?s.getValue()??null:s:s.getValue();case"blueId":return t?r?s.getBlueId()??null:s:s.getBlueId();case"blue":return s.getBlue();case"items":return s.getItems();case"properties":return s.getProperties();case v.OBJECT_CONTRACTS:return s.getContracts();default:return}}function gt(s,e,t=!0){if(s instanceof d){const r=Mt(s,e,!0,t);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",v.OBJECT_CONTRACTS].includes(e))return r;if(/^-?\d+$/.test(e)&&e!=="-"){const i=s.getItems(),o=parseInt(e,10);return i&&o>=0&&o<i.length?i[o]:void 0}const n=s.getProperties();return n&&e in n?n[e]:void 0}if(Array.isArray(s)){if(e==="-")return;const r=ie(e);return r>=0&&r<s.length?s[r]:void 0}if(K(s))return s[e]}function ae(s,e){if(e.length===0)return{parent:s,key:"value",actualTarget:s.getValue()??s};let t=s;for(let n=0;n<e.length-1;++n){const i=e[n],o=gt(t,i);if(o===void 0)throw new Error(`Cannot resolve '/${e.slice(0,n+1).join("/")}'`);t=o}const r=e[e.length-1];if(t instanceof d){const n=gt(t,r,!1);if((typeof n!="object"||n===null||F(n))&&!(n instanceof d)&&!Array.isArray(n)&&["name","description","value","blueId"].includes(r))return{parent:t,key:r,actualTarget:n}}return Array.isArray(t)&&r==="-"?{parent:t,key:"-"}:t instanceof d&&t.getItems()&&r==="-"?{parent:t,key:"-"}:{parent:t,key:Array.isArray(t)?ie(r):r}}function at(s,e){if(s instanceof d){const t=e,r=Mt(s,t,!1);if(r!==void 0||["name","description","type","itemType","keyType","valueType","value","blueId","blue","items","properties",v.OBJECT_CONTRACTS].includes(t))return r;if(typeof e=="number"||typeof e=="string"&&/^\d+$/.test(e)){const n=s.getItems(),i=typeof e=="number"?e:parseInt(e,10);if(n&&i>=0&&i<n.length)return n[i]}return s.getProperties()?.[t]}return Array.isArray(s)||K(s)?s[e]:s}function C(s){if(s instanceof d)return s;if(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean"||F(s))return y.deserialize(s);const e=Ge(s);return y.deserialize(e)}function Ge(s){if(s===void 0)return null;if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(Ge);const e={};for(const[t,r]of Object.entries(s))e[t]=Ge(r);return e}function ut(s,e,t){if(s instanceof d){const r=e;switch(r){case"name":s.setName(t);return;case"description":s.setDescription(t);return;case"type":s.setType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"itemType":s.setItemType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"keyType":s.setKeyType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"valueType":s.setValueType(t instanceof d||typeof t=="string"||t===void 0?t:C(t));return;case"value":{const n=t;s.setValue(n===void 0?null:n);return}case"blueId":s.setBlueId(t);return;case"blue":s.setBlue(t instanceof d||t===void 0?t:C(t));return;case"items":s.setItems(t);return;case"properties":s.setProperties(t);return;case v.OBJECT_CONTRACTS:s.setContracts(t);return;default:{if(t===void 0){const n=s.getProperties();n&&r in n&&delete n[r]}else s.getProperties()||s.setProperties({}),s.addProperty(r,t instanceof d?t:C(t));return}}}Array.isArray(s)?s.splice(ie(e),1):K(s)&&(t===void 0?delete s[e]:s[e]=t)}function Fr(s,e,t,r){let n=-1;if(e!=="-"&&(n=typeof e=="number"?e:parseInt(e,10),isNaN(n)))throw new Error(`Invalid numeric key for BlueNode item operation: ${e}`);if(n<-1)throw new Error(`Invalid array index for BlueNode items: ${n}`);let i=s.getItems();if(i||(i=[],s.setItems(i)),!r&&n!==-1&&n>i.length)throw new Error(`ADD operation failed: Target array index '${n}' is greater than array length ${i.length}.`);if(e==="-")i.push(t);else if(r){if(n>=0)if(n<i.length)i[n]=t;else{for(let o=i.length;o<n;o++)i.push(y.deserialize(null));i.push(t)}}else i.splice(n,0,t)}function Re(s,e,t,r){if(Array.isArray(s)){const n=e==="-"?s.length:ie(e);if(!r&&n>s.length)throw new Error(`ADD operation failed: Target array index '${n}' is greater than array length ${s.length}. Path involving key '${e}'.`);if(n<0&&e!=="-")throw new Error(`Invalid negative array index: ${e}`);const i=C(t);if(r){if(n>=0&&n<s.length)s[n]=i;else if(n>=s.length){for(let o=s.length;o<n;o++)s.push(y.deserialize(null));s.push(i)}}else s.splice(n,0,i);return}if(s instanceof d){e==="-"||typeof e=="number"&&!isNaN(e)||typeof e=="string"&&/^\d+$/.test(e)?Fr(s,e,C(t),r):ut(s,e,t);return}if(K(s)){s[e]=C(t);return}throw new Error(`Cannot insert into parent of type ${typeof s}`)}function $r(s,e){if(Array.isArray(s)){const t=ie(e);t===-1&&e==="-"?s.length>0&&s.pop():t>=0&&t<s.length&&s.splice(t,1);return}if(s instanceof d){if(typeof e=="number"||typeof e=="string"&&/^-?\d+$/.test(e)){const t=s.getItems();if(t){const r=ie(e);r===-1&&e==="-"?t.length>0&&t.pop():r>=0&&r<t.length&&t.splice(r,1),t.length===0&&s.setItems(void 0);return}}ut(s,e,void 0)}else K(s)&&delete s[e]}function We(s){if(s instanceof d)return s.clone();if(Array.isArray(s))return s.map(t=>We(t));if(K(s)){const e={};return Object.keys(s).forEach(t=>{e[t]=We(s[t])}),e}return s}function W(s,e){if(s===e||s instanceof d&&(s.isInlineValue()||s.getValue()!==void 0)&&W(s.getValue()??null,e)||e instanceof d&&(e.isInlineValue()||e.getValue()!==void 0)&&W(s,e.getValue()??null))return!0;if(s instanceof d&&e instanceof d||F(s)&&F(e)||F(s)&&typeof e=="number"||typeof s=="number"&&F(e))return s.toString()===e.toString();if(Array.isArray(s)&&Array.isArray(e))return s.length===e.length&&s.every((t,r)=>W(t,e[r]));if(K(s)&&K(e)){const t=Object.keys(s),r=Object.keys(e);return t.length===r.length&&t.every(n=>W(s[n],e[n]))}return!1}function Dt(s,e){const{parent:t,key:r}=ae(s,le(e));return at(t,r)}function xt(s,e,t){const r=le(e);if(r.length===0&&e==="/"){const o=C(t);s.setValue(o.getValue()??null),o.getItems()?s.setItems(o.getItems()):s.setItems(void 0);return}const{parent:n,key:i}=ae(s,r);Re(n,i,t,!0)}function jr(s,e,t){const r=le(e);if(r.length===0&&e==="/"){if(s.getItems()&&Array.isArray(t)){const o=C(t);o.getItems()?(s.setItems(o.getItems()),s.setValue(null)):(s.setValue(o.getValue()??null),s.setItems(void 0))}else{const o=C(t);s.setValue(o.getValue()??null),o.getItems()&&s.setItems(o.getItems())}return!0}const{parent:n,key:i}=ae(s,r);return Re(n,i,t,!1),!0}function Lr(s,e,t){const r=le(e);if(r.length===0&&e==="/"){const l=C(t);return s.setValue(l.getValue()??null),l.getItems()?s.setItems(l.getItems()):s.setItems(void 0),!0}const{parent:n,key:i,actualTarget:o}=ae(s,r);if(o!==void 0&&n instanceof d)ut(n,i,t);else{const l=at(n,i),a=Array.isArray(n)||n instanceof d&&n.getItems()&&(typeof i=="number"||typeof i=="string"&&/^\d+$/.test(i));if(l===void 0){if(a)throw new Error(`REPLACE failed: Target array index '${i.toString()}' is out of bounds or does not exist at path '${e}'.`);Re(n,i,t,!0)}else Re(n,i,t,!0)}return!0}function _t(s,e){const t=le(e);if(t.length===0&&e==="/")return s.setValue(null),s.setItems(void 0),s.setProperties(void 0),!0;const{parent:r,key:n}=ae(s,t);return $r(r,n),!0}function Ur(s,e,t){const r=We(Dt(s,e));return xt(s,t,r),!0}function zr(s,e,t){const r=le(e),{parent:n,key:i}=ae(s,r),o=at(n,i);if(o===void 0)throw new Error(`MOVE failed: 'from' location '${e}' does not exist.`);return _t(s,e)?(xt(s,t,o),!0):!1}function kr(s,e,t){const r=Dt(s,e);let n=t;if(r instanceof d)if((t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||F(t))&&(r.isInlineValue()||r.getValue()!==void 0)){if(!W(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)&&(n=C(t));else if(F(r)&&typeof t=="number")r instanceof S?n=new S(t.toString()):r instanceof A&&(n=new A(t.toString()));else if((r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&F(t)){const i=t;!W(r,i.toString())&&(typeof r=="number"&&parseFloat(i.toString()))}if(!W(r,n)){const i=r instanceof d?r.toString():JSON.stringify(r),o=n instanceof d?n.toString():JSON.stringify(n);throw new Error(`TEST failed at '${e}': Expected ${o}, got ${i}`)}return!0}function Kr(s,e){switch(e.op){case"add":return jr(s,e.path,e.val);case"replace":return Lr(s,e.path,e.val);case"remove":return _t(s,e.path);case"copy":return Ur(s,e.from,e.path);case"move":return zr(s,e.from,e.path);case"test":return kr(s,e.path,e.val)}}function Yr(s,e,t=!1){const r=t?s:s.clone();return Kr(r,e),r}const Ke=Symbol.for("zod-schema-annotations");function Jr(){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 Ft(){const s=Jr();return Ke in s||(s[Ke]=new WeakMap),s[Ke]}function be(s,e){const t=Ft(),r=t.get(s)||{};return t.set(s,{...r,...e}),s}const D=s=>Ft().get(s),$t=s=>e=>{const t=D(e);return be(e,{...t,blueDescription:s})},jt=s=>{const e=D(s);return u.isNonNullable(e)&&M.isString(e.blueDescription)?e.blueDescription:null},Zr=s=>$t(s)(c.z.string().optional()),Gr=c.z.union([c.z.string(),c.z.boolean()]),Lt=s=>e=>{const t=D(e);return be(e,{...t,blueId:s})},Ut=s=>{const e=D(s),t=Gr.safeParse(e?.blueId);return t.success?t.data:null},Wr=s=>Lt(s??!0)(c.z.string()),zt=s=>e=>{const t=D(e);return be(e,{...t,blueName:s})},kt=s=>{const e=D(s);return u.isNonNullable(e)&&M.isString(e.blueName)?e.blueName:null},Hr=s=>{const e=c.z.string().optional();return zt(s)(e)},Kt=()=>s=>{const e=D(s);return be(s,{...e,blueNode:!0})},Yt=s=>{const e=D(s);return u.isNonNullable(e)&&u.isNonNullable(e.blueNode)&&e.blueNode===!0?e.blueNode:null},ct=s=>!!Yt(s),qr=()=>{const s=c.z.instanceof(d);return Kt()(s)},Xr=c.z.object({value:c.z.array(c.z.string()).optional(),defaultValue:c.z.string().optional()}),Jt=s=>{const e=D(s),t=Xr.passthrough().safeParse(e?.typeBlueId);return t.success?t.data:null},Qr=s=>e=>{const t=D(e),r=typeof s=="string"?{value:[s]}:s;return be(e,{...t,typeBlueId:{...t?.typeBlueId||{},...r}})};class he{static resolveBlueId(e){const t=Jt(e);if(u.isNullable(t))return null;const r=t.defaultValue;if(u.isNonNullable(r))return r;const n=t.value?.[0];return u.isNonNullable(n)?n:he.getRepositoryBlueId(t,e)}static getRepositoryBlueId(e,t){throw new Error("Not implemented")}}class O{static isTypeOf(e,t,r){const n=he.resolveBlueId(t),i=e.getType()?.getBlueId();if(u.isNullable(n)||u.isNullable(i))return!1;if(n===i)return!0;if(r?.checkSchemaExtensions&&u.isNonNullable(r.typeSchemaResolver)){const o=r.typeSchemaResolver.resolveSchema(e);return O.checkSchemaExtension(o,t,{typeSchemaResolver:r.typeSchemaResolver})}return!1}static checkSchemaExtension(e,t,r){if(!u.isNonNullable(e))return!1;const n=O.unwrapSchema(e),i=O.unwrapSchema(t);return u.isNonNullable(r?.typeSchemaResolver)?r.typeSchemaResolver.isSchemaExtendedFrom(n,i):!1}static isWrapperType(e){return e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodReadonly||e instanceof c.ZodBranded||e instanceof c.ZodEffects||e instanceof c.ZodLazy}static unwrapSchema(e){return ct(e)?e:O.isWrapperType(e)?e instanceof c.ZodEffects?O.unwrapSchema(e.innerType()):e instanceof c.ZodLazy?O.unwrapSchema(e.schema):O.unwrapSchema(e.unwrap()):e}}function mt(s,e){const t=s.getType();if(t===void 0)return;const r=t.getBlueId();if(r!==void 0){if(re.includes(r)){const i=_e[r];return new d().setBlueId(r).setName(i)}const n=e.fetchByBlueId(r);if(!n||n.length===0)return;if(n.length>1)throw new Error(`Expected a single node for type with blueId '${r}', but found multiple.`);return n[0]}return t}function B(s,e,t){const r=I.calculateBlueIdSync(s),n=I.calculateBlueIdSync(e);if(r===n)return!0;if(r&&re.includes(r)){let a=e;for(;a!==void 0;){if(I.calculateBlueIdSync(a)===r)return!0;a=mt(a,t)}return!1}let i=s;const o=s.getBlueId();if(o){const a=t.fetchByBlueId(o);a&&a.length===1&&(i=a[0])}let l=i;for(;l!==void 0;){if(I.calculateBlueIdSync(l)===n)return!0;l=mt(l,t)}return!1}function es(s,e){return nt.some(t=>{const r=new d().setBlueId(t);return B(s,r,e)})}function ts(s,e){const t=new d().setBlueId(Y);return B(s,t,e)}function rs(s,e){const t=new d().setBlueId(Z);return B(s,t,e)}function ss(s,e){const t=new d().setBlueId(J);return B(s,t,e)}function ns(s,e){const t=new d().setBlueId(G);return B(s,t,e)}function we(s,e){const t=new d().setBlueId(rt);return B(s,t,e)}function Ee(s,e){const t=new d().setBlueId(st);return B(s,t,e)}function is(s,e){return xe.some(t=>{const r=new d().setName(t);return B(s,r,e)})}function os(s,e){for(const t of xe){const r=new d().setName(t);if(B(s,r,e))return t}throw new Error(`Cannot determine the basic type for node of type "${s.getName()||"unknown"}".`)}class Zt{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=he.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),n=this.getBlueIdForSchema(t);if(u.isNullable(r)||u.isNullable(n))return!1;if(r===n)return!0;if(u.isNonNullable(this.nodeProvider))try{const i=new d().setBlueId(r),o=new d().setBlueId(n);if(B(i,o,this.nodeProvider))return!0}catch{}return!1}getBlueIdForSchema(e){if(u.isNullable(e))return null;const t=he.resolveBlueId(e);if(u.isNonNullable(t))return t;for(const[r,n]of this.blueIdMap)if(n===e||n._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)?I.calculateBlueIdSync(t):null}getBlueIdMap(){return new Map(this.blueIdMap)}}const P={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 ve{static isEmptyNode(e){return this.hasFieldsAndMayHaveFields(e)}static hasBlueIdOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([P.BLUE_ID]))}static hasItemsOnly(e){return this.hasFieldsAndMayHaveFields(e,new Set([P.ITEMS]))}static isValidValueNode(e){const t=e.getValue(),r=e.getProperties(),n=e.getItems();return u.isNonNullable(t)&&u.isNullable(r)&&u.isNullable(n)}static textNode(e){return new d().setType(new d().setBlueId(Y)).setValue(e)}static integerNode(e){const t=e instanceof S?e:new S(e.toString());return new d().setType(new d().setBlueId(Z)).setValue(t)}static doubleNode(e){const t=e instanceof A?e:new A(e.toString());return new d().setType(new d().setBlueId(J)).setValue(t)}static booleanNode(e){return new d().setType(new d().setBlueId(G)).setValue(e)}static hasFieldsAndMayHaveFields(e,t=new Set,r=new Set){for(const n of Object.values(P)){const i=u.isNonNullable(this.getFieldValue(e,n));if(t.has(n)){if(!i)return!1}else if(!r.has(n)){if(i)return!1}}return!0}static getFieldValue(e,t){switch(t){case P.NAME:return e.getName();case P.TYPE:return e.getType();case P.VALUE:return e.getValue();case P.DESCRIPTION:return e.getDescription();case P.PROPERTIES:return e.getProperties();case P.BLUE:return e.getBlue();case P.ITEMS:return e.getItems();case P.KEY_TYPE:return e.getKeyType();case P.VALUE_TYPE:return e.getValueType();case P.ITEM_TYPE:return e.getItemType();case P.BLUE_ID:return e.getBlueId();default:throw new Error(`Unknown field: ${t}`)}}}class Fe{}class ue{static convert(e){const t=new He;return ue.traverseNode(e,"",t),t.build()}static traverseNode(e,t,r){if(!e)return;const n=e.getProperties(),i=e.getItems(),o=n!==void 0&&Object.keys(n).length>0,l=i!==void 0&&i.length>0;if(!o&&!l){r.addPath(t===""?"/":t);return}if(n)for(const[a,p]of Object.entries(n)){const f=`${t}/${a}`;ue.traverseNode(p,f,r)}if(i)for(let a=0;a<i.length;a++){const p=`${t}/${a}`;ue.traverseNode(i[a],p,r)}}}function It(s,e){const t=s.split(e),r=[...t].reverse().findIndex(i=>i!==""),n=r===-1?0:t.length-r;return t.slice(0,n)}class $e extends Fe{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=It(e,"/"),n=It(t,"/");if(n.length>r.length)return!1;for(let i=1;i<n.length;i++)if(r[i]!=="*"&&r[i]!==n[i])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 He().setMaxDepth(e);for(let r=1;r<=e;r++){const n="/"+Array(r).fill("*").join("/");t.addPath(n)}return t.build()}static withSinglePath(e){return new He().addPath(e).build()}static fromNode(e){return ue.convert(e)}}class He{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 $e(this.allowedPaths,this.maxDepth)}}class Se extends Fe{shouldExtendPathSegment(){return!0}shouldMergePathSegment(){return!0}enterPathSegment(){}exitPathSegment(){}}class je extends Fe{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 je(e)}}const j=new Se;class ls{blue;constructor(e){this.blue=e}matchesType(e,t,r=j){const n=$e.fromNode(t),i=je.of(r,n),o=this.extendAndResolve(e,i),l=this.blue.resolve(t,i),a=this.expandSchemaOwnedTypeReferences(t);return this.verifyMatch(o,t,i)&&this.recursiveValueComparison(o,l,a,i)}extendAndResolve(e,t){const r=e.clone(),n=r.clone();this.blue.extend(n,t);const i=this.blue.resolve(n,t);return this.restoreMissingStructure(i,r),i}restoreMissingStructure(e,t){const r=t.getItems(),n=e.getItems();if(r&&r.length>0)if(!n||n.length===0)e.setItems(r.map(a=>a.clone()));else for(let a=0;a<Math.min(n.length,r.length);a++)this.restoreMissingStructure(n[a],r[a]);const i=t.getProperties();if(i){let a=e.getProperties();a||(a={},e.setProperties(a));for(const[p,f]of Object.entries(i)){const h=a[p];h===void 0?a[p]=f.clone():this.restoreMissingStructure(h,f)}}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 n=t.getType();if(this.matchesImplicitStructure(e,n))return!0;const i=e.clone().setType(t.clone());try{this.blue.resolve(i,r)}catch{return!1}return!0}recursiveValueComparison(e,t,r=t,n=j){const i=t.getType(),o=this.matchesImplicitStructure(e,i)||this.matchesImplicitCoreCollectionType(e,t);if(e.getType()===void 0&&this.isCoreCollectionType(t)&&!o)return!1;if(i&&!o){const b=e.getType();if(!b||!B(b,i,this.blue.getNodeProvider()))return!1}const l=t.getBlueId();if(!o&&l!==void 0)if(this.isExplicitBlueIdMatcher(r)){const b=e.getBlueId(),N=e.getType()?.getBlueId();if(b!==l&&N!==l)return!1}else{const b=e.getBlueId(),N=e.getType();if(N===void 0&&b!==void 0&&b!==l||N&&!B(N,t,this.blue.getNodeProvider()))return!1}const a=t.getValue();if(a!==void 0){const b=e.getValue();if(b===void 0)return!1;if(R(b)&&R(a)){if(!b.eq(a))return!1}else if(b!==a)return!1}const p=t.getItems(),f=r.getItems();if(p!==void 0){const b=e.getItems()??[];for(let N=0;N<p.length;N++)if(N<b.length){if(!this.recursiveValueComparison(b[N],p[N],f?.[N]??p[N],n))return!1}else if(this.hasValueInNestedStructure(p[N]))return!1}const h=t.getItemType(),g=r.getItemType();if(h!==void 0){const b=e.getItems()??[];for(const N of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(N,h,g??h,n),h,g??h,n))return!1}const T=t.getProperties(),x=r.getProperties();if(T!==void 0){const b=e.getProperties()??{};for(const[N,Le]of Object.entries(T))if(N in b){if(!this.recursiveValueComparison(b[N],Le,x?.[N]??Le,n))return!1}else if(this.hasValueInNestedStructure(Le))return!1}const V=t.getValueType(),_=r.getValueType();if(V!==void 0){const b=Object.values(e.getProperties()??{});for(const N of b)if(!this.recursiveValueComparison(this.resolveUntypedNodeAgainstMatcherType(N,V,_??V,n),V,_??V,n))return!1}return!0}resolveUntypedNodeAgainstMatcherType(e,t,r,n){return e.getType()!==void 0||this.isExplicitBlueIdMatcher(r)?e:this.resolveAgainstTargetType(e,t,n)??e}hasValueInNestedStructure(e){if(e.getValue()!==void 0)return!0;const t=e.getItems();if(t!==void 0){for(const n of t)if(this.hasValueInNestedStructure(n))return!0}const r=e.getProperties();if(r!==void 0){for(const n of Object.values(r))if(this.hasValueInNestedStructure(n))return!0}return!1}matchesImplicitStructure(e,t){return t===void 0||e.getType()!==void 0?!1:we(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ee(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}matchesImplicitCoreCollectionType(e,t){return e.getType()!==void 0?!1:we(t,this.blue.getNodeProvider())?this.isImplicitListStructure(e):Ee(t,this.blue.getNodeProvider())?this.isImplicitDictionaryStructure(e):!1}isCoreCollectionType(e){return we(e,this.blue.getNodeProvider())||Ee(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 n=e.clone(),i=n.clone().setType(t.clone()),o=this.blue.resolve(i,r);return this.restoreMissingStructure(o,n),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()),n=e.getType();n&&e.setType(this.expandReferencedTypeNode(n,r));const i=e.getItemType();i&&e.setItemType(this.expandReferencedTypeNode(i,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(f=>this.expandSchemaTypeReferences(f,r)));const p=e.getProperties();return p&&e.setProperties(Object.fromEntries(Object.entries(p).map(([f,h])=>[f,this.expandSchemaTypeReferences(h,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 n=this.blue.getNodeProvider().fetchByBlueId(r);return!n||n.length!==1?e.clone():this.expandSchemaTypeReferences(n[0].clone(),t)}withVisitedBlueId(e,t){if(!t||e.has(t))return e;const r=new Set(e);return r.add(t),r}}const as=s=>s instanceof c.ZodOptional||s instanceof c.ZodNullable||s instanceof c.ZodReadonly||s instanceof c.ZodBranded||s instanceof c.ZodEffects||s instanceof c.ZodLazy,us=s=>s instanceof c.ZodString||s instanceof c.ZodNumber||s instanceof c.ZodBoolean||s instanceof c.ZodBigInt;class Gt{static convertValue(e,t){const r=e.getType()?.getBlueId(),n=e.getValue();return u.isNullable(n)?us(t)&&ve.isValidValueNode(e)?this.getDefaultPrimitiveValue(t):n:Y===r?this.convertFromString(String(n),t):J===r||n instanceof A?this.convertFromBigDecimal(new A(n?.toString()),t):Z===r||n instanceof S?this.convertFromBigInteger(new S(n?.toString()),t):G===r||typeof n=="boolean"?this.convertFromBoolean(!!n,t):this.convertFromString(String(n),t)}static convertFromString(e,t){if(!t||t instanceof c.ZodString||t instanceof c.ZodEnum||t instanceof c.ZodNativeEnum)return e;if(t instanceof c.ZodNumber)return Number(e);if(t instanceof c.ZodBoolean)return e.toLowerCase()==="true";if(t instanceof c.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert String to ${t._def.typeName}`)}static convertFromBigDecimal(e,t){if(t instanceof c.ZodNumber)return e.toNumber();if(t instanceof c.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBigInteger(e,t){if(t instanceof c.ZodNumber)return e.toNumber();if(t instanceof c.ZodBigInt)return BigInt(e.toString());if(t instanceof c.ZodString)return e.toString();throw new Error(`Cannot convert Number to ${t._def.typeName}`)}static convertFromBoolean(e,t){if(!t||t instanceof c.ZodBoolean)return e;if(t instanceof c.ZodString)return e.toString();if(t instanceof c.ZodNumber)return Number(e);if(t instanceof c.ZodBigInt)return BigInt(e);throw new Error(`Cannot convert Boolean to ${t._def.typeName}`)}static getDefaultPrimitiveValue(e){if(!e)return null;if(e instanceof c.ZodNumber)return 0;if(e instanceof c.ZodBoolean)return!1;if(e instanceof c.ZodString)return"";throw new Error(`Unsupported primitive type: ${e._def.typeName}`)}}class cs{convert(e,t){return Gt.convertValue(e,t)}}class ds{constructor(e){this.nodeToObjectConverter=e}convert(e,t){return this.convertFields(e,t)}convertFields(e,t){if(t instanceof c.ZodIntersection){const r=t._def.left,n=t._def.right,i=this.convert(e,r),o=this.convert(e,n);return{...i,...o}}if(t instanceof c.ZodUnion)throw new Error("Union not supported");if(t instanceof c.ZodObject)return Object.keys(t.shape).reduce((n,i)=>{const o=e.getProperties(),l=t.shape[i],a=Ut(l);if(u.isNonNullable(a)){const T=M.isString(a)?a:i,x=o?.[T],V=x?I.calculateBlueIdSync(x):void 0;return n[i]=V,n}const p=kt(l);if(u.isNonNullable(p)){const T=o?.[p];return n[i]=T?.getName(),n}const f=jt(l);if(u.isNonNullable(f)){const T=o?.[f];return n[i]=T?.getDescription(),n}if(i==="name"){const T=e.getName();return n[i]=T,n}if(i==="description"){const T=e.getDescription();return n[i]=T,n}const h=o?.[i];if(u.isNullable(h))return n;const g=this.nodeToObjectConverter.convert(h,l);return n[i]=g,n},{});throw new Error("Unknown schema type, "+t._def.typeName)}}class ps{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t.element;return r.map(o=>this.nodeToObjectConverter.convert(o,n))}}class hs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t._def.valueType,i=r.map(o=>this.nodeToObjectConverter.convert(o,n));return new Set(i)}}class fs{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=t.keySchema,n=t.valueSchema,i=new Map,o=e.getName();u.isNonNullable(o)&&i.set(q,o);const l=e.getDescription();u.isNonNullable(l)&&i.set(X,l);const a=e.getProperties();return u.isNonNullable(a)&&Object.entries(a).forEach(([p,f])=>{const h=new d().setValue(p);h.setType(new d().setBlueId(Y));const g=Gt.convertValue(h,r),T=this.nodeToObjectConverter.convert(f,n);i.set(g,T)}),t instanceof c.ZodRecord?Object.fromEntries(i):i}}class ys{convert(e){return m.get(e)}}class gs{convert(e){return m.get(e)}}class ms{constructor(e){this.nodeToObjectConverter=e}convert(e,t){const r=e.getItems();if(!r)return;const n=t.items;return r.map((o,l)=>this.nodeToObjectConverter.convert(o,n[l]))}}const Is=c.z.union([c.z.literal("ZodString"),c.z.literal("ZodNumber"),c.z.literal("ZodBoolean"),c.z.literal("ZodBigInt"),c.z.literal("ZodArray"),c.z.literal("ZodSet"),c.z.literal("ZodMap"),c.z.literal("ZodRecord"),c.z.literal("ZodObject"),c.z.literal("ZodEnum"),c.z.literal("ZodNativeEnum"),c.z.literal("ZodUnknown"),c.z.literal("ZodAny"),c.z.literal("ZodTuple")]);class Ts{constructor(e){this.nodeToObjectConverter=e,this.registerConverters(),this.complexObjectConverter=new ds(this.nodeToObjectConverter)}converters=new Map;complexObjectConverter;registerConverters(){const e=new cs,t=new ps(this.nodeToObjectConverter),r=new ms(this.nodeToObjectConverter),n=new hs(this.nodeToObjectConverter),i=new fs(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 ys),this.converters.set("ZodAny",new gs),this.converters.set("ZodArray",t),this.converters.set("ZodTuple",r),this.converters.set("ZodSet",n),this.converters.set("ZodMap",i),this.converters.set("ZodRecord",i),this.converters.set("ZodObject",this.complexObjectConverter)}getConverter(e){const t=this.getSchemaTypeName(e);return this.converters.get(t)??this.complexObjectConverter}getSchemaTypeName(e){if(as(e))return e instanceof c.ZodEffects?this.getSchemaTypeName(e.innerType()):e instanceof c.ZodLazy?this.getSchemaTypeName(e.schema):this.getSchemaTypeName(e.unwrap());const t=e._def.typeName;try{return Is.parse(t)}catch{throw new Error(`Schema type name ${t} is not supported`)}}}class bs{constructor(e){this.typeSchemaResolver=e,this.converterFactory=new Ts(this)}converterFactory;convert(e,t){const r=this.typeSchemaResolver?.resolveSchema(e),n=O.unwrapSchema(t);if(ct(n))return e;let i=n;return O.checkSchemaExtension(r,n,{typeSchemaResolver:this.typeSchemaResolver})&&u.isNonNullable(r)&&(i=r),this.convertWithType(e,i)}convertWithType(e,t){return this.converterFactory.getConverter(t).convert(e,t)}}class Wt{reverse(e){const t=new d;return this.reverseNode(t,e,e.getType()),t}reverseNode(e,t,r){this.isIdenticalToType(t,r)||(this.reverseBasicProperties(e,t,r),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){const n=t.getValue();u.isNonNullable(n)&&(u.isNullable(r)||u.isNullable(r.getValue()))&&e.setValue(n),u.isNonNullable(t.getName())&&(u.isNullable(r)||t.getName()!==r.getName())&&e.setName(t.getName()),u.isNonNullable(t.getDescription())&&(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 n=(i,o)=>{const l=i(t),a=r?i(r):void 0,p=l?.getBlueId();u.isNonNullable(p)&&(u.isNullable(a?.getBlueId())||p!==a.getBlueId())&&o(e,new d().setBlueId(p))};n(i=>i.getType(),(i,o)=>i.setType(o)),n(i=>i.getItemType(),(i,o)=>i.setItemType(o)),n(i=>i.getKeyType(),(i,o)=>i.setKeyType(o)),n(i=>i.getValueType(),(i,o)=>i.setValueType(o))}reverseItems(e,t,r){const n=t.getItems();if(u.isNullable(n))return;const i=r?.getItems(),o=[];if(u.isNonNullable(i)&&n.length>i.length&&u.isNonNullable(i)&&i.length>0){const p=I.calculateBlueIdSync(i);o.push(new d().setBlueId(p))}const a=i?.length||0;for(let p=a;p<n.length;p++){const f=new d;this.reverseNode(f,n[p],void 0),o.push(f)}o.length>0&&e.setItems(o)}reverseProperties(e,t,r){const n=t.getProperties();if(u.isNullable(n))return;const i={};for(const[o,l]of Object.entries(n)){const a=this.getInheritedProperty(o,t,r),p=new d;this.reverseNode(p,l,a),ve.isEmptyNode(p)||(i[o]=p)}Object.keys(i).length>0&&e.setProperties(i)}getInheritedProperty(e,t,r){const n=r?.getProperties()?.[e],i=t.getType()?.getProperties()?.[e];if(!(u.isNullable(n)&&u.isNullable(i)))return u.isNullable(n)?i:u.isNullable(i)?n:this.mergeNodes(n,i)}mergeNodes(e,t){const r=e.clone(),n=t.getValue();u.isNonNullable(n)&&r.setValue(n);const i=t.getType();u.isNonNullable(i)&&r.setType(i.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 p=t.getProperties();if(u.isNonNullable(p)){const h=r.getProperties()||{};for(const[g,T]of Object.entries(p))h[g]=T.clone();r.setProperties(h)}const f=t.getItems();return u.isNonNullable(f)&&r.setItems(f.map(h=>h.clone())),r}}class ee extends d{constructor(e){super(e.getName()),this.createFrom(e)}isResolved(){return!0}getMinimalNode(){return new Wt().reverse(this)}getMinimalBlueId(){const e=this.getMinimalNode();return I.calculateBlueIdSync(e)}clone(){const e=super.clone();return new ee(e)}cloneShallow(){const e=super.cloneShallow();return new ee(e)}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 Ne{fetchFirstByBlueId(e){const t=this.fetchByBlueId(e);return t&&t.length>0?t[0]:null}}function vs(s){return new class extends Ne{fetchByBlueId(e){return s(e)}}}const Ye=te.types.float.options,Ns={...Ye,construct:s=>{const e=s.replace(/_/g,"").toLowerCase();if(!u.isPreciseNumberString(e))return new A(e);if(Ye.construct)return Ye.construct(s)}},Bs=new te.Type("tag:yaml.org,2002:float",Ns),Je=te.types.int.options,ws={...Je,construct:s=>{let e=s;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),!u.isPreciseNumberString(e))return new S(e);if(Je.construct)return Je.construct(s)}},Es=new te.Type("tag:yaml.org,2002:int",ws),Ht=te.CORE_SCHEMA.extend({implicit:[Bs,Es]}),$=s=>{const e=te.load(s,{schema:Ht});return e===void 0?void 0:e},qt=s=>te.dump(s,{schema:Ht,replacer:(e,t)=>{if(R(t)){if(k(t)){const r=new U(Number.MIN_SAFE_INTEGER.toString()),n=new U(Number.MAX_SAFE_INTEGER.toString());if(t.lt(r)||t.gt(n))return t.toString()}return t.toNumber()}return t}});class Ss{static get(e,t={}){const{strategy:r="official"}=t,n=m.get(e,r);return qt(n)}}class Ps extends Ne{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 Xt=`- type:
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:
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
- `,Cs=`name: Transformation
13
- description: TODO`,As=`name: Infer Basic Types For Untyped Values
12
+ `,xs=`name: Transformation
13
+ description: TODO`,Fs=`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.`,Rs=`name: Replace Inline Types with BlueIds
16
+ description: This transformation infers type details for Text, Integer, Number and Boolean.`,zs=`name: Replace Inline Types with BlueIds
17
17
  type:
18
18
  blueId: Ct1SGRGw1i47qjzm1ruiUdSZofeV6WevPTGuieVvbRS4
19
- description: This transformation replaces`,Vs=[Xt,Cs,As,Rs];class Os extends Ne{blueIdToNodesMap=new Map;constructor(){super(),this.load()}fetchByBlueId(e){return this.blueIdToNodesMap.get(e)||[]}load(){for(const e of Vs){const t=$(e);if(t===void 0){console.error(`This content file is not valid YAML: ${e}`);continue}if(Array.isArray(t)){const r=t.map(i=>y.deserialize(i)),n=I.calculateBlueIdSync(r);this.blueIdToNodesMap.set(n,r)}else{const r=y.deserialize(t),n=I.calculateBlueIdSync(r);this.blueIdToNodesMap.set(n,[r])}}}}class dt extends Ne{static INSTANCE=new dt;nodeProvider;constructor(){super(),this.nodeProvider=new Os}fetchByBlueId(e){return this.nodeProvider.fetchByBlueId(e)}}class Ze{constructor(e,t,r){this.blueId=e,this.content=t,this.isMultipleDocuments=r}}class H{static THIS_REFERENCE_PATTERN=/^this(#\d+)?$/;static parseAndCalculateBlueId(e,t){let r;try{const l=$(e);if(l===void 0)throw new Error;r=l}catch{throw new Error("Failed to parse content as YAML or JSON")}let n,i;const o=Array.isArray(r)&&r.length>1;if(o){const l=r.map(a=>{const p=y.deserialize(a);return t(p)});n=I.calculateBlueIdSync(l),i=l.map(a=>m.get(a))}else{const l=y.deserialize(r),a=t(l);n=I.calculateBlueIdSync(a),i=m.get(a)}return new Ze(n,i,o)}static parseAndCalculateBlueIdForNode(e,t){const r=t(e),n=I.calculateBlueIdSync(r),i=m.get(r);return new Ze(n,i,!1)}static parseAndCalculateBlueIdForNodeList(e,t){if(!e||e.length===0)throw new Error("List of nodes cannot be null or empty");const r=e.map(t),n=I.calculateBlueIdSync(r),i=r.map(l=>m.get(l)),o=e.length>1;return new Ze(n,i,o)}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 n={};for(const[i,o]of Object.entries(e))typeof o=="string"?this.THIS_REFERENCE_PATTERN.test(o)?n[i]=this.resolveThisReference(o,t,r):n[i]=o:o&&typeof o=="object"?n[i]=this.resolveThisReferencesRecursive(o,t,r):n[i]=o;return n}else if(Array.isArray(e))return e.map(n=>typeof n=="string"?this.THIS_REFERENCE_PATTERN.test(n)?this.resolveThisReference(n,t,r):n:n&&typeof n=="object"?this.resolveThisReferencesRecursive(n,t,r):n);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 Ms extends Ne{fetchByBlueId(e){const t=e.split("#")[0],r=this.fetchContentByBlueId(t);if(r==null)return null;const n=Array.isArray(r)&&r.length>1,i=H.resolveThisReferences(r,t,n);if(e.includes("#")){const o=e.split("#");if(o.length>1){const l=parseInt(o[1]);if(Array.isArray(i)&&l<i.length){const a=i[l],p=y.deserialize(a);return p.setBlueId(e),[p]}else if(l===0){const a=y.deserialize(i);return a.setBlueId(e),[a]}else return null}}if(Array.isArray(i))return i.map(o=>y.deserialize(o));{const o=y.deserialize(i);return o.setBlueId(t),[o]}}}class Qt extends Ms{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 n of t){const i=this.fetchByBlueId(n);i&&r.push(...i)}return r}addToNameMap(e,t){this.nameToBlueIdsMap.set(e,[...this.nameToBlueIdsMap.get(e)||[],t])}}const er=s=>s instanceof d||Array.isArray(s)&&s.every(e=>e instanceof d)?s:M.isArray(s)?s.map(e=>y.deserialize(e)):y.deserialize(s),tr=async s=>{const e=er(s);return I.calculateBlueId(e)},Ds=s=>{const e=er(s);return I.calculateBlueIdSync(e)},qe=async s=>{if(Ct(s))return s;try{const e=pe.parse(s),t=await tr(e);return{...s,blueId:t}}catch(e){throw new Error(`Failed enriching object with Blue ID: ${e}`)}},xs=s=>s?.items,_s=s=>s?.value,Fs=s=>u.isNullable(s)?{}:M.omit(s,et),$s=s=>Rt(s)?s.type.name??null:Vt(s)?M.pascal(typeof s.value):At(s)?"List":null,rr=s=>u.isNonNullable(s)&&Object.keys(M.omit(s,["blueId"])).length>0,js=s=>{try{const e=y.deserialize(s),t=m.get(e);return ne.parse(t)}catch(e){throw new Error(`Failed transforming JSON-like value to BlueObject: ${e}`)}},Xe=async s=>{const{resolveFunction:e,signal:t=new AbortController().signal,omitItems:r}=s,n=s.count??s.items.length;let i=await M.map(s.items,async l=>await qe(l));const o=Math.max(i?.length-n,0);for(let l=i.length-1;l>=o;l--)if(!rr(i[l])){const a=await e(i[l],{signal:t});if(Array.isArray(a))return Xe({...s,items:[...i.slice(0,l),...a,...i.slice(l+1)]});const p=await qe(a);if(r?.includes(p.blueId))return Xe({...s,items:[...i.slice(0,l),...i.slice(l+1)]});i=[...i.slice(0,l),p,...i.slice(l+1)]}return i};function ce(s){try{const e=new URL(s);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}class Ls{process(e){return E.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(Y)):typeof r=="bigint"||k(r)?e.setType(new d().setBlueId(Z)):Ce(r)?e.setType(new d().setBlueId(J)):typeof r=="boolean"&&e.setType(new d().setBlueId(G))),e}}class Ve{static MAPPINGS="mappings";mappings=new Map;constructor(e){if(e instanceof d){const r=e.getProperties();if(r&&r[Ve.MAPPINGS]){const i=r[Ve.MAPPINGS].getProperties();i&&Object.entries(i).forEach(([o,l])=>{const a=l.getValue();typeof a=="string"&&this.mappings.set(o,a)})}}else this.mappings=e}process(e){return E.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 n=this.mappings.get(r);if(n){const i=new d().setBlueId(n);t===e.getType()?e.setType(i):t===e.getItemType()?e.setItemType(i):t===e.getKeyType()?e.setKeyType(i):t===e.getValueType()&&e.setValueType(i)}}}}}class Us{process(e){return E.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 n=String(t.getValue());throw new Error(`Unknown type "${n}" found in ${r} field. No BlueId mapping exists for this type.`)}}}class pt{nodeProvider;strategy;constructor(e,t){this.nodeProvider=fe.wrap(e),this.strategy=t||"THROW_EXCEPTION"}extend(e,t){this.extendNode(e,t,"")}extendNode(e,t,r,n=!1){if(!n){if(!t.shouldExtendPathSegment(r,e))return;t.enterPathSegment(r,e)}try{const i=e.getBlueId();if(i&&!re.includes(i)){const g=this.fetchNode(e);if(g&&g.length>0)if(g.length===1){const T=g[0];this.mergeNodes(e,T)}else{const T=g.map(V=>V.clone()),x=new d().setItems(T);this.mergeNodes(e,x)}}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 p=e.getValueType();p&&this.extendNode(p,t,"valueType",!0);const f=e.getProperties();f&&Object.entries(f).forEach(([g,T])=>{this.extendNode(T,t,g,!1)});const h=e.getItems();if(h&&h.length>0){this.reconstructList(h);for(let g=0;g<h.length;g++)this.extendNode(h[g],t,String(g),!1)}}finally{n||t.exitPathSegment()}}reconstructList(e){for(;e.length>0;){const r=e[0]?.getBlueId();if(!r)break;const n=this.nodeProvider.fetchByBlueId(r);if(!n||n.length===1)break;e.shift(),e.unshift(...n)}}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}mergeNodes(e,t){e.setName(t.getName()),e.setDescription(t.getDescription()),e.setType(t.getType()),e.setItemType(t.getItemType()),e.setKeyType(t.getKeyType()),e.setValueType(t.getValueType());const r=t.getValue();u.isNonNullable(r)&&e.setValue(r),e.setItems(t.getItems()),e.setProperties(t.getProperties())}}class ht{blueIdsCollections=[];initialize(...e){this.blueIdsCollections=[...e]}registerBlueIds(...e){this.blueIdsCollections.push(...e)}generateMappingsYaml(e="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo"){const t={};for(const n of this.blueIdsCollections)Object.assign(t,n);const r=Object.entries(t).map(([n,i])=>` ${n}: ${i}`).join(`
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(`
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 oe{static DEFAULT_BLUE_BLUE_ID="6sqUywMoBRyj9hgQxSu2nDPnqcyiSM7xu9AB9sN98YJK";processorProvider;nodeProvider;defaultSimpleBlue=null;blueIdsMappingGenerator;constructor(e={}){const{nodeProvider:t,processorProvider:r,blueIdsMappingGenerator:n}=e;if(!t)throw new Error("NodeProvider is required");this.nodeProvider=fe.wrap(t),this.processorProvider=r||oe.getStandardProvider(),this.blueIdsMappingGenerator=n||new ht,this.loadDefaultSimpleBlue()}preprocess(e){return this.preprocessWithOptions(e,null)}preprocessWithDefaultBlue(e){return this.preprocessWithOptions(e,this.defaultSimpleBlue)}preprocessWithOptions(e,t){let r=e.clone(),n=r.getBlue();if(!n&&t&&(n=t.clone()),n){new pt(this.nodeProvider).extend(n,$e.withSinglePath("/*"));const i=n.getItems();if(i&&i.length>0){for(const o of i){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 Us().process(r)}return r}static getStandardProvider(){return{getProcessor(e){const t="27B7fuxQCS1VAptiCPc2RMkKoutP5qxkh3uDxZ7dr6Eo",r="FGYuTXwaoSKfZmpTysLTLsb8WzSqf43384rKZDkXhxD4",n=e.getType()?.getBlueId();if(t===n)return new Ve(e);if(r===n)return new Ls}}}enrichDefaultBlue(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 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`
24
24
  ${e}
25
25
  ${t}
26
- `}loadDefaultSimpleBlue(){try{const e=this.enrichDefaultBlue(Xt),t=$(e);if(t)this.defaultSimpleBlue=y.deserialize(t);else throw new Error("Failed to parse default Blue content")}catch(e){throw new Error(`Error loading default Blue: ${e}`)}}}class ft extends Qt{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;constructor(e){super();const t=new ht,r=ft.collectAliasMappings(e);Object.keys(r).length>0&&t.registerBlueIds(r);const n=new oe({nodeProvider:this,blueIdsMappingGenerator:t});this.preprocessor=i=>n.preprocessWithDefaultBlue(i),this.loadRepositories(e)}static collectAliasMappings(e){const t={};for(const r of e)for(const n of Object.values(r.packages))for(const[i,o]of Object.entries(n.aliases)){const l=t[i];if(l&&l!==o)throw new Error(`Conflicting alias mapping for ${i}`);t[i]=o}return t}loadRepositories(e){for(const t of e)Object.values(t.packages).forEach(r=>{for(const[n,i]of Object.entries(r.contents))this.processContent(i,n)})}processContent(e,t){Array.isArray(e)?this.processMultipleDocuments(e,t):this.processSingleDocument(e,t)}processSingleDocument(e,t){const r=y.deserialize(e),n=H.parseAndCalculateBlueIdForNode(r,this.preprocessor),i=t||n.blueId;this.blueIdToContentMap.set(i,n.content),this.blueIdToMultipleDocumentsMap.set(i,!1);const o=r.getName();o&&this.addToNameMap(o,i)}processMultipleDocuments(e,t){const r=e.map(o=>{const l=y.deserialize(o);return this.preprocessor(l)}),n=H.parseAndCalculateBlueIdForNodeList(r,o=>o),i=t||n.blueId;this.blueIdToContentMap.set(i,n.content),this.blueIdToMultipleDocumentsMap.set(i,!0),r.forEach((o,l)=>{const a=`${i}#${l}`,p=m.get(o),f=I.calculateBlueIdSync(o);this.blueIdToContentMap.set(f,p),this.blueIdToMultipleDocumentsMap.set(f,!1);const h=o.getName();h&&this.addToNameMap(h,a)})}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?H.resolveThisReferences(t,e,r):null}getBlueIds(){return Array.from(this.blueIdToContentMap.keys())}hasBlueId(e){const t=e.split("#")[0];return this.blueIdToContentMap.has(t)}}class fe{static wrap(e,t){const r=[dt.INSTANCE];if(t&&t.length>0){const n=new ft(t);r.push(n)}return r.push(e),new Ps(r)}}class zs{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(Pe.isPotentialBlueId(t))return this.handleBlueId(r,t);throw ce(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(Pe.isPotentialBlueId(t))return this.handleBlueId(r,t);if(ce(t)&&this.urlContentFetcher)try{const n=await this.fetchFromUrl(t);return n&&r.setBlue(new d().setItems(n)),r}catch(n){throw n instanceof Error?new Error(`Failed to fetch from URL '${t}'.
27
- ${n.message}`):n}else throw ce(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 ks={fetchUrl:async s=>{throw new Error(`You must provide a custom UrlFetchStrategy to fetch content from URL: ${s}`)}};class Ks{cache=new Map;fetchStrategy;enabled=!1;allowedDomains=[];constructor(e){this.fetchStrategy=e||ks}validateUrl(e){if(!ce(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:n}=t;let i;if(n.includes("application/json")||n.includes("text/yaml")||n.includes("application/yaml")||n.includes("text/plain"))i=$(r);else throw new Error(`Unsupported content type from URL: ${n}`);if(i===void 0)throw new Error(`Failed to parse content from URL: ${e}`);let o;return Array.isArray(i)?o=i.map(l=>y.deserialize(l)):o=[y.deserialize(i)],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 sr{resolveWithoutLimits(e){return this.resolve(e,j)}}class nr extends sr{mergingProcessor;nodeProvider;constructor(e,t){super(),this.mergingProcessor=e,this.nodeProvider=fe.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 n=e;const i=t.getType();if(u.isNonNullable(i)){const o=this.resolveTypeNode(i,r),l=o.clone().setType(void 0).setBlueId(void 0);n=this.mergeObject(n,l,r);const a=t.cloneShallow().setType(o.clone());return this.mergeObject(n,a,r)}return this.mergeObject(n,t,r)}mergeObject(e,t,r){const n=e.cloneShallow();let i=this.mergingProcessor.process(n,t,r.nodeProvider);const o=t.getItems();u.isNonNullable(o)&&(i=this.mergeChildren(i,o,r));const l=t.getProperties();return u.isNonNullable(l)&&(i=this.mergeProperties(i,l,r)),u.isNonNullable(t.getBlueId())&&(i=i.cloneShallow().setBlueId(t.getBlueId())),this.mergingProcessor.postProcess&&(i=this.mergingProcessor.postProcess(i,t,r.nodeProvider)),i}mergeChildren(e,t,r){const n=e.getItems(),i=u.isNonNullable(n)||this.isInheritedListMarkerNode(t[0])?this.getInheritedItemsPrefixLength(t,n??[],r):void 0;if(this.rememberInheritedItemsPrefix(t,i,r),u.isNullable(n)){const l=[];for(let a=0;a<t.length;a++){const p=t[a];if(r.limits.shouldMergePathSegment(String(a),p)){this.enterPathSegment(r,String(a),p);try{const f=this.materializeForCurrentContext(p,r);l.push(f)}finally{this.exitPathSegment(r)}}}return e.cloneShallow().setItems(l)}if(u.isNonNullable(i)){const l=this.mergeChildrenWithInheritedItemsPrefix(t,n,i,r);return e.cloneShallow().setItems(l)}if(t.length<n.length)throw new Error(`Subtype of element must not have more items (${n.length}) than the element itself (${t.length}).`);const o=[...n];for(let l=0;l<t.length;l++)if(r.limits.shouldMergePathSegment(String(l),t[l])){this.enterPathSegment(r,String(l),t[l]);try{if(l>=o.length){const f=this.materializeForCurrentContext(t[l],r);o.push(f);continue}const a=I.calculateBlueIdSync(t[l]),p=I.calculateBlueIdSync(o[l]);if(a!==p)throw new Error(`Mismatched items at index ${l}: source item has blueId '${a}', but target item has blueId '${p}'.`)}finally{this.exitPathSegment(r)}}return e.cloneShallow().setItems(o)}getInheritedItemsPrefixLength(e,t,r){const n=e[0],i=n?.getBlueId();if(u.isNullable(i))return;let o;if(t.length>0){const l=I.calculateBlueIdSync(t);i===l&&(o=t.length)}if(u.isNullable(o)){const l=r.inheritedItemsPrefixByPath.get(this.getCurrentPointer(r));u.isNonNullable(l)&&l.blueId===i&&(o=l.length)}if(!u.isNullable(o)){if(!this.isInheritedListMarkerNode(n)){if(e.length>1)throw new Error("Invalid inherited-list marker: first list item must contain only blueId.");return}return o}}rememberInheritedItemsPrefix(e,t,r){const n=this.getCurrentPointer(r);if(e.length===0)return;const i=e[0],l=this.isInheritedListMarkerNode(i)?u.isNonNullable(t)?t+e.length-1:void 0:e.length;if(u.isNullable(l))return;const a={blueId:I.calculateBlueIdSync(e),length:l},p=r.inheritedItemsPrefixByPath.get(n);u.isNonNullable(p)&&p.length>=a.length||r.inheritedItemsPrefixByPath.set(n,a)}isInheritedListMarkerNode(e){return u.isNonNullable(e)&&u.isNonNullable(e.getBlueId())&&ve.hasBlueIdOnly(e)}mergeChildrenWithInheritedItemsPrefix(e,t,r,n){const i=[...t];for(let o=1;o<e.length;o++){const l=e[o],a=String(r+o-1);if(n.limits.shouldMergePathSegment(a,l)){this.enterPathSegment(n,a,l);try{const p=this.materializeForCurrentContext(l,n);i.push(p)}finally{this.exitPathSegment(n)}}}return i}mergeProperties(e,t,r){const n=e.getProperties()??{};let i=n,o=!1;for(const[l,a]of Object.entries(t))if(r.limits.shouldMergePathSegment(l,a)){this.enterPathSegment(r,l,a);try{const p=i[l],h=this.shouldMergePropertyWithoutPreResolve(p,a,r)?this.mergeWithContext(p,a,r):(()=>{const g=this.materializeForCurrentContext(a,r);return p===void 0?g:this.mergeObject(p,g,r)})();h!==p&&(o||(i={...n},o=!0),i[l]=h)}finally{this.exitPathSegment(r)}}return o?e.cloneShallow().setProperties(i):e}shouldMergePropertyWithoutPreResolve(e,t,r){return u.isNullable(e)||r.limits instanceof Se?!1:u.isNonNullable(t.getItems())||u.isNonNullable(e.getItems())}resolve(e,t){return this.resolveWithContext(e,this.createResolutionContext(t))}resolveWithContext(e,t){const r=new d,i=this.mergeWithContext(r,e,t).clone().setName(e.getName()).setDescription(e.getDescription()).setBlueId(e.getBlueId());return new ee(i)}createResolutionContext(e){return{limits:e,nodeProvider:this.nodeProvider,resolvedTypeCache:new Map,inheritedItemsPrefixByPath:new Map,pathStack:[]}}resolveTypeNode(e,t){const r=e.getBlueId();if(u.isNonNullable(r)){const n=this.createResolvedTypeCacheKey(r,t),i=t.resolvedTypeCache.get(n);if(u.isNonNullable(i))return i;const o=this.resolveAndExtendTypeNode(e,t);return t.resolvedTypeCache.set(n,o),o}return this.resolveAndExtendTypeNode(e,t)}resolveAndExtendTypeNode(e,t){const r=e.clone();return u.isNonNullable(r.getBlueId())&&new pt(t.nodeProvider).extend(r,$e.withSinglePath("/")),this.resolveWithContext(r,t)}createResolvedTypeCacheKey(e,t){return t.limits instanceof Se?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 Se}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 ir{mergingProcessors;constructor(e){this.mergingProcessors=e}process(e,t,r){return this.mergingProcessors.reduce((n,i)=>i.process(n,t,r),e)}postProcess(e,t,r){return this.mergingProcessors.reduce((n,i)=>i.postProcess?i.postProcess(n,t,r):n,e)}}class or{process(e,t){const r=t.getValue();if(u.isNonNullable(r)){const n=e.getValue();if(u.isNullable(n))return e.cloneShallow().setValue(r);if(!Ys(r,n))throw new Error(`Node values conflict. Source node value: ${r}, target node value: ${n}`)}return e}}const Ys=(s,e)=>k(s)&&k(e)||Ce(s)&&Ce(e)?s.eq(e):s===e;class lr{process(e,t,r){const n=e.getType(),i=t.getType();let o=e;if(n===void 0)o=e.cloneShallow().setType(i);else if(i!==void 0){if(!B(i,n,r)){const a=m.get(i),p=m.get(n);throw new Error(`The source type '${JSON.stringify(a)}' is not a subtype of the target type '${JSON.stringify(p)}'.`)}o=e.cloneShallow().setType(i)}return o}}class ar{process(e,t,r){const n=t.getItemType(),i=t.getType();if(n!==void 0&&i!==void 0&&!we(i,r))throw new Error("Source node with itemType must have a List type");const o=e.getItemType();let l=e;if(o===void 0)n!==void 0&&(l=e.cloneShallow().setItemType(n));else if(n!==void 0){if(!B(n,o,r)){const h=m.get(n),g=m.get(o);throw new Error(`The source item type '${JSON.stringify(h)}' is not a subtype of the target item type '${JSON.stringify(g)}'.`)}l=e.cloneShallow().setItemType(n)}const a=l.getItemType(),p=t.getItems();if(a!==void 0&&p!==void 0)for(const f of p){const h=f.getType();if(h!==void 0&&!B(h,a,r)){const g=m.get(h),T=m.get(a);throw new Error(`Item of type '${JSON.stringify(g)}' is not a subtype of the list's item type '${JSON.stringify(T)}'.`)}}return l}}class ur{process(e,t,r){const n=t.getKeyType(),i=t.getValueType(),o=t.getType();if((n!==void 0||i!==void 0)&&o!==void 0&&!Ee(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(),p=l.getValueType(),f=t.getProperties();return(a!==void 0||p!==void 0)&&f!==void 0&&Object.entries(f).forEach(([h,g])=>{a!==void 0&&this.validateKeyType(h,a,r),p!==void 0&&this.validateValueType(g,p,r)}),l}processKeyType(e,t,r){const n=e.getKeyType(),i=t.getKeyType();if(n===void 0){if(i!==void 0)return this.validateBasicKeyType(i,r),e.cloneShallow().setKeyType(i)}else if(i!==void 0){if(this.validateBasicKeyType(i,r),!B(i,n,r)){const l=m.get(i),a=m.get(n);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(i)}return e}processValueType(e,t,r){const n=e.getValueType(),i=t.getValueType();if(n===void 0){if(i!==void 0)return e.cloneShallow().setValueType(i)}else if(i!==void 0){if(!B(i,n,r)){const l=m.get(i),a=m.get(n);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(i)}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(!ts(t,r))if(rs(t,r)){const n=Number.parseInt(e,10);if(Number.isNaN(n)||n.toString()!==e)throw new Error(`Key '${e}' is not a valid Integer.`)}else if(ss(t,r)){const n=Number.parseFloat(e);if(Number.isNaN(n))throw new Error(`Key '${e}' is not a valid Number.`)}else if(ns(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 n=e.getType();if(n!==void 0&&!B(n,t,r)){const i=m.get(n),o=m.get(t);throw new Error(`Value of type '${JSON.stringify(i)}' is not a subtype of the dictionary's value type '${JSON.stringify(o)}'.`)}}}class cr{process(e){return e}postProcess(e,t,r){const n=e.getType();if(n!==void 0&&is(n,r)){const i=e.getItems(),o=e.getProperties();if(i!==void 0&&i.length>0||o!==void 0&&Object.keys(o).length>0){const l=os(n,r),a=n.getName()||"unknown";throw new Error(`Node of type "${a}" (which extends basic type "${l}") must not have items, properties or contracts.`)}}return e}}class dr{process(e,t){let r=e;const n=t.getName();n!==void 0&&n!==e.getName()&&(r=r.cloneShallow().setName(n));const i=t.getDescription();return i!==void 0&&i!==r.getDescription()&&(r=r.cloneShallow().setDescription(i)),r}}const Js=Object.freeze(Object.defineProperty({__proto__:null,BasicTypesVerifier:cr,DictionaryProcessor:ur,ListProcessor:ar,MetadataPropagator:dr,SequentialMergingProcessor:ir,TypeAssigner:lr,ValuePropagator:or},Symbol.toStringTag,{value:"Module"}));function Zs(){return new ir([new or,new lr,new ar,new ur,new dr,new cr])}class Gs{nodeProvider;blueIdToInlineValue=new Map;constructor(e){const{nodeProvider:t,blueIdsMappingGenerator:r}=e;this.nodeProvider=t,Object.entries(_e).forEach(([i,o])=>{this.blueIdToInlineValue.set(i,o)});const n=r.getAllBlueIds();Object.entries(n).forEach(([i,o])=>{this.blueIdToInlineValue.has(o)||this.blueIdToInlineValue.set(o,i)})}restore(e){return E.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 n=t();if(!n||n.isInlineValue()&&n.getValue()!==void 0)return;const i=n.getBlueId();if(!i)return;const o=this.resolveInlineValue(i,n);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 n=t.getName();if(n)return this.blueIdToInlineValue.set(e,n),n;const o=this.nodeProvider.fetchFirstByBlueId(e)?.getName();if(o)return this.blueIdToInlineValue.set(e,o),o}}class Ws{runtimes;contents;aliases;constructor(e){const t=[];for(const r of e)t.push(Hs(r));this.runtimes=t,this.contents={},this.aliases={};for(const r of this.runtimes)an(this.contents,r.contents,r.name),ln(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){for(const t of this.runtimes){const r=t.toCurrentBlueIdIndex[e];if(r)return r}return e}getTypeAlias(e){const t=this.toCurrentBlueId(e),r=_e[t];if(r)return r;for(const n of this.runtimes){const i=n.typeAliasByCurrentBlueId[t];if(i)return i}}findRuntimeByBlueId(e){const t=this.toCurrentBlueId(e);for(const r of this.runtimes){const n=r.types[t];if(n)return{runtime:r,currentBlueId:t,typeMeta:n,typeAlias:r.typeAliasByCurrentBlueId[t]}}}}function Hs(s){const e=qs(s);return Object.values(s.packages).forEach(t=>{Xs(e,s,t)}),{name:s.name,repositoryVersions:s.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 qs(s){const e=Object.fromEntries(s.repositoryVersions.map((r,n)=>[r,n])),t=s.repositoryVersions[s.repositoryVersions.length-1];return{aliases:{},types:{},toCurrentBlueIdIndex:{},contents:{},schemas:[],typeAliasByCurrentBlueId:{},typePackageByCurrentBlueId:{},packageNames:new Set,repoVersionIndexById:e,currentRepoBlueId:t}}function Xs(s,e,t){if(s.packageNames.has(t.name))throw new Error(`Duplicate package name detected: ${t.name}`);s.packageNames.add(t.name),Qs(s,t),en(s,e,t),tn(s,t),rn(s,t)}function Qs(s,e){Object.entries(e.aliases).forEach(([t,r])=>{if(s.aliases[t]&&s.aliases[t]!==r)throw new Error(`Conflicting alias mapping for ${t}`);s.aliases[t]=r})}function en(s,e,t){Object.entries(t.typesMeta).forEach(([r,n])=>{if(s.types[r])throw new Error(`Duplicate type mapping for BlueId ${r}`);const i=sn(n,e,r,t.name);if(s.types[r]=i,s.typePackageByCurrentBlueId[r]=t.name,s.typeAliasByCurrentBlueId[r]=`${t.name}/${n.name}`,i.status===v.BLUE_REPOSITORY_STATUS_STABLE&&!s.toCurrentBlueIdIndex[r]&&(s.toCurrentBlueIdIndex[r]=r),i.status===v.BLUE_REPOSITORY_STATUS_STABLE)for(const o of i.versions){const l=s.toCurrentBlueIdIndex[o.typeBlueId];if(l&&l!==r)throw new Error(`Conflicting toCurrentBlueIdIndex mapping for ${o.typeBlueId}`);s.toCurrentBlueIdIndex[o.typeBlueId]=r}})}function tn(s,e){Object.entries(e.contents).forEach(([t,r])=>{s.contents[t]=r})}function rn(s,e){s.schemas.push(...Object.values(e.schemas))}function sn(s,e,t,r){if(s.status===v.BLUE_REPOSITORY_STATUS_DEV)return nn(s,e,t,r),{...s,versions:s.versions?[...s.versions]:s.versions};const n=[...s.versions??[]].sort((o,l)=>o.repositoryVersionIndex-l.repositoryVersionIndex);if(n.length===0)throw new Error(`Stable type ${r}/${s.name} (${t}) must have at least one version entry`);const i=new Set;return n.forEach(o=>{if(o.repositoryVersionIndex<0||o.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${s.name}`);if(i.has(o.repositoryVersionIndex))throw new Error(`Duplicate repositoryVersionIndex ${o.repositoryVersionIndex} for ${r}/${s.name}`);i.add(o.repositoryVersionIndex);for(const l of o.attributesAdded??[])on(l,e.name,t,o.repositoryVersionIndex)}),{...s,versions:n}}function nn(s,e,t,r){if(s.status===v.BLUE_REPOSITORY_STATUS_DEV){if(s.versions&&s.versions.length>1)throw new Error(`Dev type ${r}/${s.name} (${t}) must not declare multiple versions`);if(s.versions&&s.versions.length===1){const n=s.versions[0];if(n.repositoryVersionIndex<0||n.repositoryVersionIndex>=e.repositoryVersions.length)throw new Error(`Invalid repositoryVersionIndex ${n.repositoryVersionIndex} for dev type ${r}/${s.name}`)}}}function on(s,e,t,r){try{v.validateAttributesAddedPointer(s)}catch(n){const i=n instanceof Error?n.message:"Unknown error";throw new Error(`Invalid attributesAdded pointer '${s}' for type ${t} in repository ${e} at index ${r}: ${i}`)}}function ln(s,e,t){for(const[r,n]of Object.entries(e)){const i=s[r];if(i&&i!==n)throw new Error(`Conflicting alias '${r}' across repositories: '${i}' vs '${n}' (from ${t})`);s[r]=n}}function an(s,e,t){for(const[r,n]of Object.entries(e)){if(r in s){const i=s[r];if(!un(i,n))throw new Error(`Conflicting content for BlueId '${r}' across repositories (from ${t})`);continue}s[r]=n}}function un(s,e){if(s===e)return!0;if(s===null||e===null||typeof s!="object"||typeof e!="object")return!1;const t=Ae.canonicalize(s),r=Ae.canonicalize(e);return t!==void 0&&t===r}class Oe extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r&&r.length>0?r:[],this.name="BlueError"}}const L={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"},cn=new Set(["__proto__","constructor","prototype"]);function Tt(s){const e=s.at(0),t=s.at(-1);return!e||!t?s:e==="'"&&t==="'"||e==='"'&&t==='"'?s.slice(1,-1):s}function dn(s,e){const t=s.indexOf("=");if(t===-1)throw se(e,`Missing '=' in segment '${s.trim()}'`);if(s.indexOf("=",t+1)!==-1)throw se(e,`Unexpected '=' in segment '${s.trim()}'`);const r=Tt(s.slice(0,t).trim()),n=Tt(s.slice(t+1).trim());if(!r)throw se(e,"Repository name is empty");if(!n)throw se(e,`Repository BlueId is empty for '${r}'`);return{name:r,value:n}}function pn(s){if(s.trim().length===0)return Object.create(null);const e=Object.create(null);for(const t of s.split(",")){const r=t.trim();if(!r)throw se(s,"Empty repository segment");const{name:n,value:i}=dn(r,s);fn(n,s),e[n]=i}return e}function hn(s){return typeof s=="string"?pn(s):s}function se(s,e){return new Oe(L.INVALID_BLUE_CONTEXT_REPOSITORIES,`Invalid BlueContext repositories value: ${e}`,[{code:L.INVALID_BLUE_CONTEXT_REPOSITORIES,message:e,locationPath:[],context:{rawRepositories:s,reason:e}}])}function fn(s,e){if(cn.has(s))throw se(e,`Forbidden repository name '${s}'`)}function yn(s,e){const t=s.filter(n=>n.repositoryVersionIndex>e).sort((n,i)=>i.repositoryVersionIndex-n.repositoryVersionIndex),r=[];for(const n of t){const i=[...n.attributesAdded].sort((o,l)=>bt(l)-bt(o));r.push(...i)}return r}function bt(s){return v.parsePointer(s).length}const gn=new Set([...et]),w={core:"core",noRuntime:"no-runtime",noTargetContext:"no-target-context",representable:"representable",unrepresentable:"unrepresentable"};class mn{registry;targetRepoVersionIndexes;fallbackToCurrentInlineDefinitions;inliningStack=new Set;constructor(e){this.registry=e.registry,this.targetRepoVersionIndexes=e.targetRepoVersionIndexes,this.fallbackToCurrentInlineDefinitions=e.fallbackToCurrentInlineDefinitions}transform(e){return E.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(),n=r?.getBlueId();if(!r||!n)return;const i=this.resolveType(n);switch(i.kind){case w.core:{r.setBlueId(i.blueId);return}case w.representable:{this.applyDropPointers([r],i.dropPointers,{rootIsSchema:!0}),this.applyDropPointers(t.schemaTraversalTargets,i.dropPointers),r.setBlueId(i.targetBlueId);return}case w.noRuntime:case w.noTargetContext:case w.unrepresentable:{if(this.fallbackToCurrentInlineDefinitions){this.inlineDefinition(e,t.setter,n);return}throw i.kind===w.unrepresentable?i.error:this.unrepresentableError(n,i.kind===w.noTargetContext?`Repository '${i.runtimeName}' not provided in BlueContext.`:"Type does not belong to any declared repository.",i.kind===w.noTargetContext?i.runtime:void 0,i.kind===w.noTargetContext?i.meta:void 0,void 0,i.kind===w.noTargetContext?i.typeAlias:void 0)}}}resolveType(e){if(re.includes(e))return{kind:w.core,blueId:e};const t=this.registry.toCurrentBlueId(e),r=this.registry.getTypeAlias(t),n=this.registry.findRuntimeByBlueId(t);if(!n||!n.typeMeta)return{kind:w.noRuntime};const i=this.targetRepoVersionIndexes[n.runtime.name];if(i===void 0)return{kind:w.noTargetContext,currentBlueId:t,runtimeName:n.runtime.name,runtime:n.runtime,meta:n.typeMeta,typeAlias:r};const o=n.typeMeta;if(o.status===v.BLUE_REPOSITORY_STATUS_DEV){const h=n.runtime.repositoryVersions.length-1;if(i!==h)return{kind:w.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Dev type cannot be represented at repository version index ${i}.`,n.runtime,o,i,r)};const g=o.versions?.[0];return{kind:w.representable,currentBlueId:t,targetBlueId:g?.typeBlueId??t,dropPointers:[]}}const l=o.versions||[];if(l.length===0)return{kind:w.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Stable type metadata missing versions for ${t}.`,n.runtime,o,i,r)};const a=l[0].repositoryVersionIndex;if(i<a)return{kind:w.unrepresentable,currentBlueId:t,error:this.unrepresentableError(t,`Type introduced after target repository version index ${i}.`,n.runtime,o,i,r)};let p=l[0].typeBlueId;for(const h of l)h.repositoryVersionIndex<=i&&(p=h.typeBlueId);const f=o.status===v.BLUE_REPOSITORY_STATUS_STABLE?this.getDropPointers(o,i):[];return{kind:w.representable,currentBlueId:t,targetBlueId:p,dropPointers:f}}getDropPointers(e,t){return e.status!==v.BLUE_REPOSITORY_STATUS_STABLE?[]:yn(e.versions,t)}applyDropPointers(e,t,r={}){if(e.length===0||t.length===0)return;const n=r.rootIsSchema??!1;for(const i of t)for(const o of e)this.deletePropertyAtPointer(o,i,n)}getDictionaryValueTargets(e){const t=e.getProperties();return t?Object.entries(t).filter(([r,n])=>n instanceof d&&!gn.has(r)).map(([,r])=>r):[]}deletePropertyAtPointer(e,t,r){let n;try{n=v.parsePointer(t)}catch{throw this.invalidPointerError(t)}this.applyPointerSegments(e,n,r)}applyPointerSegments(e,t,r){if(t.length===0)return;const[n,...i]=t;if(n===Q){const a=e.getType();a&&this.applyPointerSegments(a,i,!0);return}if(n===ye){const a=e.getItemType();a&&this.applyPointerSegments(a,i,!0);return}if(n===ge){const a=e.getKeyType();a&&this.applyPointerSegments(a,i,!0);return}if(n===me){const a=e.getValueType();a&&this.applyPointerSegments(a,i,!0);return}const o=e.getProperties();if(!o)return;if(i.length===0){if(!r||!(n in o))return;const a={...o};delete a[n],e.setProperties(a);return}const l=o[n];l instanceof d&&this.applyPointerSegments(l,i,r)}inlineDefinition(e,t,r){const n=this.registry.toCurrentBlueId(r);if(this.inliningStack.has(n))throw this.unrepresentableError(n,"Cycle detected while inlining type.",void 0,void 0,void 0,void 0,{cycle:Array.from(this.inliningStack).concat(n)});const i=this.registry.getContents()[n];if(!i)throw this.unrepresentableError(n,`Missing definition to inline for BlueId ${n}.`);this.inliningStack.add(n);try{const o=y.deserialize(i);o.setBlueId(void 0);const l=E.transform(o,a=>this.transformNode(a));return t(l),e}finally{this.inliningStack.delete(n)}}invalidPointerError(e){const t=`Invalid attributesAdded pointer '${e}'.`;return new Oe(L.INVALID_REPOSITORY_POINTER,t,[{code:L.INVALID_REPOSITORY_POINTER,message:t,locationPath:[],context:{pointer:e}}])}unrepresentableError(e,t,r,n,i,o,l){const a={currentTypeBlueId:e,targetRepoVersionIndex:i,typeAlias:o,...l};if(r&&(i!==void 0&&(a.requestedRepoBlueId=r.repositoryVersions[i]),a.serverRepoBlueId=r.currentRepoBlueId),n&&n.status===v.BLUE_REPOSITORY_STATUS_STABLE){const f=n.versions?.[0]?.repositoryVersionIndex;f!==void 0&&(a.typeIntroducedInRepoBlueId=r?.repositoryVersions[f])}const p={code:L.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,message:t,locationPath:[Q],context:a};return new Oe(L.REPO_UNREPRESENTABLE_IN_TARGET_VERSION,t,[p])}}function Qe(s,e){return e?E.transform(s,t=>(Be(()=>t.getType(),r=>t.setType(r),e),Be(()=>t.getItemType(),r=>t.setItemType(r),e),Be(()=>t.getKeyType(),r=>t.setKeyType(r),e),Be(()=>t.getValueType(),r=>t.setValueType(r),e),t)):s}function Be(s,e,t){const r=s();if(!r||r.isInlineValue())return;const n=r.getBlueId();if(!n)return;const i=t.toCurrentBlueId(n);i!==n&&e(r.clone().setBlueId(i))}class In{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 n=Qe(e,this.blueIdMapper);return new mn({registry:this.registry,targetRepoVersionIndexes:r,fallbackToCurrentInlineDefinitions:t.fallbackToCurrentInlineDefinitions!==!1}).transform(n)}computeTargetRepoVersionIndexes(e){const t={};if(!e?.repositories)return t;const r=typeof e.repositories=="string"?hn(e.repositories):e.repositories;for(const[n,i]of Object.entries(r)){const o=this.registry.findRuntimeByName(n);if(!o)continue;const l=o.repoVersionIndexById[i];if(l===void 0)throw this.unknownRepoBlueIdError(n,i,o.currentRepoBlueId);t[n]=l}return t}unknownRepoBlueIdError(e,t,r){const n=`Unknown RepoBlueId '${t}' for repository '${e}'.`,i={code:L.REPO_UNKNOWN_REPO_BLUE_ID,message:n,locationPath:[],context:{repoName:e,requestedRepoBlueId:t,serverRepoBlueId:r}};return new Oe(L.REPO_UNKNOWN_REPO_BLUE_ID,n,[i])}}class Tn{nodeProvider;typeSchemaResolver;blueDirectivePreprocessor;urlContentFetcher;blueIdsMappingGenerator;globalLimits=j;mergingProcessor;repositories;repositoryRegistry;blueContextResolver;constructor(e={}){const{nodeProvider:t,typeSchemaResolver:r=null,urlFetchStrategy:n,repositories:i,mergingProcessor:o}=e;this.repositories=i,this.repositoryRegistry=new Ws(i??[]),this.blueContextResolver=new In({registry:this.repositoryRegistry,blueIdMapper:this.repositoryRegistry});const l=vs(()=>[]);this.nodeProvider=fe.wrap(t||l,i),this.typeSchemaResolver=r??new Zt([],{nodeProvider:this.nodeProvider}),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this.mergingProcessor=o??Zs(),this.urlContentFetcher=new Ks(n),this.blueDirectivePreprocessor=new zs(void 0,this.urlContentFetcher),this.blueIdsMappingGenerator=new ht,this.blueIdsMappingGenerator.registerBlueIds(this.repositoryRegistry.getAliases());const a=this.repositoryRegistry.getRuntimes().flatMap(p=>p.schemas);a.length>0&&this.typeSchemaResolver?.registerSchemas(a)}nodeToJson(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),n=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return m.get(n,r.format)}nodeToYaml(e,t="official"){const r=this.normalizeNodeToJsonOptions(t),n=r.blueContext?this.blueContextResolver.transform(e,r.blueContext):e;return Ss.get(n,{strategy:r.format})}nodeToSchemaOutput(e,t){return new bs(this.typeSchemaResolver).convert(e,t)}resolve(e,t=j){const r=this.combineWithGlobalLimits(t);return new nr(this.mergingProcessor,this.nodeProvider).resolve(e,r)}createResolvedNode(e){return e instanceof ee?e:new ee(e)}reverse(e){return new Wt().reverse(e)}restoreInlineTypes(e){return new Gs({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).restore(e)}extend(e,t){const r=this.combineWithGlobalLimits(t);new pt(this.nodeProvider).extend(e,r)}jsonValueToNode(e){const t=this.preprocess(y.deserialize(e));return Qe(t,this.repositoryRegistry)}async jsonValueToNodeAsync(e){const t=await this.preprocessAsync(y.deserialize(e));return Qe(t,this.repositoryRegistry)}yamlToNode(e){const t=$(e);if(!t)throw new Error("Failed to parse YAML to JSON");return this.jsonValueToNode(t)}async yamlToNodeAsync(e){const t=$(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 I.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 I.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 oe({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}async preprocessAsync(e){const t=await this.blueDirectivePreprocessor.processAsync(e);return new oe({nodeProvider:this.nodeProvider,blueIdsMappingGenerator:this.blueIdsMappingGenerator}).preprocessWithDefaultBlue(t)}transform(e,t){return E.transform(e,t)}getNodeProvider(){return this.nodeProvider}setNodeProvider(e){return this.nodeProvider=fe.wrap(e,this.repositories),this.typeSchemaResolver?.setNodeProvider(this.nodeProvider),this}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 O.isTypeOf(e,t,{checkSchemaExtensions:r?.checkSchemaExtensions,typeSchemaResolver:this.typeSchemaResolver})}isTypeOfBlueId(e,t){const r=t.trim();if(r.length===0)return!1;const n=e.getType();if(!n)return!1;const i=new d().setBlueId(r);return B(n,i,this.nodeProvider)}isTypeOfNode(e,t){return new ls(this).matchesType(e,t,this.globalLimits)}setGlobalLimits(e){return this.globalLimits=e??j,this}getGlobalLimits(){return this.globalLimits}normalizeNodeToJsonOptions(e){return typeof e=="string"?{format:e,blueContext:void 0}:{format:e?.format??"official",blueContext:e?.blueContext}}combineWithGlobalLimits(e){return this.globalLimits==j?e:e==j?this.globalLimits:je.of(this.globalLimits,e)}}class bn extends Qt{blueIdToContentMap=new Map;blueIdToMultipleDocumentsMap=new Map;preprocessor;constructor(e=[]){super();const t=new oe({nodeProvider:this});this.preprocessor=r=>t.preprocessWithDefaultBlue(r),e.forEach(r=>this.processNode(r))}processNode(e){ve.hasItemsOnly(e)?this.processNodeWithItems(e):this.processSingleNode(e)}processSingleNode(e){const t=H.parseAndCalculateBlueIdForNode(e,this.preprocessor);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;this.processNodeList(t);const r=H.parseAndCalculateBlueIdForNodeList(t,this.preprocessor);this.blueIdToContentMap.set(r.blueId,r.content),this.blueIdToMultipleDocumentsMap.set(r.blueId,!0),t.forEach((n,i)=>{const o=n.getName();o&&this.addToNameMap(o,`${r.blueId}#${i}`)})}processNodeList(e){const t=I.calculateBlueIdSync(e),r=e.map(n=>m.get(n));this.blueIdToContentMap.set(t,r),this.blueIdToMultipleDocumentsMap.set(t,!0)}fetchContentByBlueId(e){const t=this.blueIdToContentMap.get(e),r=this.blueIdToMultipleDocumentsMap.get(e);return t!==void 0&&r!==void 0?H.resolveThisReferences(t,e,r):null}addSingleNodes(...e){e.forEach(t=>this.processNode(t))}addSingleDocs(...e){e.forEach(t=>{const r=$(t);if(r!==void 0){const n=y.deserialize(r);this.processNode(n)}})}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){this.processNodeList(e),e.forEach(t=>this.processNode(t))}addListAndItsItemsFromDoc(e){const t=$(e);if(t!==void 0){const n=y.deserialize(t).getItems();n&&this.addListAndItsItems(n)}}addListAndItsItems(e){Array.isArray(e)?this.addListAndItsItemsFromNodes(e):this.addListAndItsItemsFromDoc(e)}addList(e){this.processNodeList(e)}}exports.Base58Sha256Provider=Ot;exports.BasicNodeProvider=bn;exports.Blue=Tn;exports.BlueIdCalculator=I;exports.BlueIdToCid=xr;exports.BlueNode=d;exports.BlueNodeTypeSchema=O;exports.JsonCanonicalizer=Ae;exports.Limits=Fe;exports.Merger=nr;exports.MergingProcessors=Js;exports.NodeResolver=sr;exports.Nodes=ve;exports.Properties=mr;exports.ResolvedBlueNode=ee;exports.TypeSchemaResolver=Zt;exports.applyBlueNodePatch=Yr;exports.baseBlueObjectSchema=Te;exports.blueDescriptionField=Zr;exports.blueIdField=Wr;exports.blueIdSchema=Tr;exports.blueNameField=Hr;exports.blueNodeField=qr;exports.blueObjectBooleanValueSchema=Nr;exports.blueObjectNumberValueSchema=vr;exports.blueObjectSchema=ne;exports.blueObjectStringListItemsSchema=Br;exports.blueObjectStringValueSchema=br;exports.calculateBlueId=tr;exports.calculateBlueIdSync=Ds;exports.enrichWithBlueId=qe;exports.getBlueDescriptionAnnotation=jt;exports.getBlueIdAnnotation=Ut;exports.getBlueNameAnnotation=kt;exports.getBlueNodeAnnotation=Yt;exports.getBlueObjectItems=xs;exports.getBlueObjectProperties=Fs;exports.getBlueObjectTypeLabel=$s;exports.getBlueObjectValue=_s;exports.getTypeBlueIdAnnotation=Jt;exports.hasBlueObjectBlueIdDefined=Ct;exports.hasBlueObjectItemsDefined=At;exports.hasBlueObjectNameDefined=Er;exports.hasBlueObjectTypeDefined=Rt;exports.hasBlueObjectValueDefined=Vt;exports.isBigDecimalNumber=Ce;exports.isBigIntegerNumber=k;exports.isBigNumber=R;exports.isBlueNodeSchema=ct;exports.isBlueObject=wr;exports.isBlueObjectResolved=rr;exports.isGivenBlueObjectTypeSchema=Sr;exports.isJsonBlueArray=ot;exports.isJsonBlueObject=it;exports.isJsonBlueValue=Ar;exports.isUrl=ce;exports.jsonBlueValueSchema=pe;exports.normalizeToBlueObject=js;exports.resolveBlueObjectItems=Xe;exports.withBlueDescription=$t;exports.withBlueId=Lt;exports.withBlueName=zt;exports.withBlueNode=Kt;exports.withTypeBlueId=Qr;exports.yamlBlueDump=qt;exports.yamlBlueParse=$;
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;