@metricinsights/pp-dev 1.5.0-beta.35 → 1.5.0-beta.36

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 (32) hide show
  1. package/README.md +17 -9
  2. package/dist/cjs/auth.provider-D5AI-ujG.js +2 -0
  3. package/dist/cjs/auth.provider-D5AI-ujG.js.map +1 -0
  4. package/dist/cjs/index.js +1 -1
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/plugin.js +1 -1
  7. package/dist/cjs/plugin.js.map +1 -1
  8. package/dist/cjs/{version-manifest-DdWlzzZ6.js → version-manifest-DuXhzqGr.js} +2 -2
  9. package/dist/cjs/{version-manifest-DdWlzzZ6.js.map → version-manifest-DuXhzqGr.js.map} +1 -1
  10. package/dist/cjs/version-plugin-DrG2-mQf.js +2 -0
  11. package/dist/cjs/{version-plugin-B1Sb07cW.js.map → version-plugin-DrG2-mQf.js.map} +1 -1
  12. package/dist/client/client.js +24 -18
  13. package/dist/client/client.js.map +1 -1
  14. package/dist/client/variables-editor.js +3 -0
  15. package/dist/client/variables-editor.js.map +1 -1
  16. package/dist/esm/cli.js +1 -1
  17. package/dist/esm/{internal.middleware-Dj2-HlRc.js → internal.middleware-wi0Mb4oZ.js} +2 -2
  18. package/dist/esm/internal.middleware-wi0Mb4oZ.js.map +1 -0
  19. package/dist/esm/plugin.js +1 -1
  20. package/package.json +6 -8
  21. package/dist/cjs/auth.provider-6rZUaR33.js +0 -2
  22. package/dist/cjs/auth.provider-6rZUaR33.js.map +0 -1
  23. package/dist/cjs/cli.js +0 -2
  24. package/dist/cjs/cli.js.map +0 -1
  25. package/dist/cjs/index-Cc-bAhnE.js +0 -2
  26. package/dist/cjs/index-Cc-bAhnE.js.map +0 -1
  27. package/dist/cjs/internal.middleware-CJSvsYId.js +0 -2
  28. package/dist/cjs/internal.middleware-CJSvsYId.js.map +0 -1
  29. package/dist/cjs/migrate-DDdeB-Fj.js +0 -2
  30. package/dist/cjs/migrate-DDdeB-Fj.js.map +0 -1
  31. package/dist/cjs/version-plugin-B1Sb07cW.js +0 -2
  32. package/dist/esm/internal.middleware-Dj2-HlRc.js.map +0 -1
package/README.md CHANGED
@@ -36,6 +36,10 @@ npm install next@^16
36
36
 
37
37
  **Note**: pp-dev accepts Next.js 13 to 16 (`peerDependencies`: `>= 13 < 17`); the test apps run on Next.js 16. It is a peer dependency, so it isn't installed with pp-dev.
38
38
 
39
+ ### Bundled build tools
40
+
41
+ pp-dev installs `sass` (SCSS in a portal page), and `sharp` and `svgo` (image optimization, `build.imageOptimisations`): a page uses them without listing them itself. A page that pins its own version of one lists it in its `package.json`.
42
+
39
43
  ## Package Structure
40
44
 
41
45
  The pp-dev package provides multiple entry points for different use cases:
@@ -337,13 +341,13 @@ The command detects flat 0.x configs and legacy `pp-watch.config.*` files, conve
337
341
 
338
342
  ### Global Options
339
343
 
340
- | Option | Description |
341
- | ------------------------ | -------------------------------------------------------------------------------- |
342
- | `-c, --config <file>` | Path to configuration file (default: `pp-dev.config.js`) |
343
- | `--base <path>` | Public base path (default: `/`) |
344
- | `-l, --logLevel <level>` | Log level: `trace`, `debug`, `info`, `warn`, `error`, `silent` (default: `info`) |
345
- | `--clearScreen` | Clear screen before logging |
346
- | `--mode <mode>` | Environment mode: `development`, `production`, `test` (default: `development`) |
344
+ | Option | Description |
345
+ | ------------------------ | ------------------------------------------------------------------------------ |
346
+ | `-c, --config <file>` | Path to configuration file (default: `pp-dev.config.js`) |
347
+ | `--base <path>` | Public base path (default: `/`) |
348
+ | `-l, --logLevel <level>` | Log level: `info`, `warn`, `error`, `silent` (default: `info`) |
349
+ | `--clearScreen` | Clear screen before logging |
350
+ | `--mode <mode>` | Environment mode: `development`, `production`, `test` (default: `development`) |
347
351
 
348
352
  ### Development Server
349
353
 
@@ -360,18 +364,22 @@ pp-dev [root] [options]
360
364
  | `--open [path]` | - | Open browser on server start |
361
365
  | `--strictPort` | - | Exit if port is already in use |
362
366
 
363
- **Development Shortcuts**:
367
+ **Development Shortcuts** (`h` lists them):
364
368
 
365
369
  - `l` - Proxy re-login (refresh authentication)
366
370
  - `r` - Restart dev server
367
371
  - `u` - Show server URLs
372
+ - `o` - Open the page in the browser
373
+ - `c` - Clear the console
374
+ - `C` - Clear the proxy cache
375
+ - `p` - Start/stop the CPU profiler (when started with `--profile`)
368
376
  - `q` - Quit dev server
369
377
 
370
378
  ### Next.js Development
371
379
 
372
380
  ```bash
373
381
  pp-dev next [options]
374
- # Aliases: pp-dev next-server, pp-dev next-dev
382
+ # Aliases: pp-dev next-serve, pp-dev next-dev
375
383
  ```
376
384
 
