pagefind 1.5.1

Implement search on any static website.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use std::{cmp::Ordering, path::PathBuf};

use anyhow::{bail, Result};
use either::Either;
use fossick::{FossickedData, Fossicker};
use futures::future::join_all;
use hashbrown::HashMap;
use index::PagefindIndexes;
use options::{PagefindInboundConfig, SearchOptions};
use output::SyntheticFile;
use rayon::prelude::*;
pub use service::api;
use wax::walk::Entry;
use wax::Glob;

use crate::index::build_indexes;

mod fossick;
mod fragments;
mod index;
#[macro_use]
mod logging;
pub mod options;
mod output;
mod playground;
pub mod runner;
#[cfg(feature = "serve")]
mod serve;
mod service;
mod utils;

const PAGEFIND_VERSION: &str = env!("CARGO_PKG_VERSION");

struct SearchState {
    options: SearchOptions,
    fossicked_pages: Vec<FossickedData>,
    built_indexes: Vec<PagefindIndexes>,
}

impl SearchState {
    pub fn new(options: SearchOptions) -> Self {
        Self {
            options,
            fossicked_pages: vec![],
            built_indexes: vec![],
        }
    }

    pub fn walk_for_files(&self, dir: PathBuf, glob: String) -> Result<Vec<Fossicker>> {
        let log = &self.options.logger;

        log.status("[Walking source directory]");
        if let Ok(glob) = Glob::new(&glob) {
            Ok(glob
                .walk(&dir)
                .filter_map(Result::ok)
                .map(|e| e.into_path())
                .map(|file_path| Fossicker::new_relative_to(file_path, dir.clone()))
                .collect())
        } else {
            log.error(format!(
                "Error: Provided glob \"{}\" did not parse as a valid glob.",
                self.options.glob
            ));
            bail!(
                "Error: Provided glob \"{}\" did not parse as a valid glob.",
                self.options.glob
            );
        }
    }

    /// Fossick files in parallel using rayon
    pub fn fossick_many(&mut self, dir: PathBuf, glob: String) -> Result<usize> {
        let files = self.walk_for_files(dir.clone(), glob)?;
        let log = &self.options.logger;

        log.info(format!(
            "Found {} file{} matching {}",
            files.len(),
            plural!(files.len()),
            self.options.glob
        ));
        log.status("[Parsing files]");

        // Use rayon for parallel HTML parsing - this is the main performance win
        // Partition results into successes and failures to report errors
        let (results, errors): (Vec<_>, Vec<_>) = files
            .into_par_iter()
            .map(|f| f.fossick_sync(&self.options))
            .partition_map(|r| match r {
                Ok(data) => Either::Left(data),
                Err(e) => Either::Right(e),
            });

        // Report any errors that occurred during parallel processing
        if !errors.is_empty() {
            log.warn(format!(
                "{} file{} failed to index",
                errors.len(),
                plural!(errors.len())
            ));
            for err in errors.iter().take(5) {
                log.v_warn(format!("  - {}", err));
            }
            if errors.len() > 5 {
                log.v_warn(format!("  ... and {} more", errors.len() - 5));
            }
        }

        let existing_page_count = self.fossicked_pages.len();
        self.fossicked_pages.extend(results);

        Ok(self.fossicked_pages.len() - existing_page_count)
    }

    pub fn fossick_one(&mut self, file: Fossicker) -> Result<FossickedData> {
        let result = file.fossick_sync(&self.options);
        if let Some(result) = result.as_ref().ok() {
            let existing = self
                .fossicked_pages
                .iter()
                .position(|page| page.url == result.url);
            if let Some(existing) = existing {
                *self.fossicked_pages.get_mut(existing).unwrap() = result.clone();
            } else {
                self.fossicked_pages.push(result.clone());
            }
        }
        result
    }

