betteroffice-pptx-edit 0.3.0

Collaborative yrs-backed editing core for PPTX decks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! Read-only structured export of PPTX content: slides in deck order, each with its shape tree,
//! text stories, tables and placeholders for content the export cannot represent, every record
//! carrying the location it was read from, plus diagnostics for everything omitted.
//! [`render_pptx_markdown`] renders the same content as Markdown.
//!
//! One walker reads every source: a live session ([`DeckSession::export_structured`]) and PPTX
//! bytes ([`export_pptx_structured`]), which open a private session first.
//!
//! Reading order is the current shape tree, depth first: slides in deck order, shapes in their
//! tree order, a group's descendants at the group's position, and table cells row by row. It is
//! the authored order, not a visual or accessibility reading order inferred from geometry.

mod markdown;
mod walk;

use std::fmt;

use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};

use crate::batch::DocumentVersion;
use crate::target::TextRange;
use crate::{DeckSession, EditResult};

pub use markdown::render_pptx_markdown;

/// The only structured-content schema version this crate reads and writes.
pub const SCHEMA_VERSION: u8 = 1;
/// Blocks an export returns when the options name no limit.
pub const DEFAULT_MAX_BLOCKS: u32 = 10_000;
/// Serialized bytes an export or rendering returns when the options name no limit.
pub const DEFAULT_MAX_BYTES: u32 = 8_388_608;
/// The largest block limit an export accepts.
pub const MAX_BLOCKS_LIMIT: u32 = 1_000_000;
/// The largest byte limit an export or rendering accepts.
pub const MAX_BYTES_LIMIT: u32 = 67_108_864;
/// The smallest byte limit an export or rendering accepts: room for the envelope and one
/// truncation diagnostic.
pub const MIN_BYTES_LIMIT: u32 = 1_024;

/// Whether anchors resolve against a live session version or only against the returned
/// snapshot.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum AnchorScope {
    Session,
    Snapshot,
}

/// The order records are exported in; see the module documentation.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ReadingOrder {
    ShapeTree,
}

/// A structured export. Ids are deterministic export-tree paths, not document identities.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PptxStructuredContent {
    #[serde(deserialize_with = "schema_version")]
    pub schema_version: u8,
    pub anchor_scope: AnchorScope,
    pub reading_order: ReadingOrder,
    pub included: IncludedContent,
    pub slides: Vec<ExportSlide>,
    pub diagnostics: Vec<ExportDiagnostic>,
    pub truncated: bool,
}

fn schema_version<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u8, D::Error> {
    let version = u8::deserialize(deserializer)?;
    if version != SCHEMA_VERSION {
        return Err(D::Error::custom(format!(
            "structured content schema version {version} is not supported; expected {SCHEMA_VERSION}"
        )));
    }
    Ok(version)
}

/// The optional content an export was asked to include.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IncludedContent {
    pub hidden_slides: bool,
    pub hidden_shapes: bool,
    pub notes: bool,
    pub comments: bool,
    pub formatting: bool,
}

/// A half-open range of UTF-16 offsets.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TextSpan {
    pub start: u32,
    pub end: u32,
}

/// Where a record was read from. `range` anchors are [`TextTarget::Range`](crate::TextTarget)
/// batch targets in the story offsets of [`DeckSession::read_content`]; `notes` and `comment`
/// ranges index the plain text they carry; `sourcePart` addresses retained XML by element-child
/// ordinals from the part's root.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(
    tag = "kind",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum PptxAnchor {
    Slide {
        slide_id: String,
    },
    Shape {
        slide_id: String,
        shape_id: String,
    },
    Range(TextRange),
    Notes {
        slide_id: String,
        range: TextSpan,
    },
    Comment {
        slide_id: String,
        comment_id: String,
        range: TextSpan,
    },
    SourcePart {
        part: String,
        part_sha256: String,
        path: Vec<u32>,
    },
}

