ikigai_fn/lib.rs
1//! `ikigai-fn` — a library of reusable function endpoints.
2//!
3//! This is the first **ikigai module crate**: a standalone library of
4//! resolvable function endpoints that a host *links in* and mounts, rather than
5//! the engine shipping behaviour itself. It depends only on the published
6//! `ikigai-core` kernel, uses no OS or platform APIs, and compiles to
7//! `wasm32-unknown-unknown` — so the same module links into a native CLI and
8//! into the in-browser WebAssembly host alike (no WASI required yet).
9//!
10//! Each `snake_case` constructor builds an endpoint whose `lowerCamelCase`
11//! identifier matches its name — [`to_upper`] builds the `toUpper` endpoint,
12//! conventionally resolved at `urn:iki:fn:toUpper`. A host either pulls the
13//! constructors and binds them at IRIs of its choosing, or mounts the whole
14//! library at its conventional IRIs with [`space`].
15
16pub mod aggregate;
17pub mod html;
18pub mod markdown;
19pub mod prefix;
20
21pub use prefix::{prefix_check, prefix_expand, prefix_space, RESERVED_SCHEMES};
22
23use std::future::Future;
24use std::pin::Pin;
25use std::sync::atomic::{AtomicUsize, Ordering};
26
27use async_trait::async_trait;
28use futures_util::future::try_join_all;
29
30use ikigai_core::{
31 space_iri, ArgRef, ArgSpec, ContentId, Description, Endpoint, EndpointSpace, Error, Exact,
32 FnEndpoint, Invocation, Iri, ReprType, Representation, Request, Result, UriTemplate, Verb,
33};
34
35/// The conventional `text/plain; charset=utf-8` representation type.
36fn text_plain_utf8() -> ReprType {
37 ReprType::new("text/plain").with_param("charset", "utf-8")
38}
39
40/// The same media type as a description-output string.
41const TEXT_PLAIN_UTF8: &str = "text/plain;charset=utf-8";
42
43/// The conventional `text/html; charset=utf-8` representation type.
44fn text_html_utf8() -> ReprType {
45 ReprType::new("text/html").with_param("charset", "utf-8")
46}
47
48/// The same media type as a description-output string.
49const TEXT_HTML_UTF8: &str = "text/html;charset=utf-8";
50
51/// The datatype every text-valued input declares. `select_action` and `urn:kernel:actions
52/// types=` match on [`ArgSpec::class`] and nothing else: an input WITHOUT a class is not
53/// "untyped", it is invisible to type-driven selection (a required input with no class
54/// makes the whole endpoint un-inferable). So every input in [`space`] carries one, and a
55/// test pins that.
56const XSD_STRING: &str = "http://www.w3.org/2001/XMLSchema#string";
57
58/// The datatype of an input whose value is the IRI of another resource (compose's `src`,
59/// conditional's `if`/`then`/`else`) — the argument names a resource, it does not carry one.
60const XSD_ANY_URI: &str = "http://www.w3.org/2001/XMLSchema#anyURI";
61
62/// The datatype of an input whose value is a count (markdown's `heading_offset`).
63const XSD_NON_NEGATIVE_INTEGER: &str = "http://www.w3.org/2001/XMLSchema#nonNegativeInteger";
64
65// --- simple, idempotent, perfectly cacheable functions --------------------
66
67fn digest_impl(inv: &Invocation<'_>) -> Result<Representation> {
68 let input = inv.inline_str("in")?;
69 let digest = ContentId::of(input.as_bytes()).to_string();
70 Ok(Representation::new(text_plain_utf8(), digest.into_bytes()).cacheable())
71}
72
73/// `digest`: the BLAKE3 content id of the exact UTF-8 bytes in `in`.
74///
75/// Uses core's [`ContentId::of`], the cache's identity rule, and returns `b3:` followed
76/// by 64 lowercase hexadecimal digits, without a newline. No trimming, Unicode
77/// normalization, or line-ending conversion is applied.
78pub fn digest() -> FnEndpoint {
79 FnEndpoint::new("digest", digest_impl).with_description(
80 Description::new("digest")
81 .title("Content digest")
82 .summary("Returns the BLAKE3 content id (b3: plus lowercase hex) of the exact UTF-8 bytes in `in`, without normalization or a trailing newline.")
83 .verb(Verb::Source)
84 .verb(Verb::Meta)
85 .input(
86 ArgSpec::new("in")
87 .summary("the text to digest, preserved exactly")
88 .class(XSD_STRING),
89 )
90 .output(TEXT_PLAIN_UTF8),
91 )
92}
93
94fn markdown_impl(inv: &Invocation<'_>) -> Result<Representation> {
95 let content = inv.inline_str("content")?;
96 let heading_offset = match inv.inline_str("heading_offset") {
97 Ok(text) => text.parse().map_err(|_| Error::InvalidArgument {
98 name: "heading_offset".to_string(),
99 detail: format!("expected a whole number from 0 to 255, got {text:?}"),
100 })?,
101 Err(Error::MissingArgument(_)) => markdown::Options::default().heading_offset,
102 Err(e) => return Err(e),
103 };
104 let fragment = markdown::try_render_untrusted(content, &markdown::Options { heading_offset })
105 .map_err(|refused| Error::OverBudget {
106 detail: format!("markdown: {refused}"),
107 })?;
108 Ok(Representation::new(text_html_utf8(), fragment.into_bytes()).cacheable())
109}
110
111/// `markdown`: the untrusted Markdown in `content` as a well-formed XHTML fragment
112/// ([`markdown::try_render_untrusted`]). Input past the module's size or nesting bound is
113/// refused as [`Error::OverBudget`].
114pub fn markdown() -> FnEndpoint {
115 FnEndpoint::new("markdown", markdown_impl).with_description(
116 Description::new("markdown")
117 .title("Markdown to HTML")
118 .summary(
119 "Renders untrusted CommonMark, with tables, strikethrough and task lists, as a \
120 well-formed XHTML fragment. Raw HTML appears as text, only safe links become \
121 links, images are never fetched, and oversized or too deeply nested text is \
122 refused.",
123 )
124 .verb(Verb::Source)
125 .verb(Verb::Meta)
126 .input(
127 ArgSpec::new("content")
128 .summary("the Markdown, as text")
129 .class(XSD_STRING),
130 )
131 .input(
132 ArgSpec::new("heading_offset")
133 .summary("added to every heading's level, capped at h6; 2 when absent")
134 .class(XSD_NON_NEGATIVE_INTEGER)
135 .optional(),
136 )
137 .output(TEXT_HTML_UTF8),
138 )
139}
140
141fn to_upper_impl(inv: &Invocation<'_>) -> Result<Representation> {
142 let input = inv.inline_str("in")?;
143 Ok(Representation::new(text_plain_utf8(), input.to_uppercase().into_bytes()).cacheable())
144}
145
146/// `toUpper`: upper-cases the UTF-8 string in the `in` argument.
147pub fn to_upper() -> FnEndpoint {
148 FnEndpoint::new("toUpper", to_upper_impl).with_description(
149 Description::new("toUpper")
150 .title("Upper-case")
151 .summary("Upper-cases the UTF-8 text supplied in the `in` argument.")
152 .verb(Verb::Source)
153 .verb(Verb::Meta)
154 .input(
155 ArgSpec::new("in")
156 .summary("the text to upper-case")
157 .class(XSD_STRING),
158 )
159 .output(TEXT_PLAIN_UTF8),
160 )
161}
162
163fn reverse_list_impl(inv: &Invocation<'_>) -> Result<Representation> {
164 let input = inv.inline_str("in")?;
165 let mut items: Vec<&str> = input.split('\n').collect();
166 items.reverse();
167 Ok(Representation::new(text_plain_utf8(), items.join("\n").into_bytes()).cacheable())
168}
169
170/// `reverseList`: reverses the order of newline-separated items in `in`.
171pub fn reverse_list() -> FnEndpoint {
172 FnEndpoint::new("reverseList", reverse_list_impl).with_description(
173 Description::new("reverseList")
174 .title("Reverse list")
175 .summary("Reverses the order of newline-separated items in the `in` argument.")
176 .verb(Verb::Source)
177 .verb(Verb::Meta)
178 .input(
179 ArgSpec::new("in")
180 .summary("newline-separated items")
181 .class(XSD_STRING),
182 )
183 .output(TEXT_PLAIN_UTF8),
184 )
185}
186
187fn split_impl(inv: &Invocation<'_>) -> Result<Representation> {
188 let items = inv
189 .inline_str("in")?
190 .split(',')
191 .map(str::trim)
192 .collect::<Vec<_>>()
193 .join("\n");
194 Ok(Representation::new(text_plain_utf8(), items.into_bytes()).cacheable())
195}
196
197/// `split`: splits the `in` argument on commas (trimming each) into a
198/// newline-separated list — a *list producer* for the `..` map operator
199/// (`source urn:demo:split "a, b, c" .. urn:iki:fn:toUpper`). The newline list is the
200/// same convention [`reverse_list`] reads.
201pub fn split() -> FnEndpoint {
202 FnEndpoint::new("split", split_impl).with_description(
203 Description::new("split")
204 .title("Split")
205 .summary("Splits the `in` argument on commas into newline-separated items.")
206 .verb(Verb::Source)
207 .verb(Verb::Meta)
208 .input(
209 ArgSpec::new("in")
210 .summary("comma-separated items")
211 .class(XSD_STRING),
212 )
213 .output(TEXT_PLAIN_UTF8),
214 )
215}
216
217fn wrap_impl(inv: &Invocation<'_>) -> Result<Representation> {
218 let text = inv.inline_str("text")?;
219 Ok(Representation::new(text_plain_utf8(), format!("[{text}]").into_bytes()).cacheable())
220}
221
222/// `wrap`: surrounds the `text` argument with square brackets. Its argument is
223/// deliberately named `text`, not `in`, so contract-driven routing is visible —
224/// `source urn:demo:wrap hi` works only because the contract says the input goes
225/// to `text` (and pipelines show their work: `… | urn:demo:wrap` → `[HI]`).
226pub fn wrap() -> FnEndpoint {
227 FnEndpoint::new("wrap", wrap_impl).with_description(
228 Description::new("wrap")
229 .title("Wrap")
230 .summary("Surrounds the `text` argument with square brackets.")
231 .verb(Verb::Source)
232 .verb(Verb::Meta)
233 .input(
234 ArgSpec::new("text")
235 .summary("the text to wrap")
236 .class(XSD_STRING),
237 )
238 .output(TEXT_PLAIN_UTF8),
239 )
240}
241
242fn greet_impl(inv: &Invocation<'_>) -> Result<Representation> {
243 let greeting = inv.inline_str("greeting")?;
244 let name = inv.inline_str("name")?;
245 Ok(Representation::new(
246 text_plain_utf8(),
247 format!("{greeting}, {name}").into_bytes(),
248 )
249 .cacheable())
250}
251
252/// `greet`: combines `greeting` and `name` into `"{greeting}, {name}"` — the
253/// *multi-argument* function (`source urn:demo:greet greeting=Hello name=World`).
254pub fn greet() -> FnEndpoint {
255 FnEndpoint::new("greet", greet_impl).with_description(
256 Description::new("greet")
257 .title("Greet")
258 .summary("Combines `greeting` and `name` into a greeting.")
259 .verb(Verb::Source)
260 .verb(Verb::Meta)
261 .input(
262 ArgSpec::new("greeting")
263 .summary("the salutation, e.g. Hello")
264 .class(XSD_STRING),
265 )
266 .input(
267 ArgSpec::new("name")
268 .summary("who to greet")
269 .class(XSD_STRING),
270 )
271 .output(TEXT_PLAIN_UTF8),
272 )
273}
274
275fn html_to_text_impl(inv: &Invocation<'_>) -> Result<Representation> {
276 let text = html::to_text(inv.inline_str("in")?);
277 Ok(Representation::new(text_plain_utf8(), text.into_bytes()).cacheable())
278}
279
280/// `html-to-text`: the words the HTML in `in` shows a reader, as one line of plain text
281/// ([`html::to_text`]) — the text face a lift stores beside an RSS description, so a
282/// search runs over words and not over `strong`, `img` or `href`.
283pub fn html_to_text() -> FnEndpoint {
284 FnEndpoint::new("html-to-text", html_to_text_impl).with_description(
285 Description::new("html-to-text")
286 .title("HTML to text")
287 .summary(
288 "The text the HTML in `in` shows a reader: tags, comments, scripts and \
289 styles removed, character references decoded, whitespace collapsed to \
290 one line. Parsed by html5ever's WHATWG tokenizer.",
291 )
292 .verb(Verb::Source)
293 .verb(Verb::Meta)
294 .input(
295 ArgSpec::new("in")
296 .summary("the HTML, as text")
297 .class(XSD_STRING),
298 )
299 .output(TEXT_PLAIN_UTF8),
300 )
301}
302
303fn echo_impl(inv: &Invocation<'_>) -> Result<Representation> {
304 let message = inv
305 .bindings
306 .get("message")
307 .ok_or_else(|| Error::MissingArgument("message".to_string()))?;
308 Ok(Representation::new(text_plain_utf8(), message.as_bytes().to_vec()).cacheable())
309}
310
311/// `echo`: returns the `message` variable captured by the resolving grammar —
312/// demonstrates grammar bindings (e.g. `urn:demo:echo/{message}`) flowing to an
313/// endpoint.
314pub fn echo() -> FnEndpoint {
315 FnEndpoint::new("echo", echo_impl).with_description(
316 Description::new("echo")
317 .title("Echo")
318 .summary("Returns the `message` segment captured from the resource identifier.")
319 .verb(Verb::Source)
320 .verb(Verb::Meta)
321 .input(
322 ArgSpec::new("message")
323 .summary("the text to echo, captured from the path by the resolving grammar")
324 .class(XSD_STRING)
325 .binding(),
326 )
327 .output(TEXT_PLAIN_UTF8),
328 )
329}
330
331// --- compose: a request-template language over `$a{…}`, `$r{…}` and `$h{…}` ----
332
333/// Maximum `$a{}` expansion depth — a backstop against a shape that transcludes
334/// itself, directly or through a cycle.
335const COMPOSE_MAX_DEPTH: usize = 32;
336
337/// Maximum literal and marker nodes produced by one template fill, including every
338/// recursive `$a` expansion. Repeated uses count again even when their resource is
339/// cached. Each element of `each` is a separate fill.
340pub const COMPOSE_MAX_NODES: usize = 10_000;
341
342fn compose_node_limit() -> Error {
343 Error::Endpoint(format!(
344 "compose: node limit ({COMPOSE_MAX_NODES}, COMPOSE_MAX_NODES) exceeded"
345 ))
346}
347
348/// `compose`: a request-template language — NetKernel's TRL, resolved through the
349/// kernel.
350///
351/// Sources the template named by the `src` argument and replaces every marker in its
352/// (UTF-8 text) representation with the resource the marker names. There are four
353/// markers, one for each way of splicing what comes back:
354///
355/// | marker | splices | the spliced text's own markers |
356/// |---|---|---|
357/// | `$a{<iri>}` | as it is — trusted markup | **expanded**: a template including a template |
358/// | `$r{<iri>}` | as it is — trusted markup | left alone (terminated) |
359/// | `$h{<iri>}` | as TEXT, HTML-escaped | left alone (terminated) |
360/// | `$j{<src> <program>}` | a jq selection of `src`, as `$h` does | left alone (terminated) |
361///
362/// **`$j`** is sugar for `$h{urn:json:query?src=<src>&q=<program>&as=text/plain}`
363/// ([`JQ_QUERY`], served by ikigai-json, which this crate does not depend on: the marker only
364/// names it). The source is the body up to its first whitespace, and the program is the rest,
365/// trimmed, as written: it runs to the marker's balanced `}` (braces outside a `"…"` string
366/// nest, and a `}` inside one is text), so any jq program fits unquoted:
367/// `$j{urn:example:people map(select(.age > 30)) | .[0].name}`. The source may name template
368/// arguments (`{name}`, percent-encoded, as in any marker's IRI); the program is template text
369/// only — `{…}` there is jq's object, and no argument reaches it. The program travels as the
370/// request's `q` argument, not in the IRI, so it needs no percent-encoding. `$j` takes no
371/// fallback (`||` belongs to the program), and with nothing bound at [`JQ_QUERY`] it fails as
372/// an unresolved `$h` does.
373///
374/// **Short names.** A marker's IRI need not be a `urn:`: `$h{fn:toUpper?in=x}`,
375/// `$j{page:people .[0].name}` and an [`each`]'s `src` and `template` resolve as whatever the
376/// request's resolution chain makes of them. The ecosystem's way to give a composition short
377/// names is a prefix table declared as data and bound into a dynamic space around it
378/// ([`prefix_space`], and the [`prefix`] module): inside, `json:query` resolves to
379/// `urn:json:query` under the caller's capability; outside, the name does not exist.
380///
381/// A marker may carry inline arguments (`$a{urn:iki:fn:toUpper?in="resource oriented
382/// computing"}`). An unquoted `<iri>` argument is a reference, issued to the kernel as
383/// [`ArgRef::Reference`]: `$r{urn:iki:fn:toUpper?in=<urn:example:data>}`. The target's
384/// contract determines how the kernel settles it. `{name}` inside `<…>` is
385/// percent-encoded as in an IRI; a quoted `"<urn:example:data>"` stays inline text.
386/// A literal `$` is written `$$`, so `$$h{…}` is the literal text `$h{…}`.
387/// [`escape_markers`] writes any text that way, and [`MARKER_LETTERS`] lists the letters.
388///
389/// **Escaping.** `$h` escapes with [`html::html_text`]: `&`, `<`, `>`, `"` and `'` become
390/// `&`, `<`, `>`, `"` and `'` (and a C0 control other than tab, line feed
391/// and carriage return becomes U+FFFD), so its output is safe in element text and inside an
392/// attribute value quoted with either quote. It is not safe in an UNQUOTED attribute value
393/// (a space ends one), and no escaping makes a URL attribute safe from a `javascript:`
394/// value: quote every attribute, and put values, not whole URLs, in `href` (a whole URL
395/// from data goes through [`html::safe_href`]).
396///
397/// **Terminate.** Only `$a` expands what it splices. Content read from an atom — user
398/// data, a peer, a file — goes in through `$h` (or `$r`, for markup you trust), so a
399/// stored `$a{urn:example:secret}` renders as those characters and resolves nothing. `$a`
400/// is how a template opts in to recursion, and it re-expands EVERYTHING it splices —
401/// including the output of a nested `compose`, whose `$$` escapes have already
402/// collapsed to `$`. Splice a composed view with `$r`.
403///
404/// **Bounds.** A fill permits at most 32 template levels and [`COMPOSE_MAX_NODES`]
405/// literal/marker nodes across all `$a` expansions. Each occurrence counts, including
406/// cached resources and argument splices. Exceeding either limit returns
407/// [`Error::Endpoint`]; a node-limit failure cannot be hidden by a fallback. These are
408/// bounds on this fill; requests to other composers also have the kernel's limits.
409///
410/// **Template arguments.** Every argument of the request other than `src` — and, for
411/// [`compose_over`], every variable its name captured, which wins over an argument of
412/// the same name — is a template argument, and a marker names one as `{name}`:
413///
414/// - in the IRI its value is percent-encoded with [`html::url_segment`], as RFC 6570
415/// expands a simple variable, so an argument can never add a path segment, a query
416/// or an argument:
417/// `$h{urn:example:cell:{x}:{y}}`;
418/// - in the IRI, `{+name}` is RFC 6570's RESERVED expansion ([`html::url_reserved`]): a
419/// reserved character (`: / ? # [ ] @ ! $ & ' ( ) * + , ; =`) and a well-formed `%XX`
420/// pass through, everything else is encoded, so a name with `:` in it reaches its target
421/// whole: `$r{urn:example:fragment:{+page}}` with `page=item:default:5` sources
422/// `urn:example:fragment:item:default:5` (ledger #2132). ⚠ **Use it only for a value the
423/// HOST fixed** — a variable a [`compose_over`] binding captured from a name the host
424/// bound, under a prefix the host owns. Never for a request argument: `/`, `?`, `#` and
425/// `:` survive, so the value can pick any resource under the prefix. The template's own
426/// text before its first argument must hold the scheme and its `:`, so a reserved
427/// argument never chooses the scheme (`$r{{+x}}` is refused when parsed); `{+name}` in an
428/// inline argument value is refused too, since `{name}` there is already verbatim;
429/// - in an unquoted inline argument value it IS the value, verbatim, and still one value:
430/// `$r{urn:iki:fn:toUpper?in={name}}`;
431/// - in a quoted value it is literal text: `in="{name}"` passes six characters.
432///
433/// A marker whose body is only an argument splices the value and resolves nothing:
434/// `id="square-$h{{x}}"`. An argument is a value and never a template, so `$a{{x}}` is
435/// refused. An argument the request does not carry is [`Error::MissingArgument`].
436///
437/// **Per-marker errors.** By default a marker that fails fails the whole compose, with
438/// the marker's own typed error (a `NotFound` stays a `NotFound`). A marker may instead
439/// name fallbacks, tried left to right until one succeeds — `$h{urn:example:title ||
440/// urn:example:untitled}`, or `$h{{title} || urn:example:untitled}` for a missing
441/// argument — and the last alternative's error is the one reported. A fallback covers
442/// everything that can go wrong with its marker (resolution, a missing argument, a `$a`
443/// whose own markers fail); a marker that cannot be parsed fails the whole compose. The
444/// kernel decides what a fallback is worth caching: one standing in for an absent
445/// resource is cached and cut when the resource appears, and one standing in for a
446/// denial or any other failure makes the composite uncacheable.
447///
448/// **Authority.** Compose is its caller's deputy. The template named by `src`, and every
449/// marker in it at every depth, resolve under the capability the compose request was
450/// issued with — never more: nothing a caller cannot source directly is reachable through
451/// a template, by any marker, fallback, nested compose or view. A template therefore acts
452/// with the authority of whoever FILLS it, not of whoever wrote it, which is what lets a
453/// view read the viewer's own data. The other side of that rule is the caller's to hold:
454/// before filling a template it does not trust — one a peer or a user could have written,
455/// or a `src` forwarded from outside — narrow the capability first
456/// (`Capability::attenuate`, or `Invocation::issue_attenuated` from inside an endpoint);
457/// the narrowing reaches every marker. `tests/authority.rs` pins both halves (ledger
458/// #609).
459///
460/// The `a` is for *asynchronous*: the first alternatives of a level's markers are forked
461/// and joined, so a kernel driven on a concurrent executor resolves them simultaneously,
462/// while a single-threaded executor (the browser, for now) resolves them in turn.
463///
464/// The output mirrors the source's media type. It declares itself cacheable, so the
465/// kernel keeps it cacheable only while every part it read is — one volatile constituent
466/// makes the whole composite volatile, automatically.
467///
468/// ```
469/// use std::sync::Arc;
470/// use futures::executor::block_on;
471/// use ikigai_core::{
472/// ArgRef, Capability, EndpointSpace, Exact, FnEndpoint, Invocation, Iri, Kernel,
473/// ReprType, Representation, Request, Verb,
474/// };
475///
476/// let html = |body: &'static str| {
477/// FnEndpoint::new("fixed", move |_: &Invocation<'_>| {
478/// Ok(Representation::new(ReprType::new("text/html"), body.as_bytes().to_vec())
479/// .cacheable())
480/// })
481/// };
482/// let space = EndpointSpace::new()
483/// .bind(Exact::new("urn:iki:fn:compose"), ikigai_fn::compose())
484/// .bind(Exact::new("urn:example:mark"), html(r#"<i>"&'</i>$a{urn:example:secret}"#))
485/// .bind(
486/// Exact::new("urn:example:page"),
487/// html(r#"<b title="$h{urn:example:mark}">$h{urn:example:mark}</b>"#),
488/// );
489/// let kernel = Kernel::new(Arc::new(space));
490/// let request = Request::new(Verb::Source, Iri::parse("urn:iki:fn:compose").unwrap())
491/// .with_arg("src", ArgRef::Inline(b"urn:example:page".to_vec()));
492/// let page = block_on(kernel.issue(request, &Capability::root())).unwrap();
493/// // Escaped for text and for either quote, and the marker in the value is not
494/// // expanded: `urn:example:secret` is not even bound.
495/// let mark = "<i>"&'</i>$a{urn:example:secret}";
496/// assert_eq!(
497/// String::from_utf8(page.bytes).unwrap(),
498/// format!(r#"<b title="{mark}">{mark}</b>"#)
499/// );
500/// ```
501pub struct Compose;
502
503#[async_trait]
504impl Endpoint for Compose {
505 async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
506 let src = inv.inline_str("src")?;
507 let iri = Iri::parse(src).map_err(|e| Error::InvalidArgument {
508 name: "src".to_string(),
509 detail: format!("not an IRI: {e}"),
510 })?;
511 compose_template(inv, &iri).await
512 }
513
514 fn name(&self) -> &str {
515 "compose"
516 }
517
518 fn describe(&self) -> Description {
519 Description::new("compose")
520 .title("Compose")
521 .summary(
522 "Fills the template named by the `src` argument: `$a{<iri>}` splices a \
523 resource and expands its own markers, `$r{<iri>}` splices it as it is, \
524 `$h{<iri>}` splices it as HTML-escaped text, and `$j{<src> <program>}` \
525 splices a jq selection of `src` (urn:json:query) as `$h` does. `{name}` in a marker is \
526 a template argument — any other argument of this request — and \
527 `$h{<iri> || <fallback>}` renders the fallback when the first fails. A \
528 literal `$` is written `$$`. The output mirrors the source's media type \
529 and stays cacheable only while every part it read is.",
530 )
531 .verb(Verb::Source)
532 .verb(Verb::Meta)
533 .input(
534 ArgSpec::new("src")
535 .summary("the IRI of the template to fill")
536 .class(XSD_ANY_URI),
537 )
538 .open_arguments("each fills a {name} marker in the body")
539 // No `.output(…)`. `invoke` returns the SHAPE's `repr_type` unchanged, so the
540 // served type is the source's and not compose's to declare: over an HTML shape
541 // it serves HTML, over a Turtle one Turtle. It declared `text/html` through
542 // 0.2.1 — true of the shapes we happened to write, false as a contract, and a
543 // declaration that is merely what today's fixture produced is a lie that passes
544 // every check. `outputs` is a closed list in core's `Description` with no
545 // pass-through spelling (core PENDING §20); until there is one, announcing
546 // nothing is the only honest option, and `tests/conformance.rs` waives
547 // `Check::Outputs` here and pins the pass-through by hand.
548 //
549 // Template arguments form an open set: the template determines their names.
550 }
551}
552
553/// `compose`: fill the template named by `src`. See [`Compose`].
554pub fn compose() -> Compose {
555 Compose
556}
557
558/// The name every [`ComposeOver`] answers until it is [`named`](ComposeOver::named): the
559/// KIND of endpoint it is.
560pub const COMPOSE_OVER: &str = "composeOver";
561
562/// `composeOver`: a template bound at a NAME — [`Compose`] with its `src` fixed.
563///
564/// Bind it under a URI template and the variables the name captures are the template's
565/// arguments, so a parameterized view is a resource like any other:
566/// `urn:example:view:square:{x}:{y}` over `urn:example:template:square` answers
567/// `urn:example:view:square:0:2` with the template filled for `x=0`, `y=2`. That name is
568/// what a composer that takes an IRI (`conditional`'s `then`, another template's marker)
569/// can point at, and what the cache and a golden thread key on. The template is sourced
570/// through the kernel, so editing it recomputes every view over it.
571///
572/// **One endpoint per template, so one name per template.** Every instance answers
573/// [`name`](Endpoint::name) with `composeOver` unless it is [`named`](Self::named), and a
574/// name is how the ecosystem tells endpoints apart: a declared space binds a door to an
575/// endpoint BY NAME (`ik:endpointName`), and core's `Registry` refuses a second, different
576/// endpoint under a name already taken. So an application with several views names each
577/// one, and the name is also its [`describe`](Endpoint::describe) id — see there.
578pub struct ComposeOver {
579 src: Iri,
580 name: String,
581}
582
583impl ComposeOver {
584 /// Give this instance its own name (builder) — what [`name`](Endpoint::name) answers,
585 /// what a declared door binds it by, and its description id. Without it the name is
586 /// [`COMPOSE_OVER`].
587 ///
588 /// The name is published: it becomes the catalog node `urn:ikigai:endpoint:{name}`
589 /// and an MCP tool name, so give it the shape of an endpoint id — short, IRI-safe,
590 /// `kebab-case` by convention (`ttt-view-board`). It is not checked here; core's
591 /// `Description::validate` reports an id that is not IRI-safe.
592 pub fn named(mut self, name: impl Into<String>) -> Self {
593 self.name = name.into();
594 self
595 }
596}
597
598#[async_trait]
599impl Endpoint for ComposeOver {
600 async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
601 compose_template(inv, &self.src).await
602 }
603
604 fn name(&self) -> &str {
605 &self.name
606 }
607
608 /// The description's id is the instance's NAME, and its title is the KIND.
609 ///
610 /// The id is what the ecosystem keys an endpoint on: the catalog subject
611 /// `urn:ikigai:endpoint:{id}`, the action IRI `urn:kernel:validate` looks an endpoint
612 /// up by, the MCP tool name, and the identity guard type-driven selection checks a
613 /// template door against. Five views all describing themselves as `composeOver` would
614 /// be ONE catalog node carrying five summaries, one validate target (whichever was
615 /// found first), and one MCP tool fronting five different templates behind a
616 /// synthesized selector argument, summarized as whichever template came first. So a
617 /// named instance is described under its name, and each view is its own entry
618 /// everywhere. The kind is not lost: the title stays "Compose over a template" for
619 /// every instance, and the summary names the template. An unnamed instance describes
620 /// itself exactly as it did before `named` existed.
621 fn describe(&self) -> Description {
622 Description::new(self.name.as_str())
623 .title("Compose over a template")
624 .summary(format!(
625 "Fills the template `{}` as compose does, with the variables this name \
626 captured (and any other arguments) as its template arguments.",
627 self.src.as_str()
628 ))
629 .verb(Verb::Source)
630 .verb(Verb::Meta)
631 // No inputs: the captured variables are the binding's, not this endpoint's, and
632 // the rest are compose's open set (see `Compose::describe`). No output, for
633 // compose's reason: the served type is the template's.
634 }
635}
636
637/// `composeOver`: the template `src`, filled — bind it at the name of a view. See
638/// [`ComposeOver`].
639///
640/// An application with more than one view names each one with
641/// [`named`](ComposeOver::named), because a name is how a declared space finds its
642/// endpoint. The name answers [`name`](Endpoint::name) and is the description's id:
643///
644/// ```
645/// use std::sync::Arc;
646/// use futures::executor::block_on;
647/// use ikigai_core::{
648/// Capability, Endpoint, EndpointSpace, Exact, FnEndpoint, Iri, Kernel, ReprType,
649/// Representation, Request, Verb,
650/// };
651///
652/// let board = ikigai_fn::compose_over(Iri::parse("urn:example:template:board").unwrap())
653/// .named("board-view");
654/// assert_eq!(board.name(), "board-view");
655/// assert_eq!(board.describe().id, "board-view");
656/// assert_eq!(board.describe().title, "Compose over a template");
657///
658/// // Unnamed, it is the kind — the name every instance shares.
659/// let plain = ikigai_fn::compose_over(Iri::parse("urn:example:template:board").unwrap());
660/// assert_eq!(plain.name(), ikigai_fn::COMPOSE_OVER);
661/// assert_eq!(plain.describe().id, "composeOver");
662///
663/// // A name changes what the endpoint is called, never what it answers.
664/// let template = FnEndpoint::new("board", |_| {
665/// Ok(Representation::new(ReprType::new("text/html"), b"<p>$h{{who}}</p>".to_vec()))
666/// });
667/// let space = EndpointSpace::new()
668/// .bind(Exact::new("urn:example:template:board"), template)
669/// .bind(Exact::new("urn:example:view:board"), board);
670/// let kernel = Kernel::new(Arc::new(space));
671/// let request = Request::new(Verb::Source, Iri::parse("urn:example:view:board").unwrap())
672/// .with_arg("who", ikigai_core::ArgRef::Inline(b"<X>".to_vec()));
673/// let view = block_on(kernel.issue(request, &Capability::root())).unwrap();
674/// assert_eq!(view.bytes, b"<p><X></p>");
675/// ```
676pub fn compose_over(src: Iri) -> ComposeOver {
677 ComposeOver {
678 src,
679 name: COMPOSE_OVER.to_string(),
680 }
681}
682
683/// Source the template `src` and fill it: the one body of [`Compose`] and
684/// [`ComposeOver`].
685async fn compose_template(inv: &Invocation<'_>, src: &Iri) -> Result<Representation> {
686 let shape = inv.source(src).await?;
687 let Representation {
688 repr_type, bytes, ..
689 } = shape;
690 let text = String::from_utf8(bytes)
691 .map_err(|_| Error::Endpoint(format!("compose: `{}` is not UTF-8 text", src.as_str())))?;
692 let expanded = expand(inv, Args::Request, text, 0).await?;
693 Ok(Representation::new(repr_type, expanded.into_bytes()).cacheable())
694}
695
696/// `conditional`: the **lazy** sibling of [`Compose`]. Sources the `if` resource,
697/// reads it as a boolean, and sources — and returns — **only** `then` (true) or the
698/// optional `else` (false). The untaken branch is never invoked, so neither its
699/// work nor its golden threads enter the result. `if` is always evaluated; a false
700/// condition with no `else` yields an empty representation. Because each branch is
701/// taken via `inv.source`, dependencies propagate: if `if`'s value later flips (its
702/// thread is cut), the conditional recomputes and can take the other branch.
703///
704/// With `equals`, the condition is "`if`'s text, trimmed, is exactly `equals`" instead
705/// of a boolean — so a template can branch on a VALUE (`if` a cell `equals=-`, it is
706/// empty) with no predicate resource written for it.
707///
708/// The contract is checked before the branch is chosen: `then` is required whatever
709/// `if` says, and `if`/`then`/`else` must each be an IRI whether or not they end up
710/// sourced. Only the SOURCING is lazy.
711pub struct Conditional;
712
713#[async_trait]
714impl Endpoint for Conditional {
715 async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
716 // The whole contract is held BEFORE the branch is chosen: `then` is required
717 // and every IRI-classed input must parse as one, whichever side ends up taken.
718 // Laziness is about what gets SOURCED, not about which arguments are read — a
719 // `then` demanded only when `if` is true is "declared required, actually
720 // optional", and an `else` parsed only when taken is a class enforced on one
721 // path (ikigai-conformance PENDING #49, #118).
722 let cond_iri = parse_iri(inv.inline_str("if")?, "if")?;
723 let then_iri = parse_iri(inv.inline_str("then")?, "then")?;
724 let else_iri = match inv.inline_str("else") {
725 Ok(uri) => Some(parse_iri(uri, "else")?),
726 Err(Error::MissingArgument(_)) => None,
727 Err(e) => return Err(e),
728 };
729 let equals = match inv.inline_str("equals") {
730 Ok(value) => Some(value),
731 Err(Error::MissingArgument(_)) => None,
732 Err(e) => return Err(e),
733 };
734 let verdict = inv.source(&cond_iri).await?;
735 let taken = match equals {
736 Some(value) => as_text(&verdict.bytes, &cond_iri)?.trim() == value,
737 None => as_bool(&verdict.bytes, &cond_iri)?,
738 };
739 if taken {
740 inv.source(&then_iri).await
741 } else {
742 match else_iri {
743 Some(iri) => inv.source(&iri).await,
744 // A false condition with no `else` is a no-op. The empty result is a
745 // function of `if` alone, so it is marked cacheable: the kernel folds
746 // `if`'s expiry and threads in, and a cut of `if` recomputes it — the
747 // same rule as the taken branches, no less.
748 None => Ok(Representation::new(text_plain_utf8(), Vec::new()).cacheable()),
749 }
750 }
751 }
752
753 fn name(&self) -> &str {
754 "conditional"
755 }
756
757 fn describe(&self) -> Description {
758 Description::new("conditional")
759 .title("Conditional")
760 .summary(
761 "Sources `if` and reads it as a boolean (true/false/1/0/yes/no/on/off) — or, \
762 with `equals`, tests whether its trimmed text is exactly that value — then \
763 sources and returns ONLY `then` (when true) or the optional `else` (when \
764 false); the untaken branch is never invoked. A false condition with no \
765 `else` returns nothing. The lazy counterpart to compose's eager fan-out.",
766 )
767 .verb(Verb::Source)
768 .verb(Verb::Meta)
769 .input(
770 ArgSpec::new("if")
771 .summary(
772 "IRI of a resource whose value is a boolean (or is compared to `equals`)",
773 )
774 .class(XSD_ANY_URI),
775 )
776 .input(
777 ArgSpec::new("then")
778 .summary("IRI to source and return when `if` is true")
779 .class(XSD_ANY_URI),
780 )
781 .input(
782 ArgSpec::new("else")
783 .summary("IRI to source and return when `if` is false (optional)")
784 .class(XSD_ANY_URI)
785 .optional(),
786 )
787 .input(
788 ArgSpec::new("equals")
789 .summary(
790 "compare `if`'s trimmed text to this value instead of reading it as \
791 a boolean (optional)",
792 )
793 .class(XSD_STRING)
794 .optional(),
795 )
796 // No `.output(…)`, for compose's reason: a taken branch is returned from
797 // `inv.source` unchanged, so the served type is the branch's. The one
798 // representation this endpoint authors itself — a false condition with no
799 // `else` — is `text/plain; charset=utf-8`, and declaring THAT would silence
800 // `Check::Outputs` (it matches what the walk's fixture happens to serve) while
801 // telling a consumer that a Turtle `then` comes back as plain text. Waived and
802 // pinned by hand in `tests/conformance.rs`; core PENDING §20 is the condition
803 // for replacing both waivers with a real pass-through spelling.
804 }
805}
806
807/// `conditional`: branch on a boolean resource, invoking only the taken side. See
808/// [`Conditional`].
809pub fn conditional() -> Conditional {
810 Conditional
811}
812
813// --- each: one template fill per element of a JSON array ---------------------
814
815/// The resource a `$j{<src> <program>}` marker names: ikigai-json's jq selection. The
816/// marker is sugar for `$h{urn:json:query?src=<src>&q=<program>&as=text/plain}`, always
817/// this full name, so it works with or without a prefix table.
818pub const JQ_QUERY: &str = "urn:json:query";
819
820/// The most elements [`each`] fills a template for: 10,000. More is refused, naming the
821/// bound, before any template is filled.
822pub const EACH_MAX_ELEMENTS: usize = 10_000;
823
824/// The most fields one object element may carry: 256.
825pub const EACH_MAX_FIELDS: usize = 256;
826
827/// The most bytes [`each`] answers: 8 MiB. A longer answer is refused, naming the bound.
828pub const EACH_MAX_OUTPUT: usize = 8 << 20;
829
830/// `each`: render a collection — fill the template `template` once per element of the
831/// JSON array `src` answers, and concatenate the fills in order.
832///
833/// - An OBJECT element's top-level fields are the template's `{arguments}`, filled exactly
834/// as [`Compose`] fills request arguments: `$h{{name}}` splices one as escaped text, and
835/// `{name}` in a marker's IRI is percent-encoded as one segment.
836/// - A SCALAR element is `{value}`. A string is its text, a number its shortest decimal
837/// form, a boolean `true` or `false`.
838/// - `{index}` is the element's position, from 0. It is always the position: a field
839/// named `index` does not replace it.
840/// - A `null` field, or a `null` element's `value`, is ABSENT, so a fallback covers it:
841/// `$h{{title} || {name}}`.
842/// - A NESTED value (an object or array inside an element, or an array element) is
843/// refused, naming the element. Select the flat shape first (`$j`, or `urn:json:query`).
844///
845/// Optional: `empty`, a template filled (with no arguments) when the array is empty —
846/// without it an empty array answers nothing — and `separator`, text put between two
847/// fills, HTML-escaped as `$h` escapes.
848///
849/// **Element data is DATA.** It reaches the output only through an escaping marker
850/// (`$h`, `$j`): a template filled per element that splices an argument as it is
851/// (`$r{{name}}`, or `$r{…}` over a request that names one) is refused, at every depth of
852/// `$a`, and so is `{+name}`, so a field never chooses more than one percent-encoded
853/// segment of a name the template fixed. The request's own arguments are not template
854/// arguments here: only the element's are. Nothing in an element is ever scanned for
855/// markers, so a field holding `$a{urn:example:secret}` renders as those characters.
856///
857/// **Authority** is compose's: `src`, the templates and every marker resolve under the
858/// caller's capability.
859///
860/// **Cacheable** exactly when what it read is: it declares itself cacheable, and the
861/// kernel keeps it so only while `src`, the template and every marker's answer are,
862/// golden-threaded from each, so a write to `src` or to the template recomputes it.
863///
864/// **Bounds:** [`EACH_MAX_ELEMENTS`], [`EACH_MAX_FIELDS`], [`EACH_MAX_OUTPUT`]. The array
865/// is read by a typed deserializer that refuses a nested value at its first bracket, so
866/// it never descends below an element's fields: depth is bounded by the shape, with no
867/// pre-scan needed.
868///
869/// The output's media type is the template's.
870///
871/// ```
872/// use std::sync::Arc;
873/// use futures::executor::block_on;
874/// use ikigai_core::{
875/// ArgRef, Capability, Exact, FnEndpoint, Iri, Kernel, ReprType, Representation, Request,
876/// Verb,
877/// };
878///
879/// let fixed = |media: &'static str, body: &'static str| {
880/// FnEndpoint::new("fixed", move |_| {
881/// Ok(Representation::new(ReprType::new(media), body.as_bytes().to_vec()).cacheable())
882/// })
883/// };
884/// let space = ikigai_fn::space()
885/// .bind(
886/// Exact::new("urn:example:people"),
887/// fixed("application/json", r#"[{"name":"Ada"},{"name":"<Grace>"}]"#),
888/// )
889/// .bind(Exact::new("urn:example:row"), fixed("text/html", "<li>$h{{index}}: $h{{name}}</li>"));
890/// let kernel = Kernel::new(Arc::new(space));
891/// let request = Request::new(Verb::Source, Iri::parse("urn:iki:fn:each").unwrap())
892/// .with_arg("src", ArgRef::Inline(b"urn:example:people".to_vec()))
893/// .with_arg("template", ArgRef::Inline(b"urn:example:row".to_vec()));
894/// let list = block_on(kernel.issue(request, &Capability::root())).unwrap();
895/// assert_eq!(list.bytes, b"<li>0: Ada</li><li>1: <Grace></li>");
896/// ```
897pub struct Each;
898
899#[async_trait]
900impl Endpoint for Each {
901 async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
902 let src = parse_iri(inv.inline_str("src")?, "src")?;
903 let template = parse_iri(inv.inline_str("template")?, "template")?;
904 let empty = match inv.inline_str("empty") {
905 Ok(iri) => Some(parse_iri(iri, "empty")?),
906 Err(Error::MissingArgument(_)) => None,
907 Err(e) => return Err(e),
908 };
909 let separator = match inv.inline_str("separator") {
910 Ok(text) => html::html_text(text),
911 Err(Error::MissingArgument(_)) => String::new(),
912 Err(e) => return Err(e),
913 };
914 let collection = inv.source(&src).await?;
915 let elements = parse_elements(&collection.bytes, &src)?;
916 let shape = inv.source(&template).await?;
917 if elements.is_empty() {
918 if let Some(empty) = empty {
919 let shape = inv.source(&empty).await?;
920 let text = template_text(shape.bytes, &empty)?;
921 let none = Fields::new();
922 let filled = expand(inv, Args::Element(&none), text, 0).await?;
923 return Ok(Representation::new(shape.repr_type, filled.into_bytes()).cacheable());
924 }
925 return Ok(Representation::new(shape.repr_type, Vec::new()).cacheable());
926 }
927 let text = template_text(shape.bytes, &template)?;
928 let fills = try_join_all(
929 elements
930 .iter()
931 .map(|fields| expand(inv, Args::Element(fields), text.clone(), 0)),
932 )
933 .await?;
934 let mut out = String::new();
935 for (i, fill) in fills.iter().enumerate() {
936 if i > 0 {
937 out.push_str(&separator);
938 }
939 out.push_str(fill);
940 if out.len() > EACH_MAX_OUTPUT {
941 return Err(Error::Endpoint(format!(
942 "each: the answer passed {EACH_MAX_OUTPUT} bytes (EACH_MAX_OUTPUT) at \
943 element {i} of {}",
944 fills.len()
945 )));
946 }
947 }
948 Ok(Representation::new(shape.repr_type, out.into_bytes()).cacheable())
949 }
950
951 fn name(&self) -> &str {
952 "each"
953 }
954
955 fn describe(&self) -> Description {
956 Description::new("each")
957 .title("Each")
958 .summary(
959 "Fills the template `template` once per element of the JSON array `src` \
960 answers, in order: an object's top-level fields are its `{arguments}`, a \
961 scalar is `{value}`, and `{index}` is the position. Element data reaches \
962 the output only escaped (`$h`, `$j`); a nested value is refused. Optional \
963 `empty` (a template for an empty array) and `separator` (escaped text \
964 between fills). The output is the template's media type, cacheable while \
965 everything it read is.",
966 )
967 .verb(Verb::Source)
968 .verb(Verb::Meta)
969 .input(
970 ArgSpec::new("src")
971 .summary("the IRI of a resource whose answer is a JSON array")
972 .class(XSD_ANY_URI),
973 )
974 .input(
975 ArgSpec::new("template")
976 .summary("the IRI of the template filled once per element")
977 .class(XSD_ANY_URI),
978 )
979 .input(
980 ArgSpec::new("empty")
981 .summary("the IRI of a template filled when the array is empty (optional)")
982 .class(XSD_ANY_URI)
983 .optional(),
984 )
985 .input(
986 ArgSpec::new("separator")
987 .summary("text put between two fills, HTML-escaped (optional)")
988 .class(XSD_STRING)
989 .optional(),
990 )
991 // No `.output(…)`, for compose's reason: the served type is the template's.
992 }
993}
994
995/// `each`: one template fill per element of a JSON array. See [`Each`].
996pub fn each() -> Each {
997 Each
998}
999
1000/// A template's bytes as UTF-8 text.
1001fn template_text(bytes: Vec<u8>, iri: &Iri) -> Result<String> {
1002 String::from_utf8(bytes)
1003 .map_err(|_| Error::Endpoint(format!("each: `{}` is not UTF-8 text", iri.as_str())))
1004}
1005
1006/// The elements of the JSON array `bytes`, each as its template arguments.
1007fn parse_elements(bytes: &[u8], src: &Iri) -> Result<Vec<Fields>> {
1008 use serde::de::DeserializeSeed;
1009 let mut de = serde_json::Deserializer::from_slice(bytes);
1010 let elements = ElementsSeed
1011 .deserialize(&mut de)
1012 .and_then(|elements| de.end().map(|()| elements))
1013 .map_err(|e| {
1014 Error::Endpoint(format!(
1015 "each: `{}` is not a JSON array of flat objects or scalars: {e}",
1016 src.as_str()
1017 ))
1018 })?;
1019 Ok(elements)
1020}
1021
1022/// The array: at most [`EACH_MAX_ELEMENTS`] elements, each an object or a scalar.
1023struct ElementsSeed;
1024
1025impl<'de> serde::de::DeserializeSeed<'de> for ElementsSeed {
1026 type Value = Vec<Fields>;
1027 fn deserialize<D: serde::Deserializer<'de>>(
1028 self,
1029 de: D,
1030 ) -> std::result::Result<Self::Value, D::Error> {
1031 de.deserialize_any(self)
1032 }
1033}
1034
1035impl<'de> serde::de::Visitor<'de> for ElementsSeed {
1036 type Value = Vec<Fields>;
1037
1038 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1039 f.write_str("a JSON array")
1040 }
1041
1042 fn visit_seq<A: serde::de::SeqAccess<'de>>(
1043 self,
1044 mut seq: A,
1045 ) -> std::result::Result<Self::Value, A::Error> {
1046 let mut elements = Vec::new();
1047 while let Some(mut fields) = seq.next_element_seed(ElementSeed(elements.len()))? {
1048 if elements.len() == EACH_MAX_ELEMENTS {
1049 return Err(serde::de::Error::custom(format!(
1050 "more than {EACH_MAX_ELEMENTS} elements (EACH_MAX_ELEMENTS)"
1051 )));
1052 }
1053 fields.insert("index".to_string(), elements.len().to_string());
1054 elements.push(fields);
1055 }
1056 Ok(elements)
1057 }
1058}
1059
1060/// One element, at its position: an object's fields, or a scalar as `value`.
1061struct ElementSeed(usize);
1062
1063impl<'de> serde::de::DeserializeSeed<'de> for ElementSeed {
1064 type Value = Fields;
1065 fn deserialize<D: serde::Deserializer<'de>>(
1066 self,
1067 de: D,
1068 ) -> std::result::Result<Self::Value, D::Error> {
1069 de.deserialize_any(self)
1070 }
1071}
1072
1073impl<'de> serde::de::Visitor<'de> for ElementSeed {
1074 type Value = Fields;
1075
1076 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1077 write!(f, "element {}: an object of scalars, or a scalar", self.0)
1078 }
1079
1080 fn visit_map<A: serde::de::MapAccess<'de>>(
1081 self,
1082 mut map: A,
1083 ) -> std::result::Result<Self::Value, A::Error> {
1084 let mut fields = Fields::new();
1085 let mut count = 0usize;
1086 while let Some(key) = map.next_key::<String>()? {
1087 count += 1;
1088 if count > EACH_MAX_FIELDS {
1089 return Err(serde::de::Error::custom(format!(
1090 "element {}: more than {EACH_MAX_FIELDS} fields (EACH_MAX_FIELDS)",
1091 self.0
1092 )));
1093 }
1094 match map.next_value_seed(ScalarSeed { element: self.0 })? {
1095 Some(value) => {
1096 fields.insert(key, value);
1097 }
1098 None => {
1099 fields.remove(&key);
1100 }
1101 }
1102 }
1103 Ok(fields)
1104 }
1105
1106 fn visit_seq<A: serde::de::SeqAccess<'de>>(
1107 self,
1108 _: A,
1109 ) -> std::result::Result<Self::Value, A::Error> {
1110 Err(nested(self.0))
1111 }
1112
1113 fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<Self::Value, E> {
1114 Ok(scalar(Some(v.to_string())))
1115 }
1116 fn visit_bool<E: serde::de::Error>(self, v: bool) -> std::result::Result<Self::Value, E> {
1117 Ok(scalar(Some(v.to_string())))
1118 }
1119 fn visit_i64<E: serde::de::Error>(self, v: i64) -> std::result::Result<Self::Value, E> {
1120 Ok(scalar(Some(v.to_string())))
1121 }
1122 fn visit_u64<E: serde::de::Error>(self, v: u64) -> std::result::Result<Self::Value, E> {
1123 Ok(scalar(Some(v.to_string())))
1124 }
1125 fn visit_f64<E: serde::de::Error>(self, v: f64) -> std::result::Result<Self::Value, E> {
1126 Ok(scalar(Some(v.to_string())))
1127 }
1128 fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
1129 Ok(scalar(None))
1130 }
1131}
1132
1133/// A scalar element's fields: `value`, when it is not `null`.
1134fn scalar(value: Option<String>) -> Fields {
1135 value
1136 .map(|v| Fields::from([("value".to_string(), v)]))
1137 .unwrap_or_default()
1138}
1139
1140/// The refusal of a nested value, at its first bracket.
1141fn nested<E: serde::de::Error>(element: usize) -> E {
1142 E::custom(format!(
1143 "element {element}: a nested object or array — `each` fills a template from flat \
1144 elements; select the flat shape first (`$j`, or `urn:json:query`)"
1145 ))
1146}
1147
1148/// One field's value: its text, or `None` for `null`; a nested value is refused.
1149struct ScalarSeed {
1150 element: usize,
1151}
1152
1153impl<'de> serde::de::DeserializeSeed<'de> for ScalarSeed {
1154 type Value = Option<String>;
1155 fn deserialize<D: serde::Deserializer<'de>>(
1156 self,
1157 de: D,
1158 ) -> std::result::Result<Self::Value, D::Error> {
1159 de.deserialize_any(self)
1160 }
1161}
1162
1163impl<'de> serde::de::Visitor<'de> for ScalarSeed {
1164 type Value = Option<String>;
1165
1166 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1167 write!(f, "element {}: a scalar field value", self.element)
1168 }
1169
1170 fn visit_map<A: serde::de::MapAccess<'de>>(
1171 self,
1172 _: A,
1173 ) -> std::result::Result<Self::Value, A::Error> {
1174 Err(nested(self.element))
1175 }
1176 fn visit_seq<A: serde::de::SeqAccess<'de>>(
1177 self,
1178 _: A,
1179 ) -> std::result::Result<Self::Value, A::Error> {
1180 Err(nested(self.element))
1181 }
1182 fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<Self::Value, E> {
1183 Ok(Some(v.to_string()))
1184 }
1185 fn visit_bool<E: serde::de::Error>(self, v: bool) -> std::result::Result<Self::Value, E> {
1186 Ok(Some(v.to_string()))
1187 }
1188 fn visit_i64<E: serde::de::Error>(self, v: i64) -> std::result::Result<Self::Value, E> {
1189 Ok(Some(v.to_string()))
1190 }
1191 fn visit_u64<E: serde::de::Error>(self, v: u64) -> std::result::Result<Self::Value, E> {
1192 Ok(Some(v.to_string()))
1193 }
1194 fn visit_f64<E: serde::de::Error>(self, v: f64) -> std::result::Result<Self::Value, E> {
1195 Ok(Some(v.to_string()))
1196 }
1197 fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
1198 Ok(None)
1199 }
1200}
1201
1202/// Parse an argument that must be an IRI, reporting which argument if it isn't.
1203fn parse_iri(s: &str, arg: &str) -> Result<Iri> {
1204 Iri::parse(s).map_err(|e| Error::InvalidArgument {
1205 name: arg.to_string(),
1206 detail: format!("not an IRI: {e}"),
1207 })
1208}
1209
1210/// A condition's bytes as UTF-8 text.
1211fn as_text<'b>(bytes: &'b [u8], iri: &Iri) -> Result<&'b str> {
1212 std::str::from_utf8(bytes)
1213 .map_err(|_| Error::Endpoint(format!("conditional: `{}` is not UTF-8 text", iri.as_str())))
1214}
1215
1216/// Interpret a resource's bytes as a boolean — lenient on common spellings, strict
1217/// on anything else so a malformed condition can't silently mis-branch.
1218fn as_bool(bytes: &[u8], iri: &Iri) -> Result<bool> {
1219 let s = as_text(bytes, iri)?.trim().to_ascii_lowercase();
1220 match s.as_str() {
1221 "true" | "1" | "yes" | "on" => Ok(true),
1222 "false" | "0" | "no" | "off" | "" => Ok(false),
1223 other => Err(Error::Endpoint(format!(
1224 "conditional: `{}` returned {other:?}, not a boolean (true/false/1/0/yes/no/on/off)",
1225 iri.as_str()
1226 ))),
1227 }
1228}
1229
1230/// How a marker splices what it resolves.
1231#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1232enum Mode {
1233 /// `$a{…}`: as it is, and then its own markers expanded.
1234 Transclude,
1235 /// `$r{…}`: as it is, terminated.
1236 Raw,
1237 /// `$h{…}`: as text, HTML-escaped, terminated.
1238 Html,
1239 /// `$j{<src> <program>}`: a jq selection of `src` ([`JQ_QUERY`]), spliced as `$h`
1240 /// splices: as text, HTML-escaped, terminated.
1241 Jq,
1242}
1243
1244impl Mode {
1245 /// Every mode, in the order compose learned its letter. The ONE list: the scanner
1246 /// reads letters through it and [`MARKER_LETTERS`] is built from it, so a mode left
1247 /// out is a marker nothing recognizes (and its own tests fail), never a marker the
1248 /// parser reads and the escape misses.
1249 const ALL: [Mode; 4] = [Mode::Transclude, Mode::Raw, Mode::Html, Mode::Jq];
1250
1251 /// The letter that spells this mode after `$`.
1252 const fn letter(self) -> u8 {
1253 match self {
1254 Mode::Transclude => b'a',
1255 Mode::Raw => b'r',
1256 Mode::Html => b'h',
1257 Mode::Jq => b'j',
1258 }
1259 }
1260
1261 /// Whether what this mode splices is escaped as text — the only way element data
1262 /// ([`each`]) may reach the output.
1263 fn escapes(self) -> bool {
1264 matches!(self, Mode::Html | Mode::Jq)
1265 }
1266
1267 /// The mode a marker letter spells, if it spells one.
1268 fn from_letter(letter: u8) -> Option<Mode> {
1269 Mode::ALL.into_iter().find(|mode| mode.letter() == letter)
1270 }
1271}
1272
1273/// The letters [`Mode::ALL`] spells, as `char`s for [`MARKER_LETTERS`].
1274const LETTERS: [char; Mode::ALL.len()] = {
1275 let mut letters = ['\0'; Mode::ALL.len()];
1276 let mut i = 0;
1277 while i < letters.len() {
1278 letters[i] = Mode::ALL[i].letter() as char;
1279 i += 1;
1280 }
1281 letters
1282};
1283
1284/// The letters that open a [`compose`] marker — `$a{…}`, `$r{…}`, `$h{…}`, `$j{…}` — in
1285/// the order compose learned them (`a` in 0.2, `r` and `h` in 0.3, `j` in 0.6).
1286///
1287/// Built from the list compose's own scanner reads, so it cannot drift from it. A host
1288/// that escapes text for a template should call [`escape_markers`] rather than keep a copy
1289/// of this list: a copy escapes only the letters it knew when it was made, and the next
1290/// letter compose learns passes through it live (ledger #646). It is a slice so a new
1291/// letter is not a change to its type.
1292///
1293/// ```
1294/// assert_eq!(ikigai_fn::MARKER_LETTERS, &['a', 'r', 'h', 'j']);
1295/// ```
1296pub const MARKER_LETTERS: &[char] = &LETTERS;
1297
1298/// The marker `$` at byte `i` of `b` opens, if it opens one: a marker letter, then `{`.
1299/// Whether it is ever CLOSED is the scanner's business; [`escape_markers`] escapes an
1300/// unclosed one too, which costs nothing and stays literal.
1301fn opens_marker(b: &[u8], i: usize) -> Option<Mode> {
1302 let mode = b.get(i + 1).and_then(|letter| Mode::from_letter(*letter))?;
1303 (b.get(i + 2) == Some(&b'{')).then_some(mode)
1304}
1305
1306/// `text` written so that [`compose`] renders it exactly as it is: no marker in it
1307/// resolves, and every `$` survives.
1308///
1309/// The one thing compose reads outside a marker is `$`: `$$` is a literal `$`, and `$`
1310/// before a marker letter and `{` opens a marker. So a run of `$` is doubled whenever
1311/// compose would otherwise read it differently — a run of two or more, or a single `$`
1312/// that opens a marker — and a lone `$` before anything else is left as it is, which keeps
1313/// ordinary text (`costs $5`) readable. Compose of the result is `text`, byte for byte.
1314///
1315/// This is an escape, not a normalization: it is not idempotent, and must not be, because
1316/// `$$h{…}` in the input is text that says `$$h{…}` (say, documentation of the escape
1317/// itself), and escaping it again must keep both `$`. Escape a value once, where it enters
1318/// a template.
1319///
1320/// ```
1321/// use ikigai_fn::escape_markers;
1322///
1323/// assert_eq!(escape_markers("costs $5"), "costs $5");
1324/// assert_eq!(
1325/// escape_markers("write $h{<iri>} for text and $$ for a dollar"),
1326/// "write $$h{<iri>} for text and $$$$ for a dollar"
1327/// );
1328/// // Already-escaped text is text too: both of its `$` survive a compose.
1329/// assert_eq!(escape_markers("$$a{<iri>}"), "$$$$a{<iri>}");
1330/// ```
1331pub fn escape_markers(text: &str) -> String {
1332 let b = text.as_bytes();
1333 let mut out = String::with_capacity(text.len());
1334 let mut i = 0;
1335 while let Some(offset) = text[i..].find('$') {
1336 let start = i + offset;
1337 let end = start + b[start..].iter().take_while(|c| **c == b'$').count();
1338 // `$` is ASCII, so every index here is a char boundary.
1339 out.push_str(&text[i..end]);
1340 if end - start > 1 || opens_marker(b, start).is_some() {
1341 out.push_str(&text[start..end]);
1342 }
1343 i = end;
1344 }
1345 out.push_str(&text[i..]);
1346 out
1347}
1348
1349/// One piece of a scanned template: literal text, or a marker to resolve.
1350enum Segment {
1351 Lit(String),
1352 Marker(Mode, String),
1353}
1354
1355/// One alternative of a marker body.
1356enum Alt {
1357 /// `{name}`: a template argument's value; resolves nothing.
1358 Arg(String),
1359 /// `<iri>[?k=v&…]`: a SOURCE request. The IRI and the unquoted values may name
1360 /// template arguments.
1361 Request {
1362 iri: String,
1363 args: Vec<(String, Value)>,
1364 },
1365 /// `$j{<src> <program>}`: a SOURCE of [`JQ_QUERY`] with `src` (whose text may name
1366 /// template arguments, as an IRI does) and `q`, the program, which is template text
1367 /// only: it names no argument and nothing fills it.
1368 Jq { src: String, program: String },
1369}
1370
1371/// Where a marker's `{name}` arguments come from.
1372#[derive(Clone, Copy)]
1373enum Args<'e> {
1374 /// The request's: a variable the name captured, else an inline argument
1375 /// ([`compose`], [`compose_over`]).
1376 Request,
1377 /// One element of an [`each`] collection, and nothing else. Element data is DATA: it
1378 /// reaches the output only through an escaping marker (`$h`, `$j`), and is never
1379 /// reserved-expanded (`{+name}`) into an IRI.
1380 Element(&'e Fields),
1381}
1382
1383/// One element's template arguments: its top-level fields (or `value`), and `index`.
1384type Fields = std::collections::BTreeMap<String, String>;
1385
1386/// A marker argument: quoted literal text, unquoted text, or an `<iri>` reference.
1387struct Value {
1388 text: String,
1389 literal: bool,
1390 reference: bool,
1391}
1392
1393/// A parsed marker: how it splices, its body as written, and its alternatives in order.
1394struct Marker {
1395 mode: Mode,
1396 body: String,
1397 alts: Vec<Alt>,
1398}
1399
1400impl Marker {
1401 /// Whether any alternative reads a template argument: is one, or names one in its
1402 /// IRI or an unquoted value.
1403 fn reads_arguments(&self) -> bool {
1404 self.alts.iter().any(|alt| match alt {
1405 Alt::Arg(_) => true,
1406 Alt::Request { iri, args } => {
1407 iri.contains('{') || args.iter().any(|(_, v)| !v.literal && v.text.contains('{'))
1408 }
1409 Alt::Jq { src, .. } => src.contains('{'),
1410 })
1411 }
1412}
1413
1414/// Split `text` into ordered literal/marker segments. `$$` collapses to a literal
1415/// `$` (so `$$a{…}` becomes the literal text `$a{…}`); `$a{ … }`, `$r{ … }` and
1416/// `$h{ … }` become markers holding their trimmed body; an unterminated marker stays
1417/// literal.
1418fn scan(text: &str, nodes: &AtomicUsize) -> Result<Vec<Segment>> {
1419 let b = text.as_bytes();
1420 let mut segments = Vec::new();
1421 let mut lit = String::new();
1422 let mut ends = MarkerEnds::new(text);
1423 let mut i = 0;
1424 while i < b.len() {
1425 if b[i] == b'$' {
1426 // `$$` is a literal `$` — the escape for every marker.
1427 if b.get(i + 1) == Some(&b'$') {
1428 lit.push('$');
1429 i += 2;
1430 continue;
1431 }
1432 if let Some(mode) = opens_marker(b, i) {
1433 let brace = i + 2;
1434 if let Some(close) = ends.find(brace) {
1435 if !lit.is_empty() {
1436 push_segment(&mut segments, Segment::Lit(std::mem::take(&mut lit)), nodes)?;
1437 }
1438 let body = text[brace + 1..close].trim().to_string();
1439 push_segment(&mut segments, Segment::Marker(mode, body), nodes)?;
1440 i = close + 1;
1441 continue;
1442 }
1443 // Unterminated marker: fall through and keep the `$` literal.
1444 }
1445 }
1446 let len = utf8_len(b[i]);
1447 lit.push_str(&text[i..i + len]);
1448 i += len;
1449 }
1450 if !lit.is_empty() {
1451 push_segment(&mut segments, Segment::Lit(lit), nodes)?;
1452 }
1453 Ok(segments)
1454}
1455
1456/// Charge produced nodes before parsing or resolving their markers. This counter is
1457/// shared by sibling expansions, not by resource names or cache entries.
1458fn push_segment(segments: &mut Vec<Segment>, segment: Segment, nodes: &AtomicUsize) -> Result<()> {
1459 if nodes.fetch_add(1, Ordering::Relaxed) >= COMPOSE_MAX_NODES {
1460 return Err(compose_node_limit());
1461 }
1462 segments.push(segment);
1463 Ok(())
1464}
1465
1466/// Expand every marker in `text`. The `a` is for *asynchronous*: the first alternative
1467/// of each of a level's markers is forked via [`Invocation::fan_out`] and joined, so a
1468/// scheduled kernel resolves them **concurrently** (each spawned onto the pool,
1469/// parking on the join) while a single-threaded kernel resolves them in turn. A `$a`
1470/// result is itself expanded — a transcluded template's own markers recurse, and the
1471/// sub-expansions run concurrently too. A fallback is tried only after its marker's
1472/// first alternative failed, in turn. Boxed for the async recursion.
1473fn expand<'a>(
1474 inv: &'a Invocation<'_>,
1475 args: Args<'a>,
1476 text: String,
1477 depth: usize,
1478) -> Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>> {
1479 Box::pin(async move {
1480 let nodes = AtomicUsize::new(0);
1481 let result = expand_counted(inv, args, text, depth, &nodes).await;
1482 // A per-marker fallback must not turn exhaustion of the shared budget into
1483 // a successful (and potentially scheduling-dependent) partial answer.
1484 if nodes.load(Ordering::Relaxed) > COMPOSE_MAX_NODES {
1485 return Err(compose_node_limit());
1486 }
1487 result
1488 })
1489}
1490
1491fn expand_counted<'a>(
1492 inv: &'a Invocation<'_>,
1493 args: Args<'a>,
1494 text: String,
1495 depth: usize,
1496 nodes: &'a AtomicUsize,
1497) -> Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>> {
1498 Box::pin(async move {
1499 if depth >= COMPOSE_MAX_DEPTH {
1500 return Err(Error::Endpoint(format!(
1501 "compose: recursion limit ({COMPOSE_MAX_DEPTH}) exceeded — cyclic transclusion?"
1502 )));
1503 }
1504 let segments = scan(&text, nodes)?;
1505 // This level's markers, in document order. One that cannot be parsed is the
1506 // template's fault, and fails the whole compose whatever fallbacks it names.
1507 let markers = segments
1508 .iter()
1509 .filter_map(|segment| match segment {
1510 Segment::Marker(mode, body) => Some(parse_marker(*mode, body)),
1511 Segment::Lit(_) => None,
1512 })
1513 .collect::<Result<Vec<Marker>>>()?;
1514 if let Args::Element(_) = args {
1515 // Element data reaches the output only escaped: a marker that reads an
1516 // argument and splices as it is (`$r`) is refused, at every depth.
1517 if let Some(marker) = markers
1518 .iter()
1519 .find(|marker| !marker.mode.escapes() && marker.reads_arguments())
1520 {
1521 return Err(Error::Endpoint(format!(
1522 "each: marker `{}` reads element data and splices it as it is — element \
1523 fields reach the output only through `$h` (or `$j`)",
1524 marker.body
1525 )));
1526 }
1527 }
1528 // Fork: every first alternative that is a request resolves concurrently. An
1529 // argument is answered here, and a request that cannot be built (a missing
1530 // argument, a bad IRI) is that marker's failure — its fallback's to cover.
1531 let mut requests = Vec::new();
1532 let firsts: Vec<Option<Result<String>>> = markers
1533 .iter()
1534 .map(|marker| match &marker.alts[0] {
1535 Alt::Arg(name) => Some(template_arg(inv, args, name)),
1536 alt => match alt_request(inv, args, &marker.body, alt) {
1537 Ok(request) => {
1538 requests.push(request);
1539 None
1540 }
1541 Err(e) => Some(Err(e)),
1542 },
1543 })
1544 .collect();
1545 let mut resolved = inv.fan_out(requests).await.into_iter();
1546 let outcomes: Vec<First> = firsts
1547 .into_iter()
1548 .map(|first| match first {
1549 Some(local) => First::Local(local),
1550 None => First::Resolved(resolved.next().expect("one result per request")),
1551 })
1552 .collect();
1553 let expansions = markers
1554 .iter()
1555 .zip(outcomes)
1556 .map(|(marker, first)| async move {
1557 let mut result = match first {
1558 First::Local(value) => value.map(|value| splice_value(marker.mode, value)),
1559 First::Resolved(Ok(repr)) => {
1560 splice(inv, args, marker.mode, &marker.body, repr, depth, nodes).await
1561 }
1562 First::Resolved(Err(e)) => Err(e),
1563 };
1564 for alt in &marker.alts[1..] {
1565 if result.is_ok() {
1566 break;
1567 }
1568 result = evaluate(inv, args, marker, alt, depth, nodes).await;
1569 }
1570 result
1571 });
1572 let mut expanded = try_join_all(expansions).await?.into_iter();
1573 // Reassemble in document order.
1574 let mut out = String::with_capacity(text.len());
1575 for segment in &segments {
1576 match segment {
1577 Segment::Lit(t) => out.push_str(t),
1578 Segment::Marker(..) => {
1579 out.push_str(&expanded.next().expect("one expansion per marker"))
1580 }
1581 }
1582 }
1583 Ok(out)
1584 })
1585}
1586
1587/// A marker's first alternative, once the level's fork has joined.
1588enum First {
1589 /// Answered without the kernel: an argument's value, or the failure to build the
1590 /// request.
1591 Local(Result<String>),
1592 /// What the kernel resolved the request to.
1593 Resolved(Result<Representation>),
1594}
1595
1596/// Resolve and splice one (fallback) alternative of `marker`.
1597async fn evaluate(
1598 inv: &Invocation<'_>,
1599 args: Args<'_>,
1600 marker: &Marker,
1601 alt: &Alt,
1602 depth: usize,
1603 nodes: &AtomicUsize,
1604) -> Result<String> {
1605 match alt {
1606 Alt::Arg(name) => Ok(splice_value(marker.mode, template_arg(inv, args, name)?)),
1607 alt => {
1608 let request = alt_request(inv, args, &marker.body, alt)?;
1609 let repr = inv.issue(request).await?;
1610 splice(inv, args, marker.mode, &marker.body, repr, depth, nodes).await
1611 }
1612 }
1613}
1614
1615/// What a marker splices for the resource it resolved.
1616async fn splice(
1617 inv: &Invocation<'_>,
1618 args: Args<'_>,
1619 mode: Mode,
1620 body: &str,
1621 repr: Representation,
1622 depth: usize,
1623 nodes: &AtomicUsize,
1624) -> Result<String> {
1625 match (mode, String::from_utf8(repr.bytes)) {
1626 (Mode::Transclude, Ok(text)) => expand_counted(inv, args, text, depth + 1, nodes).await,
1627 (Mode::Raw, Ok(text)) => Ok(text),
1628 (Mode::Html | Mode::Jq, Ok(text)) => Ok(html::html_text(&text)),
1629 // A value spliced into HTML must be text: a placeholder here would be escaped
1630 // into visible garbage, or land inside an attribute.
1631 (Mode::Html | Mode::Jq, Err(e)) => Err(Error::Endpoint(format!(
1632 "compose: `{body}` is non-text ({} bytes), and `${}` splices text",
1633 e.into_bytes().len(),
1634 mode.letter() as char
1635 ))),
1636 (_, Err(e)) => Ok(format!(
1637 "<!-- compose: `{body}` is non-text ({} bytes), not inlined -->",
1638 e.into_bytes().len()
1639 )),
1640 }
1641}
1642
1643/// What a marker splices for an argument's value. (`$a` over an argument is refused
1644/// when the marker is parsed, so a value is never expanded.)
1645fn splice_value(mode: Mode, value: String) -> String {
1646 match mode {
1647 Mode::Html | Mode::Jq => html::html_text(&value),
1648 Mode::Raw | Mode::Transclude => value,
1649 }
1650}
1651
1652/// The value of the template argument `name`: the variable the name captured, else the
1653/// request's inline argument — or, for an [`each`] element, the element's field;
1654/// [`Error::MissingArgument`] if it is not there.
1655fn template_arg(inv: &Invocation<'_>, args: Args<'_>, name: &str) -> Result<String> {
1656 if let Args::Element(fields) = args {
1657 return fields
1658 .get(name)
1659 .cloned()
1660 .ok_or_else(|| Error::MissingArgument(name.to_string()));
1661 }
1662 if let Some(value) = inv.bindings.get(name) {
1663 return Ok(value.to_string());
1664 }
1665 inv.inline_str(name).map(str::to_string)
1666}
1667
1668/// Finds the `}` closing a marker whose `{` is at a given index, skipping any `}`
1669/// inside a `"…"` span (where a backslash escapes the next character) and any that
1670/// closes a `{name}` argument inside the body. `None` if unterminated.
1671///
1672/// One `MarkerEnds` serves every marker of one [`scan`], and remembers what it has
1673/// settled, so the scan stays linear in the text's length. A plain left-to-right walk
1674/// from each `$h{` would read to the end of the text at every unterminated opener,
1675/// which is quadratic (ledger #4002). Each position is settled at most once in each of
1676/// two modes: outside quotes, the index of the first `}` at brace depth zero; inside
1677/// quotes, the index of the closing `"`. An unquoted `{` (or `"`) at `p` defers to the
1678/// answer at `p + 1` in the unquoted (or quoted) mode and resumes, unquoted, just past
1679/// it. The deferrals live on an explicit stack rather than the call stack, because a
1680/// run of `{{{{…` would otherwise overflow it.
1681struct MarkerEnds<'t> {
1682 b: &'t [u8],
1683 /// The settled answers by position, unquoted and quoted: [`UNSETTLED`], [`NO_END`]
1684 /// or the index found. Allocated on the first lookup.
1685 memo: [Vec<usize>; 2],
1686 /// Positions settled, for the test that the scan is linear.
1687 #[cfg(test)]
1688 steps: usize,
1689}
1690
1691const UNSETTLED: usize = usize::MAX;
1692const NO_END: usize = usize::MAX - 1;
1693const UNQUOTED: usize = 0;
1694const QUOTED: usize = 1;
1695
1696/// A pending piece of work for [`MarkerEnds::end`].
1697enum Step {
1698 /// Settle the answer at this mode and position.
1699 Eval(usize, usize),
1700 /// Record the answer just found for this mode and position.
1701 Store(usize, usize),
1702 /// A `{…}` or `"…"` just closed at the answer: resume, unquoted, past it.
1703 Resume,
1704}
1705
1706impl<'t> MarkerEnds<'t> {
1707 fn new(text: &'t str) -> Self {
1708 MarkerEnds {
1709 b: text.as_bytes(),
1710 memo: [Vec::new(), Vec::new()],
1711 #[cfg(test)]
1712 steps: 0,
1713 }
1714 }
1715
1716 /// The index of the `}` closing the marker whose `{` is at `brace`.
1717 fn find(&mut self, brace: usize) -> Option<usize> {
1718 if self.memo[UNQUOTED].is_empty() {
1719 self.memo = [
1720 vec![UNSETTLED; self.b.len() + 1],
1721 vec![UNSETTLED; self.b.len() + 1],
1722 ];
1723 }
1724 match self.end(UNQUOTED, brace + 1) {
1725 NO_END => None,
1726 close => Some(close),
1727 }
1728 }
1729
1730 fn end(&mut self, mode: usize, start: usize) -> usize {
1731 let b = self.b;
1732 let len = b.len();
1733 let mut stack = vec![Step::Eval(mode, start)];
1734 // The answer of the work last finished; read by `Store` and `Resume`.
1735 let mut answer = NO_END;
1736 while let Some(step) = stack.pop() {
1737 match step {
1738 Step::Store(mode, p) => self.memo[mode][p] = answer,
1739 Step::Resume => {
1740 if answer != NO_END {
1741 stack.push(Step::Eval(UNQUOTED, answer + 1));
1742 }
1743 }
1744 Step::Eval(mode, p) => {
1745 // Every walk ends at or before `len`; past it nothing closes.
1746 let p = p.min(len);
1747 let known = self.memo[mode][p];
1748 if known != UNSETTLED {
1749 answer = known;
1750 continue;
1751 }
1752 #[cfg(test)]
1753 {
1754 self.steps += 1;
1755 }
1756 stack.push(Step::Store(mode, p));
1757 if p == len {
1758 answer = NO_END;
1759 continue;
1760 }
1761 let c = b[p];
1762 match (mode, c) {
1763 (UNQUOTED, b'}') | (QUOTED, b'"') => answer = p,
1764 (UNQUOTED, b'{') => {
1765 stack.push(Step::Resume);
1766 stack.push(Step::Eval(UNQUOTED, p + 1));
1767 }
1768 (UNQUOTED, b'"') => {
1769 stack.push(Step::Resume);
1770 stack.push(Step::Eval(QUOTED, p + 1));
1771 }
1772 (QUOTED, b'\\') => {
1773 // The escaped character is skipped whole, whatever it is.
1774 let next = match b.get(p + 1) {
1775 Some(&e) => p + 1 + utf8_len(e),
1776 None => len,
1777 };
1778 stack.push(Step::Eval(QUOTED, next));
1779 }
1780 _ => stack.push(Step::Eval(mode, p + utf8_len(c))),
1781 }
1782 }
1783 }
1784 }
1785 answer
1786 }
1787}
1788
1789/// Split `s` on every `sep` outside quoted text and `<iri>` argument values.
1790fn split_outside_quotes<'s>(s: &'s str, sep: &str) -> Vec<&'s str> {
1791 let b = s.as_bytes();
1792 let mut parts = Vec::new();
1793 let mut start = 0;
1794 let mut i = 0;
1795 let mut in_quote = false;
1796 let mut in_reference = false;
1797 while i < b.len() {
1798 match b[i] {
1799 b'<' if !in_quote && !in_reference && s[..i].trim_end().ends_with('=') => {
1800 in_reference = true;
1801 i += 1;
1802 }
1803 b'>' if in_reference => {
1804 in_reference = false;
1805 i += 1;
1806 }
1807 _ if in_reference => i += 1,
1808 b'\\' if in_quote => i += 2,
1809 b'"' => {
1810 in_quote = !in_quote;
1811 i += 1;
1812 }
1813 // `sep` is ASCII, so a match starts on a character boundary.
1814 _ if !in_quote && b[i..].starts_with(sep.as_bytes()) => {
1815 parts.push(&s[start..i]);
1816 i += sep.len();
1817 start = i;
1818 }
1819 _ => i += 1,
1820 }
1821 }
1822 parts.push(&s[start.min(s.len())..]);
1823 parts
1824}
1825
1826/// Parse a marker body: `alternative [|| alternative]…`, each an argument `{name}` or a
1827/// request `<iri>[?k=v&…]`. Every `{…}` must name an argument; `$a` over an argument is
1828/// refused.
1829fn parse_marker(mode: Mode, body: &str) -> Result<Marker> {
1830 let refuse = |detail: String| Error::Endpoint(format!("compose: marker `{body}`: {detail}"));
1831 if mode == Mode::Jq {
1832 // `<src> <program>`: the source runs to the first whitespace, and the program is
1833 // everything after it, as written. No `||` split and no `{name}` in the program:
1834 // jq's own `{…}` is an object, and a program is template text only.
1835 let (src, program) = body
1836 .split_once(char::is_whitespace)
1837 .map(|(src, program)| (src, program.trim()))
1838 .unwrap_or((body, ""));
1839 if program.is_empty() {
1840 return Err(refuse(
1841 "`$j{<src> <program>}` needs a source IRI, whitespace, and a jq program"
1842 .to_string(),
1843 ));
1844 }
1845 check_placeholders(src, true).map_err(refuse)?;
1846 return Ok(Marker {
1847 mode,
1848 body: body.to_string(),
1849 alts: vec![Alt::Jq {
1850 src: src.to_string(),
1851 program: program.to_string(),
1852 }],
1853 });
1854 }
1855 let mut alts = Vec::new();
1856 for alt in split_outside_quotes(body, "||") {
1857 let alt = alt.trim();
1858 if alt.is_empty() {
1859 return Err(refuse("an empty alternative".to_string()));
1860 }
1861 if let Some(name) = alt
1862 .strip_prefix('{')
1863 .and_then(|rest| rest.strip_suffix('}'))
1864 {
1865 if is_arg_name(name) {
1866 if mode == Mode::Transclude {
1867 return Err(refuse(format!(
1868 "`{{{name}}}` is an argument, a value and never a template — \
1869 splice it with `$h` or `$r`, not `$a`"
1870 )));
1871 }
1872 alts.push(Alt::Arg(name.to_string()));
1873 continue;
1874 }
1875 }
1876 let (iri, query) = match alt.split_once('?') {
1877 Some((iri, query)) => (iri.trim(), Some(query)),
1878 None => (alt, None),
1879 };
1880 check_placeholders(iri, true).map_err(refuse)?;
1881 let mut args = Vec::new();
1882 if let Some(query) = query {
1883 for pair in split_outside_quotes(query, "&") {
1884 let pair = pair.trim();
1885 if pair.is_empty() {
1886 continue;
1887 }
1888 let (key, value) = pair.split_once('=').ok_or_else(|| {
1889 Error::Endpoint(format!(
1890 "compose: marker argument `{pair}` is not key=value"
1891 ))
1892 })?;
1893 let value = value.trim();
1894 let value = match unquote(value) {
1895 Some(text) => Value {
1896 text,
1897 literal: true,
1898 reference: false,
1899 },
1900 None => {
1901 let reference = value
1902 .strip_prefix('<')
1903 .and_then(|iri| iri.strip_suffix('>'));
1904 let text = reference.unwrap_or(value);
1905 check_placeholders(text, reference.is_some()).map_err(refuse)?;
1906 Value {
1907 text: text.to_string(),
1908 literal: false,
1909 reference: reference.is_some(),
1910 }
1911 }
1912 };
1913 args.push((key.trim().to_string(), value));
1914 }
1915 }
1916 alts.push(Alt::Request {
1917 iri: iri.to_string(),
1918 args,
1919 });
1920 }
1921 Ok(Marker {
1922 mode,
1923 body: body.to_string(),
1924 alts,
1925 })
1926}
1927
1928/// Build the SOURCE request an alternative names, its arguments filled in. (An argument
1929/// alternative names no request; it is answered before this is reached.)
1930fn alt_request(inv: &Invocation<'_>, from: Args<'_>, body: &str, alt: &Alt) -> Result<Request> {
1931 let bad_iri = |e: ikigai_core::IriError| {
1932 Error::Endpoint(format!("compose: bad IRI in marker `{body}`: {e}"))
1933 };
1934 match alt {
1935 Alt::Arg(name) => unreachable!("argument `{name}` is answered without a request"),
1936 Alt::Request { iri, args } => {
1937 let filled = fill_arguments(inv, from, iri, true)?;
1938 let mut request = Request::new(Verb::Source, Iri::parse(&filled).map_err(bad_iri)?);
1939 for (key, value) in args {
1940 let text = if value.literal {
1941 value.text.clone()
1942 } else {
1943 fill_arguments(inv, from, &value.text, value.reference)?
1944 };
1945 let arg = if value.reference {
1946 ArgRef::Reference(Iri::parse(&text).map_err(bad_iri)?)
1947 } else {
1948 ArgRef::Inline(text.into_bytes())
1949 };
1950 request = request.with_arg(key.clone(), arg);
1951 }
1952 Ok(request)
1953 }
1954 Alt::Jq { src, program } => {
1955 // The source is named like any marker's IRI (its arguments percent-encoded),
1956 // and checked as one here, so a bad one is this marker's error rather than
1957 // the jq endpoint's. The program goes in as it was written.
1958 let src = fill_arguments(inv, from, src, true)?;
1959 Iri::parse(&src).map_err(bad_iri)?;
1960 Ok(
1961 Request::new(Verb::Source, Iri::parse(JQ_QUERY).expect("a valid IRI"))
1962 .with_arg("src", ArgRef::Inline(src.into_bytes()))
1963 .with_arg("q", ArgRef::Inline(program.clone().into_bytes()))
1964 .with_arg("as", ArgRef::Inline(b"text/plain".to_vec())),
1965 )
1966 }
1967 }
1968}
1969
1970/// Every `{name}` in `template` replaced by that argument's value — percent-encoded
1971/// when `encode` (in an IRI), verbatim otherwise (as one argument value) — and, in an IRI,
1972/// every `{+name}` by its value under RFC 6570's reserved expansion. The placeholders were
1973/// checked when the marker was parsed.
1974fn fill_arguments(
1975 inv: &Invocation<'_>,
1976 args: Args<'_>,
1977 template: &str,
1978 encode: bool,
1979) -> Result<String> {
1980 let mut out = String::with_capacity(template.len());
1981 let mut rest = template;
1982 while let Some(open) = rest.find('{') {
1983 out.push_str(&rest[..open]);
1984 let after = &rest[open + 1..];
1985 let close = after
1986 .find('}')
1987 .expect("placeholders are checked when parsed");
1988 let inner = &after[..close];
1989 match inner.strip_prefix('+') {
1990 Some(name) => {
1991 debug_assert!(encode, "`{{+name}}` is refused outside an IRI when parsed");
1992 if let Args::Element(_) = args {
1993 return Err(Error::Endpoint(format!(
1994 "each: `{{+{name}}}` would let element data choose a path, a query or \
1995 a name under the prefix — element fields are reserved-expanded never; \
1996 write `{{{name}}}`"
1997 )));
1998 }
1999 html::push_url_reserved(&template_arg(inv, args, name)?, &mut out);
2000 }
2001 None if encode => html::push_url_segment(&template_arg(inv, args, inner)?, &mut out),
2002 None => out.push_str(&template_arg(inv, args, inner)?),
2003 }
2004 rest = &after[close + 1..];
2005 }
2006 out.push_str(rest);
2007 Ok(out)
2008}
2009
2010/// Refuse a `{` that does not open a `{name}` argument — or, in an IRI (`in_iri`), a
2011/// `{+name}` one, whose reserved expansion lets `:` through, so it must come after the
2012/// scheme: the template's own text before its FIRST placeholder holds a `:` (an argument
2013/// before that would choose the scheme). Outside an IRI `{+name}` is
2014/// refused, since an unquoted value already takes `{name}` verbatim.
2015fn check_placeholders(template: &str, in_iri: bool) -> std::result::Result<(), String> {
2016 let scheme_fixed = template[..template.find('{').unwrap_or(template.len())].contains(':');
2017 let mut rest = template;
2018 while let Some(open) = rest.find('{') {
2019 let after = &rest[open + 1..];
2020 let close = after
2021 .find('}')
2022 .ok_or_else(|| "a `{` is never closed".to_string())?;
2023 let inner = &after[..close];
2024 match inner.strip_prefix('+') {
2025 Some(name) if is_arg_name(name) => {
2026 if !in_iri {
2027 return Err(format!(
2028 "`{{{inner}}}` (reserved expansion) belongs only in the IRI; in an \
2029 unquoted value `{{{name}}}` is already the value, verbatim"
2030 ));
2031 }
2032 if !scheme_fixed {
2033 return Err(format!(
2034 "`{{{inner}}}` would let an argument choose the IRI's scheme — the \
2035 template's text before its first argument must hold the scheme and \
2036 its `:`"
2037 ));
2038 }
2039 }
2040 _ if is_arg_name(inner) => {}
2041 _ => return Err(format!("`{{{inner}}}` is not an argument name")),
2042 }
2043 rest = &after[close + 1..];
2044 }
2045 Ok(())
2046}
2047
2048/// An argument name: a letter or `_`, then letters, digits, `_` and `-`.
2049fn is_arg_name(name: &str) -> bool {
2050 let mut chars = name.chars();
2051 chars
2052 .next()
2053 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
2054 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
2055}
2056
2057/// The text of a double-quoted marker argument value, `\"` and `\\` unescaped, or
2058/// `None` if the value is not quoted.
2059fn unquote(value: &str) -> Option<String> {
2060 let b = value.as_bytes();
2061 if b.len() >= 2 && b[0] == b'"' && b[b.len() - 1] == b'"' {
2062 let mut out = String::with_capacity(value.len() - 2);
2063 let mut chars = value[1..value.len() - 1].chars();
2064 while let Some(c) = chars.next() {
2065 match c {
2066 '\\' => out.push(chars.next().unwrap_or('\\')),
2067 _ => out.push(c),
2068 }
2069 }
2070 Some(out)
2071 } else {
2072 None
2073 }
2074}
2075
2076/// The byte length of the UTF-8 sequence starting with `first`.
2077fn utf8_len(first: u8) -> usize {
2078 match first {
2079 b if b < 0x80 => 1,
2080 b if b >> 5 == 0b110 => 2,
2081 b if b >> 4 == 0b1110 => 3,
2082 _ => 4,
2083 }
2084}
2085
2086// --- the library as a mountable space -------------------------------------
2087
2088/// The name [`space`] claims: `urn:iki:space:fn`.
2089pub const SPACE_ID: &str = "urn:iki:space:fn";
2090
2091/// The reusable function library as a mountable [`EndpointSpace`], binding every
2092/// function at its conventional IRI. A host mounts this and chains its own
2093/// host-specific bindings on top — `EndpointSpace::bind` is a builder, so:
2094///
2095/// ```ignore
2096/// let space = ikigai_fn::space()
2097/// .bind(Exact::new("urn:data:page"), page())
2098/// .bind(Exact::new("urn:host:info"), host_info(nature));
2099/// ```
2100///
2101/// Hosts that want different IRIs (binding authority is a host concern) can
2102/// instead pull the individual constructors and bind them as they like.
2103///
2104/// The space is configuration-free (no parameters, nothing read while building
2105/// it), so it names itself [`SPACE_ID`]. A host that extends it with `.bind`
2106/// gets an anonymous space back (core 0.1.89 drops the name on a new door), and
2107/// names its own composition if it wants one.
2108///
2109/// ```
2110/// use ikigai_core::{Exact, Space};
2111///
2112/// assert_eq!(
2113/// ikigai_fn::space().id().map(|iri| iri.as_str().to_owned()).as_deref(),
2114/// Some(ikigai_fn::SPACE_ID)
2115/// );
2116/// let extended = ikigai_fn::space().bind(Exact::new("urn:host:page"), ikigai_fn::echo());
2117/// assert!(extended.id().is_none(), "different doors, no inherited name");
2118/// ```
2119pub fn space() -> EndpointSpace {
2120 let echo_template = UriTemplate::parse("urn:demo:echo/{message}").expect("valid template");
2121 EndpointSpace::new()
2122 .bind(Exact::new("urn:iki:fn:toUpper"), to_upper())
2123 .bind(Exact::new("urn:iki:fn:digest"), digest())
2124 .bind(Exact::new("urn:iki:fn:markdown"), markdown())
2125 .bind(Exact::new("urn:iki:fn:reverseList"), reverse_list())
2126 .bind(Exact::new("urn:iki:fn:compose"), compose())
2127 .bind(Exact::new("urn:iki:fn:conditional"), conditional())
2128 .bind(Exact::new("urn:iki:fn:each"), each())
2129 .bind(Exact::new("urn:iki:fn:html-to-text"), html_to_text())
2130 .bind(Exact::new("urn:demo:wrap"), wrap())
2131 .bind(Exact::new("urn:demo:split"), split())
2132 .bind(Exact::new("urn:demo:greet"), greet())
2133 .bind(echo_template, echo())
2134 .named(space_iri("fn"))
2135}
2136
2137#[cfg(test)]
2138mod tests {
2139 use super::*;
2140 use futures::executor::block_on;
2141 use ikigai_core::{Capability, Kernel};
2142 use std::sync::Arc;
2143
2144 fn kernel() -> Kernel {
2145 Kernel::new(Arc::new(space()))
2146 }
2147
2148 fn source(kernel: &Kernel, iri: &str, args: &[(&str, &[u8])]) -> Representation {
2149 let mut request = Request::new(Verb::Source, Iri::parse(iri).unwrap());
2150 for (key, value) in args {
2151 request = request.with_arg(*key, ArgRef::Inline(value.to_vec()));
2152 }
2153 block_on(kernel.issue(request, &Capability::root())).unwrap()
2154 }
2155
2156 // ---- conditional -------------------------------------------------------
2157
2158 /// A resource that returns a fixed body — a stand-in boolean or branch value.
2159 fn constant(name: &'static str, body: &'static str) -> FnEndpoint {
2160 FnEndpoint::new(name, move |_inv: &Invocation<'_>| {
2161 Ok(Representation::new(
2162 text_plain_utf8(),
2163 body.as_bytes().to_vec(),
2164 ))
2165 })
2166 }
2167
2168 fn cond_kernel() -> Kernel {
2169 let space = space()
2170 .bind(Exact::new("urn:test:true"), constant("t", "true"))
2171 .bind(Exact::new("urn:test:false"), constant("f", "false"))
2172 .bind(Exact::new("urn:test:maybe"), constant("m", "maybe"))
2173 .bind(Exact::new("urn:test:A"), constant("a", "branch-A"))
2174 .bind(Exact::new("urn:test:B"), constant("b", "branch-B"));
2175 Kernel::new(Arc::new(space))
2176 }
2177
2178 fn cond(
2179 kernel: &Kernel,
2180 if_u: &str,
2181 then_u: &str,
2182 else_u: Option<&str>,
2183 ) -> Result<Representation> {
2184 let mut req = Request::new(Verb::Source, Iri::parse("urn:iki:fn:conditional").unwrap())
2185 .with_arg("if", ArgRef::Inline(if_u.as_bytes().to_vec()))
2186 .with_arg("then", ArgRef::Inline(then_u.as_bytes().to_vec()));
2187 if let Some(e) = else_u {
2188 req = req.with_arg("else", ArgRef::Inline(e.as_bytes().to_vec()));
2189 }
2190 block_on(kernel.issue(req, &Capability::root()))
2191 }
2192
2193 #[test]
2194 fn true_takes_the_then_branch() {
2195 let out = cond(
2196 &cond_kernel(),
2197 "urn:test:true",
2198 "urn:test:A",
2199 Some("urn:test:B"),
2200 )
2201 .unwrap();
2202 assert_eq!(out.bytes, b"branch-A");
2203 }
2204
2205 #[test]
2206 fn false_takes_the_else_branch() {
2207 let out = cond(
2208 &cond_kernel(),
2209 "urn:test:false",
2210 "urn:test:A",
2211 Some("urn:test:B"),
2212 )
2213 .unwrap();
2214 assert_eq!(out.bytes, b"branch-B");
2215 }
2216
2217 #[test]
2218 fn false_without_else_is_empty() {
2219 let out = cond(&cond_kernel(), "urn:test:false", "urn:test:A", None).unwrap();
2220 assert!(out.bytes.is_empty());
2221 }
2222
2223 #[test]
2224 fn the_untaken_branch_is_never_sourced() {
2225 // `else` names a nonexistent resource; a true condition must not touch it
2226 // (if it did, the kernel would fail to resolve it).
2227 let out = cond(
2228 &cond_kernel(),
2229 "urn:test:true",
2230 "urn:test:A",
2231 Some("urn:does:not:exist"),
2232 )
2233 .unwrap();
2234 assert_eq!(out.bytes, b"branch-A");
2235 }
2236
2237 #[test]
2238 fn a_non_boolean_condition_errors() {
2239 assert!(cond(&cond_kernel(), "urn:test:maybe", "urn:test:A", None).is_err());
2240 }
2241
2242 /// The spellings the summary and the refusal list are exactly the ones `as_bool`
2243 /// accepts: the list once omitted `on`/`off`, and a Deno port copied it (ledger #627).
2244 #[test]
2245 fn the_stated_boolean_spellings_are_the_accepted_ones() {
2246 const STATED: &str = "(true/false/1/0/yes/no/on/off)";
2247 let iri = Iri::parse("urn:test:x").unwrap();
2248 let refusal = as_bool(b"maybe", &iri).unwrap_err().to_string();
2249 assert!(refusal.contains(STATED), "refusal: {refusal}");
2250 assert!(
2251 conditional().describe().summary.contains(STATED),
2252 "summary lists the accepted spellings"
2253 );
2254 let words = STATED.trim_matches(|c| c == '(' || c == ')').split('/');
2255 for (i, word) in words.enumerate() {
2256 assert_eq!(
2257 as_bool(word.as_bytes(), &iri).unwrap(),
2258 i % 2 == 0,
2259 "{word}"
2260 );
2261 }
2262 }
2263
2264 #[test]
2265 fn to_upper_upper_cases_the_in_argument() {
2266 assert_eq!(
2267 source(&kernel(), "urn:iki:fn:toUpper", &[("in", b"hi there")]).bytes,
2268 b"HI THERE"
2269 );
2270 }
2271
2272 #[test]
2273 fn reverse_list_reverses_newline_items() {
2274 assert_eq!(
2275 source(&kernel(), "urn:iki:fn:reverseList", &[("in", b"a\nb\nc")]).bytes,
2276 b"c\nb\na"
2277 );
2278 }
2279
2280 #[test]
2281 fn split_makes_a_newline_list_for_map() {
2282 assert_eq!(
2283 source(&kernel(), "urn:demo:split", &[("in", b"a, b ,c")]).bytes,
2284 b"a\nb\nc"
2285 );
2286 }
2287
2288 #[test]
2289 fn wrap_routes_the_text_argument() {
2290 assert_eq!(
2291 source(&kernel(), "urn:demo:wrap", &[("text", b"hi")]).bytes,
2292 b"[hi]"
2293 );
2294 }
2295
2296 #[test]
2297 fn greet_combines_two_arguments() {
2298 assert_eq!(
2299 source(
2300 &kernel(),
2301 "urn:demo:greet",
2302 &[("greeting", b"Hello"), ("name", b"World")]
2303 )
2304 .bytes,
2305 b"Hello, World"
2306 );
2307 }
2308
2309 #[test]
2310 fn echo_returns_the_captured_binding() {
2311 assert_eq!(source(&kernel(), "urn:demo:echo/ping", &[]).bytes, b"ping");
2312 }
2313
2314 // ---- self-description ---------------------------------------------------
2315
2316 /// Every input declared in `space()` carries a class. `select_action` and
2317 /// `urn:kernel:actions types=` match on `ArgSpec::class` alone, so an input without one
2318 /// is not "untyped" — it makes its endpoint invisible to type-driven selection (and a
2319 /// REQUIRED input without one makes the endpoint un-inferable). Walks the live space
2320 /// through the kernel rather than a hand-kept list, so a new binding is covered the
2321 /// moment it is bound, and covers per-verb `ActionSpec` inputs for the day one appears.
2322 /// Enumerates THIS space's bindings, not the kernel's: `Kernel::entries` also lists the
2323 /// kernel's own `urn:kernel:*` builtins, which are core's to type, not this crate's.
2324 #[test]
2325 fn every_declared_input_has_a_class() {
2326 use ikigai_core::Space;
2327 let space = space();
2328 let entries = space.entries().expect("space() is enumerable");
2329 let kernel = Kernel::new(Arc::new(space));
2330 assert!(!entries.is_empty());
2331 let mut untyped = Vec::new();
2332 for entry in &entries {
2333 let description = kernel
2334 .describe_pattern(&entry.pattern)
2335 .unwrap_or_else(|| panic!("{} describes itself", entry.pattern));
2336 let flat = description.inputs.iter();
2337 let per_action = description.actions.iter().flat_map(|a| a.inputs.iter());
2338 for input in flat.chain(per_action) {
2339 if input.class.is_none() {
2340 untyped.push(format!("{}#{}", entry.pattern, input.name));
2341 }
2342 }
2343 }
2344 assert!(untyped.is_empty(), "inputs without a class: {untyped:?}");
2345 }
2346
2347 /// The point of declaring the classes: type-driven selection now OFFERS these endpoints.
2348 /// "I hold a string — what can I do with it?" answers with the text functions; "I hold
2349 /// an IRI" answers with the two that take one. Before, every answer was empty.
2350 #[test]
2351 fn typed_selection_offers_the_text_and_iri_functions() {
2352 use ikigai_core::select_action;
2353 let space = space();
2354 let names = |present: &[&str]| -> Vec<String> {
2355 select_action(&space, present)
2356 .into_iter()
2357 .map(|m| m.endpoint)
2358 .collect()
2359 };
2360 // `ActionMatch::endpoint` is the bound IRI — the thing a caller would invoke.
2361 let strings = names(&[XSD_STRING]);
2362 for expected in [
2363 "urn:iki:fn:digest",
2364 "urn:iki:fn:markdown",
2365 "urn:iki:fn:toUpper",
2366 "urn:iki:fn:reverseList",
2367 "urn:iki:fn:html-to-text",
2368 "urn:demo:split",
2369 "urn:demo:wrap",
2370 "urn:demo:greet",
2371 "urn:demo:echo/{message}",
2372 ] {
2373 assert!(
2374 strings.contains(&expected.to_string()),
2375 "{expected} in {strings:?}"
2376 );
2377 }
2378 let iris = names(&[XSD_ANY_URI]);
2379 for expected in ["urn:iki:fn:compose", "urn:iki:fn:conditional"] {
2380 assert!(
2381 iris.contains(&expected.to_string()),
2382 "{expected} in {iris:?}"
2383 );
2384 }
2385 assert!(
2386 !iris.contains(&"urn:iki:fn:toUpper".to_string()),
2387 "{iris:?}"
2388 );
2389 }
2390}
2391
2392#[cfg(test)]
2393mod compose_tests {
2394 use super::*;
2395 use futures::executor::block_on;
2396 use ikigai_core::{Capability, Expiry, Kernel};
2397 use std::sync::Arc;
2398
2399 /// A shape resource: returns a fixed body (which may carry markers) under the
2400 /// given media type. The type is a parameter because `compose` passes it
2401 /// through — a shape fixed at `text/html` cannot tell "mirrors the source" apart
2402 /// from "always emits HTML".
2403 fn shape(media_type: &'static str, body: &'static str) -> FnEndpoint {
2404 FnEndpoint::new("shape", move |_inv: &Invocation<'_>| {
2405 Ok(
2406 Representation::new(ReprType::new(media_type), body.as_bytes().to_vec())
2407 .cacheable(),
2408 )
2409 })
2410 }
2411
2412 /// A kernel binding `compose`, `toUpper`, and a `urn:data:page` shape.
2413 fn kernel(page: &'static str) -> Kernel {
2414 typed_kernel("text/html", page)
2415 }
2416
2417 /// The same, with the shape's media type chosen by the caller.
2418 fn typed_kernel(media_type: &'static str, page: &'static str) -> Kernel {
2419 let space = EndpointSpace::new()
2420 .bind(Exact::new("urn:iki:fn:compose"), compose())
2421 .bind(Exact::new("urn:iki:fn:toUpper"), to_upper())
2422 .bind(Exact::new("urn:data:page"), shape(media_type, page));
2423 Kernel::new(Arc::new(space))
2424 }
2425
2426 fn compose_page(kernel: &Kernel) -> Representation {
2427 block_on(
2428 kernel.issue(
2429 Request::new(Verb::Source, Iri::parse("urn:iki:fn:compose").unwrap())
2430 .with_arg("src", ArgRef::Inline(b"urn:data:page".to_vec())),
2431 &Capability::root(),
2432 ),
2433 )
2434 .unwrap()
2435 }
2436
2437 #[test]
2438 fn expands_a_marker_with_a_quoted_argument() {
2439 let rep = compose_page(&kernel(r#"<h1>$a{urn:iki:fn:toUpper?in="hi there"}</h1>"#));
2440 assert_eq!(rep.bytes, b"<h1>HI THERE</h1>".to_vec());
2441 }
2442
2443 /// Whatever the shape is labelled, the composite carries that label: the type is
2444 /// the source's, which is why `describe` declares none. Before 0.2.2 this test
2445 /// ran over a shape hard-coded to `text/html` and so could not have failed if
2446 /// compose had emitted a constant `text/html` — the very thing it claims to rule
2447 /// out, and the thing `describe` then asserted.
2448 #[test]
2449 fn preserves_the_source_media_type() {
2450 for media_type in ["text/html", "text/turtle", "application/json"] {
2451 let kernel = typed_kernel(media_type, "<p>$a{urn:iki:fn:toUpper?in=x}</p>");
2452 let rep = compose_page(&kernel);
2453 assert_eq!(rep.repr_type.media_type, media_type);
2454 assert_eq!(rep.bytes, b"<p>X</p>".to_vec(), "{media_type}");
2455 }
2456 }
2457
2458 #[test]
2459 fn a_double_dollar_keeps_a_marker_literal() {
2460 let rep = compose_page(&kernel("show $$a{urn:iki:fn:toUpper?in=x} verbatim"));
2461 assert_eq!(
2462 rep.bytes,
2463 b"show $a{urn:iki:fn:toUpper?in=x} verbatim".to_vec()
2464 );
2465 }
2466
2467 #[test]
2468 fn recurses_into_transcluded_shapes() {
2469 let space = EndpointSpace::new()
2470 .bind(Exact::new("urn:iki:fn:compose"), compose())
2471 .bind(Exact::new("urn:iki:fn:toUpper"), to_upper())
2472 .bind(
2473 Exact::new("urn:data:page"),
2474 shape("text/html", "[$a{urn:data:inner}]"),
2475 )
2476 .bind(
2477 Exact::new("urn:data:inner"),
2478 shape("text/html", "$a{urn:iki:fn:toUpper?in=hi}"),
2479 );
2480 let kernel = Kernel::new(Arc::new(space));
2481 let rep = compose_page(&kernel);
2482 assert_eq!(rep.bytes, b"[HI]".to_vec());
2483 }
2484
2485 #[test]
2486 fn a_composite_of_cacheable_parts_is_cacheable() {
2487 let rep = compose_page(&kernel("<p>$a{urn:iki:fn:toUpper?in=hi}</p>"));
2488 assert_eq!(rep.expiry, Expiry::Never);
2489 }
2490
2491 #[test]
2492 fn text_around_and_between_markers_is_preserved() {
2493 let rep = compose_page(&kernel(
2494 "a $a{urn:iki:fn:toUpper?in=b} c $a{urn:iki:fn:toUpper?in=d} e",
2495 ));
2496 assert_eq!(rep.bytes, b"a B c D e".to_vec());
2497 }
2498}
2499
2500#[cfg(test)]
2501mod marker_end_tests {
2502 use super::*;
2503
2504 /// The marker-end scan as it was before ledger #4002: correct, but quadratic over
2505 /// many unterminated openers. The reference for the differential test.
2506 mod reference {
2507 use super::utf8_len;
2508
2509 /// The index of the `}` closing the marker whose `{` is at `brace`, skipping any
2510 /// `}` inside a `"…"` span (where a backslash escapes the next character) and any that closes a
2511 /// `{name}` argument inside the body. `None` if unterminated.
2512 pub(super) fn find_marker_end(text: &str, brace: usize) -> Option<usize> {
2513 let b = text.as_bytes();
2514 let mut i = brace + 1;
2515 let mut in_quote = false;
2516 let mut depth = 0usize;
2517 while i < b.len() {
2518 match b[i] {
2519 b'\\' if in_quote => {
2520 i += 1;
2521 if i < b.len() {
2522 i += utf8_len(b[i]);
2523 }
2524 }
2525 b'"' => {
2526 in_quote = !in_quote;
2527 i += 1;
2528 }
2529 b'{' if !in_quote => {
2530 depth += 1;
2531 i += 1;
2532 }
2533 b'}' if !in_quote => {
2534 if depth == 0 {
2535 return Some(i);
2536 }
2537 depth -= 1;
2538 i += 1;
2539 }
2540 c => i += utf8_len(c),
2541 }
2542 }
2543 None
2544 }
2545 }
2546
2547 /// A small deterministic generator (xorshift64*), so the inputs repeat run to run.
2548 struct Gen(u64);
2549 impl Gen {
2550 fn next(&mut self) -> u64 {
2551 self.0 ^= self.0 >> 12;
2552 self.0 ^= self.0 << 25;
2553 self.0 ^= self.0 >> 27;
2554 self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
2555 }
2556 }
2557
2558 const PIECES: [&str; 10] = ["{", "}", "\"", "\\", "$h{", "$r{", "a", "é", " ", "$$"];
2559
2560 /// Every `{` in `text` is looked up three ways, which must agree: the reference,
2561 /// a fresh `MarkerEnds`, and one shared across the lookups in the given order.
2562 fn check(text: &str, order: &mut dyn Iterator<Item = usize>) {
2563 let mut shared = MarkerEnds::new(text);
2564 for brace in order {
2565 let want = reference::find_marker_end(text, brace);
2566 assert_eq!(
2567 MarkerEnds::new(text).find(brace),
2568 want,
2569 "{text:?} at {brace}"
2570 );
2571 assert_eq!(shared.find(brace), want, "{text:?} at {brace}, shared");
2572 }
2573 }
2574
2575 fn braces(text: &str) -> Vec<usize> {
2576 text.bytes()
2577 .enumerate()
2578 .filter(|&(_, c)| c == b'{')
2579 .map(|(i, _)| i)
2580 .collect()
2581 }
2582
2583 #[test]
2584 fn marker_ends_match_the_reference_on_every_short_input() {
2585 // Every string of up to five pieces.
2586 let mut texts = vec![String::new()];
2587 for _ in 0..5 {
2588 let mut longer = Vec::new();
2589 for text in &texts {
2590 for piece in PIECES {
2591 longer.push(format!("{text}{piece}"));
2592 }
2593 }
2594 for text in &longer {
2595 let positions = braces(text);
2596 check(text, &mut positions.iter().copied());
2597 check(text, &mut positions.iter().rev().copied());
2598 }
2599 texts = longer;
2600 }
2601 }
2602
2603 #[test]
2604 fn marker_ends_match_the_reference_on_generated_inputs() {
2605 let mut gen = Gen(0x4002_4002_4002_4002);
2606 for _ in 0..3000 {
2607 let len = (gen.next() % 80) as usize;
2608 let text: String = (0..len)
2609 .map(|_| PIECES[(gen.next() % PIECES.len() as u64) as usize])
2610 .collect();
2611 let mut positions = braces(&text);
2612 check(&text, &mut positions.clone().into_iter());
2613 // And in a shuffled order, so a lookup can land inside one already settled.
2614 for i in (1..positions.len()).rev() {
2615 positions.swap(i, (gen.next() % (i as u64 + 1)) as usize);
2616 }
2617 check(&text, &mut positions.into_iter());
2618 }
2619 }
2620
2621 #[test]
2622 fn marker_end_scan_is_linear() {
2623 // Counts positions settled, not time: at most two (one per mode) per byte,
2624 // however many openers run off the end.
2625 for unit in ["$h{", "$r{{", "$h{\"", "$h{\"\\\"{", "{$h{", "{{{{"] {
2626 let text = unit.repeat(20_000);
2627 let mut ends = MarkerEnds::new(&text);
2628 for brace in braces(&text) {
2629 assert_eq!(ends.find(brace), None, "{unit:?}");
2630 }
2631 assert!(
2632 ends.steps <= 2 * (text.len() + 1),
2633 "{unit:?}: {} steps over {} bytes",
2634 ends.steps,
2635 text.len()
2636 );
2637 }
2638 }
2639
2640 #[test]
2641 fn deep_braces_do_not_overflow_the_stack() {
2642 let text = format!("$h{{{}", "{".repeat(1_000_000));
2643 assert_eq!(MarkerEnds::new(&text).find(2), None);
2644 let closed = format!("$h{{{}{}", "{".repeat(1_000_000), "}".repeat(1_000_001));
2645 assert_eq!(MarkerEnds::new(&closed).find(2), Some(closed.len() - 1));
2646 }
2647}