hypothesis 1.1234.0 → 1.1235.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/boot.js CHANGED
@@ -1 +1 @@
1
- !function(){"use strict";var s={"scripts/annotator.bundle.js":"scripts/annotator.bundle.js?94a8fb","styles/annotator.css":"styles/annotator.css?13d96a","styles/annotator.css.map":"styles/annotator.css.map?420356","styles/highlights.css":"styles/highlights.css?6b4ebd","styles/highlights.css.map":"styles/highlights.css.map?241350","styles/katex.min.css":"styles/katex.min.css?e9b69c","styles/katex.min.css.map":"styles/katex.min.css.map?42d80c","styles/pdfjs-overrides.css":"styles/pdfjs-overrides.css?c95edf","styles/pdfjs-overrides.css.map":"styles/pdfjs-overrides.css.map?1d8ac6","styles/sidebar.css":"styles/sidebar.css?8f4540","styles/sidebar.css.map":"styles/sidebar.css.map?413951","styles/ui-playground.css":"styles/ui-playground.css?1b3d17","styles/ui-playground.css.map":"styles/ui-playground.css.map?09dade","scripts/annotator.bundle.js.map":"scripts/annotator.bundle.js.map?564425","scripts/sidebar.bundle.js":"scripts/sidebar.bundle.js?c7d3f5","scripts/ui-playground.bundle.js":"scripts/ui-playground.bundle.js?a3508b","scripts/ui-playground.bundle.js.map":"scripts/ui-playground.bundle.js.map?aa02fd","scripts/sidebar.bundle.js.map":"scripts/sidebar.bundle.js.map?5d4339"};function t(s){s.setAttribute("data-hypothesis-asset","")}function e(s,e){var r=s.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=e,t(r),s.head.appendChild(r)}function r(s,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.esModule,o=void 0===n||n,a=r.forceReload,i=void 0!==a&&a,l=s.createElement("script");o&&(l.type="module"),i&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,t(l),s.head.appendChild(l)}function n(s,e,r,n){var o=s.createElement("link");o.rel=e,o.href=n,o.type="application/annotator+".concat(r),t(o),s.head.appendChild(o)}function o(s,e,r){var n=s.createElement("link");n.rel="preload",n.as=e,n.href=r,"fetch"===e&&(n.crossOrigin="anonymous"),t(n),s.head.appendChild(n)}function a(s,t){return s.assetRoot+"build/"+s.manifest[t]}function i(s){var t=s.match(/(https?):\/\/([^:/]+)/);return t?{protocol:t[1],hostname:t[2]}:null}function l(){var s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,t=s.currentScript;return t?i(t.src):null}function p(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=l(t);if(!e)throw new Error("Could not process URL template because script origin is unknown");return s=(s=s.replace("{current_host}",e.hostname)).replace("{current_scheme}",e.protocol)}if(function(){var s=[function(){return Object.fromEntries([])},function(){return new URL(document.location.href)},function(){return new Request("https://hypothes.is")},function(){return Element.prototype.attachShadow},function(){return CSS.supports("display: grid")},function(){return document.evaluate("/html/body",document,null,XPathResult.ANY_TYPE,null),!0}];try{return s.every((function(s){return s()}))}catch(s){return!1}}()){var c=function(s){for(var t={},e=s.querySelectorAll("script.js-hypothesis-config"),r=0;r<e.length;r++){var n=void 0;try{n=JSON.parse(e[r].textContent||"")}catch(s){console.warn("Could not parse settings from js-hypothesis-config tags",s),n={}}Object.assign(t,n)}return t}(document),u=p(c.assetRoot||"https://cdn.hypothes.is/hypothesis/1.1234.0/");if(document.querySelector("hypothesis-app")){!function(s,t){o(s,"fetch",t.apiUrl),o(s,"fetch",t.apiUrl+"links");for(var n=0,i=["scripts/sidebar.bundle.js"];n<i.length;n++)r(s,a(t,i[n]),{esModule:!0});for(var l=0,p=["styles/katex.min.css","styles/sidebar.css"];l<p.length;l++)e(s,a(t,p[l]))}(document,{assetRoot:u,manifest:s,apiUrl:c.apiUrl})}else{var d=c,h=p(d.notebookAppUrl||"https://hypothes.is/notebook"),y=p(d.profileAppUrl||"https://hypothes.is/user-profile"),f=p(d.sidebarAppUrl||"https://hypothes.is/app.html");!function(s,t){if(!s.querySelector('link[type="application/annotator+html"]')){n(s,"sidebar","html",t.sidebarAppUrl),n(s,"notebook","html",t.notebookAppUrl),n(s,"profile","html",t.profileAppUrl),o(s,"style",a(t,"styles/annotator.css")),n(s,"hypothesis-client","javascript",t.assetRoot+"build/boot.js");for(var i=0,l=["scripts/annotator.bundle.js"];i<l.length;i++)r(s,a(t,l[i]),{esModule:!1});var p=[];void 0!==window.PDFViewerApplication&&p.push("styles/pdfjs-overrides.css"),p.push("styles/highlights.css");for(var c=0,u=p;c<u.length;c++)e(s,a(t,u[c]))}}(document,{assetRoot:u,manifest:s,notebookAppUrl:h,profileAppUrl:y,sidebarAppUrl:f})}}else console.warn("The Hypothesis annotation tool is not supported in this browser. See https://web.hypothes.is/help/which-browsers-are-supported-by-hypothesis/.")}();
1
+ !function(){"use strict";var s={"scripts/annotator.bundle.js":"scripts/annotator.bundle.js?10db83","styles/annotator.css":"styles/annotator.css?13d96a","styles/annotator.css.map":"styles/annotator.css.map?420356","styles/highlights.css":"styles/highlights.css?6b4ebd","styles/highlights.css.map":"styles/highlights.css.map?241350","styles/katex.min.css":"styles/katex.min.css?e9b69c","styles/katex.min.css.map":"styles/katex.min.css.map?42d80c","styles/pdfjs-overrides.css":"styles/pdfjs-overrides.css?c95edf","styles/pdfjs-overrides.css.map":"styles/pdfjs-overrides.css.map?1d8ac6","styles/sidebar.css":"styles/sidebar.css?8f4540","styles/sidebar.css.map":"styles/sidebar.css.map?413951","styles/ui-playground.css":"styles/ui-playground.css?1b3d17","styles/ui-playground.css.map":"styles/ui-playground.css.map?09dade","scripts/annotator.bundle.js.map":"scripts/annotator.bundle.js.map?564425","scripts/sidebar.bundle.js":"scripts/sidebar.bundle.js?b1ebbe","scripts/ui-playground.bundle.js":"scripts/ui-playground.bundle.js?a3508b","scripts/ui-playground.bundle.js.map":"scripts/ui-playground.bundle.js.map?aa02fd","scripts/sidebar.bundle.js.map":"scripts/sidebar.bundle.js.map?12cf22"};function t(s){s.setAttribute("data-hypothesis-asset","")}function e(s,e){var r=s.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=e,t(r),s.head.appendChild(r)}function r(s,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.esModule,o=void 0===n||n,a=r.forceReload,i=void 0!==a&&a,l=s.createElement("script");o&&(l.type="module"),i&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,t(l),s.head.appendChild(l)}function n(s,e,r,n){var o=s.createElement("link");o.rel=e,o.href=n,o.type="application/annotator+".concat(r),t(o),s.head.appendChild(o)}function o(s,e,r){var n=s.createElement("link");n.rel="preload",n.as=e,n.href=r,"fetch"===e&&(n.crossOrigin="anonymous"),t(n),s.head.appendChild(n)}function a(s,t){return s.assetRoot+"build/"+s.manifest[t]}function i(s){var t=s.match(/(https?):\/\/([^:/]+)/);return t?{protocol:t[1],hostname:t[2]}:null}function l(){var s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,t=s.currentScript;return t?i(t.src):null}function p(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=l(t);if(!e)throw new Error("Could not process URL template because script origin is unknown");return s=(s=s.replace("{current_host}",e.hostname)).replace("{current_scheme}",e.protocol)}if(function(){var s=[function(){return Object.fromEntries([])},function(){return new URL(document.location.href)},function(){return new Request("https://hypothes.is")},function(){return Element.prototype.attachShadow},function(){return CSS.supports("display: grid")},function(){return document.evaluate("/html/body",document,null,XPathResult.ANY_TYPE,null),!0}];try{return s.every((function(s){return s()}))}catch(s){return!1}}()){var c=function(s){for(var t={},e=s.querySelectorAll("script.js-hypothesis-config"),r=0;r<e.length;r++){var n=void 0;try{n=JSON.parse(e[r].textContent||"")}catch(s){console.warn("Could not parse settings from js-hypothesis-config tags",s),n={}}Object.assign(t,n)}return t}(document),u=p(c.assetRoot||"https://cdn.hypothes.is/hypothesis/1.1235.0/");if(document.querySelector("hypothesis-app")){!function(s,t){o(s,"fetch",t.apiUrl),o(s,"fetch",t.apiUrl+"links");for(var n=0,i=["scripts/sidebar.bundle.js"];n<i.length;n++)r(s,a(t,i[n]),{esModule:!0});for(var l=0,p=["styles/katex.min.css","styles/sidebar.css"];l<p.length;l++)e(s,a(t,p[l]))}(document,{assetRoot:u,manifest:s,apiUrl:c.apiUrl})}else{var d=c,h=p(d.notebookAppUrl||"https://hypothes.is/notebook"),y=p(d.profileAppUrl||"https://hypothes.is/user-profile"),f=p(d.sidebarAppUrl||"https://hypothes.is/app.html");!function(s,t){if(!s.querySelector('link[type="application/annotator+html"]')){n(s,"sidebar","html",t.sidebarAppUrl),n(s,"notebook","html",t.notebookAppUrl),n(s,"profile","html",t.profileAppUrl),o(s,"style",a(t,"styles/annotator.css")),n(s,"hypothesis-client","javascript",t.assetRoot+"build/boot.js");for(var i=0,l=["scripts/annotator.bundle.js"];i<l.length;i++)r(s,a(t,l[i]),{esModule:!1});var p=[];void 0!==window.PDFViewerApplication&&p.push("styles/pdfjs-overrides.css"),p.push("styles/highlights.css");for(var c=0,u=p;c<u.length;c++)e(s,a(t,u[c]))}}(document,{assetRoot:u,manifest:s,notebookAppUrl:h,profileAppUrl:y,sidebarAppUrl:f})}}else console.warn("The Hypothesis annotation tool is not supported in this browser. See https://web.hypothes.is/help/which-browsers-are-supported-by-hypothesis/.")}();
@@ -1,5 +1,5 @@
1
1
  {
2
- "scripts/annotator.bundle.js": "scripts/annotator.bundle.js?94a8fb",
2
+ "scripts/annotator.bundle.js": "scripts/annotator.bundle.js?10db83",
3
3
  "styles/annotator.css": "styles/annotator.css?13d96a",
4
4
  "styles/annotator.css.map": "styles/annotator.css.map?420356",
5
5
  "styles/highlights.css": "styles/highlights.css?6b4ebd",
@@ -13,8 +13,8 @@
13
13
  "styles/ui-playground.css": "styles/ui-playground.css?1b3d17",
14
14
  "styles/ui-playground.css.map": "styles/ui-playground.css.map?09dade",
15
15
  "scripts/annotator.bundle.js.map": "scripts/annotator.bundle.js.map?564425",
16
- "scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?c7d3f5",
16
+ "scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?b1ebbe",
17
17
  "scripts/ui-playground.bundle.js": "scripts/ui-playground.bundle.js?a3508b",
18
18
  "scripts/ui-playground.bundle.js.map": "scripts/ui-playground.bundle.js.map?aa02fd",
19
- "scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?5d4339"
19
+ "scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?12cf22"
20
20
  }