/// The retained source XML a record was seeded from. `path` holds element-child ordinals from
/// the part's root; `sld_id` is the owning slide's `p:sldId/@id` and `source_id` a shape's
/// `cNvPr/@id`.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceProvenance {
    pub part: String,
    pub part_sha256: String,
    pub path: Vec<u32>,
    pub sld_id: Option<u32>,
    pub source_id: Option<u32>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportSlide {
    pub id: String,
    /// Zero-based position in the current deck, hidden slides counted.
    pub index: u32,
    pub anchor: PptxAnchor,
    pub name: Option<String>,
    /// `None` when the deck does not record it.
    pub hidden: Option<bool>,
    pub provenance: Option<SourceProvenance>,
    pub shapes: Vec<ExportShape>,
    pub notes: Option<ExportNotes>,
    pub comments: Vec<ExportComment>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ExportShapeKind {
    Shape,
    Picture,
    GraphicFrame,
    Group,
    /// A shape-tree element only the source holds, anchored by its source location.
    Unknown,
}

/// A shape, group or unrepresented shape-tree element, with its stories, table, placeholder
/// object and children.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportShape {
    pub id: String,
    pub anchor: PptxAnchor,
    pub kind: ExportShapeKind,
    pub name: String,
    /// `cNvPr/@title`, the alternative-text title.
    pub title: Option<String>,
    /// `cNvPr/@descr`, the alternative-text description.
    pub description: Option<String>,
    /// Hidden itself or through a hidden group.
    pub hidden: bool,
    pub placeholder: Option<ExportPlaceholder>,
    pub provenance: Option<SourceProvenance>,
    pub stories: Vec<ExportStory>,
    pub table: Option<ExportTable>,
    pub object: Option<ExportObject>,
    pub children: Vec<ExportShape>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportPlaceholder {
    #[serde(rename = "type")]
    pub placeholder_type: Option<String>,
    pub index: Option<u32>,
}

/// One text story; `anchor` spans all of it.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportStory {
    pub id: String,
    pub anchor: PptxAnchor,
    pub paragraphs: Vec<ExportParagraph>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportParagraph {
    pub id: String,
    pub anchor: PptxAnchor,
    pub paragraph_id: String,
    pub level: u32,
    /// The authored alignment, else the inherited one.
    pub alignment: Option<String>,
    /// The paragraph's own `a:buChar`, `a:buAutoNum` or `a:buNone`, as the session stores it.
    pub bullet_json: Option<String>,
    /// The list marker after inheritance and numbering; `None` for a paragraph that is not a
    /// list item.
    pub list: Option<ExportList>,
    pub runs: Vec<ExportRun>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(
    tag = "kind",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum ExportList {
    /// `character` is the authored `a:buChar`; `font` its `a:buFont` typeface, a symbol font
    /// when the character names a glyph slot.
    Bullet {
        character: String,
        font: Option<String>,
    },
    /// `marker` is the formatted number, `None` for a scheme that cannot be formatted.
    Number {
        scheme: String,
        start_at: u32,
        value: u32,
        marker: Option<String>,
    },
}

/// A run of one kind and formatting. Line breaks are one `\n` unit and fields cover their cached
/// result; an unsupported inline is zero-width.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportRun {
    pub anchor: PptxAnchor,
    /// `None` when the export excludes formatting.
    pub marks: Option<Vec<ExportMark>>,
    pub link: Option<ExportLink>,
    #[serde(flatten)]
    pub content: ExportRunKind,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(
    tag = "kind",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum ExportRunKind {
    Text {
        text: String,
    },
    LineBreak,
    /// A field's cached result; fields are never evaluated.
    Field {
        field_type: Option<String>,
        text: String,
    },
    Unsupported {
        element: String,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ExportMark {
    Bold,
    Italic,
    Underline { style: String },
    Superscript,
    Subscript,
    SmallCaps,
    AllCaps,
}

/// A click hyperlink: an external URL, or the internal part it jumps to.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportLink {
    pub href: String,
    pub external: bool,
}

/// A table on its grid. Every source cell appears once; `merged` marks a continuation covered
/// by the cell at `merge_origin`, whose content PowerPoint does not show.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportTable {
    pub columns: u32,
    pub rows: Vec<ExportTableRow>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportTableRow {
    pub cells: Vec<ExportTableCell>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportTableCell {
    pub id: String,
    pub anchor: PptxAnchor,
    pub row: u32,
    pub column: u32,
    pub grid_span: u32,
    pub row_span: u32,
    pub merged: bool,
    pub merge_origin: Option<CellPosition>,
    pub story: Option<ExportStory>,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CellPosition {
    pub row: u32,
    pub column: u32,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ExportObjectKind {
    Picture,
    Video,
    Audio,
    Chart,
    SmartArt,
    EmbeddedObject,
    Unknown,
}

/// A placeholder for content the export does not represent; its data is never included.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportObject {
    pub id: String,
    pub kind: ExportObjectKind,
    /// The source element's qualified name, such as `p:graphicFrame`.
    pub element: String,
    /// `a:graphicData/@uri`.
    pub uri: Option<String>,
    pub relationship_ids: Vec<String>,
    /// The package parts the object references.
    pub parts: Vec<String>,
    /// Targets of the object's external relationships, such as a linked video.
    pub external_targets: Vec<String>,
}

/// A slide's speaker notes, as plain text.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportNotes {
    pub id: String,
    pub anchor: PptxAnchor,
    pub text: String,
    pub provenance: Option<SourceProvenance>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportComment {
    pub id: String,
    pub anchor: PptxAnchor,
    pub comment_id: String,
    pub author: Option<String>,
    pub date: Option<String>,
    pub parent_id: Option<String>,
    pub resolved: bool,
    pub text: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportDiagnostic {
    pub code: ExportDiagnosticCode,
    pub severity: ExportSeverity,
    pub anchor: Option<PptxAnchor>,
    pub message: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ExportSeverity {
    Info,
    Warning,
    Error,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExportDiagnosticCode {
    UnsupportedContent,
    ImageDataOmitted,
    UnsupportedNumbering,
    FieldCachedResult,
    ProvenanceUnavailable,
    VisibilityUnknown,
    HiddenContentExcluded,
    StoriesOmitted,
    FormattingOmitted,
    InheritedContentOmitted,
    NotesStructureOmitted,
    MergeContinuationContentOmitted,
    Truncated,
    MarkdownLossy,
}

/// What to export. Hidden slides and shapes, notes and comments are excluded unless requested;
/// formatting is included unless turned off.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PptxExportOptions {
    #[serde(default)]
    pub include_hidden_slides: Option<bool>,
    #[serde(default)]
    pub include_hidden_shapes: Option<bool>,
    #[serde(default)]
    pub include_notes: Option<bool>,
    #[serde(default)]
    pub include_comments: Option<bool>,
    #[serde(default)]
    pub include_formatting: Option<bool>,
    #[serde(default)]
    pub max_blocks: Option<u32>,
    #[serde(default)]
    pub max_bytes: Option<u32>,
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PptxMarkdownOptions {
    #[serde(default)]
    pub max_bytes: Option<u32>,
}

/// Markdown rendered from structured content. Each `<!-- pptx-export:N -->` marker precedes the
/// record `anchors` maps it to. Markdown keeps no slide layout, geometry or typography.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PptxMarkdownContent {
    pub markdown: String,
    pub anchors: Vec<MarkdownAnchor>,
    pub diagnostics: Vec<ExportDiagnostic>,
    pub truncated: bool,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MarkdownAnchor {
    pub marker: String,
    pub anchor: PptxAnchor,
}

/// Why an export was refused: options out of range (`InvalidOptions`), above a hard maximum
/// (`LimitExceeded`), or structured content handed to the renderer that contradicts itself
/// (`InvalidContent`). Unsupported deck content is diagnosed, never refused.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExportFailureCode {
    InvalidOptions,
    LimitExceeded,
    InvalidContent,
}

/// Why an export was refused, as data. `target` is the anchor the refusal concerns, if any.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportFailure {
    pub code: ExportFailureCode,
    pub target: Option<Box<PptxAnchor>>,
    pub message: String,
}

impl fmt::Display for ExportFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = match self.code {
            ExportFailureCode::InvalidOptions => "invalid-options",
            ExportFailureCode::LimitExceeded => "limit-exceeded",
            ExportFailureCode::InvalidContent => "invalid-content",
        };
        write!(f, "{code}: {}", self.message)
    }
}

impl std::error::Error for ExportFailure {}

/// A session export refusal; the deck is at `version`.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportRefusal {
    pub version: DocumentVersion,
    pub failure: ExportFailure,
}

/// Content read from a session together with the version it was read at.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportRead<T> {
    pub version: DocumentVersion,
    pub content: T,
}

/// A session export: the content with its version, or a refusal.
pub type PptxExportResult<T> = Result<ExportRead<T>, ExportRefusal>;

/// Why a bytes export produced nothing.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ExportError {
    /// The input is not a readable PPTX package.
    Parse(String),
    Refused(ExportFailure),
}

impl fmt::Display for ExportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse(message) => f.write_str(message),
            Self::Refused(failure) => failure.fmt(f),
        }
    }
}

