@metricinsights/pp-dev 1.5.0-beta.30 → 1.5.0-beta.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/cjs/auth.provider-fI0tFsf5.js +2 -0
- package/dist/cjs/auth.provider-fI0tFsf5.js.map +1 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/cli.js.map +1 -1
- package/dist/cjs/{index-D9zJqX2X.js → index-Ty1d2YCg.js} +2 -2
- package/dist/cjs/{index-D9zJqX2X.js.map → index-Ty1d2YCg.js.map} +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/{migrate-CuzJuHC1.js → migrate-Gi9k9cLw.js} +2 -2
- package/dist/cjs/{migrate-CuzJuHC1.js.map → migrate-Gi9k9cLw.js.map} +1 -1
- package/dist/cjs/plugin.js +1 -1
- package/dist/cjs/{request-capture.middleware-Bihrs8O-.js → request-capture.middleware-6DhFLyIz.js} +2 -2
- package/dist/cjs/request-capture.middleware-6DhFLyIz.js.map +1 -0
- package/dist/cjs/{version-manifest-5tqQXsyA.js → version-manifest-CVBuIKBS.js} +2 -2
- package/dist/cjs/{version-manifest-5tqQXsyA.js.map → version-manifest-CVBuIKBS.js.map} +1 -1
- package/dist/cjs/{version-plugin-JOQRBtAn.js → version-plugin-DBdqn2Rn.js} +2 -2
- package/dist/cjs/{version-plugin-JOQRBtAn.js.map → version-plugin-DBdqn2Rn.js.map} +1 -1
- package/dist/client/client.js +9 -1
- package/dist/client/client.js.map +1 -1
- package/dist/client/request-inspector.js +33 -11
- package/dist/client/request-inspector.js.map +1 -1
- package/dist/esm/{auth.provider-CMlTFLKr.js → auth.provider-DDUsu1H1.js} +2 -2
- package/dist/esm/auth.provider-DDUsu1H1.js.map +1 -0
- package/dist/esm/cli.js +1 -1
- package/dist/esm/cli.js.map +1 -1
- package/dist/esm/{index-B4F5_U6S.js → index-tD-QICGk.js} +2 -2
- package/dist/esm/{index-B4F5_U6S.js.map → index-tD-QICGk.js.map} +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/{migrate-r4PvE5UL.js → migrate-CCBRuVfj.js} +2 -2
- package/dist/esm/{migrate-r4PvE5UL.js.map → migrate-CCBRuVfj.js.map} +1 -1
- package/dist/esm/plugin.js +1 -1
- package/dist/esm/request-capture.middleware-VElwjU1W.js +2 -0
- package/dist/esm/request-capture.middleware-VElwjU1W.js.map +1 -0
- package/dist/esm/{version-manifest-BG-RUMD6.js → version-manifest-CyzmnFOe.js} +2 -2
- package/dist/esm/{version-manifest-BG-RUMD6.js.map → version-manifest-CyzmnFOe.js.map} +1 -1
- package/dist/esm/{version-plugin-BtTT_xRU.js → version-plugin-6rxIgQ-I.js} +2 -2
- package/dist/esm/{version-plugin-BtTT_xRU.js.map → version-plugin-6rxIgQ-I.js.map} +1 -1
- package/dist/types/index.d.ts +0 -1
- package/package.json +1 -1
- package/dist/cjs/auth.provider-BT1sgf1x.js +0 -2
- package/dist/cjs/auth.provider-BT1sgf1x.js.map +0 -1
- package/dist/cjs/request-capture.middleware-Bihrs8O-.js.map +0 -1
- package/dist/esm/auth.provider-CMlTFLKr.js.map +0 -1
- package/dist/esm/request-capture.middleware-CYtDXIxP.js +0 -2
- package/dist/esm/request-capture.middleware-CYtDXIxP.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{execSync as e}from"child_process";import{l as t,m as n,V as s,o as i,P as r,p as o,v as a,n as c,j as p,d as l,f as u,g as d,c as m,a as f,e as v,q as g,s as h}from"./auth.provider-CMlTFLKr.js";import{createRequire as _}from"node:module";import{normalizePath as j,loadEnv as y}from"vite";import*as b from"fs";import{readdirSync as $,readFileSync as E,writeFileSync as P,unlinkSync as w}from"fs";import*as I from"path";import D from"path";import{pathToFileURL as T}from"url";import"./helpers.js";import O from"ejs";const R=I.dirname(n),S=I.join(R,"index.html");let x=null;function N(e){return{css:I.posix.join(e,t,"client/client.css"),js:I.posix.join(e,t,"client/client.js")}}function F(e){return function(){if(x)return x;const e=b.readFileSync(S,{encoding:"utf8"});return x=O.compile(e,{openDelimiter:"{",closeDelimiter:"}",async:!1,rmWhitespace:!0,compileDebug:!1}),x}()({PACKAGE_NAME:t,VERSION:s,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})}function L(e,t,n){if(!/<\/?(html|body|head)\b/i.test(e))return e;const{css:s,js:i}=N(t),r=F(n),o=`<link rel="stylesheet" href="${s}">`,a=`${r}${`<script type="module" src="${i}"><\/script>`}`;let c=e,p=!1;if(/<\/head>/i.test(c)&&(c=c.replace(/<\/head>/i,e=>`${o}${e}`),p=!0),/<body[^>]*>/i.test(c)){const e=p?"":o;c=c.replace(/<body[^>]*>/i,t=>`${t}${e}${a}`)}else c=`${p?"":o}${c}${a}`;return c}const C={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function U(e){const n=I.posix.join(e,t,"client")+"/",s=new Set(["client.js","client.css","client.js.map","client.css.map"]);return(e,t,i)=>{const r=(e.url??"").split("?")[0];if(!r.startsWith(n))return void i();const o=r.slice(n.length);if(!s.has(o))return void i();const a=I.join(R,o);b.readFile(a,(e,n)=>{e?i():(t.statusCode=200,t.setHeader("Content-Type",C[I.extname(o)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(n))})}}const Z=j(I.join(i,"dist/client")),A=new RegExp(`^\\/?${t}\\/client\\/(.*)$`);const M=(e,t)=>` * ${t}`;function V(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,M)}\n */`}async function H(){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 k=()=>_(import.meta.url);async function B(){try{return k().resolve("next"),!0}catch{return!1}}async function z(){try{const e=k()("next/package.json");return"string"==typeof e.version?e.version:null}catch{return null}}let W=new Set;function q(e="development",t=process.cwd()){for(const e of W)delete process.env[e];const n=new Set(Object.keys(process.env).filter(e=>e.startsWith("MI_"))),s=y(e,t,"MI_");for(const[e,t]of Object.entries(s))process.env[e]=t;return W=new Set(Object.keys(s).filter(e=>!n.has(e))),s}const G=Object.freeze({__proto__:null,loadPPDevEnv:q}),J=new Map,K=new Map;function Y(e=process.cwd()){const t=Date.now(),n=D.resolve(e),s=K.get(n);if(s&&t-s.timestamp<6e4)return s.data;try{const e=JSON.parse(E(D.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return K.set(n,{data:e,timestamp:t}),e}catch{const e={};return K.set(n,{data:e,timestamp:t}),e}}let Q=null;const X="__pp_dev_injected_dirname",ee="__pp_dev_injected_filename",te="__pp_dev_injected_import_meta_url",ne={__dirname:X,__filename:ee,"import.meta.url":te,"import.meta.dirname":X,"import.meta.filename":ee},se={name:"pp-dev:config-module-location",setup(e){e.onLoad({filter:/\.([cm]?[jt]s|[jt]sx)$/},e=>{const t=E(e.path,"utf-8").replace(/^#![^\r\n]*/,"");return{contents:`const ${X} = ${JSON.stringify(D.dirname(e.path))};const ${ee} = ${JSON.stringify(e.path)};const ${te} = ${JSON.stringify(T(e.path).href)};`+t,loader:e.path.endsWith(".tsx")?"tsx":e.path.endsWith(".jsx")?"jsx":/ts$/.test(e.path)?"ts":"js"}})}};async function ie(e,t){const n=`bundled:${e}`,s=J.get(n);if(s&&Date.now()-s.timestamp<3e4)return s.data;let i=!1;if(/\.m[jt]s$/.test(e))i=!0;else if(/\.c[jt]s$/.test(e))i=!1;else{const e=Y(t);i=!!e&&"module"===e.type}const r=await async function(){return Q||(Q=await(import("esbuild"))),Q}(),o=await r.build({absWorkingDir:t,entryPoints:[e],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:i?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0,plugins:[se],define:ne,...i?{banner:{js:"import { createRequire as __ppDevCreateRequire } from 'node:module';const require = __ppDevCreateRequire(import.meta.url);"}}:{}}),{text:a}=o.outputFiles[0],c=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.${i?"mjs":"cjs"}`,p=D.resolve(t,c),l=T(p).toString();P(p,a);let u={};try{const t=(await(import(l))).default;u=t?.default||t,J.set(n,{data:u,timestamp:Date.now(),filePath:e})}finally{try{w(p)}catch{}}return u}async function re(e){const t=`json:${e}`,n=J.get(t);if(n&&Date.now()-n.timestamp<3e4)return n.data;const s=JSON.parse(E(e,{encoding:"utf-8"}));return J.set(t,{data:s,timestamp:Date.now(),filePath:e}),s}const oe=new Map;function ae(e=process.cwd()){return Y(e)}async function ce(e=process.cwd()){const t=D.resolve(e),n=function(e){const t=Date.now(),n=oe.get(e);if(n&&t-n.timestamp<1e4)return n.files;const s=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,i=$(e,{withFileTypes:!0}).filter(e=>e.isFile()&&s.test(e.name)).map(e=>e.name);return oe.set(e,{files:i,timestamp:t}),i}(t);let s={},i=!1;const o=await async function(e,t,n){for(const s of t)if(e.includes(s)){const e=D.resolve(n,s);if(/\.[cm]?[jt]s$/i.test(s))return await ie(e,n);if(s.endsWith(".json"))return await re(e)}return null}(n,r,t);o&&(s=o,i=!0);const a=Y(t)["pp-dev"];return i||!a||"object"!=typeof a||Array.isArray(a)||(s=a),s}const pe=Object.freeze({__proto__:null,clearConfigCache:function(){J.clear(),K.clear(),oe.clear()},getConfig:ce,getPkg:ae});function le(e){if(void 0!==e)return"1"===e||"true"===e.toLowerCase()||"0"!==e&&"false"!==e.toLowerCase()&&void 0}function ue(e){return{distZipEnabled:e.distZip??le(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??le(process.env.PP_DEV_VERSION_MANIFEST),versionFileTemplate:e.versionFileTemplate??process.env.PP_DEV_VERSION_FILE_TEMPLATE}}function de(e,t,n){if(!1===t.distZipEnabled)return!1;if(!0!==t.distZipEnabled&&void 0===t.distZipDir&&void 0===t.distZipFilename)return!1!==e&&{...e,outFileName:o(e.outFileName,"ZIP output file name")};const s=!1===e?{outFileName:n,outDir:"dist-zip"}:e,i=t.distZipFilename??s.outFileName;return{...s,...void 0!==t.distZipDir?{outDir:t.distZipDir}:{},outFileName:o(i,"ZIP output file name")}}function me(e,t){if(!1===t.versionManifestEnabled)return!1;if(!0!==t.versionManifestEnabled&&void 0===t.versionFileTemplate)return!1!==e&&void 0!==e.versionFileTemplate?{...e,versionFileTemplate:o(e.versionFileTemplate,"VERSION file name template")}:e;const n=!1===e?{enabled:!0}:e,s=t.versionFileTemplate??n.versionFileTemplate,i=void 0!==s?o(s,"VERSION file name template"):void 0;return{...n,enabled:!0,...void 0!==i?{versionFileTemplate:i}:{}}}const fe=new Set(["mi","app","proxy","build","sync","inspector","devPanel","users","server"]);function ve(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 s=process.env.GITHUB_REPOSITORY;if("string"==typeof s&&s.trim()){return`${(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${s.replace(/^\/+/,"")}`}const i=process.env.CI_PROJECT_PATH;if("string"==typeof i&&i.trim()){return`${(process.env.CI_SERVER_URL||"https://gitlab.com").replace(/\/+$/,"")}/${i.replace(/^\/+/,"")}`}const r=process.env.BITBUCKET_REPO_FULL_NAME;if("string"==typeof r&&r.trim())return`https://bitbucket.org/${r.replace(/^\/+/,"")}`;const o=process.env.TRAVIS_REPO_SLUG;if("string"==typeof o&&o.trim())return`https://github.com/${o.replace(/^\/+/,"")}`;try{const t=e("git config --get remote.origin.url",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t)return t}catch{}}async function ge(e,s={}){const i=s.root??process.cwd();q(s.mode,i);const r=ae(i),o=await ce(i);a(o,r.name);const d=c(o,r.name),{templateName:m}=d;e&&(d.distZip=de(d.distZip,e,p(m)),d.versionPlugin=me(d.versionPlugin,e));const{default:f}=await(import("./plugin.js")),v=[f(d),{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${t}/client`),e),resolveId(e){const t=e.match(A);if(t){const e=j(I.join(Z,t[1]));return e.startsWith(`${Z}/`)?{id:e}:null}},transformIndexHtml:async(e,t)=>{const n=N(t.server?.config.base||""),s={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:n.css}}]},{templateLess:i=!1,...r}=t.server?.config.clientInjectionPlugin||{};return s.tags.push({tag:"div",injectTo:"body-prepend",children:F({templateLess:i,...r})}),s.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:n.js,type:"module"}}),s},configureServer(e){const t=j(I.resolve(e.config.root,I.dirname(n)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(t)}}],{outDir:g,distZip:h,versionPlugin:_,imageOptimizer:y,templateLess:b,integrateMiTopBar:$,allowedHosts:E}=d;if($&&v.push(function(e){return{name:"mi-topbar-plugin",transformIndexHtml(){const t=[];return(!0===e||"object"==typeof e&&!0===e.addRootElement)&&t.push({tag:"div",injectTo:"body-prepend",attrs:{id:"mi-react-root"}}),(!0===e||"object"==typeof e&&!0===e.addSharedComponentsScripts)&&t.push({tag:"script",injectTo:"head-prepend",attrs:{src:"/auth/info.js"}},{tag:"script",injectTo:"head-prepend",attrs:{src:"/js/main.js",defer:"defer"}},{tag:"link",injectTo:"head-prepend",attrs:{href:"/css/main.css",rel:"stylesheet"}}),t}}}($)),y){const{ViteImageOptimizer:e}=await(import("vite-plugin-image-optimizer"));v.push(e("object"==typeof y?y:void 0))}if(_){const{versionPlugin:e}=await(import("./version-plugin-BtTT_xRU.js"));v.push(e({outDir:g,packageVersion:r.version??"0.0.0",packageRepositoryUrl:ve(r.repository),..."object"==typeof _?_:{}}))}if(h){const{default:e}=await(import("vite-plugin-zip-pack"));v.push({...e("object"==typeof h?h:{outFileName:p(m)}),enforce:"post"})}return{base:b?`${l}/${m}`:`${u}/${m}`,server:{port:3e3,...!0===E||E.length>0?{allowedHosts:E}:{}},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:V}},outDir:g},css:{modules:{localsConvention:"dashes"}},ppDevConfig:d,plugins:v}}function he(e){return e?.ppDev||{}}function _e(e,t){return async(n,s={})=>{try{const{constants:i}=await H(),{PHASE_DEVELOPMENT_SERVER:r,PHASE_PRODUCTION_BUILD:o}=i;n!==o||process.env[d]||m().warn(f.yellow('⚠ Building with plain `next build`. Use `pp-dev next-build` instead to get VERSION/BUILD-MANIFEST/zip build output in the same format as `pp-dev build` (see the "Next.js Build" section in the pp-dev README).'));const p=await ce(),_=ae().name,j="function"==typeof e?await e(n,s):e,y=function(...e){const t={},n=t;for(const t of e)if(t)for(const[e,s]of Object.entries(t))void 0!==s&&(fe.has(e)&&s&&"object"==typeof s&&!Array.isArray(s)?n[e]={...n[e]??{},...s}:n[e]=s);return t}(p,he(j),t);a(y,_);const b=c(y,_),{templateLess:$,v7Features:E}=b,P=n===r,w=function(e,t,n,s){return n?s?t?`${l}/${e}`:`${v}/${e}`:t?`${l}/${e}`:`${u}/${e}`:`${l}/${e}`}(b.templateName,$,P,E),I={basePath:w,trailingSlash:!!P||void 0};if(!$){const e=P&&E?v:u;I.assetPrefix=`${e}/${b.templateName}`}const D=Object.assign({},I,j),T=g(b.allowedHosts);P&&T.length>0&&(D.allowedDevOrigins=[...D.allowedDevOrigins??[],...T]);const O=process.env[h];return n===o&&O&&(D.distDir=O),Object.defineProperty(D,"ppDev",{value:y,enumerable:!1,configurable:!0}),Object.defineProperty(D,"ppDevWrapped",{value:!0,enumerable:!1,configurable:!0}),D}catch(e){throw m().error("Error in withPPDev:",{error:e instanceof Error?e:new Error(String(e))}),e}}}export{de as a,me as b,U as c,z as d,he as e,B as f,ge as g,G as h,L as i,pe as j,q as l,ue as r,H as s,_e as w};
|
|
2
|
-
//# sourceMappingURL=index-
|
|
1
|
+
import{execSync as e}from"child_process";import{l as t,m as n,V as s,o as i,P as r,p as o,v as a,n as c,j as p,d as l,f as u,g as d,c as m,a as f,e as v,q as g,s as h}from"./auth.provider-DDUsu1H1.js";import{createRequire as _}from"node:module";import{normalizePath as j,loadEnv as y}from"vite";import*as b from"fs";import{readdirSync as $,readFileSync as E,writeFileSync as P,unlinkSync as w}from"fs";import*as I from"path";import D from"path";import{pathToFileURL as T}from"url";import"./helpers.js";import O from"ejs";const R=I.dirname(n),S=I.join(R,"index.html");let x=null;function N(e){return{css:I.posix.join(e,t,"client/client.css"),js:I.posix.join(e,t,"client/client.js")}}function F(e){return function(){if(x)return x;const e=b.readFileSync(S,{encoding:"utf8"});return x=O.compile(e,{openDelimiter:"{",closeDelimiter:"}",async:!1,rmWhitespace:!0,compileDebug:!1}),x}()({PACKAGE_NAME:t,VERSION:s,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})}function L(e,t,n){if(!/<\/?(html|body|head)\b/i.test(e))return e;const{css:s,js:i}=N(t),r=F(n),o=`<link rel="stylesheet" href="${s}">`,a=`${r}${`<script type="module" src="${i}"><\/script>`}`;let c=e,p=!1;if(/<\/head>/i.test(c)&&(c=c.replace(/<\/head>/i,e=>`${o}${e}`),p=!0),/<body[^>]*>/i.test(c)){const e=p?"":o;c=c.replace(/<body[^>]*>/i,t=>`${t}${e}${a}`)}else c=`${p?"":o}${c}${a}`;return c}const C={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function U(e){const n=I.posix.join(e,t,"client")+"/",s=new Set(["client.js","client.css","client.js.map","client.css.map"]);return(e,t,i)=>{const r=(e.url??"").split("?")[0];if(!r.startsWith(n))return void i();const o=r.slice(n.length);if(!s.has(o))return void i();const a=I.join(R,o);b.readFile(a,(e,n)=>{e?i():(t.statusCode=200,t.setHeader("Content-Type",C[I.extname(o)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(n))})}}const Z=j(I.join(i,"dist/client")),A=new RegExp(`^\\/?${t}\\/client\\/(.*)$`);const M=(e,t)=>` * ${t}`;function V(e){return`/*!\n${"***** DO NOT EDIT THIS CODE! *****\n***** ------- *****".replace(/^(.*)$/gm,M)}\n */`}async function H(){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 k=()=>_(import.meta.url);async function B(){try{return k().resolve("next"),!0}catch{return!1}}async function z(){try{const e=k()("next/package.json");return"string"==typeof e.version?e.version:null}catch{return null}}let W=new Set;function q(e="development",t=process.cwd()){for(const e of W)delete process.env[e];const n=new Set(Object.keys(process.env).filter(e=>e.startsWith("MI_"))),s=y(e,t,"MI_");for(const[e,t]of Object.entries(s))process.env[e]=t;return W=new Set(Object.keys(s).filter(e=>!n.has(e))),s}const G=Object.freeze({__proto__:null,loadPPDevEnv:q}),J=new Map,K=new Map;function Y(e=process.cwd()){const t=Date.now(),n=D.resolve(e),s=K.get(n);if(s&&t-s.timestamp<6e4)return s.data;try{const e=JSON.parse(E(D.resolve(n,"package.json"),{encoding:"utf-8",flag:"r"}));return K.set(n,{data:e,timestamp:t}),e}catch{const e={};return K.set(n,{data:e,timestamp:t}),e}}let Q=null;const X="__pp_dev_injected_dirname",ee="__pp_dev_injected_filename",te="__pp_dev_injected_import_meta_url",ne={__dirname:X,__filename:ee,"import.meta.url":te,"import.meta.dirname":X,"import.meta.filename":ee},se={name:"pp-dev:config-module-location",setup(e){e.onLoad({filter:/\.([cm]?[jt]s|[jt]sx)$/},e=>{const t=E(e.path,"utf-8").replace(/^#![^\r\n]*/,"");return{contents:`const ${X} = ${JSON.stringify(D.dirname(e.path))};const ${ee} = ${JSON.stringify(e.path)};const ${te} = ${JSON.stringify(T(e.path).href)};`+t,loader:e.path.endsWith(".tsx")?"tsx":e.path.endsWith(".jsx")?"jsx":/ts$/.test(e.path)?"ts":"js"}})}};async function ie(e,t){const n=`bundled:${e}`,s=J.get(n);if(s&&Date.now()-s.timestamp<3e4)return s.data;let i=!1;if(/\.m[jt]s$/.test(e))i=!0;else if(/\.c[jt]s$/.test(e))i=!1;else{const e=Y(t);i=!!e&&"module"===e.type}const r=await async function(){return Q||(Q=await(import("esbuild"))),Q}(),o=await r.build({absWorkingDir:t,entryPoints:[e],outfile:"out.js",write:!1,target:"node24",platform:"node",bundle:!0,packages:"external",format:i?"esm":"cjs",mainFields:["main"],sourcemap:"inline",metafile:!0,plugins:[se],define:ne,...i?{banner:{js:"import { createRequire as __ppDevCreateRequire } from 'node:module';const require = __ppDevCreateRequire(import.meta.url);"}}:{}}),{text:a}=o.outputFiles[0],c=`${`pp-config.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.${i?"mjs":"cjs"}`,p=D.resolve(t,c),l=T(p).toString();P(p,a);let u={};try{const t=(await(import(l))).default;u=t?.default||t,J.set(n,{data:u,timestamp:Date.now(),filePath:e})}finally{try{w(p)}catch{}}return u}async function re(e){const t=`json:${e}`,n=J.get(t);if(n&&Date.now()-n.timestamp<3e4)return n.data;const s=JSON.parse(E(e,{encoding:"utf-8"}));return J.set(t,{data:s,timestamp:Date.now(),filePath:e}),s}const oe=new Map;function ae(e=process.cwd()){return Y(e)}async function ce(e=process.cwd()){const t=D.resolve(e),n=function(e){const t=Date.now(),n=oe.get(e);if(n&&t-n.timestamp<1e4)return n.files;const s=/\.config\.(([cm]?ts)|([cm]?js)|(json))$/,i=$(e,{withFileTypes:!0}).filter(e=>e.isFile()&&s.test(e.name)).map(e=>e.name);return oe.set(e,{files:i,timestamp:t}),i}(t);let s={},i=!1;const o=await async function(e,t,n){for(const s of t)if(e.includes(s)){const e=D.resolve(n,s);if(/\.[cm]?[jt]s$/i.test(s))return await ie(e,n);if(s.endsWith(".json"))return await re(e)}return null}(n,r,t);o&&(s=o,i=!0);const a=Y(t)["pp-dev"];return i||!a||"object"!=typeof a||Array.isArray(a)||(s=a),s}const pe=Object.freeze({__proto__:null,clearConfigCache:function(){J.clear(),K.clear(),oe.clear()},getConfig:ce,getPkg:ae});function le(e){if(void 0!==e)return"1"===e||"true"===e.toLowerCase()||"0"!==e&&"false"!==e.toLowerCase()&&void 0}function ue(e){return{distZipEnabled:e.distZip??le(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??le(process.env.PP_DEV_VERSION_MANIFEST),versionFileTemplate:e.versionFileTemplate??process.env.PP_DEV_VERSION_FILE_TEMPLATE}}function de(e,t,n){if(!1===t.distZipEnabled)return!1;if(!0!==t.distZipEnabled&&void 0===t.distZipDir&&void 0===t.distZipFilename)return!1!==e&&{...e,outFileName:o(e.outFileName,"ZIP output file name")};const s=!1===e?{outFileName:n,outDir:"dist-zip"}:e,i=t.distZipFilename??s.outFileName;return{...s,...void 0!==t.distZipDir?{outDir:t.distZipDir}:{},outFileName:o(i,"ZIP output file name")}}function me(e,t){if(!1===t.versionManifestEnabled)return!1;if(!0!==t.versionManifestEnabled&&void 0===t.versionFileTemplate)return!1!==e&&void 0!==e.versionFileTemplate?{...e,versionFileTemplate:o(e.versionFileTemplate,"VERSION file name template")}:e;const n=!1===e?{enabled:!0}:e,s=t.versionFileTemplate??n.versionFileTemplate,i=void 0!==s?o(s,"VERSION file name template"):void 0;return{...n,enabled:!0,...void 0!==i?{versionFileTemplate:i}:{}}}const fe=new Set(["mi","app","proxy","build","sync","inspector","devPanel","users","server"]);function ve(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 s=process.env.GITHUB_REPOSITORY;if("string"==typeof s&&s.trim()){return`${(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${s.replace(/^\/+/,"")}`}const i=process.env.CI_PROJECT_PATH;if("string"==typeof i&&i.trim()){return`${(process.env.CI_SERVER_URL||"https://gitlab.com").replace(/\/+$/,"")}/${i.replace(/^\/+/,"")}`}const r=process.env.BITBUCKET_REPO_FULL_NAME;if("string"==typeof r&&r.trim())return`https://bitbucket.org/${r.replace(/^\/+/,"")}`;const o=process.env.TRAVIS_REPO_SLUG;if("string"==typeof o&&o.trim())return`https://github.com/${o.replace(/^\/+/,"")}`;try{const t=e("git config --get remote.origin.url",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t)return t}catch{}}async function ge(e,s={}){const i=s.root??process.cwd();q(s.mode,i);const r=ae(i),o=await ce(i);a(o,r.name);const d=c(o,r.name),{templateName:m}=d;e&&(d.distZip=de(d.distZip,e,p(m)),d.versionPlugin=me(d.versionPlugin,e));const{default:f}=await(import("./plugin.js")),v=[f(d),{name:"pp-dev:client",apply:"serve",config:e=>(e.optimizeDeps?.exclude?.push(`${t}/client`),e),resolveId(e){const t=e.match(A);if(t){const e=j(I.join(Z,t[1]));return e.startsWith(`${Z}/`)?{id:e}:null}},transformIndexHtml:async(e,t)=>{const n=N(t.server?.config.base||""),s={html:e,tags:[{tag:"link",injectTo:"head",attrs:{rel:"stylesheet",href:n.css}}]},{templateLess:i=!1,...r}=t.server?.config.clientInjectionPlugin||{};return s.tags.push({tag:"div",injectTo:"body-prepend",children:F({templateLess:i,...r})}),s.tags.push({tag:"script",injectTo:"body-prepend",attrs:{src:n.js,type:"module"}}),s},configureServer(e){const t=j(I.resolve(e.config.root,I.dirname(n)));e.config.server?.fs?.allow&&e.config.server.fs.allow.push(t)}}],{outDir:g,distZip:h,versionPlugin:_,imageOptimizer:y,templateLess:b,integrateMiTopBar:$,allowedHosts:E}=d;if($&&v.push(function(e){return{name:"mi-topbar-plugin",transformIndexHtml(){const t=[];return(!0===e||"object"==typeof e&&!0===e.addRootElement)&&t.push({tag:"div",injectTo:"body-prepend",attrs:{id:"mi-react-root"}}),(!0===e||"object"==typeof e&&!0===e.addSharedComponentsScripts)&&t.push({tag:"script",injectTo:"head-prepend",attrs:{src:"/auth/info.js"}},{tag:"script",injectTo:"head-prepend",attrs:{src:"/js/main.js",defer:"defer"}},{tag:"link",injectTo:"head-prepend",attrs:{href:"/css/main.css",rel:"stylesheet"}}),t}}}($)),y){const{ViteImageOptimizer:e}=await(import("vite-plugin-image-optimizer"));v.push(e("object"==typeof y?y:void 0))}if(_){const{versionPlugin:e}=await(import("./version-plugin-6rxIgQ-I.js"));v.push(e({outDir:g,packageVersion:r.version??"0.0.0",packageRepositoryUrl:ve(r.repository),..."object"==typeof _?_:{}}))}if(h){const{default:e}=await(import("vite-plugin-zip-pack"));v.push({...e("object"==typeof h?h:{outFileName:p(m)}),enforce:"post"})}return{base:b?`${l}/${m}`:`${u}/${m}`,server:{port:3e3,...!0===E||E.length>0?{allowedHosts:E}:{}},build:{minify:!1,assetsInlineLimit:4096,rollupOptions:{output:{banner:V}},outDir:g},css:{modules:{localsConvention:"dashes"}},ppDevConfig:d,plugins:v}}function he(e){return e?.ppDev||{}}function _e(e,t){return async(n,s={})=>{try{const{constants:i}=await H(),{PHASE_DEVELOPMENT_SERVER:r,PHASE_PRODUCTION_BUILD:o}=i;n!==o||process.env[d]||m().warn(f.yellow('⚠ Building with plain `next build`. Use `pp-dev next-build` instead to get VERSION/BUILD-MANIFEST/zip build output in the same format as `pp-dev build` (see the "Next.js Build" section in the pp-dev README).'));const p=await ce(),_=ae().name,j="function"==typeof e?await e(n,s):e,y=function(...e){const t={},n=t;for(const t of e)if(t)for(const[e,s]of Object.entries(t))void 0!==s&&(fe.has(e)&&s&&"object"==typeof s&&!Array.isArray(s)?n[e]={...n[e]??{},...s}:n[e]=s);return t}(p,he(j),t);a(y,_);const b=c(y,_),{templateLess:$,v7Features:E}=b,P=n===r,w=function(e,t,n,s){return n?s?t?`${l}/${e}`:`${v}/${e}`:t?`${l}/${e}`:`${u}/${e}`:`${l}/${e}`}(b.templateName,$,P,E),I={basePath:w,trailingSlash:!!P||void 0};if(!$){const e=P&&E?v:u;I.assetPrefix=`${e}/${b.templateName}`}const D=Object.assign({},I,j),T=g(b.allowedHosts);P&&T.length>0&&(D.allowedDevOrigins=[...D.allowedDevOrigins??[],...T]);const O=process.env[h];return n===o&&O&&(D.distDir=O),Object.defineProperty(D,"ppDev",{value:y,enumerable:!1,configurable:!0}),Object.defineProperty(D,"ppDevWrapped",{value:!0,enumerable:!1,configurable:!0}),D}catch(e){throw m().error("Error in withPPDev:",{error:e instanceof Error?e:new Error(String(e))}),e}}}export{de as a,me as b,U as c,z as d,he as e,B as f,ge as g,G as h,L as i,pe as j,q as l,ue as r,H as s,_e as w};
|
|
2
|
+
//# sourceMappingURL=index-tD-QICGk.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-B4F5_U6S.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/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],"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","injectDevPanel","html","test","panelMarkup","linkTag","bodyPrepend","result","linkInjected","replace","headEnd","head","bodyStart","CONTENT_TYPES","createDevPanelAssetMiddleware","assetPrefix","allowed","Set","req","res","next","pathname","url","split","startsWith","fileName","slice","length","has","filePath","readFile","err","content","statusCode","setHeader","extname","end","normalizePath","PP_DEV_PACKAGE_DIR","PACKAGE_REGEXP","RegExp","replacer","substring","$1","header","_chunk","safeNextImport","constants","Promise","all","default","error","Error","requireFromPPDev","createRequire","isNextAvailable","resolve","getNextVersion","nextPkg","version","previouslyLoadedKeys","loadPPDevEnv","mode","envDir","process","cwd","key","env","fromEnvironment","Object","keys","filter","loadEnv","value","entries","configCache","Map","packageJsonCache","getPackageJson","projectRoot","now","Date","root","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","loadBundledConfig","cacheKey","isESM","pkg","type","esbuild","getEsbuild","absWorkingDir","entryPoints","outfile","write","target","platform","bundle","packages","format","mainFields","sourcemap","metafile","plugins","define","banner","text","code","outputFiles","fileNameTmp","Math","random","toString","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","resolveBuildCliOverrides","options","distZipEnabled","distZip","PP_DEV_DIST_ZIP","distZipDir","PP_DEV_DIST_ZIP_DIR","distZipFilename","PP_DEV_DIST_ZIP_FILENAME","versionManifestEnabled","versionManifest","PP_DEV_VERSION_MANIFEST","versionFileTemplate","PP_DEV_VERSION_FILE_TEMPLATE","applyDistZipOverride","overrides","defaultFileName","outFileName","normalizeRelativeOutputPath","baseConfig","outDir","applyVersionManifestOverride","enabled","normalizedVersionFileTemplate","PP_DEV_CONFIG_GROUPS","resolveRepositoryUrl","repository","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","getViteConfig","environment","ppDevConfig","validatePPDevConfig","normalizedPPDevConfig","normalizePPDevConfig","templateName","createDefaultZipFileName","versionPlugin","vitePPDev","apply","optimizeDeps","exclude","push","resolveId","source","match","resolvedId","id","transformIndexHtml","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","getPPDevConfigFromNextConfig","nextConfig","ppDev","withPPDev","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","String"],"mappings":"ygBA4BA,MAAMA,EAAkBC,EAAKC,QAAQC,GAC/BC,EAAgBH,EAAKI,KAAKL,EAAiB,cAEjD,IAAIM,EAA4C,KAqB1C,SAAUC,EAAsBC,GACpC,MAAO,CACLC,IAAKR,EAAKS,MAAML,KAAKG,EAAMG,EAAc,qBACzCC,GAAIX,EAAKS,MAAML,KAAKG,EAAMG,EAAc,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,eACAiB,UACAC,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,UAUgBC,EAAeC,EAAc7B,EAAcM,GACzD,IAAK,0BAA0BwB,KAAKD,GAClC,OAAOA,EAGT,MAAM5B,IAAEA,EAAGG,GAAEA,GAAOL,EAAsBC,GACpC+B,EAAc1B,EAAqBC,GAEnC0B,EAAU,gCAAgC/B,MAE1CgC,EAAc,GAAGF,IADL,8BAA8B3B,kBAGhD,IAAI8B,EAASL,EACTM,GAAe,EASnB,GALI,YAAYL,KAAKI,KACnBA,EAASA,EAAOE,QAAQ,YAAc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.ts","../../../src/banner/header.ts","../../../src/lib/next-import.ts","../../../src/lib/env.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],"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","injectDevPanel","html","test","panelMarkup","linkTag","bodyPrepend","result","linkInjected","replace","headEnd","head","bodyStart","CONTENT_TYPES","createDevPanelAssetMiddleware","assetPrefix","allowed","Set","req","res","next","pathname","url","split","startsWith","fileName","slice","length","has","filePath","readFile","err","content","statusCode","setHeader","extname","end","normalizePath","PP_DEV_PACKAGE_DIR","PACKAGE_REGEXP","RegExp","replacer","substring","$1","header","_chunk","safeNextImport","constants","Promise","all","default","error","Error","requireFromPPDev","createRequire","isNextAvailable","resolve","getNextVersion","nextPkg","version","previouslyLoadedKeys","loadPPDevEnv","mode","envDir","process","cwd","key","env","fromEnvironment","Object","keys","filter","loadEnv","value","entries","configCache","Map","packageJsonCache","getPackageJson","projectRoot","now","Date","root","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","loadBundledConfig","cacheKey","isESM","pkg","type","esbuild","getEsbuild","absWorkingDir","entryPoints","outfile","write","target","platform","bundle","packages","format","mainFields","sourcemap","metafile","plugins","define","banner","text","code","outputFiles","fileNameTmp","Math","random","toString","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","resolveBuildCliOverrides","options","distZipEnabled","distZip","PP_DEV_DIST_ZIP","distZipDir","PP_DEV_DIST_ZIP_DIR","distZipFilename","PP_DEV_DIST_ZIP_FILENAME","versionManifestEnabled","versionManifest","PP_DEV_VERSION_MANIFEST","versionFileTemplate","PP_DEV_VERSION_FILE_TEMPLATE","applyDistZipOverride","overrides","defaultFileName","outFileName","normalizeRelativeOutputPath","baseConfig","outDir","applyVersionManifestOverride","enabled","normalizedVersionFileTemplate","PP_DEV_CONFIG_GROUPS","resolveRepositoryUrl","repository","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","getViteConfig","environment","ppDevConfig","validatePPDevConfig","normalizedPPDevConfig","normalizePPDevConfig","templateName","createDefaultZipFileName","versionPlugin","vitePPDev","apply","optimizeDeps","exclude","push","resolveId","source","match","resolvedId","id","transformIndexHtml","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","getPPDevConfigFromNextConfig","nextConfig","ppDev","withPPDev","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","String"],"mappings":"ygBA4BA,MAAMA,EAAkBC,EAAKC,QAAQC,GAC/BC,EAAgBH,EAAKI,KAAKL,EAAiB,cAEjD,IAAIM,EAA4C,KAqB1C,SAAUC,EAAsBC,GACpC,MAAO,CACLC,IAAKR,EAAKS,MAAML,KAAKG,EAAMG,EAAc,qBACzCC,GAAIX,EAAKS,MAAML,KAAKG,EAAMG,EAAc,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,eACAiB,UACAC,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,UAUgBC,EAAeC,EAAc7B,EAAcM,GACzD,IAAK,0BAA0BwB,KAAKD,GAClC,OAAOA,EAGT,MAAM5B,IAAEA,EAAGG,GAAEA,GAAOL,EAAsBC,GACpC+B,EAAc1B,EAAqBC,GAEnC0B,EAAU,gCAAgC/B,MAE1CgC,E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Q,OAAOlQ,MAEzFA,CACR,EAEJ"}
|
package/dist/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"child_process";export{A as AuthProvider,t as authProvider,n as normalizePPDevConfig,v as validatePPDevConfig}from"./auth.provider-
|
|
1
|
+
import"child_process";export{A as AuthProvider,t as authProvider,n as normalizePPDevConfig,v as validatePPDevConfig}from"./auth.provider-DDUsu1H1.js";export{d as getNextVersion,e as getPPDevConfigFromNextConfig,g as getViteConfig,f as isNextAvailable,s as safeNextImport,w as withPPDev}from"./index-tD-QICGk.js";export{defineConfig}from"./helpers.js";import"fs";import"path";import"url";import"picocolors";import"node:path";import"node:net";import"vite";import"node:module";import"ejs";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as e,existsSync as i}from"fs";import t from"path";import{P as n}from"./auth.provider-
|
|
2
|
-
//# sourceMappingURL=migrate-
|
|
1
|
+
import{readFileSync as e,existsSync as i}from"fs";import t from"path";import{P as n}from"./auth.provider-DDUsu1H1.js";import"url";import"picocolors";import"node:path";import"node:net";import"vite";const o=new Set(["backendBaseURL","personalAccessToken","miHudLess","integrateMiTopBar","v7Features","appId","portalPageId","templateName","templateLess","enableProxyCache","proxyCacheTTL","disableSSLValidation","distZip","versionPlugin","imageOptimizer","outDir","syncBackupsDir"]);function r(e){return Object.keys(e).some(e=>o.has(e))}function a(e){return"baseURL"in e}function s(e){const i=new Set(["mi","app","proxy","build","sync","inspector"]);return Object.keys(e).some(e=>i.has(e))}const p=[".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 c(o,r){let a=r??null,s=!1;if(!a){for(const e of n){const n=t.join(o,e);if(i(n)){a=n;break}}if(!a)for(const e of p){const n=t.join(o,e);if(i(n)){a=n,s=!0;break}}if(!a){const n=t.join(o,"package.json");if(i(n))try{const i=JSON.parse(e(n,"utf-8"));i["pp-dev"]&&"object"==typeof i["pp-dev"]&&!Array.isArray(i["pp-dev"])&&(a=n)}catch{}}}return a?{sourceFile:a,isWatchConfig:s,isPackageJsonConfig:"package.json"===t.basename(a)}:null}function l(i){return JSON.parse(e(i,"utf-8"))["pp-dev"]}function d(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}function u(e){const i={mi:{url:e.baseURL}};return void 0!==e.portalPageId&&(i.app={id:e.portalPageId}),i}function f(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}${f(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}: ${f(t,i+1)}`).join(",\n")},\n${t}}`}return String(e)}function m(e,i="ts"){if("json"===i)return JSON.stringify(e,null,2)+"\n";return`${"ts"===i?"import { defineConfig } from '@metricinsights/pp-dev';":"const { defineConfig } = require('@metricinsights/pp-dev');"}\n\n${"ts"===i?"export default":"module.exports ="} defineConfig(${f(e)});\n`}export{c as discoverMigrateSource,m as generateConfigFileContent,s as isAlreadyMigrated,r as isLegacyFlatConfig,a as isLegacyPPWatchConfig,l as loadPackageJsonMigrateConfig,d as migrateLegacyFlatConfig,u as migratePPWatchConfig};
|
|
2
|
+
//# sourceMappingURL=migrate-CCBRuVfj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-
|
|
1
|
+
{"version":3,"file":"migrate-CCBRuVfj.js","sources":["../../../src/lib/migrate.ts"],"sourcesContent":[null],"names":["LEGACY_FLAT_KEYS","Set","isLegacyFlatConfig","config","Object","keys","some","k","has","isLegacyPPWatchConfig","isAlreadyMigrated","NEW_KEYS","WATCH_CONFIG_NAMES","discoverMigrateSource","projectRoot","configArg","sourceFile","isWatchConfig","name","PP_DEV_CONFIG_NAMES","candidate","path","join","existsSync","pkgJsonPath","pkgJson","JSON","parse","readFileSync","Array","isArray","isPackageJsonConfig","basename","loadPackageJsonMigrateConfig","migrateLegacyFlatConfig","legacy","packageName","mi","undefined","backendBaseURL","url","personalAccessToken","token","miHudLess","mode","integrateMiTopBar","include","addRootElement","addSharedComponentsScripts","v7Features","apiVersion","length","app","appId","portalPageId","id","templateName","templateLess","type","proxy","enableProxyCache","cache","proxyCacheTTL","cacheTtl","disableSSLValidation","tls","allowSelfSigned","build","outDir","distZip","zip","outFileName","fileName","inDir","versionPlugin","vf","enabled","versionFileTemplate","fileNameTemplate","versionFile","imageOptimizer","imageOptimisations","syncBackupsDir","sync","backupsDir","migratePPWatchConfig","watchCfg","baseURL","serializeValue","value","depth","indent","repeat","innerIndent","String","replace","map","v","entries","filter","generateConfigFileContent","format","stringify"],"mappings":"qMAmCA,MAAMA,EAAmB,IAAIC,IAAI,CAC/B,iBACA,sBACA,YACA,oBACA,aACA,QACA,eACA,eACA,eACA,mBACA,gBACA,uBACA,UACA,gBACA,iBACA,SACA,mBAGI,SAAUC,EAAmBC,GACjC,OAAOC,OAAOC,KAAKF,GAAQG,KAAMC,GAAMP,EAAiBQ,IAAID,GAC9D,CAEM,SAAUE,EAAsBN,GACpC,MAAO,YAAaA,CACtB,CAEM,SAAUO,EAAkBP,GAChC,MAAMQ,EAAW,IAAIV,IAAI,CAAC,KAAM,MAAO,QAAS,QAAS,OAAQ,cAEjE,OAAOG,OAAOC,KAAKF,GAAQG,KAAMC,GAAMI,EAASH,IAAID,GACtD,CAIA,MAAMK,EAAqB,CACzB,sBACA,sBACA,wBACA,qBACA,qBACA,wBAaI,SAAUC,EAAsBC,EAAqBC,GACzD,IAAIC,EAA4BD,GAAa,KACzCE,GAAgB,EAEpB,IAAKD,EA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AQ,MAAMpE,KAAK,YAE7DqE,IAC1B,CAEA,GAAqB,iBAAVF,GAAgC,OAAVA,EAAgB,CAC/C,MAAMS,EAAU9F,OAAO8F,QAAQT,GAAkCU,OAAO,GAAIF,UAAa3D,IAAN2D,GAEnF,GAAuB,IAAnBC,EAAQ/C,OACV,MAAO,KAKT,MAAO,MAFO+C,EAAQF,IAAI,EAAEzF,EAAG0F,KAAO,GAAGJ,IAActF,MAAMiF,EAAeS,EAAGP,EAAQ,MAEpEpE,KAAK,YAAYqE,IACtC,CAEA,OAAOG,OAAOL,EAChB,UAIgBW,EAA0BjG,EAAqBkG,EAA8B,MAC3F,GAAe,SAAXA,EACF,OAAO3E,KAAK4E,UAAUnG,EAAQ,KAAM,GAAK,KAS3C,MAAO,GALM,OAAXkG,EACI,yDACA,oEACwB,OAAXA,EAAkB,iBAAmB,mCAEFb,EAAerF,QACvE"}
|
package/dist/esm/plugin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{d as e,i as s,b as t,R as i,c as o,a as r,I as a,g as p,M as d,h as l,f as m,j as c,k as u,l as f,m as h,D as g,s as b,U as w,V as P,n as y,u as j}from"./request-capture.middleware-
|
|
1
|
+
import{d as e,i as s,b as t,R as i,c as o,a as r,I as a,g as p,M as d,h as l,f as m,j as c,k as u,l as f,m as h,D as g,s as b,U as w,V as P,n as y,u as j}from"./request-capture.middleware-VElwjU1W.js";import{a as L}from"./auth.provider-DDUsu1H1.js";export{n as normalizePPDevConfig,v as validatePPDevConfig}from"./auth.provider-DDUsu1H1.js";import"zlib";import"url";import"axios";import"node:http";import"node:https";import"./version-manifest-CyzmnFOe.js";import"crypto";import"child_process";import"fs/promises";import"path";import"util";import"node:module";import"fs";import"process";import"os";import"jszip";import"module";import"http-proxy-middleware";import"node:string_decoder";import"node:crypto";import"node:fs";import"node:os";import"node:path";import"express";import"picocolors";import"node:net";import"vite";function x(n){const{templateName:v,templateLess:x,backendBaseURL:I,miHudLess:k,appId:B,enableProxyCache:F,proxyCacheTTL:S,disableSSLValidation:H,outDir:T,distZip:U,versionPlugin:W,syncBackupsDir:D,syncMaxBackups:M,syncBuildTimeoutMs:A,v7Features:R,personalAccessToken:C,inspectorEnabled:V,inspectorMaxMemory:$,inspectorCaptureLimit:z,devPanelPosition:N,devPanelHidden:Z,devPanelAutoHide:O,persistUsers:_,allowedHosts:q}=n||{};let E=!0;const G=new WeakMap;return{name:"vite-pp-dev",apply:"serve",closeBundle(){G.get(this.environment)?.dispose(),G.delete(this.environment)},config:e=>(e.clientInjectionPlugin={backendBaseURL:I,appId:B,templateLess:x,v7Features:R,devPanelPosition:N,devPanelHidden:Z,devPanelAutoHide:O},R&&(e.base=`/pl/${v}`),e),transformIndexHtml:async(e,s)=>{const t={html:e,tags:[]};return E&&(E=!1,t.tags.push({tag:"script",injectTo:"body",children:`${Math.random()}`})),t},configureServer:N=>{let Z=N.config.base;if(Z.endsWith("/")||(Z+="/"),I&&N.middlewares.use(e()),N.middlewares.use(s(Z,v)),!1!==V){const e=new i($);N.middlewares.use(t(e,z));const s=o({allowedHosts:q});r(s,e,z),N.middlewares.use((e,t,i)=>{e.url?.startsWith("/@api/")||e.url?.startsWith(a)?s(e,t,i):i()})}if(I){N.config.logger.info(L.blue(`🌐 Backend URL: ${I}`)),N.config.logger.info(L.blue(`🆔 Custom App ID: ${B}`));const e=new URL(I).host,s=p(I,{appId:B,templateLess:x,disableSSLValidation:H,v7Features:R,personalAccessToken:C}),t=new d(I,s);F&&N.middlewares.use(l({devServer:N,ttl:m(S)}));const i=c(Z);N.middlewares.use(u(i,t,Object.assign({},n,{appId:B,appBase:Z}))),N.middlewares.use(f({baseURL:I,proxyIgnore:h(Z),disableSSLValidation:H,miAPI:t,templateName:v}));const r=o({allowedHosts:q}),a=new g(v,Object.assign({root:N.config.root,backupFolder:D,maxBackups:M,buildTimeoutMs:A,buildInputFolder:"object"==typeof U?U.inDir??T:T},"object"==typeof U?{distZipFolder:U.outDir,distZipFilename:U.outFileName}:void 0,"object"==typeof W?{versionFileTemplate:W.versionFileTemplate}:void 0)),V=b({server:N,internalServer:r,distService:a,miAPI:t,persistUsers:_,projectRoot:N.config.root||process.cwd(),miUrl:I});return G.set(N.environments.client,V),N.middlewares.use((e,s,t)=>{e.url?.startsWith("/@api/login")||e.url?.startsWith("/@api/variables/")||e.url?.startsWith(w)||e.url?.startsWith(P)?r(e,s,t):t()}),()=>{N.middlewares.use(y(e=>e.split("?")[0].endsWith("index.html"),(s,i)=>Buffer.from(j(e,i.headers.host??"",t.buildPage(s,k)))))}}}}}export{x as default,x as vitePPDev};
|
|
2
2
|
//# sourceMappingURL=plugin.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{inflateSync as e,brotliDecompressSync as t,unzipSync as s,deflateSync as n,brotliCompressSync as r,gzipSync as i}from"zlib";import{m as a,c as o,a as c,f as l,e as d,t as u,g as p,s as h,j as g,p as m,u as f}from"./auth.provider-DDUsu1H1.js";import{URL as y,fileURLToPath as w}from"url";import v,{isAxiosError as b}from"axios";import k from"node:http";import $ from"node:https";import{g as x,w as S}from"./version-manifest-CyzmnFOe.js";import*as A from"path";import*as E from"fs";import{promises as T}from"fs";import*as I from"crypto";import{randomUUID as j}from"crypto";import*as N from"process";import*as P from"os";import R from"jszip";import*as L from"child_process";import{createRequire as F}from"module";import{createProxyMiddleware as C,responseInterceptor as O}from"http-proxy-middleware";import{StringDecoder as B}from"node:string_decoder";import{createHash as M,randomUUID as D}from"node:crypto";import U from"node:fs";import H from"node:os";import _ from"node:path";import V from"express";const z="/@pp-dev-hmr",q=A.dirname(a),W={".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json; charset=utf-8"};function J(e,t){const s=t.clientDir??q,n=new Set([`${t.name}.js`,`${t.name}.css`,`${t.name}.js.map`,`${t.name}.css.map`]);e.get(t.path,(e,n)=>{E.readFile(A.join(s,`${t.name}.html`),"utf-8",(e,s)=>{if(e)return void n.status(500).type("text/plain").end(`${t.name} page not built (${e.message})`);const r=t.values?.()??{};n.setHeader("Content-Type","text/html; charset=utf-8"),n.setHeader("Cache-Control","no-cache"),n.end(s.replace(/\{\{(\w+)\}\}/g,(e,t)=>r[t]??e))})}),e.get(`${t.path}/:file`,(e,t,r)=>{const i=e.params.file;n.has(i)?E.readFile(A.join(s,i),(e,s)=>{e?r():(t.setHeader("Content-Type",W[A.extname(i)]??"application/octet-stream"),t.setHeader("Cache-Control","no-cache"),t.end(s))}):r()})}function Z(n,r,i={}){switch(r){case"gzip":return s(n,i);case"br":return t(n,i);case"deflate":return e(n,i);default:return n}}const K="/@pp-dev/inspector",G=new WeakMap;function X(e){const t=Array.isArray(e)?e[0]:e;return"string"==typeof t?t:void 0}function Y(e,t,s=10485760,n=q){const r=G.get(e);if(r)return r.store=t,void(r.captureLimit=s);const i={store:t,captureLimit:s};G.set(e,i),e.get("/@api/requests",(e,t)=>{const{store:s}=i,n=X(e.query.limit),r=X(e.query.offset),a=X(e.query.method),o=X(e.query.search),c=void 0!==n?parseInt(n,10):void 0,l=s.list({limit:Number.isFinite(c)?c:500,offset:void 0!==r&&Number.isFinite(parseInt(r,10))?parseInt(r,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:ee(s.memoryUsage),maxMemoryFormatted:ee(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 n=Q(s.requestHeaders["content-type"]),r=Q(s.responseHeaders["content-type"]),a=s.responseBody?function(e,t,s){const n=Array.isArray(t)?t.join(", "):String(t??"");try{return Z(e,n.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:n,responseHeaders:s.responseHeaders,responseBody:a?a.toString("base64"):null,responseBodySize:s.responseBody?.byteLength??0,responseBodyTruncated:s.responseBodyTruncated||null!==s.responseBody&&null===a,responseContentType:r})}),e.delete("/@api/requests",(e,t)=>{i.store.clear(),t.json({ok:!0})}),J(e,{path:K,name:"request-inspector",clientDir:n,values:()=>({captureLimit:String(i.captureLimit)})})}function Q(e){return Array.isArray(e)?e[0]??"":String(e??"")}function ee(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 te(e){return"string"==typeof e?e:void 0}function se(e,t){return"string"==typeof e?Buffer.from(e,t):e instanceof Uint8Array?Buffer.from(e):null}function ne(e,t,s={}){return async(a,c,l)=>{if(await e(a.url??"",a,c)){const e=o();"GET"!==a.method&&"HEAD"!==a.method||!(a.headers.accept??"").includes("text/html")||delete a.headers["if-none-match"];const d=c.end;if("HEAD"===a.method)return c.end=function(e,t,s){const n=[e,t,s].find(e=>"function"==typeof e);return c.headersSent||c.removeHeader("content-length"),d.call(this,n),this},void l();e.info(`Rewrite response for ${a.url}`);const u=[],p=c.write,h=c.writeHead,g=c.flushHeaders;let m=null,f=!1;const y=()=>{f=!0,m&&!c.headersSent&&h.apply(c,m),m=null;for(const e of u.splice(0))p.call(c,e)},w=(e=!1)=>{if(f)return!0;if(!s.contentType)return!1;const t=c.getHeader("content-type");return!(void 0===t&&!e)&&(!s.contentType(void 0===t?"":String(t))&&(y(),!0))};c.flushHeaders=function(){w()&&g.call(this)},c.writeHead=function(e,...t){if(f)return h.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 n=String(t[e]),r=s.get(n.toLowerCase())??{name:n,values:[]};r.values.push(String(t[e+1])),s.set(n.toLowerCase(),r)}for(const{name:t,values:n}of s.values())e.setHeader(t,1===n.length?n[0]:n);return}if(t&&"object"==typeof t)for(const[s,n]of Object.entries(t))void 0!==n&&e.setHeader(s,n)}(this,void 0===s?t[0]:t[1]),this.statusCode=e,m=void 0===s?[e]:[e,s],w(),this},c.write=function(e,t,s){if(w())return p.call(this,e,t,s);const n=se(e,te(t));n&&u.push(n);const r="function"==typeof t?t:s;return"function"==typeof r&&process.nextTick(r),!0},c.end=function(s,o,l){if(w(!0))return d.call(this,s,o,l);"function"==typeof s&&(l=s,s=void 0);const p=se(s,te(o));p&&u.push(p);const g="function"==typeof o?o:l,f=c.getHeader("content-encoding"),y=Z(Buffer.concat(u),f),v=function(e,t){switch(t){case"gzip":return i(e);case"br":return r(e);case"deflate":return n(e);default:return e}}(t(y,a,c),f);return void 0!==c.getHeader("content-length")&&(c.headersSent?e.warn(`Rewrite response for ${a.url}: headers already sent, Content-Length left as is`):c.setHeader("content-length",v.length)),c.headersSent||c.removeHeader("etag"),c.writeHead=h,m&&!c.headersSent&&h.apply(this,m),d.call(this,v,g),this}}l()}}const re=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ie=new Map,ae=new Map;const oe=(e,t,s)=>{let n=ie.get(e);if(!n){const t=/:\d+$/.test(e)?"":"(?::(?<port>\\d+))?";n=new RegExp(`(?<keep>!!)?(?<url>http(?<secure>s)?(?<slashes>:(?:\\\\)?/(?:\\\\)?/)${re(e)}${t})`,"gi"),ie.set(e,n)}return s.replace(n,(...e)=>{const{keep:s,url:n,secure:r,slashes:i,port:a}=e.at(-1);return s||a&&a!==(r?"443":"80")?n:`http${i}${t}`})},ce=(e,t,s)=>{const n=new RegExp(`${e.replace(/\\*\//gi,"\\\\/")}`,"gi"),r=new RegExp(`${e}`,"gi"),i=s.replace(n,t);return i===s?i.replace(r,t):i},le=(e,t,s)=>{e.setHeader("location",t),e.statusCode=s,e.end()};function de(e){return e.split("?")[0]}function ue(e,t){const s=(e=(e=e.startsWith("/")?e:`/${e}`).endsWith("/")?e:`${e}/`).endsWith("/")?e.slice(0,-1):e,n=o();return(r,i,a)=>{const o=new y(r.url??"","http://localhost"),{pathname:u,search:p}=o,h=["/",s];if(t&&(h.push(`${l}/${t}`),h.push(`${d}/${t}`)),h.includes(u)){const t=`${e}${p}`;return n.info(c.yellow(`Redirecting to: ${t}`)),le(i,t,302)}a()}}class pe{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 he extends pe{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 n=new FormData;return n.append("file",new File([new Uint8Array(t)],"file.zip",{type:"application/zip"}),"file.zip"),this.axios.post(e,n,{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 ge extends he{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 me="Something went wrong when fetching page data",fe="Something went wrong when fetching page template data",ye="Something went wrong when fetching page variables",we=" The instance may be down or in maintenance mode. Please try again later.",ve=[me,fe,ye];function be(){return new Error(`${me}.${we}`)}function ke(){return new Error(`${fe}.${we}`)}function $e(e){return e instanceof Error&&ve.some(t=>e.message.includes(t))}class xe extends pe{async getAll(e){const t=(await this.axios.get("/api/page",{withCredentials:!0,headers:Object.assign({},e,{Accept:"application/json","Content-Type":"application/json","Cache-Control":"no-cache",Pragma:"no-cache",Expires:"0"})})).data;if("object"!=typeof t||null===t||!Array.isArray(t.pages))throw be();return t.pages}async get(e,t){const s=(await this.axios.get(`/api/page/id/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw be();return s.page}async getPageContent(e,t){return(await this.axios.get(`/p/${e}`,{withCredentials:!0,headers:Object.assign({},t,{accept:"text/html","content-type":"application/json"})})).data}async create(e,t){const s=(await this.axios.post("/api/page",e,{withCredentials:!0,headers:Object.assign({},t,{accept:"application/json","content-type":"application/json"})})).data;if("object"!=typeof s||null===s||"object"!=typeof s.page||null===s.page)throw be();return s.page}}class Se extends pe{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 ke();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 ke();return s.page_template}}class Ae extends pe{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(`${ye}.${we}`);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 Ee(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 Te(e,t){const[s,...n]=e.split(";"),r=n.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(),...r].join("; ")}const Ie="metric_insights_session";function je(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 Ne(e,t){return e?je(e.split(";"),t):void 0}function Pe(e,t){if(void 0===e||"number"==typeof e)return;return je((Array.isArray(e)?e:[e]).map(e=>e.split(";",1)[0]),t)}function Re(e,t){return void 0===e?e:Array.isArray(e)?e.map(e=>Te(e,t)):Te(e,t)}const Le=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,n,r){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",n.placeholder=i.placeholder,r.replaceChildren(`You can get the ${i.label} `,a)}function n(e,t){t.textContent=e,t.classList.add("show")}function r(e){e.classList.remove("show")}function i(e,t,s,i){s.addEventListener("click",async s=>{if(s.preventDefault(),r(i),!t.value.trim())return n(`${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,r){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();n(`Login failed: ${e?.error||"Unknown error occurred"}`,r)}catch(e){n("Login failed: Unable to parse response",r)}else window.location.href=i.url}catch(e){n("Login failed: Network error. Please check your connection.",r)}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",()=>{r(i)})}function a(e){const t=e.firstChild;if(!t)return;const n=t.lastChild?.cloneNode(!0);if(!n)return;n.innerHTML="";const r=n.cloneNode(!0);r.innerText="OR",r.setAttribute("role","separator"),r.setAttribute("aria-label","Alternative login method");const a=n.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(r),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,n){const r=e.querySelectorAll(".token-type-option"),i=e=>{const i=e.dataset.value;r.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,n)};r.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 Fe(e){const{message:t,response:s}="object"==typeof e&&null!==e?e:{},n="number"==typeof s?.status?s.status:0,r=s?.data?.message;return"string"==typeof r&&r?{status:n,message:r}:"string"==typeof t&&t?{status:n,message:t}:{status:n,message:"string"==typeof e&&e?e:"Unknown error"}}function Ce(e){const{status:t,message:s}=Fe(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 Oe(e){const{status:t}=Fe(e);return 401===t||403===t||412===t}const Be="[DEV PAGE. DO NOT DELETE]",Me=new Map;class De{#e;#t;#s=null;#n;#r;#i=!1;#a=null;#o=null;#c;#l;#d;#u;#p;internalPageName;appId;templateLess;assetsApi;pageApi;pageTemplateApi;pageVariableApi;logger;constructor(e,t){const{headers:s={},appId:n,templateLess:r=!0,disableSSLValidation:i=!1,v7Features:a=!1,personalAccessToken:c}=t||{};this.#e=s,this.#r=[],this.#n="",this.#c=a,this.#l=c,this.#d=!1,this.#u=Promise.resolve(!1);const l=`${e}:${i}`;if(Me.has(l))this.#t=Me.get(l);else{const t=new $.Agent({keepAlive:!1,...i?{rejectUnauthorized:!1}:{}});this.#t=v.create({baseURL:e,headers:s,timeout:3e4,maxRedirects:5,httpAgent:new k.Agent({keepAlive:!1}),httpsAgent:t}),Me.set(l,this.#t)}this.appId=n,this.templateLess=r,this.assetsApi=new(a?ge:he)(this.#t),this.pageApi=new xe(this.#t),this.pageTemplateApi=new Se(this.#t),this.pageVariableApi=new Ae(this.#t),this.logger=o()}async isTemplateLoaded(){return this.#u}get isV710OrHigher(){return this.#d}get v7Features(){return this.#c}#h(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.#e=t,!t.authorization&&this.#l&&(t.authorization=`Bearer ${this.#l}`),t}#g(e){return e.replace(/[.*+?^${}()|[\]\\\/]/g,"\\$&")}get personalAccessToken(){return this.#l}set personalAccessToken(e){this.#l=e}updateHeaders(e){this.#h(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.#u||this.#s||(this.#u=new Promise(e=>{this.#p=e})),this.#s)return Promise.resolve(this.#s);if(void 0===this.templateLess&&(this.templateLess=!1),this.#c){const t=await this.pageApi.get(this.appId,this.#h(e)).then(e=>(this.logger.info(c.green("Page fetched")),e)).catch(async t=>{if(this.#p(!1),$e(t))throw t;throw await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(c.red(`Error fetching page data: ${t.message}\n${t.stack}`)),new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.")):t});return void 0!==t.template_id&&(this.#d=!0),this.internalPageName=t.internal_name,this.#s=this.localTemplateHTML,this.#s=this.#s.replace(/%%PAGE TITLE%%/g,t.name||"Local template"),this.logger.info(c.green("Local page template fetched")),this.#p(!0),this.#s}let t=(await this.pageApi.getAll(this.#h(e)).then(e=>(this.logger.info(c.green("Page list fetched")),e)).catch(async t=>{throw this.#p(!1),await this.pageApi.checkAuth(this.#h(e))?(this.logger.error(c.red(`Error fetching page list: ${t.message}\n${t.stack}`)),new Error("Current user does not have access to page list")):t})).find(e=>e.name===Be);return t||(this.logger.warn(c.yellow("Creating dev page template...")),t=await this.pageApi.create({enabled:"Y",name:Be,internal_name:"dev-page-template",visible_in_homepage:"Y"},this.#h(e)).then(e=>(this.logger.info(c.green("Dev page created")),e)).catch(e=>{throw this.logger.error(c.red(`Error creating dev page: ${e.message}`)),this.#p(!1),new Error(`Error when creating dev page.\n That can be caused by missing permissions or page with name "${Be}" already exists`)})),await this.pageApi.getPageContent(t.internal_name,this.#h(e)).then(e=>(this.#s=e,e)).then(e=>(this.#p(!0),this.logger.info(c.green("Page template fetched")),e)).catch(e=>{throw this.#p(!1),this.logger.error(c.red(`Error fetching page template: ${e.message}`)),new Error("Error fetching page template")})}async getPageVariables(e,t){return void 0===this.appId&&(this.appId=e,this.templateLess=!1),this.#s=await this.getPageTemplate(t),await this.pageApi.get(e,this.#h(t)).then(e=>{const{tags:t="[]",name:s,template:n}=e;if(n&&t){const e=JSON.parse(t);return this.#r=e,this.#i=!0,this.#n=s,e}return this.#r=[],this.#i=!0,this.#n=s,[]}).catch(t=>{if(this.logger.error(c.red(`Error fetching page variables: ${t.message}`)),404===t.response?.status)throw new Error(`Portal Page with id "${e}" not found on instance ${this.#t.getUri()}`);if(401===t.response?.status)throw this.logger.warn(`Unauthorized error: ${t}`),new Error(`Current user does not have access to page with id "${e}" on instance ${this.#t.getUri()}`);throw t})}async getLivePageVariables(e=this.#e){if(void 0===this.appId)throw new Error("Cannot fetch live page variables before the page ID is known");const t=this.appId,s=Date.now();this.logger.info(c.cyan(`[page-variables] Fetching live variables for page ID ${t} (page_id lookup)`));const n=await this.pageVariableApi.getById(t,this.#h(e));return this.logger.info(c.green(`[page-variables] Fetched ${n.length} live variable(s) for page ID ${t} in ${Date.now()-s}ms`)),n}async applyPageVariables(e,t=this.#e){if(void 0===this.appId)throw new Error("Cannot apply page variables before the page ID is known");const s=this.appId,n=Date.now();this.logger.info(c.cyan(`[page-variables] Applying ${e.length} variable(s) to page ID ${s} (page_id lookup)`)),await this.pageVariableApi.updateById(s,e,this.#h(t)),this.logger.info(c.green(`[page-variables] Applied variables to page ID ${s} in ${Date.now()-n}ms`))}async listPages(e=this.#e){return this.pageApi.getAll(this.#h(e))}async getPageVariablesFor(e,t=this.#e){return this.pageVariableApi.getById(e,this.#h(t))}get localPageVariables(){return this.templateLess||!this.#i?null:this.#r.map(({name:e,value:t})=>({name:e,value:t}))}get isTemplateLess(){return!!this.templateLess}async reloadPageVariables(e=this.#e){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.#h(t),n=this.appId;try{return this.#c?await this.#m(n,s):await this.#f(n,s)}catch(e){this.#y(e,n)}}async#m(e,t){const s=await this.pageApi.get(e,t);return this.logger.info(c.green("Page fetched")),void 0!==s.template_id&&(this.#d=!0),this.internalPageName=s.internal_name,s}async#f(e,t){return await this.pageApi.get(e,t)}#y(e,t){if($e(e))throw e;if(this.#c&&e.message?.includes("access"))throw new Error("The current user does not have access to this page. Check your configuration to ensure app.id is correct.");if(404===e.response?.status)throw new Error(`Portal Page with id "${t}" not found on instance ${this.#t.getUri()}`);throw 401===e.response?.status&&this.logger.error(c.red(`Current user does not have access to page with id "${t}" on instance ${this.#t.getUri()}`)),e}buildPage(e,t=!1){let s="string"==typeof e?e:e.toString("utf-8");for(const{regExp:e,value:t}of this.#w())s=s.replace(e,()=>t);if(t){return new(x())(s).serialize()}const{before:n,after:r}=this.#v();return n+s+r}#w(){return this.#a?.vars!==this.#r&&(this.#a={vars:this.#r,replacements:this.#r.map(({name:e,value:t})=>({regExp:new RegExp(`\\[${this.#g(e)}\\]`,"g"),value:t}))}),this.#a.replacements}#v(){const e=this.#s,t=this.#n;if(this.#o?.template===e&&this.#o.title===t)return this.#o;const s=new(x())(e),{document:n}=s.window,r="%%PLACEHOLDER%%",i=n.createElement("div");i.innerHTML=r;const a=n.querySelector(".main-side");if(a){const e=a.querySelectorAll("script");e.length?a.insertBefore(i,e.item(e.length-1)):a.append(i)}else{const e=n.createElement("div");e.append(i),n.body.append(e)}const o=n.querySelector("head"),c=o.querySelector("title");if(c)c.text=t;else{const e=n.createElement("title");e.textContent=t,o.appendChild(e)}const l=s.serialize(),d=new RegExp(`<div>\\s*${r}\\s*<\\/div>`,"i").exec(l);return this.#o={template:e,title:t,before:l.slice(0,d.index),after:l.slice(d.index+d[0].length)},this.#o}async getAssets(){if(this.appId){if(this.templateLess)return await this.assetsApi.downloadPageAssets(this.appId,this.#e);{const e=await this.pageApi.get(this.appId,this.#e);if(this.#d){const t=await this.pageTemplateApi.get(e.template_id,this.#e);return await this.assetsApi.downloadTemplateAssets(t.id,this.#e)}if(e.template)return await this.assetsApi.downloadTemplateAssets(e.template,this.#e)}}}async updateAssets(e){if(this.appId){if(this.templateLess)return await this.assetsApi.uploadPageAssets(this.appId,e,this.#e);{const t=await this.pageApi.get(this.appId,this.#e);if(this.#d){const s=await this.pageTemplateApi.get(t.template_id,this.#e);return await this.assetsApi.uploadTemplateAssets(s.id,e,this.#e)}if(t.template)return await this.assetsApi.uploadTemplateAssets(t.template,e,this.#e)}}}async validateCredentials(e){try{const t=e||this.#e;return await this.get("/api/user",t,!0),{isValid:!0}}catch(e){const t=Ce(e);return{isValid:!1,error:t.userFriendlyMessage,code:t.code}}}async get(e,t,s=!1,n={}){const r=s?t:Object.assign({},this.#h(this.#e),t);try{return await this.#t.get(e,{headers:r})}catch(e){if("UNKNOWN_ERROR"!==Ce(e).code){const t=Ce(e);throw n.quiet||(this.logger.error(c.red(`API request failed: ${t.userFriendlyMessage}`)),function(e,t,s){const n=Ce(t),r=`[${s}] `;e.error(c.red(`${r}${n.userFriendlyMessage}`)),e.error(c.red(`Status: ${n.status} (${n.code})`)),e.error(c.red(`Details: ${n.message}`)),n.suggestions.length>0&&(e.info(c.yellow("Suggestions:")),n.suggestions.forEach((t,s)=>{e.info(c.yellow(` ${s+1}. ${t}`))}))}(this.logger,e,"API Request")),e.tokenErrorInfo=t,e}throw e}}}const Ue=String.raw`[a-z](?:[a-z0-9\-]*[a-z0-9])?`,He=new RegExp(`^(?:${Ue})$`),_e=".localhost";function Ve(e){return e?e.length>32?"The name must be at most 32 characters long":He.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 ze(e){if(!e)return;const t=e.toLowerCase().replace(/:\d+$/,"");if(!t.endsWith(_e))return;const s=t.slice(0,-10);return s&&!s.includes(".")?s:void 0}function qe(e,t){const s=/:(\d+)$/.exec(e.headers.host??"")?.[1];return`${Ee(e)?"https":"http"}://${t?`${t}.`:""}localhost${s?`:${s}`:""}`}const We=new class{#b=new Map;#k=new Set;#$=new Set;#x=!1;#S=new Set;#A;#E=new Map;#T=new WeakMap;#I;useContext(e){void 0!==this.#I&&this.#I!==e&&this.clear(),this.#I=e}get context(){return this.#I}list(){return[...this.#b.values()]}get(e){return this.#b.get(e)}add(e){const t=Ve(e.name);if(t)throw new Error(t);if(this.#b.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.#E.delete(s.name),this.#b.set(s.name,s),this.#j(),s}replace(e,t){if(!this.#b.has(e))throw new Error(`There is no user named "${e}"`);const s=Ve(t.name);if(s)throw new Error(s);if(t.name!==e&&this.#b.has(t.name))throw new Error(`A user named "${t.name}" already exists`);const n=this.#A===e,r=[...this.#E].filter(([,t])=>t===e).map(([e])=>e);let i;this.#x=!0;try{this.remove(e),i=this.add(t)}catch(s){throw this.#x=!1,this.#j(),s}finally{this.#x=!1}for(const s of t.name===e?r:[...r,e])this.#E.set(s,i.name);return n&&(this.#A=i.name),this.#j(),i}#j(){this.#x||this.#$.forEach(e=>e())}renamedTo(e){return this.#E.get(e)}remove(e){const t=this.#b.get(e);if(!t)return!1;this.#A===e&&(this.#A=void 0);for(const[t,s]of this.#E)s===e&&this.#E.delete(t);return this.#b.delete(e),this.#k.forEach(e=>e(t)),this.#j(),!0}clear(){for(const e of[...this.#b.keys()])this.remove(e)}onRemove(e){return this.#k.add(e),()=>{this.#k.delete(e)}}onSessionChange(e){return this.#S.add(e),()=>{this.#S.delete(e)}}sessionChanged(e){this.#b.get(e.name)===e&&this.#S.forEach(t=>t(e))}onChange(e){return this.#$.add(e),()=>{this.#$.delete(e)}}get defaultUser(){return void 0===this.#A?void 0:this.#b.get(this.#A)}setDefaultUser(e){if(void 0===e)return void(this.#A=void 0);const t=this.#b.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.#A=e}resolve(e){if(this.#T.has(e))return this.#T.get(e);const t=ze(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.#b.get(t)??this.#b.get(this.#E.get(t)??"");s=e?{key:e.name,user:e}:void 0}return this.#T.set(e,s),s}};function Je(e=We){return(t,s,n)=>{const r=e.resolve(t),i=ze(t.headers.host)??"";if(r?.user&&i&&r.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",`${qe(t,r.key)}${e}`),s.setHeader("Cache-Control","no-store"),void s.end()}r?n():(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.`))}}const Ze=/(?:^|\/\/[^/]+)\/(?:login|auth\/saml\/login)(?:[/?#]|$)/i;function Ke(e){return(e??"").split(";").map(e=>e.trim()).filter(e=>e&&e.split("=",1)[0].trim()!==Ie)}function Ge({statusCode:e=200,headers:t}){return 401===e||412===e||e>=300&&e<400&&Ze.test(String(t.location??""))}class Xe{#b;#N;#P=o();#R=new WeakMap;#L=new WeakMap;#F=new WeakMap;#C=new WeakMap;constructor(e,t){this.#b=e,this.#N=t}isLeftBehindRequest(e,t,s){const n=ze(t.headers.host)===e.name?Ne(t.headers.cookie,Ie):s;return void 0!==n&&this.#O(e,n)}observe(e,t,s,n){if("session"!==e.kind||this.#b.get(e.name)!==e)return;const r=ze(t.headers.host)===e.name,i=r?Ne(t.headers.cookie,Ie):n,a=Pe(s.headers["set-cookie"],Ie),o=this.#F.get(e);let c,l,d=r;return a&&a!==i?(c=a,l=i):r&&i!==e.session&&!Ge(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&&Ge(s)&&i===e.session&&this.#B(e,`MI turned away ${t.method} ${t.url}`),c&&c!==e.session&&c!==this.#R.get(e)&&c!==this.#L.get(e)&&!this.#O(e,c)?this.#M(e,c,l,d):void 0}async#M(e,t,s,n){let r;this.#R.set(e,t);try{r=await this.#N(t)}catch(r){return this.#R.get(e)===t&&(this.#R.delete(e),this.#F.set(e,{session:t,replaced:s,ownHost:n,retryAt:Date.now()+5e3})),void this.#P.warn(c.yellow(`Could not check the MI session of user ${e.name}: ${String(r)}`))}if(this.#R.get(e)===t&&this.#b.get(e.name)===e)if(this.#R.delete(e),this.#F.get(e)?.session===t&&this.#F.delete(e),r){if(this.#O(e,t)||void 0!==s&&this.#O(e,s))return;const i="active"===e.state;n&&(this.#D(e),void 0!==s&&s!==t&&this.#D(e,s)),this.#F.delete(e),Object.assign(e,{state:"active",session:t,miUser:r}),this.#L.delete(e),this.#b.sessionChanged(e),i||this.#P.info(`${c.blue("User")} ${c.yellow(e.name)} ${c.blue("logged in")} (MI user ${r.id}${r.username?`, ${r.username}`:""})`)}else this.#L.set(e,t),"active"===e.state&&s===e.session&&this.#B(e,"MI started a guest session")}#O(e,t){return"active"===e.state&&Boolean(this.#C.get(e)?.has(t))}#D(e,t=e.session){if(!t)return;const s=this.#C.get(e)??new Set;s.add(t),s.size>20&&s.delete(s.values().next().value),this.#C.set(e,s)}#B(e,t){this.#D(e),e.state="expired",e.session=void 0,this.#R.delete(e),this.#F.delete(e),this.#b.sessionChanged(e),this.#b.defaultUser===e&&this.#b.setDefaultUser(void 0),this.#P.warn(`${c.yellow(`The MI session of user ${e.name} ended`)} (${t}). Log in again on its host.`)}}async function Ye(e,t){try{const s=await e.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",...t},!0,{quiet:!0}),n=s.data?.user;return"number"==typeof n?.user_id?{miUser:{id:n.user_id,username:"string"==typeof n.username?n.username:""}}:{miUser:void 0}}catch(e){if(Oe(e))return{miUser:void 0,refused:Ce(e).userFriendlyMessage};throw e}}async function Qe(e,t){try{const s=await Ye(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: ${Ce(e).userFriendlyMessage}`}}}const et=/^(https?:\/\/)([^/]+)(\/.*)?$/i,tt="X-PP-Proxy";const st=/^\/login(?:\/|$)/i,nt="/auth/saml/login";const rt=/^\/auth\/(?:index\/)?logout(?:[/?#]|$)/i;const it=new WeakMap,at=new WeakMap;const ot=[/^text\//,/^application\/(?:[\w.-]+\+)?(?:json|xml)$/,/^application\/(?:x-)?(?:java|ecma)script$/,/^[\w.-]+\/[\w.-]+\+(?:json|xml)$/];function ct(e){const t=e.split(";",1)[0].trim().toLowerCase();return ot.some(e=>e.test(t))}const lt=/[\w.:/\\!-]/;function dt(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&&ct(s)}function ut(e){return async(t,s,n)=>{const r=e&&dt(t.headers);n.statusCode=t.statusCode??n.statusCode,t.statusMessage&&(n.statusMessage=t.statusMessage),n.setHeader(tt,1);for(const[e,s]of Object.entries(t.headers))void 0!==s&&(r&&"content-length"===e.toLowerCase()||n.setHeader(e,s));if(!r)return void t.pipe(n);const i=new B("utf8");let a="",o=!1;const c=s=>{if(!s)return;n.write(e(Buffer.from(s,"utf8"),"utf8"))||o||(o=!0,t.pause(),n.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(!lt.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="",n.end()}),t.on("error",()=>{n.end()})}}function pt(e){const{rewritePath:t=/^\/(?!p[tl]).*/i,baseURL:s="",disableSSLValidation:n=!1,miAPI:r,templateName:i,users:a=We}=e;if(!s)throw new Error("Base url is required");const l=function(e){try{return new URL(e).host}catch{return e.replace(et,"$2")}}(s),d=s.replace(et,"$1$2"),u=import("file-type"),p=o(),h=e.sessionUsers??new Xe(a,function(e){return async t=>(await Ye(e,{Cookie:`${Ie}=${t}`})).miUser}(r));return C({selfHandleResponse:!0,pathFilter:(s,n)=>!(e.proxyIgnore||[]).some(e=>"string"==typeof e?s.startsWith(e):"function"!=typeof e.test||e.test(s))&&("string"==typeof t?s.startsWith(t):Array.isArray(t)?t.some(e=>s.startsWith(e)):"function"==typeof t.test&&t.test(s)),target:s,changeOrigin:!0,logger:{info:()=>{},warn:()=>{},error:()=>{}},secure:!n,headers:{host:l,origin:d},on:{proxyReq(e,t,n){const o=t.headers.host,l=e.getHeader("referer");o&&l&&"string"==typeof l&&e.setHeader("referer",l.replace(function(e){let t=ae.get(e);return t||(t=new RegExp(`^https?://${re(e)}(?=[/?#]|$)`,"i"),ae.set(e,t)),t}(o),s));const d=a.resolve(t);let u;d?.user?u=d.user.token:d&&(u=r.personalAccessToken),u?(e.setHeader("Authorization",`Bearer ${u}`),it.set(t,u)):"session"===d?.user?.kind&&e.removeHeader("Authorization"),d?.user&&e.removeHeader("Token");const h="session"===d?.user?.kind?d.user:void 0;let g;if(h&&ze(t.headers.host)!==h.name){g=h.session;const s=g?(m=t.headers.cookie,f=g,[...Ke(m),`${Ie}=${f}`].join("; ")):function(e){const t=Ke(e);return t.length?t.join("; "):void 0}(t.headers.cookie);s?e.setHeader("cookie",s):e.removeHeader("cookie")}var m,f;at.set(t,{user:d?.user,sentSession:g}),e.removeHeader("if-none-match"),e.removeHeader("if-modified-since");const w=t.url??"/",v=function(e,t,s,n){if(!t||!s||!n||s===n)return e;try{const t=new y(e,"http://localhost"),r=t.pathname.match(/^\/data\/page\/([^/]+)(\/.*)?$/);if(!r)return e;let i;try{i=decodeURIComponent(r[1])}catch{i=r[1]}if(i!==s)return e;return`/data/page/${n}${r[2]??""}`+t.search+t.hash}catch{return e}}(w,r.v7Features,i,r.internalPageName);v!==w&&(t.url=v,e.path=v,console.info(`${c.cyan("Rewrites data page to correct internal page name")}: ${c.yellow(w)} ${c.blue("→")} ${c.green(v)}`)),p.info(`${c.blue("Proxies request:")} ${c.green(t.method)} ${t.url} -> ${c.green(e.method)} ${e.protocol}//${e.host}${e.path}${d?.user?` ${c.blue("as")} ${c.yellow(d.user.name)}`:""}`);const{socket:b}=t,k=()=>{setTimeout(()=>{e.destroyed||e.destroy()},200)};return b.once("close",k),e.once("close",()=>b.off("close",k)),e},proxyRes:(e,t,s)=>{s.setHeader(tt,1),e.headers["set-cookie"]&&(e.headers["set-cookie"]=Re(e.headers["set-cookie"],Ee(t))),e.headers.location&&(e.headers.location=function(e,t,s){const n=s.headers.host;let r;try{r=new URL(e)}catch{return e}return n&&/^https?:$/.test(r.protocol)&&r.host===t.toLowerCase()?e.replace(/^https?:\/\/[^/?#]*/i,`${Ee(s)?"https":"http"}://${n}`):e}(e.headers.location,l,t));const n=function(e,t){if(!rt.test(e.url??""))return;const s=ze(e.headers.host);return void 0===s?void 0:t.get(s)}(t,a),r=at.get(t);if(n){e.resume();const i={"cache-control":"no-store"};r?.user===n&&(a.remove(n.name),p.info(`${c.blue("Logged out user")} ${c.yellow(n.name)}, back to the main host`),e.headers["set-cookie"]&&(i["set-cookie"]=e.headers["set-cookie"]));const o=t.headers["sec-fetch-mode"];return o&&"navigate"!==o?s.writeHead(204,i):s.writeHead(302,{...i,location:`${qe(t)}/`}),void s.end()}const i=r?.user;let o=!0;if(i&&a.get(i.name)!==i)o=!1;else if(i){let s=!1;"session"===i.kind&&(s=h.isLeftBehindRequest(i,t,r?.sentSession),h.observe(i,t,e,r?.sentSession)),o=ze(t.headers.host)===i.name&&!s}if(!o){const t=function(e){const t=(e??[]).filter(e=>void 0===Pe(e,Ie));return t.length?t:void 0}(e.headers["set-cookie"]);t?e.headers["set-cookie"]=t:delete e.headers["set-cookie"]}e.headers["cache-control"]="no-store",delete e.headers.expires,delete e.headers.pragma;const d=(e,s)=>Buffer.from(ce(nt,"/login",oe(l,t.headers.host??"",e.toString(s))),s);if(e.headers["content-type"]?.includes("text/event-stream")||e.headers["transfer-encoding"]?.includes("chunked")&&"no"===e.headers["x-accel-buffering"])return p.info(`${c.blue("Start streaming for request:")} ${c.green(t.method)} ${t.url}`),ut(d)(e,t,s);const g=function(e){const t=e["content-type"];if("string"==typeof t&&t.trim()&&!ct(t))return"pipe";const s=Number(e["content-length"]);return Number.isFinite(s)&&s>=10485760&&dt(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 ut("stream"===g?d:void 0)(e,t,s);const m=O(async(e,t,s,n)=>{n.setHeader(tt,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")){t+=`<script>(${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 n=window.location.href;const r=function(){const i=new URLSearchParams(window.location.search);if(!i.has("proxyRedirect"))return console.debug("No proxyRedirect param. Cleaning up."),void localStorage.removeItem(e);n!==window.location.href?(n=window.location.href,setTimeout(r,s<3?3e3:5e3)):window.location.href=i.get("proxyRedirect"),localStorage.setItem(e,""+ ++s),localStorage.setItem(t,(new Date).toISOString())};setTimeout(r,3e3)}.toString()})()<\/script>`}const n=t.slice(0,100);st.test(e.pathname)&&(n.includes("<html")||n.includes("<body")||n.includes("<head")||n.includes("html>"))&&!ze(s.headers.host)&&(t+=`<script>(${Le.toString()})(${r=l,JSON.stringify(r).replace(/</g,"\\u003c")})<\/script>`)}catch{}const n=s.headers.host??"";return ce(nt,"/login",oe(l,n,t))}var r});return m(e,t,s)},error(e,t,s){!function(e,t,s,n){const r=`Proxy error: "${e.message}" when trying to "${t.method} ${t.url}"`;if(n(`${r}\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(r)))}(e,t,s,e=>p.error(e))}}})}const ht=/\.(?:[a-z0-9]+)$/i,gt=6e5,mt=104857600,ft=1e3,yt=10485760;const wt=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=gt){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)}}(mt,ft),vt=new Set,bt=new Map;function kt(e){wt.clear(),bt.clear(),vt.forEach(e=>e()),o().info(c.blue(`Proxy cache cleared: ${e}`))}const $t=new WeakSet;function xt(e,t){return t?e.startsWith(`@${t}@`):!e.startsWith("@")}function St(e,t){if(e){for(const t of wt.keys())xt(t,e)&&wt.del(t);bt.delete(e),o().info(c.blue(`Proxy cache cleared for ${e}: ${t}`))}else kt(t)}function At(e,t,s){const n=function(e){return it.get(e)}(e);if(void 0!==n){const e=bt.get(s),t=void 0!==e&&n!==e;return bt.set(s,n),t?"personal access token changed":void 0}const r=Pe(t.getHeader("set-cookie"),Ie);return void 0!==r&&r!==Ne(e.headers.cookie,Ie)?"MI session changed":void 0}function Et(e){if(0===e.length)return Buffer.alloc(0);if(1===e.length)return e[0];const t=e.reduce((e,t)=>Buffer.byteLength(t)+e,0);return Buffer.concat(e,t)}function Tt(e){const{devServer:t,ttl:s=gt,maxSize:n=mt,maxItems:r=ft,users:i=We}=e,a=o();return n===mt&&r===ft||(wt.maxSize=n,wt.maxItems=r),t.cache=wt,$t.has(i)||($t.add(i),i.onRemove(e=>St(e.name,"user removed")),i.onSessionChange(e=>St(e.name,"MI session changed or ended"))),(e,t,n)=>{const r=i.resolve(e);if(!r)return n();t.once("finish",()=>{const s=t.hasHeader(tt)?At(e,t,r.key):void 0;s&&St(r.key,`${s} (${e.method} ${de(e.url??"")})`)});const l=r.user?.session,d=e.originalUrl||e.url||"",u="GET"===e.method?function(e,t,s){const n=e.split("?")[0];return ht.test(n)?n.includes("/auth/info.js")?"":t?`@${t}@${s}:${e}`:`${s}:${e}`:""}(d,r.key,e.headers.host??""):"";if(!u||!function(e,t){const{user:s}=t;return"session"!==s?.kind||!!s.session&&(ze(e.headers.host)!==s.name||Ne(e.headers.cookie,Ie)===s.session)}(e,r))return n();const p=wt.get(u);if(p)return a.info(`${c.blue("Proxies request:")} ${c.green(e.method)} ${d} -> ${c.blue("Cache")} ${u}`),function(e,t){try{for(const[s,n]of Object.entries(t))null!=n&&e.setHeader(s,n)}catch(e){o().warn(`Failed to set some response headers: ${e instanceof Error?e.message:String(e)}`)}}(t,p.headers),t.setHeader("X-PP-Cache","hit"),t.write(p.content),void t.end();const h=t.end,g=t.write,m=[];let f=0,y="undecided";const w=(e,t)=>null==e?null:"string"==typeof e?Buffer.from(e,t||"utf8"):e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf8"),v=()=>{y="pass";for(const e of m.splice(0))g.call(t,e)},b=()=>{"undecided"===y&&(t.hasHeader(tt)?!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>=yt)}(t)?v():y="buffer":y="pass")};t.write=function(e,t,s){if(b(),"pass"===y)return g.call(this,e,t,s);const n="function"==typeof t?t:s,r=w(e,"string"==typeof t?t:void 0);return r&&(m.push(r),f+=r.length),f>yt&&v(),n&&process.nextTick(n),!0},t.end=function(e,n,o){if(b(),"pass"===y)return h.call(this,e,n,o);"function"==typeof e?(o=e,e=void 0):"function"==typeof n&&(o=n,n=void 0);const d=w(e,"string"==typeof n?n:void 0);let p;d&&m.push(d);try{p=Et(m);const e=Buffer.byteLength(p);if(200===t.statusCode&&e>0&&e<yt&&function(e,t,s){return!e.user||s.get(e.key)===e.user&&e.user.session===t}(r,l,i)){const{"set-cookie":n,...r}=t.getHeaders(),i={headers:r,content:p,timestamp:Date.now(),size:e};wt.put(u,i,s),a.info(`${c.blue("[Cached]")} ${u} (${(e/1024).toFixed(1)}KB)`)}}catch(e){a.error(`Failed to cache response for ${u}: ${e}`),p=Et(m)}return h.call(this,p,o)},n()}}const It=new Map;function jt(e){const t=It.get(e);return t?Date.now()-t.timestamp>18e4?(It.delete(e),null):t.data:null}function Nt(e,t){It.set(e,{timestamp:Date.now(),data:t})}var Pt;Pt=()=>It.clear(),vt.add(Pt);let Rt=!1;function Lt(e){Rt||(Rt=!0,e.info(c.blue("Clearing proxy cache after successful login")),wt.clear())}function Ft(){Rt=!1,u.reset()}const Ct="/home?proxyRedirect=";function Ot(e){const t=e.headers??{},s=Boolean(ze(e.headers?.host));if(!s&&!We.resolve(e)?.user)return t;const{cookie:n,authorization:r,token:i,...a}=t;return s||void 0===n?a:{...a,cookie:n}}function Bt(e,t,s){const{templateLess:n=!1,miHudLess:r=!1,appId:i,base:a,appBase:l,v7Features:d}=s,p=o();if(n&&r&&void 0===i)throw new Error("Custom App ID is required when both templateLess and miHudLess are true");return async(s,o,h)=>{try{const g=!(n&&r),m=de(s.url??""),f=e.test(m),y=!f&&!m.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)}(m,l)&&function(e){const t=e.headers["sec-fetch-dest"];if("string"==typeof t)return"document"===t;const s=e.headers.accept;return"string"==typeof s&&s.includes("text/html")}(s),w=u.getState();if(!w.isAuthenticated&&!w.isRedirected&&s.url?.startsWith("/home")&&!s.url?.startsWith(Ct)){let e;p.info(c.blue("Trying to authenticate and redirect to base"));const l=t=>{e=t};try{if(g?await Dt(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:d&&a?`${a}`:`${Ct}${encodeURIComponent("/")}`},s,o,l,p):await Mt(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:d&&a?`${a}`:`${Ct}${encodeURIComponent("/")}`},s,o,l,p),o.headersSent||o.writableEnded)return;return e?h(e):(u.setRedirected(!0),p.info(c.blue("Successfully authenticated. Redirecting to base")),le(o,a??"/",302))}catch(e){if(o.headersSent||o.writableEnded)return;return h()}}if(!f&&!y)return h();if(!g){return await Mt(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:d&&a?`${a}`:`${Ct}${encodeURIComponent("/")}`},s,o,h,p)}return await Dt(t,{templateLess:n,miHudLess:r,appId:i,redirectUrl:d&&a?`${a}`:`${Ct}${encodeURIComponent("/")}`},s,o,h,p)}catch(e){return p.error(c.red(`Unexpected error in load-pp-data middleware: ${e instanceof Error?e.message:String(e)}`)),Ft(),h(e)}}}async function Mt(e,t,s,n,r,i){const{appId:a,redirectOnAuthFailure:o,redirectUrl:l}=t;if(void 0===a){const e=new Error("Custom App ID is required for page info only mode");return i.error(c.red(e.message)),r(e)}const d=Ot(s);i.info(c.green("Start loading page info"));try{const t=`pageInfo:${a}`;return jt(t)?(i.info(c.green("Page info loaded from cache")),r()):(await e.getPageInfo(a,d),Lt(i),Nt(t,{success:!0}),u.updateState({isAuthenticated:!0}),i.info(c.green("Page info loaded successfully")),r())}catch(e){return Ft(),Ut(e,o??!0,l||`${Ct}${encodeURIComponent("/")}`,n,r,i,"Page info")}}async function Dt(e,t,s,n,r,i){const{templateLess:a,appId:o,redirectOnAuthFailure:l,redirectUrl:d}=t,u=Ot(s);i.info(c.green("Start loading page data"));try{const t=`pageData:${a}:${o}`;if(jt(t))return i.info(c.green("Page data loaded from cache")),r();const s=a||void 0===o?e.getPageTemplate(u):e.getPageVariables(o,u);return await s,Lt(i),Nt(t,{success:!0}),i.info(c.green("Page data loaded successfully")),r()}catch(e){return Ft(),Ut(e,l??!0,d||`${Ct}${encodeURIComponent("/")}`,n,r,i,"Page data")}}function Ut(e,t,s,n,r,i,a){if(function(e){return null!==e&&"object"==typeof e&&Oe(e)}(e)&&(i.info(c.red(`${a} loading failed. Not authorized`)),t)){const e=`${s}`;return i.info(c.yellow(`Redirecting to: ${e}`)),le(n,e,302)}const o=e instanceof Error?e.message:String(e);return i.info(c.red(`${a} loading failed. Error: ${o}`)),r(e)}async function Ht(e){const t=new R,s=async n=>{const r=await T.readdir(n,{withFileTypes:!0});for(const i of r){const r=A.join(n,i.name);if(i.isDirectory())await s(r);else if(i.isFile()){const s=A.relative(e,r).replace(/\\/g,"/");t.file(s,await T.readFile(r))}}};return await s(e),await t.generateAsync({type:"nodebuffer",compression:"DEFLATE"})}async function _t(e,t){const s=await R.loadAsync(await T.readFile(e),{createFolders:!1}),n=A.resolve(t),r=Object.values(s.files).filter(e=>!e.name.startsWith("__MACOSX/"));for(const e of r){const t=e.unsafeOriginalName??e.name,s=A.resolve(n,t);if(s!==n&&!s.startsWith(n+A.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 T.mkdir(n,{recursive:!0});for(const e of r){const t=A.resolve(n,e.unsafeOriginalName??e.name);e.dir?await T.mkdir(t,{recursive:!0}):(await T.mkdir(A.dirname(t),{recursive:!0}),await T.writeFile(t,await e.async("nodebuffer")))}}function Vt(e,t){const s=t?.distDir;if("export"!==t?.output||!s||".next"===s)return null;const n=A.resolve(e,s,"dev","types");return E.existsSync(n)?(E.rmSync(n,{recursive:!0,force:!0}),n):null}const zt=6e5;function qt(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&&L.spawn("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore"}).on("error",()=>{})}function Wt(e,t,s,{cwd:n,env:r,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=L.spawn(t,s,{cwd:n,env:r,stdio:"inherit",detached:d});let p,h;const g=(e,t)=>{p?t||void 0===h||(clearTimeout(h),h=void 0,qt(u,"SIGKILL",d)):(p=e,t?(qt(u,"SIGTERM",d),h=setTimeout(()=>{h=void 0,qt(u,"SIGKILL",d)},o)):qt(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&&qt(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 Jt=".next";async function Zt(e,t={}){let s;try{const t=F(A.join(e,"package.json")).resolve("next/package.json");s=A.resolve(A.dirname(t),"dist/bin/next")}catch{throw new Error(`Unable to resolve the "next" binary from ${e}. Is Next.js installed?`)}const{distDir:n,...r}=t,i=Object.assign({},process.env,{NODE_ENV:"production",[p]:"1"});n?i[h]=n:delete i[h],await Wt("next build",process.execPath,[s,"build"],{...r,cwd:e,env:i})}const Kt="pageName",Gt="date",Xt=A.dirname("undefined"!=typeof __filename&&__filename||w(import.meta.url)),Yt=A.resolve(Xt,"..",".."),Qt=Buffer.from([80,75,3,4]),es=20,ts=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const ss="sync-service.meta.json",ns="BUILD-MANIFEST.json",rs="__template_variables.json";class is{root;backupFolder;backupNameTemplate;dateFormat;pageName;currentMeta=null;distZipFolder;distZipFilename;versionFileTemplate;buildInputFolder;nextBuild;maxBackups;buildTimeoutMs;metaDir;builds=new AbortController;metaLoaded;logger;constructor(e,t){this.pageName=e;const{root:s=N.cwd(),backupFolder:n="backups",distZipFolder:r=A.resolve(s,"dist-zip"),distZipFilename:i=g(this.pageName),backupNameTemplate:a=`{${Kt}}-{${Gt}}.zip`,versionFileTemplate:c="VERSION-v{packageversion}-{currentDate}.json",buildInputFolder:l,dateFormat:d=e=>e.toISOString().replace(/:/g,"-").replace(/\..*$/,""),nextBuild:u,maxBackups:p=es,buildTimeoutMs:h=zt,metaDir:f}=t||{};this.root=s,this.backupFolder=A.resolve(s,n),this.backupNameTemplate=a,this.dateFormat=d,this.distZipFolder=r,this.distZipFilename=m(i,"ZIP output file name"),this.versionFileTemplate=m(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===f?A.join(this.backupFolder,".pp-dev-meta"):A.resolve(s,f),this.logger=o(),this.metaLoaded=this.loadMeta()}stopBuilds(){this.builds.abort()}async checkMeta(){await T.mkdir(this.metaDir,{recursive:!0}),await T.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(c.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 T.readFile(A.join(this.metaDir,ss),{encoding:"utf-8"}).catch(()=>"{}")}async writeMetaFile(e){return await this.checkMeta(),await T.writeFile(A.join(this.metaDir,ss),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=A.resolve(this.backupFolder,e);try{return await T.stat(t),t}catch{return null}}backupName(e,t=new Date){return this.backupNameTemplate.replace(`{${Kt}}`,e).replace(`{${Gt}}`,this.dateFormat(t))}getBackupMeta(){return this.currentMeta}async pruneBackups(e){if(Number.isFinite(this.maxBackups))try{const t=function(e,t,s){const n=s.split(/(\d+)/).map((e,t)=>t%2==1?"\\d+":ts(e)).join(""),r=[{token:`{${Kt}}`,pattern:ts(t)},{token:`{${Gt}}`,pattern:n}].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:n}of r)i+=ts(e.slice(a,n))+s,a=n+t.length;return new RegExp(`${i}${ts(e.slice(a))}$`)}(this.backupNameTemplate,this.pageName,this.dateFormat(new Date)),s=new Set([e]),n=await T.readdir(this.backupFolder,{withFileTypes:!0}),r=(await Promise.all(n.filter(e=>e.isFile()&&t.test(e.name)).map(async e=>({name:e.name,mtimeMs:(await T.stat(A.resolve(this.backupFolder,e.name))).mtimeMs})))).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.name.localeCompare(e.name)),i=r.filter(e=>s.has(e.name)).length,a=r.filter(e=>!s.has(e.name)).slice(Math.max(0,this.maxBackups-i));for(const e of a)await T.unlink(A.resolve(this.backupFolder,e.name));a.length>0&&this.logger.info(c.gray(`[DistService] Deleted ${a.length} old backup(s), keeping the latest ${this.maxBackups}`))}catch(e){this.logger.warn(c.yellow(`[DistService] Could not delete old backups: ${e instanceof Error?e.message:String(e)}`))}}pathToPosix(e){return e.replace(/\\/g,"/")}normalizeBackupManifestPath(e){try{return m(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 T.readdir(t,{withFileTypes:!0});if(1!==e.length||!e[0]?.isDirectory())return t;t=A.join(t,e[0].name)}}async listFilesRecursive(e){const t=await T.readdir(e,{withFileTypes:!0}),s=[];for(const n of t){const t=A.join(e,n.name);n.isDirectory()?s.push(...await this.listFilesRecursive(t)):n.isFile()&&s.push(t)}return s}buildManifestChecksum(e){const t=Object.keys(e).sort().map(t=>e[t]).join("");return I.createHash("sha256").update(t).digest("hex")}buildBackupFingerprint(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("\n");return I.createHash("sha256").update(t,"utf-8").digest("hex")}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}versionFileTemplateMatcher(){const e=/\{[^}]+\}/g,t=[];let s=0,n=null;for(;n=e.exec(this.versionFileTemplate),n;){const[e]=n,r=this.versionFileTemplate.slice(s,n.index);t.push(this.escapeRegExp(r)),t.push("[^/]+"),s=n.index+e.length}const r=this.versionFileTemplate.slice(s);return t.push(this.escapeRegExp(r)),new RegExp(`^${t.join("")}$`,"i")}isTemplateVariablesBasename(e){return e===rs}async pickTemplateVariablesFromBackupZip(e,t){const s=e.find(e=>A.basename(e)===rs);if(!s)return null;const n=A.join(t,s),r=await T.readFile(n);return{relativePath:s,content:r,actualHash:I.createHash("sha256").update(r).digest("hex"),manifestHash:null}}async resolveBackupAnalysisFromZip(e){const t=await T.mkdtemp(A.join(P.tmpdir(),"pp-dev-backup-")),s=A.join(t,"backup.zip"),n=A.join(t,"extracted");try{await T.mkdir(n,{recursive:!0}),await T.writeFile(s,e),await _t(s,n);const t=await this.normalizeExtractedRootDir(n),r=(await this.listFilesRecursive(t)).map(e=>this.pathToPosix(A.relative(t,e))),i=r.filter(e=>A.basename(e)===ns);if(i.length>1)throw new Error(`Expected at most one ${ns} in backup ZIP, found ${i.length}`);const a=1===i.length?i[0]:null;let o=null;if(a){const e=A.join(t,a);if(o=JSON.parse(await T.readFile(e,"utf-8")),!(o&&"pp-dev-build-manifest"===o.manifestType&&"string"==typeof o.versionFile&&o.versionFile.trim()&&"string"==typeof o.versionFileTemplate&&o.versionFileTemplate.trim()&&"string"==typeof o.buildFingerprint&&o.buildFingerprint.trim()))throw new Error("Build manifest is missing required fields")}let l=null;if(o){const e=this.pathToPosix(o.versionFile.trim()),t=r.filter(t=>t===e),s=r.filter(t=>A.basename(t)===A.basename(e)),n=t.length>0?t:s;if(n.length>1)throw new Error(`Build manifest version file "${o.versionFile}" must resolve to exactly one file in backup ZIP, found ${n.length}`);if(1===n.length&&(l=n[0]),!0===o.compat?.versionFileRequired&&null===l)throw new Error(`Build manifest requires version file "${o.versionFile}", but it is missing in backup ZIP`)}else{const e=this.versionFileTemplateMatcher(),t=r.filter(t=>e.test(A.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&&(l=t[0])}const d={};let u=null,p=null;const h={};let g=[];if(l){const e=A.join(t,l),s=JSON.parse(await T.readFile(e,"utf-8"));if(!s?.files||"object"!=typeof s.files)throw new Error("VERSION manifest files map is missing or invalid");if("string"!=typeof s.checksum||!s.checksum)throw new Error("VERSION manifest checksum is missing or invalid");p=s.checksum;for(const[e,t]of Object.entries(s.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(d,s))throw new Error(`VERSION manifest contains duplicate normalized file path: ${s}`);d[s]=t}if(this.buildManifestChecksum(d)!==s.checksum)throw new Error("VERSION manifest checksum does not match its files map");for(const[e,s]of Object.entries(d)){const n=A.join(t,e),r=await T.readFile(n).catch(()=>null);if(!r)throw new Error(`VERSION manifest references missing file: ${e}`);const i=I.createHash("sha256").update(r).digest("hex");h[e]=i,i!==s&&g.push({relativePath:e,expected:s,actual:i}),this.isTemplateVariablesBasename(A.basename(e))&&(u={relativePath:e,content:r,actualHash:i,manifestHash:s})}g.length>0&&this.logger.warn(c.yellow(`[DistService] VERSION manifest hash mismatch for ${g.length} file(s) (confirm in UI): ${g.map(e=>e.relativePath).join(", ")}`))}const m=new Set(g.map(e=>e.relativePath)),f={},y=[];for(const e of r){if(e===a)continue;if(l&&e===l)continue;const s=A.join(t,e),n=await T.readFile(s),r=I.createHash("sha256").update(n).digest("hex");l&&Object.prototype.hasOwnProperty.call(d,e)?f[e]=m.has(e)?h[e]:d[e]:l?(f[e]="__NOT_IN_VERSION_FILE__",y.push(e)):f[e]=r}u||(u=await this.pickTemplateVariablesFromBackupZip(r,t));const w=this.buildBackupFingerprint(f);let v=null;return o&&l&&w!==o.buildFingerprint&&(v={expected:o.buildFingerprint,actual:w},this.logger.warn(c.yellow(`[DistService] Build manifest fingerprint mismatch (confirm in UI): expected ${o.buildFingerprint}, got ${w}`))),{backupFingerprint:w,unknownFiles:y,templateVariables:u,mainHash:p,allFilesInMeta:Boolean(l&&0===y.length),buildManifestMismatch:v,versionManifestHashMismatches:g}}finally{await T.rm(t,{recursive:!0,force:!0})}}async analyzeBackup(e){if(!Qt.equals(e.subarray(0,Qt.length)))throw new Error("Backup file is not a ZIP file");return await this.resolveBackupAnalysisFromZip(e)}async getPublicTemplateVariablesHash(){const e=A.resolve(this.root,"public",rs),t=await T.readFile(e).catch(()=>null);return t?I.createHash("sha256").update(t).digest("hex"):null}async readPublicTemplateVariablesFile(){const e=A.resolve(this.root,"public",rs);return await T.readFile(e).catch(()=>null)}async saveTemplateVariablesFile(e){const t=A.resolve(this.root,"public",rs);return await T.mkdir(A.dirname(t),{recursive:!0}),await T.writeFile(t,e),t}async saveBackup(e,t){const s=t??await this.analyzeBackup(e),n=s.backupFingerprint,r=await this.getLatestSavedBackup(),i=await this.meta();if(r){const{lastBackupHash:e,lastMainHash:t}=i;if(e===n)return void this.logger.info(c.yellow(`[DistService] Backup skipped: same backup fingerprint as last saved (${n.slice(0,12)}...)`));if(s.allFilesInMeta&&s.mainHash&&t===s.mainHash)return void this.logger.info(c.yellow("[DistService] Backup skipped: same VERSION manifest checksum (main hash) and all files listed in VERSION"))}const a=new Date,o=this.backupName(this.pageName,a);i.lastBackupName=o,i.lastBackupHash=n,i.lastBackupDate=a.toISOString(),s.mainHash?i.lastMainHash=s.mainHash:delete i.lastMainHash,await this.syncMeta(),await T.writeFile(A.resolve(this.backupFolder,o),e),this.logger.info(`Backup saved to ${o}`),await this.pruneBackups(o)}async buildNewAssets(){if(this.nextBuild)return await this.buildNextAssets();this.logger.info(c.cyan("[DistService] Build started"));const e=Wt("pp-dev build","node",[A.resolve(Yt,"./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=A.resolve(this.root,this.buildInputFolder);if(!await this.isDirectory(e))throw new Error(`Build input directory ${e} not found`);const t=await Ht(e);return this.throwIfStopped("pp-dev build"),t}const t=A.resolve(this.root,this.distZipFolder,this.distZipFilename);let s;try{s=await T.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:t,buildDistDir:s=t,output:n,configWrapped:r}=this.nextBuild,i=Vt(e,{output:n,distDir:t});i&&this.logger.info(c.dim(`[DistService] Removed stale dev route types: ${A.relative(e,i)}`));const a=r||s===Jt?"out":s;r||a!==t||this.logger.warn(c.yellow(`⚠️ next.config is not wrapped with withPPDev(): the sync's build exports into ${t} and removes the dev server's ${A.join(t,"dev")}; restart pp-dev next after the sync`)),this.logger.info(c.cyan("[DistService] Next.js build started")),await this.logBuild("Next.js build",Zt(e,{timeoutMs:this.buildTimeoutMs,signal:this.builds.signal,distDir:r?Jt:void 0}));const o=A.resolve(e,a);if(!await this.isDirectory(o))throw new Error(`Next.js build output directory not found: ${o}. The sync needs "output: 'export'" in next.config (static export).`);this.throwIfStopped("next build"),await S({outDir:o,packageVersion:this.nextBuild.packageVersion,versionFileTemplate:this.versionFileTemplate,packageRepositoryUrl:this.nextBuild.packageRepositoryUrl,packageBranchName:this.nextBuild.packageBranchName}),this.throwIfStopped("next build");const l=await Ht(o);return this.throwIfStopped("next build"),l}get stopped(){return this.builds.signal.aborted}throwIfStopped(e){if(this.stopped)throw new Error(`${e} was stopped`)}async logBuild(e,t){try{await t}catch(t){const s=this.builds.signal.aborted;throw this.logger.info(c.yellow(`[DistService] ${e} ${s?"stopped":"failed"}`)),t}this.logger.info(c.cyan(`[DistService] ${e} finished`))}async isDirectory(e){try{return(await T.stat(e)).isDirectory()}catch{return!1}}}const as=12e4;class os{server;opts;eventMap;logger;syncInFlight=null;syncActionResolvers=new Map;constructor(e,t){this.server=e,this.opts=t||{},this.eventMap=new Map,this.eventMap.set("info-data:request",this.onInfoDataRequest.bind(this)),this.eventMap.set("template:sync",this.onTemplateSync.bind(this)),this.eventMap.set("template:sync:action-response",this.onTemplateSyncActionResponse.bind(this)),this.eventMap.set("page-variables:reload",this.onPageVariablesReload.bind(this)),this.logger=o(),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??as)/1e3)} s.`;case"disconnected":return"Sync cancelled: the tab that started it lost its connection to the dev server.";case"shutdown":return"Sync cancelled: the dev server is shutting down."}}cancelSync(e,t){const s=this.describeSyncCancel(t);this.sendSyncResponse(e,{cancelled:!0,message:`${s} Backup was saved.`}),this.logger.info(c.yellow(s))}sendSyncResponse(e,t){e.send("template:sync:response",t)}onInfoDataRequest(e,t){t.send("info-data:response",{})}onTemplateSyncActionResponse(e){e&&"string"==typeof e.requestId&&"boolean"==typeof e.approved&&this.resolveSyncAction(e.requestId,e.approved?{approved:!0}:{approved:!1,reason:"cancelled"})}async requestSyncAction(e,t){const s=j(),n=this.opts.syncActionTimeoutMs??as;return await new Promise(r=>{const i=e=>this.resolveSyncAction(s,{approved:!1,reason:e}),a=setTimeout(()=>i("timeout"),n),{socket:o}=t,c=()=>i("disconnected");o?.once("close",c),this.syncActionResolvers.set(s,{resolve:r,timeoutId:a,cleanup:()=>o?.off("close",c)}),o&&o.readyState!==o.OPEN?i("disconnected"):t.send("template:sync:action-required",{...e,requestId:s})})}async onTemplateSync(e,t){if(this.syncInFlight)return this.logger.warn(c.yellow("Template sync requested while another one is running; ignored")),void this.sendSyncResponse(t,{error:"A template sync is already running. Wait for it to finish, or answer its dialog in the tab that started it.",code:"SYNC_IN_PROGRESS"});const s=this.runTemplateSync(e,t);this.syncInFlight=s;try{await s}finally{this.syncInFlight=null}}async runTemplateSync(e,t){if(!this.opts.distService||!this.opts.miAPI)return this.sendSyncResponse(t,{error:"Dist service or MiAPI is not defined"}),void this.logger.error(c.red("Dist service or MiAPI is not defined"));{const{distService:e,miAPI:s}=this.opts;try{if(this.server.config.clientInjectionPlugin?.v7Features){if(!s?.isV710OrHigher)return void this.sendSyncResponse(t,{error:"This feature is available only for MI v7.1.0 or higher",config:{canSync:!1}});t.send("client:config:update",{config:{canSync:!0}})}const n=await(s?.getAssets().catch(async e=>{if(b(e)){if("SESSION_EXPIRED"===Ce(e).code){this.logger.info(c.yellow("Session expired - attempting to validate credentials"));try{const e=await(s?.validateCredentials());e&&!e.isValid?(this.logger.error(c.red(`Authentication error: ${e.error}`)),this.sendSyncResponse(t,{error:e.error??"Authentication failed",code:e.code,refresh:!0})):(this.logger.info(c.yellow("Session expired")),this.sendSyncResponse(t,{error:"Session expired",code:"SESSION_EXPIRED",refresh:!0}))}catch(e){this.logger.info(c.yellow("Session expired")),this.sendSyncResponse(t,{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(c.yellow("Server in maintenance mode, VPN connection is needed or no internet connection")),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e;const n=e.response?.status;if(502===n||503===n||504===n)return this.logger.info(c.yellow(`Server in maintenance mode or unreachable (HTTP ${n}); VPN may be required`)),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e}if($e(e))return this.logger.info(c.yellow("Server in maintenance mode or non-JSON page / page-template API response (unavailable HTML body)")),this.sendSyncResponse(t,{error:"Server in maintenance mode, VPN connection is needed or no internet connection",code:"CONNECTION_ERROR"}),e;throw e}));if(n instanceof Error)return;let r;if(n){const s=await(e?.analyzeBackup(n).catch(e=>e));if(s instanceof Error)r=s;else if(s){await(e?.saveBackup(n,s));const i=0===s.unknownFiles.length&&1===s.versionManifestHashMismatches.length&&A.basename(s.versionManifestHashMismatches[0].relativePath)===rs,a=s.versionManifestHashMismatches,o=a.filter(e=>A.basename(e.relativePath)===rs),c=a.filter(e=>A.basename(e.relativePath)!==rs),l=!i&&o.length>0&&c.length>0,d=i?[]:c.map(e=>e.relativePath),u=async()=>{if(!s.templateVariables||!e)return;const{templateVariables:n}=s;if(await e.getPublicTemplateVariablesHash()!==n.actualHash){(await this.requestSyncAction({title:"Template variables (server backup)",content:"The server backup includes __template_variables.json. It differs from your local public/__template_variables.json (or that file is missing). Replace your project copy with the server backup?",confirmText:"Replace from server",cancelText:"Keep local"},t)).approved&&await e.saveTemplateVariablesFile(n.content)}};if(s.unknownFiles.length>0){const e=await this.requestSyncAction({title:"Unknown files found in backup",content:`Backup contains files not listed in VERSION: ${s.unknownFiles.join(", ")}. Continue sync or cancel?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!e.approved)return void this.cancelSync(t,e.reason)}if(l&&await u(),!i&&d.length>0){const e=40,s=d,n=s.slice(0,e),r=s.length-n.length,i=n.map(e=>`• ${e}`).join("\n"),a=r>0?`\n... and ${r} more file${1===r?"":"s"}`:"",o=await this.requestSyncAction({title:"VERSION manifest out of date",content:`These files no longer match the hashes recorded in the VERSION manifest:\n\n${i}${a}\n\nCancel sync, or override and continue using the files on disk?`,confirmText:"Override and continue",cancelText:"Cancel sync"},t);if(!o.approved)return void this.cancelSync(t,o.reason)}if(!i&&s.buildManifestMismatch&&0===s.versionManifestHashMismatches.length){const{expected:e,actual:n}=s.buildManifestMismatch,r=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: ${n.slice(0,12)}...\nContinue sync anyway?`,confirmText:"Continue sync",cancelText:"Cancel sync"},t);if(!r.approved)return void this.cancelSync(t,r.reason)}l||await u(),r=await(e?.buildNewAssets())}}else r=await(e?.buildNewAssets());if(!(r&&r instanceof Buffer))return r instanceof Error?(this.sendSyncResponse(t,{error:r.message}),void this.logger.error(c.red(r.message))):(this.sendSyncResponse(t,{error:"Failed to build new assets"}),void this.logger.error(c.red("Failed to build new assets")));{if(e.stopped)return this.sendSyncResponse(t,{error:"Sync stopped: the dev server is shutting down."}),void this.logger.warn(c.yellow("Sync stopped before the upload: the dev server is shutting down"));const n=await(s?.updateAssets(r));if("OK"===n?.status){const s=e?.getBackupMeta();this.sendSyncResponse(t,{syncedAt:(new Date).toISOString(),backupFilename:s?.lastBackupName??""}),this.logger.info(c.green("Template synced"))}else this.sendSyncResponse(t,{error:"Failed to update assets"}),this.logger.error(c.red("Failed to update assets"))}}catch(e){const s=e instanceof Error?e.message:"Template sync failed";return this.logger.error(c.red(`Template sync failed: ${s}`)),void this.sendSyncResponse(t,{error:s,code:"SYNC_FAILED"})}}}async onPageVariablesReload(e,t){const{miAPI:s}=this.opts;if(!s)return t.send("page-variables:reload:response",{error:"MiAPI is not defined"}),void this.logger.error(c.red("MiAPI is not defined"));try{const e=await s.reloadPageVariables();t.send("page-variables:reload:response",{ok:!0,count:e?e.length:0,skipped:null===e}),this.logger.info(c.green("Page variables reloaded"))}catch(e){const s=e instanceof Error?e.message:"Reload variables failed";this.logger.error(c.red(`Reload variables failed: ${s}`)),t.send("page-variables:reload:response",{error:s})}}}const cs=["text","select","multiselect","file","list","color","boolean"];function ls(e){return cs.includes(e)}const ds=["true","false","Y","N","1","0"],us=/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function ps(e,t){return e.id===t||e.text===t}function hs(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,n="string"==typeof t||"number"==typeof t?String(t):void 0;return{id:n,text:"string"==typeof s?s:n??""}}function gs(e,t,s,n){const r="select"===s.type||"multi-select"===s.type;if("string"!=typeof n&&(!r||"number"!=typeof n))return[{name:e,severity:"warning",message:`${t}: field "${s.name}" should be a string, got ${typeof n}.`}];const i=String(n);if(!i)return[];switch(s.type){case"color":return us.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 n=s.options.map(hs);return n.some(e=>ps(e,i))?[]:[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${i}" is not one of the declared options (${n.map(e=>e.text).join(", ")}).`}]}case"multi-select":{if(!Array.isArray(s.options)||!s.options.length)return[];const n=s.options.map(hs),r=i.split(",").map(e=>e.trim()).filter(e=>!n.some(t=>ps(t,e)));return r.length?[{name:e,severity:"warning",message:`${t}: field "${s.name}" value "${r.join(", ")}" is not among the declared options (${n.map(e=>e.text).join(", ")}).`}]:[]}default:return[]}}function ms(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 n=new Set(s.map(e=>e.name)),r=[];return t.forEach((t,i)=>{const a=`"${e.name}" item #${i+1}`;if("object"!=typeof t||null===t||Array.isArray(t))return void r.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?r.push(...gs(e.name,a,t,o[t.name])):r.push({name:e.name,severity:"warning",message:`${a} is missing field "${t.name}".`});const c=Object.keys(o).filter(e=>!n.has(e));c.length&&r.push({name:e.name,severity:"warning",message:`${a} has unexpected field(s) not declared in additional_options: ${c.join(", ")}.`})}),r}function fs(e,t){const s=[];switch(e.tag_type){case"boolean":ds.includes(t)||s.push({name:e.name,severity:"warning",message:`Value "${t}" is not a recognized boolean encoding (expected one of ${ds.join(", ")}).`});break;case"list":try{const n=JSON.parse(t);Array.isArray(n)?s.push(...ms(e,n)):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 n=e.additional_options.map(hs),r=("multiselect"===e.tag_type?t.split(",").map(e=>e.trim()):[t]).filter(e=>!n.some(t=>ps(t,e)));r.length&&s.push({name:e.name,severity:"warning",message:`Value "${r.join(", ")}" does not match any declared option for "${e.name}".`})}}return s}function ys(e,t){switch(e.tag_type){case"boolean":return ds.includes(t)?null:`Not a recognized boolean value ("${t}").`;case"color":return""===t||us.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 ws="/@pp-dev/variables-editor",vs=/^[A-Za-z0-9_\s-]+$/,bs="Dist service or MiAPI is not defined",ks=new WeakMap;async function $s(e){const t=await e.readPublicTemplateVariablesFile();if(!t)return null;const s=t.toString("utf-8");let n;try{n=JSON.parse(s)}catch(e){return{raw:s,schema:null,parseError:e instanceof Error?e.message:"Invalid JSON"}}return"object"!=typeof n||null===n||Array.isArray(n)||!Array.isArray(n.tags)?{raw:s,schema:null,parseError:'The root value must be a JSON object with a "tags" array.'}:{raw:s,schema:n}}async function xs(e){const t=e?(await $s(e))?.schema??null:null;return t&&{...t,tags:t.tags.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.name&&""!==e.name)}}function Ss(e,t,s){const n=ks.get(e);if(n)return void(n.deps=t);const r={deps:t};ks.set(e,r),e.get("/@api/variables/schema",async(e,t)=>{const{distService:s}=r.deps;if(!s)return void t.status(503).json({error:bs});const n=await $s(s);t.json(n?{exists:!0,...n}:{exists:!1,schema:null,raw:null})}),e.put("/@api/variables/schema",async(e,t)=>{const{distService:s}=r.deps;if(!s)return void t.status(503).json({error:bs});const n=e.body?.raw;if("string"!=typeof n)return void t.status(400).json({error:"Request body must be { raw: string }."});let i;try{i=JSON.parse(n)}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&&!ls(e.tag_type)&&c.push(`"${e.name}" has an unrecognized tag_type "${e.tag_type}".`),vs.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(n,"utf-8"))}catch(e){return void t.status(500).json({error:`Failed to write ${rs}.`,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:n}=r.deps;try{const e=await xs(s),r=await n.getLivePageVariables(),i=function(e,t){const s=(e?.tags??[]).filter(e=>"string"==typeof e?.name&&""!==e.name),n=new Map(s.map(e=>[e.name,e])),r=new Map(t.map(e=>[e.name,e.value])),i=new Set([...n.keys(),...r.keys()]);return Array.from(i).map(e=>({name:e,value:r.get(e)??n.get(e)?.default_value??""}))}(e,r);t.json({schema:e,live:r,combined:i,local:n.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:n}=r.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:n}=e;if("string"!=typeof t||!t||"string"!=typeof n)return null;s.push({name:t,value:n})}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 xs(s),r=new Map((e?.tags??[]).map(e=>[e.name,e])),a=[];for(const e of i){const t=r.get(e.name);t&&a.push(...fs(t,e.value))}let o;await n.applyPageVariables(i);try{await n.reloadPageVariables()}catch(e){o=e instanceof Error?e.message:String(e)}t.json({ok:!0,warnings:a,local:n.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}=r.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}=r.deps;try{const e=await s.listPages(),n=e.find(e=>e.internal_name===s.internalPageName)??null,r=e.filter(e=>e.internal_name!==s.internalPageName).map(e=>({id:e.id,name:e.name,internal_name:e.internal_name,sameTemplate:!!n&&(null!=n.template_id?e.template_id===n.template_id:!!n.template&&e.template===n.template)}));t.json({pages:r,currentPageName:n?.name??null})}catch(e){t.status(502).json({error:"Failed to fetch the page list.",details:e instanceof Error?e.message:String(e)})}}),e.get("/@api/variables/import-plan/:pageId",async(e,t)=>{const{distService:s,miAPI:n}=r.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 xs(s),r=await n.getPageVariablesFor(i);t.json(function(e,t){const s=new Map((e?.tags??[]).map(e=>[e.name,e])),n=[],r=[];for(const e of t){const t=s.get(e.name);if(!t){r.push({name:e.name,sourceValue:e.value,reason:"Not in the current page's schema."});continue}const i=ys(t,e.value);i?r.push({name:e.name,sourceValue:e.value,reason:i}):n.push({name:e.name,sourceValue:e.value,tagType:t.tag_type||"text"})}return{importable:n,skipped:r}}(e,r))}catch(e){t.status(502).json({error:"Failed to fetch values from the selected page.",details:e instanceof Error?e.message:String(e)})}}),J(e,{path:ws,name:"variables-editor",clientDir:s,values:()=>({templateLess:String(Boolean(r.deps.miAPI.isTemplateLess))})})}const As="/@api/users",Es=new WeakMap;function Ts(e,t){const s=qe(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 Is(e,t,s,n){e.status(t).json({error:n,code:s})}function js(e){let t;try{t=JSON.parse(U.readFileSync(e,"utf-8"))}catch(t){return"ENOENT"!==t.code&&o().warn(c.yellow(`Could not read the saved users from ${e}: ${String(t)}`)),[]}const s=t&&"object"==typeof t&&!Array.isArray(t)?t.users:void 0;return(Array.isArray(s)?s:[]).filter(e=>"string"==typeof e?.name&&"string"==typeof e.token&&Boolean(e.token))}const Ns=new WeakMap,Ps=new WeakMap;function Rs(e){Ns.delete(e),Ps.get(e)?.(),Ps.delete(e)}async function Ls(e,t){const s=function(e,t,s=H.homedir()){const n=M("sha256").update(`${_.resolve(e)}\n${t.replace(/\/+$/,"")}`).digest("hex").slice(0,16);return _.join(s,".pp-dev","users",`${n}.json`)}(t.projectRoot,t.miUrl,t.homeDir),n={project:_.resolve(t.projectRoot),miUrl:t.miUrl},r=o();if(Ns.get(e)===s)return;Rs(e),Ns.set(e,s);const i=js(s);let a=!0,l=!1,d=e.list().some(e=>"token"===e.kind&&e.token);const u=new Set,p=new Set,h=()=>{const t=e.list(),i=t.filter(e=>"token"===e.kind&&e.token).map(e=>({name:e.name,token:e.token})),a=new Set(t.map(e=>e.name)),o=js(s).filter(e=>!a.has(e.name)&&!p.has(e.name));try{!function(e,t,s){const n={version:1,...s,users:t},r=`${e}.${process.pid}.tmp`;U.mkdirSync(_.dirname(e),{recursive:!0,mode:448}),U.writeFileSync(r,`${JSON.stringify(n,null,2)}\n`,{mode:384}),U.renameSync(r,e),U.chmodSync(e,384)}(s,[...i,...o],n)}catch(e){r.warn(c.yellow(`Could not save the users to ${s}: ${String(e)}`))}},g=e.onRemove(t=>{Ns.get(e)===s&&(p.add(t.name),a&&u.add(t.name))}),m=e.onChange(()=>{Ns.get(e)===s&&(a?d||=!l:h())});Ps.set(e,()=>{g(),m()});try{const n=await Promise.all(i.map(e=>t.checkToken(e.token)));if(Ns.get(e)!==s)return;i.forEach((t,s)=>{if(Ve(t.name)||e.get(t.name)||u.has(t.name))return;const i=n[s];l=!0;try{e.add({name:t.name,kind:"token",token:t.token,...i.ok?{miUser:i.miUser}:{},...!i.ok&&i.rejected?{state:"expired"}:{}})}finally{l=!1}i.ok||r.warn(c.yellow(`Restored user ${t.name}: ${i.message}`))})}finally{a=!1}d&&Ns.get(e)===s&&h(),i.length&&r.info(`${c.blue("Restored")} ${i.length} ${c.blue("saved user(s) from")} ${s}`)}function Fs(e){const t=`${_.resolve(e.projectRoot)}\n${e.miUrl.replace(/\/+$/,"")}`;We.context!==t&&(Rs(We),We.useContext(t)),e.persist?e.miAPI.personalAccessToken?Ls(We,{projectRoot:e.projectRoot,miUrl:e.miUrl,checkToken:t=>Qe(e.miAPI,t)}).catch(e=>{o().warn(c.yellow(`Could not restore the saved users: ${String(e)}`))}):o().warn(c.yellow("users.persist is on, but users need your own API token (mi.token or MI_ACCESS_TOKEN).")):Rs(We)}function Cs(e,t,s,n,r){const i={error:s};n&&(i.details=n),r&&(i.code=r),e.status(t).json(i).end()}function Os(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}}function Bs(e){const t=Number(e);return!t||Number.isNaN(t)||t<0?6e5:t}function Ms(e){return new RegExp(`^((${t=e,t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})|/)$`);var t}function Ds(e){return["/@vite","/@metricinsights","/@",e.endsWith("/")?e.slice(0,-1):e]}function Us(e){const{distService:t,miAPI:s,persistUsers:n,projectRoot:r,miUrl:i}=e,a=new os(e.server,{distService:t,miAPI:s});return function(e,t){const{miAPI:s,persistUsers:n,projectRoot:r,miUrl:i}=t,a=o(),c=(e,t,s)=>{a.error(`${s} token validation error: ${t instanceof Error?t.message:String(t)}`);const n=Ce(t),r=t?.tokenErrorInfo;if(r)return Cs(e,r.status||500,r.userFriendlyMessage,r.message,r.code),null;let i,o,c;switch(n.code){case"SESSION_EXPIRED":i=412,o="personal"===s?"Personal access token expired":"Session expired",c="personal"===s?"PAT_EXPIRED":"SESSION_EXPIRED";break;case"UNAUTHORIZED":i=401,o="Unauthorized",c="UNAUTHORIZED";break;case"FORBIDDEN":i=403,o="Access forbidden",c="FORBIDDEN";break;default:i=500,o="Internal server error",c=n.code}return Cs(e,i,o,"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.":n.userFriendlyMessage,c),null};e.post("/@api/login",async(e,t)=>{const{token:o,tokenType:l}=e.body??{};if(ze(e.headers.host))Cs(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 o&&o)if(a.info(`Attempting to validate ${String(l)} token...`),"personal"===l){if(!await s.get("/data/page/index/auth/info",{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${o}`},!0).then(e=>"number"==typeof e.data?.user?.user_id?(s.personalAccessToken=o,a.info(`Personal access token validated successfully for user ${e.data.user.user_id}`),e):(Cs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"personal")))return;kt("logged in with a personal access token"),Fs({persist:n,miAPI:s,projectRoot:r,miUrl:i}),le(t,"/",302)}else if("regular"===l){if(!await s.get("/api/user",{"Content-Type":"application/json",Accept:"application/json",Token:o},!0).then(n=>n.data?.users?.length?(s.personalAccessToken=void 0,a.info(`Regular token validated successfully for ${n.data.users.length} user(s)`),t.setHeader("set-cookie",Re(n.headers["set-cookie"],Ee(e))??""),n):(Cs(t,400,"Token expired or invalid"),null)).catch(e=>c(t,e,"regular")))return;kt("logged in with a token"),le(t,"/",302)}else Cs(t,400,"Invalid tokenType",'tokenType must be "personal" or "regular".',"INVALID_TOKEN_TYPE");else Cs(t,400,"Token is required")})}(e.internalServer,{miAPI:s,persistUsers:n,projectRoot:r,miUrl:i}),Ss(e.internalServer,{distService:t,miAPI:s}),function(e,t){const s=Es.get(e);if(s)return void(s.deps=t);const n={deps:t};Es.set(e,n);const r=o(),i=()=>n.deps.users??We;e.get(As,(e,t)=>{const s=i();t.json({available:Boolean(n.deps.miAPI.personalAccessToken),users:s.list().map(t=>Ts(t,e)),defaultUser:s.defaultUser?.name??null})}),e.put(`${As}/default`,(e,t)=>{const s=i(),n=(e.body??{}).name;if(null===n||"string"==typeof n)if(null===n||s.get(n)){try{s.setDefaultUser(n??void 0)}catch(e){return void Is(t,409,"NOT_LOGGED_IN",e instanceof Error?e.message:String(e))}r.info(`${c.blue("Default user:")} ${c.yellow(n??"the original user")}`),t.json({defaultUser:n})}else Is(t,404,"NOT_FOUND",`There is no user named "${n}"`);else Is(t,400,"INVALID_NAME","name must be a user name or null")}),e.post(As,async(e,t)=>{const{miAPI:s}=n.deps,a=i(),o=e.body??{},l="string"==typeof o.name?o.name:"",d="string"==typeof o.token?o.token.trim():"",u=o.kind??"token";if("token"!==u&&"session"!==u)return void Is(t,400,"INVALID_KIND",'kind must be "token" or "session"');if(!s.personalAccessToken)return void Is(t,409,"ORIGINAL_TOKEN_REQUIRED","Adding users needs your own API token: set mi.token or MI_ACCESS_TOKEN.");const p=Ve(l);if(p)return void Is(t,400,"INVALID_NAME",p);if(a.get(l))return void Is(t,409,"NAME_TAKEN",`A user named "${l}" already exists`);if("session"===u){const s=a.add({name:l,kind:"session"});return r.info(`${c.blue("Added user")} ${c.yellow(s.name)}: log in at ${qe(e,s.name)}/login`),void t.status(201).json({user:Ts(s,e)})}if(!d)return void Is(t,400,"TOKEN_REQUIRED","The API token is required");const h=a.context,g=await Qe(s,d);if(a.context!==h||n.deps.miAPI!==s||i()!==a)return void Is(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; add the user again");if(!g.ok)return void(g.rejected?Is(t,400,"INVALID_TOKEN",g.message):Is(t,502,"MI_UNAVAILABLE",g.message));const{miUser:m}=g;let f;try{f=a.add({name:l,kind:"token",token:d,miUser:m})}catch(e){return void Is(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}r.info(`${c.blue("Added user")} ${c.yellow(f.name)} (MI user ${m.id}${m.username?`, ${m.username}`:""}) at ${qe(e,f.name)}`),t.status(201).json({user:Ts(f,e)})}),e.patch(`${As}/:name`,async(e,t)=>{const{miAPI:s}=n.deps,a=i(),o=String(e.params.name),l=a.get(o),d=e.body??{},u="string"==typeof d.name&&d.name?d.name:o,p="string"==typeof d.token?d.token.trim():"";if(!l)return void Is(t,404,"NOT_FOUND",`There is no user named "${o}"`);if("token"!==l.kind)return void Is(t,400,"NOT_EDITABLE","Only users added with an API token can be edited. Remove this user and add it again.");const h=Ve(u);if(h)return void Is(t,400,"INVALID_NAME",h);if(u!==o&&a.get(u))return void Is(t,409,"NAME_TAKEN",`A user named "${u}" already exists`);let g,m={...l,name:u};if(p&&p!==l.token){const e=a.context,r=await Qe(s,p);if(a.context!==e||n.deps.miAPI!==s||i()!==a)return void Is(t,409,"CONTEXT_CHANGED","The dev server switched to another MI instance; edit the user again");if(!r.ok)return void(r.rejected?Is(t,400,"INVALID_TOKEN",r.message):Is(t,502,"MI_UNAVAILABLE",r.message));const{state:o,...c}=m;m={...c,token:p,miUser:r.miUser}}if(a.get(o)===l)if(u!==o||m.token!==l.token){try{g=a.replace(o,m)}catch(e){return void Is(t,409,"NAME_TAKEN",e instanceof Error?e.message:String(e))}r.info(`${c.blue("Edited user")} ${c.yellow(o)}${u!==o?` → ${c.yellow(u)}`:""}${g.token!==l.token?" (new API token)":""}`),t.json({user:Ts(g,e)})}else t.json({user:Ts(l,e)});else Is(t,409,"USER_CHANGED",`The user "${o}" changed meanwhile; edit it again`)}),e.delete(`${As}/:name`,(e,t)=>{const s=String(e.params.name);i().remove(s)?(r.info(`${c.blue("Removed user")} ${c.yellow(s)}`),t.status(204).end()):Is(t,404,"NOT_FOUND",`There is no user named "${s}"`)})}(e.internalServer,{miAPI:s}),Fs({persist:n,miAPI:s,projectRoot:r,miUrl:i}),a}function Hs(e,t){const s=t instanceof Error?t.message:String(t);o().error(c.red(`Request failed: ${s}`)),e.writableEnded||e.destroyed||(e.headersSent?e.destroy():(e.statusCode=500,e.setHeader("content-type","text/plain; charset=utf-8"),e.end(s)))}function _s(e,t,s,n){let r=0;const i=a=>{if(a)return void Hs(s,a);if(r>=e.length)return void n();const o=e[r];r+=1;try{o(t,s,i)}catch(e){Hs(s,e)}};i()}function Vs(e,t){t?Hs(e,t):e.headersSent||e.writableEnded||(e.statusCode=404,e.setHeader("content-type","application/json"),e.end(JSON.stringify({error:"Not found"})))}const zs="10mb",qs=(e,t,s,n)=>{const r="number"==typeof e?.status?e.status:void 0;if(!r||r<400||r>=500||"string"!=typeof e.type||s.headersSent)return void n(e);const i="entity.too.large"===e.type?`The request body is larger than the dev server accepts (${zs}).`:`The request body could not be read: ${e.message}`;s.status(r).json({error:i})};function Ws({allowedHosts:e=[]}={}){const t=V();return t.use(f(e)),t.use(V.json({limit:zs})),t.use(V.urlencoded({extended:!0})),t.use(qs),t}function Js(e){return(e.requestBody?.byteLength??0)+(e.responseBody?.byteLength??0)+512}function Zs(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}}class Ks{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-=Js(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 D()}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 n=Js(t);for(;(this.totalSize+n>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+=n}get(e){return this.entries.get(e)}list(e){const t=e?.method?.toUpperCase(),s=e?.search?.toLowerCase(),n=e=>(!t||e.method===t)&&(!s||e.url.toLowerCase().includes(s)),r=Number.isFinite(e?.limit)?e.limit:1/0,i=[];if(r<=0)return i;if(void 0===e?.offset){for(let e=this.insertOrder.length-1;e>=this.head&&i.length<r;e-=1){const t=this.entries.get(this.insertOrder[e]);t&&n(t)&&i.push(Zs(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<r;e+=1){const t=this.entries.get(this.insertOrder[e]);t&&n(t)&&(a>0?a-=1:i.push(Zs(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}}const Gs="<redacted>",Xs=new RegExp(`(^|;\\s*)(${Ie}=)[^;]*`,"gi"),Ys=new RegExp(`^(\\s*${Ie}=)[^;]*`,"i");function Qs(e){const t={...e};if("string"==typeof t.authorization){const[e,s]=t.authorization.split(/\s+/,2);t.authorization=void 0===s?Gs:`${e} ${Gs}`}return void 0!==t.token&&(t.token=Gs),"string"==typeof t.cookie&&(t.cookie=t.cookie.replace(Xs,`$1$2${Gs}`)),t}function en(e){const t={...e},s=t["set-cookie"],n=e=>e.replace(Ys,`$1${Gs}`);return Array.isArray(s)?t["set-cookie"]=s.map(n):"string"==typeof s&&(t["set-cookie"]=n(s)),t}const tn=/^\/(?:login|auth)(?:[/?#]|$)/i,sn=/pass(?:word|wd|code)?|pwd|secret|token|otp|mfa|2fa/i;function nn(e,t){return Array.isArray(e)?e.map(e=>nn(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,s])=>sn.test(e)?(t.any=!0,[e,Gs]):[e,nn(s,t)])):e}function rn(e,t,s){if(!s)return s;if(tn.test(e))return Buffer.from(Gs);const n=(t??"").split(";",1)[0].trim().toLowerCase();try{if("application/x-www-form-urlencoded"===n){const e=new URLSearchParams(s.toString("utf8")),t=[...new Set(e.keys())].filter(e=>sn.test(e));return t.forEach(t=>e.set(t,Gs)),t.length?Buffer.from(e.toString()):s}if("application/json"===n||n.endsWith("+json")){const e={any:!1},t=nn(JSON.parse(s.toString("utf8")),e);return e.any?Buffer.from(JSON.stringify(t)):s}}catch{}return s}const an=["/@","/_next/","/__nextjs_"],on=new Set(["/favicon.ico","/installHook.js.map"]);function cn(e,t=10485760,s=We){return(n,r,i)=>{const a=n.url||"/",o=a.split("?")[0];if(an.some(e=>a.startsWith(e))||on.has(o))return void i();const c=e.allocateId(),l=s.resolve(n)?.user?.name,d=Date.now(),u=[];let p=0,h=!1;const g=n.emit.bind(n);n.emit=(e,...s)=>{if("data"===e&&!h){const e=s[0],n=Buffer.isBuffer(e)?e:Buffer.from(String(e));p+=n.byteLength,p<=t?u.push(n):(h=!0,u.length=0)}return g(e,...s)};const m=[];let f=0,y=!1;const w=r.write.bind(r),v=r.end.bind(r);function b(e,s){if(!y&&null!=e)try{const n=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+=n.byteLength,f<=t?m.push(n):(y=!0,m.length=0)}catch{}}function k(e){return"string"==typeof e[0]?e[0]:void 0}function $(){const e=r.getHeaders();return e["x-pp-proxy"]?"hit"===e["x-pp-cache"]?"proxy-cache":"proxy":"local"}let x=!1;r.write=(e,...t)=>(b(e,k(t)),w(e,...t)),r.end=(t,...s)=>("function"!=typeof t&&b(t,k(s)),function(){if(x)return;x=!0;const t=rn(a,"string"==typeof n.headers["content-type"]?n.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:n.method||"GET",url:a,statusCode:r.statusCode??null,duration:Date.now()-d,source:$(),user:l,requestHeaders:Qs(n.headers),requestBody:t,requestBodyTruncated:h,responseHeaders:en(r.getHeaders()),responseBody:s,responseBodyTruncated:y})}(),v(t,...s)),i()}}export{is as D,K as I,De as M,z as P,Ks as R,As as U,ws as V,Y as a,cn as b,Ws as c,Je as d,Vs as e,Bs as f,Os as g,Tt as h,ue as i,Ms as j,Bt as k,pt as l,Ds as m,ne as n,_t as o,Vt as p,Zt as q,_s as r,Us as s,oe as u,Ht as z};
|
|
2
|
+
//# sourceMappingURL=request-capture.middleware-VElwjU1W.js.map
|