@reviseio/engine 3.0.1 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/assets/{historyMaterializeWorker-Kl0syEbc.js → historyMaterializeWorker-BMHTnStL.js} +131 -130
- package/chunks/{AgentHtmlConverter-CnnB8-WI.js → AgentHtmlConverter-B5qstcmM.js} +129 -128
- package/chunks/{AgentPageRenderer-DLgUGrGy.js → AgentPageRenderer-JMhCw-hi.js} +4 -4
- package/chunks/BlockDiff-C8eiZ-sf.js +45 -0
- package/chunks/{CanvasRenderer-C1Vegx9Y.js → CanvasRenderer-C2vAzLWM.js} +12 -12
- package/chunks/DocumentCompare-DX4RWeSV.js +10 -0
- package/chunks/{DocumentLayoutEngine-C62pyGVf.js → DocumentLayoutEngine-BhcWXkeu.js} +45 -45
- package/chunks/{DocumentMutator-Bat_oLBQ.js → DocumentMutator-FEFU1YM0.js} +6 -6
- package/chunks/DocumentOutline-BOZoTohH.js +4 -0
- package/chunks/{DocumentScrubber-BZQn_z92.js → DocumentScrubber-C4N3Qagm.js} +1 -1
- package/chunks/{DocumentSession-BDcazSEv.js → DocumentSession-gZHWP7By.js} +1 -1
- package/chunks/{DocxConverter-BC31uYIL.js → DocxConverter-BOyLn5eZ.js} +709 -703
- package/chunks/{DocxGraft-L10HXM3U.js → DocxGraft-BbE-AaM5.js} +2 -2
- package/chunks/{HtmlConverter-C5ihhZ6G.js → HtmlConverter-BlzwsPEn.js} +3 -3
- package/chunks/MarkdownConverter-BHVskVXI.js +59 -0
- package/chunks/{OdtConverter-c1fTWoAt.js → OdtConverter-BdmBFOD1.js} +1 -1
- package/chunks/{OfficeImportShared-CrOpHpJ-.js → OfficeImportShared-B2XJgnDO.js} +4 -4
- package/chunks/{PdfConverter-DX7fsRH5.js → PdfConverter-DZMCHDAo.js} +6 -6
- package/chunks/{RtfConverter-hbJ2529G.js → RtfConverter-RqE-xZcW.js} +2 -2
- package/chunks/{TableBorders-DVhdvo6f.js → TableBorders-ARyTi49V.js} +1 -1
- package/chunks/{TxtConverter-YHv5FXWb.js → TxtConverter-EPQtb6A6.js} +1 -1
- package/chunks/{Typography-B4gndEdB.js → Typography-XR6scRNV.js} +9 -9
- package/chunks/{XmlConverter-BRRluy9k.js → XmlConverter-9sFRFaza.js} +1 -1
- package/chunks/{capture-i_dPkQIS.js → capture-DhGn0CWA.js} +1 -1
- package/chunks/{carrier-pYM9xf6x.js → carrier-D58g-gw4.js} +1 -1
- package/chunks/{chromeImageLayout-BiQ3Iz1-.js → chromeImageLayout-DeYYS8YP.js} +1 -1
- package/chunks/{engine-LMUnxdm2.js → engine-C5fxuZJo.js} +139 -139
- package/chunks/{footnoteFlatten-EE85Hjre.js → footnoteFlatten-coCVFd3c.js} +1 -1
- package/chunks/{graftExport-G-dG7Vcc.js → graftExport-FBGE2qvt.js} +1 -1
- package/chunks/{index-BLb10wQt.js → index-Cezk1s_y.js} +4 -4
- package/chunks/{serverDocumentSession-DGDU5Lh3.js → serverDocumentSession-LMu3kocH.js} +559 -560
- package/chunks/{signatures-DTNDS2PH.js → signatures-DsJnnIqV.js} +1 -1
- package/chunks/textExtraction-Bqaqt1Kg.js +2 -0
- package/engine.js +2 -2
- package/package.json +2 -2
- package/chunks/BlockDiff-B6-aJxHo.js +0 -42
- package/chunks/DocumentCompare-C8295s35.js +0 -6
- package/chunks/MarkdownConverter-DofaSeC4.js +0 -57
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{r as h,o as f}from"./ListNumbering-Qlu6AuRZ.js";import{e as p}from"./textExtraction-Bqaqt1Kg.js";function m(d,l){const t=e=>p({...e,children:e.children.filter(i=>!i.marks?.deletion)}).replace(/\s+/g,
|
|
2
|
+
" ").trim(),r=d.children.flatMap((e,i)=>{if(e.type==="paragraph"&&e.heading)return[{index:i,level:e.heading,blockId:e.id,itemId:void 0,title:t(e)}];if(e.type!=="list"||!e.children.some(n=>n.heading))return[];
|
|
3
|
+
const a=e.variant==="ordered"?h(d).get(e.id):void 0,o=a?f(e,a):[];return e.children.flatMap((n,c)=>n.heading?[{index:i,level:n.heading,blockId:e.id,itemId:n.id,title:[o[c],t(n)].filter(Boolean).join("\
|
|
4
|
+
")}]:[])});return r.filter(e=>e.level<=(l?.maxDepth??6)).map(e=>({...e,endIndex:(r.find(i=>i.index>e.index&&(l?.flat||i.level<=e.level))?.index??d.children.length)-1}))}export{m as documentHeadingSections};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{D as A}from"./DocumentMutator-
|
|
1
|
+
import{D as A}from"./DocumentMutator-FEFU1YM0.js";import{y as N,b as S,d as v}from"./engine-C5fxuZJo.js";const i="Author",l=e=>{const s=[e.children];e.notes&&s.push(e.notes),e.chrome&&s.push(e.chrome);
|
|
2
2
|
for(const t of[e.headers,e.footers])if(t)for(const c of Object.values(t))Array.isArray(c)&&s.push(c);return s},g=(e,s)=>{s(e);for(const t of e)t&&Array.isArray(t.children)&&g(t.children,s)},h=(e,s)=>{
|
|
3
3
|
for(const t of l(e))g(t,c=>{for(const a of c)a?.type==="text"&&s(a)})},y=e=>{e.marks&&Object.keys(e.marks).length===0&&delete e.marks},P=e=>{const s=new Set,t=c=>{typeof c=="string"&&c.length>0&&s.add(
|
|
4
4
|
c)};for(const c of l(e))g(c,a=>{for(const o of a){if(!o||typeof o!="object")continue;t(o.suggestionId),t(o.structuralSuggestionId);for(const n of["structuralSuggestionRecord","structuralSuggestionReco\
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as x,y as k,l as w,d as O,o as P,m as F}from"./engine-LMUnxdm2.js";import{D,P as R,x as z}from"./DocumentMutator-Bat_oLBQ.js";import{i as E}from"./suggestionAuthorship-B-IuLQlE.js";import{s as N}from"./carrier-pYM9xf6x.js";import*as b from"yjs";class H{constructor(t=50){this.tasks=new Map,this.intervalId=null,this.tickMs=t}schedule(t,e,s){const n=Date.now();this.tasks.set(t,{id:t,callback:s,delay:e,lastScheduledAt:n}),this.intervalId===null&&(this.intervalId=window.setInterval(()=>this.tick(),this.tickMs))}cancel(t){this.tasks.delete(t)&&this.tasks.size===0&&this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null)}tick(){const t=Date.now();for(const e of this.tasks.values())if(t-e.lastScheduledAt>=e.delay){this.tasks.delete(e.id);try{e.callback()}catch(s){console.error("[DebouncedTaskScheduler] Task error",s)}}this.tasks.size===0&&this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null)}}const W=new H;function q(u,t,e){W.schedule(u,t,e)}function L(u){if(typeof atob=="function"){const t=atob(u),e=new Uint8Array(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}return Uint8Array.from(Buffer.from(u,"base64"))}function T(u,t){const e=b;if(typeof e.applyUpdateV2=="function")try{e.applyUpdateV2(u,t)}catch(s){console.warn("[historyReplay] Failed to apply V2 update:",s)}}function A(u,t){try{b.applyUpdate(u,t),x(u)||T(u,t)}catch{T(u,t)}}function j(u,t,e=-1){const s=new b.Doc({gc:!1});A(s,L(u));const n=e<0?t.length:e;for(let i=0;i<n&&i<t.length;i++)A(s,L(t[i]));return s}class ${constructor(){this.worker=null,this.workerFailed=!1,this.nextRequestId=1,this.pendingRequests=new Map}async init(){if(!(this.worker||this.workerFailed))try{if(typeof window>"u"||typeof Worker>"u"){this.workerFailed=!0;return}this.worker=new Worker(new URL(""+new URL("../assets/historyMaterializeWorker-Kl0syEbc.js",import.meta.url).href,import.meta.url)),this.worker.onmessage=t=>{const e=t.data,s=this.pendingRequests.get(e.id);if(s){if(this.pendingRequests.delete(e.id),!e.success){s.reject(new Error(e.error||"Worker request failed"));return}e.kind==="filterDistinct"?s.resolve(e.distinctIds??[]):e.doc?s.resolve(e.doc):s.reject(new Error("Materialization failed"))}},this.worker.onerror=t=>{console.warn("[HistoryMaterializer] Worker error:",t);for(const[e,s]of this.pendingRequests)s.reject(new Error("Worker error")),this.pendingRequests.delete(e);this.workerFailed=!0,this.worker?.terminate(),this.worker=null}}catch(t){console.warn("[HistoryMaterializer] Failed to create worker:",t),this.workerFailed=!0}}async materialize(t,e,s=-1){if(await this.init(),this.worker&&!this.workerFailed)try{return await this.materializeViaWorker(t,e,s)}catch(n){console.warn("[HistoryMaterializer] Worker materialization failed, falling back:",n)}return this.materializeSync(t,e,s)}async computeDistinctContentIds(t,e){if(e.length===0)return[];if(await this.init(),!this.worker||this.workerFailed)return null;try{return await new Promise((s,n)=>{if(!this.worker){n(new Error("Worker not available"));return}const i=this.nextRequestId++;this.pendingRequests.set(i,{resolve:s,reject:n});const r={id:i,kind:"filterDistinct",segments:t,candidateIds:e};this.worker.postMessage(r),setTimeout(()=>{this.pendingRequests.has(i)&&(this.pendingRequests.delete(i),n(new Error("Worker timeout")))},6e4)})}catch(s){return console.warn("[HistoryMaterializer] Distinct-frame filtering failed:",s),null}}materializeToYDoc(t,e,s=-1){return j(t,e,s)}materializeViaWorker(t,e,s){return new Promise((n,i)=>{if(!this.worker){i(new Error("Worker not available"));return}const r=this.nextRequestId++;this.pendingRequests.set(r,{resolve:n,reject:i});const o={id:r,snapshotB64:t,updatesB64:e,uptoIndex:s};this.worker.postMessage(o),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),i(new Error("Worker timeout")))},3e4)})}materializeSync(t,e,s){const n=this.materializeToYDoc(t,e,s);try{return k(n)}finally{n.destroy()}}dispose(){for(const[,t]of this.pendingRequests)t.reject(new Error("Materializer disposed"));this.pendingRequests.clear(),this.worker?.terminate(),this.worker=null}isWorkerAvailable(){return this.worker!==null&&!this.workerFailed}}const v=new $,C="https://app-api.revise-sdk.invalid";class V{constructor(t=20){this.cache=new Map,this.maxSize=t}get(t){const e=this.cache.get(t);return e&&(this.cache.delete(t),this.cache.set(t,e)),e}set(t,e){if(this.cache.size>=this.maxSize&&!this.cache.has(t)){const s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.delete(t),this.cache.set(t,e)}clear(){this.cache.clear()}}class K{constructor(t,e,s){this.tailDebounceMs=1200,this.docCache=new V,this.totalUpdates=0,this.segments=[],this.loaded=!1,this.maxEndLoaded=0,this.loadLock=null,this.targetLocks=new Map,this.blobLocks=new Map,this.abortController=null,this.contentIds=[],this.updateTimestamps=new Map,this.contentTimestamps=[],this.chunkEndUpdateIds=[],this.chunkSegIdx=[],this.distinctContentIds=null,this.distinctSignature=null,this.changeObservers=[],this.disposed=!1,this.documentId=t,this.authToken=s?.authToken,this.tailTaskId=`history-tail-${Math.random().toString(36).slice(2)}`,this.abortController=new AbortController}onChange(t){return this.changeObservers.push(t),()=>{const e=this.changeObservers.indexOf(t);e>=0&&this.changeObservers.splice(e,1)}}async ensureLoaded(){if(this.loaded)return!0;if(this.disposed)return!1;if(!this.supportsServerHistory())return this.loaded=!0,!0;try{const t=`${C}/documents/${this.documentId}/history`,e=await this.fetchJson(t);return this.totalUpdates=this.readTotalUpdates(e),this.segments=this.parseFrames(e.frames),this.loaded=!0,this.recomputeDerivedData(),this.notifyChange(),!0}catch(t){return console.error("[UpdateHistoryManager] Failed to load update history:",{documentId:this.documentId,error:t instanceof Error?t.message:String(t)}),!1}}notifyDocUpdated(){this.disposed||!this.loaded||q(this.tailTaskId,this.tailDebounceMs,()=>{this.refreshNewSegments()})}dispose(){this.disposed=!0,this.abortController?.abort(),this.abortController=null,this.changeObservers=[],this.docCache.clear(),this.segments=[],this.updateTimestamps.clear()}getTotalUpdates(){const t=this.segments[this.segments.length-1],e=this.contentIds[this.contentIds.length-1]??0;return Math.max(this.totalUpdates,t?.endUpdateId??0,e)}getContentCount(){return this.contentIds.length}getContentUpdateIds(){return this.contentIds.slice()}getDistinctContentUpdateIds(){return this.distinctContentIds&&this.distinctSignature===this.contentIdsSignature()?this.distinctContentIds.slice():null}contentIdsSignature(){const t=this.contentIds;return`${t.length}:${t[t.length-1]??0}`}async ensureDistinctFramesComputed(){}getWorkChunkCount(){return this.chunkEndUpdateIds.length}getWorkChunkEndUpdateIds(){return this.chunkEndUpdateIds.slice()}getTimestampForUpdateId(t){const e=this.updateTimestamps.get(Math.floor(t));return e&&Number.isFinite(e)&&e>0?e:null}getContentTimeline(){return{count:this.contentIds.length,timestamps:this.contentTimestamps.slice()}}getTimeAxisTicks(){let t;if(this.contentTimestamps.length>0?t=this.contentTimestamps.filter(d=>Number.isFinite(d)&&d>0):(t=Array.from(this.updateTimestamps.values()).filter(d=>Number.isFinite(d)&&d>0),t.sort((d,I)=>d-I)),t.length===0)return null;const e=t[0],s=t[t.length-1],n=s-e;if(n<=0)return{startTs:e,endTs:s,ticksTs:[]};const i=6e4,r=60*i,o=24*r,a=7*o;let c;n<r?c=5*i:n<o?c=r:n<30*o?c=o:c=a;const m=Math.floor(e/c)*c,y=[];let f=0,l=0;for(let d=m+c;d<s;d+=c){const I=d-c;for(;f<t.length&&t[f]<=I;)f++;for(l=Math.max(l,f);l<t.length&&t[l]<=d;)l++;l>f&&d>e&&y.push(d)}return{startTs:e,endTs:s,ticksTs:y}}getPauseMarkersForContent(t,e=10){const s=this.contentTimestamps;if(s.length<=1)return[];const n=Math.max(0,s[s.length-1]-s[0]);if(n<=0||t<=0)return[];const i=n*Math.max(1,e)/Math.max(1,t),r=[];let o=-1/0;for(let a=0;a<s.length-1;a++)s[a+1]-s[a]>=i&&s[a]-o>=i&&(r.push(a+1),o=s[a]);return r}async findLatestUpdateIdBeforeTimestamp(t){if(!await this.ensureLoaded()||!Number.isFinite(t)||t<=0||this.updateTimestamps.size===0)return null;const e=Array.from(this.updateTimestamps.entries()).filter(([,r])=>r>0).sort((r,o)=>r[1]-o[1]);if(e.length===0)return null;let s=0,n=e.length-1,i=null;for(;s<=n;){const r=s+n>>1;e[r][1]<=t?(i=e[r][0],s=r+1):n=r-1}return i??e[0][0]}async materializeAtContentIndex(t,e){if(!await this.ensureLoaded()||this.contentIds.length===0)return null;const s=Math.max(1,Math.min(this.contentIds.length,t));return this.materializeAt(this.contentIds[s-1],e)}async materializeAt(t,e){if(!await this.ensureLoaded()||this.segments.length===0)return null;const s=e?.excludePendingSuggestions===!0;t=Math.max(1,Math.min(this.getTotalUpdates(),t));const n=s?`update-${t}-accepted-only`:`update-${t}`,i=this.docCache.get(n);if(i)return i;await this.ensureHasSegmentFor(t);let r=this.getPlanForUpdateId(t);if(!r)return null;if(await this.ensureBlobsForSegmentStart(r.seg.startUpdateId),r=this.getPlanForUpdateId(t),!r?.seg.snapshotB64)return console.warn("[UpdateHistoryManager] Missing snapshot for segment",r?.seg.startUpdateId),null;const{seg:o}=r;try{const a=Math.min(o.updatesB64.length,o.frameOnly?o.updatesB64.length:t-o.startUpdateId+1);let c;if(s){const m=v.materializeToYDoc(o.snapshotB64,o.updatesB64,a);try{const y=D.createSuggestionProjectionFromYDoc(m,"reject");try{c=y.doc}finally{y.ydoc.destroy()}}finally{m.destroy()}}else c=await v.materialize(o.snapshotB64,o.updatesB64,a);return c&&this.docCache.set(n,c),c}catch(a){return console.error("[UpdateHistoryManager] Materialize failed:",{updateId:t,segmentRange:`${o.startUpdateId}-${o.endUpdateId}`,error:a instanceof Error?a.message:String(a)}),null}}async materializeChunkEnd(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const s=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),n=e?.excludePendingSuggestions===!0?`chunk-end-${t}-accepted-only`:`chunk-end-${t}`,i=this.docCache.get(n);if(i)return i;const r=this.segments[this.chunkSegIdx[s]];await this.ensureBlobsForSegmentStart(r.startUpdateId);const o=await this.materializeAt(r.endUpdateId,e);return o&&this.docCache.set(n,o),o}async materializeChunkSnapshot(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const s=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),n=this.segments[this.chunkSegIdx[s]];if(await this.ensureBlobsForSegmentStart(n.startUpdateId),!n.snapshotB64)return null;if(e?.excludePendingSuggestions){const i=v.materializeToYDoc(n.snapshotB64,[],0);try{const r=D.createSuggestionProjectionFromYDoc(i,"reject");try{return r.doc}finally{r.ydoc.destroy()}}finally{i.destroy()}}return v.materialize(n.snapshotB64,[],0)}async materializeChunkPair(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const s=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),n=this.segments[this.chunkSegIdx[s]];await this.ensureBlobsForSegmentStart(n.startUpdateId);const i=await this.materializeAt(n.endUpdateId,e);if(!i)return null;if(s>0){const o=this.segments[this.chunkSegIdx[s-1]];await this.ensureBlobsForSegmentStart(o.startUpdateId);const a=await this.materializeAt(o.endUpdateId,e);if(a)return{base:a,target:i}}if(!n.snapshotB64)return null;const r=await this.materializeChunkSnapshot(t,e);return r?{base:r,target:i}:null}__getPlanForTest(t){return this.getPlanForUpdateId(t)}supportsServerHistory(){return this.documentId.length>8}async fetchJson(t){if(this.disposed)throw new Error("Manager disposed");const e={};this.authToken&&(e.Authorization=`Bearer ${this.authToken}`);const s=await fetch(t,{headers:e,credentials:"omit",signal:this.abortController?.signal});if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}readTotalUpdates(t){const e=Number(t.totalUpdates);return!Number.isFinite(e)||e<=0?this.totalUpdates:e}parseFrames(t){return t?t.filter(e=>Number.isFinite(e.updateId)&&Number.isFinite(e.sourceId)&&(e.source==="legacy"||e.source==="delta")).map(e=>({startUpdateId:Number(e.updateId),endUpdateId:Number(e.updateId),snapshotB64:"",updatesB64:[],meta:[{ts:Number(e.timestamp||0),content:!0,userId:e.userId??null,agentName:e.agentName??null}],frameSource:e.source,frameSourceId:Number(e.sourceId),frameOnly:!0})).sort((e,s)=>e.startUpdateId-s.startUpdateId):[]}async refreshNewSegments(){!this.supportsServerHistory()||this.disposed||!this.loaded||await this.withLoadLock(async()=>{const t=`${C}/documents/${this.documentId}/history`;try{const e=await this.fetchJson(t);this.totalUpdates=this.readTotalUpdates(e),this.segments=this.parseFrames(e.frames),this.recomputeDerivedData(),this.notifyChange()}catch(e){e.name!=="AbortError"&&console.warn("[UpdateHistoryManager] Failed to refresh segments:",e)}})}async ensureHasSegmentFor(t){if(!this.supportsServerHistory()||this.disposed||this.segments.some(n=>n.startUpdateId<=t&&t<=n.endUpdateId))return;const e=this.targetLocks.get(t);if(e)return e;const s=this.fetchSegmentContaining(t).finally(()=>{this.targetLocks.delete(t)});this.targetLocks.set(t,s),await s}async fetchSegmentContaining(t){if(this.disposed)return;const e=this.getPlanForUpdateId(t)?.seg;if(!e?.frameSource||e.frameSourceId==null)return;const s=new URLSearchParams({source:e.frameSource,sourceId:String(e.frameSourceId)});e.frameSource==="legacy"&&s.set("targetUpdateId",String(t));const n=`${C}/documents/${this.documentId}/history/frame?${s.toString()}`;try{const i=await this.fetchJson(n);e.snapshotB64=i.snapshotB64||"",e.updatesB64=i.updatesB64||[]}catch(i){i.name!=="AbortError"&&console.warn("[UpdateHistoryManager] Failed to fetch segment:",{updateId:t,error:i})}}async ensureBlobsForSegmentStart(t){const e=this.segments.find(n=>n.startUpdateId===t);if(e?.snapshotB64&&Array.isArray(e.updatesB64))return;let s=this.blobLocks.get(t);s||(s=this.fetchSegmentContaining(t).finally(()=>{this.blobLocks.delete(t)}),this.blobLocks.set(t,s)),await s}async withLoadLock(t){if(this.loadLock)return this.loadLock;this.loadLock=t();try{await this.loadLock}finally{this.loadLock=null}}mergeInSegments(t){if(t.length===0)return;const e=new Map;for(const s of this.segments)e.set(s.startUpdateId,s);for(const s of t){const n=e.get(s.startUpdateId);if(!n){e.set(s.startUpdateId,s);continue}e.set(s.startUpdateId,{startUpdateId:n.startUpdateId,endUpdateId:Math.max(n.endUpdateId,s.endUpdateId),snapshotB64:n.snapshotB64||s.snapshotB64,updatesB64:(s.updatesB64?.length||0)>=(n.updatesB64?.length||0)?s.updatesB64:n.updatesB64,meta:(s.meta?.length||0)>=(n.meta?.length||0)?s.meta:n.meta,frameSource:s.frameSource||n.frameSource,frameSourceId:s.frameSourceId??n.frameSourceId,frameOnly:s.frameOnly||n.frameOnly})}this.segments=Array.from(e.values()).sort((s,n)=>s.startUpdateId-n.startUpdateId),this.maxEndLoaded=0;for(const s of this.segments)s.endUpdateId>this.maxEndLoaded&&(this.maxEndLoaded=s.endUpdateId)}getPlanForUpdateId(t){if(this.segments.length===0)return null;let e=this.segments.find(n=>n.startUpdateId<=t&&t<=n.endUpdateId);if(!e){const n=this.segments[0],i=this.segments[this.segments.length-1];if(t<n.startUpdateId)e=n;else if(t>i.endUpdateId)e=i;else for(let r=0;r<this.segments.length-1;r++)if(t>this.segments[r].endUpdateId&&t<this.segments[r+1].startUpdateId){e=this.segments[r];break}}if(!e)return null;const s=Math.max(0,Math.min(e.updatesB64.length,t-e.startUpdateId+1));return{seg:e,upto:s}}recomputeDerivedData(){this.docCache.clear(),this.recomputeContentIds(),this.recomputeTimestamps(),this.recomputeChunks()}recomputeContentIds(){const t=[];for(let e=0;e<this.segments.length;e++){const s=this.segments[e];if(s.frameOnly){t.push(s.startUpdateId);continue}const n=s.meta,i=Math.max(s.updatesB64.length,n?.length||0),r=e<2;for(let o=0;o<i;o++)(n?.[o]?.content||r&&o===0)&&t.push(s.startUpdateId+o)}this.contentIds=t}recomputeTimestamps(){this.updateTimestamps.clear();for(const t of this.segments){const e=t.meta;if(e)for(let s=0;s<e.length;s++){const n=t.startUpdateId+s,i=Number(e[s]?.ts||0);i>0&&this.updateTimestamps.set(n,i)}}this.contentTimestamps=this.contentIds.map(t=>this.updateTimestamps.get(t)||0)}recomputeChunks(){const t=this.segments.length;if(t===0){this.chunkSegIdx=[],this.chunkEndUpdateIds=[];return}const e=[];for(let n=0;n<t;n++){if(this.segments[n].frameOnly){e.push(n);continue}const i=this.segments[n].meta,r=Array.isArray(i)&&i.some(a=>a?.content),o=n<2;(r||o)&&e.push(n)}const s=t-1;(e.length===0||e[e.length-1]!==s)&&e.push(s),this.chunkSegIdx=e,this.chunkEndUpdateIds=e.map(n=>this.segments[n].endUpdateId)}notifyChange(){if(!this.disposed)for(const t of this.changeObservers.slice())try{t()}catch(e){console.error("[UpdateHistoryManager] Observer error:",e)}}}const J=()=>{},Y=async()=>{},G=new Set;function B(u,t){for(const e of G)try{e(u,t)}catch{}}const X=new Proxy({track:(u,t)=>B(u,t),trackAgentToolInvoked:(u,t,e,s=!1)=>B("Agent Tool Invoked",{tool:u,documentId:t??void 0,directMode:s}),trackDocumentExported:(u,t,e)=>B("Document Exported",{documentId:u,format:t,source:e}),getCheckoutAttribution:()=>null,flush:Y},{get(u,t){return t in u?u[t]:J}});class U{constructor(t,e,s,n){this.isViewingRevision=!1,this.documentChangeObservers=[],this.isReadOnly=!1,this.timeTravelActive=!1,this.viewModeObservers=[],this.historyOpen=!1,this.historyDiffEnabled=!0,this.historySelection={start:null,end:null},this.historyObservers=[],this.notesObservers=[],this.notesValue="",this.cleanupCallbacks=[],this.disposed=!1,this.historyManager=null,this.sharedWriteAccess=null,this.autocorrectEnabled=!0,this.suggestionDecisionsAllowed=!0,this.documentId=t,this.sharedStyleMigrationPermit=n?.sharedStyleMigrationPermit,this.authToken=n?.authToken,this.onTitleChange=s;const i=n?.disableProposalPersistence??!!n?.authToken;if(this.preprocessorSession=new R,w(e)){const a=e;if(this.ydoc=O(a,this.sharedStyleMigrationPermit?{sharedStyles:this.sharedStyleMigrationPermit.formatGateConfirmed===!0&&this.sharedStyleMigrationPermit.exclusive===!0}:void 0),a.pendingDocxCarrier){const c=a.pendingDocxCarrier;delete a.pendingDocxCarrier,N(this.ydoc,c.bytes,{hash:c.hash})}a.pageless!==void 0&&this.ydoc.getMap("metadata").set("pageless",a.pageless),this.currentDocument=this.cloneDoc(a)}else{this.ydoc=e;const a=k(this.ydoc);this.currentDocument=this.cloneDoc(a)}z(this.ydoc),w(e)&&(this.sharedWriteAccess=!0),this.documentMutator=new D(k(this.ydoc),(a,c)=>this.updateWorkingDocument(a,c),this.onTitleChange,this.ydoc,t,i,this.preprocessorSession,{canRepairIdentity:()=>this.sharedWriteAccess===!0,deferIdentityRepair:!w(e)}),this.documentMutator.identityRepairedOnConstruct&&(this.currentDocument=this.cloneDoc(k(this.ydoc))),this.notesValue=this.documentMutator.getDocumentNotes();try{this.documentMutator.backfillLiveSuggestionTreeRecords(),this.documentMutator.reconcileFootnotes(),this.documentMutator.migrateChromeOutOfContent(),this.documentMutator.migrateNotesOutOfContent(),this.documentMutator.migrateLegacyHeaderFooterMetadata(),this.documentMutator.migrateLegacyPageNumbers()}catch{}this.backfillStylesheetSidecar(),this.cleanupCallbacks.push(P(this.ydoc,a=>{console.warn(`[DocumentSession] repaired a duplicate seed: removed ${a.removedBlocks} blocks from ${a.losingClaims} losing seed(s)`)}));const r=this.ydoc.getMap("metadata"),o=a=>{if(a.keysChanged.has("notes")){const c=this.documentMutator.getDocumentNotes();c!==this.notesValue&&(this.notesValue=c,this.notifyNotesObservers())}};if(r.observe(o),this.cleanupCallbacks.push(()=>r.unobserve(o)),!n?.disableHistory){this.historyManager=new K(this.documentId,this.ydoc,{authToken:this.authToken});const a=()=>{this.historyManager?.notifyDocUpdated()};this.ydoc.on("update",a),this.cleanupCallbacks.push(()=>this.ydoc.off("update",a))}}static fromDocRoot(t,e){return new U("no-id",t,e)}getDocumentId(){return this.documentId}dispose(){if(!this.disposed){this.disposed=!0;for(const t of this.cleanupCallbacks.splice(0))t();this.documentMutator.dispose(),this.historyManager?.dispose(),this.historyManager=null,this.documentChangeObservers=[],this.viewModeObservers=[],this.historyObservers=[],this.notesObservers=[]}}setReadOnly(){this.isReadOnly=!0}setReadWrite(){this.isReadOnly=!1}setSharedWriteAccess(t){const e=t&&this.sharedWriteAccess!==!0;this.sharedWriteAccess=t,e&&this.documentMutator.repairDocumentIdentity()&&this.notifyDocumentChange(this.documentMutator.getDocument(),{origin:"local"}),e&&this.sharedStyleMigrationPermit&&(F(this.ydoc,this.sharedStyleMigrationPermit),this.sharedStyleMigrationPermit=void 0)}setSuggestingMode(t){this.documentMutator.setSuggestingMode(t)}setDocxRoundTripRequired(t){this.documentMutator.docxRoundTripRequired=t}isSuggestingMode(){return this.documentMutator.isSuggestingMode()}getWorkingDocument(){return this.documentMutator.getDocument()}getDocumentWithoutPendingSuggestions(){return this.documentMutator.getLiveSuggestionIds().length>0?this.documentMutator.getDocumentWithRejectedSuggestions():this.getWorkingDocument()}getWorkingDocumentBeforePendingReview(){return this.getDocumentWithoutPendingSuggestions()}getDocumentWithPendingSuggestionsApplied(t){if(t?.conversationId!==void 0&&this.documentMutator.setDetachedSuggestionConversation(t.conversationId??null,t.serverDetachedSuggestions),this.documentMutator.getLiveSuggestionIds().length>0)return this.documentMutator.getDocumentWithAcceptedSuggestions();const e=this.documentMutator.getDetachedSuggestionStore(),s=e.getPendingSuggestions();if(s.size===0)return this.getWorkingDocument();const n=Array.from(s.keys()),i=e.materializeWithSuggestions(n);return k(i)}getCurrentDocument(){return this.currentDocument}updateWorkingDocument(t,e={origin:"unknown"}){!this.isViewingRevision&&!this.historyOpen&&(this.currentDocument=t),this.logUnresolvableLiveSuggestions(e),this.notifyDocumentChange(this.currentDocument,e)}logUnresolvableLiveSuggestions(t){const e=this.documentMutator.getLiveSuggestionIds();if(e.length===0)return;const s=this.documentMutator.getUnresolvableLiveSuggestionRecords(),n=s.filter(i=>i.source==="agent");this.documentId,t.origin,e.length,s.length,n.length}countPrunedByKey(t,e){return t.reduce((s,n)=>{const i=n[e]||"unknown";return s[i]=(s[i]??0)+1,s},{})}trackPrunedUnresolvableLiveSuggestions(t,e,s){const n=this.documentMutator.takeLastPrunedUnresolvableLiveSuggestions();if(n.length===0)return;const i=n.filter(o=>o.source==="agent").length,r={Document:this.documentId,Action:t,RequestedSuggestionCount:new Set(e).size,ResolvedSuggestionCount:s,PrunedSuggestionCount:n.length,PrunedAgentSuggestionCount:i,PrunedSuggestionTypes:this.countPrunedByKey(n,"type"),PrunedSuggestionSources:this.countPrunedByKey(n,"source"),PrunedSuggestions:n};X.track("Live Suggestions Pruned",r)}onDocumentChange(t){return this.documentChangeObservers.push(t),()=>{const e=this.documentChangeObservers.indexOf(t);e>-1&&this.documentChangeObservers.splice(e,1)}}notifyDocumentChange(t,e={origin:"unknown"}){const s=t??this.getCurrentDocument();this.documentChangeObservers.forEach(n=>{try{n(s,e)}catch(i){console.error("Error in document change observer:",i)}})}exitRevisionView(){this.isViewingRevision=!1,this.currentDocument=this.getWorkingDocument(),this.notifyViewModeChange(),this.notifyDocumentChange()}getDocumentMutator(){return this.documentMutator}async getDocumentSnapshotAtOrBefore(t){if(!this.historyManager||!Number.isFinite(t)||t<=0)return null;const e=await this.historyManager.findLatestUpdateIdBeforeTimestamp(t);return e===null?null:this.historyManager.materializeAt(e,{excludePendingSuggestions:!0})}getDocumentNotes(){return this.notesValue}setDocumentNotes(t){if(this.isReadOnly)return;const e=typeof t=="string"?t:String(t??"");e!==this.notesValue&&(this.notesValue=e,this.documentMutator.setNotes(e),this.notifyNotesObservers())}onNotesChange(t){return this.notesObservers.push(t),()=>{const e=this.notesObservers.indexOf(t);e>=0&&this.notesObservers.splice(e,1)}}getPreprocessorSession(){return this.preprocessorSession}getRevisionManager(){return null}getYDoc(){return this.ydoc}registerRemoteOrigin(t){this.documentMutator.registerRemoteOrigin(t)}unregisterRemoteOrigin(t){this.documentMutator.unregisterRemoteOrigin(t)}setTimeTravelActive(t){this.timeTravelActive=!!t}isTimeTravelActive(){return this.timeTravelActive}onViewModeChange(t){return this.viewModeObservers.push(t),()=>{const e=this.viewModeObservers.indexOf(t);e>=0&&this.viewModeObservers.splice(e,1)}}openHistory(){this.historyOpen=!0,this.notifyHistoryChange()}closeHistory(){this.historyOpen=!1,this.notifyHistoryChange()}isHistoryOpen(){return this.historyOpen}setDiffEnabled(t){this.historyDiffEnabled=!!t,this.notifyHistoryChange()}isDiffEnabled(){return this.historyDiffEnabled}setSelection(t){this.historySelection={start:t.start??null,end:t.end??null},this.notifyHistoryChange()}getSelection(){return{...this.historySelection}}onHistoryStateChange(t){return this.historyObservers.push(t),()=>{const e=this.historyObservers.indexOf(t);e>=0&&this.historyObservers.splice(e,1)}}notifyHistoryChange(){for(const t of this.historyObservers.slice())try{t()}catch(e){console.error("[DocumentSession] History observer error:",e)}}backfillStylesheetSidecar(){try{const t=this.ydoc.getMap("metadata"),e=t.get("stylesXml");if(typeof e!="string"||e.length===0||t.get("stylesheet")!==void 0)return;import("./DocxConverter-BC31uYIL.js").then(({DocxConverter:s})=>{if(this.isReadOnly||this.isViewingRevision||t.get("stylesheet")!==void 0)return;const n=s.resolveStylesheetFromStylesXml(e,this.currentDocument.pageLayout);n&&this.ydoc.transact(()=>{t.set("stylesheet",n)})}).catch(()=>{})}catch{}}notifyNotesObservers(){const t=this.getDocumentNotes();for(const e of this.notesObservers.slice())try{e(t)}catch(s){console.error("[DocumentSession] Notes observer error:",s)}}async applySelection(t){const e=this.historyManager;if(!e||!t)return;const s=this.historyDiffEnabled,n=this.historySelection;await e.ensureLoaded();const i=e.getTotalUpdates?.()||0;if(i<=0)return;const r=h=>Math.max(1,Math.min(i,Math.floor(h))),o=async h=>await e.materializeAt?.(r(h),{excludePendingSuggestions:!0}),a=()=>this.getDocumentWithoutPendingSuggestions(),c=h=>{try{t.getEditor?.()?.setDisplayDocument?.(h)}catch(g){console.error("[DocumentSession] Failed to set display document:",g)}},m=async h=>{const g=await o(h);if(g){try{t.clearDiffPresentation?.()}catch(p){console.error("[DocumentSession] Failed to clear diff presentation:",p)}c(g)}},y=async(h,g)=>{const p=await o(h),M=await o(g);!p||!M||(t.showDiffBetweenDocuments?.(p,M),c(M))},f=async h=>{const g=await o(h),p=a();!g||!p||(t.showDiffBetweenDocuments?.(g,p),c(p))},l=n.start,d=n.end;if(l!=null&&d!=null&&l!==d){const h=r(l),g=r(d),p=Math.min(h,g),M=Math.max(h,g);s?await y(p,M):await m(M);return}const I=typeof l=="number"?l:null;if(I==null)return;const S=r(I);if(S<=1){await m(1);return}if(s)if(S===i)try{const h=await o(i),g=a();JSON.stringify(h)===JSON.stringify(g)?i>1?await y(i-1,i):await m(1):await f(i)}catch{await f(i)}else S>1?await y(S-1,S):await m(S);else await m(S)}async showDiffBetweenHistoryUpdates(t,e,s){const n=this.historyManager;if(!n||!t)return!1;const i=Math.min(e,s),r=Math.max(e,s);if(!Number.isFinite(i)||!Number.isFinite(r)||i<=0||r<=i||!await n.ensureLoaded())return!1;const o=n.getTotalUpdates?.()??0;return r>o?!1:(this.openHistory(),this.setDiffEnabled(!0),this.setSelection({start:i,end:r}),await this.applySelection(t),!0)}notifyViewModeChange(){const t=this.isViewingRevision;this.viewModeObservers.forEach(e=>{try{e(t)}catch{}})}getStorageType(){return this.ydoc.getMap("metadata").get("storageType")}getParentFolderId(){const t=this.ydoc.getMap("metadata").get("parentFolderId");return typeof t=="string"&&t.length>0?t:null}getHistoryManager(){return this.historyManager}attachDemoHistoryManager(t){this.historyManager=t}async jumpToUpdateId(t){const e=await this.historyManager?.materializeAt(t,{excludePendingSuggestions:!0});return e?(this.currentDocument=this.cloneDoc(e),this.notifyDocumentChange(),!0):!1}async jumpToContentIndex(t){const e=this.historyManager;if(!e?.materializeAtContentIndex)return!1;const s=await e.materializeAtContentIndex(t,{excludePendingSuggestions:!0});return s?(this.currentDocument=this.cloneDoc(s),this.notifyDocumentChange(),!0):!1}cloneDoc(t){return JSON.parse(JSON.stringify(t))}getPagelessMode(){return this.documentMutator.getPagelessMode()}setPagelessMode(t){this.documentMutator.setPagelessMode(t)}getPageLayoutSettings(){return this.documentMutator.getPageLayoutSettings()}setPageLayoutSettings(t){this.documentMutator.setPageLayoutSettings(t)}getIndentStepPx(){return this.documentMutator.getIndentStepPx()}setAutocorrectEnabled(t){this.autocorrectEnabled=t}isAutocorrectEnabled(){return this.autocorrectEnabled}insertText(t,e,s,n){return this.documentMutator.insertText(t,e,s,n)}getAfterOperationSelection(){return this.documentMutator.getAfterOperationSelection()}insertFormattedText(t,e,s,n,i){return this.documentMutator.insertFormattedText(t,e,s,n,i)}deleteText(t,e,s,n){return this.documentMutator.deleteText(t,e,s,n)}deleteSelection(t,e,s,n){return this.documentMutator.deleteSelection(t,e,s,n)}deleteBlock(t,e,s){return this.documentMutator.deleteBlock(t,e,s)}deleteBlockById(t,e,s){return this.documentMutator.deleteBlockById(t,e,s)}insertBlock(t,e,s,n){return this.documentMutator.insertBlock(t,e,s,n)}insertBlockAfterId(t,e,s,n){return this.documentMutator.insertBlockAfterId(t,e,s,n)}insertBlockBeforeId(t,e,s,n){return this.documentMutator.insertBlockBeforeId(t,e,s,n)}insertBlockIntoParent(t,e,s,n){return this.documentMutator.insertBlockIntoParent(t,e,s,n)}insertBlockAtStart(t,e,s){return this.documentMutator.insertBlockAtStart(t,e,s)}insertBlockAtEnd(t,e,s){return this.documentMutator.insertBlockAtEnd(t,e,s)}updateBlock(t,e,s,n){return this.documentMutator.updateBlock(t,e,s,n)}updateBlockById(t,e,s,n){return this.documentMutator.updateBlockById(t,e,s,n)}replaceParagraphById(t,e,s,n){return this.documentMutator.replaceParagraphById(t,e,s,n)}toggleTodoItem(t,e,s,n,i){return this.documentMutator.toggleTodoItem(t,e,s,n,i)}toggleTodoItemById(t,e,s,n,i){return this.documentMutator.toggleTodoItemById(t,e,s,n,i)}setListItemIndent(t,e,s,n,i){return this.documentMutator.setListItemIndent(t,e,s,n,i)}splitParagraph(t,e){return this.documentMutator.splitParagraph(t,e)}applyFormatting(t,e,s,n,i){return this.documentMutator.applyFormatting(t,e,s,n,i)}setSelectionAfterOperation(t){this.documentMutator.setSelectionAfterOperation(t)}setFontFamily(t,e,s,n){return this.documentMutator.setFontFamily(t,e,s,n)}setFontSize(t,e,s,n){return this.documentMutator.setFontSize(t,e,s,n)}setLetterSpacing(t,e,s,n){return this.documentMutator.setLetterSpacing(t,e,s,n)}setTextColor(t,e,s,n){return this.documentMutator.setTextColor(t,e,s,n)}setBackgroundColor(t,e,s,n){return this.documentMutator.setBackgroundColor(t,e,s,n)}clearFormatting(t,e,s){return this.documentMutator.clearFormatting(t,e,s)}setLink(t,e,s,n){return this.documentMutator.setLink(t,e,s,n)}setCodeBlockLanguage(t,e){return this.documentMutator.setCodeBlockLanguage(t,e)}setCodeBlockRenderDiagram(t,e){return this.documentMutator.setCodeBlockRenderDiagram(t,e)}setCodeBlockShowDiagramSource(t,e){return this.documentMutator.setCodeBlockShowDiagramSource(t,e)}setMathBlockContent(t,e){return this.documentMutator.setMathBlockContent(t,e)}setMathBlockDisplayMode(t,e){return this.documentMutator.setMathBlockDisplayMode(t,e)}setMathBlockAlign(t,e){return this.documentMutator.setMathBlockAlign(t,e)}replaceParagraph(t,e,s,n){return this.documentMutator.replaceParagraph(t,e,s,n)}pasteParagraphs(t,e,s,n={}){return this.documentMutator.pasteParagraphs(t,e,s,n)}canUndo(){return this.documentMutator.canUndo()}canRedo(){return this.documentMutator.canRedo()}undo(){return this.documentMutator.undo()}redo(t){return this.documentMutator.redo(t)}getLiveSuggestionIdsBySource(t){return this.documentMutator.getLiveSuggestionIdsBySource(t)}getLiveSuggestionIdsByCommentThread(t){return this.documentMutator.getLiveSuggestionIdsByCommentThread(t)}getInlineSuggestionMetadataFromDocument(t){return this.documentMutator.getInlineSuggestionMetadataFromDocument(t)}setSuggestionDecisionsAllowed(t){this.suggestionDecisionsAllowed=t}canDecideSuggestions(){return this.suggestionDecisionsAllowed}refusedDecision(t){return{decision:t.decision,scope:t.scope,resolvedCount:0,initialSuggestionIds:[],attemptedSuggestionIds:[],attemptedSuggestionIdCount:0,prunedSuggestions:[]}}decideLiveSuggestions(t){return this.suggestionDecisionsAllowed?this.decideLiveSuggestionsUnchecked(t):this.refusedDecision(t)}decideLiveSuggestionsUnchecked(t){const e=this.documentMutator.decideLiveSuggestions(t);return this.trackPrunedUnresolvableLiveSuggestions(t.decision,e.attemptedSuggestionIds,e.resolvedCount),e}acceptLiveSuggestions(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}acceptLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"source",source:t}})}nativeAgentLiveSuggestionIds(){return this.documentMutator.getLiveSuggestionIdsBySource("agent").filter(t=>E(this.documentMutator.getInlineSuggestionMetadataFromDocument(t)?.agentName??this.documentMutator.getLiveSuggestion(t)?.agentName))}rollbackAgentSuggestions(t){const e=this.nativeAgentLiveSuggestionIds().map(r=>{const o=this.documentMutator.getInlineSuggestionMetadataFromDocument(r),a=this.documentMutator.getLiveSuggestion(r);return{suggestionId:r,agentConversationId:o?.agentConversationId??a?.agentConversationId,agentRequestId:o?.agentRequestId??a?.agentRequestId,agentTurn:o?.agentTurn??a?.agentTurn}}).filter(r=>r.agentConversationId===t.agentConversationId&&typeof r.agentRequestId=="number"&&typeof r.agentTurn=="number"),s=t.requestId??e.reduce((r,o)=>{const a=o.agentRequestId;return a>=t.currentRequestId?r:r===void 0||a>r?a:r},void 0);if(s===void 0)return{suggestionIds:[],resolvedCount:0};const n=e.filter(r=>t.turn===void 0&&r.agentRequestId>=s||t.turn!==void 0&&r.agentRequestId===s&&r.agentTurn===t.turn).map(r=>r.suggestionId);if(n.length===0)return{requestId:s,turn:t.turn,suggestionIds:[],resolvedCount:0};const i=this.decideLiveSuggestionsUnchecked({decision:"reject",scope:{kind:"ids",suggestionIds:n},historyOrigin:`agent-suggestion-rollback:${t.agentConversationId}:${s}:${t.turn??"all"}:by-${t.currentRequestId}:${t.currentTurn}`});return{requestId:s,turn:t.turn,suggestionIds:n,resolvedCount:i.resolvedCount}}setSuggestionAuthorName(t){this.documentMutator.setDefaultSuggestionAuthorName(t)}acceptLiveSuggestionsByAuthor(t){return this.suggestionDecisionsAllowed?this.documentMutator.acceptLiveSuggestionsByAuthor(t):this.refusedDecision({decision:"accept",scope:{kind:"author",authorName:t}})}rejectLiveSuggestionsByAuthor(t){return this.suggestionDecisionsAllowed?this.documentMutator.rejectLiveSuggestionsByAuthor(t):this.refusedDecision({decision:"reject",scope:{kind:"author",authorName:t}})}acceptLiveSuggestionsByKind(t){return this.suggestionDecisionsAllowed?this.documentMutator.acceptLiveSuggestionsByKind(t):this.refusedDecision({decision:"accept",scope:{kind:"suggestion-kind",suggestionKind:t}})}rejectLiveSuggestionsByKind(t){return this.suggestionDecisionsAllowed?this.documentMutator.rejectLiveSuggestionsByKind(t):this.refusedDecision({decision:"reject",scope:{kind:"suggestion-kind",suggestionKind:t}})}acceptAgentSuggestions(){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:this.nativeAgentLiveSuggestionIds()}})}rejectLiveSuggestions(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}rejectLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"source",source:t}})}rejectAgentSuggestions(){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:this.nativeAgentLiveSuggestionIds()}})}beginGroup(t){this.documentMutator.beginGroup(t)}endGroup(){this.documentMutator.endGroup()}clearHistory(){this.documentMutator.clearHistory()}getHistoryInfo(){return this.documentMutator.getHistoryInfo()}setCurrentDocument(t){this.currentDocument=this.cloneDoc(t),this.notifyDocumentChange()}hasUncommittedChanges(){return!1}getDetachedSuggestionStore(){return this.documentMutator.getDetachedSuggestionStore()}clearLegacyDetachedSuggestionState(){this.documentMutator.clearLegacyDetachedSuggestionState()}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){return this.documentMutator.migrateLegacyDetachedSuggestionsToLiveSuggestions(t)}applyAgentActions(t,e,s){return s?.startNewTurn!==!1&&this.preprocessorSession.startNewTurn(),this.documentMutator.applyAgentActions(t,e,{optimizeStyleFormatting:s?.optimizeStyleFormatting,applyBlockMovesDirectly:s?.applyBlockMovesDirectly,directMode:s?.directMode})}}export{U as DocumentSession};
|
|
1
|
+
import{k as x,y as k,l as w,d as O,o as P,m as F}from"./engine-C5fxuZJo.js";import{D,P as R,w as z}from"./DocumentMutator-FEFU1YM0.js";import{i as E}from"./suggestionAuthorship-B-IuLQlE.js";import{s as N}from"./carrier-D58g-gw4.js";import*as b from"yjs";class H{constructor(t=50){this.tasks=new Map,this.intervalId=null,this.tickMs=t}schedule(t,e,s){const n=Date.now();this.tasks.set(t,{id:t,callback:s,delay:e,lastScheduledAt:n}),this.intervalId===null&&(this.intervalId=window.setInterval(()=>this.tick(),this.tickMs))}cancel(t){this.tasks.delete(t)&&this.tasks.size===0&&this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null)}tick(){const t=Date.now();for(const e of this.tasks.values())if(t-e.lastScheduledAt>=e.delay){this.tasks.delete(e.id);try{e.callback()}catch(s){console.error("[DebouncedTaskScheduler] Task error",s)}}this.tasks.size===0&&this.intervalId!==null&&(window.clearInterval(this.intervalId),this.intervalId=null)}}const W=new H;function q(u,t,e){W.schedule(u,t,e)}function U(u){if(typeof atob=="function"){const t=atob(u),e=new Uint8Array(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}return Uint8Array.from(Buffer.from(u,"base64"))}function T(u,t){const e=b;if(typeof e.applyUpdateV2=="function")try{e.applyUpdateV2(u,t)}catch(s){console.warn("[historyReplay] Failed to apply V2 update:",s)}}function A(u,t){try{b.applyUpdate(u,t),x(u)||T(u,t)}catch{T(u,t)}}function j(u,t,e=-1){const s=new b.Doc({gc:!1});A(s,U(u));const n=e<0?t.length:e;for(let i=0;i<n&&i<t.length;i++)A(s,U(t[i]));return s}class ${constructor(){this.worker=null,this.workerFailed=!1,this.nextRequestId=1,this.pendingRequests=new Map}async init(){if(!(this.worker||this.workerFailed))try{if(typeof window>"u"||typeof Worker>"u"){this.workerFailed=!0;return}this.worker=new Worker(new URL(""+new URL("../assets/historyMaterializeWorker-BMHTnStL.js",import.meta.url).href,import.meta.url)),this.worker.onmessage=t=>{const e=t.data,s=this.pendingRequests.get(e.id);if(s){if(this.pendingRequests.delete(e.id),!e.success){s.reject(new Error(e.error||"Worker request failed"));return}e.kind==="filterDistinct"?s.resolve(e.distinctIds??[]):e.doc?s.resolve(e.doc):s.reject(new Error("Materialization failed"))}},this.worker.onerror=t=>{console.warn("[HistoryMaterializer] Worker error:",t);for(const[e,s]of this.pendingRequests)s.reject(new Error("Worker error")),this.pendingRequests.delete(e);this.workerFailed=!0,this.worker?.terminate(),this.worker=null}}catch(t){console.warn("[HistoryMaterializer] Failed to create worker:",t),this.workerFailed=!0}}async materialize(t,e,s=-1){if(await this.init(),this.worker&&!this.workerFailed)try{return await this.materializeViaWorker(t,e,s)}catch(n){console.warn("[HistoryMaterializer] Worker materialization failed, falling back:",n)}return this.materializeSync(t,e,s)}async computeDistinctContentIds(t,e){if(e.length===0)return[];if(await this.init(),!this.worker||this.workerFailed)return null;try{return await new Promise((s,n)=>{if(!this.worker){n(new Error("Worker not available"));return}const i=this.nextRequestId++;this.pendingRequests.set(i,{resolve:s,reject:n});const r={id:i,kind:"filterDistinct",segments:t,candidateIds:e};this.worker.postMessage(r),setTimeout(()=>{this.pendingRequests.has(i)&&(this.pendingRequests.delete(i),n(new Error("Worker timeout")))},6e4)})}catch(s){return console.warn("[HistoryMaterializer] Distinct-frame filtering failed:",s),null}}materializeToYDoc(t,e,s=-1){return j(t,e,s)}materializeViaWorker(t,e,s){return new Promise((n,i)=>{if(!this.worker){i(new Error("Worker not available"));return}const r=this.nextRequestId++;this.pendingRequests.set(r,{resolve:n,reject:i});const o={id:r,snapshotB64:t,updatesB64:e,uptoIndex:s};this.worker.postMessage(o),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),i(new Error("Worker timeout")))},3e4)})}materializeSync(t,e,s){const n=this.materializeToYDoc(t,e,s);try{return k(n)}finally{n.destroy()}}dispose(){for(const[,t]of this.pendingRequests)t.reject(new Error("Materializer disposed"));this.pendingRequests.clear(),this.worker?.terminate(),this.worker=null}isWorkerAvailable(){return this.worker!==null&&!this.workerFailed}}const v=new $,C="https://app-api.revise-sdk.invalid";class V{constructor(t=20){this.cache=new Map,this.maxSize=t}get(t){const e=this.cache.get(t);return e&&(this.cache.delete(t),this.cache.set(t,e)),e}set(t,e){if(this.cache.size>=this.maxSize&&!this.cache.has(t)){const s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.delete(t),this.cache.set(t,e)}clear(){this.cache.clear()}}class K{constructor(t,e,s){this.tailDebounceMs=1200,this.docCache=new V,this.totalUpdates=0,this.segments=[],this.loaded=!1,this.maxEndLoaded=0,this.loadLock=null,this.targetLocks=new Map,this.blobLocks=new Map,this.abortController=null,this.contentIds=[],this.updateTimestamps=new Map,this.contentTimestamps=[],this.chunkEndUpdateIds=[],this.chunkSegIdx=[],this.distinctContentIds=null,this.distinctSignature=null,this.changeObservers=[],this.disposed=!1,this.documentId=t,this.authToken=s?.authToken,this.tailTaskId=`history-tail-${Math.random().toString(36).slice(2)}`,this.abortController=new AbortController}onChange(t){return this.changeObservers.push(t),()=>{const e=this.changeObservers.indexOf(t);e>=0&&this.changeObservers.splice(e,1)}}async ensureLoaded(){if(this.loaded)return!0;if(this.disposed)return!1;if(!this.supportsServerHistory())return this.loaded=!0,!0;try{const t=`${C}/documents/${this.documentId}/history`,e=await this.fetchJson(t);return this.totalUpdates=this.readTotalUpdates(e),this.segments=this.parseFrames(e.frames),this.loaded=!0,this.recomputeDerivedData(),this.notifyChange(),!0}catch(t){return console.error("[UpdateHistoryManager] Failed to load update history:",{documentId:this.documentId,error:t instanceof Error?t.message:String(t)}),!1}}notifyDocUpdated(){this.disposed||!this.loaded||q(this.tailTaskId,this.tailDebounceMs,()=>{this.refreshNewSegments()})}dispose(){this.disposed=!0,this.abortController?.abort(),this.abortController=null,this.changeObservers=[],this.docCache.clear(),this.segments=[],this.updateTimestamps.clear()}getTotalUpdates(){const t=this.segments[this.segments.length-1],e=this.contentIds[this.contentIds.length-1]??0;return Math.max(this.totalUpdates,t?.endUpdateId??0,e)}getContentCount(){return this.contentIds.length}getContentUpdateIds(){return this.contentIds.slice()}getDistinctContentUpdateIds(){return this.distinctContentIds&&this.distinctSignature===this.contentIdsSignature()?this.distinctContentIds.slice():null}contentIdsSignature(){const t=this.contentIds;return`${t.length}:${t[t.length-1]??0}`}async ensureDistinctFramesComputed(){}getWorkChunkCount(){return this.chunkEndUpdateIds.length}getWorkChunkEndUpdateIds(){return this.chunkEndUpdateIds.slice()}getTimestampForUpdateId(t){const e=this.updateTimestamps.get(Math.floor(t));return e&&Number.isFinite(e)&&e>0?e:null}getContentTimeline(){return{count:this.contentIds.length,timestamps:this.contentTimestamps.slice()}}getTimeAxisTicks(){let t;if(this.contentTimestamps.length>0?t=this.contentTimestamps.filter(d=>Number.isFinite(d)&&d>0):(t=Array.from(this.updateTimestamps.values()).filter(d=>Number.isFinite(d)&&d>0),t.sort((d,I)=>d-I)),t.length===0)return null;const e=t[0],s=t[t.length-1],n=s-e;if(n<=0)return{startTs:e,endTs:s,ticksTs:[]};const i=6e4,r=60*i,o=24*r,a=7*o;let c;n<r?c=5*i:n<o?c=r:n<30*o?c=o:c=a;const m=Math.floor(e/c)*c,y=[];let f=0,l=0;for(let d=m+c;d<s;d+=c){const I=d-c;for(;f<t.length&&t[f]<=I;)f++;for(l=Math.max(l,f);l<t.length&&t[l]<=d;)l++;l>f&&d>e&&y.push(d)}return{startTs:e,endTs:s,ticksTs:y}}getPauseMarkersForContent(t,e=10){const s=this.contentTimestamps;if(s.length<=1)return[];const n=Math.max(0,s[s.length-1]-s[0]);if(n<=0||t<=0)return[];const i=n*Math.max(1,e)/Math.max(1,t),r=[];let o=-1/0;for(let a=0;a<s.length-1;a++)s[a+1]-s[a]>=i&&s[a]-o>=i&&(r.push(a+1),o=s[a]);return r}async findLatestUpdateIdBeforeTimestamp(t){if(!await this.ensureLoaded()||!Number.isFinite(t)||t<=0||this.updateTimestamps.size===0)return null;const e=Array.from(this.updateTimestamps.entries()).filter(([,r])=>r>0).sort((r,o)=>r[1]-o[1]);if(e.length===0)return null;let s=0,n=e.length-1,i=null;for(;s<=n;){const r=s+n>>1;e[r][1]<=t?(i=e[r][0],s=r+1):n=r-1}return i??e[0][0]}async materializeAtContentIndex(t,e){if(!await this.ensureLoaded()||this.contentIds.length===0)return null;const s=Math.max(1,Math.min(this.contentIds.length,t));return this.materializeAt(this.contentIds[s-1],e)}async materializeAt(t,e){if(!await this.ensureLoaded()||this.segments.length===0)return null;const s=e?.excludePendingSuggestions===!0;t=Math.max(1,Math.min(this.getTotalUpdates(),t));const n=s?`update-${t}-accepted-only`:`update-${t}`,i=this.docCache.get(n);if(i)return i;await this.ensureHasSegmentFor(t);let r=this.getPlanForUpdateId(t);if(!r)return null;if(await this.ensureBlobsForSegmentStart(r.seg.startUpdateId),r=this.getPlanForUpdateId(t),!r?.seg.snapshotB64)return console.warn("[UpdateHistoryManager] Missing snapshot for segment",r?.seg.startUpdateId),null;const{seg:o}=r;try{const a=Math.min(o.updatesB64.length,o.frameOnly?o.updatesB64.length:t-o.startUpdateId+1);let c;if(s){const m=v.materializeToYDoc(o.snapshotB64,o.updatesB64,a);try{const y=D.createSuggestionProjectionFromYDoc(m,"reject");try{c=y.doc}finally{y.ydoc.destroy()}}finally{m.destroy()}}else c=await v.materialize(o.snapshotB64,o.updatesB64,a);return c&&this.docCache.set(n,c),c}catch(a){return console.error("[UpdateHistoryManager] Materialize failed:",{updateId:t,segmentRange:`${o.startUpdateId}-${o.endUpdateId}`,error:a instanceof Error?a.message:String(a)}),null}}async materializeChunkEnd(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const s=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),n=e?.excludePendingSuggestions===!0?`chunk-end-${t}-accepted-only`:`chunk-end-${t}`,i=this.docCache.get(n);if(i)return i;const r=this.segments[this.chunkSegIdx[s]];await this.ensureBlobsForSegmentStart(r.startUpdateId);const o=await this.materializeAt(r.endUpdateId,e);return o&&this.docCache.set(n,o),o}async materializeChunkSnapshot(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const s=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),n=this.segments[this.chunkSegIdx[s]];if(await this.ensureBlobsForSegmentStart(n.startUpdateId),!n.snapshotB64)return null;if(e?.excludePendingSuggestions){const i=v.materializeToYDoc(n.snapshotB64,[],0);try{const r=D.createSuggestionProjectionFromYDoc(i,"reject");try{return r.doc}finally{r.ydoc.destroy()}}finally{i.destroy()}}return v.materialize(n.snapshotB64,[],0)}async materializeChunkPair(t,e){if(!await this.ensureLoaded()||this.chunkSegIdx.length===0)return null;const s=Math.max(0,Math.min(this.chunkSegIdx.length-1,Math.floor(t)-1)),n=this.segments[this.chunkSegIdx[s]];await this.ensureBlobsForSegmentStart(n.startUpdateId);const i=await this.materializeAt(n.endUpdateId,e);if(!i)return null;if(s>0){const o=this.segments[this.chunkSegIdx[s-1]];await this.ensureBlobsForSegmentStart(o.startUpdateId);const a=await this.materializeAt(o.endUpdateId,e);if(a)return{base:a,target:i}}if(!n.snapshotB64)return null;const r=await this.materializeChunkSnapshot(t,e);return r?{base:r,target:i}:null}__getPlanForTest(t){return this.getPlanForUpdateId(t)}supportsServerHistory(){return this.documentId.length>8}async fetchJson(t){if(this.disposed)throw new Error("Manager disposed");const e={};this.authToken&&(e.Authorization=`Bearer ${this.authToken}`);const s=await fetch(t,{headers:e,credentials:"omit",signal:this.abortController?.signal});if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}readTotalUpdates(t){const e=Number(t.totalUpdates);return!Number.isFinite(e)||e<=0?this.totalUpdates:e}parseFrames(t){return t?t.filter(e=>Number.isFinite(e.updateId)&&Number.isFinite(e.sourceId)&&(e.source==="legacy"||e.source==="delta")).map(e=>({startUpdateId:Number(e.updateId),endUpdateId:Number(e.updateId),snapshotB64:"",updatesB64:[],meta:[{ts:Number(e.timestamp||0),content:!0,userId:e.userId??null,agentName:e.agentName??null}],frameSource:e.source,frameSourceId:Number(e.sourceId),frameOnly:!0})).sort((e,s)=>e.startUpdateId-s.startUpdateId):[]}async refreshNewSegments(){!this.supportsServerHistory()||this.disposed||!this.loaded||await this.withLoadLock(async()=>{const t=`${C}/documents/${this.documentId}/history`;try{const e=await this.fetchJson(t);this.totalUpdates=this.readTotalUpdates(e),this.segments=this.parseFrames(e.frames),this.recomputeDerivedData(),this.notifyChange()}catch(e){e.name!=="AbortError"&&console.warn("[UpdateHistoryManager] Failed to refresh segments:",e)}})}async ensureHasSegmentFor(t){if(!this.supportsServerHistory()||this.disposed||this.segments.some(n=>n.startUpdateId<=t&&t<=n.endUpdateId))return;const e=this.targetLocks.get(t);if(e)return e;const s=this.fetchSegmentContaining(t).finally(()=>{this.targetLocks.delete(t)});this.targetLocks.set(t,s),await s}async fetchSegmentContaining(t){if(this.disposed)return;const e=this.getPlanForUpdateId(t)?.seg;if(!e?.frameSource||e.frameSourceId==null)return;const s=new URLSearchParams({source:e.frameSource,sourceId:String(e.frameSourceId)});e.frameSource==="legacy"&&s.set("targetUpdateId",String(t));const n=`${C}/documents/${this.documentId}/history/frame?${s.toString()}`;try{const i=await this.fetchJson(n);e.snapshotB64=i.snapshotB64||"",e.updatesB64=i.updatesB64||[]}catch(i){i.name!=="AbortError"&&console.warn("[UpdateHistoryManager] Failed to fetch segment:",{updateId:t,error:i})}}async ensureBlobsForSegmentStart(t){const e=this.segments.find(n=>n.startUpdateId===t);if(e?.snapshotB64&&Array.isArray(e.updatesB64))return;let s=this.blobLocks.get(t);s||(s=this.fetchSegmentContaining(t).finally(()=>{this.blobLocks.delete(t)}),this.blobLocks.set(t,s)),await s}async withLoadLock(t){if(this.loadLock)return this.loadLock;this.loadLock=t();try{await this.loadLock}finally{this.loadLock=null}}mergeInSegments(t){if(t.length===0)return;const e=new Map;for(const s of this.segments)e.set(s.startUpdateId,s);for(const s of t){const n=e.get(s.startUpdateId);if(!n){e.set(s.startUpdateId,s);continue}e.set(s.startUpdateId,{startUpdateId:n.startUpdateId,endUpdateId:Math.max(n.endUpdateId,s.endUpdateId),snapshotB64:n.snapshotB64||s.snapshotB64,updatesB64:(s.updatesB64?.length||0)>=(n.updatesB64?.length||0)?s.updatesB64:n.updatesB64,meta:(s.meta?.length||0)>=(n.meta?.length||0)?s.meta:n.meta,frameSource:s.frameSource||n.frameSource,frameSourceId:s.frameSourceId??n.frameSourceId,frameOnly:s.frameOnly||n.frameOnly})}this.segments=Array.from(e.values()).sort((s,n)=>s.startUpdateId-n.startUpdateId),this.maxEndLoaded=0;for(const s of this.segments)s.endUpdateId>this.maxEndLoaded&&(this.maxEndLoaded=s.endUpdateId)}getPlanForUpdateId(t){if(this.segments.length===0)return null;let e=this.segments.find(n=>n.startUpdateId<=t&&t<=n.endUpdateId);if(!e){const n=this.segments[0],i=this.segments[this.segments.length-1];if(t<n.startUpdateId)e=n;else if(t>i.endUpdateId)e=i;else for(let r=0;r<this.segments.length-1;r++)if(t>this.segments[r].endUpdateId&&t<this.segments[r+1].startUpdateId){e=this.segments[r];break}}if(!e)return null;const s=Math.max(0,Math.min(e.updatesB64.length,t-e.startUpdateId+1));return{seg:e,upto:s}}recomputeDerivedData(){this.docCache.clear(),this.recomputeContentIds(),this.recomputeTimestamps(),this.recomputeChunks()}recomputeContentIds(){const t=[];for(let e=0;e<this.segments.length;e++){const s=this.segments[e];if(s.frameOnly){t.push(s.startUpdateId);continue}const n=s.meta,i=Math.max(s.updatesB64.length,n?.length||0),r=e<2;for(let o=0;o<i;o++)(n?.[o]?.content||r&&o===0)&&t.push(s.startUpdateId+o)}this.contentIds=t}recomputeTimestamps(){this.updateTimestamps.clear();for(const t of this.segments){const e=t.meta;if(e)for(let s=0;s<e.length;s++){const n=t.startUpdateId+s,i=Number(e[s]?.ts||0);i>0&&this.updateTimestamps.set(n,i)}}this.contentTimestamps=this.contentIds.map(t=>this.updateTimestamps.get(t)||0)}recomputeChunks(){const t=this.segments.length;if(t===0){this.chunkSegIdx=[],this.chunkEndUpdateIds=[];return}const e=[];for(let n=0;n<t;n++){if(this.segments[n].frameOnly){e.push(n);continue}const i=this.segments[n].meta,r=Array.isArray(i)&&i.some(a=>a?.content),o=n<2;(r||o)&&e.push(n)}const s=t-1;(e.length===0||e[e.length-1]!==s)&&e.push(s),this.chunkSegIdx=e,this.chunkEndUpdateIds=e.map(n=>this.segments[n].endUpdateId)}notifyChange(){if(!this.disposed)for(const t of this.changeObservers.slice())try{t()}catch(e){console.error("[UpdateHistoryManager] Observer error:",e)}}}const J=()=>{},Y=async()=>{},G=new Set;function B(u,t){for(const e of G)try{e(u,t)}catch{}}const X=new Proxy({track:(u,t)=>B(u,t),trackAgentToolInvoked:(u,t,e,s=!1)=>B("Agent Tool Invoked",{tool:u,documentId:t??void 0,directMode:s}),trackDocumentExported:(u,t,e)=>B("Document Exported",{documentId:u,format:t,source:e}),getCheckoutAttribution:()=>null,flush:Y},{get(u,t){return t in u?u[t]:J}});class L{constructor(t,e,s,n){this.isViewingRevision=!1,this.documentChangeObservers=[],this.isReadOnly=!1,this.timeTravelActive=!1,this.viewModeObservers=[],this.historyOpen=!1,this.historyDiffEnabled=!0,this.historySelection={start:null,end:null},this.historyObservers=[],this.notesObservers=[],this.notesValue="",this.cleanupCallbacks=[],this.disposed=!1,this.historyManager=null,this.sharedWriteAccess=null,this.autocorrectEnabled=!0,this.suggestionDecisionsAllowed=!0,this.documentId=t,this.sharedStyleMigrationPermit=n?.sharedStyleMigrationPermit,this.authToken=n?.authToken,this.onTitleChange=s;const i=n?.disableProposalPersistence??!!n?.authToken;if(this.preprocessorSession=new R,w(e)){const a=e;if(this.ydoc=O(a,this.sharedStyleMigrationPermit?{sharedStyles:this.sharedStyleMigrationPermit.formatGateConfirmed===!0&&this.sharedStyleMigrationPermit.exclusive===!0}:void 0),a.pendingDocxCarrier){const c=a.pendingDocxCarrier;delete a.pendingDocxCarrier,N(this.ydoc,c.bytes,{hash:c.hash})}a.pageless!==void 0&&this.ydoc.getMap("metadata").set("pageless",a.pageless),this.currentDocument=this.cloneDoc(a)}else{this.ydoc=e;const a=k(this.ydoc);this.currentDocument=this.cloneDoc(a)}z(this.ydoc),w(e)&&(this.sharedWriteAccess=!0),this.documentMutator=new D(k(this.ydoc),(a,c)=>this.updateWorkingDocument(a,c),this.onTitleChange,this.ydoc,t,i,this.preprocessorSession,{canRepairIdentity:()=>this.sharedWriteAccess===!0,deferIdentityRepair:!w(e)}),this.documentMutator.identityRepairedOnConstruct&&(this.currentDocument=this.cloneDoc(k(this.ydoc))),this.notesValue=this.documentMutator.getDocumentNotes();try{this.documentMutator.backfillLiveSuggestionTreeRecords(),this.documentMutator.reconcileFootnotes(),this.documentMutator.migrateChromeOutOfContent(),this.documentMutator.migrateNotesOutOfContent(),this.documentMutator.migrateLegacyHeaderFooterMetadata(),this.documentMutator.migrateLegacyPageNumbers()}catch{}this.backfillStylesheetSidecar(),this.cleanupCallbacks.push(P(this.ydoc,a=>{console.warn(`[DocumentSession] repaired a duplicate seed: removed ${a.removedBlocks} blocks from ${a.losingClaims} losing seed(s)`)}));const r=this.ydoc.getMap("metadata"),o=a=>{if(a.keysChanged.has("notes")){const c=this.documentMutator.getDocumentNotes();c!==this.notesValue&&(this.notesValue=c,this.notifyNotesObservers())}};if(r.observe(o),this.cleanupCallbacks.push(()=>r.unobserve(o)),!n?.disableHistory){this.historyManager=new K(this.documentId,this.ydoc,{authToken:this.authToken});const a=()=>{this.historyManager?.notifyDocUpdated()};this.ydoc.on("update",a),this.cleanupCallbacks.push(()=>this.ydoc.off("update",a))}}static fromDocRoot(t,e){return new L("no-id",t,e)}getDocumentId(){return this.documentId}dispose(){if(!this.disposed){this.disposed=!0;for(const t of this.cleanupCallbacks.splice(0))t();this.documentMutator.dispose(),this.historyManager?.dispose(),this.historyManager=null,this.documentChangeObservers=[],this.viewModeObservers=[],this.historyObservers=[],this.notesObservers=[]}}setReadOnly(){this.isReadOnly=!0}setReadWrite(){this.isReadOnly=!1}setSharedWriteAccess(t){const e=t&&this.sharedWriteAccess!==!0;this.sharedWriteAccess=t,e&&this.documentMutator.repairDocumentIdentity()&&this.notifyDocumentChange(this.documentMutator.getDocument(),{origin:"local"}),e&&this.sharedStyleMigrationPermit&&(F(this.ydoc,this.sharedStyleMigrationPermit),this.sharedStyleMigrationPermit=void 0)}setSuggestingMode(t){this.documentMutator.setSuggestingMode(t)}setDocxRoundTripRequired(t){this.documentMutator.docxRoundTripRequired=t}isSuggestingMode(){return this.documentMutator.isSuggestingMode()}getWorkingDocument(){return this.documentMutator.getDocument()}getDocumentWithoutPendingSuggestions(){return this.documentMutator.getLiveSuggestionIds().length>0?this.documentMutator.getDocumentWithRejectedSuggestions():this.getWorkingDocument()}getWorkingDocumentBeforePendingReview(){return this.getDocumentWithoutPendingSuggestions()}getDocumentWithPendingSuggestionsApplied(t){if(t?.conversationId!==void 0&&this.documentMutator.setDetachedSuggestionConversation(t.conversationId??null,t.serverDetachedSuggestions),this.documentMutator.getLiveSuggestionIds().length>0)return this.documentMutator.getDocumentWithAcceptedSuggestions();const e=this.documentMutator.getDetachedSuggestionStore(),s=e.getPendingSuggestions();if(s.size===0)return this.getWorkingDocument();const n=Array.from(s.keys()),i=e.materializeWithSuggestions(n);return k(i)}getCurrentDocument(){return this.currentDocument}updateWorkingDocument(t,e={origin:"unknown"}){!this.isViewingRevision&&!this.historyOpen&&(this.currentDocument=t),this.logUnresolvableLiveSuggestions(e),this.notifyDocumentChange(this.currentDocument,e)}logUnresolvableLiveSuggestions(t){const e=this.documentMutator.getLiveSuggestionIds();if(e.length===0)return;const s=this.documentMutator.getUnresolvableLiveSuggestionRecords(),n=s.filter(i=>i.source==="agent");this.documentId,t.origin,e.length,s.length,n.length}countPrunedByKey(t,e){return t.reduce((s,n)=>{const i=n[e]||"unknown";return s[i]=(s[i]??0)+1,s},{})}trackPrunedUnresolvableLiveSuggestions(t,e,s){const n=this.documentMutator.takeLastPrunedUnresolvableLiveSuggestions();if(n.length===0)return;const i=n.filter(o=>o.source==="agent").length,r={Document:this.documentId,Action:t,RequestedSuggestionCount:new Set(e).size,ResolvedSuggestionCount:s,PrunedSuggestionCount:n.length,PrunedAgentSuggestionCount:i,PrunedSuggestionTypes:this.countPrunedByKey(n,"type"),PrunedSuggestionSources:this.countPrunedByKey(n,"source"),PrunedSuggestions:n};X.track("Live Suggestions Pruned",r)}onDocumentChange(t){return this.documentChangeObservers.push(t),()=>{const e=this.documentChangeObservers.indexOf(t);e>-1&&this.documentChangeObservers.splice(e,1)}}notifyDocumentChange(t,e={origin:"unknown"}){const s=t??this.getCurrentDocument();this.documentChangeObservers.forEach(n=>{try{n(s,e)}catch(i){console.error("Error in document change observer:",i)}})}exitRevisionView(){this.isViewingRevision=!1,this.currentDocument=this.getWorkingDocument(),this.notifyViewModeChange(),this.notifyDocumentChange()}getDocumentMutator(){return this.documentMutator}async getDocumentSnapshotAtOrBefore(t){if(!this.historyManager||!Number.isFinite(t)||t<=0)return null;const e=await this.historyManager.findLatestUpdateIdBeforeTimestamp(t);return e===null?null:this.historyManager.materializeAt(e,{excludePendingSuggestions:!0})}getDocumentNotes(){return this.notesValue}setDocumentNotes(t){if(this.isReadOnly)return;const e=typeof t=="string"?t:String(t??"");e!==this.notesValue&&(this.notesValue=e,this.documentMutator.setNotes(e),this.notifyNotesObservers())}onNotesChange(t){return this.notesObservers.push(t),()=>{const e=this.notesObservers.indexOf(t);e>=0&&this.notesObservers.splice(e,1)}}getPreprocessorSession(){return this.preprocessorSession}getRevisionManager(){return null}getYDoc(){return this.ydoc}registerRemoteOrigin(t){this.documentMutator.registerRemoteOrigin(t)}unregisterRemoteOrigin(t){this.documentMutator.unregisterRemoteOrigin(t)}setTimeTravelActive(t){this.timeTravelActive=!!t}isTimeTravelActive(){return this.timeTravelActive}onViewModeChange(t){return this.viewModeObservers.push(t),()=>{const e=this.viewModeObservers.indexOf(t);e>=0&&this.viewModeObservers.splice(e,1)}}openHistory(){this.historyOpen=!0,this.notifyHistoryChange()}closeHistory(){this.historyOpen=!1,this.notifyHistoryChange()}isHistoryOpen(){return this.historyOpen}setDiffEnabled(t){this.historyDiffEnabled=!!t,this.notifyHistoryChange()}isDiffEnabled(){return this.historyDiffEnabled}setSelection(t){this.historySelection={start:t.start??null,end:t.end??null},this.notifyHistoryChange()}getSelection(){return{...this.historySelection}}onHistoryStateChange(t){return this.historyObservers.push(t),()=>{const e=this.historyObservers.indexOf(t);e>=0&&this.historyObservers.splice(e,1)}}notifyHistoryChange(){for(const t of this.historyObservers.slice())try{t()}catch(e){console.error("[DocumentSession] History observer error:",e)}}backfillStylesheetSidecar(){try{const t=this.ydoc.getMap("metadata"),e=t.get("stylesXml");if(typeof e!="string"||e.length===0||t.get("stylesheet")!==void 0)return;import("./DocxConverter-BOyLn5eZ.js").then(({DocxConverter:s})=>{if(this.isReadOnly||this.isViewingRevision||t.get("stylesheet")!==void 0)return;const n=s.resolveStylesheetFromStylesXml(e,this.currentDocument.pageLayout);n&&this.ydoc.transact(()=>{t.set("stylesheet",n)})}).catch(()=>{})}catch{}}notifyNotesObservers(){const t=this.getDocumentNotes();for(const e of this.notesObservers.slice())try{e(t)}catch(s){console.error("[DocumentSession] Notes observer error:",s)}}async applySelection(t){const e=this.historyManager;if(!e||!t)return;const s=this.historyDiffEnabled,n=this.historySelection;await e.ensureLoaded();const i=e.getTotalUpdates?.()||0;if(i<=0)return;const r=h=>Math.max(1,Math.min(i,Math.floor(h))),o=async h=>await e.materializeAt?.(r(h),{excludePendingSuggestions:!0}),a=()=>this.getDocumentWithoutPendingSuggestions(),c=h=>{try{t.getEditor?.()?.setDisplayDocument?.(h)}catch(g){console.error("[DocumentSession] Failed to set display document:",g)}},m=async h=>{const g=await o(h);if(g){try{t.clearDiffPresentation?.()}catch(p){console.error("[DocumentSession] Failed to clear diff presentation:",p)}c(g)}},y=async(h,g)=>{const p=await o(h),M=await o(g);!p||!M||(t.showDiffBetweenDocuments?.(p,M),c(M))},f=async h=>{const g=await o(h),p=a();!g||!p||(t.showDiffBetweenDocuments?.(g,p),c(p))},l=n.start,d=n.end;if(l!=null&&d!=null&&l!==d){const h=r(l),g=r(d),p=Math.min(h,g),M=Math.max(h,g);s?await y(p,M):await m(M);return}const I=typeof l=="number"?l:null;if(I==null)return;const S=r(I);if(S<=1){await m(1);return}if(s)if(S===i)try{const h=await o(i),g=a();JSON.stringify(h)===JSON.stringify(g)?i>1?await y(i-1,i):await m(1):await f(i)}catch{await f(i)}else S>1?await y(S-1,S):await m(S);else await m(S)}async showDiffBetweenHistoryUpdates(t,e,s){const n=this.historyManager;if(!n||!t)return!1;const i=Math.min(e,s),r=Math.max(e,s);if(!Number.isFinite(i)||!Number.isFinite(r)||i<=0||r<=i||!await n.ensureLoaded())return!1;const o=n.getTotalUpdates?.()??0;return r>o?!1:(this.openHistory(),this.setDiffEnabled(!0),this.setSelection({start:i,end:r}),await this.applySelection(t),!0)}notifyViewModeChange(){const t=this.isViewingRevision;this.viewModeObservers.forEach(e=>{try{e(t)}catch{}})}getStorageType(){return this.ydoc.getMap("metadata").get("storageType")}getParentFolderId(){const t=this.ydoc.getMap("metadata").get("parentFolderId");return typeof t=="string"&&t.length>0?t:null}getHistoryManager(){return this.historyManager}attachDemoHistoryManager(t){this.historyManager=t}async jumpToUpdateId(t){const e=await this.historyManager?.materializeAt(t,{excludePendingSuggestions:!0});return e?(this.currentDocument=this.cloneDoc(e),this.notifyDocumentChange(),!0):!1}async jumpToContentIndex(t){const e=this.historyManager;if(!e?.materializeAtContentIndex)return!1;const s=await e.materializeAtContentIndex(t,{excludePendingSuggestions:!0});return s?(this.currentDocument=this.cloneDoc(s),this.notifyDocumentChange(),!0):!1}cloneDoc(t){return JSON.parse(JSON.stringify(t))}getPagelessMode(){return this.documentMutator.getPagelessMode()}setPagelessMode(t){this.documentMutator.setPagelessMode(t)}getPageLayoutSettings(){return this.documentMutator.getPageLayoutSettings()}setPageLayoutSettings(t){this.documentMutator.setPageLayoutSettings(t)}getIndentStepPx(){return this.documentMutator.getIndentStepPx()}setAutocorrectEnabled(t){this.autocorrectEnabled=t}isAutocorrectEnabled(){return this.autocorrectEnabled}insertText(t,e,s,n){return this.documentMutator.insertText(t,e,s,n)}getAfterOperationSelection(){return this.documentMutator.getAfterOperationSelection()}insertFormattedText(t,e,s,n,i){return this.documentMutator.insertFormattedText(t,e,s,n,i)}deleteText(t,e,s,n){return this.documentMutator.deleteText(t,e,s,n)}deleteSelection(t,e,s,n){return this.documentMutator.deleteSelection(t,e,s,n)}deleteBlock(t,e,s){return this.documentMutator.deleteBlock(t,e,s)}deleteBlockById(t,e,s){return this.documentMutator.deleteBlockById(t,e,s)}insertBlock(t,e,s,n){return this.documentMutator.insertBlock(t,e,s,n)}insertBlockAfterId(t,e,s,n){return this.documentMutator.insertBlockAfterId(t,e,s,n)}insertBlockBeforeId(t,e,s,n){return this.documentMutator.insertBlockBeforeId(t,e,s,n)}insertBlockIntoParent(t,e,s,n){return this.documentMutator.insertBlockIntoParent(t,e,s,n)}insertBlockAtStart(t,e,s){return this.documentMutator.insertBlockAtStart(t,e,s)}insertBlockAtEnd(t,e,s){return this.documentMutator.insertBlockAtEnd(t,e,s)}updateBlock(t,e,s,n){return this.documentMutator.updateBlock(t,e,s,n)}updateBlockById(t,e,s,n){return this.documentMutator.updateBlockById(t,e,s,n)}replaceParagraphById(t,e,s,n){return this.documentMutator.replaceParagraphById(t,e,s,n)}toggleTodoItem(t,e,s,n,i){return this.documentMutator.toggleTodoItem(t,e,s,n,i)}toggleTodoItemById(t,e,s,n,i){return this.documentMutator.toggleTodoItemById(t,e,s,n,i)}setListItemIndent(t,e,s,n,i){return this.documentMutator.setListItemIndent(t,e,s,n,i)}splitParagraph(t,e){return this.documentMutator.splitParagraph(t,e)}applyFormatting(t,e,s,n,i){return this.documentMutator.applyFormatting(t,e,s,n,i)}setSelectionAfterOperation(t){this.documentMutator.setSelectionAfterOperation(t)}setFontFamily(t,e,s,n){return this.documentMutator.setFontFamily(t,e,s,n)}setFontSize(t,e,s,n){return this.documentMutator.setFontSize(t,e,s,n)}setLetterSpacing(t,e,s,n){return this.documentMutator.setLetterSpacing(t,e,s,n)}setTextColor(t,e,s,n){return this.documentMutator.setTextColor(t,e,s,n)}setBackgroundColor(t,e,s,n){return this.documentMutator.setBackgroundColor(t,e,s,n)}clearFormatting(t,e,s){return this.documentMutator.clearFormatting(t,e,s)}setLink(t,e,s,n){return this.documentMutator.setLink(t,e,s,n)}setCodeBlockLanguage(t,e){return this.documentMutator.setCodeBlockLanguage(t,e)}setCodeBlockRenderDiagram(t,e){return this.documentMutator.setCodeBlockRenderDiagram(t,e)}setCodeBlockShowDiagramSource(t,e){return this.documentMutator.setCodeBlockShowDiagramSource(t,e)}setMathBlockContent(t,e){return this.documentMutator.setMathBlockContent(t,e)}setMathBlockDisplayMode(t,e){return this.documentMutator.setMathBlockDisplayMode(t,e)}setMathBlockAlign(t,e){return this.documentMutator.setMathBlockAlign(t,e)}replaceParagraph(t,e,s,n){return this.documentMutator.replaceParagraph(t,e,s,n)}pasteParagraphs(t,e,s,n={}){return this.documentMutator.pasteParagraphs(t,e,s,n)}canUndo(){return this.documentMutator.canUndo()}canRedo(){return this.documentMutator.canRedo()}undo(){return this.documentMutator.undo()}redo(t){return this.documentMutator.redo(t)}getLiveSuggestionIdsBySource(t){return this.documentMutator.getLiveSuggestionIdsBySource(t)}getLiveSuggestionIdsByCommentThread(t){return this.documentMutator.getLiveSuggestionIdsByCommentThread(t)}getInlineSuggestionMetadataFromDocument(t){return this.documentMutator.getInlineSuggestionMetadataFromDocument(t)}setSuggestionDecisionsAllowed(t){this.suggestionDecisionsAllowed=t}canDecideSuggestions(){return this.suggestionDecisionsAllowed}refusedDecision(t){return{decision:t.decision,scope:t.scope,resolvedCount:0,initialSuggestionIds:[],attemptedSuggestionIds:[],attemptedSuggestionIdCount:0,prunedSuggestions:[]}}decideLiveSuggestions(t){return this.suggestionDecisionsAllowed?this.decideLiveSuggestionsUnchecked(t):this.refusedDecision(t)}decideLiveSuggestionsUnchecked(t){const e=this.documentMutator.decideLiveSuggestions(t);return this.trackPrunedUnresolvableLiveSuggestions(t.decision,e.attemptedSuggestionIds,e.resolvedCount),e}acceptLiveSuggestions(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}acceptLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"source",source:t}})}nativeAgentLiveSuggestionIds(){return this.documentMutator.getLiveSuggestionIdsBySource("agent").filter(t=>E(this.documentMutator.getInlineSuggestionMetadataFromDocument(t)?.agentName??this.documentMutator.getLiveSuggestion(t)?.agentName))}rollbackAgentSuggestions(t){const e=this.nativeAgentLiveSuggestionIds().map(r=>{const o=this.documentMutator.getInlineSuggestionMetadataFromDocument(r),a=this.documentMutator.getLiveSuggestion(r);return{suggestionId:r,agentConversationId:o?.agentConversationId??a?.agentConversationId,agentRequestId:o?.agentRequestId??a?.agentRequestId,agentTurn:o?.agentTurn??a?.agentTurn}}).filter(r=>r.agentConversationId===t.agentConversationId&&typeof r.agentRequestId=="number"&&typeof r.agentTurn=="number"),s=t.requestId??e.reduce((r,o)=>{const a=o.agentRequestId;return a>=t.currentRequestId?r:r===void 0||a>r?a:r},void 0);if(s===void 0)return{suggestionIds:[],resolvedCount:0};const n=e.filter(r=>t.turn===void 0&&r.agentRequestId>=s||t.turn!==void 0&&r.agentRequestId===s&&r.agentTurn===t.turn).map(r=>r.suggestionId);if(n.length===0)return{requestId:s,turn:t.turn,suggestionIds:[],resolvedCount:0};const i=this.decideLiveSuggestionsUnchecked({decision:"reject",scope:{kind:"ids",suggestionIds:n},historyOrigin:`agent-suggestion-rollback:${t.agentConversationId}:${s}:${t.turn??"all"}:by-${t.currentRequestId}:${t.currentTurn}`});return{requestId:s,turn:t.turn,suggestionIds:n,resolvedCount:i.resolvedCount}}setSuggestionAuthorName(t){this.documentMutator.setDefaultSuggestionAuthorName(t)}acceptLiveSuggestionsByAuthor(t){return this.suggestionDecisionsAllowed?this.documentMutator.acceptLiveSuggestionsByAuthor(t):this.refusedDecision({decision:"accept",scope:{kind:"author",authorName:t}})}rejectLiveSuggestionsByAuthor(t){return this.suggestionDecisionsAllowed?this.documentMutator.rejectLiveSuggestionsByAuthor(t):this.refusedDecision({decision:"reject",scope:{kind:"author",authorName:t}})}acceptLiveSuggestionsByKind(t){return this.suggestionDecisionsAllowed?this.documentMutator.acceptLiveSuggestionsByKind(t):this.refusedDecision({decision:"accept",scope:{kind:"suggestion-kind",suggestionKind:t}})}rejectLiveSuggestionsByKind(t){return this.suggestionDecisionsAllowed?this.documentMutator.rejectLiveSuggestionsByKind(t):this.refusedDecision({decision:"reject",scope:{kind:"suggestion-kind",suggestionKind:t}})}acceptAgentSuggestions(){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:this.nativeAgentLiveSuggestionIds()}})}rejectLiveSuggestions(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}rejectLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"source",source:t}})}rejectAgentSuggestions(){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:this.nativeAgentLiveSuggestionIds()}})}beginGroup(t){this.documentMutator.beginGroup(t)}endGroup(){this.documentMutator.endGroup()}clearHistory(){this.documentMutator.clearHistory()}getHistoryInfo(){return this.documentMutator.getHistoryInfo()}setCurrentDocument(t){this.currentDocument=this.cloneDoc(t),this.notifyDocumentChange()}hasUncommittedChanges(){return!1}getDetachedSuggestionStore(){return this.documentMutator.getDetachedSuggestionStore()}clearLegacyDetachedSuggestionState(){this.documentMutator.clearLegacyDetachedSuggestionState()}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){return this.documentMutator.migrateLegacyDetachedSuggestionsToLiveSuggestions(t)}applyAgentActions(t,e,s){return s?.startNewTurn!==!1&&this.preprocessorSession.startNewTurn(),this.documentMutator.applyAgentActions(t,e,{optimizeStyleFormatting:s?.optimizeStyleFormatting,applyBlockMovesDirectly:s?.applyBlockMovesDirectly,directMode:s?.directMode})}}export{L as DocumentSession};
|