>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function k(e){return T.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(P,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function C(e,t,r,i){for(var a=0;a=t.length||a>=e.length);++a)t[a+r]=e[a];return a}function S(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function E(e){return e!=e}}.call(this)}.call(this,L("buffer").Buffer)},{"base64-js":34,buffer:35,ieee754:36}],36:[function(e,t,r){r.read=function(e,t,r,i,a){var n,o,s=8*a-i-1,l=(1<>1,p=-7,u=r?a-1:0,d=r?-1:1,a=e[t+u];for(u+=d,n=a&(1<<-p)-1,a>>=-p,p+=s;0>=-p,p+=i;0
>1,u=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,h=i?1:-1,n=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(i=Math.pow(2,-o))<1&&(o--,i*=2),2<=(t+=1<=o+p?u/i:u*Math.pow(2,1-p))*i&&(o++,i/=2),c<=o+p?(s=0,o=c):1<=o+p?(s=(t*i-1)*Math.pow(2,a),o+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,a),o=0));8<=a;e[r+d]=255&s,d+=h,s/=256,a-=8);for(o=o< app. Playing with this gist directly, may have adverse effects in your application."}}},{}],39:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});e=e("./models/GithubGist");r.default=e.default},{"./models/GithubGist":41}],40:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{n(l.next(e))}catch(e){t(e)}}function a(e){try{n(l.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,a)}n((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const a=e("axios"),n=e("../util/auth-config"),o=e("../constants");r.default=class{constructor(e){var t;this.gistOwner="",this.fileHasUpdates=!1,this.overwrite=e=>{this.fileContent=e,this.fileHasUpdates=!0},this.save=()=>i(this,void 0,void 0,function*(){var e,t;this.hasUpdates&&(e=o.default.githubGists+"/"+this.gistId,t={public:this.isPublic,files:{[this.fileName]:{content:this.fileContent}}},yield a.default.post(e,t,(0,n.default)({personalAccessToken:this.personalAccessToken})),this.fileHasUpdates=!1)}),this.fetchLatest=()=>i(this,void 0,void 0,function*(){var e=yield this.getLatestGistCommit(),e=this.getLatestGistFileFetchUrl(e),e=yield a.default.get(e,(0,n.default)({personalAccessToken:this.personalAccessToken}));this.fileContent=e.data,this.fileHasUpdates=!1}),this.getLatestGistFileFetchUrl=e=>{const{addCorsPrefix:t,customCorsPrefix:r,gistOwner:i,gistId:a}=this,n="https://gist.githubusercontent.com/"+i+`/${a}/raw/${e}/`+this.fileName;return t?null!=r?r(n):o.default.corsAnywhere+n:n},this.getLatestGistCommit=()=>i(this,void 0,void 0,function*(){var e="dummyParam="+Math.random(),e=`${o.default.githubGists}/${this.gistId}?`+e;try{return(yield a.default.get(e,(0,n.default)({personalAccessToken:this.personalAccessToken}))).data.history[0].version}catch(e){throw new Error("Error while fetching the latest commit.")}}),this.personalAccessToken=e.personalAccessToken,this.gistId=e.gistId,this.gistOwner=e.gistOwner,this.fileName=e.fileName,this.fileContent=e.fileContent,this.isPublic=e.isPublic,this.fileHasUpdates=!0,this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get hasUpdates(){return this.fileHasUpdates}get name(){return this.fileName}get content(){return this.fileContent}set hasUpdates(e){this.fileHasUpdates=e}}},{"../constants":38,"../util/auth-config":42,axios:2}],41:[function(e,t,r){"use strict";var a=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{n(l.next(e))}catch(e){t(e)}}function a(e){try{n(l.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,a)}n((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const o=e("axios"),s=e("../util/auth-config"),i=e("../util/token-validity"),n=e("../util/is-string-empty"),l=e("../util/formatted-gist-identifier"),c=e("../constants"),p=e("./GistFile");r.default=class{constructor(e){var t;this.gistId="",this.gistOwner="",this.gistFiles=[],this.touch=()=>a(this,void 0,void 0,function*(){yield(0,i.default)(this.personalAccessToken),yield this.fetchGist(),(0,n.default)(this.gistId)&&(yield this.createGist())}),this.createFile=(t,e)=>{const r=this.gistFiles.find(e=>e.name===t);if(r)return r.overwrite(e),!1;e=this.constructGistFile(t,e);return this.gistFiles.push(e),!0},this.getFile=t=>{return this.gistFiles.find(e=>e.name===t)||null},this.getFiles=()=>[...this.gistFiles],this.getFileNames=()=>this.gistFiles.map(e=>e.name),this.save=()=>a(this,void 0,void 0,function*(){const e={};for(const i of this.gistFiles)!1!==i.hasUpdates&&(e[i.name]={content:i.content});var t,r;0!==Object.keys(e).length&&(t=c.default.githubGists+"/"+this.gistId,r={public:this.isPublic,files:e},yield o.default.post(t,r,(0,s.default)({personalAccessToken:this.personalAccessToken})),this.gistFiles.forEach(e=>{e.hasUpdates=!1}))}),this.fetchGist=()=>a(this,void 0,void 0,function*(){for(const e of(yield o.default.get(c.default.githubGists,(0,s.default)({personalAccessToken:this.personalAccessToken}))).data){const t=Object.keys(e.files);if(t.includes(this.formattedAppIdentifier)){yield this.initialize(e);break}}}),this.createGist=()=>a(this,void 0,void 0,function*(){const{identifier:{content:e},githubGists:t}=c.default,r=e.replace("",this.appIdentifier),i={public:this.isPublic,files:{[this.formattedAppIdentifier]:{content:r}}},a=yield o.default.post(t,i,(0,s.default)({personalAccessToken:this.personalAccessToken})),n=a.data;yield this.initialize(n)}),this.initialize=i=>a(this,void 0,void 0,function*(){this.gistId=i.id,this.gistOwner=i.owner.login;const e=[];this.gistFiles=[];for(const t of Object.keys(i.files)){const r=this.constructGistFile(t,"");e.push(r.fetchLatest()),this.gistFiles.push(r)}yield Promise.all(e)}),this.constructGistFile=(e,t)=>new p.default({fileName:e,fileContent:t,gistId:this.gistId,gistOwner:this.gistOwner,cors:{addPrefix:this.addCorsPrefix,customPrefix:this.customCorsPrefix},personalAccessToken:this.personalAccessToken,isPublic:this.isPublic}),this.personalAccessToken=e.personalAccessToken,this.appIdentifier=e.appIdentifier,this.formattedAppIdentifier=(0,l.default)(e.appIdentifier),this.isPublic=Boolean(e.isPublic),this.addCorsPrefix=Boolean(null==(t=e.cors)?void 0:t.addPrefix),this.customCorsPrefix=null==(t=e.cors)?void 0:t.customPrefix}get id(){return this.gistId}get ownerUsername(){return this.gistOwner}}},{"../constants":38,"../util/auth-config":42,"../util/formatted-gist-identifier":43,"../util/is-string-empty":44,"../util/token-validity":45,"./GistFile":40,axios:2}],42:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>({headers:{Authorization:"token "+e.personalAccessToken}})},{}],43:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});const i=e("../constants");r.default=e=>{var{prefix:t,suffix:r}=i.default.identifier;return t+e+r}},{"../constants":38}],44:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default=e=>0===e.length},{}],45:[function(e,t,r){"use strict";var i=this&&this.__awaiter||function(e,o,s,l){return new(s=s||Promise)(function(r,t){function i(e){try{n(l.next(e))}catch(e){t(e)}}function a(e){try{n(l.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?r(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(i,a)}n((l=l.apply(e,o||[])).next())})};Object.defineProperty(r,"__esModule",{value:!0});const a=e("axios"),n=e("../constants"),o=t=>i(void 0,void 0,void 0,function*(){var e=n.default.githubRateLimit;return a.default.get(e,{headers:{Authorization:"token "+t}}).then(e=>e.headers["x-oauth-scopes"].includes("gist"))});r.default=e=>i(void 0,void 0,void 0,function*(){if(!(yield o(e)))throw new Error("Token is invalid or it doesn't have gist access.")})},{"../constants":38,axios:2}]},{},[1]),async(e,t=!0)=>{if(!(e=e||await getStorage("syncPAT")))return setStorage("syncState",!1),{ok:!1,payload:"noPAT"};var r=await getStorage("syncTest");const i=new GithubGist.default({appIdentifier:r?"TestsPaperMemorySync":"PaperMemorySync",personalAccessToken:e,isPublic:!1});try{return await i.touch(),t&&await setStorage("syncPAT",e),{ok:!0,payload:{gist:i,pat:e}}}catch(e){return console.log(e.response.data.message),warn("Because of the error ^ syncing is now disabled."),setStorage("syncState",!1),{ok:!1,payload:"wrongPAT",error:e}}}),getDataFile=async e=>{var t="PaperMemory-sync-data.json";let r=e.getFile(t);return r||(e.createFile(t),r=e.getFile(t)),r},pushToRemote=async()=>sendMessageToBackground({type:"writeSync"}),pullFromRemote=async(e,t)=>{var r=Date.now(),i=await sendMessageToBackground({type:"pullSync"});return consoleHeader("PaperMemory Pull "+String.fromCodePoint("0x1F504")),log("Remote Papers pulled: ",i),i&&(await initState({isContentScript:t,papers:i??e,print:!1}),t=(Date.now()-r)/1e3,info(`Successfully pulled from Github (${t}s).`),await setStorage("papers",global.state.papers)),console.groupEnd(),i},shouldSync=async()=>!!await getStorage("syncState"),initSyncAndState=async({papers:e=null,isContentScript:t=!1,forceInit:r=!1,stateIsReady:i=()=>{},remoteIsReady:a=()=>{}}={})=>{global.state.dataVersion&&!r||await initState({papers:e,isContentScript:t}),i(),await shouldSync()&&(t||startSyncLoader(),await pullFromRemote(e,t)?t||(r=global.state.sortedPapers.length,setPlaceholder("memory-search",`Search ${r} entries...`),global.state.memoryIsOpen||window.location.href.includes("options.html")||await makeMemoryHTML(),successSyncLoader()):t||errorSyncLoader()),a()},startSyncLoader=async()=>{showId("sync-popup-feedback"),hideId("sync-popup-error"),hideId("sync-popup-synced"),showId("sync-popup-syncing","flex")},successSyncLoader=async()=>{showId("sync-popup-feedback"),hideId("sync-popup-syncing"),hideId("sync-popup-error"),showId("sync-popup-synced"),setTimeout(()=>{hideId("sync-popup-feedback")},2e3)},errorSyncLoader=async()=>{showId("sync-popup-feedback"),hideId("sync-popup-syncing"),hideId("sync-popup-synced"),showId("sync-popup-error"),setTimeout(()=>{hideId("sync-popup-feedback")},2e3)},migrateData=async(r,i,e=!0)=>{if(void 0===r)return chrome.storage.local.set({papers:{__dataVersion:i}}),{papers:{__dataVersion:i},success:!0};var a,n,o,s=r.__dataVersion||-1,l=[];let c={...r};try{if(513<=s)return log("No migration needed"),{papers:r,success:!0};e&&backupData({...r}),delete r.__dataVersion;let t={};for(const d in r){if(t[d]=[],s<5&&(r[d].hasOwnProperty("bibtex")||(r[d].bibtex="",t[d].push("(m5) bibtex default")),r[d].pdfLink.endsWith(".pdf")||(r[d].pdfLink=r[d].pdfLink+".pdf",t[d].push("(m5) pdfLink to .pdf")),r[d].codeLink||(r[d].codeLink="",t[d].push("(m5) codeLink default")),r[d].source||(r[d].id.includes("NeurIPS")?(r[d].source="neurips",t[d].push("(m5) NeurIPS to neurips")):(r[d].source="arxiv",t[d].push("(m5) source default is arxiv")))),s<208&&("arxiv"!==r[d].source&&r[d].md.includes("https://arxiv.com/abs/")&&(r[d].md=`[${r[d].title}](${r[d].pdfLink})`,t[d].push("(m208) md from title and pdfLink")),"arxiv"!==r[d].source&&r[d].pdfLink.includes("arxiv.org/pdf/")&&(r[d].source="arxiv",t[d].push("(m208) set arxiv source from pdfLink")),d.match(/^\d/)&&"arxiv"===r[d].source&&(a="Arxiv-"+d,n={...r[d],id:a},r[a]=n,l.push(d),t[d].push("(m208) new arxiv id to Arxiv-"))),s<209&&(r[d].hasOwnProperty("favorite")||(r[d].favorite=!1,r[d].favoriteDate="",t[d].push("(m209) favorite defaults"))),s<210&&("arxiv"===r[d].source&&(o=r[d].pdfLink.match(/v\d+\.pdf/gi))&&0{delete r[e],log("Deleting "+e)}),(c={...r}).__dataVersion=i,info("Migration summary:"),Object.keys(t).forEach(e=>{0{log("Migrated papers:"),log(c),log("Data version is now "+i)}),{papers:c,success:!0}}catch(e){return log(`Error migrating data from version ${s} to ${i}:`),log(e),{papers:c,success:!1,error:e}}},logStorage=t=>{chrome.storage.local.get(t,e=>{log(e[t])})},getStorage=async r=>new Promise((t,e)=>{chrome.storage.local.get(r,e=>{t("string"==typeof r?e[r]:e)})}),setStorage=async(r,i,a=()=>{})=>new Promise((e,t)=>{chrome.storage.local.set({[r]:i},()=>{a(),e(!0)})}),deletePaperInStorage=async(e,t)=>{let r=!1;(t=t||(await getStorage("papers")??{})).hasOwnProperty(e)&&(updateDuplicatedUrls(null,e,!0),r=(r=delete global.state.titleHashToIds[miniHash(t[e].title)])&&delete t[e],delete global.state.papers[e]),r?(await setStorage("papers",t),global.state.papersList=Object.values(cleanPapers(global.state.papers)),sortMemory(),log("Successfully deleted paper",e)):log("Error: no deletion")},getTheme=async()=>{return await getStorage("checkDarkMode")?"dark":"light"},backupData=async r=>{chrome.storage.local.get("papersBackup",({papersBackup:e})=>{void 0===e&&(e={});for(const t of Object.keys(e).map(e=>parseInt(e)).sort((e,t)=>e{log("Backed up data with version: "+r.__dataVersion)})})};function dateDiffInDays(e,t){e=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),t=Date.UTC(t.getFullYear(),t.getMonth(),t.getDate());return Math.floor((t-e)/864e5)}const weeklyBackup=async()=>{var e=await getStorage("weeklyBackups")??{};const t=new Date,r=Object.keys(e).map(e=>new Date(e)).sort((e,t)=>e.getTime()-t.getTime());if(0{let e=!1,t;const r=await getStorage("prefs")??{};(e=0===Object.keys(r).length?!0:e)&&(t=await getStorage(global.prefsStorageKeys)??{});let i={};for(const a of global.prefsCheckNames)i[a]=(t??r).hasOwnProperty(a)?(t??r)[a]:!(0<=global.prefsCheckDefaultFalse.indexOf(a));return i.checkOfficialRepos&&(setStorage("pwcPrefs",{official:!0}),delete i.checkOfficialRepos,setStorage("prefs",i)),e&&setStorage("prefs",i),i},getManifestDataVersion=()=>{const e=chrome.runtime.getManifest();return e.version.split(".").map((e,t)=>parseInt(e)*10**(4-2*t)).reduce((e,t)=>e+t)},versionToSemantic=e=>(e=(e-=1e4*(major=parseInt(e/1e4,10)))-100*(minor=parseInt(e/100,10)),`${major}.${minor}.`+e),validatePaper=(t,e=!0)=>{const r={addDate:{type:"string",desc:"the paper's date of addition to the Memory",default:e=>(new Date).toJSON(),validation:e=>{try{new Date(e)}catch(e){return`Invalid addDate (could not parse as date: ${e})`}}},author:{type:"string",desc:"` and `-separated authors `${firstName} ${lastName}`",validation:e=>{if(!e)throw Error(`No author: ${e} for paper ${t.id}:
${JSON.stringify(t,null,2)}
Fix the json file and try again.
`)}},bibtex:{type:"string",desc:"BibTex citation with new lines (`\n`)",validation:t=>{try{bibtexToObject(t)}catch(e){return`Invalid BibTex: ${e} :
`+t}}},code:{type:"object",desc:"the paper's code object as returned by the PapersWithCode API",default:e=>({})},codeLink:{type:"string",desc:"the paper's code link",default:e=>"",validation:t=>{try{parseUrl(t)}catch(e){return`Invalid codeLink (${t}): `+e}}},count:{type:"number",desc:"the paper's number of visits",default:e=>1,validation:e=>{if(e<0)return`Invalid count (${e}): must be >= 0`}},extras:{type:"object",desc:"extra information about the paper which may be required per source",optional:!0},favorite:{type:"boolean",desc:"user wants to star the paper",default:e=>!1},favoriteDate:{type:"string",desc:"date the paper was added as a favorite",default:e=>""},id:{type:"string",desc:"Unique PaperMemory ID"},key:{type:"string",desc:"BibTex citation key",default:e=>"defaultKey_"+e.id},lastOpenDate:{type:"string",desc:"When the paper was last opened",default:e=>(new Date).toJSON()},md:{type:"string",desc:"markdown-formatted string `[${title}](${pdfLink})`",default:e=>`[${e.title}](${e.pdfLink})`},note:{type:"string",desc:"the user's note for this paper",default:e=>""},pdfLink:{type:"string",desc:"the link to the paper's pdf"},source:{type:"string",desc:"the paper's source i.e. where it was added to the memory from",validation:e=>{const t=Object.keys(global.knownPaperPages);if(t.indexOf(e)<0)return"Unknown source "+e}},tags:{type:"array[string]",desc:"the user's tags for this paper",default:e=>[]},title:{type:"string",desc:"the paper's title",validation:e=>{if(!e)throw Error(`No title: ${e} for paper ${t.id}:
${JSON.stringify(t,null,2)}
Fix the json file and try again.
-`)}},venue:{type:"string",desc:"the paper's publication venue",default:e=>""},year:{type:"string",desc:"year of publication",validation:e=>{if(!/^\d{4}$/.test(e))return`Invalid year (${e}): must be 4 digits exactly`}}};let i={};for(const l in r)if(i[l]||(i[l]=[]),t.hasOwnProperty(l)){const c=r[l].type;var a,n=typeof t[l];c.includes("array")||"object"===c?c.includes("array")?Array.isArray(t[l])?(o=c.split("[")[1].replace("]",""),0{let t=!0,r="",i="",a;try{e.__dataVersion||(e.__dataVersion=1);var n,o=await migrateData(e,getManifestDataVersion(),!1);if(!o.success)return i="Could not migrate the data before storing it",o.error&&(i+=":
"+stringifyError(o.error)),{success:!1,message:i};for(const s in a=o.papers)s.startsWith("__")||(paperWarnings=validatePaper(a[s]).warnings)&&0"+Object.entries(paperWarnings).map((e,t)=>`${e}
`+t.join("
")).join("
"));r&&(n=await getStorage("papers")??{},setStorage("uploadBackup",n)),t=!1}catch(e){log("prepareOverwriteData error",e),i='/!\\ OverwriteMemoryError:
'+stringifyError(e),t=!0}return{success:!t,message:i,warning:r,papersToWrite:a}},makeVenue=async e=>{let t="";switch((t=e.note&&e.note.match(/(accepted|published)\ @\ .+\(?\d{4}\)?/i)?e.note.split("@")[1].trim().replace(/\(?\d{4}\)?/,"").split("--")[0].trim():t)&&"neurips"===t.toLowerCase()&&(t="NeurIPS"),e.source){case"arxiv":break;case"neurips":t="NeurIPS";break;case"cvf":t=t||(await makeCVFPaper(e.pdfLink)).venue;break;case"openreview":t=t||(await makeOpenReviewPaper(e.pdfLink)).venue;break;case"biorxiv":break;case"pmlr":t=e.conf?.split(/\d{4}/)[0]??"";break;case"acl":t=e.conf??"";break;case"pnas":t="PNAS";break;case"nature":t=t||e.venue;break;case"iop":case"acs":t=e.venue}return t},isPaper=("undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={migrateData:migrateData,logStorage:logStorage,getStorage:getStorage,setStorage:setStorage,deletePaperInStorage:deletePaperInStorage,getTheme:getTheme,backupData:backupData,weeklyBackup:weeklyBackup,getPrefs:getPrefs,getManifestDataVersion:getManifestDataVersion,versionToSemantic:versionToSemantic,validatePaper:validatePaper,prepareOverwriteData:prepareOverwriteData,makeVenue:makeVenue}),async(e,t=!1)=>{let r={};if(!e)return r;for(const a in global.knownPaperPages){var i=global.knownPaperPages[a];r[a]=!1;for(const n of i)if("string"==typeof n){if(e.includes(n)){r[a]=!0;break}}else"function"==typeof n&&(r[a]=n(e))}return r.localFile=isKnownLocalFile(e),r.stored=!t&&(await findLocalFile(e)??!1),r.parsedWebsite=global.state.papers["Website_"+urlToWebsiteId(e)]??!1,r}),isSourceURL=async(e,t)=>Object.values(await isPaper(e,t)).some(e=>e),paperToAbs=e=>{let t,r,i;const a=e.pdfLink;let n="";switch(e.source){case"arxiv":n=a.replace("/pdf/","/abs/").replace(".pdf","");break;case"neurips":n=a.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html");break;case"cvf":n=a.replace("/papers/","/html/").replace(".pdf",".html");break;case"openreview":n=a.replace("/pdf?","/forum?");break;case"biorxiv":n=a.replace(".full.pdf","");break;case"pmlr":n=a.split("/").slice(0,-1).join("/")+".html";break;case"acl":n=a.replace(".pdf","");break;case"pnas":n=a.replace(".full.pdf","").replace("/doi/pdf/","/doi/full/");break;case"nature":n=a.replace(".pdf","");break;case"acs":n=a.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0];break;case"iop":n=a.split("#")[0].replace(/\/pdf$/,"");break;case"jmlr":n=a.split("/").slice(0,-1).join("/").replace("/papers/volume","/papers/v")+".html";break;case"pmc":var o=a.match(/PMC\d+/)[0];n=a.split(o)[0]+o;break;case"ijcai":var o=a.replace(".pdf","").split("/").last().match(/[1-9]\d*/),s=a.match(/proceedings\/\d+/gi)[0].split("/")[1];n=`https://www.ijcai.org/proceedings/${s}/`+o;break;case"acm":n=a.replace("/doi/pdf/","/doi/");break;case"ieee":n="https://ieeexplore.ieee.org/document/"+e.key;break;case"springer":n=e.extra.url;break;case"aps":[t,r]=parseUrl(a).pathname.split("/").slice(1,3),n=a.replace(`/${t}/${r}/`,`/${t}/abstract/`);break;case"wiley":n=a.replace(/\/doi\/e?pdf\//g,"/doi/abs/");break;case"sciencedirect":s=a.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];n="https://www.sciencedirect.com/science/article/pii/"+s;break;case"science":(i=a.split("/doi/")[1]).startsWith("10.")||(i=i.split("/").slice(1).join("/")),n="https://science.org/doi/full/"+i;break;case"frontiers":n=a.replace(/\/pdf$/,"/full");break;case"ihep":n="https://inspirehep.net/literature/"+e.id.split("-")[1];break;case"plos":n=a.replace("/article/file?","/article?").split("&")[0];break;case"rsc":n=a.replace("/articlepdf/","/articlelanding/");break;case"website":n=e.pdfLink;break;case"mdpi":n=e.pdfLink.split("/pdf")[0];break;default:n="https://xkcd.com/1969/"}return n.replace("http://","https://")},paperToPDF=e=>{let t=e.pdfLink;switch(e.source){case"arxiv":t=t.replace("arxiv.org/abs/","arxiv.org/pdf/").replace(/\.pdf$/,"").replace(/v\d+$/gi,""),t+=".pdf";break;case"neurips":t=t.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf");break;case"cvf":t=t.replace("/html/","/papers/").replace(".html",".pdf");break;case"openreview":t=t.replace("/forum?","/pdf?");break;case"biorxiv":t=cleanBiorxivURL(t)+".full.pdf";break;case"pmlr":case"acl":case"pnas":break;case"nature":t.endsWith(".pdf")||(t+=".pdf");break;case"iop":t.endsWith("/pdf")||(t+="/pdf");break;case"acs":case"jmlr":case"pmc":case"ijcai":case"acm":case"ieee":case"springer":case"aps":case"wiley":case"sciencedirect":case"science":case"frontiers":case"ihep":case"plos":case"rsc":case"mdpi":break;case"website":abs=e.pdfLink;break;default:t="https://xkcd.com/1969/"}return t.replace("http://","https://")},findLocalFile=async t=>{if("string"==typeof t){let e;try{e=await parseIdFromUrl(t)}catch(e){return new Promise(e=>e(null))}if(!global.state.papers.hasOwnProperty(e))return new Promise(e=>e(null));paper=global.state.papers[e]}else paper=t;t=await getStoredFiles(),t=await matchPapersToFiles({[paper.id]:paper},t),t=Object.values(t);return 1===t.length?t[0]:null},matchPapersToFiles=async(e,t)=>{var r=Object.fromEntries(Object.values(e).map(e=>[e.id,miniHash(e.title)])),i=(t=t.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt")),Object.fromEntries(t.map(e=>[e.id,miniHash(e.filename)])));let a={};for(const o of t){let t;try{(t=await parseIdFromUrl(o.finalUrl))&&e.hasOwnProperty(t)&&(a[t]=o)}catch(e){t=null}if(!t){const s=i[o.id];var n=Object.entries(r).find(([,e])=>s.includes(e));n&&(a[n[0]]=o)}}return a},matchAllFilesToPapers=()=>new Promise((t,e)=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},async e=>{e=await matchPapersToFiles(cleanPapers(global.state.papers),e);t(e)})}),mergePapers=(e={newPaper:{},oldPaper:{}})=>{const{oldPaper:t,newPaper:r,...i}=e;let a={...t};e={overwrites:["lastOpenDate"],incrementCount:!1,syncMerge:!1,...i};for(const n in r)(!t.hasOwnProperty(n)||r[n]&&!t[n])&&(a[n]=r[n]);e.incrementCount&&1===a.count&&(a.count+=1),e.syncMerge&&(a.count=t.count+r.count,a.note=t.note??"",r.note&&r.note!==t.note&&(a.note+="\n\n--[Sync Merge]--\n",a.note+=r.note),a.tags=[...t.tags,...r.tags],a.lastOpenDate=r.lastOpenDate,r.lastOpenDate>t.lastOpenDate&&(a.lastOpenDate=r.lastOpenDate),a.addDate=r.addDate,r.addDate>t.addDate&&(a.addDate=r.addDate));for(const o of e.overwrites)r.hasOwnProperty(o)&&(a[o]=r[o]);return a},updatePaperVisits=e=>(e.count+=1,e.lastOpenDate=(new Date).toJSON(),log("Updating paper to:",e),e),addOrUpdatePaper=async({url:i,is:e,prefs:a,tab:t,store:n=!0,contentScriptCallbacks:o={update:()=>{},preprints:()=>{}}})=>{const s=Date.now();let l,c,p={};consoleHeader("PaperMemory Parsing "+String.fromCodePoint("0x1F4DD")),global.state.papers=await getStorage("papers")??{};var r=await parseIdFromUrl(i,t),u=global.state.papers.hasOwnProperty(r);if(r&&u&&"anonymous"!==global.state.papers[r].author.toLowerCase())l=updatePaperVisits(global.state.papers[r]),c=!1;else{let r=await makePaper(e,i,t);if(!r)return;u=findFuzzyPaperMatch(global.state.titleHashToIds,r);if(u&&n){let t=global.state.papers[u];if(log("New paper",r,"already exists as",t),addPaperToTitleHashToId(r),t.venue){let e=["lastOpenDate"];"anonymous"===t.author.toLowerCase()&&(e.push("author"),e.push("year"),e.push("venue"),e.push("bibtex"),e.push("note")),console.log("overwrites: ",e),t=mergePapers({newPaper:r,overwrites:e,oldPaper:t,incrementCount:!1}),updateDuplicatedUrls(i,u)}else r.venue?(updateDuplicatedUrls(paperToAbs(t),r.id),updateDuplicatedUrls(paperToPDF(t),r.id),await deletePaperInStorage(t.id,global.state.papers),t=mergePapers({newPaper:r,oldPaper:t,incrementCount:!1,overwrites:["lastOpenDate","venue","bibtex","id","key","pdfLink","source","year","author"]})):"anonymous"===t.author.toLowerCase()&&(t=mergePapers({newPaper:r,oldPaper:t,incrementCount:!0,overwrites:["lastOpenDate","author","year","venue","bibtex","note"]}));r=updatePaperVisits(t),c=!1}else c=!0;l=r}if(!l.codeLink||!l.venue)try{const g=await tryPWCMatch(l);var d=!l.codeLink&&g?.codeLink,h=g?.note,f=g?.bibtex,m=!l.venue&&g?.venue;(p={codeLink:d,note:h,venue:m,bibtex:f}).codeLink&&(l.codeLink=p.codeLink,g.hasOwnProperty("note")&&delete g.note,l.code=g)}catch(e){log("Error trying to discover a code repository:"),log(e)}return global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&(warn("Paper has been created by another page: merging papers."),l=mergePapers({newPaper:global.state.papers[l.id],oldPaper:l,incrementCount:!0}),c=!1),n&&!global.state.deleted[l.id]&&(global.state.papers[l.id]=l),chrome.storage.local.set({papers:global.state.papers},async()=>{o.update(l),pushToRemote();let e;if(c||p.codeLink?c?(n?logOk("Added '"+l.title+"' to your Memory!"):warn("Discovered '"+l.title+"' but did not store it (`store` is false)."),log("paper: ",l),e="Added to your Memory",p.codeLink&&(e+="
(+ repo from PapersWithCode)
"),a&&a.checkFeedback&&n&&feedback(e,l)):(e="Found a code repository on PapersWithCode!",a&&a.checkFeedback&&n&&feedback(e)):n&&logOk("Updated '"+l.title+"' in your Memory"),!l.note||!l.venue||"anonymous"===l.author.toLowerCase()){var t,r=await tryPreprintMatch(l);for(const i of["note","venue","bibtex"])l[i]&&"bibtex"!==i||(t=r[i]??p[i])&&(log(`Updating preprint ${i} to`,t),l[i]=t);global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&1e.find(e=>e.source===t&&e[i].includes(r))?.id,parseIdFromUrl=async(t,e=null)=>{if(e)return urlToWebsiteId(t);let r;e=miniHash(t),e=global.state.urlHashToId[e];if(e)return e;var e=await isPaper(t,!0),i=Object.values(cleanPapers(global.state.papers));if(e.arxiv){var a=arxivIdFromURL(t);r="Arxiv-"+a;const o=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));o&&(r=o.find(e=>!e.startsWith("Arxiv-"))??r)}else if(e.neurips){var a=t.split("/paper/")[1].split("/")[0],n=t.split("/").last().split("-")[0].slice(0,8);r=`NeurIPS-${a}_`+n}else if(e.cvf)r=parseCVFUrl(t).id;else if(e.openreview){a=t.match(/id=\w+/)[0].replace("id=","");r=findPaperForProperty(i,"openreview",a)}else if(e.biorxiv){let e=(t=cleanBiorxivURL(t)).split("/").last();e.match(/v\d+$/)&&(e=e.split("v")[0]),r="Biorxiv-"+e;const s=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));s&&(r=s.find(e=>!e.startsWith("Biorxiv-"))??r)}else if(e.pmlr){const l=t.split("/").last().split(".")[0];var n="20"+l.match(/\d+/)[0];r=`PMLR-${n}-`+l}else if(e.acl){a=(t=(t=t.replace(".pdf","")).endsWith("/")?t.slice(0,-1):t).split("/").last();r=findPaperForProperty(i,"acl",a)}else if(e.pnas){n=((t=t.replace(".full.pdf","")).endsWith("/")?t.split("/").slice(-2):t.split("/").slice(-1))[0];r=findPaperForProperty(i,"pnas",n)}else if(e.nature){a=(t=t.replace(".pdf","").split("#")[0]).split("/").last();r=findPaperForProperty(i,"nature",a)}else if(e.acs){t=noParamUrl(t).replace("pubs.acs.org/doi/pdf/","/doi/").replace("pubs.acs.org/doi/abs/","/doi/");const doi=miniHash(t.split("/doi/")[1]);r="ACS_"+doi}else if(e.iop){t=noParamUrl(t).replace(/\/pdf$/,"");const doi=miniHash(t.split("/article/")[1].split("/meta")[0]);r="IOPscience_"+doi}else if(e.jmlr){const c=(t=(t=t.endsWith(".pdf")?t.split("/").slice(0,-1).join("/"):t).replace(".html","")).split("/").last();n="20"+c.match(/\d+/)[0];r=`JMLR-${n}_`+c}else if(e.pmc){a=t.match(/PMC\d+/g)[0].replace("PMC","");r=findPaperForProperty(i,"pmc",a)}else if(e.ijcai){n=t.endsWith(".pdf")?t.replace(".pdf","").split("/").last().match(/[1-9]\d*/):t.split("/").last(),a=t.match(/proceedings\/\d+/gi)[0].split("/")[1];r=`IJCAI-${a}_`+n}else if(e.acm){const doi=t.replace(/\/doi\/?(pdf|abs|full)?\//,"/doi/").split("/doi/")[1];r=findPaperForProperty(i,"acm",miniHash(doi))}else if(e.ieee){a=(t.includes("ieee.org/document/")?t.split("ieee.org/document/"):t.includes("ieee.org/abstract/document/")?t.split("ieee.org/abstract/document/"):t.split("arnumber="))[1].match(/\d+/)[0];r=findPaperForProperty(i,"ieee",a)}else if(e.springer){const p=global.sourceExtras.springer.types;let e=p.filter(e=>t.includes(`/${e}/`))[0];if(!e){if(!t.includes("/content/pdf/"))throw new Error("Could not find Springer type for "+t);e="content/pdf"}n=noParamUrl(t).split(`/${e}/`)[1].replace(".pdf","");r=findPaperForProperty(i,"springer",miniHash(n))}else if(e.aps){var[a,n]=parseUrl(t.split("#")[0]).pathname.split("/").slice(1,3);const doi=t.split(`/${a}/${n}/`).last();r=findPaperForProperty(i,"aps",miniHash(doi))}else if(e.wiley){const doi=t.split("?")[0].split("#")[0].split("/").slice(-2).join("/");r=findPaperForProperty(i,"wiley",miniHash(doi))}else if(e.sciencedirect){a=t.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];r=findPaperForProperty(i,"sciencedirect",miniHash(a))}else if(e.science)(doi=noParamUrl(t).split("/doi/")[1]).startsWith("10.")||(doi=doi.split("/").slice(1).join("/")),r=findPaperForProperty(i,"science",miniHash(doi));else if(e.frontiers)doi=noParamUrl(t).split("/articles/")[1].split("/").slice(0,-1).join("/"),r=findPaperForProperty(i,"frontiers",miniHash(doi));else if(e.ihep)r=t.includes("/literature/")?(n=noParamUrl(t).match(/\/literature\/(\d+)/)[1],findPaperForProperty(i,"ihep",n)):(a=noParamUrl(t).split("/files/")[1].split("/")[0],findPaperForProperty(i,"ihep",a,"pdfLink"));else if(e.plos){const doi=t.split("?id=").last().split("&")[0];r=findPaperForProperty(i,"plos",miniHash(doi))}else if(e.rsc){n=noParamUrl(t).split("/").last();r=findPaperForProperty(i,"rsc",miniHash(n))}else if(e.mdpi){a=noParamUrl(t.split("mdpi.com/")[1].split("/pdf")[0].split("/reprints")[0].split("/notes")[0]);r=findPaperForProperty(i,"mdpi",miniHash(a))}else if(e.localFile)r=e.localFile;else{if(!e.parsedWebsite)throw new Error("unknown paper url");r=e.parsedWebsite.id}return r},isKnownLocalFile=e=>{if(!e.startsWith("file://"))return!1;if(!e.endsWith(".pdf"))return!1;const t=decodeURIComponent(e).replace("file://","");var r=Object.entries(global.state.files).filter(([,e])=>e.filename===t);if(0({title:miniHash(e.title),id:e.id})).filter(e=>i.includes(e.title));return 0!==r.length&&r[0].id},makeMdLink=(e,t={})=>{var r=(t.checkPreferPdf?paperToPDF:paperToAbs)(e);let i="",a=(!t.checkMdYearVenue||(i=(i=e.note.match(/(.+)\s*@\s*([\w\s]+\(?\d{4}\)?)/i))&&i[2]?.replace(/\s+/g," ").replace(/[\(\)]/g,""))||(i="",e.venue&&(i+=e.venue+" "),i+=e.year),e.title);return`[${a=i?`${a} (${i.replace(/\s+/g," ")})`:a}](${r})`},duration=("undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={isPaper:isPaper,isSourceURL:isSourceURL,paperToAbs:paperToAbs,paperToPDF:paperToPDF,findLocalFile:findLocalFile,matchPapersToFiles:matchPapersToFiles,matchAllFilesToPapers:matchAllFilesToPapers,mergePapers:mergePapers,addOrUpdatePaper:addOrUpdatePaper,parseIdFromUrl:parseIdFromUrl,isKnownLocalFile:isKnownLocalFile,makeMdLink:makeMdLink,updatePaperVisits:updatePaperVisits}),e=>(Date.now()-e[0])/1e3),initState=async({papers:e,isContentScript:t,print:r=!0}={})=>{const i=[];i.unshift(Date.now()),r&&consoleHeader("PaperMemory Init "+String.fromCodePoint("0x2705")),e||(e=await getStorage("papers")??{},r&&log("Time to retrieve stored papers (s): "+duration(i))),i.unshift(Date.now()),global.state.dataVersion=getManifestDataVersion(),r&&log("Time to parse data version (s): "+duration(i)),i.unshift(Date.now()),weeklyBackup(),r&&log("Time to backup papers (weekly) (s): "+duration(i)),i.unshift(Date.now());var a,n,o=await migrateData(e,global.state.dataVersion);r&&log("Time to migrate data (s): "+duration(i)),i.unshift(Date.now()),e=o.papers,global.state.papers=e,global.state.prefs=await getPrefs(),r&&log("Time to retrieve user preferences (s): "+duration(i)),i.unshift(Date.now()),global.state.ignoreSources=await getStorage("ignoreSources")??{},r&&log("Time to retrieve sources to ignore (s): "+duration(i)),i.unshift(Date.now()),global.state.urlHashToId=await getStorage("urlHashToId")??{},r&&log("Time to retrieve sources to urlHashToId (s): "+duration(i)),i.unshift(Date.now()),global.state.titleHashToIds={};for([a,n]of Object.entries(cleanPapers(e))){var s=miniHash(n.title);global.state.titleHashToIds.hasOwnProperty(s)||(global.state.titleHashToIds[s]=[]),global.state.titleHashToIds[s].push(a)}r&&log("Time to hash titles (s): "+duration(i)),i.unshift(Date.now()),t||(global.state.files=await matchAllFilesToPapers(),r&&log("Time to match all local files (s): "+duration(i)),i.unshift(Date.now()),global.state.papersList=Object.values(cleanPapers(e)),global.state.sortKey="lastOpenDate",global.state.papersReady=!0,sortMemory(),r&&log("Time to sort memory (s): "+duration(i)),i.unshift(Date.now()),makeTags(),r&&log("Time to make tags (s): "+duration(i)),i.unshift(Date.now())),info("State init duration (s): "+(Date.now()-i.last())/1e3),r&&console.groupEnd()},sortMemory=()=>{global.state.sortedPapers=Object.values(cleanPapers(global.state.papers)),global.state.sortedPapers.sort(orderPapers(0<=global.descendingSortKeys.indexOf(global.state.sortKey))),global.state.papersList.sort(orderPapers(0<=global.descendingSortKeys.indexOf(global.state.sortKey)))},orderPapers=a=>(e,t)=>{let r=e[global.state.sortKey],i=t[global.state.sortKey];return void 0===r&&(r=""),void 0===i&&(i=""),"string"==typeof r&&(r=r.toLowerCase(),i=i.toLowerCase()),a?r>i?-1:1:r>i?1:-1},makeTags=()=>{let e=new Set;for(const t of global.state.sortedPapers)for(const r of t.tags)e.add(r);global.state.paperTags=[...e],global.state.paperTags.sort()},getExamplePaper=async e=>{var t=await getStorage("papers")??{},r=Object.keys(t).filter(e=>-1===e.indexOf("__")).reverse();let i=t[r[e=void 0===e?getRandomInt(r.length):e]];return i=void 0===i?{title:"Dummy title",author:"Cool Author and Great Author and Complicated Name Àuthor",year:2021,id:"NoneXiv-214324",bibtex:"@Nonesense{}",tags:["t1","t2"],note:"Thispaperdoesnotexist.com"}:i},stateTitleFunction=e=>{let t=e;if("string"==typeof e&&void 0===(t=global.state.papers[e]))return log("Error in stateTitleFunction: unknown id",e),"Unknown ID";const r=global.state.titleFunction(t);return r.replaceAll("\n"," ").replace(/\s\s+/g," ")},updateDuplicatedUrls=(t,r,e=!1)=>{if(e){let e;if((e=t?[miniHash(t)]:Object.keys(global.state.urlHashToId).filter(e=>global.state.urlHashToId[e]===r))&&e.length){for(const i of e)warn("Removing duplicated url",t,"for",r),delete global.state.urlHashToId[i];setStorage("urlHashToId",global.state.urlHashToId)}}else global.state.urlHashToId[miniHash(t)]=r,setStorage("urlHashToId",global.state.urlHashToId)},addPaperToTitleHashToId=e=>{var t=e.id,e=miniHash(e.title);global.state.titleHashToIds.hasOwnProperty(e)||(global.state.titleHashToIds[e]=[]),global.state.titleHashToIds[e].includes(t)||global.state.titleHashToIds[e].push(t)},readJournalAbbreviations=async()=>{var e,t;global.journalAbbreviations||(e=chrome.runtime.getURL("src/data/iso4-journals.json"),e=await fetch(e).then(e=>e.json()),t=chrome.runtime.getURL("src/data/journal-abbreviations.json"),t=await fetch(t).then(e=>e.json()),global.journalAbbreviations=Object.fromEntries([...Object.entries(e),...Object.entries(t)].map(([e,t])=>[miniHash(e),t])))},downloadPaperPdf=async e=>{if(!global.state.papersReady)throw new Error("[PM] State is not ready (downloadPaperPdf)");let t=stateTitleFunction(e);t=(t=t.replaceAll(":"," ")).replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\/:;<=>?@\[\]^`{|}~]/g," ").replace(/\s+/g," "),global.state.prefs.checkStore&&(t="PaperMemoryStore/"+t,0===(await getStoredFiles()).length&&chrome.downloads.download({url:URL.createObjectURL(new Blob([global.storeReadme])),filename:"PaperMemoryStore/IMPORTANT_README.txt",saveAs:!1})),(t=t.endsWith("pdf")?t.slice(0,-3)+".pdf":t).endsWith(".pdf")||(t+=".pdf"),log("Downloading paper",e,"to",t),chrome.downloads.download({url:paperToPDF(e),filename:t})},decodeHtml=("undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={initState:initState,getExamplePaper:getExamplePaper,stateTitleFunction:stateTitleFunction,updateDuplicatedUrls:updateDuplicatedUrls,addPaperToTitleHashToId:addPaperToTitleHashToId,readJournalAbbreviations:readJournalAbbreviations,downloadPaperPdf:downloadPaperPdf}),e=>{var t=document.createElement("textarea");return t.innerHTML=e,t.value}),flipAuthor=e=>e.split(", ").reverse().join(" "),flipAndAuthors=e=>e.split(" and ").map(flipAuthor).join(" and "),fetchArxivXML=async e=>{e=e.replace("Arxiv-","").replace("_","/");return fetch("https://export.arxiv.org/api/query?"+new URLSearchParams({id_list:e}))},fetchCvfHTML=async e=>{let t,r;if(t=e.endsWith(".pdf")?e.replace("/papers_backup/","/papers/").replace("/papers/","/html/").replace(".pdf",".html"):e,!(r=await fetch(t).then(e=>e.ok?e.text():""))&&t.includes("thecvf.com/content_")){const{conf:i,year:a}=parseCVFUrl(e);t=t.replace(`/content_${i}_${a}/`,`/content_${i.toLowerCase()}_${a}/`),r=await fetch(t).then(e=>e.ok?e.text():"")}return r},getOpenReviewNoteJSON=e=>sendMessageToBackground({type:"OpenReviewNoteJSON",url:e}),getOpenReviewForumJSON=e=>sendMessageToBackground({type:"OpenReviewForumJSON",url:e}),fetchDom=async e=>{const t=await fetch(e).then(e=>e.ok?e.text():"");return(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html")},fetchText=async e=>{try{const t=await fetch(e),r=t.ok?await t.text():"";return r.trim()}catch(e){return logError("fetchText error:",e),""}},fetchJSON=async e=>{try{const r=await fetch(e);var t=r.status;return{data:r.ok?await r.json():null,status:t}}catch(e){return logError("fetchJSON error:",e),{}}},fetchBibtex=async e=>{e=await fetchText(e);const t=bibtexToObject(e);delete t.abstract;var e=bibtexToString(t),r=`Published in ${t.journal} (${t.year})`;return{...t,bibtex:e,note:r,venue:t.journal,key:t.citationKey}},extractCrossrefData=e=>{if(e.status&&"ok"===e.status)if("work"!==e["message-type"])error("Unknown `message-type` from CrossRef",e);else{const o=e.message;log("Crossref data.message: ",o);var t=o.author.map(e=>e.given+" "+e.family).join(" and ");const s=o.issued?o.issued["date-parts"][0][0]+"":o.published?o.published["date-parts"][0][0]+"":null;if(s){var r=o.title[0];if(r){var i=o["container-title"][0]??"Springer",a=[miniHash(o.author[0].family),s.slice(2),firstNonStopLowercase(r)].join(""),n=o.DOI;let e={entryType:"book"===o.type?"book":"book-chapter"===o.type?"InBook":o.type.includes("article")?"Article":"InProceedings",citationKey:a,publisher:o.publisher,author:t,title:r,year:s,doi:n};o.page&&(e.pages=o.page),o.volume&&(e.volume=o.volume),o.type.includes("journal")&&(e.journal=i),o.link&&0"application/pdf"===e["content-type"]))&&(e.pdf=a.URL),(t=o.link.find(e=>"text/html"===e["content-type"])??o.link[0])&&(e.url=t.URL));r=bibtexToString(e);return{...e,bibtex:r,venue:i}}error("Cannot find title in CrossRef data",o)}else error("Cannot find year in CrossRef data",o)}else error("Cannot parse CrossRef response",e)},fetchCrossRefDataForDoi=async e=>{var{data:e,status:t}=await fetchJSON(`https://api.crossref.org/works/${e}?mailto=schmidtv%40mila.quebec`);return{data:extractCrossrefData(e),status:t}},fetchSemanticScholarDataForDoi=async e=>{const t=(await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/${e}?fields=venue,year,authors,title`))["data"];let r;var i;return t&&(r={},t.venue&&(r.venue=t.venue),t.year&&(r.year=t.year),t.authors&&(r.author=t.authors.map(e=>e.name).join(" and ")),t.title&&(r.title=t.title),e=""+miniHash(t.authors[0].name)+firstNonStopLowercase(r.title),i=bibtexToString({entryType:"article",citationKey:e,...r}),r.bibtex=i,r.key=e),r},getMetaContent=({selector:e,dom:t,all:r=!1,pure:i=!1})=>{let a="";for(var[n,o]of Object.entries(e))if(a+=`meta[${n}='${o}']`,o.startsWith("dc.")){let e;const l=o.split("dc.")[1],c=l[0];e=c===c.toLowerCase()?c.toUpperCase():c.toLowerCase(),a+=`,meta[${n}='dc.${e+l.slice(1)}']`}if(r){const s=queryAll(a,t).map(e=>e.getAttribute("content")??"");return i?s:s.map(spaceCamelCase).map(toSingleSpace)}const s=t.querySelector(a)?.getAttribute("content")??"";return i?s:toSingleSpace(spaceCamelCase(s))},extractDataFromDCMetaTags=e=>{const t=getMetaContent({selector:{name:"dc.Creator"},dom:e,all:!0}).join(" and ");if(!t)return null;var r=getMetaContent({selector:{name:"dc.Date"},dom:e}).split("-")[0],i=getMetaContent({selector:{name:"dc.Publisher"},dom:e}).replaceAll("\n"," "),a=getMetaContent({selector:{name:"dc.Title"},dom:e}),n=getMetaContent({selector:{name:"citation_journal_title"},dom:e}),o=getMetaContent({selector:{name:"citation_pdf_url"},dom:e,pure:!0}),e=getMetaContent({selector:{scheme:"doi"},dom:e})||getMetaContent({selector:{name:"citation_doi"},dom:e}),s=(""+t.split(" and ")[0].split(" ").find((e,t)=>1<=t&&1{const t=arxivIdFromURL(e),r=await fetchArxivXML(t),i=await r.text();e=(new DOMParser).parseFromString(i.replaceAll("\n",""),"text/xml");const a=queryAll("author name",e).map(e=>e.innerHTML);var n=a.join(" and "),o=[...e.getElementsByTagName("link")].map(e=>e.getAttribute("href")).filter(e=>e.includes("arxiv.org/pdf/"))[0].replace(/v\d+\.pdf$/gi,".pdf"),s=e.querySelector("entry title").innerHTML,e=e.querySelector("entry published").innerHTML.slice(0,4),l=a[0].split(" ").last().toLowerCase()+e+firstNonStopLowercase(s),c="Arxiv-"+t.replace("/","_"),p="";return{author:n,bibtex:p+`@article{${l},
+`)}},venue:{type:"string",desc:"the paper's publication venue",default:e=>""},year:{type:"string",desc:"year of publication",validation:e=>{if(!/^\d{4}$/.test(e))return`Invalid year (${e}): must be 4 digits exactly`}}};let i={};for(const l in r)if(i[l]||(i[l]=[]),t.hasOwnProperty(l)){const c=r[l].type;var a,n=typeof t[l];c.includes("array")||"object"===c?c.includes("array")?Array.isArray(t[l])?(o=c.split("[")[1].replace("]",""),0{let t=!0,r="",i="",a;try{e.__dataVersion||(e.__dataVersion=1);var n,o=await migrateData(e,getManifestDataVersion(),!1);if(!o.success)return i="Could not migrate the data before storing it",o.error&&(i+=":
"+stringifyError(o.error)),{success:!1,message:i};for(const s in a=o.papers)s.startsWith("__")||(paperWarnings=validatePaper(a[s]).warnings)&&0"+Object.entries(paperWarnings).map((e,t)=>`${e}
`+t.join("
")).join("
"));r&&(n=await getStorage("papers")??{},setStorage("uploadBackup",n)),t=!1}catch(e){log("prepareOverwriteData error",e),i='/!\\ OverwriteMemoryError:
'+stringifyError(e),t=!0}return{success:!t,message:i,warning:r,papersToWrite:a}},makeVenue=async e=>{let t="";switch((t=e.note&&e.note.match(/(accepted|published)\ @\ .+\(?\d{4}\)?/i)?e.note.split("@")[1].trim().replace(/\(?\d{4}\)?/,"").split("--")[0].trim():t)&&"neurips"===t.toLowerCase()&&(t="NeurIPS"),e.source){case"arxiv":break;case"neurips":t="NeurIPS";break;case"cvf":t=t||(await makeCVFPaper(e.pdfLink)).venue;break;case"openreview":t=t||(await makeOpenReviewPaper(e.pdfLink)).venue;break;case"biorxiv":break;case"pmlr":t=e.conf?.split(/\d{4}/)[0]??"";break;case"acl":t=e.conf??"";break;case"pnas":t="PNAS";break;case"nature":t=t||e.venue;break;case"iop":case"acs":t=e.venue}return t},isPaper=("undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={migrateData:migrateData,logStorage:logStorage,getStorage:getStorage,setStorage:setStorage,deletePaperInStorage:deletePaperInStorage,getTheme:getTheme,backupData:backupData,weeklyBackup:weeklyBackup,getPrefs:getPrefs,getManifestDataVersion:getManifestDataVersion,versionToSemantic:versionToSemantic,validatePaper:validatePaper,prepareOverwriteData:prepareOverwriteData,makeVenue:makeVenue}),async(e,t=!1)=>{let r={};if(!e)return r;for(const a in global.knownPaperPages){var i=global.knownPaperPages[a];r[a]=!1;for(const n of i)if("string"==typeof n){if(e.includes(n)){r[a]=!0;break}}else"function"==typeof n&&(r[a]=n(e))}return r.localFile=isKnownLocalFile(e),r.stored=!t&&(await findLocalFile(e)??!1),r.parsedWebsite=global.state.papers["Website_"+urlToWebsiteId(e)]??!1,r}),isSourceURL=async(e,t)=>Object.values(await isPaper(e,t)).some(e=>e),paperToAbs=e=>{let t,r,i;const a=e.pdfLink;let n="";switch(e.source){case"arxiv":n=a.replace("/pdf/","/abs/").replace(".pdf","");break;case"neurips":n=a.replace("/file/","/hash/").replace("-Paper.pdf","-Abstract.html");break;case"cvf":n=a.replace("/papers/","/html/").replace(".pdf",".html");break;case"openreview":n=a.replace("/pdf?","/forum?");break;case"biorxiv":n=a.replace(".full.pdf","");break;case"pmlr":n=a.split("/").slice(0,-1).join("/")+".html";break;case"acl":n=a.replace(".pdf","");break;case"pnas":n=a.replace(".full.pdf","").replace("/doi/pdf/","/doi/full/");break;case"nature":n=a.replace(".pdf","");break;case"acs":n=a.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0];break;case"iop":n=a.split("#")[0].replace(/\/pdf$/,"");break;case"jmlr":n=a.split("/").slice(0,-1).join("/").replace("/papers/volume","/papers/v")+".html";break;case"pmc":var o=a.match(/PMC\d+/)[0];n=a.split(o)[0]+o;break;case"ijcai":var o=a.replace(".pdf","").split("/").last().match(/[1-9]\d*/),s=a.match(/proceedings\/\d+/gi)[0].split("/")[1];n=`https://www.ijcai.org/proceedings/${s}/`+o;break;case"acm":n=a.replace("/doi/pdf/","/doi/");break;case"ieee":n="https://ieeexplore.ieee.org/document/"+e.key;break;case"springer":n=e.extra.url;break;case"aps":[t,r]=parseUrl(a).pathname.split("/").slice(1,3),n=a.replace(`/${t}/${r}/`,`/${t}/abstract/`);break;case"wiley":n=a.replace(/\/doi\/e?pdf\//g,"/doi/abs/");break;case"sciencedirect":s=a.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];n="https://www.sciencedirect.com/science/article/pii/"+s;break;case"science":(i=a.split("/doi/")[1]).startsWith("10.")||(i=i.split("/").slice(1).join("/")),n="https://science.org/doi/full/"+i;break;case"frontiers":n=a.replace(/\/pdf$/,"/full");break;case"ihep":n="https://inspirehep.net/literature/"+e.id.split("-")[1];break;case"plos":n=a.replace("/article/file?","/article?").split("&")[0];break;case"rsc":n=a.replace("/articlepdf/","/articlelanding/");break;case"website":n=e.pdfLink;break;case"mdpi":n=e.pdfLink.split("/pdf")[0];break;case"oup":n="https://doi.org/"+e.doi;break;default:n="https://xkcd.com/1969/"}return n.replace("http://","https://")},paperToPDF=e=>{let t=e.pdfLink;switch(e.source){case"arxiv":t=t.replace("arxiv.org/abs/","arxiv.org/pdf/").replace(/\.pdf$/,"").replace(/v\d+$/gi,""),t+=".pdf";break;case"neurips":t=t.replace("/hash/","/file/").replace("-Abstract.html","-Paper.pdf");break;case"cvf":t=t.replace("/html/","/papers/").replace(".html",".pdf");break;case"openreview":t=t.replace("/forum?","/pdf?");break;case"biorxiv":t=cleanBiorxivURL(t)+".full.pdf";break;case"pmlr":case"acl":case"pnas":break;case"nature":t.endsWith(".pdf")||(t+=".pdf");break;case"iop":t.endsWith("/pdf")||(t+="/pdf");break;case"acs":case"jmlr":case"pmc":case"ijcai":case"acm":case"ieee":case"springer":case"aps":case"wiley":case"sciencedirect":case"science":case"frontiers":case"ihep":case"plos":case"rsc":case"mdpi":case"oup":break;case"website":abs=e.pdfLink;break;default:t="https://xkcd.com/1969/"}return t.replace("http://","https://")},findLocalFile=async t=>{if("string"==typeof t){let e;try{e=await parseIdFromUrl(t)}catch(e){return new Promise(e=>e(null))}if(!global.state.papers.hasOwnProperty(e))return new Promise(e=>e(null));paper=global.state.papers[e]}else paper=t;t=await getStoredFiles(),t=await matchPapersToFiles({[paper.id]:paper},t),t=Object.values(t);return 1===t.length?t[0]:null},matchPapersToFiles=async(e,t)=>{var r=Object.fromEntries(Object.values(e).map(e=>[e.id,miniHash(e.title)])),i=(t=t.filter(e=>e.exists&&"complete"===e.state&&!e.filename.toLowerCase().includes("readme.txt")),Object.fromEntries(t.map(e=>[e.id,miniHash(e.filename)])));let a={};for(const o of t){let t;try{(t=await parseIdFromUrl(o.finalUrl))&&e.hasOwnProperty(t)&&(a[t]=o)}catch(e){t=null}if(!t){const s=i[o.id];var n=Object.entries(r).find(([,e])=>s.includes(e));n&&(a[n[0]]=o)}}return a},matchAllFilesToPapers=()=>new Promise((t,e)=>{chrome.downloads.search({filenameRegex:"PaperMemoryStore/.*"},async e=>{e=await matchPapersToFiles(cleanPapers(global.state.papers),e);t(e)})}),mergePapers=(e={newPaper:{},oldPaper:{}})=>{const{oldPaper:t,newPaper:r,...i}=e;let a={...t};e={overwrites:["lastOpenDate"],incrementCount:!1,syncMerge:!1,...i};for(const n in r)(!t.hasOwnProperty(n)||r[n]&&!t[n])&&(a[n]=r[n]);e.incrementCount&&1===a.count&&(a.count+=1),e.syncMerge&&(a.count=t.count+r.count,a.note=t.note??"",r.note&&r.note!==t.note&&(a.note+="\n\n--[Sync Merge]--\n",a.note+=r.note),a.tags=[...t.tags,...r.tags],a.lastOpenDate=r.lastOpenDate,r.lastOpenDate>t.lastOpenDate&&(a.lastOpenDate=r.lastOpenDate),a.addDate=r.addDate,r.addDate>t.addDate&&(a.addDate=r.addDate));for(const o of e.overwrites)r.hasOwnProperty(o)&&(a[o]=r[o]);return a},updatePaperVisits=e=>(e.count+=1,e.lastOpenDate=(new Date).toJSON(),log("Updating paper to:",e),e),addOrUpdatePaper=async({url:i,is:e,prefs:a,tab:t,store:n=!0,contentScriptCallbacks:o={update:()=>{},preprints:()=>{}}})=>{const s=Date.now();let l,c,p={};consoleHeader("PaperMemory Parsing "+String.fromCodePoint("0x1F4DD")),global.state.papers=await getStorage("papers")??{};var r=await parseIdFromUrl(i,t),u=global.state.papers.hasOwnProperty(r);if(r&&u&&"anonymous"!==global.state.papers[r].author.toLowerCase())l=updatePaperVisits(global.state.papers[r]),c=!1;else{let r=await makePaper(e,i,t);if(!r)return;u=findFuzzyPaperMatch(global.state.titleHashToIds,r);if(u&&n){let t=global.state.papers[u];if(log("New paper",r,"already exists as",t),addPaperToTitleHashToId(r),t.venue){let e=["lastOpenDate"];"anonymous"===t.author.toLowerCase()&&(e.push("author"),e.push("year"),e.push("venue"),e.push("bibtex"),e.push("note")),console.log("overwrites: ",e),t=mergePapers({newPaper:r,overwrites:e,oldPaper:t,incrementCount:!1}),updateDuplicatedUrls(i,u)}else r.venue?(updateDuplicatedUrls(paperToAbs(t),r.id),updateDuplicatedUrls(paperToPDF(t),r.id),await deletePaperInStorage(t.id,global.state.papers),t=mergePapers({newPaper:r,oldPaper:t,incrementCount:!1,overwrites:["lastOpenDate","venue","bibtex","id","key","pdfLink","source","year","author"]})):"anonymous"===t.author.toLowerCase()&&(t=mergePapers({newPaper:r,oldPaper:t,incrementCount:!0,overwrites:["lastOpenDate","author","year","venue","bibtex","note"]}));r=updatePaperVisits(t),c=!1}else c=!0;l=r}if(!l.codeLink||!l.venue)try{const g=await tryPWCMatch(l);var d=!l.codeLink&&g?.codeLink,h=g?.note,f=g?.bibtex,m=!l.venue&&g?.venue;(p={codeLink:d,note:h,venue:m,bibtex:f}).codeLink&&(l.codeLink=p.codeLink,g.hasOwnProperty("note")&&delete g.note,l.code=g)}catch(e){log("Error trying to discover a code repository:"),log(e)}return global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&(warn("Paper has been created by another page: merging papers."),l=mergePapers({newPaper:global.state.papers[l.id],oldPaper:l,incrementCount:!0}),c=!1),n&&!global.state.deleted[l.id]&&(global.state.papers[l.id]=l),chrome.storage.local.set({papers:global.state.papers},async()=>{o.update(l),pushToRemote();let e;if(c||p.codeLink?c?(n?logOk("Added '"+l.title+"' to your Memory!"):warn("Discovered '"+l.title+"' but did not store it (`store` is false)."),log("paper: ",l),e="Added to your Memory",p.codeLink&&(e+="
(+ repo from PapersWithCode)
"),a&&a.checkFeedback&&n&&feedback(e,l)):(e="Found a code repository on PapersWithCode!",a&&a.checkFeedback&&n&&feedback(e)):n&&logOk("Updated '"+l.title+"' in your Memory"),!l.note||!l.venue||"anonymous"===l.author.toLowerCase()){var t,r=await tryPreprintMatch(l);for(const i of["note","venue","bibtex"])l[i]&&"bibtex"!==i||(t=r[i]??p[i])&&(log(`Updating preprint ${i} to`,t),l[i]=t);global.state.papers=await getStorage("papers")??{},c&&global.state.papers.hasOwnProperty(l.id)&&1e.find(e=>e.source===t&&e[i].includes(r))?.id,parseIdFromUrl=async(t,e=null)=>{if(e)return urlToWebsiteId(t);let r;e=miniHash(t),e=global.state.urlHashToId[e];if(e)return e;var e=await isPaper(t,!0),i=Object.values(cleanPapers(global.state.papers));if(e.arxiv){var a=arxivIdFromURL(t);r="Arxiv-"+a;const o=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));o&&(r=o.find(e=>!e.startsWith("Arxiv-"))??r)}else if(e.neurips){var a=t.split("/paper/")[1].split("/")[0],n=t.split("/").last().split("-")[0].slice(0,8);r=`NeurIPS-${a}_`+n}else if(e.cvf)r=parseCVFUrl(t).id;else if(e.openreview){a=t.match(/id=\w+/)[0].replace("id=","");r=findPaperForProperty(i,"openreview",a)}else if(e.biorxiv){let e=(t=cleanBiorxivURL(t)).split("/").last();e.match(/v\d+$/)&&(e=e.split("v")[0]),r="Biorxiv-"+e;const s=Object.values(global.state.titleHashToIds).find(e=>e.includes(r));s&&(r=s.find(e=>!e.startsWith("Biorxiv-"))??r)}else if(e.pmlr){const l=t.split("/").last().split(".")[0];var n="20"+l.match(/\d+/)[0];r=`PMLR-${n}-`+l}else if(e.acl){a=(t=(t=t.replace(".pdf","")).endsWith("/")?t.slice(0,-1):t).split("/").last();r=findPaperForProperty(i,"acl",a)}else if(e.pnas){n=((t=t.replace(".full.pdf","")).endsWith("/")?t.split("/").slice(-2):t.split("/").slice(-1))[0];r=findPaperForProperty(i,"pnas",n)}else if(e.nature){a=(t=t.replace(".pdf","").split("#")[0]).split("/").last();r=findPaperForProperty(i,"nature",a)}else if(e.acs){t=noParamUrl(t).replace("pubs.acs.org/doi/pdf/","/doi/").replace("pubs.acs.org/doi/abs/","/doi/");const doi=miniHash(t.split("/doi/")[1]);r="ACS_"+doi}else if(e.iop){t=noParamUrl(t).replace(/\/pdf$/,"");const doi=miniHash(t.split("/article/")[1].split("/meta")[0]);r="IOPscience_"+doi}else if(e.jmlr){const c=(t=(t=t.endsWith(".pdf")?t.split("/").slice(0,-1).join("/"):t).replace(".html","")).split("/").last();n="20"+c.match(/\d+/)[0];r=`JMLR-${n}_`+c}else if(e.pmc){a=t.match(/PMC\d+/g)[0].replace("PMC","");r=findPaperForProperty(i,"pmc",a)}else if(e.ijcai){n=t.endsWith(".pdf")?t.replace(".pdf","").split("/").last().match(/[1-9]\d*/):t.split("/").last(),a=t.match(/proceedings\/\d+/gi)[0].split("/")[1];r=`IJCAI-${a}_`+n}else if(e.acm){const doi=t.replace(/\/doi\/?(pdf|abs|full)?\//,"/doi/").split("/doi/")[1];r=findPaperForProperty(i,"acm",miniHash(doi))}else if(e.ieee){a=(t.includes("ieee.org/document/")?t.split("ieee.org/document/"):t.includes("ieee.org/abstract/document/")?t.split("ieee.org/abstract/document/"):t.split("arnumber="))[1].match(/\d+/)[0];r=findPaperForProperty(i,"ieee",a)}else if(e.springer){const p=global.sourceExtras.springer.types;let e=p.filter(e=>t.includes(`/${e}/`))[0];if(!e){if(!t.includes("/content/pdf/"))throw new Error("Could not find Springer type for "+t);e="content/pdf"}n=noParamUrl(t).split(`/${e}/`)[1].replace(".pdf","");r=findPaperForProperty(i,"springer",miniHash(n))}else if(e.aps){var[a,n]=parseUrl(t.split("#")[0]).pathname.split("/").slice(1,3);const doi=t.split(`/${a}/${n}/`).last();r=findPaperForProperty(i,"aps",miniHash(doi))}else if(e.wiley){const doi=t.split("?")[0].split("#")[0].split("/").slice(-2).join("/");r=findPaperForProperty(i,"wiley",miniHash(doi))}else if(e.sciencedirect){a=t.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0];r=findPaperForProperty(i,"sciencedirect",miniHash(a))}else if(e.science)(doi=noParamUrl(t).split("/doi/")[1]).startsWith("10.")||(doi=doi.split("/").slice(1).join("/")),r=findPaperForProperty(i,"science",miniHash(doi));else if(e.frontiers)doi=noParamUrl(t).split("/articles/")[1].split("/").slice(0,-1).join("/"),r=findPaperForProperty(i,"frontiers",miniHash(doi));else if(e.ihep)r=t.includes("/literature/")?(n=noParamUrl(t).match(/\/literature\/(\d+)/)[1],findPaperForProperty(i,"ihep",n)):(a=noParamUrl(t).split("/files/")[1].split("/")[0],findPaperForProperty(i,"ihep",a,"pdfLink"));else if(e.plos){const doi=t.split("?id=").last().split("&")[0];r=findPaperForProperty(i,"plos",miniHash(doi))}else if(e.rsc){n=noParamUrl(t).split("/").last();r=findPaperForProperty(i,"rsc",miniHash(n))}else if(e.mdpi){a=noParamUrl(t.split("mdpi.com/")[1].split("/pdf")[0].split("/reprints")[0].split("/notes")[0]);r=findPaperForProperty(i,"mdpi",miniHash(a))}else if(e.oup){t=noParamUrl(t).split("https://academic.oup.com/").last();n=(t=isPdfUrl(t)?t.split("/").slice(0,-1).join("/"):t).split("/").slice(2).join("");r=findPaperForProperty(i,"oup",miniHash(n))}else if(e.localFile)r=e.localFile;else{if(!e.parsedWebsite)throw new Error("unknown paper url");r=e.parsedWebsite.id}return r},isKnownLocalFile=e=>{if(!e.startsWith("file://"))return!1;if(!e.endsWith(".pdf"))return!1;const t=decodeURIComponent(e).replace("file://","");var r=Object.entries(global.state.files).filter(([,e])=>e.filename===t);if(0({title:miniHash(e.title),id:e.id})).filter(e=>i.includes(e.title));return 0!==r.length&&r[0].id},makeMdLink=(e,t={})=>{var r=(t.checkPreferPdf?paperToPDF:paperToAbs)(e);let i="",a=(!t.checkMdYearVenue||(i=(i=e.note.match(/(.+)\s*@\s*([\w\s]+\(?\d{4}\)?)/i))&&i[2]?.replace(/\s+/g," ").replace(/[\(\)]/g,""))||(i="",e.venue&&(i+=e.venue+" "),i+=e.year),e.title);return`[${a=i?`${a} (${i.replace(/\s+/g," ")})`:a}](${r})`},duration=("undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={isPaper:isPaper,isSourceURL:isSourceURL,paperToAbs:paperToAbs,paperToPDF:paperToPDF,findLocalFile:findLocalFile,matchPapersToFiles:matchPapersToFiles,matchAllFilesToPapers:matchAllFilesToPapers,mergePapers:mergePapers,addOrUpdatePaper:addOrUpdatePaper,parseIdFromUrl:parseIdFromUrl,isKnownLocalFile:isKnownLocalFile,makeMdLink:makeMdLink,updatePaperVisits:updatePaperVisits}),e=>(Date.now()-e[0])/1e3),initState=async({papers:e,isContentScript:t,print:r=!0}={})=>{const i=[];i.unshift(Date.now()),r&&consoleHeader("PaperMemory Init "+String.fromCodePoint("0x2705")),e||(e=await getStorage("papers")??{},r&&log("Time to retrieve stored papers (s): "+duration(i))),i.unshift(Date.now()),global.state.dataVersion=getManifestDataVersion(),r&&log("Time to parse data version (s): "+duration(i)),i.unshift(Date.now()),weeklyBackup(),r&&log("Time to backup papers (weekly) (s): "+duration(i)),i.unshift(Date.now());var a,n,o=await migrateData(e,global.state.dataVersion);r&&log("Time to migrate data (s): "+duration(i)),i.unshift(Date.now()),e=o.papers,global.state.papers=e,global.state.prefs=await getPrefs(),r&&log("Time to retrieve user preferences (s): "+duration(i)),i.unshift(Date.now()),global.state.ignoreSources=await getStorage("ignoreSources")??{},r&&log("Time to retrieve sources to ignore (s): "+duration(i)),i.unshift(Date.now()),global.state.urlHashToId=await getStorage("urlHashToId")??{},r&&log("Time to retrieve sources to urlHashToId (s): "+duration(i)),i.unshift(Date.now()),global.state.titleHashToIds={};for([a,n]of Object.entries(cleanPapers(e))){var s=miniHash(n.title);global.state.titleHashToIds.hasOwnProperty(s)||(global.state.titleHashToIds[s]=[]),global.state.titleHashToIds[s].push(a)}r&&log("Time to hash titles (s): "+duration(i)),i.unshift(Date.now()),t||(global.state.files=await matchAllFilesToPapers(),r&&log("Time to match all local files (s): "+duration(i)),i.unshift(Date.now()),global.state.papersList=Object.values(cleanPapers(e)),global.state.sortKey="lastOpenDate",global.state.papersReady=!0,sortMemory(),r&&log("Time to sort memory (s): "+duration(i)),i.unshift(Date.now()),makeTags(),r&&log("Time to make tags (s): "+duration(i)),i.unshift(Date.now())),info("State init duration (s): "+(Date.now()-i.last())/1e3),r&&console.groupEnd()},sortMemory=()=>{global.state.sortedPapers=Object.values(cleanPapers(global.state.papers)),global.state.sortedPapers.sort(orderPapers(0<=global.descendingSortKeys.indexOf(global.state.sortKey))),global.state.papersList.sort(orderPapers(0<=global.descendingSortKeys.indexOf(global.state.sortKey)))},orderPapers=a=>(e,t)=>{let r=e[global.state.sortKey],i=t[global.state.sortKey];return void 0===r&&(r=""),void 0===i&&(i=""),"string"==typeof r&&(r=r.toLowerCase(),i=i.toLowerCase()),a?r>i?-1:1:r>i?1:-1},makeTags=()=>{let e=new Set;for(const t of global.state.sortedPapers)for(const r of t.tags)e.add(r);global.state.paperTags=[...e],global.state.paperTags.sort()},getExamplePaper=async e=>{var t=await getStorage("papers")??{},r=Object.keys(t).filter(e=>-1===e.indexOf("__")).reverse();let i=t[r[e=void 0===e?getRandomInt(r.length):e]];return i=void 0===i?{title:"Dummy title",author:"Cool Author and Great Author and Complicated Name Àuthor",year:2021,id:"NoneXiv-214324",bibtex:"@Nonesense{}",tags:["t1","t2"],note:"Thispaperdoesnotexist.com"}:i},stateTitleFunction=e=>{let t=e;if("string"==typeof e&&void 0===(t=global.state.papers[e]))return log("Error in stateTitleFunction: unknown id",e),"Unknown ID";const r=global.state.titleFunction(t);return r.replaceAll("\n"," ").replace(/\s\s+/g," ")},updateDuplicatedUrls=(t,r,e=!1)=>{if(e){let e;if((e=t?[miniHash(t)]:Object.keys(global.state.urlHashToId).filter(e=>global.state.urlHashToId[e]===r))&&e.length){for(const i of e)warn("Removing duplicated url",t,"for",r),delete global.state.urlHashToId[i];setStorage("urlHashToId",global.state.urlHashToId)}}else global.state.urlHashToId[miniHash(t)]=r,setStorage("urlHashToId",global.state.urlHashToId)},addPaperToTitleHashToId=e=>{var t=e.id,e=miniHash(e.title);global.state.titleHashToIds.hasOwnProperty(e)||(global.state.titleHashToIds[e]=[]),global.state.titleHashToIds[e].includes(t)||global.state.titleHashToIds[e].push(t)},readJournalAbbreviations=async()=>{var e,t;global.journalAbbreviations||(e=chrome.runtime.getURL("src/data/iso4-journals.json"),e=await fetch(e).then(e=>e.json()),t=chrome.runtime.getURL("src/data/journal-abbreviations.json"),t=await fetch(t).then(e=>e.json()),global.journalAbbreviations=Object.fromEntries([...Object.entries(e),...Object.entries(t)].map(([e,t])=>[miniHash(e),t])))},downloadPaperPdf=async e=>{if(!global.state.papersReady)throw new Error("[PM] State is not ready (downloadPaperPdf)");let t=stateTitleFunction(e);t=(t=t.replaceAll(":"," ")).replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\/:;<=>?@\[\]^`{|}~]/g," ").replace(/\s+/g," "),global.state.prefs.checkStore&&(t="PaperMemoryStore/"+t,0===(await getStoredFiles()).length&&chrome.downloads.download({url:URL.createObjectURL(new Blob([global.storeReadme])),filename:"PaperMemoryStore/IMPORTANT_README.txt",saveAs:!1})),(t=t.endsWith("pdf")?t.slice(0,-3)+".pdf":t).endsWith(".pdf")||(t+=".pdf"),log("Downloading paper",e,"to",t),chrome.downloads.download({url:paperToPDF(e),filename:t})},decodeHtml=("undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={initState:initState,getExamplePaper:getExamplePaper,stateTitleFunction:stateTitleFunction,updateDuplicatedUrls:updateDuplicatedUrls,addPaperToTitleHashToId:addPaperToTitleHashToId,readJournalAbbreviations:readJournalAbbreviations,downloadPaperPdf:downloadPaperPdf}),e=>{var t=document.createElement("textarea");return t.innerHTML=e,t.value}),flipAuthor=e=>e.split(", ").reverse().join(" "),flipAndAuthors=e=>e.split(" and ").map(flipAuthor).join(" and "),fetchArxivXML=async e=>{e=e.replace("Arxiv-","").replace("_","/");return fetch("https://export.arxiv.org/api/query?"+new URLSearchParams({id_list:e}))},fetchCvfHTML=async e=>{let t,r;if(t=e.endsWith(".pdf")?e.replace("/papers_backup/","/papers/").replace("/papers/","/html/").replace(".pdf",".html"):e,!(r=await fetch(t).then(e=>e.ok?e.text():""))&&t.includes("thecvf.com/content_")){const{conf:i,year:a}=parseCVFUrl(e);t=t.replace(`/content_${i}_${a}/`,`/content_${i.toLowerCase()}_${a}/`),r=await fetch(t).then(e=>e.ok?e.text():"")}return r},getOpenReviewNoteJSON=e=>sendMessageToBackground({type:"OpenReviewNoteJSON",url:e}),getOpenReviewForumJSON=e=>sendMessageToBackground({type:"OpenReviewForumJSON",url:e}),fetchDom=async e=>{const t=await fetch(e).then(e=>e.ok?e.text():"");return(new DOMParser).parseFromString(t.replaceAll("\n",""),"text/html")},fetchText=async e=>{try{const t=await fetch(e),r=t.ok?await t.text():"";return r.trim()}catch(e){return logError("fetchText error:",e),""}},fetchJSON=async e=>{try{const r=await fetch(e);var t=r.status;return{data:r.ok?await r.json():null,status:t}}catch(e){return logError("fetchJSON error:",e),{}}},fetchBibtex=async e=>{e=await fetchText(e);const t=bibtexToObject(e);delete t.abstract;var e=bibtexToString(t),r=`Published in ${t.journal} (${t.year})`;return{...t,bibtex:e,note:r,venue:t.journal,key:t.citationKey}},extractCrossrefData=e=>{if(e.status&&"ok"===e.status)if("work"!==e["message-type"])error("Unknown `message-type` from CrossRef",e);else{const o=e.message;log("Crossref data.message: ",o);var t=o.author.map(e=>e.given+" "+e.family).join(" and ");const s=o.issued?o.issued["date-parts"][0][0]+"":o.published?o.published["date-parts"][0][0]+"":null;if(s){var r=o.title[0];if(r){var i=o["container-title"][0]??"Springer",a=[miniHash(o.author[0].family),s.slice(2),firstNonStopLowercase(r)].join(""),n=o.DOI;let e={entryType:"book"===o.type?"book":"book-chapter"===o.type?"InBook":o.type.includes("article")?"Article":"InProceedings",citationKey:a,publisher:o.publisher,author:t,title:r,year:s,doi:n};o.page&&(e.pages=o.page),o.volume&&(e.volume=o.volume),o.type.includes("journal")&&(e.journal=i),o.link&&0"application/pdf"===e["content-type"]))&&(e.pdf=a.URL),(t=o.link.find(e=>"text/html"===e["content-type"])??o.link[0])&&(e.url=t.URL));r=bibtexToString(e);return{...e,bibtex:r,venue:i}}error("Cannot find title in CrossRef data",o)}else error("Cannot find year in CrossRef data",o)}else error("Cannot parse CrossRef response",e)},fetchCrossRefDataForDoi=async e=>{var{data:e,status:t}=await fetchJSON(`https://api.crossref.org/works/${e}?mailto=schmidtv%40mila.quebec`);return{data:extractCrossrefData(e),status:t}},fetchSemanticScholarDataForDoi=async e=>{const t=(await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/${e}?fields=venue,year,authors,title`))["data"];let r;var i;return t&&(r={},t.venue&&(r.venue=t.venue),t.year&&(r.year=t.year),t.authors&&(r.author=t.authors.map(e=>e.name).join(" and ")),t.title&&(r.title=t.title),e=""+miniHash(t.authors[0].name)+firstNonStopLowercase(r.title),i=bibtexToString({entryType:"article",citationKey:e,...r}),r.bibtex=i,r.key=e),r},getMetaContent=({selector:e,dom:t,all:r=!1,pure:i=!1})=>{let a="";for(var[n,o]of Object.entries(e))if(a+=`meta[${n}='${o}']`,o.startsWith("dc.")){let e;const l=o.split("dc.")[1],c=l[0];e=c===c.toLowerCase()?c.toUpperCase():c.toLowerCase(),a+=`,meta[${n}='dc.${e+l.slice(1)}']`}if(r){const s=queryAll(a,t).map(e=>e.getAttribute("content")??"");return i?s:s.map(spaceCamelCase).map(toSingleSpace)}const s=t.querySelector(a)?.getAttribute("content")??"";return i?s:toSingleSpace(spaceCamelCase(s))},extractDataFromDCMetaTags=e=>{const t=getMetaContent({selector:{name:"dc.Creator"},dom:e,all:!0}).join(" and ");if(!t)return null;var r=getMetaContent({selector:{name:"dc.Date"},dom:e}).split("-")[0],i=getMetaContent({selector:{name:"dc.Publisher"},dom:e}).replaceAll("\n"," "),a=getMetaContent({selector:{name:"dc.Title"},dom:e}),n=getMetaContent({selector:{name:"citation_journal_title"},dom:e}),o=getMetaContent({selector:{name:"citation_pdf_url"},dom:e,pure:!0}),e=getMetaContent({selector:{scheme:"doi"},dom:e})||getMetaContent({selector:{name:"citation_doi"},dom:e}),s=(""+t.split(" and ")[0].split(" ").find((e,t)=>1<=t&&1{const t=arxivIdFromURL(e),r=await fetchArxivXML(t),i=await r.text();e=(new DOMParser).parseFromString(i.replaceAll("\n",""),"text/xml");const a=queryAll("author name",e).map(e=>e.innerHTML);var n=a.join(" and "),o=[...e.getElementsByTagName("link")].map(e=>e.getAttribute("href")).filter(e=>e.includes("arxiv.org/pdf/"))[0].replace(/v\d+\.pdf$/gi,".pdf"),s=e.querySelector("entry title").innerHTML,e=e.querySelector("entry published").innerHTML.slice(0,4),l=a[0].split(" ").last().toLowerCase()+e+firstNonStopLowercase(s),c="Arxiv-"+t.replace("/","_"),p="";return{author:n,bibtex:p+`@article{${l},
`+`title={${s} },
`+`author={${n} },
`+`year={${e}},
@@ -29,4 +29,4 @@ Fix the json file and try again.
`+`author={${i}},
`+`year={${a}},
`+`url={${t}},
-`+"}"},extractAPIv2ContentValue=e=>{const t={};let r=!1;for(var[i,a]of Object.entries(e.content))a&&a.value?(t[i]=a.value,r=!0):t[i]=a;return e.content=t,{isV2:r,paper:e}},makeOpenReviewPaper=async e=>{var t=await getOpenReviewNoteJSON(e),r=await getOpenReviewForumJSON(e);if(403===t.status&&"ForbiddenError"===t.name)throw logError(dedent(`Error parsing OpenReview url ${e}. Most likely because this entry is protected and you do not have the rights to access it. 1/ Make sure you are logged in. 2/ Alternatively, this may be due to OpenReview changing the visibility of this paper. Try accessing this URL manually to make sure.`)),Error(t.message);if(404===t.status&&"NotFoundError"===t.name)throw logError(dedent(`Error parsing OpenReview url ${e}.`)),Error(t.message);var t=t.notes[0],i=!1,r=r.notes,a=({isV2:i,paper:t}=extractAPIv2ContentValue(t),t.content.title),n=(t.content.authors||t.content.authors.value).join(" and "),o=bibtexToString(t.content._bibtex||makeOpenReviewBibTex(t,e)),s=bibtexToObject(o),l=s.citationKey,s=s.year;let c;c=t.pdf?"https://openreview.net/pdf?id="+t.id:(t.html||e).replace("/forum?id=","/pdf?id=");const p=t.invitation?.split("/")||t.domain.split("/");let u=p[0].split(".")[0],d=p.slice(1).join("/").split("-")[0].replaceAll("/"," ").replace(" Conference",""),h=u,f=!1;global.overrideORConfs.hasOwnProperty(u)&&(h=global.overrideORConfs[u],f=!0),f&&(d=d.replace(h,""),u=h);e=(u+" "+d).replace(/ \d\d\d\d/g,"").replace(/\s\s+/g," "),t=`OR-${u}-${s}_`+t.id;let m,g,y,b="";return(m=i?r.filter(e=>e?.content?.recommendation?.value):r.filter(e=>-1<["Final Decision","Paper Decision","Acceptance Decision"].indexOf(e?.content?.title)))&&00===t?cleanStr(e)+"ed":e).join(" "),y=g+` @ ${e} (${s})`,g.toLowerCase().indexOf("rejected")<0&&(b=e)),{author:n,bibtex:o,id:t,key:l,note:y="Anonymous"===n&&"Rejected"!=g?`Under review @ ${e} (${s}) (${(new Date).toLocaleDateString()})`:y,pdfLink:c,title:a,venue:b,year:s}},makeBioRxivPaper=async e=>{var t=e.replace(".full.pdf",""),r="https://api.biorxiv.org//details/biorxiv/"+e.split("/").slice(-2).join("/").replace(".full.pdf","").split("v")[0];const i=await fetch(r).then(e=>e.json());if("ok"!==i.messages[0].status)throw new Error(r+" returned "+i.messages[0].status);const a=i.collection.last(),n=await fetchText(t),o=(new DOMParser).parseFromString(n.replaceAll("\n",""),"text/html");r=o.querySelector(".bibtext a").getAttribute("href");const s=bibtexToString(await(await fetch(r)).text());var t=extractAuthor(s),r=await parseIdFromUrl(e),l=s.split("\n")[0].split("{")[1].replace(",","").trim(),e=cleanBiorxivURL(e)+".full.pdf",c=a.title,p=a.date.split("-")[0];return{author:t,bibtex:s,id:r,key:l,note:"",pdfLink:e,title:c,venue:"",year:p}},makePMLRPaper=async e=>{var t=e.split("/").last().split(".")[0],r=await parseIdFromUrl(e);const i=e.includes(".html")?e:e.split("/").slice(0,-2).join("/")+`/${t}.html`;e=i.replace(".html","")+`/${t}.pdf`;const a=await fetchDom(i),n=a.getElementById("bibtex").innerText.replaceAll("\t"," ").replaceAll(/\s\s+/g," ");let o=n;for(const d of n.match(/,\ ?\w+ ?= ?{/g))o=o.replace(d,d.replace(", ",",\n ").replace(" = ","="));o.endsWith("}}")&&(o=o.slice(0,-2)+"}\n}"),o=bibtexToString(o);var s=extractAuthor(o),l=a.getElementsByTagName("h1")[0].innerText,c=extractBibtexValue(o,"year");let p=extractBibtexValue(o,"booktitle").replaceAll("Proceedings of the",""),u=p;note=`Accepted @ ${u} (${c})`;for(const h in global.overridePMLRConfs)if(p.includes(h)){u=global.overridePMLRConfs[h],p=u+" "+c,note="Accepted @ "+p;break}return{author:s,bibtex:o,id:r,key:t,note:note,pdfLink:e,title:l,venue:u,year:c}},findACLValue=(e,t)=>{return queryAll("dt",e).filter(e=>e.innerText.includes(t))[0].nextElementSibling.innerText},makeACLPaper=async e=>{e=e.replace(".pdf","");const t=await fetchDom(e);e=t.getElementById("citeBibtexContent");if(e){var r=t.getElementById("title").innerText,e=bibtexToString(e.innerText);const l=bibtexToObject(e);var i=l.year,a=l.author.replace(/\s+/g," ").split(" and ").map(e=>e.split(",").map(e=>e.trim()).reverse().join(" ")).join(" and "),n=l.citationKey,o=findACLValue(t,"Venue"),s=findACLValue(t,"PDF");return{author:a,bibtex:e,id:`ACL-${o}-${i}_`+findACLValue(t,"Anthology ID"),key:n,note:`Accepted @ ${o} (${i})`,pdfLink:s,title:r,venue:o,year:i}}},makePNASPaper=async e=>{e=e.replace(".full.pdf","").replace(/\/doi\/e?pdf\//,"/doi/abs/");const t=await fetchDom(e);var r=t.getElementsByTagName("h1")[0].innerText,i=queryAll(".authors span[property='author'] a:not([property='email']):not(.orcid-id)",t).filter(e=>!e.getAttribute("href").includes("mailto:")).map(e=>e.innerText).join(" and "),a=t.querySelector("span[property='datePublished']").innerText.match(/\d{4}/g)[0],n=`PNAS-${a}_`+(e.endsWith("/")?e.split("/").slice(-2):e.split("/").slice(-1))[0];const o=e.includes("/doi/pdf/")||e.includes("/doi/epdf/")?e.replace("/doi/epdf/","/doi/pdf/"):e.replace("/doi/abs/","/doi/pdf/").replace("/doi/full/","/doi/pdf/");var e=[...t.querySelector(".core-container").getElementsByTagName("a")].map(e=>e.getAttribute("href")).filter(e=>e?.includes("https://doi.org"))[0].split("/").slice(-2).join("/"),s="doi:"+e;return{author:i,bibtex:bibtexToString(`@article{${s}, author={${i}}, title={${r}}, journal = {Proceedings of the National Academy of Sciences}, year={${a}}, doi={${e}}, eprint={${o}}, URL={${o.replace("/doi/pdf/","/doi/abs/")}} }`),id:n,key:s,note:`Published @ PNAS (${a})`,pdfLink:o,title:r,venue:"PNAS",year:a}},makeNaturePaper=async e=>{var t=(e=e.replace(".pdf","").split("#")[0])+".pdf",r=e.split("/").last();const i=await fetchDom(e);e=i.querySelector("h1.c-article-title").innerText;const a=queryAll("ul.c-article-author-list li",i).map(e=>e.innerText.replace(/(\ ?,)|&|…|\d/g,"").split(/orcid/i)[0].trim()).filter(e=>0e.innerText).filter(e=>e.includes("https://doi.org"))[0];var l=""+a.split(" ")[1]+n+firstNonStopLowercase(e);let c={citationKey:l,entryType:"article",author:a,title:e,journal:o,year:n};s&&(c.doi=s,c.url="https://doi.org/"+s);var p=bibtexToString(c);return{author:a,bibtex:p,id:r,key:l,note:`Published @ ${o} (${n})`,pdfLink:t,title:e,venue:o,year:n}},makeACSPaper=async e=>{const t=(e=e.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0]).replace("/abs/","/").split("/doi/")[1];e=`https://pubs.acs.org/action/downloadCitation?doi=${t}&include=cit&format=bibtex&direct=true`,e=await fetchText(e);const r=bibtexToObject(e);var i=r.author.replaceAll("\n","").trim(),a=r.title.trim(),n=r.year.trim(),o=r.citationKey.trim(),s="https://pubs.acs.org/doi/pdf/"+t,l=`Published @ ${r.journal} (${r.year})`;return{author:i,bibtex:e,id:"ACS_"+t.replaceAll(".","").replaceAll("/",""),key:o,note:l,pdfLink:s,title:a,venue:r.journal,year:n}},makeIOPPaper=async e=>{(e=e.split("#")[0]).endsWith("/pdf")&&(e=e.slice(0,-4));var t=await fetchDom(e),t=queryAll(".btn-multi-block a",t).filter(e=>"BibTeX"===e.innerText).map(e=>e.getAttribute("href"))[0],t="https://"+parseUrl(e).host+t,t=await fetchText(t);const r=bibtexToObject(t);var i=r.author.replaceAll("\n","").trim(),a=r.title.trim(),n=r.year.trim(),o=r.citationKey.trim(),s=e+"/pdf",l=r.journal,c=`Published @ ${l} (${n})`,e=e.split("/article/").last().split("/meta")[0];return{author:i,bibtex:t,id:"IOPscience_"+miniHash(e),key:o,note:c,pdfLink:s,title:a,venue:l,year:n}},makeJMLRPaper=async e=>{var t=(e=(e=(e=e.includes("/papers/volume")?e.replace("/papers/volume","/papers/v"):e).endsWith(".pdf")?e.split("/").slice(0,-1).join("/"):e).replace(".html","")).split("/").last(),r=e+".bib",r=await fetchText(r);const{author:i,year:a,title:n,citationKey:o}=bibtexToObject(r);return{author:i,bibtex:r,id:`JMLR-${a}_`+t,key:o.trim(),note:`Published @ JMLR (${a})`,pdfLink:e.replace("/papers/v","/papers/volume")+`/${t}.pdf`,title:n,venue:"JMLR",year:a}},makePMCPaper=async e=>{var t=e.match(/PMC\d+/)[0].replace("PMC",""),r=e.split("PMC"+t)[0]+"PMC"+t;const i=await(await fetch(`https://api.ncbi.nlm.nih.gov/lit/ctxp/v1/pmc/?format=csl&id=${t}&download=true`)).json();var a=i["epub-date"]?i["epub-date"]["date-parts"][0][0]+"":i.issued["date-parts"][0][0]+"",n=i.author.map(e=>e.given+" "+e.family).join(" and "),o=i["container-title"].split(" ").map(e=>e.capitalize()).join(" "),s=i.title,t=`PMC-${a}_`+t,l=i.author[0].family+a+firstNonStopLowercase(s);let c;return{author:n,bibtex:bibtexToString({entryType:"article",citationKey:l,journal:o,issn:i.ISSN,volume:i.volume,page:i.page,doi:i.DOI,PMID:i.PMID,PMCID:i.PMCID,publisher:i.publisher,author:n,title:s}),id:t,key:l,note:`Published @ ${o} (${a})`,pdfLink:c=isPdfUrl(e)?e:r+"/pdf",title:s,venue:o,year:a}},makePubMedPaper=async e=>{const t=await fetchDom(e.split("?")[0]),r=[...t.getElementsByTagName("meta")].filter(e=>e.getAttribute("name")?.includes("citation_")),i=Object.fromEntries(r.map(e=>[e.getAttribute("name").replace("citation_",""),e.getAttribute("content")])),a=document.querySelector("div.authors-list").innerText.replace(/\d/gi,"").split(",").map(e=>e.trim()).join(" and ");var e=i.title,n=i.journal_title,o=i.date.split("/")[2],s=`PubMed-${o}_`+i.pmid,l=""+a.split(" and ")[0].split(" ").last()+o+firstNonStopLowercase(i.title),c={entryType:"article",citationKey:l,publisher:i.publisher,doi:i.doi,issn:i.issn,journal:n,year:o,author:a},c=bibtexToString(c),p=`Accepted @ ${journal} (${o})`;return{author:a,bibtex:c,id:s,key:l,note:p,pdfLink:"",title:e,venue:n,year:o}},makeIJCAIPaper=async e=>{const t=e.endsWith(".pdf")?e.replace(".pdf","").split("/").last().match(/[1-9]\d*/)[0]:e.split("/").last();e=e.match(/proceedings\/\d+/gi)[0].split("/")[1];const r=(await fetchText(`https://www.ijcai.org/proceedings/${e}/bibtex/`+t)).replace(/}\n/gi,"},\n");var i=bibtexToObject(r.split("\n").filter(e=>!/note\s+=/gi.test(e)).join("\n")),a=i.citationKey,n=i.title,i=flipAndAuthors(i.author),o=`IJCAI-${e}_`+t,s=`Accepted @ IJCAI (${e})`,l=t.padStart(4,0);return{author:i,bibtex:r,id:o,key:a,note:s,pdfLink:`https://www.ijcai.org/proceedings/${e}/${l}.pdf`,title:n,venue:"IJCAI",year:e}},makeACMPaper=async e=>{let t;t=isPdfUrl(e)?e:e.replace(/\/doi\/?(abs|full)?\//,"/doi/pdf/");const r=await fetchDom(e.replace("/doi/pdf/","/doi/"));let i,a,n,o,s,l,c,p;var u=extractDataFromDCMetaTags(r);if(u)({author:i,year:a,title:n,venue:o,key:s,doi:l,bibtex:c,note:p}=u);else{n=r.querySelector(".citation__title").innerText,i=queryAll("ul[ariaa-label='authors'] li.loa__item .loa__author-name",r).map(e=>e.innerText.replace(",","").trim()).join(" and ");const d=r.querySelector(".issue-item__detail a").innerText;o=d.split("'")[0].trim(),a="20"+d.split("'")[1].split(":")[0].trim(),l=t.split("/doi/pdf/")[1],p=`Accepted @ ${o} (${a})`,s=l,c=bibtexToString({entryType:"article",citationKey:l,journal:o,author:i,title:n,year:a,publisher:"Association for Computing Machinery",address:"New York, NY, USA",url:noParamUrl(e).replace("/doi/pdf/","/doi/")})}u=`ACM-${a}_`+miniHash(l);return{author:i,bibtex:c,id:u,key:s,note:p,pdfLink:t,title:n,venue:o,year:a}},makeIEEEPaper=async e=>{isPdfUrl(e)&&(e=`https://ieeexplore.ieee.org/document/${e.split("/stamp/stamp.jsp?tp=&arnumber=")[1].match(/\d+/)[0]}/`);const t=await fetchDom(e),r=JSON.parse([...t.getElementsByTagName("script")].filter(e=>e.innerHTML?.includes("metadata="))[0].innerHTML.split("metadata=")[1].split(/};\s*/)[0]+"}");var i=r.title,a=r.authors.map(e=>e.name).join(" and "),n=r.publicationYear,e=""+parseUrl(e).origin+r.pdfUrl,o=r.publicationTitle,s=r.articleId;return{author:a,bibtex:bibtexToString({entryType:"article",citationKey:s,journal:o,volume:r.volume,pages:r.startPage+"-"+r.endPage,doi:r.doi,title:i,year:n,author:a}),id:`IEEE-${n}_`+s,key:s,note:`Accepted @ ${o} (${n})`,pdfLink:e,title:i,venue:o,year:n}},makeSpringerPaper=async t=>{const e=[...global.sourceExtras.springer.types,"content/pdf"];var r=e.find(e=>t.includes(`/${e}/`));if(!r)throw new Error(`Could not find Springer type for ${t} (known: ${e.join(", ")})`);var i=t.split(`/${r}/`)[1].split("?")[0].replace(".pdf",""),a=(await fetchCrossRefDataForDoi(i))["data"];if(!a)throw new Error("Aborting Springer paper parsing, see error above");var{author:n,bibtex:o,citationKey:s,year:l,title:c,venue:p}=a;return{author:n,bibtex:o,id:`Springer-${l}_`+miniHash(i),key:s,note:`Published @ ${p} (${l})`,pdfLink:a.pdf??("content/pdf"===r?t:t.replace(`/${r}/`,"/content/pdf/")+".pdf"),title:c,venue:p,year:l,extra:{url:"https://doi.org/"+i}}},makeAPSPaper=async e=>{e=e.split("#")[0];var[t,r]=parseUrl(e).pathname.split("/").slice(1,3),i=e.split(`/${t}/${r}/`).last(),a=e.replace(`/${t}/${r}/`,`/${t}/export/`),a=await fetchText(a+"?type=bibtex&download=true"),n=bibtexToObject(a),e=e.replace(`/${t}/${r}/`,`/${t}/pdf/`),r=`APS-${n.year}_`+miniHash(i),t=n.journal??n.publisher,i=(await readJournalAbbreviations(),global.journalAbbreviations[miniHash(t)]??t),t=`Published @ ${i} (${n.year})`;return{author:flipAndAuthors(n.author),bibtex:a,id:r,key:n.citationKey,note:t,pdfLink:e,title:n.title,venue:i,year:n.year}},makeWileyPaper=async e=>{const t=e.replace(/\/doi\/(abs|epdf|full)\//g,"/doi/pdf/");e=t.replace("/doi/pdf/","/doi/abs/");const r=await fetchDom(e);var e=queryAll("meta[name=citation_author]",r).map(e=>e.getAttribute("content")).join(" and "),i=r.querySelector("meta[name=citation_journal_title]").getAttribute("content"),a=r.querySelector("meta[name=citation_title]").getAttribute("content"),n=r.querySelector("meta[name=citation_publisher]").getAttribute("content"),o=r.querySelector("meta[name=citation_publication_date]")?.getAttribute("content")?.split("/")[0]??r.querySelector("meta[name=citation_online_date]")?.getAttribute("content")?.split("/")[0],s=r.querySelector("meta[name=citation_doi]").getAttribute("content"),l=`Published @ ${i} (${o})`,c=`Wiley-${o}_`+miniHash(s);return{author:e,bibtex:bibtexToString({citationKey:s,entryType:"article",title:a,author:e,year:o,doi:s,publisher:n,journal:i}),id:c,key:s,note:l,pdfLink:t,title:a,venue:i,year:o}},makeScienceDirectPaper=async e=>{var e=e.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0],t=await fetchText(`https://www.sciencedirect.com/sdfe/arp/cite?pii=${e}&format=text%2Fx-bibtex&withabstract=false`),{author:r,journal:i,year:a,title:n,citationKey:o}=bibtexToObject(t),s=`Published @ ${i} (${a})`;return{author:r,bibtex:t,id:`ScienceDirect-${a}_`+miniHash(e),key:o,note:s,pdfLink:"https://reader.elsevier.com/reader/sd/pii/"+e,title:n,venue:i??"Science Direct",year:a}},makeSciencePaper=async e=>{let t,r,i,a,n,o,s,l,c,p,u;o="https://science.org/doi/pdf/"+(p=(p=noParamUrl(e).split("/doi/")[1]).startsWith("10.")?p:p.split("/").slice(1).join("/")),u="https://science.org/doi/full/"+p;var e=(await fetchCrossRefDataForDoi(p))["data"];return e?({author:t,bibtex:r,title:s,venue:l,year:c}=e,a=e.citationKey,n=`Published @ ${l} (${c})`):(e=await fetchDom(u),{author:t,year:c,publisher,title:s,venue:l,key:a,bibtex:r,note:n}=extractDataFromDCMetaTags(e)),i=`Science-${c}_`+miniHash(p),{author:t,bibtex:r,id:i,key:a,note:n,pdfLink:o,title:s,venue:l,year:c}},makeFrontiersPaper=async e=>{e=e.replace(/\/pdf$/,"/full");var t=noParamUrl(e).split("/articles/")[1].split("/full")[0],r=await fetchText(`https://www.frontiersin.org/articles/${t}/bibTex`);const i=Object.fromEntries(Object.entries(bibtexToObject(r)).map(([e,t])=>["citationKey"===e||"entryType"===e?e:e.toLowerCase(),t]));i.author=flipAndAuthors(i.author),delete i.abstract;var{author:r,journal:a,year:n,title:o,citationKey:s}=i,l=`Published @ ${a} (${n})`;return{author:r,bibtex:bibtexToString(i),id:`Frontiers-${n}_`+miniHash(t),key:s,note:l,pdfLink:e.replace(/\/full$/,"/pdf"),title:o,venue:a,year:n}},makeIHEPPaper=async t=>{let r,i;if(t.includes("/files/")){const d=t.split("/files/")[1].split("/")[0];var a="https://inspirehep.net/api/literature?q=documents.key:"+d;const e=(await fetchJSON(a)).data;if(!(r=e.hits.hits.find(e=>!!e.metadata.documents.find(e=>e.key===d))))return void warn("Could not find an Inspire HEP record for the url",t);i=r.metadata.control_number}else i=t.match(/\/literature\/(\d+)/)[1];if(i){var a=await fetchText(`https://inspirehep.net/api/literature/${i}?format=bibtex`),n=(r||({data:r}=await fetchJSON(`https://inspirehep.net/api/literature/${i}?format=json`)),bibtexToObject(a));let e=n.title??r.metadata.titles[0].title;e.startsWith("{")&&e.endsWith("}")&&(e=e.slice(1,-1));var o=r.metadata.documents?.[0]?.url??t,s=flipAndAuthors(n.author),l=n.year??r.created.split("-")[0],c="IHEP-"+i,p=n.journal??"Inspire HEP",u=n.citationKey,n=n.doi??"";return{author:s,bibtex:a,id:c,key:u,note:`Published @ ${p} (${l})`,pdfLink:o,title:e,venue:p,year:l,doi:n}}warn("Could not find an Inspire HEP id for the url",t)},makePLOSPaper=async e=>{var t=e.split("?id=").last().split("&")[0],{bibtex:r,key:i,author:a,venue:n,title:o,note:s,year:l}=await fetchBibtex(e.split("/article")[0]+"/article/citation/bibtex?id="+t),c=e.split("/article")[0]+`/article/file?id=${t}&type=printable`,e=e.split("journals.plos.org/")[1].split("/")[0];return{author:flipAndAuthors(a),bibtex:r,id:`PLOS-${e}_`+miniHash(t),key:i,note:s,pdfLink:c,title:o,venue:n,year:l,doi:t}},makeRSCPaper=async e=>{var t=noParamUrl(e).split("/").last(),r=e.split("/").find(e=>"articlehtml"===e||"articlepdf"===e||"articlelanding"===e).replace("article",""),e="articlepdf"===r?e:e.replace(`/article${r}/`,"/articlepdf/");let{bibtex:i,key:a,author:n,venue:o,title:s,note:l,year:c,doi:p}=await fetchBibtex(`https://pubs.rsc.org/en/content/formatedresult?markedids=${t}&downloadtype=article&managertype=bibtex`);return{author:flipAndAuthors(n),bibtex:i,id:`RSC-${o.replaceAll(" ","")}_`+miniHash(t),key:a,note:l,pdfLink:e,title:s,venue:o,year:c,doi:p}},makeWebsitePaper=async e=>{var t=e.url;const r=await fetchDom(t);var i=Object.fromEntries([...r.querySelectorAll("meta")].filter(e=>e.getAttribute("property")).filter(e=>e.getAttribute("property").startsWith("og:")).map(e=>[e.getAttribute("property").replace("og:",""),e.getAttribute("content")])),a=i.site_name||parseUrl(t).hostname.replace("www.","").capitalize(),n=(new Date).getFullYear()+"",o="Website_"+urlToWebsiteId(t),s=i.description||"",l=t,i=i.title||e.title,e=miniHash(a)+n+firstNonStopLowercase(i),t=`@misc{${e}, author = {${a}}, title = {${i}}, year = {${n}}, url = {${t}}, note = {Accessed ${(new Date).toISOString().split("T")[0]}} }`;return{author:a,bibtex:bibtexToString(bibtexToObject(t)),id:o,key:e,note:s,pdfLink:l,title:i,venue:"",year:n}},makeMDPIPaper=async e=>{(e=(e=(e=noParamUrl(e)).split("/").last().startsWith("pdf")?e.split("/").slice(0,-1).join("/"):e).endsWith("/notes")?e.replace("/notes",""):e).endsWith("/reprints")&&(e=e.replace("/reprints",""));var t=await fetchDom(e),{author:t,year:r,title:i,venue:a,key:n,doi:o,bibtex:s,note:l,pdfLink:c}=extractDataFromDCMetaTags(t);return{author:t,bibtex:s,id:`MDPI-${r}_`+miniHash(e.split("mdpi.com/")[1]),key:n,note:l,pdfLink:c,title:i,venue:a,year:r,doi:o}},tryPWCMatch=async e=>{let t;var r={type:"papersWithCode",pwcPrefs:await getStorage("pwcPrefs")??{},paper:e},{url:r,note:i,venue:a,pubYear:n}=await sendMessageToBackground(r)??{};return r&&!e.codeLink?log("[PapersWithCode] Discovered a code repository:",r):log("[PapersWithCode] No code repository found"),a&&!e.venue?(log("[PapersWithCode] Found a publication venue:",a),e=bibtexToObject(e.bibtex),t=bibtexToString({...e,year:n,journal:a})):log("[PapersWithCode] No publication found"),{codeLink:r,note:i,venue:a,bibtex:t}},tryCrossRef=async e=>{try{var t="https://api.crossref.org/works?rows=1&mailto=schmidtv%40mila.quebec&select=event%2Ctitle&query.title="+encodeURI(e.title);const i=await fetch(t).then(e=>e.json());if("ok"!==i.status)return log(`[Crossref] ${t} returned `+i.message.status),{note:null};if(0===i.message.items.length)return{note:null};if(i.message.items[0].title[0]?.toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," ")!==e.title.toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," "))return{note:null};if(!i.message.items[0].event||!i.message.items[0].event.name)return{note:null};info("Found a CrossRef match");var r=i.message.items[0].event.name.trim();return{venue:r,note:`Accepted @ ${r} -- [crossref.org]`}}catch(e){return logError("[Crossref]",e),{note:null}}},tryDBLP=async e=>{try{var t,r,i,a,n=encodeURI(e.title);const o=await fetch(`https://dblp.org/search/publ/api?q=${n}&format=json`);if(429===o.status)return{note:null,status:429};const s=await o.json();if(!(s.result&&s.result.hits&&s.result.hits.hit&&s.result.hits.hit.length))return{note:null};for(const l of s.result.hits.hit.sort((e,t)=>parseInt(e.info.year,10)-parseInt(t.info.year,10)))if(decodeHtml(l.info.title?.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," "))===e.title.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," ")&&"CoRR"!==l.info.venue)return info("Found a DBLP match"),t=await fetchText(l.info.url+".bib"),r=miniHash(l.info.venue),await readJournalAbbreviations(),i=(global.journalAbbreviations[r]??l.info.venue).trim(),a=l.info.year,l.info.url,{venue:i,note:`Accepted @ ${i} ${a} -- [dblp.org]`,bibtex:t};return{note:null}}catch(e){return logError("[DBLP]",e),{note:null}}},trySemanticScholar=async t=>{try{var{data:e,status:r}=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/search?query=${encodeURI(t.title)}&fields=title,venue,year,authors,externalIds,url&limit=50`);if(e&&e.data&&0e.name).join(" and "),o=l.externalIds.DOI,s=bibtexToString({entryType:"article",citationKey:miniHash(l.authors[0].name.split(" ").last())+i+firstNonStopLowercase(t.title),title:t.title,author:n,journal:e,year:i,doi:o,bibSource:"Semantic Scholar "+l.url});return{venue:e,note:a,bibtex:s,status:r}}}catch(e){logError("[SemanticScholar]",e)}},tryGoogleScholar=async e=>{return await sendMessageToBackground({type:"google-scholar",paper:e})},tryPreprintMatch=async(e,t=!1)=>{let r,i,a,n,o={},s=["DBLP","SemanticScholar","CrossRef","GoogleScholar"],l=[silentPromiseTimeout(tryGoogleScholar(e)),silentPromiseTimeout(trySemanticScholar(e)),silentPromiseTimeout(tryCrossRef(e)),silentPromiseTimeout(tryDBLP(e))];t&&(l.push(silentPromiseTimeout(tryPWCMatch(e))),s.push("PapersWithCode"));for(var[c,p]of Object.entries(s)){if(o[p]=await l[c],{note:r,venue:i,bibtex:a}=o[p]??{},r)break;log(`[${p}] No publication found`)}return t&&(t="PapersWithCode",o.hasOwnProperty(t)||(o[t]=await l[t]),o[t].codeLink&&!e.codeLink&&(n=o[t].codeLink)),{note:r,venue:i,bibtex:a,code:n}},initPaper=async e=>{e.note||(e.note=""),e.md=`[${e.title}](${e.pdfLink})`,e.tags=[],e.codeLink=e.codeLink??"",e.favorite=!1,e.favoriteDate="",e.addDate=(new Date).toJSON(),e.lastOpenDate=e.addDate,e.count=1,e.code={};for(const t in e)e.hasOwnProperty(t)&&"string"==typeof e[t]&&(e[t]=e[t].trim());return e=await autoTagPaper(e),validatePaper(e),e},autoTagPaper=async r=>{try{var e,i,a=await getStorage("autoTags");if(!a||!a.length)return r;let t=new Set;for(const n of a)n.tags?.length&&(n.title||n.author)&&(e=!n.title||new RegExp(n.title,"i").test(r.title),i=!n.author||new RegExp(n.author,"i").test(r.author),e&&i&&n.tags.forEach(e=>t.add(e)));return r.tags=[...t].sort(),r.tags.length&&log("Automatically adding tags:",r.tags),r}catch(e){return log("Error auto-tagging:",e),log("Paper:",r),r}},makePaper=async(e,t,r=!1)=>{let i;if(r)(i=await makeWebsitePaper(r))&&(i.source="website");else if(e.arxiv)(i=await makeArxivPaper(t))&&(i.source="arxiv");else if(e.neurips)(i=await makeNeuripsPaper(t))&&(i.source="neurips");else if(e.cvf)(i=await makeCVFPaper(t))&&(i.source="cvf");else if(e.openreview)(i=await makeOpenReviewPaper(t))&&(i.source="openreview");else if(e.biorxiv)(i=await makeBioRxivPaper(t))&&(i.source="biorxiv");else if(e.pmlr)(i=await makePMLRPaper(t))&&(i.source="pmlr");else if(e.acl)(i=await makeACLPaper(t))&&(i.source="acl");else if(e.pnas)(i=await makePNASPaper(t))&&(i.source="pnas");else if(e.nature)(i=await makeNaturePaper(t))&&(i.source="nature");else if(e.acs)(i=await makeACSPaper(t))&&(i.source="acs");else if(e.iop)(i=await makeIOPPaper(t))&&(i.source="iop");else if(e.jmlr)(i=await makeJMLRPaper(t))&&(i.source="jmlr");else if(e.pmc)(i=await makePMCPaper(t))&&(i.source="pmc");else if(e.ijcai)(i=await makeIJCAIPaper(t))&&(i.source="ijcai");else if(e.acm)(i=await makeACMPaper(t))&&(i.source="acm");else if(e.ieee)(i=await makeIEEEPaper(t))&&(i.source="ieee");else if(e.springer)(i=await makeSpringerPaper(t))&&(i.source="springer");else if(e.aps)(i=await makeAPSPaper(t))&&(i.source="aps");else if(e.wiley)(i=await makeWileyPaper(t))&&(i.source="wiley");else if(e.sciencedirect)(i=await makeScienceDirectPaper(t))&&(i.source="sciencedirect");else if(e.science)(i=await makeSciencePaper(t))&&(i.source="science");else if(e.frontiers)(i=await makeFrontiersPaper(t))&&(i.source="frontiers");else if(e.ihep)(i=await makeIHEPPaper(t))&&(i.source="ihep");else if(e.plos)(i=await makePLOSPaper(t))&&(i.source="plos");else if(e.rsc)(i=await makeRSCPaper(t))&&(i.source="rsc");else{if(!e.mdpi)throw new Error("Unknown paper source: "+JSON.stringify({is:e,url:t}));(i=await makeMDPIPaper(t))&&(i.source="mdpi")}if(void 0!==i)return initPaper(i)},findFuzzyPaperMatch=(e,t)=>{t=miniHash(t.title);if(e.hasOwnProperty(t)){const r=e[t];e=r.find(t=>!global.preprintSources.some(e=>t.toLowerCase().startsWith(e)));return e?e:r[0]}return null};"undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={autoTagPaper:autoTagPaper,decodeHtml:decodeHtml,fetchArxivXML:fetchArxivXML,fetchCrossRefDataForDoi:fetchCrossRefDataForDoi,fetchCvfHTML:fetchCvfHTML,fetchDom:fetchDom,getOpenReviewForumJSON:getOpenReviewForumJSON,getOpenReviewNoteJSON:getOpenReviewNoteJSON,fetchSemanticScholarDataForDoi:fetchSemanticScholarDataForDoi,fetchText:fetchText,findACLValue:findACLValue,findFuzzyPaperMatch:findFuzzyPaperMatch,flipAndAuthors:flipAndAuthors,flipAuthor:flipAuthor,initPaper:initPaper,makeACLPaper:makeACLPaper,makeACMPaper:makeACMPaper,makeACSPaper:makeACSPaper,makeAPSPaper:makeAPSPaper,makeArxivPaper:makeArxivPaper,makeBioRxivPaper:makeBioRxivPaper,makeCVFPaper:makeCVFPaper,makeIEEEPaper:makeIEEEPaper,makeIJCAIPaper:makeIJCAIPaper,makeIOPPaper:makeIOPPaper,makeJMLRPaper:makeJMLRPaper,makeNaturePaper:makeNaturePaper,makeNeuripsPaper:makeNeuripsPaper,makeOpenReviewBibTex:makeOpenReviewBibTex,makeOpenReviewPaper:makeOpenReviewPaper,makePaper:makePaper,makePMCPaper:makePMCPaper,makePMLRPaper:makePMLRPaper,makePNASPaper:makePNASPaper,makePubMedPaper:makePubMedPaper,makePLOSPaper:makePLOSPaper,makeSpringerPaper:makeSpringerPaper,makeWileyPaper:makeWileyPaper,tryCrossRef:tryCrossRef,tryDBLP:tryDBLP,tryPreprintMatch:tryPreprintMatch,tryPWCMatch:tryPWCMatch,trySemanticScholar:trySemanticScholar});
\ No newline at end of file
+`+"}"},extractAPIv2ContentValue=e=>{const t={};let r=!1;for(var[i,a]of Object.entries(e.content))a&&a.value?(t[i]=a.value,r=!0):t[i]=a;return e.content=t,{isV2:r,paper:e}},makeOpenReviewPaper=async e=>{var t=await getOpenReviewNoteJSON(e),r=await getOpenReviewForumJSON(e);if(403===t.status&&"ForbiddenError"===t.name)throw logError(dedent(`Error parsing OpenReview url ${e}. Most likely because this entry is protected and you do not have the rights to access it. 1/ Make sure you are logged in. 2/ Alternatively, this may be due to OpenReview changing the visibility of this paper. Try accessing this URL manually to make sure.`)),Error(t.message);if(404===t.status&&"NotFoundError"===t.name)throw logError(dedent(`Error parsing OpenReview url ${e}.`)),Error(t.message);var t=t.notes[0],i=!1,r=r.notes,a=({isV2:i,paper:t}=extractAPIv2ContentValue(t),t.content.title),n=(t.content.authors||t.content.authors.value).join(" and "),o=bibtexToString(t.content._bibtex||makeOpenReviewBibTex(t,e)),s=bibtexToObject(o),l=s.citationKey,s=s.year;let c;c=t.pdf?"https://openreview.net/pdf?id="+t.id:(t.html||e).replace("/forum?id=","/pdf?id=");const p=t.invitation?.split("/")||t.domain.split("/");let u=p[0].split(".")[0],d=p.slice(1).join("/").split("-")[0].replaceAll("/"," ").replace(" Conference",""),h=u,f=!1;global.overrideORConfs.hasOwnProperty(u)&&(h=global.overrideORConfs[u],f=!0),f&&(d=d.replace(h,""),u=h);e=(u+" "+d).replace(/ \d\d\d\d/g,"").replace(/\s\s+/g," "),t=`OR-${u}-${s}_`+t.id;let m,g,y,b="";return(m=i?r.filter(e=>e?.content?.recommendation?.value):r.filter(e=>-1<["Final Decision","Paper Decision","Acceptance Decision"].indexOf(e?.content?.title)))&&00===t?cleanStr(e)+"ed":e).join(" "),y=g+` @ ${e} (${s})`,g.toLowerCase().indexOf("rejected")<0&&(b=e)),{author:n,bibtex:o,id:t,key:l,note:y="Anonymous"===n&&"Rejected"!=g?`Under review @ ${e} (${s}) (${(new Date).toLocaleDateString()})`:y,pdfLink:c,title:a,venue:b,year:s}},makeBioRxivPaper=async e=>{var t=e.replace(".full.pdf",""),r="https://api.biorxiv.org//details/biorxiv/"+e.split("/").slice(-2).join("/").replace(".full.pdf","").split("v")[0];const i=await fetch(r).then(e=>e.json());if("ok"!==i.messages[0].status)throw new Error(r+" returned "+i.messages[0].status);const a=i.collection.last(),n=await fetchText(t),o=(new DOMParser).parseFromString(n.replaceAll("\n",""),"text/html");r=o.querySelector(".bibtext a").getAttribute("href");const s=bibtexToString(await(await fetch(r)).text());var t=extractAuthor(s),r=await parseIdFromUrl(e),l=s.split("\n")[0].split("{")[1].replace(",","").trim(),e=cleanBiorxivURL(e)+".full.pdf",c=a.title,p=a.date.split("-")[0];return{author:t,bibtex:s,id:r,key:l,note:"",pdfLink:e,title:c,venue:"",year:p}},makePMLRPaper=async e=>{var t=e.split("/").last().split(".")[0],r=await parseIdFromUrl(e);const i=e.includes(".html")?e:e.split("/").slice(0,-2).join("/")+`/${t}.html`;e=i.replace(".html","")+`/${t}.pdf`;const a=await fetchDom(i),n=a.getElementById("bibtex").innerText.replaceAll("\t"," ").replaceAll(/\s\s+/g," ");let o=n;for(const d of n.match(/,\ ?\w+ ?= ?{/g))o=o.replace(d,d.replace(", ",",\n ").replace(" = ","="));o.endsWith("}}")&&(o=o.slice(0,-2)+"}\n}"),o=bibtexToString(o);var s=extractAuthor(o),l=a.getElementsByTagName("h1")[0].innerText,c=extractBibtexValue(o,"year");let p=extractBibtexValue(o,"booktitle").replaceAll("Proceedings of the",""),u=p;note=`Accepted @ ${u} (${c})`;for(const h in global.overridePMLRConfs)if(p.includes(h)){u=global.overridePMLRConfs[h],p=u+" "+c,note="Accepted @ "+p;break}return{author:s,bibtex:o,id:r,key:t,note:note,pdfLink:e,title:l,venue:u,year:c}},findACLValue=(e,t)=>{return queryAll("dt",e).filter(e=>e.innerText.includes(t))[0].nextElementSibling.innerText},makeACLPaper=async e=>{e=e.replace(".pdf","");const t=await fetchDom(e);e=t.getElementById("citeBibtexContent");if(e){var r=t.getElementById("title").innerText,e=bibtexToString(e.innerText);const l=bibtexToObject(e);var i=l.year,a=l.author.replace(/\s+/g," ").split(" and ").map(e=>e.split(",").map(e=>e.trim()).reverse().join(" ")).join(" and "),n=l.citationKey,o=findACLValue(t,"Venue"),s=findACLValue(t,"PDF");return{author:a,bibtex:e,id:`ACL-${o}-${i}_`+findACLValue(t,"Anthology ID"),key:n,note:`Accepted @ ${o} (${i})`,pdfLink:s,title:r,venue:o,year:i}}},makePNASPaper=async e=>{e=e.replace(".full.pdf","").replace(/\/doi\/e?pdf\//,"/doi/abs/");const t=await fetchDom(e);var r=t.getElementsByTagName("h1")[0].innerText,i=queryAll(".authors span[property='author'] a:not([property='email']):not(.orcid-id)",t).filter(e=>!e.getAttribute("href").includes("mailto:")).map(e=>e.innerText).join(" and "),a=t.querySelector("span[property='datePublished']").innerText.match(/\d{4}/g)[0],n=`PNAS-${a}_`+(e.endsWith("/")?e.split("/").slice(-2):e.split("/").slice(-1))[0];const o=e.includes("/doi/pdf/")||e.includes("/doi/epdf/")?e.replace("/doi/epdf/","/doi/pdf/"):e.replace("/doi/abs/","/doi/pdf/").replace("/doi/full/","/doi/pdf/");var e=[...t.querySelector(".core-container").getElementsByTagName("a")].map(e=>e.getAttribute("href")).filter(e=>e?.includes("https://doi.org"))[0].split("/").slice(-2).join("/"),s="doi:"+e;return{author:i,bibtex:bibtexToString(`@article{${s}, author={${i}}, title={${r}}, journal = {Proceedings of the National Academy of Sciences}, year={${a}}, doi={${e}}, eprint={${o}}, URL={${o.replace("/doi/pdf/","/doi/abs/")}} }`),id:n,key:s,note:`Published @ PNAS (${a})`,pdfLink:o,title:r,venue:"PNAS",year:a}},makeNaturePaper=async e=>{var t=(e=e.replace(".pdf","").split("#")[0])+".pdf",r=e.split("/").last();const i=await fetchDom(e);e=i.querySelector("h1.c-article-title").innerText;const a=queryAll("ul.c-article-author-list li",i).map(e=>e.innerText.replace(/(\ ?,)|&|…|\d/g,"").split(/orcid/i)[0].trim()).filter(e=>0e.innerText).filter(e=>e.includes("https://doi.org"))[0];var l=""+a.split(" ")[1]+n+firstNonStopLowercase(e);let c={citationKey:l,entryType:"article",author:a,title:e,journal:o,year:n};s&&(c.doi=s,c.url="https://doi.org/"+s);var p=bibtexToString(c);return{author:a,bibtex:p,id:r,key:l,note:`Published @ ${o} (${n})`,pdfLink:t,title:e,venue:o,year:n}},makeACSPaper=async e=>{const t=(e=e.replace("pubs.acs.org/doi/pdf/","pubs.acs.org/doi/").split("?")[0]).replace("/abs/","/").split("/doi/")[1];e=`https://pubs.acs.org/action/downloadCitation?doi=${t}&include=cit&format=bibtex&direct=true`,e=await fetchText(e);const r=bibtexToObject(e);var i=r.author.replaceAll("\n","").trim(),a=r.title.trim(),n=r.year.trim(),o=r.citationKey.trim(),s="https://pubs.acs.org/doi/pdf/"+t,l=`Published @ ${r.journal} (${r.year})`;return{author:i,bibtex:e,id:"ACS_"+t.replaceAll(".","").replaceAll("/",""),key:o,note:l,pdfLink:s,title:a,venue:r.journal,year:n}},makeIOPPaper=async e=>{(e=e.split("#")[0]).endsWith("/pdf")&&(e=e.slice(0,-4));var t=await fetchDom(e),t=queryAll(".btn-multi-block a",t).filter(e=>"BibTeX"===e.innerText).map(e=>e.getAttribute("href"))[0],t="https://"+parseUrl(e).host+t,t=await fetchText(t);const r=bibtexToObject(t);var i=r.author.replaceAll("\n","").trim(),a=r.title.trim(),n=r.year.trim(),o=r.citationKey.trim(),s=e+"/pdf",l=r.journal,c=`Published @ ${l} (${n})`,e=e.split("/article/").last().split("/meta")[0];return{author:i,bibtex:t,id:"IOPscience_"+miniHash(e),key:o,note:c,pdfLink:s,title:a,venue:l,year:n}},makeJMLRPaper=async e=>{var t=(e=(e=(e=e.includes("/papers/volume")?e.replace("/papers/volume","/papers/v"):e).endsWith(".pdf")?e.split("/").slice(0,-1).join("/"):e).replace(".html","")).split("/").last(),r=e+".bib",r=await fetchText(r);const{author:i,year:a,title:n,citationKey:o}=bibtexToObject(r);return{author:i,bibtex:r,id:`JMLR-${a}_`+t,key:o.trim(),note:`Published @ JMLR (${a})`,pdfLink:e.replace("/papers/v","/papers/volume")+`/${t}.pdf`,title:n,venue:"JMLR",year:a}},makePMCPaper=async e=>{var t=e.match(/PMC\d+/)[0].replace("PMC",""),r=e.split("PMC"+t)[0]+"PMC"+t;const i=await(await fetch(`https://api.ncbi.nlm.nih.gov/lit/ctxp/v1/pmc/?format=csl&id=${t}&download=true`)).json();var a=i["epub-date"]?i["epub-date"]["date-parts"][0][0]+"":i.issued["date-parts"][0][0]+"",n=i.author.map(e=>e.given+" "+e.family).join(" and "),o=i["container-title"].split(" ").map(e=>e.capitalize()).join(" "),s=i.title,t=`PMC-${a}_`+t,l=i.author[0].family+a+firstNonStopLowercase(s);let c;return{author:n,bibtex:bibtexToString({entryType:"article",citationKey:l,journal:o,issn:i.ISSN,volume:i.volume,page:i.page,doi:i.DOI,PMID:i.PMID,PMCID:i.PMCID,publisher:i.publisher,author:n,title:s}),id:t,key:l,note:`Published @ ${o} (${a})`,pdfLink:c=isPdfUrl(e)?e:r+"/pdf",title:s,venue:o,year:a}},makePubMedPaper=async e=>{const t=await fetchDom(e.split("?")[0]),r=[...t.getElementsByTagName("meta")].filter(e=>e.getAttribute("name")?.includes("citation_")),i=Object.fromEntries(r.map(e=>[e.getAttribute("name").replace("citation_",""),e.getAttribute("content")])),a=document.querySelector("div.authors-list").innerText.replace(/\d/gi,"").split(",").map(e=>e.trim()).join(" and ");var e=i.title,n=i.journal_title,o=i.date.split("/")[2],s=`PubMed-${o}_`+i.pmid,l=""+a.split(" and ")[0].split(" ").last()+o+firstNonStopLowercase(i.title),c={entryType:"article",citationKey:l,publisher:i.publisher,doi:i.doi,issn:i.issn,journal:n,year:o,author:a},c=bibtexToString(c),p=`Accepted @ ${journal} (${o})`;return{author:a,bibtex:c,id:s,key:l,note:p,pdfLink:"",title:e,venue:n,year:o}},makeIJCAIPaper=async e=>{const t=e.endsWith(".pdf")?e.replace(".pdf","").split("/").last().match(/[1-9]\d*/)[0]:e.split("/").last();e=e.match(/proceedings\/\d+/gi)[0].split("/")[1];const r=(await fetchText(`https://www.ijcai.org/proceedings/${e}/bibtex/`+t)).replace(/}\n/gi,"},\n");var i=bibtexToObject(r.split("\n").filter(e=>!/note\s+=/gi.test(e)).join("\n")),a=i.citationKey,n=i.title,i=flipAndAuthors(i.author),o=`IJCAI-${e}_`+t,s=`Accepted @ IJCAI (${e})`,l=t.padStart(4,0);return{author:i,bibtex:r,id:o,key:a,note:s,pdfLink:`https://www.ijcai.org/proceedings/${e}/${l}.pdf`,title:n,venue:"IJCAI",year:e}},makeACMPaper=async e=>{let t;t=isPdfUrl(e)?e:e.replace(/\/doi\/?(abs|full)?\//,"/doi/pdf/");const r=await fetchDom(e.replace("/doi/pdf/","/doi/"));let i,a,n,o,s,l,c,p;var u=extractDataFromDCMetaTags(r);if(u)({author:i,year:a,title:n,venue:o,key:s,doi:l,bibtex:c,note:p}=u);else{n=r.querySelector(".citation__title").innerText,i=queryAll("ul[ariaa-label='authors'] li.loa__item .loa__author-name",r).map(e=>e.innerText.replace(",","").trim()).join(" and ");const d=r.querySelector(".issue-item__detail a").innerText;o=d.split("'")[0].trim(),a="20"+d.split("'")[1].split(":")[0].trim(),l=t.split("/doi/pdf/")[1],p=`Accepted @ ${o} (${a})`,s=l,c=bibtexToString({entryType:"article",citationKey:l,journal:o,author:i,title:n,year:a,publisher:"Association for Computing Machinery",address:"New York, NY, USA",url:noParamUrl(e).replace("/doi/pdf/","/doi/")})}u=`ACM-${a}_`+miniHash(l);return{author:i,bibtex:c,id:u,key:s,note:p,pdfLink:t,title:n,venue:o,year:a}},makeIEEEPaper=async e=>{isPdfUrl(e)&&(e=`https://ieeexplore.ieee.org/document/${e.split("/stamp/stamp.jsp?tp=&arnumber=")[1].match(/\d+/)[0]}/`);const t=await fetchDom(e),r=JSON.parse([...t.getElementsByTagName("script")].filter(e=>e.innerHTML?.includes("metadata="))[0].innerHTML.split("metadata=")[1].split(/};\s*/)[0]+"}");var i=r.title,a=r.authors.map(e=>e.name).join(" and "),n=r.publicationYear,e=""+parseUrl(e).origin+r.pdfUrl,o=r.publicationTitle,s=r.articleId;return{author:a,bibtex:bibtexToString({entryType:"article",citationKey:s,journal:o,volume:r.volume,pages:r.startPage+"-"+r.endPage,doi:r.doi,title:i,year:n,author:a}),id:`IEEE-${n}_`+s,key:s,note:`Accepted @ ${o} (${n})`,pdfLink:e,title:i,venue:o,year:n}},makeSpringerPaper=async t=>{const e=[...global.sourceExtras.springer.types,"content/pdf"];var r=e.find(e=>t.includes(`/${e}/`));if(!r)throw new Error(`Could not find Springer type for ${t} (known: ${e.join(", ")})`);var i=t.split(`/${r}/`)[1].split("?")[0].replace(".pdf",""),a=(await fetchCrossRefDataForDoi(i))["data"];if(!a)throw new Error("Aborting Springer paper parsing, see error above");var{author:n,bibtex:o,citationKey:s,year:l,title:c,venue:p}=a;return{author:n,bibtex:o,id:`Springer-${l}_`+miniHash(i),key:s,note:`Published @ ${p} (${l})`,pdfLink:a.pdf??("content/pdf"===r?t:t.replace(`/${r}/`,"/content/pdf/")+".pdf"),title:c,venue:p,year:l,extra:{url:"https://doi.org/"+i}}},makeAPSPaper=async e=>{e=e.split("#")[0];var[t,r]=parseUrl(e).pathname.split("/").slice(1,3),i=e.split(`/${t}/${r}/`).last(),a=e.replace(`/${t}/${r}/`,`/${t}/export/`),a=await fetchText(a+"?type=bibtex&download=true"),n=bibtexToObject(a),e=e.replace(`/${t}/${r}/`,`/${t}/pdf/`),r=`APS-${n.year}_`+miniHash(i),t=n.journal??n.publisher,i=(await readJournalAbbreviations(),global.journalAbbreviations[miniHash(t)]??t),t=`Published @ ${i} (${n.year})`;return{author:flipAndAuthors(n.author),bibtex:a,id:r,key:n.citationKey,note:t,pdfLink:e,title:n.title,venue:i,year:n.year}},makeWileyPaper=async e=>{const t=e.replace(/\/doi\/(abs|epdf|full)\//g,"/doi/pdf/");e=t.replace("/doi/pdf/","/doi/abs/");const r=await fetchDom(e);var e=queryAll("meta[name=citation_author]",r).map(e=>e.getAttribute("content")).join(" and "),i=r.querySelector("meta[name=citation_journal_title]").getAttribute("content"),a=r.querySelector("meta[name=citation_title]").getAttribute("content"),n=r.querySelector("meta[name=citation_publisher]").getAttribute("content"),o=r.querySelector("meta[name=citation_publication_date]")?.getAttribute("content")?.split("/")[0]??r.querySelector("meta[name=citation_online_date]")?.getAttribute("content")?.split("/")[0],s=r.querySelector("meta[name=citation_doi]").getAttribute("content"),l=`Published @ ${i} (${o})`,c=`Wiley-${o}_`+miniHash(s);return{author:e,bibtex:bibtexToString({citationKey:s,entryType:"article",title:a,author:e,year:o,doi:s,publisher:n,journal:i}),id:c,key:s,note:l,pdfLink:t,title:a,venue:i,year:o}},makeScienceDirectPaper=async e=>{var e=e.split("/pii/")[1].split("/")[0].split("#")[0].split("?")[0],t=await fetchText(`https://www.sciencedirect.com/sdfe/arp/cite?pii=${e}&format=text%2Fx-bibtex&withabstract=false`),{author:r,journal:i,year:a,title:n,citationKey:o}=bibtexToObject(t),s=`Published @ ${i} (${a})`;return{author:r,bibtex:t,id:`ScienceDirect-${a}_`+miniHash(e),key:o,note:s,pdfLink:"https://reader.elsevier.com/reader/sd/pii/"+e,title:n,venue:i??"Science Direct",year:a}},makeSciencePaper=async e=>{let t,r,i,a,n,o,s,l,c,p,u;o="https://science.org/doi/pdf/"+(p=(p=noParamUrl(e).split("/doi/")[1]).startsWith("10.")?p:p.split("/").slice(1).join("/")),u="https://science.org/doi/full/"+p;var e=(await fetchCrossRefDataForDoi(p))["data"];return e?({author:t,bibtex:r,title:s,venue:l,year:c}=e,a=e.citationKey,n=`Published @ ${l} (${c})`):(e=await fetchDom(u),{author:t,year:c,publisher,title:s,venue:l,key:a,bibtex:r,note:n}=extractDataFromDCMetaTags(e)),i=`Science-${c}_`+miniHash(p),{author:t,bibtex:r,id:i,key:a,note:n,pdfLink:o,title:s,venue:l,year:c}},makeFrontiersPaper=async e=>{e=e.replace(/\/pdf$/,"/full");var t=noParamUrl(e).split("/articles/")[1].split("/full")[0],r=await fetchText(`https://www.frontiersin.org/articles/${t}/bibTex`);const i=Object.fromEntries(Object.entries(bibtexToObject(r)).map(([e,t])=>["citationKey"===e||"entryType"===e?e:e.toLowerCase(),t]));i.author=flipAndAuthors(i.author),delete i.abstract;var{author:r,journal:a,year:n,title:o,citationKey:s}=i,l=`Published @ ${a} (${n})`;return{author:r,bibtex:bibtexToString(i),id:`Frontiers-${n}_`+miniHash(t),key:s,note:l,pdfLink:e.replace(/\/full$/,"/pdf"),title:o,venue:a,year:n}},makeIHEPPaper=async t=>{let r,i;if(t.includes("/files/")){const d=t.split("/files/")[1].split("/")[0];var a="https://inspirehep.net/api/literature?q=documents.key:"+d;const e=(await fetchJSON(a)).data;if(!(r=e.hits.hits.find(e=>!!e.metadata.documents.find(e=>e.key===d))))return void warn("Could not find an Inspire HEP record for the url",t);i=r.metadata.control_number}else i=t.match(/\/literature\/(\d+)/)[1];if(i){var a=await fetchText(`https://inspirehep.net/api/literature/${i}?format=bibtex`),n=(r||({data:r}=await fetchJSON(`https://inspirehep.net/api/literature/${i}?format=json`)),bibtexToObject(a));let e=n.title??r.metadata.titles[0].title;e.startsWith("{")&&e.endsWith("}")&&(e=e.slice(1,-1));var o=r.metadata.documents?.[0]?.url??t,s=flipAndAuthors(n.author),l=n.year??r.created.split("-")[0],c="IHEP-"+i,p=n.journal??"Inspire HEP",u=n.citationKey,n=n.doi??"";return{author:s,bibtex:a,id:c,key:u,note:`Published @ ${p} (${l})`,pdfLink:o,title:e,venue:p,year:l,doi:n}}warn("Could not find an Inspire HEP id for the url",t)},makePLOSPaper=async e=>{var t=e.split("?id=").last().split("&")[0],{bibtex:r,key:i,author:a,venue:n,title:o,note:s,year:l}=await fetchBibtex(e.split("/article")[0]+"/article/citation/bibtex?id="+t),c=e.split("/article")[0]+`/article/file?id=${t}&type=printable`,e=e.split("journals.plos.org/")[1].split("/")[0];return{author:flipAndAuthors(a),bibtex:r,id:`PLOS-${e}_`+miniHash(t),key:i,note:s,pdfLink:c,title:o,venue:n,year:l,doi:t}},makeRSCPaper=async e=>{var t=noParamUrl(e).split("/").last(),r=e.split("/").find(e=>"articlehtml"===e||"articlepdf"===e||"articlelanding"===e).replace("article",""),e="articlepdf"===r?e:e.replace(`/article${r}/`,"/articlepdf/");let{bibtex:i,key:a,author:n,venue:o,title:s,note:l,year:c,doi:p}=await fetchBibtex(`https://pubs.rsc.org/en/content/formatedresult?markedids=${t}&downloadtype=article&managertype=bibtex`);return{author:flipAndAuthors(n),bibtex:i,id:`RSC-${o.replaceAll(" ","")}_`+miniHash(t),key:a,note:l,pdfLink:e,title:s,venue:o,year:c,doi:p}},makeWebsitePaper=async e=>{var t=e.url;const r=await fetchDom(t);var i=Object.fromEntries([...r.querySelectorAll("meta")].filter(e=>e.getAttribute("property")).filter(e=>e.getAttribute("property").startsWith("og:")).map(e=>[e.getAttribute("property").replace("og:",""),e.getAttribute("content")])),a=i.site_name||parseUrl(t).hostname.replace("www.","").capitalize(),n=(new Date).getFullYear()+"",o="Website_"+urlToWebsiteId(t),s=i.description||"",l=t,i=i.title||e.title,e=miniHash(a)+n+firstNonStopLowercase(i),t=`@misc{${e}, author = {${a}}, title = {${i}}, year = {${n}}, url = {${t}}, note = {Accessed ${(new Date).toISOString().split("T")[0]}} }`;return{author:a,bibtex:bibtexToString(bibtexToObject(t)),id:o,key:e,note:s,pdfLink:l,title:i,venue:"",year:n}},makeMDPIPaper=async e=>{(e=(e=(e=noParamUrl(e)).split("/").last().startsWith("pdf")?e.split("/").slice(0,-1).join("/"):e).endsWith("/notes")?e.replace("/notes",""):e).endsWith("/reprints")&&(e=e.replace("/reprints",""));var t=await fetchDom(e),{author:t,year:r,title:i,venue:a,key:n,doi:o,bibtex:s,note:l,pdfLink:c}=extractDataFromDCMetaTags(t);return{author:t,bibtex:s,id:`MDPI-${r}_`+miniHash(e.split("mdpi.com/")[1]),key:n,note:l,pdfLink:c,title:i,venue:a,year:r,doi:o}},makeOUPPaper=async e=>{var t=(e=noParamUrl(e)).split("/").last(),t=await fetchText(`https://academic.oup.com/Citation/Download?resourceId=${t}&resourceType=3&citationFormat=2`);const r=bibtexToObject(t);delete r.abstract,t=bibtexToString(r);let{title:i,year:a,author:n,journal:o,doi:s,citationKey:l,eprint:c}=r;n=flipAndAuthors(n);var p=o,u=`Published @ ${p} (${a})`,d=l,h=e.split("https://academic.oup.com/")[1].split("/").slice(2).join("");return{author:n,bibtex:t,id:`OUP-${a}_`+miniHash(h),key:d,note:u,pdfLink:c?.replaceAll("\\","")??e,title:i,venue:p,year:a,doi:s}},tryPWCMatch=async e=>{let t;var r={type:"papersWithCode",pwcPrefs:await getStorage("pwcPrefs")??{},paper:e},{url:r,note:i,venue:a,pubYear:n}=await sendMessageToBackground(r)??{};return r&&!e.codeLink?log("[PapersWithCode] Discovered a code repository:",r):log("[PapersWithCode] No code repository found"),a&&!e.venue?(log("[PapersWithCode] Found a publication venue:",a),e=bibtexToObject(e.bibtex),t=bibtexToString({...e,year:n,journal:a})):log("[PapersWithCode] No publication found"),{codeLink:r,note:i,venue:a,bibtex:t}},tryCrossRef=async e=>{try{var t="https://api.crossref.org/works?rows=1&mailto=schmidtv%40mila.quebec&select=event%2Ctitle&query.title="+encodeURI(e.title);const i=await fetch(t).then(e=>e.json());if("ok"!==i.status)return log(`[Crossref] ${t} returned `+i.message.status),{note:null};if(0===i.message.items.length)return{note:null};if(i.message.items[0].title[0]?.toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," ")!==e.title.toLowerCase().replaceAll("\n"," ").replaceAll(/\s\s+/g," "))return{note:null};if(!i.message.items[0].event||!i.message.items[0].event.name)return{note:null};info("Found a CrossRef match");var r=i.message.items[0].event.name.trim();return{venue:r,note:`Accepted @ ${r} -- [crossref.org]`}}catch(e){return logError("[Crossref]",e),{note:null}}},tryDBLP=async e=>{try{var t,r,i,a,n=encodeURI(e.title);const o=await fetch(`https://dblp.org/search/publ/api?q=${n}&format=json`);if(429===o.status)return{note:null,status:429};const s=await o.json();if(!(s.result&&s.result.hits&&s.result.hits.hit&&s.result.hits.hit.length))return{note:null};for(const l of s.result.hits.hit.sort((e,t)=>parseInt(e.info.year,10)-parseInt(t.info.year,10)))if(decodeHtml(l.info.title?.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," "))===e.title.toLowerCase().replaceAll("\n"," ").replaceAll(".","").replaceAll(/\s\s+/g," ")&&"CoRR"!==l.info.venue)return info("Found a DBLP match"),t=await fetchText(l.info.url+".bib"),r=miniHash(l.info.venue),await readJournalAbbreviations(),i=(global.journalAbbreviations[r]??l.info.venue).trim(),a=l.info.year,l.info.url,{venue:i,note:`Accepted @ ${i} ${a} -- [dblp.org]`,bibtex:t};return{note:null}}catch(e){return logError("[DBLP]",e),{note:null}}},trySemanticScholar=async t=>{try{var{data:e,status:r}=await fetchJSON(`https://api.semanticscholar.org/graph/v1/paper/search?query=${encodeURI(t.title)}&fields=title,venue,year,authors,externalIds,url&limit=50`);if(e&&e.data&&0e.name).join(" and "),o=l.externalIds.DOI,s=bibtexToString({entryType:"article",citationKey:miniHash(l.authors[0].name.split(" ").last())+i+firstNonStopLowercase(t.title),title:t.title,author:n,journal:e,year:i,doi:o,bibSource:"Semantic Scholar "+l.url});return{venue:e,note:a,bibtex:s,status:r}}}catch(e){logError("[SemanticScholar]",e)}},tryGoogleScholar=async e=>{return await sendMessageToBackground({type:"google-scholar",paper:e})},tryPreprintMatch=async(e,t=!1)=>{let r,i,a,n,o={},s=["DBLP","SemanticScholar","CrossRef","GoogleScholar"],l=[silentPromiseTimeout(tryGoogleScholar(e)),silentPromiseTimeout(trySemanticScholar(e)),silentPromiseTimeout(tryCrossRef(e)),silentPromiseTimeout(tryDBLP(e))];t&&(l.push(silentPromiseTimeout(tryPWCMatch(e))),s.push("PapersWithCode"));for(var[c,p]of Object.entries(s)){if(o[p]=await l[c],{note:r,venue:i,bibtex:a}=o[p]??{},r)break;log(`[${p}] No publication found`)}return t&&(t="PapersWithCode",o.hasOwnProperty(t)||(o[t]=await l[t]),o[t].codeLink&&!e.codeLink&&(n=o[t].codeLink)),{note:r,venue:i,bibtex:a,code:n}},initPaper=async e=>{e.note||(e.note=""),e.md=`[${e.title}](${e.pdfLink})`,e.tags=[],e.codeLink=e.codeLink??"",e.favorite=!1,e.favoriteDate="",e.addDate=(new Date).toJSON(),e.lastOpenDate=e.addDate,e.count=1,e.code={};for(const t in e)e.hasOwnProperty(t)&&"string"==typeof e[t]&&(e[t]=e[t].trim());return e=await autoTagPaper(e),validatePaper(e),e},autoTagPaper=async r=>{try{var e,i,a=await getStorage("autoTags");if(!a||!a.length)return r;let t=new Set;for(const n of a)n.tags?.length&&(n.title||n.author)&&(e=!n.title||new RegExp(n.title,"i").test(r.title),i=!n.author||new RegExp(n.author,"i").test(r.author),e&&i&&n.tags.forEach(e=>t.add(e)));return r.tags=[...t].sort(),r.tags.length&&log("Automatically adding tags:",r.tags),r}catch(e){return log("Error auto-tagging:",e),log("Paper:",r),r}},makePaper=async(e,t,r=!1)=>{let i;if(r)(i=await makeWebsitePaper(r))&&(i.source="website");else if(e.arxiv)(i=await makeArxivPaper(t))&&(i.source="arxiv");else if(e.neurips)(i=await makeNeuripsPaper(t))&&(i.source="neurips");else if(e.cvf)(i=await makeCVFPaper(t))&&(i.source="cvf");else if(e.openreview)(i=await makeOpenReviewPaper(t))&&(i.source="openreview");else if(e.biorxiv)(i=await makeBioRxivPaper(t))&&(i.source="biorxiv");else if(e.pmlr)(i=await makePMLRPaper(t))&&(i.source="pmlr");else if(e.acl)(i=await makeACLPaper(t))&&(i.source="acl");else if(e.pnas)(i=await makePNASPaper(t))&&(i.source="pnas");else if(e.nature)(i=await makeNaturePaper(t))&&(i.source="nature");else if(e.acs)(i=await makeACSPaper(t))&&(i.source="acs");else if(e.iop)(i=await makeIOPPaper(t))&&(i.source="iop");else if(e.jmlr)(i=await makeJMLRPaper(t))&&(i.source="jmlr");else if(e.pmc)(i=await makePMCPaper(t))&&(i.source="pmc");else if(e.ijcai)(i=await makeIJCAIPaper(t))&&(i.source="ijcai");else if(e.acm)(i=await makeACMPaper(t))&&(i.source="acm");else if(e.ieee)(i=await makeIEEEPaper(t))&&(i.source="ieee");else if(e.springer)(i=await makeSpringerPaper(t))&&(i.source="springer");else if(e.aps)(i=await makeAPSPaper(t))&&(i.source="aps");else if(e.wiley)(i=await makeWileyPaper(t))&&(i.source="wiley");else if(e.sciencedirect)(i=await makeScienceDirectPaper(t))&&(i.source="sciencedirect");else if(e.science)(i=await makeSciencePaper(t))&&(i.source="science");else if(e.frontiers)(i=await makeFrontiersPaper(t))&&(i.source="frontiers");else if(e.ihep)(i=await makeIHEPPaper(t))&&(i.source="ihep");else if(e.plos)(i=await makePLOSPaper(t))&&(i.source="plos");else if(e.rsc)(i=await makeRSCPaper(t))&&(i.source="rsc");else if(e.mdpi)(i=await makeMDPIPaper(t))&&(i.source="mdpi");else{if(!e.oup)throw new Error("Unknown paper source: "+JSON.stringify({is:e,url:t}));(i=await makeOUPPaper(t))&&(i.source="oup")}if(void 0!==i)return initPaper(i)},findFuzzyPaperMatch=(e,t)=>{t=miniHash(t.title);if(e.hasOwnProperty(t)){const r=e[t];e=r.find(t=>!global.preprintSources.some(e=>t.toLowerCase().startsWith(e)));return e?e:r[0]}return null};"undefined"!=typeof module&&null!=module.exports&&((dummyModule=module).exports={autoTagPaper:autoTagPaper,decodeHtml:decodeHtml,fetchArxivXML:fetchArxivXML,fetchCrossRefDataForDoi:fetchCrossRefDataForDoi,fetchCvfHTML:fetchCvfHTML,fetchDom:fetchDom,getOpenReviewForumJSON:getOpenReviewForumJSON,getOpenReviewNoteJSON:getOpenReviewNoteJSON,fetchSemanticScholarDataForDoi:fetchSemanticScholarDataForDoi,fetchText:fetchText,findACLValue:findACLValue,findFuzzyPaperMatch:findFuzzyPaperMatch,flipAndAuthors:flipAndAuthors,flipAuthor:flipAuthor,initPaper:initPaper,makeACLPaper:makeACLPaper,makeACMPaper:makeACMPaper,makeACSPaper:makeACSPaper,makeAPSPaper:makeAPSPaper,makeArxivPaper:makeArxivPaper,makeBioRxivPaper:makeBioRxivPaper,makeCVFPaper:makeCVFPaper,makeIEEEPaper:makeIEEEPaper,makeIJCAIPaper:makeIJCAIPaper,makeIOPPaper:makeIOPPaper,makeJMLRPaper:makeJMLRPaper,makeNaturePaper:makeNaturePaper,makeNeuripsPaper:makeNeuripsPaper,makeOpenReviewBibTex:makeOpenReviewBibTex,makeOpenReviewPaper:makeOpenReviewPaper,makePaper:makePaper,makePMCPaper:makePMCPaper,makePMLRPaper:makePMLRPaper,makePNASPaper:makePNASPaper,makePubMedPaper:makePubMedPaper,makePLOSPaper:makePLOSPaper,makeSpringerPaper:makeSpringerPaper,makeWileyPaper:makeWileyPaper,tryCrossRef:tryCrossRef,tryDBLP:tryDBLP,tryPreprintMatch:tryPreprintMatch,tryPWCMatch:tryPWCMatch,trySemanticScholar:trySemanticScholar});
\ No newline at end of file