var D=Object.create;var M=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var T=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of H(e))!_.call(t,n)&&n!==r&&M(t,n,{get:()=>e[n],enumerable:!(s=V(e,n))||s.enumerable});return t};var w=(t,e,r)=>(r=t!=null?D(F(t)):{},T(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t));var E=require("source-map-support"),f=w(require("../main/modules/error")),o=require("electron/main"),L=require("electron/common"),O=require("fs"),h=require("./global"),U=require("../main/modules/update"),x=w(require("./modules/l10n")),R=w(require("../main/windows/main")),k=require("../main/modules/config"),a=w(require("@spacingbat3/kolor")),m=require("path"),j=require("./modules/agent"),P=require("./modules/client"),A=require("../main/modules/optimize"),W=require("../main/modules/extensions"),v=require("util");process.platform==="win32"&&(process.argv[1]?.startsWith("--squirrel-")??!1)&&(console.log("Detected --squirrel-* option, possibly application's being run during installation, aborting..."),process.exit());(0,E.install)();(0,f.default)();const z=Object.freeze({options:Object.freeze({color:{type:"string"},help:{type:"boolean",short:"h"},info:{type:"boolean",short:"?"},version:{type:"boolean",short:"V"},"start-minimized":{type:"boolean",short:"m"},"export-l10n":{type:"string"},verbose:{type:"boolean",short:"v"},"user-agent-mobile":{type:"boolean"},"user-agent-version":{type:"string"},"user-agent-device":{type:"string"},"user-agent-platform":{type:"string"},"user-agent-arch":{type:"string"},"add-css-theme":{type:"boolean"},"gpu-info":{type:"string"},"safe-mode":{type:"boolean"}}),strict:!1,args:Object.freeze(process.argv).slice(1).filter(t=>(0,m.resolve)(t)!==(0,m.resolve)(o.app.getAppPath()))}),l=Object.freeze((0,v.parseArgs)(z));{const t=console.warn,e=console.error,r=console.debug;console.error=(i,...c)=>{e(typeof i=="string"?a.default.red(i):i,...c)},console.warn=(i,...c)=>{t(typeof i=="string"?a.default.yellow(i):i,...c)},console.debug=(i,...c)=>{(__filename.startsWith(o.app.getAppPath())&&(0,v.debug)("webcord").enabled||l.values.verbose===!0)&&r(typeof i=="string"?a.default.gray(i):i,...c)};const s=()=>console.log=console.debug=()=>{},n=()=>console.error=console.warn=()=>{};process.stdout.once("error",s).once("close",s),process.stderr.once("error",n).once("close",n)}{const{AppUserModelId:t}=(0,P.getBuildInfo)();process.platform==="win32"&&t!==void 0&&o.app.setAppUserModelId(t)}let B=!1,g=!1;const S={};let b;{const t=(e,r,s,n=32)=>{const i=z.options[e],c=["--"+e,s!==void 0?"="+a.default.yellow(s):i.type==="string"?"="+a.default.yellow("{string}"):"","short"in i?"   -"+i.short:""].join(""),d=n-(0,v.stripVTControlCharacters)(c).length,u=r.replaceAll(s??/^$/g,s!==void 0?a.default.yellow(s):"").replaceAll(/(--?[a-zA-Z-]+)/g,a.default.green("$1"));return"  "+a.default.green(c)+" ".repeat(d>0?d:0)+a.default.gray(u)};if((0,P.getBuildInfo)().type!=="devel")for(const e of["inspect-brk","inspect-port","inspect","inspect-publish-uid"])o.app.commandLine.hasSwitch(e)&&(console.info("Unsafe switch detected: '--"+e+"'! It will be removed from Chromium's cmdline\u2026"),o.app.commandLine.removeSwitch(e));if(l.values.help===!0||l.values.info===!0){const e=process.argv0.endsWith("electron")&&process.argv.length>2?(process.argv[0]??"")+' "'+(process.argv[1]??"")+'"':process.argv0;console.log([`
 `+a.default.bold(a.default.blue(o.app.getName()))+" \u2013 Privacy focused Discord client made with "+a.default.bold(a.default.whiteBright(a.default.bgBlue("TypeScript")))+" and "+a.default.bold(a.default.bgBlack(a.default.cyanBright("Electron")))+`.
`," "+a.default.underline("Usage:")," "+a.default.red(e)+a.default.green(` [options]
`)," "+a.default.underline("Options:")].join(`
`)+`
`+[t("color","Whenever colorize console font.","always|auto|never"),t("help","Show this help message."),t("info","An alias for --help."),t("version","Show current application version."),t("start-minimized","Hide application at first run."),t("export-l10n","Export localization files to {dir} directory","{dir}."),t("verbose","Show debug messages."),t("gpu-info","Shows GPU information as JS object.","basic|complete"),t("user-agent-mobile","Whenever use 'mobile' variant of user agent."),t("user-agent-platform","Platform to replace in the user agent."),t("user-agent-version","Version of platform in user agent."),t("user-agent-device","Device identifier in the user agent (Android)."),t("user-agent-arch","Architecture to replace in the user agent."),t("add-css-theme","Adds theme to WebCord using file picker."),t("safe-mode","Starts WebCord in 'Safe Mode'.")].sort().join(`
`)+`
`),o.app.exit()}if(l.values.version===!0){const e=(0,P.getBuildInfo)();console.log(o.app.getName()+" v"+o.app.getVersion()+", "+(e.type==="release"?"stable":"development")+" build"+(e.commit!==void 0?", commit hash "+e.commit:"")),o.app.exit()}if(l.values["user-agent-mobile"]===!0&&(S.mobile=!0),("user-agent-device"in l.values||"user-agent-version"in l.values||"user-agent-platform"in l.values||"user-agent-arch"in l.values)&&(S.replace={platform:typeof l.values["user-agent-platform"]=="string"?l.values["user-agent-platform"]:process.platform,version:typeof l.values["user-agent-version"]=="string"?l.values["user-agent-version"]:process.getSystemVersion(),device:typeof l.values["user-agent-device"]=="string"?l.values["user-agent-device"]:void 0,arch:typeof l.values["user-agent-arch"]=="string"?l.values["user-agent-arch"]:process.arch}),l.values["start-minimized"]===!0&&(B=!0),l.values["safe-mode"]===!0&&(g=!0),l.values.verbose===!0?(process.env.NODE_DEBUG="*",process.env.DEBUG="*",o.app.commandLine.appendSwitch("enable-logging"),o.app.commandLine.appendSwitch("log-level","-1"),o.app.commandLine.appendSwitch("v","-1")):o.app.commandLine.appendSwitch("log-level","3"),"export-l10n"in l.values&&(b=()=>{const e=new x.default,r=l.values["export-l10n"];if(r!=="string")throw new TypeError("Parameter 'export-l10n' should contain a string value!");const s=[];for(const n of Object.keys(e))s.push(O.promises.writeFile((0,m.resolve)(r,n+".json"),JSON.stringify(e[n],null,2)));Promise.all(s).then(()=>{console.log([`
\u{1F389}\uFE0F `+a.default.green(a.default.bold("Successfully"))+" exported localization files to","   '"+a.default.blue(a.default.underline(r))+`'!
`].join(`
`)),o.app.quit()}).catch(n=>{if(!(n instanceof Error))return;const i="path"in n&&typeof n.path=="string"?{relative:(0,m.relative)(process.cwd(),n.path),absolute:(0,m.resolve)(process.cwd(),n.path),original:n.path}:{original:""},c=i.absolute!==void 0?i.absolute.length>i.relative.length?i.relative:i.absolute:null,d="syscall"in n&&typeof n.syscall=="string"?n.syscall:"",u="code"in n&&typeof n.code=="string"?n.code:"";console.error([`
\u26D4\uFE0F `+a.default.red(a.default.bold("code"in n&&typeof n.code=="string"?n.code:n.name))+" "+d+": ",c!==null?a.default.blue(a.default.underline(c))+": ":"",n.message.replace(u+": ","").replace(", "+d+" '"+i.original+"'","")+`.
`].join("")),o.app.exit(("errno"in n&&typeof n.errno=="number"?n.errno:0)*-1)})}),"gpu-info"in l.values){const e=l.values["gpu-info"];switch(e){case"basic":case"complete":o.app.getGPUInfo(e).then(r=>{console.log("GPU information object:"),console.dir(r)}).then(()=>o.app.exit()).catch(f.commonCatches.throw);break;default:throw new Error(`Flag 'gpu-info' should include a value of type '"basic"|"complete"'.`)}}"add-css-theme"in l.values&&(b=()=>{W.styles.add().then(()=>process.exit(0)).catch(()=>process.exit(1))})}{const t=(e,r)=>{if(r!==void 0&&o.app.commandLine.getSwitchValue(e)!=="")switch(e){case"enable-features":case"enable-blink-features":r=o.app.commandLine.getSwitchValue(e)+","+r}o.app.commandLine.appendSwitch(e,r),console.debug("[OPTIMIZE] Applying flag: %s...","--"+e+(r!==void 0?"="+r:""))};if(g)o.app.commandLine.appendSwitch("use-gl","angle"),o.app.commandLine.appendSwitch("use-angle","swiftshader");else if(k.appConfig.value.settings.advanced.optimize.gpu)for(const e of(0,A.getRecommendedGPUFlags)())t(e[0],e[1]);if(process.platform!=="win32"&&k.appConfig.value.settings.advanced.unix.autoscroll&&!g&&t("enable-blink-features","MiddleClickAutoscroll"),!g)for(const e of(0,A.getRecommendedOSFlags)())t(e[0],e[1]);if(process.platform!=="win32"&&process.platform!=="darwin"&&!g){const e=o.app.commandLine.getSwitchValue("enable-features");for(const r of["MediaSessionService","HardwareMediaKeyHandling","WebRtcAllowInputVolumeAdjustment"])if(!e.includes(r)){const s=o.app.commandLine.getSwitchValue("disable-features");console.debug("[FEATURE] Disabling '%s'...",r),s===""?o.app.commandLine.appendSwitch("disable-features",r):o.app.commandLine.appendSwitch("disable-features",s+","+r)}}}g&&o.app.disableHardwareAcceleration(),o.app.userAgentFallback=(0,j.getUserAgent)(process.versions.chrome,S.mobile,S.replace);const q=o.app.requestSingleInstanceLock();function G(){if(b)b();else{const t=setInterval(()=>{(0,U.checkVersion)(t).catch(f.commonCatches.print)},18e5);(0,U.checkVersion)(t).catch(f.commonCatches.print);const e=(0,R.default)(B);import("../main/modules/socket.mjs").then(r=>r.default()).catch(f.commonCatches.print),o.app.on("second-instance",()=>{e.isVisible()||e.show(),e.isMinimized()&&e.restore(),e.focus()})}}!q&&!b?o.app.on("ready",()=>{console.log(new x.default().client.log.singleInstance),o.app.quit()}):o.app.on("ready",G);let N=0;o.app.on("web-contents-created",(t,e)=>{const r=e.session===o.session.defaultSession;r||(e.session.setPermissionCheckHandler(()=>!1),e.session.setPermissionRequestHandler((s,n,i)=>i(!1))),e.session.setDevicePermissionHandler(()=>!1),e.on("will-navigate",(s,n)=>{const i=e.getURL();i!==""&&new URL(i).origin!==new URL(n).origin&&s.preventDefault()}),e.on("render-process-gone",(s,n)=>{if(console.error(a.default.bold("[WC_%s:%d]")+" %s",e.getProcessId(),n.exitCode,n.reason),e.reloadIgnoringCache(),!g&&++N>10){console.warn("Crash count exceeded (>10), relaunching in safe mode...");const i=[...process.argv];i.shift(),i.push("--safe-mode"),o.app.relaunch({args:i}),o.app.quit()}}),e.setWindowOpenHandler(s=>{const n=k.appConfig.value.settings;if(!o.app.isReady())return{action:"deny"};const i=new URL(s.url),c=new URL(e.getURL()).origin===i.origin,d={trust:!1,allow:!1};if(h.protocols.secure.includes(i.protocol)&&(d.trust=!0),h.protocols.allowed.includes(i.protocol)&&(d.allow=!0),(d.trust||d.allow)&&!c&&(n.advanced.redirection.warn||d.allow||!r)){const u=o.BrowserWindow.fromWebContents(e),{dialog:p,context:C}=new x.default().client,I={type:"warning",title:p.common.warning+": "+p.externalApp.title,message:p.externalApp.message,buttons:[p.common.no,C.copyURL,p.common.yes],defaultId:0,cancelId:0,detail:p.common.source+`:
`+(0,h.wordWrap)(s.url,Math.round(o.screen.getPrimaryDisplay().bounds.width/16),16),textWidth:320,normalizeAccessKeys:!0};let y;if(u instanceof o.BrowserWindow?y=o.dialog.showMessageBoxSync(u,I):y=o.dialog.showMessageBoxSync(I),y===1&&L.clipboard.writeText(s.url),y<(I.buttons?.length??0)-1)return{action:"deny"}}if(d.trust||d.allow){const u=new URL(s.url),p=o.BrowserWindow.fromWebContents(e);if(u.host===h.knownInstancesList[n.advanced.currentInstance.radio][1].host&&u.pathname==="/popout")return{action:"allow",overrideBrowserWindowOptions:{autoHideMenuBar:!0,...p?{BrowserWindow:p}:{},fullscreenable:!1,webPreferences:{nodeIntegration:!1,sandbox:!0,contextIsolation:!0,webSecurity:!0,enableWebSQL:!1}}};L.shell.openExternal(s.url).catch(f.commonCatches.print)}return{action:"deny"}}),e.once("did-create-window",s=>s.removeMenu()),e.on("did-create-window",s=>{W.styles.load(s.webContents)})}),o.app.on("child-process-gone",(t,e)=>{const r=(e.name??e.type).replace(" ","");let s,n=null;switch(e.reason){case"oom":s="Computer memory seem to be at poor condition.",n="Just let it forget some stuff, I guess?";break;case"launch-failed":s="Process is too lazy to start working!",n="Try to motivate it a little... :/.";break;case"abnormal-exit":s="Process left us unexpectedly!",n=`Rest in peace, ${r}... :(`;break;case"integrity-failure":s="Process was an impostor!";break;default:s=e.reason}e.reason!=="killed"&&e.reason!=="clean-exit"&&l.values.verbose!==!0&&(console.error(a.default.bold("[%s:%d]")+" %s",r,e.exitCode,s),n!==null&&setImmediate(()=>console.error(a.default.bold("[%s:TIP]")+" %s",r,n)))});
