From 5188319e7e941a901c448cb04ff395a969cdb4ca Mon Sep 17 00:00:00 2001 From: Sergey Shishkin Date: Sun, 21 Jul 2024 11:50:00 +0200 Subject: [PATCH] feat: replace pagefind cli call with node api --- packages/astro-pagefind/src/pagefind.ts | 31 +++++++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/packages/astro-pagefind/src/pagefind.ts b/packages/astro-pagefind/src/pagefind.ts index d0be62c..b9d93d7 100644 --- a/packages/astro-pagefind/src/pagefind.ts +++ b/packages/astro-pagefind/src/pagefind.ts @@ -1,6 +1,7 @@ import type { AstroIntegration } from "astro"; import { fileURLToPath } from "node:url"; -import { execSync } from "child_process"; +import path from "node:path"; +import { createIndex } from "pagefind"; import sirv from "sirv"; export default function pagefind(): AstroIntegration { @@ -46,7 +47,7 @@ export default function pagefind(): AstroIntegration { } }); }, - "astro:build:done": ({ logger }) => { + "astro:build:done": async ({ logger }) => { if (!outDir) { logger.warn( "astro-pagefind couldn't reliably determine the output directory. Search index will not be built.", @@ -54,10 +55,30 @@ export default function pagefind(): AstroIntegration { return; } - const cmd = `npx pagefind --site "${outDir}"`; - execSync(cmd, { - stdio: [process.stdin, process.stdout, process.stderr], + const { index, errors: createErrors } = await createIndex({}); + if (!index) { + logger.error("Pagefind failed to create index"); + createErrors.forEach((e) => logger.error(e)); + return; + } + const { page_count, errors: addErrors } = await index.addDirectory({ path: outDir }); + if (addErrors.length) { + logger.error("Pagefind failed to index files"); + addErrors.forEach((e) => logger.error(e)); + return; + } else { + logger.info(`Pagefind indexed ${page_count} pages`); + } + const { outputPath, errors: writeErrors } = await index.writeFiles({ + outputPath: path.join(outDir, "pagefind"), }); + if (writeErrors.length) { + logger.error("Pagefind failed to write index"); + writeErrors.forEach((e) => logger.error(e)); + return; + } else { + logger.info(`Pagefind wrote index to ${outputPath}`); + } }, }, };