@docx-editor.dev/pro 2.12.0 → 2.13.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 (36) hide show
  1. package/README.md +27 -6
  2. package/dist/chunk-ABW4JBFQ.js +3 -0
  3. package/dist/chunk-L6J5LQXZ.cjs +3 -0
  4. package/dist/chunk-MTNG3CRI.js +3 -0
  5. package/dist/chunk-VRIYIY2Y.cjs +3 -0
  6. package/dist/collaboration/hocuspocus.cjs +1 -1
  7. package/dist/collaboration/hocuspocus.js +1 -1
  8. package/dist/collaboration/index.cjs +2 -2
  9. package/dist/collaboration/index.js +1 -1
  10. package/dist/collaboration/webrtc.cjs +1 -1
  11. package/dist/collaboration/webrtc.js +1 -1
  12. package/dist/document-session-2QOWIMD7.js +1 -0
  13. package/dist/document-session-2YB34CXA.js +1 -0
  14. package/dist/document-session-BIMEOZBG.cjs +1 -0
  15. package/dist/document-session-DPSXU7I7.cjs +1 -0
  16. package/dist/{hocuspocus-FC5NXRLW.js → hocuspocus-ABVDFDOK.js} +1 -1
  17. package/dist/{hocuspocus-3FLNEX7M.cjs → hocuspocus-IIJMOMM5.cjs} +1 -1
  18. package/dist/react/index.cjs +1 -1
  19. package/dist/react/index.js +1 -1
  20. package/dist/vue/hocuspocus.cjs +1 -1
  21. package/dist/vue/hocuspocus.js +1 -1
  22. package/dist/vue/index.cjs +1 -1
  23. package/dist/vue/index.js +1 -1
  24. package/dist/vue/webrtc.cjs +1 -1
  25. package/dist/vue/webrtc.js +1 -1
  26. package/dist/{webrtc-UAS5I63G.cjs → webrtc-2WNLDNHU.cjs} +1 -1
  27. package/dist/{webrtc-V2JQ2NO7.js → webrtc-PZCIQ4FZ.js} +1 -1
  28. package/package.json +4 -4
  29. package/dist/chunk-C4RVARMI.cjs +0 -3
  30. package/dist/chunk-DHIPX767.js +0 -3
  31. package/dist/chunk-KOGVHJ7U.js +0 -3
  32. package/dist/chunk-QA3F5EUJ.cjs +0 -3
  33. package/dist/document-session-I77CU7RQ.cjs +0 -1
  34. package/dist/document-session-MTK2LEYT.cjs +0 -1
  35. package/dist/document-session-NFUE7UBO.js +0 -1
  36. package/dist/document-session-WEZH77T3.js +0 -1
