@betteroffice/pptx 0.1.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,18 +1,19 @@
1
1
  # @betteroffice/pptx
2
2
 
3
- Framework-free core for the BetterOffice PPTX editor — the Rust parser, yrs deck
4
- model, slide layout, and display-list engine compiled to WebAssembly, plus the
5
- Canvas2D replay host.
3
+ Framework-free PPTX parsing, editing, rendering, and saving through a Rust/WebAssembly engine.
4
+ Use it to build a presentation viewer or editor with your own interface.
5
+
6
+ ## Install
6
7
 
7
8
  ```bash
8
9
  bun add @betteroffice/pptx
9
10
  ```
10
11
 
11
- Most apps want the turnkey React component in
12
- [`@betteroffice/pptx-react`](https://www.npmjs.com/package/@betteroffice/pptx-react).
13
- Use this package directly to build custom presentation chrome.
12
+ No peer dependencies.
13
+
14
+ ## Usage
14
15
 
15
- ## Open and render a slide
16
+ Render the first slide of a presentation onto a browser canvas:
16
17
 
17
18
  ```ts
18
19
  import {
@@ -22,144 +23,129 @@ import {
22
23
  sizeCanvasForSlide,
23
24
  } from '@betteroffice/pptx';
24
25
 
25
- await initWasm();
26
- const bytes = new Uint8Array(await file.arrayBuffer());
27
- const deck = openPresentation(bytes, {
28
- fonts: [{ family: 'My Sans', bytes: fontBytes }],
29
- });
30
-
31
- const frame = deck.layoutSlide(0);
32
- sizeCanvasForSlide(canvas, frame, devicePixelRatio);
33
- await paintSlide(canvas.getContext('2d')!, frame, devicePixelRatio);
26
+ export async function renderFirstSlide(
27
+ bytes: Uint8Array,
28
+ fontBytes: Uint8Array,
29
+ canvas: HTMLCanvasElement,
30
+ ) {
31
+ await initWasm();
32
+ const deck = openPresentation(bytes, {
33
+ fonts: [{ family: 'My Sans', bytes: fontBytes }],
34
+ });
35
+ try {
36
+ const frame = deck.layoutSlide(0);
37
+ const dpr = window.devicePixelRatio;
38
+ sizeCanvasForSlide(canvas, frame, dpr);
39
+ const context = canvas.getContext('2d');
40
+ if (!context) throw new Error('Canvas 2D is unavailable');
41
+ await paintSlide(context, frame, dpr);
42
+ } finally {
43
+ deck.dispose();
44
+ }
45
+ }
34
46
  ```
35
47
 
36
- `initWasm()` with no argument only works where `fetch` of a same-origin URL works (browsers); Node and SSR must pass the wasm bytes.
48
+ `fontBytes` holds a TTF or OTF file, for example fetched from your server or loaded with
49
+ `loadBundledFontBytes` from [`@betteroffice/fonts`](https://www.npmjs.com/package/@betteroffice/fonts). Slides containing images also need an image resolver, described
50
+ below. The React editor in [`@betteroffice/pptx-react`](https://www.npmjs.com/package/@betteroffice/pptx-react)
51
+ manages rendering and user input.
52
+
53
+ ## Entry points
54
+
55
+ All entry points below are exported from `@betteroffice/pptx`.
56
+
57
+ | entry point | description |
58
+ | --- | --- |
59
+ | `initWasm(input?)` | Initialize WebAssembly before opening or inspecting a file. Browsers can omit the input; Node hosts can pass WASM bytes. |
60
+ | `openPresentation(bytes, options?)` | Open a synchronous `PresentationHandle` for reads, edits, layout, and saving. |
61
+ | `inspectPresentation(bytes, options?)` | Inspect parsed content without opening an editing handle; `includeMedia: false` omits media. |
62
+ | `sizeCanvasForSlide(canvas, frame, dpr, scale?)` | Set canvas backing dimensions and CSS size for a slide. |
63
+ | `paintSlide(context, frame, dpr?, scale?, options?)` | Paint a display list asynchronously onto a canvas. |
64
+ | `slideToPng(frame, options?)` | Return a PNG `Blob` asynchronously using a browser canvas backend. |
65
+ | `exportPptxStructured(bytes, options?)` | Export structured content asynchronously without fonts or a DOM. |
66
+ | `exportPptxMarkdown(bytes, options?)` | Export Markdown and source anchors asynchronously. |
67
+ | `renderPptxMarkdown(content, options?)` | Render structured content as Markdown asynchronously. |
68
+
69
+ `openPresentationSession(bytes, options?)` from `@betteroffice/pptx/worker` opens an experimental asynchronous
70
+ worker session.
71
+
72
+ `openPresentation` accepts `fonts`, `fallbackFonts`, `clientId`, and `initialUpdate`. Fallback fonts
73
+ supply glyphs missing from a run's own face. When opening from a collaboration update, retain the
74
+ source file bytes used to seed it so the handle can save.
75
+
76
+ The core's directly owned handle is synchronous. The React editor runs its engine in a Web Worker
77
+ by default and exposes promise-returning reads and exports.
78
+
79
+ ## Layout and rendering
80
+
81
+ `layoutSlide(index)` uses a zero-based slide index. `snapshot()` returns the deck model, and
82
+ `layouts()` lists layout IDs and names for `insertSlide`. `duplicateSlide` copies slide content and
83
+ speaker notes, excluding comments. Shape coordinates use EMU (English Metric Units, 914,400 per inch); text offsets use
84
+ UTF-16 code units.
37
85
 
38
- All parsing, edits, collaboration state, text shaping, layout, hit-testing, and
39
- display-list emission stay in Rust. The package decodes the typed boundary and
40
- replays the resulting primitives on canvas. Font bytes are supplied by the host
41
- and registered with the Rust shaper through `openPresentation`.
86
+ For embedded images, pass `paintSlide` an options object with `resolveImage`, a function mapping an
87
+ asset ID to a canvas image source or a promise for one. It may return `null` for an unavailable image.
88
+ `slideToPng` accepts the same resolver and an optional `scale`.
42
89
 
43
- Beyond rendering, `PresentationHandle` covers editing: text
44
- (`insertText` / `deleteText` / `formatText` / `setParagraphAlignment`), slides
45
- (`insertSlide` / `deleteSlide` / `moveSlide`), shapes
46
- (`addTextBox` / `moveShape` / `resizeShape` / `setShapeRect`), comments
47
- (`addComment` / `replyToComment` / `setCommentStatus` / `removeComment`),
48
- `hitTest`, undo/redo, and `save()`, which serializes the deck back to `.pptx`
49
- bytes with edits applied — untouched slides keep their exact source part bytes.
90
+ ## Saving and ownership
91
+
92
+ `save()` returns PPTX bytes with edits applied; untouched slides retain their source part bytes.
93
+ Call `dispose()` when finished with a handle. `fork()` creates an independently owned copy that must
94
+ also be disposed.
50
95
 
51
96
  ## Agent proposals
52
97
 
53
- Stage a group of edits, inspect it, then accept or reject it:
98
+ `propose(agentId, note, edits)` stages edits without changing the committed deck. Use `listProposals`,
99
+ `previewProposal`, and `layoutProposalSlide` to inspect them, then `acceptProposal` or `rejectProposal`.
100
+ Acceptance applies the group in one undo step; pending proposals stay in the open session.
54
101
 
55
- ```ts
56
- const slide = deck.snapshot().slides[0];
57
- const shape = slide.shapes.find((shape) => shape.textStories.length > 0)!;
58
- const story = shape.textStories[0];
59
- const proposal = deck.propose('editor-agent', 'Make the title concise', [{
60
- type: 'replaceText',
61
- storyId: story.id,
62
- start: 0,
63
- end: story.paragraphs[0].runs.reduce((length, run) => length + run.text.length, 0),
64
- text: 'A clear title',
65
- }]);
66
-
67
- const preview = deck.previewProposal(proposal.id);
68
- const proposedSlide = deck.layoutProposalSlide(proposal.id, 0);
69
- const diff = deck.layoutProposalDiffSlide(proposal.id, 0);
70
- await paintSlide(canvas.getContext('2d')!, diff.frame, devicePixelRatio, 1, {
71
- textChanges: diff.textChanges,
72
- });
73
- deck.acceptProposal(proposal.id);
74
- deck.undo();
75
- ```
102
+ `layoutProposalDiffSlide` returns a review frame and `textChanges`; pass both to `paintSlide` to show
103
+ insertions and deletions. Review frames contain temporary text offsets and are for display only.
104
+ If a target changed, acceptance throws `StaleProposalError`; inspect a fresh preview before choosing
105
+ `acceptProposal(id, { force: true })`.
76
106
 
77
- `listProposals()` returns agent attribution, notes, edits, before/after targets,
78
- and current `staleTargets`. `previewProposal()` and `layoutProposalSlide()` replay
79
- against the current deck without changing it. `rejectProposal(id)` removes a
80
- pending group. Acceptance applies the whole group in one undo step and emits
81
- one local update; an invalid edit prevents the entire group from being staged
82
- or accepted.
83
-
84
- `layoutProposalDiffSlide()` lays removed and inserted text out together, keeping
85
- unchanged words as context and retaining fonts and emphasis. Pass its
86
- `textChanges` to `paintSlide()` for red highlights and strikethrough on deletions,
87
- and green highlights and underlines on insertions. Its snapshot and UTF-16
88
- ranges describe a temporary review layout; use the live handle for editing and
89
- the ordinary proposed layout for the result after acceptance. Review rendering
90
- does not replace the live hit-test state or add markup to saved presentations.
91
-
92
- Supported edits replace text within one paragraph, format text, align paragraphs,
93
- set shape geometry/fill/stroke/adjustments, and replace speaker notes. Text offsets
94
- use UTF-16 and shape coordinates use EMU. Text replacement inherits the style at
95
- its start unless `style` is supplied. Edits run in order, so later text offsets
96
- refer to the result of earlier edits in the group.
97
-
98
- Changing a targeted shape or its notes makes acceptance throw `StaleProposalError`
99
- with target IDs. Review a fresh preview before calling
100
- `acceptProposal(id, { force: true })`; force still validates targets and ranges.
101
- Unrelated peer edits survive acceptance and Undo. Up to 64 proposals, each with
102
- 1–256 edits, may be pending.
103
-
104
- Pending proposals belong to this open session: they are excluded from PPTX
105
- exports and collaboration updates. Accepted edits save and sync normally.
106
- `isProposalsAvailable()` supports hosts that load an older WASM build.
107
-
108
- ## Comments
109
-
110
- PowerPoint has two comment systems and a file only ever uses one: `legacy`
111
- reads in every version of PowerPoint plus LibreOffice and Google Slides, while
112
- `modern` carries replies and a resolved state but only shows in PowerPoint 365.
113
- A deck commits to one at its first comment, so `setCommentFlavor` only works
114
- while `comments()` is empty, and `replyToComment` / `setCommentStatus` throw on
115
- a legacy deck.
116
-
117
- Saving patches existing comment XML, preserving identities, formatting, task
118
- metadata, anchors and unknown fields. Unedited parts remain byte-identical.
119
- Removing a thread removes its known replies; a concurrent reply survives as a
120
- new root if its parent was deleted.
107
+ ## Version-checked edit batches
121
108
 
122
- ```ts
123
- deck.addComment(deck.snapshot().slides[0].id, {
124
- author: 'Ada Lovelace',
125
- initials: 'AL',
126
- text: 'Tighten this claim.',
127
- created: new Date().toISOString(),
128
- xEmu: 1_828_800,
129
- yEmu: 914_400,
130
- });
131
- ```
109
+ `readContent`, `findText`, `validateEdits`, and `applyEdits` support edits against a session version.
110
+ See [Edit PPTX in version-checked batches](https://docs.betteroffice.dev/docs/javascript#edit-pptx-in-version-checked-batches)
111
+ for request shapes, atomicity, refusals, and limits.
112
+
113
+ ## Structured export
132
114
 
133
- Positions are EMU, like every other coordinate. `created` is supplied by the
134
- caller rather than read from a clock, so peers replaying the same edits
135
- converge.
115
+ `exportStructured` and `exportMarkdown` read committed state; headless exports accept file bytes.
116
+ See [PPTX structured export](https://docs.betteroffice.dev/docs/javascript#pptx-structured-export)
117
+ for options, anchors, diagnostics, and truncation.
118
+
119
+ ## Comments and history
120
+
121
+ `comments()` lists comments. `setCommentFlavor` selects `legacy` or `modern` only while that list is
122
+ empty. `replyToComment` supports both flavors; `setCommentStatus` requires modern comments. `addComment` takes the author's
123
+ name, text, and caller-supplied `created` timestamp. `setCommentPosition` moves a root comment using
124
+ safe integer EMU coordinates; replies share their root's position.
125
+
126
+ `setUndoCaptureMode('manual')` groups tracked local edits until `addUndoBoundary()`;
127
+ `undoCaptureMode()` reads the current mode. `undo()` and `redo()` navigate history.
128
+ `anchorCaret(storyId, index)` creates an anchor that follows edits; `resolveCaretAnchor` returns its
129
+ current offset, or `null` if its story no longer exists.
136
130
 
137
131
  ## Collaboration
138
132
 
139
- `PresentationHandle` is a collaboration replica. Pair it with
140
- `CollaborationProvider` and a transport implementing the small
141
- `CollaborationTransport` interface. The provider speaks the standard Yjs sync-v1
142
- wire protocol, performs state-vector handshakes, forwards only local updates,
143
- and bounds frames and pending backpressure bytes.
133
+ `PresentationHandle` implements the replica interface used by `CollaborationProvider`
134
+ from `@betteroffice/pptx/collaboration`.
135
+ See the [collaboration guide](https://docs.betteroffice.dev/docs/collaboration) for transports,
136
+ shared seeds, presence, and connection lifecycle.
144
137
 
145
- ```ts
146
- import { CollaborationProvider } from '@betteroffice/pptx';
147
-
148
- const provider = new CollaborationProvider(deck, transport, {
149
- user: { name: "Ada" }, // identity for this peer's presence chip
150
- });
151
- deck.onUpdate((_update, origin) => {
152
- if (origin === 'remote') repaint();
153
- });
154
- provider.connect();
155
- ```
138
+ ## Operation profiles
156
139
 
157
- ## Development
140
+ `layoutSlideProfiled`, `insertTextProfiled`, and `undoProfiled` expose engine stage timings.
141
+ See [Operation profiles](https://docs.betteroffice.dev/docs/javascript#operation-profiles) for result
142
+ shapes and measurement guidance.
158
143
 
159
- The generated `.wasm` binary is intentionally not committed. From the repository
160
- root, install `wasm-pack` 0.15.0 and `binaryen`, then run
161
- `bun scripts/build-pptx-wasm.ts`.
162
- Package builds copy the binary into `dist/generated`.
144
+ ## Documentation
163
145
 
164
- [JavaScript guide](https://docs.betteroffice.dev/docs/javascript) ·
165
- [Changelog](https://github.com/openooxml/betteroffice/blob/main/packages/pptx/CHANGELOG.md) · Apache-2.0.
146
+ - [JavaScript guide](https://docs.betteroffice.dev/docs/javascript)
147
+ - [Collaboration guide](https://docs.betteroffice.dev/docs/collaboration)
148
+ - [Package guide](https://docs.betteroffice.dev/docs/packages)
149
+ - [React editor: @betteroffice/pptx-react](https://www.npmjs.com/package/@betteroffice/pptx-react)
150
+ - [Fonts: @betteroffice/fonts](https://www.npmjs.com/package/@betteroffice/fonts)
151
+ - [Repository](https://github.com/openooxml/betteroffice)
@@ -0,0 +1,3 @@
1
+ import {J as J$1}from'./chunk-4FWJR3UX.js';import {a}from'./chunk-H3SEEI4U.js';var W={bold:false,italic:false,underline:"none",fontSizePt:24,color:"#111827",fontFamily:"Arial"};function D(e,n,r,o){let i=Z(e,n,r,o),a=S(i,"underline");return {bold:S(i,"bold"),italic:S(i,"italic"),underline:a===void 0?void 0:a!=="none",fontSize:S(i,"fontSizePt"),textColor:S(i,"color"),fontFamily:S(i,"fontFamily")}}function de(e,n){return D(e,0,e.length,n)}function J(e,n,r,o){let i=D(e,n,r,o);return {bold:i.bold??o.bold,italic:i.italic??o.italic,underline:i.underline===void 0?o.underline:i.underline?"sng":"none",fontSizePt:i.fontSize??o.fontSizePt,color:i.textColor??o.color,fontFamily:i.fontFamily??o.fontFamily}}function Y(e,n,r,o){return {...J(e,n,r,W),...o}}function me(e,n,r,o){if(n!==r)return null;let i={...Y(e,n,r,o),caps:null},a=s=>[...new Set([...Object.keys(s),...Object.keys(i)])].every(m=>(s[m]??null)===(i[m]??null)),t=0;for(let s of e.paragraphs){let d;for(let m of s.runs){let l=t;if(t+=m.text.length,t!==l){if(n>=l&&n<t)return !a(m.style)||n===l&&d&&!a(d.style)?null:{neighbour:"after",start:l,end:t,paragraphId:s.id};d={style:m.style,start:l,end:t};}}if(n===t&&d&&a(d.style))return {neighbour:"before",start:d.start,end:d.end,paragraphId:s.id};t+=1;}return null}function Z(e,n,r,o){let i=$(e,o);if(i.length===0)return [o];let a=Math.min(n,r),t=Math.max(n,r);if(a===t){let m=i.find(p=>a>=p.start&&a<p.end);return m?[m.style]:[[...i].reverse().find(p=>p.end<=a)?.style??i[0].style]}let s=i.filter(m=>m.end>a&&m.start<t).map(m=>m.style);return s.length>0?s:[[...i].reverse().find(m=>m.end<=a)?.style??i[0].style]}function $(e,n){let r=[],o=0;return e.paragraphs.forEach((i,a)=>{for(let t of i.runs){let s=o;o+=t.text.length,o>s&&r.push({start:s,end:o,style:ee(t.style,n)});}a<e.paragraphs.length-1&&(o+=1);}),r}function ee(e,n){return {bold:e.bold??n.bold,italic:e.italic??n.italic,underline:e.underline??n.underline,fontSizePt:e.fontSizePt??n.fontSizePt,color:e.color??n.color,fontFamily:e.fontFamily??n.fontFamily}}function S(e,n){let r=e[0]?.[n];return e.every(o=>o[n]===r)?r:void 0}var le=["insertTableRow","deleteTableRow","insertTableColumn","deleteTableColumn","setShapeFill","setShapeStroke","setShapeAdjust","removeShape","bringShapeToFront","sendShapeToBack","bringShapeForward","sendShapeBackward","insertSlide","deleteSlide","moveSlide","setSlideNotes","addComment","replyToComment","setCommentStatus","setCommentPosition","removeComment","setCommentFlavor","propose","acceptProposal","rejectProposal"],ue=Object.freeze({setChangeObserver:"mode",invoke:"local-write",applyRemoteUpdate:"remote-update",collabPipe:"remote-update",applyEdits:"local-write",registerFont:"local-write",insertTextBox:"local-write",insertShape:"local-write",insertPicture:"local-write",moveShape:"local-write",setShapeRect:"local-write",undo:"local-write",redo:"local-write",insertText:"local-write",replaceText:"local-write",formatText:"local-write",setParagraphAlignment:"local-write",deleteBackward:"local-write",deleteForward:"local-write",paragraphBreak:"local-write",compositionStart:"local-write",compositionCommit:"local-write",activateSlide:"view",selectObject:"view",moveSelection:"view",selectAtPoint:"view",setSelection:"view",compositionEnd:"view",setReadOnly:"mode"}),N=class extends Error{constructor(r,o){super(o);a(this,"seq",r);a(this,"refusal");this.name="CommandOutcomeUnknown",this.refusal={seq:r,reason:"unknown-outcome"};}},ce={openCommandEditor:true,command:true,thumbnailFrame:true,flushCommandEditor:true,saveCommandEditor:true,readEditor:true,prepareCommandPicture:true,accessCommandEditor:true,checkpointCommandEditor:true};function g(e,n){return (e[n]?.columnOffset??0)-(e[0]?.columnOffset??0)}var I,G;function Pe(e,n,r){return r==="word"?ne(e,n):te(e,n)}function ne(e,n){let r=M(e,n);I??(I=new Intl.Segmenter(void 0,{granularity:"word"}));let o=[...I.segment(e)],i=o.find(a=>r>=a.index&&r<a.index+a.segment.length)??o[o.length-1];return i?{start:i.index,end:i.index+i.segment.length}:{start:r,end:r}}function te(e,n){let r=M(e,n),o=e.lastIndexOf(`
2
+ `,Math.max(0,r-1))+1,i=e.indexOf(`
3
+ `,r);return {start:o,end:i===-1?e.length:i}}function Se(e,n){return n.start<e.start?{anchor:e.end,focus:n.start}:n.end>e.end?{anchor:e.start,focus:n.end}:{anchor:e.start,focus:e.end}}function M(e,n){return Number.isFinite(n)?Math.max(0,Math.min(e.length,Math.trunc(n))):0}function oe(e,n){let o=e[A(e,n)]?.caretStops.find(i=>i.position===n.position)?.x;return o===void 0?void 0:o-g(e,A(e,n))}function H(e,n,r,o){if(e.length===0)return {position:n.position,lineIndex:0};let i=A(e,n),a=i+(r==="up"?-1:1),t=e[a];if(!t)return {position:n.position,lineIndex:i};let s=o??oe(e,n),d=s===void 0?void 0:s+g(e,a);return d===void 0?{position:t.start,lineIndex:a}:{position:t.caretStops.reduce((l,p)=>l===null||Math.abs(p.x-d)<Math.abs(l.x-d)?p:l,null)?.position??t.start,lineIndex:a}}function z(e,n,r){let o=M(e,n);I??(I=new Intl.Segmenter(void 0,{granularity:"word"}));let i=[...I.segment(e)].filter(t=>t.isWordLike).flatMap(t=>[t.index,t.index+t.segment.length]),a=r<0?i.filter(t=>t<o):i.filter(t=>t>o);return a.length===0?r<0?0:e.length:r<0?Math.max(...a):Math.min(...a)}function A(e,n){let r=n.lineIndex;if(r!==void 0&&r>=0&&r<e.length&&n.position>=e[r].start&&n.position<=e[r].end)return r;let o=-1;for(let i=0;i<e.length;i+=1){let a=e[i];n.position>=a.start&&n.position<=a.end&&(o=i);}return o===-1?Math.max(0,e.length-1):o}function K(e){return G??(G=new Intl.Segmenter(void 0,{granularity:"grapheme"})),new Set([...[...G.segment(e)].map(n=>n.index),e.length])}var j=new WeakMap;function ge(e){let n=j.get(e);return n||(n=JSON.parse(new TextDecoder().decode(e.displayList)),j.set(e,n)),n}function E(e,n){return JSON.stringify([e,n])}function V(e){return e.paragraphs.reduce((n,r)=>n+r.runs.reduce((o,i)=>o+i.text.length,0),Math.max(0,e.paragraphs.length-1))}function Ee(e){let n={hits:[],lines:new Map};function r(o,i,a){for(let t of o){let s=[...i,t];if(t.shapeId&&n.hits.push({primitive:t,transforms:s,clips:a,...t.kind==="textBox"?{textLength:V(t)}:{}}),t.kind==="textBox"&&t.shapeId&&t.storyId){let d=E(t.shapeId,t.storyId),m=n.lines.get(d)??[];for(let l of t.lines)m.push({box:t,line:l,transforms:s});n.lines.set(d,m);}else (t.kind==="chart"||t.kind==="table")&&r(t.primitives,s,[...a,t]);}}return r(e.primitives,[],[]),n}function ke(e){let n={hits:[],lines:new Map,size:{width:e.width,height:e.height}};function r(o,i,a){for(let t of o){let s={kind:t.kind,shapeId:t.shapeId,x:t.x,y:t.y,w:t.w,h:t.h,...t.transform?{transform:{...t.transform}}:{}},d=[...i,s];if(t.shapeId&&n.hits.push({primitive:s,transforms:d,clips:a,...t.kind==="textBox"?{textLength:V(t)}:{}}),t.kind==="textBox"&&t.shapeId&&t.storyId){s.storyId=t.storyId,s.lines=t.lines.map(p=>({columnOffset:p.columnOffset,x:p.x,y:p.y,height:p.height,start:p.start,end:p.end,caretStops:p.caretStops.map(u=>({position:u.position,x:u.x}))}));let m=E(t.shapeId,t.storyId),l=n.lines.get(m)??[];for(let p of s.lines)l.push({line:p});n.lines.set(m,l);}else (t.kind==="chart"||t.kind==="table")&&r(t.primitives,d,[...a,s]);}}return r(e.primitives,[],[]),n}function q(e,n){if(!n||n.kind==="object")return null;let r=e.lines.get(E(n.shapeId,n.storyId))??[];return r.find(({line:o})=>n.focus>=o.start&&(n.focus<o.end||n.focus===o.end&&n.affinity==="upstream"))??r.find(({line:o})=>n.focus>=o.start&&n.focus<=o.end)??r[r.length-1]??null}function _(e,n,r=false){let o=e.x+e.w/2,i=e.y+e.h/2,a=(e.transform?.rotationDeg??0)*Math.PI/180,t=Math.cos(a),s=Math.sin(a),d=n.x-o,m=n.y-i;if(r){let l=d*t+m*s;m=m*t-d*s,d=l;}return e.transform?.flipH&&(d=-d),e.transform?.flipV&&(m=-m),r?{x:o+d,y:i+m}:{x:o+d*t-m*s,y:i+d*s+m*t}}function U(e,n){let r=[{x:n.x,y:n.y},{x:n.x+n.width,y:n.y},{x:n.x,y:n.y+n.height},{x:n.x+n.width,y:n.y+n.height}];for(let a=e.length-1;a>=0;a-=1)for(let t=0;t<r.length;t+=1)r[t]=_(e[a],r[t]);let o=Math.min(...r.map(a=>a.x)),i=Math.min(...r.map(a=>a.y));return {x:o,y:i,width:Math.max(...r.map(a=>a.x))-o,height:Math.max(...r.map(a=>a.y))-i}}function v(e,n){let r=e.caretStops[0];return r?e.caretStops.reduce((o,i)=>Math.abs(i.position-n)<Math.abs(o.position-n)?i:o,r).x:e.x}function Ie(e,n){let r=q(e,n);if(!r||!n)return {caret:null,selectionRects:[]};let o=U(r.transforms,{x:v(r.line,n.focus),y:r.line.y,width:1,height:r.line.height}),i=[],a=Math.min(n.anchor,n.focus),t=Math.max(n.anchor,n.focus);for(let s of e.lines.get(E(n.shapeId,n.storyId))??[]){if(t<=s.line.start||a>=s.line.end)continue;let d=v(s.line,Math.max(a,s.line.start)),m=v(s.line,Math.min(t,s.line.end));i.push(U(s.transforms,{x:Math.min(d,m),y:s.line.y,width:Math.abs(m-d),height:s.line.height}));}return {caret:o,selectionRects:i}}function ve(e,n,r,o){for(let i=e.hits.length-1;i>=0;i-=1){let a=e.hits[i],t=n,s=false;for(let m of a.transforms)if(t=_(m,t,true),a.clips.includes(m)&&!Q(m,t)&&(s=true,!r))break;let d=a.primitive;if(!(r&&(d.shapeId!==r.shapeId||d.storyId!==r.storyId))&&!(!r&&(s||!Q(d,t))||!d.shapeId)){if(!r&&o!==void 0){let m=Math.min(6/o,d.w/3,d.h/3);if(t.x-d.x<=m||d.x+d.w-t.x<=m||t.y-d.y<=m||d.y+d.h-t.y<=m)return {kind:"shape",shapeId:d.shapeId}}if(d.kind==="textBox"&&d.storyId){let m=r||a.clips.some(c=>"kind"in c&&c.kind==="table"),l=d.lines?.some((c,f,C)=>f>0&&(c.columnOffset??0)!==(C[f-1].columnOffset??0)),p=Number.POSITIVE_INFINITY,u=d.lines?.reduce((c,f)=>{if(!m&&(t.y<f.y||t.y>f.y+f.height))return c;let X=(P=>{let T=P.x,R=P.x;for(let L of P.caretStops)T=Math.min(T,L.x),R=Math.max(R,L.x);let B=Math.max(T-t.x,t.x-R,0),F=Math.max(P.y-t.y,t.y-P.y-P.height,0);return l?B*B+F*F:F})(f);return !c||X<p?(p=X,f):c},void 0),y=u?.caretStops[0];if(u&&y){let c=u.caretStops.reduce((f,C)=>Math.abs(C.x-t.x)<Math.abs(f.x-t.x)?C:f,y);return {kind:"text",shapeId:d.shapeId,storyId:d.storyId,position:c.position,affinity:c.position===u.end?"upstream":"downstream"}}}return {kind:"shape",shapeId:d.shapeId}}}return null}function Q(e,n){return n.x>=e.x&&n.x<=e.x+e.w&&n.y>=e.y&&n.y<=e.y+e.h}function re(e,n,r){if(!n||n.kind==="object")return null;let o=s=>"kind"in s&&s.kind==="table",i=e.find(({primitive:s})=>s.kind==="textBox"&&s.shapeId===n.shapeId&&s.storyId===n.storyId)?.clips.filter(o).pop();if(!i)return null;let a=[];for(let{primitive:s,clips:d,textLength:m}of e){let l=s.storyId;s.kind!=="textBox"||!l||s.shapeId!==n.shapeId||d.filter(o).pop()!==i||a.some(p=>p.storyId===l)||a.push({storyId:l,end:m??0});}let t=a[a.findIndex(s=>s.storyId===n.storyId)+(r?-1:1)];return t?{slideId:n.slideId,shapeId:n.shapeId,storyId:t.storyId,anchor:0,focus:t.end,affinity:t.end>0?"upstream":"downstream"}:{...n}}function Te(e,n,r,o,i){if(r==="nextCell"||r==="previousCell")return e.hits?re(e.hits,n,r==="previousCell"):null;let a=q(e,n);if(!a||!n||n.kind==="object")return null;let t=e.lines.get(E(n.shapeId,n.storyId))??[],s=n.focus,d=a,m;if(!o&&n.anchor!==n.focus&&(r==="left"||r==="right"))s=r==="left"?Math.min(n.anchor,n.focus):Math.max(n.anchor,n.focus);else if(r==="wordLeft"||r==="wordRight"){if(i===void 0)return null;s=z(i,s,r==="wordLeft"?-1:1);}else if(r==="storyStart")d=t[0],s=0;else if(r==="storyEnd")d=t[t.length-1],s=i?.length??d.line.end;else if(r==="lineStart"||r==="lineEnd"){let p=a.line.caretStops;if(!p.length)return null;s=r==="lineStart"?p[0].position:p[p.length-1].position;}else if(r==="left"||r==="right"){let u=(i===void 0?t.flatMap(({line:y})=>y.caretStops.map(c=>c.position)):[...K(i)]).filter(y=>r==="left"?y<s:y>s);u.length&&(s=r==="left"?Math.max(...u):Math.min(...u));}else if(r==="up"||r==="down"){let p=t.map(({line:y})=>y);m=n.goalX??v(a.line,s)-g(p,t.indexOf(a));let u=H(p,{position:s,lineIndex:t.indexOf(a)},r,m);d=t[u.lineIndex],s=u.position;}(r==="left"||r==="right"||r==="wordLeft"||r==="wordRight")&&(d=q(e,{...n,focus:s,affinity:r==="left"||r==="wordLeft"?"upstream":"downstream"})??a);let l={...n,anchor:o?n.anchor:s,focus:s,affinity:s===d.line.end?"upstream":"downstream"};return m===void 0?delete l.goalX:l.goalX=m,l}function Fe(){let e=0,n=new Map;function r(o){for(let[i,a]of n)if(a===o)return {version:o,clock:i}}return {get version(){return e},initialize(o){n.set(e,o);},commit(o){n.set(++e,o);},retain(o){let i=new Set(o);for(let[a,t]of n)a!==e&&!i.has(t)&&n.delete(a);},envelope(o,i){let a=n.get(o.basis.version);if(a===void 0)for(a="unretained";r(a);)a+="\0";return {...i,seq:o.seq,basis:{epoch:o.basis.epoch,version:a},...o.afterSeq===void 0?{}:{afterSeq:o.afterSeq},kind:o.kind,payload:o.payload}},ack(o,i){let a=o.frame?{coversThroughSeq:o.frame.coversThroughSeq,revision:o.frame.epoch,payload:o.frame}:void 0;return {session:o.session,incarnation:0,epoch:o.epoch,throughSeq:o.throughSeq,version:e,selection:o.selection,editState:o.editState,outcomes:o.outcomes.map(({committed:t,...s})=>t?s:{...s,committed:false}),...a?{frame:a}:{},pptx:{incarnation:o.incarnation,version:o.version,outcomes:o.outcomes,dirtySlideIds:o.dirtySlideIds,activeSlideId:o.activeSlideId,historyThroughSeq:o.historyThroughSeq,...o.creation?{creation:o.creation}:{},...o.change?{change:o.change}:{},..."mutationResult"in o?{mutationResult:o.mutationResult}:{},...o.updates?{updates:o.updates}:{},...o.editResult?{editResult:o.editResult}:{},...o.fontId!==void 0?{fontId:o.fontId}:{},...o.slides?{slides:o.slides,size:o.size}:{},...i===void 0?{}:{retainedBasis:r(i)}}}},dispose(){n.clear();}}}function we(e){let n=new Map,r=new Set,o=new Map,i=-1;function a(t){if(t.throughSeq<i)return;for(i=t.throughSeq,n.set(t.pptx.version,t.version),r.add(t.pptx.version);r.size>256;)r.delete(r.values().next().value);for(t.frame&&o.set(t.frame.revision,t.pptx.version);o.size>257;)o.delete(o.keys().next().value);let s=new Set([...r,...o.values(),t.pptx.version]);t.pptx.retainedBasis&&(s.add(t.pptx.retainedBasis.version),n.set(t.pptx.retainedBasis.version,t.pptx.retainedBasis.clock));for(let d of n.keys())s.has(d)||n.delete(d);}return a(e),{envelope(t){return {session:t.session,incarnation:e.incarnation,seq:t.seq,basis:{epoch:t.basis.epoch,version:n.get(t.basis.version)??-1},...t.afterSeq===void 0?{}:{afterSeq:t.afterSeq},kind:t.kind,payload:t.payload}},ack(t){return a(t),{session:t.session,incarnation:t.pptx.incarnation,epoch:t.epoch,throughSeq:t.throughSeq,version:t.pptx.version,selection:t.selection,editState:t.editState,outcomes:t.pptx.outcomes,dirtySlideIds:t.pptx.dirtySlideIds,activeSlideId:t.pptx.activeSlideId,historyThroughSeq:t.pptx.historyThroughSeq,...t.pptx.creation?{creation:t.pptx.creation}:{},...t.pptx.change?{change:t.pptx.change}:{},..."mutationResult"in t.pptx?{mutationResult:t.pptx.mutationResult}:{},...t.pptx.updates?{updates:t.pptx.updates}:{},...t.pptx.editResult?{editResult:t.pptx.editResult}:{},...t.pptx.fontId!==void 0?{fontId:t.pptx.fontId}:{},...t.pptx.slides?{slides:t.pptx.slides,size:t.pptx.size}:{},...t.frame?{frame:t.frame.payload}:t.pptx.activeSlideId===null?{frame:null}:{}}}}}var ie="CommandOutcomeUnknown";function Me(e){return x(e)&&typeof e.session=="string"&&h(e.incarnation)&&k(e.seq)&&x(e.basis)&&h(e.basis.epoch)&&b(e.basis.version)&&(e.afterSeq===void 0||k(e.afterSeq))&&(e.expectVersion===void 0||typeof e.expectVersion=="boolean")&&typeof e.kind=="string"&&J$1(e,"payload")&&(e.inputTime===void 0||b(e.inputTime))&&(e.lastInputTime===void 0||b(e.lastInputTime))&&(e.group===void 0||typeof e.group=="string")&&(e.replay===void 0||e.replay===true)}function qe(e){return x(e)&&typeof e.session=="string"&&h(e.incarnation)&&h(e.epoch)&&h(e.throughSeq)&&b(e.version)&&Array.isArray(e.outcomes)&&e.outcomes.every(ae)&&(e.frame===void 0||se(e.frame))&&(e.revisions===void 0||x(e.revisions)&&h(e.revisions.selection)&&h(e.revisions.layout))}function Xe(e){return e instanceof Error&&e.name===ie&&x(e)&&x(e.refusal)&&k(e.refusal.seq)}function x(e){return e!==null&&typeof e=="object"}function b(e){return typeof e=="number"&&Number.isFinite(e)}function h(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function k(e){return h(e)&&e>0}function ae(e){return x(e)&&k(e.seq)&&(e.status==="applied"||e.status==="noop"||e.status==="refused"||e.status==="cancelled"||e.status==="duplicate")&&(e.reason===void 0||typeof e.reason=="string")&&(e.committed===void 0||e.committed===false)&&(e.affectedSeqs===void 0||Array.isArray(e.affectedSeqs)&&e.affectedSeqs.every(k))}function se(e){return x(e)&&h(e.coversThroughSeq)&&b(e.revision)&&(e.baseRevision===void 0||b(e.baseRevision))&&J$1(e,"payload")}export{W as a,D as b,de as c,J as d,me as e,Me as f,qe as g,Xe as h,Fe as i,we as j,le as k,ue as l,N as m,ce as n,Pe as o,Se as p,K as q,ge as r,Ee as s,ke as t,q as u,U as v,Ie as w,ve as x,Te as y};
@@ -0,0 +1 @@
1
+ import {a,r}from'./chunk-H3SEEI4U.js';function me(){return new URL("./generated/pptx_wasm_bg.wasm",import.meta.url)}var Q=class extends Error{constructor(t){super(`Proposal targets changed: ${t.join(", ")}`);a(this,"targets");this.name="StaleProposalError",this.targets=t;}};var ee=class extends Error{constructor(t){super(t.message);a(this,"failure");this.name="PptxExportError",this.failure=t;}};var v=class d{static __wrap(e){let t=Object.create(d.prototype);return t.__wbg_ptr=e,ye.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ye.unregister(this),e}free(){let e=this.__destroy_into_raw();n.__wbg_pptxdocument_free(e,0);}acceptProposalJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_acceptProposalJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}addCommentJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_addCommentJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}addPictureJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_addPictureJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}addShapeJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_addShapeJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}addTextBoxJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_addTextBoxJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}addTextBoxProfiledJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_addTextBoxProfiledJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}addUndoBoundary(){n.pptxdocument_addUndoBoundary(this.__wbg_ptr);}adoptPeerIdentity(){let e=n.pptxdocument_adoptPeerIdentity(this.__wbg_ptr);if(e[1])throw _(e[0])}anchorCaretJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_anchorCaretJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}applyEditsJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_applyEditsJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}applyUpdateJson(e){let t,i;try{let a=J(e,n.__wbindgen_malloc),l=u,s=n.pptxdocument_applyUpdateJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}bringShapeForwardJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_bringShapeForwardJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}bringShapeToFrontJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_bringShapeToFrontJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}canRedo(){return n.pptxdocument_canRedo(this.__wbg_ptr)!==0}canUndo(){return n.pptxdocument_canUndo(this.__wbg_ptr)!==0}checkTableEditJson(e){let t=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),i=u,r=n.pptxdocument_checkTableEditJson(this.__wbg_ptr,t,i);if(r[1])throw _(r[0])}clearUpdateObservation(){n.pptxdocument_clearUpdateObservation(this.__wbg_ptr);}get clientId(){return n.pptxdocument_clientId(this.__wbg_ptr)}commentsJson(){let e,t;try{let o=n.pptxdocument_commentsJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}deleteSlideJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_deleteSlideJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}deleteTableColumnJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_deleteTableColumnJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}deleteTableRowJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_deleteTableRowJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}deleteTextJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_deleteTextJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}deleteTextProfiledJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_deleteTextProfiledJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}documentVersion(){let e,t;try{let i=n.pptxdocument_documentVersion(this.__wbg_ptr);return e=i[0],t=i[1],f(i[0],i[1])}finally{n.__wbindgen_free(e,t,1);}}drainUpdateEvent(){let e=n.pptxdocument_drainUpdateEvent(this.__wbg_ptr);var t=F(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}duplicateSlideJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_duplicateSlideJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}encodeDiff(e){let t=J(e,n.__wbindgen_malloc),i=u,r=n.pptxdocument_encodeDiff(this.__wbg_ptr,t,i);if(r[3])throw _(r[2]);var o=F(r[0],r[1]).slice();return n.__wbindgen_free(r[0],r[1]*1,1),o}encodeStateAsUpdate(){let e=n.pptxdocument_encodeStateAsUpdate(this.__wbg_ptr);var t=F(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}encodeStateVector(){let e=n.pptxdocument_encodeStateVector(this.__wbg_ptr);var t=F(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}exportMarkdownJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_exportMarkdownJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}exportStructuredJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_exportStructuredJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}findTextJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_findTextJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}formatTextJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_formatTextJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}insertParagraphBreakJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_insertParagraphBreakJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}insertSlideJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_insertSlideJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}insertSlideProfiledJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_insertSlideProfiledJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}insertTableColumnJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_insertTableColumnJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}insertTableRowJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_insertTableRowJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}insertTextJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_insertTextJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}insertTextProfiledJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_insertTextProfiledJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}listProposalsJson(){let e,t;try{let o=n.pptxdocument_listProposalsJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}mediaBytes(e){let t=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),i=u,r=n.pptxdocument_mediaBytes(this.__wbg_ptr,t,i);if(r[3])throw _(r[2]);var o=F(r[0],r[1]).slice();return n.__wbindgen_free(r[0],r[1]*1,1),o}moveShapeJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_moveShapeJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}moveShapeProfiledJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_moveShapeProfiledJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}moveSlideJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_moveSlideJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}static openCollaborativeFromUpdate(e,t,i){let r=J(e,n.__wbindgen_malloc),o=u;var a=M(i)?0:J(i,n.__wbindgen_malloc),l=u;let s=n.pptxdocument_openCollaborativeFromUpdate(r,o,t,a,l);if(s[2])throw _(s[1]);return d.__wrap(s[0])}static openCollaborative(e,t){let i=J(e,n.__wbindgen_malloc),r=u,o=n.pptxdocument_openCollaborative(i,r,t);if(o[2])throw _(o[1]);return d.__wrap(o[0])}static openPeerDeckJson(e,t,i){let r=J(e,n.__wbindgen_malloc),o=u,a=m(t,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u;var s=M(i)?0:J(i,n.__wbindgen_malloc),h=u;let w=n.pptxdocument_openPeerDeckJson(r,o,a,l,s,h);if(w[2])throw _(w[1]);return d.__wrap(w[0])}static openReplayBaseline(e,t,i){let r=J(e,n.__wbindgen_malloc),o=u;var a=M(i)?0:J(i,n.__wbindgen_malloc),l=u;let s=n.pptxdocument_openReplayBaseline(r,o,!M(t),M(t)?0:t,a,l);if(s[2])throw _(s[1]);return d.__wrap(s[0])}peerHydrationJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_peerHydrationJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}previewProposalJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_previewProposalJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}proposeJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_proposeJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}readCommandContentJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_readCommandContentJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}readContentJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_readContentJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}redoJson(){let e,t;try{let o=n.pptxdocument_redoJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}redoReceiptJson(){let e,t;try{let o=n.pptxdocument_redoReceiptJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}registerPeerFontsJson(e){let t=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),i=u,r=n.pptxdocument_registerPeerFontsJson(this.__wbg_ptr,t,i);if(r[1])throw _(r[0])}rejectProposalJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_rejectProposalJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}removeCommentJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_removeCommentJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}removeShapeJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_removeShapeJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}replayJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_replayJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}replyToCommentJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_replyToCommentJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}resizeShapeJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_resizeShapeJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}resolveCaretAnchorJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_resolveCaretAnchorJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}saveBytes(){let e=n.pptxdocument_saveBytes(this.__wbg_ptr);if(e[3])throw _(e[2]);var t=F(e[0],e[1]).slice();return n.__wbindgen_free(e[0],e[1]*1,1),t}searchTextJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_searchTextJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}sendShapeBackwardJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_sendShapeBackwardJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}sendShapeToBackJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_sendShapeToBackJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}sessionMetadataJson(){let e,t;try{let o=n.pptxdocument_sessionMetadataJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}setCollaborative(){let e=n.pptxdocument_setCollaborative(this.__wbg_ptr);if(e[1])throw _(e[0])}setCommentFlavorJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setCommentFlavorJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setCommentPositionJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setCommentPositionJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setCommentStatusJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setCommentStatusJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setParagraphAlignmentJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setParagraphAlignmentJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setShapeAdjustJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setShapeAdjustJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setShapeFillJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setShapeFillJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setShapeRectJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setShapeRectJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setShapeStrokeJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setShapeStrokeJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setSlideLayoutJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setSlideLayoutJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setSlideNotesJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setSlideNotesJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setStoryParagraphsJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_setStoryParagraphsJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}setUndoCaptureMode(e){let t=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),i=u,r=n.pptxdocument_setUndoCaptureMode(this.__wbg_ptr,t,i);if(r[1])throw _(r[0])}snapshotJson(){let e,t;try{let o=n.pptxdocument_snapshotJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}startUpdateObservation(){let e=n.pptxdocument_startUpdateObservation(this.__wbg_ptr);if(e[1])throw _(e[0])}storyFormattingJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_storyFormattingJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}storyJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_storyJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}undoCaptureMode(){let e,t;try{let i=n.pptxdocument_undoCaptureMode(this.__wbg_ptr);return e=i[0],t=i[1],f(i[0],i[1])}finally{n.__wbindgen_free(e,t,1);}}undoJson(){let e,t;try{let o=n.pptxdocument_undoJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}undoProfiledJson(){let e,t;try{let o=n.pptxdocument_undoProfiledJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}undoReceiptJson(){let e,t;try{let o=n.pptxdocument_undoReceiptJson(this.__wbg_ptr);var i=o[0],r=o[1];if(o[3])throw i=0,r=0,_(o[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}validateEditsJson(e){let t,i;try{let a=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=n.pptxdocument_validateEditsJson(this.__wbg_ptr,a,l);var r=s[0],o=s[1];if(s[3])throw r=0,o=0,_(s[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}static version(){let e,t;try{let i=n.pptxdocument_version();return e=i[0],t=i[1],f(i[0],i[1])}finally{n.__wbindgen_free(e,t,1);}}};Symbol.dispose&&(v.prototype[Symbol.dispose]=v.prototype.free);var N=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,be.unregister(this),e}free(){let e=this.__destroy_into_raw();n.__wbg_pptxrenderer_free(e,0);}hitTestJson(e,t){let i,r;try{let l=n.pptxrenderer_hitTestJson(this.__wbg_ptr,e,t);var o=l[0],a=l[1];if(l[3])throw o=0,a=0,_(l[2]);return i=o,r=a,f(o,a)}finally{n.__wbindgen_free(i,r,1);}}hitTestSlideJson(e,t,i,r){let o,a;try{A(e,v);let h=m(t,n.__wbindgen_malloc,n.__wbindgen_realloc),w=u,E=n.pptxrenderer_hitTestSlideJson(this.__wbg_ptr,e.__wbg_ptr,h,w,i,r);var l=E[0],s=E[1];if(E[3])throw l=0,s=0,_(E[2]);return o=l,a=s,f(l,s)}finally{n.__wbindgen_free(o,a,1);}}layoutProposalDiffSlideJson(e,t,i){let r,o;try{A(e,v);let s=m(t,n.__wbindgen_malloc,n.__wbindgen_realloc),h=u,w=n.pptxrenderer_layoutProposalDiffSlideJson(this.__wbg_ptr,e.__wbg_ptr,s,h,i);var a=w[0],l=w[1];if(w[3])throw a=0,l=0,_(w[2]);return r=a,o=l,f(a,l)}finally{n.__wbindgen_free(r,o,1);}}layoutProposalSlideJson(e,t,i){let r,o;try{A(e,v);let s=m(t,n.__wbindgen_malloc,n.__wbindgen_realloc),h=u,w=n.pptxrenderer_layoutProposalSlideJson(this.__wbg_ptr,e.__wbg_ptr,s,h,i);var a=w[0],l=w[1];if(w[3])throw a=0,l=0,_(w[2]);return r=a,o=l,f(a,l)}finally{n.__wbindgen_free(r,o,1);}}layoutSlideJson(e,t){let i,r;try{A(e,v);let l=n.pptxrenderer_layoutSlideJson(this.__wbg_ptr,e.__wbg_ptr,t);var o=l[0],a=l[1];if(l[3])throw o=0,a=0,_(l[2]);return i=o,r=a,f(o,a)}finally{n.__wbindgen_free(i,r,1);}}layoutSlideProfiledJson(e,t){let i,r;try{A(e,v);let l=n.pptxrenderer_layoutSlideProfiledJson(this.__wbg_ptr,e.__wbg_ptr,t);var o=l[0],a=l[1];if(l[3])throw o=0,a=0,_(l[2]);return i=o,r=a,f(o,a)}finally{n.__wbindgen_free(i,r,1);}}constructor(){let e=n.pptxrenderer_new();return this.__wbg_ptr=e,be.register(this,this.__wbg_ptr,this),this}registerFallbackFont(e,t,i,r){let o=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,l=J(r,n.__wbindgen_malloc),s=u,h=n.pptxrenderer_registerFallbackFont(this.__wbg_ptr,o,a,t,i,l,s);if(h[2])throw _(h[1]);return h[0]>>>0}registerFont(e,t,i,r){let o=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),a=u,l=J(r,n.__wbindgen_malloc),s=u,h=n.pptxrenderer_registerFont(this.__wbg_ptr,o,a,t,i,l,s);if(h[2])throw _(h[1]);return h[0]>>>0}saveBytes(e){A(e,v);let t=n.pptxrenderer_saveBytes(this.__wbg_ptr,e.__wbg_ptr);if(t[3])throw _(t[2]);var i=F(t[0],t[1]).slice();return n.__wbindgen_free(t[0],t[1]*1,1),i}setActiveSlide(e,t,i){A(e,v);let r=m(t,n.__wbindgen_malloc,n.__wbindgen_realloc),o=u,a=m(i,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u;return n.pptxrenderer_setActiveSlide(this.__wbg_ptr,e.__wbg_ptr,r,o,a,l)!==0}slideLayoutKey(e,t){let i,r;try{A(e,v);let l=n.pptxrenderer_slideLayoutKey(this.__wbg_ptr,e.__wbg_ptr,t);var o=l[0],a=l[1];if(l[3])throw o=0,a=0,_(l[2]);return i=o,r=a,f(o,a)}finally{n.__wbindgen_free(i,r,1);}}snapshotWithLayoutKeysJson(e){let t,i;try{A(e,v);let a=n.pptxrenderer_snapshotWithLayoutKeysJson(this.__wbg_ptr,e.__wbg_ptr);var r=a[0],o=a[1];if(a[3])throw r=0,o=0,_(a[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}};Symbol.dispose&&(N.prototype[Symbol.dispose]=N.prototype.free);function we(d){let e=J(d,n.__wbindgen_malloc),t=u,i=n.decodeTiffPng(e,t);if(i[3])throw _(i[2]);var r=F(i[0],i[1]).slice();return n.__wbindgen_free(i[0],i[1]*1,1),r}function he(d,e){let t,i;try{let a=J(d,n.__wbindgen_malloc),l=u,s=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),h=u,w=n.exportPptxMarkdownJson(a,l,s,h);var r=w[0],o=w[1];if(w[3])throw r=0,o=0,_(w[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}function xe(d,e){let t,i;try{let a=J(d,n.__wbindgen_malloc),l=u,s=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),h=u,w=n.exportPptxStructuredJson(a,l,s,h);var r=w[0],o=w[1];if(w[3])throw r=0,o=0,_(w[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}function Pe(d){let e,t;try{let o=J(d,n.__wbindgen_malloc),a=u,l=n.parsePptxJson(o,a);var i=l[0],r=l[1];if(l[3])throw i=0,r=0,_(l[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}function Se(d){let e,t;try{let o=J(d,n.__wbindgen_malloc),a=u,l=n.parsePptxJsonWithoutMedia(o,a);var i=l[0],r=l[1];if(l[3])throw i=0,r=0,_(l[2]);return e=i,t=r,f(i,r)}finally{n.__wbindgen_free(e,t,1);}}function ve(d,e){let t,i;try{let a=m(d,n.__wbindgen_malloc,n.__wbindgen_realloc),l=u,s=m(e,n.__wbindgen_malloc,n.__wbindgen_realloc),h=u,w=n.renderPptxMarkdownJson(a,l,s,h);var r=w[0],o=w[1];if(w[3])throw r=0,o=0,_(w[2]);return t=r,i=o,f(r,o)}finally{n.__wbindgen_free(t,i,1);}}function Re(){let d,e;try{let t=n.rendererVersion();return d=t[0],e=t[1],f(t[0],t[1])}finally{n.__wbindgen_free(d,e,1);}}function ze(){return {__proto__:null,"./pptx_wasm_bg.js":{__proto__:null,__wbg___wbindgen_is_function_1f9d30630b8b1d3d:function(e){return typeof e=="function"},__wbg___wbindgen_is_undefined_8865fb403f8fe9d8:function(e){return e===void 0},__wbg___wbindgen_throw_41e9ee4f547fc59a:function(e,t){throw new Error(f(e,t))},__wbg_call_6137034ef55c9d0f:function(){return te(function(e,t){return e.call(t)},arguments)},__wbg_getRandomValues_a608c4436c19407a:function(){return te(function(e,t){globalThis.crypto.getRandomValues(F(e,t));},arguments)},__wbg_get_31af05bd4842a84f:function(){return te(function(e,t){return Reflect.get(e,t)},arguments)},__wbg_new_343a093a3c2ffb4e:function(e,t){return new Error(f(e,t))},__wbg_now_768605f660f91245:function(){return performance.now()},__wbg_now_a11c1f81480929eb:function(){return performance.now()},__wbg_now_aa4ccb83129e9e55:function(){return Date.now()},__wbg_random_5a4cafd2f02395ff:function(){return Math.random()},__wbg_set_145a351398b48c65:function(){return te(function(e,t,i){return Reflect.set(e,t,i)},arguments)},__wbg_set_name_2c630595dc90a7aa:function(e,t,i){e.name=f(t,i);},__wbg_static_accessor_GLOBAL_266715b9d96ba635:function(){let e=typeof global>"u"?null:global;return M(e)?0:q(e)},__wbg_static_accessor_GLOBAL_THIS_10fb7dc1ae063179:function(){let e=typeof globalThis>"u"?null:globalThis;return M(e)?0:q(e)},__wbg_static_accessor_SELF_0b583911f537483a:function(){let e=typeof self>"u"?null:self;return M(e)?0:q(e)},__wbg_static_accessor_WINDOW_d7f903d1508cbdc4:function(){let e=typeof window>"u"?null:window;return M(e)?0:q(e)},__wbindgen_generic_0000000000000001:function(e,t){return f(e,t)},__wbindgen_init_externref_table:function(){let e=n.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,true),e.set(t+3,false);}}}}var ye=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(d=>n.__wbg_pptxdocument_free(d,1)),be=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(d=>n.__wbg_pptxrenderer_free(d,1));function q(d){let e=n.__externref_table_alloc();return n.__wbindgen_externrefs.set(e,d),e}function A(d,e){if(!(d instanceof e))throw new Error(`expected instance of ${e.name}`)}function F(d,e){return d=d>>>0,B().subarray(d/1,d/1+e)}function f(d,e){return $e(d>>>0,e)}var K=null;function B(){return (K===null||K.byteLength===0)&&(K=new Uint8Array(n.memory.buffer)),K}function te(d,e){try{return d.apply(this,e)}catch(t){let i=q(t);n.__wbindgen_exn_store(i);}}function M(d){return d==null}function J(d,e){let t=e(d.length*1,1)>>>0;return B().set(d,t/1),u=d.length,t}function m(d,e,t){if(t===void 0){let l=V.encode(d),s=e(l.length,1)>>>0;return B().subarray(s,s+l.length).set(l),u=l.length,s}let i=d.length,r=e(i,1)>>>0,o=B(),a=0;for(;a<i;a++){let l=d.charCodeAt(a);if(l>127)break;o[r+a]=l;}if(a!==i){a!==0&&(d=d.slice(a)),r=t(r,i,i=a+d.length*3,1)>>>0;let l=B().subarray(r+a,r+i),s=V.encodeInto(d,l);a+=s.written,r=t(r,i,a,1)>>>0;}return u=a,r}function _(d){let e=n.__wbindgen_externrefs.get(d);return n.__externref_table_dealloc(d),e}var re=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});re.decode();var Ze=2146435072,de=0;function $e(d,e){return de+=e,de>=Ze&&(re=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}),re.decode(),de=e),re.decode(B().subarray(d,d+e))}var V=new TextEncoder;"encodeInto"in V||(V.encodeInto=function(d,e){let t=V.encode(d);return e.set(t),{read:d.length,written:t.length}});var u=0,n;function Xe(d,e){return n=d.exports,K=null,n.__wbindgen_start(),n}async function Qe(d,e){if(typeof Response=="function"&&d instanceof Response){if(!d.ok)throw new Error(`failed to fetch Wasm: ${d.status} ${d.statusText} fetching '${d.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(d,e)}catch(r){if(t(d.type)&&d.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let i=await d.arrayBuffer();return await WebAssembly.instantiate(i,e)}else {let i=await WebAssembly.instantiate(d,e);return i instanceof WebAssembly.Instance?{instance:i,module:d}:i}function t(i){switch(i){case "basic":case "cors":case "default":return true}return false}}async function Te(d){if(n!==void 0)return n;if(d!==void 0&&(Object.getPrototypeOf(d)===Object.prototype?{module_or_path:d}=d:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),d===void 0)throw new Error("pptx-wasm requires an explicit module or URL");let e=ze();(typeof d=="string"||typeof Request=="function"&&d instanceof Request||typeof URL=="function"&&d instanceof URL)&&(d=fetch(d));let{instance:t,module:i}=await Qe(await d,e);return Xe(t)}var le=false,k=class extends Error{constructor(t,i){super(i);a(this,"code",t);this.name="PresentationPeerError";}},et=["insertText","deleteText","formatText","setStoryParagraphs","insertParagraphBreak","setParagraphAlignment","insertTableRow","deleteTableRow","insertTableColumn","deleteTableColumn","insertSlide","duplicateSlide","deleteSlide","moveSlide","setSlideNotes","setSlideLayout","addTextBox","addShape","addPicture","removeShape","moveShape","resizeShape","setShapeRect","setShapeFill","setShapeStroke","setShapeAdjust","bringShapeToFront","sendShapeToBack","bringShapeForward","sendShapeBackward","addComment","replyToComment","setCommentStatus","setCommentPosition","removeComment","setCommentFlavor","propose","acceptProposal","rejectProposal","applyEdits","addUndoBoundary","undo","redo"],Ee=new WeakMap;function j(d){let e=Ee.get(d);if(!e)throw new k("stage","Presentation is not a retained replay handle");return e}function yt(d,e={}){try{return ue(d,e,{kind:"baseline"})}catch(t){throw ne(t)}}function bt(d,e,t={}){try{return ue(d,t,{kind:"peer",identity:e})}catch(i){throw ne(i)}}function wt(d){return j(d).registerFonts()}function ht(d){j(d).adopt();}function xt(d){return j(d).hydration()}function Pt(d){return j(d).metadata()}function St(d,e){return j(d).displayListJson(e)}function vt(d,e,t){return j(d).replay(e,t)}var ke=new WeakMap,Ce=new WeakMap,Ie=new WeakMap,Oe=new WeakMap;function Rt(d,e){let t=Ie.get(d);if(!t)throw new Error("Presentation story formatting is unavailable");return t(e)}function Tt(d,e,t,i){let r=Oe.get(d);if(!r)throw new Error("Presentation paragraph joining is unavailable");return r(e,t,i)}function Jt(d){let e=Ce.get(d);if(!e)throw new Error("Presentation metadata is unavailable");return e()}function Et(d,e){let t=ke.get(d);if(!t)throw new Error("Presentation display list is unavailable");return t(e)}function Je(){return typeof v.prototype.proposeJson=="function"&&typeof N.prototype.layoutProposalSlideJson=="function"}var z;function ce(d=me()){return le?Promise.resolve():z||(z=Te({module_or_path:d}).then(()=>{le=true;},e=>{throw z=void 0,D(e)}),z)}function kt(){return typeof WebAssembly=="object"}function Ct(){return oe(),Re()}function tt(d,e={}){return oe(),ot(()=>e.includeMedia===false?Se(d):Pe(d))}function _e(d){let e=Fe(d);if(!e.ok)throw new ee(e.failure);return e.content}async function It(d,e={}){await ce();let t=C(e);return _e(()=>xe(d,t))}async function Ot(d,e={}){await ce();let t=C(e);return _e(()=>he(d,t))}async function At(d,e={}){await ce();let t=C(e);return _e(()=>ve(JSON.stringify(d),t))}function Ft(d){return oe(),pe(()=>we(d))}function rt(d,e={}){return ue(d,e)}function ue(d,e,t){if(oe(),e.clientId!==void 0&&e.clientId>=r){let p="client id must be a positive safe integer below Number.MAX_SAFE_INTEGER - 1";throw t?new k("clientId",p):new Error(p)}let i=t?[...(e.fonts??[]).map(p=>({...p,bytes:new Uint8Array(p.bytes),fallback:false})),...(e.fallbackFonts??[]).map(p=>({...p,bytes:new Uint8Array(p.bytes),fallback:true}))]:[],r$1=t&&e.initialUpdate!==void 0?new Uint8Array(e.initialUpdate):void 0,o=t?e.clientId:e.clientId??nt(),a=pe(()=>t?t.kind==="baseline"?v.openReplayBaseline(new Uint8Array(d),o,r$1):v.openPeerDeckJson(new Uint8Array(d),t.identity,r$1):e.initialUpdate===void 0?v.openCollaborative(d,o):v.openCollaborativeFromUpdate(e.initialUpdate.slice(),o,d.slice())),l;try{l=pe(()=>new N);}catch(p){if(t){try{a.free();}catch{}throw ne(p)}throw p}if(!t){for(let p of e.fonts??[])Z(l,p);for(let p of e.fallbackFonts??[])Z(l,p,true);}let s=new Map,h=[],w=0,E=false,U=false,Y=0,G=false,X=()=>{if(E)throw new Error("presentation handle is disposed")},We=()=>{if(!(E||G||Y!==0)){G=true;try{for(;!E&&h.length>0;){let p=h.shift();if(!p)break;for(let[c,y]of [...s]){if(E)return;if(s.get(c)===y)try{y(p.update.slice(),p.origin);}catch{}}}}finally{G=false,E&&(h.length=0);}}},qe=()=>{if(!(!U||E))for(;;){let p=a.drainUpdateEvent();if(p.byteLength===0)return;let c=p[0];if(c!==0&&c!==1)throw new Error(`pptx wasm returned unknown update origin ${c}`);h.push({update:p.subarray(1),origin:c===0?"local":"remote"});}},x=(p,c=false)=>{X(),Y+=1;try{let y,b,T=!1;try{y=p();}catch(S){b=S,T=!0;}if(c)try{qe();}catch(S){T||(b=S,T=!0);}if(T)throw D(b);return y}finally{Y-=1,Y===0&&We();}},g=(p,c=false)=>x(()=>JSON.parse(p()),c),Ke=()=>{U||(x(()=>a.startUpdateObservation()),U=true);},Ve=()=>{!U||s.size>0||E||(h.length=0,x(()=>a.clearUpdateObservation()),U=false);},ge=new Uint8Array(d),ie=false,I={fork(){X();let p=rt(ge,{initialUpdate:I.encodeStateAsUpdate()});return ie&&p.setCollaborative(),p},setCollaborative(){ie=true,x(()=>a.setCollaborative());},isCollaborative(){return ie},layouts(){X();let p=y=>y.flatMap(b=>[...b.placeholder?[{id:String(b.id),name:b.name,type:b.placeholder.placeholderType,idx:b.placeholder.index}]:[],...p(b.children??[])]),c=tt(ge,{includeMedia:false});return c.layouts.map(y=>({id:y.partPath,name:y.name,type:y.layoutType,masterId:y.masterPartPath??c.masters.find(b=>b.layoutPartPaths.includes(y.partPath))?.partPath??null,placeholders:p(y.shapes)}))},isProposalsAvailable:Je,propose(p,c,y){return g(()=>a.proposeJson(JSON.stringify({agentId:p,note:c,edits:y})))},listProposals(){return Je()?g(()=>a.listProposalsJson()):[]},previewProposal(p){return g(()=>a.previewProposalJson(JSON.stringify({id:p})))},layoutProposalDiffSlide(p,c){return g(()=>l.layoutProposalDiffSlideJson(a,p,c))},layoutProposalSlide(p,c){return g(()=>l.layoutProposalSlideJson(a,p,c))},acceptProposal(p,c){return g(()=>a.acceptProposalJson(JSON.stringify({id:p,force:c?.force??false})),true)},rejectProposal(p){return g(()=>a.rejectProposalJson(JSON.stringify({id:p})))},get clientId(){return x(()=>a.clientId)},snapshot(){return g(()=>a.snapshotJson())},story(p){return g(()=>a.storyJson(JSON.stringify({storyId:p})))},anchorCaret(p,c){return g(()=>a.anchorCaretJson(JSON.stringify({storyId:p,index:c})))},resolveCaretAnchor(p){return g(()=>a.resolveCaretAnchorJson(JSON.stringify({storyId:p.storyId,position:p.position})))},version(){return x(()=>a.documentVersion())},readContent(p={}){let c=C(p);return g(()=>a.readContentJson(c))},readCommandContent(p={}){let c=C(p);return g(()=>a.readCommandContentJson(c))},historyStep(p){return g(()=>p==="undo"?a.undoReceiptJson():a.redoReceiptJson(),true)},findText(p){let c=C(p);return g(()=>a.findTextJson(c))},exportStructured(p={}){let c=C(p);return g(()=>a.exportStructuredJson(c))},exportMarkdown(p={}){let c=C(p);return g(()=>a.exportMarkdownJson(c))},validateEdits(p){let c=C(p);return g(()=>a.validateEditsJson(c))},applyEdits(p){let c=C(p);return g(()=>a.applyEditsJson(c),true)},searchText(p,c={}){if(!p)return [];let y=c.limit??Number.POSITIVE_INFINITY;if(!Number.isSafeInteger(y)&&y!==Number.POSITIVE_INFINITY||y<0)throw new RangeError("search limit must be a non-negative safe integer");return g(()=>a.searchTextJson(JSON.stringify({query:p,caseSensitive:c.caseSensitive??false,limit:Number.isFinite(y)?Math.min(y,4294967295):void 0})))},registerFont(p){return x(()=>Z(l,p))},registerFallbackFont(p){return x(()=>Z(l,p,!0))},layoutSlide(p){return g(()=>l.layoutSlideJson(a,p))},layoutSlideProfiled(p){return g(()=>l.layoutSlideProfiledJson(a,p))},hitTest(p,c){return g(()=>l.hitTestJson(p,c))},mediaBytes(p){return x(()=>a.mediaBytes(p))},save(){return x(()=>l.saveBytes(a))},insertText(p,c,y,b={}){return g(()=>a.insertTextJson(JSON.stringify({storyId:p,index:c,text:y,style:b})),true)},insertTextProfiled(p,c,y,b={}){return g(()=>a.insertTextProfiledJson(JSON.stringify({storyId:p,index:c,text:y,style:b})),true)},deleteText(p,c,y){return g(()=>a.deleteTextJson(JSON.stringify({storyId:p,start:c,end:y})),true)},deleteTextProfiled(p,c,y){return g(()=>a.deleteTextProfiledJson(JSON.stringify({storyId:p,start:c,end:y})),true)},formatText(p,c,y,b){return g(()=>a.formatTextJson(JSON.stringify({storyId:p,start:c,end:y,patch:b})),true)},insertParagraphBreak(p,c){return g(()=>a.insertParagraphBreakJson(JSON.stringify({storyId:p,index:c})),true)},setParagraphAlignment(p,c,y,b){return g(()=>a.setParagraphAlignmentJson(JSON.stringify({storyId:p,start:c,end:y,alignment:b})),true)},insertTableRow(p,c,y,b,T){return g(()=>a.insertTableRowJson(JSON.stringify({slideId:p,shapeId:c,index:y,position:b,cells:T})),true)},checkTableEdit(p,c,y,b,T,S){let P={insertTableRow:"insertRow",deleteTableRow:"deleteRow",insertTableColumn:"insertColumn",deleteTableColumn:"deleteColumn"}[p];x(()=>a.checkTableEditJson(JSON.stringify({edit:P,slideId:c,shapeId:y,index:b,position:T,cells:S})));},deleteTableRow(p,c,y){return g(()=>a.deleteTableRowJson(JSON.stringify({slideId:p,shapeId:c,index:y})),true)},insertTableColumn(p,c,y,b,T){return g(()=>a.insertTableColumnJson(JSON.stringify({slideId:p,shapeId:c,index:y,position:b,cells:T})),true)},deleteTableColumn(p,c,y){return g(()=>a.deleteTableColumnJson(JSON.stringify({slideId:p,shapeId:c,index:y})),true)},insertSlide(p,c){return g(()=>a.insertSlideJson(JSON.stringify({index:p,layoutPartPath:c??null})),true)},setStoryParagraphs(p,c){return g(()=>a.setStoryParagraphsJson(JSON.stringify({storyId:p,paragraphs:c})),true)},duplicateSlide(p,c){return g(()=>a.duplicateSlideJson(JSON.stringify({slideId:p,toIndex:c})),true)},insertSlideProfiled(p,c){return g(()=>a.insertSlideProfiledJson(JSON.stringify({index:p,layoutPartPath:c??null})),true)},deleteSlide(p){return g(()=>a.deleteSlideJson(JSON.stringify({slideId:p})),true)},moveSlide(p,c){return g(()=>a.moveSlideJson(JSON.stringify({slideId:p,toIndex:c})),true)},setSlideLayout(p,c,y=[]){let b=y.map(([T,S])=>{if(!/^\d+$/u.test(S)||!Number.isSafeInteger(Number(S))||Number(S)>4294967295)throw new Error("Invalid layout placeholder ID");return [T,Number(S)]});g(()=>a.setSlideLayoutJson(JSON.stringify({slideId:p,layoutPartPath:c,mapping:b})),true);},setSlideNotes(p,c){g(()=>a.setSlideNotesJson(JSON.stringify({slideId:p,text:c})),true);},addComment(p,c){return g(()=>a.addCommentJson(JSON.stringify({slideId:p,author:c.author,initials:c.initials??"",text:c.text,created:c.created,xEmu:c.xEmu??0,yEmu:c.yEmu??0})),true)},replyToComment(p,c){return g(()=>a.replyToCommentJson(JSON.stringify({commentId:p,author:c.author,initials:c.initials??"",text:c.text,created:c.created})),true)},setCommentPosition(p,c){if(!Number.isSafeInteger(c.xEmu)||!Number.isSafeInteger(c.yEmu))throw new Error("Comment coordinates must be safe integer EMU");return g(()=>a.setCommentPositionJson(JSON.stringify({commentId:p,...c})),true)},setCommentStatus(p,c){return g(()=>a.setCommentStatusJson(JSON.stringify({commentId:p,resolved:c})),true)},removeComment(p){return g(()=>a.removeCommentJson(JSON.stringify({commentId:p})),true)},setCommentFlavor(p){return g(()=>a.setCommentFlavorJson(JSON.stringify({flavor:p})),true)},comments(){return g(()=>a.commentsJson())},addTextBox(p,c){return g(()=>a.addTextBoxJson(JSON.stringify({slideId:p,draft:c})),true)},addTextBoxProfiled(p,c){return g(()=>a.addTextBoxProfiledJson(JSON.stringify({slideId:p,draft:c})),true)},addShape(p,c){return g(()=>a.addShapeJson(JSON.stringify({slideId:p,draft:c})),true)},addPicture(p,c){return g(()=>a.addPictureJson(JSON.stringify({slideId:p,...c})),true)},setShapeFill(p,c,y){return g(()=>a.setShapeFillJson(JSON.stringify({slideId:p,shapeId:c,color:y})),true)},setShapeStroke(p,c,y){return g(()=>a.setShapeStrokeJson(JSON.stringify({slideId:p,shapeId:c,stroke:y})),true)},setShapeAdjust(p,c,y){return g(()=>a.setShapeAdjustJson(JSON.stringify({slideId:p,shapeId:c,adjustments:y})),true)},removeShape(p,c){return g(()=>a.removeShapeJson(JSON.stringify({slideId:p,shapeId:c})),true)},bringShapeToFront(p,c){return g(()=>a.bringShapeToFrontJson(JSON.stringify({slideId:p,shapeId:c})),true)},sendShapeToBack(p,c){return g(()=>a.sendShapeToBackJson(JSON.stringify({slideId:p,shapeId:c})),true)},bringShapeForward(p,c){return g(()=>a.bringShapeForwardJson(JSON.stringify({slideId:p,shapeId:c})),true)},sendShapeBackward(p,c){return g(()=>a.sendShapeBackwardJson(JSON.stringify({slideId:p,shapeId:c})),true)},moveShape(p,c,y,b){return g(()=>a.moveShapeJson(JSON.stringify({slideId:p,shapeId:c,x:y,y:b})),true)},moveShapeProfiled(p,c,y,b){return g(()=>a.moveShapeProfiledJson(JSON.stringify({slideId:p,shapeId:c,x:y,y:b})),true)},resizeShape(p,c,y,b){return g(()=>a.resizeShapeJson(JSON.stringify({slideId:p,shapeId:c,width:y,height:b})),true)},setShapeRect(p,c,y){return g(()=>a.setShapeRectJson(JSON.stringify({slideId:p,shapeId:c,rect:y})),true)},canUndo(){return x(()=>a.canUndo())},canRedo(){return x(()=>a.canRedo())},undoCaptureMode(){return x(()=>a.undoCaptureMode())},setUndoCaptureMode(p){x(()=>a.setUndoCaptureMode(p));},addUndoBoundary(){x(()=>a.addUndoBoundary());},undo(){return g(()=>a.undoJson(),true)},undoProfiled(){return g(()=>a.undoProfiledJson(),true)},redo(){return g(()=>a.redoJson(),true)},encodeStateVector(){return x(()=>a.encodeStateVector())},encodeStateAsUpdate(p){return x(()=>p===void 0?a.encodeStateAsUpdate():a.encodeDiff(p))},encodeDiff(p){return x(()=>a.encodeDiff(p))},applyUpdate(p){return g(()=>a.applyUpdateJson(p),true)},onUpdate(p){if(X(),typeof p!="function")throw new TypeError("update listener must be a function");let c=w++;s.set(c,p);try{Ke();}catch(b){throw s.delete(c),b}let y=true;return ()=>{y&&(y=false,s.delete(c),Ve());}},dispose(){if(E)return;E=true,i.length=0,s.clear(),h.length=0;let p;if(U){try{a.clearUpdateObservation();}catch(c){p=c;}U=false;}try{l.free();}catch(c){p??(p=c);}try{a.free();}catch(c){p??(p=c);}if(p!==void 0)throw D(p)}};if(ke.set(I,p=>x(()=>l.layoutSlideJson(a,p))),Ce.set(I,()=>g(()=>a.sessionMetadataJson())),Ie.set(I,p=>g(()=>a.storyFormattingJson(JSON.stringify({slideId:p.slideId,shapeId:p.shapeId,storyId:p.storyId})))),t||Oe.set(I,(p,c,y)=>g(()=>a.deleteTextJson(JSON.stringify({storyId:p,start:c,end:y,allowParagraphJoin:true})),true)),Object.defineProperty(I,Symbol.for("@betteroffice/pptx/slide-layout-cache"),{value:{snapshot:()=>g(()=>l.snapshotWithLayoutKeysJson(a)),key:p=>x(()=>l.slideLayoutKey(a,p)),activate:(p,c)=>x(()=>l.setActiveSlide(a,p,c)),hitTest:(p,c,y)=>g(()=>l.hitTestSlideJson(a,p,c,y))}}),t){let p="deck",c="",y,b=false,T=P=>{p="failed",i.length=0;try{I.dispose();}catch{}throw ne(P)},S=P=>{if(E||p!==P)throw new k("stage",`Presentation peer requires ${P} stage`)};Ee.set(I,{metadata(){return S("ready"),g(()=>a.sessionMetadataJson())},displayListJson(P){return S("ready"),x(()=>l.layoutSlideJson(a,P))},async registerFonts(){try{S("deck"),p="registering";let P=[];for(let O of i){let se=await globalThis.crypto.subtle.digest("SHA-256",O.bytes);S("registering"),P.push({family:O.family,bold:O.bold??!1,italic:O.italic??!1,fallback:O.fallback,fingerprint:Array.from(new Uint8Array(se),W=>W.toString(16).padStart(2,"0")).join("")});}c=JSON.stringify(P),x(()=>{for(let O of i)Z(l,O,O.fallback);t.kind==="peer"&&a.registerPeerFontsJson(c);}),i.length=0,p="fonts";}catch(P){return T(P)}},adopt(){try{if(S("fonts"),t.kind!=="peer")throw new k("stage","Only a peer can adopt identity");x(()=>a.adoptPeerIdentity()),p="ready";}catch(P){return T(P)}},hydration(){if(t.kind!=="baseline")throw new k("stage","Only the worker baseline can capture hydration");if(y!==void 0)return S("ready"),y;try{return S("fonts"),y=x(()=>a.peerHydrationJson(c)),p="ready",y}catch(P){return T(P)}},replay(P,O){if(S("ready"),b||G)throw new k("stage","Presentation replay cannot reenter");b=true;try{let se=C(P);return x(()=>{let W=JSON.parse(a.replayJson(se));return Ae(W),O?.(W),W},!0)}finally{b=false;}}});for(let P of [...et,"insertTextProfiled","deleteTextProfiled","insertSlideProfiled","addTextBoxProfiled","moveShapeProfiled","undoProfiled","applyUpdate","setUndoCaptureMode","registerFont","registerFallbackFont","historyStep","readCommandContent"])Object.defineProperty(I,P,{value:()=>{throw new k("stage","Retained presentations require ordered replay")}});}return I}function Ae(d){if(!(d===null||typeof d!="object")){for(let e of Object.values(d))Ae(e);Object.freeze(d);}}function ne(d){let e=D(d);return e instanceof k?e:new k("engine",e.message)}function C(d){return JSON.stringify(d,(e,t)=>{if(typeof t=="number"&&!Number.isFinite(t))throw new RangeError("host requests must not contain NaN or infinite numbers");return t})}function Z(d,e,t=false){try{return (t?d.registerFallbackFont:d.registerFont).call(d,e.family,e.bold??!1,e.italic??!1,e.bytes)}catch(i){throw D(i)}}function oe(){if(!le)throw new Error("pptx wasm is not initialized; call initWasm() first")}function nt(){let d=globalThis.crypto;if(!d||typeof d.getRandomValues!="function")throw new Error("crypto.getRandomValues is required to generate a collaboration client ID");let e=new Uint32Array(2),t;do d.getRandomValues(e),t=(e[0]&2097151)*4294967296+e[1];while(t===0||t>=r);return t}function pe(d){try{return d()}catch(e){throw D(e)}}function Fe(d){try{return JSON.parse(d())}catch(e){throw D(e)}}function ot(d){return Fe(d)}function D(d){if(d instanceof k)return d;if(d!==null&&typeof d=="object"&&"name"in d&&d.name==="PresentationPeerError"&&"code"in d&&typeof d.code=="string"&&"message"in d&&typeof d.message=="string")return new k(d.code,d.message);if(d instanceof Error)return d;if(typeof d=="string")try{let e=JSON.parse(d);if(e.code==="staleProposal"&&Array.isArray(e.targets)&&e.targets.every(t=>typeof t=="string"))return new Q(e.targets)}catch{}return Object.assign(new Error(typeof d=="string"?d:String(d)),{cause:d})}var L=class extends Error{constructor(t,i,r){super(i);a(this,"code",t);a(this,"cause",r);a(this,"refusal");this.name="PptxPeerHydrationError",this.refusal={code:t};}},Me=class extends Error{constructor(){super("Presentation editor is not ready");a(this,"code","peer-not-ready");this.name="PptxPeerNotReadyError";}},Ue=class extends Error{constructor(t){super(`Presentation worker editor failed: ${t instanceof Error?t.message:String(t)}`);a(this,"cause",t);a(this,"code","editor-failed");this.name="PptxWorkerEditorFailedError";}},Ne=class extends Error{constructor(){super("Presentation worker editor is disposed");a(this,"code","editor-disposed");this.name="PptxWorkerEditorDisposedError";}},De=class extends Error{constructor(){super("Collaboration is unavailable in the presentation worker editor");a(this,"code","collaboration-unavailable");this.name="PptxWorkerEditorCollaborationError";}};var Bt="SessionSuperseded",H=class extends Error{constructor(t,i,r){super(i);a(this,"code",t);a(this,"diagnostics",r);this.name="SessionFailure";}};function Be(d,e){let t=new Set,i=false;function r(o,a){if(i)return ()=>{};d.addEventListener(o,a);let l=()=>{d.removeEventListener(o,a),t.delete(l);};return t.add(l),d.start?.(),l}return {post(o,a=[]){if(i)throw new H("disposed","Session transport is closed");d.postMessage(o,a);},listen(o){return r("message",a=>o(a.data))},onError(o){let a=r("error",s=>o(new H("crash",s.message||"Session worker crashed"))),l=r("messageerror",()=>o(new H("message","Session transport received an unreadable message")));return ()=>{a(),l();}},close(){if(!i){i=true;for(let o of [...t])o();e();}}}}function Wt(d){return Be(d,()=>d.terminate())}function qt(d){return Be(d,()=>d.close?.())}function Vt(d){let e=new Set,t=i=>{for(let r of i)r.kind==="image"&&r.assetId?e.add(r.assetId):(r.kind==="chart"||r.kind==="table")&&t(r.primitives);};return t(d.primitives),e}function Zt(d){return d.length>=4&&(d[0]===73&&d[1]===73&&d[2]===42&&d[3]===0||d[0]===77&&d[1]===77&&d[2]===0&&d[3]===42)}var Le=Symbol("session-transfer"),it=Symbol("session-deferred");function Yt(d){return $(d)&&d[it]===true}function Gt(d,e){return {[Le]:true,value:d,transfer:e}}function Xt(d){return $(d)&&d[Le]===true}function je(d,e){return Object.prototype.hasOwnProperty.call(d,e)}function $(d){return d!==null&&typeof d=="object"}function fe(d){return typeof d=="number"&&Number.isSafeInteger(d)&&d>0}function Qt(d){return !$(d)||d.protocol!==1?false:d.kind==="wasm-compile"||d.kind==="dispose"||d.kind==="call"&&fe(d.id)&&typeof d.method=="string"&&Array.isArray(d.args)}function er(d){if(!$(d)||d.protocol!==1)return false;switch(d.kind){case "wasm-module":try{return typeof d.url=="string"&&(d.hydration===void 0||typeof d.hydration=="string")&&Object.prototype.toString.call(d.module)==="[object WebAssembly.Module]"}catch{return false}case "reply":return fe(d.id)&&(d.ok===true&&je(d,"value")||d.ok===false&&$(d.error)&&typeof d.error.name=="string"&&typeof d.error.message=="string");case "event":return typeof d.name=="string"&&je(d,"payload");case "progress":return fe(d.id);case "failure":return ["crash","trap","out-of-memory","message","silence","disposed"].includes(d.code)&&typeof d.message=="string"&&(d.diagnostics===void 0||typeof d.diagnostics=="string");default:return false}}var rr=new WeakMap,nr={beginEditor:true,attachPeer:true,replay:true,flush:true,editorFrame:true,editorSave:true},or={beginEditor:{lane:"interactive"},attachPeer:{lane:"interactive"},replay:{lane:"input",mutates:true,userInput:true},flush:{lane:"interactive"},editorFrame:{lane:"interactive",reframes:true},editorSave:{lane:"interactive"}},ir={insertText:true,deleteText:true,formatText:true,setStoryParagraphs:true,insertParagraphBreak:true,setParagraphAlignment:true,insertSlide:true,duplicateSlide:true,deleteSlide:true,moveSlide:true,setSlideNotes:true,setSlideLayout:true,addTextBox:true,addShape:true,addPicture:true,removeShape:true,moveShape:true,resizeShape:true,setShapeRect:true,setShapeFill:true,setShapeStroke:true,setShapeAdjust:true,bringShapeToFront:true,sendShapeToBack:true,bringShapeForward:true,sendShapeBackward:true,addComment:true,replyToComment:true,setCommentStatus:true,setCommentPosition:true,removeComment:true,setCommentFlavor:true,propose:true,acceptProposal:true,rejectProposal:true,applyEdits:true,addUndoBoundary:true,undo:true,redo:true};function He(d,e){if(Object.is(d,e))return true;if(!d||!e||typeof d!="object"||typeof e!="object"||Array.isArray(d)!==Array.isArray(e))return false;let t=Object.keys(d),i=Object.keys(e);return t.length===i.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&He(d[r],e[r]))}function sr(d,e){return e.consumed===true&&d.sequence===e.sequence&&d.revision===e.revision&&d.version===e.version&&d.engineVersion===e.engineVersion&&He(d.outcome,e.outcome)}var dr={open:true,version:true,readContent:true,findText:true,validateEdits:true,applyEdits:true,frame:true,slides:true,slideSize:true,save:true,dispose:true},lr={open:{lane:"interactive"},version:{lane:"interactive"},readContent:{lane:"interactive"},findText:{lane:"interactive"},validateEdits:{lane:"interactive"},applyEdits:{lane:"input",mutates:true,userInput:true},frame:{lane:"interactive",reframes:true,key:"frame",replaceableBy:"frame"},slides:{lane:"interactive"},slideSize:{lane:"interactive"},save:{lane:"interactive"},dispose:{lane:"interactive"}};function ur(d){if(d instanceof L)return d;if(d instanceof k)return new L(d.code,d.message,d);if(d instanceof Error&&"refusal"in d){let e=d.refusal;if(e!==null&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return new L(e.code,d.message,d)}return d}export{rt as A,L as B,Me as C,Ue as D,Ne as E,De as F,Yt as G,Gt as H,Xt as I,je as J,Qt as K,er as L,Bt as M,H as N,Wt as O,qt as P,Vt as Q,rr as R,nr as S,or as T,ir as U,sr as V,dr as W,lr as X,ur as Y,Zt as a,me as b,Q as c,ee as d,k as e,yt as f,bt as g,wt as h,ht as i,xt as j,Pt as k,St as l,vt as m,Rt as n,Tt as o,Jt as p,Et as q,Je as r,ce as s,kt as t,Ct as u,tt as v,It as w,Ot as x,At as y,Ft as z};
@@ -0,0 +1 @@
1
+ var X=Object.defineProperty;var G=(e,t,n)=>t in e?X(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n;var p=(e,t,n)=>G(e,typeof t!="symbol"?t+"":t,n);var ie=3e3;var S=["#B3261E","#7B1FA2","#3949AB","#00796B","#2E7D32","#A84400","#C2185B","#00695C"],D=/^#[0-9a-fA-F]+$/;function Y(e){return S[Math.abs(e)%S.length]}function E(e,t){return typeof t=="string"&&(t.length===4||t.length===7)&&D.test(t)?t:Y(e)}function ae(e,t){if(t&&(typeof t.name!="string"||t.name.trim().length===0))throw new TypeError("Collaboration user name must be a non-empty string");if(t?.color!==void 0&&typeof t.color!="string")throw new TypeError("Collaboration user color must be a string");let n=t?.name.trim().slice(0,1024)||`Guest ${e.toString(36).toUpperCase()}`,r=E(e,t?.color);return {name:n,color:r}}function $(e){return e.slideId.length<=1024&&(e.shapeId===void 0||e.shapeId.length<=1024)}function ce(e,t){if(typeof e!="object"||e===null)return false;let n=e;return typeof n.slideId=="string"&&n.slideId.length>0&&(n.shapeId===void 0||typeof n.shapeId=="string"&&n.shapeId.length>0)&&$(n)&&new TextEncoder().encode(n.slideId+(n.shapeId??"")).byteLength<=t}function q(e,t){return e?.slideId===t?.slideId&&e?.shapeId===t?.shapeId}var _=class{constructor(t,n={}){p(this,"localClientId",t);p(this,"states",new Map);p(this,"clocks",new Map);p(this,"maxTrackedIds");if(this.maxTrackedIds=n.maxTrackedIds??4096,!Number.isSafeInteger(this.maxTrackedIds)||this.maxTrackedIds<1)throw new RangeError("Presence tracked id limit must be a positive integer")}get peers(){return [...this.states.values()].sort((t,n)=>t.state.clientId-n.state.clientId).map(j)}get trackedIdCount(){return this.clocks.size}get nextExpiryAt(){let t;for(let n of this.states.values()){let r=n.lastSeen+45e3;t=t===void 0?r:Math.min(t,r);}for(let n of this.clocks.values()){let r=n.updatedAt+3e5;t=t===void 0?r:Math.min(t,r);}return t}apply(t,n){let r=this.expire(n);for(let s of t){if(s.clientId===this.localClientId)continue;let o=this.clocks.get(s.clientId);if(o&&s.clock<=o.clock)continue;if(!o&&this.clocks.size>=this.maxTrackedIds&&(r=this.evictOldest()||r),this.clocks.delete(s.clientId),this.clocks.set(s.clientId,{clock:s.clock,updatedAt:n}),!s.state){r=this.states.delete(s.clientId)||r;continue}let a=this.states.get(s.clientId),c=a&&q(a.state.cursor,s.state.cursor)?a.cursorMovedAt:n;this.states.set(s.clientId,{state:x(s.state),lastSeen:n,cursorMovedAt:c}),r=true;}return r}expire(t,n=45e3){let r=false;for(let[s,o]of this.states)t-o.lastSeen<n||(this.states.delete(s),r=true);for(let[s,o]of this.clocks)t-o.updatedAt<3e5||(this.clocks.delete(s),r=this.states.delete(s)||r);return r}clear(){let t=this.states.size>0;return this.states.clear(),this.clocks.clear(),t}evictOldest(){let t=this.clocks.keys().next();return t.done?false:(this.clocks.delete(t.value),this.states.delete(t.value))}};function x(e){return {clientId:e.clientId,clock:e.clock,user:{...e.user},cursor:e.cursor?{...e.cursor}:null}}function j(e){return {state:x(e.state),lastSeen:e.lastSeen,cursorMovedAt:e.cursorMovedAt}}var l=16777216,b=4096,C=0,N=1,K=2,T=3,R=0,k=1,O=2,W=0,z=Number.MAX_SAFE_INTEGER,J=10,m=new TextEncoder().encode("\0betteroffice-document-fingerprint-v1\0"),i=class extends Error{constructor(t){super(t),this.name="ProtocolError";}},A=class{constructor(t){p(this,"bytes",t);p(this,"offset",0);}get done(){return this.offset===this.bytes.byteLength}readVarUint(){let t=0,n=1,r=0;for(;;){if(this.offset>=this.bytes.byteLength)throw new i("Truncated varUint");let s=this.bytes[this.offset++],o=s&127;if(o>Math.floor((z-t)/n))throw new i("varUint exceeds Number.MAX_SAFE_INTEGER");if(t+=o*n,r+=1,(s&128)===0){if(r>1&&o===0)throw new i("Non-canonical varUint");return t}if(r>=8)throw new i("varUint exceeds Number.MAX_SAFE_INTEGER");n*=128;}}readVarUint8Array(){let t=this.readVarUint(),n=this.bytes.byteLength-this.offset;if(t>n)throw new i("Truncated varUint8Array");let r=this.bytes.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarString(){let t=this.readVarUint8Array();try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch(n){throw new i(`Invalid UTF-8 string${n instanceof Error?`: ${n.message}`:""}`)}}};function u(e){if(!Number.isSafeInteger(e)||e<0)throw new i("varUint value must be a non-negative safe integer");let t=[],n=e;for(;n>=128;)t.push(n%128|128),n=Math.floor(n/128);return t.push(n),Uint8Array.from(t)}function Q(e){let t=new TextEncoder().encode(e);return f([u(t.byteLength),t],l)}function f(e,t){let n=0;for(let o of e)if(n+=o.byteLength,n>t)throw new i(`Frame exceeds ${t} bytes`);let r=new Uint8Array(n),s=0;for(let o of e)r.set(o,s),s+=o.byteLength;return r}function P(e,t,n){return f([u(C),u(e),u(t.byteLength),t],n)}function ye(e,t=l){return P(R,e,t)}function he(e,t=l){return P(k,e,t)}function be(e,t=l){return P(O,e,t)}function Ae(e,t=l){if(e.length>b)throw new i(`Awareness update exceeds ${b} entries`);let n=[u(e.length)];for(let s of e){F(s);let o=JSON.stringify(s.state);if(o===void 0)throw new i("Awareness state is not JSON serializable");n.push(u(s.clientId),u(s.clock),Q(o));}let r=f(n,t);return f([u(N),u(r.byteLength),r],t)}function Ee(e=l){return f([u(T)],e)}function me(e,t=b){if(!(e instanceof Uint8Array))throw new i("Awareness update must be a Uint8Array");if(!Number.isSafeInteger(t)||t<1)throw new i("Awareness entry limit must be a positive integer");let n=new A(e),r=n.readVarUint();if(r>t)throw new i(`Awareness update exceeds ${t} entries`);let s=[];for(let o=0;o<r;o+=1){let a=n.readVarUint(),c=n.readVarUint(),d;try{d=JSON.parse(n.readVarString());}catch(h){throw h instanceof i?h:new i(`Invalid awareness JSON${h instanceof Error?`: ${h.message}`:""}`)}let y={clientId:a,clock:c,state:B(d,a,c)};F(y),s.push(y);}if(!n.done)throw new i("Awareness update has trailing bytes");return s}function M(e){let t=m.byteLength+32,n=e.byteLength-t;if(n<0)return e;for(let r=0;r<m.byteLength;r+=1)if(e[n+r]!==m[r])return e;return e.subarray(0,n)}var L=Number.MAX_SAFE_INTEGER-1,v=BigInt(L),Z=65536;function V(e){let t=0,n=()=>{let a=0n;for(let c=0;c<J&&t<e.byteLength;c+=1){let d=e[t++];if(a|=BigInt(d&127)<<BigInt(7*c),d<128)return a}},r=n();if(r===void 0)return;let s=t,o=[];for(let a=r;a>0n;a-=1n){let c=t,d=n(),y=n();if(d===void 0||y===void 0)return;o.push({client:d,clock:y,start:c,end:t});}return t===e.byteLength?{header:s,entries:o}:void 0}function ge(e){let t=M(e),n=V(t);if(!n)return e;let{header:r,entries:s}=n;if(!(s.length>=Z||s.some(({client:o})=>o===v)))return f([u(s.length+1),t.subarray(r),u(L),u(0),e.subarray(t.byteLength)],Number.MAX_SAFE_INTEGER)}function we(e){let t=M(e),n=V(t);if(!n)return {stateVector:e,open:false};let r=n.entries.filter(({client:s,clock:o})=>s!==v||o!==0n);return r.length===n.entries.length?{stateVector:e,open:false}:{stateVector:f([u(r.length),...r.map(({start:s,end:o})=>t.subarray(s,o)),e.subarray(t.byteLength)],Number.MAX_SAFE_INTEGER),open:true}}function Pe(e,t=l,n=b){if(!(e instanceof Uint8Array))throw new i("Frame must be a Uint8Array");if(e.byteLength===0)throw new i("Frame is empty");if(e.byteLength>t)throw new i(`Frame exceeds ${t} bytes`);if(!Number.isSafeInteger(n)||n<1)throw new i("Message limit must be a positive integer");let r=new A(e),s=[];for(;!r.done;){if(s.length>=n)throw new i(`Frame exceeds ${n} messages`);let o=r.readVarUint();switch(o){case C:{let a=r.readVarUint(),c=r.readVarUint8Array();if(a===R)s.push({type:"sync-step-1",stateVector:c});else if(a===k)s.push({type:"sync-step-2",update:c});else if(a===O)s.push({type:"update",update:c});else throw new i(`Unknown sync message type ${a}`);break}case N:s.push({type:"awareness",update:r.readVarUint8Array()});break;case K:{let a=r.readVarUint();if(a!==W)throw new i(`Unknown auth message type ${a}`);s.push({type:"auth",reason:r.readVarString()});break}case T:s.push({type:"query-awareness"});break;default:throw new i(`Unknown top-level message type ${o}`)}}return s}function B(e,t,n){if(e===null)return null;if(!w(e))throw new i("Awareness state must be an object or null");if(e.clientId!==t||e.clock!==n)throw new i("Awareness state identity does not match its entry");if(!w(e.user))throw new i("Awareness user must be an object");let r=g(e.user.name,"Awareness user name"),s=E(t,e.user.color);return {clientId:t,clock:n,user:{name:r,color:s},cursor:ee(e.cursor)}}function ee(e){if(e==null)return null;if(!w(e))throw new i("Awareness cursor must be an object or null");let t=g(e.slideId,"Awareness slideId"),n=e.shapeId===void 0?void 0:g(e.shapeId,"Awareness shapeId");return n?{slideId:t,shapeId:n}:{slideId:t}}function F(e){U(e.clientId,"Awareness clientId"),U(e.clock,"Awareness clock"),e.state!==null&&B(e.state,e.clientId,e.clock);}function U(e,t){if(!Number.isSafeInteger(e)||e<0)throw new i(`${t} must be a non-negative safe integer`)}function g(e,t){if(typeof e!="string"||e.length===0||e.length>1024)throw new i(`${t} must be between 1 and ${1024} characters`);return e}function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(e){let t=[];for(let n of e)n.op==="event"&&n.event.type==="message"&&t.push(n.event.data);return t}function Ie(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}var te=new Set(["backpressure","protocol","replica","transport"]);var ne=e=>Number.isSafeInteger(e)&&e>=0;function re(e){let t=e;return typeof t=="object"&&t!==null&&te.has(t.code)&&typeof t.message=="string"}function se(e,t){if(typeof e!="object"||e===null)return false;let n=e;switch(n.type){case "open":return true;case "message":return n.data instanceof ArrayBuffer&&n.data.byteLength<=t;case "close":return n.reason===void 0||typeof n.reason=="string";default:return false}}function Ue(e,t,n){if(typeof e!="object"||e===null)return false;let{provider:r,ops:s}=e;return !Number.isSafeInteger(r)||r<0||!Array.isArray(s)||s.length===0?false:s.every(o=>{if(typeof o!="object"||o===null)return false;let a=o;if(!ne(a.seq))return false;switch(a.op){case "create":return typeof a.options=="object"&&a.options!==null&&Object.keys(a.options).every(c=>n.optionKeys.has(c));case "connect":case "disconnect":case "destroy":return true;case "fail":return re(a.error);case "cursor":return typeof a.broadcast=="boolean"&&(a.cursor===null||n.validCursor(a.cursor,t));case "event":return se(a.event,t);default:return false}})}function Ce(){let e=globalThis.performance;return typeof e?.now!="function"?0:typeof e.timeOrigin=="number"?e.timeOrigin:Date.now()-e.now()}export{p as a,ie as b,Y as c,ae as d,$ as e,ce as f,q as g,_ as h,l as i,b as j,ye as k,he as l,be as m,Ae as n,Ee as o,me as p,M as q,L as r,ge as s,we as t,Pe as u,xe as v,Ie as w,Ue as x,Ce as y};
@@ -0,0 +1 @@
1
+ import {a,d as d$1,h,i,j as j$1,e,g as g$1,n,s,k,o,m,u,t,q,l as l$1,p as p$1,v,y as y$1}from'./chunk-H3SEEI4U.js';var O=new WeakMap;function ee(n,e){O.set(n,e);}function D(n){return O.get(n)}var l=class extends Error{constructor(t,r,s){super(r);a(this,"code");a(this,"cause");this.name="CollaborationError",this.code=t,this.cause=s;}};function G(n){return n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:"Unknown error"}var $=["backpressure","protocol","replica","transport"],g=64,Q=250;function X(n){if(n[0]!==0||n[1]!==2)return false;let e=0;for(let t=2,r=0;t<Math.min(n.byteLength,7);t++,r+=7)if(e+=(n[t]&127)*2**r,n[t]<128)return t+1+e===n.byteLength;return false}var y=class{constructor(e,t,r){a(this,"transport",t);a(this,"options",r);a(this,"endpoint");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"peerListeners",new Map);a(this,"nextListenerId",0);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"peerList",[]);a(this,"seq",0);a(this,"floor",0);a(this,"sendFloor",0);a(this,"inboundBytes",0);a(this,"flushingFrames",false);a(this,"queue",[]);a(this,"posting",false);a(this,"flushQueued",false);a(this,"heldTimer",null);a(this,"urgent",false);a(this,"unsubscribeTransport",null);a(this,"subscription",0);a(this,"wantsConnection",false);a(this,"connectAttempt",0);a(this,"leaveFrame",null);a(this,"pendingFrames",[]);a(this,"queuedBytes",0);a(this,"isDestroyed",false);a(this,"closed",false);this.endpoint=e.open(s=>this.receive(s),s=>this.lose(s)),this.enqueue({op:"create",seq:++this.seq,options:r.worker});}get status(){return this.connectionStatus}get synced(){return this.isSynced}get pendingBytes(){return this.queuedBytes}get peers(){return this.peerList}setCursor(e,t){this.isDestroyed||this.enqueue({op:"cursor",seq:++this.seq,cursor:e,broadcast:t});}onPeers(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.peerListeners.set(t,e),e(this.peers),()=>this.peerListeners.delete(t)}onStatus(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}connect(){if(this.isDestroyed||this.connectionStatus==="connected"||this.connectionStatus==="connecting")return;if(this.closed){this.report(this.options.makeError("replica","Collaboration replica is retired"));return}this.wantsConnection=true,this.floor=++this.seq,this.enqueue({op:"connect",seq:this.floor});let e=++this.connectAttempt;if(this.setStatus("connecting",false),!(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt)){if(!this.unsubscribeTransport){let t=++this.subscription,r;try{if(r=this.transport.onEvent(s=>this.forward(t,s)),typeof r!="function")throw new TypeError("Transport event subscription must return a function")}catch(s){this.subscription+=1,this.fail(this.transportError("Failed to subscribe to transport events",s));return}if(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt||t!==this.subscription){try{r();}catch(s){this.isDestroyed||this.report(this.transportError("Failed to unsubscribe from stale transport events",s));}return}this.unsubscribeTransport=r;}try{let t=this.transport.connect();t&&t.catch(r=>{!this.isDestroyed&&this.wantsConnection&&this.connectAttempt===e&&this.fail(this.transportError("Transport connect failed",r));});}catch(t){this.fail(this.transportError("Transport connect failed",t));}}}disconnect(){if(this.isDestroyed)return;if(this.closed){this.setStatus("disconnected",false);return}if(!(this.wantsConnection||this.unsubscribeTransport!==null||this.connectionStatus!=="disconnected"))return;this.sendLeave(),this.floor=++this.seq,this.enqueue({op:"disconnect",seq:this.floor});let t=this.release(true);this.setStatus("disconnected",false);for(let r of t)this.report(r);}destroy(){if(this.isDestroyed)return;let e=!this.closed&&(this.wantsConnection||this.unsubscribeTransport!==null||this.connectionStatus==="connecting"||this.connectionStatus==="connected");e&&this.sendLeave(),this.floor=++this.seq,this.enqueue({op:"destroy",seq:this.floor});let t=this.closed?[]:this.release(e);this.isDestroyed=true,this.setStatus("destroyed",false);for(let r of t)this.report(r);this.statusListeners.clear(),this.errorListeners.clear(),this.peerListeners.clear();}transportError(e,t){return this.options.normalize("transport",e,t)}release(e){this.wantsConnection=false,this.connectAttempt+=1,this.leaveFrame=null,this.clearQueue(),this.clearPeers();let t=[],r=this.unsubscribeTransport;if(this.unsubscribeTransport=null,this.subscription+=1,r)try{r();}catch(s){t.push(this.transportError("Failed to unsubscribe from transport events",s));}if(!e)return t;try{let s=this.transport.disconnect();s&&s.catch(o=>{this.isDestroyed||this.report(this.transportError("Transport disconnect failed",o));});}catch(s){t.push(this.transportError("Transport disconnect failed",s));}return t}fail(e){if(this.isDestroyed||!this.wantsConnection)return;let t=e.code;this.floor=++this.seq,this.enqueue({op:"fail",seq:this.floor,error:{code:typeof t=="string"&&$.includes(t)?t:"transport",message:e.message}});let r=this.release(true);this.setStatus("disconnected",false),this.report(e);for(let s of r)this.report(s);}sendLeave(){let e=this.leaveFrame;if(this.leaveFrame=null,!(!e||!this.options.hasUser||!this.unsubscribeTransport||this.connectionStatus!=="connected"))try{this.transport.send(e);}catch(t){this.report(this.transportError("Failed to send awareness leave",t));}}enqueue(e,t=false){this.closed||(this.queue.push(e),this.schedule(t));}schedule(e){if(e||(this.urgent=true),!(this.posting||this.flushQueued)){if(e){this.heldTimer??(this.heldTimer=setTimeout(()=>{this.heldTimer=null,this.flush();},Q));return}this.flushQueued=true,queueMicrotask(()=>{this.flushQueued=false,this.flush();});}}flush(){if(this.posting||this.closed||this.queue.length===0)return;this.heldTimer!==null&&(clearTimeout(this.heldTimer),this.heldTimer=null);let e=this.queue;this.queue=[],this.urgent=false,this.posting=true;let t=e.some(o=>o.op==="destroy"),r=e.reduce((o,a)=>a.op==="event"&&a.event.type==="message"?o+a.event.data.byteLength+g:o,0),s;try{s=this.endpoint.post(e,v(e));}catch(o){s=Promise.reject(o);}s.then(()=>{this.posting=false,this.inboundBytes-=r,t?this.close():this.urgent?this.flush():this.queue.length>0&&this.schedule(true);},o=>{this.posting=false,this.inboundBytes-=r,this.lose(G(o));});}forward(e,t){if(!(this.closed||this.isDestroyed||e!==this.subscription))switch(t.type){case "message":if(this.inboundBytes===0?t.data.byteLength>this.options.maxPendingBytes:t.data.byteLength+g>this.options.maxPendingBytes-this.inboundBytes){this.fail(this.options.makeError("backpressure","Pending replica data exceeds the byte limit"));return}this.inboundBytes+=t.data.byteLength+g,this.enqueue({op:"event",seq:++this.seq,event:{type:"message",data:t.data.slice().buffer}},!this.isSynced&&X(t.data)&&this.inboundBytes<=this.options.maxPendingBytes/2);return;case "open":case "close":this.clearQueue(),t.type==="close"&&(this.connectAttempt+=1,this.leaveFrame=null),this.sendFloor=++this.seq,this.enqueue({op:"event",seq:this.sendFloor,event:t.type==="open"?{type:"open"}:{type:"close",...t.reason!==void 0&&{reason:t.reason}}}),t.type==="close"&&(this.clearPeers(),this.setStatus("disconnected",false));return;case "drain":this.flushPending();return;case "error":this.fail(this.transportError("Transport error",t.error));return;default:this.fail(this.options.makeError("transport","Unknown transport event"));}}receive(e){for(let t of e){if(this.closed||this.isDestroyed)return;if(t.do==="lost"){this.lose("Collaboration replica is retired");return}if(!(t.through<this.floor))switch(t.do){case "unsubscribe":{let r=this.release(false);for(let s of r)this.report(s);break}case "disconnect":{this.wantsConnection=false;let r=this.release(true);for(let s of r)this.report(s);break}case "send":t.through>=this.sendFloor&&this.send(new Uint8Array(t.data));break;case "leave":t.through>=this.sendFloor&&(this.leaveFrame=t.data?new Uint8Array(t.data):null);break;case "status":t.through>=this.sendFloor&&this.setStatus(t.status,t.synced);break;case "peers":{if(t.through<this.sendFloor||t.peers.length===0&&this.peerList.length===0)break;let r=this.options.rebasePeer,s=t.timeOrigin-y$1();this.peerList=r?t.peers.map(o=>r(o,s)):t.peers,this.emitPeers();break}case "error":this.report(this.options.makeError(t.error.code,t.error.message));break}}}send(e){if(!this.unsubscribeTransport)return;if(this.pendingFrames.length>0){this.queueFrame(e);return}let t=this.sendFloor,r;try{r=this.transport.send(e.slice());}catch(s){this.fail(this.transportError("Transport send failed",s));return}if(typeof r!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}!r&&this.unsubscribeTransport!==null&&t===this.sendFloor&&this.queueFrame(e);}queueFrame(e){if(e.byteLength>this.options.maxPendingBytes-this.queuedBytes){this.fail(this.options.makeError("backpressure",`Pending collaboration data exceeds ${this.options.maxPendingBytes} bytes`));return}this.pendingFrames.push(e),this.queuedBytes+=e.byteLength;}flushPending(){if(!this.flushingFrames){this.flushingFrames=true;try{for(;this.unsubscribeTransport&&this.pendingFrames.length>0;){let e=this.pendingFrames[0],t;try{t=this.transport.send(e.slice());}catch(r){this.fail(this.transportError("Transport send failed",r));return}if(typeof t!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}if(!t||this.pendingFrames[0]!==e)return;this.pendingFrames.shift(),this.queuedBytes-=e.byteLength;}}finally{this.flushingFrames=false;}}}clearQueue(){this.pendingFrames.length=0,this.queuedBytes=0;}lose(e){if(this.closed||(this.close(),this.isDestroyed))return;this.sendLeave();let t=this.release(this.wantsConnection||this.connectionStatus!=="disconnected");setTimeout(()=>{if(!this.isDestroyed){this.setStatus("disconnected",false),this.report(this.options.makeError("replica",e));for(let r of t)this.report(r);}},0);}close(){this.closed||(this.closed=true,this.queue=[],this.heldTimer!==null&&(clearTimeout(this.heldTimer),this.heldTimer=null),this.endpoint.close());}clearPeers(){this.peerList.length!==0&&(this.peerList=[],this.emitPeers());}setStatus(e,t){if(!(this.connectionStatus===e&&this.isSynced===t)){this.connectionStatus=e,t&&!this.isSynced&&this.queue.length>0&&this.schedule(false),this.isSynced=t;for(let[r,s]of [...this.statusListeners])if(this.statusListeners.get(r)===s)try{s({status:e,synced:t});}catch{}}}emitPeers(){let e=this.peers;for(let[t,r]of [...this.peerListeners])if(this.peerListeners.get(t)===r)try{r(e);}catch{}}report(e){for(let[t,r]of [...this.errorListeners])if(this.errorListeners.get(t)===r)try{r(e);}catch{}}};var j=16*1024*1024,Y=16*1024*1024;function C(n,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${n} must be ${t?"a non-negative":"a positive"} integer`);return e}function J(n){return n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:"Unknown error"}function p(n,e,t){return t instanceof l?t:new l(n,`${e}: ${J(t)}`,t)}function d(n,e){if(!(n instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return n.slice()}function T(n){typeof n=="object"&&n&&"unref"in n&&n.unref();}function K(n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("Replica clientId must be a non-negative safe integer");return n}function Z(n){if(n===null)return null;if(!n||typeof n.slideId!="string"||n.slideId.length===0)throw new TypeError("Presence cursor slideId must be a non-empty string");if(n.shapeId!==void 0&&(typeof n.shapeId!="string"||n.shapeId.length===0))throw new TypeError("Presence cursor shapeId must be a non-empty string");return n.shapeId?{slideId:n.slideId,shapeId:n.shapeId}:{slideId:n.slideId}}var _=new WeakMap,N=new WeakMap;function ue(n){return _.get(n)()}function de(n){return N.get(n)()}var M=class{constructor(e,t,r={}){a(this,"piped");a(this,"openEpoch",0);a(this,"replica");a(this,"transport");a(this,"maxFrameBytes");a(this,"maxMessagesPerFrame");a(this,"maxPendingBytes");a(this,"localClientId");a(this,"localUser");a(this,"remotePresence");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"presenceListeners",new Map);a(this,"pendingFrames",[]);a(this,"unsubscribeReplica");a(this,"unsubscribeTransport",()=>{});a(this,"hasTransportSubscription",false);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"wantsConnection",false);a(this,"isOpen",false);a(this,"isDestroyed",false);a(this,"epoch",0);a(this,"connectAttempt",0);a(this,"nextListenerId",0);a(this,"queuedBytes",0);a(this,"incoming",[]);a(this,"incomingBytes",0);a(this,"incomingBusy",false);a(this,"asyncReplica",false);a(this,"incomingGeneration",0);a(this,"isFlushing",false);a(this,"localClock",0);a(this,"reportedClockExhaustion",false);a(this,"localCursor",null);a(this,"applyingArrival");a(this,"lastAwarenessSentAt",0);a(this,"cursorTimer",null);a(this,"heartbeatTimer",null);a(this,"expiryTimer",null);this.replica=e,"setCollaborative"in e&&e.setCollaborative?.(),this.transport=t,this.localClientId=K(e.clientId),this.localUser=d$1(this.localClientId,r.user),this.remotePresence=new h(this.localClientId),this.maxFrameBytes=C("maxFrameBytes",r.maxFrameBytes??i,false),this.maxMessagesPerFrame=C("maxMessagesPerFrame",r.maxMessagesPerFrame??j$1,false),this.maxPendingBytes=C("maxPendingBytes",r.maxPendingBytes??j,true),_.set(this,()=>this.beginArrival()),N.set(this,()=>this.leaveFrame());let s=D(e);if(s){this.unsubscribeReplica=()=>{},this.piped=new y(s,t,{worker:{maxFrameBytes:this.maxFrameBytes,maxMessagesPerFrame:this.maxMessagesPerFrame,user:{...this.localUser}},maxPendingBytes:this.maxPendingBytes,hasUser:true,makeError:(o,a,c)=>new l(o,a,c),normalize:p});return}try{this.unsubscribeReplica=e.onUpdate((o,a)=>{a==="local"&&this.forwardLocalUpdate(o);});}catch(o){throw p("replica","Failed to observe replica updates",o)}}get status(){return this.piped?this.piped.status:this.connectionStatus}get synced(){return this.piped?this.piped.synced:this.isSynced}get pendingBytes(){return this.piped?this.piped.pendingBytes:this.queuedBytes}get peers(){return this.piped?this.piped.peers:this.remotePresence.peers}setCursor(e$1){if(this.isDestroyed||this.piped?.status==="destroyed")return;let t=Z(e$1),r=!t||e(t)?t:null;if(t&&!r){let s=new l("protocol",`Presence cursor identifiers exceed ${1024} characters; cursor dropped`);this.report(s);}if(!g$1(this.localCursor,r)){if(this.localCursor=r,this.piped)return this.piped.setCursor(r,true);this.isOpen&&this.wantsConnection&&this.scheduleCursorBroadcast();}}connect(){if(this.piped)return this.piped.connect();if(this.isDestroyed||this.isOpen||this.connectionStatus==="connecting")return;this.wantsConnection=true;let e=this.hasTransportSubscription?this.epoch:++this.epoch,t=++this.connectAttempt;if(this.setStatus("connecting",false),!!this.isCurrent(e)){if(!this.hasTransportSubscription){let r;try{if(r=this.transport.onEvent(s=>this.handleTransportEvent(e,s)),typeof r!="function")throw new TypeError("Transport event subscription must return a function")}catch(s){this.failConnection(e,p("transport","Failed to subscribe to transport events",s));return}if(!this.isCurrent(e)){try{r();}catch(s){this.isDestroyed||this.report(p("transport","Failed to unsubscribe from stale transport events",s));}return}this.unsubscribeTransport=r,this.hasTransportSubscription=true;}try{let r=this.transport.connect();r&&r.catch(s=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,p("transport","Transport connect failed",s));});}catch(r){this.failConnection(e,p("transport","Transport connect failed",r));}}}disconnect(){if(this.piped)return this.piped.disconnect();if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;if(this.isOpen&&this.wantsConnection){let s=this.epoch;if(this.broadcastLocalPresence(true),!this.isCurrent(s))return}this.stopPresenceTimers(),this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription();this.clearPending(),this.clearRemotePresence();let r=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let s of r)this.report(s);}destroy(){if(this.piped){this.piped.destroy(),this.isDestroyed=true,this.errorListeners.clear();return}if(this.isDestroyed||(this.isOpen&&this.wantsConnection&&this.broadcastLocalPresence(true),this.isDestroyed))return;let e=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.stopPresenceTimers(),this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription();this.clearPending(),this.clearRemotePresence();let r=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let s of r)this.report(s);try{this.unsubscribeReplica();}catch(s){this.report(p("replica","Failed to unsubscribe from replica updates",s));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear(),this.presenceListeners.clear();}onStatus(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("status listener must be a function");if(this.piped)return this.piped.onStatus(e);let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("error listener must be a function");if(this.piped){let r=this.piped.onError(e),s=this.nextListenerId++;return this.errorListeners.set(s,e),()=>{r(),this.errorListeners.delete(s);}}let t=this.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}onPresence(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("presence listener must be a function");if(this.piped)return this.piped.onPeers(r=>{try{e(r);}catch{}});let t=this.nextListenerId++;this.presenceListeners.set(t,e);try{e(this.peers);}catch{}return ()=>this.presenceListeners.delete(t)}beginArrival(){let e=this.epoch,t=this.openEpoch,r=this.applyingArrival;r&&(r.deferred=true);let s=false,o=a=>{s||(s=true,this.isCurrent(e)&&this.isOpen&&this.openEpoch===t&&a());};return {settle:()=>o(()=>{r?.synced&&this.setStatus("connected",true);}),fail:a=>o(()=>this.failConnection(e,p("replica","Failed to apply remote update",a)))}}leaveFrame(){if(!this.isOpen||this.isDestroyed||!this.wantsConnection||this.localClock>=Number.MAX_SAFE_INTEGER)return null;try{let e=this.localClock+1;return {clock:e,frame:n([{clientId:this.localClientId,clock:e,state:null}],this.maxFrameBytes)}}catch{return null}}isCurrent(e){return !this.isDestroyed&&this.wantsConnection&&e===this.epoch}failConnection(e,t){if(!this.isCurrent(e))return;this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1,this.stopPresenceTimers();let r=this.takeTransportSubscription();this.clearPending(),this.clearRemotePresence();let s=this.cleanupTransport(r,true);this.setStatus("disconnected",false),this.report(t);for(let o of s)this.report(o);}takeTransportSubscription(){let e=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,e}cleanupTransport(e,t){let r=[];try{e();}catch(s){r.push(p("transport","Failed to unsubscribe from transport events",s));}if(!t)return r;try{let s=this.transport.disconnect();s&&s.catch(o=>{this.isDestroyed||this.report(p("transport","Transport disconnect failed",o));});}catch(s){r.push(p("transport","Transport disconnect failed",s));}return r}handleTransportEvent(e,t){if(this.isCurrent(e))switch(t.type){case "open":this.handleOpen(e);break;case "message":this.isOpen&&this.enqueueMessage(e,t.data);break;case "close":this.isOpen=false,this.connectAttempt+=1,this.stopPresenceTimers(),this.clearPending(),this.clearRemotePresence(),this.setStatus("disconnected",false);break;case "error":this.failConnection(e,p("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new l("transport","Unknown transport event"));}}handleOpen(e){if(this.isOpen||(this.isOpen=true,this.openEpoch+=1,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(e)||!this.isOpen))return;let t=this.connectAttempt;this.replicaResult(e,t,()=>this.replica.encodeStateVector(),r=>{try{let s$1=d(r,"encodeStateVector"),o$1=s(s$1);if(this.sendFrame(k(o$1??s$1,this.maxFrameBytes)),!this.isCurrent(e)||!this.isOpen||(o$1||this.sendFullUpdate(e,t),!this.isCurrent(e)||!this.isOpen)||(this.startPresenceTimers(),this.broadcastLocalPresence(!1),!this.isCurrent(e)||!this.isOpen))return;this.sendFrame(o(this.maxFrameBytes));}catch(s){this.failConnection(e,p("protocol","Failed to encode handshake",s));}});}sendFullUpdate(e,t){this.replicaResult(e,t,()=>this.replica.encodeStateAsUpdate(),r=>{try{this.sendFrame(m(d(r,"encodeStateAsUpdate"),this.maxFrameBytes));}catch(s){this.failConnection(e,p("protocol","Failed to encode handshake",s));}});}replicaResult(e,t,r,s){let o=c=>{this.isCurrent(e)&&this.isOpen&&this.connectAttempt===t&&s(c);},a=c=>{this.isCurrent(e)&&this.isOpen&&this.connectAttempt===t&&this.failConnection(e,p("replica","Collaboration replica operation failed",c));};try{let c=r();if(c instanceof Promise)return this.asyncReplica=!0,c.then(o,a).catch(a);o(c);}catch(c){a(c);}}handleMessage(e,t){let r;try{r=u(t.slice(),this.maxFrameBytes,this.maxMessagesPerFrame);}catch(a){this.failConnection(e,p("protocol","Invalid collaboration frame",a));return}let s=this.connectAttempt,o=a=>{for(;a<r.length;a++){if(!this.isCurrent(e)||!this.isOpen||this.connectAttempt!==s)return;let c=r[a],h;switch(c.type){case "sync-step-1":h=this.answerSyncStep1(e,s,c.stateVector);break;case "sync-step-2":case "update":{let u={deferred:false,synced:c.type==="sync-step-2"};h=this.replicaResult(e,s,()=>{let V=this.applyingArrival;this.applyingArrival=u;try{return this.replica.applyUpdate(q(c.update).slice())}finally{this.applyingArrival=V;}},()=>{u.synced&&!u.deferred&&this.setStatus("connected",true);});break}case "awareness":try{let u=p$1(c.update,this.maxMessagesPerFrame);this.remotePresence.apply(u,Date.now())&&this.emitPresence(),this.schedulePresenceExpiry();}catch(u){this.report(p("protocol","Invalid awareness update",u));}break;case "auth":this.failConnection(e,new l("protocol",c.reason?`Authentication denied: ${c.reason}`:"Authentication denied"));return;case "query-awareness":this.broadcastLocalPresence(false);break}if(h instanceof Promise)return h.then(()=>o(a+1))}};return o(0)}answerSyncStep1(e,t$1,r){let s=t(r),o=this.replicaResult(e,t$1,()=>this.replica.encodeStateAsUpdate(q(s.stateVector).slice()),c=>{try{this.sendFrame(l$1(d(c,"encodeStateAsUpdate"),this.maxFrameBytes));}catch(h){this.failConnection(e,p("protocol","Failed to encode SyncStep2",h));}});if(!s.open)return o;let a=()=>{if(!(!this.isCurrent(e)||!this.isOpen||this.connectAttempt!==t$1))return this.replicaResult(e,t$1,()=>this.replica.encodeStateVector(),c=>{try{this.sendFrame(k(d(c,"encodeStateVector"),this.maxFrameBytes));}catch(h){this.failConnection(e,p("protocol","Failed to encode handshake",h));}})};return o instanceof Promise?o.then(a):a()}enqueueMessage(e,t){if(this.asyncReplica&&this.incomingBytes+t.byteLength>this.maxPendingBytes){this.failConnection(e,new l("backpressure","Incoming collaboration queue is full"));return}this.incoming.push({token:e,data:t.slice()}),this.incomingBytes+=t.byteLength,this.drainIncoming();}drainIncoming(){if(this.incomingBusy)return;let e=this.incomingGeneration;for(;this.incoming.length;){let t=this.takeUpdateBatch(),r=t?.items??[this.incoming.shift()],s=r.reduce((a,c)=>a+c.data.byteLength,0);this.incomingBusy=true;let o=t?this.applyUpdateBatch(r[0].token,t.updates):this.handleMessage(r[0].token,r[0].data);if(e!==this.incomingGeneration)return;if(o instanceof Promise){o.finally(()=>{e===this.incomingGeneration&&(this.incomingBusy=false,this.incomingBytes-=s,this.drainIncoming());}).catch(()=>{});return}this.incomingBusy=false,this.incomingBytes-=s;}}takeUpdateBatch(){if(!this.asyncReplica||typeof this.replica.applyUpdateChunks!="function")return null;let e=[],t=[],r=Math.min(this.maxFrameBytes,Y),s=0;for(let o of this.incoming){if(o.token!==this.incoming[0].token)break;let a=this.remoteUpdates(o.data),c=a?.reduce((h,u)=>h+u.byteLength,0)??0;if(!a?.length||e.length&&s+c>r)break;e.push(o),t.push(...a),s+=c;}return e.length<2?null:(this.incoming.splice(0,e.length),{items:e,updates:t})}remoteUpdates(e){try{let t=u(e.slice(),this.maxFrameBytes,this.maxMessagesPerFrame);return t.every(r=>r.type==="update")?t.map(r=>q(r.update).slice()):null}catch{return null}}applyUpdateBatch(e,t){if(!this.isCurrent(e)||!this.isOpen)return;let r=this.replica;return this.replicaResult(e,this.connectAttempt,()=>r.applyUpdateChunks(t),()=>{})}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,r;try{r=d(e,"Replica update");}catch(s){this.failConnection(t,p("replica","Invalid replica update",s));return}try{this.sendFrame(m(r,this.maxFrameBytes));}catch(s){this.failConnection(t,p("protocol","Failed to encode update",s));}}scheduleCursorBroadcast(){if(this.cursorTimer)return;let e=Math.max(0,80-(Date.now()-this.lastAwarenessSentAt));if(e===0){this.broadcastLocalPresence(false);return}this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.broadcastLocalPresence(false);},e),T(this.cursorTimer);}broadcastLocalPresence(e){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;if(this.localClock>=Number.MAX_SAFE_INTEGER){this.reportedClockExhaustion||(this.reportedClockExhaustion=true,this.report(new l("protocol","Awareness clock exceeds Number.MAX_SAFE_INTEGER")));return}this.localClock+=1;let t=this.localClock,r=e?null:{clientId:this.localClientId,clock:t,user:{...this.localUser},cursor:this.localCursor?{...this.localCursor}:null};this.cursorTimer&&clearTimeout(this.cursorTimer),this.cursorTimer=null,this.lastAwarenessSentAt=Date.now();try{let s=n([{clientId:this.localClientId,clock:t,state:r}],this.maxFrameBytes);e?this.sendLeaveFrameBestEffort(s):this.sendFrame(s);}catch(s){this.report(p("protocol","Failed to encode awareness update",s));}}sendLeaveFrameBestEffort(e){try{this.transport.send(e.slice());}catch{}}startPresenceTimers(){this.stopPresenceTimers(),this.heartbeatTimer=setInterval(()=>{this.broadcastLocalPresence(false);},2e4),T(this.heartbeatTimer),this.schedulePresenceExpiry();}stopPresenceTimers(){this.cursorTimer&&clearTimeout(this.cursorTimer),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.expiryTimer&&clearTimeout(this.expiryTimer),this.cursorTimer=null,this.heartbeatTimer=null,this.expiryTimer=null;}schedulePresenceExpiry(){if(this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null,!this.isOpen||this.isDestroyed)return;let e=this.remotePresence.nextExpiryAt;e!==void 0&&(this.expiryTimer=setTimeout(()=>{this.expiryTimer=null,this.remotePresence.expire(Date.now())&&this.emitPresence(),this.schedulePresenceExpiry();},Math.max(0,e-Date.now())),T(this.expiryTimer));}clearRemotePresence(){this.remotePresence.clear()&&this.emitPresence();}emitPresence(){let e=this.peers;for(let[t,r]of [...this.presenceListeners])if(this.presenceListeners.get(t)===r)try{r(e);}catch{}}sendFrame(e){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;let t=this.epoch;if(this.pendingFrames.length>0){this.queueFrame(t,e);return}let r;try{r=this.transport.send(e.slice());}catch(s){this.failConnection(t,p("transport","Transport send failed",s));return}if(typeof r!="boolean"){this.failConnection(t,new l("transport","Transport send must return a boolean"));return}!r&&this.isCurrent(t)&&this.isOpen&&this.queueFrame(t,e);}queueFrame(e,t){if(t.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(e,new l("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let r=t.slice();this.pendingFrames.push(r),this.queuedBytes+=r.byteLength;}flushPending(){if(!this.isFlushing){this.isFlushing=true;try{for(;this.isOpen&&!this.isDestroyed&&this.pendingFrames.length>0;){let e=this.epoch,t=this.pendingFrames[0],r;try{r=this.transport.send(t.slice());}catch(s){this.failConnection(e,p("transport","Transport send failed",s));return}if(typeof r!="boolean"){this.failConnection(e,new l("transport","Transport send must return a boolean"));return}if(!r||!this.isOpen||this.pendingFrames[0]!==t)return;this.pendingFrames.shift(),this.queuedBytes-=t.byteLength;}}finally{this.isFlushing=false;}}}clearPending(){this.incoming.length=0,this.incomingBytes=0,this.incomingBusy=false,this.incomingGeneration+=1,this.pendingFrames.length=0,this.queuedBytes=0;}setStatus(e,t){if(this.connectionStatus===e&&this.isSynced===t)return;this.connectionStatus=e,this.isSynced=t;let r={status:e,synced:t};for(let[s,o]of [...this.statusListeners])if(this.statusListeners.get(s)===o)try{o(r);}catch{}}report(e){for(let[t,r]of [...this.errorListeners])if(this.errorListeners.get(t)===r)try{r(e);}catch{}}};export{ee as a,D as b,l as c,ue as d,de as e,M as f};