@homedev/objector 0.0.11 → 0.0.13

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 +1 @@
1
- import b from"path";import J from"fs/promises";import B from"path";import z from"yaml";var _=async(O)=>{try{return await J.access(O,J.constants.R_OK),!0}catch{return!1}},G=async(O,T)=>{let F=await(async()=>{let D=[""];if(!B.isAbsolute(O)&&T?.dirs)D.push(...T.dirs);for(let I of D){let q=B.join(I,O);if(await _(q))return B.resolve(q)}throw new Error(`File not found: "${O}"`)})(),P=await J.readFile(F),j=B.dirname(F),E={"[.](yml|yaml)$":z.parse,"[.]json$":JSON.parse,...T?.parsers},M=Object.entries(E).find((D)=>F.match(D[0]));if(!M)throw new Error(`Unhandled file type: ${O}`);return{content:M[1](P.toString()),fullPath:F,folderPath:j}};var k=async(O,T)=>{for(let C of O){let F=T?.root?b.join(T.root,C):C,P=await G(F,T?.loadOptions);if(T?.loaded)await T.loaded(P)}};var f=(O,T,C)=>{for(let F of Object.keys(T)){if(O[F]===void 0)continue;let P=T[F],j=O[F];if(typeof j!==typeof P||Array.isArray(j)!==Array.isArray(P)){let M=C?.mismatch?.(F,j,P,O,T);if(M!==void 0){T[F]=M;continue}throw new Error(`Type mismatch: ${F}`)}let E=C?.mode?.(F,j,P,O,T)??"merge";switch(E){case"source":T[F]=j;continue;case"target":continue;case"skip":delete T[F],delete O[F];continue;case"merge":break;default:throw new Error(`Unknown merge mode: ${E}`)}if(typeof j==="object")if(Array.isArray(j))P.push(...j);else{if(C?.navigate?.(F,j,P,O,T)===!1)continue;f(j,P,C)}else{if(j===P)continue;let M=C?.conflict?.(F,j,P,O,T);T[F]=M===void 0?P:M}}for(let F of Object.keys(O))if(T[F]===void 0)T[F]=O[F]};var K;((j)=>{j[j.Continue=0]="Continue";j[j.Skip=1]="Skip";j[j.ReplaceItem=2]="ReplaceItem";j[j.ReplaceParent=3]="ReplaceParent";j[j.DeleteParent=4]="DeleteParent"})(K||={});class w{action;by;constructor(O,T){this.action=O;this.by=T}static ReplaceParent(O){return new w(3,O)}static ReplaceItem(O){return new w(2,O)}static Skip(){return new w(1)}static Continue(){return new w(0)}static DeleteParent(){return new w(4)}}var H=async(O,T)=>{let C=async(P)=>{for(let[j,E]of Object.entries(P.value)){let M=await F({key:j,value:E,path:P.path,parent:P.value});switch(M.action){case 3:if(!P.key)throw new Error("Cannot replace root");P.parent[P.key]=M.by;return;case 2:P.value[j]=M.by;break;case 1:return;case 4:delete P.parent[P.key];return}}},F=async(P)=>{let j=P.key?await T(P):{action:0};if(j.action===0){if(P.value&&typeof P.value==="object"){if(P.key)P.path.push(P.key);if(await C(P),P.key)P.path.pop()}}return j};await F({key:null,value:O,path:[],parent:null})};var S=async(O,T,C,F)=>{for(let[P,j]of F?.keys??[]){let E=P.exec(O.key);if(E){let[,M,...W]=E;if(j[M]){let D={args:[O.value,...W],path:T,value:O.value,root:C,parent:O.parent,key:O.key,origin:F?.origin,options:F},I=typeof j[M]==="function"?await j[M](D):j[M];if(I===null)return w.DeleteParent();if(I===void 0)return w.Continue();return w.ReplaceParent(I)}}}};var U=async(O,T,C,F)=>{let P,j=[],E=T;for(let[M,W]of F?.sources??[]){if(P)break;E=E.replaceAll(M,(D,I,...q)=>{if(P)return D;let $=W[I];if(typeof $!=="object"&&typeof $!=="function")return $??D;if(typeof $==="object")return P=$,D;let d=$({args:q,path:O,value:E,root:C,key:I,options:F});if(typeof d==="object")return P=d,D;return d instanceof Promise?`ð[${j.push(d)}]ñ`:d})}if(P){let M=await P;if(M===null)return w.DeleteParent();if(M)return w.ReplaceItem(M)}if(j.length){let M=await Promise.all(j);E=E.replaceAll(/\xf0\[(\d+)]\xf1/g,(W,D)=>M[+D-1])}return E===T?w.Continue():w.ReplaceItem(E)};var e=async(O,T)=>H(O,async(C)=>{let F=[...C.path,C.key].join(".");if(T?.filters){if(!T.filters.some((P)=>P.test(F)))return w.Continue()}return await S(C,F,O,T)??(typeof C.value==="string"?await U(F,C.value,O,T):w.Continue())});import L from"yaml";var X=(O,T="name")=>Object.entries(O).map(([C,F])=>({[T]:C,...F})),FF=(O,T="name")=>Object.fromEntries(O.map((C)=>[C[T],C])),Z=(O,T="name")=>Object.fromEntries(O.map((C)=>{let{[T]:F,...P}=C;return[F,P]}));var Y=(O,T)=>{let C=/^\[([^=\]]*)([=]*)([^\]]*)\]$/.exec(T);if(C){let[P,j,E,M]=C;if(Array.isArray(O))switch(E){case"==":case"=":return O.find((W)=>W[j.trim()]==M.trim())}}let F=/^([^[\]]*)\[([^\]]*)]/.exec(T);if(F)return O[F[1]][F[2]];return O[T]},Q=(O,T,C)=>{let F=void 0,P=void 0;T??="";let j=(M,W)=>{let D=W.pop();if(D){let I=Y(M,D);if(!I)throw new Error(`Unknown path element: "${D}" in "${T}"`);return F=M,P=D,j(I,W)}if(C?.set&&P)F[P]=C?.set;return M},E=j(O,T.split(C?.separator??".").reverse());switch(C?.format){case"list":return X(E,C?.key);case"object":return Z(E,C?.key);case"json":return JSON.stringify(E);case"yaml":return L.stringify(E);default:return E}},CF=(O,T)=>{let C=/^(?<path>[^@>]*)?(?:@(?<from>[^>]*))?(?:>(?<format>[^|]*)(?:\|(?<key>.*))?)?$/.exec(O)?.groups;if(!C)throw new Error(`Invalid reference: "${O}"`);let{from:F,path:P,format:j,key:E}=C;if(!F)return Q(T.root,P,{format:j,key:E});if(T.async===!1){if(!T.load)throw new Error("No load function defined");return Q(T.load(F),P,{format:j,key:E})}else return(T.load??G)(F).then((M)=>Q(M,P,{format:j,key:E}))};var wF=async(O,T)=>{let C=[];return await H(O,(F)=>{if(T([...F.path,F.key].join("."),F.value))C.push(F.value);return w.Continue()}),C};export{FF as toObjectWithKey,Z as toObject,X as toList,Q as selectPath,CF as select,k as processIncludes,e as processFields,H as navigate,f as merge,G as load,wF as find,w as NavigateResult,K as NavigateAction};
1
+ import v from"path";import D from"fs/promises";import X from"path";import r from"yaml";var h=async(T)=>{try{return await D.access(T,D.constants.R_OK),!0}catch{return!1}},G=async(T,F)=>{let P=await(async()=>{let $=[""];if(!X.isAbsolute(T)&&F?.dirs)$.push(...F.dirs);for(let W of $){let U=X.join(W,T);if(await h(U))return X.resolve(U)}throw new Error(`File not found: "${T}"`)})(),O=await D.readFile(P),C=X.dirname(P),M={"[.](yml|yaml)$":r.parse,"[.]json$":JSON.parse,...F?.parsers},E=Object.entries(M).find(($)=>P.match($[0]));if(!E)throw new Error(`Unhandled file type: ${T}`);return{content:E[1](O.toString()),fullPath:P,folderPath:C}};var L=async(T,F)=>{for(let j of T){let P=F?.root?v.join(F.root,j):j,O=await G(P,F?.loadOptions);if(F?.loaded)await F.loaded(O)}};var Z=(T,F,j)=>{for(let P of Object.keys(F)){if(T[P]===void 0)continue;let O=F[P],C=T[P];if(typeof C!==typeof O||Array.isArray(C)!==Array.isArray(O)){let E=j?.mismatch?.(P,C,O,T,F);if(E!==void 0){F[P]=E;continue}throw new Error(`Type mismatch: ${P}`)}let M=j?.mode?.(P,C,O,T,F)??"merge";switch(M){case"source":F[P]=C;continue;case"target":continue;case"skip":delete F[P],delete T[P];continue;case"merge":break;default:throw new Error(`Unknown merge mode: ${M}`)}if(typeof C==="object")if(Array.isArray(C))O.push(...C);else{if(j?.navigate?.(P,C,O,T,F)===!1)continue;Z(C,O,j)}else{if(C===O)continue;let E=j?.conflict?.(P,C,O,T,F);F[P]=E===void 0?O:E}}for(let P of Object.keys(T))if(F[P]===void 0)F[P]=T[P]};var Y;((C)=>{C[C.Continue=0]="Continue";C[C.Skip=1]="Skip";C[C.ReplaceItem=2]="ReplaceItem";C[C.ReplaceParent=3]="ReplaceParent";C[C.DeleteParent=4]="DeleteParent"})(Y||={});class I{action;by;constructor(T,F){this.action=T;this.by=F}static ReplaceParent(T){return new I(3,T)}static ReplaceItem(T){return new I(2,T)}static Skip(){return new I(1)}static Continue(){return new I(0)}static DeleteParent(){return new I(4)}}var S=async(T,F)=>{let j=async(O)=>{for(let[C,M]of Object.entries(O.value)){let E=await P({key:C,value:M,path:O.path,parent:O.value});switch(E.action){case 3:if(!O.key)throw new Error("Cannot replace root");O.parent[O.key]=E.by;return;case 2:O.value[C]=E.by;break;case 1:return;case 4:delete O.parent[O.key];return}}},P=async(O)=>{let C=O.key?await F(O):{action:0};if(C.action===0){if(O.value&&typeof O.value==="object"){if(O.key)O.path.push(O.key);if(await j(O),O.key)O.path.pop()}}return C};await P({key:null,value:T,path:[],parent:null})};var z=async(T,F,j,P)=>{for(let[O,C]of P?.keys??[]){let M=O.exec(T.key);if(M){let[,E,...w]=M;if(C[E]){let $={args:[T.value,...w],path:F,value:T.value,root:j,parent:T.parent,key:T.key,origin:P?.origin,options:P},W=typeof C[E]==="function"?await C[E]($):C[E];if(W===null)return I.DeleteParent();if(W===void 0)return I.Continue();return I.ReplaceParent(W)}}}};var K=async(T,F,j,P)=>{let O,C=[],M=F;for(let[E,w]of P?.sources??[]){if(O)break;M=M.replaceAll(E,($,W,...U)=>{if(O)return $;let B=w[W];if(typeof B!=="object"&&typeof B!=="function")return B??$;if(typeof B==="object")return O=B,$;let Q=B({args:U,path:T,value:M,root:j,key:W,options:P});if(typeof Q==="object")return O=Q,$;return Q instanceof Promise?`ð[${C.push(Q)}]ñ`:Q})}if(O){let E=await O;if(E===null)return I.DeleteParent();if(E)return I.ReplaceItem(E)}if(C.length){let E=await Promise.all(C);M=M.replaceAll(/\xf0\[(\d+)]\xf1/g,(w,$)=>E[+$-1])}return M===F?I.Continue():I.ReplaceItem(M)};var _=async(T,F)=>S(T,async(j)=>{let P=[...j.path,j.key].join(".");if(F?.filters){if(!F.filters.some((C)=>C.test(P)))return I.Continue()}let O=async(C)=>{let M=await K(P,C,F?.root??T,F);if(M.action===2&&typeof M.by==="string"){let E=await O(M.by);if(E.by)return E}return M};return await z(j,P,F?.root??T,F)??(typeof j.value==="string"?await O(j.value):I.Continue())});import N from"yaml";var R=(T,F="name")=>Object.entries(T).map(([j,P])=>({[F]:j,...P})),wF=(T,F="name")=>Object.fromEntries(T.map((j)=>[j[F],j])),A=(T,F="name")=>Object.fromEntries(T.map((j)=>{let{[F]:P,...O}=j;return[P,O]}));var y=(T,F,j="(",P=")")=>{let O=0,C="",M=[];for(let E of T){if(C+=E,E===j)O++;if(E===P)O--;if(O===0&&E===F)M.push(C.slice(0,-1)),C=""}if(C)M.push(C);return M};var d=(T,F,j,P)=>{if(F.startsWith("{")){let M=F.substring(1,F.length-1),E=q(j,M,P);return q(T,E,P)}let O=/^\[([^=\]]*)([=]*)([^\]]*)\]$/.exec(F);if(O){let[M,E,w,$]=O;if(Array.isArray(T))switch(w){case"==":case"=":return T.find((W)=>W[E.trim()]==$.trim())}}let C=/^([^[\]]*)\[([^\]]*)]/.exec(F);if(C)return T[C[1]][C[2]];return T[F]},q=(T,F,j)=>{let P=void 0,O=void 0;F??="";let C=(E,w)=>{let $=w.pop();if($){let W=d(E,$,T,j);if(!W)throw new Error(`Unknown path element: "${$}" in "${F}"`);return P=E,O=$,C(W,w)}if(j?.set&&O)P[O]=j?.set;return E},M=C(T,y(F,j?.separator??".","{","}").reverse());switch(j?.format){case"list":return R(M,j?.key);case"object":return A(M,j?.key);case"json":return JSON.stringify(M);case"yaml":return N.stringify(M);default:return M}};var H=(T,F)=>{let j=/^(?<path>[^@>]*)?(?:@(?<from>[^>]*))?(?:>(?<format>[^|]*)(?:\|(?<key>.*))?)?$/.exec(T)?.groups;if(!j)throw new Error(`Invalid reference: "${T}"`);let{from:P,path:O,format:C,key:M}=j;if(!P)return q(F.root,O,{format:C,key:M});if(F.async===!1){if(!F.load)throw new Error("No load function defined");return q(F.load(P),O,{format:C,key:M})}else return(F.load??G)(P).then((E)=>q(E,O,{format:C,key:M}))};var SF=async(T,F)=>{let j=[];return await S(T,(P)=>{if(F([...P.path,P.key].join("."),P.value))j.push(P.value);return I.Continue()}),j};import b from"fs/promises";import k from"path";import m from"yaml";import g from"fs/promises";import J from"path";var f=(T)=>{return{include:(F)=>T.load(F.args[0]),file:(F)=>g.readFile(F.args[0]).then((j)=>j.toString()),env:(F)=>process.env[F.args[0]],ref:(F)=>H(F.args[0],{root:F.root,load:(j)=>T.load(j)})}},V=(T)=>{return{load:async(F)=>{for(let{file:j,alias:P}of Array.isArray(F.value)?F.value:[F.value]){if(!j)throw new Error("File reference required");await T.load(j,P??j,F.origin&&J.dirname(F.origin))}delete F.parent[F.key]},include:(F)=>T.load(F.value,void 0,F.origin&&J.dirname(F.origin)),from:async(F)=>{let j=await H(F.value,{root:F.root,load:(P)=>T.load(P,void 0,F.origin&&J.dirname(F.origin))});if(F.parent.content){if(Array.isArray(F.parent.content)&&Array.isArray(j))return[...j,...F.parent.content];return T.merge(j,F.parent.content),F.parent.content}return j},concat:async(F)=>{let j=[];for(let P of Array.isArray(F.value)?F.value:[F.value])j.push(...await H(P,{root:F.root,load:(O)=>T.load(O,void 0,F.origin&&J.dirname(F.origin))}));return j.filter((P)=>P!==void 0)},extends:async(F)=>{for(let j of Array.isArray(F.value)?F.value:[F.value])T.merge(await H(j,{root:F.root,load:(P)=>T.load(P,void 0,F.origin&&J.dirname(F.origin))}),F.parent);delete F.parent[F.key]},alias:(F)=>{T.alias(F.value,F.parent),delete F.parent[F.key]},if:(F)=>{if(!F.value)return null;delete F.parent[F.key]},output:(F)=>{delete F.parent[F.key];for(let j of Array.isArray(F.value)?F.value:[F.value])T.output(j,F.parent)},each:async(F)=>{delete F.parent[F.key];let j=Array.isArray(F.value)?F.value:await H(F.value,{root:F.root,load:(O)=>T.load(O,void 0,F.origin&&J.dirname(F.origin))}),P=[];if(!Array.isArray(j))throw new Error("source must be a list");for(let O=0;O<j.length;O++){let C=j[O],M=JSON.parse(JSON.stringify(F.parent)),E=[[/^\.(.*)/,{item:($)=>q(C,$.value)}]],w=[[/\$\((\w*)(?::([^)]*))?\)/g,{index:O,...C}]];F.options?.keys&&E.push(...F.options.keys),F.options?.sources&&w.push(...F.options.sources),console.log(M),await _(M,{...F.options,sources:w,keys:E,root:{...F.root,item:C,this:M}}),P.push(M)}return P}}};class p{options={load:{dirs:[]},merge:{},include:{},fields:{},includeKey:"includes",mergeKey:".merge"};cache={};includeDirectory(...T){return this.options.load.dirs??=[],this.options.load.dirs.push(...T),this}updateOrCreate(T,F,j){this.options.fields[F]??=[];let P=this.options.fields[F],O=P.find((C)=>C[0].source===T.source);if(!O)P.push([T,j]);else O[1]={...O[1],...j};return this}keys(T,F){return this.updateOrCreate(F??/^\.(.*)/,"keys",T)}sources(T,F){return this.updateOrCreate(F??/\$\(([^:)]*)(?::([^)]*))?\)/g,"sources",T)}output(T,F){return this.options.outputs??={},this.options.outputs[T]=F,this}defaultSources(T){return this.sources(f(this),T)}defaultKeys(T){return this.keys(V(this),T)}defaultProcessors(){return this.defaultKeys().defaultSources()}alias(T,F){return this.cache[T]=F,this}getAlias(T){return this.cache[T]}getOutputs(){return this.options.outputs??{}}async load(T,F,j){if(this.cache[T])return this.cache[T];let P=j?[j]:[];this.options.load.dirs&&P.push(...this.options.load.dirs);let O=await G(T,{...this.options.load,dirs:P});if(!O.content)return null;if(F)this.cache[F]=O.content;if(this.options.includeKey&&O.content[this.options.includeKey])await L(O.content[this.options.includeKey],{root:O.folderPath,loaded:(C)=>{if(this.options.mergeKey){if(C.content)Z(C.content,O.content,{mode:(M,E,w)=>w[this.options.mergeKey],...this.options.merge})}},loadOptions:this.options.load,...this.options.include}),delete O.content[this.options.includeKey];return await _(O.content,{...this.options.fields,origin:O.fullPath}),O.content}merge(T,F){Z(T,F,{mode:(j,P,O)=>O[this.options.mergeKey],...this.options.merge})}async writeOutputs(T){for(let[F,j]of Object.entries(this.getOutputs())){let P=k.join(T??".",F);try{switch(k.extname(F)){case".yml":case".yaml":await b.writeFile(P,m.stringify(j));break;case".json":await b.writeFile(P,JSON.stringify(j));break;default:await b.writeFile(P,j)}}catch{throw new Error(`Failed to write output: ${P}`)}}}}export{wF as toObjectWithKey,A as toObject,R as toList,H as select,L as processIncludes,_ as processFields,S as navigate,Z as merge,G as load,SF as find,p as Objector,I as NavigateResult,Y as NavigateAction};
@@ -118,7 +118,7 @@ export declare interface NavigateContext {
118
118
  */
119
119
  export declare class NavigateResult {
120
120
  readonly action: NavigateAction;
121
- readonly by?: any | undefined;
121
+ by?: any | undefined;
122
122
  constructor(action: NavigateAction, by?: any | undefined);
123
123
  static ReplaceParent(by: any): NavigateResult;
124
124
  static ReplaceItem(by: any): NavigateResult;
@@ -127,6 +127,27 @@ export declare class NavigateResult {
127
127
  static DeleteParent(): NavigateResult;
128
128
  }
129
129
 
130
+ /**
131
+ * @public
132
+ */
133
+ export declare class Objector {
134
+ private cache;
135
+ includeDirectory(...dirs: string[]): this;
136
+ private updateOrCreate;
137
+ keys(keys: FieldProcessorMap, matcher?: RegExp): this;
138
+ sources(sources: FieldProcessorMap, matcher?: RegExp): this;
139
+ output(name: string, value: any): this;
140
+ defaultSources(matcher?: RegExp): this;
141
+ defaultKeys(matcher?: RegExp): this;
142
+ defaultProcessors(): this;
143
+ alias(name: string, o: any): this;
144
+ getAlias(name: string): any;
145
+ getOutputs(): Record<string, any>;
146
+ load<T = any>(fileName: string, alias?: string, cwd?: string): Promise<T | null>;
147
+ merge(source: any, target: any): void;
148
+ writeOutputs(targetDirectory?: string): Promise<void>;
149
+ }
150
+
130
151
  /**
131
152
  * @public
132
153
  * @param root
@@ -140,6 +161,7 @@ export declare interface ProcessFieldsOptions {
140
161
  keys?: FieldProcessorMatcher[];
141
162
  filters?: RegExp[];
142
163
  origin?: string;
164
+ root?: any;
143
165
  }
144
166
 
145
167
  /**
@@ -155,22 +177,6 @@ export declare const select: (at: string, options: {
155
177
  async?: boolean;
156
178
  }) => any;
157
179
 
158
- export declare interface SelectOptions {
159
- set?: any;
160
- format?: string;
161
- key?: string;
162
- separator?: string;
163
- }
164
-
165
- /**
166
- * @public
167
- * @param from
168
- * @param path
169
- * @param set
170
- * @returns
171
- */
172
- export declare const selectPath: <T = any>(from: any, path: string, options?: SelectOptions) => T;
173
-
174
180
  export declare const toList: <T>(from: any, key?: string) => T[];
175
181
 
176
182
  export declare const toObject: <T>(from: any[], key?: string) => T;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@homedev/objector",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "object extensions for YAML/JSON",
5
5
  "author": "julzor",
6
6
  "license": "ISC",