1use 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct CapabilityDraft {
26 pub capability: CapabilityV2,
28 pub replaces: FeatureKind,
30 pub evidence: Vec<FeatureEvidence>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "camelCase")]
37pub struct DecisionOption {
38 pub id: String,
40 pub label: String,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(rename_all = "camelCase")]
47pub struct OwnerDecision {
48 pub id: String,
50 pub feature: FeatureKind,
52 pub question: String,
54 pub options: Vec<DecisionOption>,
56 pub default: String,
58 pub evidence: Vec<FeatureEvidence>,
60}
61
62#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub struct FeatureMap {
66 pub capabilities: Vec<CapabilityDraft>,
68 pub decisions: Vec<OwnerDecision>,
70 pub static_search_index: bool,
72 pub products: bool,
74}
75
76impl FeatureMap {
77 pub fn capability(&self, name: &str) -> Option<&CapabilityV2> {
79 self.capabilities.iter().map(|d| &d.capability).find(|c| c.name == name)
80 }
81
82 pub fn decision(&self, feature: FeatureKind) -> Option<&OwnerDecision> {
84 self.decisions.iter().find(|d| d.feature == feature)
85 }
86
87 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 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
168pub 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}