1use std::collections::BTreeMap;
13
14use quillmark_content::markdown::ImportError;
15use quillmark_content::model::Content;
16
17use crate::document::base::StaleBase;
18use crate::document::meta::{CardKindError, validate_composable_kind};
19use crate::document::payload::MetaKey;
20use crate::document::{Card, Codec, ContentDecodeError, Document, Payload, PayloadItem};
21use crate::error::Diagnostic;
22use crate::error::diag_args;
23use crate::path::DocPath;
24use crate::quill::{CoercionError, FieldSchema, FieldType, Leniency, QuillConfig};
25use crate::value::{PathSegment, QuillValue};
26use crate::version::QuillReference;
27
28fn render_at(field: &str, at: &[PathSegment]) -> String {
32 at.iter()
33 .fold(crate::path::DocPath::new().field(field), |p, seg| {
34 p.segment(seg)
35 })
36 .to_string()
37}
38
39pub fn is_valid_field_name(name: &str) -> bool {
46 let mut chars = name.chars();
47 let Some(first) = chars.next() else {
48 return false;
49 };
50 if !first.is_ascii_alphabetic() && first != '_' {
51 return false;
52 }
53 chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
54}
55
56pub const CODEC_RICHTEXT: &str = "richtext";
60
61pub const CODEC_TEXT: &str = "text";
63
64#[derive(Debug, Clone, PartialEq, thiserror::Error)]
66#[non_exhaustive]
67pub enum EditError {
68 #[error("invalid field name '{0}': must match [A-Za-z_][A-Za-z0-9_]*")]
69 InvalidFieldName(String),
70
71 #[error("field '{}' is not declared in the schema", render_at(.field, .at))]
78 UnknownField {
79 field: String,
80 at: Vec<PathSegment>,
86 },
87
88 #[error("invalid card kind '{0}': must match [a-z_][a-z0-9_]*")]
89 InvalidKindName(String),
90
91 #[error("card kind 'main' is reserved for the document root")]
92 ReservedKind,
93
94 #[error("'{key}' is carried by the document root only, not by a composable card")]
97 RootOnlyEntry { key: String },
98
99 #[error("index {index} is out of range (len = {len})")]
100 IndexOutOfRange { index: usize, len: usize },
101
102 #[error(
105 "invalid card id '{0}': must be 1 to 64 of [A-Za-z0-9_-], opening with a letter or digit"
106 )]
107 InvalidCardId(String),
108
109 #[error("card id '{0}' is already held by another card")]
111 DuplicateCardId(String),
112
113 #[error("no card holds the id '{0}'")]
116 UnknownCardId(String),
117
118 #[error("the document already holds the maximum of {max} cards")]
122 TooManyCards { max: usize },
123
124 #[error("value nests deeper than the maximum of {max} levels")]
125 ValueTooDeep { max: usize },
126
127 #[error("markdown import failed: {0}")]
132 Import(ImportError),
133
134 #[error("{codec} field '{}': {message}", render_at(.field, .at))]
142 FieldDecode {
143 field: String,
144 at: Vec<PathSegment>,
148 codec: String,
151 message: String,
152 },
153
154 #[error("field '{}' is declared '{declared}', which is not a content field", render_at(.field, .at))]
163 FieldNotContent {
164 field: String,
165 at: Vec<PathSegment>,
169 declared: String,
170 },
171
172 #[error(
176 "{codec} field '{field}' is not a single line: {codec} requires a single line with \
177 no container or island; declare shape: lines to admit more"
178 )]
179 FieldNotSingleLine {
180 field: String,
181 codec: String,
184 },
185
186 #[error("field '{field}' could not be coerced to its schema type: {message}")]
192 FieldCoercionFailed {
193 field: String,
194 target: String,
197 message: String,
198 },
199
200 #[error("content change refused: {0}")]
203 Change(quillmark_content::change::ApplyError),
204
205 #[error("an input of {size} bytes is past the limit of {max}")]
209 InputTooLarge { size: usize, max: usize },
210
211 #[error("a change of {count} steps is past the limit of {max}")]
215 TooManySteps { count: usize, max: usize },
216
217 #[error("{count} marks over a text that holds at most {max}")]
221 TooManyMarks { count: usize, max: usize },
222
223 #[error("{count} anchors, past the limit of {max}")]
227 TooManyAnchors { count: usize, max: usize },
228
229 #[error("{0}")]
235 InvalidPayload(PayloadViolation),
236
237 #[error(
242 "the write removes the {kind} island '{island}', which its writer may not have seen; remove it with apply"
243 )]
244 DropsExtIsland { island: String, kind: String },
245
246 #[error(transparent)]
248 StaleBase(StaleBase),
249}
250
251impl EditError {
252 pub fn change(e: quillmark_content::change::ApplyError) -> Self {
255 match &e {
256 quillmark_content::change::ApplyError::Invalid(inv) => {
257 Self::bound(inv).unwrap_or(EditError::Change(e))
258 }
259 _ => EditError::Change(e),
260 }
261 }
262
263 pub fn import(e: ImportError) -> Self {
266 match e {
267 ImportError::TooLarge { size, max } => EditError::InputTooLarge { size, max },
268 e => EditError::Import(e),
269 }
270 }
271
272 pub fn bound(inv: &quillmark_content::model::Invariant) -> Option<Self> {
275 use quillmark_content::model::Invariant;
276 match *inv {
277 Invariant::TooManyMarks { marks, max } => {
278 Some(EditError::TooManyMarks { count: marks, max })
279 }
280 Invariant::TooManyAnchors { anchors, max } => Some(EditError::TooManyAnchors {
281 count: anchors,
282 max,
283 }),
284 _ => None,
285 }
286 }
287
288 pub(crate) fn unknown_field(name: impl Into<String>) -> Self {
289 EditError::UnknownField {
290 field: name.into(),
291 at: Vec::new(),
292 }
293 }
294
295 pub fn code(&self) -> &'static str {
299 match self {
300 EditError::InvalidFieldName(_) => "edit::invalid_field_name",
301 EditError::UnknownField { .. } => "edit::unknown_field",
302 EditError::InvalidKindName(_) => "edit::invalid_kind_name",
303 EditError::ReservedKind => "edit::reserved_kind",
304 EditError::RootOnlyEntry { .. } => "edit::root_only_entry",
305 EditError::IndexOutOfRange { .. } => "edit::index_out_of_range",
306 EditError::InvalidCardId(_) => "edit::invalid_card_id",
307 EditError::DuplicateCardId(_) => "edit::duplicate_card_id",
308 EditError::UnknownCardId(_) => "edit::unknown_card_id",
309 EditError::TooManyCards { .. } => "edit::too_many_cards",
310 EditError::ValueTooDeep { .. } => "edit::value_too_deep",
311 EditError::Import(_) => "edit::import",
312 EditError::FieldDecode { .. } => "edit::field_decode",
313 EditError::FieldNotContent { .. } => "edit::field_not_content",
314 EditError::FieldNotSingleLine { .. } => "edit::field_not_single_line",
315 EditError::FieldCoercionFailed { .. } => "edit::field_coercion_failed",
316 EditError::Change(_) => "edit::content_apply",
317 EditError::InputTooLarge { .. } => "edit::input_too_large",
318 EditError::TooManySteps { .. } => "edit::too_many_steps",
319 EditError::TooManyMarks { .. } => "edit::too_many_marks",
320 EditError::TooManyAnchors { .. } => "edit::too_many_anchors",
321 EditError::InvalidPayload(_) => "edit::invalid_payload",
322 EditError::DropsExtIsland { .. } => "edit::drops_ext_island",
323 EditError::StaleBase(e) => e.code(),
324 }
325 }
326
327 pub fn args(&self) -> BTreeMap<String, serde_json::Value> {
335 match self {
336 EditError::InvalidFieldName(field) => diag_args! { "field" => field },
337 EditError::UnknownField { field, at: _ } => diag_args! { "field" => field },
338 EditError::InvalidKindName(kind) => diag_args! { "kind" => kind },
339 EditError::ReservedKind => diag_args! {},
340 EditError::RootOnlyEntry { key } => diag_args! { "key" => key },
341 EditError::IndexOutOfRange { index, len } => diag_args! {
342 "index" => index,
343 "len" => len,
344 },
345 EditError::InvalidCardId(id)
346 | EditError::DuplicateCardId(id)
347 | EditError::UnknownCardId(id) => {
348 diag_args! { "id" => id }
349 }
350 EditError::TooManyCards { max } => diag_args! { "max" => max },
351 EditError::ValueTooDeep { max } => diag_args! { "max" => max },
352 EditError::Import(_) => diag_args! {},
353 EditError::FieldDecode {
354 field,
355 at: _,
356 codec,
357 message: _,
358 } => diag_args! {
359 "field" => field,
360 "codec" => codec,
361 },
362 EditError::FieldNotContent {
363 field,
364 at: _,
365 declared,
366 } => diag_args! {
367 "field" => field,
368 "declared" => declared,
369 },
370 EditError::FieldNotSingleLine { field, codec } => diag_args! {
371 "field" => field,
372 "codec" => codec,
373 },
374 EditError::FieldCoercionFailed {
375 field,
376 target,
377 message: _,
378 } => diag_args! {
379 "field" => field,
380 "target" => target,
381 },
382 EditError::Change(e) => apply_args(e),
383 EditError::InputTooLarge { size, max } => diag_args! { "size" => size, "max" => max },
384 EditError::TooManySteps { count, max }
385 | EditError::TooManyMarks { count, max }
386 | EditError::TooManyAnchors { count, max } => {
387 diag_args! { "count" => count, "max" => max }
388 }
389 EditError::InvalidPayload(_) => diag_args! {},
392 EditError::DropsExtIsland { island, kind } => diag_args! {
393 "island" => island,
394 "type" => kind,
395 },
396 EditError::StaleBase(e) => e.args(),
397 }
398 }
399
400 pub fn to_diagnostic(&self, path: Option<DocPath>) -> Diagnostic {
403 let diagnostic = Diagnostic::new(crate::error::Severity::Error, self.to_string())
404 .with_code(self.code().to_string())
405 .with_args(self.args());
406 match path {
407 Some(path) => diagnostic.with_path(path.to_string()),
408 None => diagnostic,
409 }
410 }
411
412 pub fn doc_path(&self, base: &crate::path::DocPath) -> Option<crate::path::DocPath> {
422 use crate::path::DocPath;
423 match self {
424 EditError::FieldNotContent { field: f, at, .. }
425 | EditError::FieldDecode { field: f, at, .. }
426 | EditError::UnknownField { field: f, at } => {
427 Some(at.iter().fold(base.field(f), |p, seg| p.segment(seg)))
428 }
429 EditError::InvalidFieldName(f)
430 | EditError::FieldNotSingleLine { field: f, .. }
431 | EditError::FieldCoercionFailed { field: f, .. } => Some(base.field(f)),
432 EditError::IndexOutOfRange { index, .. } => Some(DocPath::card(None, *index)),
433 EditError::StaleBase(StaleBase { field: Some(f), .. }) => Some(base.field(f)),
434 _ => (!base.segs().is_empty()).then(|| base.clone()),
435 }
436 }
437}
438
439#[derive(Debug, Clone, Copy, PartialEq, Eq)]
447pub enum FieldViolation {
448 InvalidName,
450 TooDeep,
453}
454
455impl FieldViolation {
456 pub fn message(&self, key: &str) -> String {
460 format!("invalid field {key:?}: {self}")
461 }
462}
463
464impl std::fmt::Display for FieldViolation {
465 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466 match self {
467 FieldViolation::InvalidName => {
468 f.write_str("field names must match [A-Za-z_][A-Za-z0-9_]*")
469 }
470 FieldViolation::TooDeep => write!(
471 f,
472 "nests deeper than the maximum of {} levels",
473 quillmark_content::MAX_JSON_DEPTH
474 ),
475 }
476 }
477}
478
479#[derive(Debug, Clone, PartialEq, Eq)]
488pub enum PayloadViolation {
489 DuplicateField { key: String },
491 TooManyFields { count: usize, max: usize },
495 DuplicateMeta { key: &'static str },
497 MultiLineComment,
500}
501
502impl std::fmt::Display for PayloadViolation {
503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
504 match self {
505 PayloadViolation::DuplicateField { key } => {
506 write!(f, "duplicate user-field key {key:?}")
507 }
508 PayloadViolation::TooManyFields { count, max } => write!(
509 f,
510 "card has {count} user fields, exceeding the maximum of {max}"
511 ),
512 PayloadViolation::DuplicateMeta { key } => {
513 write!(f, "duplicate `{key}` entry")
514 }
515 PayloadViolation::MultiLineComment => {
516 f.write_str("comment text spans multiple lines; a comment occupies one line")
517 }
518 }
519 }
520}
521
522pub(crate) fn edit_error_from_violation(name: &str, v: FieldViolation) -> EditError {
523 match v {
524 FieldViolation::InvalidName => EditError::InvalidFieldName(name.to_string()),
525 FieldViolation::TooDeep => EditError::ValueTooDeep {
526 max: quillmark_content::MAX_JSON_DEPTH,
527 },
528 }
529}
530
531fn check_field_name(name: &str) -> Result<(), EditError> {
532 if is_valid_field_name(name) {
533 Ok(())
534 } else {
535 Err(EditError::InvalidFieldName(name.to_string()))
536 }
537}
538
539fn check_field(name: &str, value: &serde_json::Value) -> Result<(), EditError> {
540 validate_field(name, value).map_err(|v| edit_error_from_violation(name, v))
541}
542
543pub(crate) fn canonical_field(
549 name: &str,
550 mut value: serde_json::Value,
551) -> Result<serde_json::Value, EditError> {
552 let mut at = Vec::new();
553 canonicalize_contents(&mut value, &mut at)
554 .map_err(|(codec, e)| field_decode(name, &at, codec, ContentDecodeError::NotContent(e)))?;
555 Ok(value)
556}
557
558fn canonicalize_contents(
559 value: &mut serde_json::Value,
560 at: &mut Vec<PathSegment>,
561) -> Result<(), (Codec, String)> {
562 if quillmark_content::units::is_content_value(value) {
563 let content = quillmark_content::model::Content::from_value(value)
564 .map_err(|e| (Codec::of_object(value), e.to_string()))?;
565 *value = content.to_value();
566 return Ok(());
567 }
568 match value {
569 serde_json::Value::Object(map) => {
570 for (key, v) in map.iter_mut() {
571 at.push(PathSegment::Key(key.clone()));
572 canonicalize_contents(v, at)?;
573 at.pop();
574 }
575 }
576 serde_json::Value::Array(items) => {
577 for (index, v) in items.iter_mut().enumerate() {
578 at.push(PathSegment::Index(index));
579 canonicalize_contents(v, at)?;
580 at.pop();
581 }
582 }
583 _ => {}
584 }
585 Ok(())
586}
587
588fn check_kind(kind: &str) -> Result<(), EditError> {
590 validate_composable_kind(kind).map_err(|e| match e {
591 CardKindError::InvalidName => EditError::InvalidKindName(kind.to_string()),
592 CardKindError::Reserved => EditError::ReservedKind,
593 })
594}
595
596pub(crate) fn field_decode(
600 name: &str,
601 at: &[PathSegment],
602 codec: Codec,
603 e: ContentDecodeError,
604) -> EditError {
605 EditError::FieldDecode {
606 field: name.to_string(),
607 at: at.to_vec(),
608 codec: codec.name().to_string(),
609 message: e.into_message(),
610 }
611}
612
613fn check_meta_depth<'v>(
618 values: impl IntoIterator<Item = &'v serde_json::Value>,
619) -> Result<(), EditError> {
620 let max = quillmark_content::MAX_JSON_DEPTH;
621 if values
622 .into_iter()
623 .any(|v| crate::value::json_depth_exceeds(v, max - 1))
624 {
625 return Err(EditError::ValueTooDeep { max });
626 }
627 Ok(())
628}
629
630pub fn validate_field(key: &str, value: &serde_json::Value) -> Result<(), FieldViolation> {
632 if !is_valid_field_name(key) {
633 return Err(FieldViolation::InvalidName);
634 }
635 if crate::value::json_depth_exceeds(value, quillmark_content::MAX_JSON_DEPTH) {
636 return Err(FieldViolation::TooDeep);
637 }
638 Ok(())
639}
640
641pub fn validate_payload(payload: &Payload) -> Result<(), PayloadViolation> {
644 let max = crate::error::MAX_FIELD_COUNT;
645 let count = payload.len();
646 if count > max {
647 return Err(PayloadViolation::TooManyFields { count, max });
648 }
649
650 let mut fields: std::collections::HashSet<&str> = std::collections::HashSet::new();
651 let mut seen_quill = false;
652 let mut seen_kind = false;
653 let mut seen_id = false;
654 let mut metas: std::collections::HashSet<MetaKey> = std::collections::HashSet::new();
655 for item in payload.items() {
656 let dup = |key| Err(PayloadViolation::DuplicateMeta { key });
657 match item {
658 PayloadItem::Field { key, .. } => {
659 if !fields.insert(key.as_str()) {
660 return Err(PayloadViolation::DuplicateField { key: key.clone() });
661 }
662 }
663 PayloadItem::Quill { .. } => {
664 if std::mem::replace(&mut seen_quill, true) {
665 return dup("$quill");
666 }
667 }
668 PayloadItem::Kind { .. } => {
669 if std::mem::replace(&mut seen_kind, true) {
670 return dup("$kind");
671 }
672 }
673 PayloadItem::Id { .. } => {
674 if std::mem::replace(&mut seen_id, true) {
675 return dup("$id");
676 }
677 }
678 PayloadItem::Meta { key, .. } => {
679 if !metas.insert(*key) {
680 return dup(key.as_str());
681 }
682 }
683 PayloadItem::Comment { text, .. } => {
684 if text.contains(['\n', '\r']) {
685 return Err(PayloadViolation::MultiLineComment);
686 }
687 }
688 }
689 }
690 if payload
691 .nested_comments()
692 .iter()
693 .any(|nc| nc.text.contains(['\n', '\r']))
694 {
695 return Err(PayloadViolation::MultiLineComment);
696 }
697 Ok(())
698}
699
700fn conform_error_to_edit(name: &str, err: CoercionError) -> EditError {
706 let CoercionError::Uncoercible {
707 path: _,
708 value: _,
709 target,
710 reason,
711 } = err;
712 let field = name.to_string();
713 match target.as_str() {
714 t if t == crate::quill::RICHTEXT_SINGLE_LINE_TARGET => EditError::FieldNotSingleLine {
715 field,
716 codec: CODEC_RICHTEXT.to_string(),
717 },
718 t if t == crate::quill::TEXT_SINGLE_LINE_TARGET => EditError::FieldNotSingleLine {
719 field,
720 codec: CODEC_TEXT.to_string(),
721 },
722 CODEC_RICHTEXT | CODEC_TEXT => EditError::FieldDecode {
723 field,
724 at: Vec::new(),
725 codec: target,
726 message: reason,
727 },
728 _ => EditError::FieldCoercionFailed {
729 field,
730 target,
731 message: reason,
732 },
733 }
734}
735
736pub(crate) fn overflow_errors<'n>(
742 payload: &Payload,
743 names: impl IntoIterator<Item = &'n str>,
744) -> Option<Vec<(String, EditError)>> {
745 let (count, past) = payload.overflow(names)?;
746 Some(
747 past.into_iter()
748 .map(|name| {
749 (
750 name.to_string(),
751 EditError::InvalidPayload(PayloadViolation::TooManyFields {
752 count,
753 max: crate::error::MAX_FIELD_COUNT,
754 }),
755 )
756 })
757 .collect(),
758 )
759}
760
761pub(crate) fn resolve_field_write(
766 name: &str,
767 value: &QuillValue,
768 schema: &FieldSchema,
769 base: &crate::path::DocPath,
770) -> Result<(QuillValue, Vec<Diagnostic>), EditError> {
771 check_field_name(name)?;
772 let mut drops = Vec::new();
773 let stored = QuillConfig::conform_value(
774 value,
775 schema,
776 &base.field(name),
777 Leniency::Write,
778 &mut drops,
779 )
780 .map_err(|e| conform_error_to_edit(name, e))?;
781 check_field(name, stored.as_json())?;
782 Ok((stored, drops))
783}
784
785pub(crate) fn committed_text(
789 name: &str,
790 body: String,
791 schema: &FieldSchema,
792) -> Result<String, EditError> {
793 let (committed, _) =
794 resolve_field_write(name, &QuillValue::from(body), schema, &DocPath::new())?;
795 Codec::Text
796 .decode_field(committed.as_json())
797 .map(|c| Codec::Text.project(&c))
798 .map_err(|e| field_decode(name, &[], Codec::Text, e))
799}
800
801pub struct CardMut<'a>(&'a mut Card);
815
816impl<'a> CardMut<'a> {
817 pub(crate) fn new(card: &'a mut Card) -> Self {
818 Self(card)
819 }
820
821 #[cfg(test)]
822 pub(crate) fn payload_mut(&mut self) -> &mut Payload {
823 self.0.payload_mut()
824 }
825
826 pub fn remove_field(&mut self, name: &str) -> Result<Option<QuillValue>, EditError> {
828 self.0.remove_field(name)
829 }
830
831 pub fn store_ext(
833 &mut self,
834 value: serde_json::Map<String, serde_json::Value>,
835 ) -> Result<(), EditError> {
836 self.0.store_ext(value)
837 }
838
839 pub fn remove_ext(&mut self) -> Option<serde_json::Map<String, serde_json::Value>> {
841 self.0.remove_ext()
842 }
843
844 pub fn store_seed_overlay(
846 &mut self,
847 card_kind: impl Into<String>,
848 value: serde_json::Value,
849 ) -> Result<(), EditError> {
850 self.0.store_seed_overlay(card_kind, value)
851 }
852
853 pub fn remove_seed_overlay(&mut self, card_kind: &str) -> Option<serde_json::Value> {
855 self.0.remove_seed_overlay(card_kind)
856 }
857
858 #[cfg(test)]
860 pub(crate) fn overwrite_body(&mut self, content: Content) {
861 self.0.overwrite_body(content)
862 }
863
864 pub fn apply<'o>(
866 &mut self,
867 target: super::Target<'_>,
868 change: &quillmark_content::change::Change,
869 opts: impl Into<super::WriteOptions<'o>>,
870 ) -> Result<super::Receipt, EditError> {
871 self.0.apply(target, change, opts)
872 }
873
874 pub fn revise<'o>(
876 &mut self,
877 target: super::Target<'_>,
878 markdown: &str,
879 opts: impl Into<super::WriteOptions<'o>>,
880 ) -> Result<super::Receipt, EditError> {
881 self.0.revise(target, markdown, opts)
882 }
883
884 pub fn replace<'o>(
886 &mut self,
887 target: super::Target<'_>,
888 content: &quillmark_content::model::Content,
889 opts: impl Into<super::WriteOptions<'o>>,
890 ) -> Result<super::Receipt, EditError> {
891 self.0.replace(target, content, opts)
892 }
893
894 pub fn split_block<'o>(
896 &mut self,
897 target: super::Target<'_>,
898 at: usize,
899 id: Option<&str>,
900 opts: impl Into<super::WriteOptions<'o>>,
901 ) -> Result<super::Receipt, EditError> {
902 self.0.split_block(target, at, id, opts)
903 }
904
905 pub fn join_blocks<'o>(
907 &mut self,
908 target: super::Target<'_>,
909 id: &str,
910 opts: impl Into<super::WriteOptions<'o>>,
911 ) -> Result<super::Receipt, EditError> {
912 self.0.join_blocks(target, id, opts)
913 }
914
915 pub fn delete_range<'o>(
917 &mut self,
918 target: super::Target<'_>,
919 start: usize,
920 end: usize,
921 opts: impl Into<super::WriteOptions<'o>>,
922 ) -> Result<super::Receipt, EditError> {
923 self.0.delete_range(target, start, end, opts)
924 }
925
926 pub fn indent<'o>(
928 &mut self,
929 target: super::Target<'_>,
930 first: &str,
931 last: &str,
932 opts: impl Into<super::WriteOptions<'o>>,
933 ) -> Result<super::Receipt, EditError> {
934 self.0.indent(target, first, last, opts)
935 }
936
937 pub fn outdent<'o>(
939 &mut self,
940 target: super::Target<'_>,
941 first: &str,
942 last: &str,
943 opts: impl Into<super::WriteOptions<'o>>,
944 ) -> Result<super::Receipt, EditError> {
945 self.0.outdent(target, first, last, opts)
946 }
947
948 pub fn wrap<'o>(
950 &mut self,
951 target: super::Target<'_>,
952 first: &str,
953 last: &str,
954 with: quillmark_content::structural::Wrap,
955 opts: impl Into<super::WriteOptions<'o>>,
956 ) -> Result<super::Receipt, EditError> {
957 self.0.wrap(target, first, last, with, opts)
958 }
959
960 pub fn write<'o>(
962 &mut self,
963 target: super::Target<'_>,
964 edit: super::Edit<'_>,
965 opts: impl Into<super::WriteOptions<'o>>,
966 ) -> Result<super::Receipt, EditError> {
967 self.0.write(target, edit, opts)
968 }
969
970 pub fn write_in<'o>(
972 &mut self,
973 target: super::Target<'_>,
974 edit: super::Edit<'_>,
975 opts: impl Into<super::WriteOptions<'o>>,
976 u: impl quillmark_content::units::Units,
977 ) -> Result<super::Receipt, EditError> {
978 self.0.write_in(target, edit, opts, u)
979 }
980
981 #[cfg(test)]
983 pub(crate) fn overwrite_field(
984 &mut self,
985 name: &str,
986 content: Content,
987 ) -> Result<(), EditError> {
988 self.0.overwrite_field(name, content)
989 }
990
991 #[doc(hidden)]
992 pub fn commit_field(
993 &mut self,
994 name: &str,
995 value: impl Into<QuillValue>,
996 schema: &FieldSchema,
997 ) -> Result<(), EditError> {
998 self.0.commit_field(name, value, schema)
999 }
1000
1001 #[doc(hidden)]
1002 pub fn revise_field_checked(
1003 &mut self,
1004 name: &str,
1005 body: impl Into<String>,
1006 schema: &FieldSchema,
1007 ) -> Result<super::Receipt, EditError> {
1008 self.0.revise_field_checked(name, body, schema)
1009 }
1010}
1011
1012impl std::ops::Deref for CardMut<'_> {
1013 type Target = Card;
1014
1015 fn deref(&self) -> &Card {
1016 self.0
1017 }
1018}
1019
1020impl Document {
1021 pub fn set_quill_ref(&mut self, reference: QuillReference) {
1022 self.main_card_mut().payload_mut().set_quill(reference);
1023 }
1024
1025 pub fn card_mut(&mut self, index: usize) -> Option<CardMut<'_>> {
1026 self.cards_vec_mut().get_mut(index).map(CardMut::new)
1027 }
1028
1029 pub fn unchecked(&mut self) -> Unchecked<'_> {
1031 Unchecked(self)
1032 }
1033
1034 pub(crate) fn place_card(
1037 &mut self,
1038 at: Option<usize>,
1039 mut card: Card,
1040 ) -> Result<String, EditError> {
1041 let len = self.cards().len();
1042 let index = at.unwrap_or(len);
1043 if index > len {
1044 return Err(EditError::IndexOutOfRange { index, len });
1045 }
1046 Self::check_composable_placement(&card)?;
1047 self.check_card_room()?;
1048 let held: std::collections::HashSet<String> = self
1049 .cards()
1050 .iter()
1051 .filter_map(Card::id)
1052 .map(str::to_string)
1053 .collect();
1054 let id = match card.id() {
1055 Some(id) if !super::card_id::is_card_id(id) => {
1056 return Err(EditError::InvalidCardId(id.to_string()));
1057 }
1058 Some(id) if held.contains(id) => {
1059 return Err(EditError::DuplicateCardId(id.to_string()));
1060 }
1061 Some(id) => id.to_string(),
1062 None => {
1063 let id = super::card_id::Mint::new(held).mint();
1064 card.payload_mut().set_id(id.clone());
1065 id
1066 }
1067 };
1068 self.cards_vec_mut().insert(index, card);
1069 Ok(id)
1070 }
1071
1072 fn check_card_room(&self) -> Result<(), EditError> {
1073 let max = crate::error::MAX_CARD_COUNT;
1074 if self.cards().len() >= max {
1075 return Err(EditError::TooManyCards { max });
1076 }
1077 Ok(())
1078 }
1079
1080 fn check_composable_placement(card: &Card) -> Result<(), EditError> {
1087 check_kind(card.kind().unwrap_or(""))?;
1088 if card.quill().is_some() {
1089 return Err(EditError::RootOnlyEntry {
1090 key: "$quill".to_string(),
1091 });
1092 }
1093 if card.seed().is_some() {
1094 return Err(EditError::RootOnlyEntry {
1095 key: MetaKey::Seed.as_str().to_string(),
1096 });
1097 }
1098 Ok(())
1099 }
1100
1101 pub fn remove_card(&mut self, index: usize) -> Option<Card> {
1102 if index >= self.cards().len() {
1103 return None;
1104 }
1105 Some(self.cards_vec_mut().remove(index))
1106 }
1107
1108 pub fn move_card(&mut self, from: usize, to: usize) -> Result<(), EditError> {
1111 let len = self.cards().len();
1112 if from >= len {
1113 return Err(EditError::IndexOutOfRange { index: from, len });
1114 }
1115 if to >= len {
1116 return Err(EditError::IndexOutOfRange { index: to, len });
1117 }
1118 if from == to {
1119 return Ok(());
1120 }
1121 let card = self.cards_vec_mut().remove(from);
1122 self.cards_vec_mut().insert(to, card);
1123 Ok(())
1124 }
1125}
1126
1127pub struct Unchecked<'a>(&'a mut Document);
1135
1136impl Unchecked<'_> {
1137 pub fn store_field(
1140 &mut self,
1141 card: Option<usize>,
1142 name: &str,
1143 value: impl Into<QuillValue>,
1144 ) -> Result<(), EditError> {
1145 let len = self.0.cards().len();
1146 let card = match card {
1147 None => self.0.main_card_mut(),
1148 Some(index) => self
1149 .0
1150 .cards_vec_mut()
1151 .get_mut(index)
1152 .ok_or(EditError::IndexOutOfRange { index, len })?,
1153 };
1154 card.store_field(name, value)
1155 }
1156
1157 pub fn insert_card(&mut self, at: Option<usize>, card: Card) -> Result<String, EditError> {
1167 self.0.place_card(at, card)
1168 }
1169}
1170
1171impl Card {
1172 pub fn new(kind: impl Into<String>) -> Result<Self, EditError> {
1174 let kind = kind.into();
1175 check_kind(&kind)?;
1176 let mut payload = Payload::new();
1177 payload.set_kind(kind);
1178 Ok(Card::from_parts(payload, Content::empty()))
1179 }
1180
1181 pub fn store_field(
1195 &mut self,
1196 name: &str,
1197 value: impl Into<QuillValue>,
1198 ) -> Result<(), EditError> {
1199 let value = value.into();
1200 check_field(name, value.as_json())?;
1201 let value = QuillValue::from_json(canonical_field(name, value.into_json())?);
1202 self.payload_mut()
1203 .insert(name.to_string(), value)
1204 .map_err(EditError::InvalidPayload)?;
1205 Ok(())
1206 }
1207
1208 pub fn remove_field(&mut self, name: &str) -> Result<Option<QuillValue>, EditError> {
1211 check_field_name(name)?;
1212 Ok(self.payload_mut().remove(name))
1213 }
1214
1215 pub fn store_ext(
1224 &mut self,
1225 value: serde_json::Map<String, serde_json::Value>,
1226 ) -> Result<(), EditError> {
1227 let value =
1228 crate::value::depth_check_meta_map(value, |max| EditError::ValueTooDeep { max })?;
1229 self.payload_mut().set_ext(value);
1230 Ok(())
1231 }
1232
1233 pub fn remove_ext(&mut self) -> Option<serde_json::Map<String, serde_json::Value>> {
1236 self.payload_mut().take_ext()
1237 }
1238
1239 fn merge_meta_namespace(
1242 &mut self,
1243 key: MetaKey,
1244 namespace: String,
1245 value: serde_json::Value,
1246 ) -> Result<(), EditError> {
1247 let surviving = self
1248 .payload()
1249 .meta(key)
1250 .into_iter()
1251 .flatten()
1252 .filter(|(k, _)| **k != namespace)
1253 .map(|(_, v)| v);
1254 check_meta_depth(surviving.chain(std::iter::once(&value)))?;
1255 let mut map = self.payload().meta(key).cloned().unwrap_or_default();
1256 map.insert(namespace, value);
1257 self.payload_mut().set_meta(key, map);
1258 Ok(())
1259 }
1260
1261 fn remove_meta_namespace(
1263 &mut self,
1264 key: MetaKey,
1265 namespace: &str,
1266 ) -> Option<serde_json::Value> {
1267 let mut map = self.payload().meta(key)?.clone();
1268 let removed = map.shift_remove(namespace)?;
1269 if map.is_empty() {
1270 self.payload_mut().take_meta(key);
1271 } else {
1272 self.payload_mut().set_meta(key, map);
1273 }
1274 Some(removed)
1275 }
1276
1277 pub fn seed(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
1282 self.payload().seed()
1283 }
1284
1285 pub fn store_seed_overlay(
1295 &mut self,
1296 card_kind: impl Into<String>,
1297 value: serde_json::Value,
1298 ) -> Result<(), EditError> {
1299 let card_kind = card_kind.into();
1300 check_kind(&card_kind)?;
1301 self.check_carries_root_only(MetaKey::Seed)?;
1302 self.merge_meta_namespace(MetaKey::Seed, card_kind, value)
1303 }
1304
1305 fn check_carries_root_only(&self, key: MetaKey) -> Result<(), EditError> {
1310 if self.kind() == Some("main") {
1311 return Ok(());
1312 }
1313 Err(EditError::RootOnlyEntry {
1314 key: key.as_str().to_string(),
1315 })
1316 }
1317
1318 pub fn remove_seed_overlay(&mut self, card_kind: &str) -> Option<serde_json::Value> {
1321 self.remove_meta_namespace(MetaKey::Seed, card_kind)
1322 }
1323
1324 #[cfg(test)]
1328 pub(crate) fn overwrite_body(&mut self, content: Content) {
1329 self.set_body(quillmark_content::diff::align(self.body(), content));
1330 }
1331
1332 #[cfg(test)]
1345 pub(crate) fn overwrite_field(
1346 &mut self,
1347 name: &str,
1348 content: Content,
1349 ) -> Result<(), EditError> {
1350 check_field_name(name)?;
1351 self.store_field_content(name, &content)
1352 }
1353
1354 #[cfg(test)]
1358 fn store_field_content(&mut self, name: &str, content: &Content) -> Result<(), EditError> {
1359 let stored = self
1360 .payload
1361 .get(name)
1362 .map(QuillValue::as_json)
1363 .filter(|v| v.is_object());
1364 if stored.map_or(Codec::Richtext, Codec::of_object) == Codec::Text && !content.is_plain() {
1365 return Err(field_decode(
1366 name,
1367 &[],
1368 Codec::Text,
1369 super::ContentDecodeError::NotContent(
1370 quillmark_content::model::Invariant::NotPlain.to_string(),
1371 ),
1372 ));
1373 }
1374 let canonical =
1375 super::stored_over(self.payload.get(name).map(QuillValue::as_json), content);
1376 self.payload_mut()
1377 .insert(name.to_string(), QuillValue::from_json(canonical))
1378 .map(|_| ())
1379 .map_err(EditError::InvalidPayload)
1380 }
1381
1382 #[doc(hidden)]
1406 pub fn commit_field(
1407 &mut self,
1408 name: &str,
1409 value: impl Into<QuillValue>,
1410 schema: &FieldSchema,
1411 ) -> Result<(), EditError> {
1412 self.commit_field_at(name, &value.into(), schema, &DocPath::new())?;
1413 Ok(())
1414 }
1415
1416 pub(crate) fn commit_field_at(
1420 &mut self,
1421 name: &str,
1422 value: &QuillValue,
1423 schema: &FieldSchema,
1424 base: &DocPath,
1425 ) -> Result<Vec<Diagnostic>, EditError> {
1426 let (stored, drops) = resolve_field_write(name, value, schema, base)?;
1427 self.payload_mut()
1428 .insert(name.to_string(), stored)
1429 .map_err(EditError::InvalidPayload)?;
1430 Ok(drops)
1431 }
1432
1433 pub(crate) fn revise_body(
1438 &mut self,
1439 body: impl Into<String>,
1440 ) -> Result<super::Receipt, EditError> {
1441 self.revise_counted(super::Target::Body, &body.into())
1442 }
1443
1444 pub(crate) fn richtext_value(
1447 &self,
1448 name: &str,
1449 ) -> Result<quillmark_content::model::Content, EditError> {
1450 check_field_name(name)?;
1451 match self.payload.get(name) {
1452 None => Ok(Content::empty()),
1453 Some(v) => Codec::Richtext
1454 .read_content(v.as_json())
1455 .map_err(|e| field_decode(name, &[], Codec::Richtext, e)),
1456 }
1457 }
1458
1459 fn revision(
1462 &self,
1463 before: &quillmark_content::model::Content,
1464 markdown: &str,
1465 ) -> Result<quillmark_content::diff::Revision, EditError> {
1466 quillmark_content::diff::revise(before, markdown).map_err(|e| match e {
1467 quillmark_content::diff::ReviseError::Import(e) => EditError::import(e),
1468 quillmark_content::diff::ReviseError::Refused(e) => EditError::change(e),
1469 })
1470 }
1471
1472 #[doc(hidden)]
1483 pub fn revise_field_checked(
1484 &mut self,
1485 name: &str,
1486 body: impl Into<String>,
1487 schema: &FieldSchema,
1488 ) -> Result<super::Receipt, EditError> {
1489 check_field_name(name)?;
1490 let target = super::Target::Field(name);
1491 if matches!(schema.r#type, FieldType::Text { .. }) {
1492 let text = committed_text(name, body.into(), schema)?;
1493 let mut before = match self.payload.get(name) {
1494 None => Content::empty(),
1495 Some(v) => Codec::Text
1496 .read_content(v.as_json())
1497 .map_err(|e| field_decode(name, &[], Codec::Text, e))?,
1498 };
1499 before.codec = Codec::Text.content();
1500 let revised = self.revision(&before, &text)?;
1501 let stored = QuillValue::from_json(revised.content.to_value());
1502 return self.revising(target, before, Vec::new(), |card| {
1503 card.payload_mut()
1504 .insert(name.to_string(), stored)
1505 .map(|_| ())
1506 .map_err(EditError::InvalidPayload)
1507 });
1508 }
1509 let before = self.richtext_value(name)?;
1510 let body = body.into();
1511 let body = match schema.r#type {
1512 FieldType::RichText { shape } => {
1513 quillmark_content::markdown::admitting(&body, shape.admit())
1514 }
1515 _ => std::borrow::Cow::Borrowed(body.as_str()),
1516 };
1517 let revised = self.revision(&before, &body)?;
1518 super::write::keeps_ext_islands(&before, &revised.content)?;
1519 let (stored, _) = resolve_field_write(
1520 name,
1521 &QuillValue::from_json(revised.content.to_value()),
1522 schema,
1523 &DocPath::new(),
1524 )?;
1525 self.revising(target, before, revised.warnings, |card| {
1526 card.payload_mut()
1527 .insert(name.to_string(), stored)
1528 .map(|_| ())
1529 .map_err(EditError::InvalidPayload)
1530 })
1531 }
1532}
1533
1534fn apply_args(e: &quillmark_content::change::ApplyError) -> BTreeMap<String, serde_json::Value> {
1535 use quillmark_content::change::ApplyError as A;
1536 let reason = match e {
1537 A::Stale { .. } => "stale",
1538 A::UnknownBlock { .. } => "unknown_block",
1539 A::UnknownContainer { .. } => "unknown_container",
1540 A::ContainerKind { .. } => "container_kind",
1541 A::ContainerInUse { .. } => "container_in_use",
1542 A::UnknownAnchor { .. } => "unknown_anchor",
1543 A::AnchorHeld { .. } => "anchor_held",
1544 A::UnknownIsland { .. } => "unknown_island",
1545 A::UnknownSlot { .. } => "unknown_slot",
1546 A::BadStep { .. } => "bad_step",
1547 A::Invalid(_) => "invalid",
1548 _ => return diag_args! {},
1549 };
1550 let mut args = diag_args! { "reason" => reason };
1551 if let A::Stale { step } | A::BadStep { step, .. } = e {
1552 args.insert("step".into(), (*step).into());
1553 }
1554 args
1555}
1556
1557#[cfg(test)]
1558mod tests {
1559 use super::*;
1560 use crate::path::DocPath;
1561
1562 #[test]
1563 fn field_error_anchors_under_the_card_base() {
1564 let main = DocPath::main();
1565 assert_eq!(
1566 EditError::FieldCoercionFailed {
1567 field: "font_size".into(),
1568 target: "integer".into(),
1569 message: "x".into(),
1570 }
1571 .doc_path(&main)
1572 .unwrap()
1573 .to_string(),
1574 "main.font_size"
1575 );
1576 let card = DocPath::card(Some("indorsement"), 1);
1577 assert_eq!(
1578 EditError::unknown_field("signature_block")
1579 .doc_path(&card)
1580 .unwrap()
1581 .to_string(),
1582 "cards.indorsement[1].signature_block"
1583 );
1584 }
1585
1586 #[test]
1587 fn index_out_of_range_anchors_at_the_array_slot() {
1588 for base in [DocPath::main(), DocPath::card(Some("note"), 0)] {
1589 assert_eq!(
1590 EditError::IndexOutOfRange { index: 4, len: 2 }
1591 .doc_path(&base)
1592 .unwrap()
1593 .to_string(),
1594 "cards[4]"
1595 );
1596 }
1597 }
1598
1599 #[test]
1600 fn kind_and_depth_errors_anchor_at_base_or_nowhere() {
1601 assert_eq!(
1602 EditError::ReservedKind
1603 .doc_path(&DocPath::card(None, 2))
1604 .unwrap()
1605 .to_string(),
1606 "cards[2]"
1607 );
1608 assert_eq!(
1609 EditError::ValueTooDeep { max: 8 }.doc_path(&DocPath::new()),
1610 None
1611 );
1612 assert_eq!(
1613 EditError::ValueTooDeep { max: 8 }
1614 .doc_path(&DocPath::main())
1615 .unwrap()
1616 .to_string(),
1617 "main"
1618 );
1619 }
1620}