impl std::error::Error for ExportError {}

impl From<ExportFailure> for ExportError {
    fn from(failure: ExportFailure) -> Self {
        Self::Refused(failure)
    }
}

fn invalid_options(message: impl Into<String>) -> ExportFailure {
    ExportFailure {
        code: ExportFailureCode::InvalidOptions,
        target: None,
        message: message.into(),
    }
}

fn limit_exceeded(message: impl Into<String>) -> ExportFailure {
    ExportFailure {
        code: ExportFailureCode::LimitExceeded,
        target: None,
        message: message.into(),
    }
}

/// Validates a byte limit shared by exports and renderings.
fn byte_limit(requested: Option<u32>) -> Result<usize, ExportFailure> {
    let limit = requested.unwrap_or(DEFAULT_MAX_BYTES);
    if limit < MIN_BYTES_LIMIT {
        return Err(invalid_options(format!(
            "maxBytes must be at least {MIN_BYTES_LIMIT}"
        )));
    }
    if limit > MAX_BYTES_LIMIT {
        return Err(limit_exceeded(format!(
            "maxBytes may be at most {MAX_BYTES_LIMIT}"
        )));
    }
    Ok(limit as usize)
}

/// Export options with their defaults applied and validated.
pub(crate) struct Resolved {
    pub included: IncludedContent,
    pub max_blocks: usize,
    pub max_bytes: usize,
}

