Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] SingleFile Not Showing Up When Right Clicking To Save Webpages Using Incognito #1643

Open
cheese529 opened this issue Dec 12, 2024 · 4 comments

Comments

@cheese529
Copy link

Running the latest version of single file on the latest version of chrome on windows 11 and I've been having this bug for the past month or so where each time I right click to go save a page while using incognito, the save page single file does not show up. I have to actually turn the extension off and then on again chrome settings in order for it to be recognized but after couple minutes of using i'll run into the bug again. When not using incognito mode you can see it fine, this issue just seems to be happen with incognito and unfortunately using incognito is crucial for me in this case. Let me know if I can provide you with anymore information because I doubt you'll be able to recreate this bug on the first try.
image
image

@cheese529
Copy link
Author

cheese529 commented Dec 13, 2024

UPDATE: It's been happening again and more frequently and so when I went into chrome settings to turn the extension off and on again I found the following errors.
image
image

@cheese529
Copy link
Author

cheese529 commented Dec 13, 2024

Here's what the text is copy and pasted. Not sure if this is related to the issue I am facing or not but hopefully it can help make things more clear.
!function(){"use strict";self.oninstall=()=>skipWaiting(),self.onactivate=()=>clients.claim(),"undefined"==typeof globalThis&&(window.globalThis=window),(()=>{if(!globalThis.browser&&globalThis.chrome){const e=globalThis.chrome;globalThis.__defineGetter__("browser",(()=>({action:{onClicked:{addListener:t=>e.action.onClicked.addListener(t)},setBadgeText:t=>e.action.setBadgeText(t),setBadgeBackgroundColor:t=>e.action.setBadgeBackgroundColor(t),setTitle:t=>e.action.setTitle(t),setIcon:t=>e.action.setIcon(t)},bookmarks:{get:t=>e.bookmarks.get(t),onCreated:{addListener:t=>e.bookmarks.onCreated.addListener(t),removeListener:t=>e.bookmarks.onCreated.removeListener(t)},onChanged:{addListener:t=>e.bookmarks.onChanged.addListener(t),removeListener:t=>e.bookmarks.onChanged.removeListener(t)},onMoved:{addListener:t=>e.bookmarks.onMoved.addListener(t),removeListener:t=>e.bookmarks.onMoved.removeListener(t)},update:(t,a)=>e.bookmarks.update(t,a)},commands:{onCommand:{addListener:t=>e.commands.onCommand.addListener(t)}},downloads:{download:t=>e.downloads.download(t),onChanged:{addListener:t=>e.downloads.onChanged.addListener(t),removeListener:t=>e.downloads.onChanged.removeListener(t)},search:t=>e.downloads.search(t)},i18n:{getUILanguage:()=>e.i18n.getUILanguage(),getMessage:(t,a)=>e.i18n.getMessage(t,a)},identity:{getRedirectURL:()=>e.identity.getRedirectURL(),getAuthToken:t=>e.identity.getAuthToken(t),launchWebAuthFlow:t=>e.identity.launchWebAuthFlow(t),removeCachedAuthToken:t=>e.identity.removeCachedAuthToken(t)},contextMenus:{onClicked:{addListener:t=>e.contextMenus.onClicked.addListener(t)},create:t=>e.contextMenus.create(t),update:(t,a)=>e.contextMenus.update(t,a),removeAll:()=>e.contextMenus.removeAll()},permissions:{request:t=>e.permissions.request(t),remove:t=>e.permissions.remove(t)},runtime:{id:e.runtime.id,sendNativeMessage:(t,a)=>new Promise(((n,o)=>{e.runtime.sendNativeMessage(t,a,(t=>{e.runtime.lastError?o(e.runtime.lastError):n(t)}))})),getManifest:()=>e.runtime.getManifest(),onMessage:{addListener:t=>e.runtime.onMessage.addListener(((e,a,n)=>{const o=t(e,a);if(o&&"function"==typeof o.then)return o.then((e=>{if(void 0!==e)try{n(e)}catch(e){}})),!0})),removeListener:t=>e.runtime.onMessage.removeListener(t)},onMessageExternal:{addListener:t=>e.runtime.onMessageExternal.addListener(((e,a,n)=>{const o=t(e,a);if(o&&"function"==typeof o.then)return o.then((e=>{if(void 0!==e)try{n(e)}catch(e){}})),!0}))},sendMessage:t=>new Promise(((a,n)=>{e.runtime.sendMessage(t,(t=>{e.runtime.lastError?n(e.runtime.lastError):a(t)})),e.runtime.lastError&&n(e.runtime.lastError)})),getURL:t=>e.runtime.getURL(t),getContexts:t=>e.runtime.getContexts(t),get lastError(){return e.runtime.lastError}},scripting:{executeScript:t=>e.scripting.executeScript(t)},storage:{local:{set:t=>e.storage.local.set(t),get:t=>e.storage.local.get(t),clear:()=>e.storage.local.clear(),remove:t=>e.storage.local.remove(t)},sync:{set:t=>e.storage.sync.set(t),get:t=>e.storage.sync.get(t),clear:()=>e.storage.sync.clear(),remove:t=>e.storage.sync.remove(t)}},tabs:{onCreated:{addListener:t=>e.tabs.onCreated.addListener(t)},onActivated:{addListener:t=>e.tabs.onActivated.addListener(t)},onUpdated:{addListener:t=>e.tabs.onUpdated.addListener(t),removeListener:t=>e.tabs.onUpdated.removeListener(t)},onRemoved:{addListener:t=>e.tabs.onRemoved.addListener(t),removeListener:t=>e.tabs.onRemoved.removeListener(t)},onReplaced:{addListener:t=>e.tabs.onReplaced.addListener(t),removeListener:t=>e.tabs.onReplaced.removeListener(t)},captureVisibleTab:(t,a)=>e.tabs.captureVisibleTab(t,a),sendMessage:(t,a,n={})=>new Promise(((o,r)=>{e.tabs.sendMessage(t,a,n,(t=>{e.runtime.lastError?r(e.runtime.lastError):o(t)})),e.runtime.lastError&&r(e.runtime.lastError)})),query:t=>e.tabs.query(t),create:t=>e.tabs.create(t),get:t=>e.tabs.get(t),remove:t=>e.tabs.remove(t),update:(t,a)=>e.tabs.update(t,a)},devtools:{inspectedWindow:{onResourceContentCommitted:{addListener:t=>e.devtools.inspectedWindow.onResourceContentCommitted.addListener(t)},get tabId(){return e.devtools.inspectedWindow.tabId}}},offscreen:{createDocument:t=>e.offscreen.createDocument(t)},declarativeNetRequest:{updateSessionRules:t=>e.declarativeNetRequest.updateSessionRules(t)}})))}})(),"undefined"==typeof globalThis&&(window.globalThis=window),(()=>{if(!globalThis.browser&&globalThis.chrome){const e=globalThis.chrome;globalThis.__defineGetter__("browser",(()=>({action:{onClicked:{addListener:t=>e.action.onClicked.addListener(t)},setBadgeText:t=>e.action.setBadgeText(t),setBadgeBackgroundColor:t=>e.action.setBadgeBackgroundColor(t),setTitle:t=>e.action.setTitle(t),setIcon:t=>e.action.setIcon(t)},bookmarks:{get:t=>e.bookmarks.get(t),onCreated:{addListener:t=>e.bookmarks.onCreated.addListener(t),removeListener:t=>e.bookmarks.onCreated.removeListener(t)},onChanged:{addListener:t=>e.bookmarks.onChanged.addListener(t),removeListener:t=>e.bookmarks.onChanged.removeListener(t)},onMoved:{addListener:t=>e.bookmarks.onMoved.addListener(t),removeListener:t=>e.bookmarks.onMoved.removeListener(t)},update:(t,a)=>e.bookmarks.update(t,a)},commands:{onCommand:{addListener:t=>e.commands.onCommand.addListener(t)}},downloads:{download:t=>e.downloads.download(t),onChanged:{addListener:t=>e.downloads.onChanged.addListener(t),removeListener:t=>e.downloads.onChanged.removeListener(t)},search:t=>e.downloads.search(t)},i18n:{getUILanguage:()=>e.i18n.getUILanguage(),getMessage:(t,a)=>e.i18n.getMessage(t,a)},identity:{getRedirectURL:()=>e.identity.getRedirectURL(),getAuthToken:t=>e.identity.getAuthToken(t),launchWebAuthFlow:t=>e.identity.launchWebAuthFlow(t),removeCachedAuthToken:t=>e.identity.removeCachedAuthToken(t)},contextMenus:{onClicked:{addListener:t=>e.contextMenus.onClicked.addListener(t)},create:t=>e.contextMenus.create(t),update:(t,a)=>e.contextMenus.update(t,a),removeAll:()=>e.contextMenus.removeAll()},permissions:{request:t=>e.permissions.request(t),remove:t=>e.permissions.remove(t)},runtime:{id:e.runtime.id,sendNativeMessage:(t,a)=>new Promise(((n,o)=>{e.runtime.sendNativeMessage(t,a,(t=>{e.runtime.lastError?o(e.runtime.lastError):n(t)}))})),getManifest:()=>e.runtime.getManifest(),onMessage:{addListener:t=>e.runtime.onMessage.addListener(((e,a,n)=>{const o=t(e,a);if(o&&"function"==typeof o.then)return o.then((e=>{if(void 0!==e)try{n(e)}catch(e){}})),!0})),removeListener:t=>e.runtime.onMessage.removeListener(t)},onMessageExternal:{addListener:t=>e.runtime.onMessageExternal.addListener(((e,a,n)=>{const o=t(e,a);if(o&&"function"==typeof o.then)return o.then((e=>{if(void 0!==e)try{n(e)}catch(e){}})),!0}))},sendMessage:t=>new Promise(((a,n)=>{e.runtime.sendMessage(t,(t=>{e.runtime.lastError?n(e.runtime.lastError):a(t)})),e.runtime.lastError&&n(e.runtime.lastError)})),getURL:t=>e.runtime.getURL(t),getContexts:t=>e.runtime.getContexts(t),get lastError(){return e.runtime.lastError}},scripting:{executeScript:t=>e.scripting.executeScript(t)},storage:{local:{set:t=>e.storage.local.set(t),get:t=>e.storage.local.get(t),clear:()=>e.storage.local.clear(),remove:t=>e.storage.local.remove(t)},sync:{set:t=>e.storage.sync.set(t),get:t=>e.storage.sync.get(t),clear:()=>e.storage.sync.clear(),remove:t=>e.storage.sync.remove(t)}},tabs:{onCreated:{addListener:t=>e.tabs.onCreated.addListener(t)},onActivated:{addListener:t=>e.tabs.onActivated.addListener(t)},onUpdated:{addListener:t=>e.tabs.onUpdated.addListener(t),removeListener:t=>e.tabs.onUpdated.removeListener(t)},onRemoved:{addListener:t=>e.tabs.onRemoved.addListener(t),removeListener:t=>e.tabs.onRemoved.removeListener(t)},onReplaced:{addListener:t=>e.tabs.onReplaced.addListener(t),removeListener:t=>e.tabs.onReplaced.removeListener(t)},captureVisibleTab:(t,a)=>e.tabs.captureVisibleTab(t,a),sendMessage:(t,a,n={})=>new Promise(((o,r)=>{e.tabs.sendMessage(t,a,n,(t=>{e.runtime.lastError?r(e.runtime.lastError):o(t)})),e.runtime.lastError&&r(e.runtime.lastError)})),query:t=>e.tabs.query(t),create:t=>e.tabs.create(t),get:t=>e.tabs.get(t),remove:t=>e.tabs.remove(t),update:(t,a)=>e.tabs.update(t,a)},devtools:{inspectedWindow:{onResourceContentCommitted:{addListener:t=>e.devtools.inspectedWindow.onResourceContentCommitted.addListener(t)},get tabId(){return e.devtools.inspectedWindow.tabId}}},offscreen:{createDocument:t=>e.offscreen.createDocument(t)},declarativeNetRequest:{updateSessionRules:t=>e.declarativeNetRequest.updateSessionRules(t)}})))}})();const e=8388608;let t=1;async function a(t,a,n){for(let o=0;o*e<=n.array.length;o++){const r={method:"singlefile.fetchResponse",requestId:a,headers:n.headers,status:n.status,error:n.error};r.truncated=n.array.length>e,r.truncated?(r.finished=(o+1)*e>n.array.length,r.array=n.array.slice(o*e,(o+1)*e)):r.array=n.array,await browser.tabs.sendMessage(t,r)}return{}}browser.runtime.onMessage.addListener(((e,n)=>{if(e.method&&e.method.startsWith("singlefile.fetch"))return new Promise((o=>{(async function(e,n){if("singlefile.fetch"==e.method)try{const o=await async function(e,a={}){const n=await fetch(e,a);if(a.referrer&&401==n.status||403==n.status||404==n.status){const n=await async function(e,a){const n=t++;return await browser.declarativeNetRequest.updateSessionRules({addRules:[{action:{type:"modifyHeaders",requestHeaders:[{header:"Referer",operation:"set",value:a}]},action:{type:"modifyHeaders",responseHeaders:[{header:"Access-Control-Allow-Origin",operation:"set",value:"*"}]},condition:{initiatorDomains:[browser.runtime.id],urlFilter:e,resourceTypes:["xmlhttprequest"]},id:n}]}),n}(e,a.referrer);await new Promise((e=>setTimeout(e,1e3)));try{const t=await fetch(e,a),n=Array.from(new Uint8Array(await t.arrayBuffer())),o={"content-type":t.headers.get("content-type")};return{array:n,headers:o,status:t.status}}finally{await async function(e){await browser.declarativeNetRequest.updateSessionRules({removeRuleIds:[e]})}(n)}}const o=Array.from(new Uint8Array(await n.arrayBuffer())),r={"content-type":n.headers.get("content-type")},i=n.status;return{array:o,headers:r,status:i}}(e.url,{referrer:e.referrer,headers:e.headers});return a(n.tab.id,e.requestId,o)}catch(t){return a(n.tab.id,e.requestId,{error:t.message,array:[]})}else if("singlefile.fetchFrame"==e.method)return browser.tabs.sendMessage(n.tab.id,e)})(e,n).then(o).catch((e=>o({error:e&&(e.message||e.toString())})))}))})),browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.frameTree.initResponse"==e.method||"singlefile.frameTree.ackInitRequest"==e.method)return browser.tabs.sendMessage(t.tab.id,e,{frameId:0}),Promise.resolve({})}));const n=new Map;function o(e,t){e.delete(t)}browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.lazyTimeout.setTimeout"==e.method){let a,r=n.get(t.tab.id);if(r)if(a=r.get(t.frameId),a){const t=a.get(e.type);t&&clearTimeout(t)}else a=new Map;const i=setTimeout((async()=>{try{const a=n.get(t.tab.id),r=a.get(t.frameId);a&&r&&o(r,e.type),await browser.tabs.sendMessage(t.tab.id,{method:"singlefile.lazyTimeout.onTimeout",type:e.type})}catch(e){}}),e.delay);return r||(r=new Map,a=new Map,r.set(t.frameId,a),n.set(t.tab.id,r)),a.set(e.type,i),Promise.resolve({})}if("singlefile.lazyTimeout.clearTimeout"==e.method){let a=n.get(t.tab.id);if(a){const n=a.get(t.frameId);if(n){const t=n.get(e.type);t&&clearTimeout(t),o(n,e.type)}}return Promise.resolve({})}})),browser.tabs.onRemoved.addListener((e=>n.delete(e)));async function r(e,t){let a;const n=new Promise(((e,t)=>{browser.downloads.onChanged.addListener((function n(o){o.id==a&&o.state&&("complete"==o.state.current&&(browser.downloads.search({id:a}).then((t=>e({filename:t[0]&&t[0].filename}))).catch((()=>e({}))),browser.downloads.onChanged.removeListener(n)),"interrupted"==o.state.current&&(o.error&&"USER_CANCELED"==o.error.current?e({cancelled:!0}):t(new Error(o.state.current)),browser.downloads.onChanged.removeListener(n)))}))}));try{a=await browser.downloads.download(e)}catch(a){if(a.message){const n=a.message.toLowerCase(),o=n.includes("illegal characters")||n.includes("invalid filename");if(o&&e.filename.startsWith("."))return e.filename=t+e.filename,r(e,t);if(o&&e.filename.includes(","))return e.filename=e.filename.replace(/,/g,t),r(e,t);if(o&&e.filename.match(/\u200C|\u200D|\u200E|\u200F/))return e.filename=e.filename.replace(/\u200C|\u200D|\u200E|\u200F/g,t),r(e,t);if(o&&!e.filename.match(/^[\x00-\x7F]+$/))return e.filename=e.filename.replace(/[^\x00-\x7F]+/g,t),r(e,t);if((n.includes("'incognito'")||n.includes('"incognito"'))&&e.incognito)return delete e.incognito,r(e,t);if("conflictaction prompt not yet implemented"==n&&e.conflictAction)return delete e.conflictAction,r(e,t);if(n.includes("canceled"))return{cancelled:!0};throw a}throw a}return n}let i,s,c;async function l(e,t,a){e[a]&&!e[t]&&(e[t]=e[a],delete e[a])}async function d(e){s&&delete s[e];const t=await f();if(t[e]){const a=t[e].autoSave;t[e]={autoSave:a},await m(t)}}function u(e){return s||(s={}),void 0===e||s[e]||(s[e]={}),s}async function f(e){if(!i){const e=await browser.storage.local.get();i=e.tabsData||{}}return async function(){if(!c){c=!0;const e=await browser.tabs.query({currentWindow:!0,highlighted:!0});Object.keys(i).filter((t=>{if("autoSaveAll"!=t&&"autoSaveUnpinned"!=t&&"profileName"!=t)return!e.find((e=>e.id==t))})).forEach((e=>delete i[e])),await browser.storage.local.set({tabsData:i})}}(),void 0===e||i[e]||(i[e]={}),i}async function m(e){i=e,await browser.storage.local.set({tabsData:e})}setTimeout((()=>f().then((e=>i=e))),0);const h="-",w="__Default_Settings__",p="__Disabled_Settings__",b="regexp:",g="profile_",y=!/Mobile.*Firefox/.test(navigator.userAgent),v=navigator.canShare&&navigator.canShare({files:[new File([new Blob([""],{type:"text/html"})],"test.html")]}),k=["~","+","\\\\\\\\","?","%","*",":","|",'"',"<",">","\0-�","�"],A=["~","+","?","%","*",":","|",'"',"<",">","\\\\","\0-�","�"],x=["~","+","?","%","*",":","|",""","<",">","\"],T={removeHiddenElements:!0,removeUnusedStyles:!0,removeUnusedFonts:!0,removeFrames:!1,compressHTML:!0,compressCSS:!1,loadDeferredImages:!0,loadDeferredImagesMaxIdleTime:1500,loadDeferredImagesBlockCookies:!1,loadDeferredImagesBlockStorage:!1,loadDeferredImagesKeepZoomLevel:!1,loadDeferredImagesDispatchScrollEvent:!1,loadDeferredImagesBeforeFrames:!1,filenameTemplate:"%if-empty<{page-title}|No title> ({date-locale} {time-locale}).{filename-extension}",infobarTemplate:"",includeInfobar:!1,openInfobar:!1,confirmInfobarContent:!1,autoClose:!1,confirmFilename:!1,filenameConflictAction:"uniquify",filenameMaxLength:192,filenameMaxLengthUnit:"bytes",filenameReplacedCharacters:A,filenameReplacementCharacter:"_",filenameReplacementCharacters:x,replaceEmojisInFilename:!1,saveFilenameTemplateData:!1,contextMenuEnabled:!0,tabMenuEnabled:!0,browserActionMenuEnabled:!0,shadowEnabled:!0,logsEnabled:!0,progressBarEnabled:!0,maxResourceSizeEnabled:!1,maxResourceSize:10,displayInfobar:!0,displayStats:!1,backgroundSave:y,defaultEditorMode:"normal",applySystemTheme:!0,autoSaveDelay:1,autoSaveLoad:!1,autoSaveUnload:!1,autoSaveLoadOrUnload:!0,autoSaveDiscard:!1,autoSaveRemove:!1,autoSaveRepeat:!1,autoSaveRepeatDelay:10,removeAlternativeFonts:!0,removeAlternativeMedias:!0,removeAlternativeImages:!0,groupDuplicateImages:!0,maxSizeDuplicateImages:524288,saveRawPage:!1,saveToClipboard:!1,addProof:!1,saveToGDrive:!1,saveToDropbox:!1,saveWithWebDAV:!1,webDAVURL:"",webDAVUser:"",webDAVPassword:"",saveToGitHub:!1,saveToRestFormApi:!1,saveToS3:!1,githubToken:"",githubUser:"",githubRepository:"SingleFile-Archives",githubBranch:"main",saveWithCompanion:!1,sharePage:!1,forceWebAuthFlow:!1,resolveFragmentIdentifierURLs:!1,userScriptEnabled:!1,openEditor:!1,openSavedPage:!1,autoOpenEditor:!1,saveCreatedBookmarks:!1,allowedBookmarkFolders:[],ignoredBookmarkFolders:[],replaceBookmarkURL:!0,saveFavicon:!0,includeBOM:!1,warnUnsavedPage:!0,displayInfobarInEditor:!1,compressContent:!1,createRootDirectory:!1,selfExtractingArchive:!0,extractDataFromPage:!0,preventAppendedData:!1,insertEmbeddedImage:!1,insertEmbeddedScreenshotImage:!1,insertTextBody:!1,autoSaveExternalSave:!1,insertMetaNoIndex:!1,insertMetaCSP:!0,passReferrerOnError:!1,password:"",insertSingleFileComment:!0,removeSavedDate:!1,blockMixedContent:!1,saveOriginalURLs:!1,acceptHeaders:{font:"application/font-woff2;q=1.0,application/font-woff;q=0.9,*/*;q=0.8",image:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",stylesheet:"text/css,*/*;q=0.1",script:"*/*",document:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",video:"video/webm,video/ogg,video/*;q=0.9,application/ogg;q=0.7,audio/*;q=0.6,*/*;q=0.5",audio:"audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5"},moveStylesInHead:!1,networkTimeout:0,woleetKey:"",blockImages:!1,blockAlternativeImages:!0,blockStylesheets:!1,blockFonts:!1,blockScripts:!0,blockVideos:!0,blockAudios:!0,delayBeforeProcessing:0,_migratedTemplateFormat:!0,saveToRestFormApiUrl:"",saveToRestFormApiFileFieldName:"",saveToRestFormApiUrlFieldName:"",saveToRestFormApiToken:"",S3Domain:"s3.amazonaws.com",S3Region:"",S3Bucket:"",S3AccessKey:"",S3SecretKey:"",resolveLinks:!0,groupDuplicateStylesheets:!1},I=[{url:"file:",profile:"__Default_Settings__",autoSaveProfile:"__Disabled_Settings__"}],S={"page-title":"No title","page-heading":"No heading","page-language":"No language","page-description":"No description","page-author":"No author","page-creator":"No creator","page-publisher":"No publisher","url-hash":"No hash","url-host":"No host","url-hostname":"No hostname","url-href":"No href","url-href-digest-sha-1":"No hash","url-href-flat":"No href","url-referrer":"No referrer","url-referrer-flat":"No referrer","url-password":"No password","url-pathname":"No pathname","url-pathname-flat":"No pathname","url-port":"No port","url-protocol":"No protocol","url-search":"No search","url-username":"No username","tab-id":"No tab id","tab-index":"No tab index","url-last-segment":"No last segment"};let C,L=E();async function E(){const{sync:e}=await browser.storage.local.get();C=e?browser.storage.sync:browser.storage.local;const t=await C.get();if(t[g+w])t.profiles&&await C.remove(["profiles"]);else if(t.profiles){const e=Object.keys(t.profiles);for(const a of e)await j(a,t.profiles[a])}else await j(w,T);t.rules||await C.set({rules:I}),t.maxParallelWorkers||await C.set({maxParallelWorkers:navigator.hardwareConcurrency||4}),t.processInForeground||await C.set({processInForeground:!1});(await _()).map((async e=>{const t=await O(e);t._migratedTemplateFormat||(t.filenameTemplate=function(e){try{return Object.keys(S).forEach((t=>{const a=S[t];e=e.replaceAll(`{${t}}`,`%if-empty<{${t}}|${a}>`)})),e}catch(e){}}(t.filenameTemplate),t._migratedTemplateFormat=!0);for(const e of Object.keys(T))void 0===t[e]&&(t[e]=T[e]);Y(t.filenameReplacedCharacters,k)&&Y(t.filenameReplacementCharacters,x)&&(t.filenameReplacedCharacters=A),await j(e,t)}))}async function R(e,t){const{rules:a}=await C.get(["rules"]),n=a.filter((e=>U(e)));let o=n.sort(M).find((t=>e&&e.match(new RegExp(t.url.split(b)[1]))));if(!o){const n=a.filter((e=>!U(e)));o=n.sort(M).find((a=>!t&&"*"==a.url||e&&e.includes(a.url)))}return o}async function P(){await L;const{maxParallelWorkers:e,processInForeground:t}=await C.get(["maxParallelWorkers","processInForeground"]),a=await N();return{profiles:await W(),rules:a,maxParallelWorkers:e,processInForeground:t}}function M(e,t){return t.url.length-e.url.length}function U(e){return e.url.toLowerCase().startsWith(b)}async function D(e){if(e.method.endsWith(".deleteRules")&&await async function(e){const t=await N();await C.set({rules:e?t.filter((t=>t.autoSaveProfile!=e&&t.profile!=e)):[]})}(e.profileName),e.method.endsWith(".deleteRule")&&await async function(e){if(!e)throw new Error("URL is empty");const t=await N();await C.set({rules:t.filter((t=>t.url!=e))})}(e.url),e.method.endsWith(".addRule")&&await z(e.url,e.profileName,e.autoSaveProfileName),e.method.endsWith(".createProfile")&&await async function(e,t){if((await _()).includes(e))throw new Error("Duplicate profile name");const a=await O(t),n=JSON.parse(JSON.stringify(a));await j(e,n)}(e.profileName,e.fromProfileName||w),e.method.endsWith(".renameProfile")&&await async function(e,t){const a=await _(),n=await f(),o=await N();if(!a.includes(e))throw new Error("Profile not found");if(a.includes(t))throw new Error("Duplicate profile name");if(e==w)throw new Error("Default settings cannot be renamed");n.profileName==e&&(n.profileName=t,await m(n));o.forEach((a=>{a.profile==e&&(a.profile=t),a.autoSaveProfile==e&&(a.autoSaveProfile=t)}));const r=await O(e);await C.remove([g+e]),await C.set({[g+t]:r,rules:o})}(e.profileName,e.newProfileName),e.method.endsWith(".deleteProfile")&&await async function(e){const t=await _(),a=await f(),n=await N();if(!t.includes(e))throw new Error("Profile not found");if(e==w)throw new Error("Default settings cannot be deleted");a.profileName==e&&(delete a.profileName,await m(a));n.forEach((t=>{t.profile==e&&(t.profile=w),t.autoSaveProfile==e&&(t.autoSaveProfile=w)})),C.remove([g+e]),await C.set({rules:n})}(e.profileName),e.method.endsWith(".resetProfiles")&&await async function(){await L;const e=await f();delete e.profileName,await m(e);let t=await B();await C.remove([...t,"rules","maxParallelWorkers","processInForeground"]),await E()}(),e.method.endsWith(".resetProfile")&&await async function(e){if(!(await _()).includes(e))throw new Error("Profile not found");await j(e,T)}(e.profileName),e.method.endsWith(".importConfig")&&await async function(e){const t=await _(),a=await B(),n=await f();t.includes(n.profileName)&&(delete n.profileName,await m(n));await C.remove([...a,"rules","maxParallelWorkers","processInForeground"]);const o={rules:e.rules,maxParallelWorkers:e.maxParallelWorkers,processInForeground:e.processInForeground};Object.keys(e.profiles).forEach((t=>o[g+t]=e.profiles[t])),await C.set(o),await E()}(e.config),e.method.endsWith(".updateProfile")&&await async function(e,t){if(!(await _()).includes(e))throw new Error("Profile not found");const a=await O(e);Object.keys(a).forEach((e=>{t[e]=void 0===t[e]?a[e]:t[e]})),await j(e,t)}(e.profileName,e.profile),e.method.endsWith(".updateRule")&&await q(e.url,e.newUrl,e.profileName,e.autoSaveProfileName),e.method.endsWith(".getConstants"))return{DISABLED_PROFILE_NAME:p,DEFAULT_PROFILE_NAME:w,CURRENT_PROFILE_NAME:h,BACKGROUND_SAVE_SUPPORTED:y,SHARE_API_SUPPORTED:v};if(e.method.endsWith(".getRules"))return N();if(e.method.endsWith(".getProfiles"))return W();if(e.method.endsWith(".exportConfig"))return async function(){const e=await P(),t=JSON.stringify({profiles:e.profiles,rules:e.rules,maxParallelWorkers:e.maxParallelWorkers,processInForeground:e.processInForeground},null,2),a=`singlefile-settings-${(new Date).toISOString().replace(/:/g,"_")}.json`,n={url:"data:text/json;base64,"+btoa(unescape(encodeURIComponent(t))),filename:a,saveAs:!0};await r(n,"_")}();if(e.method.endsWith(".enableSync")){await browser.storage.local.set({sync:!0});const e=await browser.storage.sync.get();if(!e||!e.rules){const e=await B(),t=await browser.storage.local.get(["rules","maxParallelWorkers","processInForeground",...e]);await browser.storage.sync.set(t)}return C=browser.storage.sync,await E(),{}}if(e.method.endsWith(".disableSync")){await browser.storage.local.set({sync:!1});const e=await browser.storage.sync.get(),t=await browser.storage.local.get();if(e&&e.rules&&(!t||!t.rules)){await browser.storage.local.set({rules:e.rules,maxParallelWorkers:e.maxParallelWorkers,processInForeground:e.processInForeground});const t={};await browser.storage.local.set(t)}return C=browser.storage.local,await E(),{}}return e.method.endsWith(".isSync")?{sync:(await browser.storage.local.get()).sync}:{}}async function W(){await L;const e=await B(),t=await C.get(e),a={};return Object.keys(t).forEach((e=>a[e.substring(8)]=t[e])),a}async function F(e,t){await L;const[a,n]=await Promise.all([R(e),f()]),o=n.profileName||w;let r;if(a){const e=a[t?"autoSaveProfile":"profile"];r=e==h?o:e}else r=o;const i=await O(r);return Object.assign({profileName:r},i)}async function N(){return(await C.get(["rules"])).rules}async function _(){return Object.keys(await C.get()).filter((e=>e.startsWith(g))).map((e=>e.substring(8)))}async function B(){return Object.keys(await C.get()).filter((e=>e.startsWith(g)))}async function O(e){const t=g+e;return(await C.get([t]))[t]}async function j(e,t){const a=g+e;await C.set({[a]:t})}async function z(e,t,a){if(!e)throw new Error("URL is empty");const n=await N();if(n.find((t=>t.url==e)))throw new Error("URL already exists");n.push({url:e,profile:t,autoSaveProfile:a}),await C.set({rules:n})}async function q(e,t,a,n){if(!e||!t)throw new Error("URL is empty");const o=await N(),r=o.find((t=>t.url==e));if(!r)throw new Error("URL not found");if(o.find((a=>a.url==t&&a.url!=e)))throw new Error("New URL already exists");r.url=t,r.profile=a,r.autoSaveProfile=n,await C.set({rules:o})}async function K(){return(await C.get()).authInfo}async function V(){return(await C.get()).dropboxAuthInfo}async function G(e){await C.set({authInfo:e})}async function H(e){await C.set({dropboxAuthInfo:e})}async function $(){let e=K();e.revokableAccessToken?G({revokableAccessToken:e.revokableAccessToken}):await C.remove(["authInfo"])}async function J(){let e=V();e.revokableAccessToken?H({revokableAccessToken:e.revokableAccessToken}):await C.remove(["dropboxAuthInfo"])}function Y(e,t){return e.length==t.length&&e.every(((e,a)=>e==t[a]))}async function Z(e){if(e){const[t,a]=await Promise.all([f(),R(e.url)]);return Boolean(t.autoSaveAll||t.autoSaveUnpinned&&!e.pinned||t[e.id]&&t[e.id].autoSave)&&(!a||a.autoSaveProfile!=p)}}const Q=33554432,X="/src/ui/pages/editor.html",ee=new Map,te=new Map,ae=browser.runtime.getURL(X);async function ne({tabIndex:e,content:t,filename:a,compressContent:n,selfExtractingArchive:o,extractDataFromPage:r,insertTextBody:i,insertMetaCSP:s,embeddedImage:c}){const l={active:!0,url:X};null!=e&&(l.index=e);const d=await browser.tabs.create(l);ee.set(d.id,{content:t,filename:a,compressContent:n,selfExtractingArchive:o,extractDataFromPage:r,insertTextBody:i,insertMetaCSP:s,embeddedImage:c})}function oe(e){return e.url==ae}async function re(e){return(await browser.tabs.query(e)).sort(((e,t)=>e.index-t.index))}function ie(e){return new Promise(((t,a)=>{browser.tabs.onUpdated.addListener((function n(o,r){if(r&&r.url&&r.url.startsWith(e)){browser.tabs.onUpdated.removeListener(n);const e=new URLSearchParams(new URL(r.url).search).get("code");e?(browser.tabs.remove(o),t(e)):a()}}))}))}async function se(e){const t=await browser.tabs.create({url:e.url,active:!0});return new Promise(((e,a)=>{browser.tabs.onRemoved.addListener((function e(n){n==t.id&&(browser.tabs.onRemoved.removeListener(e),a(new Error("code_required")))}))}))}const ce="/src/ui/resources/icon_128.png",le="/src/ui/resources/icon_128_wait",de=browser.i18n.getMessage("buttonDefaultTooltip"),ue=browser.i18n.getMessage("buttonBlockedTooltip"),fe=browser.i18n.getMessage("buttonInitializingBadge"),me=browser.i18n.getMessage("buttonInitializingTooltip"),he=browser.i18n.getMessage("buttonErrorBadge"),we=browser.i18n.getMessage("buttonBlockedBadge"),pe=browser.i18n.getMessage("buttonOKBadge"),be=browser.i18n.getMessage("buttonSaveProgressTooltip"),ge=browser.i18n.getMessage("buttonUploadProgressTooltip"),ye=browser.i18n.getMessage("buttonAutoSaveActiveBadge"),ve=browser.i18n.getMessage("buttonAutoSaveActiveTooltip"),ke=[2,147,20,192],Ae=[4,229,36,192],xe={default:{setBadgeBackgroundColor:{color:ke},setBadgeText:{text:""},setTitle:{title:de},setIcon:{path:ce}},inject:{setBadgeBackgroundColor:{color:ke},setBadgeText:{text:fe},setTitle:{title:me}},execute:{setBadgeBackgroundColor:{color:Ae},setBadgeText:{text:fe}},progress:{setBadgeBackgroundColor:{color:Ae},setBadgeText:{text:""}},edit:{setBadgeBackgroundColor:{color:ke},setBadgeText:{text:""},setTitle:{title:de},setIcon:{path:ce}},end:{setBadgeBackgroundColor:{color:Ae},setBadgeText:{text:pe},setTitle:{title:de},setIcon:{path:ce}},error:{setBadgeBackgroundColor:{color:[229,4,12,192]},setBadgeText:{text:he},setTitle:{title:""},setIcon:{path:ce}},forbidden:{setBadgeBackgroundColor:{color:[255,255,255,1]},setBadgeText:{text:we},setTitle:{title:ue},setIcon:{path:ce}},autosave:{inject:{setBadgeBackgroundColor:{color:[64,64,64,192]},setBadgeText:{text:ye},setTitle:{title:ve},setIcon:{path:ce}},default:{setBadgeBackgroundColor:{color:[208,208,208,192]},setBadgeText:{text:ye},setTitle:{title:ve},setIcon:{path:ce}}}};let Te;function Ie(e,t){if(e.method.endsWith(".processInit")){delete u(t.tab.id)[t.tab.id].button,Re(t.tab)}var a,n,o;return e.method.endsWith(".processProgress")&&e.maxIndex&&(a=t.tab.id,n=e.index,o=e.maxIndex,Ee(a,n,o,be)),e.method.endsWith(".processEnd")&&Ce(t.tab.id),e.method.endsWith(".processError")&&(e.error&&console.error("Initialization error",e.error),Se(t.tab.id)),e.method.endsWith(".processCancelled")&&Le(t.tab),Promise.resolve({})}function Se(e){Pe(e,Ue("error"))}function Ce(e,t){Pe(e,t?Ue("default",!0):Ue("end"))}function Le(e){Re(e)}function Ee(e,t,a,n){const o=Math.max(Math.min(20,Math.floor(t/a*20)),0),r=Math.min(Math.floor(t/a*8),8),i=le+r+".png",s=Ue("progress");s.setTitle={title:n+5*o+"%"},s.setIcon={path:i},Pe(e,s)}async function Re(e){const t=Ue("default",await Z(e));await Pe(e.id,t)}async function Pe(e,t){try{const a=u(e);if(t){a[e].button||(a[e].button={lastState:null});const n=a[e].button.lastState||{},o={};Object.keys(t).forEach((e=>{void 0!==t[e]&&JSON.stringify(n[e])!=JSON.stringify(t[e])&&(o[e]=t[e])})),Object.keys(o).length&&(a[e].button.lastState=t,await async function(e,t){for(const a of Object.keys(t))await Me(e,a,t[a])}(e,o))}}catch(e){}}async function Me(e,t,a){if(browser.action[t]){const n=JSON.parse(JSON.stringify(a));n.tabId=e,await browser.action[t](n)}}function Ue(e,t){return JSON.parse(JSON.stringify(t?xe.autosave[e]:xe[e]))}browser.action.onClicked.addListener((async e=>{const t=await re({currentWindow:!0,highlighted:!0});t.length<=1?function(e){Te.isSavingTab(e)?Te.cancelTab(e.id):Te.saveTabs([e])}(e):Te.saveTabs(t)}));const De=browser.contextMenus,We="save-page",Fe="edit-and-save-page",Ne="save-with-profile",_e="save-selected-links",Be="view-pendings",Oe="select-profile",je="wasve-with-profile-",ze="select-profile-",qe="associate-with-profile",Ke="associate-with-profile-",Ve="save-selected",Ge="save-frame",He="save-tabs",$e="save-selected-tabs",Je="save-unpinned-tabs",Ye="save-all-tabs",Ze="batch-save-urls",Qe="button-"+$e,Xe="button-"+Je,et="button-"+Ye,tt="auto-save",at="auto-save-disabled",nt="auto-save-tab",ot="auto-save-unpinned",rt="auto-save-all",it=browser.i18n.getMessage("menuCreateDomainRule"),st=browser.i18n.getMessage("menuUpdateRule"),ct=browser.i18n.getMessage("menuSavePage"),lt=browser.i18n.getMessage("menuSaveWithProfile"),dt=browser.i18n.getMessage("menuSaveSelectedLinks"),ut=browser.i18n.getMessage("menuEditPage"),ft=browser.i18n.getMessage("menuEditAndSavePage"),mt=browser.i18n.getMessage("menuViewPendingSaves"),ht=browser.i18n.getMessage("menuSaveSelection"),wt=browser.i18n.getMessage("menuSaveFrame"),pt=browser.i18n.getMessage("menuSaveTabs"),bt=browser.i18n.getMessage("menuSaveSelectedTabs"),gt=browser.i18n.getMessage("menuSaveUnpinnedTabs"),yt=browser.i18n.getMessage("menuSaveAllTabs"),vt=browser.i18n.getMessage("menuBatchSaveUrls"),kt=browser.i18n.getMessage("menuSelectProfile"),At=browser.i18n.getMessage("profileDefaultSettings"),xt=browser.i18n.getMessage("menuAutoSave"),Tt=browser.i18n.getMessage("menuAutoSaveDisabled"),It=browser.i18n.getMessage("menuAutoSaveTab"),St=browser.i18n.getMessage("menuAutoSaveUnpinnedTabs"),Ct=browser.i18n.getMessage("menuAutoSaveAllTabs"),Lt=[Fe,_e,Ve,Ge,tt,qe],Et=new Map,Rt=new Map;let Pt,Mt,Ut,Dt=!0,Wt=!0,Ft=new Map;async function Nt(e){const[t,a]=await Promise.all([W(),f()]);let n=await F(e&&e.url);if(n){const o=["page","frame","image","link","video","audio","selection"],r=[];if(n.profileName==p&&(n=await F(),n.profileName=p),n.browserActionMenuEnabled&&r.push("action"),n.tabMenuEnabled)try{await De.create({id:"temporary-id",contexts:["tab"],title:"title"}),r.push("tab")}catch(e){n.tabMenuEnabled=!1}await De.removeAll();const i=r.concat(...o),s=n.contextMenuEnabled?i:r;if(De.create({id:We,contexts:s,title:ct}),De.create({id:Fe,contexts:s,title:ft}),De.create({id:_e,contexts:n.contextMenuEnabled?r.concat(["selection"]):r,title:dt}),Object.keys(t).length>1&&De.create({id:Ne,contexts:s,title:lt}),n.contextMenuEnabled&&De.create({id:"separator-1",contexts:o,type:"separator"}),De.create({id:Ve,contexts:s,title:ht}),n.contextMenuEnabled&&De.create({id:Ge,contexts:["frame"],title:wt}),De.create({id:He,contexts:r,title:pt}),De.create({id:Qe,contexts:r,title:bt,parentId:He}),De.create({id:Xe,contexts:r,title:gt,parentId:He}),De.create({id:et,contexts:r,title:yt,parentId:He}),n.contextMenuEnabled&&(De.create({id:$e,contexts:o,title:bt}),De.create({id:Je,contexts:o,title:gt}),De.create({id:Ye,contexts:o,title:yt}),De.create({id:"separator-2",contexts:o,type:"separator"})),Object.keys(t).length>1){De.create({id:Oe,title:kt,contexts:s}),De.create({id:je+"default",contexts:s,title:At,parentId:Ne});const r=ze+"default",i=!a.profileName||a.profileName==w;let c;De.create({id:r,type:"radio",contexts:s,title:At,checked:i,parentId:Oe}),Et.set(r,i),De.create({id:qe,title:it,contexts:s}),Rt.set(qe,it),e&&e.url&&(c=await R(e.url,!0));const l=Ke+"current",d=!c||c.profile==h;De.create({id:l,type:"radio",contexts:s,title:h,checked:d,parentId:qe}),Et.set(l,d);const u=Ke+"default",f=Boolean(c)&&c.profile==w;De.create({id:u,type:"radio",contexts:s,title:At,checked:f,parentId:qe}),Et.set(u,f),Ft=new Map,Object.keys(t).forEach(((e,t)=>{if(e!=w){let n=je+t;De.create({id:n,contexts:s,title:e,parentId:Ne}),n=ze+t;let o=a.profileName==e;De.create({id:n,type:"radio",contexts:s,title:e,checked:o,parentId:Oe}),Et.set(n,o),n=Ke+t,o=Boolean(c)&&c.profile==e,De.create({id:n,type:"radio",contexts:s,title:e,checked:o,parentId:qe}),Et.set(n,o),Ft.set(e,t)}})),n.contextMenuEnabled&&De.create({id:"separator-3",contexts:o,type:"separator"})}De.create({id:tt,contexts:s,title:xt}),De.create({id:at,type:"radio",title:Tt,contexts:s,checked:!0,parentId:tt}),Et.set(at,!0),De.create({id:nt,type:"radio",title:It,contexts:s,checked:!1,parentId:tt}),Et.set(nt,!1),De.create({id:ot,type:"radio",title:St,contexts:s,checked:!1,parentId:tt}),Et.set(ot,!1),De.create({id:rt,type:"radio",title:Ct,contexts:s,checked:!1,parentId:tt}),Et.set(rt,!1),De.create({id:"separator-4",contexts:s,type:"separator"}),De.create({id:Ze,contexts:s,title:vt}),De.create({id:Be,contexts:s,title:mt})}Pt=!0,Mt&&(Mt=!1,(await browser.tabs.query({})).forEach((async e=>await Bt(e))))}async function _t(e){const t=await f(e.id);await async function(){const e=await browser.tabs.query({});return Promise.all(e.map((async e=>{const[t,a]=await Promise.all([F(e.url,!0),Z(e)]);try{await browser.tabs.sendMessage(e.id,{method:"content.init",autoSaveEnabled:a,options:t})}catch(e){}})))}(),await Re(e);try{await browser.runtime.sendMessage({method:"options.refresh",profileName:t.profileName})}catch(e){}}async function Bt(e){if(Pt){const t=[],a=await f(e.id);if(a[e.id].editorDetected)Ot(!1);else if(Ot(!0),t.push(zt(at,!a[e.id].autoSave)),t.push(zt(nt,a[e.id].autoSave)),t.push(zt(ot,Boolean(a.autoSaveUnpinned))),t.push(zt(rt,Boolean(a.autoSaveAll))),e&&e.url){const n=await F(e.url);t.push(async function(e,t){const a=Dt;Dt=t,(void 0===a||a!=t)&&await Nt(e)}(e,n.contextMenuEnabled)),t.push(jt(Fe,a[e.id].savedPageDetected?ut:ft)),t.push(De.update(Ve,{visible:!n.saveRawPage})),t.push(De.update(Fe,{visible:!n.openEditor||a[e.id].savedPageDetected}));let o=Ke+"default",r=it;const[i,s]=await Promise.all([W(),R(e.url)]);if(s){const e=Ft.get(s.profile);e&&(o=Ke+e,r=st)}Object.keys(i).length>1&&(Object.keys(i).forEach(((e,a)=>{e==w?t.push(zt(Ke+"default",o==Ke+"default")):t.push(zt(Ke+a,o==Ke+a))})),t.push(jt(qe,r)))}await Promise.all(t)}}async function Ot(e){const t=Wt;if(Wt=e,void 0===t||t!=e){const t=[];try{Lt.forEach((a=>t.push(De.update(a,{visible:e})))),await Promise.all(t)}catch(e){}}}function jt(e,t){const a=Rt.get(e);return Rt.set(e,t),void 0===a||a!=t?De.update(e,{title:t}):void 0}async function zt(e,t){t=Boolean(t),Et.set(e,t),await De.update(e,{checked:t})}Promise.resolve().then((async function(){Nt(),De.onClicked.addListener((async(e,t)=>{if(e.menuItemId==We&&(e.linkUrl?Ut.saveUrls([e.linkUrl]):Ut.saveTabs([t])),e.menuItemId==Fe){(await f(t.id))[t.id].savedPageDetected?Ut.openEditor(t):e.linkUrl?Ut.saveUrls([e.linkUrl],{openEditor:!0}):Ut.saveTabs([t],{openEditor:!0})}if(e.menuItemId==_e&&Ut.saveSelectedLinks(t),e.menuItemId==Be&&await browser.tabs.create({active:!0,url:"/src/ui/pages/pendings.html"}),e.menuItemId==Ve&&Ut.saveTabs([t],{selected:!0}),e.menuItemId==Ge&&Ut.saveTabs([t],{frameId:e.frameId}),e.menuItemId==$e||e.menuItemId==Qe){const e=await re({currentWindow:!0,highlighted:!0});Ut.saveTabs(e)}if(e.menuItemId==Je||e.menuItemId==Xe){const e=await re({currentWindow:!0,pinned:!1});Ut.saveTabs(e)}if(e.menuItemId==Ye||e.menuItemId==et){const e=await re({currentWindow:!0});Ut.saveTabs(e)}if(e.menuItemId==Ze&&Ut.batchSaveUrls(),e.menuItemId==nt){const e=await f(t.id);e[t.id].autoSave=!0,await m(e),_t(t)}if(e.menuItemId==at){const e=await f();Object.keys(e).forEach((t=>{"object"==typeof e[t]&&e[t].autoSave&&(e[t].autoSave=!1)})),e.autoSaveUnpinned=e.autoSaveAll=!1,await m(e),_t(t)}if(e.menuItemId==rt){const a=await f();a.autoSaveAll=e.checked,await m(a),_t(t)}if(e.menuItemId==ot){const a=await f();a.autoSaveUnpinned=e.checked,await m(a),_t(t)}if(e.menuItemId.startsWith(je)){const a=await W(),n=e.menuItemId.split(je)[1];let o;if("default"==n)o=w;else{const e=Number(n);o=Object.keys(a)[e]}a[o].profileName=o,Ut.saveTabs([t],a[o])}if(e.menuItemId.startsWith(ze)){const[a,n]=await Promise.all([W(),f()]),o=e.menuItemId.split(ze)[1];if("default"==o)n.profileName=w;else{const e=Number(o);n.profileName=Object.keys(a)[e]}await m(n),_t(t)}if(e.menuItemId.startsWith(Ke)){const[a,n]=await Promise.all([W(),R(t.url,!0)]),o=e.menuItemId.split(Ke)[1];let r;if("default"==o)r=w;else if("current"==o)r=h;else{const e=Number(o);r=Object.keys(a)[e]}n?await q(n.url,n.url,r,r):(await jt(qe,st),await z(new URL(t.url).hostname,r,r))}})),Pt?Mt=!0:(await browser.tabs.query({})).forEach((async e=>await Bt(e)))}));let qt;function Kt(e,t){return e.method.endsWith(".refreshMenu")?function(e){if(e.method.endsWith("refreshMenu"))return Nt(),Promise.resolve({})}(e):Ie(e,t)}function Vt(e){!function(e){Pe(e.id,Ue("forbidden"))}(e)}function Gt(e,t,a){!function(e,t,a){let n;a?n=Ue("inject",!0):(n=Ue(1==t?"inject":"execute"),n.setTitle={title:me+" ("+t+"/2)"},n.setIcon={path:le+"0.png"}),Pe(e,n)}(e,t,a)}async function Ht(e,t,a){Se(e);try{t&&await browser.tabs.sendMessage(e,{method:"content.error",error:t.toString(),link:a})}catch(e){}}function $t(e){!function(e){Pe(e,Ue("edit"))}(e)}function Jt(e,t){Ce(e,t)}function Yt(e,t,a){!function(e,t,a){Ee(e,t,a,ge)}(e,t,a)}function Zt(e){Bt(e)}browser.commands.onCommand.addListener((async e=>{if("save-selected-tabs"==e){const e=await re({currentWindow:!0,highlighted:!0});qt.saveTabs(e,{optionallySelected:!0})}if("save-all-tabs"==e){const e=await re({currentWindow:!0});qt.saveTabs(e)}}));const Qt="Could not establish connection. Receiving end does not exist.",Xt="The message port closed before a response was received.",ea="Message manager disconnected",ta="Cannot access contents of url ",aa="A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received",na="pending",oa="processing",ra=["lib/single-file.js","lib/single-file-extension.js"],ia=["lib/chrome-browser-polyfill.js","lib/single-file-frames.js","lib/single-file-extension-frames.js"],sa=["lib/single-file-hooks-frames.js"],ca=["lib/chrome-browser-polyfill.js","lib/single-file-bootstrap.js","lib/single-file-extension-bootstrap.js","lib/single-file-infobar.js"],la=[];let da,ua,fa=0;var ma;async function ha(e){let t;try{t=await xa(e.id)}catch(e){}if(t){const t=await browser.tabs.sendMessage(e.id,{method:"content.getSelectedLinks"});if(t.urls&&t.urls.length){const e=await wa(),a=(n,o)=>{"complete"==o.status&&n==e.id&&(browser.tabs.onUpdated.removeListener(a),browser.tabs.sendMessage(e.id,{method:"newUrls.addURLs",urls:t.urls}))};browser.tabs.onUpdated.addListener(a)}}else Vt(e)}async function wa(){return browser.tabs.create({active:!0,url:"/src/ui/pages/batch-save-urls.html"})}async function pa(e,t={}){await ya(),await Promise.all(e.map((async e=>{const a=await F(e);a.profileName!=p&&(Object.keys(t).forEach((e=>a[e]=t[e])),a.autoClose=!0,a.originalUrl=e,ga({tab:{url:e},status:na,options:a,method:"content.save"}))}))),va()}async function ba(e,t={}){await ya(),await Promise.all(e.map((async e=>{const a=e.id,n=await F(e.url);if(n.profileName!=p){Object.keys(t).forEach((e=>n[e]=t[e])),n.tabId=a,n.tabIndex=e.index;const o={id:e.id,index:e.index,url:e.url,title:e.title};if(t.autoSave){if(Z(e)){ka(ga({status:oa,tab:o,options:n,method:"content.autosave"}))}}else{let t;Gt(a,1);try{t=await xa(a,n)}catch(e){}t||oe(e)?(Gt(a,2),ga({status:na,tab:o,options:n,method:"content.save"})):Vt(e)}}else Vt(e)}))),va()}function ga(e){const t={id:fa,status:e.status,tab:e.tab,options:e.options,method:e.method,done:function(e=!0){const t=la.findIndex((e=>e.id==this.id));t>-1&&(la.splice(t,1),e&&va())}};return la.push(t),fa++,t}async function ya(){if(!da){const e=await P();ua=e.processInForeground,da=ua?1:e.maxParallelWorkers}}function va(){const e=la.filter((e=>e.status==oa)).length;for(let t=0;t<Math.min(la.length-e,da-e);t++){const e=la.find((e=>e.status==na));e&&ka(e)}}async function ka(e){const t=e.id;if(e.status=oa,!e.tab.id){let t;try{const a=await async function(e){const t=await browser.tabs.create(e);return new Promise(((e,a)=>{function n(a,r){a==t.id&&"complete"==r.status&&(e(t),browser.tabs.onUpdated.removeListener(n),browser.tabs.onRemoved.removeListener(o))}function o(e){e==t.id&&(a(e),browser.tabs.onRemoved.removeListener(o))}browser.tabs.onUpdated.addListener(n),browser.tabs.onRemoved.addListener(o)}))}({url:e.tab.url,active:!1});e.tab.id=e.options.tabId=a.id,e.tab.index=e.options.tabIndex=a.index,Gt(e.tab.id,1);try{t=await xa(e.tab.id,e.options)}catch(e){}}catch(t){e.tab.id=t}if(!t)return void e.done();Gt(e.tab.id,2)}e.options.taskId=t;try{ua&&await browser.tabs.update(e.tab.id,{active:!0}),await browser.tabs.sendMessage(e.tab.id,{method:e.method,options:e.options})}catch(t){!t||t.message&&function(e){return e.message==Xt||e.message==Qt||e.message==ea||e.message==aa||e.message.startsWith(ta+JSON.stringify(ae))}(t)||(console.log(t.message?t.message:t),Ht(e.tab.id,t.message,t.link),e.done())}}function Aa(e){const t=la.find((t=>t.id==e));t&&(t.options.autoClose&&!t.cancelled&&browser.tabs.remove(t.tab.id),t.done())}async function xa(e,t={},a=!0){let n;const o=(await browser.scripting.executeScript({target:{tabId:e},func:()=>Boolean(window.singlefile)}))[0];if(n=o&&o.result,n)try{await browser.scripting.executeScript({target:{tabId:e},files:ra})}catch(e){}else try{if(await browser.scripting.executeScript({target:{tabId:e,allFrames:!0},files:ia}),await browser.scripting.executeScript({target:{tabId:e},files:ca}),await browser.scripting.executeScript({target:{tabId:e,allFrames:!0},files:sa,world:"MAIN"}),a)return await xa(e,t,!1)}catch(e){}return n&&t.frameId&&await browser.scripting.executeScript({target:{tabId:e,frameIds:[t.frameId]},func:()=>document.documentElement.dataset.requestedFrameId=!0}),n}function Ta(e,t){const a=la.find((t=>t.id==e));a&&(a.cancel=t)}function Ia(e,t=!0){Array.from(la).filter((a=>a.tab.id==e&&!a.options.autoSave&&(t||a.status!=oa))).forEach(Ca)}function Sa(e){return la.find((t=>t.id==e))}function Ca(e,t){const a=e.tab.id;e.cancelled=!0,a&&(browser.tabs.sendMessage(a,{method:"content.cancelSave",options:{loadDeferredImages:e.options.loadDeferredImages,loadDeferredImagesKeepZoomLevel:e.options.loadDeferredImagesKeepZoomLevel}}).catch((()=>{})),"content.autosave"==e.method&&Jt(a,!0),function(e){Le(e)}(e.tab)),e.cancel&&e.cancel(),e.done(t)}function La(e){return{id:e.id,tabId:e.tab.id,index:e.tab.index,url:e.tab.url,title:e.tab.title,cancelled:e.cancelled,status:e.status}}(function(e){Ut=e})(ma={isSavingTab:function(e){return Boolean(la.find((t=>t.tab.id==e.id)))},saveTabs:ba,saveUrls:pa,cancelTab:Ia,openEditor:function(e){browser.tabs.sendMessage(e.id,{method:"content.openEditor"})},saveSelectedLinks:ha,batchSaveUrls:wa}),function(e){Te=e}(ma),function(e){qt=e}(ma);async function Ea(e){let t;try{t=await browser.runtime.sendNativeMessage("singlefile_companion",{method:"save",pageData:e})}catch(e){if(!e.message||!e.message.includes("Native host has exited"))throw e}if(t&&t.error)throw new Error(t.error+" (Companion)")}const Ra=new Set;async function Pa(e){return e.method.endsWith(".saveCreatedBookmarks")?(Ma(),{}):e.method.endsWith(".disable")?(async function(){let e;const t=await W();Object.keys(t).forEach((a=>e=e||!t[a].saveCreatedBookmarks)),e&&(browser.bookmarks.onCreated.removeListener(Da),browser.bookmarks.onMoved.removeListener(Wa))}(),{}):void 0}async function Ma(){try{browser.bookmarks.onCreated.removeListener(Da),browser.bookmarks.onMoved.removeListener(Wa)}catch(e){}let e;const t=await W();Object.keys(t).forEach((a=>{t[a].saveCreatedBookmarks&&(e=!0)})),e&&(browser.bookmarks.onCreated.addListener(Da),browser.bookmarks.onMoved.addListener(Wa))}async function Ua(e,t){try{await browser.bookmarks.update(e,t)}catch(e){}}async function Da(e,t){Ra.add(e),await Fa(e,t.url,t)}async function Wa(e,t){if(Ra.has(e)){const a=await browser.bookmarks.get(e);a[0]&&await Fa(e,a[0].url,t)}}async function Fa(e,t,a){const n=await browser.tabs.query({lastFocusedWindow:!0,active:!0}),o=await F(t);if(o.saveCreatedBookmarks){const i=await async function e(t,a=[]){if(t){const n=(await browser.bookmarks.get(t))[0];n&&n.title&&(a.unshift(n.title),await e(n.parentId,a))}return a}(a.parentId),s=o.allowedBookmarkFolders.toString(),c=i.find((e=>o.allowedBookmarkFolders.includes(e))),l=o.ignoredBookmarkFolders.toString(),d=i.find((e=>o.ignoredBookmarkFolders.includes(e)));if((s&&c||!s)&&(l&&!d||!l))if(n.length&&n[0].url==t)Ra.delete(e),ba(n,{bookmarkId:e,bookmarkFolders:i});else{const a=await browser.tabs.query({});if(a.length){const n=a.find((e=>e.url==t));n?(Ra.delete(e),ba([n],{bookmarkId:e,bookmarkFolders:i})):t&&("about:blank"==t?browser.bookmarks.onChanged.addListener((function t(a,n){a==e&&n.url&&(browser.bookmarks.onChanged.removeListener(t),r(n.url))})):r(t))}}}function r(t){Ra.delete(e),pa([t],{bookmarkId:e})}}Promise.resolve().then(Ma);async function Na(e,t){let a=t||"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhYzZmZTMzMi0wODNjLTRjZmMtYmYxNC0xNWU5MTJmMWY4OWIiLCJpYXQiOjE1NzYxNzQzNDV9.n31j9ctJj7R1Vjwyc5yd1d6Cmg0NDnpwSaLWsqtZJQA";const n=await fetch("https://api.woleet.io/v1/anchor",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+a},body:JSON.stringify({name:e,hash:e,public:!0})});if(401==n.status){const e=new Error("Your access token on Woleet is invalid. Go to __DOC_LINK__ to create your account.");throw e.link="https://app.woleet.io/",e}if(402==n.status){const e=new Error("You have no more credits on Woleet. Go to __DOC_LINK__ to recharge them.");throw e.link="https://app.woleet.io/",e}if(n.status>=400)throw new Error((n.statusText||"Error "+n.status)+" (Woleet)");return n.json()}const _a="https://oauth2.googleapis.com/token",Ba="https://www.googleapis.com/drive/v3/files",Oa="uniquify";let ja=class{constructor(e){this.file=e.file,this.onProgress=e.onProgress,this.contentType=this.file.type||"application/octet-stream",this.metadata={name:e.filename,mimeType:this.contentType,parents:e.parents||["root"]},this.token=e.token,this.offset=0,this.chunkSize=e.chunkSize||524288,this.filenameConflictAction=e.filenameConflictAction,this.prompt=e.prompt}async upload(e=1){let t,a="POST";const n=$a(await fetch(Ba+`?q=name = '${this.metadata.name}' and trashed != true and '${this.metadata.parents[0]}' in parents`,{headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"}})),o=await n.json();if(o.files.length)if("overwrite"==this.filenameConflictAction)a="PATCH",t=o.files[0].id,this.metadata.parents=null;else if(this.filenameConflictAction==Oa){let t=this.metadata.name,a="";const n=this.metadata.name.lastIndexOf(".");n>-1&&(t=this.metadata.name.substring(0,n),a=this.metadata.name.substring(n+1));const o=t+" ("+e+")."+a,r=$a(await fetch(Ba+`?q=name = '${o}' and trashed != true and '${this.metadata.parents[0]}' in parents`,{headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"}}));if((await r.json()).files.length)return this.upload(e+1);this.metadata.name=o}else{if("prompt"==this.filenameConflictAction){if(this.prompt){const t=await this.prompt(this.metadata.name);return t?(this.metadata.name=t,this.upload(e)):o}return this.filenameConflictAction=Oa,this.upload(e)}if("skip"==this.filenameConflictAction)return o}const r=$a(await fetch("https://www.googleapis.com/upload/drive/v3/files"+(t?"/"+t:"")+"?uploadType=resumable",{method:a,headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json","X-Upload-Content-Length":this.file.size,"X-Upload-Content-Type":this.contentType},body:JSON.stringify(this.metadata)})).headers.get("Location");if(this.url=r,!this.cancelled)return this.onProgress&&this.onProgress(0,this.file.size),Ga(this)}};async function za(e,t){const a=await fetch(_a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+e.clientId+"&client_secret="+e.clientKey+"&grant_type=authorization_code&code="+t.code+"&redirect_uri="+browser.identity.getRedirectURL()}),n=await Ha(a);return e.accessToken=n.access_token,e.refreshToken=n.refresh_token,e.expirationDate=Date.now()+1e3*n.expires_in,{accessToken:e.accessToken,refreshToken:e.refreshToken,expirationDate:e.expirationDate}}function qa(e={}){return Boolean(browser.identity&&browser.identity.getAuthToken)&&!e.forceWebAuthFlow}async function Ka(e,t,a=!0){const n=t.split("/");n.pop();const o=e.folderIds.get(n.join("/"));if(o)return o;let r="root";if(n.length){let o="";for(const i of n){o&&(o+="/"),o+=i;const n=e.folderIds.get(o);if(n)r=n;else try{r=await Va(e,i,r),e.folderIds.set(o,r)}catch(n){if("path_not_found"==n.message&&a)return e.folderIds.clear(),Ka(e,t,!1);throw n}}}return r}async function Va(e,t,a){const n=await async function(e,t,a){const n=await fetch(Ba+"?q=mimeType = 'application/vnd.google-apps.folder' and name = '"+t+"' and trashed != true and '"+a+"' in parents",{headers:{Authorization:"Bearer "+e.accessToken}});return Ha(n)}(e,t,a);if(n.files.length)return n.files[0].id;{const n=await async function(e,t,a){const n=await fetch(Ba,{method:"POST",headers:{Authorization:"Bearer "+e.accessToken,"Content-Type":"application/json"},body:JSON.stringify({name:t,parents:[a],mimeType:"application/vnd.google-apps.folder"})});return Ha(n)}(e,t,a);return n.id}}async function Ga(e){let t=e.file,a=e.file.size;(e.offset||e.chunkSize)&&(e.chunkSize&&(a=Math.min(e.offset+e.chunkSize,e.file.size)),t=t.slice(e.offset,a));const n=await fetch(e.url,{method:"PUT",headers:{Authorization:"Bearer "+e.token,"Content-Type":e.contentType,"Content-Range":"bytes "+e.offset+"-"+(a-1)+"/"+e.file.size,"X-Upload-Content-Type":e.contentType},body:t});if(e.onProgress&&!e.cancelled&&e.onProgress(e.offset+e.chunkSize,e.file.size),200==n.status||201==n.status)return n.json();if(308==n.status){const t=n.headers.get("Range");if(t&&(e.offset=parseInt(t.match(/\d+/g).pop(),10)+1),e.cancelled)throw new Error("upload_cancelled");return Ga(e)}$a(n)}async function Ha(e){e=$a(e);const t=await e.json();if(t.error)throw new Error(t.error);return t}function $a(e){if(200==e.status)return e;throw 404==e.status?new Error("path_not_found"):401==e.status?new Error("invalid_token"):new Error("unknown_error ("+e.status+")")}const Ja="https://api.dropboxapi.com/oauth2/token",Ya="uniquify",Za="prompt",Qa=/[\u007f-\uffff]/g;class Xa{constructor(e){this.file=e.file,this.onProgress=e.onProgress,this.contentType=this.file.type||"application/octet-stream",this.metadata={name:e.filename,mimeType:this.contentType},this.token=e.token,this.offset=0,this.chunkSize=e.chunkSize||8388608,this.filenameConflictAction=e.filenameConflictAction,this.prompt=e.prompt}async upload(){const e=nn(await fetch("https://api.dropboxapi.com/2/files/search_v2",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:on({query:this.metadata.name,options:{filename:!0}})})),t=await an(e);if(t.matches.length)if(this.filenameConflictAction==Za)if(this.prompt){const e=await this.prompt(this.metadata.name);if(!e)return t;this.metadata.name=e}else this.filenameConflictAction=Ya;else if("skip"==this.filenameConflictAction)return t;const a=nn(await fetch("https://content.dropboxapi.com/2/files/upload_session/start",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Dropbox-API-Arg":on({close:!1}),"Content-Type":"application/octet-stream"}})),n=(await an(a)).session_id;if(this.sessionId=n,!this.cancelled)return this.onProgress&&this.onProgress(0,this.file.size),tn(this)}}async function en(e,t){const a=await fetch(Ja,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+e.clientId+"&client_secret="+e.clientKey+"&grant_type=authorization_code&code="+t.code+"&redirect_uri="+browser.identity.getRedirectURL()}),n=await an(a);return e.accessToken=n.access_token,e.refreshToken=n.refresh_token,e.expirationDate=Date.now()+1e3*n.expires_in,{accessToken:e.accessToken,refreshToken:e.refreshToken,expirationDate:e.expirationDate}}async function tn(e){let t=e.file,a=e.file.size;(e.offset||e.chunkSize)&&(e.chunkSize&&(a=Math.min(e.offset+e.chunkSize,e.file.size)),t=t.slice(e.offset,a));const n=nn(await fetch("https://content.dropboxapi.com/2/files/upload_session/append_v2",{method:"POST",headers:{Authorization:"Bearer "+e.token,"Content-Type":"application/octet-stream","Dropbox-API-Arg":on({cursor:{session_id:e.sessionId,offset:e.offset},close:a==e.file.size})},body:t}));if(e.onProgress&&!e.cancelled&&e.onProgress(e.offset+e.chunkSize,e.file.size),200==n.status&&(e.offset=a,e.offset<e.file.size))return tn(e);let o=e.metadata.name;o.startsWith("/")||(o="/"+o);const r=await fetch("https://content.dropboxapi.com/2/files/upload_session/finish",{method:"POST",headers:{Authorization:"Bearer "+e.token,"Content-Type":"application/octet-stream","Dropbox-API-Arg":on({cursor:{session_id:e.sessionId,offset:e.offset},commit:{path:o,mode:"overwrite"==e.filenameConflictAction?"overwrite":"add",autorename:e.filenameConflictAction==Ya}})}});if(200==r.status)return an(r);if(409==r.status&&e.filenameConflictAction==Za)return e.offset=0,e.upload();throw new Error("unknown_error ("+r.status+")")}async function an(e){e=nn(e);const t=await e.json();if(t.error)throw new Error(t.error);return t}function nn(e){if(200==e.status)return e;throw 401==e.status?new Error("invalid_token"):new Error("unknown_error ("+e.status+")")}function on(e){return JSON.stringify(e).replace(Qa,(function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)}))}const rn="",sn="prompt",cn="Authorization",ln="/",dn=".",un="Error ",fn=/\s\((\d+)\)$/,mn="PROPFIND",hn="MKCOL",wn=400;class pn{constructor(e,t,a){e.endsWith(ln)||(e+=ln),this.url=e,this.authorization="Basic "+btoa(t+":"+a)}upload(e,t,a){return this.controller=new AbortController,a.signal=this.controller.signal,a.authorization=this.authorization,a.url=this.url,bn(e,t,a)}abort(){this.controller&&this.controller.abort()}}async function bn(e,t,a){const{authorization:n,filenameConflictAction:o,prompt:r,signal:i,preventRetry:s}=a;let{url:c}=a;try{if("overwrite"==o){let n=await l(e,"PUT",t);if(201==n.status)return n;if(n.status>=wn){if(n=await l(e,"DELETE"),n.status>=wn)throw new Error(un+n.status);return await bn(e,t,a)}}else{let n=await l(e,"HEAD");if(200==n.status){if("uniquify"==o||o==sn&&!r){const{filenameWithoutExtension:n,extension:o,indexFilename:r}=function(e){let t=e,a=rn;const n=e.lastIndexOf(".");n>-1&&(t=e.substring(0,n),a=e.substring(n+1));let o;return({filenameWithoutExtension:t,indexFilename:o}=function(e){const t=e.match(fn);let a=0;if(t&&t.length>1){const n=Number(t[t.length-1]);Number.isNaN(n)||(a=n,e=e.replace(fn,rn))}return{filenameWithoutExtension:e,indexFilename:a}}(t)),{filenameWithoutExtension:t,extension:a,indexFilename:o}}(e);return a.indexFilename=r+1,await bn(function(e,t){return e+" ("+a.indexFilename+")"+(t?dn+t:rn)}(n,o),t,a)}if(o==sn)return(e=await r(e))?bn(e,t,a):n;if("skip"==o)return n}else{if(404==n.status){if(n=await l(e,"PUT",t),n.status>=wn&&!s){if(e.includes(ln))return await async function(){const t=e.split(ln);t.pop();let a=rn;for(const e of t)if(e){a+=e;if(404==(await l(a,mn)).status){const e=await l(a,hn);if(e.status>=wn)throw new Error(un+e.status)}a+=ln}}(),a.preventRetry=!0,await bn(e,t,a);throw new Error(un+n.status)}return n}if(n.status>=wn)throw new Error(un+n.status)}}}catch(e){if("AbortError"!=e.name)throw e}function l(e,t,a){const o={[cn]:n};return a&&(o["Content-Type"]="text/html"),fetch(c+e,{method:t,headers:o,signal:i,body:a,credentials:"omit"})}}const gn="",yn="skip",vn="uniquify",kn="overwrite",An="prompt",xn=".",Tn=/\s\((\d+)\)$/,In="AbortError",Sn="https://github.com",Cn="https://api.github.com",Ln="blob",En="repos",Rn="contents";let Pn;class Mn{constructor(e,t,a,n){this.headers=new Map([["Authorization","Bearer "+e],["Accept","application/vnd.github+json"],["X-GitHub-Api-Version","2022-11-28"]]),this.userName=t,this.repositoryName=a,this.branch=n}async upload(e,t,a){this.controller=new AbortController,a.signal=this.controller.signal,a.headers=this.headers;const n=t instanceof Blob?await(o=t,new Promise(((e,t)=>{const a=new FileReader;a.onloadend=()=>e(a.result.match(/^data:[^,]+,(.*)$/)[1]),a.onerror=e=>t(e.detail),a.readAsDataURL(o)}))):btoa(unescape(encodeURIComponent(t)));var o;return async function(e,t,a,n,o,r){const{filenameConflictAction:i,prompt:s,signal:c,headers:l}=r;for(;Pn;)await Pn;try{Pn=await d({path:n,content:o})}finally{Pn=null}return{url:`${Sn}/${e}/${t}/${Ln}/${a}/${n}`};async function d({path:n,content:o,message:f="",sha:h}){try{const e=await w("PUT",JSON.stringify({content:o,message:f,branch:a,sha:h})),t=await e.json();if(422==e.status){if(i==kn){const e=await w("GET"),t=(await e.json()).sha;return await d({path:n,content:o,message:f,sha:t})}if(i==vn){const{filenameWithoutExtension:e,extension:t,indexFilename:a}=u(n);return r.indexFilename=a+1,n=m(e,t),await d({path:n,content:o,message:f})}if(i==yn)return t;if(i==An)return s?(n=await s(n))?await d({path:n,content:o,message:f}):t:(r.filenameConflictAction=vn,await d({path:n,content:o,message:f}))}if(e.status<400)return t;throw new Error(t.message)}catch(e){if(e.name!=In)throw e}function w(a,o){return fetch(`${Cn}/${En}/${e}/${t}/${Rn}/${n}`,{method:a,headers:l,body:o,signal:c})}}function u(e){let t=e,a=gn;const n=e.lastIndexOf(xn);let o;return n>-1&&(t=e.substring(0,n),a=e.substring(n+1)),({filenameWithoutExtension:t,indexFilename:o}=f(t)),{filenameWithoutExtension:t,extension:a,indexFilename:o}}function f(e){const t=e.match(Tn);let a=0;if(t&&t.length>1){const n=Number(t[t.length-1]);Number.isNaN(n)||(a=n,e=e.replace(Tn,gn))}return{filenameWithoutExtension:e,indexFilename:a}}function m(e,t){return e+" ("+r.indexFilename+")"+(t?xn+t:gn)}}(this.userName,this.repositoryName,this.branch,e,n,a)}abort(){this.controller&&this.controller.abort()}}const Un="",Dn="uniquify",Wn=".",Fn=/\s\((\d+)\)$/;class Nn{constructor(e,t,a,n,o="s3.amazonaws.com"){this.api=new zn({domain:o,region:e,bucket:t,accessKey:a,secretKey:n}),this.headObjectSupported=!0,this.listObjectsSupported=!0}async upload(e,t,a){const{filenameConflictAction:n,prompt:o}=a;this.controller=new AbortController,a.signal=this.controller.signal;try{if("overwrite"==n)return this.api.putObject({path:e},{body:await _n(t)});{let r;if(this.headObjectSupported&&(r=await this.api.headObject({path:e},a)),this.headObjectSupported&&403!=r.status||(this.headObjectSupported=!1,this.listObjectsSupported&&(r=await this.api.listObjects({path:e},a)),this.listObjectsSupported&&403!=r.status||(this.listObjectsSupported=!1,r=await this.api.getObject({path:e},a))),200!=r.status){if(404==r.status)return t=new Uint8Array(await t.arrayBuffer()),this.api.putObject({path:e},{body:await _n(t)});throw new Error(r.statusText||"Error "+r.status)}if("prompt"==n)return o?(e=await o(e))?this.upload(e,t,a):r:(a.filenameConflictAction=Dn,this.upload(e,t,a));if(n==Dn){const{filenameWithoutExtension:n,extension:o,indexFilename:r}=function(e){let t=e,a="";const n=e.lastIndexOf(".");n>-1&&(t=e.substring(0,n),a=e.substring(n+1));let o;return({filenameWithoutExtension:t,indexFilename:o}=function(e){const t=e.match(Fn);let a=0;if(t&&t.length>1){const n=Number(t[t.length-1]);Number.isNaN(n)||(a=n,e=e.replace(Fn,""))}return{filenameWithoutExtension:e,indexFilename:a}}(t)),{filenameWithoutExtension:t,extension:a,indexFilename:o}}(e);return a.indexFilename=r+1,e=function(e,t,a){return e+" ("+t+")"+(a?Wn+a:Un)}(n,a.indexFilename,o),this.upload(e,t,a)}}}catch(e){if("AbortError"!=e.name)throw e}}abort(){this.controller&&this.controller.abort()}}async function _n(e){return new Uint8Array(await new Response(e).arrayBuffer())}const Bn="AWS4",On=Bn+"-HMAC-SHA256",jn="aws4_request";class zn{constructor({domain:e,region:t,bucket:a,accessKey:n,secretKey:o}){this.domain=e,this.region=t,this.bucket=a,this.accessKey=n,this.secretKey=o}async putObject({path:e},{headers:t={},body:a}){return qn(this,{path:e},{method:"PUT",headers:t,body:a})}async getObject({path:e},{headers:t={}}={}){return qn(this,{path:e},{method:"GET",headers:t})}async headObject({path:e},{headers:t={}}={}){return qn(this,{path:e},{method:"HEAD",headers:t})}async listObjects({path:e},{headers:t={},continuationToken:a,delimiter:n,encodingType:o,prefix:r,maxKeys:i}={}){const s=new URLSearchParams;return s.set("list-type","2"),a&&s.set("continuation-token",a),n&&s.set("delimiter",n),o&&s.set("encoding-type",o),r&&s.set("prefix",r),i&&s.set("max-keys",i),qn(this,{path:e,searchParams:s},{method:"GET",headers:t})}}async function qn({region:e,bucket:t,accessKey:a,secretKey:n,domain:o},{path:r="/",searchParams:i=new URLSearchParams},{method:s,headers:c={},body:l}){const d=function(e){const t=new Date(e);return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}(new Date);r.startsWith("/")||(r="/"+r),c.host=t+"."+o,l&&(c["content-length"]=l.byteLength),c["x-amz-content-sha256"]=await Gn(l),c["x-amz-date"]=d,c.authorization=On+" Credential="+a+"/"+Hn(d,e,"s3")+",SignedHeaders="+Vn(c)+",Signature="+await async function({region:e,secretKey:t,service:a},{path:n,searchParams:o},{method:r,headers:i,body:s,isoDate:c}){const l=await async function(e,t,a,n,o,r,i,s){const c=await async function(e,t,a,n,o=new Uint8Array(0)){return n+"\n"+function(e){return decodeURIComponent(e).replace(/[^A-Za-z0-9-._~/]/g,Kn)}(e)+"\n"+function(e){if(e){let t="";e.sort();for(const[a,n]of e)t+=encodeURIComponent(a)+"="+encodeURIComponent(n)+"&";return t.slice(0,-1)}return""}(t)+"\n"+function(e){let t="";const a=Object.keys(e).sort();for(const n of a)t+=n+":"+e[n]+"\n";return t}(a)+"\n"+Vn(a)+"\n"+await Gn(o)}(e,t,a,i,n);return On+"\n"+o+"\n"+Hn(o,r,s)+"\n"+Zn(await $n(Yn(c)))}(n,o,i,s,c,e,r,a),d=await async function(e,t,a,n){const o=await Jn(Yn(Bn+e),Yn(t.substring(0,8))),r=await Jn(o,Yn(a)),i=await Jn(r,Yn(n));return Jn(i,Yn(jn))}(t,c,e,a);return Zn(await Jn(d,Yn(l)))}({region:e,secretKey:n,service:"s3"},{path:r,searchParams:i},{method:s,headers:c,body:l,isoDate:d});const u="https://"+t+"."+o+r+(i.size?"?"+i:""),f={method:s,headers:c};return l&&(f.body=l),fetch(u,f)}function Kn(e){let t=encodeURIComponent(e);return t=t.startsWith("%")?t.toUpperCase():"%"+t.charCodeAt(0).toString(16).toUpperCase(),t}function Vn(e){return Object.keys(e).map((e=>e.toLowerCase())).sort().join(";")}async function Gn(e=new Uint8Array(0)){return Zn(await $n(e))}function Hn(e,t,a){return e.substring(0,8)+"/"+t+"/"+a+"/"+jn}async function $n(e){return crypto.subtle.digest("SHA-256",e)}async function Jn(e,t){const a={name:"HMAC",hash:{name:"SHA-256"}},n=await crypto.subtle.importKey("raw",e,a,!1,["sign"]);return crypto.subtle.sign(a,n,t)}function Yn(e){return(new TextEncoder).encode(e)}function Zn(e){return Array.from(new Uint8Array(e)).map((e=>e.toString(16).padStart(2,"0"))).join("")}const Qn=[0],Xn=Symbol(),eo=new TextEncoder,to=new TextDecoder,ao=new Array(256);let no=0;function oo(e,t,a,n){if(void 0===n){if(no++,!(ao.length-no>=Qn.length))throw new Error("Reached maximum number of custom types");ao[ao.length-no]={serialize:e,parse:t,test:a}}else ao[n]={serialize:e,parse:t,test:a}}oo((async function(e,t){const a=e.objects.indexOf(t);await co(e,a)}),(async function(e){const t=await yo(e);return new wo(t,e)}),To,0),oo(null,(function(){return{}}),So),oo(lo,vo,Co),oo(uo,ko,(function(e){return"string"==typeof e})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(8*t);return new Float64Array(a.buffer)}),(function(e){return"Float64Array"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(4*t);return new Float32Array(a.buffer)}),(function(e){return"Float32Array"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(4*t);return new Uint32Array(a.buffer)}),(function(e){return"Uint32Array"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(4*t);return new Int32Array(a.buffer)}),(function(e){return"Int32Array"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(2*t);return new Uint16Array(a.buffer)}),(function(e){return"Uint16Array"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(2*t);return new Int16Array(a.buffer)}),(function(e){return"Int16Array"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(t);return new Uint8ClampedArray(a.buffer)}),(function(e){return"Uint8ClampedArray"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e);return await e.consume(t)}),(function(e){return"Uint8Array"==e.constructor.name})),oo(fo,(async function(e){const t=await yo(e),a=await e.consume(t);return new Int8Array(a.buffer)}),(function(e){return"Int8Array"==e.constructor.name})),oo((async function(e,t){await co(e,t.byteLength),await e.append(new Uint8Array(t))}),(async function(e){const t=await yo(e);return(await e.consume(t)).buffer}),(function(e){return"ArrayBuffer"==e.constructor.name})),oo(mo,Ao,Eo),oo((async function(e,t){const a=new Uint8Array(new Uint32Array([t]).buffer);await e.append(a)}),(async function(e){const t=await e.consume(4);return new Uint32Array(t.buffer)[0]}),(function(e){return Ro(e)&&e>=0&&e<=4294967295})),oo((async function(e,t){const a=new Uint8Array(new Int32Array([t]).buffer);await e.append(a)}),(async function(e){const t=await e.consume(4);return new Int32Array(t.buffer)[0]}),(function(e){return Ro(e)&&e>=-2147483648&&e<=2147483647})),oo((async function(e,t){const a=new Uint8Array(new Uint16Array([t]).buffer);await e.append(a)}),(async function(e){const t=await e.consume(2);return new Uint16Array(t.buffer)[0]}),(function(e){return Ro(e)&&e>=0&&e<=65535})),oo((async function(e,t){const a=new Uint8Array(new Int16Array([t]).buffer);await e.append(a)}),(async function(e){const t=await e.consume(2);return new Int16Array(t.buffer)[0]}),(function(e){return Ro(e)&&e>=-32768&&e<=32767})),oo((async function(e,t){const a=new Uint8Array([t]);await e.append(a)}),(async function(e){const t=await e.consume(1);return new Uint8Array(t.buffer)[0]}),(function(e){return Ro(e)&&e>=0&&e<=255})),oo((async function(e,t){const a=new Uint8Array(new Int8Array([t]).buffer);await e.append(a)}),(async function(e){const t=await e.consume(1);return new Int8Array(t.buffer)[0]}),(function(e){return Ro(e)&&e>=-128&&e<=127})),oo(null,(function(){return}),(function(e){return void 0===e})),oo(null,(function(){return null}),(function(e){return null===e})),oo(null,(function(){return NaN}),(function(e){return Number.isNaN(e)})),oo(ho,xo,(function(e){return"boolean"==typeof e})),oo((async function(e,t){await uo(e,t.description)}),(async function(e){const t=await ko(e);return Symbol(t)}),Po),oo(null,(function(){return Xn}),Lo),oo((async function(e,t){const a=t.entries();await co(e,t.size);for(const[t,n]of a)await co(e,t),await co(e,n)}),(async function(e){const t=await yo(e),a=new Map;t&&await async function n(o=0){const r=await yo(e),i=await yo(e);e.setObject([r,i],((e,t)=>a.set(e,t))),o<t-1&&await n(o+1)}();return a}),(function(e){return e instanceof Map})),oo((async function(e,t){await co(e,t.size);for(const a of t)await co(e,a)}),(async function(e){const t=await yo(e),a=new Set;t&&await async function n(o=0){const r=await yo(e);e.setObject([r],(e=>a.add(e))),o<t-1&&await n(o+1)}();return a}),(function(e){return e instanceof Set})),oo((async function(e,t){await mo(e,t.getTime())}),(async function(e){const t=await Ao(e);return new Date(t)}),(function(e){return e instanceof Date})),oo((async function(e,t){await uo(e,t.message),await uo(e,t.stack)}),(async function(e){const t=await ko(e),a=await ko(e),n=new Error(t);return n.stack=a,n}),(function(e){return e instanceof Error})),oo((async function(e,t){await uo(e,t.source),await uo(e,t.flags)}),(async function(e){const t=await ko(e),a=await ko(e);return new RegExp(t,a)}),(function(e){return e instanceof RegExp})),oo((async function(e,t){await uo(e,t.valueOf())}),(async function(e){return new String(await ko(e))}),(function(e){return e instanceof String})),oo((async function(e,t){await mo(e,t.valueOf())}),(async function(e){return new Number(await Ao(e))}),(function(e){return e instanceof Number})),oo((async function(e,t){await ho(e,t.valueOf())}),(async function(e){return new Boolean(await xo(e))}),(function(e){return e instanceof Boolean}));class ro{constructor(e,t){this.stream=new io(e,t),this.objects=[]}append(e){return this.stream.append(e)}flush(){return this.stream.flush()}addObject(e){this.objects.push(Mo(e)&&!To(e,this)?e:void 0)}}class io{constructor(e,t){this.offset=0,this.appendData=e,this.value=new Uint8Array(t)}async append(e){if(this.offset+e.length>this.value.length){const t=this.value.length-this.offset;await this.append(new Uint8Array(e).subarray(0,t)),await this.appendData({value:this.value}),this.offset=0,await this.append(new Uint8Array(e).subarray(t))}else this.value.set(e,this.offset),this.offset+=e.length}async flush(){this.offset&&await this.appendData({value:new Uint8Array(this.value).subarray(0,this.offset),done:!0})}}function so(e,{chunkSize:t=8388608}={}){let a,n,o,r,i,s;return{[Symbol.asyncIterator]:()=>({next:()=>r?{done:r}:async function(){s?s():c().catch((()=>{}));i=new Promise((e=>s=e));const e=await async function(){const{value:e,done:t}=await n;r=t,t||l();return e}();return{value:e}}(),return:()=>({done:!0})})};async function c(){l(),a=new ro(d,t),await co(a,e),await a.flush()}function l(){n=new Promise((e=>o=e))}async function d(e){o(e),await i}}async function co(e,t){const a=ao.findIndex((({test:a}={})=>a&&a(t,e)));e.addObject(t),await e.append(new Uint8Array([a]));const n=ao[a].serialize;n&&await n(e,t),0!=a&&So(t)&&(await async function(e,t){const a=Object.getOwnPropertySymbols(t),n=a.map((e=>[e,t[e]]));await lo(e,n)}(e,t),await async function(e,t){if(ArrayBuffer.isView(t))await co(e,0);else{let a=Object.entries(t);Co(t)&&(a=a.filter((([e])=>!Ro(Number(e))))),await co(e,a.length);for(const[t,n]of a)await uo(e,t),await co(e,n)}}(e,t))}async function lo(e,t){await co(e,t.length);const a=Object.keys(t).filter((e=>Ro(Number(e)))).map((e=>Number(e)));let n=0,o=a[n];for(const[r,i]of t.entries())o==r?(o=a[++n],await co(e,i)):await co(e,Xn)}async function uo(e,t){const a=eo.encode(t);await co(e,a.length),await e.append(a)}async function fo(e,t){await co(e,t.length),await e.append("Uint8Array"==t.constructor.name?t:new Uint8Array(t.buffer))}async function mo(e,t){const a=new Uint8Array(new Float64Array([t]).buffer);await e.append(a)}async function ho(e,t){const a=new Uint8Array([Number(t)]);await e.append(a)}class wo{constructor(e,t){this.index=e,this.data=t}getObject(){return this.data.objects[this.index]}}class po{constructor(e){this.stream=new bo(e),this.objects=[],this.setters=[]}consume(e){return this.stream.consume(e)}getObjectId(){const e=this.objects.length;return this.objects.push(void 0),e}resolveObject(e,t){Mo(t)&&!Io(t)&&(this.objects[e]=t)}setObject(e,t){this.setters.push({functionArguments:e,setterFunction:t})}executeSetters(){this.setters.forEach((({functionArguments:e,setterFunction:t})=>{t(...e.map((e=>Io(e)?e.getObject():e)))}))}}class bo{constructor(e){this.offset=0,this.value=new Uint8Array(0),this.consumeData=e}async consume(e){if(this.offset+e>this.value.length){const t=new Uint8Array(this.value).subarray(this.offset,this.value.length),a=await this.consumeData();return t.length+a.length!=this.value.length&&(this.value=new Uint8Array(t.length+a.length)),this.value.set(t),this.value.set(a,t.length),this.offset=0,this.consume(e)}{const t=this.value.slice(this.offset,this.offset+e);return this.offset+=t.length,t}}}function go(){let e,t,a,n,o,r;return{next:async t=>t?async function(t){o?await o:async function(){let t;n=new Promise((e=>t=e)),e=new po(s),i();const a=await yo(e);e.executeSetters(),t(a)}().catch((()=>{}));return function(){o=new Promise((e=>r=e))}(),a(t),{done:!1}}(t):{value:await n,done:!0},return:()=>({done:!0})};function i(){t=new Promise((e=>a=e))}async function s(){const e=await t;return i(),r&&r(),e}}async function yo(e){const t=(await e.consume(1))[0],a=ao[t].parse,n=e.getObjectId(),o=await a(e);return 0!=t&&So(o)&&(await async function(e,t){const a=await vo(e);e.setObject([a],(e=>e.forEach((([e,a])=>t[e]=a))))}(e,o),await async function(e,t){const a=await yo(e);a&&await n();async function n(o=0){const r=await ko(e),i=await yo(e);e.setObject([i],(e=>t[r]=e)),o<a-1&&await n(o+1)}}(e,o)),e.resolveObject(n,o),o}async function vo(e){const t=await yo(e),a=new Array(t);return t&&await async function n(o=0){const r=await yo(e);Lo(r)||e.setObject([r],(e=>a[o]=e));o<t-1&&await n(o+1)}(),a}async function ko(e){const t=await yo(e),a=await e.consume(t);return to.decode(a)}async function Ao(e){const t=await e.consume(8);return new Float64Array(t.buffer)[0]}async function xo(e){const t=await e.consume(1);return Boolean(t[0])}function To(e,t){return So(e)&&t.objects.includes(e)}function Io(e){return e instanceof wo}function So(e){return e===Object(e)}function Co(e){return"number"==typeof e.length}function Lo(e){return e===Xn}function Eo(e){return"number"==typeof e}function Ro(e){return Eo(e)&&Number.isInteger(e)}function Po(e){return"symbol"==typeof e}function Mo(e){return So(e)||Po(e)}class Uo{constructor(e,t,a,n){this.headers=new Map([["Authorization","Bearer "+e],["Accept","multipart/form-data"]]),this.restApiUrl=t,this.fileFieldName=a,this.urlFieldName=n}async upload(e,t,a){this.controller=new AbortController;const n=t instanceof Blob?t:new Blob([t],{type:"text/html"});let o=new FormData;this.fileFieldName&&o.append(this.fileFieldName,n,e),this.urlFieldName&&o.append(this.urlFieldName,a);const r=await fetch(this.restApiUrl,{method:"POST",body:o,headers:this.headers,signal:this.controller.signal});if([200,201].includes(r.status))return r.json();throw new Error(await r.text())}abort(){this.controller&&this.controller.abort()}}const Do="/src/ui/pages/offscreen-document.html",Wo=16777216;let Fo,No=0;async function _o(e){return await jo(),browser.runtime.sendMessage({method:"revokeObjectURL",url:e})}async function Bo(e,t){return await jo(),zo({method:"getBlobURL",mimeType:t,requestId:No},e)}async function Oo(e,t,a){return await jo(),browser.runtime.sendMessage({method:"getImageData",url:e,width:t,height:a})}async function jo(){const e=browser.runtime.getURL(Do);(await browser.runtime.getContexts({contextTypes:["OFFSCREEN_DOCUMENT"],documentUrls:[e]})).length>0||(Fo?await Fo:(Fo=await browser.offscreen.createDocument({url:Do,justification:"Auto-save/Compression features",reasons:["DOM_PARSER","WORKERS","CLIPBOARD","BLOBS"]}),Fo=null))}async function zo(e,t){let a;No++;for(let n=0;n*Wo<t.length;n++)e.truncated=t.length>Wo,e.truncated?(e.finished=(n+1)*Wo>t.length,e.data=t.slice(n*Wo,(n+1)*Wo)):e.data=t,a=await browser.runtime.sendMessage(e);return a}const qo=new Map,Ko=new Map,Vo=/([{}()^$&.*?/+|[\\\\]|\]|-)/g;let Go="207618107333-h1220p1oasj3050kr5r416661adm091a.apps.googleusercontent.com",Ho="VQJ8Gq8Vxx72QyxPyeLtWvUt";const $o=browser.runtime.getManifest().oauth2;$o&&(Go=$o.client_id,Ho=$o.client_secret);const Jo=new class{constructor(e,t,a){this.clientId=e,this.clientKey=t,this.scopes=a,this.folderIds=new Map,setInterval((()=>this.folderIds.clear()),6e4)}async auth(e={interactive:!0}){return qa(e)?(this.accessToken=await browser.identity.getAuthToken({interactive:e.interactive}),{revokableAccessToken:this.accessToken}):(this.authURL="https://accounts.google.com/o/oauth2/v2/auth?client_id="+this.clientId+"&response_type=code&access_type=offline&redirect_uri="+browser.identity.getRedirectURL()+"&scope="+this.scopes.join(" "),e.code?za(this,e):async function(e,t){let a;try{if(browser.identity&&browser.identity.launchWebAuthFlow&&!t.forceWebAuthFlow){const a=await browser.identity.launchWebAuthFlow({interactive:t.interactive,url:e.authURL});return t.code=new URLSearchParams(new URL(a).search).get("code"),await za(e,t)}if(t.launchWebAuthFlow)return t.extractAuthCode(browser.identity.getRedirectURL()).then((e=>a=e)).catch((()=>{})),await t.launchWebAuthFlow({url:e.authURL});throw new Error("auth_not_supported")}catch(n){if(n.message&&("code_required"==n.message||n.message.includes("access"))){if(a)return t.code=a,await za(e,t);throw new Error("code_required")}throw n}}(this,e))}setAuthInfo(e,t){qa(t)||(e?(this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationDate=e.expirationDate):(delete this.accessToken,delete this.refreshToken,delete this.expirationDate))}async refreshAuthToken(){if(this.refreshToken){const e=await fetch(_a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+this.clientId+"&refresh_token="+this.refreshToken+"&grant_type=refresh_token&client_secret="+this.clientKey});if(400==e.status)throw new Error("unknown_token");const t=await Ha(e);return this.accessToken=t.access_token,t.refresh_token&&(this.refreshToken=t.refresh_token),t.expires_in&&(this.expirationDate=Date.now()+1e3*t.expires_in),{accessToken:this.accessToken,refreshToken:this.refreshToken,expirationDate:this.expirationDate}}try{return browser.identity&&browser.identity.removeCachedAuthToken&&this.accessToken&&await browser.identity.removeCachedAuthToken({token:this.accessToken}),this.accessToken=await browser.identity.getAuthToken({interactive:!1}),{revokableAccessToken:this.accessToken}}catch(e){delete this.accessToken}}async revokeAuthToken(e){if(e){if(browser.identity&&browser.identity.removeCachedAuthToken)try{await browser.identity.removeCachedAuthToken({token:e})}catch(e){}const t=await fetch("https://accounts.google.com/o/oauth2/revoke",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"token="+e});try{await Ha(t)}catch(e){if("invalid_token"!=e.message)throw e}finally{delete this.accessToken,delete this.refreshToken,delete this.expirationDate}}}async upload(e,t,a,n,o=!0){const r=await Ka(this,e),i=e.split("/").pop(),s=new ja({token:this.accessToken,file:t,parents:[r],filename:i,onProgress:a.onProgress,filenameConflictAction:a.filenameConflictAction,prompt:a.prompt});try{n&&n((()=>s.cancelled=!0)),await s.upload()}catch(r){if("path_not_found"==r.message&&o)return this.folderIds.clear(),this.upload(e,t,a,n);throw r}}}(Go,Ho,["https://www.googleapis.com/auth/drive.file"]),Yo=new class{constructor(e,t){this.clientId=e,this.clientKey=t}async auth(e={interactive:!0}){return this.authURL="https://www.dropbox.com/oauth2/authorize?client_id="+this.clientId+"&response_type=code&token_access_type=offline&redirect_uri="+browser.identity.getRedirectURL(),e.code?en(this,e):async function(e,t){let a;try{return t.extractAuthCode(browser.identity.getRedirectURL()).then((e=>a=e)).catch((()=>{})),await t.launchWebAuthFlow({url:e.authURL})}catch(n){if(n.message&&("code_required"==n.message||n.message.includes("access"))){if(a)return t.code=a,await en(e,t);throw new Error("code_required")}throw n}}(this,e)}setAuthInfo(e){e?(this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationDate=e.expirationDate):(delete this.accessToken,delete this.refreshToken,delete this.expirationDate)}async refreshAuthToken(){if(this.refreshToken){const e=await fetch(Ja,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+this.clientId+"&refresh_token="+this.refreshToken+"&grant_type=refresh_token&client_secret="+this.clientKey});if(400==e.status)throw new Error("unknown_token");const t=await an(e);return this.accessToken=t.access_token,t.refresh_token&&(this.refreshToken=t.refresh_token),t.expires_in&&(this.expirationDate=Date.now()+1e3*t.expires_in),{accessToken:this.accessToken,refreshToken:this.refreshToken,expirationDate:this.expirationDate}}delete this.accessToken}async revokeAuthToken(e){if(e){const t=await fetch("https://api.dropboxapi.com/2/auth/token/revoke",{method:"POST",headers:{Authorization:"Bearer "+e}});try{await t.text()}catch(e){if("invalid_token"!=e.message)throw e}finally{delete this.accessToken,delete this.refreshToken,delete this.expirationDate}}}async upload(e,t,a,n){const o=new Xa({token:this.accessToken,file:t,filename:e,onProgress:a.onProgress,filenameConflictAction:a.filenameConflictAction,prompt:a.prompt});n&&n((()=>o.cancelled=!0)),await o.upload()}}("s50p6litdvuzrtb","i1vzwllesr14fzd");async function Zo(e,t){if(e.method.endsWith(".download"))return async function(e,t){const a=t.id;let n;if(e.blobURL)try{e.url=e.blobURL,e.compressContent?(e.pageData=await async function(e){const t=go();return await t.next(e),(await t.next()).value}(new Uint8Array(await(await fetch(e.blobURL)).arrayBuffer())),await Xo(e,t)):(e.content=await(await fetch(e.blobURL)).text(),await Qo(e,t))}catch(e){return{error:!0}}finally{try{await _o(e.blobURL)}catch(e){}}else if(e.compressContent){let n=Ko.get(a);if(n||(n=go(),Ko.set(a,n)),e.data)await n.next(new Uint8Array(e.data));else{Ko.delete(a);const e=(await n.next()).value;await Xo(e,t)}}else if(e.truncated?(n=qo.get(a),n||(n=[],qo.set(a,n)),n.push(e.content),e.finished&&qo.delete(a)):e.content&&(n=[e.content]),!e.truncated||e.finished){e.content=n.join("");try{e.url=await Bo(Array.from((new TextEncoder).encode(e.content)),e.mimeType),await Qo(e,t)}finally{try{await _o(e.url)}catch(e){}}}return{}}(e,t.tab);if(e.method.endsWith(".disableGDrive")){const e=await K();return $(),await Jo.revokeAuthToken(e&&(e.accessToken||e.revokableAccessToken)),{}}if(e.method.endsWith(".disableDropbox")){const e=await V();return J(),await Yo.revokeAuthToken(e&&(e.accessToken||e.revokableAccessToken)),{}}if(e.method.endsWith(".end")){if(e.hash)try{await Na(e.hash,e.woleetKey)}catch(e){Ht(t.tab.id,e.message,e.link)}return Aa(e.taskId),{}}return e.method.endsWith(".getInfo")?la.map(La):e.method.endsWith(".cancel")?(e.taskId?function(e){const t=la.find((t=>t.id==e));t&&Ca(t)}(e.taskId):Ia(t.tab.id),{}):e.method.endsWith(".cancelAll")?(Array.from(la).forEach((e=>Ca(e,!1))),{}):e.method.endsWith(".saveUrls")?(pa(e.urls),{}):void 0}async function Qo(e,t){const a=t.id;try{let n;if(e.backgroundSave&&!e.saveToGDrive&&!e.saveToDropbox&&!e.saveWithWebDAV&&!e.saveToGitHub&&!e.saveToRestFormApi&&!e.saveToS3){const t=await cr(e.filename,e);e.filenameConflictAction=t.filenameConflictAction,n=t.skipped}if(n)Jt(a);else{const n=e=>lr(a,e);let o;if(e.openEditor)$t(a),await ne({tabIndex:t.index+1,filename:e.filename,content:e.content});else if(e.saveToClipboard)await async function(e,t){return await jo(),zo({method:"saveToClipboard",mimeType:t,requestId:No},Array.from((new TextEncoder).encode(e)))}(e.content,e.mimeType);else if(e.saveWithWebDAV)o=await rr(e.taskId,er(e.filename),e.content,e.webDAVURL,e.webDAVUser,e.webDAVPassword,{filenameConflictAction:e.filenameConflictAction,prompt:n});else if(e.saveToGDrive)await ir(e.taskId,er(e.filename),new Blob([e.content],{type:e.mimeType}),{forceWebAuthFlow:e.forceWebAuthFlow},{onProgress:(e,t)=>Yt(a,e,t),filenameConflictAction:e.filenameConflictAction,prompt:n});else if(e.saveToDropbox)await sr(e.taskId,er(e.filename),new Blob([e.content],{type:e.mimeType}),{onProgress:(e,t)=>Yt(a,e,t),filenameConflictAction:e.filenameConflictAction,prompt:n});else if(e.saveToGitHub)o=await nr(e.taskId,er(e.filename),e.content,e.githubToken,e.githubUser,e.githubRepository,e.githubBranch,{filenameConflictAction:e.filenameConflictAction,prompt:n}),await o.pushPromise;else if(e.saveWithCompanion)await Ea({filename:e.filename,content:e.content,filenameConflictAction:e.filenameConflictAction});else if(e.saveToRestFormApi)o=await ur(e.taskId,e.filename,e.content,t.url,e.saveToRestFormApiToken,e.saveToRestFormApiUrl,e.saveToRestFormApiFileFieldName,e.saveToRestFormApiUrlFieldName);else if(e.saveToS3)o=await or(e.taskId,er(e.filename),new Blob([e.content],{type:e.mimeType}),e.S3Domain,e.S3Region,e.S3Bucket,e.S3AccessKey,e.S3SecretKey,{filenameConflictAction:e.filenameConflictAction,prompt:n});else if(o=await dr(e,{confirmFilename:e.confirmFilename,incognito:t.incognito,filenameConflictAction:e.filenameConflictAction,filenameReplacementCharacter:e.filenameReplacementCharacter,bookmarkId:e.bookmarkId,replaceBookmarkURL:e.replaceBookmarkURL,includeInfobar:e.includeInfobar,openInfobar:e.openInfobar}),!o)throw new Error("upload_cancelled");if(e.bookmarkId&&e.replaceBookmarkURL&&o&&o.url&&await Ua(e.bookmarkId,{url:o.url}),Jt(a),e.openSavedPage&&!e.openEditor){const a={active:!0,url:"/src/ui/pages/viewer.html?blobURI="+e.url};null!=t.index&&(a.index=t.index+1),browser.tabs.create(a)}}}catch(e){e.message&&"upload_cancelled"==e.message||(console.error(e),Ht(a,e.message,e.link))}finally{if(!e.openSavedPage&&e.url)try{await _o(e.url)}catch(e){}}}async function Xo(e,t){const a=t.id;let n;try{const o=e=>lr(a,e);let r,i;if(e.backgroundSave&&!e.saveToGDrive&&!e.saveToDropbox&&!e.saveWithWebDAV&&!e.saveToGitHub&&!e.saveToRestFormApi&&!e.sharePage){const t=await cr(e.filename,e);e.filenameConflictAction=t.filenameConflictAction,r=t.skipped}if(r)Jt(a);else{if(n=await async function(e,t){await jo();const a=so(e);for await(const e of a)await browser.runtime.sendMessage({method:"compressPage",tabId:t.tabId,data:Array.from(e)});return browser.runtime.sendMessage({method:"compressPage",tabId:t.tabId,options:t})}(e.pageData,{insertTextBody:e.insertTextBody,url:e.pageData.url||t.url,createRootDirectory:e.createRootDirectory,tabId:a,selfExtractingArchive:e.selfExtractingArchive,extractDataFromPage:e.extractDataFromPage,preventAppendedData:e.preventAppendedData,insertCanonicalLink:e.insertCanonicalLink,insertMetaNoIndex:e.insertMetaNoIndex,insertMetaCSP:e.insertMetaCSP,password:e.password,embeddedImage:e.embeddedImage}),e.openEditor){$t(a);const o=Array.from(new Uint8Array(await(await fetch(n)).arrayBuffer()));await ne({tabIndex:t.index+1,filename:e.filename,content:o,compressContent:e.compressContent,selfExtractingArchive:e.selfExtractingArchive,extractDataFromPage:e.extractDataFromPage,insertTextBody:e.insertTextBody,insertMetaCSP:e.insertMetaCSP,embeddedImage:e.embeddedImage})}else if(e.foregroundSave||e.sharePage){const t=(await fetch(n)).blob();await fr(e.taskId,e.filename,t,e.pageData.mimeType,a,{foregroundSave:e.foregroundSave,sharePage:e.sharePage})}else if(e.saveWithWebDAV){const t=await(await fetch(n)).blob();i=await rr(e.taskId,er(e.filename),t,e.webDAVURL,e.webDAVUser,e.webDAVPassword,{filenameConflictAction:e.filenameConflictAction,prompt:o})}else if(e.saveToGDrive){const t=await(await fetch(n)).blob();await ir(e.taskId,er(e.filename),t,{forceWebAuthFlow:e.forceWebAuthFlow},{onProgress:(e,t)=>Yt(a,e,t),filenameConflictAction:e.filenameConflictAction,prompt:o})}else if(e.saveToDropbox){const t=await(await fetch(n)).blob();await sr(e.taskId,er(e.filename),t,{onProgress:(e,t)=>Yt(a,e,t),filenameConflictAction:e.filenameConflictAction,prompt:o})}else if(e.saveToGitHub){const t=await(await fetch(n)).blob();i=await nr(e.taskId,er(e.filename),t,e.githubToken,e.githubUser,e.githubRepository,e.githubBranch,{filenameConflictAction:e.filenameConflictAction,prompt:o}),await i.pushPromise}else if(e.saveToRestFormApi){const a=await(await fetch(n)).blob();i=await ur(e.taskId,e.filename,a,t.url,e.saveToRestFormApiToken,e.saveToRestFormApiUrl,e.saveToRestFormApiFileFieldName,e.saveToRestFormApiUrlFieldName)}else if(e.saveToS3){const t=await(await fetch(n)).blob();i=await or(e.taskId,er(e.filename),t,e.S3Domain,e.S3Region,e.S3Bucket,e.S3AccessKey,e.S3SecretKey,{filenameConflictAction:e.filenameConflictAction,prompt:o})}else if(e.backgroundSave)e.url=n,i=await dr(e,{confirmFilename:e.confirmFilename,incognito:t.incognito,filenameConflictAction:e.filenameConflictAction,filenameReplacementCharacter:e.filenameReplacementCharacter,bookmarkId:e.bookmarkId,replaceBookmarkURL:e.replaceBookmarkURL,includeInfobar:e.includeInfobar,openInfobar:e.openInfobar});else{const t=await(await fetch(n)).blob();await fr(e.taskId,e.filename,t,e.mimeType,a)}if(e.bookmarkId&&e.replaceBookmarkURL&&i&&i.url&&await Ua(e.bookmarkId,{url:i.url}),Jt(a),e.openSavedPage&&!e.openEditor){const e={active:!0,url:"/src/ui/pages/viewer.html?compressed&blobURI="+n,windowId:t.windowId};null!=t.index&&(e.index=t.index+1),browser.tabs.create(e)}}}catch(e){e.message&&"upload_cancelled"==e.message||(console.error(e),Ht(a,e.message,e.link))}finally{if(!e.openSavedPage&&n)try{await _o(n)}catch(e){}}}function er(e){return e.replace(/#/g,"%23")}async function tr(e,t){let a=await K();const n={interactive:!0,forceWebAuthFlow:e.forceWebAuthFlow,launchWebAuthFlow:e=>se(e),extractAuthCode:e=>ie(e)};return Jo.setAuthInfo(a,n),a&&a.accessToken&&!t||(a=await Jo.auth(n),a?await G(a):await $()),a}async function ar(e){let t=await V();const a={launchWebAuthFlow:e=>se(e),extractAuthCode:e=>ie(e)};return Yo.setAuthInfo(t),t&&t.accessToken&&!e||(t=await Yo.auth(a),t?await H(t):await J()),t}async function nr(e,t,a,n,o,r,i,{filenameConflictAction:s,prompt:c}){try{const l=Sa(e);if(!l||!l.cancelled){const l=new Mn(n,o,r,i);return Ta(e,(()=>l.abort())),await l.upload(t,a,{filenameConflictAction:s,prompt:c})}}catch(e){throw new Error(e.message+" (GitHub)")}}async function or(e,t,a,n,o,r,i,s,{filenameConflictAction:c,prompt:l}){try{const d=Sa(e);if(!d||!d.cancelled){const d=new Nn(o,r,i,s,n);return Ta(e,(()=>d.abort())),await d.upload(t,a,{filenameConflictAction:c,prompt:l})}}catch(e){throw new Error(e.message+" (S3)")}}async function rr(e,t,a,n,o,r,{filenameConflictAction:i,prompt:s}){try{const c=Sa(e);if(!c||!c.cancelled){const c=new pn(n,o,r);return Ta(e,(()=>c.abort())),await c.upload(t,a,{filenameConflictAction:i,prompt:s})}}catch(e){throw new Error(e.message+" (WebDAV)")}}async function ir(e,t,a,n,o){try{await tr(n);const r=Sa(e);if(!r||!r.cancelled)return await Jo.upload(t,a,o,(t=>Ta(e,t)))}catch(r){if("invalid_token"==r.message){let r;try{r=await Jo.refreshAuthToken()}catch(e){if("unknown_token"!=e.message)throw new Error(e.message+" (Google Drive)");r=await tr(n,!0)}return r?await G(r):await $(),await ir(e,t,a,n,o)}throw new Error(r.message+" (Google Drive)")}}async function sr(e,t,a,n){try{await ar();const o=Sa(e);if(!o||!o.cancelled)return await Yo.upload(t,a,n,(t=>Ta(e,t)))}catch(o){if("invalid_token"==o.message){let o;try{o=await Yo.refreshAuthToken()}catch(e){if("unknown_token"!=e.message)throw new Error(e.message+" (Dropbox)");o=await ar(!0)}return o?await H(o):await J(),await sr(e,t,a,n)}throw new Error(o.message+" (Dropbox)")}}async function cr(e,t){let a,n=t.filenameConflictAction;if("skip"==n){(await browser.downloads.search({filenameRegex:"(\\\\|/)"+(o=e,o.replace(Vo,"\\$1")+"$"),exists:!0})).length?a=!0:n="uniquify"}var o;return{skipped:a,filenameConflictAction:n}}function lr(e,t){return browser.tabs.sendMessage(e,{method:"content.prompt",message:"Filename conflict, please enter a new filename",value:t})}async function dr(e,t){const a={url:e.url,saveAs:t.confirmFilename,filename:e.filename,conflictAction:t.filenameConflictAction};t.incognito&&(a.incognito=!0);const n=await r(a,t.filenameReplacementCharacter);if(n.filename){let e=n.filename;return e.startsWith("file:")||(e.startsWith("/")&&(e=e.substring(1)),e="file:///"+er(e)),{url:e}}}async function ur(e,t,a,n,o,r,i,s){try{const c=Sa(e);if(!c||!c.cancelled){const c=new Uo(o,r,i,s);return Ta(e,(()=>c.abort())),await c.upload(t,a,n)}}catch(e){throw new Error(e.message+" (RestFormApi)")}}async function fr(e,t,a,n,o,{foregroundSave:r,sharePage:i}={}){const s=so({filename:t,taskId:e,foregroundSave:r,sharePage:i,content:await a.arrayBuffer(),mimeType:n});for await(const e of s)await browser.tabs.sendMessage(o,{method:"content.download",data:Array.from(e)});return browser.tabs.sendMessage(o,{method:"content.download"})}const mr={},hr={};async function wr(e,t){if("enableAutoSave"==e.method){const a=await f(t.id);a[t.id].autoSave=e.enabled,await m(a),async function(e){Promise.all([Nt(e),Re(e)])}(t)}if("isAutoSaveEnabled"==e.method)return Z(t)}async function pr(e,t){const a=t.id,n=await F(t.url,!0);if(n){let o;Gt(a,1,!0),n.content=e.content,n.url=e.url,n.frames=e.frames,n.canvases=e.canvases,n.fonts=e.fonts,n.stylesheets=e.stylesheets,n.images=e.images,n.posters=e.posters,n.videos=e.videos,n.usedFonts=e.usedFonts,n.shadowRoots=e.shadowRoots,n.referrer=e.referrer,n.updatedResources=e.updatedResources,n.worklets=e.worklets,n.adoptedStyleSheets=e.adoptedStyleSheets,n.visitDate=new Date(e.visitDate),n.backgroundTab=!0,n.autoSave=!0,n.incognito=t.incognito,n.tabId=a,n.tabIndex=t.index;try{if(n.autoSaveExternalSave)await async function(e){let t;e.autoSaveExternalSave=!1;try{t=await browser.runtime.sendNativeMessage("singlefile_companion",{method:"externalSave",pageData:e})}catch(e){if(!e.message||!e.message.includes("Native host has exited"))throw e}if(t&&t.error)throw new Error(t.error+" (Companion)")}(n);else{let r;if(o=await async function(e){return await jo(),browser.runtime.sendMessage({method:"processPage",options:e})}(n),!(n.saveToGDrive||n.saveWithWebDAV||n.saveToGitHub||n.saveToDropbox||n.saveWithCompanion||n.saveToRestFormApi||n.saveToS3)){const e=await cr(o.filename,n);r=e.skipped,n.filenameConflictAction=e.filenameConflictAction}if(!r){if(n.saveToGDrive){const t=await(await fetch(o.url)).blob();await ir(e.taskId,er(o.filename),t,n,{forceWebAuthFlow:n.forceWebAuthFlow},n.filenameConflictAction)}if(n.saveToDropbox){const t=await(await fetch(o.url)).blob();await sr(e.taskId,er(o.filename),t,{filenameConflictAction:n.filenameConflictAction})}else if(n.saveWithWebDAV){const t=await(await fetch(o.url)).blob();await rr(e.taskId,er(o.filename),t,n.webDAVURL,n.webDAVUser,n.webDAVPassword,{filenameConflictAction:n.filenameConflictAction})}else if(n.saveToGitHub){const t=await(await fetch(o.url)).blob();await(await nr(e.taskId,er(o.filename),t,n.githubToken,n.githubUser,n.githubRepository,n.githubBranch,{filenameConflictAction:n.filenameConflictAction})).pushPromise}else if(n.saveWithCompanion&&!n.compressContent){const e=await(await fetch(o.url)).text();await Ea({filename:o.filename,content:e,filenameConflictAction:n.filenameConflictAction})}else if(n.saveToRestFormApi){const t=await(await fetch(o.url)).blob();await ur(e.taskId,o.filename,t,n.url,n.saveToRestFormApiToken,n.saveToRestFormApiUrl,n.saveToRestFormApiFileFieldName,n.saveToRestFormApiUrlFieldName)}else if(n.saveToS3){const t=await(await fetch(o.url)).blob();await or(e.taskId,o.filename,t,n.S3Domain,n.S3Region,n.S3Bucket,n.S3AccessKey,n.S3SecretKey,{filenameConflictAction:n.filenameConflictAction})}else await dr(o,n);if(n.openSavedPage){const e={active:!0,url:"/src/ui/pages/viewer.html?compressed=true&blobURI="+o.url,windowId:t.windowId},n=t.index;try{await browser.tabs.get(a),e.index=n+1}catch(t){e.index=n}browser.tabs.create(e)}o.hash&&await Na(o.hash,n.woleetKey)}}}finally{e.taskId?Aa(e.taskId):n.autoClose&&(browser.tabs.remove(hr[a]||a),delete hr[a]),o&&o.url&&!n.openSavedPage&&_o(o.url),Jt(a,!0)}}}async function br(e,t){return e.method.endsWith(".init")&&(await async function(e,t){await d(e.id);const a=await f(e.id);a[e.id].savedPageDetected=t.savedPageDetected,await m(a)}(t.tab,e),Bt(t.tab),function(e){Ia(e.id,!1)}(t.tab),async function(e){const[t,a]=await Promise.all([F(e.url,!0),Z(e)]);t&&(t.autoSaveLoad||t.autoSaveLoadOrUnload)&&a&&ba([e],{autoSave:!0})}(t.tab)),e.method.endsWith(".getOptions")?F(e.url):(e.method.endsWith(".activate")&&await browser.tabs.update(e.tabId,{active:!0}),e.method.endsWith(".getScreenshot")?gr(t.tab.id,e):void 0)}async function gr(e,t){const{width:a,height:n,scale:o=1}=t,r=Math.floor(a*o),i=Math.floor(n*o);let s,c,l,d=0,u=0;browser.tabs.captureTab?c=4096:(c=t.innerHeight,l=(await browser.tabs.query({active:!0,currentWindow:!0}))[0].id);const f=Math.floor(c*o);await browser.tabs.sendMessage(e,{method:"content.beginScrollTo"});try{s=new OffscreenCanvas(r,i);const t=s.getContext("2d");for(;d<n;){let o;browser.tabs.captureTab?o=await browser.tabs.captureTab(e,{format:"png",rect:{x:0,y:d,width:a,height:Math.min(n-d,c)}}):(await browser.tabs.sendMessage(e,{method:"content.scrollTo",y:d}),await browser.tabs.update(e,{active:!0}),o=await browser.tabs.captureVisibleTab(null,{format:"png"}));const s=Math.min(i-u,f),l=(await Oo(o,r,s)).url,m=await fetch(l).then((e=>e.arrayBuffer()));await _o(l);const h=new ImageData(new Uint8ClampedArray(m),a);t.putImageData(h,0,d),d+=c,u+=f}browser.tabs.captureTab||await browser.tabs.update(l,{active:!0})}catch(a){if(o>.1)return t.scale=.75*o,gr(e,t);throw a}finally{await browser.tabs.sendMessage(e,{method:"content.endScrollTo"})}if(s){await browser.tabs.sendMessage(e,{method:"content.endScrollTo"});const t=await s.convertToBlob({type:"image/png"});return await Bo(Array.from(new Uint8Array(await t.arrayBuffer())))}}browser.tabs.onCreated.addListener((e=>function(e){!function(e){Bt(e)}(e)}(e))),browser.tabs.onActivated.addListener((e=>async function(e){const t=await browser.tabs.get(e.tabId);Zt(t)}(e))),browser.tabs.onRemoved.addListener((e=>function(e){Ia(e),d(e),function(e){ee.delete(e)}(e),async function(e){const t=mr[e];t?t.autoSaveRemove&&(delete mr[e],await pr(t,t.tab)):mr[e]={removed:!0}}(e)}(e))),browser.tabs.onUpdated.addListener(((e,t)=>async function(e,t){if("complete"==t.status){setTimeout((async()=>{try{await browser.tabs.sendMessage(e,{method:"content.maybeInit"})}catch(e){}}),1500),function(e){delete mr[e]}(e);const t=await browser.tabs.get(e);if(oe(t)){const e=await f(t.id);e[t.id].editorDetected=!0,await m(e),Zt(t)}}t.discarded&&async function(e){const t=mr[e];t?(delete mr[e],await pr(t,t.tab)):mr[e]={discarded:!0}}(e)}(e,t))),browser.tabs.onReplaced.addListener(((e,t)=>function(e,t){(async function(e,t){let a=await f();await l(a,e,t),m(a),await l(s,e,t)})(e,t),async function(e,t){mr[t]&&!mr[e]&&(mr[e]=mr[t],delete mr[t],hr[t]=e)}(e,t),function(e,t){la.forEach((a=>{a.tab.id==t&&(a.tab.id=e)}))}(e,t)}(e,t)));async function yr(e){return(await browser.tabs.query(e)).sort(((e,t)=>e.index-t.index))}browser.runtime.onMessage.addListener(((e,t)=>e.method.startsWith("tabs.")?br(e,t):e.method.startsWith("downloads.")?Zo(e,t):e.method.startsWith("autosave.")?async function(e,t){if(e.method.endsWith(".save"))return e.autoSaveDiscard||e.autoSaveRemove?(t.tab?(e.tab=t.tab,mr[t.tab.id]=e):mr[e.tabId]&&(mr[e.tabId].removed&&e.autoSaveRemove||mr[e.tabId].discarded&&e.autoSaveDiscard)&&(delete mr[e.tabId],await pr(e,{id:e.tabId,index:e.tabIndex,url:t.url})),e.autoSaveUnload&&(delete mr[e.tabId],await pr(e,t.tab))):(delete mr[e.tabId],await pr(e,t.tab)),{}}(e,t):e.method.startsWith("ui.")?Kt(e,t):e.method.startsWith("config.")?D(e):e.method.startsWith("tabsData.")?function(e){return e.method.endsWith(".get")?f():e.method.endsWith(".set")?m(e.tabsData):void 0}(e):e.method.startsWith("devtools.")?async function(e){e.method.endsWith(".resourceCommitted")&&e.tabId&&e.url&&("stylesheet"==e.type||"script"==e.type)&&await browser.tabs.sendMessage(e.tabId,e)}(e):e.method.startsWith("editor.")?async function(e,t){if(e.method.endsWith(".getTabData")){const e=t.tab,a=ee.get(e.id);if(a){const t=await F(a.url),n=JSON.stringify(a);for(let o=0;o*Q<n.length;o++){const r={method:"editor.setTabData",compressContent:a.compressContent,tabId:e.id,url:a.url};r.truncated=n.length>Q,r.truncated?(r.finished=(o+1)*Q>n.length,r.content=n.substring(o*Q,(o+1)*Q),r.finished&&(r.options=t)):(r.content=n,t.embeddedImage=a.embeddedImage,r.options=t),await browser.tabs.sendMessage(e.id,r)}}else{const t={method:"editor.setTabData",tabId:e.id};await browser.tabs.sendMessage(e.id,t)}return{}}if(e.method.endsWith(".open")){let a;const n=t.tab;if(e.truncated?(a=te.get(n.id),a||(a=[],te.set(n.id,a)),a.push(e.content),e.finished&&te.delete(n.id)):e.content&&(a=[e.content]),!e.truncated||e.finished){const t={url:X};await browser.tabs.update(n.id,t);const o=e.compressContent?a.flat():a.join("");ee.set(n.id,{url:n.url,content:o,filename:e.filename,compressContent:e.compressContent,selfExtractingArchive:e.selfExtractingArchive,extractDataFromPageTags:e.extractDataFromPageTags,insertTextBody:e.insertTextBody,insertMetaCSP:e.insertMetaCSP,embeddedImage:e.embeddedImage})}return{}}}(e,t):e.method.startsWith("bookmarks.")?Pa(e):e.method.startsWith("companion.")?async function(e){if(e.method.endsWith(".state"))return{enabled:!0}}(e):e.method.startsWith("bootstrap.")?async function(e,t){if(e.method.endsWith(".init")){const[e,a,n]=await Promise.all([F(t.tab.url,!0),F(t.tab.url),Z(t.tab)]);return{optionsAutoSave:e,options:a,autoSaveEnabled:n,tabId:t.tab.id,tabIndex:t.tab.index}}}(e,t):"ping"==e.method?Promise.resolve({}):void 0)),browser.runtime.onMessageExternal&&browser.runtime.onMessageExternal.addListener((async function(e,t){if("save-page"==e){const e=await browser.tabs.query({currentWindow:!0,active:!0});e.length=1,await ba(e)}else if("edit-and-save-page"==e){const e=await browser.tabs.query({currentWindow:!0,active:!0});e.length=1,await ba(e,{openEditor:!0})}else if("save-selected-links"==e){const e=await browser.tabs.query({currentWindow:!0,active:!0});await ha(e[0])}else if("save-selected-content"==e){const e=await browser.tabs.query({currentWindow:!0,active:!0});await ba(e,{selected:!0})}else if("save-selected-tabs"==e){const e=await yr({currentWindow:!0,highlighted:!0});await ba(e)}else if("save-unpinned-tabs"==e){const e=await yr({currentWindow:!0,pinned:!1});await ba(e)}else if("save-all-tabs"==e){const e=await yr({currentWindow:!0});await ba(e)}else if(e.method){const t=(await browser.tabs.query({currentWindow:!0,active:!0}))[0];return!!t&&wr(e,t)}}))}();

@cheese529
Copy link
Author

cheese529 commented Dec 13, 2024

Another update: Unfortunately this extension has become completely unusable for me now as I have to turn the extension on and of each time in order to get it to work again and at this point turning it on and off doesn't always work either, i'll get this error where the save page pop up will look like this. The pages I have been trying to save btw are all the links here in this archive https://boards.4chan.org/news/archive
image

@cheese529
Copy link
Author

UPDATE: this has started happening outside of incognito as well. is there anything at all I could provide to help you better understand the issue @gildas-lormeau ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant