diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
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
use super::*;
use serde::{Deserialize, Serialize};

use crate::assembly::ExecutedWorkspace;
use crate::documents::{includes, prepare_collection_document_with_resources};
use crate::execution::output_safety::*;
use crate::execution::validated::{
    DiagnosticEvidence, OutputProducer, OwnedRepresentation, SlotEvidence,
};
use crate::execution::{
    PageExecutionRecord, PageExecutionRequest, PreparedExecution, ValidatedPage,
    ValidatedRepresentationRef,
};
use crate::ir::{Block, CodeCell, PageKind};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct StoredPage {
    record: PageExecutionRecord,
    diagnostics: Vec<ExecutionDiagnostic>,
    diagnostic_offset: usize,
    slots: Vec<StoredSlot>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StoredSlot {
    owning_cell: usize,
    slot: usize,
    origin: OutputProducer,
    representations: Vec<StoredRepresentation>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
enum StoredRepresentation {
    Text {
        text: String,
    },
    Markdown {
        content: DecodedMarkdown,
        origin: OutputOrigin,
    },
    Html {
        content: DecodedHtml,
    },
    Asset {
        asset: crate::execution::ExecutionAsset,
    },
}

impl StoredPage {
    fn capture(page: &ValidatedPage) -> Result<Self, SnapshotError> {
        let mut slots = Vec::new();
        for cell in &page.record().cells {
            for output in &cell.outputs {
                let mut representations = Vec::new();
                for index in 0..output.output.representations.len() {
                    let stored = match page
                        .representation(cell.ordinal, output.slot, index)
                        .ok_or(SnapshotError::Invalid("missing live output evidence"))?
                    {
                        ValidatedRepresentationRef::Text(text) => {
                            StoredRepresentation::Text { text: text.into() }
                        }
                        ValidatedRepresentationRef::Markdown(value) => {
                            StoredRepresentation::Markdown {
                                content: value.canonical_content().clone(),
                                origin: page
                                    .representation_origin(cell.ordinal, output.slot, index)
                                    .ok_or(SnapshotError::Invalid("missing fragment attribution"))?
                                    .clone(),
                            }
                        }
                        ValidatedRepresentationRef::Html(value) => StoredRepresentation::Html {
                            content: value.canonical_content().clone(),
                        },
                        ValidatedRepresentationRef::Asset(asset) => StoredRepresentation::Asset {
                            asset: asset.clone(),
                        },
                    };
                    representations.push(stored);
                }
                slots.push(StoredSlot {
                    owning_cell: cell.ordinal,
                    slot: output.slot,
                    origin: page
                        .output_origin(cell.ordinal, output.slot)
                        .ok_or(SnapshotError::Invalid("missing output attribution"))?
                        .clone(),
                    representations,
                });
            }
        }
        Ok(Self {
            record: page.portable_record(),
            diagnostics: page.diagnostics().to_vec(),
            diagnostic_offset: page.execution_diagnostic_offset(),
            slots,
        })
    }
}

impl Snapshot {
    /// Copy an executed workspace, retaining all output alternatives and evidence.
    ///
    /// Sources and staged assets are rechecked before this portable owner is
    /// returned. The execution owner may then discard its staging directory.
    pub fn from_executed(
        executed: &ExecutedWorkspace,
        resolved: &ResolvedWorkspace,
    ) -> Result<Self, SnapshotError> {
        executed.sources().revalidate()?;
        resolved.revalidate()?;
        let mut workspace = executed.workspace().clone();
        workspace.diagnostics = resolved.diagnostics().clone();
        let mut snapshot = Self {
            bundle: false,
            workspace,
            presentation: executed.sources().configuration().presentation.clone(),
            package_mounts: executed.sources().bundles.mounts.clone(),
            public_assets: resolved.public_assets.clone(),
            logo: resolved.logo().cloned(),
            open_graph: resolved.open_graph().cloned(),
            components: resolved.components.clone(),
            documents: resolved.records().to_vec(),
            assets: resolved.assets().clone(),
            producer: env!("CARGO_PKG_VERSION").into(),
            executions: executed
                .executed_pages()
                .iter()
                .map(|(id, page)| Ok((id.clone(), StoredPage::capture(page.validated())?)))
                .collect::<Result<_, SnapshotError>>()?,
            validated_outputs: BTreeMap::new(),
        };
        snapshot.validated_outputs = snapshot.validate()?;
        Ok(snapshot)
    }

    /// Outputs revalidated against current policies and snapshot-owned bytes.
    pub fn executed_page(&self, page: &str) -> Option<&ValidatedPage> {
        self.validated_outputs.get(page)
    }

    pub(super) fn restore_outputs(&self) -> Result<BTreeMap<String, ValidatedPage>, SnapshotError> {
        use super::validation::require;
        let mut restored = BTreeMap::new();
        let source_maps: BTreeMap<_, _> = self
            .documents
            .iter()
            .filter_map(|record| match &record.document {
                crate::validation::DocumentIdentity::Page { page } => {
                    Some((page, record.source_ranges.as_slice()))
                }
                _ => None,
            })
            .collect();
        for (id, stored) in &self.executions {
            let page = self
                .workspace
                .pages
                .get(id)
                .ok_or(SnapshotError::Invalid("execution page identity"))?;
            let PageKind::Authored { collection } = &page.kind else {
                return Err(SnapshotError::Invalid("execution on non-authored page"));
            };
            let declaration = self
                .workspace
                .content_collections
                .get(collection)
                .ok_or(SnapshotError::Invalid("execution collection"))?;
            require(
                stored.record.page.collection == *collection
                    && page.document.source_location.as_ref() == Some(&stored.record.page.source)
                    && stored.record.page.mode == declaration.execution.mode
                    && stored.record.page.format == declaration.format,
                "execution page association",
            )?;
            let raw = page
                .document
                .raw_source
                .as_ref()
                .ok_or(SnapshotError::Invalid("missing authored source"))?;
            let configuration = crate::configuration::ContentConfiguration {
                id: collection.clone(),
                owner: "project".into(),
                repository: declaration.repository.clone(),
                path: ".".into(),
                mount: declaration.mount.clone(),
                format: declaration.format,
                navigation: declaration.navigation,
                incremental: Default::default(),
                execution: crate::configuration::ExecutionConfiguration {
                    mode: declaration.execution.mode,
                    engine: declaration.execution.engine,
                    kernel: declaration.execution.kernel.clone(),
                    julia_project: declaration
                        .execution
                        .julia_project
                        .as_ref()
                        .map(|path| path.as_str().into()),
                    declared_environment_inputs: Vec::new(),
                },
            };
            let ranges = source_maps.get(id).copied().unwrap_or_default();
            let parsed =
                prepare_collection_document_with_resources(raw, &configuration, &|target, span| {
                    includes::resource_target(target, span, &stored.record.page.source, ranges)
                        .unwrap_or_else(|| target.to_owned())
                })
                .map_err(|_| SnapshotError::Invalid("execution configuration"))?;
            let preparation = parsed
                .preparation
                .ok_or(SnapshotError::Invalid("authored preparation"))?;
            let context = AuthoredOutputContext::new(
                stored.record.page.source.clone(),
                collection.clone(),
                preparation.authored_anchors,
            );
            let request = PageExecutionRequest {
                page: stored.record.page.clone(),
                kernel: declaration
                    .execution
                    .kernel
                    .clone()
                    .ok_or(SnapshotError::Invalid("missing kernel declaration"))?,
                defaults: preparation.defaults,
                cells: preparation.cells,
                declared_environment_inputs: Vec::new(),
            };
            let prepared = PreparedExecution::checked(request, raw.as_bytes().to_vec(), context)
                .map_err(|_| SnapshotError::Invalid("prepared execution inputs"))?;
            let mut projected = parsed.parsed.document;
            let mut index = 0;
            project(&mut projected.blocks, &stored.record.cells, &mut index)?;
            require(
                index == stored.record.cells.len() && projected == page.document.document,
                "execution document projection",
            )?;
            let mut verified = VerifiedAssets::new();
            for asset in &stored.record.assets {
                let bytes = self
                    .assets
                    .get(&asset.reference.fingerprint.value)
                    .ok_or(SnapshotError::Invalid("missing execution asset"))?;
                require(
                    bytes.media_type == asset.media_type,
                    "execution asset media",
                )?;
                verified
                    .verify_bytes(prepared.context(), asset, &bytes.bytes)
                    .map_err(|_| SnapshotError::Invalid("execution asset bytes"))?;
            }
            let mut slots = Vec::new();
            for slot in &stored.slots {
                let mut representations = Vec::new();
                for value in &slot.representations {
                    representations.push(match value {
                        StoredRepresentation::Text { text } => {
                            OwnedRepresentation::Text(text.clone())
                        }
                        StoredRepresentation::Markdown { content, origin } => {
                            OwnedRepresentation::Markdown {
                                value: Box::new(
                                    restore_markdown(
                                        content.clone(),
                                        origin,
                                        prepared.context(),
                                        &verified,
                                    )
                                    .map_err(|_| {
                                        SnapshotError::Invalid("generated Markdown policy")
                                    })?,
                                ),
                                origin: origin.clone(),
                            }
                        }
                        StoredRepresentation::Html { content } => OwnedRepresentation::Html {
                            value: restore_html_content(
                                content.clone(),
                                prepared.context(),
                                &verified,
                            )
                            .map_err(|_| SnapshotError::Invalid("generated HTML policy"))?,
                        },
                        StoredRepresentation::Asset { asset } => {
                            OwnedRepresentation::Asset(asset.clone())
                        }
                    });
                }
                slots.push(SlotEvidence {
                    owning_cell: slot.owning_cell,
                    slot: slot.slot,
                    origin: slot.origin.clone(),
                    representations,
                });
            }
            let end = stored
                .diagnostic_offset
                .checked_add(stored.diagnostics.len())
                .ok_or(SnapshotError::Invalid("diagnostic indices"))?;
            require(end <= stored.record.diagnostics.len(), "diagnostic indices")?;
            let diagnostics = DiagnosticEvidence {
                before: stored.record.diagnostics[..stored.diagnostic_offset].to_vec(),
                execution: stored.diagnostics.clone(),
                after: stored.record.diagnostics[end..].to_vec(),
            };
            let checked = ValidatedPage::restored(
                &prepared,
                stored.record.clone(),
                slots,
                diagnostics,
                verified,
            )
            .map_err(|_| SnapshotError::Invalid("execution record association"))?;
            restored.insert(id.clone(), checked);
        }
        for (id, page) in &self.workspace.pages {
            if !restored.contains_key(id) {
                require(
                    no_outputs(&page.document.document.blocks),
                    "outputs lack validation evidence",
                )?;
            }
        }
        for package in self.workspace.packages.values() {
            for item in package.items.values() {
                if let Some(document) = &item.documentation {
                    require(
                        no_outputs(&document.document.blocks),
                        "execution in API documentation",
                    )?;
                }
            }
        }
        for concept in self.workspace.concepts.values() {
            if let Some(document) = &concept.documentation {
                require(
                    no_outputs(&document.document.blocks),
                    "execution in concept documentation",
                )?;
            }
        }
        Ok(restored)
    }
}

fn cells(blocks: &[Block], visit: &mut impl FnMut(&CodeCell)) {
    for block in blocks {
        match block {
            Block::CodeCell(cell) => visit(cell),
            Block::BlockQuote { blocks, .. }
            | Block::Container { blocks, .. }
            | Block::Component { blocks, .. }
            | Block::Tabset { blocks, .. }
            | Block::Callout { blocks, .. } => cells(blocks, visit),
            Block::List { items, .. } => {
                for item in items {
                    cells(&item.blocks, visit);
                }
            }
            Block::Table { rows, .. } => {
                for row in rows {
                    for cell in &row.cells {
                        cells(&cell.blocks, visit);
                    }
                }
            }
            _ => {}
        }
    }
}
fn no_outputs(blocks: &[Block]) -> bool {
    let mut empty = true;
    cells(blocks, &mut |cell| empty &= cell.outputs.is_empty());
    empty
}
fn project(
    blocks: &mut [Block],
    records: &[crate::execution::CellExecutionResult],
    ordinal: &mut usize,
) -> Result<(), SnapshotError> {
    for block in blocks {
        match block {
            Block::CodeCell(cell) => {
                let record = records
                    .get(*ordinal)
                    .ok_or(SnapshotError::Invalid("execution cell count"))?;
                cell.outputs = record
                    .outputs
                    .iter()
                    .map(|output| output.output.clone())
                    .collect();
                *ordinal += 1;
            }
            Block::BlockQuote { blocks, .. }
            | Block::Container { blocks, .. }
            | Block::Component { blocks, .. }
            | Block::Tabset { blocks, .. }
            | Block::Callout { blocks, .. } => project(blocks, records, ordinal)?,
            Block::List { items, .. } => {
                for item in items {
                    project(&mut item.blocks, records, ordinal)?;
                }
            }
            Block::Table { rows, .. } => {
                for row in rows {
                    for cell in &mut row.cells {
                        project(&mut cell.blocks, records, ordinal)?;
                    }
                }
            }
            _ => {}
        }
    }
    Ok(())
}