impl Resolved {
    fn new(options: &PptxExportOptions) -> Result<Self, ExportFailure> {
        let max_blocks = options.max_blocks.unwrap_or(DEFAULT_MAX_BLOCKS);
        if max_blocks == 0 {
            return Err(invalid_options("maxBlocks must be at least 1"));
        }
        if max_blocks > MAX_BLOCKS_LIMIT {
            return Err(limit_exceeded(format!(
                "maxBlocks may be at most {MAX_BLOCKS_LIMIT}"
            )));
        }
        Ok(Self {
            included: IncludedContent {
                hidden_slides: options.include_hidden_slides.unwrap_or(false),
                hidden_shapes: options.include_hidden_shapes.unwrap_or(false),
                notes: options.include_notes.unwrap_or(false),
                comments: options.include_comments.unwrap_or(false),
                formatting: options.include_formatting.unwrap_or(true),
            },
            max_blocks: max_blocks as usize,
            max_bytes: byte_limit(options.max_bytes)?,
        })
    }
}

impl DeckSession {
    /// Exports the committed deck with the version it was read at; anchors are scoped to that
    /// version. Nothing is mutated, minted, published or laid out, and pending input is not
    /// flushed. Refusals are the inner `Err`.
    pub fn export_structured(
        &self,
        options: &PptxExportOptions,
    ) -> EditResult<PptxExportResult<PptxStructuredContent>> {
        let version = self.version();
        let resolved = match Resolved::new(options) {
            Ok(resolved) => resolved,
            Err(failure) => return Ok(Err(ExportRefusal { version, failure })),
        };
        let content = walk::export(self, &resolved, AnchorScope::Session)?;
        Ok(Ok(ExportRead { version, content }))
    }

