xml-disassembler
Version:
Disassemble XML files into smaller, more manageable files and reassemble the XML when needed.
3 lines (2 loc) • 11.8 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("log4js"),require("node:fs/promises"),require("node:path/posix"),require("node:fs"),require("node:path"),require("ignore"),require("fast-xml-parser"),require("json5"),require("smol-toml"),require("ini"),require("yaml"),require("node:crypto"),require("fs/promises")):"function"==typeof define&&define.amd?define(["exports","log4js","node:fs/promises","node:path/posix","node:fs","node:path","ignore","fast-xml-parser","json5","smol-toml","ini","yaml","node:crypto","fs/promises"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).jsTemplate={},e.log4js,e.promises,e.posix,e.node_fs,e.node_path,e.ignore,e.fastXmlParser,e.json5,e.smolToml,e.ini,e.yaml,e.node_crypto,e.promises$1)}(this,(function(e,t,r,n,o,i,s,l,a,u,d,c,f,m){"use strict";function y(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{a(n.next(e))}catch(e){i(e)}}function l(e){try{a(n.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,l)}a((n=n.apply(e,t||[])).next())}))}function p(e,t){for(const[r,n]of Object.entries(t))Array.isArray(n)?h(e,r,n):v(n)?g(e,r,n):b(e,r,n)}function h(e,t,r){e[t]=[...r]}function g(e,t,r){Array.isArray(e[t])?e[t].push(r):e[t]?e[t]=[e[t],r]:e[t]=r}function b(e,t,r){Object.prototype.hasOwnProperty.call(e,t)||(e[t]=r)}function v(e){return"object"==typeof e&&null!==e}"function"==typeof SuppressedError&&SuppressedError;const P={commentPropName:"!---",ignoreAttributes:!1,ignoreNameSpace:!1,parseTagValue:!1,parseNodeValue:!1,parseAttributeValue:!1,trimValues:!1,processEntities:!1,cdataPropName:"![CDATA["},j=Object.assign(Object.assign({},P),{format:!0,indentBy:" ",suppressBooleanAttributes:!1,suppressEmptyNode:!1});function E(e,t){return"#text"===e&&"string"==typeof t&&""===t.trim()}function x(e){return Array.isArray(e)?e.map(x).filter((e=>!("object"==typeof e&&0===Object.keys(e).length))):"object"==typeof e&&null!==e?function(e){const t={};for(const r in e){const n=e[r];if(E(r,n))continue;const o=x(n);void 0!==o&&(t[r]=o)}return t}(e):e}function N(e){return y(this,void 0,void 0,(function*(){const t=new l.XMLParser(P);let n;try{const o=yield r.readFile(e,"utf-8");n=t.parse(o,!0);return x(n)}catch(t){return void M.error(`${e} was unabled to be parsed and will not be processed. Confirm formatting and try again.`)}}))}const A={".yaml":c.parse,".yml":c.parse,".json":JSON.parse,".json5":a.parse,".toml":u.parse,".ini":d.parse};function q(e){return y(this,void 0,void 0,(function*(){if(e.endsWith(".xml"))return yield N(e);const t=Object.keys(A).find((t=>e.endsWith(t))),r=yield m.readFile(e,"utf-8");return A[t](r)}))}function F(e){return new l.XMLBuilder(j).build(e).trimEnd()}function O(e){return y(this,void 0,void 0,(function*(){return c.stringify(e)}))}function D(e){return y(this,void 0,void 0,(function*(){return a.stringify(e,null,2)}))}function C(e){return y(this,void 0,void 0,(function*(){return JSON.stringify(e,null,2)}))}function $(e){return y(this,void 0,void 0,(function*(){return u.stringify(e)}))}function _(e){return y(this,void 0,void 0,(function*(){return d.stringify(e)}))}const w={yaml:O,json5:D,json:C,toml:$,ini:_};function I(e,t){var r,n;if(!t)return k(e);return null!==(n=null!==(r=function(e,t){for(const r of t){const t=e[r];if("string"==typeof t)return t}}(e,t.split(",")))&&void 0!==r?r:function(e,t){for(const r in e){const n=e[r];if(!T(n))continue;const o=I(n,t);if(o)return o}}(e,t))&&void 0!==n?n:k(e)}function T(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function k(e){return f.createHash("sha256").update(JSON.stringify(e)).digest("hex").slice(0,8)}function L(e){return y(this,arguments,void 0,(function*({content:e,disassembledPath:t,outputFileName:o,subdirectory:i,wrapKey:s,isGroupedArray:l=!1,rootElementName:a,rootAttributes:u,xmlDeclaration:d,format:c,uniqueIdElements:f}){const m=i?n.join(t,i):t;let y=o;if(!y&&s&&!l&&"object"==typeof e){y=`${I(e,f)}.${s}-meta.${c}`}const p=n.join(m,y);yield r.mkdir(m,{recursive:!0});let h={[a]:Object.assign(Object.assign({},u),s?{[s]:e}:e)};"object"==typeof d&&null!==d&&(h=Object.assign({"?xml":d},h));const g=function(e){return w[e]}(c),b=g?yield g(h):F(h);yield r.writeFile(p,b),M.debug(`Created disassembled file: ${p}`)}))}function X(e){return y(this,void 0,void 0,(function*(){const{element:t,disassembledPath:r,uniqueIdElements:n,rootElementName:o,rootAttributes:i,key:s,leafCount:l,hasNestedElements:a,format:u,xmlDeclaration:d,strategy:c}=e,f=Array.isArray(t),m="object"==typeof t&&null!==t&&Object.keys(t).some((e=>!e.startsWith("#")));return f||m?"grouped-by-tag"===c?{leafContent:{},leafCount:l,hasNestedElements:!0,nestedGroups:{[s]:[t]}}:(yield L({content:t,disassembledPath:r,subdirectory:s,wrapKey:s,rootElementName:o,rootAttributes:i,xmlDeclaration:d,format:u,uniqueIdElements:n}),{leafContent:{},leafCount:l,hasNestedElements:!0}):{leafContent:{[s]:[t]},leafCount:l+1,hasNestedElements:a}}))}function S(e){return y(this,arguments,void 0,(function*({filePath:e,disassembledPath:t,baseName:n,postPurge:o,format:i,uniqueIdElements:s,strategy:l}){const a=yield N(e);if(!a)return;const{rootElementName:u,rootElement:d,xmlDeclaration:c}=function(e){const t=e["?xml"],r="object"==typeof t&&null!==t?t:void 0,n=Object.keys(e).find((e=>"?xml"!==e)),o=e[n];return{rootElementName:n,rootElement:o,xmlDeclaration:r}}(a),f=function(e){const t={};for(const[r,n]of Object.entries(e))r.startsWith("@")&&"string"==typeof n&&(t[r]=n);return t}(d),m=Object.keys(d).filter((e=>!e.startsWith("@"))),{leafContent:p,nestedGroups:h,leafCount:g,hasNestedElements:b}=yield function(e){return y(this,arguments,void 0,(function*({rootElement:e,keyOrder:t,disassembledPath:r,rootElementName:n,rootAttributes:o,xmlDeclaration:i,uniqueIdElements:s,strategy:l,format:a}){var u,d;let c={},f={},m=0,y=!1;for(const p of t){const t=Array.isArray(e[p])?e[p]:[e[p]];for(const e of t){const t=yield X({element:e,disassembledPath:r,uniqueIdElements:s,rootElementName:n,rootAttributes:o,key:p,leafCount:m,hasNestedElements:y,format:a,xmlDeclaration:i,strategy:l});if(t.leafContent[p]&&(c[p]=[...null!==(u=c[p])&&void 0!==u?u:[],...t.leafContent[p]]),"grouped-by-tag"===l&&t.nestedGroups)for(const e in t.nestedGroups)f[e]=[...null!==(d=f[e])&&void 0!==d?d:[],...t.nestedGroups[e]];m=t.leafCount,y=t.hasNestedElements}}return{leafContent:c,nestedGroups:f,leafCount:m,hasNestedElements:y}}))}({rootElement:d,keyOrder:m,disassembledPath:t,rootElementName:u,rootAttributes:f,xmlDeclaration:c,uniqueIdElements:s,strategy:l,format:i});(function(e,t,r){if(!t&&e>0)return M.error(`The XML file ${r} only has leaf elements. This file will not be disassembled.`),!0;return!1})(g,b,e)||(yield function(e,t,r){return y(this,void 0,void 0,(function*(){if("grouped-by-tag"===t)for(const t in e)yield L({content:e[t],disassembledPath:r.disassembledPath,outputFileName:`${t}.${r.format}`,wrapKey:t,isGroupedArray:!0,rootElementName:r.rootElementName,rootAttributes:r.rootAttributes,xmlDeclaration:r.xmlDeclaration,format:r.format})}))}(h,l,{disassembledPath:t,rootElementName:u,rootAttributes:f,xmlDeclaration:c,format:i}),yield function(e){return y(this,arguments,void 0,(function*({leafCount:e,leafContent:t,strategy:r,keyOrder:n,options:o}){if(0===e)return;const i="grouped-by-tag"===r?function(e,t){const r={};for(const n of t)void 0!==e[n]&&(r[n]=e[n]);return r}(t,n):t;yield L(Object.assign({content:i},o))}))}({leafCount:g,leafContent:p,strategy:l,keyOrder:m,options:{disassembledPath:t,outputFileName:`${n}.${i}`,rootElementName:u,rootAttributes:f,xmlDeclaration:c,format:i}}),o&&(yield r.unlink(e)))}))}const M=t.getLogger();t.configure({appenders:{disassemble:{type:"file",filename:"disassemble.log"}},categories:{default:{appenders:["disassemble"],level:"error"}}}),e.DisassembleXMLFileHandler=class{constructor(){this.ign=s()}disassemble(e){return y(this,void 0,void 0,(function*(){let{filePath:t,uniqueIdElements:n,strategy:o="unique-id",prePurge:s=!1,postPurge:l=!1,ignorePath:a=".xmldisassemblerignore",format:u="xml"}=e;["unique-id","grouped-by-tag"].includes(o)||(M.warn(`Unsupported strategy "${o}", defaulting to "unique-id".`),o="unique-id"),yield this._loadIgnoreRules(a);const d=yield r.stat(t),c=this.posixPath(i.relative(process.cwd(),t));d.isFile()?yield this._handleFile(t,c,{uniqueIdElements:n,strategy:o,prePurge:s,postPurge:l,format:u}):d.isDirectory()&&(yield this._handleDirectory(t,{uniqueIdElements:n,strategy:o,prePurge:s,postPurge:l,format:u,ignorePath:a}))}))}_loadIgnoreRules(e){return y(this,void 0,void 0,(function*(){const t=i.resolve(e);if(o.existsSync(t)){const e=yield r.readFile(t);this.ign.add(e.toString())}}))}_handleFile(e,t,r){return y(this,void 0,void 0,(function*(){const n=i.resolve(e);if(!this._isXmlFile(n))return void M.error(`The file path provided is not an XML file: ${n}`);if(this.ign.ignores(t))return void M.warn(`File ignored by ignore rules: ${n}`);const o=i.dirname(n);yield this.processFile(Object.assign(Object.assign({},r),{dirPath:o,filePath:n}))}))}_handleDirectory(e,t){return y(this,void 0,void 0,(function*(){const n=yield r.readdir(e);for(const r of n){const n=i.join(e,r),o=this.posixPath(i.relative(process.cwd(),n));this._isXmlFile(n)&&!this.ign.ignores(o)?yield this.processFile(Object.assign(Object.assign({},t),{dirPath:e,filePath:n})):this.ign.ignores(o)&&M.warn(`File ignored by ignore rules: ${n}`)}}))}_isXmlFile(e){return e.endsWith(".xml")}processFile(e){return y(this,void 0,void 0,(function*(){const{dirPath:t,strategy:n,filePath:s,uniqueIdElements:l,prePurge:a,postPurge:u,format:d}=e;M.debug(`Parsing file to disassemble: ${s}`);const c=i.basename(s,i.extname(s)),f=c.split(".")[0],m=i.join(t,f);a&&o.existsSync(m)&&(yield r.rm(m,{recursive:!0})),yield S({filePath:s,disassembledPath:m,uniqueIdElements:l,baseName:c,postPurge:u,format:d,strategy:n})}))}posixPath(e){return e.replace(/\\+/g,"/")}},e.ReassembleXMLFileHandler=class{reassemble(e){return y(this,void 0,void 0,(function*(){const{filePath:t,fileExtension:n,postPurge:o=!1}=e;if(!(yield this._validateDirectory(t)))return;M.debug(`Parsing directory to reassemble: ${t}`);const i=yield this.processFilesInDirectory(t);if(!i.length)return void this._logEmptyParseError(t);const s=F(function(e){if(0===e.length)return void M.error("No elements to merge.");const t=e[0],r=Object.keys(t).find((e=>"?xml"!==e)),n={};for(const t of e)p(n,t[r]);return function(e,t,r){return e?{"?xml":e,[t]:r}:{[t]:r}}(t["?xml"],r,n)}(i)),l=this._getOutputPath(t,n);yield r.writeFile(l,s,"utf-8"),o&&(yield r.rm(t,{recursive:!0}))}))}processFilesInDirectory(e){return y(this,void 0,void 0,(function*(){const t=[],o=yield r.readdir(e),i=this._sortFilesByBaseName(o);for(const o of i){const i=n.join(e,o),s=yield r.stat(i);if(s.isFile()&&this._isParsableFile(o)){const e=yield q(i);e&&t.push(e)}else if(s.isDirectory()){const e=yield this.processFilesInDirectory(i);t.push(...e)}}return t}))}_sortFilesByBaseName(e){return e.sort(((e,t)=>e.split(".")[0].localeCompare(t.split(".")[0])))}_isParsableFile(e){return/\.(xml|json|json5|ya?ml|toml|ini)$/i.test(e)}_validateDirectory(e){return y(this,void 0,void 0,(function*(){return!!(yield r.stat(e)).isDirectory()||(M.error(`The provided path to reassemble is not a directory: ${e}`),!1)}))}_logEmptyParseError(e){M.error(`No files under ${e} were parsed successfully. A reassembled XML file was not created.`)}_getOutputPath(e,t){const r=n.dirname(e),o=`${n.basename(e)}.${null!=t?t:"xml"}`;return n.join(r,o)}},e.buildXMLString=F,e.logger=M,e.parseXML=N,e.setLogLevel=function(e){t.getLogger().level=e},e.transformToIni=_,e.transformToJson=C,e.transformToJson5=D,e.transformToToml=$,e.transformToYaml=O}));
//# sourceMappingURL=index.min.umd.js.map