377
385
  | Option | Default | Description |
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("node:path"),t=require("fs"),i=require("path"),r=require("ejs"),s=require("url"),n=require("picocolors"),o=require("vite");var a="undefined"!=typeof document?document.currentScript:null;const p=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function d(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const i in e)t[i]=e[i];return t.default=e,Object.freeze(t)}const c=p(e),l=d(t),u=d(i),m=p(r);function h(e,t){if(!e||e.includes("\0")||c.posix.isAbsolute(e)||c.win32.isAbsolute(e)||c.win32.parse(e).root)throw new Error(`[pp-dev] ${t} must be a relative path inside its output directory.`);const i=c.posix.normalize(e.replace(/\\/g,"/"));if("."===i||".."===i||i.startsWith("../"))throw new Error(`[pp-dev] ${t} must stay inside its output directory.`);return i}function f(e){return h(`${e.replace(/^@/,"").replace(/[\\/]+/g,"-")}.zip`,"default ZIP output file name")}const v=["top-left","top-right","bottom-left","bottom-right"],g=2147483647;const P=s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("auth.provider-D5AI-ujG.js",document.baseURI).href),E=i.resolve(P,"../../.."),w=i.resolve(P,"../.."),_=t.existsSync(i.resolve(E,"package.json"))?E:w,b=i.resolve(_,"dist/client/client.js"),{version:y,name:x}=JSON.parse(t.readFileSync(i.resolve(_,"package.json")).toString()),A=y,D=x,T=u.dirname(b),R=u.join(T,"index.html");let L=null;const S={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};const j="info";let N,O;function I(){return N??={level:j,logger:o.createLogger(j)},N.logger}function C(e){return O??={info:(e,t)=>I().info(e,t),warn:(e,t)=>I().warn(e,t),warnOnce:(e,t)=>I().warnOnce(e,t),error:(e,t)=>I().error(e,t),clearScreen:e=>I().clearScreen(e),hasErrorLogged:e=>I().hasErrorLogged(e),get hasWarned(){return I().hasWarned},set hasWarned(e){I().hasWarned=e}},O}const k=n.createColors(),H=new Set(["GET","HEAD","OPTIONS"]);function V(e){return!0===e?[]:e.filter(e=>!e.startsWith("."))}function M(e,t=[]){const i=e.headers.origin,r=e.headers.host;if("string"==typeof i){if("null"===i)return'Origin "null" (a sandboxed or file:// page)';let e;try{e=new URL(i)}catch{return`unreadable Origin "${i}"`}if("localhost"===(s=e.hostname)||s.endsWith(".localhost")||"[::1]"===s||/^127(?:\.\d{1,3}){3}$/.test(s)||V(t).includes(e.hostname))return null;const n=r?function(e,t){try{return new URL(`${e}//${t}`).host}catch{return}}(e.protocol,r):void 0;return n&&e.host===n?null:`Origin ${e.origin} is neither this dev server (${r??"no Host"}) nor this machine`}var s;const n=e.headers["sec-fetch-site"];return H.has((e.method??"GET").toUpperCase())||"cross-site"!==n?null:"sent from a cross-site page"}class U{state={isAuthenticated:!1,isRedirected:!1};listeners=new Set;getState(){return{...this.state}}isAuthenticated(){return this.state.isAuthenticated}isRedirected(){return this.state.isRedirected}setAuthenticated(e){this.state.isAuthenticated=e,this.notifyListeners()}setRedirected(e){this.state.isRedirected=e,this.notifyListeners()}updateState(e){void 0!==e.isAuthenticated&&(this.state.isAuthenticated=e.isAuthenticated),void 0!==e.isRedirected&&(this.state.isRedirected=e.isRedirected),this.notifyListeners()}reset(){this.state={isAuthenticated:!1,isRedirected:!1},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{try{e(this.getState())}catch(e){C().error(`Error in auth state listener: ${e instanceof Error?e.stack??e.message:String(e)}`)}})}}const B=new U;exports.AuthProvider=U,exports.PACKAGE_NAME=D,exports.PATH_PAGE_PREFIX="/p",exports.PATH_TEMPLATE_LOCAL_PREFIX="/pl",exports.PATH_TEMPLATE_PREFIX="/pt",exports.PP_DEV_CLIENT_ENTRY=b,exports.PP_DEV_CONFIG_NAMES=[".pp-dev.config.js",".pp-dev.config.cjs",".pp-dev.config.mjs",".pp-dev.config.ts",".pp-dev.config.cts",".pp-dev.config.mts",".pp-dev.config.json","pp-dev.config.js","pp-dev.config.cjs","pp-dev.config.mjs","pp-dev.config.ts","pp-dev.config.cts","pp-dev.config.mts","pp-dev.config.json"],exports.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR="PP_DEV_NEXT_BUILD_DIST_DIR",exports.PP_DEV_NEXT_BUILD_ENV_VAR="PP_DEV_NEXT_BUILD",exports.PP_DEV_PACKAGE_DIR=_,exports.PP_DEV_PROJECT_ROOT_ENV_VAR="PP_DEV_PROJECT_ROOT",exports.authProvider=B,exports.colors=k,exports.createDefaultZipFileName=f,exports.createDevPanelAssetMiddleware=function(e){const t=u.posix.join(e,D,"client")+"/",i=new Set(["client.js","client.css","client.js.map","client.css.map"]);return(e,r,s)=>{const n=(e.url??"").split("?")[0];if(!n.startsWith(t))return void s();const o=n.slice(t.length);if(!i.has(o))return void s();const a=u.join(T,o);l.readFile(a,(e,t)=>{e?s():(r.statusCode=200,r.setHeader("Content-Type",S[u.extname(o)]??"application/octet-stream"),r.setHeader("Cache-Control","no-cache"),r.end(t))})}},exports.createLogger=C,exports.createOriginGuard=function(e=[]){return(t,i,r)=>{const s=M(t,e);s?i.status(403).json({error:`Blocked by pp-dev: ${s}.`}):r()}},exports.exactAllowedHosts=V,exports.getDevPanelAssetPaths=function(e){return{css:u.posix.join(e,D,"client/client.css"),js:u.posix.join(e,D,"client/client.js")}},exports.normalizePPDevConfig=function(e,t){const{mi:i={},app:r={},proxy:s={},build:n={},sync:o={},inspector:a={},devPanel:p={},users:d={},server:c={}}=e,l=i.mode??"standalone",u=r.type??"template",m=i.apiVersion??7,v="standalone"===l;let g=!1;"top-bar"===i.include?g=!0:"shared-components"===i.include&&(g={addSharedComponentsScripts:!0,addRootElement:!1});const P="page"===u,E=r.name??t;if(!E)throw new Error("[pp-dev] app.name is required (or set package.json#name)");const w="VERSION-v{packageversion}-{currentDate}.json";let _;const b=n.zip;let y;_=!1!==b&&(!0===b||void 0===b?{outFileName:f(E),outDir:"dist-zip"}:{outFileName:h(b.fileName??f(E),"build.zip.fileName"),outDir:b.outDir??"dist-zip",...b.inDir?{inDir:b.inDir}:{}});const x=n.versionFile;let A;y=!1!==x&&(!0===x||void 0===x?{versionFileTemplate:w,enabled:!0}:{versionFileTemplate:h(x.fileNameTemplate??w,"build.versionFile.fileNameTemplate"),enabled:x.enabled??!0});const D=n.imageOptimisations;return A=!1!==D&&(!0===D||void 0===D?{}:D),{templateName:E,backendBaseURL:i.url??process.env.MI_BACKEND_URL,appId:r.id,templateLess:P,miHudLess:v,integrateMiTopBar:g,enableProxyCache:s.cache??!0,proxyCacheTTL:s.cacheTtl??6e5,disableSSLValidation:s.tls?.allowSelfSigned??!1,imageOptimizer:A,outDir:n.outDir??"dist",distZip:_,versionPlugin:y,syncBackupsDir:o.backupsDir??"backups",syncMaxBackups:o.maxBackups,syncBuildTimeoutMs:o.buildTimeoutMs,v7Features:m>=7,personalAccessToken:i.token??process.env.MI_ACCESS_TOKEN,inspectorEnabled:a.enabled??!0,inspectorMaxMemory:a.maxMemory??1073741824,inspectorCaptureLimit:a.captureLimit??10485760,devPanelPosition:p.position??"bottom-right",devPanelHidden:p.hidden??!1,devPanelAutoHide:p.autoHide??!1,persistUsers:d.persist??!1,allowedHosts:!0===c.allowedHosts||(c.allowedHosts??[]).map(e=>e.trim().toLowerCase())}},exports.normalizeRelativeOutputPath=h,exports.renderDevPanelMarkup=function(e){return function(){if(L)return L;const e=l.readFileSync(R,{encoding:"utf8"});return L=m.compile(e,{openDelimiter:"{",closeDelimiter:"}",async:!1,rmWhitespace:!0,compileDebug:!1}),L}()({PACKAGE_NAME:D,VERSION:A,backendBaseURL:e.backendBaseURL,templateLess:e.templateLess,appId:e.appId,canSync:e.canSync??!0,devPanelPosition:e.devPanelPosition??"bottom-right",devPanelHidden:e.devPanelHidden??!1,devPanelAutoHide:e.devPanelAutoHide??!1})},exports.resolveOutputFilePath=function(e,t,i){const r=h(t,i),s=c.resolve(e),n=c.resolve(s,...r.split("/")),o=c.relative(s,n);if(".."===o||o.startsWith(`..${c.sep}`)||c.isAbsolute(o))throw new Error(`[pp-dev] ${i} must resolve inside its output directory.`);return n},exports.validatePPDevConfig=function(e,t){const i=e.mi?.mode??"standalone",r=e.app?.type??"template",s=e.mi?.apiVersion??7,n=e.mi?.url??process.env.MI_BACKEND_URL;if(!(e.app?.name??t))throw new Error("[pp-dev] app.name is required (or set package.json#name)");const o=e.sync?.maxBackups;if(void 0!==o&&!1!==o&&!(Number.isInteger(o)&&o>=0))throw new Error(`[pp-dev] sync.maxBackups must be a whole number ≥ 0 or false (0 and false keep every backup), got ${JSON.stringify(o)}`);const a=e.sync?.buildTimeoutMs;if(void 0!==a&&!(Number.isInteger(a)&&a>0&&a<=g))throw new Error(`[pp-dev] sync.buildTimeoutMs must be a whole number of milliseconds between 1 and 2147483647, got ${JSON.stringify(a)}`);if(e.mi?.include&&"standalone"!==i)throw console.warn('[pp-dev] mi.include is only valid when mi.mode is "standalone"'),new Error('[pp-dev] mi.include requires mi.mode to be "standalone"');if(!n){if("embedding"===i||"template"===r)throw new Error('[pp-dev] mi.url is required when mi.mode is "embedding" or app.type is "template"');"standalone"===i&&"page"===r&&console.warn("[pp-dev] mi.url is not set — dev server will run without a backend proxy")}if("template"===r&&!e.app?.id)throw new Error('[pp-dev] app.id is required when app.type is "template"');if("page"===r&&n&&("standalone"===i||s>=7)&&!e.app?.id)throw new Error('[pp-dev] app.id is required when backend page data is loaded for app.type "page"');if(void 0!==e.devPanel?.position&&!v.includes(e.devPanel.position))throw new Error(`[pp-dev] devPanel.position must be one of: ${v.join(", ")}`);const p=e.server?.allowedHosts;if(!(void 0===p||!0===p||Array.isArray(p)&&p.every(e=>"string"==typeof e&&""!==e.trim())))throw new Error(`[pp-dev] server.allowedHosts must be a list of host names or true, got ${JSON.stringify(p)}`)};
2
+ //# sourceMappingURL=auth.provider-D5AI-ujG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.provider-D5AI-ujG.js","sources":["../../../src/lib/output-path.ts","../../../src/lib/pp-dev-config.ts","../../../src/constants.ts","../../../src/lib/dev-panel.ts","../../../src/lib/logger.ts","../../../src/lib/helpers/color.helper.ts","../../../src/lib/helpers/origin-guard.ts","../../../src/lib/auth.provider.ts"],"sourcesContent":[null,null,null,null,null,null,null,null],"names":["normalizeRelativeOutputPath","relativePath","optionName","includes","path","posix","isAbsolute","win32","parse","root","Error","normalized","normalize","replace","startsWith","createDefaultZipFileName","appName","DEV_PANEL_POSITIONS","MAX_TIMER_DELAY_MS","modulePath","fileURLToPath","afterBundlePath","resolve","beforeBundlePath","PP_DEV_PACKAGE_DIR","existsSync","PP_DEV_CLIENT_ENTRY","version","name","JSON","readFileSync","toString","VERSION","PACKAGE_NAME","CLIENT_DIST_DIR","dirname","TEMPLATE_PATH","join","compiledTemplate","CONTENT_TYPES","DEFAULT_LEVEL","current","shared","active","level","logger","createViteLogger","createLogger","info","msg","options","warn","warnOnce","error","clearScreen","type","hasErrorLogged","hasWarned","value","colors","createColors","SAFE_METHODS","Set","exactAllowedHosts","allowedHosts","filter","host","crossOriginReason","req","origin","headers","originUrl","URL","hostname","endsWith","test","requestHost","scheme","normalizeHost","protocol","undefined","fetchSite","has","method","toUpperCase","AuthProvider","state","isAuthenticated","isRedirected","listeners","getState","this","setAuthenticated","authenticated","notifyListeners","setRedirected","redirected","updateState","updates","reset","subscribe","listener","add","delete","forEach","stack","message","String","authProvider","base","assetPrefix","allowed","res","next","pathname","url","split","fileName","slice","length","filePath","fs","readFile","err","content","statusCode","setHeader","extname","end","reason","status","json","css","js","config","templateName","mi","app","proxy","build","sync","inspector","devPanel","users","server","miMode","mode","appType","apiVersion","miHudLess","integrateMiTopBar","include","addSharedComponentsScripts","addRootElement","templateLess","resolvedName","defaultVersionFileTemplate","distZip","zipCfg","zip","versionPlugin","outFileName","outDir","inDir","vfCfg","versionFile","imageOptimizer","versionFileTemplate","enabled","fileNameTemplate","imgCfg","imageOptimisations","backendBaseURL","process","env","MI_BACKEND_URL","appId","id","enableProxyCache","cache","proxyCacheTTL","cacheTtl","disableSSLValidation","tls","allowSelfSigned","syncBackupsDir","backupsDir","syncMaxBackups","maxBackups","syncBuildTimeoutMs","buildTimeoutMs","v7Features","personalAccessToken","token","MI_ACCESS_TOKEN","inspectorEnabled","inspectorMaxMemory","maxMemory","inspectorCaptureLimit","captureLimit","devPanelPosition","position","devPanelHidden","hidden","devPanelAutoHide","autoHide","persistUsers","persist","map","trim","toLowerCase","data","templateContent","encoding","ejs","compile","openDelimiter","closeDelimiter","async","rmWhitespace","compileDebug","getTemplate","template","canSync","directory","safeRelativePath","resolvedDirectory","resolvedFile","relativeToDirectory","relative","sep","miUrl","Number","isInteger","stringify","console","Array","isArray","every"],"mappings":"odAOM,SAAUA,EAA4BC,EAAsBC,GAChE,IACGD,GACDA,EAAaE,SAAS,OACtBC,EAAKC,MAAMC,WAAWL,IACtBG,EAAKG,MAAMD,WAAWL,IACtBG,EAAKG,MAAMC,MAAMP,GAAcQ,KAE/B,MAAM,IAAIC,MAAM,YAAYR,0DAG9B,MAAMS,EAAaP,EAAKC,MAAMO,UAAUX,EAAaY,QAAQ,MAAO,MAEpE,GAAmB,MAAfF,GAAqC,OAAfA,GAAuBA,EAAWG,WAAW,OACrE,MAAM,IAAIJ,MAAM,YAAYR,4CAG9B,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,KAA0B4C,OAAOC,UAAU7C,IAAeA,GAAc,GACtG,MAAM,IAAIlL,MACR,qGAAqGmB,KAAK6M,UAAU9C,MAIxH,MAAME,EAAiBxD,EAAOM,MAAMkD,eAIpC,QACqB9G,IAAnB8G,KACE0C,OAAOC,UAAU3C,IAAmBA,EAAiB,GAAKA,GAAkB5K,GAE9E,MAAM,IAAIR,MACR,qGAAgHmB,KAAK6M,UAAU5C,MAInI,GAAIxD,EAAOE,IAAIe,SAAsB,eAAXN,EAExB,MADA0F,QAAQxL,KAAK,kEACP,IAAIzC,MAAM,2DAGlB,IAAK6N,EAAO,CACV,GAAe,cAAXtF,GAAsC,aAAZE,EAC5B,MAAM,IAAIzI,MAAM,qFAGH,eAAXuI,GAAuC,SAAZE,GAC7BwF,QAAQxL,KAAK,2EAEjB,CAEA,GAAgB,aAAZgG,IAA2Bb,EAAOG,KAAKwC,GACzC,MAAM,IAAIvK,MAAM,2DAKlB,GAFsC,SAAZyI,GAAsBoF,IAAqB,eAAXtF,GAA2BG,GAAc,KAEzEd,EAAOG,KAAKwC,GACpC,MAAM,IAAIvK,MAAM,oFAGlB,QAAkCsE,IAA9BsD,EAAOQ,UAAU2D,WAA2BxL,EAAoBd,SAASmI,EAAOQ,SAAS2D,UAC3F,MAAM,IAAI/L,MAAM,8CAA8CO,EAAoBoB,KAAK,SAGzF,MAAM2B,EAAwBsE,EAAOU,QAAQhF,aAE7C,UACmBgB,IAAjBhB,IACiB,IAAjBA,GACE4K,MAAMC,QAAQ7K,IAAiBA,EAAa8K,MAAO5K,GAAyB,iBAATA,GAAqC,KAAhBA,EAAK+I,SAE/F,MAAM,IAAIvM,MACR,0EAA0EmB,KAAK6M,UAAU1K,KAG/F"}
package/dist/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";require("child_process");const e=require("./auth.provider-6rZUaR33.js"),r=require("./index-Cc-bAhnE.js"),i=require("./helpers.js");require("picocolors"),require("node:path"),require("fs"),require("path"),require("ejs"),require("url"),require("node:net"),require("vite"),require("node:module"),exports.AuthProvider=e.AuthProvider,exports.authProvider=e.authProvider,exports.normalizePPDevConfig=e.normalizePPDevConfig,exports.validatePPDevConfig=e.validatePPDevConfig,exports.getNextVersion=r.getNextVersion,exports.getPPDevConfigFromNextConfig=r.getPPDevConfigFromNextConfig,exports.getViteConfig=r.getViteConfig,exports.isNextAvailable=r.isNextAvailable,exports.safeNextImport=r.safeNextImport,exports.withPPDev=r.withPPDev,exports.defineConfig=i.defineConfig;
1
+ "use strict";const e=require("child_process"),t=require("./auth.provider-D5AI-ujG.js"),n=require("node:module"),r=require("vite"),i=require("fs"),o=require("path"),s=require("url"),a=require("./helpers.js");require("node:path"),require("ejs"),require("picocolors");var c="undefined"!=typeof document?document.currentScript:null;const p=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function l(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const n in e)t[n]=e[n];return t.default=e,Object.freeze(t)}const u=l(o),f=p(o),d=r.normalizePath(u.join(t.PP_DEV_PACKAGE_DIR,"dist/client")),m=new RegExp(`^\\/?${t.PACKAGE_NAME}\\/client\\/(.*)$`);const v=(e,t)=>` * ${t}`;function g(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,v)}\n */`}async function P(){try{const[e,t]=await Promise.all([import("next"),import("next/constants.js")]);return{next:e.default,constants:t}}catch(e){throw new Error(`Next.js is required but not available. Please install Next.js as a dependency:\nnpm install next@^15\n\nThis package requires Next.js >=15 <17 as a peer dependency.\n\nError: ${e}`)}}const _=()=>n.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:c&&"SCRIPT"===c.tagName.toUpperCase()&&c.src||new URL("index.js",document.baseURI).href);let h=new Set;const E=Symbol.for("@metricinsights/pp-dev:withPPDev");const y=new Map,T=new Map;function j(e=process.cwd()){const t=Date.now(),n=f.resolve(e),r=T.get(n);if(r&&t-r.timestamp<6e4)return r.data;try{const e=JSON.parse(i.readFileSync(f.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return T.set(n,{data:e,timestamp:t}),e}catch{const e={};return T.set(n,{data:e,timestamp:t}),e}}let D=null;const R="__pp_dev_injected_dirname",w="__pp_dev_injected_filename",b="__pp_dev_injected_import_meta_url",I={__dirname:R,__filename:w,"import.meta.url":b,"import.meta.dirname":R,"import.meta.filename":w},O={name:"pp-dev:config-module-location",setup(e){e.onLoad({filter:/\.([cm]?[jt]s|[jt]sx)$/},e=>{const t=i.readFileSync(e.path,"utf-8").replace(/^#![^\r\n]*/,"");return{contents:`const ${R} = ${JSON.stringify(f.dirname(e.path))};const ${w} = ${JSON.stringify(e.path)};const ${b} = ${JSON.stringify(s.pathToFileURL(e.path).href)};`+t,loader:e.path.endsWith(".tsx")?"tsx":e.path.endsWith(".jsx")?"jsx":/ts$/.test(e.path)?"ts":"js"}})}};async function $(e,t){const n=`bundled:${e}`,r=y.get(n);if(r&&Date.now()-r.timestamp<3e4)return r.data;let o=!1;if(/\.m[jt]s$/.test(e))o=!0;else if(/\.c[jt]s$/.test(e))o=!1;else{const e=j(t);o=!!e&&"module"===e.type}const a=await async function(){return D||(D=await(import("esbuild"))),D}(),c=await a.build({absWorkingDir:t,entryPoints:[e],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:o?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0,plugins:[O],define:I,...o?{banner:{js:"import { createRequire as __ppDevCreateRequire } from 'node:module';const require = __ppDevCreateRequire(import.meta.url);"}}:{}}),{text:p}=c.outputFiles[0],l=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.${o?"mjs":"cjs"}`,u=f.resolve(t,l),d=s.pathToFileURL(u).toString();i.writeFileSync(u,p);let m={};try{const t=(await(import(d))).default;m=t?.default||t,y.set(n,{data:m,timestamp:Date.now(),filePath:e})}finally{try{i.unlinkSync(u)}catch{}}return m}async function A(e){const t=`json:${e}`,n=y.get(t);if(n&&Date.now()-n.timestamp<3e4)return n.data;const r=JSON.parse(i.readFileSync(e,{encoding:"utf-8"}));return y.set(t,{data:r,timestamp:Date.now(),filePath:e}),r}const N=new Map;function x(e=process.cwd()){return j(e)}async function S(e=process.cwd()){return(await async function(e=process.cwd()){const n=f.resolve(e),r=function(e){const t=Date.now(),n=N.get(e);if(n&&t-n.timestamp<1e4)return n.files;const r=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,o=i.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isFile()&&r.test(e.name)).map(e=>e.name);return N.set(e,{files:o,timestamp:t}),o}(n),o=t.PP_DEV_CONFIG_NAMES,s=o.some(e=>r.includes(e)),a=j(n),c=Object.prototype.hasOwnProperty.call(a,"pp-dev"),p=s?await async function(e,t,n){for(const r of t)if(e.includes(r)){const e=f.resolve(n,r);if(/\.[cm]?[jt]s$/i.test(r))return await $(e,n);if(r.endsWith(".json"))return await A(e)}return null}(r,o,n):null;if(p)return{config:p,found:!0};const l=a["pp-dev"];if(l&&"object"==typeof l&&!Array.isArray(l))return{config:l,found:!0};return{config:{},found:s||c}}(e)).config}const F=new Set(["mi","app","proxy","build","sync","inspector","devPanel","users","server"]);function C(t){if("string"==typeof t)return t;if(t&&"object"==typeof t&&"url"in t&&"string"==typeof t.url)return t.url;const n=["CI_REPOSITORY_URL","GIT_URL","BUILD_REPOSITORY_URI","CI_PROJECT_URL","BITBUCKET_GIT_HTTP_ORIGIN","BUILDKITE_REPO"];for(const e of n){const t=process.env[e];if("string"==typeof t&&t.trim())return t}const r=process.env.GITHUB_REPOSITORY;if("string"==typeof r&&r.trim()){return`${(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${r.replace(/^\/+/,"")}`}const i=process.env.CI_PROJECT_PATH;if("string"==typeof i&&i.trim()){return`${(process.env.CI_SERVER_URL||"https://gitlab.com").replace(/\/+$/,"")}/${i.replace(/^\/+/,"")}`}const o=process.env.BITBUCKET_REPO_FULL_NAME;if("string"==typeof o&&o.trim())return`https://bitbucket.org/${o.replace(/^\/+/,"")}`;const s=process.env.TRAVIS_REPO_SLUG;if("string"==typeof s&&s.trim())return`https://github.com/${s.replace(/^\/+/,"")}`;try{const t=e.execSync("git config --get remote.origin.url",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t)return t}catch{}}function L(e){return e?.ppDev||{}}exports.AuthProvider=t.AuthProvider,exports.authProvider=t.authProvider,exports.normalizePPDevConfig=t.normalizePPDevConfig,exports.validatePPDevConfig=t.validatePPDevConfig,exports.defineConfig=a.defineConfig,exports.getNextVersion=async function(){try{const e=_()("next/package.json");return"string"==typeof e.version?e.version:null}catch{return null}},exports.getPPDevConfigFromNextConfig=L,exports.getViteConfig=async function(e,n={}){const i=n.root??process.cwd();!function(e="development",t=process.cwd()){for(const e of h)delete process.env[e];const n=new Set(Object.keys(process.env).filter(e=>e.startsWith("MI_"))),i=r.loadEnv(e,t,"MI_");for(const[e,t]of Object.entries(i))process.env[e]=t;h=new Set(Object.keys(i).filter(e=>!n.has(e)))}(n.mode,i);const o=x(i),s=await S(i);t.validatePPDevConfig(s,o.name);const a=t.normalizePPDevConfig(s,o.name),{templateName:c}=a;e&&(a.distZip=function(e,n,r){if(!1===n.distZipEnabled)return!1;if(!0!==n.distZipEnabled&&void 0===n.distZipDir&&void 0===n.distZipFilename)return!1!==e&&{...e,outFileName:t.normalizeRelativeOutputPath(e.outFileName,"ZIP output file name")};const i=!1===e?{outFileName:r,outDir:"dist-zip"}:e,o=n.distZipFilename??i.outFileName;return{...i,...void 0!==n.distZipDir?{outDir:n.distZipDir}:{},outFileName:t.normalizeRelativeOutputPath(o,"ZIP output file name")}}(a.distZip,e,t.createDefaultZipFileName(c)),a.versionPlugin=function(e,n){if(!1===n.versionManifestEnabled)return!1;if(!0!==n.versionManifestEnabled&&void 0===n.versionFileTemplate)return!1!==e&&void 0!==e.versionFileTemplate?{...e,versionFileTemplate:t.normalizeRelativeOutputPath(e.versionFileTemplate,"VERSION file name template")}:e;const r=!1===e?{enabled:!0}:e,i=n.versionFileTemplate??r.versionFileTemplate,o=void 0!==i?t.normalizeRelativeOutputPath(i,"VERSION file name template"):void 0;return{...r,enabled:!0,...void 0!==o?{versionFileTemplate:o}:{}}}(a.versionPlugin,e));const{default:p}=await Promise.resolve().then(()=>require("./plugin.js")),l=[p(a),{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${t.PACKAGE_NAME}/client`),e),resolveId(e){const t=e.match(m);if(t){const e=r.normalizePath(u.join(d,t[1]));return e.startsWith(`${d}/`)?{id:e}:null}},transformIndexHtml:async(e,n)=>{const r=n.server?.config.base||"",i=t.getDevPanelAssetPaths(r),o={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:i.css}}]},{templateLess:s=!1,...a}=n.server?.config.clientInjectionPlugin||{};return o.tags.push({tag:"div",injectTo:"body-prepend",children:t.renderDevPanelMarkup({templateLess:s,...a})}),o.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:i.js,type:"module"}}),o},configureServer(e){const n=r.normalizePath(u.resolve(e.config.root,u.dirname(t.PP_DEV_CLIENT_ENTRY)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(n)}}],{outDir:f,distZip:v,versionPlugin:P,imageOptimizer:_,templateLess:E,integrateMiTopBar:y,allowedHosts:T}=a;if(y&&l.push(function(e){return{name:"mi-topbar-plugin",transformIndexHtml(){const t=[];return(!0===e||"object"==typeof e&&!0===e.addRootElement)&&t.push({tag:"div",injectTo:"body-prepend",attrs:{id:"mi-react-root"}}),(!0===e||"object"==typeof e&&!0===e.addSharedComponentsScripts)&&t.push({tag:"script",injectTo:"head-prepend",attrs:{src:"/auth/info.js"}},{tag:"script",injectTo:"head-prepend",attrs:{src:"/js/main.js",defer:"defer"}},{tag:"link",injectTo:"head-prepend",attrs:{href:"/css/main.css",rel:"stylesheet"}}),t}}}(y)),_){const{ViteImageOptimizer:e}=await(import("vite-plugin-image-optimizer"));l.push(e("object"==typeof _?_:void 0))}if(P){const{versionPlugin:e}=await Promise.resolve().then(()=>require("./version-plugin-DrG2-mQf.js"));l.push(e({outDir:f,packageVersion:o.version??"0.0.0",packageRepositoryUrl:C(o.repository),..."object"==typeof P?P:{}}))}if(v){const{default:e}=await(import("vite-plugin-zip-pack"));l.push({...e("object"==typeof v?v:{outFileName:t.createDefaultZipFileName(c)}),enforce:"post"})}return{base:E?`${t.PATH_PAGE_PREFIX}/${c}`:`${t.PATH_TEMPLATE_PREFIX}/${c}`,server:{port:3e3,...!0===T||T.length>0?{allowedHosts:T}:{}},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:g}},outDir:f},css:{modules:{localsConvention:"dashes"}},ppDevConfig:a,plugins:l}},exports.isNextAvailable=async function(){try{return _().resolve("next"),!0}catch{return!1}},exports.safeNextImport=P,exports.withPPDev=function(e,n){return async(r,i={})=>{try{const{constants:s}=await P(),{PHASE_DEVELOPMENT_SERVER:a,PHASE_PRODUCTION_BUILD:c}=s;r!==c||process.env[t.PP_DEV_NEXT_BUILD_ENV_VAR]||t.createLogger().warn(t.colors.yellow('⚠ Building with plain `next build`. Use `pp-dev next-build` instead to get VERSION/BUILD-MANIFEST/zip build output in the same format as `pp-dev build` (see the "Next.js Build" section in the pp-dev README).'));const p=process.env[t.PP_DEV_PROJECT_ROOT_ENV_VAR]||process.cwd(),l=await S(p),u=x(p).name,f="function"==typeof e?await e(r,i):e,d=function(...e){const t={},n=t;for(const t of e)if(t)for(const[e,r]of Object.entries(t))void 0!==r&&(F.has(e)&&r&&"object"==typeof r&&!Array.isArray(r)?n[e]={...n[e]??{},...r}:n[e]=r);return t}(l,L(f),n);t.validatePPDevConfig(d,u);const m=t.normalizePPDevConfig(d,u),{templateLess:v,v7Features:g}=m,_=r===a,h=function(e,n,r,i){return r?i?n?`${t.PATH_PAGE_PREFIX}/${e}`:`${t.PATH_TEMPLATE_LOCAL_PREFIX}/${e}`:n?`${t.PATH_PAGE_PREFIX}/${e}`:`${t.PATH_TEMPLATE_PREFIX}/${e}`:`${t.PATH_PAGE_PREFIX}/${e}`}(m.templateName,v,_,g),y={basePath:h,trailingSlash:!!_||void 0};if(!v){const e=_&&g?t.PATH_TEMPLATE_LOCAL_PREFIX:t.PATH_TEMPLATE_PREFIX;y.assetPrefix=`${e}/${m.templateName}`}const T=Object.assign({},y,f),j=t.exactAllowedHosts(m.allowedHosts);_&&j.length>0&&(T.allowedDevOrigins=[...T.allowedDevOrigins??[],...j]);const D=process.env[t.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR];return r===c&&D&&(T.distDir=D),Object.defineProperty(T,"ppDev",{value:d,enumerable:!1,configurable:!0}),Object.defineProperty(T,"ppDevWrapped",{value:!0,enumerable:!1,configurable:!0}),o={ppDev:d,wrapped:!0},globalThis[E]=o,T}catch(e){throw t.createLogger().error("Error in withPPDev:",{error:e instanceof Error?e:new Error(String(e))}),e}var o}};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
1
+ {"version":3,"file":"index.js","sources":["../../../src/plugins/client-injection-plugin.ts","../../../src/banner/header.ts","../../../src/lib/next-import.ts","../../../src/lib/env.ts","../../../src/lib/next-config-handoff.ts","../../../src/config.ts","../../../src/index.ts","../../../src/lib/build-cli-overrides.ts","../../../src/plugins/mi-topbar-plugin.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null],"names":["CLIENT_DIST_DIR","normalizePath","path","join","PP_DEV_PACKAGE_DIR","PACKAGE_REGEXP","RegExp","PACKAGE_NAME","replacer","substring","$1","header","_chunk","replace","async","safeNextImport","next","constants","Promise","all","default","error","Error","requireFromPPDev","createRequire","previouslyLoadedKeys","Set","HANDOFF_KEY","Symbol","for","configCache","Map","packageJsonCache","getPackageJson","projectRoot","process","cwd","now","Date","root","resolve","cached","get","timestamp","data","JSON","parse","readFileSync","encoding","flag","set","empty","esbuildModule","MODULE_LOCATION","MODULE_LOCATION_DEFINE","__dirname","__filename","moduleLocationPlugin","name","setup","build","onLoad","filter","args","contents","stringify","dirname","pathToFileURL","href","loader","endsWith","test","loadBundledConfig","filePath","cacheKey","isESM","pkg","type","esbuild","getEsbuild","result","absWorkingDir","entryPoints","outfile","write","target","platform","bundle","packages","format","mainFields","sourcemap","metafile","plugins","define","banner","js","text","code","outputFiles","fileNameTmp","Math","random","toString","slice","tempFilePath","fileUrl","writeFileSync","config","conf","unlinkSync","loadJSONConfig","dirContentCache","getPkg","getConfig","dirContent","files","endsWithRegExp","readdirSync","withFileTypes","value","isFile","map","getDirectoryContent","configNames","PP_DEV_CONFIG_NAMES","hasConfigFile","some","includes","hasPackageConfig","Object","prototype","hasOwnProperty","call","newConfig","dirFiles","configName","configPath","loadConfig","found","packageConfig","Array","isArray","findConfig","PP_DEV_CONFIG_GROUPS","resolveRepositoryUrl","repository","url","directCiRepositoryUrlEnvVars","variableName","ciRepositoryUrl","env","trim","githubRepository","GITHUB_REPOSITORY","GITHUB_SERVER_URL","gitlabProjectPath","CI_PROJECT_PATH","CI_SERVER_URL","bitbucketRepositoryFullName","BITBUCKET_REPO_FULL_NAME","travisRepositorySlug","TRAVIS_REPO_SLUG","gitRemoteOriginUrl","execSync","stdio","getPPDevConfigFromNextConfig","nextConfig","ppDev","nextPkg","version","overrides","environment","mode","envDir","key","fromEnvironment","keys","startsWith","loadEnv","entries","has","loadPPDevEnv","ppDevConfig","validatePPDevConfig","normalizedPPDevConfig","normalizePPDevConfig","templateName","distZip","base","defaultFileName","distZipEnabled","undefined","distZipDir","distZipFilename","outFileName","normalizeRelativeOutputPath","baseConfig","outDir","applyDistZipOverride","createDefaultZipFileName","versionPlugin","versionManifestEnabled","versionFileTemplate","enabled","normalizedVersionFileTemplate","applyVersionManifestOverride","vitePPDev","then","require","apply","optimizeDeps","exclude","push","resolveId","source","match","resolvedId","id","transformIndexHtml","html","ctx","server","assetPaths","getDevPanelAssetPaths","tags","tag","injectTo","attrs","rel","css","templateLess","panelOptions","clientInjectionPlugin","children","renderDevPanelMarkup","src","configureServer","clientDir","PP_DEV_CLIENT_ENTRY","fs","allow","imageOptimizer","integrateMiTopBar","allowedHosts","addRootElement","addSharedComponentsScripts","defer","miTopBarPlugin","ViteImageOptimizer","versionPluginFn","packageVersion","packageRepositoryUrl","zipPack","enforce","PATH_PAGE_PREFIX","PATH_TEMPLATE_PREFIX","port","length","minify","assetsInlineLimit","rollupOptions","output","modules","localsConvention","nextjsConfig","phase","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_BUILD","PP_DEV_NEXT_BUILD_ENV_VAR","createLogger","warn","colors","yellow","PP_DEV_PROJECT_ROOT_ENV_VAR","nextConfiguration","mergedConfig","configs","merged","mutableMerged","mergePPDevConfigs","normalized","v7Features","isDevelopment","basePath","PATH_TEMPLATE_LOCAL_PREFIX","createBasePath","trailingSlash","prefix","assetPrefix","assign","tunnelOrigins","exactAllowedHosts","allowedDevOrigins","buildDistDir","PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR","distDir","defineProperty","enumerable","configurable","handoff","wrapped","globalThis","String"],"mappings":"ujBAuBMA,EAAkBC,EAAAA,cAAcC,EAAKC,KAAKC,EAAAA,mBAAoB,gBAC9DC,EAAiB,IAAIC,OAAO,QAAQC,EAAAA,iCCtB1C,MAIMC,EAAW,CAACC,EAAmBC,IAAe,MAAYA,IAElD,SAAAC,EAAWC,GAIvB,MAAO,QAHS,0DAGUC,QAAQ,WAAYL,SAChD,CCKOM,eAAeC,IACpB,IACE,MAAOC,EAAMC,SAAmBC,QAAQC,IAAI,QAAQ,eAAgB,uBAEpE,MAAO,CACLH,KAAMA,EAAKI,QACXH,YAEJ,CAAE,MAAOI,GACP,MAAM,IAAIC,MAIN,kLAAUD,IAEhB,CACF,CAGA,MAAME,EAAmB,IAAMC,EAAAA,kLCnC/B,IAAIC,EAAuB,IAAIC,ICe/B,MAAMC,EAAcC,OAAOC,IAAI,oCCF/B,MAAMC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AO1R,MAEzFA,CACR,CFvbE,IAAiCuR,EEybvC"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const e=require("./internal.middleware-CJSvsYId.js"),r=require("./auth.provider-6rZUaR33.js");function i(i){const{templateName:s,templateLess:t,backendBaseURL:o,miHudLess:n,appId:a,enableProxyCache:d,proxyCacheTTL:l,disableSSLValidation:u,outDir:c,distZip:p,versionPlugin:m,syncBackupsDir:v,syncMaxBackups:q,syncBuildTimeoutMs:f,v7Features:g,personalAccessToken:h,inspectorEnabled:P,inspectorMaxMemory:b,inspectorCaptureLimit:y,devPanelPosition:x,devPanelHidden:L,devPanelAutoHide:j,persistUsers:w,allowedHosts:S}=i||{};let k=!0;const M=new WeakMap;return{name:"vite-pp-dev",apply:"serve",closeBundle(){M.get(this.environment)?.dispose(),M.delete(this.environment)},config:e=>(e.clientInjectionPlugin={backendBaseURL:o,appId:a,templateLess:t,v7Features:g,devPanelPosition:x,devPanelHidden:L,devPanelAutoHide:j},g&&(e.base=`/pl/${s}`),e),transformIndexHtml:async(e,r)=>{const i={html:e,tags:[]};return k&&(k=!1,i.tags.push({tag:"script",injectTo:"body",children:`${Math.random()}`})),i},configureServer:i=>{let x=i.config.base;x.endsWith("/")||(x+="/");const L=e.createInternalServer({allowedHosts:S}),j=e.createMiddlewareChain({base:x,templateName:s,internalServer:L,backendBaseURL:o,mi:{appId:a,templateLess:t,miHudLess:n,disableSSLValidation:u,v7Features:g,personalAccessToken:h},inspector:{enabled:!1!==P,maxMemory:b,captureLimit:y},proxy:{cache:d,cacheTtl:l,devServer:i},rewrite:(r,i)=>({predicate:e=>e.split("?")[0].endsWith("index.html"),transform:(s,t)=>Buffer.from(e.urlReplacer(i,t.headers.host??"",r.buildPage(s,n)))})});if(e.mountMiddlewareChain(i,j),o&&j.mi){const t=j.mi;i.config.logger.info(r.colors.blue(`🌐 Backend URL: ${o}`)),i.config.logger.info(r.colors.blue(`🆔 Custom App ID: ${a}`));const n=new e.DistService(s,Object.assign({root:i.config.root,backupFolder:v,maxBackups:q,buildTimeoutMs:f,buildInputFolder:"object"==typeof p?p.inDir??c:c},"object"==typeof m?{versionFileTemplate:m.versionFileTemplate}:void 0)),d=e.startSyncAndUsers({server:i,internalServer:L,distService:n,miAPI:t,persistUsers:w,projectRoot:i.config.root||process.cwd(),miUrl:o});M.set(i.environments.client,d)}const{rewrite:k}=j;if(k)return()=>{i.middlewares.use(k)}}}}require("axios"),require("node:http"),require("node:https"),require("./version-manifest-DdWlzzZ6.js"),require("crypto"),require("child_process"),require("fs/promises"),require("path"),require("url"),require("util"),require("node:module"),require("http-proxy-middleware"),require("node:string_decoder"),require("zlib"),require("fs"),require("node:crypto"),require("process"),require("os"),require("jszip"),require("node:fs"),require("node:fs/promises"),require("module"),require("node:os"),require("node:path"),require("express"),require("picocolors"),require("ejs"),require("node:net"),require("vite"),exports.normalizePPDevConfig=r.normalizePPDevConfig,exports.validatePPDevConfig=r.validatePPDevConfig,exports.default=i,exports.vitePPDev=i;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const e=require("url"),t=require("path"),s=require("fs"),r=require("crypto"),n=require("process"),i=require("os"),a=require("./auth.provider-D5AI-ujG.js"),o=require("./version-manifest-DuXhzqGr.js"),c=require("jszip"),l=require("node:fs"),d=require("node:fs/promises"),u=require("node:crypto"),p=require("child_process"),h=require("module"),g=require("express"),m=require("axios"),f=require("http-proxy-middleware"),y=require("node:string_decoder"),w=require("node:os"),v=require("node:path"),b=require("node:http"),k=require("node:https"),$=require("zlib");require("ejs"),require("picocolors"),require("vite"),require("fs/promises"),require("util"),require("node:module");var S="undefined"!=typeof document?document.currentScript:null;const x=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function A(e){if(e&&"object"==typeof e&&"default"in e)return e;const t=Object.create(null);if(e)for(const s in e)t[s]=e[s];return t.default=e,Object.freeze(t)}const T=A(t),E=A(s),I=A(r),P=A(n),L=A(i),j=x(c),N=A(l),R=x(l),B=A(d),C=A(p),F=x(g),M=x(m),O=x(w),D=x(v),U=x(b),_=x(k),H=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),V=new Map,q=new Map;const z=(e,t,s)=>{let r=V.get(e);if(!r){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";r=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${H(e)}${t})`,"gi"),V.set(e,r)}return s.replace(r,(...e)=>{const{keep:s,url:r,secure:n,slashes:i,port:a}=e.at(-1);return s||a&&a!==(n?"443":"80")?r:`http${i}${t}`})},W=(e,t,s)=>{const r=new RegExp(`${e.replace(/\\*\//gi,"\\\\/")}`,"gi"),n=new RegExp(`${e}`,"gi"),i=s.replace(r,t);return i===s?i.replace(n,t):i},J=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function G(e){return e.split("?")[0]}async function K(e){const t=new j,r=async n=>{const i=await s.promises.readdir(n,{withFileTypes:!0});for(const a of i){const i=T.join(n,a.name);if(a.isDirectory())await r(i);else if(a.isFile()){const r=T.relative(e,i).replace(/\\/g,"/");t.file(r,await s.promises.readFile(i))}}};return await r(e),await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"})}function X(e){return`${e}.${process.pid}.${u.randomBytes(4).toString("hex")}.tmp`}const Z=new Map;async function Y(e,t,s){const r=X(e);try{await B.writeFile(r,t,s),await B.rename(r,e)}catch(e){throw await B.rm(r,{force:!0}),e}}const Q=6e5;function ee(e,t,s){if(e.pid)if("win32"!==process.platform)try{s?process.kill(-e.pid,t):e.kill(t)}catch{}else null===e.exitCode&&null===e.signalCode&&C.spawn("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"}).on("error",()=>{})}function te(e,t,s,{cwd:r,env:n,timeoutMs:i,signal:a,killGraceMs:o=5e3}){return new Promise((c,l)=>{if(a?.aborted)return void l(new Error(`${e} was stopped`));const d="win32"!==process.platform&&(void 0!==a||void 0!==i),u=C.spawn(t,s,{cwd:r,env:n,stdio:"inherit",detached:d});let p,h;const g=(e,t)=>{p?t||void 0===h||(clearTimeout(h),h=void 0,ee(u,"SIGKILL",d)):(p=e,t?(ee(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,ee(u,"SIGKILL",d)},o)):ee(u,"SIGKILL",d))},m=()=>g(`${e} was stopped`,!1),f=void 0===i?void 0:setTimeout(()=>g(`${e} timed out after ${Math.round(i/1e3)} s`,!0),i);a?.addEventListener("abort",m,{once:!0});const y=e=>{clearTimeout(f),clearTimeout(h),a?.removeEventListener("abort",m),d&&ee(u,"SIGKILL",d),e?l(e):c()};u.on("close",t=>{p?y(new Error(p)):0!==t?y(new Error(`${e} exited with code ${t}`)):y()}),u.on("error",e=>y(e))})}const se=".next";const re="pageName",ne="date",ie=T.dirname("undefined"!=typeof __filename&&__filename||e.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:S&&"SCRIPT"===S.tagName.toUpperCase()&&S.src||new URL("plugin.js",document.baseURI).href)),ae=T.resolve(ie,"..",".."),oe=Buffer.from([80,75,3,4]),ce=20,le=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const de="sync-service.meta.json",ue="BUILD-MANIFEST.json",pe="__template_variables.json";class he{root;backupFolder;backupNameTemplate;dateFormat;pageName;currentMeta=null;versionFileTemplate;buildInputFolder;nextBuild;maxBackups;buildTimeoutMs;metaDir;builds=new AbortController;metaLoaded;logger;constructor(e,t){this.pageName=e;const{root:s=P.cwd(),backupFolder:r="backups",backupNameTemplate:n=`{${re}}-{${ne}}.zip`,versionFileTemplate:i="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:o,dateFormat:c=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:l,maxBackups:d=ce,buildTimeoutMs:u=Q,metaDir:p}=t||{};this.root=s,this.backupFolder=T.resolve(s,r),this.backupNameTemplate=n,this.dateFormat=c,this.versionFileTemplate=a.normalizeRelativeOutputPath(i,"VERSION file name template"),this.buildInputFolder=o,this.nextBuild=l,this.maxBackups="number"==typeof d&&Number.isInteger(d)&&d>0?d:1/0,this.buildTimeoutMs=u,this.metaDir=void 0===p?T.join(this.backupFolder,".pp-dev-meta"):T.resolve(s,p),this.logger=a.createLogger(),this.metaLoaded=this.loadMeta()}stopBuilds(){this.builds.abort()}async checkMeta(){await s.promises.mkdir(this.metaDir,{recursive:!0}),await s.promises.mkdir(this.backupFolder,{recursive:!0})}async loadMeta(){try{const e=JSON.parse(await this.readMetaFile());this.currentMeta=e&&"object"==typeof e?e:{}}catch(e){this.logger.warn(a.colors.yellow(`[DistService] Could not read the sync meta (${e instanceof Error?e.message:String(e)}); starting a new one`)),this.currentMeta={}}}async meta(){return await this.metaLoaded,this.currentMeta||(this.currentMeta={}),this.currentMeta}async readMetaFile(){return await this.checkMeta(),await s.promises.readFile(T.join(this.metaDir,de),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await s.promises.writeFile(T.join(this.metaDir,de),JSON.stringify(e,null,2),{encoding:"utf-8"})}async syncMeta(){await this.writeMetaFile(await this.meta())}async getLatestSavedBackup(){const{lastBackupName:e}=await this.meta();if(!e)return null;const t=T.resolve(this.backupFolder,e);try{return await s.promises.stat(t),t}catch{return null}}backupName(e,t=new Date,s=1){return this.backupNameTemplate.replace(`{${re}}`,e).replace(`{${ne}}`,this.dateFormat(t)+(s>1?`-${s}`:""))}async freeBackupName(e){let t=this.backupName(this.pageName,e);for(let r=2;;r+=1){try{await s.promises.access(T.resolve(this.backupFolder,t))}catch{return t}const n=this.backupName(this.pageName,e,r);if(n===t)return t;t=n}}getBackupMeta(){return this.currentMeta}async pruneBackups(e){if(Number.isFinite(this.maxBackups))try{const t=function(e,t,s){const r=s.split(/(\d+)/).map((e,t)=>t%2==1?"\\d+":le(e)).join("")+"(?:-\\d+)?",n=[{token:`{${re}}`,pattern:le(t)},{token:`{${ne}}`,pattern:r}].map(t=>({...t,at:e.indexOf(t.token)})).filter(e=>-1!==e.at).sort((e,t)=>e.at-t.at);let i="^",a=0;for(const{token:t,pattern:s,at:r}of n)i+=le(e.slice(a,r))+s,a=r+t.length;return new RegExp(`${i}${le(e.slice(a))}$`)}(this.backupNameTemplate,this.pageName,this.dateFormat(new Date)),r=new Set([e]),n=await s.promises.readdir(this.backupFolder,{withFileTypes:!0}),i=(await Promise.all(n.filter(e=>e.isFile()&&t.test(e.name)).map(async e=>({name:e.name,mtimeMs:(await s.promises.stat(T.resolve(this.backupFolder,e.name))).mtimeMs})))).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.name.localeCompare(e.name)),o=i.filter(e=>r.has(e.name)).length,c=i.filter(e=>!r.has(e.name)).slice(Math.max(0,this.maxBackups-o));for(const e of c)await s.promises.unlink(T.resolve(this.backupFolder,e.name));c.length>0&&this.logger.info(a.colors.gray(`[DistService] Deleted ${c.length} old backup(s), keeping the latest ${this.maxBackups}`))}catch(e){this.logger.warn(a.colors.yellow(`[DistService] Could not delete old backups: ${e instanceof Error?e.message:String(e)}`))}}pathToPosix(e){return e.replace(/\\/g,"/")}normalizeBackupManifestPath(e){try{return a.normalizeRelativeOutputPath(e,"VERSION manifest file path")}catch{throw new Error(`VERSION manifest file path "${e}" resolves outside the backup root`)}}async normalizeExtractedRootDir(e){let t=e;for(;;){const e=await s.promises.readdir(t,{withFileTypes:!0});if(1!==e.length||!e[0]?.isDirectory())return t;t=T.join(t,e[0].name)}}async listFilesRecursive(e){const t=await s.promises.readdir(e,{withFileTypes:!0}),r=[];for(const s of t){const t=T.join(e,s.name);s.isDirectory()?r.push(...await this.listFilesRecursive(t)):s.isFile()&&r.push(t)}return r}buildManifestChecksum(e){const t=Object.keys(e).sort().map(t=>e[t]).join("");return I.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return I.createHash("sha256").update(t,"utf-8").digest("hex")}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}versionFileTemplateMatcher(){const e=/\{[^}]+\}/g,t=[];let s=0,r=null;for(;r=e.exec(this.versionFileTemplate),r;){const[e]=r,n=this.versionFileTemplate.slice(s,r.index);t.push(this.escapeRegExp(n)),t.push("[^/]+"),s=r.index+e.length}const n=this.versionFileTemplate.slice(s);return t.push(this.escapeRegExp(n)),new RegExp(`^${t.join("")}$`,"i")}isTemplateVariablesBasename(e){return e===pe}async pickTemplateVariablesFromBackupZip(e,t){const r=e.find(e=>T.basename(e)===pe);if(!r)return null;const n=T.join(t,r),i=await s.promises.readFile(n);return{relativePath:r,content:i,actualHash:I.createHash("sha256").update(i).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const t=await s.promises.mkdtemp(T.join(L.tmpdir(),"pp-dev-backup-")),r=T.join(t,"backup.zip"),n=T.join(t,"extracted");try{await s.promises.mkdir(n,{recursive:!0}),await s.promises.writeFile(r,e),await async function(e,t){const r=await j.loadAsync(await s.promises.readFile(e),{createFolders:!1}),n=T.resolve(t),i=Object.values(r.files).filter(e=>!e.name.startsWith("__MACOSX/"));for(const e of i){const t=e.unsafeOriginalName??e.name,s=T.resolve(n,t);if(s!==n&&!s.startsWith(n+T.sep))throw new Error(`Zip entry "${t}" resolves outside the extraction directory`);if("number"==typeof e.unixPermissions&&40960==(61440&e.unixPermissions))throw new Error(`Zip archive contains a symlink ("${t}"), which is not allowed`)}await s.promises.mkdir(n,{recursive:!0});for(const e of i){const t=T.resolve(n,e.unsafeOriginalName??e.name);e.dir?await s.promises.mkdir(t,{recursive:!0}):(await s.promises.mkdir(T.dirname(t),{recursive:!0}),await s.promises.writeFile(t,await e.async("nodebuffer")))}}(r,n);const t=await this.normalizeExtractedRootDir(n),i=(await this.listFilesRecursive(t)).map(e=>this.pathToPosix(T.relative(t,e))),o=i.filter(e=>T.basename(e)===ue);if(o.length>1)throw new Error(`Expected at most one ${ue} in backup ZIP, found ${o.length}`);const c=1===o.length?o[0]:null;let l=null;if(c){const e=T.join(t,c);if(l=JSON.parse(await s.promises.readFile(e,"utf-8")),!(l&&"pp-dev-build-manifest"===l.manifestType&&"string"==typeof l.versionFile&&l.versionFile.trim()&&"string"==typeof l.versionFileTemplate&&l.versionFileTemplate.trim()&&"string"==typeof l.buildFingerprint&&l.buildFingerprint.trim()))throw new Error("Build manifest is missing required fields")}let d=null;if(l){const e=this.pathToPosix(l.versionFile.trim()),t=i.filter(t=>t===e),s=i.filter(t=>T.basename(t)===T.basename(e)),r=t.length>0?t:s;if(r.length>1)throw new Error(`Build manifest version file "${l.versionFile}" must resolve to exactly one file in backup ZIP, found ${r.length}`);if(1===r.length&&(d=r[0]),!0===l.compat?.versionFileRequired&&null===d)throw new Error(`Build manifest requires version file "${l.versionFile}", but it is missing in backup ZIP`)}else{const e=this.versionFileTemplateMatcher(),t=i.filter(t=>e.test(T.basename(t)));if(t.length>1)throw new Error(`Expected exactly one version file matching template "${this.versionFileTemplate}" in backup ZIP, found ${t.length}`);1===t.length&&(d=t[0])}const u={};let p=null,h=null,g=[];if(d){const e=T.join(t,d),r=JSON.parse(await s.promises.readFile(e,"utf-8"));if(!r?.files||"object"!=typeof r.files)throw new Error("VERSION manifest files map is missing or invalid");if("string"!=typeof r.checksum||!r.checksum)throw new Error("VERSION manifest checksum is missing or invalid");h=r.checksum;for(const[e,t]of Object.entries(r.files)){if("string"!=typeof t||!t.trim())throw new Error(`VERSION manifest contains invalid hash for file: ${e}`);const s=this.normalizeBackupManifestPath(e);if(Object.prototype.hasOwnProperty.call(u,s))throw new Error(`VERSION manifest contains duplicate normalized file path: ${s}`);u[s]=t}if(this.buildManifestChecksum(u)!==r.checksum)throw new Error("VERSION manifest checksum does not match its files map");for(const[e,r]of Object.entries(u)){const n=T.join(t,e),i=await s.promises.readFile(n).catch(()=>null);if(!i)throw new Error(`VERSION manifest references missing file: ${e}`);const a=I.createHash("sha256").update(i).digest("hex");a!==r&&g.push({relativePath:e,expected:r,actual:a}),this.isTemplateVariablesBasename(T.basename(e))&&(p={relativePath:e,content:i,actualHash:a,manifestHash:r})}g.length>0&&this.logger.warn(a.colors.yellow(`[DistService] VERSION manifest hash mismatch for ${g.length} file(s) (confirm in UI): ${g.map(e=>e.relativePath).join(", ")}`))}const m={},f=[];for(const e of i){if(e===c)continue;if(d&&e===d)continue;const r=T.join(t,e),n=await s.promises.readFile(r);m[e]=I.createHash("sha256").update(n).digest("hex"),d&&!Object.prototype.hasOwnProperty.call(u,e)&&f.push(e)}p||(p=await this.pickTemplateVariablesFromBackupZip(i,t));const y=this.buildBackupFingerprint(m);let w=null;return l&&d&&y!==l.buildFingerprint&&(w={expected:l.buildFingerprint,actual:y},this.logger.warn(a.colors.yellow(`[DistService] Build manifest fingerprint mismatch (confirm in UI): expected ${l.buildFingerprint}, got ${y}`))),{backupFingerprint:y,unknownFiles:f,templateVariables:p,mainHash:h,buildManifestMismatch:w,versionManifestHashMismatches:g}}finally{await s.promises.rm(t,{recursive:!0,force:!0})}}async analyzeBackup(e){if(!oe.equals(e.subarray(0,oe.length)))throw new Error("Backup file is not a ZIP file");return await this.resolveBackupAnalysisFromZip(e)}async getPublicTemplateVariablesHash(){const e=T.resolve(this.root,"public",pe),t=await s.promises.readFile(e).catch(()=>null);return t?I.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=T.resolve(this.root,"public",pe);return await s.promises.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=T.resolve(this.root,"public",pe);return await s.promises.mkdir(T.dirname(t),{recursive:!0}),await function(e,t,s){const r=(Z.get(e)??Promise.resolve()).then(()=>Y(e,t,s),()=>Y(e,t,s)),n=()=>{Z.get(e)===r&&Z.delete(e)};return Z.set(e,r),r.then(n,n),r}(t,e),t}async saveBackup(e,t){const r=(t??await this.analyzeBackup(e)).backupFingerprint,n=await this.getLatestSavedBackup(),i=await this.meta();if(n&&i.lastBackupHash===r)return void this.logger.info(a.colors.yellow(`[DistService] Backup skipped: same backup fingerprint as last saved (${r.slice(0,12)}...)`));const o=new Date,c=await this.freeBackupName(o);i.lastBackupName=c,i.lastBackupHash=r,i.lastBackupDate=o.toISOString(),delete i.lastMainHash,await this.syncMeta(),await s.promises.writeFile(T.resolve(this.backupFolder,c),e),this.logger.info(`Backup saved to ${c}`),await this.pruneBackups(c)}async buildNewAssets(){if(this.nextBuild)return await this.buildNextAssets();this.logger.info(a.colors.cyan("[DistService] Build started"));const e=te("pp-dev build",P.execPath,[T.resolve(ae,"./bin/pp-dev.js"),"build"],{cwd:this.root,env:Object.assign({},P.env,{NODE_ENV:"production"}),timeoutMs:this.buildTimeoutMs,signal:this.builds.signal});try{if(await this.logBuild("Build",e),!this.buildInputFolder)throw new Error("The sync has no build directory to zip (build.outDir or build.zip.inDir)");const t=T.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(t))throw new Error(`Build input directory ${t} not found`);const s=await K(t);return this.throwIfStopped("pp-dev build"),s}catch(e){throw this.logger.error(e instanceof Error?e.stack??e.message:String(e)),e}}async saveBackupAndBuild(e){return await this.saveBackup(e),await this.buildNewAssets()}async buildNextAssets(){const{projectRoot:e,distDir:t,buildDistDir:r=t,output:n,configWrapped:i}=this.nextBuild,c=i||r===se?"out":r,l=T.resolve(e,c);if(i&&function(e,t){const s=T.relative(t,e);return""===s||!(".."===s||s.startsWith(`..${T.sep}`)||T.isAbsolute(s))}(T.resolve(e,t),l))throw new Error(`The app's distDir (${t}) is inside the sync's export directory (${c}), which next build empties: set another distDir in next.config.`);const d=function(e,t){const s=t?.distDir;if("export"!==t?.output||!s||".next"===s)return null;const r=T.resolve(e,s,"dev","types");return E.existsSync(r)?(E.rmSync(r,{recursive:!0,force:!0}),r):null}(e,{output:n,distDir:t});if(d&&this.logger.info(a.colors.dim(`[DistService] Removed stale dev route types: ${T.relative(e,d)}`)),i||c!==t||this.logger.warn(a.colors.yellow(`⚠️ next.config is not wrapped with withPPDev(): the sync's build exports into ${t} and removes the dev server's ${T.join(t,"dev")}; restart pp-dev next after the sync`)),i&&await s.promises.rm(l,{recursive:!0,force:!0}),this.logger.info(a.colors.cyan("[DistService] Next.js build started")),await this.logBuild("Next.js build",async function(e,t={}){let s;try{const t=h.createRequire(T.join(e,"package.json")).resolve("next/package.json");s=T.resolve(T.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}const{distDir:r,...n}=t,i=Object.assign({},process.env,{NODE_ENV:"production",[a.PP_DEV_NEXT_BUILD_ENV_VAR]:"1"});r?i[a.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR]=r:delete i[a.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR],await te("next build",process.execPath,[s,"build"],{...n,cwd:e,env:i})}(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal,distDir:i?se:void 0})),!await this.isDirectory(l))throw new Error(`Next.js build output directory not found: ${l}. The sync needs "output: 'export'" in next.config (static export).`);this.throwIfStopped("next build"),await o.writeBuildVersionManifest({outDir:l,root:e,packageVersion:this.nextBuild.packageVersion,versionFileTemplate:this.versionFileTemplate,packageRepositoryUrl:this.nextBuild.packageRepositoryUrl,packageBranchName:this.nextBuild.packageBranchName}),this.throwIfStopped("next build");const u=await K(l);return this.throwIfStopped("next build"),u}get stopped(){return this.builds.signal.aborted}throwIfStopped(e){if(this.stopped)throw new Error(`${e} was stopped`)}async logBuild(e,t){try{await t}catch(t){const s=this.builds.signal.aborted;throw this.logger.info(a.colors.yellow(`[DistService] ${e} ${s?"stopped":"failed"}`)),t}this.logger.info(a.colors.cyan(`[DistService] ${e} finished`))}async isDirectory(e){try{return(await s.promises.stat(e)).isDirectory()}catch{return!1}}}const ge="10mb",me=(e,t,s,r)=>{const n="number"==typeof e?.status?e.status:void 0;if(!n||n<400||n>=500||"string"!=typeof e.type||s.headersSent)return void r(e);const i="entity.too.large"===e.type?`The request body is larger than the dev server accepts (${ge}).`:`The request body could not be read: ${e.message}`;s.status(n).json({error:i})};function fe(e,t,s={}){switch(t){case"gzip":return $.unzipSync(e,s);case"br":return $.brotliDecompressSync(e,s);case"deflate":return $.inflateSync(e,s);default:return e}}function ye(e){if(e.socket?.encrypted)return!0;const t=e.headers?.["x-forwarded-proto"],s=Array.isArray(t)?t[0]:t;return"string"==typeof s&&"https"===s.split(",",1)[0].trim().toLowerCase()}function we(e,t){const[s,...r]=e.split(";"),n=r.map(e=>e.trim()).filter(e=>{if(!e)return!1;const s=e.split("=",1)[0].trim().toLowerCase();return"domain"!==s&&(t||"secure"!==s)}).map(e=>!t&&/^samesite\s*=\s*none$/i.test(e)?"SameSite=Lax":e);return[s.trim(),...n].join("; ")}const ve="metric_insights_session";function be(e,t){for(const s of e){const e=s.indexOf("=");if(-1!==e&&s.slice(0,e).trim()===t)return s.slice(e+1).trim()}}function ke(e,t){return e?be(e.split(";"),t):void 0}function $e(e,t){if(void 0===e||"number"==typeof e)return;return be((Array.isArray(e)?e:[e]).map(e=>e.split(";",1)[0]),t)}function Se(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>we(e,t)):we(e,t)}const xe=function(e){const t={personal:{placeholder:"API Token",label:"API Token",path:"/api-token"},regular:{placeholder:"Legacy Token",label:"Legacy Token",path:"/api/get_token"}};function s(s,r,n){const i=t[s],a=document.createElement("a");a.href=`https://${e}${i.path}`,a.target="_blank",a.style.color="#007bff",a.style.textDecoration="none",a.textContent="here",r.placeholder=i.placeholder,n.replaceChildren(`You can get the ${i.label} `,a)}function r(e,t){t.textContent=e,t.classList.add("show")}function n(e){e.classList.remove("show")}function i(e,t,s,i){s.addEventListener("click",async s=>{if(s.preventDefault(),n(i),!t.value.trim())return r(`${t.placeholder} is required`,i),void t.focus();const a=document.getElementById("token-type-switcher"),o=a?.querySelector(".token-type-option.active"),c=o?.dataset.value||"personal";await async function(e,t,s,n){try{s.classList.add("loading");const i=await fetch("/@api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,tokenType:t}),redirect:"follow"}),a=i.url&&new URL(i.url,window.location.origin);if(!a||a.pathname.startsWith("/login")||a.pathname.startsWith("/@api/"))try{const e=await i.json();r(`Login failed: ${e?.error||"Unknown error occurred"}`,n)}catch(e){r("Login failed: Unable to parse response",n)}else window.location.href=i.url}catch(e){r("Login failed: Network error. Please check your connection.",n)}finally{s.classList.remove("loading")}}(t.value.trim(),c,e,i)}),t.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),s.click())}),t.addEventListener("input",()=>{n(i)})}function a(e){const t=e.firstChild;if(!t)return;const r=t.lastChild?.cloneNode(!0);if(!r)return;r.innerHTML="";const n=r.cloneNode(!0);n.innerText="OR",n.setAttribute("role","separator"),n.setAttribute("aria-label","Alternative login method");const a=r.cloneNode(!0),o=document.createElement("div"),c=document.createElement("style");c.textContent="\n.helper-login-wrapper {\n font-family: Arial, sans-serif;\n color: #222;\n padding: 8px;\n background-color: #f8f9fa;\n border-radius: 8px;\n border: 1px solid #ddd;\n width: 100%;\n max-width: 400px;\n margin: 0 auto;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n}\n\n.helper-login-wrapper .title {\n font-weight: bold;\n font-size: 18px;\n margin-bottom: 12px;\n text-align: center;\n}\n\n.helper-login-wrapper .control {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.helper-login-wrapper .control input {\n border: 1px solid #ddd;\n border-radius: 4px;\n width: 100%;\n box-sizing: border-box;\n text-align: center;\n height: 26px;\n padding: 0 8px;\n font-size: 14px;\n}\n\n.helper-login-wrapper .control input:focus {\n outline: none;\n border-color: #007bff;\n box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);\n}\n\n.helper-login-wrapper .control .caption {\n font-size: 12px;\n color: #666;\n text-align: center;\n}\n\n.helper-login-wrapper .footer {\n margin-top: 16px;\n text-align: center;\n}\n\n.helper-login-wrapper .footer .btn.submit {\n background-color: #007bff;\n color: white;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n width: 100%;\n font-size: 14px;\n transition: background-color 0.3s;\n height: 26px;\n font-weight: 500;\n}\n\n.helper-login-wrapper .footer .btn.submit:hover {\n background-color: #0056b3;\n}\n\n.helper-login-wrapper .footer .btn.submit:disabled {\n background-color: #6c757d;\n cursor: not-allowed;\n}\n\n.helper-login-wrapper .token-type-switcher {\n display: flex;\n border: 1px solid #ccc;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 12px;\n width: 100%;\n}\n\n.helper-login-wrapper .token-type-option {\n padding: 4px 8px;\n cursor: pointer;\n background-color: #f8f9fa;\n color: #666;\n font-size: 12px;\n text-align: center;\n transition: background-color 0.2s, color 0.2s;\n border-right: 1px solid #ccc;\n flex: 1;\n user-select: none;\n}\n\n.helper-login-wrapper .token-type-option:last-child {\n border-right: none;\n}\n\n.helper-login-wrapper .token-type-option.active {\n background-color: #007bff;\n color: white;\n font-weight: bold;\n}\n\n.helper-login-wrapper .token-type-option:not(.active):hover {\n background-color: #e9ecef;\n}\n\n.helper-login-wrapper .error-message {\n color: #dc3545;\n font-size: 12px;\n text-align: center;\n margin-top: 8px;\n display: none;\n}\n\n.helper-login-wrapper .error-message.show {\n display: block;\n}\n\n.helper-login-wrapper .loading {\n opacity: 0.6;\n pointer-events: none;\n}\n",document.head.appendChild(c),o.innerHTML='\n<div class="helper-login-wrapper" role="form" aria-label="PP Dev Helper Login">\n <div class="title" role="heading" aria-level="2">PP Dev Helper</div>\n\n <div class="token-type-switcher" id="token-type-switcher" role="tablist" aria-label="Token type selection">\n <div class="token-type-option active" data-value="personal" role="tab" aria-selected="true" tabindex="0">\n API Token\n </div>\n <div class="token-type-option" data-value="regular" role="tab" aria-selected="false" tabindex="0">\n Legacy Token\n </div>\n </div>\n\n <div class="control">\n <input \n type="password" \n id="helper-token" \n placeholder="API Token"\n aria-label="Token input"\n aria-describedby="token-caption"\n >\n <span class="caption" id="token-caption"></span>\n </div>\n\n <div class="error-message" id="error-message" role="alert" aria-live="polite"></div>\n\n <div class="footer">\n <button id="helper-token-submit" class="btn submit" type="button">\n Token Login\n </button>\n </div>\n</div>',a.appendChild(o),t.appendChild(n),t.appendChild(a);const l=document.getElementById("token-type-switcher"),d=document.getElementById("helper-token"),u=document.getElementById("token-caption"),p=document.getElementById("helper-token-submit"),h=document.getElementById("error-message"),g=o.querySelector(".helper-login-wrapper");l&&d&&u&&p&&h&&g?(!function(e,t,r){const n=e.querySelectorAll(".token-type-option"),i=e=>{const i=e.dataset.value;n.forEach(e=>{e.classList.remove("active"),e.setAttribute("aria-selected","false"),e.setAttribute("tabindex","-1")}),e.classList.add("active"),e.setAttribute("aria-selected","true"),e.setAttribute("tabindex","0"),s(i,t,r)};n.forEach(e=>{e.addEventListener("click",e=>{const t=e.currentTarget;i(t)}),e.addEventListener("keydown",t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),i(e))})})}(l,d,u),i(g,d,p,h),s("personal",d,u)):console.error("Failed to find required form elements")}const o='#mi-react-root form:not([id]):has(input[name="login"]):has(input[name="password"])',c=new MutationObserver(e=>{for(const t of e)if("childList"===t.type){const e=document.querySelector(o);if(e){c.disconnect(),a(e);break}}});c.observe(document.body,{childList:!0,subtree:!0});const l=document.querySelector(o);l&&(c.disconnect(),a(l))};function Ae(e){const{message:t,response:s}="object"==typeof e&&null!==e?e:{},r="number"==typeof s?.status?s.status:0,n=s?.data?.message;return"string"==typeof n&&n?{status:r,message:n}:"string"==typeof t&&t?{status:r,message:t}:{status:r,message:"string"==typeof e&&e?e:"Unknown error"}}function Te(e){const{status:t,message:s}=Ae(e);switch(t){case 412:{const e=s.toLowerCase();return e.includes("session expired")||e.includes("session has expired")?{status:t,message:s,code:"SESSION_EXPIRED",userFriendlyMessage:"Your session has expired",suggestions:["Refresh your token in the portal","Re-authenticate with the portal","Check if your token has been revoked","Ensure your token has the correct permissions"]}:{status:t,message:s,code:"AUTH_FAILED",userFriendlyMessage:"Authentication failed",suggestions:["Verify your token is correct","Check token permissions","Ensure the token hasn't expired","Try generating a new token"]}}case 401:return{status:t,message:s,code:"UNAUTHORIZED",userFriendlyMessage:"Unauthorized access",suggestions:["Check if your token is valid","Verify you have the required permissions","Ensure the token hasn't been revoked","Try logging in again"]};case 403:return{status:t,message:s,code:"FORBIDDEN",userFriendlyMessage:"Access forbidden",suggestions:["Check your user permissions","Verify the portal page ID is correct","Ensure your token has the right scope","Contact your administrator"]};default:return{status:t,message:s,code:"UNKNOWN_ERROR",userFriendlyMessage:"An unexpected error occurred",suggestions:["Check your network connection","Verify the portal URL is correct","Try again in a few moments","Check the portal status"]}}}function Ee(e){const{status:t}=Ae(e);return 401===t||403===t||412===t}const Ie="Something went wrong when fetching page data",Pe="Something went wrong when fetching page template data",Le="Something went wrong when fetching page variables",je="Something went wrong when checking who the credentials belong to",Ne=" The instance may be down or in maintenance mode. Please try again later.",Re=[Ie,Pe,Le,je];function Be(){return new Error(`${Ie}.${Ne}`)}function Ce(){return new Error(`${Pe}.${Ne}`)}function Fe(e){return e instanceof Error&&Re.some(t=>e.message.includes(t))}const Me=12e4;class Oe{server;opts;eventMap;logger;syncInFlight=null;syncActionResolvers=new Map;constructor(e,t){this.server=e,this.opts=t||{},this.eventMap=new Map,this.eventMap.set("info-data:request",this.onInfoDataRequest.bind(this)),this.eventMap.set("template:sync",this.onTemplateSync.bind(this)),this.eventMap.set("template:sync:action-response",this.onTemplateSyncActionResponse.bind(this)),this.eventMap.set("page-variables:reload",this.onPageVariablesReload.bind(this)),this.logger=a.createLogger(),this.init()}init(){const{ws:e}=this.server;for(const[t,s]of this.eventMap)e.on(t,s);e.on("error",()=>{this.clearAllPendingSyncActions("disconnected")})}dispose(){this.clearAllPendingSyncActions("shutdown"),this.opts.distService?.stopBuilds()}resolveSyncAction(e,t){const s=this.syncActionResolvers.get(e);s&&(clearTimeout(s.timeoutId),s.cleanup(),this.syncActionResolvers.delete(e),s.resolve(t))}clearAllPendingSyncActions(e){for(const t of[...this.syncActionResolvers.keys()])this.resolveSyncAction(t,{approved:!1,reason:e})}describeSyncCancel(e){switch(e){case"cancelled":return"Sync cancelled by user.";case"timeout":return`Sync cancelled: its dialog was not answered within ${Math.round((this.opts.syncActionTimeoutMs??Me)/1e3)} s.`;case"disconnected":return"Sync cancelled: the tab that started it lost its connection to the dev server.";case"shutdown":return"Sync cancelled: the dev server is shutting down."}}cancelSync(e,t){const s=this.describeSyncCancel(t);this.sendSyncResponse(e,{cancelled:!0,message:`${s} Backup was saved.`}),this.logger.info(a.colors.yellow(s))}sendSyncResponse(e,t){e.send("template:sync:response",t)}onInfoDataRequest(e,t){t.send("info-data:response",{})}onTemplateSyncActionResponse(e){e&&"string"==typeof e.requestId&&"boolean"==typeof e.approved&&this.resolveSyncAction(e.requestId,e.approved?{approved:!0}:{approved:!1,reason:"cancelled"})}async requestSyncAction(e,t){const s=r.randomUUID(),n=this.opts.syncActionTimeoutMs??Me;return await new Promise(r=>{const i=e=>this.resolveSyncAction(s,{approved:!1,reason:e}),a=setTimeout(()=>i("timeout"),n),{socket:o}=t,c=()=>i("disconnected");o?.once("close",c),this.syncActionResolvers.set(s,{resolve:r,timeoutId:a,cleanup:()=>o?.off("close",c)}),o&&o.readyState!==o.OPEN?i("disconnected"):t.send("template:sync:action-required",{...e,requestId:s})})}async onTemplateSync(e,t){if(this.syncInFlight)return this.logger.warn(a.colors.yellow("Template sync requested while another one is running; ignored")),void this.sendSyncResponse(t,{error:"A template sync is already running. Wait for it to finish, or answer its dialog in the tab that started it.",code:"SYNC_IN_PROGRESS"});const s=this.runTemplateSync(e,t);this.syncInFlight=s;try{await s}finally{this.syncInFlight=null}}async runTemplateSync(e,t){if(!this.opts.distService||!this.opts.miAPI)return this.sendSyncResponse(t,{error:"Dist service or MiAPI is not defined"}),void this.logger.error(a.colors.red("Dist service or MiAPI is not defined"));{const{distService:e,miAPI:s}=this.opts;try{if(this.server.config.clientInjectionPlugin?.v7Features){if(!s?.isV710OrHigher)return void this.sendSyncResponse(t,{error:"This feature is available only for MI v7.1.0 or higher",config:{canSync:!1}});t.send("client:config:update",{config:{canSync:!0}})}const r=await s.getAssets().catch(async e=>{if(await this.reportMiFailure(t,e))return e;throw e});if(r instanceof Error)return;let n;if(r){const s=await(e?.analyzeBackup(r).catch(e=>e));if(s instanceof Error)n=s;else if(s){await(e?.saveBackup(r,s));const i=0===s.unknownFiles.length&&1===s.versionManifestHashMismatches.length&&T.basename(s.versionManifestHashMismatches[0].relativePath)===pe,a=s.versionManifestHashMismatches,o=a.filter(e=>T.basename(e.relativePath)===pe),c=a.filter(e=>T.basename(e.relativePath)!==pe),l=!i&&o.length>0&&c.length>0,d=i?[]:c.map(e=>e.relativePath),u=async()=>{if(!s.templateVariables||!e)return!0;const{templateVariables:r}=s;if(await e.getPublicTemplateVariablesHash()!==r.actualHash){const s=await this.requestSyncAction({title:"Template variables (server backup)",content:"The server backup includes __template_variables.json. It differs from your local public/__template_variables.json (or that file is missing). Replace your project copy with the server backup?",confirmText:"Replace from server",cancelText:"Keep local"},t);if(s.approved)await e.saveTemplateVariablesFile(r.content);else if("cancelled"!==s.reason)return this.cancelSync(t,s.reason),!1}return!0};if(s.unknownFiles.length>0){const e=await this.requestSyncAction({title:"Unknown files found in backup",content:`Backup contains files not listed in VERSION: ${s.unknownFiles.join(", ")}. Continue sync or cancel?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!e.approved)return void this.cancelSync(t,e.reason)}if(l&&!await u())return;if(!i&&d.length>0){const e=40,s=d,r=s.slice(0,e),n=s.length-r.length,i=r.map(e=>`• ${e}`).join("\n"),a=n>0?`\n... and ${n} more file${1===n?"":"s"}`:"",o=await this.requestSyncAction({title:"VERSION manifest out of date",content:`These files no longer match the hashes recorded in the VERSION manifest:\n\n${i}${a}\n\nCancel sync, or override and continue using the files on disk?`,confirmText:"Override and continue",cancelText:"Cancel sync"},t);if(!o.approved)return void this.cancelSync(t,o.reason)}if(!i&&s.buildManifestMismatch&&0===s.versionManifestHashMismatches.length){const{expected:e,actual:r}=s.buildManifestMismatch,n=await this.requestSyncAction({title:"Build manifest fingerprint mismatch",content:`The recomputed backup fingerprint does not match BUILD-MANIFEST.json.\nManifest: ${e.slice(0,12)}...\nComputed: ${r.slice(0,12)}...\nContinue sync anyway?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!n.approved)return void this.cancelSync(t,n.reason)}if(!l&&!await u())return;n=await(e?.buildNewAssets())}}else n=await(e?.buildNewAssets());if(!(n&&n instanceof Buffer))return n instanceof Error?(this.sendSyncResponse(t,{error:n.message}),void this.logger.error(a.colors.red(n.message))):(this.sendSyncResponse(t,{error:"Failed to build new assets"}),void this.logger.error(a.colors.red("Failed to build new assets")));{if(e.stopped)return this.sendSyncResponse(t,{error:"Sync stopped: the dev server is shutting down."}),void this.logger.warn(a.colors.yellow("Sync stopped before the upload: the dev server is shutting down"));let r;try{r=await s.updateAssets(n)}catch(e){if(await this.reportMiFailure(t,e))return;throw e}if("OK"===r?.status){const s=e?.getBackupMeta();this.sendSyncResponse(t,{syncedAt:(new Date).toISOString(),backupFilename:s?.lastBackupName??""}),this.logger.info(a.colors.green("Template synced"))}else{const e=`Failed to update assets: MI answered ${function(e){if("string"==typeof e){const t=e.replace(/\s+/g," ").trim();return`with a non-JSON body: "${t.slice(0,120)}${t.length>120?"…":""}"`}return e&&"object"==typeof e?`with ${JSON.stringify(e).slice(0,200)}`:`with ${String(e)}`}(r)}`;this.sendSyncResponse(t,{error:e}),this.logger.error(a.colors.red(e))}}}catch(e){const s=e instanceof Error?e.message:"Template sync failed";return this.logger.error(a.colors.red(`Template sync failed: ${s}`)),void this.sendSyncResponse(t,{error:s,code:"SYNC_FAILED"})}}}async reportMiFailure(e,t){if(m.isAxiosError(t)){if("SESSION_EXPIRED"===Te(t).code){this.logger.info(a.colors.yellow("Session expired - attempting to validate credentials"));try{const t=await(this.opts.miAPI?.validateCredentials());t&&!t.isValid?(this.logger.error(a.colors.red(`Authentication error: ${t.error}`)),this.sendSyncResponse(e,{error:t.error??"Authentication failed",code:t.code,refresh:!0})):(this.logger.info(a.colors.yellow("Session expired")),this.sendSyncResponse(e,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch{this.logger.info(a.colors.yellow("Session expired")),this.sendSyncResponse(e,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0})}return!0}if(t.cause instanceof Error&&("ECONNRESET"===t.cause.code||"ENOTFOUND"===t.cause.code))return this.logger.info(a.colors.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.sendSyncResponse(e,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0;const s=t.response?.status;if(502===s||503===s||504===s)return this.logger.info(a.colors.yellow(`Server in maintenance mode or unreachable (HTTP ${s}); VPN may be required`)),this.sendSyncResponse(e,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0}return!!Fe(t)&&(this.logger.info(a.colors.yellow("Server in maintenance mode or non-JSON page / page-template API response (unavailable HTML body)")),this.sendSyncResponse(e,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),!0)}async onPageVariablesReload(e,t){const{miAPI:s}=this.opts;if(!s)return t.send("page-variables:reload:response",{error:"MiAPI is not defined"}),void this.logger.error(a.colors.red("MiAPI is not defined"));try{const e=await s.reloadPageVariables();t.send("page-variables:reload:response",{ok:!0,count:e?e.length:0,skipped:null===e}),this.logger.info(a.colors.green("Page variables reloaded"))}catch(e){const s=e instanceof Error?e.message:"Reload variables failed";this.logger.error(a.colors.red(`Reload variables failed: ${s}`)),t.send("page-variables:reload:response",{error:s})}}}const De=T.dirname(a.PP_DEV_CLIENT_ENTRY),Ue={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function _e(e,t){const s=t.clientDir??De,r=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,r)=>{E.readFile(T.join(s,`${t.name}.html`),"utf-8",(e,s)=>{if(e)return void r.status(500).type("text/plain").end(`${t.name} page not built (${e.message})`);const n=t.values?.()??{};r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-cache"),r.end(s.replace(/\{\{(\w+)\}\}/g,(e,t)=>n[t]??e))})}),e.get(`${t.path}/:file`,(e,t,n)=>{const i=e.params.file;r.has(i)?E.readFile(T.join(s,i),(e,s)=>{e?n():(t.setHeader("Content-Type",Ue[T.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):n()})}const He=["text","select","multiselect","file","list","color","boolean"];function Ve(e){return He.includes(e)}const qe=["true","false","Y","N","1","0"],ze=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function We(e,t){return e.id===t||e.text===t}function Je(e){if("string"==typeof e||"number"==typeof e)return{id:String(e),text:String(e)};if("object"!=typeof e||null===e)return{text:""};const{id:t,text:s}=e,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{id:r,text:"string"==typeof s?s:r??""}}function Ge(e,t,s,r){const n="select"===s.type||"multi-select"===s.type;if("string"!=typeof r&&(!n||"number"!=typeof r))return[{name:e,severity:"warning",message:`${t}: field "${s.name}" should be a string, got ${typeof r}.`}];const i=String(r);if(!i)return[];switch(s.type){case"color":return ze.test(i)?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not a recognized color (expected e.g. "#075b7e").`}];case"select":{if(!Array.isArray(s.options)||!s.options.length)return[];const r=s.options.map(Je);return r.some(e=>We(e,i))?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not one of the declared options (${r.map(e=>e.text).join(", ")}).`}]}case"multi-select":{if(!Array.isArray(s.options)||!s.options.length)return[];const r=s.options.map(Je),n=i.split(",").map(e=>e.trim()).filter(e=>!r.some(t=>We(t,e)));return n.length?[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${n.join(", ")}" is not among the declared options (${r.map(e=>e.text).join(", ")}).`}]:[]}default:return[]}}function Ke(e,t){const s=function(e){if(!Array.isArray(e)||0===e.length)return null;const t=e.map(e=>"string"==typeof e?{name:e,type:"textarea"}:e&&"object"==typeof e&&"string"==typeof e.name?e:null).filter(e=>null!==e);return t.length?t:null}(e.additional_options);if(!s)return[];const r=new Set(s.map(e=>e.name)),n=[];return t.forEach((t,i)=>{const a=`"${e.name}" item #${i+1}`;if("object"!=typeof t||null===t||Array.isArray(t))return void n.push({name:e.name,severity:"warning",message:`${a} should be an object with field(s): ${s.map(e=>e.name).join(", ")}.`});const o=t;for(const t of s)t.name in o?n.push(...Ge(e.name,a,t,o[t.name])):n.push({name:e.name,severity:"warning",message:`${a} is missing field "${t.name}".`});const c=Object.keys(o).filter(e=>!r.has(e));c.length&&n.push({name:e.name,severity:"warning",message:`${a} has unexpected field(s) not declared in additional_options: ${c.join(", ")}.`})}),n}function Xe(e,t){const s=[];switch(e.tag_type){case"boolean":qe.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${qe.join(", ")}).`});break;case"list":try{const r=JSON.parse(t);Array.isArray(r)?s.push(...Ke(e,r)):s.push({name:e.name,severity:"warning",message:`Value for list variable "${e.name}" is valid JSON but not an array.`})}catch{s.push({name:e.name,severity:"warning",message:`Value for list variable "${e.name}" is not valid JSON.`})}break;case"select":case"multiselect":if(Array.isArray(e.additional_options)){const r=e.additional_options.map(Je),n=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!r.some(t=>We(t,e)));n.length&&s.push({name:e.name,severity:"warning",message:`Value "${n.join(", ")}" does not match any declared option for "${e.name}".`})}}return s}function Ze(e,t){switch(e.tag_type){case"boolean":return qe.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||ze.test(t)?null:`Not a recognized color value ("${t}").`;case"list":if(""===t)return null;try{const e=JSON.parse(t);return null===e||Array.isArray(e)?null:"Value is valid JSON but not an array."}catch{return"Value is not valid JSON."}default:return null}}const Ye="/@pp-dev/variables-editor",Qe=/^[A-Za-z0-9_\s-]+$/,et="Dist service or MiAPI is not defined",tt=new WeakMap;async function st(e){const t=await e.readPublicTemplateVariablesFile();if(!t)return null;const s=t.toString("utf-8");let r;try{r=JSON.parse(s)}catch(e){return{raw:s,schema:null,parseError:e instanceof Error?e.message:"Invalid JSON"}}return"object"!=typeof r||null===r||Array.isArray(r)||!Array.isArray(r.tags)?{raw:s,schema:null,parseError:'The root value must be a JSON object with a "tags" array.'}:{raw:s,schema:r}}async function rt(e){const t=e?(await st(e))?.schema??null:null;return t&&{...t,tags:t.tags.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.name&&""!==e.name)}}function nt(e,t,s){const r=tt.get(e);if(r)return void(r.deps=t);const n={deps:t};tt.set(e,n),e.get("/@api/variables/schema",async(e,t)=>{const{distService:s}=n.deps;if(!s)return void t.status(503).json({error:et});const r=await st(s);t.json(r?{exists:!0,...r}:{exists:!1,schema:null,raw:null})}),e.put("/@api/variables/schema",async(e,t)=>{const{distService:s}=n.deps;if(!s)return void t.status(503).json({error:et});const r=e.body?.raw;if("string"!=typeof r)return void t.status(400).json({error:"Request body must be { raw: string }."});let i;try{i=JSON.parse(r)}catch{return void t.status(400).json({error:"Not valid JSON."})}if("object"!=typeof i||null===i||Array.isArray(i))return void t.status(400).json({error:"The root value must be a JSON object."});const a=i.tags;if(!Array.isArray(a))return void t.status(400).json({error:'"tags" must be an array.'});const o=a.findIndex(e=>"object"!=typeof e||null===e||"string"!=typeof e.name||!e.name);if(-1!==o)return void t.status(400).json({error:`tags[${o}] is missing a non-empty "name".`});const c=[],l=new Set;for(const e of a)l.has(e.name)&&c.push(`Duplicate variable name "${e.name}".`),l.add(e.name),e.tag_type&&!Ve(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),"string"==typeof e.additional_options&&""!==e.additional_options.trim()&&c.push(`"${e.name}" has additional_options that are text, not JSON (an object or a list).`),Qe.test(e.name)||c.push(`"${e.name}" contains a character MI's own editor doesn't allow (only letters, digits, underscore, hyphen, and whitespace).`);try{await s.saveTemplateVariablesFile(Buffer.from(r,"utf-8"))}catch(e){return void t.status(500).json({error:`Failed to write ${pe}.`,details:e instanceof Error?e.message:String(e)})}t.json({ok:!0,warnings:c})}),e.get("/@api/variables/values",async(e,t)=>{const{distService:s,miAPI:r}=n.deps;try{const e=await rt(s),n=await r.getLivePageVariables(),i=function(e,t){const s=(e?.tags??[]).filter(e=>"string"==typeof e?.name&&""!==e.name),r=new Map(s.map(e=>[e.name,e])),n=new Map(t.map(e=>[e.name,e.value])),i=new Set([...r.keys(),...n.keys()]);return Array.from(i).map(e=>({name:e,value:n.get(e)??r.get(e)?.default_value??""}))}(e,n);t.json({schema:e,live:n,combined:i,local:r.localPageVariables??null})}catch(e){t.status(502).json({error:"Failed to fetch live page variables.",details:e instanceof Error?e.message:String(e)})}}),e.put("/@api/variables/values",async(e,t)=>{const{distService:s,miAPI:r}=n.deps,i=function(e){const t="object"==typeof e&&null!==e?e.tags:void 0;if(!Array.isArray(t))return null;const s=[];for(const e of t){if("object"!=typeof e||null===e)return null;const{name:t,value:r}=e;if("string"!=typeof t||!t||"string"!=typeof r)return null;s.push({name:t,value:r})}return s}(e.body);if(!i)return void t.status(400).json({error:"Request body must be { tags: {name, value}[] }."});const a=i.map(e=>e.name).find((e,t,s)=>s.indexOf(e)!==t);if(void 0===a)try{const e=await rt(s),n=new Map((e?.tags??[]).map(e=>[e.name,e])),a=[];for(const e of i){const t=n.get(e.name);t&&a.push(...Xe(t,e.value))}let o;await r.applyPageVariables(i);try{await r.reloadPageVariables()}catch(e){o=e instanceof Error?e.message:String(e)}t.json({ok:!0,warnings:a,local:r.localPageVariables??null,...o?{localError:o}:{}})}catch(e){t.status(502).json({error:"Failed to save live page variables.",details:e instanceof Error?e.message:String(e)})}else t.status(400).json({error:`Variable "${a}" is listed more than once.`})}),e.post("/@api/variables/values/local",async(e,t)=>{const{miAPI:s}=n.deps;try{await s.reloadPageVariables(),t.json({local:s.localPageVariables??null})}catch(e){t.status(502).json({error:"Failed to update the local values.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/pages",async(e,t)=>{const{miAPI:s}=n.deps;try{const e=await s.listPages(),r=e=>void 0!==s.pageId?e.id===s.pageId:e.internal_name===s.internalPageName,n=e.find(r)??null,i=e.filter(e=>!r(e)).map(e=>({id:e.id,name:e.name,internal_name:e.internal_name,sameTemplate:!!n&&(null!=n.template_id?e.template_id===n.template_id:!!n.template&&e.template===n.template)}));t.json({pages:i,currentPageName:n?.name??null})}catch(e){t.status(502).json({error:"Failed to fetch the page list.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/import-plan/:pageId",async(e,t)=>{const{distService:s,miAPI:r}=n.deps,i=Number(e.params.pageId);if(!Number.isInteger(i)||i<=0)t.status(400).json({error:"pageId must be a positive integer."});else try{const e=await rt(s),n=await r.getPageVariablesFor(i);t.json(function(e,t){const s=new Map((e?.tags??[]).map(e=>[e.name,e])),r=[],n=[];for(const e of t){const t=s.get(e.name);if(!t){n.push({name:e.name,sourceValue:e.value,reason:"Not in the current page's schema."});continue}const i=Ze(t,e.value);i?n.push({name:e.name,sourceValue:e.value,reason:i}):r.push({name:e.name,sourceValue:e.value,tagType:t.tag_type||"text"})}return{importable:r,skipped:n}}(e,n))}catch(e){t.status(502).json({error:"Failed to fetch values from the selected page.",details:e instanceof Error?e.message:String(e)})}}),_e(e,{path:Ye,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(n.deps.miAPI.isTemplateLess))})})}const it=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,at=new RegExp(`^(?:${it})$`),ot=".localhost";function ct(e){return e?e.length>32?"The name must be at most 32 characters long":at.test(e)?void 0:'The name may contain only lowercase latin letters, digits and "-", must start with a letter and must not end with "-"':"The name is required"}function lt(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(ot))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function dt(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${ye(e)?"https":"http"}://${t?`${t}.`:""}localhost${s?`:${s}`:""}`}const ut=new class{#e=new Map;#t=new Set;#s=new Set;#r=!1;#n=new Set;#i;#a=new Map;#o=new WeakMap;#c;useContext(e){void 0!==this.#c&&this.#c!==e&&this.clear(),this.#c=e}get context(){return this.#c}list(){return[...this.#e.values()]}get(e){return this.#e.get(e)}add(e){const t=ct(e.name);if(t)throw new Error(t);if(this.#e.has(e.name))throw new Error(`A user named "${e.name}" already exists`);if("token"===e.kind&&!e.token)throw new Error("A token user needs an API token");const s="session"===e.kind?{state:"pending",...e}:{...e};return this.#a.delete(s.name),this.#e.set(s.name,s),this.#l(),s}replace(e,t){if(!this.#e.has(e))throw new Error(`There is no user named "${e}"`);const s=ct(t.name);if(s)throw new Error(s);if(t.name!==e&&this.#e.has(t.name))throw new Error(`A user named "${t.name}" already exists`);const r=this.#i===e,n=[...this.#a].filter(([,t])=>t===e).map(([e])=>e);let i;this.#r=!0;try{this.remove(e),i=this.add(t)}catch(s){throw this.#r=!1,this.#l(),s}finally{this.#r=!1}for(const s of t.name===e?n:[...n,e])this.#a.set(s,i.name);return r&&(this.#i=i.name),this.#l(),i}#l(){this.#r||this.#s.forEach(e=>e())}renamedTo(e){return this.#a.get(e)}remove(e){const t=this.#e.get(e);if(!t)return!1;this.#i===e&&(this.#i=void 0);for(const[t,s]of this.#a)s===e&&this.#a.delete(t);return this.#e.delete(e),this.#t.forEach(e=>e(t)),this.#l(),!0}clear(){for(const e of[...this.#e.keys()])this.remove(e)}onRemove(e){return this.#t.add(e),()=>{this.#t.delete(e)}}onSessionChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}sessionChanged(e){this.#e.get(e.name)===e&&this.#n.forEach(t=>t(e))}onChange(e){return this.#s.add(e),()=>{this.#s.delete(e)}}get defaultUser(){return void 0===this.#i?void 0:this.#e.get(this.#i)}setDefaultUser(e){if(void 0===e)return void(this.#i=void 0);const t=this.#e.get(e);if(!t)throw new Error(`There is no user named "${e}"`);if("session"===t.kind&&("active"!==t.state||!t.session))throw new Error(`"${e}" has to log in on its own host before it can be the default user`);if("token"===t.kind&&"expired"===t.state)throw new Error(`MI turned down the API token of "${e}"`);this.#i=e}resolve(e){if(this.#o.has(e))return this.#o.get(e);const t=lt(e.headers.host);let s;if(void 0===t){const t="localhost"===(e.headers.host??"").toLowerCase().replace(/:\d+$/,"")?this.defaultUser:void 0;s={key:t?.name??"",user:t}}else{const e=this.#e.get(t)??this.#e.get(this.#a.get(t)??"");s=e?{key:e.name,user:e}:void 0}return this.#o.set(e,s),s}};function pt(e=ut){return(t,s,r)=>{const n=e.resolve(t),i=lt(t.headers.host)??"";if(n?.user&&i&&n.key!==i&&function(e){if("GET"!==e.method&&"HEAD"!==e.method)return!1;const t=e.headers["sec-fetch-mode"];return"string"==typeof t?"navigate"===t:String(e.headers.accept??"").includes("text/html")}(t)){const e=t.originalUrl??t.url??"/";return s.statusCode=302,s.setHeader("Location",`${dt(t,n.key)}${e}`),s.setHeader("Cache-Control","no-store"),void s.end()}n?r():(s.statusCode=404,s.setHeader("Content-Type","text/plain; charset=utf-8"),s.setHeader("Cache-Control","no-store"),s.end(`pp-dev has no user named "${i}". Open users from the pp-dev dev panel on the main host.`))}}async function ht(e,t){try{const s=(await e.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",...t},!0,{quiet:!0})).data;if("object"!=typeof s||null===s)throw new Error(`${je}.${Ne}`);const r=s.user;return"number"==typeof r?.user_id?{miUser:{id:r.user_id,username:"string"==typeof r.username?r.username:""}}:{miUser:void 0}}catch(e){if(Ee(e))return{miUser:void 0,refused:Te(e).userFriendlyMessage};throw e}}async function gt(e,t){try{const s=await ht(e,{Authorization:`Bearer ${t}`});return s.miUser?{ok:!0,miUser:s.miUser}:{ok:!1,rejected:!0,message:s.refused?`The API token was rejected: ${s.refused}`:"The API token is expired or invalid"}}catch(e){return{ok:!1,rejected:!1,message:`Could not check the API token with MI: ${Te(e).userFriendlyMessage}`}}}const mt="/@api/users",ft=new WeakMap;function yt(e,t){const s=dt(t,e.name);return{name:e.name,kind:e.kind,...e.state?{state:e.state}:{},..."session"===e.kind?{loginUrl:`${s}/login`}:{},miUser:e.miUser,origin:s}}function wt(e,t,s,r){e.status(t).json({error:r,code:s})}const vt=/(?:^|\/\/[^/]+)\/(?:login|auth\/saml\/login)(?:[/?#]|$)/i;function bt(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==ve)}function kt({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&vt.test(String(t.location??""))}class $t{#e;#d;#u=a.createLogger();#p=new WeakMap;#h=new WeakMap;#g=new WeakMap;#m=new WeakMap;constructor(e,t){this.#e=e,this.#d=t}isLeftBehindRequest(e,t,s){const r=lt(t.headers.host)===e.name?ke(t.headers.cookie,ve):s;return void 0!==r&&this.#f(e,r)}observe(e,t,s,r){if("session"!==e.kind||this.#e.get(e.name)!==e)return;const n=lt(t.headers.host)===e.name,i=n?ke(t.headers.cookie,ve):r,a=$e(s.headers["set-cookie"],ve),o=this.#g.get(e);let c,l,d=n;return a&&a!==i?(c=a,l=i):n&&i!==e.session&&!kt(s)?c=i:o&&Date.now()>=o.retryAt&&(c=o.session,d=o.ownHost),c&&c===o?.session&&void 0===l&&(l=o.replaced),"active"===e.state&&kt(s)&&i===e.session&&this.#y(e,`MI turned away ${t.method} ${t.url}`),c&&c!==e.session&&c!==this.#p.get(e)&&c!==this.#h.get(e)&&!this.#f(e,c)?this.#w(e,c,l,d):void 0}async#w(e,t,s,r){let n;this.#p.set(e,t);try{n=await this.#d(t)}catch(n){return this.#p.get(e)===t&&(this.#p.delete(e),this.#g.set(e,{session:t,replaced:s,ownHost:r,retryAt:Date.now()+5e3})),void this.#u.warn(a.colors.yellow(`Could not check the MI session of user ${e.name}: ${String(n)}`))}if(this.#p.get(e)===t&&this.#e.get(e.name)===e)if(this.#p.delete(e),this.#g.get(e)?.session===t&&this.#g.delete(e),n){if(this.#f(e,t)||void 0!==s&&this.#f(e,s))return;const i="active"===e.state;r&&(this.#v(e),void 0!==s&&s!==t&&this.#v(e,s)),this.#g.delete(e),Object.assign(e,{state:"active",session:t,miUser:n}),this.#h.delete(e),this.#e.sessionChanged(e),i||this.#u.info(`${a.colors.blue("User")} ${a.colors.yellow(e.name)} ${a.colors.blue("logged in")} (MI user ${n.id}${n.username?`, ${n.username}`:""})`)}else this.#h.set(e,t),"active"===e.state&&s===e.session&&this.#y(e,"MI started a guest session")}#f(e,t){return"active"===e.state&&Boolean(this.#m.get(e)?.has(t))}#v(e,t=e.session){if(!t)return;const s=this.#m.get(e)??new Set;s.add(t),s.size>20&&s.delete(s.values().next().value),this.#m.set(e,s)}#y(e,t){this.#v(e),e.state="expired",e.session=void 0,this.#p.delete(e),this.#g.delete(e),this.#e.sessionChanged(e),this.#e.defaultUser===e&&this.#e.setDefaultUser(void 0),this.#u.warn(`${a.colors.yellow(`The MI session of user ${e.name} ended`)} (${t}). Log in again on its host.`)}}const St=/^(https?:\/\/)([^/]+)(\/.*)?$/i,xt="X-PP-Proxy";const At=/^\/login(?:\/|$)/i,Tt="/auth/saml/login";const Et=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const It=new WeakMap,Pt=new WeakMap;const Lt=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function jt(e){const t=e.split(";",1)[0].trim().toLowerCase();return Lt.some(e=>e.test(t))}const Nt=/[\w.:/\\!-]/;function Rt(e){const t=e["content-encoding"];if("string"==typeof t&&t.trim()&&"identity"!==t.trim())return!1;const s=e["content-type"];return"string"==typeof s&&jt(s)}function Bt(e){return async(t,s,r)=>{const n=e&&Rt(t.headers);r.statusCode=t.statusCode??r.statusCode,t.statusMessage&&(r.statusMessage=t.statusMessage),r.setHeader(xt,1);for(const[e,s]of Object.entries(t.headers))void 0!==s&&(n&&"content-length"===e.toLowerCase()||r.setHeader(e,s));if(!n)return void t.pipe(r);const i=new y.StringDecoder("utf8");let a="",o=!1;const c=s=>{if(!s)return;r.write(e(Buffer.from(s,"utf8"),"utf8"))||o||(o=!0,t.pause(),r.once("drain",()=>{o=!1,t.resume()}))};t.on("data",e=>{a+=i.write(e);const t=a.lastIndexOf("\n");if(-1!==t&&(c(a.slice(0,t+1)),a=a.slice(t+1)),a.length>=65536){const e=function(e){for(let t=e.length-1;t>=0;t-=1)if(!Nt.test(e[t]))return t;return-1}(a)+1||a.length;c(a.slice(0,e)),a=a.slice(e)}}),t.on("end",()=>{c(a+i.end()),a="",r.end()}),t.on("error",()=>{r.end()})}}function Ct(t){const{rewritePath:s=/^\/(?!p[tl]).*/i,baseURL:r="",disableSSLValidation:n=!1,miAPI:i,templateName:o,users:c=ut}=t;if(!r)throw new Error("Base url is required");const l=function(e){try{return new URL(e).host}catch{return e.replace(St,"$2")}}(r),d=r.replace(St,"$1$2"),u=import("file-type"),p=a.createLogger(),h=t.sessionUsers??new $t(c,function(e){return async t=>(await ht(e,{Cookie:`${ve}=${t}`})).miUser}(i));return f.createProxyMiddleware({selfHandleResponse:!0,pathFilter:(e,r)=>!(t.proxyIgnore||[]).some(t=>"string"==typeof t?e.startsWith(t):"function"!=typeof t.test||t.test(e))&&("string"==typeof s?e.startsWith(s):Array.isArray(s)?s.some(t=>e.startsWith(t)):"function"==typeof s.test&&s.test(e)),target:r,changeOrigin:!0,logger:{info:()=>{},warn:()=>{},error:()=>{}},secure:!n,headers:{host:l,origin:d},on:{proxyReq(t,s,n){const l=s.headers.host,d=t.getHeader("referer");l&&d&&"string"==typeof d&&t.setHeader("referer",d.replace(function(e){let t=q.get(e);return t||(t=new RegExp(`^https?://${H(e)}(?=[/?#]|$)`,"i"),q.set(e,t)),t}(l),r));const u=c.resolve(s);let h;u?.user?h=u.user.token:u&&(h=i.personalAccessToken),h?(t.setHeader("Authorization",`Bearer ${h}`),It.set(s,h)):"session"===u?.user?.kind&&t.removeHeader("Authorization"),u?.user&&t.removeHeader("Token");const g="session"===u?.user?.kind?u.user:void 0;let m;if(g&&lt(s.headers.host)!==g.name){m=g.session;const e=m?(f=s.headers.cookie,y=m,[...bt(f),`${ve}=${y}`].join("; ")):function(e){const t=bt(e);return t.length?t.join("; "):void 0}(s.headers.cookie);e?t.setHeader("cookie",e):t.removeHeader("cookie")}var f,y;Pt.set(s,{user:u?.user,sentSession:m}),t.removeHeader("if-none-match"),t.removeHeader("if-modified-since");const w=s.url??"/",v=function(t,s,r,n){if(!s||!r||!n||r===n)return t;try{const s=new e.URL(t,"http://localhost"),i=s.pathname.match(/^\/data\/page\/([^/]+)(\/.*)?$/);if(!i)return t;let a;try{a=decodeURIComponent(i[1])}catch{a=i[1]}if(a!==r)return t;return`/data/page/${n}${i[2]??""}`+s.search+s.hash}catch{return t}}(w,i.v7Features,o,i.internalPageName);v!==w&&(s.url=v,t.path=v,console.info(`${a.colors.cyan("Rewrites data page to correct internal page name")}: ${a.colors.yellow(w)} ${a.colors.blue("→")} ${a.colors.green(v)}`)),p.info(`${a.colors.blue("Proxies request:")} ${a.colors.green(s.method)} ${s.url} -> ${a.colors.green(t.method)} ${t.protocol}//${t.host}${t.path}${u?.user?` ${a.colors.blue("as")} ${a.colors.yellow(u.user.name)}`:""}`);const{socket:b}=s,k=()=>{setTimeout(()=>{t.destroyed||t.destroy()},200)};return b.once("close",k),t.once("close",()=>b.off("close",k)),t},proxyRes:(e,t,s)=>{s.setHeader(xt,1),e.headers["set-cookie"]&&(e.headers["set-cookie"]=Se(e.headers["set-cookie"],ye(t))),e.headers.location&&(e.headers.location=function(e,t,s){const r=s.headers.host;let n;try{n=new URL(e)}catch{return e}return r&&/^https?:$/.test(n.protocol)&&n.host===t.toLowerCase()?e.replace(/^https?:\/\/[^/?#]*/i,`${ye(s)?"https":"http"}://${r}`):e}(e.headers.location,l,t));const r=function(e,t){if(!Et.test(e.url??""))return;const s=lt(e.headers.host);return void 0===s?void 0:t.get(s)}(t,c),n=Pt.get(t);if(r){e.resume();const i={"cache-control":"no-store"};n?.user===r&&(c.remove(r.name),p.info(`${a.colors.blue("Logged out user")} ${a.colors.yellow(r.name)}, back to the main host`),e.headers["set-cookie"]&&(i["set-cookie"]=e.headers["set-cookie"]));const o=t.headers["sec-fetch-mode"];return o&&"navigate"!==o?s.writeHead(204,i):s.writeHead(302,{...i,location:`${dt(t)}/`}),void s.end()}const i=n?.user;let o=!0;if(i&&c.get(i.name)!==i)o=!1;else if(i){let s=!1;"session"===i.kind&&(s=h.isLeftBehindRequest(i,t,n?.sentSession),h.observe(i,t,e,n?.sentSession)),o=lt(t.headers.host)===i.name&&!s}if(!o){const t=function(e){const t=(e??[]).filter(e=>void 0===$e(e,ve));return t.length?t:void 0}(e.headers["set-cookie"]);t?e.headers["set-cookie"]=t:delete e.headers["set-cookie"]}e.headers["cache-control"]="no-store",delete e.headers.expires,delete e.headers.pragma;const d=(e,s)=>Buffer.from(W(Tt,"/login",z(l,t.headers.host??"",e.toString(s))),s);if(e.headers["content-type"]?.includes("text/event-stream")||e.headers["transfer-encoding"]?.includes("chunked")&&"no"===e.headers["x-accel-buffering"])return p.info(`${a.colors.blue("Start streaming for request:")} ${a.colors.green(t.method)} ${t.url}`),Bt(d)(e,t,s);const g=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!jt(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&Rt(e)&&!function(e){const t="string"==typeof e?e.split(";",1)[0].trim().toLowerCase():"";return"text/html"===t||"application/xhtml+xml"===t}(t)?"stream":"buffer"}(e.headers);if("stream"===g&&(e.headers["x-accel-buffering"]="no"),"buffer"!==g)return Bt("stream"===g?d:void 0)(e,t,s);const m=f.responseInterceptor(async(e,t,s,r)=>{r.setHeader(xt,1);if(await(await u).fileTypeFromBuffer(e))return e;{let t=e.toString("utf8");try{const e=new URL(s.url??"",`http://${l}`);if(e.searchParams&&e.searchParams.has("proxyRedirect")){const e=function(){const e="pp-dev::redirectCount",t="pp-dev::lastRedirect";let s=+(localStorage.getItem(e)??0);localStorage.getItem(t);Number.isNaN(s)&&(s=0);let r=window.location.href;const n=function(){const i=new URLSearchParams(window.location.search);if(!i.has("proxyRedirect"))return console.debug("No proxyRedirect param. Cleaning up."),void localStorage.removeItem(e);r!==window.location.href?(r=window.location.href,setTimeout(n,s<3?3e3:5e3)):window.location.href=i.get("proxyRedirect"),localStorage.setItem(e,""+ ++s),localStorage.setItem(t,(new Date).toISOString())};setTimeout(n,3e3)};t+=`<script>(${e.toString()})()<\/script>`}const r=t.slice(0,100);At.test(e.pathname)&&(r.includes("<html")||r.includes("<body")||r.includes("<head")||r.includes("html>"))&&!lt(s.headers.host)&&(t+=`<script>(${xe.toString()})(${n=l,JSON.stringify(n).replace(/</g,"\\u003c")})<\/script>`)}catch{}const r=s.headers.host??"";return W(Tt,"/login",z(l,r,t))}var n});return m(e,t,s)},error(e,t,s){!function(e,t,s,r){const n=`Proxy error: "${e.message}" when trying to "${t.method} ${t.url}"`;if(r(`${n}\n\n${e.stack??""}`),"function"!=typeof s.writeHead)return void s.destroy();const i=s;i.writableEnded||i.destroyed||(i.headersSent?i.destroy():(i.writeHead(502,{"Content-Type":"text/plain; charset=utf-8"}),i.end(n)))}(e,t,s,e=>p.error(e))}}})}const Ft=/\.(?:[a-z0-9]+)$/i,Mt=6e5,Ot=104857600,Dt=1e3,Ut=10485760;const _t=new class{items=new Map;totalSize=0;maxSize;maxItems;constructor(e,t){this.maxSize=e,this.maxItems=t}get(e){const t=this.items.get(e);return t?t.expiresAt<=Date.now()?(this.del(e),null):t.value:null}put(e,t,s=Mt){return this.del(e),this.items.set(e,{value:t,expiresAt:Date.now()+s}),this.totalSize+=t.size,this.cleanup(),t}del(e){const t=this.items.get(e);return!!t&&(this.totalSize-=t.value.size,this.items.delete(e))}clear(){this.items.clear(),this.totalSize=0}keys(){return this.purgeExpired(),[...this.items.keys()]}getTotalSize(){return this.totalSize}getItemCount(){return this.keys().length}purgeExpired(){const e=Date.now();for(const[t,s]of this.items)s.expiresAt<=e&&this.del(t)}cleanup(){for(this.purgeExpired();this.items.size>0&&(this.items.size>this.maxItems||this.totalSize>this.maxSize);)this.del(this.items.keys().next().value)}}(Ot,Dt),Ht=new Set,Vt=new Map;function qt(e){_t.clear(),Vt.clear(),Ht.forEach(e=>e()),a.createLogger().info(a.colors.blue(`Proxy cache cleared: ${e}`))}const zt=new WeakSet;function Wt(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function Jt(e,t){if(e){for(const t of _t.keys())Wt(t,e)&&_t.del(t);Vt.delete(e),a.createLogger().info(a.colors.blue(`Proxy cache cleared for ${e}: ${t}`))}else qt(t)}function Gt(e,t,s){const r=function(e){return It.get(e)}(e);if(void 0!==r){const e=Vt.get(s),t=void 0!==e&&r!==e;return Vt.set(s,r),t?"personal access token changed":void 0}const n=$e(t.getHeader("set-cookie"),ve);return void 0!==n&&n!==ke(e.headers.cookie,ve)?"MI session changed":void 0}function Kt(e){if(0===e.length)return Buffer.alloc(0);if(1===e.length)return e[0];const t=e.reduce((e,t)=>Buffer.byteLength(t)+e,0);return Buffer.concat(e,t)}function Xt(e){const{devServer:t,ttl:s=Mt,maxSize:r=Ot,maxItems:n=Dt,users:i=ut}=e,o=a.createLogger();return r===Ot&&n===Dt||(_t.maxSize=r,_t.maxItems=n),t&&(t.cache=_t),zt.has(i)||(zt.add(i),i.onRemove(e=>Jt(e.name,"user removed")),i.onSessionChange(e=>Jt(e.name,"MI session changed or ended"))),(e,t,r)=>{const n=i.resolve(e);if(!n)return r();t.once("finish",()=>{const s=t.hasHeader(xt)?Gt(e,t,n.key):void 0;s&&Jt(n.key,`${s} (${e.method} ${G(e.url??"")})`)});const c=n.user?.session,l=e.originalUrl||e.url||"",d="GET"===e.method?function(e,t,s){const r=e.split("?")[0];return Ft.test(r)?r.includes("/auth/info.js")?"":t?`@${t}@${s}:${e}`:`${s}:${e}`:""}(l,n.key,e.headers.host??""):"";if(!d||!function(e,t){const{user:s}=t;return"session"!==s?.kind||!!s.session&&(lt(e.headers.host)!==s.name||ke(e.headers.cookie,ve)===s.session)}(e,n))return r();const u=_t.get(d);if(u)return o.info(`${a.colors.blue("Proxies request:")} ${a.colors.green(e.method)} ${l} -> ${a.colors.blue("Cache")} ${d}`),function(e,t){try{for(const[s,r]of Object.entries(t))null!=r&&e.setHeader(s,r)}catch(e){a.createLogger().warn(`Failed to set some response headers: ${e instanceof Error?e.message:String(e)}`)}}(t,u.headers),t.setHeader("X-PP-Cache","hit"),t.write(u.content),void t.end();const p=t.end,h=t.write,g=[];let m=0,f="undecided";const y=(e,t)=>null==e?null:"string"==typeof e?Buffer.from(e,t||"utf8"):e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf8"),w=()=>{f="pass";for(const e of g.splice(0))h.call(t,e)},v=()=>{"undecided"===f&&(t.hasHeader(xt)?!function(e){if(200!==e.statusCode)return!1;if(/^text\/event-stream/i.test(String(e.getHeader("content-type")??"")))return!1;if("no"===String(e.getHeader("x-accel-buffering")??"").toLowerCase())return!1;const t=Number(e.getHeader("content-length"));return!(Number.isFinite(t)&&t>=Ut)}(t)?w():f="buffer":f="pass")};t.write=function(e,t,s){if(v(),"pass"===f)return h.call(this,e,t,s);const r="function"==typeof t?t:s,n=y(e,"string"==typeof t?t:void 0);return n&&(g.push(n),m+=n.length),m>Ut&&w(),r&&process.nextTick(r),!0},t.end=function(e,r,l){if(v(),"pass"===f)return p.call(this,e,r,l);"function"==typeof e?(l=e,e=void 0):"function"==typeof r&&(l=r,r=void 0);const u=y(e,"string"==typeof r?r:void 0);let h;u&&g.push(u);try{h=Kt(g);const e=Buffer.byteLength(h);if(200===t.statusCode&&e>0&&e<Ut&&function(e,t,s){return!e.user||s.get(e.key)===e.user&&e.user.session===t}(n,c,i)){const{"set-cookie":r,...n}=t.getHeaders(),i={headers:n,content:h,timestamp:Date.now(),size:e};_t.put(d,i,s),o.info(`${a.colors.blue("[Cached]")} ${d} (${(e/1024).toFixed(1)}KB)`)}}catch(e){o.error(`Failed to cache response for ${d}: ${e}`),h=Kt(g)}return p.call(this,h,l)},r()}}function Zt(e){let t;try{t=JSON.parse(R.readFileSync(e,"utf-8"))}catch(t){return"ENOENT"!==t.code&&a.createLogger().warn(a.colors.yellow(`Could not read the saved users from ${e}: ${String(t)}`)),[]}const s=t&&"object"==typeof t&&!Array.isArray(t)?t.users:void 0;return(Array.isArray(s)?s:[]).filter(e=>"string"==typeof e?.name&&"string"==typeof e.token&&Boolean(e.token))}function Yt(e,t,s){const r={version:1,...s,users:t};R.mkdirSync(D.dirname(e),{recursive:!0,mode:448}),function(e,t,s){const r=X(e);try{N.writeFileSync(r,t,s),N.renameSync(r,e)}catch(e){throw N.rmSync(r,{force:!0}),e}}(e,`${JSON.stringify(r,null,2)}\n`,{mode:384}),R.chmodSync(e,384)}const Qt=new WeakMap,es=new WeakMap;function ts(e){Qt.delete(e),es.get(e)?.(),es.delete(e)}async function ss(e,t){const s=function(e,t,s=O.homedir()){const r=u.createHash("sha256").update(`${D.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return D.join(s,".pp-dev","users",`${r}.json`)}(t.projectRoot,t.miUrl,t.homeDir),r={project:D.resolve(t.projectRoot),miUrl:t.miUrl},n=a.createLogger();if(Qt.get(e)===s)return;ts(e),Qt.set(e,s);const i=Zt(s);let o=!0,c=!1,l=e.list().some(e=>"token"===e.kind&&e.token);const d=new Set,p=new Set,h=()=>{const t=e.list(),i=t.filter(e=>"token"===e.kind&&e.token).map(e=>({name:e.name,token:e.token})),o=new Set(t.map(e=>e.name)),c=Zt(s).filter(e=>!o.has(e.name)&&!p.has(e.name));try{Yt(s,[...i,...c],r)}catch(e){n.warn(a.colors.yellow(`Could not save the users to ${s}: ${String(e)}`))}},g=e.onRemove(t=>{Qt.get(e)===s&&(p.add(t.name),o&&d.add(t.name))}),m=e.onChange(()=>{Qt.get(e)===s&&(o?l||=!c:h())});es.set(e,()=>{g(),m()});try{const r=await Promise.all(i.map(e=>t.checkToken(e.token)));if(Qt.get(e)!==s)return;i.forEach((t,s)=>{if(ct(t.name)||e.get(t.name)||d.has(t.name))return;const i=r[s];c=!0;try{e.add({name:t.name,kind:"token",token:t.token,...i.ok?{miUser:i.miUser}:{},...!i.ok&&i.rejected?{state:"expired"}:{}})}finally{c=!1}i.ok||n.warn(a.colors.yellow(`Restored user ${t.name}: ${i.message}`))})}finally{o=!1}l&&Qt.get(e)===s&&h(),i.length&&n.info(`${a.colors.blue("Restored")} ${i.length} ${a.colors.blue("saved user(s) from")} ${s}`)}function rs(e){const t=`${D.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;ut.context!==t&&(ts(ut),ut.useContext(t)),e.persist?e.miAPI.personalAccessToken?ss(ut,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>gt(e.miAPI,t)}).catch(e=>{a.createLogger().warn(a.colors.yellow(`Could not restore the saved users: ${String(e)}`))}):a.createLogger().warn(a.colors.yellow("users.persist is on, but users need your own API token (mi.token or MI_ACCESS_TOKEN).")):ts(ut)}function ns(e,t,s,r,n){const i={error:s};r&&(i.details=r),n&&(i.code=n),e.status(t).json(i).end()}function is(e){return["/@vite","/@metricinsights","/@",(e.endsWith("/")?e.slice(0,-1):e)||"/"]}function as(e){const{distService:t,miAPI:s,persistUsers:r,projectRoot:n,miUrl:i}=e,o=new Oe(e.server,{distService:t,miAPI:s});return function(e,t){const{miAPI:s,persistUsers:r,projectRoot:n,miUrl:i}=t,o=a.createLogger(),c=(e,t,s)=>{o.error(`${s} token validation error: ${t instanceof Error?t.message:String(t)}`);const r=Te(t),n=t?.tokenErrorInfo;if(n)return ns(e,n.status||500,n.userFriendlyMessage,n.message,n.code),null;let i,a,c;switch(r.code){case"SESSION_EXPIRED":i=412,a="personal"===s?"Personal access token expired":"Session expired",c="personal"===s?"PAT_EXPIRED":"SESSION_EXPIRED";break;case"UNAUTHORIZED":i=401,a="Unauthorized",c="UNAUTHORIZED";break;case"FORBIDDEN":i=403,a="Access forbidden",c="FORBIDDEN";break;default:i=500,a="Internal server error",c=r.code}return ns(e,i,a,"personal"===s&&"PAT_EXPIRED"===c?"Your personal access token has expired. Please generate a new token from the portal.":"regular"===s&&"SESSION_EXPIRED"===c?"Your portal session has expired. Please refresh your token or re-authenticate.":r.userFriendlyMessage,c),null};e.post("/@api/login",async(e,t)=>{const{token:a,tokenType:l}=e.body??{};if(lt(e.headers.host))ns(t,409,"Token login is only available on the main host","This tab belongs to a saved pp-dev user. Log in with a token on the main host (localhost).","USER_HOST");else if("string"==typeof a&&a)if(o.info(`Attempting to validate ${String(l)} token...`),"personal"===l){if(!await s.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${a}`},!0).then(e=>"object"!=typeof e.data||null===e.data?(ns(t,502,"MI is unavailable","The instance may be down or in maintenance mode. Please try again later.","MI_UNAVAILABLE"),null):"number"==typeof e.data?.user?.user_id?(s.personalAccessToken=a,o.info(`Personal access token validated successfully for user ${e.data.user.user_id}`),e):(ns(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"personal")))return;qt("logged in with a personal access token"),rs({persist:r,miAPI:s,projectRoot:n,miUrl:i}),J(t,"/",302)}else if("regular"===l){if(!await s.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:a},!0).then(r=>r.data?.users?.length?(s.personalAccessToken=void 0,o.info(`Regular token validated successfully for ${r.data.users.length} user(s)`),t.setHeader("set-cookie",Se(r.headers["set-cookie"],ye(e))??""),r):(ns(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"regular")))return;qt("logged in with a token"),J(t,"/",302)}else ns(t,400,"Invalid tokenType",'tokenType must be "personal" or "regular".',"INVALID_TOKEN_TYPE");else ns(t,400,"Token is required")})}(e.internalServer,{miAPI:s,persistUsers:r,projectRoot:n,miUrl:i}),nt(e.internalServer,{distService:t,miAPI:s}),function(e,t){const s=ft.get(e);if(s)return void(s.deps=t);const r={deps:t};ft.set(e,r);const n=a.createLogger(),i=()=>r.deps.users??ut;e.get(mt,(e,t)=>{const s=i();t.json({available:Boolean(r.deps.miAPI.personalAccessToken),users:s.list().map(t=>yt(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${mt}/default`,(e,t)=>{const s=i(),r=(e.body??{}).name;if(null===r||"string"==typeof r)if(null===r||s.get(r)){try{s.setDefaultUser(r??void 0)}catch(e){return void wt(t,409,"NOT_LOGGED_IN",e instanceof Error?e.message:String(e))}n.info(`${a.colors.blue("Default user:")} ${a.colors.yellow(r??"the original user")}`),t.json({defaultUser:r})}else wt(t,404,"NOT_FOUND",`There is no user named "${r}"`);else wt(t,400,"INVALID_NAME","name must be a user name or null")}),e.post(mt,async(e,t)=>{const{miAPI:s}=r.deps,o=i(),c=e.body??{},l="string"==typeof c.name?c.name:"",d="string"==typeof c.token?c.token.trim():"",u=c.kind??"token";if("token"!==u&&"session"!==u)return void wt(t,400,"INVALID_KIND",'kind must be "token" or "session"');if(!s.personalAccessToken)return void wt(t,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=ct(l);if(p)return void wt(t,400,"INVALID_NAME",p);if(o.get(l))return void wt(t,409,"NAME_TAKEN",`A user named "${l}" already exists`);if("session"===u){const s=o.add({name:l,kind:"session"});return n.info(`${a.colors.blue("Added user")} ${a.colors.yellow(s.name)}: log in at ${dt(e,s.name)}/login`),void t.status(201).json({user:yt(s,e)})}if(!d)return void wt(t,400,"TOKEN_REQUIRED","The API token is required");const h=o.context,g=await gt(s,d);if(o.context!==h||r.deps.miAPI!==s||i()!==o)return void wt(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!g.ok)return void(g.rejected?wt(t,400,"INVALID_TOKEN",g.message):wt(t,502,"MI_UNAVAILABLE",g.message));const{miUser:m}=g;let f;try{f=o.add({name:l,kind:"token",token:d,miUser:m})}catch(e){return void wt(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}n.info(`${a.colors.blue("Added user")} ${a.colors.yellow(f.name)} (MI user ${m.id}${m.username?`, ${m.username}`:""}) at ${dt(e,f.name)}`),t.status(201).json({user:yt(f,e)})}),e.patch(`${mt}/:name`,async(e,t)=>{const{miAPI:s}=r.deps,o=i(),c=String(e.params.name),l=o.get(c),d=e.body??{},u="string"==typeof d.name&&d.name?d.name:c,p="string"==typeof d.token?d.token.trim():"";if(!l)return void wt(t,404,"NOT_FOUND",`There is no user named "${c}"`);if("token"!==l.kind)return void wt(t,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=ct(u);if(h)return void wt(t,400,"INVALID_NAME",h);if(u!==c&&o.get(u))return void wt(t,409,"NAME_TAKEN",`A user named "${u}" already exists`);let g,m={...l,name:u};if(p&&(p!==l.token||"expired"===l.state)){const e=o.context,n=await gt(s,p);if(o.context!==e||r.deps.miAPI!==s||i()!==o)return void wt(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!n.ok)return void(n.rejected?wt(t,400,"INVALID_TOKEN",n.message):wt(t,502,"MI_UNAVAILABLE",n.message));const{state:a,...c}=m;m={...c,token:p,miUser:n.miUser}}if(o.get(c)===l)if(u!==c||m.token!==l.token||m.state!==l.state){try{g=o.replace(c,m)}catch(e){return void wt(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}n.info(`${a.colors.blue("Edited user")} ${a.colors.yellow(c)}${u!==c?` → ${a.colors.yellow(u)}`:""}${g.token!==l.token?" (new API token)":""}`),t.json({user:yt(g,e)})}else t.json({user:yt(l,e)});else wt(t,409,"USER_CHANGED",`The user "${c}" changed meanwhile; edit it again`)}),e.delete(`${mt}/:name`,(e,t)=>{const s=String(e.params.name);i().remove(s)?(n.info(`${a.colors.blue("Removed user")} ${a.colors.yellow(s)}`),t.status(204).end()):wt(t,404,"NOT_FOUND",`There is no user named "${s}"`)})}(e.internalServer,{miAPI:s}),rs({persist:r,miAPI:s,projectRoot:n,miUrl:i}),o}function os(e,t){t?function(e,t){const s=t instanceof Error?t.message:String(t);a.createLogger().error(a.colors.red(`Request failed: ${s}`)),e.writableEnded||e.destroyed||(e.headersSent?e.destroy():(e.statusCode=500,e.setHeader("content-type","text/plain; charset=utf-8"),e.end(s)))}(e,t):e.headersSent||e.writableEnded||(e.statusCode=404,e.setHeader("content-type","application/json"),e.end(JSON.stringify({error:"Not found"})))}class cs{axios;constructor(e){this.axios=e}async checkAuth(e){return this.axios.get("/data/page/index/auth/info",{headers:Object.assign({},e,{accept:"text/html"}),maxRedirects:0}).then(()=>!0).catch(()=>!1)}}class ls extends cs{getDownloadUrl(e){return`/admin/page/downloadassets/id/${e}`}getDownloadTemplateUrl(e){return`/admin/pagetemplate/downloadassets/id/${e}`}getUploadUrl(e){return`/admin/page/uploadassets/id/${e}`}getUploadTemplateUrl(e){return`/admin/pagetemplate/uploadassets/id/${e}`}async downloadPageAssets(e,t){return this.download(this.getDownloadUrl(e),t)}async uploadPageAssets(e,t,s){return this.upload(this.getUploadUrl(e),t,s)}async downloadTemplateAssets(e,t){return this.download(this.getDownloadTemplateUrl(e),t)}async uploadTemplateAssets(e,t,s){return this.upload(this.getUploadTemplateUrl(e),t,s)}async download(e,t){return this.axios.get(e,{withCredentials:!0,headers:Object.assign({},t,{accept:"*/*"}),responseType:"arraybuffer"}).then(e=>e.data)}async upload(e,t,s){const r=new FormData;return r.append("file",new File([new Uint8Array(t)],"file.zip",{type:"application/zip"}),"file.zip"),this.axios.post(e,r,{withCredentials:!0,headers:Object.assign({},s,{accept:"application/json","Content-Type":"multipart/form-data",Referer:this.axios.getUri({url:e})})}).then(e=>e.data)}}class ds extends ls{getDownloadUrl(e){return`/api/page/id/${e}/asset/download`}getDownloadTemplateUrl(e){return`/api/page_template/id/${e}/asset/download`}getUploadUrl(e){return`/api/page/id/${e}/asset/upload`}getUploadTemplateUrl(e){return`/api/page_template/id/${e}/asset/upload`}}class us extends cs{async getAll(e){const t=(await this.axios.get("/api/page",{withCredentials:!0,headers:Object.assign({},e,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"})})).data;if("object"!=typeof t||null===t||!Array.isArray(t.pages))throw Be();return t.pages}async get(e,t){const s=(await this.axios.get(`/api/page/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw Be();return s.page}async getPageContent(e,t){return(await this.axios.get(`/p/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"text/html","content-type":"application/json"})})).data}async create(e,t){const s=(await this.axios.post("/api/page",e,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw Be();return s.page}}class ps extends cs{async getAll(e,t){const s=(await this.axios.get("/api/page_template",{withCredentials:!0,headers:Object.assign({},t,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"}),params:{internal_name:e}})).data;if("object"!=typeof s||null===s||!Array.isArray(s.page_templates))throw Ce();return s.page_templates}async get(e,t){const s=(await this.axios.get(`/api/page_template/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page_template||null===s.page_template)throw Ce();return s.page_template}}class hs extends cs{async getById(e,t){const s=(await this.axios.get("/api/page_variable",{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"}),params:{page_id:e}})).data;if("object"!=typeof s||null===s)throw new Error(`${Le}.${Ne}`);return function(e){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch{throw new TypeError('Page variable response contains invalid JSON in "tags".')}if(!Array.isArray(t))throw new TypeError('Page variable response must contain a "tags" array.');const s=t.findIndex(e=>{return!("object"==typeof(t=e)&&null!==t&&"string"==typeof t.name&&"string"==typeof t.value);var t});if(-1!==s)throw new TypeError(`Page variable response contains a malformed entry at index ${s}.`);return t}(s.tags)}async updateById(e,t,s){await this.axios.put("/api/page_variable",{tags:JSON.stringify(t)},{withCredentials:!0,headers:Object.assign({},s,{accept:"application/json","content-type":"application/json"}),params:{page_id:e}})}}const gs="[DEV PAGE. DO NOT DELETE]",ms=new Map;class fs{#b;#k;#$=null;#S;#x;#A=!1;#T=null;#E=null;#I;#P;#L;#j;#N;internalPageName;appId;templateLess;assetsApi;pageApi;pageTemplateApi;pageVariableApi;logger;constructor(e,t){const{headers:s={},appId:r,templateLess:n=!0,disableSSLValidation:i=!1,v7Features:o=!1,personalAccessToken:c}=t||{};this.#b=s,this.#x=[],this.#S="",this.#I=o,this.#P=c,this.#L=!1,this.#j=Promise.resolve(!1);const l=`${e}:${i}`;if(ms.has(l))this.#k=ms.get(l);else{const t=new _.Agent({keepAlive:!1,...i?{rejectUnauthorized:!1}:{}});this.#k=M.create({baseURL:e,headers:s,timeout:3e4,maxRedirects:5,httpAgent:new U.Agent({keepAlive:!1}),httpsAgent:t}),ms.set(l,this.#k)}this.appId=r,this.templateLess=n,this.assetsApi=new(o?ds:ls)(this.#k),this.pageApi=new us(this.#k),this.pageTemplateApi=new ps(this.#k),this.pageVariableApi=new hs(this.#k),this.logger=a.createLogger()}async isTemplateLoaded(){return this.#j}get isV710OrHigher(){return this.#L}get v7Features(){return this.#I}get pageId(){return this.appId}#R(e){const t=Object.assign({},e,{host:void 0,referer:void 0});return Object.keys(t).forEach(e=>void 0===t[e]&&delete t[e]),this.#b=t,!t.authorization&&this.#P&&(t.authorization=`Bearer ${this.#P}`),t}#B(){return this.#R(this.#b)}#C(e){return e.replace(/[.*+?^${}()|[\]\\\/]/g,"\\$&")}get personalAccessToken(){return this.#P}set personalAccessToken(e){this.#P=e}get localTemplateHTML(){return'<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8" />\n <title>%%PAGE TITLE%%</title>\n <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />\n <meta name="theme-color" content="rgba(255, 255, 255, 1)" />\n <link rel="shortcut icon" type="image/x-icon" sizes="any" href="/img/favicon/favicon.ico" />\n <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon/favicon-16x16.png" />\n <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon/favicon-32x32.png" />\n <link rel="icon" type="image/png" sizes="48x48" href="/img/favicon/favicon-48x48.png" />\n <meta name="msapplication-config" content="/auth/browserconfig.xml" />\n <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon/apple-touch-icon.png" />\n <link rel="manifest" href="/auth/site.webmanifest" />\n <link rel="manifest" href="/auth/manifest.json" />\n <link rel="stylesheet" type="text/css" href="/auth/theme-vars.css" />\n <link rel="icon" type="image/svg+xml" href="/favicon.ico" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <script src="/js/libs/underscore-latest.min.js" charset="utf-8"><\/script>\n <script src="/js/jquery/jquery-latest.min.js" charset="utf-8"><\/script>\n <script src="/js/application/rating_component.js" charset="utf-8"><\/script>\n </head>\n <body>\n <div id="mi-react-root"></div>\n <script src="/auth/info.js"><\/script>\n <script src="/js/main.js" defer><\/script>\n <link rel="stylesheet" href="/css/main.css" />\n </body>\n </html>'}async getPageTemplate(e){if(await this.#j||this.#$||(this.#j=new Promise(e=>{this.#N=e})),this.#$)return Promise.resolve(this.#$);if(void 0===this.templateLess&&(this.templateLess=!1),this.#I){const t=await this.pageApi.get(this.appId,this.#R(e)).then(e=>(this.logger.info(a.colors.green("Page fetched")),e)).catch(async t=>{if(this.#N(!1),Fe(t))throw t;throw await this.pageApi.checkAuth(this.#R(e))?(this.logger.error(a.colors.red(`Error fetching page data: ${t.message}\n${t.stack}`)),new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.")):t});return void 0!==t.template_id&&(this.#L=!0),this.internalPageName=t.internal_name,this.#$=this.localTemplateHTML,this.#$=this.#$.replace(/%%PAGE TITLE%%/g,t.name||"Local template"),this.logger.info(a.colors.green("Local page template fetched")),this.#N(!0),this.#$}let t=(await this.pageApi.getAll(this.#R(e)).then(e=>(this.logger.info(a.colors.green("Page list fetched")),e)).catch(async t=>{throw this.#N(!1),await this.pageApi.checkAuth(this.#R(e))?(this.logger.error(a.colors.red(`Error fetching page list: ${t.message}\n${t.stack}`)),new Error("Current user does not have access to page list")):t})).find(e=>e.name===gs);return t||(this.logger.warn(a.colors.yellow("Creating dev page template...")),t=await this.pageApi.create({enabled:"Y",name:gs,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#R(e)).then(e=>(this.logger.info(a.colors.green("Dev page created")),e)).catch(e=>{throw this.logger.error(a.colors.red(`Error creating dev page: ${e.message}`)),this.#N(!1),new Error(`Error when creating dev page.\n That can be caused by missing permissions or page with name "${gs}" already exists`)})),await this.pageApi.getPageContent(t.internal_name,this.#R(e)).then(e=>(this.#$=e,e)).then(e=>(this.#N(!0),this.logger.info(a.colors.green("Page template fetched")),e)).catch(e=>{throw this.#N(!1),this.logger.error(a.colors.red(`Error fetching page template: ${e.message}`)),new Error("Error fetching page template")})}async getPageVariables(e,t){return void 0===this.appId&&(this.appId=e,this.templateLess=!1),this.#$=await this.getPageTemplate(t),await this.pageApi.get(e,this.#R(t)).then(e=>{const{tags:t="[]",name:s,template:r}=e;if(r&&t){const e=JSON.parse(t);return this.#x=e,this.#A=!0,this.#S=s,e}return this.#x=[],this.#A=!0,this.#S=s,[]}).catch(t=>{if(this.logger.error(a.colors.red(`Error fetching page variables: ${t.message}`)),404===t.response?.status)throw new Error(`Portal Page with id "${e}" not found on instance ${this.#k.getUri()}`);if(401===t.response?.status)throw this.logger.warn(`Unauthorized error: ${t}`),new Error(`Current user does not have access to page with id "${e}" on instance ${this.#k.getUri()}`);throw t})}async getLivePageVariables(e=this.#b){if(void 0===this.appId)throw new Error("Cannot fetch live page variables before the page ID is known");const t=this.appId,s=Date.now();this.logger.info(a.colors.cyan(`[page-variables] Fetching live variables for page ID ${t} (page_id lookup)`));const r=await this.pageVariableApi.getById(t,this.#R(e));return this.logger.info(a.colors.green(`[page-variables] Fetched ${r.length} live variable(s) for page ID ${t} in ${Date.now()-s}ms`)),r}async applyPageVariables(e,t=this.#b){if(void 0===this.appId)throw new Error("Cannot apply page variables before the page ID is known");const s=this.appId,r=Date.now();this.logger.info(a.colors.cyan(`[page-variables] Applying ${e.length} variable(s) to page ID ${s} (page_id lookup)`)),await this.pageVariableApi.updateById(s,e,this.#R(t)),this.logger.info(a.colors.green(`[page-variables] Applied variables to page ID ${s} in ${Date.now()-r}ms`))}async listPages(e=this.#b){return this.pageApi.getAll(this.#R(e))}async getPageVariablesFor(e,t=this.#b){return this.pageVariableApi.getById(e,this.#R(t))}get localPageVariables(){return this.templateLess||!this.#A?null:this.#x.map(({name:e,value:t})=>({name:e,value:t}))}get isTemplateLess(){return!!this.templateLess}async reloadPageVariables(e=this.#b){return this.templateLess||void 0===this.appId?null:this.getPageVariables(this.appId,e)}async getPageInfo(e,t){void 0===this.appId&&(this.appId=e);const s=this.#R(t),r=this.appId;try{return this.#I?await this.#F(r,s):await this.#M(r,s)}catch(e){this.#O(e,r)}}async#F(e,t){const s=await this.pageApi.get(e,t);return this.logger.info(a.colors.green("Page fetched")),void 0!==s.template_id&&(this.#L=!0),this.internalPageName=s.internal_name,s}async#M(e,t){return await this.pageApi.get(e,t)}#O(e,t){if(Fe(e))throw e;if(this.#I&&e.message?.includes("access"))throw new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.");if(404===e.response?.status)throw new Error(`Portal Page with id "${t}" not found on instance ${this.#k.getUri()}`);throw 401===e.response?.status&&this.logger.error(a.colors.red(`Current user does not have access to page with id "${t}" on instance ${this.#k.getUri()}`)),e}buildPage(e,t=!1){let s="string"==typeof e?e:e.toString("utf-8");for(const{regExp:e,value:t}of this.#D())s=s.replace(e,()=>t);if(t){return new(o.getJSDOM())(s).serialize()}const{before:r,after:n}=this.#U();return r+s+n}#D(){return this.#T?.vars!==this.#x&&(this.#T={vars:this.#x,replacements:this.#x.map(({name:e,value:t})=>({regExp:new RegExp(`\\[${this.#C(e)}\\]`,"g"),value:t}))}),this.#T.replacements}#U(){const e=this.#$,t=this.#S;if(this.#E?.template===e&&this.#E.title===t)return this.#E;const s=new(o.getJSDOM())(e),{document:r}=s.window,n="%%PLACEHOLDER%%",i=r.createElement("div");i.innerHTML=n;const a=r.querySelector(".main-side");if(a){const e=a.querySelectorAll("script");e.length?a.insertBefore(i,e.item(e.length-1)):a.append(i)}else{const e=r.createElement("div");e.append(i),r.body.append(e)}const c=r.querySelector("head"),l=c.querySelector("title");if(l)l.text=t;else{const e=r.createElement("title");e.textContent=t,c.appendChild(e)}const d=s.serialize(),u=new RegExp(`<div>\\s*${n}\\s*<\\/div>`,"i").exec(d);return this.#E={template:e,title:t,before:d.slice(0,u.index),after:d.slice(u.index+u[0].length)},this.#E}async getAssets(){if(this.appId){const e=this.#B();if(this.templateLess)return await this.assetsApi.downloadPageAssets(this.appId,e);{const t=await this.pageApi.get(this.appId,e);if(this.#L){const s=await this.pageTemplateApi.get(t.template_id,e);return await this.assetsApi.downloadTemplateAssets(s.id,e)}if(t.template)return await this.assetsApi.downloadTemplateAssets(t.template,e)}}}async updateAssets(e){if(this.appId){const t=this.#B();if(this.templateLess)return await this.assetsApi.uploadPageAssets(this.appId,e,t);{const s=await this.pageApi.get(this.appId,t);if(this.#L){const r=await this.pageTemplateApi.get(s.template_id,t);return await this.assetsApi.uploadTemplateAssets(r.id,e,t)}if(s.template)return await this.assetsApi.uploadTemplateAssets(s.template,e,t)}}}async validateCredentials(e){try{const t=e?this.#R(e):this.#B();return await this.get("/api/user",t,!0),{isValid:!0}}catch(e){const t=Te(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,t,s=!1,r={}){const n=s?t:Object.assign({},this.#R(this.#b),t);try{return await this.#k.get(e,{headers:n})}catch(e){if("UNKNOWN_ERROR"!==Te(e).code){const t=Te(e);throw r.quiet||(this.logger.error(a.colors.red(`API request failed: ${t.userFriendlyMessage}`)),function(e,t,s){const r=Te(t),n=`[${s}] `;e.error(a.colors.red(`${n}${r.userFriendlyMessage}`)),e.error(a.colors.red(`Status: ${r.status} (${r.code})`)),e.error(a.colors.red(`Details: ${r.message}`)),r.suggestions.length>0&&(e.info(a.colors.yellow("Suggestions:")),r.suggestions.forEach((t,s)=>{e.info(a.colors.yellow(` ${s+1}. ${t}`))}))}(this.logger,e,"API Request")),e.tokenErrorInfo=t,e}throw e}}}function ys(t,s){const r=(t=(t=t.startsWith("/")?t:`/${t}`).endsWith("/")?t:`${t}/`).endsWith("/")?t.slice(0,-1):t,n=a.createLogger();return(i,o,c)=>{const l=new e.URL(i.url??"","http://localhost"),{pathname:d,search:u}=l,p=["/",r];if(s&&(p.push(`${a.PATH_TEMPLATE_PREFIX}/${s}`),p.push(`${a.PATH_TEMPLATE_LOCAL_PREFIX}/${s}`)),p.includes(d)){const e=`${t}${u}`;return n.info(a.colors.yellow(`Redirecting to: ${e}`)),J(o,e,302)}c()}}const ws=new WeakMap;let vs=0;function bs(e){let t=ws.get(e);return t||(t=new Map,ws.set(e,t)),t}function ks(e,t){const s=bs(e),r=s.get(t);return r?r.epoch!==vs||Date.now()-r.timestamp>18e4?(s.delete(t),null):r.data:null}function $s(e,t,s){bs(e).set(t,{timestamp:Date.now(),epoch:vs,data:s})}var Ss;Ss=()=>{vs+=1},Ht.add(Ss);let xs=!1;function As(e){xs||(xs=!0,e.info(a.colors.blue("Clearing proxy cache after successful login")),_t.clear())}function Ts(){xs=!1,a.authProvider.reset()}const Es="/home?proxyRedirect=",Is=`${Es}${encodeURIComponent("/")}`;function Ps(e){const t=e.headers??{},s=Boolean(lt(e.headers?.host));if(!s&&!ut.resolve(e)?.user)return t;const{cookie:r,authorization:n,token:i,...a}=t;return s||void 0===r?a:{...a,cookie:r}}function Ls(e,t,s){const{templateLess:r=!1,miHudLess:n=!1,appId:i,base:o,appBase:c}=s,l=a.createLogger();if(r&&n&&void 0===i)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");return async(s,d,u)=>{try{const p=!(r&&n),h=G(s.url??""),g=e.test(h),m=!g&&!h.startsWith("/home")&&function(e,t){if(!t)return!1;if("/"===t)return!0;const s=t.endsWith("/")?t:`${t}/`;return e===s||e===s.slice(0,-1)||e.startsWith(s)}(h,c)&&function(e){const t=e.headers["sec-fetch-dest"];if("string"==typeof t)return"document"===t;const s=e.headers.accept;return"string"==typeof s&&s.includes("text/html")}(s),f=a.authProvider.getState();if(!f.isAuthenticated&&!f.isRedirected&&s.url?.startsWith("/home")&&!s.url?.startsWith(Es)){let e;l.info(a.colors.blue("Trying to authenticate and redirect to base"));const c=t=>{e=t};try{if(p?await Ns(t,{templateLess:r,miHudLess:n,appId:i,redirectUrl:Is},s,d,c,l):await js(t,{templateLess:r,miHudLess:n,appId:i,redirectUrl:Is},s,d,c,l),d.headersSent||d.writableEnded)return;return e?u(e):(a.authProvider.setRedirected(!0),l.info(a.colors.blue("Successfully authenticated. Redirecting to base")),J(d,o??"/",302))}catch(e){if(d.headersSent||d.writableEnded)return;return u()}}if(!g&&!m)return u();if(!p){return await js(t,{templateLess:r,miHudLess:n,appId:i,redirectUrl:Is},s,d,u,l)}return await Ns(t,{templateLess:r,miHudLess:n,appId:i,redirectUrl:Is},s,d,u,l)}catch(e){return l.error(a.colors.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),Ts(),u(e)}}}async function js(e,t,s,r,n,i){const{appId:o,redirectOnAuthFailure:c,redirectUrl:l}=t;if(void 0===o){const e=new Error("Custom App ID is required for page info only mode");return i.error(a.colors.red(e.message)),n(e)}const d=Ps(s);i.info(a.colors.green("Start loading page info"));try{const t=`pageInfo:${o}`;return ks(e,t)?(i.info(a.colors.green("Page info loaded from cache")),n()):(await e.getPageInfo(o,d),As(i),$s(e,t,{success:!0}),a.authProvider.updateState({isAuthenticated:!0}),i.info(a.colors.green("Page info loaded successfully")),n())}catch(e){return Ts(),Rs(e,c??!0,l||Is,r,n,i,"Page info")}}async function Ns(e,t,s,r,n,i){const{templateLess:o,appId:c,redirectOnAuthFailure:l,redirectUrl:d}=t,u=Ps(s);i.info(a.colors.green("Start loading page data"));try{const t=`pageData:${o}:${c}`;if(ks(e,t))return i.info(a.colors.green("Page data loaded from cache")),n();const s=o||void 0===c?e.getPageTemplate(u):e.getPageVariables(c,u);return await s,As(i),$s(e,t,{success:!0}),i.info(a.colors.green("Page data loaded successfully")),n()}catch(e){return Ts(),Rs(e,l??!0,d||Is,r,n,i,"Page data")}}function Rs(e,t,s,r,n,i,o){if(function(e){return null!==e&&"object"==typeof e&&Ee(e)}(e)&&(i.info(a.colors.red(`${o} loading failed. Not authorized`)),t)){const e=`${s}`;return i.info(a.colors.yellow(`Redirecting to: ${e}`)),J(r,e,302)}const c=e instanceof Error?e.message:String(e);return i.info(a.colors.red(`${o} loading failed. Error: ${c}`)),n(e)}function Bs(e){return"string"==typeof e?e:void 0}function Cs(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}function Fs(e,t,s={}){return async(r,n,i)=>{if(await e(r.url??"",r,n)){const e=a.createLogger();"GET"!==r.method&&"HEAD"!==r.method||!(r.headers.accept??"").includes("text/html")||delete r.headers["if-none-match"];const o=n.end;if("HEAD"===r.method)return n.end=function(e,t,r){const i=[e,t,r].find(e=>"function"==typeof e),a=n.getHeader("content-type"),c=!s.contentType||s.contentType(void 0===a?"":String(a));return!n.headersSent&&c&&n.removeHeader("content-length"),o.call(this,i),this},void i();e.info(`Rewrite response for ${r.url}`);const c=[],l=n.write,d=n.writeHead,u=n.flushHeaders;let p=null,h=!1;const g=()=>{h=!0,p&&!n.headersSent&&d.apply(n,p),p=null;for(const e of c.splice(0))l.call(n,e)},m=(e=!1)=>{if(h)return!0;if(!s.contentType)return!1;const t=n.getHeader("content-type");return!(void 0===t&&!e)&&(!s.contentType(void 0===t?"":String(t))&&(g(),!0))};n.flushHeaders=function(){m()&&u.call(this)},n.writeHead=function(e,...t){if(h)return d.call(this,e,...t);const s="string"==typeof t[0]?t[0]:void 0;return function(e,t){if(Array.isArray(t)){const s=new Map;for(let e=0;e+1<t.length;e+=2){const r=String(t[e]),n=s.get(r.toLowerCase())??{name:r,values:[]};n.values.push(String(t[e+1])),s.set(r.toLowerCase(),n)}for(const{name:t,values:r}of s.values())e.setHeader(t,1===r.length?r[0]:r);return}if(t&&"object"==typeof t)for(const[s,r]of Object.entries(t))void 0!==r&&e.setHeader(s,r)}(this,void 0===s?t[0]:t[1]),this.statusCode=e,p=void 0===s?[e]:[e,s],m(),this},n.write=function(e,t,s){if(m())return l.call(this,e,t,s);const r=Cs(e,Bs(t));r&&c.push(r);const n="function"==typeof t?t:s;return"function"==typeof n&&process.nextTick(n),!0},n.end=function(s,i,a){if(m(!0))return o.call(this,s,i,a);"function"==typeof s&&(a=s,s=void 0);const l=Cs(s,Bs(i));l&&c.push(l);const u="function"==typeof i?i:a,h=n.getHeader("content-encoding"),g=fe(Buffer.concat(c),h),f=function(e,t){switch(t){case"gzip":return $.gzipSync(e);case"br":return $.brotliCompressSync(e);case"deflate":return $.deflateSync(e);default:return e}}(t(g,r,n),h);return void 0!==n.getHeader("content-length")&&(n.headersSent?e.warn(`Rewrite response for ${r.url}: headers already sent, Content-Length left as is`):n.setHeader("content-length",f.length)),n.headersSent||n.removeHeader("etag"),n.writeHead=d,p&&!n.headersSent&&d.apply(this,p),o.call(this,f,u),this}}i()}}const Ms="<redacted>",Os=new RegExp(`(^|;\\s*)(${ve}=)[^;]*`,"gi"),Ds=new RegExp(`^(\\s*${ve}=)[^;]*`,"i");function Us(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?Ms:`${e} ${Ms}`}return void 0!==t.token&&(t.token=Ms),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(Os,`$1$2${Ms}`)),t}function _s(e){const t={...e},s=t["set-cookie"],r=e=>e.replace(Ds,`$1${Ms}`);return Array.isArray(s)?t["set-cookie"]=s.map(r):"string"==typeof s&&(t["set-cookie"]=r(s)),t}const Hs=/^\/(?:login|auth)(?:[/?#]|$)/i,Vs=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function qs(e,t){return Array.isArray(e)?e.map(e=>qs(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>Vs.test(e)?(t.any=!0,[e,Ms]):[e,qs(s,t)])):e}function zs(e,t,s){if(!s)return s;if(Hs.test(e))return Buffer.from(Ms);const r=(t??"").split(";",1)[0].trim().toLowerCase();try{if("application/x-www-form-urlencoded"===r){const e=new URLSearchParams(s.toString("utf8")),t=[...new Set(e.keys())].filter(e=>Vs.test(e));return t.forEach(t=>e.set(t,Ms)),t.length?Buffer.from(e.toString()):s}if("application/json"===r||r.endsWith("+json")){const e={any:!1},t=qs(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const Ws=["/@","/_next/","/__nextjs_"],Js=new Set(["/favicon.ico","/installHook.js.map"]);const Gs="/@pp-dev/inspector",Ks=new WeakMap;function Xs(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function Zs(e,t,s=10485760,r=De){const n=Ks.get(e);if(n)return n.store=t,void(n.captureLimit=s);const i={store:t,captureLimit:s};Ks.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,r=Xs(e.query.limit),n=Xs(e.query.offset),a=Xs(e.query.method),o=Xs(e.query.search),c=void 0!==r?parseInt(r,10):void 0,l=s.list({limit:Number.isFinite(c)?c:500,offset:void 0!==n&&Number.isFinite(parseInt(n,10))?parseInt(n,10):void 0,method:a,search:o});t.json({requests:l,total:s.size,memoryUsage:s.memoryUsage,maxMemory:s.maxMemory})}),e.get("/@api/requests/stats",(e,t)=>{const{store:s}=i;t.json({total:s.size,memoryUsage:s.memoryUsage,maxMemory:s.maxMemory,memoryUsageFormatted:Qs(s.memoryUsage),maxMemoryFormatted:Qs(s.maxMemory)})}),e.get("/@api/requests/:id",(e,t)=>{const s=i.store.get(e.params.id);if(!s)return void t.status(404).json({error:"Not found",id:e.params.id});const r=Ys(s.requestHeaders["content-type"]),n=Ys(s.responseHeaders["content-type"]),a=s.responseBody?function(e,t,s){const r=Array.isArray(t)?t.join(", "):String(t??"");try{return fe(e,r.trim().toLowerCase(),{maxOutputLength:s})}catch(t){return t instanceof RangeError?null:e}}(s.responseBody,s.responseHeaders["content-encoding"],i.captureLimit):null;t.json({id:s.id,timestamp:s.timestamp,method:s.method,url:s.url,statusCode:s.statusCode,duration:s.duration,source:s.source,user:s.user,requestHeaders:s.requestHeaders,requestBody:s.requestBody?s.requestBody.toString("base64"):null,requestBodySize:s.requestBody?.byteLength??0,requestBodyTruncated:s.requestBodyTruncated,requestContentType:r,responseHeaders:s.responseHeaders,responseBody:a?a.toString("base64"):null,responseBodySize:s.responseBody?.byteLength??0,responseBodyTruncated:s.responseBodyTruncated||null!==s.responseBody&&null===a,responseContentType:n})}),e.delete("/@api/requests",(e,t)=>{i.store.clear(),t.json({ok:!0})}),_e(e,{path:Gs,name:"request-inspector",clientDir:r,values:()=>({captureLimit:String(i.captureLimit)})})}function Ys(e){return Array.isArray(e)?e[0]??"":String(e??"")}function Qs(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/1073741824).toFixed(2)} GB`}function er(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function tr(e){return{id:e.id,timestamp:e.timestamp,method:e.method,url:e.url,statusCode:e.statusCode,duration:e.duration,source:e.source,user:e.user,requestSize:e.requestBody?.byteLength??0,responseSize:e.responseBody?.byteLength??0,requestBodyTruncated:e.requestBodyTruncated,responseBodyTruncated:e.responseBodyTruncated,aborted:e.aborted}}class sr{entries=new Map;insertOrder=[];head=0;totalSize=0;maxMemory;maxEntries;constructor(e=1073741824,t=1e4){this.maxMemory=e,this.maxEntries=t}evictOldest(){const e=this.insertOrder[this.head++],t=this.entries.get(e);t&&(this.totalSize-=er(t),this.entries.delete(e)),this.head>=1024&&2*this.head>=this.insertOrder.length&&(this.insertOrder=this.insertOrder.slice(this.head),this.head=0)}allocateId(){return u.randomUUID()}add(e){let t=e,s=(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0);s>this.maxMemory&&(t={...e,requestBody:null,responseBody:null,requestBodyTruncated:e.requestBodyTruncated||null!==e.requestBody,responseBodyTruncated:e.responseBodyTruncated||null!==e.responseBody},s=0);const r=er(t);for(;(this.totalSize+r>this.maxMemory||this.entries.size>=this.maxEntries)&&this.head<this.insertOrder.length;)this.evictOldest();this.entries.set(t.id,t),this.insertOrder.push(t.id),this.totalSize+=r}get(e){return this.entries.get(e)}list(e){const t=e?.method?.toUpperCase(),s=e?.search?.toLowerCase(),r=e=>(!t||e.method===t)&&(!s||e.url.toLowerCase().includes(s)),n=Number.isFinite(e?.limit)?e.limit:1/0,i=[];if(n<=0)return i;if(void 0===e?.offset){for(let e=this.insertOrder.length-1;e>=this.head&&i.length<n;e-=1){const t=this.entries.get(this.insertOrder[e]);t&&r(t)&&i.push(tr(t))}return i.reverse()}let a=Number.isFinite(e.offset)?Math.max(0,e.offset):0;for(let e=this.head;e<this.insertOrder.length&&i.length<n;e+=1){const t=this.entries.get(this.insertOrder[e]);t&&r(t)&&(a>0?a-=1:i.push(tr(t)))}return i}clear(){this.entries.clear(),this.insertOrder=[],this.head=0,this.totalSize=0}get size(){return this.entries.size}get memoryUsage(){return this.totalSize}}function rr(e){const{templateName:t,internalServer:s,backendBaseURL:r,inspector:n,proxy:i}=e,o=e.base.endsWith("/")?e.base:`${e.base}/`,c=[],l=[];if(r){const e=pt();c.push(e),l.push(e)}if(n.enabled){const e=new sr(n.maxMemory);Zs(s,e,n.captureLimit),c.push(function(e,t=10485760,s=ut){return(r,n,i)=>{const a=r.url||"/",o=a.split("?")[0];if(Ws.some(e=>a.startsWith(e))||Js.has(o))return void i();const c=e.allocateId(),l=s.resolve(r)?.user?.name,d=Date.now(),u=[];let p=0,h=!1;const g=r.emit.bind(r);r.emit=(e,...s)=>{if("data"===e&&!h){const e=s[0],r=Buffer.isBuffer(e)?e:Buffer.from(String(e));p+=r.byteLength,p<=t?u.push(r):(h=!0,u.length=0)}return g(e,...s)};const m=[];let f=0,y=!1;const w=n.write.bind(n),v=n.end.bind(n);function b(e,s){if(!y&&null!=e)try{const r=Buffer.isBuffer(e)?e:"string"==typeof e?Buffer.from(e,s):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?Buffer.from(e):Buffer.from(String(e));f+=r.byteLength,f<=t?m.push(r):(y=!0,m.length=0)}catch{}}function k(e){return"string"==typeof e[0]?e[0]:void 0}function $(){const e=n.getHeaders();return e["x-pp-proxy"]?"hit"===e["x-pp-cache"]?"proxy-cache":"proxy":"local"}let S=!1;function x(t=!1){if(S)return;S=!0;const s=zs(a,"string"==typeof r.headers["content-type"]?r.headers["content-type"]:void 0,!h&&u.length>0?Buffer.concat(u):null),i=!y&&m.length>0?Buffer.concat(m):null;e.add({id:c,timestamp:d,method:r.method||"GET",url:a,statusCode:n.statusCode??null,duration:Date.now()-d,source:$(),user:l,requestHeaders:Us(r.headers),requestBody:s,requestBodyTruncated:h,responseHeaders:_s(n.getHeaders()),responseBody:i,responseBodyTruncated:y,...t?{aborted:t}:{}})}n.once("close",()=>x(!0)),n.write=(e,...t)=>(b(e,k(t)),w(e,...t)),n.end=(e,...t)=>("function"!=typeof e&&b(e,k(t)),x(),v(e,...t)),i()}}(e,n.captureLimit))}const d=ys(o,t);if(c.push(d),l.push(d),e.devPanelAssets){const e=a.createDevPanelAssetMiddleware(o);c.push(e),l.push(e)}if(n.enabled||r){const e=(e,t,r)=>{const n=e.url??"";n.startsWith("/@api/")||n.startsWith(Gs)||n.startsWith(Ye)?s(e,t,e=>os(t,e)):r()};c.push(e),l.push(e)}let u=null,p=null,h=null;if(r){"/"===o&&a.createLogger().warn(a.colors.yellow("⚠️ The app's base is '/': MI's paths can't be told from the app's files, so nothing is proxied to MI. Give the app a base path (withPPDev() does, from app.name)."));const s=function(e,t){return{headers:{host:new URL(e).host,referer:e,origin:e.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i,"$1$2")},appId:t.appId,templateLess:t.templateLess,disableSSLValidation:t.disableSSLValidation,v7Features:t.v7Features,personalAccessToken:t.personalAccessToken??process.env.MI_ACCESS_TOKEN}}(r,e.mi);u=new fs(r,s),i.cache&&(p=function(e){const t=Number(e);return!t||Number.isNaN(t)||t<0?6e5:t}(i.cacheTtl),c.push(Xt({devServer:i.devServer,ttl:p}))),c.push(Ls(function(e){return new RegExp(`^((${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`);var t}(o),u,{...e.mi,base:o,appBase:o})),c.push(Ct({baseURL:r,proxyIgnore:[...is(o),...i.ignore??[]],disableSSLValidation:e.mi.disableSSLValidation,miAPI:u,templateName:t}));const n=e.rewrite(u,new URL(r).host);h=Fs((e,t)=>n.predicate(e,t),(e,t)=>n.transform(e,t),n.contentType?{contentType:n.contentType}:{})}return{main:c,essential:l,rewrite:h,mi:u,proxyCacheTtl:p}}function nr(e){const{templateName:t,templateLess:s,backendBaseURL:r,miHudLess:n,appId:i,enableProxyCache:o,proxyCacheTTL:c,disableSSLValidation:l,outDir:d,distZip:u,versionPlugin:p,syncBackupsDir:h,syncMaxBackups:g,syncBuildTimeoutMs:m,v7Features:f,personalAccessToken:y,inspectorEnabled:w,inspectorMaxMemory:v,inspectorCaptureLimit:b,devPanelPosition:k,devPanelHidden:$,devPanelAutoHide:S,persistUsers:x,allowedHosts:A}=e||{};let T=!0;const E=new WeakMap;return{name:"vite-pp-dev",apply:"serve",closeBundle(){E.get(this.environment)?.dispose(),E.delete(this.environment)},config:e=>(e.clientInjectionPlugin={backendBaseURL:r,appId:i,templateLess:s,v7Features:f,devPanelPosition:k,devPanelHidden:$,devPanelAutoHide:S},f&&(e.base=`/pl/${t}`),e),transformIndexHtml:async(e,t)=>{const s={html:e,tags:[]};return T&&(T=!1,s.tags.push({tag:"script",injectTo:"body",children:`${Math.random()}`})),s},configureServer:e=>{let k=e.config.base;k.endsWith("/")||(k+="/");const $=function({allowedHosts:e=[]}={}){const t=F();return t.use(a.createOriginGuard(e)),t.use(F.json({limit:ge})),t.use(F.urlencoded({extended:!0})),t.use(me),t}({allowedHosts:A}),S=rr({base:k,templateName:t,internalServer:$,backendBaseURL:r,mi:{appId:i,templateLess:s,miHudLess:n,disableSSLValidation:l,v7Features:f,personalAccessToken:y},inspector:{enabled:!1!==w,maxMemory:v,captureLimit:b},proxy:{cache:o,cacheTtl:c,devServer:e},rewrite:(e,t)=>({predicate:e=>e.split("?")[0].endsWith("index.html"),transform:(s,r)=>Buffer.from(z(t,r.headers.host??"",e.buildPage(s,n)))})});if(function(e,t){for(const s of t.main)e.middlewares.use(s)}(e,S),r&&S.mi){const s=S.mi;e.config.logger.info(a.colors.blue(`🌐 Backend URL: ${r}`)),e.config.logger.info(a.colors.blue(`🆔 Custom App ID: ${i}`));const n=new he(t,Object.assign({root:e.config.root,backupFolder:h,maxBackups:g,buildTimeoutMs:m,buildInputFolder:"object"==typeof u?u.inDir??d:d},"object"==typeof p?{versionFileTemplate:p.versionFileTemplate}:void 0)),o=as({server:e,internalServer:$,distService:n,miAPI:s,persistUsers:x,projectRoot:e.config.root||process.cwd(),miUrl:r});E.set(e.environments.client,o)}const{rewrite:T}=S;if(T)return()=>{e.middlewares.use(T)}}}}exports.normalizePPDevConfig=a.normalizePPDevConfig,exports.validatePPDevConfig=a.validatePPDevConfig,exports.default=nr,exports.vitePPDev=nr;
2
2
  //# sourceMappingURL=plugin.js.map