@metricinsights/pp-dev 1.5.0-beta.2 → 1.5.0-beta.21

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 (68) hide show
  1. package/README.md +54 -11
  2. package/dist/README.md +54 -11
  3. package/dist/cjs/auth.provider-CyXyBAm3.js +2 -0
  4. package/dist/cjs/auth.provider-CyXyBAm3.js.map +1 -0
  5. package/dist/cjs/cli.js +1 -1
  6. package/dist/cjs/cli.js.map +1 -1
  7. package/dist/cjs/index-CeIQtamz.js +2 -0
  8. package/dist/cjs/index-CeIQtamz.js.map +1 -0
  9. package/dist/cjs/index.js +1 -1
  10. package/dist/cjs/migrate-C1svbbPB.js +2 -0
  11. package/dist/cjs/migrate-C1svbbPB.js.map +1 -0
  12. package/dist/cjs/package.json +8 -12
  13. package/dist/cjs/plugin.js +1 -1
  14. package/dist/cjs/plugin.js.map +1 -1
  15. package/dist/cjs/request-capture.middleware-Chm27VXb.js +2 -0
  16. package/dist/cjs/request-capture.middleware-Chm27VXb.js.map +1 -0
  17. package/dist/cjs/version-manifest-C15hpGGV.js +2 -0
  18. package/dist/cjs/version-manifest-C15hpGGV.js.map +1 -0
  19. package/dist/cjs/version-plugin-DtPQBhEK.js +2 -0
  20. package/dist/cjs/version-plugin-DtPQBhEK.js.map +1 -0
  21. package/dist/client/client.js +269 -125
  22. package/dist/client/client.js.map +1 -1
  23. package/dist/client/request-inspector.css +3 -0
  24. package/dist/client/request-inspector.css.map +1 -0
  25. package/dist/client/request-inspector.html +87 -0
  26. package/dist/client/request-inspector.js +527 -0
  27. package/dist/client/request-inspector.js.map +1 -0
  28. package/dist/client/variables-editor.css +3 -0
  29. package/dist/client/variables-editor.css.map +1 -0
  30. package/dist/client/variables-editor.html +44 -0
  31. package/dist/client/variables-editor.js +3419 -0
  32. package/dist/client/variables-editor.js.map +1 -0
  33. package/dist/esm/auth.provider-Cq0EuReh.js +2 -0
  34. package/dist/esm/auth.provider-Cq0EuReh.js.map +1 -0
  35. package/dist/esm/cli.js +1 -1
  36. package/dist/esm/cli.js.map +1 -1
  37. package/dist/esm/index-DioJ4R68.js +2 -0
  38. package/dist/esm/index-DioJ4R68.js.map +1 -0
  39. package/dist/esm/index.js +1 -1
  40. package/dist/esm/migrate-FpJKfYgz.js +2 -0
  41. package/dist/esm/{migrate-CCFtF5bt.js.map → migrate-FpJKfYgz.js.map} +1 -1
  42. package/dist/esm/package.json +8 -12
  43. package/dist/esm/plugin.js +1 -1
  44. package/dist/esm/plugin.js.map +1 -1
  45. package/dist/esm/request-capture.middleware-BNCdPdkF.js +2 -0
  46. package/dist/esm/request-capture.middleware-BNCdPdkF.js.map +1 -0
  47. package/dist/esm/version-manifest-qxz5FXuG.js +2 -0
  48. package/dist/esm/version-manifest-qxz5FXuG.js.map +1 -0
  49. package/dist/esm/version-plugin-b2xMXK9M.js +2 -0
  50. package/dist/esm/version-plugin-b2xMXK9M.js.map +1 -0
  51. package/dist/types/index.d.ts +46 -9
  52. package/docs/features.md +4 -1
  53. package/package.json +21 -28
  54. package/dist/cjs/index-CNJgcIGX.js +0 -2
  55. package/dist/cjs/index-CNJgcIGX.js.map +0 -1
  56. package/dist/cjs/migrate-DkUysGJq.js +0 -2
  57. package/dist/cjs/migrate-DkUysGJq.js.map +0 -1
  58. package/dist/cjs/plugin-BZ6G8J6V.js +0 -2
  59. package/dist/cjs/plugin-BZ6G8J6V.js.map +0 -1
  60. package/dist/cjs/version-plugin-433yyuTq.js +0 -2
  61. package/dist/cjs/version-plugin-433yyuTq.js.map +0 -1
  62. package/dist/esm/index-BeF76QPw.js +0 -2
  63. package/dist/esm/index-BeF76QPw.js.map +0 -1
  64. package/dist/esm/migrate-CCFtF5bt.js +0 -2
  65. package/dist/esm/plugin-l4fgvJz0.js +0 -2
  66. package/dist/esm/plugin-l4fgvJz0.js.map +0 -1
  67. package/dist/esm/version-plugin-Bqy1V1SQ.js +0 -2
  68. package/dist/esm/version-plugin-Bqy1V1SQ.js.map +0 -1
