@metricinsights/pp-dev 1.5.0-beta.3 → 1.5.0-beta.31
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/README.md +200 -145
- package/dist/cjs/auth.provider-fI0tFsf5.js +2 -0
- package/dist/cjs/auth.provider-fI0tFsf5.js.map +1 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/cli.js.map +1 -1
- package/dist/cjs/index-Ty1d2YCg.js +2 -0
- package/dist/cjs/index-Ty1d2YCg.js.map +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/migrate-Gi9k9cLw.js +2 -0
- package/dist/cjs/migrate-Gi9k9cLw.js.map +1 -0
- package/dist/cjs/package.json +2 -135
- package/dist/cjs/plugin.js +1 -1
- package/dist/cjs/plugin.js.map +1 -1
- package/dist/cjs/request-capture.middleware-6DhFLyIz.js +2 -0
- package/dist/cjs/request-capture.middleware-6DhFLyIz.js.map +1 -0
- package/dist/cjs/version-manifest-CVBuIKBS.js +2 -0
- package/dist/cjs/version-manifest-CVBuIKBS.js.map +1 -0
- package/dist/cjs/version-plugin-DBdqn2Rn.js +2 -0
- package/dist/cjs/version-plugin-DBdqn2Rn.js.map +1 -0
- package/dist/client/client.js +278 -126
- package/dist/client/client.js.map +1 -1
- package/dist/client/request-inspector.css +3 -0
- package/dist/client/request-inspector.css.map +1 -0
- package/dist/client/request-inspector.html +87 -0
- package/dist/client/request-inspector.js +549 -0
- package/dist/client/request-inspector.js.map +1 -0
- package/dist/client/variables-editor.css +3 -0
- package/dist/client/variables-editor.css.map +1 -0
- package/dist/client/variables-editor.html +44 -0
- package/dist/client/variables-editor.js +3474 -0
- package/dist/client/variables-editor.js.map +1 -0
- package/dist/esm/auth.provider-DDUsu1H1.js +2 -0
- package/dist/esm/auth.provider-DDUsu1H1.js.map +1 -0
- package/dist/esm/cli.js +1 -1
- package/dist/esm/cli.js.map +1 -1
- package/dist/esm/index-tD-QICGk.js +2 -0
- package/dist/esm/index-tD-QICGk.js.map +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/migrate-CCBRuVfj.js +2 -0
- package/dist/esm/{migrate-B2gJ62fm.js.map → migrate-CCBRuVfj.js.map} +1 -1
- package/dist/esm/package.json +2 -135
- package/dist/esm/plugin.js +1 -1
- package/dist/esm/plugin.js.map +1 -1
- package/dist/esm/request-capture.middleware-VElwjU1W.js +2 -0
- package/dist/esm/request-capture.middleware-VElwjU1W.js.map +1 -0
- package/dist/esm/version-manifest-CyzmnFOe.js +2 -0
- package/dist/esm/version-manifest-CyzmnFOe.js.map +1 -0
- package/dist/esm/version-plugin-6rxIgQ-I.js +2 -0
- package/dist/esm/version-plugin-6rxIgQ-I.js.map +1 -0
- package/dist/types/helpers.d.ts +29 -0
- package/dist/types/index.d.ts +15 -156
- package/dist/types/plugin.d.ts +8 -0
- package/dist/types/pp-dev-config-D889A-PO.d.ts +189 -0
- package/docs/features.md +2 -1
- package/package.json +26 -35
- package/dist/CHANGELOG.md +0 -442
- package/dist/README.md +0 -724
- package/dist/cjs/index-CCUrjlJE.js +0 -2
- package/dist/cjs/index-CCUrjlJE.js.map +0 -1
- package/dist/cjs/migrate-BYno__sx.js +0 -2
- package/dist/cjs/migrate-BYno__sx.js.map +0 -1
- package/dist/cjs/plugin-D_RXI7ru.js +0 -2
- package/dist/cjs/plugin-D_RXI7ru.js.map +0 -1
- package/dist/cjs/version-plugin-Bf4jLh17.js +0 -2
- package/dist/cjs/version-plugin-Bf4jLh17.js.map +0 -1
- package/dist/esm/index-BazQY12s.js +0 -2
- package/dist/esm/index-BazQY12s.js.map +0 -1
- package/dist/esm/migrate-B2gJ62fm.js +0 -2
- package/dist/esm/plugin-NIWxLreC.js +0 -2
- package/dist/esm/plugin-NIWxLreC.js.map +0 -1
- package/dist/esm/version-plugin-DwuZCHob.js +0 -2
- package/dist/esm/version-plugin-DwuZCHob.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readFileSync as e,existsSync as t}from"fs";import{resolve as i}from"path";import{fileURLToPath as s}from"url";import{createColors as r}from"picocolors";import n from"node:path";import{isIP as o}from"node:net";import{createLogger as a}from"vite";const d=i("undefined"!=typeof __filename&&__filename||s(import.meta.url),"../../.."),p=i("undefined"!=typeof __filename&&__filename||s(import.meta.url),"../.."),l=t(i(d,"package.json"))?d:p,c=i(l,"dist/client/client.js"),{version:u,name:m}=JSON.parse(e(i(l,"package.json")).toString()),f=u,h=m,v="/p",g="/pt",w="/pl",b="PP_DEV_NEXT_BUILD",y="PP_DEV_NEXT_BUILD_DIST_DIR",E=[".pp-dev.config.js",".pp-dev.config.cjs",".pp-dev.config.mjs",".pp-dev.config.ts",".pp-dev.config.cts",".pp-dev.config.mts",".pp-dev.config.json","pp-dev.config.js","pp-dev.config.cjs","pp-dev.config.mjs","pp-dev.config.ts","pp-dev.config.cts","pp-dev.config.mts","pp-dev.config.json"],_="info";let S,k;function L(){return S??={level:_,logger:a(_)},S.logger}function D(e){return void 0!==e&&e!==S?.level&&(S={level:e,logger:a(e)}),k??={info:(e,t)=>L().info(e,t),warn:(e,t)=>L().warn(e,t),warnOnce:(e,t)=>L().warnOnce(e,t),error:(e,t)=>L().error(e,t),clearScreen:e=>L().clearScreen(e),hasErrorLogged:e=>L().hasErrorLogged(e),get hasWarned(){return L().hasWarned},set hasWarned(e){L().hasWarned=e}},k}const A=r();function N(e,t){if(!e||e.includes("\0")||n.posix.isAbsolute(e)||n.win32.isAbsolute(e)||n.win32.parse(e).root)throw new Error(`[pp-dev] ${t} must be a relative path inside its output directory.`);const i=n.posix.normalize(e.replace(/\\/g,"/"));if("."===i||".."===i||i.startsWith("../"))throw new Error(`[pp-dev] ${t} must stay inside its output directory.`);return i}function P(e){return N(`${e.replace(/^@/,"").replace(/[\\/]+/g,"-")}.zip`,"default ZIP output file name")}function T(e,t,i){return n.resolve(e,i||t)}function $(e,t,i){const s=N(t,i),r=n.resolve(e),o=n.resolve(r,...s.split("/")),a=n.relative(r,o);if(".."===a||a.startsWith(`..${n.sep}`)||n.isAbsolute(a))throw new Error(`[pp-dev] ${i} must resolve inside its output directory.`);return o}const j=["top-left","top-right","bottom-left","bottom-right"],O=2147483647;function R(e,t){const i=e.mi?.mode??"standalone",s=e.app?.type??"template",r=e.mi?.apiVersion??7,n=e.mi?.url??process.env.MI_BACKEND_URL;if(!(e.app?.name??t))throw new Error("[pp-dev] app.name is required (or set package.json#name)");const o=e.sync?.maxBackups;if(void 0!==o&&!1!==o&&!(Number.isInteger(o)&&o>=0))throw new Error(`[pp-dev] sync.maxBackups must be a whole number ≥ 0 or false (0 and false keep every backup), got ${JSON.stringify(o)}`);const a=e.sync?.buildTimeoutMs;if(void 0!==a&&!(Number.isInteger(a)&&a>0&&a<=O))throw new Error(`[pp-dev] sync.buildTimeoutMs must be a whole number of milliseconds between 1 and 2147483647, got ${JSON.stringify(a)}`);if(e.mi?.include&&"standalone"!==i)throw console.warn('[pp-dev] mi.include is only valid when mi.mode is "standalone"'),new Error('[pp-dev] mi.include requires mi.mode to be "standalone"');if(!n){if("embedding"===i||"template"===s)throw new Error('[pp-dev] mi.url is required when mi.mode is "embedding" or app.type is "template"');"standalone"===i&&"page"===s&&console.warn("[pp-dev] mi.url is not set — dev server will run without a backend proxy")}if("template"===s&&!e.app?.id)throw new Error('[pp-dev] app.id is required when app.type is "template"');if("page"===s&&n&&("standalone"===i||r>=7)&&!e.app?.id)throw new Error('[pp-dev] app.id is required when backend page data is loaded for app.type "page"');if(void 0!==e.devPanel?.position&&!j.includes(e.devPanel.position))throw new Error(`[pp-dev] devPanel.position must be one of: ${j.join(", ")}`);const d=e.server?.allowedHosts;if(!(void 0===d||!0===d||Array.isArray(d)&&d.every(e=>"string"==typeof e&&""!==e.trim())))throw new Error(`[pp-dev] server.allowedHosts must be a list of host names or true, got ${JSON.stringify(d)}`)}function x(e,t){const{mi:i={},app:s={},proxy:r={},build:n={},sync:o={},inspector:a={},devPanel:d={},users:p={},server:l={}}=e,c=i.mode??"standalone",u=s.type??"template",m=i.apiVersion??7,f="standalone"===c;let h=!1;"top-bar"===i.include?h=!0:"shared-components"===i.include&&(h={addSharedComponentsScripts:!0,addRootElement:!1});const v="page"===u,g=s.name??t;if(!g)throw new Error("[pp-dev] app.name is required (or set package.json#name)");const w="VERSION-v{packageversion}-{currentDate}.json";let b;const y=n.zip;let E;b=!1!==y&&(!0===y||void 0===y?{outFileName:P(g),outDir:"dist-zip"}:{outFileName:N(y.fileName??P(g),"build.zip.fileName"),outDir:y.outDir??"dist-zip",...y.inDir?{inDir:y.inDir}:{}});const _=n.versionFile;let S;E=!1!==_&&(!0===_||void 0===_?{versionFileTemplate:w,enabled:!0}:{versionFileTemplate:N(_.fileNameTemplate??w,"build.versionFile.fileNameTemplate"),enabled:_.enabled??!0});const k=n.imageOptimisations;return S=!1!==k&&(!0===k||void 0===k?{}:k),{templateName:g,backendBaseURL:i.url??process.env.MI_BACKEND_URL,appId:s.id,templateLess:v,miHudLess:f,integrateMiTopBar:h,enableProxyCache:r.cache??!0,proxyCacheTTL:r.cacheTtl??6e5,disableSSLValidation:r.tls?.allowSelfSigned??!1,imageOptimizer:S,outDir:n.outDir??"dist",distZip:b,versionPlugin:E,syncBackupsDir:o.backupsDir??"backups",syncMaxBackups:o.maxBackups,syncBuildTimeoutMs:o.buildTimeoutMs,v7Features:m>=7,personalAccessToken:i.token??process.env.MI_ACCESS_TOKEN,inspectorEnabled:a.enabled??!0,inspectorMaxMemory:a.maxMemory??1073741824,inspectorCaptureLimit:a.captureLimit??10485760,devPanelPosition:d.position??"bottom-right",devPanelHidden:d.hidden??!1,devPanelAutoHide:d.autoHide??!1,persistUsers:p.persist??!1,allowedHosts:!0===l.allowedHosts||(l.allowedHosts??[]).map(e=>e.trim().toLowerCase())}}const B=Object.freeze({__proto__:null,normalizePPDevConfig:x,validatePPDevConfig:R}),C=new Set(["GET","HEAD","OPTIONS"]);function I(e,t){if(void 0===e||!0===t)return!0;const i=function(e){const t=e.trim().toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");return e>0&&6===o(t.slice(1,e))?{ip:!0}:void 0}const i=t.replace(/:\d*$/,"");if(i&&!i.includes(":"))return 4===o(i)?{ip:!0}:{hostname:i}}(e);if(void 0===i)return!1;if("ip"in i)return!0;const{hostname:s}=i;return"localhost"===s||s.endsWith(".localhost")||function(e,t){return t.some(t=>t===e||t.startsWith(".")&&(t.slice(1)===e||e.endsWith(t)))}(s,t)}function H(e){const t=JSON.stringify((e??"").replace(/:\d*$/,""));return`Blocked by pp-dev: this host (${t}) is not allowed. To allow it, add ${t} to server.allowedHosts in the pp-dev config.`}function M(e){return!0===e?[]:e.filter(e=>!e.startsWith("."))}function W(e,t=[]){const i=e.headers.origin,s=e.headers.host;if("string"==typeof i){if("null"===i)return'Origin "null" (a sandboxed or file:// page)';let e;try{e=new URL(i)}catch{return`unreadable Origin "${i}"`}if("localhost"===(r=e.hostname)||r.endsWith(".localhost")||"[::1]"===r||/^127(?:\.\d{1,3}){3}$/.test(r)||M(t).includes(e.hostname))return null;const n=s?function(e,t){try{return new URL(`${e}//${t}`).host}catch{return}}(e.protocol,s):void 0;return n&&e.host===n?null:`Origin ${e.origin} is neither this dev server (${s??"no Host"}) nor this machine`}var r;const n=e.headers["sec-fetch-site"];return C.has((e.method??"GET").toUpperCase())||"cross-site"!==n?null:"sent from a cross-site page"}function z(e=[]){return(t,i,s)=>{const r=W(t,e);r?i.status(403).json({error:`Blocked by pp-dev: ${r}.`}):s()}}class U{state={isAuthenticated:!1,isRedirected:!1};listeners=new Set;getState(){return{...this.state}}isAuthenticated(){return this.state.isAuthenticated}isRedirected(){return this.state.isRedirected}setAuthenticated(e){this.state.isAuthenticated=e,this.notifyListeners()}setRedirected(e){this.state.isRedirected=e,this.notifyListeners()}updateState(e){void 0!==e.isAuthenticated&&(this.state.isAuthenticated=e.isAuthenticated),void 0!==e.isRedirected&&(this.state.isRedirected=e.isRedirected),this.notifyListeners()}reset(){this.state={isAuthenticated:!1,isRedirected:!1},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{try{e(this.getState())}catch(e){D().error(`Error in auth state listener: ${e instanceof Error?e.stack??e.message:String(e)}`)}})}}const q=new U;export{U as A,E as P,f as V,A as a,W as b,D as c,v as d,w as e,g as f,b as g,H as h,I as i,P as j,$ as k,h as l,c as m,x as n,l as o,N as p,M as q,T as r,y as s,q as t,z as u,R as v,B as w};
|
|
2
|
+
//# sourceMappingURL=auth.provider-DDUsu1H1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.provider-DDUsu1H1.js","sources":["../../../src/constants.ts","../../../src/lib/logger.ts","../../../src/lib/helpers/color.helper.ts","../../../src/lib/output-path.ts","../../../src/lib/pp-dev-config.ts","../../../src/lib/helpers/origin-guard.ts","../../../src/lib/auth.provider.ts"],"sourcesContent":[null,null,null,null,null,null,null],"names":["afterBundlePath","resolve","__filename","fileURLToPath","url","beforeBundlePath","PP_DEV_PACKAGE_DIR","existsSync","PP_DEV_CLIENT_ENTRY","version","name","JSON","parse","readFileSync","toString","VERSION","PACKAGE_NAME","PATH_PAGE_PREFIX","PATH_TEMPLATE_PREFIX","PATH_TEMPLATE_LOCAL_PREFIX","PP_DEV_NEXT_BUILD_ENV_VAR","PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR","PP_DEV_CONFIG_NAMES","DEFAULT_LEVEL","current","shared","active","level","logger","createViteLogger","createLogger","undefined","info","msg","options","warn","warnOnce","error","clearScreen","type","hasErrorLogged","hasWarned","value","colors","createColors","normalizeRelativeOutputPath","relativePath","optionName","includes","path","posix","isAbsolute","win32","root","Error","normalized","normalize","replace","startsWith","createDefaultZipFileName","appName","resolveZipSourceDir","projectRoot","outDir","inDir","resolveOutputFilePath","directory","fileName","safeRelativePath","resolvedDirectory","resolvedFile","split","relativeToDirectory","relative","sep","DEV_PANEL_POSITIONS","MAX_TIMER_DELAY_MS","validatePPDevConfig","config","templateName","miMode","mi","mode","appType","app","apiVersion","miUrl","process","env","MI_BACKEND_URL","maxBackups","sync","Number","isInteger","stringify","buildTimeoutMs","include","console","id","devPanel","position","join","allowedHosts","server","Array","isArray","every","host","trim","normalizePPDevConfig","proxy","build","inspector","users","miHudLess","integrateMiTopBar","addSharedComponentsScripts","addRootElement","templateLess","resolvedName","defaultVersionFileTemplate","distZip","zipCfg","zip","versionPlugin","outFileName","vfCfg","versionFile","imageOptimizer","versionFileTemplate","enabled","fileNameTemplate","imgCfg","imageOptimisations","backendBaseURL","appId","enableProxyCache","cache","proxyCacheTTL","cacheTtl","disableSSLValidation","tls","allowSelfSigned","syncBackupsDir","backupsDir","syncMaxBackups","syncBuildTimeoutMs","v7Features","personalAccessToken","token","MI_ACCESS_TOKEN","inspectorEnabled","inspectorMaxMemory","maxMemory","inspectorCaptureLimit","captureLimit","devPanelPosition","devPanelHidden","hidden","devPanelAutoHide","autoHide","persistUsers","persist","map","toLowerCase","SAFE_METHODS","Set","isHostAllowed","named","trimmed","end","indexOf","isIP","slice","ip","hostname","readHostHeader","endsWith","some","allowed","matchesAllowedHost","hostNotAllowedMessage","exactAllowedHosts","filter","crossOriginReason","req","origin","headers","originUrl","URL","test","requestHost","scheme","normalizeHost","protocol","fetchSite","has","method","toUpperCase","createOriginGuard","res","next","reason","status","json","AuthProvider","state","isAuthenticated","isRedirected","listeners","getState","this","setAuthenticated","authenticated","notifyListeners","setRedirected","redirected","updateState","updates","reset","subscribe","listener","add","delete","forEach","stack","message","String","authProvider"],"mappings":"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"}
|
package/dist/esm/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as e from"path";import*as t from"fs";import{EventEmitter as o}from"node:events";import{performance as n}from"node:perf_hooks";import{watch as i}from"chokidar";import{cac as s}from"cac";import{c as r,a,e as l,P as c,b as d,n as p,d as f,r as u,f as g,w as h,g as m,z as b,V as w,I as v,v as y,h as P,i as x,j as S,R as T,k,l as E,m as L,o as $,M as I,p as F,q as D,s as j,t as _,u as A,x as N,y as C,D as R,C as M,A as O,B as z,E as U,F as H}from"./plugin-NIWxLreC.js";import{r as V,l as W,g as Z,s as G,a as B,b as q,c as J,i as K}from"./index-BazQY12s.js";import{loadConfigFromFile as Y,mergeConfig as X,build as Q,resolveConfig as ee,optimizeDeps as te,preview as oe}from"vite";import{parse as ne}from"url";import*as ie from"dir-compare";import se from"diff-match-patch";import{isBinaryFile as re}from"isbinaryfile";import*as ae from"os";import*as le from"crypto";import ce from"svgtofont";import{WebSocketServer as de,WebSocket as pe}from"ws";import"http-proxy-middleware";import"picocolors";import"node:string_decoder";import"axios";import"node:http";import"node:https";import"jsdom";import"process";import"child_process";import"node:path";import"jszip";import"module";import"zlib";import"express";import"node:crypto";import"node:fs";import"node:os";import"./helpers.js";import"ejs";function fe(e){return null!=e&&!1!==e}let ue=null;const ge=[{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 he=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class me{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:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n 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:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n 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:l,diffLineTemplateHandler:c,changelogFilename:d,contextLines:p}=t;if(this.logger=r(),!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(ae.tmpdir(),le.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(ae.tmpdir(),le.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=d||"CHANGELOG.html",s&&(this.templateIsValid(s)?this.changelogTemplate=s:this.logger.warn(a.yellow("Invalid changelog template, using default"))),"function"==typeof l&&(this.diffFileTemplateHandler=l),"function"==typeof c&&(this.diffLineTemplateHandler=c),p&&(this.contextLines=p)}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){t.rmSync(o,{force:!0,recursive:!0}),await l(e,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(a.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await ie.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(he.test(e)&&(e=e.replace(he,"$1$3")),he.test(t)&&(t=t.replace(he,"$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 se,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 re(n)||await re(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(a.green("Generating changelog"));const o=await this.generateAssetFoldersDiff(),n=(await Promise.all(o.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(a.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(a.green(`Changelog file written to ${e.join(this.destinationPath,this.changelogFilename)}`))}}class be{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await ce({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class we{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new de({noServer:!0}),this.wss.on("connection",e=>this.onConnection(e)),this.wss.on("error",e=>this.fireLifecycle("error",e)),this.ws={on:(e,t)=>{"close"!==e&&"error"!==e?this.getEventSet(e).add(t):this.getLifecycleSet(e).add(t)},off:(e,t)=>{this.eventListeners.get(e)?.delete(t),"close"!==e&&"error"!==e||this.lifecycleListeners.get(e)?.delete(t)},send:(e,t)=>{if("string"==typeof e)for(const o of this.clients.keys())this.sendToSocket(o,e,t);else{const t=JSON.stringify(e);for(const e of this.clients.keys())e.readyState===pe.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===c&&(this.wss.handleUpgrade(e,t,o,t=>{this.wss.emit("connection",t,e)}),!0)}async close(){this.fireLifecycle("close");for(const e of this.clients.keys())e.terminate();this.clients.clear(),await new Promise(e=>this.wss.close(()=>e()))}onConnection(e){const t={send:(t,o)=>this.sendToSocket(e,t,o)};this.clients.set(e,t),e.on("message",e=>this.onMessage(t,e)),e.on("close",()=>this.clients.delete(e)),e.on("error",()=>{})}onMessage(e,t){let o;try{o=JSON.parse(t.toString())}catch{return}if(!o||"custom"!==o.type||"string"!=typeof o.event)return;const n=this.eventListeners.get(o.event);if(n)for(const t of n)try{t(o.data,e)}catch(e){r().error(`ws handler for "${o.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===pe.OPEN&&e.send(JSON.stringify({type:"custom",event:t,data:o}))}fireLifecycle(e,t){for(const o of this.lifecycleListeners.get(e)??[])try{o(t)}catch{}}getEventSet(e){let t=this.eventListeners.get(e);return t||(t=new Set,this.eventListeners.set(e,t)),t}getLifecycleSet(e){let t=this.lifecycleListeners.get(e);return t||(t=new Set,this.lifecycleListeners.set(e,t)),t}}const ve=s("pp-dev");function ye(t,o,n){const s=[...H,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"].map(o=>e.join(t,o)),r=i(s,{ignored:t=>{const o=e.basename(t);return/(^|[\/\\])\../.test(t)&&!o.startsWith(".env")&&!o.startsWith(".pp-dev")&&!o.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let l=null;return r.on("change",i=>{n(a.blue(`🔧 Config file changed: ${e.relative(t,i)}`)),l&&clearTimeout(l),l=setTimeout(async()=>{try{n(a.yellow("🔄 Restarting dev server due to config change...")),await o()}catch(e){n(a.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{n(a.red(`❌ Config watcher error: ${e}`))}),{watcher:r,restartCallback:o,logger:n}}function Pe(e){e.watcher&&e.watcher.close()}function xe(e){if(!e||"object"!=typeof e||!("message"in e))return!1;const t=String(e.message);return/Turbopack is not supported/i.test(t)||/native bindings are not available/i.test(t)||/Only WebAssembly \(WASM\) bindings were loaded/i.test(t)}async function Se(o){const{changelog:n,executionRoot:i,newAssetsPath:s,backupsDirPath:l,changelogDestinationPath:c,logLevel:d}=o;let p;if("string"==typeof n)p=e.resolve(i,n);else{if(!t.existsSync(l))return void r(d).warn(a.yellow("backups directory not found, skipping changelog generation"));const o=t.readdirSync(l,{withFileTypes:!0});if(!o.length)return void r(d).warn(a.yellow("no backups found, skipping changelog generation"));const n=o.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!n.length)return void r(d).warn(a.yellow("no ZIP backups found, skipping changelog generation"));const i=n.reduce((o,n)=>t.statSync(e.resolve(l,o.name)).mtimeMs>t.statSync(e.resolve(l,n.name)).mtimeMs?o:n).name;p=e.resolve(l,i)}const f=new me({oldAssetsPath:p,newAssetsPath:s,destinationPath:c});await f.generateChangelog()}let Te=global.__pp_dev_profile_session,ke=0;const Ee=o=>{if(Te)return new Promise((n,i)=>{Te.post("Profiler.stop",(s,{profile:r})=>{if(s)i(s);else{const i=e.resolve(`./pp-dev-profile-${ke++}.cpuprofile`);t.writeFileSync(i,JSON.stringify(r)),o(a.yellow(`CPU profile written to ${a.white(a.dim(i))}`)),Te=void 0,n()}})})},Le=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function $e(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}ve.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"),ve.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(t,o)=>{Le(o);let i=null,s=null,l=!1;const c=t?e.resolve(process.cwd(),t):process.cwd(),d=r(o.logLevel),p=async()=>{if(!l){l=!0;try{i&&(d.info(a.yellow("🛑 Stopping existing dev server...")),await i.close(),i=null);const{clearConfigCache:f,getConfig:u}=await import("./index-BazQY12s.js").then(e=>e.h);f();const{createServer:g}=await(import("vite")),h=o.mode||"development",m=e.resolve(process.cwd(),t??".");W(h,m);const b=await Y({mode:h,command:"serve"},o.config,t,o.logLevel);let y=await Z(void 0,{mode:h,root:m});if(b){const{plugins:e,...t}=b.config;y=X(y,t)}if(i=await g(X(y,{root:t,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:$e(o),customLogger:d},!0)),!i.config.base||"/"===i.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!i.httpServer)throw new Error("HTTP server not available");await i.listen();const P=global.__pp_dev_start_time??!1,x=P?a.dim(`ready in ${a.reset(a.bold(Math.ceil(n.now()-P)))} ms`):"";d.info(`\n ${a.green(`${a.bold("PP-DEV")} v${w}`)} ${x}\n`),i.printUrls();const S=await u(m);if(!1!==S.inspector?.enabled){const e=i.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${i.config.server.port??5173}`;d.info(`\n ${a.cyan("🔍 Request Inspector")} ${a.dim(t+v)}\n`)}!function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=r();t.print&&o.info(a.dim(a.green(" ➜"))+a.dim(" press ")+a.bold("h")+a.dim(" to show help"));const n=(t.customShortcuts??[]).filter(fe).concat(ge);ue?.(),ue=null;let i=!1;const s=process.stdin.isPaused(),l=process.stdin,c=Boolean(l.isRaw),d=async t=>{if(""===t)return void process.kill(process.pid,"SIGINT");if(""===t)return void await e.close().finally(()=>process.exit(0));if(i)return;"h"===t&&o.info(["",a.bold(" Shortcuts"),...n.map(e=>a.dim(" press ")+a.bold(e.key)+a.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",d).setEncoding("utf8").resume();const p=e.httpServer,f=()=>{ue===f&&(p.removeListener("close",f),process.stdin.off("data",d),c||process.stdin.setRawMode(!1),s&&process.stdin.pause(),ue=null)};ue=f,p.on("close",f)}(i,{print:!0,customShortcuts:[...Te?[{key:"p",description:"start/stop the profiler",async action(e){if(Te)await Ee(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{Te=new e.Session,Te.connect(),Te.post("Profiler.enable",()=>{Te?.post("Profiler.start",()=>{d.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("/")}`}})}}]}),s||(s=ye(c,p,d.info),d.info(a.blue("🔧 Config file watcher started"))),l=!1}catch(e){l=!1,d.error(a.red(`error when starting dev server:\n${e.stack}`),{error:e}),Ee(d.info),process.exit(1)}}},f=async e=>{d.info(a.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{s&&(Pe(s),s=null),i&&(await i.close(),i=null),Ee(d.info),d.info(a.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(a.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),process.on("uncaughtException",e=>{d.error(a.red(`❌ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(a.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),f("unhandledRejection")}),await p()}),ve.command("next [root]","start Next.js development server with pp-dev integration").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").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(n,i)=>{Le(i);let s=null,l=null,c=null,f=null,u=!1;const g=r(),h=async()=>{if(!u){u=!0;try{const{next:m,constants:b}=await G(),{PHASE_DEVELOPMENT_SERVER:w}=b;c&&(await c.close(),c=null),l&&(g.info(a.yellow("🛑 Stopping existing Next.js server...")),await new Promise(e=>{l.close(()=>{l=null,e()})})),s&&"function"==typeof s.close&&(await s.close(),s=null);const{clearConfigCache:H}=await import("./index-BazQY12s.js").then(e=>e.h);H();const{join:V,basename:Z}=await(import("path")),{createServer:B}=await(import("http")),q=await(import("next/dist/server/config.js")),Y=q.default.default||q["module.exports"].default||q.default,X=$e(i),Q=n?V(process.cwd(),n):process.cwd();W(i.mode||"development",Q),g.info(Q);const ee=await Y(w,Q);let te=ee?.ppDev||{};if(0===Object.keys(te).length)try{const{getConfig:e}=await import("./index-BazQY12s.js").then(e=>e.h),t=await e(Q);Object.keys(t).length>0?(te=t,g.info(a.blue("🔧 Loaded pp-dev config from standalone config file"))):g.info(a.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){g.info(a.yellow("⚠️ Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else g.info(a.blue("🔧 Loaded pp-dev config from Next.js config"));let oe=null;try{const{getPkg:e}=await import("./index-BazQY12s.js").then(e=>e.h);oe=e(Q).name}catch{oe=Z(Q)}y(te,oe??"");const ie=p(te,oe??""),se=ie.backendBaseURL??"http://localhost:8080",re=ie.templateLess,ae=ie.v7Features,le=ie.disableSSLValidation,ce=ie.enableProxyCache,de=ie.proxyCacheTTL,pe=ie.personalAccessToken,fe=ie.miHudLess,ue=ie.inspectorEnabled,ge=ie.inspectorMaxMemory,he=ie.inspectorCaptureLimit,me=ie.appId??(process.env.MI_APP_ID&&parseInt(process.env.MI_APP_ID,10)||void 0)??(process.env.MI_PORTAL_PAGE_ID&&parseInt(process.env.MI_PORTAL_PAGE_ID,10)||void 0)??1,be=ee?.basePath;let ve="";be?ve=be:(ve=re?P:ae?x:S,ve+=`/${oe}`);const Se=function(e){const t="1"===process.env.PP_DEV_NEXT_WEBPACK||"true"===process.env.PP_DEV_NEXT_WEBPACK;if(t&&(e.webpack||e.turbopack))throw new Error("Do not combine PP_DEV_NEXT_WEBPACK with --webpack or --turbopack");if(t)return{webpack:!0};if(e.webpack&&e.turbopack)throw new Error("Use only one of --webpack or --turbopack");return e.webpack?{webpack:!0}:e.turbopack?{turbopack:!0}:{}}(i),Te=async e=>{delete process.env.TURBOPACK,s&&"function"==typeof s.close&&(await s.close(),s=null);const t={dev:!0,customServer:!0,hostname:X.host||"localhost",port:X.port,dir:Q,conf:{...ee,basePath:ve,assetPrefix:ve}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),s=m(t),await s.prepare()};if(Se.webpack)await Te({webpack:!0});else if(Se.turbopack)try{await Te({turbopack:!0})}catch(e){if(!xe(e))throw e;g.warn(a.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await Te({webpack:!0})}else try{await Te({})}catch(e){if(!xe(e))throw e;g.warn(a.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await Te({webpack:!0})}if(!s)throw new Error("Next.js app failed to initialize");if(ve.endsWith("/")||(ve+="/"),"/"===ve)throw new Error('basePath cannot be equal to "/" or equal to empty string');g.info(a.green("✅ Next.js app prepared successfully")),g.info(a.blue(`🔧 pp-dev plugin configured for template: ${oe}`)),g.info(a.blue(`🔧 Base path configured: ${ve}`)),se&&(g.info(a.blue(`🌐 Backend URL: ${se}`)),g.info(a.blue(`🆔 Custom App ID: ${me}`)));const ke=s.getRequestHandler(),Ee="number"==typeof X.port?X.port:3e3,Le="string"==typeof X.host?X.host||"0.0.0.0":"localhost",Ie=new Set;l=B(async(e,t)=>{try{const o=e.url||"/",n=o.split("?")[0];let i=ne(o,!0);if(De.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(je.length>0){let l=0;const c=()=>{if(l>=je.length)return void s();const o=je[l];l++,o(e,t,c)};return void c()}return void s()}let r=0;const a=()=>{if(r>=De.length)return void s();const o=De[r];r++,o(e,t,a)};return void a()}async function s(){if(n.startsWith(ve))i=ne(o,!0);else{if(n===ve.replace(/\/$/,"")){const e=o.replace(n,ve);return t.writeHead(302,{Location:e}),void t.end()}if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_"));else if("/"===n)return t.writeHead(302,{Location:ve}),void t.end()}await ke(e,t,i)}s()}catch(d){g.error(`Error handling request: ${d instanceof Error?d.message:String(d)}`,{error:d instanceof Error?d:void 0}),t.statusCode=500,t.end("Internal Server Error")}});let Fe=null,De=[],je=[];if(!1!==ue){const e=new T(ge);k(E,e,he);const t=L(e,he);De.push(t)}if(se){const n=new URL(se).host,i=$();je.unshift(i),De.unshift(i),se.startsWith("https://")&&(o.defaultMaxListeners=Math.max(o.defaultMaxListeners,20));const p={headers:{host:n,referer:se,origin:se.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:me,templateLess:re,disableSSLValidation:le,v7Features:ae,personalAccessToken:pe??process.env.MI_ACCESS_TOKEN};Fe=new I(se,p);const f=F(ve,oe??void 0),u=(e,t,o)=>{f(e,t,o)};je.push(u),De.push(u);const h=J(ve);if(je.push(h),De.push(h),ce){let e=+de;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={middlewares:{use:e=>e},config:{logger:console}},o=D({devServer:t,ttl:e}),n=(e,t,n)=>{o(e,t,n)};De.push(n),g.info(a.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const m=new RegExp(`^((${r=ve,r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),w=j(m,Fe,Object.assign({base:ve},p,{miHudLess:fe})),y=(e,t,o)=>{w(e,t,o)};De.push(y);const P=ve.endsWith("/")?ve.substring(0,ve.length-1):ve,x={middlewares:{use:e=>e},config:{logger:console}},S=_({devServer:x,baseURL:se,proxyIgnore:["/@vite","/@metricinsights","/@",P,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:le,miAPI:Fe,templateName:oe??void 0}),T=(e,t,o)=>{S(e,t,o)};De.push(T);const k=E,L=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(v)||e.url?.startsWith(A)){return void k(e,t,()=>{})}o()};je.push(L),De.push(L);const H=N(e=>{const t=e.split("?")[0];return t.startsWith(ve)&&!t.includes("/_next/")},(e,t)=>{const o=Fe.buildPage(e,fe),i=K(o,ve,{backendBaseURL:se,templateLess:re,appId:me,devPanelPosition:ie.devPanelPosition,devPanelHidden:ie.devPanelHidden,devPanelAutoHide:ie.devPanelAutoHide});return Buffer.from(C(n,t.headers.host??"",i))}),V=(e,t,o)=>{H(e,t,o)};De.push(V),c=new we;let W=ee?.distDir;try{process.env[d]="1";const e=await Y(b.PHASE_PRODUCTION_BUILD,Q);W=e?.distDir??W}catch{}const G=(W??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),B=G&&".next"!==G?G:"out";let q,X="0.0.0";try{const o=JSON.parse(t.readFileSync(e.join(Q,"package.json"),"utf-8"));X="string"==typeof o.version?o.version:X,q="string"==typeof o.repository?o.repository:o.repository?.url}catch{}const te=new R(oe??Z(Q),{root:Q,backupFolder:e.resolve(Q,ie.syncBackupsDir),nextBuild:{projectRoot:Q,distDir:B,packageVersion:X,packageRepositoryUrl:q}}),ne={ws:c.ws,config:{clientInjectionPlugin:{v7Features:ae}}};new M(ne,{distService:te,miAPI:Fe}),O(E,{distService:te,miAPI:Fe}),z(E,{miAPI:Fe}),U({persist:ie.persistUsers,miAPI:Fe,projectRoot:Q,miUrl:se});const ue="function"==typeof s?.getUpgradeHandler?s.getUpgradeHandler():null;l.on("upgrade",(e,t,o)=>{c?.handleUpgrade(e,t,o)||(ue?ue(e,t,o):t.destroy())}),g.info(a.blue(`🔧 ${De.length} pp-dev middlewares initialized`)),g.info(a.blue(`🔧 ${je.length} essential middlewares for internal routes`)),g.info(a.blue(`🔧 MiAPI initialized for backend: ${se}`)),g.info(a.blue(`🔧 Custom App ID: ${me}`))}l.listen(Ee,Le,()=>{g.info(a.green(`✅ pp-dev Next.js server running at http://${Le}:${Ee}`)),g.info(a.blue(`📱 Next.js app accessible at http://${Le}:${Ee}${ve}`)),!1!==ue&&g.info(a.cyan(`🔍 Request Inspector: http://${Le}:${Ee}${v}`)),g.info(a.blue("🔧 Base path handling active")),f||(f=ye(Q,h,g.info),g.info(a.blue("🔧 Config file watcher started"))),l.on("connection",e=>{Ie.add(e),e.on("close",()=>Ie.delete(e))});const e=async e=>{g.info(a.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));const t=setTimeout(()=>{g.info(a.yellow("⏰ Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{f&&(Pe(f),f=null);for(const e of Array.from(Ie))e.destroy();Ie.clear(),c&&(await c.close(),c=null),await new Promise(e=>{l.close(()=>{g.info(a.yellow("🛑 HTTP server closed")),e()})}),s&&"function"==typeof s.close&&(await s.close(),g.info(a.yellow("🛑 Next.js app closed"))),clearTimeout(t),g.info(a.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(t),g.error(a.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};let t=process;if("function"!=typeof process.on){const e=globalThis.process||global.process;e&&"function"==typeof e.on&&(t=e,g.info(a.green("✅ Using global process object for event handlers")))}if("function"==typeof t.on)try{t.on("SIGINT",()=>e("SIGINT")),t.on("SIGTERM",()=>e("SIGTERM")),t.on("uncaughtException",t=>{g.error(a.red(`❌ Uncaught Exception: ${t}`)),e("uncaughtException")}),t.on("unhandledRejection",(t,o)=>{g.error(a.red(`❌ Unhandled Rejection at: ${o}, reason: ${t}`)),e("unhandledRejection")}),g.info(a.green("✅ Process event handlers registered successfully"))}catch(e){g.warn(a.yellow(`⚠️ Failed to register process event handlers: ${e}`))}else g.warn(a.yellow("⚠️ process.on is not available, graceful shutdown handlers will not be registered")),g.info(a.blue("💡 This might be due to bundling or environment constraints"))}),u=!1}catch(e){u=!1,g.error(a.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(g.error(a.red("❌ Next.js Peer Dependency Error:")),g.error(a.red(e.message)),g.error(a.yellow("\n💡 To fix this issue:")),g.error(a.blue(" 1. Install Next.js in your project:")),g.error(a.white(" npm install next@^16")),g.error(a.blue(" 2. Or use yarn:")),g.error(a.white(" yarn add next@^16")),g.error(a.blue(" 3. Or use pnpm:")),g.error(a.white(" pnpm add next@^16")),g.error(a.yellow("\n📖 For more information, see:")),g.error(a.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var r}},m=async e=>{g.info(a.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{f&&(Pe(f),f=null),c&&(await c.close(),c=null),l&&await new Promise(e=>{l.close(()=>{l=null,e()})}),s&&"function"==typeof s.close&&(await s.close(),s=null),g.info(a.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){g.error(a.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("uncaughtException",e=>{g.error(a.red(`❌ Uncaught Exception: ${e}`)),m("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{g.error(a.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),m("unhandledRejection")}),await h()}),ve.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)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(t,o)=>{Le(o);const n=$e(o),i=V(o);try{const s=o.mode||"production",r=e.resolve(process.cwd(),t??".");W(s,r);const a=await Y({mode:s,command:"build"},o.config,t,o.logLevel);let l=await Z(i,{mode:s,root:r});if(a){const{plugins:e,...t}=a.config;l=X(l,t)}const c=X(l,{root:t,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},build:n},!0);if(await Q(c),n.changelog){const i=t||process.cwd(),s=c.build?.outDir||"dist";let r="dist-zip";c.ppDevConfig&&(!1===c.ppDevConfig.distZip?r=s:"object"==typeof c.ppDevConfig.distZip&&"string"==typeof c.ppDevConfig.distZip.outDir&&(r=c.ppDevConfig.distZip.outDir)),await Se({changelog:n.changelog,executionRoot:i,newAssetsPath:e.resolve(i,s),backupsDirPath:e.resolve(i,c.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:e.resolve(i,r),logLevel:o.logLevel})}}catch(e){r(o.logLevel).error(a.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{Ee(e=>r(o.logLevel).info(e))}}),ve.command("next-build [root]","build a Next.js app for production (`next build`) and emit VERSION/BUILD-MANIFEST/zip in the same format as `pp-dev build`").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(o,n)=>{Le(n);const i=r(n.logLevel),s=o?e.resolve(process.cwd(),o):process.cwd(),l=V(n);process.env[d]="1";try{W(n.mode||"production",s);const{constants:o}=await G(),r=await(import("next/dist/server/config.js")),c=r.default.default||r["module.exports"].default||r.default,d=await c(o.PHASE_PRODUCTION_BUILD,s);let w,v=d?.ppDev||{};if(0===Object.keys(v).length){const{getConfig:e}=await import("./index-BazQY12s.js").then(e=>e.h);v=await e(s)}try{const{getPkg:e}=await import("./index-BazQY12s.js").then(e=>e.h);w=e(s).name}catch{w=e.basename(s)}const y=p(v,w),P=B(y.distZip,l,f(w)),x=q(y.versionPlugin,l),S=u(s,d);S&&i.info(a.dim(`[pp-dev] Removed stale dev route types: ${e.relative(s,S)}`)),i.info(a.cyan("[pp-dev] Running `next build`...")),await g(s);const T="string"==typeof d?.distDir&&d.distDir?d.distDir:".next",k=".next"===T?"out":T,E=e.resolve(s,k);if(!t.existsSync(E)||!t.statSync(E).isDirectory())throw new Error(`Next.js build output directory not found: ${E}. "next-build" requires "output: 'export'" in next.config (static export).`);const L=JSON.parse(t.readFileSync(e.join(s,"package.json"),"utf-8"));if(!1!==x&&!1!==x.enabled&&(h({outDir:E,packageVersion:"string"==typeof L.version?L.version:"0.0.0",versionFileTemplate:x.versionFileTemplate,packageRepositoryUrl:"string"==typeof L.repository?L.repository:L.repository?.url,enabled:x.enabled}),i.info(a.green(`✅ VERSION / BUILD-MANIFEST written to ${e.relative(s,E)}`))),!1!==P){const o=e.resolve(s,P.outDir),n=P.inDir?e.resolve(E,P.inDir):E,r=m(o,P.outFileName,"ZIP output file name");t.mkdirSync(e.dirname(r),{recursive:!0});const l=await b(n);t.writeFileSync(r,l),i.info(a.green(`✅ Zip archive written to ${e.relative(s,r)}`))}if(n.changelog){const t=!1!==P?P.outDir:k;await Se({changelog:n.changelog,executionRoot:s,newAssetsPath:E,backupsDirPath:e.resolve(s,y.syncBackupsDir),changelogDestinationPath:e.resolve(s,t),logLevel:n.logLevel})}}catch(e){r(n.logLevel).error(a.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{Ee(e=>r(n.logLevel).info(e))}}),ve.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)=>{Le(n);const{oldAssetsPath:i=t,newAssetsPath:s=o,destination:l=".",filename:c="CHANGELOG.html",logLevel:d}=n,p=process.cwd();i&&s||(r(d).error(a.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const f=e.resolve(p,i),u=e.resolve(p,s),g=e.resolve(p,l),h=new me({oldAssetsPath:f,newAssetsPath:u,destinationPath:g,changelogFilename:c});await h.generateChangelog()}),ve.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)=>{Le(n);const{source:i=t,destination:s=o,fontName:l="icon-font"}=n,c=process.cwd(),d=e.resolve(c,i),p=e.resolve(c,s),f=new be({sourceDir:d,outputDir:p,fontName:l}),u=r(n.logLevel);u.info(`Generating icon font from SVG files in ${a.dim(d)}`),await f.generate(),u.info(`Icon font generated and saved to ${a.dim(p)}`)}),ve.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(t,o)=>{Le(o);try{const n=o.mode||"production",i=e.resolve(process.cwd(),t??".");W(n,i);const s=await Y({mode:n,command:"build"},o.config,t,o.logLevel);let r=await Z(void 0,{mode:n,root:i});if(s){const{plugins:e,...t}=s.config;r=X(r,t)}const a=await ee(X(r,{root:t,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode}),"serve");await te(a,o.force,!0)}catch(e){r(o.logLevel).error(a.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),ve.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(t,o)=>{Le(o);try{const n=o.mode||"production",i=e.resolve(process.cwd(),t??".");W(n,i);const s=await Y({mode:n,command:"build"},o.config,t,o.logLevel);let r=await Z(void 0,{mode:n,root:i});if(s){const{plugins:e,...t}=s.config;r=X(r,t)}(await oe(X(r,{root:t,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode,build:{outDir:o.outDir},preview:{port:o.port,strictPort:o.strictPort,host:o.host,https:o.https,open:o.open}}))).printUrls()}catch(e){r(o.logLevel).error(a.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{Ee(e=>r(o.logLevel).info(e))}}),ve.command("migrate [config]","migrate pp-dev config from 0.x flat format to 1.0 grouped format").option("--dry-run","[boolean] print migrated config without writing any files").option("--format <format>","[string] output format: ts (default), js, json").option("--output <file>","[string] output file path (default: pp-dev.config.ts)").option("--no-backup","[boolean] skip backup of original config file").action(async(o,n)=>{const i=r(n.logLevel),{isLegacyFlatConfig:s,isLegacyPPWatchConfig:l,isAlreadyMigrated:c,migrateLegacyFlatConfig:d,migratePPWatchConfig:p,generateConfigFileContent:f,discoverMigrateSource:u,loadPackageJsonMigrateConfig:g}=await(import("./migrate-B2gJ62fm.js")),h=n.format??"ts",m=!1!==n.backup,b=process.cwd(),w=u(b,o);w||(i.warn(a.yellow("No pp-dev or pp-watch config file found in the current directory.")),i.info(a.blue('Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}, or a "pp-dev" field in package.json')),process.exit(1));const{sourceFile:v,isWatchConfig:y,isPackageJsonConfig:P}=w;i.info(a.blue(`Found config: ${e.relative(b,v)}`));const{getPkg:x}=await import("./index-BazQY12s.js").then(e=>e.h),S=x();let T,k={};try{if(/\.[cm]?ts$/i.test(v)){const o=await(import("esbuild")),{pathToFileURL:n}=await(import("url")),i=(await o.build({absWorkingDir:b,entryPoints:[v],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,s=`pp-migrate-tmp-${Date.now()}.mjs`;t.writeFileSync(s,i);try{const t=await(import(n(e.resolve(b,s)).toString()));k=t.default?.default??t.default??t}finally{t.existsSync(s)&&t.unlinkSync(s)}}else if(/\.[cm]?js$/i.test(v)){const{pathToFileURL:t}=await(import("url")),o=await(import(t(e.resolve(b,v)).toString()));k=o.default?.default??o.default??o}else P?k=g(v):v.endsWith(".json")&&(k=JSON.parse(t.readFileSync(v,"utf-8")))}catch(e){i.error(a.red(`Failed to load config file: ${e.message}`)),process.exit(1)}k&&"object"==typeof k||(i.error(a.red("Config file did not export a valid object.")),process.exit(1)),c(k)?(i.info(a.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):y||l(k)?(i.info(a.blue("Detected pp-watch config format → migrating to 1.0")),T=p(k)):s(k)?(i.info(a.blue("Detected 0.x flat config format → migrating to 1.0")),T=d(k,S.name)):(i.warn(a.yellow("Could not detect config format. No known keys found.")),process.exit(1));const E=f(T,h),L=n.output??e.join(b,`pp-dev.config.${h}`);if(n.dryRun&&(i.info(a.green(`\n--- Migrated config (dry-run) → ${e.relative(b,L)} ---\n`)),process.exit(0)),m&&!P&&t.existsSync(v)){const o=`${v}.bak`;t.copyFileSync(v,o),i.info(a.blue(`Backed up original to: ${e.relative(b,o)}`))}t.writeFileSync(L,E,"utf-8"),i.info(a.green(`✅ Migration complete → ${e.relative(b,L)}`)),P?i.info(a.yellow('You can now remove the "pp-dev" field from package.json.')):v!==L&&t.existsSync(v)&&i.info(a.yellow(`You can now delete the old config: ${e.relative(b,v)}`))}),ve.help(),ve.version(w),ve.parse();export{Ee as stopProfiler};
|
|
1
|
+
import{cac as e}from"cac";import{c as t,a as o,P as n,V as i,b as s,v as r,n as a,d as l,e as c,f as d,i as p,h as f,g as u,j as g,r as h,k as m}from"./auth.provider-DDUsu1H1.js";import*as w from"path";import{performance as v}from"node:perf_hooks";import{loadConfigFromFile as b,mergeConfig as y,build as P,resolveConfig as x,optimizeDeps as S,preview as k}from"vite";import{I as T,P as L,c as E,r as F,R as D,a as $,b as j,V as I,e as N,d as C,g as _,M as A,i as M,f as R,h as H,j as O,k as U,l as V,m as z,n as G,u as W,D as Z,s as B,o as q,p as J,q as K,z as X}from"./request-capture.middleware-VElwjU1W.js";import{watch as Y}from"chokidar";import{l as Q,g as ee,s as te,c as oe,i as ne,r as ie,a as se,b as re}from"./index-tD-QICGk.js";import*as ae from"fs";import{EventEmitter as le}from"node:events";import{parse as ce}from"url";import{WebSocketServer as de,WebSocket as pe}from"ws";import{fork as fe}from"node:child_process";import*as ue from"dir-compare";import ge from"diff-match-patch";import{isBinaryFile as he}from"isbinaryfile";import*as me from"os";import*as we from"crypto";import{w as ve}from"./version-manifest-CyzmnFOe.js";import"picocolors";import"node:path";import"node:net";import"zlib";import"axios";import"node:http";import"node:https";import"process";import"jszip";import"child_process";import"module";import"http-proxy-middleware";import"node:string_decoder";import"node:crypto";import"node:fs";import"node:os";import"express";import"node:module";import"./helpers.js";import"ejs";import"fs/promises";import"util";function be(e){return null!=e&&!1!==e}let ye=null;const Pe=new WeakMap;function xe(e,n){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;Pe.set(e,n);const i=t();n.print&&i.info(o.dim(o.green(" ➜"))+o.dim(" press ")+o.bold("h")+o.dim(" to show help"));const s=(n.customShortcuts??[]).filter(be).concat(Se);ye?.(),ye=null;let r=!1;const a=process.stdin.isPaused(),l=process.stdin,c=Boolean(l.isRaw),d=async t=>{if(""===t)return void function(e=process){"win32"===e.platform?e.emit("SIGINT","SIGINT"):e.kill(e.pid,"SIGINT")}();if(""===t)return void await e.close().finally(()=>process.exit(0));if(r)return;"h"===t&&i.info(["",o.bold(" Shortcuts"),...s.map(e=>o.dim(" press ")+o.bold(e.key)+o.dim(` to ${e.description}`))].join("\n"));const n=s.find(e=>e.key===t);n&&(r=!0,await n.action(e),r=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",d).setEncoding("utf8").resume();const p=e.httpServer,f=()=>{ye===f&&(p.removeListener("close",f),process.stdin.off("data",d),c||process.stdin.setRawMode(!1),a&&process.stdin.pause(),ye=null)};ye=f,p.on("close",f)}const Se=[{key:"r",description:"restart the server",async action(e){const t=Pe.get(e);await e.restart(),t&&xe(e,{...t,print:!1})}},{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"))}}],ke="pp-dev:ready",Te="pp-dev:shutdown";function Le(e){return e instanceof Error?e.stack??e.message:String(e)}function Ee({logger:e,knownRejections:t=[],shutdown:n,shutdownTimeoutMs:i=5e3,processRef:s=process}){let r=!1,a=!1,l=0;const c=async(t,c,{repeatable:d=!0}={})=>{if((e=>{l=Math.max(l,e)})(c),r){if(d&&(e=>"SIGINT"===e||"SIGTERM"===e||"SIGHUP"===e)(t)){if(a)return void(a=!1);e.warn(o.yellow(`\n⚠️ Received ${t} again, exiting without waiting for the shutdown`)),s.exit(l)}return}r=!0,a=!d,e.info(o.yellow(`\n🛑 Received ${t}, shutting down gracefully...`));const p=setTimeout(()=>{e.error(o.red(`⏰ Shutdown did not finish within ${i} ms, forcing exit`)),s.exit(1)},i);try{await n(),clearTimeout(p),e.info(o.green("✅ Graceful shutdown completed")),s.exit(l)}catch(t){clearTimeout(p),e.error(o.red(`❌ Error during graceful shutdown: ${Le(t)}`)),s.exit(1)}},d=()=>{c("SIGINT",0)},p=()=>{c("SIGTERM",0)},f=()=>{c("SIGHUP",0)},u=t=>{e.error(o.red(`❌ Uncaught exception: ${Le(t)}`)),c("uncaughtException",1)},g=n=>{const i=t.find(e=>e.matches(n));i?e.info(o.dim(i.message)):e.error(o.red(`❌ Unhandled promise rejection (the server keeps running): ${Le(n)}`))},h=e=>{(function(e){return"object"==typeof e&&null!==e&&e.type===Te&&"string"==typeof e.reason})(e)&&c(e.reason,0,{repeatable:!1})},m=()=>{c("the end of the pp-dev process",0,{repeatable:!1})},w="function"==typeof s.send;return s.on("SIGINT",d),s.on("SIGTERM",p),s.on("SIGHUP",f),s.on("uncaughtException",u),s.on("unhandledRejection",g),w&&(s.on("message",h),s.on("disconnect",m)),()=>{s.off("SIGINT",d),s.off("SIGTERM",p),s.off("SIGHUP",f),s.off("uncaughtException",u),s.off("unhandledRejection",g),w&&(s.off("message",h),s.off("disconnect",m))}}const Fe=["--","c","config","base","l","logLevel","clearScreen","configLoader","profile","d","debug","f","filter","m","mode","force","w","changelog","distZip","distZipDir","distZipFilename","versionManifest","versionFileTemplate","webpack","turbopack"];function De(e){const t={...e};for(const e of Fe)delete t[e];return"sourcemap"in t&&(t.sourcemap="true"===t.sourcemap||"false"!==t.sourcemap&&t.sourcemap),"watch"in t&&(t.watch=t.watch?{}:void 0),t}const $e=["https","open","cors","strictPort","force"];const je=[...n,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"];function Ie(e){return e instanceof Error?e.stack??e.message:String(e)}function Ne(e,t,n,i={}){const{debounceMs:s=500}=i,r=w.resolve(e),a=new Set(je),l=Y(r,{ignored:(e,t)=>!!t&&(t.isDirectory()?w.resolve(e)!==r:!a.has(w.basename(e))),depth:0,persistent:!0,ignoreInitial:!0,followSymlinks:!1});let c=null,d=!1,p=!1,f=!1;const u=()=>{c&&clearTimeout(c),c=setTimeout(()=>{(async()=>{if(c=null,!f)if(d)p=!0;else{d=!0;try{n(o.yellow("🔄 Restarting dev server due to config change...")),await t()}catch(e){n(o.red(`❌ Failed to restart dev server: ${Ie(e)}`))}finally{d=!1}p&&!f&&(p=!1,n(o.blue("🔧 Config changed again during the restart")),u())}})()},s)},g=e=>t=>{n(o.blue(`🔧 Config file ${e}: ${w.relative(r,t)}`)),u()};l.on("change",g("changed")),l.on("add",g("added")),l.on("unlink",g("removed")),l.on("error",e=>{n(o.red(`❌ Config watcher error: ${Ie(e)}`))});const h=new Promise(e=>{l.once("ready",()=>{n(o.blue("🔧 Config file watcher started")),e()})});return{watcher:l,ready:h,async close(){f=!0,c&&(clearTimeout(c),c=null),await l.close()}}}function Ce(e){if(!e||"object"!=typeof e||!("message"in e))return!1;const t=String(e.message);return/Turbopack is not supported/i.test(t)||/native bindings are not available/i.test(t)||/Only WebAssembly \(WASM\) bindings were loaded/i.test(t)}const _e=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};async function Ae(e){const{root:t,mode:o,command:n,isPreview:i}=e,s=w.resolve(process.cwd(),t??".");Q(o,s);const r=await b({mode:o,command:n,...i?{isPreview:i}:{}},e.configFile,t,e.logLevel);let a=await ee(e.buildOverrides,{mode:o,root:s});if(r){const e={...r.config};delete e.plugins,a=y(a,e)}return{config:a,envDir:s}}let Me=global.__pp_dev_profile_session,Re=0;const He=e=>{if(Me)return new Promise((t,n)=>{Me.post("Profiler.stop",(i,{profile:s})=>{if(i)n(i);else{const n=w.resolve(`./pp-dev-profile-${Re++}.cpuprofile`);ae.writeFileSync(n,JSON.stringify(s)),e(o.yellow(`CPU profile written to ${o.white(o.dim(n))}`)),Me=void 0,t()}})})};function Oe(e){e.once("error",()=>e.destroy()),e.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n",()=>e.destroy())}class Ue{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;allowedHosts;constructor({allowedHosts:e=[]}={}){this.allowedHosts=e,this.wss=new de({noServer:!0}),this.wss.on("connection",e=>this.onConnection(e)),this.wss.on("error",e=>this.fireLifecycle("error",e)),this.ws={on:(e,t)=>{"close"!==e&&"error"!==e?this.getEventSet(e).add(t):this.getLifecycleSet(e).add(t)},off:(e,t)=>{"close"!==e&&"error"!==e?this.eventListeners.get(e)?.delete(t):this.lifecycleListeners.get(e)?.delete(t)},send:(e,t)=>{if("string"==typeof e)for(const o of this.clients.keys())this.sendToSocket(o,e,t);else{const t=JSON.stringify(e);for(const e of this.clients.keys())e.readyState===pe.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===L&&(s(e,this.allowedHosts)?(Oe(t),!0):(this.wss.handleUpgrade(e,t,o,t=>{this.wss.emit("connection",t,e)}),!0))}async close(){this.fireLifecycle("close");for(const e of this.clients.keys())e.terminate();this.clients.clear(),await new Promise(e=>this.wss.close(()=>e()))}onConnection(e){const t={send:(t,o)=>this.sendToSocket(e,t,o),socket:e};this.clients.set(e,t),e.on("message",e=>this.onMessage(t,e)),e.on("close",()=>this.clients.delete(e)),e.on("error",()=>{})}onMessage(e,o){let n;try{n=JSON.parse(o.toString())}catch{return}if(!n||"custom"!==n.type||"string"!=typeof n.event)return;const i=this.eventListeners.get(n.event);if(i)for(const o of i)try{o(n.data,e)}catch(e){t().error(`ws handler for "${n.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===pe.OPEN&&e.send(JSON.stringify({type:"custom",event:t,data:o}))}fireLifecycle(e,t){for(const o of this.lifecycleListeners.get(e)??[])try{o(t)}catch{}}getEventSet(e){let t=this.eventListeners.get(e);return t||(t=new Set,this.eventListeners.set(e,t)),t}getLifecycleSet(e){let t=this.lifecycleListeners.get(e);return t||(t=new Set,this.lifecycleListeners.set(e,t)),t}}const Ve={matches:e=>e instanceof Error&&"Worker creator already registered"===e.message,message:"Next.js kept its Turbopack worker pool from before the restart ('Worker creator already registered')"};const ze="PP_DEV_NEXT_SERVER_PROCESS";function Ge(){const[,e,...t]=process.argv;if(!e)throw new Error("pp-dev next: cannot start the server process, no script in process.argv");return fe(e,t,{env:{...process.env,[ze]:"1"},stdio:"inherit",execArgv:process.execArgv})}async function We(e,t="development"){const[{loadPPDevEnv:o},{clearConfigCache:n,getConfig:i,getPkg:s},{validatePPDevConfig:r}]=await Promise.all([import("./index-tD-QICGk.js").then(e=>e.h),import("./index-tD-QICGk.js").then(e=>e.j),import("./auth.provider-DDUsu1H1.js").then(e=>e.w)]);o(t,e),n();r(await i(e),s(e).name)}function Ze(e){return e instanceof Error?e.message:String(e)}const Be=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class qe{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:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n 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:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n 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(e){const{oldAssetsPath:n,newAssetsPath:i,destinationPath:s,changelogTemplate:r,diffFileTemplateHandler:a,diffLineTemplateHandler:l,changelogFilename:c,contextLines:d}=e;if(this.logger=t(),!n||!i||!s)throw new Error("Previous assets path, current assets path and destination path are required");if(n===i)throw new Error("Previous and current assets paths must be different");if(!this.isExists(n))throw new Error(`Previous assets path ${n} does not exist`);if(!this.isExists(i))throw new Error(`Current assets path ${i} does not exist`);if(this.isZipFile(n)){const e=w.resolve(me.tmpdir(),we.createHash("md5").update(n).digest("hex"));this.oldAssetsPath=this.unzipFile(n,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(n))throw new Error(`Invalid previous assets path ${n}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(n);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(i)){const e=w.resolve(me.tmpdir(),we.createHash("md5").update(i).digest("hex"));this.newAssetsPath=this.unzipFile(i,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(i))throw new Error(`Invalid current assets path ${i}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(i);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${i} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=s,this.mkdirpSync(this.destinationPath),this.changelogFilename=c||"CHANGELOG.html",r&&(this.templateIsValid(r)?this.changelogTemplate=r:this.logger.warn(o.yellow("Invalid changelog template, using default"))),"function"==typeof a&&(this.diffFileTemplateHandler=a),"function"==typeof l&&(this.diffLineTemplateHandler=l),d&&(this.contextLines=d)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return ae.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return ae.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===ae.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){ae.existsSync(e)||ae.mkdirSync(e,{recursive:!0})}async unzipFile(e,t){ae.rmSync(t,{force:!0,recursive:!0}),await q(e,t)}normalizeAssetFolderPath(e){const t=ae.readdirSync(e);return 1===t.length&&ae.lstatSync(w.join(e,t[0])).isDirectory()?this.normalizeAssetFolderPath(w.join(e,t[0])):e}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(o.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await ue.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(Be.test(e)&&(e=e.replace(Be,"$1$3")),Be.test(t)&&(t=t.replace(Be,"$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 ge,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(e){if("equal"===e.state){const t=this.pathToPosix(w.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(w.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${o}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const t=e.path1&&e.name1?w.join(e.path1,e.name1):null,o=e.path2&&e.name2?w.join(e.path2,e.name2):null,n=this.pathToPosix(w.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&t)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&o)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&t&&o){const i=this.pathToPosix(w.join(".",e.relativePath,e.name1??"")),s=this.pathToPosix(w.join(".",e.relativePath,e.name2??"")),r=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${s}</span></span\n >`:n;return this.diffFileTemplate(r,await he(t)||await he(o)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(ae.readFileSync(t,"utf-8"),ae.readFileSync(o,"utf-8"))))}return""}async generateChangelog(){this.logger.info(o.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),t=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(o.green("Writing changelog file"));const n=this.changelogTemplate.split("%FILES%");n.splice(1,0,t);const i=n.join("");ae.writeFileSync(w.join(this.destinationPath,this.changelogFilename),i),this.logger.info(o.green(`Changelog file written to ${w.join(this.destinationPath,this.changelogFilename)}`))}}async function Je(e){const{changelog:n,executionRoot:i,newAssetsPath:s,backupsDirPath:r,changelogDestinationPath:a,logLevel:l}=e;let c;if("string"==typeof n)c=w.resolve(i,n);else{if(!ae.existsSync(r))return void t(l).warn(o.yellow("backups directory not found, skipping changelog generation"));const e=ae.readdirSync(r,{withFileTypes:!0});if(!e.length)return void t(l).warn(o.yellow("no backups found, skipping changelog generation"));const n=e.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!n.length)return void t(l).warn(o.yellow("no ZIP backups found, skipping changelog generation"));const i=n.reduce((e,t)=>ae.statSync(w.resolve(r,e.name)).mtimeMs>ae.statSync(w.resolve(r,t.name)).mtimeMs?e:t).name;c=w.resolve(r,i)}const d=new qe({oldAssetsPath:c,newAssetsPath:s,destinationPath:a});await d.generateChangelog()}class Ke{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){const{default:e}=await(import("svgtofont"));await e({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}const Xe=e("pp-dev");Xe.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"),function(e){e.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,n)=>{_e(n);let s=null,r=null;const a=e?w.resolve(process.cwd(),e):process.cwd(),l=t(n.logLevel),c=async({restart:t=!1}={})=>{let d=null;try{const{clearConfigCache:t,getConfig:f}=await import("./index-tD-QICGk.js").then(e=>e.j);t();const{createServer:u}=await(import("vite")),g=n.mode||"development",{config:h,envDir:m}=await Ae({root:e,mode:g,command:"serve",configFile:n.config,logLevel:n.logLevel}),w=n.base??h.base;if(!w||"/"===w)throw new Error('base cannot be equal to "/" or empty string');if(d=await u(y(h,{root:e,base:n.base,mode:n.mode,configFile:n.config,logLevel:n.logLevel,clearScreen:n.clearScreen,optimizeDeps:{force:n.force},server:De(n),customLogger:l},!0)),!d.httpServer)throw new Error("HTTP server not available");if(s){const e=s;s=null,l.info(o.yellow("🛑 Stopping existing dev server...")),await e.close()}await d.listen(),s=d;const b=global.__pp_dev_start_time??!1,P=b?o.dim(`ready in ${o.reset(o.bold(Math.ceil(v.now()-b)))} ms`):"";l.info(`\n ${o.green(`${o.bold("PP-DEV")} v${i}`)} ${P}\n`),s.printUrls();const x=await f(m);if(!1!==x.inspector?.enabled){const e=s.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${s.config.server.port??5173}`;l.info(`\n ${o.cyan("🔍 Request Inspector")} ${o.dim(t+T)}\n`)}xe(s,{print:!0,customShortcuts:[...(p=l.info,Me?[{key:"p",description:"start/stop the profiler",async action(){if(Me)await He(p);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{Me=new e.Session,Me.connect(),Me.post("Profiler.enable",()=>{Me?.post("Profiler.start",()=>{p("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("/")}`}})}}]}),r||(r=Ne(a,()=>c({restart:!0}),l.info))}catch(e){if(!t)return l.error(o.red(`error when starting dev server:\n${e.stack}`),{error:e}),He(l.info),void process.exit(1);d&&d!==s&&await d.close().catch(()=>{}),l.error(o.red(`❌ Failed to restart dev server:\n${e.stack}`),{error:e}),l.warn(o.yellow(s?"⚠️ The running dev server is kept, with its config, until the next config change":"⚠️ No dev server is running; it starts again on the next config change"))}var p};Ee({logger:l,shutdown:async()=>{var e;r&&(await(e=r,e.close()),r=null),s&&(await s.close(),s=null),He(l.info)}}),await c()})}(Xe),function(e){e.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname; without a value, listen on all addresses").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] no effect with pp-dev next (deprecated)").option("--open [path]","[boolean | string] no effect with pp-dev next (deprecated)").option("--cors","[boolean] no effect with pp-dev next (deprecated)").option("--strictPort","[boolean] no effect with pp-dev next (deprecated)").option("--force","[boolean] no effect with pp-dev next (deprecated)").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(e,n)=>{if(_e(n),!function(e=process.env){return"1"===e[ze]}())return void await function(e){const{projectRoot:t,logger:n,mode:i="development",checkConfig:s=()=>We(t,i),startServerProcess:r=Ge,createWatcher:a=Ne,stopTimeoutMs:l=1e4,processRef:c=process}=e;let d=null,p=!1,f=!1,u=null,g=null,h=!1;return new Promise(()=>{const e=async e=>{if(u){const e=u;u=null,await e.close()}c.exit(e)},i=e=>{const t=d;return t?g||(g=new Promise(i=>{if(null!==t.exitCode||null!==t.signalCode)return void i(t.exitCode);const s=setTimeout(()=>{n.warn(o.yellow(`⏰ The dev server did not stop within ${l} ms, killing it`)),t.kill("SIGKILL")},l);t.on("exit",e=>{clearTimeout(s),i(e)}),t.send({type:Te,reason:e},()=>{})}).finally(()=>{g=null}),g):Promise.resolve(0)},m=()=>{const i=r();let s;const l=new Promise(e=>s=e);d=i,p=!1,i.on("message",e=>{e?.type===ke&&d===i&&(p=!0,f=!0,s(),u||h||(u=a(t,w,n.info)))});let c=!1;const m=(t,r,a)=>{if(c)return;if(c=!0,s(),d===i&&(d=null),g||h)return;const l=p,u=t??1,m=a??r??`code ${u}`;p=!1,l?(n.error(o.red(`❌ The dev server exited (${m})`)),e(u)):f?n.error(o.red(`❌ The dev server did not start after the config change (${m}); fix the config and save it again`)):e(u)};return i.on("exit",(e,t)=>m(e,t)),i.on("error",e=>m(1,null,Ze(e))),l},w=async()=>{if(!h){try{await s()}catch(e){return void n.error(o.red(`❌ The pp-dev config could not be loaded, the dev server keeps running: ${Ze(e)}`))}await i("a config change"),h||await m()}},v=async t=>{if(h)return;h=!0;const o=await i(t);await e(o??1)};c.on("SIGINT",()=>{v("SIGINT")}),c.on("SIGTERM",()=>{v("SIGTERM")}),c.on("SIGHUP",()=>{v("SIGHUP")}),c.on("exit",()=>{d&&null===d.exitCode&&null===d.signalCode&&d.kill("SIGKILL")}),m()})}({projectRoot:e?w.resolve(process.cwd(),e):process.cwd(),logger:t(n.logLevel),mode:n.mode||"development"});const i=$e.filter(e=>void 0!==n[e]);let s,u;i.length>0&&t(n.logLevel).warn(o.yellow(`⚠️ ${i.map(e=>`--${e}`).join(", ")} ${1===i.length?"has":"have"} no effect with pp-dev next and will be removed.`));try{({host:s,port:u}=function(e,t){let o="localhost";!0===e||""===e?o="0.0.0.0":"string"==typeof e?o=e:"number"==typeof e&&(o=String(e));const n=void 0===t?3e3:"number"==typeof t?t:"string"==typeof t&&t.trim()?Number(t):NaN;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`--port must be a port number (0-65535), got ${JSON.stringify(t)}`);return{host:o,port:n}}(n.host,n.port))}catch(e){t(n.logLevel).error(o.red(`❌ ${e.message}`)),process.exit(1)}let g=null,h=null,m=null,v=null;const b=new Set,y=t(n.logLevel),P=function(e=["uncaughtException"],t=process){const o=e=>t.listeners(e);let n=null,i=null;return{beforeCreate(){n=new Map(e.map(e=>[e,new Set(o(e))]))},afterCreate(){if(!n)return 0;const s=n,r=new Map(e.map(e=>[e,o(e).filter(t=>!s.get(e).has(t))]));let a=0;if(i)for(const[e,o]of i){const n=new Set(r.get(e).map(e=>e.toString()));for(const i of o)n.has(i.toString())&&(t.off(e,i),a+=1)}return i=r,n=null,a}}}(),x=async()=>{g&&"function"==typeof g.close&&await g.close(),g=null};Ee({logger:y,knownRejections:[Ve],shutdown:async()=>{v?.dispose(),v=null,m&&(await m.close(),m=null),await(async()=>{const e=h;if(e){for(const e of b)e.destroy();b.clear(),await new Promise(t=>{e.close(()=>t())}),h===e&&(h=null)}})(),await x()}}),await(async()=>{try{const{next:t,constants:i}=await te(),{PHASE_DEVELOPMENT_SERVER:S}=i,{createServer:k}=await(import("http")),L=await(import("next/dist/server/config.js")),q=L.default.default||L["module.exports"].default||L.default,J=e?w.resolve(process.cwd(),e):process.cwd();Q(n.mode||"development",J);const K=await q(S,J);let X=K?.ppDev||{};if(0===Object.keys(X).length)try{const{getConfig:e}=await import("./index-tD-QICGk.js").then(e=>e.j),t=await e(J);Object.keys(t).length>0?(X=t,y.info(o.blue("🔧 Loaded pp-dev config from standalone config file"))):y.info(o.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){y.warn(o.yellow(`⚠️ Failed to load standalone pp-dev config, using defaults: ${e instanceof Error?e.message:String(e)}`))}else y.info(o.blue("🔧 Loaded pp-dev config from Next.js config"));const{getPkg:Y}=await import("./index-tD-QICGk.js").then(e=>e.j),ee=Y(J).name;r(X,ee);const ie=a(X,ee),{templateName:se}=ie,re=ie.backendBaseURL,de=ie.templateLess,pe=ie.v7Features,fe=ie.disableSSLValidation,ue=ie.enableProxyCache,ge=ie.proxyCacheTTL,he=ie.personalAccessToken,me=ie.miHudLess,we=ie.inspectorEnabled,ve=ie.inspectorMaxMemory,be=ie.inspectorCaptureLimit,ye=ie.appId,Pe=!0===ie.allowedHosts||[...ie.allowedHosts,s.toLowerCase()],xe=E({allowedHosts:ie.allowedHosts}),Se=K?.basePath;let Te="";Se?Te=Se:(Te=de?l:pe?c:d,Te+=`/${se}`);const Le=function(e){const t="1"===process.env.PP_DEV_NEXT_WEBPACK||"true"===process.env.PP_DEV_NEXT_WEBPACK;if(t&&(e.webpack||e.turbopack))throw new Error("Do not combine PP_DEV_NEXT_WEBPACK with --webpack or --turbopack");if(t)return{webpack:!0};if(e.webpack&&e.turbopack)throw new Error("Use only one of --webpack or --turbopack");return e.webpack?{webpack:!0}:e.turbopack?{turbopack:!0}:{}}(n),Ee=async e=>{delete process.env.TURBOPACK,await x();const o={dev:!0,customServer:!0,hostname:s,port:u,dir:J,conf:{...K,basePath:Te,assetPrefix:Te}};e.webpack?o.webpack=!0:e.turbopack&&(o.turbopack=!0),P.beforeCreate(),g=t(o),await g.prepare(),P.afterCreate()};if(Le.webpack)await Ee({webpack:!0});else if(Le.turbopack)try{await Ee({turbopack:!0})}catch(e){if(!Ce(e))throw e;y.warn(o.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await Ee({webpack:!0})}else try{await Ee({})}catch(e){if(!Ce(e))throw e;y.warn(o.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await Ee({webpack:!0})}if(!g)throw new Error("Next.js app failed to initialize");if(Te.endsWith("/")||(Te+="/"),"/"===Te)throw new Error('basePath cannot be equal to "/" or equal to empty string');y.info(o.green("✅ Next.js app prepared successfully")),y.info(o.blue(`🔧 pp-dev plugin configured for template: ${se}`)),y.info(o.blue(`🔧 Base path configured: ${Te}`)),re&&(y.info(o.blue(`🌐 Backend URL: ${re}`)),y.info(o.blue(`🆔 Custom App ID: ${ye}`)));const Fe=g.getRequestHandler(),De=u,$e=s;h=k(async(e,t)=>{const o=e.headers.host;if(!p(o,Pe))return t.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),void t.end(f(o));try{const n=e.url||"/",i=n.split("?")[0];let s=ce(n,!0);if(_e.length>0){const a=i.startsWith("/_next/")||i.startsWith("/__nextjs_");return void F(a?Ae:_e,e,t,()=>{r()})}async function r(){if(i.startsWith(Te))s=ce(n,!0);else{if(i===Te.replace(/\/$/,"")){const e=n.replace(i,Te);return t.writeHead(302,{Location:e}),void t.end()}if(i.startsWith("/_next/")||i.startsWith("/__nextjs_"));else if("/"===i)return t.writeHead(302,{Location:Te}),void t.end()}await Fe(e,t,s)}r()}catch(l){y.error(`Error handling request: ${l instanceof Error?l.message:String(l)}`,{error:l instanceof Error?l:void 0}),t.statusCode=500,t.end("Internal Server Error")}});let je=null;const Ie=(e,t,o)=>{p(e.headers.host,Pe)?je?je(e,t,o):h.listeners("upgrade").every(e=>e===Ie)&&t.destroy():Oe(t)};h.on("upgrade",Ie);let Ne=null;const _e=[],Ae=[];if(!1!==we){const e=new D(ve);$(xe,e,be);const t=j(e,be);_e.push(t)}const Me=(e,t,o)=>{e.url?.startsWith("/@api/")||e.url?.startsWith(T)||e.url?.startsWith(I)?xe(e,t,e=>N(t,e)):o()};if(re||!1===we||(Ae.push(Me),_e.push(Me)),re){const e=new URL(re).host,t=C();Ae.unshift(t),_e.unshift(t),re.startsWith("https://")&&(le.defaultMaxListeners=Math.max(le.defaultMaxListeners,20));const n=_(re,{appId:ye,templateLess:de,disableSSLValidation:fe,v7Features:pe,personalAccessToken:he});Ne=new A(re,n);const s=M(Te,se),r=(e,t,o)=>{s(e,t,o)};Ae.push(r),_e.push(r);const a=oe(Te);if(Ae.push(a),_e.push(a),ue){const e=R(ge),t={middlewares:{use:e=>e},config:{logger:console}},n=H({devServer:t,ttl:e}),i=(e,t,o)=>{n(e,t,o)};_e.push(i),y.info(o.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const l=O(Te),c=U(l,Ne,Object.assign({base:Te,appBase:Te},n,{miHudLess:me})),d=(e,t,o)=>{c(e,t,o)};_e.push(d);const p={middlewares:{use:e=>e},config:{logger:console}},f=V({devServer:p,baseURL:re,proxyIgnore:[...z(Te),"/_next","/__nextjs_","/installHook.js.map"],disableSSLValidation:fe,miAPI:Ne,templateName:se}),u=(e,t,o)=>{f(e,t,o)};_e.push(u),Ae.push(Me),_e.push(Me);const h=G(e=>{const t=e.split("?")[0];return t.startsWith(Te)&&!t.includes("/_next/")},(t,o)=>{const n=Ne.buildPage(t,me),i=ne(n,Te,{backendBaseURL:re,templateLess:de,appId:ye,devPanelPosition:ie.devPanelPosition,devPanelHidden:ie.devPanelHidden,devPanelAutoHide:ie.devPanelAutoHide});return Buffer.from(W(e,o.headers.host??"",i))},{contentType:e=>e.includes("text/html")}),b=(e,t,o)=>{h(e,t,o)};_e.push(b),m=new Ue({allowedHosts:ie.allowedHosts});const P=K?.distDirRoot||(K?.distDir||".next").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),x=!0===K?.ppDevWrapped;let S=P;if(!x)try{const e=await q(i.PHASE_PRODUCTION_BUILD,J);S=e?.distDir||P}catch{}let k,T="0.0.0";try{const e=JSON.parse(ae.readFileSync(w.join(J,"package.json"),"utf-8"));T="string"==typeof e.version?e.version:T,k="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const L=new Z(se,{root:J,backupFolder:w.resolve(J,ie.syncBackupsDir),maxBackups:ie.syncMaxBackups,buildTimeoutMs:ie.syncBuildTimeoutMs,nextBuild:{projectRoot:J,distDir:P,buildDistDir:S,output:K?.output,configWrapped:x,packageVersion:T,packageRepositoryUrl:k}}),E={ws:m.ws,config:{clientInjectionPlugin:{v7Features:pe}}};v=B({server:E,internalServer:xe,distService:L,miAPI:Ne,persistUsers:ie.persistUsers,projectRoot:J,miUrl:re});const F="function"==typeof g?.getUpgradeHandler?g.getUpgradeHandler():null;je=(e,t,o)=>{m?.handleUpgrade(e,t,o)||(F?F(e,t,o):t.destroy())},y.info(o.blue(`🔧 ${_e.length} pp-dev middlewares initialized`)),y.info(o.blue(`🔧 ${Ae.length} essential middlewares for internal routes`)),y.info(o.blue(`🔧 MiAPI initialized for backend: ${re}`)),y.info(o.blue(`🔧 Custom App ID: ${ye}`))}h.listen(De,$e,()=>{const e="0.0.0.0"===$e||"::"===$e,t=`http://${e?"localhost":$e}:${De}`;y.info(o.green(`✅ pp-dev Next.js server running at ${t}`)),y.info(o.blue(`📱 Next.js app accessible at ${t}${Te}`)),e&&y.info(o.blue("🌐 Listening on all addresses. A page opened from another device needs this machine's address in allowedDevOrigins (next.config) for Next's HMR, as with next dev -H 0.0.0.0.")),!1!==we&&y.info(o.cyan(`🔍 Request Inspector: ${t}${T}`)),y.info(o.blue("🔧 Base path handling active")),h.on("connection",e=>{b.add(e),e.on("close",()=>b.delete(e))}),function(e=process){if("function"!=typeof e.send)return;e.stdout.write("",()=>e.send({type:ke},()=>{}))}()})}catch(e){y.error(o.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(y.error(o.red("❌ Next.js Peer Dependency Error:")),y.error(o.red(e.message)),y.error(o.yellow("\n💡 To fix this issue:")),y.error(o.blue(" 1. Install Next.js in your project:")),y.error(o.white(" npm install next@^16")),y.error(o.blue(" 2. Or use yarn:")),y.error(o.white(" yarn add next@^16")),y.error(o.blue(" 3. Or use pnpm:")),y.error(o.white(" pnpm add next@^16")),y.error(o.yellow("\n📖 For more information, see:")),y.error(o.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}})()})}(Xe),function(e){e.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)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,n)=>{_e(n);const i=De(n),s=ie(n);try{const t=n.mode||"production",{config:o}=await Ae({root:e,mode:t,command:"build",configFile:n.config,logLevel:n.logLevel,buildOverrides:s}),r=y(o,{root:e,base:n.base,mode:n.mode,configFile:n.config,logLevel:n.logLevel,clearScreen:n.clearScreen,optimizeDeps:{force:n.force},build:i},!0);if(await P(r),n.changelog){const t=e||process.cwd(),o=r.build?.outDir||"dist";let i="dist-zip";r.ppDevConfig&&(!1===r.ppDevConfig.distZip?i=o:"object"==typeof r.ppDevConfig.distZip&&"string"==typeof r.ppDevConfig.distZip.outDir&&(i=r.ppDevConfig.distZip.outDir)),await Je({changelog:n.changelog,executionRoot:t,newAssetsPath:w.resolve(t,o),backupsDirPath:w.resolve(t,r.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:w.resolve(t,i),logLevel:n.logLevel})}}catch(e){t(n.logLevel).error(o.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{He(e=>t(n.logLevel).info(e))}})}(Xe),function(e){e.command("next-build [root]","build a Next.js app for production (`next build`) and emit VERSION/BUILD-MANIFEST/zip in the same format as `pp-dev build`").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,n)=>{_e(n);const i=t(n.logLevel),s=e?w.resolve(process.cwd(),e):process.cwd(),l=ie(n);process.env[u]="1";try{Q(n.mode||"production",s);const{constants:e}=await te(),t=await(import("next/dist/server/config.js")),c=t.default.default||t["module.exports"].default||t.default,d=await c(e.PHASE_PRODUCTION_BUILD,s);let p=d?.ppDev||{};if(0===Object.keys(p).length){const{getConfig:e}=await import("./index-tD-QICGk.js").then(e=>e.j);p=await e(s)}const{getPkg:f}=await import("./index-tD-QICGk.js").then(e=>e.j),u=f(s).name;r(p,u);const v=a(p,u),b=se(v.distZip,l,g(v.templateName)),y=re(v.versionPlugin,l),P=J(s,d);P&&i.info(o.dim(`[pp-dev] Removed stale dev route types: ${w.relative(s,P)}`)),i.info(o.cyan("[pp-dev] Running `next build`...")),await K(s);const x="string"==typeof d?.distDir&&d.distDir?d.distDir:".next",S=".next"===x?"out":x,k=w.resolve(s,S);if(!ae.existsSync(k)||!ae.statSync(k).isDirectory())throw new Error(`Next.js build output directory not found: ${k}. "next-build" requires "output: 'export'" in next.config (static export).`);const T=JSON.parse(ae.readFileSync(w.join(s,"package.json"),"utf-8"));if(!1!==y&&!1!==y.enabled&&(await ve({outDir:k,packageVersion:"string"==typeof T.version?T.version:"0.0.0",versionFileTemplate:y.versionFileTemplate,packageRepositoryUrl:"string"==typeof T.repository?T.repository:T.repository?.url,enabled:y.enabled}),i.info(o.green(`✅ VERSION / BUILD-MANIFEST written to ${w.relative(s,k)}`))),!1!==b){const e=w.resolve(s,b.outDir),t=h(s,k,b.inDir),n=m(e,b.outFileName,"ZIP output file name");ae.mkdirSync(w.dirname(n),{recursive:!0});const r=await X(t);ae.writeFileSync(n,r),i.info(o.green(`✅ Zip archive written to ${w.relative(s,n)}`))}if(n.changelog){const e=!1!==b?b.outDir:S;await Je({changelog:n.changelog,executionRoot:s,newAssetsPath:k,backupsDirPath:w.resolve(s,v.syncBackupsDir),changelogDestinationPath:w.resolve(s,e),logLevel:n.logLevel})}}catch(e){t(n.logLevel).error(o.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{He(e=>t(n.logLevel).info(e))}})}(Xe),function(e){e.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(e,n,i)=>{_e(i);const{oldAssetsPath:s=e,newAssetsPath:r=n,destination:a=".",filename:l="CHANGELOG.html",logLevel:c}=i,d=process.cwd();s&&r||(t(c).error(o.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const p=w.resolve(d,s),f=w.resolve(d,r),u=w.resolve(d,a),g=new qe({oldAssetsPath:p,newAssetsPath:f,destinationPath:u,changelogFilename:l});await g.generateChangelog()})}(Xe),function(e){e.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(e,n,i)=>{_e(i);const{source:s=e,destination:r=n,fontName:a="icon-font"}=i,l=process.cwd(),c=w.resolve(l,s),d=w.resolve(l,r),p=new Ke({sourceDir:c,outputDir:d,fontName:a}),f=t(i.logLevel);f.info(`Generating icon font from SVG files in ${o.dim(c)}`),await p.generate(),f.info(`Icon font generated and saved to ${o.dim(d)}`)})}(Xe),function(e){e.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,n)=>{_e(n);try{const t=n.mode||"production",{config:o}=await Ae({root:e,mode:t,command:"serve",configFile:n.config,logLevel:n.logLevel}),i=await x(y(o,{root:e,base:n.base,configFile:n.config,logLevel:n.logLevel,mode:n.mode}),"serve");await S(i,n.force,!0)}catch(e){t(n.logLevel).error(o.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}})}(Xe),function(e){e.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,n)=>{_e(n);try{const t=n.mode||"production",{config:o}=await Ae({root:e,mode:t,command:"serve",isPreview:!0,configFile:n.config,logLevel:n.logLevel});(await k(y(o,{root:e,base:n.base,configFile:n.config,logLevel:n.logLevel,mode:n.mode,build:{outDir:n.outDir},preview:{port:n.port,strictPort:n.strictPort,host:n.host,https:n.https,open:n.open}}))).printUrls()}catch(e){t(n.logLevel).error(o.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{He(e=>t(n.logLevel).info(e))}})}(Xe),function(e){e.command("migrate [config]","migrate pp-dev config from 0.x flat format to 1.0 grouped format").option("--dry-run","[boolean] print migrated config without writing any files").option("--format <format>","[string] output format: ts (default), js, json").option("--output <file>","[string] output file path (default: pp-dev.config.ts)").option("--no-backup","[boolean] skip backup of original config file").action(async(e,n)=>{const i=t(n.logLevel),{isLegacyFlatConfig:s,isLegacyPPWatchConfig:r,isAlreadyMigrated:a,migrateLegacyFlatConfig:l,migratePPWatchConfig:c,generateConfigFileContent:d,discoverMigrateSource:p,loadPackageJsonMigrateConfig:f}=await(import("./migrate-CCBRuVfj.js")),u=n.format??"ts",g=!1!==n.backup,h=process.cwd(),m=p(h,e);m||(i.warn(o.yellow("No pp-dev or pp-watch config file found in the current directory.")),i.info(o.blue('Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}, or a "pp-dev" field in package.json')),process.exit(1));const{sourceFile:v,isWatchConfig:b,isPackageJsonConfig:y}=m;i.info(o.blue(`Found config: ${w.relative(h,v)}`));const{getPkg:P}=await import("./index-tD-QICGk.js").then(e=>e.j),x=P();let S,k={};try{if(/\.[cm]?ts$/i.test(v)){const e=await(import("esbuild")),{pathToFileURL:t}=await(import("url")),o=(await e.build({absWorkingDir:h,entryPoints:[v],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,n=`pp-migrate-tmp-${Date.now()}.mjs`;ae.writeFileSync(n,o);try{const e=await(import(t(w.resolve(h,n)).toString()));k=e.default?.default??e.default??e}finally{ae.existsSync(n)&&ae.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(v)){const{pathToFileURL:e}=await(import("url")),t=await(import(e(w.resolve(h,v)).toString()));k=t.default?.default??t.default??t}else y?k=f(v):v.endsWith(".json")&&(k=JSON.parse(ae.readFileSync(v,"utf-8")))}catch(e){i.error(o.red(`Failed to load config file: ${e.message}`)),process.exit(1)}k&&"object"==typeof k||(i.error(o.red("Config file did not export a valid object.")),process.exit(1)),a(k)?(i.info(o.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):b||r(k)?(i.info(o.blue("Detected pp-watch config format → migrating to 1.0")),S=c(k)):s(k)?(i.info(o.blue("Detected 0.x flat config format → migrating to 1.0")),S=l(k,x.name)):(i.warn(o.yellow("Could not detect config format. No known keys found.")),process.exit(1));const T=d(S,u),L=n.output??w.join(h,`pp-dev.config.${u}`);if(n.dryRun&&(i.info(o.green(`\n--- Migrated config (dry-run) → ${w.relative(h,L)} ---\n`)),process.stdout.write(`${T}\n`),process.exit(0)),g&&!y&&ae.existsSync(v)){const e=`${v}.bak`;ae.copyFileSync(v,e),i.info(o.blue(`Backed up original to: ${w.relative(h,e)}`))}ae.writeFileSync(L,T,"utf-8"),i.info(o.green(`✅ Migration complete → ${w.relative(h,L)}`)),y?i.info(o.yellow('You can now remove the "pp-dev" field from package.json.')):v!==L&&ae.existsSync(v)&&i.info(o.yellow(`You can now delete the old config: ${w.relative(h,v)}`))})}(Xe),Xe.help(),Xe.version(i),Xe.parse();export{He as stopProfiler};
|
|
2
2
|
//# sourceMappingURL=cli.js.map
|