Skip to main content

rustango_cms/api/
pages.rs

1//! `GET /api/v2/pages/` + `GET /api/v2/pages/{id}/`.
2//!
3//! Lists + retrieves published pages over JSON.
4//!
5//! Every surface here is viewer-aware. `detail` runs
6//! [`crate::view_restriction_guard`] and answers a denial with 401 / 403;
7//! `list` (and its `?child_of=` / `?descendant_of=` / `?ancestor_of=`
8//! filters), `find` and the `children` summaries all drop what the caller
9//! may not see via [`crate::view_restriction::denied_page_ids`]. `find`
10//! answers a gated page and a missing one identically, so it cannot be
11//! used to probe for hidden URLs.
12
13// Our extractors, not axum's: they refuse a malformed value in the same
14// JSON envelope as everything else. See `query::Query`.
15use crate::api::query::{Path, Query};
16use axum::http::{HeaderMap, StatusCode};
17use axum::response::{IntoResponse, Response};
18use axum::Json;
19use rustango::core::Column as _;
20use rustango::extractors::{SessionUser, Tenant};
21use rustango::sql::FetcherPool as _;
22use serde::Deserialize;
23
24use super::query as q;
25use crate::page::{Page, PageStatus};
26use crate::page_type::{find_handler, PageTypeHandler};
27use crate::page_type_model::PageType;
28
29/// Per-endpoint filters layered on top of [`crate::api::query::ListQuery`].
30#[derive(Debug, Default, Deserialize)]
31pub struct PageFilters {
32    /// `?type=cms_pages.HomePage` — handler type_name match.
33    #[serde(default, deserialize_with = "q::empty_string_as_none")]
34    pub r#type: Option<String>,
35    /// `?child_of=N` — direct children of page N.
36    #[serde(default, deserialize_with = "q::empty_as_none")]
37    pub child_of: Option<i64>,
38    /// `?descendant_of=N` — every descendant of page N (excluding N).
39    #[serde(default, deserialize_with = "q::empty_as_none")]
40    pub descendant_of: Option<i64>,
41    /// `?ancestor_of=N` — every ancestor of page N (excluding N).
42    #[serde(default, deserialize_with = "q::empty_as_none")]
43    pub ancestor_of: Option<i64>,
44    /// `?translation_of=N` — sibling locale variants of page N.
45    #[serde(default, deserialize_with = "q::empty_as_none")]
46    pub translation_of: Option<i64>,
47    /// `?locale=en` — restrict to a specific locale.
48    #[serde(default, deserialize_with = "q::empty_string_as_none")]
49    pub locale: Option<String>,
50    /// `?tag=release` — restrict to pages carrying this tag.
51    #[serde(default, deserialize_with = "q::empty_string_as_none")]
52    pub tag: Option<String>,
53    /// `?id_in=3,9,14` — fetch several pages by id in one request.
54    ///
55    /// Without it, hydrating a resolved menu (which returns `page_id`
56    /// per node and nothing else) costs one request per item. Unknown
57    /// and non-public ids are simply absent from the result rather than
58    /// an error, so a stale client id degrades to a missing row instead
59    /// of failing the whole batch. Bounded by `?limit=` like any list.
60    #[serde(default, deserialize_with = "q::empty_string_as_none")]
61    pub id_in: Option<String>,
62}
63
64/// Combined query string for `GET /api/v2/pages/`.
65#[derive(Debug, Default, Deserialize)]
66pub struct PageListQuery {
67    #[serde(flatten)]
68    pub list: q::ListQuery,
69    #[serde(flatten)]
70    pub filters: PageFilters,
71}
72
73/// Query string for `GET /api/v2/pages/find/`.
74#[derive(Debug, Default, Deserialize)]
75pub struct FindQuery {
76    /// Public URL path to resolve, e.g. `/about` (with or without a
77    /// trailing slash).
78    #[serde(default, deserialize_with = "q::empty_string_as_none")]
79    pub html_path: Option<String>,
80}
81
82/// Query for the page detail endpoint.
83#[derive(Default, Deserialize)]
84pub struct DetailQuery {
85    /// A signed preview token (from the admin mint endpoint).
86    /// When valid for this page id, the endpoint serves the page even
87    /// if it isn't published, so a decoupled frontend can render the
88    /// draft.
89    #[serde(default, deserialize_with = "q::empty_string_as_none")]
90    pub preview_token: Option<String>,
91    /// `?locale=fr` — return this locale's content. Overrides from
92    /// `cms_translation` are applied per field, so anything untranslated
93    /// falls back to canonical rather than blanking. An unknown or
94    /// inactive code falls back to the tenant default.
95    ///
96    /// Note this is a *content selector*, unlike the list endpoint's
97    /// `?locale=`, which is a legacy row filter over the deprecated
98    /// `locale_variant_of` column.
99    #[serde(default, deserialize_with = "q::empty_string_as_none")]
100    pub locale: Option<String>,
101    /// `?fields=title,seo_title` — same sparse selection the list
102    /// endpoints accept. It was list-only, so a client fetching one page
103    /// had no way to avoid pulling `extension`, `builder` and the whole
104    /// `children` array. `id` and `meta` are always kept.
105    #[serde(default, deserialize_with = "q::empty_string_as_none")]
106    pub fields: Option<String>,
107}
108
109/// `GET /api/v2/pages/`
110pub async fn list(
111    tenant: Tenant,
112    SessionUser(session_user): SessionUser,
113    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
114    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
115    Query(qs): Query<PageListQuery>,
116) -> Response {
117    // #members — a public member outranks an admin session, matching
118    // `tree`, `menus::detail` and the public renderer.
119    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
120    match list_inner(tenant.pool(), &tenant.org.slug, viewer, &qs).await {
121        Ok(resp) => resp,
122        Err(e) => {
123            tracing::error!(target: "rustango_cms::api", error = %e, "pages list failed");
124            crate::api::error::ApiError::internal().into_response()
125        }
126    }
127}
128
129/// The SQL side of a page listing: every filter that is an exact match,
130/// resolved once so the count, the window and the in-memory fallback all
131/// read the same rows.
132struct PageScope {
133    /// `?translation_of=` keeps the legacy locale-variant rows every
134    /// other query drops.
135    translation_of: Option<i64>,
136    type_id: Option<i64>,
137    updated_since: Option<chrono::DateTime<chrono::Utc>>,
138    id_in: Option<Vec<i64>>,
139    child_of: Option<i64>,
140    /// `?descendant_of=` as the anchor's path prefix.
141    descendant_prefix: Option<String>,
142    /// `?ancestor_of=` as the anchor's ancestor paths.
143    ancestor_paths: Option<Vec<String>>,
144    /// A non-default `?locale=`: only the variant rows.
145    variants_only: bool,
146    /// `?tag=`, normalized.
147    tag: Option<String>,
148    /// A filter that can match nothing (an unknown type, an anchor the
149    /// viewer cannot see, an empty id list) — no query needed.
150    matches_nothing: bool,
151}
152
153impl PageScope {
154    /// The filters the tree anchors are resolved against: public, no
155    /// legacy variants (unless `translation_of`), type, `updated_since`,
156    /// `id_in` and `child_of`. The anchor of `?descendant_of=` has to pass
157    /// these but not the tag, locale or translation filters, which is the
158    /// order the in-memory listing has always applied them in.
159    fn base(&self) -> rustango::query::QuerySet<Page> {
160        let mut qs = Page::objects().where_(Page::status.is_in([
161            PageStatus::Published.as_str().to_owned(),
162            PageStatus::Archived.as_str().to_owned(),
163        ]));
164        if self.translation_of.is_none() {
165            qs = qs.where_(Page::locale_variant_of.is_null());
166        }
167        if let Some(tid) = self.type_id {
168            qs = qs.where_(Page::page_type_id.eq(tid));
169        }
170        if let Some(since) = self.updated_since {
171            qs = qs.where_(Page::updated_at.gte(since));
172        }
173        if let Some(ids) = &self.id_in {
174            qs = qs.where_(Page::id.is_in(ids.iter().copied()));
175        }
176        if let Some(parent) = self.child_of {
177            qs = qs.where_(Page::parent_id.eq(parent));
178        }
179        qs
180    }
181
182    /// [`Self::base`] plus the tree, translation, locale and tag filters.
183    fn narrowed(&self) -> Result<rustango::query::QuerySet<Page>, rustango::sql::ExecError> {
184        let mut qs = self.base();
185        if let Some(prefix) = &self.descendant_prefix {
186            // Materialized paths are lowercase hex and `/`, so the prefix
187            // needs no LIKE escaping (see `tree`).
188            qs = qs.where_(Page::path.like(format!("{prefix}%")));
189            qs = qs.where_(Page::path.ne(prefix.clone()));
190        }
191        if let Some(paths) = &self.ancestor_paths {
192            qs = qs.where_(Page::path.is_in(paths.iter().cloned()));
193        }
194        if let Some(canon) = self.translation_of {
195            qs = qs.where_(Page::locale_variant_of.eq(canon));
196        }
197        if self.variants_only {
198            qs = qs.where_(Page::locale_variant_of.is_not_null());
199        }
200        if let Some(tag) = &self.tag {
201            // A subquery rather than an id list: a popular tag must not
202            // run into a backend's bind-parameter ceiling.
203            let tagged = crate::page_tag::PageTag::objects()
204                .where_(crate::page_tag::PageTag::name.eq(tag.clone()))
205                .values_list_flat("page_id")
206                .compile()?;
207            qs = qs.where_(rustango::core::TypedExpr::from_where_expr(
208                rustango::core::subquery::in_subquery("id", tagged),
209            ));
210        }
211        Ok(qs)
212    }
213}
214
215/// How a listing with no text search may be ordered in SQL.
216enum SqlOrder {
217    /// The default: newest published first, then title, then id.
218    Default,
219    /// Only date and number keys, then `id`.
220    Keys(Vec<(&'static str, bool, rustango::core::NullsOrder)>),
221}
222
223/// The SQL order for `orderings`, or `None` when it needs Rust: a text
224/// key (collations differ per backend, Rust's byte order does not) or
225/// `random`.
226fn sql_order(orderings: &[q::OrderSpec]) -> Option<SqlOrder> {
227    use rustango::core::NullsOrder;
228    if orderings.is_empty() {
229        return Some(SqlOrder::Default);
230    }
231    let mut keys = Vec::with_capacity(orderings.len() + 1);
232    for o in orderings {
233        if o.random {
234            return None;
235        }
236        let col = match o.field.as_str() {
237            "published_at" => "published_at",
238            "updated_at" => "updated_at",
239            "created_at" => "created_at",
240            "depth" => "depth",
241            "sort_order" => "sort_order",
242            _ => return None,
243        };
244        // Rust orders `None` first, so a descending sort puts it last.
245        let nulls = if col != "published_at" {
246            NullsOrder::Default
247        } else if o.descending {
248            NullsOrder::Last
249        } else {
250            NullsOrder::First
251        };
252        keys.push((col, o.descending, nulls));
253    }
254    keys.push(("id", false, NullsOrder::Default));
255    Some(SqlOrder::Keys(keys))
256}
257
258/// The default listing order: most recently published first, then
259/// title, then id.
260fn compare_default(a: &Page, b: &Page) -> std::cmp::Ordering {
261    b.published_at
262        .cmp(&a.published_at)
263        .then_with(|| a.title.cmp(&b.title))
264        // Unique tiebreaker: `sort_by` is stable, so without one tied
265        // rows keep the fetch order and paging is only as stable as the
266        // driver happens to be.
267        .then_with(|| a.id.get().cmp(&b.id.get()))
268}
269
270/// One window of `scope` in the default order, without loading the rest.
271///
272/// SQL sorts by `published_at DESC, id`, which puts the rows in the same
273/// groups of equal `published_at` as [`compare_default`] and differs only
274/// inside a group, where the title decides. So: take the SQL window, read
275/// the (at most two) groups that straddle its edges in full, and order
276/// that run in Rust. It starts right after every row of a newer group.
277/// Most ids `?id_in=` accepts in one request.
278const MAX_ID_IN: usize = 200;
279
280/// The default-order page window (`published_at` desc, then title, id).
281/// SQL picks the window by `published_at, id`; the rows sharing a
282/// `published_at` with the window's first or last row are re-read in full
283/// and sorted in Rust, since a title order isn't the same on every
284/// backend. Cost note: that re-read is as big as the tie group — pages
285/// bulk-published in the same instant all load once a window touches them.
286async fn default_order_window(
287    pool: &rustango::sql::Pool,
288    scope: &PageScope,
289    limit: usize,
290    offset: usize,
291) -> Result<Vec<Page>, rustango::sql::ExecError> {
292    use rustango::core::NullsOrder;
293    use rustango::sql::CounterPool as _;
294    let sql_window: Vec<Page> = scope
295        .narrowed()?
296        .order_by_with_nulls(&[
297            ("published_at", true, NullsOrder::Last),
298            ("id", false, NullsOrder::Default),
299        ])
300        .limit(i64::try_from(limit).unwrap_or(i64::MAX))
301        // A huge `?offset=` must not wrap negative (backends differ).
302        .offset(i64::try_from(offset).unwrap_or(i64::MAX))
303        .fetch(pool)
304        .await?;
305    let (Some(first), Some(last)) = (sql_window.first(), sql_window.last()) else {
306        return Ok(Vec::new());
307    };
308    let (first_key, last_key) = (first.published_at, last.published_at);
309    let ahead = match first_key {
310        Some(t) => scope.narrowed()?.where_(Page::published_at.gt(t)).count(pool).await?,
311        // NULLs sort last, so every dated row is ahead of them.
312        None => scope.narrowed()?.where_(Page::published_at.is_not_null()).count(pool).await?,
313    };
314    let group = |key: Option<chrono::DateTime<chrono::Utc>>| -> Result<_, rustango::sql::ExecError> {
315        Ok(match key {
316            Some(t) => scope.narrowed()?.where_(Page::published_at.eq(t)),
317            None => scope.narrowed()?.where_(Page::published_at.is_null()),
318        })
319    };
320    let mut run: Vec<Page> = group(first_key)?.fetch(pool).await?;
321    if last_key != first_key {
322        run.extend(
323            sql_window
324                .into_iter()
325                .filter(|p| p.published_at != first_key && p.published_at != last_key),
326        );
327        run.extend(group(last_key)?.fetch(pool).await?);
328    }
329    run.sort_by(compare_default);
330    let skip = offset.saturating_sub(usize::try_from(ahead).unwrap_or_default());
331    Ok(run.into_iter().skip(skip).take(limit).collect())
332}
333
334/// The path of anchor page `id` when it is in `base` and `access` lets
335/// the viewer see it.
336///
337/// `None` for "gated" and for "absent" alike is deliberate: answering
338/// differently would tell a caller whether a page it may not see exists.
339async fn visible_anchor_path(
340    pool: &rustango::sql::Pool,
341    base: rustango::query::QuerySet<Page>,
342    access: &crate::view_restriction::AccessContext,
343    id: i64,
344) -> Result<Option<String>, rustango::sql::ExecError> {
345    let anchor: Option<Page> = base.where_(Page::id.eq(id)).first(pool).await?;
346    Ok(anchor
347        .filter(|p| access.can_view(&p.path, p.page_type_id))
348        .map(|p| p.path))
349}
350
351/// The body of `GET /api/v2/pages/`.
352///
353/// Takes a `&Pool` and the tenant slug rather than the `Tenant`, so the
354/// endpoint is exercisable against an in-memory database (see
355/// [`crate::api::tree::tree_inner`]).
356///
357/// Exact filters run in SQL (#655). Count, order and paging do too when
358/// there is no text search, the viewer is denied nothing, and the order
359/// is the default or uses only date and number keys; otherwise the
360/// SQL-narrowed rows are filtered, ordered and paged in memory.
361///
362/// # Errors
363/// Driver / query failures.
364pub async fn list_inner(
365    pool: &rustango::sql::Pool,
366    tenant_slug: &str,
367    viewer: Option<&rustango::tenancy::auth::User>,
368    qs: &PageListQuery,
369) -> Result<Response, rustango::sql::ExecError> {
370    let (limit, offset) = q::paginate(&qs.list);
371    let fields = q::field_set(&qs.list);
372    let orderings = match q::parse_order_in(&qs.list, &PAGE_ORDER_FIELDS) {
373        Ok(v) => v,
374        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
375    };
376    // #changes — `?updated_since=` so a polling client can ask for only
377    // what moved, instead of re-fetching the collection and diffing it.
378    let updated_since = match crate::api::query::parse_updated_since(&qs.list) {
379        Ok(v) => v,
380        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
381    };
382    // ----- explicit id set ----------------------------------------------
383    // An *unknown* id is deliberately absent rather than an error, so one
384    // stale id costs a batch one row instead of all of them. A segment
385    // that is not a number at all is a different thing: it was never an
386    // id, so it cannot be stale, and dropping it made a client's own bug
387    // look like a deleted page — the worst possible reading, on the
388    // endpoint whose whole job is hydrating a list of ids a menu just
389    // handed over.
390    let mut id_in: Option<Vec<i64>> = None;
391    if let Some(raw) = qs.filters.id_in.as_deref() {
392        let mut wanted = std::collections::BTreeSet::new();
393        for seg in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
394            match seg.parse::<i64>() {
395                Ok(id) => {
396                    wanted.insert(id);
397                }
398                Err(_) => {
399                    return Ok(crate::api::error::ApiError::bad_request(format!(
400                        "`id_in` expects comma-separated integers; `{seg}` is not one",
401                    ))
402                    .into_response())
403                }
404            }
405        }
406        // Bound the list: it is bound as one `IN (…)` in several queries,
407        // and SQLite builds can cap bind parameters at 999.
408        if wanted.len() > MAX_ID_IN {
409            return Ok(crate::api::error::ApiError::bad_request(format!(
410                "`id_in` takes at most {MAX_ID_IN} ids; got {}",
411                wanted.len()
412            ))
413            .into_response());
414        }
415        id_in = Some(wanted.into_iter().collect());
416    }
417
418    // `random` reshuffles per request, so an offset into it is not a
419    // second page — it is a fresh shuffle with rows skipped. Refuse the
420    // combination rather than quietly returning overlapping garbage.
421    if orderings.iter().any(|o| o.random) && offset > 0 {
422        return Ok(crate::api::error::ApiError::bad_request(
423            "`order=random` cannot be paged — omit `offset`, or order by a field",
424        )
425        .into_response());
426    }
427    // Public means `published` **or** `archived` (`PageStatus::is_public`),
428    // matching the renderer, the sitemap, the tree, the child summaries
429    // and the menu resolver — so `?id_in=` can re-fetch any page a menu
430    // just named.
431    //
432    // Legacy per-locale variant trees were standalone copies of the whole
433    // site, so leaving them in returned it once per locale (#275).
434    // `?translation_of=` exists precisely to list those rows, so it opts
435    // out.
436    let mut scope = PageScope {
437        translation_of: qs.filters.translation_of,
438        type_id: None,
439        updated_since,
440        matches_nothing: id_in.as_ref().is_some_and(Vec::is_empty),
441        id_in,
442        child_of: qs.filters.child_of,
443        descendant_prefix: None,
444        ancestor_paths: None,
445        variants_only: false,
446        tag: None,
447    };
448
449    // ----- type filter --------------------------------------------------
450    if let Some(type_name) = qs.filters.r#type.as_deref().filter(|s| !s.is_empty()) {
451        // `cms_page_type.type_name` stores the bare handler name and
452        // keeps `app_label` in its own column, so the dotted form the
453        // doc comment advertises (`cms_pages.HomePage`) could never
454        // match. Accept both rather than making the documentation wrong.
455        let bare = type_name.rsplit('.').next().unwrap_or(type_name);
456        match lookup_page_type(pool, bare).await? {
457            Some(pt) => scope.type_id = Some(pt.id.get().copied().unwrap_or_default()),
458            None => scope.matches_nothing = true,
459        }
460    }
461
462    // #members — what this viewer may not see is dropped *before* any
463    // filter runs, so a gated page's title, SEO text and URL stay
464    // private, and `?descendant_of=` against a member-only section
465    // cannot dump it. Subtree-aware via `path`, so a gated ancestor takes
466    // its descendants with it.
467    let access = crate::view_restriction::access_context(pool, viewer).await;
468
469    // ----- tree filters -------------------------------------------------
470    // The anchors are resolved against the *visible* set, not the whole
471    // table. Looking them up unrestricted would let a caller pivot off a
472    // page they cannot see: the anchor's path is all `?descendant_of=`
473    // needs.
474    let mut descendant_prefix = None;
475    let mut ancestor_paths = None;
476    if !scope.matches_nothing {
477        if let Some(root_id) = qs.filters.descendant_of {
478            descendant_prefix = visible_anchor_path(pool, scope.base(), &access, root_id).await?;
479            if descendant_prefix.is_none() {
480                scope.matches_nothing = true;
481            }
482        }
483        if let Some(leaf_id) = qs.filters.ancestor_of {
484            match visible_anchor_path(pool, scope.base(), &access, leaf_id).await? {
485                Some(path) => {
486                    let paths: Vec<String> = ancestor_paths_of(&path).into_iter().collect();
487                    if paths.is_empty() {
488                        scope.matches_nothing = true;
489                    }
490                    ancestor_paths = Some(paths);
491                }
492                None => scope.matches_nothing = true,
493            }
494        }
495    }
496    scope.descendant_prefix = descendant_prefix;
497    scope.ancestor_paths = ancestor_paths;
498
499    // ----- locale -------------------------------------------------------
500    if let Some(code) = qs.filters.locale.as_deref().filter(|s| !s.is_empty()) {
501        // Resolve through the shared helper: it honours `active` and
502        // falls back to the tenant default on an unknown code, which is
503        // what `tree`, `detail` and `menus` all do.
504        //
505        // Canonical content lives on the page row, so the default locale
506        // filters nothing. A non-default locale keeps only rows
507        // explicitly marked as variants (a v1 proxy for "in that locale").
508        let locale = crate::translation::resolve_locale(pool, Some(code)).await?;
509        scope.variants_only = locale.is_some_and(|loc| !loc.is_default);
510    }
511
512    // ----- tag ----------------------------------------------------------
513    if let Some(raw) = qs.filters.tag.as_deref().filter(|s| !s.is_empty()) {
514        scope.tag = Some(crate::page_tag::normalize_name(raw));
515    }
516
517    // Capture the raw needle so the promotion-pinning step below can run
518    // off the same value the title/slug/url_path filter uses.
519    let search_needle = qs.list.search.as_deref().filter(|s| !s.trim().is_empty());
520
521    // ----- SQL fast path ------------------------------------------------
522    let fast = if search_needle.is_some() || !access.denies_nothing() {
523        None
524    } else {
525        sql_order(&orderings)
526    };
527    let mut fts_ordered = false;
528    let (window, total_count): (Vec<Page>, usize) = if scope.matches_nothing && fast.is_some() {
529        (Vec::new(), 0)
530    } else if let Some(order) = fast {
531        use rustango::sql::CounterPool as _;
532        let total = usize::try_from(scope.narrowed()?.count(pool).await?).unwrap_or_default();
533        let rows = match order {
534            SqlOrder::Default => default_order_window(pool, &scope, limit, offset).await?,
535            SqlOrder::Keys(keys) => {
536                scope
537                    .narrowed()?
538                    .order_by_with_nulls(&keys)
539                    .limit(i64::try_from(limit).unwrap_or(i64::MAX))
540                    // A huge `?offset=` must not wrap negative.
541                    .offset(i64::try_from(offset).unwrap_or(i64::MAX))
542                    .fetch(pool)
543                    .await?
544            }
545        };
546        (rows, total)
547    } else {
548        let mut pages: Vec<Page> = if scope.matches_nothing {
549            Vec::new()
550        } else {
551            scope
552                .narrowed()?
553                // A deterministic base order. Without it the driver
554                // decides, and on Postgres an unrelated UPDATE moves a row
555                // to the end of the heap. `id` is unique, which is what
556                // the in-memory comparators below lack.
557                .order_by(&[("id", false)])
558                .fetch(pool)
559                .await?
560        };
561        if !access.is_unrestricted() {
562            pages.retain(|p| access.can_view(&p.path, p.page_type_id));
563        }
564
565        // ----- search ---------------------------------------------------
566        // #408 — relevance-ranked search. An installed external backend
567        // (Elasticsearch) takes priority; else Postgres full-text; else
568        // (None) the substring filter below. The ranked hit list also
569        // drives result order (relevance by default).
570        if let Some(needle) = search_needle {
571            crate::search_promotion::log_public_query(pool, needle, offset);
572            let ranked =
573                crate::search::ranked_public_page_ids(pool, tenant_slug, needle, 1000).await;
574            // A ranked hit OR a substring match (#702): the ranked backend
575            // finds stemmed words but not a partial word, slug fragment or
576            // URL path, so it adds to the substring match every backend
577            // runs rather than replacing it. Ranked hits lead, in rank
578            // order; substring-only hits follow in their existing order
579            // (the sort is stable).
580            let rank: Option<std::collections::HashMap<i64, usize>> =
581                ranked.map(|r| r.iter().enumerate().map(|(i, id)| (*id, i)).collect());
582            let n = crate::api::search::fold(needle);
583            pages.retain(|p| {
584                rank.as_ref()
585                    .is_some_and(|r| p.id.get().copied().is_some_and(|id| r.contains_key(&id)))
586                    || crate::api::search::contains_folded(&p.title, &n)
587                    || crate::api::search::contains_folded(&p.slug, &n)
588                    || crate::api::search::contains_folded(&p.url_path, &n)
589            });
590            if let Some(rank) = &rank {
591                pages.sort_by_key(|p| {
592                    p.id.get()
593                        .copied()
594                        .and_then(|id| rank.get(&id).copied())
595                        .unwrap_or(usize::MAX)
596                });
597                fts_ordered = true;
598            }
599        }
600
601        // ----- ordering -------------------------------------------------
602        // FTS already ordered by relevance; an explicit ?order= still wins.
603        if fts_ordered && orderings.is_empty() {
604            // keep the relevance order from the FTS hit list
605        } else if orderings.iter().any(|o| o.random) {
606            // Random is one-shot per request; cheap on bounded list size.
607            use rand::seq::SliceRandom as _;
608            pages.shuffle(&mut rand::rng());
609        } else if !orderings.is_empty() {
610            pages.sort_by(|a, b| compare_pages(a, b, &orderings));
611        } else {
612            pages.sort_by(compare_default);
613        }
614
615        // ----- search promotions (#289) ---------------------------------
616        // After the search filter + ordering settle, pin editor-promoted
617        // pages to the front of the list. Skipped when the request didn't
618        // include a search needle, when no SearchQuery row matches the
619        // normalized form, or when the query has no promotions attached.
620        //
621        // Promotion order: pages are inserted in `sort_order` ascending,
622        // de-duplicated against whatever was already at the head of the
623        // filtered list (a page that organically ranked first AND was
624        // promoted stays where the promotion put it, doesn't appear
625        // twice).
626        if let Some(needle) = search_needle {
627            if let Ok(Some(q)) = crate::search_promotion::find_by_query(pool, needle).await {
628                let query_id = q.id.get().copied().unwrap_or_default();
629                if query_id != 0 {
630                    if let Ok(promos) =
631                        crate::search_promotion::promotions_for_query(pool, query_id).await
632                    {
633                        // Pull each promoted page out of the filtered list
634                        // and reinsert it at the front in promotion order.
635                        // Promoted pages outside the filtered result set
636                        // stay dropped; the promotion table doesn't
637                        // override the visitor's filter scope.
638                        let mut pinned: Vec<Page> = Vec::with_capacity(promos.len());
639                        for p in &promos {
640                            if let Some(pos) = pages
641                                .iter()
642                                .position(|page| page.id.get().copied() == Some(p.page_id))
643                            {
644                                pinned.push(pages.remove(pos));
645                            }
646                        }
647                        for (i, page) in pinned.into_iter().enumerate() {
648                            pages.insert(i, page);
649                        }
650                    }
651                }
652            }
653        }
654
655        let total = pages.len();
656        (pages.into_iter().skip(offset).take(limit).collect(), total)
657    };
658
659    // #408 — a fuzzy "did you mean?" when an FTS search matched nothing
660    // but a near-match title exists (Postgres + pg_trgm only; None
661    // otherwise). The suggestion comes from a similarity query that joins
662    // nothing and spans `published + archived`, so confirm the suggested
663    // title belongs to something this caller can see before offering it.
664    let did_you_mean = match (fts_ordered, total_count, search_needle) {
665        (true, 0, Some(needle)) => match crate::search::did_you_mean(pool, needle, 0.3).await {
666            Some(title) => visible_title(pool, viewer, &title).await,
667            None => None,
668        },
669        _ => None,
670    };
671
672    // ----- serialize ----------------------------------------------------
673    let type_names = page_type_names(pool).await?;
674    let mut items = Vec::with_capacity(window.len());
675    for p in &window {
676        let mut obj = serialize_summary(p, &type_names);
677        // Validated against the first serialized row rather than a
678        // hand-written list, so it cannot drift from what we return.
679        if let Err(msg) = q::validate_fields(fields.as_ref(), &obj) {
680            return Ok(crate::api::error::ApiError::bad_request(msg).into_response());
681        }
682        q::apply_fields(&mut obj, fields.as_ref());
683        items.push(serde_json::Value::Object(obj));
684    }
685
686    let envelope = q::ListEnvelope {
687        meta: q::ListMeta {
688            did_you_mean,
689            ..q::ListMeta::paged(total_count, limit, offset)
690        },
691        items,
692    };
693    Ok(Json(envelope).into_response())
694}
695
696/// `GET /api/v2/pages/{id}/`
697pub async fn detail(
698    tenant: Tenant,
699    SessionUser(session_user): SessionUser,
700    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
701    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
702    headers: HeaderMap,
703    Path(id): Path<i64>,
704    Query(qs): Query<DetailQuery>,
705) -> Response {
706    // #members — gate against a public member OR an admin (member wins).
707    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
708    // #430 — a valid preview token for THIS page unlocks draft access.
709    let allow_draft = qs
710        .preview_token
711        .as_deref()
712        .zip(rustango::tenancy::TenantSlug::of(&tenant.org))
713        .and_then(|(t, org)| crate::preview_token::verify(&org, t, chrono::Utc::now().timestamp()))
714        == Some(id);
715    match detail_inner(
716        &tenant,
717        viewer,
718        &headers,
719        id,
720        allow_draft,
721        qs.locale.as_deref(),
722        qs.fields.as_deref(),
723    )
724    .await
725    {
726        Ok(resp) => resp,
727        Err(e) => {
728            tracing::error!(target: "rustango_cms::api", error = %e, "page detail failed");
729            crate::api::error::ApiError::internal().into_response()
730        }
731    }
732}
733
734/// `GET /api/v2/pages/find/?html_path=/about` — resolve a public URL
735/// path to its page and 302-redirect to the detail endpoint. Resolves **published** pages only; view
736/// restrictions are enforced by the detail endpoint the client follows
737/// to (`find` itself doesn't pre-check them).
738pub async fn find(
739    tenant: Tenant,
740    SessionUser(session_user): SessionUser,
741    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
742    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
743    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
744    Query(qs): Query<FindQuery>,
745) -> Response {
746    let Some(html_path) = qs.html_path.filter(|p| !p.is_empty()) else {
747        return crate::api::error::ApiError::bad_request("missing `html_path` query parameter")
748            .into_response();
749    };
750    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
751    let carry = carried_query(raw_query.as_deref());
752    match find_inner(&tenant, viewer, &html_path, &carry).await {
753        Ok(resp) => resp,
754        Err(e) => {
755            tracing::error!(target: "rustango_cms::api", error = %e, "page find failed");
756            crate::api::error::ApiError::internal().into_response()
757        }
758    }
759}
760
761/// The part of `find/`'s own query string that the detail URL should
762/// inherit, rendered as `?a=b&c=d` (or empty).
763///
764/// A client resolves its route with `find/` and lets `fetch` follow the
765/// 302 — that is the whole point of answering with a redirect. But the
766/// `Location` named only the id, so every other parameter was dropped in
767/// flight: `find/?html_path=/&locale=fr` returned the **English** page,
768/// and a SPA had no way to ask for anything else in one hop. Worse, it
769/// looked like it had worked; only `meta.locale` gave it away.
770///
771/// `html_path` is consumed here and must not travel. Everything else is
772/// forwarded verbatim, including parameters this endpoint knows nothing
773/// about — the detail endpoint ignores names it does not recognise, and
774/// hard-coding a list here would silently drop the next one added.
775fn carried_query(raw: Option<&str>) -> String {
776    let Some(raw) = raw.filter(|r| !r.is_empty()) else {
777        return String::new();
778    };
779    let kept: Vec<&str> = raw
780        .split('&')
781        .filter(|pair| !pair.is_empty())
782        .filter(|pair| {
783            let name = pair.split('=').next().unwrap_or("");
784            name != "html_path"
785        })
786        .collect();
787    if kept.is_empty() {
788        String::new()
789    } else {
790        format!("?{}", kept.join("&"))
791    }
792}
793
794async fn find_inner(
795    tenant: &Tenant,
796    viewer: Option<&rustango::tenancy::auth::User>,
797    html_path: &str,
798    carry: &str,
799) -> Result<Response, rustango::sql::ExecError> {
800    let pool = tenant.pool();
801    // url_path is stored without a trailing slash (e.g. "/about"); accept
802    // either form from callers by trying the path and its slash-variant.
803    let mut rows: Vec<Page> = Page::objects()
804        .where_(Page::url_path.eq(html_path))
805        .fetch(pool)
806        .await?;
807    if rows.is_empty() {
808        let alt = if let Some(stripped) = html_path.strip_suffix('/') {
809            stripped.to_owned()
810        } else {
811            format!("{html_path}/")
812        };
813        rows = Page::objects()
814            .where_(Page::url_path.eq(alt))
815            .fetch(pool)
816            .await?;
817    }
818    // `is_public()`, not `Published`: `list`, `tree` and `detail` all
819    // serve archived pages, and the tree hands out a `detail_url` for
820    // one. Matching on `Published` alone left `find` as the single
821    // endpoint that 404'd a page the rest of the API was happy to
822    // return — the same contradiction archived pages already caused on
823    // `detail`, one endpoint over.
824    let hit = rows
825        .into_iter()
826        .find(|p| PageStatus::str_is_public(&p.status));
827
828    // #members — a gated page must be indistinguishable from a missing
829    // one. Redirecting for one and 404-ing for the other turned this
830    // endpoint into an oracle: an anonymous caller could walk URLs and
831    // learn both which member-only pages exist and their ids, straight
832    // out of the `Location` header.
833    let id = match hit {
834        Some(p) => {
835            let pid = p.id.get().copied().unwrap_or_default();
836            let denied = crate::view_restriction::denied_page_ids(
837                pool,
838                viewer,
839                &[(pid, p.path.clone(), p.page_type_id)],
840            )
841            .await;
842            if denied.contains(&pid) {
843                None
844            } else {
845                Some(pid)
846            }
847        }
848        None => None,
849    };
850    match id {
851        // 302 Found → detail endpoint (which enforces view restrictions).
852        Some(id) => Ok((
853            StatusCode::FOUND,
854            [(
855                axum::http::header::LOCATION,
856                format!("/api/v2/pages/{id}/{carry}"),
857            )],
858        )
859            .into_response()),
860        // `not_found` appends " not found", so this must be the noun
861        // alone — and it must be the *same* noun the detail endpoint
862        // uses, because a gated page and a missing one are deliberately
863        // indistinguishable here.
864        None => Ok(crate::api::error::ApiError::not_found("page").into_response()),
865    }
866}
867
868async fn detail_inner(
869    tenant: &Tenant,
870    viewer: Option<&rustango::tenancy::auth::User>,
871    headers: &HeaderMap,
872    id: i64,
873    allow_draft: bool,
874    locale_code: Option<&str>,
875    fields: Option<&str>,
876) -> Result<Response, rustango::sql::ExecError> {
877    let pool = tenant.pool();
878    let Some(page) = lookup_page(pool, id).await? else {
879        return Ok(crate::api::error::ApiError::not_found("page").into_response());
880    };
881    // Public means `published` **or** `archived` — the same
882    // `PageStatus::is_public` test the renderer and sitemap use. Serving
883    // only `published` here made `detail` 404 pages that `tree` and
884    // `children` list *and* hand out a `detail_url` for, so every
885    // archived node advertised a dead link. Drafts still 404 unless a
886    // valid preview token unlocked them (#430).
887    let is_public = PageStatus::str_is_public(&page.status);
888    if !is_public && !allow_draft {
889        return Ok(crate::api::error::ApiError::not_found("page").into_response());
890    }
891    // Honour view restrictions — the same decision the public renderer
892    // makes, reported the way a JSON client can act on.
893    //
894    // The HTML path answers a denial with `303 → /members/login`, which
895    // is right for a browser and useless here: `fetch()` follows it and
896    // the caller ends up with a login page under status 200, with no
897    // signal that it is unauthenticated. So the API renders the same
898    // `Denial` as a status code instead.
899    if let Some(denial) =
900        crate::view_restriction_guard::decide(tenant, &page, viewer, headers).await
901    {
902        use crate::view_restriction_guard::Denial;
903        return Ok(match denial {
904            Denial::NeedsLogin => crate::api::error::ApiError::unauthenticated(),
905            Denial::Forbidden => crate::api::error::ApiError::forbidden(),
906            Denial::NeedsPassword { .. } => crate::api::error::ApiError::password_required(),
907        }
908        .into_response());
909    }
910
911    // #75 — an alias serves the source's content under its own URL. The
912    // gating above ran against the alias row (its own restrictions), and
913    // only the *content* is borrowed. Without this, detail returned the
914    // stale title copied at creation, no `extension` and no `builder`,
915    // while `tree` and the renderer all showed the source's live content.
916    let mut alias_owned = None;
917    if let Some(source_id) = page.alias_of {
918        match lookup_page(pool, source_id).await? {
919            Some(src) => alias_owned = Some(crate::page::alias_hybrid(&page, &src)),
920            None => tracing::warn!(
921                target: "rustango_cms::api",
922                alias_id = ?page.id.get().copied(),
923                source_id,
924                "alias source missing — serving the alias row verbatim",
925            ),
926        }
927    }
928    let page = alias_owned.as_ref().unwrap_or(&page);
929
930    let type_name = page_type_names(pool)
931        .await?
932        .get(&page.page_type_id)
933        .cloned()
934        .unwrap_or_default();
935    // Default locale resolves to `None` — canonical content already is
936    // the default-locale content, so the overlay would be a wasted query.
937    let locale = crate::translation::resolve_locale(pool, locale_code)
938        .await
939        .ok()
940        .flatten();
941    // Only a non-default locale needs an overlay — canonical content
942    // already *is* the default-locale content.
943    let locale_id = locale
944        .as_ref()
945        .filter(|l| !l.is_default)
946        .and_then(|l| l.id.get().copied());
947    let mut obj =
948        detail_object_with_type(pool, page, &type_name, None, None, locale_id, viewer).await;
949
950    echo_locale(&mut obj, locale.as_ref());
951
952    // Sparse selection, matching the list endpoints.
953    let keep = fields.map(|raw| -> std::collections::HashSet<String> {
954        raw.split(',')
955            .map(str::trim)
956            .filter(|s| !s.is_empty())
957            .map(str::to_owned)
958            .collect()
959    });
960    q::apply_fields(&mut obj, keep.as_ref());
961
962    Ok(Json(serde_json::Value::Object(obj)).into_response())
963}
964
965/// Return `title` only if some published page with that title is visible
966/// to `viewer`.
967///
968/// Used to vet a search suggestion before echoing it back — otherwise the
969/// "did you mean?" hint becomes a way to enumerate the titles of pages the
970/// caller is not allowed to see.
971async fn visible_title(
972    pool: &rustango::sql::Pool,
973    viewer: Option<&rustango::tenancy::auth::User>,
974    title: &str,
975) -> Option<String> {
976    let matches: Vec<Page> = Page::objects()
977        .where_(Page::title.eq(title.to_owned()))
978        .where_(Page::status.eq(PageStatus::Published.as_str().to_owned()))
979        .fetch(pool)
980        .await
981        .ok()?;
982    if matches.is_empty() {
983        return None;
984    }
985    let triples: Vec<(i64, String, i64)> = matches
986        .iter()
987        .map(|p| {
988            (
989                p.id.get().copied().unwrap_or_default(),
990                p.path.clone(),
991                p.page_type_id,
992            )
993        })
994        .collect();
995    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
996    triples
997        .iter()
998        .any(|(id, _, _)| !denied.contains(id))
999        .then(|| title.to_owned())
1000}
1001
1002/// Echo the locale a detail body was built in as `meta.locale`. An
1003/// unknown or inactive code falls back to the tenant default silently, so
1004/// without this a client cannot tell `?locale=fr` from `?locale=fr-typo`.
1005/// Every page detail body carries it, so the page URL's negotiated JSON
1006/// stays equal to `/api/v2/pages/{id}/`.
1007pub(crate) fn echo_locale(
1008    obj: &mut serde_json::Map<String, serde_json::Value>,
1009    locale: Option<&crate::locale::Locale>,
1010) {
1011    if let Some(meta) = obj.get_mut("meta").and_then(|m| m.as_object_mut()) {
1012        meta.insert(
1013            "locale".to_owned(),
1014            locale.map_or(serde_json::Value::Null, |l| serde_json::Value::String(l.code.clone())),
1015        );
1016    }
1017}
1018
1019/// Build the canonical page-detail object.
1020///
1021/// Shared by `GET /api/v2/pages/{id}/` and the public `Accept`-negotiated
1022/// JSON view, so the two are byte-identical by construction rather than
1023/// by discipline — the whole reason the editor's JSON preview can be
1024/// trusted to show what a client will actually receive.
1025///
1026/// The two `Option` parameters are the preview seam. `None` loads from
1027/// the database, which is what the saved-row API path wants; `Some(_)`
1028/// substitutes *virtual* values built from unsaved editor form state.
1029/// Callers that already hold the registry row pass `type_name` directly
1030/// to skip the full `cms_page_type` scan `page_type_names` performs.
1031///
1032/// `locale_id` localizes the result. `None` (or the default locale)
1033/// returns canonical content; `Some(id)` overlays that locale's
1034/// `cms_translation` rows — scalars (`title`, `seo_*`, extension fields),
1035/// per-leaf StreamField overrides, and page-builder text leaves. Every
1036/// JSON surface shares this, so localizing here localizes the v2 endpoint
1037/// and the `Accept`-negotiated page view together.
1038///
1039/// Note this deliberately performs **no** access control *on the page
1040/// itself*: the published check and `view_restriction_guard::enforce`
1041/// live in the callers, because a draft preview must bypass exactly
1042/// those gates. `viewer` is used only to filter the `children` listing —
1043/// see `child_summaries`.
1044pub async fn detail_object_with_type(
1045    pool: &rustango::sql::Pool,
1046    page: &Page,
1047    type_name: &str,
1048    extension_override: Option<serde_json::Value>,
1049    builder_override: Option<serde_json::Value>,
1050    locale_id: Option<i64>,
1051    viewer: Option<&rustango::tenancy::auth::User>,
1052) -> serde_json::Map<String, serde_json::Value> {
1053    let id = page.id.get().copied().unwrap_or_default();
1054    // #75 — per-type extension rows and builder documents live against
1055    // the *source* for an alias; the alias row has none of its own. Same
1056    // resolution the renderer applies (`extension_page_id`).
1057    let content_id = page.alias_of.unwrap_or(id);
1058    let mut type_names = std::collections::HashMap::new();
1059    type_names.insert(page.page_type_id, type_name.to_owned());
1060    let mut obj = serialize_summary(page, &type_names);
1061
1062    // Extension fields via the registered handler. `load_extension`
1063    // is opt-in per handler; the default returns `Value::Null`.
1064    let handler: Option<Box<dyn PageTypeHandler>> = find_handler(type_name);
1065    if let Some(h) = handler {
1066        // #442 — expose this page's routable sub-URL patterns so API
1067        // consumers can resolve/reverse them client-side. Omitted when
1068        // the page type declares none.
1069        let routes = h.routes();
1070        if !routes.is_empty() {
1071            let arr: Vec<serde_json::Value> = routes
1072                .iter()
1073                .map(|r| serde_json::json!({ "name": r.name, "pattern": r.pattern.as_str() }))
1074                .collect();
1075            obj.insert("routes".to_owned(), serde_json::Value::Array(arr));
1076        }
1077        let streams = stream_field_names(h.as_ref(), pool, content_id).await;
1078        match extension_override {
1079            Some(mut ext) => {
1080                if !ext.is_null() {
1081                    decode_stream_fields(&mut ext, &streams);
1082                    obj.insert("extension".to_owned(), ext);
1083                }
1084            }
1085            None => match h.load_extension(pool, content_id).await {
1086                Ok(mut ext) if !ext.is_null() => {
1087                    decode_stream_fields(&mut ext, &streams);
1088                    obj.insert("extension".to_owned(), ext);
1089                }
1090                Ok(_) => {}
1091                Err(e) => {
1092                    tracing::warn!(
1093                        target: "rustango_cms::api",
1094                        page_id = id,
1095                        error = %e,
1096                        "load_extension failed in api detail",
1097                    );
1098                }
1099            },
1100        }
1101    }
1102
1103    // #572 — page-builder body. When the page type has a published schema
1104    // (code type with a UI body, or a UI-created type), expose the filled,
1105    // lazily-upgraded values so headless clients render the UI-defined body.
1106    // Values only — clients render; no server-side zone HTML here.
1107    //
1108    // The compiled schema is kept so the localization pass below can reach
1109    // the builder's text leaves — they are keyed `builder.<path>`, which
1110    // the flat scalar overlay cannot address.
1111    let mut compiled_schema = None;
1112    match builder_override {
1113        Some(values) => {
1114            obj.insert("builder".to_owned(), values);
1115            if locale_id.is_some() {
1116                compiled_schema = crate::page_builder::values::values_for(
1117                    pool,
1118                    content_id,
1119                    page.page_type_id,
1120                    None,
1121                )
1122                .await
1123                .map(|(_, c)| c);
1124            }
1125        }
1126        None => {
1127            if let Some((values, compiled)) =
1128                crate::page_builder::values::values_for(pool, content_id, page.page_type_id, None)
1129                    .await
1130            {
1131                obj.insert("builder".to_owned(), values);
1132                compiled_schema = Some(compiled);
1133            }
1134        }
1135    }
1136
1137    if let Some(lid) = locale_id {
1138        localize_detail_object(pool, id, type_name, lid, &mut obj, compiled_schema.as_ref()).await;
1139    }
1140
1141    // Direct children, so a client can walk the site from any page without
1142    // first fetching the whole tree. One level only — `/api/v2/pages/tree/`
1143    // is the endpoint for depth.
1144    obj.insert(
1145        "children".to_owned(),
1146        serde_json::Value::Array(child_summaries(pool, page, viewer, locale_id).await),
1147    );
1148
1149    obj
1150}
1151
1152/// Most children a detail response will inline.
1153///
1154/// `tree` caps itself at `MAX_NODES` and says so via `meta.truncated`;
1155/// `children` had no equivalent, so a flat blog's homepage returned every
1156/// one of its posts on every request — including on each
1157/// `Accept: application/json` render of `/`. Clients that need the whole
1158/// set have `/api/v2/pages/?child_of=`, which is paged.
1159pub const MAX_CHILDREN: usize = 100;
1160
1161/// Summaries of a page's **direct** children — `id, title, slug, url,
1162/// has_children`.
1163///
1164/// One query covers both levels: children *and* grandchildren, sliced by
1165/// `depth`, so `has_children` costs nothing extra. It filters on `path`
1166/// rather than `parent_id` because `cms_page` indexes `path` and does not
1167/// index `parent_id` (`migrations/0001_cms_initial.json`).
1168///
1169/// `viewer` gates the listing: without it a page whose child subtree is
1170/// member-only would publish those titles and URLs to anonymous callers,
1171/// which is exactly what the restriction is for. This is the *only* thing
1172/// `detail_object_with_type` uses the viewer for — the page itself is
1173/// gated by its callers.
1174async fn child_summaries(
1175    pool: &rustango::sql::Pool,
1176    page: &Page,
1177    viewer: Option<&rustango::tenancy::auth::User>,
1178    locale_id: Option<i64>,
1179) -> Vec<serde_json::Value> {
1180    // An unsaved preview row has no id and therefore no children yet.
1181    let Some(&parent_id) = page.id.get() else {
1182        return Vec::new();
1183    };
1184    if page.path.is_empty() {
1185        return Vec::new();
1186    }
1187
1188    // Match the public renderer, not `list`: `archived` still resolves to
1189    // a real URL (`PageStatus::is_public`), so omitting it would advertise
1190    // fewer children than the site actually serves.
1191    let statuses = [
1192        PageStatus::Published.as_str().to_owned(),
1193        PageStatus::Archived.as_str().to_owned(),
1194    ];
1195    let mut rows: Vec<Page> = match Page::objects()
1196        .where_(Page::path.like(crate::tree::descendants_like(&page.path)))
1197        .where_(Page::depth.is_in([page.depth + 1, page.depth + 2]))
1198        .where_(Page::status.is_in(statuses))
1199        .order_by(&[("path", false)])
1200        .fetch(pool)
1201        .await
1202    {
1203        Ok(rows) => rows,
1204        Err(e) => {
1205            tracing::warn!(
1206                target: "rustango_cms::api",
1207                page_id = parent_id,
1208                error = %e,
1209                "child summaries lookup failed",
1210            );
1211            return Vec::new();
1212        }
1213    };
1214
1215    // Error pages are routing furniture, not site structure — excluded
1216    // here exactly as `tree` and `auto_menu` exclude them. Without this a
1217    // 404 handler parented under Home showed up as one of its children.
1218    let error_tid = crate::error_pages::error_page_type_id(pool).await;
1219    rows.retain(|p| error_tid.is_none_or(|tid| p.page_type_id != tid));
1220
1221    // #members — drop what the viewer may not see, before anything is
1222    // counted, so `has_children` never advertises a gated subtree either.
1223    let triples: Vec<(i64, String, i64)> = rows
1224        .iter()
1225        .map(|p| {
1226            (
1227                p.id.get().copied().unwrap_or_default(),
1228                p.path.clone(),
1229                p.page_type_id,
1230            )
1231        })
1232        .collect();
1233    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
1234
1235    let visible: Vec<&Page> = rows
1236        .iter()
1237        .filter(|p| !denied.contains(&p.id.get().copied().unwrap_or_default()))
1238        // Legacy per-locale variant trees are not children of this page in
1239        // any sense a client cares about (#275) — `feed` and the tree
1240        // endpoint drop them too.
1241        .filter(|p| p.locale_variant_of.is_none())
1242        .collect();
1243
1244    let mut grandchildren: std::collections::HashSet<i64> = std::collections::HashSet::new();
1245    for p in visible.iter().filter(|p| p.depth == page.depth + 2) {
1246        if let Some(pid) = p.parent_id {
1247            grandchildren.insert(pid);
1248        }
1249    }
1250
1251    let mut children: Vec<&&Page> = visible
1252        .iter()
1253        .filter(|p| p.depth == page.depth + 1)
1254        .collect();
1255    // Same ordering the rendered site uses (`sort_order, id`), not the
1256    // `path` order the query returned — see the note in `api::tree`.
1257    children.sort_by_key(|p| (p.sort_order, p.id.get().copied().unwrap_or_default()));
1258    if children.is_empty() {
1259        return Vec::new();
1260    }
1261
1262    // Localized titles for the whole set in one query, never per child.
1263    let translations = match locale_id {
1264        Some(lid) => {
1265            let ids: Vec<i64> = children.iter().filter_map(|p| p.id.get().copied()).collect();
1266            crate::translation::fetch_for_pages(pool, &ids, lid)
1267                .await
1268                .unwrap_or_default()
1269        }
1270        None => std::collections::HashMap::new(),
1271    };
1272
1273    children
1274        .into_iter()
1275        .take(MAX_CHILDREN)
1276        .map(|p| {
1277            let id = p.id.get().copied().unwrap_or_default();
1278            let title = translations
1279                .get(&id)
1280                .and_then(|m| m.get("title"))
1281                .filter(|s| !s.is_empty())
1282                .cloned()
1283                .unwrap_or_else(|| p.title.clone());
1284            serde_json::json!({
1285                "id": id,
1286                "title": title,
1287                "slug": p.slug,
1288                "url": if p.url_path.is_empty() { "/" } else { p.url_path.as_str() },
1289                "has_children": grandchildren.contains(&id),
1290                "detail_url": format!("/api/v2/pages/{id}/"),
1291            })
1292        })
1293        .collect()
1294}
1295
1296/// The extension fields this page type declares as StreamFields. Taken from
1297/// the handler's widgets rather than by sniffing whether a string parses as
1298/// a JSON array — that heuristic corrupts a prose field whose text happens
1299/// to look like "[1,2]".
1300async fn stream_field_names(
1301    h: &dyn PageTypeHandler,
1302    pool: &rustango::sql::Pool,
1303    page_id: i64,
1304) -> Vec<String> {
1305    h.widgets(pool, page_id)
1306        .await
1307        .unwrap_or_default()
1308        .into_iter()
1309        .filter(|w| w.kind == crate::widget::WidgetKind::Stream)
1310        .map(|w| w.name)
1311        .collect()
1312}
1313
1314/// StreamField columns are stored as JSON text. Hand them to API clients as
1315/// the block array itself — the same shape `builder` zones already use — so
1316/// a client never has to parse a string inside the JSON. An empty column is
1317/// an empty stream; text that is not a JSON array is left as it is.
1318fn decode_stream_fields(ext: &mut serde_json::Value, names: &[String]) {
1319    let Some(map) = ext.as_object_mut() else {
1320        return;
1321    };
1322    for name in names {
1323        let Some(serde_json::Value::String(raw)) = map.get(name) else {
1324            continue;
1325        };
1326        let decoded = if raw.trim().is_empty() {
1327            serde_json::Value::Array(Vec::new())
1328        } else {
1329            match serde_json::from_str::<serde_json::Value>(raw) {
1330                Ok(v @ serde_json::Value::Array(_)) => v,
1331                _ => continue,
1332            }
1333        };
1334        map.insert(name.clone(), decoded);
1335    }
1336}
1337
1338/// Overlay one locale's `cms_translation` rows onto a built detail object.
1339///
1340/// Three storage shapes, three mechanisms — a single flat overlay cannot
1341/// cover them, which is why the HTML renderer needs three calls too:
1342///
1343/// * **scalars** (`title`, `seo_*`, extension columns, and the legacy
1344///   whole-body stream blob) — [`crate::translation::overlay_translations`],
1345///   which replaces only keys the object already carries and recurses into
1346///   `extension`, matching on its `page_id`.
1347/// * **StreamField leaves** keyed `<field>.<uuid>.<name>` —
1348///   [`crate::block::translate::apply_translatable_overrides`], per stream
1349///   field, since dotted paths address block contents the flat overlay skips.
1350/// * **page-builder leaves** keyed `builder.<path>` —
1351///   [`crate::page_builder::values::apply_builder_translations`].
1352///
1353/// One `fetch_for_pages` query feeds all three. Missing or empty overrides
1354/// leave canonical content in place, so a partially-translated page degrades
1355/// per field rather than blanking.
1356async fn localize_detail_object(
1357    pool: &rustango::sql::Pool,
1358    page_id: i64,
1359    type_name: &str,
1360    locale_id: i64,
1361    obj: &mut serde_json::Map<String, serde_json::Value>,
1362    compiled: Option<&crate::page_builder::compile::CompiledSchema>,
1363) {
1364    let by_page = crate::translation::fetch_for_pages(pool, &[page_id], locale_id)
1365        .await
1366        .unwrap_or_default();
1367    let Some(here) = by_page.get(&page_id) else {
1368        return; // nothing translated for this page in this locale
1369    };
1370
1371    let mut value = serde_json::Value::Object(std::mem::take(obj));
1372    crate::translation::overlay_translations(&mut value, &by_page);
1373
1374    // Per-leaf stream overrides. Which extension fields are streams comes
1375    // from the handler's declared widgets rather than sniffing whether a
1376    // string happens to parse as a JSON array — that heuristic corrupts a
1377    // prose field whose text is something like "[1,2]".
1378    if let Some(h) = find_handler(type_name) {
1379        let stream_fields = stream_field_names(h.as_ref(), pool, page_id).await;
1380        if let Some(ext) = value.get_mut("extension") {
1381            // A whole-body translation row puts the stream back as a JSON
1382            // string; decode it so the per-leaf overrides below can apply.
1383            decode_stream_fields(ext, &stream_fields);
1384            for name in stream_fields {
1385                if let Some(raw) = ext.get(&name).cloned() {
1386                    let localized =
1387                        crate::block::translate::apply_translatable_overrides(&name, &raw, here);
1388                    if let Some(m) = ext.as_object_mut() {
1389                        m.insert(name, localized);
1390                    }
1391                }
1392            }
1393        }
1394    }
1395
1396    if let (Some(compiled), Some(builder)) = (compiled, value.get_mut("builder")) {
1397        if let Some(map) = builder.as_object_mut() {
1398            crate::page_builder::values::apply_builder_translations(compiled, map, here);
1399        }
1400    }
1401
1402    if let serde_json::Value::Object(m) = value {
1403        *obj = m;
1404    }
1405}
1406
1407// ---------------------------------------------------------------
1408// helpers
1409// ---------------------------------------------------------------
1410
1411async fn lookup_page(
1412    pool: &rustango::sql::Pool,
1413    id: i64,
1414) -> Result<Option<Page>, rustango::sql::ExecError> {
1415    let mut rows: Vec<Page> = Page::objects().where_(Page::id.eq(id)).fetch(pool).await?;
1416    Ok(rows.pop())
1417}
1418
1419async fn lookup_page_type(
1420    pool: &rustango::sql::Pool,
1421    type_name: &str,
1422) -> Result<Option<PageType>, rustango::sql::ExecError> {
1423    let mut rows: Vec<PageType> = PageType::objects()
1424        .where_(PageType::type_name.eq(type_name.to_owned()))
1425        .fetch(pool)
1426        .await?;
1427    Ok(rows.pop())
1428}
1429
1430/// Build a `{ page_type_id → type_name }` lookup so each row can
1431/// emit its symbolic type in the response without an N+1.
1432pub(crate) async fn page_type_names(
1433    pool: &rustango::sql::Pool,
1434) -> Result<std::collections::HashMap<i64, String>, rustango::sql::ExecError> {
1435    let rows: Vec<PageType> = PageType::objects().fetch(pool).await?;
1436    Ok(rows
1437        .into_iter()
1438        .filter_map(|pt| pt.id.get().copied().map(|id| (id, pt.type_name)))
1439        .collect())
1440}
1441
1442fn serialize_summary(
1443    p: &Page,
1444    type_names: &std::collections::HashMap<i64, String>,
1445) -> serde_json::Map<String, serde_json::Value> {
1446    let id = p.id.get().copied().unwrap_or_default();
1447    let type_name = type_names.get(&p.page_type_id).cloned().unwrap_or_default();
1448    let mut obj = serde_json::Map::new();
1449    obj.insert("id".to_owned(), serde_json::json!(id));
1450    obj.insert(
1451        "meta".to_owned(),
1452        serde_json::json!({
1453            "type": type_name,
1454            "detail_url": format!("/api/v2/pages/{id}/"),
1455            "html_url": p.url_path,
1456            "slug": p.slug,
1457            "depth": p.depth,
1458            "parent_id": p.parent_id,
1459            "alias_of": p.alias_of,
1460            "first_published_at": p.published_at,
1461            "updated_at": p.updated_at.get().copied(),
1462        }),
1463    );
1464    obj.insert("title".to_owned(), serde_json::json!(p.title));
1465    // The same `url` key tree nodes and child summaries use. It is also
1466    // at `meta.html_url` for compatibility, but a client should not need
1467    // a different accessor per endpoint to read one field — and unlike
1468    // `html_url`, this normalizes the root's empty `url_path` to "/",
1469    // as the other two shapes already did.
1470    obj.insert(
1471        "url".to_owned(),
1472        serde_json::json!(if p.url_path.is_empty() {
1473            "/"
1474        } else {
1475            p.url_path.as_str()
1476        }),
1477    );
1478    obj.insert("seo_title".to_owned(), serde_json::json!(p.seo_title));
1479    obj.insert(
1480        "seo_description".to_owned(),
1481        serde_json::json!(p.seo_description),
1482    );
1483    obj.insert("robots_index".to_owned(), serde_json::json!(p.robots_index));
1484    obj.insert(
1485        "sitemap_priority".to_owned(),
1486        serde_json::json!(p.sitemap_priority),
1487    );
1488    obj.insert(
1489        "show_in_menus".to_owned(),
1490        serde_json::json!(p.show_in_menus),
1491    );
1492    obj
1493}
1494
1495/// Build the set of ancestor paths for `path` (excluding `path` itself).
1496/// Mirrors [`crate::tree::MaterializedPath::ancestors`] without needing a
1497/// `MaterializedPath` value.
1498fn ancestor_paths_of(path: &str) -> std::collections::HashSet<String> {
1499    let mut out = std::collections::HashSet::new();
1500    let mut acc = String::new();
1501    for seg in path.split('/').filter(|s| !s.is_empty()) {
1502        acc.push_str(seg);
1503        acc.push('/');
1504        if acc != path {
1505            out.insert(acc.clone());
1506        }
1507    }
1508    out
1509}
1510
1511/// Fields `?order=` accepts on this endpoint. Anything else is a `400`
1512/// — kept next to `compare_pages`, which must handle exactly these.
1513const PAGE_ORDER_FIELDS: [&str; 8] = [
1514    "title",
1515    "slug",
1516    "url_path",
1517    "depth",
1518    "sort_order",
1519    "published_at",
1520    "updated_at",
1521    "created_at",
1522];
1523
1524fn compare_pages(a: &Page, b: &Page, specs: &[q::OrderSpec]) -> std::cmp::Ordering {
1525    for spec in specs {
1526        let ord = match spec.field.as_str() {
1527            "title" => a.title.cmp(&b.title),
1528            "slug" => a.slug.cmp(&b.slug),
1529            "url_path" => a.url_path.cmp(&b.url_path),
1530            "depth" => a.depth.cmp(&b.depth),
1531            "sort_order" => a.sort_order.cmp(&b.sort_order),
1532            "published_at" => a.published_at.cmp(&b.published_at),
1533            "updated_at" => a.updated_at.get().cmp(&b.updated_at.get()),
1534            "created_at" => a.created_at.get().cmp(&b.created_at.get()),
1535            _ => continue,
1536        };
1537        if ord != std::cmp::Ordering::Equal {
1538            return if spec.descending { ord.reverse() } else { ord };
1539        }
1540    }
1541    // Same reason as the default ordering: a unique last resort, so two
1542    // rows tied on every requested key still page deterministically.
1543    a.id.get().cmp(&b.id.get())
1544}
1545
1546#[cfg(test)]
1547mod tests {
1548    use super::carried_query;
1549
1550    #[test]
1551    fn the_resolved_path_is_not_carried_onto_the_detail_url() {
1552        // `html_path` is what `find/` consumed; repeating it on the
1553        // detail URL would be noise at best.
1554        assert_eq!(carried_query(Some("html_path=%2Fabout")), "");
1555        assert_eq!(carried_query(None), "");
1556        assert_eq!(carried_query(Some("")), "");
1557    }
1558
1559    #[test]
1560    fn everything_else_survives_the_redirect() {
1561        // The bug this exists for: a SPA resolving its route with
1562        // `?locale=fr` followed the 302 and got English back.
1563        assert_eq!(carried_query(Some("html_path=%2F&locale=fr")), "?locale=fr");
1564        assert_eq!(
1565            carried_query(Some("locale=fr&html_path=%2F&fields=title")),
1566            "?locale=fr&fields=title",
1567        );
1568    }
1569
1570    #[test]
1571    fn a_parameter_this_endpoint_never_heard_of_is_still_forwarded() {
1572        // Hard-coding an allowlist here would silently drop whatever the
1573        // detail endpoint gains next; it ignores names it doesn't know.
1574        assert_eq!(carried_query(Some("html_path=%2F&whatever=1")), "?whatever=1");
1575    }
1576
1577    #[test]
1578    fn values_are_forwarded_verbatim_not_re_encoded() {
1579        // Re-encoding risks double-escaping a token that already is.
1580        assert_eq!(
1581            carried_query(Some("html_path=%2Fx&preview_token=7.123.ab%2Fcd")),
1582            "?preview_token=7.123.ab%2Fcd",
1583        );
1584    }
1585}