    pub async fn build_indexes(&mut self) -> Result<()> {
        let log = &self.options.logger;

        let used_custom_body = self.fossicked_pages.iter().any(|page| page.has_custom_body);
        if used_custom_body {
            log.info("Found a data-pagefind-body element on the site.\n↳ Ignoring pages without this tag.");
        } else {
            log.info(
                "Did not find a data-pagefind-body element on the site.\n↳ Indexing all <body> elements on the site."
            );
        }

        if self.options.root_selector == "html" {
            let pages_without_html = self
                .fossicked_pages
                .iter()
                .filter(|p| !p.has_html_element)
                .map(|p| format!("  * {:?} has no <html> element", p.fragment.data.url))
                .collect::<Vec<_>>();
            if !pages_without_html.is_empty() {
                log.warn(format!(
                    "{} page{} found without an <html> element. \n\
                    Pages without an outer <html> element will not be processed by default. \n\
                    If adding this element is not possible, use the root selector config to target a different root element.",
                    pages_without_html.len(),
                    plural!(pages_without_html.len())
                ));
                log.v_warn(pages_without_html.join("\n"));
            }
        }

        log.status("[Reading languages]");

        let pages_with_data = self.fossicked_pages.iter().filter(|d| {
            if used_custom_body && !d.has_custom_body && !d.force_inclusion {
                return false;
            }
            !d.word_data.is_empty()
        });

        let mut language_map: HashMap<String, Vec<fossick::FossickedData>> = HashMap::new();
        for page in pages_with_data {
            let language = page.language.clone();
            if let Some(lang_pages) = language_map.get_mut(&language) {
                lang_pages.push(page.clone());
            } else {
                language_map.insert(language, vec![page.clone()]);
            }
        }

        log.info(format!(
            "Discovered {} language{}: {}",
            language_map.len(),
            plural!(language_map.len()),
            language_map.keys().cloned().collect::<Vec<_>>().join(", ")
        ));
        log.v_info(
            language_map
                .iter()
                .map(|(k, v)| format!("  * {}: {} page{}", k, v.len(), plural!(v.len())))
                .collect::<Vec<_>>()
                .join("\n"),
        );

        let primary_language = language_map
            .iter()
            .filter(|(k, _)| k.as_str() != "unknown")
            .max_by(|(lang_a, pages_a), (lang_b, pages_b)| {
                let size = pages_a.len().cmp(&pages_b.len());
                if matches!(size, Ordering::Equal) {
                    return lang_b.cmp(lang_a);
                }
                size
            })
            .map(|(k, _)| k.clone())
            .unwrap_or_else(|| "unknown".into());

        if let Some(mut unknown_pages) = language_map.remove("unknown") {
            if !language_map.is_empty() {
                log.warn(format!(
                    "{} page{} found without an html lang attribute. \n\
                    Merging these pages with the {} language, as that is the main language on this site. \n\
                    Run Pagefind with --verbose for more information.",
                    unknown_pages.len(),
                    plural!(unknown_pages.len()),
                    primary_language
                ));

                log.v_warn(
                    unknown_pages
                        .iter()
                        .map(|p| {
                            format!("  * {:?} has no html lang attribute", p.fragment.data.url)
                        })
                        .collect::<Vec<_>>()
                        .join("\n"),
                );

                if let Some(primary) = language_map.get_mut(&primary_language) {
                    primary.append(&mut unknown_pages);
                } else {
                    language_map.insert(primary_language, unknown_pages);
                }
            } else {
                language_map.insert(primary_language, unknown_pages);
            }
        }

        log.status("[Building search indexes]");

        let indexes: Vec<_> = language_map
            .into_iter()
            .map(|(language, pages)| async { build_indexes(pages, language, &self.options).await })
            .collect();
        let built_indexes = join_all(indexes).await;
        self.built_indexes = built_indexes.into_iter().flat_map(|i| i.ok()).collect();

        let stats = self.built_indexes.iter().fold((0, 0, 0, 0), |mut stats, index| {
            log.v_info(format!(
                "Language {}: \n  Indexed {} page{}\n  Indexed {} word{}\n  Indexed {} filter{}\n  Indexed {} sort{}\n",
                index.language,
                index.fragments.len(),
                plural!(index.fragments.len()),
                index.word_count,
                plural!(index.word_count),
                index.filter_indexes.len(),
                plural!(index.filter_indexes.len()),
                index.sorts.len(),
                plural!(index.sorts.len())
            ));

            #[cfg(not(feature = "extended"))]
            match index.language.split('-').next() {
                Some("zh") => log.warn("⚠ Indexing Chinese in non-extended mode. \n\
                                        In this mode, Pagefind will not segment words that are not whitespace separated. \n\
                                        Running the extended Pagefind binary will include this segmentation. \n\
                                        Either download the pagefind_extended binary, or run via npx pagefind."),
                Some("ja") => log.warn("⚠ Indexing Japanese in non-extended mode. \n\
                                        In this mode, Pagefind will not segment words that are not whitespace separated. \n\
                                        Running the extended Pagefind binary will include this segmentation. \n\
                                        Either download the pagefind_extended binary, or run via npx pagefind."),
                _ => {}
            };

            stats.0 += index.fragments.len();
            stats.1 += index.word_count;
            stats.2 += index.filter_indexes.len();
            stats.3 += index.sorts.len();
            stats
        });

        log.info(format!(
            "Total: \n  Indexed {} language{}\n  Indexed {} page{}\n  Indexed {} word{}\n  Indexed {} filter{}\n  Indexed {} sort{}",
            self.built_indexes.len(),
            plural!(self.built_indexes.len()),
            stats.0,
            plural!(stats.0),
            stats.1,
            plural!(stats.1),
            stats.2,
            plural!(stats.2),
            stats.3,
            plural!(stats.3)
        ));

        if stats.1 == 0 && !self.options.running_as_service {
            log.error(
                "Error: Pagefind was not able to build an index. \n\
                Most likely, the directory passed to Pagefind was empty \
                or did not contain any html files.",
            );
            bail!(
                "Error: Pagefind was not able to build an index. \n\
                Most likely, the directory passed to Pagefind was empty \
                or did not contain any html files."
            );
        }
        Ok(())
    }

