hypothesis 1.1208.0 → 1.1209.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";function s(s){s.setAttribute("data-hypothesis-asset","")}function t(t,e){var r=t.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=e,s(r),t.head.appendChild(r)}function e(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.esModule,o=void 0===n||n,a=r.forceReload,i=void 0!==a&&a,l=t.createElement("script");o&&(l.type="module"),i&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,s(l),t.head.appendChild(l)}function r(t,e,r,n){var o=t.createElement("link");o.rel=e,o.href=n,o.type="application/annotator+".concat(r),s(o),t.head.appendChild(o)}function n(t,e,r){var n=t.createElement("link");n.rel="preload",n.as=e,n.href=r,"fetch"===e&&(n.crossOrigin="anonymous"),s(n),t.head.appendChild(n)}function o(s,t){return s.assetRoot+"build/"+s.manifest[t]}function a(s){var t=s.match(/(https?):\/\/([^:/]+)/);return t?{protocol:t[1],hostname:t[2]}:null}function i(){var s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,t=s.currentScript;return t?a(t.src):null}function l(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=i(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)}var p={"scripts/annotator.bundle.js":"scripts/annotator.bundle.js?
|
|
1
|
+
!function(){"use strict";function s(s){s.setAttribute("data-hypothesis-asset","")}function t(t,e){var r=t.createElement("link");r.rel="stylesheet",r.type="text/css",r.href=e,s(r),t.head.appendChild(r)}function e(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.esModule,o=void 0===n||n,a=r.forceReload,i=void 0!==a&&a,l=t.createElement("script");o&&(l.type="module"),i&&(e+="#ts=".concat(Date.now())),l.src=e,l.async=!1,s(l),t.head.appendChild(l)}function r(t,e,r,n){var o=t.createElement("link");o.rel=e,o.href=n,o.type="application/annotator+".concat(r),s(o),t.head.appendChild(o)}function n(t,e,r){var n=t.createElement("link");n.rel="preload",n.as=e,n.href=r,"fetch"===e&&(n.crossOrigin="anonymous"),s(n),t.head.appendChild(n)}function o(s,t){return s.assetRoot+"build/"+s.manifest[t]}function a(s){var t=s.match(/(https?):\/\/([^:/]+)/);return t?{protocol:t[1],hostname:t[2]}:null}function i(){var s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,t=s.currentScript;return t?a(t.src):null}function l(s){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(-1===s.indexOf("{"))return s;var e=i(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)}var p={"scripts/annotator.bundle.js":"scripts/annotator.bundle.js?ed8181","styles/annotator.css":"styles/annotator.css?e12a00","styles/annotator.css.map":"styles/annotator.css.map?9e8d4d","styles/highlights.css":"styles/highlights.css?6b4ebd","styles/highlights.css.map":"styles/highlights.css.map?241350","styles/katex.min.css":"styles/katex.min.css?e9b69c","styles/katex.min.css.map":"styles/katex.min.css.map?42d80c","styles/pdfjs-overrides.css":"styles/pdfjs-overrides.css?c95edf","styles/pdfjs-overrides.css.map":"styles/pdfjs-overrides.css.map?1d8ac6","styles/sidebar.css":"styles/sidebar.css?ea4ed5","styles/sidebar.css.map":"styles/sidebar.css.map?a5c2a6","styles/ui-playground.css":"styles/ui-playground.css?70f9ed","styles/ui-playground.css.map":"styles/ui-playground.css.map?9b3989","scripts/sidebar.bundle.js":"scripts/sidebar.bundle.js?c19843","scripts/annotator.bundle.js.map":"scripts/annotator.bundle.js.map?a65da6","scripts/ui-playground.bundle.js":"scripts/ui-playground.bundle.js?518fa9","scripts/ui-playground.bundle.js.map":"scripts/ui-playground.bundle.js.map?7521e4","scripts/sidebar.bundle.js.map":"scripts/sidebar.bundle.js.map?fa0ad4"};if(function(){var s=[function(){return Object.fromEntries([])},function(){return new URL(document.location.href)},function(){return new Request("https://hypothes.is")},function(){return Element.prototype.attachShadow},function(){return CSS.supports("display: grid")},function(){return document.evaluate("/html/body",document,null,XPathResult.ANY_TYPE,null),!0}];try{return s.every((function(s){return s()}))}catch(s){return!1}}()){var c=function(s){for(var t={},e=s.querySelectorAll("script.js-hypothesis-config"),r=0;r<e.length;r++){var n=void 0;try{n=JSON.parse(e[r].textContent||"")}catch(s){console.warn("Could not parse settings from js-hypothesis-config tags",s),n={}}Object.assign(t,n)}return t}(document),u=l(c.assetRoot||"https://cdn.hypothes.is/hypothesis/1.1209.0/");if(document.querySelector("hypothesis-app")){!function(s,r){n(s,"fetch",r.apiUrl),n(s,"fetch",r.apiUrl+"links");for(var a=0,i=["scripts/sidebar.bundle.js"];a<i.length;a++)e(s,o(r,i[a]),{esModule:!0});for(var l=0,p=["styles/katex.min.css","styles/sidebar.css"];l<p.length;l++)t(s,o(r,p[l]))}(document,{assetRoot:u,manifest:p,apiUrl:c.apiUrl})}else{var d=c,h=l(d.notebookAppUrl||"https://hypothes.is/notebook"),y=l(d.profileAppUrl||"https://hypothes.is/user-profile"),f=l(d.sidebarAppUrl||"https://hypothes.is/app.html");!function(s,a){if(!s.querySelector('link[type="application/annotator+html"]')){r(s,"sidebar","html",a.sidebarAppUrl),r(s,"notebook","html",a.notebookAppUrl),r(s,"profile","html",a.profileAppUrl),n(s,"style",o(a,"styles/annotator.css")),r(s,"hypothesis-client","javascript",a.assetRoot+"build/boot.js");for(var i=0,l=["scripts/annotator.bundle.js"];i<l.length;i++)e(s,o(a,l[i]),{esModule:!1});var p=[];void 0!==window.PDFViewerApplication&&p.push("styles/pdfjs-overrides.css"),p.push("styles/highlights.css");for(var c=0,u=p;c<u.length;c++)t(s,o(a,u[c]))}}(document,{assetRoot:u,manifest:p,notebookAppUrl:h,profileAppUrl:y,sidebarAppUrl:f})}}else console.warn("The Hypothesis annotation tool is not supported in this browser. See https://web.hypothes.is/help/which-browsers-are-supported-by-hypothesis/.")}();
|
package/build/manifest.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"scripts/annotator.bundle.js": "scripts/annotator.bundle.js?
|
|
2
|
+
"scripts/annotator.bundle.js": "scripts/annotator.bundle.js?ed8181",
|
|
3
3
|
"styles/annotator.css": "styles/annotator.css?e12a00",
|
|
4
4
|
"styles/annotator.css.map": "styles/annotator.css.map?9e8d4d",
|
|
5
5
|
"styles/highlights.css": "styles/highlights.css?6b4ebd",
|
|
@@ -12,9 +12,9 @@
|
|
|
12
12
|
"styles/sidebar.css.map": "styles/sidebar.css.map?a5c2a6",
|
|
13
13
|
"styles/ui-playground.css": "styles/ui-playground.css?70f9ed",
|
|
14
14
|
"styles/ui-playground.css.map": "styles/ui-playground.css.map?9b3989",
|
|
15
|
+
"scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?c19843",
|
|
15
16
|
"scripts/annotator.bundle.js.map": "scripts/annotator.bundle.js.map?a65da6",
|
|
16
|
-
"scripts/sidebar.bundle.js": "scripts/sidebar.bundle.js?a08d12",
|
|
17
17
|
"scripts/ui-playground.bundle.js": "scripts/ui-playground.bundle.js?518fa9",
|
|
18
18
|
"scripts/ui-playground.bundle.js.map": "scripts/ui-playground.bundle.js.map?7521e4",
|
|
19
|
-
"scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?
|
|
19
|
+
"scripts/sidebar.bundle.js.map": "scripts/sidebar.bundle.js.map?fa0ad4"
|
|
20
20
|
}
|
|
@@ -117,7 +117,7 @@ this._sidebarRPC.on("setHighlightsVisible",(t=>{this.setHighlightsVisible(t,!1)}
|
|
|
117
117
|
;const n=xo(t);if(!n)return;const i=Ke(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)&&tn(i,!0)};this.detach(t.$tag,!1),this._annotations.add(t.$tag),t.target||(t.target=[]);const n=await Promise.all(t.target.map((async e=>{if(!e.selector||!e.selector.some((t=>"TextQuoteSelector"===t.type)))return{annotation:t,target:e};let n;try{const i=await this._integration.anchor(this.element,e.selector),o=qe.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&&Je(e.highlights);this._updateAnchors(n,e)}
|
|
118
118
|
_updateAnchors(t,e){var n;this.anchors=t,null===(n=this._clusterToolbar)||void 0===n||n.scheduleClusterUpdates(),e&&this._bucketBarClient.update(this.anchors)}async createAnnotation({highlight:t=!1}={}){const e=this.selectedRanges;this.selectedRanges=[];const n=await this.getDocumentInfo(),i=this.element,r=(await Promise.all(e.map((t=>this._integration.describe(i,t))))).map((t=>({source:n.uri,selector:t}))),s={uri:n.uri,document:n.metadata,target:r,$highlight:t,$cluster:t?"user-highlights":"user-annotations",$tag:"a:"+o(8)};return this._sidebarRPC.call("createAnnotation",s),this.anchor(s),Co(),s}_hoverAnnotations(t){this._hoveredAnnotations.clear(),t.forEach((t=>this._hoveredAnnotations.add(t)));for(const e of this.anchors)if(e.highlights){const n=t.includes(e.annotation.$tag);tn(e.highlights,n)}this._sidebarRPC.call("hoverAnnotations",t)}_scrollToClosestOffScreenAnchor(t,e){const n=function(t,e){let n=null,i=0;for(let r of t){var o;if(null===(o=r.highlights)||void 0===o||!o.length)continue
|
|
119
119
|
;const t=en(r.highlights).top;"up"===e&&t>=137||"down"===e&&t<=window.innerHeight-22||(!n||"up"===e&&t>i||"down"===e&&t<i)&&(n=r,i=t)}return n}(this.anchors.filter((({annotation:e})=>t.includes(e.$tag))),e);n&&this._integration.scrollToAnchor(n)}_onSelection(t){const e=this._integration.getAnnotatableRange(t);if(!e)return void this._onClearSelection();const n=document.getSelection(),i=ze(n),o=Ye(n);o?(this.selectedRanges=[e],this._hostRPC.call("textSelected"),this._adder.annotationsForSelection=yo(),this._isAdderVisible=!0,this._adder.show(o,i)):this._onClearSelection()}_onClearSelection(){this._isAdderVisible=!1,this._adder.hide(),this.selectedRanges=[],this._informHostOnNextSelectionClear&&this._hostRPC.call("textUnselected"),this._informHostOnNextSelectionClear=!0}selectAnnotations(t,{toggle:e=!1,focusInSidebar:n=!1}={}){e?this._sidebarRPC.call("toggleAnnotationSelection",t):this._sidebarRPC.call("showAnnotations",t,n),this._sidebarRPC.call("openSidebar")}setHighlightsVisible(t,e=!0){!function(t,e){
|
|
120
|
-
t.classList.toggle("hypothesis-highlights-always-on",e)}(this.element,t),this._highlightsVisible=t,e&&this._hostRPC.call("highlightsVisibleChanged",t)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(t){this._sideBySideActive=this._integration.fitSideBySide(t)}get sideBySideActive(){return this._sideBySideActive}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){It(t,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}}function Eo(t,e){const n=new URL(t),i=new URLSearchParams;return i.append("config",JSON.stringify(e)),n.hash=i.toString(),n.toString()}function No(t,e){var n;const i={};for(let[t,n]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=n&&(i[t]=n);i.origin=new URL(t).origin,i.version="1.
|
|
120
|
+
t.classList.toggle("hypothesis-highlights-always-on",e)}(this.element,t),this._highlightsVisible=t,e&&this._hostRPC.call("highlightsVisibleChanged",t)}get highlightsVisible(){return this._highlightsVisible}fitSideBySide(t){this._sideBySideActive=this._integration.fitSideBySide(t)}get sideBySideActive(){return this._sideBySideActive}get hoveredAnnotationTags(){return this._hoveredAnnotations}_handleShortcut(t){It(t,"Ctrl+Shift+H")&&this.setHighlightsVisible(!this._highlightsVisible)}}function Eo(t,e){const n=new URL(t),i=new URLSearchParams;return i.append("config",JSON.stringify(e)),n.hash=i.toString(),n.toString()}function No(t,e){var n;const i={};for(let[t,n]of Object.entries(e))"notebookAppUrl"!==t&&"sidebarAppUrl"!==t&&null!=n&&(i[t]=n);i.origin=new URL(t).origin,i.version="1.1209.0";const o=new URL(window.location.href);if(o.hash="",i.hostURL=o.toString(),Array.isArray(i.services)&&(null===(n=i.services)||void 0===n?void 0:n.length)>0){const t=i.services[0]
|
|
121
121
|
;t.onLoginRequest&&(t.onLoginRequestProvided=!0),t.onLogoutRequest&&(t.onLogoutRequestProvided=!0),t.onSignupRequest&&(t.onSignupRequestProvided=!0),t.onProfileRequest&&(t.onProfileRequestProvided=!0),t.onHelpRequest&&(t.onHelpRequestProvided=!0)}return i}function Ao({config:t,groupId:e}){return qt("iframe",{title:"Hypothesis annotation notebook",className:"h-full w-full border-0",allowFullScreen:!0,src:Eo(t.notebookAppUrl,{...No(t.notebookAppUrl,t),group:e})})}function To({eventBus:t,config:e}){const[n,i]=Ct(0),[o,r]=Ct(!0),[s,a]=Ct(null),l=Et(""),c=Et(null);St((()=>(l.current=document.body.style.overflow,()=>{document.body.style.overflow=l.current})),[]),St((()=>{document.body.style.overflow=o?l.current:"hidden"}),[o]),St((()=>{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:qt("div",{className:Ht("fixed z-max top-0 left-0 right-0 bottom-0 p-3 bg-black/50",{hidden:o}),"data-testid":"notebook-outer",
|
|
122
122
|
children:qt("div",{className:"relative w-full h-full","data-testid":"notebook-inner",children:[qt("div",{className:"absolute right-0 m-3",children:qt(ve,{title:"Close the Notebook",onClick:()=>{var t;r(!0),null===(t=c.current)||void 0===t||t.publish("closeNotebook")},variant:"dark",classes:Ht("!bg-transparent enabled:hover:!bg-grey-3"),children:qt($t,{className:"w-4 h-4"})})}),qt(Ao,{config:e,groupId:s},n)]})})}class Ro{constructor(t,e,n){this._outerContainer=document.createElement("hypothesis-notebook"),t.appendChild(this._outerContainer),this.shadowRoot=ke(this._outerContainer),lt(qt(To,{eventBus:e,config:n}),this.shadowRoot)}destroy(){lt(null,this.shadowRoot),this._outerContainer.remove()}}var ko={},Po={get exports(){return ko},set exports(t){ko=t}};!function(t){!function(e,n,i,o){var r,s=["","webkit","Moz","MS","ms","o"],a=n.createElement("div"),l=Math.round,c=Math.abs,h=Date.now;function u(t,e,n){return setTimeout(v(t,n),e)}function d(t,e,n){return!!Array.isArray(t)&&(f(t,n[e],n),!0)}function f(t,e,n){
|
|
123
123
|
var i;if(t)if(t.forEach)t.forEach(e,n);else if(t.length!==o)for(i=0;i<t.length;)e.call(n,t[i],i,t),i++;else for(i in t)t.hasOwnProperty(i)&&e.call(n,t[i],i,t)}function p(t,n,i){var o="DEPRECATED METHOD: "+n+"\n"+i+" AT \n";return function(){var n=new Error("get-stack-trace"),i=n&&n.stack?n.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",r=e.console&&(e.console.warn||e.console.log);return r&&r.call(e.console,o,i),t.apply(this,arguments)}}r="function"!=typeof Object.assign?function(t){if(t===o||null===t)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(t),n=1;n<arguments.length;n++){var i=arguments[n];if(i!==o&&null!==i)for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])}return e}:Object.assign;var g=p((function(t,e,n){for(var i=Object.keys(e),r=0;r<i.length;)(!n||n&&t[i[r]]===o)&&(t[i[r]]=e[i[r]]),r++;return t}),"extend","Use `assign`."),m=p((function(t,e){return g(t,e,!0)
|
|
@@ -606,7 +606,7 @@ function Kv({onLogin:e,onSignUp:t}){return Xa().isLoggedIn()?null:eo(Wv,{icon:kc
|
|
|
606
606
|
},u="annotation"===o&&0===a&&!l,d="note"===o&&0===i;return eo("div",{className:Tr("space-y-3 pb-[9px]"),children:[eo("div",{className:"flex gap-x-6 theme-clean:ml-[15px]",role:"tablist",children:[eo(Xv,{count:a,isWaitingToAnchor:l,isSelected:"annotation"===o,label:"Annotations",onSelect:()=>c("annotation"),children:"Annotations"}),eo(Xv,{count:i,isWaitingToAnchor:l,isSelected:"note"===o,label:"Page notes",onSelect:()=>c("note"),children:"Page Notes"}),s>0&&eo(Xv,{count:s,isWaitingToAnchor:l,isSelected:"orphan"===o,label:"Orphans",onSelect:()=>c("orphan"),children:"Orphans"})]}),"note"===o&&n.enableExperimentalNewNoteButton&&eo("div",{className:"flex justify-end",children:eo(Hc,{"data-testid":"new-note-button",onClick:()=>e.createPageNote(),variant:"primary",style:xo(["ctaBackgroundColor"],n),children:[eo(dc,{}),"New note"]})}),!t&&d&&eo(Yc,{"data-testid":"notes-unavailable-message",variant:"flat",children:eo(Wc,{classes:"text-center",children:"There are no page notes in this group."})}),!t&&u&&eo(Yc,{
|
|
607
607
|
"data-testid":"annotations-unavailable-message",variant:"flat",children:eo(Wc,{classes:"text-center !space-y-1",children:[eo("p",{children:"There are no annotations in this group."}),eo("p",{children:["Create one by selecting some text and clicking the"," ",eo(Ks,{className:"w-em h-em inline m-0.5 -mt-0.5",title:"Annotate"})," ","button."]})]})})]})}),["annotationsService","settings"]);var Jv=No((function({frameSync:e,onLogin:t,onSignUp:n,loadAnnotationsService:r,streamer:o}){const i=Ts(),a=Xa(),s=a.focusedGroupId(),l=a.hasAppliedFilter()||a.hasSelectedAnnotations(),c=a.isLoading(),u=a.isLoggedIn(),d=a.directLinkedAnnotationId(),h=d?a.findAnnotationByID(d):void 0,m=h?vs(h):"annotation",p=a.searchUris(),f=a.hasSidebarOpened(),g=a.profile().userid,v=!(c||!d)&&!h,b=a.directLinkedGroupFetchFailed(),_=v||b,y=!_,w=!_&&!l,x=d&&!u&&!v&&!c,k=Ur(s);jr((()=>{if(!k.current||k.current!==s){if(k.current){const e=a.focusState().active;a.clearSelection(),e&&a.toggleFocusMode(!0)}k.current=s}s&&p.length&&r.load({groupId:s,
|
|
608
608
|
uris:p})}),[a,r,s,g,p]),jr((()=>{h&&!1===h.$orphan?(e.hoverAnnotation(h),e.scrollToAnnotation(h),a.selectTab(m)):h&&a.selectTab(m)}),[m,e,h,a]);const N=a.hasFetchedProfile();return jr((()=>{N&&(f||u)&&o.connect({applyUpdatesImmediately:!1})}),[N,u,f,o]),eo("div",{children:[eo("h2",{className:"sr-only",children:"Annotations"}),y&&eo(Fv,{}),eo(Kv,{onLogin:t,onSignUp:n}),v&&eo(Dv,{errorType:"annotation",onLoginRequest:t,showClearSelection:!0}),b&&eo(Dv,{errorType:"group",onLoginRequest:t}),w&&eo(Zv,{isLoading:c}),eo(Ov,{threads:i.children}),x&&eo(jv,{onLogin:t})]})}),["frameSync","loadAnnotationsService","streamer"]);var Qv=No((function({api:e,toastMessenger:t}){const n=Xa(),r=n.routeParams().q,o=$r((async t=>{const r={_separate_replies:!0,offset:0,limit:20,...us(t)};try{n.annotationFetchStarted();const t=await e.search(r);n.addAnnotations([...t.rows,...t.replies])}finally{n.annotationFetchFinished()}}),[e,n]);return jr((()=>{n.setSortKey("Newest"),n.clearAnnotations(),o(r).catch((e=>{
|
|
609
|
-
t.error(`Unable to fetch annotations: ${e.message}`)}))}),[r,o,n,t]),eo(Ov,{threads:Ts().children})}),["api","toastMessenger"]);class eb{constructor(e,t,n=window){var r,o,i,a;const s="N/A";let l=s;e.userid&&(l=e.userid,e.displayName&&(l=`${e.displayName} (${l})`)),this.version="1.
|
|
609
|
+
t.error(`Unable to fetch annotations: ${e.message}`)}))}),[r,o,n,t]),eo(Ov,{threads:Ts().children})}),["api","toastMessenger"]);class eb{constructor(e,t,n=window){var r,o,i,a;const s="N/A";let l=s;e.userid&&(l=e.userid,e.displayName&&(l=`${e.displayName} (${l})`)),this.version="1.1209.0",this.userAgent=n.navigator.userAgent,this.urls=t.map((e=>e.uri)).join(", ")||s,this.fingerprint=null!==(r=null===(o=t[0])||void 0===o||null===(i=o.metadata)||void 0===i?void 0:i.documentFingerprint)&&void 0!==r?r:s,this.account=l,this.timestamp=(new Date).toString();const c=null===(a=t[0])||void 0===a?void 0:a.segment;if(c){const e=[];c.cfi&&e.push(["CFI",c.cfi]),c.url&&e.push(["URL",c.url]),this.segment=e.map((([e,t])=>`${e}: ${t}`)).join(", ")}}asFormattedString(){return`Version: ${this.version}\nUser Agent: ${this.userAgent}\nURL: ${this.urls}\nFingerprint: ${this.fingerprint}\nAccount: ${this.account}\nDate: ${this.timestamp}\n`}asEncodedURLString(){return encodeURIComponent(this.asFormattedString())}}function tb(e){
|
|
610
610
|
const n=t(e);return!(null==n||!n.authority)&&n.authority!==e.authDomain}function nb({commandName:e,icon:t}){return eo("span",{className:"whitespace-nowrap","data-testid":"instruction",children:[eo(t,{className:Tr("w-em h-em","mx-1 -mt-1","text-color-text-light inline")}),eo("em",{"data-testid":"command-name",children:e})]})}var rb=No((function({settings:e}){const t=!tb(e);return eo("ol",{className:"list-decimal pl-10 space-y-2",children:[eo("li",{children:["To create an annotation, select text and then select the"," ",eo(nb,{icon:Ks,commandName:"Annotate"})," button."]}),eo("li",{children:["To create a highlight (",eo(nu,{href:"https://web.hypothes.is/help/why-are-highlights-private-by-default/",target:"_blank",underline:"always",children:"visible only to you"}),"), select text and then select the"," ",eo(nb,{icon:Yl,commandName:"Highlight"})," button."]}),t&&eo("li",{
|
|
611
611
|
children:["To annotate in a private group, select the group from the groups dropdown. Don't see your group? Ask the group creator to send a"," ",eo(nu,{href:"https://web.hypothes.is/help/how-to-join-a-private-group/",target:"_blank",underline:"always",children:"join link"}),"."]}),eo("li",{children:["To reply to an annotation, select the"," ",eo(nb,{icon:wc,commandName:"Reply"})," button."]})]})}),["settings"]);function ob({label:e,children:t,classes:n}){return eo(er,{children:[eo("dt",{className:"col-span-1 sm:text-right font-medium",children:e}),eo("dd",{className:Tr("col-span-1 sm:col-span-3 text-color-text-light break-words",n),children:t})]})}var ib=No((function({toastMessenger:e,versionData:t}){return eo("div",{className:"space-y-4",children:[eo("dl",{className:"grid grid-cols-1 sm:grid-cols-4 sm:gap-x-2",children:[eo(ob,{label:"Version",children:t.version}),eo(ob,{label:"User Agent",children:t.userAgent}),eo(ob,{classes:Tr("break-all"),label:"URL",children:t.urls}),eo(ob,{label:"Fingerprint",
|
|
612
612
|
children:t.fingerprint}),t.segment&&eo(ob,{label:"Segment",children:t.segment}),eo(ob,{label:"Account",children:t.account}),eo(ob,{label:"Date",children:t.timestamp})]}),eo("div",{className:"flex items-center justify-center",children:eo(Hc,{onClick:()=>{try{fu(t.asFormattedString()),e.success("Copied version info to clipboard")}catch(t){e.error("Unable to copy version info")}},icon:vl,children:"Copy version details"})})]})}),["toastMessenger"]);function ab({children:e,onClick:t}){return eo(ru,{color:"brand",onClick:t,underline:"hover",children:eo("div",{className:"flex items-center gap-x-1",children:[e,eo(Qs,{className:"w-em h-em"})]})})}function sb({linkText:e,url:t}){return eo("div",{className:"flex-1 flex items-center justify-center border-r last-of-type:border-r-0 text-md font-medium",children:eo(nu,{color:"text-light",href:t,target:"_blank",children:eo("div",{className:"flex items-center gap-x-2",children:[eo("span",{children:e})," ",eo(Rl,{className:"w-3 h-3"})]})})})}var lb=No((function({session:e}){
|
|
@@ -629,35 +629,35 @@ const n=Xa(),r=n.getCurrentlyViewingGroups(),o=n.getFeaturedGroups(),i=n.getMyGr
|
|
|
629
629
|
expandedGroup:p,onExpandGroup:f,heading:"My Groups",groups:l}),h&&eo(ov,{icon:dc,href:m,label:"New private group"})]})}),["settings"]);const Rb={alt:1,ctrl:2,meta:4,shift:8};function Ib(e,t,{rootElement:n=document.documentElement}={}){const r=n=>{(function(e,t){const n=t.split("+").map((e=>e.toLowerCase()));let r=0,o=null;for(const e of n){const t=Rb[e];if(t)r|=t;else{if(null!==o)throw new Error("Multiple non-modifier keys specified");o=e}}if(!o)throw new Error(`Invalid shortcut: ${t}`);return((e.ctrlKey?Rb.ctrl:0)|(e.metaKey?Rb.meta:0)|(e.altKey?Rb.alt:0)|(e.shiftKey?Rb.shift:0))===r&&e.key.toLowerCase()===o})(n,e)&&t(n)};return n.addEventListener("keydown",r),()=>n.removeEventListener("keydown",r)}function Ob(e,t,{rootElement:n}={}){jr((()=>{if(e)return Ib(e,t,{rootElement:n})}),[e,t,n])}function Db({alwaysExpanded:e,query:t,onSearch:n}){const r=Xa().isLoading(),o=Ur(null);!function(e){const t=Ur(null),n=$r((n=>{var r
|
|
630
630
|
;!n.metaKey&&!n.ctrlKey&&n.target instanceof HTMLElement&&["INPUT","TEXTAREA"].includes(n.target.tagName)||(t.current=document.activeElement,e.current&&(null===(r=e.current)||void 0===r||r.focus(),n.preventDefault(),n.stopPropagation()))}),[e]),r=$r((()=>{var n;document.activeElement===e.current&&(t.current&&(t.current.focus(),t.current=null),null===(n=e.current)||void 0===n||n.blur())}),[e]),o=pu()?"meta":"ctrl";Ob("/",n),Ob(`${o}+k`,n),Ob("escape",r)}(o);const[i,a]=Br(t),[s,l]=Br(t);t!==i&&(l(t),a(t));const c=e||t;return eo("form",{action:"#",className:Tr("relative","flex items-center","bg-white/90 hover:bg-white transition-colors"),name:"searchForm",onSubmit:e=>{var t,r,a;(e.preventDefault(),null!==(t=o.current)&&void 0!==t&&t.value||i)&&n(null!==(r=null===(a=o.current)||void 0===a?void 0:a.value)&&void 0!==r?r:"")},children:[eo(Vc,{"aria-label":"Search",classes:Tr("order-1","text-base",{"border-0":!c,"focus:border":!0,border:c},{"max-w-0 p-0":!c,"focus:max-w-[150px] focus:p-1.5 focus:ml-[2px]":!0,
|
|
631
631
|
"max-w-[150px] p-1.5 ml-[2px]":c},"transition-[max-width] duration-300 ease-out"),"data-testid":"search-input",dir:"auto",type:"text",name:"query",placeholder:r?"Loading…":"Search…",disabled:r,elementRef:o,value:s||"",onInput:e=>l(e.target.value)}),!r&&eo("div",{className:"order-0",children:eo(Gc,{icon:Sc,onClick:()=>{var e;return null===(e=o.current)||void 0===e?void 0:e.focus()},size:"xs",title:"Search annotations"})}),r&&eo(Bc,{})]})}function Pb(){const e=Xa(),t=e.sortKey(),n=e.sortKeys().map((n=>eo(ov,{label:n,onClick:()=>e.setSortKey(n),isSelected:n===t},n))),r=eo("span",{className:"p-1",children:eo(Rc,{})});return eo("div",{className:"SortMenu",children:eo(tv,{label:r,title:`Sort by ${t}`,align:"right",menuIndicator:!1,children:n})})}var Bb=No((function({router:e}){return eo(Db,{query:Xa().routeParams().q,onSearch:t=>{e.navigate("stream",{q:t})},alwaysExpanded:!0})}),["router"]);var Fb=No((function({frameSync:e,onLogout:n,settings:r}){var o,i
|
|
632
|
-
;const a=Xa(),s=a.defaultAuthority(),l=a.profile(),c=au(l.userid,s),u=t(r),d=iu(l.userid),h=null!==(o=null===(i=l.user_info)||void 0===i?void 0:i.display_name)&&void 0!==o?o:d,[m,p]=Br(!1),f=e=>u&&!!u[e],g=!c||f("onProfileRequestProvided"),v=!c||f("onLogoutRequestProvided"),b=()=>{e.notifyHost("openNotebook",a.focusedGroupId())},
|
|
633
|
-
const l=!tb(a),c=xo(["accentColor"],a),u=Xa(),d=u.filterQuery(),h=u.pendingUpdateCount(),m=u.isLoggedIn(),p=u.hasFetchedProfile(),f=u.isSidebarPanelOpen("help"),g=u.isSidebarPanelOpen("shareGroupAnnotations");return eo("div",{className:Tr("absolute h-10 left-0 top-0 right-0 z-4","text-grey-7 border-b theme-clean:border-b-0 bg-white"),"data-testid":"top-bar",children:eo("div",{className:Tr("container flex items-center h-full","text-[16px]"),"data-testid":"top-bar-content",children:[eo(e?Lb:Bb,{}),eo("div",{className:"grow flex items-center justify-end",children:[e&&eo(er,{children:[h>0&&eo(Gc,{icon:_c,onClick:()=>s.applyPendingUpdates(),size:"xs",variant:"primary",title:`Show ${h} new/updated ${1===h?"annotation":"annotations"}`}),eo(Db,{query:d||null,onSearch:u.setFilterQuery}),eo(Pb,{}),l&&eo(Gc,{icon:Ac,expanded:g,onClick:()=>{
|
|
634
|
-
;e&&e.onHelpRequestProvided?i.notifyHost("helpRequested"):u.toggleSidebarPanel("help")},size:"xs",title:"Help"}),m?eo(Fb,{onLogout:r}):eo("div",{className:"flex items-center text-md font-medium space-x-1","data-testid":"login-links",children:[!m&&!p&&eo("span",{children:"⋯"}),!m&&p&&eo(er,{children:[eo(ru,{classes:"inline",onClick:o,style:c,children:"Sign up"}),eo("div",{children:"/"}),eo(ru,{classes:"inline",onClick:n,style:c,children:"Log in"})]})]})]})]})})}),["frameSync","settings","streamer"]);var Hb=No((function({auth:e,frameSync:n,settings:r,session:o,toastMessenger:i}){const a=Xa(),s=a.profile(),l=a.route(),c=qr((()=>xo(["appBackgroundColor"],r)),[r]),u="clean"===r.theme,d="sidebar"===l;jr((()=>{(function(e,n,r){const o="object"==typeof n.preferences&&!!n.preferences.show_sidebar_tutorial,i=t(r)||{onHelpRequestProvided:!1}
|
|
635
|
-
a.closeSidebarPanel("loginPrompt"),a.clearGroups(),o.reload()}catch(e){i.error(e.message)}},m=()=>{t(r)?n.notifyHost("signupRequested"):window.open(a.getLink("signup"))};return eo("div",{className:Tr("h-full min-h-full overflow-scroll","lg:pb-16 bg-grey-2","js-thread-list-scroll-root",{"theme-clean":u,"pt-[49px]":"notebook"!==l,"p-4 lg:p-12":"notebook"===l}),"data-testid":"hypothesis-app",style:c,children:["notebook"!==l&&eo(jb,{onLogin:h,onSignUp:m,onLogout:async()=>{await(async()=>{const e=a.countDrafts();if(0===e)return!0;let t="";return 1===e?t="You have an unsaved annotation.\nDo you really want to discard this draft?":e>1&&(t="You have "+e+" unsaved annotations.\nDo you really want to discard these drafts?"),yo({title:"Discard drafts?",message:t,confirmAction:"Discard"})})()&&(a.clearGroups(),
|
|
636
|
-
children:[eo(Sb,{}),eo(lb,{}),eo(kb,{}),l&&eo("main",{children:["annotation"===l&&eo(Pv,{onLogin:h}),"notebook"===l&&eo(xb,{}),"stream"===l&&eo(Qv,{}),"sidebar"===l&&eo(Jv,{onLogin:h,onSignUp:m})]})]})]})}),["auth","frameSync","session","settings","toastMessenger"]);function Ub({error:e}){return eo("div",{className:Tr("m-2 mt-12"),children:eo(eu,{title:"Unable to start Hypothesis",children:e.message})})}class qb{constructor(e,t,n){this._activity=e,this._api=t,this._store=n}_applyDraftChanges(e){const t={},n=this._store.getDraft(e);return n&&(t.tags=n.tags,t.text=n.text,t.permissions=n.isPrivate?cu(e.user):uu(e.user,e.group)),{...e,...t}}_initialize(e,t=new Date){const n=this._store.getDefault("annotationPrivacy"),r=this._store.focusedGroupId(),o=this._store.profile();if(!r)throw new Error("Cannot create annotation without a group");const i=o.userid
|
|
637
|
-
permissions:du(i,r,n),tags:[],text:"",updated:t.toISOString(),user:i,user_info:s,$tag:l,hidden:!1,links:{},document:{title:""}},e);return pi(c)&&(c.permissions=cu(i)),c}create(e,t=new Date){const n=this._initialize(e,t);this._store.addAnnotations([n]),this._store.deleteNewAndEmptyDrafts(),pi(n)||this._store.createDraft(n,{tags:n.tags,text:n.text,isPrivate:!ui(n)}),gi(n)?this._store.selectTab("note"):vi(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:[],uri:e.uri};this.create(t)}async delete(e){await this._api.annotation.delete({id:e.id}),this._activity.reportActivity("delete",e),this._store.removeAnnotations([e])}async flag(e){
|
|
638
|
-
permissions:ui(e)?uu(t,e.group):cu(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;li(e)?(t=this._api.annotation.update({id:e.id},r),n="update"):(t=this._api.annotation.create({},r),n="create"),this._store.annotationSaveStarted(e);try{o=await t,this._activity.reportActivity(n,o)}finally{this._store.annotationSaveFinished(e)}for(let[t,n]of Object.entries(e))if(t.startsWith("$")){o[t]=n}return this._store.removeDraft(e),this._store.addAnnotations([o]),o}}qb.$inject=["annotationActivity","api","store"];class $b{constructor(e){this._rpc=e.rpc,this._reportConfig=e.reportActivity}reportActivity(e,t){if(!this._rpc||!this._reportConfig)return;let n;switch(e){case"create":n=new Date(t.created).toISOString();break;case"update":
|
|
639
|
-
;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])}}$b.$inject=["settings"];class Gb extends Error{constructor(e,t,n=""){let r="Network request failed";t&&(r+=` (${t.status})`),n&&(r+=`: ${n}`),super(r),this.url=e,this.response=t,this.reason=n}}async function Vb(e,t){let n,r;try{n=await fetch(e,t)}catch(t){throw new Gb(e,null,t.message)}if(204===n.status)return null;try{r=await n.json()}catch(t){throw new Gb(e,n,"Failed to parse response")}var o;if(!n.ok)throw new Gb(e,n,null===(o=r)||void 0===o?void 0:o.reason);return r}function Yb(e){const t={};for(let[n,r]of Object.entries(e))n.startsWith("$")||(t[n]=r);return t}class Wb{constructor(e,t,n){const r=e.routes();this._clientId=null
|
|
640
|
-
const[o,l]=await Promise.all([e,n()]),c=function(e,t){let n=e;const r=t.split(".");for(let[e,t]of r.entries()){const o=n[t];if(!o||"url"in o){if(o&&e===r.length-1)return o;break}n=o}return null}(o,t);if(!c)throw new Error(`Missing API route: ${t}`);const u={"Content-Type":"application/json","Hypothesis-Client-Version":"1.
|
|
641
|
-
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}}Wb.$inject=["apiRoutes","auth","store"];var Kb={},Xb={get exports(){return Kb},set exports(e){Kb=e}},Zb={};function Jb(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 Qb=Jb;Jb.prototype.reset=function(){
|
|
642
|
-
this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},Jb.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},Jb.prototype.attempt=function(e,t){this._fn=e,
|
|
643
|
-
n._operationTimeoutCb()}),n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},Jb.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},Jb.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},Jb.prototype.start=Jb.prototype.try,Jb.prototype.errors=function(){return this._errors},Jb.prototype.attempts=function(){return this._attempts},Jb.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=Qb;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})},
|
|
644
|
-
;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}}}(Zb),Xb.exports=Zb;var e_=h(Kb)
|
|
645
|
-
function n_(e){return t_((()=>Vb(e)))}class r_{constructor(e){this._apiURL=e.apiUrl,this._routeCache=null,this._linkCache=null}routes(){return this._routeCache||(this._routeCache=n_(this._apiURL).then((e=>e.links))),this._routeCache}links(){return this._linkCache||(this._linkCache=this.routes().then((async e=>{const t=e.links;return await n_(t.url)}))),this._linkCache}}r_.$inject=["settings"];class o_ extends Error{constructor(e,t){super(e),this.cause=t}}class i_{constructor(e){this.clientId=e.clientId,this.tokenEndpoint=e.tokenEndpoint,this.authorizationEndpoint=e.authorizationEndpoint,this.revokeEndpoint=e.revokeEndpoint}exchangeAuthCode(e){return this._getAccessToken({client_id:this.clientId,grant_type:"authorization_code",code:e})}exchangeGrantToken(e){return this._getAccessToken({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
646
|
-
token:e})}catch(e){throw new o_("Failed to revoke access token",e)}}authorize(e){const t=a(16),n=new Promise(((n,r)=>{e.addEventListener("message",(function o(i){"object"==typeof i.data&&i.data.state===t&&("authorization_response"===i.data.type&&n(i.data),"authorization_canceled"===i.data.type&&r(new Error("Authorization window was closed")),e.removeEventListener("message",o))}))})),r=new URL(this.authorizationEndpoint);r.searchParams.set("client_id",this.clientId),r.searchParams.set("origin",e.location.origin),r.searchParams.set("response_mode","web_message"),r.searchParams.set("response_type","code"),r.searchParams.set("state",t);const o=`left=${e.screen.width/2-237.5},top=${e.screen.height/2-215},width=475,height=430`;if(!e.open(r.toString(),"Log in to Hypothesis",o))throw new Error("Failed to open login window")
|
|
647
|
-
"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 o_("Failed to fetch access token",e)}return{accessToken:t.access_token,expiresAt:Date.now()+1e3*(t.expires_in-10),refreshToken:t.refresh_token}}}class a_ extends hb{constructor(e,t,n,r,o){super(),$s(this,"_authCode",void 0),$s(this,"_client",void 0),$s(this,"_tokenInfoPromise",void 0),$s(this,"_apiRoutes",void 0),$s(this,"_localStorage",void 0),$s(this,"_settings",void 0),$s(this,"_toastMessenger",void 0),$s(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(){
|
|
648
|
-
const e=this._localStorage.getObject(this._storageKey());return e&&"string"==typeof e.accessToken&&"string"==typeof e.refreshToken&&"number"==typeof e.expiresAt?{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}:null}async _oauthClient(){if(this._client)return this._client;const e=await this._apiRoutes.links();var t,n;return this._client=new i_({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){
|
|
649
|
-
_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())}
|
|
650
|
-
;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())}}a_.$inject=["$window","apiRoutes","localStorage","settings","toastMessenger"];class s_{constructor(e,t,n){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
|
|
651
|
-
})).finally((()=>{this._saving.delete(n)})))}))}))}isSaving(){return this._saving.size>0}}function l_(e){if(null===e||"object"!=typeof e)return!1;for(let t of["frame1","frame2","type","requestId"])if("string"!=typeof e[t])return!1;return!0}function c_(e,t){return!!l_(e)&&JSON.stringify(e,Object.keys(t).sort())===JSON.stringify(t,Object.keys(t).sort())}s_.$inject=["annotationsService","toastMessenger","store"];class u_{constructor({hostFrame:e,source:t,sourceId:n}){this._hostFrame=e,this._source=t,this._sourceId=n,this._listeners=new Gs}destroy(){this._listeners.removeAll()}async discover(e){let t=!1;if(("guest"===this._source&&"host"===e||"guest"===this._source&&"sidebar"===e||"sidebar"===this._source&&"host"===e||"notebook"===this._source&&"sidebar"===e)&&(t=!0),!t)throw new Error("Invalid request of channel/port");const n=a(6)
|
|
652
|
-
},i=setInterval(o,250),a=setTimeout((()=>{clearInterval(i),r(new Error(`Unable to establish ${this._source}-${e} communication channel`))}),2e4),s=this._listeners.add(window,"message",(r=>{const{data:o,ports:l}=r;c_(o,{frame1:this._source,frame2:e,type:"offer",requestId:n})&&(clearInterval(i),clearTimeout(a),this._listeners.remove(s),t(l[0]))}));o()}))}}function d_(e,t,n=[],r=-1){e.postMessage({protocol:"frame-rpc",version:"1.0.0",arguments:n,method:t,sequence:r})}class h_{constructor({userAgent:e=navigator.userAgent,currentWindow:t=window}={}){this._port=null,this._methods=new Map,this._sequence=1,this._callbacks=new Map,this._listeners=new Gs,this._listeners.add(t,"unload",(()=>{this._port&&(d_(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({
|
|
653
|
-
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(),d_(e,"connect");for(let[e,t]of this._pendingCalls)this.call(e,...t);this._pendingCalls=[]}destroy(){this._port&&(d_(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)),d_(this._port,e,t,n)}_parseMessage({data:e}){return e&&"object"==typeof e?"frame-rpc"!==e.protocol||"1.0.0"!==e.version?null:Array.isArray(e.arguments)?e:null:null}_handle(e){const t=this._parseMessage(e),n=this._port;if(t&&n)if("method"in t){if("close"===t.method){if(this._receivedCloseEvent)return
|
|
654
|
-
protocol:"frame-rpc",response:t.sequence,version:"1.0.0"};n.postMessage(r)};e(...t.arguments,r)}else if("response"in t){const e=this._callbacks.get(t.response);this._callbacks.delete(t.response),e&&e(...t.arguments)}}}function m_(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&&bs(r.cfi)===bs(t.cfi))}function p_(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 f_({$cluster:e,$tag:t,target:n,uri:r}){return{$cluster:e,$tag:t,target:n,uri:r}}function g_(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 v_{constructor(e,t,n){$s(this,"_annotationsService",void 0),$s(this,"_guestRPC",void 0),$s(this,"_highlightsVisible",void 0)
|
|
655
|
-
$s(this,"_store",void 0),$s(this,"_pendingScrollToTag",void 0),$s(this,"_pendingHoverTag",void 0),$s(this,"_pendingAnchorStatusUpdates",void 0),$s(this,"_scheduleAnchorStatusUpdate",void 0),$s(this,"_window",void 0),this._window=e,this._annotationsService=t,this._store=n,this._portFinder=new u_({hostFrame:this._window.parent,source:"sidebar"}),this._listeners=new Gs,this._hostRPC=new h_,this._guestRPC=new Map,this._inFrame=new Set,this._highlightsVisible=!1,this._pendingScrollToTag=null,this._pendingHoverTag=null,this._pendingAnchorStatusUpdates=new Map,this._scheduleAnchorStatusUpdate=qs((()=>{const e=Object.fromEntries(this._pendingAnchorStatusUpdates.entries());this._store.updateAnchorStatus(e),this._pendingAnchorStatusUpdates.clear()}),10),this._setupSyncToGuests(),this._setupHostEvents(),this._setupFeatureFlagSync()}_setupSyncToGuests(){let e=0;const t=(t,n,r)=>{let o=0;const i=new Set,a=[]
|
|
656
|
-
;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=g_(n,r);if(!o||o.segment&&!m_(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(f_))}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))};p_(this._store.subscribe,(()=>[this._store.allAnnotations(),this._store.frames()]),(([e,n],[r])=>t(e,n,r)),ca),p_(this._store.subscribe,(()=>this._store.getContentInfo()),(e=>{this._guestRPC.forEach((t=>{t.call("showContentInfo",e)}))}))}_updateAnchorStatus(e,t){
|
|
657
|
-
;this._scheduleAnchorStatusUpdate()}_connectGuest(e,t){const n=new h_;this._guestRPC.set(t,n),n.on("documentInfoChanged",(e=>{this._store.connectFrame({id:t,metadata:e.metadata,uri:e.uri,segment:e.segmentInfo,persistent:e.persistent})})),n.on("close",(()=>{const e=this._store.frames().find((e=>e.id===t));e&&!e.persistent&&this._store.destroyFrame(e),this._inFrame.clear(),n.destroy(),this._guestRPC.delete(t)})),n.on("createAnnotation",(e=>{if(!this._store.isLoggedIn())return this._hostRPC.call("openSidebar"),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"),
|
|
658
|
-
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.profile().features);const r=this._store.getContentInfo();r&&n.call("showContentInfo",r)}_setupHostEvents(){this._hostRPC.on("sidebarOpened",(()=>{this._store.setSidebarOpened(!0)
|
|
659
|
-
this._guestRPC.forEach((t=>t.call("setHighlightsVisible",e)))}))}_setupFeatureFlagSync(){const e=()=>this._store.profile().features,t=e=>{this._hostRPC.call("featureFlagsUpdated",e);for(const t of this._guestRPC.values())t.call("featureFlagsUpdated",e)};t(e()),p_(this._store.subscribe,e,t)}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;l_(r)&&(c_(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",[])));const n=g_(this._store.frames(),e)
|
|
660
|
-
;if(!t)return;const n=this._guestRPC.get(null==t?void 0:t.id);return n?t.segment&&!m_(e,t.segment)?(this._pendingScrollToTag=e.$tag,void n.call("navigateToSegment",f_(e))):void n.call("scrollToAnnotation",e.$tag):void 0}destroy(){this._portFinder.destroy(),this._listeners.removeAll()}}v_.$inject=["$window","annotationsService","store"];const b_={id:"__default__",name:"__DEFAULT__",
|
|
632
|
+
;const a=Xa(),s=a.defaultAuthority(),l=a.profile(),c=au(l.userid,s),u=t(r),d=iu(l.userid),h=null!==(o=null===(i=l.user_info)||void 0===i?void 0:i.display_name)&&void 0!==o?o:d,[m,p]=Br(!1),f=e=>u&&!!u[e],g=!c||f("onProfileRequestProvided"),v=!c||f("onLogoutRequestProvided"),b=a.isFeatureEnabled("client_user_profile"),_=()=>{e.notifyHost("openNotebook",a.focusedGroupId())},y=()=>e.notifyHost("openProfile"),w=g&&!c?a.getLink("user",{user:d}):void 0,x=eo("span",{className:"p-1",children:eo(vc,{})});return eo("div",{"data-testid":"user-menu",onKeyDown:e=>{"n"===e.key?(_(),p(!1)):b&&"p"===e.key&&(y(),p(!1))},children:eo(tv,{label:x,title:h,align:"right",open:m,onOpenChanged:p,children:[eo(Cb,{children:[eo(ov,{label:h,isDisabled:!g,href:w,onClick:g?()=>c&&e.notifyHost("profileRequested"):void 0}),!c&&eo(ov,{label:"Account settings",href:a.getLink("account.settings")}),b&&eo(ov,{label:"Your profile",onClick:()=>y()}),eo(ov,{label:"Open notebook",onClick:()=>_()})]}),v&&eo(Cb,{children:eo(ov,{label:"Log out",
|
|
633
|
+
onClick:n})})]})})}),["frameSync","settings"]);var jb=No((function({isSidebar:e,onLogin:n,onLogout:r,onSignUp:o,frameSync:i,settings:a,streamer:s}){const l=!tb(a),c=xo(["accentColor"],a),u=Xa(),d=u.filterQuery(),h=u.pendingUpdateCount(),m=u.isLoggedIn(),p=u.hasFetchedProfile(),f=u.isSidebarPanelOpen("help"),g=u.isSidebarPanelOpen("shareGroupAnnotations");return eo("div",{className:Tr("absolute h-10 left-0 top-0 right-0 z-4","text-grey-7 border-b theme-clean:border-b-0 bg-white"),"data-testid":"top-bar",children:eo("div",{className:Tr("container flex items-center h-full","text-[16px]"),"data-testid":"top-bar-content",children:[eo(e?Lb:Bb,{}),eo("div",{className:"grow flex items-center justify-end",children:[e&&eo(er,{children:[h>0&&eo(Gc,{icon:_c,onClick:()=>s.applyPendingUpdates(),size:"xs",variant:"primary",title:`Show ${h} new/updated ${1===h?"annotation":"annotations"}`}),eo(Db,{query:d||null,onSearch:u.setFilterQuery}),eo(Pb,{}),l&&eo(Gc,{icon:Ac,expanded:g,onClick:()=>{
|
|
634
|
+
u.toggleSidebarPanel("shareGroupAnnotations")},size:"xs",title:"Share annotations on this page"})]}),eo(Gc,{icon:ql,expanded:f,onClick:()=>{const e=t(a);e&&e.onHelpRequestProvided?i.notifyHost("helpRequested"):u.toggleSidebarPanel("help")},size:"xs",title:"Help"}),m?eo(Fb,{onLogout:r}):eo("div",{className:"flex items-center text-md font-medium space-x-1","data-testid":"login-links",children:[!m&&!p&&eo("span",{children:"⋯"}),!m&&p&&eo(er,{children:[eo(ru,{classes:"inline",onClick:o,style:c,children:"Sign up"}),eo("div",{children:"/"}),eo(ru,{classes:"inline",onClick:n,style:c,children:"Log in"})]})]})]})]})})}),["frameSync","settings","streamer"]);var Hb=No((function({auth:e,frameSync:n,settings:r,session:o,toastMessenger:i}){const a=Xa(),s=a.profile(),l=a.route(),c=qr((()=>xo(["appBackgroundColor"],r)),[r]),u="clean"===r.theme,d="sidebar"===l;jr((()=>{(function(e,n,r){const o="object"==typeof n.preferences&&!!n.preferences.show_sidebar_tutorial,i=t(r)||{onHelpRequestProvided:!1}
|
|
635
|
+
;return e&&!i.onHelpRequestProvided&&o})(d,s,r)&&a.openSidebarPanel("help")}),[d,s,r,a]);const h=async()=>{if(t(r))n.notifyHost("loginRequested");else try{await e.login(),a.closeSidebarPanel("loginPrompt"),a.clearGroups(),o.reload()}catch(e){i.error(e.message)}},m=()=>{t(r)?n.notifyHost("signupRequested"):window.open(a.getLink("signup"))};return eo("div",{className:Tr("h-full min-h-full overflow-scroll","lg:pb-16 bg-grey-2","js-thread-list-scroll-root",{"theme-clean":u,"pt-[49px]":"notebook"!==l,"p-4 lg:p-12":"notebook"===l}),"data-testid":"hypothesis-app",style:c,children:["notebook"!==l&&eo(jb,{onLogin:h,onSignUp:m,onLogout:async()=>{await(async()=>{const e=a.countDrafts();if(0===e)return!0;let t="";return 1===e?t="You have an unsaved annotation.\nDo you really want to discard this draft?":e>1&&(t="You have "+e+" unsaved annotations.\nDo you really want to discard these drafts?"),yo({title:"Discard drafts?",message:t,confirmAction:"Discard"})})()&&(a.clearGroups(),
|
|
636
|
+
a.removeAnnotations(a.unsavedAnnotations()),a.discardAllDrafts(),t(r)?n.notifyHost("logoutRequested"):o.logout())},isSidebar:d}),eo("div",{className:"container",children:[eo(Sb,{}),eo(lb,{}),eo(kb,{}),l&&eo("main",{children:["annotation"===l&&eo(Pv,{onLogin:h}),"notebook"===l&&eo(xb,{}),"stream"===l&&eo(Qv,{}),"sidebar"===l&&eo(Jv,{onLogin:h,onSignUp:m})]})]})]})}),["auth","frameSync","session","settings","toastMessenger"]);function Ub({error:e}){return eo("div",{className:Tr("m-2 mt-12"),children:eo(eu,{title:"Unable to start Hypothesis",children:e.message})})}class qb{constructor(e,t,n){this._activity=e,this._api=t,this._store=n}_applyDraftChanges(e){const t={},n=this._store.getDraft(e);return n&&(t.tags=n.tags,t.text=n.text,t.permissions=n.isPrivate?cu(e.user):uu(e.user,e.group)),{...e,...t}}_initialize(e,t=new Date){const n=this._store.getDefault("annotationPrivacy"),r=this._store.focusedGroupId(),o=this._store.profile();if(!r)throw new Error("Cannot create annotation without a group");const i=o.userid
|
|
637
|
+
;if(!i)throw new Error("Cannot create annotation when logged out");const s=o.user_info,l="s:"+a(8),c=Object.assign({created:t.toISOString(),group:r,permissions:du(i,r,n),tags:[],text:"",updated:t.toISOString(),user:i,user_info:s,$tag:l,hidden:!1,links:{},document:{title:""}},e);return pi(c)&&(c.permissions=cu(i)),c}create(e,t=new Date){const n=this._initialize(e,t);this._store.addAnnotations([n]),this._store.deleteNewAndEmptyDrafts(),pi(n)||this._store.createDraft(n,{tags:n.tags,text:n.text,isPrivate:!ui(n)}),gi(n)?this._store.selectTab("note"):vi(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:[],uri:e.uri};this.create(t)}async delete(e){await this._api.annotation.delete({id:e.id}),this._activity.reportActivity("delete",e),this._store.removeAnnotations([e])}async flag(e){
|
|
638
|
+
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:ui(e)?uu(t,e.group):cu(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;li(e)?(t=this._api.annotation.update({id:e.id},r),n="update"):(t=this._api.annotation.create({},r),n="create"),this._store.annotationSaveStarted(e);try{o=await t,this._activity.reportActivity(n,o)}finally{this._store.annotationSaveFinished(e)}for(let[t,n]of Object.entries(e))if(t.startsWith("$")){o[t]=n}return this._store.removeDraft(e),this._store.addAnnotations([o]),o}}qb.$inject=["annotationActivity","api","store"];class $b{constructor(e){this._rpc=e.rpc,this._reportConfig=e.reportActivity}reportActivity(e,t){if(!this._rpc||!this._reportConfig)return;let n;switch(e){case"create":n=new Date(t.created).toISOString();break;case"update":
|
|
639
|
+
n=new Date(t.updated).toISOString();break;default:n=(new Date).toISOString()}const r={date:n,annotation:{id:t.id,isShared:hu(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])}}$b.$inject=["settings"];class Gb extends Error{constructor(e,t,n=""){let r="Network request failed";t&&(r+=` (${t.status})`),n&&(r+=`: ${n}`),super(r),this.url=e,this.response=t,this.reason=n}}async function Vb(e,t){let n,r;try{n=await fetch(e,t)}catch(t){throw new Gb(e,null,t.message)}if(204===n.status)return null;try{r=await n.json()}catch(t){throw new Gb(e,n,"Failed to parse response")}var o;if(!n.ok)throw new Gb(e,n,null===(o=r)||void 0===o?void 0:o.reason);return r}function Yb(e){const t={};for(let[n,r]of Object.entries(e))n.startsWith("$")||(t[n]=r);return t}class Wb{constructor(e,t,n){const r=e.routes();this._clientId=null
|
|
640
|
+
;const o=()=>this._clientId,i=e=>function(e,t,{getAccessToken:n,getClientId:r,onRequestStarted:o,onRequestFinished:i}){return async(a,s)=>{o();try{const[o,l]=await Promise.all([e,n()]),c=function(e,t){let n=e;const r=t.split(".");for(let[e,t]of r.entries()){const o=n[t];if(!o||"url"in o){if(o&&e===r.length-1)return o;break}n=o}return null}(o,t);if(!c)throw new Error(`Missing API route: ${t}`);const u={"Content-Type":"application/json","Hypothesis-Client-Version":"1.1209.0"};l&&(u.Authorization="Bearer "+l);const d=r();d&&(u["X-Client-Id"]=d);const{url:h,unusedParams:m}=xa(c.url,a),p=new URL(h);for(let[e,t]of Object.entries(m)){Array.isArray(t)||(t=[t]);for(let n of t)null!=n&&p.searchParams.append(e,n.toString())}return await Vb(p.toString(),{body:s?JSON.stringify(Yb(s)):null,headers:u,method:c.method})}finally{i()}}}(r,e,{getAccessToken:()=>t.getAccessToken(),getClientId:o,onRequestStarted:n.apiRequestStarted,onRequestFinished:n.apiRequestFinished});this.search=i("search"),this.annotation={
|
|
641
|
+
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:{read:i("profile.groups.read")},read:i("profile.read"),update:i("profile.update")}}setClientId(e){this._clientId=e}}Wb.$inject=["apiRoutes","auth","store"];var Kb={},Xb={get exports(){return Kb},set exports(e){Kb=e}},Zb={};function Jb(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 Qb=Jb;Jb.prototype.reset=function(){
|
|
642
|
+
this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},Jb.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},Jb.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},Jb.prototype.attempt=function(e,t){this._fn=e,
|
|
643
|
+
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)},Jb.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},Jb.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},Jb.prototype.start=Jb.prototype.try,Jb.prototype.errors=function(){return this._errors},Jb.prototype.attempts=function(){return this._attempts},Jb.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=Qb;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})},
|
|
644
|
+
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));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}}}(Zb),Xb.exports=Zb;var e_=h(Kb)
|
|
645
|
+
;function t_(e,t){return new Promise(((n,r)=>{const o=e_.operation(t);o.attempt((async()=>{try{const t=await e();o.retry(),n(t)}catch(e){o.retry(e)||r(e)}}))}))}function n_(e){return t_((()=>Vb(e)))}class r_{constructor(e){this._apiURL=e.apiUrl,this._routeCache=null,this._linkCache=null}routes(){return this._routeCache||(this._routeCache=n_(this._apiURL).then((e=>e.links))),this._routeCache}links(){return this._linkCache||(this._linkCache=this.routes().then((async e=>{const t=e.links;return await n_(t.url)}))),this._linkCache}}r_.$inject=["settings"];class o_ extends Error{constructor(e,t){super(e),this.cause=t}}class i_{constructor(e){this.clientId=e.clientId,this.tokenEndpoint=e.tokenEndpoint,this.authorizationEndpoint=e.authorizationEndpoint,this.revokeEndpoint=e.revokeEndpoint}exchangeAuthCode(e){return this._getAccessToken({client_id:this.clientId,grant_type:"authorization_code",code:e})}exchangeGrantToken(e){return this._getAccessToken({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
646
|
+
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 o_("Failed to revoke access token",e)}}authorize(e){const t=a(16),n=new Promise(((n,r)=>{e.addEventListener("message",(function o(i){"object"==typeof i.data&&i.data.state===t&&("authorization_response"===i.data.type&&n(i.data),"authorization_canceled"===i.data.type&&r(new Error("Authorization window was closed")),e.removeEventListener("message",o))}))})),r=new URL(this.authorizationEndpoint);r.searchParams.set("client_id",this.clientId),r.searchParams.set("origin",e.location.origin),r.searchParams.set("response_mode","web_message"),r.searchParams.set("response_type","code"),r.searchParams.set("state",t);const o=`left=${e.screen.width/2-237.5},top=${e.screen.height/2-215},width=475,height=430`;if(!e.open(r.toString(),"Log in to Hypothesis",o))throw new Error("Failed to open login window")
|
|
647
|
+
;return n.then((e=>e.code))}async _formPost(e,t){const n=new URLSearchParams;for(let[e,r]of Object.entries(t))n.set(e,r);n.sort();return Vb(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 o_("Failed to fetch access token",e)}return{accessToken:t.access_token,expiresAt:Date.now()+1e3*(t.expires_in-10),refreshToken:t.refresh_token}}}class a_ extends hb{constructor(e,t,n,r,o){super(),$s(this,"_authCode",void 0),$s(this,"_client",void 0),$s(this,"_tokenInfoPromise",void 0),$s(this,"_apiRoutes",void 0),$s(this,"_localStorage",void 0),$s(this,"_settings",void 0),$s(this,"_toastMessenger",void 0),$s(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(){
|
|
648
|
+
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&&"string"==typeof e.accessToken&&"string"==typeof e.refreshToken&&"number"==typeof e.expiresAt?{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}:null}async _oauthClient(){if(this._client)return this._client;const e=await this._apiRoutes.links();var t,n;return this._client=new i_({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){
|
|
649
|
+
throw this._toastMessenger.error("Hypothesis login lost: You must reload the page to annotate.",{autoDismiss:!1}),e}}_getGrantToken(){var e;return null===(e=t(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())}
|
|
650
|
+
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())}}a_.$inject=["$window","apiRoutes","localStorage","settings","toastMessenger"];class s_{constructor(e,t,n){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
|
|
651
|
+
;e(n)&&(this._saving.add(n),t_((()=>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 l_(e){if(null===e||"object"!=typeof e)return!1;for(let t of["frame1","frame2","type","requestId"])if("string"!=typeof e[t])return!1;return!0}function c_(e,t){return!!l_(e)&&JSON.stringify(e,Object.keys(t).sort())===JSON.stringify(t,Object.keys(t).sort())}s_.$inject=["annotationsService","toastMessenger","store"];class u_{constructor({hostFrame:e,source:t,sourceId:n}){this._hostFrame=e,this._source=t,this._sourceId=n,this._listeners=new Gs}destroy(){this._listeners.removeAll()}async discover(e){let t=!1;if(("guest"===this._source&&"host"===e||"guest"===this._source&&"sidebar"===e||"sidebar"===this._source&&"host"===e||"notebook"===this._source&&"sidebar"===e)&&(t=!0),!t)throw new Error("Invalid request of channel/port");const n=a(6)
|
|
652
|
+
;return new Promise(((t,r)=>{const o=()=>{this._hostFrame.postMessage({frame1:this._source,frame2:e,type:"request",requestId:n,sourceId:this._sourceId},"*")},i=setInterval(o,250),a=setTimeout((()=>{clearInterval(i),r(new Error(`Unable to establish ${this._source}-${e} communication channel`))}),2e4),s=this._listeners.add(window,"message",(r=>{const{data:o,ports:l}=r;c_(o,{frame1:this._source,frame2:e,type:"offer",requestId:n})&&(clearInterval(i),clearTimeout(a),this._listeners.remove(s),t(l[0]))}));o()}))}}function d_(e,t,n=[],r=-1){e.postMessage({protocol:"frame-rpc",version:"1.0.0",arguments:n,method:t,sequence:r})}class h_{constructor({userAgent:e=navigator.userAgent,currentWindow:t=window}={}){this._port=null,this._methods=new Map,this._sequence=1,this._callbacks=new Map,this._listeners=new Gs,this._listeners.add(t,"unload",(()=>{this._port&&(d_(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({
|
|
653
|
+
type:"hypothesisPortClosed"},"*",[this._port]))})),this._pendingCalls=[],this._receivedCloseEvent=!1}on(e,t){if(this._port)throw new Error("Cannot add a method handler after a port is connected");this._methods.set(e,t)}connect(e){this._port=e,this._listeners.add(e,"message",(e=>this._handle(e))),e.start(),d_(e,"connect");for(let[e,t]of this._pendingCalls)this.call(e,...t);this._pendingCalls=[]}destroy(){this._port&&(d_(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)),d_(this._port,e,t,n)}_parseMessage({data:e}){return e&&"object"==typeof e?"frame-rpc"!==e.protocol||"1.0.0"!==e.version?null:Array.isArray(e.arguments)?e:null:null}_handle(e){const t=this._parseMessage(e),n=this._port;if(t&&n)if("method"in t){if("close"===t.method){if(this._receivedCloseEvent)return
|
|
654
|
+
;this._receivedCloseEvent=!0}const e=this._methods.get(t.method);if(!e)return;const r=(...e)=>{const r={arguments:e,protocol:"frame-rpc",response:t.sequence,version:"1.0.0"};n.postMessage(r)};e(...t.arguments,r)}else if("response"in t){const e=this._callbacks.get(t.response);this._callbacks.delete(t.response),e&&e(...t.arguments)}}}function m_(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&&bs(r.cfi)===bs(t.cfi))}function p_(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 f_({$cluster:e,$tag:t,target:n,uri:r}){return{$cluster:e,$tag:t,target:n,uri:r}}function g_(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 v_{constructor(e,t,n){$s(this,"_annotationsService",void 0),$s(this,"_guestRPC",void 0),$s(this,"_highlightsVisible",void 0),
|
|
655
|
+
$s(this,"_hostRPC",void 0),$s(this,"_inFrame",void 0),$s(this,"_listeners",void 0),$s(this,"_portFinder",void 0),$s(this,"_store",void 0),$s(this,"_pendingScrollToTag",void 0),$s(this,"_pendingHoverTag",void 0),$s(this,"_pendingAnchorStatusUpdates",void 0),$s(this,"_scheduleAnchorStatusUpdate",void 0),$s(this,"_window",void 0),this._window=e,this._annotationsService=t,this._store=n,this._portFinder=new u_({hostFrame:this._window.parent,source:"sidebar"}),this._listeners=new Gs,this._hostRPC=new h_,this._guestRPC=new Map,this._inFrame=new Set,this._highlightsVisible=!1,this._pendingScrollToTag=null,this._pendingHoverTag=null,this._pendingAnchorStatusUpdates=new Map,this._scheduleAnchorStatusUpdate=qs((()=>{const e=Object.fromEntries(this._pendingAnchorStatusUpdates.entries());this._store.updateAnchorStatus(e),this._pendingAnchorStatusUpdates.clear()}),10),this._setupSyncToGuests(),this._setupHostEvents(),this._setupFeatureFlagSync()}_setupSyncToGuests(){let e=0;const t=(t,n,r)=>{let o=0;const i=new Set,a=[]
|
|
656
|
+
;t.forEach((e=>{si(e)||(ui(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=g_(n,r);if(!o||o.segment&&!m_(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(f_))}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))};p_(this._store.subscribe,(()=>[this._store.allAnnotations(),this._store.frames()]),(([e,n],[r])=>t(e,n,r)),ca),p_(this._store.subscribe,(()=>this._store.getContentInfo()),(e=>{this._guestRPC.forEach((t=>{t.call("showContentInfo",e)}))}))}_updateAnchorStatus(e,t){
|
|
657
|
+
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 h_;this._guestRPC.set(t,n),n.on("documentInfoChanged",(e=>{this._store.connectFrame({id:t,metadata:e.metadata,uri:e.uri,segment:e.segmentInfo,persistent:e.persistent})})),n.on("close",(()=>{const e=this._store.frames().find((e=>e.id===t));e&&!e.persistent&&this._store.destroyFrame(e),this._inFrame.clear(),n.destroy(),this._guestRPC.delete(t)})),n.on("createAnnotation",(e=>{if(!this._store.isLoggedIn())return this._hostRPC.call("openSidebar"),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"),
|
|
658
|
+
e===this._pendingHoverTag&&(this._pendingHoverTag=null,n.call("hoverAnnotations",[e])),this._pendingScrollToTag&&e===this._pendingScrollToTag&&(this._pendingScrollToTag=null,n.call("scrollToAnnotation",e))})),n.on("showAnnotations",((e,t=!1)=>{const n=this._store.findIDsForTags(e);this._store.selectAnnotations(n),this._store.selectTab("annotation"),n.length>0&&t&&(this._store.setAnnotationFocusRequest(n[0]),window.focus())})),n.on("hoverAnnotations",(e=>{this._store.hoverAnnotations(e||[])})),n.on("toggleAnnotationSelection",(e=>{this._store.toggleSelectedAnnotations(this._store.findIDsForTags(e))})),n.on("openSidebar",(()=>{this._hostRPC.call("openSidebar")})),n.on("closeSidebar",(()=>{this._hostRPC.call("closeSidebar")})),n.connect(e),n.call("setHighlightsVisible",this._highlightsVisible),n.call("featureFlagsUpdated",this._store.profile().features);const r=this._store.getContentInfo();r&&n.call("showContentInfo",r)}_setupHostEvents(){this._hostRPC.on("sidebarOpened",(()=>{this._store.setSidebarOpened(!0)
|
|
659
|
+
})),this._hostRPC.on("setHighlightsVisible",(e=>{this._highlightsVisible=e,this._guestRPC.forEach((t=>t.call("setHighlightsVisible",e)))}))}_setupFeatureFlagSync(){const e=()=>this._store.profile().features,t=e=>{this._hostRPC.call("featureFlagsUpdated",e);for(const t of this._guestRPC.values())t.call("featureFlagsUpdated",e)};t(e()),p_(this._store.subscribe,e,t)}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;l_(r)&&(c_(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",[])));const n=g_(this._store.frames(),e)
|
|
660
|
+
;!n||n.segment&&!m_(e,n.segment)?this._pendingHoverTag=e.$tag:this._guestRPC.forEach((e=>e.call("hoverAnnotations",t)))}scrollToAnnotation(e){const t=g_(this._store.frames(),e);if(!t)return;const n=this._guestRPC.get(null==t?void 0:t.id);return n?t.segment&&!m_(e,t.segment)?(this._pendingScrollToTag=e.$tag,void n.call("navigateToSegment",f_(e))):void n.call("scrollToAnnotation",e.$tag):void 0}destroy(){this._portFinder.destroy(),this._listeners.removeAll()}}v_.$inject=["$window","annotationsService","store"];const b_={id:"__default__",name:"__DEFAULT__",
|
|
661
661
|
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>')
|
|
662
662
|
};const __=["organization","scopes"];class y_{constructor(e,n,r,o,i,a){this._store=e,this._api=n,this._auth=r,this._settings=i,this._toastMessenger=a,this._serviceConfig=t(i),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,p_(this._store.subscribe,(()=>this._mainURI()),(()=>this.load())),p_(this._store.subscribe,(()=>[this._store.hasFetchedProfile(),this._store.profile().userid]),((e,[t])=>{t&&this.load()}),ca))}_addGroupsToStore(e,t){!function(e){e.forEach((e=>{
|
|
663
663
|
e.organization&&"object"==typeof e.organization||(e.organization=b_)}))}(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:__})}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;i&&(a=this._fetchGroup(i).then((e=>(this._store.clearDirectLinkedGroupFetchFailed(),e))).catch((()=>(this._store.setDirectLinkedGroupFetchFailed(),null))));const s={expand:__
|
|
@@ -675,8 +675,8 @@ const e=Object.values(this._store.pendingUpdates());e.length&&this._store.addAnn
|
|
|
675
675
|
}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,p_(this._store.subscribe,(()=>this._store.profile().userid),(()=>this._reconnect()))),this._socket||await this._reconnect()}}z_.$inject=["store","apiRoutes","auth","groups","session"];class L_{constructor(e){this._storage=e}filter(e,t=null){const n=this._storage.getObject("hypothesis.user.tags.list")||[];let r=0;return n.filter((n=>{if(null!==t&&r>=t)return!1;const o=n.split(/\W+/),i=new RegExp(`^${m(e)}`,"i");return!(!o.some((e=>e.match(i)))&&!n.match(i))&&(++r,!0)}))}store(e){
|
|
676
676
|
const t=this._storage.getObject("hypothesis.user.tags.map")||{};e.forEach((e=>{t[e]?(t[e].count+=1,t[e].updated=Date.now()):t[e]={text:e,count:1,updated:Date.now()}})),this._storage.setObject("hypothesis.user.tags.map",t);const n=Object.keys(t).sort(((e,n)=>t[e].count!==t[n].count?t[n].count-t[e].count:e.localeCompare(n)));this._storage.setObject("hypothesis.user.tags.list",n)}}L_.$inject=["localStorage"];class R_{constructor(e){this._store=e}forceVisible(e){e.children.forEach((e=>{this.forceVisible(e)})),e.visible||this._store.setForcedVisible(e.id,!0)}}R_.$inject=["store"];class I_{constructor(e){this._store=e}dismiss(e){const t=this._store.getToastMessage(e);t&&!t.isDismissed&&(this._store.updateToastMessage({...t,isDismissed:!0}),setTimeout((()=>{this._store.removeToastMessage(e)}),500))}_addMessage(e,t,{autoDismiss:n=!0,moreInfoURL:r="",visuallyHidden:o=!1}={}){if(this._store.hasToastMessage(e,t))return;const i=a(10),s={type:e,id:i,message:t,moreInfoURL:r,visuallyHidden:o};this._store.addToastMessage({
|
|
677
677
|
isDismissed:!1,...s}),n&&setTimeout((()=>{this.dismiss(i)}),5e3)}error(e,t){this._addMessage("error",e,t)}success(e,t){this._addMessage("success",e,t)}notice(e,t){this._addMessage("notice",e,t)}}I_.$inject=["store"];class O_{constructor(){this._providers=new Map,this._instances=new Map,this._constructing=new Set}get(e){if(this._instances.has(e))return this._instances.get(e);const t=this._providers.get(e);if(!t)throw new Error(`"${e}" is not registered`);if("value"in t)return this._instances.set(e,t.value),t.value;if(this._constructing.has(e))throw new Error(`Encountered a circular dependency when constructing "${e}"`);this._constructing.add(e);try{const n=[],r="class"in t&&t.class.$inject||"factory"in t&&t.factory.$inject||[];for(const t of r)try{n.push(this.get(t))}catch(n){const r=new Error(`Failed to construct dependency "${t}" of "${e}": ${n.message}`);throw r.cause=n,r}let o;if(t.class)o=new t.class(...n);else{o=(0,t.factory)(...n)}return this._instances.set(e,o),o}finally{this._constructing.delete(e)}}
|
|
678
|
-
register(e,t){if("function"==typeof t)t={class:t};else if(!function(e){return"object"==typeof e&&null!==e&&("value"in e||"function"==typeof e.class||"function"==typeof e.factory)}(t))throw new Error(`Invalid provider for "${e}"`);return this._providers.set(e,t),this}run(e){const t="Injector.run";this.register(t,{factory:e});try{return this.get(t)}finally{this._instances.delete(t),this._providers.delete(t)}}}const D_=function(e){for(var t={},n=e.querySelectorAll("script.js-hypothesis-config"),r=0;r<n.length;r++){var o=void 0;try{o=JSON.parse(n[r].textContent||"")}catch(e){console.warn("Could not parse settings from js-hypothesis-config tags",e),o={}}Object.assign(t,o)}return t}(document),P_=function(t){const{version:n,origin:r}=e(t.location.href);return"1.
|
|
679
|
-
!1):t.origin===r||(console.warn(`The Hypothesis sidebar is running in a different origin (${t.origin}) than expected (${r}). It may not work.`),!1)}(window);function B_(e,t){e.setClientId(t.clientId)}function F_(e,t,n){e.load(),t.load(),n.sync()}function j_(e,t,n){e.init(),t.init(),n.init()}function H_(e,t){"sidebar"===t.route()&&e.connect()}D_.sentry&&P_&&function(t){const n=function(){let e=import.meta.url;return e?new URL(e).origin:null}(),r=n?[n]:void 0;Pn({dsn:t.dsn,environment:t.environment,allowUrls:r,ignoreErrors:["Network request failed","Object Not Found Matching Id"],release:"1.
|
|
678
|
+
register(e,t){if("function"==typeof t)t={class:t};else if(!function(e){return"object"==typeof e&&null!==e&&("value"in e||"function"==typeof e.class||"function"==typeof e.factory)}(t))throw new Error(`Invalid provider for "${e}"`);return this._providers.set(e,t),this}run(e){const t="Injector.run";this.register(t,{factory:e});try{return this.get(t)}finally{this._instances.delete(t),this._providers.delete(t)}}}const D_=function(e){for(var t={},n=e.querySelectorAll("script.js-hypothesis-config"),r=0;r<n.length;r++){var o=void 0;try{o=JSON.parse(n[r].textContent||"")}catch(e){console.warn("Could not parse settings from js-hypothesis-config tags",e),o={}}Object.assign(t,o)}return t}(document),P_=function(t){const{version:n,origin:r}=e(t.location.href);return"1.1209.0"!==n?(console.warn(`The Hypothesis sidebar is using a different version (1.1209.0) than the host page (${n}). It may not work.`),!1):"null"===t.origin?(console.warn("Hypothesis has been loaded in a sandboxed frame. This is not supported."),
|
|
679
|
+
!1):t.origin===r||(console.warn(`The Hypothesis sidebar is running in a different origin (${t.origin}) than expected (${r}). It may not work.`),!1)}(window);function B_(e,t){e.setClientId(t.clientId)}function F_(e,t,n){e.load(),t.load(),n.sync()}function j_(e,t,n){e.init(),t.init(),n.init()}function H_(e,t){"sidebar"===t.route()&&e.connect()}D_.sentry&&P_&&function(t){const n=function(){let e=import.meta.url;return e?new URL(e).origin:null}(),r=n?[n]:void 0;Pn({dsn:t.dsn,environment:t.environment,allowUrls:r,ignoreErrors:["Network request failed","Object Not Found Matching Id"],release:"1.1209.0",beforeSend:(e,t)=>{if(jn>=5)return u("Client-side Sentry quota reached. No further Sentry events will be sent"),null;++jn;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{bt("host_config",e(window.location.href))}catch(e){}
|
|
680
680
|
bt("loaded_scripts",Array.from(document.querySelectorAll("script")).filter((e=>!e.type||e.type.match(/javascript|module/))).map((e=>e.src||"<inline>"))),Fn(((e,t)=>{vt(e,{tags:{context:t}})}))}(D_.sentry),function(e){e.addEventListener("click",(e=>{const t=e.target;if("A"===t.tagName){const e=t;"_blank"===e.target&&(e.rel="noopener")}}))}(document.body),B_.$inject=["api","streamer"],F_.$inject=["groups","session","router"],j_.$inject=["autosaveService","persistedDefaults","serviceURL"],H_.$inject=["frameSync","store"];const U_=document.querySelector("hypothesis-app");!function(e=window){e.addEventListener("message",v)}(),async function(i,a=window){const c=function(t){const i=e(t.location.href),a=["annotations","group","query","appType","openSidebar","showHighlights","services","branding","enableExperimentalNewNoteButton","focus","requestConfigFromFrame","theme","usernameUrl"],s={openSidebar:n,requestConfigFromFrame:e=>{if("string"==typeof e)return e;const t=function(e){return"object"==typeof e&&null!==e?e:{}
|
|
681
681
|
}(e);return{origin:o(t.origin),ancestorLevel:r(t.ancestorLevel)}}},l={};for(let[e,t]of Object.entries(i))a.includes(e)&&null!==t&&(s[e]?l[e]=s[e](t):l[e]=t);return l}(window),u=function(e,t){const n=e.requestConfigFromFrame;if(!n)return null;if("number"!=typeof n.ancestorLevel||"string"!=typeof n.origin)throw new Error("Improper `requestConfigFromFrame` object. Both `ancestorLevel` and `origin` need to be specified");return{targetFrame:l(n.ancestorLevel,t),origin:n.origin}}(c,a);let d;if(u){const e=await async function(e,t){return{...await s(t.targetFrame,t.origin,"requestConfig",[],3e3),...e.group?{group:e.group}:{}}}(c,u);d=function(e,t){const n=e.services;return Array.isArray(n)?(n.forEach(((e,n)=>{"$rpc:requestGroups"===e.groups&&(e.groups=s(t.targetFrame,t.origin,"requestGroups",[n],0).catch((()=>{throw new Error("Unable to fetch groups")})))})),e):e}(e,u)}else d=c;const h={...i,...d};return u&&(h.rpc=u),h.apiUrl=function(e){const n=t(e);if(n){if(n.apiUrl)return n.apiUrl
|
|
682
682
|
;throw new Error("Service should contain an apiUrl value.")}return e.apiUrl}(h),h}(D_).then((e=>{!function(e,t){const n=new O_;n.register("annotationsService",qb).register("annotationActivity",$b).register("api",Wb).register("apiRoutes",r_).register("auth",a_).register("autosaveService",s_).register("frameSync",v_).register("groups",y_).register("loadAnnotationsService",w_).register("localStorage",k_).register("persistedDefaults",S_).register("router",E_).register("serviceURL",A_).register("session",T_).register("streamer",z_).register("streamFilter",C_).register("tags",L_).register("threadsService",R_).register("toastMessenger",I_).register("store",{factory:Ka}),n.register("$window",{value:window}).register("settings",{value:e}),n.run(j_),n.run(B_),n.run(F_),n.run(g),n.run(H_),yr(eo(ko.Provider,{value:n,children:eo(Hb,{})}),t)}(e,U_)})).catch((e=>function(e,t){console.error("Failed to start Hypothesis client: ",e),yr(eo(Ub,{error:e}),t)}(e,U_)));
|