hypothesis 1.1407.0 → 1.1408.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?d28af4","styles/annotator.css":"styles/annotator.css?51e5f8","styles/annotator.css.map":"styles/annotator.css.map?dcd4af","styles/highlights.css":"styles/highlights.css?6b4ebd","styles/highlights.css.map":"styles/highlights.css.map?241350","styles/katex.min.css":"styles/katex.min.css?e179ab","styles/katex.min.css.map":"styles/katex.min.css.map?cd8c0e","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?0a77f3","styles/sidebar.css.map":"styles/sidebar.css.map?ddd0f6","styles/ui-playground.css":"styles/ui-playground.css?53b0d1","styles/ui-playground.css.map":"styles/ui-playground.css.map?96dc88","scripts/sidebar.bundle.js":"scripts/sidebar.bundle.js?8e6446","scripts/ui-playground.bundle.js":"scripts/ui-playground.bundle.js?75d664","scripts/annotator.bundle.js.map":"scripts/annotator.bundle.js.map?b0371d","scripts/ui-playground.bundle.js.map":"scripts/ui-playground.bundle.js.map?e54f16","scripts/sidebar.bundle.js.map":"scripts/sidebar.bundle.js.map?71fc60"};function t(s){s.setAttribute("data-hypothesis-asset","")}function e(s,e){var n=s.createElement("link");n.rel="stylesheet",n.type="text/css",n.href=e,t(n),s.head.appendChild(n)}function n(s,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.esModule,o=void 0===r||r,i=n.forceReload,a=void 0!==i&&i,l=s.createElement("script");o&&(l.type="module"),a&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,t(l),s.head.appendChild(l)}function r(s,e,n,r){var o=s.createElement("link");o.rel=e,o.href=r,o.type="application/annotator+".concat(n),t(o),s.head.appendChild(o)}function o(s,e,n){var r=s.createElement("link");r.rel="preload",r.as=e,r.href=n,"fetch"===e&&(r.crossOrigin="anonymous"),t(r),s.head.appendChild(r)}function i(s,t){return s.assetRoot+"build/"+s.manifest[t]}function a(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=function(){var s,t,e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:document).currentScript;return e?(s=e.src,(t=s.match(/(https?):\/\/([^:/]+)/))?{protocol:t[1],hostname:t[2]}:null):null}(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 l=function(s){for(var t={},e=s.querySelectorAll("script.js-hypothesis-config"),n=0;n<e.length;n++){var r=void 0;try{r=JSON.parse(e[n].textContent||"")}catch(s){console.warn("Could not parse settings from js-hypothesis-config tags",s),r={}}Object.assign(t,r)}return t}(document),c=a(l.assetRoot||"https://cdn.hypothes.is/hypothesis/1.1407.0/");if(document.querySelector("hypothesis-app")){!function(s,t){o(s,"fetch",t.apiUrl),o(s,"fetch",t.apiUrl+"links");for(var r=0,a=["scripts/sidebar.bundle.js"];r<a.length;r++)n(s,i(t,a[r]),{esModule:!0});for(var l=0,c=["styles/katex.min.css","styles/sidebar.css"];l<c.length;l++)e(s,i(t,c[l]))}(document,{assetRoot:c,manifest:s,apiUrl:l.apiUrl})}else{var p=function(){var s;return null===(s=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window).chrome)||void 0===s||null===(s=s.runtime)||void 0===s?void 0:s.id}();if(p&&!function(s){return!!(arguments.length>1&&void 0!==arguments[1]?arguments[1]:document).querySelector("script.js-hypothesis-config[data-extension-id=".concat(s,"]"))}(p))throw new Error("Could not start Hypothesis extension as configuration is missing");var d=l,u=a(d.notebookAppUrl||"https://hypothes.is/notebook"),h=a(d.profileAppUrl||"https://hypothes.is/user-profile"),y=a(d.sidebarAppUrl||"https://hypothes.is/app.html");!function(s,t){if(!s.querySelector('link[type="application/annotator+html"]')){r(s,"sidebar","html",t.sidebarAppUrl),r(s,"notebook","html",t.notebookAppUrl),r(s,"profile","html",t.profileAppUrl),o(s,"style",i(t,"styles/annotator.css")),r(s,"hypothesis-client","javascript",t.assetRoot+"build/boot.js");for(var a=0,l=["scripts/annotator.bundle.js"];a<l.length;a++)n(s,i(t,l[a]),{esModule:!1});var c=[];void 0!==window.PDFViewerApplication&&c.push("styles/pdfjs-overrides.css"),c.push("styles/highlights.css");for(var p=0,d=c;p<d.length;p++)e(s,i(t,d[p]))}}(document,{assetRoot:c,manifest:s,notebookAppUrl:u,profileAppUrl:h,sidebarAppUrl:y})}}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?7d8021","styles/annotator.css":"styles/annotator.css?51e5f8","styles/annotator.css.map":"styles/annotator.css.map?dcd4af","styles/highlights.css":"styles/highlights.css?6b4ebd","styles/highlights.css.map":"styles/highlights.css.map?241350","styles/katex.min.css":"styles/katex.min.css?e179ab","styles/katex.min.css.map":"styles/katex.min.css.map?cd8c0e","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?0a77f3","styles/sidebar.css.map":"styles/sidebar.css.map?ddd0f6","styles/ui-playground.css":"styles/ui-playground.css?53b0d1","styles/ui-playground.css.map":"styles/ui-playground.css.map?96dc88","scripts/sidebar.bundle.js":"scripts/sidebar.bundle.js?c78058","scripts/ui-playground.bundle.js":"scripts/ui-playground.bundle.js?75d664","scripts/annotator.bundle.js.map":"scripts/annotator.bundle.js.map?b0371d","scripts/ui-playground.bundle.js.map":"scripts/ui-playground.bundle.js.map?e54f16","scripts/sidebar.bundle.js.map":"scripts/sidebar.bundle.js.map?6b41bb"};function t(s){s.setAttribute("data-hypothesis-asset","")}function e(s,e){var n=s.createElement("link");n.rel="stylesheet",n.type="text/css",n.href=e,t(n),s.head.appendChild(n)}function n(s,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.esModule,o=void 0===r||r,i=n.forceReload,a=void 0!==i&&i,l=s.createElement("script");o&&(l.type="module"),a&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,t(l),s.head.appendChild(l)}function r(s,e,n,r){var o=s.createElement("link");o.rel=e,o.href=r,o.type="application/annotator+".concat(n),t(o),s.head.appendChild(o)}function o(s,e,n){var r=s.createElement("link");r.rel="preload",r.as=e,r.href=n,"fetch"===e&&(r.crossOrigin="anonymous"),t(r),s.head.appendChild(r)}function i(s,t){return s.assetRoot+"build/"+s.manifest[t]}function a(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=function(){var s,t,e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:document).currentScript;return e?(s=e.src,(t=s.match(/(https?):\/\/([^:/]+)/))?{protocol:t[1],hostname:t[2]}:null):null}(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 l=function(s){for(var t={},e=s.querySelectorAll("script.js-hypothesis-config"),n=0;n<e.length;n++){var r=void 0;try{r=JSON.parse(e[n].textContent||"")}catch(s){console.warn("Could not parse settings from js-hypothesis-config tags",s),r={}}Object.assign(t,r)}return t}(document),c=a(l.assetRoot||"https://cdn.hypothes.is/hypothesis/1.1408.0/");if(document.querySelector("hypothesis-app")){!function(s,t){o(s,"fetch",t.apiUrl),o(s,"fetch",t.apiUrl+"links");for(var r=0,a=["scripts/sidebar.bundle.js"];r<a.length;r++)n(s,i(t,a[r]),{esModule:!0});for(var l=0,c=["styles/katex.min.css","styles/sidebar.css"];l<c.length;l++)e(s,i(t,c[l]))}(document,{assetRoot:c,manifest:s,apiUrl:l.apiUrl})}else{var p=function(){var s;return null===(s=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window).chrome)||void 0===s||null===(s=s.runtime)||void 0===s?void 0:s.id}();if(p&&!function(s){return!!(arguments.length>1&&void 0!==arguments[1]?arguments[1]:document).querySelector("script.js-hypothesis-config[data-extension-id=".concat(s,"]"))}(p))throw new Error("Could not start Hypothesis extension as configuration is missing");var d=l,u=a(d.notebookAppUrl||"https://hypothes.is/notebook"),h=a(d.profileAppUrl||"https://hypothes.is/user-profile"),y=a(d.sidebarAppUrl||"https://hypothes.is/app.html");!function(s,t){if(!s.querySelector('link[type="application/annotator+html"]')){r(s,"sidebar","html",t.sidebarAppUrl),r(s,"notebook","html",t.notebookAppUrl),r(s,"profile","html",t.profileAppUrl),o(s,"style",i(t,"styles/annotator.css")),r(s,"hypothesis-client","javascript",t.assetRoot+"build/boot.js");for(var a=0,l=["scripts/annotator.bundle.js"];a<l.length;a++)n(s,i(t,l[a]),{esModule:!1});var c=[];void 0!==window.PDFViewerApplication&&c.push("styles/pdfjs-overrides.css"),c.push("styles/highlights.css");for(var p=0,d=c;p<d.length;p++)e(s,i(t,d[p]))}}(document,{assetRoot:c,manifest:s,notebookAppUrl:u,profileAppUrl:h,sidebarAppUrl:y})}}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?d28af4",
2
+ "scripts/annotator.bundle.js": "scripts/annotator.bundle.js?7d8021",
3
3
  "styles/annotator.css": "styles/annotator.css?51e5f8",
4
4
  "styles/annotator.css.map": "styles/annotator.css.map?dcd4af",
5
5
  "styles/highlights.css": "styles/highlights.css?6b4ebd",
@@ -12,9 +12,9 @@
12
12
  "styles/sidebar.css.map": "styles/sidebar.css.map?ddd0f6",
13
13
  "styles/ui-playground.css": "styles/ui-playground.css?53b0d1",
14
14
  "styles/ui-playground.css.map": "styles/ui-playground.css.map?96dc88",
15
- "scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?8e6446",
15
+ "scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?c78058",
16
16
  "scripts/ui-playground.bundle.js": "scripts/ui-playground.bundle.js?75d664",
17
17
  "scripts/annotator.bundle.js.map": "scripts/annotator.bundle.js.map?b0371d",
18
18
  "scripts/ui-playground.bundle.js.map": "scripts/ui-playground.bundle.js.map?e54f16",
19
- "scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?71fc60"
19
+ "scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?6b41bb"
20
20
  }
