use crate::{
ActionAddress, ActionContract, ActionDescriptor, ActionParam, Collects, ExecutionLocus,
InputSpec, OperationKind, ResourceSemanticIdentity, ResourceViewDescriptor,
};
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PublishedInput {
None,
Text {
prompt: String,
placeholder: String,
wants_content: bool,
},
}
impl From<&InputSpec> for PublishedInput {
fn from(input: &InputSpec) -> Self {
match input {
InputSpec::None => Self::None,
InputSpec::Text {
prompt,
placeholder,
collects,
} => Self::Text {
prompt: prompt.clone(),
placeholder: placeholder.clone(),
wants_content: *collects == Collects::Content,
},
}
}
}
impl From<&PublishedInput> for InputSpec {
fn from(input: &PublishedInput) -> Self {
match input {
PublishedInput::None => Self::None,
PublishedInput::Text {
prompt,
placeholder,
wants_content,
} => Self::Text {
prompt: prompt.clone(),
placeholder: placeholder.clone(),
collects: if *wants_content {
Collects::Content
} else {
Collects::Words
},
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PublishedAction {
pub resource: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub semantic_identity: Option<ResourceSemanticIdentity>,
pub action: String,
pub resource_kind: String,
pub resource_label: String,
pub action_label: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub did: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub description: Option<String>,
#[serde(default, skip_serializing_if = "crate::ActionState::is_empty")]
pub state: crate::ActionState,
pub operation_kind: OperationKind,
pub params: Vec<ActionParam>,
pub contract: ActionContract,
pub view: Option<ResourceViewDescriptor>,
pub input: PublishedInput,
}
#[derive(Clone, Debug)]
pub struct Offer<'a> {
pub resource: &'a str,
pub resource_kind: &'a str,
pub action: &'a str,
pub label: &'a str,
pub description: Option<&'a str>,
pub kind: crate::ActionKind,
pub operation: OperationKind,
pub confirm: bool,
pub asks: Vec<OfferParam<'a>>,
pub keywords: Vec<&'a str>,
pub icon: Option<&'a str>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OfferParam<'a> {
pub name: &'a str,
pub ty: &'a str,
pub description: Option<&'a str>,
}
impl OfferParam<'_> {
#[must_use]
pub fn param_type(&self) -> crate::ParamType {
match self.ty {
"integer" => crate::ParamType::Integer,
"number" => crate::ParamType::Number,
"boolean" => crate::ParamType::Boolean,
"object" => crate::ParamType::Object,
"array" => crate::ParamType::Array,
"resource" => crate::ParamType::Resource,
"datetime" => crate::ParamType::DateTime,
"secret" => crate::ParamType::Secret,
_ => crate::ParamType::Text,
}
}
}
impl PublishedAction {
#[must_use]
pub fn offered(offer: &Offer<'_>, app_name: &str) -> Self {
use crate::{ActionKind, ConfirmationPolicy, RiskLevel};
let (risk, confirmation) = match (offer.confirm, offer.kind) {
(true, _) => (RiskLevel::Destructive, ConfirmationPolicy::Confirm),
(false, ActionKind::Read) => (RiskLevel::None, ConfirmationPolicy::None),
(false, _) => (RiskLevel::Low, ConfirmationPolicy::None),
};
let params: Vec<ActionParam> = offer
.asks
.iter()
.map(|asked| {
let mut param = ActionParam::required_owned(
"",
asked.param_type(),
asked.description.unwrap_or_default().to_owned(),
);
param.name = asked.name.to_owned().into();
param
})
.collect();
Self {
resource: offer.resource.to_owned(),
semantic_identity: None,
action: offer.action.to_owned(),
resource_kind: offer.resource_kind.to_owned(),
resource_label: app_name.to_owned(),
action_label: offer.label.to_owned(),
keywords: offer
.keywords
.iter()
.map(|word| (*word).to_owned())
.collect(),
did: None,
icon: offer.icon.map(str::to_owned),
description: offer.description.map(str::to_owned),
state: crate::ActionState::default(),
operation_kind: offer.operation,
input: if params.is_empty() {
PublishedInput::None
} else {
PublishedInput::Text {
prompt: offer.label.to_owned(),
placeholder: String::new(),
wants_content: false,
}
},
params,
contract: ActionContract {
kind: offer.kind,
risk,
confirmation,
..ActionContract::default()
},
view: None,
}
}
pub fn check(&self) -> Result<(), String> {
if self.semantic_identity.as_ref().is_some_and(|identity| {
identity.kind.len() > ResourceSemanticIdentity::MAX_KIND_BYTES
|| identity.key.len() > ResourceSemanticIdentity::MAX_KEY_BYTES
|| !identity.is_valid()
|| identity.kind != self.resource_kind
}) {
return Err(format!(
"action `{}`/`{}`: invalid resource semantic identity",
self.resource, self.action
));
}
Ok(())
}
#[must_use]
pub fn domain_resource(&self) -> &str {
match &self.semantic_identity {
Some(identity) if identity.is_valid() => identity.key.as_str(),
_ => self.resource.as_str(),
}
}
pub fn descriptor(&self, locus: ExecutionLocus) -> ActionDescriptor {
ActionDescriptor {
semantic_identity: self.semantic_identity.clone(),
address: ActionAddress::new(&self.resource, &self.action),
resource_kind: self.resource_kind.clone(),
resource_label: self.resource_label.clone(),
action_label: self.action_label.clone(),
keywords: self.keywords.clone(),
did: self.did.clone(),
icon: self.icon.clone(),
description: self.description.clone(),
state: self.state.clone(),
locus,
kind: self.operation_kind,
contract: self.contract.clone(),
input: (&self.input).into(),
params: self.params.clone(),
view: self.view.clone(),
}
}
}
impl From<&ActionDescriptor> for PublishedAction {
fn from(descriptor: &ActionDescriptor) -> Self {
Self {
resource: descriptor.address.resource.clone(),
semantic_identity: descriptor.semantic_identity.clone(),
action: descriptor.address.action.clone(),
resource_kind: descriptor.resource_kind.clone(),
resource_label: descriptor.resource_label.clone(),
action_label: descriptor.action_label.clone(),
keywords: descriptor.keywords.clone(),
did: descriptor.did.clone(),
icon: descriptor.icon.clone(),
description: descriptor.description.clone(),
state: descriptor.state.clone(),
operation_kind: descriptor.kind,
params: descriptor.params.clone(),
contract: descriptor.contract.clone(),
view: descriptor.view.clone(),
input: (&descriptor.input).into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ResourceFields {
pub resource_kind: String,
pub resource_label: String,
pub semantic_identity: Option<ResourceSemanticIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
}
const MARK: char = '\u{1}';
const LABEL_MARK: char = 'L';
fn mark_label(text: &str, label: &str) -> String {
let escaped = text.replace(MARK, "\u{1}\u{1}");
if label.is_empty() || label.contains(MARK) {
return escaped;
}
let mut out = String::with_capacity(escaped.len());
let mut from = 0;
for (at, _) in escaped.match_indices(label) {
let end = at.saturating_add(label.len());
let word = |c: Option<char>| c.is_some_and(char::is_alphanumeric);
let before = escaped.get(..at).and_then(|text| text.chars().next_back());
let after = escaped.get(end..).and_then(|text| text.chars().next());
if word(before) || word(after) {
continue;
}
out.push_str(escaped.get(from..at).unwrap_or_default());
out.push(MARK);
out.push(LABEL_MARK);
from = end;
}
out.push_str(escaped.get(from..).unwrap_or_default());
out
}
fn unmark_label(text: &str, label: &str) -> String {
if !text.contains(MARK) {
return text.to_owned();
}
let mut out = String::with_capacity(text.len().saturating_add(label.len()));
let mut chars = text.chars();
while let Some(c) = chars.next() {
if c != MARK {
out.push(c);
continue;
}
match chars.next() {
Some(LABEL_MARK) => out.push_str(label),
Some(other) => out.push(other),
None => {}
}
}
out
}
impl PublishedAction {
#[must_use]
pub fn shape(&self) -> Self {
let mut shape = Self {
resource: String::new(),
semantic_identity: None,
resource_kind: String::new(),
resource_label: String::new(),
..self.clone()
};
shape.map_words(|text| mark_label(text, &self.resource_label));
shape
}
#[must_use]
pub fn on_resource(&self, resource: &str, fields: &ResourceFields) -> Self {
let mut action = Self {
resource: resource.to_owned(),
semantic_identity: fields.semantic_identity.clone(),
resource_kind: fields.resource_kind.clone(),
resource_label: fields.resource_label.clone(),
..self.clone()
};
action.map_words(|text| unmark_label(text, &fields.resource_label));
action
}
fn map_words(&mut self, map: impl Fn(&str) -> String) {
self.action_label = map(&self.action_label);
if let Some(description) = &mut self.description {
*description = map(description);
}
if let PublishedInput::Text {
prompt,
placeholder,
..
} = &mut self.input
{
*prompt = map(prompt);
*placeholder = map(placeholder);
}
for param in &mut self.params {
param.description = map(¶m.description).into();
}
}
#[must_use]
pub fn resource_fields(&self) -> ResourceFields {
ResourceFields {
resource_kind: self.resource_kind.clone(),
resource_label: self.resource_label.clone(),
semantic_identity: self.semantic_identity.clone(),
workspace: None,
}
}
}