@bdocs/ssg 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -72,6 +72,7 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
72
72
  beastiesOptions?: Options | false;
73
73
  /**
74
74
  * Enable turbo mode: use zig-critters WASM instead of beasties JS for critical CSS.
75
+ * Falls back to beasties if the WASM binary is unavailable.
75
76
  *
76
77
  * @default false
77
78
  */
@@ -104,6 +105,17 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
104
105
  */
105
106
  onPageRendered?: (route: string, renderedHTML: string, appCtx: Context) => Promise<string | null | undefined> | string | null | undefined;
106
107
  onFinished?: (dir: string) => Promise<void> | void;
108
+ /**
109
+ * Callback invoked at each build sub-step boundary.
110
+ * Used to collect step data for the pipeline summary.
111
+ */
112
+ onStep?: (step: {
113
+ name: string;
114
+ duration: number;
115
+ success: boolean;
116
+ details?: string;
117
+ metrics?: Record<string, any>;
118
+ }) => void;
107
119
  /**
108
120
  * The application's root container `id`.
109
121
  *
@@ -72,6 +72,7 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
72
72
  beastiesOptions?: Options | false;
73
73
  /**
74
74
  * Enable turbo mode: use zig-critters WASM instead of beasties JS for critical CSS.
75
+ * Falls back to beasties if the WASM binary is unavailable.
75
76
  *
76
77
  * @default false
77
78
  */
@@ -104,6 +105,17 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
104
105
  */
105
106
  onPageRendered?: (route: string, renderedHTML: string, appCtx: Context) => Promise<string | null | undefined> | string | null | undefined;
106
107
  onFinished?: (dir: string) => Promise<void> | void;
