use std::collections::BTreeSet;
use serde::{Deserialize, Deserializer, Serialize};
use super::{Edge, EditError, ExistingRevisions, Side};
use crate::namespaces::W;
use crate::xmllinq::{Dom, NodeId};
pub const SCHEMA_JSON: &str = include_str!("../../schemas/edit-plan-v2.schema.json");
pub const TEXT_CODEC_VERSION: u32 = 1;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PlanV2 {
#[serde(deserialize_with = "integer")]
pub schema_version: u64,
pub source: Source,
pub policy: Policy,
pub resolve_revisions: RevisionDecisions,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
pub removed_anchor_comments: Option<super::RemovedAnchorComments>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
pub rewrite_others_comments: Option<bool>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
pub others: Option<super::Others>,
pub author: String,
pub date: String,
pub scope: Scope,
pub operations: Vec<Operation>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
pub source_context: Option<Vec<SourceContext>>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
pub coverage: Option<Coverage>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Source {
pub sha256: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Policy {
#[serde(deserialize_with = "string_enum")]
pub track: Track,
#[serde(deserialize_with = "string_enum")]
pub existing_revisions: ExistingRevisions,
#[serde(deserialize_with = "string_enum")]
pub text_view: TextView,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Track {
On,
Off,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextView {
Final,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Target {
pub short_id: String,
pub long_id: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RevisionDecisions {
pub accept: Vec<Target>,
pub reject: Vec<Target>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Scope {
All {},
Selected {
targets: Vec<Target>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AttachedComment {
pub text: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Operation {
Replace {
target: Target,
find: String,
text: String,
#[serde(
default,
deserialize_with = "present_integer",
skip_serializing_if = "Option::is_none"
)]
occurrence: Option<u64>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
attached_comment: Option<AttachedComment>,
},
Insert {
target: Target,
text: String,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
before_text: Option<String>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
after_text: Option<String>,
#[serde(
default,
deserialize_with = "present_string_enum",
skip_serializing_if = "Option::is_none"
)]
edge: Option<Edge>,
#[serde(
default,
deserialize_with = "present_integer",
skip_serializing_if = "Option::is_none"
)]
occurrence: Option<u64>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
attached_comment: Option<AttachedComment>,
},
Delete {
target: Target,
find: String,
#[serde(
default,
deserialize_with = "present_integer",
skip_serializing_if = "Option::is_none"
)]
occurrence: Option<u64>,
},
Rewrite {
target: Target,
before_sha256: String,
text: String,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
attached_comment: Option<AttachedComment>,
},
InsertParagraph {
target: Target,
#[serde(deserialize_with = "string_enum")]
position: Side,
text: String,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
attached_comment: Option<AttachedComment>,
},
DeleteParagraph {
target: Target,
},
Comment {
target: Target,
text: String,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
find: Option<String>,
#[serde(
default,
deserialize_with = "present_integer",
skip_serializing_if = "Option::is_none"
)]
occurrence: Option<u64>,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
through: Option<Target>,
},
ReplyComment {
target: Target,
text: String,
},
ResolveComment {
target: Target,
done: bool,
},
EditComment {
target: Target,
text: String,
},
DeleteComment {
target: Target,
include_replies: bool,
},
Strike {
target: Target,
},
Restore {
target: Target,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextKind {
Paragraph,
Comment,
Opaque,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceContext {
#[serde(deserialize_with = "string_enum")]
pub kind: ContextKind,
pub target: Target,
#[serde(
default,
deserialize_with = "present",
skip_serializing_if = "Option::is_none"
)]
pub text: Option<String>,
pub reason_codes: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Coverage {
pub traversal_complete: bool,
pub text_complete: bool,
#[serde(deserialize_with = "integer")]
pub eligible_paragraphs: u64,
#[serde(
default,
deserialize_with = "present_integer",
skip_serializing_if = "Option::is_none"
)]
pub conditional_paragraphs: Option<u64>,
#[serde(deserialize_with = "integer")]
pub context_paragraphs: u64,
#[serde(deserialize_with = "integer")]
pub opaque_regions: u64,
}
fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
T::deserialize(d).map(Some)
}
fn integer<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
let n = serde_json::Number::deserialize(d)?;
if let Some(n) = n.as_u64() {
return Ok(n);
}
if let Some(n) = n.as_f64() {
if !(0.0..9_007_199_254_740_992.0).contains(&n) || n.fract() != 0.0 {
return Err(serde::de::Error::custom(
"expected an unsigned 64-bit integer; an integer written with a fraction or exponent must be below 2^53; write it as a plain integer",
));
}
return Ok(n as u64);
}
Err(serde::de::Error::custom(
"expected an unsigned 64-bit integer",
))
}
fn string_enum<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> {
let value = String::deserialize(d)?;
T::deserialize(serde::de::value::StringDeserializer::<D::Error>::new(value))
}
fn present_string_enum<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
d: D,
) -> Result<Option<T>, D::Error> {
string_enum(d).map(Some)
}
fn present_integer<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
integer(d).map(Some)
}
fn invalid(message: impl Into<String>) -> EditError {
super::err("INVALID_PLAN", None, message)
}
fn operation_fields(kind: &str) -> Option<&'static [&'static str]> {
let fields: &[&str] = match kind {
"replace" => &["attached_comment", "find", "occurrence", "target", "text"],
"insert" => &[
"after_text",
"attached_comment",
"before_text",
"edge",
"occurrence",
"target",
"text",
],
"delete" => &["find", "occurrence", "target"],
"rewrite" => &["attached_comment", "before_sha256", "target", "text"],
"insert_paragraph" => &["attached_comment", "position", "target", "text"],
"delete_paragraph" => &["target"],
"comment" => &["find", "occurrence", "target", "text", "through"],
"reply_comment" => &["target", "text"],
"resolve_comment" => &["done", "target"],
"edit_comment" => &["target", "text"],
"delete_comment" => &["include_replies", "target"],
"strike" | "restore" => &["target"],
_ => return None,
};
Some(fields)
}
fn v1_target_name(key: &str) -> Option<&'static str> {
match key {
"paragraph" | "paragraphs" | "anchor" => Some("target"),
_ => None,
}
}
fn check_operation_fields(plan: &serde_json::Value) -> Result<(), EditError> {
let Some(operations) = plan.get("operations").and_then(serde_json::Value::as_array) else {
return Ok(());
};
for (i, operation) in operations.iter().enumerate() {
let Some(map) = operation.as_object() else {
continue;
};
let Some(kind) = map.get("kind").and_then(serde_json::Value::as_str) else {
continue;
};
let Some(fields) = operation_fields(kind) else {
continue;
};
let Some(key) = map
.keys()
.find(|key| key.as_str() != "kind" && !fields.contains(&key.as_str()))
else {
continue;
};
let label = format!("op-{}", i + 1);
let meant = v1_target_name(key).filter(|name| fields.contains(name));
let message = format!("{kind}: {}", super::unknown_field(key, fields, meant));
return Err(super::err("INVALID_PLAN", Some(&label), message));
}
Ok(())
}
fn unsupported(version: u64) -> EditError {
super::err(
"UNSUPPORTED_SCHEMA",
None,
format!("schema_version {version} is not supported (expected 2)"),
)
}
fn require(condition: bool, message: &str) -> Result<(), EditError> {
if condition {
Ok(())
} else {
Err(invalid(message))
}
}
fn hash(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
fn unique<T: Ord>(values: &[T]) -> bool {
values.iter().collect::<BTreeSet<_>>().len() == values.len()
}
impl Target {
fn validate(&self) -> Result<(), EditError> {
require(
!self.short_id.is_empty() && !self.long_id.is_empty(),
"target requires nonempty short_id and long_id",
)
}
}
fn targets(values: &[Target]) -> Result<(), EditError> {
require(unique(values), "target array contains duplicates")?;
for target in values {
target.validate()?;
}
Ok(())
}
fn occurrence(value: Option<u64>) -> Result<(), EditError> {
require(value != Some(0), "occurrence must be at least 1")
}
fn attachment(text: &str, comment: Option<&AttachedComment>) -> Result<(), EditError> {
if let Some(comment) = comment {
require(
!text.is_empty(),
"attached_comment requires nonempty resulting text",
)?;
require(
!comment.text.is_empty(),
"attached_comment.text must be nonempty",
)?;
}
Ok(())
}
impl PlanV2 {
pub fn from_json(json: &str) -> Result<Self, EditError> {
let json = super::without_byte_order_mark(json);
let plan: Self = match serde_json::from_str(json) {
Ok(plan) => plan,
Err(e) => {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(json) {
if let Some(version) = value
.get("schema_version")
.and_then(serde_json::Value::as_u64)
.filter(|&version| version != 2)
{
return Err(unsupported(version));
}
check_operation_fields(&value)?;
}
return Err(invalid(e.to_string()));
}
};
plan.validate()?;
Ok(plan)
}
pub fn validate(&self) -> Result<(), EditError> {
if self.schema_version != 2 {
return Err(unsupported(self.schema_version));
}
require(
hash(&self.source.sha256),
"source.sha256 must be 64 lowercase hexadecimal characters",
)?;
require(
self.author.chars().any(|c| !is_author_whitespace(c)),
"author must contain a non-whitespace character",
)?;
require(
timestamp(&self.date),
"date must be a valid timezone-bearing RFC 3339 timestamp",
)?;
targets(&self.resolve_revisions.accept)?;
targets(&self.resolve_revisions.reject)?;
if let Scope::Selected { targets: selected } = &self.scope {
require(!selected.is_empty(), "selected scope must be nonempty")?;
targets(selected)?;
}
if let Some(context) = &self.source_context {
for item in context {
item.target.validate()?;
require(
item.kind == ContextKind::Opaque || item.text.is_some(),
"paragraph/comment context requires text",
)?;
require(
!item.reason_codes.is_empty()
&& item.reason_codes.iter().all(|s| !s.is_empty())
&& unique(&item.reason_codes),
"reason_codes must be nonempty, unique, nonempty strings",
)?;
}
}
for (index, operation) in self.operations.iter().enumerate() {
operation.validate().map_err(|mut e| {
e.operation = Some(format!("/operations/{index}"));
e
})?;
}
Ok(())
}
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).expect("PlanV2 serializes")
}
}
impl Operation {
pub fn target(&self) -> &Target {
match self {
Self::Replace { target, .. }
| Self::Insert { target, .. }
| Self::Delete { target, .. }
| Self::Rewrite { target, .. }
| Self::InsertParagraph { target, .. }
| Self::DeleteParagraph { target }
| Self::Comment { target, .. }
| Self::ReplyComment { target, .. }
| Self::ResolveComment { target, .. }
| Self::EditComment { target, .. }
| Self::DeleteComment { target, .. }
| Self::Strike { target }
| Self::Restore { target } => target,
}
}
fn validate(&self) -> Result<(), EditError> {
self.target().validate()?;
match self {
Self::Replace { text, .. }
| Self::Rewrite { text, .. }
| Self::Insert { text, .. }
| Self::InsertParagraph { text, .. } => check_payload_text(text, false)?,
_ => {}
}
match self {
Self::Rewrite {
before_sha256,
text,
attached_comment,
..
} => {
require(
hash(before_sha256),
"before_sha256 must be 64 lowercase hexadecimal characters",
)?;
attachment(text, attached_comment.as_ref())?;
}
Self::Replace {
find,
text,
occurrence: selected,
attached_comment,
..
} => {
require(!find.is_empty(), "find must be nonempty")?;
occurrence(*selected)?;
attachment(text, attached_comment.as_ref())?;
}
Self::Delete {
find,
occurrence: selected,
..
} => {
require(!find.is_empty(), "find must be nonempty")?;
occurrence(*selected)?;
}
Self::Insert {
text,
before_text,
after_text,
edge,
occurrence: selected,
attached_comment,
..
} => {
require(!text.is_empty(), "insert.text must be nonempty")?;
require(
usize::from(before_text.is_some())
+ usize::from(after_text.is_some())
+ usize::from(edge.is_some())
== 1,
"insert requires exactly one of before_text, after_text or edge",
)?;
require(
before_text.as_ref().is_none_or(|s| !s.is_empty())
&& after_text.as_ref().is_none_or(|s| !s.is_empty()),
"insertion anchors must be nonempty",
)?;
require(
edge.is_none() || selected.is_none(),
"edge excludes occurrence",
)?;
occurrence(*selected)?;
attachment(text, attached_comment.as_ref())?;
}
Self::InsertParagraph {
text,
attached_comment,
..
} => attachment(text, attached_comment.as_ref())?,
Self::Comment {
text,
find,
occurrence: selected,
through,
..
} => {
require(!text.is_empty(), "comment.text must be nonempty")?;
require(
find.is_none() || through.is_none(),
"comment find and through are mutually exclusive",
)?;
require(
selected.is_none() || find.is_some(),
"comment occurrence requires find",
)?;
require(
find.as_ref().is_none_or(|s| !s.is_empty()),
"comment.find must be nonempty",
)?;
occurrence(*selected)?;
if let Some(target) = through {
target.validate()?;
}
}
Self::ReplyComment { text, .. } | Self::EditComment { text, .. } => {
require(!text.is_empty(), "comment text must be nonempty")?;
}
Self::DeleteParagraph { .. }
| Self::ResolveComment { .. }
| Self::DeleteComment { .. }
| Self::Strike { .. }
| Self::Restore { .. } => {}
}
Ok(())
}
}
fn is_author_whitespace(c: char) -> bool {
c.is_whitespace() || c == '\u{feff}'
}
fn timestamp(value: &str) -> bool {
let b = value.as_bytes();
if b.len() < 20
|| b[4] != b'-'
|| b[7] != b'-'
|| b[10] != b'T'
|| b[13] != b':'
|| b[16] != b':'
{
return false;
}
let number = |start, end| {
value
.get(start..end)
.filter(|s| s.bytes().all(|c| c.is_ascii_digit()))
.and_then(|s| s.parse::<i32>().ok())
};
let (Some(year), Some(month), Some(day), Some(hour), Some(minute), Some(second)) = (
number(0, 4),
number(5, 7),
number(8, 10),
number(11, 13),
number(14, 16),
number(17, 19),
) else {
return false;
};
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
let days = match month {
2 if leap => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
1..=12 => 31,
_ => 0,
};
if year == 0 || !(1..=days).contains(&day) || hour > 23 || minute > 59 || second > 59 {
return false;
}
let mut zone = 19;
if b[zone] == b'.' {
zone += 1;
let start = zone;
while zone < b.len() && b[zone].is_ascii_digit() {
zone += 1;
}
if zone == start {
return false;
}
}
match &b[zone..] {
[b'Z'] => true,
[b'+' | b'-', a, c, b':', d, e] if [a, c, d, e].iter().all(|v| v.is_ascii_digit()) => {
let hours = (a - b'0') * 10 + (c - b'0');
let minutes = (d - b'0') * 10 + (e - b'0');
hours <= 23 && minutes <= 59
}
_ => false,
}
}
pub fn logical_text(dom: &Dom, paragraph: NodeId) -> Result<String, EditError> {
if dom.name(paragraph) != Some(W::p()) {
return Err(codec_error("expected a w:p element"));
}
check_text_content(dom, paragraph)?;
Ok(crate::inspect::project_paragraph(dom, paragraph).text)
}
#[doc(hidden)]
pub fn check_payload_text(text: &str, from_file: bool) -> Result<(), EditError> {
if from_file && text.starts_with('\u{feff}') {
return Err(super::err(
"INVALID_EDIT",
None,
"text file holds U+FEFF at character offset 0, an encoding mark; save exact UTF-8 without a BOM",
));
}
if let Some(offset) = text.chars().position(|c| c == '\r') {
return Err(super::err(
"INVALID_EDIT",
None,
format!(
"text holds U+000D at character offset {offset}; use LF (U+000A) for line breaks"
),
));
}
Ok(())
}
pub fn before_sha256(dom: &Dom, paragraph: NodeId) -> Result<String, EditError> {
Ok(crate::inspect::source_sha256(
logical_text(dom, paragraph)?.as_bytes(),
))
}
fn codec_error(message: impl Into<String>) -> EditError {
super::err("UNSUPPORTED_TEXT_CODEC", None, message)
}
fn check_text_content(dom: &Dom, container: NodeId) -> Result<(), EditError> {
let in_run = dom.name(container) == Some(W::r());
for child in dom.elements(container, None) {
let Some(name) = dom.name(child) else {
return Err(codec_error("unnamed text element"));
};
if name.namespace_name() != W::URI {
return Err(codec_error(format!("unsupported text element {name:?}")));
}
match (in_run, name.local_name()) {
(
false,
"pPr" | "proofErr" | "bookmarkStart" | "bookmarkEnd" | "commentRangeStart"
| "commentRangeEnd" | "permStart" | "permEnd" | "moveFromRangeStart"
| "moveFromRangeEnd" | "moveToRangeStart" | "moveToRangeEnd" | "del" | "moveFrom",
) => {}
(true, "rPr" | "commentReference" | "lastRenderedPageBreak") => {}
(false, "r" | "ins" | "moveTo" | "hyperlink") => check_text_content(dom, child)?,
(true, "t" | "tab") if !dom.has_elements(child) => {}
(true, "br")
if matches!(
dom.attribute(child, &W::type_()),
None | Some("textWrapping")
) && !dom.has_elements(child) => {}
_ => return Err(codec_error(format!("unsupported text element {name:?}"))),
}
}
Ok(())
}