remark-mdat 0.6.5 → 0.6.7

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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import h from"chalk";var J,L=((J=process==null?void 0:process.versions)==null?void 0:J.node)!==void 0,ae={verbose:!1,log(...e){if(!this.verbose)return;let r=h.gray("[Log]");L?console.warn(r,...e):console.log(r,...e)},logPrefixed(e,...r){this.info(h.blue(`[${e}]`),...r)},info(...e){if(!this.verbose)return;let r=h.green("[Info]");L?console.warn(r,...e):console.info(r,...e)},infoPrefixed(e,...r){this.info(h.blue(`[${e}]`),...r)},warn(...e){console.warn(h.yellow("[Warning]"),...e)},warnPrefixed(e,...r){this.warn(h.blue(`[${e}]`),...r)},error(...e){console.error(h.red("[Error]"),...e)},errorPrefixed(e,...r){this.error(h.blue(`[${e}]`),...r)}},y=ae;import w from"chalk";import D from"node:path";function p(e,r,n,t,o,i){var u,f;let a,s;o===void 0||typeof o=="number"?(a=o??0,s=i??0):(a=((u=o==null?void 0:o.position)==null?void 0:u.start.line)??0,s=((f=o==null?void 0:o.position)==null?void 0:f.start.column)??0);let l={place:{end:{column:s,line:a},start:{column:s,line:a}},source:n},d=e.message(t,l);d.fatal=r==="error"?!0:r==="warn"?!1:void 0}function le(e){return{column:e.column,level:e.fatal?"error":e.fatal===!1?"warn":"info",line:e.line,message:e.reason,source:e.source}}function me(e){return e.map(r=>U(r))}function U(e){var n;let r={destinationPath:e.history.length>0?e.history.at(-1):void 0,errors:[],infos:[],sourcePath:e.history.at(0)??e.path,warnings:[]};(n=r.sourcePath)!=null&&n.startsWith(".")&&(r.sourcePath=D.relative(process.cwd(),D.join(process.cwd(),r.sourcePath)));for(let t of e.messages){let o=le(t);o.level==="error"?r.errors.push(o):o.level==="warn"?r.warnings.push(o):r.infos.push(o)}return r}function de(e){for(let r of e){let n=U(r),{destinationPath:t,errors:o,infos:i,sourcePath:a,warnings:s}=n;y.info(`${w.bold("Mdat Report:")}`),y.info(` From: ${w.blue.bold(a)}`),y.info(` To: ${w.blue.bold(t)}`);for(let l of o)y.error(V(a,l));for(let l of s)y.warn(V(a,l));for(let l of i)y.info(V(a,l));o.length===0&&s.length===0?y.info(`No issues found in ${a}`):y.error(`${o.length} errors, ${s.length} warnings found in ${a}`)}}function V(e,r){let{column:n,level:t,line:o,message:i,source:a}=r,s=a?w.gray(`[${a}] `):"",l=o&&n?`:${o}:${n}`:"",d=pe(i,t);return`${s}${d} ${w.whiteBright(e+l)}`}function pe(e,r){return e.replaceAll(/<!--.+-->/g,n=>r==="info"?w.green(n):r==="warn"?w.yellow(n):w.red(n))}import ue from"json5";import{VFileMessage as b}from"vfile-message";function R(e,r,n){var t;try{let o=fe(e.value,n);return o===void 0?void 0:{...o,node:e,parent:r}}catch(o){throw o instanceof b?(o.line=(t=e.position)==null?void 0:t.start.line,o):o instanceof Error?new b(o.message,e):new b("Unknown error",e)}}function fe(e,r){if(!ce(e))return;let{closingPrefix:n,keywordPrefix:t,metaCommentIdentifier:o}=r,i=e.trim(),a=i.replace(/^\s*<!--+\s*/,"").replace(/\s*-*-->\s*$/,""),[s,...l]=a.split(/(\s+|\(|{)/),d=s.startsWith(o)?"meta":t!==""&&!s.startsWith(t)&&!s.startsWith(`${n}${t}`)?"native":s.startsWith(n)?"close":"open";if(d==="meta")return{content:ye(a,o),html:i,type:d};if(d==="native")return{content:a,html:i,type:d};let u=s.replace(new RegExp(`^${n}`),"").replace(new RegExp(`^${t}`),""),f=ge(l.join(""));if(d==="open"||d==="close"){let g={};try{g=ue.parse(f)}catch(c){if(c instanceof Error)throw new b(`Failed to parse comment options "${f}" for keyword "${u}": ${c.message}`)}return{closingPrefix:n,html:i,keyword:u,keywordPrefix:t,options:g,type:d}}}function ce(e){let r=e.trim();return r.startsWith("<!--")&&r.endsWith("-->")}function ge(e){return e=e.trim(),e=e.startsWith("(")?e.slice(1):e,e=e.endsWith(")")?e.slice(0,-1):e,e=e.trim(),!e.startsWith("{")&&!e.startsWith("[")&&(e="{"+e),!e.endsWith("}")&&!e.endsWith("]")&&(e+="}"),e}function ye(e,r){return e=e.trim(),e=e.startsWith(r)?e.slice(r.length):e,e=e.endsWith(r)?e.slice(0,-r.length):e,e}import{z as m}from"zod";function M(e){let r={};for(let[n,t]of Object.entries(e))if(typeof t=="string")r[n]={applicationOrder:0,content:async()=>t,order:void 0,required:!1};else if(typeof t=="function")r[n]={applicationOrder:0,content:async(o,i)=>t(o,i),order:void 0,required:!1};else if(Array.isArray(t))r[n]={applicationOrder:0,content:Object.values(M(Object.fromEntries(t.entries()))),order:void 0,required:!1};else if(typeof t.content=="string"){let o=t.content;r[n]={applicationOrder:t.applicationOrder??0,content:async()=>o,order:t.order??void 0,required:t.required??!1}}else if(Array.isArray(t.content))r[n]={applicationOrder:t.applicationOrder??0,content:Object.values(M(Object.fromEntries(t.content.entries()))),order:t.order??void 0,required:t.required??!1};else{let o=t.content;r[n]={applicationOrder:t.applicationOrder??0,content:async(i,a)=>o(i,a),order:t.order??void 0,required:t.required??!1}}return he(r),r}function P(e){try{v.parse(e)}catch(r){if(r instanceof Error)throw new TypeError(`Error validating rules: ${r.message}`)}}function he(e){try{we.parse(e)}catch(r){if(r instanceof Error)throw new TypeError(`Error validating rules: ${r.message}`)}}var B=m.any(),G=m.any(),Z=m.lazy(()=>m.object({applicationOrder:m.number(),content:m.union([m.function().args(B.optional(),G.optional()).returns(m.promise(m.string())),m.array(Z)]),order:m.number().optional(),required:m.boolean().default(!1)})),K=m.function().args(B.optional(),G.optional()).returns(m.union([m.string(),m.promise(m.string())])),S=m.lazy(()=>m.union([K,m.array(S),m.string(),m.object({applicationOrder:m.number().optional(),content:m.union([K,m.array(S),m.string()]),order:m.number().optional(),required:m.boolean().optional()})])),v=m.record(S).describe("Mdat Rules"),we=m.record(Z).describe("Mdat Rules");async function C(e,r,n,t=!1){if(Array.isArray(e.content)){let o=[];for(let[i,a]of e.content.entries()){let s=Array.isArray(r)?r.at(i):void 0;try{o.push(await C(a,s??{},n))}catch(l){if(t)throw l}}return o.join(`
1
+ import h from"chalk";var L,D=((L=process==null?void 0:process.versions)==null?void 0:L.node)!==void 0,ae={verbose:!1,log(...e){if(!this.verbose)return;let r=h.gray("[Log]");D?console.warn(r,...e):console.log(r,...e)},logPrefixed(e,...r){this.info(h.blue(`[${e}]`),...r)},info(...e){if(!this.verbose)return;let r=h.green("[Info]");D?console.warn(r,...e):console.info(r,...e)},infoPrefixed(e,...r){this.info(h.blue(`[${e}]`),...r)},warn(...e){console.warn(h.yellow("[Warning]"),...e)},warnPrefixed(e,...r){this.warn(h.blue(`[${e}]`),...r)},error(...e){console.error(h.red("[Error]"),...e)},errorPrefixed(e,...r){this.error(h.blue(`[${e}]`),...r)}},y=ae;import w from"chalk";import J from"node:path";function p(e,r,n,t,o,i){var u,f;let a,s;o===void 0||typeof o=="number"?(a=o??0,s=i??0):(a=((u=o==null?void 0:o.position)==null?void 0:u.start.line)??0,s=((f=o==null?void 0:o.position)==null?void 0:f.start.column)??0);let l={place:{end:{column:s,line:a},start:{column:s,line:a}},source:n},d=e.message(t,l);d.fatal=r==="error"?!0:r==="warn"?!1:void 0}function le(e){return{column:e.column,level:e.fatal?"error":e.fatal===!1?"warn":"info",line:e.line,message:e.reason,source:e.source}}function me(e){return e.map(r=>U(r))}function U(e){var n;let r={destinationPath:e.history.length>0?e.history.at(-1):void 0,errors:[],infos:[],sourcePath:e.history.at(0)??e.path,warnings:[]};(n=r.sourcePath)!=null&&n.startsWith(".")&&(r.sourcePath=J.relative(process.cwd(),J.join(process.cwd(),r.sourcePath)));for(let t of e.messages){let o=le(t);o.level==="error"?r.errors.push(o):o.level==="warn"?r.warnings.push(o):r.infos.push(o)}return r}function de(e){for(let r of e){let n=U(r),{destinationPath:t,errors:o,infos:i,sourcePath:a,warnings:s}=n;y.info(`${w.bold("MDAT Report:")}`),y.info(` From: ${w.blue.bold(a)}`),y.info(` To: ${w.blue.bold(t)}`);for(let l of o)y.error(V(a,l));for(let l of s)y.warn(V(a,l));for(let l of i)y.info(V(a,l));o.length===0&&s.length===0?y.info(`No issues found in ${a}`):y.error(`${o.length} errors, ${s.length} warnings found in ${a}`)}}function V(e,r){let{column:n,level:t,line:o,message:i,source:a}=r,s=a?w.gray(`[${a}] `):"",l=o&&n?`:${o}:${n}`:"",d=pe(i,t);return`${s}${d} ${w.whiteBright(e+l)}`}function pe(e,r){return e.replaceAll(/<!--.+-->/g,n=>r==="info"?w.green(n):r==="warn"?w.yellow(n):w.red(n))}import ue from"json5";import{VFileMessage as b}from"vfile-message";function R(e,r,n){var t;try{let o=fe(e.value,n);return o===void 0?void 0:{...o,node:e,parent:r}}catch(o){throw o instanceof b?(o.line=(t=e.position)==null?void 0:t.start.line,o):o instanceof Error?new b(o.message,e):new b("Unknown error",e)}}function fe(e,r){if(!ce(e))return;let{closingPrefix:n,keywordPrefix:t,metaCommentIdentifier:o}=r,i=e.trim(),a=i.replace(/^\s*<!--+\s*/,"").replace(/\s*-*-->\s*$/,""),[s,...l]=a.split(/(\s+|\(|{)/),d=s.startsWith(o)?"meta":t!==""&&!s.startsWith(t)&&!s.startsWith(`${n}${t}`)?"native":s.startsWith(n)?"close":"open";if(d==="meta")return{content:ye(a,o),html:i,type:d};if(d==="native")return{content:a,html:i,type:d};let u=s.replace(new RegExp(`^${n}`),"").replace(new RegExp(`^${t}`),""),f=ge(l.join(""));if(d==="open"||d==="close"){let g={};try{g=ue.parse(f)}catch(c){if(c instanceof Error)throw new b(`Failed to parse comment options "${f}" for keyword "${u}": ${c.message}`)}return{closingPrefix:n,html:i,keyword:u,keywordPrefix:t,options:g,type:d}}}function ce(e){let r=e.trim();return r.startsWith("<!--")&&r.endsWith("-->")}function ge(e){return e=e.trim(),e=e.startsWith("(")?e.slice(1):e,e=e.endsWith(")")?e.slice(0,-1):e,e=e.trim(),!e.startsWith("{")&&!e.startsWith("[")&&(e="{"+e),!e.endsWith("}")&&!e.endsWith("]")&&(e+="}"),e}function ye(e,r){return e=e.trim(),e=e.startsWith(r)?e.slice(r.length):e,e=e.endsWith(r)?e.slice(0,-r.length):e,e}import{z as m}from"zod";function M(e){let r={};for(let[n,t]of Object.entries(e))if(typeof t=="string")r[n]={applicationOrder:0,content:async()=>t,order:void 0,required:!1};else if(typeof t=="function")r[n]={applicationOrder:0,content:async(o,i)=>t(o,i),order:void 0,required:!1};else if(Array.isArray(t))r[n]={applicationOrder:0,content:Object.values(M(Object.fromEntries(t.entries()))),order:void 0,required:!1};else if(typeof t.content=="string"){let o=t.content;r[n]={applicationOrder:t.applicationOrder??0,content:async()=>o,order:t.order??void 0,required:t.required??!1}}else if(Array.isArray(t.content))r[n]={applicationOrder:t.applicationOrder??0,content:Object.values(M(Object.fromEntries(t.content.entries()))),order:t.order??void 0,required:t.required??!1};else{let o=t.content;r[n]={applicationOrder:t.applicationOrder??0,content:async(i,a)=>o(i,a),order:t.order??void 0,required:t.required??!1}}return he(r),r}function P(e){try{v.parse(e)}catch(r){if(r instanceof Error)throw new TypeError(`Error validating rules: ${r.message}`)}}function he(e){try{we.parse(e)}catch(r){if(r instanceof Error)throw new TypeError(`Error validating rules: ${r.message}`)}}var B=m.any(),G=m.any(),Z=m.lazy(()=>m.object({applicationOrder:m.number(),content:m.union([m.function().args(B.optional(),G.optional()).returns(m.promise(m.string())),m.array(Z)]),order:m.number().optional(),required:m.boolean().default(!1)})),K=m.function().args(B.optional(),G.optional()).returns(m.union([m.string(),m.promise(m.string())])),S=m.lazy(()=>m.union([K,m.array(S),m.string(),m.object({applicationOrder:m.number().optional(),content:m.union([K,m.array(S),m.string()]),order:m.number().optional(),required:m.boolean().optional()})])),v=m.record(S).describe("MDAT Rules"),we=m.record(Z).describe("MDAT Rules");async function C(e,r,n,t=!1){if(Array.isArray(e.content)){let o=[];for(let[i,a]of e.content.entries()){let s=Array.isArray(r)?r.at(i):void 0;try{o.push(await C(a,s??{},n))}catch(l){if(t)throw l}}return o.join(`
2
2
 
3
- `)}try{return await e.content(r,n)}catch(o){if(t)throw o}throw new Error("Failed to expand content")}function ke(e){return Me(e)}function Re(e){let r=Object.keys(e);if(r.length!==1)throw new Error(`Expected exactly one rule, found ${r.length}`);return r[0]}function Me(e){let r=Object.values(e);if(r.length===0)throw new Error('Found no entries in a "sole record" record. This should never happen');if(r.length>1)throw new Error('Found multiple entries in "sole record" record. This should never happen');return r[0]}import Q from"chalk";import Ce from"cli-table3";import{CONTINUE as xe,visit as Oe}from"unist-util-visit";async function F(e,r,n){let{closingPrefix:t,keywordPrefix:o,metaCommentIdentifier:i,paranoid:a=!1,rules:s}=n;P(s);let l=M(s),d=[];Oe(e,"html",(u,f,g)=>{if(g===void 0||f===void 0)return xe;let c=R(u,g,{closingPrefix:t,keywordPrefix:o,metaCommentIdentifier:i});if(c!==void 0){let $=c.type==="open"||c.type==="close"?l[c.keyword]:void 0;d.push({...c,rule:$})}}),Te(r,d,l),Ve(r,d),Se(r,d,n),await be(r,d,e),a&&$e(r,d,l),ve(r,d),Pe(r,d,l,n)}async function be(e,r,n){for(let t of r)if(t.type==="open"&&t.rule!==void 0)try{(await C(t.rule,t.options,n,!0)).trim()===""&&p(e,t.rule.required?"error":"warn","check",`${t.html} returned an empty string.`,t.node)}catch(o){o instanceof Error&&p(e,t.rule.required?"error":"warn","check",`Could not get content for ${t.html}. ${o.message}`,t.node)}}function Pe(e,r,n,t){if(t.keywordPrefix==="")return;let o=Object.keys(n);for(let i of r)i.type==="native"&&o.includes(i.content)&&p(e,"warn","check",`Missing prefix: ${i.html}`,i.node)}function ve(e,r){for(let n of r)n.type==="open"&&n.rule===void 0&&p(e,"warn","check",`Missing rule for: ${n.html}`,n.node)}function $e(e,r,n){for(let[t,o]of Object.entries(n))!o.required&&!r.some(i=>i.type==="open"&&i.keyword===t)&&!Y(o,r)&&p(e,"warn","check",`Missing optional: <!-- ${t} -->`)}function Te(e,r,n){for(let[t,o]of Object.entries(n))o.required&&!r.some(i=>i.type==="open"&&i.keyword===t)&&!Y(o,r)&&p(e,"error","check",`Missing required: <!-- ${t} -->`)}function Y(e,r){return r.reduce((n,t)=>{var o;if(Array.isArray((o=t.rule)==null?void 0:o.content))for(let i of t.rule.content)i.content.toString()===e.content.toString()&&(n=!0);return n},!1)}function Ve(e,r){let n=r.filter(s=>{var l;return s.type==="open"&&((l=s.rule)==null?void 0:l.order)!==void 0}),t=[...n].sort((s,l)=>{var f,g;let d=(f=s.rule)==null?void 0:f.order,u=(g=l.rule)==null?void 0:g.order;if(d===void 0||u===void 0)throw new Error("Unexpected undefined rule order");return d-u}),o=X(n),i=X(t),a=new Ce({head:[Q.bold.red("Current Order"),Q.bold.green("Required Order")],style:{compact:!0}});o.join(",")!==i.join(",")&&(a.push(...o.map((s,l)=>[s,i[l]])),p(e,"error","check",`Out of order:
4
- ${a.toString()}`))}function Se(e,r,n){let{addMetaComment:t}=n,o=r.filter(i=>i.type==="meta").length;t&&o!==1&&p(e,"error","check","Missing meta comment"),!t&&o!==0&&p(e,"error","check","Unexpected meta comment"),o>1&&p(e,"error","check","Multiple meta comments")}function X(e){return e.map((r,n)=>{if(r.type==="open"||r.type==="close")return`${n+1}. ${r.html}`;throw new Error("Unexpected comment type")})}import{CONTINUE as k,visit as Fe}from"unist-util-visit";function E(e,r,n){let t;Fe(e,"html",(o,i,a)=>{if(a===void 0||i===void 0)return k;let s=R(o,a,n);if(s===void 0||s.type==="native")return k;if(s.type==="meta")return a.children.splice(i,1),[k,i];if(s.type==="open")return t=s,k;if(s.type==="close"){if(t===void 0)return p(r,"error","clean","Found closing marker without opening marker",o),k;if(t.parent!==s.parent)return p(r,"error","clean","Opening marker doesn't share a parent",o),k;if(t.keyword!==s.keyword)return p(r,"error","clean","Opening marker doesn't share a keyword",o),k;let l=a.children.indexOf(t.node),u=a.children.indexOf(s.node)-l+1;return a.children.splice(l+1,u-1),t=void 0,[k,i-u+1]}})}import{remark as Ee}from"remark";import ze from"remark-gfm";import{CONTINUE as Ne,visit as We}from"unist-util-visit";async function z(e,r,n){let{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,rules:s}=n;P(s);let l=M(s),d=[];We(e,"html",(u,f,g)=>{if(g===void 0||f===void 0)return Ne;let c=R(u,g,{closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a});c!==void 0&&c.type==="open"&&l[c.keyword]!==void 0&&d.push(c)}),d.sort((u,f)=>l[u.keyword].applicationOrder-l[f.keyword].applicationOrder);for(let u of d){let{closingPrefix:f,html:g,keyword:c,keywordPrefix:$,node:O,options:te,parent:A}=u,oe=l[c],T="";try{T=await C(oe,te,e),T.trim()===""&&p(r,"error","expand",`Got empty content when expanding ${g}`,O)}catch(H){H instanceof Error&&p(r,"error","expand",`Caught error expanding ${g}, Error message: "${H.message}"`,O);continue}let ne=Ee().use(ze).parse(T).children,ie={type:"html",value:`<!-- ${f}${$}${c} -->`},se=A.children.indexOf(O);A.children.splice(se+1,0,...ne,ie),p(r,"info","expand",`Expanded: ${g}`,O)}if(t){let f={type:"html",value:`<!--${a} Warning: Content inside HTML comment blocks was generated by mdat and may be overwritten. ${a}-->`};e.children.unshift(f)}}import{fromHtml as Ie}from"hast-util-from-html";import{CONTINUE as N,SKIP as je,visit as re}from"unist-util-visit";function W(e,r){re(e,"html",(n,t,o)=>{if(o===void 0||t===void 0)return N;let i=qe(n);i.length>1&&(p(r,"warn","split","Multiple comments in a single HTML node.",n),o.children.splice(t,1,{children:i,type:"paragraph"}))})}function qe(e){let r=Ie(e.value,{fragment:!0}),n=[];return re(r,t=>{var o,i;return t.type==="root"?N:t.type==="text"?(n.push({position:_(t.position,(o=e.position)==null?void 0:o.start),type:"text",value:ee(e,t)}),N):(n.push({position:_(t.position,(i=e.position)==null?void 0:i.start),type:"html",value:ee(e,t)}),je)}),n}function _(e,r){if(!(e===void 0||r===void 0))return{end:{column:e.end.column-1+r.column,line:e.end.line-1+r.line,offset:e.end.offset!==void 0&&r.offset!==void 0?e.end.offset+r.offset:void 0},start:{column:e.start.column-1+r.column,line:e.start.line-1+r.line,offset:e.start.offset!==void 0&&r.offset!==void 0?e.start.offset+r.offset:void 0}}}function ee(e,r){if(r.position===void 0)throw new Error("Hast ElementContent node has no position!");return e.value.slice(r.position.start.offset,r.position.end.offset)}async function I(e,r,n){let{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,rules:s}=n;W(e,r),E(e,r,{closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a}),await z(e,r,{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,rules:s}),await F(e,r,{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,paranoid:!1,rules:s})}import{deepmerge as Ae}from"deepmerge-ts";function j(e){return Array.isArray(e)?e.map(r=>r&&typeof r=="object"?j(r):r).filter(r=>r!==void 0):Object.entries(e).map(([r,n])=>[r,n&&typeof n=="object"?j(n):n]).reduce((r,[n,t])=>t===void 0?r:{...r,[n]:t},{})}function q(...e){let r=e.map((n,t)=>t===0?n:j(n));return Ae(...r)}import{z as x}from"zod";var He={addMetaComment:!1,closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},Le=x.object({addMetaComment:x.boolean().optional(),closingPrefix:x.string().optional(),keywordPrefix:x.string().optional(),metaCommentIdentifier:x.string().optional(),rules:v.optional()}).describe("Mdat Options"),Je=function(e){let r=q(He,e);return async function(n,t){await I(n,t,r)}},De=Je;export{q as deepMergeDefined,De as default,me as getMdatReports,ke as getSoleRule,Re as getSoleRuleKey,y as log,I as mdat,F as mdatCheck,E as mdatClean,z as mdatExpand,W as mdatSplit,Le as optionsSchema,de as reporterMdat,v as rulesSchema};
3
+ `)}try{return await e.content(r,n)}catch(o){if(t)throw o}throw new Error("Failed to expand content")}function ke(e){return Me(e)}function Re(e){let r=Object.keys(e);if(r.length!==1)throw new Error(`Expected exactly one rule, found ${r.length}`);return r[0]}function Me(e){let r=Object.values(e);if(r.length===0)throw new Error('Found no entries in a "sole record" record. This should never happen');if(r.length>1)throw new Error('Found multiple entries in "sole record" record. This should never happen');return r[0]}import Q from"chalk";import Ce from"cli-table3";import{CONTINUE as xe,visit as Oe}from"unist-util-visit";async function F(e,r,n){let{closingPrefix:t,keywordPrefix:o,metaCommentIdentifier:i,paranoid:a=!1,rules:s}=n;P(s);let l=M(s),d=[];Oe(e,"html",(u,f,g)=>{if(g===void 0||f===void 0)return xe;let c=R(u,g,{closingPrefix:t,keywordPrefix:o,metaCommentIdentifier:i});if(c!==void 0){let T=c.type==="open"||c.type==="close"?l[c.keyword]:void 0;d.push({...c,rule:T})}}),$e(r,d,l),Ve(r,d),Se(r,d,n),await be(r,d,e),a&&Te(r,d,l),ve(r,d),Pe(r,d,l,n)}async function be(e,r,n){for(let t of r)if(t.type==="open"&&t.rule!==void 0)try{(await C(t.rule,t.options,n,!0)).trim()===""&&p(e,t.rule.required?"error":"warn","check",`${t.html} returned an empty string.`,t.node)}catch(o){o instanceof Error&&p(e,t.rule.required?"error":"warn","check",`Could not get content for ${t.html}. ${o.message}`,t.node)}}function Pe(e,r,n,t){if(t.keywordPrefix==="")return;let o=Object.keys(n);for(let i of r)i.type==="native"&&o.includes(i.content)&&p(e,"warn","check",`Missing prefix: ${i.html}`,i.node)}function ve(e,r){for(let n of r)n.type==="open"&&n.rule===void 0&&p(e,"warn","check",`Missing rule for: ${n.html}`,n.node)}function Te(e,r,n){for(let[t,o]of Object.entries(n))!o.required&&!r.some(i=>i.type==="open"&&i.keyword===t)&&!Y(o,r)&&p(e,"warn","check",`Missing optional: <!-- ${t} -->`)}function $e(e,r,n){for(let[t,o]of Object.entries(n))o.required&&!r.some(i=>i.type==="open"&&i.keyword===t)&&!Y(o,r)&&p(e,"error","check",`Missing required: <!-- ${t} -->`)}function Y(e,r){return r.reduce((n,t)=>{var o;if(Array.isArray((o=t.rule)==null?void 0:o.content))for(let i of t.rule.content)i.content.toString()===e.content.toString()&&(n=!0);return n},!1)}function Ve(e,r){let n=r.filter(s=>{var l;return s.type==="open"&&((l=s.rule)==null?void 0:l.order)!==void 0}),t=[...n].sort((s,l)=>{var f,g;let d=(f=s.rule)==null?void 0:f.order,u=(g=l.rule)==null?void 0:g.order;if(d===void 0||u===void 0)throw new Error("Unexpected undefined rule order");return d-u}),o=X(n),i=X(t),a=new Ce({head:[Q.bold.red("Current Order"),Q.bold.green("Required Order")],style:{compact:!0}});o.join(",")!==i.join(",")&&(a.push(...o.map((s,l)=>[s,i[l]])),p(e,"error","check",`Out of order:
4
+ ${a.toString()}`))}function Se(e,r,n){let{addMetaComment:t}=n,o=r.filter(i=>i.type==="meta").length;t&&o!==1&&p(e,"error","check","Missing meta comment"),!t&&o!==0&&p(e,"error","check","Unexpected meta comment"),o>1&&p(e,"error","check","Multiple meta comments")}function X(e){return e.map((r,n)=>{if(r.type==="open"||r.type==="close")return`${n+1}. ${r.html}`;throw new Error("Unexpected comment type")})}import{CONTINUE as k,visit as Fe}from"unist-util-visit";function E(e,r,n){let t;Fe(e,"html",(o,i,a)=>{if(a===void 0||i===void 0)return k;let s=R(o,a,n);if(s===void 0||s.type==="native")return k;if(s.type==="meta")return a.children.splice(i,1),[k,i];if(s.type==="open")return t=s,k;if(s.type==="close"){if(t===void 0)return p(r,"error","clean","Found closing marker without opening marker",o),k;if(t.parent!==s.parent)return p(r,"error","clean","Opening marker doesn't share a parent",o),k;if(t.keyword!==s.keyword)return p(r,"error","clean","Opening marker doesn't share a keyword",o),k;let l=a.children.indexOf(t.node),u=a.children.indexOf(s.node)-l+1;return a.children.splice(l+1,u-1),t=void 0,[k,i-u+1]}})}import{remark as Ee}from"remark";import ze from"remark-gfm";import{CONTINUE as Ne,visit as We}from"unist-util-visit";async function z(e,r,n){let{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,rules:s}=n;P(s);let l=M(s),d=[];We(e,"html",(u,f,g)=>{if(g===void 0||f===void 0)return Ne;let c=R(u,g,{closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a});c!==void 0&&c.type==="open"&&l[c.keyword]!==void 0&&d.push(c)}),d.sort((u,f)=>l[u.keyword].applicationOrder-l[f.keyword].applicationOrder);for(let u of d){let{closingPrefix:f,html:g,keyword:c,keywordPrefix:T,node:O,options:te,parent:q}=u,oe=l[c],$="";try{$=await C(oe,te,e),$.trim()===""&&p(r,"error","expand",`Got empty content when expanding ${g}`,O)}catch(H){H instanceof Error&&p(r,"error","expand",`Caught error expanding ${g}, Error message: "${H.message}"`,O);continue}let ne=Ee().use(ze).parse($).children,ie={type:"html",value:`<!-- ${f}${T}${c} -->`},se=q.children.indexOf(O);q.children.splice(se+1,0,...ne,ie),p(r,"info","expand",`Expanded: ${g}`,O)}if(t){let f={type:"html",value:`<!--${a} Warning: Content inside HTML comment blocks was generated by mdat and may be overwritten. ${a}-->`};e.children.unshift(f)}}import{fromHtml as Ae}from"hast-util-from-html";import{CONTINUE as N,SKIP as Ie,visit as re}from"unist-util-visit";function W(e,r){re(e,"html",(n,t,o)=>{if(o===void 0||t===void 0)return N;let i=je(n);i.length>1&&(p(r,"warn","split","Multiple comments in a single HTML node.",n),o.children.splice(t,1,{children:i,type:"paragraph"}))})}function je(e){let r=Ae(e.value,{fragment:!0}),n=[];return re(r,t=>{var o,i;return t.type==="root"?N:t.type==="text"?(n.push({position:_(t.position,(o=e.position)==null?void 0:o.start),type:"text",value:ee(e,t)}),N):(n.push({position:_(t.position,(i=e.position)==null?void 0:i.start),type:"html",value:ee(e,t)}),Ie)}),n}function _(e,r){if(!(e===void 0||r===void 0))return{end:{column:e.end.column-1+r.column,line:e.end.line-1+r.line,offset:e.end.offset!==void 0&&r.offset!==void 0?e.end.offset+r.offset:void 0},start:{column:e.start.column-1+r.column,line:e.start.line-1+r.line,offset:e.start.offset!==void 0&&r.offset!==void 0?e.start.offset+r.offset:void 0}}}function ee(e,r){if(r.position===void 0)throw new Error("Hast ElementContent node has no position!");return e.value.slice(r.position.start.offset,r.position.end.offset)}async function A(e,r,n){let{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,rules:s}=n;W(e,r),E(e,r,{closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a}),await z(e,r,{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,rules:s}),await F(e,r,{addMetaComment:t,closingPrefix:o,keywordPrefix:i,metaCommentIdentifier:a,paranoid:!1,rules:s})}import{deepmerge as qe}from"deepmerge-ts";function I(e){return Array.isArray(e)?e.map(r=>r&&typeof r=="object"?I(r):r).filter(r=>r!==void 0):Object.entries(e).map(([r,n])=>[r,n&&typeof n=="object"?I(n):n]).reduce((r,[n,t])=>t===void 0?r:{...r,[n]:t},{})}function j(...e){let r=e.map((n,t)=>t===0?n:I(n));return qe(...r)}import{z as x}from"zod";var He={addMetaComment:!1,closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},De=x.object({addMetaComment:x.boolean().optional(),closingPrefix:x.string().optional(),keywordPrefix:x.string().optional(),metaCommentIdentifier:x.string().optional(),rules:v.optional()}).describe("MDAT Options"),Le=function(e){let r=j(He,e);return async function(n,t){await A(n,t,r)}},Je=Le;export{j as deepMergeDefined,Je as default,me as getMdatReports,ke as getSoleRule,Re as getSoleRuleKey,y as log,A as mdat,F as mdatCheck,E as mdatClean,z as mdatExpand,W as mdatSplit,De as optionsSchema,de as reporterMdat,v as rulesSchema};
@@ -16,7 +16,7 @@ export type NormalizedRule = {
16
16
  */
17
17
  applicationOrder: number;
18
18
  /**
19
- * The function that generates the expansion markdown string.
19
+ * The function that generates the expanded Markdown string.
20
20
  * For 'compound' rules, this can be an array of rules (without keywords).
21
21
  */
22
22
  content: ((options: JsonValue, tree: Root) => Promise<string>) | NormalizedRule[];
@@ -36,7 +36,7 @@ export type NormalizedRule = {
36
36
  };
37
37
  export type Rule =
38
38
  /**
39
- * Function that returns the markdown string to expand at the comment site.
39
+ * Function that returns the Markdown string to expand at the comment site.
40
40
  */
41
41
  ((options: JsonValue, tree: Root) => Promise<string> | string)
42
42
  /**
@@ -46,7 +46,7 @@ export type Rule =
46
46
  */
47
47
  | Rule[]
48
48
  /**
49
- * The markdown string to expand at the comment site.
49
+ * The Markdown string to expand at the comment site.
50
50
  */
51
51
  | SetOptional<Merge<NormalizedRule, {
52
52
  /**
@@ -64,7 +64,7 @@ export type Rule =
64
64
  * @param tree
65
65
  * Markdown (mdast) abstract syntax tree containing the entire parsed document. Useful for expanders that need the entire document context, such as when generating a table of contents. Do not mutate the AST, instead return a new string.
66
66
  *
67
- * @returns A string with the generated content. The string will be parsed as markdown and inserted into the document at the comment's location.
67
+ * @returns A string with the generated content. The string will be parsed as Markdown and inserted into the document at the comment's location.
68
68
  */
69
69
  content: ((options: JsonValue, tree: Root) => Promise<string> | string) | Rule[] | string;
70
70
  }>, 'applicationOrder' | 'order' | 'required'> | string;
@@ -101,5 +101,17 @@ export declare function validateRules(rules: Rules): void;
101
101
  export declare const rulesSchema: z.ZodRecord<z.ZodString, z.ZodType<any, z.ZodTypeDef, any>>;
102
102
  export declare const normalizedRulesSchema: z.ZodRecord<z.ZodString, z.ZodType<any, z.ZodTypeDef, any>>;
103
103
  export declare function getRuleContent(rule: NormalizedRule, options: JsonValue, tree: Root, check?: boolean): Promise<string>;
104
+ /**
105
+ * Returns the rule value from a single-rule record.
106
+ * Useful when aliasing rules or invoking them programmatically.
107
+ *
108
+ * Throws if there are no entries or more than one entry.
109
+ */
104
110
  export declare function getSoleRule<T extends NormalizedRules | Rules>(rules: T): T[keyof T];
111
+ /**
112
+ * Returns the rule key from a single-rule record.
113
+ * Useful for comment placeholder validation.
114
+ *
115
+ * Throws if there are no entries or more than one entry.
116
+ */
105
117
  export declare function getSoleRuleKey<T extends NormalizedRules | Rules>(rules: T): keyof T;
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "remark-mdat",
3
- "version": "0.6.5",
3
+ "version": "0.6.7",
4
4
  "type": "module",
5
- "description": "A remark plugin implementing the Markdown Autophagic Template (mdat) system.",
5
+ "description": "A remark plugin implementing the Markdown Autophagic Template (MDAT) system.",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git@github.com:kitschpatrol/mdat.git",
@@ -58,7 +58,7 @@
58
58
  "zod": "^3.22.4"
59
59
  },
60
60
  "devDependencies": {
61
- "@types/node": "^20.11.20",
61
+ "@types/node": "^20.11.24",
62
62
  "tsup": "^8.0.2",
63
63
  "typescript": "^5.3.3",
64
64
  "vitest": "^1.3.1"
package/readme.md CHANGED
@@ -7,12 +7,12 @@
7
7
  [![NPM Package remark-mdat](https://img.shields.io/npm/v/remark-mdat.svg)](https://npmjs.com/package/remark-mdat)
8
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
9
 
10
- **A remark plugin implementing the Markdown Autophagic Template (mdat) system.**
10
+ **A remark plugin implementing the Markdown Autophagic Template (MDAT) system.**
11
11
 
12
12
  <!-- /header -->
13
13
 
14
14
  > \[!NOTE]\
15
- > **Please see [mdat](http://github.com/kitschpatrol/mdat) for a higher-level CLI tool and library with a collection of built-in expansion rules.**
15
+ > **Please see The [`mdat` package](http://github.com/kitschpatrol/mdat) for a higher-level CLI tool and library with a collection of built-in expansion rules.**
16
16
 
17
17
  <!-- table-of-contents -->
18
18
 
@@ -54,7 +54,7 @@ And replace it with dynamic data. In this case, from `package.json`:
54
54
  <!-- /title -->
55
55
  ```
56
56
 
57
- This plugin powers the higher-level [`mdat`](../mdat) package in this monorepo. [`mdat`](../mdat) is a better better place to start if you just want to expand some comments and aren't working directly with remark processing pipelines.
57
+ This plugin powers the higher-level [`mdat` package](../mdat) in this monorepo. [`mdat`](../mdat) is a better better place to start if you just want to expand some comments and aren't working directly with remark processing pipelines.
58
58
 
59
59
  ## Getting started
60
60