@@ -119,7 +119,7 @@ this._sidebarRPC.on("setHighlightsVisible",(t=>{this.setHighlightsVisible(t,!1)}
119
119
  ;const n=xo(t);if(!n)return;const i=Je(n,null===(e=t.annotation)||void 0===e?void 0:e.$cluster);i.forEach((e=>{e._annotation=t.annotation})),t.highlights=i,this._hoveredAnnotations.has(t.annotation.$tag)&&nn(i,!0)};this.detach(t.$tag,!1),this._annotations.add(t.$tag),t.target||(t.target=[]);const n=await Promise.all(t.target.map((async e=>{if(!e.selector||!e.selector.some((t=>"TextQuoteSelector"===t.type)))return{annotation:t,target:e};let n;try{const i=await this._integration.anchor(this.element,e.selector),o=ze.fromRange(i);n={annotation:t,target:e,range:o}}catch(i){n={annotation:t,target:e}}return n})));if(!this._annotations.has(t.$tag))return[];for(const t of n)e(t);return t.$orphan=n.length>0&&n.every((t=>t.target.selector&&!t.range)),this._updateAnchors(this.anchors.concat(n),!0),this._sidebarRPC.call("syncAnchoringStatus",t),n}detach(t,e=!0){this._annotations.delete(t);const n=[];for(const e of this.anchors)e.annotation.$tag!==t?n.push(e):e.highlights&&en(e.highlights);this._updateAnchors(n,e)}
