/*************************************************************************
* 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{common as e}from"./common.js";import{Proxy as t}from"./proxy.js";import{CACHE_PURGE_SCHEME as s,ADOBE_INTERNAL as r,EXPRESS as a,EXPERIMENT_VARIANTS_STORAGE_KEY as o}from"./constant.js";import{dcLocalStorage as n}from"../common/local-storage.js";import{util as i}from"./util.js";import{forceResetService as l}from"./force-reset-service.js";import{OFFSCREEN_DOCUMENT_PATH as c}from"../common/constant.js";import{analytics as g}from"../common/analytics.js";import{toggleExpressTouchpoints as u}from"./express/express-context-menu.js";import{checkForImsSidCookie as h}from"../common/util.js";import{toggleAddWebpageToProjectContextMenu as m}from"./add-webpage-to-project.js";import{viewerModuleUtils as d}from"./viewer-module-utils.js";import{communicate as f}from"./communicate.js";import{addLocalStorageARFFlagValue as p}from"../common/analyticsThrottlingService.js";var I=null;class U{proxy(...e){return t.proxy.bind(this)(...e)}registerExperimentVariantChangeListener(){chrome.storage.onChanged.addListener((t,s)=>{"local"===s&&Object.entries(t).forEach(([t,{newValue:s}])=>{t===o&&e.registerUninstallUrl({experimentCodes:s})})})}removeFgStackTractLogCookie(){n.getItem("fgStackTractLogStartTime")&&n.removeItem("fgStackTractLogStartTime")}init(){this.clientId=e.getViewerIMSClientId(),this.floodgateUri=e.getFloodgateuri(),this.env=e.getEnv(),this.accessToken=null,this.useAnonymousUUID=!0,this.anonUserUUID=null,this.featureGroups=null,this.featuresMeta={},this.lastCallTime=0,this.callInProgress=!1,this.callPromise=null,this.adobeInternalTTL=9e5,this.adobeExternalTTL=432e5,this.ffResponse=null,this.registerExperimentVariantChangeListener(),this.removeFgStackTractLogCookie()}getReleaseVariant(e,t){return this.getReleaseVariants(e,t).then(e=>{if(Array.isArray(e)&&e.length>0)return e[0]})}getReleaseVariants(e,t){return this.getFeatureGroups(t).then(t=>{const s=[e,`${e}-cohort`,`${e}-internal`,`${e}-external`].find(e=>Object.keys(t).includes(e));if(s)return t[s]})}async getFeaturesAndGroups(e){try{const t=await this.getFeatureGroups(e);let s=[].concat(...Object.values(t));return s=this.updateLocalFeatureFlags(s),{featureFlags:s,featureGroups:t,ffResponse:this.ffResponse}}catch(e){return{featureFlags:[],featureGroups:{}}}}getFeatureMeta(e){return this.featuresMeta[e]||this.featuresMeta[`${e}-internal`]||this.featuresMeta[`${e}-cohort`]}getFeatureFlag(e){let t=[].concat(...Object.values(this.featureGroups||{}));return t.includes(e)||t.includes(`${e}-internal`)||t.includes(`${e}-cohort`)}hasFlag(e,t){return this.getFeaturesAndGroups(t).then(({featureFlags:t})=>t.includes(e)||t.includes(`${e}-install`)||t.includes(`${e}-internal`)||t.includes(`${e}-cohort`)||t.includes(`${e}-external`)).catch(e=>null)}getFeatureGroups(e){return this.processOteFeatureConfig(),new Promise(t=>{e===s.NO_CALL?t(this.featureGroups||{}):e!==s.EAGER&&this.featureGroups?(t(this.featureGroups),this._getFeatureGroups()):this._getFeatureGroups().then(e=>{t(e)})})}setAdobeInternal(e){e[r]&&e[r].length&&n.setItem("adobeInternal","true")}processFloodgateResponse(e){if(!e||0===Object.keys(e).length)return!1;try{const t={},s={};e.timestamp=Date.now(),e.releases.forEach(({release_name:e,features:r,meta:a})=>{t[e]=r,a.forEach(({k:e,v:t})=>{s[e]=atob(t)})}),this.ffResponse=e,this.featureGroups=t,this.featuresMeta=s,this.lastCallTime=Date.now(),this.setAdobeInternal(t);const r=e.userId?`ffResponse_${e.userId}`:"ffResponse_anon";n.setItem(r,JSON.stringify(e))}catch(e){return console.log("Error in processing floodgate response",e),!1}}async _getFeatureGroups(e=!1){const t=(new Date).getTime();this.fgRearch=n.getItem("fgRearch")||await this.hasFlag("dc-cv-fg-rearch2",s.NO_CALL);const r="true"===n.getItem("adobeInternal"),a=r?"adobeInternalTTL":"adobeExternalTTL",o=r?this.adobeInternalTTL:this.adobeExternalTTL,i=n.getItem(a)||o;if(navigator.onLine&&(t>this.lastCallTime+i||e)){this.callInProgress||(this.callInProgress=!0,this.fgRearch?this.callPromise=this.callFloodgateAPIThroughOffscreen():this.callPromise=this.callFloodgateAPI());const e=await this.callPromise;this.callInProgress=!1,e&&(this.processFloodgateResponse(e),this.onFloodgateCallCompleted())}return this.featureGroups}floodgateForceReset(e){const t=e.timeDelay||0;setTimeout(()=>{this._getFeatureGroups(!0)},t)}processOteFeatureConfig(){(n.getItem("fgRearch")||this.getFeatureFlag("dc-cv-fg-rearch2"))&&(l.executeFeature("floodgate",this.floodgateForceReset.bind(this)),l.getFloodgateTTLs())}updateLocalFeatureFlags(e){const t=n.getItem("floodgate-add").split(/[, ]+/).filter(t=>!e.includes(t));e.push(...t);const s=n.getItem("floodgate-remove").split(/[, ]+/),r=n.getItem("floodgate-rollback")?.split(/[, ]+/),a=new Set([...s,...r]);return e=e.filter(e=>!a.has(e))}getQueryParams(){const e="true"===n.getItem("betaOptOut"),t="true"===n.getItem("adobeInternal"),s=n.getItem("pdfViewer");let r,a=n.getItem("lastUserGuid");a&&""!==a||(a=this.anonUserUUID),r=s?"true"===s?"enabled":"disabled":"neverEnabled";const o={clientId:this.clientId,meta:!0,extVersion:chrome.runtime.getManifest().version,extId:chrome.runtime.id,installType:n.getItem("installType"),installVersion:n.getItem("installVersion"),adbInt:!e&&t,extbrowser:i.isEdge()?"edge":"chrome",viewerStatus:r,anonId:a};return n.getItem("lvt")&&(o.flag1=n.getItem("lvt")),n.getItem("gvt")&&(o.flag2=n.getItem("gvt")),n.setItem("fgContextVars",o),o}handleViewerFloodgateResponse(e){this.processFloodgateResponse(e),this.getQueryParams(),d.updateVariables(f.version)}getApiUrl(){const e=new URL(`${this.floodgateUri}/v3/feature`),t=this.getQueryParams();if(Object.entries(t).forEach(([t,s])=>{e.searchParams.append(t,s)}),!this.floodgateUri||!this.clientId)throw new Error("missing data");return e.href}callFloodgateAPI(){const t=e.getFloodgateSandboxName(),s=this.accessToken?`Bearer ${this.accessToken}`:"",r={"x-api-key":this.clientId,"x-gw-ims-org-id":"9E1005A551ED61CA0A490D45@AdobeOrg","x-sandbox-name":t};if(this.useAnonymousUUID){try{this.anonUserUUID=n.getItem("anonUserUUID")}catch(e){}this.anonUserUUID?r["x-adobe-uuid"]=this.anonUserUUID:s?r.Authorization=s:(this.anonUserUUID=e.createAnonUserUUID(),r["x-adobe-uuid"]=this.anonUserUUID)}else s&&(r.Authorization=s);return fetch(this.getApiUrl(),{method:"GET",headers:r}).then(e=>{const t=e.headers.get("content-type");if(e.ok&&t&&t.includes("application/json"))return this.error=void 0,e.json();e.text().then(s=>{const r=`Floodgate API failed with status ${e.status} ${e.statusText} type ${t} text ${s}`;throw new TypeError(r)})}).catch(e=>{this.error=e&&e.message?e:new Error(`Floodgate failure: ${JSON.stringify(e)}`)})}async callFloodgateAPIThroughOffscreen(){const t=this.getQueryParams();this.anonUserUUID=this.anonUserUUID||n.getItem("anonUserUUID")||e.createAnonUserUUID();const r=await h(),a=await this.hasFlag("dc-cv-fg-loadImsLib",s.NO_CALL),o={main_op:"callFloodgateAPI",target:"offscreen",fgContextVars:t,anonUserUUID:this.anonUserUUID,iframeURL:e.getFloodgateUrl(),ims_sid_cookie_available:r,loadImsLib:a},l=`${c}?env=${e.getEnv()}`;return await i.setupOffscreenDocument(l),new Promise(e=>{setTimeout(async()=>{const t=await chrome.runtime.sendMessage(o);if(t&&t.response)try{const s=JSON.parse(t.response.fgApiResponse);s.isSignedIn=t.response.isSignedIn,s.userId=t.response.userId,e(s)}catch(t){e(null)}else{const t=n.getItem("ffResponse_anon");e(t?JSON.parse(t):null)}},50)})}onFloodgateCallCompleted(){p(),u(),m(),n.removeItem("userCohort"),n.removeItem("feature_cohort")}}function F(){const e=Object.entries(n.getAllItems()).filter(([e,t])=>e.startsWith("ffResponse_")&&"ffResponse_anon"!==e).map(([e,t])=>({key:e,timestamp:JSON.parse(n.getItem(e)).timestamp}));if(e.length>5){e.sort((e,t)=>t.timestamp-e.timestamp).slice(5).forEach(({key:e})=>{n.removeItem(e)})}}setInterval(F,864e5),F(),I||(I=new U).init();export const floodgate=I;