108
+ /**
109
+ * Callback invoked at each build sub-step boundary.
110
+ * Used to collect step data for the pipeline summary.
111
+ */
112
+ onStep?: (step: {
113
+ name: string;
114
+ duration: number;
115
+ success: boolean;
116
+ details?: string;
117
+ metrics?: Record<string, any>;
118
+ }) => void;
107
119
  /**
108
120
  * The application's root container `id`.
109
121
  *
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as RouterOptions, c as ViteReactSSGContext, i as RouterFutureConfig, l as ViteReactSSGOptions, n as NonIndexRouteRecord, o as StyleCollector, r as RouteRecord, s as ViteReactSSGClientOptions, t as IndexRouteRecord } from "./types-DnC0a9DP.cjs";
1
+ import { a as RouterOptions, c as ViteReactSSGContext, i as RouterFutureConfig, l as ViteReactSSGOptions, n as NonIndexRouteRecord, o as StyleCollector, r as RouteRecord, s as ViteReactSSGClientOptions, t as IndexRouteRecord } from "./types-BMIDte34.cjs";
2
2
  import { ReactNode } from "react";
3
3
  import { HelmetProps } from "react-helmet-async";
4
4
 
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as RouterOptions, c as ViteReactSSGContext, i as RouterFutureConfig, l as ViteReactSSGOptions, n as NonIndexRouteRecord, o as StyleCollector, r as RouteRecord, s as ViteReactSSGClientOptions, t as IndexRouteRecord } from "./types-BC2n-pCm.mjs";
1
+ import { a as RouterOptions, c as ViteReactSSGContext, i as RouterFutureConfig, l as ViteReactSSGOptions, n as NonIndexRouteRecord, o as StyleCollector, r as RouteRecord, s as ViteReactSSGClientOptions, t as IndexRouteRecord } from "./types-DefKqSqW.mjs";
2
2
  import { HelmetProps } from "react-helmet-async";
3
3
  import { ReactNode } from "react";
4
4
 
package/dist/node.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./state-CAM2wH0H.cjs`);let n=require(`react/jsx-runtime`),r=require(`@bdocs/dui`),i=require(`node:module`),a=require(`node:path`);a=e.t(a,1);let o=require(`fs-extra`);o=e.t(o,1);let s=require(`vite`),c=require(`node:crypto`);c=e.t(c,1);let l=require(`node:events`),u=require(`node:stream`),d=require(`react-dom/server`);d=e.t(d);let f=require(`node:fs`);f=e.t(f,1);let p=require(`node:fs/promises`);p=e.t(p,1);const m=/import\("([^)]+)"\)/g;let h=null;async function g(){if(!h){let{matchRoutes:e}=await import(`react-router-dom`);h=e}return h}async function _({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await g())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(m);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=v(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function v(e,t){let n=new Set;if(!t)return n;for(let r of t)y(e,r,n);return n}function y(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{y(e,t,n)}),n):n}async function b(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function ee(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const x=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function S({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${x}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function C(e,t=`index.html`){let[,n]=[...(await o.default.readFile((0,a.join)(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function w(e){return`<link rel="stylesheet" href="${e}">`}function T(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=E(e);r&&n.push(r)}}),n.join(``)}function E(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function te(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function D(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function ne(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;te(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:D(e.headers)};return new Request(n.href,r)}async function re(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=u.Readable.from(n);r.pipe(t),await(0,l.once)(r,`end`)}else t.end()}function ie(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function O(e){return d.renderToString((0,n.jsx)(n.Fragment,{children:e}))}function k(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let A=null;function j(){return A||(A=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=require(`node:module`);return e(require(`url`).pathToFileURL(__filename).href)(`react-helmet-async`).HelmetProvider})(),A)}let ae=null;async function M(){return ae||=await import(`react-router-dom`),ae}var N=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,n)=>{let{routes:r,base:i}=this.context,{matchRoutes:a}=await M(),o=ne(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=a(t.r([...r],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},i);if(!l){n.statusCode=404,n.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){n.statusCode=404,n.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){n.statusCode=200,n.end(`There is no loader for the route: ${c}`);return}await re(await P({loader:d,params:u.params,request:o,routeId:c}),n)},this.context=e}async render(e){let{base:r,routes:i,getStyleCollector:a,routerOptions:o}=this.context,s=t.s(e),c=s;if(r!==`/`){let e=t.s(r).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let l=`http://localhost${c}`,u=new Request(l),d=a?await a():null,f={},p=null,{StaticRouterProvider:m,createStaticHandler:h,createStaticRouter:g}=await M(),_=this._dataRoutes??=t.r([...i],e=>e);this._staticHandler??=h(_,{basename:r});let{query:v}=this._staticHandler,y=await v(u),b=0;for(;y instanceof Response&&b<10;){let e=y.headers.get(`Location`);if(!e)break;let n;if(/^https?:\/\//i.test(e))try{let r=new URL(e);if(r.hostname===`localhost`||r.hostname===``)n=`http://localhost${t.s(r.pathname+r.search+r.hash)}`;else break}catch{break}else n=`http://localhost${t.s(e)}`;y=await v(new Request(n)),b++}if(y instanceof Response)throw y;p=y;let ee=g(_,p,{future:o.future}),x=j(),S=x;S&&typeof S==`function`&&(S.canUseDOM=!1);let C=(0,n.jsx)(x,{context:f,children:(0,n.jsx)(m,{router:ee,context:p})});d&&(C=d.collect(C));let w=await O(C),{htmlAttributes:T,bodyAttributes:E,metaAttributes:te,styleTag:D}=k(w,f,d);return{appHTML:w,htmlAttributes:T,bodyAttributes:E,metaAttributes:te,styleTag:D,routerContext:p}}};async function P({loader:e,params:t,request:n,routeId:r}){let{json:i}=await M(),a=await e({request:ie(I(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return F(a)?a:i(a)}function F(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function I(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function oe(e){return new N(e)}var L=`0.2.0`;function R(e,t){(0,r.info)(`${e}${t?r.colors.blue(` (${t})`):``}`)}function se(e){return`${(e.length/1024).toFixed(2)} KiB`}async function ce(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&ue(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function le(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:(0,a.join)(e.root,t))}const z=/[:*?]/;function ue(e){return e?z.test(e):!1}const B=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),V=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function H(e){try{return f.default.statSync(e).size}catch{return 0}}async function de(e,t){let n=(0,a.join)(e,`.vite`),r=(0,a.join)(e,`assets`),i={},o=(0,a.join)(n,`manifest.json`);f.default.existsSync(o)&&(i=JSON.parse(await f.default.readFileSync(o,`utf-8`)));let s=0,c=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=H((0,a.join)(e,n));s+=i;for(let t of r)c+=H((0,a.join)(e,t))}let l=0,u=0;if(f.default.existsSync(r)){let e=f.default.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=a.default.extname(t.name).toLowerCase(),n=(0,a.join)(r,t.name);B.has(e)?l+=H(n):V.has(e)&&u++}}let d=(0,a.join)(e,`index.html`),p=0,m=[];if(f.default.existsSync(d)){let e=H(d);p+=e,m.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=f.default.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=H((0,a.join)(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);p+=t,m.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:s,totalCSSBundleSize:c,totalImagesSize:l,totalHTMLSize:p,fontCount:u,pages:m}}function fe(e,t){let n=a.default.resolve(e,`..`,`.boltdocs`,`reports`);f.default.existsSync(n)||f.default.mkdirSync(n,{recursive:!0});let r=(0,a.join)(n,`performance.json`);f.default.writeFileSync(r,JSON.stringify(t,null,2))}const pe=Number.parseInt(s.version)>=5?[`.vite`]:[];function me(e){return Number.parseInt(s.version)>=8?{rolldownOptions:e}:{rollupOptions:e}}function U(e){let t=[];if(!o.default.existsSync(e))return t;let n=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),r=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]),i=o.default.readdirSync(e,{withFileTypes:!0});for(let o of i){if(o.name.startsWith(`.`)||r.has(o.name))continue;let i=(0,a.join)(e,o.name);if(o.isDirectory())t.push(...U(i));else{let e=`.`+o.name.split(`.`).pop()?.toLowerCase();n.has(e)&&t.push(i)}}return t}function he(e,t,n){try{let n=[],r=(0,a.join)(e,t);o.default.existsSync(r)&&n.push(...U(r));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=(0,a.join)(e,t);o.default.existsSync(r)&&n.push(r)}n.sort();let i=c.default.createHash(`sha256`);for(let t of n){let n=o.default.statSync(t),r=(0,a.relative)(e,t).replace(/\\/g,`/`);i.update(r),i.update(n.mtimeMs.toString()),i.update(n.size.toString())}return i.digest(`hex`)}catch{return Math.random().toString(36).substring(2,12)}}function ge(e,n){return`static-loader-data${t.s(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${n}.json`}function _e(e,n=`/`){let r=t.s(e),i=r;if(n!==`/`){let e=t.s(n).replace(/\/$/,``);!r.startsWith(e+`/`)&&r!==e&&(i=`${e}${r}`)}return i!==`/`&&i.endsWith(`/`)?i.slice(0,-1):i}function ve(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function ye(e={},n={}){let l=process.env.MODE||process.env.NODE_ENV||e.mode||`production`,u=await(0,s.resolveConfig)(n,`build`,l,l),d=process.cwd(),f=u.root||d,p=u.build.outDir||`dist`,m=u.base,h=Object.assign({},u.ssgOptions||{},e),g=performance.now(),{script:v=`sync`,mock:y=!1,htmlEntry:w=`index.html`,entry:E=await C(f,w),formatting:te=`none`,includedRoutes:D=ve,onBeforePageRender:ne,onPageRendered:re,onFinished:ie,dirStyle:O=`flat`,includeAllRoutes:k=!1,format:A=`esm`,concurrency:j=20,rootContainerId:ae=`root`,routeToSourceFileMap:M={},cacheDir:N=`.boltdocs/build`}=h,P=h.beastiesOptions??{},F=h.turbo??!1,I=`docs`,L=Object.values(M);if(L.length>0){let e=L[0],t=(0,a.relative)(f,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(I=t[0])}let z=(0,a.isAbsolute)(p)?p:(0,a.join)(f,p),ue=he(f,I,p),B=ue.substring(0,12),V=(0,a.join)(f,`.vite-react-ssg-temp`,F?`turbo-ssr`:B),H=(0,a.isAbsolute)(N)?N:(0,a.join)(f,N),U=(0,a.join)(H,`client-hash.txt`),ye=(0,a.join)(H,`template-index.html`),W=!1;try{o.default.existsSync(U)&&o.default.existsSync(ye)&&o.default.existsSync(z)&&o.default.existsSync((0,a.join)(z,`assets`))&&(await o.default.readFile(U,`utf-8`)).trim()===ue&&(W=!0)}catch{}function G(e){return e.startsWith(`dist/`)||e.startsWith(`.vite-react-ssg-temp/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=(0,s.createLogger)(),Se=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||G(e)||Se(e,t)};let Ce=K.info;K.info=(e,t)=>{G(e)||Ce(e,t)},W?(R(`Client code unchanged. Bypassing client build...`),await o.default.ensureDir(z),await o.default.copy(ye,(0,a.join)(z,w))):((0,r.dividerLog)(),R(`Build for client...`),await(0,s.build)((0,s.mergeConfig)(n,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...me({input:{app:(0,a.join)(f,w||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:u.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){p=e.build.outDir||`dist`}}]})),(0,r.success)(`Client build complete`),await o.default.ensureDir(H),await o.default.copy((0,a.join)(z,w),ye),await o.default.writeFile(U,ue,`utf-8`)),(0,r.dividerLog)();let we=()=>{};if(y){let{jsdomGlobal:e}=await Promise.resolve().then(()=>require(`./jsdomGlobal-B4hHTFBO.cjs`));we=e()}let q=await le(u,E);(F||W)&&o.default.existsSync(V)&&o.default.readdirSync(V).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0?R(`Server build unchanged. Bypassing server build...`):(o.default.existsSync(V)&&await o.default.remove(V),R(`Build for server...`),process.env.VITE_SSG=`true`,await(0,s.build)((0,s.mergeConfig)(n,{logLevel:`warn`,build:{ssr:q,manifest:!0,outDir:V,minify:!1,cssCodeSplit:!1,...me({output:A===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:u.mode})),(0,r.success)(`Server build complete`));let Te=A===`esm`&&process.platform===`win32`?`file://`:``,Ee=A===`esm`?`.mjs`:`.cjs`,De=q.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),Oe=Te+(0,a.join)(V,(q.includes(`/`)||q.includes(`\\`)?q.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(Ee,``):De)+Ee).replace(/\\/g,`/`),ke=JSON.parse(await o.default.readFile((0,a.join)(V,...pe,`manifest.json`),`utf-8`)),Ae=typeof require<`u`?require:(0,i.createRequire)(require(`url`).pathToFileURL(__filename).href),{createRoot:je,includedRoutes:Me}=A===`esm`?await import(Oe):Ae(Oe),Ne=Me||D,{routes:Pe}=await je(!1),{paths:Fe}=await ce(Pe),J=k?Fe:await Ne(Fe,Pe||[]);J=ve(J,Pe||[]),J=Array.from(new Set(J)),(0,r.dividerLog)(),R(`Rendering Pages...`,J.length);let Ie=P!==!1&&!F?await b(p,{publicPath:m,...P}):void 0,Y;F&&(Y=await ee(),Y?(0,r.info)("Critical CSS generation enabled via `zig-critters` (turbo)"):(0,r.warn)(`zig-critters not available, falling back to beasties`)),Ie&&!Y&&(0,r.info)("Critical CSS generation enabled via `beasties`");let Le=``;if(Y){let e=(0,a.join)(z,`assets`);if(o.default.existsSync(e)){let t=o.default.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Le+=o.default.readFileSync((0,a.join)(e,n),`utf-8`)+`
2
- `}}let Re=(0,r.createSpinner)(`Rendering pages...`);Re.start();let ze=JSON.parse(await o.default.readFile((0,a.join)(z,...pe,`ssr-manifest.json`),`utf-8`)),Be=JSON.parse(await o.default.readFile((0,a.join)(z,...pe,`manifest.json`),`utf-8`)),Ve=await o.default.readFile((0,a.join)(z,w),`utf-8`);o.default.rmSync((0,a.join)(z,w)),Ve=be(Ve,v);let He=(await import(`p-queue`)).default||await import(`p-queue`),Ue=new He({concurrency:j}),We=new He({concurrency:1}),Ge={},Ke=0,qe=new Map,Je=0,Ye=0,Xe=0,Ze=(0,a.join)(H,`ssg-cache.json`),X=(0,a.join)(H,`ssg-pages`),Z={};if(!F)try{o.default.existsSync(Ze)&&(Z=await o.default.readJson(Ze))}catch{}let Qe={...Z},Q=new Set;Q.add(X);for(let e of J){let t=O===`nested`?(0,a.join)(e.replace(/^\//g,``),`index.html`):`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`;Q.add((0,a.join)(z,(0,a.dirname)(t)));let n=e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e;Q.add((0,a.join)(z,`static-loader-data`,(0,a.dirname)(n)))}Q.add((0,a.join)(z,`static-loader-data`)),await Promise.all([...Q].map(e=>o.default.ensureDir(e)));for(let e of J){let n=c.default.createHash(`md5`).update(e).digest(`hex`),i=(0,a.join)(X,`${n}.html`),s=(0,a.join)(X,`${n}.json`),l=`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`,u=O===`nested`?(0,a.join)(e.replace(/^\//g,``),`index.html`):l,d=(0,a.join)(z,u),f=t.s(e).replace(/\/$/,``),p=M[f]||M[e],h=!1,g=0;if(!F&&W&&p&&o.default.existsSync(p))try{if(g=Math.round(o.default.statSync(p).mtimeMs),o.default.existsSync(i)){let t=Z[f]||Z[e];t&&Math.round(t.mtime)===g&&(h=!0)}}catch{}if(h){Ue.add(async()=>{try{if(W)await o.default.copy(i,d);else{let e=await o.default.readFile(i,`utf-8`);e=e.replace(/window\.__VITE_REACT_SSG_HASH__\s*=\s*'[^']*'/,`window.__VITE_REACT_SSG_HASH__ = '${B}'`),await o.default.writeFile(d,e,`utf-8`)}let t=Z[f]||Z[e];if(t?.loaderDataFilePath&&o.default.existsSync(s)){let n=W?t.loaderDataFilePath:ge(e,B);await o.default.copy(s,(0,a.join)(z,n)),Ge[_e(e,m)]=n,Ke++}Ye++}catch(t){throw Error(`Error on cached page: ${e}\n${t.stack}`)}});continue}Ue.add(async()=>{try{let n=await je(!1,e),{base:c,routes:l,triggerOnSSRAppRendered:d,transformState:f=t.n,app:h,routerType:v}=n,y=await ne?.(e,Ve,n)||Ve,b=`${t.c(c)}${t.a(e)}`,ee=oe(n),C;if(!h&&v===`remix`){let t=qe.get(e);t?C=t:(C=await _({routes:[...l],locationArg:b,base:c,serverManifest:ke,manifest:Be,ssrManifest:ze}),qe.set(e,C))}else C=new Set;let{appHTML:w,bodyAttributes:E,htmlAttributes:D,metaAttributes:ie,styleTag:O,routerContext:k}=await ee.render(e),A=k?.loaderData,j;if(A&&Object.keys(A).length>0){let t=ge(e,B);j=t,await o.default.writeFile((0,a.join)(z,t),JSON.stringify(A)),Ge[_e(e,m)]=t,Ke++}await d?.(e,w,n);let M=await S({rootContainerId:ae,appHTML:w,indexHTML:y,metaAttributes:ie,bodyAttributes:E,htmlAttributes:D,initialState:null}),N=T(C),P=M.replace(/<script[^>]*>(?:(?!<\/script>)[\s\S])*__staticRouterHydrationData(?:(?!<\/script>)[\s\S])*<\/script>/g,``);N&&(P=P.replace(`<head>`,`<head>${N}`));let I=await re?.(e,P,n)||P,L=``;if(A&&Object.keys(A).length>0){let t=JSON.stringify(A).replace(/</g,`\\u003c`);L=`window.__VITE_REACT_SSG_STATIC_LOADER_DATA__ = { '${_e(e,m)}': ${t} };`}let R=``;if(k){let e={loaderData:k.loaderData??{},actionData:k.actionData??null,errors:k.errors??null};R=`window.__staticRouterHydrationData = ${JSON.stringify(e).replace(/</g,`\\u003c`)};`}let se=`<script>window.__VITE_REACT_SSG_HASH__ = '${B}';${L}${R}<\/script>`;if(I=I.replace(`<head>`,`<head>${se}`),I=I.replace(`<script>${x}<\/script>`,``),Y){try{Le&&(I=await Y.processHtml(I,Le))}catch(t){(0,r.warn)(`[zig-critters] Failed to inline CSS for "${e}": ${t instanceof Error?t.message:String(t)}`)}I=I.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`)}else Ie&&(I=await We.add(()=>Ie.process(I)),I=I.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`));O&&(I=I.replace(`<head>`,`<head>${O}`));let ce=await xe(I,te);if(await o.default.writeFile((0,a.join)(z,u),ce,`utf-8`),!F&&p&&o.default.existsSync(p)){await o.default.writeFile(i,ce,`utf-8`);let n=t.s(e).replace(/\/$/,``),r=Math.round(g);A&&Object.keys(A).length>0&&j?(await o.default.writeFile(s,JSON.stringify(A),`utf-8`),Qe[n]={mtime:r,loaderDataFilePath:j}):Qe[n]={mtime:r}}Je++,Xe+=ce.length}catch(t){throw Error(`Error on page: ${e}\n${t.stack}`)}})}await Ue.start().onIdle(),Re.stop(`success`,`Rendering complete`);let $e=Je+Ye,et=(Xe/1024/1024).toFixed(2);if((0,r.info)(`${r.colors.cyan(String($e).padStart(3,` `))} pages rendered ${r.colors.dim(`(${Je} new, ${Ye} cached, ${et} MB)`)}`),!F)try{if(await o.default.ensureDir((0,a.dirname)(Ze)),await o.default.writeJson(Ze,Qe),o.default.existsSync(X)){let e=await o.default.readdir(X),t=new Set;for(let e of Object.keys(Qe)){let n=c.default.createHash(`md5`).update(e).digest(`hex`);t.add(`${n}.html`),t.add(`${n}.json`)}let n=0;for(let r of e)(r.endsWith(`.html`)||r.endsWith(`.json`))&&(t.has(r)||(await o.default.remove((0,a.join)(X,r)),n++));n>0&&R(`Pruned ${n} obsolete files from SSG cache.`)}}catch{}(0,r.dividerLog)(),R(`Generating static loader data...`,Ke);let tt=JSON.stringify(Ge,null,0);await o.default.writeFile((0,a.join)(z,`static-loader-data-manifest-${B}.json`),tt),(0,r.info)(`${r.colors.dim(`${p}/`)}${r.colors.cyan(`static-loader-data-manifest-${B}.json`.padEnd(15,` `))} ${r.colors.dim(se(tt))}`),await o.default.remove((0,a.join)(f,`.vite-react-ssg-temp`)),we();let nt=u.plugins.find(e=>e.name===`vite-plugin-pwa`)?.api;nt&&!nt.disabled&&nt.generateSW&&(R(`Regenerate PWA...`),await nt.generateSW());let rt=Math.round(performance.now()-g),$=await de(z,rt);fe(z,$);let it=e=>(e/1024).toFixed(0),at=e=>(e/1024/1024).toFixed(1),ot=$.totalJSBundleSize>1024*1024?at($.totalJSBundleSize)+` MB`:it($.totalJSBundleSize)+` kB`,st=$.totalCSSBundleSize>1024*1024?at($.totalCSSBundleSize)+` MB`:it($.totalCSSBundleSize)+` kB`;console.log((0,r.table)([`Metric`,`Result`],[[`Build Time`,`${(rt/1e3).toFixed(1)}s`],[`Pages`,String($.pages.length)],[`JavaScript`,ot],[`CSS`,st]],{style:`round`,headerSeparator:!0})),(0,r.success)(`Build finished.`),await ie?.(p),setTimeout(()=>{(0,r.warn)(`Build process still running after 15s. There might be something misconfigured in your setup. Force exit.`),process.exit(0)},15*1e3).unref()}function be(e,t){return!t||t===`sync`?e:e.replace(/<script type="module" /g,`<script type="module" ${t} `)}async function xe(e,t){if(t===`prettify`)try{let t=(await import(`prettier/esm/standalone.mjs`)).default,n=(await import(`prettier/esm/parser-html.mjs`)).default;return t.format(e,{semi:!1,parser:`html`,plugins:[n]})}catch(t){return(0,r.error)(`Error formatting html: ${t?.message}`),e}return e}function W({template:e,ssrEntry:n,onBeforePageRender:i,entry:a,rootContainerId:o,onPageRendered:c}){return{name:`vite-react-ssg:dev-server`,configureServer(l){let u=async(u,d,f)=>{try{let r=u.originalUrl,f=await(await l.ssrLoadModule(n).then(e=>e.createRoot))(!1,r),p=oe(f),{app:m,base:h}=f,[g,_]=r.split(`?`),v=new URLSearchParams(_);if(!m&&v.has(`_data`))return p.handleLoader(u,d);let y=await l.transformIndexHtml(r,e),b=await i?.(r,y,f)||y,{appHTML:ee,bodyAttributes:x,htmlAttributes:C,metaAttributes:T,styleTag:E}=await p.render(t.o(g,h));T.push(E);let te=await Promise.all([n,a].map(async e=>await l.moduleGraph.getModuleByUrl(e))),D=new Set,ne=new Set,re=async e=>{if(!e||!e?.ssrTransformResult||ne.has(e))return;ne.add(e);let{deps:t=[],dynamicDeps:n=[]}=e?.ssrTransformResult,r=[...t,...n];for(let e of r)if(e.endsWith(`.css`)||e.endsWith(`.scss`)||e.endsWith(`.sass`)||e.endsWith(`.less`))D.add(e);else if(e.endsWith(`.ts`)||e.endsWith(`.tsx`)){let t=await l.moduleGraph.getModuleByUrl(e);t&&await re(t)}};await Promise.all(te.map(async e=>re(e)));let ie=[...D].map(e=>w(t.i(l.config.base,e)));T.push(...ie);let O=await S({rootContainerId:o,appHTML:ee,indexHTML:b,metaAttributes:T,bodyAttributes:x,htmlAttributes:C,initialState:null}),k=await c?.(r,O,f)||O;d.statusCode=200,d.setHeader(`Content-Type`,`text/html`),(0,s.send)(u,d,k,`html`,{headers:`pluginContainer`in l?l.config.server.headers:l.config.preview.headers})}catch(e){l.ssrFixStacktrace(e),(0,r.error)(`SSR render error`,e),d.statusCode=500,d.end(e.stack)}};return()=>{l.middlewares.use(u)}}}}async function G(e={},t={}){try{let n=process.env.NODE_ENV||t.mode||`development`,r=await(0,s.resolveConfig)(e,`serve`,n,n),i=process.cwd(),o=r.root||i,c={...r.ssgOptions,...t},{htmlEntry:l=`index.html`,onBeforePageRender:u,onPageRendered:d,rootContainerId:f=`root`,mock:m=!1}=c,h=c.entry||await C(o,l),[g,_]=await Promise.all([le(r,h),p.default.readFile((0,a.join)(o,l),`utf-8`)]);if(process.env.__DEV_MODE_SSR=`true`,m){let{jsdomGlobal:e}=await Promise.resolve().then(()=>require(`./jsdomGlobal-B4hHTFBO.cjs`));e()}return await(0,s.createServer)({...e,plugins:[...e.plugins??[],W({template:_,ssrEntry:g,onBeforePageRender:u,onPageRendered:d,entry:h,rootContainerId:f})]})}catch(e){throw Error(`[vite-react-ssg] Failed to create dev server: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function K(e={},t={},n){globalThis.__ssr_start_time=performance.now();try{let r=await G(t,e);return await r.listen(),Se(r,!!n),r.bindCLIShortcuts({print:!0}),r}catch(e){(0,r.error)(`failed to start server: ${e?.message??e}`),process.exit(1)}}function Se(e,t=!1){if(t){e.printUrls();return}let n=e.config.logger.info,i=` -- SSR`;if(globalThis.__ssr_start_time){let e=Math.round(performance.now()-globalThis.__ssr_start_time);i+=` ready in ${r.colors.reset(r.colors.bold(`${e}ms`))}`}n(`\n ${r.colors.cyan(` VITE-REACT-SSG v${L} `)}`,{clear:!e.config.logger.hasWarned}),n(`${r.colors.cyan(`\n VITE v${s.version}`)+r.colors.dim(i)}\n`),n(r.colors.green(` dev server running at:`)),e.printUrls()}exports.build=ye,exports.createServer=G,exports.dev=K;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./state-CAM2wH0H.cjs`);let n=require(`react/jsx-runtime`),r=require(`@bdocs/dui`),i=require(`node:module`),a=require(`node:os`);a=e.t(a,1);let o=require(`node:path`);o=e.t(o,1);let s=require(`fs-extra`);s=e.t(s,1);let c=require(`vite`),l=require(`node:crypto`);l=e.t(l,1);let u=require(`node:events`),d=require(`node:stream`),f=require(`react-dom/server`);f=e.t(f);let p=require(`node:fs`);p=e.t(p,1);let m=require(`node:fs/promises`);m=e.t(m,1);const h=/import\("([^)]+)"\)/g;let g=null;async function _(){if(!g){let{matchRoutes:e}=await import(`react-router-dom`);g=e}return g}async function ee({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await _())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(h);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=v(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function v(e,t){let n=new Set;if(!t)return n;for(let r of t)y(e,r,n);return n}function y(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{y(e,t,n)}),n):n}async function te(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function b(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const x=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function S({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${x}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function C(e,t=`index.html`){let[,n]=[...(await s.default.readFile((0,o.join)(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function w(e){return`<link rel="stylesheet" href="${e}">`}function ne(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=T(e);r&&n.push(r)}}),n.join(``)}function T(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function E(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function D(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function re(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;E(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:D(e.headers)};return new Request(n.href,r)}async function ie(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=d.Readable.from(n);r.pipe(t),await(0,u.once)(r,`end`)}else t.end()}function O(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function k(e){return f.renderToString((0,n.jsx)(n.Fragment,{children:e}))}function A(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let j=null;function M(){return j||(j=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=require(`node:module`);return e(require(`url`).pathToFileURL(__filename).href)(`react-helmet-async`).HelmetProvider})(),j)}let N=null;async function ae(){return N||=await import(`react-router-dom`),N}var P=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,n)=>{let{routes:r,base:i}=this.context,{matchRoutes:a}=await ae(),o=re(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=a(t.r([...r],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},i);if(!l){n.statusCode=404,n.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){n.statusCode=404,n.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){n.statusCode=200,n.end(`There is no loader for the route: ${c}`);return}await ie(await F({loader:d,params:u.params,request:o,routeId:c}),n)},this.context=e}async render(e){let{base:r,routes:i,getStyleCollector:a,routerOptions:o}=this.context,s=t.s(e),c=s;if(r!==`/`){let e=t.s(r).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let l=`http://localhost${c}`,u=new Request(l),d=a?await a():null,f={},p=null,{StaticRouterProvider:m,createStaticHandler:h,createStaticRouter:g}=await ae(),_=this._dataRoutes??=t.r([...i],e=>e);this._staticHandler??=h(_,{basename:r});let{query:ee}=this._staticHandler,v=await ee(u),y=0;for(;v instanceof Response&&y<10;){let e=v.headers.get(`Location`);if(!e)break;let n;if(/^https?:\/\//i.test(e))try{let r=new URL(e);if(r.hostname===`localhost`||r.hostname===``)n=`http://localhost${t.s(r.pathname+r.search+r.hash)}`;else break}catch{break}else n=`http://localhost${t.s(e)}`;v=await ee(new Request(n)),y++}if(v instanceof Response)throw v;p=v;let te=g(_,p,{future:o.future}),b=M(),x=b;x&&typeof x==`function`&&(x.canUseDOM=!1);let S=(0,n.jsx)(b,{context:f,children:(0,n.jsx)(m,{router:te,context:p})});d&&(S=d.collect(S));let C=await k(S),{htmlAttributes:w,bodyAttributes:ne,metaAttributes:T,styleTag:E}=A(C,f,d);return{appHTML:C,htmlAttributes:w,bodyAttributes:ne,metaAttributes:T,styleTag:E,routerContext:p}}};async function F({loader:e,params:t,request:n,routeId:r}){let{json:i}=await ae(),a=await e({request:O(L(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return I(a)?a:i(a)}function I(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function L(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function oe(e){return new P(e)}var R=`0.3.1`;async function se(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&B(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function z(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:(0,o.join)(e.root,t))}const ce=/[:*?]/;function B(e){return e?ce.test(e):!1}const V=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),le=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function H(e){try{return p.default.statSync(e).size}catch{return 0}}async function ue(e,t){let n=(0,o.join)(e,`.vite`),r=(0,o.join)(e,`assets`),i={},a=(0,o.join)(n,`manifest.json`);p.default.existsSync(a)&&(i=JSON.parse(await p.default.readFileSync(a,`utf-8`)));let s=0,c=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=H((0,o.join)(e,n));s+=i;for(let t of r)c+=H((0,o.join)(e,t))}let l=0,u=0;if(p.default.existsSync(r)){let e=p.default.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=o.default.extname(t.name).toLowerCase(),n=(0,o.join)(r,t.name);V.has(e)?l+=H(n):le.has(e)&&u++}}let d=(0,o.join)(e,`index.html`),f=0,m=[];if(p.default.existsSync(d)){let e=H(d);f+=e,m.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=p.default.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=H((0,o.join)(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);f+=t,m.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:s,totalCSSBundleSize:c,totalImagesSize:l,totalHTMLSize:f,fontCount:u,pages:m}}function de(e,t){let n=o.default.resolve(e,`..`,`.boltdocs`,`reports`);p.default.existsSync(n)||p.default.mkdirSync(n,{recursive:!0});let r=(0,o.join)(n,`performance.json`);p.default.writeFileSync(r,JSON.stringify(t,null,2))}const fe=Number.parseInt(c.version)>=5?[`.vite`]:[];function pe(e){return Number.parseInt(c.version)>=8?{rolldownOptions:e}:{rollupOptions:e}}const U=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),me=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]);function he(e){let t=[];if(!s.default.existsSync(e))return t;let n=s.default.readdirSync(e,{withFileTypes:!0,recursive:!0});for(let e of n){if(!e.isFile()||e.name.startsWith(`.`))continue;let n=String(e.parentPath??e.path);if(n.split(`/`).slice(-1).some(e=>me.has(e)))continue;let r=`.`+e.name.split(`.`).pop()?.toLowerCase();U.has(r)&&t.push((0,o.join)(n,e.name))}return t}let W=null,G=null;function ge(e,t,n,r){try{let n=[],i=(0,o.join)(e,t);s.default.existsSync(i)&&n.push(...he(i));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=(0,o.join)(e,t);s.default.existsSync(r)&&n.push(r)}n.sort();let a=`${n.length}:${n[0]}:${n[n.length-1]}`;if(W&&G===a)return W;let c=Array(n.length);for(let e=0;e<n.length;e++){let t=s.default.statSync(n[e]);c[e]={file:n[e],mtime:t.mtimeMs,size:t.size}}if(r){let e=(0,o.join)(r,`hash-meta.json`),t=(0,o.join)(r,`client-hash.txt`);try{if(s.default.existsSync(e)&&s.default.existsSync(t)){let r=JSON.parse(s.default.readFileSync(e,`utf-8`)),i=Math.max(...c.map(e=>e.mtime));if(r.fileCount===n.length&&r.lastMtime===i){let e=s.default.readFileSync(t,`utf-8`).trim();if(e)return W=e,G=a,e}}}catch{}}let u=l.default.createHash(`sha256`);for(let{file:t,mtime:n,size:r}of c)u.update((0,o.relative)(e,t).replace(/\\/g,`/`)),u.update(n.toString()),u.update(r.toString());let d=u.digest(`hex`);if(W=d,G=a,r)try{let e=Math.max(...c.map(e=>e.mtime)),t=(0,o.join)(r,`hash-meta.json`);s.default.mkdirSync(r,{recursive:!0}),s.default.writeFileSync(t,JSON.stringify({fileCount:n.length,lastMtime:e}))}catch{}return d}catch{return Math.random().toString(36).substring(2,12)}}function _e(e,n){return`static-loader-data${t.s(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${n}.json`}function ve(e,n=`/`){let r=t.s(e),i=r;if(n!==`/`){let e=t.s(n).replace(/\/$/,``);!r.startsWith(e+`/`)&&r!==e&&(i=`${e}${r}`)}return i!==`/`&&i.endsWith(`/`)?i.slice(0,-1):i}function ye(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function K(e={},n={}){let u=process.env.MODE||process.env.NODE_ENV||e.mode||`production`;u!==process.env.NODE_ENV&&(process.env.NODE_ENV=u);let d=await(0,c.resolveConfig)(n,`build`,u,u),f=process.cwd(),p=d.root||f,m=d.build.outDir||`dist`,h=d.base,g=Object.assign({},d.ssgOptions||{},e),_=performance.now(),{script:v=`sync`,mock:y=!1,htmlEntry:w=`index.html`,entry:T=await C(p,w),formatting:E=`none`,includedRoutes:D=ye,onBeforePageRender:re,onPageRendered:ie,onFinished:O,onStep:k,dirStyle:A=`flat`,includeAllRoutes:j=!1,format:M=`esm`,concurrency:N=20,rootContainerId:ae=`root`,routeToSourceFileMap:P={},cacheDir:F=`.boltdocs/build`}=g,I=g.beastiesOptions??{},L=g.turbo??!1,R=`docs`,ce=Object.values(P);if(ce.length>0){let e=ce[0],t=(0,o.relative)(p,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(R=t[0])}let B=(0,o.isAbsolute)(m)?m:(0,o.join)(p,m),V=(0,o.isAbsolute)(F)?F:(0,o.join)(p,F),le=ge(p,R,m,V),H=le.substring(0,12),U=(0,o.join)(V,`ssr`,L?`turbo-ssr`:H),me=(0,o.join)(V,`client-hash.txt`),he=(0,o.join)(V,`template-index.html`),W=!1;try{s.default.existsSync(me)&&s.default.existsSync(he)&&s.default.existsSync(B)&&s.default.existsSync((0,o.join)(B,`assets`))&&(await s.default.readFile(me,`utf-8`)).trim()===le&&(W=!0)}catch{}function G(e){return e.startsWith(`dist/`)||e.startsWith(`.boltdocs/build/ssr/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=(0,c.createLogger)(),Se=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||G(e)||Se(e,t)};let Ce=K.info;if(K.info=(e,t)=>{G(e)||Ce(e,t)},W)k?.({name:`Client build`,duration:0,success:!0,details:`Code unchanged, skipped`}),await s.default.ensureDir(B),await s.default.copy(he,(0,o.join)(B,w));else{let e=performance.now();await(0,c.build)((0,c.mergeConfig)(n,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...pe({input:{app:(0,o.join)(p,w||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:d.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){m=e.build.outDir||`dist`}}]})),k?.({name:`Client build`,duration:performance.now()-e,success:!0,details:`Vite production build`}),await s.default.ensureDir(V),await s.default.copy((0,o.join)(B,w),he),await s.default.writeFile(me,le,`utf-8`)}let we=()=>{};if(y){let{jsdomGlobal:e}=await Promise.resolve().then(()=>require(`./jsdomGlobal-B4hHTFBO.cjs`));we=e()}let q=await z(d,T);if((L||W)&&s.default.existsSync(U)&&s.default.readdirSync(U).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0)k?.({name:`Server build`,duration:0,success:!0,details:`SSR bundle unchanged, skipped`});else{s.default.existsSync(U)&&await s.default.remove(U),process.env.VITE_SSG=`true`;let e=performance.now();await(0,c.build)((0,c.mergeConfig)(n,{logLevel:`warn`,build:{ssr:q,manifest:!0,outDir:U,minify:!1,cssCodeSplit:!1,...pe({output:M===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:d.mode})),k?.({name:`Server build`,duration:performance.now()-e,success:!0,details:`Vite SSR bundle`})}let Te=M===`esm`&&process.platform===`win32`?`file://`:``,Ee=M===`esm`?`.mjs`:`.cjs`,De=q.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),Oe=Te+(0,o.join)(U,(q.includes(`/`)||q.includes(`\\`)?q.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(Ee,``):De)+Ee).replace(/\\/g,`/`),ke=JSON.parse(await s.default.readFile((0,o.join)(U,...fe,`manifest.json`),`utf-8`)),Ae=typeof require<`u`?require:(0,i.createRequire)(require(`url`).pathToFileURL(__filename).href),{createRoot:je,includedRoutes:Me}=M===`esm`?await import(Oe):Ae(Oe),Ne=Me||D,{routes:Pe}=await je(!1),{paths:Fe}=await se(Pe),J=j?Fe:await Ne(Fe,Pe||[]);J=ye(J,Pe||[]),J=Array.from(new Set(J));let Y;L&&(Y=await b(),Y||(0,r.warn)(`[zig-critters] WASM unavailable; falling back to beasties for critical CSS`));let Ie=I!==!1&&!Y?await te(m,{publicPath:h,...I}):void 0,Le=``;if(Y){let e=(0,o.join)(B,`assets`);if(s.default.existsSync(e)){let t=s.default.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Le+=s.default.readFileSync((0,o.join)(e,n),`utf-8`)+`
2
+ `}}let Re=performance.now(),ze=JSON.parse(await s.default.readFile((0,o.join)(B,...fe,`ssr-manifest.json`),`utf-8`)),Be=JSON.parse(await s.default.readFile((0,o.join)(B,...fe,`manifest.json`),`utf-8`)),Ve=await s.default.readFile((0,o.join)(B,w),`utf-8`);s.default.rmSync((0,o.join)(B,w)),Ve=be(Ve,v);let He=(await import(`p-queue`)).default||await import(`p-queue`),Ue=new He({concurrency:N}),We=new He({concurrency:Math.min(a.default.cpus().length,4)}),Ge={},Ke=0,qe=new Map,Je=0,Ye=0,Xe=0,Ze=(0,o.join)(V,`ssg-cache.json`),X=(0,o.join)(V,`ssg-pages`),Z={};if(!L)try{s.default.existsSync(Ze)&&(Z=await s.default.readJson(Ze))}catch{}let Qe={...Z},Q=new Set;Q.add(X);for(let e of J){let t=A===`nested`?(0,o.join)(e.replace(/^\//g,``),`index.html`):`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`;Q.add((0,o.join)(B,(0,o.dirname)(t)));let n=e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e;Q.add((0,o.join)(B,`static-loader-data`,(0,o.dirname)(n)))}Q.add((0,o.join)(B,`static-loader-data`)),await Promise.all([...Q].map(e=>s.default.ensureDir(e)));for(let e of J){let n=l.default.createHash(`md5`).update(e).digest(`hex`),i=(0,o.join)(X,`${n}.html`),a=(0,o.join)(X,`${n}.json`),c=`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`,u=A===`nested`?(0,o.join)(e.replace(/^\//g,``),`index.html`):c,d=(0,o.join)(B,u),f=t.s(e).replace(/\/$/,``),p=P[f]||P[e],m=!1,g=0;if(!L&&W&&p&&s.default.existsSync(p))try{if(g=Math.round(s.default.statSync(p).mtimeMs),s.default.existsSync(i)){let t=Z[f]||Z[e];t&&Math.round(t.mtime)===g&&(m=!0)}}catch{}if(m){Ue.add(async()=>{try{if(W)await s.default.copy(i,d);else{let e=await s.default.readFile(i,`utf-8`);e=e.replace(/window\.__VITE_REACT_SSG_HASH__\s*=\s*'[^']*'/,`window.__VITE_REACT_SSG_HASH__ = '${H}'`),await s.default.writeFile(d,e,`utf-8`)}let t=Z[f]||Z[e];if(t?.loaderDataFilePath&&s.default.existsSync(a)){let n=W?t.loaderDataFilePath:_e(e,H);await s.default.copy(a,(0,o.join)(B,n)),Ge[ve(e,h)]=n,Ke++}Ye++}catch(t){throw Error(`Error on cached page: ${e}\n${t.stack}`)}});continue}Ue.add(async()=>{try{let n=await je(!1,e),{base:c,routes:l,triggerOnSSRAppRendered:d,transformState:f=t.n,app:m,routerType:_}=n,v=await re?.(e,Ve,n)||Ve,y=`${t.c(c)}${t.a(e)}`,te=oe(n),b;if(!m&&_===`remix`){let t=qe.get(e);t?b=t:(b=await ee({routes:[...l],locationArg:y,base:c,serverManifest:ke,manifest:Be,ssrManifest:ze}),qe.set(e,b))}else b=new Set;let{appHTML:C,bodyAttributes:w,htmlAttributes:T,metaAttributes:D,styleTag:O,routerContext:k}=await te.render(e),A=k?.loaderData,j;if(A&&Object.keys(A).length>0){let t=_e(e,H);j=t,await s.default.writeFile((0,o.join)(B,t),JSON.stringify(A)),Ge[ve(e,h)]=t,Ke++}await d?.(e,C,n);let M=await S({rootContainerId:ae,appHTML:C,indexHTML:v,metaAttributes:D,bodyAttributes:w,htmlAttributes:T,initialState:null}),N=ne(b),P=M.replace(/<script[^>]*>(?:(?!<\/script>)[\s\S])*__staticRouterHydrationData(?:(?!<\/script>)[\s\S])*<\/script>/g,``);N&&(P=P.replace(`<head>`,`<head>${N}`));let F=await ie?.(e,P,n)||P,I=``;if(A&&Object.keys(A).length>0){let t=JSON.stringify(A).replace(/</g,`\\u003c`);I=`window.__VITE_REACT_SSG_STATIC_LOADER_DATA__ = { '${ve(e,h)}': ${t} };`}let R=``;if(k){let e={loaderData:k.loaderData??{},actionData:k.actionData??null,errors:k.errors??null};R=`window.__staticRouterHydrationData = ${JSON.stringify(e).replace(/</g,`\\u003c`)};`}let se=`<script>window.__VITE_REACT_SSG_HASH__ = '${H}';${I}${R}<\/script>`;if(F=F.replace(`<head>`,`<head>${se}`),F=F.replace(`<script>${x}<\/script>`,``),Y){try{Le&&(F=await Y.processHtml(F,Le))}catch(t){(0,r.warn)(`[zig-critters] Failed to inline CSS for "${e}": ${t instanceof Error?t.message:String(t)}`)}F=F.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`)}else Ie&&(F=await We.add(()=>Ie.process(F)),F=F.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`));O&&(F=F.replace(`<head>`,`<head>${O}`));let z=await xe(F,E);if(await s.default.writeFile((0,o.join)(B,u),z,`utf-8`),!L&&p&&s.default.existsSync(p)){await s.default.writeFile(i,z,`utf-8`);let n=t.s(e).replace(/\/$/,``),r=Math.round(g);A&&Object.keys(A).length>0&&j?(await s.default.writeFile(a,JSON.stringify(A),`utf-8`),Qe[n]={mtime:r,loaderDataFilePath:j}):Qe[n]={mtime:r}}Je++,Xe+=z.length}catch(t){throw Error(`Error on page: ${e}\n${t.stack}`)}})}await Ue.start().onIdle();let $e=Je+Ye,et=(Xe/1024/1024).toFixed(2),tt=0;if(!L)try{if(await s.default.ensureDir((0,o.dirname)(Ze)),await s.default.writeJson(Ze,Qe),s.default.existsSync(X)){let e=await s.default.readdir(X),t=new Set;for(let e of Object.keys(Qe)){let n=l.default.createHash(`md5`).update(e).digest(`hex`);t.add(`${n}.html`),t.add(`${n}.json`)}for(let n of e)(n.endsWith(`.html`)||n.endsWith(`.json`))&&(t.has(n)||(await s.default.remove((0,o.join)(X,n)),tt++))}}catch{}k?.({name:`Render pages`,duration:performance.now()-Re,success:!0,details:`${$e} pages (${Je} new, ${Ye} cached, ${et} MB)`,metrics:{renderedCount:Je,cachedCount:Ye,renderedSize:Xe,totalPages:$e,prunedCount:tt}});let nt=performance.now(),rt=JSON.stringify(Ge,null,0);await s.default.writeFile((0,o.join)(B,`static-loader-data-manifest-${H}.json`),rt),W||await s.default.remove((0,o.join)(V,`ssr`)),we();let it=d.plugins.find(e=>e.name===`vite-plugin-pwa`)?.api;it&&!it.disabled&&it.generateSW&&await it.generateSW();let at=Math.round(performance.now()-_),$=await ue(B,at);de(B,$),k?.({name:`Static loader data`,duration:performance.now()-nt,success:!0,details:`${Ke} loader data files`,metrics:{loaderDataFileCount:Ke}}),k?.({name:`Build metrics`,duration:0,success:!0,details:`Build time: ${(at/1e3).toFixed(1)}s, JS: ${($.totalJSBundleSize/1024).toFixed(0)} kB, CSS: ${($.totalCSSBundleSize/1024).toFixed(0)} kB`,metrics:{buildTime:at,totalPages:$.pages.length,jsSize:$.totalJSBundleSize,cssSize:$.totalCSSBundleSize}}),await O?.(m),setTimeout(()=>{(0,r.warn)(`Build process still running after 15s. There might be something misconfigured in your setup. Force exit.`),process.exit(0)},15*1e3).unref()}function be(e,t){return!t||t===`sync`?e:e.replace(/<script type="module" /g,`<script type="module" ${t} `)}async function xe(e,t){if(t===`prettify`)try{let t=(await import(`prettier/esm/standalone.mjs`)).default,n=(await import(`prettier/esm/parser-html.mjs`)).default;return t.format(e,{semi:!1,parser:`html`,plugins:[n]})}catch(t){return(0,r.error)(`Error formatting html: ${t?.message}`),e}return e}function Se(e,t,n){if(e.url)try{let t=e.url,n=t.indexOf(`?`),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n):``;if(/%[0-9A-Fa-f]{2}/.test(r)){let t=decodeURI(r);if(t!==r){let n=t+i;e.url=n,e.originalUrl&&=n}}}catch{}n()}function Ce({template:e,ssrEntry:n,onBeforePageRender:i,entry:a,rootContainerId:o,onPageRendered:s}){return{name:`vite-react-ssg:dev-server`,configureServer(l){let u=async(u,d,f)=>{try{let r=u.originalUrl,f=await(await l.ssrLoadModule(n).then(e=>e.createRoot))(!1,r),p=oe(f),{app:m,base:h}=f,[g,_]=r.split(`?`),ee=new URLSearchParams(_);if(!m&&ee.has(`_data`))return p.handleLoader(u,d);let v=await l.transformIndexHtml(r,e),y=await i?.(r,v,f)||v,{appHTML:te,bodyAttributes:b,htmlAttributes:x,metaAttributes:C,styleTag:ne}=await p.render(t.o(g,h));C.push(ne);let T=await Promise.all([n,a].map(async e=>await l.moduleGraph.getModuleByUrl(e))),E=new Set,D=new Set,re=async e=>{if(!e||!e?.ssrTransformResult||D.has(e))return;D.add(e);let{deps:t=[],dynamicDeps:n=[]}=e?.ssrTransformResult,r=[...t,...n];for(let e of r)if(e.endsWith(`.css`)||e.endsWith(`.scss`)||e.endsWith(`.sass`)||e.endsWith(`.less`))E.add(e);else if(e.endsWith(`.ts`)||e.endsWith(`.tsx`)){let t=await l.moduleGraph.getModuleByUrl(e);t&&await re(t)}};await Promise.all(T.map(async e=>re(e)));let ie=[...E].map(e=>w(t.i(l.config.base,e)));C.push(...ie);let O=await S({rootContainerId:o,appHTML:te,indexHTML:y,metaAttributes:C,bodyAttributes:b,htmlAttributes:x,initialState:null}),k=await s?.(r,O,f)||O;d.statusCode=200,d.setHeader(`Content-Type`,`text/html`),(0,c.send)(u,d,k,`html`,{headers:`pluginContainer`in l?l.config.server.headers:l.config.preview.headers})}catch(e){l.ssrFixStacktrace(e),(0,r.error)(`SSR render error`,e),d.statusCode=500,d.end(e.stack)}};return l.middlewares.use(Se),()=>{l.middlewares.use(u)}}}}async function we(e={},t={}){try{let n=process.env.NODE_ENV||t.mode||`development`,r=await(0,c.resolveConfig)(e,`serve`,n,n),i=process.cwd(),a=r.root||i,s={...r.ssgOptions,...t},{htmlEntry:l=`index.html`,onBeforePageRender:u,onPageRendered:d,rootContainerId:f=`root`,mock:p=!1}=s,h=s.entry||await C(a,l),[g,_]=await Promise.all([z(r,h),m.default.readFile((0,o.join)(a,l),`utf-8`)]);if(process.env.__DEV_MODE_SSR=`true`,p){let{jsdomGlobal:e}=await Promise.resolve().then(()=>require(`./jsdomGlobal-B4hHTFBO.cjs`));e()}return await(0,c.createServer)({...e,plugins:[...e.plugins??[],Ce({template:_,ssrEntry:g,onBeforePageRender:u,onPageRendered:d,entry:h,rootContainerId:f})]})}catch(e){throw Error(`[vite-react-ssg] Failed to create dev server: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function q(e={},t={},n){globalThis.__ssr_start_time=performance.now();try{let r=await we(t,e);return await r.listen(),Te(r,!!n),r.bindCLIShortcuts({print:!0}),r}catch(e){(0,r.error)(`failed to start server: ${e?.message??e}`),process.exit(1)}}function Te(e,t=!1){if(t){e.printUrls();return}let n=e.config.logger.info,i=` -- SSR`;if(globalThis.__ssr_start_time){let e=Math.round(performance.now()-globalThis.__ssr_start_time);i+=` ready in ${r.colors.reset(r.colors.bold(`${e}ms`))}`}n(`\n ${r.colors.cyan(` VITE-REACT-SSG v${R} `)}`,{clear:!e.config.logger.hasWarned}),n(`${r.colors.cyan(`\n VITE v${c.version}`)+r.colors.dim(i)}\n`),n(r.colors.green(` dev server running at:`)),e.printUrls()}exports.build=K,exports.createServer=we,exports.dev=q;
package/dist/node.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { l as ViteReactSSGOptions } from "./types-DnC0a9DP.cjs";
1
+ import { l as ViteReactSSGOptions } from "./types-BMIDte34.cjs";
2
2
  import { InlineConfig, ViteDevServer } from "vite";
3
3
 
4
4
  //#region src/node/build.d.ts
package/dist/node.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { l as ViteReactSSGOptions } from "./types-BC2n-pCm.mjs";
1
+ import { l as ViteReactSSGOptions } from "./types-DefKqSqW.mjs";
2
2
  import { InlineConfig, ViteDevServer } from "vite";
3
3
 
4
4
  //#region src/node/build.d.ts
package/dist/node.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{a as e,c as t,i as n,n as r,o as i,r as a,s as o}from"./state-CkhLd6hN.mjs";import{createRequire as s}from"node:module";import{Fragment as c,jsx as l}from"react/jsx-runtime";import{colors as u,createSpinner as d,dividerLog as f,error as p,info as m,success as h,table as g,warn as _}from"@bdocs/dui";import v,{dirname as y,isAbsolute as b,join as x,relative as S}from"node:path";import C from"fs-extra";import{build as w,createLogger as T,createServer as E,mergeConfig as D,resolveConfig as O,send as k,version as A}from"vite";import j from"node:crypto";import{once as M}from"node:events";import{Readable as ee}from"node:stream";import*as N from"react-dom/server";import P from"node:fs";import te from"node:fs/promises";var F=s(import.meta.url);const ne=/import\("([^)]+)"\)/g;let re=null;async function ie(){if(!re){let{matchRoutes:e}=await import(`react-router-dom`);re=e}return re}async function ae({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await ie())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(ne);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=oe(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function oe(e,t){let n=new Set;if(!t)return n;for(let r of t)se(e,r,n);return n}function se(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{se(e,t,n)}),n):n}async function ce(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function le(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const ue=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function de({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${ue}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function fe(e,t=`index.html`){let[,n]=[...(await C.readFile(x(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function pe(e){return`<link rel="stylesheet" href="${e}">`}function me(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=he(e);r&&n.push(r)}}),n.join(``)}function he(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function ge(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function _e(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function ve(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;ge(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:_e(e.headers)};return new Request(n.href,r)}async function ye(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=ee.from(n);r.pipe(t),await M(r,`end`)}else t.end()}function be(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function I(e){return N.renderToString(l(c,{children:e}))}function xe(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let L=null;function R(){return L||(L=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=F(`node:module`);return e(import.meta.url)(`react-helmet-async`).HelmetProvider})(),L)}let z=null;async function B(){return z||=await import(`react-router-dom`),z}var V=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,t)=>{let{routes:n,base:r}=this.context,{matchRoutes:i}=await B(),o=ve(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=i(a([...n],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},r);if(!l){t.statusCode=404,t.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){t.statusCode=404,t.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){t.statusCode=200,t.end(`There is no loader for the route: ${c}`);return}await ye(await H({loader:d,params:u.params,request:o,routeId:c}),t)},this.context=e}async render(e){let{base:t,routes:n,getStyleCollector:r,routerOptions:i}=this.context,s=o(e),c=s;if(t!==`/`){let e=o(t).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let u=`http://localhost${c}`,d=new Request(u),f=r?await r():null,p={},m=null,{StaticRouterProvider:h,createStaticHandler:g,createStaticRouter:_}=await B(),v=this._dataRoutes??=a([...n],e=>e);this._staticHandler??=g(v,{basename:t});let{query:y}=this._staticHandler,b=await y(d),x=0;for(;b instanceof Response&&x<10;){let e=b.headers.get(`Location`);if(!e)break;let t;if(/^https?:\/\//i.test(e))try{let n=new URL(e);if(n.hostname===`localhost`||n.hostname===``)t=`http://localhost${o(n.pathname+n.search+n.hash)}`;else break}catch{break}else t=`http://localhost${o(e)}`;b=await y(new Request(t)),x++}if(b instanceof Response)throw b;m=b;let S=_(v,m,{future:i.future}),C=R(),w=C;w&&typeof w==`function`&&(w.canUseDOM=!1);let T=l(C,{context:p,children:l(h,{router:S,context:m})});f&&(T=f.collect(T));let E=await I(T),{htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A}=xe(E,p,f);return{appHTML:E,htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A,routerContext:m}}};async function H({loader:e,params:t,request:n,routeId:r}){let{json:i}=await B(),a=await e({request:be(Ce(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return Se(a)?a:i(a)}function Se(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function Ce(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function we(e){return new V(e)}var U=`0.2.0`;function W(e,t){m(`${e}${t?u.blue(` (${t})`):``}`)}function Te(e){return`${(e.length/1024).toFixed(2)} KiB`}async function Ee(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&K(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function De(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:x(e.root,t))}const G=/[:*?]/;function K(e){return e?G.test(e):!1}const Oe=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),ke=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function q(e){try{return P.statSync(e).size}catch{return 0}}async function Ae(e,t){let n=x(e,`.vite`),r=x(e,`assets`),i={},a=x(n,`manifest.json`);P.existsSync(a)&&(i=JSON.parse(await P.readFileSync(a,`utf-8`)));let o=0,s=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=q(x(e,n));o+=i;for(let t of r)s+=q(x(e,t))}let c=0,l=0;if(P.existsSync(r)){let e=P.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=v.extname(t.name).toLowerCase(),n=x(r,t.name);Oe.has(e)?c+=q(n):ke.has(e)&&l++}}let u=x(e,`index.html`),d=0,f=[];if(P.existsSync(u)){let e=q(u);d+=e,f.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=P.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=q(x(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);d+=t,f.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:o,totalCSSBundleSize:s,totalImagesSize:c,totalHTMLSize:d,fontCount:l,pages:f}}function je(e,t){let n=v.resolve(e,`..`,`.boltdocs`,`reports`);P.existsSync(n)||P.mkdirSync(n,{recursive:!0});let r=x(n,`performance.json`);P.writeFileSync(r,JSON.stringify(t,null,2))}const Me=Number.parseInt(A)>=5?[`.vite`]:[];function Ne(e){return Number.parseInt(A)>=8?{rolldownOptions:e}:{rollupOptions:e}}function J(e){let t=[];if(!C.existsSync(e))return t;let n=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),r=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]),i=C.readdirSync(e,{withFileTypes:!0});for(let a of i){if(a.name.startsWith(`.`)||r.has(a.name))continue;let i=x(e,a.name);if(a.isDirectory())t.push(...J(i));else{let e=`.`+a.name.split(`.`).pop()?.toLowerCase();n.has(e)&&t.push(i)}}return t}function Pe(e,t,n){try{let n=[],r=x(e,t);C.existsSync(r)&&n.push(...J(r));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=x(e,t);C.existsSync(r)&&n.push(r)}n.sort();let i=j.createHash(`sha256`);for(let t of n){let n=C.statSync(t),r=S(e,t).replace(/\\/g,`/`);i.update(r),i.update(n.mtimeMs.toString()),i.update(n.size.toString())}return i.digest(`hex`)}catch{return Math.random().toString(36).substring(2,12)}}function Fe(e,t){return`static-loader-data${o(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${t}.json`}function Ie(e,t=`/`){let n=o(e),r=n;if(t!==`/`){let e=o(t).replace(/\/$/,``);!n.startsWith(e+`/`)&&n!==e&&(r=`${e}${n}`)}return r!==`/`&&r.endsWith(`/`)?r.slice(0,-1):r}function Le(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function Re(n={},i={}){let a=process.env.MODE||process.env.NODE_ENV||n.mode||`production`,c=await O(i,`build`,a,a),l=process.cwd(),p=c.root||l,v=c.build.outDir||`dist`,E=c.base,k=Object.assign({},c.ssgOptions||{},n),A=performance.now(),{script:M=`sync`,mock:ee=!1,htmlEntry:N=`index.html`,entry:P=await fe(p,N),formatting:te=`none`,includedRoutes:ne=Le,onBeforePageRender:re,onPageRendered:ie,onFinished:oe,dirStyle:se=`flat`,includeAllRoutes:pe=!1,format:he=`esm`,concurrency:ge=20,rootContainerId:_e=`root`,routeToSourceFileMap:ve={},cacheDir:ye=`.boltdocs/build`}=k,be=k.beastiesOptions??{},I=k.turbo??!1,xe=`docs`,L=Object.values(ve);if(L.length>0){let e=L[0],t=S(p,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(xe=t[0])}let R=b(v)?v:x(p,v),z=Pe(p,xe,v),B=z.substring(0,12),V=x(p,`.vite-react-ssg-temp`,I?`turbo-ssr`:B),H=b(ye)?ye:x(p,ye),Se=x(H,`client-hash.txt`),Ce=x(H,`template-index.html`),U=!1;try{C.existsSync(Se)&&C.existsSync(Ce)&&C.existsSync(R)&&C.existsSync(x(R,`assets`))&&(await C.readFile(Se,`utf-8`)).trim()===z&&(U=!0)}catch{}function G(e){return e.startsWith(`dist/`)||e.startsWith(`.vite-react-ssg-temp/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=T(),Oe=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||G(e)||Oe(e,t)};let ke=K.info;K.info=(e,t)=>{G(e)||ke(e,t)},U?(W(`Client code unchanged. Bypassing client build...`),await C.ensureDir(R),await C.copy(Ce,x(R,N))):(f(),W(`Build for client...`),await w(D(i,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...Ne({input:{app:x(p,N||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:c.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){v=e.build.outDir||`dist`}}]})),h(`Client build complete`),await C.ensureDir(H),await C.copy(x(R,N),Ce),await C.writeFile(Se,z,`utf-8`)),f();let q=()=>{};if(ee){let{jsdomGlobal:e}=await import(`./jsdomGlobal-u0wZKDvc.mjs`);q=e()}let J=await De(c,P);(I||U)&&C.existsSync(V)&&C.readdirSync(V).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0?W(`Server build unchanged. Bypassing server build...`):(C.existsSync(V)&&await C.remove(V),W(`Build for server...`),process.env.VITE_SSG=`true`,await w(D(i,{logLevel:`warn`,build:{ssr:J,manifest:!0,outDir:V,minify:!1,cssCodeSplit:!1,...Ne({output:he===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||G(t.message)||n(e,t)}})},customLogger:K,mode:c.mode})),h(`Server build complete`));let Re=he===`esm`&&process.platform===`win32`?`file://`:``,Ve=he===`esm`?`.mjs`:`.cjs`,He=J.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),Ue=Re+x(V,(J.includes(`/`)||J.includes(`\\`)?J.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(Ve,``):He)+Ve).replace(/\\/g,`/`),We=JSON.parse(await C.readFile(x(V,...Me,`manifest.json`),`utf-8`)),Ge=F===void 0?s(import.meta.url):F,{createRoot:Ke,includedRoutes:qe}=he===`esm`?await import(Ue):Ge(Ue),Je=qe||ne,{routes:Ye}=await Ke(!1),{paths:Xe}=await Ee(Ye),Y=pe?Xe:await Je(Xe,Ye||[]);Y=Le(Y,Ye||[]),Y=Array.from(new Set(Y)),f(),W(`Rendering Pages...`,Y.length);let Ze=be!==!1&&!I?await ce(v,{publicPath:E,...be}):void 0,X;I&&(X=await le(),X?m("Critical CSS generation enabled via `zig-critters` (turbo)"):_(`zig-critters not available, falling back to beasties`)),Ze&&!X&&m("Critical CSS generation enabled via `beasties`");let Qe=``;if(X){let e=x(R,`assets`);if(C.existsSync(e)){let t=C.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Qe+=C.readFileSync(x(e,n),`utf-8`)+`
2
- `}}let $e=d(`Rendering pages...`);$e.start();let et=JSON.parse(await C.readFile(x(R,...Me,`ssr-manifest.json`),`utf-8`)),tt=JSON.parse(await C.readFile(x(R,...Me,`manifest.json`),`utf-8`)),nt=await C.readFile(x(R,N),`utf-8`);C.rmSync(x(R,N)),nt=ze(nt,M);let rt=(await import(`p-queue`)).default||await import(`p-queue`),it=new rt({concurrency:ge}),at=new rt({concurrency:1}),ot={},st=0,ct=new Map,lt=0,ut=0,dt=0,ft=x(H,`ssg-cache.json`),Z=x(H,`ssg-pages`),Q={};if(!I)try{C.existsSync(ft)&&(Q=await C.readJson(ft))}catch{}let pt={...Q},mt=new Set;mt.add(Z);for(let e of Y){let t=se===`nested`?x(e.replace(/^\//g,``),`index.html`):`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`;mt.add(x(R,y(t)));let n=e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e;mt.add(x(R,`static-loader-data`,y(n)))}mt.add(x(R,`static-loader-data`)),await Promise.all([...mt].map(e=>C.ensureDir(e)));for(let n of Y){let i=j.createHash(`md5`).update(n).digest(`hex`),a=x(Z,`${i}.html`),s=x(Z,`${i}.json`),c=`${(n.endsWith(`/`)?`${n}index`:n).replace(/^\//g,``)}.html`,l=se===`nested`?x(n.replace(/^\//g,``),`index.html`):c,u=x(R,l),d=o(n).replace(/\/$/,``),f=ve[d]||ve[n],p=!1,m=0;if(!I&&U&&f&&C.existsSync(f))try{if(m=Math.round(C.statSync(f).mtimeMs),C.existsSync(a)){let e=Q[d]||Q[n];e&&Math.round(e.mtime)===m&&(p=!0)}}catch{}if(p){it.add(async()=>{try{if(U)await C.copy(a,u);else{let e=await C.readFile(a,`utf-8`);e=e.replace(/window\.__VITE_REACT_SSG_HASH__\s*=\s*'[^']*'/,`window.__VITE_REACT_SSG_HASH__ = '${B}'`),await C.writeFile(u,e,`utf-8`)}let e=Q[d]||Q[n];if(e?.loaderDataFilePath&&C.existsSync(s)){let t=U?e.loaderDataFilePath:Fe(n,B);await C.copy(s,x(R,t)),ot[Ie(n,E)]=t,st++}ut++}catch(e){throw Error(`Error on cached page: ${n}\n${e.stack}`)}});continue}it.add(async()=>{try{let i=await Ke(!1,n),{base:c,routes:u,triggerOnSSRAppRendered:d,transformState:p=r,app:h,routerType:g}=i,v=await re?.(n,nt,i)||nt,y=`${t(c)}${e(n)}`,b=we(i),S;if(!h&&g===`remix`){let e=ct.get(n);e?S=e:(S=await ae({routes:[...u],locationArg:y,base:c,serverManifest:We,manifest:tt,ssrManifest:et}),ct.set(n,S))}else S=new Set;let{appHTML:w,bodyAttributes:T,htmlAttributes:D,metaAttributes:O,styleTag:k,routerContext:A}=await b.render(n),j=A?.loaderData,M;if(j&&Object.keys(j).length>0){let e=Fe(n,B);M=e,await C.writeFile(x(R,e),JSON.stringify(j)),ot[Ie(n,E)]=e,st++}await d?.(n,w,i);let ee=await de({rootContainerId:_e,appHTML:w,indexHTML:v,metaAttributes:O,bodyAttributes:T,htmlAttributes:D,initialState:null}),N=me(S),P=ee.replace(/<script[^>]*>(?:(?!<\/script>)[\s\S])*__staticRouterHydrationData(?:(?!<\/script>)[\s\S])*<\/script>/g,``);N&&(P=P.replace(`<head>`,`<head>${N}`));let F=await ie?.(n,P,i)||P,ne=``;if(j&&Object.keys(j).length>0){let e=JSON.stringify(j).replace(/</g,`\\u003c`);ne=`window.__VITE_REACT_SSG_STATIC_LOADER_DATA__ = { '${Ie(n,E)}': ${e} };`}let oe=``;if(A){let e={loaderData:A.loaderData??{},actionData:A.actionData??null,errors:A.errors??null};oe=`window.__staticRouterHydrationData = ${JSON.stringify(e).replace(/</g,`\\u003c`)};`}let se=`<script>window.__VITE_REACT_SSG_HASH__ = '${B}';${ne}${oe}<\/script>`;if(F=F.replace(`<head>`,`<head>${se}`),F=F.replace(`<script>${ue}<\/script>`,``),X){try{Qe&&(F=await X.processHtml(F,Qe))}catch(e){_(`[zig-critters] Failed to inline CSS for "${n}": ${e instanceof Error?e.message:String(e)}`)}F=F.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`)}else Ze&&(F=await at.add(()=>Ze.process(F)),F=F.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`));k&&(F=F.replace(`<head>`,`<head>${k}`));let ce=await Be(F,te);if(await C.writeFile(x(R,l),ce,`utf-8`),!I&&f&&C.existsSync(f)){await C.writeFile(a,ce,`utf-8`);let e=o(n).replace(/\/$/,``),t=Math.round(m);j&&Object.keys(j).length>0&&M?(await C.writeFile(s,JSON.stringify(j),`utf-8`),pt[e]={mtime:t,loaderDataFilePath:M}):pt[e]={mtime:t}}lt++,dt+=ce.length}catch(e){throw Error(`Error on page: ${n}\n${e.stack}`)}})}await it.start().onIdle(),$e.stop(`success`,`Rendering complete`);let ht=lt+ut,gt=(dt/1024/1024).toFixed(2);if(m(`${u.cyan(String(ht).padStart(3,` `))} pages rendered ${u.dim(`(${lt} new, ${ut} cached, ${gt} MB)`)}`),!I)try{if(await C.ensureDir(y(ft)),await C.writeJson(ft,pt),C.existsSync(Z)){let e=await C.readdir(Z),t=new Set;for(let e of Object.keys(pt)){let n=j.createHash(`md5`).update(e).digest(`hex`);t.add(`${n}.html`),t.add(`${n}.json`)}let n=0;for(let r of e)(r.endsWith(`.html`)||r.endsWith(`.json`))&&(t.has(r)||(await C.remove(x(Z,r)),n++));n>0&&W(`Pruned ${n} obsolete files from SSG cache.`)}}catch{}f(),W(`Generating static loader data...`,st);let _t=JSON.stringify(ot,null,0);await C.writeFile(x(R,`static-loader-data-manifest-${B}.json`),_t),m(`${u.dim(`${v}/`)}${u.cyan(`static-loader-data-manifest-${B}.json`.padEnd(15,` `))} ${u.dim(Te(_t))}`),await C.remove(x(p,`.vite-react-ssg-temp`)),q();let vt=c.plugins.find(e=>e.name===`vite-plugin-pwa`)?.api;vt&&!vt.disabled&&vt.generateSW&&(W(`Regenerate PWA...`),await vt.generateSW());let yt=Math.round(performance.now()-A),$=await Ae(R,yt);je(R,$);let bt=e=>(e/1024).toFixed(0),xt=e=>(e/1024/1024).toFixed(1),St=$.totalJSBundleSize>1024*1024?xt($.totalJSBundleSize)+` MB`:bt($.totalJSBundleSize)+` kB`,Ct=$.totalCSSBundleSize>1024*1024?xt($.totalCSSBundleSize)+` MB`:bt($.totalCSSBundleSize)+` kB`;console.log(g([`Metric`,`Result`],[[`Build Time`,`${(yt/1e3).toFixed(1)}s`],[`Pages`,String($.pages.length)],[`JavaScript`,St],[`CSS`,Ct]],{style:`round`,headerSeparator:!0})),h(`Build finished.`),await oe?.(v),setTimeout(()=>{_(`Build process still running after 15s. There might be something misconfigured in your setup. Force exit.`),process.exit(0)},15*1e3).unref()}function ze(e,t){return!t||t===`sync`?e:e.replace(/<script type="module" /g,`<script type="module" ${t} `)}async function Be(e,t){if(t===`prettify`)try{let t=(await import(`prettier/esm/standalone.mjs`)).default,n=(await import(`prettier/esm/parser-html.mjs`)).default;return t.format(e,{semi:!1,parser:`html`,plugins:[n]})}catch(t){return p(`Error formatting html: ${t?.message}`),e}return e}function Ve({template:e,ssrEntry:t,onBeforePageRender:r,entry:a,rootContainerId:o,onPageRendered:s}){return{name:`vite-react-ssg:dev-server`,configureServer(c){let l=async(l,u,d)=>{try{let d=l.originalUrl,f=await(await c.ssrLoadModule(t).then(e=>e.createRoot))(!1,d),p=we(f),{app:m,base:h}=f,[g,_]=d.split(`?`),v=new URLSearchParams(_);if(!m&&v.has(`_data`))return p.handleLoader(l,u);let y=await c.transformIndexHtml(d,e),b=await r?.(d,y,f)||y,{appHTML:x,bodyAttributes:S,htmlAttributes:C,metaAttributes:w,styleTag:T}=await p.render(i(g,h));w.push(T);let E=await Promise.all([t,a].map(async e=>await c.moduleGraph.getModuleByUrl(e))),D=new Set,O=new Set,A=async e=>{if(!e||!e?.ssrTransformResult||O.has(e))return;O.add(e);let{deps:t=[],dynamicDeps:n=[]}=e?.ssrTransformResult,r=[...t,...n];for(let e of r)if(e.endsWith(`.css`)||e.endsWith(`.scss`)||e.endsWith(`.sass`)||e.endsWith(`.less`))D.add(e);else if(e.endsWith(`.ts`)||e.endsWith(`.tsx`)){let t=await c.moduleGraph.getModuleByUrl(e);t&&await A(t)}};await Promise.all(E.map(async e=>A(e)));let j=[...D].map(e=>pe(n(c.config.base,e)));w.push(...j);let M=await de({rootContainerId:o,appHTML:x,indexHTML:b,metaAttributes:w,bodyAttributes:S,htmlAttributes:C,initialState:null}),ee=await s?.(d,M,f)||M;u.statusCode=200,u.setHeader(`Content-Type`,`text/html`),k(l,u,ee,`html`,{headers:`pluginContainer`in c?c.config.server.headers:c.config.preview.headers})}catch(e){c.ssrFixStacktrace(e),p(`SSR render error`,e),u.statusCode=500,u.end(e.stack)}};return()=>{c.middlewares.use(l)}}}}async function He(e={},t={}){try{let n=process.env.NODE_ENV||t.mode||`development`,r=await O(e,`serve`,n,n),i=process.cwd(),a=r.root||i,o={...r.ssgOptions,...t},{htmlEntry:s=`index.html`,onBeforePageRender:c,onPageRendered:l,rootContainerId:u=`root`,mock:d=!1}=o,f=o.entry||await fe(a,s),[p,m]=await Promise.all([De(r,f),te.readFile(x(a,s),`utf-8`)]);if(process.env.__DEV_MODE_SSR=`true`,d){let{jsdomGlobal:e}=await import(`./jsdomGlobal-u0wZKDvc.mjs`);e()}return await E({...e,plugins:[...e.plugins??[],Ve({template:m,ssrEntry:p,onBeforePageRender:c,onPageRendered:l,entry:f,rootContainerId:u})]})}catch(e){throw Error(`[vite-react-ssg] Failed to create dev server: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function Ue(e={},t={},n){globalThis.__ssr_start_time=performance.now();try{let r=await He(t,e);return await r.listen(),We(r,!!n),r.bindCLIShortcuts({print:!0}),r}catch(e){p(`failed to start server: ${e?.message??e}`),process.exit(1)}}function We(e,t=!1){if(t){e.printUrls();return}let n=e.config.logger.info,r=` -- SSR`;if(globalThis.__ssr_start_time){let e=Math.round(performance.now()-globalThis.__ssr_start_time);r+=` ready in ${u.reset(u.bold(`${e}ms`))}`}n(`\n ${u.cyan(` VITE-REACT-SSG v${U} `)}`,{clear:!e.config.logger.hasWarned}),n(`${u.cyan(`\n VITE v${A}`)+u.dim(r)}\n`),n(u.green(` dev server running at:`)),e.printUrls()}export{Re as build,He as createServer,Ue as dev};
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o}from"./state-CkhLd6hN.mjs";import{createRequire as s}from"node:module";import{Fragment as c,jsx as l}from"react/jsx-runtime";import{colors as u,error as d,warn as f}from"@bdocs/dui";import p from"node:os";import m,{dirname as h,isAbsolute as g,join as _,relative as v}from"node:path";import y from"fs-extra";import{build as b,createLogger as x,createServer as S,mergeConfig as C,resolveConfig as w,send as T,version as E}from"vite";import D from"node:crypto";import{once as O}from"node:events";import{Readable as k}from"node:stream";import*as A from"react-dom/server";import j from"node:fs";import M from"node:fs/promises";var N=s(import.meta.url);const ee=/import\("([^)]+)"\)/g;let te=null;async function ne(){if(!te){let{matchRoutes:e}=await import(`react-router-dom`);te=e}return te}async function re({routes:e,locationArg:t,base:n,serverManifest:r,manifest:i,ssrManifest:a}){let o=(await ne())([...e],t,n),s=o?.map(e=>e.route.entry).filter(Boolean)??[],c=new Set;o?.forEach(e=>{let t=``;e.route.lazy&&(t+=e.route.lazy.toString()),e.route.Component?._payload?._result&&(t+=e.route.Component._payload._result.toString());let n=t.matchAll(ee);for(let e of n)c.add(e[1].split(`/`).at(-1)??``)});let l=new Set;s.forEach(e=>l.add(e));let u=[...Object.entries(r)];c.forEach(e=>{let t=u.find(([t,n])=>n.file.endsWith(e));t&&l.add(t[0])});let d=P(i,l),f=new Set;return Array.from(d).forEach(e=>{(a[e]||[]).forEach(e=>{f.add(e)})}),f}function P(e,t){let n=new Set;if(!t)return n;for(let r of t)F(e,r,n);return n}function F(e,t,n=new Set){return t?(n.add(t),e[t]?.dynamicImports?.forEach(t=>{F(e,t,n)}),n):n}async function I(e,t={}){try{let n=await import(`beasties`);return new(n.default||n)({path:e,logLevel:`warn`,external:!0,inlineFonts:!0,preloadFonts:!0,...t})}catch{return}}async function ie(){try{let e=await import(`@bdocs/zig-critters`),t=e.processHtml||e.default?.processHtml;return t?{processHtml:t}:void 0}catch{return}}const ae=`/* SCRIPT_COMMENT_PLACEHOLDER */`;async function oe({rootContainerId:e,indexHTML:t,appHTML:n,metaAttributes:r,bodyAttributes:i,htmlAttributes:a,initialState:o}){let s=o?`\n<script>window.__INITIAL_STATE__=${o}<\/script>`:``,c=`\n<script>${ae}<\/script>`,l=`<head>`,u=r.join(``);t=t.replace(l,l+u);let d=`<body`;t=t.replace(d,`${d} ${i}`);let f=`<html`;t=t.replace(f,`${f} ${a}`);let p=`<div id="${e}"></div>`;if(t.includes(p))return t.replace(p,`<div id="${e}" data-server-rendered="true">${n}</div>${s}${c}`);let m=await import(`html5parser`),h=m.parse(t),g;if(m.walk(h,{enter:r=>{if(!g&&r?.type===m.SyntaxKind.Tag&&Array.isArray(r.attributes)&&r.attributes.length>0&&r.attributes.some(t=>t.name.value===`id`&&t.value?.value===e)){let e=[...r.attributes.map(({name:{value:e},value:t})=>`${e}="${t.value}"`)].join(` `),i=t.slice(0,r.start),a=t.slice(r.end);g=`${i}<${r.name} ${e} data-server-rendered="true">${n}</${r.name}>${s}${c}${a}`}}}),!g)throw Error(`Could not find a tag with id="${e}" to replace it with server-side rendered HTML`);return g}async function se(e,t=`index.html`){let[,n]=[...(await y.readFile(_(e,t),`utf-8`)).matchAll(/<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim)].find(e=>{let[t]=e,[,n]=t.match(/.*\stype=(?:'|")?([^>'"\s]+)/i)||[];return n===`module`})||[];return n||`src/main.ts`}function ce(e){return`<link rel="stylesheet" href="${e}">`}function le(e){let t=new Set,n=[];return e&&e.forEach(e=>{if(!t.has(e)){t.add(e);let r=L(e);r&&n.push(r)}}),n.join(``)}function L(e){return e.endsWith(`.js`)?`<link rel="modulepreload" crossorigin href="${e}">`:e.endsWith(`.css`)?`<link rel="stylesheet" crossorigin href="${e}">`:e.endsWith(`.woff`)||e.endsWith(`.woff2`)||e.endsWith(`.ttf`)?`<link rel="preload" as="font" type="font/woff2" crossorigin href="${e}">`:e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.webp`)||e.endsWith(`.gif`)||e.endsWith(`.ico`)||e.endsWith(`.svg`)?`<link rel="preload" as="image" crossorigin href="${e}">`:null}function ue(e,t){if(e===!1||e==null)throw console.error(`The following error is a bug in Boltdocs SSG; please open an issue! https://github.com/bolt-docs/boltdocs/issues/new`),Error(t)}function de(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(r)if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r);return t}function fe(e){let t=e.headers.origin&&e.headers.origin!==`null`?e.headers.origin:`http://${e.headers.host}`;ue(e.originalUrl,"Expected `nodeReq.originalUrl` to be defined");let n=new URL(e.originalUrl,t),r={method:e.method,headers:de(e.headers)};return new Request(n.href,r)}async function pe(e,t){t.statusCode=e.status,t.statusMessage=e.statusText;for(let[n,r]of e.headers)t.setHeader(n,r);if(e.body){let n=e.body,r=k.from(n);r.pipe(t),await O(r,`end`)}else t.end()}function me(e){let t=new URL(e.url);t.searchParams.delete(`_data`);let n={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return n.body&&(n.duplex=`half`),new Request(t.href,n)}async function R(e){return A.renderToString(l(c,{children:e}))}function he(e,t,n){let{helmet:r}=t,i=r.htmlAttributes.toString(),a=r.bodyAttributes.toString(),o=r.title.toString();o.split(`>`)[1]===`</title`&&(o=``);let s=[o,r.meta.toString(),r.link.toString(),r.script.toString()],c=n?.toString?.(e)??``;return{htmlAttributes:i,bodyAttributes:a,metaAttributes:s.filter(Boolean),styleTag:c}}let z=null;function B(){return z||(z=globalThis.__BOLTDOCS_HELMET_PROVIDER__||(()=>{let{createRequire:e}=N(`node:module`);return e(import.meta.url)(`react-helmet-async`).HelmetProvider})(),z)}let V=null;async function H(){return V||=await import(`react-router-dom`),V}var U=class{constructor(e){this._dataRoutes=null,this._staticHandler=null,this.handleLoader=async(e,t)=>{let{routes:n,base:r}=this.context,{matchRoutes:i}=await H(),o=fe(e),s=new URL(o.url),c=decodeURIComponent(s.searchParams.get(`_data`)),l=i(a([...n],e=>e),{pathname:s.pathname,search:s.search,hash:s.hash,state:null,key:`default`},r);if(!l){t.statusCode=404,t.end(`Route not found: ${c}`);return}let u=l.find(e=>e.route.id===c);if(!u){t.statusCode=404,t.end(`Route not found: ${c}`);return}let d=u.route.loader??await u.route.lazy?.().then(e=>e.loader);if(!d){t.statusCode=200,t.end(`There is no loader for the route: ${c}`);return}await pe(await W({loader:d,params:u.params,request:o,routeId:c}),t)},this.context=e}async render(e){let{base:t,routes:n,getStyleCollector:r,routerOptions:i}=this.context,s=o(e),c=s;if(t!==`/`){let e=o(t).replace(/\/$/,``);!s.startsWith(e+`/`)&&s!==e&&(c=`${e}${s}`)}let u=`http://localhost${c}`,d=new Request(u),f=r?await r():null,p={},m=null,{StaticRouterProvider:h,createStaticHandler:g,createStaticRouter:_}=await H(),v=this._dataRoutes??=a([...n],e=>e);this._staticHandler??=g(v,{basename:t});let{query:y}=this._staticHandler,b=await y(d),x=0;for(;b instanceof Response&&x<10;){let e=b.headers.get(`Location`);if(!e)break;let t;if(/^https?:\/\//i.test(e))try{let n=new URL(e);if(n.hostname===`localhost`||n.hostname===``)t=`http://localhost${o(n.pathname+n.search+n.hash)}`;else break}catch{break}else t=`http://localhost${o(e)}`;b=await y(new Request(t)),x++}if(b instanceof Response)throw b;m=b;let S=_(v,m,{future:i.future}),C=B(),w=C;w&&typeof w==`function`&&(w.canUseDOM=!1);let T=l(C,{context:p,children:l(h,{router:S,context:m})});f&&(T=f.collect(T));let E=await R(T),{htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A}=he(E,p,f);return{appHTML:E,htmlAttributes:D,bodyAttributes:O,metaAttributes:k,styleTag:A,routerContext:m}}};async function W({loader:e,params:t,request:n,routeId:r}){let{json:i}=await H(),a=await e({request:me(_e(n)),params:t});if(a===void 0)throw Error(`You defined a loader for route "${r}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`);return ge(a)?a:i(a)}function ge(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function _e(e){let t=new URL(e.url),n=t.searchParams.getAll(`index`);t.searchParams.delete(`index`);let r=[];for(let e of n)e&&r.push(e);for(let e of r)t.searchParams.append(`index`,e);let i={method:e.method,body:e.body,headers:e.headers,signal:e.signal};return i.body&&(i.duplex=`half`),new Request(t.href,i)}function ve(e){return new U(e)}var G=`0.3.1`;async function ye(e){if(!e||e.length===0)return{paths:[`/`]};let t=new Set,n=async(e,i=``)=>{i=i.replace(/\/$/g,``);for(let a of e){if(a.lazy){let e=await a.lazy();e&&(a={...a,...e})}let e=a.path;if(e=r(e,i),a.getStaticPaths&&K(e)){let e=await a.getStaticPaths();for(let t of e)t=r(t,i),Array.isArray(a.children)&&await n(a.children,t)}a.index&&!e&&t.add(i||`/`),Array.isArray(a.children)&&await n(a.children,e)}};return await n(e),{paths:Array.from(t)};function r(e,n){if(e!=null){if(e===`.`){let e=n||`/`;return t.add(e),e}e=n&&!e.startsWith(`/`)?`${n}${e?`/${e}`:``}`:e,t.add(e)}return e}}async function be(e,t){return await e.createResolver()(t,e.root)||(t.startsWith(`virtual:`)||t.includes(`\0`)?t:_(e.root,t))}const xe=/[:*?]/;function K(e){return e?xe.test(e):!1}const Se=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.svg`,`.webp`,`.avif`,`.ico`]),Ce=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function q(e){try{return j.statSync(e).size}catch{return 0}}async function we(e,t){let n=_(e,`.vite`),r=_(e,`assets`),i={},a=_(n,`manifest.json`);j.existsSync(a)&&(i=JSON.parse(await j.readFileSync(a,`utf-8`)));let o=0,s=0;for(let[,t]of Object.entries(i)){let{file:n,css:r=[]}=t,i=q(_(e,n));o+=i;for(let t of r)s+=q(_(e,t))}let c=0,l=0;if(j.existsSync(r)){let e=j.readdirSync(r,{withFileTypes:!0});for(let t of e){if(!t.isFile())continue;let e=m.extname(t.name).toLowerCase(),n=_(r,t.name);Se.has(e)?c+=q(n):Ce.has(e)&&l++}}let u=_(e,`index.html`),d=0,f=[];if(j.existsSync(u)){let e=q(u);d+=e,f.push({route:`/`,htmlSize:e,htmlFile:`index.html`})}try{let t=j.readdirSync(e,{recursive:!0});for(let n of t){if(!n.endsWith(`.html`)||n===`index.html`)continue;let t=q(_(e,n));if(t>0){let e=`/`+n.replace(/\\/g,`/`).replace(/\/index\.html$/,``).replace(/\.html$/,``);d+=t,f.push({route:e,htmlSize:t,htmlFile:n})}}}catch{}return{buildTime:t,totalJSBundleSize:o,totalCSSBundleSize:s,totalImagesSize:c,totalHTMLSize:d,fontCount:l,pages:f}}function Te(e,t){let n=m.resolve(e,`..`,`.boltdocs`,`reports`);j.existsSync(n)||j.mkdirSync(n,{recursive:!0});let r=_(n,`performance.json`);j.writeFileSync(r,JSON.stringify(t,null,2))}const Ee=Number.parseInt(E)>=5?[`.vite`]:[];function De(e){return Number.parseInt(E)>=8?{rolldownOptions:e}:{rollupOptions:e}}const J=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.css`,`.json`,`.md`,`.mdx`,`.html`,`.svg`,`.yaml`,`.yml`]),Oe=new Set([`node_modules`,`.git`,`.boltdocs`,`.turbo`,`dist`,`coverage`,`__tests__`,`test`,`tests`,`.next`,`.cache`,`public`]);function ke(e){let t=[];if(!y.existsSync(e))return t;let n=y.readdirSync(e,{withFileTypes:!0,recursive:!0});for(let e of n){if(!e.isFile()||e.name.startsWith(`.`))continue;let n=String(e.parentPath??e.path);if(n.split(`/`).slice(-1).some(e=>Oe.has(e)))continue;let r=`.`+e.name.split(`.`).pop()?.toLowerCase();J.has(r)&&t.push(_(n,e.name))}return t}let Ae=null,je=null;function Me(e,t,n,r){try{let n=[],i=_(e,t);y.existsSync(i)&&n.push(...ke(i));for(let t of[`boltdocs.config.ts`,`boltdocs.config.js`,`boltdocs.config.mjs`,`boltdocs.config.cjs`,`package.json`,`tsconfig.json`]){let r=_(e,t);y.existsSync(r)&&n.push(r)}n.sort();let a=`${n.length}:${n[0]}:${n[n.length-1]}`;if(Ae&&je===a)return Ae;let o=Array(n.length);for(let e=0;e<n.length;e++){let t=y.statSync(n[e]);o[e]={file:n[e],mtime:t.mtimeMs,size:t.size}}if(r){let e=_(r,`hash-meta.json`),t=_(r,`client-hash.txt`);try{if(y.existsSync(e)&&y.existsSync(t)){let r=JSON.parse(y.readFileSync(e,`utf-8`)),i=Math.max(...o.map(e=>e.mtime));if(r.fileCount===n.length&&r.lastMtime===i){let e=y.readFileSync(t,`utf-8`).trim();if(e)return Ae=e,je=a,e}}}catch{}}let s=D.createHash(`sha256`);for(let{file:t,mtime:n,size:r}of o)s.update(v(e,t).replace(/\\/g,`/`)),s.update(n.toString()),s.update(r.toString());let c=s.digest(`hex`);if(Ae=c,je=a,r)try{let e=Math.max(...o.map(e=>e.mtime)),t=_(r,`hash-meta.json`);y.mkdirSync(r,{recursive:!0}),y.writeFileSync(t,JSON.stringify({fileCount:n.length,lastMtime:e}))}catch{}return c}catch{return Math.random().toString(36).substring(2,12)}}function Ne(e,t){return`static-loader-data${o(e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e)}.${t}.json`}function Pe(e,t=`/`){let n=o(e),r=n;if(t!==`/`){let e=o(t).replace(/\/$/,``);!n.startsWith(e+`/`)&&n!==e&&(r=`${e}${n}`)}return r!==`/`&&r.endsWith(`/`)?r.slice(0,-1):r}function Fe(e,t){return e.filter(e=>!e.includes(`:`)&&!e.includes(`*`))}async function Ie(n={},i={}){let a=process.env.MODE||process.env.NODE_ENV||n.mode||`production`;a!==process.env.NODE_ENV&&(process.env.NODE_ENV=a);let c=await w(i,`build`,a,a),l=process.cwd(),u=c.root||l,d=c.build.outDir||`dist`,m=c.base,S=Object.assign({},c.ssgOptions||{},n),T=performance.now(),{script:E=`sync`,mock:O=!1,htmlEntry:k=`index.html`,entry:A=await se(u,k),formatting:j=`none`,includedRoutes:M=Fe,onBeforePageRender:ee,onPageRendered:te,onFinished:ne,onStep:P,dirStyle:F=`flat`,includeAllRoutes:ce=!1,format:L=`esm`,concurrency:ue=20,rootContainerId:de=`root`,routeToSourceFileMap:fe={},cacheDir:pe=`.boltdocs/build`}=S,me=S.beastiesOptions??{},R=S.turbo??!1,he=`docs`,z=Object.values(fe);if(z.length>0){let e=z[0],t=v(u,e).replace(/\\/g,`/`).split(`/`);t.length>0&&(he=t[0])}let B=g(d)?d:_(u,d),V=g(pe)?pe:_(u,pe),H=Me(u,he,d,V),U=H.substring(0,12),W=_(V,`ssr`,R?`turbo-ssr`:U),ge=_(V,`client-hash.txt`),_e=_(V,`template-index.html`),G=!1;try{y.existsSync(ge)&&y.existsSync(_e)&&y.existsSync(B)&&y.existsSync(_(B,`assets`))&&(await y.readFile(ge,`utf-8`)).trim()===H&&(G=!0)}catch{}function xe(e){return e.startsWith(`dist/`)||e.startsWith(`.boltdocs/build/ssr/`)||e.startsWith(`rendering chunks`)||e===`computing gzip size...`||e.includes(`built in`)&&e.includes(`s`)}let K=x(),Se=K.warn;K.warn=(e,t)=>{e.includes(`externalized for browser compatibility`)||e.includes(`can't be bundled without type`)||xe(e)||Se(e,t)};let Ce=K.info;if(K.info=(e,t)=>{xe(e)||Ce(e,t)},G)P?.({name:`Client build`,duration:0,success:!0,details:`Code unchanged, skipped`}),await y.ensureDir(B),await y.copy(_e,_(B,k));else{let e=performance.now();await b(C(i,{logLevel:`warn`,build:{manifest:!0,ssrManifest:!0,chunkSizeWarningLimit:2e3,...De({input:{app:_(u,k||`./index.html`)},onLog(e,t,n){t.message.includes(`react-helmet-async`)||xe(t.message)||n(e,t)}})},customLogger:K,mode:c.mode,plugins:[{name:`vite-react-ssg:get-oup-dir`,configResolved(e){d=e.build.outDir||`dist`}}]})),P?.({name:`Client build`,duration:performance.now()-e,success:!0,details:`Vite production build`}),await y.ensureDir(V),await y.copy(_(B,k),_e),await y.writeFile(ge,H,`utf-8`)}let q=()=>{};if(O){let{jsdomGlobal:e}=await import(`./jsdomGlobal-u0wZKDvc.mjs`);q=e()}let J=await be(c,A);if((R||G)&&y.existsSync(W)&&y.readdirSync(W).filter(e=>e.endsWith(`.mjs`)||e.endsWith(`.cjs`)).length>0)P?.({name:`Server build`,duration:0,success:!0,details:`SSR bundle unchanged, skipped`});else{y.existsSync(W)&&await y.remove(W),process.env.VITE_SSG=`true`;let e=performance.now();await b(C(i,{logLevel:`warn`,build:{ssr:J,manifest:!0,outDir:W,minify:!1,cssCodeSplit:!1,...De({output:L===`esm`?{entryFileNames:`[name].mjs`,format:`esm`}:{entryFileNames:`[name].cjs`,format:`cjs`},onLog(e,t,n){t.message.includes(`react-helmet-async`)||xe(t.message)||n(e,t)}})},customLogger:K,mode:c.mode})),P?.({name:`Server build`,duration:performance.now()-e,success:!0,details:`Vite SSR bundle`})}let Oe=L===`esm`&&process.platform===`win32`?`file://`:``,ke=L===`esm`?`.mjs`:`.cjs`,Ae=J.replace(/\0/g,``).replace(`virtual:`,``).replace(/[^a-zA-Z0-9-]/g,`_`),je=Oe+_(W,(J.includes(`/`)||J.includes(`\\`)?J.split(/[/\\]/).pop().replace(/\.[^/.]+$/,``).replace(ke,``):Ae)+ke).replace(/\\/g,`/`),Ie=JSON.parse(await y.readFile(_(W,...Ee,`manifest.json`),`utf-8`)),ze=N===void 0?s(import.meta.url):N,{createRoot:Be,includedRoutes:Ve}=L===`esm`?await import(je):ze(je),He=Ve||M,{routes:Ue}=await Be(!1),{paths:We}=await ye(Ue),Y=ce?We:await He(We,Ue||[]);Y=Fe(Y,Ue||[]),Y=Array.from(new Set(Y));let X;R&&(X=await ie(),X||f(`[zig-critters] WASM unavailable; falling back to beasties for critical CSS`));let Ge=me!==!1&&!X?await I(d,{publicPath:m,...me}):void 0,Ke=``;if(X){let e=_(B,`assets`);if(y.existsSync(e)){let t=y.readdirSync(e).filter(e=>e.endsWith(`.css`));for(let n of t)Ke+=y.readFileSync(_(e,n),`utf-8`)+`
2
+ `}}let qe=performance.now(),Je=JSON.parse(await y.readFile(_(B,...Ee,`ssr-manifest.json`),`utf-8`)),Ye=JSON.parse(await y.readFile(_(B,...Ee,`manifest.json`),`utf-8`)),Xe=await y.readFile(_(B,k),`utf-8`);y.rmSync(_(B,k)),Xe=Le(Xe,E);let Ze=(await import(`p-queue`)).default||await import(`p-queue`),Qe=new Ze({concurrency:ue}),$e=new Ze({concurrency:Math.min(p.cpus().length,4)}),et={},tt=0,nt=new Map,rt=0,it=0,at=0,ot=_(V,`ssg-cache.json`),Z=_(V,`ssg-pages`),Q={};if(!R)try{y.existsSync(ot)&&(Q=await y.readJson(ot))}catch{}let st={...Q},ct=new Set;ct.add(Z);for(let e of Y){let t=F===`nested`?_(e.replace(/^\//g,``),`index.html`):`${(e.endsWith(`/`)?`${e}index`:e).replace(/^\//g,``)}.html`;ct.add(_(B,h(t)));let n=e===`/`?`/index`:e.endsWith(`/`)?`${e}index`:e;ct.add(_(B,`static-loader-data`,h(n)))}ct.add(_(B,`static-loader-data`)),await Promise.all([...ct].map(e=>y.ensureDir(e)));for(let n of Y){let i=D.createHash(`md5`).update(n).digest(`hex`),a=_(Z,`${i}.html`),s=_(Z,`${i}.json`),c=`${(n.endsWith(`/`)?`${n}index`:n).replace(/^\//g,``)}.html`,l=F===`nested`?_(n.replace(/^\//g,``),`index.html`):c,u=_(B,l),d=o(n).replace(/\/$/,``),p=fe[d]||fe[n],h=!1,g=0;if(!R&&G&&p&&y.existsSync(p))try{if(g=Math.round(y.statSync(p).mtimeMs),y.existsSync(a)){let e=Q[d]||Q[n];e&&Math.round(e.mtime)===g&&(h=!0)}}catch{}if(h){Qe.add(async()=>{try{if(G)await y.copy(a,u);else{let e=await y.readFile(a,`utf-8`);e=e.replace(/window\.__VITE_REACT_SSG_HASH__\s*=\s*'[^']*'/,`window.__VITE_REACT_SSG_HASH__ = '${U}'`),await y.writeFile(u,e,`utf-8`)}let e=Q[d]||Q[n];if(e?.loaderDataFilePath&&y.existsSync(s)){let t=G?e.loaderDataFilePath:Ne(n,U);await y.copy(s,_(B,t)),et[Pe(n,m)]=t,tt++}it++}catch(e){throw Error(`Error on cached page: ${n}\n${e.stack}`)}});continue}Qe.add(async()=>{try{let i=await Be(!1,n),{base:c,routes:u,triggerOnSSRAppRendered:d,transformState:h=r,app:v,routerType:b}=i,x=await ee?.(n,Xe,i)||Xe,S=`${t(c)}${e(n)}`,C=ve(i),w;if(!v&&b===`remix`){let e=nt.get(n);e?w=e:(w=await re({routes:[...u],locationArg:S,base:c,serverManifest:Ie,manifest:Ye,ssrManifest:Je}),nt.set(n,w))}else w=new Set;let{appHTML:T,bodyAttributes:E,htmlAttributes:D,metaAttributes:O,styleTag:k,routerContext:A}=await C.render(n),M=A?.loaderData,N;if(M&&Object.keys(M).length>0){let e=Ne(n,U);N=e,await y.writeFile(_(B,e),JSON.stringify(M)),et[Pe(n,m)]=e,tt++}await d?.(n,T,i);let ne=await oe({rootContainerId:de,appHTML:T,indexHTML:x,metaAttributes:O,bodyAttributes:E,htmlAttributes:D,initialState:null}),P=le(w),F=ne.replace(/<script[^>]*>(?:(?!<\/script>)[\s\S])*__staticRouterHydrationData(?:(?!<\/script>)[\s\S])*<\/script>/g,``);P&&(F=F.replace(`<head>`,`<head>${P}`));let I=await te?.(n,F,i)||F,ie=``;if(M&&Object.keys(M).length>0){let e=JSON.stringify(M).replace(/</g,`\\u003c`);ie=`window.__VITE_REACT_SSG_STATIC_LOADER_DATA__ = { '${Pe(n,m)}': ${e} };`}let se=``;if(A){let e={loaderData:A.loaderData??{},actionData:A.actionData??null,errors:A.errors??null};se=`window.__staticRouterHydrationData = ${JSON.stringify(e).replace(/</g,`\\u003c`)};`}let ce=`<script>window.__VITE_REACT_SSG_HASH__ = '${U}';${ie}${se}<\/script>`;if(I=I.replace(`<head>`,`<head>${ce}`),I=I.replace(`<script>${ae}<\/script>`,``),X){try{Ke&&(I=await X.processHtml(I,Ke))}catch(e){f(`[zig-critters] Failed to inline CSS for "${n}": ${e instanceof Error?e.message:String(e)}`)}I=I.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`)}else Ge&&(I=await $e.add(()=>Ge.process(I)),I=I.replace(/<link\srel="stylesheet"(?!.*\bcrossorigin\b)/g,`<link rel="stylesheet" crossorigin`));k&&(I=I.replace(`<head>`,`<head>${k}`));let L=await Re(I,j);if(await y.writeFile(_(B,l),L,`utf-8`),!R&&p&&y.existsSync(p)){await y.writeFile(a,L,`utf-8`);let e=o(n).replace(/\/$/,``),t=Math.round(g);M&&Object.keys(M).length>0&&N?(await y.writeFile(s,JSON.stringify(M),`utf-8`),st[e]={mtime:t,loaderDataFilePath:N}):st[e]={mtime:t}}rt++,at+=L.length}catch(e){throw Error(`Error on page: ${n}\n${e.stack}`)}})}await Qe.start().onIdle();let lt=rt+it,ut=(at/1024/1024).toFixed(2),dt=0;if(!R)try{if(await y.ensureDir(h(ot)),await y.writeJson(ot,st),y.existsSync(Z)){let e=await y.readdir(Z),t=new Set;for(let e of Object.keys(st)){let n=D.createHash(`md5`).update(e).digest(`hex`);t.add(`${n}.html`),t.add(`${n}.json`)}for(let n of e)(n.endsWith(`.html`)||n.endsWith(`.json`))&&(t.has(n)||(await y.remove(_(Z,n)),dt++))}}catch{}P?.({name:`Render pages`,duration:performance.now()-qe,success:!0,details:`${lt} pages (${rt} new, ${it} cached, ${ut} MB)`,metrics:{renderedCount:rt,cachedCount:it,renderedSize:at,totalPages:lt,prunedCount:dt}});let ft=performance.now(),pt=JSON.stringify(et,null,0);await y.writeFile(_(B,`static-loader-data-manifest-${U}.json`),pt),G||await y.remove(_(V,`ssr`)),q();let mt=c.plugins.find(e=>e.name===`vite-plugin-pwa`)?.api;mt&&!mt.disabled&&mt.generateSW&&await mt.generateSW();let ht=Math.round(performance.now()-T),$=await we(B,ht);Te(B,$),P?.({name:`Static loader data`,duration:performance.now()-ft,success:!0,details:`${tt} loader data files`,metrics:{loaderDataFileCount:tt}}),P?.({name:`Build metrics`,duration:0,success:!0,details:`Build time: ${(ht/1e3).toFixed(1)}s, JS: ${($.totalJSBundleSize/1024).toFixed(0)} kB, CSS: ${($.totalCSSBundleSize/1024).toFixed(0)} kB`,metrics:{buildTime:ht,totalPages:$.pages.length,jsSize:$.totalJSBundleSize,cssSize:$.totalCSSBundleSize}}),await ne?.(d),setTimeout(()=>{f(`Build process still running after 15s. There might be something misconfigured in your setup. Force exit.`),process.exit(0)},15*1e3).unref()}function Le(e,t){return!t||t===`sync`?e:e.replace(/<script type="module" /g,`<script type="module" ${t} `)}async function Re(e,t){if(t===`prettify`)try{let t=(await import(`prettier/esm/standalone.mjs`)).default,n=(await import(`prettier/esm/parser-html.mjs`)).default;return t.format(e,{semi:!1,parser:`html`,plugins:[n]})}catch(t){return d(`Error formatting html: ${t?.message}`),e}return e}function ze(e,t,n){if(e.url)try{let t=e.url,n=t.indexOf(`?`),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n):``;if(/%[0-9A-Fa-f]{2}/.test(r)){let t=decodeURI(r);if(t!==r){let n=t+i;e.url=n,e.originalUrl&&=n}}}catch{}n()}function Be({template:e,ssrEntry:t,onBeforePageRender:r,entry:a,rootContainerId:o,onPageRendered:s}){return{name:`vite-react-ssg:dev-server`,configureServer(c){let l=async(l,u,f)=>{try{let d=l.originalUrl,f=await(await c.ssrLoadModule(t).then(e=>e.createRoot))(!1,d),p=ve(f),{app:m,base:h}=f,[g,_]=d.split(`?`),v=new URLSearchParams(_);if(!m&&v.has(`_data`))return p.handleLoader(l,u);let y=await c.transformIndexHtml(d,e),b=await r?.(d,y,f)||y,{appHTML:x,bodyAttributes:S,htmlAttributes:C,metaAttributes:w,styleTag:E}=await p.render(i(g,h));w.push(E);let D=await Promise.all([t,a].map(async e=>await c.moduleGraph.getModuleByUrl(e))),O=new Set,k=new Set,A=async e=>{if(!e||!e?.ssrTransformResult||k.has(e))return;k.add(e);let{deps:t=[],dynamicDeps:n=[]}=e?.ssrTransformResult,r=[...t,...n];for(let e of r)if(e.endsWith(`.css`)||e.endsWith(`.scss`)||e.endsWith(`.sass`)||e.endsWith(`.less`))O.add(e);else if(e.endsWith(`.ts`)||e.endsWith(`.tsx`)){let t=await c.moduleGraph.getModuleByUrl(e);t&&await A(t)}};await Promise.all(D.map(async e=>A(e)));let j=[...O].map(e=>ce(n(c.config.base,e)));w.push(...j);let M=await oe({rootContainerId:o,appHTML:x,indexHTML:b,metaAttributes:w,bodyAttributes:S,htmlAttributes:C,initialState:null}),N=await s?.(d,M,f)||M;u.statusCode=200,u.setHeader(`Content-Type`,`text/html`),T(l,u,N,`html`,{headers:`pluginContainer`in c?c.config.server.headers:c.config.preview.headers})}catch(e){c.ssrFixStacktrace(e),d(`SSR render error`,e),u.statusCode=500,u.end(e.stack)}};return c.middlewares.use(ze),()=>{c.middlewares.use(l)}}}}async function Ve(e={},t={}){try{let n=process.env.NODE_ENV||t.mode||`development`,r=await w(e,`serve`,n,n),i=process.cwd(),a=r.root||i,o={...r.ssgOptions,...t},{htmlEntry:s=`index.html`,onBeforePageRender:c,onPageRendered:l,rootContainerId:u=`root`,mock:d=!1}=o,f=o.entry||await se(a,s),[p,m]=await Promise.all([be(r,f),M.readFile(_(a,s),`utf-8`)]);if(process.env.__DEV_MODE_SSR=`true`,d){let{jsdomGlobal:e}=await import(`./jsdomGlobal-u0wZKDvc.mjs`);e()}return await S({...e,plugins:[...e.plugins??[],Be({template:m,ssrEntry:p,onBeforePageRender:c,onPageRendered:l,entry:f,rootContainerId:u})]})}catch(e){throw Error(`[vite-react-ssg] Failed to create dev server: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async function He(e={},t={},n){globalThis.__ssr_start_time=performance.now();try{let r=await Ve(t,e);return await r.listen(),Ue(r,!!n),r.bindCLIShortcuts({print:!0}),r}catch(e){d(`failed to start server: ${e?.message??e}`),process.exit(1)}}function Ue(e,t=!1){if(t){e.printUrls();return}let n=e.config.logger.info,r=` -- SSR`;if(globalThis.__ssr_start_time){let e=Math.round(performance.now()-globalThis.__ssr_start_time);r+=` ready in ${u.reset(u.bold(`${e}ms`))}`}n(`\n ${u.cyan(` VITE-REACT-SSG v${G} `)}`,{clear:!e.config.logger.hasWarned}),n(`${u.cyan(`\n VITE v${E}`)+u.dim(r)}\n`),n(u.green(` dev server running at:`)),e.printUrls()}export{Ie as build,Ve as createServer,He as dev};
@@ -1,6 +1,6 @@
1
- import { FutureConfig, IndexRouteObject, NonIndexRouteObject, createBrowserRouter } from "react-router-dom";
2
- import { ReactElement, ReactNode } from "react";
3
1
  import { Options } from "beasties";
2
+ import { ReactElement, ReactNode } from "react";
3
+ import { FutureConfig, IndexRouteObject, NonIndexRouteObject, createBrowserRouter } from "react-router-dom";
4
4
 
5
5
  //#region src/types.d.ts
6
6
  type Router = ReturnType<typeof createBrowserRouter>;
@@ -71,6 +71,7 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
71
71
  beastiesOptions?: Options | false;
72
72
  /**
73
73
  * Enable turbo mode: use zig-critters WASM instead of beasties JS for critical CSS.
74
+ * Falls back to beasties if the WASM binary is unavailable.
74
75
  *
75
76
  * @default false
76
77
  */
@@ -103,6 +104,17 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
103
104
  */
104
105
  onPageRendered?: (route: string, renderedHTML: string, appCtx: Context) => Promise<string | null | undefined> | string | null | undefined;
105
106
  onFinished?: (dir: string) => Promise<void> | void;
107
+ /**
108
+ * Callback invoked at each build sub-step boundary.
109
+ * Used to collect step data for the pipeline summary.
110
+ */
111
+ onStep?: (step: {
112
+ name: string;
113
+ duration: number;
114
+ success: boolean;
115
+ details?: string;
116
+ metrics?: Record<string, any>;
117
+ }) => void;
106
118
  /**
107
119
  * The application's root container `id`.
108
120
  *
@@ -1,6 +1,6 @@
1
- import { Options } from "beasties";
2
- import { ReactElement, ReactNode } from "react";
3
1
  import { FutureConfig, IndexRouteObject, NonIndexRouteObject, createBrowserRouter } from "react-router-dom";
2
+ import { ReactElement, ReactNode } from "react";
3
+ import { Options } from "beasties";
4
4
 
5
5
  //#region src/types.d.ts
6
6
  type Router = ReturnType<typeof createBrowserRouter>;
@@ -71,6 +71,7 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
71
71
  beastiesOptions?: Options | false;
72
72
  /**
73
73
  * Enable turbo mode: use zig-critters WASM instead of beasties JS for critical CSS.
74
+ * Falls back to beasties if the WASM binary is unavailable.
74
75
  *
75
76
  * @default false
76
77
  */
@@ -103,6 +104,17 @@ interface ViteReactSSGOptions<Context = ViteReactSSGContext> {
103
104
  */
104
105
  onPageRendered?: (route: string, renderedHTML: string, appCtx: Context) => Promise<string | null | undefined> | string | null | undefined;
105
106
  onFinished?: (dir: string) => Promise<void> | void;
107
+ /**
108
+ * Callback invoked at each build sub-step boundary.
109
+ * Used to collect step data for the pipeline summary.
110
+ */
111
+ onStep?: (step: {
112
+ name: string;
113
+ duration: number;
114
+ success: boolean;
115
+ details?: string;
116
+ metrics?: Record<string, any>;
117
+ }) => void;
106
118
  /**
107
119
  * The application's root container `id`.
108
120
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@bdocs/ssg",
3
3
  "type": "module",
4
- "version": "0.2.0",
4
+ "version": "0.3.1",
5
5
  "description": "A Vite plugin for static site generation (SSG) with React.",
6
6
  "license": "MIT",
7
7
  "publishConfig": {
@@ -82,17 +82,18 @@
82
82
  }
83
83
  },
84
84
  "dependencies": {
85
+ "@bdocs/dui": "^0.3.0",
85
86
  "fs-extra": "^11.3.4",
86
87
  "html5parser": "^2.0.2",
87
88
  "jsdom": "^24.1.3",
88
- "@bdocs/dui": "^0.2.0",
89
89
  "p-queue": "^9.1.2",
90
90
  "react-helmet-async": "^2.0.1",
91
- "yargs": "^17.7.2",
91
+ "yargs": "^17.7.2"
92
+ },
93
+ "optionalDependencies": {
92
94
  "@bdocs/zig-critters": "0.2.0"
93
95
  },
94
96
  "devDependencies": {
95
- "@ririd/eslint-config": "^2.1.1",
96
97
  "@types/fs-extra": "^11.0.4",
97
98
  "@types/jsdom": "^21.1.7",
98
99
  "@types/node": "^22.0.0",
@@ -100,14 +101,10 @@
100
101
  "@types/react-dom": "^19.0.0",
101
102
  "@types/yargs": "^17.0.35",
102
103
  "beasties": "^0.4.2",
103
- "bumpp": "^10.4.1",
104
- "eslint": "^9.39.4",
105
- "esno": "^4.8.0",
106
104
  "prettier": "^3.8.2",
107
105
  "react": "^19.0.0",
108
106
  "react-dom": "^19.0.0",
109
107
  "react-router-dom": "^7.0.0",
110
- "rimraf": "^5.0.1",
111
108
  "styled-components": "6.0.5",
112
109
  "tsdown": "^0.21.9",
113
110
  "typescript": "^5.9.3",