HEX
Server: Apache
System: Linux cp4.skywebbox.com 5.14.0-503.15.1.el9_5.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Nov 28 07:25:19 EST 2024 x86_64
User: alfouzantranspor (1054)
PHP: 8.3.23
Disabled: exec,passthru,shell_exec,system
Upload Files
File: /home/alfouzantranspor/public_html/wp-content/plugins/kadence-blocks/dist/kadence-optimizer.js
(()=>{"use strict";var e={4962:(e,t,o)=>{o.d(t,{NOTICE_TYPES:()=>r,createDismissibleNotice:()=>n,createNotice:()=>s});var i=o(7723);const r={SUCCESS:"success",ERROR:"error",WARNING:"warning",INFO:"info"};function s(e,t=r.SUCCESS,o=!0,s=null){const n=document.querySelector(".wrap h1")||document.querySelector(".wrap h2")||document.querySelector(".wrap");if(!n)return void console.error("Could not find container for admin notice");let a=e;if(s&&"object"==typeof s){const t=s.message||"",o=s.code||"";t&&(a=`${e}: ${t}`),o&&(a=`${a}<br />Error Code: <code>${o}</code>`)}const c=document.createElement("div");if(c.className=`notice notice-${t}${o?" is-dismissible":""}`,c.style.transition="opacity 0.5s ease-out",c.innerHTML=`\n\t\t<p>${a}</p>\n\t\t${o?`<button type="button" class="notice-dismiss"><span class="screen-reader-text">${(0,i.__)("Dismiss this notice.")}</span></button>`:""}\n\t`,n.insertAdjacentElement("afterend",c),o){const e=c.querySelector(".notice-dismiss");e?.addEventListener("click",()=>{c.remove()})}}function n(e,t=r.SUCCESS,o=null){s(e,t,!1,o);const i=document.querySelector(".wrap h1")||document.querySelector(".wrap h2")||document.querySelector(".wrap");return i?i.nextElementSibling:null}},7723:e=>{e.exports=window.wp.i18n}},t={};function o(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i](s,s.exports,o),s.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var i in t)o.o(t,i)&&!o.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i=o(7723);const r=window.wp.hooks,s=window.wp.data,n=window.wp.url;class a extends Error{url;code;constructor(e,t,o){super(e),this.name="IframeError",this.url=t,this.code=o}}class c extends a{constructor(e){super(`Cross-domain request blocked for ${e}`,e),this.name="CrossDomainError"}}class l extends a{constructor(e,t){super(`Page load timeout after ${t}ms for ${e}`,e),this.name="LoadTimeoutError"}}class d extends a{constructor(e){super(`X-Frame-Options: DENY prevents loading ${e} in iframe`,e),this.name="XFrameDenyError"}}class p{iframe;wrapperDiv;logger;currentUrl=null;currentViewport=null;defaultTimeout;closed=!1;constructor(e,t){this.logger=e,this.defaultTimeout=t||3e4;const{iframe:o,wrapperDiv:i}=this.createIframe();this.iframe=o,this.wrapperDiv=i}createIframe(){const e=document.createElement("div");e.setAttribute("style","position: fixed; z-index: -1000; opacity: 0; top: -10000px; left: -10000px;"),document.body.appendChild(e);const t=document.createElement("iframe");return t.setAttribute("style","max-width: none; max-height: none; border: 0;"),t.setAttribute("aria-hidden","true"),t.setAttribute("sandbox","allow-same-origin allow-scripts"),t.setAttribute("credentialless","true"),e.appendChild(t),{iframe:t,wrapperDiv:e}}async setViewport(e){if(this.closed)throw new Error("Cannot set viewport on closed page");if(this.currentViewport?.width!==e.width||this.currentViewport?.height!==e.height)return new Promise(t=>{this.iframe.width=e.width.toString(),this.iframe.height=e.height.toString(),this.currentViewport=e,setTimeout(t,1)})}setHeaders(e){return Promise.reject(new Error("setHeaders is not supported in iframe adapter - iframes cannot set custom HTTP headers due to browser security restrictions"))}async goto(e,t){if(this.closed)throw new Error("Cannot navigate closed page");if(e===this.currentUrl)return;const o=t?.timeout||this.defaultTimeout;try{if(new URL(e),!this.isSameOrigin(e))throw new c(e);await this.loadPage(e,o,t?.waitUntil),this.currentUrl=e}catch(t){throw this.logger.error({err:t},`Failed to navigate to ${e}`),t}}isSameOrigin(e){try{return new URL(e).origin===window.location.origin}catch{return!1}}async loadPage(e,t,o){return new Promise((i,r)=>{const s=setTimeout(()=>{this.iframe.onload=null,this.iframe.onerror=null,r(new l(e,t))},t),n=()=>{clearTimeout(s),this.iframe.onload=null,this.iframe.onerror=null};this.iframe.onload=async()=>{try{if(n(),!this.iframe.contentDocument||!this.iframe.contentWindow)throw await this.diagnoseLoadError(e)||new c(e);o&&"load"!==o&&await this.waitForCondition(o,t),i()}catch(e){const t=e instanceof Error?e:new Error(String(e));r(t)}},this.iframe.onerror=()=>{n(),r(new a(`Failed to load ${e}`,e))},this.iframe.src=e})}async diagnoseLoadError(e){try{const t=await fetch(e,{method:"HEAD"});return"deny"===t.headers.get("x-frame-options")?.toLowerCase()?new d(e):t.ok?null:new a(`HTTP ${t.status}`,e,t.status)}catch(t){const o=t instanceof Error?t.message:String(t);return new a(`Network error: ${o}`,e)}}async waitForCondition(e,t){const o=Date.now();return new Promise((i,r)=>{const s=()=>{if(Date.now()-o>t)r(new l(this.currentUrl||"unknown",t));else try{const t=this.iframe.contentDocument;if(!t)return void setTimeout(s,100);let o;switch(e){case"domcontentloaded":o="interactive"===t.readyState||"complete"===t.readyState;break;case"networkidle":case"networkidle0":case"networkidle2":o="complete"===t.readyState;break;default:o=!0}o?i():setTimeout(s,100)}catch{setTimeout(s,100)}};s()})}evaluate(e,...t){if(this.closed)return Promise.reject(new Error("Cannot evaluate on closed page"));if(!this.iframe.contentWindow)return Promise.reject(new Error("No content window available for evaluation"));try{const o=e.toString(),i=JSON.stringify(t),r=this.iframe.contentDocument.createElement("script");r.textContent=`\n                window.__iframeResult = (${o}).apply(this, ${i});\n            `,this.iframe.contentDocument.head.appendChild(r);const s=this.iframe.contentWindow.__iframeResult;return r.remove(),delete this.iframe.contentWindow.__iframeResult,Promise.resolve(s)}catch(e){const t=e instanceof Error?e.message:String(e);return this.logger.error({err:e},"Failed to evaluate script in iframe"),Promise.reject(new Error(`Evaluation failed: ${t}`))}}close(){return this.closed||(this.closed=!0,this.iframe.remove(),this.wrapperDiv.remove(),this.currentUrl=null,this.currentViewport=null),Promise.resolve()}}class u{logger;config;pages=new Set;constructor(e,t={}){this.logger=e,this.config={defaultViewport:{desktop:{width:1920,height:1080,deviceScaleFactor:1},mobile:{width:412,height:823,deviceScaleFactor:1.8,isMobile:!0,hasTouch:!0}},defaultHeaders:{"Accept-Language":"en-US,en;q=0.9",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},defaultNavigationOptions:{waitUntil:"domcontentloaded",timeout:3e4},...t}}createPage(){try{const e=new p(this.logger,this.config.defaultNavigationOptions?.timeout);return this.pages.add(e),Promise.resolve(e)}catch(e){this.logger.error({err:e},"Failed to create iframe page");const t=e instanceof Error?e:new Error(String(e));return Promise.reject(t)}}async createDesktopPage(){const e=await this.createPage();return await e.setViewport(this.config.defaultViewport.desktop),e}async createMobilePage(){const e=await this.createPage();return await e.setViewport(this.config.defaultViewport.mobile),e}async close(){const e=Array.from(this.pages).map(e=>e.close().catch(e=>this.logger.error({err:e},"Error closing iframe page")));await Promise.all(e),this.pages.clear()}static create(e,t){return"undefined"==typeof window||"undefined"==typeof document?Promise.reject(new Error("Iframe browser service can only be used in browser environments")):Promise.resolve(new u(e,t))}}class m{browserService;logger;collectors=[];postProcessors=[];constructor(e,t){this.browserService=e,this.logger=t}registerCollector(e){this.collectors.push(e)}registerPostProcessor(e){this.postProcessors.push(e)}async collect(e){const t=await this.browserService.createDesktopPage(),o=await this.browserService.createMobilePage(),i={desktop:{criticalImages:[],backgroundImages:[],sections:[],images:[]},mobile:{criticalImages:[],backgroundImages:[],sections:[],images:[]},images:[]};try{await Promise.all([this.runProcessors(t,"desktop",e,i),this.runProcessors(o,"mobile",e,i)])}catch(e){this.logger.error({err:e},"Error collecting critical data")}finally{await Promise.all([t.close(),o.close()])}let r=i;for(const e of this.postProcessors)r=await e.process(r);return r}async runProcessors(e,t,o,i){let r={width:1920,height:940};"mobile"===t&&(r={width:412,height:823,isMobile:!0,hasTouch:!0,deviceScaleFactor:1.8}),await e.setViewport(r),await e.goto(o,{waitUntil:"load",timeout:3e4});for(const o of this.collectors){const s=await o.process(e,r);this.logger.debug({collector:s},`Collector Data ${t}`),(i[t].backgroundImages??=[]).push(...s.backgroundImages??[]),(i[t].sections??=[]).push(...s.sections??[]),(i[t].images??=[]).push(...s.images??[])}}}class h{name="Section";async process(e,t){return e.evaluate(e=>{const t=Array.from(document.querySelectorAll(["main","article","section","footer",'div[class*="section"]','div[class*="container"]','div[class*="wrapper"]','div[class*="content"]','div[class*="block"]','div[class*="module"]','div[role="main"]','div[role="article"]','div[role="complementary"]','div[role="contentinfo"]'].join(","))),o=e.height,i=3*e.height,r=e=>{const t=[];let o=!0;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let i=e.nodeName.toLowerCase(),r=!1;if(e.id)i+=`#${e.id}`,r=!0;else if(e.className){const t=e.className.trim().split(/\s+/);t.length>0&&""!==t[0]&&(i+=`.${t.join(".")}`)}if("body"!==i&&"html"!==i&&t.unshift(i),r&&!o)break;e=e.parentNode,o=!1}return t.join(" > ")},s=e=>e.querySelectorAll("img, picture").length>0,n=e=>{const t=window.getComputedStyle(e);return!!t.backgroundImage&&"none"!==t.backgroundImage},a=t.filter(e=>{const t=e.tagName.toLowerCase();return"main"===t||"body"===t||"html"===t?(console.warn("⚠️ Section excluded due to tag:",t),!1):(e=>{const t=getComputedStyle(e).display;return"block"===t||"flex"===t||"grid"===t})(e)&&(e=>{const t=e.getBoundingClientRect(),o=getComputedStyle(e);return t.height>40&&t.width>40&&"none"!==o.display&&"hidden"!==o.visibility&&"0"!==o.opacity})(e)&&(e=>{const t=e.getBoundingClientRect();return t.height>=300&&t.height<=i})(e)}),c=a.filter(e=>(e=>{const t=e.getBoundingClientRect(),o=e=>{const i=getComputedStyle(e);if(parseFloat(i.marginTop)<0||parseFloat(i.marginBottom)<0||parseFloat(i.marginLeft)<0||parseFloat(i.marginRight)<0){const o=e.getBoundingClientRect();if(o.top<t.top||o.bottom>t.bottom||o.left<t.left||o.right>t.right)return!0}for(const t of Array.from(e.children))if(o(t))return!0;return!1};return o(e)})(e)),l=a.filter(e=>!c.some(t=>t===e||t.contains(e))),d=l.filter(e=>!l.some(t=>t!==e&&t.contains(e))).map(e=>{const t=e.getBoundingClientRect();return{id:e.id||"",height:t.height,tagName:e.tagName.toLowerCase(),className:e.className||"",path:r(e),isAboveFold:t.top<o,hasImages:s(e),hasBackground:n(e)}}),p=new Map;for(const e of d)p.has(e.path)||p.set(e.path,e);return{sections:Array.from(p.values())}},t)}}class g{name="BackgroundImage";async process(e,t){return e.evaluate(e=>{const t=e.height,o=[],i=document.querySelectorAll(["div","section","header","article","main","aside"].join(","));for(const e of i){const i=e.getBoundingClientRect();if(i.top>t)break;if(i.bottom<0)continue;const r=window.getComputedStyle(e).backgroundImage;if(r&&"none"!==r){const e=Array.from(r.matchAll(/url\(["']?(.*?)["']?\)/g)).map(e=>e[1]);o.push(...e)}}return{backgroundImages:o}},t)}}class f{name="Image";async process(e,t){return e.evaluate(e=>{const t=e=>{const t=[];let o=!0;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let i=e.nodeName.toLowerCase(),r=!1;if(e.id?(i+=`#${e.id}`,r=!0):e.className&&"body"!==i&&"html"!==i&&(i+=`.${e.className.split(" ").join(".")}`),"body"!==i&&"html"!==i&&t.unshift(i),r&&!o)break;e=e.parentNode,o=!1}return t.join(" > ")};return{images:Array.from(document.images).map(o=>{const i=o.getBoundingClientRect(),{width:r,height:s,objectFit:n,objectPosition:a}=getComputedStyle(o),c=o.getAttribute("width"),l=o.getAttribute("height");let d;if(o.naturalWidth&&o.naturalHeight)d=o.naturalWidth/o.naturalHeight;else if(c&&l){const e=parseInt(c,10),t=parseInt(l,10);isNaN(e)||isNaN(t)||0===t||(d=e/t)}else o.width&&o.height&&(d=o.width/o.height);return{path:t(o),src:o.getAttribute("src"),srcset:(p=o.srcset||null,p?p.split(",").map(e=>{const[t,o]=e.trim().split(" ");return{url:t,width:parseInt(o)||0}}):[]),width:o.width,height:o.height,widthAttr:c,heightAttr:l,naturalWidth:o.naturalWidth,naturalHeight:o.naturalHeight,aspectRatio:d,isAboveFold:i.top>=0&&i.top<window.innerHeight&&i.bottom>0,isMobile:e.isMobile??!1,alt:o.alt||null,class:o.className||null,loading:o.loading||null,decoding:o.decoding||null,sizes:o.sizes||null,computedStyle:{width:r,height:s,objectFit:n,objectPosition:a}};var p})}},t)}}class w{name="VideoPoster";async process(e,t){return e.evaluate(e=>{const t=e.height,o=[],i=document.querySelectorAll("video");for(const e of i){const i=e.getBoundingClientRect();if(i.top>t)break;if(i.bottom<0)continue;const r=e.getAttribute("poster");r&&o.push(r)}return{backgroundImages:o}},t)}}class b{name="CriticalImageCounter";process(e){const t=this.collectCriticalImageSources(e.desktop.images||[]),o=this.collectCriticalImageSources(e.mobile.images||[]);return{...e,desktop:{...e.desktop,criticalImages:t},mobile:{...e.mobile,criticalImages:o}}}collectCriticalImageSources(e){return e.filter(e=>e.isAboveFold&&e.src).map(e=>e.src).filter(e=>null!==e)}}class y{name="CalculateOptimalImageSizes";process(e){const t=new Map;for(const o of e.desktop.images??[])t.set(o.path??"",{desktop:o});for(const o of e.mobile.images??[])t.has(o.path??"")?t.get(o.path??"").mobile=o:t.set(o.path??"",{mobile:o});return e.images=Array.from(t.entries()).map(([,{desktop:e,mobile:t}])=>{const o=e||t,i=t||e,r=[{maxWidth:480,renderedWidth:i.width??0,renderedHeight:i.height??0},{maxWidth:900,renderedWidth:o.width??0,renderedHeight:o.height??0}];let s=1;if(o.naturalWidth&&o.naturalHeight)s=o.naturalWidth/o.naturalHeight;else if(o.widthAttr&&o.heightAttr){const e=parseInt(o.widthAttr,10),t=parseInt(o.heightAttr,10);isNaN(e)||isNaN(t)||0===t||(s=e/t)}else o.width&&o.height&&(s=o.width/o.height);const{sizes:n}=function({breakpoints:e,objectFit:t,intrinsicAspectRatio:o}){const i=(e,i)=>{if("cover"===t){const t=i*o;return Math.max(e,t)}return e},r=e.map(({maxWidth:e,renderedWidth:t,renderedHeight:o})=>`(max-width: ${e}px) ${Math.ceil(i(t,o))}px`),{renderedWidth:s,renderedHeight:n}=e[e.length-1],a=Math.ceil(i(s,n));return r.push(`${a}px`),{sizes:r.join(", ")}}({breakpoints:r,srcsetCandidates:o.srcset??[],objectFit:o.computedStyle?.objectFit??"contain",intrinsicAspectRatio:s}),a=n;return{...o,optimalSizes:a}}),e}}class E{propertiesToRemove;name="RemoveImagesFromViewports";constructor(e=["isAboveFold","isMobile"]){this.propertiesToRemove=e}process(e){const{images:t,...o}=e.desktop,{images:i,...r}=e.mobile,s=(e.images??[]).filter(e=>e.srcset&&e.srcset.length>0);for(const e of s)for(const t of this.propertiesToRemove)delete e[t];return{...e,desktop:o,mobile:r,images:s}}}class v{prefix;constructor(e="[Analyzer]"){this.prefix=e}trace(e,t){"string"==typeof e?console.debug(`${this.prefix} TRACE:`,e):console.debug(`${this.prefix} TRACE:`,t||"",e)}debug(e,t){"string"==typeof e?console.debug(`${this.prefix} DEBUG:`,e):console.debug(`${this.prefix} DEBUG:`,t||"",e)}info(e,t){"string"==typeof e?console.info(`${this.prefix} INFO:`,e):console.info(`${this.prefix} INFO:`,t||"",e)}warn(e,t){"string"==typeof e?console.warn(`${this.prefix} WARN:`,e):console.warn(`${this.prefix} WARN:`,t||"",e)}error(e,t){e instanceof Error?console.error(`${this.prefix} ERROR:`,t||"",e):"string"==typeof e?console.error(`${this.prefix} ERROR:`,e):console.error(`${this.prefix} ERROR:`,t||"",e)}fatal(e,t){e instanceof Error?console.error(`${this.prefix} FATAL:`,t||"",e):"string"==typeof e?console.error(`${this.prefix} FATAL:`,e):console.error(`${this.prefix} FATAL:`,t||"",e)}}const k="/kb-optimizer/v1/optimize",I=window.kbOptimizerL10n||{},_=window.kbOptimizer||{},S={OPTIMIZE:{class:"kb-optimize-post",text:I.runOptimizer||"Run Optimizer"},REMOVE:{class:"kb-remove-post-optimization",text:I.removeOptimization||"Remove Optimization"},OPTIMIZING:{class:"kb-optimizing",text:I.optimizing||"Optimizing"},OPTIMIZED:{text:I.optimized||"Optimized"},NOT_OPTIMIZED:{text:I.notOptimized||"Not Optimized"},EXCLUDED:{text:I.excluded||"Excluded"},NOT_OPTIMIZABLE:{text:I.notOptimizable||"Not Optimizable"}},P=window.wp.apiFetch;var N=o.n(P);async function O(e,t,o,i){if(console.log(`🎯 Analyzing post ${t}: ${e}`),"undefined"==typeof window||"undefined"==typeof document||"undefined"==typeof HTMLIFrameElement)throw console.log("❌ Performance analysis not supported in this browser"),new Error("Performance analysis not supported in this browser.");try{let r;try{r=await async function(e,t=!0,o,i){if("undefined"==typeof window||"undefined"==typeof document)throw new Error("analyzeWebsite can only be used in browser environments");let r;try{r=new URL(e)}catch{throw new Error(`Invalid URL: ${e}`)}const s=window.location.origin;if(r.origin!==s)throw new Error(`Cross-domain analysis not supported. URL origin (${r.origin}) must match current origin (${s})`);let n=e;if(t){const e=n.includes("?");n+=(e?"&":"?")+"nocache="+Math.random().toString(16).slice(2,10)}if(i){const e=n.includes("?");n+=(e?"&":"?")+"perf_token="+encodeURIComponent(i)}const a=function(e={}){return new v(e.prefix)}({prefix:o});let c;a.info({url:n},"Analyzing website");try{c=new u(a,{defaultViewport:{desktop:{width:1920,height:1080,deviceScaleFactor:1},mobile:{width:412,height:823,deviceScaleFactor:1.8,isMobile:!0,hasTouch:!0}}});const e=function({browserService:e,logger:t}){const o=new m(e,t);return o.registerCollector(new f),o.registerCollector(new g),o.registerCollector(new w),o.registerCollector(new h),o.registerPostProcessor(new b),o.registerPostProcessor(new y),o.registerPostProcessor(new E),o}({browserService:c,logger:a});return await e.collect(n)}finally{c&&await c.close()}}(e,!0,"[Kadence]",i)}catch(e){throw console.error("❌ Website analysis failed:",e),e}const s=await N()({path:k,method:"POST",data:{post_path:o,post_id:t,results:r}});return console.log(s),console.log(`βœ… Analysis complete for post ID ${t}:`,r),fetch(e+"?kadence_set_optimizer_hash=1",{credentials:"omit",keepalive:!0}).catch(e=>{console.error("❌ Failed to generate desktop hash:",e)}),fetch(e+"?kadence_set_optimizer_hash=1&kadence_is_mobile=1",{credentials:"omit",keepalive:!0}).catch(e=>{console.error("❌ Failed to generate mobile hash:",e)}),s}catch(e){throw console.error("❌ Analysis failed:",e),e}}var R=o(4962);function T(e,t){e.className=e.className.replace(S.OPTIMIZE.class,"").replace(S.REMOVE.class,"").replace(S.OPTIMIZING.class,"").trim(),e.className+=" "+t.class,e.textContent=t.text}function z(e,t){const o=e.closest("tr");return(o?o.querySelector(".row-title")?.textContent?.trim():null)||`Post ID: ${t}`}function C(e){let t=0;const o=e.textContent;return setInterval(()=>{t=(t+1)%4;const i=".".repeat(t);e.textContent=o+i},500)}function x(){(0,r.addAction)("kadence.postSaved","kadence",async({post:e,permalink:t,suffix:o=""})=>{if(console.log("Post Saved",e,t,o),!t)return void console.error("❌ No URL found for optimization. This is likely not a public post.");const r=e.id,a=t,c=(0,n.getPathAndQueryString)(t),l=_.token;if(c.includes("?"))return void console.error("❌ Unable to optimize. This is a public post, but has no rewrite rules.");const d=(0,s.select)("core/editor").getEditedPostAttribute("meta");if(void 0===d||-1!==d._kb_optimizer_status){console.log("πŸš€ Starting optimization...",{postId:r,postUrl:a,postPath:c}),console.log("%cWarnings are expected!","color: #edd144; -webkit-text-stroke: 0.5px black; font-size: 28px; font-weight: bold;");try{const t=await O(a,r,c,l);console.log(t),(0,s.dispatch)("core/notices").createSuccessNotice((0,i.__)("Kadence Optimization Data Updated.","kadence-blocks"),{type:"snackbar"}),(0,s.dispatch)("core").invalidateResolution("getEntityRecord",["postType",e.type,e.id])}catch(e){console.error("❌ Optimization failed:",e),(0,s.dispatch)("core/notices").createErrorNotice((0,i.__)("Failed to update Kadence Optimization Data.","kadence-blocks"),{type:"snackbar"})}}else console.warn(`⚠️ Post ID ${r} was excluded from optimization via post meta.`)}),document.addEventListener("click",async function(e){e.target.classList.contains("kb-optimize-post")?await async function(e){e.preventDefault();const t=e.target.dataset.postUrl,o=e.target.dataset.postPath;if(!t)return void console.error("❌ No URL found for optimization");if(!o)return void console.error("❌ No Post Path found for optimization");const r=parseInt(e.target.dataset.postId,10),s=e.target.dataset.nonce;console.log("πŸš€ Starting optimization...",{postId:r,postUrl:t}),console.log("%cWarnings are expected!","color: #edd144; -webkit-text-stroke: 0.5px black; font-size: 28px; font-weight: bold;"),T(e.target,S.OPTIMIZING);const n=C(e.target),a=z(e.target,r);try{const c=await O(t,r,o,s);console.log(c),clearInterval(n),T(e.target,S.REMOVE),(0,R.createNotice)((0,i.sprintf)(
// translators: %s: The post title or post ID.
// translators: %s: The post title or post ID.
(0,i.__)('πŸŽ‰ "%s" is now Optimized!',"kadence-blocks"),a))}catch(t){console.error("❌ Optimization failed:",t),clearInterval(n),T(e.target,S.OPTIMIZE),(0,R.createNotice)(
// translators: %s: The post title or post ID.
// translators: %s: The post title or post ID.
(0,i.sprintf)((0,i.__)('Optimization failed for "%s"',"kadence-blocks"),a),R.NOTICE_TYPES.ERROR,!0,t)}}(e):e.target.classList.contains("kb-remove-post-optimization")&&await async function(e){e.preventDefault();const t=parseInt(e.target.dataset.postId,10),o=e.target.dataset.postPath;console.log("Removing optimization...",{postId:t,postPath:o});try{const r=await async function(e,t){try{return await N()({path:k,method:"DELETE",data:{post_path:t,post_id:e}})}catch(t){throw console.error(`❌ Failed to remove optimization for post ID ${e}:`,t),t}}(t,o);console.log(r),T(e.target,S.OPTIMIZE);const s=z(e.target,t);(0,R.createNotice)((0,i.sprintf)(
// translators: %s: The post title or post ID.
// translators: %s: The post title or post ID.
(0,i.__)('Optimization data removed for "%s".',"kadence-blocks"),s))}catch(e){console.error("❌ Failed to remove optimization:",e),(0,R.createNotice)((0,i.__)("An error occurred","kadence-blocks"),R.NOTICE_TYPES.ERROR,!0,e)}}(e)})}class ${constructor(){this.intervals=new Map}start(e,t){const o=C(t);this.intervals.set(e,o)}stop(e){const t=this.intervals.get(e);t&&(clearInterval(t),this.intervals.delete(e))}stopAll(){this.intervals.forEach(e=>clearInterval(e)),this.intervals.clear()}}function A(e,t){const o=document.querySelector(`a[data-post-id="${e}"]`);return o&&T(o,t),o}async function F(e){return await N()({path:"/kb-optimizer/v1/optimize/posts-metadata",method:"POST",data:{post_ids:e}})}function D(e,t){e.forEach(e=>{const o=A(e,S.OPTIMIZING);o&&t.start(e,o)})}function M(){const e=document.querySelector("#posts-filter");e&&e.addEventListener("submit",async e=>{if(!e.submitter||"doaction"!==e.submitter.id)return;const t=document.querySelector("#bulk-action-selector-top"),o=t?t.value:null;if("kb_optimize_posts"===o||"kb_optimize_remove"===o){e.preventDefault();const t=function(){const e=document.querySelectorAll('input[name="post[]"]:checked');return Array.from(e).map(e=>parseInt(e.value,10))}();if(0===t.length)return;"kb_optimize_posts"===o?await async function(e){console.log("πŸš€ Starting bulk optimization for posts:",e);const t=new $;D(e,t);const o=(0,R.createDismissibleNotice)((0,i.sprintf)(
// translators: %d: Number of posts being optimized.
// translators: %d: Number of posts being optimized.
(0,i._n)("Optimizing %d post…","Optimizing %d posts…",e.length,"kadence-blocks"),e.length),R.NOTICE_TYPES.INFO);try{const r=await F(e),{data:s,errors:n}=r;!function(e,t){e&&0!==e.length&&e.forEach(e=>{(0,R.createNotice)(`Post ID ${e.post_id}: ${e.message}`,R.NOTICE_TYPES.ERROR,!0),t.stop(e.post_id),A(e.post_id,S.OPTIMIZE)})}(n,t);const a={successful:[],failed:[]};for(const e of s){console.log(`🎯 Optimizing post ${e.post_id}...`);try{await O(e.url,e.post_id,e.post_path,_.token),a.successful.push(e.post_id),t.stop(e.post_id),A(e.post_id,S.REMOVE)}catch(o){console.error(`❌ Failed to optimize post ${e.post_id}:`,o),a.failed.push(e.post_id),(0,R.createNotice)(`Post ID ${e.post_id}: ${o.message}`,R.NOTICE_TYPES.ERROR,!0),t.stop(e.post_id),A(e.post_id,S.OPTIMIZE)}}a.successful.length>0&&(0,R.createNotice)((0,i.sprintf)(
// translators: %d: Number of posts optimized.
// translators: %d: Number of posts optimized.
(0,i._n)("πŸŽ‰ %d post optimized successfully!","πŸŽ‰ %d posts optimized successfully!",a.successful.length,"kadence-blocks"),a.successful.length),R.NOTICE_TYPES.SUCCESS),a.failed.length>0&&(0,R.createNotice)((0,i.sprintf)(
// translators: %d: Number of posts that failed.
// translators: %d: Number of posts that failed.
(0,i._n)("Failed to optimize %d post.","Failed to optimize %d posts.",a.failed.length,"kadence-blocks"),a.failed.length),R.NOTICE_TYPES.ERROR,!0),o?.remove()}catch(e){console.error("❌ Bulk optimization failed:",e),o?.remove(),(0,R.createNotice)((0,i.__)("Failed to fetch post data for bulk optimization.","kadence-blocks"),R.NOTICE_TYPES.ERROR,!0,e)}}(t):"kb_optimize_remove"===o&&await async function(e){console.log("πŸ—‘οΈ Removing optimization for posts:",e);const t=new $;D(e,t);const o=(0,R.createDismissibleNotice)((0,i.sprintf)(
// translators: %d: Number of posts having optimization removed.
// translators: %d: Number of posts having optimization removed.
(0,i._n)("Removing optimization for %d post…","Removing optimization for %d posts…",e.length,"kadence-blocks"),e.length),R.NOTICE_TYPES.INFO);try{const r=await F(e),{data:s,errors:n}=r;if(n&&n.length>0&&n.forEach(e=>{(0,R.createNotice)(`Post ID ${e.post_id}: ${e.message}`,R.NOTICE_TYPES.ERROR,!0),t.stop(e.post_id),A(e.post_id,S.REMOVE)}),s.length>0){const e=s.map(e=>e.post_id),o=s.map(e=>e.post_path);console.log(`Removing optimization for ${e.length} posts...`);const r=await async function(e,t){return await N()({path:"/kb-optimizer/v1/optimize/bulk/delete",method:"DELETE",data:{post_ids:e,post_paths:t}})}(e,o),{data:n}=r;n.successful.forEach(e=>{t.stop(e),A(e,S.OPTIMIZE)}),n.failed&&n.failed.length>0&&n.failed.forEach(e=>{(0,R.createNotice)(`Post ID ${e.post_id}: ${e.message}`,R.NOTICE_TYPES.ERROR,!0),t.stop(e.post_id),A(e.post_id,S.REMOVE)}),n.successful.length>0&&(0,R.createNotice)((0,i.sprintf)(
// translators: %d: Number of posts.
// translators: %d: Number of posts.
(0,i._n)("Removed optimization for %d post.","Removed optimization for %d posts.",n.successful.length,"kadence-blocks"),n.successful.length),R.NOTICE_TYPES.SUCCESS),n.failed&&n.failed.length>0&&(0,R.createNotice)((0,i.sprintf)(
// translators: %d: Number of posts that failed.
// translators: %d: Number of posts that failed.
(0,i._n)("Failed to remove optimization for %d post.","Failed to remove optimization for %d posts.",n.failed.length,"kadence-blocks"),n.failed.length),R.NOTICE_TYPES.ERROR,!0)}o?.remove()}catch(e){console.error("❌ Bulk remove optimization failed:",e),o?.remove(),(0,R.createNotice)((0,i.__)("Failed to fetch post data for bulk operation.","kadence-blocks"),R.NOTICE_TYPES.ERROR,!0,e)}}(t)}})}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{x(),M()}):(x(),M()),(this.kadence=this.kadence||{})["kadence-optimizer"]={}})();