/*************************************************************************
* 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{communicate as e}from"./communicate.js";import{util as t}from"./util.js";import{analytics as o,events as n}from"../common/analytics.js";import{SETTINGS as a}from"./settings.js";import{dcLocalStorage as i,dcSessionStorage as r}from"../common/local-storage.js";import{floodgate as s}from"./floodgate.js";import{privateApi as l}from"./private-api.js";import{common as c}from"./common.js";import{userSubscription as m}from"./user-subscription.js";import{userDetailsAcrobat as d}from"./acrobatUserDetails.js";import{performSyncToAsyncStorageMigration as u,performAsyncStorageCleanup as p}from"./storage-migration.js";import{ADD_WEBPAGE_TO_PROJECT_CONTEXT_MENU_TP_CTX as g,downloadBannerExcludeList as I,LOCAL_FTE_WINDOW as h,ONE_DAY_IN_MS as f,POPUP_CONTEXT as E}from"../common/constant.js";import{CACHE_PURGE_SCHEME as w,EXPRESS as _}from"./constant.js";import{versionChecks as L}from"./handleVersionChecks.js";import{sendPingEventHandler as C,fetchCombinationOfLocalFilePromptCooldownConfig as A,fetchLocalFileAccessAndSummaryCoachmarkCooldownConfig as N}from"../common/util.js";import{loggingApi as O}from"../common/loggingApi.js";import{offscreenActions as S}from"./offscreen-actions.js";import{viewerModuleUtils as T}from"./viewer-module-utils.js";import{launchExpress as F}from"./express.js";import{toggleExpressTouchpoints as v}from"./express/express-context-menu.js";import{indexedDBScript as b}from"../common/indexDB.js";import{llmUtil as D}from"./llm-util.js";import{floodgateMigration as P}from"./floodgateMigration.js";import{removeExperimentCodeForAnalytics as R,setExperimentCodeForAnalytics as M}from"../common/experimentUtils.js";import{toggleAddWebpageToProjectContextMenu as y,handleAddWebpageToProjectContextMenu as U}from"./add-webpage-to-project.js";import x from"./dynamic-tab-context-manager.js";import{clearEventsFromLocalStorage as k}from"./analytics-event-cleanup.js";let B,W,V,j,G=new Promise(function(e){j=e}),H={},X=()=>e.getModule("acro-web2pdf"),Y=()=>e.getModule("acro-gstate"),$=["http://*/*","https://*/*"];const K=()=>(B||(B=(async()=>{let e;try{const t=`https://chromewebstore.google.com/detail/*/${chrome.runtime.id}*`,o=`https://microsoftedge.microsoft.com/addons/detail/*/${chrome.runtime.id}*`,n=new Promise(t=>{e=setTimeout(()=>t(null),1500)}),a=chrome.tabs.query({url:[t,o]}).catch(()=>null),i=await Promise.race([a,n]);return Array.isArray(i)&&(V=void 0,W=void 0,i.some(e=>{const t=new URLSearchParams(new URL(e.url).search);return!!t.has("mv")&&(V=e,W={},Array.from(t.entries()).forEach(([e,t])=>{null==W[e]&&(W[e]=t)}),!0)})),W||null}catch(e){return null}finally{e&&clearTimeout(e)}})()),B),q="Error in Local File Prompt";async function J(){!async function(){const[e,t]=await Promise.all([chrome.tabs.query({url:"https://mail.google.com/*"}),chrome.tabs.query({url:"https://drive.google.com/*"})]);e?.length>0&&o.event("DCBrowserExt:ExtensionUpdate:Gmail:Open"),t?.length>0&&o.event("DCBrowserExt:ExtensionUpdate:GDrive:Open")}();for(const e of chrome.runtime.getManifest().content_scripts){const t=await chrome.tabs.query({url:e.matches});for(const o of t)(o.url.includes("mail.google.com")||o.url.includes("drive.google.com"))&&(e.css&&chrome.scripting.insertCSS({files:e.css,target:{tabId:o.id}}),chrome.scripting.executeScript({files:e.js,target:{tabId:o.id,allFrames:e.all_frames}}))}}async function z(e,t){try{const o=e?.reason===chrome.runtime.OnInstalledReason.INSTALL,n=await s.hasFlag(`dc-cv-${t}-implicit-default-viewership`)||await s.hasFlag(`dc-cv-${t}-implicit-default-viewership-control`);if(o&&n){M({gmail:"GIDN",gdrive:"GDIN"}[t])}}catch(e){}}async function Z(e){try{if(chrome.sidePanel?.setOptions({enabled:!1}),!i.getItem("installUuid")){const e=t.generateUUID();i.setItem("installUuid",e)}e&&(e.reason===chrome.runtime.OnInstalledReason.UPDATE&&e.previousVersion!==chrome.runtime.getManifest().version?(t.verCmp(e.previousVersion,"15.1.3.30")<0&&await async function(){let e;try{const o=await chrome.tabs.query({});await Promise.allSettled(o.map(({id:e})=>chrome.scripting.executeScript({target:{tabId:e},files:["content_scripts/injectCopyLSIframe.js"]}))),await t.sleep(300),e=await chrome.runtime.sendMessage({main_op:"copy-ls"}),o.map(({id:e})=>chrome.tabs.sendMessage(e,{content_op:"remove-lsCopy"}).catch(()=>null))}catch(e){}finally{"succeed"!==e?(i.setItem("retryOnNextPage",!0),o.event(o.e.LOCAL_STORAGE_MIGRATION_FAILED)):o.event(o.e.LOCAL_STORAGE_MIGRATION_SUCCESS)}}(),i.getItem("installVersion")||i.setItem("installVersion",e.previousVersion),i.setItem("installType",e.reason),i.getItem("thirdPartyCookieChecked")&&i.removeItem("thirdPartyCookieChecked"),i.getItem("tpcBlockAnalyticsEnable")&&i.removeItem("tpcBlockAnalyticsEnable"),i.getItem("startupNewEventLastLogged")&&i.removeItem("startupNewEventLastLogged"),i.getItem("offlineSupportDisable")&&i.removeItem("offlineSupportDisable")):e.reason===chrome.runtime.OnInstalledReason.INSTALL&&(K(),i.setItem("installVersion",chrome.runtime.getManifest().version),i.setItem("installType",e.reason))),G.then(({env:t,msg:n})=>{const r=i.getItem("installSource");if(i.setItem("installSource",t.installType),z(e,"gmail"),z(e,"gdrive"),c.registerUninstallUrl(),b.clearExpiredBlobBuffers()?.catch(e=>{O.error({message:"Failed to clear old file buffer entries on startup",error:e})}),b.clearFileHashOldEntries()?.catch(e=>{O.error({message:"Failed to clear old blob cache entries on startup",error:e})}),"true"===n.repromptDone&&o.event(o.e.EXTENSION_REPROMPT_TRACKING,{REASON:e.reason,TYPE:t.installType}),e.reason===chrome.runtime.OnInstalledReason.UPDATE&&e.previousVersion!==chrome.runtime.getManifest().version)J(),P.init(),o.event(o.e.EXTENSION_UPDATE,{installReason:e.reason,previousVersion:e.previousVersion||"none"}),ie(t,!0,r);else if(e.reason===chrome.runtime.OnInstalledReason.INSTALL||e.previousVersion===chrome.runtime.getManifest().version){switch(J(),o.event(o.e.EXTENSION_INSTALLED,{installReason:e.reason,previousVersion:e.previousVersion||"none"}),o.logEventOnce(o.e.EXTENSION_INSTALLED_NEW,{storageKey:"installAnalyticsLogged",installReason:e.reason,previousVersion:e.previousVersion||"none"}),t.installType){case"admin":o.event(o.e.EXTENSION_INSTALLED_ADMIN);break;case"development":o.event(o.e.EXTENSION_INSTALLED_DEVELOPMENT);break;case"other":o.event(o.e.EXTENSION_INSTALLED_OTHER);break;case"normal":l.isInstalledViaUpsell().then(e=>{if(e)o.event(o.e.EXTENSION_INSTALLED_UPSELL);else{o.event(o.e.EXTENSION_INSTALLED_DIRECT);K().then(e=>{const t=e?.mv||"store_direct";o.event(o.e.EXTENSION_INSTALLED_SOURCE,{SOURCE:t})})}});break;case"sideload":o.event(o.e.EXTENSION_INSTALLED_SIDE_LOADED),n.installMonth&&n.installYear?o.event(o.e.EXTENSION_INSTALLED_SIDE_LOADED_MONTH_YEAR,{MONTH:n.installMonth,YEAR:n.installYear}):o.event(o.e.EXTENSION_INSTALLED_SIDE_LOADED_MONTH_YEAR,{MONTH:"None",YEAR:"None"}),a.IS_READER&&o.event(o.e.EXTENSION_INSTALLED_SIDE_LOADED_SOURCE,{SOURCE:n.source});break;default:o.event(o.e.EXTENSION_INSTALLED_DEFAULT)}ie(t)}})}catch(e){}}function Q(){try{if(navigator.onLine){const e=i.getItem("pdfViewer"),t=i.getItem("killSwitch"),n=i.getItem("cdnUrl");"false"===e&&"on"===t&&async function(e){const t=new AbortController,o=t.signal;let n=!1;setTimeout(()=>{n||t.abort()},5e3);const a=await fetch(e,{signal:o});if(n=!0,200===a.status)return await a.text();return new Error(a.statusText)}(n).then(e=>{-1===e.toString().indexOf("<meta name='killSwitch' content='off'/>")&&-1===e.toString().indexOf('<meta name="killSwitch" content="off"/>')||(i.setItem("pdfViewer",!0),l.setViewerState("enabled"),i.setItem("killSwitch","off"),o.event(o.e.VIEWER_KILL_SWITCH_OFF_SUCCESS))}).catch(e=>{o.event(o.e.VIEWER_KILL_SWITCH_OFF_FAILED)})}}catch(e){o.event(o.e.VIEWER_KILL_SWITCH_OFF_FAILED)}}function ee(e){return t&&t.isChromeOnlyMessage(e)&&t.isEdge()&&(e+="Edge"),t&&t.getTranslation?t.getTranslation(e):chrome.i18n.getMessage(e)}function te(e){return(e.title||ee("web2pdfUntitledFileName")).replace(/[<>?:|\*"\/\\'&\.]/g,"")}function oe(e,o){if(!e&&!o)return!1;try{const t=e.pageUrl||o.url,n=new URL(t);if(n.protocol&&["http:","https:"].includes(n.protocol))return!0}catch(e){t.consoleError(e)}return!1}async function ne(e,t){chrome.tabs.sendMessage(t.id,{type:"removeActionableCoachmark"}),i.setItem("touchpoint",e.touchpoint),o.event(`${o.e.OPEN_SIDE_PANEL_RECIEIVED}:${e.touchpoint||"Unspecified"}`);try{await(chrome.sidePanel?.open({tabId:t.id})),O.info({message:"Opening sidepanel success",touchpoint:e.touchpoint})}catch(t){O.error({message:"Opening sidepanel failed",error:t.toString(),touchpoint:e.touchpoint})}}function ae(e,t){C(),"convertPageContextMenu"===e.menuItemId?function(e,t){oe(e,t)&&(o.event(o.e.CONTEXT_MENU_CONVERT_PAGE),X().handleConversionRequest({tabId:t.id,caller:Y().web2pdfCaller.MENU,action:Y().web2pdfAction.CONVERT,context:Y().web2pdfContext.PAGE,url:e.pageUrl||t.url,domtitle:te(t)}))}(e,t):"appendPageContextMenu"===e.menuItemId?function(e,t){oe(e,t)&&(o.event(o.e.CONTEXT_MENU_APPEND_PAGE),X().handleConversionRequest({tabId:t.id,caller:Y().web2pdfCaller.MENU,action:Y().web2pdfAction.APPEND,context:Y().web2pdfContext.PAGE,url:e.pageUrl||t.url,domtitle:te(t)}))}(e,t):"convertLinkTargetToPDFContextMenu"===e.menuItemId?function(e,t){oe(e,t)&&(o.event(o.e.CONTEXT_MENU_CONVERT_LINK),X().handleConversionRequest({tabId:t.id,caller:Y().web2pdfCaller.MENU,action:Y().web2pdfAction.CONVERT,context:Y().web2pdfContext.LINK,url:e.linkUrl,domtitle:te(t)}))}(e,t):"appendLinkTargetToExistingPDFContextMenu"===e.menuItemId?function(e,t){oe(e,t)&&(o.event(o.e.CONTEXT_MENU_APPEND_LINK),X().handleConversionRequest({tabId:t.id,caller:Y().web2pdfCaller.MENU,action:Y().web2pdfAction.APPEND,context:Y().web2pdfContext.LINK,url:e.linkUrl,domtitle:te(t)}))}(e,t):Object.values(_.VERBS).includes(e.menuItemId.replace("ContextMenu",""))||"expressMenu"===e.menuItemId?function(e,t){if(!oe(e,t))return;const n=new URL(t.url).hostname;"expressMenu"===e.menuItemId?e.intent="editImage":e.intent=e?.menuItemId?.replace("ContextMenu",""),o.event(o.e.CONTEXT_MENU_EXPRESS_VERB,{domain:n,TARGET:e?.linkUrl?"Link":"Image",VERB:e?.intent}),i.setItem(_.CONTEXT_MENU_INTERACTION_DONE,"true"),e.touchpoint="ContextMenu",F(e,t)}(e,t):"addWebpageToProject"===e.menuItemId&&U(e,t,g)}function ie(e,n=!1,a=!1){"false"!==i.getItem("fte")&&(n&&i.getItem("pdfViewer")||(i.getItem("installTimestamp")||i.setItem("installTimestamp",Date.now()),setTimeout(()=>{chrome.storage.managed.get("OpenHelpx",async r=>{let s=!r||"false"!==r.OpenHelpx;try{const e=await K();"suppress"===e?.fte&&(s=!1,o.event(o.e.VIEWER_FTE_SUPPRESSED_VIA_STORE_PARAM,{MV:e?.mv||"unknown"}),V?.id&&V?.url&&chrome.tabs.remove(V.id).catch(()=>null))}catch(e){}o.event(s?o.e.VIEWER_FTE_OPEN_HELPX_ENABLED:o.e.VIEWER_FTE_OPEN_HELPX_DISABLED),n&&o.event(o.e.USE_ACROBAT_DEF_OWNERSHIP_ON_UPDATE),function(){try{i.getItem("pdfViewer")||(i.setItem("viewer-enabled-source","ownership-install"),i.setItem("pdfViewer","true"),l.setViewerState("enabled"),t.isEdge()?(m.initiateUserPolling(),o.event(o.e.USE_ACROBAT_IN_EDGE_AUTO_ENABLED)):o.event(o.e.USE_ACROBAT_IN_CHROME_AUTO_ENABLED))}catch(e){o.event(o.e.LOCAL_STORAGE_DISABLED)}}(),i.setItem("fte","false"),a&&(s=!1);const d=t.isEdge()&&("admin"===e.installType||"sideload"===e.installType);s&&!d&&async function(){let e=chrome.i18n.getMessage("@@ui_locale");["ca","da","en_GB","es","fi","hr","it","ko","nl","pt_BR","ru","sl","tr","zh_CN","cs","de","en_US","eu","fr","hu","ja","nb","pl","ro","sk","sv","uk","zh_TW"].includes(e)||(e="en_US");const o=t.isEdge()?"Edge":"Chrome";return`${c.getWelcomePdfUrlHost()}/dc-chrome-extension/mv/${e}/Acrobat-for-${o}.pdf`}().then(e=>t.createTab(e,e=>{const t=(new Date).getTime();H={...e,timestamp:t},chrome.tabs.onUpdated.addListener(function t(n,a){e.id==n&&"complete"===a.status&&(o.event(o.e.WELCOME_PDF_LOADED),chrome.tabs.onUpdated.removeListener(t))})}))})},2e3)))}function re(){const e="true"===i.getItem("pdfViewer")?"enabled":"disabled";l.setViewerState(e)}function se(e){const t=e.UsageMeasurement,o=t&&"false"===t.newValue?"false":"true";i.setItem("ANALYTICS_OPT_IN_ADMIN",o)}function le(){const e=i.getItem("pdfViewer");let t="neverTaken";return"true"===e?t="enabled":"false"===e&&(t="disabled"),t}async function ce(e){const t=i.getItem("localFileConfig");t?e&&!t?.localFilePermission&&function(e,t){me(t?.promptCount>0?o.e.LOCAL_FILE_PROMPT_ACCESS_ALREADY_GRANTED:o.e.LOCAL_FILE_PROMPT_NO_SHOW_ACCESS_GRANTED);t.localFilePermission=e,i.setItem("localFileConfig",t)}(e,t):async function(e){const t=await ve(),n={promptCount:0,localFilePermission:e,eligibleDate:new Date(Date.now()).toISOString()};i.setItem("localFileConfig",n),function(e){if("localFileFte"===e)return;let t;switch(e){case"localFileAccessAndSummaryCoachmark":t="LSC";break;case"combinationOfLocalFilePrompt":t="CLP";break;case"localFilePrompt":t="LFP";break;case"localFileBlockingPrompt":t="LFF";break;case"localFileFteControl":t="LFC";break;default:O.error({message:q+`setLocalFilePromptExperimentAnalyticsCode: Invalid localFileCohort ${e}`})}M(t)}(t),o.event(o.e.LOCAL_FILE_PROMPT_LANDING_IN_COHORT)}(e)}function me(e){if(!e)return;const t=new Date,n=`${t.getUTCFullYear()}${(t.getUTCMonth()+1).toString().padStart(2,"0")}`;chrome.storage.local.get([e],t=>{const a=t[e]?.lastSentYearMonth;(!a||n>a)&&(o.event(e),chrome.storage.local.set({[e]:{lastSentYearMonth:n}}))})}async function de(){try{const e=await chrome.extension.isAllowedFileSchemeAccess();await ce(e),(async()=>{await s.hasFlag("dc-cv-show-animation-on-settings",w.NO_CALL)&&M("LFS")})(),(async()=>{await s.hasFlag("dc-cv-combination-of-local-file-prompt",w.NO_CALL)?(M("CLP"),["LSC","LSC1","LSC2","LSC3"].forEach(R)):["CLP","CLP1","CLP2"].forEach(R)})(),(async()=>{await s.hasFlag("dc-cv-local-file-access-and-summary-coachmark",w.NO_CALL)?(M("LSC"),["CLP","CLP1","CLP2"].forEach(R)):["LSC","LSC1","LSC2","LSC3"].forEach(R)})();const{tabId:t,url:a}=i.getItem("localFileFteData");i.removeItem("localFileFteData");const r=i.getWithTTL("LocalFileAccessTouchpointsFromViewer");i.removeItem("LocalFileAccessTouchpointsFromViewer");const l=i.getWithTTL("downloadBanner");i.removeItem("downloadBanner");const c=i.getWithTTL("LocalFileAccessBannerChallengerTouchpointsFromViewer");i.removeItem("LocalFileAccessBannerChallengerTouchpointsFromViewer");const m=i.getWithTTL("LocalFileAccessBannerControlTouchpointsFromViewer");if(i.removeItem("LocalFileAccessBannerControlTouchpointsFromViewer"),e){try{const{url:e}=t?await chrome.tabs.get(t):{};(t&&e&&e===a||r||l)&&(r?function(e,t){o.event(n.LOCAL_FILE_ACCESS_TOUCHPOINT_PERMISSION_GRANTED),e?o.event(n.LOCAL_FILE_ACCESS_BANNER_CHALLENGER_TOUCHPOINT_PERMISSION_GRANTED):t&&o.event(n.LOCAL_FILE_ACCESS_BANNER_CONTROL_TOUCHPOINT_PERMISSION_GRANTED)}(c,m):l?await async function(){o.event(n.DOWNLOAD_BANNER_PERMISSION_GRANTED);const e=i.getItem("lastOpenTabId");await chrome.scripting.executeScript({target:{tabId:e},files:["content_scripts/injectBannerIframe.js"]}),chrome.tabs.sendMessage(e,{panel_op:"load-downloadBanner",showToast:!0}),o.event(n.DOWNLOAD_BANNER_TOAST_SHOWN),setTimeout(()=>{chrome.tabs.sendMessage(e,{content_op:"dismissBanner"})},5e3)}():o.event(n.LOCAL_FTE_PERMISSION_GRANTED),function(){const e=i.getItem("loadedTabsInfo");let t=e?.tabsInfo||[];if(t.length){const e=i.getItem("lastOpenTabId");i.removeItem("lastOpenTabId"),o.event(o.e.REOPENED_TABS_ON_LOCAL_FILE_ACCESS),t=t.sort((e,t)=>e.index-t.index);const n=[];let a={},r={};t.forEach(e=>{const t=e.url||e.pendingUrl;t.includes("file:///")||n.push(chrome.tabs.create({url:t,index:e.index,active:!1,windowId:e.windowId}))}),Promise.allSettled(n).then(o=>{o.forEach((o,n)=>{if(o.reason&&o.reason?.message?.includes("No window with id")){O.error({message:"Error in reopening tab",error:o.reason?.message});const e=t[n].windowId,i=t[n].url;a[e]=a[e]?[...a[e],i]:[i]}e&&o?.value?.id&&(r[o.value.id]=t[n].id,e===t[n].id&&setTimeout(()=>{chrome.tabs.highlight({tabs:o.value.index,windowId:o.value.windowId});const e=i.getItem("settingsWindow");e&&(chrome.tabs.remove(e?.id),i.removeItem("settingsWindow"),chrome.tabs.sendMessage(o.value.id,{content_op:"showLocalFileAccessToast",action:e?.action}))},2e3))}),i.setItem("tabIdMap",r);for(const o in a)chrome.windows.create({url:a[o],focused:!1}).then(n=>{if(e){for(const a of n.tabs){const n=a.url||a.pendingUrl;r[a.id]=t.find(e=>e.url===n&&e.windowId===Number(o))?.id,r[a.id]===e&&setTimeout(()=>{chrome.tabs.highlight({tabs:a.index,windowId:a.windowId});const e=i.getItem("settingsWindow");e&&(chrome.tabs.remove(e?.id),i.removeItem("settingsWindow"),chrome.tabs.sendMessage(a.id,{content_op:"showLocalFileAccessToast",action:e?.action}))},2e3)}i.setItem("tabIdMap",r)}})}),i.removeItem("loadedTabsInfo")}}())}catch(e){}me(n.LOCAL_FILE_PERMISSION_GRANTED),await async function(){const e=await chrome.tabs.query({url:"file:///*"});for(let t in e){const{id:o,url:n}=e[t];n.toLowerCase().endsWith(".pdf")&&chrome.tabs.reload(o)}}(),function(e,t){const o=i.getItem("settingsWindow");o&&!e&&(chrome.tabs.remove(o?.id),i.removeItem("settingsWindow"),setTimeout(()=>{t&&chrome.tabs.sendMessage(t,{content_op:"showLocalFileAccessToast",action:o?.action})},2e3))}(r,t)}else i.removeItem("loadedTabsInfo")}catch(e){O.error({message:q+`checkLocalFileAccess: Error checking local file access permissions: ${e}`})}}function ue(){const e={LEGACY:"acrobat-gsuite-touch-points",OLD:"acrobat-touch-points-in-other-surfaces",PARENT:"show-acrobat-shortcuts-master-switch",INDIVIDUAL:["acrobat-touch-point-in-gmail","acrobat-touch-point-in-gdrive","acrobat-touch-point-in-outlook","acrobat-touch-point-in-linkedin","acrobat-touch-point-in-google-docs"]},t=e=>{const t=i.getItem(e);return t&&""!==t&&null!=t};if(t(e.LEGACY)&&!t(e.OLD)&&(i.setItem(e.OLD,i.getItem(e.LEGACY)),i.removeItem(e.LEGACY)),t(e.OLD)&&!t(e.PARENT)&&!e.INDIVIDUAL.some(e=>t(e))){const t=i.getItem(e.OLD);i.setItem(e.PARENT,t),o=t,e.INDIVIDUAL.forEach(e=>i.setItem(e,o))}var o}async function pe(n){T.setCommonItems(),T.initializeViewerVariables(e.version),(async()=>{i.getItem("appLocale")||i.setItem("appLocale",i.getItem("viewer-locale")||t.getFrictionlessLocale(chrome.i18n.getMessage("@@ui_locale")))})(),ue(),l.isMimeHandlerAvailable().then(e=>{e?r.getItem("startupComplete")||t.mimeReloadAllTabs():de()}),u(),async function(){try{await s.hasFlag("dc-cv-new-preferences",w.NO_CALL)&&i.setItem("always-show-pdf-menu","true")}catch(e){console.error("Error setting always-show-pdf-menu:",e)}}(),setTimeout(re,1e4),function(){try{t.isEdge()&&i.setItem("IsRunningInEdge","true")}catch(e){}}(),async function(){if(!i.getItem("ANALYTICS_OPT_IN_ADMIN")){const e=await chrome.storage.managed.get("UsageMeasurement"),t=e&&"false"===e.UsageMeasurement?"false":"true";i.setItem("ANALYTICS_OPT_IN_ADMIN",t)}}(),async function(){const e=await chrome.storage.managed.get("DisableGenAI"),t=e&&"true"===e.DisableGenAI?"true":"false";i.setItem("DISABLE_GENAI_BY_ADMIN",t)}(),async function(){const e=await chrome.storage.managed.get("DisableWhatsNewAutoOpen"),t="true"===e?.DisableWhatsNewAutoOpen,o=i.getItem("whatsNewState")||{};i.setItem("whatsNewState",{...o,disableAutoOpenByAdmin:t})}(),k();const c=await L(),{repromptDone:m,pdfOwner:p,isAcrobatInstalled:g,isReaderInstalled:I}=c??{};s.hasFlag("dc-cv-adobe-yolo",w.NO_CALL).then(e=>{e&&a.ADOBE_YOLO_ENABLED&&!i.getWithTTL("adobe-yolo-freeze")&&d.updateUserDetails()}),j({env:n,msg:c}),D.checkAndLogGeminiNanoModel(),r.getItem("startupComplete")||(Q(),function(o){const n=0==o||1==o&&!1===e.NMHConnStatus||o==a.READER_VER||o==a.ERP_READER_VER;chrome.contextMenus.removeAll(function(){chrome.contextMenus.create({id:"addWebpageToProject",title:t.getTranslation("addWebpageToProjectContextMenuTitle"),contexts:["page"],documentUrlPatterns:$,visible:!1}),a.IS_READER||n||(chrome.contextMenus.create({id:"convertPageContextMenu",title:ee("web2pdfConvertPageContextMenu"),contexts:["page"],documentUrlPatterns:$}),chrome.contextMenus.create({id:"appendPageContextMenu",title:ee("web2pdfAppendPageContextMenu"),contexts:["page"],documentUrlPatterns:$})),v(i.getItem("express-touch-points")),y()})}(c.ver),"true"!==m&&!0!==m||o.logEventOnce(o.e.ENABLED_AFTER_READER_REPROMPT,{storageKey:"repromptAnalyticsLogged"}),setTimeout(()=>{i.getItem("firstTimeStartup")?i.setItem("firstTimeStartup","false"):i.setItem("firstTimeStartup","true"),o.event(o.e.EXTENSION_STARTUP,{ownershipStatus:le(),pdfOwner:p,isAcrobatInstalled:g,isReaderInstalled:I})},5e3),r.setItem("startupComplete",!0),async function(){if("true"!==i.getItem("pdfViewer"))return!1;const e=Date.now();let t=6048e5;const o="dc-cv-offscreen-wp-grace-period";if(!await s.hasFlag(o,w.NO_CALL))return!0;const n=s.getFeatureMeta(o);if(n)try{const e=JSON.parse(n);e.gracePeriod&&(t=parseInt(e.gracePeriod,10))}catch(e){}const a=parseInt(i.getItem("lastPdfOpenTimestamp"),10);return a?e-a<=t:(i.setItem("lastPdfOpenTimestamp",e),!0)}().then(e=>{e&&S.setupWorkerOffscreen({startup:!0})}))}function ge(e){const{id:t,timestamp:n}=H,a=(new Date).getTime();e===t&&a-n<=15e3&&o.event(o.e.WELCOME_PDF_TAB_CLOSED);const r=i.getItem("signInExperimentShown");if(r){const{currTabId:t,timestamp:n}=JSON.parse(r),s=a-n,l="true"===i.getItem("signInExperimentSuppressed");e===t&&s<=15e3&&!l&&o.event(o.e.SIGN_IN_PROMPT_TAB_CLOSED),i.removeItem("signInExperimentShown"),i.removeItem("signInExperimentSuppressed")}}const Ie=e=>{const{height:t,width:o}=h;return{height:t,width:o,top:Math.round(.5*(e.height-t)+e.top),left:Math.round(.5*(e.width-o)+e.left)}},he=e=>{const t=Math.min(Math.round(.8*e.height),900),o=Math.min(Math.round(.9*e.width),1550);return{height:t,width:o,top:Math.round(.5*(e.height-t)+e.top),left:Math.round(.5*(e.width-o)+e.left)}},fe=async({windowId:e})=>{const t=await chrome.windows.get(e);if("fullscreen"===t?.state||"locked-fullscreen"===t?.state)return;const{tabId:o,url:n}=i.getItem("localFileFteData"),[a]=await chrome.tabs.query({currentWindow:!0,active:!0}),r=i.getItem("localFteWindow");if(a&&a.id===o&&a.url===n){let{height:e,width:o,top:n,left:a}=Ie(t);"localFilePrompt"===await ve()&&({height:e,width:o,top:n,left:a}=he(t)),await chrome.windows.update(r?.id,{height:e,width:o,left:a,top:n,focused:!0})}},Ee=async e=>{const t=await ve();switch(t){case"localFileAccessAndSummaryCoachmark":Ce(e);break;case"combinationOfLocalFilePrompt":Se(e);break;case"localFilePrompt":Te(e);break;case"localFileBlockingPrompt":Fe(e);break;case"localFileFteControl":case"localFileFte":Pe(e,t);break;default:O.error({message:q+"openLocalFileFTEPrompts: No Valid local file prompt found"})}},we=e=>{const t=i.getItem("localFileConfig");return!t||!t.localFilePermission&&(e.promptLimit>t.promptCount&&t.eligibleDate<=new Date(Date.now()).toISOString())},_e=(e,t=!1)=>{try{let o=i.getItem("localFileConfig");o?t||(o.promptCount=o.promptCount+1):o={promptCount:1},o.eligibleDate=(e=>{const t=Number(e);return isNaN(t)&&O.error({message:q+`_getLocalFilePromptCooldown: cooldownConfig.settingsCoolDown must be a valid number: ${e}`}),new Date(Date.now()+t*f).toISOString()})(e),i.setItem("localFileConfig",o)}catch(e){O.error({message:q+`updateLocalFilePromptCooldown: Error updating local file prompt cooldown: ${e}`})}},Le=async()=>{let e;try{e=await s.getFeatureMeta("dc-cv-local-file-permission-prompt"),e=JSON.parse(e)}catch(t){e={promptLimit:5,ignoreCoolDown:7,settingsCoolDown:7,dismissCoolDown:7}}return e},Ce=async e=>{try{const t=i.getItem("localFileConfig")||{},n=await N();if(!we(n))return;if(!t.onceBlockingPromptShown)return["LSC2","LSC3"].forEach(R),M("LSC1"),void Ne(e,n,o.e.LOCAL_FILE_BLOCKING_SUMMARY_COMBINATION_SHOWN);if(await(async()=>{const e="false"!==i.getItem("egaf"),t="true"===i.getItem("genAIEligible"),o="true"===(await chrome.storage.managed.get("DisableGenAI"))?.DisableGenAI;return!(!e||!t||o)&&!(i.getItem("localFileConfig")||{}).summaryCoachmarkShown})())return["LSC1","LSC3"].forEach(R),M("LSC2"),Ae(e,n),void o.event(o.e.LOCAL_FILE_ACCESS_AND_SUMMARY_COACHMARK_COMBINATION_OF_PROMPT_SHOWN);["LSC1","LSC2"].forEach(R),M("LSC3");const a=i.getItem("localFileConfig");a.summaryCoachmarkShown=!1,i.setItem("localFileConfig",a),Oe(e,n,o.e.LOCAL_FILE_PROMPT_SUMMARY_COMBINATION_SHOWN)}catch(e){O.error({message:q+`openLocalFileAccessAndSummaryCoachmarkCombination: Error handling local file access and summary coachmark: ${e}`})}},Ae=async(e,t,n)=>{x.setPopupContext(e.id,e.url,E.LOCAL_FILE_ACCESS_AND_SUMMARY_COACHMARK),chrome.action.openPopup().then(()=>{i.setItem("localFileFteData",{tabId:e.id,url:e.url}),_e(t?.ignoreCoolDown);const a=i.getItem("localFileConfig");a.summaryCoachmarkShown=!0,o.event(n),i.setItem("localFileConfig",a)}).catch(e=>console.error(e))},Ne=async(e,t,n)=>{i.setItem("localFileFteData",{tabId:e.id,url:e.url}),chrome.tabs.update(e.id,{url:chrome.runtime.getURL("browser/js/local-file/local-file-blocking-page.html")}),o.event(n),_e(t?.ignoreCoolDown);const a=i.getItem("localFileConfig");a.onceBlockingPromptShown=!0,i.setItem("localFileConfig",a)},Oe=async(e,t,n)=>{const a=await chrome.windows.get(e.windowId);if(await De(a)&&!be){const{height:r,width:s,top:l,left:c}=he(a);i.setItem("localFileFteData",{tabId:e.id,url:e.url}),be=!0;const m=await chrome.windows.create({height:r,width:s,left:c,top:l,focused:e.active,type:"popup",url:chrome.runtime.getURL("browser/js/local-file/local-file-prompt.html")});o.event(n),i.setItem("localFteWindow",m),Re(m),_e(t?.ignoreCoolDown)}},Se=async e=>{try{const t=i.getItem("localFileConfig")||{},n=await A();if(!we(n))return;if(!t.onceBlockingPromptShown)return R("CLP2"),M("CLP1"),void Ne(e,n,o.e.LOCAL_FILE_BLOCKING_COMBINATION_OF_PROMPT_SHOWN);R("CLP1"),M("CLP2"),Oe(e,n,o.e.LOCAL_FILE_PROMPT_COMBINATION_OF_PROMPT_SHOWN)}catch(e){O.error({message:q+`openCombinationOfLocalFilePrompt: Error handling local PDF prompt: ${e}`})}},Te=async e=>{try{const t=await chrome.windows.get(e.windowId);if(!await De(t))return;const n=await Le();if(we(n)&&!be){const{height:a,width:r,top:s,left:l}=he(t);i.setItem("localFileFteData",{tabId:e.id,url:e.url}),be=!0;const c=await chrome.windows.create({height:a,width:r,left:l,top:s,focused:e.active,type:"popup",url:chrome.runtime.getURL("browser/js/local-file/local-file-prompt.html")});i.setItem("localFteWindow",c),o.event(o.e.LOCAL_FILE_PERMISSION_PROMPT_SHOWN),Re(c),_e(n?.ignoreCoolDown)}}catch(e){O.error({message:q+`openLocalFilePrompt: Error handling local PDF prompt: ${e}`})}},Fe=async e=>{try{const t=await(async()=>{let e;try{e=await s.getFeatureMeta("dc-cv-local-file-permission-blocking-prompt"),e=JSON.parse(e)}catch(t){O.error({message:q+`_fetchLocalFileBlockingPromptCooldownConfig: Error fetching local file prompt cooldown config: ${t}`}),e={promptLimit:1,ignoreCoolDown:1,settingsCoolDown:1,dismissCoolDown:1}}return e})();we(t)&&(i.setItem("localFileFteData",{tabId:e.id,url:e.url}),o.event(o.e.LOCAL_FILE_BLOCKING_PAGE_SHOWN),_e(t?.ignoreCoolDown),chrome.tabs.update(e.id,{url:chrome.runtime.getURL("browser/js/local-file/local-file-blocking-page.html")}))}catch(e){O.error({message:q+`openLocalFileBlockingPrompt: Error handling local PDF blocking: ${e}`})}},ve=async()=>{const[e,t,o,n,a,i]=await Promise.all([s.hasFlag("dc-cv-local-file-access-and-summary-coachmark"),s.hasFlag("dc-cv-local-file-permission-prompt"),s.hasFlag("dc-cv-local-file-permission-blocking-prompt"),s.hasFlag("dc-cv-local-file-permission-control"),s.hasFlag("dc-cv-local-file-fte"),s.hasFlag("dc-cv-combination-of-local-file-prompt")]);return e?"localFileAccessAndSummaryCoachmark":i?"combinationOfLocalFilePrompt":t?"localFilePrompt":o?"localFileBlockingPrompt":n?"localFileFteControl":a?"localFileFte":void 0};let be=!1;const De=async e=>!("fullscreen"===e?.state||"locked-fullscreen"===e?.state),Pe=async(e,n)=>{const a=await chrome.windows.get(e.windowId);if(!await De(a))return;let r,l;if((e=>{("localFileFteControl"===e&&!i.getItem("localFileConfig")||i.getItem("rc")&&!i.getItem("localFteCounterResetNew"))&&(i.removeItem("localFteCount"),i.removeItem("localFteCooldown"),i.removeItem("localFteCounterReset"),i.setItem("localFteCounterResetNew",!0))})(n),"localFileFteControl"===n){const e=i.getItem("localFteDontShowAgain");l=await(async()=>{let e;try{e=await s.getFeatureMeta("dc-cv-local-file-fte"),e=JSON.parse(e)}catch(t){O.error({message:q+`_fetchLocalFileControlPromptCooldownConfig: Error fetching local file prompt cooldown config: ${t}`}),e={promptLimit:5,ignoreCoolDown:7,settingsCoolDown:7,dismissCoolDown:7}}return e})(),r=we(l)&&!e}else r=await(async()=>{const e=t.isEdge(),o=i.getWithTTL("localFteCooldown"),n=i.getItem("localFteCount")||0,a=i.getItem("localFteDontShowAgain"),r=await chrome.extension.isAllowedFileSchemeAccess();return!(e||r||a||o||n>=20)})();if(r&&!be){const{height:t,width:r,top:s,left:c}=Ie(a);i.setItem("localFileFteData",{tabId:e.id,url:e.url}),be=!0;const m=await chrome.windows.create({height:t,width:r,left:c,top:s,focused:e.active,type:"popup",url:chrome.runtime.getURL("browser/js/local-fte.html")});o.event(o.e.LOCAL_FILE_FTE_SHOWN),"localFileFteControl"===n&&_e(l?.ignoreCoolDown),i.setItem("localFteWindow",m),Re(m)}},Re=t=>{const o=t?.tabs?.[0]?.id;o&&setTimeout(()=>{chrome.tabs.setZoom(o,1)},500),e.registerHandlers({closeLocalFte:()=>chrome.windows.remove(t.id)})},Me=async e=>{const t=i.getItem("localFteWindow");e===t?.id&&(be=!1,i.removeItem("localFteWindow"),xe())},ye=async e=>{const{tabId:t}=i.getItem("localFileFteData");if(t===e){const e=i.getItem("localFteWindow");chrome.windows.remove(e?.id)}},Ue=e=>{const t=i.getItem("isAllowedLocalFileAccess"),{filename:n,id:a}=e||{};if(n&&a){let e=i.getItem("downloadCount")||0;i.setItem("downloadCount",++e),t||chrome.downloads.search({id:a},async t=>{const{mime:n,referrer:a,finalUrl:r}=t[0],l=(a||r).split("/")[2];"application/pdf"===n&&(l===chrome.runtime.id?chrome.tabs.query({active:!0,currentWindow:!0},e=>{chrome.tabs.sendMessage(e[0].id,{main_op:"downloadFileSuccess"})}):!I.includes(l)&&e>=3&&(async()=>{if(!await s.hasFlag("dc-cv-download-banner",w.NO_CALL))return!1;i.getItem("downloadBannerFlag")||(i.setItem("downloadBannerFlag",!0),o.event(o.e.DOWNLOAD_BANNER_ENABLED));const e=i.getItem("downloadBannerData");if(e){const{count:t,lastShown:o,doNotShow:n}=e;if(n||t>=10)return!1;const a=t>=3?12096e5:864e5;if((new Date).getTime()-o<a)return!1}return!0})().then(e=>{e&&chrome.tabs.query({active:!0,currentWindow:!0},e=>{e[0]?.id&&(chrome.tabs.sendMessage(e[0].id,{panel_op:"load-downloadBanner"}),o.event(o.e.DOWNLOAD_BANNER_SHOWN),(()=>{const e=i.getItem("downloadBannerData")||{};e.count=(e.count||0)+1,e.lastShown=(new Date).getTime(),i.setItem("downloadBannerData",e),e.count>=10&&o.event(o.e.DOWNLOAD_BANNER_MAX_LIMIT_SHOWN)})())})}))})}},xe=async()=>{try{const e=await ve(),t=i.getItem("settingsWindow");if("localFilePrompt"===e&&!t){const e=await Le();_e(e?.dismissCoolDown,!0),o.event(o.e.LOCAL_FILE_PERMISSION_PROMPT_CLOSED)}}catch(e){O.error({message:q+`handleLocalFilePromptDismiss: Error updating dismiss cooldown ${e}`})}};e.registerHandlers({themeChange:()=>c.registerUninstallUrl(),reRegisterUninstallUrl:()=>c.registerUninstallUrl(),localeChange:e=>c.registerUninstallUrl({locale:e.locale}),updateLoadedTabsInfo:(e,t)=>{const o=i.getItem("loadedTabsInfo");let n=o?.tabsInfo||[];const a=t.tab;if(o.tabsInfo){const e=n.findIndex(e=>e.id==a.id);-1===e?n.push(a):n[e]={...a}}else n=[a];i.setItem("loadedTabsInfo",{tabsInfo:n})},"storage-migration-sync-to-async-cleanup":p});export{pe as startup,Z as registerActions,ge as onWelcomeTabRemoved,ae as contextMenuOnClickHandler,se as updateAnalyticsOptInAdmin,fe as refocusLocalFteWindow,ye as onLocalFileClosed,Me as onLocalFteWindowClosed,ne as startQAWithWebpage,Ue as onDownloadChanged,Ee as openLocalFileFTEPrompts,he as getLocalFilePromptDimensions};