Skip to main content

adk_site/migrate/
mapping.rs

1//! Feature mapping (spec 3.5 ยง7.8 "Feature mapping", N5): every dynamic feature of the legacy
2//! site becomes a [`CapabilityV2`] draft on the edge or a named owner decision.
3//!
4//! | Feature | Becomes |
5//! |---------|---------|
6//! | Contact form | `submit_inquiry`: `NonIdempotent`, consent `contact` |
7//! | Search | A static index plus `search_site`: `ReadOnly` |
8//! | Comments | An owner decision: off (the default) or a held `submit_comment` |
9//! | Shop | Products, plus `get_quote` and `place_order` |
10//! | Bookings | `check_availability` and `book` |
11//! | Logins and member areas | A named owner decision (N5): no account area on the content origin |
12//! | Newsletter sign-up | `subscribe_newsletter`, consent `newsletter` (S17) |
13
14use awp_types::{
15    ApprovalHint, CapabilityEffect, CapabilityV2, ConsentRequirement, ConsentScope, TrustTier,
16};
17use serde::{Deserialize, Serialize};
18use serde_json::{Value, json};
19
20use super::inventory::{FeatureEvidence, FeatureKind, FormField, SiteInventory};
21
22/// A capability drafted for a legacy feature.
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct CapabilityDraft {
26    /// The capability.
27    pub capability: CapabilityV2,
28    /// The feature it replaces.
29    pub replaces: FeatureKind,
30    /// Where the feature was seen.
31    pub evidence: Vec<FeatureEvidence>,
32}
33
34/// One choice of an owner decision.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "camelCase")]
37pub struct DecisionOption {
38    /// A stable id.
39    pub id: String,
40    /// What it does, in plain words.
41    pub label: String,
42}
43
44/// A decision the owner makes about a feature the static site cannot carry as it was.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(rename_all = "camelCase")]
47pub struct OwnerDecision {
48    /// A stable id, `migration.<feature>`.
49    pub id: String,
50    /// The feature.
51    pub feature: FeatureKind,
52    /// The question.
53    pub question: String,
54    /// The choices.
55    pub options: Vec<DecisionOption>,
56    /// The choice that applies until the owner decides.
57    pub default: String,
58    /// Where the feature was seen.
59    pub evidence: Vec<FeatureEvidence>,
60}
61
62/// What the legacy features map to.
63#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub struct FeatureMap {
66    /// Capability drafts for the edge.
67    pub capabilities: Vec<CapabilityDraft>,
68    /// Decisions for the owner.
69    pub decisions: Vec<OwnerDecision>,
70    /// Whether the build writes a static search index.
71    pub static_search_index: bool,
72    /// Whether the site's products migrate as product items.
73    pub products: bool,
74}
75
76impl FeatureMap {
77    /// The drafted capability named `name`.
78    pub fn capability(&self, name: &str) -> Option<&CapabilityV2> {
79        self.capabilities.iter().map(|d| &d.capability).find(|c| c.name == name)
80    }
81
82    /// The decision about `feature`.
83    pub fn decision(&self, feature: FeatureKind) -> Option<&OwnerDecision> {
84        self.decisions.iter().find(|d| d.feature == feature)
85    }
86
87    /// Applies an owner's answer: choosing a held `submit_comment` adds that capability.
88    pub fn answer(&mut self, feature: FeatureKind, option: &str) {
89        if feature == FeatureKind::Comments
90            && option == "held"
91            && self.capability("submit_comment").is_none()
92        {
93            let evidence = self.decision(feature).map(|d| d.evidence.clone()).unwrap_or_default();
94            self.capabilities.push(CapabilityDraft {
95                capability: submit_comment(),
96                replaces: FeatureKind::Comments,
97                evidence,
98            });
99        }
100        if let Some(decision) = self.decisions.iter_mut().find(|d| d.feature == feature) {
101            decision.default = option.to_string();
102        }
103    }
104
105    /// The capability a form of `feature` posts to, for freeze and the generator.
106    pub fn capability_for(&self, feature: FeatureKind) -> Option<&CapabilityV2> {
107        self.capabilities.iter().find(|d| d.replaces == feature).map(|d| &d.capability)
108    }
109}
110
111fn schema(fields: &[FormField], fallback: &[(&str, &str, bool)]) -> Value {
112    let mut properties = serde_json::Map::new();
113    let mut required = Vec::new();
114    let mut add = |name: &str, kind: &str, needed: bool| {
115        let property = match kind {
116            "email" => json!({ "type": "string", "format": "email", "maxLength": 254 }),
117            "number" | "range" => json!({ "type": "number" }),
118            "date" => json!({ "type": "string", "format": "date" }),
119            "datetime-local" => json!({ "type": "string", "format": "date-time" }),
120            "checkbox" => json!({ "type": "boolean" }),
121            "textarea" => json!({ "type": "string", "maxLength": 5000 }),
122            _ => json!({ "type": "string", "maxLength": 500 }),
123        };
124        properties.insert(name.to_string(), property);
125        if needed {
126            required.push(Value::String(name.to_string()));
127        }
128    };
129    if fields.is_empty() {
130        for (name, kind, needed) in fallback {
131            add(name, kind, *needed);
132        }
133    } else {
134        for field in fields {
135            let name: String = field
136                .name
137                .trim_start_matches("your-")
138                .chars()
139                .map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' })
140                .collect();
141            add(&name, &field.input_type, field.required);
142        }
143    }
144    json!({ "type": "object", "properties": properties, "required": required, "additionalProperties": false })
145}
146
147fn submit_comment() -> CapabilityV2 {
148    CapabilityV2 {
149        input_schema: Some(json!({
150            "type": "object",
151            "properties": {
152                "path": { "type": "string", "maxLength": 500 },
153                "name": { "type": "string", "maxLength": 100 },
154                "comment": { "type": "string", "maxLength": 5000 }
155            },
156            "required": ["path", "comment"],
157            "additionalProperties": false
158        })),
159        ..CapabilityV2::new(
160            "submit_comment",
161            "Submit a comment on a page; every comment is held for moderation",
162            CapabilityEffect::NonIdempotent,
163        )
164        .with_approval(ApprovalHint::Always)
165    }
166}
167
168/// Maps the inventory's features to capability drafts and owner decisions.
169///
170/// # Example
171///
172/// ```rust
173/// use adk_site::migrate::mapping::map_features;
174/// use adk_site::migrate::{DetectedFeature, FeatureKind, SiteInventory, SourceKind};
175///
176/// let mut inventory = SiteInventory::new(SourceKind::Crawl, chrono::Utc::now());
177/// inventory.add_feature(DetectedFeature { kind: FeatureKind::ContactForm, evidence: vec![], fields: vec![] });
178/// let map = map_features(&inventory);
179/// let inquiry = map.capability("submit_inquiry").unwrap();
180/// assert!(inquiry.requires_idempotency());
181/// assert_eq!(inquiry.consent.as_ref().unwrap().scope.as_str(), "contact");
182/// ```
183pub fn map_features(inventory: &SiteInventory) -> FeatureMap {
184    let mut map = FeatureMap::default();
185    let mut features = inventory.features.clone();
186    features.sort_by_key(|f| f.kind);
187    for feature in features {
188        let evidence = feature.evidence.clone();
189        let mut draft = |capability: CapabilityV2| {
190            map.capabilities.push(CapabilityDraft {
191                capability,
192                replaces: feature.kind,
193                evidence: evidence.clone(),
194            });
195        };
196        match feature.kind {
197            FeatureKind::ContactForm => {
198                let mut capability = CapabilityV2::new(
199                    "submit_inquiry",
200                    "Send the site's owner an enquiry",
201                    CapabilityEffect::NonIdempotent,
202                );
203                capability.consent = Some(ConsentRequirement {
204                    scope: ConsentScope::Custom("contact".into()),
205                    policy_version: "1".into(),
206                });
207                capability.input_schema = Some(schema(
208                    &feature.fields,
209                    &[("name", "text", true), ("email", "email", true), ("message", "textarea", true)],
210                ));
211                draft(capability);
212            }
213            FeatureKind::Search => {
214                let mut capability =
215                    CapabilityV2::new("search_site", "Search the site's pages", CapabilityEffect::ReadOnly);
216                capability.input_schema = Some(json!({
217                    "type": "object",
218                    "properties": { "query": { "type": "string", "maxLength": 200 } },
219                    "required": ["query"],
220                    "additionalProperties": false
221                }));
222                draft(capability);
223                map.static_search_index = true;
224            }
225            FeatureKind::Shop => {
226                let mut quote = CapabilityV2::new(
227                    "get_quote",
228                    "Quote products at their published prices",
229                    CapabilityEffect::Idempotent,
230                )
231                .with_min_trust(TrustTier::Known);
232                quote.input_schema = Some(json!({
233                    "type": "object",
234                    "properties": { "items": { "type": "array", "items": {
235                        "type": "object",
236                        "properties": { "sku": { "type": "string" }, "quantity": { "type": "integer", "minimum": 1 } },
237                        "required": ["sku", "quantity"]
238                    } } },
239                    "required": ["items"]
240                }));
241                draft(quote);
242                let mut order = CapabilityV2::new(
243                    "place_order",
244                    "Place an order against a quote",
245                    CapabilityEffect::NonIdempotent,
246                )
247                .with_min_trust(TrustTier::Known);
248                order.input_schema = Some(json!({
249                    "type": "object",
250                    "properties": { "quoteId": { "type": "string" } },
251                    "required": ["quoteId"]
252                }));
253                draft(order);
254                map.products = true;
255            }
256            FeatureKind::Bookings => {
257                let mut availability = CapabilityV2::new(
258                    "check_availability",
259                    "List open booking slots",
260                    CapabilityEffect::ReadOnly,
261                );
262                availability.input_schema = Some(json!({
263                    "type": "object",
264                    "properties": { "from": { "type": "string", "format": "date" }, "to": { "type": "string", "format": "date" } }
265                }));
266                draft(availability);
267                let mut book = CapabilityV2::new("book", "Book a slot", CapabilityEffect::NonIdempotent)
268                    .with_min_trust(TrustTier::Known);
269                book.input_schema = Some(schema(
270                    &feature.fields,
271                    &[("slot", "text", true), ("name", "text", true), ("email", "email", true)],
272                ));
273                draft(book);
274            }
275            FeatureKind::Newsletter => {
276                let mut capability = CapabilityV2::new(
277                    "subscribe_newsletter",
278                    "Subscribe to the site's newsletter",
279                    CapabilityEffect::Idempotent,
280                );
281                capability.consent = Some(ConsentRequirement {
282                    scope: ConsentScope::Newsletter,
283                    policy_version: "1".into(),
284                });
285                capability.input_schema = Some(schema(&[], &[("email", "email", true)]));
286                draft(capability);
287            }
288            FeatureKind::Comments => map.decisions.push(OwnerDecision {
289                id: "migration.comments".into(),
290                feature: FeatureKind::Comments,
291                question: "The old site takes comments. Turn comments off, or accept them through a capability that holds every comment for your moderation?".into(),
292                options: vec![
293                    DecisionOption { id: "off".into(), label: "Turn comments off; existing comments are not published".into() },
294                    DecisionOption { id: "held".into(), label: "Accept comments, each held until you approve it".into() },
295                ],
296                default: "off".into(),
297                evidence,
298            }),
299            FeatureKind::Login | FeatureKind::MemberArea => {
300                if map.decision(FeatureKind::MemberArea).is_some() || map.decision(FeatureKind::Login).is_some() {
301                    if let Some(existing) = map.decisions.iter_mut().find(|d| matches!(d.feature, FeatureKind::Login | FeatureKind::MemberArea)) {
302                        existing.evidence.extend(evidence);
303                    }
304                    continue;
305                }
306                map.decisions.push(OwnerDecision {
307                    id: "migration.accounts".into(),
308                    feature: feature.kind,
309                    question: "The old site has logins or a member area. The new site serves no accounts from its pages. What happens to that area?".into(),
310                    options: vec![
311                        DecisionOption { id: "remove".into(), label: "Remove the login and member pages".into() },
312                        DecisionOption { id: "named_service".into(), label: "Link to a service you name that holds the accounts".into() },
313                        DecisionOption { id: "later".into(), label: "Leave the account area out until authenticated areas are supported".into() },
314                    ],
315                    default: "later".into(),
316                    evidence,
317                });
318            }
319        }
320    }
321    if inventory.items.iter().any(|i| i.kind == awp_types::ContentKind::Product) {
322        map.products = true;
323    }
324    map
325}