@@ -1,3 +0,0 @@
1
- 'use strict';var R=require('yjs'),store=require('@docx-editor.dev/core/store'),collaboration=require('@docx-editor.dev/core/collaboration'),layout=require('@docx-editor.dev/core/layout'),replication=require('@docx-editor.dev/core/collaboration/replication');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var R__namespace=/*#__PURE__*/_interopNamespace(R);var Wn=new Set(["paraId","textId","id","numId","bookmarkId"]);function et(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}function tt(t){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),et(e)}function we(t){return /^[0-9a-f]{32}$/.test(t)}function nt(t,e){if(!we(t))throw new Error("invalid replica identity");if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid logical-id counter");return `lid:${t}:${e.toString(10)}`}function Re(t,e){return `yjs:${t}:${e}`}function Ce(t){let e=[];for(let n of t)Wn.has(n.localName)&&e.push(n.value);return e}var W=class{replicaId;next=0;constructor(e){if(this.replicaId=e??tt(),!we(this.replicaId))throw new Error("invalid replica identity")}take(){let e=nt(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};var O=Object.freeze({maxNodes:2e5,maxTreeDepth:256,maxTextLength:1048576,maxAttributes:4096,maxChildren:1e5,maxParts:512,maxRelationships:1e4,maxBlobBytes:32*1024*1024,maxDigestLength:80,maxMediaTypeLength:256,maxStorageKeyLength:512,maxStringLength:4096}),Xn=/^sha256:[0-9a-f]{64}$/;function ot(t){return t?Object.freeze({...O,...t}):O}function g(t){return store.isDangerousKey(t)?"prototype-key":null}function C(t,e){return typeof t!="string"||t.length>e?"invalid-string":store.isDangerousKey(t)?"prototype-key":null}function w(t){let e=g(t);if(e)return e;if(typeof t!="string"||t.length===0)return "unsafe-part-name";let n=store.normalizePartName(t);return !n.ok||n.partName!==t?"unsafe-part-name":null}function it(t){for(let e of Object.keys(t)){let n=g(e);if(n)return n}return !Xn.test(t.digest)||t.digest.length>80||!Number.isSafeInteger(t.size)||t.size<0?"invalid-blob-descriptor":t.size>O.maxBlobBytes?"blob-too-large":C(t.mediaType,O.maxMediaTypeLength)||t.mediaType.length===0||C(t.storageKey,O.maxStorageKeyLength)||t.storageKey.length===0?"invalid-blob-descriptor":null}var at=1,st=2,lt=1,dt=1,Jn="docx-package-meta-v1",Hn="docx-package-nodes-v1",Gn="docx-package-parts-v1",qn="docx-package-rels-v1",Zn="docx-package-overrides-v1",Qn="docx-package-defaults-v1",er="docx-package-binaries-v1",tr="docx-package-namespaces-v1",nr="docx-package-attributes-v1",rr="docx-package-bindings-v1",z="s",B="t",ie="children",_="deleted",$="replacedBy",S="",ct="-",ut=Object.freeze({kind:"docx-package-bootstrap"}),pt=Object.freeze({kind:"docx-package-journal"});function ae(t){return t.kind==="textValue"}function v(t){return !ae(t)}var or=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),ir=200;function ht(t){let e=new Map;for(let n of t)or.has(n.code)&&e.set(n.code,(e.get(n.code)??0)+1);return e.size===0?null:[...e].sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${n}=${r}`).join(",").slice(0,ir)}function mt(t){return {meta:t.getMap(Jn),nodes:t.getMap(Hn),parts:t.getMap(Gn),relationships:t.getMap(qn),overrides:t.getMap(Zn),defaults:t.getMap(Qn),binaries:t.getMap(er),namespaces:t.getMap(tr),attributes:t.getMap(nr),bindings:t.getMap(rr)}}var gt=[["http://schemas.openxmlformats.org/wordprocessingml/2006/main","w"],["http://schemas.openxmlformats.org/officeDocument/2006/relationships","r"],["http://schemas.openxmlformats.org/package/2006/relationships","pr"],["http://schemas.openxmlformats.org/package/2006/content-types","ct"],["http://www.w3.org/XML/1998/namespace","xml"],["http://www.w3.org/2000/xmlns/","xmlns"],["http://schemas.openxmlformats.org/drawingml/2006/main","a"],["http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing","wp"],["http://schemas.openxmlformats.org/drawingml/2006/picture","pic"],["http://schemas.openxmlformats.org/officeDocument/2006/math","m"],["http://schemas.openxmlformats.org/markup-compatibility/2006","mc"],["http://schemas.microsoft.com/office/word/2010/wordml","w14"],["http://schemas.microsoft.com/office/word/2012/wordml","w15"],["http://schemas.microsoft.com/office/word/2015/wordml/symex","w16se"],["http://schemas.microsoft.com/office/word/2016/wordml/cid","w16cid"],["http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument","od"],["http://schemas.openxmlformats.org/officeDocument/2006/extended-properties","ep"],["http://schemas.openxmlformats.org/package/2006/metadata/core-properties","cp"],["http://purl.org/dc/elements/1.1/","dc"],["http://purl.org/dc/terms/","dcterms"],["http://www.w3.org/2001/XMLSchema-instance","xsi"],["http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes","vt"],["http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas","wpc"],["http://schemas.microsoft.com/office/word/2010/wordprocessingGroup","wpg"],["http://schemas.microsoft.com/office/word/2010/wordprocessingInk","wpi"],["http://schemas.microsoft.com/office/word/2010/wordprocessingShape","wps"],["http://schemas.openxmlformats.org/drawingml/2006/chart","c"],["http://schemas.openxmlformats.org/schemaLibrary/2006/main","sl"]],ar=new Map(gt),sr=new Map(gt.map(([t,e])=>[e,t]));function lr(t){let e=0xcbf29ce484222325n,n=0x100000001b3n;for(let r=0;r<t.length;r+=1)e^=BigInt(t.charCodeAt(r)),e=e*n&0xffffffffffffffffn;return e.toString(16).padStart(16,"0")}function X(t){return t.length===0?ct:ar.get(t)??`n${lr(t)}`}function j(t,e,n){let r=X(e);return e.length===0||g(r)||C(e,n)||t.get(r)!==e&&t.set(r,e),r}function J(t,e){if(e===ct||g(e))return "";let n=t.get(e);return typeof n=="string"?n:sr.get(e)??""}function Le(t,e,n,r){return `${t}${S}${e}${S}${n}${S}${r}`}function se(t){let e=t.split(S);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function ke(t,e,n){return `${t}${S}${e}${S}${n}`}function le(t){let e=t.split(S);if(e.length!==3)return null;let n=e[0],r=e[1],o=e[2];return n.length===0||o.length===0?null:{logicalId:n,namespaceId:r,localName:o}}function Pe(t,e){return `${t}${S}${e}`}function de(t){let e=t.split(S);if(e.length!==2)return null;let n=e[0],r=e[1];return n.length===0?null:{logicalId:n,prefix:r}}function ft(t,e){return `${t}${S}${e}`}function yt(t){let e=t.indexOf(S);return e<0?{prefix:"",value:t}:{prefix:t.slice(0,e),value:t.slice(e+1)}}function bt(t){let e=new R__namespace.Map;e.set(z,Le(t.kind,t.namespaceId,t.localName,t.prefix??""));let n=new R__namespace.Array;return t.childIds&&t.childIds.length>0&&n.push([...t.childIds]),e.set(ie,n),e}function It(t){let e=new R__namespace.Map;return e.set(B,new R__namespace.Text(t)),e}function xt(t,e,n){let r=new R__namespace.Map;return r.set("id",t),r.set("rootId",e),r.set("contentType",n),r}function vt(t){let e=new R__namespace.Map;return e.set("ownerPart",t.ownerPart),e.set("id",t.id),e.set("type",t.type),e.set("rawTarget",t.rawTarget),e.set("targetMode",t.targetMode),e.set("order",t.order),e}function St(t){let e=new R__namespace.Map;return e.set("digest",t.digest),e.set("size",t.size),e.set("mediaType",t.mediaType),e.set("storageKey",t.storageKey),e}function Et(t){t.set("protocolVersion",at),t.set("sharedSchemaVersion",st),t.set("repairVersion",lt),t.set("canonicalModelVersion",dt),t.set("initialized",true);}function b(t){return t instanceof R__namespace.Map}function k(t){if(!b(t))return null;let e=t.get(ie);return e instanceof R__namespace.Array?e:null}function H(t){return b(t)&&t.get(B)instanceof R__namespace.Text}function U(t){return b(t)&&t.get(_)===true}function Ae(t){if(!b(t))return null;let e=t.get($);return typeof e=="string"&&e.length>0?e:null}function ce(t){return typeof t=="string"?t:""}function wt(t,e){return t<e?-1:t>e?1:0}function Oe(t,e){return `${t}${S}${e}`}function cr(t){let e=t.indexOf(S);return e<0?t:t.slice(0,e)}function Rt(t){let e=[];return t.forEach((n,r)=>{!b(n)||g(r)||n.forEach(o=>{if(!b(o))return;let i=ce(o.get("id")),a=ce(o.get("type"));if(i.length===0||a.length===0)return;let s=ce(o.get("ownerPart"))||cr(r);if(g(s))return;let l=o.get("order");e.push({ownerPart:s,id:i,type:a,rawTarget:ce(o.get("rawTarget")),targetMode:o.get("targetMode")==="External"?"External":"Internal",order:typeof l=="number"&&Number.isSafeInteger(l)?l:0});});}),e.sort((n,r)=>n.order-r.order||wt(n.ownerPart,r.ownerPart)||wt(n.id,r.id)),e}function Ct(t,e){return t.nodes.observeDeep(e.onNodeEvents),t.attributes.observe(e.onAttributeEvent),t.bindings.observe(e.onBindingEvent),t.relationships.observeDeep(e.onRelationshipChange),t.parts.observeDeep(e.onPartChange),()=>{t.nodes.unobserveDeep(e.onNodeEvents),t.attributes.unobserve(e.onAttributeEvent),t.bindings.unobserve(e.onBindingEvent),t.relationships.unobserveDeep(e.onRelationshipChange),t.parts.unobserveDeep(e.onPartChange);}}function ur(t,e){let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1){let o=t[r]-e[r];if(o!==0)return o}return t.length-e.length}function Lt(t,e){let n=t.childrenSnapshot.get(e);return n||(k(t.nodes.get(e))?.toArray()??[])}function pr(t,e){let n=t.nodes.get(e);return !b(n)||U(n)}function hr(t,e,n,r){let o=[],i=new Set,a=r,s;for(;;){if(i.has(a)||(i.add(a),pr(t,a)))return null;s=e.get(a);let c=t.parentIndex.get(a);if(s!==void 0){if(c!==void 0)return "fallback";break}if(c===void 0)return n.has(a)?"deferred":null;o.push(a),a=c;}let l=[s],d=a;for(let c=o.length-1;c>=0;c-=1){let h=o[c],u=Lt(t,d).indexOf(h);if(u<0)return null;l.push(u),d=h;}return l}function kt(t,e){let n=new Set(e);for(let i of n)t.parentIndex.delete(i);let r=new Map;t.partRoots.forEach((i,a)=>{r.has(i)||r.set(i,a);});let o=[...n];for(;o.length>0;){let i=[];for(let a of o){let s=null,l=false;for(let d of t.listings.get(a)??[]){if(d===a)continue;let c=hr(t,r,n,d);if(c==="fallback")return false;if(c==="deferred"){l=true;continue}if(c===null)continue;let h=Lt(t,d).indexOf(a);if(h<0)continue;let u=[...c,h];(!s||ur(u,s.rank)<0)&&(s={rank:u,parent:d});}if(l){i.push(a);continue}s&&t.parentIndex.set(a,s.parent),n.delete(a);}if(i.length===o.length)return false;o=i;}return true}function Pt(t,e){let{nodes:n,parentIndex:r,childrenSnapshot:o,partRoots:i}=t;if(e)for(let a of e)r.delete(a);for(let a of i){let s=new Set,l=[{id:a,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){s.delete(d.id);continue}let c=d.id;if(d.parent!==null&&(e===null||e.has(c))&&(r.has(c)||r.set(c,d.parent)),s.has(c))continue;let h=n.get(c);if(!b(h)||U(h))continue;let u=o.get(c)??k(h)?.toArray()??[];s.add(c),l.push({id:c,parent:null,exit:true});let m=new Set,f=[];for(let y of u)m.has(y)||y===c||(m.add(y),f.push(y));for(let y=f.length-1;y>=0;y-=1)l.push({id:f[y],parent:c,exit:false});}}}function At(t,e){return `${t}${S}${e}`}function Ne(t,e,n,r,o){if(g(n)||g(r.localName))return;let i=j(t.namespaces,r.namespaceUri,e),a=ke(n,i,r.localName);g(a)||t.attributes.set(a,ft(r.prefix??"",o));}function Ot(t,e,n,r){t.attributes.delete(ke(e,X(n),r));}function Me(t,e,n,r,o){if(g(n)||g(r))return;let i=j(t.namespaces,o,e),a=Pe(n,r);g(a)||t.bindings.set(a,i);}function Nt(t,e,n){t.bindings.delete(Pe(e,n));}function Te(t,e,n,r,o,i){let{prefix:a,value:s}=yt(i),l=e.get(n);l||(l=new Map,e.set(n,l)),l.set(At(r,o),{namespaceUri:J(t.namespaces,r),localName:o,prefix:a.length>0?a:void 0,value:s});}function Mt(t,e,n,r){let o=t.get(e);o&&(o.delete(At(n,r)),o.size===0&&t.delete(e));}function De(t,e,n,r,o){let i=e.get(n);i||(i=new Map,e.set(n,i)),i.set(r,{prefix:r,namespaceUri:J(t.namespaces,o)});}function Tt(t,e,n){let r=t.get(e);r&&(r.delete(n),r.size===0&&t.delete(e));}function Bt(t,e){let n=t.get(e);if(!b(n))return null;if(H(n)){let r=n.get(B);return {isText:true,textLength:r instanceof R__namespace.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:k(n)?.toArray()??[]}}function _t(t,e){let n=t.get(e);if(!b(n))return null;if(H(n))return "textValue";let r=n.get(z);return se(typeof r=="string"?r:"").kind}function Ut(t,e){if(t.length!==e.length)return false;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return false;return true}function K(t){return typeof t=="string"?t:""}function Yt(t){let e=[];return t.forEach((n,r)=>{if(!b(n)||g(r))return;let o=K(n.get("rootId"));o.length!==0&&e.push({name:r,id:K(n.get("id")),rootLogicalId:o,contentType:K(n.get("contentType"))});}),e.sort((n,r)=>n.name<r.name?-1:n.name>r.name?1:0),e}function zt(t){let e=new Map;return t.forEach((n,r)=>{typeof n=="string"&&!g(r)&&e.set(store.partNameKey(r),n);}),e}function jt(t){let e=new Map;return t.forEach((n,r)=>{typeof n=="string"&&!g(r)&&e.set(r,n);}),e}function Kt(t){let e=[];return t.forEach((n,r)=>{if(!b(n)||g(r))return;let o=K(n.get("digest")),i=n.get("size"),a=K(n.get("mediaType")),s=K(n.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:a,storageKey:s});}),e}function gr(t){return t?._item??null}function fr(t){return t.content instanceof R__namespace.ContentType}function Vt(t){return e=>{let n=e.parent;if(n===null)return true;if(n===t)return false;let r=gr(n);return r===null||r.parent!==t?true:!fr(e)}}function yr(t){let e=t._item;return e?Re(e.id.client,e.id.clock):null}function $t(t){return typeof t=="string"?t:""}var A=class{constructor(e,n){this.doc=e;this.schema=mt(e),this.limits=ot(n),this.stopObserving=Ct(this.schema,{onNodeEvents:r=>{this.bulkLoad>0||this.applyChildArrayEvents(r);},onAttributeEvent:r=>{this.bulkLoad>0||this.applyAttributeMapEvent(r);},onBindingEvent:r=>{this.bulkLoad>0||this.applyBindingMapEvent(r);},onRelationshipChange:()=>{this.relationshipCountCache=-1;},onPartChange:()=>{this.partCountCache=-1;}});}doc;schema;limits;parentIndex=new Map;listings=new Map;childrenSnapshot=new Map;adoptees=new Map;tombstoneSources=new Map;tombstoneSurvivor=new Map;attributesByNode=new Map;bindingsByNode=new Map;bulkLoad=0;unobservedWrites=0;nodeCountCache=-1;pendingNodeAdds=0;relationshipCountCache=-1;partCountCache=-1;stopObserving;destroy(){this.stopObserving();}beginBulkLoad(){this.bulkLoad+=1;}endBulkLoad(){this.bulkLoad=Math.max(0,this.bulkLoad-1),this.bulkLoad===0&&this.rebuildDerivedIndexes();}trackedTypes(){return [this.schema.meta,this.schema.nodes,this.schema.parts,this.schema.relationships,this.schema.overrides,this.schema.defaults,this.schema.binaries,this.schema.attributes,this.schema.bindings]}undoDeleteFilter(){return Vt(this.schema.nodes)}encodeSnapshot(){return R__namespace.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return R__namespace.encodeStateAsUpdate(this.doc,e)}partEntries(){return Yt(this.schema.parts)}partCount(){return this.partCountCache<0&&(this.partCountCache=this.partEntries().length),this.partCountCache}relationshipCount(){return this.relationshipCountCache<0&&(this.relationshipCountCache=this.relationships().length),this.relationshipCountCache}mainDocumentPart(){return $t(this.schema.meta.get("mainDocumentPart"))}record(e){if(g(e))return null;let n=this.schema.nodes.get(e);if(!b(n))return null;if(H(n)){let r=n.get(B),o=r instanceof R__namespace.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return this.elementRecord(e,n)}parentOf(e){return this.parentIndex.get(e)??null}identityMeta(e){let n=this.schema.nodes.get(e);if(!n)return null;let r=this.record(e),o=r&&v(r)?r.attributes:[];return {logicalId:e,yjsItemKey:yr(n),wordFacingIds:Ce(o)}}isTombstoned(e){return U(this.schema.nodes.get(e))}replacedByOf(e){return Ae(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(X(e))===e}noteWrite(){this.unobservedWrites+=1;}hasUnobservedWrites(){return this.unobservedWrites>0}listingParents(e){return [...this.listings.get(e)??[]]}allLogicalIds(){return [...this.schema.nodes.keys()].filter(e=>!g(e))}nodeCount(){return this.nodeCountCache<0&&(this.nodeCountCache=this.schema.nodes.size),this.nodeCountCache+this.pendingNodeAdds}nodeShape(e){return g(e)?null:Bt(this.schema.nodes,e)}kindOf(e){return g(e)?null:_t(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let n=j(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,bt({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:n,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)Ne(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)Me(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,n){let r=this.require(e),o=j(this.schema.namespaces,n.namespaceUri,this.limits.maxStringLength);r.set(z,Le(n.kind,o,n.localName,n.prefix??""));}putText(e,n){this.noteNodeWrite(e),this.schema.nodes.set(e,It(n));}spliceText(e,n,r,o){let i=this.textOf(e);r>0&&i.delete(n,r),o.length>0&&i.insert(n,o);}setAttribute(e,n,r){if(r===null){Ot(this.schema,e,n.namespaceUri,n.localName);return}Ne(this.schema,this.limits.maxStringLength,e,n,r);}setNamespaceBinding(e,n,r){if(r===null){Nt(this.schema,e,n);return}Me(this.schema,this.limits.maxStringLength,e,n,r);}spliceChildren(e,n,r,o){let i=this.childArray(e);r>0&&i.delete(n,r),o.length>0&&i.insert(n,[...o]);}moveNode(e,n,r){this.unlinkFromAllParents(e);let o=this.childArray(n);o.insert(Math.max(0,Math.min(r,o.length)),[e]);}tombstone(e,n){this.unlinkFromAllParents(e);let r=this.require(e);r.set(_,true),n&&r.set($,n);}unlistChildren(e,n){if(n.length===0)return;let r=this.schema.nodes.get(e),o=r?k(r):null;if(!o)return;let i=new Map;for(let a of n)i.set(a,(i.get(a)??0)+1);for(let a=o.length-1;a>=0;a-=1){let s=o.get(a),l=i.get(s)??0;l!==0&&(i.set(s,l-1),o.delete(a,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,xt(e.id,e.rootLogicalId,e.contentType));}deleteXmlPart(e){this.partCountCache=-1,this.schema.parts.delete(e);}putRelationship(e){if(g(e.ownerPart)||g(e.id))return;this.relationshipCountCache=-1;let n=new R__namespace.Map;n.set(e.id,vt(e)),this.schema.relationships.set(Oe(e.ownerPart,e.id),n);}deleteRelationship(e,n){this.relationshipCountCache=-1,this.schema.relationships.delete(Oe(e,n)),this.schema.relationships.get(e)?.delete(n);}putContentTypeOverride(e,n){this.schema.overrides.set(store.partNameKey(e),n);}deleteContentTypeOverride(e){this.schema.overrides.delete(store.partNameKey(e));}putContentTypeDefault(e,n){this.schema.defaults.set(e,n);}putBinary(e){this.schema.binaries.set(e.storageKey,St(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return Rt(this.schema.relationships)}contentTypeOverrides(){return zt(this.schema.overrides)}contentTypeDefaults(){return jt(this.schema.defaults)}binaries(){return Kt(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){let n=i=>{let a=new Set,s=false;for(let l of i){let d=l.path;if(d.length===0){for(let c of l.changes.keys.keys())a.add(String(c));s=true;continue}a.add(String(d[0])),l.target instanceof R__namespace.Array&&(s=true),l.target instanceof R__namespace.Map&&(l.changes.keys.has(_)||l.changes.keys.has($))&&(s=true);}(a.size>0||s)&&e({logicalIds:a,membershipChanged:s,packageChanged:false});},r=i=>{let a=new Set;for(let s of i.changes.keys.keys()){let l=le(String(s))??de(String(s));!l||g(l.logicalId)||a.add(l.logicalId);}a.size>0&&e({logicalIds:a,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return this.schema.nodes.observeDeep(n),this.schema.attributes.observe(r),this.schema.bindings.observe(r),this.schema.parts.observeDeep(o),this.schema.relationships.observeDeep(o),this.schema.overrides.observe(o),this.schema.defaults.observe(o),this.schema.binaries.observeDeep(o),()=>{this.schema.nodes.unobserveDeep(n),this.schema.attributes.unobserve(r),this.schema.bindings.unobserve(r),this.schema.parts.unobserveDeep(o),this.schema.relationships.unobserveDeep(o),this.schema.overrides.unobserve(o),this.schema.defaults.unobserve(o),this.schema.binaries.unobserveDeep(o);}}rebuildDerivedIndexes(){this.unobservedWrites=0,this.nodeCountCache=-1,this.pendingNodeAdds=0,this.relationshipCountCache=-1,this.partCountCache=-1,this.parentIndex=new Map,this.listings=new Map,this.childrenSnapshot=new Map,this.adoptees=new Map,this.tombstoneSources=new Map,this.tombstoneSurvivor=new Map,this.attributesByNode=new Map,this.bindingsByNode=new Map,this.schema.nodes.forEach((e,n)=>{if(g(n))return;let r=k(e);if(!r)return;let o=r.toArray();this.childrenSnapshot.set(n,o);for(let i of o)this.addListing(i,n);}),this.schema.nodes.forEach((e,n)=>{U(e)&&this.syncAdoptee(n);}),this.schema.attributes.forEach((e,n)=>{if(typeof e!="string"||g(n))return;let r=le(n);!r||g(r.logicalId)||g(r.localName)||Te(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,n)=>{if(typeof e!="string"||g(n))return;let r=de(n);!r||g(r.logicalId)||g(r.prefix)||De(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(b(e)&&(e.has("parent")||e.has("parentId")))throw new Error("registry record must not replicate a parent field")});}applyChildArrayEvents(e){this.unobservedWrites=0,this.pendingNodeAdds=0;let n=new Set;for(let r of e){if(r.path.length===0&&r.target instanceof R__namespace.Map){for(let[o,i]of r.changes.keys)if(this.nodeCountCache>=0&&i.action!=="update"&&(this.nodeCountCache+=i.action==="add"?1:-1),!(i.action==="delete"||g(String(o))))for(let a of this.syncChildListings(String(o)))n.add(a);continue}if(r.target instanceof R__namespace.Array&&r.path.length>0){let o=String(r.path[0]);for(let i of this.syncChildListings(o))n.add(i);this.isTombstoned(o)&&this.syncAdoptee(o);continue}r.target instanceof R__namespace.Map&&r.path.length===1&&(r.changes.keys.has(_)||r.changes.keys.has($))&&this.syncAdoptee(String(r.path[0]));}n.size>0&&this.resolveParents(n);}applyAttributeMapEvent(e){this.unobservedWrites=0;for(let[n,r]of e.changes.keys){let o=le(String(n));if(!o||g(o.logicalId)||g(o.localName))continue;if(r.action==="delete"){Mt(this.attributesByNode,o.logicalId,o.namespaceId,o.localName);continue}let i=this.schema.attributes.get(String(n));typeof i=="string"&&Te(this.schema,this.attributesByNode,o.logicalId,o.namespaceId,o.localName,i);}}applyBindingMapEvent(e){this.unobservedWrites=0;for(let[n,r]of e.changes.keys){let o=de(String(n));if(!o||g(o.logicalId)||g(o.prefix))continue;if(r.action==="delete"){Tt(this.bindingsByNode,o.logicalId,o.prefix);continue}let i=this.schema.bindings.get(String(n));typeof i=="string"&&De(this.schema,this.bindingsByNode,o.logicalId,o.prefix,i);}}syncChildListings(e){let n=this.schema.nodes.get(e),r=n?k(n)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(Ut(o,r))return [];let i=new Set(r),a=new Set(o),s=[];for(let l of o)i.has(l)||(this.removeListing(l,e),s.push(l));for(let l of r)a.has(l)||(this.addListing(l,e),s.push(l));return this.childrenSnapshot.set(e,r),s}addListing(e,n){let r=this.listings.get(e)??new Set;r.add(n),this.listings.set(e,r);}removeListing(e,n){let r=this.listings.get(e);r&&(r.delete(n),r.size===0&&this.listings.delete(e));}resolveParents(e){let n=[];for(let o of e){let i=this.listings.get(o);if(!i||i.size===0){this.parentIndex.delete(o);continue}if(i.size===1){this.parentIndex.set(o,[...i][0]);continue}n.push(o);}if(n.length===0)return;kt({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(o=>o.rootLogicalId)},n)||this.assignFirstReachable(new Set(n));}assignFirstReachable(e){Pt({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(n=>n.rootLogicalId)},e);}syncAdoptee(e){let n=this.tombstoneSurvivor.get(e);if(n!==void 0){this.tombstoneSurvivor.delete(e);let i=this.tombstoneSources.get(n);i&&(i.delete(e),i.size===0&&this.tombstoneSources.delete(n));}let r=this.schema.nodes.get(e),o=Ae(r);if(o!==null){if(U(r)){let i=this.tombstoneSources.get(o)??new Set;i.add(e),this.tombstoneSources.set(o,i),this.tombstoneSurvivor.set(e,o);}this.recomputeAdoptees(o);}}isContentWitness(e){let n=this.kindOf(e);return n!==null&&!n.endsWith("Properties")}recomputeAdoptees(e){let n=[];for(let r of this.tombstoneSources.get(e)??[]){let o=this.schema.nodes.get(r);if(o)for(let i of k(o)?.toArray()??[])this.isTombstoned(i)||!this.schema.nodes.has(i)||this.isContentWitness(i)&&n.push(i);}n.length>0?this.adoptees.set(e,n):this.adoptees.delete(e);}unlinkFromAllParents(e){let n=[...this.listings.get(e)??[]];if(n.length===0){this.schema.nodes.forEach(r=>{let o=k(r);o&&this.removeFromArray(o,e);});return}for(let r of n){let o=this.schema.nodes.get(r),i=o?k(o):null;i&&this.removeFromArray(i,e);}}removeFromArray(e,n){for(let r=e.length-1;r>=0;r-=1)e.get(r)===n&&e.delete(r,1);}elementRecord(e,n){let r=se($t(n.get(z))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:J(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:k(n)?.toArray()??[]}}textOf(e){let n=this.require(e).get(B);if(!(n instanceof R__namespace.Text))throw new Error(`no text at ${e}`);return n}childArray(e){let n=this.require(e).get(ie);if(!(n instanceof R__namespace.Array))throw new Error(`no children at ${e}`);return n}require(e){let n=this.schema.nodes.get(e);if(!n)throw new Error(`registry node ${e} missing`);return n}};var ue=class{blobs=new Map;get(e){let n=this.blobs.get(e);return n?n.slice():null}put(e,n){this.blobs.set(e,n.slice());}};async function Xt(t){let e=await globalThis.crypto.subtle.digest("SHA-256",t.slice().buffer);return `sha256:${[...new Uint8Array(e)].map(n=>n.toString(16).padStart(2,"0")).join("")}`}function Jt(t){let e=t.binaryPart;return typeof e=="function"?e:null}function Ht(t,e){let n=[];for(let o of t)o.kind==="putBinary"&&n.push(o.descriptor);if(n.length===0)return null;if(!e)return {ok:false,failure:{code:"blob-read",detail:"binary-part-reader"}};let r=[];for(let o of n){let i=e(o.storageKey);if(!i)return {ok:false,failure:{code:"missing-local-blob",detail:o.storageKey}};r.push({digest:o.digest,bytes:i});}return {ok:true,payloads:r}}function Gt(t,e){for(let n of e)t.put(n.digest,n.bytes);}function Ir(t){return t.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function xr(t){return t.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function qt(t,e,n,r,o){if(r>t.limits.maxTreeDepth)return "tree-too-deep";if(g(e.id))return "prototype-key";if(o.nodes+=1,o.nodes>t.limits.maxNodes)return "too-many-nodes";if(e.kind==="textValue"){if(e.value.length>t.limits.maxTextLength)return "text-too-long";t.putText(e.id,e.value);}else {if(e.attributes.length>t.limits.maxAttributes)return "too-many-attributes";if(e.children.length>t.limits.maxChildren)return "too-many-children";if(C(e.namespaceUri,t.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(g(i.localName))return "prototype-key";if(C(i.namespaceUri,t.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(g(i.prefix))return "prototype-key";if(C(i.namespaceUri,t.limits.maxStringLength))return "invalid-string"}t.putElement({logicalId:e.id,kind:e.kind,namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,attributes:Ir(e),bindings:xr(e)});for(let i of e.children){let a=qt(t,i,e.id,r+1,o);if(a)return a}}return n&&t.childArray(n).push([e.id]),null}async function vr(t){let e=[],n=[];for(let[r,o]of t.partBytes){if(t.parts.has(r))continue;let a=t.contentTypes.overrides.get(r)??"application/octet-stream",s=w(r);if(s)return {ok:false,code:s};if(o.byteLength>O.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await Xt(o);n.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:a,storageKey:r});}return {ok:true,descriptors:e,payloads:n}}async function G(t,e,n=new ue){if(e.parts.size>t.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await vr(e);if(!r.ok)return r;let o=null;t.beginBulkLoad();try{t.doc.transact(()=>{for(let s of r.payloads)n.put(s.digest,s.bytes);let i={nodes:0};for(let[s,l]of e.parts){let d=w(s);if(d){o=d;return}if(C(l.contentType,t.limits.maxMediaTypeLength)){o="invalid-string";return}let c=qt(t,l.root,null,0,i);if(c){o=c;return}t.putXmlPart({name:s,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let a=0;for(let s of e.relationships.values())for(let l of s){if(a+=1,a>t.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=w(l.ownerPart);if(d){o=d;return}}if(g(l.id)){o="prototype-key";return}t.putRelationship({ownerPart:l.ownerPart,id:l.id,type:l.type,rawTarget:l.rawTarget,targetMode:l.targetMode,order:l.order});}for(let[s,l]of e.contentTypes.defaults){if(g(s)){o="prototype-key";return}t.putContentTypeDefault(s,l);}for(let[s,l]of e.contentTypes.overrides){let d=w(s);if(d){o=d;return}t.putContentTypeOverride(s,l);}for(let s of r.descriptors)t.putBinary(s);Et(t.schema.meta),t.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},ut);}finally{t.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var pe=class{constructor(e){this.registry=e;}registry;touched=new Map;created=new Set;has(e){return this.created.has(e)||this.touched.has(e)||this.registry.hasNode(e)}node(e){let n=this.touched.get(e);if(n)return n;let r=this.registry.nodeShape(e);return r?(this.touched.set(e,r),r):null}putNode(e){this.node(e.logicalId)||(this.created.add(e.logicalId),this.touched.set(e.logicalId,{isText:e.kind==="textValue",textLength:0,children:[]}));}spliceText(e,n,r){let o=this.node(e);o&&(o.textLength=Math.max(0,o.textLength-n)+r);}spliceChildren(e,n,r,o){let i=this.node(e);i&&i.children.splice(n,r,...o);}moveNode(e,n,r){let o=this.parentOf(e);if(o!==null){let s=this.node(o),l=s?.children.indexOf(e)??-1;s&&l>=0&&s.children.splice(l,1);}let i=this.node(n);if(!i)return;let a=Math.min(r,i.children.length);i.children.splice(a,0,e);}parentOf(e){for(let[n,r]of this.touched)if(r.children.includes(e))return n;return this.registry.parentOf(e)}};function Zt(t,e){switch(e.kind){case "putNode":t.putNode(e.descriptor);return;case "spliceText":t.spliceText(e.logicalId,e.deleteCount,e.insert.length);return;case "spliceChildren":t.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":t.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;default:return}}function N(t,e){return g(e)||e.length===0?{ok:false,code:"prototype-key",detail:e}:t.has(e)?null:{ok:false,code:"unknown-logical-id",detail:e}}function Sr(t,e,n){if(g(e.logicalId)||e.logicalId.length===0)return {ok:false,code:"invalid-logical-id",detail:e.logicalId};let r=n.node(e.logicalId);return r&&r.isText!==(e.kind==="textValue")?{ok:false,code:"invalid-bound",detail:`node class ${e.logicalId}`}:e.kind==="textValue"?null:g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:C(e.qname.namespaceUri,t.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function Er(t,e,n){switch(e.kind){case "putNode":return Sr(t,e.descriptor,n);case "spliceText":{let r=N(n,e.logicalId);if(r)return r;if(!Number.isSafeInteger(e.utf16Start)||!Number.isSafeInteger(e.deleteCount)||e.utf16Start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.insert.length>t.limits.maxTextLength)return {ok:false,code:"text-too-long"};let o=n.node(e.logicalId);if(o&&o.isText){if(e.utf16Start+e.deleteCount>o.textLength)return {ok:false,code:"invalid-bound",detail:e.logicalId};if(o.textLength-e.deleteCount+e.insert.length>t.limits.maxTextLength)return {ok:false,code:"text-too-long"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.logicalId};return null}case "setAttribute":{let r=N(n,e.logicalId);return r||(g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:C(e.qname.namespaceUri,t.limits.maxStringLength)?{ok:false,code:"invalid-string"}:e.value!==null&&e.value.length>t.limits.maxStringLength?{ok:false,code:"invalid-string"}:null)}case "setNamespaceBinding":{let r=N(n,e.logicalId);return r||(g(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&C(e.uri,t.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=N(n,e.parentLogicalId);if(r)return r;if(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.deleteCount)||e.start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.childLogicalIds.length>t.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let i of e.childLogicalIds){let a=N(n,i);if(a)return a}let o=n.node(e.parentLogicalId);if(o&&!o.isText){if(e.start+e.deleteCount>o.children.length)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};if(o.children.length-e.deleteCount+e.childLogicalIds.length>t.limits.maxChildren)return {ok:false,code:"too-many-children"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};return null}case "moveNode":{let r=N(n,e.logicalId);if(r)return r;let o=N(n,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=w(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=N(n,e.rootLogicalId);return o||(t.partCount()>=t.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=w(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=w(e.owner);if(r)return {ok:false,code:r}}return g(e.record.id)?{ok:false,code:"prototype-key"}:t.relationshipCount()>=t.limits.maxRelationships?{ok:false,code:"too-many-relationships"}:null}case "deleteRelationship":return g(e.relationshipId)?{ok:false,code:"prototype-key"}:null;case "putContentTypeOverride":{let r=w(e.partName);return r?{ok:false,code:r}:C(e.mediaType,t.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=w(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=it(e.descriptor);return r?{ok:false,code:r}:null}case "deleteBinary":return g(e.storageKey)?{ok:false,code:"prototype-key"}:null;default:return {ok:false,code:"invalid-bound"}}}function wr(t,e,n){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?t.hasNode(e.descriptor.logicalId)||t.putText(e.descriptor.logicalId,""):t.hasNode(e.descriptor.logicalId)?t.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):t.putElement({logicalId:e.descriptor.logicalId,kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix,attributes:[],bindings:[]});return;case "spliceText":if(n.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&t.textOf(e.logicalId).toString()===e.insert)return;t.spliceText(e.logicalId,e.utf16Start,e.deleteCount,e.insert);return;case "setAttribute":t.setAttribute(e.logicalId,e.qname,e.value);return;case "setNamespaceBinding":t.setNamespaceBinding(e.logicalId,e.prefix,e.uri);return;case "spliceChildren":t.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":t.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;case "putXmlPart":t.putXmlPart({name:e.name,id:e.name,rootLogicalId:e.rootLogicalId,contentType:"application/xml"});return;case "deleteXmlPart":t.deleteXmlPart(e.name);return;case "putRelationship":t.putRelationship({...e.record,ownerPart:e.owner});return;case "deleteRelationship":t.deleteRelationship(e.owner,e.relationshipId);return;case "putContentTypeOverride":t.putContentTypeOverride(e.partName,e.mediaType);return;case "deleteContentTypeOverride":t.deleteContentTypeOverride(e.partName);return;case "putBinary":t.putBinary(e.descriptor);return;case "deleteBinary":t.deleteBinary(e.storageKey);return}}function Rr(t,e){let n=t.kindOf(e);return n!==null&&!n.endsWith("Properties")}function Cr(t,e,n,r){let o=new Set((n.get(e)??[]).filter(i=>Rr(t,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(a=>o.has(a)))return i.parentLogicalId}}function Lr(t,e){let n=new pe(t),r=[],o=new Set,i=new Set;for(let a of e){let s=Er(t,a,n);if(s)return s;if(a.kind==="spliceChildren"){let l=a.deleteCount>0?n.node(a.parentLogicalId):null;if(l&&!l.isText){let d=a.start+a.deleteCount;for(let c=a.start;c<d;c+=1){let h=l.children[c];h!==void 0&&r.push(h);}}for(let d of a.childLogicalIds)o.add(d);}else a.kind==="moveNode"?o.add(a.logicalId):a.kind==="putNode"&&a.descriptor.kind==="textValue"&&i.add(a.descriptor.logicalId);Zt(n,a);}return {removed:r,reinserted:o,mintedText:i}}function kr(t){let e=0;for(let n of t)n.kind==="putNode"&&(e+=1);return e}function Be(t,e){if(t.nodeCount()+kr(e.effects)>t.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let n=Lr(t,e.effects);return "ok"in n?n:(t.doc.transact(()=>{t.noteWrite();let r=Ar(t,n.removed);for(let o of e.effects)wr(t,o,n.mintedText);Pr(t,e.effects,n,r);},pt),{ok:true})}function Pr(t,e,n,r){if(n.removed.length===0)return;let o=new Set;for(let i of t.partEntries())o.add(i.rootLogicalId);for(let i of n.removed){if(n.reinserted.has(i)||!t.hasNode(i)||t.isTombstoned(i)||o.has(i))continue;let a=Cr(t,i,r,e);a&&t.unlistChildren(i,r.get(i)??[]),t.tombstone(i,a);}}function Ar(t,e){let n=new Map;for(let r of e){let o=t.nodeShape(r);o&&!o.isText&&n.set(r,o.children);}return n}var me="http://schemas.openxmlformats.org/package/2006/relationships",Or="application/vnd.openxmlformats-package.relationships+xml",Qt=/^(.*)\/_rels\/([^/]*)\.rels$/;function en(t){return Qt.test(t)}function tn(t){let e=Qt.exec(t);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function q(t,e){return t.attributes.find(n=>n.localName===e)?.value}function he(t,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:t,value:e})}function Nr(t,e){let n=[he("Id",e.id),he("Type",e.type),he("Target",e.rawTarget)];return e.targetMode==="External"&&n.push(he("TargetMode","External")),Object.freeze({id:t,kind:"generic",namespaceUri:me,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(n),children:Object.freeze([])})}function nn(t,e){if(t.kind==="textValue"||t.namespaceUri!==me||t.localName!=="Relationship"||q(t,"Id")!==e.id||q(t,"Type")!==e.type||q(t,"Target")!==e.rawTarget)return false;let n=q(t,"TargetMode");return e.targetMode==="External"?n==="External":n===void 0}function rn(t,e){return t.children.length!==e.length?false:t.children.every((n,r)=>nn(n,e[r]))}function on(t,e){if(t.id!==e.id||t.kind!==e.kind||t.namespaceUri!==e.namespaceUri||t.localName!==e.localName||t.prefix!==e.prefix||t.attributes.length!==e.attributes.length)return false;for(let n=0;n<t.attributes.length;n+=1){let r=t.attributes[n],o=e.attributes[n];if(r.namespaceUri!==o.namespaceUri||r.localName!==o.localName||r.value!==o.value||r.prefix!==o.prefix)return false}return t.namespaceBindings.length!==e.namespaceBindings.length?false:t.namespaceBindings.every((n,r)=>{let o=e.namespaceBindings[r];return n.prefix===o.prefix&&n.namespaceUri===o.namespaceUri})}function an(t,e,n){let r=[];for(let o of e){if(g(o.id))continue;let i=t.find(s=>s.kind!=="textValue"&&q(s,"Id")===o.id);if(i&&nn(i,o)){r.push(i);continue}let a=i&&i.kind!=="textValue"?i.id:`${n}#rel-${o.id}`;g(a)||r.push(Nr(a,o));}return r}function Mr(t){return Object.freeze({id:`${t}#root`,kind:"generic",namespaceUri:me,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:me})]),attributes:Object.freeze([]),children:Object.freeze([])})}function sn(t){return Object.freeze({id:t,name:t,contentType:Or,root:Mr(t)})}function ln(t){let e=new Map;for(let n of t){if(g(n.id)||n.ownerPart!=="/"&&w(n.ownerPart))continue;let r=e.get(n.ownerPart)??[];r.push(n),e.set(n.ownerPart,r);}return e}var pn=/^\/customXml\/item(\d+)\.xml$/i,_r=/^\/customXml\/itemProps(\d+)\.xml$/i;function Q(t){return pn.test(t)}function Ue(t){return _r.test(t)}function Ur(t){let e=pn.exec(t);if(!e)return null;let n=Number(e[1]);return Number.isSafeInteger(n)&&n>0?n:null}function dn(t){return {item:`/customXml/item${String(t)}.xml`,props:`/customXml/itemProps${String(t)}.xml`}}function Yr(t,e,n){let r=t.attributes.find(o=>o.localName===e&&o.namespaceUri===n);return r&&r.value.length>0?r.value:null}function cn(t,e){let n=t.record(e);return !n||!v(n)?e:n.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function zr(t,e){let n=t.record(e);if(!n||!v(n))return null;for(let r of n.childIds){let o=t.record(r);if(!(!o||!v(o)||o.localName!=="schemaRefs")&&o.namespaceUri===store.DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let a=t.record(i);if(!a||!v(a)||a.localName!=="schemaRef")continue;let s=Yr(a,"uri",store.DATASTORE_NAMESPACE_URI);if(s)return s}}return null}function jr(t,e){return e.childIds.some(n=>{let r=t.record(n);return !!r&&v(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Kr(t,e){return e.localName==="node"||e.namespaceUri===store.WML_NAMESPACE_URI||e.namespaceUri===store.DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||t.parentOf(e.logicalId)!==null?false:jr(t,e)}function Fr(t,e){return e.localName!=="datastoreItem"||e.namespaceUri!==store.DATASTORE_NAMESPACE_URI?false:t.parentOf(e.logicalId)===null}function hn(t,e){if(!t.hasNamespace(store.DATASTORE_NAMESPACE_URI))return [];let n=new Map,r=new Map;for(let[u,m]of e){let f=t.record(m.root.id);!f||!v(f)||(Q(u)&&n.set(f.logicalId,f),Ue(u)&&r.set(f.logicalId,f));}for(let u of t.allLogicalIds()){if(t.isTombstoned(u)||n.has(u)||r.has(u))continue;let m=t.record(u);!m||!v(m)||(Kr(t,m)?n.set(u,m):Fr(t,m)&&r.set(u,m));}if(n.size===0)return [];let o=new Map;for(let u of n.values()){let m=o.get(u.namespaceUri)??[];m.push(u),o.set(u.namespaceUri,m);}let i=new Map;for(let u of r.values()){let m=zr(t,u.logicalId);if(!m)continue;let f=i.get(m)??[];f.push(u),i.set(m,f);}let a=[];for(let[u,m]of o){let f=i.get(u);if(!f||f.length===0)continue;m.sort((x,E)=>x.logicalId.localeCompare(E.logicalId)),f.sort((x,E)=>x.logicalId.localeCompare(E.logicalId));let y=m[0],D=f[0],P=[],I=new Set;for(let x of m)for(let E of x.childIds){if(I.has(E))continue;let oe=t.record(E);!oe||!v(oe)||oe.localName!=="node"||oe.namespaceUri!==u||(I.add(E),P.push(E));}for(let x of t.allLogicalIds()){if(I.has(x)||t.isTombstoned(x))continue;let E=t.record(x);!E||!v(E)||E.localName!=="node"||E.namespaceUri!==u||(I.add(x),P.push(x));}P.sort((x,E)=>cn(t,x).localeCompare(cn(t,E))),a.push({data:y,props:D,nodeIds:P});}a.sort((u,m)=>u.data.logicalId.localeCompare(m.data.logicalId));let s=new Set,l=[],d=new Set,c=new Set;for(let[u,m]of e){let f=Ur(u);if(f===null)continue;let y=a.find(I=>I.data.logicalId===m.root.id&&!d.has(I.data.logicalId));if(!y)continue;let D=dn(f).props,P=e.get(D);P&&P.root.id!==y.props.logicalId||(s.add(f),d.add(y.data.logicalId),c.add(y.props.logicalId),l.push({dataRootId:y.data.logicalId,propsRootId:y.props.logicalId,namespaceUri:y.data.namespaceUri,itemName:u,propsName:D,nodeIds:y.nodeIds}));}let h=1;for(let u of a){if(d.has(u.data.logicalId))continue;for(;s.has(h);)h+=1;s.add(h);let m=dn(h);l.push({dataRootId:u.data.logicalId,propsRootId:u.props.logicalId,namespaceUri:u.data.namespaceUri,itemName:m.item,propsName:m.props,nodeIds:u.nodeIds}),h+=1;}return l.sort((u,m)=>u.itemName.localeCompare(m.itemName)),l}function Vr(t){return t.type===store.CUSTOM_XML_REL||t.type===store.CUSTOM_XML_PROPS_REL?true:Q(t.ownerPart)}function Wr(t){let e=/^rId(\d+)$/.exec(t);if(!e)return 0;let n=Number(e[1]);return Number.isSafeInteger(n)?n:0}function $r(t,e){let n=t.split("/").slice(1,-1),r=e.split("/").slice(1),o=0;for(;o<n.length&&o<r.length-1&&n[o]===r[o];)o+=1;return `${"../".repeat(n.length-o)}${r.slice(o).join("/")}`}function mn(t,e){if(e.length===0)return [];let n=t.mainDocumentPart();if(!n)return [];let r=t.relationships(),o=r.filter(s=>s.ownerPart===n&&s.type===store.CUSTOM_XML_REL).sort((s,l)=>s.id.localeCompare(l.id)),i=0;for(let s of r)i=Math.max(i,Wr(s.id));let a=[];for(let s=0;s<e.length;s+=1){let l=e[s],d=o[s],c=d?.id??`rId${String(i+=1)}`;a.push({ownerPart:n,id:c,type:store.CUSTOM_XML_REL,rawTarget:$r(n,l.itemName),targetMode:"Internal",order:d?.order??s}),a.push({ownerPart:l.itemName,id:"rId1",type:store.CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return a}function gn(t,e){return e.length===0?[...t]:[...t.filter(n=>!Vr(n)),...e]}function fn(t){let e=new Map;for(let n of t)e.set(store.partNameKey(n.propsName),store.CUSTOM_XML_PROPS_TYPE);return e}function Ye(t,e){if(e.length===0)return false;let n=[...t.keys()].filter(Q).sort(),r=e.map(o=>o.itemName).sort();if(n.length!==r.length||n.some((o,i)=>o!==r[i]))return true;for(let o of e){let i=t.get(o.itemName),a=t.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!a||a.root.id!==o.propsRootId)return true}return false}function yn(t,e){if(Ye(t,e))return true;for(let n of e){let r=t.get(n.itemName);if(!r)return true;let o=new Set(r.root.children.map(s=>s.id));if(n.nodeIds.some(s=>!o.has(s)))return true;let i=[];for(let s of r.root.children)s.kind!=="textValue"&&i.push(s.attributes.find(l=>l.localName==="id")?.value??s.id);let a=[...i].sort((s,l)=>s.localeCompare(l));if(i.some((s,l)=>s!==a[l]))return true}return false}var Xr="http://schemas.microsoft.com/office/word/2012/wordml";function ge(t,e){return t.attributes.find(n=>n.localName===e)?.value}function fe(t){let e=Number(t);return t===void 0||t.length===0||!Number.isSafeInteger(e)?`2${t??""}`:`${e<0?"0":"1"}${String(Math.abs(e)).padStart(12,"0")}`}function bn(t){return e=>e.localName===t&&e.namespaceUri===store.WML_NAMESPACE_URI}function Jr(t){return t.localName==="abstractNum"?`0${fe(ge(t,"abstractNumId"))}`:`1${fe(ge(t,"numId"))}`}function Hr(t){return t.namespaceUri!==store.WML_NAMESPACE_URI?false:t.localName==="abstractNum"||t.localName==="num"}function In(t){return t.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:t.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===Xr,sortKey:e=>e.id}:t.localName==="footnotes"&&t.namespaceUri===store.WML_NAMESPACE_URI?{isMember:bn("footnote"),sortKey:e=>fe(ge(e,"id"))}:t.localName==="endnotes"&&t.namespaceUri===store.WML_NAMESPACE_URI?{isMember:bn("endnote"),sortKey:e=>fe(ge(e,"id"))}:t.localName==="numbering"&&t.namespaceUri===store.WML_NAMESPACE_URI?{isMember:Hr,sortKey:Jr}:null}function Gr(t,e){return t.attributes.find(n=>n.localName===e)?.value}function ze(t){return t.kind==="textValue"?t.id:Gr(t,"id")??t.id}function F(t,e){if(t.length===e.length&&t.every((a,s)=>a===e[s]))return t;let n=0,r=Math.min(t.length,e.length);for(;n<r&&t[n]===e[n];)n+=1;let o=t.length,i=e.length;for(;o>n&&i>n&&t[o-1]===e[i-1];)o-=1,i-=1;return Object.freeze([...t.slice(0,n),...e.slice(n,i),...t.slice(o)])}function Sn(t,e){let n=t.root;if(n.children.length===e.length&&n.children.every((o,i)=>o===e[i]))return t;let r=Object.freeze({...n,children:F(n.children,e)});return Object.freeze({...t,root:r})}function qr(t){if(t.namespaceUri===store.XML_NAMESPACE_URI&&t.localName==="space"){let e=t.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:store.XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return t.namespaceUri===store.WML_NAMESPACE_URI&&t.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:store.WML_NAMESPACE_URI,localName:"val",prefix:t.prefix,value:t.value}):Object.freeze({kind:"genericExtension",namespaceUri:t.namespaceUri,localName:t.localName,prefix:t.prefix,value:t.value})}function Rn(t){}function Ln(t,e){return Object.freeze({id:t,kind:"textValue",value:e})}function ro(t,e){return t.namespaceBindings.length!==e.bindings.length?false:t.namespaceBindings.every((n,r)=>{let o=e.bindings[r];return n.prefix===o.prefix&&n.namespaceUri===o.namespaceUri})}function oo(t,e){return t.attributes.length!==e.attributes.length?false:t.attributes.every((n,r)=>{let o=e.attributes[r];return n.namespaceUri===o.namespaceUri&&n.localName===o.localName&&n.value===o.value&&n.prefix===(o.prefix?.length?o.prefix:void 0)})}function ye(t,e,n){let r=n&&n.kind!=="textValue"?n:void 0;return Object.freeze({id:t.logicalId,kind:t.kind,namespaceUri:t.namespaceUri,localName:t.localName,prefix:t.prefix,namespaceBindings:r&&ro(r,t)?r.namespaceBindings:Object.freeze(t.bindings.map(o=>Object.freeze({...o}))),attributes:r&&oo(r,t)?r.attributes:Object.freeze(t.attributes.map(qr)),children:e})}function kn(t,e){if(t.attributes.length!==e.attributes.length)return false;let n=new Map(e.attributes.map(r=>[`${r.namespaceUri}
2
- ${r.localName}`,r.value]));for(let r of t.attributes)if(n.get(`${r.namespaceUri}
3
- ${r.localName}`)!==r.value)return false;return t.localName===e.localName&&t.kind===e.kind}function je(t,e){let n=e.size;e.add(t.id);let r=e.size!==n;if(t.kind==="textValue")return r;for(let o of t.children)je(o,e)||(r=false);return r}function Pn(t,e){let n=new Set(e);for(let r of e){let o=t.parentOf(r);for(;o&&!n.has(o);)n.add(o),o=t.parentOf(o);}return n}var be=class{constructor(e){this.registry=e;}registry;decoded=null;merged=null;grouped=null;assembly=null;defaults=null;overrides=null;partBytes=null;blobBytes=new Map;invalidate(){this.decoded=null,this.merged=null,this.grouped=null,this.assembly=null,this.defaults=null,this.overrides=null,this.partBytes=null;}projected(e){return this.decoded||(this.decoded=this.registry.relationships(),this.merged=null),(!this.merged||this.merged.custom!==e)&&(this.merged={custom:e,records:e.length===0?this.decoded:gn(this.decoded,e)}),this.merged.records}groupedByOwner(e){let n=this.projected(e);return (!this.grouped||this.grouped.records!==n)&&(this.grouped={records:n,map:ln(n)}),this.grouped.map}relationshipAssembly(e){let n=this.projected(e);return (!this.assembly||this.assembly.records!==n)&&(this.assembly={records:n,value:so(n)}),this.assembly.value}contentTypeDefaults(){return this.defaults??=this.registry.contentTypeDefaults()}contentTypeOverrides(){return this.overrides??=this.registry.contentTypeOverrides()}resolvePartBytes(e){if(this.partBytes)return this.partBytes;let n=new Map,r=new Set;for(let o of this.registry.binaries()){r.add(o.storageKey);let i=this.blobBytes.get(o.storageKey);if(i&&i.digest===o.digest){n.set(o.storageKey,i.bytes);continue}let a=e.get(o.digest);if(!a)return null;Rn(a.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:a}),n.set(o.storageKey,a);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=n,n}};function so(t){let e=store.buildRelationshipSet(t);if(!e.ok)return null;let n=[];for(let r of t){let o=store.resolveRelationship(r);o.mode==="External"&&n.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(n)}}function uo(t){let e=new Set,n=[];for(let r of t){let o=`${r.code}${r.logicalId??""}`;e.has(o)||(e.add(o),n.push(r));}return n}var Y=class{constructor(e,n){this.registry=e;this.blobs=n;this.packageCache=new be(e),this.stop=e.observeDirty(r=>{for(let o of r.logicalIds)this.pendingDirty.add(o);r.membershipChanged&&(this.pendingMembership=true),r.packageChanged&&(this.pendingPackage=true);});}registry;blobs;cache=new Map;heights=new Map;partCache=new Map;packageCache;relsProjection=new Map;pendingDirty=new Set;pendingMembership=false;pendingPackage=false;lastDirty=new Set;lastAdoption=new Map;placementContested=false;lastContestResolution=new Map;contestEncountered=new Set;contestMatchesResolution=true;claimsWholeSubtrees=true;lastDuplicateParents=[];droppedChildren=new Set;looseCandidates=new Set;pkg=null;customXmlRels=[];customXmlOverrides=new Map;stop;issues=[];destroy(){this.stop();}dirtyLogicalIds(){return this.lastDirty}current(){return this.pkg&&this.pendingDirty.size===0&&!this.pendingPackage&&!this.pendingMembership?{ok:true,package:this.pkg,issues:[...this.issues]}:this.rebuild()}adoptionChanges(){let e=[],n=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");n.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())n.has(r)||e.push(r);return this.lastAdoption=n,e}rebuild(){let e=new Set(this.pendingDirty),n=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(n||r)&&this.packageCache.invalidate();for(let c of this.adoptionChanges())e.add(c);let o=Pn(this.registry,e),i=new Set(this.registry.partEntries().map(c=>c.rootLogicalId)),a=[...e].some(c=>i.has(c)||this.registry.parentOf(c)===null&&!this.registry.isTombstoned(c)),s=this.pkg!==null&&!r&&!a&&(o.size>0||n),l=this.materializePass(o,n,s);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:uo(l.issues)};let d=this.materializePass(o,n,false);return this.recordContestResolution(),d}contestUnchanged(){for(let e of this.contestEncountered){let n=this.lastContestResolution.get(e);if(n===void 0||n!==this.registry.parentOf(e))return false}return true}recordContestResolution(){let e=new Map;for(let n of this.contestEncountered)e.set(n,this.registry.parentOf(n));for(let n of this.lastDuplicateParents)e.set(n,this.registry.parentOf(n));this.lastContestResolution=e;}materializePass(e,n,r){if(this.issues.length=0,this.lastDirty=e,this.placementContested=false,this.contestEncountered.clear(),this.contestMatchesResolution=true,this.claimsWholeSubtrees=!r,this.droppedChildren.clear(),r)for(let d of this.lastDuplicateParents)this.push("duplicate-parent",d);this.customXmlRels=[],this.customXmlOverrides.clear();let o=new Set,i=new Map;for(let d of this.registry.partEntries()){let c=new Set,h=this.materialize(d.rootLogicalId,o,c,r);if(!h||h.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let u=this.partCache.get(d.name);if(u&&u.root===h&&u.contentType===d.contentType){i.set(d.name,u);continue}let m=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:h});i.set(d.name,m),this.partCache.set(d.name,m);}let a=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),s=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,a,s),this.applyCustomXmlStores(i,o,r);for(let d of [...this.partCache.keys()])i.has(d)||this.partCache.delete(d);for(let d of [...this.relsProjection.keys()])i.has(d)||this.relsProjection.delete(d);this.evictDeadSubtrees(o),this.reportOrphans(a,o,r,s),this.looseCandidates=s,r||(this.lastDuplicateParents=this.issues.filter(d=>d.code==="duplicate-parent"&&d.logicalId!==void 0).map(d=>d.logicalId));let l=this.assemblePackage(i);return l.ok?this.pkg&&!n&&this.pkg.parts.size===i.size&&[...i].every(([d,c])=>this.pkg?.parts.get(d)===c)?{ok:true,package:this.pkg,issues:[...this.issues]}:(this.pkg=l.package,{ok:true,package:this.pkg,issues:[...this.issues]}):l}push(e,n){this.issues.push(n?{code:e,logicalId:n}:{code:e});}stillListed(e){for(let n of this.registry.listingParents(e)){let r=this.registry.record(n);if(r&&v(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,n,r,o){if(!r){for(let s of e)this.registry.isTombstoned(s)||n.has(s)||(this.pushOrphan(s),o.add(s));return}let i=new Set(this.registry.partEntries().map(s=>s.rootLogicalId)),a=new Set;for(let s of e)a.has(s)||(a.add(s),this.reportOrphansUnder(s,n,i)&&o.add(s));}reportOrphansUnder(e,n,r){let o=false,i=new Set,a=[{id:e,underTombstone:false}];for(;a.length>0;){let{id:s,underTombstone:l}=a.pop();if(!(i.has(s)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(s),this.registry.isTombstoned(s)){let d=this.registry.record(s);if(d&&v(d))for(let c of d.childIds)a.push({id:c,underTombstone:true});continue}r.has(s)||(l?n.has(s):this.stillListed(s))||(this.pushOrphan(s),o=true);}}return o}pushOrphan(e){let n=this.registry.record(e),r=!!n&&(ae(n)?n.value.length>0:n.childIds.length>0||n.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,n,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(n.has(e))return this.push("duplicate-parent",e),null;if(o&&!this.lastDirty.has(e)){let u=this.cache.get(e);if(u&&r.size+this.heightOf(u)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?je(u,n)||(this.placementContested=true):n.add(u.id),u}if(this.registry.isTombstoned(e))return null;n.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(ae(i)){let u=this.cache.get(e);if(u?.kind==="textValue"&&u.value===i.value)return u;let m=Ln(e,i.value);return this.remember(e,m),m}r.add(e);let a=new Set,s=[...i.childIds];for(let u of this.registry.adoptedChildren(e))s.includes(u)||s.push(u);let l=[];for(let u of s){if(u===e){this.push("self-child",u);continue}if(a.has(u)){this.push("duplicate-child",u);continue}if(a.add(u),this.registry.isTombstoned(u)){this.push("deleted-referenced",u);continue}if(g(u)||!this.registry.hasNode(u)){this.push("child-id-not-in-registry",u);continue}if(!this.claimsWholeSubtrees){let f=this.registry.listingParents(u);f.length>1&&(this.placementContested=true,this.contestEncountered.add(u),f.some(y=>this.registry.isTombstoned(y)&&this.registry.replacedByOf(y)!==null)?this.contestMatchesResolution=false:!n.has(u)&&this.registry.parentOf(u)!==e&&(this.contestMatchesResolution=false));}let m=this.materialize(u,n,r,o);m&&l.push(m);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((u,m)=>u===l[m])&&kn(d,i))return d;let c=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(c,l);let h=ye(i,F(c,l),d);return this.remember(e,h),h}recordDroppedChildren(e,n){if(e.length===0)return;let r=new Set(n.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,n){this.cache.set(e,n),this.heights.delete(e);}evictDeadSubtrees(e){for(let n of this.droppedChildren)e.has(n)||(this.registry.isTombstoned(n)||!this.registry.hasNode(n))&&this.evictSubtree(n,e);}evictSubtree(e,n){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)n.has(o.id)||this.evictSubtree(o.id,n);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let n=this.heights.get(e.id);if(n!==void 0)return n;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let n=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of n){let a=store.relsPartNameFor(o);if(a!=="/_rels/.rels"&&w(a))continue;r.add(a);let s=this.projectOneRelsPart(a,e.get(a),i);s&&(e.set(a,s),this.partCache.set(a,s));}for(let[o,i]of e){if(r.has(o)||!en(o))continue;let a=tn(o);if(a===null)continue;let s=this.projectOneRelsPart(o,i,n.get(a)??[]);!s||s===i||(e.set(o,s),this.partCache.set(o,s));}}projectOneRelsPart(e,n,r){if(!n&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),a=!!o&&(!n||on(o.root,n.root))&&o?o:n??sn(e);if(rn(a.root,r))return this.relsProjection.set(e,a),a;let s=a.root.children,l=Sn(a,an(s,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,n,r,o,i){for(let[a,s]of e){let l=In(s.root);if(!l)continue;let d=I=>I.logicalId!==s.root.id&&l.isMember(I),c=[],h=new Set;for(let I of s.root.children){if(I.kind==="textValue")continue;let x=this.registry.record(I.id);!x||!v(x)||!d(x)||(c.push(I),h.add(I.id));}if(this.adoptLooseMembers(c,h,d,n,r,o,i)===0)continue;c.sort((I,x)=>l.sortKey(I).localeCompare(l.sortKey(x)));let m=[];for(let I of s.root.children)h.has(I.id)||m.push(I);let f=F(s.root.children,[...m,...c]);if(f===s.root.children)continue;let y=this.registry.record(s.root.id);if(!y||!v(y))continue;let D=ye(y,f,s.root);this.remember(s.root.id,D);let P=Object.freeze({...s,root:D});e.set(a,P),this.partCache.set(a,P);}}adoptLooseMembers(e,n,r,o,i,a,s){let l=0;for(let d of a){if(o.has(d)||n.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let c=this.registry.record(d);if(!c||!v(c)||!r(c))continue;let h=this.materialize(d,o,new Set,i);!h||h.kind==="textValue"||(e.push(h),n.add(d),s.add(d),l+=1);}return l}materializeOnce(e,n,r){return n.has(e)?this.cache.get(e)??null:this.materialize(e,n,new Set,r)}adoptNodesIntoRoot(e,n,r,o){let i=this.cache.get(e),a=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!a||a.kind==="textValue")return null;let s=[...a.children],l=new Set(s.map(m=>m.id)),d=0;for(let m of n){if(l.has(m))continue;let f=this.materializeOnce(m,r,o);!f||f.kind==="textValue"||(s.push(f),l.add(m),d+=1);}if(s.sort((m,f)=>ze(m).localeCompare(ze(f))),d===0&&s.every((m,f)=>m===a.children[f]))return a;let c=this.registry.record(e);if(!c||!v(c))return a;let h=F(a.children,s),u=ye(c,h,a);return this.remember(e,u),u}applyCustomXmlStores(e,n,r){let o=hn(this.registry,e);if(o.length===0||!yn(e,o))return;let i=Ye(e,o),a=new Set;for(let s of o){a.add(s.itemName),a.add(s.propsName);let l=this.adoptNodesIntoRoot(s.dataRootId,s.nodeIds,n,r),d=this.materializeOnce(s.propsRootId,n,r);if(!l||!d||d.kind==="textValue")continue;let c=Object.freeze({id:s.itemName,name:s.itemName,contentType:"application/xml",root:l}),h=Object.freeze({id:s.propsName,name:s.propsName,contentType:store.CUSTOM_XML_PROPS_TYPE,root:d});e.set(s.itemName,c),e.set(s.propsName,h),this.partCache.set(s.itemName,c),this.partCache.set(s.propsName,h);}if(i){for(let s of [...e.keys()])!Q(s)&&!Ue(s)||a.has(s)||(e.delete(s),this.partCache.delete(s));this.customXmlRels=mn(this.registry,o),this.customXmlOverrides=fn(o),this.projectRelsParts(e);}}assemblePackage(e){let n=this.packageCache.relationshipAssembly(this.customXmlRels);if(!n)return {ok:false,code:"invalid-relationships",issues:[...this.issues]};let r=this.packageCache.resolvePartBytes(this.blobs);if(!r)return {ok:false,code:"missing-blob",issues:[...this.issues]};let o=new Map(this.packageCache.contentTypeOverrides());for(let[s,l]of this.customXmlOverrides)o.set(s,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},a=this.registry.mainDocumentPart()||[...e.keys()].find(s=>s.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:n.byOwner,externalTargets:n.externalTargets,contentTypes:i,mainDocumentPart:a}),issues:[...this.issues]}}};var On=1,Nn=1,Fe=20*1024*1024,yo="docx-collaboration-v1",bo="docx-body-paragraphs-v1",Io=Object.freeze({kind:"docx-collaboration-bootstrap"}),p=class extends Error{constructor(n,r){super(r?`${n}: ${r}`:n);this.code=n;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function We(t){return {root:t.getMap(yo),paragraphs:t.getMap(bo)}}function xo(t,e){if(!(t instanceof Uint8Array)||t.byteLength===0)throw new p("invalid-baseline");if(t.byteLength>Fe)throw new p("baseline-too-large");let n=store.readOoxmlPackage(t,{zip:{maxEntries:1e4,maxTotalBytes:Fe,maxRatio:200}});if(!n.ok)throw new p("invalid-baseline");let r=n.package.parts.get(n.package.mainDocumentPart);if(!r)throw new p("no-main-document-part");let o=store.normalizeParagraphIdentity(r),i=new store.TreePackageStore(n.package,o),a=replication.createCollaborationDocumentPort(i,{documentId:e});return {bytes:store.writeOoxmlPackage(i.currentPackage()),paragraphs:a.paragraphs()}}async function Mn(t){let e=await globalThis.crypto.subtle.digest("SHA-256",t.slice().buffer);return [...new Uint8Array(e)].map(n=>n.toString(16).padStart(2,"0")).join("")}function An(t,e){let n=t.get(e);if(typeof n!="string"||n.length===0||n.length>256)throw new p("invalid-shared-metadata",e);return n}function Ke(t,e){let n=t.get(e);if(!Number.isSafeInteger(n)||n<0)throw new p("invalid-shared-metadata",e);return n}function te(t){return t.get("initialized")===true}async function Ia(t,e,n,r){let{root:o,paragraphs:i}=We(t);if(te(o))throw new p("already-initialized");let a=await Mn(r.bytes);t.transact(()=>{if(te(o))throw new p("already-initialized");o.set("protocolVersion",On),o.set("schemaVersion",Nn),o.set("documentId",e),o.set("baselineSha256",a),o.set("baselineByteLength",r.bytes.byteLength),o.set("initializedBy",n),o.set("baseline",new Uint8Array(r.bytes));for(let s of r.paragraphs){if(i.has(s.paragraphId))throw new p("duplicate-paragraph-id");let l=new R__namespace.Text;i.set(s.paragraphId,l),l.insert(0,s.text);}o.set("initialized",true);},Io);}async function xa(t,e){let{root:n,paragraphs:r}=We(t);if(!te(n))throw new p("not-initialized");if(Ke(n,"protocolVersion")!==On)throw new p("protocol-version-mismatch");if(Ke(n,"schemaVersion")!==Nn)throw new p("schema-version-mismatch");if(An(n,"documentId")!==e)throw new p("document-id-mismatch");let o=Ke(n,"baselineByteLength");if(o===0||o>Fe)throw new p("baseline-too-large");let i=n.get("baseline");if(!(i instanceof Uint8Array)||i.byteLength!==o)throw new p("invalid-baseline");if(await Mn(i)!==An(n,"baselineSha256"))throw new p("baseline-digest-mismatch");let a=xo(new Uint8Array(i),e),s=new Set(a.paragraphs.map(l=>l.paragraphId));if(r.size!==s.size)throw new p("paragraph-set-mismatch");for(let[l,d]of r)if(!s.has(l)||!(d instanceof R__namespace.Text))throw new p("paragraph-set-mismatch");return a}function va(t,e,n){let{root:r}=We(t);return te(r)?Promise.resolve():n?.aborted?Promise.reject(new p("initialization-aborted")):new Promise((o,i)=>{let a=c=>{clearTimeout(d),r.unobserve(s),n?.removeEventListener("abort",l),c?i(c):o();},s=()=>{te(r)&&a();},l=()=>a(new p("initialization-aborted")),d=setTimeout(()=>a(new p("initialization-timeout")),e);r.observe(s),n?.addEventListener("abort",l,{once:true});})}var xe=64*1024*1024,V="docx-package-blobs-v1";function So(t){if(t instanceof Uint8Array)return new Uint8Array(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t)){let e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}return null}function Eo(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:0}function Ie(t,e){return Object.freeze(e===void 0?{code:t}:{code:t,detail:e})}var M=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let n=this.shared.get(e),r=So(n);return !r||typeof n!="object"||n===null?null:this.verify(e,n,r)?r:null}has(e){let n=this.shared.get(e);return n===void 0?false:this.verified.has(n)?true:this.get(e)!==null}poisonedDigest(){for(let e of this.poisoned)return e;return null}observeChanges(e){let n=r=>{e([...r.keysChanged]);};return this.shared.observe(n),()=>this.shared.unobserve(n)}verifyNow(e){for(let n of e)if(this.shared.has(n)&&this.get(n)===null)return n;return null}totalByteLength(){let e=0;return this.shared.forEach(n=>{e+=Eo(n);}),e}put(e,n){if(!this.shared.has(e)){if(this.totalByteLength()+n.byteLength>xe)throw new p("blob-store-full");this.shared.set(e,new Uint8Array(n));}}verify(e,n,r){return this.verified.has(n)?true:this.poisoned.has(e)?false:layout.sha256FontBytes(r)!==e?(this.poisoned.add(e),false):(this.verified.add(n),true)}};function ne(t,e){let{limits:n}=t,r=t.nodeCount();if(r>n.maxNodes)return Ie("too-many-nodes",`${r}`);let o=t.schema.parts.size;if(o>n.maxParts)return Ie("too-many-parts",`${o}`);let i=0;if(t.schema.relationships.forEach(s=>{i+=s instanceof R__namespace.Map?s.size:0;}),i>n.maxRelationships)return Ie("too-many-relationships",`${i}`);let a=e.totalByteLength();return a>xe?Ie("blob-store-full",`${a}`):null}var Dn=20*1024*1024,Xe=3e4,Lo=4e3,ko=1500,Po="docx-collaboration-seeds-v1",$e="docxEditorSeedCandidate",Ao=/^[0-9a-f]{16}$/,Oo=256;function Je(t){if(!(t instanceof Uint8Array)||t.byteLength===0)throw new p("invalid-baseline");if(t.byteLength>Dn)throw new p("baseline-too-large");let e=store.readOoxmlPackage(t,{zip:{maxEntries:1e4,maxTotalBytes:Dn,maxRatio:200}});if(!e.ok)throw new p("invalid-baseline");let n=e.package.parts.get(e.package.mainDocumentPart);if(!n)throw new p("no-main-document-part");return new store.TreePackageStore(e.package,store.normalizeParagraphIdentity(n)).currentPackage()}function No(t,e){for(let n of t.binaries())if(!e.has(n.digest))return false;return true}function re(t,e,n,r){let o=t.schema.meta,i=()=>o.get("initialized")===true&&No(t,e),a=()=>{let l=e.poisonedDigest();return l?new p("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let s=a();return s?Promise.reject(s):r?.aborted?Promise.reject(new p("initialization-aborted")):new Promise((l,d)=>{let c=f=>{clearTimeout(m),o.unobserve(h),t.doc.off("afterTransaction",h),r?.removeEventListener("abort",u),f?d(f):l();},h=()=>{let f=a();if(f){c(f);return}i()&&c();},u=()=>c(new p("initialization-aborted")),m=setTimeout(()=>c(new p("initialization-timeout")),n);o.observe(h),t.doc.on("afterTransaction",h),r?.addEventListener("abort",u,{once:true});})}function He(t){return t.getArray(Po)}function ve(t){return He(t).length}function _n(t,e){let n=He(t),r=()=>{n.length>1&&e();};return r(),n.observe(r),()=>n.unobserve(r)}function Mo(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}function To(t,e){let n=[...t.getStates().entries()].slice(0,Oo);for(let[r,o]of n){if(r===t.clientID)continue;let i=o[$e];if(!(typeof i!="string"||!Ao.test(i))&&i<e)return true}return false}async function Bn(t,e,n,r){try{return await re(t,e,n,r),!0}catch(o){if(o instanceof p&&o.code==="initialization-timeout")return false;throw o}}function Do(t,e,n){let r=t.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():n?.aborted?Promise.reject(new p("initialization-aborted")):new Promise((i,a)=>{let s=h=>{clearTimeout(c),r.unobserve(l),n?.removeEventListener("abort",d),h?a(h):i();},l=()=>{o()&&s();},d=()=>s(new p("initialization-aborted")),c=setTimeout(()=>s(new p("initialization-timeout")),e);r.observe(l),n?.addEventListener("abort",d,{once:true});})}async function Un(t){let{ydoc:e,awareness:n,registry:r,blobs:o}=t,i=t.probeTimeoutMs??Lo,a=t.electionWindowMs??ko,s=t.timeoutMs??Xe,l=async()=>(await Do(r,s,t.signal),"joined");if(await Bn(r,o,i,t.signal))return l();let d=Mo();n.setLocalStateField($e,d);try{let c=await Bn(r,o,a,t.signal);if(!c&&To(n,d)&&(await re(r,o,s,t.signal),c=!0),c)return await l();if(r.schema.meta.get("initialized")===!0)return await re(r,o,s,t.signal),await l();let h=await G(r,Je(t.document),o);if(!h.ok)throw new p(h.code);return e.transact(()=>{r.schema.meta.set("documentId",t.documentId),He(e).push([d]);}),"seeded"}finally{n.setLocalStateField($e,null);}}var Se=class{constructor(e,n){this.knows=e;this.allocator=new W(n);}knows;allocator;toLogical=new Map;get replicaId(){return this.allocator.replicaId}reset(){this.toLogical.clear();}mint(e){let n=this.allocator.take();return this.toLogical.set(e,n),n}resolve(e){return this.toLogical.get(e)??e}translate(e){let n=[],r=false;for(let o of e.effects){let i=this.translateEffect(o);i!==o&&(r=true),n.push(i);}return r?Object.freeze({effects:Object.freeze(n)}):e}translateEffect(e){switch(e.kind){case "putNode":{let n=this.translateDescriptor(e.descriptor);return n.logicalId===e.descriptor.logicalId?e:{...e,descriptor:n}}case "spliceText":case "setAttribute":case "setNamespaceBinding":{let n=this.resolve(e.logicalId);return n===e.logicalId?e:{...e,logicalId:n}}case "spliceChildren":{let n=this.resolve(e.parentLogicalId),r=e.childLogicalIds.map(i=>this.resolve(i));return n===e.parentLogicalId&&r.every((i,a)=>i===e.childLogicalIds[a])?e:{...e,parentLogicalId:n,childLogicalIds:r}}case "moveNode":{let n=this.resolve(e.logicalId),r=this.resolve(e.destinationParentLogicalId);return n===e.logicalId&&r===e.destinationParentLogicalId?e:{...e,logicalId:n,destinationParentLogicalId:r}}case "putXmlPart":{let n=this.resolve(e.rootLogicalId);return n===e.rootLogicalId?e:{...e,rootLogicalId:n}}default:return e}}translateDescriptor(e){let n=this.resolve(e.logicalId);return this.knows(n)?{...e,logicalId:n}:{...e,logicalId:this.mint(e.logicalId)}}};function Bo(t){let e=0;return t.schema.nodes.forEach(n=>{b(n)&&n.get(_)===true&&(e+=1);}),e}function _o(t){let e=0;return t.schema.relationships.forEach(n=>{e+=n instanceof R__namespace.Map?n.size:0;}),e}function Ge(t,e){return Object.freeze({nodes:t.nodeCount(),tombstonedNodes:Bo(t),maxNodes:t.limits.maxNodes,relationships:_o(t),maxRelationships:t.limits.maxRelationships,parts:t.schema.parts.size,maxParts:t.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:xe})}function Da(t){let e=new A(t);try{let n=new M(t.getMap(V));return Ge(e,n)}finally{e.destroy();}}var Ee="docxEditor",T=256,qe=256;function jn(t){let e=t.actorId.trim(),n=t.name.trim();if(e.length===0||e.length>T||n.length===0||n.length>T)throw new p("invalid-identity");if(t.color!==void 0&&t.color.length>64)throw new p("invalid-identity-color");return Object.freeze({actorId:e,name:n,...t.color?{color:t.color}:{},role:t.role??"human"})}function Kn(t){let e=t.trim();if(e.length===0||e.length>T)throw new p("invalid-document-id");return e}function Fn(t){let e=t?.trim()||globalThis.crypto.randomUUID();if(e.length>T)throw new p("invalid-session-id");return e}function zn(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;return typeof e.paragraphId!="string"||e.paragraphId.length!==8||!Number.isSafeInteger(e.offset)||e.offset<0?null:{paragraphId:e.paragraphId.toUpperCase(),offset:e.offset}}function Yo(t){if(t===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=zn(e.anchor),r=zn(e.head);if(n&&r)return e.kind==="cells"?{anchor:n,head:r,kind:"cells"}:{anchor:n,head:r};if(typeof e.paragraphId=="string"&&e.paragraphId.length===8&&Number.isSafeInteger(e.start)&&Number.isSafeInteger(e.end)&&e.start>=0&&e.end>=0){let o=e.paragraphId.toUpperCase();return {anchor:{paragraphId:o,offset:e.start},head:{paragraphId:o,offset:e.end}}}}function Ze(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;if(typeof e.actorId!="string"||e.actorId.length===0||e.actorId.length>T||typeof e.name!="string"||e.name.length===0||e.name.length>T)return null;let n=collaboration.safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...n?{color:n}:{},role:r},i=Yo(e.selection);return i?{...o,selection:i}:o}function jo(t){let e=new A(t),n=null;try{if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new p("not-initialized");if(ve(t)>1)throw new p("concurrent-seed");let r=new M(t.getMap(V)),o=ne(e,r);if(o)throw new p(o.code,o.detail);n=new Y(e,r);let i=n.current(),a=r.poisonedDigest();if(a)throw new p("blob-digest-mismatch",a);if(!i.ok)throw new p(i.code);return store.writeOoxmlPackage(i.package)}finally{n?.destroy(),e.destroy();}}var $o=3,Xo=5e3,Jo=2e3,Ho=Symbol("createDocumentCollaboration.attachWatchdogMs"),Qe=class{constructor(e,n,r,o,i,a,s,l,d,c,h){this.ydoc=e;this.awareness=n;this.registry=a;this.materializer=s;this.identityMap=l;this.blobs=d;this.offlineEditing=h;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new R__namespace.UndoManager([...a.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:Xo,deleteFilter:a.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),n.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(u=>{let m=d.verifyNow(u);m&&this.setStatus("error","blob-digest-mismatch",m);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=_n(e,()=>{this.setStatus("error","concurrent-seed");}),this.attachWatchdog=setTimeout(()=>{this.attachWatchdog=null,!(this.destroyed||this.port)&&console.warn(`[docx-editor] The collaboration session for "${this.documentId}" was created ${c}ms ago and no editor attached its document port. The session reports "ready" but no edits replicate. Remount the editor when the session appears \u2014 for example pass key={session.sessionId} \u2014 so collaborationModule({ session }) attaches it.`);},c),this.attachWatchdog.unref?.();}ydoc;awareness;registry;materializer;identityMap;blobs;offlineEditing;documentId;sessionId;currentIdentity;currentSelection;attachWatchdog=null;statusState=collaboration.createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-document-local"});undoManager;port=null;detachPort=null;applyingRemote=false;realignedInBatch=false;journalsHeldDuringRemote=[];drainingHeldJournals=false;remoteCounter=0;destroyed=false;refusedInARow=0;stopBlobWatch;stopSeedWatch;get identity(){return this.currentIdentity}clearAttachWatchdog(){this.attachWatchdog!==null&&(clearTimeout(this.attachWatchdog),this.attachWatchdog=null);}status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}resourceUsage(){return Ge(this.registry,this.blobs)}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,n,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(n!==void 0){this.setStatus(e,n,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let n=this.refuseAttach(e);if(n)return n;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{if(!this.destroyed){if(this.applyingRemote){this.journalsHeldDuringRemote.push(o);return}this.realignedInBatch||this.applyJournal(o);}});return this.detachPort=()=>{this.flushPendingJournals(),r(),this.port===e&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}refuseAttach(e){return this.destroyed?()=>{}:this.port?(this.port!==e&&this.setStatus("error","port-already-attached"),()=>{}):e.documentId!==this.documentId?(this.setStatus("error","document-id-mismatch"),()=>{}):null}canWriteSharedState(){if(this.destroyed)return false;let e=this.statusState.status();return e==="ready"||this.offlineEditing&&e==="disconnected"}gateOperations(e,n){return this.destroyed?"collaboration-session-destroyed":this.canWriteSharedState()?this.port?null:"collaboration-session-not-attached":"collaboration-session-not-ready"}canUndo(){return this.canWriteSharedState()&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return this.canWriteSharedState()&&this.undoManager.redoStack.length>0}undo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.undoStack.length===0?false:(this.undoManager.undo(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.undoManager.redo(),true)}flushPendingJournals(){this.port?.flushPendingJournals();}setLocalSelection(e){if(!this.destroyed){if(!e){this.publishAwareness();return}this.publishAwareness({anchor:{paragraphId:e.anchor.paragraphId.toUpperCase(),offset:Math.max(0,e.anchor.offset)},head:{paragraphId:e.head.paragraphId.toUpperCase(),offset:Math.max(0,e.head.offset)},...e.kind==="cells"?{kind:"cells"}:{}});}}participants(){let e=[],n=[...this.awareness.getStates().entries()].slice(0,qe);for(let[r,o]of n){let i=Ze(o[Ee]);i&&e.push({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},role:i.role,isLocal:r===this.awareness.clientID});}return Object.freeze(e)}subscribeParticipants(e){return this.participantListeners.add(e),()=>this.participantListeners.delete(e)}remoteSelections(){let e=this.port;if(!e)return [];let n=i=>{let a=e.paragraphByStableId(i.paragraphId);return a?Object.freeze({paragraphId:a.paragraphId,nodeId:a.nodeId,offset:Math.min(i.offset,a.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,qe),o=[];for(let[i,a]of r){if(i===this.awareness.clientID)continue;let s=Ze(a[Ee]);if(!s?.selection)continue;let l=n(s.selection.anchor),d=n(s.selection.head);!l||!d||o.push(Object.freeze({actorId:s.actorId,name:s.name,...s.color?{color:s.color}:{},...s.selection.kind==="cells"?{kind:"cells"}:{},anchor:l,head:d}));}return Object.freeze(o)}subscribeRemoteSelections(e){return this.selectionListeners.add(e),()=>this.selectionListeners.delete(e)}setIdentity(e){if(this.destroyed)return;let n=e.name===void 0?this.currentIdentity.name:e.name.trim();if(n.length===0||n.length>T)throw new p("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new p("invalid-identity-color");r=collaboration.safeParticipantColor(e.color);}this.currentIdentity=Object.freeze({actorId:this.currentIdentity.actorId,name:n,...r?{color:r}:{},role:this.currentIdentity.role??"human"}),this.publishAwareness(this.currentSelection);}destroy(){this.destroyed||(this.clearAttachWatchdog(),this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.stopBlobWatch(),this.stopSeedWatch(),this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.materializer.destroy(),this.registry.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}applyJournal(e){let n=this.identityMap.translate(e),r=this.collectJournalBlobs(e);if(r!==null&&r.ok===false){this.refuseLocalJournal(r.failure);return}let o=this.ydoc.transact(()=>{if(r!==null){let a=this.putJournalBlobs(r.payloads);if(a!==null)return a}let i=Be(this.registry,n);return i.ok?null:{code:i.code,...i.detail?{detail:i.detail}:{}}},this.localOrigin);if(o===null){this.refusedInARow=0;return}this.refuseLocalJournal(o);}collectJournalBlobs(e){let n=this.port;if(!n)return e.effects.some(i=>i.kind==="putBinary")?{ok:false,failure:Object.freeze({code:"collaboration-session-not-attached"})}:null;let r=Ht(e.effects,Jt(n));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{Gt(this.blobs,e);}catch(n){return n instanceof p?Object.freeze({code:n.code,...n.detail?{detail:n.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){this.undoManager.stopCapturing();let n=this.statusState.snapshot();this.refusedInARow+=1,this.setStatus("error",e.code,e.detail),this.publishSharedToPort(),this.realignedInBatch=true,queueMicrotask(()=>{this.realignedInBatch=false;});let r=this.statusState.snapshot().reason;this.refusedInARow<$o&&this.statusState.status()==="error"&&r!==void 0&&r.code===e.code&&r.detail===e.detail&&(n.status==="ready"||n.status==="disconnected")&&this.setStatus(n.status,n.reason?.code,n.reason?.detail);}onYjsTransaction=e=>{this.destroyed||!this.port||e.origin!==this.localOrigin&&this.publishSharedToPort();};publishSharedToPort(){let e=this.port;if(!(!e||this.applyingRemote)){this.applyingRemote=true;try{let n=ne(this.registry,this.blobs);if(n){this.setStatus("error",n.code,n.detail);return}let r=this.materializer.current(),o=this.blobs.poisonedDigest();if(o){this.setStatus("error","blob-digest-mismatch",o);return}if(!r.ok){this.setStatus("error",r.code);return}let i=ht(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let a=e.applyRemotePackage(r.package,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!a.ok){this.setStatus("error","remote-apply-failed",a.reason);return}a.changed&&this.identityMap.reset();}catch(n){this.setStatus("error",n instanceof p?n.code:"remote-apply-failed",n instanceof p?n.detail:void 0);}finally{this.applyingRemote=false,this.drainJournalsHeldDuringRemote();}}}drainJournalsHeldDuringRemote(){if(!this.drainingHeldJournals){this.drainingHeldJournals=true;try{for(;this.journalsHeldDuringRemote.length>0;){if(this.destroyed||this.realignedInBatch){this.journalsHeldDuringRemote.length=0;return}let e=this.journalsHeldDuringRemote.shift();e&&this.applyJournal(e);}}finally{this.drainingHeldJournals=false;}}}onAwarenessChange=()=>{if(this.destroyed)return;let e=this.remoteSelections();for(let r of [...this.selectionListeners])r(e);let n=this.participants();for(let r of [...this.participantListeners])r(n);};publishAwareness(e){this.currentSelection=e;let n={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...e?{selection:e}:{}};this.awareness.setLocalStateField(Ee,n);}setStatus(e,n,r){if(!this.statusState.set(e,n,r))return;let o=this.statusState.snapshot();for(let i of [...this.statusListeners])i(o.status,o.reason?.code,o.reason?.detail);}};async function rs(t){let e=t[Ho]??Jo,n=Kn(t.documentId),r=Fn(t.sessionId),o=jn(t.identity),i=new A(t.ydoc);try{return await Go(t,{attachWatchdogMs:e,documentId:n,sessionId:r,identity:o,registry:i})}catch(a){throw i.destroy(),a}}async function Go(t,e){let{attachWatchdogMs:n,documentId:r,sessionId:o,identity:i,registry:a}=e,s=new Se(h=>a.hasNode(h)),l=new M(t.ydoc.getMap(V));if(t.bootstrap.kind==="create"){if(a.schema.meta.get("initialized")===true)throw new p("already-initialized");let h=await G(a,Je(t.bootstrap.document),l);if(!h.ok)throw new p(h.code);t.ydoc.transact(()=>{a.schema.meta.set("documentId",r);});}else if(t.bootstrap.kind==="create-or-join"){if(await Un({ydoc:t.ydoc,awareness:t.awareness,registry:a,blobs:l,documentId:r,document:t.bootstrap.document,probeTimeoutMs:t.bootstrap.probeTimeoutMs,electionWindowMs:t.bootstrap.electionWindowMs,timeoutMs:t.bootstrap.timeoutMs,signal:t.bootstrap.signal})==="joined"){if(a.schema.meta.get("documentId")!==r)throw new p("document-id-mismatch");a.rebuildDerivedIndexes();}}else {if(await re(a,l,t.bootstrap.timeoutMs??Xe,t.bootstrap.signal),a.schema.meta.get("documentId")!==r)throw new p("document-id-mismatch");a.rebuildDerivedIndexes();}if(ve(t.ydoc)>1)throw new p("concurrent-seed");let d=ne(a,l);if(d)throw new p(d.code,d.detail);let c=new Y(a,l);try{let h=c.current(),u=l.poisonedDigest();if(u)throw new p("blob-digest-mismatch",u);if(!h.ok)throw new p(h.code);let m=store.writeOoxmlPackage(h.package),f=new Qe(t.ydoc,t.awareness,r,o,i,a,c,s,l,n,t.offlineEditing===!0);return Object.freeze({document:m,session:f,destroy:()=>f.destroy()})}catch(h){throw c.destroy(),h}}exports.a=On;exports.b=Nn;exports.c=Fe;exports.d=p;exports.e=We;exports.f=xo;exports.g=Ia;exports.h=xa;exports.i=va;exports.j=Da;exports.k=jo;exports.l=Ho;exports.m=rs;
@@ -1,3 +0,0 @@
1
- import*as R from'yjs';import {writeOoxmlPackage,partNameKey,relsPartNameFor,CUSTOM_XML_PROPS_TYPE,readOoxmlPackage,TreePackageStore,normalizeParagraphIdentity,ORIGIN_IDS,isDangerousKey,normalizePartName,WML_NAMESPACE_URI,DATASTORE_NAMESPACE_URI,CUSTOM_XML_REL,CUSTOM_XML_PROPS_REL,buildRelationshipSet,resolveRelationship,XML_NAMESPACE_URI}from'@docx-editor.dev/core/store';import {createCollaborationStatusTracker,safeParticipantColor}from'@docx-editor.dev/core/collaboration';import {sha256FontBytes}from'@docx-editor.dev/core/layout';import'@docx-editor.dev/core/collaboration/replication';var Bn=new Set(["paraId","textId","id","numId","bookmarkId"]);function Je(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}function He(t){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Je(e)}function Ee(t){return /^[0-9a-f]{32}$/.test(t)}function Ge(t,e){if(!Ee(t))throw new Error("invalid replica identity");if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid logical-id counter");return `lid:${t}:${e.toString(10)}`}function we(t,e){return `yjs:${t}:${e}`}function Re(t){let e=[];for(let n of t)Bn.has(n.localName)&&e.push(n.value);return e}var V=class{replicaId;next=0;constructor(e){if(this.replicaId=e??He(),!Ee(this.replicaId))throw new Error("invalid replica identity")}take(){let e=Ge(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};var A=Object.freeze({maxNodes:2e5,maxTreeDepth:256,maxTextLength:1048576,maxAttributes:4096,maxChildren:1e5,maxParts:512,maxRelationships:1e4,maxBlobBytes:32*1024*1024,maxDigestLength:80,maxMediaTypeLength:256,maxStorageKeyLength:512,maxStringLength:4096}),Un=/^sha256:[0-9a-f]{64}$/;function Ze(t){return t?Object.freeze({...A,...t}):A}function m(t){return isDangerousKey(t)?"prototype-key":null}function C(t,e){return typeof t!="string"||t.length>e?"invalid-string":isDangerousKey(t)?"prototype-key":null}function w(t){let e=m(t);if(e)return e;if(typeof t!="string"||t.length===0)return "unsafe-part-name";let n=normalizePartName(t);return !n.ok||n.partName!==t?"unsafe-part-name":null}function Qe(t){for(let e of Object.keys(t)){let n=m(e);if(n)return n}return !Un.test(t.digest)||t.digest.length>80||!Number.isSafeInteger(t.size)||t.size<0?"invalid-blob-descriptor":t.size>A.maxBlobBytes?"blob-too-large":C(t.mediaType,A.maxMediaTypeLength)||t.mediaType.length===0||C(t.storageKey,A.maxStorageKeyLength)||t.storageKey.length===0?"invalid-blob-descriptor":null}var et=1,tt=2,nt=1,rt=1,Yn="docx-package-meta-v1",zn="docx-package-nodes-v1",jn="docx-package-parts-v1",Kn="docx-package-rels-v1",Fn="docx-package-overrides-v1",Vn="docx-package-defaults-v1",Wn="docx-package-binaries-v1",$n="docx-package-namespaces-v1",Xn="docx-package-attributes-v1",Jn="docx-package-bindings-v1",z="s",T="t",oe="children",D="deleted",W="replacedBy",S="",ot="-",it=Object.freeze({kind:"docx-package-bootstrap"}),at=Object.freeze({kind:"docx-package-journal"});function ie(t){return t.kind==="textValue"}function v(t){return !ie(t)}var Hn=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),Gn=200;function st(t){let e=new Map;for(let n of t)Hn.has(n.code)&&e.set(n.code,(e.get(n.code)??0)+1);return e.size===0?null:[...e].sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${n}=${r}`).join(",").slice(0,Gn)}function lt(t){return {meta:t.getMap(Yn),nodes:t.getMap(zn),parts:t.getMap(jn),relationships:t.getMap(Kn),overrides:t.getMap(Fn),defaults:t.getMap(Vn),binaries:t.getMap(Wn),namespaces:t.getMap($n),attributes:t.getMap(Xn),bindings:t.getMap(Jn)}}var dt=[["http://schemas.openxmlformats.org/wordprocessingml/2006/main","w"],["http://schemas.openxmlformats.org/officeDocument/2006/relationships","r"],["http://schemas.openxmlformats.org/package/2006/relationships","pr"],["http://schemas.openxmlformats.org/package/2006/content-types","ct"],["http://www.w3.org/XML/1998/namespace","xml"],["http://www.w3.org/2000/xmlns/","xmlns"],["http://schemas.openxmlformats.org/drawingml/2006/main","a"],["http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing","wp"],["http://schemas.openxmlformats.org/drawingml/2006/picture","pic"],["http://schemas.openxmlformats.org/officeDocument/2006/math","m"],["http://schemas.openxmlformats.org/markup-compatibility/2006","mc"],["http://schemas.microsoft.com/office/word/2010/wordml","w14"],["http://schemas.microsoft.com/office/word/2012/wordml","w15"],["http://schemas.microsoft.com/office/word/2015/wordml/symex","w16se"],["http://schemas.microsoft.com/office/word/2016/wordml/cid","w16cid"],["http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument","od"],["http://schemas.openxmlformats.org/officeDocument/2006/extended-properties","ep"],["http://schemas.openxmlformats.org/package/2006/metadata/core-properties","cp"],["http://purl.org/dc/elements/1.1/","dc"],["http://purl.org/dc/terms/","dcterms"],["http://www.w3.org/2001/XMLSchema-instance","xsi"],["http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes","vt"],["http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas","wpc"],["http://schemas.microsoft.com/office/word/2010/wordprocessingGroup","wpg"],["http://schemas.microsoft.com/office/word/2010/wordprocessingInk","wpi"],["http://schemas.microsoft.com/office/word/2010/wordprocessingShape","wps"],["http://schemas.openxmlformats.org/drawingml/2006/chart","c"],["http://schemas.openxmlformats.org/schemaLibrary/2006/main","sl"]],qn=new Map(dt),Zn=new Map(dt.map(([t,e])=>[e,t]));function Qn(t){let e=0xcbf29ce484222325n,n=0x100000001b3n;for(let r=0;r<t.length;r+=1)e^=BigInt(t.charCodeAt(r)),e=e*n&0xffffffffffffffffn;return e.toString(16).padStart(16,"0")}function $(t){return t.length===0?ot:qn.get(t)??`n${Qn(t)}`}function j(t,e,n){let r=$(e);return e.length===0||m(r)||C(e,n)||t.get(r)!==e&&t.set(r,e),r}function X(t,e){if(e===ot||m(e))return "";let n=t.get(e);return typeof n=="string"?n:Zn.get(e)??""}function Ce(t,e,n,r){return `${t}${S}${e}${S}${n}${S}${r}`}function ae(t){let e=t.split(S);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function Le(t,e,n){return `${t}${S}${e}${S}${n}`}function se(t){let e=t.split(S);if(e.length!==3)return null;let n=e[0],r=e[1],o=e[2];return n.length===0||o.length===0?null:{logicalId:n,namespaceId:r,localName:o}}function ke(t,e){return `${t}${S}${e}`}function le(t){let e=t.split(S);if(e.length!==2)return null;let n=e[0],r=e[1];return n.length===0?null:{logicalId:n,prefix:r}}function ct(t,e){return `${t}${S}${e}`}function ut(t){let e=t.indexOf(S);return e<0?{prefix:"",value:t}:{prefix:t.slice(0,e),value:t.slice(e+1)}}function pt(t){let e=new R.Map;e.set(z,Ce(t.kind,t.namespaceId,t.localName,t.prefix??""));let n=new R.Array;return t.childIds&&t.childIds.length>0&&n.push([...t.childIds]),e.set(oe,n),e}function ht(t){let e=new R.Map;return e.set(T,new R.Text(t)),e}function mt(t,e,n){let r=new R.Map;return r.set("id",t),r.set("rootId",e),r.set("contentType",n),r}function gt(t){let e=new R.Map;return e.set("ownerPart",t.ownerPart),e.set("id",t.id),e.set("type",t.type),e.set("rawTarget",t.rawTarget),e.set("targetMode",t.targetMode),e.set("order",t.order),e}function ft(t){let e=new R.Map;return e.set("digest",t.digest),e.set("size",t.size),e.set("mediaType",t.mediaType),e.set("storageKey",t.storageKey),e}function yt(t){t.set("protocolVersion",et),t.set("sharedSchemaVersion",tt),t.set("repairVersion",nt),t.set("canonicalModelVersion",rt),t.set("initialized",true);}function b(t){return t instanceof R.Map}function k(t){if(!b(t))return null;let e=t.get(oe);return e instanceof R.Array?e:null}function J(t){return b(t)&&t.get(T)instanceof R.Text}function B(t){return b(t)&&t.get(D)===true}function Pe(t){if(!b(t))return null;let e=t.get(W);return typeof e=="string"&&e.length>0?e:null}function de(t){return typeof t=="string"?t:""}function bt(t,e){return t<e?-1:t>e?1:0}function Ae(t,e){return `${t}${S}${e}`}function tr(t){let e=t.indexOf(S);return e<0?t:t.slice(0,e)}function It(t){let e=[];return t.forEach((n,r)=>{!b(n)||m(r)||n.forEach(o=>{if(!b(o))return;let i=de(o.get("id")),a=de(o.get("type"));if(i.length===0||a.length===0)return;let s=de(o.get("ownerPart"))||tr(r);if(m(s))return;let l=o.get("order");e.push({ownerPart:s,id:i,type:a,rawTarget:de(o.get("rawTarget")),targetMode:o.get("targetMode")==="External"?"External":"Internal",order:typeof l=="number"&&Number.isSafeInteger(l)?l:0});});}),e.sort((n,r)=>n.order-r.order||bt(n.ownerPart,r.ownerPart)||bt(n.id,r.id)),e}function xt(t,e){return t.nodes.observeDeep(e.onNodeEvents),t.attributes.observe(e.onAttributeEvent),t.bindings.observe(e.onBindingEvent),t.relationships.observeDeep(e.onRelationshipChange),t.parts.observeDeep(e.onPartChange),()=>{t.nodes.unobserveDeep(e.onNodeEvents),t.attributes.unobserve(e.onAttributeEvent),t.bindings.unobserve(e.onBindingEvent),t.relationships.unobserveDeep(e.onRelationshipChange),t.parts.unobserveDeep(e.onPartChange);}}function nr(t,e){let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1){let o=t[r]-e[r];if(o!==0)return o}return t.length-e.length}function vt(t,e){let n=t.childrenSnapshot.get(e);return n||(k(t.nodes.get(e))?.toArray()??[])}function rr(t,e){let n=t.nodes.get(e);return !b(n)||B(n)}function or(t,e,n,r){let o=[],i=new Set,a=r,s;for(;;){if(i.has(a)||(i.add(a),rr(t,a)))return null;s=e.get(a);let u=t.parentIndex.get(a);if(s!==void 0){if(u!==void 0)return "fallback";break}if(u===void 0)return n.has(a)?"deferred":null;o.push(a),a=u;}let l=[s],d=a;for(let u=o.length-1;u>=0;u-=1){let p=o[u],c=vt(t,d).indexOf(p);if(c<0)return null;l.push(c),d=p;}return l}function St(t,e){let n=new Set(e);for(let i of n)t.parentIndex.delete(i);let r=new Map;t.partRoots.forEach((i,a)=>{r.has(i)||r.set(i,a);});let o=[...n];for(;o.length>0;){let i=[];for(let a of o){let s=null,l=false;for(let d of t.listings.get(a)??[]){if(d===a)continue;let u=or(t,r,n,d);if(u==="fallback")return false;if(u==="deferred"){l=true;continue}if(u===null)continue;let p=vt(t,d).indexOf(a);if(p<0)continue;let c=[...u,p];(!s||nr(c,s.rank)<0)&&(s={rank:c,parent:d});}if(l){i.push(a);continue}s&&t.parentIndex.set(a,s.parent),n.delete(a);}if(i.length===o.length)return false;o=i;}return true}function Et(t,e){let{nodes:n,parentIndex:r,childrenSnapshot:o,partRoots:i}=t;if(e)for(let a of e)r.delete(a);for(let a of i){let s=new Set,l=[{id:a,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){s.delete(d.id);continue}let u=d.id;if(d.parent!==null&&(e===null||e.has(u))&&(r.has(u)||r.set(u,d.parent)),s.has(u))continue;let p=n.get(u);if(!b(p)||B(p))continue;let c=o.get(u)??k(p)?.toArray()??[];s.add(u),l.push({id:u,parent:null,exit:true});let h=new Set,g=[];for(let y of c)h.has(y)||y===u||(h.add(y),g.push(y));for(let y=g.length-1;y>=0;y-=1)l.push({id:g[y],parent:u,exit:false});}}}function wt(t,e){return `${t}${S}${e}`}function Oe(t,e,n,r,o){if(m(n)||m(r.localName))return;let i=j(t.namespaces,r.namespaceUri,e),a=Le(n,i,r.localName);m(a)||t.attributes.set(a,ct(r.prefix??"",o));}function Rt(t,e,n,r){t.attributes.delete(Le(e,$(n),r));}function Ne(t,e,n,r,o){if(m(n)||m(r))return;let i=j(t.namespaces,o,e),a=ke(n,r);m(a)||t.bindings.set(a,i);}function Ct(t,e,n){t.bindings.delete(ke(e,n));}function Me(t,e,n,r,o,i){let{prefix:a,value:s}=ut(i),l=e.get(n);l||(l=new Map,e.set(n,l)),l.set(wt(r,o),{namespaceUri:X(t.namespaces,r),localName:o,prefix:a.length>0?a:void 0,value:s});}function Lt(t,e,n,r){let o=t.get(e);o&&(o.delete(wt(n,r)),o.size===0&&t.delete(e));}function Te(t,e,n,r,o){let i=e.get(n);i||(i=new Map,e.set(n,i)),i.set(r,{prefix:r,namespaceUri:X(t.namespaces,o)});}function kt(t,e,n){let r=t.get(e);r&&(r.delete(n),r.size===0&&t.delete(e));}function At(t,e){let n=t.get(e);if(!b(n))return null;if(J(n)){let r=n.get(T);return {isText:true,textLength:r instanceof R.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:k(n)?.toArray()??[]}}function Ot(t,e){let n=t.get(e);if(!b(n))return null;if(J(n))return "textValue";let r=n.get(z);return ae(typeof r=="string"?r:"").kind}function Nt(t,e){if(t.length!==e.length)return false;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return false;return true}function K(t){return typeof t=="string"?t:""}function Mt(t){let e=[];return t.forEach((n,r)=>{if(!b(n)||m(r))return;let o=K(n.get("rootId"));o.length!==0&&e.push({name:r,id:K(n.get("id")),rootLogicalId:o,contentType:K(n.get("contentType"))});}),e.sort((n,r)=>n.name<r.name?-1:n.name>r.name?1:0),e}function Tt(t){let e=new Map;return t.forEach((n,r)=>{typeof n=="string"&&!m(r)&&e.set(partNameKey(r),n);}),e}function Dt(t){let e=new Map;return t.forEach((n,r)=>{typeof n=="string"&&!m(r)&&e.set(r,n);}),e}function Bt(t){let e=[];return t.forEach((n,r)=>{if(!b(n)||m(r))return;let o=K(n.get("digest")),i=n.get("size"),a=K(n.get("mediaType")),s=K(n.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:a,storageKey:s});}),e}function ar(t){return t?._item??null}function sr(t){return t.content instanceof R.ContentType}function Ut(t){return e=>{let n=e.parent;if(n===null)return true;if(n===t)return false;let r=ar(n);return r===null||r.parent!==t?true:!sr(e)}}function lr(t){let e=t._item;return e?we(e.id.client,e.id.clock):null}function zt(t){return typeof t=="string"?t:""}var _=class{constructor(e,n){this.doc=e;this.schema=lt(e),this.limits=Ze(n),this.stopObserving=xt(this.schema,{onNodeEvents:r=>{this.bulkLoad>0||this.applyChildArrayEvents(r);},onAttributeEvent:r=>{this.bulkLoad>0||this.applyAttributeMapEvent(r);},onBindingEvent:r=>{this.bulkLoad>0||this.applyBindingMapEvent(r);},onRelationshipChange:()=>{this.relationshipCountCache=-1;},onPartChange:()=>{this.partCountCache=-1;}});}doc;schema;limits;parentIndex=new Map;listings=new Map;childrenSnapshot=new Map;adoptees=new Map;tombstoneSources=new Map;tombstoneSurvivor=new Map;attributesByNode=new Map;bindingsByNode=new Map;bulkLoad=0;unobservedWrites=0;nodeCountCache=-1;pendingNodeAdds=0;relationshipCountCache=-1;partCountCache=-1;stopObserving;destroy(){this.stopObserving();}beginBulkLoad(){this.bulkLoad+=1;}endBulkLoad(){this.bulkLoad=Math.max(0,this.bulkLoad-1),this.bulkLoad===0&&this.rebuildDerivedIndexes();}trackedTypes(){return [this.schema.meta,this.schema.nodes,this.schema.parts,this.schema.relationships,this.schema.overrides,this.schema.defaults,this.schema.binaries,this.schema.attributes,this.schema.bindings]}undoDeleteFilter(){return Ut(this.schema.nodes)}encodeSnapshot(){return R.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return R.encodeStateAsUpdate(this.doc,e)}partEntries(){return Mt(this.schema.parts)}partCount(){return this.partCountCache<0&&(this.partCountCache=this.partEntries().length),this.partCountCache}relationshipCount(){return this.relationshipCountCache<0&&(this.relationshipCountCache=this.relationships().length),this.relationshipCountCache}mainDocumentPart(){return zt(this.schema.meta.get("mainDocumentPart"))}record(e){if(m(e))return null;let n=this.schema.nodes.get(e);if(!b(n))return null;if(J(n)){let r=n.get(T),o=r instanceof R.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return this.elementRecord(e,n)}parentOf(e){return this.parentIndex.get(e)??null}identityMeta(e){let n=this.schema.nodes.get(e);if(!n)return null;let r=this.record(e),o=r&&v(r)?r.attributes:[];return {logicalId:e,yjsItemKey:lr(n),wordFacingIds:Re(o)}}isTombstoned(e){return B(this.schema.nodes.get(e))}replacedByOf(e){return Pe(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get($(e))===e}noteWrite(){this.unobservedWrites+=1;}hasUnobservedWrites(){return this.unobservedWrites>0}listingParents(e){return [...this.listings.get(e)??[]]}allLogicalIds(){return [...this.schema.nodes.keys()].filter(e=>!m(e))}nodeCount(){return this.nodeCountCache<0&&(this.nodeCountCache=this.schema.nodes.size),this.nodeCountCache+this.pendingNodeAdds}nodeShape(e){return m(e)?null:At(this.schema.nodes,e)}kindOf(e){return m(e)?null:Ot(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let n=j(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,pt({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:n,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)Oe(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)Ne(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,n){let r=this.require(e),o=j(this.schema.namespaces,n.namespaceUri,this.limits.maxStringLength);r.set(z,Ce(n.kind,o,n.localName,n.prefix??""));}putText(e,n){this.noteNodeWrite(e),this.schema.nodes.set(e,ht(n));}spliceText(e,n,r,o){let i=this.textOf(e);r>0&&i.delete(n,r),o.length>0&&i.insert(n,o);}setAttribute(e,n,r){if(r===null){Rt(this.schema,e,n.namespaceUri,n.localName);return}Oe(this.schema,this.limits.maxStringLength,e,n,r);}setNamespaceBinding(e,n,r){if(r===null){Ct(this.schema,e,n);return}Ne(this.schema,this.limits.maxStringLength,e,n,r);}spliceChildren(e,n,r,o){let i=this.childArray(e);r>0&&i.delete(n,r),o.length>0&&i.insert(n,[...o]);}moveNode(e,n,r){this.unlinkFromAllParents(e);let o=this.childArray(n);o.insert(Math.max(0,Math.min(r,o.length)),[e]);}tombstone(e,n){this.unlinkFromAllParents(e);let r=this.require(e);r.set(D,true),n&&r.set(W,n);}unlistChildren(e,n){if(n.length===0)return;let r=this.schema.nodes.get(e),o=r?k(r):null;if(!o)return;let i=new Map;for(let a of n)i.set(a,(i.get(a)??0)+1);for(let a=o.length-1;a>=0;a-=1){let s=o.get(a),l=i.get(s)??0;l!==0&&(i.set(s,l-1),o.delete(a,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,mt(e.id,e.rootLogicalId,e.contentType));}deleteXmlPart(e){this.partCountCache=-1,this.schema.parts.delete(e);}putRelationship(e){if(m(e.ownerPart)||m(e.id))return;this.relationshipCountCache=-1;let n=new R.Map;n.set(e.id,gt(e)),this.schema.relationships.set(Ae(e.ownerPart,e.id),n);}deleteRelationship(e,n){this.relationshipCountCache=-1,this.schema.relationships.delete(Ae(e,n)),this.schema.relationships.get(e)?.delete(n);}putContentTypeOverride(e,n){this.schema.overrides.set(partNameKey(e),n);}deleteContentTypeOverride(e){this.schema.overrides.delete(partNameKey(e));}putContentTypeDefault(e,n){this.schema.defaults.set(e,n);}putBinary(e){this.schema.binaries.set(e.storageKey,ft(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return It(this.schema.relationships)}contentTypeOverrides(){return Tt(this.schema.overrides)}contentTypeDefaults(){return Dt(this.schema.defaults)}binaries(){return Bt(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){let n=i=>{let a=new Set,s=false;for(let l of i){let d=l.path;if(d.length===0){for(let u of l.changes.keys.keys())a.add(String(u));s=true;continue}a.add(String(d[0])),l.target instanceof R.Array&&(s=true),l.target instanceof R.Map&&(l.changes.keys.has(D)||l.changes.keys.has(W))&&(s=true);}(a.size>0||s)&&e({logicalIds:a,membershipChanged:s,packageChanged:false});},r=i=>{let a=new Set;for(let s of i.changes.keys.keys()){let l=se(String(s))??le(String(s));!l||m(l.logicalId)||a.add(l.logicalId);}a.size>0&&e({logicalIds:a,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return this.schema.nodes.observeDeep(n),this.schema.attributes.observe(r),this.schema.bindings.observe(r),this.schema.parts.observeDeep(o),this.schema.relationships.observeDeep(o),this.schema.overrides.observe(o),this.schema.defaults.observe(o),this.schema.binaries.observeDeep(o),()=>{this.schema.nodes.unobserveDeep(n),this.schema.attributes.unobserve(r),this.schema.bindings.unobserve(r),this.schema.parts.unobserveDeep(o),this.schema.relationships.unobserveDeep(o),this.schema.overrides.unobserve(o),this.schema.defaults.unobserve(o),this.schema.binaries.unobserveDeep(o);}}rebuildDerivedIndexes(){this.unobservedWrites=0,this.nodeCountCache=-1,this.pendingNodeAdds=0,this.relationshipCountCache=-1,this.partCountCache=-1,this.parentIndex=new Map,this.listings=new Map,this.childrenSnapshot=new Map,this.adoptees=new Map,this.tombstoneSources=new Map,this.tombstoneSurvivor=new Map,this.attributesByNode=new Map,this.bindingsByNode=new Map,this.schema.nodes.forEach((e,n)=>{if(m(n))return;let r=k(e);if(!r)return;let o=r.toArray();this.childrenSnapshot.set(n,o);for(let i of o)this.addListing(i,n);}),this.schema.nodes.forEach((e,n)=>{B(e)&&this.syncAdoptee(n);}),this.schema.attributes.forEach((e,n)=>{if(typeof e!="string"||m(n))return;let r=se(n);!r||m(r.logicalId)||m(r.localName)||Me(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,n)=>{if(typeof e!="string"||m(n))return;let r=le(n);!r||m(r.logicalId)||m(r.prefix)||Te(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(b(e)&&(e.has("parent")||e.has("parentId")))throw new Error("registry record must not replicate a parent field")});}applyChildArrayEvents(e){this.unobservedWrites=0,this.pendingNodeAdds=0;let n=new Set;for(let r of e){if(r.path.length===0&&r.target instanceof R.Map){for(let[o,i]of r.changes.keys)if(this.nodeCountCache>=0&&i.action!=="update"&&(this.nodeCountCache+=i.action==="add"?1:-1),!(i.action==="delete"||m(String(o))))for(let a of this.syncChildListings(String(o)))n.add(a);continue}if(r.target instanceof R.Array&&r.path.length>0){let o=String(r.path[0]);for(let i of this.syncChildListings(o))n.add(i);this.isTombstoned(o)&&this.syncAdoptee(o);continue}r.target instanceof R.Map&&r.path.length===1&&(r.changes.keys.has(D)||r.changes.keys.has(W))&&this.syncAdoptee(String(r.path[0]));}n.size>0&&this.resolveParents(n);}applyAttributeMapEvent(e){this.unobservedWrites=0;for(let[n,r]of e.changes.keys){let o=se(String(n));if(!o||m(o.logicalId)||m(o.localName))continue;if(r.action==="delete"){Lt(this.attributesByNode,o.logicalId,o.namespaceId,o.localName);continue}let i=this.schema.attributes.get(String(n));typeof i=="string"&&Me(this.schema,this.attributesByNode,o.logicalId,o.namespaceId,o.localName,i);}}applyBindingMapEvent(e){this.unobservedWrites=0;for(let[n,r]of e.changes.keys){let o=le(String(n));if(!o||m(o.logicalId)||m(o.prefix))continue;if(r.action==="delete"){kt(this.bindingsByNode,o.logicalId,o.prefix);continue}let i=this.schema.bindings.get(String(n));typeof i=="string"&&Te(this.schema,this.bindingsByNode,o.logicalId,o.prefix,i);}}syncChildListings(e){let n=this.schema.nodes.get(e),r=n?k(n)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(Nt(o,r))return [];let i=new Set(r),a=new Set(o),s=[];for(let l of o)i.has(l)||(this.removeListing(l,e),s.push(l));for(let l of r)a.has(l)||(this.addListing(l,e),s.push(l));return this.childrenSnapshot.set(e,r),s}addListing(e,n){let r=this.listings.get(e)??new Set;r.add(n),this.listings.set(e,r);}removeListing(e,n){let r=this.listings.get(e);r&&(r.delete(n),r.size===0&&this.listings.delete(e));}resolveParents(e){let n=[];for(let o of e){let i=this.listings.get(o);if(!i||i.size===0){this.parentIndex.delete(o);continue}if(i.size===1){this.parentIndex.set(o,[...i][0]);continue}n.push(o);}if(n.length===0)return;St({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(o=>o.rootLogicalId)},n)||this.assignFirstReachable(new Set(n));}assignFirstReachable(e){Et({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(n=>n.rootLogicalId)},e);}syncAdoptee(e){let n=this.tombstoneSurvivor.get(e);if(n!==void 0){this.tombstoneSurvivor.delete(e);let i=this.tombstoneSources.get(n);i&&(i.delete(e),i.size===0&&this.tombstoneSources.delete(n));}let r=this.schema.nodes.get(e),o=Pe(r);if(o!==null){if(B(r)){let i=this.tombstoneSources.get(o)??new Set;i.add(e),this.tombstoneSources.set(o,i),this.tombstoneSurvivor.set(e,o);}this.recomputeAdoptees(o);}}isContentWitness(e){let n=this.kindOf(e);return n!==null&&!n.endsWith("Properties")}recomputeAdoptees(e){let n=[];for(let r of this.tombstoneSources.get(e)??[]){let o=this.schema.nodes.get(r);if(o)for(let i of k(o)?.toArray()??[])this.isTombstoned(i)||!this.schema.nodes.has(i)||this.isContentWitness(i)&&n.push(i);}n.length>0?this.adoptees.set(e,n):this.adoptees.delete(e);}unlinkFromAllParents(e){let n=[...this.listings.get(e)??[]];if(n.length===0){this.schema.nodes.forEach(r=>{let o=k(r);o&&this.removeFromArray(o,e);});return}for(let r of n){let o=this.schema.nodes.get(r),i=o?k(o):null;i&&this.removeFromArray(i,e);}}removeFromArray(e,n){for(let r=e.length-1;r>=0;r-=1)e.get(r)===n&&e.delete(r,1);}elementRecord(e,n){let r=ae(zt(n.get(z))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:X(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:k(n)?.toArray()??[]}}textOf(e){let n=this.require(e).get(T);if(!(n instanceof R.Text))throw new Error(`no text at ${e}`);return n}childArray(e){let n=this.require(e).get(oe);if(!(n instanceof R.Array))throw new Error(`no children at ${e}`);return n}require(e){let n=this.schema.nodes.get(e);if(!n)throw new Error(`registry node ${e} missing`);return n}};var ce=class{blobs=new Map;get(e){let n=this.blobs.get(e);return n?n.slice():null}put(e,n){this.blobs.set(e,n.slice());}};async function jt(t){let e=await globalThis.crypto.subtle.digest("SHA-256",t.slice().buffer);return `sha256:${[...new Uint8Array(e)].map(n=>n.toString(16).padStart(2,"0")).join("")}`}function Kt(t){let e=t.binaryPart;return typeof e=="function"?e:null}function Ft(t,e){let n=[];for(let o of t)o.kind==="putBinary"&&n.push(o.descriptor);if(n.length===0)return null;if(!e)return {ok:false,failure:{code:"blob-read",detail:"binary-part-reader"}};let r=[];for(let o of n){let i=e(o.storageKey);if(!i)return {ok:false,failure:{code:"missing-local-blob",detail:o.storageKey}};r.push({digest:o.digest,bytes:i});}return {ok:true,payloads:r}}function Vt(t,e){for(let n of e)t.put(n.digest,n.bytes);}function cr(t){return t.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function ur(t){return t.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function Wt(t,e,n,r,o){if(r>t.limits.maxTreeDepth)return "tree-too-deep";if(m(e.id))return "prototype-key";if(o.nodes+=1,o.nodes>t.limits.maxNodes)return "too-many-nodes";if(e.kind==="textValue"){if(e.value.length>t.limits.maxTextLength)return "text-too-long";t.putText(e.id,e.value);}else {if(e.attributes.length>t.limits.maxAttributes)return "too-many-attributes";if(e.children.length>t.limits.maxChildren)return "too-many-children";if(C(e.namespaceUri,t.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(m(i.localName))return "prototype-key";if(C(i.namespaceUri,t.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(m(i.prefix))return "prototype-key";if(C(i.namespaceUri,t.limits.maxStringLength))return "invalid-string"}t.putElement({logicalId:e.id,kind:e.kind,namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,attributes:cr(e),bindings:ur(e)});for(let i of e.children){let a=Wt(t,i,e.id,r+1,o);if(a)return a}}return n&&t.childArray(n).push([e.id]),null}async function pr(t){let e=[],n=[];for(let[r,o]of t.partBytes){if(t.parts.has(r))continue;let a=t.contentTypes.overrides.get(r)??"application/octet-stream",s=w(r);if(s)return {ok:false,code:s};if(o.byteLength>A.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await jt(o);n.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:a,storageKey:r});}return {ok:true,descriptors:e,payloads:n}}async function H(t,e,n=new ce){if(e.parts.size>t.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await pr(e);if(!r.ok)return r;let o=null;t.beginBulkLoad();try{t.doc.transact(()=>{for(let s of r.payloads)n.put(s.digest,s.bytes);let i={nodes:0};for(let[s,l]of e.parts){let d=w(s);if(d){o=d;return}if(C(l.contentType,t.limits.maxMediaTypeLength)){o="invalid-string";return}let u=Wt(t,l.root,null,0,i);if(u){o=u;return}t.putXmlPart({name:s,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let a=0;for(let s of e.relationships.values())for(let l of s){if(a+=1,a>t.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=w(l.ownerPart);if(d){o=d;return}}if(m(l.id)){o="prototype-key";return}t.putRelationship({ownerPart:l.ownerPart,id:l.id,type:l.type,rawTarget:l.rawTarget,targetMode:l.targetMode,order:l.order});}for(let[s,l]of e.contentTypes.defaults){if(m(s)){o="prototype-key";return}t.putContentTypeDefault(s,l);}for(let[s,l]of e.contentTypes.overrides){let d=w(s);if(d){o=d;return}t.putContentTypeOverride(s,l);}for(let s of r.descriptors)t.putBinary(s);yt(t.schema.meta),t.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},it);}finally{t.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var ue=class{constructor(e){this.registry=e;}registry;touched=new Map;created=new Set;has(e){return this.created.has(e)||this.touched.has(e)||this.registry.hasNode(e)}node(e){let n=this.touched.get(e);if(n)return n;let r=this.registry.nodeShape(e);return r?(this.touched.set(e,r),r):null}putNode(e){this.node(e.logicalId)||(this.created.add(e.logicalId),this.touched.set(e.logicalId,{isText:e.kind==="textValue",textLength:0,children:[]}));}spliceText(e,n,r){let o=this.node(e);o&&(o.textLength=Math.max(0,o.textLength-n)+r);}spliceChildren(e,n,r,o){let i=this.node(e);i&&i.children.splice(n,r,...o);}moveNode(e,n,r){let o=this.parentOf(e);if(o!==null){let s=this.node(o),l=s?.children.indexOf(e)??-1;s&&l>=0&&s.children.splice(l,1);}let i=this.node(n);if(!i)return;let a=Math.min(r,i.children.length);i.children.splice(a,0,e);}parentOf(e){for(let[n,r]of this.touched)if(r.children.includes(e))return n;return this.registry.parentOf(e)}};function $t(t,e){switch(e.kind){case "putNode":t.putNode(e.descriptor);return;case "spliceText":t.spliceText(e.logicalId,e.deleteCount,e.insert.length);return;case "spliceChildren":t.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":t.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;default:return}}function O(t,e){return m(e)||e.length===0?{ok:false,code:"prototype-key",detail:e}:t.has(e)?null:{ok:false,code:"unknown-logical-id",detail:e}}function hr(t,e,n){if(m(e.logicalId)||e.logicalId.length===0)return {ok:false,code:"invalid-logical-id",detail:e.logicalId};let r=n.node(e.logicalId);return r&&r.isText!==(e.kind==="textValue")?{ok:false,code:"invalid-bound",detail:`node class ${e.logicalId}`}:e.kind==="textValue"?null:m(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:C(e.qname.namespaceUri,t.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function mr(t,e,n){switch(e.kind){case "putNode":return hr(t,e.descriptor,n);case "spliceText":{let r=O(n,e.logicalId);if(r)return r;if(!Number.isSafeInteger(e.utf16Start)||!Number.isSafeInteger(e.deleteCount)||e.utf16Start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.insert.length>t.limits.maxTextLength)return {ok:false,code:"text-too-long"};let o=n.node(e.logicalId);if(o&&o.isText){if(e.utf16Start+e.deleteCount>o.textLength)return {ok:false,code:"invalid-bound",detail:e.logicalId};if(o.textLength-e.deleteCount+e.insert.length>t.limits.maxTextLength)return {ok:false,code:"text-too-long"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.logicalId};return null}case "setAttribute":{let r=O(n,e.logicalId);return r||(m(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:C(e.qname.namespaceUri,t.limits.maxStringLength)?{ok:false,code:"invalid-string"}:e.value!==null&&e.value.length>t.limits.maxStringLength?{ok:false,code:"invalid-string"}:null)}case "setNamespaceBinding":{let r=O(n,e.logicalId);return r||(m(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&C(e.uri,t.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=O(n,e.parentLogicalId);if(r)return r;if(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.deleteCount)||e.start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.childLogicalIds.length>t.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let i of e.childLogicalIds){let a=O(n,i);if(a)return a}let o=n.node(e.parentLogicalId);if(o&&!o.isText){if(e.start+e.deleteCount>o.children.length)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};if(o.children.length-e.deleteCount+e.childLogicalIds.length>t.limits.maxChildren)return {ok:false,code:"too-many-children"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};return null}case "moveNode":{let r=O(n,e.logicalId);if(r)return r;let o=O(n,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=w(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=O(n,e.rootLogicalId);return o||(t.partCount()>=t.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=w(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=w(e.owner);if(r)return {ok:false,code:r}}return m(e.record.id)?{ok:false,code:"prototype-key"}:t.relationshipCount()>=t.limits.maxRelationships?{ok:false,code:"too-many-relationships"}:null}case "deleteRelationship":return m(e.relationshipId)?{ok:false,code:"prototype-key"}:null;case "putContentTypeOverride":{let r=w(e.partName);return r?{ok:false,code:r}:C(e.mediaType,t.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=w(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=Qe(e.descriptor);return r?{ok:false,code:r}:null}case "deleteBinary":return m(e.storageKey)?{ok:false,code:"prototype-key"}:null;default:return {ok:false,code:"invalid-bound"}}}function gr(t,e,n){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?t.hasNode(e.descriptor.logicalId)||t.putText(e.descriptor.logicalId,""):t.hasNode(e.descriptor.logicalId)?t.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):t.putElement({logicalId:e.descriptor.logicalId,kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix,attributes:[],bindings:[]});return;case "spliceText":if(n.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&t.textOf(e.logicalId).toString()===e.insert)return;t.spliceText(e.logicalId,e.utf16Start,e.deleteCount,e.insert);return;case "setAttribute":t.setAttribute(e.logicalId,e.qname,e.value);return;case "setNamespaceBinding":t.setNamespaceBinding(e.logicalId,e.prefix,e.uri);return;case "spliceChildren":t.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":t.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;case "putXmlPart":t.putXmlPart({name:e.name,id:e.name,rootLogicalId:e.rootLogicalId,contentType:"application/xml"});return;case "deleteXmlPart":t.deleteXmlPart(e.name);return;case "putRelationship":t.putRelationship({...e.record,ownerPart:e.owner});return;case "deleteRelationship":t.deleteRelationship(e.owner,e.relationshipId);return;case "putContentTypeOverride":t.putContentTypeOverride(e.partName,e.mediaType);return;case "deleteContentTypeOverride":t.deleteContentTypeOverride(e.partName);return;case "putBinary":t.putBinary(e.descriptor);return;case "deleteBinary":t.deleteBinary(e.storageKey);return}}function fr(t,e){let n=t.kindOf(e);return n!==null&&!n.endsWith("Properties")}function yr(t,e,n,r){let o=new Set((n.get(e)??[]).filter(i=>fr(t,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(a=>o.has(a)))return i.parentLogicalId}}function br(t,e){let n=new ue(t),r=[],o=new Set,i=new Set;for(let a of e){let s=mr(t,a,n);if(s)return s;if(a.kind==="spliceChildren"){let l=a.deleteCount>0?n.node(a.parentLogicalId):null;if(l&&!l.isText){let d=a.start+a.deleteCount;for(let u=a.start;u<d;u+=1){let p=l.children[u];p!==void 0&&r.push(p);}}for(let d of a.childLogicalIds)o.add(d);}else a.kind==="moveNode"?o.add(a.logicalId):a.kind==="putNode"&&a.descriptor.kind==="textValue"&&i.add(a.descriptor.logicalId);$t(n,a);}return {removed:r,reinserted:o,mintedText:i}}function Ir(t){let e=0;for(let n of t)n.kind==="putNode"&&(e+=1);return e}function De(t,e){if(t.nodeCount()+Ir(e.effects)>t.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let n=br(t,e.effects);return "ok"in n?n:(t.doc.transact(()=>{t.noteWrite();let r=vr(t,n.removed);for(let o of e.effects)gr(t,o,n.mintedText);xr(t,e.effects,n,r);},at),{ok:true})}function xr(t,e,n,r){if(n.removed.length===0)return;let o=new Set;for(let i of t.partEntries())o.add(i.rootLogicalId);for(let i of n.removed){if(n.reinserted.has(i)||!t.hasNode(i)||t.isTombstoned(i)||o.has(i))continue;let a=yr(t,i,r,e);a&&t.unlistChildren(i,r.get(i)??[]),t.tombstone(i,a);}}function vr(t,e){let n=new Map;for(let r of e){let o=t.nodeShape(r);o&&!o.isText&&n.set(r,o.children);}return n}var he="http://schemas.openxmlformats.org/package/2006/relationships",Sr="application/vnd.openxmlformats-package.relationships+xml",Xt=/^(.*)\/_rels\/([^/]*)\.rels$/;function Jt(t){return Xt.test(t)}function Ht(t){let e=Xt.exec(t);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function G(t,e){return t.attributes.find(n=>n.localName===e)?.value}function pe(t,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:t,value:e})}function Er(t,e){let n=[pe("Id",e.id),pe("Type",e.type),pe("Target",e.rawTarget)];return e.targetMode==="External"&&n.push(pe("TargetMode","External")),Object.freeze({id:t,kind:"generic",namespaceUri:he,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(n),children:Object.freeze([])})}function Gt(t,e){if(t.kind==="textValue"||t.namespaceUri!==he||t.localName!=="Relationship"||G(t,"Id")!==e.id||G(t,"Type")!==e.type||G(t,"Target")!==e.rawTarget)return false;let n=G(t,"TargetMode");return e.targetMode==="External"?n==="External":n===void 0}function qt(t,e){return t.children.length!==e.length?false:t.children.every((n,r)=>Gt(n,e[r]))}function Zt(t,e){if(t.id!==e.id||t.kind!==e.kind||t.namespaceUri!==e.namespaceUri||t.localName!==e.localName||t.prefix!==e.prefix||t.attributes.length!==e.attributes.length)return false;for(let n=0;n<t.attributes.length;n+=1){let r=t.attributes[n],o=e.attributes[n];if(r.namespaceUri!==o.namespaceUri||r.localName!==o.localName||r.value!==o.value||r.prefix!==o.prefix)return false}return t.namespaceBindings.length!==e.namespaceBindings.length?false:t.namespaceBindings.every((n,r)=>{let o=e.namespaceBindings[r];return n.prefix===o.prefix&&n.namespaceUri===o.namespaceUri})}function Qt(t,e,n){let r=[];for(let o of e){if(m(o.id))continue;let i=t.find(s=>s.kind!=="textValue"&&G(s,"Id")===o.id);if(i&&Gt(i,o)){r.push(i);continue}let a=i&&i.kind!=="textValue"?i.id:`${n}#rel-${o.id}`;m(a)||r.push(Er(a,o));}return r}function wr(t){return Object.freeze({id:`${t}#root`,kind:"generic",namespaceUri:he,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:he})]),attributes:Object.freeze([]),children:Object.freeze([])})}function en(t){return Object.freeze({id:t,name:t,contentType:Sr,root:wr(t)})}function tn(t){let e=new Map;for(let n of t){if(m(n.id)||n.ownerPart!=="/"&&w(n.ownerPart))continue;let r=e.get(n.ownerPart)??[];r.push(n),e.set(n.ownerPart,r);}return e}var an=/^\/customXml\/item(\d+)\.xml$/i,kr=/^\/customXml\/itemProps(\d+)\.xml$/i;function Z(t){return an.test(t)}function _e(t){return kr.test(t)}function Pr(t){let e=an.exec(t);if(!e)return null;let n=Number(e[1]);return Number.isSafeInteger(n)&&n>0?n:null}function nn(t){return {item:`/customXml/item${String(t)}.xml`,props:`/customXml/itemProps${String(t)}.xml`}}function Ar(t,e,n){let r=t.attributes.find(o=>o.localName===e&&o.namespaceUri===n);return r&&r.value.length>0?r.value:null}function rn(t,e){let n=t.record(e);return !n||!v(n)?e:n.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function Or(t,e){let n=t.record(e);if(!n||!v(n))return null;for(let r of n.childIds){let o=t.record(r);if(!(!o||!v(o)||o.localName!=="schemaRefs")&&o.namespaceUri===DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let a=t.record(i);if(!a||!v(a)||a.localName!=="schemaRef")continue;let s=Ar(a,"uri",DATASTORE_NAMESPACE_URI);if(s)return s}}return null}function Nr(t,e){return e.childIds.some(n=>{let r=t.record(n);return !!r&&v(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Mr(t,e){return e.localName==="node"||e.namespaceUri===WML_NAMESPACE_URI||e.namespaceUri===DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||t.parentOf(e.logicalId)!==null?false:Nr(t,e)}function Tr(t,e){return e.localName!=="datastoreItem"||e.namespaceUri!==DATASTORE_NAMESPACE_URI?false:t.parentOf(e.logicalId)===null}function sn(t,e){if(!t.hasNamespace(DATASTORE_NAMESPACE_URI))return [];let n=new Map,r=new Map;for(let[c,h]of e){let g=t.record(h.root.id);!g||!v(g)||(Z(c)&&n.set(g.logicalId,g),_e(c)&&r.set(g.logicalId,g));}for(let c of t.allLogicalIds()){if(t.isTombstoned(c)||n.has(c)||r.has(c))continue;let h=t.record(c);!h||!v(h)||(Mr(t,h)?n.set(c,h):Tr(t,h)&&r.set(c,h));}if(n.size===0)return [];let o=new Map;for(let c of n.values()){let h=o.get(c.namespaceUri)??[];h.push(c),o.set(c.namespaceUri,h);}let i=new Map;for(let c of r.values()){let h=Or(t,c.logicalId);if(!h)continue;let g=i.get(h)??[];g.push(c),i.set(h,g);}let a=[];for(let[c,h]of o){let g=i.get(c);if(!g||g.length===0)continue;h.sort((x,E)=>x.logicalId.localeCompare(E.logicalId)),g.sort((x,E)=>x.logicalId.localeCompare(E.logicalId));let y=h[0],M=g[0],P=[],I=new Set;for(let x of h)for(let E of x.childIds){if(I.has(E))continue;let re=t.record(E);!re||!v(re)||re.localName!=="node"||re.namespaceUri!==c||(I.add(E),P.push(E));}for(let x of t.allLogicalIds()){if(I.has(x)||t.isTombstoned(x))continue;let E=t.record(x);!E||!v(E)||E.localName!=="node"||E.namespaceUri!==c||(I.add(x),P.push(x));}P.sort((x,E)=>rn(t,x).localeCompare(rn(t,E))),a.push({data:y,props:M,nodeIds:P});}a.sort((c,h)=>c.data.logicalId.localeCompare(h.data.logicalId));let s=new Set,l=[],d=new Set,u=new Set;for(let[c,h]of e){let g=Pr(c);if(g===null)continue;let y=a.find(I=>I.data.logicalId===h.root.id&&!d.has(I.data.logicalId));if(!y)continue;let M=nn(g).props,P=e.get(M);P&&P.root.id!==y.props.logicalId||(s.add(g),d.add(y.data.logicalId),u.add(y.props.logicalId),l.push({dataRootId:y.data.logicalId,propsRootId:y.props.logicalId,namespaceUri:y.data.namespaceUri,itemName:c,propsName:M,nodeIds:y.nodeIds}));}let p=1;for(let c of a){if(d.has(c.data.logicalId))continue;for(;s.has(p);)p+=1;s.add(p);let h=nn(p);l.push({dataRootId:c.data.logicalId,propsRootId:c.props.logicalId,namespaceUri:c.data.namespaceUri,itemName:h.item,propsName:h.props,nodeIds:c.nodeIds}),p+=1;}return l.sort((c,h)=>c.itemName.localeCompare(h.itemName)),l}function Dr(t){return t.type===CUSTOM_XML_REL||t.type===CUSTOM_XML_PROPS_REL?true:Z(t.ownerPart)}function Br(t){let e=/^rId(\d+)$/.exec(t);if(!e)return 0;let n=Number(e[1]);return Number.isSafeInteger(n)?n:0}function _r(t,e){let n=t.split("/").slice(1,-1),r=e.split("/").slice(1),o=0;for(;o<n.length&&o<r.length-1&&n[o]===r[o];)o+=1;return `${"../".repeat(n.length-o)}${r.slice(o).join("/")}`}function ln(t,e){if(e.length===0)return [];let n=t.mainDocumentPart();if(!n)return [];let r=t.relationships(),o=r.filter(s=>s.ownerPart===n&&s.type===CUSTOM_XML_REL).sort((s,l)=>s.id.localeCompare(l.id)),i=0;for(let s of r)i=Math.max(i,Br(s.id));let a=[];for(let s=0;s<e.length;s+=1){let l=e[s],d=o[s],u=d?.id??`rId${String(i+=1)}`;a.push({ownerPart:n,id:u,type:CUSTOM_XML_REL,rawTarget:_r(n,l.itemName),targetMode:"Internal",order:d?.order??s}),a.push({ownerPart:l.itemName,id:"rId1",type:CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return a}function dn(t,e){return e.length===0?[...t]:[...t.filter(n=>!Dr(n)),...e]}function cn(t){let e=new Map;for(let n of t)e.set(partNameKey(n.propsName),CUSTOM_XML_PROPS_TYPE);return e}function Ue(t,e){if(e.length===0)return false;let n=[...t.keys()].filter(Z).sort(),r=e.map(o=>o.itemName).sort();if(n.length!==r.length||n.some((o,i)=>o!==r[i]))return true;for(let o of e){let i=t.get(o.itemName),a=t.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!a||a.root.id!==o.propsRootId)return true}return false}function un(t,e){if(Ue(t,e))return true;for(let n of e){let r=t.get(n.itemName);if(!r)return true;let o=new Set(r.root.children.map(s=>s.id));if(n.nodeIds.some(s=>!o.has(s)))return true;let i=[];for(let s of r.root.children)s.kind!=="textValue"&&i.push(s.attributes.find(l=>l.localName==="id")?.value??s.id);let a=[...i].sort((s,l)=>s.localeCompare(l));if(i.some((s,l)=>s!==a[l]))return true}return false}var Ur="http://schemas.microsoft.com/office/word/2012/wordml";function me(t,e){return t.attributes.find(n=>n.localName===e)?.value}function ge(t){let e=Number(t);return t===void 0||t.length===0||!Number.isSafeInteger(e)?`2${t??""}`:`${e<0?"0":"1"}${String(Math.abs(e)).padStart(12,"0")}`}function pn(t){return e=>e.localName===t&&e.namespaceUri===WML_NAMESPACE_URI}function Yr(t){return t.localName==="abstractNum"?`0${ge(me(t,"abstractNumId"))}`:`1${ge(me(t,"numId"))}`}function zr(t){return t.namespaceUri!==WML_NAMESPACE_URI?false:t.localName==="abstractNum"||t.localName==="num"}function hn(t){return t.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:t.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===Ur,sortKey:e=>e.id}:t.localName==="footnotes"&&t.namespaceUri===WML_NAMESPACE_URI?{isMember:pn("footnote"),sortKey:e=>ge(me(e,"id"))}:t.localName==="endnotes"&&t.namespaceUri===WML_NAMESPACE_URI?{isMember:pn("endnote"),sortKey:e=>ge(me(e,"id"))}:t.localName==="numbering"&&t.namespaceUri===WML_NAMESPACE_URI?{isMember:zr,sortKey:Yr}:null}function jr(t,e){return t.attributes.find(n=>n.localName===e)?.value}function Ye(t){return t.kind==="textValue"?t.id:jr(t,"id")??t.id}function F(t,e){if(t.length===e.length&&t.every((a,s)=>a===e[s]))return t;let n=0,r=Math.min(t.length,e.length);for(;n<r&&t[n]===e[n];)n+=1;let o=t.length,i=e.length;for(;o>n&&i>n&&t[o-1]===e[i-1];)o-=1,i-=1;return Object.freeze([...t.slice(0,n),...e.slice(n,i),...t.slice(o)])}function fn(t,e){let n=t.root;if(n.children.length===e.length&&n.children.every((o,i)=>o===e[i]))return t;let r=Object.freeze({...n,children:F(n.children,e)});return Object.freeze({...t,root:r})}function Kr(t){if(t.namespaceUri===XML_NAMESPACE_URI&&t.localName==="space"){let e=t.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return t.namespaceUri===WML_NAMESPACE_URI&&t.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:WML_NAMESPACE_URI,localName:"val",prefix:t.prefix,value:t.value}):Object.freeze({kind:"genericExtension",namespaceUri:t.namespaceUri,localName:t.localName,prefix:t.prefix,value:t.value})}function In(t){}function vn(t,e){return Object.freeze({id:t,kind:"textValue",value:e})}function Jr(t,e){return t.namespaceBindings.length!==e.bindings.length?false:t.namespaceBindings.every((n,r)=>{let o=e.bindings[r];return n.prefix===o.prefix&&n.namespaceUri===o.namespaceUri})}function Hr(t,e){return t.attributes.length!==e.attributes.length?false:t.attributes.every((n,r)=>{let o=e.attributes[r];return n.namespaceUri===o.namespaceUri&&n.localName===o.localName&&n.value===o.value&&n.prefix===(o.prefix?.length?o.prefix:void 0)})}function fe(t,e,n){let r=n&&n.kind!=="textValue"?n:void 0;return Object.freeze({id:t.logicalId,kind:t.kind,namespaceUri:t.namespaceUri,localName:t.localName,prefix:t.prefix,namespaceBindings:r&&Jr(r,t)?r.namespaceBindings:Object.freeze(t.bindings.map(o=>Object.freeze({...o}))),attributes:r&&Hr(r,t)?r.attributes:Object.freeze(t.attributes.map(Kr)),children:e})}function Sn(t,e){if(t.attributes.length!==e.attributes.length)return false;let n=new Map(e.attributes.map(r=>[`${r.namespaceUri}
2
- ${r.localName}`,r.value]));for(let r of t.attributes)if(n.get(`${r.namespaceUri}
3
- ${r.localName}`)!==r.value)return false;return t.localName===e.localName&&t.kind===e.kind}function ze(t,e){let n=e.size;e.add(t.id);let r=e.size!==n;if(t.kind==="textValue")return r;for(let o of t.children)ze(o,e)||(r=false);return r}function En(t,e){let n=new Set(e);for(let r of e){let o=t.parentOf(r);for(;o&&!n.has(o);)n.add(o),o=t.parentOf(o);}return n}var ye=class{constructor(e){this.registry=e;}registry;decoded=null;merged=null;grouped=null;assembly=null;defaults=null;overrides=null;partBytes=null;blobBytes=new Map;invalidate(){this.decoded=null,this.merged=null,this.grouped=null,this.assembly=null,this.defaults=null,this.overrides=null,this.partBytes=null;}projected(e){return this.decoded||(this.decoded=this.registry.relationships(),this.merged=null),(!this.merged||this.merged.custom!==e)&&(this.merged={custom:e,records:e.length===0?this.decoded:dn(this.decoded,e)}),this.merged.records}groupedByOwner(e){let n=this.projected(e);return (!this.grouped||this.grouped.records!==n)&&(this.grouped={records:n,map:tn(n)}),this.grouped.map}relationshipAssembly(e){let n=this.projected(e);return (!this.assembly||this.assembly.records!==n)&&(this.assembly={records:n,value:Zr(n)}),this.assembly.value}contentTypeDefaults(){return this.defaults??=this.registry.contentTypeDefaults()}contentTypeOverrides(){return this.overrides??=this.registry.contentTypeOverrides()}resolvePartBytes(e){if(this.partBytes)return this.partBytes;let n=new Map,r=new Set;for(let o of this.registry.binaries()){r.add(o.storageKey);let i=this.blobBytes.get(o.storageKey);if(i&&i.digest===o.digest){n.set(o.storageKey,i.bytes);continue}let a=e.get(o.digest);if(!a)return null;In(a.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:a}),n.set(o.storageKey,a);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=n,n}};function Zr(t){let e=buildRelationshipSet(t);if(!e.ok)return null;let n=[];for(let r of t){let o=resolveRelationship(r);o.mode==="External"&&n.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(n)}}function to(t){let e=new Set,n=[];for(let r of t){let o=`${r.code}${r.logicalId??""}`;e.has(o)||(e.add(o),n.push(r));}return n}var U=class{constructor(e,n){this.registry=e;this.blobs=n;this.packageCache=new ye(e),this.stop=e.observeDirty(r=>{for(let o of r.logicalIds)this.pendingDirty.add(o);r.membershipChanged&&(this.pendingMembership=true),r.packageChanged&&(this.pendingPackage=true);});}registry;blobs;cache=new Map;heights=new Map;partCache=new Map;packageCache;relsProjection=new Map;pendingDirty=new Set;pendingMembership=false;pendingPackage=false;lastDirty=new Set;lastAdoption=new Map;placementContested=false;lastContestResolution=new Map;contestEncountered=new Set;contestMatchesResolution=true;claimsWholeSubtrees=true;lastDuplicateParents=[];droppedChildren=new Set;looseCandidates=new Set;pkg=null;customXmlRels=[];customXmlOverrides=new Map;stop;issues=[];destroy(){this.stop();}dirtyLogicalIds(){return this.lastDirty}current(){return this.pkg&&this.pendingDirty.size===0&&!this.pendingPackage&&!this.pendingMembership?{ok:true,package:this.pkg,issues:[...this.issues]}:this.rebuild()}adoptionChanges(){let e=[],n=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");n.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())n.has(r)||e.push(r);return this.lastAdoption=n,e}rebuild(){let e=new Set(this.pendingDirty),n=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(n||r)&&this.packageCache.invalidate();for(let u of this.adoptionChanges())e.add(u);let o=En(this.registry,e),i=new Set(this.registry.partEntries().map(u=>u.rootLogicalId)),a=[...e].some(u=>i.has(u)||this.registry.parentOf(u)===null&&!this.registry.isTombstoned(u)),s=this.pkg!==null&&!r&&!a&&(o.size>0||n),l=this.materializePass(o,n,s);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:to(l.issues)};let d=this.materializePass(o,n,false);return this.recordContestResolution(),d}contestUnchanged(){for(let e of this.contestEncountered){let n=this.lastContestResolution.get(e);if(n===void 0||n!==this.registry.parentOf(e))return false}return true}recordContestResolution(){let e=new Map;for(let n of this.contestEncountered)e.set(n,this.registry.parentOf(n));for(let n of this.lastDuplicateParents)e.set(n,this.registry.parentOf(n));this.lastContestResolution=e;}materializePass(e,n,r){if(this.issues.length=0,this.lastDirty=e,this.placementContested=false,this.contestEncountered.clear(),this.contestMatchesResolution=true,this.claimsWholeSubtrees=!r,this.droppedChildren.clear(),r)for(let d of this.lastDuplicateParents)this.push("duplicate-parent",d);this.customXmlRels=[],this.customXmlOverrides.clear();let o=new Set,i=new Map;for(let d of this.registry.partEntries()){let u=new Set,p=this.materialize(d.rootLogicalId,o,u,r);if(!p||p.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let c=this.partCache.get(d.name);if(c&&c.root===p&&c.contentType===d.contentType){i.set(d.name,c);continue}let h=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:p});i.set(d.name,h),this.partCache.set(d.name,h);}let a=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),s=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,a,s),this.applyCustomXmlStores(i,o,r);for(let d of [...this.partCache.keys()])i.has(d)||this.partCache.delete(d);for(let d of [...this.relsProjection.keys()])i.has(d)||this.relsProjection.delete(d);this.evictDeadSubtrees(o),this.reportOrphans(a,o,r,s),this.looseCandidates=s,r||(this.lastDuplicateParents=this.issues.filter(d=>d.code==="duplicate-parent"&&d.logicalId!==void 0).map(d=>d.logicalId));let l=this.assemblePackage(i);return l.ok?this.pkg&&!n&&this.pkg.parts.size===i.size&&[...i].every(([d,u])=>this.pkg?.parts.get(d)===u)?{ok:true,package:this.pkg,issues:[...this.issues]}:(this.pkg=l.package,{ok:true,package:this.pkg,issues:[...this.issues]}):l}push(e,n){this.issues.push(n?{code:e,logicalId:n}:{code:e});}stillListed(e){for(let n of this.registry.listingParents(e)){let r=this.registry.record(n);if(r&&v(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,n,r,o){if(!r){for(let s of e)this.registry.isTombstoned(s)||n.has(s)||(this.pushOrphan(s),o.add(s));return}let i=new Set(this.registry.partEntries().map(s=>s.rootLogicalId)),a=new Set;for(let s of e)a.has(s)||(a.add(s),this.reportOrphansUnder(s,n,i)&&o.add(s));}reportOrphansUnder(e,n,r){let o=false,i=new Set,a=[{id:e,underTombstone:false}];for(;a.length>0;){let{id:s,underTombstone:l}=a.pop();if(!(i.has(s)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(s),this.registry.isTombstoned(s)){let d=this.registry.record(s);if(d&&v(d))for(let u of d.childIds)a.push({id:u,underTombstone:true});continue}r.has(s)||(l?n.has(s):this.stillListed(s))||(this.pushOrphan(s),o=true);}}return o}pushOrphan(e){let n=this.registry.record(e),r=!!n&&(ie(n)?n.value.length>0:n.childIds.length>0||n.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,n,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(n.has(e))return this.push("duplicate-parent",e),null;if(o&&!this.lastDirty.has(e)){let c=this.cache.get(e);if(c&&r.size+this.heightOf(c)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?ze(c,n)||(this.placementContested=true):n.add(c.id),c}if(this.registry.isTombstoned(e))return null;n.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(ie(i)){let c=this.cache.get(e);if(c?.kind==="textValue"&&c.value===i.value)return c;let h=vn(e,i.value);return this.remember(e,h),h}r.add(e);let a=new Set,s=[...i.childIds];for(let c of this.registry.adoptedChildren(e))s.includes(c)||s.push(c);let l=[];for(let c of s){if(c===e){this.push("self-child",c);continue}if(a.has(c)){this.push("duplicate-child",c);continue}if(a.add(c),this.registry.isTombstoned(c)){this.push("deleted-referenced",c);continue}if(m(c)||!this.registry.hasNode(c)){this.push("child-id-not-in-registry",c);continue}if(!this.claimsWholeSubtrees){let g=this.registry.listingParents(c);g.length>1&&(this.placementContested=true,this.contestEncountered.add(c),g.some(y=>this.registry.isTombstoned(y)&&this.registry.replacedByOf(y)!==null)?this.contestMatchesResolution=false:!n.has(c)&&this.registry.parentOf(c)!==e&&(this.contestMatchesResolution=false));}let h=this.materialize(c,n,r,o);h&&l.push(h);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((c,h)=>c===l[h])&&Sn(d,i))return d;let u=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(u,l);let p=fe(i,F(u,l),d);return this.remember(e,p),p}recordDroppedChildren(e,n){if(e.length===0)return;let r=new Set(n.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,n){this.cache.set(e,n),this.heights.delete(e);}evictDeadSubtrees(e){for(let n of this.droppedChildren)e.has(n)||(this.registry.isTombstoned(n)||!this.registry.hasNode(n))&&this.evictSubtree(n,e);}evictSubtree(e,n){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)n.has(o.id)||this.evictSubtree(o.id,n);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let n=this.heights.get(e.id);if(n!==void 0)return n;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let n=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of n){let a=relsPartNameFor(o);if(a!=="/_rels/.rels"&&w(a))continue;r.add(a);let s=this.projectOneRelsPart(a,e.get(a),i);s&&(e.set(a,s),this.partCache.set(a,s));}for(let[o,i]of e){if(r.has(o)||!Jt(o))continue;let a=Ht(o);if(a===null)continue;let s=this.projectOneRelsPart(o,i,n.get(a)??[]);!s||s===i||(e.set(o,s),this.partCache.set(o,s));}}projectOneRelsPart(e,n,r){if(!n&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),a=!!o&&(!n||Zt(o.root,n.root))&&o?o:n??en(e);if(qt(a.root,r))return this.relsProjection.set(e,a),a;let s=a.root.children,l=fn(a,Qt(s,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,n,r,o,i){for(let[a,s]of e){let l=hn(s.root);if(!l)continue;let d=I=>I.logicalId!==s.root.id&&l.isMember(I),u=[],p=new Set;for(let I of s.root.children){if(I.kind==="textValue")continue;let x=this.registry.record(I.id);!x||!v(x)||!d(x)||(u.push(I),p.add(I.id));}if(this.adoptLooseMembers(u,p,d,n,r,o,i)===0)continue;u.sort((I,x)=>l.sortKey(I).localeCompare(l.sortKey(x)));let h=[];for(let I of s.root.children)p.has(I.id)||h.push(I);let g=F(s.root.children,[...h,...u]);if(g===s.root.children)continue;let y=this.registry.record(s.root.id);if(!y||!v(y))continue;let M=fe(y,g,s.root);this.remember(s.root.id,M);let P=Object.freeze({...s,root:M});e.set(a,P),this.partCache.set(a,P);}}adoptLooseMembers(e,n,r,o,i,a,s){let l=0;for(let d of a){if(o.has(d)||n.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let u=this.registry.record(d);if(!u||!v(u)||!r(u))continue;let p=this.materialize(d,o,new Set,i);!p||p.kind==="textValue"||(e.push(p),n.add(d),s.add(d),l+=1);}return l}materializeOnce(e,n,r){return n.has(e)?this.cache.get(e)??null:this.materialize(e,n,new Set,r)}adoptNodesIntoRoot(e,n,r,o){let i=this.cache.get(e),a=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!a||a.kind==="textValue")return null;let s=[...a.children],l=new Set(s.map(h=>h.id)),d=0;for(let h of n){if(l.has(h))continue;let g=this.materializeOnce(h,r,o);!g||g.kind==="textValue"||(s.push(g),l.add(h),d+=1);}if(s.sort((h,g)=>Ye(h).localeCompare(Ye(g))),d===0&&s.every((h,g)=>h===a.children[g]))return a;let u=this.registry.record(e);if(!u||!v(u))return a;let p=F(a.children,s),c=fe(u,p,a);return this.remember(e,c),c}applyCustomXmlStores(e,n,r){let o=sn(this.registry,e);if(o.length===0||!un(e,o))return;let i=Ue(e,o),a=new Set;for(let s of o){a.add(s.itemName),a.add(s.propsName);let l=this.adoptNodesIntoRoot(s.dataRootId,s.nodeIds,n,r),d=this.materializeOnce(s.propsRootId,n,r);if(!l||!d||d.kind==="textValue")continue;let u=Object.freeze({id:s.itemName,name:s.itemName,contentType:"application/xml",root:l}),p=Object.freeze({id:s.propsName,name:s.propsName,contentType:CUSTOM_XML_PROPS_TYPE,root:d});e.set(s.itemName,u),e.set(s.propsName,p),this.partCache.set(s.itemName,u),this.partCache.set(s.propsName,p);}if(i){for(let s of [...e.keys()])!Z(s)&&!_e(s)||a.has(s)||(e.delete(s),this.partCache.delete(s));this.customXmlRels=ln(this.registry,o),this.customXmlOverrides=cn(o),this.projectRelsParts(e);}}assemblePackage(e){let n=this.packageCache.relationshipAssembly(this.customXmlRels);if(!n)return {ok:false,code:"invalid-relationships",issues:[...this.issues]};let r=this.packageCache.resolvePartBytes(this.blobs);if(!r)return {ok:false,code:"missing-blob",issues:[...this.issues]};let o=new Map(this.packageCache.contentTypeOverrides());for(let[s,l]of this.customXmlOverrides)o.set(s,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},a=this.registry.mainDocumentPart()||[...e.keys()].find(s=>s.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:n.byOwner,externalTargets:n.externalTargets,contentTypes:i,mainDocumentPart:a}),issues:[...this.issues]}}};var f=class extends Error{constructor(n,r){super(r?`${n}: ${r}`:n);this.code=n;this.detail=r;this.name="CollaborationSchemaError";}code;detail};var Ie=64*1024*1024,ee="docx-package-blobs-v1";function oo(t){if(t instanceof Uint8Array)return new Uint8Array(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t)){let e=t;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}return null}function io(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:0}function be(t,e){return Object.freeze(e===void 0?{code:t}:{code:t,detail:e})}var Y=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let n=this.shared.get(e),r=oo(n);return !r||typeof n!="object"||n===null?null:this.verify(e,n,r)?r:null}has(e){let n=this.shared.get(e);return n===void 0?false:this.verified.has(n)?true:this.get(e)!==null}poisonedDigest(){for(let e of this.poisoned)return e;return null}observeChanges(e){let n=r=>{e([...r.keysChanged]);};return this.shared.observe(n),()=>this.shared.unobserve(n)}verifyNow(e){for(let n of e)if(this.shared.has(n)&&this.get(n)===null)return n;return null}totalByteLength(){let e=0;return this.shared.forEach(n=>{e+=io(n);}),e}put(e,n){if(!this.shared.has(e)){if(this.totalByteLength()+n.byteLength>Ie)throw new f("blob-store-full");this.shared.set(e,new Uint8Array(n));}}verify(e,n,r){return this.verified.has(n)?true:this.poisoned.has(e)?false:sha256FontBytes(r)!==e?(this.poisoned.add(e),false):(this.verified.add(n),true)}};function te(t,e){let{limits:n}=t,r=t.nodeCount();if(r>n.maxNodes)return be("too-many-nodes",`${r}`);let o=t.schema.parts.size;if(o>n.maxParts)return be("too-many-parts",`${o}`);let i=0;if(t.schema.relationships.forEach(s=>{i+=s instanceof R.Map?s.size:0;}),i>n.maxRelationships)return be("too-many-relationships",`${i}`);let a=e.totalByteLength();return a>Ie?be("blob-store-full",`${a}`):null}var Rn=20*1024*1024,Ke=3e4,co=4e3,uo=1500,po="docx-collaboration-seeds-v1",je="docxEditorSeedCandidate",ho=/^[0-9a-f]{16}$/,mo=256;function Fe(t){if(!(t instanceof Uint8Array)||t.byteLength===0)throw new f("invalid-baseline");if(t.byteLength>Rn)throw new f("baseline-too-large");let e=readOoxmlPackage(t,{zip:{maxEntries:1e4,maxTotalBytes:Rn,maxRatio:200}});if(!e.ok)throw new f("invalid-baseline");let n=e.package.parts.get(e.package.mainDocumentPart);if(!n)throw new f("no-main-document-part");return new TreePackageStore(e.package,normalizeParagraphIdentity(n)).currentPackage()}function go(t,e){for(let n of t.binaries())if(!e.has(n.digest))return false;return true}function ne(t,e,n,r){let o=t.schema.meta,i=()=>o.get("initialized")===true&&go(t,e),a=()=>{let l=e.poisonedDigest();return l?new f("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let s=a();return s?Promise.reject(s):r?.aborted?Promise.reject(new f("initialization-aborted")):new Promise((l,d)=>{let u=g=>{clearTimeout(h),o.unobserve(p),t.doc.off("afterTransaction",p),r?.removeEventListener("abort",c),g?d(g):l();},p=()=>{let g=a();if(g){u(g);return}i()&&u();},c=()=>u(new f("initialization-aborted")),h=setTimeout(()=>u(new f("initialization-timeout")),n);o.observe(p),t.doc.on("afterTransaction",p),r?.addEventListener("abort",c,{once:true});})}function Ve(t){return t.getArray(po)}function xe(t){return Ve(t).length}function Ln(t,e){let n=Ve(t),r=()=>{n.length>1&&e();};return r(),n.observe(r),()=>n.unobserve(r)}function fo(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}function yo(t,e){let n=[...t.getStates().entries()].slice(0,mo);for(let[r,o]of n){if(r===t.clientID)continue;let i=o[je];if(!(typeof i!="string"||!ho.test(i))&&i<e)return true}return false}async function Cn(t,e,n,r){try{return await ne(t,e,n,r),!0}catch(o){if(o instanceof f&&o.code==="initialization-timeout")return false;throw o}}function bo(t,e,n){let r=t.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():n?.aborted?Promise.reject(new f("initialization-aborted")):new Promise((i,a)=>{let s=p=>{clearTimeout(u),r.unobserve(l),n?.removeEventListener("abort",d),p?a(p):i();},l=()=>{o()&&s();},d=()=>s(new f("initialization-aborted")),u=setTimeout(()=>s(new f("initialization-timeout")),e);r.observe(l),n?.addEventListener("abort",d,{once:true});})}async function kn(t){let{ydoc:e,awareness:n,registry:r,blobs:o}=t,i=t.probeTimeoutMs??co,a=t.electionWindowMs??uo,s=t.timeoutMs??Ke,l=async()=>(await bo(r,s,t.signal),"joined");if(await Cn(r,o,i,t.signal))return l();let d=fo();n.setLocalStateField(je,d);try{let u=await Cn(r,o,a,t.signal);if(!u&&yo(n,d)&&(await ne(r,o,s,t.signal),u=!0),u)return await l();if(r.schema.meta.get("initialized")===!0)return await ne(r,o,s,t.signal),await l();let p=await H(r,Fe(t.document),o);if(!p.ok)throw new f(p.code);return e.transact(()=>{r.schema.meta.set("documentId",t.documentId),Ve(e).push([d]);}),"seeded"}finally{n.setLocalStateField(je,null);}}var ve=class{constructor(e,n){this.knows=e;this.allocator=new V(n);}knows;allocator;toLogical=new Map;get replicaId(){return this.allocator.replicaId}reset(){this.toLogical.clear();}mint(e){let n=this.allocator.take();return this.toLogical.set(e,n),n}resolve(e){return this.toLogical.get(e)??e}translate(e){let n=[],r=false;for(let o of e.effects){let i=this.translateEffect(o);i!==o&&(r=true),n.push(i);}return r?Object.freeze({effects:Object.freeze(n)}):e}translateEffect(e){switch(e.kind){case "putNode":{let n=this.translateDescriptor(e.descriptor);return n.logicalId===e.descriptor.logicalId?e:{...e,descriptor:n}}case "spliceText":case "setAttribute":case "setNamespaceBinding":{let n=this.resolve(e.logicalId);return n===e.logicalId?e:{...e,logicalId:n}}case "spliceChildren":{let n=this.resolve(e.parentLogicalId),r=e.childLogicalIds.map(i=>this.resolve(i));return n===e.parentLogicalId&&r.every((i,a)=>i===e.childLogicalIds[a])?e:{...e,parentLogicalId:n,childLogicalIds:r}}case "moveNode":{let n=this.resolve(e.logicalId),r=this.resolve(e.destinationParentLogicalId);return n===e.logicalId&&r===e.destinationParentLogicalId?e:{...e,logicalId:n,destinationParentLogicalId:r}}case "putXmlPart":{let n=this.resolve(e.rootLogicalId);return n===e.rootLogicalId?e:{...e,rootLogicalId:n}}default:return e}}translateDescriptor(e){let n=this.resolve(e.logicalId);return this.knows(n)?{...e,logicalId:n}:{...e,logicalId:this.mint(e.logicalId)}}};function Io(t){let e=0;return t.schema.nodes.forEach(n=>{b(n)&&n.get(D)===true&&(e+=1);}),e}function xo(t){let e=0;return t.schema.relationships.forEach(n=>{e+=n instanceof R.Map?n.size:0;}),e}function An(t,e){return Object.freeze({nodes:t.nodeCount(),tombstonedNodes:Io(t),maxNodes:t.limits.maxNodes,relationships:xo(t),maxRelationships:t.limits.maxRelationships,parts:t.schema.parts.size,maxParts:t.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:Ie})}var Se="docxEditor",N=256,We=256;function Nn(t){let e=t.actorId.trim(),n=t.name.trim();if(e.length===0||e.length>N||n.length===0||n.length>N)throw new f("invalid-identity");if(t.color!==void 0&&t.color.length>64)throw new f("invalid-identity-color");return Object.freeze({actorId:e,name:n,...t.color?{color:t.color}:{},role:t.role??"human"})}function Mn(t){let e=t.trim();if(e.length===0||e.length>N)throw new f("invalid-document-id");return e}function Tn(t){let e=t?.trim()||globalThis.crypto.randomUUID();if(e.length>N)throw new f("invalid-session-id");return e}function On(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;return typeof e.paragraphId!="string"||e.paragraphId.length!==8||!Number.isSafeInteger(e.offset)||e.offset<0?null:{paragraphId:e.paragraphId.toUpperCase(),offset:e.offset}}function So(t){if(t===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=On(e.anchor),r=On(e.head);if(n&&r)return e.kind==="cells"?{anchor:n,head:r,kind:"cells"}:{anchor:n,head:r};if(typeof e.paragraphId=="string"&&e.paragraphId.length===8&&Number.isSafeInteger(e.start)&&Number.isSafeInteger(e.end)&&e.start>=0&&e.end>=0){let o=e.paragraphId.toUpperCase();return {anchor:{paragraphId:o,offset:e.start},head:{paragraphId:o,offset:e.end}}}}function $e(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;if(typeof e.actorId!="string"||e.actorId.length===0||e.actorId.length>N||typeof e.name!="string"||e.name.length===0||e.name.length>N)return null;let n=safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...n?{color:n}:{},role:r},i=So(e.selection);return i?{...o,selection:i}:o}function wo(t){let e=new _(t),n=null;try{if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new f("not-initialized");if(xe(t)>1)throw new f("concurrent-seed");let r=new Y(t.getMap(ee)),o=te(e,r);if(o)throw new f(o.code,o.detail);n=new U(e,r);let i=n.current(),a=r.poisonedDigest();if(a)throw new f("blob-digest-mismatch",a);if(!i.ok)throw new f(i.code);return writeOoxmlPackage(i.package)}finally{n?.destroy(),e.destroy();}}var Po=3,Ao=5e3,Oo=2e3,No=Symbol("createDocumentCollaboration.attachWatchdogMs"),Xe=class{constructor(e,n,r,o,i,a,s,l,d,u,p){this.ydoc=e;this.awareness=n;this.registry=a;this.materializer=s;this.identityMap=l;this.blobs=d;this.offlineEditing=p;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new R.UndoManager([...a.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:Ao,deleteFilter:a.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),n.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(c=>{let h=d.verifyNow(c);h&&this.setStatus("error","blob-digest-mismatch",h);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=Ln(e,()=>{this.setStatus("error","concurrent-seed");}),this.attachWatchdog=setTimeout(()=>{this.attachWatchdog=null,!(this.destroyed||this.port)&&console.warn(`[docx-editor] The collaboration session for "${this.documentId}" was created ${u}ms ago and no editor attached its document port. The session reports "ready" but no edits replicate. Remount the editor when the session appears \u2014 for example pass key={session.sessionId} \u2014 so collaborationModule({ session }) attaches it.`);},u),this.attachWatchdog.unref?.();}ydoc;awareness;registry;materializer;identityMap;blobs;offlineEditing;documentId;sessionId;currentIdentity;currentSelection;attachWatchdog=null;statusState=createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-document-local"});undoManager;port=null;detachPort=null;applyingRemote=false;realignedInBatch=false;journalsHeldDuringRemote=[];drainingHeldJournals=false;remoteCounter=0;destroyed=false;refusedInARow=0;stopBlobWatch;stopSeedWatch;get identity(){return this.currentIdentity}clearAttachWatchdog(){this.attachWatchdog!==null&&(clearTimeout(this.attachWatchdog),this.attachWatchdog=null);}status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}resourceUsage(){return An(this.registry,this.blobs)}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,n,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(n!==void 0){this.setStatus(e,n,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let n=this.refuseAttach(e);if(n)return n;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{if(!this.destroyed){if(this.applyingRemote){this.journalsHeldDuringRemote.push(o);return}this.realignedInBatch||this.applyJournal(o);}});return this.detachPort=()=>{this.flushPendingJournals(),r(),this.port===e&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}refuseAttach(e){return this.destroyed?()=>{}:this.port?(this.port!==e&&this.setStatus("error","port-already-attached"),()=>{}):e.documentId!==this.documentId?(this.setStatus("error","document-id-mismatch"),()=>{}):null}canWriteSharedState(){if(this.destroyed)return false;let e=this.statusState.status();return e==="ready"||this.offlineEditing&&e==="disconnected"}gateOperations(e,n){return this.destroyed?"collaboration-session-destroyed":this.canWriteSharedState()?this.port?null:"collaboration-session-not-attached":"collaboration-session-not-ready"}canUndo(){return this.canWriteSharedState()&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return this.canWriteSharedState()&&this.undoManager.redoStack.length>0}undo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.undoStack.length===0?false:(this.undoManager.undo(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.undoManager.redo(),true)}flushPendingJournals(){this.port?.flushPendingJournals();}setLocalSelection(e){if(!this.destroyed){if(!e){this.publishAwareness();return}this.publishAwareness({anchor:{paragraphId:e.anchor.paragraphId.toUpperCase(),offset:Math.max(0,e.anchor.offset)},head:{paragraphId:e.head.paragraphId.toUpperCase(),offset:Math.max(0,e.head.offset)},...e.kind==="cells"?{kind:"cells"}:{}});}}participants(){let e=[],n=[...this.awareness.getStates().entries()].slice(0,We);for(let[r,o]of n){let i=$e(o[Se]);i&&e.push({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},role:i.role,isLocal:r===this.awareness.clientID});}return Object.freeze(e)}subscribeParticipants(e){return this.participantListeners.add(e),()=>this.participantListeners.delete(e)}remoteSelections(){let e=this.port;if(!e)return [];let n=i=>{let a=e.paragraphByStableId(i.paragraphId);return a?Object.freeze({paragraphId:a.paragraphId,nodeId:a.nodeId,offset:Math.min(i.offset,a.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,We),o=[];for(let[i,a]of r){if(i===this.awareness.clientID)continue;let s=$e(a[Se]);if(!s?.selection)continue;let l=n(s.selection.anchor),d=n(s.selection.head);!l||!d||o.push(Object.freeze({actorId:s.actorId,name:s.name,...s.color?{color:s.color}:{},...s.selection.kind==="cells"?{kind:"cells"}:{},anchor:l,head:d}));}return Object.freeze(o)}subscribeRemoteSelections(e){return this.selectionListeners.add(e),()=>this.selectionListeners.delete(e)}setIdentity(e){if(this.destroyed)return;let n=e.name===void 0?this.currentIdentity.name:e.name.trim();if(n.length===0||n.length>N)throw new f("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new f("invalid-identity-color");r=safeParticipantColor(e.color);}this.currentIdentity=Object.freeze({actorId:this.currentIdentity.actorId,name:n,...r?{color:r}:{},role:this.currentIdentity.role??"human"}),this.publishAwareness(this.currentSelection);}destroy(){this.destroyed||(this.clearAttachWatchdog(),this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.stopBlobWatch(),this.stopSeedWatch(),this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.materializer.destroy(),this.registry.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}applyJournal(e){let n=this.identityMap.translate(e),r=this.collectJournalBlobs(e);if(r!==null&&r.ok===false){this.refuseLocalJournal(r.failure);return}let o=this.ydoc.transact(()=>{if(r!==null){let a=this.putJournalBlobs(r.payloads);if(a!==null)return a}let i=De(this.registry,n);return i.ok?null:{code:i.code,...i.detail?{detail:i.detail}:{}}},this.localOrigin);if(o===null){this.refusedInARow=0;return}this.refuseLocalJournal(o);}collectJournalBlobs(e){let n=this.port;if(!n)return e.effects.some(i=>i.kind==="putBinary")?{ok:false,failure:Object.freeze({code:"collaboration-session-not-attached"})}:null;let r=Ft(e.effects,Kt(n));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{Vt(this.blobs,e);}catch(n){return n instanceof f?Object.freeze({code:n.code,...n.detail?{detail:n.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){this.undoManager.stopCapturing();let n=this.statusState.snapshot();this.refusedInARow+=1,this.setStatus("error",e.code,e.detail),this.publishSharedToPort(),this.realignedInBatch=true,queueMicrotask(()=>{this.realignedInBatch=false;});let r=this.statusState.snapshot().reason;this.refusedInARow<Po&&this.statusState.status()==="error"&&r!==void 0&&r.code===e.code&&r.detail===e.detail&&(n.status==="ready"||n.status==="disconnected")&&this.setStatus(n.status,n.reason?.code,n.reason?.detail);}onYjsTransaction=e=>{this.destroyed||!this.port||e.origin!==this.localOrigin&&this.publishSharedToPort();};publishSharedToPort(){let e=this.port;if(!(!e||this.applyingRemote)){this.applyingRemote=true;try{let n=te(this.registry,this.blobs);if(n){this.setStatus("error",n.code,n.detail);return}let r=this.materializer.current(),o=this.blobs.poisonedDigest();if(o){this.setStatus("error","blob-digest-mismatch",o);return}if(!r.ok){this.setStatus("error",r.code);return}let i=st(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let a=e.applyRemotePackage(r.package,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!a.ok){this.setStatus("error","remote-apply-failed",a.reason);return}a.changed&&this.identityMap.reset();}catch(n){this.setStatus("error",n instanceof f?n.code:"remote-apply-failed",n instanceof f?n.detail:void 0);}finally{this.applyingRemote=false,this.drainJournalsHeldDuringRemote();}}}drainJournalsHeldDuringRemote(){if(!this.drainingHeldJournals){this.drainingHeldJournals=true;try{for(;this.journalsHeldDuringRemote.length>0;){if(this.destroyed||this.realignedInBatch){this.journalsHeldDuringRemote.length=0;return}let e=this.journalsHeldDuringRemote.shift();e&&this.applyJournal(e);}}finally{this.drainingHeldJournals=false;}}}onAwarenessChange=()=>{if(this.destroyed)return;let e=this.remoteSelections();for(let r of [...this.selectionListeners])r(e);let n=this.participants();for(let r of [...this.participantListeners])r(n);};publishAwareness(e){this.currentSelection=e;let n={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...e?{selection:e}:{}};this.awareness.setLocalStateField(Se,n);}setStatus(e,n,r){if(!this.statusState.set(e,n,r))return;let o=this.statusState.snapshot();for(let i of [...this.statusListeners])i(o.status,o.reason?.code,o.reason?.detail);}};async function Ka(t){let e=t[No]??Oo,n=Mn(t.documentId),r=Tn(t.sessionId),o=Nn(t.identity),i=new _(t.ydoc);try{return await Mo(t,{attachWatchdogMs:e,documentId:n,sessionId:r,identity:o,registry:i})}catch(a){throw i.destroy(),a}}async function Mo(t,e){let{attachWatchdogMs:n,documentId:r,sessionId:o,identity:i,registry:a}=e,s=new ve(p=>a.hasNode(p)),l=new Y(t.ydoc.getMap(ee));if(t.bootstrap.kind==="create"){if(a.schema.meta.get("initialized")===true)throw new f("already-initialized");let p=await H(a,Fe(t.bootstrap.document),l);if(!p.ok)throw new f(p.code);t.ydoc.transact(()=>{a.schema.meta.set("documentId",r);});}else if(t.bootstrap.kind==="create-or-join"){if(await kn({ydoc:t.ydoc,awareness:t.awareness,registry:a,blobs:l,documentId:r,document:t.bootstrap.document,probeTimeoutMs:t.bootstrap.probeTimeoutMs,electionWindowMs:t.bootstrap.electionWindowMs,timeoutMs:t.bootstrap.timeoutMs,signal:t.bootstrap.signal})==="joined"){if(a.schema.meta.get("documentId")!==r)throw new f("document-id-mismatch");a.rebuildDerivedIndexes();}}else {if(await ne(a,l,t.bootstrap.timeoutMs??Ke,t.bootstrap.signal),a.schema.meta.get("documentId")!==r)throw new f("document-id-mismatch");a.rebuildDerivedIndexes();}if(xe(t.ydoc)>1)throw new f("concurrent-seed");let d=te(a,l);if(d)throw new f(d.code,d.detail);let u=new U(a,l);try{let p=u.current(),c=l.poisonedDigest();if(c)throw new f("blob-digest-mismatch",c);if(!p.ok)throw new f(p.code);let h=writeOoxmlPackage(p.package),g=new Xe(t.ydoc,t.awareness,r,o,i,a,u,s,l,n,t.offlineEditing===!0);return Object.freeze({document:h,session:g,destroy:()=>g.destroy()})}catch(p){throw u.destroy(),p}}export{f as a,wo as b,No as c,Ka as d};