UNPKG

@metricinsights/pp-dev

Version:
3 lines (2 loc) 27 kB
import*as e from"path";import*as t from"fs";import{performance as o}from"node:perf_hooks";import{cac as n}from"cac";import{loadConfigFromFile as i,loadEnv as s,mergeConfig as r,build as a,resolveConfig as l,optimizeDeps as d,preview as c}from"vite";import{g as p,V as f}from"./index-kmS_-y6Z.js";import{c as h,a as m,i as g,M as u,b,d as v,e as w,f as y,g as P,r as T,u as x,h as L}from"./plugin-H4ccpQoX.js";import{URL as $,parse as S}from"url";import*as F from"express";import*as k from"winston";import*as A from"dir-compare";import C from"diff-match-patch";import{isBinaryFile as D}from"isbinaryfile";import*as E from"os";import*as j from"crypto";import z from"extract-zip";import H from"svgtofont";import*as _ from"node:process";import"ejs";import"esbuild";import"http-proxy-middleware";import"picocolors";import"axios";import"jsdom";import"https";import"memory-cache";import"process";import"child_process";import"console";import"zlib";function I(e){return null!==e||void 0!==e}const M=[{key:"r",description:"restart the server",async action(e){await e.restart()}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally((()=>process.exit()))}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}];const N=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class R{oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(t){const{oldAssetsPath:o,newAssetsPath:n,destinationPath:i,changelogTemplate:s,diffFileTemplateHandler:r,diffLineTemplateHandler:a,changelogFilename:l,contextLines:d}=t;if(this.logger=h(),!o||!n||!i)throw new Error("Previous assets path, current assets path and destination path are required");if(o===n)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(n))throw new Error(`Current assets path ${n} does not exist`);if(this.isZipFile(o)){const t=e.resolve(E.tmpdir(),j.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,t).then((()=>this.normalizeAssetFolderPath(t))).then((e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e}))}else{if(!this.isFolder(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(n)){const t=e.resolve(E.tmpdir(),j.createHash("md5").update(n).digest("hex"));this.newAssetsPath=this.unzipFile(n,t).then((()=>this.normalizeAssetFolderPath(t))).then((e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e}))}else{if(!this.isFolder(n))throw new Error(`Invalid current assets path ${n}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(n);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${n} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=i,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",s&&(this.templateIsValid(s)?this.changelogTemplate=s:this.logger.warn(m.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof a&&(this.diffLineTemplateHandler=a),d&&(this.contextLines=d)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return t.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return t.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===t.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){t.existsSync(e)||t.mkdirSync(e,{recursive:!0})}async unzipFile(e,o){return t.rmSync(o,{force:!0,recursive:!0}),z(e,{dir:o})}normalizeAssetFolderPath(o){const n=t.readdirSync(o);return 1===n.length&&t.lstatSync(e.join(o,n[0])).isDirectory()?this.normalizeAssetFolderPath(e.join(o,n[0])):o}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const t=e.filter(((e,t,o)=>0!==e.lineType||(t>=0&&t<this.contextLines||t>o.length-(this.contextLines+1)&&t<=o.length-1||o.slice(t-this.contextLines,t+this.contextLines+1).some((e=>0!==e.lineType))))).map(((e,t,o)=>{if(t>0){const n=o[t-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]})).flat().map((e=>this.diffLineHTML(e))).join("");return this.diffTableTemplate(t)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:t,lineContent:o,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${s=o??"",s.replace(/[\u00A0-\u9999<>&]/g,(e=>"&#"+e.charCodeAt(0)+";"))}</span>\n </td>\n </tr>`;var s}diffLineHTML(e){if(this.diffLineTemplateHandler)return this.diffLineTemplateHandler(e);const{lineNumber:t}=e;return-1===t?this.diffLineSkipTemplate():this.diffLineTemplate(e)}diffFileTemplate(e,t){return this.diffFileTemplateHandler?this.diffFileTemplateHandler(e,t):`<div class="diff-file">\n <div class="diff-file-title">${e}</div>\n <div class="diff-file-content">${t}</div>\n </div>`}async generateAssetFoldersDiff(){this.logger.info(m.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await A.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(N.test(e)&&(e=e.replace(N,"$1$3")),N.test(t)&&(t=t.replace(N,"$1$3")),0===e.localeCompare(t)?0:e.localeCompare(t)>0?1:-1)});return e.diffSet?.filter((e=>"equal"!==e.state||e.name1!==e.name2))||[]}async generateAssetFilesDiff(e,t){const o=new C,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let s=0;return i.map((e=>{const[t,o]=e,n=o.endsWith("\n")?o.split("\n").length-1:o.split("\n").length,i=o.split("\n").map(((e,o)=>({lineContent:e,lineNumber:s+o+1,lineType:t}))).slice(0,n);return-1!==t&&(s+=n),i})).flat()}async generateFilesDiff(o){if("equal"===o.state){const t=this.pathToPosix(e.join(".",o.relativePath,o.name1??"")),n=this.pathToPosix(e.join(".",o.relativePath,o.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${n}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const n=o.path1&&o.name1?e.join(o.path1,o.name1):null,i=o.path2&&o.name2?e.join(o.path2,o.name2):null,s=this.pathToPosix(e.join(".",o.relativePath,(o.name1||o.name2)??""));if("left"===o.state&&n)return this.diffFileTemplate(`<span class="removed">Removed ${s}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===o.state&&i)return this.diffFileTemplate(`<span class="added">Added ${s}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===o.state&&n&&i){const r=this.pathToPosix(e.join(".",o.relativePath,o.name1??"")),a=this.pathToPosix(e.join(".",o.relativePath,o.name2??"")),l=o.name1!==o.name2?`<span class="renamed"\n >Renamed <span class="from">${r}</span> -> <span class="to">${a}</span></span\n >`:s;return this.diffFileTemplate(l,await D(n)||await D(i)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(t.readFileSync(n,"utf-8"),t.readFileSync(i,"utf-8"))))}return""}async generateChangelog(){this.logger.info(m.green("Generating changelog"));const o=await this.generateAssetFoldersDiff(),n=(await Promise.all(o.map((e=>this.generateFilesDiff(e))))).join("");this.logger.info(m.green("Writing changelog file"));const i=this.changelogTemplate.split("%FILES%");i.splice(1,0,n);const s=i.join("");t.writeFileSync(e.join(this.destinationPath,this.changelogFilename),s),this.logger.info(m.green(`Changelog file written to ${e.join(this.destinationPath,this.changelogFilename)}`))}}class U{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await H({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}const O=n("pp-dev");let q=global.__pp_dev_profile_session,G=0;const V=o=>{if(q)return new Promise(((n,i)=>{q.post("Profiler.stop",((s,{profile:r})=>{if(s)i(s);else{const i=e.resolve(`./pp-dev-profile-${G++}.cpuprofile`);t.writeFileSync(i,JSON.stringify(r)),o(m.yellow(`CPU profile written to ${m.white(m.dim(i))}`)),q=void 0,n()}}))}))},W=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function B(e){const t={...e};return delete t["--"],delete t.c,delete t.config,delete t.base,delete t.l,delete t.logLevel,delete t.clearScreen,delete t.d,delete t.debug,delete t.f,delete t.filter,delete t.m,delete t.mode,t}O.option("-c, --config <file>","[string] use specified config file").option("--base <path>","[string] public base path (default: /)").option("-l, --logLevel <level>","[string] info | warn | error | silent").option("--clearScreen","[boolean] allow/disable clear screen when logging").option("-d, --debug [feat]","[string | boolean] show debug logs").option("-f, --filter <filter>","[string] filter debug logs").option("-m, --mode <mode>","[string] set env mode"),O.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action((async(e,t)=>{W(t);const{createServer:n}=await import("vite");try{const a=await i({mode:t.mode||"development",command:"serve"},t.config,e,t.logLevel);let l=await p();const d=s(t.mode||"development",e??_.cwd(),"");if(d&&Object.keys(d).forEach((e=>{e.startsWith("MI_")&&(_.env[e]=d[e])})),a){const{plugins:e,...t}=a.config;l=r(l,t)}const c=await n(r(l,{root:e,base:t.base,mode:t.mode,configFile:t.config,logLevel:t.logLevel,clearScreen:t.clearScreen,optimizeDeps:{force:t.force},server:B(t),customLogger:h(t.logLevel)},!0));if(!c.config.base||"/"===c.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!c.httpServer)throw new Error("HTTP server not available");await c.listen();const g=h(t.logLevel),u=global.__pp_dev_start_time??!1,b=u?m.dim(`ready in ${m.reset(m.bold(Math.ceil(o.now()-u)))} ms`):"";g.info(`\n ${m.green(`${m.bold("PP-DEV")} v${f}`)} ${b}\n`),c.printUrls(),function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=h();t.print&&o.info(m.dim(m.green(" ➜"))+m.dim(" press ")+m.bold("h")+m.dim(" to show help"));const n=(t.customShortcuts??[]).filter(I).concat(M);let i=!1;const s=async t=>{if(""===t||""===t)return void await e.close().finally((()=>process.exit(1)));if(i)return;"h"===t&&o.info(["",m.bold(" Shortcuts"),...n.map((e=>m.dim(" press ")+m.bold(e.key)+m.dim(` to ${e.description}`)))].join("\n"));const s=n.find((e=>e.key===t));s&&(i=!0,await s.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",s).setEncoding("utf8").resume(),e.httpServer.on("close",(()=>{process.stdin.off("data",s).pause()}))}(c,{print:!0,customShortcuts:[q&&{key:"p",description:"start/stop the profiler",async action(e){if(q)await V(g.info);else{const e=await import("node:inspector").then((e=>e.default));await new Promise((t=>{q=new e.Session,q.connect(),q.post("Profiler.enable",(()=>{q?.post("Profiler.start",(()=>{g.info("Profiler started"),t()}))}))}))}}},{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]})}catch(e){const o=h(t.logLevel);o.error(m.red(`error when starting dev server:\n${e.stack}`),{error:e}),V(o.info),_.exit(1)}})),O.command("next [root]","start dev server").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action((async(e,t)=>{W(t);const{default:n}=await import("next"),i=h(),r=function(e="info"){const t=F.default(),o=k.createLogger({level:e,format:k.format.cli({level:!0}),transports:[new k.transports.Console]});t.config={logger:o};const n=t.listen;let i;return t.listen=function(...e){i=n.apply(this,e)},t.printUrls=function(e){if(!i)throw new Error("Server is not listening");const t=e=>m.cyan(e.replace(/:(\d+)\//,((e,t)=>`:${m.bold(t)}/`))),n=i.address();if(n&&"object"==typeof n)if("::"===n.address){const i=new $(e||"",`http://localhost:${n.port}`);o.info(` ${m.green("➜")} ${m.bold("Local")}: ${t(i.toString())}`)}else{const i=new $(e||"",`http://[${n.address}]:${n.port}`);o.info(` ${m.green("➜")} ${m.bold("Local")}: ${t(i.toString())}`)}},t}(t.logLevel),a=B(t),l=s(t.mode||"development",e??_.cwd(),"");l&&Object.keys(l).forEach((e=>{e.startsWith("MI_")&&(_.env[e]=l[e])}));const d=n({dev:!0,hostname:a.host,port:a.port});await d.prepare();const c=await d.getServer();let p=c.nextConfig.basePath;const{assetPrefix:A}=c.nextConfig;if(p.endsWith("/")||(p+="/"),"/"===p)throw new Error('basePath cannot be equal to "/" or empty string');const C=p.substring(0,p.lastIndexOf("/")),D=c.nextConfig.serverRuntimeConfig.templateName,E=c.nextConfig.serverRuntimeConfig.ppDevConfig,{backendBaseURL:j,portalPageId:z,appId:H,templateLess:I=!0,enableProxyCache:M=!0,miHudLess:N=!0,proxyCacheTTL:R=6e5,disableSSLValidation:U=!1,v7Features:O=!1,personalAccessToken:q=_.env.MI_ACCESS_TOKEN}=E,G=H??z;if(r.use(g(p,D)),j){let e;try{e=new URL(j).host}catch(e){i.error(m.red(`Invalid backendBaseURL: ${j}`)),_.exit(1)}const t=new u(j,{headers:{host:e,referer:j,origin:j.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},portalPageId:G,templateLess:I,disableSSLValidation:U,v7Features:O,personalAccessToken:q});if(M){let e=+R;(!e||Number.isNaN(e)||e<0)&&(e=6e5),r.use(b({devServer:r,ttl:e}))}const o=["/@vite","/@metricinsights","/@",C];A&&o.push(A),r.use(v({devServer:r,baseURL:j,proxyIgnore:o,disableSSLValidation:U,miAPI:t}));const n=new RegExp(`^((${p})|/)$`);r.use(w(n,t,E)),r.use(y((e=>n.test(L(e))),((o,n)=>Buffer.from(x(e,n.headers.host??"",t.buildPage(o,N)))))),P.post("/@api/login",(async(e,o,n)=>{const{token:s,tokenType:r}=e.body;if(!s)return void o.status(400).json({error:"Token is required"}).end();const a=e=>(i.error(e),n(e),null);if("personal"===r){if(!await t.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${s}`},!0).then((async e=>{if("number"==typeof e.data?.user?.user_id)return t.personalAccessToken=s,e;o.status(400).json({error:"Token expired or invalid"}).end()})).catch(a))return;T(o,"/",302)}else if("regular"===r){if(!await t.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:s},!0).then((e=>{if(e.data?.users?.length)return t.personalAccessToken=void 0,o.setHeader("set-cookie",e.headers["set-cookie"]??""),e;o.status(400).json({error:"Token expired or invalid"}).end()})).catch(a))return;T(o,"/",302)}})),r.use(P)}const Z=d.getRequestHandler();r.all("*",((e,t)=>{try{if(e.url?.startsWith(A)&&A!==C){const o=e.url.replace(A,C),n=S(o,!0);return n.pathname?Z(e,t,n):(t.statusCode=400,void t.end("Invalid URL"))}const o=S(e.url||"/",!0);if(!o.pathname)return t.statusCode=400,void t.end("Invalid URL");Z(e,t,o)}catch(e){const o=e instanceof Error?e.message:"Unknown error";i.error(m.red(`Error handling request: ${o}`)),t.statusCode=500,t.end("Internal Server Error")}}));try{await new Promise((e=>{a.host?e(r.listen(a.port,a.host,(()=>{}))):e(r.listen(a.port,(()=>{})))}));const e=global.__pp_dev_start_time??!1,t=e?m.dim(`ready in ${m.reset(m.bold(Math.ceil(o.now()-e)))} ms`):"";i.info(`\n ${m.green(`${m.bold("PP-DEV")} v${f}`)} ${t}\n`,{clear:!0}),r.printUrls(p)}catch(e){const o=h(t.logLevel);o.error(m.red(`error when starting dev server:\n${e.stack}`),{error:e}),V(o.info),_.exit(1)}})),O.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").action((async(o,n)=>{W(n);const s=B(n);try{const l=await i({mode:n.mode||"production",command:"build"},n.config,o,n.logLevel);let d=await p();if(l){const{plugins:e,...t}=l.config;d=r(d,t)}const c=r(d,{root:o,base:n.base,mode:n.mode,configFile:n.config,logLevel:n.logLevel,clearScreen:n.clearScreen,optimizeDeps:{force:n.force},build:s},!0);if(await a(c),s.changelog){const i=o||_.cwd(),r=c.build?.outDir||"dist";let a="";if("string"==typeof s.changelog)a=e.resolve(i,s.changelog);else{const o=e.resolve(i,c.ppDevConfig?.syncBackupsDir||"backups");if(!t.existsSync(o))return void h(n.logLevel).warn(m.yellow("backups directory not found, skipping changelog generation"));const s=t.readdirSync(o,{withFileTypes:!0});if(!s.length)return void h(n.logLevel).warn(m.yellow("no backups found, skipping changelog generation"));const r=s.filter((e=>e.isFile()&&e.name.endsWith(".zip"))).reduce(((n,i)=>t.statSync(e.resolve(o,n.name)).mtimeMs>t.statSync(e.resolve(o,i.name)).mtimeMs?n:i),s[0]).name;a=e.resolve(o,r)}const l=e.resolve(i,r);let d="dist-zip";c.ppDevConfig&&(!1===c.ppDevConfig.distZip?d=c.build?.outDir||"dist":"object"==typeof c.ppDevConfig.distZip&&"string"==typeof c.ppDevConfig.distZip.outDir&&(d=c.ppDevConfig.distZip.outDir));const p=new R({oldAssetsPath:a,newAssetsPath:l,destinationPath:e.resolve(i,d)});await p.generateChangelog()}}catch(e){h(n.logLevel).error(m.red(`error during build:\n${e.stack}`),{error:e}),_.exit(1)}finally{V((e=>h(n.logLevel).info(e)))}})),O.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action((async(t,o,n)=>{W(n);const{oldAssetsPath:i=t,newAssetsPath:s=o,destination:r=".",filename:a="CHANGELOG.html",logLevel:l}=n,d=_.cwd();i&&s||(h(l).error(m.red("error during changelog generation: oldAssetPath and newAssetPath are required")),_.exit(1));const c=e.resolve(d,i),p=e.resolve(d,s),f=e.resolve(d,r),g=new R({oldAssetsPath:c,newAssetsPath:p,destinationPath:f,changelogFilename:a});await g.generateChangelog()})),O.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action((async(t,o,n)=>{W(n);const{source:i=t,destination:s=o,fontName:r="icon-font"}=n,a=_.cwd(),l=e.resolve(a,i),d=e.resolve(a,s),c=new U({sourceDir:l,outputDir:d,fontName:r}),p=h(n.logLevel);p.info(`Generating icon font from SVG files in ${m.dim(l)}`),await c.generate(),p.info(`Icon font generated and saved to ${m.dim(d)}`)})),O.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action((async(e,t)=>{W(t);try{const o=await i({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await p();if(o){const{plugins:e,...t}=o.config;n=r(n,t)}const s=await l(r(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode}),"serve");await d(s,t.force,!0)}catch(e){h(t.logLevel).error(m.red(`error when optimizing deps:\n${e.stack}`),{error:e}),_.exit(1)}})),O.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action((async(e,t)=>{W(t);try{const o=await i({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await p();if(o){const{plugins:e,...t}=o.config;n=r(n,t)}(await c(r(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode,build:{outDir:t.outDir},preview:{port:t.port,strictPort:t.strictPort,host:t.host,https:t.https,open:t.open}}))).printUrls()}catch(e){h(t.logLevel).error(m.red(`error when starting preview server:\n${e.stack}`),{error:e}),_.exit(1)}finally{V((e=>h(t.logLevel).info(e)))}})),O.help(),O.version(f),O.parse();export{V as stopProfiler}; //# sourceMappingURL=cli.js.map