    pub async fn write_files(&self, custom_outdir: Option<PathBuf>) -> PathBuf {
        let outdir = custom_outdir.unwrap_or(self.options.bundle_output.clone());

        let index_entries: Vec<_> = self
            .built_indexes
            .iter()
            .map(|indexes| indexes.get_lang_meta(&self.options))
            .collect();

        join_all(
            self.built_indexes
                .iter()
                .map(|indexes| async { indexes.write_files_to_disk(&self.options, &outdir).await }),
        )
        .await;

        output::write_common_to_disk(
            index_entries,
            self.options.write_playground,
            &outdir,
            &self.options,
        )
        .await;

        outdir
    }

    pub async fn get_files(&self) -> Vec<SyntheticFile> {
        let outdir = &self.options.bundle_output;

        let index_entries: Vec<_> = self
            .built_indexes
            .iter()
            .map(|indexes| indexes.get_lang_meta(&self.options))
            .collect();

        let mut files: Vec<_> =
            join_all(self.built_indexes.iter().map(|indexes| async {
                indexes.write_files_to_memory(&self.options, outdir).await
            }))
            .await
            .into_iter()
            .flatten()
            .collect();

        files.extend(
            output::write_common_to_memory(
                index_entries,
                self.options.write_playground,
                outdir,
                &self.options,
            )
            .await
            .into_iter(),
        );

        // SyntheticFiles should only return the relative path to the file
        // _within_ the bundle directory — placing them in a final location
        // is left to the API consumer.
        for file in files.iter_mut() {
            if let Ok(relative_path) = file.filename.strip_prefix(outdir) {
                file.filename = relative_path.to_path_buf();
            }
        }

        files
    }

    pub fn log_start(&self) {
        let log = &self.options.logger;

        #[cfg(not(feature = "extended"))]
        log.status(&format!("Running Pagefind v{}", self.options.version));
        #[cfg(feature = "extended")]
        log.status(&format!(
            "Running Pagefind v{} (Extended)",
            self.options.version
        ));
        log.v_info("Running in verbose mode");

        log.info(format!(
            "Running from: {:?}",
            self.options.working_directory
        ));
        log.info(format!(
            "Source:       {:?}",
            self.options
                .site_source
                .strip_prefix(&self.options.working_directory)
                .unwrap_or(&self.options.site_source)
        ));
        log.info(format!(
            "Output:       {:?}",
            self.options
                .bundle_output
                .strip_prefix(&self.options.working_directory)
                .unwrap_or(&self.options.bundle_output)
        ));
    }
}