1extern crate self as tilo_resource;
110
111mod absolute_path;
112pub mod action;
113mod apply_cache;
114pub mod batch;
115pub mod child;
116pub mod children;
117mod chunk_map;
118mod clock;
119pub mod collection;
120#[cfg(test)]
121mod concurrent_text_tests;
122pub mod content;
123mod cow;
124mod dates;
125mod search_preview;
126pub use search_preview::SearchPreview;
127pub mod delta;
128pub mod derived;
129mod describe;
130pub mod diff;
131pub mod effect;
132pub mod evolution;
133pub mod footprint;
134pub mod genesis;
135pub mod group;
136pub mod history;
137pub mod items;
138mod kept;
139pub mod keyed;
140pub mod kind;
141pub mod label;
142mod map;
143pub mod members;
144pub mod model;
145mod non_blank;
146pub mod order;
147pub mod ordered;
148pub mod origin;
149pub mod path;
150pub mod reactions;
151pub mod read;
152pub mod reader;
153mod recents;
154pub mod recording;
155pub mod replica;
156pub mod resource;
157pub mod row;
158pub mod schema;
159pub mod schema_check;
160pub mod search_default;
161pub use tilo_actions::search_index;
162pub mod shape;
163pub mod share;
164pub mod sort;
165pub mod status;
166pub mod storage;
167pub mod stored_items;
168pub mod surface;
169pub mod table;
170pub mod text;
171pub mod unreadable;
172mod upsert;
173mod value;
174pub mod vocabulary;
175pub mod words;
176
177pub use __private::FlatFields;
178pub use absolute_path::{AbsolutePath, RelativePath};
179pub use action::{
180 ActionCx, ActionKey, ActionKind, ActionRef, Binds, Invoke, Mapped, NoParams, Operation,
181 Outcome, Params, Refusal, Reverting, Stamped, TryMapped, Undoing, fresh_uuid, invoking_member,
182 invoking_name, minted_entry, minted_ids, minted_keys, restore_minted, reverting_type,
183 take_minted,
184};
185pub use automerge::Patch;
187pub use child::{child_resource_id, publish_child};
188pub use children::{ChildList, ChildRef, Children, Trashed};
189pub use clock::HybridClock;
190pub use collection::{
191 Collection, Id, Membership, Quarantined, stored_entry, stored_ids, stored_item,
192};
193pub use delta::{Delta, ObjPath, Touch, Touched, Tracker};
194pub use derived::{Bound, Derived};
195pub use effect::{
196 Answers, Effect, EffectDecl, EffectDecodeError, EffectOffload, EffectTarget, NoEffect, decode,
197 offer,
198};
199pub use evolution::Unreadable;
200pub use group::{ActionGroup, GROUP, GROUP_PARAM};
201pub use keyed::{ById, Identified, ItemStorage, Items, Keyed};
202pub use kind::{Kinds, ResourceKind};
203pub use map::Map;
204pub use model::{
205 Atom, Doc, Fields, Fresh, LocatedAt, MapSlot, Model, ModelError, Slot, VARIANT_KEY, edit_whole,
206 load_slot, read_key, read_slots, refresh_key, take_slot, write_key, write_key_changed,
207};
208pub use non_blank::{Blank, NonBlank};
209pub use ordered::{Arranged, Ordered};
210pub use origin::Origin;
211pub use path::{
212 At, Edit, EditOp, OP_ARGUMENTS, Operations, Path, Segment, Settable, op_argument_schema,
213 op_arguments, op_usage, outbox_settle_arguments,
214};
215pub use reactions::{
216 Reaction, ReactionGroup, Reactions, Reactor, custom_emoji_name, reaction_emoji,
217 valid_custom_emoji_name,
218};
219pub use reader::{Demand, Reader, heads_of};
220pub use recents::Recents;
221pub use replica::{AppNamed, NoApp, Replica};
222pub use resource::{
223 APPLY, APPLY_PARAM, ActionDecl, BuildAction, EDIT_PARAM, FIELD_EDIT, HeadInputs, NamesItem,
224 NoAction, Place, Resource, ScopeDecl, SearchBody, SearchEntry, SearchPiece, SearchRow,
225 SearchRowShape, SearchText, SearchWeight, SharedResource, bind_declaration, build_action,
226 by_app_refusal, child_by_id, declaration_spec, default_search, encode, head_inputs, need_of,
227 origin_now_ms, publish, publish_head, publish_head_of, reset_type_schemas, scope_contains,
228 spec_kind, state_from_reading, with_origin_clock,
229};
230pub use row::{Handle, LiveRow, RowBindings, typed_resource};
231pub use schema::JsonSchema;
232pub use shape::{FieldShape, Shape, StoredText, Trust, absent_scalar, stored_text};
233pub use status::EffectStatus;
234pub use storage::{Bytes, Counter, Grid, Outbox, OutboxEntry, Set, Settled};
235pub use surface::Surface;
236pub use text::{PlainText, TextEdit};
237pub use tilo_action_policy::edits::Weaker;
238pub use tilo_action_policy::{DIRECT_CONVERSATION_PREFIX, MemberId, PersonId};
239pub use tilo_actions::surface::{FieldType, TypeSet};
240pub use tilo_actions::{Acting, Availability};
241pub use tilo_resource_macros::{Effect, JsonSchema, Model, Row, committed_surface, resource};
242pub use tilo_sort::{Frecency, frecency};
243pub use unreadable::withhold_document_actions;
244pub use vocabulary::{Built, Declaration, Vocabulary, vocabulary};
245
246#[macro_export]
259macro_rules! word {
260 ($($input:tt)*) => {
261 $crate::__private::word!($crate, $($input)*)
262 };
263}
264
265#[doc(hidden)]
267pub mod __private {
268 pub use automerge::{ObjId, ObjType, Patch, ROOT, ReadDoc, ScalarValue, Value};
269 pub use serde;
270 pub use serde_json;
271 pub use tilo_actions::{
272 ActionArgs, ActionKind, ActionParam, ActionRegistry, ActionSpec, Audience, ChangeKind,
273 HOST_RENDER_TAG, OperationKind, PROMPTED_PARAM, ParamType, ResourceSpec, ResourceViewSpec,
274 RiskLevel, SCREEN_PLACE_TAG, SCREEN_TAG, StepKind, picked_address_schema,
275 picked_resource_schema,
276 };
277 pub use tilo_resource_macros::word;
278
279 pub use crate::apply_cache::forget_all;
280
281 #[must_use]
284 pub fn holds_nested_items(
285 record: &crate::table::ResourceDesc,
286 state: &dyn std::any::Any,
287 action: &crate::items::ItemAction,
288 ) -> bool {
289 let Some(field) = action.collection else {
290 return false;
291 };
292 let mut path: Vec<&str> = action.within.to_vec();
293 path.push(field);
294 crate::table::holds_nested_items(record, state, &path)
295 }
296
297 pub struct Snapshot<'a, T>(pub &'a T);
302
303 pub trait SnapshotByClone<T> {
305 fn snapshot(&self) -> Option<T>;
306 }
307
308 impl<T: Clone> SnapshotByClone<T> for &Snapshot<'_, T> {
309 fn snapshot(&self) -> Option<T> {
310 Some(self.0.clone())
311 }
312 }
313
314 pub trait SnapshotUnavailable<T> {
316 fn snapshot(&self) -> Option<T>;
317 }
318
319 impl<T> SnapshotUnavailable<T> for Snapshot<'_, T> {
320 fn snapshot(&self) -> Option<T> {
321 None
322 }
323 }
324
325 use crate::model::LocatedAt as _;
331
332 pub fn edit_at<T: crate::Model>(
335 doc: &mut crate::Doc,
336 obj: &ObjId,
337 key: &str,
338 rest: &[crate::Segment],
339 op: &crate::EditOp,
340 cx: &mut crate::ActionCx,
341 ) -> Result<(), crate::ModelError> {
342 T::edit(doc, crate::Slot::Key(obj, key), rest, op, cx).located(key)
343 }
344
345 #[derive(Clone, Copy, PartialEq, Eq)]
347 pub enum VerbUndo {
348 Revert,
350 Compensation,
353 }
354
355 #[derive(Clone, Copy, PartialEq, Eq)]
357 pub enum VerbAnswer {
358 Created,
360 Made,
362 Queued,
365 }
366
367 #[derive(Clone)]
369 #[allow(
370 clippy::struct_excessive_bools,
371 reason = "one independent `#[action(...)]` flag each, as the macro reads them"
372 )]
373 pub struct VerbDecl {
374 pub id: &'static str,
375 pub label: crate::label::Word,
376 pub keywords: &'static [&'static str],
378 pub icon: Option<&'static str>,
380 pub did: Option<&'static str>,
383 pub description: &'static str,
384 pub kind: ActionKind,
385 pub by_arguments: bool,
388 pub field: Option<&'static str>,
389 pub destructive: bool,
390 pub irreversible: bool,
393 pub housekeeping: bool,
396 pub answer: VerbAnswer,
397 pub incoming_message: bool,
399 pub undo: VerbUndo,
401 pub audience: tilo_actions::Audience,
403 pub collects: Option<&'static str>,
404 pub content: Option<&'static str>,
406 pub item_field: Option<&'static str>,
407 pub item: Option<&'static str>,
410 pub writes: &'static [&'static str],
411 pub step: Option<tilo_actions::StepKind>,
416 pub shape: crate::Shape,
417 pub params: &'static [ParamDecl],
418 }
419
420 #[derive(Clone, Copy)]
423 pub struct ParamDecl {
424 pub name: &'static str,
425 pub ty: ParamTypeOf,
426 pub description: &'static str,
427 pub schema: fn() -> serde_json::Value,
429 pub optional: bool,
430 pub place: PlaceIn,
431 pub example: Option<fn() -> serde_json::Value>,
432 pub flat: bool,
434 pub flat_types: Option<crate::surface::FlatTypes>,
437 pub content: bool,
440 pub field_type: crate::vocabulary::ParamFieldType,
442 }
443
444 #[derive(Clone, Copy)]
446 pub enum ParamTypeOf {
447 Known(ParamType),
449 Schema(fn() -> serde_json::Value),
451 }
452
453 pub trait FlatFields {
457 fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)>;
460 }
461
462 impl<T: crate::JsonSchema> FlatFields for T {
463 fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)> {
464 let crate::FieldType::Named(name) = <T as crate::JsonSchema>::field_type(types) else {
465 return Vec::new();
466 };
467 types
468 .get(&name)
469 .map(|record| {
470 record
471 .fields
472 .iter()
473 .map(|field| (field.name.clone(), field.ty.clone()))
474 .collect()
475 })
476 .unwrap_or_default()
477 }
478 }
479
480 #[must_use]
482 pub fn params_of(params: &[ParamDecl]) -> Vec<ActionParam> {
483 let mut out = Vec::with_capacity(params.len());
484 for param in params {
485 if param.flat {
486 out.extend(flat_params(&(param.schema)()));
487 continue;
488 }
489 let ty = match param.ty {
490 ParamTypeOf::Known(ty) => ty,
491 ParamTypeOf::Schema(schema) => param_type_of(&schema()),
492 };
493 let declared = declared_param(
494 param.name,
495 ty,
496 param.description,
497 param.schema,
498 param.optional,
499 param.place,
500 param.example,
501 );
502 out.push(if param.content {
503 declared.as_content()
504 } else {
505 declared
506 });
507 }
508 out
509 }
510
511 pub fn declare<R: crate::Resource>(
513 verb: VerbDecl,
514 build: fn(&ActionArgs, i64) -> Result<R::Action, String>,
515 ) -> crate::ActionDecl<R> {
516 let builds: crate::vocabulary::Builds =
517 std::sync::Arc::new(move |args, now_ms| match build(args, now_ms) {
518 Ok(action) => Ok(crate::Built::of::<R>(action)),
519 Err(reason) => Err(reason),
520 });
521 crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
522 }
523
524 pub fn declare_verb<R, O>(verb: VerbDecl) -> crate::ActionDecl<R>
528 where
529 R: crate::Resource<Action = crate::Stamped<O>>,
530 O: serde::de::DeserializeOwned,
531 {
532 let (id, content) = (verb.id, verb.content);
533 let builds: crate::vocabulary::Builds = std::sync::Arc::new(move |args, now_ms| {
534 let arguments = verb_arguments(args, content);
535 match build_stamped::<O>(id, &arguments, now_ms) {
536 Ok(action) => Ok(crate::Built::of::<R>(action)),
537 Err(reason) => Err(reason),
538 }
539 });
540 crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
541 }
542
543 fn verb_arguments(
546 args: &ActionArgs,
547 content: Option<&'static str>,
548 ) -> serde_json::Map<String, serde_json::Value> {
549 let mut arguments = args.to_json();
550 if let Some(content) = content
551 && let Some(hash) = arguments.remove(PROMPTED_PARAM)
552 {
553 arguments.insert(String::from(content), hash);
554 }
555 arguments
556 }
557
558 fn verb_declaration(
561 vocabulary: &crate::Vocabulary,
562 verb: VerbDecl,
563 build: crate::vocabulary::Builds,
564 ) -> crate::Declaration {
565 let written = verb.label.source;
566 let mut decl = crate::Declaration::new(
567 vocabulary,
568 verb.id,
569 written.to_owned(),
570 params_of(verb.params),
571 build,
572 );
573 decl.word = Some(verb.label);
574 decl.param_types = verb
575 .params
576 .iter()
577 .filter(|param| !param.flat)
578 .map(|param| (param.name, param.field_type))
579 .collect();
580 decl.flat_types = verb
581 .params
582 .iter()
583 .find(|param| param.flat)
584 .and_then(|param| param.flat_types);
585 decl.kind = verb.kind;
586 decl.keywords = verb
587 .keywords
588 .iter()
589 .map(|word| (*word).to_owned())
590 .collect();
591 decl.icon = verb.icon.map(str::to_owned);
592 decl.did = verb.did.map(str::to_owned);
593 decl.by_arguments = verb.by_arguments;
594 decl.writes = crate::footprint::declared(verb.shape, verb.item_field, verb.writes);
595 decl.item = verb.item;
596 let description = verb
598 .description
599 .strip_prefix(written)
600 .map_or(verb.description, |rest| {
601 rest.trim_start_matches('.').trim_start()
602 });
603 if !description.is_empty() {
604 decl.description = Some(description.to_owned());
605 }
606 decl.field = verb.field;
607 decl.destructive = verb.destructive;
608 decl.step = verb
609 .step
610 .or_else(|| verb.destructive.then_some(tilo_actions::StepKind::Delete));
611 decl.creates = (decl.step == Some(tilo_actions::StepKind::Create))
614 .then(|| verb.writes.first().copied())
615 .flatten();
616 if verb.irreversible {
617 decl.tags.push(tilo_actions::IRREVERSIBLE_TAG.to_owned());
618 }
619 if verb.housekeeping {
620 decl.tags.push(tilo_actions::HOUSEKEEPING_TAG.to_owned());
621 }
622 if verb.incoming_message {
623 decl.tags
624 .push(tilo_actions::INCOMING_MESSAGE_TAG.to_owned());
625 }
626 if let Some(tag) = verb.audience.tag() {
627 decl.tags.push(tag.to_owned());
628 }
629 if verb.undo == VerbUndo::Compensation {
630 decl.tags
631 .push(tilo_actions::COMPENSATED_UNDO_TAG.to_owned());
632 }
633 match verb.answer {
634 VerbAnswer::Created => {}
635 VerbAnswer::Made => {
636 decl.result = Some(tilo_actions::ResultSpec::Json {
637 schema: serde_json::json!({"type": "object"}),
638 });
639 }
640 VerbAnswer::Queued => {
643 decl.result = Some(tilo_actions::ResultSpec::Json {
644 schema: serde_json::json!({"type": ["object", "array", "null"]}),
645 });
646 }
647 }
648 if let Some(prompt) = verb.collects {
649 decl.content = Some(prompt.to_owned());
650 }
651 decl
652 }
653
654 #[derive(Clone, Copy)]
656 pub enum PlaceIn {
657 Nowhere,
659 Record,
661 Field(&'static str),
663 }
664
665 #[must_use]
671 pub fn declared_param(
672 name: impl Into<String>,
673 ty: ParamType,
674 description: impl Into<String>,
675 schema: fn() -> serde_json::Value,
676 optional: bool,
677 place: PlaceIn,
678 example: Option<fn() -> serde_json::Value>,
679 ) -> ActionParam {
680 let name = name.into();
681 let description = description.into();
682 let param = if optional {
683 ActionParam::optional_owned(name, ty, description)
684 } else {
685 ActionParam::required_owned(name, ty, description)
686 }
687 .with_schema(param_schema(schema(), "", example.map(|example| example())));
690 match place {
691 PlaceIn::Nowhere => param,
692 PlaceIn::Record => param.as_place(),
693 PlaceIn::Field(field) => param.as_place_in(field),
694 }
695 }
696
697 #[must_use]
699 pub fn param_schema(
700 schema: serde_json::Value,
701 description: &str,
702 example: Option<serde_json::Value>,
703 ) -> serde_json::Value {
704 let mut schema = crate::schema::describe(schema, description);
705 if let (Some(example), serde_json::Value::Object(fields)) = (example, &mut schema) {
706 fields.insert("examples".into(), serde_json::Value::Array(vec![example]));
707 }
708 schema
709 }
710
711 pub struct DefaultOf<T>(::core::marker::PhantomData<T>);
716
717 impl<T> DefaultOf<T> {
718 #[must_use]
719 pub const fn new() -> Self {
720 Self(::core::marker::PhantomData)
721 }
722 }
723
724 impl<T> Default for DefaultOf<T> {
725 fn default() -> Self {
726 Self::new()
727 }
728 }
729
730 pub trait HasDefault<T> {
732 fn default_value(&self) -> Option<T>;
733 }
734
735 impl<T: Default> HasDefault<T> for DefaultOf<T> {
736 fn default_value(&self) -> Option<T> {
737 Some(T::default())
738 }
739 }
740
741 pub trait NoDefault<T> {
743 fn default_value(&self) -> Option<T>;
744 }
745
746 impl<T> NoDefault<T> for &DefaultOf<T> {
747 fn default_value(&self) -> Option<T> {
748 None
749 }
750 }
751
752 pub trait DeclaredNumber {
755 fn declared_number(&self) -> Option<f64>;
756 }
757
758 macro_rules! declared_number {
759 ($($ty:ty),*) => {$(
760 impl DeclaredNumber for $ty {
761 #[allow(clippy::cast_precision_loss, clippy::cast_lossless, reason = "a range bound is a numeric limit far below 2^53")]
762 fn declared_number(&self) -> Option<f64> {
763 Some(*self as f64)
764 }
765 }
766 )*};
767 }
768 declared_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
769
770 impl<T: DeclaredNumber> DeclaredNumber for Option<T> {
771 fn declared_number(&self) -> Option<f64> {
772 self.as_ref().and_then(DeclaredNumber::declared_number)
773 }
774 }
775
776 pub trait DeclaredChoice {
779 fn declared_choice(&self) -> Option<&str>;
780 }
781
782 impl DeclaredChoice for String {
783 fn declared_choice(&self) -> Option<&str> {
784 Some(self)
785 }
786 }
787
788 impl<T: DeclaredChoice> DeclaredChoice for Option<T> {
789 fn declared_choice(&self) -> Option<&str> {
790 self.as_ref().and_then(DeclaredChoice::declared_choice)
791 }
792 }
793
794 #[must_use]
796 pub fn declared_bound(bound: &impl DeclaredNumber) -> f64 {
797 bound.declared_number().unwrap_or(f64::NAN)
798 }
799
800 pub fn declared_range(
803 value: &impl DeclaredNumber,
804 low: f64,
805 high: f64,
806 key: &str,
807 ) -> Result<(), crate::Refusal> {
808 match value.declared_number() {
809 Some(number) if !(number.is_finite() && (low..=high).contains(&number)) => Err(
810 crate::Refusal::new(format!("`{key}` is between {low} and {high}")),
811 ),
812 _ => Ok(()),
813 }
814 }
815
816 pub fn declared_choices(
818 value: &impl DeclaredChoice,
819 choices: &[&str],
820 key: &str,
821 ) -> Result<(), crate::Refusal> {
822 match value.declared_choice() {
823 Some(chosen) if !choices.contains(&chosen) => Err(crate::Refusal::new(format!(
824 "`{key}` is one of {}",
825 choices.join(", ")
826 ))),
827 _ => Ok(()),
828 }
829 }
830
831 pub fn apply_item<R, T>(
843 doc: &mut crate::Doc,
844 cx: &mut crate::ActionCx,
845 path: &[crate::Segment],
846 change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
847 ) -> Option<Result<(), crate::Refusal>>
848 where
849 R: crate::Fields,
850 T: crate::Model,
851 {
852 let obj = crate::Path::<R, T>::from_segments(path.to_vec()).object(doc)?;
853 Some(apply_item_at::<R, T>(doc, cx, path, &obj, change))
854 }
855
856 fn apply_item_at<R, T>(
857 doc: &mut crate::Doc,
858 cx: &mut crate::ActionCx,
859 path: &[crate::Segment],
860 obj: &automerge::ObjId,
861 change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
862 ) -> Result<(), crate::Refusal>
863 where
864 R: crate::Fields,
865 T: crate::Model,
866 {
867 let refused = |error: crate::ModelError| crate::Refusal::new(error.to_string());
868 let map = automerge::Value::Object(automerge::ObjType::Map);
869 let before = T::load(doc, &map, obj).map_err(refused)?;
870 let mut after = T::load(doc, &map, obj).map_err(refused)?;
871 let _ = cx.take_item_removal();
872 change(&mut after, cx)?;
873 if cx.take_item_removal() {
874 let (Some(crate::Segment::Item(id)), Some(collection)) = (
875 path.last(),
876 path.len().checked_sub(1).and_then(|at| path.get(..at)),
877 ) else {
878 return Err(crate::Refusal::new(
879 "only an item of a collection is removed",
880 ));
881 };
882 let op = crate::EditOp::RemoveItem { id: id.clone() };
883 return R::edit_fields(doc, &ROOT, collection, &op, cx).map_err(refused);
884 }
885 crate::Model::check(&after)?;
886 if after.stores_as(&before) {
887 return Ok(());
888 }
889 let Some(automerge::Parent {
893 obj: parent,
894 prop: automerge::Prop::Map(key),
895 ..
896 }) = doc.parents(obj).ok().and_then(|mut parents| parents.next())
897 else {
898 return Err(crate::Refusal::new("the item is not kept under a key"));
899 };
900 after
901 .store(doc, crate::Slot::Key(&parent, &key))
902 .map_err(refused)
903 }
904
905 pub fn first_line<T: crate::Model>(value: &T) -> Option<String> {
908 let mut text = Vec::new();
909 value.collect_text(&mut text);
910 first_line_of(text)
911 }
912
913 pub use tilo_actions::params::param_type_of;
914
915 #[must_use]
919 pub fn flat_params(schema: &serde_json::Value) -> Vec<ActionParam> {
920 let required: Vec<&str> = schema
921 .get("required")
922 .and_then(serde_json::Value::as_array)
923 .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
924 .unwrap_or_default();
925 let Some(properties) = schema
926 .get("properties")
927 .and_then(serde_json::Value::as_object)
928 else {
929 return Vec::new();
930 };
931 properties
932 .iter()
933 .map(|(name, property)| {
934 let description = property
935 .get("description")
936 .and_then(serde_json::Value::as_str)
937 .unwrap_or(name)
938 .to_owned();
939 let ty = param_type_of(property);
940 let param = if required.contains(&name.as_str()) {
941 ActionParam::required_owned(name.clone(), ty, description)
942 } else {
943 ActionParam::optional_owned(name.clone(), ty, description)
944 };
945 let mut schema = property.clone();
948 if let Some(schema) = schema.as_object_mut() {
949 schema.remove("description");
950 }
951 param.with_schema(schema)
952 })
953 .collect()
954 }
955
956 #[inline(never)]
963 pub fn json_via_bytes<T: serde::Serialize + ?Sized>(
964 value: &T,
965 ) -> Result<serde_json::Value, serde_json::Error> {
966 let bytes = serde_json::to_vec(value)?;
967 value_of_bytes(&bytes)
968 }
969
970 #[inline(never)]
975 pub(crate) fn value_of_bytes(bytes: &[u8]) -> Result<serde_json::Value, serde_json::Error> {
976 serde_json::from_slice(bytes)
977 }
978
979 pub fn build_stamped<O: serde::de::DeserializeOwned>(
983 id: &str,
984 arguments: &serde_json::Map<String, serde_json::Value>,
985 now_ms: i64,
986 ) -> Result<crate::Stamped<O>, String> {
987 let operation = serde_json::json!({ "action": id, "args": arguments });
988 O::deserialize(operation)
989 .map(|operation| crate::Stamped { operation, now_ms })
990 .map_err(|error| error.to_string())
991 }
992
993 pub use crate::resource::{default_search, kept_of, listed_of};
994
995 #[inline(never)]
1000 pub fn args_object(
1001 value: serde_json::Value,
1002 ) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
1003 use serde::de::Error as _;
1004 match value {
1005 serde_json::Value::Object(args) => Ok(args),
1006 serde_json::Value::Null => Ok(serde_json::Map::new()),
1007 other => Err(serde_json::Error::invalid_type(
1008 serde::de::Unexpected::Other(&other.to_string()),
1009 &"the arguments as an object",
1010 )),
1011 }
1012 }
1013
1014 pub fn arg<T: serde::de::DeserializeOwned>(
1020 args: &mut serde_json::Map<String, serde_json::Value>,
1021 name: &'static str,
1022 optional: bool,
1023 ) -> Result<T, serde_json::Error> {
1024 T::deserialize(take_arg(args, name, optional)?)
1027 }
1028
1029 #[inline(never)]
1032 fn take_arg(
1033 args: &mut serde_json::Map<String, serde_json::Value>,
1034 name: &'static str,
1035 optional: bool,
1036 ) -> Result<serde_json::Value, serde_json::Error> {
1037 use serde::de::Error as _;
1038 match args.remove(name) {
1039 Some(value) => Ok(value),
1040 None if optional => Ok(serde_json::Value::Null),
1041 None => Err(serde_json::Error::missing_field(name)),
1042 }
1043 }
1044
1045 #[inline(never)]
1051 pub fn tagged(
1052 value: serde_json::Value,
1053 ) -> Result<(String, serde_json::Value), serde_json::Error> {
1054 use serde::de::Error as _;
1055 let serde_json::Value::Object(mut fields) = value else {
1056 return Err(serde_json::Error::custom("an action is an object"));
1057 };
1058 let Some(serde_json::Value::String(action)) = fields.remove("action") else {
1059 return Err(serde_json::Error::missing_field("action"));
1060 };
1061 Ok((
1062 action,
1063 fields.remove("args").unwrap_or(serde_json::Value::Null),
1064 ))
1065 }
1066
1067 #[must_use]
1071 pub fn resource_value_schema(shape: crate::Shape) -> serde_json::Value {
1072 let properties: serde_json::Map<String, serde_json::Value> = shape
1073 .fields()
1074 .iter()
1075 .map(|field| (field.key.to_owned(), (field.schema)()))
1076 .collect();
1077 serde_json::json!({"type": "object", "properties": properties})
1078 }
1079
1080 #[inline(never)]
1082 pub(crate) fn first_line_of(text: Vec<String>) -> Option<String> {
1083 text.into_iter()
1084 .map(|line| line.lines().next().unwrap_or_default().trim().to_owned())
1085 .find(|line| !line.is_empty())
1086 }
1087
1088 pub fn check_outcome<O: crate::Outcome>(outcome: O) -> Result<(), crate::Refusal> {
1090 outcome.into_result()
1091 }
1092}
1093
1094pub use tilo_actions::profiling;