refactor: refactor to 11ty to support Tencent Cloud EdgeOne Maker
continuous-integration/drone/push Build is failing

This commit is contained in:
2026-11-02 17:06:03 +08:00
parent 338858bd57
commit 21253ee102
174 changed files with 22956 additions and 30 deletions
+52
View File
@@ -0,0 +1,52 @@
import fs from 'node:fs';
import path from 'node:path';
import YAML from 'yaml';
import {parse as csv} from 'csv-parse/sync';
export const root=process.cwd();
export function walk(dir){return fs.existsSync(dir)?fs.readdirSync(dir,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name,'en')).flatMap(e=>e.isDirectory()?walk(path.join(dir,e.name)):[path.join(dir,e.name)]):[];}
export function read(file){return fs.readFileSync(path.resolve(root,file),'utf8');}
export function front(text){
const m=text.match(/^(?:---|\/\*\s*@frontmatter)\s*\r?\n([\s\S]*?)^(?:---|\*\/)\s*\r?\n?/m);
return m&&m.index===0?{data:YAML.parse(m[1])||{},body:text.slice(m[0].length)}:{data:{},body:text};
}
export function merge(a,b){const out={...a};for(const [k,v] of Object.entries(b))out[k]=v&&typeof v==='object'&&!Array.isArray(v)&&out[k]&&typeof out[k]==='object'&&!Array.isArray(out[k])?merge(out[k],v):v;return out;}
export function load(){
const config=YAML.parse(read('_config.yml'));
const data={};
for(const file of walk('theme/minimal-mistakes/_data')){
const ext=path.extname(file),name=path.basename(file,ext);
if(['.yml','.yaml'].includes(ext))data[name]=YAML.parse(read(file));
}
for(const file of walk('_data')){
const ext=path.extname(file),name=path.basename(file,ext);
if(['.yml','.yaml'].includes(ext))data[name]=merge(data[name]||{},YAML.parse(read(file)));
if(ext==='.csv')data[name]=csv(read(file),{columns:true,skip_empty_lines:true,bom:true}).map(row=>Object.fromEntries(Object.entries(row).map(([k,v])=>[k,v===''?null:v])));
}
const site={...config,data,posts:[],related_posts:[],time:new Date(process.env.SOURCE_DATE_EPOCH?Number(process.env.SOURCE_DATE_EPOCH)*1000:Date.now()).toISOString()};
const documents=[],urlMap=new Map();
function doc(file,collection){
const {data:meta,body}=front(read(file));let defaults={};
for(const d of config.defaults||[]){const s=d.scope||{};if((!s.type||s.type===collection)&&(!s.path||file.startsWith(s.path)))defaults=merge(defaults,d.values||{});}
const p=merge(defaults,meta);p.path=file;p.relative_path=file;p.collection=collection||p.collection;p.explicitDate=!!p.date;
if(collection&&!p.date)p.date=new Date(process.env.SOURCE_DATE_EPOCH?Number(process.env.SOURCE_DATE_EPOCH)*1000:fs.statSync(file).mtimeMs).toISOString();
p.slug=path.basename(file,path.extname(file));
p.url=p.permalink||(collection?(collection==='docs'?`/${p.slug}.html`:`/${collection}/${file.slice(collection.length+2).replace(/\.md$/,'.html')}`):`/${p.slug}.html`);
if(file==='index.md')p.url='/';
if(file==='404.md')p.url='/404.html';
p.output=p.url.endsWith('/')?`${p.url}index.html`:p.url;
p.raw=body;p.content=body;p.id=p.url.replace(/\.html$/,'');
documents.push(p);urlMap.set('/'+file,p.url);return p;
}
for(const name of Object.keys(config.collections)){
site[name]=walk('_'+name).filter(f=>f.endsWith('.md')).map(f=>doc(f,name));
site[name].sort((a,b)=>(a.explicitDate&&b.explicitDate?(Date.parse(a.date)||0)-(Date.parse(b.date)||0):0)||(a.path<b.path?-1:a.path>b.path?1:0));
site[name].forEach((p,i,items)=>{const adjacent=x=>x?{url:x.url,title:x.title}:null;p.previous=adjacent(items[i-1]);p.next=adjacent(items[i+1]);});
if(config.collections[name].output===false)for(const p of site[name])p.hiddenOutput=true;
}
for(const file of [...walk('_pages').filter(f=>f.endsWith('.md')),'index.md','404.md','settings.yaml'])doc(file);
const index=front(read('index.json'));
const redirects=walk('redirects').filter(f=>/\.ya?ml$/.test(f)).map(f=>front(read(f)).data);
for(const p of documents)for(const from of [].concat(p.redirect_from||[]))redirects.push({permalink:from,redirect_to:p.url});
return {site,config,documents,urlMap,index,redirects};
}
+31
View File
@@ -0,0 +1,31 @@
import fs from 'node:fs';
import path from 'node:path';
import sharp from 'sharp';
import {walk} from './content.mjs';
// The plan reads source assets; conversion writes exclusively to the build output.
export function planImages(directory='assets',publicPath='/assets'){
const urls=new Map(),pending=[];
for(const source of walk(directory)){
const relative=path.relative(directory,source).split(path.sep).join('/');
const url=publicPath+'/'+relative;
if(fs.existsSync(source+'.webp'))urls.set(url,url+'.webp');
else if(/\.(png|jpe?g|tiff?)$/i.test(source)){
urls.set(url,url+'.webp');
pending.push({source,relative:relative+'.webp'});
}
}
return {urls,pending};
}
export async function writeWebp(output,plan){
const pending=[...plan.pending];
// Bound CPU/memory use on the shared CI host. Match the old encoder's quality=100.
await Promise.all(Array.from({length:2},async()=>{
while(pending.length){
const {source,relative}=pending.shift(),target=path.join(output,'assets',relative);
fs.mkdirSync(path.dirname(target),{recursive:true});
await sharp(source).webp({quality:100}).toFile(target);
}
}));
}
+140
View File
@@ -0,0 +1,140 @@
import MarkdownIt from 'markdown-it';
import attrs from 'markdown-it-attrs';
import footnotes from 'markdown-it-footnote';
import hljs from 'highlight.js';
import {load as html} from 'cheerio';
import fs from 'node:fs';
import crypto from 'node:crypto';
import {planImages} from './images.mjs';
const escape=s=>String(s).replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;');
export function makeMarkdown(model){
const codeCache=JSON.parse(fs.readFileSync('theme/compat-code.json','utf8')).entries;
const images=model.images??=planImages();
const md=new MarkdownIt({html:true,breaks:false,linkify:false,typographer:true,quotes:'“”‘’',xhtmlOut:true}).use(attrs).use(footnotes);
md.normalizeLink=s=>s.replace(/ /g,'%20');
md.renderer.rules.s_open=()=>'<del>';md.renderer.rules.s_close=()=>'</del>';
md.renderer.rules.ordered_list_open=(ts,i,opts,env,self)=>{ts[i].attrs=(ts[i].attrs||[]).filter(([k])=>k!=='start');return self.renderToken(ts,i,opts);};
md.renderer.rules.heading_open=(ts,i,opts,env,self)=>{ts[i].attrSet('data-hmcl-heading','');return self.renderToken(ts,i,opts);};
md.renderer.rules.table_open=()=>'<table data-hmcl-table="">\n';
const footLabel=(t,e)=>e.footnotes.list[t.meta.id]?.label||String(t.meta.id+1);
md.renderer.rules.footnote_ref=(ts,i,o,e)=>{const t=ts[i],label=footLabel(t,e),suffix=t.meta.subId?':'+t.meta.subId:'';return `<sup id="fnref:${label}${suffix}"><a href="#fn:${label}" class="footnote" rel="footnote" role="doc-noteref">${t.meta.id+1}</a></sup>`;};
md.renderer.rules.footnote_block_open=()=>'<div class="footnotes" role="doc-endnotes"><ol>';
md.renderer.rules.footnote_block_close=()=>'</ol></div>';
md.renderer.rules.footnote_open=(ts,i,o,e)=>`<li id="fn:${footLabel(ts[i],e)}">`;
md.renderer.rules.footnote_anchor=(ts,i,o,e)=>`&nbsp;<a href="#fnref:${footLabel(ts[i],e)}" class="reversefootnote" role="doc-backlink">↩</a>`;
md.core.ruler.disable(['replacements','smartquotes']);
// Separate typographic symbols from text just as Kramdown's AST does.
// This matters when its GitHub-reference plugin wraps one text node in a span.
const typographyBoundary='\uE000';
md.renderer.rules.text=(ts,i)=>escape(ts[i].content).replaceAll(typographyBoundary,'<!-- HMCL_TYPOGRAPHY -->');
md.core.ruler.after('inline','kramdown_typography',state=>{
const symbol=s=>typographyBoundary+s+typographyBoundary;
function visit(tokens){for(const token of tokens){
if(token.type==='text')token.content=token.content.replace(/\.\.\./g,()=>symbol('…')).replace(/---/g,()=>symbol('—')).replace(/--/g,()=>symbol('–')).replace(/["']/g,(q,i,s)=>{
const prev=s[i-1]||'',next=s[i+1]||'';
const close=(prev&&!/[\s\\\[{(\-]/.test(prev))||!next||/\s/.test(next)||next==='s'&&!/\w/.test(s[i+2]||'');
return symbol(q==='"'?(close?'”':'“'):(close?'’':'‘'));
});
if(token.children)visit(token.children);
}}visit(state.tokens);
});
// Kramdown accepts emphasis delimiters next to CJK/punctuation where CommonMark differs.
md.inline.ruler.before('emphasis','kramdown_emphasis',(state,silent)=>{
if(state.src[state.pos]!=='*')return false;
const width=state.src[state.pos+1]==='*'?2:1,marker='*'.repeat(width),start=state.pos+width;
if(/\s/.test(state.src[start]||' '))return false;
let end=state.src.indexOf(marker,start);
while(end>=0&&(/\s/.test(state.src[end-1])||(width===1&&(state.src[end+1]==='*'||state.src[end-1]==='*'))))end=state.src.indexOf(marker,end+width);
if(end<0)return false;
if(!silent){const tag=width===2?'strong':'em';state.push(tag+'_open',tag,1);state.md.inline.parse(state.src.slice(start,end),state.md,state.env,state.tokens);state.push(tag+'_close',tag,-1);}
state.pos=end+width;return true;
});
md.renderer.rules.code_inline=(ts,i)=>`<code class="language-plaintext highlighter-rouge">${escape(ts[i].content)}</code>`;
md.renderer.rules.fence=(ts,i)=>{
const t=ts[i],lang=t.info.trim().split(/\s/)[0]||'plaintext';
const key=lang+':'+crypto.createHash('sha256').update(t.content).digest('hex');
let content=codeCache[key]??escape(t.content);
if(!Object.hasOwn(codeCache,key)&&hljs.getLanguage(lang)&&lang!=='plaintext')content=hljs.highlight(t.content,{language:lang,ignoreIllegals:true}).value.replace(/class="hljs-([^" ]+)(?: [^"]*)?"/g,(_,name)=>`class="${({keyword:'k',built_in:'nb',type:'kt',literal:'kc',number:'mi',string:'s',comment:'c',title:'nf',attr:'na',variable:'nv',meta:'cp',params:'n',symbol:'ss',regexp:'sr',punctuation:'p',operator:'o'})[name]||'n'}"`);
return `<div class="language-${lang} highlighter-rouge"${t.info.includes('hmcl-tight-li')?' data-hmcl-tight-list=""':''}><div class="highlight"><pre class="highlight"><code>${content}</code></pre></div></div>\n`;
};
function relative(input){
if(typeof input!=='string')return input;
const match=input.match(/^([^?#]*)([?#][\s\S]*)?$/),base=match[1];
return (model.urlMap.get(base)||base)+(match[2]||'');
}
function render(source){
let tocInline=false;
source=String(source??'').replace(/<!---->/g,'').replace(/^(\s*\d+)\)/gm,'$1\\)').replace(/\* This will become a table of contents[\s\S]*?\{:\s*toc\s*\}/g,()=>{tocInline=true;return '<!-- HMCL_INLINE_TOC -->';});
source=source.replace(/^(\d+\. [^\n]*\n)(```[^\n]*\n[\s\S]*?\n```)/gm,(_,item,code)=>item+code.replace(/\n/,' hmcl-tight-li\n').split('\n').map(line=>' '+line).join('\n'));
// Kramdown block attribute lists attach to the preceding block.
source=source.replace(/^\{:\s*([^}]+)\}\s*$/gm,(_,a)=>`\n<hmcl-attrs data-attrs="${escape(a.trim())}"></hmcl-attrs>\n`);
let result=md.render(source);
const $=html(result,null,false),ids=new Map();
$('table[data-hmcl-table]').removeAttr('data-hmcl-table').find('td').each((_,e)=>{if(!$(e).contents().length)$(e).html('&nbsp;');});
$('h1[id=""],h2[id=""],h3[id=""],h4[id=""],h5[id=""],h6[id=""]').removeAttr('id');
$('li > p:first-child').each((_,e)=>{const p=$(e);if(p.siblings('[data-hmcl-tight-list]').length&&p.parent().children('p').length===1)p.replaceWith(p.html());});
$('[data-hmcl-tight-list]').removeAttr('data-hmcl-tight-list');
if(/<li[ >]/.test(source))$('li').each((_,e)=>{
const el=$(e);if(el.find('br,table,ul,ol,p').length||!el.text().includes(' | '))return;
const cells=el.text().split(/\s*\|\s*/);el.html(`<table><tbody><tr>${cells.map(s=>`<td>${escape(s)}</td>`).join('')}</tr></tbody></table>`);
});
$('hmcl-attrs').each((_,e)=>{
const marker=$(e),container=marker.parent().is('p')&&marker.parent().text().trim()===''?marker.parent():marker,prev=container.prev();
for(const item of marker.attr('data-attrs').match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)||[]){if(item.startsWith('.'))prev.addClass(item.slice(1));else if(item.startsWith('#'))prev.attr('id',item.slice(1));}
container.remove();
});
$('[data-hmcl-heading]').each((_,e)=>{
$(e).removeAttr('data-hmcl-heading');
const el=$(e);if(el.attr('id'))return;
let id=el.text().trim().toLowerCase().replace(/\s/g,'-').replace(/[^\p{L}\p{N}\p{M}_-]/gu,'');
if(!id)id='section';const n=ids.get(id)||0;ids.set(id,n+1);el.attr('id',id+(n?`-${n}`:''));
});
$('blockquote').each((_,e)=>{
const q=$(e),p=q.children('p').first();if(!p.length)return;
const first=p.contents().first();if(first[0]?.type!=='text')return;
const m=first.text().match(/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:\n|$)/i);
if(m){q.addClass({'note':'notice--info','tip':'notice--success','important':'notice--primary','warning':'notice--warning','caution':'notice--danger'}[m[1].toLowerCase()]);first[0].data=first[0].data.slice(m[0].length);}
});
$('a[href],img[src],script[src]').each((_,e)=>{const el=$(e),a=e.name==='a'?'href':'src';el.attr(a,relative(el.attr(a)));});
$('img').each((_,e)=>{
const el=$(e),src=el.attr('src');
if(el.closest('picture').length||!src?.startsWith('/'))return;
const [,pathname,suffix]=src.match(/^([^?#]*)(.*)$/);
let original;try{original=decodeURI(pathname);}catch{return;}
const webp=images.urls.get(original);if(!webp)return;
el.wrap('<picture></picture>').before(` <source srcset="${escape(webp.replaceAll(' ','%20')+suffix)}" type="image/webp"> `);
const previous=el.parent()[0].prev;
if(previous?.type==='text')previous.data=previous.data.replace(/\s+$/,'');
});
function autolinks(parent){
for(const child of [...(parent.children||[])]){
if(child.type==='tag'&&['code','pre','script','style','a'].includes(child.name))continue;
if(child.type==='text'&&/\b(?:GP-\d+|GC-[0-9a-f]{7})\b/.test(child.data)){
const value=escape(child.data).replace(/\b(GP-(\d+)|GC-([0-9a-f]{7}))\b/g,(_,all,pr,sha)=>`<a href="https://github.com/HMCL-dev/HMCL/${pr?'pull/'+pr:'commit/'+sha}" target="_blank">${all}</a>`);
// Kramdown emits an HTML span on its own indented line, including
// separating whitespace around adjacent inline elements.
$(child).replaceWith(` <span>${value}</span> `);
}else if(child.children)autolinks(child);
}
}
autolinks($.root()[0]);
result=$.html().replaceAll('<!-- HMCL_TYPOGRAPHY -->','');
if(tocInline)result=result.replace('<!-- HMCL_INLINE_TOC -->',inlineTOC(result));
return result;
}
function inlineTOC(content){return `<aside class="sidebar__right"><nav class="toc"><header><h4 class="nav__title"><i class="fas fa-file-alt"></i> 目录</h4></header>${toc(content,'toc__menu','markdown-toc')}</nav></aside>`;}
function toc(content,cls='toc__menu',id){
const $=html(content,null,false);const heads=$('h1,h2,h3,h4,h5,h6').toArray().filter(e=>$(e).attr('id')&&!$(e).hasClass('no_toc'));
if(!heads.length)return '';
let out='',level=0,base=Number(heads[0].name.slice(1));
for(const h of heads){if(Number(h.name.slice(1))<base)continue;const n=Number(h.name.slice(1))-base+1;
if(n>level){for(let i=level;i<n;i++)out+=i===0?`<ul class="${cls}"${id?` id="${id}"`:''}>`:'<ul>';}
else if(n<level){for(let i=n;i<level;i++)out+='</li></ul>';out+='</li>';}
else out+='</li>';
out+=`<li><a href="#${escape($(h).attr('id'))}"${id?` id="${id}-${escape($(h).attr('id'))}"`:''}>${escape($(h).text())}</a>`;level=n;
}
for(let i=0;i<level;i++)out+='</li></ul>';return out;
}
return {render,relative,toc,inlineTOC};
}
+61
View File
@@ -0,0 +1,61 @@
import fs from 'node:fs';
import path from 'node:path';
import {Liquid} from 'liquidjs';
import {minify} from 'html-minifier-terser';
import {front,read} from './content.mjs';
import {makeMarkdown} from './markdown.mjs';
export function renderer(model){
const markdown=makeMarkdown(model);
const liquid=new Liquid({jsTruthy:false,strictFilters:true,strictVariables:false,dynamicPartials:false,dateTimezoneOffset:480});
const cache=new Map();
function includeFile(name){
name=name.replace(/^\//,'');if(name.includes('..'))throw Error('Invalid include path');
for(const base of ['_includes','theme/minimal-mistakes/_includes'])for(const ext of ['', '.html']){const p=path.join(base,name+ext);if(fs.existsSync(p))return read(p);}
throw Error('Missing include: '+name);
}
for(const tag of ['include','include_cached'])liquid.registerTag(tag,{
parse(token){
const match=token.args.match(/^(\S+)\s*([\s\S]*)$/);this.name=match[1].replace(/^['"]|['"]$/g,'');this.args=[];
const regex=/(\w+)\s*=\s*("[^"]*"|'[^']*'|[^\s]+)/g;let m;
while((m=regex.exec(match[2])))this.args.push([m[1],m[2]]);
},
*render(ctx){
if(this.name==='toc'&&!this.args.length)return '<!-- HMCL_INLINE_TOC -->';
const args={};for(const [k,v] of this.args)args[k]=yield liquid.evalValue(v,ctx);
if(this.name==='toc.html')return markdown.toc(args.html||'',args.class||'toc__menu',args.id);
const source=includeFile(this.name);if(!cache.has(source))cache.set(source,liquid.parse(source));
return yield liquid.render(cache.get(source),{...ctx.getAll(),include:args});
}
});
liquid.registerFilter('markdownify',s=>markdown.render(s));
liquid.registerFilter('relative_url',s=>typeof s==='string'?`${model.site.baseurl||''}${markdown.relative(s)}`:s);
liquid.registerFilter('absolute_url',s=>s===undefined||s===null?'':new URL(markdown.relative(String(s)),model.site.url+'/').href);
liquid.registerFilter('jsonify',s=>JSON.stringify(s??null));
liquid.registerFilter('date_to_xmlschema',s=>typeof s==='string'?s.replace(' ','T').replace(/\s([+-]\d\d)(\d\d)$/,'$1:$2'):new Date(s).toISOString());
liquid.registerFilter('version_sort',(xs,key)=>[...(xs||[])].sort((a,b)=>{const x=a[key].split('.').map(Number),y=b[key].split('.').map(Number);for(let i=0;i<Math.max(x.length,y.length);i++){const n=(x[i]||0)-(y[i]||0);if(n)return n;}return 0;}));
liquid.registerFilter('number_of_words',s=>String(s||'').trim().split(/\s+/).length);
liquid.registerFilter('smartify',s=>s);
liquid.registerFilter('normalize_whitespace',s=>String(s||'').replace(/\s+/g,' '));
const context=(p,extra={})=>({site:model.site,page:p,jekyll:{environment:'production'},...extra});
async function template(s,p,extra){return liquid.parseAndRender(s,context(p,extra));}
async function body(p){
let value=await template(p.raw,p);
value=markdown.render(value);
value=value.replace('<!-- HMCL_INLINE_TOC -->',markdown.inlineTOC(value));
return value;
}
async function page(p){
let content=p.rendered;let name=p.layout;const seen=new Set();
while(name&&name!=='compress'){
if(seen.has(name))throw Error('Cyclic layout '+name);seen.add(name);
let file=['_layouts','theme/minimal-mistakes/_layouts'].map(d=>path.join(d,name+'.html')).find(f=>fs.existsSync(f));
if(!file)throw Error('Missing layout '+name);
const layout=front(read(file));content=await template(layout.body,p,{content,layout:layout.data});name=layout.data.layout;
}
content=content.replace(/<p class="page__meta">[\s\S]*?<\/p>/g,p=>p.replace(/\s+/g,' ').replace(/ +<\/p>/g,'</p>'));
const result=await minify(content,{collapseWhitespace:true,ignoreCustomFragments:[/<p class="page__meta">[\s\S]*?<\/p>/,/<picture>[\s\S]*?<\/picture>/],removeComments:true,keepClosingSlash:true,caseSensitive:true,removeOptionalTags:false});
return result.replace(/<br\s*\/?>(?!\s)/g,'<br /> ');
}
return {liquid,markdown,template,body,page};
}
+57
View File
@@ -0,0 +1,57 @@
import fs from 'node:fs';
import path from 'node:path';
import {minify as minifyJS} from 'terser';
import {load,walk,read,front} from './content.mjs';
import {renderer} from './render.mjs';
import {writeWebp} from './images.mjs';
let state;
export async function prepare(){
if(state)return state;
const model=load(),r=renderer(model);state={model,r};
for(const p of model.documents){p.rendered=await r.body(p);p.content=p.rendered;}
return state;
}
export async function renderPage(p){return (await prepare()).r.page(p);}
const xml=s=>String(s??'').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;');
function output(out,file,value){const p=path.join(out,file.replace(/^\//,''));fs.mkdirSync(path.dirname(p),{recursive:true});fs.writeFileSync(p,value);}
export async function assets(out){
const {model,r}=await prepare();
for(const dir of ['theme/minimal-mistakes/assets','theme/minimal-mistakes/prebuilt/assets','assets'])for(const file of walk(dir)){
const rel=path.relative(dir,file);if(/\.(?:scss|map)$/.test(rel))continue;
const p=path.join(out,'assets',rel);fs.mkdirSync(path.dirname(p),{recursive:true});fs.copyFileSync(file,p);
}
fs.copyFileSync('favicon.ico',path.join(out,'favicon.ico'));
for(const [target,inputs] of Object.entries(model.config.post_process.terser)){
const code=[];
for(const input of inputs){
const source=['.'+input,'theme/minimal-mistakes'+input].find(f=>fs.existsSync(f));if(!source)throw Error('Missing script '+input);
const original=read(source),parsed=front(original);
code.push(parsed.body===original?original:await r.template(parsed.body,{url:input,layout:null}));
}
const result=await minifyJS(code.join(';'));output(out,target,result.code);
}
for(const p of [...model.config.post_process.remove_files,...model.config.post_process.remove_dirs])fs.rmSync(path.join(out,p.replace(/^\//,'')),{force:true,recursive:true});
// Styles are deliberately pinned to the published version for the first migration.
const cssDir='theme/minimal-mistakes/prebuilt/assets/css';
for(const p of walk(cssDir))output(out,'assets/css/'+path.relative(cssDir,p),fs.readFileSync(p));
await writeWebp(out,model.images);
const index=await r.template(model.index.body,model.index.data);JSON.parse(index);output(out,'index.json',index);
const redirects={};
for(const d of model.redirects){
const to=d.redirect_to.startsWith('/')?model.site.url+d.redirect_to:d.redirect_to;redirects[d.permalink]=to;
output(out,d.permalink,`<!DOCTYPE html>\n<html lang="en-US">\n <meta charset="utf-8">\n <title>Redirecting&hellip;</title>\n <link rel="canonical" href="${xml(to)}">\n <script>location=${JSON.stringify(to)}</script>\n <meta http-equiv="refresh" content="0; url=${xml(to)}">\n <meta name="robots" content="noindex">\n <h1>Redirecting&hellip;</h1>\n <a href="${xml(to)}">Click here if you are not redirected.</a>\n</html>\n`);
}
output(out,'redirects.json',JSON.stringify(redirects));
const date=s=>s?r.liquid.filters.date_to_xmlschema(s):model.site.time;
const feed=(collection)=>{
const file=collection?`feed/${collection}.xml`:'feed.xml';const url=model.site.url+'/'+file;
const docs=collection?[...model.site[collection]].filter(p=>p.date).sort((a,b)=>new Date(a.date)-new Date(b.date)).reverse().slice(0,10):[];
const entries=docs.map(p=>`<entry><title type="html">${xml(xml(p.title))}</title><link href="${xml(model.site.url+p.url)}" rel="alternate" type="text/html" title="${xml(p.title)}"/><published>${date(p.date)}</published><updated>${date(p.last_modified_at||p.date)}</updated><id>${xml(model.site.url+p.id)}</id><content type="html" xml:base="${xml(model.site.url+p.url)}"><![CDATA[${p.rendered.replaceAll(']]>',']]]]><![CDATA[>')}]]></content>${p.author?`<author><name>${xml(p.author)}</name></author>`:''}${p.excerpt?`<summary type="html">${xml(r.markdown.render(p.excerpt).trim())}</summary>`:''}</entry>`).join('');
output(out,file,`<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom"><generator uri="https://www.11ty.dev/">Eleventy</generator><link href="${url}" rel="self" type="application/atom+xml"/><link href="${model.site.url}/" rel="alternate" type="text/html"/><updated>${model.site.time}</updated><id>${url}</id><title type="html">${xml(model.site.title+(collection?' | '+collection[0].toUpperCase()+collection.slice(1):''))}</title><subtitle>${xml(model.site.description)}</subtitle>${entries}</feed>`);
};
feed();for(const name of model.config.feed.collections)feed(name);
const urls=model.documents.filter(p=>!p.hiddenOutput).map(p=>p.url).concat(Object.keys(redirects));
output(out,'sitemap.xml',`<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${urls.map(u=>`<url><loc>${xml(model.site.url+u)}</loc></url>`).join('')}</urlset>`);
output(out,'robots.txt',`Sitemap: ${model.site.url}/sitemap.xml\n`);
}