/*************************************************************************
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2015 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by all applicable intellectual property laws,
* including trade secret and or copyright laws.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
import{analytics as e}from"../common/analytics.js";import{dcLocalStorage as t}from"../common/local-storage.js";import{loggingApi as r}from"../common/loggingApi.js";import{sendCoiEnabledEvent as a}from"../common/util.js";import{checkForImsSidCookie as o}from"../common/util.js";import{common as n}from"./common.js";import{communicate as s}from"./communicate.js";import c from"./ExplicitBlocklist.js";import{floodgate as i}from"./floodgate.js";import{createPerfTracker as m,PERF_MARKERS as d}from"./perf-tracker.js";import{cleanupUsedOrExpiredRequests as l,registerRequestId as u}from"./request-validator.js";import{util as g}from"./util.js";let p=!1;const f=new Map,h=function(){const e="abcdefghijklmnopqrstuvwxyz0123456789.-",t={};for(let r=0;r<38;r++)t[e[r]]="tubg6lxdq8jc1m9-vw.pfhskar0oi5zn372ye4"[r];return t}(),b=["documentcloud.adobe.com","acrobat.adobe.com","stage.acrobat.adobe.com","dev.acrobat.adobe.com"];async function _({url:e,domain:t}){if(!e&&!t)return!1;try{if(t||(t=new URL(e).hostname),b.includes(t))return!0;const[r=[],a=[]]=await Promise.all([c.getKWBlockList(),c.getExplicitBlocklist()]);return!![...r,...a].includes(function(e){return e.toLowerCase().split("").map(e=>h[e]||e).join("")}(t))}catch(e){return r.error({message:"Error in checking for blocked domain",error:e?.message}),!1}}function w(){!function(){const e=Date.now();f.forEach((t,r)=>{e-(t?.getStartTime?.()||0)>36e5&&f.delete(r)})}(),l()}async function E(){await t.init();if(!await i.hasFlag("dc-cv-add-webpage-to-project"))return!1;const e="false"!==t.getItem("egaf"),a="true"===t.getItem("DISABLE_GENAI_BY_ADMIN"),o=t.getItem("appLocale")||chrome.i18n.getMessage("@@ui_locale"),n=function(){const e=["en-US","en-GB"],a="true"===t.getItem("adobeInternal"),o="dc-cv-add-webpage-to-project";let n={};try{const t=JSON.parse(i.getFeatureMeta(o)||"{}");a&&(n=JSON.parse(i.getFeatureMeta(`${o}-internal`)||"{}"));const r=[...t.allowedLocales??[],...n.allowedLocales??[]];return r.length>0?r:e}catch(t){return r.error({message:"Failed to get AddWebpageToProject allowed locales:",error:t?.message}),e}}().includes(o)||o.startsWith("en");return!(!e||a||!n)}async function I(){const e=await E();try{e?p||(chrome.contextMenus.update("addWebpageToProject",{visible:!0}),p=!0):p&&(chrome.contextMenus.update("addWebpageToProject",{visible:!1}),p=!1)}catch(e){r.error({message:"Error creating AddWebpageToProject context menu",error:e?.message})}}function P(e){if(document.getElementById("addWebpageToProjectExtnIframe"))return;const{env:t,tabId:r,locale:a,requestId:o,context:n,imsca:s}=e,c=(e,t={})=>{const r={main_op:"kw-perf-mark",data:{requestId:o,name:e,metadata:t,timestamp:Date.now()}};chrome.runtime.sendMessage(r)};c("AWPP_Extension_Iframe_Creation_Started");const i=window?.matchMedia?.("(prefers-color-scheme: dark)"),m=i?.matches,d=document.createElement("iframe"),l=chrome.runtime.getURL("resources/addWebpage/index.html"),u=new URL(l);u.searchParams.set("env",t),u.searchParams.set("tabId",r),u.searchParams.set("locale",a),u.searchParams.set("requestId",o),u.searchParams.set("context",n),u.searchParams.set("theme",m?"dark":"light"),u.searchParams.set("imsca",s),d.src=u.toString(),d.id="addWebpageToProjectExtnIframe",d.allowFullscreen=!0,d.style.cssText="\n        position: fixed;\n        top: 0;\n        left: 0;\n        width: 100%;\n        height: 100%;\n        border: none;\n        z-index: 10000;\n        background: rgba(0, 0, 0, 0.1);\n        color-scheme: light;\n    ",d.onload=()=>{c("AWPP_Extension_Iframe_Loaded")},d.onerror=()=>{c("AWPP_Extension_Iframe_Error"),f()},document.body.appendChild(d),c("AWPP_Extension_Iframe_Added_To_Document");const g=new URL(chrome.runtime.getURL("resources/addWebpage/index.html")).origin,p=e=>{if(e.origin!==g)return;const{main_op:t}=e.data;switch(t){case"closeAllIframes":f();break;case"openCollectionTab":chrome.runtime.sendMessage({main_op:"openCollectionTab",data:e.data},e=>{e.closeDialog&&f()});break;case"kw-perf-mark":const{main_op:t,...r}=e.data;chrome.runtime.sendMessage({main_op:t,data:r})}};i?.addEventListener?.("change",e=>{c("AWPP_Extension_Iframe_Theme_Changed",{theme:e.matches?"dark":"light"})});const f=()=>{const e=document.getElementById("addWebpageToProjectExtnIframe");e&&(c("AWPP_Extension_Iframe_Removed"),chrome.runtime.sendMessage({main_op:"emit-perf-data",data:{requestId:o}}),window.removeEventListener("message",p),e.style.display="none",setTimeout(()=>{document.body.removeChild(e)},2e3))};window.addEventListener("message",p),window.addEventListener("beforeunload",()=>{chrome.runtime.sendMessage({main_op:"emit-perf-data",data:{requestId:o}})})}async function T(s,c,i){w();const l=new URL(c.url);a(c.id,{domain:l.hostname,expressTouchpoint:i});const g=`req_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;u(g,i);const p=m({requestId:g});f.set(g,p),p.mark(d.AWPP_CONTEXT_MENU_CLICKED),e.event(e.e.CONTEXT_MENU_ADD_WEB_PAGE_TO_PROJECT,{CONTEXT:i});const h=n.getEnv(),b=t.getItem("appLocale")||chrome.i18n.getMessage("@@ui_locale"),_=await o(),E={env:h,locale:b,requestId:g,tabId:c.id,context:i,imsca:_};try{const e=await Promise.race([chrome.scripting.executeScript({target:{tabId:c.id},func:P,args:[E]}),new Promise((e,t)=>{setTimeout(()=>{t(new Error("AddWebpageToProject Extension iframe script execution timeout"))},1e4)})]);if(!e||0===e.length)throw new Error("Script execution returned no results")}catch(e){let t=e?.message;chrome.runtime.lastError&&(t=chrome.runtime.lastError.message),p.mark(d.AWPP_EXTENSION_IFRAME_SCRIPT_EXECUTION_FAILED,{error:t}),r.error({message:"Error in executing AddWebpageToProject Extension iframe script",error:t,requestId:g})}finally{p.mark(d.AWPP_EXTENSION_IFRAME_SCRIPT_EXECUTION_COMPLETED)}}function x(e){T(0,{id:e.tabId,url:e.url},e.context)}chrome.runtime.onMessage.addListener((e,t,a)=>{const o=e?.main_op;switch(o){case"kw-perf-mark":!function(e){const t=e?.data?.requestId,r=f.get(t);r&&r.mark(e.data.name,e.data.metadata)}(e);break;case"emit-perf-data":!function(e){const t=e?.data?.requestId,a=f.get(t);if(a){const e=a.getPerfTimings();r.info({message:"AddWebpageToProject_PerfTimings",perfTimings:e}),f.delete(t)}}(e)}return!0}),s.registerHandlers({openCollectionTab:async function(e,t,a){try{const{collectionUrl:o,requestId:n,activeTab:s=!0}=e.data||{},c=new URL(o);chrome.tabs.query({url:`${c.origin}${c.pathname}*`,windowId:t?.tab?.windowId},t=>{let c=!1;t?.length>0?chrome.tabs.update(t[0].id,{active:s,url:o}):(c=!0,chrome.tabs.create({url:o,active:s})),a({success:!0,closeDialog:e.data.closeDialog}),r.info({message:"AddWebpageToProject Open project url "+(c?"in new tab":"in existing tab"),requestId:n})});await async function(e){try{const t=await chrome.scripting.executeScript({target:{tabId:e},func:async()=>"function"==typeof window.extractWebpageHTML});return t?.[0]?.result}catch(e){return!1}}(t?.tab?.id)||await chrome.scripting.executeScript({target:{tabId:t?.tab?.id},files:["content_scripts/extract-webpage-html.js"]}),chrome.scripting.executeScript({target:{tabId:t?.tab?.id},func:async()=>(await getExtractWebpageHTML(),await(window.extractWebpageHTML?.(document)))})}catch(t){r.error({message:"Error in opening collection tab",error:t?.message,...e.data})}}});export{E as isAddWebpageToProjectEnabled,I as toggleAddWebpageToProjectContextMenu,T as handleAddWebpageToProjectContextMenu,x as handleAddWebpageToProjectAction,_ as checkForBlockedDomain};