@homedev/objector 0.1.28 → 0.1.30
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 +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
in ${r.file??""}(${
|
|
3
|
-
`))},list:(r)=>
|
|
1
|
+
import X from"fs/promises";import Q from"path";import p from"yaml";var s=async(w)=>{try{return await X.access(w,X.constants.R_OK),!0}catch{return!1}},B=async(w,r)=>{let F=await(async()=>{let T=[""];if(!Q.isAbsolute(w)&&r?.dirs)T.push(...r.dirs);for(let C of T){let M=Q.join(C,w);if(await s(M))return Q.resolve(M)}throw new Error(`File not found: "${w}"`)})(),n=await X.readFile(F),g=Q.dirname(F),O={"[.](yml|yaml)$":p.parse,"[.]json$":JSON.parse,...r?.parsers},E=Object.entries(O).find((T)=>F.match(T[0]));if(!E)throw new Error(`Unhandled file type: ${w}`);return{content:E[1](n.toString()),fullPath:F,folderPath:g}};var Y=async(w,r)=>{for(let f of w){let F=[];if(r?.root)F.push(r.root);if(r?.loadOptions?.dirs)F.push(...r.loadOptions.dirs);let n=r?.load?await r.load(f):(await B(f,{...r?.loadOptions,dirs:F})).content;if(r?.loaded&&n)await r.loaded(n)}};var Z=(w,r,f)=>{for(let F of Object.keys(r)){if(w[F]===void 0)continue;let n=r[F],g=w[F];if(typeof g!==typeof n||Array.isArray(g)!==Array.isArray(n)){let E=f?.mismatch?.(F,g,n,w,r);if(E!==void 0){r[F]=E;continue}throw new Error(`Type mismatch: ${F}`)}let O=f?.mode?.(F,g,n,w,r)??"merge";switch(O){case"source":r[F]=g;continue;case"target":continue;case"skip":delete r[F],delete w[F];continue;case"merge":break;default:throw new Error(`Unknown merge mode: ${O}`)}if(typeof g==="object")if(Array.isArray(g))n.push(...g);else{if(f?.navigate?.(F,g,n,w,r)===!1)continue;Z(g,n,f)}else{if(g===n)continue;let E=f?.conflict?.(F,g,n,w,r);r[F]=E===void 0?n:E}}for(let F of Object.keys(w))if(r[F]===void 0)r[F]=w[F]};var P;((O)=>{O[O.Explore=0]="Explore";O[O.SkipSiblings=1]="SkipSiblings";O[O.NoExplore=2]="NoExplore";O[O.ReplaceItem=3]="ReplaceItem";O[O.ReplaceParent=4]="ReplaceParent";O[O.DeleteParent=5]="DeleteParent"})(P||={});class j{action;by;constructor(w,r){this.action=w;this.by=r}static ReplaceParent(w){return new j(4,w)}static ReplaceItem(w){return new j(3,w)}static SkipSiblings(){return new j(1)}static Explore(){return new j(0)}static NoExplore(){return new j(2)}static DeleteParent(){return new j(5)}}var D=async(w,r)=>{let f=async(n)=>{let g=n.key===null,O=g?{action:0}:await r(n);if(n.value&&typeof n.value==="object"&&O.action==0){if(!g)n.path.push(n.key),n.parents.push(n.parent);if(await F(n),!g)n.parents.pop(),n.path.pop()}return O},F=async(n)=>{for(let[g,O]of Object.entries(n.value)){let E=await f({key:g,value:O,path:n.path,parent:n.value,parents:n.parents});switch(E.action){case 4:if(!n.key)throw new Error("Cannot replace root");n.parent[n.key]=E.by;return;case 3:n.value[g]=E.by;break;case 5:delete n.parent[n.key];return;case 1:return}}};await f({key:null,value:w,path:[],parent:null,parents:[]})};var K=(w,r,f="(",F=")")=>{let n=0,g="",O=[];for(let E of w){if(g+=E,E===f)n++;if(E===F)n--;if(n===0&&E===r)O.push(g.slice(0,-1)),g=""}if(g)O.push(g);return O},z=(w)=>{let r=/(?:\s*(?:"([^"]*)"|'([^']*)')\s*|([^"',]+))(?:,)?|(,)/g,f=[],F;while((F=r.exec(w))!==null){let n=F[1]??F[2];f.push({value:n??F[3]?.trim()??"",quoted:n!==void 0})}return f};var y=(w,r,f,F)=>{if(w.startsWith("{")){let n=w.substring(1,w.length-1);return J(r,n,f).toString()}return F?w:void 0},i=(w,r,f,F)=>{let n=y(r,f,F);if(n)return J(w,n,F);let g=/^\[([^=\]]*)([=]*)([^\]]*)\]$/.exec(r);if(g){let[E,b,T,C]=g,M=y(b.trim(),f,F,!0),_=y(C.trim(),f,F,!0);if(Array.isArray(w))switch(T){case"==":case"=":return w.find((S)=>S[M]==_)}}let O=/^([^[\]]*)\[([^\]]*)]/.exec(r);if(O)return w[O[1]][O[2]];return w[r]},J=(w,r,f)=>{let F=void 0,n=void 0;r??="";let g=(C)=>C?.endsWith("?")?[C.substring(0,C.length-1),!0]:[C,!1],O=(C,M)=>{let[_,S]=g(M.pop());if(_){let W=i(C,_,w,f);if(W===void 0){if(S||f?.defaultValue!==void 0)return;throw new Error(`Unknown path element: "${_}" in "${r}"`)}return F=C,n=_,O(W,M)}if(f?.set&&n)F[n]=f?.set;return C},E=K(r,f?.separator??".","{","}"),b=E.length>0&&E[E.length-1].startsWith("?=")?E.pop()?.substring(2):void 0;E.reverse();let T=O(w,E);if(T===void 0)return b??f?.defaultValue;return T};var $=(w,r)=>{let f=/^(?<path>[^@>]*)?(?:@(?<from>[^>]*))?$/.exec(w)?.groups;if(!f)throw new Error(`Invalid reference: "${w}"`);let{from:F,path:n}=f;if(!F)return J(r.root,n,{defaultValue:r?.defaultValue});if(r.async===!1){if(!r.load)throw new Error("No load function defined");return J(r.load(F),n,{defaultValue:r?.defaultValue})}else return(r.load??B)(F).then((g)=>J(g,n))};var d=async(w,r,f,F)=>{let n,g=[],O=r;if(!F.sources)return j.Explore();if(O=O.replaceAll(F.sourcesMatcher??/\$\((?<key>[^:()]+)(?::(?<arg>(?:(?:"[^"]*"|[^",()]*),?)*))?\)/g,(E,...b)=>{if(n)return E;let T=(A)=>{if(A instanceof Promise)return`ð[${g.push(A)}]ñ`;if(typeof A==="object")return n=A,E;return A??""},C=b[b.length-1],M=F.sources[C.key];if(C.arg===void 0)return T($(C.key,{root:f,load:F?.load}));if(M===void 0)throw new Error(`Unhandled source type: ${C.key}`);let[_,S]="fn"in M?[M.fn,M]:[M,{}],W=z(C.arg),a=S.processArgs===!1?[]:W.map((A)=>{if(A.quoted)return A.value;return A.value.startsWith("@")?A.value.substring(1):$(A.value,{root:f})});return T(_({groups:C,args:a,rawArgs:W,path:w,value:O,root:f,key:C.key,options:F,file:F.file}))}),n)O=await n;else if(g.length){let E=await Promise.all(g);O=E.find((b)=>typeof b==="object")??O.replaceAll(/\xf0\[(\d+)]\xf1/g,(b,T)=>E[+T-1])}if(O===null)return j.DeleteParent();if(O===r)return j.Explore();if(O instanceof j)return O;if(typeof O==="string"){let E=await d(w,O,f,F);if(E.action!==0)return E}return j.ReplaceItem(O)};var m=async(w,r,f,F)=>{if(w.key.startsWith("$"))return j.NoExplore();if(!F.keys)return;let n=(F?.keysMatcher??/^\.(?<key>.*)/).exec(w.key)?.groups;if(n){let g=F.keys[n.key];if(g!==void 0){let O=typeof g==="object"?g:{},E=typeof g==="function"?g:g.fn,b={...f,self:w.value,this:w.parent,parent:w.parents[w.parents.length-1],parents:[w.parent,...w.parents.toReversed()]};if(typeof w.value==="string"){let M=await d(r,w.value,b,F);if(M.by)w.value=M.by}else await U(w.value,{...F,root:b,filters:[...F.filters??[],...O.filters??[]]});let T={args:[w.value],rawArgs:[],groups:n,path:r,value:w.value,root:f,parent:w.parent,key:w.key,file:F?.file,options:F},C=await E(T);if(C instanceof j)return C;if(C===null)return j.DeleteParent();if(C===void 0)return j.Explore();return j.ReplaceParent(C)}}};var U=async(w,r)=>D(w,async(f)=>{let F=[...f.path,f.key].join(".");if(r.filters?.length&&r.filters.some((g)=>g.test(F)))return j.NoExplore();let n={...w,this:f.parent,parent:f.parents.length>0?f.parents[f.parents.length-1]:{},parents:f.parents.toReversed(),...r.root};try{return await m(f,F,n,r)??(typeof f.value==="string"?await d(F,f.value,n,r):j.Explore())}catch(g){throw new Error(`${g.message}
|
|
2
|
+
in ${r.file??""}(${F}) `)}});var yr=async(w,r)=>{let f=[];return await D(w,(F)=>{if(r([...F.path,F.key].join("."),F.value))f.push(F.value);return j.Explore()}),f};var I=(w,r="name")=>Object.entries(w).map(([f,F])=>({[r]:f,...F})),Yr=(w,r="name")=>Object.fromEntries(w.map((f)=>[f[r],f])),V=(w,r="name")=>Object.fromEntries(w.map((f)=>{let{[r]:F,...n}=f;return[F,n]}));import G from"fs/promises";import u from"path";import x from"yaml";import L from"path";var R=(w)=>{return{load:async(r)=>{for(let{file:f,alias:F}of Array.isArray(r.value)?r.value:[r.value]){if(!f)throw new Error("File reference required");await w.load(f,F??f,r.file&&L.dirname(r.file))}delete r.parent[r.key]},include:(r)=>w.load(r.value,void 0,r.file&&L.dirname(r.file)),from:async(r)=>{let f=await $(r.value,{root:r.root,load:(F)=>w.load(F,void 0,r.file&&L.dirname(r.file))});if(r.parent.content){if(Array.isArray(r.parent.content)&&Array.isArray(f))return[...f,...r.parent.content];return w.merge(f,r.parent.content),r.parent.content}return f},concat:async(r)=>{let f=[];for(let F of Array.isArray(r.value)?r.value:[r.value])f.push(...await $(F,{root:r.root,load:(n)=>w.load(n,void 0,r.file&&L.dirname(r.file))}));return f.filter((F)=>F!==void 0)},extends:async(r)=>{let f=async(F,n)=>{for(let g of Array.isArray(n)?n:[n]){let O=await $(g,{root:r.root,load:(b)=>w.load(b,void 0,r.file&&L.dirname(r.file))}),E=JSON.parse(JSON.stringify(O));if(E[r.key])await f(E,E[r.key]);await U(E,{...r.options}),w.merge(E,F),delete F[r.key]}};await f(r.parent,r.value)},alias:(r)=>{w.alias(r.value,r.parent),delete r.parent[r.key]},if:(r)=>{if(delete r.parent[r.key],r.value===null||r.value===void 0||["0",0,"false",""].includes(r.value)||Array.isArray(r.value)&&r.value.length===0)return null},skip:(r)=>{return delete r.parent[r.key],j.SkipSiblings()},output:(r)=>{delete r.parent[r.key];for(let f of Array.isArray(r.value)?r.value:[r.value])if(typeof f==="string")w.output({name:f,value:r.parent});else w.output({...f,value:f.value??r.parent})},each:{filters:[/select|model/],fn:async(r)=>{delete r.parent[r.key];let f=(T)=>$(T,{root:r.root,load:(C)=>w.load(C,void 0,r.file&&L.dirname(r.file))}),F=()=>{if(typeof r.value==="string"||!r.value.model)return r.parent;if(typeof r.value.model==="string")return f(r.value.model);return r.value.model},n=()=>{if(typeof r.value==="string")return f(r.value);if(Array.isArray(r.value))return r.value;if(typeof r.value.from==="string")return f(r.value.from);return r.value.from},g=async(T)=>{let C=r.value.select;if(C===void 0)return T;if(typeof C!=="string"){let M=JSON.parse(JSON.stringify(C));return await U(M,{...r.options,root:{...r.root,result:T}}),M}return await $(C,{root:{...r.root,result:T}})},O=await n(),E=await F();if(!Array.isArray(O))throw new Error('Key "each" requires a source list');if(E===void 0)throw new Error('Key "each" must define a model');if(r.value.extend?.model)E=w.mergeAll([E,...Array.isArray(r.value.extend.model)?r.value.extend.model:[r.value.extend.model]]);let b=[];for(let T=0;T<O.length;T++){let C=JSON.parse(JSON.stringify(E));if(await U(C,{...r.options,root:{...r.root,item:O[T],this:C,index:T}}),r.value.extend?.result)C=w.mergeAll([C,...Array.isArray(r.value.extend?.result)?r.value.extend.result:[Array.isArray(r.value.extend?.result)]]);b.push(await g(C))}return b}}}};import h from"fs/promises";import H from"path";var e=(w,r)=>{if(r??=["null","empty","zero"],w==="false"||w===!1)return!1;if(r?.includes("null")&&(w===null||w===void 0))return!1;if(r?.includes("empty")&&w==="")return!1;if(r?.includes("zero")&&w==0)return!1;return!0},l=(w)=>w.replace(/((?:[_ ]+)\w|^\w)/g,(r,f)=>f.toUpperCase()).replace(/_/g,""),o=(w)=>l(w).replace(/((?:[ ]+\w)|^\w)/g,(r,f)=>f.toLowerCase()),k=(w,r)=>w.replace(/([a-z])([A-Z])/g,`$1${r}$2`).replace(/\s+/g,r),N=(w,r)=>{switch(r){case"upper":return w.toUpperCase();case"lower":return w.toLowerCase();default:return w}},q=async(w,r,f,F)=>r.rawArgs[f].quoted?r.rawArgs[f].value:await $(r.rawArgs[f].value,{root:r.root,load:(n)=>w.load(n),defaultValue:F}),v=(w)=>{return{include:async(r)=>await w.load(r.args[0],r.args[1],r.file&&H.dirname(r.file),{parent:r.root}),file:async(r)=>await h.readFile(r.args[0]).then((f)=>f.toString()),scan:async(r)=>{let f=[],n=(()=>{let g=r.args[2]??["**/node_modules/**"],O=typeof g==="string"?g.split(",").map((E)=>E.trim()):g;if(!Array.isArray(O))throw new Error("Scan exclusion must be a list");return O})();for await(let g of h.glob(r.args[0],{cwd:r.args[1]??H.dirname(r.file??"."),exclude:(O)=>n.some((E)=>H.matchesGlob(O,E))}))f.push(g);return f},env:(r)=>process.env[r.args[0]],len:(r)=>r.args[0].length,reverse:(r)=>r.args[0].split("").reverse().join(""),substring:(r)=>r.args[0].substring(+r.args[1],+r.args[2]),concat:(r)=>r.args.join(""),lower:(r)=>r.args[0].toLowerCase(),upper:(r)=>r.args[0].toUpperCase(),pascal:(r)=>l(r.args[0]),camel:(r)=>o(r.args[0]),snake:(r)=>N(k(r.args[0],"_"),r.args[1]),kebab:(r)=>N(k(r.args[0],"-"),r.args[1]),encode:(r)=>Buffer.from(r.args[0]).toString(r.args[1]??"base64"),decode:(r)=>Buffer.from(r.args[0],r.args[1]??"base64").toString(),uuid:(r)=>crypto.randomUUID(),merge:(r)=>r.args.flatMap((f)=>f),join:(r)=>{let[f,F,n]=r.args,g=f;if(!Array.isArray(g))throw new Error("Object is not a list");if(F?.length)g=g.map((O)=>$(F,{root:{...r.root,...O},load:(E)=>w.load(E)}));return g.join(n?.replace("\\n",`
|
|
3
|
+
`))},list:(r)=>I(r.args[0],r.args[1]),object:(r)=>V(r.args[0],r.args[1]),each:{processArgs:!1,fn:async(r)=>{let f=(b)=>$(b,{root:r.root,load:(T)=>w.load(T,void 0,r.file&&H.dirname(r.file))}),F=await f(r.rawArgs[0].value),n=await f(r.rawArgs[1].value),g=r.rawArgs[2]?.value,O=Array.isArray(F)?F:I(F),E=[];for(let b=0;b<O.length;b++){let T=JSON.parse(JSON.stringify(n)),C={instance:T};if(await U(C,{...r.options,root:{...r.root,item:O[b],this:T,parent:r.root.this,index:b,params:r.rawArgs.slice(3).map((M)=>M.value)}}),g!==void 0&&g!=="@")E.push(C.instance[g]);else E.push(C.instance)}return E}},log:(r)=>{console.log(...r.args)},default:{processArgs:!1,fn:async(r)=>{let f=r.rawArgs[1]?.value?await q(w,r,1):"";return q(w,r,0,f)}},if:{processArgs:!1,fn:async(r)=>{let f=await q(w,r,0,!1);if(!e(f,r.rawArgs.length>3?r.rawArgs[3].value.split(","):void 0))return r.rawArgs.length>2?q(w,r,2):"";return q(w,r,1)}},switch:{processArgs:!1,fn:async(r)=>{let f=await q(w,r,0,!1),F=await q(w,r,1);if(F[f]===void 0){if(r.rawArgs.length>2)return q(w,r,2);throw new Error(`Unhandled switch case: ${f}`)}return F[f]}}}};class c{options={load:{dirs:[]},merge:{},include:{},fields:{},includeKey:"includes",mergeKey:".merge",includes:[],outputs:[]};cache={};includeDirectory(...w){return this.options.load.dirs??=[],this.options.load.dirs.push(...w),this}include(...w){return this.options.includes??=[],this.options.includes.push(...w),this}keys(w){return this.options.fields.keys={...this.options.fields.keys,...w},this}sources(w){return this.options.fields.sources={...this.options.fields.sources,...w},this}variables(w){return this.options.variables={...this.options.variables,...w},this}output(w){return this.options.outputs??=[],this.options.outputs.push(w),this}defaultProcessors(){return this.sources(v(this)).keys(R(this))}alias(w,r){return this.cache[w]=r,this}getAlias(w){return this.cache[w]}getOutputs(){return this.options.outputs??[]}use(w){return w(this),this}filter(w){return this.options.fields.filters??=[],this.options.fields.filters?.push(w),this}async load(w,r,f,F,n){if(r&&this.cache[r])return this.cache[r];if(this.cache[w])return this.cache[w];let g=f?[f]:[];this.options.load.dirs&&g.push(...this.options.load.dirs);let O=await B(w,{...this.options.load,dirs:g});if(!O.content)return null;if(r)this.cache[r]=O.content;let E=[];if(this.options.includeKey&&O.content[this.options.includeKey])E.push(...O.content[this.options.includeKey]),delete O.content[this.options.includeKey];if(this.options.includes)E.push(...this.options.includes),this.options.includes.length=0;if(await Y(E,{root:O.folderPath,loaded:(b)=>{if(this.options.mergeKey)Z(b,O.content,{mode:(T,C,M)=>M[this.options.mergeKey],...this.options.merge})},load:(b)=>this.load(b,void 0,O.folderPath,{parent:O.content,...F},!0),...this.options.include}),n!==!0)await U(O.content,{...this.options.fields,file:O.fullPath,root:{...this.options.fields.root,...this.options.variables,$document:{root:O,fileName:w,folder:O.folderPath,fullPath:O.fullPath,...F}},load:(b)=>this.load(b,void 0,O.folderPath,{parent:O.content,...F})});return O.content}merge(w,r){Z(w,r,{mode:(f,F,n)=>n[this.options.mergeKey],...this.options.merge})}mergeAll(w){let r={};for(let f of w.toReversed())this.merge(f,r);return r}async writeOutputs(w){if(w?.targetDirectory&&w?.removeFirst)try{await G.rm(w?.targetDirectory,{recursive:!0,force:!0})}catch(r){throw new Error(`Failed to clean the output directory: ${r.message}`)}for(let r of this.getOutputs()){let f=u.join(w?.targetDirectory??".",r.name),F=u.dirname(f);if(w?.writing?.(r)===!1)continue;try{await G.mkdir(F,{recursive:!0})}catch(n){throw new Error(`Failed to create target directory "${F}" for output "${f}": ${n.message}`)}try{switch(r.type){case"yaml":await G.writeFile(f,x.stringify(r.value));break;case"json":await G.writeFile(f,JSON.stringify(r.value));break;default:await G.writeFile(f,r.value.toString())}}catch(n){throw new Error(`Failed to write output "${f}": ${n.message}`)}}}}export{Yr as toObjectWithKey,V as toObject,I as toList,$ as select,Y as processIncludes,U as processFields,D as navigate,Z as merge,B as load,yr as find,c as Objector,j as NavigateResult,P as NavigateAction};
|