Skip to main content

adk_site/migrate/
convert.rs

1//! Inventory to content (spec 3.5 §7.8.2 "Content model", S3, S17): every item becomes a
2//! [`ContentItem`] with a sanitised Markdown body that keeps its URL, uploads keep their paths,
3//! and taxonomy, feed and legacy redirects become 301s.
4//!
5//! After a crawl, a link to a page of the site the crawl could not read — one `robots.txt`
6//! disallows, say — becomes its text, since the new site will not have the page. Legacy
7//! runtime paths the new site does not serve — `/wp-includes/…`, theme and plugin files,
8//! `*.php` endpoints, and WordPress's `/wp-login.php` and `/xmlrpc.php` — answer 410 Gone
9//! (A-I4, S3).
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::sync::OnceLock;
13
14use awp_types::{
15    ContentId, ContentItem, ContentKind, ContentState, LanguageTag, Markdown, Redirect, Schedule,
16};
17use bytes::Bytes;
18use regex::Regex;
19use serde_json::Value;
20use url::Url;
21
22use super::error::Result;
23use super::inventory::{ItemStatus, SiteInventory, SourceKind};
24use super::sanitize::{DropReason, Dropped, Sanitiser, UrlUse};
25use crate::content::kind_directory;
26use crate::media::{MediaPipeline, MediaPolicy, MediaUpload};
27use crate::redirects::GONE_PAGE;
28
29/// Path prefixes of legacy server runtimes: theme, plugin, core and API files a static site
30/// replaces and answers 410 Gone for (spec 3.5 A-I4, S3).
31pub const LEGACY_RUNTIME_PREFIXES: &[&str] = &[
32    "/wp-admin/",
33    "/wp-includes/",
34    "/wp-content/themes/",
35    "/wp-content/plugins/",
36    "/wp-content/cache/",
37    "/wp-content/mu-plugins/",
38    "/wp-json/",
39    "/cgi-bin/",
40];
41
42/// WordPress endpoints that answer 410 Gone after a WordPress migration, whether or not the
43/// source read them (spec 3.5 A-I4).
44pub const WORDPRESS_ENDPOINTS: &[&str] = &[
45    "/wp-login.php",
46    "/xmlrpc.php",
47    "/wp-admin/",
48    "/wp-cron.php",
49    "/wp-comments-post.php",
50    "/wp-trackback.php",
51    "/wp-signup.php",
52    "/wp-activate.php",
53];
54
55/// Whether `path` belongs to a legacy server runtime: under [`LEGACY_RUNTIME_PREFIXES`] or a
56/// server-side script by its extension.
57///
58/// # Example
59///
60/// ```rust
61/// use adk_site::migrate::convert::legacy_runtime_path;
62///
63/// assert!(legacy_runtime_path("/wp-includes/js/jquery/jquery.min.js"));
64/// assert!(legacy_runtime_path("/wp-login.php"));
65/// assert!(!legacy_runtime_path("/wp-content/uploads/2026/10/panel.jpg"));
66/// assert!(!legacy_runtime_path("/about/"));
67/// ```
68pub fn legacy_runtime_path(path: &str) -> bool {
69    let path = path.split(['?', '#']).next().unwrap_or_default().to_ascii_lowercase();
70    LEGACY_RUNTIME_PREFIXES.iter().any(|prefix| path.starts_with(prefix))
71        || [".php", ".phtml", ".php5", ".asp", ".aspx", ".jsp", ".cgi"]
72            .iter()
73            .any(|extension| path.ends_with(extension))
74}
75
76/// The paths a crawl read: items, media, answered URLs and taxonomy archives.
77fn read_paths(inventory: &SiteInventory) -> BTreeSet<String> {
78    let mut read: BTreeSet<String> = BTreeSet::from(["/".to_string()]);
79    read.extend(inventory.items.iter().map(|item| item.path.clone()));
80    read.extend(inventory.media.iter().map(|media| media.path.clone()));
81    read.extend(
82        inventory
83            .urls
84            .iter()
85            .filter(|url| matches!(url.status, 200..=299 | 301 | 302 | 303 | 307 | 308))
86            .map(|url| url.path.split('?').next().unwrap_or_default().to_string()),
87    );
88    read.extend(
89        inventory
90            .taxonomies
91            .iter()
92            .flat_map(|t| t.terms.iter().filter_map(|term| term.path.clone())),
93    );
94    read
95}
96
97/// Whether `path` names a page in `read`, with or without its trailing slash or
98/// `index.html`.
99fn was_read(read: &BTreeSet<String>, path: &str) -> bool {
100    let path = path.split(['?', '#']).next().unwrap_or_default();
101    let bare = path.strip_suffix("index.html").unwrap_or(path);
102    let slashed = if bare.ends_with('/') { bare.to_string() } else { format!("{bare}/") };
103    [path, bare, slashed.as_str(), slashed.trim_end_matches('/')]
104        .iter()
105        .any(|candidate| !candidate.is_empty() && read.contains(*candidate))
106}
107
108/// How to convert.
109#[derive(Debug, Clone)]
110pub struct ConvertOptions {
111    /// The site's default language, for items whose language the source does not know.
112    pub language: LanguageTag,
113    /// The sanitiser.
114    pub sanitiser: Sanitiser,
115    /// Item keys and media paths left out: refused or quarantined subjects.
116    pub excluded: BTreeSet<String>,
117    /// The media pipeline uploads go through (type sniffing, metadata stripped).
118    pub media: MediaPolicy,
119}
120
121impl ConvertOptions {
122    /// Options for a site in `language` with the default sanitiser and media policy.
123    pub fn new(language: LanguageTag) -> Self {
124        Self {
125            language,
126            sanitiser: Sanitiser::new(),
127            excluded: BTreeSet::new(),
128            media: MediaPolicy::default(),
129        }
130    }
131
132    /// Leaves out these item keys and media paths.
133    #[must_use]
134    pub fn excluding(mut self, keys: impl IntoIterator<Item = String>) -> Self {
135        self.excluded.extend(keys);
136        self
137    }
138}
139
140/// The converted site.
141#[derive(Debug, Clone, Default)]
142pub struct Converted {
143    /// The items, sorted by id.
144    pub items: Vec<ContentItem>,
145    /// Uploads by their legacy path, for [`SiteProject::documents`](crate::content::SiteProject::documents),
146    /// so they keep their URLs.
147    pub documents: BTreeMap<String, Bytes>,
148    /// Redirects for the site configuration: legacy redirects, taxonomy archives, feeds and
149    /// items whose URL could not be kept.
150    pub redirects: Vec<Redirect>,
151    /// Item key to content id.
152    pub ids: BTreeMap<String, ContentId>,
153    /// Item key to the URL path its page has.
154    pub paths: BTreeMap<String, String>,
155    /// What the sanitiser dropped, by item key.
156    pub dropped: BTreeMap<String, Vec<Dropped>>,
157    /// What was not converted, and why.
158    pub notes: Vec<String>,
159}
160
161/// The built-in generator's tag slug, so a taxonomy archive redirects to its tag page.
162fn tag_slug(text: &str) -> String {
163    let slug = slug_part(text);
164    if slug.is_empty() { "tag".into() } else { slug }
165}
166
167fn slug_part(text: &str) -> String {
168    let mut out = String::new();
169    for c in text.chars().flat_map(char::to_lowercase) {
170        if c.is_alphanumeric() {
171            out.push(c);
172        } else if !out.ends_with('-') && !out.is_empty() {
173            out.push('-');
174        }
175    }
176    out.trim_matches('-').to_string()
177}
178
179/// Removes WordPress shortcodes from stored post content; the features they render are
180/// mapped to capabilities instead.
181fn strip_shortcodes(content: &str) -> String {
182    static SHORTCODE: OnceLock<Regex> = OnceLock::new();
183    let shortcode = SHORTCODE.get_or_init(|| {
184        Regex::new(r#"\[/?[a-z][a-z0-9_-]*(?:\s+[^\]]*)?/?\]"#).expect("static regex")
185    });
186    shortcode.replace_all(content, "").into_owned()
187}
188
189fn keepable_path(path: &str) -> bool {
190    path.starts_with('/') && path.ends_with('/') && !path.contains("..") && !path.contains('?')
191}
192
193fn text_of(html: &str) -> String {
194    let document = scraper::Html::parse_fragment(html);
195    super::html::collapse(&document.root_element().text().collect::<String>())
196}
197
198/// Converts an inventory into content items, uploads at their legacy paths and redirects.
199///
200/// # Errors
201///
202/// None today; reserved for stores that fail.
203///
204/// # Example
205///
206/// ```rust
207/// use adk_site::migrate::convert::{ConvertOptions, to_content};
208/// use adk_site::migrate::{InventoryItem, ItemStatus, SiteInventory, SourceKind};
209/// use awp_types::ContentKind;
210///
211/// let mut inventory = SiteInventory::new(SourceKind::Wxr, chrono::Utc::now());
212/// inventory.items.push(InventoryItem {
213///     key: "wp:post:1".into(), kind: ContentKind::Post, slug: "hello".into(), url: None,
214///     path: "/2026/10/hello/".into(), title: "Hello".into(), html: "<p>Hi</p>".into(),
215///     excerpt: None, status: ItemStatus::Published, published_at: None, modified_at: None,
216///     language: None, categories: vec![], tags: vec![], fields: Default::default(),
217///     media: vec![], author: None,
218/// });
219/// let converted = to_content(&inventory, &ConvertOptions::new("en".parse().unwrap())).unwrap();
220/// assert_eq!(converted.items[0].id.0, "posts/hello/en");
221/// assert_eq!(converted.paths["wp:post:1"], "/2026/10/hello/");
222/// ```
223pub fn to_content(inventory: &SiteInventory, options: &ConvertOptions) -> Result<Converted> {
224    let mut converted = Converted::default();
225    let origin = inventory.origin.as_deref().and_then(|o| Url::parse(o).ok());
226    let raw_content = inventory.source == SourceKind::Wxr;
227    let mut used: BTreeSet<(ContentKind, String, String)> = BTreeSet::new();
228    // Only a crawl knows which of the site's pages it could not read.
229    let read = matches!(inventory.source, SourceKind::Crawl | SourceKind::IsolatedReplay)
230        .then(|| read_paths(inventory));
231    let nav: BTreeMap<String, usize> = inventory
232        .menus
233        .first()
234        .map(|menu| {
235            menu.entries
236                .iter()
237                .enumerate()
238                .filter(|(_, e)| e.parent.is_none())
239                .map(|(i, e)| (e.target.clone(), i + 1))
240                .collect()
241        })
242        .unwrap_or_default();
243    for item in &inventory.items {
244        if options.excluded.contains(&item.key) {
245            converted.notes.push(format!("{} left out: excluded", item.key));
246            continue;
247        }
248        // A regional tag of the site's language (`en-US` on an `en` site) is the site's language.
249        let primary = |tag: &str| tag.split('-').next().unwrap_or(tag).to_ascii_lowercase();
250        let language = item
251            .language
252            .as_deref()
253            .filter(|l| primary(l) != primary(options.language.as_str()))
254            .and_then(|l| l.parse::<LanguageTag>().ok())
255            .unwrap_or_else(|| options.language.clone());
256        let home = item.path == "/";
257        let mut slug = if home {
258            "index".to_string()
259        } else {
260            let base = if item.kind == ContentKind::Page {
261                item.path
262                    .trim_matches('/')
263                    .split('/')
264                    .map(slug_part)
265                    .filter(|s| !s.is_empty())
266                    .collect::<Vec<_>>()
267                    .join("/")
268            } else {
269                slug_part(&item.slug)
270            };
271            if base.is_empty() { slug_part(&item.title) } else { base }
272        };
273        if slug.is_empty() {
274            slug = slug_part(&item.key);
275        }
276        let mut unique = slug.clone();
277        let mut n = 2;
278        while !used.insert((item.kind, unique.clone(), language.to_string())) {
279            unique = format!("{slug}-{n}");
280            n += 1;
281        }
282        let slug = unique;
283        let id = ContentId(format!("{}/{slug}/{language}", kind_directory(item.kind)));
284        let mut fields: BTreeMap<String, Value> = BTreeMap::new();
285        fields.insert("title".into(), Value::String(item.title.clone()));
286        if let Some(excerpt) = item.excerpt.as_deref().map(text_of).filter(|e| !e.is_empty()) {
287            fields.insert("summary".into(), Value::String(excerpt));
288        }
289        let page_path = if home {
290            "/".to_string()
291        } else if keepable_path(&item.path) {
292            fields.insert("path".into(), Value::String(item.path.clone()));
293            item.path.clone()
294        } else {
295            let default = match item.kind {
296                ContentKind::Page | ContentKind::Collection => format!("/{slug}/"),
297                kind => format!("/{}/{slug}/", kind_directory(kind)),
298            };
299            if item.path.starts_with('/') && !item.path.contains('?') && item.path != default {
300                converted.redirects.push(Redirect {
301                    from: item.path.clone(),
302                    to: default.clone(),
303                    status: 301,
304                });
305            }
306            default
307        };
308        if let Some(at) = item.published_at {
309            fields.insert("publishedAt".into(), Value::String(at.to_rfc3339()));
310        }
311        if let Some(at) = item.modified_at {
312            fields.insert("updatedAt".into(), Value::String(at.to_rfc3339()));
313        }
314        let mut tags: Vec<String> = item.categories.iter().chain(&item.tags).cloned().collect();
315        tags.retain(|t| !t.eq_ignore_ascii_case("uncategorized"));
316        tags.sort();
317        tags.dedup();
318        if !tags.is_empty() {
319            fields
320                .insert("tags".into(), Value::Array(tags.into_iter().map(Value::String).collect()));
321        }
322        if let Some(author) = &item.author {
323            fields.insert("byline".into(), Value::String(author.clone()));
324        }
325        for (key, value) in &item.fields {
326            fields.entry(key.clone()).or_insert_with(|| value.clone());
327        }
328        if let Some(order) = nav.get(&item.path) {
329            fields.insert("navOrder".into(), Value::from(*order as u64));
330        }
331        let page = origin.as_ref().and_then(|o| o.join(&item.path).ok());
332        let body_html = if raw_content { strip_shortcodes(&item.html) } else { item.html.clone() };
333        let mut unread: Vec<String> = Vec::new();
334        let site_origin = page.as_ref().map(super::http::origin_of);
335        let mut sanitised = options.sanitiser.sanitise_mapped(
336            &body_html,
337            page.as_ref(),
338            &mut |_: UrlUse, url: &Url| {
339                let Some(site_origin) = &site_origin else { return url.to_string() };
340                let path = super::html::site_path(url, site_origin);
341                // A link to a page the crawl could not read would break on the new site.
342                if let Some(read) = &read
343                    && path.starts_with('/')
344                    && !was_read(read, &path)
345                {
346                    unread.push(path);
347                    return String::new();
348                }
349                path
350            },
351        );
352        for target in unread {
353            converted.notes.push(format!(
354                "{}: the link to {target} became text; the crawl could not read that page",
355                item.key
356            ));
357            sanitised.dropped.push(Dropped {
358                element: "a".into(),
359                reason: DropReason::UnreadTarget { target },
360                excerpt: String::new(),
361            });
362        }
363        if !sanitised.dropped.is_empty() {
364            converted.dropped.insert(item.key.clone(), sanitised.dropped.clone());
365        }
366        let (state, schedule) = match item.status {
367            ItemStatus::Published => (ContentState::Published, None),
368            ItemStatus::Scheduled => (
369                ContentState::Scheduled,
370                item.published_at
371                    .map(|at| Schedule { publish_at: Some(at), ..Schedule::default() }),
372            ),
373            ItemStatus::Draft | ItemStatus::Pending | ItemStatus::Private => {
374                (ContentState::Draft, None)
375            }
376        };
377        let content = ContentItem {
378            id: id.clone(),
379            kind: item.kind,
380            slug,
381            language,
382            fields,
383            volatile: if item.kind == ContentKind::Product && item.fields.contains_key("stock") {
384                vec!["stock".into()]
385            } else {
386                Vec::new()
387            },
388            body: (!sanitised.markdown.trim().is_empty()).then_some(Markdown(sanitised.markdown)),
389            media: Vec::new(),
390            sources: Vec::new(),
391            schedule,
392            state,
393        };
394        converted.ids.insert(item.key.clone(), id);
395        converted.paths.insert(item.key.clone(), page_path);
396        converted.items.push(content);
397    }
398    converted.items.sort_by(|a, b| a.id.cmp(&b.id));
399    let pipeline = MediaPipeline::new(options.media.clone());
400    for media in &inventory.media {
401        if options.excluded.contains(&media.path) {
402            converted.notes.push(format!("{} left out: excluded", media.path));
403            continue;
404        }
405        let Some(bytes) = &media.bytes else {
406            converted.notes.push(format!("{} not copied: its bytes were not read", media.path));
407            continue;
408        };
409        if !media.path.starts_with('/') || media.path.contains("..") || media.path.ends_with('/') {
410            converted.notes.push(format!("{} not copied: not a file path", media.path));
411            continue;
412        }
413        let name = media.path.rsplit('/').next().unwrap_or(&media.path);
414        match pipeline.process(&MediaUpload {
415            name,
416            bytes,
417            alt: media.alt.clone(),
418            generated: false,
419        }) {
420            // Re-encoded to drop metadata, kept at its legacy path so its URL keeps working.
421            Ok(processed) => {
422                converted.documents.insert(media.path.clone(), processed.bytes);
423            }
424            Err(error) => converted.notes.push(format!("{} not copied: {error}", media.path)),
425        }
426    }
427    let listing =
428        if inventory.items.iter().any(|i| i.kind == ContentKind::Post) { "/posts/" } else { "/" };
429    let published_tags: BTreeSet<String> = converted
430        .items
431        .iter()
432        .filter(|i| i.state == ContentState::Published)
433        .filter_map(|i| i.fields.get("tags").and_then(Value::as_array))
434        .flatten()
435        .filter_map(Value::as_str)
436        .map(tag_slug)
437        .collect();
438    for taxonomy in &inventory.taxonomies {
439        for term in &taxonomy.terms {
440            let Some(path) = &term.path else { continue };
441            if keepable_path(path) {
442                let tag = tag_slug(&term.name);
443                let to = if published_tags.contains(&tag) {
444                    format!("/tags/{tag}/")
445                } else {
446                    listing.to_string()
447                };
448                converted.redirects.push(Redirect { from: path.clone(), to, status: 301 });
449            }
450        }
451    }
452    let origin_text = inventory.origin.clone().unwrap_or_default();
453    for url in &inventory.urls {
454        let Some(target) = &url.redirect_to else { continue };
455        if !matches!(url.status, 301 | 308) || url.path.contains('?') {
456            continue;
457        }
458        let to = target.strip_prefix(&origin_text).unwrap_or(target).to_string();
459        if to.starts_with('/') && to != url.path {
460            converted.redirects.push(Redirect { from: url.path.clone(), to, status: 301 });
461        }
462    }
463    let taxonomy_paths: BTreeSet<&String> = inventory
464        .taxonomies
465        .iter()
466        .flat_map(|t| t.terms.iter().filter_map(|term| term.path.as_ref()))
467        .collect();
468    for url in &inventory.urls {
469        // Pages that are no item: archives, listings and server endpoints the static site
470        // replaces; their URLs keep answering with a 301.
471        if url.status != 200
472            || url.item.is_some()
473            || url.page.is_none()
474            || url.path == "/"
475            || url.path.contains('?')
476            || taxonomy_paths.contains(&url.path)
477        {
478            continue;
479        }
480        let to = if url.path.ends_with(".php") { "/" } else { listing };
481        converted.redirects.push(Redirect { from: url.path.clone(), to: to.into(), status: 301 });
482    }
483    if inventory.urls.iter().any(|u| u.path == "/feed/") {
484        converted.redirects.push(Redirect {
485            from: "/feed/".into(),
486            to: "/feed.xml".into(),
487            status: 301,
488        });
489    }
490    // Legacy runtime paths the new site does not serve answer 410 Gone; a redirect added
491    // above for the same path wins (A-I4).
492    let wordpress = matches!(
493        inventory.source,
494        SourceKind::WordPressRest | SourceKind::Wxr | SourceKind::IsolatedReplay
495    ) || inventory.urls.iter().any(|url| url.path.contains("/wp-"));
496    let mut gone: BTreeSet<String> = inventory
497        .urls
498        .iter()
499        .map(|url| url.path.split('?').next().unwrap_or_default().to_string())
500        .filter(|path| legacy_runtime_path(path))
501        .collect();
502    if wordpress {
503        gone.extend(WORDPRESS_ENDPOINTS.iter().map(|path| (*path).to_string()));
504    }
505    for path in gone {
506        if converted.documents.contains_key(&path) || path.is_empty() {
507            continue;
508        }
509        converted.redirects.push(Redirect { from: path, to: GONE_PAGE.into(), status: 410 });
510    }
511    let kept: BTreeSet<&String> = converted.paths.values().collect();
512    let mut seen = BTreeSet::new();
513    converted.redirects.retain(|r| !kept.contains(&r.from) && seen.insert(r.from.clone()));
514    converted.redirects.sort_by(|a, b| a.from.cmp(&b.from));
515    tracing::info!(
516        items = converted.items.len(),
517        documents = converted.documents.len(),
518        redirects = converted.redirects.len(),
519        "inventory converted"
520    );
521    Ok(converted)
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    #[test]
529    fn shortcodes_are_removed() {
530        assert_eq!(
531            strip_shortcodes(
532                "a [contact-form-7 id=\"1\" title=\"x\"] b [gallery/] [/caption] c [1]"
533            ),
534            "a  b   c [1]"
535        );
536    }
537
538    #[test]
539    fn slugs_are_url_safe() {
540        assert_eq!(slug_part("Hello, World!"), "hello-world");
541        assert_eq!(slug_part("  über Café "), "über-café");
542        assert_eq!(tag_slug("!!"), "tag");
543    }
544}