120
120
  _updateAnchors(t,e){var n;this.anchors=t,null===(n=this._clusterToolbar)||void 0===n||n.scheduleClusterUpdates(),e&&this._bucketBarClient.update(this.anchors)}async createAnnotation({highlight:t=!1}={}){const e=this.selectedRanges;this.selectedRanges=[];const n=await this.getDocumentInfo(),i=this.element,r=(await Promise.all(e.map((t=>this._integration.describe(i,t))))).map((t=>({source:n.uri,selector:t}))),s={uri:n.uri,document:n.metadata,target:r,$highlight:t,$cluster:t?"user-highlights":"user-annotations",$tag:"a:"+o(8)};return this._sidebarRPC.call("createAnnotation",s),this.anchor(s),Co(),s}_hoverAnnotations(t){this._hoveredAnnotations.clear(),t.forEach((t=>this._hoveredAnnotations.add(t)));for(const e of this.anchors)if(e.highlights){const n=t.includes(e.annotation.$tag);nn(e.highlights,n)}this._sidebarRPC.call("hoverAnnotations",t)}_scrollToClosestOffScreenAnchor(t,e){const n=function(t,e){let n=null,i=0;for(let r of t){var o;if(null===(o=r.highlights)||void 0===o||!o.length)continue
121
121
  ;const t=on(r.highlights).top;"up"===e&&t>=137||"down"===e&&t<=window.innerHeight-22||(!n||"up"===e&&t>i||"down"===e&&t<i)&&(n=r,i=t)}return n}(this.anchors.filter((({annotation:e})=>t.includes(e.$tag))),e);n&&this._integration.scrollToAnchor(n)}_onSelection(t){const e=this._integration.getAnnotatableRange(t);if(!e)return void this._onClearSelection();const n=document.getSelection(),i=Xe(n),o=Ge(n);o?(this.selectedRanges=[e],this._hostRPC.call("textSelected"),this._adder.annotationsForSelection=yo(),this._isAdderVisible=!0,this._adder.show(o,i)):this._onClearSelection()}_onClearSelection(){this._isAdderVisible=!1,this._adder.hide(),this.selectedRanges=[],this._informHostOnNextSelectionClear&&this._hostRPC.call("textUnselected"),this._informHostOnNextSelectionClear=!0}selectAnnotations(t,{toggle:e=!1,focusInSidebar:n=!1}={}){e?this._sidebarRPC.call("toggleAnnotationSelection",t):this._sidebarRPC.call("showAnnotations",t,n),this._sidebarRPC.call("openSidebar")}setHighlightsVisible(t,e=!0){!function(t,e){
122
- t.classList.toggle("hypothesis-highlights-always-on",e)}(this.element,t),this._highlightsVisible=t,e&&this._hostRPC.call("highlightsVisibleChanged",t)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(t){this._sideBySideActive=this._integration.fitSideBySide(t)}get sideBySideActive(){return this._sideBySideActive}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){Bt(t,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}}function Eo(t,e){const n=new URL(t),i=new URLSearchParams;return i.append("config",JSON.stringify(e)),n.hash=i.toString(),n.toString()}function No(t,e){var n;const i={};for(let[t,n]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=n&&(i[t]=n);i.origin=new URL(t).origin,i.version="1.1234.0";const o=new URL(window.location.href);if(o.hash="",i.hostURL=o.toString(),Array.isArray(i.services)&&(null===(n=i.services)||void 0===n?void 0:n.length)>0){const t=i.services[0]
122
+ t.classList.toggle("hypothesis-highlights-always-on",e)}(this.element,t),this._highlightsVisible=t,e&&this._hostRPC.call("highlightsVisibleChanged",t)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(t){this._sideBySideActive=this._integration.fitSideBySide(t)}get sideBySideActive(){return this._sideBySideActive}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){Bt(t,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}}function Eo(t,e){const n=new URL(t),i=new URLSearchParams;return i.append("config",JSON.stringify(e)),n.hash=i.toString(),n.toString()}function No(t,e){var n;const i={};for(let[t,n]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=n&&(i[t]=n);i.origin=new URL(t).origin,i.version="1.1235.0";const o=new URL(window.location.href);if(o.hash="",i.hostURL=o.toString(),Array.isArray(i.services)&&(null===(n=i.services)||void 0===n?void 0:n.length)>0){const t=i.services[0]
123
123
  ;t.onLoginRequest&&(t.onLoginRequestProvided=!0),t.onLogoutRequest&&(t.onLogoutRequestProvided=!0),t.onSignupRequest&&(t.onSignupRequestProvided=!0),t.onProfileRequest&&(t.onProfileRequestProvided=!0),t.onHelpRequest&&(t.onHelpRequestProvided=!0)}return i}function Ao({config:t,groupId:e}){return Ut("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allowFullScreen:!0,src:Eo(t.notebookAppUrl,{...No(t.notebookAppUrl,t),group:e})})}function To({eventBus:t,config:e}){const[n,i]=Et(0),[o,r]=Et(!0),[s,a]=Et(null),l=At(""),c=At(null);Nt((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),Nt((()=>{document.body.style.overflow=o?l.current:"hidden"}),[o]),Nt((()=>{const e=t.createEmitter();return e.subscribe("openNotebook",(t=>{r(!1),i((t=>t+1)),a(t)})),c.current=e,()=>{e.destroy()}}),[t]);return null===s?null:Ut("div",{className:me("fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50",{hidden:o}),"data-testid":"notebook-outer",
124
124
  children:Ut("div",{className:"relative w-full h-full","data-testid":"notebook-inner",children:[Ut("div",{className:"absolute right-0 m-3",children:Ut(Ce,{title:"Close the Notebook",onClick:()=>{var t;r(!0),null===(t=c.current)||void 0===t||t.publish("closeNotebook")},variant:"dark",classes:me("!bg-transparent enabled:hover:!bg-grey-3"),children:Ut($t,{className:"w-4 h-4"})})}),Ut(Ao,{config:e,groupId:s},n)]})})}class Ro{constructor(t,n,i){e(this,"_outerContainer",void 0),e(this,"_shadowRoot",void 0),this._outerContainer=document.createElement("hypothesis-notebook"),t.appendChild(this._outerContainer),this._shadowRoot=Oe(this._outerContainer),ht(Ut(To,{eventBus:n,config:i}),this._shadowRoot)}destroy(){ht(null,this._shadowRoot),this._outerContainer.remove()}}function ko({eventBus:t,config:e}){const[n,i]=Et(!0),o=At(null);Nt((()=>{const e=t.createEmitter();return e.subscribe("openProfile",(()=>{i(!1)})),o.current=e,()=>{e.destroy()}}),[t]);return n?null:Ut("div",{
125
125
  className:"fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50","data-testid":"profile-outer",children:Ut("div",{className:"relative w-full h-full","data-testid":"profile-inner",children:[Ut("div",{className:"absolute right-0 m-3",children:Ut(Ce,{title:"Close the Profile",onClick:()=>{var t;i(!0),null===(t=o.current)||void 0===t||t.publish("closeProfile")},variant:"dark",classes:me("!bg-transparent enabled:hover:!bg-grey-3"),children:Ut($t,{className:"w-4 h-4"})})}),Ut("iframe",{title:"Hypothesis profile",className:"h-full w-full border-0",src:e.profileAppUrl})]})})}class Po{constructor(t,n,i){e(this,"_outerContainer",void 0),e(this,"shadowRoot",void 0),this._outerContainer=document.createElement("hypothesis-profile"),t.appendChild(this._outerContainer),this.shadowRoot=Oe(this._outerContainer),ht(Ut(ko,{eventBus:n,config:i}),this.shadowRoot)}destroy(){ht(null,this.shadowRoot),this._outerContainer.remove()}}var Oo={},Lo={get exports(){return Oo},set exports(t){Oo=t}};!function(t){!function(e,n,i,o){
@@ -533,7 +533,7 @@ n.push(t[e]));return{...Pm,id:"root",children:n}}(e);return n&&(o.children=o.chi
533
533
  ;function ep(e){return function(e){return e.replace(Qm,"")}((t=e,t.normalize("NFKD"))).toLowerCase();var t}class tp{constructor(e,t){qi(this,"term",void 0),qi(this,"matcher",void 0),this.term=t.normalize(e),this.matcher=t}matches(e){const t=this.matcher;return t.fieldValues(e).some((e=>t.matches(t.normalize(e),this.term)))}}class np{constructor(e,t){qi(this,"operator",void 0),qi(this,"filters",void 0),this.operator=e,this.filters=t}matches(e){return"and"===this.operator?this.filters.every((t=>t.matches(e))):this.filters.some((t=>t.matches(e)))}}function rp(e){return{fieldValues:e,matches:(e,t)=>e.includes(t),normalize:ep}}const op={quote:rp((e=>{var t;return[null!==(t=Kr(e))&&void 0!==t?t:""]})),since:{fieldValues:e=>[new Date(e.updated).valueOf()],matches:(e,t)=>(Date.now()-e)/1e3<=t,normalize:e=>e},tag:rp((e=>e.tags)),text:rp((e=>[e.text])),uri:rp((e=>[e.uri])),user:rp((e=>{var t,n;return[e.user,null!==(t=null===(n=e.user_info)||void 0===n?void 0:n.display_name)&&void 0!==t?t:""]}))};const ip=function(e){
534
534
  if(1!==e.length)throw new Error("Memoize input must be a function of one argument");let t,n;return function(r){return r===t||(t=r,n=e(r)),n}}((function(e){const t=e.selection,n={expanded:t.expanded,forcedVisible:t.forcedVisible,selected:t.selected,sortCompareFn:Jm[t.sortKey]},r=!!t.filterQuery||Object.keys(t.filters).length>0;if(r){const e=function(e,t={}){const n=[],r=[],o=[],i=[],a=[],s=[],l=t.user?[t.user]:[],c=Om(e);for(const e of c){const t=e.slice(0,e.indexOf(":")),c=e.slice(t.length+1);switch(t){case"quote":r.push(c);break;case"since":{const t=86400,n={sec:1,min:60,hour:3600,day:t,week:7*t,month:30*t,year:365*t},r=e.slice(6).toLowerCase().match(/^(\d+)(sec|min|hour|day|week|month|year)?$/);if(r){const e=parseFloat(r[1]),t=r[2]||"sec";o.push(e*n[t])}}break;case"tag":i.push(c);break;case"text":a.push(c);break;case"uri":s.push(c);break;case"user":l.push(c);break;default:n.push(e)}}return{any:{terms:n,operator:"and"},quote:{terms:r,operator:"and"},since:{terms:o,operator:"and"},tag:{terms:i,operator:"and"
535
535
  },text:{terms:a,operator:"and"},uri:{terms:s,operator:"or"},user:{terms:l,operator:"or"}}}(t.filterQuery||"",t.filters);n.filterFn=t=>function(e,t){const n=(e,t)=>new tp(t,op[e]),r=Object.entries(t).filter((([,e])=>e.terms.length>0)).map((([e,t])=>{let r;if("any"===e){const e=["quote","text","tag","user"];r=t.terms.map((t=>new np("or",e.map((e=>n(e,t))))))}else r=t.terms.map((t=>n(e,t)));return new np(t.operator,r)})),o=new np("and",r);return e.filter((e=>e.id&&o.matches(e))).map((e=>e.id))}([t],e).length>0}return!r&&"sidebar"===e.route&&(n.threadFilterFn=e=>{return!!e.annotation&&(n=e.annotation,r=t.selectedTab,!Ur(n)&&Ym(n)===r);var n,r}),Vm(e.annotations,n)}));function ap(){const e=Ei(),t=e.allAnnotations(),n=e.filterQuery(),r=e.route(),o=e.selectionState(),i=e.getFilterValues(),a=ae((()=>({annotations:t,route:r,selection:{...o,filterQuery:n,filters:i}})),[t,n,r,o,i]);return ip(a)}var sp=Qn((function({loadAnnotationsService:e,onLogin:t}){
536
- const n=Ei(),r=n.routeParams().id,o=ap(),i=n.profile().userid,[a,s]=te(!1);return re((()=>{s(!1),n.clearAnnotations(),e.loadThread(r).then((e=>{const t=e.filter((e=>0===(e.references||[]).length))[0];t&&(e.forEach((e=>e.id&&n.setExpanded(e.id,!0))),t.id!==r&&n.highlightAnnotations([r]))})).catch((()=>{s(!0)}))}),[r,i,e,n]),we(f,{children:[a&&we(Ai,{errorType:"annotation",onLoginRequest:t}),we(Im,{threads:o.children})]})}),["loadAnnotationsService"]);class lp{constructor(e,t,n=window){var r,o,i,a;qi(this,"version",void 0),qi(this,"userAgent",void 0),qi(this,"urls",void 0),qi(this,"fingerprint",void 0),qi(this,"account",void 0),qi(this,"timestamp",void 0),qi(this,"segment",void 0);const s="N/A";let l=s;e.userid&&(l=e.userid,e.displayName&&(l=`${e.displayName} (${l})`)),this.version="1.1234.0",this.userAgent=n.navigator.userAgent,this.urls=t.map((e=>e.uri)).join(", ")||s,this.fingerprint=null!==(r=null===(o=t[0])||void 0===o||null===(i=o.metadata)||void 0===i?void 0:i.documentFingerprint)&&void 0!==r?r:s,
536
+ const n=Ei(),r=n.routeParams().id,o=ap(),i=n.profile().userid,[a,s]=te(!1);return re((()=>{s(!1),n.clearAnnotations(),e.loadThread(r).then((e=>{const t=e.filter((e=>0===(e.references||[]).length))[0];t&&(e.forEach((e=>e.id&&n.setExpanded(e.id,!0))),t.id!==r&&n.highlightAnnotations([r]))})).catch((()=>{s(!0)}))}),[r,i,e,n]),we(f,{children:[a&&we(Ai,{errorType:"annotation",onLoginRequest:t}),we(Im,{threads:o.children})]})}),["loadAnnotationsService"]);class lp{constructor(e,t,n=window){var r,o,i,a;qi(this,"version",void 0),qi(this,"userAgent",void 0),qi(this,"urls",void 0),qi(this,"fingerprint",void 0),qi(this,"account",void 0),qi(this,"timestamp",void 0),qi(this,"segment",void 0);const s="N/A";let l=s;e.userid&&(l=e.userid,e.displayName&&(l=`${e.displayName} (${l})`)),this.version="1.1235.0",this.userAgent=n.navigator.userAgent,this.urls=t.map((e=>e.uri)).join(", ")||s,this.fingerprint=null!==(r=null===(o=t[0])||void 0===o||null===(i=o.metadata)||void 0===i?void 0:i.documentFingerprint)&&void 0!==r?r:s,
537
537
  this.account=l,this.timestamp=(new Date).toString();const c=null===(a=t[0])||void 0===a?void 0:a.segment;if(c){const e=[];c.cfi&&e.push(["CFI",c.cfi]),c.url&&e.push(["URL",c.url]),this.segment=e.map((([e,t])=>`${e}: ${t}`)).join(", ")}}asFormattedString(){return`Version: ${this.version}\nUser Agent: ${this.userAgent}\nURL: ${this.urls}\nFingerprint: ${this.fingerprint}\nAccount: ${this.account}\nDate: ${this.timestamp}\n`}asEncodedURLString(){return encodeURIComponent(this.asFormattedString())}}function cp(e,t,n){e.self===e?e.scrollTo(t,n):(e.scrollLeft=t,e.scrollTop=n)}function up(e){var t=e._scrollSettings;if(t){var n=t.maxSynchronousAlignments,r=function(e,t){var n,r,o,i,a,s,l,c=e.align,u=e.target.getBoundingClientRect(),d=c&&null!=c.left?c.left:.5,h=c&&null!=c.top?c.top:.5,m=c&&null!=c.leftOffset?c.leftOffset:0,p=c&&null!=c.topOffset?c.topOffset:0,f=d,g=h;if(e.isWindow(t))s=Math.min(u.width,t.innerWidth),l=Math.min(u.height,t.innerHeight),r=u.left+t.pageXOffset-t.innerWidth*f+s*f,
538
538
  o=u.top+t.pageYOffset-t.innerHeight*g+l*g,r-=m,o-=p,r=e.align.lockX?t.pageXOffset:r,o=e.align.lockY?t.pageYOffset:o,i=r-t.pageXOffset,a=o-t.pageYOffset;else{s=u.width,l=u.height,n=t.getBoundingClientRect();var v=u.left-(n.left-t.scrollLeft),b=u.top-(n.top-t.scrollTop);r=v+s*f-t.clientWidth*f,o=b+l*g-t.clientHeight*g,r-=m,o-=p,r=Math.max(Math.min(r,t.scrollWidth-t.clientWidth),0),o=Math.max(Math.min(o,t.scrollHeight-t.clientHeight),0),r=e.align.lockX?t.scrollLeft:r,o=e.align.lockY?t.scrollTop:o,i=r-t.scrollLeft,a=o-t.scrollTop}return{x:r,y:o,differenceX:i,differenceY:a}}(t,e),o=Date.now()-t.startTime,i=Math.min(1/t.time*o,1);if(t.endIterations>=n)return cp(e,r.x,r.y),e._scrollSettings=null,t.end("complete");var a=1-t.ease(i);if(cp(e,r.x-r.differenceX*a,r.y-r.differenceY*a),o>=t.time)return t.endIterations++,t.scrollAncestor&&up(t.scrollAncestor),void up(e);!function(e){if("requestAnimationFrame"in window)return window.requestAnimationFrame(e);setTimeout(e,16)}(up.bind(null,e))}}function dp(e){return e.self===e
539
539
  }function hp(e){return"pageXOffset"in e||(e.scrollHeight!==e.clientHeight||e.scrollWidth!==e.clientWidth)&&"hidden"!==getComputedStyle(e).overflow}function mp(){return!0}function pp(e){if(e.assignedSlot)return pp(e.assignedSlot);if(e.parentElement)return"body"===e.parentElement.tagName.toLowerCase()?e.parentElement.ownerDocument.defaultView||e.parentElement.ownerDocument.ownerWindow:e.parentElement;if(e.getRootNode){var t=e.getRootNode();if(11===t.nodeType)return t.host}}var fp=function(e,t,n){if(e){"function"==typeof t&&(n=t,t=null),t||(t={}),t.time=isNaN(t.time)?1e3:t.time,t.ease=t.ease||function(e){return 1-Math.pow(1-e,e/2)},t.align=t.align||{};var r=pp(e),o=1,i=t.validTarget||mp,a=t.isScrollable;t.debug&&(console.log("About to scroll to",e),r||console.error("Target did not have a parent, is it mounted in the DOM?"));for(var s=[];r;)if(t.debug&&console.log("Scrolling parent node",r),i(r,o)&&(a?a(r,hp):hp(r))&&(o++,s.push(r)),!(r=pp(r))){l("complete");break}return s.reduce(((n,r,o)=>function(e,t,n,r,o){
@@ -580,22 +580,22 @@ if(e.scopes&&e.scopes.uri_patterns.length>0&&t)return function(e,t){return t.som
580
580
  t.permissions=n.isPrivate?na(e.user):ra(e.user,e.group)),{...e,...t}}_initialize(e,t=new Date){const n=this._store.getDefault("annotationPrivacy"),r=this._store.focusedGroupId(),o=this._store.profile();if(!r)throw new Error("Cannot create annotation without a group");const i=o.userid;if(!i)throw new Error("Cannot create annotation when logged out");const a=o.user_info,s="s:"+bf(8),l=Object.assign({created:t.toISOString(),group:r,permissions:oa(i,r,n),tags:[],text:"",updated:t.toISOString(),user:i,user_info:a,$tag:s,hidden:!1,links:{},document:{title:""}},e);return qr(l)&&(l.permissions=na(i)),l}create(e,t=new Date){const n=this._initialize(e,t);this._store.addAnnotations([n]),this._store.deleteNewAndEmptyDrafts(),qr(n)||this._store.createDraft(n,{tags:n.tags,text:n.text,isPrivate:!Fr(n)}),Gr(n)?this._store.selectTab("note"):Vr(n)&&this._store.selectTab("annotation"),(n.references||[]).forEach((e=>{this._store.setExpanded(e,!0)}))}createPageNote(){const e=this._store.mainFrame()
581
581
  ;if(!this._store.isLoggedIn())return void this._store.openSidebarPanel("loginPrompt");if(!e)return;const t={target:[],uri:e.uri};this.create(t)}async delete(e){await this._api.annotation.delete({id:e.id}),this._activity.reportActivity("delete",e),this._store.removeAnnotations([e])}async flag(e){await this._api.annotation.flag({id:e.id}),this._activity.reportActivity("flag",e),this._store.updateFlagStatus(e.id,!0)}reply(e,t){const n={group:e.group,permissions:Fr(e)?ra(t,e.group):na(t),references:(e.references||[]).concat(e.id),target:[{source:e.target[0].source}],uri:e.uri};this.create(n)}async save(e){let t,n;const r=this._applyDraftChanges(e);let o;Pr(e)?(t=this._api.annotation.update({id:e.id},r),n="update"):(t=this._api.annotation.create({},r),n="create"),this._store.annotationSaveStarted(e);try{o=await t,this._activity.reportActivity(n,o)}finally{this._store.annotationSaveFinished(e)}for(let[t,n]of Object.entries(e))if(t.startsWith("$")){o[t]=n}return this._store.removeDraft(e),
582
582
  this._store.addAnnotations([o]),o}}Lf.$inject=["annotationActivity","api","store"];class Rf extends Error{constructor(e,t,n=""){let r="Network request failed";t&&(r+=` (${t.status})`),n&&(r+=`: ${n}`),super(r),this.url=e,this.response=t,this.reason=n}}async function Of(e,t){let n,r;try{n=await fetch(e,t)}catch(t){throw new Rf(e,null,t.message)}if(204===n.status)return null;try{r=await n.json()}catch(t){throw new Rf(e,n,"Failed to parse response")}var o;if(!n.ok)throw new Rf(e,n,null===(o=r)||void 0===o?void 0:o.reason);return r}function Df(e){const t={};for(let[n,r]of Object.entries(e))n.startsWith("$")||(t[n]=r);return t}class Pf{constructor(e,t,n){const r=e.routes();this._clientId=null;const o=()=>this._clientId,i=e=>function(e,t,{getAccessToken:n,getClientId:r,onRequestStarted:o,onRequestFinished:i}){return async(a,s)=>{o();try{const[o,l]=await Promise.all([e,n()]),c=function(e,t){let n=e;const r=t.split(".");for(let[e,t]of r.entries()){const o=n[t];if(!o||"url"in o){if(o&&e===r.length-1)return o;break}n=o
583
- }return null}(o,t);if(!c)throw new Error(`Missing API route: ${t}`);const u={"Content-Type":"application/json","Hypothesis-Client-Version":"1.1234.0"};l&&(u.Authorization="Bearer "+l);const d=r();d&&(u["X-Client-Id"]=d);const{url:h,unusedParams:m}=Jo(c.url,a),p=new URL(h);for(let[e,t]of Object.entries(m)){Array.isArray(t)||(t=[t]);for(let n of t)null!=n&&p.searchParams.append(e,n.toString())}return await Of(p.toString(),{body:s?JSON.stringify(Df(s)):null,headers:u,method:c.method})}finally{i()}}}(r,e,{getAccessToken:()=>t.getAccessToken(),getClientId:o,onRequestStarted:n.apiRequestStarted,onRequestFinished:n.apiRequestFinished});this.search=i("search"),this.annotation={create:i("annotation.create"),delete:i("annotation.delete"),get:i("annotation.read"),update:i("annotation.update"),flag:i("annotation.flag"),hide:i("annotation.hide"),unhide:i("annotation.unhide")},this.group={member:{delete:i("group.member.delete")},read:i("group.read")},this.groups={list:i("groups.read")},this.profile={groups:{
583
+ }return null}(o,t);if(!c)throw new Error(`Missing API route: ${t}`);const u={"Content-Type":"application/json","Hypothesis-Client-Version":"1.1235.0"};l&&(u.Authorization="Bearer "+l);const d=r();d&&(u["X-Client-Id"]=d);const{url:h,unusedParams:m}=Jo(c.url,a),p=new URL(h);for(let[e,t]of Object.entries(m)){Array.isArray(t)||(t=[t]);for(let n of t)null!=n&&p.searchParams.append(e,n.toString())}return await Of(p.toString(),{body:s?JSON.stringify(Df(s)):null,headers:u,method:c.method})}finally{i()}}}(r,e,{getAccessToken:()=>t.getAccessToken(),getClientId:o,onRequestStarted:n.apiRequestStarted,onRequestFinished:n.apiRequestFinished});this.search=i("search"),this.annotation={create:i("annotation.create"),delete:i("annotation.delete"),get:i("annotation.read"),update:i("annotation.update"),flag:i("annotation.flag"),hide:i("annotation.hide"),unhide:i("annotation.unhide")},this.group={member:{delete:i("group.member.delete")},read:i("group.read")},this.groups={list:i("groups.read")},this.profile={groups:{
584
584
  read:i("profile.groups.read")},read:i("profile.read"),update:i("profile.update")}}setClientId(e){this._clientId=e}}Pf.$inject=["apiRoutes","auth","store"];var Bf={},Ff={get exports(){return Bf},set exports(e){Bf=e}},Hf={};function Uf(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var jf=Uf;Uf.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},Uf.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},Uf.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime()