    /// [`DeckSession::export_structured`] rendered as Markdown from that one read.
    pub fn export_markdown(
        &self,
        options: &PptxExportOptions,
    ) -> EditResult<PptxExportResult<PptxMarkdownContent>> {
        let read = match self.export_structured(options)? {
            Ok(read) => read,
            Err(refusal) => return Ok(Err(refusal)),
        };
        let markdown_options = PptxMarkdownOptions {
            max_bytes: options.max_bytes,
        };
        Ok(
            match render_pptx_markdown(&read.content, &markdown_options) {
                Ok(content) => Ok(ExportRead {
                    version: read.version,
                    content,
                }),
                Err(failure) => Err(ExportRefusal {
                    version: read.version,
                    failure,
                }),
            },
        )
    }
}

/// The client id of the private session a bytes export opens; exports never reveal it.
const SNAPSHOT_CLIENT_ID: u64 = 1;

/// Exports PPTX bytes as a snapshot: anchors address the returned content only.
pub fn export_pptx_structured(
    bytes: &[u8],
    options: &PptxExportOptions,
) -> Result<PptxStructuredContent, ExportError> {
    let resolved = Resolved::new(options)?;
    let session = DeckSession::open(bytes, SNAPSHOT_CLIENT_ID)
        .map_err(|error| ExportError::Parse(error.to_string()))?;
    walk::export(&session, &resolved, AnchorScope::Snapshot)
        .map_err(|error| ExportError::Parse(error.to_string()))
}

/// JSON of a session export: `{"ok":true,"version","content"}` or
/// `{"ok":false,"version","failure"}`.
pub fn export_outcome_json<T: Serialize>(
    outcome: &PptxExportResult<T>,
) -> Result<String, serde_json::Error> {
    tagged(
        outcome.is_ok(),
        match outcome {
            Ok(read) => serde_json::to_value(read)?,
            Err(refusal) => serde_json::to_value(refusal)?,
        },
    )
}

/// JSON of a bytes export or rendering: `{"ok":true,"content"}` or `{"ok":false,"failure"}`.
/// `Err` is the message for input that is not a readable PPTX.
pub fn snapshot_outcome_json<T: Serialize>(
    outcome: Result<T, ExportError>,
) -> Result<String, String> {
    let value = match &outcome {
        Ok(content) => serde_json::json!({ "content": content }),
        Err(ExportError::Refused(failure)) => serde_json::json!({ "failure": failure }),
        Err(ExportError::Parse(message)) => return Err(message.clone()),
    };
    tagged(outcome.is_ok(), value).map_err(|error| error.to_string())
}

fn tagged(ok: bool, mut value: serde_json::Value) -> Result<String, serde_json::Error> {
    if let serde_json::Value::Object(object) = &mut value {
        object.insert("ok".to_owned(), serde_json::Value::Bool(ok));
    }
    serde_json::to_string(&value)
}

/// [`export_pptx_structured`] rendered as Markdown.
pub fn export_pptx_markdown(
    bytes: &[u8],
    options: &PptxExportOptions,
) -> Result<PptxMarkdownContent, ExportError> {
    let content = export_pptx_structured(bytes, options)?;
    Ok(render_pptx_markdown(
        &content,
        &PptxMarkdownOptions {
            max_bytes: options.max_bytes,
        },
    )?)
}