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