@metricinsights/pp-dev 1.5.0-beta.32 → 1.5.0-beta.34

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 (56) hide show
  1. package/TEMPLATE_VARIABLES.md +25 -25
  2. package/dist/cjs/auth.provider-6rZUaR33.js +2 -0
  3. package/dist/cjs/auth.provider-6rZUaR33.js.map +1 -0
  4. package/dist/cjs/cli.js +1 -1
  5. package/dist/cjs/cli.js.map +1 -1
  6. package/dist/cjs/index-Cc-bAhnE.js +2 -0
  7. package/dist/cjs/index-Cc-bAhnE.js.map +1 -0
  8. package/dist/cjs/index.js +1 -1
  9. package/dist/cjs/internal.middleware-BlM7gqkq.js +2 -0
  10. package/dist/cjs/internal.middleware-BlM7gqkq.js.map +1 -0
  11. package/dist/cjs/migrate-DDdeB-Fj.js +2 -0
  12. package/dist/cjs/{migrate-Gi9k9cLw.js.map → migrate-DDdeB-Fj.js.map} +1 -1
  13. package/dist/cjs/plugin.js +1 -1
  14. package/dist/cjs/plugin.js.map +1 -1
  15. package/dist/cjs/{version-manifest-CVBuIKBS.js → version-manifest-DdWlzzZ6.js} +2 -2
  16. package/dist/cjs/{version-manifest-CVBuIKBS.js.map → version-manifest-DdWlzzZ6.js.map} +1 -1
  17. package/dist/cjs/version-plugin-B1Sb07cW.js +2 -0
  18. package/dist/cjs/{version-plugin-DBdqn2Rn.js.map → version-plugin-B1Sb07cW.js.map} +1 -1
  19. package/dist/client/index.html +1 -3
  20. package/dist/client/request-inspector.html +90 -79
  21. package/dist/client/variables-editor.html +47 -40
  22. package/dist/esm/auth.provider-BFK6x9Df.js +2 -0
  23. package/dist/esm/auth.provider-BFK6x9Df.js.map +1 -0
  24. package/dist/esm/cli.js +1 -1
  25. package/dist/esm/cli.js.map +1 -1
  26. package/dist/esm/index-PvH-M_Io.js +2 -0
  27. package/dist/esm/index-PvH-M_Io.js.map +1 -0
  28. package/dist/esm/index.js +1 -1
  29. package/dist/esm/internal.middleware-CC20He9L.js +2 -0
  30. package/dist/esm/internal.middleware-CC20He9L.js.map +1 -0
  31. package/dist/esm/migrate-C1MkJPzS.js +2 -0
  32. package/dist/esm/{migrate-CCBRuVfj.js.map → migrate-C1MkJPzS.js.map} +1 -1
  33. package/dist/esm/plugin.js +1 -1
  34. package/dist/esm/plugin.js.map +1 -1
  35. package/dist/esm/version-manifest-BVgENnKn.js +2 -0
  36. package/dist/esm/{version-manifest-CyzmnFOe.js.map → version-manifest-BVgENnKn.js.map} +1 -1
  37. package/dist/esm/version-plugin-CA9HNV-6.js +2 -0
  38. package/dist/esm/{version-plugin-6rxIgQ-I.js.map → version-plugin-CA9HNV-6.js.map} +1 -1
  39. package/package.json +1 -1
  40. package/dist/cjs/auth.provider-fI0tFsf5.js +0 -2
  41. package/dist/cjs/auth.provider-fI0tFsf5.js.map +0 -1
  42. package/dist/cjs/index-CZ7sZQJX.js +0 -2
  43. package/dist/cjs/index-CZ7sZQJX.js.map +0 -1
  44. package/dist/cjs/migrate-Gi9k9cLw.js +0 -2
  45. package/dist/cjs/request-capture.middleware-C9SbJkfk.js +0 -2
  46. package/dist/cjs/request-capture.middleware-C9SbJkfk.js.map +0 -1
  47. package/dist/cjs/version-plugin-DBdqn2Rn.js +0 -2
  48. package/dist/esm/auth.provider-DDUsu1H1.js +0 -2
  49. package/dist/esm/auth.provider-DDUsu1H1.js.map +0 -1
  50. package/dist/esm/index-GSdCxN3K.js +0 -2
  51. package/dist/esm/index-GSdCxN3K.js.map +0 -1
  52. package/dist/esm/migrate-CCBRuVfj.js +0 -2
  53. package/dist/esm/request-capture.middleware-B2BGaP0g.js +0 -2
  54. package/dist/esm/request-capture.middleware-B2BGaP0g.js.map +0 -1
  55. package/dist/esm/version-manifest-CyzmnFOe.js +0 -2
  56. package/dist/esm/version-plugin-6rxIgQ-I.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth.provider-fI0tFsf5.js","sources":["../../../src/constants.ts","../../../src/lib/logger.ts","../../../src/lib/helpers/color.helper.ts","../../../src/lib/output-path.ts","../../../src/lib/pp-dev-config.ts","../../../src/lib/helpers/origin-guard.ts","../../../src/lib/auth.provider.ts"],"sourcesContent":[null,null,null,null,null,null,null],"names":["afterBundlePath","resolve","__filename","fileURLToPath","document","require","pathToFileURL","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","beforeBundlePath","PP_DEV_PACKAGE_DIR","existsSync","PP_DEV_CLIENT_ENTRY","version","name","JSON","parse","readFileSync","toString","VERSION","PACKAGE_NAME","DEFAULT_LEVEL","current","shared","active","level","logger","createViteLogger","createLogger","undefined","info","msg","options","warn","warnOnce","error","clearScreen","type","hasErrorLogged","hasWarned","value","colors","createColors","normalizeRelativeOutputPath","relativePath","optionName","includes","path","posix","isAbsolute","win32","root","Error","normalized","normalize","replace","startsWith","createDefaultZipFileName","appName","DEV_PANEL_POSITIONS","MAX_TIMER_DELAY_MS","validatePPDevConfig","config","templateName","miMode","mi","mode","appType","app","apiVersion","miUrl","url","process","env","MI_BACKEND_URL","maxBackups","sync","Number","isInteger","stringify","buildTimeoutMs","include","console","id","devPanel","position","join","allowedHosts","server","Array","isArray","every","host","trim","normalizePPDevConfig","proxy","build","inspector","users","miHudLess","integrateMiTopBar","addSharedComponentsScripts","addRootElement","templateLess","resolvedName","defaultVersionFileTemplate","distZip","zipCfg","zip","versionPlugin","outFileName","outDir","fileName","inDir","vfCfg","versionFile","imageOptimizer","versionFileTemplate","enabled","fileNameTemplate","imgCfg","imageOptimisations","backendBaseURL","appId","enableProxyCache","cache","proxyCacheTTL","cacheTtl","disableSSLValidation","tls","allowSelfSigned","syncBackupsDir","backupsDir","syncMaxBackups","syncBuildTimeoutMs","v7Features","personalAccessToken","token","MI_ACCESS_TOKEN","inspectorEnabled","inspectorMaxMemory","maxMemory","inspectorCaptureLimit","captureLimit","devPanelPosition","devPanelHidden","hidden","devPanelAutoHide","autoHide","persistUsers","persist","map","toLowerCase","SAFE_METHODS","Set","exactAllowedHosts","filter","crossOriginReason","req","origin","headers","originUrl","hostname","endsWith","test","requestHost","scheme","normalizeHost","protocol","fetchSite","has","method","AuthProvider","state","isAuthenticated","isRedirected","listeners","getState","this","setAuthenticated","authenticated","notifyListeners","setRedirected","redirected","updateState","updates","reset","subscribe","listener","add","delete","forEach","stack","message","String","authProvider","res","next","reason","status","json","named","trimmed","end","indexOf","isIP","slice","ip","readHostHeader","some","allowed","matchesAllowedHost","directory","safeRelativePath","resolvedDirectory","resolvedFile","split","relativeToDirectory","relative","sep","projectRoot"],"mappings":"6RAIMA,EAAkBC,EAAAA,QAEC,oBAAfC,YAA8BA,YAAeC,EAAAA,cAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,4BAAAR,SAAAS,SAAAN,MACnE,YAGIO,EAAmBb,EAAAA,QAEA,oBAAfC,YAA8BA,YAAeC,EAAAA,cAAc,oBAAAC,SAAAC,QAAA,OAAAC,cAAAJ,YAAAK,KAAAC,GAAA,WAAAA,EAAAC,QAAAC,eAAAF,EAAAG,KAAA,IAAAC,IAAA,4BAAAR,SAAAS,SAAAN,MACnE,SAGWQ,EAAqBC,EAAAA,WAAWf,UAAQD,EAAiB,iBAClEA,EACAc,EAESG,EAAsBhB,EAAAA,QAAQc,EAAoB,0BAEzDG,QAAEA,EAAOC,KAAEA,GAASC,KAAKC,MAAMC,EAAAA,aAAarB,EAAAA,QAAQc,EAAoB,iBAAiBQ,YAElFC,EAAUN,EACVO,EAAeN,ECvBtBO,EAA0B,OAEhC,IAAIC,EACAC,EAEJ,SAASC,IAGP,OAFAF,IAAY,CAAEG,MAAOJ,EAAeK,OAAQC,EAAAA,aAAiBN,IAEtDC,EAAQI,MACjB,CAUM,SAAUE,EAAaH,GAoB3B,YAnBcI,IAAVJ,GAAuBA,IAAUH,GAASG,QAC5CH,EAAU,CAAEG,QAAOC,OAAQC,EAAAA,aA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J,WAAW,OAAS0J,EAAQJ,MAAM,KAAO5C,GAAYA,EAASC,SAAS+C,IAEtF,CA2BwEC,CAAmBjD,EAAU3E,EACrG,oIFxBsC6H,EAAmBpG,EAAkBnE,GACzE,MAAMwK,EAAmB1K,EAA4BqE,EAAUnE,GACzDyK,EAAoBvK,EAAKnD,QAAQwN,GACjCG,EAAexK,EAAKnD,QAAQ0N,KAAsBD,EAAiBG,MAAM,MACzEC,EAAsB1K,EAAK2K,SAASJ,EAAmBC,GAE7D,GAC0B,OAAxBE,GACAA,EAAoBjK,WAAW,KAAKT,EAAK4K,QACzC5K,EAAKE,WAAWwK,GAEhB,MAAM,IAAIrK,MAAM,YAAYP,+CAG9B,OAAO0K,CACT,uCAnBoCK,EAAqB7G,EAAgBE,GACvE,OAAOlE,EAAKnD,QAAQgO,EAAa3G,GAASF,EAC5C"}
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("child_process"),t=require("./auth.provider-fI0tFsf5.js"),n=require("node:module"),i=require("vite"),r=require("fs"),s=require("path"),o=require("url");require("./helpers.js");const a=require("ejs");var c="undefined"!=typeof document?document.currentScript:null;const l=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function p(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=p(r),d=p(s),f=l(s),m=l(a),v=d.dirname(t.PP_DEV_CLIENT_ENTRY),P=d.join(v,"index.html");let _=null;function g(e){return{css:d.posix.join(e,t.PACKAGE_NAME,"client/client.css"),js:d.posix.join(e,t.PACKAGE_NAME,"client/client.js")}}function E(e){return function(){if(_)return _;const e=u.readFileSync(P,{encoding:"utf8"});return _=m.compile(e,{openDelimiter:"{",closeDelimiter:"}",async:!1,rmWhitespace:!0,compileDebug:!1}),_}()({PACKAGE_NAME:t.PACKAGE_NAME,VERSION:t.VERSION,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})}const h={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};const y=i.normalizePath(d.join(t.PP_DEV_PACKAGE_DIR,"dist/client")),T=new RegExp(`^\\/?${t.PACKAGE_NAME}\\/client\\/(.*)$`);const j=(e,t)=>` * ${t}`;function D(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,j)}\n */`}async function I(){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 b=()=>n.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:c&&"SCRIPT"===c.tagName.toUpperCase()&&c.src||new URL("index-CZ7sZQJX.js",document.baseURI).href);let R=new Set;function A(e="development",t=process.cwd()){for(const e of R)delete process.env[e];const n=new Set(Object.keys(process.env).filter(e=>e.startsWith("MI_"))),r=i.loadEnv(e,t,"MI_");for(const[e,t]of Object.entries(r))process.env[e]=t;return R=new Set(Object.keys(r).filter(e=>!n.has(e))),r}const w=Object.freeze({__proto__:null,loadPPDevEnv:A}),$=Symbol.for("@metricinsights/pp-dev:withPPDev");const N=new Map,O=new Map;function x(e=process.cwd()){const t=Date.now(),n=f.resolve(e),i=O.get(n);if(i&&t-i.timestamp<6e4)return i.data;try{const e=JSON.parse(r.readFileSync(f.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return O.set(n,{data:e,timestamp:t}),e}catch{const e={};return O.set(n,{data:e,timestamp:t}),e}}let S=null;const F="__pp_dev_injected_dirname",C="__pp_dev_injected_filename",L="__pp_dev_injected_import_meta_url",M={__dirname:F,__filename:C,"import.meta.url":L,"import.meta.dirname":F,"import.meta.filename":C},V={name:"pp-dev:config-module-location",setup(e){e.onLoad({filter:/\.([cm]?[jt]s|[jt]sx)$/},e=>{const t=r.readFileSync(e.path,"utf-8").replace(/^#![^\r\n]*/,"");return{contents:`const ${F} = ${JSON.stringify(f.dirname(e.path))};const ${C} = ${JSON.stringify(e.path)};const ${L} = ${JSON.stringify(o.pathToFileURL(e.path).href)};`+t,loader:e.path.endsWith(".tsx")?"tsx":e.path.endsWith(".jsx")?"jsx":/ts$/.test(e.path)?"ts":"js"}})}};async function H(e,t){const n=`bundled:${e}`,i=N.get(n);if(i&&Date.now()-i.timestamp<3e4)return i.data;let s=!1;if(/\.m[jt]s$/.test(e))s=!0;else if(/\.c[jt]s$/.test(e))s=!1;else{const e=x(t);s=!!e&&"module"===e.type}const a=await async function(){return S||(S=await(import("esbuild"))),S}(),c=await a.build({absWorkingDir:t,entryPoints:[e],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:s?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0,plugins:[V],define:M,...s?{banner:{js:"import { createRequire as __ppDevCreateRequire } from 'node:module';const require = __ppDevCreateRequire(import.meta.url);"}}:{}}),{text:l}=c.outputFiles[0],p=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.${s?"mjs":"cjs"}`,u=f.resolve(t,p),d=o.pathToFileURL(u).toString();r.writeFileSync(u,l);let m={};try{const t=(await(import(d))).default;m=t?.default||t,N.set(n,{data:m,timestamp:Date.now(),filePath:e})}finally{try{r.unlinkSync(u)}catch{}}return m}async function U(e){const t=`json:${e}`,n=N.get(t);if(n&&Date.now()-n.timestamp<3e4)return n.data;const i=JSON.parse(r.readFileSync(e,{encoding:"utf-8"}));return N.set(t,{data:i,timestamp:Date.now(),filePath:e}),i}const Z=new Map;function q(e=process.cwd()){return x(e)}async function z(e=process.cwd()){const n=f.resolve(e),i=function(e){const t=Date.now(),n=Z.get(e);if(n&&t-n.timestamp<1e4)return n.files;const i=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,s=r.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isFile()&&i.test(e.name)).map(e=>e.name);return Z.set(e,{files:s,timestamp:t}),s}(n);let s={},o=!1;const a=await async function(e,t,n){for(const i of t)if(e.includes(i)){const e=f.resolve(n,i);if(/\.[cm]?[jt]s$/i.test(i))return await H(e,n);if(i.endsWith(".json"))return await U(e)}return null}(i,t.PP_DEV_CONFIG_NAMES,n);a&&(s=a,o=!0);const c=x(n)["pp-dev"];return o||!c||"object"!=typeof c||Array.isArray(c)||(s=c),s}const G=Object.freeze({__proto__:null,clearConfigCache:function(){N.clear(),O.clear(),Z.clear()},getConfig:z,getPkg:q});function k(e){if(void 0!==e)return"1"===e||"true"===e.toLowerCase()||"0"!==e&&"false"!==e.toLowerCase()&&void 0}function B(e,n,i){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 r=!1===e?{outFileName:i,outDir:"dist-zip"}:e,s=n.distZipFilename??r.outFileName;return{...r,...void 0!==n.distZipDir?{outDir:n.distZipDir}:{},outFileName:t.normalizeRelativeOutputPath(s,"ZIP output file name")}}function K(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 i=!1===e?{enabled:!0}:e,r=n.versionFileTemplate??i.versionFileTemplate,s=void 0!==r?t.normalizeRelativeOutputPath(r,"VERSION file name template"):void 0;return{...i,enabled:!0,...void 0!==s?{versionFileTemplate:s}:{}}}const W=new Set(["mi","app","proxy","build","sync","inspector","devPanel","users","server"]);function X(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 i=process.env.GITHUB_REPOSITORY;if("string"==typeof i&&i.trim()){return`${(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${i.replace(/^\/+/,"")}`}const r=process.env.CI_PROJECT_PATH;if("string"==typeof r&&r.trim()){return`${(process.env.CI_SERVER_URL||"https://gitlab.com").replace(/\/+$/,"")}/${r.replace(/^\/+/,"")}`}const s=process.env.BITBUCKET_REPO_FULL_NAME;if("string"==typeof s&&s.trim())return`https://bitbucket.org/${s.replace(/^\/+/,"")}`;const o=process.env.TRAVIS_REPO_SLUG;if("string"==typeof o&&o.trim())return`https://github.com/${o.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 J(e){return e?.ppDev||{}}exports.applyDistZipOverride=B,exports.applyVersionManifestOverride=K,exports.clearWithPPDevHandoff=function(){delete globalThis[$]},exports.config=G,exports.createDevPanelAssetMiddleware=function(e){const n=d.posix.join(e,t.PACKAGE_NAME,"client")+"/",i=new Set(["client.js","client.css","client.js.map","client.css.map"]);return(e,t,r)=>{const s=(e.url??"").split("?")[0];if(!s.startsWith(n))return void r();const o=s.slice(n.length);if(!i.has(o))return void r();const a=d.join(v,o);u.readFile(a,(e,n)=>{e?r():(t.statusCode=200,t.setHeader("Content-Type",h[d.extname(o)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(n))})}},exports.env=w,exports.getNextVersion=async function(){try{const e=b()("next/package.json");return"string"==typeof e.version?e.version:null}catch{return null}},exports.getPPDevConfigFromNextConfig=J,exports.getViteConfig=async function(e,n={}){const r=n.root??process.cwd();A(n.mode,r);const s=q(r),o=await z(r);t.validatePPDevConfig(o,s.name);const a=t.normalizePPDevConfig(o,s.name),{templateName:c}=a;e&&(a.distZip=B(a.distZip,e,t.createDefaultZipFileName(c)),a.versionPlugin=K(a.versionPlugin,e));const{default:l}=await Promise.resolve().then(()=>require("./plugin.js")),p=[l(a),{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${t.PACKAGE_NAME}/client`),e),resolveId(e){const t=e.match(T);if(t){const e=i.normalizePath(d.join(y,t[1]));return e.startsWith(`${y}/`)?{id:e}:null}},transformIndexHtml:async(e,t)=>{const n=g(t.server?.config.base||""),i={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:n.css}}]},{templateLess:r=!1,...s}=t.server?.config.clientInjectionPlugin||{};return i.tags.push({tag:"div",injectTo:"body-prepend",children:E({templateLess:r,...s})}),i.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:n.js,type:"module"}}),i},configureServer(e){const n=i.normalizePath(d.resolve(e.config.root,d.dirname(t.PP_DEV_CLIENT_ENTRY)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(n)}}],{outDir:u,distZip:f,versionPlugin:m,imageOptimizer:v,templateLess:P,integrateMiTopBar:_,allowedHosts:h}=a;if(_&&p.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}}}(_)),v){const{ViteImageOptimizer:e}=await(import("vite-plugin-image-optimizer"));p.push(e("object"==typeof v?v:void 0))}if(m){const{versionPlugin:e}=await Promise.resolve().then(()=>require("./version-plugin-DBdqn2Rn.js"));p.push(e({outDir:u,packageVersion:s.version??"0.0.0",packageRepositoryUrl:X(s.repository),..."object"==typeof m?m:{}}))}if(f){const{default:e}=await(import("vite-plugin-zip-pack"));p.push({...e("object"==typeof f?f:{outFileName:t.createDefaultZipFileName(c)}),enforce:"post"})}return{base:P?`${t.PATH_PAGE_PREFIX}/${c}`:`${t.PATH_TEMPLATE_PREFIX}/${c}`,server:{port:3e3,...!0===h||h.length>0?{allowedHosts:h}:{}},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:D}},outDir:u},css:{modules:{localsConvention:"dashes"}},ppDevConfig:a,plugins:p}},exports.injectDevPanel=function(e,t,n){if(!/<\/?(html|body|head)\b/i.test(e))return e;const{css:i,js:r}=g(t),s=E(n),o=`<link rel="stylesheet" href="${i}">`,a=`${s}${`<script type="module" src="${r}"><\/script>`}`;let c=e,l=!1;if(/<\/head>/i.test(c)&&(c=c.replace(/<\/head>/i,e=>`${o}${e}`),l=!0),/<body[^>]*>/i.test(c)){const e=l?"":o;c=c.replace(/<body[^>]*>/i,t=>`${t}${e}${a}`)}else c=`${l?"":o}${c}${a}`;return c},exports.isNextAvailable=async function(){try{return b().resolve("next"),!0}catch{return!1}},exports.loadPPDevEnv=A,exports.readWithPPDevHandoff=function(){return globalThis[$]},exports.resolveBuildCliOverrides=function(e){return{distZipEnabled:e.distZip??k(process.env.PP_DEV_DIST_ZIP),distZipDir:e.distZipDir??process.env.PP_DEV_DIST_ZIP_DIR,distZipFilename:e.distZipFilename??process.env.PP_DEV_DIST_ZIP_FILENAME,versionManifestEnabled:e.versionManifest??k(process.env.PP_DEV_VERSION_MANIFEST),versionFileTemplate:e.versionFileTemplate??process.env.PP_DEV_VERSION_FILE_TEMPLATE}},exports.safeNextImport=I,exports.withPPDev=function(e,n){return async(i,r={})=>{try{const{constants:o}=await I(),{PHASE_DEVELOPMENT_SERVER:a,PHASE_PRODUCTION_BUILD:c}=o;i!==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 l=await z(),p=q().name,u="function"==typeof e?await e(i,r):e,d=function(...e){const t={},n=t;for(const t of e)if(t)for(const[e,i]of Object.entries(t))void 0!==i&&(W.has(e)&&i&&"object"==typeof i&&!Array.isArray(i)?n[e]={...n[e]??{},...i}:n[e]=i);return t}(l,J(u),n);t.validatePPDevConfig(d,p);const f=t.normalizePPDevConfig(d,p),{templateLess:m,v7Features:v}=f,P=i===a,_=function(e,n,i,r){return i?r?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}`}(f.templateName,m,P,v),g={basePath:_,trailingSlash:!!P||void 0};if(!m){const e=P&&v?t.PATH_TEMPLATE_LOCAL_PREFIX:t.PATH_TEMPLATE_PREFIX;g.assetPrefix=`${e}/${f.templateName}`}const E=Object.assign({},g,u),h=t.exactAllowedHosts(f.allowedHosts);P&&h.length>0&&(E.allowedDevOrigins=[...E.allowedDevOrigins??[],...h]);const y=process.env[t.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR];return i===c&&y&&(E.distDir=y),Object.defineProperty(E,"ppDev",{value:d,enumerable:!1,configurable:!0}),Object.defineProperty(E,"ppDevWrapped",{value:!0,enumerable:!1,configurable:!0}),s={ppDev:d,wrapped:!0},globalThis[$]=s,E}catch(e){throw t.createLogger().error("Error in withPPDev:",{error:e instanceof Error?e:new Error(String(e))}),e}var s}};
2
- //# sourceMappingURL=index-CZ7sZQJX.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-CZ7sZQJX.js","sources":["../../../src/lib/dev-panel.ts","../../../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/lib/build-cli-overrides.ts","../../../src/index.ts","../../../src/plugins/mi-topbar-plugin.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null],"names":["CLIENT_DIST_DIR","path","dirname","PP_DEV_CLIENT_ENTRY","TEMPLATE_PATH","join","compiledTemplate","getDevPanelAssetPaths","base","css","posix","PACKAGE_NAME","js","renderDevPanelMarkup","data","templateContent","fs","readFileSync","encoding","ejs","compile","openDelimiter","closeDelimiter","async","rmWhitespace","compileDebug","getTemplate","template","VERSION","backendBaseURL","templateLess","appId","canSync","devPanelPosition","devPanelHidden","devPanelAutoHide","CONTENT_TYPES","normalizePath","PP_DEV_PACKAGE_DIR","PACKAGE_REGEXP","RegExp","replacer","substring","$1","header","_chunk","replace","safeNextImport","next","constants","Promise","all","default","error","Error","requireFromPPDev","createRequire","previouslyLoadedKeys","Set","loadPPDevEnv","mode","envDir","process","cwd","key","env","fromEnvironment","Object","keys","filter","startsWith","loadEnv","value","entries","has","HANDOFF_KEY","Symbol","for","configCache","Map","packageJsonCache","getPackageJson","projectRoot","now","Date","root","resolve","cached","get","timestamp","JSON","parse","flag","set","empty","esbuildModule","MODULE_LOCATION","MODULE_LOCATION_DEFINE","__dirname","__filename","moduleLocationPlugin","name","setup","build","onLoad","args","contents","stringify","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","text","code","outputFiles","fileNameTmp","Math","random","toString","slice","tempFilePath","fileUrl","writeFileSync","config","conf","unlinkSync","loadJSONConfig","dirContentCache","getPkg","getConfig","dirContent","files","endsWithRegExp","readdirSync","withFileTypes","isFile","map","getDirectoryContent","configFound","newConfig","dirFiles","configNames","configName","includes","configPath","loadConfig","PP_DEV_CONFIG_NAMES","packageConfig","Array","isArray","clear","parseBooleanFlag","undefined","toLowerCase","applyDistZipOverride","overrides","defaultFileName","distZipEnabled","distZipDir","distZipFilename","outFileName","normalizeRelativeOutputPath","baseConfig","outDir","applyVersionManifestOverride","versionManifestEnabled","versionFileTemplate","enabled","normalizedVersionFileTemplate","PP_DEV_CONFIG_GROUPS","resolveRepositoryUrl","repository","url","directCiRepositoryUrlEnvVars","variableName","ciRepositoryUrl","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","globalThis","assetPrefix","allowed","req","res","pathname","split","fileName","length","readFile","err","content","statusCode","setHeader","extname","end","nextPkg","version","environment","ppDevConfig","validatePPDevConfig","normalizedPPDevConfig","normalizePPDevConfig","templateName","distZip","createDefaultZipFileName","versionPlugin","vitePPDev","then","require","apply","optimizeDeps","exclude","push","resolveId","source","match","resolvedId","id","transformIndexHtml","html","ctx","assetPaths","server","tags","tag","injectTo","attrs","rel","panelOptions","clientInjectionPlugin","children","src","configureServer","clientDir","allow","imageOptimizer","integrateMiTopBar","allowedHosts","addRootElement","addSharedComponentsScripts","defer","miTopBarPlugin","ViteImageOptimizer","versionPluginFn","packageVersion","packageRepositoryUrl","zipPack","enforce","PATH_PAGE_PREFIX","PATH_TEMPLATE_PREFIX","port","minify","assetsInlineLimit","rollupOptions","output","modules","localsConvention","panelMarkup","linkTag","bodyPrepend","linkInjected","headEnd","head","bodyStart","options","PP_DEV_DIST_ZIP","PP_DEV_DIST_ZIP_DIR","PP_DEV_DIST_ZIP_FILENAME","versionManifest","PP_DEV_VERSION_MANIFEST","PP_DEV_VERSION_FILE_TEMPLATE","nextjsConfig","phase","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_BUILD","PP_DEV_NEXT_BUILD_ENV_VAR","createLogger","warn","colors","yellow","nextConfiguration","mergedConfig","configs","merged","mutableMerged","mergePPDevConfigs","normalized","v7Features","isDevelopment","basePath","PATH_TEMPLATE_LOCAL_PREFIX","createBasePath","trailingSlash","prefix","assign","tunnelOrigins","exactAllowedHosts","allowedDevOrigins","buildDistDir","PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR","distDir","defineProperty","enumerable","configurable","handoff","wrapped","String"],"mappings":"giBA4BMA,EAAkBC,EAAKC,QAAQC,uBAC/BC,EAAgBH,EAAKI,KAAKL,EAAiB,cAEjD,IAAIM,EAA4C,KAqB1C,SAAUC,EAAsBC,GACpC,MAAO,CACLC,IAAKR,EAAKS,MAAML,KAAKG,EAAMG,EAAAA,aAAc,qBACzCC,GAAIX,EAAKS,MAAML,KAAKG,EAAMG,EAAAA,aAAc,oBAE5C,CAGM,SAAUE,EAAqBC,GAGnC,OA9BF,WACE,GAAIR,EACF,OAAOA,EAGT,MAAMS,EAAkBC,EAAGC,aAAab,EAAe,CAAEc,SAAU,SAUnE,OARAZ,EAAmBa,EAAIC,QAAQL,EAAiB,CAC9CM,cAAe,IACfC,eAAgB,IAChBC,OAAO,EACPC,cAAc,EACdC,cAAc,IAGTnB,CACT,CAYmBoB,EAEVC,CAAS,cACdhB,EAAAA,qBACAiB,EAAAA,QACAC,eAAgBf,EAAKe,eACrBC,aAAchB,EAAKgB,aACnBC,MAAOjB,EAAKiB,MACZC,QAASlB,EAAKkB,UAAW,EAGzBC,iBAAkBnB,EAAKmB,kBAAoB,eAC3CC,eAAgBpB,EAAKoB,iBAAkB,EACvCC,iBAAkBrB,EAAKqB,mBAAoB,GAE/C,CA4CA,MAAMC,EAAwC,CAC5C,MAAO,iCACP,OAAQ,0BACR,OAAQ,mCCpGV,MAAMpC,EAAkBqC,EAAAA,cAAcpC,EAAKI,KAAKiC,EAAAA,mBAAoB,gBAC9DC,EAAiB,IAAIC,OAAO,QAAQ7B,EAAAA,iCCtB1C,MAIM8B,EAAW,CAACC,EAAmBC,I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WjD,cAE/CmD,GAAiBO,EAAc5G,OAAS,IAC1CzG,EAAOuN,kBAAoB,IAAKvN,EAAOuN,mBAAqB,MAAQF,IAKtE,MAAMG,EAAenR,QAAQG,IAAIiR,sCAejC,OAbI3B,IAAUE,GAA0BwB,IACtCxN,EAAO0N,QAAUF,GAGnB9Q,OAAOiR,eAAe3N,EAAQ,QAAS,CACrCjD,MAAOwP,EACPqB,YAAY,EACZC,cAAc,IAEhBnR,OAAOiR,eAAe3N,EAAQ,eAAgB,CAAEjD,OAAO,EAAM6Q,YAAY,EAAOC,cAAc,IHza7DC,EG2aV,CAAE9H,MAAOuG,EAAcwB,SAAS,GH1a1D9H,WAA6B/I,GAAe4Q,EG4alC9N,CACT,CAAE,MAAOpE,GAKP,MAJesQ,EAAAA,eAERtQ,MAAM,sBAAuB,CAAEA,MAAOA,aAAiBC,MAAQD,EAAQ,IAAIC,MAAMmS,OAAOpS,MAEzFA,CACR,CHpbE,IAAiCkS,EGsbvC"}
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("fs"),i=require("path"),t=require("./auth.provider-fI0tFsf5.js");require("url"),require("picocolors"),require("node:path"),require("node:net"),require("vite");const n=(e=>e&&"object"==typeof e&&"default"in e?e.default:e)(i),o=new Set(["backendBaseURL","personalAccessToken","miHudLess","integrateMiTopBar","v7Features","appId","portalPageId","templateName","templateLess","enableProxyCache","proxyCacheTTL","disableSSLValidation","distZip","versionPlugin","imageOptimizer","outDir","syncBackupsDir"]);const r=[".pp-watch.config.ts",".pp-watch.config.js",".pp-watch.config.json","pp-watch.config.ts","pp-watch.config.js","pp-watch.config.json"];function a(e,i=0){const t=" ".repeat(i),n=" ".repeat(i+1);if(null===e)return"null";if("boolean"==typeof e)return String(e);if("number"==typeof e)return String(e);if("string"==typeof e)return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`;if(Array.isArray(e)){if(0===e.length)return"[]";return`[\n${e.map(e=>`${n}${a(e,i+1)}`).join(",\n")},\n${t}]`}if("object"==typeof e&&null!==e){const o=Object.entries(e).filter(([,e])=>void 0!==e);if(0===o.length)return"{}";return`{\n${o.map(([e,t])=>`${n}${e}: ${a(t,i+1)}`).join(",\n")},\n${t}}`}return String(e)}exports.discoverMigrateSource=function(i,o){let a=o??null,s=!1;if(!a){for(const o of t.PP_DEV_CONFIG_NAMES){const t=n.join(i,o);if(e.existsSync(t)){a=t;break}}if(!a)for(const t of r){const o=n.join(i,t);if(e.existsSync(o)){a=o,s=!0;break}}if(!a){const t=n.join(i,"package.json");if(e.existsSync(t))try{const i=JSON.parse(e.readFileSync(t,"utf-8"));i["pp-dev"]&&"object"==typeof i["pp-dev"]&&!Array.isArray(i["pp-dev"])&&(a=t)}catch{}}}return a?{sourceFile:a,isWatchConfig:s,isPackageJsonConfig:"package.json"===n.basename(a)}:null},exports.generateConfigFileContent=function(e,i="ts"){return"json"===i?JSON.stringify(e,null,2)+"\n":`${"ts"===i?"import { defineConfig } from '@metricinsights/pp-dev';":"const { defineConfig } = require('@metricinsights/pp-dev');"}\n\n${"ts"===i?"export default":"module.exports ="} defineConfig(${a(e)});\n`},exports.isAlreadyMigrated=function(e){const i=new Set(["mi","app","proxy","build","sync","inspector"]);return Object.keys(e).some(e=>i.has(e))},exports.isLegacyFlatConfig=function(e){return Object.keys(e).some(e=>o.has(e))},exports.isLegacyPPWatchConfig=function(e){return"baseURL"in e},exports.loadPackageJsonMigrateConfig=function(i){return JSON.parse(e.readFileSync(i,"utf-8"))["pp-dev"]},exports.migrateLegacyFlatConfig=function(e,i){const t={},n={};void 0!==e.backendBaseURL&&(n.url=e.backendBaseURL),void 0!==e.personalAccessToken&&(n.token=e.personalAccessToken),void 0!==e.miHudLess&&(n.mode=e.miHudLess?"standalone":"embedding"),e.integrateMiTopBar&&(!0===e.integrateMiTopBar?(n.mode||(n.mode="standalone"),n.include="top-bar"):"object"==typeof e.integrateMiTopBar&&(e.integrateMiTopBar.addRootElement||e.integrateMiTopBar.addSharedComponentsScripts)&&(n.mode||(n.mode="standalone"),n.include=e.integrateMiTopBar.addRootElement?"top-bar":"shared-components")),void 0!==e.v7Features&&(n.apiVersion=e.v7Features?7:6),Object.keys(n).length>0&&(t.mi=n);const o={},r=e.appId??e.portalPageId;void 0!==r&&(o.id=r),void 0!==e.templateName&&e.templateName!==i&&(o.name=e.templateName),void 0!==e.templateLess&&(o.type=e.templateLess?"page":"template"),Object.keys(o).length>0&&(t.app=o);const a={};void 0!==e.enableProxyCache&&(a.cache=e.enableProxyCache),void 0!==e.proxyCacheTTL&&(a.cacheTtl=e.proxyCacheTTL),void 0!==e.disableSSLValidation&&(a.tls={allowSelfSigned:e.disableSSLValidation}),Object.keys(a).length>0&&(t.proxy=a);const s={};if(void 0!==e.outDir&&(s.outDir=e.outDir),void 0!==e.distZip)if("object"==typeof e.distZip&&null!==e.distZip){const i={};void 0!==e.distZip.outFileName&&(i.fileName=e.distZip.outFileName),void 0!==e.distZip.outDir&&(i.outDir=e.distZip.outDir),void 0!==e.distZip.inDir&&(i.inDir=e.distZip.inDir),s.zip=!(Object.keys(i).length>0)||i}else s.zip=e.distZip;if(void 0!==e.versionPlugin)if("object"==typeof e.versionPlugin&&null!==e.versionPlugin){const i={};void 0!==e.versionPlugin.enabled&&(i.enabled=e.versionPlugin.enabled),void 0!==e.versionPlugin.versionFileTemplate&&(i.fileNameTemplate=e.versionPlugin.versionFileTemplate),s.versionFile=!(Object.keys(i).length>0)||i}else s.versionFile=e.versionPlugin;return void 0!==e.imageOptimizer&&(s.imageOptimisations=e.imageOptimizer),Object.keys(s).length>0&&(t.build=s),void 0!==e.syncBackupsDir&&(t.sync={backupsDir:e.syncBackupsDir}),t},exports.migratePPWatchConfig=function(e){const i={mi:{url:e.baseURL}};return void 0!==e.portalPageId&&(i.app={id:e.portalPageId}),i};
2
- //# sourceMappingURL=migrate-Gi9k9cLw.js.map
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("zlib"),t=require("./auth.provider-fI0tFsf5.js"),s=require("url"),r=require("axios"),n=require("node:http"),i=require("node:https"),a=require("./version-manifest-CVBuIKBS.js"),o=require("path"),c=require("fs"),l=require("crypto"),d=require("process"),u=require("os"),p=require("jszip"),h=require("child_process"),g=require("module"),m=require("http-proxy-middleware"),f=require("node:string_decoder"),y=require("node:crypto"),w=require("node:fs"),v=require("node:os"),b=require("node:path"),k=require("express");var $="undefined"!=typeof document?document.currentScript:null;const x=e=>e&&"object"==typeof e&&"default"in e?e.default:e;function S(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 A=x(r),E=x(n),T=x(i),I=S(o),P=S(c),R=S(l),N=S(d),j=S(u),L=x(p),F=S(h),O=x(w),C=x(v),B=x(b),M=x(k),D=I.dirname(t.PP_DEV_CLIENT_ENTRY),_={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function U(e,t){const s=t.clientDir??D,r=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,r)=>{P.readFile(I.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)?P.readFile(I.join(s,i),(e,s)=>{e?n():(t.setHeader("Content-Type",_[I.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):n()})}function H(t,s,r={}){switch(s){case"gzip":return e.unzipSync(t,r);case"br":return e.brotliDecompressSync(t,r);case"deflate":return e.inflateSync(t,r);default:return t}}const V="/@pp-dev/inspector",q=new WeakMap;function z(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function W(e){return Array.isArray(e)?e[0]??"":String(e??"")}function J(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 Z(e){return"string"==typeof e?e:void 0}function G(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}const K=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),X=new Map,Y=new Map;const Q=(e,t,s)=>{let r=X.get(e);if(!r){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";r=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${K(e)}${t})`,"gi"),X.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}`})},ee=(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},te=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function se(e){return e.split("?")[0]}class re{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 ne extends re{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 ie extends ne{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`}}const ae="Something went wrong when fetching page data",oe="Something went wrong when fetching page template data",ce="Something went wrong when fetching page variables",le=" The instance may be down or in maintenance mode. Please try again later.",de=[ae,oe,ce];function ue(){return new Error(`${ae}.${le}`)}function pe(){return new Error(`${oe}.${le}`)}function he(e){return e instanceof Error&&de.some(t=>e.message.includes(t))}class ge extends re{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 ue();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 ue();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 ue();return s.page}}class me extends re{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 pe();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 pe();return s.page_template}}class fe extends re{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(`${ce}.${le}`);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}})}}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 xe(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>we(e,t)):we(e,t)}const Se=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 Ee(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 Te(e){const{status:t}=Ae(e);return 401===t||403===t||412===t}const Ie="[DEV PAGE. DO NOT DELETE]",Pe=new Map;const Re=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,Ne=new RegExp(`^(?:${Re})$`),je=".localhost";function Le(e){return e?e.length>32?"The name must be at most 32 characters long":Ne.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 Fe(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(je))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function Oe(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${ye(e)?"https":"http"}://${t?`${t}.`:""}localhost${s?`:${s}`:""}`}const Ce=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=Le(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=Le(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=Fe(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}};const Be=/(?:^|\/\/[^/]+)\/(?:login|auth\/saml\/login)(?:[/?#]|$)/i;function Me(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==ve)}function De({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&Be.test(String(t.location??""))}class _e{#e;#d;#u=t.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=Fe(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=Fe(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&&!De(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&&De(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,s,r,n){let i;this.#p.set(e,s);try{i=await this.#d(s)}catch(i){return this.#p.get(e)===s&&(this.#p.delete(e),this.#g.set(e,{session:s,replaced:r,ownHost:n,retryAt:Date.now()+5e3})),void this.#u.warn(t.colors.yellow(`Could not check the MI session of user ${e.name}: ${String(i)}`))}if(this.#p.get(e)===s&&this.#e.get(e.name)===e)if(this.#p.delete(e),this.#g.get(e)?.session===s&&this.#g.delete(e),i){if(this.#f(e,s)||void 0!==r&&this.#f(e,r))return;const a="active"===e.state;n&&(this.#v(e),void 0!==r&&r!==s&&this.#v(e,r)),this.#g.delete(e),Object.assign(e,{state:"active",session:s,miUser:i}),this.#h.delete(e),this.#e.sessionChanged(e),a||this.#u.info(`${t.colors.blue("User")} ${t.colors.yellow(e.name)} ${t.colors.blue("logged in")} (MI user ${i.id}${i.username?`, ${i.username}`:""})`)}else this.#h.set(e,s),"active"===e.state&&r===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,s){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(`${t.colors.yellow(`The MI session of user ${e.name} ended`)} (${s}). Log in again on its host.`)}}async function Ue(e,t){try{const s=await e.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",...t},!0,{quiet:!0}),r=s.data?.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(Te(e))return{miUser:void 0,refused:Ee(e).userFriendlyMessage};throw e}}async function He(e,t){try{const s=await Ue(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: ${Ee(e).userFriendlyMessage}`}}}const Ve=/^(https?:\/\/)([^/]+)(\/.*)?$/i,qe="X-PP-Proxy";const ze=/^\/login(?:\/|$)/i,We="/auth/saml/login";const Je=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const Ze=new WeakMap,Ge=new WeakMap;const Ke=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function Xe(e){const t=e.split(";",1)[0].trim().toLowerCase();return Ke.some(e=>e.test(t))}const Ye=/[\w.:/\\!-]/;function Qe(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&&Xe(s)}function et(e){return async(t,s,r)=>{const n=e&&Qe(t.headers);r.statusCode=t.statusCode??r.statusCode,t.statusMessage&&(r.statusMessage=t.statusMessage),r.setHeader(qe,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 f.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(!Ye.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()})}}const tt=/\.(?:[a-z0-9]+)$/i,st=6e5,rt=104857600,nt=1e3,it=10485760;const at=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=st){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)}}(rt,nt),ot=new Set,ct=new Map;function lt(e){at.clear(),ct.clear(),ot.forEach(e=>e()),t.createLogger().info(t.colors.blue(`Proxy cache cleared: ${e}`))}const dt=new WeakSet;function ut(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function pt(e,s){if(e){for(const t of at.keys())ut(t,e)&&at.del(t);ct.delete(e),t.createLogger().info(t.colors.blue(`Proxy cache cleared for ${e}: ${s}`))}else lt(s)}function ht(e,t,s){const r=function(e){return Ze.get(e)}(e);if(void 0!==r){const e=ct.get(s),t=void 0!==e&&r!==e;return ct.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 gt(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)}const mt=new Map;function ft(e){const t=mt.get(e);return t?Date.now()-t.timestamp>18e4?(mt.delete(e),null):t.data:null}function yt(e,t){mt.set(e,{timestamp:Date.now(),data:t})}var wt;wt=()=>mt.clear(),ot.add(wt);let vt=!1;function bt(e){vt||(vt=!0,e.info(t.colors.blue("Clearing proxy cache after successful login")),at.clear())}function kt(){vt=!1,t.authProvider.reset()}const $t="/home?proxyRedirect=";function xt(e){const t=e.headers??{},s=Boolean(Fe(e.headers?.host));if(!s&&!Ce.resolve(e)?.user)return t;const{cookie:r,authorization:n,token:i,...a}=t;return s||void 0===r?a:{...a,cookie:r}}async function St(e,s,r,n,i,a){const{appId:o,redirectOnAuthFailure:c,redirectUrl:l}=s;if(void 0===o){const e=new Error("Custom App ID is required for page info only mode");return a.error(t.colors.red(e.message)),i(e)}const d=xt(r);a.info(t.colors.green("Start loading page info"));try{const s=`pageInfo:${o}`;return ft(s)?(a.info(t.colors.green("Page info loaded from cache")),i()):(await e.getPageInfo(o,d),bt(a),yt(s,{success:!0}),t.authProvider.updateState({isAuthenticated:!0}),a.info(t.colors.green("Page info loaded successfully")),i())}catch(e){return kt(),Et(e,c??!0,l||`${$t}${encodeURIComponent("/")}`,n,i,a,"Page info")}}async function At(e,s,r,n,i,a){const{templateLess:o,appId:c,redirectOnAuthFailure:l,redirectUrl:d}=s,u=xt(r);a.info(t.colors.green("Start loading page data"));try{const s=`pageData:${o}:${c}`;if(ft(s))return a.info(t.colors.green("Page data loaded from cache")),i();const r=o||void 0===c?e.getPageTemplate(u):e.getPageVariables(c,u);return await r,bt(a),yt(s,{success:!0}),a.info(t.colors.green("Page data loaded successfully")),i()}catch(e){return kt(),Et(e,l??!0,d||`${$t}${encodeURIComponent("/")}`,n,i,a,"Page data")}}function Et(e,s,r,n,i,a,o){if(function(e){return null!==e&&"object"==typeof e&&Te(e)}(e)&&(a.info(t.colors.red(`${o} loading failed. Not authorized`)),s)){const e=`${r}`;return a.info(t.colors.yellow(`Redirecting to: ${e}`)),te(n,e,302)}const c=e instanceof Error?e.message:String(e);return a.info(t.colors.red(`${o} loading failed. Error: ${c}`)),i(e)}async function Tt(e){const t=new L,s=async r=>{const n=await c.promises.readdir(r,{withFileTypes:!0});for(const i of n){const n=I.join(r,i.name);if(i.isDirectory())await s(n);else if(i.isFile()){const s=I.relative(e,n).replace(/\\/g,"/");t.file(s,await c.promises.readFile(n))}}};return await s(e),await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"})}async function It(e,t){const s=await L.loadAsync(await c.promises.readFile(e),{createFolders:!1}),r=I.resolve(t),n=Object.values(s.files).filter(e=>!e.name.startsWith("__MACOSX/"));for(const e of n){const t=e.unsafeOriginalName??e.name,s=I.resolve(r,t);if(s!==r&&!s.startsWith(r+I.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 c.promises.mkdir(r,{recursive:!0});for(const e of n){const t=I.resolve(r,e.unsafeOriginalName??e.name);e.dir?await c.promises.mkdir(t,{recursive:!0}):(await c.promises.mkdir(I.dirname(t),{recursive:!0}),await c.promises.writeFile(t,await e.async("nodebuffer")))}}function Pt(e,t){const s=t?.distDir;if("export"!==t?.output||!s||".next"===s)return null;const r=I.resolve(e,s,"dev","types");return P.existsSync(r)?(P.rmSync(r,{recursive:!0,force:!0}),r):null}const Rt=6e5;function Nt(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&&F.spawn("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"}).on("error",()=>{})}function jt(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=F.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,Nt(u,"SIGKILL",d)):(p=e,t?(Nt(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,Nt(u,"SIGKILL",d)},o)):Nt(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&&Nt(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 Lt=".next";async function Ft(e,s={}){let r;try{const t=g.createRequire(I.join(e,"package.json")).resolve("next/package.json");r=I.resolve(I.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}const{distDir:n,...i}=s,a=Object.assign({},process.env,{NODE_ENV:"production",[t.PP_DEV_NEXT_BUILD_ENV_VAR]:"1"});n?a[t.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR]=n:delete a[t.PP_DEV_NEXT_BUILD_DIST_DIR_ENV_VAR],await jt("next build",process.execPath,[r,"build"],{...i,cwd:e,env:a})}const Ot="pageName",Ct="date",Bt=I.dirname("undefined"!=typeof __filename&&__filename||s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:$&&"SCRIPT"===$.tagName.toUpperCase()&&$.src||new URL("request-capture.middleware-C9SbJkfk.js",document.baseURI).href)),Mt=I.resolve(Bt,"..",".."),Dt=Buffer.from([80,75,3,4]),_t=20,Ut=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const Ht="sync-service.meta.json",Vt="BUILD-MANIFEST.json",qt="__template_variables.json";const zt=12e4;class Wt{server;opts;eventMap;logger;syncInFlight=null;syncActionResolvers=new Map;constructor(e,s){this.server=e,this.opts=s||{},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=t.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??zt)/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,s){const r=this.describeSyncCancel(s);this.sendSyncResponse(e,{cancelled:!0,message:`${r} Backup was saved.`}),this.logger.info(t.colors.yellow(r))}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=l.randomUUID(),r=this.opts.syncActionTimeoutMs??zt;return await new Promise(n=>{const i=e=>this.resolveSyncAction(s,{approved:!1,reason:e}),a=setTimeout(()=>i("timeout"),r),{socket:o}=t,c=()=>i("disconnected");o?.once("close",c),this.syncActionResolvers.set(s,{resolve:n,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,s){if(this.syncInFlight)return this.logger.warn(t.colors.yellow("Template sync requested while another one is running; ignored")),void this.sendSyncResponse(s,{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 r=this.runTemplateSync(e,s);this.syncInFlight=r;try{await r}finally{this.syncInFlight=null}}async runTemplateSync(e,s){if(!this.opts.distService||!this.opts.miAPI)return this.sendSyncResponse(s,{error:"Dist service or MiAPI is not defined"}),void this.logger.error(t.colors.red("Dist service or MiAPI is not defined"));{const{distService:e,miAPI:n}=this.opts;try{if(this.server.config.clientInjectionPlugin?.v7Features){if(!n?.isV710OrHigher)return void this.sendSyncResponse(s,{error:"This feature is available only for MI v7.1.0 or higher",config:{canSync:!1}});s.send("client:config:update",{config:{canSync:!0}})}const i=await(n?.getAssets().catch(async e=>{if(r.isAxiosError(e)){if("SESSION_EXPIRED"===Ee(e).code){this.logger.info(t.colors.yellow("Session expired - attempting to validate credentials"));try{const e=await(n?.validateCredentials());e&&!e.isValid?(this.logger.error(t.colors.red(`Authentication error: ${e.error}`)),this.sendSyncResponse(s,{error:e.error??"Authentication failed",code:e.code,refresh:!0})):(this.logger.info(t.colors.yellow("Session expired")),this.sendSyncResponse(s,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch(e){this.logger.info(t.colors.yellow("Session expired")),this.sendSyncResponse(s,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0})}return e}if(e.cause instanceof Error&&("ECONNRESET"===e.cause.code||"ENOTFOUND"===e.cause.code))return this.logger.info(t.colors.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.sendSyncResponse(s,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e;const r=e.response?.status;if(502===r||503===r||504===r)return this.logger.info(t.colors.yellow(`Server in maintenance mode or unreachable (HTTP ${r}); VPN may be required`)),this.sendSyncResponse(s,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e}if(he(e))return this.logger.info(t.colors.yellow("Server in maintenance mode or non-JSON page / page-template API response (unavailable HTML body)")),this.sendSyncResponse(s,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e;throw e}));if(i instanceof Error)return;let a;if(i){const t=await(e?.analyzeBackup(i).catch(e=>e));if(t instanceof Error)a=t;else if(t){await(e?.saveBackup(i,t));const r=0===t.unknownFiles.length&&1===t.versionManifestHashMismatches.length&&I.basename(t.versionManifestHashMismatches[0].relativePath)===qt,n=t.versionManifestHashMismatches,o=n.filter(e=>I.basename(e.relativePath)===qt),c=n.filter(e=>I.basename(e.relativePath)!==qt),l=!r&&o.length>0&&c.length>0,d=r?[]:c.map(e=>e.relativePath),u=async()=>{if(!t.templateVariables||!e)return!0;const{templateVariables:r}=t;if(await e.getPublicTemplateVariablesHash()!==r.actualHash){const t=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"},s);if(t.approved)await e.saveTemplateVariablesFile(r.content);else if("cancelled"!==t.reason)return this.cancelSync(s,t.reason),!1}return!0};if(t.unknownFiles.length>0){const e=await this.requestSyncAction({title:"Unknown files found in backup",content:`Backup contains files not listed in VERSION: ${t.unknownFiles.join(", ")}. Continue sync or cancel?`,confirmText:"Continue sync",cancelText:"Cancel sync"},s);if(!e.approved)return void this.cancelSync(s,e.reason)}if(l&&!await u())return;if(!r&&d.length>0){const e=40,t=d,r=t.slice(0,e),n=t.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"},s);if(!o.approved)return void this.cancelSync(s,o.reason)}if(!r&&t.buildManifestMismatch&&0===t.versionManifestHashMismatches.length){const{expected:e,actual:r}=t.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"},s);if(!n.approved)return void this.cancelSync(s,n.reason)}if(!l&&!await u())return;a=await(e?.buildNewAssets())}}else a=await(e?.buildNewAssets());if(!(a&&a instanceof Buffer))return a instanceof Error?(this.sendSyncResponse(s,{error:a.message}),void this.logger.error(t.colors.red(a.message))):(this.sendSyncResponse(s,{error:"Failed to build new assets"}),void this.logger.error(t.colors.red("Failed to build new assets")));{if(e.stopped)return this.sendSyncResponse(s,{error:"Sync stopped: the dev server is shutting down."}),void this.logger.warn(t.colors.yellow("Sync stopped before the upload: the dev server is shutting down"));const r=await(n?.updateAssets(a));if("OK"===r?.status){const r=e?.getBackupMeta();this.sendSyncResponse(s,{syncedAt:(new Date).toISOString(),backupFilename:r?.lastBackupName??""}),this.logger.info(t.colors.green("Template synced"))}else this.sendSyncResponse(s,{error:"Failed to update assets"}),this.logger.error(t.colors.red("Failed to update assets"))}}catch(e){const r=e instanceof Error?e.message:"Template sync failed";return this.logger.error(t.colors.red(`Template sync failed: ${r}`)),void this.sendSyncResponse(s,{error:r,code:"SYNC_FAILED"})}}}async onPageVariablesReload(e,s){const{miAPI:r}=this.opts;if(!r)return s.send("page-variables:reload:response",{error:"MiAPI is not defined"}),void this.logger.error(t.colors.red("MiAPI is not defined"));try{const e=await r.reloadPageVariables();s.send("page-variables:reload:response",{ok:!0,count:e?e.length:0,skipped:null===e}),this.logger.info(t.colors.green("Page variables reloaded"))}catch(e){const r=e instanceof Error?e.message:"Reload variables failed";this.logger.error(t.colors.red(`Reload variables failed: ${r}`)),s.send("page-variables:reload:response",{error:r})}}}const Jt=["text","select","multiselect","file","list","color","boolean"];function Zt(e){return Jt.includes(e)}const Gt=["true","false","Y","N","1","0"],Kt=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function Xt(e,t){return e.id===t||e.text===t}function Yt(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 Qt(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 Kt.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(Yt);return r.some(e=>Xt(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(Yt),n=i.split(",").map(e=>e.trim()).filter(e=>!r.some(t=>Xt(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 es(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(...Qt(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 ts(e,t){const s=[];switch(e.tag_type){case"boolean":Gt.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${Gt.join(", ")}).`});break;case"list":try{const r=JSON.parse(t);Array.isArray(r)?s.push(...es(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(Yt),n=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!r.some(t=>Xt(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 ss(e,t){switch(e.tag_type){case"boolean":return Gt.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||Kt.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 rs="/@pp-dev/variables-editor",ns=/^[A-Za-z0-9_\s-]+$/,is="Dist service or MiAPI is not defined",as=new WeakMap;async function os(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 cs(e){const t=e?(await os(e))?.schema??null:null;return t&&{...t,tags:t.tags.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.name&&""!==e.name)}}function ls(e,t,s){const r=as.get(e);if(r)return void(r.deps=t);const n={deps:t};as.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:is});const r=await os(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:is});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&&!Zt(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),ns.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 ${qt}.`,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 cs(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 cs(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(...ts(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.find(e=>e.internal_name===s.internalPageName)??null,n=e.filter(e=>e.internal_name!==s.internalPageName).map(e=>({id:e.id,name:e.name,internal_name:e.internal_name,sameTemplate:!!r&&(null!=r.template_id?e.template_id===r.template_id:!!r.template&&e.template===r.template)}));t.json({pages:n,currentPageName:r?.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 cs(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=ss(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)})}}),U(e,{path:rs,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(n.deps.miAPI.isTemplateLess))})})}const ds="/@api/users",us=new WeakMap;function ps(e,t){const s=Oe(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 hs(e,t,s,r){e.status(t).json({error:r,code:s})}function gs(e){let s;try{s=JSON.parse(O.readFileSync(e,"utf-8"))}catch(s){return"ENOENT"!==s.code&&t.createLogger().warn(t.colors.yellow(`Could not read the saved users from ${e}: ${String(s)}`)),[]}const r=s&&"object"==typeof s&&!Array.isArray(s)?s.users:void 0;return(Array.isArray(r)?r:[]).filter(e=>"string"==typeof e?.name&&"string"==typeof e.token&&Boolean(e.token))}const ms=new WeakMap,fs=new WeakMap;function ys(e){ms.delete(e),fs.get(e)?.(),fs.delete(e)}async function ws(e,s){const r=function(e,t,s=C.homedir()){const r=y.createHash("sha256").update(`${B.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return B.join(s,".pp-dev","users",`${r}.json`)}(s.projectRoot,s.miUrl,s.homeDir),n={project:B.resolve(s.projectRoot),miUrl:s.miUrl},i=t.createLogger();if(ms.get(e)===r)return;ys(e),ms.set(e,r);const a=gs(r);let o=!0,c=!1,l=e.list().some(e=>"token"===e.kind&&e.token);const d=new Set,u=new Set,p=()=>{const s=e.list(),a=s.filter(e=>"token"===e.kind&&e.token).map(e=>({name:e.name,token:e.token})),o=new Set(s.map(e=>e.name)),c=gs(r).filter(e=>!o.has(e.name)&&!u.has(e.name));try{!function(e,t,s){const r={version:1,...s,users:t},n=`${e}.${process.pid}.tmp`;O.mkdirSync(B.dirname(e),{recursive:!0,mode:448}),O.writeFileSync(n,`${JSON.stringify(r,null,2)}\n`,{mode:384}),O.renameSync(n,e),O.chmodSync(e,384)}(r,[...a,...c],n)}catch(e){i.warn(t.colors.yellow(`Could not save the users to ${r}: ${String(e)}`))}},h=e.onRemove(t=>{ms.get(e)===r&&(u.add(t.name),o&&d.add(t.name))}),g=e.onChange(()=>{ms.get(e)===r&&(o?l||=!c:p())});fs.set(e,()=>{h(),g()});try{const n=await Promise.all(a.map(e=>s.checkToken(e.token)));if(ms.get(e)!==r)return;a.forEach((s,r)=>{if(Le(s.name)||e.get(s.name)||d.has(s.name))return;const a=n[r];c=!0;try{e.add({name:s.name,kind:"token",token:s.token,...a.ok?{miUser:a.miUser}:{},...!a.ok&&a.rejected?{state:"expired"}:{}})}finally{c=!1}a.ok||i.warn(t.colors.yellow(`Restored user ${s.name}: ${a.message}`))})}finally{o=!1}l&&ms.get(e)===r&&p(),a.length&&i.info(`${t.colors.blue("Restored")} ${a.length} ${t.colors.blue("saved user(s) from")} ${r}`)}function vs(e){const s=`${B.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;Ce.context!==s&&(ys(Ce),Ce.useContext(s)),e.persist?e.miAPI.personalAccessToken?ws(Ce,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>He(e.miAPI,t)}).catch(e=>{t.createLogger().warn(t.colors.yellow(`Could not restore the saved users: ${String(e)}`))}):t.createLogger().warn(t.colors.yellow("users.persist is on, but users need your own API token (mi.token or MI_ACCESS_TOKEN).")):ys(Ce)}function bs(e,t,s,r,n){const i={error:s};r&&(i.details=r),n&&(i.code=n),e.status(t).json(i).end()}function ks(e,s){const r=s instanceof Error?s.message:String(s);t.createLogger().error(t.colors.red(`Request failed: ${r}`)),e.writableEnded||e.destroyed||(e.headersSent?e.destroy():(e.statusCode=500,e.setHeader("content-type","text/plain; charset=utf-8"),e.end(r)))}const $s="10mb",xs=(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 (${$s}).`:`The request body could not be read: ${e.message}`;s.status(n).json({error:i})};function Ss(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function As(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}}const Es="<redacted>",Ts=new RegExp(`(^|;\\s*)(${ve}=)[^;]*`,"gi"),Is=new RegExp(`^(\\s*${ve}=)[^;]*`,"i");function Ps(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?Es:`${e} ${Es}`}return void 0!==t.token&&(t.token=Es),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(Ts,`$1$2${Es}`)),t}function Rs(e){const t={...e},s=t["set-cookie"],r=e=>e.replace(Is,`$1${Es}`);return Array.isArray(s)?t["set-cookie"]=s.map(r):"string"==typeof s&&(t["set-cookie"]=r(s)),t}const Ns=/^\/(?:login|auth)(?:[/?#]|$)/i,js=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function Ls(e,t){return Array.isArray(e)?e.map(e=>Ls(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>js.test(e)?(t.any=!0,[e,Es]):[e,Ls(s,t)])):e}function Fs(e,t,s){if(!s)return s;if(Ns.test(e))return Buffer.from(Es);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=>js.test(e));return t.forEach(t=>e.set(t,Es)),t.length?Buffer.from(e.toString()):s}if("application/json"===r||r.endsWith("+json")){const e={any:!1},t=Ls(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const Os=["/@","/_next/","/__nextjs_"],Cs=new Set(["/favicon.ico","/installHook.js.map"]);exports.DistService=class{root;backupFolder;backupNameTemplate;dateFormat;pageName;currentMeta=null;distZipFolder;distZipFilename;versionFileTemplate;buildInputFolder;nextBuild;maxBackups;buildTimeoutMs;metaDir;builds=new AbortController;metaLoaded;logger;constructor(e,s){this.pageName=e;const{root:r=N.cwd(),backupFolder:n="backups",distZipFolder:i=I.resolve(r,"dist-zip"),distZipFilename:a=t.createDefaultZipFileName(this.pageName),backupNameTemplate:o=`{${Ot}}-{${Ct}}.zip`,versionFileTemplate:c="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:l,dateFormat:d=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:u,maxBackups:p=_t,buildTimeoutMs:h=Rt,metaDir:g}=s||{};this.root=r,this.backupFolder=I.resolve(r,n),this.backupNameTemplate=o,this.dateFormat=d,this.distZipFolder=i,this.distZipFilename=t.normalizeRelativeOutputPath(a,"ZIP output file name"),this.versionFileTemplate=t.normalizeRelativeOutputPath(c,"VERSION file name template"),this.buildInputFolder=l,this.nextBuild=u,this.maxBackups="number"==typeof p&&Number.isInteger(p)&&p>0?p:1/0,this.buildTimeoutMs=h,this.metaDir=void 0===g?I.join(this.backupFolder,".pp-dev-meta"):I.resolve(r,g),this.logger=t.createLogger(),this.metaLoaded=this.loadMeta()}stopBuilds(){this.builds.abort()}async checkMeta(){await c.promises.mkdir(this.metaDir,{recursive:!0}),await c.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(t.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 c.promises.readFile(I.join(this.metaDir,Ht),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await c.promises.writeFile(I.join(this.metaDir,Ht),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=I.resolve(this.backupFolder,e);try{return await c.promises.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${Ot}}`,e).replace(`{${Ct}}`,this.dateFormat(t))}getBackupMeta(){return this.currentMeta}async pruneBackups(e){if(Number.isFinite(this.maxBackups))try{const s=function(e,t,s){const r=s.split(/(\d+)/).map((e,t)=>t%2==1?"\\d+":Ut(e)).join(""),n=[{token:`{${Ot}}`,pattern:Ut(t)},{token:`{${Ct}}`,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+=Ut(e.slice(a,r))+s,a=r+t.length;return new RegExp(`${i}${Ut(e.slice(a))}$`)}(this.backupNameTemplate,this.pageName,this.dateFormat(new Date)),r=new Set([e]),n=await c.promises.readdir(this.backupFolder,{withFileTypes:!0}),i=(await Promise.all(n.filter(e=>e.isFile()&&s.test(e.name)).map(async e=>({name:e.name,mtimeMs:(await c.promises.stat(I.resolve(this.backupFolder,e.name))).mtimeMs})))).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.name.localeCompare(e.name)),a=i.filter(e=>r.has(e.name)).length,o=i.filter(e=>!r.has(e.name)).slice(Math.max(0,this.maxBackups-a));for(const e of o)await c.promises.unlink(I.resolve(this.backupFolder,e.name));o.length>0&&this.logger.info(t.colors.gray(`[DistService] Deleted ${o.length} old backup(s), keeping the latest ${this.maxBackups}`))}catch(e){this.logger.warn(t.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 t.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 c.promises.readdir(t,{withFileTypes:!0});if(1!==e.length||!e[0]?.isDirectory())return t;t=I.join(t,e[0].name)}}async listFilesRecursive(e){const t=await c.promises.readdir(e,{withFileTypes:!0}),s=[];for(const r of t){const t=I.join(e,r.name);r.isDirectory()?s.push(...await this.listFilesRecursive(t)):r.isFile()&&s.push(t)}return s}buildManifestChecksum(e){const t=Object.keys(e).sort().map(t=>e[t]).join("");return R.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return R.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===qt}async pickTemplateVariablesFromBackupZip(e,t){const s=e.find(e=>I.basename(e)===qt);if(!s)return null;const r=I.join(t,s),n=await c.promises.readFile(r);return{relativePath:s,content:n,actualHash:R.createHash("sha256").update(n).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const s=await c.promises.mkdtemp(I.join(j.tmpdir(),"pp-dev-backup-")),r=I.join(s,"backup.zip"),n=I.join(s,"extracted");try{await c.promises.mkdir(n,{recursive:!0}),await c.promises.writeFile(r,e),await It(r,n);const s=await this.normalizeExtractedRootDir(n),i=(await this.listFilesRecursive(s)).map(e=>this.pathToPosix(I.relative(s,e))),a=i.filter(e=>I.basename(e)===Vt);if(a.length>1)throw new Error(`Expected at most one ${Vt} in backup ZIP, found ${a.length}`);const o=1===a.length?a[0]:null;let l=null;if(o){const e=I.join(s,o);if(l=JSON.parse(await c.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=>I.basename(t)===I.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(I.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;const g={};let m=[];if(d){const e=I.join(s,d),r=JSON.parse(await c.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,t]of Object.entries(u)){const r=I.join(s,e),n=await c.promises.readFile(r).catch(()=>null);if(!n)throw new Error(`VERSION manifest references missing file: ${e}`);const i=R.createHash("sha256").update(n).digest("hex");g[e]=i,i!==t&&m.push({relativePath:e,expected:t,actual:i}),this.isTemplateVariablesBasename(I.basename(e))&&(p={relativePath:e,content:n,actualHash:i,manifestHash:t})}m.length>0&&this.logger.warn(t.colors.yellow(`[DistService] VERSION manifest hash mismatch for ${m.length} file(s) (confirm in UI): ${m.map(e=>e.relativePath).join(", ")}`))}const f=new Set(m.map(e=>e.relativePath)),y={},w=[];for(const e of i){if(e===o)continue;if(d&&e===d)continue;const t=I.join(s,e),r=await c.promises.readFile(t),n=R.createHash("sha256").update(r).digest("hex");d&&Object.prototype.hasOwnProperty.call(u,e)?y[e]=f.has(e)?g[e]:u[e]:d?(y[e]="__NOT_IN_VERSION_FILE__",w.push(e)):y[e]=n}p||(p=await this.pickTemplateVariablesFromBackupZip(i,s));const v=this.buildBackupFingerprint(y);let b=null;return l&&d&&v!==l.buildFingerprint&&(b={expected:l.buildFingerprint,actual:v},this.logger.warn(t.colors.yellow(`[DistService] Build manifest fingerprint mismatch (confirm in UI): expected ${l.buildFingerprint}, got ${v}`))),{backupFingerprint:v,unknownFiles:w,templateVariables:p,mainHash:h,allFilesInMeta:Boolean(d&&0===w.length),buildManifestMismatch:b,versionManifestHashMismatches:m}}finally{await c.promises.rm(s,{recursive:!0,force:!0})}}async analyzeBackup(e){if(!Dt.equals(e.subarray(0,Dt.length)))throw new Error("Backup file is not a ZIP file");return await this.resolveBackupAnalysisFromZip(e)}async getPublicTemplateVariablesHash(){const e=I.resolve(this.root,"public",qt),t=await c.promises.readFile(e).catch(()=>null);return t?R.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=I.resolve(this.root,"public",qt);return await c.promises.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=I.resolve(this.root,"public",qt);return await c.promises.mkdir(I.dirname(t),{recursive:!0}),await c.promises.writeFile(t,e),t}async saveBackup(e,s){const r=s??await this.analyzeBackup(e),n=r.backupFingerprint,i=await this.getLatestSavedBackup(),a=await this.meta();if(i){const{lastBackupHash:e,lastMainHash:s}=a;if(e===n)return void this.logger.info(t.colors.yellow(`[DistService] Backup skipped: same backup fingerprint as last saved (${n.slice(0,12)}...)`));if(r.allFilesInMeta&&r.mainHash&&s===r.mainHash)return void this.logger.info(t.colors.yellow("[DistService] Backup skipped: same VERSION manifest checksum (main hash) and all files listed in VERSION"))}const o=new Date,l=this.backupName(this.pageName,o);a.lastBackupName=l,a.lastBackupHash=n,a.lastBackupDate=o.toISOString(),r.mainHash?a.lastMainHash=r.mainHash:delete a.lastMainHash,await this.syncMeta(),await c.promises.writeFile(I.resolve(this.backupFolder,l),e),this.logger.info(`Backup saved to ${l}`),await this.pruneBackups(l)}async buildNewAssets(){if(this.nextBuild)return await this.buildNextAssets();this.logger.info(t.colors.cyan("[DistService] Build started"));const e=jt("pp-dev build","node",[I.resolve(Mt,"./bin/pp-dev.js"),"build"],{cwd:this.root,env:Object.assign({},N.env,{NODE_ENV:"production"}),timeoutMs:this.buildTimeoutMs,signal:this.builds.signal});try{if(await this.logBuild("Build",e),this.buildInputFolder){const e=I.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(e))throw new Error(`Build input directory ${e} not found`);const t=await Tt(e);return this.throwIfStopped("pp-dev build"),t}const t=I.resolve(this.root,this.distZipFolder,this.distZipFilename);let s;try{s=await c.promises.readFile(t)}catch(e){if("ENOENT"===e.code)throw new Error(`File ${t} not found`);throw e}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:s,buildDistDir:r=s,output:n,configWrapped:i}=this.nextBuild,o=i||r===Lt?"out":r,l=I.resolve(e,o);if(i&&function(e,t){const s=I.relative(t,e);return""===s||!(".."===s||s.startsWith(`..${I.sep}`)||I.isAbsolute(s))}(I.resolve(e,s),l))throw new Error(`The app's distDir (${s}) is inside the sync's export directory (${o}), which next build empties: set another distDir in next.config.`);const d=Pt(e,{output:n,distDir:s});if(d&&this.logger.info(t.colors.dim(`[DistService] Removed stale dev route types: ${I.relative(e,d)}`)),i||o!==s||this.logger.warn(t.colors.yellow(`⚠️ next.config is not wrapped with withPPDev(): the sync's build exports into ${s} and removes the dev server's ${I.join(s,"dev")}; restart pp-dev next after the sync`)),i&&await c.promises.rm(l,{recursive:!0,force:!0}),this.logger.info(t.colors.cyan("[DistService] Next.js build started")),await this.logBuild("Next.js build",Ft(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal,distDir:i?Lt: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 a.writeBuildVersionManifest({outDir:l,packageVersion:this.nextBuild.packageVersion,versionFileTemplate:this.versionFileTemplate,packageRepositoryUrl:this.nextBuild.packageRepositoryUrl,packageBranchName:this.nextBuild.packageBranchName}),this.throwIfStopped("next build");const u=await Tt(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,s){try{await s}catch(s){const r=this.builds.signal.aborted;throw this.logger.info(t.colors.yellow(`[DistService] ${e} ${r?"stopped":"failed"}`)),s}this.logger.info(t.colors.cyan(`[DistService] ${e} finished`))}async isDirectory(e){try{return(await c.promises.stat(e)).isDirectory()}catch{return!1}}},exports.INSPECTOR_PATH=V,exports.MiAPI=class{#b;#k;#$=null;#x;#S;#A=!1;#E=null;#T=null;#I;#P;#R;#N;#j;internalPageName;appId;templateLess;assetsApi;pageApi;pageTemplateApi;pageVariableApi;logger;constructor(e,s){const{headers:r={},appId:n,templateLess:i=!0,disableSSLValidation:a=!1,v7Features:o=!1,personalAccessToken:c}=s||{};this.#b=r,this.#S=[],this.#x="",this.#I=o,this.#P=c,this.#R=!1,this.#N=Promise.resolve(!1);const l=`${e}:${a}`;if(Pe.has(l))this.#k=Pe.get(l);else{const t=new T.Agent({keepAlive:!1,...a?{rejectUnauthorized:!1}:{}});this.#k=A.create({baseURL:e,headers:r,timeout:3e4,maxRedirects:5,httpAgent:new E.Agent({keepAlive:!1}),httpsAgent:t}),Pe.set(l,this.#k)}this.appId=n,this.templateLess=i,this.assetsApi=new(o?ie:ne)(this.#k),this.pageApi=new ge(this.#k),this.pageTemplateApi=new me(this.#k),this.pageVariableApi=new fe(this.#k),this.logger=t.createLogger()}async isTemplateLoaded(){return this.#N}get isV710OrHigher(){return this.#R}get v7Features(){return this.#I}#L(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}#F(e){return e.replace(/[.*+?^${}()|[\]\\\/]/g,"\\$&")}get personalAccessToken(){return this.#P}set personalAccessToken(e){this.#P=e}updateHeaders(e){this.#L(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.#N||this.#$||(this.#N=new Promise(e=>{this.#j=e})),this.#$)return Promise.resolve(this.#$);if(void 0===this.templateLess&&(this.templateLess=!1),this.#I){const s=await this.pageApi.get(this.appId,this.#L(e)).then(e=>(this.logger.info(t.colors.green("Page fetched")),e)).catch(async s=>{if(this.#j(!1),he(s))throw s;throw await this.pageApi.checkAuth(this.#L(e))?(this.logger.error(t.colors.red(`Error fetching page data: ${s.message}\n${s.stack}`)),new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.")):s});return void 0!==s.template_id&&(this.#R=!0),this.internalPageName=s.internal_name,this.#$=this.localTemplateHTML,this.#$=this.#$.replace(/%%PAGE TITLE%%/g,s.name||"Local template"),this.logger.info(t.colors.green("Local page template fetched")),this.#j(!0),this.#$}let s=(await this.pageApi.getAll(this.#L(e)).then(e=>(this.logger.info(t.colors.green("Page list fetched")),e)).catch(async s=>{throw this.#j(!1),await this.pageApi.checkAuth(this.#L(e))?(this.logger.error(t.colors.red(`Error fetching page list: ${s.message}\n${s.stack}`)),new Error("Current user does not have access to page list")):s})).find(e=>e.name===Ie);return s||(this.logger.warn(t.colors.yellow("Creating dev page template...")),s=await this.pageApi.create({enabled:"Y",name:Ie,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#L(e)).then(e=>(this.logger.info(t.colors.green("Dev page created")),e)).catch(e=>{throw this.logger.error(t.colors.red(`Error creating dev page: ${e.message}`)),this.#j(!1),new Error(`Error when creating dev page.\n That can be caused by missing permissions or page with name "${Ie}" already exists`)})),await this.pageApi.getPageContent(s.internal_name,this.#L(e)).then(e=>(this.#$=e,e)).then(e=>(this.#j(!0),this.logger.info(t.colors.green("Page template fetched")),e)).catch(e=>{throw this.#j(!1),this.logger.error(t.colors.red(`Error fetching page template: ${e.message}`)),new Error("Error fetching page template")})}async getPageVariables(e,s){return void 0===this.appId&&(this.appId=e,this.templateLess=!1),this.#$=await this.getPageTemplate(s),await this.pageApi.get(e,this.#L(s)).then(e=>{const{tags:t="[]",name:s,template:r}=e;if(r&&t){const e=JSON.parse(t);return this.#S=e,this.#A=!0,this.#x=s,e}return this.#S=[],this.#A=!0,this.#x=s,[]}).catch(s=>{if(this.logger.error(t.colors.red(`Error fetching page variables: ${s.message}`)),404===s.response?.status)throw new Error(`Portal Page with id "${e}" not found on instance ${this.#k.getUri()}`);if(401===s.response?.status)throw this.logger.warn(`Unauthorized error: ${s}`),new Error(`Current user does not have access to page with id "${e}" on instance ${this.#k.getUri()}`);throw s})}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 s=this.appId,r=Date.now();this.logger.info(t.colors.cyan(`[page-variables] Fetching live variables for page ID ${s} (page_id lookup)`));const n=await this.pageVariableApi.getById(s,this.#L(e));return this.logger.info(t.colors.green(`[page-variables] Fetched ${n.length} live variable(s) for page ID ${s} in ${Date.now()-r}ms`)),n}async applyPageVariables(e,s=this.#b){if(void 0===this.appId)throw new Error("Cannot apply page variables before the page ID is known");const r=this.appId,n=Date.now();this.logger.info(t.colors.cyan(`[page-variables] Applying ${e.length} variable(s) to page ID ${r} (page_id lookup)`)),await this.pageVariableApi.updateById(r,e,this.#L(s)),this.logger.info(t.colors.green(`[page-variables] Applied variables to page ID ${r} in ${Date.now()-n}ms`))}async listPages(e=this.#b){return this.pageApi.getAll(this.#L(e))}async getPageVariablesFor(e,t=this.#b){return this.pageVariableApi.getById(e,this.#L(t))}get localPageVariables(){return this.templateLess||!this.#A?null:this.#S.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.#L(t),r=this.appId;try{return this.#I?await this.#O(r,s):await this.#C(r,s)}catch(e){this.#B(e,r)}}async#O(e,s){const r=await this.pageApi.get(e,s);return this.logger.info(t.colors.green("Page fetched")),void 0!==r.template_id&&(this.#R=!0),this.internalPageName=r.internal_name,r}async#C(e,t){return await this.pageApi.get(e,t)}#B(e,s){if(he(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 "${s}" not found on instance ${this.#k.getUri()}`);throw 401===e.response?.status&&this.logger.error(t.colors.red(`Current user does not have access to page with id "${s}" 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.#M())s=s.replace(e,()=>t);if(t){return new(a.getJSDOM())(s).serialize()}const{before:r,after:n}=this.#D();return r+s+n}#M(){return this.#E?.vars!==this.#S&&(this.#E={vars:this.#S,replacements:this.#S.map(({name:e,value:t})=>({regExp:new RegExp(`\\[${this.#F(e)}\\]`,"g"),value:t}))}),this.#E.replacements}#D(){const e=this.#$,t=this.#x;if(this.#T?.template===e&&this.#T.title===t)return this.#T;const s=new(a.getJSDOM())(e),{document:r}=s.window,n="%%PLACEHOLDER%%",i=r.createElement("div");i.innerHTML=n;const o=r.querySelector(".main-side");if(o){const e=o.querySelectorAll("script");e.length?o.insertBefore(i,e.item(e.length-1)):o.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.#T={template:e,title:t,before:d.slice(0,u.index),after:d.slice(u.index+u[0].length)},this.#T}async getAssets(){if(this.appId){if(this.templateLess)return await this.assetsApi.downloadPageAssets(this.appId,this.#b);{const e=await this.pageApi.get(this.appId,this.#b);if(this.#R){const t=await this.pageTemplateApi.get(e.template_id,this.#b);return await this.assetsApi.downloadTemplateAssets(t.id,this.#b)}if(e.template)return await this.assetsApi.downloadTemplateAssets(e.template,this.#b)}}}async updateAssets(e){if(this.appId){if(this.templateLess)return await this.assetsApi.uploadPageAssets(this.appId,e,this.#b);{const t=await this.pageApi.get(this.appId,this.#b);if(this.#R){const s=await this.pageTemplateApi.get(t.template_id,this.#b);return await this.assetsApi.uploadTemplateAssets(s.id,e,this.#b)}if(t.template)return await this.assetsApi.uploadTemplateAssets(t.template,e,this.#b)}}}async validateCredentials(e){try{const t=e||this.#b;return await this.get("/api/user",t,!0),{isValid:!0}}catch(e){const t=Ee(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,s,r=!1,n={}){const i=r?s:Object.assign({},this.#L(this.#b),s);try{return await this.#k.get(e,{headers:i})}catch(e){if("UNKNOWN_ERROR"!==Ee(e).code){const s=Ee(e);throw n.quiet||(this.logger.error(t.colors.red(`API request failed: ${s.userFriendlyMessage}`)),function(e,s,r){const n=Ee(s),i=`[${r}] `;e.error(t.colors.red(`${i}${n.userFriendlyMessage}`)),e.error(t.colors.red(`Status: ${n.status} (${n.code})`)),e.error(t.colors.red(`Details: ${n.message}`)),n.suggestions.length>0&&(e.info(t.colors.yellow("Suggestions:")),n.suggestions.forEach((s,r)=>{e.info(t.colors.yellow(` ${r+1}. ${s}`))}))}(this.logger,e,"API Request")),e.tokenErrorInfo=s,e}throw e}}},exports.PP_DEV_HMR_WS_PATH="/@pp-dev-hmr",exports.RequestStore=class{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-=Ss(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 y.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=Ss(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(As(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(As(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}},exports.USERS_API_PATH=ds,exports.VARIABLES_EDITOR_PATH=rs,exports.createInternalServer=function({allowedHosts:e=[]}={}){const s=M();return s.use(t.createOriginGuard(e)),s.use(M.json({limit:$s})),s.use(M.urlencoded({extended:!0})),s.use(xs),s},exports.createRequestCaptureMiddleware=function(e,t=10485760,s=Ce){return(r,n,i)=>{const a=r.url||"/",o=a.split("?")[0];if(Os.some(e=>a.startsWith(e))||Cs.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 x=!1;n.write=(e,...t)=>(b(e,k(t)),w(e,...t)),n.end=(t,...s)=>("function"!=typeof t&&b(t,k(s)),function(){if(x)return;x=!0;const t=Fs(a,"string"==typeof r.headers["content-type"]?r.headers["content-type"]:void 0,!h&&u.length>0?Buffer.concat(u):null),s=!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:Ps(r.headers),requestBody:t,requestBodyTruncated:h,responseHeaders:Rs(n.getHeaders()),responseBody:s,responseBodyTruncated:y})}(),v(t,...s)),i()}},exports.createUserHostGuard=function(e=Ce){return(t,s,r)=>{const n=e.resolve(t),i=Fe(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",`${Oe(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.`))}},exports.endUnhandledInternalRequest=function(e,t){t?ks(e,t):e.headersSent||e.writableEnded||(e.statusCode=404,e.setHeader("content-type","application/json"),e.end(JSON.stringify({error:"Not found"})))},exports.extractZipSafe=It,exports.getIndexPageRegExp=function(e){return new RegExp(`^((${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`);var t},exports.getMiAPIOptions=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}},exports.getProxyIgnore=function(e){return["/@vite","/@metricinsights","/@",e.endsWith("/")?e.slice(0,-1):e]},exports.initLoadPPData=function(e,s,r){const{templateLess:n=!1,miHudLess:i=!1,appId:a,base:o,appBase:c,v7Features:l}=r,d=t.createLogger();if(n&&i&&void 0===a)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");return async(r,u,p)=>{try{const h=!(n&&i),g=se(r.url??""),m=e.test(g),f=!m&&!g.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)}(g,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")}(r),y=t.authProvider.getState();if(!y.isAuthenticated&&!y.isRedirected&&r.url?.startsWith("/home")&&!r.url?.startsWith($t)){let e;d.info(t.colors.blue("Trying to authenticate and redirect to base"));const c=t=>{e=t};try{if(h?await At(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,c,d):await St(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,c,d),u.headersSent||u.writableEnded)return;return e?p(e):(t.authProvider.setRedirected(!0),d.info(t.colors.blue("Successfully authenticated. Redirecting to base")),te(u,o??"/",302))}catch(e){if(u.headersSent||u.writableEnded)return;return p()}}if(!m&&!f)return p();if(!h){return await St(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,p,d)}return await At(s,{templateLess:n,miHudLess:i,appId:a,redirectUrl:l&&o?`${o}`:`${$t}${encodeURIComponent("/")}`},r,u,p,d)}catch(e){return d.error(t.colors.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),kt(),p(e)}}},exports.initPPRedirect=function(e,r){const n=(e=(e=e.startsWith("/")?e:`/${e}`).endsWith("/")?e:`${e}/`).endsWith("/")?e.slice(0,-1):e,i=t.createLogger();return(a,o,c)=>{const l=new s.URL(a.url??"","http://localhost"),{pathname:d,search:u}=l,p=["/",n];if(r&&(p.push(`${t.PATH_TEMPLATE_PREFIX}/${r}`),p.push(`${t.PATH_TEMPLATE_LOCAL_PREFIX}/${r}`)),p.includes(d)){const s=`${e}${u}`;return i.info(t.colors.yellow(`Redirecting to: ${s}`)),te(o,s,302)}c()}},exports.initProxy=function(e){const{rewritePath:r=/^\/(?!p[tl]).*/i,baseURL:n="",disableSSLValidation:i=!1,miAPI:a,templateName:o,users:c=Ce}=e;if(!n)throw new Error("Base url is required");const l=function(e){try{return new URL(e).host}catch{return e.replace(Ve,"$2")}}(n),d=n.replace(Ve,"$1$2"),u=import("file-type"),p=t.createLogger(),h=e.sessionUsers??new _e(c,function(e){return async t=>(await Ue(e,{Cookie:`${ve}=${t}`})).miUser}(a));return m.createProxyMiddleware({selfHandleResponse:!0,pathFilter:(t,s)=>!(e.proxyIgnore||[]).some(e=>"string"==typeof e?t.startsWith(e):"function"!=typeof e.test||e.test(t))&&("string"==typeof r?t.startsWith(r):Array.isArray(r)?r.some(e=>t.startsWith(e)):"function"==typeof r.test&&r.test(t)),target:n,changeOrigin:!0,logger:{info:()=>{},warn:()=>{},error:()=>{}},secure:!i,headers:{host:l,origin:d},on:{proxyReq(e,r,i){const l=r.headers.host,d=e.getHeader("referer");l&&d&&"string"==typeof d&&e.setHeader("referer",d.replace(function(e){let t=Y.get(e);return t||(t=new RegExp(`^https?://${K(e)}(?=[/?#]|$)`,"i"),Y.set(e,t)),t}(l),n));const u=c.resolve(r);let h;u?.user?h=u.user.token:u&&(h=a.personalAccessToken),h?(e.setHeader("Authorization",`Bearer ${h}`),Ze.set(r,h)):"session"===u?.user?.kind&&e.removeHeader("Authorization"),u?.user&&e.removeHeader("Token");const g="session"===u?.user?.kind?u.user:void 0;let m;if(g&&Fe(r.headers.host)!==g.name){m=g.session;const t=m?(f=r.headers.cookie,y=m,[...Me(f),`${ve}=${y}`].join("; ")):function(e){const t=Me(e);return t.length?t.join("; "):void 0}(r.headers.cookie);t?e.setHeader("cookie",t):e.removeHeader("cookie")}var f,y;Ge.set(r,{user:u?.user,sentSession:m}),e.removeHeader("if-none-match"),e.removeHeader("if-modified-since");const w=r.url??"/",v=function(e,t,r,n){if(!t||!r||!n||r===n)return e;try{const t=new s.URL(e,"http://localhost"),i=t.pathname.match(/^\/data\/page\/([^/]+)(\/.*)?$/);if(!i)return e;let a;try{a=decodeURIComponent(i[1])}catch{a=i[1]}if(a!==r)return e;return`/data/page/${n}${i[2]??""}`+t.search+t.hash}catch{return e}}(w,a.v7Features,o,a.internalPageName);v!==w&&(r.url=v,e.path=v,console.info(`${t.colors.cyan("Rewrites data page to correct internal page name")}: ${t.colors.yellow(w)} ${t.colors.blue("→")} ${t.colors.green(v)}`)),p.info(`${t.colors.blue("Proxies request:")} ${t.colors.green(r.method)} ${r.url} -> ${t.colors.green(e.method)} ${e.protocol}//${e.host}${e.path}${u?.user?` ${t.colors.blue("as")} ${t.colors.yellow(u.user.name)}`:""}`);const{socket:b}=r,k=()=>{setTimeout(()=>{e.destroyed||e.destroy()},200)};return b.once("close",k),e.once("close",()=>b.off("close",k)),e},proxyRes:(e,s,r)=>{r.setHeader(qe,1),e.headers["set-cookie"]&&(e.headers["set-cookie"]=xe(e.headers["set-cookie"],ye(s))),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,s));const n=function(e,t){if(!Je.test(e.url??""))return;const s=Fe(e.headers.host);return void 0===s?void 0:t.get(s)}(s,c),i=Ge.get(s);if(n){e.resume();const a={"cache-control":"no-store"};i?.user===n&&(c.remove(n.name),p.info(`${t.colors.blue("Logged out user")} ${t.colors.yellow(n.name)}, back to the main host`),e.headers["set-cookie"]&&(a["set-cookie"]=e.headers["set-cookie"]));const o=s.headers["sec-fetch-mode"];return o&&"navigate"!==o?r.writeHead(204,a):r.writeHead(302,{...a,location:`${Oe(s)}/`}),void r.end()}const a=i?.user;let o=!0;if(a&&c.get(a.name)!==a)o=!1;else if(a){let t=!1;"session"===a.kind&&(t=h.isLeftBehindRequest(a,s,i?.sentSession),h.observe(a,s,e,i?.sentSession)),o=Fe(s.headers.host)===a.name&&!t}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,t)=>Buffer.from(ee(We,"/login",Q(l,s.headers.host??"",e.toString(t))),t);if(e.headers["content-type"]?.includes("text/event-stream")||e.headers["transfer-encoding"]?.includes("chunked")&&"no"===e.headers["x-accel-buffering"])return p.info(`${t.colors.blue("Start streaming for request:")} ${t.colors.green(s.method)} ${s.url}`),et(d)(e,s,r);const g=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!Xe(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&Qe(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 et("stream"===g?d:void 0)(e,s,r);const f=m.responseInterceptor(async(e,t,s,r)=>{r.setHeader(qe,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);ze.test(e.pathname)&&(r.includes("<html")||r.includes("<body")||r.includes("<head")||r.includes("html>"))&&!Fe(s.headers.host)&&(t+=`<script>(${Se.toString()})(${n=l,JSON.stringify(n).replace(/</g,"\\u003c")})<\/script>`)}catch{}const r=s.headers.host??"";return ee(We,"/login",Q(l,r,t))}var n});return f(e,s,r)},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))}}})},exports.initProxyCache=function(e){const{devServer:s,ttl:r=st,maxSize:n=rt,maxItems:i=nt,users:a=Ce}=e,o=t.createLogger();return n===rt&&i===nt||(at.maxSize=n,at.maxItems=i),s.cache=at,dt.has(a)||(dt.add(a),a.onRemove(e=>pt(e.name,"user removed")),a.onSessionChange(e=>pt(e.name,"MI session changed or ended"))),(e,s,n)=>{const i=a.resolve(e);if(!i)return n();s.once("finish",()=>{const t=s.hasHeader(qe)?ht(e,s,i.key):void 0;t&&pt(i.key,`${t} (${e.method} ${se(e.url??"")})`)});const c=i.user?.session,l=e.originalUrl||e.url||"",d="GET"===e.method?function(e,t,s){const r=e.split("?")[0];return tt.test(r)?r.includes("/auth/info.js")?"":t?`@${t}@${s}:${e}`:`${s}:${e}`:""}(l,i.key,e.headers.host??""):"";if(!d||!function(e,t){const{user:s}=t;return"session"!==s?.kind||!!s.session&&(Fe(e.headers.host)!==s.name||ke(e.headers.cookie,ve)===s.session)}(e,i))return n();const u=at.get(d);if(u)return o.info(`${t.colors.blue("Proxies request:")} ${t.colors.green(e.method)} ${l} -> ${t.colors.blue("Cache")} ${d}`),function(e,s){try{for(const[t,r]of Object.entries(s))null!=r&&e.setHeader(t,r)}catch(e){t.createLogger().warn(`Failed to set some response headers: ${e instanceof Error?e.message:String(e)}`)}}(s,u.headers),s.setHeader("X-PP-Cache","hit"),s.write(u.content),void s.end();const p=s.end,h=s.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(s,e)},v=()=>{"undecided"===f&&(s.hasHeader(qe)?!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>=it)}(s)?w():f="buffer":f="pass")};s.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>it&&w(),r&&process.nextTick(r),!0},s.end=function(e,n,l){if(v(),"pass"===f)return p.call(this,e,n,l);"function"==typeof e?(l=e,e=void 0):"function"==typeof n&&(l=n,n=void 0);const u=y(e,"string"==typeof n?n:void 0);let h;u&&g.push(u);try{h=gt(g);const e=Buffer.byteLength(h);if(200===s.statusCode&&e>0&&e<it&&function(e,t,s){return!e.user||s.get(e.key)===e.user&&e.user.session===t}(i,c,a)){const{"set-cookie":n,...i}=s.getHeaders(),a={headers:i,content:h,timestamp:Date.now(),size:e};at.put(d,a,r),o.info(`${t.colors.blue("[Cached]")} ${d} (${(e/1024).toFixed(1)}KB)`)}}catch(e){o.error(`Failed to cache response for ${d}: ${e}`),h=gt(g)}return p.call(this,h,l)},n()}},exports.initRewriteResponse=function(s,r,n={}){return async(i,a,o)=>{if(await s(i.url??"",i,a)){const s=t.createLogger();"GET"!==i.method&&"HEAD"!==i.method||!(i.headers.accept??"").includes("text/html")||delete i.headers["if-none-match"];const c=a.end;if("HEAD"===i.method)return a.end=function(e,t,s){const r=[e,t,s].find(e=>"function"==typeof e);return a.headersSent||a.removeHeader("content-length"),c.call(this,r),this},void o();s.info(`Rewrite response for ${i.url}`);const l=[],d=a.write,u=a.writeHead,p=a.flushHeaders;let h=null,g=!1;const m=()=>{g=!0,h&&!a.headersSent&&u.apply(a,h),h=null;for(const e of l.splice(0))d.call(a,e)},f=(e=!1)=>{if(g)return!0;if(!n.contentType)return!1;const t=a.getHeader("content-type");return!(void 0===t&&!e)&&(!n.contentType(void 0===t?"":String(t))&&(m(),!0))};a.flushHeaders=function(){f()&&p.call(this)},a.writeHead=function(e,...t){if(g)return u.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,h=void 0===s?[e]:[e,s],f(),this},a.write=function(e,t,s){if(f())return d.call(this,e,t,s);const r=G(e,Z(t));r&&l.push(r);const n="function"==typeof t?t:s;return"function"==typeof n&&process.nextTick(n),!0},a.end=function(t,n,o){if(f(!0))return c.call(this,t,n,o);"function"==typeof t&&(o=t,t=void 0);const d=G(t,Z(n));d&&l.push(d);const p="function"==typeof n?n:o,g=a.getHeader("content-encoding"),m=H(Buffer.concat(l),g),y=function(t,s){switch(s){case"gzip":return e.gzipSync(t);case"br":return e.brotliCompressSync(t);case"deflate":return e.deflateSync(t);default:return t}}(r(m,i,a),g);return void 0!==a.getHeader("content-length")&&(a.headersSent?s.warn(`Rewrite response for ${i.url}: headers already sent, Content-Length left as is`):a.setHeader("content-length",y.length)),a.headersSent||a.removeHeader("etag"),a.writeHead=u,h&&!a.headersSent&&u.apply(this,h),c.call(this,y,p),this}}o()}},exports.registerInspectorRoutes=function(e,t,s=10485760,r=D){const n=q.get(e);if(n)return n.store=t,void(n.captureLimit=s);const i={store:t,captureLimit:s};q.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,r=z(e.query.limit),n=z(e.query.offset),a=z(e.query.method),o=z(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:J(s.memoryUsage),maxMemoryFormatted:J(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=W(s.requestHeaders["content-type"]),n=W(s.responseHeaders["content-type"]),a=s.responseBody?function(e,t,s){const r=Array.isArray(t)?t.join(", "):String(t??"");try{return H(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})}),U(e,{path:V,name:"request-inspector",clientDir:r,values:()=>({captureLimit:String(i.captureLimit)})})},exports.removeStaleDevTypes=Pt,exports.resolveProxyCacheTtl=function(e){const t=Number(e);return!t||Number.isNaN(t)||t<0?6e5:t},exports.runMiddlewareChain=function(e,t,s,r){let n=0;const i=a=>{if(a)return void ks(s,a);if(n>=e.length)return void r();const o=e[n];n+=1;try{o(t,s,i)}catch(e){ks(s,e)}};i()},exports.runNextBuildProcess=Ft,exports.startSyncAndUsers=function(e){const{distService:s,miAPI:r,persistUsers:n,projectRoot:i,miUrl:a}=e,o=new Wt(e.server,{distService:s,miAPI:r});return function(e,s){const{miAPI:r,persistUsers:n,projectRoot:i,miUrl:a}=s,o=t.createLogger(),c=(e,t,s)=>{o.error(`${s} token validation error: ${t instanceof Error?t.message:String(t)}`);const r=Ee(t),n=t?.tokenErrorInfo;if(n)return bs(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 bs(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:s,tokenType:l}=e.body??{};if(Fe(e.headers.host))bs(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 s&&s)if(o.info(`Attempting to validate ${String(l)} token...`),"personal"===l){if(!await r.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${s}`},!0).then(e=>"number"==typeof e.data?.user?.user_id?(r.personalAccessToken=s,o.info(`Personal access token validated successfully for user ${e.data.user.user_id}`),e):(bs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"personal")))return;lt("logged in with a personal access token"),vs({persist:n,miAPI:r,projectRoot:i,miUrl:a}),te(t,"/",302)}else if("regular"===l){if(!await r.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:s},!0).then(s=>s.data?.users?.length?(r.personalAccessToken=void 0,o.info(`Regular token validated successfully for ${s.data.users.length} user(s)`),t.setHeader("set-cookie",xe(s.headers["set-cookie"],ye(e))??""),s):(bs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"regular")))return;lt("logged in with a token"),te(t,"/",302)}else bs(t,400,"Invalid tokenType",'tokenType must be "personal" or "regular".',"INVALID_TOKEN_TYPE");else bs(t,400,"Token is required")})}(e.internalServer,{miAPI:r,persistUsers:n,projectRoot:i,miUrl:a}),ls(e.internalServer,{distService:s,miAPI:r}),function(e,s){const r=us.get(e);if(r)return void(r.deps=s);const n={deps:s};us.set(e,n);const i=t.createLogger(),a=()=>n.deps.users??Ce;e.get(ds,(e,t)=>{const s=a();t.json({available:Boolean(n.deps.miAPI.personalAccessToken),users:s.list().map(t=>ps(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${ds}/default`,(e,s)=>{const r=a(),n=(e.body??{}).name;if(null===n||"string"==typeof n)if(null===n||r.get(n)){try{r.setDefaultUser(n??void 0)}catch(e){return void hs(s,409,"NOT_LOGGED_IN",e instanceof Error?e.message:String(e))}i.info(`${t.colors.blue("Default user:")} ${t.colors.yellow(n??"the original user")}`),s.json({defaultUser:n})}else hs(s,404,"NOT_FOUND",`There is no user named "${n}"`);else hs(s,400,"INVALID_NAME","name must be a user name or null")}),e.post(ds,async(e,s)=>{const{miAPI:r}=n.deps,o=a(),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 hs(s,400,"INVALID_KIND",'kind must be "token" or "session"');if(!r.personalAccessToken)return void hs(s,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=Le(l);if(p)return void hs(s,400,"INVALID_NAME",p);if(o.get(l))return void hs(s,409,"NAME_TAKEN",`A user named "${l}" already exists`);if("session"===u){const r=o.add({name:l,kind:"session"});return i.info(`${t.colors.blue("Added user")} ${t.colors.yellow(r.name)}: log in at ${Oe(e,r.name)}/login`),void s.status(201).json({user:ps(r,e)})}if(!d)return void hs(s,400,"TOKEN_REQUIRED","The API token is required");const h=o.context,g=await He(r,d);if(o.context!==h||n.deps.miAPI!==r||a()!==o)return void hs(s,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!g.ok)return void(g.rejected?hs(s,400,"INVALID_TOKEN",g.message):hs(s,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 hs(s,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${t.colors.blue("Added user")} ${t.colors.yellow(f.name)} (MI user ${m.id}${m.username?`, ${m.username}`:""}) at ${Oe(e,f.name)}`),s.status(201).json({user:ps(f,e)})}),e.patch(`${ds}/:name`,async(e,s)=>{const{miAPI:r}=n.deps,o=a(),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 hs(s,404,"NOT_FOUND",`There is no user named "${c}"`);if("token"!==l.kind)return void hs(s,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=Le(u);if(h)return void hs(s,400,"INVALID_NAME",h);if(u!==c&&o.get(u))return void hs(s,409,"NAME_TAKEN",`A user named "${u}" already exists`);let g,m={...l,name:u};if(p&&p!==l.token){const e=o.context,t=await He(r,p);if(o.context!==e||n.deps.miAPI!==r||a()!==o)return void hs(s,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!t.ok)return void(t.rejected?hs(s,400,"INVALID_TOKEN",t.message):hs(s,502,"MI_UNAVAILABLE",t.message));const{state:i,...c}=m;m={...c,token:p,miUser:t.miUser}}if(o.get(c)===l)if(u!==c||m.token!==l.token){try{g=o.replace(c,m)}catch(e){return void hs(s,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}i.info(`${t.colors.blue("Edited user")} ${t.colors.yellow(c)}${u!==c?` → ${t.colors.yellow(u)}`:""}${g.token!==l.token?" (new API token)":""}`),s.json({user:ps(g,e)})}else s.json({user:ps(l,e)});else hs(s,409,"USER_CHANGED",`The user "${c}" changed meanwhile; edit it again`)}),e.delete(`${ds}/:name`,(e,s)=>{const r=String(e.params.name);a().remove(r)?(i.info(`${t.colors.blue("Removed user")} ${t.colors.yellow(r)}`),s.status(204).end()):hs(s,404,"NOT_FOUND",`There is no user named "${r}"`)})}(e.internalServer,{miAPI:r}),vs({persist:n,miAPI:r,projectRoot:i,miUrl:a}),o},exports.urlReplacer=Q,exports.zipDirectoryToBuffer=Tt;
2
- //# sourceMappingURL=request-capture.middleware-C9SbJkfk.js.map