const e=require("fs"),t=require("path"),a=require("jsdom"),r=require("prettier"),n=require("@babel/core"),s=require("@babel/parser"),i=require("../package.json"),o=t.resolve("src/livecodes/i18n/locales/tmp"),l=t.resolve("src/livecodes/i18n/locales/en"),u=t.resolve("src/livecodes"),c=i.prettier,p="// ATTENTION: This file is auto-generated from source code. Do not edit manually!",d={translation:{},"language-info":{}},m={translation:{},"language-info":{}},g=(e,t=2)=>JSON.stringify(e,(e,t)=>t instanceof Object&&!(t instanceof Array)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,t),h=async(a,n)=>{let s="translation"===a?"translation":"languageInfo",i=`${p} import type { I18nTranslationTemplate } from '../models'; // This is used as a template for other translations. // Other translations should be typed like this: // const ${s}: ${"translation"===a?"I18nTranslation":"I18nLangInfoTranslation"} = { /* translation here */ }; // Since we allow nested objects, it is important to distinguish I18nTranslationTemplate from I18nAttributes. // In view of this, properties declared in I18nAttributes (and those attributes might be used in future) shall not be used as a nested key. const ${s} = ${g(d[a])} as const satisfies I18nTranslationTemplate; export default ${s}; `,u=await r.format(i,{parser:"typescript",...c});m[a].$comment=p.substring(3);let h=n?o:l;e.existsSync(h)||e.mkdirSync(h,{recursive:!0}),await Promise.all([e.promises.writeFile(t.join(h,a+".ts"),u),e.promises.writeFile(t.join(h,a+".lokalise.json"),await r.format(g(m[a]).replace(/<(\/?)(\d+)>/g,"<$1tag-$2>"),{parser:"json",...c}))]),console.log(`Generated namespace ${a} in ${h}.`)},f=(e,t,a,r)=>{let n=(e=e.split(":")).pop(),s=1===e.length?e.pop():"translation",i=n.split("."),o=d[s];i.forEach((e,a)=>{o[e]?a===i.length-1&&o[e]!==t&&console.error(`Duplicate key: ${n}`):o[e]=a===i.length-1?t:{},o=o[e]}),r&&1!==r.length?r.forEach(e=>{m[s][n+`#${e}`]={translation:t[e],notes:a[e]}}):m[s][n]={translation:t,notes:a}},y=e=>{let t=new a.JSDOM(e).window.document,r=[],n=0,s=e=>{if(e.nodeType!==t.ELEMENT_NODE)return;e.childNodes.forEach(e=>{s(e)});let a=e.tagName.toLowerCase();if("body"===a)return;let i=0===e.attributes.length?void 0:Array.from(e.attributes).reduce((e,t)=>(e[t.name]=t.value,e),{});r.push({name:a,attributes:i});let o=t.createElement(`tag-${n}`);for(;e.firstChild;)o.appendChild(e.firstChild);e.parentNode.replaceChild(o,e),n++};s(t.body);let i=1,o=[],l=t.body.innerHTML.replace(/tag-/g,""),u=[];return l=l.replace(/<(\d+)>/g,(e,t)=>(u.push(r[t]),o.push({from:RegExp(``,"g"),to:`<*/${i}>`}),`<${i++}>`)),o.forEach(({from:e,to:t})=>{l=l.replace(e,t)}),{html:l=l.replace(/<\*\//g,"e.map((e,t)=>`### <${t+1}> ### <${e.name} ${e.attributes?Object.keys(e.attributes).map(t=>`${t}="${e.attributes[t]}"`).join(" "):""} /> `).join(""),b=async t=>{let r=(e,t)=>{if("innerHTML"===t){let{html:t,elements:a}=y(e.innerHTML);return{value:t.trim(),desc:v(a)}}return{value:(t.startsWith("data-")?e.dataset[t.slice(5)]:e[t]||e.getAttribute(t)).trim(),desc:""}};f("translation:splash.loading","Loading LiveCodes\u2026","",["textContent"]),await Promise.all(t.map(async t=>{try{let n=(await e.promises.readFile(t,"utf8")).replace(/\s+/g," ").trim();new a.JSDOM(n).window.document.querySelectorAll("[data-i18n]").forEach(e=>{let t=e.getAttribute("data-i18n"),a=(e.getAttribute("data-i18n-prop")??"textContent").split(" "),{value:n,desc:s}=1===a.length?r(e,a[0]):a.reduce((t,a)=>{let n=r(e,a);return t.value[a]=n.value,t.desc[a]=n.desc,t},{value:{},desc:{}});f(t,n,s,a)})}catch(e){console.error(e)}}))},$=async t=>{await Promise.all(t.map(async t=>{try{let a=await e.promises.readFile(t,"utf8"),r=s.parse(a,{sourceType:"module",plugins:["typescript"]});n.traverse(r,{CallExpression(e){if("MemberExpression"===e.node.callee.type&&"Identifier"===e.node.callee.property.type&&"translateString"===e.node.callee.property.name&&e.node.arguments.length>=2&&"StringLiteral"===e.node.arguments[0].type&&"StringLiteral"===e.node.arguments[1].type){if(!e.node.arguments[2]||e.node.arguments[2].properties.every(e=>!e.key||!e.value||"isHTML"!==e.key.name||"isHTML"===e.key.name&&!0!==e.value.value))f(e.node.arguments[0].value,e.node.arguments[1].value,"",void 0);else{let{html:t,elements:a}=y(e.node.arguments[1].value);f(e.node.arguments[0].value,t.trim(),v(a),void 0)}}}})}catch(e){console.error(e)}}))},w=function(a,r=[]){return e.readdirSync(a).forEach(function(n){let s=a+t.sep+n;e.statSync(s).isDirectory()?r=w(s,r):r.push(s)}),r},T=async()=>{let e=process.argv.slice(2).filter(e=>!e.startsWith("-")),a=process.argv.includes("--save-temp"),r=[],n=[];e.length||e.push(...w(u)),r.push(...e.filter(e=>e.endsWith(".html")&&e.startsWith(t.resolve(u,`html${t.sep}`))).map(e=>t.resolve(u,e))),n.push(...e.filter(e=>e.endsWith(".ts")).map(e=>t.resolve(u,e))),await b(r),await $(n),h("translation",a),Object.keys(d["language-info"]).length>0&&h("language-info",a)};module.exports={generateTranslation:T,sortedJSONify:g,prettierConfig:c,autoGeneratedWarning:p},require.main===module&&T();