1use crate::{
9 ActionAddress, ActionContract, ActionDescriptor, ActionParam, Collects, ExecutionLocus,
10 InputSpec, OperationKind, ResourceSemanticIdentity, ResourceViewDescriptor,
11};
12
13#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16pub enum PublishedInput {
17 None,
18 Text {
19 prompt: String,
20 placeholder: String,
21 wants_content: bool,
24 },
25}
26
27impl From<&InputSpec> for PublishedInput {
28 fn from(input: &InputSpec) -> Self {
29 match input {
30 InputSpec::None => Self::None,
31 InputSpec::Text {
32 prompt,
33 placeholder,
34 collects,
35 } => Self::Text {
36 prompt: prompt.clone(),
37 placeholder: placeholder.clone(),
38 wants_content: *collects == Collects::Content,
39 },
40 }
41 }
42}
43
44impl From<&PublishedInput> for InputSpec {
45 fn from(input: &PublishedInput) -> Self {
46 match input {
47 PublishedInput::None => Self::None,
48 PublishedInput::Text {
49 prompt,
50 placeholder,
51 wants_content,
52 } => Self::Text {
53 prompt: prompt.clone(),
54 placeholder: placeholder.clone(),
55 collects: if *wants_content {
56 Collects::Content
57 } else {
58 Collects::Words
59 },
60 },
61 }
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
67pub struct PublishedAction {
68 pub resource: String,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub semantic_identity: Option<ResourceSemanticIdentity>,
71 pub action: String,
72 pub resource_kind: String,
73 pub resource_label: String,
74 pub action_label: String,
75 #[serde(default, skip_serializing_if = "Vec::is_empty")]
77 pub keywords: Vec<String>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub did: Option<String>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub icon: Option<String>,
84 pub description: Option<String>,
85 #[serde(default, skip_serializing_if = "crate::ActionState::is_empty")]
87 pub state: crate::ActionState,
88 pub operation_kind: OperationKind,
89 pub params: Vec<ActionParam>,
91 pub contract: ActionContract,
93 pub view: Option<ResourceViewDescriptor>,
94 pub input: PublishedInput,
95}
96
97#[derive(Clone, Debug)]
101pub struct Offer<'a> {
102 pub resource: &'a str,
103 pub resource_kind: &'a str,
104 pub action: &'a str,
105 pub label: &'a str,
106 pub description: Option<&'a str>,
107 pub kind: crate::ActionKind,
108 pub operation: OperationKind,
109 pub confirm: bool,
111 pub asks: Vec<OfferParam<'a>>,
113 pub keywords: Vec<&'a str>,
114 pub icon: Option<&'a str>,
115}
116
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub struct OfferParam<'a> {
121 pub name: &'a str,
122 pub ty: &'a str,
123 pub description: Option<&'a str>,
124}
125
126impl OfferParam<'_> {
127 #[must_use]
130 pub fn param_type(&self) -> crate::ParamType {
131 match self.ty {
132 "integer" => crate::ParamType::Integer,
133 "number" => crate::ParamType::Number,
134 "boolean" => crate::ParamType::Boolean,
135 "object" => crate::ParamType::Object,
136 "array" => crate::ParamType::Array,
137 "resource" => crate::ParamType::Resource,
138 "datetime" => crate::ParamType::DateTime,
139 "secret" => crate::ParamType::Secret,
140 _ => crate::ParamType::Text,
141 }
142 }
143}
144
145impl PublishedAction {
146 #[must_use]
148 pub fn offered(offer: &Offer<'_>, app_name: &str) -> Self {
149 use crate::{ActionKind, ConfirmationPolicy, RiskLevel};
150 let (risk, confirmation) = match (offer.confirm, offer.kind) {
151 (true, _) => (RiskLevel::Destructive, ConfirmationPolicy::Confirm),
152 (false, ActionKind::Read) => (RiskLevel::None, ConfirmationPolicy::None),
153 (false, _) => (RiskLevel::Low, ConfirmationPolicy::None),
154 };
155 let params: Vec<ActionParam> = offer
156 .asks
157 .iter()
158 .map(|asked| {
159 let mut param = ActionParam::required_owned(
160 "",
161 asked.param_type(),
162 asked.description.unwrap_or_default().to_owned(),
163 );
164 param.name = asked.name.to_owned().into();
165 param
166 })
167 .collect();
168 Self {
169 resource: offer.resource.to_owned(),
170 semantic_identity: None,
171 action: offer.action.to_owned(),
172 resource_kind: offer.resource_kind.to_owned(),
173 resource_label: app_name.to_owned(),
174 action_label: offer.label.to_owned(),
175 keywords: offer
176 .keywords
177 .iter()
178 .map(|word| (*word).to_owned())
179 .collect(),
180 did: None,
181 icon: offer.icon.map(str::to_owned),
182 description: offer.description.map(str::to_owned),
183 state: crate::ActionState::default(),
184 operation_kind: offer.operation,
185 input: if params.is_empty() {
186 PublishedInput::None
187 } else {
188 PublishedInput::Text {
189 prompt: offer.label.to_owned(),
190 placeholder: String::new(),
191 wants_content: false,
192 }
193 },
194 params,
195 contract: ActionContract {
196 kind: offer.kind,
197 risk,
198 confirmation,
199 ..ActionContract::default()
200 },
201 view: None,
202 }
203 }
204
205 pub fn check(&self) -> Result<(), String> {
208 if self.semantic_identity.as_ref().is_some_and(|identity| {
209 identity.kind.len() > ResourceSemanticIdentity::MAX_KIND_BYTES
210 || identity.key.len() > ResourceSemanticIdentity::MAX_KEY_BYTES
211 || !identity.is_valid()
212 || identity.kind != self.resource_kind
213 }) {
214 return Err(format!(
215 "action `{}`/`{}`: invalid resource semantic identity",
216 self.resource, self.action
217 ));
218 }
219 Ok(())
220 }
221
222 #[must_use]
225 pub fn domain_resource(&self) -> &str {
226 match &self.semantic_identity {
227 Some(identity) if identity.is_valid() => identity.key.as_str(),
228 _ => self.resource.as_str(),
229 }
230 }
231
232 pub fn descriptor(&self, locus: ExecutionLocus) -> ActionDescriptor {
235 ActionDescriptor {
236 semantic_identity: self.semantic_identity.clone(),
237 address: ActionAddress::new(&self.resource, &self.action),
238 resource_kind: self.resource_kind.clone(),
239 resource_label: self.resource_label.clone(),
240 action_label: self.action_label.clone(),
241 keywords: self.keywords.clone(),
242 did: self.did.clone(),
243 icon: self.icon.clone(),
244 description: self.description.clone(),
245 state: self.state.clone(),
246 locus,
247 kind: self.operation_kind,
248 contract: self.contract.clone(),
249 input: (&self.input).into(),
250 params: self.params.clone(),
251 view: self.view.clone(),
252 }
253 }
254}
255
256impl From<&ActionDescriptor> for PublishedAction {
257 fn from(descriptor: &ActionDescriptor) -> Self {
258 Self {
259 resource: descriptor.address.resource.clone(),
260 semantic_identity: descriptor.semantic_identity.clone(),
261 action: descriptor.address.action.clone(),
262 resource_kind: descriptor.resource_kind.clone(),
263 resource_label: descriptor.resource_label.clone(),
264 action_label: descriptor.action_label.clone(),
265 keywords: descriptor.keywords.clone(),
266 did: descriptor.did.clone(),
267 icon: descriptor.icon.clone(),
268 description: descriptor.description.clone(),
269 state: descriptor.state.clone(),
270 operation_kind: descriptor.kind,
271 params: descriptor.params.clone(),
272 contract: descriptor.contract.clone(),
273 view: descriptor.view.clone(),
274 input: (&descriptor.input).into(),
275 }
276 }
277}
278
279#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
281pub struct ResourceFields {
282 pub resource_kind: String,
283 pub resource_label: String,
284 pub semantic_identity: Option<ResourceSemanticIdentity>,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
288 pub workspace: Option<String>,
289}
290
291const MARK: char = '\u{1}';
294const LABEL_MARK: char = 'L';
295
296fn mark_label(text: &str, label: &str) -> String {
300 let escaped = text.replace(MARK, "\u{1}\u{1}");
301 if label.is_empty() || label.contains(MARK) {
302 return escaped;
303 }
304 let mut out = String::with_capacity(escaped.len());
305 let mut from = 0;
306 for (at, _) in escaped.match_indices(label) {
307 let end = at.saturating_add(label.len());
308 let word = |c: Option<char>| c.is_some_and(char::is_alphanumeric);
309 let before = escaped.get(..at).and_then(|text| text.chars().next_back());
310 let after = escaped.get(end..).and_then(|text| text.chars().next());
311 if word(before) || word(after) {
312 continue;
313 }
314 out.push_str(escaped.get(from..at).unwrap_or_default());
315 out.push(MARK);
316 out.push(LABEL_MARK);
317 from = end;
318 }
319 out.push_str(escaped.get(from..).unwrap_or_default());
320 out
321}
322
323fn unmark_label(text: &str, label: &str) -> String {
325 if !text.contains(MARK) {
326 return text.to_owned();
327 }
328 let mut out = String::with_capacity(text.len().saturating_add(label.len()));
329 let mut chars = text.chars();
330 while let Some(c) = chars.next() {
331 if c != MARK {
332 out.push(c);
333 continue;
334 }
335 match chars.next() {
336 Some(LABEL_MARK) => out.push_str(label),
337 Some(other) => out.push(other),
338 None => {}
339 }
340 }
341 out
342}
343
344impl PublishedAction {
345 #[must_use]
352 pub fn shape(&self) -> Self {
353 let mut shape = Self {
354 resource: String::new(),
355 semantic_identity: None,
356 resource_kind: String::new(),
357 resource_label: String::new(),
358 ..self.clone()
359 };
360 shape.map_words(|text| mark_label(text, &self.resource_label));
361 shape
362 }
363
364 #[must_use]
367 pub fn on_resource(&self, resource: &str, fields: &ResourceFields) -> Self {
368 let mut action = Self {
369 resource: resource.to_owned(),
370 semantic_identity: fields.semantic_identity.clone(),
371 resource_kind: fields.resource_kind.clone(),
372 resource_label: fields.resource_label.clone(),
373 ..self.clone()
374 };
375 action.map_words(|text| unmark_label(text, &fields.resource_label));
376 action
377 }
378
379 fn map_words(&mut self, map: impl Fn(&str) -> String) {
382 self.action_label = map(&self.action_label);
383 if let Some(description) = &mut self.description {
384 *description = map(description);
385 }
386 if let PublishedInput::Text {
387 prompt,
388 placeholder,
389 ..
390 } = &mut self.input
391 {
392 *prompt = map(prompt);
393 *placeholder = map(placeholder);
394 }
395 for param in &mut self.params {
396 param.description = map(¶m.description).into();
397 }
398 }
399
400 #[must_use]
401 pub fn resource_fields(&self) -> ResourceFields {
402 ResourceFields {
403 resource_kind: self.resource_kind.clone(),
404 resource_label: self.resource_label.clone(),
405 semantic_identity: self.semantic_identity.clone(),
406 workspace: None,
407 }
408 }
409}