mdat 0.6.10 → 0.6.11
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.
- package/bin/cli.js +19 -19
- package/dist/index.js +13 -13
- package/package.json +3 -2
package/bin/cli.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{defaultLoaders as
|
|
3
|
-
${JSON.stringify(t,void 0,2)}`)}function
|
|
4
|
-
${JSON.stringify(t,void 0,2)}`)}var ee;async function P(){return ee===void 0&&(b.warn("getConfig(): config was undefined"),ee??=await L()),ee}var ve;async function h(){let{packageFile:t}=await P();if(t===void 0)throw new Error("No packageFile found or set in config");if(ve??=await
|
|
5
|
-
`)},order:3}};import{globby as
|
|
2
|
+
import{defaultLoaders as $n}from"cosmiconfig";function Ee(t,e){let n=$n[".json"],o=n(t,e);return yt(o)}function yt(t,e="",n={}){for(let[o,i]of Object.entries(t)){let r=e?`${e}.${o}`:o;typeof i=="object"&&i!==null&&!Array.isArray(i)?yt(i,r,n):i===null?n[r]="null":n[r]=i.toString()}return n}import Nn from"node:fs";import R from"node:path";import{packageUp as Mn}from"package-up";import{isFileSync as wt}from"path-type";import Dn from"untildify";function _n(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function Ct(t,e,n,o){let i=[];for(let[r,s]of t.entries()){let a=n&&t.length>1?`-${_n(r+1,t.length+1)}`:"",d=In(s,e,n,o,a);i.push(d)}return i}function In(t,e,n,o,i=""){let r=bt(t),s=e?bt(e):void 0;if(!wt(r))throw new Error(`Input file not found: "${r}"`);if(s){if(wt(s))throw new Error(`Output path must be a directory, received a file path: "${s}"`);Nn.mkdirSync(s,{recursive:!0})}let a=n?R.basename(n,R.extname(n)):R.basename(r,R.extname(r)),d=`.${o??(n&&R.extname(n)!==""?R.extname(n):R.extname(t)===""?"":R.extname(t))}`,m=`${a}${i}${d}`,c=s??R.dirname(r);return{input:r,name:m,output:c}}function bt(t){return Dn(t)}async function X(){return Mn()}function Q(t){return t==null?[]:Array.isArray(t)?t:[t]}import Pt from"chalk";import{cosmiconfig as Rt}from"cosmiconfig";import{TypeScriptLoader as Ot}from"cosmiconfig-typescript-loader";import jn from"node:fs/promises";import kt from"node:path";import Fn from"plur";import{readPackage as Un}from"read-pkg";import{deepMergeDefined as Le,log as b,optionsSchema as Vn,rulesSchema as Bn}from"remark-mdat";import{z as Te}from"zod";var St=Vn.merge(Te.object({assetsPath:Te.string().optional(),packageFile:Te.string().optional()})).describe("Config Extension");async function L(t){let{additionalConfig:e,additionalRules:n,searchFrom:o}=t??{},i={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await X(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},r=Rt("mdat",{loaders:{".ts":Ot()}}),s=await r.search(o);if(s){let{config:a,filepath:d}=s;b.info(`Using config from "${d}"`);let m=xt(a,St);m&&(i=Le(i,m))}if(e!==void 0){let a=Array.isArray(e)?e:[e];for(let d of a){let m;if(typeof d=="string"){let p=await r.load(d);if(p==null)continue;let{config:g,filepath:y}=p;b.info(`Loaded additional config from "${y}"`),m=g}else m=d;if(m===void 0)continue;b.info("Merging configuration object");let c=xt(m,St);c!==void 0&&(i=Le(i,c))}}if(n!==void 0){let a=Array.isArray(n)?n:[n],d=Rt("mdat",{loaders:{".json":Ee,".ts":Ot()}});for(let m of a){let c;if(typeof m=="string"){let g;if(kt.basename(m).endsWith("package.json")){let _=await jn.readFile(m,"utf8");g={config:Ee(m,_),filepath:m}}else g=await d.load(m);if(g==null)continue;let{config:y,filepath:w}=g;b.info(`Loaded additional config from "${w}"`),c=y}else c=m;if(c===void 0)continue;b.info("Merging rules into configuration object");let p=Jn(c,Bn);p!==void 0&&(i=Le(i,p))}}if(i.rules){let a=Object.keys(i.rules).sort().map(d=>`"${Pt.bold.green(d)}"`);b.info(`Loaded ${Pt.bold(a.length)} mdat comment expansion ${Fn("rule",a.length)}:`);for(let d of a)b.info(` ${d}`)}else b.error("No rules loaded from additional configurations or rules, using default.");return ee=i,i}function Jn(t,e){if(e.safeParse(t).success)return{rules:t};b.error(`Rules object has the wrong shape. Ignoring and using default configuration:
|
|
3
|
+
${JSON.stringify(t,void 0,2)}`)}function xt(t,e){if(e.safeParse(t).success)return t;b.error(`Config object has the wrong shape. Ignoring and using default configuration:
|
|
4
|
+
${JSON.stringify(t,void 0,2)}`)}var ee;async function P(){return ee===void 0&&(b.warn("getConfig(): config was undefined"),ee??=await L()),ee}var ve;async function h(){let{packageFile:t}=await P();if(t===void 0)throw new Error("No packageFile found or set in config");if(ve??=await Un({cwd:kt.dirname(t)}),ve===void 0)throw new Error("No package.json found");return ve}import{remark as Ae}from"remark";import $e from"remark-gfm";import{mdatCheck as Hn,mdatClean as Et,mdatExpand as zn,mdatSplit as Lt}from"remark-mdat";import{read as qn}from"to-vfile";import{VFile as Si}from"vfile";async function S(t,e,n,o,i,r,s){let a=await e({additionalConfig:r,additionalRules:s});r=a;let d=Q(t),m=Ct(d,i,o,"md"),c=[],p=n(a);for(let{input:g,name:y,output:w}of m){let _=await qn(g),Z=await p.process(_);Z.dirname=w,Z.basename=y,c.push(Z)}return c}function te(t){return Ae().use({settings:{bullet:"-",emphasis:"_"}}).use($e).use(()=>async function(n,o){Lt(n,o),Et(n,o,t),await zn(n,o,t)})}function ne(t){return Ae().use({settings:{bullet:"-",emphasis:"_"}}).use($e).use(()=>function(n,o){Lt(n,o),Et(n,o,t)})}function oe(t){return Ae().use({settings:{bullet:"-",emphasis:"_"}}).use($e).use(()=>async function(n,o){await Hn(n,o,{...t,paranoid:!1})})}async function Tt(t,e,n,o,i){return S(t,L,te,e,n,o,i)}async function vt(t,e,n,o,i){return S(t,L,oe,e,n,o,i)}async function At(t,e,n,o,i){return S(t,L,ne,e,n,o,i)}import{z as T}from"zod";var ie={badges:{async content(t){var s;let e=T.object({custom:T.record(T.object({image:T.string(),link:T.string()})).optional(),npm:T.array(T.string()).optional()}).optional().parse(t),n=await h(),{name:o}=n,i=[];if(!n.private&&((s=n.publishConfig)==null?void 0:s.access)==="public"&&i.push(`[](https://npmjs.com/package/${o})`),(e==null?void 0:e.npm)!==void 0)for(let a of e.npm)i.push(`[](https://npmjs.com/package/${a})`);let{license:r}=n;if(r!==void 0&&i.push(`[](https://opensource.org/licenses/${r})`),(e==null?void 0:e.custom)!==void 0)for(let[a,{image:d,link:m}]of Object.entries(e.custom))i.push(`[](${m})`);return i.join(`
|
|
5
|
+
`)},order:3}};import{globby as Kn}from"globby";import re from"node:path";import{isFile as Wn}from"path-type";import{readPackage as Yn}from"read-pkg";import{z as Ne}from"zod";var se={banner:{async content(t){let e=Ne.object({alt:Ne.string().optional(),src:Ne.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:o}=await P();if(o===void 0)throw new Error("No package.json found");let i=(e==null?void 0:e.src)??await $t(n)??await $t();if(i===void 0)throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");if(!Nt(i)&&!await Wn(i))throw new Error(`Banner image not found at "${i}"`);let r=(e==null?void 0:e.alt)??`${(await Yn({cwd:re.dirname(o)})).name} banner`;if(r===void 0||r==="undefined banner")throw new Error("Banner image alt text not available");return``},order:2}};async function $t(t){let{packageFile:e}=await P();if(e===void 0)throw new Error("No package.json found");let n=re.dirname(e),o=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images",".github/assets"]:[t],i=["banner","cover","demo","header","hero","image","logo","overview","readme","screenshot","screenshots","splash"],r=["png","gif","jpg","jpeg","svg","webp"],s=await Kn(o.map(a=>re.join(n,a)),{deep:1,expandDirectories:{extensions:r,files:i}});if(s.length>0)return re.relative(process.cwd(),s[0])}function Nt(t,e=!0){if(typeof t!="string")throw new TypeError("Expected a string");if(t=t.trim(),t.includes(" "))return!1;try{return new URL(t),!0}catch{return e?Nt(`https://${t}`,!1):!1}}function Mt(t,e=Number.MAX_SAFE_INTEGER){var i;let n=[],o=Zn(t,e);return n.push(Xn(o)),n.push(Qn(t,o)),o.hasMultipleSubcommands&&o.canRecurse&&n.push(eo(o.fullCommandName)),((i=o.defaultCommand)==null?void 0:i.commandName)!==void 0&&n.push(to(o)),n.push(no(t,o)),t.positionals&&!o.commandsOnly&&n.push(Me(["Positional Argument","Description","Type","Default"],t.positionals.map(r=>[r.arguments?[r.arguments.map(s=>`\`${s}\``)].join(" "):"",`${r.description??""}${r.required?" _(Required.)_":" _(Optional.)_"}`,r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),t.commands&&n.push(Me(["Command","Argument","Description"],t.commands.map(r=>{var s;return[`\`${r.commandName??(r.default?"[default]":"")}\``,r.arguments?(s=r.arguments)==null?void 0:s.map(a=>`\`${a}\``).join(" "):"",`${r.description??""}${r.default?" _(Default command.)_":""}`]}))),t.options&&!o.commandsOnly&&n.push(Me(["Option","Alias","Argument","Description","Type","Default"],t.options.map(r=>[r.flags?r.flags.map(s=>`\`${s}\``).join(" "):"",r.aliases?r.aliases.map(s=>`\`${s}\``).join(" "):"",r.arguments?r.arguments.map(s=>`\`${s}\``).join(" "):"",r.description??"",r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),o.canRecurse&&o.hasMultipleSubcommands&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
|
|
6
6
|
|
|
7
|
-
`)}function
|
|
7
|
+
`)}function Zn(t,e){var m,c;let n=t.subcommandName===void 0,o=t.commands?t.commands.length>1:!1,i=e>1,r=(m=t.commands)==null?void 0:m.find(p=>p.default),s=(c=t.commands)==null?void 0:c.find(p=>p.commandName===void 0),a=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`,d=i&&o&&(r==null?void 0:r.commandName)!==void 0;return{canRecurse:i,commandsOnly:d,defaultCommand:r,fullCommandName:a,hasMultipleSubcommands:o,isTopLevel:n,topLevelCommand:s}}function Xn(t){return`#### ${t.isTopLevel?"Command":"Subcommand"}: \`${t.fullCommandName}\``}function Qn(t,e){var n,o;return e.isTopLevel&&((n=e.topLevelCommand)!=null&&n.description)?(t.commands=(o=t.commands)==null?void 0:o.filter(i=>i!==e.topLevelCommand),e.topLevelCommand.description):t.description??""}function eo(t){return`This section lists top-level commands for \`${t}\`.`}function to(t){var e,n;return`If no command is provided, \`${(e=t.defaultCommand)==null?void 0:e.parentCommandName} ${(n=t.defaultCommand)==null?void 0:n.commandName}\` is run by default.`}function no(t,e){var o;let n=(o=e.topLevelCommand)!=null&&o.arguments?` ${e.topLevelCommand.arguments.join(" ")}`:`${t.arguments?` ${t.arguments.join(" ")}`:""}`;return`Usage:
|
|
8
8
|
|
|
9
9
|
\`\`\`txt
|
|
10
10
|
${e.fullCommandName}${n}
|
|
11
|
-
\`\`\``}function Me(t,e){let n=
|
|
11
|
+
\`\`\``}function Me(t,e){let n=oo(e);t=t.filter((i,r)=>!n.includes(r)),e=e.map(i=>i.filter((r,s)=>!n.includes(s)));let o="";o+=`| ${t.join(" | ")} |
|
|
12
12
|
`,o+=`| ${t.map(()=>"---").join(" | ")} |
|
|
13
13
|
`;for(let i of e)o+=`| ${i.join(" | ")} |
|
|
14
|
-
`;return o}function
|
|
14
|
+
`;return o}function oo(t){var o;let e=[],n=((o=t[0])==null?void 0:o.length)||0;for(let i=0;i<n;i++){let r=!0;for(let s of t)if(s[i]!==""){r=!1;break}r&&e.push(i)}return e}import{CstParser as io,Lexer as O,createToken as f}from"chevrotain";var me=f({name:"flag",pattern:/--[\w-_]+/}),Ie=f({longer_alt:me,name:"alias",pattern:/-[A-Za-z]/}),Dt=f({group:O.SKIPPED,name:"comma",pattern:/,/}),_t=f({group:O.SKIPPED,name:"dollar",pattern:/\$/}),ae=f({group:O.SKIPPED,name:"whiteSpace",pattern:/ /}),It=f({group:O.SKIPPED,name:"newLine",pattern:/\n/}),je=f({name:"word",pattern:/\S+/}),H=f({name:"argument",pattern:/(<\S+>|\[.+])/}),Fe=f({name:"programDescription",pattern:/\w.+(?=\n\n {2}Usage)/}),jt=f({group:O.SKIPPED,name:"startUsage",pattern:/ {2}Usage\n/,push_mode:"USAGE_MODE"}),Ft=f({group:O.SKIPPED,name:"endUsage",pattern:/\n/,pop_mode:!0}),Ue=f({name:"startOptions",pattern:/ {2}Options\n/,push_mode:"OPTIONS_MODE"}),Ve=f({name:"startRow",pattern:/ {4}/,push_mode:"ROW_MODE"}),Be=f({name:"rowDescription",pattern:/\w.+/}),Ut=f({group:O.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),Vt=f({group:O.SKIPPED,name:"endOptions",pattern:/\n/,pop_mode:!0}),ro=new O({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[jt,Ue,Fe,It,ae],OPTIONS_MODE:[Vt,Ve],ROW_MODE:[Ut,Ie,me,Dt,H,Be,ae],USAGE_MODE:[Ft,_t,H,je,ae]}}),so=[me,Ie,Dt,_t,ae,It,je,H,Fe,jt,Ft,Ue,Ve,Be,Ut,Vt],De=class extends io{programHelp=this.RULE("programHelp",()=>{this.CONSUME(Fe,{LABEL:"description"}),this.AT_LEAST_ONE(()=>{this.CONSUME(je,{LABEL:"commandName"})}),this.MANY(()=>{this.CONSUME(H)}),this.OPTION(()=>{this.SUBRULE(this.optionsSection)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(Ue),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(Ve),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(H)},{ALT:()=>this.CONSUME(Ie)},{ALT:()=>this.CONSUME(me)},{ALT:()=>this.CONSUME(Be,{LABEL:"description"})}])})});constructor(){super(so),this.performSelfAnalysis()}},J=new De,_e=class extends J.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:o}=de(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,subcommandName:o}}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),description:this.getString(e.description,!0),flags:this.getArray(e.flag)}}getString(e,n=!1){if(e!==void 0)return e.map(o=>n?this.clean(o.image):o.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}},ao=new _e;function Bt(t){let e=ro.tokenize(t);if(e.errors.length>0)throw new Error(`Errors lexing CLI command: ${JSON.stringify(e.errors,void 0,2)}`);J.input=e.tokens;let n=J.programHelp();if(J.errors.length>0)throw new Error(`Errors parsing CLI command help text: ${JSON.stringify(J.errors,void 0,2)}`);let o;try{o=ao.visit(n)}catch(i){if(i instanceof Error)throw new TypeError(`Errors visiting CLI command help text: ${String(i)}`)}if(o===void 0)throw new Error("Could not parse help string");return o}import{CstParser as mo,Lexer as v,createToken as l}from"chevrotain";var qe=l({name:"flag",pattern:/--[\w-_]+/}),Ge=l({name:"alias",pattern:/-[A-Za-z]/}),Jt=l({group:v.SKIPPED,name:"comma",pattern:/,/}),I=l({name:"word",pattern:/\S+/}),q=l({name:"argument",pattern:/<\S+>|\[\S+]/}),Ke=l({name:"type",pattern:/\[(boolean|string|array)]/}),We=l({name:"defaultInfo",pattern:/\[default]/}),Ye=l({name:"required",pattern:/\[required]/}),Ze=l({name:"defaultInfoDescription",pattern:/\[default:\s.+?]/}),Xe=l({name:"choices",pattern:/\[choices:\s.+?]/}),Je=l({group:v.SKIPPED,name:"whiteSpace",pattern:/\s/}),Ht=l({group:v.SKIPPED,name:"startProgramDescription",pattern:/\n\n/,push_mode:"PROGRAM_DESCRIPTION_MODE"}),Qe=l({name:"programDescription",pattern:/.+/}),zt=l({group:v.SKIPPED,name:"endProgramDescription",pattern:/\n\n/,pop_mode:!0}),et=l({name:"startOptionsSection",pattern:/Options:?\n/,push_mode:"SECTION_MODE"}),tt=l({name:"startPositionalsSection",pattern:/Positionals:\n/,push_mode:"SECTION_MODE"}),nt=l({name:"startCommandsSection",pattern:/Commands:\n/,push_mode:"SECTION_MODE"}),ot=l({name:"startRow",pattern:/ {2,}/,push_mode:"ROW_MODE"}),it=l({name:"rowDescription",pattern:/ {2}\w.+ {2}/}),rt=l({name:"rowDescriptionTerminal",pattern:/ {2}\w.+/}),qt=l({group:v.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),Gt=l({group:v.SKIPPED,name:"endSection",pattern:/\n+/,pop_mode:!0}),co=new v({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[et,tt,nt,Ht,q,I,Je],PROGRAM_DESCRIPTION_MODE:[zt,Qe],ROW_MODE:[qt,Jt,Ke,it,rt,Ze,We,Ye,Xe,qe,Ge,q,I,Je],SECTION_MODE:[ot,Gt]}}),po=[qe,Ge,Jt,I,q,Ke,We,Ye,Ze,Xe,Je,Ht,Qe,zt,et,tt,nt,ot,it,rt,qt,Gt],He=class extends mo{programHelp=this.RULE("programHelp",()=>{this.AT_LEAST_ONE(()=>{this.CONSUME(I,{LABEL:"commandName"})}),this.MANY1(()=>{this.CONSUME(q)}),this.OPTION(()=>{this.CONSUME(Qe,{LABEL:"description"})}),this.OPTION1(()=>{this.SUBRULE(this.commandsSection)}),this.OPTION2(()=>{this.SUBRULE(this.positionalsSection)}),this.OPTION3(()=>{this.SUBRULE(this.optionsSection)})});positionalsSection=this.RULE("positionalsSection",()=>{this.CONSUME(tt),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});commandsSection=this.RULE("commandsSection",()=>{this.CONSUME(nt),this.MANY1(()=>{this.SUBRULE1(this.sectionRow)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(et),this.MANY2(()=>{this.SUBRULE2(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(ot),this.OPTION(()=>{this.CONSUME(I,{LABEL:"parentCommandName"})}),this.MANY(()=>{this.CONSUME1(I,{LABEL:"commandName"})}),this.MANY1(()=>{this.OR([{ALT:()=>this.CONSUME(q)},{ALT:()=>this.CONSUME(Ge)},{ALT:()=>this.CONSUME(qe)},{ALT:()=>this.CONSUME(it,{LABEL:"description"})},{ALT:()=>this.CONSUME(rt,{LABEL:"description"})},{ALT:()=>this.CONSUME(Ke)},{ALT:()=>this.CONSUME(Ye)},{ALT:()=>this.CONSUME(Ze)},{ALT:()=>this.CONSUME(We)},{ALT:()=>this.CONSUME(Xe)}])})});constructor(){super(po),this.performSelfAnalysis()}},z=new He,ze=class extends z.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:o}=de(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,commands:e.commandsSection?this.visit(e.commandsSection):void 0,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,positionals:e.positionalsSection?this.visit(e.positionalsSection):void 0,subcommandName:o}}positionalsSection(e){return e.sectionRow.map(n=>this.positionalParentCommandToArguments(this.visit(n)))}commandsSection(e){return e.sectionRow.map(n=>this.visit(n))}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),choices:this.splitChoices(this.getString(e.choices)),commandName:this.getString(e.commandName),default:e.defaultInfo?!0:void 0,defaultValue:this.getString(e.defaultInfoDescription,!0),description:this.getString(e.description,!0),flags:this.getArray(e.flag),parentCommandName:this.getString(e.parentCommandName),required:e.required?!0:void 0,type:this.getString(e.type,!0)}}positionalParentCommandToArguments(e){let{arguments:n,parentCommandName:o,...i}=e;return o===void 0?e:{arguments:[o,...n??[]],...i}}getString(e,n=!1){if(e!==void 0)return e.map(o=>n?this.clean(o.image):o.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}splitChoices(e){if(e!==void 0)return this.clean(e.replaceAll(/^\[choices:\s/g,"")).split(", ")}},lo=new ze;function Kt(t){let e=co.tokenize(t);if(e.errors.length>0)throw new Error(`Errors lexing CLI command: ${JSON.stringify(e.errors,void 0,2)}`);z.input=e.tokens;let n=z.programHelp();if(z.errors.length>0)throw new Error(`Errors parsing CLI command help text: ${JSON.stringify(z.errors,void 0,2)}`);let o;try{o=lo.visit(n)}catch(i){if(i instanceof Error)throw new TypeError(`Errors visiting CLI command help text: ${String(i)}`)}if(o===void 0)throw new Error("Could not parse help string");return o}var Wt={meow:Bt,yargs:Kt};function de(t){if(t===void 0)throw new Error('Could not find "commandName" entry in help');let e=t.split(" ");if(e.length===0&&t===void 0)throw new Error('Could not find "commandName" entry in help');if(e.length===1)return{command:e[0],subcommand:void 0};let n=e.at(-1);return{command:e.slice(0,-1).join(" "),subcommand:n}}import{log as st}from"remark-mdat";function Yt(t){for(let[e,n]of Object.entries(Wt)){st.info(`Trying to parse help string with ${e} parser...`);try{return n(t)}catch(o){o instanceof Error&&st.info(`Error in "${e}" parser: ${String(o)}`);continue}}st.error("Could not parse help string with any parser")}import{execaCommand as uo}from"execa";import{log as Zt}from"remark-mdat";async function at(t,e="--help",n){let o=`${t} ${e}`,i=await ho(o),r=Yt(i);return r===void 0?(Zt.warn("Falling back to basic cli help text output."),go(i)):fo(t,e,n??Number.MAX_SAFE_INTEGER,r)}async function fo(t,e,n,o){if(n<=0)return Zt.info("Max CLI command help depth reached, stopping recursion"),"";let i=Mt(o,n),r=t.split(" ")[0];if(o.commands)for(let s of o.commands){if(!s.parentCommandName||!s.commandName)continue;let a=await at(`${r} ${s.commandName}`,e,n-1);if(a==="")return i;i+=`
|
|
15
15
|
|
|
16
|
-
${a}`}return i}function
|
|
16
|
+
${a}`}return i}function go(t){return`\`\`\`txt
|
|
17
17
|
${t}
|
|
18
|
-
\`\`\``}async function
|
|
18
|
+
\`\`\``}async function ho(t){let e;try{let{stderr:n,stdout:o}=await uo(t);e=o,(e===void 0||e==="")&&(e=n)}catch(n){if(n instanceof Error)throw new TypeError(`Error running CLI help command: "${t}"
|
|
19
19
|
${n.message}
|
|
20
20
|
`)}if(e===void 0||e==="")throw new Error(`No result from running CLI help command: "${t}"
|
|
21
|
-
`);return e}import{isExecutable as
|
|
21
|
+
`);return e}import{isExecutable as yo}from"is-executable";import wo from"node:path";import{log as bo}from"remark-mdat";import Co from"which";async function Xt(t){return t??=await Po(),Oo(t)}async function Po(){let t=await h();if(t!=null&&t.bin){let e=typeof t.bin=="string"?t.bin:String(Object.values(t.bin).at(0));if(Ro(e))return bo.info(`Inferred <!-- cli-help --> command to run from package.json: ${e}`),e}throw new Error(`Could not infer which command to run for the <!-- cli-help --> rule. Please pass a "cliCommand" option to the expansion comment, e.g. <!-- cli-help {cliCommend: './dist/bin.js'} -->`)}function Ro(t){let e=wo.parse(t);return e.root!==""||e.dir!==""}async function Oo(t){let e=await Co(t,{nothrow:!0});if(e===null&&(e=await So(t)??void 0),e!==void 0&&await yo(e))return e;throw new Error(`The cli-help rule noticed that "${e}" is not executable.`)}async function So(t){var n;let e=await h();return((n=e==null?void 0:e.bin)==null?void 0:n[t])??void 0}import{z as ce}from"zod";var Qt={"cli-help":{async content(t){let e=ce.object({cliCommand:ce.string().optional(),depth:ce.number().optional(),helpFlag:ce.string().optional()}).optional().parse(t),n=await Xt(e==null?void 0:e.cliCommand);return at(n,e==null?void 0:e.helpFlag,e==null?void 0:e.depth)}}};import xo from"node:fs/promises";import en from"node:path";import{z as mt}from"zod";var tn={code:{async content(t){let e=mt.object({file:mt.string(),language:mt.string().optional()}).parse(t),n=en.extname(e.file)??"",o=await xo.readFile(en.join(process.cwd(),e.file),"utf8");return`\`\`\`${n}
|
|
22
22
|
${o}
|
|
23
23
|
\`\`\``}}};var pe={contributing:{async content(){var n;let t=await h(),e=(n=t==null?void 0:t.bugs)==null?void 0:n.url;if(e===void 0)throw new Error('Could not find "bugs.url" entry in package.json');return`## Contributing
|
|
24
24
|
[Issues](${e}) and pull requests are welcome.`},order:15}};var le={description:{async content(){let t=await h();if(t.description===void 0)throw new Error('Could not find "description" entry in package.json');return`**${t.description}**`},order:4}};var ue={license:{async content(){let t=await h(),{author:e,license:n}=t;if((e==null?void 0:e.name)===void 0)throw new Error('Could not find "author.name" entry in package.json');if(n===void 0)throw new Error('Could not find "license" entry in package.json');return`## License
|
|
25
|
-
[${n}](license.txt) \xA9 ${e.name}`},order:16}};import{getSoleRule as
|
|
25
|
+
[${n}](license.txt) \xA9 ${e.name}`},order:16}};import{getSoleRule as nn}from"remark-mdat";var on={footer:{content:[nn(pe),nn(ue)],order:17}};import{getSoleRule as ko}from"remark-mdat";var fe={"short-description":ko(le)};import{z as ge}from"zod";var he={title:{applicationOrder:2,async content(t){let{postfix:e,prefix:n,titleCase:o}=ge.object({postfix:ge.string().optional().default(""),prefix:ge.string().optional().default(""),titleCase:ge.boolean().optional().default(!1)}).parse(t??{}),{name:i}=await h();return`# ${n}${o?Eo(i):i}${e}`},order:1}};function Eo(t){return t.split(/[ _-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}import{getSoleRule as ye}from"remark-mdat";var rn={header:{applicationOrder:2,content:[ye(he),ye(se),ye(ie),ye(fe)],order:1}};import{toc as Lo}from"mdast-util-toc";import{remark as To}from"remark";import vo from"remark-gfm";import{z as x}from"zod";var we={"table-of-contents":{applicationOrder:1,async content(t,e){let n=x.object({depth:x.union([x.literal(1),x.literal(2),x.literal(3),x.literal(4),x.literal(5),x.literal(6)]).optional()}).optional().parse(t),o=Lo(e,{heading:null,maxDepth:(n==null?void 0:n.depth)??3,tight:!0}),i="## Table of contents";if(o.map===void 0)throw new Error("Could not generate table of contents");let r={children:o.map.children,type:"root"},s=To().use(vo).stringify(r).replaceAll(`
|
|
26
26
|
|
|
27
27
|
`,`
|
|
28
28
|
`);return[i,s].join(`
|
|
29
|
-
`)},order:6}};import{tldrawToImage as
|
|
29
|
+
`)},order:6}};import{tldrawToImage as sn}from"@kitschpatrol/tldraw-cli";import Ao from"node:crypto";import j from"node:fs/promises";import C from"node:path";import{isFile as dt}from"path-type";import{z as ct}from"zod";var cn={tldraw:{async content(t){let{alt:e="tldraw diagram",src:n}=ct.object({alt:ct.string().optional(),src:ct.string()}).parse(t),{assetsPath:o}=await P();if(o===void 0)throw new Error("No assets path found");await j.mkdir(o,{recursive:!0});let i=await dt(n)?await mn(n):void 0;if(i!==void 0){let m=C.basename(n,C.extname(n)),c=C.join(o,`${m}-${i}-light.svg`),p=C.join(o,`${m}-${i}-dark.svg`);if(await dt(c)&&await dt(p))return an(c,p,e)}let[r]=await sn(n,{dark:!1,format:"svg",output:o,transparent:!0});i??=await mn(r);let s=`${dn(r)}-${i}-light.svg`;await j.rename(r,s);let[a]=await sn(n,{dark:!0,format:"svg",output:o,transparent:!0}),d=`${dn(a)}-${i}-dark.svg`;if(await j.rename(a,d),i!==void 0){let m=C.basename(d),c=C.basename(s),p=c.replace(`${i}-light.svg`,""),g=await j.readdir(o);for(let y of g){let w=C.basename(y);w!==m&&w!==c&&w.startsWith(p)&&w.endsWith(".svg")&&await j.rm(C.join(o,w))}}return an(s,d,e)}}};async function an(t,e,n){let{packageFile:o}=await P();if(o===void 0)throw new Error("No package file found");let i=C.dirname(o),r=C.relative(i,t);return`<picture>
|
|
30
30
|
<source media="(prefers-color-scheme: dark)" srcset="${C.relative(i,e)}">
|
|
31
31
|
<source media="(prefers-color-scheme: light)" srcset="${r}">
|
|
32
32
|
<img alt="${n}" src="${r}">
|
|
33
|
-
</picture>`}async function
|
|
33
|
+
</picture>`}async function mn(t){let e=await j.readFile(t),n=Ao.createHash("sha1");return n.update(e),n.digest("hex").slice(0,8)}function dn(t){return t.replace(/\.[^./]+$/,"")}import{getSoleRule as $o}from"remark-mdat";var pn={toc:$o(we)};var ln={...ie,...se,...Qt,...tn,...pe,...le,...on,...rn,...ue,...fe,...we,...cn,...pn,...he};async function be(t){let e={addMetaComment:!0,rules:ln},{additionalConfig:n=[],...o}=t??{},i=Array.isArray(n)?n:[n],r=await L({additionalConfig:[e,...i],...o});if(r.packageFile===void 0)throw new Error("Package file path is required in `mdat readme` config");return r}import{findUp as No}from"find-up";import{packageDirectory as Mo}from"pkg-dir";import{log as un}from"remark-mdat";async function pt(){un.info("Searching for package directory...");let t=await Mo()??process.cwd(),e=await No("readme.md",{stopAt:t,type:"file"});if(e!==void 0)return un.info(`Found closest readme at "${e}"`),e}async function Ce(){let t=await pt();if(t===void 0)throw new Error("No readme found");return t}async function Pe(t,e,n,o,i){return t??=await Ce(),S(t,be,te,e,n,o,i)}async function fn(t,e,n,o,i){return t??=await Ce(),S(t,be,oe,e,n,o,i)}async function gn(t,e,n,o,i){return t??=await Ce(),S(t,be,ne,e,n,o,i)}var hn=`<!-- header -->
|
|
34
34
|
|
|
35
35
|
<!-- table-of-contents -->
|
|
36
36
|
|
|
@@ -75,7 +75,7 @@ _List maintainer(s) for a repository, along with one way of contacting them (e.g
|
|
|
75
75
|
_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
|
|
76
76
|
|
|
77
77
|
<!-- footer -->
|
|
78
|
-
`;var
|
|
78
|
+
`;var yn=`<!-- title -->
|
|
79
79
|
|
|
80
80
|
<!-- banner -->
|
|
81
81
|
|
|
@@ -128,7 +128,7 @@ _State anyone or anything that significantly helped with the development of your
|
|
|
128
128
|
<!-- contributing -->
|
|
129
129
|
|
|
130
130
|
<!-- license -->
|
|
131
|
-
`;var
|
|
131
|
+
`;var wn=`<!-- header -->
|
|
132
132
|
|
|
133
133
|
## Install
|
|
134
134
|
|
|
@@ -144,7 +144,7 @@ Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
|
|
|
144
144
|
\`\`\`
|
|
145
145
|
|
|
146
146
|
<!-- footer -->
|
|
147
|
-
`;var
|
|
147
|
+
`;var bn=`<!-- title -->
|
|
148
148
|
|
|
149
149
|
<!-- short-description -->
|
|
150
150
|
|
|
@@ -166,7 +166,7 @@ Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
|
|
|
166
166
|
<!-- contributing -->
|
|
167
167
|
|
|
168
168
|
<!-- license -->
|
|
169
|
-
`;var
|
|
169
|
+
`;var Cn=`<!-- header -->
|
|
170
170
|
|
|
171
171
|
_Long description goes here._
|
|
172
172
|
|
|
@@ -229,7 +229,7 @@ _List maintainer(s) for a repository, along with one way of contacting them (e.g
|
|
|
229
229
|
_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
|
|
230
230
|
|
|
231
231
|
<!-- footer -->
|
|
232
|
-
`;var
|
|
232
|
+
`;var Pn=`<!-- title -->
|
|
233
233
|
|
|
234
234
|
<!-- banner -->
|
|
235
235
|
|
|
@@ -300,4 +300,4 @@ _State anyone or anything that significantly helped with the development of your
|
|
|
300
300
|
<!-- contributing -->
|
|
301
301
|
|
|
302
302
|
<!-- license -->
|
|
303
|
-
`;var A={"MDAT Readme":{content:{compound:gn,explicit:hn},description:"The house style. An expansive starting point. Prune to your context and taste.",exampleLink:"https://github.com/kitschpatrol/mdat/blob/main/readme.md"},"Standard Readme Basic":{content:{compound:yn,explicit:wn},description:'Includes only the "required" sections from the Standard Readme specification.',exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/minimal-readme.md"},"Standard Readme Full":{content:{compound:bn,explicit:Cn},description:"Includes all sections from the Standard Readme specification.",exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/maximal-readme.md"}};import{confirm as Pn,group as Uo,intro as Vo,note as Rn,outro as Bo,select as lt}from"@clack/prompts";import k from"chalk";import Jo from"node:fs/promises";import Re from"node:path";import{deepMergeDefined as Ho}from"remark-mdat";import{write as zo}from"to-vfile";async function On(){let t=await pt(),e=await X();return{packageDirectory:e===void 0?void 0:Re.dirname(Re.resolve(e)),readmePath:t}}async function Sn(){let{packageDirectory:t,readmePath:e}=await On(),n=Re.resolve(process.cwd());Vo(`Running ${k.bold("mdat readme init")} interactively`);let o=await Uo({overwrite:async()=>e===void 0||await Pn({message:`Found an existing readme at "${k.blue(e)}". Do you want to overwrite it?`,active:"Overwrite",inactive:"Exit"})?!0:(()=>{throw new Error("`mdat readme init` was cancelled to avoid an overwrite - no changes were made")})(),output:async()=>t!==void 0&&t!==n?lt({initialValue:t,message:"There's a root package directory nearby, do you want to create the readme there instead of the current directory?",options:[{label:`Create in the current package root: "${k.blue(t)}"`,value:t},{label:`Create in current working directory: "${k.blue(n)}"`,value:n}]}):n,template:async()=>lt({message:"Which template would you like to use?",options:Go()}),compound:async()=>lt({message:'Do you want to use "compound comments" where possible, which combine several expansions into a single comment block?',options:[{label:`Yes: Combine things like ${k.green("<!-- title -->")} and ${k.green("<!-- badges -->")} in a single ${k.green("<!-- header -->")} comment.`,value:!0},{label:"No: Use individual MDAT expansion comments for each section.",value:!1}]}),expand:async()=>t===void 0?!1:Pn({initialValue:!0,message:"Do you want to run `mdat readme` now to expand the template with content from your package.json?"})},{onCancel(){throw new Error("`mdat readme init` was cancelled - no changes were made")}}),i=await ut(o);return t===void 0&&Rn("No package.json was found. Once you've created one, you can run `mdat readme` to expand the template with content from your package.json."),Rn(`Readme created: "${k.bold.blue(i)}"`),Bo("Done!"),i}async function ut(t){let{packageDirectory:e}=await On(),n=Ho({compound:!0,output:e??process.cwd(),overwrite:!0,expand:e!==void 0,template:Object.keys(A)[0]},t??{}),o=qo(n.template,n.compound),i=Re.join(n.output,"readme.md");await Jo.writeFile(i,o,"utf8");let[r]=await Pe(i);return await zo(r),i}function qo(t,e){let o=A[t].content[e?"compound":"explicit"];if(o===void 0||o==="")throw new Error(`No template found for "${t}"`);return o}function Go(){return Object.entries(A).map(([t,e])=>({label:t,hint:e.description,value:t}))}var $={config:{defaultDescription:"Configuration is loaded if found from the usual places, or defaults are used.",description:"Path(s) to files containing MDAT configuration.",string:!0,type:"array"}},G={meta:{alias:"m",description:"Embed an extra comment at the top of the generated Markdown warning editors that certain sections of the document have been generated dynamically.",type:"boolean"}},K={name:{alias:"n",defaultDescription:"Same name as input file. Overwrites the input file.",description:"Output file name.",type:"string"}},F={output:{alias:"o",defaultDescription:"Same directory as input file.",description:"Output file directory.",type:"string"}},N={prefix:{description:"Require a string prefix before all comments to be considered for expansion. Useful if you have a bunch of non-MDAT comments in your Markdown file, or if you're willing to trade some verbosity for safety.",type:"string"}},W={print:{description:"Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options.",type:"boolean"}},Y={rules:{alias:"r",description:"Path(s) to files containing MDAT comment expansion rules.",string:!0,type:"array"}},E={verbose:{describe:"Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection.",type:"boolean"}},Oe=["files",{array:!0,demandOption:!0,describe:"Markdown file(s) with MDAT placeholder comments.",type:"string"}];var ft={package:{defaultDescription:"The closest package.json file is used by default.",description:"Path to the package.json file to use to populate the readme.",string:!0}},gt={assets:{defaultDescription:"./assets",description:"Path to find and save readme-related assets.",string:!0}},xn={interactive:{alias:"i",default:!0,description:"Run the guided interactive `init` process. Set explicitly to `false` to use default values and skip the prompt.",type:"boolean"}},kn={overwrite:{default:!1,defaultDescription:"`false`, if an existing readme is found, don't touch it.",description:"Replace an existing readme file if one is found.",type:"boolean"}},En={expand:{alias:"e",default:!0,description:"Automatically run `mdat readme` immediately after creating the readme template.",type:"boolean"}},Ln={template:{alias:"t",choices:Object.keys(A),default:Object.keys(A)[0],description:"Specify a template to use for the new readme.",type:"string"}},Tn={compound:{alias:"c",default:!0,description:"Use compound comment version of the template to replace several individual comment placeholders where possible. This combines things like `<!-- title -->`, `<!-- badges -->`, etc. in a single `<!-- header -->` comment. It's less clutter when you're editing, but it's also less explicit. The final readme.md output is identical.",type:"boolean"}},Se=["files",{array:!0,demandOption:!1,describe:"Readme file(s) with MDAT placeholder comments. If not provided, the closest readme.md file is used.",type:"string"}];import ht from"chalk";import M from"pretty-ms";import{getMdatReports as Ko,log as u,reporterMdat as U}from"remark-mdat";import{write as xe}from"to-vfile";import Wo from"yargs";import{hideBin as Yo}from"yargs/helpers";var D=performance.now(),vn=Wo(Yo(process.argv));try{await vn.scriptName("mdat").usage("$0 [command]","Work with MDAT placeholder comments in any Markdown file.").command(["$0 <files..> [options]","expand <files..> [options]"],"Expand MDAT placeholder comments.",t=>t.positional(...Oe).option($).option(Y).option(F).option(K).option(G).option(N).option(W).option(E),async({config:t,files:e,meta:n,name:o,output:i,prefix:r,print:s,rules:a,verbose:d})=>{u.verbose=d??!1,ke({name:o,output:i,print:s});let m=V(t,{addMetaComment:n,keywordPrefix:r}),c=await Lt(e,o,i,m,a);for(let p of c)s?process.stdout.write(p.toString()):await xe(p);U(c),u.info(`Expanded comments in ${M(performance.now()-D)}.`),process.exitCode=B(c)}).command("check <files..> [options]","Validate a Markdown file containing MDAT placeholder comments.",t=>t.positional(...Oe).option($).option(Y).option(G).option(N).option(E),async({config:t,files:e,meta:n,prefix:o,rules:i,verbose:r})=>{u.verbose=r??!1;let s=V(t,{addMetaComment:n,keywordPrefix:o}),a=await Tt(e,void 0,void 0,s,i);U(a),u.info(`Checked comments in ${M(performance.now()-D)}.`),process.exitCode=B(a)}).command("collapse <files..> [options]","Collapse MDAT placeholder comments.",t=>t.positional(...Oe).option($).option(F).option(K).option(N).option(W).option(E),async({config:t,files:e,name:n,output:o,prefix:i,print:r,verbose:s})=>{u.verbose=s??!1,ke({name:n,output:o,print:r});let a=V(t,{keywordPrefix:i}),d=await vt(e,void 0,void 0,a);for(let m of d)r?process.stdout.write(m.toString()):await xe(m);U(d),u.info(`Cleaned comments in ${M(performance.now()-D)}.`),process.exitCode=B(d)}).command("readme [command]","Work with MDAT comments in your readme.md.",t=>t.command(["$0 [files..] [options]","expand [files..] [options]"],"Expand MDAT comment placeholders in your readme.md using a collection of helpful built-in expansion rules.",e=>e.positional(...Se).option($).option(Y).option(F).option(K).option(ft).option(gt).option(N).option(G).option(W).option(E),async({assets:e,config:n,files:o,meta:i,name:r,output:s,package:a,prefix:d,print:m,rules:c,verbose:p})=>{u.verbose=p??!1,ke({name:r,output:s,print:m});let g=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:d,packageFile:a}),y=await Pe(o,r,s,g,c);for(let _ of y)m?process.stdout.write(_.toString()):await xe(_);U(y);let{packageFile:w}=await P();u.info(`Pulled package metadata from: ${ht.bold.blue(w)}`),u.info(`Expanded readme(s) in ${M(performance.now()-D)}.`),process.exitCode=B(y)}).command("check [files..] [options]","Validate MDAT placeholder comments in your readme.md.",e=>e.positional(...Se).option($).option(Y).option(ft).option(gt).option(N).option(G).option(E),async({assets:e,config:n,files:o,meta:i,package:r,prefix:s,rules:a,verbose:d})=>{u.verbose=d??!1;let m=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:s,packageFile:r}),c=await un(o,void 0,void 0,m,a);U(c);let{packageFile:p}=await P();u.info(`Pulled package metadata from: ${ht.bold.blue(p)}`),u.info(`Checked readme(s) in ${M(performance.now()-D)}.`),process.exitCode=B(c)}).command("collapse [files..] [options]","Collapse MDAT placeholder comments in your readme.md.",e=>e.positional(...Se).option(F).option(K).option(W).option($).option(N).option(E),async({config:e,files:n,name:o,output:i,prefix:r,print:s,verbose:a})=>{u.verbose=a??!1,ke({name:o,output:i,print:s});let d=V(e,{keywordPrefix:r}),m=await fn(n,void 0,void 0,d);for(let c of m)s?process.stdout.write(c.toString()):await xe(c);U(m),u.info(`Cleaned readme(s) in ${M(performance.now()-D)}.`),process.exitCode=B(m)}).command("init [options]","Interactively create a new readme.md file with sensible default MDAT comment placeholders.",e=>e.option(xn).option(kn).option(F).option(En).option(Ln).option(Tn).option(E),async({compound:e,expand:n,interactive:o,output:i,overwrite:r,template:s,verbose:a})=>{if(u.verbose=a??!1,o)await Sn();else{let d=await ut({compound:e,expand:n,output:i,overwrite:r,template:s});u.info(`Created readme at "${ht.blue(d)}" in ${M(performance.now()-D)}.`)}process.exitCode=0}),()=>{u.error("Root MDAT readme command should be unreachable.")}).help().alias("h","help").version().alias("v","version").wrap(process.stdout.isTTY?Math.min(120,vn.terminalWidth()):0).fail(!1).parse()}catch(t){t instanceof Error&&u.error(t.message),process.exitCode=1}function ke(t){t.print&&t.output&&u.warn("Ignoring --output option because --print is set"),t.print&&t.name&&u.warn("Ignoring --name option because --print is set")}function V(t,e){return[...Q(t),e]}function B(t){return Ko(t).reduce((o,i)=>o+i.errors.length,0)>0?1:0}
|
|
303
|
+
`;var A={"MDAT Readme":{content:{compound:hn,explicit:yn},description:"The house style. An expansive starting point. Prune to your context and taste.",exampleLink:"https://github.com/kitschpatrol/mdat/blob/main/readme.md"},"Standard Readme Basic":{content:{compound:wn,explicit:bn},description:'Includes only the "required" sections from the Standard Readme specification.',exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/minimal-readme.md"},"Standard Readme Full":{content:{compound:Cn,explicit:Pn},description:"Includes all sections from the Standard Readme specification.",exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/maximal-readme.md"}};import{confirm as Rn,group as Vo,intro as Bo,note as On,outro as Jo,select as lt}from"@clack/prompts";import k from"chalk";import Ho from"node:fs/promises";import Re from"node:path";import{deepMergeDefined as zo}from"remark-mdat";import{write as qo}from"to-vfile";async function Sn(){let t=await pt(),e=await X();return{packageDirectory:e===void 0?void 0:Re.dirname(Re.resolve(e)),readmePath:t}}async function xn(){let{packageDirectory:t,readmePath:e}=await Sn(),n=Re.resolve(process.cwd());Bo(`Running ${k.bold("mdat readme init")} interactively`);let o=await Vo({overwrite:async()=>e===void 0||await Rn({message:`Found an existing readme at "${k.blue(e)}". Do you want to overwrite it?`,active:"Overwrite",inactive:"Exit"})?!0:(()=>{throw new Error("`mdat readme init` was cancelled to avoid an overwrite - no changes were made")})(),output:async()=>t!==void 0&&t!==n?lt({initialValue:t,message:"There's a root package directory nearby, do you want to create the readme there instead of the current directory?",options:[{label:`Create in the current package root: "${k.blue(t)}"`,value:t},{label:`Create in current working directory: "${k.blue(n)}"`,value:n}]}):n,template:async()=>lt({message:"Which template would you like to use?",options:Ko()}),compound:async()=>lt({message:'Do you want to use "compound comments" where possible, which combine several expansions into a single comment block?',options:[{label:`Yes: Combine things like ${k.green("<!-- title -->")} and ${k.green("<!-- badges -->")} in a single ${k.green("<!-- header -->")} comment.`,value:!0},{label:"No: Use individual MDAT expansion comments for each section.",value:!1}]}),expand:async()=>t===void 0?!1:Rn({initialValue:!0,message:"Do you want to run `mdat readme` now to expand the template with content from your package.json?"})},{onCancel(){throw new Error("`mdat readme init` was cancelled - no changes were made")}}),i=await ut(o);return t===void 0&&On("No package.json was found. Once you've created one, you can run `mdat readme` to expand the template with content from your package.json."),On(`Readme created: "${k.bold.blue(i)}"`),Jo("Done!"),i}async function ut(t){let{packageDirectory:e}=await Sn(),n=zo({compound:!0,output:e??process.cwd(),overwrite:!0,expand:e!==void 0,template:Object.keys(A)[0]},t??{}),o=Go(n.template,n.compound),i=Re.join(n.output,"readme.md");await Ho.writeFile(i,o,"utf8");let[r]=await Pe(i);return await qo(r),i}function Go(t,e){let o=A[t].content[e?"compound":"explicit"];if(o===void 0||o==="")throw new Error(`No template found for "${t}"`);return o}function Ko(){return Object.entries(A).map(([t,e])=>({label:t,hint:e.description,value:t}))}var $={config:{defaultDescription:"Configuration is loaded if found from the usual places, or defaults are used.",description:"Path(s) to files containing MDAT configuration.",string:!0,type:"array"}},G={meta:{alias:"m",description:"Embed an extra comment at the top of the generated Markdown warning editors that certain sections of the document have been generated dynamically.",type:"boolean"}},K={name:{alias:"n",defaultDescription:"Same name as input file. Overwrites the input file.",description:"Output file name.",type:"string"}},F={output:{alias:"o",defaultDescription:"Same directory as input file.",description:"Output file directory.",type:"string"}},N={prefix:{description:"Require a string prefix before all comments to be considered for expansion. Useful if you have a bunch of non-MDAT comments in your Markdown file, or if you're willing to trade some verbosity for safety.",type:"string"}},W={print:{description:"Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options.",type:"boolean"}},Y={rules:{alias:"r",description:"Path(s) to files containing MDAT comment expansion rules.",string:!0,type:"array"}},E={verbose:{describe:"Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection.",type:"boolean"}},Oe=["files",{array:!0,demandOption:!0,describe:"Markdown file(s) with MDAT placeholder comments.",type:"string"}];var ft={package:{defaultDescription:"The closest package.json file is used by default.",description:"Path to the package.json file to use to populate the readme.",string:!0}},gt={assets:{defaultDescription:"./assets",description:"Path to find and save readme-related assets.",string:!0}},kn={interactive:{alias:"i",default:!0,description:"Run the guided interactive `init` process. Set explicitly to `false` to use default values and skip the prompt.",type:"boolean"}},En={overwrite:{default:!1,defaultDescription:"`false`, if an existing readme is found, don't touch it.",description:"Replace an existing readme file if one is found.",type:"boolean"}},Ln={expand:{alias:"e",default:!0,description:"Automatically run `mdat readme` immediately after creating the readme template.",type:"boolean"}},Tn={template:{alias:"t",choices:Object.keys(A),default:Object.keys(A)[0],description:"Specify a template to use for the new readme.",type:"string"}},vn={compound:{alias:"c",default:!0,description:"Use compound comment version of the template to replace several individual comment placeholders where possible. This combines things like `<!-- title -->`, `<!-- badges -->`, etc. in a single `<!-- header -->` comment. It's less clutter when you're editing, but it's also less explicit. The final readme.md output is identical.",type:"boolean"}},Se=["files",{array:!0,demandOption:!1,describe:"Readme file(s) with MDAT placeholder comments. If not provided, the closest readme.md file is used.",type:"string"}];import ht from"chalk";import M from"pretty-ms";import{getMdatReports as Wo,log as u,reporterMdat as U}from"remark-mdat";import{write as xe}from"to-vfile";import Yo from"yargs";import{hideBin as Zo}from"yargs/helpers";var D=performance.now(),An=Yo(Zo(process.argv));try{await An.scriptName("mdat").usage("$0 [command]","Work with MDAT placeholder comments in any Markdown file.").command(["$0 <files..> [options]","expand <files..> [options]"],"Expand MDAT placeholder comments.",t=>t.positional(...Oe).option($).option(Y).option(F).option(K).option(G).option(N).option(W).option(E),async({config:t,files:e,meta:n,name:o,output:i,prefix:r,print:s,rules:a,verbose:d})=>{u.verbose=d??!1,ke({name:o,output:i,print:s});let m=V(t,{addMetaComment:n,keywordPrefix:r}),c=await Tt(e,o,i,m,a);for(let p of c)s?process.stdout.write(p.toString()):await xe(p);U(c),u.info(`Expanded comments in ${M(performance.now()-D)}.`),process.exitCode=B(c)}).command("check <files..> [options]","Validate a Markdown file containing MDAT placeholder comments.",t=>t.positional(...Oe).option($).option(Y).option(G).option(N).option(E),async({config:t,files:e,meta:n,prefix:o,rules:i,verbose:r})=>{u.verbose=r??!1;let s=V(t,{addMetaComment:n,keywordPrefix:o}),a=await vt(e,void 0,void 0,s,i);U(a),u.info(`Checked comments in ${M(performance.now()-D)}.`),process.exitCode=B(a)}).command("collapse <files..> [options]","Collapse MDAT placeholder comments.",t=>t.positional(...Oe).option($).option(F).option(K).option(N).option(W).option(E),async({config:t,files:e,name:n,output:o,prefix:i,print:r,verbose:s})=>{u.verbose=s??!1,ke({name:n,output:o,print:r});let a=V(t,{keywordPrefix:i}),d=await At(e,void 0,void 0,a);for(let m of d)r?process.stdout.write(m.toString()):await xe(m);U(d),u.info(`Cleaned comments in ${M(performance.now()-D)}.`),process.exitCode=B(d)}).command("readme [command]","Work with MDAT comments in your readme.md.",t=>t.command(["$0 [files..] [options]","expand [files..] [options]"],"Expand MDAT comment placeholders in your readme.md using a collection of helpful built-in expansion rules.",e=>e.positional(...Se).option($).option(Y).option(F).option(K).option(ft).option(gt).option(N).option(G).option(W).option(E),async({assets:e,config:n,files:o,meta:i,name:r,output:s,package:a,prefix:d,print:m,rules:c,verbose:p})=>{u.verbose=p??!1,ke({name:r,output:s,print:m});let g=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:d,packageFile:a}),y=await Pe(o,r,s,g,c);for(let _ of y)m?process.stdout.write(_.toString()):await xe(_);U(y);let{packageFile:w}=await P();u.info(`Pulled package metadata from: ${ht.bold.blue(w)}`),u.info(`Expanded readme(s) in ${M(performance.now()-D)}.`),process.exitCode=B(y)}).command("check [files..] [options]","Validate MDAT placeholder comments in your readme.md.",e=>e.positional(...Se).option($).option(Y).option(ft).option(gt).option(N).option(G).option(E),async({assets:e,config:n,files:o,meta:i,package:r,prefix:s,rules:a,verbose:d})=>{u.verbose=d??!1;let m=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:s,packageFile:r}),c=await fn(o,void 0,void 0,m,a);U(c);let{packageFile:p}=await P();u.info(`Pulled package metadata from: ${ht.bold.blue(p)}`),u.info(`Checked readme(s) in ${M(performance.now()-D)}.`),process.exitCode=B(c)}).command("collapse [files..] [options]","Collapse MDAT placeholder comments in your readme.md.",e=>e.positional(...Se).option(F).option(K).option(W).option($).option(N).option(E),async({config:e,files:n,name:o,output:i,prefix:r,print:s,verbose:a})=>{u.verbose=a??!1,ke({name:o,output:i,print:s});let d=V(e,{keywordPrefix:r}),m=await gn(n,void 0,void 0,d);for(let c of m)s?process.stdout.write(c.toString()):await xe(c);U(m),u.info(`Cleaned readme(s) in ${M(performance.now()-D)}.`),process.exitCode=B(m)}).command("init [options]","Interactively create a new readme.md file with sensible default MDAT comment placeholders.",e=>e.option(kn).option(En).option(F).option(Ln).option(Tn).option(vn).option(E),async({compound:e,expand:n,interactive:o,output:i,overwrite:r,template:s,verbose:a})=>{if(u.verbose=a??!1,o)await xn();else{let d=await ut({compound:e,expand:n,output:i,overwrite:r,template:s});u.info(`Created readme at "${ht.blue(d)}" in ${M(performance.now()-D)}.`)}process.exitCode=0}),()=>{u.error("Root MDAT readme command should be unreachable.")}).help().alias("h","help").version().alias("v","version").wrap(process.stdout.isTTY?Math.min(120,An.terminalWidth()):0).fail(!1).parse()}catch(t){t instanceof Error&&u.error(t.message),process.exitCode=1}function ke(t){t.print&&t.output&&u.warn("Ignoring --output option because --print is set"),t.print&&t.name&&u.warn("Ignoring --name option because --print is set")}function V(t,e){return[...Q(t),e]}function B(t){return Wo(t).reduce((o,i)=>o+i.errors.length,0)>0?1:0}
|
package/dist/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
import{defaultLoaders as
|
|
2
|
-
${JSON.stringify(t,void 0,2)}`)}function
|
|
3
|
-
${JSON.stringify(t,void 0,2)}`)}var V;async function b(){return V===void 0&&(h.warn("getConfig(): config was undefined"),V??=await y()),V}var ae;async function l(){let{packageFile:t}=await b();if(t===void 0)throw new Error("No packageFile found or set in config");if(ae??=await
|
|
4
|
-
`)},order:3}};import{globby as
|
|
1
|
+
import{defaultLoaders as Ut}from"cosmiconfig";function ie(t,e){let n=Ut[".json"],o=n(t,e);return Je(o)}function Je(t,e="",n={}){for(let[o,r]of Object.entries(t)){let i=e?`${e}.${o}`:o;typeof r=="object"&&r!==null&&!Array.isArray(r)?Je(r,i,n):r===null?n[i]="null":n[i]=r.toString()}return n}import vt from"node:fs";import P from"node:path";import{packageUp as It}from"package-up";import{isFileSync as Be}from"path-type";import _t from"untildify";function Vt(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function ze(t,e,n,o){let r=[];for(let[i,s]of t.entries()){let a=n&&t.length>1?`-${Vt(i+1,t.length+1)}`:"",d=Jt(s,e,n,o,a);r.push(d)}return r}function Jt(t,e,n,o,r=""){let i=He(t),s=e?He(e):void 0;if(!Be(i))throw new Error(`Input file not found: "${i}"`);if(s){if(Be(s))throw new Error(`Output path must be a directory, received a file path: "${s}"`);vt.mkdirSync(s,{recursive:!0})}let a=n?P.basename(n,P.extname(n)):P.basename(i,P.extname(i)),d=`.${o??(n&&P.extname(n)!==""?P.extname(n):P.extname(t)===""?"":P.extname(t))}`,m=`${a}${r}${d}`,p=s??P.dirname(i);return{input:i,name:m,output:p}}function He(t){return _t(t)}async function Ke(){return It()}function Ge(t){return t==null?[]:Array.isArray(t)?t:[t]}import qe from"chalk";import{cosmiconfig as Ye}from"cosmiconfig";import{TypeScriptLoader as We}from"cosmiconfig-typescript-loader";import Bt from"node:fs/promises";import Qe from"node:path";import Ht from"plur";import{readPackage as zt}from"read-pkg";import{deepMergeDefined as _,log as h,optionsSchema as Kt,rulesSchema as Gt}from"remark-mdat";import{z as se}from"zod";var Ze=Kt.merge(se.object({assetsPath:se.string().optional(),packageFile:se.string().optional()})).describe("Config Extension");async function y(t){let{additionalConfig:e,additionalRules:n,searchFrom:o}=t??{},r={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await Ke(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},i=Ye("mdat",{loaders:{".ts":We()}}),s=await i.search(o);if(s){let{config:a,filepath:d}=s;h.info(`Using config from "${d}"`);let m=Xe(a,Ze);m&&(r=_(r,m))}if(e!==void 0){let a=Array.isArray(e)?e:[e];for(let d of a){let m;if(typeof d=="string"){let f=await i.load(d);if(f==null)continue;let{config:g,filepath:L}=f;h.info(`Loaded additional config from "${L}"`),m=g}else m=d;if(m===void 0)continue;h.info("Merging configuration object");let p=Xe(m,Ze);p!==void 0&&(r=_(r,p))}}if(n!==void 0){let a=Array.isArray(n)?n:[n],d=Ye("mdat",{loaders:{".json":ie,".ts":We()}});for(let m of a){let p;if(typeof m=="string"){let g;if(Qe.basename(m).endsWith("package.json")){let re=await Bt.readFile(m,"utf8");g={config:ie(m,re),filepath:m}}else g=await d.load(m);if(g==null)continue;let{config:L,filepath:w}=g;h.info(`Loaded additional config from "${w}"`),p=L}else p=m;if(p===void 0)continue;h.info("Merging rules into configuration object");let f=qt(p,Gt);f!==void 0&&(r=_(r,f))}}if(r.rules){let a=Object.keys(r.rules).sort().map(d=>`"${qe.bold.green(d)}"`);h.info(`Loaded ${qe.bold(a.length)} mdat comment expansion ${Ht("rule",a.length)}:`);for(let d of a)h.info(` ${d}`)}else h.error("No rules loaded from additional configurations or rules, using default.");return V=r,r}function qt(t,e){if(e.safeParse(t).success)return{rules:t};h.error(`Rules object has the wrong shape. Ignoring and using default configuration:
|
|
2
|
+
${JSON.stringify(t,void 0,2)}`)}function Xe(t,e){if(e.safeParse(t).success)return t;h.error(`Config object has the wrong shape. Ignoring and using default configuration:
|
|
3
|
+
${JSON.stringify(t,void 0,2)}`)}var V;async function b(){return V===void 0&&(h.warn("getConfig(): config was undefined"),V??=await y()),V}var ae;async function l(){let{packageFile:t}=await b();if(t===void 0)throw new Error("No packageFile found or set in config");if(ae??=await zt({cwd:Qe.dirname(t)}),ae===void 0)throw new Error("No package.json found");return ae}function Yt(t,e){return _(t,e)}import{remark as me}from"remark";import de from"remark-gfm";import{mdatCheck as Wt,mdatClean as et,mdatExpand as Zt,mdatSplit as tt}from"remark-mdat";import{read as Xt}from"to-vfile";import{VFile as Qt}from"vfile";async function E(t,e,n,o,r,i,s){let a=await e({additionalConfig:i,additionalRules:s});i=a;let d=Ge(t),m=ze(d,r,o,"md"),p=[],f=n(a);for(let{input:g,name:L,output:w}of m){let re=await Xt(g),I=await f.process(re);I.dirname=w,I.basename=L,p.push(I)}return p}async function O(t,e,n,o,r){let i=await e({additionalConfig:o,additionalRules:r});return o=i,n(i).process(new Qt(t))}function x(t){return me().use({settings:{bullet:"-",emphasis:"_"}}).use(de).use(()=>async function(n,o){tt(n,o),et(n,o,t),await Zt(n,o,t)})}function F(t){return me().use({settings:{bullet:"-",emphasis:"_"}}).use(de).use(()=>function(n,o){tt(n,o),et(n,o,t)})}function $(t){return me().use({settings:{bullet:"-",emphasis:"_"}}).use(de).use(()=>async function(n,o){await Wt(n,o,{...t,paranoid:!1})})}async function en(t,e,n,o,r){return E(t,y,x,e,n,o,r)}async function tn(t,e,n){return O(t,y,x,e,n)}async function nn(t,e,n,o,r){return E(t,y,$,e,n,o,r)}async function on(t,e,n){return O(t,y,$,e,n)}async function rn(t,e,n,o,r){return E(t,y,F,e,n,o,r)}async function sn(t,e,n){return O(t,y,F,e,n)}import{z as N}from"zod";var J={badges:{async content(t){var s;let e=N.object({custom:N.record(N.object({image:N.string(),link:N.string()})).optional(),npm:N.array(N.string()).optional()}).optional().parse(t),n=await l(),{name:o}=n,r=[];if(!n.private&&((s=n.publishConfig)==null?void 0:s.access)==="public"&&r.push(`[](https://npmjs.com/package/${o})`),(e==null?void 0:e.npm)!==void 0)for(let a of e.npm)r.push(`[](https://npmjs.com/package/${a})`);let{license:i}=n;if(i!==void 0&&r.push(`[](https://opensource.org/licenses/${i})`),(e==null?void 0:e.custom)!==void 0)for(let[a,{image:d,link:m}]of Object.entries(e.custom))r.push(`[](${m})`);return r.join(`
|
|
4
|
+
`)},order:3}};import{globby as an}from"globby";import B from"node:path";import{isFile as mn}from"path-type";import{readPackage as dn}from"read-pkg";import{z as ce}from"zod";var H={banner:{async content(t){let e=ce.object({alt:ce.string().optional(),src:ce.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:o}=await b();if(o===void 0)throw new Error("No package.json found");let r=(e==null?void 0:e.src)??await nt(n)??await nt();if(r===void 0)throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");if(!ot(r)&&!await mn(r))throw new Error(`Banner image not found at "${r}"`);let i=(e==null?void 0:e.alt)??`${(await dn({cwd:B.dirname(o)})).name} banner`;if(i===void 0||i==="undefined banner")throw new Error("Banner image alt text not available");return``},order:2}};async function nt(t){let{packageFile:e}=await b();if(e===void 0)throw new Error("No package.json found");let n=B.dirname(e),o=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images",".github/assets"]:[t],r=["banner","cover","demo","header","hero","image","logo","overview","readme","screenshot","screenshots","splash"],i=["png","gif","jpg","jpeg","svg","webp"],s=await an(o.map(a=>B.join(n,a)),{deep:1,expandDirectories:{extensions:i,files:r}});if(s.length>0)return B.relative(process.cwd(),s[0])}function ot(t,e=!0){if(typeof t!="string")throw new TypeError("Expected a string");if(t=t.trim(),t.includes(" "))return!1;try{return new URL(t),!0}catch{return e?ot(`https://${t}`,!1):!1}}function rt(t,e=Number.MAX_SAFE_INTEGER){var r;let n=[],o=cn(t,e);return n.push(pn(o)),n.push(fn(t,o)),o.hasMultipleSubcommands&&o.canRecurse&&n.push(un(o.fullCommandName)),((r=o.defaultCommand)==null?void 0:r.commandName)!==void 0&&n.push(ln(o)),n.push(gn(t,o)),t.positionals&&!o.commandsOnly&&n.push(pe(["Positional Argument","Description","Type","Default"],t.positionals.map(i=>[i.arguments?[i.arguments.map(s=>`\`${s}\``)].join(" "):"",`${i.description??""}${i.required?" _(Required.)_":" _(Optional.)_"}`,i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),t.commands&&n.push(pe(["Command","Argument","Description"],t.commands.map(i=>{var s;return[`\`${i.commandName??(i.default?"[default]":"")}\``,i.arguments?(s=i.arguments)==null?void 0:s.map(a=>`\`${a}\``).join(" "):"",`${i.description??""}${i.default?" _(Default command.)_":""}`]}))),t.options&&!o.commandsOnly&&n.push(pe(["Option","Alias","Argument","Description","Type","Default"],t.options.map(i=>[i.flags?i.flags.map(s=>`\`${s}\``).join(" "):"",i.aliases?i.aliases.map(s=>`\`${s}\``).join(" "):"",i.arguments?i.arguments.map(s=>`\`${s}\``).join(" "):"",i.description??"",i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),o.canRecurse&&o.hasMultipleSubcommands&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
|
|
5
5
|
|
|
6
|
-
`)}function
|
|
6
|
+
`)}function cn(t,e){var m,p;let n=t.subcommandName===void 0,o=t.commands?t.commands.length>1:!1,r=e>1,i=(m=t.commands)==null?void 0:m.find(f=>f.default),s=(p=t.commands)==null?void 0:p.find(f=>f.commandName===void 0),a=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`,d=r&&o&&(i==null?void 0:i.commandName)!==void 0;return{canRecurse:r,commandsOnly:d,defaultCommand:i,fullCommandName:a,hasMultipleSubcommands:o,isTopLevel:n,topLevelCommand:s}}function pn(t){return`#### ${t.isTopLevel?"Command":"Subcommand"}: \`${t.fullCommandName}\``}function fn(t,e){var n,o;return e.isTopLevel&&((n=e.topLevelCommand)!=null&&n.description)?(t.commands=(o=t.commands)==null?void 0:o.filter(r=>r!==e.topLevelCommand),e.topLevelCommand.description):t.description??""}function un(t){return`This section lists top-level commands for \`${t}\`.`}function ln(t){var e,n;return`If no command is provided, \`${(e=t.defaultCommand)==null?void 0:e.parentCommandName} ${(n=t.defaultCommand)==null?void 0:n.commandName}\` is run by default.`}function gn(t,e){var o;let n=(o=e.topLevelCommand)!=null&&o.arguments?` ${e.topLevelCommand.arguments.join(" ")}`:`${t.arguments?` ${t.arguments.join(" ")}`:""}`;return`Usage:
|
|
7
7
|
|
|
8
8
|
\`\`\`txt
|
|
9
9
|
${e.fullCommandName}${n}
|
|
10
|
-
\`\`\``}function pe(t,e){let n=
|
|
10
|
+
\`\`\``}function pe(t,e){let n=hn(e);t=t.filter((r,i)=>!n.includes(i)),e=e.map(r=>r.filter((i,s)=>!n.includes(s)));let o="";o+=`| ${t.join(" | ")} |
|
|
11
11
|
`,o+=`| ${t.map(()=>"---").join(" | ")} |
|
|
12
12
|
`;for(let r of e)o+=`| ${r.join(" | ")} |
|
|
13
|
-
`;return o}function
|
|
13
|
+
`;return o}function hn(t){var o;let e=[],n=((o=t[0])==null?void 0:o.length)||0;for(let r=0;r<n;r++){let i=!0;for(let s of t)if(s[r]!==""){i=!1;break}i&&e.push(r)}return e}import{CstParser as yn,Lexer as S,createToken as u}from"chevrotain";var K=u({name:"flag",pattern:/--[\w-_]+/}),le=u({longer_alt:K,name:"alias",pattern:/-[A-Za-z]/}),it=u({group:S.SKIPPED,name:"comma",pattern:/,/}),st=u({group:S.SKIPPED,name:"dollar",pattern:/\$/}),z=u({group:S.SKIPPED,name:"whiteSpace",pattern:/ /}),at=u({group:S.SKIPPED,name:"newLine",pattern:/\n/}),ge=u({name:"word",pattern:/\S+/}),D=u({name:"argument",pattern:/(<\S+>|\[.+])/}),he=u({name:"programDescription",pattern:/\w.+(?=\n\n {2}Usage)/}),mt=u({group:S.SKIPPED,name:"startUsage",pattern:/ {2}Usage\n/,push_mode:"USAGE_MODE"}),dt=u({group:S.SKIPPED,name:"endUsage",pattern:/\n/,pop_mode:!0}),ye=u({name:"startOptions",pattern:/ {2}Options\n/,push_mode:"OPTIONS_MODE"}),Ce=u({name:"startRow",pattern:/ {4}/,push_mode:"ROW_MODE"}),we=u({name:"rowDescription",pattern:/\w.+/}),ct=u({group:S.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),pt=u({group:S.SKIPPED,name:"endOptions",pattern:/\n/,pop_mode:!0}),Cn=new S({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[mt,ye,he,at,z],OPTIONS_MODE:[pt,Ce],ROW_MODE:[ct,le,K,it,D,we,z],USAGE_MODE:[dt,st,D,ge,z]}}),wn=[K,le,it,st,z,at,ge,D,he,mt,dt,ye,Ce,we,ct,pt],fe=class extends yn{programHelp=this.RULE("programHelp",()=>{this.CONSUME(he,{LABEL:"description"}),this.AT_LEAST_ONE(()=>{this.CONSUME(ge,{LABEL:"commandName"})}),this.MANY(()=>{this.CONSUME(D)}),this.OPTION(()=>{this.SUBRULE(this.optionsSection)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(ye),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(Ce),this.MANY(()=>{this.OR([{ALT:()=>this.CONSUME(D)},{ALT:()=>this.CONSUME(le)},{ALT:()=>this.CONSUME(K)},{ALT:()=>this.CONSUME(we,{LABEL:"description"})}])})});constructor(){super(wn),this.performSelfAnalysis()}},j=new fe,ue=class extends j.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:o}=G(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,subcommandName:o}}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),description:this.getString(e.description,!0),flags:this.getArray(e.flag)}}getString(e,n=!1){if(e!==void 0)return e.map(o=>n?this.clean(o.image):o.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}},Pn=new ue;function ft(t){let e=Cn.tokenize(t);if(e.errors.length>0)throw new Error(`Errors lexing CLI command: ${JSON.stringify(e.errors,void 0,2)}`);j.input=e.tokens;let n=j.programHelp();if(j.errors.length>0)throw new Error(`Errors parsing CLI command help text: ${JSON.stringify(j.errors,void 0,2)}`);let o;try{o=Pn.visit(n)}catch(r){if(r instanceof Error)throw new TypeError(`Errors visiting CLI command help text: ${String(r)}`)}if(o===void 0)throw new Error("Could not parse help string");return o}import{CstParser as Sn,Lexer as k,createToken as c}from"chevrotain";var Re=c({name:"flag",pattern:/--[\w-_]+/}),Le=c({name:"alias",pattern:/-[A-Za-z]/}),ut=c({group:k.SKIPPED,name:"comma",pattern:/,/}),A=c({name:"word",pattern:/\S+/}),v=c({name:"argument",pattern:/<\S+>|\[\S+]/}),be=c({name:"type",pattern:/\[(boolean|string|array)]/}),Oe=c({name:"defaultInfo",pattern:/\[default]/}),Ne=c({name:"required",pattern:/\[required]/}),ke=c({name:"defaultInfoDescription",pattern:/\[default:\s.+?]/}),Te=c({name:"choices",pattern:/\[choices:\s.+?]/}),Pe=c({group:k.SKIPPED,name:"whiteSpace",pattern:/\s/}),lt=c({group:k.SKIPPED,name:"startProgramDescription",pattern:/\n\n/,push_mode:"PROGRAM_DESCRIPTION_MODE"}),xe=c({name:"programDescription",pattern:/.+/}),gt=c({group:k.SKIPPED,name:"endProgramDescription",pattern:/\n\n/,pop_mode:!0}),$e=c({name:"startOptionsSection",pattern:/Options:?\n/,push_mode:"SECTION_MODE"}),Ae=c({name:"startPositionalsSection",pattern:/Positionals:\n/,push_mode:"SECTION_MODE"}),Me=c({name:"startCommandsSection",pattern:/Commands:\n/,push_mode:"SECTION_MODE"}),Fe=c({name:"startRow",pattern:/ {2,}/,push_mode:"ROW_MODE"}),je=c({name:"rowDescription",pattern:/ {2}\w.+ {2}/}),De=c({name:"rowDescriptionTerminal",pattern:/ {2}\w.+/}),ht=c({group:k.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),yt=c({group:k.SKIPPED,name:"endSection",pattern:/\n+/,pop_mode:!0}),En=new k({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[$e,Ae,Me,lt,v,A,Pe],PROGRAM_DESCRIPTION_MODE:[gt,xe],ROW_MODE:[ht,ut,be,je,De,ke,Oe,Ne,Te,Re,Le,v,A,Pe],SECTION_MODE:[Fe,yt]}}),Rn=[Re,Le,ut,A,v,be,Oe,Ne,ke,Te,Pe,lt,xe,gt,$e,Ae,Me,Fe,je,De,ht,yt],Se=class extends Sn{programHelp=this.RULE("programHelp",()=>{this.AT_LEAST_ONE(()=>{this.CONSUME(A,{LABEL:"commandName"})}),this.MANY1(()=>{this.CONSUME(v)}),this.OPTION(()=>{this.CONSUME(xe,{LABEL:"description"})}),this.OPTION1(()=>{this.SUBRULE(this.commandsSection)}),this.OPTION2(()=>{this.SUBRULE(this.positionalsSection)}),this.OPTION3(()=>{this.SUBRULE(this.optionsSection)})});positionalsSection=this.RULE("positionalsSection",()=>{this.CONSUME(Ae),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});commandsSection=this.RULE("commandsSection",()=>{this.CONSUME(Me),this.MANY1(()=>{this.SUBRULE1(this.sectionRow)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME($e),this.MANY2(()=>{this.SUBRULE2(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(Fe),this.OPTION(()=>{this.CONSUME(A,{LABEL:"parentCommandName"})}),this.MANY(()=>{this.CONSUME1(A,{LABEL:"commandName"})}),this.MANY1(()=>{this.OR([{ALT:()=>this.CONSUME(v)},{ALT:()=>this.CONSUME(Le)},{ALT:()=>this.CONSUME(Re)},{ALT:()=>this.CONSUME(je,{LABEL:"description"})},{ALT:()=>this.CONSUME(De,{LABEL:"description"})},{ALT:()=>this.CONSUME(be)},{ALT:()=>this.CONSUME(Ne)},{ALT:()=>this.CONSUME(ke)},{ALT:()=>this.CONSUME(Oe)},{ALT:()=>this.CONSUME(Te)}])})});constructor(){super(Rn),this.performSelfAnalysis()}},U=new Se,Ee=class extends U.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:o}=G(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,commands:e.commandsSection?this.visit(e.commandsSection):void 0,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,positionals:e.positionalsSection?this.visit(e.positionalsSection):void 0,subcommandName:o}}positionalsSection(e){return e.sectionRow.map(n=>this.positionalParentCommandToArguments(this.visit(n)))}commandsSection(e){return e.sectionRow.map(n=>this.visit(n))}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),choices:this.splitChoices(this.getString(e.choices)),commandName:this.getString(e.commandName),default:e.defaultInfo?!0:void 0,defaultValue:this.getString(e.defaultInfoDescription,!0),description:this.getString(e.description,!0),flags:this.getArray(e.flag),parentCommandName:this.getString(e.parentCommandName),required:e.required?!0:void 0,type:this.getString(e.type,!0)}}positionalParentCommandToArguments(e){let{arguments:n,parentCommandName:o,...r}=e;return o===void 0?e:{arguments:[o,...n??[]],...r}}getString(e,n=!1){if(e!==void 0)return e.map(o=>n?this.clean(o.image):o.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}splitChoices(e){if(e!==void 0)return this.clean(e.replaceAll(/^\[choices:\s/g,"")).split(", ")}},Ln=new Ee;function Ct(t){let e=En.tokenize(t);if(e.errors.length>0)throw new Error(`Errors lexing CLI command: ${JSON.stringify(e.errors,void 0,2)}`);U.input=e.tokens;let n=U.programHelp();if(U.errors.length>0)throw new Error(`Errors parsing CLI command help text: ${JSON.stringify(U.errors,void 0,2)}`);let o;try{o=Ln.visit(n)}catch(r){if(r instanceof Error)throw new TypeError(`Errors visiting CLI command help text: ${String(r)}`)}if(o===void 0)throw new Error("Could not parse help string");return o}var wt={meow:ft,yargs:Ct};function G(t){if(t===void 0)throw new Error('Could not find "commandName" entry in help');let e=t.split(" ");if(e.length===0&&t===void 0)throw new Error('Could not find "commandName" entry in help');if(e.length===1)return{command:e[0],subcommand:void 0};let n=e.at(-1);return{command:e.slice(0,-1).join(" "),subcommand:n}}import{log as Ue}from"remark-mdat";function Pt(t){for(let[e,n]of Object.entries(wt)){Ue.info(`Trying to parse help string with ${e} parser...`);try{return n(t)}catch(o){o instanceof Error&&Ue.info(`Error in "${e}" parser: ${String(o)}`);continue}}Ue.error("Could not parse help string with any parser")}import{execaCommand as bn}from"execa";import{log as St}from"remark-mdat";async function ve(t,e="--help",n){let o=`${t} ${e}`,r=await kn(o),i=Pt(r);return i===void 0?(St.warn("Falling back to basic cli help text output."),Nn(r)):On(t,e,n??Number.MAX_SAFE_INTEGER,i)}async function On(t,e,n,o){if(n<=0)return St.info("Max CLI command help depth reached, stopping recursion"),"";let r=rt(o,n),i=t.split(" ")[0];if(o.commands)for(let s of o.commands){if(!s.parentCommandName||!s.commandName)continue;let a=await ve(`${i} ${s.commandName}`,e,n-1);if(a==="")return r;r+=`
|
|
14
14
|
|
|
15
|
-
${a}`}return r}function
|
|
15
|
+
${a}`}return r}function Nn(t){return`\`\`\`txt
|
|
16
16
|
${t}
|
|
17
|
-
\`\`\``}async function
|
|
17
|
+
\`\`\``}async function kn(t){let e;try{let{stderr:n,stdout:o}=await bn(t);e=o,(e===void 0||e==="")&&(e=n)}catch(n){if(n instanceof Error)throw new TypeError(`Error running CLI help command: "${t}"
|
|
18
18
|
${n.message}
|
|
19
19
|
`)}if(e===void 0||e==="")throw new Error(`No result from running CLI help command: "${t}"
|
|
20
|
-
`);return e}import{isExecutable as
|
|
20
|
+
`);return e}import{isExecutable as Tn}from"is-executable";import xn from"node:path";import{log as $n}from"remark-mdat";import An from"which";async function Et(t){return t??=await Mn(),jn(t)}async function Mn(){let t=await l();if(t!=null&&t.bin){let e=typeof t.bin=="string"?t.bin:String(Object.values(t.bin).at(0));if(Fn(e))return $n.info(`Inferred <!-- cli-help --> command to run from package.json: ${e}`),e}throw new Error(`Could not infer which command to run for the <!-- cli-help --> rule. Please pass a "cliCommand" option to the expansion comment, e.g. <!-- cli-help {cliCommend: './dist/bin.js'} -->`)}function Fn(t){let e=xn.parse(t);return e.root!==""||e.dir!==""}async function jn(t){let e=await An(t,{nothrow:!0});if(e===null&&(e=await Dn(t)??void 0),e!==void 0&&await Tn(e))return e;throw new Error(`The cli-help rule noticed that "${e}" is not executable.`)}async function Dn(t){var n;let e=await l();return((n=e==null?void 0:e.bin)==null?void 0:n[t])??void 0}import{z as q}from"zod";var Rt={"cli-help":{async content(t){let e=q.object({cliCommand:q.string().optional(),depth:q.number().optional(),helpFlag:q.string().optional()}).optional().parse(t),n=await Et(e==null?void 0:e.cliCommand);return ve(n,e==null?void 0:e.helpFlag,e==null?void 0:e.depth)}}};import Un from"node:fs/promises";import Lt from"node:path";import{z as Ie}from"zod";var bt={code:{async content(t){let e=Ie.object({file:Ie.string(),language:Ie.string().optional()}).parse(t),n=Lt.extname(e.file)??"",o=await Un.readFile(Lt.join(process.cwd(),e.file),"utf8");return`\`\`\`${n}
|
|
21
21
|
${o}
|
|
22
22
|
\`\`\``}}};var Y={contributing:{async content(){var n;let t=await l(),e=(n=t==null?void 0:t.bugs)==null?void 0:n.url;if(e===void 0)throw new Error('Could not find "bugs.url" entry in package.json');return`## Contributing
|
|
23
23
|
[Issues](${e}) and pull requests are welcome.`},order:15}};var W={description:{async content(){let t=await l();if(t.description===void 0)throw new Error('Could not find "description" entry in package.json');return`**${t.description}**`},order:4}};var Z={license:{async content(){let t=await l(),{author:e,license:n}=t;if((e==null?void 0:e.name)===void 0)throw new Error('Could not find "author.name" entry in package.json');if(n===void 0)throw new Error('Could not find "license" entry in package.json');return`## License
|
|
24
|
-
[${n}](license.txt) \xA9 ${e.name}`},order:16}};import{getSoleRule as
|
|
24
|
+
[${n}](license.txt) \xA9 ${e.name}`},order:16}};import{getSoleRule as Ot}from"remark-mdat";var Nt={footer:{content:[Ot(Y),Ot(Z)],order:17}};import{getSoleRule as vn}from"remark-mdat";var X={"short-description":vn(W)};import{z as Q}from"zod";var ee={title:{applicationOrder:2,async content(t){let{postfix:e,prefix:n,titleCase:o}=Q.object({postfix:Q.string().optional().default(""),prefix:Q.string().optional().default(""),titleCase:Q.boolean().optional().default(!1)}).parse(t??{}),{name:r}=await l();return`# ${n}${o?In(r):r}${e}`},order:1}};function In(t){return t.split(/[ _-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}import{getSoleRule as te}from"remark-mdat";var kt={header:{applicationOrder:2,content:[te(ee),te(H),te(J),te(X)],order:1}};import{toc as _n}from"mdast-util-toc";import{remark as Vn}from"remark";import Jn from"remark-gfm";import{z as R}from"zod";var ne={"table-of-contents":{applicationOrder:1,async content(t,e){let n=R.object({depth:R.union([R.literal(1),R.literal(2),R.literal(3),R.literal(4),R.literal(5),R.literal(6)]).optional()}).optional().parse(t),o=_n(e,{heading:null,maxDepth:(n==null?void 0:n.depth)??3,tight:!0}),r="## Table of contents";if(o.map===void 0)throw new Error("Could not generate table of contents");let i={children:o.map.children,type:"root"},s=Vn().use(Jn).stringify(i).replaceAll(`
|
|
25
25
|
|
|
26
26
|
`,`
|
|
27
27
|
`);return[r,s].join(`
|
|
28
|
-
`)},order:6}};import{tldrawToImage as
|
|
28
|
+
`)},order:6}};import{tldrawToImage as Tt}from"@kitschpatrol/tldraw-cli";import Bn from"node:crypto";import M from"node:fs/promises";import C from"node:path";import{isFile as _e}from"path-type";import{z as Ve}from"zod";var Mt={tldraw:{async content(t){let{alt:e="tldraw diagram",src:n}=Ve.object({alt:Ve.string().optional(),src:Ve.string()}).parse(t),{assetsPath:o}=await b();if(o===void 0)throw new Error("No assets path found");await M.mkdir(o,{recursive:!0});let r=await _e(n)?await $t(n):void 0;if(r!==void 0){let m=C.basename(n,C.extname(n)),p=C.join(o,`${m}-${r}-light.svg`),f=C.join(o,`${m}-${r}-dark.svg`);if(await _e(p)&&await _e(f))return xt(p,f,e)}let[i]=await Tt(n,{dark:!1,format:"svg",output:o,transparent:!0});r??=await $t(i);let s=`${At(i)}-${r}-light.svg`;await M.rename(i,s);let[a]=await Tt(n,{dark:!0,format:"svg",output:o,transparent:!0}),d=`${At(a)}-${r}-dark.svg`;if(await M.rename(a,d),r!==void 0){let m=C.basename(d),p=C.basename(s),f=p.replace(`${r}-light.svg`,""),g=await M.readdir(o);for(let L of g){let w=C.basename(L);w!==m&&w!==p&&w.startsWith(f)&&w.endsWith(".svg")&&await M.rm(C.join(o,w))}}return xt(s,d,e)}}};async function xt(t,e,n){let{packageFile:o}=await b();if(o===void 0)throw new Error("No package file found");let r=C.dirname(o),i=C.relative(r,t);return`<picture>
|
|
29
29
|
<source media="(prefers-color-scheme: dark)" srcset="${C.relative(r,e)}">
|
|
30
30
|
<source media="(prefers-color-scheme: light)" srcset="${i}">
|
|
31
31
|
<img alt="${n}" src="${i}">
|
|
32
|
-
</picture>`}async function
|
|
32
|
+
</picture>`}async function $t(t){let e=await M.readFile(t),n=Bn.createHash("sha1");return n.update(e),n.digest("hex").slice(0,8)}function At(t){return t.replace(/\.[^./]+$/,"")}import{getSoleRule as Hn}from"remark-mdat";var Ft={toc:Hn(ne)};var jt={...J,...H,...Rt,...bt,...Y,...W,...Nt,...kt,...Z,...X,...ne,...Mt,...Ft,...ee};async function T(t){let e={addMetaComment:!0,rules:jt},{additionalConfig:n=[],...o}=t??{},r=Array.isArray(n)?n:[n],i=await y({additionalConfig:[e,...r],...o});if(i.packageFile===void 0)throw new Error("Package file path is required in `mdat readme` config");return i}import{findUp as zn}from"find-up";import{packageDirectory as Kn}from"pkg-dir";import{log as Dt}from"remark-mdat";async function Gn(){Dt.info("Searching for package directory...");let t=await Kn()??process.cwd(),e=await zn("readme.md",{stopAt:t,type:"file"});if(e!==void 0)return Dt.info(`Found closest readme at "${e}"`),e}async function oe(){let t=await Gn();if(t===void 0)throw new Error("No readme found");return t}async function qn(t,e,n,o,r){return t??=await oe(),E(t,T,x,e,n,o,r)}async function Yn(t,e,n){return O(t,T,x,e,n)}async function Wn(t,e,n,o,r){return t??=await oe(),E(t,T,$,e,n,o,r)}async function Zn(t,e,n){return O(t,T,$,e,n)}async function Xn(t,e,n,o,r){return t??=await oe(),E(t,T,F,e,n,o,r)}export{nn as checkFiles,Wn as checkReadmeFiles,Zn as checkReadmeString,on as checkString,rn as collapseFiles,Xn as collapseReadmeFiles,sn as collapseString,en as expandFiles,qn as expandReadmeFiles,Yn as expandReadmeString,tn as expandString,y as loadConfig,T as loadConfigReadme,Yt as mergeConfigs};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mdat",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.11",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "CLI tool and library implementing the Markdown Autophagic Template (MDAT) system. MDAT lets you use comments as dynamic content templates in Markdown files, making it easy to generate and update readme boilerplate.",
|
|
6
6
|
"repository": {
|
|
@@ -49,6 +49,7 @@
|
|
|
49
49
|
"chalk": "^5.3.0",
|
|
50
50
|
"chevrotain": "^11.0.3",
|
|
51
51
|
"cosmiconfig": "^9.0.0",
|
|
52
|
+
"cosmiconfig-typescript-loader": "^5.0.0",
|
|
52
53
|
"execa": "^9.1.0",
|
|
53
54
|
"find-up": "^7.0.0",
|
|
54
55
|
"globby": "^14.0.1",
|
|
@@ -70,7 +71,7 @@
|
|
|
70
71
|
"which": "^4.0.0",
|
|
71
72
|
"yargs": "^17.7.2",
|
|
72
73
|
"zod": "^3.23.8",
|
|
73
|
-
"remark-mdat": "0.6.
|
|
74
|
+
"remark-mdat": "0.6.11"
|
|
74
75
|
},
|
|
75
76
|
"devDependencies": {
|
|
76
77
|
"@types/node": "^20.12.12",
|