585
585
  ;if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var r=this;return this._timer=setTimeout((function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout((function(){r._operationTimeoutCb(r._attempts)}),r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)}),n),this._options.unref&&this._timer.unref(),!0},Uf.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){n._operationTimeoutCb()}),n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},Uf.prototype.try=function(e){
586
586
  console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},Uf.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},Uf.prototype.start=Uf.prototype.try,Uf.prototype.errors=function(){return this._errors},Uf.prototype.attempts=function(){return this._attempts},Uf.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var o=this._errors[r],i=o.message,a=(e[i]||0)+1;e[i]=a,a>=n&&(t=o,n=a)}return t},function(e){var t=jf;e.operation=function(n){var r=e.timeouts(n);return new t(r,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],o=0;o<t.retries;o++)r.push(this.createTimeout(o,t))
587
587
  ;return e&&e.forever&&!r.length&&r.push(this.createTimeout(o,t)),r.sort((function(e,t){return e-t})),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return r=Math.min(r,t.maxTimeout)},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var o in r=[],t)"function"==typeof t[o]&&r.push(o);for(var i=0;i<r.length;i++){var a=r[i],s=t[a];t[a]=function(r){var o=e.operation(n),i=Array.prototype.slice.call(arguments,1),a=i.pop();i.push((function(e){o.retry(e)||(e&&(arguments[0]=o.mainError()),a.apply(this,arguments))})),o.attempt((function(){r.apply(t,i)}))}.bind(t,s),t[a].options=n}}}(Hf),Ff.exports=Hf;var qf=t(Bf);function $f(e,t){return new Promise(((n,r)=>{const o=qf.operation(t);o.attempt((async()=>{try{const t=await e();o.retry(),n(t)}catch(e){o.retry(e)||r(e)}}))}))}function Gf(e){return $f((()=>Of(e)))}class Vf{constructor(e){this._apiURL=e.apiUrl,this._routeCache=null,this._linkCache=null}routes(){
588
- return this._routeCache||(this._routeCache=Gf(this._apiURL).then((e=>e.links))),this._routeCache}links(){return this._linkCache||(this._linkCache=this.routes().then((async e=>{const t=e.links;return await Gf(t.url)}))),this._linkCache}}Vf.$inject=["settings"];class Yf extends Error{constructor(e,t){super(e),this.cause=t}}class Wf{constructor(e){this.clientId=e.clientId,this.tokenEndpoint=e.tokenEndpoint,this.authorizationEndpoint=e.authorizationEndpoint,this.revokeEndpoint=e.revokeEndpoint}exchangeAuthCode(e){return this._getAccessToken({client_id:this.clientId,grant_type:"authorization_code",code:e})}exchangeGrantToken(e){return this._getAccessToken({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e})}refreshToken(e){return this._getAccessToken({grant_type:"refresh_token",refresh_token:e})}async revokeToken(e){try{await this._formPost(this.revokeEndpoint,{token:e})}catch(e){throw new Yf("Failed to revoke access token",e)}}authorize(e){const t=bf(16),n=new Promise(((n,r)=>{
589
- e.addEventListener("message",(function o(i){"object"==typeof i.data&&i.data.state===t&&("authorization_response"===i.data.type&&n(i.data),"authorization_canceled"===i.data.type&&r(new Error("Authorization window was closed")),e.removeEventListener("message",o))}))})),r=new URL(this.authorizationEndpoint);r.searchParams.set("client_id",this.clientId),r.searchParams.set("origin",e.location.origin),r.searchParams.set("response_mode","web_message"),r.searchParams.set("response_type","code"),r.searchParams.set("state",t);const o=`left=${e.screen.width/2-237.5},top=${e.screen.height/2-215},width=475,height=430`;if(!e.open(r.toString(),"Log in to Hypothesis",o))throw new Error("Failed to open login window");return n.then((e=>e.code))}async _formPost(e,t){const n=new URLSearchParams;for(let[e,r]of Object.entries(t))n.set(e,r);n.sort();return Of(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()})}async _getAccessToken(e){let t;try{
590
- t=await this._formPost(this.tokenEndpoint,e)}catch(e){throw new Yf("Failed to fetch access token",e)}return{accessToken:t.access_token,expiresAt:Date.now()+1e3*(t.expires_in-10),refreshToken:t.refresh_token}}}class Kf extends Tp{constructor(e,t,n,r,o){super(),qi(this,"_authCode",void 0),qi(this,"_client",void 0),qi(this,"_tokenInfoPromise",void 0),qi(this,"_apiRoutes",void 0),qi(this,"_localStorage",void 0),qi(this,"_settings",void 0),qi(this,"_toastMessenger",void 0),qi(this,"_window",void 0),this._authCode=null,this._client=null,this._tokenInfoPromise=null,this._apiRoutes=t,this._localStorage=n,this._settings=r,this._toastMessenger=o,this._window=e,this._listenForTokenStorageEvents()}_listenForTokenStorageEvents(){this._window.addEventListener("storage",(({key:e})=>{e===this._storageKey()&&(this._tokenInfoPromise=null,this.emit("oauthTokensChanged"))}))}_loadToken(){const e=this._localStorage.getObject(this._storageKey())
591
- ;return e&&"string"==typeof e.accessToken&&"string"==typeof e.refreshToken&&"number"==typeof e.expiresAt?{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}:null}async _oauthClient(){if(this._client)return this._client;const e=await this._apiRoutes.links();var t,n;return this._client=new Wf({clientId:this._settings.oauthClientId,authorizationEndpoint:e["oauth.authorize"],revokeEndpoint:e["oauth.revoke"],tokenEndpoint:(t="token",n=this._settings.apiUrl,new URL(t,n).href)}),this._client}async _exchangeAuthCodeForToken(e){const t=await this._oauthClient(),n=await t.exchangeAuthCode(e);return this._saveToken(n),n}async _exchangeGrantToken(e){const t=await this._oauthClient();try{return await t.exchangeGrantToken(e)}catch(e){throw this._toastMessenger.error("Hypothesis login lost: You must reload the page to annotate.",{autoDismiss:!1}),e}}_getGrantToken(){var e;return null===(e=Kn(this._settings))||void 0===e?void 0:e.grantToken}_storageKey(){let e=new URL(this._settings.apiUrl).hostname
592
- ;return e=e.replace(/\./g,"%2E"),`hypothesis.oauth.${e}.token`}_saveToken(e){this._localStorage.setObject(this._storageKey(),e)}async _refreshAccessToken(e,t){const n=await this._oauthClient();let r;try{if(r=await n.refreshToken(e),Date.now()>r.expiresAt)throw new Error("Refreshed token expired in the past")}catch{return null}return t.persist&&this._saveToken(r),r}async getAccessToken(){if(!this._tokenInfoPromise){const e=this._getGrantToken();void 0!==e?this._tokenInfoPromise=e?this._exchangeGrantToken(e):Promise.resolve(null):this._authCode?(this._tokenInfoPromise=this._exchangeAuthCodeForToken(this._authCode),this._authCode=null):this._tokenInfoPromise=Promise.resolve(this._loadToken())}const e=this._tokenInfoPromise,t=await this._tokenInfoPromise;if(!t)return null;if(e!==this._tokenInfoPromise)return this.getAccessToken();if(Date.now()>t.expiresAt){const e=this._getGrantToken();return this._tokenInfoPromise=this._refreshAccessToken(t.refreshToken,{persist:void 0===e}),this.getAccessToken()}
593
- return t.accessToken}async login(){const e=await this._oauthClient(),t=await e.authorize(this._window);this._authCode=t,this._tokenInfoPromise=null}async logout(){const[e,t]=await Promise.all([this._tokenInfoPromise,this._oauthClient()]);e&&await t.revokeToken(e.accessToken),this._tokenInfoPromise=null,this._localStorage.removeItem(this._storageKey())}}Kf.$inject=["$window","apiRoutes","localStorage","settings","toastMessenger"];class Xf{constructor(e,t,n){qi(this,"_annotationsService",void 0),qi(this,"_toastMessenger",void 0),qi(this,"_store",void 0),qi(this,"_saving",void 0),qi(this,"_failed",void 0),this._annotationsService=e,this._toastMessenger=t,this._store=n,this._saving=new Set,this._failed=new Set}init(){const e=e=>!this._saving.has(e)&&!this._failed.has(e);this._store.subscribe((()=>{this._store.newHighlights().forEach((t=>{const n=t.$tag;e(n)&&(this._saving.add(n),$f((()=>this._annotationsService.save(t))).then((()=>{this._toastMessenger.success("Highlight saved",{visuallyHidden:!0})
594
- })).catch((()=>{this._failed.add(n)})).finally((()=>{this._saving.delete(n)})))}))}))}isSaving(){return this._saving.size>0}}function Zf(e){if(null===e||"object"!=typeof e)return!1;for(let t of["frame1","frame2","type","requestId"])if("string"!=typeof e[t])return!1;return!0}function Jf(e,t){return!!Zf(e)&&JSON.stringify(e,Object.keys(t).sort())===JSON.stringify(t,Object.keys(t).sort())}Xf.$inject=["annotationsService","toastMessenger","store"];class Qf{constructor({hostFrame:e,source:t,sourceId:n}){this._hostFrame=e,this._source=t,this._sourceId=n,this._listeners=new $i}destroy(){this._listeners.removeAll()}async discover(e){let t=!1;if(("guest"===this._source&&"host"===e||"guest"===this._source&&"sidebar"===e||"sidebar"===this._source&&"host"===e||"notebook"===this._source&&"sidebar"===e)&&(t=!0),!t)throw new Error("Invalid request of channel/port");const n=bf(6);return new Promise(((t,r)=>{const o=()=>{this._hostFrame.postMessage({frame1:this._source,frame2:e,type:"request",requestId:n,
595
- sourceId:this._sourceId},"*")},i=setInterval(o,250),a=setTimeout((()=>{clearInterval(i),r(new Error(`Unable to establish ${this._source}-${e} communication channel`))}),2e4),s=this._listeners.add(window,"message",(r=>{const{data:o,ports:l}=r;Jf(o,{frame1:this._source,frame2:e,type:"offer",requestId:n})&&(clearInterval(i),clearTimeout(a),this._listeners.remove(s),t(l[0]))}));o()}))}}function eg(e){const t=t=>{const{data:n}=t;if(n&&"hypothesis-error"===(null==n?void 0:n.type)){const{context:t,error:r}=n;e(r instanceof Error?r:function(e){const t=new Error(e.message);return t.stack=e.stack,t}(r),t)}};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function tg(e,t,n=[],r=-1){e.postMessage({protocol:"frame-rpc",version:"1.0.0",arguments:n,method:t,sequence:r})}class ng{constructor({userAgent:e=navigator.userAgent,currentWindow:t=window}={}){this._port=null,this._methods=new Map,this._sequence=1,this._callbacks=new Map,this._listeners=new $i,
596
- this._listeners.add(t,"unload",(()=>{this._port&&(tg(this._port,"close"),t!==t.parent&&function(e){const t=e.match(/\bAppleWebKit\/([0-9]+)\b/);return!!t&&!(parseInt(t[1])<=537)}(e)&&t.parent.postMessage({type:"hypothesisPortClosed"},"*",[this._port]))})),this._pendingCalls=[],this._receivedCloseEvent=!1}on(e,t){if(this._port)throw new Error("Cannot add a method handler after a port is connected");this._methods.set(e,t)}connect(e){this._port=e,this._listeners.add(e,"message",(e=>this._handle(e))),e.start(),tg(e,"connect");for(let[e,t]of this._pendingCalls)this.call(e,...t);this._pendingCalls=[]}destroy(){this._port&&(tg(this._port,"close"),this._port.close()),this._destroyed=!0,this._listeners.removeAll()}call(e,...t){if(this._port||this._pendingCalls.push([e,t]),!this._port||this._destroyed)return;const n=this._sequence++,r=t[t.length-1];"function"==typeof r&&(this._callbacks.set(n,r),t=t.slice(0,-1)),tg(this._port,e,t,n)}_parseMessage({data:e}){
597
- return e&&"object"==typeof e?"frame-rpc"!==e.protocol||"1.0.0"!==e.version?null:Array.isArray(e.arguments)?e:null:null}_handle(e){const t=this._parseMessage(e),n=this._port;if(t&&n)if("method"in t){if("close"===t.method){if(this._receivedCloseEvent)return;this._receivedCloseEvent=!0}const e=this._methods.get(t.method);if(!e)return;const r=(...e)=>{const r={arguments:e,protocol:"frame-rpc",response:t.sequence,version:"1.0.0"};n.postMessage(r)};e(...t.arguments,r)}else if("response"in t){const e=this._callbacks.get(t.response);this._callbacks.delete(t.response),e&&e(...t.arguments)}}}function rg(e,t){var n;const r=null===(n=e.target[0].selector)||void 0===n?void 0:n.find((e=>"EPUBContentSelector"===e.type));return!r||Boolean(t.url&&r.url===t.url||t.cfi&&r.cfi&&Wm(r.cfi)===Wm(t.cfi))}function og(e,t,n,r){let o=t();return e((()=>{const e=t();if(r?r(e,o):e===o)return;const i=o;o=e,n(e,i)}))}function ig({$cluster:e,$tag:t,target:n,uri:r}){return{$cluster:e,$tag:t,target:n,uri:r}}function ag(e,t){var n
598
- ;const r=e.find((e=>e.uri===t.uri));if(r)return r;const o=e.find((e=>null===e.id));return o||(null!==(n=e[0])&&void 0!==n?n:null)}class sg{constructor(e,t,n){qi(this,"_annotationsService",void 0),qi(this,"_guestRPC",void 0),qi(this,"_highlightsVisible",void 0),qi(this,"_hostRPC",void 0),qi(this,"_inFrame",void 0),qi(this,"_listeners",void 0),qi(this,"_portFinder",void 0),qi(this,"_store",void 0),qi(this,"_pendingScrollToTag",void 0),qi(this,"_pendingHoverTag",void 0),qi(this,"_pendingAnchorStatusUpdates",void 0),qi(this,"_scheduleAnchorStatusUpdate",void 0),qi(this,"_window",void 0),this._window=e,this._annotationsService=t,this._store=n,this._portFinder=new Qf({hostFrame:this._window.parent,source:"sidebar"}),this._listeners=new $i,this._hostRPC=new ng,this._guestRPC=new Map,this._inFrame=new Set,this._highlightsVisible=!1,this._pendingScrollToTag=null,this._pendingHoverTag=null,this._pendingAnchorStatusUpdates=new Map,this._scheduleAnchorStatusUpdate=ji((()=>{
588
+ return this._routeCache||(this._routeCache=Gf(this._apiURL).then((e=>e.links))),this._routeCache}links(){return this._linkCache||(this._linkCache=this.routes().then((async e=>{const t=e.links;return await Gf(t.url)}))),this._linkCache}}Vf.$inject=["settings"];class Yf extends Error{constructor(e,t){super(e),qi(this,"cause",void 0),this.cause=t}}class Wf{constructor(e){qi(this,"clientId",void 0),qi(this,"tokenEndpoint",void 0),qi(this,"authorizationEndpoint",void 0),qi(this,"revokeEndpoint",void 0),this.clientId=e.clientId,this.tokenEndpoint=e.tokenEndpoint,this.authorizationEndpoint=e.authorizationEndpoint,this.revokeEndpoint=e.revokeEndpoint}exchangeAuthCode(e){return this._getAccessToken({client_id:this.clientId,grant_type:"authorization_code",code:e})}exchangeGrantToken(e){return this._getAccessToken({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e})}refreshToken(e){return this._getAccessToken({grant_type:"refresh_token",refresh_token:e})}async revokeToken(e){try{
589
+ await this._formPost(this.revokeEndpoint,{token:e})}catch(e){throw new Yf("Failed to revoke access token",e)}}authorize(e){const t=bf(16),n=new Promise(((n,r)=>{e.addEventListener("message",(function o(i){if("object"!=typeof i.data)return;const a=i.data;a.state===t&&("authorization_response"===a.type&&n(i.data),"authorization_canceled"===a.type&&r(new Error("Authorization window was closed")),e.removeEventListener("message",o))}))})),r=new URL(this.authorizationEndpoint);r.searchParams.set("client_id",this.clientId),r.searchParams.set("origin",e.location.origin),r.searchParams.set("response_mode","web_message"),r.searchParams.set("response_type","code"),r.searchParams.set("state",t);const o=`left=${e.screen.width/2-237.5},top=${e.screen.height/2-215},width=475,height=430`;if(!e.open(r.toString(),"Log in to Hypothesis",o))throw new Error("Failed to open login window");return n.then((e=>e.code))}async _formPost(e,t){const n=new URLSearchParams;for(const[e,r]of Object.entries(t))n.set(e,r);n.sort();return Of(e,{
590
+ method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()})}async _getAccessToken(e){let t;try{t=await this._formPost(this.tokenEndpoint,e)}catch(e){throw new Yf("Failed to fetch access token",e)}return{accessToken:t.access_token,expiresAt:Date.now()+1e3*(t.expires_in-10),refreshToken:t.refresh_token}}}class Kf extends Tp{constructor(e,t,n,r,o){super(),qi(this,"_authCode",void 0),qi(this,"_client",void 0),qi(this,"_tokenInfoPromise",void 0),qi(this,"_apiRoutes",void 0),qi(this,"_localStorage",void 0),qi(this,"_settings",void 0),qi(this,"_toastMessenger",void 0),qi(this,"_window",void 0),this._authCode=null,this._client=null,this._tokenInfoPromise=null,this._apiRoutes=t,this._localStorage=n,this._settings=r,this._toastMessenger=o,this._window=e,this._listenForTokenStorageEvents()}_listenForTokenStorageEvents(){this._window.addEventListener("storage",(({key:e})=>{e===this._storageKey()&&(this._tokenInfoPromise=null,this.emit("oauthTokensChanged"))}))}_loadToken(){
591
+ const e=this._localStorage.getObject(this._storageKey());return e&&"string"==typeof e.accessToken&&"string"==typeof e.refreshToken&&"number"==typeof e.expiresAt?{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}:null}async _oauthClient(){if(this._client)return this._client;const e=await this._apiRoutes.links();var t,n;return this._client=new Wf({clientId:this._settings.oauthClientId,authorizationEndpoint:e["oauth.authorize"],revokeEndpoint:e["oauth.revoke"],tokenEndpoint:(t="token",n=this._settings.apiUrl,new URL(t,n).href)}),this._client}async _exchangeAuthCodeForToken(e){const t=await this._oauthClient(),n=await t.exchangeAuthCode(e);return this._saveToken(n),n}async _exchangeGrantToken(e){const t=await this._oauthClient();try{return await t.exchangeGrantToken(e)}catch(e){throw this._toastMessenger.error("Hypothesis login lost: You must reload the page to annotate.",{autoDismiss:!1}),e}}_getGrantToken(){var e;return null===(e=Kn(this._settings))||void 0===e?void 0:e.grantToken}
592
+ _storageKey(){let e=new URL(this._settings.apiUrl).hostname;return e=e.replace(/\./g,"%2E"),`hypothesis.oauth.${e}.token`}_saveToken(e){this._localStorage.setObject(this._storageKey(),e)}async _refreshAccessToken(e,t){const n=await this._oauthClient();let r;try{if(r=await n.refreshToken(e),Date.now()>r.expiresAt)throw new Error("Refreshed token expired in the past")}catch{return null}return t.persist&&this._saveToken(r),r}async getAccessToken(){if(!this._tokenInfoPromise){const e=this._getGrantToken();void 0!==e?this._tokenInfoPromise=e?this._exchangeGrantToken(e):Promise.resolve(null):this._authCode?(this._tokenInfoPromise=this._exchangeAuthCodeForToken(this._authCode),this._authCode=null):this._tokenInfoPromise=Promise.resolve(this._loadToken())}const e=this._tokenInfoPromise,t=await this._tokenInfoPromise;if(!t)return null;if(e!==this._tokenInfoPromise)return this.getAccessToken();if(Date.now()>t.expiresAt){const e=this._getGrantToken()
593
+ ;return this._tokenInfoPromise=this._refreshAccessToken(t.refreshToken,{persist:void 0===e}),this.getAccessToken()}return t.accessToken}async login(){const e=await this._oauthClient(),t=await e.authorize(this._window);this._authCode=t,this._tokenInfoPromise=null}async logout(){const[e,t]=await Promise.all([this._tokenInfoPromise,this._oauthClient()]);e&&await t.revokeToken(e.accessToken),this._tokenInfoPromise=null,this._localStorage.removeItem(this._storageKey())}}Kf.$inject=["$window","apiRoutes","localStorage","settings","toastMessenger"];class Xf{constructor(e,t,n){qi(this,"_annotationsService",void 0),qi(this,"_toastMessenger",void 0),qi(this,"_store",void 0),qi(this,"_saving",void 0),qi(this,"_failed",void 0),this._annotationsService=e,this._toastMessenger=t,this._store=n,this._saving=new Set,this._failed=new Set}init(){const e=e=>!this._saving.has(e)&&!this._failed.has(e);this._store.subscribe((()=>{this._store.newHighlights().forEach((t=>{const n=t.$tag;e(n)&&(this._saving.add(n),
594
+ $f((()=>this._annotationsService.save(t))).then((()=>{this._toastMessenger.success("Highlight saved",{visuallyHidden:!0})})).catch((()=>{this._failed.add(n)})).finally((()=>{this._saving.delete(n)})))}))}))}isSaving(){return this._saving.size>0}}function Zf(e){if(null===e||"object"!=typeof e)return!1;for(let t of["frame1","frame2","type","requestId"])if("string"!=typeof e[t])return!1;return!0}function Jf(e,t){return!!Zf(e)&&JSON.stringify(e,Object.keys(t).sort())===JSON.stringify(t,Object.keys(t).sort())}Xf.$inject=["annotationsService","toastMessenger","store"];class Qf{constructor({hostFrame:e,source:t,sourceId:n}){this._hostFrame=e,this._source=t,this._sourceId=n,this._listeners=new $i}destroy(){this._listeners.removeAll()}async discover(e){let t=!1;if(("guest"===this._source&&"host"===e||"guest"===this._source&&"sidebar"===e||"sidebar"===this._source&&"host"===e||"notebook"===this._source&&"sidebar"===e)&&(t=!0),!t)throw new Error("Invalid request of channel/port");const n=bf(6)
595
+ ;return new Promise(((t,r)=>{const o=()=>{this._hostFrame.postMessage({frame1:this._source,frame2:e,type:"request",requestId:n,sourceId:this._sourceId},"*")},i=setInterval(o,250),a=setTimeout((()=>{clearInterval(i),r(new Error(`Unable to establish ${this._source}-${e} communication channel`))}),2e4),s=this._listeners.add(window,"message",(r=>{const{data:o,ports:l}=r;Jf(o,{frame1:this._source,frame2:e,type:"offer",requestId:n})&&(clearInterval(i),clearTimeout(a),this._listeners.remove(s),t(l[0]))}));o()}))}}function eg(e){const t=t=>{const{data:n}=t;if(n&&"hypothesis-error"===(null==n?void 0:n.type)){const{context:t,error:r}=n;e(r instanceof Error?r:function(e){const t=new Error(e.message);return t.stack=e.stack,t}(r),t)}};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function tg(e,t,n=[],r=-1){e.postMessage({protocol:"frame-rpc",version:"1.0.0",arguments:n,method:t,sequence:r})}class ng{constructor({userAgent:e=navigator.userAgent,currentWindow:t=window}={}){
596
+ this._port=null,this._methods=new Map,this._sequence=1,this._callbacks=new Map,this._listeners=new $i,this._listeners.add(t,"unload",(()=>{this._port&&(tg(this._port,"close"),t!==t.parent&&function(e){const t=e.match(/\bAppleWebKit\/([0-9]+)\b/);return!!t&&!(parseInt(t[1])<=537)}(e)&&t.parent.postMessage({type:"hypothesisPortClosed"},"*",[this._port]))})),this._pendingCalls=[],this._receivedCloseEvent=!1}on(e,t){if(this._port)throw new Error("Cannot add a method handler after a port is connected");this._methods.set(e,t)}connect(e){this._port=e,this._listeners.add(e,"message",(e=>this._handle(e))),e.start(),tg(e,"connect");for(let[e,t]of this._pendingCalls)this.call(e,...t);this._pendingCalls=[]}destroy(){this._port&&(tg(this._port,"close"),this._port.close()),this._destroyed=!0,this._listeners.removeAll()}call(e,...t){if(this._port||this._pendingCalls.push([e,t]),!this._port||this._destroyed)return;const n=this._sequence++,r=t[t.length-1];"function"==typeof r&&(this._callbacks.set(n,r),t=t.slice(0,-1)),
597
+ tg(this._port,e,t,n)}_parseMessage({data:e}){return e&&"object"==typeof e?"frame-rpc"!==e.protocol||"1.0.0"!==e.version?null:Array.isArray(e.arguments)?e:null:null}_handle(e){const t=this._parseMessage(e),n=this._port;if(t&&n)if("method"in t){if("close"===t.method){if(this._receivedCloseEvent)return;this._receivedCloseEvent=!0}const e=this._methods.get(t.method);if(!e)return;const r=(...e)=>{const r={arguments:e,protocol:"frame-rpc",response:t.sequence,version:"1.0.0"};n.postMessage(r)};e(...t.arguments,r)}else if("response"in t){const e=this._callbacks.get(t.response);this._callbacks.delete(t.response),e&&e(...t.arguments)}}}function rg(e,t){var n;const r=null===(n=e.target[0].selector)||void 0===n?void 0:n.find((e=>"EPUBContentSelector"===e.type));return!r||Boolean(t.url&&r.url===t.url||t.cfi&&r.cfi&&Wm(r.cfi)===Wm(t.cfi))}function og(e,t,n,r){let o=t();return e((()=>{const e=t();if(r?r(e,o):e===o)return;const i=o;o=e,n(e,i)}))}function ig({$cluster:e,$tag:t,target:n,uri:r}){return{$cluster:e,$tag:t,
598
+ target:n,uri:r}}function ag(e,t){var n;const r=e.find((e=>e.uri===t.uri));if(r)return r;const o=e.find((e=>null===e.id));return o||(null!==(n=e[0])&&void 0!==n?n:null)}class sg{constructor(e,t,n){qi(this,"_annotationsService",void 0),qi(this,"_guestRPC",void 0),qi(this,"_highlightsVisible",void 0),qi(this,"_hostRPC",void 0),qi(this,"_inFrame",void 0),qi(this,"_listeners",void 0),qi(this,"_portFinder",void 0),qi(this,"_store",void 0),qi(this,"_pendingScrollToTag",void 0),qi(this,"_pendingHoverTag",void 0),qi(this,"_pendingAnchorStatusUpdates",void 0),qi(this,"_scheduleAnchorStatusUpdate",void 0),qi(this,"_window",void 0),this._window=e,this._annotationsService=t,this._store=n,this._portFinder=new Qf({hostFrame:this._window.parent,source:"sidebar"}),this._listeners=new $i,this._hostRPC=new ng,this._guestRPC=new Map,this._inFrame=new Set,this._highlightsVisible=!1,this._pendingScrollToTag=null,this._pendingHoverTag=null,this._pendingAnchorStatusUpdates=new Map,this._scheduleAnchorStatusUpdate=ji((()=>{
599
599
  const e=Object.fromEntries(this._pendingAnchorStatusUpdates.entries());this._store.updateAnchorStatus(e),this._pendingAnchorStatusUpdates.clear()}),10),this._setupSyncToGuests(),this._setupHostEvents(),this._setupFeatureFlagSync()}_setupSyncToGuests(){let e=0;const t=(t,n,r)=>{let o=0;const i=new Set,a=[];t.forEach((e=>{Dr(e)||(Fr(e)&&++o,i.add(e.$tag),this._inFrame.has(e.$tag)||a.push(e))}));const s=r.filter((e=>!i.has(e.$tag)));if(a.length>0){const e=new Map,t=[];for(const r of a){var l;const o=ag(n,r);if(!o||o.segment&&!rg(r,o.segment)){t.push(r.$tag);continue}const i=null!==(l=e.get(o.id))&&void 0!==l?l:[];i.push(r),e.set(o.id,i)}t.length>0&&this._updateAnchorStatus(t,"anchored");for(const[t,n]of e){const e=this._guestRPC.get(t);e&&e.call("loadAnnotations",n.map(ig))}a.forEach((e=>{this._inFrame.add(e.$tag)}))}s.forEach((e=>{this._guestRPC.forEach((t=>t.call("deleteAnnotation",e.$tag))),this._inFrame.delete(e.$tag)})),
600
600
  n.length>0&&n.every((e=>e.isAnnotationFetchComplete))&&(0!==o&&o===e||(this._hostRPC.call("publicAnnotationCountChanged",o),e=o))};og(this._store.subscribe,(()=>[this._store.allAnnotations(),this._store.frames()]),(([e,n],[r])=>t(e,n,r)),Fo),og(this._store.subscribe,(()=>this._store.getContentInfo()),(e=>{this._guestRPC.forEach((t=>{t.call("showContentInfo",e)}))}))}_updateAnchorStatus(e,t){const n=Array.isArray(e)?e:[e];for(const e of n)this._pendingAnchorStatusUpdates.set(e,t);this._scheduleAnchorStatusUpdate()}_connectGuest(e,t){const n=new ng;this._guestRPC.set(t,n),n.on("documentInfoChanged",(e=>{this._store.connectFrame({id:t,metadata:e.metadata,uri:e.uri,segment:e.segmentInfo,persistent:e.persistent})})),n.on("close",(()=>{const e=this._store.frames().find((e=>e.id===t));e&&!e.persistent&&this._store.destroyFrame(e),this._inFrame.clear(),n.destroy(),this._guestRPC.delete(t)})),n.on("createAnnotation",(e=>{if(!this._store.isLoggedIn())return this._hostRPC.call("openSidebar"),
601
601
  this._store.openSidebarPanel("loginPrompt"),void this._guestRPC.forEach((t=>t.call("deleteAnnotation",e.$tag)));this._inFrame.add(e.$tag),e.$highlight||this._hostRPC.call("openSidebar"),this._hostRPC.call("showHighlights"),this._annotationsService.create(e)})),n.on("syncAnchoringStatus",(({$tag:e,$orphan:t})=>{this._inFrame.add(e),this._updateAnchorStatus(e,t?"orphan":"anchored"),e===this._pendingHoverTag&&(this._pendingHoverTag=null,n.call("hoverAnnotations",[e])),this._pendingScrollToTag&&e===this._pendingScrollToTag&&(this._pendingScrollToTag=null,n.call("scrollToAnnotation",e))})),n.on("showAnnotations",((e,t=!1)=>{const n=this._store.findIDsForTags(e);this._store.selectAnnotations(n),this._store.selectTab("annotation"),n.length>0&&t&&(this._store.setAnnotationFocusRequest(n[0]),window.focus())})),n.on("hoverAnnotations",(e=>{this._store.hoverAnnotations(e||[])})),n.on("toggleAnnotationSelection",(e=>{this._store.toggleSelectedAnnotations(this._store.findIDsForTags(e))})),n.on("openSidebar",(()=>{
@@ -681,8 +681,8 @@ Ef("Error connecting to H push notification service:",t);const n=new URL(e).host
681
681
  }))}setConfig(e,t){var n;this._configMessages[e]=t,null!==(n=this._socket)&&void 0!==n&&n.isConnected()&&this._socket.send(t)}async _reconnect(){var e;const t=await this._websocketURL;if(!t)return;let n,r;null===(e=this._socket)||void 0===e||e.close();try{n=await this._auth.getAccessToken()}catch(e){throw console.error("Failed to fetch token for WebSocket authentication",e),e}if(n){const e=new URL(t);e.searchParams.set("access_token",n),r=e.toString()}else r=t;const o=new q_(r);o.on("open",(()=>{this._reconnectionAttempts=0,this._sendClientConfig(o)})),o.on("disconnect",(()=>{if(++this._reconnectionAttempts,this._reconnectionAttempts<10){const e=1e3*2**this._reconnectionAttempts;setTimeout((()=>this._reconnect()),e)}else console.error("Gave up trying to reconnect to Hypothesis real time update service")})),o.on("error",(e=>this._handleSocketError(t,e))),o.on("message",(e=>this._handleSocketMessage(e))),this._socket=o,this.setConfig("client-id",{messageType:"client_id",value:this.clientId}),
682
682
  this.setConfig("auth-check",{type:"whoami",id:1})}async connect(e={}){var t;this._updateImmediately=null===(t=e.applyUpdatesImmediately)||void 0===t||t,this._reconnectSetUp||(this._reconnectSetUp=!0,og(this._store.subscribe,(()=>this._store.profile().userid),(()=>this._reconnect()))),this._socket||await this._reconnect()}}$_.$inject=["store","apiRoutes","auth","groups","session"];class G_{constructor(e){this._storage=e}filter(e,t=null){const n=this._storage.getObject("hypothesis.user.tags.list")||[];let r=0;return n.filter((n=>{if(null!==t&&r>=t)return!1;const o=n.split(/\W+/),i=new RegExp(`^${Af(e)}`,"i");return!(!o.some((e=>e.match(i)))&&!n.match(i))&&(++r,!0)}))}store(e){const t=this._storage.getObject("hypothesis.user.tags.map")||{};e.forEach((e=>{t[e]?(t[e].count+=1,t[e].updated=Date.now()):t[e]={text:e,count:1,updated:Date.now()}})),this._storage.setObject("hypothesis.user.tags.map",t);const n=Object.keys(t).sort(((e,n)=>t[e].count!==t[n].count?t[n].count-t[e].count:e.localeCompare(n)))
683
683
  ;this._storage.setObject("hypothesis.user.tags.list",n)}}G_.$inject=["localStorage"];class V_{constructor(e){this._store=e}forceVisible(e){e.children.forEach((e=>{this.forceVisible(e)})),e.visible||this._store.setForcedVisible(e.id,!0)}}V_.$inject=["store"];class Y_{constructor(e,t){qi(this,"_store",void 0),qi(this,"_window",void 0),qi(this,"_delayedMessageQueue",void 0),this._store=e,this._window=t,this._delayedMessageQueue=[],this._window.addEventListener("focus",(()=>{this._delayedMessageQueue.forEach((({type:e,messageText:t,options:n})=>this._addMessage(e,t,n))),this._delayedMessageQueue=[]}))}dismiss(e){const t=this._store.getToastMessage(e);t&&!t.isDismissed&&(this._store.updateToastMessage({...t,isDismissed:!0}),setTimeout((()=>{this._store.removeToastMessage(e)}),500))}_addMessage(e,t,{autoDismiss:n=!0,moreInfoURL:r="",visuallyHidden:o=!1,delayed:i=!1}={}){if(this._store.hasToastMessage(e,t))return;if(i&&!this._window.document.hasFocus()){const i={autoDismiss:n,moreInfoURL:r,visuallyHidden:o}
684
- ;return void this._delayedMessageQueue.push({type:e,messageText:t,options:i})}const a=bf(10),s={type:e,id:a,message:t,moreInfoURL:r,visuallyHidden:o};this._store.addToastMessage({isDismissed:!1,...s}),n&&setTimeout((()=>{this.dismiss(a)}),5e3)}error(e,t){this._addMessage("error",e,t)}success(e,t){this._addMessage("success",e,t)}notice(e,t){this._addMessage("notice",e,t)}}Y_.$inject=["store","$window"];const W_=function(e){for(var t={},n=e.querySelectorAll("script.js-hypothesis-config"),r=0;r<n.length;r++){var o=void 0;try{o=JSON.parse(n[r].textContent||"")}catch(e){console.warn("Could not parse settings from js-hypothesis-config tags",e),o={}}Object.assign(t,o)}return t}(document),K_=function(e){const{version:t,origin:n}=yf(e.location.href);return"1.1234.0"!==t?(console.warn(`The Hypothesis sidebar is using a different version (1.1234.0) than the host page (${t}). It may not work.`),!1):"null"===e.origin?(console.warn("Hypothesis has been loaded in a sandboxed frame. This is not supported."),
685
- !1):e.origin===n||(console.warn(`The Hypothesis sidebar is running in a different origin (${e.origin}) than expected (${n}). It may not work.`),!1)}(window);function X_(e,t){e.setClientId(t.clientId)}function Z_(e,t,n){e.load(),t.load(),n.sync()}function J_(e,t,n){e.init(),t.init(),n.init()}function Q_(e,t){"sidebar"===t.route()&&e.connect()}W_.sentry&&K_&&function(e){const t=function(){let e=import.meta.url;return e?new URL(e).origin:null}(),n=t?[t]:void 0;P_({dsn:e.dsn,environment:e.environment,allowUrls:n,ignoreErrors:["Network request failed","Object Not Found Matching Id"],release:"1.1234.0",beforeSend:(e,t)=>{if(F_>=5)return Ef("Client-side Sentry quota reached. No further Sentry events will be sent"),null;++F_;try{const n=t&&t.originalException;n instanceof Event&&(e.extra||(e.extra={}),Object.assign(e.extra,{type:n.type,detail:n.detail,isTrusted:n.isTrusted}))}catch(e){}return e}});try{_b("host_config",yf(window.location.href))}catch(e){}
684
+ ;return void this._delayedMessageQueue.push({type:e,messageText:t,options:i})}const a=bf(10),s={type:e,id:a,message:t,moreInfoURL:r,visuallyHidden:o};this._store.addToastMessage({isDismissed:!1,...s}),n&&setTimeout((()=>{this.dismiss(a)}),5e3)}error(e,t){this._addMessage("error",e,t)}success(e,t){this._addMessage("success",e,t)}notice(e,t){this._addMessage("notice",e,t)}}Y_.$inject=["store","$window"];const W_=function(e){for(var t={},n=e.querySelectorAll("script.js-hypothesis-config"),r=0;r<n.length;r++){var o=void 0;try{o=JSON.parse(n[r].textContent||"")}catch(e){console.warn("Could not parse settings from js-hypothesis-config tags",e),o={}}Object.assign(t,o)}return t}(document),K_=function(e){const{version:t,origin:n}=yf(e.location.href);return"1.1235.0"!==t?(console.warn(`The Hypothesis sidebar is using a different version (1.1235.0) than the host page (${t}). It may not work.`),!1):"null"===e.origin?(console.warn("Hypothesis has been loaded in a sandboxed frame. This is not supported."),
685
+ !1):e.origin===n||(console.warn(`The Hypothesis sidebar is running in a different origin (${e.origin}) than expected (${n}). It may not work.`),!1)}(window);function X_(e,t){e.setClientId(t.clientId)}function Z_(e,t,n){e.load(),t.load(),n.sync()}function J_(e,t,n){e.init(),t.init(),n.init()}function Q_(e,t){"sidebar"===t.route()&&e.connect()}W_.sentry&&K_&&function(e){const t=function(){let e=import.meta.url;return e?new URL(e).origin:null}(),n=t?[t]:void 0;P_({dsn:e.dsn,environment:e.environment,allowUrls:n,ignoreErrors:["Network request failed","Object Not Found Matching Id"],release:"1.1235.0",beforeSend:(e,t)=>{if(F_>=5)return Ef("Client-side Sentry quota reached. No further Sentry events will be sent"),null;++F_;try{const n=t&&t.originalException;n instanceof Event&&(e.extra||(e.extra={}),Object.assign(e.extra,{type:n.type,detail:n.detail,isTrusted:n.isTrusted}))}catch(e){}return e}});try{_b("host_config",yf(window.location.href))}catch(e){}
686
686
  _b("loaded_scripts",Array.from(document.querySelectorAll("script")).filter((e=>!e.type||e.type.match(/javascript|module/))).map((e=>e.src||"<inline>"))),eg(((e,t)=>{bb(e,{tags:{context:t}})}))}(W_.sentry),function(e){e.addEventListener("click",(e=>{const t=e.target;if("A"===t.tagName){const e=t;"_blank"===e.target&&(e.rel="noopener")}}))}(document.body),X_.$inject=["api","streamer"],Z_.$inject=["groups","session","router"],J_.$inject=["autosaveService","persistedDefaults","serviceURL"],Q_.$inject=["frameSync","store"];const ey=document.querySelector("hypothesis-app");!function(e=window){e.addEventListener("message",zf)}(),async function(e,t=window){const n=function(e){const t=yf(e.location.href),n=["annotations","group","query","appType","openSidebar","showHighlights","services","branding","enableExperimentalNewNoteButton","focus","requestConfigFromFrame","theme","usernameUrl"],r={openSidebar:wf,requestConfigFromFrame:e=>{if("string"==typeof e)return e;const t=function(e){
687
687
  return"object"==typeof e&&null!==e?e:{}}(e);return{origin:kf(t.origin),ancestorLevel:xf(t.ancestorLevel)}}},o={};for(let[e,i]of Object.entries(t))n.includes(e)&&null!==i&&(r[e]?o[e]=r[e](i):o[e]=i);return o}(window),r=function(e,t){const n=e.requestConfigFromFrame;if(!n)return null;if("number"!=typeof n.ancestorLevel||"string"!=typeof n.origin)throw new Error("Improper `requestConfigFromFrame` object. Both `ancestorLevel` and `origin` need to be specified");return{targetFrame:Sf(n.ancestorLevel,t),origin:n.origin}}(n,t);let o;if(r){const e=await async function(e,t){return{...await _f(t.targetFrame,t.origin,"requestConfig",[],3e3),...e.group?{group:e.group}:{}}}(n,r);o=function(e,t){const n=e.services;return Array.isArray(n)?(n.forEach(((e,n)=>{"$rpc:requestGroups"===e.groups&&(e.groups=_f(t.targetFrame,t.origin,"requestGroups",[n],0).catch((()=>{throw new Error("Unable to fetch groups")})))})),e):e}(e,r)}else o=n;const i={...e,...o};return r&&(i.rpc=r),i.apiUrl=function(e){const t=Kn(e);if(t){
688
688
  if(t.apiUrl)return t.apiUrl;throw new Error("Service should contain an apiUrl value.")}return e.apiUrl}(i),i}(W_).then((e=>{!function(e,t){const n=new B;n.register("annotationsService",Lf).register("annotationActivity",If).register("api",Pf).register("apiRoutes",Vf).register("auth",Kf).register("autosaveService",Xf).register("frameSync",sg).register("groups",ug).register("loadAnnotationsService",dg).register("localStorage",mg).register("persistedDefaults",fg).register("router",gg).register("serviceURL",vg).register("session",U_).register("streamer",$_).register("streamFilter",j_).register("tags",G_).register("threadsService",V_).register("toastMessenger",Y_).register("store",{factory:Ni}),n.register("$window",{value:window}).register("settings",{value:e}),n.run(J_),n.run(X_),n.run(Z_),n.run(Mf),n.run(Q_),D(we(Jn.Provider,{value:n,children:we(ff,{})}),t)}(e,ey)})).catch((e=>function(e,t){console.error("Failed to start Hypothesis client: ",e),D(we(gf,{error:e}),t)}(e,ey)));