@@ -138,7 +138,7 @@ const e=this.anchors.find((e=>e.annotation.$tag===t));null!=e&&e.highlights&&awa
138
138
  this._sendDocumentInfo()}destroy(){var t;this._portFinder.destroy(),this._hostRPC.destroy(),this._sidebarRPC.destroy(),this._listeners.removeAll(),this._selectionObserver.disconnect(),this._adder.destroy(),this._bucketBarClient.destroy(),null===(t=this._clusterToolbar)||void 0===t||t.destroy(),function(t){Gn(Array.from(t.querySelectorAll("hypothesis-highlight")))}(this.element),this._integration.destroy()}async anchor(t){this._contentReady&&(await this._contentReady,this._contentReady=void 0);const e=t=>{var e;const n=cr(t);if(!n)return;const i=Xn(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)&&Kn(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{
139
139
  const i=await this._integration.anchor(this.element,e.selector),o=Bn.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&&Gn(e.highlights);this._updateAnchors(n,e)}_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,o=(await Promise.all(e.map((t=>this._integration.describe(i,t))))).map((t=>({source:n.uri,selector:t}))),r={uri:n.uri,document:n.metadata,target:o,
140
140
  $highlight:t,$cluster:t?"user-highlights":"user-annotations",$tag:"a:"+s(8)};return this._sidebarRPC.call("createAnnotation",r),this.anchor(r),hr(),r}_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);Kn(e.highlights,n)}this._sidebarRPC.call("hoverAnnotations",t)}_onSelection(t){const e=this._integration.getAnnotatableRange(t);if(!e)return void this._onClearSelection();const n=document.getSelection(),i=Un(n),o=zn(n);o?(this.selectedRanges=[e],this._hostRPC.call("textSelected"),this._adder.annotationsForSelection=ar(),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}={}){
141
- e?this._sidebarRPC.call("toggleAnnotationSelection",t):this._sidebarRPC.call("showAnnotations",t,n),this._sidebarRPC.call("openSidebar")}setHighlightsVisible(t,e=!0){!function(t,e){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._sidebarLayout=t,this._integration.fitSideBySide(t)}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){oe(t,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}}function fr(t,e){const n=new URL(t),i=new URLSearchParams;return i.append("config",JSON.stringify(e)),n.hash=i.toString(),n.toString()}function pr(t,e){var n;const i={};for(const[t,n]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=n&&(i[t]=n);i.origin=new URL(t).origin,i.version="1.1407.0";const o=new URL(window.location.href);if(o.hash="",i.hostURL=o.toString(),
141
+ e?this._sidebarRPC.call("toggleAnnotationSelection",t):this._sidebarRPC.call("showAnnotations",t,n),this._sidebarRPC.call("openSidebar")}setHighlightsVisible(t,e=!0){!function(t,e){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._sidebarLayout=t,this._integration.fitSideBySide(t)}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){oe(t,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}}function fr(t,e){const n=new URL(t),i=new URLSearchParams;return i.append("config",JSON.stringify(e)),n.hash=i.toString(),n.toString()}function pr(t,e){var n;const i={};for(const[t,n]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=n&&(i[t]=n);i.origin=new URL(t).origin,i.version="1.1408.0";const o=new URL(window.location.href);if(o.hash="",i.hostURL=o.toString(),
142
142
  Array.isArray(i.services)&&(null===(n=i.services)||void 0===n?void 0:n.length)>0){const t=i.services[0];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 mr({config:t,groupId:e}){return _e("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allowFullScreen:!0,src:fr(t.notebookAppUrl,{...pr(t.notebookAppUrl,t),group:e})})}function gr({eventBus:t,config:e}){const[n,i]=Wt(0),[o,r]=Wt(!0),[s,a]=Wt(null),l=jt(""),c=jt(null);zt((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),zt((()=>{document.body.style.overflow=o?l.current:"hidden"}),[o]),zt((()=>{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:_e("div",{
143
143
  className:me("fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50",{hidden:o}),"data-testid":"notebook-outer",children:_e("div",{className:"relative w-full h-full","data-testid":"notebook-inner",children:[_e("div",{className:"absolute right-0 m-3",children:_e(nn,{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:_e(Ne,{className:"w-4 h-4"})})}),_e(mr,{config:e,groupId:s},n)]})})}class _r{constructor(t,e,n){i(this,"_outerContainer",void 0),i(this,"_shadowRoot",void 0),this._outerContainer=document.createElement("hypothesis-notebook"),t.appendChild(this._outerContainer),this._shadowRoot=Sn(this._outerContainer),Tt(_e(gr,{eventBus:e,config:n}),this._shadowRoot)}destroy(){Tt(null,this._shadowRoot),this._outerContainer.remove()}}function vr({eventBus:t,config:e}){const[n,i]=Wt(!0),o=jt(null);zt((()=>{const e=t.createEmitter();return e.subscribe("openProfile",(()=>{
144
144
  i(!1)})),o.current=e,()=>{e.destroy()}}),[t]);return n?null:_e("div",{className:"fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50","data-testid":"profile-outer",children:_e("div",{className:"relative w-full h-full","data-testid":"profile-inner",children:[_e("div",{className:"absolute right-0 m-3",children:_e(nn,{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:_e(Ne,{className:"w-4 h-4"})})}),_e("iframe",{title:"Hypothesis profile",className:"h-full w-full border-0",src:e.profileAppUrl})]})})}class br{constructor(t,e,n){i(this,"_outerContainer",void 0),i(this,"shadowRoot",void 0),this._outerContainer=document.createElement("hypothesis-profile"),t.appendChild(this._outerContainer),this.shadowRoot=Sn(this._outerContainer),Tt(_e(vr,{eventBus:e,config:n}),this.shadowRoot)}destroy(){Tt(null,this.shadowRoot),this._outerContainer.remove()}}var yr={exports:{}}
@@ -552,7 +552,7 @@ const n=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);return n?n.map(sf).filter((e=>
552
552
  const a=null!==(n=o.position)&&void 0!==n?n:Number.MAX_SAFE_INTEGER,s=null!==(r=i.position)&&void 0!==r?r:Number.MAX_SAFE_INTEGER;return Math.sign(a-s)}};const pf=function(e){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:mf[t.sortKey]},r=!!t.filterQuery||Object.keys(t.filters).length>0;if(r){const e=function(e,t={}){const n=e=>{const n=t[e];return"string"==typeof n?[n]:[]},r=n("cfi"),o=n("page"),i=n("quote"),a=n("tag"),s=n("text"),l=n("uri"),c=n("user"),u=[],d=[],h=lf(e,rf);for(const e of h){const t=e.slice(0,e.indexOf(":")),n=e.slice(t.length+1);switch(t){case"cfi":r.push(n);break;case"quote":i.push(n);break;case"page":o.push(n);break;case"since":{const t=86400,n={sec:1,min:60,hour:3600,day:t,week:7*t,month:30*t,year:365*t
553
553
  },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";d.push(e*n[t])}}break;case"tag":a.push(n);break;case"text":s.push(n);break;case"uri":l.push(n);break;case"user":c.push(n);break;default:u.push(e)}}return{any:{terms:u,operator:"and"},cfi:{terms:r,operator:"or"},quote:{terms:i,operator:"and"},page:{terms:o,operator:"or"},since:{terms:d,operator:"and"},tag:{terms:a,operator:"and"},text:{terms:s,operator:"and"},uri:{terms:l,operator:"or"},user:{terms:c,operator:"or"}}}(t.filterQuery||"",t.filters);n.filterFn=t=>function(e,t){const n=(e,t)=>new Qp(t,nf[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 ef("or",e.map((e=>n(e,t))))))}else r=t.terms.map((t=>n(e,t)));return new ef(t.operator,r)})),o=new ef("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=>{
554
554
  return!!e.annotation&&(n=e.annotation,r=t.selectedTab,!Oo(n)&&uf(n)===r);var n,r}),Yp(e.annotations,n)}));function ff(){const e=Aa(),t=e.allAnnotations(),n=e.filterQuery(),r=e.route(),o=e.selectionState(),i=e.getFilterValues(),a=de((()=>({annotations:t,route:r,selection:{...o,filterQuery:n,filters:i}})),[t,n,r,o,i]);return pf(a)}var gf=Wr((function({loadAnnotationsService:e,onLogin:t}){var n;const r=Aa(),o=null!==(n=r.routeParams().id)&&void 0!==n?n:"",i=ff(),a=r.profile().userid,[s,l]=ae(!1);return le((()=>{l(!1),r.clearAnnotations(),e.loadThread(o).then((e=>{const t=e.filter((e=>0===(e.references||[]).length))[0];t&&(e.forEach((e=>e.id&&r.setExpanded(e.id,!0))),t.id!==o&&r.highlightAnnotations([o]))})).catch((()=>{l(!0)}))}),[o,a,e,r]),Re(v,{children:[s&&Re(Ea,{errorType:"annotation",onLoginRequest:t}),Re(Fp,{threads:i.children})]})}),["loadAnnotationsService"]);class vf{constructor(e,t,n=window){var r,o,i;H(this,"version",void 0),H(this,"userAgent",void 0),H(this,"urls",void 0),
555
- H(this,"fingerprint",void 0),H(this,"account",void 0),H(this,"timestamp",void 0),H(this,"segment",void 0);const a="N/A";let s=a;e.userid&&(s=e.userid,e.displayName&&(s=`${e.displayName} (${s})`)),this.version="1.1407.0",this.userAgent=n.navigator.userAgent,this.urls=t.map((e=>e.uri)).join(", ")||a,this.fingerprint=null!==(r=null===(o=t[0])||void 0===o||null===(o=o.metadata)||void 0===o?void 0:o.documentFingerprint)&&void 0!==r?r:a,this.account=s,this.timestamp=(new Date).toString();const l=null===(i=t[0])||void 0===i?void 0:i.segment;if(l){const e=[];l.cfi&&e.push(["CFI",l.cfi]),l.url&&e.push(["URL",l.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())}}var bf="complete",_f="canceled";function yf(e,t,n){
555
+ H(this,"fingerprint",void 0),H(this,"account",void 0),H(this,"timestamp",void 0),H(this,"segment",void 0);const a="N/A";let s=a;e.userid&&(s=e.userid,e.displayName&&(s=`${e.displayName} (${s})`)),this.version="1.1408.0",this.userAgent=n.navigator.userAgent,this.urls=t.map((e=>e.uri)).join(", ")||a,this.fingerprint=null!==(r=null===(o=t[0])||void 0===o||null===(o=o.metadata)||void 0===o?void 0:o.documentFingerprint)&&void 0!==r?r:a,this.account=s,this.timestamp=(new Date).toString();const l=null===(i=t[0])||void 0===i?void 0:i.segment;if(l){const e=[];l.cfi&&e.push(["CFI",l.cfi]),l.url&&e.push(["URL",l.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())}}var bf="complete",_f="canceled";function yf(e,t,n){
556
556
  e.self===e?e.scrollTo(t,n):(e.scrollLeft=t,e.scrollTop=n)}function wf(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,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,
557
557
  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 yf(e,r.x,r.y),e._scrollSettings=null,t.end(bf);var a=1-t.ease(i);if(yf(e,r.x-r.differenceX*a,r.y-r.differenceY*a),o>=t.time)return t.endIterations++,t.scrollAncestor&&wf(t.scrollAncestor),void wf(e);!function(e){if("requestAnimationFrame"in window)return window.requestAnimationFrame(e);setTimeout(e,16)}(wf.bind(null,e))}}function xf(e){return e.self===e}function kf(e){return"pageXOffset"in e||(e.scrollHeight!==e.clientHeight||e.scrollWidth!==e.clientWidth)&&"hidden"!==getComputedStyle(e).overflow}function Nf(){return!0}function Sf(e){if(e.assignedSlot)return Sf(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 Af=function(e,t,n){if(e){"function"==typeof t&&(n=t,t=null),t||(t={}),
558
558
  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=Sf(e),o=1,i=t.validTarget||Nf,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,kf):kf(r))&&(o++,s.push(r)),!(r=Sf(r))){l(bf);break}return s.reduce(((n,r,o)=>function(e,t,n,r,o){var i,a=!t._scrollSettings,s=t._scrollSettings,l=Date.now(),c={passive:!0};function u(e){t._scrollSettings=null,t.parentElement&&t.parentElement._scrollSettings&&t.parentElement._scrollSettings.end(e),n.debug&&console.log("Scrolling ended with type",e,"for",t),o(e),i&&(t.removeEventListener("touchstart",i,c),t.removeEventListener("wheel",i,c))}s&&s.end(_f);var d=n.maxSynchronousAlignments;return null==d&&(d=3),t._scrollSettings={startTime:l,endIterations:0,target:e,time:n.time,ease:n.ease,align:n.align,isWindow:n.isWindow||xf,maxSynchronousAlignments:d,
@@ -573,15 +573,15 @@ e instanceof Hf&&v(!0)},_=r.hasFetchedProfile();le((()=>{_&&t.connect({applyUpda
573
573
  title:"Too many results to show",children:[Re("p",{children:["This preview of the Notebook can show"," ",Re("strong",{children:["up to ",5e3," results"]})," at a time (there are"," ",c," to show here)."]}),Re("p",{children:[Re(Ir,{href:"mailto:support@hypothes.is?subject=Hypothesis%20Notebook&body=Please%20notify%20me%20when%20the%20Hypothesis%20Notebook%20is%20updated%20to%20support%20more%20than%205000%20annotations",underline:"always",children:"Contact us"})," ","if you would like to be notified when support for more annotations is available."]})]})}),Re(Yf,{currentPage:p,isLoading:l,onChangePage:y,threads:u.children})]})]})}),["loadAnnotationsService","streamer"]);function eg({classes:e,children:t,onClose:n=(()=>{}),...r}){return Re("div",{className:X("flex items-center gap-x-1 py-1 px-2 rounded","bg-green-success/10 animate-pulse-fade-out",e),onAnimationEnd:n,...r,children:[Re(ht,{className:"text-green-success w-em h-em p-[0.125em]"}),Re("div",{className:"text-sm",children:t})]})}function tg(){
574
574
  const e=Aa(),[t,n]=ae(!1),[r,o]=ae(0);if(le((()=>{let e;return t&&(e=setTimeout((()=>{n(!1),o((e=>e+1))}),1e3)),()=>{clearTimeout(e)}}),[t]),!e.isFeatureEnabled("client_user_profile"))return null;const i=r>0&&!t;return Re($e,{"data-testid":"profile-container",classes:"overflow-hidden",children:[Re("div",{className:X("h-12","px-3 border-b flex items-center"),children:[Re("div",{className:"grow",children:Re("h1",{className:"text-xl text-slate-7 font-normal",children:"Notifications"})}),Re("ul",{className:"sr-only","aria-live":"polite",children:i&&Re("li",{children:"Notification preferences saved"},r)}),r>0&&Re(eg,{onClose:()=>o(0),children:"Saved"},r)]}),Re(He,{children:Re(Ve,{size:"lg",children:Re(yr,{defaultChecked:!0,disabled:t,onChange:()=>n(!0),checkedIcon:t?Un:void 0,icon:t?Un:void 0,children:"Email me a daily summary of activity in my courses"})})})]})}function ng(e,t,n,r){const o=new Blob([e],{type:t}),i=URL.createObjectURL(o),a=r.createElement("a");a.setAttribute("href",i),a.setAttribute("download",n),
575
575
  a.style.visibility="hidden",r.body.appendChild(a),a.click(),r.body.removeChild(a),URL.revokeObjectURL(i)}function rg({annotations:e,getDisplayName:t,excludeReplies:n=!1}){const r=new Map;for(const o of e){if(n&&Mo(o))continue;let e=r.get(o.user);e||(e={userid:o.user,displayName:t(o),annotations:[]},r.set(o.user,e)),e.annotations.push(o)}const o=[...r.values()];return o.sort(((e,t)=>e.displayName.localeCompare(t.displayName))),o}function og(e){return`${e.getFullYear()}-${`${e.getMonth()+1}`.padStart(2,"0")}-${`${e.getDate()}`.padStart(2,"0")}`}function ig({documentMetadata:e,groupName:t,date:n=new Date}){const r=[og(n)];return null!=e&&e.title?r.push(function(e,t){const n=Array.from(e);return n.length<=t?e:n.slice(0,t).join("")}(e.title,50)):r.push("Hypothesis"),t&&r.push(t.replace(/ /g,"-")),r.join("-")}function ag(){return Re("div",{className:"flex flex-row items-center justify-center","data-testid":"loading-spinner",children:Re(hr,{size:"md"})})}function sg({userAnnotations:e}){return Re("div",{
576
- className:"flex gap-x-2",children:[e.displayName,Re("div",{className:"rounded px-1 bg-grey-7 text-white",children:e.annotations.length})]})}const lg=[{value:"json",name:"JSON"},{value:"txt",name:"Text"}];var cg=Wr((function({annotationsExporter:e,toastMessenger:t}){var n;const r=Aa(),o=r.focusedGroup(),i=o&&!r.isLoading(),a=r.defaultContentFrame(),s=r.savedAnnotations(),l=r.defaultAuthority(),c=r.isFeatureEnabled("client_display_names"),u=he((e=>ns(e,l,c)),[l,c]),d=de((()=>rg({annotations:s,getDisplayName:u})),[s,u]),h=r.profile(),m=h.userid,p=de((()=>({annotations:s,displayName:"All annotations"})),[s]),[f,g]=ae(null!==(n=d.find((e=>e.userid===m)))&&void 0!==n?n:p),b=r.isFeatureEnabled("export_formats"),[_,y]=ae(lg[0]),w=pe(),x=pe(),k=r.countDrafts(),N=de((()=>ig({documentMetadata:null==a?void 0:a.metadata,groupName:null==o?void 0:o.name})),[a,o]),[S,A]=ae();return i?Re("form",{className:"space-y-3",onSubmit:n=>{n.preventDefault();try{var r
577
- ;const t=_.value,n=null!==(r=null==f?void 0:f.annotations)&&void 0!==r?r:s,i=`${null!=S?S:N}.${t}`;switch(t){case"json":!function(e,t,n=document){const r=JSON.stringify(e,null,2);ng(r,"application/json",t,n)}(e.buildJSONExportContent(n,{profile:h}),i);break;case"txt":!function(e,t,n=document){ng(e,"text/plain",t,n)}(e.buildTextExportContent(n,{groupName:null==o?void 0:o.name,defaultAuthority:l,displayNamesEnabled:c}),i);break}}catch(n){t.error("Exporting annotations failed")}},"data-testid":"export-form",children:[s.length>0?Re(v,{children:[Re("p",{className:"text-color-text-light mb-3",children:[Re(Ir,{variant:"text-light",underline:"always",href:"https://web.hypothes.is/help/exporting-and-importing-annotations-in-the-hypothesis-web-app/",target:"_blank",children:"Learn more"})," ","about copying and exporting annotations."]}),Re("label",{"data-testid":"export-count",htmlFor:w,className:"font-medium",children:"Name of export file:"}),Re("div",{className:"flex",children:[Re(kr,{classes:"grow",
578
- "data-testid":"export-filename",id:w,defaultValue:N,value:S,onChange:e=>A(e.target.value),required:!0,maxLength:250}),b&&Re("div",{className:"grow-0 ml-2 min-w-[5rem]",children:Re(Cr,{value:_,onChange:y,buttonContent:_.name,"data-testid":"export-format-select",right:!0,children:lg.map((e=>Re(Cr.Option,{value:e,children:e.name},e.value)))})})]}),Re("label",{htmlFor:x,className:"block font-medium",children:["Select which user","'","s annotations to export:"]}),Re(Cr,{value:f,onChange:g,buttonId:x,buttonContent:Re(sg,{userAnnotations:f}),"data-testid":"user-select",children:[Re(Cr.Option,{value:p,children:Re(sg,{userAnnotations:p})}),d.map((e=>Re(Cr.Option,{value:e,children:Re(sg,{userAnnotations:e})},e.userid)))]})]}):Re("p",{"data-testid":"no-annotations-message",children:"There are no annotations available for export."}),k>0&&Re("p",{"data-testid":"drafts-message",children:["You have ",k," unsaved"," ",(E=k,T="draft",C="drafts",1===E?T:C),s.length>0&&Re(v,{children:" that will not be included"}),"."]
579
- }),Re(qe,{children:Re(Wn,{"data-testid":"export-button",variant:"primary",disabled:0===s.length,type:"submit",children:"Export"})})]}):Re(ag,{});var E,T,C}),["annotationsExporter","toastMessenger"]);function ug(e,t=new FileReader){const{promise:n,resolve:r,reject:o}=function(){let e,t;return{promise:new Promise(((n,r)=>{e=n,t=r})),resolve:e,reject:t}}();return t.addEventListener("loadend",(e=>{try{var t,n;const o=null!==(t=null===(n=e.target)||void 0===n||null===(n=n.result)||void 0===n?void 0:n.toString())&&void 0!==t?t:"",i=JSON.parse(o);r(i)}catch(e){o(e)}})),t.readAsText(e),n}function dg({size:e,value:t}){const n=e-4,r=Math.PI*n;return Re("span",{className:"text-grey-3",role:"progressbar","aria-valuenow":t,style:{width:`${e}px`,height:`${e}px`,transform:"rotate(-90deg)"},children:Re("svg",{viewBox:`0 0 ${e} ${e}`,children:Re("circle",{cx:e/2,cy:e/2,r:n/2,fill:"none",stroke:"currentColor","stroke-width":2,style:{strokeDasharray:r,strokeDashoffset:r-r*(t/100)+"px",transitionDuration:"300ms",
580
- transitionProperty:"stroke-dashoffset"}})})})}function hg({onFileSelected:e,disabled:t,id:n}){const r=ue(null),[o,i]=ae(null);return Re(Wn,{variant:"custom",classes:X("w-full relative overflow-hidden border rounded","bg-grey-0 hover:bg-grey-0"),title:o?`${o}, Select a file`:"Select a file",onClick:()=>{var e;return null===(e=r.current)||void 0===e?void 0:e.click()},disabled:t,"data-testid":"file-input-proxy-button",children:[Re("input",{ref:r,accept:".json",id:n,type:"file",disabled:t,className:"invisible absolute w-0 h-0","aria-hidden":!0,"data-testid":"file-input",onChange:t=>{var n,r;const o=t.target.files;i(null!==(n=null==o||null===(r=o[0])||void 0===r?void 0:r.name)&&void 0!==n?n:null),null!==o&&o.length>0&&e(o[0])}}),Re("div",{className:"max-w-full pr-10 truncate","data-testid":"filename-container",children:null!=o?o:"Select a file"}),Re("div",{className:"absolute right-0 h-full p-2 border-l bg-grey-2",children:Re(Ft,{})})]})}var mg=Wr((function({importAnnotationsService:e}){
581
- const[t,n]=ae(null),[r,o]=ae(null),[i,a]=ae(null),s=Aa(),l=s.profile().userid,c=s.defaultAuthority(),u=s.isFeatureEnabled("client_display_names"),d=he((e=>ns(e,c,u)),[c,u]),h=de((()=>r?rg({annotations:r,getDisplayName:d,excludeReplies:!0}):null),[r,d]),[m,p]=ae(null),f=de((()=>{var e;return null!==(e=null==h?void 0:h.find((e=>e.userid===m)))&&void 0!==e?e:null}),[m,h]);let g;le((()=>{l&&t&&(o(null),a(null),p(null),async function(e){let t;try{t=await ug(e)}catch(e){throw new Error("Not a valid JSON file")}if(null===(n=t)||"object"!=typeof n||!Array.isArray(t.annotations))throw new Error("Not a valid Hypothesis JSON file");var n;return t.annotations}(t).then((e=>{o(e);const t=e.some((e=>e.user===l));p(t?l:null)})).catch((e=>{a(e.message)})))}),[l,t]),f&&(g=async()=>{e.import(f.annotations)});const b=pe(),_=pe();if(!l)return Re("p",{"data-testid":"log-in-message",children:"You must log in to import annotations."})
582
- ;const y=Boolean(s.focusedGroup()&&s.defaultContentFrame()&&s.hasFetchedAnnotations()&&!s.isFetchingAnnotations()&&g),w=t&&!r&&!i,x=s.importsPending(),k=s.importsTotal(),N=k-x,S=w||x>0,A=x>0?Math.round(N/k*100):null;return Re(v,{children:[Re("p",{className:"text-color-text-light mb-3",children:[Re(Ir,{variant:"text-light",underline:"always",href:"https://web.hypothes.is/help/exporting-and-importing-annotations-in-the-hypothesis-web-app/",target:"_blank",children:"Learn more"})," ","about importing annotations."]}),Re("label",{htmlFor:b,className:"font-medium",children:"Select Hypothesis export file:"}),Re(hg,{onFileSelected:n,disabled:S,id:b}),h&&Re(v,{children:[Re("label",{htmlFor:_,className:"block font-medium",children:"Select which user's annotations to import:"}),Re(Cr,{value:f,onChange:e=>{var t;return p(null!==(t=null==e?void 0:e.userid)&&void 0!==t?t:null)},buttonId:_,buttonContent:f?Re(sg,{userAnnotations:f}):Re("span",{className:"text-grey-6",children:"Select a user..."}),
583
- children:h.map((e=>Re(Cr.Option,{value:e,children:Re(sg,{userAnnotations:e})},e.userid)))})]}),i&&Re("p",{"data-testid":"error-info",children:[Re("b",{children:"Unable to find annotations to import:"})," ",i]}),Re(qe,{children:[null!==A&&Re("span",{"data-testid":"progress-text",className:"text-grey-6",children:[A,"% complete"]}),Re(Wn,{"data-testid":"import-button",disabled:!y||S,onClick:g,variant:"primary",children:[null!==A&&Re(dg,{size:22,value:A}),"Import"]})]})]})}),["importAnnotationsService"]);var pg=Wr((function({toastMessenger:e}){const t=Aa(),n=t.mainFrame(),r=t.focusedGroup(),o=r&&n,i=o&&(a=n.uri,s=r.id,rs(a)?`https://hyp.is/go?url=${encodeURIComponent(a)}&group=${s}`:null);var a,s;const l=he((()=>{try{i&&(ds(i),e.success("Copied share link to clipboard"))}catch(t){e.error("Unable to copy link")}}),[i,e]);return o?Re("div",{className:"text-color-text-light space-y-3",children:i?Re(v,{children:[Re("div",{className:"text-color-text font-medium","data-testid":"sharing-intro",
584
- children:"private"===r.type?Re("p",{children:"Use this link to share these annotations with other group members:"}):Re("p",{children:"Use this link to share these annotations with anyone:"})}),Re("div",{children:Re(Xn,{children:[Re(kr,{"aria-label":"Use this URL to share these annotations",type:"text",value:i,readOnly:!0}),Re(Jn,{icon:yt,onClick:l,title:"Copy share link",variant:"dark"})]})}),Re("p",{"data-testid":"sharing-details",children:["private"===r.type?Re("span",{children:["Annotations in the private group ",Re("em",{children:r.name})," ","are only visible to group members."]}):Re("span",{children:["Anyone using this link may view the annotations in the group"," ",Re("em",{children:r.name}),"."]})," ",Re("span",{children:["Private (",Re(dn,{className:"inline w-em h-em ml-0.5 -mt-0.5"})," ",Re("em",{children:"Only Me"}),") annotations are only visible to you."]})]}),Re("div",{className:"text-[24px]",children:Re(ps,{shareURI:i})})]}):Re("p",{"data-testid":"no-sharing",
576
+ className:"flex gap-x-2",children:[e.displayName,Re("div",{className:"rounded px-1 bg-grey-7 text-white",children:e.annotations.length})]})}const lg=[{value:"json",name:"JSON"},{value:"txt",name:"Text"},{value:"csv",name:"CSV"}];var cg=Wr((function({annotationsExporter:e,toastMessenger:t}){var n;const r=Aa(),o=r.focusedGroup(),i=o&&!r.isLoading(),a=r.defaultContentFrame(),s=r.savedAnnotations(),l=r.defaultAuthority(),c=r.isFeatureEnabled("client_display_names"),u=he((e=>ns(e,l,c)),[l,c]),d=de((()=>rg({annotations:s,getDisplayName:u})),[s,u]),h=r.profile(),m=h.userid,p=de((()=>({annotations:s,displayName:"All annotations"})),[s]),[f,g]=ae(null!==(n=d.find((e=>e.userid===m)))&&void 0!==n?n:p),b=r.isFeatureEnabled("export_formats"),[_,y]=ae(lg[0]),w=pe(),x=pe(),k=r.countDrafts(),N=de((()=>ig({documentMetadata:null==a?void 0:a.metadata,groupName:null==o?void 0:o.name})),[a,o]),[S,A]=ae();return i?Re("form",{className:"space-y-3",onSubmit:n=>{n.preventDefault();try{var r
577
+ ;const t=_.value,n=null!==(r=null==f?void 0:f.annotations)&&void 0!==r?r:s,i=`${null!=S?S:N}.${t}`;switch(t){case"json":!function(e,t,n=document){const r=JSON.stringify(e,null,2);ng(r,"application/json",t,n)}(e.buildJSONExportContent(n,{profile:h}),i);break;case"txt":!function(e,t,n=document){ng(e,"text/plain",t,n)}(e.buildTextExportContent(n,{groupName:null==o?void 0:o.name,defaultAuthority:l,displayNamesEnabled:c}),i);break;case"csv":!function(e,t,n=document){ng(e,"text/csv",t,n)}(e.buildCSVExportContent(n,{groupName:null==o?void 0:o.name,defaultAuthority:l,displayNamesEnabled:c}),i);break}}catch(n){t.error("Exporting annotations failed")}},"data-testid":"export-form",children:[s.length>0?Re(v,{children:[Re("p",{className:"text-color-text-light mb-3",children:[Re(Ir,{variant:"text-light",underline:"always",href:"https://web.hypothes.is/help/exporting-and-importing-annotations-in-the-hypothesis-web-app/",target:"_blank",children:"Learn more"})," ","about copying and exporting annotations."]}),Re("label",{
578
+ "data-testid":"export-count",htmlFor:w,className:"font-medium",children:"Name of export file:"}),Re("div",{className:"flex",children:[Re(kr,{classes:"grow","data-testid":"export-filename",id:w,defaultValue:N,value:S,onChange:e=>A(e.target.value),required:!0,maxLength:250}),b&&Re("div",{className:"grow-0 ml-2 min-w-[5rem]",children:Re(Cr,{value:_,onChange:y,buttonContent:_.name,"data-testid":"export-format-select",right:!0,children:lg.map((e=>Re(Cr.Option,{value:e,children:e.name},e.value)))})})]}),Re("label",{htmlFor:x,className:"block font-medium",children:["Select which user","'","s annotations to export:"]}),Re(Cr,{value:f,onChange:g,buttonId:x,buttonContent:Re(sg,{userAnnotations:f}),"data-testid":"user-select",children:[Re(Cr.Option,{value:p,children:Re(sg,{userAnnotations:p})}),d.map((e=>Re(Cr.Option,{value:e,children:Re(sg,{userAnnotations:e})},e.userid)))]})]}):Re("p",{"data-testid":"no-annotations-message",children:"There are no annotations available for export."}),k>0&&Re("p",{
579
+ "data-testid":"drafts-message",children:["You have ",k," unsaved"," ",(E=k,T="draft",C="drafts",1===E?T:C),s.length>0&&Re(v,{children:" that will not be included"}),"."]}),Re(qe,{children:Re(Wn,{"data-testid":"export-button",variant:"primary",disabled:0===s.length,type:"submit",children:"Export"})})]}):Re(ag,{});var E,T,C}),["annotationsExporter","toastMessenger"]);function ug(e,t=new FileReader){const{promise:n,resolve:r,reject:o}=function(){let e,t;return{promise:new Promise(((n,r)=>{e=n,t=r})),resolve:e,reject:t}}();return t.addEventListener("loadend",(e=>{try{var t,n;const o=null!==(t=null===(n=e.target)||void 0===n||null===(n=n.result)||void 0===n?void 0:n.toString())&&void 0!==t?t:"",i=JSON.parse(o);r(i)}catch(e){o(e)}})),t.readAsText(e),n}function dg({size:e,value:t}){const n=e-4,r=Math.PI*n;return Re("span",{className:"text-grey-3",role:"progressbar","aria-valuenow":t,style:{width:`${e}px`,height:`${e}px`,transform:"rotate(-90deg)"},children:Re("svg",{viewBox:`0 0 ${e} ${e}`,children:Re("circle",{
580
+ cx:e/2,cy:e/2,r:n/2,fill:"none",stroke:"currentColor","stroke-width":2,style:{strokeDasharray:r,strokeDashoffset:r-r*(t/100)+"px",transitionDuration:"300ms",transitionProperty:"stroke-dashoffset"}})})})}function hg({onFileSelected:e,disabled:t,id:n}){const r=ue(null),[o,i]=ae(null);return Re(Wn,{variant:"custom",classes:X("w-full relative overflow-hidden border rounded","bg-grey-0 hover:bg-grey-0"),title:o?`${o}, Select a file`:"Select a file",onClick:()=>{var e;return null===(e=r.current)||void 0===e?void 0:e.click()},disabled:t,"data-testid":"file-input-proxy-button",children:[Re("input",{ref:r,accept:".json",id:n,type:"file",disabled:t,className:"invisible absolute w-0 h-0","aria-hidden":!0,"data-testid":"file-input",onChange:t=>{var n,r;const o=t.target.files;i(null!==(n=null==o||null===(r=o[0])||void 0===r?void 0:r.name)&&void 0!==n?n:null),null!==o&&o.length>0&&e(o[0])}}),Re("div",{className:"max-w-full pr-10 truncate","data-testid":"filename-container",children:null!=o?o:"Select a file"}),Re("div",{
581
+ className:"absolute right-0 h-full p-2 border-l bg-grey-2",children:Re(Ft,{})})]})}var mg=Wr((function({importAnnotationsService:e}){const[t,n]=ae(null),[r,o]=ae(null),[i,a]=ae(null),s=Aa(),l=s.profile().userid,c=s.defaultAuthority(),u=s.isFeatureEnabled("client_display_names"),d=he((e=>ns(e,c,u)),[c,u]),h=de((()=>r?rg({annotations:r,getDisplayName:d,excludeReplies:!0}):null),[r,d]),[m,p]=ae(null),f=de((()=>{var e;return null!==(e=null==h?void 0:h.find((e=>e.userid===m)))&&void 0!==e?e:null}),[m,h]);let g;le((()=>{l&&t&&(o(null),a(null),p(null),async function(e){let t;try{t=await ug(e)}catch(e){throw new Error("Not a valid JSON file")}if(null===(n=t)||"object"!=typeof n||!Array.isArray(t.annotations))throw new Error("Not a valid Hypothesis JSON file");var n;return t.annotations}(t).then((e=>{o(e);const t=e.some((e=>e.user===l));p(t?l:null)})).catch((e=>{a(e.message)})))}),[l,t]),f&&(g=async()=>{e.import(f.annotations)});const b=pe(),_=pe();if(!l)return Re("p",{"data-testid":"log-in-message",
582
+ children:"You must log in to import annotations."});const y=Boolean(s.focusedGroup()&&s.defaultContentFrame()&&s.hasFetchedAnnotations()&&!s.isFetchingAnnotations()&&g),w=t&&!r&&!i,x=s.importsPending(),k=s.importsTotal(),N=k-x,S=w||x>0,A=x>0?Math.round(N/k*100):null;return Re(v,{children:[Re("p",{className:"text-color-text-light mb-3",children:[Re(Ir,{variant:"text-light",underline:"always",href:"https://web.hypothes.is/help/exporting-and-importing-annotations-in-the-hypothesis-web-app/",target:"_blank",children:"Learn more"})," ","about importing annotations."]}),Re("label",{htmlFor:b,className:"font-medium",children:"Select Hypothesis export file:"}),Re(hg,{onFileSelected:n,disabled:S,id:b}),h&&Re(v,{children:[Re("label",{htmlFor:_,className:"block font-medium",children:"Select which user's annotations to import:"}),Re(Cr,{value:f,onChange:e=>{var t;return p(null!==(t=null==e?void 0:e.userid)&&void 0!==t?t:null)},buttonId:_,buttonContent:f?Re(sg,{userAnnotations:f}):Re("span",{className:"text-grey-6",
583
+ children:"Select a user..."}),children:h.map((e=>Re(Cr.Option,{value:e,children:Re(sg,{userAnnotations:e})},e.userid)))})]}),i&&Re("p",{"data-testid":"error-info",children:[Re("b",{children:"Unable to find annotations to import:"})," ",i]}),Re(qe,{children:[null!==A&&Re("span",{"data-testid":"progress-text",className:"text-grey-6",children:[A,"% complete"]}),Re(Wn,{"data-testid":"import-button",disabled:!y||S,onClick:g,variant:"primary",children:[null!==A&&Re(dg,{size:22,value:A}),"Import"]})]})]})}),["importAnnotationsService"]);var pg=Wr((function({toastMessenger:e}){const t=Aa(),n=t.mainFrame(),r=t.focusedGroup(),o=r&&n,i=o&&(a=n.uri,s=r.id,rs(a)?`https://hyp.is/go?url=${encodeURIComponent(a)}&group=${s}`:null);var a,s;const l=he((()=>{try{i&&(ds(i),e.success("Copied share link to clipboard"))}catch(t){e.error("Unable to copy link")}}),[i,e]);return o?Re("div",{className:"text-color-text-light space-y-3",children:i?Re(v,{children:[Re("div",{className:"text-color-text font-medium",
584
+ "data-testid":"sharing-intro",children:"private"===r.type?Re("p",{children:"Use this link to share these annotations with other group members:"}):Re("p",{children:"Use this link to share these annotations with anyone:"})}),Re("div",{children:Re(Xn,{children:[Re(kr,{"aria-label":"Use this URL to share these annotations",type:"text",value:i,readOnly:!0}),Re(Jn,{icon:yt,onClick:l,title:"Copy share link",variant:"dark"})]})}),Re("p",{"data-testid":"sharing-details",children:["private"===r.type?Re("span",{children:["Annotations in the private group ",Re("em",{children:r.name})," ","are only visible to group members."]}):Re("span",{children:["Anyone using this link may view the annotations in the group"," ",Re("em",{children:r.name}),"."]})," ",Re("span",{children:["Private (",Re(dn,{className:"inline w-em h-em ml-0.5 -mt-0.5"})," ",Re("em",{children:"Only Me"}),") annotations are only visible to you."]})]}),Re("div",{className:"text-[24px]",children:Re(ps,{shareURI:i})})]}):Re("p",{"data-testid":"no-sharing",
585
585
  children:"These annotations cannot be shared because this document is not available on the web."})}):Re(ag,{})}),["toastMessenger"]);function fg({shareTab:e}){const t=Aa().focusedGroup(),n=t&&t.name||"...",r=`Share Annotations in ${n}`,o=e?"share":"export",[i,a]=ae(o),s=i===o;return Re(Tf,{title:r,panelName:"shareGroupAnnotations",variant:"custom",children:[Re(Lf,{children:[e&&Re(Or,{id:"share-panel-tab","aria-controls":"share-panel",variant:"tab",selected:"share"===i,onClick:()=>a("share"),textContent:"Share",children:"Share"}),Re(Or,{id:"export-panel-tab","aria-controls":"export-panel",variant:"tab",selected:"export"===i,onClick:()=>a("export"),textContent:"Export",children:"Export"}),Re(Or,{id:"import-panel-tab","aria-controls":"import-panel",variant:"tab",selected:"import"===i,onClick:()=>a("import"),textContent:"Import",children:"Import"})]}),Re($e,{classes:X({"rounded-tl-none":s}),children:[Re(Rf,{id:"share-panel",active:"share"===i,"aria-labelledby":"share-panel-tab",title:r,children:Re(pg,{})
586
586
  }),Re(Rf,{id:"export-panel",active:"export"===i,"aria-labelledby":"export-panel-tab",title:`Export from ${n}`,children:Re(cg,{})}),Re(Rf,{id:"import-panel",active:"import"===i,"aria-labelledby":"import-panel-tab",title:`Import into ${n}`,children:Re(mg,{})})]})]})}function gg({onLogin:e}){const t=Aa();return Re("div",{className:"flex flex-col items-center m-6 space-y-6",children:[Re("span",{className:"text-center",children:["This is a public annotation created with Hypothesis. ",Re("br",{}),"To reply or make your own annotations on this document,"," ",Re(Ir,{variant:"text",href:t.getLink("signup"),target:"_blank",underline:"always",children:"create a free account"})," ","or"," ",Re(Lr,{inline:!0,variant:"text",onClick:e,underline:"always",children:"log in"}),"."]}),Re("div",{children:Re(Ir,{href:"https://hypothes.is","aria-label":"Hypothesis homepage",target:"_blank",title:"Hypothesis homepage",underline:"none",variant:"custom",children:Re(mn,{className:"w-16 h-16 text-grey-7"})})})]})}
587
587
  function vg({onLogin:e,onSignUp:t}){return Aa().isLoggedIn()?null:Re(Tf,{icon:In,title:"Login needed",panelName:"loginPrompt",children:[Re("p",{children:"Please log in to create annotations or highlights."}),Re(qe,{children:[Re(Wn,{title:"Sign up",onClick:t,children:"Sign up"}),Re(Wn,{title:"Log in",variant:"primary",onClick:e,children:"Log in"})]})]})}function bg({children:e,count:t,isWaitingToAnchor:n,isSelected:r,label:o,onSelect:i}){const a=()=>{r||i()},s=t>0?`${o} (${t} available)`:o;return Re(Lr,{classes:X("bg-transparent min-w-[5.25rem]",{"font-bold":r}),variant:"text",onClick:a,onMouseDown:a,pressed:!!r,role:"tab",tabIndex:0,title:s,underline:"none",children:Re(v,{children:[e,t>0&&!n&&Re("span",{className:"relative bottom-[3px] left-[2px] text-[10px]",children:t})]})})}var _g=Wr((function({annotationsService:e,isLoading:t,settings:n}){const r=Aa(),o=r.selectedTab(),i=r.noteCount(),a=r.annotationCount(),s=r.orphanCount(),l=r.isWaitingToAnchorAnnotations(),c=e=>{r.clearSelection(),r.selectTab(e)
@@ -613,7 +613,7 @@ e.filterGroups(o)},showContentInfo:t=>{e.setContentInfo(t)}});function sv(e,t,n)
613
613
  n=new Date(t.updated).toISOString();break;default:n=(new Date).toISOString()}const r={date:n,annotation:{id:t.id,isShared:ss(t.permissions)}};this._reportConfig.events.includes(e)&&function(e,t,n,r=[]){const o={jsonrpc:"2.0",method:n,params:r};e.postMessage(o,t)}(this._rpc.targetFrame,this._rpc.origin,this._reportConfig.method,[e,r])}}cv.$inject=["settings"];class uv{constructor(e,t,n,r){H(this,"_activity",void 0),H(this,"_api",void 0),H(this,"_settings",void 0),H(this,"_store",void 0),this._activity=e,this._api=t,this._settings=n,this._store=r}_applyDraftChanges(e){const t={},n=this._store.getDraft(e);return n&&(t.tags=n.tags,t.text=n.text,t.permissions=n.isPrivate?os(e.user):is(e.user,e.group)),{...e,...t}}annotationFromData(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")
614
614
  ;const a=o.user_info,s=`s:${Yg(8)}`,l=Object.assign({created:t.toISOString(),group:r,permissions:as(i,r,n),tags:[],text:"",updated:t.toISOString(),user:i,user_info:a,$tag:s,hidden:!1,links:{},document:{title:""}},e);return Do(l)&&(l.permissions=os(i)),this._settings.annotationMetadata&&(l.metadata={...this._settings.annotationMetadata}),l}create(e,t=new Date){const n=this.annotationFromData(e,t);this._store.addAnnotations([n]),this._store.deleteNewAndEmptyDrafts(),Do(n)||this._store.createDraft(n,{tags:n.tags,text:n.text,isPrivate:!Lo(n)}),Bo(n)?this._store.selectTab("note"):Ho(n)&&this._store.selectTab("annotation"),(n.references||[]).forEach((e=>{this._store.setExpanded(e,!0)}))}createPageNote(){const e=this._store.mainFrame();if(!this._store.isLoggedIn())return void this._store.openSidebarPanel("loginPrompt");if(!e)return;const t={target:[{source:e.uri}],uri:e.uri};this.create(t)}async delete(e){await this._api.annotation.delete({id:e.id}),this._activity.reportActivity("delete",e),
615
615
  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:Lo(e)?is(t,e.group):os(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;Io(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(const[t,n]of Object.entries(e))if(t.startsWith("$")){o[t]=n}return this._store.removeDraft(e),this._store.addAnnotations([o]),o}}function dv(e,t){const n=new RegExp(`^ {${t}}`,"gm");return e.replace(n,"")}function hv(e,...t){return n=function(e,...t){const n=e.join("").match(/^[ \t]*(?=\S)/gm),r=n?Math.min(...n.map((e=>e.length))):0;let o=""
616
- ;for(const[n,i]of t.entries())o+=dv(e[n],r),o+=i;return o+dv(e[e.length-1],r)}([...e],...t),n.replace(/^\s*\n|\n\s*$/g,"");var n}function mv(e){const t={};for(const[n,r]of Object.entries(e))n.startsWith("$")||(t[n]=r);return t}uv.$inject=["annotationActivity","api","settings","store"];let pv,fv,gv=e=>e;class vv{buildJSONExportContent(e,{profile:t,now:n=new Date}){var r;const o=new vf(t,[]);return{export_date:n.toISOString(),export_userid:null!==(r=t.userid)&&void 0!==r?r:"",client_version:o.version,annotations:e.map(mv)}}buildTextExportContent(e,{groupName:t="",displayNamesEnabled:n=!1,defaultAuthority:r="",now:o=new Date}={}){const[i]=e;if(!i)throw new Error("No annotations to export");const a=e=>ns(e,r,n),{uri:s,title:l}=Ao(i),c=[...new Set(e.map((e=>a(e))).filter(Boolean))],u=e.map(((e,t)=>{const n=Go(e),r=[e.created,e.text,a(e),`"${Uo(e)}"`,e.tags.length>0?`Tags: ${e.tags.join(", ")}`:void 0,n?`Page: ${n}`:void 0].filter(Boolean);return hv(pv||(pv=gv`
616
+ ;for(const[n,i]of t.entries())o+=dv(e[n],r),o+=i;return o+dv(e[e.length-1],r)}([...e],...t),n.replace(/^\s*\n|\n\s*$/g,"");var n}function mv(e){const t={};for(const[n,r]of Object.entries(e))n.startsWith("$")||(t[n]=r);return t}uv.$inject=["annotationActivity","api","settings","store"];let pv,fv,gv=e=>e;class vv{buildJSONExportContent(e,{profile:t,now:n=new Date}){var r;const o=new vf(t,[]);return{export_date:n.toISOString(),export_userid:null!==(r=t.userid)&&void 0!==r?r:"",client_version:o.version,annotations:e.map(mv)}}buildTextExportContent(e,{groupName:t="",displayNamesEnabled:n=!1,defaultAuthority:r="",now:o=new Date}={}){const{uri:i,title:a,uniqueUsers:s,replies:l,extractUsername:c}=this._exportCommon(e,{displayNamesEnabled:n,defaultAuthority:r}),u=e.map(((e,t)=>{const n=Go(e),r=[e.created,e.text,c(e),`"${Uo(e)}"`,e.tags.length>0?`Tags: ${e.tags.join(", ")}`:void 0,n?`Page: ${n}`:void 0].filter(Boolean);return hv(pv||(pv=gv`
617
617
  Annotation ${0}:
618
618
  ${0}`),t+1,r.join("\n"))})).join("\n\n");return hv(fv||(fv=gv`
619
619
  ${0}
@@ -625,29 +625,30 @@ this._store.removeAnnotations([e])}async flag(e){await this._api.annotation.flag
625
625
  Total annotations: ${0}
626
626
  Total replies: ${0}
627
627
 
628
- ${0}`),o.toISOString(),l,s,t,c.length,c.join(", "),e.length,e.filter(Mo).length,u)}}vv.$inject=[];class bv extends Error{constructor(e,t,n=""){let r="Network request failed";t&&(r+=` (${t.status})`),n&&(r+=`: ${n}`),super(r),H(this,"url",void 0),H(this,"response",void 0),H(this,"reason",void 0),this.url=e,this.response=t,this.reason=n}}async function _v(e,t){let n,r;try{n=await fetch(e,t)}catch(t){throw new bv(e,null,t.message)}if(204===n.status)return null;try{r=await n.json()}catch(t){throw new bv(e,n,"Failed to parse response")}var o;if(!n.ok)throw new bv(e,n,null===(o=r)||void 0===o?void 0:o.reason);return r}class yv{constructor(e,t,n){H(this,"_clientId",void 0),H(this,"search",void 0),H(this,"annotation",void 0),H(this,"group",void 0),H(this,"groups",void 0),H(this,"profile",void 0),this._clientId=null;const r=e.routes(),o=()=>this._clientId,i=e=>function(e,t,{getAccessToken:n,getClientId:r,onRequestStarted:o,onRequestFinished:i}){return async(a,s)=>{o();try{
629
- const[o,i]=await Promise.all([e,n()]),l=function(e,t){let n=e;const r=t.split(".");for(const[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}return null}(o,t);if(!l)throw new Error(`Missing API route: ${t}`);const c={"Content-Type":"application/json","Hypothesis-Client-Version":"1.1407.0"};i&&(c.Authorization="Bearer "+i);const u=r();u&&(c["X-Client-Id"]=u);const{url:d,unusedParams:h}=Ji(l.url,a),m=new URL(d);for(const[e,t]of Object.entries(h)){const n=Array.isArray(t)?t:[t];for(const t of n)null!=t&&m.searchParams.append(e,t.toString())}return await _v(m.toString(),{body:s?JSON.stringify(mv(s)):null,headers:c,method:l.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"),
630
- 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:{read:i("profile.groups.read")},read:i("profile.read"),update:i("profile.update")}}setClientId(e){this._clientId=e}}yv.$inject=["apiRoutes","auth","store"];var wv={};function xv(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 kv=xv;xv.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},xv.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],
631
- this._cachedTimeouts=null},xv.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();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},xv.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)),
632
- this._operationStart=(new Date).getTime(),this._fn(this._attempts)},xv.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},xv.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},xv.prototype.start=xv.prototype.try,xv.prototype.errors=function(){return this._errors},xv.prototype.attempts=function(){return this._attempts},xv.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=kv;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]
633
- ;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));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}}}(wv);var Nv=t(wv);function Sv(e,t){return new Promise(((n,r)=>{const o=Nv.operation(t);o.attempt((async()=>{try{const t=await e();o.retry(),n(t)}catch(e){o.retry(e)||r(e)}}))}))}function Av(e){
634
- return Sv((()=>_v(e)))}class Ev{constructor(e){H(this,"_apiURL",void 0),H(this,"_routeCache",void 0),H(this,"_linkCache",void 0),this._apiURL=e.apiUrl,this._routeCache=null,this._linkCache=null}routes(){return this._routeCache||(this._routeCache=Av(this._apiURL).then((e=>e.links))),this._routeCache}links(){return this._linkCache||(this._linkCache=this.routes().then((async e=>Av(e.links.url)))),this._linkCache}}Ev.$inject=["settings"];class Tv extends Error{constructor(e,t){super(e),H(this,"cause",void 0),this.cause=t}}class Cv{constructor(e){H(this,"clientId",void 0),H(this,"tokenEndpoint",void 0),H(this,"authorizationEndpoint",void 0),H(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({
635
- 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 Tv("Failed to revoke access token",e)}}authorize(e){const t=Yg(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`
636
- ;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 _v(e,{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 Tv("Failed to fetch access token",e)}return{accessToken:t.access_token,expiresAt:Date.now()+1e3*(t.expires_in-10),refreshToken:t.refresh_token}}}class Mv extends Bf{constructor(e,t,n,r,o){super(),H(this,"_authCode",void 0),H(this,"_client",void 0),H(this,"_tokenInfoPromise",void 0),H(this,"_apiRoutes",void 0),H(this,"_localStorage",void 0),H(this,"_settings",void 0),H(this,"_toastMessenger",void 0),H(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,
637
- 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());return(e=>!!e&&"object"==typeof e&&"accessToken"in e&&"string"==typeof e.accessToken&&"refreshToken"in e&&"string"==typeof e.refreshToken&&"expiresAt"in e&&"number"==typeof e.expiresAt)(e)?{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 Cv({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}
638
- 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=$r(this._settings))||void 0===e?void 0:e.grantToken}_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),
639
- 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()}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())}}Mv.$inject=["$window","apiRoutes","localStorage","settings","toastMessenger"];class Iv{constructor(e,t,n){H(this,"_annotationsService",void 0),H(this,"_toastMessenger",void 0),H(this,"_store",void 0),H(this,"_saving",void 0),H(this,"_failed",void 0),this._annotationsService=e,
640
- 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),Sv((()=>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 zv(e){if(null===e||"object"!=typeof e)return!1;for(const t of["frame1","frame2","type","requestId"])if("string"!=typeof e[t])return!1;return!0}Iv.$inject=["annotationsService","toastMessenger","store"];class Lv extends Error{constructor(e){super(e)}}class Rv{constructor({hostFrame:e,source:t,sourceId:n}){H(this,"_hostFrame",void 0),H(this,"_listeners",void 0),H(this,"_source",void 0),H(this,"_sourceId",void 0),this._hostFrame=e,this._source=t,this._sourceId=n,this._listeners=new Va}destroy(){
641
- this._listeners.removeAll()}async discover(e){const t=Yg(6);return new Promise(((n,r)=>{const o=()=>{this._hostFrame.postMessage({frame1:this._source,frame2:e,type:"request",requestId:t,sourceId:this._sourceId},"*")},i=setInterval(o,250),a=setTimeout((()=>{clearInterval(i),r(new Lv(`Unable to establish ${this._source}-${e} communication channel`))}),2e4),s=this._listeners.add(window,"message",(o=>{const{data:l,ports:c}=o;zv(l)&&l.requestId===t&&"request"!==l.type&&(clearInterval(i),clearTimeout(a),this._listeners.remove(s),"string"==typeof l.error?r(new Lv(l.error)):c.length>0?n(c[0]):r(new Lv(`${this._source}-${e} port request failed`)))}));o()}))}}function Ov(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)}const Pv="1.0.0",Dv="frame-rpc"
642
- ;function Fv(e,t,n=[],r=-1){e.postMessage({protocol:Dv,version:Pv,arguments:n,method:t,sequence:r})}class Bv{constructor({userAgent:e=navigator.userAgent,currentWindow:t=window}={}){H(this,"_callbacks",void 0),H(this,"_destroyed",void 0),H(this,"_listeners",void 0),H(this,"_methods",void 0),H(this,"_port",void 0),H(this,"_sequence",void 0),H(this,"_pendingCalls",void 0),H(this,"_receivedCloseEvent",void 0),this._port=null,this._methods=new Map,this._sequence=1,this._callbacks=new Map,this._listeners=new Va,this._listeners.add(t,"unload",(()=>{this._port&&(Fv(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._destroyed=!1,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,
643
- this._listeners.add(e,"message",(e=>this._handle(e))),e.start(),Fv(e,"connect");for(const[e,t]of this._pendingCalls)this.call(e,...t);this._pendingCalls=[]}destroy(){this._port&&(Fv(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)),Fv(this._port,e,t,n)}_parseMessage({data:e}){return e&&"object"==typeof e?e.protocol!==Dv||e.version!==Pv?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:Dv,response:t.sequence,version:Pv};n.postMessage(r)};e(...t.arguments,r)}else if("response"in t){const e=this._callbacks.get(t.response)
644
- ;this._callbacks.delete(t.response),e&&e(...t.arguments)}}}function Hv(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&&Kp(r.cfi)===Kp(t.cfi))}function jv(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 $v({$cluster:e,$tag:t,target:n,uri:r}){return{$cluster:e,$tag:t,target:n,uri:r}}function Uv(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 qv{constructor(e,t,n,r){H(this,"_annotationsService",void 0),H(this,"_guestRPC",void 0),H(this,"_highlightsVisible",void 0),H(this,"_hostRPC",void 0),H(this,"_inFrame",void 0),H(this,"_listeners",void 0),H(this,"_portFinder",void 0),H(this,"_store",void 0),H(this,"_toastMessenger",void 0),H(this,"_pendingScrollToTag",void 0),H(this,"_pendingHoverTag",void 0),H(this,"_pendingAnchorStatusUpdates",void 0),
645
- H(this,"_scheduleAnchorStatusUpdate",void 0),H(this,"_sidebarIsOpen",void 0),H(this,"_window",void 0),this._window=e,this._annotationsService=t,this._store=n,this._toastMessenger=r,this._portFinder=new Rv({hostFrame:this._window.parent,source:"sidebar"}),this._listeners=new Va,this._hostRPC=new Bv,this._guestRPC=new Map,this._inFrame=new Set,this._highlightsVisible=!1,this._pendingScrollToTag=null,this._pendingHoverTag=null,this._pendingAnchorStatusUpdates=new Map,this._scheduleAnchorStatusUpdate=Ga((()=>{const e=Object.fromEntries(this._pendingAnchorStatusUpdates.entries());this._store.updateAnchorStatus(e),this._pendingAnchorStatusUpdates.clear()}),10),this._sidebarIsOpen=!1,this._setupSyncToGuests(),this._setupHostEvents(),this._setupFeatureFlagSync(),this._setupToastMessengerEvents()}_setupSyncToGuests(){let e=0;const t=(t,n,r)=>{let o=0;const i=new Set,a=[];t.forEach((e=>{Mo(e)||(Lo(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){
646
- const e=new Map,t=[];for(const r of a){var l;const o=Uv(n,r);if(!o||o.segment&&!Hv(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($v))}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)})),n.length>0&&n.every((e=>e.isAnnotationFetchComplete))&&(0!==o&&o===e||(this._hostRPC.call("publicAnnotationCountChanged",o),e=o))};jv(this._store.subscribe,(()=>[this._store.allAnnotations(),this._store.frames()]),(([e,n],[r])=>t(e,n,r)),Pi),jv(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()}
647
- _connectGuest(e,t){const n=new Bv;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=>{const t=this._store.isLoggedIn(),n=null!==this._store.focusedGroup();if(!t||!n)return this._hostRPC.call("openSidebar"),t||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])),
648
- 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",(()=>{this._hostRPC.call("openSidebar")})),n.on("closeSidebar",(()=>{this._hostRPC.call("closeSidebar")})),n.connect(e),n.call("setHighlightsVisible",this._highlightsVisible),n.call("featureFlagsUpdated",this._store.features());const r=this._store.getContentInfo();r&&n.call("showContentInfo",r)}_setupHostEvents(){this._hostRPC.on("sidebarOpened",(()=>{this._sidebarIsOpen=!0,this._store.setSidebarOpened(!0)})),this._hostRPC.on("sidebarClosed",(()=>{this._sidebarIsOpen=!1})),
649
- this._hostRPC.on("setHighlightsVisible",(e=>{this._highlightsVisible=e,this._guestRPC.forEach((t=>t.call("setHighlightsVisible",e)))}))}_setupFeatureFlagSync(){const e=()=>this._store.features(),t=e=>{this._hostRPC.call("featureFlagsUpdated",e);for(const t of this._guestRPC.values())t.call("featureFlagsUpdated",e)};t(e()),jv(this._store.subscribe,e,t)}_setupToastMessengerEvents(){this._toastMessenger.on("toastMessageAdded",(e=>{e.visuallyHidden&&!this._sidebarIsOpen&&this.notifyHost("toastMessageAdded",e)})),this._toastMessenger.on("toastMessageDismissed",(e=>{this.notifyHost("toastMessageDismissed",e)}))}async connect(){const e=await this._portFinder.discover("host");this._hostRPC.connect(e),this._listeners.add(e,"message",(e=>{const{data:t,ports:n}=e,r=t;var o;zv(r)&&(function(e,t){return!!zv(e)&&JSON.stringify(e,Object.keys(t).sort())===JSON.stringify(t,Object.keys(t).sort())}(r,{frame1:"guest",frame2:"sidebar",type:"offer"})&&this._connectGuest(n[0],null!==(o=r.sourceId)&&void 0!==o?o:null))}))}
650
- notifyHost(e,...t){this._hostRPC.call(e,...t)}hoverAnnotation(e){this._pendingHoverTag=null;const t=e?[e.$tag]:[];if(this._store.hoverAnnotations(t),!e)return void this._guestRPC.forEach((e=>e.call("hoverAnnotations",[])));const n=Uv(this._store.frames(),e);!n||n.segment&&!Hv(e,n.segment)?this._pendingHoverTag=e.$tag:this._guestRPC.forEach((e=>e.call("hoverAnnotations",t)))}scrollToAnnotation(e){const t=Uv(this._store.frames(),e);if(!t)return;const n=this._guestRPC.get(null==t?void 0:t.id);return n?t.segment&&!Hv(e,t.segment)?(this._pendingScrollToTag=e.$tag,void n.call("navigateToSegment",$v(e))):void n.call("scrollToAnnotation",e.$tag):void 0}destroy(){this._portFinder.destroy(),this._listeners.removeAll()}}qv.$inject=["$window","annotationsService","store","toastMessenger"];const Gv={id:"__default__",name:"__DEFAULT__",
628
+ ${0}`),o.toISOString(),a,i,t,s.length,s.join(", "),e.length,l.length,u)}buildCSVExportContent(e,{groupName:t="",defaultAuthority:n="",displayNamesEnabled:r=!1}={}){const{uri:o,extractUsername:i}=this._exportCommon(e,{displayNamesEnabled:r,defaultAuthority:n}),a=e=>/[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e;return`${["Creation Date","URL","Group","Annotation/Reply Type","Quote","User","Body","Tags","Page"].join(",")}\n${e.map((e=>{return[(n=e).created,o,t,Mo(n)?"Reply":"Annotation",null!==(r=Uo(n))&&void 0!==r?r:"",i(n),n.text,n.tags.join(","),null!==(s=Go(n))&&void 0!==s?s:""].map(a).join(",");var n,r,s})).join("\n")}`}_exportCommon(e,{displayNamesEnabled:t,defaultAuthority:n}){const[r]=e;if(!r)throw new Error("No annotations to export");const o=e=>ns(e,n,t),{uri:i,title:a}=Ao(r);return{uri:i,title:a,uniqueUsers:[...new Set(e.map((e=>o(e))).filter(Boolean))],replies:e.filter((e=>Mo(e))),extractUsername:o}}}vv.$inject=[];class bv extends Error{constructor(e,t,n=""){let r="Network request failed"
629
+ ;t&&(r+=` (${t.status})`),n&&(r+=`: ${n}`),super(r),H(this,"url",void 0),H(this,"response",void 0),H(this,"reason",void 0),this.url=e,this.response=t,this.reason=n}}async function _v(e,t){let n,r;try{n=await fetch(e,t)}catch(t){throw new bv(e,null,t.message)}if(204===n.status)return null;try{r=await n.json()}catch(t){throw new bv(e,n,"Failed to parse response")}var o;if(!n.ok)throw new bv(e,n,null===(o=r)||void 0===o?void 0:o.reason);return r}class yv{constructor(e,t,n){H(this,"_clientId",void 0),H(this,"search",void 0),H(this,"annotation",void 0),H(this,"group",void 0),H(this,"groups",void 0),H(this,"profile",void 0),this._clientId=null;const r=e.routes(),o=()=>this._clientId,i=e=>function(e,t,{getAccessToken:n,getClientId:r,onRequestStarted:o,onRequestFinished:i}){return async(a,s)=>{o();try{const[o,i]=await Promise.all([e,n()]),l=function(e,t){let n=e;const r=t.split(".");for(const[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}return null}(o,t)
630
+ ;if(!l)throw new Error(`Missing API route: ${t}`);const c={"Content-Type":"application/json","Hypothesis-Client-Version":"1.1408.0"};i&&(c.Authorization="Bearer "+i);const u=r();u&&(c["X-Client-Id"]=u);const{url:d,unusedParams:h}=Ji(l.url,a),m=new URL(d);for(const[e,t]of Object.entries(h)){const n=Array.isArray(t)?t:[t];for(const t of n)null!=t&&m.searchParams.append(e,t.toString())}return await _v(m.toString(),{body:s?JSON.stringify(mv(s)):null,headers:c,method:l.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:{
631
+ read:i("profile.groups.read")},read:i("profile.read"),update:i("profile.update")}}setClientId(e){this._clientId=e}}yv.$inject=["apiRoutes","auth","store"];var wv={};function xv(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 kv=xv;xv.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},xv.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},xv.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime()
632
+ ;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},xv.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)},xv.prototype.try=function(e){
633
+ console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},xv.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},xv.prototype.start=xv.prototype.try,xv.prototype.errors=function(){return this._errors},xv.prototype.attempts=function(){return this._attempts},xv.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=kv;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))
634
+ ;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}}}(wv);var Nv=t(wv);function Sv(e,t){return new Promise(((n,r)=>{const o=Nv.operation(t);o.attempt((async()=>{try{const t=await e();o.retry(),n(t)}catch(e){o.retry(e)||r(e)}}))}))}function Av(e){return Sv((()=>_v(e)))}class Ev{constructor(e){H(this,"_apiURL",void 0),H(this,"_routeCache",void 0),H(this,"_linkCache",void 0),this._apiURL=e.apiUrl,
635
+ this._routeCache=null,this._linkCache=null}routes(){return this._routeCache||(this._routeCache=Av(this._apiURL).then((e=>e.links))),this._routeCache}links(){return this._linkCache||(this._linkCache=this.routes().then((async e=>Av(e.links.url)))),this._linkCache}}Ev.$inject=["settings"];class Tv extends Error{constructor(e,t){super(e),H(this,"cause",void 0),this.cause=t}}class Cv{constructor(e){H(this,"clientId",void 0),H(this,"tokenEndpoint",void 0),H(this,"authorizationEndpoint",void 0),H(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{
636
+ await this._formPost(this.revokeEndpoint,{token:e})}catch(e){throw new Tv("Failed to revoke access token",e)}}authorize(e){const t=Yg(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 _v(e,{
637
+ 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 Tv("Failed to fetch access token",e)}return{accessToken:t.access_token,expiresAt:Date.now()+1e3*(t.expires_in-10),refreshToken:t.refresh_token}}}class Mv extends Bf{constructor(e,t,n,r,o){super(),H(this,"_authCode",void 0),H(this,"_client",void 0),H(this,"_tokenInfoPromise",void 0),H(this,"_apiRoutes",void 0),H(this,"_localStorage",void 0),H(this,"_settings",void 0),H(this,"_toastMessenger",void 0),H(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(){
638
+ const e=this._localStorage.getObject(this._storageKey());return(e=>!!e&&"object"==typeof e&&"accessToken"in e&&"string"==typeof e.accessToken&&"refreshToken"in e&&"string"==typeof e.refreshToken&&"expiresAt"in e&&"number"==typeof e.expiresAt)(e)?{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 Cv({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}}
639
+ _getGrantToken(){var e;return null===(e=$r(this._settings))||void 0===e?void 0:e.grantToken}_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){
640
+ const e=this._getGrantToken();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())}}Mv.$inject=["$window","apiRoutes","localStorage","settings","toastMessenger"];class Iv{constructor(e,t,n){H(this,"_annotationsService",void 0),H(this,"_toastMessenger",void 0),H(this,"_store",void 0),H(this,"_saving",void 0),H(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
641
+ ;e(n)&&(this._saving.add(n),Sv((()=>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 zv(e){if(null===e||"object"!=typeof e)return!1;for(const t of["frame1","frame2","type","requestId"])if("string"!=typeof e[t])return!1;return!0}Iv.$inject=["annotationsService","toastMessenger","store"];class Lv extends Error{constructor(e){super(e)}}class Rv{constructor({hostFrame:e,source:t,sourceId:n}){H(this,"_hostFrame",void 0),H(this,"_listeners",void 0),H(this,"_source",void 0),H(this,"_sourceId",void 0),this._hostFrame=e,this._source=t,this._sourceId=n,this._listeners=new Va}destroy(){this._listeners.removeAll()}async discover(e){const t=Yg(6);return new Promise(((n,r)=>{const o=()=>{this._hostFrame.postMessage({frame1:this._source,frame2:e,type:"request",requestId:t,sourceId:this._sourceId},"*")
642
+ },i=setInterval(o,250),a=setTimeout((()=>{clearInterval(i),r(new Lv(`Unable to establish ${this._source}-${e} communication channel`))}),2e4),s=this._listeners.add(window,"message",(o=>{const{data:l,ports:c}=o;zv(l)&&l.requestId===t&&"request"!==l.type&&(clearInterval(i),clearTimeout(a),this._listeners.remove(s),"string"==typeof l.error?r(new Lv(l.error)):c.length>0?n(c[0]):r(new Lv(`${this._source}-${e} port request failed`)))}));o()}))}}function Ov(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)}const Pv="1.0.0",Dv="frame-rpc";function Fv(e,t,n=[],r=-1){e.postMessage({protocol:Dv,version:Pv,arguments:n,method:t,sequence:r})}class Bv{constructor({userAgent:e=navigator.userAgent,currentWindow:t=window}={}){H(this,"_callbacks",void 0),H(this,"_destroyed",void 0),
643
+ H(this,"_listeners",void 0),H(this,"_methods",void 0),H(this,"_port",void 0),H(this,"_sequence",void 0),H(this,"_pendingCalls",void 0),H(this,"_receivedCloseEvent",void 0),this._port=null,this._methods=new Map,this._sequence=1,this._callbacks=new Map,this._listeners=new Va,this._listeners.add(t,"unload",(()=>{this._port&&(Fv(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._destroyed=!1,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(),Fv(e,"connect");for(const[e,t]of this._pendingCalls)this.call(e,...t);this._pendingCalls=[]}destroy(){this._port&&(Fv(this._port,"close"),this._port.close()),this._destroyed=!0,this._listeners.removeAll()}call(e,...t){
644
+ 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)),Fv(this._port,e,t,n)}_parseMessage({data:e}){return e&&"object"==typeof e?e.protocol!==Dv||e.version!==Pv?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:Dv,response:t.sequence,version:Pv};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 Hv(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&&Kp(r.cfi)===Kp(t.cfi))}function jv(e,t,n,r){
645
+ 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 $v({$cluster:e,$tag:t,target:n,uri:r}){return{$cluster:e,$tag:t,target:n,uri:r}}function Uv(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 qv{constructor(e,t,n,r){H(this,"_annotationsService",void 0),H(this,"_guestRPC",void 0),H(this,"_highlightsVisible",void 0),H(this,"_hostRPC",void 0),H(this,"_inFrame",void 0),H(this,"_listeners",void 0),H(this,"_portFinder",void 0),H(this,"_store",void 0),H(this,"_toastMessenger",void 0),H(this,"_pendingScrollToTag",void 0),H(this,"_pendingHoverTag",void 0),H(this,"_pendingAnchorStatusUpdates",void 0),H(this,"_scheduleAnchorStatusUpdate",void 0),H(this,"_sidebarIsOpen",void 0),H(this,"_window",void 0),this._window=e,this._annotationsService=t,this._store=n,this._toastMessenger=r,this._portFinder=new Rv({hostFrame:this._window.parent,source:"sidebar"}),this._listeners=new Va,
646
+ this._hostRPC=new Bv,this._guestRPC=new Map,this._inFrame=new Set,this._highlightsVisible=!1,this._pendingScrollToTag=null,this._pendingHoverTag=null,this._pendingAnchorStatusUpdates=new Map,this._scheduleAnchorStatusUpdate=Ga((()=>{const e=Object.fromEntries(this._pendingAnchorStatusUpdates.entries());this._store.updateAnchorStatus(e),this._pendingAnchorStatusUpdates.clear()}),10),this._sidebarIsOpen=!1,this._setupSyncToGuests(),this._setupHostEvents(),this._setupFeatureFlagSync(),this._setupToastMessengerEvents()}_setupSyncToGuests(){let e=0;const t=(t,n,r)=>{let o=0;const i=new Set,a=[];t.forEach((e=>{Mo(e)||(Lo(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=Uv(n,r);if(!o||o.segment&&!Hv(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){
647
+ const e=this._guestRPC.get(t);e&&e.call("loadAnnotations",n.map($v))}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)})),n.length>0&&n.every((e=>e.isAnnotationFetchComplete))&&(0!==o&&o===e||(this._hostRPC.call("publicAnnotationCountChanged",o),e=o))};jv(this._store.subscribe,(()=>[this._store.allAnnotations(),this._store.frames()]),(([e,n],[r])=>t(e,n,r)),Pi),jv(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 Bv;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))
648
+ ;e&&!e.persistent&&this._store.destroyFrame(e),this._inFrame.clear(),n.destroy(),this._guestRPC.delete(t)})),n.on("createAnnotation",(e=>{const t=this._store.isLoggedIn(),n=null!==this._store.focusedGroup();if(!t||!n)return this._hostRPC.call("openSidebar"),t||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"),
649
+ 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",(()=>{this._hostRPC.call("openSidebar")})),n.on("closeSidebar",(()=>{this._hostRPC.call("closeSidebar")})),n.connect(e),n.call("setHighlightsVisible",this._highlightsVisible),n.call("featureFlagsUpdated",this._store.features());const r=this._store.getContentInfo();r&&n.call("showContentInfo",r)}_setupHostEvents(){this._hostRPC.on("sidebarOpened",(()=>{this._sidebarIsOpen=!0,this._store.setSidebarOpened(!0)})),this._hostRPC.on("sidebarClosed",(()=>{this._sidebarIsOpen=!1})),this._hostRPC.on("setHighlightsVisible",(e=>{this._highlightsVisible=e,this._guestRPC.forEach((t=>t.call("setHighlightsVisible",e)))}))}_setupFeatureFlagSync(){const e=()=>this._store.features(),t=e=>{this._hostRPC.call("featureFlagsUpdated",e)
650
+ ;for(const t of this._guestRPC.values())t.call("featureFlagsUpdated",e)};t(e()),jv(this._store.subscribe,e,t)}_setupToastMessengerEvents(){this._toastMessenger.on("toastMessageAdded",(e=>{e.visuallyHidden&&!this._sidebarIsOpen&&this.notifyHost("toastMessageAdded",e)})),this._toastMessenger.on("toastMessageDismissed",(e=>{this.notifyHost("toastMessageDismissed",e)}))}async connect(){const e=await this._portFinder.discover("host");this._hostRPC.connect(e),this._listeners.add(e,"message",(e=>{const{data:t,ports:n}=e,r=t;var o;zv(r)&&(function(e,t){return!!zv(e)&&JSON.stringify(e,Object.keys(t).sort())===JSON.stringify(t,Object.keys(t).sort())}(r,{frame1:"guest",frame2:"sidebar",type:"offer"})&&this._connectGuest(n[0],null!==(o=r.sourceId)&&void 0!==o?o:null))}))}notifyHost(e,...t){this._hostRPC.call(e,...t)}hoverAnnotation(e){this._pendingHoverTag=null;const t=e?[e.$tag]:[];if(this._store.hoverAnnotations(t),!e)return void this._guestRPC.forEach((e=>e.call("hoverAnnotations",[])))
651
+ ;const n=Uv(this._store.frames(),e);!n||n.segment&&!Hv(e,n.segment)?this._pendingHoverTag=e.$tag:this._guestRPC.forEach((e=>e.call("hoverAnnotations",t)))}scrollToAnnotation(e){const t=Uv(this._store.frames(),e);if(!t)return;const n=this._guestRPC.get(null==t?void 0:t.id);return n?t.segment&&!Hv(e,t.segment)?(this._pendingScrollToTag=e.$tag,void n.call("navigateToSegment",$v(e))):void n.call("scrollToAnnotation",e.$tag):void 0}destroy(){this._portFinder.destroy(),this._listeners.removeAll()}}qv.$inject=["$window","annotationsService","store","toastMessenger"];const Gv={id:"__default__",name:"__DEFAULT__",
651
652
  logo:"data:image/svg+xml;utf8,"+encodeURIComponent('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg width="24px" height="28px" viewBox="0 0 24 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n <rect fill="#ffffff" stroke="none" width="17.14407" height="16.046612" x="3.8855932" y="3.9449153" />\n <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n <path d="M0,2.00494659 C0,0.897645164 0.897026226,0 2.00494659,0 L21.9950534,0 C23.1023548,0 24,0.897026226 24,2.00494659 L24,21.9950534 C24,23.1023548 23.1029738,24 21.9950534,24 L2.00494659,24 C0.897645164,24 0,23.1029738 0,21.9950534 L0,2.00494659 Z M9,24 L12,28 L15,24 L9,24 Z M7.00811294,4 L4,4 L4,20 L7.00811294,20 L7.00811294,15.0028975 C7.00811294,12.004636 8.16824717,12.0097227 9,12 C10,12.0072451 11.0189302,12.0606714 11.0189302,14.003477 L11.0189302,20 L14.0270431,20 L14.0270431,13.1087862 C14.0270433,10 12,9.00309038 10,9.00309064 C8.01081726,9.00309091 8,9.00309086 7.00811294,11.0019317 L7.00811294,4 Z M19,19.9869002 C20.1045695,19.9869002 21,19.0944022 21,17.9934501 C21,16.892498 20.1045695,16 19,16 C17.8954305,16 17,16.892498 17,17.9934501 C17,19.0944022 17.8954305,19.9869002 19,19.9869002 Z" fill="currentColor"></path>\n </g>\n</svg>')
652
653
  };const Vv=["organization","scopes"];class Wv{constructor(e,t,n,r,o){H(this,"_store",void 0),H(this,"_api",void 0),H(this,"_auth",void 0),H(this,"_settings",void 0),H(this,"_toastMessenger",void 0),H(this,"_serviceConfig",void 0),H(this,"_reloadSetUp",void 0),this._store=e,this._api=t,this._auth=n,this._settings=r,this._toastMessenger=o,this._serviceConfig=$r(r),this._reloadSetUp=!1}_mainURI(){var e,t;return null!==(e=null===(t=this._store.mainFrame())||void 0===t?void 0:t.uri)&&void 0!==e?e:null}async _filterGroups(e,t,n,r){if(r){const t=e.find((e=>e.id===r));t&&!t.isScopedToUri&&t.scopes&&t.scopes.enforced&&(e=e.filter((e=>e.id!==r)),this._store.setDirectLinkedGroupFetchFailed(),r=null)}if(t)return e;const o=e.some((e=>"__world__"!==e.id&&e.isScopedToUri));return o?"__world__"===r||"__world__"===n?e:e.filter((e=>"__world__"!==e.id)):e}_setupAutoReload(){this._reloadSetUp||(this._reloadSetUp=!0,jv(this._store.subscribe,(()=>this._mainURI()),(()=>this.load())),
653
654
  jv(this._store.subscribe,(()=>[this._store.hasFetchedProfile(),this._store.profile().userid]),((e,[t])=>{t&&this.load()}),Pi))}_addGroupsToStore(e,t){!function(e){e.forEach((e=>{e.organization&&"object"==typeof e.organization||(e.organization=Gv)}))}(e);const n=0===this._store.allGroups().length,r=this._store.getDefault("focusedGroup");this._store.loadGroups(e),n&&(t&&e.some((e=>e.id===t))?this.focus(t):r&&e.some((e=>e.id===r))&&this.focus(r))}_fetchGroup(e){return this._api.group.read({id:e,expand:Vv})}async _loadGroupsForUserAndDocument(){var e;const t=()=>function(e,t){const n=t(e);return null!==n?Promise.resolve(n):new Promise((n=>{const r=e.subscribe((()=>{const o=t(e);null!==o&&(r(),n(o))}))}))}(this._store,(()=>this._mainURI()));let n=null;"sidebar"===this._store.route()&&(n=await t()),this._setupAutoReload();const r=this._store.directLinkedAnnotationId();let o=null;r&&(o=this._api.annotation.get({id:r}).catch((()=>null)));const i=this._store.directLinkedGroupId();let a=null
@@ -737,8 +738,8 @@ case"update":case"past":this._store.receiveRealTimeUpdates({updatedAnnotations:e
737
738
  const e=new URL(t);e.searchParams.set("access_token",n),r=e.toString()}else r=t;const o=new xx(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}),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,jv(this._store.subscribe,(()=>this._store.profile().userid),(()=>this._reconnect()))),this._socket||await this._reconnect()}}kx.$inject=["store","apiRoutes","auth","groups","session"]
738
739
  ;const Nx="hypothesis.user.tags.list",Sx="hypothesis.user.tags.map";class Ax{constructor(e){H(this,"_storage",void 0),this._storage=e}filter(e,t=null){const n=this._storage.getObject(Nx)||[];let r=0;return n.filter((n=>{if(null!==t&&r>=t)return!1;const o=n.split(/\W+/),i=new RegExp(`^${rv(e)}`,"i");return!(!o.some((e=>e.match(i)))&&!n.match(i))&&(++r,!0)}))}store(e){const t=this._storage.getObject(Sx)||{};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(Sx,t);const n=Object.keys(t).sort(((e,n)=>t[e].count!==t[n].count?t[n].count-t[e].count:e.localeCompare(n)));this._storage.setObject(Nx,n)}}Ax.$inject=["localStorage"];class Ex{constructor(e){H(this,"_store",void 0),this._store=e}forceVisible(e){e.children.forEach((e=>{this.forceVisible(e)})),e.visible||this._store.setForcedVisible(e.id,!0)}}Ex.$inject=["store"];class Tx extends Bf{constructor(e,t){super(),H(this,"_store",void 0),H(this,"_window",void 0),
739
740
  H(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){this._store.getToastMessage(e)&&(this._store.removeToastMessage(e),this.emit("toastMessageDismissed",e))}_addMessage(e,t,{autoDismiss:n=!0,visuallyHidden:r=!1,delayed:o=!1}={}){if(this._store.hasToastMessage(e,t))return;if(o&&!this._window.document.hasFocus()){const o={autoDismiss:n,visuallyHidden:r};return void this._delayedMessageQueue.push({type:e,messageText:t,options:o})}const i={type:e,id:Yg(10),message:t,visuallyHidden:r};this._store.addToastMessage(i),this.emit("toastMessageAdded",i)}error(e,t){this._addMessage("error",e,t)}success(e,t){this._addMessage("success",e,t)}notice(e,t){this._addMessage("notice",e,t)}}Tx.$inject=["store","$window"];const Cx=function(e){
740
- 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),Mx=function(e){const{version:t,origin:n}=Xg(e.location.href);return"1.1407.0"!==t?(console.warn(`The Hypothesis sidebar is using a different version (1.1407.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."),!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 Ix(e,t){e.setClientId(t.clientId)}function zx(e,t,n){e.load(),t.load(),n.sync()}function Lx(e,t,n){e.init(),t.init(),n.init()}function Rx(e,t,n){"sidebar"===t.route()&&e.connect().catch((()=>{n.error("Hypothesis failed to connect to the web page. Try reloading the page.",{
741
- autoDismiss:!1})}))}Cx.sentry&&Mx&&function(e){const t=function(){const e=import.meta.url;return e?new URL(e).origin:null}(),n=t?[t]:void 0;sx({dsn:e.dsn,environment:e.environment,allowUrls:n,ignoreErrors:["Network request failed","Object Not Found Matching Id"],release:"1.1407.0",beforeSend:(e,t)=>{if(cx>=5)return nv("Client-side Sentry quota reached. No further Sentry events will be sent"),null;++cx;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{Oy("host_config",Xg(window.location.href))}catch(e){}Oy("loaded_scripts",Array.from(document.querySelectorAll("script")).filter((e=>!e.type||e.type.match(/javascript|module/))).map((e=>e.src||"<inline>"))),Ov(((e,t)=>{ux(e,t)}))}(Cx.sentry),function(e){e.addEventListener("click",(e=>{const t=e.target;"A"===t.tagName&&"_blank"===t.target&&(t.rel="noopener")}))}(document.body),Ix.$inject=["api","streamer"],
741
+ 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),Mx=function(e){const{version:t,origin:n}=Xg(e.location.href);return"1.1408.0"!==t?(console.warn(`The Hypothesis sidebar is using a different version (1.1408.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."),!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 Ix(e,t){e.setClientId(t.clientId)}function zx(e,t,n){e.load(),t.load(),n.sync()}function Lx(e,t,n){e.init(),t.init(),n.init()}function Rx(e,t,n){"sidebar"===t.route()&&e.connect().catch((()=>{n.error("Hypothesis failed to connect to the web page. Try reloading the page.",{
742
+ autoDismiss:!1})}))}Cx.sentry&&Mx&&function(e){const t=function(){const e=import.meta.url;return e?new URL(e).origin:null}(),n=t?[t]:void 0;sx({dsn:e.dsn,environment:e.environment,allowUrls:n,ignoreErrors:["Network request failed","Object Not Found Matching Id"],release:"1.1408.0",beforeSend:(e,t)=>{if(cx>=5)return nv("Client-side Sentry quota reached. No further Sentry events will be sent"),null;++cx;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{Oy("host_config",Xg(window.location.href))}catch(e){}Oy("loaded_scripts",Array.from(document.querySelectorAll("script")).filter((e=>!e.type||e.type.match(/javascript|module/))).map((e=>e.src||"<inline>"))),Ov(((e,t)=>{ux(e,t)}))}(Cx.sentry),function(e){e.addEventListener("click",(e=>{const t=e.target;"A"===t.tagName&&"_blank"===t.target&&(t.rel="noopener")}))}(document.body),Ix.$inject=["api","streamer"],
742
743
  zx.$inject=["groups","session","router"],Lx.$inject=["autosaveService","persistedDefaults","serviceURL"],Rx.$inject=["frameSync","store","toastMessenger"];const Ox=document.querySelector("hypothesis-app");!function(e=window){e.addEventListener("message",lv)}(),async function(e,t=window){const n=function(e){const t=Xg(e.location.href),n=["annotations","group","query","appType","openSidebar","showHighlights","services","branding","enableExperimentalNewNoteButton","focus","requestConfigFromFrame","theme","usernameUrl"],r={openSidebar:Zg,requestConfigFromFrame:e=>{if("string"==typeof e)return e;const t=function(e){return"object"==typeof e&&null!==e?e:{}}(e);return{origin:Qg(t.origin),ancestorLevel:Jg(t.ancestorLevel)}}},o={};for(const[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
743
744
  ;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:ev(n.ancestorLevel,t),origin:n.origin}}(n,t);let o;if(r){const e=await async function(e,t){return{...await Kg(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=Kg(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=$r(e);if(!t)return e.apiUrl;if(t.apiUrl)return t.apiUrl;throw new Error("Service should contain an apiUrl value.")}(i),i}(Cx).then((e=>{!function(e,t){const n=new q
744
745
  ;n.register("annotationsExporter",vv).register("annotationsService",uv).register("annotationActivity",cv).register("api",yv).register("apiRoutes",Ev).register("auth",Mv).register("autosaveService",Iv).register("frameSync",qv).register("groups",Wv).register("importAnnotationsService",hx).register("loadAnnotationsService",mx).register("localStorage",fx).register("persistedDefaults",vx).register("router",bx).register("serviceURL",_x).register("session",yx).register("streamer",kx).register("streamFilter",wx).register("tags",Ax).register("threadsService",Ex).register("toastMessenger",Tx).register("store",{factory:Sa}),n.register("$window",{value:window}).register("settings",{value:e}),n.run(Lx),n.run(Ix),n.run(zx),n.run(sv),n.run(Rx),D(Re(Vr.Provider,{value:n,children:Re(Gg,{})}),t)}(e,Ox)})).catch((e=>function(e,t){console.error("Failed to start Hypothesis client: ",e),D(Re(Vg,{error:e}),t)}(e,Ox)));