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