extern crate self as tilo_resource;
mod absolute_path;
pub mod action;
mod apply_cache;
pub mod batch;
pub mod child;
pub mod children;
mod chunk_map;
mod clock;
pub mod collection;
#[cfg(test)]
mod concurrent_text_tests;
pub mod content;
mod cow;
mod dates;
mod search_preview;
pub use search_preview::SearchPreview;
pub mod delta;
pub mod derived;
mod describe;
pub mod diff;
pub mod effect;
pub mod evolution;
pub mod footprint;
pub mod genesis;
pub mod group;
pub mod history;
pub mod items;
mod kept;
pub mod keyed;
pub mod kind;
pub mod label;
mod map;
pub mod members;
pub mod model;
mod non_blank;
pub mod order;
pub mod ordered;
pub mod origin;
pub mod path;
pub mod reactions;
pub mod read;
pub mod reader;
mod recents;
pub mod recording;
pub mod replica;
pub mod resource;
pub mod row;
pub mod schema;
pub mod schema_check;
pub mod search_default;
pub use tilo_actions::search_index;
pub mod shape;
pub mod share;
pub mod sort;
pub mod status;
pub mod storage;
pub mod stored_items;
pub mod surface;
pub mod table;
pub mod text;
pub mod unreadable;
mod upsert;
mod value;
pub mod vocabulary;
pub mod words;
pub use __private::FlatFields;
pub use absolute_path::{AbsolutePath, RelativePath};
pub use action::{
ActionCx, ActionKey, ActionKind, ActionRef, Binds, Invoke, Mapped, NoParams, Operation,
Outcome, Params, Refusal, Reverting, Stamped, TryMapped, Undoing, fresh_uuid, invoking_member,
invoking_name, minted_entry, minted_ids, minted_keys, restore_minted, reverting_type,
take_minted,
};
pub use automerge::Patch;
pub use child::{child_resource_id, publish_child};
pub use children::{ChildList, ChildRef, Children, Trashed};
pub use clock::HybridClock;
pub use collection::{
Collection, Id, Membership, Quarantined, stored_entry, stored_ids, stored_item,
};
pub use delta::{Delta, ObjPath, Touch, Touched, Tracker};
pub use derived::{Bound, Derived};
pub use effect::{
Answers, Effect, EffectDecl, EffectDecodeError, EffectOffload, EffectTarget, NoEffect, decode,
offer,
};
pub use evolution::Unreadable;
pub use group::{ActionGroup, GROUP, GROUP_PARAM};
pub use keyed::{ById, Identified, ItemStorage, Items, Keyed};
pub use kind::{Kinds, ResourceKind};
pub use map::Map;
pub use model::{
Atom, Doc, Fields, Fresh, LocatedAt, MapSlot, Model, ModelError, Slot, VARIANT_KEY, edit_whole,
load_slot, read_key, read_slots, refresh_key, take_slot, write_key, write_key_changed,
};
pub use non_blank::{Blank, NonBlank};
pub use ordered::{Arranged, Ordered};
pub use origin::Origin;
pub use path::{
At, Edit, EditOp, OP_ARGUMENTS, Operations, Path, Segment, Settable, op_argument_schema,
op_arguments, op_usage, outbox_settle_arguments,
};
pub use reactions::{
Reaction, ReactionGroup, Reactions, Reactor, custom_emoji_name, reaction_emoji,
valid_custom_emoji_name,
};
pub use reader::{Demand, Reader, heads_of};
pub use recents::Recents;
pub use replica::{AppNamed, NoApp, Replica};
pub use resource::{
APPLY, APPLY_PARAM, ActionDecl, BuildAction, EDIT_PARAM, FIELD_EDIT, HeadInputs, NamesItem,
NoAction, Place, Resource, ScopeDecl, SearchBody, SearchEntry, SearchPiece, SearchRow,
SearchRowShape, SearchText, SearchWeight, SharedResource, bind_declaration, build_action,
by_app_refusal, child_by_id, declaration_spec, default_search, encode, head_inputs, need_of,
origin_now_ms, publish, publish_head, publish_head_of, reset_type_schemas, scope_contains,
spec_kind, state_from_reading, with_origin_clock,
};
pub use row::{Handle, LiveRow, RowBindings, typed_resource};
pub use schema::JsonSchema;
pub use shape::{FieldShape, Shape, StoredText, Trust, absent_scalar, stored_text};
pub use status::EffectStatus;
pub use storage::{Bytes, Counter, Grid, Outbox, OutboxEntry, Set, Settled};
pub use surface::Surface;
pub use text::{PlainText, TextEdit};
pub use tilo_action_policy::edits::Weaker;
pub use tilo_action_policy::{DIRECT_CONVERSATION_PREFIX, MemberId, PersonId};
pub use tilo_actions::surface::{FieldType, TypeSet};
pub use tilo_actions::{Acting, Availability};
pub use tilo_resource_macros::{Effect, JsonSchema, Model, Row, committed_surface, resource};
pub use tilo_sort::{Frecency, frecency};
pub use unreadable::withhold_document_actions;
pub use vocabulary::{Built, Declaration, Vocabulary, vocabulary};
#[macro_export]
macro_rules! word {
($($input:tt)*) => {
$crate::__private::word!($crate, $($input)*)
};
}
#[doc(hidden)]
pub mod __private {
pub use automerge::{ObjId, ObjType, Patch, ROOT, ReadDoc, ScalarValue, Value};
pub use serde;
pub use serde_json;
pub use tilo_actions::{
ActionArgs, ActionKind, ActionParam, ActionRegistry, ActionSpec, Audience, ChangeKind,
HOST_RENDER_TAG, OperationKind, PROMPTED_PARAM, ParamType, ResourceSpec, ResourceViewSpec,
RiskLevel, SCREEN_PLACE_TAG, SCREEN_TAG, StepKind, picked_address_schema,
picked_resource_schema,
};
pub use tilo_resource_macros::word;
pub use crate::apply_cache::forget_all;
#[must_use]
pub fn holds_nested_items(
record: &crate::table::ResourceDesc,
state: &dyn std::any::Any,
action: &crate::items::ItemAction,
) -> bool {
let Some(field) = action.collection else {
return false;
};
let mut path: Vec<&str> = action.within.to_vec();
path.push(field);
crate::table::holds_nested_items(record, state, &path)
}
pub struct Snapshot<'a, T>(pub &'a T);
pub trait SnapshotByClone<T> {
fn snapshot(&self) -> Option<T>;
}
impl<T: Clone> SnapshotByClone<T> for &Snapshot<'_, T> {
fn snapshot(&self) -> Option<T> {
Some(self.0.clone())
}
}
pub trait SnapshotUnavailable<T> {
fn snapshot(&self) -> Option<T>;
}
impl<T> SnapshotUnavailable<T> for Snapshot<'_, T> {
fn snapshot(&self) -> Option<T> {
None
}
}
use crate::model::LocatedAt as _;
pub fn edit_at<T: crate::Model>(
doc: &mut crate::Doc,
obj: &ObjId,
key: &str,
rest: &[crate::Segment],
op: &crate::EditOp,
cx: &mut crate::ActionCx,
) -> Result<(), crate::ModelError> {
T::edit(doc, crate::Slot::Key(obj, key), rest, op, cx).located(key)
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum VerbUndo {
Revert,
Compensation,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum VerbAnswer {
Created,
Made,
Queued,
}
#[derive(Clone)]
#[allow(
clippy::struct_excessive_bools,
reason = "one independent `#[action(...)]` flag each, as the macro reads them"
)]
pub struct VerbDecl {
pub id: &'static str,
pub label: crate::label::Word,
pub keywords: &'static [&'static str],
pub icon: Option<&'static str>,
pub did: Option<&'static str>,
pub description: &'static str,
pub kind: ActionKind,
pub by_arguments: bool,
pub field: Option<&'static str>,
pub destructive: bool,
pub irreversible: bool,
pub housekeeping: bool,
pub answer: VerbAnswer,
pub incoming_message: bool,
pub undo: VerbUndo,
pub audience: tilo_actions::Audience,
pub collects: Option<&'static str>,
pub content: Option<&'static str>,
pub item_field: Option<&'static str>,
pub item: Option<&'static str>,
pub writes: &'static [&'static str],
pub step: Option<tilo_actions::StepKind>,
pub shape: crate::Shape,
pub params: &'static [ParamDecl],
}
#[derive(Clone, Copy)]
pub struct ParamDecl {
pub name: &'static str,
pub ty: ParamTypeOf,
pub description: &'static str,
pub schema: fn() -> serde_json::Value,
pub optional: bool,
pub place: PlaceIn,
pub example: Option<fn() -> serde_json::Value>,
pub flat: bool,
pub flat_types: Option<crate::surface::FlatTypes>,
pub content: bool,
pub field_type: crate::vocabulary::ParamFieldType,
}
#[derive(Clone, Copy)]
pub enum ParamTypeOf {
Known(ParamType),
Schema(fn() -> serde_json::Value),
}
pub trait FlatFields {
fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)>;
}
impl<T: crate::JsonSchema> FlatFields for T {
fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)> {
let crate::FieldType::Named(name) = <T as crate::JsonSchema>::field_type(types) else {
return Vec::new();
};
types
.get(&name)
.map(|record| {
record
.fields
.iter()
.map(|field| (field.name.clone(), field.ty.clone()))
.collect()
})
.unwrap_or_default()
}
}
#[must_use]
pub fn params_of(params: &[ParamDecl]) -> Vec<ActionParam> {
let mut out = Vec::with_capacity(params.len());
for param in params {
if param.flat {
out.extend(flat_params(&(param.schema)()));
continue;
}
let ty = match param.ty {
ParamTypeOf::Known(ty) => ty,
ParamTypeOf::Schema(schema) => param_type_of(&schema()),
};
let declared = declared_param(
param.name,
ty,
param.description,
param.schema,
param.optional,
param.place,
param.example,
);
out.push(if param.content {
declared.as_content()
} else {
declared
});
}
out
}
pub fn declare<R: crate::Resource>(
verb: VerbDecl,
build: fn(&ActionArgs, i64) -> Result<R::Action, String>,
) -> crate::ActionDecl<R> {
let builds: crate::vocabulary::Builds =
std::sync::Arc::new(move |args, now_ms| match build(args, now_ms) {
Ok(action) => Ok(crate::Built::of::<R>(action)),
Err(reason) => Err(reason),
});
crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
}
pub fn declare_verb<R, O>(verb: VerbDecl) -> crate::ActionDecl<R>
where
R: crate::Resource<Action = crate::Stamped<O>>,
O: serde::de::DeserializeOwned,
{
let (id, content) = (verb.id, verb.content);
let builds: crate::vocabulary::Builds = std::sync::Arc::new(move |args, now_ms| {
let arguments = verb_arguments(args, content);
match build_stamped::<O>(id, &arguments, now_ms) {
Ok(action) => Ok(crate::Built::of::<R>(action)),
Err(reason) => Err(reason),
}
});
crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
}
fn verb_arguments(
args: &ActionArgs,
content: Option<&'static str>,
) -> serde_json::Map<String, serde_json::Value> {
let mut arguments = args.to_json();
if let Some(content) = content
&& let Some(hash) = arguments.remove(PROMPTED_PARAM)
{
arguments.insert(String::from(content), hash);
}
arguments
}
fn verb_declaration(
vocabulary: &crate::Vocabulary,
verb: VerbDecl,
build: crate::vocabulary::Builds,
) -> crate::Declaration {
let written = verb.label.source;
let mut decl = crate::Declaration::new(
vocabulary,
verb.id,
written.to_owned(),
params_of(verb.params),
build,
);
decl.word = Some(verb.label);
decl.param_types = verb
.params
.iter()
.filter(|param| !param.flat)
.map(|param| (param.name, param.field_type))
.collect();
decl.flat_types = verb
.params
.iter()
.find(|param| param.flat)
.and_then(|param| param.flat_types);
decl.kind = verb.kind;
decl.keywords = verb
.keywords
.iter()
.map(|word| (*word).to_owned())
.collect();
decl.icon = verb.icon.map(str::to_owned);
decl.did = verb.did.map(str::to_owned);
decl.by_arguments = verb.by_arguments;
decl.writes = crate::footprint::declared(verb.shape, verb.item_field, verb.writes);
decl.item = verb.item;
let description = verb
.description
.strip_prefix(written)
.map_or(verb.description, |rest| {
rest.trim_start_matches('.').trim_start()
});
if !description.is_empty() {
decl.description = Some(description.to_owned());
}
decl.field = verb.field;
decl.destructive = verb.destructive;
decl.step = verb
.step
.or_else(|| verb.destructive.then_some(tilo_actions::StepKind::Delete));
decl.creates = (decl.step == Some(tilo_actions::StepKind::Create))
.then(|| verb.writes.first().copied())
.flatten();
if verb.irreversible {
decl.tags.push(tilo_actions::IRREVERSIBLE_TAG.to_owned());
}
if verb.housekeeping {
decl.tags.push(tilo_actions::HOUSEKEEPING_TAG.to_owned());
}
if verb.incoming_message {
decl.tags
.push(tilo_actions::INCOMING_MESSAGE_TAG.to_owned());
}
if let Some(tag) = verb.audience.tag() {
decl.tags.push(tag.to_owned());
}
if verb.undo == VerbUndo::Compensation {
decl.tags
.push(tilo_actions::COMPENSATED_UNDO_TAG.to_owned());
}
match verb.answer {
VerbAnswer::Created => {}
VerbAnswer::Made => {
decl.result = Some(tilo_actions::ResultSpec::Json {
schema: serde_json::json!({"type": "object"}),
});
}
VerbAnswer::Queued => {
decl.result = Some(tilo_actions::ResultSpec::Json {
schema: serde_json::json!({"type": ["object", "array", "null"]}),
});
}
}
if let Some(prompt) = verb.collects {
decl.content = Some(prompt.to_owned());
}
decl
}
#[derive(Clone, Copy)]
pub enum PlaceIn {
Nowhere,
Record,
Field(&'static str),
}
#[must_use]
pub fn declared_param(
name: impl Into<String>,
ty: ParamType,
description: impl Into<String>,
schema: fn() -> serde_json::Value,
optional: bool,
place: PlaceIn,
example: Option<fn() -> serde_json::Value>,
) -> ActionParam {
let name = name.into();
let description = description.into();
let param = if optional {
ActionParam::optional_owned(name, ty, description)
} else {
ActionParam::required_owned(name, ty, description)
}
.with_schema(param_schema(schema(), "", example.map(|example| example())));
match place {
PlaceIn::Nowhere => param,
PlaceIn::Record => param.as_place(),
PlaceIn::Field(field) => param.as_place_in(field),
}
}
#[must_use]
pub fn param_schema(
schema: serde_json::Value,
description: &str,
example: Option<serde_json::Value>,
) -> serde_json::Value {
let mut schema = crate::schema::describe(schema, description);
if let (Some(example), serde_json::Value::Object(fields)) = (example, &mut schema) {
fields.insert("examples".into(), serde_json::Value::Array(vec![example]));
}
schema
}
pub struct DefaultOf<T>(::core::marker::PhantomData<T>);
impl<T> DefaultOf<T> {
#[must_use]
pub const fn new() -> Self {
Self(::core::marker::PhantomData)
}
}
impl<T> Default for DefaultOf<T> {
fn default() -> Self {
Self::new()
}
}
pub trait HasDefault<T> {
fn default_value(&self) -> Option<T>;
}
impl<T: Default> HasDefault<T> for DefaultOf<T> {
fn default_value(&self) -> Option<T> {
Some(T::default())
}
}
pub trait NoDefault<T> {
fn default_value(&self) -> Option<T>;
}
impl<T> NoDefault<T> for &DefaultOf<T> {
fn default_value(&self) -> Option<T> {
None
}
}
pub trait DeclaredNumber {
fn declared_number(&self) -> Option<f64>;
}
macro_rules! declared_number {
($($ty:ty),*) => {$(
impl DeclaredNumber for $ty {
#[allow(clippy::cast_precision_loss, clippy::cast_lossless, reason = "a range bound is a numeric limit far below 2^53")]
fn declared_number(&self) -> Option<f64> {
Some(*self as f64)
}
}
)*};
}
declared_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
impl<T: DeclaredNumber> DeclaredNumber for Option<T> {
fn declared_number(&self) -> Option<f64> {
self.as_ref().and_then(DeclaredNumber::declared_number)
}
}
pub trait DeclaredChoice {
fn declared_choice(&self) -> Option<&str>;
}
impl DeclaredChoice for String {
fn declared_choice(&self) -> Option<&str> {
Some(self)
}
}
impl<T: DeclaredChoice> DeclaredChoice for Option<T> {
fn declared_choice(&self) -> Option<&str> {
self.as_ref().and_then(DeclaredChoice::declared_choice)
}
}
#[must_use]
pub fn declared_bound(bound: &impl DeclaredNumber) -> f64 {
bound.declared_number().unwrap_or(f64::NAN)
}
pub fn declared_range(
value: &impl DeclaredNumber,
low: f64,
high: f64,
key: &str,
) -> Result<(), crate::Refusal> {
match value.declared_number() {
Some(number) if !(number.is_finite() && (low..=high).contains(&number)) => Err(
crate::Refusal::new(format!("`{key}` is between {low} and {high}")),
),
_ => Ok(()),
}
}
pub fn declared_choices(
value: &impl DeclaredChoice,
choices: &[&str],
key: &str,
) -> Result<(), crate::Refusal> {
match value.declared_choice() {
Some(chosen) if !choices.contains(&chosen) => Err(crate::Refusal::new(format!(
"`{key}` is one of {}",
choices.join(", ")
))),
_ => Ok(()),
}
}
pub fn apply_item<R, T>(
doc: &mut crate::Doc,
cx: &mut crate::ActionCx,
path: &[crate::Segment],
change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
) -> Option<Result<(), crate::Refusal>>
where
R: crate::Fields,
T: crate::Model,
{
let obj = crate::Path::<R, T>::from_segments(path.to_vec()).object(doc)?;
Some(apply_item_at::<R, T>(doc, cx, path, &obj, change))
}
fn apply_item_at<R, T>(
doc: &mut crate::Doc,
cx: &mut crate::ActionCx,
path: &[crate::Segment],
obj: &automerge::ObjId,
change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
) -> Result<(), crate::Refusal>
where
R: crate::Fields,
T: crate::Model,
{
let refused = |error: crate::ModelError| crate::Refusal::new(error.to_string());
let map = automerge::Value::Object(automerge::ObjType::Map);
let before = T::load(doc, &map, obj).map_err(refused)?;
let mut after = T::load(doc, &map, obj).map_err(refused)?;
let _ = cx.take_item_removal();
change(&mut after, cx)?;
if cx.take_item_removal() {
let (Some(crate::Segment::Item(id)), Some(collection)) = (
path.last(),
path.len().checked_sub(1).and_then(|at| path.get(..at)),
) else {
return Err(crate::Refusal::new(
"only an item of a collection is removed",
));
};
let op = crate::EditOp::RemoveItem { id: id.clone() };
return R::edit_fields(doc, &ROOT, collection, &op, cx).map_err(refused);
}
crate::Model::check(&after)?;
if after.stores_as(&before) {
return Ok(());
}
let Some(automerge::Parent {
obj: parent,
prop: automerge::Prop::Map(key),
..
}) = doc.parents(obj).ok().and_then(|mut parents| parents.next())
else {
return Err(crate::Refusal::new("the item is not kept under a key"));
};
after
.store(doc, crate::Slot::Key(&parent, &key))
.map_err(refused)
}
pub fn first_line<T: crate::Model>(value: &T) -> Option<String> {
let mut text = Vec::new();
value.collect_text(&mut text);
first_line_of(text)
}
pub use tilo_actions::params::param_type_of;
#[must_use]
pub fn flat_params(schema: &serde_json::Value) -> Vec<ActionParam> {
let required: Vec<&str> = schema
.get("required")
.and_then(serde_json::Value::as_array)
.map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
.unwrap_or_default();
let Some(properties) = schema
.get("properties")
.and_then(serde_json::Value::as_object)
else {
return Vec::new();
};
properties
.iter()
.map(|(name, property)| {
let description = property
.get("description")
.and_then(serde_json::Value::as_str)
.unwrap_or(name)
.to_owned();
let ty = param_type_of(property);
let param = if required.contains(&name.as_str()) {
ActionParam::required_owned(name.clone(), ty, description)
} else {
ActionParam::optional_owned(name.clone(), ty, description)
};
let mut schema = property.clone();
if let Some(schema) = schema.as_object_mut() {
schema.remove("description");
}
param.with_schema(schema)
})
.collect()
}
#[inline(never)]
pub fn json_via_bytes<T: serde::Serialize + ?Sized>(
value: &T,
) -> Result<serde_json::Value, serde_json::Error> {
let bytes = serde_json::to_vec(value)?;
value_of_bytes(&bytes)
}
#[inline(never)]
pub(crate) fn value_of_bytes(bytes: &[u8]) -> Result<serde_json::Value, serde_json::Error> {
serde_json::from_slice(bytes)
}
pub fn build_stamped<O: serde::de::DeserializeOwned>(
id: &str,
arguments: &serde_json::Map<String, serde_json::Value>,
now_ms: i64,
) -> Result<crate::Stamped<O>, String> {
let operation = serde_json::json!({ "action": id, "args": arguments });
O::deserialize(operation)
.map(|operation| crate::Stamped { operation, now_ms })
.map_err(|error| error.to_string())
}
pub use crate::resource::{default_search, kept_of, listed_of};
#[inline(never)]
pub fn args_object(
value: serde_json::Value,
) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
use serde::de::Error as _;
match value {
serde_json::Value::Object(args) => Ok(args),
serde_json::Value::Null => Ok(serde_json::Map::new()),
other => Err(serde_json::Error::invalid_type(
serde::de::Unexpected::Other(&other.to_string()),
&"the arguments as an object",
)),
}
}
pub fn arg<T: serde::de::DeserializeOwned>(
args: &mut serde_json::Map<String, serde_json::Value>,
name: &'static str,
optional: bool,
) -> Result<T, serde_json::Error> {
T::deserialize(take_arg(args, name, optional)?)
}
#[inline(never)]
fn take_arg(
args: &mut serde_json::Map<String, serde_json::Value>,
name: &'static str,
optional: bool,
) -> Result<serde_json::Value, serde_json::Error> {
use serde::de::Error as _;
match args.remove(name) {
Some(value) => Ok(value),
None if optional => Ok(serde_json::Value::Null),
None => Err(serde_json::Error::missing_field(name)),
}
}
#[inline(never)]
pub fn tagged(
value: serde_json::Value,
) -> Result<(String, serde_json::Value), serde_json::Error> {
use serde::de::Error as _;
let serde_json::Value::Object(mut fields) = value else {
return Err(serde_json::Error::custom("an action is an object"));
};
let Some(serde_json::Value::String(action)) = fields.remove("action") else {
return Err(serde_json::Error::missing_field("action"));
};
Ok((
action,
fields.remove("args").unwrap_or(serde_json::Value::Null),
))
}
#[must_use]
pub fn resource_value_schema(shape: crate::Shape) -> serde_json::Value {
let properties: serde_json::Map<String, serde_json::Value> = shape
.fields()
.iter()
.map(|field| (field.key.to_owned(), (field.schema)()))
.collect();
serde_json::json!({"type": "object", "properties": properties})
}
#[inline(never)]
pub(crate) fn first_line_of(text: Vec<String>) -> Option<String> {
text.into_iter()
.map(|line| line.lines().next().unwrap_or_default().trim().to_owned())
.find(|line| !line.is_empty())
}
pub fn check_outcome<O: crate::Outcome>(outcome: O) -> Result<(), crate::Refusal> {
outcome.into_result()
}
}
pub use tilo_actions::profiling;