@metricinsights/pp-dev 1.0.0-beta.1 → 1.0.0-beta.2
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 +50 -0
- package/README.md +60 -0
- package/dist/CHANGELOG.md +50 -0
- package/dist/README.md +60 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/cli.js.map +1 -1
- package/dist/cjs/index-DeUfAH6g.js +2 -0
- package/dist/cjs/index-DeUfAH6g.js.map +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/package.json +2 -2
- package/dist/cjs/{plugin-34c8_AjI.js → plugin-Cm9vRLCu.js} +2 -2
- package/dist/cjs/plugin-Cm9vRLCu.js.map +1 -0
- package/dist/cjs/plugin.js +1 -1
- package/dist/cjs/{version-plugin-BOFuJ-Rp.js → version-plugin-DsC5NLoX.js} +2 -2
- package/dist/cjs/{version-plugin-BOFuJ-Rp.js.map → version-plugin-DsC5NLoX.js.map} +1 -1
- package/dist/client/client.css +1 -1
- package/dist/client/client.css.map +1 -1
- package/dist/client/client.js +481 -30
- package/dist/client/client.js.map +1 -1
- package/dist/client/index.html +38 -2
- package/dist/esm/cli.js +1 -1
- package/dist/esm/cli.js.map +1 -1
- package/dist/esm/index-DOjGFYJ7.js +2 -0
- package/dist/esm/index-DOjGFYJ7.js.map +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/package.json +2 -2
- package/dist/esm/plugin-B2ocw-wb.js +2 -0
- package/dist/esm/plugin-B2ocw-wb.js.map +1 -0
- package/dist/esm/plugin.js +1 -1
- package/dist/esm/{version-plugin-vu8VWkws.js → version-plugin-BGWVTSsN.js} +2 -2
- package/dist/esm/{version-plugin-vu8VWkws.js.map → version-plugin-BGWVTSsN.js.map} +1 -1
- package/dist/types/index.d.ts +14 -1
- package/package.json +6 -6
- package/dist/cjs/index-MzGAxNTB.js +0 -2
- package/dist/cjs/index-MzGAxNTB.js.map +0 -1
- package/dist/cjs/plugin-34c8_AjI.js.map +0 -1
- package/dist/esm/index-C7dYPskY.js +0 -2
- package/dist/esm/index-C7dYPskY.js.map +0 -1
- package/dist/esm/plugin-Dvva-sxE.js +0 -2
- package/dist/esm/plugin-Dvva-sxE.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
+
# [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
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* **PP-3449:** add Dev Panel guide to README (position, auto-hide, hide/restore) ([54b8331](https://github.com/mi-examples/pp-dev/commit/54b833163bf65372f6ba55f5910cd7e3332261a9))
|
|
7
|
+
|
|
8
|
+
# [1.0.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.6...v1.0.0-beta.1) (2026-07-07)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
* feat(PP-3449)!: update dependencies and start the 1.0 release line ([abdad45](https://github.com/mi-examples/pp-dev/commit/abdad45b87e752d7468994f821841adc9e288e70))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
### Features
|
|
15
|
+
|
|
16
|
+
* **PP-3449:** add Dev Panel guide to README (position, auto-hide, hide/restore) ([54b8331](https://github.com/mi-examples/pp-dev/commit/54b833163bf65372f6ba55f5910cd7e3332261a9))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
### BREAKING CHANGES
|
|
20
|
+
|
|
21
|
+
* pp-dev moves to the 1.0 release line. Node.js >= 24
|
|
22
|
+
is required (declared in engines) and the package is no longer
|
|
23
|
+
published under the 0.x version scheme.
|
|
24
|
+
|
|
25
|
+
# [1.0.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.6...v1.0.0-beta.1) (2026-07-07)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
* feat(PP-3449)!: update dependencies and start the 1.0 release line ([abdad45](https://github.com/mi-examples/pp-dev/commit/abdad45b87e752d7468994f821841adc9e288e70))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
### BREAKING CHANGES
|
|
32
|
+
|
|
33
|
+
* pp-dev moves to the 1.0 release line. Node.js >= 24
|
|
34
|
+
is required (declared in engines) and the package is no longer
|
|
35
|
+
published under the 0.x version scheme.
|
|
36
|
+
|
|
37
|
+
# [0.20.0-beta.6](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.5...v0.20.0-beta.6) (2026-07-06)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
### Features
|
|
41
|
+
|
|
42
|
+
* **PP-3449:** configurable dev panel position, hide and auto-hide modes ([315d6fc](https://github.com/mi-examples/pp-dev/commit/315d6fc4182c1128f77fe192a425e3f816970f6f))
|
|
43
|
+
|
|
44
|
+
# [0.20.0-beta.5](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.4...v0.20.0-beta.5) (2026-07-06)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
### Bug Fixes
|
|
48
|
+
|
|
49
|
+
* **PP-3449:** stop request inspector from swallowing proxied PUT/POST bodies ([610a993](https://github.com/mi-examples/pp-dev/commit/610a9933ac0a7ec19ee349ff7c6490b605a739ed))
|
|
50
|
+
|
|
1
51
|
# [0.20.0-beta.4](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.3...v0.20.0-beta.4) (2026-07-02)
|
|
2
52
|
|
|
3
53
|
|
package/README.md
CHANGED
|
@@ -189,6 +189,24 @@ module.exports = defineConfig({
|
|
|
189
189
|
|--------------|----------|-------------|-----------------------------------------|
|
|
190
190
|
| `backupsDir` | `string` | `'backups'` | Directory for backups from the MI server |
|
|
191
191
|
|
|
192
|
+
### `devPanel` — Dev panel appearance
|
|
193
|
+
|
|
194
|
+
| Field | Type | Default | Description |
|
|
195
|
+
|------------|-----------------------------------------------------------------|------------------|-----------------------------------------------------------------------------|
|
|
196
|
+
| `position` | `'top-left' \| 'top-right' \| 'bottom-left' \| 'bottom-right'` | `'bottom-right'` | Screen corner the dev panel is anchored to |
|
|
197
|
+
| `hidden` | `boolean` | `false` | Fully hide the panel. Restore in the browser with `?pp-dev-panel=show` |
|
|
198
|
+
| `autoHide` | `boolean` | `false` | Panel slides behind the screen edge leaving a thin strip; hover reveals it |
|
|
199
|
+
|
|
200
|
+
These values are **defaults**: the panel itself has a settings popover (gear icon) with a corner
|
|
201
|
+
picker, an auto-hide toggle and a hide button, and the panel can be dragged by its grip handle and
|
|
202
|
+
snapped to any corner. Runtime choices are persisted in the browser's `localStorage`
|
|
203
|
+
(`pp-dev-info-position`, `pp-dev-info-auto-hide`, `pp-dev-info-hidden`) and take precedence over
|
|
204
|
+
the config until "Reset to config defaults" is clicked in the popover. The URL params
|
|
205
|
+
`?pp-dev-panel=show` / `?pp-dev-panel=hide` set a persistent override too — handy for restoring a
|
|
206
|
+
hidden panel or taking clean screenshots. Note that `localStorage` is origin-scoped, so overrides
|
|
207
|
+
apply to every pp-dev app served on the same host and port. See the [Dev Panel](#dev-panel)
|
|
208
|
+
section for the full feature description.
|
|
209
|
+
|
|
192
210
|
### Validation
|
|
193
211
|
|
|
194
212
|
pp-dev validates your config at startup and reports problems clearly:
|
|
@@ -201,6 +219,7 @@ pp-dev validates your config at startup and reports problems clearly:
|
|
|
201
219
|
| `app.type === 'template'` without `app.id` | error |
|
|
202
220
|
| `app.type === 'page'` + `mi.mode === 'standalone'` without `app.id` | error |
|
|
203
221
|
| `app.name` missing and no `package.json#name` | error |
|
|
222
|
+
| `devPanel.position` not one of the four corners | error |
|
|
204
223
|
|
|
205
224
|
### Environment Variables
|
|
206
225
|
|
|
@@ -388,6 +407,47 @@ module.exports = withPPDev({
|
|
|
388
407
|
|
|
389
408
|
For custom build configuration, create a `vite.config` file. See [Vite Configuration](https://vitejs.dev/config/) for details.
|
|
390
409
|
|
|
410
|
+
## Dev Panel
|
|
411
|
+
|
|
412
|
+
pp-dev injects a floating dev panel into every served page. It shows the package name and version, the backend URL, the template mode and the App ID, and hosts the template **Sync** button. Since 1.0 the panel is fully repositionable and can be hidden.
|
|
413
|
+
|
|
414
|
+
### Position
|
|
415
|
+
|
|
416
|
+
The panel can be anchored to any of the four screen corners (default: bottom-right). Three ways to move it:
|
|
417
|
+
|
|
418
|
+
- **Drag & snap** — grab the grip handle (six dots on the panel's left side) and drag; on release the panel snaps to the nearest corner. Dragging works across iframes and is cancelled with <kbd>Escape</kbd>.
|
|
419
|
+
- **Settings popover** — click the gear icon and pick a corner in the 2×2 grid.
|
|
420
|
+
- **Config default** — set `devPanel.position` in `pp-dev.config` (see below).
|
|
421
|
+
|
|
422
|
+
The minimize arrow, the panel's shadow, rounded corner and slide direction all mirror automatically for left/top placements. Sync notification popups stack from the screen edge opposite the panel so they never cover it.
|
|
423
|
+
|
|
424
|
+
### Auto-hide
|
|
425
|
+
|
|
426
|
+
Toggle **Auto-hide** in the settings popover (or set `devPanel.autoHide: true`). The panel slides behind the nearest screen edge leaving a 4px accent strip; hovering the strip for ~300 ms slides it out, and it hides again ~500 ms after the pointer leaves. Keyboard focus inside the panel keeps it revealed. While auto-hide is active the minimize arrow acts as a **pin** button that returns the panel to normal mode.
|
|
427
|
+
|
|
428
|
+
### Hiding and restoring
|
|
429
|
+
|
|
430
|
+
**Hide panel** in the settings popover (or `devPanel.hidden: true`) removes the panel from view entirely. To bring it back, open any page with `?pp-dev-panel=show` in the URL — the override persists across reloads. The symmetric `?pp-dev-panel=hide` hides it, which is handy for demos and clean screenshots.
|
|
431
|
+
|
|
432
|
+
### State persistence
|
|
433
|
+
|
|
434
|
+
Runtime choices are saved in the browser's `localStorage` (`pp-dev-info-position`, `pp-dev-info-auto-hide`, `pp-dev-info-hidden`) and take precedence over config values. **Reset to config defaults** in the settings popover clears all overrides. Storage is origin-scoped: overrides apply to every pp-dev app served on the same host and port, and a Metric Insights page that clears origin storage will reset them to config defaults.
|
|
435
|
+
|
|
436
|
+
### Configuration
|
|
437
|
+
|
|
438
|
+
```typescript
|
|
439
|
+
// pp-dev.config.ts
|
|
440
|
+
export default defineConfig({
|
|
441
|
+
devPanel: {
|
|
442
|
+
position: 'bottom-right', // 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
|
|
443
|
+
hidden: false, // hide the panel entirely (restore with ?pp-dev-panel=show)
|
|
444
|
+
autoHide: false, // slide behind the screen edge, reveal on hover
|
|
445
|
+
},
|
|
446
|
+
});
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
See the [`devPanel` option reference](#devpanel--dev-panel-appearance) for details.
|
|
450
|
+
|
|
391
451
|
## Request Inspector
|
|
392
452
|
|
|
393
453
|
pp-dev includes a built-in request inspector that captures every proxied and locally-served HTTP request made during development. It is enabled by default.
|
package/dist/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
+
# [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
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* **PP-3449:** add Dev Panel guide to README (position, auto-hide, hide/restore) ([54b8331](https://github.com/mi-examples/pp-dev/commit/54b833163bf65372f6ba55f5910cd7e3332261a9))
|
|
7
|
+
|
|
8
|
+
# [1.0.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.6...v1.0.0-beta.1) (2026-07-07)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
* feat(PP-3449)!: update dependencies and start the 1.0 release line ([abdad45](https://github.com/mi-examples/pp-dev/commit/abdad45b87e752d7468994f821841adc9e288e70))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
### Features
|
|
15
|
+
|
|
16
|
+
* **PP-3449:** add Dev Panel guide to README (position, auto-hide, hide/restore) ([54b8331](https://github.com/mi-examples/pp-dev/commit/54b833163bf65372f6ba55f5910cd7e3332261a9))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
### BREAKING CHANGES
|
|
20
|
+
|
|
21
|
+
* pp-dev moves to the 1.0 release line. Node.js >= 24
|
|
22
|
+
is required (declared in engines) and the package is no longer
|
|
23
|
+
published under the 0.x version scheme.
|
|
24
|
+
|
|
25
|
+
# [1.0.0-beta.1](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.6...v1.0.0-beta.1) (2026-07-07)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
* feat(PP-3449)!: update dependencies and start the 1.0 release line ([abdad45](https://github.com/mi-examples/pp-dev/commit/abdad45b87e752d7468994f821841adc9e288e70))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
### BREAKING CHANGES
|
|
32
|
+
|
|
33
|
+
* pp-dev moves to the 1.0 release line. Node.js >= 24
|
|
34
|
+
is required (declared in engines) and the package is no longer
|
|
35
|
+
published under the 0.x version scheme.
|
|
36
|
+
|
|
37
|
+
# [0.20.0-beta.6](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.5...v0.20.0-beta.6) (2026-07-06)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
### Features
|
|
41
|
+
|
|
42
|
+
* **PP-3449:** configurable dev panel position, hide and auto-hide modes ([315d6fc](https://github.com/mi-examples/pp-dev/commit/315d6fc4182c1128f77fe192a425e3f816970f6f))
|
|
43
|
+
|
|
44
|
+
# [0.20.0-beta.5](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.4...v0.20.0-beta.5) (2026-07-06)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
### Bug Fixes
|
|
48
|
+
|
|
49
|
+
* **PP-3449:** stop request inspector from swallowing proxied PUT/POST bodies ([610a993](https://github.com/mi-examples/pp-dev/commit/610a9933ac0a7ec19ee349ff7c6490b605a739ed))
|
|
50
|
+
|
|
1
51
|
# [0.20.0-beta.4](https://github.com/mi-examples/pp-dev/compare/v0.20.0-beta.3...v0.20.0-beta.4) (2026-07-02)
|
|
2
52
|
|
|
3
53
|
|
package/dist/README.md
CHANGED
|
@@ -189,6 +189,24 @@ module.exports = defineConfig({
|
|
|
189
189
|
|--------------|----------|-------------|-----------------------------------------|
|
|
190
190
|
| `backupsDir` | `string` | `'backups'` | Directory for backups from the MI server |
|
|
191
191
|
|
|
192
|
+
### `devPanel` — Dev panel appearance
|
|
193
|
+
|
|
194
|
+
| Field | Type | Default | Description |
|
|
195
|
+
|------------|-----------------------------------------------------------------|------------------|-----------------------------------------------------------------------------|
|
|
196
|
+
| `position` | `'top-left' \| 'top-right' \| 'bottom-left' \| 'bottom-right'` | `'bottom-right'` | Screen corner the dev panel is anchored to |
|
|
197
|
+
| `hidden` | `boolean` | `false` | Fully hide the panel. Restore in the browser with `?pp-dev-panel=show` |
|
|
198
|
+
| `autoHide` | `boolean` | `false` | Panel slides behind the screen edge leaving a thin strip; hover reveals it |
|
|
199
|
+
|
|
200
|
+
These values are **defaults**: the panel itself has a settings popover (gear icon) with a corner
|
|
201
|
+
picker, an auto-hide toggle and a hide button, and the panel can be dragged by its grip handle and
|
|
202
|
+
snapped to any corner. Runtime choices are persisted in the browser's `localStorage`
|
|
203
|
+
(`pp-dev-info-position`, `pp-dev-info-auto-hide`, `pp-dev-info-hidden`) and take precedence over
|
|
204
|
+
the config until "Reset to config defaults" is clicked in the popover. The URL params
|
|
205
|
+
`?pp-dev-panel=show` / `?pp-dev-panel=hide` set a persistent override too — handy for restoring a
|
|
206
|
+
hidden panel or taking clean screenshots. Note that `localStorage` is origin-scoped, so overrides
|
|
207
|
+
apply to every pp-dev app served on the same host and port. See the [Dev Panel](#dev-panel)
|
|
208
|
+
section for the full feature description.
|
|
209
|
+
|
|
192
210
|
### Validation
|
|
193
211
|
|
|
194
212
|
pp-dev validates your config at startup and reports problems clearly:
|
|
@@ -201,6 +219,7 @@ pp-dev validates your config at startup and reports problems clearly:
|
|
|
201
219
|
| `app.type === 'template'` without `app.id` | error |
|
|
202
220
|
| `app.type === 'page'` + `mi.mode === 'standalone'` without `app.id` | error |
|
|
203
221
|
| `app.name` missing and no `package.json#name` | error |
|
|
222
|
+
| `devPanel.position` not one of the four corners | error |
|
|
204
223
|
|
|
205
224
|
### Environment Variables
|
|
206
225
|
|
|
@@ -388,6 +407,47 @@ module.exports = withPPDev({
|
|
|
388
407
|
|
|
389
408
|
For custom build configuration, create a `vite.config` file. See [Vite Configuration](https://vitejs.dev/config/) for details.
|
|
390
409
|
|
|
410
|
+
## Dev Panel
|
|
411
|
+
|
|
412
|
+
pp-dev injects a floating dev panel into every served page. It shows the package name and version, the backend URL, the template mode and the App ID, and hosts the template **Sync** button. Since 1.0 the panel is fully repositionable and can be hidden.
|
|
413
|
+
|
|
414
|
+
### Position
|
|
415
|
+
|
|
416
|
+
The panel can be anchored to any of the four screen corners (default: bottom-right). Three ways to move it:
|
|
417
|
+
|
|
418
|
+
- **Drag & snap** — grab the grip handle (six dots on the panel's left side) and drag; on release the panel snaps to the nearest corner. Dragging works across iframes and is cancelled with <kbd>Escape</kbd>.
|
|
419
|
+
- **Settings popover** — click the gear icon and pick a corner in the 2×2 grid.
|
|
420
|
+
- **Config default** — set `devPanel.position` in `pp-dev.config` (see below).
|
|
421
|
+
|
|
422
|
+
The minimize arrow, the panel's shadow, rounded corner and slide direction all mirror automatically for left/top placements. Sync notification popups stack from the screen edge opposite the panel so they never cover it.
|
|
423
|
+
|
|
424
|
+
### Auto-hide
|
|
425
|
+
|
|
426
|
+
Toggle **Auto-hide** in the settings popover (or set `devPanel.autoHide: true`). The panel slides behind the nearest screen edge leaving a 4px accent strip; hovering the strip for ~300 ms slides it out, and it hides again ~500 ms after the pointer leaves. Keyboard focus inside the panel keeps it revealed. While auto-hide is active the minimize arrow acts as a **pin** button that returns the panel to normal mode.
|
|
427
|
+
|
|
428
|
+
### Hiding and restoring
|
|
429
|
+
|
|
430
|
+
**Hide panel** in the settings popover (or `devPanel.hidden: true`) removes the panel from view entirely. To bring it back, open any page with `?pp-dev-panel=show` in the URL — the override persists across reloads. The symmetric `?pp-dev-panel=hide` hides it, which is handy for demos and clean screenshots.
|
|
431
|
+
|
|
432
|
+
### State persistence
|
|
433
|
+
|
|
434
|
+
Runtime choices are saved in the browser's `localStorage` (`pp-dev-info-position`, `pp-dev-info-auto-hide`, `pp-dev-info-hidden`) and take precedence over config values. **Reset to config defaults** in the settings popover clears all overrides. Storage is origin-scoped: overrides apply to every pp-dev app served on the same host and port, and a Metric Insights page that clears origin storage will reset them to config defaults.
|
|
435
|
+
|
|
436
|
+
### Configuration
|
|
437
|
+
|
|
438
|
+
```typescript
|
|
439
|
+
// pp-dev.config.ts
|
|
440
|
+
export default defineConfig({
|
|
441
|
+
devPanel: {
|
|
442
|
+
position: 'bottom-right', // 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
|
|
443
|
+
hidden: false, // hide the panel entirely (restore with ?pp-dev-panel=show)
|
|
444
|
+
autoHide: false, // slide behind the screen edge, reveal on hover
|
|
445
|
+
},
|
|
446
|
+
});
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
See the [`devPanel` option reference](#devpanel--dev-panel-appearance) for details.
|
|
450
|
+
|
|
391
451
|
## Request Inspector
|
|
392
452
|
|
|
393
453
|
pp-dev includes a built-in request inspector that captures every proxied and locally-served HTTP request made during development. It is enabled by default.
|
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-34c8_AjI.js"),l=require("./index-MzGAxNTB.js"),c=require("url"),d=require("dir-compare"),p=require("diff-match-patch"),f=require("isbinaryfile"),g=require("os"),u=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(g),L=v(u),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:g}=await Promise.resolve().then(()=>require("./index-MzGAxNTB.js")).then(e=>e.config);f();const{createServer:u}=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 u(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 g();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(),g=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-MzGAxNTB.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-MzGAxNTB.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-MzGAxNTB.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(`^((${u=K,u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),g=a.initLoadPPData(p,ie,Object.assign({base:K},t,{miHudLess:G})),h=(e,t,o)=>{g(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});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,g,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 u}},u=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",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),process.on("uncaughtException",e=>{f.error(a.colors.red(`❌ Uncaught Exception: ${e}`)),u("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{f.error(a.colors.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),u("unhandledRejection")}),await g()}),_.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),g=new A({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:s});await g.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(),g=[".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 u=e??null,h=!1;if(!u){for(const e of a.PP_DEV_CONFIG_NAMES)if(P.existsSync(y.join(f,e))){u=y.join(f,e);break}if(!u)for(const e of g)if(P.existsSync(y.join(f,e))){u=y.join(f,e),h=!0;break}}u||(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,u)}`));const{getPkg:m}=await Promise.resolve().then(()=>require("./index-MzGAxNTB.js")).then(e=>e.config),b=m();let w,v={};try{if(/\.[cm]?ts$/i.test(u)){const e=await import("esbuild"),{pathToFileURL:t}=await import("url"),o=(await e.build({absWorkingDir:f,entryPoints:[u],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(u)){const{pathToFileURL:e}=await import("url"),t=await import(e(y.resolve(f,u)).toString());v=t.default?.default??t.default??t}else u.endsWith(".json")&&(v=JSON.parse(P.readFileSync(u,"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(u)){const e=`${u}.bak`;P.copyFileSync(u,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)}`)),u!==S&&P.existsSync(u)&&o.info(a.colors.yellow(`You can now delete the old config: ${y.relative(f,u)}`))}),_.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-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;
|
|
2
2
|
//# sourceMappingURL=cli.js.map
|