@stacksjs/bunpress 0.2.21 → 0.2.22

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.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ea as B}from"./chunk-rnzqf7rp.js";var{YAML:R}=globalThis.Bun;import*as X from"fs";import*as T from"path";async function F(H,J,j){let K=B(J),N=j?.title||J.title||J.markdown?.title||"Documentation Feed",O=j?.description||J.description||J.markdown?.meta?.description||"Documentation updates",Q=j?.author||"Documentation Team",Z=j?.email||"",_=j?.language||"en-us",$=j?.maxItems||20,V=j?.fullContent||!1,W=await w(H,K,V);W.sort((Y,z)=>z.pubDate.getTime()-Y.pubDate.getTime());let G=W.slice(0,$);return P({title:N,description:O,link:K,language:_,author:Q,email:Z,items:G})}async function c(H,J,j,K){if(!K?.enabled)return;if(!B(j)){if(j.verbose)console.warn("\u26A0\uFE0F RSS feed generation skipped: baseUrl not configured");return}let N=await F(H,j,K),O=K.filename||"feed.xml",Q=T.join(J,O);if(await X.promises.writeFile(Q,N,"utf-8"),j.verbose){let Z=(N.match(/<item>/g)||[]).length;console.log(`\u2705 RSS feed generated: ${Q} (${Z} items)`)}}async function w(H,J,j){let K=[],N=await k(H);for(let O of N){let Q=await X.promises.readFile(O,"utf-8"),{frontmatter:Z,markdown:_}=x(Q);if(!Z.date||!Z.title)continue;let V=T.relative(H,O).replace(/\.md$/,"").replace(/index$/,"").replace(/\\/g,"/");if(!V.startsWith("/"))V=`/${V}`;if(V.endsWith("/")&&V!=="/")V=V.slice(0,-1);let W=`${J.replace(/\/$/,"")}${V}`,G=Z.description||U(_),Y=new Date(Z.date),z=Z.author;K.push({title:Z.title,link:W,description:G,pubDate:Y,author:z,content:j?_:void 0})}return K}async function k(H){let J=[];async function j(K){let N=await X.promises.readdir(K,{withFileTypes:!0});for(let O of N){let Q=T.join(K,O.name);if(O.isDirectory()){if(!O.name.startsWith(".")&&O.name!=="node_modules")await j(Q)}else if(O.isFile()&&O.name.endsWith(".md"))J.push(Q)}}return await j(H),J}function x(H){let J=/^---\n([\s\S]*?)\n---\n?/,j=H.match(J);if(!j)return{frontmatter:{},markdown:H};let K=j[1],N=H.slice(j[0].length);try{return{frontmatter:R.parse(K),markdown:N}}catch{return{frontmatter:{},markdown:H}}}function U(H,J=200){let j=H.replace(/^#{1,6}\s+(?:\S.*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])$/gm,"").replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/!\[.*?\]\(.*?\)/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/[*_~]/g,"").trim(),K=j.split(`
2
+ import{ha as B}from"./chunk-ynp2pgxy.js";var{YAML:R}=globalThis.Bun;import*as X from"fs";import*as T from"path";async function F(H,J,j){let K=B(J),N=j?.title||J.title||J.markdown?.title||"Documentation Feed",O=j?.description||J.description||J.markdown?.meta?.description||"Documentation updates",Q=j?.author||"Documentation Team",Z=j?.email||"",_=j?.language||"en-us",$=j?.maxItems||20,V=j?.fullContent||!1,W=await w(H,K,V);W.sort((Y,z)=>z.pubDate.getTime()-Y.pubDate.getTime());let G=W.slice(0,$);return P({title:N,description:O,link:K,language:_,author:Q,email:Z,items:G})}async function c(H,J,j,K){if(!K?.enabled)return;if(!B(j)){if(j.verbose)console.warn("\u26A0\uFE0F RSS feed generation skipped: baseUrl not configured");return}let N=await F(H,j,K),O=K.filename||"feed.xml",Q=T.join(J,O);if(await X.promises.writeFile(Q,N,"utf-8"),j.verbose){let Z=(N.match(/<item>/g)||[]).length;console.log(`\u2705 RSS feed generated: ${Q} (${Z} items)`)}}async function w(H,J,j){let K=[],N=await k(H);for(let O of N){let Q=await X.promises.readFile(O,"utf-8"),{frontmatter:Z,markdown:_}=x(Q);if(!Z.date||!Z.title)continue;let V=T.relative(H,O).replace(/\.md$/,"").replace(/index$/,"").replace(/\\/g,"/");if(!V.startsWith("/"))V=`/${V}`;if(V.endsWith("/")&&V!=="/")V=V.slice(0,-1);let W=`${J.replace(/\/$/,"")}${V}`,G=Z.description||U(_),Y=new Date(Z.date),z=Z.author;K.push({title:Z.title,link:W,description:G,pubDate:Y,author:z,content:j?_:void 0})}return K}async function k(H){let J=[];async function j(K){let N=await X.promises.readdir(K,{withFileTypes:!0});for(let O of N){let Q=T.join(K,O.name);if(O.isDirectory()){if(!O.name.startsWith(".")&&O.name!=="node_modules")await j(Q)}else if(O.isFile()&&O.name.endsWith(".md"))J.push(Q)}}return await j(H),J}function x(H){let J=/^---\n([\s\S]*?)\n---\n?/,j=H.match(J);if(!j)return{frontmatter:{},markdown:H};let K=j[1],N=H.slice(j[0].length);try{return{frontmatter:R.parse(K),markdown:N}}catch{return{frontmatter:{},markdown:H}}}function U(H,J=200){let j=H.replace(/^#{1,6}\s+(?:\S.*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])$/gm,"").replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/!\[.*?\]\(.*?\)/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/[*_~]/g,"").trim(),K=j.split(`
3
3
 
4
4
  `)[0]||j;if(K.length>J)return`${K.slice(0,J)}...`;return K}function P(H){let J=new Date,j=H.items.length>0?H.items[0].pubDate:J,K=H.items.map((N)=>{let O=N.content?`
5
5
  <content:encoded><![CDATA[${N.content}]]></content:encoded>`:"",Q=N.author?`
@@ -29,4 +29,4 @@ ${Q.map((V)=>{return` <sitemap>
29
29
  </sitemap>`}).join(`
30
30
  `)}
31
31
  </sitemapindex>`,$=A.join(J,K);await I.promises.writeFile($,_,"utf-8")}function d(H){return(typeof H==="string"?new Date(H):H).toISOString().split("T")[0]}function m(H,J){let j=[];for(let K=0;K<H.length;K+=J)j.push(H.slice(K,K+J));return j}
32
- export{F as x,c as y,a as z,n as A,i as B};
32
+ export{F as v,c as w,a as x,n as y,i as z};
@@ -35,4 +35,4 @@ var j=import.meta.require;function X(q){return(q.sitemap?.baseUrl||q.url||"").re
35
35
  }
36
36
  })();
37
37
  `.trim()}
38
- export{j as da,X as ea,O as fa,A as ga,E as ha,x as ia,I as ja,_ as ka,D as la,F as ma,R as na};
38
+ export{j as ga,X as ha,O as ia,A as ja,E as ka,x as la,I as ma,_ as na,D as oa,F as pa,R as qa};
@@ -0,0 +1,393 @@
1
+ // @bun
2
+ import{w as f4,x as c4,z as p4}from"./chunk-xjz041s0.js";import{B as g4,C as O,E as $4,J as w4,K as b4,L as v4,_ as d4,aa as u4,da as r,ea as l4}from"./chunk-8rsrw3sw.js";import{ga as F,ha as i}from"./chunk-ynp2pgxy.js";var{Glob:g6}=globalThis.Bun;import{copyFile as f6,mkdir as c6,readdir as p6}from"fs/promises";import{existsSync as d6}from"fs";import{join as v,resolve as u6}from"path";import S from"process";import{CLI as l6}from"@stacksjs/clapp";var p="0.2.22";import{randomUUID as e4}from"crypto";import{mkdir as R4,mkdtemp as K6,readFile as Q6,realpath as Z6,rename as o,rm as d,rmdir as $6,writeFile as X6}from"fs/promises";import{basename as Y6,dirname as W4,join as q4,resolve as N6}from"path";var u=new Map;async function H6(K,Z){let Q=u.get(K)??Promise.resolve(),$,Y=new Promise((H)=>{$=H}),X=Q.then(()=>Y);u.set(K,X),await Q;try{return await Z()}finally{if($(),u.get(K)===X)u.delete(K)}}function _6(K){return K!==null&&typeof K==="object"&&"code"in K&&K.code==="ENOENT"}async function G4(K,Z,Q){let $=N6(K);await R4(W4($),{recursive:!0});let Y=q4(await Z6(W4($)),Y6($));return H6(Y,async()=>{let X=`${Y}.lock`;try{await R4(X,{mode:448})}catch(V){if(V!==null&&typeof V==="object"&&"code"in V&&V.code==="EEXIST")throw Error(`Documentation output is locked: ${X}. Verify the recorded owner has stopped before removing a stale lock.`);throw V}let H=JSON.stringify({pid:process.pid,token:e4()}),N=q4(X,"owner.json"),_,R,q=!1,G=!1;try{await X6(N,H,{flag:"wx",mode:384}),_=await K6(`${Y}.tmp-`);let V=await Z(_),U=`${_}.previous`;try{await o(Y,U),R=U}catch(W){if(!_6(W))throw W}if(await o(_,Y),q=!0,await Q?.(),G=!0,R)await d(R,{recursive:!0});return V}catch(V){if(!G&&(q||R))try{if(q)await d(Y,{recursive:!0});if(R)await o(R,Y)}catch(U){throw AggregateError([V,U],`Documentation publication failed; previous output is retained at ${R??Y}`)}throw V}finally{try{if(_)await d(_,{recursive:!0,force:!0})}finally{if(await Q6(N,"utf8").catch(()=>{return})===H)await d(N),await $6(X);else throw Error(`Documentation output lock ownership changed: ${X}`)}}})}var{Glob:R6}=globalThis.Bun;import{dirname as W6,relative as q6,resolve as l,sep as V4}from"path";import{mkdir as G6}from"fs/promises";function A4(K){return V4==="/"?K:K.split(V4).join("/")}function V6(K){let Z=new Bun.CryptoHasher("sha256");return Z.update(K),Z.digest("hex")}async function j4(K,Z,Q){let $=l(K),Y=Q?A4(q6($,l(Q))):void 0,X=[],H=new R6("**/*");for await(let R of H.scan({cwd:$,onlyFiles:!0})){let q=A4(R);if(q===Y)continue;X.push(q)}X.sort((R,q)=>R.localeCompare(q));let N=[],_=new Bun.CryptoHasher("sha256");for(let R of X){let q=new Uint8Array(await Bun.file(l($,R)).arrayBuffer()),G=V6(q);N.push({path:R,bytes:q.byteLength,sha256:G}),_.update(`${R}\x00${q.byteLength}\x00${G}
3
+ `)}return{schema_version:1,generator:"bunpress",generator_version:Z,outputs:N,tree_sha256:_.digest("hex")}}async function M4(K,Z,Q){let $=await j4(K,Q,Z);return await G6(W6(l(Z)),{recursive:!0}),await Bun.write(Z,`${JSON.stringify($,null,2)}
4
+ `),$}function J4(K){return new Map(K.outputs.map((Z)=>[Z.path,Z]))}async function U4(K,Z,Q){let $=await Bun.file(Z).json();if($.schema_version!==1||$.generator!=="bunpress"||!Array.isArray($.outputs))throw Error(`Unsupported or malformed BunPress build manifest: ${Z}`);let Y=await j4(K,Q,Z);if(JSON.stringify(Y)===JSON.stringify($))return Y;let X=J4($),H=J4(Y),N=Y.outputs.filter((G)=>!X.has(G.path)).map((G)=>G.path),_=$.outputs.filter((G)=>!H.has(G.path)).map((G)=>G.path),R=Y.outputs.filter((G)=>{let V=X.get(G.path);return V&&(V.bytes!==G.bytes||V.sha256!==G.sha256)}).map((G)=>{let V=X.get(G.path);return`${G.path} [bytes ${V.bytes} -> ${G.bytes}; sha256 ${V.sha256} -> ${G.sha256}]`}),q=[$.generator_version!==Y.generator_version?`generator ${$.generator_version} -> ${Y.generator_version}`:"",N.length?`added: ${N.join(", ")}`:"",_.length?`removed: ${_.join(", ")}`:"",R.length?`changed: ${R.join(", ")}`:""].filter(Boolean);throw Error(`BunPress output does not match ${Z}: ${q.join("; ")||"tree hash changed"}`)}import{existsSync as A6}from"fs";import{rm as J6}from"fs/promises";import{join as j6}from"path";var I={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m"};function z(K,Z){return`${I[Z]}${K}${I.reset}`}function T(K){console.log(`${I.green}\u2713${I.reset} ${K}`)}function A(K){console.error(`${I.red}\u2717${I.reset} ${K}`)}function h(K){console.warn(`${I.yellow}\u26A0${I.reset} ${K}`)}function B(K){console.log(`${I.blue}\u2139${I.reset} ${K}`)}function w(K){if(K===0)return"0 B";let Z=1024,Q=["B","KB","MB","GB"],$=Math.floor(Math.log(K)/Math.log(Z));return`${Number.parseFloat((K/Z**$).toFixed(2))} ${Q[$]}`}function t(K){if(K<1000)return`${K}ms`;if(K<60000)return`${(K/1000).toFixed(2)}s`;return`${(K/60000).toFixed(2)}m`}var B4=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class C{frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;interval=null;text;constructor(K){this.text=K}start(){if(B4){console.log(` ${this.text}`);return}process.stdout.write("\x1B[?25l"),this.interval=setInterval(()=>{let K=this.frames[this.index];process.stdout.write(`\r${I.cyan}${K}${I.reset} ${this.text}`),this.index=(this.index+1)%this.frames.length},80)}succeed(K){this.stop(),T(K||this.text)}fail(K){this.stop(),A(K||this.text)}stop(){if(this.interval)clearInterval(this.interval),this.interval=null;if(!B4)process.stdout.write("\r\x1B[K"),process.stdout.write("\x1B[?25h")}update(K){this.text=K}}async function a(K,Z=!1){let Q=Z?"Y/n":"y/N";process.stdout.write(`${I.cyan}?${I.reset} ${K} ${I.dim}(${Q})${I.reset}: `);let $=Bun.file("/dev/stdin").stream().getReader(),Y=new TextDecoder,{value:X}=await $.read(),H=Y.decode(X).trim().toLowerCase();if(!H)return Z;return H==="y"||H==="yes"}function g(K){if(K.length===0)return;let Z=Object.keys(K[0]),Q={};for(let Y of Z)Q[Y]=Math.max(Y.length,...K.map((X)=>String(X[Y]).length));let $=Z.map((Y)=>Y.padEnd(Q[Y])).join(" ");console.log(z($,"bold")),console.log("\u2500".repeat($.length));for(let Y of K){let X=Z.map((H)=>String(Y[H]).padEnd(Q[H])).join(" ");console.log(X)}}async function n(K){try{return Bun.file(K).size}catch{return 0}}async function M6(K){try{let{Glob:Z}=awaitPromise.resolve(globalThis.Bun),Q=new Z("**/*"),$=0;for await(let Y of Q.scan(K)){let X=`${K}/${Y}`,H=await n(X);$+=H}return $}catch{return 0}}async function T4(K={}){let Z=await O,Q=K.outdir||Z.outDir||"./dist",$=j6(Q,".bunpress"),Y=K.force||!1,X=K.verbose||!1;try{if(!A6($))return B(`Directory "${$}" does not exist, nothing to clean`),!0;let N=await M6($);if(X)B(`Found "${$}" (${w(N)})`);if(!Y){if(!await a(`Delete "${$}" directory? (${w(N)})`,!1))return B("Clean cancelled"),!1}let _=process.env.VITEST==="true"||!1,R=null;if(!_&&!X)R=new C("Cleaning build artifacts..."),R.start();if(await J6($,{recursive:!0,force:!0}),R)R.succeed(`Cleaned ${w(N)} from "${$}"`);else if(X||_)T(`Cleaned ${w(N)} from "${$}"`);return!0}catch(H){return A(`Failed to clean directory: ${H}`),!1}}import{existsSync as e}from"fs";import{join as K4}from"path";async function z4(K={}){try{let Z=["bunpress.config.ts","bunpress.config.js"],Q=null;for(let Y of Z){let X=K4(process.cwd(),Y);if(e(X)){Q=X;break}}if(!Q)return A("No configuration file found"),B('Run "bunpress config init" to create one'),!1;T(`Configuration file: ${Q}`),console.log();let $=await Bun.file(Q).text();return console.log(z("Configuration:","bold")),console.log($),!0}catch(Z){return A(`Failed to show configuration: ${Z}`),!1}}async function O4(K={}){let Z=K.verbose||!1;try{let Q=["bunpress.config.ts","bunpress.config.js"],$=null;for(let _ of Q){let R=K4(process.cwd(),_);if(e(R)){$=R;break}}if(!$)return A("No configuration file found"),!1;if(Z)B(`Validating ${$}...`);let X=(await import($)).default;if(!X)return A("Configuration file does not export a default object"),!1;let H=[],N=[];if(X.markdown){if(X.markdown.toc&&typeof X.markdown.toc!=="object"&&typeof X.markdown.toc!=="boolean")H.push("markdown.toc should be an object or boolean");if(X.markdown.features){if(typeof X.markdown.features!=="object")H.push("markdown.features should be an object")}}if(X.nav){if(!Array.isArray(X.nav))H.push("nav should be an array");else for(let[_,R]of X.nav.entries())if(!R.text||!R.link)H.push(`nav[${_}] is missing required fields (text, link)`)}if(!i(X))N.push("no `url` set: sitemap, RSS, canonical links and Open Graph tags are all skipped without an absolute base URL");if(H.length>0){A("Configuration validation failed:");for(let _ of H)console.log(` \u2022 ${_}`);return!1}for(let _ of N)h(_);return T("Configuration is valid \u2713"),!0}catch(Q){return A(`Failed to validate configuration: ${Q}`),!1}}async function L4(K={}){let Z=K4(process.cwd(),"bunpress.config.ts");if(e(Z))return A("Configuration file already exists"),!1;let Q=`import type { BunPressConfig } from '@stacksjs/bunpress'
5
+
6
+ export default {
7
+ verbose: false,
8
+
9
+ markdown: {
10
+ toc: {
11
+ enabled: true,
12
+ position: 'sidebar',
13
+ minDepth: 2,
14
+ maxDepth: 3,
15
+ },
16
+ features: {
17
+ inlineFormatting: true,
18
+ containers: true,
19
+ githubAlerts: true,
20
+ codeBlocks: {
21
+ lineNumbers: true,
22
+ lineHighlighting: true,
23
+ focus: true,
24
+ diff: true,
25
+ errorWarning: true,
26
+ },
27
+ codeGroups: true,
28
+ codeImports: true,
29
+ inlineToc: true,
30
+ customAnchors: true,
31
+ emoji: true,
32
+ badges: true,
33
+ includes: true,
34
+ externalLinks: {
35
+ enabled: true,
36
+ openInNewTab: true,
37
+ addIcon: true,
38
+ },
39
+ imageLazyLoading: true,
40
+ tables: {
41
+ responsive: true,
42
+ striped: true,
43
+ hover: true,
44
+ },
45
+ },
46
+ },
47
+
48
+ nav: [
49
+ { text: 'Home', link: '/' },
50
+ { text: 'Guide', link: '/guide/' },
51
+ ],
52
+
53
+ sitemap: {
54
+ hostname: 'https://example.com',
55
+ },
56
+ } satisfies BunPressConfig
57
+ `;try{return await Bun.write(Z,Q),T(`Created ${Z}`),!0}catch($){return A(`Failed to create configuration: ${$}`),!1}}import{existsSync as k}from"fs";import{join as P}from"path";function I4(){let Z=["bunpress","docs"].flatMap(($)=>[`${$}.config`,`.${$}.config`,$,`.${$}`]),Q=[".ts",".js",".mjs",".cjs",".json"];return Z.flatMap(($)=>Q.map((Y)=>`${$}${Y}`))}async function x4(K={}){let Z=K.verbose||!1,Q=[];console.log(z(`
58
+ Running diagnostics...
59
+ `,"bold")),Q.push({name:"Bun Runtime",status:"pass",message:`v${Bun.version}`});let $=I4().find((W)=>k(P(process.cwd(),W)));if($)Q.push({name:"Configuration",status:"pass",message:$});else Q.push({name:"Configuration",status:"pass",message:"using defaults (no config file)",detail:`Looked for: ${I4().join(", ")}`});let Y=K.dir||O.docsDir||"./docs",X=P(process.cwd(),Y);if(k(X)){let{Glob:W}=awaitPromise.resolve(globalThis.Bun),E=new W("**/*.md"),x=0;for await(let j of E.scan(X))x++;Q.push({name:"Documentation",status:x>0?"pass":"warn",message:`${x} markdown files in ${Y}`,fix:x>0?void 0:`Add a .md file under ${Y}, or run "bunpress new index"`})}else Q.push({name:"Documentation",status:"fail",message:`${Y} not found`,fix:'Run "bunpress init" to create the docs directory',detail:`Resolved from ${K.dir?"--dir":O.docsDir?"config docsDir":"the default"}`});let H=P(process.cwd(),"package.json");if(k(H)){let W=await Bun.file(H).json(),E=W.scripts?.dev,x=W.scripts?.build;Q.push({name:"Package Scripts",status:E&&x?"pass":"warn",message:`dev: ${E?"\u2713":"\u2717"}, build: ${x?"\u2713":"\u2717"}`,fix:E&&x?void 0:'Add "dev": "bunpress dev" and "build": "bunpress build" to package.json scripts'});let j=W.dependencies?.["@stacksjs/bunpress"]||W.devDependencies?.["@stacksjs/bunpress"];if(W.name==="@stacksjs/bunpress"||k(P(process.cwd(),"packages","bunpress","package.json")))Q.push({name:"BunPress Package",status:"pass",message:"this is the BunPress source repository"});else Q.push({name:"BunPress Package",status:j?"pass":"warn",message:j||"not declared in package.json",fix:j?void 0:'Run "bun add -d @stacksjs/bunpress"'})}else Q.push({name:"Package.json",status:"warn",message:"Not found",fix:'Run "bun init" to create one'});let N=P(process.cwd(),"node_modules");if(k(N))Q.push({name:"Dependencies",status:"pass",message:"node_modules found"});else Q.push({name:"Dependencies",status:"warn",message:"node_modules not found",fix:'Run "bun install"'});let _=P(process.cwd(),".git");if(k(_))Q.push({name:"Git Repository",status:"pass",message:"Initialized"});else Q.push({name:"Git Repository",status:"warn",message:"Not initialized",fix:'Run "git init" \u2014 without it, "last updated" falls back to file timestamps'});let R=P(process.cwd(),"tsconfig.json");if(k(R))Q.push({name:"TypeScript",status:"pass",message:"tsconfig.json found"});else Q.push({name:"TypeScript",status:"warn",message:"tsconfig.json not found",fix:"Only needed for a TypeScript config file \u2014 safe to ignore otherwise"});for(let W of Q){let E=W.status==="pass"?"\u2713":W.status==="fail"?"\u2717":"\u26A0",x=W.status==="pass"?"green":W.status==="fail"?"red":"yellow";if(console.log(` ${z(E,x)} ${W.name}: ${z(W.message,"dim")}`),Z&&W.detail)console.log(` ${z(W.detail,"dim")}`)}console.log();let q=Q.filter((W)=>W.status==="pass").length,G=Q.filter((W)=>W.status==="fail").length,V=Q.filter((W)=>W.status==="warn").length,U=Q.filter((W)=>W.status!=="pass"&&W.fix);if(U.length>0){B("Recommended actions:");for(let W of U)console.log(` \u2022 ${W.fix}`);console.log()}if(G>0)return A(`${G} checks failed, ${V} warnings`),!1;if(V>0)return h(`${q} checks passed, ${V} warnings`),!0;return T(`All ${q} checks passed!`),!0}import{mkdir as Q4}from"fs/promises";var U6=`import type { BunPressConfig } from '@stacksjs/bunpress'
60
+
61
+ export default {
62
+ verbose: false,
63
+
64
+ markdown: {
65
+ toc: {
66
+ enabled: true,
67
+ position: 'sidebar',
68
+ minDepth: 2,
69
+ maxDepth: 3,
70
+ },
71
+ features: {
72
+ inlineFormatting: true,
73
+ containers: true,
74
+ githubAlerts: true,
75
+ codeBlocks: {
76
+ lineNumbers: true,
77
+ lineHighlighting: true,
78
+ focus: true,
79
+ diff: true,
80
+ errorWarning: true,
81
+ },
82
+ codeGroups: true,
83
+ codeImports: true,
84
+ inlineToc: true,
85
+ customAnchors: true,
86
+ emoji: true,
87
+ badges: true,
88
+ includes: true,
89
+ externalLinks: {
90
+ enabled: true,
91
+ openInNewTab: true,
92
+ addIcon: true,
93
+ },
94
+ imageLazyLoading: true,
95
+ tables: {
96
+ responsive: true,
97
+ striped: true,
98
+ hover: true,
99
+ },
100
+ },
101
+ },
102
+
103
+ nav: [
104
+ { text: 'Home', link: '/' },
105
+ { text: 'Guide', link: '/guide/' },
106
+ { text: 'GitHub', link: 'https://github.com/stacksjs/bunpress' },
107
+ ],
108
+
109
+ sitemap: {
110
+ hostname: 'https://example.com',
111
+ },
112
+ } satisfies BunPressConfig
113
+ `,B6=`---
114
+ layout: home
115
+ title: Welcome to My Documentation
116
+
117
+ hero:
118
+ name: My Project
119
+ text: Modern documentation made easy
120
+ tagline: Fast, flexible, and beautiful documentation powered by BunPress
121
+ actions:
122
+ - theme: brand
123
+ text: Get Started
124
+ link: /guide/
125
+ - theme: alt
126
+ text: View on GitHub
127
+ link: https://github.com/yourusername/your-repo
128
+
129
+ features:
130
+ - icon: \u26A1
131
+ title: Lightning Fast
132
+ details: Powered by Bun runtime for incredible build and dev server performance
133
+ - icon: \uD83C\uDFA8
134
+ title: Beautiful by Default
135
+ details: Clean, modern design with dark mode support out of the box
136
+ - icon: \uD83D\uDCDD
137
+ title: Markdown Enhanced
138
+ details: Extended markdown features including containers, code groups, and more
139
+ ---
140
+
141
+ # Welcome
142
+
143
+ This is your new BunPress documentation site. Start editing files in the \`docs/\` directory to customize your content.
144
+ `,T6=`# Getting Started
145
+
146
+ Welcome to the getting started guide!
147
+
148
+ ## Installation
149
+
150
+ \`\`\`bash
151
+ bun install @stacksjs/bunpress
152
+ \`\`\`
153
+
154
+ ## Quick Start
155
+
156
+ Create your first documentation page:
157
+
158
+ \`\`\`bash
159
+ bunpress new my-page
160
+ \`\`\`
161
+
162
+ ## Next Steps
163
+
164
+ ::: tip
165
+ Check out the [markdown extensions](/guide/markdown) to learn about all the powerful features available.
166
+ :::
167
+
168
+ - Learn about [configuration](/guide/configuration)
169
+ - Explore [advanced features](/guide/advanced)
170
+ - Read the [API reference](/api/)
171
+ `,z6=`node_modules/
172
+ dist/
173
+ .DS_Store
174
+ *.log
175
+ .env
176
+ .env.*
177
+ !.env.example
178
+ `,O6=`# My BunPress Documentation
179
+
180
+ Documentation powered by [BunPress](https://github.com/stacksjs/bunpress).
181
+
182
+ ## Development
183
+
184
+ Start the dev server:
185
+
186
+ \`\`\`bash
187
+ bun run dev
188
+ \`\`\`
189
+
190
+ ## Build
191
+
192
+ Build the documentation:
193
+
194
+ \`\`\`bash
195
+ bun run build
196
+ \`\`\`
197
+
198
+ ## Preview
199
+
200
+ Preview the built site:
201
+
202
+ \`\`\`bash
203
+ bun run preview
204
+ \`\`\`
205
+ `;async function E4(K={}){try{if(await Bun.file("./docs").exists()&&!K.force){if(!await a("Documentation directory already exists. Continue?",!1))return B("Initialization cancelled"),!1}let Q=new C("Initializing BunPress project...");Q.start(),await Q4("./docs",{recursive:!0}),await Q4("./docs/guide",{recursive:!0}),await Q4("./docs/public",{recursive:!0}),await Bun.write("./bunpress.config.ts",U6),await Bun.write("./docs/index.md",B6),await Bun.write("./docs/guide/index.md",T6);let $=await Bun.file("./.gitignore").exists();if(!$)await Bun.write("./.gitignore",z6);let Y=await Bun.file("./README.md").exists();if(!Y)await Bun.write("./README.md",O6);let X="./package.json";if(await Bun.file(X).exists()){let N=await Bun.file(X).json();N.scripts=N.scripts||{},N.scripts.dev=N.scripts.dev||"bunpress dev",N.scripts.build=N.scripts.build||"bunpress build",N.scripts.preview=N.scripts.preview||"bunpress preview",await Bun.write(X,JSON.stringify(N,null,2))}if(Q.succeed("BunPress project initialized successfully!"),console.log(),T("Created files:"),console.log(" \u2022 bunpress.config.ts"),console.log(" \u2022 docs/index.md"),console.log(" \u2022 docs/guide/index.md"),console.log(" \u2022 docs/public/"),!$)console.log(" \u2022 .gitignore");if(!Y)console.log(" \u2022 README.md");return console.log(),B("Next steps:"),console.log(" 1. Install BunPress: bun add @stacksjs/bunpress"),console.log(" 2. Start dev server: bun run dev"),console.log(" 3. Edit docs/index.md to customize your home page"),!0}catch(Z){return A(`Failed to initialize project: ${Z}`),!1}}import{mkdir as L6}from"fs/promises";import{dirname as I6,join as x6}from"path";var S4={default:(K)=>`---
206
+ title: ${K}
207
+ description:
208
+ ---
209
+
210
+ # ${K}
211
+
212
+ Your content goes here...
213
+ `,guide:(K)=>`---
214
+ title: ${K}
215
+ description: ${K} guide
216
+ ---
217
+
218
+ # ${K}
219
+
220
+ ## Introduction
221
+
222
+ Brief introduction to the topic.
223
+
224
+ ## Getting Started
225
+
226
+ Step-by-step instructions.
227
+
228
+ ## Examples
229
+
230
+ \`\`\`typescript
231
+ // Example code
232
+ \`\`\`
233
+
234
+ ## Next Steps
235
+
236
+ - [ ] Task 1
237
+ - [ ] Task 2
238
+ `,api:(K)=>`---
239
+ title: ${K}
240
+ description: API reference for ${K}
241
+ ---
242
+
243
+ # ${K}
244
+
245
+ ## Overview
246
+
247
+ Brief overview of the API.
248
+
249
+ ## Methods
250
+
251
+ ### \`methodName()\`
252
+
253
+ Description of the method.
254
+
255
+ **Parameters:**
256
+
257
+ - \`param1\` (\`type\`) - Description
258
+
259
+ **Returns:**
260
+
261
+ - \`ReturnType\` - Description
262
+
263
+ **Example:**
264
+
265
+ \`\`\`typescript
266
+ // Example usage
267
+ \`\`\`
268
+ `,blog:(K)=>`---
269
+ title: ${K}
270
+ description:
271
+ date: ${new Date().toISOString().split("T")[0]}
272
+ author:
273
+ tags: []
274
+ ---
275
+
276
+ # ${K}
277
+
278
+ Post content goes here...
279
+
280
+ ## Section 1
281
+
282
+ Content...
283
+ `};async function F4(K,Z={}){try{let Q=K.endsWith(".md")?K:`${K}.md`,$=x6(process.cwd(),"docs",Q);if(await Bun.file($).exists())return A(`File already exists: ${Q}`),!1;let X=Z.title;if(!X)X=(Q.split("/").pop()?.replace(".md","")||"").split("-").map((G)=>G.charAt(0).toUpperCase()+G.slice(1)).join(" ");let H=Z.template||"default",N=S4[H];if(!N)return A(`Unknown template: ${H}`),A(`Available templates: ${Object.keys(S4).join(", ")}`),!1;let _=N(X),R=I6($);return await L6(R,{recursive:!0}),await Bun.write($,_),T(`Created ${Q}`),console.log(),console.log(` Title: ${X}`),console.log(` Template: ${H}`),console.log(` Path: ${$}`),!0}catch(Q){return A(`Failed to create file: ${Q}`),!1}}import{join as s}from"path";async function D4(K={}){let Z=K.port||3000,Q=await O,$=K.outdir||Q.outDir||"./dist",Y=s($,".bunpress"),X=K.verbose||!1;try{let{stat:H}=await import("fs/promises");try{if(!(await H(Y)).isDirectory())A(`"${Y}" is not a directory.`),A('Run "bunpress build" first to generate the documentation.'),process.exit(1)}catch{A(`Build directory "${Y}" not found.`),A('Run "bunpress build" first to generate the documentation.'),process.exit(1)}B(`Starting preview server from ${Y}`);try{let N=Bun.serve({port:Z,fetch:async(_)=>{let q=new URL(_.url).pathname;if(q.startsWith("/"))q=q.slice(1);if(q===""||q==="/")q="index.html";let G=[q,`${q}.html`,s(q,"index.html")];for(let U of G){let W=Bun.file(s(Y,U));if(await W.exists())return new Response(W,{headers:{"Content-Type":E6(U)}})}let V=Bun.file(s(Y,"404.html"));if(await V.exists())return new Response(V,{status:404,headers:{"Content-Type":"text/html"}});return new Response("404 - Not Found",{status:404})}});T(`Preview server running at http://localhost:${Z}`),console.log(`Press Ctrl+C to stop
284
+ `),await new Promise(()=>{})}catch(N){if(N.message?.includes("EADDRINUSE")||N.code==="EADDRINUSE")A(`Port ${Z} is already in use.`),A("Try running with a different port: bunpress preview --port <port>"),A(`Or stop any processes using port ${Z}`);else A(`Failed to start server: ${N.message||N}`);process.exit(1)}}catch(H){A(`Failed to start preview server: ${H}`),process.exit(1)}}function E6(K){let Z=K.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",mjs:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",map:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",webmanifest:"application/manifest+json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject"}[Z||""]||"application/octet-stream"}import*as b from"fs";import*as D from"path";var{YAML:C4}=globalThis.Bun;async function k4(K={}){let Z=await O,Q=K.dir||Z.docsDir||"./docs",$=K.fix||!1;if(B("\uD83D\uDD0D Running SEO checks..."),console.log(""),!b.existsSync(Q))A(`Documentation directory not found: ${Q}`),process.exit(1);let Y={totalPages:0,errors:[],warnings:[],passed:0},X=await y6(Q);Y.totalPages=X.length;for(let H of X)await S6(H,Q,Y,$);if(F6(Z,Q,Y),P6(Y),Y.errors.length>0)process.exit(1)}async function S6(K,Z,Q,$){let Y=await b.promises.readFile(K,"utf-8"),{frontmatter:X,markdown:H}=w6(Y),N=D.relative(Z,K),_=!1,R=$&&Object.keys(X).length>0,q={...X},G=X.layout==="home"?X.hero?.text||X.hero?.name:void 0;if(!X.title&&G);else if(!X.title){let W=b6(H);if(!W)Q.errors.push({type:"error",category:"Title",file:N,message:"Missing title in frontmatter"}),_=!0;else if($)q.title=W,R=!0,B(`\u2713 Added title to ${N}: "${W}"`);else Q.warnings.push({type:"warning",category:"Title",file:N,message:`No title in frontmatter (could extract: "${W}")`}),_=!0}else{let W=X.title.length;if(W>60)Q.warnings.push({type:"warning",category:"Title",file:N,message:`Title too long (${W} chars, recommended <60)`}),_=!0;else if(W<10)Q.warnings.push({type:"warning",category:"Title",file:N,message:`Title too short (${W} chars, recommended >10)`}),_=!0}if(!X.description){let W=v6(H);if($)q.description=W,R=!0,B(`\u2713 Added description to ${N}`);else Q.warnings.push({type:"warning",category:"Description",file:N,message:"Missing description in frontmatter"}),_=!0}else{let W=X.description.length;if(W>160)Q.warnings.push({type:"warning",category:"Description",file:N,message:`Description too long (${W} chars, recommended <160)`}),_=!0;else if(W<50)Q.warnings.push({type:"warning",category:"Description",file:N,message:`Description too short (${W} chars, recommended >50)`}),_=!0}let V=C6(H,Z,K);for(let W of V)Q.errors.push({type:"error",category:"Links",file:N,message:`Broken internal link: ${W}`}),_=!0;let U=k6(H);for(let W of U)Q.warnings.push({type:"warning",category:"Images",file:N,message:`Image missing alt text: ${W}`}),_=!0;if(R){let W=D6(q,H);await b.promises.writeFile(K,W,"utf-8")}if(!_)Q.passed++}function F6(K,Z,Q){let $=new Set,Y=(N,_)=>{if(typeof N!=="string"||!N.startsWith("/"))return;let R=`${_}:${N}`;if($.has(R))return;$.add(R);let[q,G]=N.split("#"),V=P4(D.resolve(Z,`.${q}`));if(!V){Q.errors.push({type:"error",category:"Links",file:_,message:`Broken link: ${N}`});return}if(G&&!Z4(V).has(G))Q.errors.push({type:"error",category:"Links",file:_,message:`Broken anchor: ${N}`})},X=(N,_)=>{if(!Array.isArray(N))return;for(let R of N){if(!R||typeof R!=="object")continue;let q=R;Y(q.link,_),X(q.items,_)}};X(K.nav,"config nav"),X(K.themeConfig?.nav,"themeConfig nav");let H=[[K.markdown?.sidebar,"config sidebar"],[K.themeConfig?.sidebar,"themeConfig sidebar"]];for(let[N,_]of H)if(Array.isArray(N))X(N,_);else if(N&&typeof N==="object")for(let[R,q]of Object.entries(N))X(q,`${_} ${R}`)}function D6(K,Z){return`---
285
+ ${C4.stringify(K,null,2)}
286
+ ---
287
+ ${Z}`}async function y6(K){let Z=[];async function Q($){let Y=await b.promises.readdir($,{withFileTypes:!0});for(let X of Y){let H=D.join($,X.name);if(X.isDirectory()){if(!X.name.startsWith(".")&&X.name!=="node_modules"&&X.name!=="public")await Q(H)}else if(X.isFile()&&X.name.endsWith(".md"))Z.push(H)}}return await Q(K),Z}function w6(K){let Z=/^---\n([\s\S]*?)\n---\n?/,Q=K.match(Z);if(!Q)return{frontmatter:{},markdown:K};let $=Q[1],Y=K.slice(Q[0].length);try{return{frontmatter:C4.parse($),markdown:Y}}catch{return{frontmatter:{},markdown:K}}}function b6(K){let Z=K.match(/^#\s+(.+)$/m);return Z?Z[1].trim():null}function v6(K,Z=155){let Q=K.replace(/^#{1,6}\s+.+$/gm,"").replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,"").replace(/!\[.*?\]\(.*?\)/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/[*_~]/g,"").trim(),$=Q.split(`
288
+
289
+ `)[0]||Q;if($.length>Z)return`${$.slice(0,Z)}...`;return $||"Documentation page"}function C6(K,Z,Q){let $=[],Y=/\[([^\]]+)\]\(([^)]+)\)/g,X=$4(K).replace(/`+[^`\n]*`+/g,"").replace(/<!--[\s\S]*?-->/g,""),H;while((H=Y.exec(X))!==null){let N=H[2].trim();if(/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(N))continue;let _=N.includes("#")?N.slice(N.indexOf("#")+1):"";if(N.startsWith("#")){if(_&&!Z4(Q).has(_))$.push(N);continue}let R=N.split("#",1)[0].split("?",1)[0];if(!R)continue;let q;try{q=decodeURIComponent(R.replace(/^<|>$/g,""))}catch{$.push(N);continue}let G=q.startsWith("/")?D.resolve(Z,`.${q}`):D.resolve(D.dirname(Q),q),V=P4(G);if(!V){$.push(N);continue}if(_&&!Z4(V).has(_))$.push(N)}return $}function P4(K){let Z=K.endsWith(".md")?[K]:[K,`${K}.md`,D.join(K,"index.md")];for(let Q of Z)try{if(b.statSync(Q).isFile())return Q}catch{}return null}var y4=new Map;function Z4(K){let Z=y4.get(K);if(Z)return Z;let Q=new Set;try{let $=$4(b.readFileSync(K,"utf8"));for(let Y of $.split(`
290
+ `)){let X=Y.match(/^#{1,6}\s+(.*)$/);if(!X)continue;let H=X[1].trim(),N=H.match(/\{#([\w-]+)\}\s*$/),_=N?N[1]:b4(w4(H));if(!_)continue;v4(_,Q)}}catch{}return y4.set(K,Q),Q}function k6(K){let Z=[],Q=/!\[([^\]]*)\]\(([^)]+)\)/g,$;while(($=Q.exec(K))!==null){let Y=$[1],X=$[2];if(!Y||Y.trim()==="")Z.push(X)}return Z}function P6(K){if(console.log(""),B("\uD83D\uDCCA SEO Report"),console.log(""),console.log(`Total pages checked: ${z(K.totalPages.toString(),"blue")}`),console.log(`Passed: ${z(K.passed.toString(),"green")}`),console.log(`Errors: ${z(K.errors.length.toString(),K.errors.length>0?"red":"green")}`),console.log(`Warnings: ${z(K.warnings.length.toString(),K.warnings.length>0?"yellow":"green")}`),console.log(""),K.errors.length>0){A(`\u2717 ${K.errors.length} errors found:`),console.log("");let Z=K.errors.map((Q)=>({Category:Q.category,File:Q.file,Message:Q.message}));g(Z),console.log("")}if(K.warnings.length>0){h(`\u26A0 ${K.warnings.length} warnings found:`),console.log("");let Z=K.warnings.map((Q)=>({Category:Q.category,File:Q.file,Message:Q.message}));g(Z),console.log("")}if(K.errors.length===0&&K.warnings.length===0)T("\u2713 All SEO checks passed!");else if(K.errors.length===0)T("\u2713 No errors found (only warnings)")}import{join as h6}from"path";async function m6(K){let Z=await Bun.file(K).text(),Q=Z.split(`
291
+ `),$=0,Y=!1,X=[];for(let R of Q){if(R.trim().startsWith("```")){Y=!Y;continue}if(!Y)X.push(R)}$=X.join(" ").split(/\s+/).filter((R)=>R.length>0).length;let N=Q.filter((R)=>R.match(/^#{1,6}\s+/)).length,_=(Z.match(/```/g)||[]).length/2;return{path:K,size:await n(K),lines:Q.length,words:$,headings:N,codeBlocks:Math.floor(_)}}async function h4(K={}){let Z=await O,Q=K.dir||Z.docsDir||"./docs",$=K.verbose||!1;try{console.log(z(`
292
+ Analyzing documentation...
293
+ `,"bold"));let{Glob:Y}=awaitPromise.resolve(globalThis.Bun),X=new Y("**/*.md"),H=[];for await(let j of X.scan(Q)){let J=h6(Q,j),f=await m6(J);H.push(f)}if(H.length===0)return A("No markdown files found"),!1;let N=H.reduce((j,J)=>j+J.size,0),_=H.reduce((j,J)=>j+J.lines,0),R=H.reduce((j,J)=>j+J.words,0),q=H.reduce((j,J)=>j+J.headings,0),G=H.reduce((j,J)=>j+J.codeBlocks,0);if(console.log(z("Summary","bold")),console.log("\u2500".repeat(50)),console.log(`Files: ${H.length}`),console.log(`Total size: ${w(N)}`),console.log(`Total lines: ${_.toLocaleString()}`),console.log(`Total words: ${R.toLocaleString()}`),console.log(`Headings: ${q}`),console.log(`Code blocks: ${G}`),console.log(),$){console.log(z("Per-file Statistics","bold")),console.log("\u2500".repeat(50));let j=H.map((J)=>({File:J.path.replace(`${Q}/`,""),Size:w(J.size),Lines:J.lines,Words:J.words,Headings:J.headings,"Code Blocks":J.codeBlocks}));g(j),console.log()}let V=N/H.length,U=_/H.length,W=R/H.length;console.log(z("Averages per File","bold")),console.log("\u2500".repeat(50)),console.log(`Size: ${w(V)}`),console.log(`Lines: ${Math.round(U)}`),console.log(`Words: ${Math.round(W)}`),console.log();let E=[...H].sort((j,J)=>J.size-j.size).slice(0,5);if(E.length>0){console.log(z("Top 5 Largest Files","bold")),console.log("\u2500".repeat(50));for(let j of E){let J=j.path.replace(`${Q}/`,"");console.log(` ${J.padEnd(40)} ${w(j.size)}`)}console.log()}let x=Math.ceil(R/200);return B(`Estimated reading time: ${x} minutes`),!0}catch(Y){return A(`Failed to generate statistics: ${Y}`),!1}}var L=new l6("bunpress"),M={outdir:O.outDir||"./dist",docsdir:O.docsDir||"./docs",port:3000,open:!0,watch:!0,verbose:O.verbose};async function a6(K,Z,Q=!1){let $=`${Z}/public`;try{await p6($);let Y=new g6("**/*");for await(let X of Y.scan($)){let H=v($,X),N=v(K,X);await c6(v(K,X.split("/").slice(0,-1).join("/")),{recursive:!0}),await f6(H,N)}}catch{if(Q)console.log("No public directory found, skipping static assets copy")}}async function n6(K,Z,Q,$){if((Q.search??Q.markdown?.search)?.enabled===!1)return;try{let Y=await u4(K,Q);if(await Bun.write(v(Z,d4.replace(/^\//,"")),JSON.stringify(Y)),$)console.log(`Indexed ${Y.length} sections for search.`)}catch(Y){if($)console.error("Error generating search index:",Y)}}async function i6(K,Z,Q,$){try{if(Q.sitemap?.enabled!==!1&&i(Q))await p4(K,Z,Q);if(Q.robots?.enabled!==!1)await c4(Z,Q);if(Q.rss?.enabled)await f4(K,Z,Q,Q.rss)}catch(Y){if($)console.error("Error generating SEO files:",Y)}}async function s6(K={}){let Z=await O;if(!K.config)return Z;let Q=u6(S.cwd(),K.config);if(!d6(Q))throw Error(`Config file not found: ${Q}`);let $=await import(Q),Y=$.default??$;return g4({...Z,...Y})}async function m4(K={}){if(K.manifest&&K.checkManifest)throw Error("--manifest and --check-manifest are mutually exclusive");let Z=await s6(K),Q=K.outdir||Z.outDir||M.outdir,$=v(Q,".bunpress"),Y=K.dir||Z.docsDir||M.docsdir,X=K.verbose??M.verbose,H=performance.now(),N=new C("Building documentation...");if(!X)N.start();try{let _=await G4($,async(q)=>{let G=await r(Y);if(G.length===0)throw Error("No markdown files found in docs directory");if(X)console.log(`Found ${G.length} markdown files:`),G.forEach((y)=>console.log(`- ${y}`));let{markdownToHtml:V,wrapInLayout:U}=await import("./chunk-amkb7f82.js"),{loadI18nTranslations:W,resolveI18nConfig:E}=await import("./chunk-3z2k0ntf.js"),{mkdir:x,writeFile:j}=await import("fs/promises"),J=await W(E(Z),Z);if(X)console.log("Transforming markdown to HTML...");let f=l4(G,Y,J),Y4=f.pages;for(let y of Y4){let a4=await Bun.file(y.sourceFile).text(),{html:n4,frontmatter:N4}=await V(a4,Y,{page:y,catalog:f}),m=y.relativePath,i4=`/${m}`,s4=N4.layout||"doc",r4=await U(n4,Z,i4,s4,N4,{i18n:J,locale:y.locale,sourceFile:y.sourceFile,docsDir:Y}),o4=m==="index"||m.endsWith("/index"),H4=y.locale&&y.locale!==J.defaultLocale&&J.enabled?v(q,y.locale):q,c=o4?v(H4,`${m}.html`):v(H4,m,"index.html"),_4=c.substring(0,c.lastIndexOf("/"));if(_4)await x(_4,{recursive:!0});if(await j(c,r4),X)console.log(`Generated: ${c}`)}if(X)console.log(`Processed ${G.length} markdown files into ${Y4.length} pages.`);if(await a6(q,Y,X),await o6(q),await r6(q,Z),K.searchIndex!==!1)await n6(Y,q,Z,X||!1);if(await i6(Y,q,Z,X||!1),K.checkManifest)await U4(q,K.checkManifest,p);return G.length},async()=>{if(K.manifest)await M4($,K.manifest,p)}),R=performance.now()-H;if(!X)N.succeed(`Built ${_} pages to HTML in ${t(R)}`);else T(`Build completed in ${t(R)}`),console.log(`
294
+ Generated ${_} HTML files in ${$}`);return!0}catch(_){if(!X)N.fail("Build failed");return console.error("Error during build:",_),!1}}async function r6(K,Z){let{getConfiguredBasePath:Q,wrapInLayout:$}=await import("./chunk-amkb7f82.js"),X=`
295
+ <style>
296
+ .NotFound {
297
+ padding: 64px 24px 96px;
298
+ text-align: center;
299
+ }
300
+
301
+ @media (min-width: 768px) {
302
+ .NotFound {
303
+ padding: 96px 32px 168px;
304
+ }
305
+ }
306
+
307
+ .NotFound .code {
308
+ line-height: 64px;
309
+ font-size: 64px;
310
+ font-weight: 600;
311
+ }
312
+
313
+ .NotFound .title {
314
+ padding-top: 12px;
315
+ letter-spacing: 2px;
316
+ line-height: 20px;
317
+ font-size: 20px;
318
+ font-weight: 700;
319
+ }
320
+
321
+ .NotFound .divider {
322
+ margin: 24px auto 18px;
323
+ width: 64px;
324
+ height: 1px;
325
+ background-color: var(--vp-c-divider);
326
+ }
327
+
328
+ .NotFound .quote {
329
+ margin: 0 auto;
330
+ max-width: 256px;
331
+ font-size: 14px;
332
+ font-weight: 500;
333
+ color: var(--vp-c-text-2);
334
+ }
335
+
336
+ .NotFound .action {
337
+ padding-top: 20px;
338
+ }
339
+
340
+ .NotFound .link {
341
+ display: inline-block;
342
+ border: 1px solid var(--vp-c-brand-1);
343
+ border-radius: 16px;
344
+ padding: 3px 16px;
345
+ font-size: 14px;
346
+ font-weight: 500;
347
+ color: var(--vp-c-brand-1);
348
+ transition: border-color 0.25s, color 0.25s;
349
+ text-decoration: none;
350
+ }
351
+
352
+ .NotFound .link:hover {
353
+ border-color: var(--vp-c-brand-2);
354
+ color: var(--vp-c-brand-2);
355
+ }
356
+ </style>
357
+
358
+ <div class="NotFound">
359
+ <p class="code">404</p>
360
+ <h1 class="title">PAGE NOT FOUND</h1>
361
+ <div class="divider"></div>
362
+ <blockquote class="quote">
363
+ But if you don't change your direction, and if you keep looking, you may end up where you are heading.
364
+ </blockquote>
365
+ <div class="action">
366
+ <a class="link" href="${`${Q(Z)}/`}" aria-label="go to home">
367
+ Take me home
368
+ </a>
369
+ </div>
370
+ </div>
371
+ `,H=await $(X,Z,"/404","doc");await Bun.write(v(K,"404.html"),H)}async function o6(K){let Z=v(K,"index.html");try{if(!await Bun.file(Z).exists())console.error("Warning: No index.html found at root")}catch(Q){console.error("Error checking root index.html:",Q)}}L.command("build","Build the documentation site").option("--outdir <outdir>","Output directory").option("--dir <dir>","Documentation directory").option("--config <config>","Path to config file").option("--minify","Minify output files",{default:!1}).option("--sourcemap","Generate source maps",{default:!1}).option("--manifest <path>","Write a deterministic rendered-tree manifest").option("--check-manifest <path>","Fail unless the rendered tree matches a checked manifest").option("--search-index","Write the client search index (on by default; --no-search-index skips it)",{default:!0}).option("--watch","Watch for changes and rebuild",{default:!1}).option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{if(!await m4(K))S.exit(1);if(K.watch){let{watch:Q}=await import("fs"),$=await O,Y=K.dir||$.docsDir||"./docs";console.log(`
372
+ Watching for changes...`),Q(Y,{recursive:!0},async(X,H)=>{if(H&&H.endsWith(".md"))console.log(`
373
+ Detected change in ${H}, rebuilding...`),await m4(K)}),await new Promise(()=>{})}});L.command("dev","Build and serve documentation using BunPress server").option("--port <port>","Port to listen on",{default:M.port}).option("--dir <dir>","Documentation directory").option("--watch","Watch for changes",{default:M.watch}).option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{let Z=await O,Q=K.port||M.port,$=K.dir||Z.docsDir||M.docsdir,Y=K.watch??M.watch,X=K.verbose??M.verbose;if(X)console.log("Starting BunPress dev server with options:",{port:Q,root:$,watch:Y,verbose:X});let{serveCLI:H}=await import("./chunk-amkb7f82.js");await H({port:Q,root:$,watch:Y,config:Z})});async function t6(K={}){let Z=await O,Q=K.dir||Z.docsDir||M.docsdir,$=K.output||"./docs.md",Y=K.full??!1,X=K.verbose??M.verbose;if(X)console.log(`Generating LLM markdown from ${Q}`),console.log(`Output file: ${$}`),console.log(`Full content: ${Y}`);let H=await r(Q);if(H.length===0)return console.log("No markdown files found in docs directory"),!1;if(X)console.log(`Found ${H.length} markdown files`);H.sort();let N=`# Documentation
374
+
375
+ `;N+=`Generated: ${new Date().toISOString()}
376
+
377
+ `,N+=`Total files: ${H.length}
378
+
379
+ `,N+=`---
380
+
381
+ `;for(let _ of H){let R=_.replace(`${Q}/`,""),q=await Bun.file(_).text();if(X)console.log(`Processing: ${R}`);if(N+=`## File: ${R}
382
+
383
+ `,Y)N+=q,N+=`
384
+
385
+ `;else{let G=q.split(`
386
+ `),V=!1,U="";for(let W of G){if(W.trim()==="---")if(!V){V=!0;continue}else{if(V=!1,U)N+="**Frontmatter:**\n```yaml\n",N+=U,N+="```\n\n",U="";continue}if(V){U+=`${W}
387
+ `;continue}if(W.match(/^#{1,6}\s+/))N+=`${W}
388
+ `}N+=`
389
+ `}N+=`---
390
+
391
+ `}return await Bun.write($,N),console.log(`
392
+ LLM markdown generated successfully: ${$}`),console.log(`Total size: ${(N.length/1024).toFixed(2)} KB`),!0}L.command("llm","Generate LLM-friendly markdown file from documentation").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--output <output>","Output file path",{default:"./docs.md"}).option("--full","Include full content (not just titles and headings)",{default:!1}).option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{if(!await t6(K))S.exit(1)});L.command("init","Initialize a new BunPress project").option("--name <name>","Project name").option("--template <template>","Template to use").option("--force","Overwrite existing files",{default:!1}).action(async(K)=>{if(!await E4(K))S.exit(1)});L.command("preview","Preview the built documentation site").option("--port <port>","Port to listen on",{default:M.port}).option("--outdir <outdir>","Output directory (looks for .bunpress folder inside)").option("--open","Open in browser",{default:!1}).option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{await D4(K)});L.command("clean","Clean build artifacts").option("--outdir <outdir>","Output directory to clean",{default:M.outdir}).option("--force","Skip confirmation prompt",{default:!1}).option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{if(!await T4(K))S.exit(1)});L.command("doctor","Run diagnostic checks on the project").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{if(!await x4(K))S.exit(1)});L.command("config:show","Show current configuration").option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{if(!await z4(K))S.exit(1)});L.command("config:validate","Validate configuration file").option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{if(!await O4(K))S.exit(1)});L.command("config:init","Initialize configuration file").action(async(K)=>{if(!await L4(K))S.exit(1)});L.command("new <path>","Create a new markdown file").option("--title <title>","Page title").option("--template <template>","Template to use (default, guide, api, blog)",{default:"default"}).option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K,Z)=>{if(!await F4(K,Z))S.exit(1)});L.command("stats","Show documentation statistics").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{if(!await h4(K))S.exit(1)});L.command("seo:check","Check SEO for all documentation pages").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--fix","Automatically fix issues (add missing titles/descriptions)",{default:!1}).action(async(K)=>{await k4(K)});L.command("deploy","Deploy documentation to AWS using CloudFormation (S3 + CloudFront + Route53)").option("--region <region>","AWS region for S3 bucket",{default:"us-east-1"}).option("--bucket <bucket>","S3 bucket name (auto-generated if not provided)").option("--domain <domain>","Custom domain (e.g., docs.example.com)").option("--subdomain <subdomain>","Subdomain (used with --base-domain)").option("--base-domain <baseDomain>","Base domain (e.g., example.com) - must have Route53 hosted zone").option("--stack-name <stackName>","CloudFormation stack name").option("--hosted-zone-id <hostedZoneId>","Route53 hosted zone ID (auto-detected from domain)").option("--certificate-arn <certificateArn>","ACM certificate ARN (auto-created if not provided)").option("--dry-run","Show configuration without deploying",{default:!1}).option("--verbose","Enable verbose logging",{default:M.verbose}).action(async(K)=>{let{deployCommand:Z}=await import("./chunk-a68w1rpw.js");if(!await Z(K))S.exit(1)});L.help();L.version(p);var X4=Bun.argv[1]||"",e6=X4.endsWith("/bunpress")||X4.endsWith("/cli.ts")||X4.endsWith("/cli.js");if(e6)L.parse();
393
+ export{T as p,A as q,B as r,C as s,s6 as t,m4 as u};
@@ -0,0 +1,2 @@
1
+ /** A complete replacement, serialized locally and locked against other build processes. */
2
+ export declare function withBuildOutput<T>(directory: string, render: (staging: string) => Promise<T>, afterPublish?: () => Promise<void>): Promise<T>;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Text from HTML back to text: `Raster &amp; heatmap` to `Raster & heatmap`.
3
+ * A page title is read from its rendered `<h1>`, and is escaped again where
4
+ * it is written; left encoded, `&` came out as `&amp;amp;` in the tab.
5
+ */
6
+ export declare function decodeHtmlEntities(value: string): string;
7
+ export declare function escapeHtmlAttribute(value: string): string;
package/dist/src/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{a as W,b as X,c as Y,d as Z,e as _,f as $,g as b,h as v,i as A,j as zj,k as Bj,l as Dj,m as Ej,n as Gj,o as Hj,p as Ij}from"../chunk-7jcye3th.js";import{A as u,B as w,x as j,y as k,z as q}from"../chunk-rcr6k1et.js";import{$ as wj,C as Q,D as S,E as T,F as V,K as p,L as f,M as c,N as d,O as g,P as a,Q as n,R as o,S as r,T as t,U as i,V as s,W as e,X as jj,Y as kj,Z as qj,_ as uj,aa as z,ba as B,ca as D}from"../chunk-3ymfys00.js";import{fa as F,ga as R,ha as U,ia as m,ja as x,ka as C,la as l,ma as h,na as y}from"../chunk-rnzqf7rp.js";export{Ej as wrapInLayout,Dj as stripConfiguredBasePath,Hj as startServer,U as splitLocaleFromPath,X as setLanguageAliases,Ij as serveCLI,F as resolveI18nConfig,W as resetHighlighter,d as reserveUniqueSlug,kj as processInlineTocSyntax,v as prewarmHighlighter,Y as normalizeLanguage,Gj as markdownToHtml,f as markdownHeadingText,m as localizeUrl,l as localeLabel,x as localeContentCandidates,R as loadI18nTranslations,Z as isLanguageSupported,$ as highlightCodeSync,_ as highlightCode,b as getSyntaxHighlightingStyles,A as getHighlighterInstance,Bj as getConfiguredBasePath,V as getConfig,g as generateUniqueSlug,uj as generateTocStyles,wj as generateTocScripts,jj as generateTocPositions,r as generateTocHtml,e as generateTocData,c as generateSlug,w as generateSitemap,i as generateSidebarTocHtml,k as generateRssFeed,q as generateRobotsTxt,y as generateLocaleDetectionScript,t as generateInlineTocHtml,h as generateHreflangTags,s as generateFloatingTocHtml,o as filterHeadings,a as extractHeadings,qj as enhanceHeadingsWithAnchors,p as defaultTocConfig,Q as defaultConfig,zj as decodeHtmlEntities,C as configForLocale,T as config,n as buildTocHierarchy,u as buildSitemap,B as buildSearchRuntimeConfig,D as buildSearchIndex,j as buildRssFeed,S as applyConfigPlugins,z as SEARCH_INDEX_PATH};
2
+ import{a as W,b as X,c as Y,d as Z,e as _,f as $,g as b,h as v,i as A,j as Bj,k as Dj,l as Ej,m as Gj,n as Hj,o as Ij}from"../chunk-m7y4g28p.js";import{v as j,w as k,x as q,y as u,z as w}from"../chunk-xjz041s0.js";import{$ as B,A as Q,B as S,C as T,D as V,I as p,J as f,K as c,L as d,M as g,N as a,O as n,P as o,Q as r,R as t,S as i,T as s,U as e,V as jj,W as kj,X as qj,Y as uj,Z as wj,_ as z,aa as D,ba as zj}from"../chunk-8rsrw3sw.js";import{ia as F,ja as R,ka as U,la as m,ma as x,na as C,oa as l,pa as h,qa as y}from"../chunk-ynp2pgxy.js";export{Ej as wrapInLayout,Dj as stripConfiguredBasePath,Hj as startServer,U as splitLocaleFromPath,X as setLanguageAliases,Ij as serveCLI,F as resolveI18nConfig,W as resetHighlighter,d as reserveUniqueSlug,kj as processInlineTocSyntax,v as prewarmHighlighter,Y as normalizeLanguage,Gj as markdownToHtml,f as markdownHeadingText,m as localizeUrl,l as localeLabel,x as localeContentCandidates,R as loadI18nTranslations,Z as isLanguageSupported,$ as highlightCodeSync,_ as highlightCode,b as getSyntaxHighlightingStyles,A as getHighlighterInstance,Bj as getConfiguredBasePath,V as getConfig,g as generateUniqueSlug,uj as generateTocStyles,wj as generateTocScripts,jj as generateTocPositions,r as generateTocHtml,e as generateTocData,c as generateSlug,w as generateSitemap,i as generateSidebarTocHtml,k as generateRssFeed,q as generateRobotsTxt,y as generateLocaleDetectionScript,t as generateInlineTocHtml,h as generateHreflangTags,s as generateFloatingTocHtml,o as filterHeadings,a as extractHeadings,qj as enhanceHeadingsWithAnchors,p as defaultTocConfig,Q as defaultConfig,zj as decodeHtmlEntities,C as configForLocale,T as config,n as buildTocHierarchy,u as buildSitemap,B as buildSearchRuntimeConfig,D as buildSearchIndex,j as buildRssFeed,S as applyConfigPlugins,z as SEARCH_INDEX_PATH};
@@ -0,0 +1,22 @@
1
+ import type { ResolvedI18n } from './i18n';
2
+ export declare function findMarkdownFiles(dir: string): Promise<string[]>;
3
+ /** One finite source/route snapshot, owned by one build or one dev request. */
4
+ export declare function createMarkdownPageCatalog(markdownFiles: readonly string[], docsDir: string, i18n: ResolvedI18n): MarkdownPageCatalog;
5
+ /** Parse actual anchor attributes; code text, images and external destinations stay intact. */
6
+ export declare function rewriteMarkdownSourceLinks(html: string, context: MarkdownPageContext, origins?: MarkdownLinkOrigins): Promise<string>;
7
+ export declare interface MarkdownPage {
8
+ readonly sourceFile: string
9
+ readonly relativePath: string
10
+ readonly locale: string
11
+ }
12
+ export declare interface MarkdownPageCatalog {
13
+ readonly pages: readonly MarkdownPage[]
14
+ findPage: (locale: string, path: string) => MarkdownPage | undefined
15
+ resolveLink: (page: MarkdownPage, destination: string) => string
16
+ }
17
+ export declare interface MarkdownPageContext {
18
+ readonly page: MarkdownPage
19
+ readonly catalog: MarkdownPageCatalog
20
+ }
21
+ /** Per-render boundaries for authored content expanded from another file. */
22
+ export type MarkdownLinkOrigins = Map<string, MarkdownPage | null>;
@@ -1,12 +1,8 @@
1
1
  import { config } from './config';
2
+ import { decodeHtmlEntities } from './html-entities';
2
3
  import type { BunPressConfig, Frontmatter } from './types';
4
+ import type { MarkdownPageContext } from './markdown-pages';
3
5
  import type { ResolvedI18n } from './i18n';
4
- /**
5
- * Text from HTML back to text: `Raster &amp; heatmap` to `Raster & heatmap`.
6
- * A page title is read from its rendered `<h1>`, and is escaped again where
7
- * it is written; left encoded, `&` came out as `&amp;amp;` in the tab.
8
- */
9
- export declare function decodeHtmlEntities(value: string): string;
10
6
  export declare function getConfiguredBasePath(config: BunPressConfig): string;
11
7
  export declare function stripConfiguredBasePath(config: BunPressConfig, pathname: string): string;
12
8
  export declare function wrapInLayout(content: string, siteConfig: BunPressConfig, currentPath: string, layout?: string, frontmatter?: Frontmatter, options?: WrapLayoutOptions): Promise<string>;
@@ -14,7 +10,7 @@ export declare function wrapInLayout(content: string, siteConfig: BunPressConfig
14
10
  * Convert markdown to HTML using Bun's built-in markdown parser
15
11
  * See: https://bun.com/docs/runtime/markdown
16
12
  */
17
- export declare function markdownToHtml(markdown: string, rootDir?: string): Promise<{ html: string, frontmatter: any }>;
13
+ export declare function markdownToHtml(markdown: string, rootDir?: string, pageContext?: MarkdownPageContext): Promise<{ html: string, frontmatter: any }>;
18
14
  /**
19
15
  * Start the BunPress documentation server
20
16
  */
@@ -52,3 +48,4 @@ export declare interface WrapLayoutOptions {
52
48
  sourceFile?: string
53
49
  docsDir?: string
54
50
  }
51
+ export { decodeHtmlEntities } from './html-entities';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/bunpress",
3
3
  "type": "module",
4
- "version": "0.2.21",
4
+ "version": "0.2.22",
5
5
  "description": "Modern documentation engine. Powered by Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",