@docx-editor.dev/pro 2.10.0 → 2.11.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.
- package/README.md +1 -7
- package/dist/chunk-32RB7HPL.js +3 -0
- package/dist/chunk-4HGT2OVX.cjs +3 -0
- package/dist/chunk-6DEUT2RQ.js +1 -0
- package/dist/chunk-7QSJBMZV.js +3 -0
- package/dist/chunk-EMO6YTKO.cjs +1 -0
- package/dist/chunk-GDTCNTK7.cjs +1 -0
- package/dist/chunk-HJB77VBO.js +1 -0
- package/dist/chunk-LUUFBXJ5.cjs +1 -0
- package/dist/chunk-NQW54J56.js +1 -0
- package/dist/chunk-Q2VBO66F.js +1 -0
- package/dist/chunk-Q4YPX2DT.cjs +1 -0
- package/dist/chunk-QLZH2Q2C.cjs +1 -0
- package/dist/chunk-W3V54DWZ.js +1 -0
- package/dist/chunk-YJM6R76M.cjs +3 -0
- package/dist/collaboration/hocuspocus.cjs +1 -0
- package/dist/collaboration/hocuspocus.d.cts +58 -0
- package/dist/collaboration/hocuspocus.d.ts +58 -0
- package/dist/collaboration/hocuspocus.js +1 -0
- package/dist/collaboration/index.cjs +2 -0
- package/dist/collaboration/index.d.cts +22 -0
- package/dist/collaboration/index.d.ts +22 -0
- package/dist/collaboration/index.js +2 -0
- package/dist/collaboration/webrtc.cjs +2 -0
- package/dist/collaboration/webrtc.d.cts +86 -0
- package/dist/collaboration/webrtc.d.ts +86 -0
- package/dist/collaboration/webrtc.js +2 -0
- package/dist/collaboration-module-BgRxhW5b.d.cts +45 -0
- package/dist/collaboration-module-BgRxhW5b.d.ts +45 -0
- package/dist/{define-custom-node-Bk8kFO27.d.cts → define-custom-node-B_p2nr9T.d.cts} +2 -20
- package/dist/{define-custom-node-Bk8kFO27.d.ts → define-custom-node-BehI3jWX.d.ts} +2 -20
- package/dist/document-session-2B3QFWBQ.cjs +1 -0
- package/dist/document-session-6UET6BWT.js +1 -0
- package/dist/document-session-DVa53DAw.d.cts +94 -0
- package/dist/document-session-DiBuzWwA.d.ts +94 -0
- package/dist/document-session-RGNZHMWF.js +1 -0
- package/dist/document-session-TU7WVBRB.cjs +1 -0
- package/dist/hocuspocus-EUC4BGDD.js +1 -0
- package/dist/hocuspocus-YIKH6ENE.cjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +1 -1
- package/dist/react/hocuspocus.cjs +1 -0
- package/dist/react/hocuspocus.d.cts +104 -0
- package/dist/react/hocuspocus.d.ts +104 -0
- package/dist/react/hocuspocus.js +1 -0
- package/dist/react/index.cjs +2 -2
- package/dist/react/index.d.cts +320 -5
- package/dist/react/index.d.ts +320 -5
- package/dist/react/index.js +2 -2
- package/dist/react/webrtc.cjs +1 -0
- package/dist/react/webrtc.d.cts +98 -0
- package/dist/react/webrtc.d.ts +98 -0
- package/dist/react/webrtc.js +1 -0
- package/dist/room-id-BfudXOZz.d.cts +13 -0
- package/dist/room-id-BfudXOZz.d.ts +13 -0
- package/dist/session-BH7Qgyp6.d.cts +140 -0
- package/dist/session-BH7Qgyp6.d.ts +140 -0
- package/dist/session-okdqygLg.d.cts +82 -0
- package/dist/session-okdqygLg.d.ts +82 -0
- package/dist/vue/hocuspocus.cjs +1 -0
- package/dist/vue/hocuspocus.d.cts +105 -0
- package/dist/vue/hocuspocus.d.ts +105 -0
- package/dist/vue/hocuspocus.js +1 -0
- package/dist/vue/index.cjs +2 -2
- package/dist/vue/index.d.cts +437 -1
- package/dist/vue/index.d.ts +437 -1
- package/dist/vue/index.js +2 -2
- package/dist/vue/webrtc.cjs +1 -0
- package/dist/vue/webrtc.d.cts +99 -0
- package/dist/vue/webrtc.d.ts +99 -0
- package/dist/vue/webrtc.js +1 -0
- package/dist/webrtc-36GPPCW4.js +2 -0
- package/dist/webrtc-CDIFHCQY.cjs +2 -0
- package/package.json +62 -7
- package/dist/chunk-4LFF2FXG.cjs +0 -1
- package/dist/chunk-TH5PXU6L.js +0 -1
package/README.md
CHANGED
|
@@ -125,13 +125,7 @@ Every value reaching `fromDocx` came out of a `.docx`, so treat `attrs` and `tex
|
|
|
125
125
|
|
|
126
126
|
## Licensing
|
|
127
127
|
|
|
128
|
-
|
|
129
|
-
[EigenPal Pro Evaluation License 1.0](https://github.com/eigenpal/docx-editor/blob/main/packages/pro/LICENSE.md):
|
|
130
|
-
free to read, run, and modify internally to evaluate. Production use (a live or customer-facing
|
|
131
|
-
environment, business-operational data, or this package inside something you offer to others)
|
|
132
|
-
requires a written commercial agreement, and so does redistribution.
|
|
133
|
-
|
|
134
|
-
Commercial licensing: [licensing@eigenpal.com](mailto:licensing@eigenpal.com)
|
|
128
|
+
This package is licensed under the [EigenPal Pro License](https://github.com/eigenpal/docx-editor/blob/main/packages/pro/LICENSE.md), and you can compare and buy license and support levels on the [pricing page](https://www.docx-editor.dev/pricing).
|
|
135
129
|
|
|
136
130
|
Both module factories accept an optional `licenseKey`. Construction never validates it and never
|
|
137
131
|
touches the network.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import*as w from'yjs';import {readOoxmlPackage,normalizeParagraphIdentity,TreePackageStore,writeOoxmlPackage,partNameKey,relsPartNameFor,CUSTOM_XML_PROPS_TYPE,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 {createCollaborationDocumentPort}from'@docx-editor.dev/core/collaboration/replication';var zn=new Set(["paraId","textId","id","numId","bookmarkId"]);function We(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function Je(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),We(e)}function Ie(n){return /^[0-9a-f]{32}$/.test(n)}function Ge(n,e){if(!Ie(n))throw new Error("invalid replica identity");if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid logical-id counter");return `lid:${n}:${e.toString(10)}`}function xe(n,e){return `yjs:${n}:${e}`}function ve(n){let e=[];for(let t of n)zn.has(t.localName)&&e.push(t.value);return e}var F=class{replicaId;next=0;constructor(e){if(this.replicaId=e??Je(),!Ie(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}),jn=/^sha256:[0-9a-f]{64}$/;function qe(n){return n?Object.freeze({...A,...n}):A}function m(n){return isDangerousKey(n)?"prototype-key":null}function L(n,e){return typeof n!="string"||n.length>e?"invalid-string":isDangerousKey(n)?"prototype-key":null}function E(n){let e=m(n);if(e)return e;if(typeof n!="string"||n.length===0)return "unsafe-part-name";let t=normalizePartName(n);return !t.ok||t.partName!==n?"unsafe-part-name":null}function Ze(n){for(let e of Object.keys(n)){let t=m(e);if(t)return t}return !jn.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>A.maxBlobBytes?"blob-too-large":L(n.mediaType,A.maxMediaTypeLength)||n.mediaType.length===0||L(n.storageKey,A.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var Qe=1,et=2,tt=1,nt=1,Kn="docx-package-meta-v1",Fn="docx-package-nodes-v1",Vn="docx-package-parts-v1",$n="docx-package-rels-v1",Xn="docx-package-overrides-v1",Wn="docx-package-defaults-v1",Jn="docx-package-binaries-v1",Gn="docx-package-namespaces-v1",Hn="docx-package-attributes-v1",qn="docx-package-bindings-v1",B="s",T="t",ne="children",P="deleted",_="replacedBy",v="",rt="-",ot=Object.freeze({kind:"docx-package-bootstrap"}),it=Object.freeze({kind:"docx-package-journal"});function re(n){return n.kind==="textValue"}function x(n){return !re(n)}var Zn=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),Qn=200;function at(n){let e=new Map;for(let t of n)Zn.has(t.code)&&e.set(t.code,(e.get(t.code)??0)+1);return e.size===0?null:[...e].sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${t}=${r}`).join(",").slice(0,Qn)}function st(n){return {meta:n.getMap(Kn),nodes:n.getMap(Fn),parts:n.getMap(Vn),relationships:n.getMap($n),overrides:n.getMap(Xn),defaults:n.getMap(Wn),binaries:n.getMap(Jn),namespaces:n.getMap(Gn),attributes:n.getMap(Hn),bindings:n.getMap(qn)}}var lt=[["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"]],er=new Map(lt),tr=new Map(lt.map(([n,e])=>[e,n]));function nr(n){let e=0xcbf29ce484222325n,t=0x100000001b3n;for(let r=0;r<n.length;r+=1)e^=BigInt(n.charCodeAt(r)),e=e*t&0xffffffffffffffffn;return e.toString(16).padStart(16,"0")}function V(n){return n.length===0?rt:er.get(n)??`n${nr(n)}`}function U(n,e,t){let r=V(e);return e.length===0||m(r)||L(e,t)||n.get(r)!==e&&n.set(r,e),r}function $(n,e){if(e===rt||m(e))return "";let t=n.get(e);return typeof t=="string"?t:tr.get(e)??""}function Se(n,e,t,r){return `${n}${v}${e}${v}${t}${v}${r}`}function oe(n){let e=n.split(v);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function Ee(n,e,t){return `${n}${v}${e}${v}${t}`}function ie(n){let e=n.split(v);if(e.length!==3)return null;let t=e[0],r=e[1],o=e[2];return t.length===0||o.length===0?null:{logicalId:t,namespaceId:r,localName:o}}function we(n,e){return `${n}${v}${e}`}function ae(n){let e=n.split(v);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function dt(n,e){return `${n}${v}${e}`}function ct(n){let e=n.indexOf(v);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function ut(n){let e=new w.Map;e.set(B,Se(n.kind,n.namespaceId,n.localName,n.prefix??""));let t=new w.Array;return n.childIds&&n.childIds.length>0&&t.push([...n.childIds]),e.set(ne,t),e}function pt(n){let e=new w.Map;return e.set(T,new w.Text(n)),e}function ht(n,e,t){let r=new w.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function mt(n){let e=new w.Map;return e.set("ownerPart",n.ownerPart),e.set("id",n.id),e.set("type",n.type),e.set("rawTarget",n.rawTarget),e.set("targetMode",n.targetMode),e.set("order",n.order),e}function gt(n){let e=new w.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function ft(n){n.set("protocolVersion",Qe),n.set("sharedSchemaVersion",et),n.set("repairVersion",tt),n.set("canonicalModelVersion",nt),n.set("initialized",true);}function R(n){let e=n.get(ne);return e instanceof w.Array?e:null}function X(n){return n.get(T)instanceof w.Text}function O(n){return n instanceof w.Map}function se(n){return typeof n=="string"?n:""}function yt(n,e){return n<e?-1:n>e?1:0}function Le(n,e){return `${n}${v}${e}`}function or(n){let e=n.indexOf(v);return e<0?n:n.slice(0,e)}function bt(n){let e=[];return n.forEach((t,r)=>{!O(t)||m(r)||t.forEach(o=>{if(!O(o))return;let i=se(o.get("id")),s=se(o.get("type"));if(i.length===0||s.length===0)return;let a=se(o.get("ownerPart"))||or(r);if(m(a))return;let l=o.get("order");e.push({ownerPart:a,id:i,type:s,rawTarget:se(o.get("rawTarget")),targetMode:o.get("targetMode")==="External"?"External":"Internal",order:typeof l=="number"&&Number.isSafeInteger(l)?l:0});});}),e.sort((t,r)=>t.order-r.order||yt(t.ownerPart,r.ownerPart)||yt(t.id,r.id)),e}function ir(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r+=1){let o=n[r]-e[r];if(o!==0)return o}return n.length-e.length}function It(n,e){let t=n.childrenSnapshot.get(e);if(t)return t;let r=n.nodes.get(e);return r?R(r)?.toArray()??[]:[]}function ar(n,e){let t=n.nodes.get(e);return !t||t.get(P)===true}function sr(n,e,t,r){let o=[],i=new Set,s=r,a;for(;;){if(i.has(s)||(i.add(s),ar(n,s)))return null;a=e.get(s);let c=n.parentIndex.get(s);if(a!==void 0){if(c!==void 0)return "fallback";break}if(c===void 0)return t.has(s)?"deferred":null;o.push(s),s=c;}let l=[a],d=s;for(let c=o.length-1;c>=0;c-=1){let g=o[c],u=It(n,d).indexOf(g);if(u<0)return null;l.push(u),d=g;}return l}function xt(n,e){let t=new Set(e);for(let i of t)n.parentIndex.delete(i);let r=new Map;n.partRoots.forEach((i,s)=>{r.has(i)||r.set(i,s);});let o=[...t];for(;o.length>0;){let i=[];for(let s of o){let a=null,l=false;for(let d of n.listings.get(s)??[]){if(d===s)continue;let c=sr(n,r,t,d);if(c==="fallback")return false;if(c==="deferred"){l=true;continue}if(c===null)continue;let g=It(n,d).indexOf(s);if(g<0)continue;let u=[...c,g];(!a||ir(u,a.rank)<0)&&(a={rank:u,parent:d});}if(l){i.push(s);continue}a&&n.parentIndex.set(s,a.parent),t.delete(s);}if(i.length===o.length)return false;o=i;}return true}function vt(n,e){let{nodes:t,parentIndex:r,childrenSnapshot:o,partRoots:i}=n;if(e)for(let s of e)r.delete(s);for(let s of i){let a=new Set,l=[{id:s,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){a.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)),a.has(c))continue;let g=t.get(c);if(!g||g.get(P)===true)continue;let u=o.get(c)??R(g)?.toArray()??[];a.add(c),l.push({id:c,parent:null,exit:true});let p=new Set,f=[];for(let y of u)p.has(y)||y===c||(p.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 St(n,e){return `${n}${v}${e}`}function Ce(n,e,t,r,o){if(m(t)||m(r.localName))return;let i=U(n.namespaces,r.namespaceUri,e),s=Ee(t,i,r.localName);m(s)||n.attributes.set(s,dt(r.prefix??"",o));}function Et(n,e,t,r){n.attributes.delete(Ee(e,V(t),r));}function Re(n,e,t,r,o){if(m(t)||m(r))return;let i=U(n.namespaces,o,e),s=we(t,r);m(s)||n.bindings.set(s,i);}function wt(n,e,t){n.bindings.delete(we(e,t));}function ke(n,e,t,r,o,i){let{prefix:s,value:a}=ct(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(St(r,o),{namespaceUri:$(n.namespaces,r),localName:o,prefix:s.length>0?s:void 0,value:a});}function Lt(n,e,t,r){let o=n.get(e);o&&(o.delete(St(t,r)),o.size===0&&n.delete(e));}function Pe(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:$(n.namespaces,o)});}function Ct(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function kt(n,e){let t=n.get(e);if(!t)return null;if(X(t)){let r=t.get(T);return {isText:true,textLength:r instanceof w.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:R(t)?.toArray()??[]}}function Pt(n,e){let t=n.get(e);if(!t)return null;if(X(t))return "textValue";let r=t.get(B);return oe(typeof r=="string"?r:"").kind}function At(n,e){if(n.length!==e.length)return false;for(let t=0;t<n.length;t+=1)if(n[t]!==e[t])return false;return true}function z(n){return typeof n=="string"?n:""}function Ot(n){let e=[];return n.forEach((t,r)=>{if(!O(t)||m(r))return;let o=z(t.get("rootId"));o.length!==0&&e.push({name:r,id:z(t.get("id")),rootLogicalId:o,contentType:z(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function Nt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!m(r)&&e.set(partNameKey(r),t);}),e}function Mt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!m(r)&&e.set(r,t);}),e}function Tt(n){let e=[];return n.forEach((t,r)=>{if(!O(t)||m(r))return;let o=z(t.get("digest")),i=t.get("size"),s=z(t.get("mediaType")),a=z(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:s,storageKey:a});}),e}function dr(n){return n?._item??null}function cr(n){return n.content instanceof w.ContentType}function Bt(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=dr(t);return r===null||r.parent!==n?true:!cr(e)}}function ur(n){let e=n._item;return e?xe(e.id.client,e.id.clock):null}function Ut(n){return typeof n=="string"?n:""}var Y=class{constructor(e,t){this.doc=e;this.schema=st(e),this.limits=qe(t),this.schema.nodes.observeDeep(r=>{this.bulkLoad>0||this.applyChildArrayEvents(r);}),this.schema.attributes.observe(r=>{this.bulkLoad>0||this.applyAttributeMapEvent(r);}),this.schema.bindings.observe(r=>{this.bulkLoad>0||this.applyBindingMapEvent(r);}),this.schema.relationships.observeDeep(()=>{this.relationshipCountCache=-1;}),this.schema.parts.observeDeep(()=>{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;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 Bt(this.schema.nodes)}encodeSnapshot(){return w.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return w.encodeStateAsUpdate(this.doc,e)}partEntries(){return Ot(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 Ut(this.schema.meta.get("mainDocumentPart"))}record(e){if(m(e))return null;let t=this.schema.nodes.get(e);if(!t)return null;if(X(t)){let r=t.get(T),o=r instanceof w.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return this.elementRecord(e,t)}parentOf(e){return this.parentIndex.get(e)??null}identityMeta(e){let t=this.schema.nodes.get(e);if(!t)return null;let r=this.record(e),o=r&&x(r)?r.attributes:[];return {logicalId:e,yjsItemKey:ur(t),wordFacingIds:ve(o)}}isTombstoned(e){return this.schema.nodes.get(e)?.get(P)===true}replacedByOf(e){let t=this.schema.nodes.get(e)?.get(_);return typeof t=="string"&&t.length>0?t:null}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(V(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:kt(this.schema.nodes,e)}kindOf(e){return m(e)?null:Pt(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=U(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,ut({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)Ce(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)Re(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=U(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(B,Se(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,pt(t));}spliceText(e,t,r,o){let i=this.textOf(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,o);}setAttribute(e,t,r){if(r===null){Et(this.schema,e,t.namespaceUri,t.localName);return}Ce(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){wt(this.schema,e,t);return}Re(this.schema,this.limits.maxStringLength,e,t,r);}spliceChildren(e,t,r,o){let i=this.childArray(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,[...o]);}moveNode(e,t,r){this.unlinkFromAllParents(e);let o=this.childArray(t);o.insert(Math.max(0,Math.min(r,o.length)),[e]);}tombstone(e,t){this.unlinkFromAllParents(e);let r=this.require(e);r.set(P,true),t&&r.set(_,t);}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?R(r):null;if(!o)return;let i=new Map;for(let s of t)i.set(s,(i.get(s)??0)+1);for(let s=o.length-1;s>=0;s-=1){let a=o.get(s),l=i.get(a)??0;l!==0&&(i.set(a,l-1),o.delete(s,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,ht(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 t=new w.Map;t.set(e.id,mt(e)),this.schema.relationships.set(Le(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(Le(e,t)),this.schema.relationships.get(e)?.delete(t);}putContentTypeOverride(e,t){this.schema.overrides.set(partNameKey(e),t);}deleteContentTypeOverride(e){this.schema.overrides.delete(partNameKey(e));}putContentTypeDefault(e,t){this.schema.defaults.set(e,t);}putBinary(e){this.schema.binaries.set(e.storageKey,gt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return bt(this.schema.relationships)}contentTypeOverrides(){return Nt(this.schema.overrides)}contentTypeDefaults(){return Mt(this.schema.defaults)}binaries(){return Tt(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){let t=i=>{let s=new Set,a=false;for(let l of i){let d=l.path;if(d.length===0){for(let c of l.changes.keys.keys())s.add(String(c));a=true;continue}s.add(String(d[0])),l.target instanceof w.Array&&(a=true),l.target instanceof w.Map&&(l.changes.keys.has(P)||l.changes.keys.has(_))&&(a=true);}(s.size>0||a)&&e({logicalIds:s,membershipChanged:a,packageChanged:false});},r=i=>{let s=new Set;for(let a of i.changes.keys.keys()){let l=ie(String(a))??ae(String(a));!l||m(l.logicalId)||s.add(l.logicalId);}s.size>0&&e({logicalIds:s,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return this.schema.nodes.observeDeep(t),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(t),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,t)=>{if(m(t))return;let r=R(e);if(!r)return;let o=r.toArray();this.childrenSnapshot.set(t,o);for(let i of o)this.addListing(i,t);}),this.schema.nodes.forEach((e,t)=>{e.get(P)===true&&this.syncAdoptee(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||m(t))return;let r=ie(t);!r||m(r.logicalId)||m(r.localName)||ke(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,t)=>{if(typeof e!="string"||m(t))return;let r=ae(t);!r||m(r.logicalId)||m(r.prefix)||Pe(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(O(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 t=new Set;for(let r of e){if(r.path.length===0&&r.target instanceof w.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 s of this.syncChildListings(String(o)))t.add(s);continue}if(r.target instanceof w.Array&&r.path.length>0){let o=String(r.path[0]);for(let i of this.syncChildListings(o))t.add(i);this.isTombstoned(o)&&this.syncAdoptee(o);continue}r.target instanceof w.Map&&r.path.length===1&&(r.changes.keys.has(P)||r.changes.keys.has(_))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0;for(let[t,r]of e.changes.keys){let o=ie(String(t));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(t));typeof i=="string"&&ke(this.schema,this.attributesByNode,o.logicalId,o.namespaceId,o.localName,i);}}applyBindingMapEvent(e){this.unobservedWrites=0;for(let[t,r]of e.changes.keys){let o=ae(String(t));if(!o||m(o.logicalId)||m(o.prefix))continue;if(r.action==="delete"){Ct(this.bindingsByNode,o.logicalId,o.prefix);continue}let i=this.schema.bindings.get(String(t));typeof i=="string"&&Pe(this.schema,this.bindingsByNode,o.logicalId,o.prefix,i);}}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?R(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(At(o,r))return [];let i=new Set(r),s=new Set(o),a=[];for(let l of o)i.has(l)||(this.removeListing(l,e),a.push(l));for(let l of r)s.has(l)||(this.addListing(l,e),a.push(l));return this.childrenSnapshot.set(e,r),a}addListing(e,t){let r=this.listings.get(e)??new Set;r.add(t),this.listings.set(e,r);}removeListing(e,t){let r=this.listings.get(e);r&&(r.delete(t),r.size===0&&this.listings.delete(e));}resolveParents(e){let t=[];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}t.push(o);}if(t.length===0)return;xt({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(o=>o.rootLogicalId)},t)||this.assignFirstReachable(new Set(t));}assignFirstReachable(e){vt({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(t=>t.rootLogicalId)},e);}syncAdoptee(e){let t=this.tombstoneSurvivor.get(e);if(t!==void 0){this.tombstoneSurvivor.delete(e);let i=this.tombstoneSources.get(t);i&&(i.delete(e),i.size===0&&this.tombstoneSources.delete(t));}let r=this.schema.nodes.get(e),o=r?.get(_);if(!(typeof o!="string"||o.length===0)){if(r?.get(P)===true){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 t=this.kindOf(e);return t!==null&&!t.endsWith("Properties")}recomputeAdoptees(e){let t=[];for(let r of this.tombstoneSources.get(e)??[]){let o=this.schema.nodes.get(r);if(o)for(let i of R(o)?.toArray()??[])this.isTombstoned(i)||!this.schema.nodes.has(i)||this.isContentWitness(i)&&t.push(i);}t.length>0?this.adoptees.set(e,t):this.adoptees.delete(e);}unlinkFromAllParents(e){let t=[...this.listings.get(e)??[]];if(t.length===0){this.schema.nodes.forEach(r=>{let o=R(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?R(o):null;i&&this.removeFromArray(i,e);}}removeFromArray(e,t){for(let r=e.length-1;r>=0;r-=1)e.get(r)===t&&e.delete(r,1);}elementRecord(e,t){let r=oe(Ut(t.get(B))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:$(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:this.childArray(e).toArray()}}textOf(e){let t=this.require(e).get(T);if(!(t instanceof w.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(ne);if(!(t instanceof w.Array))throw new Error(`no children at ${e}`);return t}require(e){let t=this.schema.nodes.get(e);if(!t)throw new Error(`registry node ${e} missing`);return t}};var le=class{blobs=new Map;get(e){let t=this.blobs.get(e);return t?t.slice():null}put(e,t){this.blobs.set(e,t.slice());}};async function zt(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return `sha256:${[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Yt(n){let e=n.binaryPart;return typeof e=="function"?e:null}function jt(n,e){let t=[];for(let o of n)o.kind==="putBinary"&&t.push(o.descriptor);if(t.length===0)return null;if(!e)return {ok:false,failure:{code:"blob-read",detail:"binary-part-reader"}};let r=[];for(let o of t){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 Kt(n,e){for(let t of e)n.put(t.digest,t.bytes);}function hr(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function mr(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function Ft(n,e,t,r,o){if(r>n.limits.maxTreeDepth)return "tree-too-deep";if(m(e.id))return "prototype-key";if(o.nodes+=1,o.nodes>n.limits.maxNodes)return "too-many-nodes";if(e.kind==="textValue"){if(e.value.length>n.limits.maxTextLength)return "text-too-long";n.putText(e.id,e.value);}else {if(e.attributes.length>n.limits.maxAttributes)return "too-many-attributes";if(e.children.length>n.limits.maxChildren)return "too-many-children";if(L(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(m(i.localName))return "prototype-key";if(L(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(m(i.prefix))return "prototype-key";if(L(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}n.putElement({logicalId:e.id,kind:e.kind,namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,attributes:hr(e),bindings:mr(e)});for(let i of e.children){let s=Ft(n,i,e.id,r+1,o);if(s)return s}}return t&&n.childArray(t).push([e.id]),null}async function gr(n){let e=[],t=[];for(let[r,o]of n.partBytes){if(n.parts.has(r))continue;let s=n.contentTypes.overrides.get(r)??"application/octet-stream",a=E(r);if(a)return {ok:false,code:a};if(o.byteLength>A.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await zt(o);t.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:s,storageKey:r});}return {ok:true,descriptors:e,payloads:t}}async function W(n,e,t=new le){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await gr(e);if(!r.ok)return r;let o=null;n.beginBulkLoad();try{n.doc.transact(()=>{for(let a of r.payloads)t.put(a.digest,a.bytes);ft(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);let i={nodes:0};for(let[a,l]of e.parts){let d=E(a);if(d){o=d;return}if(L(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let c=Ft(n,l.root,null,0,i);if(c){o=c;return}n.putXmlPart({name:a,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let s=0;for(let a of e.relationships.values())for(let l of a){if(s+=1,s>n.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=E(l.ownerPart);if(d){o=d;return}}if(m(l.id)){o="prototype-key";return}n.putRelationship({ownerPart:l.ownerPart,id:l.id,type:l.type,rawTarget:l.rawTarget,targetMode:l.targetMode,order:l.order});}for(let[a,l]of e.contentTypes.defaults){if(m(a)){o="prototype-key";return}n.putContentTypeDefault(a,l);}for(let[a,l]of e.contentTypes.overrides){let d=E(a);if(d){o=d;return}n.putContentTypeOverride(a,l);}for(let a of r.descriptors)n.putBinary(a);},ot);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var de=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 t=this.touched.get(e);if(t)return t;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,t,r){let o=this.node(e);o&&(o.textLength=Math.max(0,o.textLength-t)+r);}spliceChildren(e,t,r,o){let i=this.node(e);i&&i.children.splice(t,r,...o);}moveNode(e,t,r){let o=this.parentOf(e);if(o!==null){let a=this.node(o),l=a?.children.indexOf(e)??-1;a&&l>=0&&a.children.splice(l,1);}let i=this.node(t);if(!i)return;let s=Math.min(r,i.children.length);i.children.splice(s,0,e);}parentOf(e){for(let[t,r]of this.touched)if(r.children.includes(e))return t;return this.registry.parentOf(e)}};function Vt(n,e){switch(e.kind){case "putNode":n.putNode(e.descriptor);return;case "spliceText":n.spliceText(e.logicalId,e.deleteCount,e.insert.length);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;default:return}}function N(n,e){return m(e)||e.length===0?{ok:false,code:"prototype-key",detail:e}:n.has(e)?null:{ok:false,code:"unknown-logical-id",detail:e}}function fr(n,e,t){if(m(e.logicalId)||e.logicalId.length===0)return {ok:false,code:"invalid-logical-id",detail:e.logicalId};let r=t.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}:L(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function yr(n,e,t){switch(e.kind){case "putNode":return fr(n,e.descriptor,t);case "spliceText":{let r=N(t,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>n.limits.maxTextLength)return {ok:false,code:"text-too-long"};let o=t.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>n.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(t,e.logicalId);return r||(m(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:L(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:e.value!==null&&e.value.length>n.limits.maxStringLength?{ok:false,code:"invalid-string"}:null)}case "setNamespaceBinding":{let r=N(t,e.logicalId);return r||(m(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&L(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=N(t,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>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let i of e.childLogicalIds){let s=N(t,i);if(s)return s}let o=t.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>n.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(t,e.logicalId);if(r)return r;let o=N(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=E(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=N(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=E(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=E(e.owner);if(r)return {ok:false,code:r}}return m(e.record.id)?{ok:false,code:"prototype-key"}:n.relationshipCount()>=n.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=E(e.partName);return r?{ok:false,code:r}:L(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=E(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=Ze(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 br(n,e,t){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?n.hasNode(e.descriptor.logicalId)||n.putText(e.descriptor.logicalId,""):n.hasNode(e.descriptor.logicalId)?n.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):n.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(t.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&n.textOf(e.logicalId).toString()===e.insert)return;n.spliceText(e.logicalId,e.utf16Start,e.deleteCount,e.insert);return;case "setAttribute":n.setAttribute(e.logicalId,e.qname,e.value);return;case "setNamespaceBinding":n.setNamespaceBinding(e.logicalId,e.prefix,e.uri);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;case "putXmlPart":n.putXmlPart({name:e.name,id:e.name,rootLogicalId:e.rootLogicalId,contentType:"application/xml"});return;case "deleteXmlPart":n.deleteXmlPart(e.name);return;case "putRelationship":n.putRelationship({...e.record,ownerPart:e.owner});return;case "deleteRelationship":n.deleteRelationship(e.owner,e.relationshipId);return;case "putContentTypeOverride":n.putContentTypeOverride(e.partName,e.mediaType);return;case "deleteContentTypeOverride":n.deleteContentTypeOverride(e.partName);return;case "putBinary":n.putBinary(e.descriptor);return;case "deleteBinary":n.deleteBinary(e.storageKey);return}}function Ir(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function xr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Ir(n,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(s=>o.has(s)))return i.parentLogicalId}}function vr(n,e){let t=new de(n),r=[],o=new Set,i=new Set;for(let s of e){let a=yr(n,s,t);if(a)return a;if(s.kind==="spliceChildren"){let l=s.deleteCount>0?t.node(s.parentLogicalId):null;if(l&&!l.isText){let d=s.start+s.deleteCount;for(let c=s.start;c<d;c+=1){let g=l.children[c];g!==void 0&&r.push(g);}}for(let d of s.childLogicalIds)o.add(d);}else s.kind==="moveNode"?o.add(s.logicalId):s.kind==="putNode"&&s.descriptor.kind==="textValue"&&i.add(s.descriptor.logicalId);Vt(t,s);}return {removed:r,reinserted:o,mintedText:i}}function Sr(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function Ae(n,e){if(n.nodeCount()+Sr(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=vr(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=wr(n,t.removed);for(let o of e.effects)br(n,o,t.mintedText);Er(n,e.effects,t,r);},it),{ok:true})}function Er(n,e,t,r){if(t.removed.length===0)return;let o=new Set;for(let i of n.partEntries())o.add(i.rootLogicalId);for(let i of t.removed){if(t.reinserted.has(i)||!n.hasNode(i)||n.isTombstoned(i)||o.has(i))continue;let s=xr(n,i,r,e);s&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,s);}}function wr(n,e){let t=new Map;for(let r of e){let o=n.nodeShape(r);o&&!o.isText&&t.set(r,o.children);}return t}var ue="http://schemas.openxmlformats.org/package/2006/relationships",Lr="application/vnd.openxmlformats-package.relationships+xml",$t=/^(.*)\/_rels\/([^/]*)\.rels$/;function Xt(n){return $t.test(n)}function Wt(n){let e=$t.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function J(n,e){return n.attributes.find(t=>t.localName===e)?.value}function ce(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function Cr(n,e){let t=[ce("Id",e.id),ce("Type",e.type),ce("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(ce("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:ue,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function Jt(n,e){if(n.kind==="textValue"||n.namespaceUri!==ue||n.localName!=="Relationship"||J(n,"Id")!==e.id||J(n,"Type")!==e.type||J(n,"Target")!==e.rawTarget)return false;let t=J(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function Gt(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>Jt(t,e[r]))}function Ht(n,e){if(n.id!==e.id||n.kind!==e.kind||n.namespaceUri!==e.namespaceUri||n.localName!==e.localName||n.prefix!==e.prefix||n.attributes.length!==e.attributes.length)return false;for(let t=0;t<n.attributes.length;t+=1){let r=n.attributes[t],o=e.attributes[t];if(r.namespaceUri!==o.namespaceUri||r.localName!==o.localName||r.value!==o.value||r.prefix!==o.prefix)return false}return n.namespaceBindings.length!==e.namespaceBindings.length?false:n.namespaceBindings.every((t,r)=>{let o=e.namespaceBindings[r];return t.prefix===o.prefix&&t.namespaceUri===o.namespaceUri})}function qt(n,e,t){let r=[];for(let o of e){if(m(o.id))continue;let i=n.find(a=>a.kind!=="textValue"&&J(a,"Id")===o.id);if(i&&Jt(i,o)){r.push(i);continue}let s=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;m(s)||r.push(Cr(s,o));}return r}function Rr(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:ue,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:ue})]),attributes:Object.freeze([]),children:Object.freeze([])})}function Zt(n){return Object.freeze({id:n,name:n,contentType:Lr,root:Rr(n)})}function Qt(n){let e=new Map;for(let t of n){if(m(t.id)||t.ownerPart!=="/"&&E(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var rn=/^\/customXml\/item(\d+)\.xml$/i,Or=/^\/customXml\/itemProps(\d+)\.xml$/i;function H(n){return rn.test(n)}function Ne(n){return Or.test(n)}function Nr(n){let e=rn.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function en(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function Mr(n,e,t){let r=n.attributes.find(o=>o.localName===e&&o.namespaceUri===t);return r&&r.value.length>0?r.value:null}function tn(n,e){let t=n.record(e);return !t||!x(t)?e:t.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function Tr(n,e){let t=n.record(e);if(!t||!x(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!x(o)||o.localName!=="schemaRefs")&&o.namespaceUri===DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let s=n.record(i);if(!s||!x(s)||s.localName!=="schemaRef")continue;let a=Mr(s,"uri",DATASTORE_NAMESPACE_URI);if(a)return a}}return null}function Dr(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&x(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Br(n,e){return e.localName==="node"||e.namespaceUri===WML_NAMESPACE_URI||e.namespaceUri===DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||n.parentOf(e.logicalId)!==null?false:Dr(n,e)}function _r(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function on(n,e){if(!n.hasNamespace(DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[u,p]of e){let f=n.record(p.root.id);!f||!x(f)||(H(u)&&t.set(f.logicalId,f),Ne(u)&&r.set(f.logicalId,f));}for(let u of n.allLogicalIds()){if(n.isTombstoned(u)||t.has(u)||r.has(u))continue;let p=n.record(u);!p||!x(p)||(Br(n,p)?t.set(u,p):_r(n,p)&&r.set(u,p));}if(t.size===0)return [];let o=new Map;for(let u of t.values()){let p=o.get(u.namespaceUri)??[];p.push(u),o.set(u.namespaceUri,p);}let i=new Map;for(let u of r.values()){let p=Tr(n,u.logicalId);if(!p)continue;let f=i.get(p)??[];f.push(u),i.set(p,f);}let s=[];for(let[u,p]of o){let f=i.get(u);if(!f||f.length===0)continue;p.sort((I,S)=>I.logicalId.localeCompare(S.logicalId)),f.sort((I,S)=>I.logicalId.localeCompare(S.logicalId));let y=p[0],M=f[0],k=[],b=new Set;for(let I of p)for(let S of I.childIds){if(b.has(S))continue;let te=n.record(S);!te||!x(te)||te.localName!=="node"||te.namespaceUri!==u||(b.add(S),k.push(S));}for(let I of n.allLogicalIds()){if(b.has(I)||n.isTombstoned(I))continue;let S=n.record(I);!S||!x(S)||S.localName!=="node"||S.namespaceUri!==u||(b.add(I),k.push(I));}k.sort((I,S)=>tn(n,I).localeCompare(tn(n,S))),s.push({data:y,props:M,nodeIds:k});}s.sort((u,p)=>u.data.logicalId.localeCompare(p.data.logicalId));let a=new Set,l=[],d=new Set,c=new Set;for(let[u,p]of e){let f=Nr(u);if(f===null)continue;let y=s.find(b=>b.data.logicalId===p.root.id&&!d.has(b.data.logicalId));if(!y)continue;let M=en(f).props,k=e.get(M);k&&k.root.id!==y.props.logicalId||(a.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:M,nodeIds:y.nodeIds}));}let g=1;for(let u of s){if(d.has(u.data.logicalId))continue;for(;a.has(g);)g+=1;a.add(g);let p=en(g);l.push({dataRootId:u.data.logicalId,propsRootId:u.props.logicalId,namespaceUri:u.data.namespaceUri,itemName:p.item,propsName:p.props,nodeIds:u.nodeIds}),g+=1;}return l.sort((u,p)=>u.itemName.localeCompare(p.itemName)),l}function Ur(n){return n.type===CUSTOM_XML_REL||n.type===CUSTOM_XML_PROPS_REL?true:H(n.ownerPart)}function zr(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function Yr(n,e){let t=n.split("/").slice(1,-1),r=e.split("/").slice(1),o=0;for(;o<t.length&&o<r.length-1&&t[o]===r[o];)o+=1;return `${"../".repeat(t.length-o)}${r.slice(o).join("/")}`}function an(n,e){if(e.length===0)return [];let t=n.mainDocumentPart();if(!t)return [];let r=n.relationships(),o=r.filter(a=>a.ownerPart===t&&a.type===CUSTOM_XML_REL).sort((a,l)=>a.id.localeCompare(l.id)),i=0;for(let a of r)i=Math.max(i,zr(a.id));let s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=o[a],c=d?.id??`rId${String(i+=1)}`;s.push({ownerPart:t,id:c,type:CUSTOM_XML_REL,rawTarget:Yr(t,l.itemName),targetMode:"Internal",order:d?.order??a}),s.push({ownerPart:l.itemName,id:"rId1",type:CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return s}function sn(n,e){return e.length===0?[...n]:[...n.filter(t=>!Ur(t)),...e]}function ln(n){let e=new Map;for(let t of n)e.set(partNameKey(t.propsName),CUSTOM_XML_PROPS_TYPE);return e}function Me(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(H).sort(),r=e.map(o=>o.itemName).sort();if(t.length!==r.length||t.some((o,i)=>o!==r[i]))return true;for(let o of e){let i=n.get(o.itemName),s=n.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!s||s.root.id!==o.propsRootId)return true}return false}function dn(n,e){if(Me(n,e))return true;for(let t of e){let r=n.get(t.itemName);if(!r)return true;let o=new Set(r.root.children.map(a=>a.id));if(t.nodeIds.some(a=>!o.has(a)))return true;let i=[];for(let a of r.root.children)a.kind!=="textValue"&&i.push(a.attributes.find(l=>l.localName==="id")?.value??a.id);let s=[...i].sort((a,l)=>a.localeCompare(l));if(i.some((a,l)=>a!==s[l]))return true}return false}var jr="http://schemas.microsoft.com/office/word/2012/wordml";function pe(n,e){return n.attributes.find(t=>t.localName===e)?.value}function he(n){let e=Number(n);return n===void 0||n.length===0||!Number.isSafeInteger(e)?`2${n??""}`:`${e<0?"0":"1"}${String(Math.abs(e)).padStart(12,"0")}`}function cn(n){return e=>e.localName===n&&e.namespaceUri===WML_NAMESPACE_URI}function Kr(n){return n.localName==="abstractNum"?`0${he(pe(n,"abstractNumId"))}`:`1${he(pe(n,"numId"))}`}function Fr(n){return n.namespaceUri!==WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function un(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===jr,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:cn("footnote"),sortKey:e=>he(pe(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:cn("endnote"),sortKey:e=>he(pe(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:Fr,sortKey:Kr}:null}function Vr(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Te(n){return n.kind==="textValue"?n.id:Vr(n,"id")??n.id}function j(n,e){if(n.length===e.length&&n.every((s,a)=>s===e[a]))return n;let t=0,r=Math.min(n.length,e.length);for(;t<r&&n[t]===e[t];)t+=1;let o=n.length,i=e.length;for(;o>t&&i>t&&n[o-1]===e[i-1];)o-=1,i-=1;return Object.freeze([...n.slice(0,t),...e.slice(t,i),...n.slice(o)])}function mn(n,e){let t=n.root;if(t.children.length===e.length&&t.children.every((o,i)=>o===e[i]))return n;let r=Object.freeze({...t,children:j(t.children,e)});return Object.freeze({...n,root:r})}function $r(n){if(n.namespaceUri===XML_NAMESPACE_URI&&n.localName==="space"){let e=n.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return n.namespaceUri===WML_NAMESPACE_URI&&n.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:WML_NAMESPACE_URI,localName:"val",prefix:n.prefix,value:n.value}):Object.freeze({kind:"genericExtension",namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,value:n.value})}function yn(n){}function In(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function qr(n,e){return n.namespaceBindings.length!==e.bindings.length?false:n.namespaceBindings.every((t,r)=>{let o=e.bindings[r];return t.prefix===o.prefix&&t.namespaceUri===o.namespaceUri})}function Zr(n,e){return n.attributes.length!==e.attributes.length?false:n.attributes.every((t,r)=>{let o=e.attributes[r];return t.namespaceUri===o.namespaceUri&&t.localName===o.localName&&t.value===o.value&&t.prefix===(o.prefix?.length?o.prefix:void 0)})}function me(n,e,t){let r=t&&t.kind!=="textValue"?t:void 0;return Object.freeze({id:n.logicalId,kind:n.kind,namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,namespaceBindings:r&&qr(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&Zr(r,n)?r.attributes:Object.freeze(n.attributes.map($r)),children:e})}function xn(n,e){if(n.attributes.length!==e.attributes.length)return false;let t=new Map(e.attributes.map(r=>[`${r.namespaceUri}
|
|
2
|
+
${r.localName}`,r.value]));for(let r of n.attributes)if(t.get(`${r.namespaceUri}
|
|
3
|
+
${r.localName}`)!==r.value)return false;return n.localName===e.localName&&n.kind===e.kind}function De(n,e){let t=e.size;e.add(n.id);let r=e.size!==t;if(n.kind==="textValue")return r;for(let o of n.children)De(o,e)||(r=false);return r}function vn(n,e){let t=new Set(e);for(let r of e){let o=n.parentOf(r);for(;o&&!t.has(o);)t.add(o),o=n.parentOf(o);}return t}var ge=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:sn(this.decoded,e)}),this.merged.records}groupedByOwner(e){let t=this.projected(e);return (!this.grouped||this.grouped.records!==t)&&(this.grouped={records:t,map:Qt(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:to(t)}),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 t=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){t.set(o.storageKey,i.bytes);continue}let s=e.get(o.digest);if(!s)return null;yn(s.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:s}),t.set(o.storageKey,s);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=t,t}};function to(n){let e=buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}function oo(n){let e=new Set,t=[];for(let r of n){let o=`${r.code}${r.logicalId??""}`;e.has(o)||(e.add(o),t.push(r));}return t}var K=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new ge(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=[],t=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");t.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())t.has(r)||e.push(r);return this.lastAdoption=t,e}rebuild(){let e=new Set(this.pendingDirty),t=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(t||r)&&this.packageCache.invalidate();for(let c of this.adoptionChanges())e.add(c);let o=vn(this.registry,e),i=new Set(this.registry.partEntries().map(c=>c.rootLogicalId)),s=[...e].some(c=>i.has(c)||this.registry.parentOf(c)===null&&!this.registry.isTombstoned(c)),a=this.pkg!==null&&!r&&!s&&(o.size>0||t),l=this.materializePass(o,t,a);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:oo(l.issues)};let d=this.materializePass(o,t,false);return this.recordContestResolution(),d}contestUnchanged(){for(let e of this.contestEncountered){let t=this.lastContestResolution.get(e);if(t===void 0||t!==this.registry.parentOf(e))return false}return true}recordContestResolution(){let e=new Map;for(let t of this.contestEncountered)e.set(t,this.registry.parentOf(t));for(let t of this.lastDuplicateParents)e.set(t,this.registry.parentOf(t));this.lastContestResolution=e;}materializePass(e,t,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,g=this.materialize(d.rootLogicalId,o,c,r);if(!g||g.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let u=this.partCache.get(d.name);if(u&&u.root===g&&u.contentType===d.contentType){i.set(d.name,u);continue}let p=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:g});i.set(d.name,p),this.partCache.set(d.name,p);}let s=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),a=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,s,a),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(s,o,r,a),this.looseCandidates=a,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&&!t&&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,t){this.issues.push(t?{code:e,logicalId:t}:{code:e});}stillListed(e){for(let t of this.registry.listingParents(e)){let r=this.registry.record(t);if(r&&x(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,t,r,o){if(!r){for(let a of e)this.registry.isTombstoned(a)||t.has(a)||(this.pushOrphan(a),o.add(a));return}let i=new Set(this.registry.partEntries().map(a=>a.rootLogicalId)),s=new Set;for(let a of e)s.has(a)||(s.add(a),this.reportOrphansUnder(a,t,i)&&o.add(a));}reportOrphansUnder(e,t,r){let o=false,i=new Set,s=[{id:e,underTombstone:false}];for(;s.length>0;){let{id:a,underTombstone:l}=s.pop();if(!(i.has(a)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(a),this.registry.isTombstoned(a)){let d=this.registry.record(a);if(d&&x(d))for(let c of d.childIds)s.push({id:c,underTombstone:true});continue}r.has(a)||(l?t.has(a):this.stillListed(a))||(this.pushOrphan(a),o=true);}}return o}pushOrphan(e){let t=this.registry.record(e),r=!!t&&(re(t)?t.value.length>0:t.childIds.length>0||t.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,t,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(t.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?De(u,t)||(this.placementContested=true):t.add(u.id),u}if(this.registry.isTombstoned(e))return null;t.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(re(i)){let u=this.cache.get(e);if(u?.kind==="textValue"&&u.value===i.value)return u;let p=In(e,i.value);return this.remember(e,p),p}r.add(e);let s=new Set,a=[...i.childIds];for(let u of this.registry.adoptedChildren(e))a.includes(u)||a.push(u);let l=[];for(let u of a){if(u===e){this.push("self-child",u);continue}if(s.has(u)){this.push("duplicate-child",u);continue}if(s.add(u),this.registry.isTombstoned(u)){this.push("deleted-referenced",u);continue}if(m(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:!t.has(u)&&this.registry.parentOf(u)!==e&&(this.contestMatchesResolution=false));}let p=this.materialize(u,t,r,o);p&&l.push(p);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((u,p)=>u===l[p])&&xn(d,i))return d;let c=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(c,l);let g=me(i,j(c,l),d);return this.remember(e,g),g}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){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)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;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 t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let s=relsPartNameFor(o);if(s!=="/_rels/.rels"&&E(s))continue;r.add(s);let a=this.projectOneRelsPart(s,e.get(s),i);a&&(e.set(s,a),this.partCache.set(s,a));}for(let[o,i]of e){if(r.has(o)||!Xt(o))continue;let s=Wt(o);if(s===null)continue;let a=this.projectOneRelsPart(o,i,t.get(s)??[]);!a||a===i||(e.set(o,a),this.partCache.set(o,a));}}projectOneRelsPart(e,t,r){if(!t&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),s=!!o&&(!t||Ht(o.root,t.root))&&o?o:t??Zt(e);if(Gt(s.root,r))return this.relsProjection.set(e,s),s;let a=s.root.children,l=mn(s,qt(a,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[s,a]of e){let l=un(a.root);if(!l)continue;let d=b=>b.logicalId!==a.root.id&&l.isMember(b),c=[],g=new Set;for(let b of a.root.children){if(b.kind==="textValue")continue;let I=this.registry.record(b.id);!I||!x(I)||!d(I)||(c.push(b),g.add(b.id));}if(this.adoptLooseMembers(c,g,d,t,r,o,i)===0)continue;c.sort((b,I)=>l.sortKey(b).localeCompare(l.sortKey(I)));let p=[];for(let b of a.root.children)g.has(b.id)||p.push(b);let f=j(a.root.children,[...p,...c]);if(f===a.root.children)continue;let y=this.registry.record(a.root.id);if(!y||!x(y))continue;let M=me(y,f,a.root);this.remember(a.root.id,M);let k=Object.freeze({...a,root:M});e.set(s,k),this.partCache.set(s,k);}}adoptLooseMembers(e,t,r,o,i,s,a){let l=0;for(let d of s){if(o.has(d)||t.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let c=this.registry.record(d);if(!c||!x(c)||!r(c))continue;let g=this.materialize(d,o,new Set,i);!g||g.kind==="textValue"||(e.push(g),t.add(d),a.add(d),l+=1);}return l}materializeOnce(e,t,r){return t.has(e)?this.cache.get(e)??null:this.materialize(e,t,new Set,r)}adoptNodesIntoRoot(e,t,r,o){let i=this.cache.get(e),s=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!s||s.kind==="textValue")return null;let a=[...s.children],l=new Set(a.map(p=>p.id)),d=0;for(let p of t){if(l.has(p))continue;let f=this.materializeOnce(p,r,o);!f||f.kind==="textValue"||(a.push(f),l.add(p),d+=1);}if(a.sort((p,f)=>Te(p).localeCompare(Te(f))),d===0&&a.every((p,f)=>p===s.children[f]))return s;let c=this.registry.record(e);if(!c||!x(c))return s;let g=j(s.children,a),u=me(c,g,s);return this.remember(e,u),u}applyCustomXmlStores(e,t,r){let o=on(this.registry,e);if(o.length===0||!dn(e,o))return;let i=Me(e,o),s=new Set;for(let a of o){s.add(a.itemName),s.add(a.propsName);let l=this.adoptNodesIntoRoot(a.dataRootId,a.nodeIds,t,r),d=this.materializeOnce(a.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let c=Object.freeze({id:a.itemName,name:a.itemName,contentType:"application/xml",root:l}),g=Object.freeze({id:a.propsName,name:a.propsName,contentType:CUSTOM_XML_PROPS_TYPE,root:d});e.set(a.itemName,c),e.set(a.propsName,g),this.partCache.set(a.itemName,c),this.partCache.set(a.propsName,g);}if(i){for(let a of [...e.keys()])!H(a)&&!Ne(a)||s.has(a)||(e.delete(a),this.partCache.delete(a));this.customXmlRels=an(this.registry,o),this.customXmlOverrides=ln(o),this.projectRelsParts(e);}}assemblePackage(e){let t=this.packageCache.relationshipAssembly(this.customXmlRels);if(!t)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[a,l]of this.customXmlOverrides)o.set(a,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},s=this.registry.mainDocumentPart()||[...e.keys()].find(a=>a.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:t.byOwner,externalTargets:t.externalTargets,contentTypes:i,mainDocumentPart:s}),issues:[...this.issues]}}};var En=1,wn=1,_e=20*1024*1024,uo="docx-collaboration-v1",po="docx-body-paragraphs-v1",ho=Object.freeze({kind:"docx-collaboration-bootstrap"}),h=class extends Error{constructor(t,r){super(r?`${t}: ${r}`:t);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function ze(n){return {root:n.getMap(uo),paragraphs:n.getMap(po)}}function mo(n,e){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>_e)throw new h("baseline-too-large");let t=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:_e,maxRatio:200}});if(!t.ok)throw new h("invalid-baseline");let r=t.package.parts.get(t.package.mainDocumentPart);if(!r)throw new h("no-main-document-part");let o=normalizeParagraphIdentity(r),i=new TreePackageStore(t.package,o),s=createCollaborationDocumentPort(i,{documentId:e});return {bytes:writeOoxmlPackage(i.currentPackage()),paragraphs:s.paragraphs()}}async function Ln(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return [...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function Sn(n,e){let t=n.get(e);if(typeof t!="string"||t.length===0||t.length>256)throw new h("invalid-shared-metadata",e);return t}function Be(n,e){let t=n.get(e);if(!Number.isSafeInteger(t)||t<0)throw new h("invalid-shared-metadata",e);return t}function Z(n){return n.get("initialized")===true}async function aa(n,e,t,r){let{root:o,paragraphs:i}=ze(n);if(Z(o))throw new h("already-initialized");let s=await Ln(r.bytes);n.transact(()=>{if(Z(o))throw new h("already-initialized");o.set("protocolVersion",En),o.set("schemaVersion",wn),o.set("documentId",e),o.set("baselineSha256",s),o.set("baselineByteLength",r.bytes.byteLength),o.set("initializedBy",t),o.set("baseline",new Uint8Array(r.bytes));for(let a of r.paragraphs){if(i.has(a.paragraphId))throw new h("duplicate-paragraph-id");let l=new w.Text;i.set(a.paragraphId,l),l.insert(0,a.text);}o.set("initialized",true);},ho);}async function sa(n,e){let{root:t,paragraphs:r}=ze(n);if(!Z(t))throw new h("not-initialized");if(Be(t,"protocolVersion")!==En)throw new h("protocol-version-mismatch");if(Be(t,"schemaVersion")!==wn)throw new h("schema-version-mismatch");if(Sn(t,"documentId")!==e)throw new h("document-id-mismatch");let o=Be(t,"baselineByteLength");if(o===0||o>_e)throw new h("baseline-too-large");let i=t.get("baseline");if(!(i instanceof Uint8Array)||i.byteLength!==o)throw new h("invalid-baseline");if(await Ln(i)!==Sn(t,"baselineSha256"))throw new h("baseline-digest-mismatch");let s=mo(new Uint8Array(i),e),a=new Set(s.paragraphs.map(l=>l.paragraphId));if(r.size!==a.size)throw new h("paragraph-set-mismatch");for(let[l,d]of r)if(!a.has(l)||!(d instanceof w.Text))throw new h("paragraph-set-mismatch");return s}function la(n,e,t){let{root:r}=ze(n);return Z(r)?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((o,i)=>{let s=c=>{clearTimeout(d),r.unobserve(a),t?.removeEventListener("abort",l),c?i(c):o();},a=()=>{Z(r)&&s();},l=()=>s(new h("initialization-aborted")),d=setTimeout(()=>s(new h("initialization-timeout")),e);r.observe(a),t?.addEventListener("abort",l,{once:true});})}var Rn=64*1024*1024;function fo(n){if(n instanceof Uint8Array)return new Uint8Array(n);if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n)){let e=n;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}return null}function yo(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function fe(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var Q=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=fo(t);return !r||typeof t!="object"||t===null?null:this.verify(e,t,r)?r:null}has(e){let t=this.shared.get(e);return t===void 0?false:this.verified.has(t)?true:this.get(e)!==null}poisonedDigest(){for(let e of this.poisoned)return e;return null}observeChanges(e){let t=r=>{e([...r.keysChanged]);};return this.shared.observe(t),()=>this.shared.unobserve(t)}verifyNow(e){for(let t of e)if(this.shared.has(t)&&this.get(t)===null)return t;return null}totalByteLength(){let e=0;return this.shared.forEach(t=>{e+=yo(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Rn)throw new h("blob-store-full");this.shared.set(e,new Uint8Array(t));}}verify(e,t,r){return this.verified.has(t)?true:this.poisoned.has(e)?false:sha256FontBytes(r)!==e?(this.poisoned.add(e),false):(this.verified.add(t),true)}};function ye(n,e){let{limits:t}=n,r=n.nodeCount();if(r>t.maxNodes)return fe("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return fe("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(a=>{i+=a instanceof w.Map?a.size:0;}),i>t.maxRelationships)return fe("too-many-relationships",`${i}`);let s=e.totalByteLength();return s>Rn?fe("blob-store-full",`${s}`):null}var kn=20*1024*1024,je=3e4,vo=4e3,So=1500,Eo="docx-collaboration-seeds-v1",Ye="docxEditorSeedCandidate",wo=/^[0-9a-f]{16}$/,Lo=256;function Ke(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>kn)throw new h("baseline-too-large");let e=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:kn,maxRatio:200}});if(!e.ok)throw new h("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new h("no-main-document-part");return new TreePackageStore(e.package,normalizeParagraphIdentity(t)).currentPackage()}function Co(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function ee(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&Co(n,e),s=()=>{let l=e.poisonedDigest();return l?new h("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let a=s();return a?Promise.reject(a):r?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((l,d)=>{let c=f=>{clearTimeout(p),o.unobserve(g),n.doc.off("afterTransaction",g),r?.removeEventListener("abort",u),f?d(f):l();},g=()=>{let f=s();if(f){c(f);return}i()&&c();},u=()=>c(new h("initialization-aborted")),p=setTimeout(()=>c(new h("initialization-timeout")),t);o.observe(g),n.doc.on("afterTransaction",g),r?.addEventListener("abort",u,{once:true});})}function Fe(n){return n.getArray(Eo)}function Ve(n){return Fe(n).length}function An(n,e){let t=Fe(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Ro(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function ko(n,e){let t=[...n.getStates().entries()].slice(0,Lo);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[Ye];if(!(typeof i!="string"||!wo.test(i))&&i<e)return true}return false}async function Pn(n,e,t,r){try{return await ee(n,e,t,r),!0}catch(o){if(o instanceof h&&o.code==="initialization-timeout")return false;throw o}}function Po(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((i,s)=>{let a=g=>{clearTimeout(c),r.unobserve(l),t?.removeEventListener("abort",d),g?s(g):i();},l=()=>{o()&&a();},d=()=>a(new h("initialization-aborted")),c=setTimeout(()=>a(new h("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function On(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??vo,s=n.electionWindowMs??So,a=n.timeoutMs??je,l=async()=>(await Po(r,a,n.signal),"joined");if(await Pn(r,o,i,n.signal))return l();let d=Ro();t.setLocalStateField(Ye,d);try{let c=await Pn(r,o,s,n.signal);if(!c&&ko(t,d)&&(await ee(r,o,a,n.signal),c=!0),c)return await l();if(r.schema.meta.get("initialized")===!0)return await ee(r,o,a,n.signal),await l();let g=await W(r,Ke(n.document),o);if(!g.ok)throw new h(g.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),Fe(e).push([d]);}),"seeded"}finally{t.setLocalStateField(Ye,null);}}var be=class{constructor(e,t){this.knows=e;this.allocator=new F(t);}knows;allocator;toLogical=new Map;get replicaId(){return this.allocator.replicaId}reset(){this.toLogical.clear();}mint(e){let t=this.allocator.take();return this.toLogical.set(e,t),t}resolve(e){return this.toLogical.get(e)??e}translate(e){let t=[],r=false;for(let o of e.effects){let i=this.translateEffect(o);i!==o&&(r=true),t.push(i);}return r?Object.freeze({effects:Object.freeze(t)}):e}translateEffect(e){switch(e.kind){case "putNode":{let t=this.translateDescriptor(e.descriptor);return t.logicalId===e.descriptor.logicalId?e:{...e,descriptor:t}}case "spliceText":case "setAttribute":case "setNamespaceBinding":{let t=this.resolve(e.logicalId);return t===e.logicalId?e:{...e,logicalId:t}}case "spliceChildren":{let t=this.resolve(e.parentLogicalId),r=e.childLogicalIds.map(i=>this.resolve(i));return t===e.parentLogicalId&&r.every((i,s)=>i===e.childLogicalIds[s])?e:{...e,parentLogicalId:t,childLogicalIds:r}}case "moveNode":{let t=this.resolve(e.logicalId),r=this.resolve(e.destinationParentLogicalId);return t===e.logicalId&&r===e.destinationParentLogicalId?e:{...e,logicalId:t,destinationParentLogicalId:r}}case "putXmlPart":{let t=this.resolve(e.rootLogicalId);return t===e.rootLogicalId?e:{...e,rootLogicalId:t}}default:return e}}translateDescriptor(e){let t=this.resolve(e.logicalId);return this.knows(t)?{...e,logicalId:t}:{...e,logicalId:this.mint(e.logicalId)}}};var $e="docxEditor",Un="docx-package-blobs-v1",D=256,Nn=256,No=3,Mo=5e3,To=2e3,Do=Symbol("createDocumentCollaboration.attachWatchdogMs");function Bo(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>D||t.length===0||t.length>D)throw new h("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new h("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function _o(n){let e=n.trim();if(e.length===0||e.length>D)throw new h("invalid-document-id");return e}function Uo(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>D)throw new h("invalid-session-id");return e}function Mn(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;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 zo(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=Mn(e.anchor),r=Mn(e.head);if(t&&r)return e.kind==="cells"?{anchor:t,head:r,kind:"cells"}:{anchor:t,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 Tn(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;if(typeof e.actorId!="string"||e.actorId.length===0||e.actorId.length>D||typeof e.name!="string"||e.name.length===0||e.name.length>D)return null;let t=safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...t?{color:t}:{},role:r},i=zo(e.selection);return i?{...o,selection:i}:o}var Xe=class{constructor(e,t,r,o,i,s,a,l,d,c,g){this.ydoc=e;this.awareness=t;this.registry=s;this.materializer=a;this.identityMap=l;this.blobs=d;this.offlineEditing=g;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new w.UndoManager([...s.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:Mo,deleteFilter:s.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(u=>{let p=d.verifyNow(u);p&&this.setStatus("error","blob-digest-mismatch",p);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=An(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=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;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()}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,t,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(t!==void 0){this.setStatus(e,t,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let t=this.refuseAttach(e);if(t)return t;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{this.destroyed||this.applyingRemote||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}gateOperations(e,t){if(this.destroyed)return "collaboration-session-destroyed";let r=this.statusState.status();return r!=="ready"&&!(this.offlineEditing&&r==="disconnected")?"collaboration-session-not-ready":this.port?null:"collaboration-session-not-attached"}canUndo(){return !this.destroyed&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return !this.destroyed&&this.undoManager.redoStack.length>0}undo(){return this.destroyed||(this.flushPendingJournals(),this.undoManager.undoStack.length===0)?false:(this.undoManager.undo(),true)}redo(){return this.destroyed||(this.flushPendingJournals(),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=[],t=[...this.awareness.getStates().entries()].slice(0,Nn);for(let[r,o]of t){let i=Tn(o[$e]);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 t=i=>{let s=e.paragraphByStableId(i.paragraphId);return s?Object.freeze({paragraphId:s.paragraphId,nodeId:s.nodeId,offset:Math.min(i.offset,s.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,Nn),o=[];for(let[i,s]of r){if(i===this.awareness.clientID)continue;let a=Tn(s[$e]);if(!a?.selection)continue;let l=t(a.selection.anchor),d=t(a.selection.head);!l||!d||o.push(Object.freeze({actorId:a.actorId,name:a.name,...a.color?{color:a.color}:{},...a.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 t=e.name===void 0?this.currentIdentity.name:e.name.trim();if(t.length===0||t.length>D)throw new h("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new h("invalid-identity-color");r=safeParticipantColor(e.color);}this.currentIdentity=Object.freeze({actorId:this.currentIdentity.actorId,name:t,...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.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}applyJournal(e){let t=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 s=this.putJournalBlobs(r.payloads);if(s!==null)return s}let i=Ae(this.registry,t);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 t=this.port;if(!t)return e.effects.some(i=>i.kind==="putBinary")?{ok:false,failure:Object.freeze({code:"collaboration-session-not-attached"})}:null;let r=jt(e.effects,Yt(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{Kt(this.blobs,e);}catch(t){return t instanceof h?Object.freeze({code:t.code,...t.detail?{detail:t.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){this.undoManager.stopCapturing(),this.refusedInARow+=1,this.setStatus("error",e.code,e.detail),this.publishSharedToPort(),this.realignedInBatch=true,queueMicrotask(()=>{this.realignedInBatch=false;});let t=this.statusState.snapshot().reason;this.refusedInARow<No&&this.statusState.status()==="error"&&t!==void 0&&t.code===e.code&&t.detail===e.detail&&this.setStatus("ready");}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 t=ye(this.registry,this.blobs);if(t){this.setStatus("error",t.code,t.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=at(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let s=e.applyRemotePackage(r.package,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!s.ok){this.setStatus("error","remote-apply-failed",s.reason);return}s.changed&&this.identityMap.reset();}catch(t){this.setStatus("error",t instanceof h?t.code:"remote-apply-failed",t instanceof h?t.detail:void 0);}finally{this.applyingRemote=false;}}}onAwarenessChange=()=>{if(this.destroyed)return;let e=this.remoteSelections();for(let r of [...this.selectionListeners])r(e);let t=this.participants();for(let r of [...this.participantListeners])r(t);};publishAwareness(e){this.currentSelection=e;let t={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($e,t);}setStatus(e,t,r){if(!this.statusState.set(e,t,r))return;let o=this.statusState.snapshot();for(let i of [...this.statusListeners])i(o.status,o.reason?.code,o.reason?.detail);}};function ka(n){let e=new Y(n);if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new h("not-initialized");if(Ve(n)>1)throw new h("concurrent-seed");let t=new Q(n.getMap(Un)),r=ye(e,t);if(r)throw new h(r.code,r.detail);let o=new K(e,t);try{let i=o.current(),s=t.poisonedDigest();if(s)throw new h("blob-digest-mismatch",s);if(!i.ok)throw new h(i.code);return writeOoxmlPackage(i.package)}finally{o.destroy();}}async function Pa(n){let e=n[Do]??To,t=_o(n.documentId),r=Uo(n.sessionId),o=Bo(n.identity),i=new Y(n.ydoc),s=new be(p=>i.hasNode(p)),a=new Q(n.ydoc.getMap(Un));if(n.bootstrap.kind==="create"){if(i.schema.meta.get("initialized")===true)throw new h("already-initialized");let p=await W(i,Ke(n.bootstrap.document),a);if(!p.ok)throw new h(p.code);n.ydoc.transact(()=>{i.schema.meta.set("documentId",t);});}else if(n.bootstrap.kind==="create-or-join"){if(await On({ydoc:n.ydoc,awareness:n.awareness,registry:i,blobs:a,documentId:t,document:n.bootstrap.document,probeTimeoutMs:n.bootstrap.probeTimeoutMs,electionWindowMs:n.bootstrap.electionWindowMs,timeoutMs:n.bootstrap.timeoutMs,signal:n.bootstrap.signal})==="joined"){if(i.schema.meta.get("documentId")!==t)throw new h("document-id-mismatch");i.rebuildDerivedIndexes();}}else {if(await ee(i,a,n.bootstrap.timeoutMs??je,n.bootstrap.signal),i.schema.meta.get("documentId")!==t)throw new h("document-id-mismatch");i.rebuildDerivedIndexes();}if(Ve(n.ydoc)>1)throw new h("concurrent-seed");let l=ye(i,a);if(l)throw new h(l.code,l.detail);let d=new K(i,a),c=d.current(),g=a.poisonedDigest();if(g)throw d.destroy(),new h("blob-digest-mismatch",g);if(!c.ok)throw d.destroy(),new h(c.code);let u=new Xe(n.ydoc,n.awareness,t,r,o,i,d,s,a,e,n.offlineEditing===true);return Object.freeze({document:writeOoxmlPackage(c.package),session:u,destroy:()=>u.destroy()})}export{En as a,wn as b,_e as c,h as d,ze as e,mo as f,aa as g,sa as h,la as i,Do as j,ka as k,Pa as l};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var w=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 w__namespace=/*#__PURE__*/_interopNamespace(w);var zn=new Set(["paraId","textId","id","numId","bookmarkId"]);function We(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function Je(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),We(e)}function Ie(n){return /^[0-9a-f]{32}$/.test(n)}function Ge(n,e){if(!Ie(n))throw new Error("invalid replica identity");if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid logical-id counter");return `lid:${n}:${e.toString(10)}`}function xe(n,e){return `yjs:${n}:${e}`}function ve(n){let e=[];for(let t of n)zn.has(t.localName)&&e.push(t.value);return e}var F=class{replicaId;next=0;constructor(e){if(this.replicaId=e??Je(),!Ie(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}),jn=/^sha256:[0-9a-f]{64}$/;function qe(n){return n?Object.freeze({...A,...n}):A}function m(n){return store.isDangerousKey(n)?"prototype-key":null}function L(n,e){return typeof n!="string"||n.length>e?"invalid-string":store.isDangerousKey(n)?"prototype-key":null}function E(n){let e=m(n);if(e)return e;if(typeof n!="string"||n.length===0)return "unsafe-part-name";let t=store.normalizePartName(n);return !t.ok||t.partName!==n?"unsafe-part-name":null}function Ze(n){for(let e of Object.keys(n)){let t=m(e);if(t)return t}return !jn.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>A.maxBlobBytes?"blob-too-large":L(n.mediaType,A.maxMediaTypeLength)||n.mediaType.length===0||L(n.storageKey,A.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var Qe=1,et=2,tt=1,nt=1,Kn="docx-package-meta-v1",Fn="docx-package-nodes-v1",Vn="docx-package-parts-v1",$n="docx-package-rels-v1",Xn="docx-package-overrides-v1",Wn="docx-package-defaults-v1",Jn="docx-package-binaries-v1",Gn="docx-package-namespaces-v1",Hn="docx-package-attributes-v1",qn="docx-package-bindings-v1",B="s",T="t",ne="children",P="deleted",_="replacedBy",v="",rt="-",ot=Object.freeze({kind:"docx-package-bootstrap"}),it=Object.freeze({kind:"docx-package-journal"});function re(n){return n.kind==="textValue"}function x(n){return !re(n)}var Zn=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),Qn=200;function at(n){let e=new Map;for(let t of n)Zn.has(t.code)&&e.set(t.code,(e.get(t.code)??0)+1);return e.size===0?null:[...e].sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${t}=${r}`).join(",").slice(0,Qn)}function st(n){return {meta:n.getMap(Kn),nodes:n.getMap(Fn),parts:n.getMap(Vn),relationships:n.getMap($n),overrides:n.getMap(Xn),defaults:n.getMap(Wn),binaries:n.getMap(Jn),namespaces:n.getMap(Gn),attributes:n.getMap(Hn),bindings:n.getMap(qn)}}var lt=[["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"]],er=new Map(lt),tr=new Map(lt.map(([n,e])=>[e,n]));function nr(n){let e=0xcbf29ce484222325n,t=0x100000001b3n;for(let r=0;r<n.length;r+=1)e^=BigInt(n.charCodeAt(r)),e=e*t&0xffffffffffffffffn;return e.toString(16).padStart(16,"0")}function V(n){return n.length===0?rt:er.get(n)??`n${nr(n)}`}function U(n,e,t){let r=V(e);return e.length===0||m(r)||L(e,t)||n.get(r)!==e&&n.set(r,e),r}function $(n,e){if(e===rt||m(e))return "";let t=n.get(e);return typeof t=="string"?t:tr.get(e)??""}function Se(n,e,t,r){return `${n}${v}${e}${v}${t}${v}${r}`}function oe(n){let e=n.split(v);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function Ee(n,e,t){return `${n}${v}${e}${v}${t}`}function ie(n){let e=n.split(v);if(e.length!==3)return null;let t=e[0],r=e[1],o=e[2];return t.length===0||o.length===0?null:{logicalId:t,namespaceId:r,localName:o}}function we(n,e){return `${n}${v}${e}`}function ae(n){let e=n.split(v);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function dt(n,e){return `${n}${v}${e}`}function ct(n){let e=n.indexOf(v);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function ut(n){let e=new w__namespace.Map;e.set(B,Se(n.kind,n.namespaceId,n.localName,n.prefix??""));let t=new w__namespace.Array;return n.childIds&&n.childIds.length>0&&t.push([...n.childIds]),e.set(ne,t),e}function pt(n){let e=new w__namespace.Map;return e.set(T,new w__namespace.Text(n)),e}function ht(n,e,t){let r=new w__namespace.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function mt(n){let e=new w__namespace.Map;return e.set("ownerPart",n.ownerPart),e.set("id",n.id),e.set("type",n.type),e.set("rawTarget",n.rawTarget),e.set("targetMode",n.targetMode),e.set("order",n.order),e}function gt(n){let e=new w__namespace.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function ft(n){n.set("protocolVersion",Qe),n.set("sharedSchemaVersion",et),n.set("repairVersion",tt),n.set("canonicalModelVersion",nt),n.set("initialized",true);}function R(n){let e=n.get(ne);return e instanceof w__namespace.Array?e:null}function X(n){return n.get(T)instanceof w__namespace.Text}function O(n){return n instanceof w__namespace.Map}function se(n){return typeof n=="string"?n:""}function yt(n,e){return n<e?-1:n>e?1:0}function Le(n,e){return `${n}${v}${e}`}function or(n){let e=n.indexOf(v);return e<0?n:n.slice(0,e)}function bt(n){let e=[];return n.forEach((t,r)=>{!O(t)||m(r)||t.forEach(o=>{if(!O(o))return;let i=se(o.get("id")),s=se(o.get("type"));if(i.length===0||s.length===0)return;let a=se(o.get("ownerPart"))||or(r);if(m(a))return;let l=o.get("order");e.push({ownerPart:a,id:i,type:s,rawTarget:se(o.get("rawTarget")),targetMode:o.get("targetMode")==="External"?"External":"Internal",order:typeof l=="number"&&Number.isSafeInteger(l)?l:0});});}),e.sort((t,r)=>t.order-r.order||yt(t.ownerPart,r.ownerPart)||yt(t.id,r.id)),e}function ir(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r+=1){let o=n[r]-e[r];if(o!==0)return o}return n.length-e.length}function It(n,e){let t=n.childrenSnapshot.get(e);if(t)return t;let r=n.nodes.get(e);return r?R(r)?.toArray()??[]:[]}function ar(n,e){let t=n.nodes.get(e);return !t||t.get(P)===true}function sr(n,e,t,r){let o=[],i=new Set,s=r,a;for(;;){if(i.has(s)||(i.add(s),ar(n,s)))return null;a=e.get(s);let c=n.parentIndex.get(s);if(a!==void 0){if(c!==void 0)return "fallback";break}if(c===void 0)return t.has(s)?"deferred":null;o.push(s),s=c;}let l=[a],d=s;for(let c=o.length-1;c>=0;c-=1){let g=o[c],u=It(n,d).indexOf(g);if(u<0)return null;l.push(u),d=g;}return l}function xt(n,e){let t=new Set(e);for(let i of t)n.parentIndex.delete(i);let r=new Map;n.partRoots.forEach((i,s)=>{r.has(i)||r.set(i,s);});let o=[...t];for(;o.length>0;){let i=[];for(let s of o){let a=null,l=false;for(let d of n.listings.get(s)??[]){if(d===s)continue;let c=sr(n,r,t,d);if(c==="fallback")return false;if(c==="deferred"){l=true;continue}if(c===null)continue;let g=It(n,d).indexOf(s);if(g<0)continue;let u=[...c,g];(!a||ir(u,a.rank)<0)&&(a={rank:u,parent:d});}if(l){i.push(s);continue}a&&n.parentIndex.set(s,a.parent),t.delete(s);}if(i.length===o.length)return false;o=i;}return true}function vt(n,e){let{nodes:t,parentIndex:r,childrenSnapshot:o,partRoots:i}=n;if(e)for(let s of e)r.delete(s);for(let s of i){let a=new Set,l=[{id:s,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){a.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)),a.has(c))continue;let g=t.get(c);if(!g||g.get(P)===true)continue;let u=o.get(c)??R(g)?.toArray()??[];a.add(c),l.push({id:c,parent:null,exit:true});let p=new Set,f=[];for(let y of u)p.has(y)||y===c||(p.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 St(n,e){return `${n}${v}${e}`}function Ce(n,e,t,r,o){if(m(t)||m(r.localName))return;let i=U(n.namespaces,r.namespaceUri,e),s=Ee(t,i,r.localName);m(s)||n.attributes.set(s,dt(r.prefix??"",o));}function Et(n,e,t,r){n.attributes.delete(Ee(e,V(t),r));}function Re(n,e,t,r,o){if(m(t)||m(r))return;let i=U(n.namespaces,o,e),s=we(t,r);m(s)||n.bindings.set(s,i);}function wt(n,e,t){n.bindings.delete(we(e,t));}function ke(n,e,t,r,o,i){let{prefix:s,value:a}=ct(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(St(r,o),{namespaceUri:$(n.namespaces,r),localName:o,prefix:s.length>0?s:void 0,value:a});}function Lt(n,e,t,r){let o=n.get(e);o&&(o.delete(St(t,r)),o.size===0&&n.delete(e));}function Pe(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:$(n.namespaces,o)});}function Ct(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function kt(n,e){let t=n.get(e);if(!t)return null;if(X(t)){let r=t.get(T);return {isText:true,textLength:r instanceof w__namespace.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:R(t)?.toArray()??[]}}function Pt(n,e){let t=n.get(e);if(!t)return null;if(X(t))return "textValue";let r=t.get(B);return oe(typeof r=="string"?r:"").kind}function At(n,e){if(n.length!==e.length)return false;for(let t=0;t<n.length;t+=1)if(n[t]!==e[t])return false;return true}function z(n){return typeof n=="string"?n:""}function Ot(n){let e=[];return n.forEach((t,r)=>{if(!O(t)||m(r))return;let o=z(t.get("rootId"));o.length!==0&&e.push({name:r,id:z(t.get("id")),rootLogicalId:o,contentType:z(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function Nt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!m(r)&&e.set(store.partNameKey(r),t);}),e}function Mt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!m(r)&&e.set(r,t);}),e}function Tt(n){let e=[];return n.forEach((t,r)=>{if(!O(t)||m(r))return;let o=z(t.get("digest")),i=t.get("size"),s=z(t.get("mediaType")),a=z(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:s,storageKey:a});}),e}function dr(n){return n?._item??null}function cr(n){return n.content instanceof w__namespace.ContentType}function Bt(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=dr(t);return r===null||r.parent!==n?true:!cr(e)}}function ur(n){let e=n._item;return e?xe(e.id.client,e.id.clock):null}function Ut(n){return typeof n=="string"?n:""}var Y=class{constructor(e,t){this.doc=e;this.schema=st(e),this.limits=qe(t),this.schema.nodes.observeDeep(r=>{this.bulkLoad>0||this.applyChildArrayEvents(r);}),this.schema.attributes.observe(r=>{this.bulkLoad>0||this.applyAttributeMapEvent(r);}),this.schema.bindings.observe(r=>{this.bulkLoad>0||this.applyBindingMapEvent(r);}),this.schema.relationships.observeDeep(()=>{this.relationshipCountCache=-1;}),this.schema.parts.observeDeep(()=>{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;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 Bt(this.schema.nodes)}encodeSnapshot(){return w__namespace.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return w__namespace.encodeStateAsUpdate(this.doc,e)}partEntries(){return Ot(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 Ut(this.schema.meta.get("mainDocumentPart"))}record(e){if(m(e))return null;let t=this.schema.nodes.get(e);if(!t)return null;if(X(t)){let r=t.get(T),o=r instanceof w__namespace.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return this.elementRecord(e,t)}parentOf(e){return this.parentIndex.get(e)??null}identityMeta(e){let t=this.schema.nodes.get(e);if(!t)return null;let r=this.record(e),o=r&&x(r)?r.attributes:[];return {logicalId:e,yjsItemKey:ur(t),wordFacingIds:ve(o)}}isTombstoned(e){return this.schema.nodes.get(e)?.get(P)===true}replacedByOf(e){let t=this.schema.nodes.get(e)?.get(_);return typeof t=="string"&&t.length>0?t:null}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(V(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:kt(this.schema.nodes,e)}kindOf(e){return m(e)?null:Pt(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=U(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,ut({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)Ce(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)Re(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=U(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(B,Se(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,pt(t));}spliceText(e,t,r,o){let i=this.textOf(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,o);}setAttribute(e,t,r){if(r===null){Et(this.schema,e,t.namespaceUri,t.localName);return}Ce(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){wt(this.schema,e,t);return}Re(this.schema,this.limits.maxStringLength,e,t,r);}spliceChildren(e,t,r,o){let i=this.childArray(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,[...o]);}moveNode(e,t,r){this.unlinkFromAllParents(e);let o=this.childArray(t);o.insert(Math.max(0,Math.min(r,o.length)),[e]);}tombstone(e,t){this.unlinkFromAllParents(e);let r=this.require(e);r.set(P,true),t&&r.set(_,t);}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?R(r):null;if(!o)return;let i=new Map;for(let s of t)i.set(s,(i.get(s)??0)+1);for(let s=o.length-1;s>=0;s-=1){let a=o.get(s),l=i.get(a)??0;l!==0&&(i.set(a,l-1),o.delete(s,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,ht(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 t=new w__namespace.Map;t.set(e.id,mt(e)),this.schema.relationships.set(Le(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(Le(e,t)),this.schema.relationships.get(e)?.delete(t);}putContentTypeOverride(e,t){this.schema.overrides.set(store.partNameKey(e),t);}deleteContentTypeOverride(e){this.schema.overrides.delete(store.partNameKey(e));}putContentTypeDefault(e,t){this.schema.defaults.set(e,t);}putBinary(e){this.schema.binaries.set(e.storageKey,gt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return bt(this.schema.relationships)}contentTypeOverrides(){return Nt(this.schema.overrides)}contentTypeDefaults(){return Mt(this.schema.defaults)}binaries(){return Tt(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){let t=i=>{let s=new Set,a=false;for(let l of i){let d=l.path;if(d.length===0){for(let c of l.changes.keys.keys())s.add(String(c));a=true;continue}s.add(String(d[0])),l.target instanceof w__namespace.Array&&(a=true),l.target instanceof w__namespace.Map&&(l.changes.keys.has(P)||l.changes.keys.has(_))&&(a=true);}(s.size>0||a)&&e({logicalIds:s,membershipChanged:a,packageChanged:false});},r=i=>{let s=new Set;for(let a of i.changes.keys.keys()){let l=ie(String(a))??ae(String(a));!l||m(l.logicalId)||s.add(l.logicalId);}s.size>0&&e({logicalIds:s,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return this.schema.nodes.observeDeep(t),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(t),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,t)=>{if(m(t))return;let r=R(e);if(!r)return;let o=r.toArray();this.childrenSnapshot.set(t,o);for(let i of o)this.addListing(i,t);}),this.schema.nodes.forEach((e,t)=>{e.get(P)===true&&this.syncAdoptee(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||m(t))return;let r=ie(t);!r||m(r.logicalId)||m(r.localName)||ke(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,t)=>{if(typeof e!="string"||m(t))return;let r=ae(t);!r||m(r.logicalId)||m(r.prefix)||Pe(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(O(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 t=new Set;for(let r of e){if(r.path.length===0&&r.target instanceof w__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"||m(String(o))))for(let s of this.syncChildListings(String(o)))t.add(s);continue}if(r.target instanceof w__namespace.Array&&r.path.length>0){let o=String(r.path[0]);for(let i of this.syncChildListings(o))t.add(i);this.isTombstoned(o)&&this.syncAdoptee(o);continue}r.target instanceof w__namespace.Map&&r.path.length===1&&(r.changes.keys.has(P)||r.changes.keys.has(_))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0;for(let[t,r]of e.changes.keys){let o=ie(String(t));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(t));typeof i=="string"&&ke(this.schema,this.attributesByNode,o.logicalId,o.namespaceId,o.localName,i);}}applyBindingMapEvent(e){this.unobservedWrites=0;for(let[t,r]of e.changes.keys){let o=ae(String(t));if(!o||m(o.logicalId)||m(o.prefix))continue;if(r.action==="delete"){Ct(this.bindingsByNode,o.logicalId,o.prefix);continue}let i=this.schema.bindings.get(String(t));typeof i=="string"&&Pe(this.schema,this.bindingsByNode,o.logicalId,o.prefix,i);}}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?R(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(At(o,r))return [];let i=new Set(r),s=new Set(o),a=[];for(let l of o)i.has(l)||(this.removeListing(l,e),a.push(l));for(let l of r)s.has(l)||(this.addListing(l,e),a.push(l));return this.childrenSnapshot.set(e,r),a}addListing(e,t){let r=this.listings.get(e)??new Set;r.add(t),this.listings.set(e,r);}removeListing(e,t){let r=this.listings.get(e);r&&(r.delete(t),r.size===0&&this.listings.delete(e));}resolveParents(e){let t=[];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}t.push(o);}if(t.length===0)return;xt({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(o=>o.rootLogicalId)},t)||this.assignFirstReachable(new Set(t));}assignFirstReachable(e){vt({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(t=>t.rootLogicalId)},e);}syncAdoptee(e){let t=this.tombstoneSurvivor.get(e);if(t!==void 0){this.tombstoneSurvivor.delete(e);let i=this.tombstoneSources.get(t);i&&(i.delete(e),i.size===0&&this.tombstoneSources.delete(t));}let r=this.schema.nodes.get(e),o=r?.get(_);if(!(typeof o!="string"||o.length===0)){if(r?.get(P)===true){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 t=this.kindOf(e);return t!==null&&!t.endsWith("Properties")}recomputeAdoptees(e){let t=[];for(let r of this.tombstoneSources.get(e)??[]){let o=this.schema.nodes.get(r);if(o)for(let i of R(o)?.toArray()??[])this.isTombstoned(i)||!this.schema.nodes.has(i)||this.isContentWitness(i)&&t.push(i);}t.length>0?this.adoptees.set(e,t):this.adoptees.delete(e);}unlinkFromAllParents(e){let t=[...this.listings.get(e)??[]];if(t.length===0){this.schema.nodes.forEach(r=>{let o=R(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?R(o):null;i&&this.removeFromArray(i,e);}}removeFromArray(e,t){for(let r=e.length-1;r>=0;r-=1)e.get(r)===t&&e.delete(r,1);}elementRecord(e,t){let r=oe(Ut(t.get(B))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:$(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:this.childArray(e).toArray()}}textOf(e){let t=this.require(e).get(T);if(!(t instanceof w__namespace.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(ne);if(!(t instanceof w__namespace.Array))throw new Error(`no children at ${e}`);return t}require(e){let t=this.schema.nodes.get(e);if(!t)throw new Error(`registry node ${e} missing`);return t}};var le=class{blobs=new Map;get(e){let t=this.blobs.get(e);return t?t.slice():null}put(e,t){this.blobs.set(e,t.slice());}};async function zt(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return `sha256:${[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Yt(n){let e=n.binaryPart;return typeof e=="function"?e:null}function jt(n,e){let t=[];for(let o of n)o.kind==="putBinary"&&t.push(o.descriptor);if(t.length===0)return null;if(!e)return {ok:false,failure:{code:"blob-read",detail:"binary-part-reader"}};let r=[];for(let o of t){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 Kt(n,e){for(let t of e)n.put(t.digest,t.bytes);}function hr(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function mr(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function Ft(n,e,t,r,o){if(r>n.limits.maxTreeDepth)return "tree-too-deep";if(m(e.id))return "prototype-key";if(o.nodes+=1,o.nodes>n.limits.maxNodes)return "too-many-nodes";if(e.kind==="textValue"){if(e.value.length>n.limits.maxTextLength)return "text-too-long";n.putText(e.id,e.value);}else {if(e.attributes.length>n.limits.maxAttributes)return "too-many-attributes";if(e.children.length>n.limits.maxChildren)return "too-many-children";if(L(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(m(i.localName))return "prototype-key";if(L(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(m(i.prefix))return "prototype-key";if(L(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}n.putElement({logicalId:e.id,kind:e.kind,namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,attributes:hr(e),bindings:mr(e)});for(let i of e.children){let s=Ft(n,i,e.id,r+1,o);if(s)return s}}return t&&n.childArray(t).push([e.id]),null}async function gr(n){let e=[],t=[];for(let[r,o]of n.partBytes){if(n.parts.has(r))continue;let s=n.contentTypes.overrides.get(r)??"application/octet-stream",a=E(r);if(a)return {ok:false,code:a};if(o.byteLength>A.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await zt(o);t.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:s,storageKey:r});}return {ok:true,descriptors:e,payloads:t}}async function W(n,e,t=new le){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await gr(e);if(!r.ok)return r;let o=null;n.beginBulkLoad();try{n.doc.transact(()=>{for(let a of r.payloads)t.put(a.digest,a.bytes);ft(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);let i={nodes:0};for(let[a,l]of e.parts){let d=E(a);if(d){o=d;return}if(L(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let c=Ft(n,l.root,null,0,i);if(c){o=c;return}n.putXmlPart({name:a,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let s=0;for(let a of e.relationships.values())for(let l of a){if(s+=1,s>n.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=E(l.ownerPart);if(d){o=d;return}}if(m(l.id)){o="prototype-key";return}n.putRelationship({ownerPart:l.ownerPart,id:l.id,type:l.type,rawTarget:l.rawTarget,targetMode:l.targetMode,order:l.order});}for(let[a,l]of e.contentTypes.defaults){if(m(a)){o="prototype-key";return}n.putContentTypeDefault(a,l);}for(let[a,l]of e.contentTypes.overrides){let d=E(a);if(d){o=d;return}n.putContentTypeOverride(a,l);}for(let a of r.descriptors)n.putBinary(a);},ot);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var de=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 t=this.touched.get(e);if(t)return t;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,t,r){let o=this.node(e);o&&(o.textLength=Math.max(0,o.textLength-t)+r);}spliceChildren(e,t,r,o){let i=this.node(e);i&&i.children.splice(t,r,...o);}moveNode(e,t,r){let o=this.parentOf(e);if(o!==null){let a=this.node(o),l=a?.children.indexOf(e)??-1;a&&l>=0&&a.children.splice(l,1);}let i=this.node(t);if(!i)return;let s=Math.min(r,i.children.length);i.children.splice(s,0,e);}parentOf(e){for(let[t,r]of this.touched)if(r.children.includes(e))return t;return this.registry.parentOf(e)}};function Vt(n,e){switch(e.kind){case "putNode":n.putNode(e.descriptor);return;case "spliceText":n.spliceText(e.logicalId,e.deleteCount,e.insert.length);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;default:return}}function N(n,e){return m(e)||e.length===0?{ok:false,code:"prototype-key",detail:e}:n.has(e)?null:{ok:false,code:"unknown-logical-id",detail:e}}function fr(n,e,t){if(m(e.logicalId)||e.logicalId.length===0)return {ok:false,code:"invalid-logical-id",detail:e.logicalId};let r=t.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}:L(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function yr(n,e,t){switch(e.kind){case "putNode":return fr(n,e.descriptor,t);case "spliceText":{let r=N(t,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>n.limits.maxTextLength)return {ok:false,code:"text-too-long"};let o=t.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>n.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(t,e.logicalId);return r||(m(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:L(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:e.value!==null&&e.value.length>n.limits.maxStringLength?{ok:false,code:"invalid-string"}:null)}case "setNamespaceBinding":{let r=N(t,e.logicalId);return r||(m(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&L(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=N(t,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>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let i of e.childLogicalIds){let s=N(t,i);if(s)return s}let o=t.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>n.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(t,e.logicalId);if(r)return r;let o=N(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=E(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=N(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=E(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=E(e.owner);if(r)return {ok:false,code:r}}return m(e.record.id)?{ok:false,code:"prototype-key"}:n.relationshipCount()>=n.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=E(e.partName);return r?{ok:false,code:r}:L(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=E(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=Ze(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 br(n,e,t){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?n.hasNode(e.descriptor.logicalId)||n.putText(e.descriptor.logicalId,""):n.hasNode(e.descriptor.logicalId)?n.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):n.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(t.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&n.textOf(e.logicalId).toString()===e.insert)return;n.spliceText(e.logicalId,e.utf16Start,e.deleteCount,e.insert);return;case "setAttribute":n.setAttribute(e.logicalId,e.qname,e.value);return;case "setNamespaceBinding":n.setNamespaceBinding(e.logicalId,e.prefix,e.uri);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;case "putXmlPart":n.putXmlPart({name:e.name,id:e.name,rootLogicalId:e.rootLogicalId,contentType:"application/xml"});return;case "deleteXmlPart":n.deleteXmlPart(e.name);return;case "putRelationship":n.putRelationship({...e.record,ownerPart:e.owner});return;case "deleteRelationship":n.deleteRelationship(e.owner,e.relationshipId);return;case "putContentTypeOverride":n.putContentTypeOverride(e.partName,e.mediaType);return;case "deleteContentTypeOverride":n.deleteContentTypeOverride(e.partName);return;case "putBinary":n.putBinary(e.descriptor);return;case "deleteBinary":n.deleteBinary(e.storageKey);return}}function Ir(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function xr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Ir(n,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(s=>o.has(s)))return i.parentLogicalId}}function vr(n,e){let t=new de(n),r=[],o=new Set,i=new Set;for(let s of e){let a=yr(n,s,t);if(a)return a;if(s.kind==="spliceChildren"){let l=s.deleteCount>0?t.node(s.parentLogicalId):null;if(l&&!l.isText){let d=s.start+s.deleteCount;for(let c=s.start;c<d;c+=1){let g=l.children[c];g!==void 0&&r.push(g);}}for(let d of s.childLogicalIds)o.add(d);}else s.kind==="moveNode"?o.add(s.logicalId):s.kind==="putNode"&&s.descriptor.kind==="textValue"&&i.add(s.descriptor.logicalId);Vt(t,s);}return {removed:r,reinserted:o,mintedText:i}}function Sr(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function Ae(n,e){if(n.nodeCount()+Sr(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=vr(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=wr(n,t.removed);for(let o of e.effects)br(n,o,t.mintedText);Er(n,e.effects,t,r);},it),{ok:true})}function Er(n,e,t,r){if(t.removed.length===0)return;let o=new Set;for(let i of n.partEntries())o.add(i.rootLogicalId);for(let i of t.removed){if(t.reinserted.has(i)||!n.hasNode(i)||n.isTombstoned(i)||o.has(i))continue;let s=xr(n,i,r,e);s&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,s);}}function wr(n,e){let t=new Map;for(let r of e){let o=n.nodeShape(r);o&&!o.isText&&t.set(r,o.children);}return t}var ue="http://schemas.openxmlformats.org/package/2006/relationships",Lr="application/vnd.openxmlformats-package.relationships+xml",$t=/^(.*)\/_rels\/([^/]*)\.rels$/;function Xt(n){return $t.test(n)}function Wt(n){let e=$t.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function J(n,e){return n.attributes.find(t=>t.localName===e)?.value}function ce(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function Cr(n,e){let t=[ce("Id",e.id),ce("Type",e.type),ce("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(ce("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:ue,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function Jt(n,e){if(n.kind==="textValue"||n.namespaceUri!==ue||n.localName!=="Relationship"||J(n,"Id")!==e.id||J(n,"Type")!==e.type||J(n,"Target")!==e.rawTarget)return false;let t=J(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function Gt(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>Jt(t,e[r]))}function Ht(n,e){if(n.id!==e.id||n.kind!==e.kind||n.namespaceUri!==e.namespaceUri||n.localName!==e.localName||n.prefix!==e.prefix||n.attributes.length!==e.attributes.length)return false;for(let t=0;t<n.attributes.length;t+=1){let r=n.attributes[t],o=e.attributes[t];if(r.namespaceUri!==o.namespaceUri||r.localName!==o.localName||r.value!==o.value||r.prefix!==o.prefix)return false}return n.namespaceBindings.length!==e.namespaceBindings.length?false:n.namespaceBindings.every((t,r)=>{let o=e.namespaceBindings[r];return t.prefix===o.prefix&&t.namespaceUri===o.namespaceUri})}function qt(n,e,t){let r=[];for(let o of e){if(m(o.id))continue;let i=n.find(a=>a.kind!=="textValue"&&J(a,"Id")===o.id);if(i&&Jt(i,o)){r.push(i);continue}let s=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;m(s)||r.push(Cr(s,o));}return r}function Rr(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:ue,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:ue})]),attributes:Object.freeze([]),children:Object.freeze([])})}function Zt(n){return Object.freeze({id:n,name:n,contentType:Lr,root:Rr(n)})}function Qt(n){let e=new Map;for(let t of n){if(m(t.id)||t.ownerPart!=="/"&&E(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var rn=/^\/customXml\/item(\d+)\.xml$/i,Or=/^\/customXml\/itemProps(\d+)\.xml$/i;function H(n){return rn.test(n)}function Ne(n){return Or.test(n)}function Nr(n){let e=rn.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function en(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function Mr(n,e,t){let r=n.attributes.find(o=>o.localName===e&&o.namespaceUri===t);return r&&r.value.length>0?r.value:null}function tn(n,e){let t=n.record(e);return !t||!x(t)?e:t.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function Tr(n,e){let t=n.record(e);if(!t||!x(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!x(o)||o.localName!=="schemaRefs")&&o.namespaceUri===store.DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let s=n.record(i);if(!s||!x(s)||s.localName!=="schemaRef")continue;let a=Mr(s,"uri",store.DATASTORE_NAMESPACE_URI);if(a)return a}}return null}function Dr(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&x(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Br(n,e){return e.localName==="node"||e.namespaceUri===store.WML_NAMESPACE_URI||e.namespaceUri===store.DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||n.parentOf(e.logicalId)!==null?false:Dr(n,e)}function _r(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==store.DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function on(n,e){if(!n.hasNamespace(store.DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[u,p]of e){let f=n.record(p.root.id);!f||!x(f)||(H(u)&&t.set(f.logicalId,f),Ne(u)&&r.set(f.logicalId,f));}for(let u of n.allLogicalIds()){if(n.isTombstoned(u)||t.has(u)||r.has(u))continue;let p=n.record(u);!p||!x(p)||(Br(n,p)?t.set(u,p):_r(n,p)&&r.set(u,p));}if(t.size===0)return [];let o=new Map;for(let u of t.values()){let p=o.get(u.namespaceUri)??[];p.push(u),o.set(u.namespaceUri,p);}let i=new Map;for(let u of r.values()){let p=Tr(n,u.logicalId);if(!p)continue;let f=i.get(p)??[];f.push(u),i.set(p,f);}let s=[];for(let[u,p]of o){let f=i.get(u);if(!f||f.length===0)continue;p.sort((I,S)=>I.logicalId.localeCompare(S.logicalId)),f.sort((I,S)=>I.logicalId.localeCompare(S.logicalId));let y=p[0],M=f[0],k=[],b=new Set;for(let I of p)for(let S of I.childIds){if(b.has(S))continue;let te=n.record(S);!te||!x(te)||te.localName!=="node"||te.namespaceUri!==u||(b.add(S),k.push(S));}for(let I of n.allLogicalIds()){if(b.has(I)||n.isTombstoned(I))continue;let S=n.record(I);!S||!x(S)||S.localName!=="node"||S.namespaceUri!==u||(b.add(I),k.push(I));}k.sort((I,S)=>tn(n,I).localeCompare(tn(n,S))),s.push({data:y,props:M,nodeIds:k});}s.sort((u,p)=>u.data.logicalId.localeCompare(p.data.logicalId));let a=new Set,l=[],d=new Set,c=new Set;for(let[u,p]of e){let f=Nr(u);if(f===null)continue;let y=s.find(b=>b.data.logicalId===p.root.id&&!d.has(b.data.logicalId));if(!y)continue;let M=en(f).props,k=e.get(M);k&&k.root.id!==y.props.logicalId||(a.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:M,nodeIds:y.nodeIds}));}let g=1;for(let u of s){if(d.has(u.data.logicalId))continue;for(;a.has(g);)g+=1;a.add(g);let p=en(g);l.push({dataRootId:u.data.logicalId,propsRootId:u.props.logicalId,namespaceUri:u.data.namespaceUri,itemName:p.item,propsName:p.props,nodeIds:u.nodeIds}),g+=1;}return l.sort((u,p)=>u.itemName.localeCompare(p.itemName)),l}function Ur(n){return n.type===store.CUSTOM_XML_REL||n.type===store.CUSTOM_XML_PROPS_REL?true:H(n.ownerPart)}function zr(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function Yr(n,e){let t=n.split("/").slice(1,-1),r=e.split("/").slice(1),o=0;for(;o<t.length&&o<r.length-1&&t[o]===r[o];)o+=1;return `${"../".repeat(t.length-o)}${r.slice(o).join("/")}`}function an(n,e){if(e.length===0)return [];let t=n.mainDocumentPart();if(!t)return [];let r=n.relationships(),o=r.filter(a=>a.ownerPart===t&&a.type===store.CUSTOM_XML_REL).sort((a,l)=>a.id.localeCompare(l.id)),i=0;for(let a of r)i=Math.max(i,zr(a.id));let s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=o[a],c=d?.id??`rId${String(i+=1)}`;s.push({ownerPart:t,id:c,type:store.CUSTOM_XML_REL,rawTarget:Yr(t,l.itemName),targetMode:"Internal",order:d?.order??a}),s.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 s}function sn(n,e){return e.length===0?[...n]:[...n.filter(t=>!Ur(t)),...e]}function ln(n){let e=new Map;for(let t of n)e.set(store.partNameKey(t.propsName),store.CUSTOM_XML_PROPS_TYPE);return e}function Me(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(H).sort(),r=e.map(o=>o.itemName).sort();if(t.length!==r.length||t.some((o,i)=>o!==r[i]))return true;for(let o of e){let i=n.get(o.itemName),s=n.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!s||s.root.id!==o.propsRootId)return true}return false}function dn(n,e){if(Me(n,e))return true;for(let t of e){let r=n.get(t.itemName);if(!r)return true;let o=new Set(r.root.children.map(a=>a.id));if(t.nodeIds.some(a=>!o.has(a)))return true;let i=[];for(let a of r.root.children)a.kind!=="textValue"&&i.push(a.attributes.find(l=>l.localName==="id")?.value??a.id);let s=[...i].sort((a,l)=>a.localeCompare(l));if(i.some((a,l)=>a!==s[l]))return true}return false}var jr="http://schemas.microsoft.com/office/word/2012/wordml";function pe(n,e){return n.attributes.find(t=>t.localName===e)?.value}function he(n){let e=Number(n);return n===void 0||n.length===0||!Number.isSafeInteger(e)?`2${n??""}`:`${e<0?"0":"1"}${String(Math.abs(e)).padStart(12,"0")}`}function cn(n){return e=>e.localName===n&&e.namespaceUri===store.WML_NAMESPACE_URI}function Kr(n){return n.localName==="abstractNum"?`0${he(pe(n,"abstractNumId"))}`:`1${he(pe(n,"numId"))}`}function Fr(n){return n.namespaceUri!==store.WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function un(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===jr,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:cn("footnote"),sortKey:e=>he(pe(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:cn("endnote"),sortKey:e=>he(pe(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:Fr,sortKey:Kr}:null}function Vr(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Te(n){return n.kind==="textValue"?n.id:Vr(n,"id")??n.id}function j(n,e){if(n.length===e.length&&n.every((s,a)=>s===e[a]))return n;let t=0,r=Math.min(n.length,e.length);for(;t<r&&n[t]===e[t];)t+=1;let o=n.length,i=e.length;for(;o>t&&i>t&&n[o-1]===e[i-1];)o-=1,i-=1;return Object.freeze([...n.slice(0,t),...e.slice(t,i),...n.slice(o)])}function mn(n,e){let t=n.root;if(t.children.length===e.length&&t.children.every((o,i)=>o===e[i]))return n;let r=Object.freeze({...t,children:j(t.children,e)});return Object.freeze({...n,root:r})}function $r(n){if(n.namespaceUri===store.XML_NAMESPACE_URI&&n.localName==="space"){let e=n.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:store.XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return n.namespaceUri===store.WML_NAMESPACE_URI&&n.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:store.WML_NAMESPACE_URI,localName:"val",prefix:n.prefix,value:n.value}):Object.freeze({kind:"genericExtension",namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,value:n.value})}function yn(n){}function In(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function qr(n,e){return n.namespaceBindings.length!==e.bindings.length?false:n.namespaceBindings.every((t,r)=>{let o=e.bindings[r];return t.prefix===o.prefix&&t.namespaceUri===o.namespaceUri})}function Zr(n,e){return n.attributes.length!==e.attributes.length?false:n.attributes.every((t,r)=>{let o=e.attributes[r];return t.namespaceUri===o.namespaceUri&&t.localName===o.localName&&t.value===o.value&&t.prefix===(o.prefix?.length?o.prefix:void 0)})}function me(n,e,t){let r=t&&t.kind!=="textValue"?t:void 0;return Object.freeze({id:n.logicalId,kind:n.kind,namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,namespaceBindings:r&&qr(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&Zr(r,n)?r.attributes:Object.freeze(n.attributes.map($r)),children:e})}function xn(n,e){if(n.attributes.length!==e.attributes.length)return false;let t=new Map(e.attributes.map(r=>[`${r.namespaceUri}
|
|
2
|
+
${r.localName}`,r.value]));for(let r of n.attributes)if(t.get(`${r.namespaceUri}
|
|
3
|
+
${r.localName}`)!==r.value)return false;return n.localName===e.localName&&n.kind===e.kind}function De(n,e){let t=e.size;e.add(n.id);let r=e.size!==t;if(n.kind==="textValue")return r;for(let o of n.children)De(o,e)||(r=false);return r}function vn(n,e){let t=new Set(e);for(let r of e){let o=n.parentOf(r);for(;o&&!t.has(o);)t.add(o),o=n.parentOf(o);}return t}var ge=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:sn(this.decoded,e)}),this.merged.records}groupedByOwner(e){let t=this.projected(e);return (!this.grouped||this.grouped.records!==t)&&(this.grouped={records:t,map:Qt(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:to(t)}),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 t=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){t.set(o.storageKey,i.bytes);continue}let s=e.get(o.digest);if(!s)return null;yn(s.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:s}),t.set(o.storageKey,s);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=t,t}};function to(n){let e=store.buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=store.resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}function oo(n){let e=new Set,t=[];for(let r of n){let o=`${r.code}${r.logicalId??""}`;e.has(o)||(e.add(o),t.push(r));}return t}var K=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new ge(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=[],t=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");t.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())t.has(r)||e.push(r);return this.lastAdoption=t,e}rebuild(){let e=new Set(this.pendingDirty),t=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(t||r)&&this.packageCache.invalidate();for(let c of this.adoptionChanges())e.add(c);let o=vn(this.registry,e),i=new Set(this.registry.partEntries().map(c=>c.rootLogicalId)),s=[...e].some(c=>i.has(c)||this.registry.parentOf(c)===null&&!this.registry.isTombstoned(c)),a=this.pkg!==null&&!r&&!s&&(o.size>0||t),l=this.materializePass(o,t,a);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:oo(l.issues)};let d=this.materializePass(o,t,false);return this.recordContestResolution(),d}contestUnchanged(){for(let e of this.contestEncountered){let t=this.lastContestResolution.get(e);if(t===void 0||t!==this.registry.parentOf(e))return false}return true}recordContestResolution(){let e=new Map;for(let t of this.contestEncountered)e.set(t,this.registry.parentOf(t));for(let t of this.lastDuplicateParents)e.set(t,this.registry.parentOf(t));this.lastContestResolution=e;}materializePass(e,t,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,g=this.materialize(d.rootLogicalId,o,c,r);if(!g||g.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let u=this.partCache.get(d.name);if(u&&u.root===g&&u.contentType===d.contentType){i.set(d.name,u);continue}let p=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:g});i.set(d.name,p),this.partCache.set(d.name,p);}let s=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),a=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,s,a),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(s,o,r,a),this.looseCandidates=a,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&&!t&&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,t){this.issues.push(t?{code:e,logicalId:t}:{code:e});}stillListed(e){for(let t of this.registry.listingParents(e)){let r=this.registry.record(t);if(r&&x(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,t,r,o){if(!r){for(let a of e)this.registry.isTombstoned(a)||t.has(a)||(this.pushOrphan(a),o.add(a));return}let i=new Set(this.registry.partEntries().map(a=>a.rootLogicalId)),s=new Set;for(let a of e)s.has(a)||(s.add(a),this.reportOrphansUnder(a,t,i)&&o.add(a));}reportOrphansUnder(e,t,r){let o=false,i=new Set,s=[{id:e,underTombstone:false}];for(;s.length>0;){let{id:a,underTombstone:l}=s.pop();if(!(i.has(a)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(a),this.registry.isTombstoned(a)){let d=this.registry.record(a);if(d&&x(d))for(let c of d.childIds)s.push({id:c,underTombstone:true});continue}r.has(a)||(l?t.has(a):this.stillListed(a))||(this.pushOrphan(a),o=true);}}return o}pushOrphan(e){let t=this.registry.record(e),r=!!t&&(re(t)?t.value.length>0:t.childIds.length>0||t.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,t,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(t.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?De(u,t)||(this.placementContested=true):t.add(u.id),u}if(this.registry.isTombstoned(e))return null;t.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(re(i)){let u=this.cache.get(e);if(u?.kind==="textValue"&&u.value===i.value)return u;let p=In(e,i.value);return this.remember(e,p),p}r.add(e);let s=new Set,a=[...i.childIds];for(let u of this.registry.adoptedChildren(e))a.includes(u)||a.push(u);let l=[];for(let u of a){if(u===e){this.push("self-child",u);continue}if(s.has(u)){this.push("duplicate-child",u);continue}if(s.add(u),this.registry.isTombstoned(u)){this.push("deleted-referenced",u);continue}if(m(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:!t.has(u)&&this.registry.parentOf(u)!==e&&(this.contestMatchesResolution=false));}let p=this.materialize(u,t,r,o);p&&l.push(p);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((u,p)=>u===l[p])&&xn(d,i))return d;let c=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(c,l);let g=me(i,j(c,l),d);return this.remember(e,g),g}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){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)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;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 t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let s=store.relsPartNameFor(o);if(s!=="/_rels/.rels"&&E(s))continue;r.add(s);let a=this.projectOneRelsPart(s,e.get(s),i);a&&(e.set(s,a),this.partCache.set(s,a));}for(let[o,i]of e){if(r.has(o)||!Xt(o))continue;let s=Wt(o);if(s===null)continue;let a=this.projectOneRelsPart(o,i,t.get(s)??[]);!a||a===i||(e.set(o,a),this.partCache.set(o,a));}}projectOneRelsPart(e,t,r){if(!t&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),s=!!o&&(!t||Ht(o.root,t.root))&&o?o:t??Zt(e);if(Gt(s.root,r))return this.relsProjection.set(e,s),s;let a=s.root.children,l=mn(s,qt(a,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[s,a]of e){let l=un(a.root);if(!l)continue;let d=b=>b.logicalId!==a.root.id&&l.isMember(b),c=[],g=new Set;for(let b of a.root.children){if(b.kind==="textValue")continue;let I=this.registry.record(b.id);!I||!x(I)||!d(I)||(c.push(b),g.add(b.id));}if(this.adoptLooseMembers(c,g,d,t,r,o,i)===0)continue;c.sort((b,I)=>l.sortKey(b).localeCompare(l.sortKey(I)));let p=[];for(let b of a.root.children)g.has(b.id)||p.push(b);let f=j(a.root.children,[...p,...c]);if(f===a.root.children)continue;let y=this.registry.record(a.root.id);if(!y||!x(y))continue;let M=me(y,f,a.root);this.remember(a.root.id,M);let k=Object.freeze({...a,root:M});e.set(s,k),this.partCache.set(s,k);}}adoptLooseMembers(e,t,r,o,i,s,a){let l=0;for(let d of s){if(o.has(d)||t.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let c=this.registry.record(d);if(!c||!x(c)||!r(c))continue;let g=this.materialize(d,o,new Set,i);!g||g.kind==="textValue"||(e.push(g),t.add(d),a.add(d),l+=1);}return l}materializeOnce(e,t,r){return t.has(e)?this.cache.get(e)??null:this.materialize(e,t,new Set,r)}adoptNodesIntoRoot(e,t,r,o){let i=this.cache.get(e),s=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!s||s.kind==="textValue")return null;let a=[...s.children],l=new Set(a.map(p=>p.id)),d=0;for(let p of t){if(l.has(p))continue;let f=this.materializeOnce(p,r,o);!f||f.kind==="textValue"||(a.push(f),l.add(p),d+=1);}if(a.sort((p,f)=>Te(p).localeCompare(Te(f))),d===0&&a.every((p,f)=>p===s.children[f]))return s;let c=this.registry.record(e);if(!c||!x(c))return s;let g=j(s.children,a),u=me(c,g,s);return this.remember(e,u),u}applyCustomXmlStores(e,t,r){let o=on(this.registry,e);if(o.length===0||!dn(e,o))return;let i=Me(e,o),s=new Set;for(let a of o){s.add(a.itemName),s.add(a.propsName);let l=this.adoptNodesIntoRoot(a.dataRootId,a.nodeIds,t,r),d=this.materializeOnce(a.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let c=Object.freeze({id:a.itemName,name:a.itemName,contentType:"application/xml",root:l}),g=Object.freeze({id:a.propsName,name:a.propsName,contentType:store.CUSTOM_XML_PROPS_TYPE,root:d});e.set(a.itemName,c),e.set(a.propsName,g),this.partCache.set(a.itemName,c),this.partCache.set(a.propsName,g);}if(i){for(let a of [...e.keys()])!H(a)&&!Ne(a)||s.has(a)||(e.delete(a),this.partCache.delete(a));this.customXmlRels=an(this.registry,o),this.customXmlOverrides=ln(o),this.projectRelsParts(e);}}assemblePackage(e){let t=this.packageCache.relationshipAssembly(this.customXmlRels);if(!t)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[a,l]of this.customXmlOverrides)o.set(a,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},s=this.registry.mainDocumentPart()||[...e.keys()].find(a=>a.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:t.byOwner,externalTargets:t.externalTargets,contentTypes:i,mainDocumentPart:s}),issues:[...this.issues]}}};var En=1,wn=1,_e=20*1024*1024,uo="docx-collaboration-v1",po="docx-body-paragraphs-v1",ho=Object.freeze({kind:"docx-collaboration-bootstrap"}),h=class extends Error{constructor(t,r){super(r?`${t}: ${r}`:t);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function ze(n){return {root:n.getMap(uo),paragraphs:n.getMap(po)}}function mo(n,e){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>_e)throw new h("baseline-too-large");let t=store.readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:_e,maxRatio:200}});if(!t.ok)throw new h("invalid-baseline");let r=t.package.parts.get(t.package.mainDocumentPart);if(!r)throw new h("no-main-document-part");let o=store.normalizeParagraphIdentity(r),i=new store.TreePackageStore(t.package,o),s=replication.createCollaborationDocumentPort(i,{documentId:e});return {bytes:store.writeOoxmlPackage(i.currentPackage()),paragraphs:s.paragraphs()}}async function Ln(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return [...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function Sn(n,e){let t=n.get(e);if(typeof t!="string"||t.length===0||t.length>256)throw new h("invalid-shared-metadata",e);return t}function Be(n,e){let t=n.get(e);if(!Number.isSafeInteger(t)||t<0)throw new h("invalid-shared-metadata",e);return t}function Z(n){return n.get("initialized")===true}async function aa(n,e,t,r){let{root:o,paragraphs:i}=ze(n);if(Z(o))throw new h("already-initialized");let s=await Ln(r.bytes);n.transact(()=>{if(Z(o))throw new h("already-initialized");o.set("protocolVersion",En),o.set("schemaVersion",wn),o.set("documentId",e),o.set("baselineSha256",s),o.set("baselineByteLength",r.bytes.byteLength),o.set("initializedBy",t),o.set("baseline",new Uint8Array(r.bytes));for(let a of r.paragraphs){if(i.has(a.paragraphId))throw new h("duplicate-paragraph-id");let l=new w__namespace.Text;i.set(a.paragraphId,l),l.insert(0,a.text);}o.set("initialized",true);},ho);}async function sa(n,e){let{root:t,paragraphs:r}=ze(n);if(!Z(t))throw new h("not-initialized");if(Be(t,"protocolVersion")!==En)throw new h("protocol-version-mismatch");if(Be(t,"schemaVersion")!==wn)throw new h("schema-version-mismatch");if(Sn(t,"documentId")!==e)throw new h("document-id-mismatch");let o=Be(t,"baselineByteLength");if(o===0||o>_e)throw new h("baseline-too-large");let i=t.get("baseline");if(!(i instanceof Uint8Array)||i.byteLength!==o)throw new h("invalid-baseline");if(await Ln(i)!==Sn(t,"baselineSha256"))throw new h("baseline-digest-mismatch");let s=mo(new Uint8Array(i),e),a=new Set(s.paragraphs.map(l=>l.paragraphId));if(r.size!==a.size)throw new h("paragraph-set-mismatch");for(let[l,d]of r)if(!a.has(l)||!(d instanceof w__namespace.Text))throw new h("paragraph-set-mismatch");return s}function la(n,e,t){let{root:r}=ze(n);return Z(r)?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((o,i)=>{let s=c=>{clearTimeout(d),r.unobserve(a),t?.removeEventListener("abort",l),c?i(c):o();},a=()=>{Z(r)&&s();},l=()=>s(new h("initialization-aborted")),d=setTimeout(()=>s(new h("initialization-timeout")),e);r.observe(a),t?.addEventListener("abort",l,{once:true});})}var Rn=64*1024*1024;function fo(n){if(n instanceof Uint8Array)return new Uint8Array(n);if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n)){let e=n;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}return null}function yo(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function fe(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var Q=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=fo(t);return !r||typeof t!="object"||t===null?null:this.verify(e,t,r)?r:null}has(e){let t=this.shared.get(e);return t===void 0?false:this.verified.has(t)?true:this.get(e)!==null}poisonedDigest(){for(let e of this.poisoned)return e;return null}observeChanges(e){let t=r=>{e([...r.keysChanged]);};return this.shared.observe(t),()=>this.shared.unobserve(t)}verifyNow(e){for(let t of e)if(this.shared.has(t)&&this.get(t)===null)return t;return null}totalByteLength(){let e=0;return this.shared.forEach(t=>{e+=yo(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Rn)throw new h("blob-store-full");this.shared.set(e,new Uint8Array(t));}}verify(e,t,r){return this.verified.has(t)?true:this.poisoned.has(e)?false:layout.sha256FontBytes(r)!==e?(this.poisoned.add(e),false):(this.verified.add(t),true)}};function ye(n,e){let{limits:t}=n,r=n.nodeCount();if(r>t.maxNodes)return fe("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return fe("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(a=>{i+=a instanceof w__namespace.Map?a.size:0;}),i>t.maxRelationships)return fe("too-many-relationships",`${i}`);let s=e.totalByteLength();return s>Rn?fe("blob-store-full",`${s}`):null}var kn=20*1024*1024,je=3e4,vo=4e3,So=1500,Eo="docx-collaboration-seeds-v1",Ye="docxEditorSeedCandidate",wo=/^[0-9a-f]{16}$/,Lo=256;function Ke(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>kn)throw new h("baseline-too-large");let e=store.readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:kn,maxRatio:200}});if(!e.ok)throw new h("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new h("no-main-document-part");return new store.TreePackageStore(e.package,store.normalizeParagraphIdentity(t)).currentPackage()}function Co(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function ee(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&Co(n,e),s=()=>{let l=e.poisonedDigest();return l?new h("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let a=s();return a?Promise.reject(a):r?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((l,d)=>{let c=f=>{clearTimeout(p),o.unobserve(g),n.doc.off("afterTransaction",g),r?.removeEventListener("abort",u),f?d(f):l();},g=()=>{let f=s();if(f){c(f);return}i()&&c();},u=()=>c(new h("initialization-aborted")),p=setTimeout(()=>c(new h("initialization-timeout")),t);o.observe(g),n.doc.on("afterTransaction",g),r?.addEventListener("abort",u,{once:true});})}function Fe(n){return n.getArray(Eo)}function Ve(n){return Fe(n).length}function An(n,e){let t=Fe(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Ro(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function ko(n,e){let t=[...n.getStates().entries()].slice(0,Lo);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[Ye];if(!(typeof i!="string"||!wo.test(i))&&i<e)return true}return false}async function Pn(n,e,t,r){try{return await ee(n,e,t,r),!0}catch(o){if(o instanceof h&&o.code==="initialization-timeout")return false;throw o}}function Po(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((i,s)=>{let a=g=>{clearTimeout(c),r.unobserve(l),t?.removeEventListener("abort",d),g?s(g):i();},l=()=>{o()&&a();},d=()=>a(new h("initialization-aborted")),c=setTimeout(()=>a(new h("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function On(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??vo,s=n.electionWindowMs??So,a=n.timeoutMs??je,l=async()=>(await Po(r,a,n.signal),"joined");if(await Pn(r,o,i,n.signal))return l();let d=Ro();t.setLocalStateField(Ye,d);try{let c=await Pn(r,o,s,n.signal);if(!c&&ko(t,d)&&(await ee(r,o,a,n.signal),c=!0),c)return await l();if(r.schema.meta.get("initialized")===!0)return await ee(r,o,a,n.signal),await l();let g=await W(r,Ke(n.document),o);if(!g.ok)throw new h(g.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),Fe(e).push([d]);}),"seeded"}finally{t.setLocalStateField(Ye,null);}}var be=class{constructor(e,t){this.knows=e;this.allocator=new F(t);}knows;allocator;toLogical=new Map;get replicaId(){return this.allocator.replicaId}reset(){this.toLogical.clear();}mint(e){let t=this.allocator.take();return this.toLogical.set(e,t),t}resolve(e){return this.toLogical.get(e)??e}translate(e){let t=[],r=false;for(let o of e.effects){let i=this.translateEffect(o);i!==o&&(r=true),t.push(i);}return r?Object.freeze({effects:Object.freeze(t)}):e}translateEffect(e){switch(e.kind){case "putNode":{let t=this.translateDescriptor(e.descriptor);return t.logicalId===e.descriptor.logicalId?e:{...e,descriptor:t}}case "spliceText":case "setAttribute":case "setNamespaceBinding":{let t=this.resolve(e.logicalId);return t===e.logicalId?e:{...e,logicalId:t}}case "spliceChildren":{let t=this.resolve(e.parentLogicalId),r=e.childLogicalIds.map(i=>this.resolve(i));return t===e.parentLogicalId&&r.every((i,s)=>i===e.childLogicalIds[s])?e:{...e,parentLogicalId:t,childLogicalIds:r}}case "moveNode":{let t=this.resolve(e.logicalId),r=this.resolve(e.destinationParentLogicalId);return t===e.logicalId&&r===e.destinationParentLogicalId?e:{...e,logicalId:t,destinationParentLogicalId:r}}case "putXmlPart":{let t=this.resolve(e.rootLogicalId);return t===e.rootLogicalId?e:{...e,rootLogicalId:t}}default:return e}}translateDescriptor(e){let t=this.resolve(e.logicalId);return this.knows(t)?{...e,logicalId:t}:{...e,logicalId:this.mint(e.logicalId)}}};var $e="docxEditor",Un="docx-package-blobs-v1",D=256,Nn=256,No=3,Mo=5e3,To=2e3,Do=Symbol("createDocumentCollaboration.attachWatchdogMs");function Bo(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>D||t.length===0||t.length>D)throw new h("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new h("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function _o(n){let e=n.trim();if(e.length===0||e.length>D)throw new h("invalid-document-id");return e}function Uo(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>D)throw new h("invalid-session-id");return e}function Mn(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;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 zo(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=Mn(e.anchor),r=Mn(e.head);if(t&&r)return e.kind==="cells"?{anchor:t,head:r,kind:"cells"}:{anchor:t,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 Tn(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;if(typeof e.actorId!="string"||e.actorId.length===0||e.actorId.length>D||typeof e.name!="string"||e.name.length===0||e.name.length>D)return null;let t=collaboration.safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...t?{color:t}:{},role:r},i=zo(e.selection);return i?{...o,selection:i}:o}var Xe=class{constructor(e,t,r,o,i,s,a,l,d,c,g){this.ydoc=e;this.awareness=t;this.registry=s;this.materializer=a;this.identityMap=l;this.blobs=d;this.offlineEditing=g;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new w__namespace.UndoManager([...s.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:Mo,deleteFilter:s.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(u=>{let p=d.verifyNow(u);p&&this.setStatus("error","blob-digest-mismatch",p);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=An(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;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()}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,t,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(t!==void 0){this.setStatus(e,t,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let t=this.refuseAttach(e);if(t)return t;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{this.destroyed||this.applyingRemote||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}gateOperations(e,t){if(this.destroyed)return "collaboration-session-destroyed";let r=this.statusState.status();return r!=="ready"&&!(this.offlineEditing&&r==="disconnected")?"collaboration-session-not-ready":this.port?null:"collaboration-session-not-attached"}canUndo(){return !this.destroyed&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return !this.destroyed&&this.undoManager.redoStack.length>0}undo(){return this.destroyed||(this.flushPendingJournals(),this.undoManager.undoStack.length===0)?false:(this.undoManager.undo(),true)}redo(){return this.destroyed||(this.flushPendingJournals(),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=[],t=[...this.awareness.getStates().entries()].slice(0,Nn);for(let[r,o]of t){let i=Tn(o[$e]);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 t=i=>{let s=e.paragraphByStableId(i.paragraphId);return s?Object.freeze({paragraphId:s.paragraphId,nodeId:s.nodeId,offset:Math.min(i.offset,s.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,Nn),o=[];for(let[i,s]of r){if(i===this.awareness.clientID)continue;let a=Tn(s[$e]);if(!a?.selection)continue;let l=t(a.selection.anchor),d=t(a.selection.head);!l||!d||o.push(Object.freeze({actorId:a.actorId,name:a.name,...a.color?{color:a.color}:{},...a.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 t=e.name===void 0?this.currentIdentity.name:e.name.trim();if(t.length===0||t.length>D)throw new h("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new h("invalid-identity-color");r=collaboration.safeParticipantColor(e.color);}this.currentIdentity=Object.freeze({actorId:this.currentIdentity.actorId,name:t,...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.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}applyJournal(e){let t=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 s=this.putJournalBlobs(r.payloads);if(s!==null)return s}let i=Ae(this.registry,t);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 t=this.port;if(!t)return e.effects.some(i=>i.kind==="putBinary")?{ok:false,failure:Object.freeze({code:"collaboration-session-not-attached"})}:null;let r=jt(e.effects,Yt(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{Kt(this.blobs,e);}catch(t){return t instanceof h?Object.freeze({code:t.code,...t.detail?{detail:t.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){this.undoManager.stopCapturing(),this.refusedInARow+=1,this.setStatus("error",e.code,e.detail),this.publishSharedToPort(),this.realignedInBatch=true,queueMicrotask(()=>{this.realignedInBatch=false;});let t=this.statusState.snapshot().reason;this.refusedInARow<No&&this.statusState.status()==="error"&&t!==void 0&&t.code===e.code&&t.detail===e.detail&&this.setStatus("ready");}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 t=ye(this.registry,this.blobs);if(t){this.setStatus("error",t.code,t.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=at(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let s=e.applyRemotePackage(r.package,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!s.ok){this.setStatus("error","remote-apply-failed",s.reason);return}s.changed&&this.identityMap.reset();}catch(t){this.setStatus("error",t instanceof h?t.code:"remote-apply-failed",t instanceof h?t.detail:void 0);}finally{this.applyingRemote=false;}}}onAwarenessChange=()=>{if(this.destroyed)return;let e=this.remoteSelections();for(let r of [...this.selectionListeners])r(e);let t=this.participants();for(let r of [...this.participantListeners])r(t);};publishAwareness(e){this.currentSelection=e;let t={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($e,t);}setStatus(e,t,r){if(!this.statusState.set(e,t,r))return;let o=this.statusState.snapshot();for(let i of [...this.statusListeners])i(o.status,o.reason?.code,o.reason?.detail);}};function ka(n){let e=new Y(n);if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new h("not-initialized");if(Ve(n)>1)throw new h("concurrent-seed");let t=new Q(n.getMap(Un)),r=ye(e,t);if(r)throw new h(r.code,r.detail);let o=new K(e,t);try{let i=o.current(),s=t.poisonedDigest();if(s)throw new h("blob-digest-mismatch",s);if(!i.ok)throw new h(i.code);return store.writeOoxmlPackage(i.package)}finally{o.destroy();}}async function Pa(n){let e=n[Do]??To,t=_o(n.documentId),r=Uo(n.sessionId),o=Bo(n.identity),i=new Y(n.ydoc),s=new be(p=>i.hasNode(p)),a=new Q(n.ydoc.getMap(Un));if(n.bootstrap.kind==="create"){if(i.schema.meta.get("initialized")===true)throw new h("already-initialized");let p=await W(i,Ke(n.bootstrap.document),a);if(!p.ok)throw new h(p.code);n.ydoc.transact(()=>{i.schema.meta.set("documentId",t);});}else if(n.bootstrap.kind==="create-or-join"){if(await On({ydoc:n.ydoc,awareness:n.awareness,registry:i,blobs:a,documentId:t,document:n.bootstrap.document,probeTimeoutMs:n.bootstrap.probeTimeoutMs,electionWindowMs:n.bootstrap.electionWindowMs,timeoutMs:n.bootstrap.timeoutMs,signal:n.bootstrap.signal})==="joined"){if(i.schema.meta.get("documentId")!==t)throw new h("document-id-mismatch");i.rebuildDerivedIndexes();}}else {if(await ee(i,a,n.bootstrap.timeoutMs??je,n.bootstrap.signal),i.schema.meta.get("documentId")!==t)throw new h("document-id-mismatch");i.rebuildDerivedIndexes();}if(Ve(n.ydoc)>1)throw new h("concurrent-seed");let l=ye(i,a);if(l)throw new h(l.code,l.detail);let d=new K(i,a),c=d.current(),g=a.poisonedDigest();if(g)throw d.destroy(),new h("blob-digest-mismatch",g);if(!c.ok)throw d.destroy(),new h(c.code);let u=new Xe(n.ydoc,n.awareness,t,r,o,i,d,s,a,e,n.offlineEditing===true);return Object.freeze({document:store.writeOoxmlPackage(c.package),session:u,destroy:()=>u.destroy()})}exports.a=En;exports.b=wn;exports.c=_e;exports.d=h;exports.e=ze;exports.f=mo;exports.g=aa;exports.h=sa;exports.i=la;exports.j=Do;exports.k=ka;exports.l=Pa;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function r(){let t=new Uint8Array(24);return globalThis.crypto.getRandomValues(t),[...t].map(o=>o.toString(16).padStart(2,"0")).join("")}function n(t){let o=t.trim();if(!/^[A-Za-z0-9_-]{24,256}$/.test(o))throw new TypeError("roomId must contain 24 to 256 URL-safe characters");return o}export{r as a,n as b};
|