@reviseio/engine 3.0.0 → 3.0.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 +9 -0
- package/chunks/{AgentHtmlConverter-BnK7NaYA.js → AgentHtmlConverter-CnnB8-WI.js} +3 -3
- package/chunks/{AgentPageRenderer-DLwq6nAa.js → AgentPageRenderer-DLgUGrGy.js} +4 -4
- package/chunks/{BlockDiff-BdlcKY-t.js → BlockDiff-B6-aJxHo.js} +1 -1
- package/chunks/{CanvasRenderer-Bqsj1S0p.js → CanvasRenderer-C1Vegx9Y.js} +2 -2
- package/chunks/{DocumentCompare-BqyiP87r.js → DocumentCompare-C8295s35.js} +1 -1
- package/chunks/{DocumentLayoutEngine-7iOYvyVb.js → DocumentLayoutEngine-C62pyGVf.js} +3 -3
- package/chunks/{DocumentMutator-DIrZBuLr.js → DocumentMutator-Bat_oLBQ.js} +2 -2
- package/chunks/{DocumentScrubber-Cz8Q05hF.js → DocumentScrubber-BZQn_z92.js} +1 -1
- package/chunks/{DocumentSession-lXSXqua5.js → DocumentSession-BDcazSEv.js} +1 -1
- package/chunks/{DocxConverter-BfDw7777.js → DocxConverter-BC31uYIL.js} +3 -3
- package/chunks/{DocxGraft-D0uCnGCo.js → DocxGraft-L10HXM3U.js} +2 -2
- package/chunks/{HtmlConverter-7Xj_g9Jr.js → HtmlConverter-C5ihhZ6G.js} +3 -3
- package/chunks/{MarkdownConverter-cnW_oePY.js → MarkdownConverter-DofaSeC4.js} +1 -1
- package/chunks/{OdtConverter-GwRDMnwS.js → OdtConverter-c1fTWoAt.js} +1 -1
- package/chunks/{OfficeImportShared-nlMtIUni.js → OfficeImportShared-CrOpHpJ-.js} +1 -1
- package/chunks/{PdfConverter-yOlWiVIj.js → PdfConverter-DX7fsRH5.js} +5 -5
- package/chunks/{RtfConverter--wLd0qrw.js → RtfConverter-hbJ2529G.js} +66 -66
- package/chunks/{TableBorders-C5pNsuxP.js → TableBorders-DVhdvo6f.js} +1 -1
- package/chunks/TextDecoding-IPbuUqcC.js +2 -0
- package/chunks/TextFileDecoder-BZBBejlR.js +10 -0
- package/chunks/{TxtConverter-BoRVCDZw.js → TxtConverter-YHv5FXWb.js} +1 -1
- package/chunks/{Typography-DAGM5kfI.js → Typography-B4gndEdB.js} +1 -1
- package/chunks/XmlConverter-BRRluy9k.js +55 -0
- package/chunks/{capture-Dtinb4bY.js → capture-i_dPkQIS.js} +1 -1
- package/chunks/{carrier-RNy67HN4.js → carrier-pYM9xf6x.js} +1 -1
- package/chunks/{chromeImageLayout-bgHYmqTp.js → chromeImageLayout-BiQ3Iz1-.js} +1 -1
- package/chunks/{engine-TnK8N-gT.js → engine-LMUnxdm2.js} +18 -18
- package/chunks/{footnoteFlatten-BcKaWzVs.js → footnoteFlatten-EE85Hjre.js} +1 -1
- package/chunks/{graftExport-DxAALMHp.js → graftExport-G-dG7Vcc.js} +1 -1
- package/chunks/{index-CTti7wRd.js → index-BLb10wQt.js} +3 -3
- package/chunks/{serverDocumentSession-BmYdjC6e.js → serverDocumentSession-DGDU5Lh3.js} +5 -5
- package/chunks/{signatures-CU2LMLBp.js → signatures-DTNDS2PH.js} +1 -1
- package/engine.js +1 -1
- package/package.json +2 -2
- package/chunks/TextFileDecoder--rsVs3NR.js +0 -9
- package/chunks/XmlConverter-CO8Z28dX.js +0 -55
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{D as A}from"./DocumentMutator-
|
|
1
|
+
import{D as A}from"./DocumentMutator-Bat_oLBQ.js";import{y as N,b as S,d as v}from"./engine-LMUnxdm2.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-TnK8N-gT.js";import{D,P as R,x as z}from"./DocumentMutator-DIrZBuLr.js";import{i as E}from"./suggestionAuthorship-B-IuLQlE.js";import{s as N}from"./carrier-RNy67HN4.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-BfDw7777.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-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,8 +1,8 @@
|
|
|
1
1
|
import{b8 as Pi,b9 as Ci,a8 as Er,ab as Ni,a7 as Ai,r as Ee,b1 as Ti,av as Mi,aE as Ei,ba as Di,aN as Lt,X as Ri,aX as Bi,e as tr,v as Dr,bb as Oi,bc as Li,bd as $i,be as Fi,b0 as _i,aR as Wi,O as Xi,
|
|
2
|
-
N as zi,aW as rr,W as Rr,ae as ji,bf as Hi,ar as Br,ad as Ji,bg as Gi,at as Ui,a9 as Or}from"./engine-
|
|
3
|
-
import{b as $t,l as Qi,g as en,d as tn,h as rn,t as nn}from"./BidiText-Bkp4Y90s.js";import{k as on,s as Lr,j as sn,p as an,W as $r,l as ln,c as nr,b as cn,e as dn}from"./TableBorders-
|
|
2
|
+
N as zi,aW as rr,W as Rr,ae as ji,bf as Hi,ar as Br,ad as Ji,bg as Gi,at as Ui,a9 as Or}from"./engine-LMUnxdm2.js";import{c as Ki,h as Zi,m as ir}from"./capture-i_dPkQIS.js";import{g as Vi,a as qi,G as Yi}from"./graftExport-G-dG7Vcc.js";
|
|
3
|
+
import{b as $t,l as Qi,g as en,d as tn,h as rn,t as nn}from"./BidiText-Bkp4Y90s.js";import{k as on,s as Lr,j as sn,p as an,W as $r,l as ln,c as nr,b as cn,e as dn}from"./TableBorders-DVhdvo6f.js";import{
|
|
4
4
|
b as Qe}from"./TableGrid-DbroRucl.js";import{R as Ct}from"./suggestionAuthorship-B-IuLQlE.js";import{b as pn,c as Fr}from"./MathRenderer-Bz9WEVvF.js";import{J as _r}from"./jszip.min-CPW0h1Kx.js";import{
|
|
5
|
-
F as Ae,L as hn,h as or,g as mn}from"./Typography-
|
|
5
|
+
F as Ae,L as hn,h as or,g as mn}from"./Typography-B4gndEdB.js";import{c as gn}from"./chromeImageLayout-BiQ3Iz1-.js";import{a as un}from"./DocumentStylesheet-CEEt18sr.js";const Wr=()=>new XMLSerializer,
|
|
6
6
|
Xr=new Set(["w:rStyle","w:b","w:i","w:u","w:strike","w:dstrike","w:smallCaps","w:caps","w:vanish","w:lang","w:spacing","w:vertAlign","w:color","w:highlight","w:shd","w:rFonts","w:sz","w:rPrChange","w:\
|
|
7
7
|
bCs","w:iCs","w:szCs","w:highlightCs","w:ins","w:del","w:rtl","w:specVanish","w:imprint","w:emboss","w:snapToGrid"]),zr=new Set(["w:pStyle","w:keepNext","w:keepLines","w:widowControl","w:bidi","w:jc",
|
|
8
8
|
"w:ind","w:pageBreakBefore","w:spacing","w:contextualSpacing","w:outlineLvl","w:numPr","w:pBdr","w:shd","w:tabs","w:rPr","w:sectPr","w:pPrChange"]),jr=new Set(["w:tblStyle","w:tblW","w:jc","w:tblInd",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{c,h as u,m as g,r as f}from"./capture-
|
|
2
|
-
import{a as i}from"./graftExport-
|
|
1
|
+
import{c,h as u,m as g,r as f}from"./capture-i_dPkQIS.js";import{C as S,a as d,b as m,c as l,i as p,f as h,g as R,h as x,n as C,p as D,l as E,k as y,d as b,s as k,j as _,e as A}from"./signatures-DTNDS2PH.js";
|
|
2
|
+
import{a as i}from"./graftExport-G-dG7Vcc.js";import{G,b as I,g as B,r as T}from"./graftExport-G-dG7Vcc.js";import{C as F,D as H,c as N,g as P,l as U,s as v}from"./carrier-pYM9xf6x.js";function L(a,o){
|
|
3
3
|
const r=a.docxSource;if(!r)return s("no-capture");if(!o)return s("no-carrier");if(!r.sourceHash)return s("unpaired-capture");if(o.hash!==r.sourceHash)return s("carrier-hash-mismatch");const e=i(a),n=Object.
|
|
4
4
|
entries(e.domains).filter(([,t])=>!t).map(([t])=>t);return{fidelity:e.fullyExact?"exact":"grafted",regeneratedBlockIds:e.regeneratedBlockIds,changedDomains:n}}function s(a){return{fidelity:"converted",
|
|
5
5
|
regeneratedBlockIds:[],changedDomains:[],convertedReason:a}}export{F as CARRIER_MAP_KEY,S as CURRENT_GRAFT_SIGNATURE_VERSION,H as DEFAULT_CARRIER_BYTE_CAP,G as GraftProofError,i as assessGraftability,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as A,a_ as T,aM as V,b6 as J,b4 as K,W as P,C as U,aV as Z,r as j,Q as B,O as Y,aW as I,N as Q,R as tt,t as et,aS as rt,b7 as nt,aU as it}from"./engine-
|
|
2
|
-
r as st,s as lt}from"./ListNumbering-Qlu6AuRZ.js";import{f as O}from"./footnoteFlatten-
|
|
3
|
-
import{a as ht,l as dt,b as pt,c as z}from"./MathRenderer-Bz9WEVvF.js";import{b as H,a as q,e as mt,g as ut,c as gt,l as ft,h as bt}from"./BidiText-Bkp4Y90s.js";import{c as yt,F as N,g as R,d as xt,L as E}from"./Typography-
|
|
1
|
+
import{a as A,a_ as T,aM as V,b6 as J,b4 as K,W as P,C as U,aV as Z,r as j,Q as B,O as Y,aW as I,N as Q,R as tt,t as et,aS as rt,b7 as nt,aU as it}from"./engine-LMUnxdm2.js";import{i as at,p as D,e as ot,
|
|
2
|
+
r as st,s as lt}from"./ListNumbering-Qlu6AuRZ.js";import{f as O}from"./footnoteFlatten-EE85Hjre.js";import{i as ct}from"./HorizontalRuleOrnaments-gmUZ3R7Q.js";import{b as F}from"./TableGrid-DbroRucl.js";
|
|
3
|
+
import{a as ht,l as dt,b as pt,c as z}from"./MathRenderer-Bz9WEVvF.js";import{b as H,a as q,e as mt,g as ut,c as gt,l as ft,h as bt}from"./BidiText-Bkp4Y90s.js";import{c as yt,F as N,g as R,d as xt,L as E}from"./Typography-B4gndEdB.js";
|
|
4
4
|
const $t=[[/[\p{Script=Hiragana}\p{Script=Katakana}]/u,"ja"],[/\p{Script=Hangul}/u,"ko"],[/\p{Script=Han}/u,"und-Hani"],[/\p{Script=Arabic}/u,"und-Arab"],[/\p{Script=Hebrew}/u,"und-Hebr"],[/\p{Script=Devanagari}/u,
|
|
5
5
|
"und-Deva"],[/\p{Script=Bengali}/u,"und-Beng"],[/\p{Script=Gurmukhi}/u,"pa"],[/\p{Script=Gujarati}/u,"gu"],[/\p{Script=Oriya}/u,"or"],[/\p{Script=Tamil}/u,"ta"],[/\p{Script=Telugu}/u,"te"],[/\p{Script=Kannada}/u,
|
|
6
6
|
"kn"],[/\p{Script=Malayalam}/u,"ml"],[/\p{Script=Sinhala}/u,"si"],[/\p{Script=Thai}/u,"th"],[/\p{Script=Lao}/u,"lo"],[/\p{Script=Khmer}/u,"km"],[/\p{Script=Myanmar}/u,"my"],[/\p{Script=Tibetan}/u,"bo"],
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a_ as k,b0 as y,aR as b,aK as $,b1 as w,b2 as M,b3 as T,b4 as I,a as u,b5 as _}from"./engine-
|
|
1
|
+
import{a_ as k,b0 as y,aR as b,aK as $,b1 as w,b2 as M,b3 as T,b4 as I,a as u,b5 as _}from"./engine-LMUnxdm2.js";import{b as j}from"./TableGrid-DbroRucl.js";import{a as C,e as v,i as N}from"./ListNumbering-Qlu6AuRZ.js";
|
|
2
2
|
class L{static toMarkdown(e){if(!e||e.type!=="doc"||!e.children)return"";this.exportListNumbering=C(e);const n=[];for(const t of e.children){if(t.type==="header-footer"||t.type==="footnote")continue;if(t.
|
|
3
3
|
type==="toc"){const a=this.tocToMarkdown(t,e);a!==null&&n.push(a);continue}const s=this.blockToMarkdown(t);s!==null&&n.push(s)}const i=[...e.notes??[],...e.children.filter(t=>t.type==="footnote")];if(i.
|
|
4
4
|
length>0){const t=new Map,s=c=>{if(!c||typeof c!="object")return;if(Array.isArray(c)){c.forEach(s);return}const o=c;o.type!=="footnote"&&(o.marks?.footnoteRef&&!t.has(o.marks.footnoteRef)&&t.set(o.marks.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a_ as P,a as S}from"./engine-
|
|
1
|
+
import{a_ as P,a as S}from"./engine-LMUnxdm2.js";import{N as _,k as Z,m as E,a as C,l as q,f as U,h as J,g as G,i as O,c as K,j as k,d as Q,p as Y,b as tt,n as W,M as et,s as nt}from"./OfficeImportShared-CrOpHpJ-.js";
|
|
2
2
|
class st{static async parseFile(e){const t=(await import("./jszip.min-CPW0h1Kx.js").then(d=>d.j)).default,n=await e.arrayBuffer(),s=await t.loadAsync(new Uint8Array(n)),a=s.file("content.xml");if(!a)throw new Error(
|
|
3
3
|
"Invalid ODT file: missing content.xml");const o=await a.async("text"),l=await s.file("styles.xml")?.async("text"),c=new Set;for(const d of[o,l??""])for(const u of d.matchAll(/xlink:href="([^"]+)"/g))
|
|
4
4
|
c.add(R(ct(u[1])));const h=new Map;return await Promise.all([...c].map(async d=>{const u=s.file(d);u&&!u.dir&&h.set(d,await u.async("uint8array"))})),this.fromContentXml(o,l,{parts:h})}static fromContentXml(e,t,n={}){
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a_ as l,b1 as M,ae as P,aN as m,bj as g,a as f,aH as y}from"./engine-
|
|
1
|
+
import{a_ as l,b1 as M,ae as P,aN as m,bj as g,a as f,aH as y}from"./engine-LMUnxdm2.js";import{R as v}from"./suggestionAuthorship-B-IuLQlE.js";import{b as S}from"./TableGrid-DbroRucl.js";const k=new Set(
|
|
2
2
|
["http","https","mailto","tel","ftp"]);function j(n){const t=n?.trim();if(!t)return;const e=t.replace(/[\u0000- \u007f]/g,"");if(e.startsWith("//")||e.startsWith("\\\\"))return;const r=/^([a-z][a-z0-9+.-]*):/i.
|
|
3
3
|
exec(e)?.[1];if(!(r&&!k.has(r.toLowerCase())))return t}function $(n){return n/15}function d(n){return Math.round(n*100)/100}function A(n){if(!n)return;const t=/^\s*(-?\d*\.?\d+)\s*(pt|px|cm|mm|in|pc|em)\s*$/i.
|
|
4
4
|
exec(n);if(!t)return;const e=parseFloat(t[1]);if(Number.isFinite(e))switch(t[2].toLowerCase()){case"px":return e;case"pt":return e*96/72;case"pc":return e*16;case"in":return e*96;case"cm":return e*96/
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import{bk as ne,bl as Pt,bm as Ht,bn as Nt,r as Gt,bo as Rt,R as zt,e as Ut,t as re,bp as se,bq as le,br as ce,bs as he,ae as Kt,bt as tt,af as jt,b0 as ge,aR as de,bu as Yt,bv as fe,bw as vt,bx as It,
|
|
2
|
-
by as dt,bz as me,bA as Pe,bB as pe,p as ue,a_ as Ft,h as Te,a8 as xe,ab as ye,a4 as Bt}from"./engine-
|
|
3
|
-
e as $t,f as Vt,d as we,c as Oe,s as Ce,h as Me,i as ke,j as Ne,D as St,k as Re,l as ve,m as Ie,w as qt,n as Jt,o as Be,p as Zt,q as Qt,r as Ee,S as te}from"./index-
|
|
4
|
-
c as Ae,r as We,o as He,b as Ge,q as ze}from"./TableBorders-
|
|
5
|
-
import{c as qe,p as Et,K as ee,e as Je}from"./DocumentLayoutEngine-
|
|
2
|
+
by as dt,bz as me,bA as Pe,bB as pe,p as ue,a_ as Ft,h as Te,a8 as xe,ab as ye,a4 as Bt}from"./engine-LMUnxdm2.js";import{b as _e,s as be,o as Fe,p as Se,n as Le}from"./ListNumbering-Qlu6AuRZ.js";import{
|
|
3
|
+
e as $t,f as Vt,d as we,c as Oe,s as Ce,h as Me,i as ke,j as Ne,D as St,k as Re,l as ve,m as Ie,w as qt,n as Jt,o as Be,p as Zt,q as Qt,r as Ee,S as te}from"./index-BLb10wQt.js";import{m as De,p as Xe,
|
|
4
|
+
c as Ae,r as We,o as He,b as Ge,q as ze}from"./TableBorders-DVhdvo6f.js";import{b as Ue,n as Ke}from"./TableGrid-DbroRucl.js";import{i as je,l as Ye,s as $e,d as Ve}from"./HorizontalRuleOrnaments-gmUZ3R7Q.js";
|
|
5
|
+
import{c as qe,p as Et,K as ee,e as Je}from"./DocumentLayoutEngine-C62pyGVf.js";import{a as Ze}from"./chromeImageLayout-BiQ3Iz1-.js";import{l as Dt}from"./UnicodeUtils-CXtusU4g.js";import{createStandardLayout as Qe}from"./DocumentLayout-CsU5MR-3.js";
|
|
6
6
|
import{g as ta}from"./PageNumeralFonts-BWzI061X.js";import{l as Xt,a as ea,b as aa,g as ia,f as oa,i as na}from"./BidiText-Bkp4Y90s.js";import{r as Lt,o as ra,e as sa,d as la,b as ca}from"./MathRenderer-Bz9WEVvF.js";
|
|
7
|
-
import{L as ha,F as yt,l as wt,e as ae,g as ie,d as ga,f as da}from"./Typography-
|
|
7
|
+
import{L as ha,F as yt,l as wt,e as ae,g as ie,d as ga,f as da}from"./Typography-B4gndEdB.js";import{b as oe}from"./base64-Di1bxoXD.js";const kt=new Map;ra(()=>kt.clear());function fa(it){const t=String.
|
|
8
8
|
fromCharCode(...it.subarray(0,4));return it[0]===0&&it[1]===1&&it[2]===0&&it[3]===0||t==="true"||t==="OTTO"}function ma(it){let t="";for(let e=0;e<it.length;e+=32768)t+=String.fromCharCode(...it.subarray(
|
|
9
9
|
e,e+32768));return btoa(t)}async function Pa(it){try{const t=await fetch(Lt(`fonts/${encodeURIComponent(it)}`),{credentials:"omit"});if(!t.ok)return null;const e=new Uint8Array(await t.arrayBuffer());
|
|
10
10
|
return fa(e)?ma(e):null}catch{return null}}async function pa(it){let t=kt.get(it);return t||(t=Pa(it),kt.set(it,t),t.then(e=>{e===null&&kt.delete(it)})),t}const J=it=>({normal:it,bold:it}),ua={japanese:{
|
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import{a_ as
|
|
2
|
-
import{f as
|
|
3
|
-
|
|
4
|
-
"windows-1252"}function C(a){const t=String(a);return
|
|
5
|
-
|
|
6
|
-
this.kind=t,this.items=[],this.runs=[],this.runText="",this.runMarks={},this.paraId=w(),this.suppressEmptyPar=!1}}const
|
|
7
|
-
["ldblquote","“"],["rdblquote","”"],["bullet","•"],["emspace"," "],["enspace"," "],["qmspace"," "],["zwj",""],["zwnj",""],["ltrmark",""],["rtlmark",""]]),
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"ftnsep","ftnsepc","ftncn","blipuid","picprop","atnicn","atntime","do","falt","panose","fname","oldcprops","oldpprops","oldtprops","oldsprops","annotation-ignore"]),
|
|
11
|
-
|
|
12
|
-
"fldrslt","header","headerl","headerr","headerf","footer","footerl","footerr","footerf"]),
|
|
13
|
-
|
|
14
|
-
"footerl","even"],["footerf","first"]]);function
|
|
15
|
-
{r:0,g:0,b:0},this.colorHasValue=!1,this.expandedIndex=0,this.expandedParts=[],this.styles=new Map,this.currentStyle=null,this.lists=new Map,this.currentList=null,this.listOverrides=
|
|
16
|
-
null,this.revAuthors=[],this.currentFontEntry=null,this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1,this.body=new L("body"),this.notes=new
|
|
17
|
-
[],this.openCommentRanges=[],this.commentMeta={},this.annotationCounter=0,this.commentRangeIds=new Map,this.commentIds=new Set,this.page={margins:{}},this.sectionSeen
|
|
18
|
-
0,this.cachedMarksVersion=-1,this.cachedMarks={},this.pendingBytes=[],this.pendingBytesEncoding="",this.chainsSeen=new Set,this.ansiEncoding=
|
|
19
|
-
512)),this.state={dest:"body",chars:{},para:{borders:{}},unicodeSkip:1,storyRef:{story:this.body}}}read(){this.tokenize(),this.flushBytes();const t=this.body;this.flushRun(
|
|
20
|
-
length>0)&&this.flushParagraph(t);const e=this.buildBlocks(t.items,"body");
|
|
21
|
-
this.headers).length>0&&(s.headers=this.headers),Object.keys(this.footers).length>0&&(s.footers=this.footers);const r=
|
|
22
|
-
pageLayout();return n&&(s.pageLayout=n),s}tokenize(){const t=this.rtf,e=t.length,s=/\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/y;let r=0;for(;r<e;){const n=t.charCodeAt(r);if(n===
|
|
23
|
-
r++;continue}if(n===125){this.flushBytes(),this.popGroup(),r++;continue}if(n===10||n===13){r++;continue}if(n!==92){let l=r+1;for(;l<e;){const f=t.charCodeAt(l);
|
|
24
|
-
13)break;l++}this.literal(t.slice(r,l)),r=l;continue}const i=t[r+1];if(i===void 0)break;if(i==="\\"||i==="{"||i==="}"){this.flushBytes(),this.text(i),r+=2;continue}
|
|
25
|
-
r+2,r+4),16);r+=4,Number.isNaN(l)||this.byte(l);continue}if(this.flushBytes(),i==="*"){this.state.starred=!0,r+=2;continue}if(i==="~"){this.text(" "),r+=2;continue}
|
|
26
|
-
if(i==="-"){r+=2;continue}if(i===`
|
|
1
|
+
import{a_ as I,a as w,b0 as K,aR as U,aK as G}from"./engine-LMUnxdm2.js";import{d as j}from"./TextDecoding-IPbuUqcC.js";import{N as z,k as _,r as $,s as Y,a as T,t as k,i as X,m as Z,b as J,c as Q,d as tt,
|
|
2
|
+
l as et,f as st,e as rt,g as nt,p as it}from"./OfficeImportShared-CrOpHpJ-.js";import{f as at}from"./footnoteFlatten-EE85Hjre.js";import{a as ot,e as lt}from"./ListNumbering-Qlu6AuRZ.js";import{b as ct}from"./TableGrid-DbroRucl.js";
|
|
3
|
+
const ht={65001:"utf-8",932:"shift_jis",936:"gb18030",949:"euc-kr",950:"big5",874:"windows-874",1e4:"macintosh",437:"windows-1252",850:"windows-1252"};function dt(a){const t=/\\ansicpg(\d+)/i.exec(a)?.[1];
|
|
4
|
+
return t?C(t):/\\mac\b/.test(a)?"macintosh":"windows-1252"}function C(a){const t=String(a);return ht[t]??`windows-${t}`}const ut={77:1e4,128:932,129:949,134:936,136:950,161:1253,162:1254,163:1258,177:1255,
|
|
5
|
+
178:1256,186:1257,204:1251,222:874,238:1250},W=new Map;function pt(a,t){let e=W.get(t);if(!e){try{j(new Uint8Array,t),e=t}catch{e="windows-1252"}W.set(t,e)}return j(a instanceof Uint8Array?a:new Uint8Array(
|
|
6
|
+
a),e)}class L{constructor(t){this.kind=t,this.items=[],this.runs=[],this.runText="",this.runMarks={},this.paraId=w(),this.suppressEmptyPar=!1}}const ft=new Map([["emdash","—"],["endash","–"],["lqu\
|
|
7
|
+
ote","‘"],["rquote","’"],["ldblquote","“"],["rdblquote","”"],["bullet","•"],["emspace"," "],["enspace"," "],["qmspace"," "],["zwj",""],["zwnj",""],["ltrmark",""],["rtlmark",""]]),
|
|
8
|
+
gt=new Set(["info","xmlnstbl","themedata","colorschememapping","latentstyles","datastore","generator","filetbl","rsidtbl","nonshppict","objdata","objclass","objname","shpinst","shptxt","userprops","do\
|
|
9
|
+
cvar","pgdsctbl","mmathPr","bkmkstart","bkmkend","xe","tc","txe","template","private","passwordhash","wgrffmtfilter","defchp","defpap","listpicture","pnseclvl","protusertbl","fchars","lchars","aftnsep",
|
|
10
|
+
"aftnsepc","aftncn","ftnsep","ftnsepc","ftncn","blipuid","picprop","atnicn","atntime","do","falt","panose","fname","oldcprops","oldpprops","oldtprops","oldsprops","annotation-ignore"]),mt=new Set(["ex\
|
|
11
|
+
pandedcolortbl","listtable","listoverridetable","shppict","fldinst","annotation","atnauthor","atnid","atnref","atndate","atrfstart","atrfend","pn","revtbl","footnote"]),bt=new Set(["pict","footnote","\
|
|
12
|
+
annotation","fldinst","fldrslt","header","headerl","headerr","headerf","footer","footerl","footerr","footerf"]),kt=new Set(["ul","uld","uldash","uldashd","uldashdd","uldb","ulhwave","ulldash","ulth","\
|
|
13
|
+
ulthd","ulthdash","ulthdashd","ulthdashdd","ulthldash","ululdbwave","ulw","ulwave"]),E=new Map([["header","default"],["headerr","default"],["headerl","even"],["headerf","first"],["footer","default"],[
|
|
14
|
+
"footerr","default"],["footerl","even"],["footerf","first"]]);function F(a,t={}){return new vt(a,t).read()}class vt{constructor(t,e){this.rtf=t,this.options=e,this.defaultFont=0,this.fonts=new Map,this.
|
|
15
|
+
colors=[],this.colorParts={r:0,g:0,b:0},this.colorHasValue=!1,this.expandedIndex=0,this.expandedParts=[],this.styles=new Map,this.currentStyle=null,this.lists=new Map,this.currentList=null,this.listOverrides=
|
|
16
|
+
new Map,this.currentOverride=null,this.revAuthors=[],this.currentFontEntry=null,this.rowDefs=[],this.pendingCellDef={},this.rowIsHeader=!1,this.body=new L("body"),this.notes=new z("rtffn"),this.headers=
|
|
17
|
+
{},this.footers={},this.comments=[],this.openCommentRanges=[],this.commentMeta={},this.annotationCounter=0,this.commentRangeIds=new Map,this.commentIds=new Set,this.page={margins:{}},this.sectionSeen=
|
|
18
|
+
!1,this.stack=[],this.marksVersion=0,this.cachedMarksVersion=-1,this.cachedMarks={},this.pendingBytes=[],this.pendingBytesEncoding="",this.chainsSeen=new Set,this.ansiEncoding=dt(t.slice(0,4096)),this.
|
|
19
|
+
cocoa=/\\cocoartf/.test(t.slice(0,512)),this.state={dest:"body",chars:{},para:{borders:{}},unicodeSkip:1,storyRef:{story:this.body}}}read(){this.tokenize(),this.flushBytes();const t=this.body;this.flushRun(
|
|
20
|
+
t),t.runs.some(i=>i.text.trim().length>0)&&this.flushParagraph(t);const e=this.buildBlocks(t.items,"body");V(e),e.length===0&&e.push(I());const s={type:"doc",children:e};this.notes.notes.length>0&&(s.
|
|
21
|
+
notes=this.notes.notes),Object.keys(this.headers).length>0&&(s.headers=this.headers),Object.keys(this.footers).length>0&&(s.footers=this.footers);const r=_(this.comments,[s.children,s.notes??[]]);r.length>
|
|
22
|
+
0&&(s.comments=r);const n=this.pageLayout();return n&&(s.pageLayout=n),s}tokenize(){const t=this.rtf,e=t.length,s=/\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/y;let r=0;for(;r<e;){const n=t.charCodeAt(r);if(n===
|
|
23
|
+
123){this.flushBytes(),this.pushGroup(),r++;continue}if(n===125){this.flushBytes(),this.popGroup(),r++;continue}if(n===10||n===13){r++;continue}if(n!==92){let l=r+1;for(;l<e;){const f=t.charCodeAt(l);
|
|
24
|
+
if(f===92||f===123||f===125||f===10||f===13)break;l++}this.literal(t.slice(r,l)),r=l;continue}const i=t[r+1];if(i===void 0)break;if(i==="\\"||i==="{"||i==="}"){this.flushBytes(),this.text(i),r+=2;continue}
|
|
25
|
+
if(i==="'"){const l=parseInt(t.slice(r+2,r+4),16);r+=4,Number.isNaN(l)||this.byte(l);continue}if(this.flushBytes(),i==="*"){this.state.starred=!0,r+=2;continue}if(i==="~"){this.text(" "),r+=2;continue}
|
|
26
|
+
if(i==="_"){this.text("‑"),r+=2;continue}if(i==="-"){r+=2;continue}if(i===`
|
|
27
27
|
`||i==="\r"){this.controlWord("par",null),r+=2;continue}s.lastIndex=r;const o=s.exec(t);if(!o){r+=2;continue}r+=o[0].length;const c=o[1],d=o[2]!==void 0?parseInt(o[2],10):null;if(c==="bin"&&d!==null&&
|
|
28
28
|
d>0){this.binary(t.slice(r,r+d)),r+=d;continue}if(c==="u"&&d!==null){this.text(String.fromCharCode(d<0?d+65536:d));let l=this.state.unicodeSkip;for(;l>0&&r<e;){const f=t[r];if(f==="\\")if(t[r+1]==="'")
|
|
29
29
|
r+=4;else{s.lastIndex=r;const m=s.exec(t);r+=m?m[0].length:2}else{if(f==="{"||f==="}")break;if(f===`
|
|
@@ -36,9 +36,9 @@ e.capture&&this.finishStyle(t.capture.text);break;case"listtext":e.dest!=="listt
|
|
|
36
36
|
capture.text.split(";").slice(0,-1))this.revAuthors.push(s.trim());break}t.opensStory&&this.finishStory(t,e)}literal(t){const e=this.state;if(this.flushBytes(),e.dest==="pict"){e.pict?.hex.push(t);return}
|
|
37
37
|
if(this.options.binary){let s=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)>=128&&(r>s&&(this.flushBytes(),this.text(t.slice(s,r))),this.byte(t.charCodeAt(r)&255),s=r+1);s<t.length&&(this.flushBytes(),
|
|
38
38
|
this.text(t.slice(s)));return}this.text(t)}byte(t){const e=this.currentEncoding();this.pendingBytes.length>0&&e!==this.pendingBytesEncoding&&this.flushBytes(),this.pendingBytesEncoding=e,this.pendingBytes.
|
|
39
|
-
push(t)}flushBytes(){if(this.pendingBytes.length===0)return;const t=this.pendingBytes;this.pendingBytes=[],this.text(
|
|
39
|
+
push(t)}flushBytes(){if(this.pendingBytes.length===0)return;const t=this.pendingBytes;this.pendingBytes=[],this.text(pt(t,this.pendingBytesEncoding))}currentEncoding(){const t=this.state.chars;return this.
|
|
40
40
|
fonts.get(t.font??t.lochFont??this.defaultFont)?.encoding??this.ansiEncoding}binary(t){const e=this.state.pict;if(this.state.dest!=="pict"||!e)return;const s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)
|
|
41
|
-
s[r]=t.charCodeAt(r)&255;(e.binary??(e.binary=[])).push(s)}text(t){if(!t)return;const e=this.state;switch(e.dest){case"body":{const s=e.storyRef.story,r=this.effectiveMarks();
|
|
41
|
+
s[r]=t.charCodeAt(r)&255;(e.binary??(e.binary=[])).push(s)}text(t){if(!t)return;const e=this.state;switch(e.dest){case"body":{const s=e.storyRef.story,r=this.effectiveMarks();Y(r,s.runMarks)||(this.flushRun(
|
|
42
42
|
s),s.runMarks=r),s.runText+=t,s.suppressEmptyPar=!1;return}case"fonttbl":case"stylesheet":case"listtext":case"fldinst":case"meta":e.capture&&(e.capture.text+=t),e.dest==="fonttbl"&&t.includes(";")&&this.
|
|
43
43
|
fontTableSemicolons(t);return;case"colortbl":for(const s of t)s===";"&&(this.colors.push(this.colorHasValue?$(this.colorParts.r,this.colorParts.g,this.colorParts.b):void 0),this.colorParts={r:0,g:0,b:0},
|
|
44
44
|
this.colorHasValue=!1);return;case"expandedcolortbl":for(const s of t){if(s!==";")continue;const r=this.expandedParts,n=i=>i/1e5*255;if(r.length>=3)this.colors[this.expandedIndex]=$(n(r[0]),n(r[1]),n(
|
|
@@ -50,37 +50,37 @@ name;r&&(s.fontFamily=r),e.halfPoints&&e.halfPoints>0&&(s.fontSize=T(e.halfPoint
|
|
|
50
50
|
highlight]:void 0)??(e.background?this.colors[e.background]:void 0);return i&&i!=="#ffffff"&&(s.backgroundColor=i),e.expandTwips&&(s.letterSpacing=T(k(e.expandTwips))),t.link&&(s.link=t.link),t.fieldKind&&
|
|
51
51
|
(s.field=t.fieldKind),this.openCommentRanges.length>0&&t.storyRef.story.kind!=="annotation"&&(s.comment=this.openCommentRanges.join(",")),e.deleted?Object.assign(s,this.revisionMarks("deletion",e.revAuthorDel??
|
|
52
52
|
e.revAuthor,e.revTimeDel??e.revTime)):e.revised&&Object.assign(s,this.revisionMarks("insertion",e.revAuthor,e.revTime)),this.cachedMarks=s,this.cachedMarksVersion=this.marksVersion,s}revisionMarks(t,e,s){
|
|
53
|
-
const r=e!==void 0?this.revAuthors[e]:void 0,n=s!==void 0?
|
|
53
|
+
const r=e!==void 0?this.revAuthors[e]:void 0,n=s!==void 0?q(s):void 0;return X(t,`rtfrev-${t==="insertion"?"ins":"del"}-${e??0}-${s??0}`,r&&r!=="Unknown"?r:void 0,n)}flushRun(t){t.runText&&(t.runs.push(
|
|
54
54
|
{type:"text",text:t.runText,marks:{...t.runMarks}}),t.runText="")}flushParagraph(t,e=!1){this.flushRun(t);const s=t.runs.filter(r=>r.text.length>0);if(t.runs=[],s.length===0&&t.suppressEmptyPar&&!e){t.
|
|
55
|
-
suppressEmptyPar=!1,t.listText=void 0,t.paraId=w();return}t.items.push({kind:"para",id:t.paraId,runs:
|
|
55
|
+
suppressEmptyPar=!1,t.listText=void 0,t.paraId=w();return}t.items.push({kind:"para",id:t.paraId,runs:Z(s),para:{...this.state.para,borders:{...this.state.para.borders}},...t.listText!==void 0?{listText:t.
|
|
56
56
|
listText}:{},...e?{forcedInTable:!0}:{}}),t.listText=void 0,t.suppressEmptyPar=!1,t.paraId=w()}controlWord(t,e){const s=this.state,r=s.starred;if(s.starred=!1,s.dest!=="skip"&&!this.startDestination(t)){
|
|
57
|
-
if(r&&!
|
|
57
|
+
if(r&&!mt.has(t)){s.dest="skip";return}if(gt.has(t)){s.dest="skip";return}switch(s.dest){case"fonttbl":this.fontTableWord(t,e);return;case"colortbl":this.colorTableWord(t,e);return;case"expandedcolort\
|
|
58
58
|
bl":t==="c"&&e!==null?this.expandedParts.push(e):(t==="cssrgb"||t==="csgray"||t==="csgenericrgb")&&(this.expandedParts=[]);return;case"stylesheet":this.styleSheetWord(t,e);return;case"listtable":this.
|
|
59
59
|
listTableWord(t,e);return;case"listoverridetable":this.listOverrideWord(t,e);return;case"pict":this.pictWord(t,e);return;case"pn":this.pnWord(t,e);return;case"listtext":case"fldinst":case"meta":t==="t\
|
|
60
60
|
ab"&&this.text(" ");return;case"revtbl":return}if(this.characterWord(t,e)){this.marksVersion++;return}this.paragraphWord(t,e)||this.structureWord(t,e)}}startDestination(t){const e=this.state;if(e.dest!==
|
|
61
|
-
"body"&&
|
|
61
|
+
"body"&&bt.has(t))return e.dest="skip",!0;switch(t){case"fonttbl":return e.dest="fonttbl",e.capture={text:""},!0;case"colortbl":return e.dest="colortbl",this.colors=[],!0;case"expandedcolortbl":return e.
|
|
62
62
|
dest="expandedcolortbl",this.expandedIndex=0,this.expandedParts=[],!0;case"stylesheet":return e.dest="stylesheet",!0;case"listtable":return e.dest="listtable",!0;case"listoverridetable":return e.dest=
|
|
63
63
|
"listoverridetable",!0;case"revtbl":return e.dest="revtbl",!0;case"pict":return e.dest="pict",e.pict={hex:[]},!0;case"shppict":case"shprslt":case"result":case"shp":case"object":case"field":return t===
|
|
64
64
|
"field"&&(e.field={instr:""}),!0;case"fldinst":return e.dest="fldinst",e.capture={text:""},!0;case"fldrslt":{const s=e.field?.instr??"",r=/^\s*HYPERLINK\s+(?:\\[a-z]\s+)*"([^"]+)"/i.exec(s);return r&&
|
|
65
|
-
!/^\s*HYPERLINK\s+\\l\b/i.test(s)&&(e.link=
|
|
65
|
+
!/^\s*HYPERLINK\s+\\l\b/i.test(s)&&(e.link=J(r[1])),/^\s*PAGE\b/i.test(s)&&(e.fieldKind="page"),/^\s*NUMPAGES\b/i.test(s)&&(e.fieldKind="numPages"),this.marksVersion++,!0}case"listtext":case"pntext":return e.
|
|
66
66
|
dest="listtext",e.capture={text:""},!0;case"pn":return e.dest="pn",e.para.pn={kind:"number",level:0},!0;case"footnote":return this.openStory("footnote");case"annotation":return this.openStory("annotat\
|
|
67
|
-
ion");case"atnauthor":case"atnid":case"atnref":case"atndate":case"atrfstart":case"atrfend":return e.dest="meta",e.metaKind=t,e.capture={text:""},!0;default:return
|
|
67
|
+
ion");case"atnauthor":case"atnid":case"atnref":case"atndate":case"atrfstart":case"atrfend":return e.dest="meta",e.metaKind=t,e.capture={text:""},!0;default:return E.has(t)?(e.dest="body",e.opensStory=
|
|
68
68
|
!0,e.storyRef={story:new L("header")},e.para={borders:{}},e.headerWord=t,!0):!1}}openStory(t){const e=this.state;return e.dest="body",e.opensStory=!0,e.storyRef={story:new L(t)},e.para={borders:{}},e.
|
|
69
69
|
link=void 0,t==="annotation"&&(this.annotationRef=void 0,this.annotationDate=void 0),this.marksVersion++,!0}finishStory(t,e){const s=t.storyRef.story;if(this.flushRun(s),s.runs.some(i=>i.text.length>0)){
|
|
70
|
-
const i=this.state;this.state=t,this.flushParagraph(s),this.state=i}const r=this.buildBlocks(s.items,s.kind);
|
|
70
|
+
const i=this.state;this.state=t,this.flushParagraph(s),this.state=i}const r=this.buildBlocks(s.items,s.kind);V(r);const n=e.storyRef.story;if(s.kind==="footnote"||s.kind==="endnote"){if(e.dest!=="body")
|
|
71
71
|
return;this.flushRun(n),this.state=e,this.marksVersion++;const i=this.effectiveMarks(),o=this.notes.add(s.kind,r,i);n.runs.push(o),n.runMarks={},this.marksVersion++;return}if(s.kind==="header"){const i=t.
|
|
72
|
-
headerWord??"header",o=
|
|
72
|
+
headerWord??"header",o=E.get(i)??"default",c=r.filter(d=>d.type==="paragraph");if(c.some(d=>d.children.some(l=>l.text.trim()!==""||l.marks?.field))){const d=i.startsWith("footer")?this.footers:this.headers;
|
|
73
73
|
d[o]=c}return}if(s.kind==="annotation"){const i=r.map(l=>l.type==="paragraph"?l.children.map(f=>f.text).join("").trim():"").filter(l=>l.length>0).join(`
|
|
74
74
|
|
|
75
75
|
`);this.annotationCounter++;const o=this.annotationRef;let c=`rtfcmt-${o??`point-${this.annotationCounter}`}`,d=o!==void 0&&this.commentRangeIds.has(o);if(this.commentIds.has(c)){d=!1;let l=this.annotationCounter;
|
|
76
76
|
for(;this.commentIds.has(`${c}-${l}`);)l++;c=`${c}-${l}`}this.commentIds.add(c),this.comments.push({id:c,author:this.commentMeta.author||this.commentMeta.initials||"Unknown",...this.commentMeta.initials?
|
|
77
|
-
{initials:this.commentMeta.initials}:{},createdAt:new Date(this.annotationDate!==void 0?
|
|
77
|
+
{initials:this.commentMeta.initials}:{},createdAt:new Date(this.annotationDate!==void 0?q(this.annotationDate)??0:0).toISOString(),bodyMd:i,...d?{}:{anchorBlockId:n.paraId}}),this.commentMeta={}}}finishMeta(t,e){
|
|
78
78
|
switch(t){case"atnauthor":this.commentMeta.author=e;break;case"atnid":this.commentMeta.initials=e;break;case"atnref":this.annotationRef=e;break;case"atndate":{const s=parseInt(e,10);Number.isFinite(s)&&
|
|
79
79
|
(this.annotationDate=s);break}case"atrfstart":e&&(this.commentRangeIds.set(e,`rtfcmt-${e}`),this.openCommentRanges=[...this.openCommentRanges,`rtfcmt-${e}`],this.marksVersion++);break;case"atrfend":e&&
|
|
80
80
|
(this.openCommentRanges=this.openCommentRanges.filter(s=>s!==`rtfcmt-${e}`),this.marksVersion++);break}}fontTableWord(t,e){if(t==="f"&&e!==null){const r=this.state.capture;r&&r.text.trim()&&this.currentFontEntry!==
|
|
81
81
|
null&&this.finishFontName(r.text),this.currentFontEntry=e,this.fonts.has(e)||this.fonts.set(e,{name:""}),this.state.capture={text:""};return}const s=this.currentFontEntry!==null?this.fonts.get(this.currentFontEntry):
|
|
82
|
-
void 0;if(s)if(t==="fcharset"&&e!==null){const r=
|
|
83
|
-
null)return;const e=this.fonts.get(this.currentFontEntry),s=t.replace(/;$/,"").trim();e&&s&&!e.name&&(e.name=this.cocoa?
|
|
82
|
+
void 0;if(s)if(t==="fcharset"&&e!==null){const r=ut[e];r&&(s.encoding=C(r)),e===2&&(s.encoding="windows-1252")}else t==="cpg"&&e!==null&&e>0&&(s.encoding=C(e))}finishFontName(t){if(this.currentFontEntry===
|
|
83
|
+
null)return;const e=this.fonts.get(this.currentFontEntry),s=t.replace(/;$/,"").trim();e&&s&&!e.name&&(e.name=this.cocoa?Rt(s):s)}colorTableWord(t,e){if(e!==null){if(t==="red")this.colorParts.r=e;else if(t===
|
|
84
84
|
"green")this.colorParts.g=e;else if(t==="blue")this.colorParts.b=e;else return;this.colorHasValue=!0}}styleSheetWord(t,e){const s=this.state;t==="s"&&e!==null?(this.currentStyle={index:e},s.capture={text:""}):
|
|
85
85
|
t==="outlinelevel"&&e!==null&&this.currentStyle&&(this.currentStyle.outlineLevel=e)}finishStyle(t){if(!this.currentStyle)return;const e=t.replace(/;[\s\S]*$/,"").trim();this.styles.set(this.currentStyle.
|
|
86
86
|
index,{name:e,outlineLevel:this.currentStyle.outlineLevel}),this.currentStyle=null}listTableWord(t,e){switch(t){case"list":this.currentList={def:{levels:[]}};break;case"listlevel":this.currentList?.def.
|
|
@@ -92,10 +92,10 @@ t==="pnlvl"&&e!==null&&(s.level=Math.max(0,e-1));const r=this.stack[this.stack.l
|
|
|
92
92
|
jpegblip":s.format="jpeg";break;case"emfblip":s.format="emf";break;case"wmetafile":s.format="wmf";break;case"macpict":case"dibitmap":case"wbitmap":case"pmmetafile":s.format??(s.format="unsupported");break;case"\
|
|
93
93
|
picw":e!==null&&(s.picw=e);break;case"pich":e!==null&&(s.pich=e);break;case"picwgoal":e!==null&&(s.goalW=e);break;case"pichgoal":e!==null&&(s.goalH=e);break;case"picscalex":e!==null&&(s.scaleX=e);break;case"\
|
|
94
94
|
picscaley":e!==null&&(s.scaleY=e);break}}finishPicture(t,e){let s;if(t.binary&&t.binary.length>0){const b=t.binary.reduce((u,p)=>u+p.length,0);s=new Uint8Array(b);let h=0;for(const u of t.binary)s.set(
|
|
95
|
-
u,h),h+=u.length}else s=
|
|
95
|
+
u,h),h+=u.length}else s=yt(t.hex.join(""));if(s.length===0)return;const r=t.format&&t.format!=="unsupported"?t.format:void 0,n=Q(s)??r;if(!n)return;const i=n==="emf"||n==="wmf",o=(t.scaleX??100)/100,c=(t.
|
|
96
96
|
scaleY??100)/100,d=(b,h)=>b?k(b):h?i?h/2540*96:h:void 0,l=d(t.goalW,t.picw),f=d(t.goalH,t.pich),m=e.storyRef.story,M=e.para;if(this.flushRun(m),m.runs.some(b=>b.text.length>0)){const b=this.state;this.
|
|
97
|
-
state=e,this.flushParagraph(m),this.state=b}else m.runs=[];const
|
|
98
|
-
{align:
|
|
97
|
+
state=e,this.flushParagraph(m),this.state=b}else m.runs=[];const A=M.align==="justify"?void 0:M.align;m.items.push({kind:"image",image:tt(s,n,{width:l!==void 0?l*o:void 0,height:f!==void 0?f*c:void 0},
|
|
98
|
+
{align:A}),inTable:!!M.inTable}),m.suppressEmptyPar=!0}characterWord(t,e){const s=this.state.chars,r=e!==0;if(kt.has(t))return s.underline=r,!0;switch(t){case"plain":{const{revised:n,deleted:i,revAuthor:o,
|
|
99
99
|
revTime:c,revAuthorDel:d,revTimeDel:l}=s;return this.state.chars={revised:n,deleted:i,revAuthor:o,revTime:c,revAuthorDel:d,revTimeDel:l},!0}case"b":return s.bold=r,!0;case"i":return s.italic=r,!0;case"\
|
|
100
100
|
ulnone":return s.underline=!1,!0;case"strike":return s.strike=r,!0;case"striked":return s.dstrike=r,!0;case"super":return s.superscript=r,s.subscript=!1,!0;case"sub":return s.subscript=r,s.superscript=
|
|
101
101
|
!1,!0;case"nosupersub":return s.superscript=!1,s.subscript=!1,!0;case"caps":return s.caps=r,!0;case"scaps":return s.scaps=r,!0;case"v":return s.hidden=r,!0;case"f":return e!==null&&(s.font=e),!0;case"\
|
|
@@ -125,20 +125,20 @@ pendingCellDef.valign="top";return;case"clvertalc":this.pendingCellDef.valign="m
|
|
|
125
125
|
fieldKind=void 0,this.marksVersion++);return;case"ftnalt":s.kind==="footnote"&&(s.kind="endnote");return;case"uc":this.state.unicodeSkip=e??1;return;case"deff":e!==null&&(this.defaultFont=e);return;case"\
|
|
126
126
|
paperw":case"pgwsxn":e!==null&&(!this.sectionSeen||this.page.widthTwips===void 0)&&(this.page.widthTwips=e);return;case"paperh":case"pghsxn":e!==null&&(!this.sectionSeen||this.page.heightTwips===void 0)&&
|
|
127
127
|
(this.page.heightTwips=e);return;case"landscape":case"lndscpsxn":this.page.landscape=!0;return;case"margl":case"margr":case"margt":case"margb":case"marglsxn":case"margrsxn":case"margtsxn":case"margbsx\
|
|
128
|
-
n":{if(e===null)return;const n=t.slice(4,5);if(t.endsWith("sxn")&&this.sectionSeen)return;this.page.margins[n]=e;return}default:{const n=
|
|
128
|
+
n":{if(e===null)return;const n=t.slice(4,5);if(t.endsWith("sxn")&&this.sectionSeen)return;this.page.margins[n]=e;return}default:{const n=ft.get(t);n!==void 0&&this.text(n)}}}buildBlocks(t,e){const s=[],
|
|
129
129
|
r=i=>i.kind==="cell"||i.kind==="row"||i.kind==="para"&&(!!i.para.inTable||!!i.forcedInTable)||(i.kind==="image"||i.kind==="pagebreak")&&i.inTable;let n=0;for(;n<t.length;){const i=t[n];if(e!=="header"&&
|
|
130
130
|
r(i)){const o=n;for(;n<t.length&&r(t[n]);)n++;const c=this.buildTable(t.slice(o,n),e);c&&s.push(...c);continue}if(i.kind==="para"){const o=this.listInfo(i);if(o&&e!=="header"){const c=[{item:i,info:o}];
|
|
131
131
|
for(n++;n<t.length;){const d=t[n];if(d.kind!=="para"||r(d))break;const l=this.listInfo(d);if(!l||l.key!==o.key)break;c.push({item:d,info:l}),n++}s.push(this.buildList(c));continue}i.para.pageBreakBefore&&
|
|
132
132
|
e==="body"&&s.length>0&&s.push({type:"page-break",id:w()}),s.push(this.buildParagraph(i,e)),n++;continue}i.kind==="image"?s.push(i.image):i.kind==="pagebreak"&&s.push({type:"page-break",id:w()}),n++}return s}buildParagraph(t,e){
|
|
133
|
-
const s=t.runs.length>0?t.runs:[{type:"text",text:"",marks:{}}],r=
|
|
134
|
-
(r.heading=i),n.leftTwips!==void 0){const c=
|
|
133
|
+
const s=t.runs.length>0?t.runs:[{type:"text",text:"",marks:{}}],r=I(s);r.id=t.id;const n=t.para;if(n.align&&(r.align=n.align),n.rtl&&(r.direction="rtl"),e!=="header"){const i=this.headingLevel(n);if(i&&
|
|
134
|
+
(r.heading=i),n.leftTwips!==void 0){const c=et(k(n.leftTwips));c&&(r.leftIndent=c)}if(n.firstTwips!==void 0){const c=st(k(n.firstTwips));c&&(r.firstLineIndent=c)}n.spaceBeforeTwips!==void 0&&(r.spaceBefore=
|
|
135
135
|
T(k(Math.max(0,n.spaceBeforeTwips)))),n.spaceAfterTwips!==void 0&&(r.spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.lineMultiple&&n.lineTwips&&n.lineTwips>0&&(r.lineSpacing=T(n.lineTwips/240)),n.keepNext&&
|
|
136
136
|
(r.keepNext=!0),n.keepLines&&(r.keepLines=!0);const o=n.shading?this.colors[n.shading]:void 0;o&&o!=="#ffffff"&&(r.shading=o),Object.keys(n.borders).length>0&&(r.borders=JSON.stringify(n.borders))}return r}headingLevel(t){
|
|
137
137
|
let e;if(t.outlineLevel!==void 0&&t.outlineLevel<9&&(e=t.outlineLevel+1),e===void 0&&t.style!==void 0){const s=this.styles.get(t.style),r=s?.name&&/^heading\s*(\d)$/i.exec(s.name);r?e=parseInt(r[1],10):
|
|
138
138
|
s?.outlineLevel!==void 0&&s.outlineLevel<9&&(e=s.outlineLevel+1)}if(!(!e||e<1))return Math.min(e,6)}listInfo(t){const e=t.para;if(!this.headingLevel(e)){if(e.ls!==void 0&&e.ls>0){const s=this.listOverrides.
|
|
139
139
|
get(e.ls),r=s!==void 0?this.lists.get(s):void 0,n=Math.max(0,Math.min(8,e.ilvl??0));if(r){const i=r.levels[n]??r.levels[0];if(i&&i.nfc===255&&t.listText===void 0)return;const o=i?i.nfc!==23&&i.nfc!==255:
|
|
140
|
-
!1;return{key:`ls${e.ls}`,ordered:o,level:n,startAt:r.levels[0]?.startAt??1,chain:`rtf-ls-${e.ls}`}}return{key:`ls${e.ls}`,ordered:t.listText!==void 0&&
|
|
141
|
-
ls}`}}if(e.pn)return{key:`pn-${e.pn.kind}`,ordered:e.pn.kind==="number",level:e.pn.level,startAt:1};if(t.listText!==void 0&&t.listText.trim()!==""){const s=
|
|
140
|
+
!1;return{key:`ls${e.ls}`,ordered:o,level:n,startAt:r.levels[0]?.startAt??1,chain:`rtf-ls-${e.ls}`}}return{key:`ls${e.ls}`,ordered:t.listText!==void 0&&O(t.listText),level:n,startAt:1,chain:`rtf-ls-${e.
|
|
141
|
+
ls}`}}if(e.pn)return{key:`pn-${e.pn.kind}`,ordered:e.pn.kind==="number",level:e.pn.level,startAt:1};if(t.listText!==void 0&&t.listText.trim()!==""){const s=O(t.listText);return{key:`lt-${s}`,ordered:s,
|
|
142
142
|
level:0,startAt:1}}}}buildList(t){const e=t[0].info,s=t.map(({item:i,info:o})=>{const c=i.runs.length>0?i.runs:[{type:"text",text:"",marks:{}}];return{type:"list-item",id:i.id,children:c,...o.level>0?
|
|
143
143
|
{indentLevel:o.level}:{},...i.para.rtl?{direction:"rtl"}:{}}}),r={type:"list",id:w(),variant:e.ordered?"ordered":"unordered",children:s};e.ordered&&e.chain?(r.numberingChainId=e.chain,this.chainsSeen.
|
|
144
144
|
has(e.chain)||(this.chainsSeen.add(e.chain),e.startAt!==1&&(r.startNumber=e.startAt))):e.ordered&&e.startAt!==1&&(r.startNumber=e.startAt);const n=t[0].item.para;return n.spaceAfterTwips!==void 0&&(r.
|
|
@@ -146,41 +146,41 @@ spaceAfter=T(k(Math.max(0,n.spaceAfterTwips)))),n.spaceBeforeTwips!==void 0&&(r.
|
|
|
146
146
|
240)),r}buildTable(t,e){const s=[];let r=[],n=[],i=[];for(const h of t)h.kind==="cell"?(r.push({items:n}),n=[]):h.kind==="row"?(n.length>0&&(r.push({items:n}),n=[]),s.push({cells:r,defs:h.defs.length>
|
|
147
147
|
0?h.defs:i,header:h.header}),h.defs.length>0&&(i=h.defs),r=[]):n.push(h);if(n.length>0&&r.push({items:n}),r.length>0&&s.push({cells:r,defs:i,header:!1}),s.length===0)return null;const o=new Set([0]),c=s.
|
|
148
148
|
map(h=>{const u=[];let p=0,g=0;const P=h.defs.length>0?h.defs[h.defs.length-1].right/Math.max(1,h.defs.length):1440;return h.cells.forEach((R,S)=>{const x=h.defs[S],v=x?x.right:g+Math.max(1,Math.round(
|
|
149
|
-
P));if(x?.hmergeCont&&u.length>0){const
|
|
150
|
-
for(const u of h)o.add(Math.max(d,u.left)),o.add(u.right);const l=xt(
|
|
149
|
+
P));if(x?.hmergeCont&&u.length>0){const D=u[u.length-1];D.right=v,D.items.push(...R.items.filter(H=>!Tt(H)))}else u.push({left:p,right:Math.max(v,p+1),def:x,items:R.items});p=v,g=v}),u}),d=0;for(const h of c)
|
|
150
|
+
for(const u of h)o.add(Math.max(d,u.left)),o.add(u.right);const l=wt(xt([...o].sort((h,u)=>h-u),30),rt(c.length)),f=h=>{let u=0,p=l.length-1;for(;u<p;){const g=u+p>>1;l[g]<h?u=g+1:p=g}return u>0&&Math.
|
|
151
151
|
abs(l[u-1]-h)<=Math.abs(l[u]-h)?u-1:u},m=[],M=new Map;c.forEach(h=>{const u=[];for(const p of h){const g=f(p.left),P=Math.max(g+1,f(p.right));if(p.def?.vmergeCont){const v=M.get(g);if(v){v.rowSpan=(v.
|
|
152
|
-
rowSpan??1)+1;continue}}const R=this.buildBlocks(p.items.map(v=>
|
|
152
|
+
rowSpan??1)+1;continue}}const R=this.buildBlocks(p.items.map(v=>Mt(v)),e);St(R);const S={type:"table-cell",id:w(),children:R.length>0?R:[I()]};P-g>1&&(S.colSpan=P-g);const x=p.def?.background?this.colors[p.
|
|
153
153
|
def.background]:void 0;x&&x!=="#ffffff"&&(S.backgroundColor=x),p.def?.valign&&p.def.valign!=="top"&&(S.verticalAlign=p.def.valign),p.def?.vmergeFirst?M.set(g,S):M.delete(g),u.push(S)}m.push({type:"tab\
|
|
154
|
-
le-row",id:w(),children:u})});const
|
|
155
|
-
void 0?k(t.margins[s]):void 0;return
|
|
156
|
-
"b"),marginLeftPx:e("l")})}}function
|
|
157
|
-
e=new Uint8Array(t.length>>1);for(let s=0;s<e.length;s++)e[s]=parseInt(t.slice(s*2,s*2+2),16);return e}function
|
|
158
|
-
function
|
|
159
|
-
function
|
|
160
|
-
a.children.every(t=>t.text.trim()===""&&!t.marks?.footnoteRef)}function
|
|
161
|
-
1]);)a.pop()}function
|
|
154
|
+
le-row",id:w(),children:u})});const A=[];for(let h=1;h<l.length;h++)A.push(l[h]-l[h-1]);const b=nt(m,{columnWidths:A,hasHeader:s[0]?.header});return b?[b]:null}pageLayout(){const t=this.page,e=s=>t.margins[s]!==
|
|
155
|
+
void 0?k(t.margins[s]):void 0;return it({widthPx:t.widthTwips?k(t.widthTwips):void 0,heightPx:t.heightTwips?k(t.heightTwips):void 0,landscape:t.landscape,marginTopPx:e("t"),marginRightPx:e("r"),marginBottomPx:e(
|
|
156
|
+
"b"),marginLeftPx:e("l")})}}function O(a){const t=a.replace(/[\t\s]+/g,"");return/^(\d+|[a-zA-Z]|[ivxlcdm]+|[IVXLCDM]+)[.)]?$/.test(t)&&t.length>0}function yt(a){const t=a.replace(/[^0-9a-fA-F]/g,""),
|
|
157
|
+
e=new Uint8Array(t.length>>1);for(let s=0;s<e.length;s++)e[s]=parseInt(t.slice(s*2,s*2+2),16);return e}function xt(a,t){const e=[];for(const s of a)(e.length===0||s-e[e.length-1]>t)&&e.push(s);return e}
|
|
158
|
+
function wt(a,t){if(a.length-1<=t)return a;const e=a.length-1,s=[];for(let r=0;r<=t;r++)s.push(a[Math.round(r*e/t)]);return s}function Tt(a){return a.kind==="para"&&a.runs.every(t=>t.text.trim()==="")}
|
|
159
|
+
function Mt(a){return a.kind==="para"?{...a,forcedInTable:!1,para:{...a.para,inTable:!1}}:a.kind==="image"||a.kind==="pagebreak"?{...a,inTable:!1}:a}function B(a){return a.type==="paragraph"&&!a.borders&&
|
|
160
|
+
a.children.every(t=>t.text.trim()===""&&!t.marks?.footnoteRef)}function V(a){for(;a.length>0&&B(a[0]);)a.shift();for(;a.length>0&&B(a[a.length-1]);)a.pop()}function St(a){for(;a.length>1&&B(a[a.length-
|
|
161
|
+
1]);)a.pop()}function q(a){const t=a>>>0;if(t===0)return;const e=t&63,s=t>>>6&31,r=t>>>11&31,n=t>>>16&15,i=(t>>>20&511)+1900;if(!(n<1||n>12||r<1))return Date.UTC(i,n-1,r,s,e)}function Rt(a){if(a.startsWith(
|
|
162
162
|
"."))return"";if(/\s/.test(a))return a;let t=a.replace(/-(Regular|Roman|Book|Bold|Italic|Oblique|BoldItalic|BoldOblique|Light|LightItalic|Medium|MediumItalic|Semibold|SemiBold|SemiboldItalic|Heavy|Black|Condensed|Thin|UltraLight)$/,
|
|
163
|
-
"");return t=t.replace(/(PSMT|PS|MT)$/,""),t=t.replace(/([a-z])([A-Z])/g,"$1 $2"),t}const
|
|
164
|
-
e.length;n+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+r)));return
|
|
163
|
+
"");return t=t.replace(/(PSMT|PS|MT)$/,""),t=t.replace(/([a-z])([A-Z])/g,"$1 $2"),t}const N=class{static async parseFile(t){const e=new Uint8Array(await t.arrayBuffer());let s="";const r=32768;for(let n=0;n<
|
|
164
|
+
e.length;n+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+r)));return F(s,{binary:!0})}static fromRtf(t){return F(t)}static toRtf(t){t=at(t),this.exportListNumbering=ot(t);const e=[];for(const s of t.
|
|
165
165
|
children){const r=this.blockToRtf(s,t);r!==null&&e.push(r)}return this.exportListNumbering=null,`{\\rtf1\\ansi\\ansicpg1252\\deff0\\uc1{\\fonttbl{\\f0\\froman Times New Roman;}{\\f1\\fmodern Courier New;}}
|
|
166
166
|
\\f0\\fs24
|
|
167
167
|
`+e.join(`
|
|
168
168
|
`)+`
|
|
169
|
-
}`}static blockToRtf(t,e){switch(t.type){case"paragraph":return
|
|
170
|
-
t);case"code":return"\\pard{\\f1\\fs20 "+y(t.content).replace(/\n/g,"\\line ")+"}\\par";case"math":return"\\pard "+y(t.content)+"\\par";case"toc":{const s=
|
|
169
|
+
}`}static blockToRtf(t,e){switch(t.type){case"paragraph":return G(t)?"\\pard\\brdrb\\brdrs\\brdrw15 \\par":this.paragraphToRtf(t);case"list":return this.listToRtf(t);case"table":return this.tableToRtf(
|
|
170
|
+
t);case"code":return"\\pard{\\f1\\fs20 "+y(t.content).replace(/\n/g,"\\line ")+"}\\par";case"math":return"\\pard "+y(t.content)+"\\par";case"toc":{const s=K(e,U(t));return s.length===0?null:s.map(r=>`\
|
|
171
171
|
\\pard${t.direction==="rtl"?"\\rtlpar":"\\ltrpar"}${t.align==="justify"?"\\qj":t.align==="center"?"\\qc":(t.align??(t.direction==="rtl"?"right":"left"))==="right"?"\\qr":"\\ql"}\\${t.direction==="rtl"?
|
|
172
172
|
"ri":"li"}${(r.level-1)*360} `+y(r.text)+"\\par").join(`
|
|
173
173
|
`)}case"image":return"\\pard{\\i [Image"+(t.alt?`: ${y(t.alt)}`:"")+"]}\\par";case"page-break":return"\\page";case"container":return t.children.map(s=>this.blockToRtf(s,e)).filter(s=>s!==null).join(`
|
|
174
174
|
`);default:return null}}static paragraphToRtf(t){let e="\\pard";t.align==="center"?e+="\\qc":t.align==="right"?e+="\\qr":t.align==="justify"&&(e+="\\qj");let s=this.inlineNodesToRtf(t.children);return t.
|
|
175
|
-
heading&&(s=`{\\b\\fs${this.HEADING_HALF_POINTS[t.heading-1]} ${s}}`),`${e} ${s}\\par`}static listToRtf(t){const e=this.exportListNumbering?.get(t.id);let s=e?
|
|
175
|
+
heading&&(s=`{\\b\\fs${this.HEADING_HALF_POINTS[t.heading-1]} ${s}}`),`${e} ${s}\\par`}static listToRtf(t){const e=this.exportListNumbering?.get(t.id);let s=e?lt(e):t.startNumber??1;const r=[];for(const n of t.
|
|
176
176
|
children){if(n.type!=="list-item")continue;const i=((n.indentLevel??0)+1)*360;let o;t.variant==="ordered"?(o=`${s}. `,s++):t.variant==="todo"?o=n.checked?"[x] ":"[ ] ":o="\\bullet ",r.push(`\\pard\\li${i}\
|
|
177
177
|
${o}`+this.inlineNodesToRtf(n.children)+"\\par")}return r.join(`
|
|
178
|
-
`)}static tableToRtf(t){if(!t.children||t.children.length===0)return"";const e=
|
|
178
|
+
`)}static tableToRtf(t){if(!t.children||t.children.length===0)return"";const e=ct(t),s=9360,r=[];for(let n=0;n<e.rows;n++){const i=["\\trowd\\trgaph108"];for(let o=0;o<e.cols;o++)i.push(`\\cellx${Math.
|
|
179
179
|
round(s*(o+1)/e.cols)}`);for(let o=0;o<e.cols;o++){const c=e.occupancy[n][o];let d="";c&&c.row===n&&c.col===o&&(d=c.cell.children.map(l=>l.type==="paragraph"?this.inlineNodesToRtf(l.children):l.type===
|
|
180
180
|
"code"?y(l.content):"").filter(l=>l.length>0).join("\\line ")),i.push(`\\pard\\intbl ${d}\\cell`)}i.push("\\row"),r.push(i.join(""))}return r.join(`
|
|
181
181
|
`)+`
|
|
182
182
|
\\pard`}static inlineNodesToRtf(t){return t.map(e=>this.textNodeToRtf(e)).join("")}static textNodeToRtf(t){if(t.marks?.footnoteRef)return`{\\super ${y(t.text)}}`;const e=y(t.text).replace(/\n/g,"\\line\
|
|
183
183
|
");if(!t.marks)return e;const s=[];t.marks.bold&&s.push("\\b"),t.marks.italic&&s.push("\\i"),t.marks.underline&&s.push("\\ul"),t.marks.strikethrough&&s.push("\\strike"),t.marks.superscript&&s.push("\\\
|
|
184
184
|
super"),t.marks.subscript&&s.push("\\sub"),t.marks.code&&s.push("\\f1");const r=s.length>0?`{${s.join("")} ${e}}`:e;return t.marks.link?`{\\field{\\*\\fldinst HYPERLINK "${y(t.marks.link)}"}{\\fldrslt ${r}\
|
|
185
|
-
}}`:r}};
|
|
186
|
-
const r=a.charCodeAt(e);if(r<128){t+=s;continue}t+=`\\u${r>32767?r-65536:r}?`}return t}export{
|
|
185
|
+
}}`:r}};N.exportListNumbering=null,N.HEADING_HALF_POINTS=[32,28,26,24,22,22];let At=N;function y(a){let t="";for(let e=0;e<a.length;e++){const s=a[e];if(s==="\\"||s==="{"||s==="}"){t+="\\"+s;continue}
|
|
186
|
+
const r=a.charCodeAt(e);if(r<128){t+=s;continue}t+=`\\u${r>32767?r-65536:r}?`}return t}export{At as RtfConverter,y as escapeRtfText};
|