package/README.md CHANGED
@@ -187,9 +187,11 @@ module.exports = defineConfig({
187
187
 
188
188
  ### `sync` — Template sync
189
189
 
190
- | Field | Type | Default | Description |
191
- |--------------|----------|-------------|-----------------------------------------|
192
- | `backupsDir` | `string` | `'backups'` | Directory for backups from the MI server |
190
+ | Field | Type | Default | Description |
191
+ |--------------|-------------------|-------------|-----------------------------------------------------------------------------------------------------|
192
+ | `backupsDir` | `string` | `'backups'` | Directory for backups from the MI server |
193
+ | `maxBackups` | `number \| false` | `20` | How many of this page's backups to keep; each new backup deletes the oldest beyond that. `false` or `0` keeps them all. |
194
+ | `buildTimeoutMs` | `number` | `600000` | How long the build a sync starts (`pp-dev build`, `next build`) may run, in milliseconds, before it is stopped and the sync fails (default 10 minutes). |
193
195
 
194
196
  ### `devPanel` — Dev panel appearance
195
197
 
@@ -213,10 +215,44 @@ section for the full feature description.
213
215
 
214
216
  | Field | Type | Default | Description |
215
217
  |-----------|-----------|---------|--------------------------------------------------------------------------------------------------------------|
216
- | `persist` | `boolean` | `false` | Keep the users added with an API token between dev server runs, in `~/.pp-dev/users/` (readable by you only) |
218
+ | `persist` | `boolean` | `false` | Keep the users added with an API token between dev server runs, in `~/.pp-dev/users/` (plain text, readable by you only; on Windows, by your profile's permissions) |
217
219
 
218
220
  See [Working as other users](#working-as-other-users).
219
221
 
222
+ ### `server` — The dev server
223
+
224
+ | Field | Type | Default | Description |
225
+ |----------------|--------------------|---------|-------------|
226
+ | `allowedHosts` | `string[] \| true` | `[]` | Host names the dev server answers besides `localhost`, `*.localhost` and IP addresses, as Vite's [`server.allowedHosts`](https://vite.dev/config/server-options#server-allowedhosts): `'my-app.ngrok.app'`, or `'.ngrok.app'` for the domain and its subdomains. `true` answers any host; avoid it |
227
+
228
+ A request whose `Host` is any other name gets 403: that is how DNS rebinding reaches a local server
229
+ (a page on `evil.example:3000` whose name is then pointed at `127.0.0.1`). `pp-dev` passes the list
230
+ to Vite, which checks `Host` itself; `pp-dev next` checks it for every request and WebSocket. The
231
+ `--host <name>` you start the server with is allowed too.
232
+
233
+ **Tunnels** (ngrok, cloudflared, an nginx in front): list the tunnel's exact name
234
+ (`'my-app.ngrok.app'`). The dev server then answers that `Host`, and the pages served through the
235
+ tunnel may use its own API (`/@api/*`), the dev panel's WebSocket and, under `pp-dev next`, Next's
236
+ HMR: in development `withPPDev()` adds the exact names to Next's
237
+ [`allowedDevOrigins`](https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins),
238
+ next to the ones in your Next config. A `.domain` entry (`'.ngrok.app'`) only answers the `Host`:
239
+ as a page's origin it would let any page on that domain, someone else's tunnel too, act with your MI
240
+ token or read Next's dev resources.
241
+
242
+ Use a tunnel that keeps its name in `Host` (ngrok's default). One that rewrites `Host` to
243
+ `localhost` (`ngrok --host-header=rewrite`, cloudflared's `httpHostHeader`, nginx
244
+ `proxy_set_header Host localhost`) serves the pages, but the dev server then knows itself only as
245
+ `localhost`: MI's redirects and the MI links it rewrites in responses point the browser at
246
+ `localhost`, out of the tunnel. `X-Forwarded-Host` is not trusted to fix that: a rebinding page
247
+ can send it.
248
+
249
+ ```ts
250
+ export default defineConfig({
251
+ // ...
252
+ server: { allowedHosts: ['my-app.ngrok.app'] },
253
+ });
254
+ ```
255
+
220
256
  ### Validation
221
257
 
222
258
  pp-dev validates your config at startup and reports problems clearly:
@@ -230,6 +266,7 @@ pp-dev validates your config at startup and reports problems clearly:
230
266
  | `app.type === 'page'` + `mi.mode === 'standalone'` without `app.id` | error |
231
267
  | `app.name` missing and no `package.json#name` | error |
232
268
  | `devPanel.position` not one of the four corners | error |
269
+ | `server.allowedHosts` neither a list of host names nor `true` | error |
233
270
 
234
271
  ### Environment Variables
235
272
 
@@ -337,11 +374,15 @@ pp-dev next [options]
337
374
  # Aliases: pp-dev next-server, pp-dev next-dev
338
375
  ```
339
376
 
340
- | Option | Default | Description |
341
- | --------------- | ----------- | --------------------------------- |
342
- | `[root]` | `.` | Root directory of the application |
343
- | `--port <port>` | `3000` | Server port |
344
- | `--host <host>` | `localhost` | Server hostname |
377
+ | Option | Default | Description |
378
+ | --------------- | ----------- | -------------------------------------------------------------------- |
379
+ | `[root]` | `.` | Root directory of the application |
380
+ | `--port <port>` | `3000` | Server port |
381
+ | `--host [host]` | `localhost` | Server hostname; `--host` without a value listens on all addresses |
382
+ | `--webpack` | - | Use Webpack for Next dev (when Turbopack/native SWC is unavailable) |
383
+ | `--turbopack` | - | Use Turbopack for Next dev |
384
+
385
+ `--https`, `--open`, `--cors`, `--strictPort` and `--force` are accepted for compatibility but have no effect with `pp-dev next` (a warning says so); they will be removed.
345
386
 
346
387
  ### Build
347
388
 
@@ -542,7 +583,9 @@ A standalone page at `/@pp-dev/variables-editor`, alongside the [Request Inspect
542
583
 
543
584
  ![Variables Editor — Schema tab](./docs/screenshots/06-editor-schema.png)
544
585
 
545
- - **Values** — edit the page's live variable values in place, with type-aware widgets (searchable select for `static` options, a per-item form for `list`, …). A JSON mode (`View/edit raw JSON`) shows/accepts the same values as plain JSON — list-type values as native arrays, not double-escaped strings — with **Save to JSON file…** / **Import from JSON file…** buttons, and flags values that don't match a declared option, changed since the last load, or aren't in the schema.
586
+ - **Values** — edit the page's live variable values in place, with type-aware widgets (searchable select for `static` options, a per-item form for `list`, …). A JSON mode (`View/edit raw JSON`) shows/accepts the same values as plain JSON — list-type values as native arrays, not double-escaped strings — with **Save to JSON file…** / **Import from JSON file…** buttons, and flags values that don't match a declared option, changed since the last load, or aren't in the schema. Each variable's description is shown as markdown, the way MI renders it: **bold**, *italic*, `code` and fenced code blocks, lists, and `<u>` / `<s>` / `<del>` for underline and strikethrough.
587
+
588
+ The pages the dev server serves substitute `[VarName]` from its own copy of the values, loaded from MI with the page data. **Save** updates that copy too, so every tab (any user) shows the saved values on its next load. When the values in MI change some other way (edited in MI itself, or the update after a save failed), the Values tab shows **Update local pages · N** in its bottom-right corner; its tooltip lists the values that differ, and a click updates the copy.
546
589
 
547
590
  ![Variables Editor — Values tab](./docs/screenshots/09-editor-values.png)
548
591
 
@@ -586,7 +629,7 @@ Logging out on a user's host ends that user's MI session (or token) as it would
586
629
 
587
630
  ### Keeping users between runs
588
631
 
589
- Users live as long as the dev server. With `users: { persist: true }` the users added with an API token are kept in `~/.pp-dev/users/<hash>.json` — one file per project and MI instance, readable by you only, outside the project so it never ends up in git or a build. Passwords and MI sessions are never written. On start, every kept token is checked with MI again; one MI turns down shows as *API token turned down by MI*.
632
+ Users live as long as the dev server. With `users: { persist: true }` the users added with an API token are kept in `~/.pp-dev/users/<hash>.json` — one file per project and MI instance, outside the project so it never ends up in git or a build. The tokens are stored as plain text: on macOS and Linux the file is readable by you only (mode `0600`); Windows ignores file modes, so there it is as private as your user profile folder (by default readable by you, administrators and the system). Two dev servers on the same project and MI instance share the file: each keeps the users the other added. Passwords and MI sessions are never written. On start, every kept token is checked with MI again; one MI turns down shows as *API token turned down by MI*.
590
633
 
591
634
  ```typescript
592
635
  // pp-dev.config.ts
package/dist/README.md CHANGED
@@ -187,9 +187,11 @@ module.exports = defineConfig({
187
187
 
188
188
  ### `sync` — Template sync
189
189
 
190
- | Field | Type | Default | Description |
191
- |--------------|----------|-------------|-----------------------------------------|
192
- | `backupsDir` | `string` | `'backups'` | Directory for backups from the MI server |
190
+ | Field | Type | Default | Description |
191
+ |--------------|-------------------|-------------|-----------------------------------------------------------------------------------------------------|
192
+ | `backupsDir` | `string` | `'backups'` | Directory for backups from the MI server |
193
+ | `maxBackups` | `number \| false` | `20` | How many of this page's backups to keep; each new backup deletes the oldest beyond that. `false` or `0` keeps them all. |
194
+ | `buildTimeoutMs` | `number` | `600000` | How long the build a sync starts (`pp-dev build`, `next build`) may run, in milliseconds, before it is stopped and the sync fails (default 10 minutes). |
193
195
 
194
196
  ### `devPanel` — Dev panel appearance
195
197
 
@@ -213,10 +215,44 @@ section for the full feature description.
213
215
 
214
216
  | Field | Type | Default | Description |
215
217
  |-----------|-----------|---------|--------------------------------------------------------------------------------------------------------------|
216
- | `persist` | `boolean` | `false` | Keep the users added with an API token between dev server runs, in `~/.pp-dev/users/` (readable by you only) |
218
+ | `persist` | `boolean` | `false` | Keep the users added with an API token between dev server runs, in `~/.pp-dev/users/` (plain text, readable by you only; on Windows, by your profile's permissions) |
217
219
 
218
220
  See [Working as other users](#working-as-other-users).
219
221
 
222
+ ### `server` — The dev server
223
+
224
+ | Field | Type | Default | Description |
225
+ |----------------|--------------------|---------|-------------|
226
+ | `allowedHosts` | `string[] \| true` | `[]` | Host names the dev server answers besides `localhost`, `*.localhost` and IP addresses, as Vite's [`server.allowedHosts`](https://vite.dev/config/server-options#server-allowedhosts): `'my-app.ngrok.app'`, or `'.ngrok.app'` for the domain and its subdomains. `true` answers any host; avoid it |
227
+
228
+ A request whose `Host` is any other name gets 403: that is how DNS rebinding reaches a local server
229
+ (a page on `evil.example:3000` whose name is then pointed at `127.0.0.1`). `pp-dev` passes the list
230
+ to Vite, which checks `Host` itself; `pp-dev next` checks it for every request and WebSocket. The
231
+ `--host <name>` you start the server with is allowed too.
232
+
233
+ **Tunnels** (ngrok, cloudflared, an nginx in front): list the tunnel's exact name
234
+ (`'my-app.ngrok.app'`). The dev server then answers that `Host`, and the pages served through the
235
+ tunnel may use its own API (`/@api/*`), the dev panel's WebSocket and, under `pp-dev next`, Next's
236
+ HMR: in development `withPPDev()` adds the exact names to Next's
237
+ [`allowedDevOrigins`](https://nextjs.org/docs/app/api-reference/config/next-config-js/allowedDevOrigins),
238
+ next to the ones in your Next config. A `.domain` entry (`'.ngrok.app'`) only answers the `Host`:
239
+ as a page's origin it would let any page on that domain, someone else's tunnel too, act with your MI
240
+ token or read Next's dev resources.
241
+
242
+ Use a tunnel that keeps its name in `Host` (ngrok's default). One that rewrites `Host` to
243
+ `localhost` (`ngrok --host-header=rewrite`, cloudflared's `httpHostHeader`, nginx
244
+ `proxy_set_header Host localhost`) serves the pages, but the dev server then knows itself only as
245
+ `localhost`: MI's redirects and the MI links it rewrites in responses point the browser at
246
+ `localhost`, out of the tunnel. `X-Forwarded-Host` is not trusted to fix that: a rebinding page
247
+ can send it.
248
+
249
+ ```ts
250
+ export default defineConfig({
251
+ // ...
252
+ server: { allowedHosts: ['my-app.ngrok.app'] },
253
+ });
254
+ ```
255
+
220
256
  ### Validation
221
257
 
222
258
  pp-dev validates your config at startup and reports problems clearly:
@@ -230,6 +266,7 @@ pp-dev validates your config at startup and reports problems clearly:
230
266
  | `app.type === 'page'` + `mi.mode === 'standalone'` without `app.id` | error |
231
267
  | `app.name` missing and no `package.json#name` | error |
232
268
  | `devPanel.position` not one of the four corners | error |
269
+ | `server.allowedHosts` neither a list of host names nor `true` | error |
233
270
 
234
271
  ### Environment Variables
235
272
 
@@ -337,11 +374,15 @@ pp-dev next [options]
337
374
  # Aliases: pp-dev next-server, pp-dev next-dev
338
375
  ```
339
376
 
340
- | Option | Default | Description |
341
- | --------------- | ----------- | --------------------------------- |
342
- | `[root]` | `.` | Root directory of the application |
343
- | `--port <port>` | `3000` | Server port |
344
- | `--host <host>` | `localhost` | Server hostname |
377
+ | Option | Default | Description |
378
+ | --------------- | ----------- | -------------------------------------------------------------------- |
379
+ | `[root]` | `.` | Root directory of the application |
380
+ | `--port <port>` | `3000` | Server port |
381
+ | `--host [host]` | `localhost` | Server hostname; `--host` without a value listens on all addresses |
382
+ | `--webpack` | - | Use Webpack for Next dev (when Turbopack/native SWC is unavailable) |
383
+ | `--turbopack` | - | Use Turbopack for Next dev |
384
+
385
+ `--https`, `--open`, `--cors`, `--strictPort` and `--force` are accepted for compatibility but have no effect with `pp-dev next` (a warning says so); they will be removed.
345
386
 
346
387
  ### Build
347
388
 
@@ -542,7 +583,9 @@ A standalone page at `/@pp-dev/variables-editor`, alongside the [Request Inspect
542
583
 
543
584
  ![Variables Editor — Schema tab](./docs/screenshots/06-editor-schema.png)
544
585
 
545
- - **Values** — edit the page's live variable values in place, with type-aware widgets (searchable select for `static` options, a per-item form for `list`, …). A JSON mode (`View/edit raw JSON`) shows/accepts the same values as plain JSON — list-type values as native arrays, not double-escaped strings — with **Save to JSON file…** / **Import from JSON file…** buttons, and flags values that don't match a declared option, changed since the last load, or aren't in the schema.
586
+ - **Values** — edit the page's live variable values in place, with type-aware widgets (searchable select for `static` options, a per-item form for `list`, …). A JSON mode (`View/edit raw JSON`) shows/accepts the same values as plain JSON — list-type values as native arrays, not double-escaped strings — with **Save to JSON file…** / **Import from JSON file…** buttons, and flags values that don't match a declared option, changed since the last load, or aren't in the schema. Each variable's description is shown as markdown, the way MI renders it: **bold**, *italic*, `code` and fenced code blocks, lists, and `<u>` / `<s>` / `<del>` for underline and strikethrough.
587
+
588
+ The pages the dev server serves substitute `[VarName]` from its own copy of the values, loaded from MI with the page data. **Save** updates that copy too, so every tab (any user) shows the saved values on its next load. When the values in MI change some other way (edited in MI itself, or the update after a save failed), the Values tab shows **Update local pages · N** in its bottom-right corner; its tooltip lists the values that differ, and a click updates the copy.
546
589
 
547
590
  ![Variables Editor — Values tab](./docs/screenshots/09-editor-values.png)
548
591
 
@@ -586,7 +629,7 @@ Logging out on a user's host ends that user's MI session (or token) as it would
586
629
 
587
630
  ### Keeping users between runs
588
631
 
589
- Users live as long as the dev server. With `users: { persist: true }` the users added with an API token are kept in `~/.pp-dev/users/<hash>.json` — one file per project and MI instance, readable by you only, outside the project so it never ends up in git or a build. Passwords and MI sessions are never written. On start, every kept token is checked with MI again; one MI turns down shows as *API token turned down by MI*.
632
+ Users live as long as the dev server. With `users: { persist: true }` the users added with an API token are kept in `~/.pp-dev/users/<hash>.json` — one file per project and MI instance, outside the project so it never ends up in git or a build. The tokens are stored as plain text: on macOS and Linux the file is readable by you only (mode `0600`); Windows ignores file modes, so there it is as private as your user profile folder (by default readable by you, administrators and the system). Two dev servers on the same project and MI instance share the file: each keeps the users the other added. Passwords and MI sessions are never written. On start, every kept token is checked with MI again; one MI turns down shows as *API token turned down by MI*.
590
633
 
591
634
  ```typescript
592
635
  // pp-dev.config.ts
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("fs"),t=require("path"),i=require("url"),r=require("picocolors"),s=require("node:path"),o=require("node:net"),n=require("vite");var a="undefined"!=typeof document?document.currentScript:null;const d=(e=>e&&"object"==typeof e&&"default"in e?e.default:e)(s),p=t.resolve("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("auth.provider-CyXyBAm3.js",document.baseURI).href),"../../.."),l=t.resolve("undefined"!=typeof __filename&&__filename||i.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("auth.provider-CyXyBAm3.js",document.baseURI).href),"../.."),c=e.existsSync(t.resolve(p,"package.json"))?p:l,u=t.resolve(c,"dist/client/client.js"),{version:h,name:f}=JSON.parse(e.readFileSync(t.resolve(c,"package.json")).toString()),m=h,v=f,g="info";let w,y;function E(){return w??={level:g,logger:n.createLogger(g)},w.logger}function b(e){return void 0!==e&&e!==w?.level&&(w={level:e,logger:n.createLogger(e)}),y??={info:(e,t)=>E().info(e,t),warn:(e,t)=>E().warn(e,t),warnOnce:(e,t)=>E().warnOnce(e,t),error:(e,t)=>E().error(e,t),clearScreen:e=>E().clearScreen(e),hasErrorLogged:e=>E().hasErrorLogged(e),get hasWarned(){return E().hasWarned},set hasWarned(e){E().hasWarned=e}},y}const P=r.createColors();function _(e,t){if(!e||e.includes("\0")||d.posix.isAbsolute(e)||d.win32.isAbsolute(e)||d.win32.parse(e).root)throw new Error(`[pp-dev] ${t} must be a relative path inside its output directory.`);const i=d.posix.normalize(e.replace(/\\/g,"/"));if("."===i||".."===i||i.startsWith("../"))throw new Error(`[pp-dev] ${t} must stay inside its output directory.`);return i}function x(e){return _(`${e.replace(/^@/,"").replace(/[\\/]+/g,"-")}.zip`,"default ZIP output file name")}const A=["top-left","top-right","bottom-left","bottom-right"],L=2147483647;const R=new Set(["GET","HEAD","OPTIONS"]);function T(e){return!0===e?[]:e.filter(e=>!e.startsWith("."))}function N(e,t=[]){const i=e.headers.origin,r=e.headers.host;if("string"==typeof i){if("null"===i)return'Origin "null" (a sandboxed or file:// page)';let e;try{e=new URL(i)}catch{return`unreadable Origin "${i}"`}if("localhost"===(s=e.hostname)||s.endsWith(".localhost")||"[::1]"===s||/^127(?:\.\d{1,3}){3}$/.test(s)||T(t).includes(e.hostname))return null;const o=r?function(e,t){try{return new URL(`${e}//${t}`).host}catch{return}}(e.protocol,r):void 0;return o&&e.host===o?null:`Origin ${e.origin} is neither this dev server (${r??"no Host"}) nor this machine`}var s;const o=e.headers["sec-fetch-site"];return R.has((e.method??"GET").toUpperCase())||"cross-site"!==o?null:"sent from a cross-site page"}class S{state={isAuthenticated:!1,isRedirected:!1,lastChecked:0};listeners=new Set;getState(){return{...this.state}}isAuthenticated(){return this.state.isAuthenticated}isRedirected(){return this.state.isRedirected}setAuthenticated(e){this.state.isAuthenticated=e,this.state.lastChecked=Date.now(),this.notifyListeners()}setRedirected(e){this.state.isRedirected=e,this.notifyListeners()}updateState(e){void 0!==e.isAuthenticated&&(this.state.isAuthenticated=e.isAuthenticated),void 0!==e.isRedirected&&(this.state.isRedirected=e.isRedirected),this.state.lastChecked=Date.now(),this.notifyListeners()}reset(){this.state={isAuthenticated:!1,isRedirected:!1,lastChecked:0},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{try{e(this.getState())}catch(e){b().error(`Error in auth state listener: ${e instanceof Error?e.stack??e.message:String(e)}`)}})}}const C=new S;exports.AuthProvider=S,exports.PACKAGE_NAME=v,exports.PATH_PAGE_PREFIX="/p",exports.PATH_TEMPLATE_LOCAL_PREFIX="/pl",exports.PATH_TEMPLATE_PREFIX="/pt",exports.PP_DEV_CLIENT_ENTRY=u,exports.PP_DEV_CONFIG_NAMES=[".pp-dev.config.js",".pp-dev.config.cjs",".pp-dev.config.mjs",".pp-dev.config.ts",".pp-dev.config.cts",".pp-dev.config.mts",".pp-dev.config.json","pp-dev.config.js","pp-dev.config.cjs","pp-dev.config.mjs","pp-dev.config.ts","pp-dev.config.cts","pp-dev.config.mts","pp-dev.config.json"],exports.PP_DEV_NEXT_BUILD_ENV_VAR="PP_DEV_NEXT_BUILD",exports.PP_DEV_PACKAGE_DIR=c,exports.VERSION=m,exports.authProvider=C,exports.colors=P,exports.createDefaultZipFileName=x,exports.createLogger=b,exports.createOriginGuard=function(e=[]){return(t,i,r)=>{const s=N(t,e);s?i.status(403).json({error:`Blocked by pp-dev: ${s}.`}):r()}},exports.crossOriginReason=N,exports.exactAllowedHosts=T,exports.hostNotAllowedMessage=function(e){const t=JSON.stringify((e??"").replace(/:\d*$/,""));return`Blocked by pp-dev: this host (${t}) is not allowed. To allow it, add ${t} to server.allowedHosts in the pp-dev config.`},exports.isHostAllowed=function(e,t){if(void 0===e||!0===t)return!0;const i=function(e){const t=e.trim().toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");return e>0&&6===o.isIP(t.slice(1,e))?{ip:!0}:void 0}const i=t.replace(/:\d*$/,"");if(i&&!i.includes(":"))return 4===o.isIP(i)?{ip:!0}:{hostname:i}}(e);if(void 0===i)return!1;if("ip"in i)return!0;const{hostname:r}=i;return"localhost"===r||r.endsWith(".localhost")||function(e,t){return t.some(t=>t===e||t.startsWith(".")&&(t.slice(1)===e||e.endsWith(t)))}(r,t)},exports.normalizePPDevConfig=function(e,t){const{mi:i={},app:r={},proxy:s={},build:o={},sync:n={},inspector:a={},devPanel:d={},users:p={},server:l={}}=e,c=i.mode??"standalone",u=r.type??"template",h=i.apiVersion??7,f="standalone"===c;let m=!1;"top-bar"===i.include?m=!0:"shared-components"===i.include&&(m={addSharedComponentsScripts:!0,addRootElement:!1});const v="page"===u,g=r.name??t;if(!g)throw new Error("[pp-dev] app.name is required (or set package.json#name)");const w="VERSION-v{packageversion}-{currentDate}.json";let y;const E=o.zip;let b;y=!1!==E&&(!0===E||void 0===E?{outFileName:x(g),outDir:"dist-zip"}:{outFileName:_(E.fileName??x(g),"build.zip.fileName"),outDir:E.outDir??"dist-zip",...E.inDir?{inDir:E.inDir}:{}});const P=o.versionFile;let A;b=!1!==P&&(!0===P||void 0===P?{versionFileTemplate:w,enabled:!0}:{versionFileTemplate:_(P.fileNameTemplate??w,"build.versionFile.fileNameTemplate"),enabled:P.enabled??!0});const L=o.imageOptimisations;return A=!1!==L&&(!0===L||void 0===L?{}:L),{templateName:g,backendBaseURL:i.url??process.env.MI_BACKEND_URL,appId:r.id,templateLess:v,miHudLess:f,integrateMiTopBar:m,enableProxyCache:s.cache??!0,proxyCacheTTL:s.cacheTtl??6e5,disableSSLValidation:s.tls?.allowSelfSigned??!1,imageOptimizer:A,outDir:o.outDir??"dist",distZip:y,versionPlugin:b,syncBackupsDir:n.backupsDir??"backups",syncMaxBackups:n.maxBackups,syncBuildTimeoutMs:n.buildTimeoutMs,v7Features:h>=7,personalAccessToken:i.token??process.env.MI_ACCESS_TOKEN,inspectorEnabled:a.enabled??!0,inspectorMaxMemory:a.maxMemory??1073741824,inspectorCaptureLimit:a.captureLimit??10485760,devPanelPosition:d.position??"bottom-right",devPanelHidden:d.hidden??!1,devPanelAutoHide:d.autoHide??!1,persistUsers:p.persist??!1,allowedHosts:!0===l.allowedHosts||(l.allowedHosts??[]).map(e=>e.trim().toLowerCase())}},exports.normalizeRelativeOutputPath=_,exports.resolveOutputFilePath=function(e,t,i){const r=_(t,i),s=d.resolve(e),o=d.resolve(s,...r.split("/")),n=d.relative(s,o);if(".."===n||n.startsWith(`..${d.sep}`)||d.isAbsolute(n))throw new Error(`[pp-dev] ${i} must resolve inside its output directory.`);return o},exports.validatePPDevConfig=function(e,t){const i=e.mi?.mode??"standalone",r=e.app?.type??"template",s=e.mi?.apiVersion??7,o=e.mi?.url??process.env.MI_BACKEND_URL;if(!(e.app?.name??t))throw new Error("[pp-dev] app.name is required (or set package.json#name)");const n=e.sync?.maxBackups;if(void 0!==n&&!1!==n&&!(Number.isInteger(n)&&n>=0))throw new Error(`[pp-dev] sync.maxBackups must be a whole number ≥ 0 or false (0 and false keep every backup), got ${JSON.stringify(n)}`);const a=e.sync?.buildTimeoutMs;if(void 0!==a&&!(Number.isInteger(a)&&a>0&&a<=L))throw new Error(`[pp-dev] sync.buildTimeoutMs must be a whole number of milliseconds between 1 and 2147483647, got ${JSON.stringify(a)}`);if(e.mi?.include&&"standalone"!==i)throw console.warn('[pp-dev] mi.include is only valid when mi.mode is "standalone"'),new Error('[pp-dev] mi.include requires mi.mode to be "standalone"');if(!o){if("embedding"===i||"template"===r)throw new Error('[pp-dev] mi.url is required when mi.mode is "embedding" or app.type is "template"');"standalone"===i&&"page"===r&&console.warn("[pp-dev] mi.url is not set — dev server will run without a backend proxy")}if("template"===r&&!e.app?.id)throw new Error('[pp-dev] app.id is required when app.type is "template"');if("page"===r&&o&&("standalone"===i||s>=7)&&!e.app?.id)throw new Error('[pp-dev] app.id is required when backend page data is loaded for app.type "page"');if(void 0!==e.devPanel?.position&&!A.includes(e.devPanel.position))throw new Error(`[pp-dev] devPanel.position must be one of: ${A.join(", ")}`);const d=e.server?.allowedHosts;if(!(void 0===d||!0===d||Array.isArray(d)&&d.every(e=>"string"==typeof e&&""!==e.trim())))throw new Error(`[pp-dev] server.allowedHosts must be a list of host names or true, got ${JSON.stringify(d)}`)};
2
+ //# sourceMappingURL=auth.provider-CyXyBAm3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.provider-CyXyBAm3.js","sources":["../../../src/constants.ts","../../../src/lib/logger.ts","../../../src/lib/helpers/color.helper.ts","../../../src/lib/output-path.ts","../../../src/lib/pp-dev-config.ts","../../../src/lib/helpers/origin-guard.ts","../../../src/lib/auth.provider.ts"],"sourcesContent":[null,null,null,null,null,null,null],"names":["afterBundlePath","resolve","__filename","fileURLToPath","document","require","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","beforeBundlePath","PP_DEV_PACKAGE_DIR","existsSync","PP_DEV_CLIENT_ENTRY","version","name","JSON","parse","readFileSync","toString","VERSION","PACKAGE_NAME","DEFAULT_LEVEL","current","shared","active","level","logger","createViteLogger","createLogger","undefined","info","msg","options","warn","warnOnce","error","clearScreen","type","hasErrorLogged","hasWarned","value","colors","createColors","normalizeRelativeOutputPath","relativePath","optionName","includes","path","posix","isAbsolute","win32","root","Error","normalized","normalize","replace","startsWith","createDefaultZipFileName","appName","DEV_PANEL_POSITIONS","MAX_TIMER_DELAY_MS","SAFE_METHODS","Set","exactAllowedHosts","allowedHosts","filter","host","crossOriginReason","req","origin","headers","originUrl","hostname","endsWith","test","requestHost","scheme","normalizeHost","protocol","fetchSite","has","method","AuthProvider","state","isAuthenticated","isRedirected","lastChecked","listeners","getState","this","setAuthenticated","authenticated","Date","now","notifyListeners","setRedirected","redirected","updateState","updates","reset","subscribe","listener","add","delete","forEach","stack","message","String","authProvider","res","next","reason","status","json","stringify","named","trimmed","trim","toLowerCase","end","indexOf","isIP","slice","ip","readHostHeader","some","allowed","matchesAllowedHost","config","templateName","mi","app","proxy","build","sync","inspector","devPanel","users","server","miMode","mode","appType","apiVersion","miHudLess","integrateMiTopBar","include","addSharedComponentsScripts","addRootElement","templateLess","resolvedName","defaultVersionFileTemplate","distZip","zipCfg","zip","versionPlugin","outFileName","outDir","fileName","inDir","vfCfg","versionFile","imageOptimizer","versionFileTemplate","enabled","fileNameTemplate","imgCfg","imageOptimisations","backendBaseURL","url","process","env","MI_BACKEND_URL","appId","id","enableProxyCache","cache","proxyCacheTTL","cacheTtl","disableSSLValidation","tls","allowSelfSigned","syncBackupsDir","backupsDir","syncMaxBackups","maxBackups","syncBuildTimeoutMs","buildTimeoutMs","v7Features","personalAccessToken","token","MI_ACCESS_TOKEN","inspectorEnabled","inspectorMaxMemory","maxMemory","inspectorCaptureLimit","captureLimit","devPanelPosition","position","devPanelHidden","hidden","devPanelAutoHide","autoHide","persistUsers","persist","map","directory","safeRelativePath","resolvedDirectory","resolvedFile","split","relativeToDirectory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CO,EAAoB8J,KAAK,SAGzF,MAAMzJ,EAAwBgE,EAAOU,QAAQ1E,aAE7C,UACmBnC,IAAjBmC,IACiB,IAAjBA,GACE0J,MAAMC,QAAQ3J,IAAiBA,EAAa4J,MAAO1J,GAAyB,iBAATA,GAAqC,KAAhBA,EAAKmD,SAE/F,MAAM,IAAIjE,MACR,0EAA0ErC,KAAKmG,UAAUlD,KAG/F"}
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-BZ6G8J6V.js"),a=require("./index-CNJgcIGX.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("svgtofont"),m=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("zlib"),require("express"),require("node:crypto"),require("node:fs"),require("node:os"),require("./helpers.js"),require("ejs");const v=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function b(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 w=b(e),y=b(t),P=b(d),x=v(p),S=b(u),E=b(g),T=v(h);function L(e){return null!=e&&!1!==e}let k=null;const D=[{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 I=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class F{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=w.resolve(S.tmpdir(),E.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=w.resolve(S.tmpdir(),E.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 y.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return y.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===y.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){y.existsSync(e)||y.mkdirSync(e,{recursive:!0})}async unzipFile(e,t){y.rmSync(t,{force:!0,recursive:!0}),await s.extractZipSafe(e,t)}normalizeAssetFolderPath(e){const t=y.readdirSync(e);return 1===t.length&&y.lstatSync(w.join(e,t[0])).isDirectory()?this.normalizeAssetFolderPath(w.join(e,t[0])):e}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const t=e.filter((e,t,o)=>0!==e.lineType||(t>=0&&t<this.contextLines||t>o.length-(this.contextLines+1)&&t<=o.length-1||o.slice(t-this.contextLines,t+this.contextLines+1).some(e=>0!==e.lineType))).map((e,t,o)=>{if(t>0){const n=o[t-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]}).flat().map(e=>this.diffLineHTML(e)).join("");return this.diffTableTemplate(t)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:t,lineContent:o,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${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 P.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(I.test(e)&&(e=e.replace(I,"$1$3")),I.test(t)&&(t=t.replace(I,"$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 x,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(w.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(w.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${o}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const t=e.path1&&e.name1?w.join(e.path1,e.name1):null,o=e.path2&&e.name2?w.join(e.path2,e.name2):null,n=this.pathToPosix(w.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&t)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&o)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&t&&o){const i=this.pathToPosix(w.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(w.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(y.readFileSync(t,"utf-8"),y.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("");y.writeFileSync(w.join(this.destinationPath,this.changelogFilename),n),this.logger.info(s.colors.green(`Changelog file written to ${w.join(this.destinationPath,this.changelogFilename)}`))}}class _{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await T({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class ${wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new m.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===m.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===m.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 j=r.cac("pp-dev");function A(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=>w.join(e,t)),r=i.watch(n,{ignored:e=>{const t=w.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: ${w.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 C(e){e.watcher&&e.watcher.close()}function N(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 R(e){const{changelog:t,executionRoot:o,newAssetsPath:n,backupsDirPath:i,changelogDestinationPath:r,logLevel:a}=e;let l;if("string"==typeof t)l=w.resolve(o,t);else{if(!y.existsSync(i))return void s.createLogger(a).warn(s.colors.yellow("backups directory not found, skipping changelog generation"));const e=y.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)=>y.statSync(w.resolve(i,e.name)).mtimeMs>y.statSync(w.resolve(i,t.name)).mtimeMs?e:t).name;l=w.resolve(i,o)}const c=new F({oldAssetsPath:l,newAssetsPath:n,destinationPath:r});await c.generateChangelog()}let M=global.__pp_dev_profile_session,q=0;const O=e=>{if(M)return new Promise((t,o)=>{M.post("Profiler.stop",(n,{profile:i})=>{if(n)o(n);else{const o=w.resolve(`./pp-dev-profile-${q++}.cpuprofile`);y.writeFileSync(o,JSON.stringify(i)),e(s.colors.yellow(`CPU profile written to ${s.colors.white(s.colors.dim(o))}`)),M=void 0,t()}})})},V=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function H(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}j.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"),j.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)=>{V(t);let o=null,i=null,r=!1;const c=e?w.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-CNJgcIGX.js")).then(e=>e.config);f();const{createServer:g}=await(import("vite")),h=t.mode||"development",m=w.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:H(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 y=global.__pp_dev_start_time??!1,P=y?s.colors.dim(`ready in ${s.colors.reset(s.colors.bold(Math.ceil(n.performance.now()-y)))} 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(L).concat(D);k?.(),k=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=()=>{k===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),r&&process.stdin.pause(),k=null)};k=p,d.on("close",p)}(o,{print:!0,customShortcuts:[...M?[{key:"p",description:"start/stop the profiler",async action(e){if(M)await O(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{M=new e.Session,M.connect(),M.post("Profiler.enable",()=>{M?.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=A(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}),O(d.info),process.exit(1)}}},f=async e=>{d.info(s.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{i&&(C(i),i=null),o&&(await o.close(),o=null),O(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()}),j.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)=>{V(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-CNJgcIGX.js")).then(e=>e.config);v();const{join:b,basename:P}=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=H(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-CNJgcIGX.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-CNJgcIGX.js")).then(e=>e.config);I=e(L).name}catch{I=P(L)}s.validatePPDevConfig(D,I??"");const F=s.normalizePPDevConfig(D,I??""),_=F.backendBaseURL??"http://localhost:8080",j=F.templateLess,R=F.v7Features,M=F.disableSSLValidation,q=F.enableProxyCache,O=F.proxyCacheTTL,V=F.personalAccessToken,U=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 J="";G?J=G:(J=j?s.PATH_PAGE_PREFIX:R?s.PATH_TEMPLATE_LOCAL_PREFIX:s.PATH_TEMPLATE_PREFIX,J+=`/${I}`);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(!N(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(!N(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: ${I}`)),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,t=s.createUserHostGuard();ie.unshift(t),ne.unshift(t),_.startsWith("https://")&&(o.EventEmitter.defaultMaxListeners=Math.max(o.EventEmitter.defaultMaxListeners,20));const l={headers:{host:e,referer:_,origin:_.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:Z,templateLess:j,disableSSLValidation:M,v7Features:R,personalAccessToken:V??process.env.MI_ACCESS_TOKEN};oe=new s.MiAPI(_,l);const c=s.initPPRedirect(J,I??void 0),d=(e,t,o)=>{c(e,t,o)};ie.push(d),ne.push(d);const f=a.createDevPanelAssetMiddleware(J);if(ie.push(f),ne.push(f),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 g=new RegExp(`^((${u=J,u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),m=s.initLoadPPData(g,oe,Object.assign({base:J},l,{miHudLess:U})),v=(e,t,o)=>{m(e,t,o)};ne.push(v);const b=J.endsWith("/")?J.substring(0,J.length-1):J,x={middlewares:{use:e=>e},config:{logger:console}},S=s.initProxy({devServer:x,baseURL:_,proxyIgnore:["/@vite","/@metricinsights","/@",b,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:M,miAPI:oe,templateName:I??void 0}),T=(e,t,o)=>{S(e,t,o)};ne.push(T);const D=s.internalServer,A=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(s.INSPECTOR_PATH)||e.url?.startsWith(s.VARIABLES_EDITOR_PATH)){return void D(e,t,()=>{})}o()};ie.push(A),ne.push(A);const C=s.initRewriteResponse(e=>{const t=e.split("?")[0];return t.startsWith(J)&&!t.includes("/_next/")},(t,o)=>{const n=oe.buildPage(t,U),i=a.injectDevPanel(n,J,{backendBaseURL:_,templateLess:j,appId:Z,devPanelPosition:F.devPanelPosition,devPanelHidden:F.devPanelHidden,devPanelAutoHide:F.devPanelAutoHide});return Buffer.from(s.urlReplacer(e,o.headers.host??"",i))}),N=(e,t,o)=>{C(e,t,o)};ne.push(N),r=new $;let H=k?.distDir;try{process.env[s.PP_DEV_NEXT_BUILD_ENV_VAR]="1";const e=await E(h.PHASE_PRODUCTION_BUILD,L);H=e?.distDir??H}catch{}const z=(H??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),W=z&&".next"!==z?z:"out";let B,G="0.0.0";try{const e=JSON.parse(y.readFileSync(w.join(L,"package.json"),"utf-8"));G="string"==typeof e.version?e.version:G,B="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const X=new s.DistService(I??P(L),{root:L,backupFolder:w.resolve(L,F.syncBackupsDir),nextBuild:{projectRoot:L,distDir:W,packageVersion:G,packageRepositoryUrl:B}}),K={ws:r.ws,config:{clientInjectionPlugin:{v7Features:R}}};new s.ClientService(K,{distService:X,miAPI:oe}),s.registerVariablesEditorRoutes(s.internalServer,{distService:X,miAPI:oe}),s.registerUserRoutes(s.internalServer,{miAPI:oe}),s.startKeepingUsers({persist:F.persistUsers,miAPI:oe,projectRoot:L,miUrl:_});const Y="function"==typeof n?.getUpgradeHandler?n.getUpgradeHandler():null;i.on("upgrade",(e,t,o)=>{r?.handleUpgrade(e,t,o)||(Y?Y(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=A(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&&(C(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&&(C(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()}),j.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)=>{V(t);const o=H(t),n=a.resolveBuildCliOverrides(t);try{const i=t.mode||"production",r=w.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 R({changelog:o.changelog,executionRoot:n,newAssetsPath:w.resolve(n,i),backupsDirPath:w.resolve(n,d.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:w.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{O(e=>s.createLogger(t.logLevel).info(e))}}),j.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)=>{V(t);const o=s.createLogger(t.logLevel),n=e?w.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-CNJgcIGX.js")).then(e=>e.config);p=await e(n)}try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-CNJgcIGX.js")).then(e=>e.config);d=e(n).name}catch{d=w.basename(n)}const f=s.normalizePPDevConfig(p,d),u=a.applyDistZipOverride(f.distZip,i,s.createDefaultZipFileName(d)),g=a.applyVersionManifestOverride(f.versionPlugin,i),h=s.removeStaleDevTypes(n,c);h&&o.info(s.colors.dim(`[pp-dev] Removed stale dev route types: ${w.relative(n,h)}`)),o.info(s.colors.cyan("[pp-dev] Running `next build`...")),await s.runNextBuildProcess(n);const m="string"==typeof c?.distDir&&c.distDir?c.distDir:".next",v=".next"===m?"out":m,b=w.resolve(n,v);if(!y.existsSync(b)||!y.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 P=JSON.parse(y.readFileSync(w.join(n,"package.json"),"utf-8"));if(!1!==g&&!1!==g.enabled&&(s.writeBuildVersionManifest({outDir:b,packageVersion:"string"==typeof P.version?P.version:"0.0.0",versionFileTemplate:g.versionFileTemplate,packageRepositoryUrl:"string"==typeof P.repository?P.repository:P.repository?.url,enabled:g.enabled}),o.info(s.colors.green(`✅ VERSION / BUILD-MANIFEST written to ${w.relative(n,b)}`))),!1!==u){const e=w.resolve(n,u.outDir),t=u.inDir?w.resolve(b,u.inDir):b,i=s.resolveOutputFilePath(e,u.outFileName,"ZIP output file name");y.mkdirSync(w.dirname(i),{recursive:!0});const r=await s.zipDirectoryToBuffer(t);y.writeFileSync(i,r),o.info(s.colors.green(`✅ Zip archive written to ${w.relative(n,i)}`))}if(t.changelog){const e=!1!==u?u.outDir:v;await R({changelog:t.changelog,executionRoot:n,newAssetsPath:b,backupsDirPath:w.resolve(n,f.syncBackupsDir),changelogDestinationPath:w.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{O(e=>s.createLogger(t.logLevel).info(e))}}),j.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)=>{V(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=w.resolve(c,n),p=w.resolve(c,i),f=w.resolve(c,r),u=new F({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await u.generateChangelog()}),j.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)=>{V(o);const{source:n=e,destination:i=t,fontName:r="icon-font"}=o,a=process.cwd(),l=w.resolve(a,n),c=w.resolve(a,i),d=new _({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)}`)}),j.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{V(t);try{const o=t.mode||"production",n=w.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)}}),j.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)=>{V(t);try{const o=t.mode||"production",n=w.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{O(e=>s.createLogger(t.logLevel).info(e))}}),j.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-DkUysGJq.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: ${w.relative(g,m)}`));const{getPkg:P}=await Promise.resolve().then(()=>require("./index-CNJgcIGX.js")).then(e=>e.config),x=P();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`;y.writeFileSync(n,o);try{const e=await(import(t(w.resolve(g,n)).toString()));E=e.default?.default??e.default??e}finally{y.existsSync(n)&&y.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(m)){const{pathToFileURL:e}=await(import("url")),t=await(import(e(w.resolve(g,m)).toString()));E=t.default?.default??t.default??t}else b?E=p(m):m.endsWith(".json")&&(E=JSON.parse(y.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??w.join(g,`pp-dev.config.${f}`);if(t.dryRun&&(o.info(s.colors.green(`\n--- Migrated config (dry-run) → ${w.relative(g,L)} ---\n`)),process.exit(0)),u&&!b&&y.existsSync(m)){const e=`${m}.bak`;y.copyFileSync(m,e),o.info(s.colors.blue(`Backed up original to: ${w.relative(g,e)}`))}y.writeFileSync(L,T,"utf-8"),o.info(s.colors.green(`✅ Migration complete → ${w.relative(g,L)}`)),b?o.info(s.colors.yellow('You can now remove the "pp-dev" field from package.json.')):m!==L&&y.existsSync(m)&&o.info(s.colors.yellow(`You can now delete the old config: ${w.relative(g,m)}`))}),j.help(),j.version(s.VERSION),j.parse(),exports.stopProfiler=O;
1
+ "use strict";const e=require("cac"),t=require("./auth.provider-CyXyBAm3.js"),o=require("path"),n=require("node:perf_hooks"),i=require("vite"),r=require("./request-capture.middleware-Chm27VXb.js"),s=require("chokidar"),a=require("./index-CeIQtamz.js"),l=require("fs"),c=require("node:events"),d=require("url"),p=require("ws"),f=require("dir-compare"),u=require("diff-match-patch"),g=require("isbinaryfile"),h=require("os"),m=require("crypto"),v=require("./version-manifest-C15hpGGV.js");require("picocolors"),require("node:path"),require("node:net"),require("zlib"),require("axios"),require("node:http"),require("node:https"),require("http-proxy-middleware"),require("node:string_decoder"),require("process"),require("jszip"),require("child_process"),require("module"),require("node:crypto"),require("node:fs"),require("node:os"),require("express"),require("node:module"),require("./helpers.js"),require("ejs"),require("fs/promises"),require("util");const w=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function b(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=b(o),P=b(l),x=b(f),S=w(u),L=b(h),E=b(m);function T(e){return null!=e&&!1!==e}let k=null;const D=new WeakMap;function F(e,o){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;D.set(e,o);const n=t.createLogger();o.print&&n.info(t.colors.dim(t.colors.green(" ➜"))+t.colors.dim(" press ")+t.colors.bold("h")+t.colors.dim(" to show help"));const i=(o.customShortcuts??[]).filter(T).concat(I);k?.(),k=null;let r=!1;const s=process.stdin.isPaused(),a=process.stdin,l=Boolean(a.isRaw),c=async o=>{if(""===o)return void function(e=process){"win32"===e.platform?e.emit("SIGINT","SIGINT"):e.kill(e.pid,"SIGINT")}();if(""===o)return void await e.close().finally(()=>process.exit(0));if(r)return;"h"===o&&n.info(["",t.colors.bold(" Shortcuts"),...i.map(e=>t.colors.dim(" press ")+t.colors.bold(e.key)+t.colors.dim(` to ${e.description}`))].join("\n"));const s=i.find(e=>e.key===o);s&&(r=!0,await s.action(e),r=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",c).setEncoding("utf8").resume();const d=e.httpServer,p=()=>{k===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),s&&process.stdin.pause(),k=null)};k=p,d.on("close",p)}const I=[{key:"r",description:"restart the server",async action(e){const t=D.get(e);await e.restart(),t&&F(e,{...t,print:!1})}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally(()=>process.exit())}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}];function _(e){return e instanceof Error?e.stack??e.message:String(e)}function N({logger:e,knownRejections:o=[],shutdown:n,shutdownTimeoutMs:i=5e3,processRef:r=process}){let s=!1,a=0;const l=async(o,l)=>{if((e=>{a=Math.max(a,e)})(l),s)return void("SIGINT"!==o&&"SIGTERM"!==o&&"SIGHUP"!==o||(e.warn(t.colors.yellow(`\n⚠️ Received ${o} again, exiting without waiting for the shutdown`)),r.exit(a)));s=!0,e.info(t.colors.yellow(`\n🛑 Received ${o}, shutting down gracefully...`));const c=setTimeout(()=>{e.error(t.colors.red(`⏰ Shutdown did not finish within ${i} ms, forcing exit`)),r.exit(1)},i);try{await n(),clearTimeout(c),e.info(t.colors.green("✅ Graceful shutdown completed")),r.exit(a)}catch(o){clearTimeout(c),e.error(t.colors.red(`❌ Error during graceful shutdown: ${_(o)}`)),r.exit(1)}},c=()=>{l("SIGINT",0)},d=()=>{l("SIGTERM",0)},p=()=>{l("SIGHUP",0)},f=o=>{e.error(t.colors.red(`❌ Uncaught exception: ${_(o)}`)),l("uncaughtException",1)},u=n=>{const i=o.find(e=>e.matches(n));i?e.info(t.colors.dim(i.message)):e.error(t.colors.red(`❌ Unhandled promise rejection (the server keeps running): ${_(n)}`))};return r.on("SIGINT",c),r.on("SIGTERM",d),r.on("SIGHUP",p),r.on("uncaughtException",f),r.on("unhandledRejection",u),()=>{r.off("SIGINT",c),r.off("SIGTERM",d),r.off("SIGHUP",p),r.off("uncaughtException",f),r.off("unhandledRejection",u)}}const j=["--","c","config","base","l","logLevel","clearScreen","configLoader","profile","d","debug","f","filter","m","mode","force","w","changelog","distZip","distZipDir","distZipFilename","versionManifest","versionFileTemplate","webpack","turbopack"];function $(e){const t={...e};for(const e of j)delete t[e];return"sourcemap"in t&&(t.sourcemap="true"===t.sourcemap||"false"!==t.sourcemap&&t.sourcemap),"watch"in t&&(t.watch=t.watch?{}:void 0),t}const A=["https","open","cors","strictPort","force"];function C(e,o,n){const i=[...t.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=s.watch(i,{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",i=>{n(t.colors.blue(`🔧 Config file changed: ${y.relative(e,i)}`)),a&&clearTimeout(a),a=setTimeout(async()=>{try{n(t.colors.yellow("🔄 Restarting dev server due to config change...")),await o()}catch(e){n(t.colors.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{n(t.colors.red(`❌ Config watcher error: ${e}`))}),{watcher:r}}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)}const H=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};async function q(e){const{root:t,mode:o,command:n}=e,r=y.resolve(process.cwd(),t??".");a.loadPPDevEnv(o,r);const s=await i.loadConfigFromFile({mode:o,command:n},e.configFile,t,e.logLevel);let l=await a.getViteConfig(e.buildOverrides,{mode:o,root:r});if(s){const e={...s.config};delete e.plugins,l=i.mergeConfig(l,e)}return{config:l,envDir:r}}let V=global.__pp_dev_profile_session,O=0;const U=e=>{if(V)return new Promise((o,n)=>{V.post("Profiler.stop",(i,{profile:r})=>{if(i)n(i);else{const n=y.resolve(`./pp-dev-profile-${O++}.cpuprofile`);P.writeFileSync(n,JSON.stringify(r)),e(t.colors.yellow(`CPU profile written to ${t.colors.white(t.colors.dim(n))}`)),V=void 0,o()}})})};function z(e){e.once("error",()=>e.destroy()),e.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n",()=>e.destroy())}class B{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;allowedHosts;constructor({allowedHosts:e=[]}={}){this.allowedHosts=e,this.wss=new p.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===p.WebSocket.OPEN&&e.send(t)}}}}handleUpgrade(e,o,n){return(e.url??"").split("?")[0]===r.PP_DEV_HMR_WS_PATH&&(t.crossOriginReason(e,this.allowedHosts)?(z(o),!0):(this.wss.handleUpgrade(e,o,n,t=>{this.wss.emit("connection",t,e)}),!0))}async close(){this.fireLifecycle("close");for(const e of this.clients.keys())e.terminate();this.clients.clear(),await new Promise(e=>this.wss.close(()=>e()))}onConnection(e){const t={send:(t,o)=>this.sendToSocket(e,t,o),socket:e};this.clients.set(e,t),e.on("message",e=>this.onMessage(t,e)),e.on("close",()=>this.clients.delete(e)),e.on("error",()=>{})}onMessage(e,o){let n;try{n=JSON.parse(o.toString())}catch{return}if(!n||"custom"!==n.type||"string"!=typeof n.event)return;const i=this.eventListeners.get(n.event);if(i)for(const o of i)try{o(n.data,e)}catch(e){t.createLogger().error(`ws handler for "${n.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===p.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 W={matches:e=>e instanceof Error&&"Worker creator already registered"===e.message,message:"Next.js kept its Turbopack worker pool from before the restart ('Worker creator already registered')"};const Z=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class G{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:o,newAssetsPath:n,destinationPath:i,changelogTemplate:r,diffFileTemplateHandler:s,diffLineTemplateHandler:a,changelogFilename:l,contextLines:c}=e;if(this.logger=t.createLogger(),!o||!n||!i)throw new Error("Previous assets path, current assets path and destination path are required");if(o===n)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(n))throw new Error(`Current assets path ${n} does not exist`);if(this.isZipFile(o)){const e=y.resolve(L.tmpdir(),E.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,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(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(n)){const e=y.resolve(L.tmpdir(),E.createHash("md5").update(n).digest("hex"));this.newAssetsPath=this.unzipFile(n,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(n))throw new Error(`Invalid current assets path ${n}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(n);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${n} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=i,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",r&&(this.templateIsValid(r)?this.changelogTemplate=r:this.logger.warn(t.colors.yellow("Invalid changelog template, using default"))),"function"==typeof s&&(this.diffFileTemplateHandler=s),"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 r.extractZipSafe(e,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(t.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)=>(Z.test(e)&&(e=e.replace(Z,"$1$3")),Z.test(t)&&(t=t.replace(Z,"$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 g.isBinaryFile(t)||await g.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(t.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),o=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(t.colors.green("Writing changelog file"));const n=this.changelogTemplate.split("%FILES%");n.splice(1,0,o);const i=n.join("");P.writeFileSync(y.join(this.destinationPath,this.changelogFilename),i),this.logger.info(t.colors.green(`Changelog file written to ${y.join(this.destinationPath,this.changelogFilename)}`))}}async function X(e){const{changelog:o,executionRoot:n,newAssetsPath:i,backupsDirPath:r,changelogDestinationPath:s,logLevel:a}=e;let l;if("string"==typeof o)l=y.resolve(n,o);else{if(!P.existsSync(r))return void t.createLogger(a).warn(t.colors.yellow("backups directory not found, skipping changelog generation"));const e=P.readdirSync(r,{withFileTypes:!0});if(!e.length)return void t.createLogger(a).warn(t.colors.yellow("no backups found, skipping changelog generation"));const o=e.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!o.length)return void t.createLogger(a).warn(t.colors.yellow("no ZIP backups found, skipping changelog generation"));const n=o.reduce((e,t)=>P.statSync(y.resolve(r,e.name)).mtimeMs>P.statSync(y.resolve(r,t.name)).mtimeMs?e:t).name;l=y.resolve(r,n)}const c=new G({oldAssetsPath:l,newAssetsPath:i,destinationPath:s});await c.generateChangelog()}class J{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){const{default:e}=await(import("svgtofont"));await e({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}const K=e.cac("pp-dev");K.option("-c, --config <file>","[string] use specified config file").option("--base <path>","[string] public base path (default: /)").option("-l, --logLevel <level>","[string] info | warn | error | silent").option("--clearScreen","[boolean] allow/disable clear screen when logging").option("-d, --debug [feat]","[string | boolean] show debug logs").option("-f, --filter <filter>","[string] filter debug logs").option("-m, --mode <mode>","[string] set env mode"),function(e){e.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{H(o);let s=null,a=null,l=!1;const c=e?y.resolve(process.cwd(),e):process.cwd(),d=t.createLogger(o.logLevel),p=async()=>{if(!l){l=!0;try{s&&(d.info(t.colors.yellow("🛑 Stopping existing dev server...")),await s.close(),s=null);const{clearConfigCache:u,getConfig:g}=await Promise.resolve().then(()=>require("./index-CeIQtamz.js")).then(e=>e.config);u();const{createServer:h}=await(import("vite")),m=o.mode||"development",{config:v,envDir:w}=await q({root:e,mode:m,command:"serve",configFile:o.config,logLevel:o.logLevel});if(s=await h(i.mergeConfig(v,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:$(o),customLogger:d},!0)),!s.config.base||"/"===s.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!s.httpServer)throw new Error("HTTP server not available");await s.listen();const b=global.__pp_dev_start_time??!1,y=b?t.colors.dim(`ready in ${t.colors.reset(t.colors.bold(Math.ceil(n.performance.now()-b)))} ms`):"";d.info(`\n ${t.colors.green(`${t.colors.bold("PP-DEV")} v${t.VERSION}`)} ${y}\n`),s.printUrls();const P=await g(w);if(!1!==P.inspector?.enabled){const e=s.resolvedUrls?.local[0],o=e?new URL(e).origin:`http://localhost:${s.config.server.port??5173}`;d.info(`\n ${t.colors.cyan("🔍 Request Inspector")} ${t.colors.dim(o+r.INSPECTOR_PATH)}\n`)}F(s,{print:!0,customShortcuts:[...(f=d.info,V?[{key:"p",description:"start/stop the profiler",async action(){if(V)await U(f);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{V=new e.Session,V.connect(),V.post("Profiler.enable",()=>{V?.post("Profiler.start",()=>{f("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("/")}`}})}}]}),a||(a=C(c,p,d.info),d.info(t.colors.blue("🔧 Config file watcher started"))),l=!1}catch(e){l=!1,d.error(t.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),U(d.info),process.exit(1)}var f}};N({logger:d,shutdown:async()=>{a&&(R(a),a=null),s&&(await s.close(),s=null),U(d.info)}}),await p()})}(K),function(e){e.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname; without a value, listen on all addresses").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] no effect with pp-dev next (deprecated)").option("--open [path]","[boolean | string] no effect with pp-dev next (deprecated)").option("--cors","[boolean] no effect with pp-dev next (deprecated)").option("--strictPort","[boolean] no effect with pp-dev next (deprecated)").option("--force","[boolean] no effect with pp-dev next (deprecated)").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(e,o)=>{H(o);const n=A.filter(e=>void 0!==o[e]);n.length>0&&t.createLogger(o.logLevel).warn(t.colors.yellow(`⚠️ ${n.map(e=>`--${e}`).join(", ")} ${1===n.length?"has":"have"} no effect with pp-dev next and will be removed.`));const{host:i,port:s}=function(e,t){let o="localhost";!0===e||""===e?o="0.0.0.0":"string"==typeof e?o=e:"number"==typeof e&&(o=String(e));const n="number"==typeof t?t:"string"==typeof t?Number.parseInt(t,10):NaN;return{host:o,port:Number.isInteger(n)&&n>=0?n:3e3}}(o.host,o.port);let l=null,p=null,f=null,u=null,g=null,h=!1;const m=new Set,v=t.createLogger(o.logLevel),w=function(e=["uncaughtException"],t=process){const o=e=>t.listeners(e);let n=null,i=null;return{beforeCreate(){n=new Map(e.map(e=>[e,new Set(o(e))]))},afterCreate(){if(!n)return 0;const r=n,s=new Map(e.map(e=>[e,o(e).filter(t=>!r.get(e).has(t))]));let a=0;if(i)for(const[e,o]of i){const n=new Set(s.get(e).map(e=>e.toString()));for(const i of o)n.has(i.toString())&&(t.off(e,i),a+=1)}return i=s,n=null,a}}}(),b=async()=>{l&&"function"==typeof l.close&&await l.close(),l=null},x=async()=>{const e=p;if(e){for(const e of m)e.destroy();m.clear(),await new Promise(t=>{e.close(()=>t())}),p===e&&(p=null)}},S=async()=>{if(!h){h=!0;try{const{next:n,constants:L}=await a.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:E}=L;u?.dispose(),u=null,f&&(await f.close(),f=null),p&&(v.info(t.colors.yellow("🛑 Stopping existing Next.js server...")),await x()),await b();const{clearConfigCache:T}=await Promise.resolve().then(()=>require("./index-CeIQtamz.js")).then(e=>e.config);T();const{join:k}=await(import("path")),{createServer:D}=await(import("http")),F=await(import("next/dist/server/config.js")),I=F.default.default||F["module.exports"].default||F.default,_=e?k(process.cwd(),e):process.cwd();a.loadPPDevEnv(o.mode||"development",_);const N=await I(E,_);let j=N?.ppDev||{};if(0===Object.keys(j).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-CeIQtamz.js")).then(e=>e.config),o=await e(_);Object.keys(o).length>0?(j=o,v.info(t.colors.blue("🔧 Loaded pp-dev config from standalone config file"))):v.info(t.colors.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){v.warn(t.colors.yellow(`⚠️ Failed to load standalone pp-dev config, using defaults: ${e instanceof Error?e.message:String(e)}`))}else v.info(t.colors.blue("🔧 Loaded pp-dev config from Next.js config"));const{getPkg:$}=await Promise.resolve().then(()=>require("./index-CeIQtamz.js")).then(e=>e.config),A=$(_).name;t.validatePPDevConfig(j,A);const R=t.normalizePPDevConfig(j,A),{templateName:H}=R,q=R.backendBaseURL,V=R.templateLess,O=R.v7Features,U=R.disableSSLValidation,W=R.enableProxyCache,Z=R.proxyCacheTTL,G=R.personalAccessToken,X=R.miHudLess,J=R.inspectorEnabled,K=R.inspectorMaxMemory,Y=R.inspectorCaptureLimit,Q=R.appId,ee=!0===R.allowedHosts||[...R.allowedHosts,i.toLowerCase()],te=r.createInternalServer({allowedHosts:R.allowedHosts}),oe=N?.basePath;let ne="";oe?ne=oe:(ne=V?t.PATH_PAGE_PREFIX:O?t.PATH_TEMPLATE_LOCAL_PREFIX:t.PATH_TEMPLATE_PREFIX,ne+=`/${H}`);const ie=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}:{}}(o),re=async e=>{delete process.env.TURBOPACK,await b();const t={dev:!0,customServer:!0,hostname:i,port:s,dir:_,conf:{...N,basePath:ne,assetPrefix:ne}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),w.beforeCreate(),l=n(t),await l.prepare(),w.afterCreate()};if(ie.webpack)await re({webpack:!0});else if(ie.turbopack)try{await re({turbopack:!0})}catch(e){if(!M(e))throw e;v.warn(t.colors.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await re({webpack:!0})}else try{await re({})}catch(e){if(!M(e))throw e;v.warn(t.colors.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await re({webpack:!0})}if(!l)throw new Error("Next.js app failed to initialize");if(ne.endsWith("/")||(ne+="/"),"/"===ne)throw new Error('basePath cannot be equal to "/" or equal to empty string');v.info(t.colors.green("✅ Next.js app prepared successfully")),v.info(t.colors.blue(`🔧 pp-dev plugin configured for template: ${H}`)),v.info(t.colors.blue(`🔧 Base path configured: ${ne}`)),q&&(v.info(t.colors.blue(`🌐 Backend URL: ${q}`)),v.info(t.colors.blue(`🆔 Custom App ID: ${Q}`)));const se=l.getRequestHandler(),ae=s,le=i;p=D(async(e,o)=>{const n=e.headers.host;if(!t.isHostAllowed(n,ee))return o.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),void o.end(t.hostNotAllowedMessage(n));try{const i=e.url||"/",r=i.split("?")[0];let s=d.parse(i,!0);if(fe.length>0){if(r.startsWith("/_next/")||"/favicon.ico"===r||r.startsWith("/__nextjs_")){if(ue.length>0){let p=0;const f=()=>{if(p>=ue.length)return void a();const t=ue[p];p++,t(e,o,f)};return void f()}return void a()}let l=0;const c=()=>{if(l>=fe.length)return void a();const t=fe[l];l++,t(e,o,c)};return void c()}async function a(){if(r.startsWith(ne))s=d.parse(i,!0);else{if(r===ne.replace(/\/$/,"")){const e=i.replace(r,ne);return o.writeHead(302,{Location:e}),void o.end()}if(r.startsWith("/_next/")||"/favicon.ico"===r||r.startsWith("/__nextjs_"));else if("/"===r)return o.writeHead(302,{Location:ne}),void o.end()}await se(e,o,s)}a()}catch(u){v.error(`Error handling request: ${u instanceof Error?u.message:String(u)}`,{error:u instanceof Error?u:void 0}),o.statusCode=500,o.end("Internal Server Error")}});let ce=null;const de=(e,o,n)=>{t.isHostAllowed(e.headers.host,ee)?ce?ce(e,o,n):p.listeners("upgrade").every(e=>e===de)&&o.destroy():z(o)};p.on("upgrade",de);let pe=null;const fe=[],ue=[];if(!1!==J){const e=new r.RequestStore(K);r.registerInspectorRoutes(te,e,Y);const t=r.createRequestCaptureMiddleware(e,Y);fe.push(t)}const ge=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(r.INSPECTOR_PATH)||e.url?.startsWith(r.VARIABLES_EDITOR_PATH)){return void te(e,t,()=>{})}o()};if(q||!1===J||(ue.push(ge),fe.push(ge)),q){const e=new URL(q).host,o=r.createUserHostGuard();ue.unshift(o),fe.unshift(o),q.startsWith("https://")&&(c.EventEmitter.defaultMaxListeners=Math.max(c.EventEmitter.defaultMaxListeners,20));const n=r.getMiAPIOptions(q,{appId:Q,templateLess:V,disableSSLValidation:U,v7Features:O,personalAccessToken:G});pe=new r.MiAPI(q,n);const i=r.initPPRedirect(ne,H),s=(e,t,o)=>{i(e,t,o)};ue.push(s),fe.push(s);const d=a.createDevPanelAssetMiddleware(ne);if(ue.push(d),fe.push(d),W){const e=r.resolveProxyCacheTtl(Z),o={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},n=r.initProxyCache(o),i=(e,t,o)=>{n(e,t,o)};fe.push(i),v.info(t.colors.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const p=r.getIndexPageRegExp(ne),g=r.initLoadPPData(p,pe,Object.assign({base:ne},n,{miHudLess:X})),h=(e,t,o)=>{g(e,t,o)};fe.push(h);const m={middlewares:{use:e=>e},config:{logger:console}},w=r.initProxy({devServer:m,baseURL:q,proxyIgnore:[...r.getProxyIgnore(ne),"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:U,miAPI:pe,templateName:H}),b=(e,t,o)=>{w(e,t,o)};fe.push(b),ue.push(ge),fe.push(ge);const x=r.initRewriteResponse(e=>{const t=e.split("?")[0];return t.startsWith(ne)&&!t.includes("/_next/")},(t,o)=>{const n=pe.buildPage(t,X),i=a.injectDevPanel(n,ne,{backendBaseURL:q,templateLess:V,appId:Q,devPanelPosition:R.devPanelPosition,devPanelHidden:R.devPanelHidden,devPanelAutoHide:R.devPanelAutoHide});return Buffer.from(r.urlReplacer(e,o.headers.host??"",i))}),S=(e,t,o)=>{x(e,t,o)};fe.push(S),f=new B({allowedHosts:R.allowedHosts});let E=N?.distDir;const T=process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR];process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]="1";try{const e=await I(L.PHASE_PRODUCTION_BUILD,_);E=e?.distDir??E}catch{}finally{void 0===T?delete process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]:process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]=T}const k=(E??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),D=k&&".next"!==k?k:"out";let F,j="0.0.0";try{const e=JSON.parse(P.readFileSync(y.join(_,"package.json"),"utf-8"));j="string"==typeof e.version?e.version:j,F="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const $=new r.DistService(H,{root:_,backupFolder:y.resolve(_,R.syncBackupsDir),maxBackups:R.syncMaxBackups,buildTimeoutMs:R.syncBuildTimeoutMs,nextBuild:{projectRoot:_,distDir:D,packageVersion:j,packageRepositoryUrl:F}}),A={ws:f.ws,config:{clientInjectionPlugin:{v7Features:O}}};u=r.startSyncAndUsers({server:A,internalServer:te,distService:$,miAPI:pe,persistUsers:R.persistUsers,projectRoot:_,miUrl:q});const C="function"==typeof l?.getUpgradeHandler?l.getUpgradeHandler():null;ce=(e,t,o)=>{f?.handleUpgrade(e,t,o)||(C?C(e,t,o):t.destroy())},v.info(t.colors.blue(`🔧 ${fe.length} pp-dev middlewares initialized`)),v.info(t.colors.blue(`🔧 ${ue.length} essential middlewares for internal routes`)),v.info(t.colors.blue(`🔧 MiAPI initialized for backend: ${q}`)),v.info(t.colors.blue(`🔧 Custom App ID: ${Q}`))}p.listen(ae,le,()=>{v.info(t.colors.green(`✅ pp-dev Next.js server running at http://${le}:${ae}`)),v.info(t.colors.blue(`📱 Next.js app accessible at http://${le}:${ae}${ne}`)),!1!==J&&v.info(t.colors.cyan(`🔍 Request Inspector: http://${le}:${ae}${r.INSPECTOR_PATH}`)),v.info(t.colors.blue("🔧 Base path handling active")),g||(g=C(_,S,v.info),v.info(t.colors.blue("🔧 Config file watcher started"))),p.on("connection",e=>{m.add(e),e.on("close",()=>m.delete(e))})}),h=!1}catch(e){h=!1,v.error(t.colors.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(v.error(t.colors.red("❌ Next.js Peer Dependency Error:")),v.error(t.colors.red(e.message)),v.error(t.colors.yellow("\n💡 To fix this issue:")),v.error(t.colors.blue(" 1. Install Next.js in your project:")),v.error(t.colors.white(" npm install next@^16")),v.error(t.colors.blue(" 2. Or use yarn:")),v.error(t.colors.white(" yarn add next@^16")),v.error(t.colors.blue(" 3. Or use pnpm:")),v.error(t.colors.white(" pnpm add next@^16")),v.error(t.colors.yellow("\n📖 For more information, see:")),v.error(t.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}}};N({logger:v,knownRejections:[W],shutdown:async()=>{g&&(R(g),g=null),u?.dispose(),u=null,f&&(await f.close(),f=null),await x(),await b()}}),await S()})}(K),function(e){e.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,o)=>{H(o);const n=$(o),r=a.resolveBuildCliOverrides(o);try{const t=o.mode||"production",{config:s}=await q({root:e,mode:t,command:"build",configFile:o.config,logLevel:o.logLevel,buildOverrides:r}),a=i.mergeConfig(s,{root:e,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},build:n},!0);if(await i.build(a),o.changelog){const t=e||process.cwd(),n=a.build?.outDir||"dist";let i="dist-zip";a.ppDevConfig&&(!1===a.ppDevConfig.distZip?i=n:"object"==typeof a.ppDevConfig.distZip&&"string"==typeof a.ppDevConfig.distZip.outDir&&(i=a.ppDevConfig.distZip.outDir)),await X({changelog:o.changelog,executionRoot:t,newAssetsPath:y.resolve(t,n),backupsDirPath:y.resolve(t,a.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:y.resolve(t,i),logLevel:o.logLevel})}}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{U(e=>t.createLogger(o.logLevel).info(e))}})}(K),function(e){e.command("next-build [root]","build a Next.js app for production (`next build`) and emit VERSION/BUILD-MANIFEST/zip in the same format as `pp-dev build`").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,o)=>{H(o);const n=t.createLogger(o.logLevel),i=e?y.resolve(process.cwd(),e):process.cwd(),s=a.resolveBuildCliOverrides(o);process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]="1";try{a.loadPPDevEnv(o.mode||"production",i);const{constants:e}=await a.safeNextImport(),l=await(import("next/dist/server/config.js")),c=l.default.default||l["module.exports"].default||l.default,d=await c(e.PHASE_PRODUCTION_BUILD,i);let p=d?.ppDev||{};if(0===Object.keys(p).length){const{getConfig:e}=await Promise.resolve().then(()=>require("./index-CeIQtamz.js")).then(e=>e.config);p=await e(i)}const{getPkg:f}=await Promise.resolve().then(()=>require("./index-CeIQtamz.js")).then(e=>e.config),u=t.normalizePPDevConfig(p,f(i).name),g=a.applyDistZipOverride(u.distZip,s,t.createDefaultZipFileName(u.templateName)),h=a.applyVersionManifestOverride(u.versionPlugin,s),m=r.removeStaleDevTypes(i,d);m&&n.info(t.colors.dim(`[pp-dev] Removed stale dev route types: ${y.relative(i,m)}`)),n.info(t.colors.cyan("[pp-dev] Running `next build`...")),await r.runNextBuildProcess(i);const w="string"==typeof d?.distDir&&d.distDir?d.distDir:".next",b=".next"===w?"out":w,x=y.resolve(i,b);if(!P.existsSync(x)||!P.statSync(x).isDirectory())throw new Error(`Next.js build output directory not found: ${x}. "next-build" requires "output: 'export'" in next.config (static export).`);const S=JSON.parse(P.readFileSync(y.join(i,"package.json"),"utf-8"));if(!1!==h&&!1!==h.enabled&&(await v.writeBuildVersionManifest({outDir:x,packageVersion:"string"==typeof S.version?S.version:"0.0.0",versionFileTemplate:h.versionFileTemplate,packageRepositoryUrl:"string"==typeof S.repository?S.repository:S.repository?.url,enabled:h.enabled}),n.info(t.colors.green(`✅ VERSION / BUILD-MANIFEST written to ${y.relative(i,x)}`))),!1!==g){const e=y.resolve(i,g.outDir),o=g.inDir?y.resolve(x,g.inDir):x,s=t.resolveOutputFilePath(e,g.outFileName,"ZIP output file name");P.mkdirSync(y.dirname(s),{recursive:!0});const a=await r.zipDirectoryToBuffer(o);P.writeFileSync(s,a),n.info(t.colors.green(`✅ Zip archive written to ${y.relative(i,s)}`))}if(o.changelog){const e=!1!==g?g.outDir:b;await X({changelog:o.changelog,executionRoot:i,newAssetsPath:x,backupsDirPath:y.resolve(i,u.syncBackupsDir),changelogDestinationPath:y.resolve(i,e),logLevel:o.logLevel})}}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{U(e=>t.createLogger(o.logLevel).info(e))}})}(K),function(e){e.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(e,o,n)=>{H(n);const{oldAssetsPath:i=e,newAssetsPath:r=o,destination:s=".",filename:a="CHANGELOG.html",logLevel:l}=n,c=process.cwd();i&&r||(t.createLogger(l).error(t.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=y.resolve(c,i),p=y.resolve(c,r),f=y.resolve(c,s),u=new G({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await u.generateChangelog()})}(K),function(e){e.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(e,o,n)=>{H(n);const{source:i=e,destination:r=o,fontName:s="icon-font"}=n,a=process.cwd(),l=y.resolve(a,i),c=y.resolve(a,r),d=new J({sourceDir:l,outputDir:c,fontName:s}),p=t.createLogger(n.logLevel);p.info(`Generating icon font from SVG files in ${t.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${t.colors.dim(c)}`)})}(K),function(e){e.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,o)=>{H(o);try{const t=o.mode||"production",{config:n}=await q({root:e,mode:t,command:"build",configFile:o.config,logLevel:o.logLevel}),r=await i.resolveConfig(i.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode}),"serve");await i.optimizeDeps(r,o.force,!0)}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}})}(K),function(e){e.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,o)=>{H(o);try{const t=o.mode||"production",{config:n}=await q({root:e,mode:t,command:"build",configFile:o.config,logLevel:o.logLevel});(await i.preview(i.mergeConfig(n,{root:e,base:o.base,configFile:o.config,logLevel:o.logLevel,mode:o.mode,build:{outDir:o.outDir},preview:{port:o.port,strictPort:o.strictPort,host:o.host,https:o.https,open:o.open}}))).printUrls()}catch(e){t.createLogger(o.logLevel).error(t.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{U(e=>t.createLogger(o.logLevel).info(e))}})}(K),function(e){e.command("migrate [config]","migrate pp-dev config from 0.x flat format to 1.0 grouped format").option("--dry-run","[boolean] print migrated config without writing any files").option("--format <format>","[string] output format: ts (default), js, json").option("--output <file>","[string] output file path (default: pp-dev.config.ts)").option("--no-backup","[boolean] skip backup of original config file").action(async(e,o)=>{const n=t.createLogger(o.logLevel),{isLegacyFlatConfig:i,isLegacyPPWatchConfig:r,isAlreadyMigrated:s,migrateLegacyFlatConfig:a,migratePPWatchConfig:l,generateConfigFileContent:c,discoverMigrateSource:d,loadPackageJsonMigrateConfig:p}=await Promise.resolve().then(()=>require("./migrate-C1svbbPB.js")),f=o.format??"ts",u=!1!==o.backup,g=process.cwd(),h=d(g,e);h||(n.warn(t.colors.yellow("No pp-dev or pp-watch config file found in the current directory.")),n.info(t.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:w}=h;n.info(t.colors.blue(`Found config: ${y.relative(g,m)}`));const{getPkg:b}=await Promise.resolve().then(()=>require("./index-CeIQtamz.js")).then(e=>e.config),x=b();let S,L={};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()));L=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()));L=t.default?.default??t.default??t}else w?L=p(m):m.endsWith(".json")&&(L=JSON.parse(P.readFileSync(m,"utf-8")))}catch(e){n.error(t.colors.red(`Failed to load config file: ${e.message}`)),process.exit(1)}L&&"object"==typeof L||(n.error(t.colors.red("Config file did not export a valid object.")),process.exit(1)),s(L)?(n.info(t.colors.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):v||r(L)?(n.info(t.colors.blue("Detected pp-watch config format → migrating to 1.0")),S=l(L)):i(L)?(n.info(t.colors.blue("Detected 0.x flat config format → migrating to 1.0")),S=a(L,x.name)):(n.warn(t.colors.yellow("Could not detect config format. No known keys found.")),process.exit(1));const E=c(S,f),T=o.output??y.join(g,`pp-dev.config.${f}`);if(o.dryRun&&(n.info(t.colors.green(`\n--- Migrated config (dry-run) → ${y.relative(g,T)} ---\n`)),process.exit(0)),u&&!w&&P.existsSync(m)){const e=`${m}.bak`;P.copyFileSync(m,e),n.info(t.colors.blue(`Backed up original to: ${y.relative(g,e)}`))}P.writeFileSync(T,E,"utf-8"),n.info(t.colors.green(`✅ Migration complete → ${y.relative(g,T)}`)),w?n.info(t.colors.yellow('You can now remove the "pp-dev" field from package.json.')):m!==T&&P.existsSync(m)&&n.info(t.colors.yellow(`You can now delete the old config: ${y.relative(g,m)}`))})}(K),K.help(),K.version(t.VERSION),K.parse(),exports.stopProfiler=U;
2
2
  //# sourceMappingURL=cli.js.map