@metricinsights/pp-dev 1.3.0 → 1.4.1-beta.1

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/CHANGELOG.md +42 -0
  3. package/dist/cjs/cli.js +1 -1
  4. package/dist/cjs/cli.js.map +1 -1
  5. package/dist/cjs/index-Bi5Lt1-H.js +2 -0
  6. package/dist/cjs/index-Bi5Lt1-H.js.map +1 -0
  7. package/dist/cjs/index.js +1 -1
  8. package/dist/cjs/migrate-x1NtMIxu.js +2 -0
  9. package/dist/cjs/migrate-x1NtMIxu.js.map +1 -0
  10. package/dist/cjs/package.json +1 -1
  11. package/dist/cjs/plugin-pf9CAeeA.js +2 -0
  12. package/dist/cjs/plugin-pf9CAeeA.js.map +1 -0
  13. package/dist/cjs/plugin.js +1 -1
  14. package/dist/cjs/{version-plugin-BXydoNOH.js → version-plugin-CzE3wJA7.js} +2 -2
  15. package/dist/cjs/{version-plugin-BXydoNOH.js.map → version-plugin-CzE3wJA7.js.map} +1 -1
  16. package/dist/client/client.css +1 -1
  17. package/dist/client/client.css.map +1 -1
  18. package/dist/esm/cli.js +1 -1
  19. package/dist/esm/cli.js.map +1 -1
  20. package/dist/esm/index-BO1pevnG.js +2 -0
  21. package/dist/esm/index-BO1pevnG.js.map +1 -0
  22. package/dist/esm/index.js +1 -1
  23. package/dist/esm/migrate-IkEPpASc.js +2 -0
  24. package/dist/esm/migrate-IkEPpASc.js.map +1 -0
  25. package/dist/esm/package.json +1 -1
  26. package/dist/esm/plugin-ncn64ZTK.js +2 -0
  27. package/dist/esm/plugin-ncn64ZTK.js.map +1 -0
  28. package/dist/esm/plugin.js +1 -1
  29. package/dist/esm/{version-plugin-gYCnpPok.js → version-plugin-DhGQovXU.js} +2 -2
  30. package/dist/esm/{version-plugin-gYCnpPok.js.map → version-plugin-DhGQovXU.js.map} +1 -1
  31. package/package.json +1 -1
  32. package/dist/cjs/index-xObEyFiP.js +0 -2
  33. package/dist/cjs/index-xObEyFiP.js.map +0 -1
  34. package/dist/cjs/migrate-r2mXdGLZ.js +0 -2
  35. package/dist/cjs/migrate-r2mXdGLZ.js.map +0 -1
  36. package/dist/cjs/plugin-DXUOFhPN.js +0 -2
  37. package/dist/cjs/plugin-DXUOFhPN.js.map +0 -1
  38. package/dist/esm/index-BDerKo6V.js +0 -2
  39. package/dist/esm/index-BDerKo6V.js.map +0 -1
  40. package/dist/esm/migrate-BYuCtRbI.js +0 -2
  41. package/dist/esm/migrate-BYuCtRbI.js.map +0 -1
  42. package/dist/esm/plugin-CHYaG0Px.js +0 -2
  43. package/dist/esm/plugin-CHYaG0Px.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,45 @@
