@docx-editor.dev/pro 2.16.2 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/chunk-4NIIGM6D.cjs +4 -0
  2. package/dist/chunk-EFCL3VQI.cjs +4 -0
  3. package/dist/chunk-HMTYXNMO.js +4 -0
  4. package/dist/chunk-OZT67MLG.js +4 -0
  5. package/dist/collaboration/hocuspocus.cjs +1 -1
  6. package/dist/collaboration/hocuspocus.js +1 -1
  7. package/dist/collaboration/index.cjs +2 -2
  8. package/dist/collaboration/index.d.cts +87 -6
  9. package/dist/collaboration/index.d.ts +87 -6
  10. package/dist/collaboration/index.js +2 -2
  11. package/dist/collaboration/webrtc.cjs +1 -1
  12. package/dist/collaboration/webrtc.js +1 -1
  13. package/dist/document-session-HHDGRM4Z.js +1 -0
  14. package/dist/document-session-I2C7MA6E.cjs +1 -0
  15. package/dist/document-session-OXC3PO7A.js +1 -0
  16. package/dist/document-session-U4VGKQYC.cjs +1 -0
  17. package/dist/hocuspocus-KOLAIT7T.cjs +1 -0
  18. package/dist/hocuspocus-ZBQCCO4G.js +1 -0
  19. package/dist/react/index.cjs +1 -1
  20. package/dist/react/index.js +1 -1
  21. package/dist/vue/hocuspocus.cjs +1 -1
  22. package/dist/vue/hocuspocus.js +1 -1
  23. package/dist/vue/index.cjs +1 -1
  24. package/dist/vue/index.d.cts +3 -3
  25. package/dist/vue/index.d.ts +3 -3
  26. package/dist/vue/index.js +1 -1
  27. package/dist/vue/webrtc.cjs +1 -1
  28. package/dist/vue/webrtc.js +1 -1
  29. package/dist/{webrtc-F6OLZU65.cjs → webrtc-6HVF33UP.cjs} +1 -1
  30. package/dist/{webrtc-O3Y4W4P6.js → webrtc-CUEMY3DZ.js} +1 -1
  31. package/package.json +4 -4
  32. package/dist/chunk-3625DZUE.js +0 -3
  33. package/dist/chunk-54OI2PSM.js +0 -3
  34. package/dist/chunk-AB6CJLJ4.cjs +0 -3
  35. package/dist/chunk-DOVUXFIP.cjs +0 -3
  36. package/dist/document-session-6NLJAJY2.cjs +0 -1
  37. package/dist/document-session-CULOPWY6.js +0 -1
  38. package/dist/document-session-JVA7VYPB.cjs +0 -1
  39. package/dist/document-session-R4ETEHGF.js +0 -1
  40. package/dist/hocuspocus-AJOJV5NQ.js +0 -1
  41. package/dist/hocuspocus-TST45TQ6.cjs +0 -1
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkQLZH2Q2C_cjs=require('../chunk-QLZH2Q2C.cjs'),chunkDOVUXFIP_cjs=require('../chunk-DOVUXFIP.cjs'),l=require('yjs'),store=require('@docx-editor.dev/core/store'),collaboration=require('@docx-editor.dev/core/collaboration');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 l__namespace=/*#__PURE__*/_interopNamespace(l);var C="docxEditor",h=256,O=256,I=1e6,D=3e4;function B(a){let t=a.actorId.trim(),n=a.name.trim();if(t.length===0||t.length>h||n.length===0||n.length>h)throw new chunkDOVUXFIP_cjs.d("invalid-identity");if(a.color!==void 0&&a.color.length>64)throw new chunkDOVUXFIP_cjs.d("invalid-identity-color");return Object.freeze({actorId:t,name:n,...a.color?{color:a.color}:{},role:a.role??"human"})}function F(a){let t=a.trim();if(t.length===0||t.length>h)throw new chunkDOVUXFIP_cjs.d("invalid-document-id");return t}function N(a){let t=a?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new chunkDOVUXFIP_cjs.d("invalid-session-id");return t}function H(a,t){let n=a.toString();if(n===t)return;let o=0;for(;o<n.length&&o<t.length&&n.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<n.length-o&&e<t.length-o&&n.charCodeAt(n.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=n.length-o-e;r>0&&a.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&a.insert(o,i);}function R(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function V(a){if(a===void 0||typeof a!="object"||a===null||Array.isArray(a))return;let t=a,n=R(t.anchor),o=R(t.head);if(n&&o)return {anchor:n,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function L(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let n=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=V(t.selection);return {actorId:t.actorId,name:t.name,...n?{color:n}:{},role:o,...e?{selection:e}:{}}}function X(a){let t="";for(let n of a)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function $(a){let t=a.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,o=>o.charCodeAt(0))}var w=class{constructor(t,n,o,e,r,i){this.ydoc=t;this.awareness=n;this.baseline=i;this.documentId=o,this.sessionId=e,this.identity=r;let{root:d,paragraphs:p}=chunkDOVUXFIP_cjs.e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l__namespace.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),n.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=collaboration.createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,n,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(n!==void 0){this.setStatus(t,n,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let n=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===store.ORIGIN_IDS.mutationRemote||o.origin===store.ORIGIN_IDS.projection||o.origin===store.ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof chunkDOVUXFIP_cjs.d?e.code:"local-mirror-failed",e instanceof chunkDOVUXFIP_cjs.d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),n(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,n){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(n.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>I)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:n}=chunkDOVUXFIP_cjs.e(this.ydoc),o=(r,i)=>{let d=n.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:X(l__namespace.encodeRelativePosition(l__namespace.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e={anchor:r,head:i});}this.publishAwareness(e);}participants(){let t=[],n=[...this.awareness.getStates().entries()].slice(0,O);for(let[o,e]of n){let r=L(e[C]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,O),{paragraphs:n}=chunkDOVUXFIP_cjs.e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=L(r[C]);if(!i?.selection)continue;let d=y=>{let x=n.get(y.paragraphId);if(!x)return null;let u;try{u=l__namespace.createAbsolutePositionFromRelativePosition(l__namespace.decodeRelativePosition($(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==x)return null;let f=this.port?.paragraphs().find(M=>M.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),v=d(i.selection.head);!p||!v||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(v)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(n){this.setStatus("error",n instanceof chunkDOVUXFIP_cjs.d?n.code:"shared-schema-invalid",n instanceof chunkDOVUXFIP_cjs.d?n.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let n=this.participants();for(let o of [...this.participantListeners])o(n);};publishAwareness(t){let n={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(C,n);}validateParagraphSet(t){let{paragraphs:n}=chunkDOVUXFIP_cjs.e(this.ydoc),o=t.paragraphs();if(o.length!==n.size||o.some(e=>!n.has(e.paragraphId)||!(n.get(e.paragraphId)instanceof l__namespace.Text)||n.get(e.paragraphId).length>I))throw new chunkDOVUXFIP_cjs.d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:n}=chunkDOVUXFIP_cjs.e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new chunkDOVUXFIP_cjs.d("unsupported-root-key");if(t.get("protocolVersion")!==chunkDOVUXFIP_cjs.a||t.get("schemaVersion")!==chunkDOVUXFIP_cjs.b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new chunkDOVUXFIP_cjs.d("immutable-metadata-changed");let e=t.get("baseline");if(!(e instanceof Uint8Array)||e.byteLength!==this.baseline.bytes.byteLength||e.some((r,i)=>r!==this.baseline.bytes[i]))throw new chunkDOVUXFIP_cjs.d("immutable-baseline-changed");for(let[r,i]of n)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l__namespace.Text)||i.length>I)throw new chunkDOVUXFIP_cjs.d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:n}=chunkDOVUXFIP_cjs.e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=n.get(o.paragraphId);if(!e)throw new chunkDOVUXFIP_cjs.d("paragraph-set-mismatch");H(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:n}=chunkDOVUXFIP_cjs.e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=n.get(e.paragraphId);if(!r)throw new chunkDOVUXFIP_cjs.d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new chunkDOVUXFIP_cjs.d(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",collaboration.isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof chunkDOVUXFIP_cjs.d?o.code:"remote-apply-failed",o instanceof chunkDOVUXFIP_cjs.d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,n,o){if(!this.statusState.set(t,n,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function J(a,t,n){if(a.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(a.bootstrap.kind==="create"){let o=chunkDOVUXFIP_cjs.f(a.bootstrap.document,t);return await chunkDOVUXFIP_cjs.g(a.ydoc,t,n.actorId,o),chunkDOVUXFIP_cjs.h(a.ydoc,t)}return await chunkDOVUXFIP_cjs.i(a.ydoc,a.bootstrap.timeoutMs??D,a.bootstrap.signal),chunkDOVUXFIP_cjs.h(a.ydoc,t)}async function Z(a){let t=F(a.documentId),n=N(a.sessionId),o=B(a.identity),e=await J(a,t,o),r=new w(a.ydoc,a.awareness,t,n,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}
2
- Object.defineProperty(exports,"collaborationModule",{enumerable:true,get:function(){return chunkQLZH2Q2C_cjs.b}});Object.defineProperty(exports,"CollaborationSchemaError",{enumerable:true,get:function(){return chunkDOVUXFIP_cjs.d}});Object.defineProperty(exports,"MAX_BASELINE_BYTES",{enumerable:true,get:function(){return chunkDOVUXFIP_cjs.c}});Object.defineProperty(exports,"PROTOCOL_VERSION",{enumerable:true,get:function(){return chunkDOVUXFIP_cjs.a}});Object.defineProperty(exports,"SCHEMA_VERSION",{enumerable:true,get:function(){return chunkDOVUXFIP_cjs.b}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunkDOVUXFIP_cjs.m}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunkDOVUXFIP_cjs.k}});Object.defineProperty(exports,"readCollaborationResourceUsage",{enumerable:true,get:function(){return chunkDOVUXFIP_cjs.j}});exports.createTextCollaboration=Z;
1
+ 'use strict';var chunkQLZH2Q2C_cjs=require('../chunk-QLZH2Q2C.cjs'),chunkEFCL3VQI_cjs=require('../chunk-EFCL3VQI.cjs'),l=require('yjs'),store=require('@docx-editor.dev/core/store'),collaboration=require('@docx-editor.dev/core/collaboration');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 l__namespace=/*#__PURE__*/_interopNamespace(l);var w="docxEditor",h=256,L=256,v=1e6,$=3e4;function X(n){let t=n.actorId.trim(),a=n.name.trim();if(t.length===0||t.length>h||a.length===0||a.length>h)throw new chunkEFCL3VQI_cjs.d("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new chunkEFCL3VQI_cjs.d("invalid-identity-color");return Object.freeze({actorId:t,name:a,...n.color?{color:n.color}:{},role:n.role??"human"})}function G(n){let t=n.trim();if(t.length===0||t.length>h)throw new chunkEFCL3VQI_cjs.d("invalid-document-id");return t}function J(n){let t=n?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new chunkEFCL3VQI_cjs.d("invalid-session-id");return t}function Z(n,t){let a=n.toString();if(a===t)return;let o=0;for(;o<a.length&&o<t.length&&a.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<a.length-o&&e<t.length-o&&a.charCodeAt(a.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=a.length-o-e;r>0&&n.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&n.insert(o,i);}function M(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function W(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let t=n,a=M(t.anchor),o=M(t.head);if(a&&o)return {anchor:a,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function _(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let a=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=W(t.selection);return {actorId:t.actorId,name:t.name,...a?{color:a}:{},role:o,...e?{selection:e}:{}}}function K(n){let t="";for(let a of n)t+=String.fromCharCode(a);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function q(n){let t=n.replace(/-/g,"+").replace(/_/g,"/"),a=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(a,o=>o.charCodeAt(0))}var A=class{constructor(t,a,o,e,r,i){this.ydoc=t;this.awareness=a;this.baseline=i;this.documentId=o,this.sessionId=e,this.identity=r;let{root:d,paragraphs:p}=chunkEFCL3VQI_cjs.e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l__namespace.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),a.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=collaboration.createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,a,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(a!==void 0){this.setStatus(t,a,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let a=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===store.ORIGIN_IDS.mutationRemote||o.origin===store.ORIGIN_IDS.projection||o.origin===store.ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof chunkEFCL3VQI_cjs.d?e.code:"local-mirror-failed",e instanceof chunkEFCL3VQI_cjs.d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),a(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,a){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(a.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>v)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:a}=chunkEFCL3VQI_cjs.e(this.ydoc),o=(r,i)=>{let d=a.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:K(l__namespace.encodeRelativePosition(l__namespace.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e={anchor:r,head:i});}this.publishAwareness(e);}participants(){let t=[],a=[...this.awareness.getStates().entries()].slice(0,L);for(let[o,e]of a){let r=_(e[w]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,L),{paragraphs:a}=chunkEFCL3VQI_cjs.e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=_(r[w]);if(!i?.selection)continue;let d=y=>{let T=a.get(y.paragraphId);if(!T)return null;let u;try{u=l__namespace.createAbsolutePositionFromRelativePosition(l__namespace.decodeRelativePosition(q(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==T)return null;let f=this.port?.paragraphs().find(U=>U.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),x=d(i.selection.head);!p||!x||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(x)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(a){this.setStatus("error",a instanceof chunkEFCL3VQI_cjs.d?a.code:"shared-schema-invalid",a instanceof chunkEFCL3VQI_cjs.d?a.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let a=this.participants();for(let o of [...this.participantListeners])o(a);};publishAwareness(t){let a={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(w,a);}validateParagraphSet(t){let{paragraphs:a}=chunkEFCL3VQI_cjs.e(this.ydoc),o=t.paragraphs();if(o.length!==a.size||o.some(e=>!a.has(e.paragraphId)||!(a.get(e.paragraphId)instanceof l__namespace.Text)||a.get(e.paragraphId).length>v))throw new chunkEFCL3VQI_cjs.d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:a}=chunkEFCL3VQI_cjs.e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new chunkEFCL3VQI_cjs.d("unsupported-root-key");if(t.get("protocolVersion")!==chunkEFCL3VQI_cjs.a||t.get("schemaVersion")!==chunkEFCL3VQI_cjs.b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new chunkEFCL3VQI_cjs.d("immutable-metadata-changed");let e=t.get("baseline");if(!(e instanceof Uint8Array)||e.byteLength!==this.baseline.bytes.byteLength||e.some((r,i)=>r!==this.baseline.bytes[i]))throw new chunkEFCL3VQI_cjs.d("immutable-baseline-changed");for(let[r,i]of a)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l__namespace.Text)||i.length>v)throw new chunkEFCL3VQI_cjs.d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:a}=chunkEFCL3VQI_cjs.e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=a.get(o.paragraphId);if(!e)throw new chunkEFCL3VQI_cjs.d("paragraph-set-mismatch");Z(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:a}=chunkEFCL3VQI_cjs.e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=a.get(e.paragraphId);if(!r)throw new chunkEFCL3VQI_cjs.d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new chunkEFCL3VQI_cjs.d(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",collaboration.isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof chunkEFCL3VQI_cjs.d?o.code:"remote-apply-failed",o instanceof chunkEFCL3VQI_cjs.d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,a,o){if(!this.statusState.set(t,a,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function Q(n,t,a){if(n.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(n.bootstrap.kind==="create"){let o=chunkEFCL3VQI_cjs.f(n.bootstrap.document,t);return await chunkEFCL3VQI_cjs.g(n.ydoc,t,a.actorId,o),chunkEFCL3VQI_cjs.h(n.ydoc,t)}return await chunkEFCL3VQI_cjs.i(n.ydoc,n.bootstrap.timeoutMs??$,n.bootstrap.signal),chunkEFCL3VQI_cjs.h(n.ydoc,t)}async function tt(n){let t=G(n.documentId),a=J(n.sessionId),o=X(n.identity),e=await Q(n,t,o),r=new A(n.ydoc,n.awareness,t,a,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}var D=["protocolVersion","sharedSchemaVersion","repairVersion","canonicalModelVersion"];function Y(n){return `docx-collaboration:${n.join(".")}`}var F=Y(D.map(n=>chunkEFCL3VQI_cjs.j[n]));function et(n){if(n!==F)throw new chunkEFCL3VQI_cjs.d("collaboration-format-mismatch","The collaboration format version is missing or incompatible with this deployment.")}function ot(n){if(!n.share.has(chunkEFCL3VQI_cjs.l))throw new chunkEFCL3VQI_cjs.d("not-initialized");let t;try{t=n.getMap(chunkEFCL3VQI_cjs.l);}catch{throw new chunkEFCL3VQI_cjs.d("collaboration-format-mismatch","The saved room has invalid collaboration version information.")}if(t.get("initialized")!==true||typeof t.get("documentId")!="string")throw new chunkEFCL3VQI_cjs.d("not-initialized");let a=D.map(o=>{let e=t.get(o);if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new chunkEFCL3VQI_cjs.d("collaboration-format-mismatch","The saved room has missing or invalid collaboration version information.");return e});return Y(a)}
2
+ Object.defineProperty(exports,"collaborationModule",{enumerable:true,get:function(){return chunkQLZH2Q2C_cjs.b}});Object.defineProperty(exports,"CollaborationSchemaError",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.d}});Object.defineProperty(exports,"DOCUMENT_COLLABORATION_VERSIONS",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.j}});Object.defineProperty(exports,"MAX_BASELINE_BYTES",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.c}});Object.defineProperty(exports,"PROTOCOL_VERSION",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.a}});Object.defineProperty(exports,"SCHEMA_VERSION",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.b}});Object.defineProperty(exports,"assertDocumentCollaborationCompatibility",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.k}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.p}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.n}});Object.defineProperty(exports,"readCollaborationResourceUsage",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.m}});exports.COLLABORATION_FORMAT_VERSION=F;exports.assertCollaborationFormatCompatibility=et;exports.createTextCollaboration=tt;exports.readCollaborationFormatVersion=ot;
@@ -6,6 +6,43 @@ import * as Y from 'yjs';
6
6
  import '@docx-editor.dev/core/editor';
7
7
  import 'y-protocols/awareness';
8
8
 
9
+ /** Version contract for full-document collaboration clients and export workers. @public */
10
+ interface DocumentCollaborationVersions {
11
+ /** Transport-level interpretation of the shared package. */
12
+ readonly protocolVersion: number;
13
+ /** Shared node and character representation. */
14
+ readonly sharedSchemaVersion: number;
15
+ /** Deterministic rules for repairing shared structure. */
16
+ readonly repairVersion: number;
17
+ /** Canonical document model interpreted by a replica. */
18
+ readonly canonicalModelVersion: number;
19
+ }
20
+ /**
21
+ * Versions supported by this full-document collaboration release.
22
+ *
23
+ * Use assertDocumentCollaborationCompatibility before admitting a client to synchronization. These values
24
+ * describe the application schema, not the DOCX format or the Yjs binary update format.
25
+ * Releases with the same tuple can share rooms. A changed tuple requires a coordinated
26
+ * upgrade. This descriptor does not migrate persisted rooms or authenticate clients.
27
+ * @public
28
+ */
29
+ declare const DOCUMENT_COLLABORATION_VERSIONS: DocumentCollaborationVersions;
30
+ /**
31
+ * Refuse an incompatible full-document client or persisted-room version descriptor.
32
+ *
33
+ * Pass the client's version tuple from your admission handshake before permitting sync.
34
+ * Check persisted-room versions separately: a compatible client cannot migrate an older
35
+ * room. This validates compatibility only; your server must also authorize access.
36
+ * Missing or malformed fields refuse. Additional fields are ignored. Exact equality is
37
+ * required for all four supported versions; no migration or shared-state mutation occurs.
38
+ * Handle the stable error code; `detail` is a bounded diagnostic, not a parsing contract.
39
+ *
40
+ * @throws CollaborationSchemaError with `protocol-version-mismatch` or
41
+ * `schema-version-mismatch`, including the field and expected/received version in `detail`.
42
+ * @public
43
+ */
44
+ declare function assertDocumentCollaborationCompatibility(versions: unknown): void;
45
+
9
46
  /**
10
47
  * Server-side read of one collaboration room: shared state to `.docx` bytes, joining nothing.
11
48
  */
@@ -32,23 +69,67 @@ import 'y-protocols/awareness';
32
69
  * Synchronous, and it materializes the whole package per call — this is a job, not a render.
33
70
  *
34
71
  * @throws CollaborationSchemaError — `not-initialized`, `concurrent-seed`,
35
- * `blob-digest-mismatch`, or a limit code: the same refusals a joining replica makes, for the
36
- * same reasons.
72
+ * `protocol-version-mismatch`, `schema-version-mismatch`, `blob-digest-mismatch`,
73
+ * `materialize-dropped-content`, `no-main-document-part`, or a limit code. Incomplete or
74
+ * corrupt shared state refuses instead of producing an incomplete DOCX.
37
75
  * @public
38
76
  */
39
77
  declare function readCollaborationDocument(ydoc: Y.Doc): Uint8Array;
40
78
 
41
- /** Wire protocol version a replica writes into shared metadata and refuses to mismatch. @public */
79
+ /** Wire protocol for experimental text-only collaboration. Full-document clients use DOCUMENT_COLLABORATION_VERSIONS. @public */
42
80
  declare const PROTOCOL_VERSION = 1;
43
- /** Shared Yjs schema version a replica writes into shared metadata and refuses to mismatch. @public */
81
+ /** Schema for experimental text-only collaboration. Full-document clients use DOCUMENT_COLLABORATION_VERSIONS. @public */
44
82
  declare const SCHEMA_VERSION = 1;
45
83
  /** Maximum accepted creator baseline size in bytes. @public */
46
84
  declare const MAX_BASELINE_BYTES: number;
47
- /** Typed collaboration schema or trust-boundary failure. @public */
85
+ /**
86
+ * Typed collaboration schema or trust-boundary failure.
87
+ * Version-mismatch messages include recovery guidance and a documentation link.
88
+ * Use `code` for application logic; `detail` remains diagnostic information.
89
+ * @public
90
+ */
48
91
  declare class CollaborationSchemaError extends Error {
49
92
  readonly code: CollaborationFailureCode;
50
93
  readonly detail?: string | undefined;
51
94
  constructor(code: CollaborationFailureCode, detail?: string | undefined);
52
95
  }
53
96
 
54
- export { CollaborationSchemaError, MAX_BASELINE_BYTES, PROTOCOL_VERSION, SCHEMA_VERSION, readCollaborationDocument };
97
+ /**
98
+ * Opaque collaboration format version, independent of the editor package version.
99
+ *
100
+ * Send this value unchanged during connection admission. Check it with
101
+ * {@link assertCollaborationFormatCompatibility} before allowing synchronization.
102
+ * Equal values declare format compatibility across clients, workers, and saved rooms.
103
+ * Do not parse, order, hard-code, or override the value. It is not a credential.
104
+ * Inspect saved rooms separately with {@link readCollaborationFormatVersion}.
105
+ * @public
106
+ */
107
+ declare const COLLABORATION_FORMAT_VERSION: string;
108
+ /**
109
+ * Refuse a collaboration format version unsupported by this deployment.
110
+ *
111
+ * Pass the untrusted value received during connection admission, after authorizing
112
+ * document access and before synchronization. Only an exact string match succeeds.
113
+ * This check does not authenticate clients, validate room content, or migrate data.
114
+ *
115
+ * @throws CollaborationSchemaError with `collaboration-format-mismatch` for an
116
+ * incompatible, missing, or malformed version. Use `code` for application logic.
117
+ * @public
118
+ */
119
+ declare function assertCollaborationFormatCompatibility(version: unknown): void;
120
+ /**
121
+ * Read the opaque format version recorded in a synchronized or restored room.
122
+ *
123
+ * Reads version metadata without joining, exporting, or changing shared state.
124
+ * Can inspect incompatible rooms; pass the result to
125
+ * {@link assertCollaborationFormatCompatibility} before admitting their state.
126
+ * The result does not validate document content or guarantee a successful export.
127
+ * Use {@link readCollaborationDocument} to validate and export compatible content.
128
+ *
129
+ * @throws CollaborationSchemaError with `not-initialized` for an unseeded room,
130
+ * or `collaboration-format-mismatch` for missing or malformed version metadata.
131
+ * @public
132
+ */
133
+ declare function readCollaborationFormatVersion(ydoc: Y.Doc): string;
134
+
135
+ export { COLLABORATION_FORMAT_VERSION, CollaborationSchemaError, DOCUMENT_COLLABORATION_VERSIONS, type DocumentCollaborationVersions, MAX_BASELINE_BYTES, PROTOCOL_VERSION, SCHEMA_VERSION, assertCollaborationFormatCompatibility, assertDocumentCollaborationCompatibility, readCollaborationDocument, readCollaborationFormatVersion };
@@ -6,6 +6,43 @@ import * as Y from 'yjs';
6
6
  import '@docx-editor.dev/core/editor';
7
7
  import 'y-protocols/awareness';
8
8
 
9
+ /** Version contract for full-document collaboration clients and export workers. @public */
10
+ interface DocumentCollaborationVersions {
11
+ /** Transport-level interpretation of the shared package. */
12
+ readonly protocolVersion: number;
13
+ /** Shared node and character representation. */
14
+ readonly sharedSchemaVersion: number;
15
+ /** Deterministic rules for repairing shared structure. */
16
+ readonly repairVersion: number;
17
+ /** Canonical document model interpreted by a replica. */
18
+ readonly canonicalModelVersion: number;
19
+ }
20
+ /**
21
+ * Versions supported by this full-document collaboration release.
22
+ *
23
+ * Use assertDocumentCollaborationCompatibility before admitting a client to synchronization. These values
24
+ * describe the application schema, not the DOCX format or the Yjs binary update format.
25
+ * Releases with the same tuple can share rooms. A changed tuple requires a coordinated
26
+ * upgrade. This descriptor does not migrate persisted rooms or authenticate clients.
27
+ * @public
28
+ */
29
+ declare const DOCUMENT_COLLABORATION_VERSIONS: DocumentCollaborationVersions;
30
+ /**
31
+ * Refuse an incompatible full-document client or persisted-room version descriptor.
32
+ *
33
+ * Pass the client's version tuple from your admission handshake before permitting sync.
34
+ * Check persisted-room versions separately: a compatible client cannot migrate an older
35
+ * room. This validates compatibility only; your server must also authorize access.
36
+ * Missing or malformed fields refuse. Additional fields are ignored. Exact equality is
37
+ * required for all four supported versions; no migration or shared-state mutation occurs.
38
+ * Handle the stable error code; `detail` is a bounded diagnostic, not a parsing contract.
39
+ *
40
+ * @throws CollaborationSchemaError with `protocol-version-mismatch` or
41
+ * `schema-version-mismatch`, including the field and expected/received version in `detail`.
42
+ * @public
43
+ */
44
+ declare function assertDocumentCollaborationCompatibility(versions: unknown): void;
45
+
9
46
  /**
10
47
  * Server-side read of one collaboration room: shared state to `.docx` bytes, joining nothing.
11
48
  */
@@ -32,23 +69,67 @@ import 'y-protocols/awareness';
32
69
  * Synchronous, and it materializes the whole package per call — this is a job, not a render.
33
70
  *
34
71
  * @throws CollaborationSchemaError — `not-initialized`, `concurrent-seed`,
35
- * `blob-digest-mismatch`, or a limit code: the same refusals a joining replica makes, for the
36
- * same reasons.
72
+ * `protocol-version-mismatch`, `schema-version-mismatch`, `blob-digest-mismatch`,
73
+ * `materialize-dropped-content`, `no-main-document-part`, or a limit code. Incomplete or
74
+ * corrupt shared state refuses instead of producing an incomplete DOCX.
37
75
  * @public
38
76
  */
39
77
  declare function readCollaborationDocument(ydoc: Y.Doc): Uint8Array;
40
78
 
41
- /** Wire protocol version a replica writes into shared metadata and refuses to mismatch. @public */
79
+ /** Wire protocol for experimental text-only collaboration. Full-document clients use DOCUMENT_COLLABORATION_VERSIONS. @public */
42
80
  declare const PROTOCOL_VERSION = 1;
43
- /** Shared Yjs schema version a replica writes into shared metadata and refuses to mismatch. @public */
81
+ /** Schema for experimental text-only collaboration. Full-document clients use DOCUMENT_COLLABORATION_VERSIONS. @public */
44
82
  declare const SCHEMA_VERSION = 1;
45
83
  /** Maximum accepted creator baseline size in bytes. @public */
46
84
  declare const MAX_BASELINE_BYTES: number;
47
- /** Typed collaboration schema or trust-boundary failure. @public */
85
+ /**
86
+ * Typed collaboration schema or trust-boundary failure.
87
+ * Version-mismatch messages include recovery guidance and a documentation link.
88
+ * Use `code` for application logic; `detail` remains diagnostic information.
89
+ * @public
90
+ */
48
91
  declare class CollaborationSchemaError extends Error {
49
92
  readonly code: CollaborationFailureCode;
50
93
  readonly detail?: string | undefined;
51
94
  constructor(code: CollaborationFailureCode, detail?: string | undefined);
52
95
  }
53
96
 
54
- export { CollaborationSchemaError, MAX_BASELINE_BYTES, PROTOCOL_VERSION, SCHEMA_VERSION, readCollaborationDocument };
97
+ /**
98
+ * Opaque collaboration format version, independent of the editor package version.
99
+ *
100
+ * Send this value unchanged during connection admission. Check it with
101
+ * {@link assertCollaborationFormatCompatibility} before allowing synchronization.
102
+ * Equal values declare format compatibility across clients, workers, and saved rooms.
103
+ * Do not parse, order, hard-code, or override the value. It is not a credential.
104
+ * Inspect saved rooms separately with {@link readCollaborationFormatVersion}.
105
+ * @public
106
+ */
107
+ declare const COLLABORATION_FORMAT_VERSION: string;
108
+ /**
109
+ * Refuse a collaboration format version unsupported by this deployment.
110
+ *
111
+ * Pass the untrusted value received during connection admission, after authorizing
112
+ * document access and before synchronization. Only an exact string match succeeds.
113
+ * This check does not authenticate clients, validate room content, or migrate data.
114
+ *
115
+ * @throws CollaborationSchemaError with `collaboration-format-mismatch` for an
116
+ * incompatible, missing, or malformed version. Use `code` for application logic.
117
+ * @public
118
+ */
119
+ declare function assertCollaborationFormatCompatibility(version: unknown): void;
120
+ /**
121
+ * Read the opaque format version recorded in a synchronized or restored room.
122
+ *
123
+ * Reads version metadata without joining, exporting, or changing shared state.
124
+ * Can inspect incompatible rooms; pass the result to
125
+ * {@link assertCollaborationFormatCompatibility} before admitting their state.
126
+ * The result does not validate document content or guarantee a successful export.
127
+ * Use {@link readCollaborationDocument} to validate and export compatible content.
128
+ *
129
+ * @throws CollaborationSchemaError with `not-initialized` for an unseeded room,
130
+ * or `collaboration-format-mismatch` for missing or malformed version metadata.
131
+ * @public
132
+ */
133
+ declare function readCollaborationFormatVersion(ydoc: Y.Doc): string;
134
+
135
+ export { COLLABORATION_FORMAT_VERSION, CollaborationSchemaError, DOCUMENT_COLLABORATION_VERSIONS, type DocumentCollaborationVersions, MAX_BASELINE_BYTES, PROTOCOL_VERSION, SCHEMA_VERSION, assertCollaborationFormatCompatibility, assertDocumentCollaborationCompatibility, readCollaborationDocument, readCollaborationFormatVersion };
@@ -1,2 +1,2 @@
1
- export{b as collaborationModule}from'../chunk-Q2VBO66F.js';import {d,f,g,h as h$1,i,e,a,b}from'../chunk-3625DZUE.js';export{d as CollaborationSchemaError,c as MAX_BASELINE_BYTES,a as PROTOCOL_VERSION,b as SCHEMA_VERSION,m as createDocumentCollaboration,k as readCollaborationDocument,j as readCollaborationResourceUsage}from'../chunk-3625DZUE.js';import*as l from'yjs';import {ORIGIN_IDS}from'@docx-editor.dev/core/store';import {createCollaborationStatusTracker,isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var C="docxEditor",h=256,O=256,I=1e6,D=3e4;function B(a){let t=a.actorId.trim(),n=a.name.trim();if(t.length===0||t.length>h||n.length===0||n.length>h)throw new d("invalid-identity");if(a.color!==void 0&&a.color.length>64)throw new d("invalid-identity-color");return Object.freeze({actorId:t,name:n,...a.color?{color:a.color}:{},role:a.role??"human"})}function F(a){let t=a.trim();if(t.length===0||t.length>h)throw new d("invalid-document-id");return t}function N(a){let t=a?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new d("invalid-session-id");return t}function H(a,t){let n=a.toString();if(n===t)return;let o=0;for(;o<n.length&&o<t.length&&n.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<n.length-o&&e<t.length-o&&n.charCodeAt(n.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=n.length-o-e;r>0&&a.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&a.insert(o,i);}function R(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function V(a){if(a===void 0||typeof a!="object"||a===null||Array.isArray(a))return;let t=a,n=R(t.anchor),o=R(t.head);if(n&&o)return {anchor:n,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function L(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let n=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=V(t.selection);return {actorId:t.actorId,name:t.name,...n?{color:n}:{},role:o,...e?{selection:e}:{}}}function X(a){let t="";for(let n of a)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function $(a){let t=a.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,o=>o.charCodeAt(0))}var w=class{constructor(t,n,o,e$1,r,i){this.ydoc=t;this.awareness=n;this.baseline=i;this.documentId=o,this.sessionId=e$1,this.identity=r;let{root:d,paragraphs:p}=e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),n.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,n,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(n!==void 0){this.setStatus(t,n,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let n=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===ORIGIN_IDS.mutationRemote||o.origin===ORIGIN_IDS.projection||o.origin===ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof d?e.code:"local-mirror-failed",e instanceof d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),n(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,n){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(n.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>I)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:n}=e(this.ydoc),o=(r,i)=>{let d=n.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:X(l.encodeRelativePosition(l.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e$1;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e$1={anchor:r,head:i});}this.publishAwareness(e$1);}participants(){let t=[],n=[...this.awareness.getStates().entries()].slice(0,O);for(let[o,e]of n){let r=L(e[C]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,O),{paragraphs:n}=e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=L(r[C]);if(!i?.selection)continue;let d=y=>{let x=n.get(y.paragraphId);if(!x)return null;let u;try{u=l.createAbsolutePositionFromRelativePosition(l.decodeRelativePosition($(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==x)return null;let f=this.port?.paragraphs().find(M=>M.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),v=d(i.selection.head);!p||!v||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(v)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(n){this.setStatus("error",n instanceof d?n.code:"shared-schema-invalid",n instanceof d?n.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let n=this.participants();for(let o of [...this.participantListeners])o(n);};publishAwareness(t){let n={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(C,n);}validateParagraphSet(t){let{paragraphs:n}=e(this.ydoc),o=t.paragraphs();if(o.length!==n.size||o.some(e=>!n.has(e.paragraphId)||!(n.get(e.paragraphId)instanceof l.Text)||n.get(e.paragraphId).length>I))throw new d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:n}=e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new d("unsupported-root-key");if(t.get("protocolVersion")!==a||t.get("schemaVersion")!==b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new d("immutable-metadata-changed");let e$1=t.get("baseline");if(!(e$1 instanceof Uint8Array)||e$1.byteLength!==this.baseline.bytes.byteLength||e$1.some((r,i)=>r!==this.baseline.bytes[i]))throw new d("immutable-baseline-changed");for(let[r,i]of n)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l.Text)||i.length>I)throw new d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:n}=e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=n.get(o.paragraphId);if(!e)throw new d("paragraph-set-mismatch");H(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:n}=e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=n.get(e.paragraphId);if(!r)throw new d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new d(isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof d?o.code:"remote-apply-failed",o instanceof d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,n,o){if(!this.statusState.set(t,n,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function J(a,t,n){if(a.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(a.bootstrap.kind==="create"){let o=f(a.bootstrap.document,t);return await g(a.ydoc,t,n.actorId,o),h$1(a.ydoc,t)}return await i(a.ydoc,a.bootstrap.timeoutMs??D,a.bootstrap.signal),h$1(a.ydoc,t)}async function Z(a){let t=F(a.documentId),n=N(a.sessionId),o=B(a.identity),e=await J(a,t,o),r=new w(a.ydoc,a.awareness,t,n,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}
2
- export{Z as createTextCollaboration};
1
+ export{b as collaborationModule}from'../chunk-Q2VBO66F.js';import {j,d,l as l$1,f,g,h as h$1,i,e,a,b}from'../chunk-HMTYXNMO.js';export{d as CollaborationSchemaError,j as DOCUMENT_COLLABORATION_VERSIONS,c as MAX_BASELINE_BYTES,a as PROTOCOL_VERSION,b as SCHEMA_VERSION,k as assertDocumentCollaborationCompatibility,p as createDocumentCollaboration,n as readCollaborationDocument,m as readCollaborationResourceUsage}from'../chunk-HMTYXNMO.js';import*as l from'yjs';import {ORIGIN_IDS}from'@docx-editor.dev/core/store';import {createCollaborationStatusTracker,isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var w="docxEditor",h=256,L=256,v=1e6,$=3e4;function X(n){let t=n.actorId.trim(),a=n.name.trim();if(t.length===0||t.length>h||a.length===0||a.length>h)throw new d("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new d("invalid-identity-color");return Object.freeze({actorId:t,name:a,...n.color?{color:n.color}:{},role:n.role??"human"})}function G(n){let t=n.trim();if(t.length===0||t.length>h)throw new d("invalid-document-id");return t}function J(n){let t=n?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new d("invalid-session-id");return t}function Z(n,t){let a=n.toString();if(a===t)return;let o=0;for(;o<a.length&&o<t.length&&a.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<a.length-o&&e<t.length-o&&a.charCodeAt(a.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=a.length-o-e;r>0&&n.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&n.insert(o,i);}function M(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function W(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let t=n,a=M(t.anchor),o=M(t.head);if(a&&o)return {anchor:a,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function _(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let a=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=W(t.selection);return {actorId:t.actorId,name:t.name,...a?{color:a}:{},role:o,...e?{selection:e}:{}}}function K(n){let t="";for(let a of n)t+=String.fromCharCode(a);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function q(n){let t=n.replace(/-/g,"+").replace(/_/g,"/"),a=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(a,o=>o.charCodeAt(0))}var A=class{constructor(t,a,o,e$1,r,i){this.ydoc=t;this.awareness=a;this.baseline=i;this.documentId=o,this.sessionId=e$1,this.identity=r;let{root:d,paragraphs:p}=e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),a.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,a,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(a!==void 0){this.setStatus(t,a,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let a=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===ORIGIN_IDS.mutationRemote||o.origin===ORIGIN_IDS.projection||o.origin===ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof d?e.code:"local-mirror-failed",e instanceof d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),a(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,a){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(a.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>v)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:a}=e(this.ydoc),o=(r,i)=>{let d=a.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:K(l.encodeRelativePosition(l.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e$1;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e$1={anchor:r,head:i});}this.publishAwareness(e$1);}participants(){let t=[],a=[...this.awareness.getStates().entries()].slice(0,L);for(let[o,e]of a){let r=_(e[w]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,L),{paragraphs:a}=e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=_(r[w]);if(!i?.selection)continue;let d=y=>{let T=a.get(y.paragraphId);if(!T)return null;let u;try{u=l.createAbsolutePositionFromRelativePosition(l.decodeRelativePosition(q(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==T)return null;let f=this.port?.paragraphs().find(U=>U.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),x=d(i.selection.head);!p||!x||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(x)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(a){this.setStatus("error",a instanceof d?a.code:"shared-schema-invalid",a instanceof d?a.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let a=this.participants();for(let o of [...this.participantListeners])o(a);};publishAwareness(t){let a={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(w,a);}validateParagraphSet(t){let{paragraphs:a}=e(this.ydoc),o=t.paragraphs();if(o.length!==a.size||o.some(e=>!a.has(e.paragraphId)||!(a.get(e.paragraphId)instanceof l.Text)||a.get(e.paragraphId).length>v))throw new d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:a$1}=e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new d("unsupported-root-key");if(t.get("protocolVersion")!==a||t.get("schemaVersion")!==b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new d("immutable-metadata-changed");let e$1=t.get("baseline");if(!(e$1 instanceof Uint8Array)||e$1.byteLength!==this.baseline.bytes.byteLength||e$1.some((r,i)=>r!==this.baseline.bytes[i]))throw new d("immutable-baseline-changed");for(let[r,i]of a$1)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l.Text)||i.length>v)throw new d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:a}=e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=a.get(o.paragraphId);if(!e)throw new d("paragraph-set-mismatch");Z(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:a}=e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=a.get(e.paragraphId);if(!r)throw new d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new d(isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof d?o.code:"remote-apply-failed",o instanceof d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,a,o){if(!this.statusState.set(t,a,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function Q(n,t,a){if(n.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(n.bootstrap.kind==="create"){let o=f(n.bootstrap.document,t);return await g(n.ydoc,t,a.actorId,o),h$1(n.ydoc,t)}return await i(n.ydoc,n.bootstrap.timeoutMs??$,n.bootstrap.signal),h$1(n.ydoc,t)}async function tt(n){let t=G(n.documentId),a=J(n.sessionId),o=X(n.identity),e=await Q(n,t,o),r=new A(n.ydoc,n.awareness,t,a,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}var D=["protocolVersion","sharedSchemaVersion","repairVersion","canonicalModelVersion"];function Y(n){return `docx-collaboration:${n.join(".")}`}var F=Y(D.map(n=>j[n]));function et(n){if(n!==F)throw new d("collaboration-format-mismatch","The collaboration format version is missing or incompatible with this deployment.")}function ot(n){if(!n.share.has(l$1))throw new d("not-initialized");let t;try{t=n.getMap(l$1);}catch{throw new d("collaboration-format-mismatch","The saved room has invalid collaboration version information.")}if(t.get("initialized")!==true||typeof t.get("documentId")!="string")throw new d("not-initialized");let a=D.map(o=>{let e=t.get(o);if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new d("collaboration-format-mismatch","The saved room has missing or invalid collaboration version information.");return e});return Y(a)}
2
+ export{F as COLLABORATION_FORMAT_VERSION,et as assertCollaborationFormatCompatibility,tt as createTextCollaboration,ot as readCollaborationFormatVersion};
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),chunkDOVUXFIP_cjs=require('../chunk-DOVUXFIP.cjs'),F=require('yjs'),awareness=require('y-protocols/awareness'),yWebrtc=require('y-webrtc');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 F__namespace=/*#__PURE__*/_interopNamespace(F);var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=chunkLUUFBXJ5_cjs.b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F__namespace.Doc,d=new awareness.Awareness(o),c=null,l=()=>{},f=()=>{let u=new yWebrtc.WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await chunkDOVUXFIP_cjs.m({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b,destroy(){S||(S=true,b.off("status",h),s.destroy(),b.destroy(),d.destroy(),o.destroy());}})}
1
+ 'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),chunkEFCL3VQI_cjs=require('../chunk-EFCL3VQI.cjs'),F=require('yjs'),awareness=require('y-protocols/awareness'),yWebrtc=require('y-webrtc');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 F__namespace=/*#__PURE__*/_interopNamespace(F);var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=chunkLUUFBXJ5_cjs.b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F__namespace.Doc,d=new awareness.Awareness(o),c=null,l=()=>{},f=()=>{let u=new yWebrtc.WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await chunkEFCL3VQI_cjs.p({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b,destroy(){S||(S=true,b.off("status",h),s.destroy(),b.destroy(),d.destroy(),o.destroy());}})}
2
2
  Object.defineProperty(exports,"createCollaborationRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.a}});Object.defineProperty(exports,"validateRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.b}});exports.DEMO_SIGNALING_ENDPOINTS=W;exports.createWebrtcCollaboration=ee;exports.resetDemoSignalingWarningForTests=V;exports.resolveWebrtcRoomPassword=X;exports.warnOnDemoSignalingFallback=H;
@@ -1,2 +1,2 @@
1
- import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {m}from'../chunk-3625DZUE.js';import*as F from'yjs';import {Awareness}from'y-protocols/awareness';import {WebrtcProvider}from'y-webrtc';var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F.Doc,d=new Awareness(o),c=null,l=()=>{},f=()=>{let u=new WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await m({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b$1=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b$1.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b$1,destroy(){S||(S=true,b$1.off("status",h),s.destroy(),b$1.destroy(),d.destroy(),o.destroy());}})}
1
+ import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {p}from'../chunk-HMTYXNMO.js';import*as F from'yjs';import {Awareness}from'y-protocols/awareness';import {WebrtcProvider}from'y-webrtc';var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F.Doc,d=new Awareness(o),c=null,l=()=>{},f=()=>{let u=new WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await p({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b$1=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b$1.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b$1,destroy(){S||(S=true,b$1.off("status",h),s.destroy(),b$1.destroy(),d.destroy(),o.destroy());}})}
2
2
  export{W as DEMO_SIGNALING_ENDPOINTS,ee as createWebrtcCollaboration,V as resetDemoSignalingWarningForTests,X as resolveWebrtcRoomPassword,H as warnOnDemoSignalingFallback};
@@ -0,0 +1 @@
1
+ export{c as ATTACH_WATCHDOG_MS_FOR_TESTS,d as createDocumentCollaboration,b as readCollaborationDocument}from'./chunk-OZT67MLG.js';
@@ -0,0 +1 @@
1
+ 'use strict';var chunk4NIIGM6D_cjs=require('./chunk-4NIIGM6D.cjs');Object.defineProperty(exports,"ATTACH_WATCHDOG_MS_FOR_TESTS",{enumerable:true,get:function(){return chunk4NIIGM6D_cjs.c}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunk4NIIGM6D_cjs.d}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunk4NIIGM6D_cjs.b}});
@@ -0,0 +1 @@
1
+ export{o as ATTACH_WATCHDOG_MS_FOR_TESTS,p as createDocumentCollaboration,n as readCollaborationDocument}from'./chunk-HMTYXNMO.js';
@@ -0,0 +1 @@
1
+ 'use strict';var chunkEFCL3VQI_cjs=require('./chunk-EFCL3VQI.cjs');Object.defineProperty(exports,"ATTACH_WATCHDOG_MS_FOR_TESTS",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.o}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.p}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunkEFCL3VQI_cjs.n}});
@@ -0,0 +1 @@
1
+ 'use strict';var chunkLUUFBXJ5_cjs=require('./chunk-LUUFBXJ5.cjs'),chunk4NIIGM6D_cjs=require('./chunk-4NIIGM6D.cjs'),P=require('yjs'),awareness=require('y-protocols/awareness'),provider=require('@hocuspocus/provider'),collaboration=require('@docx-editor.dev/core/collaboration');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 P__namespace=/*#__PURE__*/_interopNamespace(P);var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new provider.HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new chunk4NIIGM6D_cjs.a(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new chunk4NIIGM6D_cjs.a("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d=chunkLUUFBXJ5_cjs.b(o.roomId),c=o[O]??F,n=new P__namespace.Doc,r=new awareness.Awareness(n),s=()=>c({url:o.url,name:d,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await chunk4NIIGM6D_cjs.d({ydoc:n,awareness:r,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",collaboration.isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b||(b=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}Object.defineProperty(exports,"createCollaborationRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.a}});Object.defineProperty(exports,"validateRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.b}});exports.HOCUSPOCUS_PROVIDER_FOR_TESTS=O;exports.createHocuspocusCollaboration=_;
@@ -0,0 +1 @@
1
+ import {b}from'./chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'./chunk-6DEUT2RQ.js';import {d,a}from'./chunk-OZT67MLG.js';import*as P from'yjs';import {Awareness}from'y-protocols/awareness';import {HocuspocusProvider}from'@hocuspocus/provider';import {isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new a(isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new a("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d$1=b(o.roomId),c=o[O]??F,n=new P.Doc,r=new Awareness(n),s=()=>c({url:o.url,name:d$1,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await d({ydoc:n,awareness:r,documentId:d$1,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b$1=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b$1||(b$1=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}export{O as HOCUSPOCUS_PROVIDER_FOR_TESTS,_ as createHocuspocusCollaboration};