@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.
Files changed (40) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +60 -0
  3. package/dist/CHANGELOG.md +50 -0
  4. package/dist/README.md +60 -0
  5. package/dist/cjs/cli.js +1 -1
  6. package/dist/cjs/cli.js.map +1 -1
  7. package/dist/cjs/index-DeUfAH6g.js +2 -0
  8. package/dist/cjs/index-DeUfAH6g.js.map +1 -0
  9. package/dist/cjs/index.js +1 -1
  10. package/dist/cjs/package.json +2 -2
  11. package/dist/cjs/{plugin-34c8_AjI.js → plugin-Cm9vRLCu.js} +2 -2
  12. package/dist/cjs/plugin-Cm9vRLCu.js.map +1 -0
  13. package/dist/cjs/plugin.js +1 -1
  14. package/dist/cjs/{version-plugin-BOFuJ-Rp.js → version-plugin-DsC5NLoX.js} +2 -2
  15. package/dist/cjs/{version-plugin-BOFuJ-Rp.js.map → version-plugin-DsC5NLoX.js.map} +1 -1
  16. package/dist/client/client.css +1 -1
  17. package/dist/client/client.css.map +1 -1
  18. package/dist/client/client.js +481 -30
  19. package/dist/client/client.js.map +1 -1
  20. package/dist/client/index.html +38 -2
  21. package/dist/esm/cli.js +1 -1
  22. package/dist/esm/cli.js.map +1 -1
  23. package/dist/esm/index-DOjGFYJ7.js +2 -0
  24. package/dist/esm/index-DOjGFYJ7.js.map +1 -0
  25. package/dist/esm/index.js +1 -1
  26. package/dist/esm/package.json +2 -2
  27. package/dist/esm/plugin-B2ocw-wb.js +2 -0
  28. package/dist/esm/plugin-B2ocw-wb.js.map +1 -0
  29. package/dist/esm/plugin.js +1 -1
  30. package/dist/esm/{version-plugin-vu8VWkws.js → version-plugin-BGWVTSsN.js} +2 -2
  31. package/dist/esm/{version-plugin-vu8VWkws.js.map → version-plugin-BGWVTSsN.js.map} +1 -1
  32. package/dist/types/index.d.ts +14 -1
  33. package/package.json +6 -6
  34. package/dist/cjs/index-MzGAxNTB.js +0 -2
  35. package/dist/cjs/index-MzGAxNTB.js.map +0 -1
  36. package/dist/cjs/plugin-34c8_AjI.js.map +0 -1
  37. package/dist/esm/index-C7dYPskY.js +0 -2
  38. package/dist/esm/index-C7dYPskY.js.map +0 -1
  39. package/dist/esm/plugin-Dvva-sxE.js +0 -2
  40. package/dist/esm/plugin-Dvva-sxE.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../src/client/hot-context.ts","../../src/client/index.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\nimport type { ViteHotContext } from 'vite/types/hot.js';\n\n/**\n * Minimal `import.meta.hot`-compatible context for environments without Vite HMR\n * (e.g. the `pp-dev next` server). The dev-panel client only uses `hot.on()` and\n * `hot.send()`; this shim implements those over a raw WebSocket using the same\n * custom-event wire shape Vite uses: `{ type: 'custom', event, data }`.\n *\n * Used only as a fallback: when `import.meta.hot` exists (Vite), that is used\n * instead and this code never runs.\n */\n\n/**\n * WebSocket path the pp-dev Next.js server listens on for dev-panel messages.\n * Kept in sync with `PP_DEV_HMR_WS_PATH` in `src/constants.ts` (server side).\n */\nconst PP_DEV_HMR_WS_PATH = '/@pp-dev-hmr';\n\ntype CustomMessage = { type: 'custom'; event: string; data?: unknown };\n\ntype Handler = (payload: any) => void;\n\nconst MAX_OUTBOX_SIZE = 50;\n\nfunction resolveWebSocketUrl(): string {\n const { protocol, host } = window.location;\n const wsProtocol = protocol === 'https:' ? 'wss:' : 'ws:';\n\n return `${wsProtocol}//${host}${PP_DEV_HMR_WS_PATH}`;\n}\n\nexport function createPPDevHotContext(): ViteHotContext {\n const handlers = new Map<string, Set<Handler>>();\n /** Outgoing messages queued while the socket is not OPEN; flushed on connect. */\n const outbox: string[] = [];\n\n let socket: WebSocket | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n let reconnectDelay = 1_000;\n const MAX_RECONNECT_DELAY = 10_000;\n\n const flushOutbox = () => {\n if (!socket || socket.readyState !== WebSocket.OPEN) {\n return;\n }\n\n while (outbox.length > 0) {\n socket.send(outbox.shift()!);\n }\n };\n\n const dispatch = (event: string, data: unknown) => {\n const eventHandlers = handlers.get(event);\n\n if (!eventHandlers) {\n return;\n }\n\n for (const handler of eventHandlers) {\n try {\n handler(data);\n } catch (err) {\n // A failing handler must not break dispatch to the others.\n console.error(`[pp-dev] hot handler for \"${event}\" failed`, err);\n }\n }\n };\n\n const connect = () => {\n try {\n socket = new WebSocket(resolveWebSocketUrl());\n } catch (err) {\n console.error('[pp-dev] failed to open dev-panel WebSocket', err);\n scheduleReconnect();\n\n return;\n }\n\n socket.addEventListener('open', () => {\n reconnectDelay = 1_000;\n flushOutbox();\n });\n\n socket.addEventListener('message', (ev) => {\n let message: CustomMessage;\n\n try {\n message = JSON.parse(typeof ev.data === 'string' ? ev.data : '');\n } catch {\n return;\n }\n\n if (message && message.type === 'custom' && typeof message.event === 'string') {\n dispatch(message.event, message.data);\n }\n });\n\n socket.addEventListener('close', () => {\n socket = null;\n scheduleReconnect();\n });\n\n socket.addEventListener('error', () => {\n // `close` follows `error`; reconnect is scheduled there.\n socket?.close();\n });\n };\n\n const scheduleReconnect = () => {\n if (reconnectTimer) {\n return;\n }\n\n reconnectTimer = setTimeout(() => {\n reconnectTimer = null;\n reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY);\n connect();\n }, reconnectDelay);\n };\n\n connect();\n\n const noop = () => {};\n\n const context: Pick<ViteHotContext, 'on' | 'off' | 'send'> & Partial<ViteHotContext> = {\n on(event, cb) {\n let set = handlers.get(event);\n\n if (!set) {\n set = new Set();\n handlers.set(event, set);\n }\n\n set.add(cb as Handler);\n },\n off(event, cb) {\n handlers.get(event)?.delete(cb as Handler);\n },\n send(event, data) {\n const payload = JSON.stringify({ type: 'custom', event, data } satisfies CustomMessage);\n\n if (socket && socket.readyState === WebSocket.OPEN) {\n socket.send(payload);\n } else {\n if (outbox.length >= MAX_OUTBOX_SIZE) {\n outbox.shift();\n }\n\n outbox.push(payload);\n }\n },\n // Unused by the dev-panel client; provided as no-ops to satisfy the shape.\n accept: noop as ViteHotContext['accept'],\n acceptExports: noop as ViteHotContext['acceptExports'],\n dispose: noop,\n prune: noop,\n invalidate: noop,\n data: {},\n };\n\n return context as ViteHotContext;\n}\n","/// <reference types=\"vite/client\" />\nimport './assets/css/client.scss';\nimport './index.html';\nimport { createPPDevHotContext } from './hot-context.js';\n\nfunction checkLocalStorage() {\n try {\n localStorage.setItem('test', 'test');\n localStorage.removeItem('test');\n\n return true;\n } catch (e) {\n return false;\n }\n}\n\nfunction setStorageItem(key: string, value: string) {\n if (checkLocalStorage()) {\n localStorage.setItem(key, value);\n }\n}\n\nfunction getStorageItem(key: string) {\n if (checkLocalStorage()) {\n return localStorage.getItem(key);\n }\n\n return null;\n}\n\nfunction removeStorageItem(key: string) {\n if (checkLocalStorage()) {\n localStorage.removeItem(key);\n }\n}\n\ninterface InfoPopupOptions {\n title: string;\n content: string;\n style?: string;\n className?: string;\n duration?: number;\n onClose?: () => void;\n type?: 'success' | 'danger' | 'info' | 'warning';\n}\n\ninterface SyncActionRequiredPayload {\n requestId: string;\n title: string;\n content: string;\n confirmText: string;\n cancelText: string;\n}\n\ninterface ConfirmModalOptions {\n title: string;\n content: string;\n confirmText: string;\n cancelText: string;\n}\n\nlet activePopups = 0;\nconst POPUP_OFFSET = 10;\nconst POPUP_HEIGHT = 100;\nconst ANIMATION_DURATION = 300;\nconst CONFIRM_MODAL_OVERLAY_CLASS = 'pp-dev-info__confirm-overlay';\n\nconst activeConfirmModals = new Map<\n HTMLDivElement,\n { resolve: (value: boolean) => void; onKeyDown: (event: KeyboardEvent) => void }\n>();\n\nconst ICON_SIZE = 16;\nconst CLOSE_ICON_SIZE = 12;\n\nfunction teardownConfirmModal(overlay: HTMLDivElement, result: boolean) {\n const entry = activeConfirmModals.get(overlay);\n\n if (!entry) {\n return;\n }\n\n document.removeEventListener('keydown', entry.onKeyDown);\n\n activeConfirmModals.delete(overlay);\n overlay.remove();\n entry.resolve(result);\n}\n\nconst TYPE_ICONS: Record<NonNullable<InfoPopupOptions['type']>, string> = {\n success: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"m9 12 2 2 4-4\"/></svg>`,\n danger: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 8v4\"/><path d=\"M12 16h.01\"/></svg>`,\n warning: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z\"/><path d=\"M12 9v4\"/><path d=\"M12 17h.01\"/></svg>`,\n info: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 16v-4\"/><path d=\"M12 8h.01\"/></svg>`,\n};\n\nfunction createPopupElement(opts: InfoPopupOptions): HTMLDivElement {\n const $popup = document.createElement('div');\n\n $popup.classList.add('pp-dev-info-namespace');\n\n const typeClass = opts.type ? `pp-dev-info__popup--${opts.type}` : '';\n const iconHtml = opts.type ? `<div class=\"pp-dev-info__popup-title-icon\">${TYPE_ICONS[opts.type]}</div>` : '';\n\n const template = `\n <div class=\"pp-dev-info__popup ${typeClass} ${opts.className || ''}\" style=\"${opts.style || ''}\">\n <div class=\"pp-dev-info__popup-title\">\n ${iconHtml}\n <div class=\"pp-dev-info__popup-title-text\">${opts.title}</div>\n <div class=\"pp-dev-info__popup-title-close\">\n <svg\n viewBox=\"0 0 24 24\"\n width=\"${CLOSE_ICON_SIZE}\"\n height=\"${CLOSE_ICON_SIZE}\"\n stroke=\"currentColor\"\n stroke-width=\"1.5\"\n fill=\"none\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n >\n <path d=\"M18 6L6 18\"></path>\n <path d=\"M6 6l12 12\"></path>\n </svg>\n </div>\n </div>\n <div class=\"pp-dev-info__popup-content\">${opts.content}</div>\n </div>\n `;\n\n $popup.innerHTML = template;\n\n return $popup;\n}\n\nfunction updatePopupPositions() {\n const popups = document.querySelectorAll<HTMLElement>('.pp-dev-info-namespace:not(.pp-dev-info)');\n const $devPanel = document.querySelector('.pp-dev-info');\n\n // Update popup positions\n popups.forEach((popup, index: number) => {\n const top = POPUP_OFFSET + index * (POPUP_HEIGHT + POPUP_OFFSET);\n const $popupContent = popup.querySelector<HTMLElement>('.pp-dev-info__popup');\n\n if ($popupContent) {\n $popupContent.style.top = `${top}px`;\n }\n });\n\n // Ensure dev panel stays at the bottom\n if ($devPanel) {\n ($devPanel as HTMLElement).style.top = 'auto';\n ($devPanel as HTMLElement).style.bottom = '0';\n }\n}\n\nfunction animatePopup($popup: HTMLDivElement, type: 'enter' | 'exit') {\n return new Promise<void>((resolve) => {\n const $popupContent = $popup.querySelector('.pp-dev-info__popup');\n\n if (!$popupContent) {\n return resolve();\n }\n\n if (type === 'enter') {\n $popupContent.classList.add('entering');\n\n requestAnimationFrame(() => {\n $popupContent.classList.remove('entering');\n\n resolve();\n });\n } else {\n $popupContent.classList.add('exiting');\n\n setTimeout(() => {\n $popupContent.classList.remove('exiting');\n\n resolve();\n }, ANIMATION_DURATION);\n }\n });\n}\n\nfunction infoPopup(opts: InfoPopupOptions) {\n const $popup = createPopupElement(opts);\n const $closeButton = $popup.querySelector('.pp-dev-info__popup-title-close');\n\n const removePopup = async () => {\n await animatePopup($popup, 'exit');\n\n $popup.remove();\n\n activePopups--;\n\n updatePopupPositions();\n\n opts.onClose?.();\n };\n\n $closeButton?.addEventListener('click', removePopup);\n document.body.appendChild($popup);\n\n // Position the popup\n activePopups++;\n updatePopupPositions();\n\n // Animate entrance\n animatePopup($popup, 'enter');\n\n const duration = opts.duration ?? 10000;\n\n if (duration > 0) {\n let remainingTime = duration;\n let lastUpdate = Date.now();\n let isVisible = true;\n\n const scheduleDismiss = () => {\n if (!isVisible) {\n return;\n }\n\n const now = Date.now();\n const elapsed = now - lastUpdate;\n\n remainingTime -= elapsed;\n lastUpdate = now;\n\n if (remainingTime <= 0) {\n removePopup();\n\n return;\n }\n\n requestAnimationFrame(scheduleDismiss);\n };\n\n // Handle visibility change\n document.addEventListener('visibilitychange', () => {\n isVisible = !document.hidden;\n\n if (isVisible) {\n lastUpdate = Date.now();\n requestAnimationFrame(scheduleDismiss);\n }\n });\n\n requestAnimationFrame(scheduleDismiss);\n }\n}\n\nfunction closeAllConfirmModals() {\n for (const overlay of [...activeConfirmModals.keys()]) {\n teardownConfirmModal(overlay, false);\n }\n}\n\nfunction confirmModal(opts: ConfirmModalOptions): Promise<boolean> {\n closeAllConfirmModals();\n\n return new Promise<boolean>((resolve) => {\n const $overlay = document.createElement('div');\n\n $overlay.classList.add('pp-dev-info-namespace', CONFIRM_MODAL_OVERLAY_CLASS);\n\n const $confirm = document.createElement('div');\n\n $confirm.classList.add('pp-dev-info__confirm');\n\n const $title = document.createElement('div');\n\n $title.classList.add('pp-dev-info__confirm-title');\n $title.textContent = opts.title;\n\n const $content = document.createElement('div');\n\n $content.classList.add('pp-dev-info__confirm-content');\n $content.textContent = opts.content;\n\n const $actions = document.createElement('div');\n\n $actions.classList.add('pp-dev-info__confirm-actions');\n\n const $cancelButton = document.createElement('button');\n\n $cancelButton.type = 'button';\n $cancelButton.classList.add('pp-dev-info__confirm-btn', 'pp-dev-info__confirm-btn--cancel');\n $cancelButton.textContent = opts.cancelText;\n\n const $confirmButton = document.createElement('button');\n\n $confirmButton.type = 'button';\n $confirmButton.classList.add('pp-dev-info__confirm-btn', 'pp-dev-info__confirm-btn--confirm');\n $confirmButton.textContent = opts.confirmText;\n\n $actions.append($cancelButton, $confirmButton);\n $confirm.append($title, $content, $actions);\n $overlay.appendChild($confirm);\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n teardownConfirmModal($overlay, false);\n }\n };\n\n activeConfirmModals.set($overlay, { resolve, onKeyDown });\n\n $confirmButton.addEventListener('click', () => {\n teardownConfirmModal($overlay, true);\n });\n\n $cancelButton.addEventListener('click', () => {\n teardownConfirmModal($overlay, false);\n });\n\n $overlay.addEventListener('click', (event) => {\n if (event.target === $overlay) {\n teardownConfirmModal($overlay, false);\n }\n });\n\n document.addEventListener('keydown', onKeyDown);\n document.body.appendChild($overlay);\n });\n}\n\n// ── Inspector console banner ──────────────────────────────────────────────────\n// Logged once on page load so it is visible in DevTools history when the console\n// is opened. The message is harmless if the inspector is disabled.\n(function printInspectorBanner() {\n const url = window.location.origin + '/@pp-dev/inspector';\n\n console.log(\n '%cpp-dev%c 🔍 Request Inspector → %c%s',\n 'background:#6e8efb;color:#fff;padding:2px 8px;border-radius:4px;font-weight:700;font-size:11px',\n 'color:#a0a0b8;font-size:11px',\n 'color:#a78bfa;font-size:11px;text-decoration:underline',\n url,\n );\n})();\n\n// Use Vite's HMR context when available; otherwise fall back to a raw-WebSocket\n// shim so the dev panel also works under the `pp-dev next` server (no Vite HMR).\nconst hot = import.meta.hot ?? createPPDevHotContext();\n\nif (hot) {\n const CLOSED_CLASS = 'closed';\n const CLOSED_CLASS_STORAGE_KEY = 'pp-dev-info-closed';\n\n hot.on('redirect', (data: { url: string }) => {\n window.location.href = data.url;\n });\n\n hot.on('client:config:update', (data: { config: { [key: string]: any } }) => {\n if (typeof data.config?.canSync === 'boolean') {\n if (data.config.canSync) {\n const $syncButton = document.getElementById('sync-template') as HTMLButtonElement | null;\n\n if ($syncButton) {\n $syncButton.disabled = false;\n $syncButton.classList.remove('disabled');\n $syncButton.title = 'Sync template';\n }\n } else {\n const $syncButton = document.getElementById('sync-template') as HTMLButtonElement | null;\n\n if ($syncButton) {\n $syncButton.disabled = true;\n $syncButton.classList.add('disabled');\n $syncButton.title = 'Sync is unavailable on this instance';\n }\n }\n }\n });\n\n let isClosed = getStorageItem(CLOSED_CLASS_STORAGE_KEY) === 'true' || false;\n\n const $infoPanel = document.querySelector('.pp-dev-info');\n\n const $minimizeButtonWrap = document.querySelector('.pp-dev-info__wrap-btn');\n const $minimizeButtonSVG = $minimizeButtonWrap?.querySelector('svg');\n\n if ($infoPanel && $minimizeButtonWrap && $minimizeButtonSVG) {\n if (isClosed) {\n $infoPanel.classList.add(CLOSED_CLASS);\n $minimizeButtonSVG.classList.add(CLOSED_CLASS);\n }\n\n $minimizeButtonWrap.addEventListener('click', (e: Event) => {\n e.preventDefault();\n\n $infoPanel.classList.toggle(CLOSED_CLASS);\n $minimizeButtonSVG.classList.toggle(CLOSED_CLASS);\n\n isClosed = !isClosed;\n\n setStorageItem(CLOSED_CLASS_STORAGE_KEY, isClosed ? 'true' : 'false');\n });\n }\n\n const $syncButton = document.getElementById('sync-template') as HTMLButtonElement | null;\n\n if ($syncButton) {\n hot.on('template:sync:action-required', async (payload: SyncActionRequiredPayload) => {\n // Keep the sync spinner running while a confirmation modal is shown — the sync\n // process is still in progress and only ends on `template:sync:response`.\n const approved = await confirmModal({\n title: payload.title,\n content: payload.content,\n confirmText: payload.confirmText,\n cancelText: payload.cancelText,\n });\n\n hot.send('template:sync:action-response', {\n requestId: payload.requestId,\n approved,\n });\n });\n\n hot.on(\n 'template:sync:response',\n (\n payload:\n | { syncedAt: string; currentHash: string; backupFilename: string }\n | { error: string; config?: { [p: string]: any }; refresh?: boolean }\n | { cancelled: boolean; message: string },\n ) => {\n closeAllConfirmModals();\n $syncButton.classList.remove('syncing');\n\n if ('cancelled' in payload && payload.cancelled) {\n infoPopup({\n title: 'Sync cancelled',\n content: payload.message,\n type: 'warning',\n });\n } else if ('error' in payload && typeof payload.error !== 'undefined') {\n infoPopup({\n title: 'Sync error',\n content: payload.error,\n type: 'danger',\n });\n\n if (payload.refresh) {\n setTimeout(() => {\n window.location.reload();\n });\n } else {\n $syncButton.disabled = true;\n $syncButton.classList.add('disabled');\n $syncButton.title = 'Sync is unavailable on this instance';\n }\n } else if ('syncedAt' in payload && typeof payload.syncedAt !== 'undefined') {\n infoPopup({\n title: 'Sync success',\n content: `Synced at ${new Date(payload.syncedAt).toLocaleString()}.<br />Backup filename: ${\n payload.backupFilename\n }`,\n type: 'success',\n });\n }\n },\n );\n\n $syncButton.addEventListener('click', (ev: Event) => {\n ev.preventDefault();\n\n $syncButton.classList.add('syncing');\n\n hot.send('template:sync', {});\n });\n }\n}\n"],"names":[],"mappings":"AAGA;;;;;;;;AAQG;AAEH;;;AAGG;AACH,MAAM,kBAAkB,GAAG,cAAc;AAMzC,MAAM,eAAe,GAAG,EAAE;AAE1B,SAAS,mBAAmB,GAAA;IAC1B,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,QAAQ;AAC1C,IAAA,MAAM,UAAU,GAAG,QAAQ,KAAK,QAAQ,GAAG,MAAM,GAAG,KAAK;AAEzD,IAAA,OAAO,GAAG,UAAU,CAAA,EAAA,EAAK,IAAI,CAAA,EAAG,kBAAkB,EAAE;AACtD;SAEgB,qBAAqB,GAAA;AACnC,IAAA,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAwB;;IAEhD,MAAM,MAAM,GAAa,EAAE;IAE3B,IAAI,MAAM,GAAqB,IAAI;IACnC,IAAI,cAAc,GAAyC,IAAI;IAC/D,IAAI,cAAc,GAAG,KAAK;IAC1B,MAAM,mBAAmB,GAAG,MA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AC,CAAC,cAAc,EAAE,CAAA,wBAAA,EAC/D,OAAO,CAAC,cACV,CAAA,CAAE;AACF,oBAAA,IAAI,EAAE,SAAS;AAChB,iBAAA,CAAC;YACJ;AACF,QAAA,CAAC,CACF;QAED,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,EAAS,KAAI;YAClD,EAAE,CAAC,cAAc,EAAE;AAEnB,YAAA,WAAW,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC;AAEpC,YAAA,GAAG,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,CAAC;AAC/B,QAAA,CAAC,CAAC;IACJ;AACF","x_google_ignoreList":[0,1]}
1
+ {"version":3,"file":"client.js","sources":["../../src/client/hot-context.ts","../../src/client/storage.ts","../../src/client/panel-state.ts","../../src/client/panel-position.ts","../../src/client/panel-settings.ts","../../src/client/index.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\nimport type { ViteHotContext } from 'vite/types/hot.js';\n\n/**\n * Minimal `import.meta.hot`-compatible context for environments without Vite HMR\n * (e.g. the `pp-dev next` server). The dev-panel client only uses `hot.on()` and\n * `hot.send()`; this shim implements those over a raw WebSocket using the same\n * custom-event wire shape Vite uses: `{ type: 'custom', event, data }`.\n *\n * Used only as a fallback: when `import.meta.hot` exists (Vite), that is used\n * instead and this code never runs.\n */\n\n/**\n * WebSocket path the pp-dev Next.js server listens on for dev-panel messages.\n * Kept in sync with `PP_DEV_HMR_WS_PATH` in `src/constants.ts` (server side).\n */\nconst PP_DEV_HMR_WS_PATH = '/@pp-dev-hmr';\n\ntype CustomMessage = { type: 'custom'; event: string; data?: unknown };\n\ntype Handler = (payload: any) => void;\n\nconst MAX_OUTBOX_SIZE = 50;\n\nfunction resolveWebSocketUrl(): string {\n const { protocol, host } = window.location;\n const wsProtocol = protocol === 'https:' ? 'wss:' : 'ws:';\n\n return `${wsProtocol}//${host}${PP_DEV_HMR_WS_PATH}`;\n}\n\nexport function createPPDevHotContext(): ViteHotContext {\n const handlers = new Map<string, Set<Handler>>();\n /** Outgoing messages queued while the socket is not OPEN; flushed on connect. */\n const outbox: string[] = [];\n\n let socket: WebSocket | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n let reconnectDelay = 1_000;\n const MAX_RECONNECT_DELAY = 10_000;\n\n const flushOutbox = () => {\n if (!socket || socket.readyState !== WebSocket.OPEN) {\n return;\n }\n\n while (outbox.length > 0) {\n socket.send(outbox.shift()!);\n }\n };\n\n const dispatch = (event: string, data: unknown) => {\n const eventHandlers = handlers.get(event);\n\n if (!eventHandlers) {\n return;\n }\n\n for (const handler of eventHandlers) {\n try {\n handler(data);\n } catch (err) {\n // A failing handler must not break dispatch to the others.\n console.error(`[pp-dev] hot handler for \"${event}\" failed`, err);\n }\n }\n };\n\n const connect = () => {\n try {\n socket = new WebSocket(resolveWebSocketUrl());\n } catch (err) {\n console.error('[pp-dev] failed to open dev-panel WebSocket', err);\n scheduleReconnect();\n\n return;\n }\n\n socket.addEventListener('open', () => {\n reconnectDelay = 1_000;\n flushOutbox();\n });\n\n socket.addEventListener('message', (ev) => {\n let message: CustomMessage;\n\n try {\n message = JSON.parse(typeof ev.data === 'string' ? ev.data : '');\n } catch {\n return;\n }\n\n if (message && message.type === 'custom' && typeof message.event === 'string') {\n dispatch(message.event, message.data);\n }\n });\n\n socket.addEventListener('close', () => {\n socket = null;\n scheduleReconnect();\n });\n\n socket.addEventListener('error', () => {\n // `close` follows `error`; reconnect is scheduled there.\n socket?.close();\n });\n };\n\n const scheduleReconnect = () => {\n if (reconnectTimer) {\n return;\n }\n\n reconnectTimer = setTimeout(() => {\n reconnectTimer = null;\n reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY);\n connect();\n }, reconnectDelay);\n };\n\n connect();\n\n const noop = () => {};\n\n const context: Pick<ViteHotContext, 'on' | 'off' | 'send'> & Partial<ViteHotContext> = {\n on(event, cb) {\n let set = handlers.get(event);\n\n if (!set) {\n set = new Set();\n handlers.set(event, set);\n }\n\n set.add(cb as Handler);\n },\n off(event, cb) {\n handlers.get(event)?.delete(cb as Handler);\n },\n send(event, data) {\n const payload = JSON.stringify({ type: 'custom', event, data } satisfies CustomMessage);\n\n if (socket && socket.readyState === WebSocket.OPEN) {\n socket.send(payload);\n } else {\n if (outbox.length >= MAX_OUTBOX_SIZE) {\n outbox.shift();\n }\n\n outbox.push(payload);\n }\n },\n // Unused by the dev-panel client; provided as no-ops to satisfy the shape.\n accept: noop as ViteHotContext['accept'],\n acceptExports: noop as ViteHotContext['acceptExports'],\n dispose: noop,\n prune: noop,\n invalidate: noop,\n data: {},\n };\n\n return context as ViteHotContext;\n}\n","// localStorage helpers guarded against environments where storage is unavailable\n// (e.g. sandboxed iframes). Keys follow the original `pp-dev-info-closed` naming.\n\nexport const STORAGE_KEYS = {\n closed: 'pp-dev-info-closed',\n position: 'pp-dev-info-position',\n autoHide: 'pp-dev-info-auto-hide',\n hidden: 'pp-dev-info-hidden',\n} as const;\n\nexport function checkLocalStorage() {\n try {\n localStorage.setItem('test', 'test');\n localStorage.removeItem('test');\n\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexport function setStorageItem(key: string, value: string) {\n if (checkLocalStorage()) {\n localStorage.setItem(key, value);\n }\n}\n\nexport function getStorageItem(key: string) {\n if (checkLocalStorage()) {\n return localStorage.getItem(key);\n }\n\n return null;\n}\n\nexport function removeStorageItem(key: string) {\n if (checkLocalStorage()) {\n localStorage.removeItem(key);\n }\n}\n","import { STORAGE_KEYS, getStorageItem, setStorageItem, removeStorageItem } from './storage.js';\n\nexport type Corner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\nexport const CORNERS: readonly Corner[] = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];\n\nexport interface PanelState {\n position: Corner;\n autoHide: boolean;\n hidden: boolean;\n}\n\nexport interface PanelStateController {\n getState(): PanelState;\n setPosition(corner: Corner): void;\n setAutoHide(on: boolean): void;\n setHidden(on: boolean): void;\n /** Clear all persisted overrides and re-resolve from the server-rendered config. */\n reset(): void;\n onChange(cb: (state: PanelState) => void): void;\n}\n\nconst POSITION_CLASS_PREFIX = 'pp-dev-info--';\nconst AUTO_HIDE_CLASS = 'pp-dev-info--auto-hide';\nconst HIDDEN_CLASS = 'pp-dev-info--hidden';\nconst CLOSED_CLASS = 'closed';\nconst NO_TRANSITION_CLASS = 'is-dragging';\n\nexport function isCorner(value: unknown): value is Corner {\n return typeof value === 'string' && (CORNERS as readonly string[]).includes(value);\n}\n\nfunction stateFromDataAttrs($panel: HTMLElement): PanelState {\n return {\n position: isCorner($panel.dataset.position) ? $panel.dataset.position : 'bottom-right',\n autoHide: $panel.dataset.autoHide === 'true',\n hidden: $panel.dataset.hidden === 'true',\n };\n}\n\n/**\n * Resolve the effective panel state. Precedence per setting:\n * localStorage (runtime user choice) → data-* attribute (config) → built-in default.\n * The `?pp-dev-panel=show|hide` URL param writes a persistent localStorage override\n * before resolution, so it both restores a hidden panel and survives reloads.\n */\nexport function resolvePanelState($panel: HTMLElement): PanelState {\n const param = new URLSearchParams(window.location.search).get('pp-dev-panel');\n\n if (param === 'show') {\n setStorageItem(STORAGE_KEYS.hidden, 'false');\n } else if (param === 'hide') {\n setStorageItem(STORAGE_KEYS.hidden, 'true');\n }\n\n const defaults = stateFromDataAttrs($panel);\n\n const storedPosition = getStorageItem(STORAGE_KEYS.position);\n const storedAutoHide = getStorageItem(STORAGE_KEYS.autoHide);\n const storedHidden = getStorageItem(STORAGE_KEYS.hidden);\n\n return {\n position: isCorner(storedPosition) ? storedPosition : defaults.position,\n autoHide: storedAutoHide !== null ? storedAutoHide === 'true' : defaults.autoHide,\n hidden: storedHidden !== null ? storedHidden === 'true' : defaults.hidden,\n };\n}\n\nexport function applyPanelState($panel: HTMLElement, state: PanelState, opts?: { instant?: boolean }): void {\n const apply = () => {\n for (const corner of CORNERS) {\n $panel.classList.toggle(POSITION_CLASS_PREFIX + corner, corner === state.position);\n }\n\n $panel.classList.toggle(AUTO_HIDE_CLASS, state.autoHide);\n $panel.classList.toggle(HIDDEN_CLASS, state.hidden);\n };\n\n if (opts?.instant) {\n // No-transition guard: when localStorage differs from the server-rendered corner,\n // the panel must not visibly slide across the screen on load. `is-dragging`\n // disables transitions; a reflow makes the class swap land before it is removed.\n $panel.classList.add(NO_TRANSITION_CLASS);\n apply();\n void $panel.offsetWidth;\n\n const unlock = () => $panel.classList.remove(NO_TRANSITION_CLASS);\n\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(unlock);\n } else {\n setTimeout(unlock, 0);\n }\n } else {\n apply();\n }\n}\n\nfunction clearClosed($panel: HTMLElement): void {\n $panel.classList.remove(CLOSED_CLASS);\n $panel.querySelector('.pp-dev-info__wrap-btn svg')?.classList.remove(CLOSED_CLASS);\n removeStorageItem(STORAGE_KEYS.closed);\n}\n\nexport function createPanelStateController($panel: HTMLElement): PanelStateController {\n let state = resolvePanelState($panel);\n const listeners: Array<(s: PanelState) => void> = [];\n\n if (state.autoHide) {\n // Auto-hide and minimize are mutually exclusive; a stale persisted `closed`\n // state must not combine with the auto-hide transform.\n clearClosed($panel);\n }\n\n applyPanelState($panel, state, { instant: true });\n\n const commit = () => {\n applyPanelState($panel, state);\n\n for (const cb of listeners) {\n cb(state);\n }\n };\n\n return {\n getState: () => state,\n\n setPosition(corner) {\n state = { ...state, position: corner };\n setStorageItem(STORAGE_KEYS.position, corner);\n commit();\n },\n\n setAutoHide(on) {\n state = { ...state, autoHide: on };\n setStorageItem(STORAGE_KEYS.autoHide, String(on));\n\n if (on) {\n clearClosed($panel);\n }\n\n commit();\n },\n\n setHidden(on) {\n state = { ...state, hidden: on };\n setStorageItem(STORAGE_KEYS.hidden, String(on));\n commit();\n },\n\n reset() {\n removeStorageItem(STORAGE_KEYS.position);\n removeStorageItem(STORAGE_KEYS.autoHide);\n removeStorageItem(STORAGE_KEYS.hidden);\n clearClosed($panel);\n\n // Re-resolve purely from the server-rendered config (bypass the URL param,\n // which would immediately re-write its localStorage override).\n state = stateFromDataAttrs($panel);\n commit();\n },\n\n onChange(cb) {\n listeners.push(cb);\n },\n };\n}\n","import type { Corner } from './panel-state.js';\n\nexport const AUTO_HIDE_SHOW_DELAY = 300;\nexport const AUTO_HIDE_HIDE_DELAY = 500;\n\nconst PEEKING_CLASS = 'is-peeking';\nconst DRAGGING_CLASS = 'is-dragging';\n\n/** Nearest screen corner for a viewport point; ties resolve toward bottom-right. */\nexport function nearestCorner(x: number, y: number, viewportWidth: number, viewportHeight: number): Corner {\n const left = x < viewportWidth / 2;\n const top = y < viewportHeight / 2;\n\n if (top) {\n return left ? 'top-left' : 'top-right';\n }\n\n return left ? 'bottom-left' : 'bottom-right';\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\n/**\n * Drag the panel by its handle and snap to the nearest corner on release.\n * Pointer capture keeps the drag tracking over iframes and outside the window.\n */\nexport function initDrag($panel: HTMLElement, $handle: HTMLElement, onSnap: (corner: Corner) => void): void {\n let dragging = false;\n let pointerId = -1;\n let offsetX = 0;\n let offsetY = 0;\n let panelWidth = 0;\n let panelHeight = 0;\n\n const onKeyDown = (ev: KeyboardEvent) => {\n if (ev.key === 'Escape') {\n stop(false);\n }\n };\n\n const stop = (snap: boolean, ev?: PointerEvent) => {\n if (!dragging) {\n return;\n }\n\n dragging = false;\n\n try {\n $handle.releasePointerCapture(pointerId);\n } catch {\n // pointer already released\n }\n\n document.body.style.userSelect = '';\n document.removeEventListener('keydown', onKeyDown, true);\n\n // Re-enable transitions before clearing the inline placement so the snap animates.\n $panel.classList.remove(DRAGGING_CLASS);\n $panel.style.left = '';\n $panel.style.top = '';\n $panel.style.right = '';\n $panel.style.bottom = '';\n $panel.style.transform = '';\n\n if (snap && ev) {\n onSnap(nearestCorner(ev.clientX, ev.clientY, window.innerWidth, window.innerHeight));\n }\n };\n\n const moveTo = (ev: PointerEvent) => {\n const x = clamp(ev.clientX - offsetX, 0, Math.max(0, window.innerWidth - panelWidth));\n const y = clamp(ev.clientY - offsetY, 0, Math.max(0, window.innerHeight - panelHeight));\n\n $panel.style.transform = `translate3d(${x}px, ${y}px, 0)`;\n };\n\n $handle.addEventListener('pointerdown', (ev: PointerEvent) => {\n if (ev.pointerType === 'mouse' && ev.button !== 0) {\n return;\n }\n\n const rect = $panel.getBoundingClientRect();\n\n dragging = true;\n pointerId = ev.pointerId;\n offsetX = ev.clientX - rect.left;\n offsetY = ev.clientY - rect.top;\n panelWidth = rect.width;\n panelHeight = rect.height;\n\n $handle.setPointerCapture(ev.pointerId);\n $panel.classList.add(DRAGGING_CLASS);\n\n // Anchor to the top-left origin so translate3d coordinates are viewport-absolute;\n // inline styles override the corner-class placement for the duration of the drag.\n $panel.style.left = '0';\n $panel.style.top = '0';\n $panel.style.right = 'auto';\n $panel.style.bottom = 'auto';\n\n moveTo(ev);\n\n document.body.style.userSelect = 'none';\n document.addEventListener('keydown', onKeyDown, true);\n ev.preventDefault();\n });\n\n $handle.addEventListener('pointermove', (ev: PointerEvent) => {\n if (dragging) {\n moveTo(ev);\n }\n });\n\n $handle.addEventListener('pointerup', (ev: PointerEvent) => stop(true, ev));\n $handle.addEventListener('pointercancel', () => stop(false));\n}\n\nexport interface AutoHideHandle {\n /** Force the panel to stay revealed (e.g. while the settings popover is open). */\n keepPeeked(on: boolean): void;\n}\n\n/**\n * Hover-reveal behavior for the auto-hide mode: pointer over the exposed strip for\n * AUTO_HIDE_SHOW_DELAY slides the panel out; leaving re-hides it after a grace period.\n * Keyboard focus inside the panel also keeps it revealed.\n */\nexport function initAutoHide($panel: HTMLElement, isActive: () => boolean): AutoHideHandle {\n let showTimer: number | undefined;\n let hideTimer: number | undefined;\n let popoverOpen = false;\n\n const shouldStayPeeked = () =>\n popoverOpen || $panel.matches(':focus-within') || $panel.classList.contains(DRAGGING_CLASS);\n\n const scheduleHide = () => {\n window.clearTimeout(hideTimer);\n hideTimer = window.setTimeout(() => {\n if (!shouldStayPeeked() && !$panel.matches(':hover')) {\n $panel.classList.remove(PEEKING_CLASS);\n }\n }, AUTO_HIDE_HIDE_DELAY);\n };\n\n $panel.addEventListener('pointerenter', () => {\n if (!isActive()) {\n return;\n }\n\n window.clearTimeout(hideTimer);\n showTimer = window.setTimeout(() => $panel.classList.add(PEEKING_CLASS), AUTO_HIDE_SHOW_DELAY);\n });\n\n $panel.addEventListener('pointerleave', () => {\n if (!isActive()) {\n return;\n }\n\n window.clearTimeout(showTimer);\n scheduleHide();\n });\n\n $panel.addEventListener('focusin', () => {\n if (isActive()) {\n window.clearTimeout(hideTimer);\n $panel.classList.add(PEEKING_CLASS);\n }\n });\n\n $panel.addEventListener('focusout', () => {\n if (isActive()) {\n scheduleHide();\n }\n });\n\n return {\n keepPeeked(on: boolean) {\n popoverOpen = on;\n\n if (!isActive()) {\n return;\n }\n\n if (on) {\n window.clearTimeout(showTimer);\n window.clearTimeout(hideTimer);\n $panel.classList.add(PEEKING_CLASS);\n } else {\n scheduleHide();\n }\n },\n };\n}\n","import type { Corner, PanelStateController } from './panel-state.js';\nimport { CORNERS } from './panel-state.js';\n\nconst CORNER_TITLES: Record<Corner, string> = {\n 'top-left': 'Top left',\n 'top-right': 'Top right',\n 'bottom-left': 'Bottom left',\n 'bottom-right': 'Bottom right',\n};\n\nfunction buildPopover(controller: PanelStateController): HTMLDivElement {\n const state = controller.getState();\n const $popover = document.createElement('div');\n\n $popover.classList.add('pp-dev-info__settings');\n\n const cornerButtons = CORNERS.map((corner) => {\n const active = corner === state.position ? ' active' : '';\n\n return `<button type=\"button\" class=\"pp-dev-info__corner-btn pp-dev-info__corner-btn--${corner}${active}\" data-corner=\"${corner}\" title=\"${CORNER_TITLES[corner]}\" aria-pressed=\"${corner === state.position}\"></button>`;\n }).join('');\n\n $popover.innerHTML = `\n <div class=\"pp-dev-info__settings-title\">Panel settings</div>\n <div class=\"pp-dev-info__settings-row\">\n <span class=\"pp-dev-info__settings-label\">Position</span>\n <div class=\"pp-dev-info__corner-grid\">${cornerButtons}</div>\n </div>\n <div class=\"pp-dev-info__settings-row\">\n <label class=\"pp-dev-info__settings-label\" for=\"pp-dev-auto-hide-toggle\">Auto-hide</label>\n <input\n type=\"checkbox\"\n id=\"pp-dev-auto-hide-toggle\"\n class=\"pp-dev-info__settings-toggle\"\n ${state.autoHide ? 'checked' : ''}\n />\n </div>\n <button type=\"button\" class=\"pp-dev-info__settings-hide-btn\">Hide panel</button>\n <div class=\"pp-dev-info__settings-hint\">Restore with <code>?pp-dev-panel=show</code> in the URL</div>\n <span class=\"pp-dev-info__settings-reset\" role=\"button\" tabindex=\"0\">Reset to config defaults</span>\n `;\n\n return $popover;\n}\n\nfunction syncPopover($popover: HTMLDivElement, controller: PanelStateController): void {\n const state = controller.getState();\n\n $popover.querySelectorAll<HTMLButtonElement>('.pp-dev-info__corner-btn').forEach(($btn) => {\n const active = $btn.dataset.corner === state.position;\n\n $btn.classList.toggle('active', active);\n $btn.setAttribute('aria-pressed', String(active));\n });\n\n const $toggle = $popover.querySelector<HTMLInputElement>('.pp-dev-info__settings-toggle');\n\n if ($toggle) {\n $toggle.checked = state.autoHide;\n }\n}\n\nexport interface PanelSettingsHooks {\n onOpenChange?: (open: boolean) => void;\n}\n\n/** Settings popover: corner picker, auto-hide toggle, hide button, reset. */\nexport function initPanelSettings(\n $panel: HTMLElement,\n controller: PanelStateController,\n hooks?: PanelSettingsHooks,\n): void {\n const $btn = $panel.querySelector<HTMLButtonElement>('.pp-dev-info__settings-btn');\n\n if (!$btn) {\n return;\n }\n\n let $popover: HTMLDivElement | null = null;\n\n const onDocClick = (ev: MouseEvent) => {\n const target = ev.target as Node;\n\n if ($popover && !$popover.contains(target) && !$btn.contains(target)) {\n close();\n }\n };\n\n const onKeyDown = (ev: KeyboardEvent) => {\n if (ev.key === 'Escape') {\n close();\n }\n };\n\n const close = () => {\n if (!$popover) {\n return;\n }\n\n $popover.remove();\n $popover = null;\n document.removeEventListener('click', onDocClick, true);\n document.removeEventListener('keydown', onKeyDown, true);\n hooks?.onOpenChange?.(false);\n };\n\n const open = () => {\n $popover = buildPopover(controller);\n\n $popover.querySelectorAll<HTMLButtonElement>('.pp-dev-info__corner-btn').forEach(($cornerBtn) => {\n $cornerBtn.addEventListener('click', (ev) => {\n ev.preventDefault();\n controller.setPosition($cornerBtn.dataset.corner as Corner);\n });\n });\n\n $popover.querySelector<HTMLInputElement>('.pp-dev-info__settings-toggle')?.addEventListener('change', (ev) => {\n controller.setAutoHide((ev.target as HTMLInputElement).checked);\n });\n\n $popover.querySelector<HTMLButtonElement>('.pp-dev-info__settings-hide-btn')?.addEventListener('click', (ev) => {\n ev.preventDefault();\n close();\n controller.setHidden(true);\n });\n\n const $reset = $popover.querySelector<HTMLElement>('.pp-dev-info__settings-reset');\n\n $reset?.addEventListener('click', (ev) => {\n ev.preventDefault();\n controller.reset();\n });\n $reset?.addEventListener('keydown', (ev: KeyboardEvent) => {\n if (ev.key === 'Enter' || ev.key === ' ') {\n ev.preventDefault();\n controller.reset();\n }\n });\n\n $panel.appendChild($popover);\n document.addEventListener('click', onDocClick, true);\n document.addEventListener('keydown', onKeyDown, true);\n hooks?.onOpenChange?.(true);\n };\n\n $btn.addEventListener('click', (ev) => {\n ev.preventDefault();\n\n if ($popover) {\n close();\n } else {\n open();\n }\n });\n\n controller.onChange(() => {\n if ($popover) {\n syncPopover($popover, controller);\n }\n });\n}\n","/// <reference types=\"vite/client\" />\nimport './assets/css/client.scss';\nimport './index.html';\nimport { createPPDevHotContext } from './hot-context.js';\nimport { STORAGE_KEYS, getStorageItem, setStorageItem } from './storage.js';\nimport { createPanelStateController, type PanelStateController } from './panel-state.js';\nimport { initDrag, initAutoHide } from './panel-position.js';\nimport { initPanelSettings } from './panel-settings.js';\n\ninterface InfoPopupOptions {\n title: string;\n content: string;\n style?: string;\n className?: string;\n duration?: number;\n onClose?: () => void;\n type?: 'success' | 'danger' | 'info' | 'warning';\n}\n\ninterface SyncActionRequiredPayload {\n requestId: string;\n title: string;\n content: string;\n confirmText: string;\n cancelText: string;\n}\n\ninterface ConfirmModalOptions {\n title: string;\n content: string;\n confirmText: string;\n cancelText: string;\n}\n\nlet activePopups = 0;\nconst POPUP_OFFSET = 10;\nconst POPUP_HEIGHT = 100;\nconst ANIMATION_DURATION = 300;\nconst CONFIRM_MODAL_OVERLAY_CLASS = 'pp-dev-info__confirm-overlay';\n\nconst activeConfirmModals = new Map<\n HTMLDivElement,\n { resolve: (value: boolean) => void; onKeyDown: (event: KeyboardEvent) => void }\n>();\n\nconst ICON_SIZE = 16;\nconst CLOSE_ICON_SIZE = 12;\n\nfunction teardownConfirmModal(overlay: HTMLDivElement, result: boolean) {\n const entry = activeConfirmModals.get(overlay);\n\n if (!entry) {\n return;\n }\n\n document.removeEventListener('keydown', entry.onKeyDown);\n\n activeConfirmModals.delete(overlay);\n overlay.remove();\n entry.resolve(result);\n}\n\nconst TYPE_ICONS: Record<NonNullable<InfoPopupOptions['type']>, string> = {\n success: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"m9 12 2 2 4-4\"/></svg>`,\n danger: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 8v4\"/><path d=\"M12 16h.01\"/></svg>`,\n warning: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z\"/><path d=\"M12 9v4\"/><path d=\"M12 17h.01\"/></svg>`,\n info: `<svg viewBox=\"0 0 24 24\" width=\"${ICON_SIZE}\" height=\"${ICON_SIZE}\" stroke=\"currentColor\" stroke-width=\"1.5\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 16v-4\"/><path d=\"M12 8h.01\"/></svg>`,\n};\n\nfunction createPopupElement(opts: InfoPopupOptions): HTMLDivElement {\n const $popup = document.createElement('div');\n\n $popup.classList.add('pp-dev-info-namespace');\n\n const typeClass = opts.type ? `pp-dev-info__popup--${opts.type}` : '';\n const iconHtml = opts.type ? `<div class=\"pp-dev-info__popup-title-icon\">${TYPE_ICONS[opts.type]}</div>` : '';\n\n const template = `\n <div class=\"pp-dev-info__popup ${typeClass} ${opts.className || ''}\" style=\"${opts.style || ''}\">\n <div class=\"pp-dev-info__popup-title\">\n ${iconHtml}\n <div class=\"pp-dev-info__popup-title-text\">${opts.title}</div>\n <div class=\"pp-dev-info__popup-title-close\">\n <svg\n viewBox=\"0 0 24 24\"\n width=\"${CLOSE_ICON_SIZE}\"\n height=\"${CLOSE_ICON_SIZE}\"\n stroke=\"currentColor\"\n stroke-width=\"1.5\"\n fill=\"none\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n >\n <path d=\"M18 6L6 18\"></path>\n <path d=\"M6 6l12 12\"></path>\n </svg>\n </div>\n </div>\n <div class=\"pp-dev-info__popup-content\">${opts.content}</div>\n </div>\n `;\n\n $popup.innerHTML = template;\n\n return $popup;\n}\n\nlet panelController: PanelStateController | null = null;\n\nfunction updatePopupPositions() {\n const popups = document.querySelectorAll<HTMLElement>('.pp-dev-info-namespace:not(.pp-dev-info)');\n const position = panelController?.getState().position ?? 'bottom-right';\n const isLeft = position === 'top-left' || position === 'bottom-left';\n const isTop = position === 'top-left' || position === 'top-right';\n\n // Anchor popups to the panel's horizontal side and stack them from the vertically\n // opposite edge so they never cover the panel.\n popups.forEach((popup, index: number) => {\n const offset = POPUP_OFFSET + index * (POPUP_HEIGHT + POPUP_OFFSET);\n const $popupContent = popup.querySelector<HTMLElement>('.pp-dev-info__popup');\n\n if (!$popupContent) {\n return;\n }\n\n $popupContent.classList.toggle('pp-dev-info__popup--left', isLeft);\n\n if (isTop) {\n $popupContent.style.top = 'auto';\n $popupContent.style.bottom = `${offset}px`;\n } else {\n $popupContent.style.bottom = 'auto';\n $popupContent.style.top = `${offset}px`;\n }\n });\n}\n\nfunction animatePopup($popup: HTMLDivElement, type: 'enter' | 'exit') {\n return new Promise<void>((resolve) => {\n const $popupContent = $popup.querySelector('.pp-dev-info__popup');\n\n if (!$popupContent) {\n return resolve();\n }\n\n if (type === 'enter') {\n $popupContent.classList.add('entering');\n\n requestAnimationFrame(() => {\n $popupContent.classList.remove('entering');\n\n resolve();\n });\n } else {\n $popupContent.classList.add('exiting');\n\n setTimeout(() => {\n $popupContent.classList.remove('exiting');\n\n resolve();\n }, ANIMATION_DURATION);\n }\n });\n}\n\nfunction infoPopup(opts: InfoPopupOptions) {\n const $popup = createPopupElement(opts);\n const $closeButton = $popup.querySelector('.pp-dev-info__popup-title-close');\n\n const removePopup = async () => {\n await animatePopup($popup, 'exit');\n\n $popup.remove();\n\n activePopups--;\n\n updatePopupPositions();\n\n opts.onClose?.();\n };\n\n $closeButton?.addEventListener('click', removePopup);\n document.body.appendChild($popup);\n\n // Position the popup\n activePopups++;\n updatePopupPositions();\n\n // Animate entrance\n animatePopup($popup, 'enter');\n\n const duration = opts.duration ?? 10000;\n\n if (duration > 0) {\n let remainingTime = duration;\n let lastUpdate = Date.now();\n let isVisible = true;\n\n const scheduleDismiss = () => {\n if (!isVisible) {\n return;\n }\n\n const now = Date.now();\n const elapsed = now - lastUpdate;\n\n remainingTime -= elapsed;\n lastUpdate = now;\n\n if (remainingTime <= 0) {\n removePopup();\n\n return;\n }\n\n requestAnimationFrame(scheduleDismiss);\n };\n\n // Handle visibility change\n document.addEventListener('visibilitychange', () => {\n isVisible = !document.hidden;\n\n if (isVisible) {\n lastUpdate = Date.now();\n requestAnimationFrame(scheduleDismiss);\n }\n });\n\n requestAnimationFrame(scheduleDismiss);\n }\n}\n\nfunction closeAllConfirmModals() {\n for (const overlay of [...activeConfirmModals.keys()]) {\n teardownConfirmModal(overlay, false);\n }\n}\n\nfunction confirmModal(opts: ConfirmModalOptions): Promise<boolean> {\n closeAllConfirmModals();\n\n return new Promise<boolean>((resolve) => {\n const $overlay = document.createElement('div');\n\n $overlay.classList.add('pp-dev-info-namespace', CONFIRM_MODAL_OVERLAY_CLASS);\n\n const $confirm = document.createElement('div');\n\n $confirm.classList.add('pp-dev-info__confirm');\n\n const $title = document.createElement('div');\n\n $title.classList.add('pp-dev-info__confirm-title');\n $title.textContent = opts.title;\n\n const $content = document.createElement('div');\n\n $content.classList.add('pp-dev-info__confirm-content');\n $content.textContent = opts.content;\n\n const $actions = document.createElement('div');\n\n $actions.classList.add('pp-dev-info__confirm-actions');\n\n const $cancelButton = document.createElement('button');\n\n $cancelButton.type = 'button';\n $cancelButton.classList.add('pp-dev-info__confirm-btn', 'pp-dev-info__confirm-btn--cancel');\n $cancelButton.textContent = opts.cancelText;\n\n const $confirmButton = document.createElement('button');\n\n $confirmButton.type = 'button';\n $confirmButton.classList.add('pp-dev-info__confirm-btn', 'pp-dev-info__confirm-btn--confirm');\n $confirmButton.textContent = opts.confirmText;\n\n $actions.append($cancelButton, $confirmButton);\n $confirm.append($title, $content, $actions);\n $overlay.appendChild($confirm);\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n teardownConfirmModal($overlay, false);\n }\n };\n\n activeConfirmModals.set($overlay, { resolve, onKeyDown });\n\n $confirmButton.addEventListener('click', () => {\n teardownConfirmModal($overlay, true);\n });\n\n $cancelButton.addEventListener('click', () => {\n teardownConfirmModal($overlay, false);\n });\n\n $overlay.addEventListener('click', (event) => {\n if (event.target === $overlay) {\n teardownConfirmModal($overlay, false);\n }\n });\n\n document.addEventListener('keydown', onKeyDown);\n document.body.appendChild($overlay);\n });\n}\n\n// ── Inspector console banner ──────────────────────────────────────────────────\n// Logged once on page load so it is visible in DevTools history when the console\n// is opened. The message is harmless if the inspector is disabled.\n(function printInspectorBanner() {\n const url = window.location.origin + '/@pp-dev/inspector';\n\n console.log(\n '%cpp-dev%c 🔍 Request Inspector → %c%s',\n 'background:#6e8efb;color:#fff;padding:2px 8px;border-radius:4px;font-weight:700;font-size:11px',\n 'color:#a0a0b8;font-size:11px',\n 'color:#a78bfa;font-size:11px;text-decoration:underline',\n url,\n );\n})();\n\n// ── Panel UI: position, auto-hide, hide, minimize ─────────────────────────────\n// Initialized outside the hot-context guard — panel placement and visibility must\n// not depend on the WebSocket transport being available.\nconst CLOSED_CLASS = 'closed';\n\nconst $infoPanel = document.querySelector<HTMLElement>('.pp-dev-info');\n\nif ($infoPanel) {\n panelController = createPanelStateController($infoPanel);\n\n const $dragHandle = $infoPanel.querySelector<HTMLElement>('.pp-dev-info__drag-handle');\n\n if ($dragHandle) {\n initDrag($infoPanel, $dragHandle, (corner) => panelController!.setPosition(corner));\n }\n\n const autoHide = initAutoHide($infoPanel, () => panelController!.getState().autoHide);\n\n initPanelSettings($infoPanel, panelController, {\n onOpenChange: (open) => autoHide.keepPeeked(open),\n });\n\n panelController.onChange((state) => {\n if (!state.autoHide) {\n $infoPanel.classList.remove('is-peeking');\n }\n\n updatePopupPositions();\n });\n\n // Minimize button; in auto-hide mode it acts as \"pin\" (disables auto-hide).\n const $minimizeButtonWrap = $infoPanel.querySelector<HTMLElement>('.pp-dev-info__wrap-btn');\n const $minimizeButtonSVG = $minimizeButtonWrap?.querySelector('svg');\n\n if ($minimizeButtonWrap && $minimizeButtonSVG) {\n let isClosed = getStorageItem(STORAGE_KEYS.closed) === 'true' && !panelController.getState().autoHide;\n\n const updateTitle = () => {\n $minimizeButtonWrap.title = panelController!.getState().autoHide ? 'Pin panel' : 'Minimize';\n };\n\n updateTitle();\n panelController.onChange(updateTitle);\n\n if (isClosed) {\n $infoPanel.classList.add(CLOSED_CLASS);\n $minimizeButtonSVG.classList.add(CLOSED_CLASS);\n }\n\n $minimizeButtonWrap.addEventListener('click', (e: Event) => {\n e.preventDefault();\n\n if (panelController!.getState().autoHide) {\n isClosed = false;\n panelController!.setAutoHide(false);\n\n return;\n }\n\n $infoPanel.classList.toggle(CLOSED_CLASS);\n $minimizeButtonSVG.classList.toggle(CLOSED_CLASS);\n\n isClosed = !isClosed;\n\n setStorageItem(STORAGE_KEYS.closed, isClosed ? 'true' : 'false');\n });\n }\n}\n\n// Use Vite's HMR context when available; otherwise fall back to a raw-WebSocket\n// shim so the dev panel also works under the `pp-dev next` server (no Vite HMR).\nconst hot = import.meta.hot ?? createPPDevHotContext();\n\nif (hot) {\n hot.on('redirect', (data: { url: string }) => {\n window.location.href = data.url;\n });\n\n hot.on('client:config:update', (data: { config: { [key: string]: any } }) => {\n if (typeof data.config?.canSync === 'boolean') {\n if (data.config.canSync) {\n const $syncButton = document.getElementById('sync-template') as HTMLButtonElement | null;\n\n if ($syncButton) {\n $syncButton.disabled = false;\n $syncButton.classList.remove('disabled');\n $syncButton.title = 'Sync template';\n }\n } else {\n const $syncButton = document.getElementById('sync-template') as HTMLButtonElement | null;\n\n if ($syncButton) {\n $syncButton.disabled = true;\n $syncButton.classList.add('disabled');\n $syncButton.title = 'Sync is unavailable on this instance';\n }\n }\n }\n });\n\n const $syncButton = document.getElementById('sync-template') as HTMLButtonElement | null;\n\n if ($syncButton) {\n hot.on('template:sync:action-required', async (payload: SyncActionRequiredPayload) => {\n // Keep the sync spinner running while a confirmation modal is shown — the sync\n // process is still in progress and only ends on `template:sync:response`.\n const approved = await confirmModal({\n title: payload.title,\n content: payload.content,\n confirmText: payload.confirmText,\n cancelText: payload.cancelText,\n });\n\n hot.send('template:sync:action-response', {\n requestId: payload.requestId,\n approved,\n });\n });\n\n hot.on(\n 'template:sync:response',\n (\n payload:\n | { syncedAt: string; currentHash: string; backupFilename: string }\n | { error: string; config?: { [p: string]: any }; refresh?: boolean }\n | { cancelled: boolean; message: string },\n ) => {\n closeAllConfirmModals();\n $syncButton.classList.remove('syncing');\n\n if ('cancelled' in payload && payload.cancelled) {\n infoPopup({\n title: 'Sync cancelled',\n content: payload.message,\n type: 'warning',\n });\n } else if ('error' in payload && typeof payload.error !== 'undefined') {\n infoPopup({\n title: 'Sync error',\n content: payload.error,\n type: 'danger',\n });\n\n if (payload.refresh) {\n setTimeout(() => {\n window.location.reload();\n });\n } else {\n $syncButton.disabled = true;\n $syncButton.classList.add('disabled');\n $syncButton.title = 'Sync is unavailable on this instance';\n }\n } else if ('syncedAt' in payload && typeof payload.syncedAt !== 'undefined') {\n infoPopup({\n title: 'Sync success',\n content: `Synced at ${new Date(payload.syncedAt).toLocaleString()}.<br />Backup filename: ${\n payload.backupFilename\n }`,\n type: 'success',\n });\n }\n },\n );\n\n $syncButton.addEventListener('click', (ev: Event) => {\n ev.preventDefault();\n\n $syncButton.classList.add('syncing');\n\n hot.send('template:sync', {});\n });\n }\n}\n"],"names":["CLOSED_CLASS"],"mappings":"AAGA;;;;;;;;AAQG;AAEH;;;AAGG;AACH,MAAM,kBAAkB,GAAG,cAAc;AAMzC,MAAM,eAAe,GAAG,EAAE;AAE1B,SAAS,mBAAmB,GAAA;IAC1B,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,QAAQ;AAC1C,IAAA,MAAM,UAAU,GAAG,QAAQ,KAAK,QAAQ,GAAG,MAAM,GAAG,KAAK;AAEzD,IAAA,OAAO,GAAG,UAAU,CAAA,EAAA,EAAK,IAAI,CAAA,EAAG,kBAAkB,EAAE;AACtD;SAEgB,qBAAqB,GAAA;AACnC,IAAA,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAwB;;IAEhD,MAAM,MAAM,GAAa,EAAE;IAE3B,IAAI,MAAM,GAAqB,IAAI;IACnC,IAAI,cAAc,GAAyC,IAAI;IAC/D,IAAI,c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AAI,OAAO,OAAO,CAAC,QAAQ,KAAK,WAAW,EAAE;AAC3E,gBAAA,SAAS,CAAC;AACR,oBAAA,KAAK,EAAE,cAAc;AACrB,oBAAA,OAAO,EAAE,CAAA,UAAA,EAAa,IAAI,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,cAAc,EAAE,CAAA,wBAAA,EAC/D,OAAO,CAAC,cACV,CAAA,CAAE;AACF,oBAAA,IAAI,EAAE,SAAS;AAChB,iBAAA,CAAC;YACJ;AACF,QAAA,CAAC,CACF;QAED,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,EAAS,KAAI;YAClD,EAAE,CAAC,cAAc,EAAE;AAEnB,YAAA,WAAW,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC;AAEpC,YAAA,GAAG,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,CAAC;AAC/B,QAAA,CAAC,CAAC;IACJ;AACF","x_google_ignoreList":[0,1,2,3,4,5]}
@@ -1,5 +1,10 @@
1
1
  {%# This is EJS template. Parameters: openDelimiter: "{", closeDelimiter="}" %}
2
- <div class="pp-dev-info-namespace pp-dev-info">
2
+ <div
3
+ class="pp-dev-info-namespace pp-dev-info pp-dev-info--{%= devPanelPosition %}{% if (devPanelAutoHide) { %} pp-dev-info--auto-hide{% } %}{% if (devPanelHidden) { %} pp-dev-info--hidden{% } %}"
4
+ data-position="{%= devPanelPosition %}"
5
+ data-auto-hide="{%= devPanelAutoHide %}"
6
+ data-hidden="{%= devPanelHidden %}"
7
+ >
3
8
  <div class="pp-dev-info__wrap-btn">
4
9
  <svg
5
10
  class="pp-dev-info__wrap-btn-arrow"
@@ -16,6 +21,17 @@
16
21
  </svg>
17
22
  </div>
18
23
 
24
+ <div class="pp-dev-info__drag-handle" title="Drag to move">
25
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="14" height="14">
26
+ <circle cx="9" cy="5" r="1.5"></circle>
27
+ <circle cx="15" cy="5" r="1.5"></circle>
28
+ <circle cx="9" cy="12" r="1.5"></circle>
29
+ <circle cx="15" cy="12" r="1.5"></circle>
30
+ <circle cx="9" cy="19" r="1.5"></circle>
31
+ <circle cx="15" cy="19" r="1.5"></circle>
32
+ </svg>
33
+ </div>
34
+
19
35
  <div class="pp-dev-info__content">
20
36
  <div class="pp-dev-info__section">
21
37
  <span class="pp-dev-info__item">
@@ -54,7 +70,7 @@
54
70
  {% if (backendBaseURL && !Number.isNaN(+appId)) { %}
55
71
  <div class="pp-dev-info__section">
56
72
  <span class="pp-dev-info__item">
57
- <span class="pp-dev-info__label">Portal page ID:</span>
73
+ <span class="pp-dev-info__label">App ID:</span>
58
74
  <a href="!!{%= backendBaseURL %}/admin/page/edit/id/{%= appId %}" target="_blank" class="pp-dev-info__link"
59
75
  >{%= appId %}</a
60
76
  >
@@ -84,4 +100,24 @@
84
100
  </svg>
85
101
  </button>
86
102
  {% } %}
103
+
104
+ <span class="pp-dev-info__sep" aria-hidden="true"></span>
105
+ <button class="pp-dev-info__settings-btn" title="Panel settings">
106
+ <svg
107
+ fill="none"
108
+ width="16px"
109
+ height="16px"
110
+ viewBox="0 0 24 24"
111
+ stroke="currentColor"
112
+ stroke-width="1.5"
113
+ stroke-linecap="round"
114
+ stroke-linejoin="round"
115
+ xmlns="http://www.w3.org/2000/svg"
116
+ >
117
+ <circle cx="12" cy="12" r="3"></circle>
118
+ <path
119
+ d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"
120
+ ></path>
121
+ </svg>
122
+ </button>
87
123
  </div>
package/dist/esm/cli.js CHANGED
@@ -1,2 +1,2 @@
1
- import*as e from"path";import*as t from"fs";import{EventEmitter as o}from"node:events";import{performance as n}from"node:perf_hooks";import{watch as i}from"chokidar";import{cac as s}from"cac";import{loadConfigFromFile as r,mergeConfig as a,build as l,resolveConfig as c,optimizeDeps as d,preview as p,loadEnv as f}from"vite";import{c as h,a as u,P as g,b as m,V as b,I as w,v as y,n as v,d as x,e as P,f as S,R as T,r as k,i as $,g as L,M as j,h as F,j as E,k as C,l as A,m as D,u as I,D as N,C as _}from"./plugin-Dvva-sxE.js";import{g as M,s as R,c as H,i as z}from"./index-C7dYPskY.js";import{parse as U}from"url";import*as W from"dir-compare";import O from"diff-match-patch";import{isBinaryFile as G}from"isbinaryfile";import*as B from"os";import*as V from"crypto";import q from"extract-zip";import Z from"svgtofont";import{WebSocketServer as J,WebSocket as K}from"ws";import"http-proxy-middleware";import"picocolors";import"axios";import"node:http";import"node:https";import"jsdom";import"process";import"child_process";import"module";import"jszip";import"memory-cache";import"zlib";import"express";import"node:crypto";import"./helpers.js";import"ejs";function X(e){return null!=e&&!1!==e}let Y=null;const Q=[{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 ee=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class te{oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(t){const{oldAssetsPath:o,newAssetsPath:n,destinationPath:i,changelogTemplate:s,diffFileTemplateHandler:r,diffLineTemplateHandler:a,changelogFilename:l,contextLines:c}=t;if(this.logger=h(),!o||!n||!i)throw new Error("Previous assets path, current assets path and destination path are required");if(o===n)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(n))throw new Error(`Current assets path ${n} does not exist`);if(this.isZipFile(o)){const t=e.resolve(B.tmpdir(),V.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,t).then(()=>this.normalizeAssetFolderPath(t)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(n)){const t=e.resolve(B.tmpdir(),V.createHash("md5").update(n).digest("hex"));this.newAssetsPath=this.unzipFile(n,t).then(()=>this.normalizeAssetFolderPath(t)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(n))throw new Error(`Invalid current assets path ${n}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(n);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${n} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=i,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",s&&(this.templateIsValid(s)?this.changelogTemplate=s:this.logger.warn(u.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof a&&(this.diffLineTemplateHandler=a),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return t.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return t.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===t.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){t.existsSync(e)||t.mkdirSync(e,{recursive:!0})}async unzipFile(e,o){return t.rmSync(o,{force:!0,recursive:!0}),q(e,{dir:o})}normalizeAssetFolderPath(o){const n=t.readdirSync(o);return 1===n.length&&t.lstatSync(e.join(o,n[0])).isDirectory()?this.normalizeAssetFolderPath(e.join(o,n[0])):o}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const t=e.filter((e,t,o)=>0!==e.lineType||(t>=0&&t<this.contextLines||t>o.length-(this.contextLines+1)&&t<=o.length-1||o.slice(t-this.contextLines,t+this.contextLines+1).some(e=>0!==e.lineType))).map((e,t,o)=>{if(t>0){const n=o[t-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]}).flat().map(e=>this.diffLineHTML(e)).join("");return this.diffTableTemplate(t)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:t,lineContent:o,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${s=o??"",s.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var s}diffLineHTML(e){if(this.diffLineTemplateHandler)return this.diffLineTemplateHandler(e);const{lineNumber:t}=e;return-1===t?this.diffLineSkipTemplate():this.diffLineTemplate(e)}diffFileTemplate(e,t){return this.diffFileTemplateHandler?this.diffFileTemplateHandler(e,t):`<div class="diff-file">\n <div class="diff-file-title">${e}</div>\n <div class="diff-file-content">${t}</div>\n </div>`}async generateAssetFoldersDiff(){this.logger.info(u.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await W.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(ee.test(e)&&(e=e.replace(ee,"$1$3")),ee.test(t)&&(t=t.replace(ee,"$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 O,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let s=0;return i.map(e=>{const[t,o]=e,n=o.endsWith("\n")?o.split("\n").length-1:o.split("\n").length,i=o.split("\n").map((e,o)=>({lineContent:e,lineNumber:s+o+1,lineType:t})).slice(0,n);return-1!==t&&(s+=n),i}).flat()}async generateFilesDiff(o){if("equal"===o.state){const t=this.pathToPosix(e.join(".",o.relativePath,o.name1??"")),n=this.pathToPosix(e.join(".",o.relativePath,o.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${n}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const n=o.path1&&o.name1?e.join(o.path1,o.name1):null,i=o.path2&&o.name2?e.join(o.path2,o.name2):null,s=this.pathToPosix(e.join(".",o.relativePath,(o.name1||o.name2)??""));if("left"===o.state&&n)return this.diffFileTemplate(`<span class="removed">Removed ${s}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===o.state&&i)return this.diffFileTemplate(`<span class="added">Added ${s}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===o.state&&n&&i){const r=this.pathToPosix(e.join(".",o.relativePath,o.name1??"")),a=this.pathToPosix(e.join(".",o.relativePath,o.name2??"")),l=o.name1!==o.name2?`<span class="renamed"\n >Renamed <span class="from">${r}</span> -> <span class="to">${a}</span></span\n >`:s;return this.diffFileTemplate(l,await G(n)||await G(i)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(t.readFileSync(n,"utf-8"),t.readFileSync(i,"utf-8"))))}return""}async generateChangelog(){this.logger.info(u.green("Generating changelog"));const o=await this.generateAssetFoldersDiff(),n=(await Promise.all(o.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(u.green("Writing changelog file"));const i=this.changelogTemplate.split("%FILES%");i.splice(1,0,n);const s=i.join("");t.writeFileSync(e.join(this.destinationPath,this.changelogFilename),s),this.logger.info(u.green(`Changelog file written to ${e.join(this.destinationPath,this.changelogFilename)}`))}}class oe{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await Z({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class ne{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new J({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===K.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===g&&(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){h().error(`ws handler for "${o.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===K.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 ie=s("pp-dev");function se(t,o,n){const s=[...m,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"].map(o=>e.join(t,o)),r=i(s,{ignored:t=>{const o=e.basename(t);return/(^|[\/\\])\../.test(t)&&!o.startsWith(".env")&&!o.startsWith(".pp-dev")&&!o.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let a=null;return r.on("change",i=>{n(u.blue(`🔧 Config file changed: ${e.relative(t,i)}`)),a&&clearTimeout(a),a=setTimeout(async()=>{try{n(u.yellow("🔄 Restarting dev server due to config change...")),await o()}catch(e){n(u.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{n(u.red(`❌ Config watcher error: ${e}`))}),{watcher:r,restartCallback:o,logger:n}}function re(e){e.watcher&&e.watcher.close()}function ae(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 le=global.__pp_dev_profile_session,ce=0;const de=o=>{if(le)return new Promise((n,i)=>{le.post("Profiler.stop",(s,{profile:r})=>{if(s)i(s);else{const i=e.resolve(`./pp-dev-profile-${ce++}.cpuprofile`);t.writeFileSync(i,JSON.stringify(r)),o(u.yellow(`CPU profile written to ${u.white(u.dim(i))}`)),le=void 0,n()}})})},pe=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function fe(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}ie.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"),ie.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(t,o)=>{pe(o);let i=null,s=null,l=!1;const c=t?e.resolve(process.cwd(),t):process.cwd(),d=h(o.logLevel),p=async()=>{if(!l){l=!0;try{i&&(d.info(u.yellow("🛑 Stopping existing dev server...")),await i.close(),i=null);const{clearConfigCache:e,getConfig:g}=await import("./index-C7dYPskY.js").then(e=>e.e);e();const{createServer:m}=await import("vite"),y=await r({mode:o.mode||"development",command:"serve"},o.config,t,o.logLevel);let v=await M();const x=f(o.mode||"development",t??process.cwd(),"");if(x&&Object.keys(x).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=x[e])}),y){const{plugins:e,...t}=y.config;v=a(v,t)}if(i=await m(a(v,{root:t,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:fe(o),customLogger:d},!0)),!i.config.base||"/"===i.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!i.httpServer)throw new Error("HTTP server not available");await i.listen();const P=global.__pp_dev_start_time??!1,S=P?u.dim(`ready in ${u.reset(u.bold(Math.ceil(n.now()-P)))} ms`):"";d.info(`\n ${u.green(`${u.bold("PP-DEV")} v${b}`)} ${S}\n`),i.printUrls();const T=await g();if(!1!==T.inspector?.enabled){const e=i.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${i.config.server.port??5173}`;d.info(`\n ${u.cyan("🔍 Request Inspector")} ${u.dim(t+w)}\n`)}!function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=h();t.print&&o.info(u.dim(u.green(" ➜"))+u.dim(" press ")+u.bold("h")+u.dim(" to show help"));const n=(t.customShortcuts??[]).filter(X).concat(Q);Y?.(),Y=null;let i=!1;const s=process.stdin.isPaused(),r=process.stdin,a=Boolean(r.isRaw),l=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(["",u.bold(" Shortcuts"),...n.map(e=>u.dim(" press ")+u.bold(e.key)+u.dim(` to ${e.description}`))].join("\n"));const s=n.find(e=>e.key===t);s&&(i=!0,await s.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",l).setEncoding("utf8").resume();const c=e.httpServer,d=()=>{Y===d&&(c.removeListener("close",d),process.stdin.off("data",l),a||process.stdin.setRawMode(!1),s&&process.stdin.pause(),Y=null)};Y=d,c.on("close",d)}(i,{print:!0,customShortcuts:[...le?[{key:"p",description:"start/stop the profiler",async action(e){if(le)await de(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{le=new e.Session,le.connect(),le.post("Profiler.enable",()=>{le?.post("Profiler.start",()=>{d.info("Profiler started"),t()})})})}}}]:[],{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),s||(s=se(c,p,d.info),d.info(u.blue("🔧 Config file watcher started"))),l=!1}catch(e){l=!1,d.error(u.red(`error when starting dev server:\n${e.stack}`),{error:e}),de(d.info),process.exit(1)}}},g=async e=>{d.info(u.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{s&&(re(s),s=null),i&&(await i.close(),i=null),de(d.info),d.info(u.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(u.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM")),process.on("uncaughtException",e=>{d.error(u.red(`❌ Uncaught Exception: ${e}`)),g("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(u.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),g("unhandledRejection")}),await p()}),ie.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(n,i)=>{pe(i);let s=null,r=null,a=null,l=null,c=!1;const d=h(),p=async()=>{if(!c){c=!0;try{const{next:g,constants:m}=await R(),{PHASE_DEVELOPMENT_SERVER:b}=m;a&&(await a.close(),a=null),r&&(d.info(u.yellow("🛑 Stopping existing Next.js server...")),await new Promise(e=>{r.close(()=>{r=null,e()})})),s&&"function"==typeof s.close&&(await s.close(),s=null);const{clearConfigCache:M}=await import("./index-C7dYPskY.js").then(e=>e.e);M();const{join:W,basename:O}=await import("path"),{createServer:G}=await import("http"),B=await import("next/dist/server/config.js"),V=B.default.default||B["module.exports"].default||B.default,q=fe(i),Z=f(i.mode||"development",n??process.cwd(),"");Z&&Object.keys(Z).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=Z[e])});const J=n?W(process.cwd(),n):process.cwd();d.info(J);const K=await V(b,J);let X=K?.ppDev||{};if(0===Object.keys(X).length)try{const{getConfig:e}=await import("./index-C7dYPskY.js").then(e=>e.e),t=await e();Object.keys(t).length>0?(X=t,d.info(u.blue("🔧 Loaded pp-dev config from standalone config file"))):d.info(u.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){d.info(u.yellow("⚠️ Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else d.info(u.blue("🔧 Loaded pp-dev config from Next.js config"));let Y=null;try{const{getPkg:e}=await import("./index-C7dYPskY.js").then(e=>e.e);Y=e().name}catch{Y=O(J)}y(X,Y??"");const Q=v(X,Y??""),ee=Q.backendBaseURL??"http://localhost:8080",te=Q.templateLess,oe=Q.v7Features,ie=Q.disableSSLValidation,le=Q.enableProxyCache,ce=Q.proxyCacheTTL,de=Q.personalAccessToken,pe=Q.miHudLess,he=Q.inspectorEnabled,ue=Q.inspectorMaxMemory,ge=Q.inspectorCaptureLimit,me=Q.appId??(process.env.MI_APP_ID&&parseInt(process.env.MI_APP_ID,10)||void 0)??(process.env.MI_PORTAL_PAGE_ID&&parseInt(process.env.MI_PORTAL_PAGE_ID,10)||void 0)??1,be=K?.basePath;let we="";be?we=be:(we=te?x:oe?P:S,we+=`/${Y}`);const ye=function(e){const t="1"===process.env.PP_DEV_NEXT_WEBPACK||"true"===process.env.PP_DEV_NEXT_WEBPACK;if(t&&(e.webpack||e.turbopack))throw new Error("Do not combine PP_DEV_NEXT_WEBPACK with --webpack or --turbopack");if(t)return{webpack:!0};if(e.webpack&&e.turbopack)throw new Error("Use only one of --webpack or --turbopack");return e.webpack?{webpack:!0}:e.turbopack?{turbopack:!0}:{}}(i),ve=async e=>{delete process.env.TURBOPACK,s&&"function"==typeof s.close&&(await s.close(),s=null);const t={dev:!0,customServer:!0,hostname:q.host||"localhost",port:q.port,dir:J,conf:{...K,basePath:we,assetPrefix:we}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),s=g(t),await s.prepare()};if(ye.webpack)await ve({webpack:!0});else if(ye.turbopack)try{await ve({turbopack:!0})}catch(e){if(!ae(e))throw e;d.warn(u.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await ve({webpack:!0})}else try{await ve({})}catch(e){if(!ae(e))throw e;d.warn(u.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await ve({webpack:!0})}if(!s)throw new Error("Next.js app failed to initialize");if(we.endsWith("/")||(we+="/"),"/"===we)throw new Error('basePath cannot be equal to "/" or equal to empty string');d.info(u.green("✅ Next.js app prepared successfully")),d.info(u.blue(`🔧 pp-dev plugin configured for template: ${Y}`)),d.info(u.blue(`🔧 Base path configured: ${we}`)),ee&&(d.info(u.blue(`🌐 Backend URL: ${ee}`)),d.info(u.blue(`🆔 Custom App ID: ${me}`)));const xe=s.getRequestHandler(),Pe="number"==typeof q.port?q.port:3e3,Se="string"==typeof q.host?q.host||"0.0.0.0":"localhost",Te=new Set;r=G(async(e,t)=>{try{const o=e.url||"/",n=o.split("?")[0];let i=U(o,!0);if($e.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(Le.length>0){let l=0;const c=()=>{if(l>=Le.length)return void s();const o=Le[l];l++,o(e,t,c)};return void c()}return void s()}let r=0;const a=()=>{if(r>=$e.length)return void s();const o=$e[r];r++,o(e,t,a)};return void a()}async function s(){if(n.startsWith(we))i=U(o,!0);else{if(n===we.replace(/\/$/,"")){const e=o.replace(n,we);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:we}),void t.end()}await xe(e,t,i)}s()}catch(p){d.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 ke=null,$e=[],Le=[];if(!1!==he){const e=new T(ue);k($,e,ge);const t=L(e,ge);$e.push(t)}if(ee){const n=new URL(ee).host;ee.startsWith("https://")&&(o.defaultMaxListeners=Math.max(o.defaultMaxListeners,20));const i={headers:{host:n,referer:ee,origin:ee.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:me,templateLess:te,disableSSLValidation:ie,v7Features:oe,personalAccessToken:de??process.env.MI_ACCESS_TOKEN};ke=new j(ee,i);const l=F(we,Y??void 0),c=(e,t,o)=>{l(e,t,o)};Le.push(c),$e.push(c);const p=H(we);if(Le.push(p),$e.push(p),le){let e=+ce;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={middlewares:{use:e=>e},config:{logger:console}},o=E({devServer:t,ttl:e}),n=(e,t,n)=>{o(e,t,n)};$e.push(n),d.info(u.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const f=new RegExp(`^((${h=we,h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),g=C(f,ke,Object.assign({base:we},i,{miHudLess:pe})),b=(e,t,o)=>{g(e,t,o)};$e.push(b);const y=we.endsWith("/")?we.substring(0,we.length-1):we,v={middlewares:{use:e=>e},config:{logger:console}},x=A({devServer:v,baseURL:ee,proxyIgnore:["/@vite","/@metricinsights","/@",y,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:ie,miAPI:ke,templateName:Y??void 0}),P=(e,t,o)=>{x(e,t,o)};$e.push(P);const S=$,T=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(w)){return void S(e,t,()=>{})}o()};Le.push(T),$e.push(T);const k=D(e=>{const t=e.split("?")[0];return t.startsWith(we)&&!t.includes("/_next/")},(e,t)=>{const o=ke.buildPage(e,pe),i=z(o,we,{backendBaseURL:ee,templateLess:te,appId:me});return Buffer.from(I(n,t.headers.host??"",i))}),L=(e,t,o)=>{k(e,t,o)};$e.push(L),a=new ne;let M=K?.distDir;try{const e=await V(m.PHASE_PRODUCTION_BUILD,J);M=e?.distDir??M}catch{}const R=(M??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),U=R&&".next"!==R?R:"out";let W,G="0.0.0";try{const o=JSON.parse(t.readFileSync(e.join(J,"package.json"),"utf-8"));G="string"==typeof o.version?o.version:G,W="string"==typeof o.repository?o.repository:o.repository?.url}catch{}const B=!1!==Q.distZip?new N(Y??O(J),{nextBuild:{projectRoot:J,distDir:U,packageVersion:G,packageRepositoryUrl:W}}):void 0,q={ws:a.ws,config:{clientInjectionPlugin:{v7Features:oe}}};new _(q,{distService:B,miAPI:ke});const Z="function"==typeof s?.getUpgradeHandler?s.getUpgradeHandler():null;r.on("upgrade",(e,t,o)=>{a?.handleUpgrade(e,t,o)||(Z?Z(e,t,o):t.destroy())}),d.info(u.blue(`🔧 ${$e.length} pp-dev middlewares initialized`)),d.info(u.blue(`🔧 ${Le.length} essential middlewares for internal routes`)),d.info(u.blue(`🔧 MiAPI initialized for backend: ${ee}`)),d.info(u.blue(`🔧 Custom App ID: ${me}`))}r.listen(Pe,Se,()=>{d.info(u.green(`✅ pp-dev Next.js server running at http://${Se}:${Pe}`)),d.info(u.blue(`📱 Next.js app accessible at http://${Se}:${Pe}${we}`)),!1!==he&&d.info(u.cyan(`🔍 Request Inspector: http://${Se}:${Pe}${w}`)),d.info(u.blue("🔧 Base path handling active")),l||(l=se(J,p,d.info),d.info(u.blue("🔧 Config file watcher started"))),r.on("connection",e=>{Te.add(e),e.on("close",()=>Te.delete(e))});const e=async e=>{d.info(u.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));const t=setTimeout(()=>{d.info(u.yellow("⏰ Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{l&&(re(l),l=null);for(const e of Array.from(Te))e.destroy();Te.clear(),a&&(await a.close(),a=null),await new Promise(e=>{r.close(()=>{d.info(u.yellow("🛑 HTTP server closed")),e()})}),s&&"function"==typeof s.close&&(await s.close(),d.info(u.yellow("🛑 Next.js app closed"))),clearTimeout(t),d.info(u.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(t),d.error(u.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,d.info(u.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=>{d.error(u.red(`❌ Uncaught Exception: ${t}`)),e("uncaughtException")}),t.on("unhandledRejection",(t,o)=>{d.error(u.red(`❌ Unhandled Rejection at: ${o}, reason: ${t}`)),e("unhandledRejection")}),d.info(u.green("✅ Process event handlers registered successfully"))}catch(e){d.warn(u.yellow(`⚠️ Failed to register process event handlers: ${e}`))}else d.warn(u.yellow("⚠️ process.on is not available, graceful shutdown handlers will not be registered")),d.info(u.blue("💡 This might be due to bundling or environment constraints"))}),c=!1}catch(e){c=!1,d.error(u.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(d.error(u.red("❌ Next.js Peer Dependency Error:")),d.error(u.red(e.message)),d.error(u.yellow("\n💡 To fix this issue:")),d.error(u.blue(" 1. Install Next.js in your project:")),d.error(u.white(" npm install next@^16")),d.error(u.blue(" 2. Or use yarn:")),d.error(u.white(" yarn add next@^16")),d.error(u.blue(" 3. Or use pnpm:")),d.error(u.white(" pnpm add next@^16")),d.error(u.yellow("\n📖 For more information, see:")),d.error(u.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var h}},g=async e=>{d.info(u.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{l&&(re(l),l=null),a&&(await a.close(),a=null),r&&await new Promise(e=>{r.close(()=>{r=null,e()})}),s&&"function"==typeof s.close&&(await s.close(),s=null),d.info(u.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(u.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM")),process.on("uncaughtException",e=>{d.error(u.red(`❌ Uncaught Exception: ${e}`)),g("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(u.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),g("unhandledRejection")}),await p()}),ie.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(o,n)=>{pe(n);const i=fe(n);try{const s=await r({mode:n.mode||"production",command:"build"},n.config,o,n.logLevel);let c=await M();if(s){const{plugins:e,...t}=s.config;c=a(c,t)}const d=a(c,{root:o,base:n.base,mode:n.mode,configFile:n.config,logLevel:n.logLevel,clearScreen:n.clearScreen,optimizeDeps:{force:n.force},build:i},!0);if(await l(d),i.changelog){const s=o||process.cwd(),r=d.build?.outDir||"dist";let a="";if("string"==typeof i.changelog)a=e.resolve(s,i.changelog);else{const o=e.resolve(s,d.ppDevConfig?.syncBackupsDir||"backups");if(!t.existsSync(o))return void h(n.logLevel).warn(u.yellow("backups directory not found, skipping changelog generation"));const i=t.readdirSync(o,{withFileTypes:!0});if(!i.length)return void h(n.logLevel).warn(u.yellow("no backups found, skipping changelog generation"));const r=i.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!r.length)return void h(n.logLevel).warn(u.yellow("no ZIP backups found, skipping changelog generation"));const l=r.reduce((n,i)=>t.statSync(e.resolve(o,n.name)).mtimeMs>t.statSync(e.resolve(o,i.name)).mtimeMs?n:i).name;a=e.resolve(o,l)}const l=e.resolve(s,r);let c="dist-zip";d.ppDevConfig&&(!1===d.ppDevConfig.distZip?c=d.build?.outDir||"dist":"object"==typeof d.ppDevConfig.distZip&&"string"==typeof d.ppDevConfig.distZip.outDir&&(c=d.ppDevConfig.distZip.outDir));const p=new te({oldAssetsPath:a,newAssetsPath:l,destinationPath:e.resolve(s,c)});await p.generateChangelog()}}catch(e){h(n.logLevel).error(u.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{de(e=>h(n.logLevel).info(e))}}),ie.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(t,o,n)=>{pe(n);const{oldAssetsPath:i=t,newAssetsPath:s=o,destination:r=".",filename:a="CHANGELOG.html",logLevel:l}=n,c=process.cwd();i&&s||(h(l).error(u.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=e.resolve(c,i),p=e.resolve(c,s),f=e.resolve(c,r),g=new te({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await g.generateChangelog()}),ie.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(t,o,n)=>{pe(n);const{source:i=t,destination:s=o,fontName:r="icon-font"}=n,a=process.cwd(),l=e.resolve(a,i),c=e.resolve(a,s),d=new oe({sourceDir:l,outputDir:c,fontName:r}),p=h(n.logLevel);p.info(`Generating icon font from SVG files in ${u.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${u.dim(c)}`)}),ie.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{pe(t);try{const o=await r({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await M();if(o){const{plugins:e,...t}=o.config;n=a(n,t)}const i=await c(a(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode}),"serve");await d(i,t.force,!0)}catch(e){h(t.logLevel).error(u.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),ie.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)=>{pe(t);try{const o=await r({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await M();if(o){const{plugins:e,...t}=o.config;n=a(n,t)}(await p(a(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){h(t.logLevel).error(u.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{de(e=>h(t.logLevel).info(e))}}),ie.command("migrate [config]","migrate pp-dev config from 0.x flat format to 1.0 grouped format").option("--dry-run","[boolean] print migrated config without writing any files").option("--format <format>","[string] output format: ts (default), js, json").option("--output <file>","[string] output file path (default: pp-dev.config.ts)").option("--no-backup","[boolean] skip backup of original config file").action(async(o,n)=>{const i=h(n.logLevel),{isLegacyFlatConfig:s,isLegacyPPWatchConfig:r,isAlreadyMigrated:a,migrateLegacyFlatConfig:l,migratePPWatchConfig:c,generateConfigFileContent:d}=await import("./migrate-BYuCtRbI.js"),p=n.format??"ts",f=!1!==n.backup,g=process.cwd(),b=[".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 w=o??null,y=!1;if(!w){for(const o of m)if(t.existsSync(e.join(g,o))){w=e.join(g,o);break}if(!w)for(const o of b)if(t.existsSync(e.join(g,o))){w=e.join(g,o),y=!0;break}}w||(i.warn(u.yellow("No pp-dev or pp-watch config file found in the current directory.")),i.info(u.blue("Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}")),process.exit(1)),i.info(u.blue(`Found config: ${e.relative(g,w)}`));const{getPkg:v}=await import("./index-C7dYPskY.js").then(e=>e.e),x=v();let P,S={};try{if(/\.[cm]?ts$/i.test(w)){const o=await import("esbuild"),{pathToFileURL:n}=await import("url"),i=(await o.build({absWorkingDir:g,entryPoints:[w],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,s=`pp-migrate-tmp-${Date.now()}.mjs`;t.writeFileSync(s,i);try{const t=await import(n(e.resolve(g,s)).toString());S=t.default?.default??t.default??t}finally{t.existsSync(s)&&t.unlinkSync(s)}}else if(/\.[cm]?js$/i.test(w)){const{pathToFileURL:t}=await import("url"),o=await import(t(e.resolve(g,w)).toString());S=o.default?.default??o.default??o}else w.endsWith(".json")&&(S=JSON.parse(t.readFileSync(w,"utf-8")))}catch(e){i.error(u.red(`Failed to load config file: ${e.message}`)),process.exit(1)}S&&"object"==typeof S||(i.error(u.red("Config file did not export a valid object.")),process.exit(1)),a(S)?(i.info(u.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):y||r(S)?(i.info(u.blue("Detected pp-watch config format → migrating to 1.0")),P=c(S)):s(S)?(i.info(u.blue("Detected 0.x flat config format → migrating to 1.0")),P=l(S,x.name)):(i.warn(u.yellow("Could not detect config format. No known keys found.")),process.exit(1));const T=d(P,p),k=n.output??e.join(g,`pp-dev.config.${p}`);if(n.dryRun&&(i.info(u.green(`\n--- Migrated config (dry-run) → ${e.relative(g,k)} ---\n`)),process.exit(0)),f&&t.existsSync(w)){const o=`${w}.bak`;t.copyFileSync(w,o),i.info(u.blue(`Backed up original to: ${e.relative(g,o)}`))}t.writeFileSync(k,T,"utf-8"),i.info(u.green(`✅ Migration complete → ${e.relative(g,k)}`)),w!==k&&t.existsSync(w)&&i.info(u.yellow(`You can now delete the old config: ${e.relative(g,w)}`))}),ie.help(),ie.version(b),ie.parse();export{de as stopProfiler};
1
+ import*as e from"path";import*as t from"fs";import{EventEmitter as o}from"node:events";import{performance as n}from"node:perf_hooks";import{watch as i}from"chokidar";import{cac as s}from"cac";import{loadConfigFromFile as r,mergeConfig as a,build as l,resolveConfig as c,optimizeDeps as d,preview as p,loadEnv as f}from"vite";import{c as h,a as u,P as g,b as m,V as b,I as w,v as y,n as v,d as x,e as P,f as S,R as T,r as k,i as $,g as L,M as j,h as F,j as E,k as C,l as A,m as D,u as I,D as N,C as _}from"./plugin-B2ocw-wb.js";import{g as M,s as R,c as H,i as z}from"./index-DOjGFYJ7.js";import{parse as U}from"url";import*as W from"dir-compare";import O from"diff-match-patch";import{isBinaryFile as G}from"isbinaryfile";import*as B from"os";import*as V from"crypto";import q from"extract-zip";import Z from"svgtofont";import{WebSocketServer as J,WebSocket as K}from"ws";import"http-proxy-middleware";import"picocolors";import"axios";import"node:http";import"node:https";import"jsdom";import"process";import"child_process";import"module";import"jszip";import"memory-cache";import"zlib";import"express";import"node:crypto";import"./helpers.js";import"ejs";function X(e){return null!=e&&!1!==e}let Y=null;const Q=[{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 ee=/(.+)(-[a-f0-9]{6,20})(\.[a-z0-9]+)$/i;class te{oldAssetsPath;newAssetsPath;destinationPath;changelogFilename;changelogTemplate='<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>Changelog Diff</title>\n <style>\n tr,\n td {\n padding: 0;\n }\n .diff-file {\n margin-top: 20px;\n border: 1px solid #e1e4e8;\n border-radius: 6px;\n }\n .diff-file-title {\n padding: 10px 20px;\n background-color: #f6f8fa;\n border-bottom: 1px solid #e1e4e8;\n border-radius: 6px 6px 0 0;\n font-weight: bold;\n }\n .diff-file-title .renamed {\n font-weight: normal;\n }\n .diff-file-title .renamed .from {\n color: #cb2431;\n }\n .diff-file-title .renamed .to {\n color: #22863a;\n }\n .diff-file-title .added {\n color: #22863a;\n }\n .diff-file-title .deleted {\n color: #cb2431;\n }\n .diff-file-content {\n }\n .diff-table {\n tab-size: 8;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n }\n .blob-num {\n position: relative;\n color: #1f2328;\n width: 1%;\n min-width: 50px;\n padding: 0 10px;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n line-height: 20px;\n text-align: right;\n white-space: nowrap;\n vertical-align: top;\n cursor: pointer;\n -webkit-user-select: none;\n user-select: none;\n }\n .blob-num.addition {\n background-color: #ccffd8;\n border-color: #1f883e;\n }\n .blob-num.deletion {\n background-color: #ffd7d5;\n border-color: #cf222e;\n }\n .blob-num::before {\n content: attr(data-line-number);\n }\n .blob-code {\n position: relative;\n padding: 0 10px 0 22px;\n vertical-align: top;\n color: #1f2329;\n }\n .blob-code.code-addition {\n background-color: #e6ffec;\n }\n .blob-code.code-deletion {\n background-color: #ffebe9;\n }\n .blob-code.skip,\n .blob-code.message {\n text-align: center;\n }\n .blob-code.skip .blob-code-inner,\n .blob-code.message .blob-code-inner {\n font-weight: bold;\n color: #6a737d;\n padding: 10px 0;\n }\n .blob-code-inner {\n display: table-cell;\n overflow: visible;\n font-family:\n ui-monospace,\n SFMono-Regular,\n SF Mono,\n Menlo,\n Consolas,\n Liberation Mono,\n monospace;\n font-size: 12px;\n word-wrap: anywhere;\n white-space: pre-wrap;\n }\n .blob-code-inner::before {\n content: attr(data-code-prefix);\n position: absolute;\n top: 1px;\n left: 8px;\n padding-right: 8px;\n }\n </style>\n </head>\n <body>\n <h1>Changelog Diff</h1>\n\n %FILES%\n </body>\n </html>';diffFileTemplateHandler;diffLineTemplateHandler;contextLines=3;logger;constructor(t){const{oldAssetsPath:o,newAssetsPath:n,destinationPath:i,changelogTemplate:s,diffFileTemplateHandler:r,diffLineTemplateHandler:a,changelogFilename:l,contextLines:c}=t;if(this.logger=h(),!o||!n||!i)throw new Error("Previous assets path, current assets path and destination path are required");if(o===n)throw new Error("Previous and current assets paths must be different");if(!this.isExists(o))throw new Error(`Previous assets path ${o} does not exist`);if(!this.isExists(n))throw new Error(`Current assets path ${n} does not exist`);if(this.isZipFile(o)){const t=e.resolve(B.tmpdir(),V.createHash("md5").update(o).digest("hex"));this.oldAssetsPath=this.unzipFile(o,t).then(()=>this.normalizeAssetFolderPath(t)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);return e})}else{if(!this.isFolder(o))throw new Error(`Invalid previous assets path ${o}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(o);if(this.isEmptyFolder(e))throw new Error(`Previous assets path ${e} is empty`);this.oldAssetsPath=Promise.resolve(e)}}if(this.isZipFile(n)){const t=e.resolve(B.tmpdir(),V.createHash("md5").update(n).digest("hex"));this.newAssetsPath=this.unzipFile(n,t).then(()=>this.normalizeAssetFolderPath(t)).then(e=>{if(this.isEmptyFolder(e))throw new Error(`Current assets path ${e} is empty`);return e})}else{if(!this.isFolder(n))throw new Error(`Invalid current assets path ${n}. It must be a folder or a zip file`);{const e=this.normalizeAssetFolderPath(n);if(this.isEmptyFolder(e))throw new Error(`Current assets path ${n} is empty`);this.newAssetsPath=Promise.resolve(e)}}this.destinationPath=i,this.mkdirpSync(this.destinationPath),this.changelogFilename=l||"CHANGELOG.html",s&&(this.templateIsValid(s)?this.changelogTemplate=s:this.logger.warn(u.yellow("Invalid changelog template, using default"))),"function"==typeof r&&(this.diffFileTemplateHandler=r),"function"==typeof a&&(this.diffLineTemplateHandler=a),c&&(this.contextLines=c)}templateIsValid(e){return e.includes("%FILES%")}isExists(e){return t.existsSync(e)}isZipFile(e){return e.endsWith(".zip")}isFolder(e){return t.lstatSync(e).isDirectory()}isEmptyFolder(e){return 0===t.readdirSync(e,{withFileTypes:!0}).length}mkdirpSync(e){t.existsSync(e)||t.mkdirSync(e,{recursive:!0})}async unzipFile(e,o){return t.rmSync(o,{force:!0,recursive:!0}),q(e,{dir:o})}normalizeAssetFolderPath(o){const n=t.readdirSync(o);return 1===n.length&&t.lstatSync(e.join(o,n[0])).isDirectory()?this.normalizeAssetFolderPath(e.join(o,n[0])):o}pathToPosix(e){return e.replace(/\\/g,"/")}diffTableTemplate(e){return`<table class="diff-table">\n <tbody>\n ${e}\n </tbody>\n </table>`}getDiffTableHTML(e){const t=e.filter((e,t,o)=>0!==e.lineType||(t>=0&&t<this.contextLines||t>o.length-(this.contextLines+1)&&t<=o.length-1||o.slice(t-this.contextLines,t+this.contextLines+1).some(e=>0!==e.lineType))).map((e,t,o)=>{if(t>0){const n=o[t-1];if(e.lineNumber-n.lineNumber>1)return[{lineNumber:-1,lineContent:"",lineType:0},e]}return[e]}).flat().map(e=>this.diffLineHTML(e)).join("");return this.diffTableTemplate(t)}diffLineMessageTemplate(e){return`<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code message">\n <span class="blob-code-inner">${e}</span>\n </td>\n </tr>`}diffLineSkipTemplate(){return'<tr>\n <td class="blob-num"></td>\n <td class="blob-num"></td>\n <td class="blob-code skip">\n <span class="blob-code-inner">Skip</span>\n </td>\n </tr>'}diffLineTemplate(e){const{lineNumber:t,lineContent:o,lineType:n}=e,i=1===n?"addition":-1===n?"deletion":"";return`<tr>\n <td\n class="blob-num ${i}${"addition"===i?" empty":""}"\n ${"addition"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td\n class="blob-num ${i}${"deletion"===i?" empty":""}"\n ${"deletion"!==i?` data-line-number="${t}"`:""}\n ></td>\n <td class="blob-code ${1===n?"code-addition":-1===n?"code-deletion":""}">\n <span class="blob-code-inner" data-code-prefix="${1===n?"+":-1===n?"-":" "}">${s=o??"",s.replace(/[\u00A0-\u9999<>&]/g,e=>"&#"+e.charCodeAt(0)+";")}</span>\n </td>\n </tr>`;var s}diffLineHTML(e){if(this.diffLineTemplateHandler)return this.diffLineTemplateHandler(e);const{lineNumber:t}=e;return-1===t?this.diffLineSkipTemplate():this.diffLineTemplate(e)}diffFileTemplate(e,t){return this.diffFileTemplateHandler?this.diffFileTemplateHandler(e,t):`<div class="diff-file">\n <div class="diff-file-title">${e}</div>\n <div class="diff-file-content">${t}</div>\n </div>`}async generateAssetFoldersDiff(){this.logger.info(u.blue(`Comparing asset folders ${await this.oldAssetsPath} and ${await this.newAssetsPath}`));const e=await W.compare(await this.oldAssetsPath,await this.newAssetsPath,{compareContent:!0,skipSymlinks:!0,compareSize:!0,compareDate:!1,compareNameHandler:(e,t)=>(ee.test(e)&&(e=e.replace(ee,"$1$3")),ee.test(t)&&(t=t.replace(ee,"$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 O,n=o.diff_linesToChars_(e,t),i=o.diff_main(n.chars1,n.chars2,!1);o.diff_charsToLines_(i,n.lineArray);let s=0;return i.map(e=>{const[t,o]=e,n=o.endsWith("\n")?o.split("\n").length-1:o.split("\n").length,i=o.split("\n").map((e,o)=>({lineContent:e,lineNumber:s+o+1,lineType:t})).slice(0,n);return-1!==t&&(s+=n),i}).flat()}async generateFilesDiff(o){if("equal"===o.state){const t=this.pathToPosix(e.join(".",o.relativePath,o.name1??"")),n=this.pathToPosix(e.join(".",o.relativePath,o.name2??""));return this.diffFileTemplate(`<span class="renamed"\n >Renamed <span class="from">${t}</span> -> <span class="to">${n}</span></span\n >`,this.diffTableTemplate(this.diffLineMessageTemplate("No changes")))}const n=o.path1&&o.name1?e.join(o.path1,o.name1):null,i=o.path2&&o.name2?e.join(o.path2,o.name2):null,s=this.pathToPosix(e.join(".",o.relativePath,(o.name1||o.name2)??""));if("left"===o.state&&n)return this.diffFileTemplate(`<span class="removed">Removed ${s}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File removed")));if("right"===o.state&&i)return this.diffFileTemplate(`<span class="added">Added ${s}</span>`,this.diffTableTemplate(this.diffLineMessageTemplate("File added")));if("distinct"===o.state&&n&&i){const r=this.pathToPosix(e.join(".",o.relativePath,o.name1??"")),a=this.pathToPosix(e.join(".",o.relativePath,o.name2??"")),l=o.name1!==o.name2?`<span class="renamed"\n >Renamed <span class="from">${r}</span> -> <span class="to">${a}</span></span\n >`:s;return this.diffFileTemplate(l,await G(n)||await G(i)?this.diffTableTemplate(this.diffLineMessageTemplate("Binary file")):this.getDiffTableHTML(await this.generateAssetFilesDiff(t.readFileSync(n,"utf-8"),t.readFileSync(i,"utf-8"))))}return""}async generateChangelog(){this.logger.info(u.green("Generating changelog"));const o=await this.generateAssetFoldersDiff(),n=(await Promise.all(o.map(e=>this.generateFilesDiff(e)))).join("");this.logger.info(u.green("Writing changelog file"));const i=this.changelogTemplate.split("%FILES%");i.splice(1,0,n);const s=i.join("");t.writeFileSync(e.join(this.destinationPath,this.changelogFilename),s),this.logger.info(u.green(`Changelog file written to ${e.join(this.destinationPath,this.changelogFilename)}`))}}class oe{sourceDir;outputDir;fontName;constructor(e){this.sourceDir=e.sourceDir,this.outputDir=e.outputDir,this.fontName=e.fontName}async generate(){await Z({src:this.sourceDir,dist:this.outputDir,fontName:this.fontName,css:!0,typescript:!0,startUnicode:59905,svgicons2svgfont:{fontHeight:1024}})}}class ne{wss;eventListeners=new Map;lifecycleListeners=new Map;clients=new Map;ws;constructor(){this.wss=new J({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===K.OPEN&&e.send(t)}}}}handleUpgrade(e,t,o){return(e.url??"").split("?")[0]===g&&(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){h().error(`ws handler for "${o.event}" failed`,{error:e instanceof Error?e:new Error(String(e))})}}sendToSocket(e,t,o){e.readyState===K.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 ie=s("pp-dev");function se(t,o,n){const s=[...m,"package.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.mjs","vite.config.ts",".env",".env.local",".env.development",".env.development.local"].map(o=>e.join(t,o)),r=i(s,{ignored:t=>{const o=e.basename(t);return/(^|[\/\\])\../.test(t)&&!o.startsWith(".env")&&!o.startsWith(".pp-dev")&&!o.startsWith(".pp-watch")},persistent:!0,ignoreInitial:!0,followSymlinks:!1});let a=null;return r.on("change",i=>{n(u.blue(`🔧 Config file changed: ${e.relative(t,i)}`)),a&&clearTimeout(a),a=setTimeout(async()=>{try{n(u.yellow("🔄 Restarting dev server due to config change...")),await o()}catch(e){n(u.red(`❌ Failed to restart dev server: ${e?.message}. Stack: ${e?.stack}`))}},500)}),r.on("error",e=>{n(u.red(`❌ Config watcher error: ${e}`))}),{watcher:r,restartCallback:o,logger:n}}function re(e){e.watcher&&e.watcher.close()}function ae(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 le=global.__pp_dev_profile_session,ce=0;const de=o=>{if(le)return new Promise((n,i)=>{le.post("Profiler.stop",(s,{profile:r})=>{if(s)i(s);else{const i=e.resolve(`./pp-dev-profile-${ce++}.cpuprofile`);t.writeFileSync(i,JSON.stringify(r)),o(u.yellow(`CPU profile written to ${u.white(u.dim(i))}`)),le=void 0,n()}})})},pe=e=>{for(const[t,o]of Object.entries(e))Array.isArray(o)&&(e[t]=o[o.length-1])};function fe(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}ie.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"),ie.command("[root]","start dev server").alias("serve").alias("dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port").option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(t,o)=>{pe(o);let i=null,s=null,l=!1;const c=t?e.resolve(process.cwd(),t):process.cwd(),d=h(o.logLevel),p=async()=>{if(!l){l=!0;try{i&&(d.info(u.yellow("🛑 Stopping existing dev server...")),await i.close(),i=null);const{clearConfigCache:e,getConfig:g}=await import("./index-DOjGFYJ7.js").then(e=>e.e);e();const{createServer:m}=await import("vite"),y=await r({mode:o.mode||"development",command:"serve"},o.config,t,o.logLevel);let v=await M();const x=f(o.mode||"development",t??process.cwd(),"");if(x&&Object.keys(x).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=x[e])}),y){const{plugins:e,...t}=y.config;v=a(v,t)}if(i=await m(a(v,{root:t,base:o.base,mode:o.mode,configFile:o.config,logLevel:o.logLevel,clearScreen:o.clearScreen,optimizeDeps:{force:o.force},server:fe(o),customLogger:d},!0)),!i.config.base||"/"===i.config.base)throw new Error('base cannot be equal to "/" or empty string');if(!i.httpServer)throw new Error("HTTP server not available");await i.listen();const P=global.__pp_dev_start_time??!1,S=P?u.dim(`ready in ${u.reset(u.bold(Math.ceil(n.now()-P)))} ms`):"";d.info(`\n ${u.green(`${u.bold("PP-DEV")} v${b}`)} ${S}\n`),i.printUrls();const T=await g();if(!1!==T.inspector?.enabled){const e=i.resolvedUrls?.local[0],t=e?new URL(e).origin:`http://localhost:${i.config.server.port??5173}`;d.info(`\n ${u.cyan("🔍 Request Inspector")} ${u.dim(t+w)}\n`)}!function(e,t){if(!e.httpServer||!process.stdin.isTTY||process.env.CI)return;e._shortcutsOptions=t;const o=h();t.print&&o.info(u.dim(u.green(" ➜"))+u.dim(" press ")+u.bold("h")+u.dim(" to show help"));const n=(t.customShortcuts??[]).filter(X).concat(Q);Y?.(),Y=null;let i=!1;const s=process.stdin.isPaused(),r=process.stdin,a=Boolean(r.isRaw),l=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(["",u.bold(" Shortcuts"),...n.map(e=>u.dim(" press ")+u.bold(e.key)+u.dim(` to ${e.description}`))].join("\n"));const s=n.find(e=>e.key===t);s&&(i=!0,await s.action(e),i=!1)};process.stdin.setRawMode(!0),process.stdin.on("data",l).setEncoding("utf8").resume();const c=e.httpServer,d=()=>{Y===d&&(c.removeListener("close",d),process.stdin.off("data",l),a||process.stdin.setRawMode(!1),s&&process.stdin.pause(),Y=null)};Y=d,c.on("close",d)}(i,{print:!0,customShortcuts:[...le?[{key:"p",description:"start/stop the profiler",async action(e){if(le)await de(d.info);else{const e=await import("node:inspector").then(e=>e.default);await new Promise(t=>{le=new e.Session,le.connect(),le.post("Profiler.enable",()=>{le?.post("Profiler.start",()=>{d.info("Profiler started"),t()})})})}}}]:[],{key:"l",description:"proxy re-login",action(e){e.ws.send({type:"custom",event:"redirect",data:{url:`/auth/index/logout?proxyRedirect=${encodeURIComponent("/")}`}})}}]}),s||(s=se(c,p,d.info),d.info(u.blue("🔧 Config file watcher started"))),l=!1}catch(e){l=!1,d.error(u.red(`error when starting dev server:\n${e.stack}`),{error:e}),de(d.info),process.exit(1)}}},g=async e=>{d.info(u.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{s&&(re(s),s=null),i&&(await i.close(),i=null),de(d.info),d.info(u.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(u.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM")),process.on("uncaughtException",e=>{d.error(u.red(`❌ Uncaught Exception: ${e}`)),g("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(u.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),g("unhandledRejection")}),await p()}),ie.command("next [root]","start Next.js development server with pp-dev integration").alias("next-serve").alias("next-dev").option("--host [host]","[string] specify hostname").option("--port <port>","[number] specify port",{default:3e3}).option("--https","[boolean] use TLS + HTTP/2").option("--open [path]","[boolean | string] open browser on startup").option("--cors","[boolean] enable CORS").option("--strictPort","[boolean] exit if specified port is already in use").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").option("--webpack","[boolean] use Webpack for Next dev (use when Turbopack/native SWC is unavailable)").option("--turbopack","[boolean] use Turbopack for Next dev when native bindings work").action(async(n,i)=>{pe(i);let s=null,r=null,a=null,l=null,c=!1;const d=h(),p=async()=>{if(!c){c=!0;try{const{next:g,constants:m}=await R(),{PHASE_DEVELOPMENT_SERVER:b}=m;a&&(await a.close(),a=null),r&&(d.info(u.yellow("🛑 Stopping existing Next.js server...")),await new Promise(e=>{r.close(()=>{r=null,e()})})),s&&"function"==typeof s.close&&(await s.close(),s=null);const{clearConfigCache:M}=await import("./index-DOjGFYJ7.js").then(e=>e.e);M();const{join:W,basename:O}=await import("path"),{createServer:G}=await import("http"),B=await import("next/dist/server/config.js"),V=B.default.default||B["module.exports"].default||B.default,q=fe(i),Z=f(i.mode||"development",n??process.cwd(),"");Z&&Object.keys(Z).forEach(e=>{e.startsWith("MI_")&&(process.env[e]=Z[e])});const J=n?W(process.cwd(),n):process.cwd();d.info(J);const K=await V(b,J);let X=K?.ppDev||{};if(0===Object.keys(X).length)try{const{getConfig:e}=await import("./index-DOjGFYJ7.js").then(e=>e.e),t=await e();Object.keys(t).length>0?(X=t,d.info(u.blue("🔧 Loaded pp-dev config from standalone config file"))):d.info(u.yellow("⚠️ No pp-dev config found in Next.js config or standalone file, using defaults"))}catch(e){d.info(u.yellow("⚠️ Failed to load standalone pp-dev config, using defaults")),console.debug("Error loading standalone config:",e)}else d.info(u.blue("🔧 Loaded pp-dev config from Next.js config"));let Y=null;try{const{getPkg:e}=await import("./index-DOjGFYJ7.js").then(e=>e.e);Y=e().name}catch{Y=O(J)}y(X,Y??"");const Q=v(X,Y??""),ee=Q.backendBaseURL??"http://localhost:8080",te=Q.templateLess,oe=Q.v7Features,ie=Q.disableSSLValidation,le=Q.enableProxyCache,ce=Q.proxyCacheTTL,de=Q.personalAccessToken,pe=Q.miHudLess,he=Q.inspectorEnabled,ue=Q.inspectorMaxMemory,ge=Q.inspectorCaptureLimit,me=Q.appId??(process.env.MI_APP_ID&&parseInt(process.env.MI_APP_ID,10)||void 0)??(process.env.MI_PORTAL_PAGE_ID&&parseInt(process.env.MI_PORTAL_PAGE_ID,10)||void 0)??1,be=K?.basePath;let we="";be?we=be:(we=te?x:oe?P:S,we+=`/${Y}`);const ye=function(e){const t="1"===process.env.PP_DEV_NEXT_WEBPACK||"true"===process.env.PP_DEV_NEXT_WEBPACK;if(t&&(e.webpack||e.turbopack))throw new Error("Do not combine PP_DEV_NEXT_WEBPACK with --webpack or --turbopack");if(t)return{webpack:!0};if(e.webpack&&e.turbopack)throw new Error("Use only one of --webpack or --turbopack");return e.webpack?{webpack:!0}:e.turbopack?{turbopack:!0}:{}}(i),ve=async e=>{delete process.env.TURBOPACK,s&&"function"==typeof s.close&&(await s.close(),s=null);const t={dev:!0,customServer:!0,hostname:q.host||"localhost",port:q.port,dir:J,conf:{...K,basePath:we,assetPrefix:we}};e.webpack?t.webpack=!0:e.turbopack&&(t.turbopack=!0),s=g(t),await s.prepare()};if(ye.webpack)await ve({webpack:!0});else if(ye.turbopack)try{await ve({turbopack:!0})}catch(e){if(!ae(e))throw e;d.warn(u.yellow("⚠ Turbopack is unavailable (native bindings). Falling back to Webpack.")),await ve({webpack:!0})}else try{await ve({})}catch(e){if(!ae(e))throw e;d.warn(u.yellow("⚠ Turbopack cannot run (native Next.js bindings unavailable). Falling back to Webpack.")),await ve({webpack:!0})}if(!s)throw new Error("Next.js app failed to initialize");if(we.endsWith("/")||(we+="/"),"/"===we)throw new Error('basePath cannot be equal to "/" or equal to empty string');d.info(u.green("✅ Next.js app prepared successfully")),d.info(u.blue(`🔧 pp-dev plugin configured for template: ${Y}`)),d.info(u.blue(`🔧 Base path configured: ${we}`)),ee&&(d.info(u.blue(`🌐 Backend URL: ${ee}`)),d.info(u.blue(`🆔 Custom App ID: ${me}`)));const xe=s.getRequestHandler(),Pe="number"==typeof q.port?q.port:3e3,Se="string"==typeof q.host?q.host||"0.0.0.0":"localhost",Te=new Set;r=G(async(e,t)=>{try{const o=e.url||"/",n=o.split("?")[0];let i=U(o,!0);if($e.length>0){if(n.startsWith("/_next/")||"/favicon.ico"===n||n.startsWith("/__nextjs_")){if(Le.length>0){let l=0;const c=()=>{if(l>=Le.length)return void s();const o=Le[l];l++,o(e,t,c)};return void c()}return void s()}let r=0;const a=()=>{if(r>=$e.length)return void s();const o=$e[r];r++,o(e,t,a)};return void a()}async function s(){if(n.startsWith(we))i=U(o,!0);else{if(n===we.replace(/\/$/,"")){const e=o.replace(n,we);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:we}),void t.end()}await xe(e,t,i)}s()}catch(p){d.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 ke=null,$e=[],Le=[];if(!1!==he){const e=new T(ue);k($,e,ge);const t=L(e,ge);$e.push(t)}if(ee){const n=new URL(ee).host;ee.startsWith("https://")&&(o.defaultMaxListeners=Math.max(o.defaultMaxListeners,20));const i={headers:{host:n,referer:ee,origin:ee.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:me,templateLess:te,disableSSLValidation:ie,v7Features:oe,personalAccessToken:de??process.env.MI_ACCESS_TOKEN};ke=new j(ee,i);const l=F(we,Y??void 0),c=(e,t,o)=>{l(e,t,o)};Le.push(c),$e.push(c);const p=H(we);if(Le.push(p),$e.push(p),le){let e=+ce;(!e||Number.isNaN(e)||e<0)&&(e=6e5);const t={middlewares:{use:e=>e},config:{logger:console}},o=E({devServer:t,ttl:e}),n=(e,t,n)=>{o(e,t,n)};$e.push(n),d.info(u.blue(`🔧 Proxy cache middleware added with TTL: ${e}ms`))}const f=new RegExp(`^((${h=we,h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`),g=C(f,ke,Object.assign({base:we},i,{miHudLess:pe})),b=(e,t,o)=>{g(e,t,o)};$e.push(b);const y=we.endsWith("/")?we.substring(0,we.length-1):we,v={middlewares:{use:e=>e},config:{logger:console}},x=A({devServer:v,baseURL:ee,proxyIgnore:["/@vite","/@metricinsights","/@",y,"/_next","/favicon.ico","/__nextjs_","/installHook.js.map"],disableSSLValidation:ie,miAPI:ke,templateName:Y??void 0}),P=(e,t,o)=>{x(e,t,o)};$e.push(P);const S=$,T=(e,t,o)=>{if(e.url?.startsWith("/@api/")||e.url?.startsWith(w)){return void S(e,t,()=>{})}o()};Le.push(T),$e.push(T);const k=D(e=>{const t=e.split("?")[0];return t.startsWith(we)&&!t.includes("/_next/")},(e,t)=>{const o=ke.buildPage(e,pe),i=z(o,we,{backendBaseURL:ee,templateLess:te,appId:me,devPanelPosition:Q.devPanelPosition,devPanelHidden:Q.devPanelHidden,devPanelAutoHide:Q.devPanelAutoHide});return Buffer.from(I(n,t.headers.host??"",i))}),L=(e,t,o)=>{k(e,t,o)};$e.push(L),a=new ne;let M=K?.distDir;try{const e=await V(m.PHASE_PRODUCTION_BUILD,J);M=e?.distDir??M}catch{}const R=(M??"").replace(/\\/g,"/").replace(/\/+$/,"").replace(/\/dev$/,""),U=R&&".next"!==R?R:"out";let W,G="0.0.0";try{const o=JSON.parse(t.readFileSync(e.join(J,"package.json"),"utf-8"));G="string"==typeof o.version?o.version:G,W="string"==typeof o.repository?o.repository:o.repository?.url}catch{}const B=!1!==Q.distZip?new N(Y??O(J),{nextBuild:{projectRoot:J,distDir:U,packageVersion:G,packageRepositoryUrl:W}}):void 0,q={ws:a.ws,config:{clientInjectionPlugin:{v7Features:oe}}};new _(q,{distService:B,miAPI:ke});const Z="function"==typeof s?.getUpgradeHandler?s.getUpgradeHandler():null;r.on("upgrade",(e,t,o)=>{a?.handleUpgrade(e,t,o)||(Z?Z(e,t,o):t.destroy())}),d.info(u.blue(`🔧 ${$e.length} pp-dev middlewares initialized`)),d.info(u.blue(`🔧 ${Le.length} essential middlewares for internal routes`)),d.info(u.blue(`🔧 MiAPI initialized for backend: ${ee}`)),d.info(u.blue(`🔧 Custom App ID: ${me}`))}r.listen(Pe,Se,()=>{d.info(u.green(`✅ pp-dev Next.js server running at http://${Se}:${Pe}`)),d.info(u.blue(`📱 Next.js app accessible at http://${Se}:${Pe}${we}`)),!1!==he&&d.info(u.cyan(`🔍 Request Inspector: http://${Se}:${Pe}${w}`)),d.info(u.blue("🔧 Base path handling active")),l||(l=se(J,p,d.info),d.info(u.blue("🔧 Config file watcher started"))),r.on("connection",e=>{Te.add(e),e.on("close",()=>Te.delete(e))});const e=async e=>{d.info(u.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));const t=setTimeout(()=>{d.info(u.yellow("⏰ Shutdown timeout reached, forcing exit")),process.exit(0)},5e3);try{l&&(re(l),l=null);for(const e of Array.from(Te))e.destroy();Te.clear(),a&&(await a.close(),a=null),await new Promise(e=>{r.close(()=>{d.info(u.yellow("🛑 HTTP server closed")),e()})}),s&&"function"==typeof s.close&&(await s.close(),d.info(u.yellow("🛑 Next.js app closed"))),clearTimeout(t),d.info(u.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){clearTimeout(t),d.error(u.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,d.info(u.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=>{d.error(u.red(`❌ Uncaught Exception: ${t}`)),e("uncaughtException")}),t.on("unhandledRejection",(t,o)=>{d.error(u.red(`❌ Unhandled Rejection at: ${o}, reason: ${t}`)),e("unhandledRejection")}),d.info(u.green("✅ Process event handlers registered successfully"))}catch(e){d.warn(u.yellow(`⚠️ Failed to register process event handlers: ${e}`))}else d.warn(u.yellow("⚠️ process.on is not available, graceful shutdown handlers will not be registered")),d.info(u.blue("💡 This might be due to bundling or environment constraints"))}),c=!1}catch(e){c=!1,d.error(u.red(`❌ Failed to start Next.js server: ${e?.message}. Stack: ${e?.stack}`)),e instanceof Error&&e.message.includes("Next.js is required")&&(d.error(u.red("❌ Next.js Peer Dependency Error:")),d.error(u.red(e.message)),d.error(u.yellow("\n💡 To fix this issue:")),d.error(u.blue(" 1. Install Next.js in your project:")),d.error(u.white(" npm install next@^16")),d.error(u.blue(" 2. Or use yarn:")),d.error(u.white(" yarn add next@^16")),d.error(u.blue(" 3. Or use pnpm:")),d.error(u.white(" pnpm add next@^16")),d.error(u.yellow("\n📖 For more information, see:")),d.error(u.blue(" https://nextjs.org/docs/getting-started"))),process.exit(1)}var h}},g=async e=>{d.info(u.yellow(`\n🛑 Received ${e}, shutting down gracefully...`));try{l&&(re(l),l=null),a&&(await a.close(),a=null),r&&await new Promise(e=>{r.close(()=>{r=null,e()})}),s&&"function"==typeof s.close&&(await s.close(),s=null),d.info(u.green("✅ Graceful shutdown completed")),process.exit(0)}catch(e){d.error(u.red(`❌ Error during graceful shutdown: ${e}`)),process.exit(1)}};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM")),process.on("uncaughtException",e=>{d.error(u.red(`❌ Uncaught Exception: ${e}`)),g("uncaughtException")}),process.on("unhandledRejection",(e,t)=>{d.error(u.red(`❌ Unhandled Rejection at: ${t}, reason: ${e}`)),g("unhandledRejection")}),await p()}),ie.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(o,n)=>{pe(n);const i=fe(n);try{const s=await r({mode:n.mode||"production",command:"build"},n.config,o,n.logLevel);let c=await M();if(s){const{plugins:e,...t}=s.config;c=a(c,t)}const d=a(c,{root:o,base:n.base,mode:n.mode,configFile:n.config,logLevel:n.logLevel,clearScreen:n.clearScreen,optimizeDeps:{force:n.force},build:i},!0);if(await l(d),i.changelog){const s=o||process.cwd(),r=d.build?.outDir||"dist";let a="";if("string"==typeof i.changelog)a=e.resolve(s,i.changelog);else{const o=e.resolve(s,d.ppDevConfig?.syncBackupsDir||"backups");if(!t.existsSync(o))return void h(n.logLevel).warn(u.yellow("backups directory not found, skipping changelog generation"));const i=t.readdirSync(o,{withFileTypes:!0});if(!i.length)return void h(n.logLevel).warn(u.yellow("no backups found, skipping changelog generation"));const r=i.filter(e=>e.isFile()&&e.name.endsWith(".zip"));if(!r.length)return void h(n.logLevel).warn(u.yellow("no ZIP backups found, skipping changelog generation"));const l=r.reduce((n,i)=>t.statSync(e.resolve(o,n.name)).mtimeMs>t.statSync(e.resolve(o,i.name)).mtimeMs?n:i).name;a=e.resolve(o,l)}const l=e.resolve(s,r);let c="dist-zip";d.ppDevConfig&&(!1===d.ppDevConfig.distZip?c=d.build?.outDir||"dist":"object"==typeof d.ppDevConfig.distZip&&"string"==typeof d.ppDevConfig.distZip.outDir&&(c=d.ppDevConfig.distZip.outDir));const p=new te({oldAssetsPath:a,newAssetsPath:l,destinationPath:e.resolve(s,c)});await p.generateChangelog()}}catch(e){h(n.logLevel).error(u.red(`error during build:\n${e.stack}`),{error:e}),process.exit(1)}finally{de(e=>h(n.logLevel).info(e))}}),ie.command("changelog [oldAssetPath] [newAssetPath]","generate changelog between two assets files/folders").option("--oldAssetsPath <oldAssetsPath>","[string] path to the old assets zip file or folder").option("--newAssetsPath <newAssetsPath>","[string] path to the new assets zip file or folder").option("--destination <destination>","[string] destination folder for the changelog (default: .)").option("--filename <filename>","[string] filename for the changelog (default: CHANGELOG.html)").action(async(t,o,n)=>{pe(n);const{oldAssetsPath:i=t,newAssetsPath:s=o,destination:r=".",filename:a="CHANGELOG.html",logLevel:l}=n,c=process.cwd();i&&s||(h(l).error(u.red("error during changelog generation: oldAssetPath and newAssetPath are required")),process.exit(1));const d=e.resolve(c,i),p=e.resolve(c,s),f=e.resolve(c,r),g=new te({oldAssetsPath:d,newAssetsPath:p,destinationPath:f,changelogFilename:a});await g.generateChangelog()}),ie.command("generate-icon-font [source] [destination]","generate icon font from SVG files").option("--source <source>","[string] path to the source directory with SVG files").option("--destination <destination>","[string] path to the destination directory to save the generated font files").option("--font-name, -n <fontName>","[string] name of the font to generate (default: 'icon-font')").action(async(t,o,n)=>{pe(n);const{source:i=t,destination:s=o,fontName:r="icon-font"}=n,a=process.cwd(),l=e.resolve(a,i),c=e.resolve(a,s),d=new oe({sourceDir:l,outputDir:c,fontName:r}),p=h(n.logLevel);p.info(`Generating icon font from SVG files in ${u.dim(l)}`),await d.generate(),p.info(`Icon font generated and saved to ${u.dim(c)}`)}),ie.command("optimize [root]","pre-bundle dependencies").option("--force","[boolean] force the optimizer to ignore the cache and re-bundle").action(async(e,t)=>{pe(t);try{const o=await r({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await M();if(o){const{plugins:e,...t}=o.config;n=a(n,t)}const i=await c(a(n,{root:e,base:t.base,configFile:t.config,logLevel:t.logLevel,mode:t.mode}),"serve");await d(i,t.force,!0)}catch(e){h(t.logLevel).error(u.red(`error when optimizing deps:\n${e.stack}`),{error:e}),process.exit(1)}}),ie.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)=>{pe(t);try{const o=await r({mode:t.mode||"production",command:"build"},t.config,e,t.logLevel);let n=await M();if(o){const{plugins:e,...t}=o.config;n=a(n,t)}(await p(a(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){h(t.logLevel).error(u.red(`error when starting preview server:\n${e.stack}`),{error:e}),process.exit(1)}finally{de(e=>h(t.logLevel).info(e))}}),ie.command("migrate [config]","migrate pp-dev config from 0.x flat format to 1.0 grouped format").option("--dry-run","[boolean] print migrated config without writing any files").option("--format <format>","[string] output format: ts (default), js, json").option("--output <file>","[string] output file path (default: pp-dev.config.ts)").option("--no-backup","[boolean] skip backup of original config file").action(async(o,n)=>{const i=h(n.logLevel),{isLegacyFlatConfig:s,isLegacyPPWatchConfig:r,isAlreadyMigrated:a,migrateLegacyFlatConfig:l,migratePPWatchConfig:c,generateConfigFileContent:d}=await import("./migrate-BYuCtRbI.js"),p=n.format??"ts",f=!1!==n.backup,g=process.cwd(),b=[".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 w=o??null,y=!1;if(!w){for(const o of m)if(t.existsSync(e.join(g,o))){w=e.join(g,o);break}if(!w)for(const o of b)if(t.existsSync(e.join(g,o))){w=e.join(g,o),y=!0;break}}w||(i.warn(u.yellow("No pp-dev or pp-watch config file found in the current directory.")),i.info(u.blue("Supported files: pp-dev.config.{ts,js,cjs,mjs,json}, .pp-watch.config.{ts,js,json}")),process.exit(1)),i.info(u.blue(`Found config: ${e.relative(g,w)}`));const{getPkg:v}=await import("./index-DOjGFYJ7.js").then(e=>e.e),x=v();let P,S={};try{if(/\.[cm]?ts$/i.test(w)){const o=await import("esbuild"),{pathToFileURL:n}=await import("url"),i=(await o.build({absWorkingDir:g,entryPoints:[w],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:"esm",mainFields:["main"]})).outputFiles[0].text,s=`pp-migrate-tmp-${Date.now()}.mjs`;t.writeFileSync(s,i);try{const t=await import(n(e.resolve(g,s)).toString());S=t.default?.default??t.default??t}finally{t.existsSync(s)&&t.unlinkSync(s)}}else if(/\.[cm]?js$/i.test(w)){const{pathToFileURL:t}=await import("url"),o=await import(t(e.resolve(g,w)).toString());S=o.default?.default??o.default??o}else w.endsWith(".json")&&(S=JSON.parse(t.readFileSync(w,"utf-8")))}catch(e){i.error(u.red(`Failed to load config file: ${e.message}`)),process.exit(1)}S&&"object"==typeof S||(i.error(u.red("Config file did not export a valid object.")),process.exit(1)),a(S)?(i.info(u.green("Config is already in 1.0 format — nothing to migrate.")),process.exit(0)):y||r(S)?(i.info(u.blue("Detected pp-watch config format → migrating to 1.0")),P=c(S)):s(S)?(i.info(u.blue("Detected 0.x flat config format → migrating to 1.0")),P=l(S,x.name)):(i.warn(u.yellow("Could not detect config format. No known keys found.")),process.exit(1));const T=d(P,p),k=n.output??e.join(g,`pp-dev.config.${p}`);if(n.dryRun&&(i.info(u.green(`\n--- Migrated config (dry-run) → ${e.relative(g,k)} ---\n`)),process.exit(0)),f&&t.existsSync(w)){const o=`${w}.bak`;t.copyFileSync(w,o),i.info(u.blue(`Backed up original to: ${e.relative(g,o)}`))}t.writeFileSync(k,T,"utf-8"),i.info(u.green(`✅ Migration complete → ${e.relative(g,k)}`)),w!==k&&t.existsSync(w)&&i.info(u.yellow(`You can now delete the old config: ${e.relative(g,w)}`))}),ie.help(),ie.version(b),ie.parse();export{de as stopProfiler};
2
2
  //# sourceMappingURL=cli.js.map