@betteroffice/pptx 0.2.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +112 -263
- package/dist/chunk-2CPM3HRW.js +1 -0
- package/dist/chunk-3TTZUGDD.js +1 -0
- package/dist/chunk-B6OFSXHM.js +1 -0
- package/dist/chunk-DDNX2Z7E.js +1 -0
- package/dist/chunk-JZOLK2OC.js +1 -0
- package/dist/chunk-NWXUJY6L.js +3 -0
- package/dist/chunk-O2XFH626.js +1 -0
- package/dist/chunk-YMIVEAXD.js +0 -0
- package/dist/collaboration.d.ts +11 -0
- package/dist/collaboration.js +1 -0
- package/dist/editorSession-Cl_EWgAi.d.ts +1751 -0
- package/dist/generated/pptx_wasm_bg.wasm +0 -0
- package/dist/index.d.ts +9 -1552
- package/dist/index.js +1 -1
- package/dist/main-C6-cc0fR.d.ts +146 -0
- package/dist/pptxSessionWorker.d.ts +2 -0
- package/dist/pptxSessionWorker.mjs +9 -0
- package/dist/presence-C1o8TDwu.d.ts +95 -0
- package/dist/types-ui_ARP0o.d.ts +93 -0
- package/dist/worker.d.ts +621 -0
- package/dist/worker.js +1 -0
- package/package.json +17 -3
package/README.md
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
# @betteroffice/pptx
|
|
2
2
|
|
|
3
|
-
Framework-free
|
|
4
|
-
|
|
5
|
-
|
|
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
|
-
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
No peer dependencies.
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
14
15
|
|
|
15
|
-
|
|
16
|
+
Render the first slide of a presentation onto a browser canvas:
|
|
16
17
|
|
|
17
18
|
```ts
|
|
18
19
|
import {
|
|
@@ -22,281 +23,129 @@ import {
|
|
|
22
23
|
sizeCanvasForSlide,
|
|
23
24
|
} from '@betteroffice/pptx';
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
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
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
replays the resulting primitives on canvas. Font bytes are supplied by the host
|
|
41
|
-
and registered with the Rust shaper through `openPresentation`.
|
|
42
|
-
|
|
43
|
-
Beyond rendering, `PresentationHandle` covers editing: version-checked batches
|
|
44
|
-
(`readContent` / `findText` / `validateEdits` / `applyEdits`), read-only
|
|
45
|
-
structured export (`exportStructured` / `exportMarkdown`), text
|
|
46
|
-
(`insertText` / `deleteText` / `formatText` / `setParagraphAlignment`), slides
|
|
47
|
-
(`insertSlide` / `deleteSlide` / `moveSlide`), shapes
|
|
48
|
-
(`addTextBox` / `addShape` / `addPicture` / `moveShape` / `resizeShape` /
|
|
49
|
-
`setShapeRect`), paint order (`bringShapeToFront` / `sendShapeToBack` /
|
|
50
|
-
`bringShapeForward` / `sendShapeBackward`), comments
|
|
51
|
-
(`addComment` / `replyToComment` / `setCommentStatus` / `removeComment`),
|
|
52
|
-
`hitTest`, undo/redo, and `save()`, which serializes the deck back to `.pptx`
|
|
53
|
-
bytes with edits applied — untouched slides keep their exact source part bytes.
|
|
54
|
-
`addPicture` accepts common raster/vector MIME types (PNG, JPEG, GIF, BMP,
|
|
55
|
-
TIFF, WebP, SVG) up to 8 MiB, rejecting anything past either limit before it
|
|
56
|
-
reaches the deck.
|
|
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.
|
|
57
52
|
|
|
58
|
-
##
|
|
53
|
+
## Entry points
|
|
59
54
|
|
|
60
|
-
|
|
55
|
+
All entry points below are exported from `@betteroffice/pptx`.
|
|
61
56
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const preview = deck.previewProposal(proposal.id);
|
|
75
|
-
const proposedSlide = deck.layoutProposalSlide(proposal.id, 0);
|
|
76
|
-
const diff = deck.layoutProposalDiffSlide(proposal.id, 0);
|
|
77
|
-
await paintSlide(canvas.getContext('2d')!, diff.frame, devicePixelRatio, 1, {
|
|
78
|
-
textChanges: diff.textChanges,
|
|
79
|
-
});
|
|
80
|
-
deck.acceptProposal(proposal.id);
|
|
81
|
-
deck.undo();
|
|
82
|
-
```
|
|
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. |
|
|
83
68
|
|
|
84
|
-
`
|
|
85
|
-
|
|
86
|
-
against the current deck without changing it. `rejectProposal(id)` removes a
|
|
87
|
-
pending group. Acceptance applies the whole group in one undo step and emits
|
|
88
|
-
one local update; an invalid edit prevents the entire group from being staged
|
|
89
|
-
or accepted.
|
|
90
|
-
|
|
91
|
-
`layoutProposalDiffSlide()` lays removed and inserted text out together, keeping
|
|
92
|
-
unchanged words as context and retaining fonts and emphasis. Pass its
|
|
93
|
-
`textChanges` to `paintSlide()` for red highlights and strikethrough on deletions,
|
|
94
|
-
and green highlights and underlines on insertions. Its snapshot and UTF-16
|
|
95
|
-
ranges describe a temporary review layout; use the live handle for editing and
|
|
96
|
-
the ordinary proposed layout for the result after acceptance.
|
|
97
|
-
|
|
98
|
-
Supported edits replace text within one paragraph, format text, align paragraphs,
|
|
99
|
-
set shape geometry/fill/stroke/adjustments, and replace speaker notes. Text offsets
|
|
100
|
-
use UTF-16 and shape coordinates use EMU. Text replacement inherits the style at
|
|
101
|
-
its start unless `style` is supplied. Edits run in order, so later text offsets
|
|
102
|
-
refer to the result of earlier edits in the group.
|
|
103
|
-
|
|
104
|
-
Changing a targeted shape or its notes makes acceptance throw `StaleProposalError`
|
|
105
|
-
with target IDs. Review a fresh preview before calling
|
|
106
|
-
`acceptProposal(id, { force: true })`; force still validates targets and ranges.
|
|
107
|
-
Unrelated peer edits survive acceptance and Undo. Up to 64 proposals, each with
|
|
108
|
-
1–256 edits, may be pending.
|
|
109
|
-
|
|
110
|
-
Pending proposals live in the open session; accepted edits save and synchronize.
|
|
111
|
-
`isProposalsAvailable()` supports hosts that load an older WASM build.
|
|
69
|
+
`openPresentationSession(bytes, options?)` from `@betteroffice/pptx/worker` opens an experimental asynchronous
|
|
70
|
+
worker session.
|
|
112
71
|
|
|
113
|
-
|
|
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.
|
|
114
75
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
or the batch returns a typed refusal and nothing changes.
|
|
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.
|
|
118
78
|
|
|
119
|
-
|
|
120
|
-
const read = deck.readContent();
|
|
121
|
-
if (!read.ok) throw new Error(read.failure.message);
|
|
122
|
-
const story = read.stories[0];
|
|
123
|
-
const within = { slideId: story.slideId, shapeId: story.shapeId, storyId: story.storyId };
|
|
124
|
-
|
|
125
|
-
const result = deck.applyEdits({
|
|
126
|
-
expectVersion: read.version,
|
|
127
|
-
steps: [
|
|
128
|
-
{ op: 'replaceText', target: { kind: 'search', within, text: 'Q3' }, text: 'Q4' },
|
|
129
|
-
{ op: 'setSlideNotes', target: { slideId: story.slideId }, text: 'Updated for Q4' },
|
|
130
|
-
],
|
|
131
|
-
});
|
|
132
|
-
if (!result.ok) console.warn(result.failure.code, result.failure.stepIndex);
|
|
133
|
-
```
|
|
79
|
+
## Layout and rendering
|
|
134
80
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
must match exactly once in its story, overlapping occurrences included. Every
|
|
140
|
-
target and guard resolves against `expectVersion`, so a later step never sees
|
|
141
|
-
an earlier step's offsets.
|
|
142
|
-
|
|
143
|
-
Steps insert, replace and delete text within one paragraph, format text, align
|
|
144
|
-
paragraphs, replace speaker notes, and set the rectangle, fill or outline of a
|
|
145
|
-
shape at the top of a slide (fill and outline on preset shapes). An `expect`
|
|
146
|
-
guard refuses its step unless the target still reads as expected. Receipts
|
|
147
|
-
locate each change in the final state. `validateEdits()` runs every check,
|
|
148
|
-
staging included, without changing anything. `history: 'none'` keeps a batch
|
|
149
|
-
out of undo history and existing undo and redo entries in place;
|
|
150
|
-
`source: 'agent'` records provenance only.
|
|
151
|
-
|
|
152
|
-
Refusals carry a `code` (`stale-version`, `missing-target`, `ambiguous-target`,
|
|
153
|
-
`content-mismatch`, `overlapping-steps`, `unsupported`, `invalid-step`,
|
|
154
|
-
`limit-exceeded`), the failing `stepIndex` and the target; malformed requests
|
|
155
|
-
throw, and so do NaN or infinite numbers. Slide, shape, story and paragraph
|
|
156
|
-
ids and versions are session-scoped.
|
|
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.
|
|
157
85
|
|
|
158
|
-
|
|
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`.
|
|
159
89
|
|
|
160
|
-
|
|
161
|
-
read at, and `exportMarkdown()` renders that same read as Markdown. Neither
|
|
162
|
-
flushes editor input or changes anything. `exportPptxStructured(bytes)`,
|
|
163
|
-
`exportPptxMarkdown(bytes)` and `renderPptxMarkdown(content)` do the same
|
|
164
|
-
headless, with anchors that address the returned snapshot only.
|
|
90
|
+
## Saving and ownership
|
|
165
91
|
|
|
166
|
-
|
|
167
|
-
|
|
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.
|
|
168
95
|
|
|
169
|
-
|
|
170
|
-
if (!read.ok) throw new Error(read.failure.message);
|
|
171
|
-
console.log(read.content.slides);
|
|
172
|
-
const { markdown, anchors } = await exportPptxMarkdown(bytes);
|
|
173
|
-
```
|
|
96
|
+
## Agent proposals
|
|
174
97
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
geometry. Paragraphs carry their level, effective alignment, authored
|
|
179
|
-
`bulletJson` and the resolved list marker (inherited from the layout, master
|
|
180
|
-
and text styles and numbered as the renderer numbers them); runs carry
|
|
181
|
-
formatting marks, links, soft line breaks, fields with their cached result and
|
|
182
|
-
zero-width placeholders for inline content such as equations. Tables keep their
|
|
183
|
-
grid, spans and merge continuations with each cell's current story. Pictures,
|
|
184
|
-
video, audio, charts, SmartArt, embedded objects and unmodelled shape-tree
|
|
185
|
-
elements become placeholders with their alternative text and relationships.
|
|
186
|
-
Each slide exports its own shapes, with an `inherited-content-omitted`
|
|
187
|
-
diagnostic for layout and master shapes drawn on it.
|
|
188
|
-
|
|
189
|
-
Every record carries an anchor: `range` anchors are batch text targets in the
|
|
190
|
-
story offsets of `readContent()`, so a session export's `range` anchor can be a
|
|
191
|
-
step's `target` at the version it was read at; `notes` and `comment` ranges
|
|
192
|
-
index their plain text, and records seeded from the file carry `provenance`
|
|
193
|
-
(part, SHA-256, element path, `sldId`, `cNvPr` id). Session anchors belong to
|
|
194
|
-
the returned version. A collaboration
|
|
195
|
-
session opened from an update seeded by an older release, without its source
|
|
196
|
-
file, may not know which slides are hidden:
|
|
197
|
-
those slides are exported with `hidden: null` and a `visibility-unknown`
|
|
198
|
-
diagnostic, and reopening the session with its source file restores their
|
|
199
|
-
visibility. Hidden slides and shapes, speaker notes (plain text)
|
|
200
|
-
and comments are excluded unless `includeHiddenSlides`, `includeHiddenShapes`,
|
|
201
|
-
`includeNotes` or `includeComments` asks for them, and `includeFormatting:
|
|
202
|
-
false` drops marks. Everything left out or not represented is listed in
|
|
203
|
-
`diagnostics`. `maxBlocks` (10,000 by default; slides, shapes, paragraphs,
|
|
204
|
-
notes and comments count) and `maxBytes` (8 MiB of compact JSON) stop the
|
|
205
|
-
export at a whole record and set `truncated`. Unusable limits come back as an
|
|
206
|
-
`invalid-options` or `limit-exceeded` refusal (`PptxExportError` for the
|
|
207
|
-
headless functions); malformed options throw.
|
|
208
|
-
|
|
209
|
-
Markdown renders slide headings, title placeholders as headings, paragraphs
|
|
210
|
-
with literal list markers, pipe or entity-escaped HTML tables, object
|
|
211
|
-
placeholders, notes and comments, with a `<!-- pptx-export:N -->` marker before
|
|
212
|
-
each block that `anchors` maps back to its source.
|
|
213
|
-
|
|
214
|
-
## Comments
|
|
215
|
-
|
|
216
|
-
PowerPoint has two comment systems and a file only ever uses one: `legacy`
|
|
217
|
-
reads in every version of PowerPoint plus LibreOffice and Google Slides, while
|
|
218
|
-
`modern` carries replies and resolution for PowerPoint 365.
|
|
219
|
-
A deck commits to one at its first comment, so `setCommentFlavor` only works
|
|
220
|
-
while `comments()` is empty, and `replyToComment` / `setCommentStatus` throw on
|
|
221
|
-
a legacy deck.
|
|
222
|
-
|
|
223
|
-
Saving patches existing comment XML, preserving identities, formatting, task
|
|
224
|
-
metadata, anchors and unknown fields. Unedited parts remain byte-identical.
|
|
225
|
-
Removing a thread removes its known replies; a concurrent reply survives as a
|
|
226
|
-
new root if its parent was deleted.
|
|
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.
|
|
227
101
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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 })`.
|
|
106
|
+
|
|
107
|
+
## Version-checked edit batches
|
|
108
|
+
|
|
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
|
|
114
|
+
|
|
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.
|
|
238
118
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
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.
|
|
242
130
|
|
|
243
131
|
## Collaboration
|
|
244
132
|
|
|
245
|
-
`PresentationHandle`
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
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.
|
|
250
137
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
if (origin === 'remote') repaint();
|
|
259
|
-
});
|
|
260
|
-
provider.connect();
|
|
261
|
-
```
|
|
138
|
+
## Operation profiles
|
|
139
|
+
|
|
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.
|
|
143
|
+
|
|
144
|
+
## Documentation
|
|
262
145
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
[JavaScript guide](https://docs.betteroffice.dev/docs/javascript) ·
|
|
271
|
-
[Changelog](https://github.com/openooxml/betteroffice/blob/main/packages/pptx/CHANGELOG.md) · Apache-2.0.
|
|
272
|
-
|
|
273
|
-
### Operation profiles
|
|
274
|
-
|
|
275
|
-
`layoutSlideProfiled` returns `{ layout, profile }` with scope, layout, and
|
|
276
|
-
serialization durations in milliseconds. Profiled mutation methods such as
|
|
277
|
-
`insertTextProfiled` and `addTextBoxProfiled` return `{ receipt, profile }`;
|
|
278
|
-
`undoProfiled` reports undo, snapshot, and serialization timings. These methods
|
|
279
|
-
share the normal operations and add stage timing. See the
|
|
280
|
-
[corpus and browser tests](../../e2e/README.md) for usage and timing limits.
|
|
281
|
-
|
|
282
|
-
## Host undo and comment controls
|
|
283
|
-
|
|
284
|
-
`handle.setUndoCaptureMode('manual')` groups tracked local edits across pauses
|
|
285
|
-
and operation types until `handle.addUndoBoundary()`. The getter
|
|
286
|
-
`handle.undoCaptureMode()` returns `'auto'` or `'manual'`. Changing modes closes
|
|
287
|
-
the current group and preserves history; setting the same mode is a no-op.
|
|
288
|
-
Auto preserves the existing policy (500 ms capture on native targets, separate
|
|
289
|
-
transactions in the browser). Remote and agent origins remain outside local
|
|
290
|
-
undo. These controls group history; edit batches make edits atomic.
|
|
291
|
-
|
|
292
|
-
`handle.anchorCaret(storyId, index)` returns a caret anchor, plain data that
|
|
293
|
-
later edits, undo, redo and remote updates carry along with the text;
|
|
294
|
-
`handle.resolveCaretAnchor(anchor)` returns its current UTF-16 offset, or `null`
|
|
295
|
-
once the story is gone.
|
|
296
|
-
|
|
297
|
-
`handle.setCommentPosition(commentId, { xEmu, yEmu })` moves an existing root
|
|
298
|
-
comment on its current slide, preserving identity, author, text, replies, and
|
|
299
|
-
resolution state through collaboration, undo/redo, and export. Coordinates must
|
|
300
|
-
be safe integers in EMU. Replies share their root's position. Unknown IDs,
|
|
301
|
-
reply IDs, and invalid coordinates fail before mutation. Legacy PowerPoint
|
|
302
|
-
comments quantize exported positions to master units (1/576 inch).
|
|
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 @@
|
|
|
1
|
+
import {a}from'./chunk-O2XFH626.js';var re=3e3;var S=["#B3261E","#7B1FA2","#3949AB","#00796B","#2E7D32","#A84400","#C2185B","#00695C"],X=/^#[0-9a-fA-F]+$/;function G(e){return S[Math.abs(e)%S.length]}function E(e,t){return typeof t=="string"&&(t.length===4||t.length===7)&&X.test(t)?t:G(e)}function se(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 D(e){return e.slideId.length<=1024&&(e.shapeId===void 0||e.shapeId.length<=1024)}function oe(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)&&D(n)&&new TextEncoder().encode(n.slideId+(n.shapeId??"")).byteLength<=t}function Y(e,t){return e?.slideId===t?.slideId&&e?.shapeId===t?.shapeId}var _=class{constructor(t,n={}){a(this,"localClientId",t);a(this,"states",new Map);a(this,"clocks",new Map);a(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($)}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&&Y(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 $(e){return {state:x(e.state),lastSeen:e.lastSeen,cursorMovedAt:e.cursorMovedAt}}var l=16777216,b=4096,C=0,N=1,j=2,T=3,R=0,k=1,O=2,H=0,K=Number.MAX_SAFE_INTEGER,W=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){a(this,"bytes",t);a(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((K-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 z(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 pe(e,t=l){return P(R,e,t)}function fe(e,t=l){return P(k,e,t)}function le(e,t=l){return P(O,e,t)}function ye(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),z(o));}let r=f(n,t);return f([u(N),u(r.byteLength),r],t)}function he(e=l){return f([u(T)],e)}function be(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),J=65536;function V(e){let t=0,n=()=>{let a=0n;for(let c=0;c<W&&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 Ae(e){let t=M(e),n=V(t);if(!n)return e;let{header:r,entries:s}=n;if(!(s.length>=J||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 Ee(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 me(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 j:{let a=r.readVarUint();if(a!==H)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:Q(e.cursor)}}function Q(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 Pe(e){let t=[];for(let n of e)n.op==="event"&&n.event.type==="message"&&t.push(n.event.data);return t}function Se(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}var Z=new Set(["backpressure","protocol","replica","transport"]);var ee=e=>Number.isSafeInteger(e)&&e>=0;function te(e){let t=e;return typeof t=="object"&&t!==null&&Z.has(t.code)&&typeof t.message=="string"}function ne(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 _e(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(!ee(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 te(a.error);case "cursor":return typeof a.broadcast=="boolean"&&(a.cursor===null||n.validCursor(a.cursor,t));case "event":return ne(a.event,t);default:return false}})}function xe(){let e=globalThis.performance;return typeof e?.now!="function"?0:typeof e.timeOrigin=="number"?e.timeOrigin:Date.now()-e.now()}export{re as a,G as b,se as c,D as d,oe as e,Y as f,_ as g,l as h,b as i,pe as j,fe as k,le as l,ye as m,he as n,be as o,M as p,L as q,Ae as r,Ee as s,me as t,Pe as u,Se as v,_e as w,xe as x};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import'./chunk-O2XFH626.js';function R(t,c,p,g){for(let i of C(c)){let h=i.width===void 0||g!==0?0:t.measureText(i.fitText??i.text)?.width,a=h&&h>0?(i.width??0)/h:1;(Math.abs(a-1)<.001||a<.75||a>1.33)&&(a=1),a===1?t.fillText(i.text,i.x,p):(t.save(),t.translate(i.x,p),t.scale(a,1),t.fillText(i.text,0,0),t.restore());}}function C(t){if(t.glyphs.length===0)return [{text:t.text,x:t.x}];let c=t.glyphs.find(e=>e.cluster!==t.glyphs[0].cluster);if(c&&c.x<t.glyphs[0].x){let e=t.text.split(" "),s=[],n=-1;for(let f of e)n+=f.length+1,s.push(n);let u=e.map(()=>1/0);for(let f of t.glyphs){let l=f.cluster-t.start,o=0,r=s.length-1;for(;o<r;){let d=o+r>>1;s[d]<l?o=d+1:r=d;}l>=0&&l<s[o]&&(u[o]=Math.min(u[o],f.x));}return e.flatMap((f,l)=>f.length>0&&u[l]<1/0?[{text:f,x:u[l]}]:[])}let p=[],g=e=>/^[\p{M}\u200c\u200d]/u.test(t.text.slice(e))||t.text[e-1]==="\u200D",i=(e,s)=>/\s/u.test(t.text[e-1])||w(t.text.codePointAt(e))||w(P(t.text,e))||s&&/\s/u.test(t.text[e]),h=e=>{let s=t.glyphs[e-1],n=s?Math.fround(Math.fround(s.x)+Math.fround(s.advance)):t.x;return Math.abs(t.glyphs[e].x-n)>1e-4},y=!(!t.letterSpacingPx&&t.glyphs.some((e,s)=>{let n=e.cluster-t.start;return n>0&&n<t.text.length&&h(s)&&!g(n)&&!i(n,true)}))&&!M.test(t.text)&&t.glyphs.every((e,s)=>s===0||e.cluster>=t.glyphs[s-1].cluster),b=0,x=y&&t.glyphs[0].cluster===t.start?t.glyphs[0].x:t.x,k=0,v=(e,s,n)=>{let u=t.text.slice(b,e),f={text:u,x};if(y&&!u.includes(" ")){let l=u.trimEnd(),o=n-x,r=0,d=x;for(let T=k;T<s;T++){let m=t.glyphs[T];if(m.cluster-t.start>=b+l.length){o=m.x-x,f.fitText=l;break}r+=m.advance,d=Math.max(d,m.x);}f.width=Number.isFinite(o)&&o>0&&o>=d-x?o:r;}p.push(f);};for(let[e,s]of t.glyphs.entries()){let n=s.cluster-t.start;n>b&&n<t.text.length&&(y?!g(n)&&i(n,h(e)):h(e))&&(v(n,e,s.x),b=n,k=e,x=s.x);}return v(t.text.length,t.glyphs.length,t.x+t.width),p}var M=/[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc]/u;function P(t,c){return t.codePointAt(c-(/[\ud800-\udbff][\udc00-\udfff]$/.test(t.slice(0,c))?2:1))}function w(t){return /[\u3000-\u3098\u309b-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef\u{20000}-\u{2ffff}]/u.test(String.fromCodePoint(t??0))}export{R as paintTextChunks};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a,L,N,J,O,b,W,F,E,R,B,s,g,h,i,Y,Q,C,D,S,U,m,V as V$1,e}from'./chunk-DDNX2Z7E.js';function fe(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<10)return;let r=0,i=0;if(t.length>=24&&e.getUint32(0)===2303741511&&e.getUint32(4)===218765834&&e.getUint32(12)===1229472850)r=e.getUint32(16),i=e.getUint32(20);else if(e.getUint32(0)===1195984440&&[55,57].includes(t[4])&&t[5]===97)r=e.getUint16(6,true),i=e.getUint16(8,true);else if(t.length>=26&&e.getUint16(0,true)===19778)e.getUint32(14,true)===12?(r=e.getUint16(18,true),i=e.getUint16(20,true)):(r=e.getInt32(18,true),i=Math.abs(e.getInt32(22,true)));else if(t.length>=20&&e.getUint32(0)===1380533830&&e.getUint32(8)===1464156752){let s=e.getUint32(12);if(s===1448097880&&t.length>=30)r=1+t[24]+(t[25]<<8)+(t[26]<<16),i=1+t[27]+(t[28]<<8)+(t[29]<<16);else if(s===1448097868&&t.length>=25&&t[20]===47){let n=e.getUint32(21,true);r=1+(n&16383),i=1+(n>>>14&16383);}else s===1448097824&&t.length>=30&&t[23]===157&&t[24]===1&&t[25]===42&&(r=e.getUint16(26,true)&16383,i=e.getUint16(28,true)&16383);}else if(e.getUint16(0)===65496){let s=false;for(let n=2;n+4<=t.length;){if(t[n++]!==255)return;for(;t[n]===255;)n+=1;let o=t[n++];if(o===217||o===218)break;if(o===1||o>=208&&o<=216)continue;if(n+2>t.length)return;let l=e.getUint16(n);if(l<2||n+l>t.length)return;o===225&&(s=s||Se(t.subarray(n+2,n+l))),o>=192&&o<=207&&![196,200,204].includes(o)&&l>=7&&(i=e.getUint16(n+3),r=e.getUint16(n+5)),n+=l;}s&&([r,i]=[i,r]);}return r>0&&i>0?{width:r,height:i}:void 0}function Se(t){if(t.length<14||![69,120,105,102,0,0].every((n,o)=>t[o]===n))return false;let e=new DataView(t.buffer,t.byteOffset+6,t.byteLength-6),r=e.getUint16(0)===18761;if(!r&&e.getUint16(0)!==19789||e.getUint16(2,r)!==42)return false;let i=e.getUint32(4,r);if(i>e.byteLength-2)return false;let s=e.getUint16(i,r);for(let n=0;n<s;n+=1){let o=i+2+n*12;if(o>e.byteLength-12)return false;if(e.getUint16(o,r)===274&&e.getUint16(o+2,r)===3&&e.getUint32(o+4,r)===1)return [5,6,7,8].includes(e.getUint16(o+8,r))}return false}var ke=33554432,ue="image/svg+xml",be=4194304,Ue=4096,pe=new WeakMap;function Ne(t){return pe.get(t)??{x:1,y:1}}function We(t,e){pe.set(t,e);}function Ae(t){if(a(t))throw new Error("TIFF images require worker conversion");let e=Ce(t)??Be(t);return e?new Blob([e],{type:"image/bmp"}):Me(t)??new Blob([t.slice()])}function Ie(t){return t.type===ue}async function Ke(t,e,r={}){let i=Ae(t);return Oe(i,e,r)}async function Oe(t,e,r={}){let i=r.maxDimension??Ue;if(!Number.isSafeInteger(i)||i<1)throw new Error("invalid image dimension limit");if(typeof createImageBitmap=="function"&&!Ie(t)){let n=fe(new Uint8Array(await t.arrayBuffer()));if(n&&Math.max(n.width,n.height)>i){let l=i/Math.max(n.width,n.height),u=await createImageBitmap(t,{resizeWidth:Math.max(1,Math.floor(n.width*l)),resizeHeight:Math.max(1,Math.floor(n.height*l))});return K(u,n,i)}let o=await createImageBitmap(t);return K(o,{width:o.width,height:o.height},i)}let s=URL.createObjectURL(t);try{let n=await new Promise((o,l)=>{let u=new Image;u.onload=()=>o(u),u.onerror=()=>l(new Error(e)),u.src=s;});return await K(n,{width:n.naturalWidth,height:n.naturalHeight},i)}finally{URL.revokeObjectURL(s);}}async function K(t,e,r){let i="naturalWidth"in t?t.naturalWidth:t.width,s="naturalHeight"in t?t.naturalHeight:t.height,n=t;if(Math.max(i,s)>r){let u=r/Math.max(i,s),f={width:Math.max(1,Math.floor(i*u)),height:Math.max(1,Math.floor(s*u))},d,m;try{typeof OffscreenCanvas=="function"&&(d=new OffscreenCanvas(f.width,f.height),m=d.getContext("2d"));}catch{d=void 0;}if(!m&&typeof document<"u")try{d=document.createElement("canvas"),d.width=f.width,d.height=f.height,m=d.getContext("2d");}catch{d=void 0;}if(d&&m){m.drawImage(t,0,0,f.width,f.height),"close"in t&&typeof t.close=="function"&&t.close();try{n=typeof createImageBitmap=="function"?await createImageBitmap(d):d;}catch{n=d;}}}let o="naturalWidth"in n?n.naturalWidth:n.width,l="naturalHeight"in n?n.naturalHeight:n.height;return (e.width!==o||e.height!==l)&&We(n,{x:e.width/o,y:e.height/l}),n}function Me(t){if(t.byteLength>be)return;let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t).replace(/^\ufeff/,"");}catch{return}if(!(!/^\s*</.test(e)||!e.slice(0,1024).includes("<svg")))return new Blob([Fe(e)],{type:ue})}function Fe(t){let e=Te(t);if(!e||/\s(?:width|height)\s*=/.test(t.slice(e.start,e.end)))return t;let r=t.slice(e.start,e.end).match(/\sviewBox\s*=\s*(["'])\s*[-+.\deE]+[\s,]+[-+.\deE]+[\s,]+([-+.\deE]+)[\s,]+([-+.\deE]+)\s*\1/),[i,s]=[Number(r?.[2]),Number(r?.[3])];if(!(i>0)||!(s>0))return t;let n=e.start+4;return `${t.slice(0,n)} width="${i}" height="${s}"${t.slice(n)}`}function Te(t){let e=0;for(;e<t.length;){if(/\s/.test(t[e]))e+=1;else if(t.startsWith("<!--",e))e=j(t.indexOf("-->",e+4),3);else if(t.startsWith("<?",e))e=j(t.indexOf("?>",e+2),2);else if(t.startsWith("<!",e))e=j(le(t,e+2),1);else break;if(e<0)return}if(!/^<svg[\s/>]/.test(t.slice(e,e+5)))return;let r=le(t,e+4);return r<0?void 0:{start:e,end:r}}function j(t,e){return t<0?-1:t+e}function le(t,e){let r="",i=false;for(let s=e;s<t.length;s+=1){let n=t[s];if(r)n===r&&(r="");else if(i&&t.startsWith("<!--",s)){if(s=j(t.indexOf("-->",s+4),2),s<0)return -1}else if(i&&t.startsWith("<?",s)){if(s=j(t.indexOf("?>",s+2),1),s<0)return -1}else if(n==='"'||n==="'")r=n;else if(n==="[")i=true;else if(n==="]")i=false;else if(n===">"&&!i)return s}return -1}function Be(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(e.byteLength<108||e.getUint32(0,true)!==1||e.getUint32(40,true)!==1179469088)return;let r=e.getUint32(4,true);if(r<88||r%4||r>e.byteLength-8)return;let i=e.getInt32(16,true)-e.getInt32(8,true)+1,s=e.getInt32(20,true)-e.getInt32(12,true)+1,n=e.getUint32(r+4,true);if(e.getUint32(r,true)!==81||n<80||n>e.byteLength-r-8)return;let o=m=>e.getInt32(r+m,true),l=e.getUint32(r+48,true),u=e.getUint32(r+56,true),f=e.getUint32(r+60,true);if(o(24)!==e.getInt32(8,true)||o(28)!==e.getInt32(12,true)||o(72)!==i||o(76)!==s||o(32)!==0||o(36)!==0||o(40)!==i||o(44)!==s||e.getUint32(r+64,true)!==0||e.getUint32(r+68,true)!==13369376||l<80||l+e.getUint32(r+52,true)!==u||u+f!==n)return;let d=r+n;if(!(e.getUint32(d,true)!==14||e.getUint32(d+4,true)!==e.byteLength-d))return me(t.subarray(r+l,d),i,s)}function Ce(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(e.byteLength<18)return;let r=e.getUint32(0,true)===2596720087?22:0;if(e.byteLength<r+18||![1,2].includes(e.getUint16(r,true))||e.getUint16(r+2,true)!==9||e.getUint16(r+4,true)!==768||e.getUint32(r+6,true)*2!==e.byteLength-r)return;let i=0,s=0,n=0,o=0,l=false,u;for(let f=r+18;f+6<=e.byteLength;){let d=e.getUint32(f,true)*2,m=e.getUint16(f+4,true);if(d<6||d>e.byteLength-f)return;if(m===0)return d===6&&f+d===e.byteLength?u:void 0;if(u)return;if(m===259){if(d<8||e.getUint16(f+6,true)!==8)return;l=true;}else if(m===263){if(d<8||![1,2,3,4].includes(e.getUint16(f+6,true)))return}else if(m===523||m===524){if(d!==10)return;let E=e.getInt16(f+6,true),U=e.getInt16(f+8,true);if(m===523)i=U,s=E;else {if(!l)return;n=U,o=E;}}else if(m===2881){if(d<66||e.getUint32(f+6,true)!==13369376||e.getInt16(f+14,true)!==0||e.getInt16(f+16,true)!==0||e.getInt16(f+18,true)!==o||e.getInt16(f+20,true)!==n||e.getInt16(f+22,true)!==s||e.getInt16(f+24,true)!==i||!n||!o||(u=me(t.subarray(f+26,f+d),e.getInt16(f+12,true),e.getInt16(f+10,true)),!u))return}else return;f+=d;}}function me(t,e,r){if(t.length<40)return;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),s=i.getInt32(4,true),n=i.getInt32(8,true),o=i.getUint16(14,true);if(i.getUint32(0,true)!==40||s<1||!n||s*Math.abs(n)>ke||e!==s||r!==Math.abs(n)||i.getUint16(12,true)!==1||![24,32].includes(o)||i.getUint32(16,true)!==0||i.getUint32(32,true)!==0)return;let l=Math.ceil(s*o/32)*4*Math.abs(n),u=i.getUint32(20,true);if(40+l!==t.length||u!==0&&u!==l)return;let f=new Uint8Array(14+t.length),d=new DataView(f.buffer);return d.setUint16(0,19778,true),d.setUint32(2,f.length,true),d.setUint32(10,54,true),f.set(t,14),f}var Le=6e4;function ge(t){try{t.post({protocol:1,kind:"wasm-compile"});}catch(e){try{t.close();}catch{}throw e}}function V(t,e){let r=new Map,i=new Map,s=new Set,n=new Set(Object.keys(e.methods)),o=e.now??Date.now,l=e.timer??((a,h)=>{let w=setTimeout(a,h);return ()=>clearTimeout(w)}),u=e.silenceMs??Le,f=1,d,m,E,U=()=>{},k=()=>{};function x(){m?.(),m=void 0;}function P(a,h,w=false){for(let W of [...a])if(!(!a.has(W)||w&&d))try{W(h);}catch{}}function b(a,h=true){if(!d){d=a,x(),U(),k();for(let w of r.values())w.reject(a);if(r.clear(),i.clear(),h){try{t.close();}catch{}P(s,a);}s.clear();}}function y(){if(x(),r.size===0||d)return;let a=o();m=l(()=>b(new N("silence",`Session received no message within ${u}ms`,`Waiting for ${r.size} call(s); silent for ${o()-a}ms`)),u);}function v(a,h,w=[]){if(d)return Promise.reject(d);if(!n.has(a))return Promise.reject(new Error(`Unknown session method: ${a}`));let W=f++;return new Promise((F,g)=>{let c=r.size===0;r.set(W,{resolve:F,reject:g}),c&&y();try{t.post({protocol:1,kind:"call",id:W,method:a,args:h},w);}catch(p){r.delete(W),r.size===0&&x(),g(p instanceof Error?p:new Error(`Session call could not be posted: ${String(p)}`));}})}U=t.listen(a=>{if(!d)if(y(),L(a))if(a.kind==="failure")b(new N(a.code,a.message,a.diagnostics));else if(a.kind==="wasm-module"){try{e.onWasmModule?.(a.url,a.module);}catch{}try{e.onWasmModuleMessage?.(a);}catch{}}else {if(a.kind==="progress")return;if(a.kind==="event"){let h=i.get(a.name);h&&P(h,a.payload,true);}else {let h=r.get(a.id);if(!h)return;if(r.delete(a.id),r.size===0&&x(),a.ok)h.resolve(a.value);else {let w=new Error(a.error.message);w.name=a.error.name,J(a.error,"refusal")&&Object.assign(w,{refusal:a.error.refusal}),h.reject(w);}}}else {if(a!==null&&typeof a=="object"&&"kind"in a&&a.kind==="wasm-module")return;b(new N("message","Session received a malformed host message"));}}),k=t.onError(a=>b(a instanceof N?a:new N("crash",a instanceof Error?a.message:String(a))));let M=Object.create(null);for(let a of n)Object.defineProperty(M,a,{enumerable:true,value:(...h)=>v(a,h)});return {call:M,callWithTransfer:(a,h,w)=>v(a,h,w),on(a,h){if(d)return ()=>{};let w=i.get(a)??new Set;i.set(a,w);let W=h;return w.add(W),()=>{w.delete(W);}},onFailure(a){return d||s.add(a),()=>{s.delete(a);}},get failure(){return d},dispose(){if(E)return E;let a=d!==void 0;return b(new N("disposed","Session was disposed"),false),E=new Promise(h=>{if(!a)try{t.post({protocol:1,kind:"dispose"});}catch{}setTimeout(()=>{try{t.close();}catch{}h();},0);}),E}}}var z=new Map;function $(t){return ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():new Uint8Array(t).slice()}function ye(t,e){for(let{assetId:s,bytes:n}of t.media)e.set(s,new Uint8Array(n));let r=JSON.parse(new TextDecoder().decode(t.displayList)),i=new Map;for(let s of Q(r)){let n=e.get(s);n!==void 0&&i.set(s,n);}return {...t,displayList:r,media:i}}function he(t,e){return t?.map(r=>{let i=$(r.bytes).buffer;return e.push(i),{family:r.family,bytes:i,bold:r.bold,italic:r.italic}})}function we(t,e){let r=$(t).buffer,i=[r],s={clientId:e.clientId,fonts:he(e.fonts,i),fallbackFonts:he(e.fallbackFonts,i)};if(e.initialUpdate!==void 0){let n=$(e.initialUpdate);s.initialUpdate=n,i.push(n.buffer);}return e.wasm instanceof ArrayBuffer?(s.wasm=e.wasm.slice(0),i.push(s.wasm)):e.wasm!==void 0?s.wasm=e.wasm:e.worker||(s.wasm=z.get(b().href)),{document:r,input:s,transfer:i}}function Pe(t,e,r){try{let{document:i,input:s,transfer:n}=we(t,e);e.wasm===void 0&&delete s.wasm;let o=V(r,{methods:S}),l=new Map,u=!1,f={get failure(){return o.failure},onFailure:d=>o.onFailure(d),begin:()=>o.callWithTransfer("beginEditor",[i,s],n),frame:async d=>{if(u)throw new E;let m=await o.call.editorFrame(d);if(u)throw new E;return {...ye(m,l),slideId:m.slideId,sequence:m.sequence}},dispose:async()=>{u=!0;try{await o.dispose();}finally{l.clear();}}};return R.set(f,{client:o,peerAttached:!1}),f}catch(i){try{r.close();}catch{}throw i}}async function nt(t,e={}){let r=O(e.worker?e.worker():new Worker(new URL("./pptxSessionWorker.mjs",import.meta.url),{type:"module"}));return !e.worker&&e.wasm===void 0&&!z.has(b().href)&&ge(r),Re(t,e,r)}async function Re(t,e,r){let i,s,n,o;try{(({document:i,input:s,transfer:n}=we(t,e))),o=V(r,{methods:W,onWasmModule:e.wasm===void 0&&!e.worker?(y,v)=>{y===b().href&&!z.has(y)&&z.set(y,v);}:void 0});}catch(y){try{r.close();}catch{}throw y}let l;o.on("changed",y=>{l={...l,...y};}),o.onFailure(()=>{l={...l,stage:"failed"};});try{l=await o.callWithTransfer("open",[i,s],n);}catch(y){throw await o.dispose(),y}let u=new Map,{version:f,readContent:d,findText:m,validateEdits:E,applyEdits:U,frame:k,slides:x,slideSize:P,save:b$1}=o.call;return {get state(){return l},call:{version:f,readContent:d,findText:m,validateEdits:E,applyEdits:U,slides:x,slideSize:P,save:b$1,frame:async y=>ye(await k(y),u)},save:async()=>new Uint8Array(await b$1()),on:(y,v)=>o.on(y,v),onFailure:y=>o.onFailure(y),get failure(){return o.failure},dispose:async()=>{try{await o.dispose();}finally{u.clear();}}}}var _=new WeakMap;var je=["snapshot","story","anchorCaret","resolveCaretAnchor","version","readContent","findText","validateEdits","searchText","isProposalsAvailable","listProposals","layoutSlide","hitTest","mediaBytes","comments","canUndo","canRedo","undoCaptureMode","onUpdate"];function He(t){let e=structuredClone(t),r=new WeakSet;function i(s){if(typeof s=="number"&&!Number.isFinite(s))throw new B("arguments","Editor arguments must be finite");if(s!==null&&typeof s=="object"){if(r.has(s))throw new B("arguments","Editor arguments must be acyclic");r.add(s);for(let n of Object.values(s))i(n);r.delete(s),Object.freeze(s);}}return i(e),e}function xe(t){let{peer:e$1,session:r}=t,i=R.get(r);if(!i)throw new TypeError("Presentation session does not support editor replay");if(i.peerAttached)throw new B("attachment","Presentation peer is already attached");let{client:s}=i,n=0,o=0,l=e$1.version(),u,f=false,d=false,m$1=Promise.resolve(),E$1,U$1=new Promise((g,c)=>{E$1=c;});U$1.catch(()=>{});function k(g){u||f||(u=g instanceof D?g:new D(Y(g)),E$1(u),t.onFailure(u));}function x(){if(t.guard(),f)throw new E;if(s.failure&&k(s.failure),u)throw u}function P(g){let c=m$1.then(async()=>{x();let p=await Promise.race([g(),U$1]);return x(),p}).catch(p=>{throw k(p),u??p});return m$1=c.then(()=>{},()=>{}),Promise.race([c,U$1])}function b(g){if(x(),d)throw new B("reentrant","Presentation editor mutation cannot reenter");d=true;let c=false,p=false;try{let S={sequence:n+1,baseVersion:l,op:He(g)};return p=!0,m(e$1,S,A=>{if(c=!0,!A.consumed)return;n=A.sequence,l=A.version;let N=Object.freeze({...S,expectedOutcome:A.outcome});P(async()=>{let L=await s.call.replay(N);if(!V$1(A,L))throw new B("ack-mismatch","Presentation replay acknowledgement differs");o=L.sequence,t.onProgress(n,o,L.projection);}).catch(()=>{}),t.onProgress(n,o);})}catch(S){throw (c||p&&!(S instanceof e&&["arguments","invalidJson","method"].includes(S.code)))&&k(S),u??S}finally{d=false;}}function y(g){try{x();}catch(S){return Promise.reject(S)}let c=n,p=l;return P(async()=>{let S=await s.call.flush(c,p);if(S.sequence!==c||S.version!==p||o!==c)throw new B("ack-mismatch","Presentation flush acknowledgement differs");return g(c,p)})}let v={};function M(g,c){return (...p)=>(x(),g[c](...p))}Object.defineProperty(v,"clientId",{enumerable:true,get:()=>(x(),e$1.clientId)});for(let g of je)Object.defineProperty(v,g,{enumerable:true,value:M(e$1,g)});let a=Symbol.for("@betteroffice/pptx/slide-layout-cache"),h=e$1[a],w=Object.freeze(Object.fromEntries(["snapshot","key","activate","hitTest"].map(g=>[g,M(h,g)])));Object.defineProperty(v,"interaction",{enumerable:true,value:w}),Object.defineProperty(v,a,{value:w});for(let g of Object.keys(U))Object.defineProperty(v,g,{enumerable:true,value:(...c)=>b({method:g,args:c}).outcome.result});let W=s.onFailure(k),F={access:Object.freeze(v),get sequence(){return n},get acknowledgedSequence(){return o},get version(){return l},apply:b,flush:()=>y(async()=>{}),saveAsync:()=>y(async(g,c)=>new Uint8Array(await s.call.editorSave(g,c))),dispose(){f||(f=true,E$1(new E),W());}};return i.peerAttached=true,_.set(F,{fail:k,whenAcknowledged:()=>{try{x();}catch(g){return Promise.reject(g)}return Promise.race([m$1,U$1])}}),F}function xt(t,e={}){ve(e);let r=O(e.worker?e.worker():new Worker(new URL("./pptxSessionWorker.mjs",import.meta.url),{type:"module"}));return De(t,e,r)}function ve(t){if(t.collaboration!=null)throw new F;if(t.signal?.aborted)throw new E}function Ee(t){return t?.map(e=>({...e,bytes:new Uint8Array(e.bytes).slice()}))}function De(t,e,r){ve(e);let i$1,s$1,n;try{s$1=ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():new Uint8Array(t).slice(),n={fonts:Ee(e.fonts),fallbackFonts:Ee(e.fallbackFonts),initialUpdate:e.initialUpdate?.slice()},i$1=Pe(s$1,{...e,...n},r);}catch(c){try{r.close();}catch{}throw c}let o={stage:"opening",sequence:0,acknowledgedSequence:0},l,u,f,d,m,E$1=new Set,U,k=new Promise((c,p)=>{U=p;});k.catch(()=>{});function x(c){o=Object.freeze({...o,...c});for(let p of [...E$1])if(E$1.has(p))try{p(o);}catch{}}function P(){if(o.stage==="disposed")throw new E;if(o.failure)throw o.failure}function b(){if(P(),o.stage!=="ready"||!f)throw new C;return f}function y(){let c=u;u=void 0,l===c&&(l=void 0);try{c?.dispose();}catch{}}function v(c){if(o.failure||o.stage==="disposed")return;let p=c instanceof D?c:new D(c);y(),x({stage:"failed",failure:p}),U(p),f&&_.get(f)?.fail(p);try{e.onError?.(p);}catch{}i$1.dispose();}function M(){if(!d){if(!l)throw new C;d=new Uint8Array(l.save()).slice();}return o.stage==="disposed"&&l&&(l.dispose(),l=void 0),d.slice()}let{client:a}=R.get(i$1),h$1=i$1.onFailure(v),w=()=>new Promise(c=>setTimeout(c,0)),W=(async()=>{try{let c=await Promise.race([i$1.begin(),k]);if(P(),c.sequence!==0)throw new B("sequence","Editor baseline is not at zero");if(x({stage:"hydrating",projection:c.state,version:c.version}),P(),await s(c.module),await w(),P(),u=g(s$1,c.hydration,n),await w(),P(),await h(u),await w(),P(),i(u),u.version()!==c.version)throw new B("version","Hydrated peer version differs");let p=await Promise.race([a.call.attachPeer(u.version(),0),k]);if(P(),p.sequence!==0||p.version!==u.version())throw new B("attachment","Worker attachment acknowledgement differs");let S=c.state.slides[0]?.id,A=S===void 0?void 0:await Promise.race([i$1.frame(S),k]);if(P(),A&&(A.sequence!==0||A.version!==c.version||A.slideId!==S))throw new B("frame","Initial worker frame differs");l=u,f=xe({peer:l,session:i$1,guard:()=>{b();},onFailure:v,onProgress:(N,L,X)=>{o.stage==="ready"&&x({sequence:N,acknowledgedSequence:L,version:f?.version,...X?{projection:X}:{}});}}),u=void 0,x({stage:"ready",initialFrame:A}),P();}catch(c){let p=Y(c);throw v(p),o.stage==="disposed"?new E:o.failure??p}finally{y();}})();W.catch(()=>{});let F={get state(){return o},get hydrated(){return o.stage==="ready"},get failure(){return o.failure},subscribe(c){if(o.stage==="disposed")throw new E;return E$1.add(c),()=>{E$1.delete(c);}},whenHydrated:async()=>{P(),await Promise.race([W,k]),P();},handleAsync:async()=>(await F.whenHydrated(),b().access),apply:c=>b().apply(c),flush:async()=>b().flush(),saveAsync:async()=>b().saveAsync(),frame:async c=>{if(P(),!o.projection)throw new C;try{let p=await Promise.race([i$1.frame(c),k]);return P(),p}catch(p){throw P(),p instanceof Error&&p.name==="RangeError"||(v(p),P()),p}},recoverySave:async()=>{if(o.stage==="recovering")throw new B("stage","Recovery is already in progress");if(o.stage!=="disposed"&&!o.failure)throw new C;o.stage==="disposed"||x({stage:"recovering"});try{return {bytes:M(),recovery:!0}}finally{o.stage!=="disposed"&&x({stage:"failed"});}},dispose(){if(m)return m;let c,p;m=new Promise((S,A)=>{c=S,p=A;}),x({stage:"disposed"}),y(),U(new E),f?.dispose(),h$1(),e.signal?.removeEventListener("abort",g$1);try{l&&M();}catch{}return E$1.clear(),i$1.dispose().then(c,p),m}},g$1=()=>{F.dispose();};return e.signal?.addEventListener("abort",g$1,{once:true}),e.signal?.aborted&&g$1(),F}export{Ne as a,We as b,Ae as c,Ie as d,Ke as e,Oe as f,ge as g,V as h,nt as i,xt as j};
|