@metricinsights/pp-dev 1.0.0-beta.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +72 -11
- package/dist/CHANGELOG.md +27 -0
- package/dist/README.md +72 -11
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/cli.js.map +1 -1
- package/dist/cjs/index-ctxv-2Kt.js +2 -0
- package/dist/cjs/index-ctxv-2Kt.js.map +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/package.json +3 -3
- package/dist/cjs/plugin-cgWPoZgR.js +2 -0
- package/dist/cjs/plugin-cgWPoZgR.js.map +1 -0
- package/dist/cjs/plugin.js +1 -1
- package/dist/cjs/{version-plugin-DsC5NLoX.js → version-plugin-Bhywa-Hu.js} +2 -2
- package/dist/cjs/{version-plugin-DsC5NLoX.js.map → version-plugin-Bhywa-Hu.js.map} +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/cli.js.map +1 -1
- package/dist/esm/index-N58WZBr_.js +2 -0
- package/dist/esm/index-N58WZBr_.js.map +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/package.json +3 -3
- package/dist/esm/plugin-ClbE2EOy.js +2 -0
- package/dist/esm/plugin-ClbE2EOy.js.map +1 -0
- package/dist/esm/plugin.js +1 -1
- package/dist/esm/{version-plugin-BGWVTSsN.js → version-plugin-Lyuzh4c2.js} +2 -2
- package/dist/esm/{version-plugin-BGWVTSsN.js.map → version-plugin-Lyuzh4c2.js.map} +1 -1
- package/dist/types/index.d.ts +10 -2
- package/package.json +3 -3
- package/dist/cjs/index-DeUfAH6g.js +0 -2
- package/dist/cjs/index-DeUfAH6g.js.map +0 -1
- package/dist/cjs/plugin-Cm9vRLCu.js +0 -2
- package/dist/cjs/plugin-Cm9vRLCu.js.map +0 -1
- package/dist/esm/index-DOjGFYJ7.js +0 -2
- package/dist/esm/index-DOjGFYJ7.js.map +0 -1
- package/dist/esm/plugin-B2ocw-wb.js +0 -2
- package/dist/esm/plugin-B2ocw-wb.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
+
# [1.1.0-beta.3](https://github.com/mi-examples/pp-dev/compare/v1.1.0-beta.2...v1.1.0-beta.3) (2026-07-21)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Bug Fixes
|
|
5
|
+
|
|
6
|
+
* don't log VERSION/BUILD-MANIFEST written when versionFile is disabled ([100820c](https://github.com/mi-examples/pp-dev/commit/100820cddc0d283c00850e640e5dae7b065c0db4)), closes [#208](https://github.com/mi-examples/pp-dev/issues/208)
|
|
7
|
+
|
|
8
|
+
# [1.1.0-beta.2](https://github.com/mi-examples/pp-dev/compare/v1.1.0-beta.1...v1.1.0-beta.2) (2026-07-21)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Features
|
|
12
|
+
|
|
13
|
+
* warn when a wrapped Next.js app builds via plain `next build` ([be6d4c2](https://github.com/mi-examples/pp-dev/commit/be6d4c2b4f6a176c2c3057e240106bc02b3781f7))
|
|
14
|
+
|
|
15
|
+
# [1.1.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v1.0.0...v1.1.0-beta.1) (2026-07-21)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
### Bug Fixes
|
|
19
|
+
|
|
20
|
+
* address new npm audit advisories in root and test fixtures ([c02c3dc](https://github.com/mi-examples/pp-dev/commit/c02c3dc94a06d238df3c4383fb906b335db54eed))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
### Features
|
|
24
|
+
|
|
25
|
+
* add `next-build` command for Next.js build output parity with `pp-dev build` ([f16871e](https://github.com/mi-examples/pp-dev/commit/f16871ebbc05588800805cb2bd1ccfd27d25f763))
|
|
26
|
+
* extract shared next-build helpers and CLI/env build-output overrides ([cd455ac](https://github.com/mi-examples/pp-dev/commit/cd455ac4b8488178f72416d43267b4545aa508c9))
|
|
27
|
+
|
|
1
28
|
# [1.0.0-beta.2](https://github.com/mi-examples/pp-dev/compare/v1.0.0-beta.1...v1.0.0-beta.2) (2026-07-07)
|
|
2
29
|
|
|
3
30
|
|
package/README.md
CHANGED
|
@@ -223,9 +223,18 @@ pp-dev validates your config at startup and reports problems clearly:
|
|
|
223
223
|
|
|
224
224
|
### Environment Variables
|
|
225
225
|
|
|
226
|
-
| Variable
|
|
227
|
-
|
|
228
|
-
| `MI_ACCESS_TOKEN`
|
|
226
|
+
| Variable | Description |
|
|
227
|
+
|----------------------------------|-------------------------------------------------------------------------------------|
|
|
228
|
+
| `MI_ACCESS_TOKEN` | Default value for `mi.token` when not set in config |
|
|
229
|
+
| `PP_DEV_DIST_ZIP` | `true`/`false` — override `build.zip` for `pp-dev build` / `pp-dev next-build` |
|
|
230
|
+
| `PP_DEV_DIST_ZIP_DIR` | Override the ZIP output directory (`build.zip.outDir`) |
|
|
231
|
+
| `PP_DEV_DIST_ZIP_FILENAME` | Override the ZIP file name (`build.zip.fileName`) |
|
|
232
|
+
| `PP_DEV_VERSION_MANIFEST` | `true`/`false` — override `build.versionFile` (VERSION/BUILD-MANIFEST generation) |
|
|
233
|
+
| `PP_DEV_VERSION_FILE_TEMPLATE` | Override the VERSION file name template |
|
|
234
|
+
|
|
235
|
+
The `PP_DEV_DIST_ZIP*`/`PP_DEV_VERSION_*` variables are read by `pp-dev build` and
|
|
236
|
+
`pp-dev next-build`; an equivalent CLI flag always takes precedence over its env var. See
|
|
237
|
+
[Build](#build) / [Next.js Build](#nextjs-build).
|
|
229
238
|
|
|
230
239
|
**Local development and network exposure**: pp-dev is a **development** tool. It assumes a trusted machine. Personal access tokens and session helpers are still sensitive: they can authenticate to your Metric Insights backend as you.
|
|
231
240
|
|
|
@@ -330,13 +339,62 @@ pp-dev next [options]
|
|
|
330
339
|
pp-dev build [options]
|
|
331
340
|
```
|
|
332
341
|
|
|
333
|
-
| Option
|
|
334
|
-
|
|
|
335
|
-
| `[root]`
|
|
336
|
-
| `--target <target>`
|
|
337
|
-
| `--outDir <dir>`
|
|
338
|
-
| `--assetsDir <dir>`
|
|
339
|
-
| `--changelog [file]`
|
|
342
|
+
| Option | Default | Description |
|
|
343
|
+
| ------------------------------- | --------- | ------------------------------------------------------ |
|
|
344
|
+
| `[root]` | `.` | Root directory of the application |
|
|
345
|
+
| `--target <target>` | `modules` | Transpile target |
|
|
346
|
+
| `--outDir <dir>` | `dist` | Output directory |
|
|
347
|
+
| `--assetsDir <dir>` | `assets` | Assets directory under outDir |
|
|
348
|
+
| `--changelog [file]` | `true` | Create changelog file |
|
|
349
|
+
| `--distZip` / `--no-distZip` | see below | Override `build.zip` — pack (or skip) the output ZIP |
|
|
350
|
+
| `--distZipDir <dir>` | see below | Override the ZIP output directory (`build.zip.outDir`) |
|
|
351
|
+
| `--distZipFilename <file>` | see below | Override the ZIP file name (`build.zip.fileName`) |
|
|
352
|
+
| `--versionManifest` / `--no-versionManifest` | see below | Override `build.versionFile` — emit (or skip) VERSION/BUILD-MANIFEST |
|
|
353
|
+
| `--versionFileTemplate <tpl>` | see below | Override the VERSION file name template |
|
|
354
|
+
|
|
355
|
+
The `--distZip*`/`--versionManifest*` flags (and their `PP_DEV_*` env var equivalents, see
|
|
356
|
+
[Environment Variables](#environment-variables)) let CI or ad-hoc builds override the `build.zip`
|
|
357
|
+
and `build.versionFile` config without editing `pp-dev.config`. Precedence: CLI flag > env var >
|
|
358
|
+
config file > built-in default. The same flags are available on `pp-dev next-build` (below).
|
|
359
|
+
|
|
360
|
+
### Next.js Build
|
|
361
|
+
|
|
362
|
+
```bash
|
|
363
|
+
pp-dev next-build [options]
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
Plain `next build` only produces the Next.js static export — no VERSION file, BUILD-MANIFEST, or
|
|
367
|
+
ZIP archive. `pp-dev next-build` runs `next build` and then applies the same post-build steps as
|
|
368
|
+
`pp-dev build`, so Next.js and Vite templates produce build artifacts in the same format:
|
|
369
|
+
|
|
370
|
+
1. Runs `next build` (requires `output: 'export'` in `next.config`)
|
|
371
|
+
2. Writes `VERSION-*.json` + `BUILD-MANIFEST.json` into the export directory (`build.versionFile`)
|
|
372
|
+
3. Zips the export directory into `dist-zip/<name>.zip` (`build.zip`)
|
|
373
|
+
|
|
374
|
+
If a project using `withPPDev()` still runs plain `next build` (e.g. directly, or via a `build`
|
|
375
|
+
script nobody updated), `withPPDev()` prints a console warning during the production build phase
|
|
376
|
+
suggesting `pp-dev next-build` instead. The warning is suppressed automatically when the build was
|
|
377
|
+
started by `pp-dev next-build` itself.
|
|
378
|
+
|
|
379
|
+
Use it in place of `next build` in your `package.json`:
|
|
380
|
+
|
|
381
|
+
```json
|
|
382
|
+
{
|
|
383
|
+
"scripts": {
|
|
384
|
+
"build": "pp-dev next-build --changelog"
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
| Option | Default | Description |
|
|
390
|
+
| ------------------------------- | --------- | ------------------------------------------------------ |
|
|
391
|
+
| `[root]` | `.` | Root directory of the application |
|
|
392
|
+
| `--changelog [file]` | `true` | Create changelog file |
|
|
393
|
+
| `--distZip` / `--no-distZip` | see below | Override `build.zip` — pack (or skip) the output ZIP |
|
|
394
|
+
| `--distZipDir <dir>` | see below | Override the ZIP output directory (`build.zip.outDir`) |
|
|
395
|
+
| `--distZipFilename <file>` | see below | Override the ZIP file name (`build.zip.fileName`) |
|
|
396
|
+
| `--versionManifest` / `--no-versionManifest` | see below | Override `build.versionFile` — emit (or skip) VERSION/BUILD-MANIFEST |
|
|
397
|
+
| `--versionFileTemplate <tpl>` | see below | Override the VERSION file name template |
|
|
340
398
|
|
|
341
399
|
### Migration
|
|
342
400
|
|
|
@@ -388,10 +446,13 @@ pp-dev generate-icon-font [source] [destination] [options]
|
|
|
388
446
|
```json
|
|
389
447
|
{
|
|
390
448
|
"scripts": {
|
|
391
|
-
"dev": "pp-dev next"
|
|
449
|
+
"dev": "pp-dev next",
|
|
450
|
+
"build": "pp-dev next-build"
|
|
392
451
|
}
|
|
393
452
|
}
|
|
394
453
|
```
|
|
454
|
+
`pp-dev next-build` replaces a plain `next build` so the Next.js template produces the same
|
|
455
|
+
VERSION/BUILD-MANIFEST/ZIP artifacts as `pp-dev build` — see [Next.js Build](#nextjs-build).
|
|
395
456
|
3. Wrap your Next.js config:
|
|
396
457
|
|
|
397
458
|
```javascript
|
package/dist/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
+
# [1.1.0-beta.3](https://github.com/mi-examples/pp-dev/compare/v1.1.0-beta.2...v1.1.0-beta.3) (2026-07-21)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Bug Fixes
|
|
5
|
+
|
|
6
|
+
* don't log VERSION/BUILD-MANIFEST written when versionFile is disabled ([100820c](https://github.com/mi-examples/pp-dev/commit/100820cddc0d283c00850e640e5dae7b065c0db4)), closes [#208](https://github.com/mi-examples/pp-dev/issues/208)
|
|
7
|
+
|
|
8
|
+
# [1.1.0-beta.2](https://github.com/mi-examples/pp-dev/compare/v1.1.0-beta.1...v1.1.0-beta.2) (2026-07-21)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Features
|
|
12
|
+
|
|
13
|
+
* warn when a wrapped Next.js app builds via plain `next build` ([be6d4c2](https://github.com/mi-examples/pp-dev/commit/be6d4c2b4f6a176c2c3057e240106bc02b3781f7))
|
|
14
|
+
|
|
15
|
+
# [1.1.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v1.0.0...v1.1.0-beta.1) (2026-07-21)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
### Bug Fixes
|
|
19
|
+
|
|
20
|
+
* address new npm audit advisories in root and test fixtures ([c02c3dc](https://github.com/mi-examples/pp-dev/commit/c02c3dc94a06d238df3c4383fb906b335db54eed))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
### Features
|
|
24
|
+
|
|
25
|
+
* add `next-build` command for Next.js build output parity with `pp-dev build` ([f16871e](https://github.com/mi-examples/pp-dev/commit/f16871ebbc05588800805cb2bd1ccfd27d25f763))
|
|
26
|
+
* extract shared next-build helpers and CLI/env build-output overrides ([cd455ac](https://github.com/mi-examples/pp-dev/commit/cd455ac4b8488178f72416d43267b4545aa508c9))
|
|
27
|
+
|
|
1
28
|
# [1.0.0-beta.2](https://github.com/mi-examples/pp-dev/compare/v1.0.0-beta.1...v1.0.0-beta.2) (2026-07-07)
|
|
2
29
|
|
|
3
30
|
|
package/dist/README.md
CHANGED
|
@@ -223,9 +223,18 @@ pp-dev validates your config at startup and reports problems clearly:
|
|
|
223
223
|
|
|
224
224
|
### Environment Variables
|
|
225
225
|
|
|
226
|
-
| Variable
|
|
227
|
-
|
|
228
|
-
| `MI_ACCESS_TOKEN`
|
|
226
|
+
| Variable | Description |
|
|
227
|
+
|----------------------------------|-------------------------------------------------------------------------------------|
|
|
228
|
+
| `MI_ACCESS_TOKEN` | Default value for `mi.token` when not set in config |
|
|
229
|
+
| `PP_DEV_DIST_ZIP` | `true`/`false` — override `build.zip` for `pp-dev build` / `pp-dev next-build` |
|
|
230
|
+
| `PP_DEV_DIST_ZIP_DIR` | Override the ZIP output directory (`build.zip.outDir`) |
|
|
231
|
+
| `PP_DEV_DIST_ZIP_FILENAME` | Override the ZIP file name (`build.zip.fileName`) |
|
|
232
|
+
| `PP_DEV_VERSION_MANIFEST` | `true`/`false` — override `build.versionFile` (VERSION/BUILD-MANIFEST generation) |
|
|
233
|
+
| `PP_DEV_VERSION_FILE_TEMPLATE` | Override the VERSION file name template |
|
|
234
|
+
|
|
235
|
+
The `PP_DEV_DIST_ZIP*`/`PP_DEV_VERSION_*` variables are read by `pp-dev build` and
|
|
236
|
+
`pp-dev next-build`; an equivalent CLI flag always takes precedence over its env var. See
|
|
237
|
+
[Build](#build) / [Next.js Build](#nextjs-build).
|
|
229
238
|
|
|
230
239
|
**Local development and network exposure**: pp-dev is a **development** tool. It assumes a trusted machine. Personal access tokens and session helpers are still sensitive: they can authenticate to your Metric Insights backend as you.
|
|
231
240
|
|
|
@@ -330,13 +339,62 @@ pp-dev next [options]
|
|
|
330
339
|
pp-dev build [options]
|
|
331
340
|
```
|
|
332
341
|
|
|
333
|
-
| Option
|
|
334
|
-
|
|
|
335
|
-
| `[root]`
|
|
336
|
-
| `--target <target>`
|
|
337
|
-
| `--outDir <dir>`
|
|
338
|
-
| `--assetsDir <dir>`
|
|
339
|
-
| `--changelog [file]`
|
|
342
|
+
| Option | Default | Description |
|
|
343
|
+
| ------------------------------- | --------- | ------------------------------------------------------ |
|
|
344
|
+
| `[root]` | `.` | Root directory of the application |
|
|
345
|
+
| `--target <target>` | `modules` | Transpile target |
|
|
346
|
+
| `--outDir <dir>` | `dist` | Output directory |
|
|
347
|
+
| `--assetsDir <dir>` | `assets` | Assets directory under outDir |
|
|
348
|
+
| `--changelog [file]` | `true` | Create changelog file |
|
|
349
|
+
| `--distZip` / `--no-distZip` | see below | Override `build.zip` — pack (or skip) the output ZIP |
|
|
350
|
+
| `--distZipDir <dir>` | see below | Override the ZIP output directory (`build.zip.outDir`) |
|
|
351
|
+
| `--distZipFilename <file>` | see below | Override the ZIP file name (`build.zip.fileName`) |
|
|
352
|
+
| `--versionManifest` / `--no-versionManifest` | see below | Override `build.versionFile` — emit (or skip) VERSION/BUILD-MANIFEST |
|
|
353
|
+
| `--versionFileTemplate <tpl>` | see below | Override the VERSION file name template |
|
|
354
|
+
|
|
355
|
+
The `--distZip*`/`--versionManifest*` flags (and their `PP_DEV_*` env var equivalents, see
|
|
356
|
+
[Environment Variables](#environment-variables)) let CI or ad-hoc builds override the `build.zip`
|
|
357
|
+
and `build.versionFile` config without editing `pp-dev.config`. Precedence: CLI flag > env var >
|
|
358
|
+
config file > built-in default. The same flags are available on `pp-dev next-build` (below).
|
|
359
|
+
|
|
360
|
+
### Next.js Build
|
|
361
|
+
|
|
362
|
+
```bash
|
|
363
|
+
pp-dev next-build [options]
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
Plain `next build` only produces the Next.js static export — no VERSION file, BUILD-MANIFEST, or
|
|
367
|
+
ZIP archive. `pp-dev next-build` runs `next build` and then applies the same post-build steps as
|
|
368
|
+
`pp-dev build`, so Next.js and Vite templates produce build artifacts in the same format:
|
|
369
|
+
|
|
370
|
+
1. Runs `next build` (requires `output: 'export'` in `next.config`)
|
|
371
|
+
2. Writes `VERSION-*.json` + `BUILD-MANIFEST.json` into the export directory (`build.versionFile`)
|
|
372
|
+
3. Zips the export directory into `dist-zip/<name>.zip` (`build.zip`)
|
|
373
|
+
|
|
374
|
+
If a project using `withPPDev()` still runs plain `next build` (e.g. directly, or via a `build`
|
|
375
|
+
script nobody updated), `withPPDev()` prints a console warning during the production build phase
|
|
376
|
+
suggesting `pp-dev next-build` instead. The warning is suppressed automatically when the build was
|
|
377
|
+
started by `pp-dev next-build` itself.
|
|
378
|
+
|
|
379
|
+
Use it in place of `next build` in your `package.json`:
|
|
380
|
+
|
|
381
|
+
```json
|
|
382
|
+
{
|
|
383
|
+
"scripts": {
|
|
384
|
+
"build": "pp-dev next-build --changelog"
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
| Option | Default | Description |
|
|
390
|
+
| ------------------------------- | --------- | ------------------------------------------------------ |
|
|
391
|
+
| `[root]` | `.` | Root directory of the application |
|
|
392
|
+
| `--changelog [file]` | `true` | Create changelog file |
|
|
393
|
+
| `--distZip` / `--no-distZip` | see below | Override `build.zip` — pack (or skip) the output ZIP |
|
|
394
|
+
| `--distZipDir <dir>` | see below | Override the ZIP output directory (`build.zip.outDir`) |
|
|
395
|
+
| `--distZipFilename <file>` | see below | Override the ZIP file name (`build.zip.fileName`) |
|
|
396
|
+
| `--versionManifest` / `--no-versionManifest` | see below | Override `build.versionFile` — emit (or skip) VERSION/BUILD-MANIFEST |
|
|
397
|
+
| `--versionFileTemplate <tpl>` | see below | Override the VERSION file name template |
|
|
340
398
|
|
|
341
399
|
### Migration
|
|
342
400
|
|
|
@@ -388,10 +446,13 @@ pp-dev generate-icon-font [source] [destination] [options]
|
|
|
388
446
|
```json
|
|
389
447
|
{
|
|
390
448
|
"scripts": {
|
|
391
|
-
"dev": "pp-dev next"
|
|
449
|
+
"dev": "pp-dev next",
|
|
450
|
+
"build": "pp-dev next-build"
|
|
392
451
|
}
|
|
393
452
|
}
|
|
394
453
|
```
|
|
454
|
+
`pp-dev next-build` replaces a plain `next build` so the Next.js template produces the same
|
|
455
|
+
VERSION/BUILD-MANIFEST/ZIP artifacts as `pp-dev build` — see [Next.js Build](#nextjs-build).
|
|
395
456
|
3. Wrap your Next.js config:
|
|
396
457
|
|
|
397
458
|
```javascript
|
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("vite"),a=require("./plugin-Cm9vRLCu.js"),l=require("./index-DeUfAH6g.js"),c=require("url"),d=require("dir-compare"),p=require("diff-match-patch"),f=require("isbinaryfile"),u=require("os"),g=require("crypto"),h=require("extract-zip"),m=require("svgtofont"),b=require("ws");require("http-proxy-middleware"),require("picocolors"),require("axios"),require("node:http"),require("node:https"),require("jsdom"),require("process"),require("child_process"),require("module"),require("jszip"),require("memory-cache"),require("zlib"),require("express"),require("node:crypto"),require("./helpers.js"),require("ejs");const w=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function v(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=v(e),P=v(t),x=v(d),S=w(p),T=v(u),L=v(g),k=w(h),$=w(m);function E(e){return null!=e&&!1!==e}let j=null;const F=[{key:"r",description:"restart the server",async action(e){await e.restart()}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally(()=>process.exit())}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}];const C=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class A{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:s,changelogFilename:l,contextLines:c}=e;if(this.logger=a.createLogger(),!t||!o||!n)throw new Error("Previous assets path, current assets path and destination path are required");if(t===o)throw new Error("Previous and current assets paths must be different");if(!this.isExists(t))throw new Error(`Previous assets path ${t} does not exist`);if(!this.isExists(o))throw new Error(`Current assets path ${o} does not exist`);if(this.isZipFile(t)){const e=y.resolve(T.tmpdir(),L.createHash("md5").update(t).digest("hex"));this.oldAssetsPath=this.unzipFile(t,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(t))throw new Error(`Invalid previous assets path ${t}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(t);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(o)){const e=y.resolve(T.tmpdir(),L.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(a.colors.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof s&&(this.diffLineTemplateHandler=s),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){return P.rmSync(t,{force:!0,recursive:!0}),k(e,{dir: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(a.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)=>(C.test(e)&&(e=e.replace(C,"$1$3")),C.test(t)&&(t=t.replace(C,"$1$3")),0===e.localeCompare(t)?0:e.localeCompare(t)>0?1:-1)});return e.diffSet?.filter(e=>"equal"!==e.state||e.name1!==e.name2)||[]}async generateAssetFilesDiff(e,t){const o=new S,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let r=0;return i.map(e=>{const[t,o]=e,n=o.endsWith("\n")?o.split("\n").length-1:o.split("\n").length,i=o.split("\n").map((e,o)=>({lineContent:e,lineNumber:r+o+1,lineType:t})).slice(0,n);return-1!==t&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const t=this.pathToPosix(y.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(y.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${o}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const t=e.path1&&e.name1?y.join(e.path1,e.name1):null,o=e.path2&&e.name2?y.join(e.path2,e.name2):null,n=this.pathToPosix(y.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&t)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&o)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&t&&o){const i=this.pathToPosix(y.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(y.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await f.isBinaryFile(t)||await f.isBinaryFile(o)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(P.readFileSync(t,"utf-8"),P.readFileSync(o,"utf-8"))))}return""}async generateChangelog(){this.logger.info(a.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),t=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(a.colors.green("Writing changelog file"));const o=this.changelogTemplate.split("%FILES%");o.splice(1,0,t);const n=o.join("");P.writeFileSync(y.join(this.destinationPath,this.changelogFilename),n),this.logger.info(a.colors.green(`Changelog file written to ${y.join(this.destinationPath,this.changelogFilename)}`))}}class D{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await $({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class I{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new b.WebSocketServer({noServer:!0}),this.wss.on("connection",e=>this.onConnection(e)),this.wss.on("error",e=>this.fireLifecycle("error",e)),this.ws={on:(e,t)=>{"close"!==e&&"error"!==e?this.getEventSet(e).add(t):this.getLifecycleSet(e).add(t)},off:(e,t)=>{this.eventListeners.get(e)?.delete(t),"close"!==e&&"error"!==e||this.lifecycleListeners.get(e)?.delete(t)},send:(e,t)=>{if("string"==typeof e)for(const o of this.clients.keys())this.sendToSocket(o,e,t);else{const t=JSON.stringify(e);for(const e of this.clients.keys())e.readyState===b.WebSocket.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===a.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){a.createLogger().error(`ws handler for "${o.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===b.WebSocket.OPEN&&e.send(JSON.stringify({type:"custom",event:t,data:o}))}fireLifecycle(e,t){for(const o of this.lifecycleListeners.get(e)??[])try{o(t)}catch{}}getEventSet(e){let t=this.eventListeners.get(e);return t||(t=new Set,this.eventListeners.set(e,t)),t}getLifecycleSet(e){let t=this.lifecycleListeners.get(e);return t||(t=new Set,this.lifecycleListeners.set(e,t)),t}}const _=r.cac("pp-dev");function N(e,t,o){const n=[...a.PP_DEV_CONFIG_NAMES,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"].map(t=>y.join(e,t)),r=i.watch(n,{ignored:e=>{const t=y.basename(e);return/(^|[\/\\])\../.test(e)&&!t.startsWith(".env")&&!t.startsWith(".pp-dev")&&!t.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let s=null;return r.on("change",n=>{o(a.colors.blue(`🔧 Config file changed: ${y.relative(e,n)}`)),s&&clearTimeout(s),s=setTimeout(async()=>{try{o(a.colors.yellow("🔄 Restarting dev server due to config change...")),await t()}catch(e){o(a.colors.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{o(a.colors.red(`❌ Config watcher error: ${e}`))}),{watcher:r,restartCallback:t,logger:o}}function R(e){e.watcher&&e.watcher.close()}function M(e){if(!e||"object"!=typeof e||!("message"in e))return!1;const t=String(e.message);return/Turbopack is not supported/i.test(t)||/native bindings are not available/i.test(t)||/Only WebAssembly \(WASM\) bindings were loaded/i.test(t)}let q=global.__pp_dev_profile_session,H=0;const O=e=>{if(q)return new Promise((t,o)=>{q.post("Profiler.stop",(n,{profile:i})=>{if(n)o(n);else{const o=y.resolve(`./pp-dev-profile-${H++}.cpuprofile`);P.writeFileSync(o,JSON.stringify(i)),e(a.colors.yellow(`CPU profile written to ${a.colors.white(a.colors.dim(o))}`)),q=void 0,t()}})})},z=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function W(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}_.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"),_.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);let o=null,i=null,r=!1;const c=e?y.resolve(process.cwd(),e):process.cwd(),d=a.createLogger(t.logLevel),p=async()=>{if(!r){r=!0;try{o&&(d.info(a.colors.yellow("🛑 Stopping existing dev server...")),await o.close(),o=null);const{clearConfigCache:f,getConfig:u}=await Promise.resolve().then(()=>require("./index-DeUfAH6g.js")).then(e=>e.config);f();const{createServer:g}=await import("vite"),h=await s.loadConfigFromFile({mode:t.mode||"development",command:"serve"},t.config,e,t.logLevel);let m=await l.getViteConfig();const b=s.loadEnv(t.mode||"development",e??process.cwd(),"");if(b&&Object.keys(b).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=b[e])}),h){const{plugins:e,...t}=h.config;m=s.mergeConfig(m,t)}if(o=await g(s.mergeConfig(m,{root:e,base:t.base,mode:t.mode,configFile:t.config,logLevel:t.logLevel,clearScreen:t.clearScreen,optimizeDeps:{force:t.force},server:W(t),customLogger:d},!0)),!o.config.base||"/"===o.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!o.httpServer)throw new Error("HTTP server not available");await o.listen();const w=global.__pp_dev_start_time??!1,v=w?a.colors.dim(`ready in ${a.colors.reset(a.colors.bold(Math.ceil(n.performance.now()-w)))} ms`):"";d.info(`\n ${a.colors.green(`${a.colors.bold("PP-DEV")} v${a.VERSION}`)} ${v}\n`),o.printUrls();const y=await u();if(!1!==y.inspector?.enabled){const e=o.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${o.config.server.port??5173}`;d.info(`\n ${a.colors.cyan("🔍 Request Inspector")} ${a.colors.dim(t+a.INSPECTOR_PATH)}\n`)}!function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=a.createLogger();t.print&&o.info(a.colors.dim(a.colors.green(" ➜"))+a.colors.dim(" press ")+a.colors.bold("h")+a.colors.dim(" to show help"));const n=(t.customShortcuts??[]).filter(E).concat(F);j?.(),j=null;let i=!1;const r=process.stdin.isPaused(),s=process.stdin,l=Boolean(s.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(["",a.colors.bold(" Shortcuts"),...n.map(e=>a.colors.dim(" press ")+a.colors.bold(e.key)+a.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=()=>{j===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),r&&process.stdin.pause(),j=null)};j=p,d.on("close",p)}(o,{print:!0,customShortcuts:[...q?[{key:"p",description:"start/stop the profiler",async action(e){if(q)await O(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{q=new e.Session,q.connect(),q.post("Profiler.enable",()=>{q?.post("Profiler.start",()=>{d.info("Profiler started"),t()})})})}}}]:[],{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),i||(i=N(c,p,d.info),d.info(a.colors.blue("🔧 Config file watcher started"))),r=!1}catch(e){r=!1,d.error(a.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),O(d.info),process.exit(1)}}},f=async e=>{d.info(a.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{i&&(R(i),i=null),o&&(await o.close(),o=null),O(d.info),d.info(a.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(a.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(a.colors.red(`❌ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(a.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),f("unhandledRejection")}),await p()}),_.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(e,t)=>{z(t);let n=null,i=null,r=null,d=null,p=!1;const f=a.createLogger(),u=async()=>{if(!p){p=!0;try{const{next:h,constants:m}=await l.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:b}=m;r&&(await r.close(),r=null),i&&(f.info(a.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:w}=await Promise.resolve().then(()=>require("./index-DeUfAH6g.js")).then(e=>e.config);w();const{join:v,basename:x}=await import("path"),{createServer:S}=await import("http"),T=await import("next/dist/server/config.js"),L=T.default.default||T["module.exports"].default||T.default,k=W(t),$=s.loadEnv(t.mode||"development",e??process.cwd(),"");$&&Object.keys($).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=$[e])});const E=e?v(process.cwd(),e):process.cwd();f.info(E);const j=await L(b,E);let F=j?.ppDev||{};if(0===Object.keys(F).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-DeUfAH6g.js")).then(e=>e.config),t=await e();Object.keys(t).length>0?(F=t,f.info(a.colors.blue("🔧 Loaded pp-dev config from standalone config file"))):f.info(a.colors.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){f.info(a.colors.yellow("⚠️ Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else f.info(a.colors.blue("🔧 Loaded pp-dev config from Next.js config"));let C=null;try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-DeUfAH6g.js")).then(e=>e.config);C=e().name}catch{C=x(E)}a.validatePPDevConfig(F,C??"");const A=a.normalizePPDevConfig(F,C??""),D=A.backendBaseURL??"http://localhost:8080",_=A.templateLess,q=A.v7Features,H=A.disableSSLValidation,O=A.enableProxyCache,z=A.proxyCacheTTL,U=A.personalAccessToken,G=A.miHudLess,V=A.inspectorEnabled,B=A.inspectorMaxMemory,Z=A.inspectorCaptureLimit,J=A.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,X=j?.basePath;let K="";X?K=X:(K=_?a.PATH_PAGE_PREFIX:q?a.PATH_TEMPLATE_LOCAL_PREFIX:a.PATH_TEMPLATE_PREFIX,K+=`/${C}`);const Y=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),Q=async e=>{delete process.env.TURBOPACK,n&&"function"==typeof n.close&&(await n.close(),n=null);const t={dev:!0,customServer:!0,hostname:k.host||"localhost",port:k.port,dir:E,conf:{...j,basePath:K,assetPrefix:K}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),n=h(t),await n.prepare()};if(Y.webpack)await Q({webpack:!0});else if(Y.turbopack)try{await Q({turbopack:!0})}catch(e){if(!M(e))throw e;f.warn(a.colors.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await Q({webpack:!0})}else try{await Q({})}catch(e){if(!M(e))throw e;f.warn(a.colors.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await Q({webpack:!0})}if(!n)throw new Error("Next.js app failed to initialize");if(K.endsWith("/")||(K+="/"),"/"===K)throw new Error('basePath cannot be equal to "/" or equal to empty string');f.info(a.colors.green("✅ Next.js app prepared successfully")),f.info(a.colors.blue(`🔧 pp-dev plugin configured for template: ${C}`)),f.info(a.colors.blue(`🔧 Base path configured: ${K}`)),D&&(f.info(a.colors.blue(`🌐 Backend URL: ${D}`)),f.info(a.colors.blue(`🆔 Custom App ID: ${J}`)));const ee=n.getRequestHandler(),te="number"==typeof k.port?k.port:3e3,oe="string"==typeof k.host?k.host||"0.0.0.0":"localhost",ne=new Set;i=S(async(e,t)=>{try{const o=e.url||"/",n=o.split("?")[0];let i=c.parse(o,!0);if(re.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(se.length>0){let l=0;const d=()=>{if(l>=se.length)return void r();const o=se[l];l++,o(e,t,d)};return void d()}return void r()}let s=0;const a=()=>{if(s>=re.length)return void r();const o=re[s];s++,o(e,t,a)};return void a()}async function r(){if(n.startsWith(K))i=c.parse(o,!0);else{if(n===K.replace(/\/$/,"")){const e=o.replace(n,K);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:K}),void t.end()}await ee(e,t,i)}r()}catch(p){f.error(`Error handling request: ${p instanceof Error?p.message:String(p)}`,{error:p instanceof Error?p:void 0}),t.statusCode=500,t.end("Internal Server Error")}});let ie=null,re=[],se=[];if(!1!==V){const e=new a.RequestStore(B);a.registerInspectorRoutes(a.internalServer,e,Z);const t=a.createRequestCaptureMiddleware(e,Z);re.push(t)}if(D){const e=new URL(D).host;D.startsWith("https://")&&(o.EventEmitter.defaultMaxListeners=Math.max(o.EventEmitter.defaultMaxListeners,20));const t={headers:{host:e,referer:D,origin:D.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:J,templateLess:_,disableSSLValidation:H,v7Features:q,personalAccessToken:U??process.env.MI_ACCESS_TOKEN};ie=new a.MiAPI(D,t);const s=a.initPPRedirect(K,C??void 0),c=(e,t,o)=>{s(e,t,o)};se.push(c),re.push(c);const d=l.createDevPanelAssetMiddleware(K);if(se.push(d),re.push(d),O){let e=+z;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},o=a.initProxyCache(t),n=(e,t,n)=>{o(e,t,n)};re.push(n),f.info(a.colors.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const p=new RegExp(`^((${g=K,g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),u=a.initLoadPPData(p,ie,Object.assign({base:K},t,{miHudLess:G})),h=(e,t,o)=>{u(e,t,o)};re.push(h);const b=K.endsWith("/")?K.substring(0,K.length-1):K,w={middlewares:{use:e=>e},config:{logger:console}},v=a.initProxy({devServer:w,baseURL:D,proxyIgnore:["/@vite","/@metricinsights","/@",b,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:H,miAPI:ie,templateName:C??void 0}),S=(e,t,o)=>{v(e,t,o)};re.push(S);const T=a.internalServer,k=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(a.INSPECTOR_PATH)){return void T(e,t,()=>{})}o()};se.push(k),re.push(k);const $=a.initRewriteResponse(e=>{const t=e.split("?")[0];return t.startsWith(K)&&!t.includes("/_next/")},(t,o)=>{const n=ie.buildPage(t,G),i=l.injectDevPanel(n,K,{backendBaseURL:D,templateLess:_,appId:J,devPanelPosition:A.devPanelPosition,devPanelHidden:A.devPanelHidden,devPanelAutoHide:A.devPanelAutoHide});return Buffer.from(a.urlReplacer(e,o.headers.host??"",i))}),F=(e,t,o)=>{$(e,t,o)};re.push(F),r=new I;let N=j?.distDir;try{const e=await L(m.PHASE_PRODUCTION_BUILD,E);N=e?.distDir??N}catch{}const R=(N??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),M=R&&".next"!==R?R:"out";let W,V="0.0.0";try{const e=JSON.parse(P.readFileSync(y.join(E,"package.json"),"utf-8"));V="string"==typeof e.version?e.version:V,W="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const B=!1!==A.distZip?new a.DistService(C??x(E),{nextBuild:{projectRoot:E,distDir:M,packageVersion:V,packageRepositoryUrl:W}}):void 0,Z={ws:r.ws,config:{clientInjectionPlugin:{v7Features:q}}};new a.ClientService(Z,{distService:B,miAPI:ie});const X="function"==typeof n?.getUpgradeHandler?n.getUpgradeHandler():null;i.on("upgrade",(e,t,o)=>{r?.handleUpgrade(e,t,o)||(X?X(e,t,o):t.destroy())}),f.info(a.colors.blue(`🔧 ${re.length} pp-dev middlewares initialized`)),f.info(a.colors.blue(`🔧 ${se.length} essential middlewares for internal routes`)),f.info(a.colors.blue(`🔧 MiAPI initialized for backend: ${D}`)),f.info(a.colors.blue(`🔧 Custom App ID: ${J}`))}i.listen(te,oe,()=>{f.info(a.colors.green(`✅ pp-dev Next.js server running at http://${oe}:${te}`)),f.info(a.colors.blue(`📱 Next.js app accessible at http://${oe}:${te}${K}`)),!1!==V&&f.info(a.colors.cyan(`🔍 Request Inspector: http://${oe}:${te}${a.INSPECTOR_PATH}`)),f.info(a.colors.blue("🔧 Base path handling active")),d||(d=N(E,u,f.info),f.info(a.colors.blue("🔧 Config file watcher started"))),i.on("connection",e=>{ne.add(e),e.on("close",()=>ne.delete(e))});const e=async e=>{f.info(a.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));const t=setTimeout(()=>{f.info(a.colors.yellow("⏰ Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{d&&(R(d),d=null);for(const e of Array.from(ne))e.destroy();ne.clear(),r&&(await r.close(),r=null),await new Promise(e=>{i.close(()=>{f.info(a.colors.yellow("🛑 HTTP server closed")),e()})}),n&&"function"==typeof n.close&&(await n.close(),f.info(a.colors.yellow("🛑 Next.js app closed"))),clearTimeout(t),f.info(a.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(t),f.error(a.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,f.info(a.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=>{f.error(a.colors.red(`❌ Uncaught Exception: ${t}`)),e("uncaughtException")}),t.on("unhandledRejection",(t,o)=>{f.error(a.colors.red(`❌ Unhandled Rejection at: ${o}, reason: ${t}`)),e("unhandledRejection")}),f.info(a.colors.green("✅ Process event handlers registered successfully"))}catch(e){f.warn(a.colors.yellow(`⚠️ Failed to register process event handlers: ${e}`))}else f.warn(a.colors.yellow("⚠️ process.on is not available, graceful shutdown handlers will not be registered")),f.info(a.colors.blue("💡 This might be due to bundling or environment constraints"))}),p=!1}catch(e){p=!1,f.error(a.colors.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(f.error(a.colors.red("❌ Next.js Peer Dependency Error:")),f.error(a.colors.red(e.message)),f.error(a.colors.yellow("\n💡 To fix this issue:")),f.error(a.colors.blue(" 1. Install Next.js in your project:")),f.error(a.colors.white(" npm install next@^16")),f.error(a.colors.blue(" 2. Or use yarn:")),f.error(a.colors.white(" yarn add next@^16")),f.error(a.colors.blue(" 3. Or use pnpm:")),f.error(a.colors.white(" pnpm add next@^16")),f.error(a.colors.yellow("\n📖 For more information, see:")),f.error(a.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var g}},g=async e=>{f.info(a.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{d&&(R(d),d=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),f.info(a.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){f.error(a.colors.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM")),process.on("uncaughtException",e=>{f.error(a.colors.red(`❌ Uncaught Exception: ${e}`)),g("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{f.error(a.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),g("unhandledRejection")}),await u()}),_.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").action(async(e,t)=>{z(t);const o=W(t);try{const n=await s.loadConfigFromFile({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let i=await l.getViteConfig();if(n){const{plugins:e,...t}=n.config;i=s.mergeConfig(i,t)}const r=s.mergeConfig(i,{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 s.build(r),o.changelog){const n=e||process.cwd(),i=r.build?.outDir||"dist";let s="";if("string"==typeof o.changelog)s=y.resolve(n,o.changelog);else{const e=y.resolve(n,r.ppDevConfig?.syncBackupsDir||"backups");if(!P.existsSync(e))return void a.createLogger(t.logLevel).warn(a.colors.yellow("backups directory not found, skipping changelog generation"));const o=P.readdirSync(e,{withFileTypes:!0});if(!o.length)return void a.createLogger(t.logLevel).warn(a.colors.yellow("no backups found, skipping changelog generation"));const i=o.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!i.length)return void a.createLogger(t.logLevel).warn(a.colors.yellow("no ZIP backups found, skipping changelog generation"));const l=i.reduce((t,o)=>P.statSync(y.resolve(e,t.name)).mtimeMs>P.statSync(y.resolve(e,o.name)).mtimeMs?t:o).name;s=y.resolve(e,l)}const l=y.resolve(n,i);let c="dist-zip";r.ppDevConfig&&(!1===r.ppDevConfig.distZip?c=r.build?.outDir||"dist":"object"==typeof r.ppDevConfig.distZip&&"string"==typeof r.ppDevConfig.distZip.outDir&&(c=r.ppDevConfig.distZip.outDir));const d=new A({oldAssetsPath:s,newAssetsPath:l,destinationPath:y.resolve(n,c)});await d.generateChangelog()}}catch(e){a.createLogger(t.logLevel).error(a.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{O(e=>a.createLogger(t.logLevel).info(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,t,o)=>{z(o);const{oldAssetsPath:n=e,newAssetsPath:i=t,destination:r=".",filename:s="CHANGELOG.html",logLevel:l}=o,c=process.cwd();n&&i||(a.createLogger(l).error(a.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=y.resolve(c,n),p=y.resolve(c,i),f=y.resolve(c,r),u=new A({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:s});await u.generateChangelog()}),_.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(e,t,o)=>{z(o);const{source:n=e,destination:i=t,fontName:r="icon-font"}=o,s=process.cwd(),l=y.resolve(s,n),c=y.resolve(s,i),d=new D({sourceDir:l,outputDir:c,fontName:r}),p=a.createLogger(o.logLevel);p.info(`Generating icon font from SVG files in ${a.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${a.colors.dim(c)}`)}),_.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);try{const o=await s.loadConfigFromFile({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await l.getViteConfig();if(o){const{plugins:e,...t}=o.config;n=s.mergeConfig(n,t)}const i=await s.resolveConfig(s.mergeConfig(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode}),"serve");await s.optimizeDeps(i,t.force,!0)}catch(e){a.createLogger(t.logLevel).error(a.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),_.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,t)=>{z(t);try{const o=await s.loadConfigFromFile({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await l.getViteConfig();if(o){const{plugins:e,...t}=o.config;n=s.mergeConfig(n,t)}(await s.preview(s.mergeConfig(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode,build:{outDir:t.outDir},preview:{port:t.port,strictPort:t.strictPort,host:t.host,https:t.https,open:t.open}}))).printUrls()}catch(e){a.createLogger(t.logLevel).error(a.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{O(e=>a.createLogger(t.logLevel).info(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,t)=>{const o=a.createLogger(t.logLevel),{isLegacyFlatConfig:n,isLegacyPPWatchConfig:i,isAlreadyMigrated:r,migrateLegacyFlatConfig:s,migratePPWatchConfig:l,generateConfigFileContent:c}=await Promise.resolve().then(()=>require("./migrate-r2mXdGLZ.js")),d=t.format??"ts",p=!1!==t.backup,f=process.cwd(),u=[".pp-watch.config.ts",".pp-watch.config.js",".pp-watch.config.json","pp-watch.config.ts","pp-watch.config.js","pp-watch.config.json"];let g=e??null,h=!1;if(!g){for(const e of a.PP_DEV_CONFIG_NAMES)if(P.existsSync(y.join(f,e))){g=y.join(f,e);break}if(!g)for(const e of u)if(P.existsSync(y.join(f,e))){g=y.join(f,e),h=!0;break}}g||(o.warn(a.colors.yellow("No pp-dev or pp-watch config file found in the current directory.")),o.info(a.colors.blue("Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}")),process.exit(1)),o.info(a.colors.blue(`Found config: ${y.relative(f,g)}`));const{getPkg:m}=await Promise.resolve().then(()=>require("./index-DeUfAH6g.js")).then(e=>e.config),b=m();let w,v={};try{if(/\.[cm]?ts$/i.test(g)){const e=await import("esbuild"),{pathToFileURL:t}=await import("url"),o=(await e.build({absWorkingDir:f,entryPoints:[g],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,n=`pp-migrate-tmp-${Date.now()}.mjs`;P.writeFileSync(n,o);try{const e=await import(t(y.resolve(f,n)).toString());v=e.default?.default??e.default??e}finally{P.existsSync(n)&&P.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(g)){const{pathToFileURL:e}=await import("url"),t=await import(e(y.resolve(f,g)).toString());v=t.default?.default??t.default??t}else g.endsWith(".json")&&(v=JSON.parse(P.readFileSync(g,"utf-8")))}catch(e){o.error(a.colors.red(`Failed to load config file: ${e.message}`)),process.exit(1)}v&&"object"==typeof v||(o.error(a.colors.red("Config file did not export a valid object.")),process.exit(1)),r(v)?(o.info(a.colors.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):h||i(v)?(o.info(a.colors.blue("Detected pp-watch config format → migrating to 1.0")),w=l(v)):n(v)?(o.info(a.colors.blue("Detected 0.x flat config format → migrating to 1.0")),w=s(v,b.name)):(o.warn(a.colors.yellow("Could not detect config format. No known keys found.")),process.exit(1));const x=c(w,d),S=t.output??y.join(f,`pp-dev.config.${d}`);if(t.dryRun&&(o.info(a.colors.green(`\n--- Migrated config (dry-run) → ${y.relative(f,S)} ---\n`)),process.exit(0)),p&&P.existsSync(g)){const e=`${g}.bak`;P.copyFileSync(g,e),o.info(a.colors.blue(`Backed up original to: ${y.relative(f,e)}`))}P.writeFileSync(S,x,"utf-8"),o.info(a.colors.green(`✅ Migration complete → ${y.relative(f,S)}`)),g!==S&&P.existsSync(g)&&o.info(a.colors.yellow(`You can now delete the old config: ${y.relative(f,g)}`))}),_.help(),_.version(a.VERSION),_.parse(),exports.stopProfiler=O;
|
|
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("vite"),a=require("./plugin-cgWPoZgR.js"),l=require("./index-ctxv-2Kt.js"),c=require("url"),d=require("dir-compare"),p=require("diff-match-patch"),f=require("isbinaryfile"),u=require("os"),g=require("crypto"),h=require("extract-zip"),m=require("svgtofont"),b=require("ws");require("http-proxy-middleware"),require("picocolors"),require("axios"),require("node:http"),require("node:https"),require("jsdom"),require("process"),require("child_process"),require("jszip"),require("module"),require("memory-cache"),require("zlib"),require("express"),require("node:crypto"),require("./helpers.js"),require("ejs");const w=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function v(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=v(e),P=v(t),x=v(d),S=w(p),E=v(u),T=v(g),L=w(h),k=w(m);function D(e){return null!=e&&!1!==e}let I=null;const F=[{key:"r",description:"restart the server",async action(e){await e.restart()}},{key:"u",description:"show server url",action(e){e.config.logger.info(""),e.printUrls()}},{key:"o",description:"open in browser",action(e){e.openBrowser()}},{key:"c",description:"clear console",action(e){e.config.logger.clearScreen("error")}},{key:"q",description:"quit",async action(e){await e.close().finally(()=>process.exit())}},{key:"C",description:"clear proxy cache",action(e){e.cache&&(e.cache.clear(),e.config.logger.info("Proxy cache cleared"))}}];const _=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class ${oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(e){const{oldAssetsPath:t,newAssetsPath:o,destinationPath:n,changelogTemplate:i,diffFileTemplateHandler:r,diffLineTemplateHandler:s,changelogFilename:l,contextLines:c}=e;if(this.logger=a.createLogger(),!t||!o||!n)throw new Error("Previous assets path, current assets path and destination path are required");if(t===o)throw new Error("Previous and current assets paths must be different");if(!this.isExists(t))throw new Error(`Previous assets path ${t} does not exist`);if(!this.isExists(o))throw new Error(`Current assets path ${o} does not exist`);if(this.isZipFile(t)){const e=y.resolve(E.tmpdir(),T.createHash("md5").update(t).digest("hex"));this.oldAssetsPath=this.unzipFile(t,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(t))throw new Error(`Invalid previous assets path ${t}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(t);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(o)){const e=y.resolve(E.tmpdir(),T.createHash("md5").update(o).digest("hex"));this.newAssetsPath=this.unzipFile(o,e).then(()=>this.normalizeAssetFolderPath(e)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(o))throw new Error(`Invalid current assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${o} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=n,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",i&&(this.templateIsValid(i)?this.changelogTemplate=i:this.logger.warn(a.colors.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof s&&(this.diffLineTemplateHandler=s),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){return P.rmSync(t,{force:!0,recursive:!0}),L(e,{dir: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(a.colors.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await x.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(_.test(e)&&(e=e.replace(_,"$1$3")),_.test(t)&&(t=t.replace(_,"$1$3")),0===e.localeCompare(t)?0:e.localeCompare(t)>0?1:-1)});return e.diffSet?.filter(e=>"equal"!==e.state||e.name1!==e.name2)||[]}async generateAssetFilesDiff(e,t){const o=new S,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let r=0;return i.map(e=>{const[t,o]=e,n=o.endsWith("\n")?o.split("\n").length-1:o.split("\n").length,i=o.split("\n").map((e,o)=>({lineContent:e,lineNumber:r+o+1,lineType:t})).slice(0,n);return-1!==t&&(r+=n),i}).flat()}async generateFilesDiff(e){if("equal"===e.state){const t=this.pathToPosix(y.join(".",e.relativePath,e.name1??"")),o=this.pathToPosix(y.join(".",e.relativePath,e.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${o}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const t=e.path1&&e.name1?y.join(e.path1,e.name1):null,o=e.path2&&e.name2?y.join(e.path2,e.name2):null,n=this.pathToPosix(y.join(".",e.relativePath,(e.name1||e.name2)??""));if("left"===e.state&&t)return this.diffFileTemplate(`<span class="removed">Removed ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===e.state&&o)return this.diffFileTemplate(`<span class="added">Added ${n}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===e.state&&t&&o){const i=this.pathToPosix(y.join(".",e.relativePath,e.name1??"")),r=this.pathToPosix(y.join(".",e.relativePath,e.name2??"")),s=e.name1!==e.name2?`<span class="renamed"\n >Renamed <span class="from">${i}</span> -> <span class="to">${r}</span></span\n >`:n;return this.diffFileTemplate(s,await f.isBinaryFile(t)||await f.isBinaryFile(o)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(P.readFileSync(t,"utf-8"),P.readFileSync(o,"utf-8"))))}return""}async generateChangelog(){this.logger.info(a.colors.green("Generating changelog"));const e=await this.generateAssetFoldersDiff(),t=(await Promise.all(e.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(a.colors.green("Writing changelog file"));const o=this.changelogTemplate.split("%FILES%");o.splice(1,0,t);const n=o.join("");P.writeFileSync(y.join(this.destinationPath,this.changelogFilename),n),this.logger.info(a.colors.green(`Changelog file written to ${y.join(this.destinationPath,this.changelogFilename)}`))}}class j{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await k({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class C{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new b.WebSocketServer({noServer:!0}),this.wss.on("connection",e=>this.onConnection(e)),this.wss.on("error",e=>this.fireLifecycle("error",e)),this.ws={on:(e,t)=>{"close"!==e&&"error"!==e?this.getEventSet(e).add(t):this.getLifecycleSet(e).add(t)},off:(e,t)=>{this.eventListeners.get(e)?.delete(t),"close"!==e&&"error"!==e||this.lifecycleListeners.get(e)?.delete(t)},send:(e,t)=>{if("string"==typeof e)for(const o of this.clients.keys())this.sendToSocket(o,e,t);else{const t=JSON.stringify(e);for(const e of this.clients.keys())e.readyState===b.WebSocket.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===a.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){a.createLogger().error(`ws handler for "${o.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===b.WebSocket.OPEN&&e.send(JSON.stringify({type:"custom",event:t,data:o}))}fireLifecycle(e,t){for(const o of this.lifecycleListeners.get(e)??[])try{o(t)}catch{}}getEventSet(e){let t=this.eventListeners.get(e);return t||(t=new Set,this.eventListeners.set(e,t)),t}getLifecycleSet(e){let t=this.lifecycleListeners.get(e);return t||(t=new Set,this.lifecycleListeners.set(e,t)),t}}const N=r.cac("pp-dev");function A(e,t,o){const n=[...a.PP_DEV_CONFIG_NAMES,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"].map(t=>y.join(e,t)),r=i.watch(n,{ignored:e=>{const t=y.basename(e);return/(^|[\/\\])\../.test(e)&&!t.startsWith(".env")&&!t.startsWith(".pp-dev")&&!t.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let s=null;return r.on("change",n=>{o(a.colors.blue(`🔧 Config file changed: ${y.relative(e,n)}`)),s&&clearTimeout(s),s=setTimeout(async()=>{try{o(a.colors.yellow("🔄 Restarting dev server due to config change...")),await t()}catch(e){o(a.colors.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{o(a.colors.red(`❌ Config watcher error: ${e}`))}),{watcher:r,restartCallback:t,logger:o}}function R(e){e.watcher&&e.watcher.close()}function M(e){if(!e||"object"!=typeof e||!("message"in e))return!1;const t=String(e.message);return/Turbopack is not supported/i.test(t)||/native bindings are not available/i.test(t)||/Only WebAssembly \(WASM\) bindings were loaded/i.test(t)}async function O(e){const{changelog:t,executionRoot:o,newAssetsPath:n,backupsDirPath:i,changelogDestinationPath:r,logLevel:s}=e;let l;if("string"==typeof t)l=y.resolve(o,t);else{if(!P.existsSync(i))return void a.createLogger(s).warn(a.colors.yellow("backups directory not found, skipping changelog generation"));const e=P.readdirSync(i,{withFileTypes:!0});if(!e.length)return void a.createLogger(s).warn(a.colors.yellow("no backups found, skipping changelog generation"));const t=e.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!t.length)return void a.createLogger(s).warn(a.colors.yellow("no ZIP backups found, skipping changelog generation"));const o=t.reduce((e,t)=>P.statSync(y.resolve(i,e.name)).mtimeMs>P.statSync(y.resolve(i,t.name)).mtimeMs?e:t).name;l=y.resolve(i,o)}const c=new $({oldAssetsPath:l,newAssetsPath:n,destinationPath:r});await c.generateChangelog()}let q=global.__pp_dev_profile_session,V=0;const H=e=>{if(q)return new Promise((t,o)=>{q.post("Profiler.stop",(n,{profile:i})=>{if(n)o(n);else{const o=y.resolve(`./pp-dev-profile-${V++}.cpuprofile`);P.writeFileSync(o,JSON.stringify(i)),e(a.colors.yellow(`CPU profile written to ${a.colors.white(a.colors.dim(o))}`)),q=void 0,t()}})})},z=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function U(e){const t={...e};return delete t["--"],delete t.c,delete t.config,delete t.base,delete t.l,delete t.logLevel,delete t.clearScreen,delete t.d,delete t.debug,delete t.f,delete t.filter,delete t.m,delete t.mode,t}N.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"),N.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);let o=null,i=null,r=!1;const c=e?y.resolve(process.cwd(),e):process.cwd(),d=a.createLogger(t.logLevel),p=async()=>{if(!r){r=!0;try{o&&(d.info(a.colors.yellow("🛑 Stopping existing dev server...")),await o.close(),o=null);const{clearConfigCache:f,getConfig:u}=await Promise.resolve().then(()=>require("./index-ctxv-2Kt.js")).then(e=>e.config);f();const{createServer:g}=await import("vite"),h=await s.loadConfigFromFile({mode:t.mode||"development",command:"serve"},t.config,e,t.logLevel);let m=await l.getViteConfig();const b=s.loadEnv(t.mode||"development",e??process.cwd(),"");if(b&&Object.keys(b).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=b[e])}),h){const{plugins:e,...t}=h.config;m=s.mergeConfig(m,t)}if(o=await g(s.mergeConfig(m,{root:e,base:t.base,mode:t.mode,configFile:t.config,logLevel:t.logLevel,clearScreen:t.clearScreen,optimizeDeps:{force:t.force},server:U(t),customLogger:d},!0)),!o.config.base||"/"===o.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!o.httpServer)throw new Error("HTTP server not available");await o.listen();const w=global.__pp_dev_start_time??!1,v=w?a.colors.dim(`ready in ${a.colors.reset(a.colors.bold(Math.ceil(n.performance.now()-w)))} ms`):"";d.info(`\n ${a.colors.green(`${a.colors.bold("PP-DEV")} v${a.VERSION}`)} ${v}\n`),o.printUrls();const y=await u();if(!1!==y.inspector?.enabled){const e=o.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${o.config.server.port??5173}`;d.info(`\n ${a.colors.cyan("🔍 Request Inspector")} ${a.colors.dim(t+a.INSPECTOR_PATH)}\n`)}!function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=a.createLogger();t.print&&o.info(a.colors.dim(a.colors.green(" ➜"))+a.colors.dim(" press ")+a.colors.bold("h")+a.colors.dim(" to show help"));const n=(t.customShortcuts??[]).filter(D).concat(F);I?.(),I=null;let i=!1;const r=process.stdin.isPaused(),s=process.stdin,l=Boolean(s.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(["",a.colors.bold(" Shortcuts"),...n.map(e=>a.colors.dim(" press ")+a.colors.bold(e.key)+a.colors.dim(` to ${e.description}`))].join("\n"));const r=n.find(e=>e.key===t);r&&(i=!0,await r.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",c).setEncoding("utf8").resume();const d=e.httpServer,p=()=>{I===p&&(d.removeListener("close",p),process.stdin.off("data",c),l||process.stdin.setRawMode(!1),r&&process.stdin.pause(),I=null)};I=p,d.on("close",p)}(o,{print:!0,customShortcuts:[...q?[{key:"p",description:"start/stop the profiler",async action(e){if(q)await H(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{q=new e.Session,q.connect(),q.post("Profiler.enable",()=>{q?.post("Profiler.start",()=>{d.info("Profiler started"),t()})})})}}}]:[],{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),i||(i=A(c,p,d.info),d.info(a.colors.blue("🔧 Config file watcher started"))),r=!1}catch(e){r=!1,d.error(a.colors.red(`error when starting dev server:\n${e.stack}`),{error:e}),H(d.info),process.exit(1)}}},f=async e=>{d.info(a.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{i&&(R(i),i=null),o&&(await o.close(),o=null),H(d.info),d.info(a.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(a.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(a.colors.red(`❌ Uncaught Exception: ${e}`)),f("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(a.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),f("unhandledRejection")}),await p()}),N.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(e,t)=>{z(t);let n=null,i=null,r=null,d=null,p=!1;const f=a.createLogger(),u=async()=>{if(!p){p=!0;try{const{next:h,constants:m}=await l.safeNextImport(),{PHASE_DEVELOPMENT_SERVER:b}=m;r&&(await r.close(),r=null),i&&(f.info(a.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:w}=await Promise.resolve().then(()=>require("./index-ctxv-2Kt.js")).then(e=>e.config);w();const{join:v,basename:x}=await import("path"),{createServer:S}=await import("http"),E=await import("next/dist/server/config.js"),T=E.default.default||E["module.exports"].default||E.default,L=U(t),k=s.loadEnv(t.mode||"development",e??process.cwd(),"");k&&Object.keys(k).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=k[e])});const D=e?v(process.cwd(),e):process.cwd();f.info(D);const I=await T(b,D);let F=I?.ppDev||{};if(0===Object.keys(F).length)try{const{getConfig:e}=await Promise.resolve().then(()=>require("./index-ctxv-2Kt.js")).then(e=>e.config),t=await e();Object.keys(t).length>0?(F=t,f.info(a.colors.blue("🔧 Loaded pp-dev config from standalone config file"))):f.info(a.colors.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){f.info(a.colors.yellow("⚠️ Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else f.info(a.colors.blue("🔧 Loaded pp-dev config from Next.js config"));let _=null;try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-ctxv-2Kt.js")).then(e=>e.config);_=e().name}catch{_=x(D)}a.validatePPDevConfig(F,_??"");const $=a.normalizePPDevConfig(F,_??""),j=$.backendBaseURL??"http://localhost:8080",N=$.templateLess,O=$.v7Features,q=$.disableSSLValidation,V=$.enableProxyCache,H=$.proxyCacheTTL,z=$.personalAccessToken,W=$.miHudLess,B=$.inspectorEnabled,G=$.inspectorMaxMemory,Z=$.inspectorCaptureLimit,X=$.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,J=I?.basePath;let K="";J?K=J:(K=N?a.PATH_PAGE_PREFIX:O?a.PATH_TEMPLATE_LOCAL_PREFIX:a.PATH_TEMPLATE_PREFIX,K+=`/${_}`);const Y=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),Q=async e=>{delete process.env.TURBOPACK,n&&"function"==typeof n.close&&(await n.close(),n=null);const t={dev:!0,customServer:!0,hostname:L.host||"localhost",port:L.port,dir:D,conf:{...I,basePath:K,assetPrefix:K}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),n=h(t),await n.prepare()};if(Y.webpack)await Q({webpack:!0});else if(Y.turbopack)try{await Q({turbopack:!0})}catch(e){if(!M(e))throw e;f.warn(a.colors.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await Q({webpack:!0})}else try{await Q({})}catch(e){if(!M(e))throw e;f.warn(a.colors.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await Q({webpack:!0})}if(!n)throw new Error("Next.js app failed to initialize");if(K.endsWith("/")||(K+="/"),"/"===K)throw new Error('basePath cannot be equal to "/" or equal to empty string');f.info(a.colors.green("✅ Next.js app prepared successfully")),f.info(a.colors.blue(`🔧 pp-dev plugin configured for template: ${_}`)),f.info(a.colors.blue(`🔧 Base path configured: ${K}`)),j&&(f.info(a.colors.blue(`🌐 Backend URL: ${j}`)),f.info(a.colors.blue(`🆔 Custom App ID: ${X}`)));const ee=n.getRequestHandler(),te="number"==typeof L.port?L.port:3e3,oe="string"==typeof L.host?L.host||"0.0.0.0":"localhost",ne=new Set;i=S(async(e,t)=>{try{const o=e.url||"/",n=o.split("?")[0];let i=c.parse(o,!0);if(re.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(se.length>0){let l=0;const d=()=>{if(l>=se.length)return void r();const o=se[l];l++,o(e,t,d)};return void d()}return void r()}let s=0;const a=()=>{if(s>=re.length)return void r();const o=re[s];s++,o(e,t,a)};return void a()}async function r(){if(n.startsWith(K))i=c.parse(o,!0);else{if(n===K.replace(/\/$/,"")){const e=o.replace(n,K);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:K}),void t.end()}await ee(e,t,i)}r()}catch(p){f.error(`Error handling request: ${p instanceof Error?p.message:String(p)}`,{error:p instanceof Error?p:void 0}),t.statusCode=500,t.end("Internal Server Error")}});let ie=null,re=[],se=[];if(!1!==B){const e=new a.RequestStore(G);a.registerInspectorRoutes(a.internalServer,e,Z);const t=a.createRequestCaptureMiddleware(e,Z);re.push(t)}if(j){const e=new URL(j).host;j.startsWith("https://")&&(o.EventEmitter.defaultMaxListeners=Math.max(o.EventEmitter.defaultMaxListeners,20));const t={headers:{host:e,referer:j,origin:j.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:X,templateLess:N,disableSSLValidation:q,v7Features:O,personalAccessToken:z??process.env.MI_ACCESS_TOKEN};ie=new a.MiAPI(j,t);const s=a.initPPRedirect(K,_??void 0),c=(e,t,o)=>{s(e,t,o)};se.push(c),re.push(c);const d=l.createDevPanelAssetMiddleware(K);if(se.push(d),re.push(d),V){let e=+H;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={devServer:{middlewares:{use:e=>e},config:{logger:console}},ttl:e},o=a.initProxyCache(t),n=(e,t,n)=>{o(e,t,n)};re.push(n),f.info(a.colors.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const p=new RegExp(`^((${g=K,g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),u=a.initLoadPPData(p,ie,Object.assign({base:K},t,{miHudLess:W})),h=(e,t,o)=>{u(e,t,o)};re.push(h);const b=K.endsWith("/")?K.substring(0,K.length-1):K,w={middlewares:{use:e=>e},config:{logger:console}},v=a.initProxy({devServer:w,baseURL:j,proxyIgnore:["/@vite","/@metricinsights","/@",b,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:q,miAPI:ie,templateName:_??void 0}),S=(e,t,o)=>{v(e,t,o)};re.push(S);const E=a.internalServer,L=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(a.INSPECTOR_PATH)){return void E(e,t,()=>{})}o()};se.push(L),re.push(L);const k=a.initRewriteResponse(e=>{const t=e.split("?")[0];return t.startsWith(K)&&!t.includes("/_next/")},(t,o)=>{const n=ie.buildPage(t,W),i=l.injectDevPanel(n,K,{backendBaseURL:j,templateLess:N,appId:X,devPanelPosition:$.devPanelPosition,devPanelHidden:$.devPanelHidden,devPanelAutoHide:$.devPanelAutoHide});return Buffer.from(a.urlReplacer(e,o.headers.host??"",i))}),F=(e,t,o)=>{k(e,t,o)};re.push(F),r=new C;let A=I?.distDir;try{process.env[a.PP_DEV_NEXT_BUILD_ENV_VAR]="1";const e=await T(m.PHASE_PRODUCTION_BUILD,D);A=e?.distDir??A}catch{}const R=(A??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),M=R&&".next"!==R?R:"out";let U,B="0.0.0";try{const e=JSON.parse(P.readFileSync(y.join(D,"package.json"),"utf-8"));B="string"==typeof e.version?e.version:B,U="string"==typeof e.repository?e.repository:e.repository?.url}catch{}const G=!1!==$.distZip?new a.DistService(_??x(D),{nextBuild:{projectRoot:D,distDir:M,packageVersion:B,packageRepositoryUrl:U}}):void 0,Z={ws:r.ws,config:{clientInjectionPlugin:{v7Features:O}}};new a.ClientService(Z,{distService:G,miAPI:ie});const J="function"==typeof n?.getUpgradeHandler?n.getUpgradeHandler():null;i.on("upgrade",(e,t,o)=>{r?.handleUpgrade(e,t,o)||(J?J(e,t,o):t.destroy())}),f.info(a.colors.blue(`🔧 ${re.length} pp-dev middlewares initialized`)),f.info(a.colors.blue(`🔧 ${se.length} essential middlewares for internal routes`)),f.info(a.colors.blue(`🔧 MiAPI initialized for backend: ${j}`)),f.info(a.colors.blue(`🔧 Custom App ID: ${X}`))}i.listen(te,oe,()=>{f.info(a.colors.green(`✅ pp-dev Next.js server running at http://${oe}:${te}`)),f.info(a.colors.blue(`📱 Next.js app accessible at http://${oe}:${te}${K}`)),!1!==B&&f.info(a.colors.cyan(`🔍 Request Inspector: http://${oe}:${te}${a.INSPECTOR_PATH}`)),f.info(a.colors.blue("🔧 Base path handling active")),d||(d=A(D,u,f.info),f.info(a.colors.blue("🔧 Config file watcher started"))),i.on("connection",e=>{ne.add(e),e.on("close",()=>ne.delete(e))});const e=async e=>{f.info(a.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));const t=setTimeout(()=>{f.info(a.colors.yellow("⏰ Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{d&&(R(d),d=null);for(const e of Array.from(ne))e.destroy();ne.clear(),r&&(await r.close(),r=null),await new Promise(e=>{i.close(()=>{f.info(a.colors.yellow("🛑 HTTP server closed")),e()})}),n&&"function"==typeof n.close&&(await n.close(),f.info(a.colors.yellow("🛑 Next.js app closed"))),clearTimeout(t),f.info(a.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(t),f.error(a.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,f.info(a.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=>{f.error(a.colors.red(`❌ Uncaught Exception: ${t}`)),e("uncaughtException")}),t.on("unhandledRejection",(t,o)=>{f.error(a.colors.red(`❌ Unhandled Rejection at: ${o}, reason: ${t}`)),e("unhandledRejection")}),f.info(a.colors.green("✅ Process event handlers registered successfully"))}catch(e){f.warn(a.colors.yellow(`⚠️ Failed to register process event handlers: ${e}`))}else f.warn(a.colors.yellow("⚠️ process.on is not available, graceful shutdown handlers will not be registered")),f.info(a.colors.blue("💡 This might be due to bundling or environment constraints"))}),p=!1}catch(e){p=!1,f.error(a.colors.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(f.error(a.colors.red("❌ Next.js Peer Dependency Error:")),f.error(a.colors.red(e.message)),f.error(a.colors.yellow("\n💡 To fix this issue:")),f.error(a.colors.blue(" 1. Install Next.js in your project:")),f.error(a.colors.white(" npm install next@^16")),f.error(a.colors.blue(" 2. Or use yarn:")),f.error(a.colors.white(" yarn add next@^16")),f.error(a.colors.blue(" 3. Or use pnpm:")),f.error(a.colors.white(" pnpm add next@^16")),f.error(a.colors.yellow("\n📖 For more information, see:")),f.error(a.colors.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var g}},g=async e=>{f.info(a.colors.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{d&&(R(d),d=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),f.info(a.colors.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){f.error(a.colors.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM")),process.on("uncaughtException",e=>{f.error(a.colors.red(`❌ Uncaught Exception: ${e}`)),g("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{f.error(a.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),g("unhandledRejection")}),await u()}),N.command("build [root]","build for production").option("--target <target>","[string] transpile target (default: 'modules')").option("--outDir <dir>","[string] output directory (default: dist)").option("--assetsDir <dir>","[string] directory under outDir to place assets in (default: assets)").option("--assetsInlineLimit <number>","[number] static asset base64 inline threshold in bytes (default: 4096)").option("--ssr [entry]","[string] build specified entry for server-side rendering").option("--sourcemap [output]",'[boolean | "inline" | "hidden"] output source maps for build (default: false)').option("--minify [minifier]",'[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)').option("--manifest [name]","[boolean | string] emit build manifest json").option("--ssrManifest [name]","[boolean | string] emit ssr manifest json").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle (experimental)").option("--emptyOutDir","[boolean] force empty outDir when it's outside of root").option("-w, --watch","[boolean] rebuilds when modules have changed on disk").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,t)=>{z(t);const o=U(t),n=l.resolveBuildCliOverrides(t);try{const i=await s.loadConfigFromFile({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let r=await l.getViteConfig(n);if(i){const{plugins:e,...t}=i.config;r=s.mergeConfig(r,t)}const a=s.mergeConfig(r,{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 s.build(a),o.changelog){const n=e||process.cwd(),i=a.build?.outDir||"dist";let r="dist-zip";a.ppDevConfig&&(!1===a.ppDevConfig.distZip?r=i:"object"==typeof a.ppDevConfig.distZip&&"string"==typeof a.ppDevConfig.distZip.outDir&&(r=a.ppDevConfig.distZip.outDir)),await O({changelog:o.changelog,executionRoot:n,newAssetsPath:y.resolve(n,i),backupsDirPath:y.resolve(n,a.ppDevConfig?.syncBackupsDir||"backups"),changelogDestinationPath:y.resolve(n,r),logLevel:t.logLevel})}}catch(e){a.createLogger(t.logLevel).error(a.colors.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>a.createLogger(t.logLevel).info(e))}}),N.command("next-build [root]","build a Next.js app for production (`next build`) and emit VERSION/BUILD-MANIFEST/zip in the same format as `pp-dev build`").option("--changelog [assetsFile]","[boolean | string] generate changelog between assetsFile and current build (default: false)").option("--distZip","[boolean] pack build output into a ZIP archive; use --no-distZip to disable (default: pp-dev config build.zip, or true). Env: PP_DEV_DIST_ZIP").option("--distZipDir <dir>","[string] override the ZIP output directory (default: 'dist-zip'). Env: PP_DEV_DIST_ZIP_DIR").option("--distZipFilename <filename>","[string] override the ZIP output file name (default: '<app-name>.zip'). Env: PP_DEV_DIST_ZIP_FILENAME").option("--versionManifest","[boolean] emit VERSION-*.json + BUILD-MANIFEST.json; use --no-versionManifest to disable (default: pp-dev config build.versionFile, or true). Env: PP_DEV_VERSION_MANIFEST").option("--versionFileTemplate <template>","[string] override the VERSION file name template (default: 'VERSION-v{packageversion}-{currentDate}.json'). Env: PP_DEV_VERSION_FILE_TEMPLATE").action(async(e,t)=>{z(t);const o=a.createLogger(t.logLevel),n=e?y.resolve(process.cwd(),e):process.cwd(),i=l.resolveBuildCliOverrides(t);process.env[a.PP_DEV_NEXT_BUILD_ENV_VAR]="1";try{const{constants:e}=await l.safeNextImport(),r=await import("next/dist/server/config.js"),s=r.default.default||r["module.exports"].default||r.default,c=await s(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-ctxv-2Kt.js")).then(e=>e.config);p=await e()}try{const{getPkg:e}=await Promise.resolve().then(()=>require("./index-ctxv-2Kt.js")).then(e=>e.config);d=e().name}catch{d=y.basename(n)}const f=a.normalizePPDevConfig(p,d),u=l.applyDistZipOverride(f.distZip,i,`${d}.zip`),g=l.applyVersionManifestOverride(f.versionPlugin,i);o.info(a.colors.cyan("[pp-dev] Running `next build`...")),await a.runNextBuildProcess(n);const h="string"==typeof c?.distDir&&c.distDir?c.distDir:".next",m=".next"===h?"out":h,b=y.resolve(n,m);if(!P.existsSync(b)||!P.statSync(b).isDirectory())throw new Error(`Next.js build output directory not found: ${b}. "next-build" requires "output: 'export'" in next.config (static export).`);const w=JSON.parse(P.readFileSync(y.join(n,"package.json"),"utf-8"));if(!1!==g&&!1!==g.enabled&&(a.writeBuildVersionManifest({outDir:b,packageVersion:"string"==typeof w.version?w.version:"0.0.0",versionFileTemplate:g.versionFileTemplate,packageRepositoryUrl:"string"==typeof w.repository?w.repository:w.repository?.url,enabled:g.enabled}),o.info(a.colors.green(`✅ VERSION / BUILD-MANIFEST written to ${y.relative(n,b)}`))),!1!==u){const e=y.resolve(n,u.outDir),t=u.inDir?y.resolve(b,u.inDir):b,i=y.join(e,u.outFileName);P.mkdirSync(e,{recursive:!0});const r=await a.zipDirectoryToBuffer(t);P.writeFileSync(i,r),o.info(a.colors.green(`✅ Zip archive written to ${y.relative(n,i)}`))}if(t.changelog){const e=!1!==u?u.outDir:m;await O({changelog:t.changelog,executionRoot:n,newAssetsPath:b,backupsDirPath:y.resolve(n,f.syncBackupsDir),changelogDestinationPath:y.resolve(n,e),logLevel:t.logLevel})}}catch(e){a.createLogger(t.logLevel).error(a.colors.red(`error during next-build:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>a.createLogger(t.logLevel).info(e))}}),N.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(e,t,o)=>{z(o);const{oldAssetsPath:n=e,newAssetsPath:i=t,destination:r=".",filename:s="CHANGELOG.html",logLevel:l}=o,c=process.cwd();n&&i||(a.createLogger(l).error(a.colors.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=y.resolve(c,n),p=y.resolve(c,i),f=y.resolve(c,r),u=new $({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:s});await u.generateChangelog()}),N.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(e,t,o)=>{z(o);const{source:n=e,destination:i=t,fontName:r="icon-font"}=o,s=process.cwd(),l=y.resolve(s,n),c=y.resolve(s,i),d=new j({sourceDir:l,outputDir:c,fontName:r}),p=a.createLogger(o.logLevel);p.info(`Generating icon font from SVG files in ${a.colors.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${a.colors.dim(c)}`)}),N.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{z(t);try{const o=await s.loadConfigFromFile({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await l.getViteConfig();if(o){const{plugins:e,...t}=o.config;n=s.mergeConfig(n,t)}const i=await s.resolveConfig(s.mergeConfig(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode}),"serve");await s.optimizeDeps(i,t.force,!0)}catch(e){a.createLogger(t.logLevel).error(a.colors.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),N.command("preview [root]","locally preview production build").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--strictPort","[boolean] exit if specified port is already in use").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--outDir <dir>","[string] output directory (default: dist)").action(async(e,t)=>{z(t);try{const o=await s.loadConfigFromFile({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await l.getViteConfig();if(o){const{plugins:e,...t}=o.config;n=s.mergeConfig(n,t)}(await s.preview(s.mergeConfig(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode,build:{outDir:t.outDir},preview:{port:t.port,strictPort:t.strictPort,host:t.host,https:t.https,open:t.open}}))).printUrls()}catch(e){a.createLogger(t.logLevel).error(a.colors.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{H(e=>a.createLogger(t.logLevel).info(e))}}),N.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=a.createLogger(t.logLevel),{isLegacyFlatConfig:n,isLegacyPPWatchConfig:i,isAlreadyMigrated:r,migrateLegacyFlatConfig:s,migratePPWatchConfig:l,generateConfigFileContent:c}=await Promise.resolve().then(()=>require("./migrate-r2mXdGLZ.js")),d=t.format??"ts",p=!1!==t.backup,f=process.cwd(),u=[".pp-watch.config.ts",".pp-watch.config.js",".pp-watch.config.json","pp-watch.config.ts","pp-watch.config.js","pp-watch.config.json"];let g=e??null,h=!1;if(!g){for(const e of a.PP_DEV_CONFIG_NAMES)if(P.existsSync(y.join(f,e))){g=y.join(f,e);break}if(!g)for(const e of u)if(P.existsSync(y.join(f,e))){g=y.join(f,e),h=!0;break}}g||(o.warn(a.colors.yellow("No pp-dev or pp-watch config file found in the current directory.")),o.info(a.colors.blue("Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}")),process.exit(1)),o.info(a.colors.blue(`Found config: ${y.relative(f,g)}`));const{getPkg:m}=await Promise.resolve().then(()=>require("./index-ctxv-2Kt.js")).then(e=>e.config),b=m();let w,v={};try{if(/\.[cm]?ts$/i.test(g)){const e=await import("esbuild"),{pathToFileURL:t}=await import("url"),o=(await e.build({absWorkingDir:f,entryPoints:[g],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,n=`pp-migrate-tmp-${Date.now()}.mjs`;P.writeFileSync(n,o);try{const e=await import(t(y.resolve(f,n)).toString());v=e.default?.default??e.default??e}finally{P.existsSync(n)&&P.unlinkSync(n)}}else if(/\.[cm]?js$/i.test(g)){const{pathToFileURL:e}=await import("url"),t=await import(e(y.resolve(f,g)).toString());v=t.default?.default??t.default??t}else g.endsWith(".json")&&(v=JSON.parse(P.readFileSync(g,"utf-8")))}catch(e){o.error(a.colors.red(`Failed to load config file: ${e.message}`)),process.exit(1)}v&&"object"==typeof v||(o.error(a.colors.red("Config file did not export a valid object.")),process.exit(1)),r(v)?(o.info(a.colors.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):h||i(v)?(o.info(a.colors.blue("Detected pp-watch config format → migrating to 1.0")),w=l(v)):n(v)?(o.info(a.colors.blue("Detected 0.x flat config format → migrating to 1.0")),w=s(v,b.name)):(o.warn(a.colors.yellow("Could not detect config format. No known keys found.")),process.exit(1));const x=c(w,d),S=t.output??y.join(f,`pp-dev.config.${d}`);if(t.dryRun&&(o.info(a.colors.green(`\n--- Migrated config (dry-run) → ${y.relative(f,S)} ---\n`)),process.exit(0)),p&&P.existsSync(g)){const e=`${g}.bak`;P.copyFileSync(g,e),o.info(a.colors.blue(`Backed up original to: ${y.relative(f,e)}`))}P.writeFileSync(S,x,"utf-8"),o.info(a.colors.green(`✅ Migration complete → ${y.relative(f,S)}`)),g!==S&&P.existsSync(g)&&o.info(a.colors.yellow(`You can now delete the old config: ${y.relative(f,g)}`))}),N.help(),N.version(a.VERSION),N.parse(),exports.stopProfiler=H;
|
|
2
2
|
//# sourceMappingURL=cli.js.map
|