1
+ ## [1.4.1-beta.1](https://github.com/mi-examples/pp-dev/compare/v1.4.0...v1.4.1-beta.1) (2026-09-02)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **migrate:** read pp-dev config from package.json (PP-4105) ([78c89a5](https://github.com/mi-examples/pp-dev/commit/78c89a5515d6f475b099d8c992f106c814085044))
7
+
8
+ # [1.3.0-beta.3](https://github.com/mi-examples/pp-dev/compare/v1.3.0-beta.2...v1.3.0-beta.3) (2026-09-02)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **migrate:** read pp-dev config from package.json (PP-4105) ([78c89a5](https://github.com/mi-examples/pp-dev/commit/78c89a5515d6f475b099d8c992f106c814085044))
14
+
15
+ # [1.3.0-beta.2](https://github.com/mi-examples/pp-dev/compare/v1.3.0-beta.1...v1.3.0-beta.2) (2026-08-28)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **ci:** run the beta release in-workflow instead of via workflow_run ([69f1282](https://github.com/mi-examples/pp-dev/commit/69f1282ff1f94947c0108c0ad96f82cd65414462))
21
+
22
+ # [1.3.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v1.2.2...v1.3.0-beta.1) (2026-08-28)
23
+
24
+
25
+ ### Bug Fixes
26
+
27
+ * **ci:** allowlist extract-zip's unfixable advisory in audit-all ([670c48f](https://github.com/mi-examples/pp-dev/commit/670c48fec79bef3717ab987dd802daf1cdf361fb))
28
+ * **ci:** force GITHUB_REF to develop in the beta release step ([af5a36d](https://github.com/mi-examples/pp-dev/commit/af5a36dee8bb8fcca4e18a81110f669ecb5eb1ce))
29
+ * **e2e:** stop asserting a hardcoded MI auth-info shape ([6db8edf](https://github.com/mi-examples/pp-dev/commit/6db8edfcff70c61d916a719ca31b8ec9c3d48d4e))
30
+ * **proxy:** rewrite JSON and XML streams, and respect client backpressure ([e653e93](https://github.com/mi-examples/pp-dev/commit/e653e93a5bdba03a0289a495aef361f5df3898bb))
31
+ * **proxy:** rewrite URLs and forward status for streamed responses ([94dc9dd](https://github.com/mi-examples/pp-dev/commit/94dc9dd8e91c84d5b6513071770797a0c8ac1c5e))
32
+ * **security:** reject unvalidated symlinks after zip extraction ([707d8cc](https://github.com/mi-examples/pp-dev/commit/707d8cc08d9ae1bb0955a111307253ed98d6b70c))
33
+ * **variables-editor:** allow manual input for non-static list columns, treat null list value as empty array ([368e218](https://github.com/mi-examples/pp-dev/commit/368e218f4a928ab5daf756e8319c4b0dff5fa31d))
34
+ * **variables-editor:** guard missing browser APIs, update stale test selectors ([21fa412](https://github.com/mi-examples/pp-dev/commit/21fa412ded827a9266aa4d8e8d5d524e8c36c748)), closes [#content](https://github.com/mi-examples/pp-dev/issues/content)
35
+ * **variables-editor:** render {id,text} options correctly in list-column select widgets ([dfb031c](https://github.com/mi-examples/pp-dev/commit/dfb031c69c53f11ec5e445f3405ab6b451154d75))
36
+
37
+
38
+ ### Features
39
+
40
+ * **ui:** improve variables editor schema/values UX ([6610ee5](https://github.com/mi-examples/pp-dev/commit/6610ee54056ab6c6339fc5b2549f811483ac1712))
41
+ * **variables-editor:** import variable values from another page ([5c5bf2e](https://github.com/mi-examples/pp-dev/commit/5c5bf2eaf63499d3abb4cdc07645f378b9bdb533))
42
+
1
43
  # [1.2.0-beta.3](https://github.com/mi-examples/pp-dev/compare/v1.2.0-beta.2...v1.2.0-beta.3) (2026-08-07)
2
44
 
3
45
 
package/dist/CHANGELOG.md CHANGED
@@ -1,3 +1,45 @@
1
+ ## [1.4.1-beta.1](https://github.com/mi-examples/pp-dev/compare/v1.4.0...v1.4.1-beta.1) (2026-09-02)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **migrate:** read pp-dev config from package.json (PP-4105) ([78c89a5](https://github.com/mi-examples/pp-dev/commit/78c89a5515d6f475b099d8c992f106c814085044))
7
+
8
+ # [1.3.0-beta.3](https://github.com/mi-examples/pp-dev/compare/v1.3.0-beta.2...v1.3.0-beta.3) (2026-09-02)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **migrate:** read pp-dev config from package.json (PP-4105) ([78c89a5](https://github.com/mi-examples/pp-dev/commit/78c89a5515d6f475b099d8c992f106c814085044))
14
+
15
+ # [1.3.0-beta.2](https://github.com/mi-examples/pp-dev/compare/v1.3.0-beta.1...v1.3.0-beta.2) (2026-08-28)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **ci:** run the beta release in-workflow instead of via workflow_run ([69f1282](https://github.com/mi-examples/pp-dev/commit/69f1282ff1f94947c0108c0ad96f82cd65414462))
21
+
22
+ # [1.3.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v1.2.2...v1.3.0-beta.1) (2026-08-28)
23
+
24
+
25
+ ### Bug Fixes
26
+
27
+ * **ci:** allowlist extract-zip's unfixable advisory in audit-all ([670c48f](https://github.com/mi-examples/pp-dev/commit/670c48fec79bef3717ab987dd802daf1cdf361fb))
28
+ * **ci:** force GITHUB_REF to develop in the beta release step ([af5a36d](https://github.com/mi-examples/pp-dev/commit/af5a36dee8bb8fcca4e18a81110f669ecb5eb1ce))
29
+ * **e2e:** stop asserting a hardcoded MI auth-info shape ([6db8edf](https://github.com/mi-examples/pp-dev/commit/6db8edfcff70c61d916a719ca31b8ec9c3d48d4e))
30
+ * **proxy:** rewrite JSON and XML streams, and respect client backpressure ([e653e93](https://github.com/mi-examples/pp-dev/commit/e653e93a5bdba03a0289a495aef361f5df3898bb))
31
+ * **proxy:** rewrite URLs and forward status for streamed responses ([94dc9dd](https://github.com/mi-examples/pp-dev/commit/94dc9dd8e91c84d5b6513071770797a0c8ac1c5e))
32
+ * **security:** reject unvalidated symlinks after zip extraction ([707d8cc](https://github.com/mi-examples/pp-dev/commit/707d8cc08d9ae1bb0955a111307253ed98d6b70c))
33
+ * **variables-editor:** allow manual input for non-static list columns, treat null list value as empty array ([368e218](https://github.com/mi-examples/pp-dev/commit/368e218f4a928ab5daf756e8319c4b0dff5fa31d))
34
+ * **variables-editor:** guard missing browser APIs, update stale test selectors ([21fa412](https://github.com/mi-examples/pp-dev/commit/21fa412ded827a9266aa4d8e8d5d524e8c36c748)), closes [#content](https://github.com/mi-examples/pp-dev/issues/content)
35
+ * **variables-editor:** render {id,text} options correctly in list-column select widgets ([dfb031c](https://github.com/mi-examples/pp-dev/commit/dfb031c69c53f11ec5e445f3405ab6b451154d75))
36
+
37
+
38
+ ### Features
39
+
40
+ * **ui:** improve variables editor schema/values UX ([6610ee5](https://github.com/mi-examples/pp-dev/commit/6610ee54056ab6c6339fc5b2549f811483ac1712))
41
+ * **variables-editor:** import variable values from another page ([5c5bf2e](https://github.com/mi-examples/pp-dev/commit/5c5bf2eaf63499d3abb4cdc07645f378b9bdb533))
42
+
1
43
  # [1.2.0-beta.3](https://github.com/mi-examples/pp-dev/compare/v1.2.0-beta.2...v1.2.0-beta.3) (2026-08-07)
2
44
 
3
45
 
package/dist/cjs/cli.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("path"),t=require("fs"),o=require("node:events"),n=require("node:perf_hooks"),i=require("chokidar"),r=require("cac"),s=require("./plugin-DXUOFhPN.js"),a=require("./index-xObEyFiP.js"),l=require("vite"),c=require("url"),d=require("dir-compare"),p=require("diff-match-patch"),f=require("isbinaryfile"),u=require("os"),g=require("crypto"),h=require("extract-zip"),m=require("svgtofont"),b=require("ws");require("http-proxy-middleware"),require("picocolors"),require("node:string_decoder"),require("axios"),require("node:http"),require("node:https"),require("jsdom"),require("process"),require("child_process"),require("node:path"),require("jszip"),require("module"),require("memory-cache"),require("zlib"),require("express"),require("node:crypto"),require("./helpers.js"),require("ejs");const v=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function w(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const o in e)t[o]=e[o];return t.default=e,Object.freeze(t)}const y=w(e),P=w(t),x=w(d),S=v(p),E=w(u),T=w(g),L=v(h),k=v(m);function D(e){return null!=e&&!1!==e}let I=null;const F=[{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 _=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class ${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:t,newAssetsPath:o,destinationPath:n,changelogTemplate:i,diffFileTemplateHandler:r,diffLineTemplateHandler:a,changelogFilename:l,contextLines:c}=e;if(this.logger=s.createLogger(),!t||!o||!n)throw new Error("Previous assets path, current assets path and destination path are required");if(t===o)throw new Error("Previous and current assets paths must be different");if(!this.isExists(t))throw new Error(`Previous assets path ${t} does not exist`);if(!this.isExists(o))throw new Error(`Current assets path ${o} does not exist`);if(this.isZipFile(t)){const e=y.resolve(E.tmpdir(),T.createHash("md5").update(t).digest("hex"));this.oldAssetsPath=this.unzipFile(t,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(t))throw new Error(`Invalid previous assets path ${t}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(t);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(o)){const e=y.resolve(E.tmpdir(),T.createHash("md5").update(o).digest("hex"));this.newAssetsPath=this.unzipFile(o,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(o))throw new Error(`Invalid current assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${o} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=n,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",i&&(this.templateIsValid(i)?this.changelogTemplate=i:this.logger.warn(s.colors.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof a&&(this.diffLineTemplateHandler=a),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return P.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return P.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===P.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){P.existsSync(e)||P.mkdirSync(e,{recursive:!0})}async unzipFile(e,t){P.rmSync(t,{force:!0,recursive:!0}),await L(e,{dir:t}),await s.rejectSymlinks(t)}normalizeAssetFolderPath(e){const t=P.readdirSync(e);return 1===t.length&&P.lstatSync(y.join(e,t[0])).isDirectory()?this.normalizeAssetFolderPath(y.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?"-":" "}">${r=o??"",r.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var r}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(s.colors.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await x.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(_.test(e)&&(e=e.replace(_,"$1$3")),_.test(t)&&(t=t.replace(_,"$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 S,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let r=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:r+o+1,lineType:t})).slice(0,n);return-1!==t&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const t=this.pathToPosix(y.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(y.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?y.join(e.path1,e.name1):null,o=e.path2&&e.name2?y.join(e.path2,e.name2):null,n=this.pathToPosix(y.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(y.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(y.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await f.isBinaryFile(t)||await f.isBinaryFile(o)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(P.readFileSync(t,"utf-8"),P.readFileSync(o,"utf-8"))))}return""}async generateChangelog(){this.logger.info(s.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),t=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(s.colors.green("Writing changelog file"));const o=this.changelogTemplate.split("%FILES%");o.splice(1,0,t);const n=o.join("");P.writeFileSync(y.join(this.destinationPath,this.changelogFilename),n),this.logger.info(s.colors.green(`Changelog file written to ${y.join(this.destinationPath,this.changelogFilename)}`))}}class j{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await k({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class A{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new b.WebSocketServer({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===b.WebSocket.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===s.PP_DEV_HMR_WS_PATH&&(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){s.createLogger().error(`ws handler for "${o.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===b.WebSocket.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 C=r.cac("pp-dev");function N(e,t,o){const n=[...s.PP_DEV_CONFIG_NAMES,"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(t=>y.join(e,t)),r=i.watch(n,{ignored:e=>{const t=y.basename(e);return/(^|[\/\\])\../.test(e)&&!t.startsWith(".env")&&!t.startsWith(".pp-dev")&&!t.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let a=null;return r.on("change",n=>{o(s.colors.blue(`🔧 Config file changed: ${y.relative(e,n)}`)),a&&clearTimeout(a),a=setTimeout(async()=>{try{o(s.colors.yellow("🔄 Restarting dev server due to config change...")),await t()}catch(e){o(s.colors.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{o(s.colors.red(`❌ Config watcher error: ${e}`))}),{watcher:r,restartCallback:t,logger:o}}function R(e){e.watcher&&e.watcher.close()}function M(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 O(e){const{changelog:t,executionRoot:o,newAssetsPath:n,backupsDirPath:i,changelogDestinationPath:r,logLevel:a}=e;let l;if("string"==typeof t)l=y.resolve(o,t);else{if(!P.existsSync(i))return void s.createLogger(a).warn(s.colors.yellow("backups directory not found, skipping changelog generation"));const e=P.readdirSync(i,{withFileTypes:!0});if(!e.length)return void s.createLogger(a).warn(s.colors.yellow("no backups found, skipping changelog generation"));const t=e.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!t.length)return void s.createLogger(a).warn(s.colors.yellow("no ZIP backups found, skipping changelog generation"));const o=t.reduce((e,t)=>P.statSync(y.resolve(i,e.name)).mtimeMs>P.statSync(y.resolve(i,t.name)).mtimeMs?e:t).name;l=y.resolve(i,o)}const c=new $({oldAssetsPath:l,newAssetsPath:n,destinationPath:r});await c.generateChangelog()}let q=global.__pp_dev_profile_session,V=0;const H=e=>{if(q)return new Promise((t,o)=>{q.post("Profiler.stop",(n,{profile:i})=>{if(n)o(n);else{const o=y.resolve(`./pp-dev-profile-${V++}.cpuprofile`);P.writeFileSync(o,JSON.stringify(i)),e(s.colors.yellow(`CPU profile written to ${s.colors.white(s.colors.dim(o))}`)),q=void 0,t()}})})},z=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function U(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}C.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"),C.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);let o=null,i=null,r=!1;const c=e?y.resolve(process.cwd(),e):process.cwd(),d=s.createLogger(t.logLevel),p=async()=>{if(!r){r=!0;try{o&&(d.info(s.colors.yellow("🛑 Stopping existing dev server...")),await o.close(),o=null);const{clearConfigCache:f,getConfig:u}=await Promise.resolve().then(()=>require("./index-xObEyFiP.js")).then(e=>e.config);f();const{createServer:g}=await import("vite"),h=t.mode||"development",m=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(h,m);const b=await l.loadConfigFromFile({mode:h,command:"serve"},t.config,e,t.logLevel);let v=await a.getViteConfig(void 0,{mode:h,root:m});if(b){const{plugins:e,...t}=b.config;v=l.mergeConfig(v,t)}if(o=await g(l.mergeConfig(v,{root:e,base:t.base,mode:t.mode,configFile:t.config,logLevel:t.logLevel,clearScreen:t.clearScreen,optimizeDeps:{force:t.force},server:U(t),customLogger:d},!0)),!o.config.base||"/"===o.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!o.httpServer)throw new Error("HTTP server not available");await o.listen();const w=global.__pp_dev_start_time??!1,P=w?s.colors.dim(`ready in ${s.colors.reset(s.colors.bold(Math.ceil(n.performance.now()-w)))} ms`):"";d.info(`\n ${s.colors.green(`${s.colors.bold("PP-DEV")} v${s.VERSION}`)} ${P}\n`),o.printUrls();const x=await u(m);if(!1!==x.inspector?.enabled){const e=o.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${o.config.server.port??5173}`;d.info(`\n ${s.colors.cyan("🔍 Request Inspector")} ${s.colors.dim(t+s.INSPECTOR_PATH)}\n`)}!function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=s.createLogger();t.print&&o.info(s.colors.dim(s.colors.green(" ➜"))+s.colors.dim(" press ")+s.colors.bold("h")+s.colors.dim(" to show help"));const n=(t.customShortcuts??[]).filter(D).concat(F);I?.(),I=null;let i=!1;const r=process.stdin.isPaused(),a=process.stdin,l=Boolean(a.isRaw),c=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(["",s.colors.bold(" Shortcuts"),...n.map(e=>s.colors.dim(" press ")+s.colors.bold(e.key)+s.colors.dim(` to ${e.description}`))].join("\n"));const r=n.find(e=>e.key===t);r&&(i=!0,await r.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",c).setEncoding("utf8").resume();const d=e.httpServer,p=()=>{I===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),r&&process.stdin.pause(),I=null)};I=p,d.on("close",p)}(o,{print:!0,customShortcuts:[...q?[{key:"p",description:"start/stop the profiler",async action(e){if(q)await H(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{q=new e.Session,q.connect(),q.post("Profiler.enable",()=>{q?.post("Profiler.start",()=>{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("/")}`}})}}]}),i||(i=N(c,p,d.info),d.info(s.colors.blue("🔧 Config file watcher started"))),r=!1}catch(e){r=!1,d.error(s.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),H(d.info),process.exit(1)}}},f=async e=>{d.info(s.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{i&&(R(i),i=null),o&&(await o.close(),o=null),H(d.info),d.info(s.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(s.colors.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(s.colors.red(`❌ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(s.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),f("unhandledRejection")}),await p()}),C.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(e,t)=>{z(t);let n=null,i=null,r=null,l=null,d=!1;const p=s.createLogger(),f=async()=>{if(!d){d=!0;try{const{next:g,constants:h}=await a.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:m}=h;r&&(await r.close(),r=null),i&&(p.info(s.colors.yellow("🛑 Stopping existing Next.js server...")),await new Promise(e=>{i.close(()=>{i=null,e()})})),n&&"function"==typeof n.close&&(await n.close(),n=null);const{clearConfigCache:b}=await Promise.resolve().then(()=>require("./index-xObEyFiP.js")).then(e=>e.config);b();const{join:v,basename:w}=await import("path"),{createServer:x}=await import("http"),S=await import("next/dist/server/config.js"),E=S.default.default||S["module.exports"].default||S.default,T=U(t),L=e?v(process.cwd(),e):process.cwd();a.loadPPDevEnv(t.mode||"development",L),p.info(L);const k=await E(m,L);let D=k?.ppDev||{};if(0===Object.keys(D).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-xObEyFiP.js")).then(e=>e.config),t=await e(L);Object.keys(t).length>0?(D=t,p.info(s.colors.blue("🔧 Loaded pp-dev config from standalone config file"))):p.info(s.colors.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){p.info(s.colors.yellow("⚠️ Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else p.info(s.colors.blue("🔧 Loaded pp-dev config from Next.js config"));let I=null;try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-xObEyFiP.js")).then(e=>e.config);I=e(L).name}catch{I=w(L)}s.validatePPDevConfig(D,I??"");const F=s.normalizePPDevConfig(D,I??""),_=F.backendBaseURL??"http://localhost:8080",$=F.templateLess,j=F.v7Features,C=F.disableSSLValidation,O=F.enableProxyCache,q=F.proxyCacheTTL,V=F.personalAccessToken,H=F.miHudLess,z=F.inspectorEnabled,W=F.inspectorMaxMemory,B=F.inspectorCaptureLimit,Z=F.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,G=k?.basePath;let X="";G?X=G:(X=$?s.PATH_PAGE_PREFIX:j?s.PATH_TEMPLATE_LOCAL_PREFIX:s.PATH_TEMPLATE_PREFIX,X+=`/${I}`);const J=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}:{}}(t),K=async e=>{delete process.env.TURBOPACK,n&&"function"==typeof n.close&&(await n.close(),n=null);const t={dev:!0,customServer:!0,hostname:T.host||"localhost",port:T.port,dir:L,conf:{...k,basePath:X,assetPrefix:X}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),n=g(t),await n.prepare()};if(J.webpack)await K({webpack:!0});else if(J.turbopack)try{await K({turbopack:!0})}catch(e){if(!M(e))throw e;p.warn(s.colors.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await K({webpack:!0})}else try{await K({})}catch(e){if(!M(e))throw e;p.warn(s.colors.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await K({webpack:!0})}if(!n)throw new Error("Next.js app failed to initialize");if(X.endsWith("/")||(X+="/"),"/"===X)throw new Error('basePath cannot be equal to "/" or equal to empty string');p.info(s.colors.green("✅ Next.js app prepared successfully")),p.info(s.colors.blue(`🔧 pp-dev plugin configured for template: ${I}`)),p.info(s.colors.blue(`🔧 Base path configured: ${X}`)),_&&(p.info(s.colors.blue(`🌐 Backend URL: ${_}`)),p.info(s.colors.blue(`🆔 Custom App ID: ${Z}`)));const Y=n.getRequestHandler(),Q="number"==typeof T.port?T.port:3e3,ee="string"==typeof T.host?T.host||"0.0.0.0":"localhost",te=new Set;i=x(async(e,t)=>{try{const o=e.url||"/",n=o.split("?")[0];let i=c.parse(o,!0);if(ne.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(ie.length>0){let l=0;const d=()=>{if(l>=ie.length)return void r();const o=ie[l];l++,o(e,t,d)};return void d()}return void r()}let s=0;const a=()=>{if(s>=ne.length)return void r();const o=ne[s];s++,o(e,t,a)};return void a()}async function r(){if(n.startsWith(X))i=c.parse(o,!0);else{if(n===X.replace(/\/$/,"")){const e=o.replace(n,X);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:X}),void t.end()}await Y(e,t,i)}r()}catch(f){p.error(`Error handling request: ${f instanceof Error?f.message:String(f)}`,{error:f instanceof Error?f:void 0}),t.statusCode=500,t.end("Internal Server Error")}});let oe=null,ne=[],ie=[];if(!1!==z){const e=new s.RequestStore(W);s.registerInspectorRoutes(s.internalServer,e,B);const t=s.createRequestCaptureMiddleware(e,B);ne.push(t)}if(_){const e=new URL(_).host;_.startsWith("https://")&&(o.EventEmitter.defaultMaxListeners=Math.max(o.EventEmitter.defaultMaxListeners,20));const t={headers:{host:e,referer:_,origin:_.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:Z,templateLess:$,disableSSLValidation:C,v7Features:j,personalAccessToken:V??process.env.MI_ACCESS_TOKEN};oe=new s.MiAPI(_,t);const l=s.initPPRedirect(X,I??void 0),c=(e,t,o)=>{l(e,t,o)};ie.push(c),ne.push(c);const d=a.createDevPanelAssetMiddleware(X);if(ie.push(d),ne.push(d),O){let e=+q;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},o=s.initProxyCache(t),n=(e,t,n)=>{o(e,t,n)};ne.push(n),p.info(s.colors.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const f=new RegExp(`^((${u=X,u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),g=s.initLoadPPData(f,oe,Object.assign({base:X},t,{miHudLess:H})),m=(e,t,o)=>{g(e,t,o)};ne.push(m);const b=X.endsWith("/")?X.substring(0,X.length-1):X,v={middlewares:{use:e=>e},config:{logger:console}},x=s.initProxy({devServer:v,baseURL:_,proxyIgnore:["/@vite","/@metricinsights","/@",b,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:C,miAPI:oe,templateName:I??void 0}),S=(e,t,o)=>{x(e,t,o)};ne.push(S);const T=s.internalServer,D=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(s.INSPECTOR_PATH)||e.url?.startsWith(s.VARIABLES_EDITOR_PATH)){return void T(e,t,()=>{})}o()};ie.push(D),ne.push(D);const N=s.initRewriteResponse(e=>{const t=e.split("?")[0];return t.startsWith(X)&&!t.includes("/_next/")},(t,o)=>{const n=oe.buildPage(t,H),i=a.injectDevPanel(n,X,{backendBaseURL:_,templateLess:$,appId:Z,devPanelPosition:F.devPanelPosition,devPanelHidden:F.devPanelHidden,devPanelAutoHide:F.devPanelAutoHide});return Buffer.from(s.urlReplacer(e,o.headers.host??"",i))}),R=(e,t,o)=>{N(e,t,o)};ne.push(R),r=new A;let M=k?.distDir;try{process.env[s.PP_DEV_NEXT_BUILD_ENV_VAR]="1";const e=await E(h.PHASE_PRODUCTION_BUILD,L);M=e?.distDir??M}catch{}const z=(M??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),U=z&&".next"!==z?z:"out";let W,B="0.0.0";try{const e=JSON.parse(P.readFileSync(y.join(L,"package.json"),"utf-8"));B="string"==typeof e.version?e.version:B,W="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const G=new s.DistService(I??w(L),{root:L,backupFolder:y.resolve(L,F.syncBackupsDir),nextBuild:{projectRoot:L,distDir:U,packageVersion:B,packageRepositoryUrl:W}}),J={ws:r.ws,config:{clientInjectionPlugin:{v7Features:j}}};new s.ClientService(J,{distService:G,miAPI:oe}),s.registerVariablesEditorRoutes(s.internalServer,{distService:G,miAPI:oe});const K="function"==typeof n?.getUpgradeHandler?n.getUpgradeHandler():null;i.on("upgrade",(e,t,o)=>{r?.handleUpgrade(e,t,o)||(K?K(e,t,o):t.destroy())}),p.info(s.colors.blue(`🔧 ${ne.length} pp-dev middlewares initialized`)),p.info(s.colors.blue(`🔧 ${ie.length} essential middlewares for internal routes`)),p.info(s.colors.blue(`🔧 MiAPI initialized for backend: ${_}`)),p.info(s.colors.blue(`🔧 Custom App ID: ${Z}`))}i.listen(Q,ee,()=>{p.info(s.colors.green(`✅ pp-dev Next.js server running at http://${ee}:${Q}`)),p.info(s.colors.blue(`📱 Next.js app accessible at http://${ee}:${Q}${X}`)),!1!==z&&p.info(s.colors.cyan(`🔍 Request Inspector: http://${ee}:${Q}${s.INSPECTOR_PATH}`)),p.info(s.colors.blue("🔧 Base path handling active")),l||(l=N(L,f,p.info),p.info(s.colors.blue("🔧 Config file watcher started"))),i.on("connection",e=>{te.add(e),e.on("close",()=>te.delete(e))});const e=async e=>{p.info(s.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));const t=setTimeout(()=>{p.info(s.colors.yellow("⏰ Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{l&&(R(l),l=null);for(const e of Array.from(te))e.destroy();te.clear(),r&&(await r.close(),r=null),await new Promise(e=>{i.close(()=>{p.info(s.colors.yellow("🛑 HTTP server closed")),e()})}),n&&"function"==typeof n.close&&(await n.close(),p.info(s.colors.yellow("🛑 Next.js app closed"))),clearTimeout(t),p.info(s.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(t),p.error(s.colors.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,p.info(s.colors.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=>{p.error(s.colors.red(`❌ Uncaught Exception: ${t}`)),e("uncaughtException")}),t.on("unhandledRejection",(t,o)=>{p.error(s.colors.red(`❌ Unhandled Rejection at: ${o}, reason: ${t}`)),e("unhandledRejection")}),p.info(s.colors.green("✅ Process event handlers registered successfully"))}catch(e){p.warn(s.colors.yellow(`⚠️ Failed to register process event handlers: ${e}`))}else p.warn(s.colors.yellow("⚠️ process.on is not available, graceful shutdown handlers will not be registered")),p.info(s.colors.blue("💡 This might be due to bundling or environment constraints"))}),d=!1}catch(e){d=!1,p.error(s.colors.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(p.error(s.colors.red("❌ Next.js Peer Dependency Error:")),p.error(s.colors.red(e.message)),p.error(s.colors.yellow("\n💡 To fix this issue:")),p.error(s.colors.blue(" 1. Install Next.js in your project:")),p.error(s.colors.white(" npm install next@^16")),p.error(s.colors.blue(" 2. Or use yarn:")),p.error(s.colors.white(" yarn add next@^16")),p.error(s.colors.blue(" 3. Or use pnpm:")),p.error(s.colors.white(" pnpm add next@^16")),p.error(s.colors.yellow("\n📖 For more information, see:")),p.error(s.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var u}},u=async e=>{p.info(s.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{l&&(R(l),l=null),r&&(await r.close(),r=null),i&&await new Promise(e=>{i.close(()=>{i=null,e()})}),n&&"function"==typeof n.close&&(await n.close(),n=null),p.info(s.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){p.error(s.colors.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),process.on("uncaughtException",e=>{p.error(s.colors.red(`❌ Uncaught Exception: ${e}`)),u("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{p.error(s.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),u("unhandledRejection")}),await f()}),C.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,t)=>{z(t);const o=U(t),n=a.resolveBuildCliOverrides(t);try{const i=t.mode||"production",r=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(i,r);const s=await l.loadConfigFromFile({mode:i,command:"build"},t.config,e,t.logLevel);let c=await a.getViteConfig(n,{mode:i,root:r});if(s){const{plugins:e,...t}=s.config;c=l.mergeConfig(c,t)}const d=l.mergeConfig(c,{root:e,base:t.base,mode:t.mode,configFile:t.config,logLevel:t.logLevel,clearScreen:t.clearScreen,optimizeDeps:{force:t.force},build:o},!0);if(await l.build(d),o.changelog){const n=e||process.cwd(),i=d.build?.outDir||"dist";let r="dist-zip";d.ppDevConfig&&(!1===d.ppDevConfig.distZip?r=i:"object"==typeof d.ppDevConfig.distZip&&"string"==typeof d.ppDevConfig.distZip.outDir&&(r=d.ppDevConfig.distZip.outDir)),await O({changelog:o.changelog,executionRoot:n,newAssetsPath:y.resolve(n,i),backupsDirPath:y.resolve(n,d.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:y.resolve(n,r),logLevel:t.logLevel})}}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>s.createLogger(t.logLevel).info(e))}}),C.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,t)=>{z(t);const o=s.createLogger(t.logLevel),n=e?y.resolve(process.cwd(),e):process.cwd(),i=a.resolveBuildCliOverrides(t);process.env[s.PP_DEV_NEXT_BUILD_ENV_VAR]="1";try{a.loadPPDevEnv(t.mode||"production",n);const{constants:e}=await a.safeNextImport(),r=await import("next/dist/server/config.js"),l=r.default.default||r["module.exports"].default||r.default,c=await l(e.PHASE_PRODUCTION_BUILD,n);let d,p=c?.ppDev||{};if(0===Object.keys(p).length){const{getConfig:e}=await Promise.resolve().then(()=>require("./index-xObEyFiP.js")).then(e=>e.config);p=await e(n)}try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-xObEyFiP.js")).then(e=>e.config);d=e(n).name}catch{d=y.basename(n)}const f=s.normalizePPDevConfig(p,d),u=a.applyDistZipOverride(f.distZip,i,s.createDefaultZipFileName(d)),g=a.applyVersionManifestOverride(f.versionPlugin,i);o.info(s.colors.cyan("[pp-dev] Running `next build`...")),await s.runNextBuildProcess(n);const h="string"==typeof c?.distDir&&c.distDir?c.distDir:".next",m=".next"===h?"out":h,b=y.resolve(n,m);if(!P.existsSync(b)||!P.statSync(b).isDirectory())throw new Error(`Next.js build output directory not found: ${b}. "next-build" requires "output: 'export'" in next.config (static export).`);const v=JSON.parse(P.readFileSync(y.join(n,"package.json"),"utf-8"));if(!1!==g&&!1!==g.enabled&&(s.writeBuildVersionManifest({outDir:b,packageVersion:"string"==typeof v.version?v.version:"0.0.0",versionFileTemplate:g.versionFileTemplate,packageRepositoryUrl:"string"==typeof v.repository?v.repository:v.repository?.url,enabled:g.enabled}),o.info(s.colors.green(`✅ VERSION / BUILD-MANIFEST written to ${y.relative(n,b)}`))),!1!==u){const e=y.resolve(n,u.outDir),t=u.inDir?y.resolve(b,u.inDir):b,i=s.resolveOutputFilePath(e,u.outFileName,"ZIP output file name");P.mkdirSync(y.dirname(i),{recursive:!0});const r=await s.zipDirectoryToBuffer(t);P.writeFileSync(i,r),o.info(s.colors.green(`✅ Zip archive written to ${y.relative(n,i)}`))}if(t.changelog){const e=!1!==u?u.outDir:m;await O({changelog:t.changelog,executionRoot:n,newAssetsPath:b,backupsDirPath:y.resolve(n,f.syncBackupsDir),changelogDestinationPath:y.resolve(n,e),logLevel:t.logLevel})}}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>s.createLogger(t.logLevel).info(e))}}),C.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,t,o)=>{z(o);const{oldAssetsPath:n=e,newAssetsPath:i=t,destination:r=".",filename:a="CHANGELOG.html",logLevel:l}=o,c=process.cwd();n&&i||(s.createLogger(l).error(s.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=y.resolve(c,n),p=y.resolve(c,i),f=y.resolve(c,r),u=new $({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await u.generateChangelog()}),C.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,t,o)=>{z(o);const{source:n=e,destination:i=t,fontName:r="icon-font"}=o,a=process.cwd(),l=y.resolve(a,n),c=y.resolve(a,i),d=new j({sourceDir:l,outputDir:c,fontName:r}),p=s.createLogger(o.logLevel);p.info(`Generating icon font from SVG files in ${s.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${s.colors.dim(c)}`)}),C.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);try{const o=t.mode||"production",n=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(o,n);const i=await l.loadConfigFromFile({mode:o,command:"build"},t.config,e,t.logLevel);let r=await a.getViteConfig(void 0,{mode:o,root:n});if(i){const{plugins:e,...t}=i.config;r=l.mergeConfig(r,t)}const s=await l.resolveConfig(l.mergeConfig(r,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode}),"serve");await l.optimizeDeps(s,t.force,!0)}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),C.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,t)=>{z(t);try{const o=t.mode||"production",n=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(o,n);const i=await l.loadConfigFromFile({mode:o,command:"build"},t.config,e,t.logLevel);let r=await a.getViteConfig(void 0,{mode:o,root:n});if(i){const{plugins:e,...t}=i.config;r=l.mergeConfig(r,t)}(await l.preview(l.mergeConfig(r,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode,build:{outDir:t.outDir},preview:{port:t.port,strictPort:t.strictPort,host:t.host,https:t.https,open:t.open}}))).printUrls()}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>s.createLogger(t.logLevel).info(e))}}),C.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,t)=>{const o=s.createLogger(t.logLevel),{isLegacyFlatConfig:n,isLegacyPPWatchConfig:i,isAlreadyMigrated:r,migrateLegacyFlatConfig:a,migratePPWatchConfig:l,generateConfigFileContent:c}=await Promise.resolve().then(()=>require("./migrate-r2mXdGLZ.js")),d=t.format??"ts",p=!1!==t.backup,f=process.cwd(),u=[".pp-watch.config.ts",".pp-watch.config.js",".pp-watch.config.json","pp-watch.config.ts","pp-watch.config.js","pp-watch.config.json"];let g=e??null,h=!1;if(!g){for(const e of s.PP_DEV_CONFIG_NAMES)if(P.existsSync(y.join(f,e))){g=y.join(f,e);break}if(!g)for(const e of u)if(P.existsSync(y.join(f,e))){g=y.join(f,e),h=!0;break}}g||(o.warn(s.colors.yellow("No pp-dev or pp-watch config file found in the current directory.")),o.info(s.colors.blue("Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}")),process.exit(1)),o.info(s.colors.blue(`Found config: ${y.relative(f,g)}`));const{getPkg:m}=await Promise.resolve().then(()=>require("./index-xObEyFiP.js")).then(e=>e.config),b=m();let v,w={};try{if(/\.[cm]?ts$/i.test(g)){const e=await import("esbuild"),{pathToFileURL:t}=await import("url"),o=(await e.build({absWorkingDir:f,entryPoints:[g],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`;P.writeFileSync(n,o);try{const e=await import(t(y.resolve(f,n)).toString());w=e.default?.default??e.default??e}finally{P.existsSync(n)&&P.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(g)){const{pathToFileURL:e}=await import("url"),t=await import(e(y.resolve(f,g)).toString());w=t.default?.default??t.default??t}else g.endsWith(".json")&&(w=JSON.parse(P.readFileSync(g,"utf-8")))}catch(e){o.error(s.colors.red(`Failed to load config file: ${e.message}`)),process.exit(1)}w&&"object"==typeof w||(o.error(s.colors.red("Config file did not export a valid object.")),process.exit(1)),r(w)?(o.info(s.colors.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):h||i(w)?(o.info(s.colors.blue("Detected pp-watch config format → migrating to 1.0")),v=l(w)):n(w)?(o.info(s.colors.blue("Detected 0.x flat config format → migrating to 1.0")),v=a(w,b.name)):(o.warn(s.colors.yellow("Could not detect config format. No known keys found.")),process.exit(1));const x=c(v,d),S=t.output??y.join(f,`pp-dev.config.${d}`);if(t.dryRun&&(o.info(s.colors.green(`\n--- Migrated config (dry-run) → ${y.relative(f,S)} ---\n`)),process.exit(0)),p&&P.existsSync(g)){const e=`${g}.bak`;P.copyFileSync(g,e),o.info(s.colors.blue(`Backed up original to: ${y.relative(f,e)}`))}P.writeFileSync(S,x,"utf-8"),o.info(s.colors.green(`✅ Migration complete → ${y.relative(f,S)}`)),g!==S&&P.existsSync(g)&&o.info(s.colors.yellow(`You can now delete the old config: ${y.relative(f,g)}`))}),C.help(),C.version(s.VERSION),C.parse(),exports.stopProfiler=H;
1
+ "use strict";const e=require("path"),t=require("fs"),o=require("node:events"),n=require("node:perf_hooks"),i=require("chokidar"),r=require("cac"),s=require("./plugin-pf9CAeeA.js"),a=require("./index-Bi5Lt1-H.js"),l=require("vite"),c=require("url"),d=require("dir-compare"),p=require("diff-match-patch"),f=require("isbinaryfile"),u=require("os"),g=require("crypto"),h=require("extract-zip"),m=require("svgtofont"),v=require("ws");require("http-proxy-middleware"),require("picocolors"),require("node:string_decoder"),require("axios"),require("node:http"),require("node:https"),require("jsdom"),require("process"),require("child_process"),require("node:path"),require("jszip"),require("module"),require("memory-cache"),require("zlib"),require("express"),require("node:crypto"),require("./helpers.js"),require("ejs");const b=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function w(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const o in e)t[o]=e[o];return t.default=e,Object.freeze(t)}const y=w(e),P=w(t),x=w(d),S=b(p),E=w(u),T=w(g),L=b(h),k=b(m);function D(e){return null!=e&&!1!==e}let F=null;const I=[{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 _=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class ${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:t,newAssetsPath:o,destinationPath:n,changelogTemplate:i,diffFileTemplateHandler:r,diffLineTemplateHandler:a,changelogFilename:l,contextLines:c}=e;if(this.logger=s.createLogger(),!t||!o||!n)throw new Error("Previous assets path, current assets path and destination path are required");if(t===o)throw new Error("Previous and current assets paths must be different");if(!this.isExists(t))throw new Error(`Previous assets path ${t} does not exist`);if(!this.isExists(o))throw new Error(`Current assets path ${o} does not exist`);if(this.isZipFile(t)){const e=y.resolve(E.tmpdir(),T.createHash("md5").update(t).digest("hex"));this.oldAssetsPath=this.unzipFile(t,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(t))throw new Error(`Invalid previous assets path ${t}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(t);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(o)){const e=y.resolve(E.tmpdir(),T.createHash("md5").update(o).digest("hex"));this.newAssetsPath=this.unzipFile(o,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(o))throw new Error(`Invalid current assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${o} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=n,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",i&&(this.templateIsValid(i)?this.changelogTemplate=i:this.logger.warn(s.colors.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof a&&(this.diffLineTemplateHandler=a),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return P.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return P.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===P.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){P.existsSync(e)||P.mkdirSync(e,{recursive:!0})}async unzipFile(e,t){P.rmSync(t,{force:!0,recursive:!0}),await L(e,{dir:t}),await s.rejectSymlinks(t)}normalizeAssetFolderPath(e){const t=P.readdirSync(e);return 1===t.length&&P.lstatSync(y.join(e,t[0])).isDirectory()?this.normalizeAssetFolderPath(y.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?"-":" "}">${r=o??"",r.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var r}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(s.colors.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await x.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(_.test(e)&&(e=e.replace(_,"$1$3")),_.test(t)&&(t=t.replace(_,"$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 S,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let r=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:r+o+1,lineType:t})).slice(0,n);return-1!==t&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const t=this.pathToPosix(y.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(y.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?y.join(e.path1,e.name1):null,o=e.path2&&e.name2?y.join(e.path2,e.name2):null,n=this.pathToPosix(y.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(y.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(y.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await f.isBinaryFile(t)||await f.isBinaryFile(o)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(P.readFileSync(t,"utf-8"),P.readFileSync(o,"utf-8"))))}return""}async generateChangelog(){this.logger.info(s.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),t=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(s.colors.green("Writing changelog file"));const o=this.changelogTemplate.split("%FILES%");o.splice(1,0,t);const n=o.join("");P.writeFileSync(y.join(this.destinationPath,this.changelogFilename),n),this.logger.info(s.colors.green(`Changelog file written to ${y.join(this.destinationPath,this.changelogFilename)}`))}}class j{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await k({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class C{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new v.WebSocketServer({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===v.WebSocket.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===s.PP_DEV_HMR_WS_PATH&&(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){s.createLogger().error(`ws handler for "${o.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===v.WebSocket.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 A=r.cac("pp-dev");function N(e,t,o){const n=[...s.PP_DEV_CONFIG_NAMES,"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(t=>y.join(e,t)),r=i.watch(n,{ignored:e=>{const t=y.basename(e);return/(^|[\/\\])\../.test(e)&&!t.startsWith(".env")&&!t.startsWith(".pp-dev")&&!t.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let a=null;return r.on("change",n=>{o(s.colors.blue(`🔧 Config file changed: ${y.relative(e,n)}`)),a&&clearTimeout(a),a=setTimeout(async()=>{try{o(s.colors.yellow("🔄 Restarting dev server due to config change...")),await t()}catch(e){o(s.colors.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{o(s.colors.red(`❌ Config watcher error: ${e}`))}),{watcher:r,restartCallback:t,logger:o}}function R(e){e.watcher&&e.watcher.close()}function M(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 q(e){const{changelog:t,executionRoot:o,newAssetsPath:n,backupsDirPath:i,changelogDestinationPath:r,logLevel:a}=e;let l;if("string"==typeof t)l=y.resolve(o,t);else{if(!P.existsSync(i))return void s.createLogger(a).warn(s.colors.yellow("backups directory not found, skipping changelog generation"));const e=P.readdirSync(i,{withFileTypes:!0});if(!e.length)return void s.createLogger(a).warn(s.colors.yellow("no backups found, skipping changelog generation"));const t=e.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!t.length)return void s.createLogger(a).warn(s.colors.yellow("no ZIP backups found, skipping changelog generation"));const o=t.reduce((e,t)=>P.statSync(y.resolve(i,e.name)).mtimeMs>P.statSync(y.resolve(i,t.name)).mtimeMs?e:t).name;l=y.resolve(i,o)}const c=new $({oldAssetsPath:l,newAssetsPath:n,destinationPath:r});await c.generateChangelog()}let O=global.__pp_dev_profile_session,V=0;const H=e=>{if(O)return new Promise((t,o)=>{O.post("Profiler.stop",(n,{profile:i})=>{if(n)o(n);else{const o=y.resolve(`./pp-dev-profile-${V++}.cpuprofile`);P.writeFileSync(o,JSON.stringify(i)),e(s.colors.yellow(`CPU profile written to ${s.colors.white(s.colors.dim(o))}`)),O=void 0,t()}})})},z=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function U(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}A.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"),A.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);let o=null,i=null,r=!1;const c=e?y.resolve(process.cwd(),e):process.cwd(),d=s.createLogger(t.logLevel),p=async()=>{if(!r){r=!0;try{o&&(d.info(s.colors.yellow("🛑 Stopping existing dev server...")),await o.close(),o=null);const{clearConfigCache:f,getConfig:u}=await Promise.resolve().then(()=>require("./index-Bi5Lt1-H.js")).then(e=>e.config);f();const{createServer:g}=await(import("vite")),h=t.mode||"development",m=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(h,m);const v=await l.loadConfigFromFile({mode:h,command:"serve"},t.config,e,t.logLevel);let b=await a.getViteConfig(void 0,{mode:h,root:m});if(v){const{plugins:e,...t}=v.config;b=l.mergeConfig(b,t)}if(o=await g(l.mergeConfig(b,{root:e,base:t.base,mode:t.mode,configFile:t.config,logLevel:t.logLevel,clearScreen:t.clearScreen,optimizeDeps:{force:t.force},server:U(t),customLogger:d},!0)),!o.config.base||"/"===o.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!o.httpServer)throw new Error("HTTP server not available");await o.listen();const w=global.__pp_dev_start_time??!1,P=w?s.colors.dim(`ready in ${s.colors.reset(s.colors.bold(Math.ceil(n.performance.now()-w)))} ms`):"";d.info(`\n ${s.colors.green(`${s.colors.bold("PP-DEV")} v${s.VERSION}`)} ${P}\n`),o.printUrls();const x=await u(m);if(!1!==x.inspector?.enabled){const e=o.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${o.config.server.port??5173}`;d.info(`\n ${s.colors.cyan("🔍 Request Inspector")} ${s.colors.dim(t+s.INSPECTOR_PATH)}\n`)}!function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=s.createLogger();t.print&&o.info(s.colors.dim(s.colors.green(" ➜"))+s.colors.dim(" press ")+s.colors.bold("h")+s.colors.dim(" to show help"));const n=(t.customShortcuts??[]).filter(D).concat(I);F?.(),F=null;let i=!1;const r=process.stdin.isPaused(),a=process.stdin,l=Boolean(a.isRaw),c=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(["",s.colors.bold(" Shortcuts"),...n.map(e=>s.colors.dim(" press ")+s.colors.bold(e.key)+s.colors.dim(` to ${e.description}`))].join("\n"));const r=n.find(e=>e.key===t);r&&(i=!0,await r.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",c).setEncoding("utf8").resume();const d=e.httpServer,p=()=>{F===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),r&&process.stdin.pause(),F=null)};F=p,d.on("close",p)}(o,{print:!0,customShortcuts:[...O?[{key:"p",description:"start/stop the profiler",async action(e){if(O)await H(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{O=new e.Session,O.connect(),O.post("Profiler.enable",()=>{O?.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("/")}`}})}}]}),i||(i=N(c,p,d.info),d.info(s.colors.blue("🔧 Config file watcher started"))),r=!1}catch(e){r=!1,d.error(s.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),H(d.info),process.exit(1)}}},f=async e=>{d.info(s.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{i&&(R(i),i=null),o&&(await o.close(),o=null),H(d.info),d.info(s.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(s.colors.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(s.colors.red(`❌ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(s.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),f("unhandledRejection")}),await p()}),A.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(e,t)=>{z(t);let n=null,i=null,r=null,l=null,d=!1;const p=s.createLogger(),f=async()=>{if(!d){d=!0;try{const{next:g,constants:h}=await a.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:m}=h;r&&(await r.close(),r=null),i&&(p.info(s.colors.yellow("🛑 Stopping existing Next.js server...")),await new Promise(e=>{i.close(()=>{i=null,e()})})),n&&"function"==typeof n.close&&(await n.close(),n=null);const{clearConfigCache:v}=await Promise.resolve().then(()=>require("./index-Bi5Lt1-H.js")).then(e=>e.config);v();const{join:b,basename:w}=await(import("path")),{createServer:x}=await(import("http")),S=await(import("next/dist/server/config.js")),E=S.default.default||S["module.exports"].default||S.default,T=U(t),L=e?b(process.cwd(),e):process.cwd();a.loadPPDevEnv(t.mode||"development",L),p.info(L);const k=await E(m,L);let D=k?.ppDev||{};if(0===Object.keys(D).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-Bi5Lt1-H.js")).then(e=>e.config),t=await e(L);Object.keys(t).length>0?(D=t,p.info(s.colors.blue("🔧 Loaded pp-dev config from standalone config file"))):p.info(s.colors.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){p.info(s.colors.yellow("⚠️ Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else p.info(s.colors.blue("🔧 Loaded pp-dev config from Next.js config"));let F=null;try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-Bi5Lt1-H.js")).then(e=>e.config);F=e(L).name}catch{F=w(L)}s.validatePPDevConfig(D,F??"");const I=s.normalizePPDevConfig(D,F??""),_=I.backendBaseURL??"http://localhost:8080",$=I.templateLess,j=I.v7Features,A=I.disableSSLValidation,q=I.enableProxyCache,O=I.proxyCacheTTL,V=I.personalAccessToken,H=I.miHudLess,z=I.inspectorEnabled,W=I.inspectorMaxMemory,B=I.inspectorCaptureLimit,Z=I.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,G=k?.basePath;let J="";G?J=G:(J=$?s.PATH_PAGE_PREFIX:j?s.PATH_TEMPLATE_LOCAL_PREFIX:s.PATH_TEMPLATE_PREFIX,J+=`/${F}`);const X=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}:{}}(t),K=async e=>{delete process.env.TURBOPACK,n&&"function"==typeof n.close&&(await n.close(),n=null);const t={dev:!0,customServer:!0,hostname:T.host||"localhost",port:T.port,dir:L,conf:{...k,basePath:J,assetPrefix:J}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),n=g(t),await n.prepare()};if(X.webpack)await K({webpack:!0});else if(X.turbopack)try{await K({turbopack:!0})}catch(e){if(!M(e))throw e;p.warn(s.colors.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await K({webpack:!0})}else try{await K({})}catch(e){if(!M(e))throw e;p.warn(s.colors.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await K({webpack:!0})}if(!n)throw new Error("Next.js app failed to initialize");if(J.endsWith("/")||(J+="/"),"/"===J)throw new Error('basePath cannot be equal to "/" or equal to empty string');p.info(s.colors.green("✅ Next.js app prepared successfully")),p.info(s.colors.blue(`🔧 pp-dev plugin configured for template: ${F}`)),p.info(s.colors.blue(`🔧 Base path configured: ${J}`)),_&&(p.info(s.colors.blue(`🌐 Backend URL: ${_}`)),p.info(s.colors.blue(`🆔 Custom App ID: ${Z}`)));const Y=n.getRequestHandler(),Q="number"==typeof T.port?T.port:3e3,ee="string"==typeof T.host?T.host||"0.0.0.0":"localhost",te=new Set;i=x(async(e,t)=>{try{const o=e.url||"/",n=o.split("?")[0];let i=c.parse(o,!0);if(ne.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(ie.length>0){let l=0;const d=()=>{if(l>=ie.length)return void r();const o=ie[l];l++,o(e,t,d)};return void d()}return void r()}let s=0;const a=()=>{if(s>=ne.length)return void r();const o=ne[s];s++,o(e,t,a)};return void a()}async function r(){if(n.startsWith(J))i=c.parse(o,!0);else{if(n===J.replace(/\/$/,"")){const e=o.replace(n,J);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:J}),void t.end()}await Y(e,t,i)}r()}catch(f){p.error(`Error handling request: ${f instanceof Error?f.message:String(f)}`,{error:f instanceof Error?f:void 0}),t.statusCode=500,t.end("Internal Server Error")}});let oe=null,ne=[],ie=[];if(!1!==z){const e=new s.RequestStore(W);s.registerInspectorRoutes(s.internalServer,e,B);const t=s.createRequestCaptureMiddleware(e,B);ne.push(t)}if(_){const e=new URL(_).host;_.startsWith("https://")&&(o.EventEmitter.defaultMaxListeners=Math.max(o.EventEmitter.defaultMaxListeners,20));const t={headers:{host:e,referer:_,origin:_.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:Z,templateLess:$,disableSSLValidation:A,v7Features:j,personalAccessToken:V??process.env.MI_ACCESS_TOKEN};oe=new s.MiAPI(_,t);const l=s.initPPRedirect(J,F??void 0),c=(e,t,o)=>{l(e,t,o)};ie.push(c),ne.push(c);const d=a.createDevPanelAssetMiddleware(J);if(ie.push(d),ne.push(d),q){let e=+O;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},o=s.initProxyCache(t),n=(e,t,n)=>{o(e,t,n)};ne.push(n),p.info(s.colors.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const f=new RegExp(`^((${u=J,u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),g=s.initLoadPPData(f,oe,Object.assign({base:J},t,{miHudLess:H})),m=(e,t,o)=>{g(e,t,o)};ne.push(m);const v=J.endsWith("/")?J.substring(0,J.length-1):J,b={middlewares:{use:e=>e},config:{logger:console}},x=s.initProxy({devServer:b,baseURL:_,proxyIgnore:["/@vite","/@metricinsights","/@",v,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:A,miAPI:oe,templateName:F??void 0}),S=(e,t,o)=>{x(e,t,o)};ne.push(S);const T=s.internalServer,D=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(s.INSPECTOR_PATH)||e.url?.startsWith(s.VARIABLES_EDITOR_PATH)){return void T(e,t,()=>{})}o()};ie.push(D),ne.push(D);const N=s.initRewriteResponse(e=>{const t=e.split("?")[0];return t.startsWith(J)&&!t.includes("/_next/")},(t,o)=>{const n=oe.buildPage(t,H),i=a.injectDevPanel(n,J,{backendBaseURL:_,templateLess:$,appId:Z,devPanelPosition:I.devPanelPosition,devPanelHidden:I.devPanelHidden,devPanelAutoHide:I.devPanelAutoHide});return Buffer.from(s.urlReplacer(e,o.headers.host??"",i))}),R=(e,t,o)=>{N(e,t,o)};ne.push(R),r=new C;let M=k?.distDir;try{process.env[s.PP_DEV_NEXT_BUILD_ENV_VAR]="1";const e=await E(h.PHASE_PRODUCTION_BUILD,L);M=e?.distDir??M}catch{}const z=(M??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),U=z&&".next"!==z?z:"out";let W,B="0.0.0";try{const e=JSON.parse(P.readFileSync(y.join(L,"package.json"),"utf-8"));B="string"==typeof e.version?e.version:B,W="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const G=new s.DistService(F??w(L),{root:L,backupFolder:y.resolve(L,I.syncBackupsDir),nextBuild:{projectRoot:L,distDir:U,packageVersion:B,packageRepositoryUrl:W}}),X={ws:r.ws,config:{clientInjectionPlugin:{v7Features:j}}};new s.ClientService(X,{distService:G,miAPI:oe}),s.registerVariablesEditorRoutes(s.internalServer,{distService:G,miAPI:oe});const K="function"==typeof n?.getUpgradeHandler?n.getUpgradeHandler():null;i.on("upgrade",(e,t,o)=>{r?.handleUpgrade(e,t,o)||(K?K(e,t,o):t.destroy())}),p.info(s.colors.blue(`🔧 ${ne.length} pp-dev middlewares initialized`)),p.info(s.colors.blue(`🔧 ${ie.length} essential middlewares for internal routes`)),p.info(s.colors.blue(`🔧 MiAPI initialized for backend: ${_}`)),p.info(s.colors.blue(`🔧 Custom App ID: ${Z}`))}i.listen(Q,ee,()=>{p.info(s.colors.green(`✅ pp-dev Next.js server running at http://${ee}:${Q}`)),p.info(s.colors.blue(`📱 Next.js app accessible at http://${ee}:${Q}${J}`)),!1!==z&&p.info(s.colors.cyan(`🔍 Request Inspector: http://${ee}:${Q}${s.INSPECTOR_PATH}`)),p.info(s.colors.blue("🔧 Base path handling active")),l||(l=N(L,f,p.info),p.info(s.colors.blue("🔧 Config file watcher started"))),i.on("connection",e=>{te.add(e),e.on("close",()=>te.delete(e))});const e=async e=>{p.info(s.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));const t=setTimeout(()=>{p.info(s.colors.yellow("⏰ Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{l&&(R(l),l=null);for(const e of Array.from(te))e.destroy();te.clear(),r&&(await r.close(),r=null),await new Promise(e=>{i.close(()=>{p.info(s.colors.yellow("🛑 HTTP server closed")),e()})}),n&&"function"==typeof n.close&&(await n.close(),p.info(s.colors.yellow("🛑 Next.js app closed"))),clearTimeout(t),p.info(s.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(t),p.error(s.colors.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,p.info(s.colors.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=>{p.error(s.colors.red(`❌ Uncaught Exception: ${t}`)),e("uncaughtException")}),t.on("unhandledRejection",(t,o)=>{p.error(s.colors.red(`❌ Unhandled Rejection at: ${o}, reason: ${t}`)),e("unhandledRejection")}),p.info(s.colors.green("✅ Process event handlers registered successfully"))}catch(e){p.warn(s.colors.yellow(`⚠️ Failed to register process event handlers: ${e}`))}else p.warn(s.colors.yellow("⚠️ process.on is not available, graceful shutdown handlers will not be registered")),p.info(s.colors.blue("💡 This might be due to bundling or environment constraints"))}),d=!1}catch(e){d=!1,p.error(s.colors.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(p.error(s.colors.red("❌ Next.js Peer Dependency Error:")),p.error(s.colors.red(e.message)),p.error(s.colors.yellow("\n💡 To fix this issue:")),p.error(s.colors.blue(" 1. Install Next.js in your project:")),p.error(s.colors.white(" npm install next@^16")),p.error(s.colors.blue(" 2. Or use yarn:")),p.error(s.colors.white(" yarn add next@^16")),p.error(s.colors.blue(" 3. Or use pnpm:")),p.error(s.colors.white(" pnpm add next@^16")),p.error(s.colors.yellow("\n📖 For more information, see:")),p.error(s.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var u}},u=async e=>{p.info(s.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{l&&(R(l),l=null),r&&(await r.close(),r=null),i&&await new Promise(e=>{i.close(()=>{i=null,e()})}),n&&"function"==typeof n.close&&(await n.close(),n=null),p.info(s.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){p.error(s.colors.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),process.on("uncaughtException",e=>{p.error(s.colors.red(`❌ Uncaught Exception: ${e}`)),u("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{p.error(s.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),u("unhandledRejection")}),await f()}),A.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,t)=>{z(t);const o=U(t),n=a.resolveBuildCliOverrides(t);try{const i=t.mode||"production",r=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(i,r);const s=await l.loadConfigFromFile({mode:i,command:"build"},t.config,e,t.logLevel);let c=await a.getViteConfig(n,{mode:i,root:r});if(s){const{plugins:e,...t}=s.config;c=l.mergeConfig(c,t)}const d=l.mergeConfig(c,{root:e,base:t.base,mode:t.mode,configFile:t.config,logLevel:t.logLevel,clearScreen:t.clearScreen,optimizeDeps:{force:t.force},build:o},!0);if(await l.build(d),o.changelog){const n=e||process.cwd(),i=d.build?.outDir||"dist";let r="dist-zip";d.ppDevConfig&&(!1===d.ppDevConfig.distZip?r=i:"object"==typeof d.ppDevConfig.distZip&&"string"==typeof d.ppDevConfig.distZip.outDir&&(r=d.ppDevConfig.distZip.outDir)),await q({changelog:o.changelog,executionRoot:n,newAssetsPath:y.resolve(n,i),backupsDirPath:y.resolve(n,d.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:y.resolve(n,r),logLevel:t.logLevel})}}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>s.createLogger(t.logLevel).info(e))}}),A.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,t)=>{z(t);const o=s.createLogger(t.logLevel),n=e?y.resolve(process.cwd(),e):process.cwd(),i=a.resolveBuildCliOverrides(t);process.env[s.PP_DEV_NEXT_BUILD_ENV_VAR]="1";try{a.loadPPDevEnv(t.mode||"production",n);const{constants:e}=await a.safeNextImport(),r=await(import("next/dist/server/config.js")),l=r.default.default||r["module.exports"].default||r.default,c=await l(e.PHASE_PRODUCTION_BUILD,n);let d,p=c?.ppDev||{};if(0===Object.keys(p).length){const{getConfig:e}=await Promise.resolve().then(()=>require("./index-Bi5Lt1-H.js")).then(e=>e.config);p=await e(n)}try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-Bi5Lt1-H.js")).then(e=>e.config);d=e(n).name}catch{d=y.basename(n)}const f=s.normalizePPDevConfig(p,d),u=a.applyDistZipOverride(f.distZip,i,s.createDefaultZipFileName(d)),g=a.applyVersionManifestOverride(f.versionPlugin,i);o.info(s.colors.cyan("[pp-dev] Running `next build`...")),await s.runNextBuildProcess(n);const h="string"==typeof c?.distDir&&c.distDir?c.distDir:".next",m=".next"===h?"out":h,v=y.resolve(n,m);if(!P.existsSync(v)||!P.statSync(v).isDirectory())throw new Error(`Next.js build output directory not found: ${v}. "next-build" requires "output: 'export'" in next.config (static export).`);const b=JSON.parse(P.readFileSync(y.join(n,"package.json"),"utf-8"));if(!1!==g&&!1!==g.enabled&&(s.writeBuildVersionManifest({outDir:v,packageVersion:"string"==typeof b.version?b.version:"0.0.0",versionFileTemplate:g.versionFileTemplate,packageRepositoryUrl:"string"==typeof b.repository?b.repository:b.repository?.url,enabled:g.enabled}),o.info(s.colors.green(`✅ VERSION / BUILD-MANIFEST written to ${y.relative(n,v)}`))),!1!==u){const e=y.resolve(n,u.outDir),t=u.inDir?y.resolve(v,u.inDir):v,i=s.resolveOutputFilePath(e,u.outFileName,"ZIP output file name");P.mkdirSync(y.dirname(i),{recursive:!0});const r=await s.zipDirectoryToBuffer(t);P.writeFileSync(i,r),o.info(s.colors.green(`✅ Zip archive written to ${y.relative(n,i)}`))}if(t.changelog){const e=!1!==u?u.outDir:m;await q({changelog:t.changelog,executionRoot:n,newAssetsPath:v,backupsDirPath:y.resolve(n,f.syncBackupsDir),changelogDestinationPath:y.resolve(n,e),logLevel:t.logLevel})}}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>s.createLogger(t.logLevel).info(e))}}),A.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,t,o)=>{z(o);const{oldAssetsPath:n=e,newAssetsPath:i=t,destination:r=".",filename:a="CHANGELOG.html",logLevel:l}=o,c=process.cwd();n&&i||(s.createLogger(l).error(s.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=y.resolve(c,n),p=y.resolve(c,i),f=y.resolve(c,r),u=new $({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await u.generateChangelog()}),A.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,t,o)=>{z(o);const{source:n=e,destination:i=t,fontName:r="icon-font"}=o,a=process.cwd(),l=y.resolve(a,n),c=y.resolve(a,i),d=new j({sourceDir:l,outputDir:c,fontName:r}),p=s.createLogger(o.logLevel);p.info(`Generating icon font from SVG files in ${s.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${s.colors.dim(c)}`)}),A.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);try{const o=t.mode||"production",n=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(o,n);const i=await l.loadConfigFromFile({mode:o,command:"build"},t.config,e,t.logLevel);let r=await a.getViteConfig(void 0,{mode:o,root:n});if(i){const{plugins:e,...t}=i.config;r=l.mergeConfig(r,t)}const s=await l.resolveConfig(l.mergeConfig(r,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode}),"serve");await l.optimizeDeps(s,t.force,!0)}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),A.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,t)=>{z(t);try{const o=t.mode||"production",n=y.resolve(process.cwd(),e??".");a.loadPPDevEnv(o,n);const i=await l.loadConfigFromFile({mode:o,command:"build"},t.config,e,t.logLevel);let r=await a.getViteConfig(void 0,{mode:o,root:n});if(i){const{plugins:e,...t}=i.config;r=l.mergeConfig(r,t)}(await l.preview(l.mergeConfig(r,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode,build:{outDir:t.outDir},preview:{port:t.port,strictPort:t.strictPort,host:t.host,https:t.https,open:t.open}}))).printUrls()}catch(e){s.createLogger(t.logLevel).error(s.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>s.createLogger(t.logLevel).info(e))}}),A.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,t)=>{const o=s.createLogger(t.logLevel),{isLegacyFlatConfig:n,isLegacyPPWatchConfig:i,isAlreadyMigrated:r,migrateLegacyFlatConfig:a,migratePPWatchConfig:l,generateConfigFileContent:c,discoverMigrateSource:d,loadPackageJsonMigrateConfig:p}=await Promise.resolve().then(()=>require("./migrate-x1NtMIxu.js")),f=t.format??"ts",u=!1!==t.backup,g=process.cwd(),h=d(g,e);h||(o.warn(s.colors.yellow("No pp-dev or pp-watch config file found in the current directory.")),o.info(s.colors.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:m,isWatchConfig:v,isPackageJsonConfig:b}=h;o.info(s.colors.blue(`Found config: ${y.relative(g,m)}`));const{getPkg:w}=await Promise.resolve().then(()=>require("./index-Bi5Lt1-H.js")).then(e=>e.config),x=w();let S,E={};try{if(/\.[cm]?ts$/i.test(m)){const e=await(import("esbuild")),{pathToFileURL:t}=await(import("url")),o=(await e.build({absWorkingDir:g,entryPoints:[m],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`;P.writeFileSync(n,o);try{const e=await(import(t(y.resolve(g,n)).toString()));E=e.default?.default??e.default??e}finally{P.existsSync(n)&&P.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(m)){const{pathToFileURL:e}=await(import("url")),t=await(import(e(y.resolve(g,m)).toString()));E=t.default?.default??t.default??t}else b?E=p(m):m.endsWith(".json")&&(E=JSON.parse(P.readFileSync(m,"utf-8")))}catch(e){o.error(s.colors.red(`Failed to load config file: ${e.message}`)),process.exit(1)}E&&"object"==typeof E||(o.error(s.colors.red("Config file did not export a valid object.")),process.exit(1)),r(E)?(o.info(s.colors.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):v||i(E)?(o.info(s.colors.blue("Detected pp-watch config format → migrating to 1.0")),S=l(E)):n(E)?(o.info(s.colors.blue("Detected 0.x flat config format → migrating to 1.0")),S=a(E,x.name)):(o.warn(s.colors.yellow("Could not detect config format. No known keys found.")),process.exit(1));const T=c(S,f),L=t.output??y.join(g,`pp-dev.config.${f}`);if(t.dryRun&&(o.info(s.colors.green(`\n--- Migrated config (dry-run) → ${y.relative(g,L)} ---\n`)),process.exit(0)),u&&!b&&P.existsSync(m)){const e=`${m}.bak`;P.copyFileSync(m,e),o.info(s.colors.blue(`Backed up original to: ${y.relative(g,e)}`))}P.writeFileSync(L,T,"utf-8"),o.info(s.colors.green(`✅ Migration complete → ${y.relative(g,L)}`)),b?o.info(s.colors.yellow('You can now remove the "pp-dev" field from package.json.')):m!==L&&P.existsSync(m)&&o.info(s.colors.yellow(`You can now delete the old config: ${y.relative(g,m)}`))}),A.help(),A.version(s.VERSION),A.parse(),exports.stopProfiler=H;
2
2
  //# sourceMappingURL=cli.js.map